text:
The purpose of this chapter is to describe the tools used by \gruppo{} to develop the application.
If you are not interested in contributing to this project but you just want to run it, you can use any editor.
\subsection{IntelliJ IDEA}
The default IDE for development is IntelliJ IDEA Community created by Jet Brains, you can use it for Java and JSX development. The community edition is free and multi-platform, it runs on Windows, MacOs and Linux.

\subsection{Visual Studio Code}
An alternative IDE is Visual Studio Code developed by Microsoft, it's free and open-source and you can use it to write Java and JSX code. There are some plugins created by Pivotal and RedHat which allow you to have an environment similar to IntelliJ IDEA.

\subsection{Maven}
To manage the project you need Maven. It downloads all the dependencies including Spring Boot, compiles the source code and finally runs the application. Maven is written in Java, so you just need the {Oracle JDK}\ or the OpenJDK at least version 8.
You can download it at the link \href{https://maven.apache.org/}{Maven page}

\subsection{React}
To better debug React components it is recommended to use the following plugins:
\begin{itemize}
\item \textbf{Mozilla Firefox}(current version 66): \\
\url{https://addons.mozilla.org/it/firefox/addon/react-devtools/};
\item \textbf{Google Chrome}(current version 73): \\
\href{https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi}{https://chrome.google.com/webstore/detail/react-developer-tools/}
\end{itemize}
Remember to disable cache in the browser during the development.

\subsection{Redux}
To better debug in Redux it is recommended to use the plugin available at\\ \url{https://extension.remotedev.io/} which can be used as extension in Google Chrome 73 and Mozilla Firefox 66.

max_stars_repo_name: SWEightgroup/Colletta

max_issues_repo_name: SWEightgroup/Colletta

max_forks_repo_name: SWEightgroup/Colletta


text:
% !TEX root = ./physics_of_fluids.tex
% !TEX TS-program = xelatex
% !TEX encoding = UTF-8 Unicode
\chapter{Boundary conditions and interfaces}
\label{chap:boundary_conditions}
We have seen in the previous chapter how to express mass and momentum conservation at the fluid particle level, and we have derived the corresponding equations for fluid motion. These equations are naturally associated with \textbf{boundary conditions} that either express conservation laws (e.g. no mass flux at a boundary) or peculiar physical processes occurring at a surface (temperature or velocity continuity). In both cases these boundary conditions will be pivoting in the determination of the solution.
\section{Fluxes at boundaries: impermeability and imbibition}
\begin{figure}[htbp]
\begin{center}
\includegraphics{impermeability.pdf}
\caption{Balance over an elementary volume located across a solid boundary.}
\label{fig:impermeability}
\end{center}
\end{figure}

Let's consider a solid moving in a fluid at velocity $\bu_\text s$ (possibly time dependent) and let's conduct a mass balance on a small cylindrical volume of base $\delA$ and height $\delh$ located across the fluid and the solid (Fig.~\ref{fig:impermeability}). Now let $\delh$ tends to 0 so that the mass element shrinks down to zero.  From now on, the mass variation of the element should necessarily be zero, and this implies that the mass flux from the fluid has to be balanced by the mass flux from the solid side:
\begin{equation}
-\lp\bj_\text{fluid}\cdot \bn_\text{fluid}\rp \delA -  \lp\bj_\text{solid}\cdot \bn_\text{solid}\rp \delA = 0.
\end{equation}
Let's write arbitrarily $\bn = \bn_\text{fluid} = - \bn_\text{solid}$ so that:
\begin{equation}
-\bj_\text{fluid}\cdot \bn +  \bj_\text{solid}\cdot \bn = 0.
\end{equation}
Without mixing phenomena, the fluid velocity $\bu$ already takes into account diffusive effects (it is the chemical species velocity) and the mass flux reduces to the convective flux. Beware that as we are in the solid reference frame, the relative velocity of the fluid is $\bu - \bu_\text s$, so that the mass flux on the fluid side is:
\begin{equation}
\bj_\text{fluid} = \rho \lp\bu-\bu_\text s\rp.
\end{equation}
\prg{The impermeable wall.\index{boundary conditions!impermeability}} A very common case is that of an \textbf{impermeable} solid in which the fluid cannot penetrate; the fluid mass flux within the solid is therefore zero and $\bj_\text{solid} = \boldsymbol 0$. Mass conservation expressed at an impermeable boundary therefore reduces to:
\begin{equation}
\bu\cdot\bn = \bu_\text s \cdot\bn
\label{eq:impermeability}
\end{equation}
This is the \textbf{impermeability condition} for an object (or a wall). As the name implies, it simply expresses the fact that the fluid cannot penetrate into the solid. This condition takes the form of a \textbf{continuity of normal velocities}.

Note: in the quite particular (but still very common!) case of a fixed solid object, this condition reduces to $\bu\cdot\bn =0$.
\prg{Permeable wall.} The previous discussion naturally extends to the case of permeable walls. Those may correspond to biological tissues permeable to given solutes, to materials swollen by solvents, to terrains soaked by rain or to lifting sails or wings made porous in order to control the boundary layer (such as Cousteau and Malavard' turbosail seen in the lecture).

Now the mass flux is non-zero and its precise determination requires a knowledge of the flow \textit{inside} the solid. Suppose however that the imbibition velocity $\bu_\text{imbib}$ be constant and known (this corresponds for example to a suction with an imposed flowrate). The mass conservation at the permeable wall will then be written:
\begin{equation}
\rho (\bu-\bu_\text s) \cdot \bn = \rho (\bu_\text{imbib}) \cdot \bn,
\end{equation}
thus
\begin{equation}
\bu\cdot\bn = \lp\bu_\text s + \bu_\text{imbib}\rp\cdot\bn.
\end{equation}
\prg{Boundary conditions on a concentration field near a wall.\index{boundary conditions!no-flux}}
The boundary conditions to apply on the transport equation of a concentration field~(\ref{eq:conv_diff}) can be obtained following the same principles. Imagine a concentration field transported with a fluid flow $\bu$. Suppose also that an (impermeable) solid is moving in the fluid at velocity $\bu_\text s$. In the solid reference frame the mass flux across any surface $\delA \,\bn$ is:
\begin{equation}
\bj_\text{mass} = \bj_\text{conv} + \bj_\text{diff} = c \lp \bu - \bu_s\rp - D \nabla c.
\end{equation}
The impermeability condition at the wall for the concentration field $c$ is therefore:
\begin{equation}
c (\bu-\bu_\text s) \cdot \bn - D \nabla c \cdot \bn = 0,
\end{equation}
because the mass flux inside the solid is zero.
On using the impermeability condition on the velocity field~(\ref{eq:impermeability}), this relation reduces to:
\begin{equation}
\nabla c \cdot \bn \equiv \pd{c}{n} = 0.
\end{equation}
This Neumann condition is also called a \textbf{no-flux boundary condition.}
\prg{Mass transfer at an interface: evaporation.\index{boundary conditions!evaporation}} One last example of boundary conditions arising from conservation considerations is the continuity of the mass flux across a liquid-gas interface, when the (single-phase) liquid is evaporating.

Let's write a mass balance on a fluid element analogous to the previous one: a small cylindrical element of base $\delA$ and height~$\delh$ located across a moving interface with velocity $\bu_\text i$. We let the height $\delh$ of the element tend to zero, so that the element mass equally tends to zero. The mass balance over this element is:
\begin{equation}
\bj_\text{liquid conv.} \cdot \bn = \lp\bj_\text{gas conv.} + \bj_\text{gas diff.}\rp \cdot \bn
\end{equation}
so that :
\begin{equation}
\rho_\ell \lp\bu_\ell - \bu_\text i\rp \cdot \bn = \rho_v \lp\bu_g -\bu_\text i\rp\cdot \bn - D \nabla \rho_v \cdot n.
\end{equation}
In the case of a violent evaporation (e.g. combustion front), the flux is dominated by convection effects and
$$\bu_g \sim \underbrace{\frac{\rho_\ell}{\rho_v}}_{\gg 1} \bu_\ell$$
so that the (so-called Stefan) flow induced in the vapour is much stronger than that in the liquid.
In the other limit where evaporation is very slow (case of a slowly drying water drop), it is rather the diffusive term that dominates.
%fixme: add reference on Stefan flow
%fixme: add d2 law for evaporating droplets (e.g. Cazabat et al.) -> tutorial?
\section{Phenomenological conditions: adherence and continuity}
In addition to the previous boundary conditions arising from conservation principles, fluids are also subject to other boundary conditions as well. The latter have been established and confirmed on experimental grounds, so there is a consensus about their relevance but not an exact demonstration. These phenomenological conditions are \textbf{field continuity conditions} at interfaces and apply on velocity, temperature etc.

\paragraph{$\rhd$ A short history of adherence.\index{boundary conditions!adherence}} The adherence condition $\bu = \bu_\mathrm{s}$ has an astonishing history full of twists and turns, which is accounted for in details in \citet{Goldstein1950}. At the \textsc{xviii}$^\text{th}$ century, the theoretical description of potential flows (corresponding to the idealisation of perfect flow of fluid) was already well established, but the comparisons with experimental data were mediocre. Daniel Bernoulli was well aware of this fact and attributed the discrepancies between (ideal) predicted flows and those observed to some ``adherence condition'' that would prevail at the wall. Coulomb then demonstrated experimentally that a disk oscillating in a liquid was not particularly affected by a change in surface properties (smooth, rough or covered with grease). Therefore it appeared to Coulomb that the fluid velocity matched the disk velocity in its vicinity. In this vision the fluid has the same properties in every point of space; the flow just fulfils an additional condition at the wall.

But during the \textsc{xix}$^\text{th}$ century alternate theories appeared. Girard proposed that the liquid layer adjacent to a wall had differing physical properties, leading it to adhere the solid. The next fluid layer (composed of ``regular fluid'') could then freely slip onto the first affixed layer. Navier also got interested into this problem and suggested a boundary condition involving a slip directly proportional to the shear stress $\beta u = \mu \pd{u}{n}$. Here the ratio $\mu/\beta$ has the dimension of a length: it is the \textit{slip length}. From there a period of relative confusion ensued where famous theoreticians of the time (Poisson, Stokes) alternately adopted one or the other of the boundary conditions.

With time however, delicate experiments conducted by Couette or Maxwell advocated definitely for the adherence condition. Maxwell suggested on molecular dynamics considerations that if Navier's condition was effectively valid, the length over which slip occurred was so small -- of the order of a few mean free paths -- that considering it to be zero was a really reasonable hypothesis. This amounted to consider adherence at the wall: $\bu = \bu_\text s$ \citep{Maxwell1879}. This is in particular verified in the usual conditions of laboratory experiments, but not necessarily for rarefied gas flows (e.g. atmospheric reentry, hypersonic flight) or flows involving fluids with long polymer chains (microfluidic flows), as experiments confirm \citep{Henot2018}.
%fixme: add ref on polymer slip

During the \textsc{xx}$^\text{th}$ century, the almost perfect agreement between experimental observations and theoretical predictions using adherence condition for a number of flows (Poiseuille flow, Couette flow, Stokes' sphere settlement in a viscous fluid, the instability threshold for the Taylor-Couette experiment etc) definitely settled the validity of this condition.

Moreover, the scaling laws for the drag on an object deduced from dimensional considerations based on the characteristic scales $\rho, U, D$ and $\mu$ capture the evolution of aerodynamic forces over a wide range of scales. If another lengthscale (associated with slip) was relevant in the description of conventional flows, it would result in an alteration of the scaling laws (not observed).

We can understand adherence condition (continuity of $\bu$ across an interface) but also the condition on temperature continuity as resulting from equilibrium at the molecular level. The extremely rapid transfers between neighbouring molecules induce a quasi-instantaneous equilibrium of mean momentum (velocity) and mean thermal agitation velocity (temperature) \citep{Batchelor1967}. At an interface between a medium \textsc{i} and a medium \textsc{ii} (solid-fluid, or fluid-fluid), we will therefore get:
\begin{equation}
\bu_\text{\textsc{i}} = \bu_\text{\textsc{ii}} \quad \text{and} \quad T_\text{\textsc{i}} = T_\text{\textsc{ii}}.
\end{equation}

\section{Where is the interface?}
A wide range of flows are associated with interfaces: avalanches, rivers, oceans, emulsion droplets, rain or ink drops etc. As we shall see, an interface between a liquid and another fluid is not just an immaterial boundary geometrically delimiting portions of space occupied by fluids. An interface is an \textbf{active region} where surface tension forces act, in some way analogous to those exerted by a taut membrane.

But before precising the nature of these forces acting on the interface, we first need to be able to know where the interface is! Indeed, an interface is constantly moving by definition and we have to start tracking the interface through time and space. This is the purpose of the \textit{kinematic boundary condition} which will allow us to follow the interface in its motion.
\subsection{Kinematic boundary condition.\index{boundary conditions!kinematic}} In order to describe the motion of any given interface, as a free surface for example, let's introduce an arbitrary function $\mathcal S(\bx,t)$ that vanishes on the interface at all times: for each point $\bx_\text{interf}$ of the interface,~$\mathcal S(\bx_\text{interf},t)~=~0$. Between two successive instants, an interface point is displaced with a distance $\delbx = \bu_\text i \delt$ and:
\begin{equation}
\mathcal S(\bx_\text{interf} + \bu_\text i \delt, t + \delt) \approx \underbrace{\vphantom{\lp\pd{\mathcal S}{t}\rp}\mathcal S(\bx_\text{interf},t)}_0 + \delt\underbrace{\lp\pd{\mathcal S}{t} + \lp\bu_\text  i \cdot \nabla\rp\mathcal S\rp}_{\D{_\text i\mathcal S}{t}} = 0.
\end{equation}
To get the interface velocity $\bu_\text i$\footnote{We note that in the expression of $\mathcal S$, only the normal component $\bu_\text i \cdot \bn$ of $\bu_\text i$ at the interface is involved.} we just need to express the mass flux boundary condition at the interface. If there is no mass transfer at the interface (such as e.g. evaporation), the latter reads:
\begin{equation}
\rho \lp \bu - \bu_\text i\rp \cdot \bn = 0 \quad \text{thus} \quad \bu \cdot \bn = \bu_\text i \cdot \bn,
\end{equation}
so that the kinematic boundary condition describing the motion of a free surface simply reads:
\begin{equation}
\D{\mathcal S}{t} = 0
\end{equation}
\prg{Example: description of a free surface.} Consider a free surface such as the ocean's, characterised\footnote{We here suppose that the interface is single valued (no wave breaking!).} with $z = \zeta(x,y,t)$. The surface is described at each instant by the vanishing of the function\footnote{We could imagine other functions as well, e.g. $\mathcal S(\bx,t) = \tanh\lp z - \zeta\lp x,y,t\rp\rp$ \ldots} :
\begin{equation}
\mathcal S(\bx,t) = z - \zeta(x,y,t).
\label{eq:bumped_free_surface}
\end{equation}
The kinematic boundary condition describing the position of the free surface is therefore:
\begin{equation}
\D{\mathcal S}{t} = 0 \quad \text{hence}\quad \pd{\zeta}{t} = u_z - u_x \pd{\zeta}{x} - u_y \pd{\zeta}{y}
\end{equation}
\subsection{Surface geometry I. Normals.\index{normal vector}} In a number of problems involving free surfaces, deformable and/or complex boundaries, the expression for the normal vector has to be provided. A systematic procedure to obtain the expression for this vector stems in remarking that the free surface coincides with a $\mathcal S$-isosurface. As a result the normal vector is necessarily parallel with the \textbf{gradient} of $\mathcal S$ :
\begin{equation}
\bn = \frac{\nabla \matS}{\|\nabla \matS\|}
\end{equation}
\prg{Example: free surface normal.} Let's consider the previous example again. We have:
$$
\nabla \matS = \lp
\arraycolsep=1.4pt\def\arraystretch{1.5}
\begin{array}{c}
-\pd{\zeta}{x}\\
-\pd{\zeta}{y}\\
1
\end{array}
\rp,
$$
so
\begin{equation}
\bn = \frac{1}{\sqrt{1+\pd{\zeta}{x}^2+\pd{\zeta}{y}^2}}\lp
\arraycolsep=1.4pt\def\arraystretch{1.5}
\begin{array}{c}
-\pd{\zeta}{x}\\
-\pd{\zeta}{y}\\
1
\end{array}
\rp.
\label{eq:wave_normal}
\end{equation}
We note the the direction of this normal is quite arbitrary and chosen by convention (usually, the convention is that of exterior-pointing normal. However this only makes sense if the very notion of exterior makes sense!).

\section{Capillarity\index{surface tension}}
\begin{figure}[htbp]
\begin{center}
\includegraphics[width=4cm]{boys_brush.pdf} \\
\includegraphics[height=4cm]{capillary_spool_downsampled.jpg} \quad
\includegraphics[height=4cm]{gerris_on_water_downsampled.png}
\end{center}
\caption{Top: when pulled out of water, a wet brush has its bristles stuck altogether, but those are neatly separated is the brush is dry or fully immersed \citep{Boys1890}. Bottom left: a drop deposited on a sufficiently thin fibre such as the spider capture silk induces coiling and spooling within the droplet \citep{Elettro2016}. Bottom right: the Gerris, an aquatic insect, can literally walk on water although it is denser (\href{https://www.flickr.com/photos/ryoichi360/5847533955/in/photolist-9UJ97X-EU3vy-V3eJzF-8wimyD-fafpgs-HKfkdJ-22TUHgL-SWUure-dcK4vX-2baXF3n-DhVeuP-rMc5KH-253wqN-2fQ2VWT-8p2CBK-8d9rrm-VmimZt-PcW89C-283Sj59-Hvg77b-N9Ytvw-SN5EhR-cQ7gBj-s4aR9q-eDcCJz-HrEa1e-6hizYZ-Wq8cWg-FYhg7k-8874aQ-iJqVV-56yPYc-X5ffoi-pkU5Zt-p9ztvz-ZSJkzJ-ofYXjT-a9n3xT-2ekD2e9-5sAmFu-ccGJis-24KoY9K-QZW2Li-4f9Fjc-fyuZPT-Hr29p5-kLdZ8n-Tu8m9W-nQg4Lr-s85mcc}{photograph by Ryoichi on Flickr}). These examples are manifestations of surface tension exerted at liquid-gas interfaces.}
\label{fig:surface_tension}
\end{figure}
Having described kinematically interfaces (i.e. how to locate them) along with the boundary conditions resulting from mass conservation and molecular equilibria (adherence condition), we shall now get interested into the dynamical aspects of interfaces and more particularly to the phenomenon of \textit{capillarity} \citep{de-Gennes2015}.

An interface between two immiscible fluids, as that between air and water is, is a material surface separating the two media. But actually such an interface is in reality way more that a simple geometric place delimiting two portions of space. An interface \textbf{bears forces} whose manifestation is visible in daily-life examples, such as the clogging of wet hairs, the spooling of spider thread within glue droplets or the sustentation of small aquatic animals such as the Gerris (Fig.~\ref{fig:surface_tension}).

\subsection{Cohesion}
The microscopic origin of surface tension is rooted in \textbf{cohesion} effects in liquids. Indeed, atoms or molecules that constitute matter interact with each other with forces of changing nature. Repulsive at very short distance, the forces become attractive at longer range. In the context of a gas, the intermolecular distances are far too large for these interactions to have any notable effect. But this is not true for dense phases such as liquids where molecules attract each other. This matter cohesion phenomenon is responsible for the rounded shape of droplets, the curvature of menisci or that of soap films. The history of the link between attractive forces and surface tension is already present in the writings of Newton, but this link was not really elucidated until Laplace in 1805 \citep{Laplace1805}. With the unique hypothesis of attractive forces between two matter particles decaying with distance, Laplace succeeded in finding with differential calculus all equilibria shapes of interfaces. He also explained the capillary rise in tubes, a phenomenon resisting understanding so far \citep{Rowlinson2005}. He further evidenced a pressure jump phenomenon (normal stress) proportional to curvature, as we shall now see.
\subsection{Surface tension}
In parallel to Laplace's works on cohesion and capillarity, Thomas Young also managed to find in 1805 a result on the pressure jump across interfaces identical to Laplace's finding. But he followed an entirely different route \citep{Young1805}. On the basis of experimental observations of free surface deformations similar to those of elastic membrane, Young postulated the existence of a tension force localised at the liquid surface, and analogue to membrane tension -- such as the one developing in a stretched balloon. Following this reasoning, a small, flat and rectangular surface element $\delta S = \delta \ell_1 \delta \ell_2$ such as the one illustrated figure~\ref{fig:flat_surface} would be subject to a total force:
$$
\lp \gamma \delta \ell_2 - \gamma \delta \ell_2 \rp \be_1 + \lp \gamma \delta \ell_1 - \gamma \delta \ell_1 \rp \be_2 = \boldsymbol 0.
$$
As a matter of fact, each force contribution is balanced by another because the surface is flat. But we feel here that this result may change as soon as the surface will be curved. Before proceeding in the estimation of the surface tension force for a general surface, we have to characterise the curvature of a surface.
\begin{figure}[htbp]
\begin{center}
\includegraphics{flat_surface_poly.pdf} \end{center}
\caption{A flat interface portion is subject to a tension force at its periphery.}
\label{fig:flat_surface}
\end{figure}

\subsection{Surface geometry II. Curvature.\index{curvature}}
\begin{figure}[htbp]
\begin{center}
\includegraphics[width=10cm]{principal_curvature.pdf}
\end{center}
\caption{A curved surface portion intersected with a plane displays different radii of curvature depending on the plane orientation.}
\label{fig:principal_curvature}
\end{figure}
Let's consider the portion of curved interface represented figure~\ref{fig:principal_curvature}. The curvature of the surface on a given point is a geometric quantity that can be built as follows. Start by identifying the normal $\bn$ to the surface at the chosen point. Consider now two perpendicular planes that each contain $\bn$. Each plane will intersect the surface following a curve which may be approximated by a circle in the vicinity of the chosen point. Of course the circle radius will differ in each plane in the general case: we will note it for example $R_1$ in the plane $\lp\be_1,\bn\rp$ and $R_2$ in the plane $\lp\be_2,\bn\rp$. The \textbf{mean} (or arithmetic) \textbf{curvature} $\kappa$ of the surface at the considered point is defined as the sum of the two circle curvatures :
\begin{equation}
\kappa \equiv \frac{1}{R_1} + \frac{1}{R_2}.
\end{equation}
This definition calls for two remarks. The first one regards the unicity of $\kappa$'s definition. Indeed we might envisage another set of two orthogonal planes, each of them also containing $\bn$ (obtained via a simple rotation around $\bn$). We would then get two other values for $R_1$ and $R_2$. Remarkably, it can be shown in surface geometry that if $R_1$ and $R_2$ are not defined in an univocal way, the sum $\frac{1}{R_1} + \frac{1}{R_2}$ is independent of the planes choice! The curvature $\kappa$ is a surface \textbf{invariant} (except in ill-defined cases, such as surfaces with cusps or corners -- in which case the curvature diverges). The second remark is about the curvature sign. Curvature radii are signed quantities, considered positive by convention if the curvature centre is inside the surface, and negative otherwise (to differentiate what is inside from what is outside, we still use the exterior normal convention). It is therefore possible to have a surface of negative curvature.

\prg{Curvature of a sphere.}
To illustrate this notion, let's consider a simple sphere of radius $R$.
\begin{figure}[htbp]
\begin{center}
\includegraphics[width=4cm]{sphere_undeformed.png}
\end{center}
\caption{A sphere.}
\label{fig:sphere}
\end{figure}
At a given point of the surface, the normal vector is given by $\be_r$ and the two perpendicular planes intersecting the sphere will be two (exact) circles each of radius $R$. As a consequence we will have:
\begin{equation}
\kappa_\text{sphere} = \frac{2}{R}.
\end{equation}

\prg{Extension to general surfaces.}
The previous approach, although visual and making direct contact with the meaning of curvature, suffers from some shortcomings. Indeed, beyond elementary shapes (cylinder, cone, axisymmetric surfaces etc) it appears difficult to identify the relevant curvature radii for more general surfaces, such as the wavefield described by equation~\eqref{eq:bumped_free_surface}.

Fortunately there exists an alternate definition for the curvature that comes from surface differential geometry. This alternate definition allows for an easy computation of curvature in every situations:
\begin{equation}
\kappa \equiv \nabla_s \cdot \bn.
\end{equation}
Here the operator $\nabla_s$ represents the surface divergence. In practice we will calculate the (full) divergence of the vector field~$\bn$ defined in every point of space, and then simply consider the restriction of this field at the interface. Now an example to shed some light over this definition.
\prg{Curvature of a sphere (again).} Let's consider again the sphere example. In order to determine $\bn$, we introduce the ``colour function'' $\matS(r) = r - R$. Its normalised gradient gives $\bn = \be_r$ in every point of space -- and in particular at the sphere' surface. The divergence of $\be_r$ reads \textit{in every point of space}:
\begin{equation}
\nabla \cdot \be_r = \frac{1}{r^2} \pd{}{r} \lp r^2 \times 1 \rp = \frac{2}{r}
\end{equation}
The restriction of this field \textit{to the sphere' surface} gives the curvature:
\begin{equation}
\kappa_\text{sphere} = \left.\nabla \cdot \be_r\right|_{r=R} = \left.\frac{2}{r}\right|_{r=R} = \frac{2}{R}.
\end{equation}
\prg{Curvature of a wavefield.} Let's go back to the wavefield equation~\eqref{eq:bumped_free_surface}. The divergence of the normal vector field~\eqref{eq:wave_normal} in each point of space is:
\begin{equation}
\kappa= -\frac{\Delta_\parallel \zeta}{\sqrt{1+\zeta_x^2+\zeta_y^2}} + \frac{\zeta_x\lp\zeta_x \zeta_{xx} + \zeta_y \zeta_{yx}\rp + \zeta_y\lp\zeta_x \zeta_{xy} + \zeta_y \zeta_{yy}\rp}{\lp 1+\zeta_x^2+\zeta_y^2\rp^{3/2}},
\end{equation}
where $\Delta_\parallel \equiv \frac{\partial^2}{\partial x^2} + \frac{\partial^2}{\partial y^2}$ represents the horizontal Laplace operator. We denote in the previous expression differentiation with indices, so that $ \zeta_{yy} = \frac{\partial^2\zeta}{\partial y^2}$. We see thatt it would have been difficult to establish this relation with circles tangenting the surface! We finally note that in the limit of slender slope, where $\zeta_x,\zeta_y$ are \textit{a priori} much smaller than 1, the expression simplifies significantly to become
\begin{equation}
\kappa \simeq - \Delta_\parallel \zeta \quad \text{in the limit of slender slopes}.
\end{equation}
Yet another manifestation of Laplace operator!
\section{Young-Laplace's pressure jump}
\begin{figure}[htbp]
\begin{center}
\includegraphics[valign=m,width=6cm]{curved_surface_force.pdf}
\includegraphics[valign=m,width=8cm]{curved_surface_cut.pdf}
\end{center}
\caption{Left: a portion of curved interface is subjected to an effective force that depends both on surface tension and on geometry $-\gamma \kappa \, \bn \, \delta S$. Right: sketch of the forces acting on a surface slice showing that contributions along the normal add up.}
\label{fig:curved_surface}
\end{figure}
Having clarified the notion of surface curvature, we can go back to the estimation of the effective surface tension force exerted on a \textit{curved} interface portion. To do so we consider the elementary surface portion described in figure~\ref{fig:curved_surface}. This elementary surface is subtended by two elementary arcs of curvilinear lengths $\delta \ell_1$ and $\delta \ell_2$. To first order the surface is then given by $$\delta S = \delta \ell_1 \delta \ell_2.$$ These two elementary arcs are linked to the two curvature radii $R_1$ and $R_2$ by the infinitesimal angles $\delta \theta$ and $\delta \psi$ represented on figure~\ref{fig:curved_surface} :
\begin{subequations}
\label{eq:curvature_radius}
\begin{empheq}[left=\empheqlbrace]{alignat=2}
\delta \ell_1 \,&=&\, R_1 \delta \theta\\
\delta \ell_2 \,&=&\, R_2 \delta \psi
\end{empheq}
\end{subequations}
To quantify the action of the forces, start by considering the cut indicated on figure~\ref{fig:curved_surface} (right). The two contributions of intensity $\gamma$ are each inclined by $\delta \theta / 2$ with respect to the tangent at the considered point. As a result, the projection along the tangent  $\bt$ and the normal $\bn$ are:
\begin{empheq}[left=\empheqlbrace]{alignat=2}
\text{projection along $\bt$ :} \qquad & \gamma \cos \lp \delta \theta / 2 \rp -  \gamma \cos \lp \delta \theta / 2 \rp = 0\\
\text{projection along $\bn$ :} \qquad & -\gamma \sin \lp \delta \theta / 2 \rp -  \gamma \sin \lp \delta \theta / 2 \rp \simeq -2 \gamma \delta \theta / 2 = - \gamma \delta \theta
\end{empheq}
This is true for each cut along the path $\delta \ell_2$, so that the contribution of surface tension for these two opposite sides is $ -\gamma \delta \theta \delta \ell_2$ along $\bn$. We can repeat this line of reasoning for the two other sides, and we obtain the total contribution of surface tension on this small curved element:
\begin{equation}
\delta \boldsymbol f_\text{cap} = - \gamma \lp \delta \theta \delta \ell_2 + \delta \psi \delta \ell_1 \rp \bn.
\end{equation}
We can reexpress this relation with the help of the curvature radii~\eqref{eq:curvature_radius}:
\begin{equation}
\delta \boldsymbol f_\text{cap} = - \gamma \lp \frac{1}{R_1}\delta \ell_1 \delta \ell_2 + \frac{1}{R_2}\delta \ell_1 \delta \ell_1 \rp \bn,
\end{equation}
so that finally:
\begin{equation}
\delta \boldsymbol f_\text{cap} = - \gamma \kappa \, \bn \, \delta S.
\end{equation}
In other words a small curved surface element will be accelerated towards its curvature centre with a force of intensity proportional to both surface tension and curvature. The force exerted on an element therefore depends on its geometry!

Let's stop for a moment and discuss the consequences of such a force. From the previous expression we might be tempted to conclude that each element of a water droplet is accelerated towards its centre, and that the droplet should collapse onto itself. To understand how droplets and other interfaces can withstand this force and remain at equilibrium, we have to remember that droplets are made of a liquid (e.g. water) that is hardly compressible. In practice this incompressibility constraint is guaranteed\footnote{Note: even in compressible fluids (ex: bubble) a pressure field is established to counterbalance the effect of capillary force.} with the help of a pressure field that will balance the effect of surface tension. Actually, a pressure field is present in the liquid, even at equilibrium. As seen in chapter~\ref{chap:fluid-motion} the pressure force exerted onto the small considered surface element will be:
$$
\delta \bff_\text{pressure} = \lp p_\text{int} - p_\text{ext}\rp \bn \,\delta S.
$$
The interface portion equilibrium condition will then be:
\begin{equation}
\delta \bff_\text{cap} + \delta \bff_\text{pressure}  = \boldsymbol 0,
\end{equation}
so that\index{Laplace pressure jump}
\begin{equation}
\Delta p = p_\text{int} - p_\text{ext} = \gamma \kappa.
\label{eq:laplace_jump}
\end{equation}
To ensure equilibrium, a \textbf{pressure jump} will be established across an interface. This surprising result, due to Young and Laplace, implies that a millimetric rain droplet can sustain overpressure of $\gamma \kappa \simeq 7 \times 10^{-2} \times \frac{2}{10^{-3}} = 140 $ Pa with respect to the atmosphere, and a micron-sized fog droplet will endure an overpressure of $\simeq 7 \times 10^{-2} \times \frac{2}{10^{-6}} = 1.4\times 10^{5} $ Pa, thus 1.4 bars more than atmospheric pressure!
\subsection{Surface tension?}
We followed in the previous analysis Young's viewpoint according to which the interface would be taut by a constant surface tension $\gamma$. We also recovered Laplace's result of the pressure jump when traversing a curved interface. Laplace did not suppose a distributed surface tension but only attractive forces between molecules. But as we have seen in the previous part, it is possible to switch mathematically from a tangent force representation to an effective normal force, and the reverse. Our demonstration is in fact the expression of a generalisation of Frénet's formulae to three dimensions:
\begin{equation}
\oint_C \bp\,\mathrm d\ell = -\iint_A \kappa \bn\, \mathrm dS,
\end{equation}
where $\bp$ is a vector tangent to the interface and $C$ a closed curve over the interface \citep{Tryggvason2011}. From this, we may wonder if surface tension exists \textit{really}, or if it is not simply a convenient mathematical trick to describe the attractive interactions between molecules.
\begin{figure}[htbp]
\begin{center}
\includegraphics[width=8cm]{marchand_andreotti.pdf}
\end{center}
\caption{Dynamic molecular simulations show that in the vicinity of an interface, molecules are farther apart than in the liquid bulk. This depletion is associated with an increase of attractive force between molecules at the surface. The macroscopic consequence of this increase is the emergence of surface tension \citep{Marchand2011}.}
\label{fig:marchand}
\end{figure}
It is now possible to use dynamic molecular simulations to answer this question. As shown in figure~\ref{fig:marchand}, there exists a force parallel to the interface that stems from a depletion in near surface molecules: surface tension has therefore a physical reality! \citep{Berry1971,Marchand2011}.

%Mais contrairement à une membrane élastique, la \textbf{tension de surface} $\gamma$ d'une interface est constante, quel que soit l'étirement imposé. La valeur de cette tension de surface est très faible -- de l'ordre de quelques dizaines de milliNewtons par mètre tout au plus, mais elle est suffisante pour sculpter des interfaces liquides et conférer, par exemple, une forme sphérique à de petites gouttes d'eau.

\subsection{Stress (dis-)continuity}
Thanks to the notion of \textit{stress}, we may easily extend the previous result to the case of moving interfaces. To do so let's consider an elementary volume in the shape of a camembert box leaning on each side of the interface, see figure~\ref{fig:impermeability}. Now we let the volume thickness tend to 0, and so will its mass -- and therefore its momentum. As a result the sum of the forces acting on this volume must be zero as well. We have already seen that the net sum of interfacial stresses is $-\gamma \kappa \, \bn \, \delta S$. The stress exerted by the exterior medium is $\mathsfbfit{\sigma}_\text{ext} \bn_\text{ext} \delta S$, and similarly for the stress exerted by the interior medium $\mathsfbfit{\sigma}_\text{int} \bn_\text{int} \delta S$, with $\bn_\text{ext} = - \bn_\text{int} = \bn$. The condition for interface equilibrium will thus be:
\begin{equation}
\lp\mathsfbfit{\sigma}_\text{ext} - \mathsfbfit{\sigma}_\text{int}\rp \bn = \gamma \kappa \bn.
\end{equation}
This is a really general relation that expresses a \textbf{normal stress jump} at the interface. So in the static case where $\sigij = -p \delij$, this relation becomes:
\begin{equation}
\Delta p = p_\text{int} - p_\text{ext} = \gamma \kappa,
\end{equation}
which is naturally the Laplace pressure jump seen in~\eqref{eq:laplace_jump}.

\section{Equilibrium shape for a meniscus\index{meniscus}}
\begin{figure}[htbp]
\begin{center}
\includegraphics[height=4.5cm]{wss-property-meniscus-water-mercury_0.jpg}
\includegraphics{meniscus.pdf}
\end{center}
\caption{Left: mercury or water contained in test tubes exhibit sharply different menisci (\href{https://www.usgs.gov/media/images/water-has-upward-meniscus-mercury-has-a-downward-meniscus}{Creative Commons}). Right: equilibrium profile for a meniscus, parameterised by the wetting angle at the wall.}
\label{fig:meniscus}
\end{figure}
We now have all the keys to determine interface shapes under the influence of surface tension. As an illustration we will consider in this last part the equilibrium shape for a meniscus. A meniscus is the particular shape adopted by a liquid-gas interface near a wall (figure~\ref{fig:meniscus} left). Actually at the contact of a wall, an interface displays a \textit{contact angle} that depends on the chemical nature of the liquid and of the wall: water or alcohol on glass or metal will have contact angles smaller than $\frac{\pi}{2}$ (\textit{wetting} or \textit{hydrophilic} case) whereas water on wax, on a non-stick frying pan or mercury over glass will display contact anglese larger than $\frac{\pi}{2}$. The corresponding case will qualify as \textit{non-wetting} or \textit{hydrophobic}.
\prg{Equation for the meniscus.} At the wall contact, the interface forms an angle $\theta$. Yet far from the wall the interface is back to planar undedr the influence of gravity. In between, the interface will adopt a shape of a membrane ``taut'' by the action of surface tension -- and under the influence of gravity. Over which lengthscale $\ell$ does this matching take place? We can give a first estimation with dimensional analysis. Here $\ell = f(\rho, \gamma, g)$, and as $[\gamma] = \mathsf{M}\mathsf{T}^{-2}$ a direct application of $\pi$ theorem informs us that this matching length will be proportional to:
\begin{equation}
\ell_\text{gc} = \sqrt{\frac{\gamma}{\rho g}}.
\end{equation}
This is the \textit{gravity-capillary length} (sometimes simply coined capillary length).

Let's now determine the equation driving the shape for the interface. To this end, let's introduce first the $z$ coordinate whose origin will be at the interface height very far from the wall. We will monitor the interface height at each point with the function $z = h(x)$. At the interface level the pressure jump relation~\eqref{eq:laplace_jump} allows us to write:
\begin{equation}
p(z=h) - P_\text{atm} = \gamma \kappa,
\end{equation}
where $p(z=h)$ is the pressure in the liquid near the interface, and $P_\text{atm}$ is the atmospheric pressure. Before going further, let's remark that the interface curvature centre is \textit{outside} (of the liquid): the pressure jump will therefore be negative, which implies that the liquid pressure will be  \textit{lower} than atmospheric pressure.

In the liquid, hydrostatics applies, so $p(z) = P_\text{atm} - \rho g z$. We therefore have:
\begin{equation}
-\rho g h = \gamma \kappa,
\end{equation}
or
\begin{equation}
h = -\ell_\text{gc}^2 \kappa.
\label{eq:meniscus}
\end{equation}
This is the interface equation.
\prg{Equilibrium profile in the slender slope limit.} In general this equation is quite difficult to solve because of its nonlinearities. Indeed, the interface curvature reads:
\begin{equation}
\kappa(x) = -\frac{h''}{\lp 1 + h'^2\rp^{3/2}}.
\end{equation}
But in the slender slope limit, corresponding to contact angles close to $\frac{\pi}{2}$ -- and anyway always true sufficiently far from the wall --, $h' \ll 1$ and $\kappa \simeq -h''$. As a result~(\ref{eq:meniscus}) admits exponential solutions of the type $e^{x/\ell_\text{gc}}$ and $e^{-x/\ell_\text{gc}}$. Only the latter solution allows to recover a flat profile at infinity. In the slender slope limit, the interface is therefore desccribed with:
\begin{equation}
h(x) = A e^{-x/\ell_\text{gc}},
\end{equation}
where $A$ is a constant set by the boundary conditions. In the slender slope limit, we will have near the wall $h' = - (\frac{\pi}{2}-\theta)$, so:
\begin{equation}
h(x) =  \ell_\text{gc} (\frac{\pi}{2}-\theta) e^{-x/\ell_\text{gc}}.
\end{equation}
\prg{Meniscus weight.} If we were to suppress the wall in figure~\ref{fig:meniscus} right, the interface would naturally get back to the position $z=0$. A question is therefore: what bears the meniscus weight? (because it is not the liquid pressure far below). The only remaining candidate is the wall: the wall exerts a force of intensity $\gamma$ parallel to the interface and therefore lifts the liquid. In vertical projection, this force has a contribution $F_\text{cap}=\gamma \cos \theta$, which has to balance the meniscus weight.

We can verify this fact by calculus with the help of equation~\eqref{eq:meniscus}. Let's introduce the angle $\phi$ that the interface forms locally with the horizontal ($\phi = \theta - \pi/2$). Whenever we follow an elementary interface portion $\mathrm ds$, this angle changes by an amount $\mathrm d \phi$ such that $\mathrm ds = R \mathrm d \phi = -\frac{1}{\kappa} \mathrm d \phi$. From this relation we deduce $\kappa = -\dd{\phi}{s}$. The equation for the meniscus then becomes:
\begin{equation}
-\rho g h(s) = - \gamma \dd{\phi}{s}.
\end{equation}
On remarking that $\cos\phi = \dd{x}{s}$, we see that the meniscus weight can be written as:
\begin{equation}
P = - \rho g \int_0^\infty h(x) \, \mathrm dx = - \rho g \int_0^\infty h(s) \cos \phi \, \mathrm ds.
\end{equation}
Thus, by multiplying the interface equation by $\cos \phi$ we get:
\begin{equation}
\underbrace{-\rho g \int_0^\infty h(s)\cos \phi\,\mathrm ds}_P = - \gamma \int_0^\infty \cos\phi \dd{\phi}{s}\, \mathrm ds = - \gamma \left[ \sin \phi \right]_0^\infty = \gamma \sin \phi_0 = \underbrace{-\gamma \cos \theta}_{-F_\text{cap}}.
\end{equation}

ext: tex

max_stars_repo_name: antko/physics-of-fluids

max_issues_repo_name: antko/physics-of-fluids

max_forks_repo_name: antko/physics-of-fluids


text:
\subsection{Recruitment Variability and Bias Correction}
\hypertarget{BiasCorrect}{}

Recruitments are defined as lognormal deviates around a log-bias adjusted spawner-recruitment curve.  The magnitude of the log-bias adjustment is calculated from the level of $\sigma_R$ , which is the standard deviation of the recruitment deviations (in log-space).  There are 5 segments of the time series in which to consider the effect of the log-bias adjustment: virgin; initial equilibrium; early data-poor period; data-rich period; very-recent/forecast. The choice of break points between these segments need not correspond directly with the settings for the bias adjustment, although some alignment might be desired. \citet{methot-adjusting-2011} provide more detailed discussion of the bias adjustment than what is provided below but do not address the separation of time periods into separate segments. The approach is illustrated with figures associated the assessment for darkblotched rockfish \citep{gertseva-status-2013}.

\begin{figure}[H]
	\begin{center}
		\includegraphics[scale = 0.70]{appendixA_recruits}\\
	\end{center}
	\caption{Spawner-recruitment relationship for dark-blotched rockfish \citep{gertseva-status-2013}. Red points represent estimated recruitments, the solid black line is the stock-recruit relationship and the green line represents the adjustment to this relationship after adjustment to account for the lognormal distribution associated with each year. The "+" symbol labeled 1915 near the right side represents both the virgin and initial equilibrium of the model. The numerous red points close to the initial conditions correspond to the early years of the model with low harvest rates.}
	\label{fig:recruits}
\end{figure}

\begin{figure}[H]
	\begin{center}
		\includegraphics[scale = 0.90]{appendixA_logdevs}\\
	\end{center}
\caption{ Time series of log recruitment deviations for darkblotched rockfish with 95\% uncertainty intervals. The start year of the model is 1915, but recruitment deviations are estimated starting in 1870. The 45 deviation estimates for 1870–1914 inform the age structure used in the start year. The black color for the years 1960–2011 indicates the "main" recruitment deviation vector, while the blue color for the years 1870–1959 and 2012–2024 indicates the "early" and "late/forecast" recruitment deviation vectors, respectively.}
\label{fig:recdevs}
\end{figure}

\myparagraph{Virgin Biomass}
The R0 level of recruitment is a parameter of the spawner-recruitment curve.  This recruitment and the corresponding spawning biomass are expected to represent the long-term arithmetic mean.

\myparagraph{Initial Equilibrium}
The level of recruitment is typically maintained at the R0 level even though the initial equilibrium catch will reduce the spawning biomass below the virgin level. If steepness is moderately low or the initial F is high, then the lack of response in recruitment level may appear paradoxical. The logic is that building in the spawner-recruitment response to initial F would significantly complicate the calculations and would imply that the initial equilibrium catch level had been going on for multiple generations. If the lack of response is considered to be problematic in a particular application, then start the model at an earlier year and with a lower initial equilibrium catch so that the dynamics of the spawner-recruitment response get captured in the early period, rather than getting lost in the initial equilibrium.

\myparagraph{Early Data-Poor Period}
This is the early part of the time series where the only data typically are landed catch. There are no data to inform the model about the specific year-to-year fluctuations in recruitment, although the ending years of this period will begin to be influenced by the data.  The "early time period" is not a formal concept. It is up to the user to decide whether to start estimating recruitment deviations beginning with the first year of the model, or to delay such estimation until the data become more informative. Modeling recruitment deviations in this period may lead to a more realistic portrayal of the uncertainty in depletion, but can also lead to spurious patterns in estimated recruitments that may be driven by the fit to index data or other sources that would not be expected to have accurate information on recruitment.
	\begin{itemize}
		\item Option A: Do not estimate recruitment deviations during this early period.  During years prior to the first year of recruitment deviations, the model will set the recruitment equal to the level of the spawner-recruitment curve.  Thus, it is a mean-based level of recruitment.  Because these annual parameters are fixed to the level of the spawner-recruitment curve, they have no additional uncertainty and make no contribution to the variance of the model. This approach may produce relatively large, or small, magnitude deviations at the very beginning of the subsequent period, as the model "catches up" to any slight signal that could not be captured through estimated deviations in the early data-poor period.  There may be some effect on the estimate of R0 as a result of lack of model flexibility in balancing early period removals with signal in the early portion of the data-rich period.
		\item Option B: Estimate recruitment deviations for all the early years. Each of these recruitment deviations is now a deviation parameter so will have a variance that contributes to the total model variance. The estimated standard deviation of each of these deviation parameters should be similar to $\sigma_R$ because $\sigma_R$ is the only constraint on these parameters (however, the last few in the sequence will begin to feel the effect of the data so may have lower standard deviations).
	\end{itemize}

\myparagraph{Data-Rich Period}
Here the length and or age data inform the model on the year-to-year level of recruitment.  These fluctuations in recruitment are assumed to have a lognormal distribution around the log-bias adjusted spawner-recruitment curve.  The level of $\sigma_R$ input to the model should match this level of fluctuation to a reasonable degree.  Because the recruitments are lognormal, they produce a mean biomass level that is comparable to the virgin biomass and thus the depletion level can be calculated without bias.  However, if the early period has recruitment deviations estimated by maximum posterior density, then the depletion levels during the early part of the data-rich period may have some lingering effect of negative bias during the early time period. The level of $\sigma_R$ should be at least as large as the level of variability in these estimated recruitments.  If too high a level of $\sigma_R$ is used, then a bias can occur in the estimate of spawner-recruitment steepness, which determines the trend in recruitment.  This occurs when the early recruitments are taken directly from the spawner- recruitment curve, so are mean unbiased, then the later recruitments are estimated as deviations from the log-bias adjusted curve.  If $\sigma_R$ is too large, then the bias-adjustment is too large, and the model may compensate by increasing steepness to keep the mean level of recent recruitments at the correct level.

\myparagraph{Recent Years/Forecast}
Here the situation is very similar to the early time period in that there are no data to inform the model about the year-to-year pattern in recruitment fluctuations so all deviations will be pulled to a zero level in the maximum posterior density.  The structure of SS3 creates no sharp dividing line between the estimation period and the forecast period.  In many cases one or more recruitments at the end of the time series will lack appreciable signal in the data and should therefore be treated as forecast recruit deviations.  To the degree that some variability is observed in these recruitments, partial or full bias correction may be desirable for these deviations separate from the purely forecast deviations, there is therefore an additional control for the level of bias correction applied to forecast deviations occurring prior to end year + 1.

\begin{figure}[H]
	\begin{center}
	\includegraphics[scale = 0.90]{appendixA_asymerror}\\
	\end{center}
	\caption{ Timeseries of standard error estimates for the log recruitment deviations for darkblotched rockfish with 95\% uncertainty intervals. As in Figure \ref{fig:recdevs}, the black color indicates the main recruitment period. This period with lower standard error is associated with higher variability among deviations (Figure \ref{fig:recdevs}). The red line at 0.75 indicates the  $\sigma_R$ value in this model.}
	\label{fig:recSE}
\end{figure}

\begin{figure}[H]
	\begin{center}
	\includegraphics[scale = 0.90]{appendixA_biasadj}\\
	\end{center}
	\caption{ Transformation of the standard error estimates (shown in Figure \ref{fig:recSE}) for darkblotched rockfish following the approach suggested by \citet{methot-adjusting-2011}. These values were used to set the 5 values controlling the degree of bias adjustment (as a fraction of  $\sigma_R/2$) to account for differences in the mean and median of the lognormal distribution from which the recruitment deviations are drawn. The red line indicates a bias adjustment of 0 up to the  1960.75, ramping up to a maximum adjustment level of 0.877 for the period 1990.4–2008.98,and reducing back to 0 starting in 2013.08. Note that these values controlling the bias adjustment need not be integer year values. Also the break points in the bias adjustment function need not match the break points between early, main, and late/forecast recruitment deviation vectors (indicated by blue and black colors in Figures \ref{fig:recdevs} and \ref{fig:recSE}). The blue line indicates a functional form that minimizes the sum of squared differences between the bias adjustment function and the transformed standard error values. The subtle differences between red and blue lines are unlikely to have any appreciable effect on the model results.}
	\label{fig:ramp}
\end{figure}

\begin{figure}[H]
	\begin{center}
	\includegraphics[scale = 0.90]{appendixA_depl}\\
	\end{center}
	\caption{ Comparison of timeseries of spawning depletion for darkblotched rockfish models with early recruitment deviations (starting in 1870) and without early deviations (only main recruitment deviations starting in 1960). The point estimates are similar, but the 95\% uncertainty intervals are substantially different. With no recruitment deviations for the early period, the estimates of spawning depletion in the early years are very precise and uncertainty increases as the stock moves into the data rich period. In contrast, the addition of the early recruitment deviations results in a large uncertainty in spawning depletion for the early years and an increase in precision as the stock moves into the data rich period. In this application, the uncertainty associated with the recent years is independent of the assumptions about early recruitments.}
\end{figure}

\myparagraph{Issues with Including Environmental Effects}
The expected level of recruitment is a function of spawning biomass, an environmental time series, and a log-bias adjustment.
\begin{equation}
	E(Recruitment) = f(SpBio) * exp(\beta*envdata) * exp(-0.5*\sigma_R^2)
\end{equation}
$\sigma_R$ is the variability of the deviations, so it is in addition to the variance "created" by the environmental effect.  So, as more of the total recruitment variability is explained by the environmental effect, the residual $\sigma_R$ should be decreased.  The model does not do this automatically.

The environmental effect is inherently lognormal.  So when an environmental effect is included in the model, the arithmetic mean recruitment level will be increased above the level predicted by f(SpBio) alone.  The consequences of this have not yet been thoroughly investigated, but there probably should be another bias correction based on the variability of the environmental data as scaled by the estimated linkage parameter, $\beta$.  It is also problematic that the environmental effect time series used as input is assumed to be measured without error.

The preferred approach to including environmental effects on recruitment is not to use the environmental effect in the direct calculation of the expected level of recruitment.  Instead, the environmental data would be used as if it was a survey observation of the recruitment deviation.  This approach is similar to using the environmental index as if it was a survey of age 0 recruitment abundance because by focusing on the fit to the deviations it removes the effect of SpBio on recruitment.  In this alternative, the $\sigma_R$ would not be changed by the environmental data; instead the environmental data would be used to explain some of the total variability represented by $\sigma_R$.  This approach may also allow greater uncertainty in forecasts, as the variability in projected recruitments would reflect both the uncertainty in the environmental observations themselves and the model fit to these observations.

\myparagraph{Initial Age Composition}
If the first year with recruitment deviations is set less than the start year of the model, then these early deviations will modify the initial age composition.  The amount of information on historical recruitment variability certainly will degrade as the model attempts to estimate deviations for older age groups in the initial equilibrium.  So the degree of bias correction is reduced linearly in proportion to age so that the correction disappears when maximum age is reached.  The initial age composition approach normally produces a result that is indistinguishable from a configuration that starts earlier in the time series and estimates a longer time series of recruitments.  However, because the initial equilibrium is calculated from a recruitment level unaffected by spawner-recruitment steepness and initial age composition adjustments are applied after the initial equilibrium is calculated, it is possible that the initial age composition approach will produce a slightly different result than if the time series was started earlier and the deviations were being applied to the recruitment levels predicted from the spawner-recruitment curve.

max_stars_repo_name: nmfs-stock-synthesis/doc

max_issues_repo_name: nmfs-stock-synthesis/ss-documentation

max_forks_repo_name: nmfs-stock-synthesis/ss-documentation


text:
\documentclass[a4paper,titlepage,oneside,12pt]{amsart} %amsart
\usepackage{graphicx}
\usepackage{hyperref}
%\usepackage{geometry} % see geometry.pdf on how to lay out the page. There's lots.
\usepackage[margin=1.3in]{geometry}
\geometry{a4paper} % or letter or a5paper or ... etc
% \geometry{landscape} % rotated page geometry
\usepackage{ifthen}

% See the ``Article customise'' template for come common customisations
\usepackage[usenames,dvipsnames]{color}

\definecolor{lightgray}{RGB}{245, 245, 245}
\definecolor{bkblue}{RGB}{18, 47, 76}
\definecolor{bklightblue}{RGB}{102, 131, 158}
\definecolor{mygreen}{rgb}{0,0.6,0}
\definecolor{orange}{RGB}{255,153,0}

\usepackage{opensans}
\usepackage{setspace}
\usepackage{booktabs} \newcommand{\ra}[1]{\renewcommand{\arraystretch}{#1}}

\usepackage{color}
\newcommand{\todo}[1]{\colorbox{yellow}{#1}}
\newcommand{\toread}[1]{{\color{bklightblue} #1}}

\usepackage{listings}
\lstset{ %
language=C,                % choose the language of the code
basicstyle=\footnotesize,       % the size of the fonts that are used for the code
%numbers=left,                   % where to put the line-numbers
%numberstyle=\footnotesize,      % the size of the fonts that are used for the line-numbers
%stepnumber=1,                   % the step between two line-numbers. If it is 1 each line will be numbered
%numbersep=5pt,                  % how far the line-numbers are from the code
backgroundcolor=\color{lightgray},  % choose the background color. You must add \usepackage{color}
showspaces=false,               % show spaces adding particular underscores
showstringspaces=false,         % underline spaces within strings
showtabs=false,                 % show tabs within strings adding particular underscores
frame=single,           % adds a frame around the code
framerule=0.2pt,
tabsize=2,          % sets default tabsize to 2 spaces
captionpos=b,           % sets the caption-position to bottom
breaklines=true,        % sets automatic line breaking
breakatwhitespace=false,    % sets if automatic breaks should only happen at whitespace
escapeinside={\%*}{*)},          % if you want to add a comment within your code
belowcaptionskip=5em,
belowskip=1em,
aboveskip=1.8em,
commentstyle=\itshape\color{mygreen},
keywordstyle=\bfseries\color{black},
identifierstyle=\color{black},
stringstyle=\color{blue},
morekeywords={*, }
}

\newcommand{\versionNr}{0.1}
\newcommand{\authorMila}{Dr. sc. Milanka Ringwald}
\newcommand{\authorMatthias}{Dr. sc. Matthias Ringwald}
\newcommand{\bkContact}{\href{contact@bluekitchen-gmbh.com}{contact@bluekitchen-gmbh.com}}
\newcommand{\barWidth}{0.3cm}

\makeatletter
\renewcommand{\maketitle}{
  \begin{titlepage}
    \fosfamily
    \begin{center}
    \begin{minipage}[b]{\textwidth}
        \begin{minipage}[b]{.1\textwidth}
            \color{bkblue}\rule{\barWidth{}}{22cm}
        \end{minipage}
        \hfill\begin{minipage}[b]{.8\textwidth}\begin{flushright}
            {\color{bkblue}VERSION \versionNr{} \\
            \today \\}
            \vspace*{7.5cm}
            \hfill\includegraphics[width=0.95\textwidth]{../../../docs/manual/picts/bklogo.pdf}
            \vspace*{1.5cm}
            \begin{spacing}{2}
                {\huge \color{bkblue} \@title} \\
                {\Large \color{bklightblue} Getting Started}
            \end{spacing}
            \vspace*{1.5cm}
            {\color{bkblue}\large \authorMila \\
            \large \authorMatthias \\
            \large \bkContact\\ }
        \end{flushright}\end{minipage}
        \vfill
        \begin{minipage}[b]{\textwidth}
            \color{bklightblue}\rule{\barWidth{}}{\barWidth{}}
        \end{minipage}
    \end{minipage}

    \end{center}
  \end{titlepage}
}
\makeatother

\title[] {BTstack for RugGear/MediaTek Chipsets}
\author{Copyright \copyright  2014 BlueKitchen GmbH}

%%% BEGIN DOCUMENT
\begin{document}

\maketitle

\tableofcontents
\pagebreak

\newcommand{\urlfoot}[2]{\href{#1}{{\color{blue} #2}}\footnote{#1}}
\newcommand{\BTstack}{\urlfoot{http://bluekitchen-gmbh.com/btstack}{BTstack}{}}
\newcommand{\CydiaImpactor}{\urlfoot{http://www.cydiaimpactor.com}{Cydia Impactor}{}}
\newcommand{\CydiaImpactorURL}{\href{http://www.cydiaimpactor.com}{\color{blue} Cydia Impactor}}

\newcommand{\ADT}{\urlfoot{http://developer.android.com/tools/index.html}{Android Developer Tools}{}}
\newcommand{\nio}{\urlfoot{https://www.bluenio.com/products/accessories/niotag}{nio Tag}{}}
\newcommand{\PacketLogger}{\urlfoot{http://adcdownload.apple.com/Developer\_Tools/hardware\_io\_tools\_for\_xcode\_\_june\_2014/hardwareiotools\_june\_2014.dmg}{PacketLogger}{}}
\newcommand{\Wireshark}{\urlfoot{http://www.wireshark.org}{Wireshark}{}}
\newcommand{\Cygwin}{\urlfoot{https://www.cygwin.com}{Cygwin}{}}
\newcommand{\MSYS}{\urlfoot{www.mingw.org/wiki/msys}{MSYS}{}}
\newcommand{\adb}{\urlfoot{http://developer.android.com/tools/help/adb.html}{Android Debug Bridge}{}}

This documents describes how \BTstack{} can be installed and used on RugGear devices with MediaTek chipset. It also presents measurements of the reception of Advertising reports from a remote devices, e.g. beacons or peripherals, as this is the crucial step for discovering and connecting to them.

\section{Hardware Setup}
To install BTstack on a RugGear mobile phone, connect the RugGear device to a Mac or Linux system using a micro USB cable. The installation might also work on Windows with \Cygwin{} and/or \MSYS{} installed. The RugGear device is connected to an USB port during setup and development.

\section{General Tools}

\begin{itemize}
\item \CydiaImpactor{} to get root access.
\item Google's \ADT{} (ADT) to develop an Android LE Client.
\item The \adb{} (adb) to communicate with a connected Android device via a command line. It comes as a part of the Android Developer Tools.
\item Apple's \PacketLogger{} (available to the registered developers as part of the Hardware IO Tools for Xcode download) or \Wireshark{} to look and analyze Bluetooth packet logs.
\item Some LE devices that send Advertising reports to test your LE Client. Here, we used the \nio{} and a BTstack-based LE Peripheral on a desktop machine using the BCM20702A0 module.
\end{itemize}

\section{Rooting the RugGear Device}
There are various ways to root an Android device. We recommend the \CydiaImpactorURL{} tool. It is available for all major platforms, it works with most Android devices and it comes from a trustworthy source\footnote{It was created by Jay Freeman, who has supporting the use iOS devices outside of Apple's walled garden since the device came out}.

To root the device, start Impactor, and press the "Start" button as shown in Fig.\ref{fig:cydiaimpactor}

\begin{figure}[htbp]
\begin{center}
 \includegraphics[width=\textwidth]{picts/cydiaimpactor.png}
\caption{Cydia Impactor running on OS X.}
\label{fig:cydiaimpactor}
\end{center}
\end{figure}

\section{Installing BTstack on RugGear devices with MediaTek Chipsets}

First, extract the provided \path{btstack-android-mtk-VERSION.tar.gz} archive. Please make sure that the path to the extracted archive does not contain spaces as the installer may fail in this case. Then, start the provided \path{./installer.sh} in the \path{mtk} folder. This should look similar to this listing.

\begin{lstlisting}
$ mkdir btstack
$ tar -zxvf btstack-android-mtk.tar.gz -C btstack
$ ls btstack
java	mtk
$ cd btstack/mtk
$ ./installer.sh
BTstack Installer for RugGear/Mediatek devices
from: .
- /system mounted as read/write
- stopping Bluetooth daemon
- transfer files to device
9192 KB/s (279736 bytes in 0.029s)
2949 KB/s (6188 bytes in 0.002s)
7753 KB/s (62360 bytes in 0.007s)
4184 KB/s (11316 bytes in 0.002s)
3201 KB/s (6592 bytes in 0.002s)
5348 KB/s (11720 bytes in 0.002s)
- put files in place
- start BTstack daemon
DONE
\end{lstlisting}

If BTstack was installed properly, we can have a look at its packet log.

\begin{lstlisting}
$ make hci_dump
killall PacketLogger
adb shell su root chmod 666 /data/btstack/hci_dump.pklg
adb pull /data/btstack/hci_dump.pklg 2> /dev/null
open hci_dump.pklg
\end{lstlisting}

The \path{make} \path{hci_dump} command assumes that the underlying system is OS X and that PacketLogger is already running. The two\path{adb} commands, shown in the following Listing, are used to fetch the packet log (hci\_dump.pklg) and it can be run on any platform. Wireshark can then be used to open the packet log.

\begin{lstlisting}
$ adb shell su root chmod 666 /data/btstack/hci_dump.pklg
$ adb pull /data/btstack/hci_dump.pklg 2> /dev/null
\end{lstlisting}

The initial packet log should look like in Figure \ref{fig:firstLog}.

\begin{figure}[htbp]
\begin{center}
 \includegraphics[width=\textwidth]{picts/ruggear_initial_hci_dump.pdf}
\caption{hci\_dump.pklg right after BTstack daemon was installed.}
\label{fig:firstLog}
\end{center}
\end{figure}

\section{Running the First Example}

As first, make sure that BTstack was installed properly and it is running, i.e. by checking the packet log as explained in the previous section. Now, let's do an LE Scan using a test program written in C against libBTstack.

\begin{lstlisting}
$ adb shell
$ le_scan
le_scan started
- connecting to BTstack Daemon
- connected
- send power on
- btstack state 1
- btstack state 2
- start LE scan
- ADV: 3E 0F 02 01 00 01 F2 01 8F 45 16 66 03 02 01 1A B3
\end{lstlisting}

The \path{le\_scan} just dumps the data of each received advertisement. It uses the default parameters used by iOS, which are scan window 30 ms, scan interval 300 ms. More on these parameters is in Section \ref{ss:measurements}. The packet log looks like in Figure \ref{fig:leScan}.

\begin{figure}[htbp]
\begin{center}
 \includegraphics[width=\textwidth]{picts/scan_parameters_hci_dump.png}
\caption{HCI dump of the le\_scan program.}
\label{fig:leScan}
\end{center}
\end{figure}

\section{BTstack Java API}

BTstack on RugGear/MediaTek provides its own Bluetooth stack and its own interface for using it. While BTstack has been certified for Classic SPP and LE Peripheral, it does not provide a complete Java API for this. At the moment, the functionality to turn Bluetooth on/off, scan for LE devices, connect, and make use of Services and Characteristics is provided. This covers the use of BTstack as LE Central. Please note that the Security Manager is not implemented yet. Use of the Security Manager is necessary when devices require explicit pairing before some services can be used.

 The Java classes that make up the BTstack API  are split into three folders. Please add all of them to your Android Java project:

 \begin{enumerate}
\item \path{java/src} - main code for BTstack client, i.e., socket communication with BTstack server that runs as a daemon.
\item \path{java/android} - Android specific Client/Server communication.
\item \path{java/gen} -  code for available commands and events, auto-generated from the BTstack C source.
\end{enumerate}

\subsection{BTstack GATT Client for Android example}
More documentation on the Java API is needed. For now, please have a look at the Anrdoid example in \path{java/example/com/bluekitchen/GATTClientTest.java}. It connects to BTstack Server and turns Bluetooth on. On success, it starts an LE Scan for devices. When it finds a device, it connects to it and queries the available Services. Then, it requests the list of Characteristics for the first service. Finally, it performs some read/write operations on the found Characteristics.

BTstack server runs as a daemon. In the event of a crash, the Java client will get notified and can restart the daemon, to provide a continuous use of the Bluetooth services.

\section{BCM20702A0 and RugGear RG500 Reception of Advertisements}
\label{ss:measurements}

During the first tests of BTstack on RugGear/MediaTek, we have seen that it receives less Advertisements than other devices.

Advertisements serve three main purposes:
\begin{enumerate}
\item They provide information that a particular device is in range and turned on.
\item They can provide some information without connecting to a particular device (e.g. its name, provided services, or even manufacturer specific data).
\item They allow to connect to a particular device, i.e., an LE device listens for incoming connection requests only a short moment after sending an Advertisement (to save energy).
\end{enumerate}

A setup with one device that sends Advertisements and one device that receives them, can be completely described by three parameters:
\begin{enumerate}
\item the \emph{Advertisement Interval} - the period between two consecutive Advertisements being sent.
\item the \emph{Scan Interval} - it determines how frequent the receiving device listens for Advertisements.
\item the \emph{Scan Window} - the time window in which the receiving device listens for Advertisements.
\end{enumerate}

\subsection{Setup} To evaluate the MediaTek Bluetooth chipsets used in the RugGear RG500, we compared them to a common Bluetooth USB Dual-Mode Dongle that uses the Broadcom BCM20702A0. We used two LE Peripherals. As the first LE Peripheral, we setup another device with the BCM20702A0 and configured it to advertise every 30 ms. This is very often, but it helps to establish how good Advertisements are received, if they occur frequently. As a second more real-world example, we used the nio Tag without further configuration. Based on the measured results, the nio Tag advertises roughly every second.

We measured two cases:
\begin{enumerate}
\item continuous scanning (Scan Window 30ms, Scan Interval 30ms),
\item intermittent scanning (Scan Window 30ms, Scan Interval 300ms) as performed by iOS.
\end{enumerate}

\subsection{Process}
For the continuous and intermittent scanning measurements on the RugGear, we used the \path{le_scan} test. We let it run for 15 minutes in continuous, and then 15 min in intermittent scanning setup. For each of the two measurement, we retrieved the packet logs from the device.  We processed it an analyzed it using two Python scripts \path{process_scan.py} and \path{plot_scan.py}. The measurements with the BCM module have been carried out with the GATT Browser example of BTstack on OS. Hence, we have up to four experiments for each setup:
\begin{itemize}
\item BCM/BCM - BCM20702A0 receives Advertisements from second BCM 20702A0 module
\item BCM/nio - BCM20702A0 receives Advertisements from nio tag
\item RugGear/BCM - RugGear RG500 receives Advertisements from BCM 20702A0 module
\item RugGear/nio - RugGear RG500 receives Advertisements from nio tag
\end{itemize}

\subsection{Measurements with continuous scanning}
For this experiment with set the Scan Interval to 30 ms and the Scan Windows to 30 ms, which translates to continuous scanning.

The plot in Figure \ref{fig:accumulatedAds} shows how many Advertisements have been received for both receivers from the two senders. In the BCM/BCM combination, 27 out of max 33 (1s /30 ms) Advertisements have been received. On the RugGear device, only about 1 in 15 Advertisements have been received.

Figure \ref{fig:delayHist} shows the distribution of the time between two received Advertisements over the full range.

All setups but the RugGear vs. nio Tag, received an Advertisement every second, which is sufficient for most interactive applications. We further analyzed the RugGear vs. nio Tag setup in more detail. For this setup, we calculated the expected delay between the start of a scan and the first received Advertisement based on the previous measurements as shown in Figure \ref{fig:expectedDelay}. An alternative and easier to read representation of the same is given in Figure \ref{fig:cdfExpectedDelay}. From this Figure we can, for example, see that we have 20 percent probability of receiving an Advertisement with less then 1 second.

\subsection{Measurements with normal scanning}
For this experiment with set the Scan Interval to 300 ms and the Scan Windows to 30 ms, which translates to scanning for 1/10 of the time. As the scanning time is reduced by a factor of 10, we also expect the number of received Advertisements to be lower by 1/10. We didn't had the nio Tag around this time.

The plot in Figure \ref{fig:accumulatedNormalAds} shows the number of Advertisements received for both receivers. The BCM/BCM received 2.9 Advertisements per second (adv/s) which is roughly 1/10 of the 27 adv/s received in the continuous scanning experiment. For the RugGear/BCM combination, we received 0.6 adv/s, which is roughly 1/3 of the 1.8 adv/s received in the continuous scanning experiment and is unexpected.

We conclude from this data, that the MediaTek chipset didn't do continuous scanning in the first experiment. Instead, it looks like it was scanning for only 1/3 of the time, potentially due to internal resource limitations or scheduling problems. In the intermittent scanning setup, the RugGear device received 1/5 of the Advertisements received by the BCM chipset.

		\begin{figure}[htbp]
		\begin{center}
		 \includegraphics[width=0.9\textwidth]{picts_experiments/nio_acc_number_of_advertisements_continuous_scanning.pdf}
		\caption{Advertising reports accumulated over time, continuous scanning.}
		\label{fig:accumulatedAds}
		\end{center}
		\end{figure}

		\begin{figure}[htbp]
		\begin{center}
		 \includegraphics[width=0.9\textwidth]{picts_experiments/nio_histogram_advertisements_time_delay.pdf}
		\caption{Time delay histogram,  continuous scanning.}
		\label{fig:delayHist}
		\end{center}
		\end{figure}

		\begin{figure}[htbp]
		\begin{center}
		 \includegraphics[width=0.9\textwidth]{picts_experiments/nio_ruggear_expected_scan_response.pdf}
		\caption{Expected time until first Advertisement, continuous scanning.}
		\label{fig:expectedDelay}
		\end{center}
		\end{figure}

		\begin{figure}[htbp]
		\begin{center}
		 \includegraphics[width=0.9\textwidth]{picts_experiments/nio_ruggear_cdf.pdf}
		\caption{Cumulative distribution of expected time until first Advertisement, continuous scanning.}
		\label{fig:cdfExpectedDelay}
		\end{center}
		\end{figure}

		\begin{figure}[htbp]
		\begin{center}
		 \includegraphics[width=0.9\textwidth]{picts_experiments/nio_acc_number_of_advertisements_normal_scanning.pdf}
		\caption{Advertising reports accumulated over time, normal scanning.}
		\label{fig:accumulatedNormalAds}
		\end{center}
		\end{figure}

%\end{minipage}

\end{document}


text:
\documentclass[11pt,a4paper]{article}

%\usepackage[a4paper,left=35mm,right=30mm,top=30mm,bottom=30mm]{geometry}
\usepackage[utf8x]{inputenc}
\usepackage[english]{babel}
\usepackage{amsmath}
\usepackage{graphicx}
\usepackage{url}
\usepackage{booktabs}
\usepackage{colortbl}
\usepackage{xcolor}
\usepackage{array}
\usepackage{listings}
\usepackage{hyperref}
\usepackage{longtable}
\usepackage{placeins}
\usepackage[T1]{fontenc}
\usepackage{epstopdf}

\parindent 0pt

\newcommand{\changefont}[3]{
\fontfamily{#1} \fontseries{#2} \fontshape{#3} \selectfont}

\newcommand*{\todo}[1]{\textcolor{red}{[TODO: #1]}}
\newcommand*{\code}[1]{\lstinline|#1|}

\hypersetup{pdftex=true, colorlinks=true, breaklinks=true,linkcolor=black,citecolor=black}

	% Floatpage stuff
    \renewcommand{\topfraction}{0.9}	% max fraction of floats at top
    \renewcommand{\bottomfraction}{0.8}	% max fraction of floats at bottom
    %   Parameters for TEXT pages (not float pages):
    \setcounter{topnumber}{2}
    \setcounter{bottomnumber}{2}
    \setcounter{totalnumber}{4}     % 2 may work better
    \setcounter{dbltopnumber}{2}    % for 2-column pages
    \renewcommand{\dbltopfraction}{0.9}	% fit big float above 2-col. text
    \renewcommand{\textfraction}{0.2}	% allow minimal text w. figs
    %   Parameters for FLOAT pages (not text pages):
    \renewcommand{\floatpagefraction}{0.7}	% require fuller float pages
	% N.B.: floatpagefraction MUST be less than topfraction !!
    \renewcommand{\dblfloatpagefraction}{0.7}	% require fuller float pages

\begin{document}
\changefont{pbk}{m}{n}

\title{Documentation: \\ -------------------------------- \\ BuriTrack \\ --- \\ CeTrAn}
\date{\today}
\maketitle
\begin{center}
\begin{figure}[h]
	\centerline{
    	\mbox{\includegraphics[width=0.5\textwidth]{figures/occupancy_plot.eps}}
  	\label{fig:title}
	}
 \end{figure}
\parskip 1cm
Project Homepage: \\
\url{http://sourceforge.net/projects/buridan/} \\
Project video:\\
\url{http://www.youtube.com/watch?feature=player_detailpage&v=YwGUlgiGcg4}
\end{center}

\thispagestyle{empty}
\newpage

\tableofcontents

\newpage

\begin{abstract}
This freeware package offers the tools to track a fly (buritrack) in the Buridan's assay and to analyse the recorded trajectories with different statistical methods (CeTrAn). The tracker may use a live picture stream from a video camera or pre-recorded videos. Since the analysis tools are written in R, they can easily be edited and customised to a user's specific needs. Furthermore, the analysis tools presently offer analyses of single flies as well as comparative analyses between groups of flies.

Please refer to the scientific paper you will find with your download for scientific question and a better explanation of the analysis.
\end{abstract}

\section{BuriTrack}

\begin{figure}[h]
    	\mbox{\includegraphics[width=0.99\textwidth]{figures/tracker_mainscreen.eps}}
 	\caption{The main window of BuriTrack.}
  	\label{fig:mainscreen}
 \end{figure}

\subsection{Installation}

\begin{enumerate}
\item Download the tracker from the sourceforge website. Built versions of the tracker are available for Windows and OSX.
\item Unzip the file.
\item Copy the folder to your preferred location on your filesystem.
\item Run the executable.
\end{enumerate}

\subsection{Compiling from source}

\subsubsection{Windows}

\begin{enumerate}
\item Install the latest versions of QT and Qt Creator: \\ \url{http://qt.nokia.com/products/developer-tools/}
\item Install the latest versions of OpenCV. We recommend MinGW (Minimalist GNU for Windows) to compile the OpenCV source \\ \url{http://opencv.willowgarage.com/wiki/} \\
Help provided by Willowgarage can be found here: \\
\url{http://opencv.willowgarage.com/wiki/InstallGuide}
\item Edit the {\bf .pro} file to set your path variables.
\end{enumerate}

\subsubsection{OSX}

This section describes the basic steps of how to compile {\it Buridan} using Qt Creator on Mac OS X. These instructions can be easily generalised to other UNIX- or Linux-based systems.

\begin{enumerate}
\item We recommend to install the latest versions of QT and Qt Creator: \\ \url{http://qt.nokia.com/products/developer-tools/}
\item Compile the latest version of OpenCV. We recommend using MacPorts (an easy to use system for compiling, installing, and managing open source software) to install OpenCV \\ \url{http://www.macports.org/}
\item Edit the {\bf .pro} file to set your path variables.
\end{enumerate}

\subsubsection{Linux}

Under construction.

\subsection{Getting started}

\begin{enumerate}
\item Load a video or capture from a webcam by clicking on \\
Main->"New Video Capture". \\
The contrast and luminosity of your camera may need to be adjusted, such that the arena is visible.
\item Set the camera ROI (Region Of Interest) by clicking on the button.
\item Press the Button "New Tracking" and adjust all the parameters in the Tracking dialog. While setting the platform position left-click on three points on the platform edge. Check that the drawn circle fits with the platform, if not you can right-click on the mouse to erase one point (one per click).
\item Put a fly in the arena, you may want to adjust the luminosity of your camera again, such that the platform become nearly invisible. Click on "Activate Tracking".
\end{enumerate}

To start a new tracking before the end of the experiment, deactivate the tracker by clicking "Activate Tracking" again and press the button "New Tracking". If the fly jumps off of the platform, the tracker stops and plays a sound alarming the experimenter. Put the fly back on the platform using a brush and click "Activate Tracking" again to continue with the experiment.

Once the experiment is over, you can simply start a new one by clicking the  "New Tracking" button. Note that you should either wash the platform or rotate it between experiments in order to control for  any chemical cues the flies might have left on the platform.

\subsection{Troubleshooting}

Should you get an address exception error, when starting the program, we recommend installing the Microsoft Visual C++ 2010 Redistributable Package. \\ \url{http://www.microsoft.com/download/en/details.aspx?id=8328}

Regarding any other issues you may encounter, please use the sourceforge project website \\
\url{http://sourceforge.net/projects/buridan/support} \\
or alternatively you can email {\bf jwessnit@users.sf.net}.

\newpage
\section{CeTrAn}

\begin{figure}[h]
    	\mbox{\includegraphics[width=0.99\textwidth]{figures/analysis_trajviewer.eps}}
 	\caption{The graphical user interface of CeTrAn.}
  	\label{fig:CeTrAn}
 \end{figure}

\subsection{Installation}

Tested version: install an up to date versions
\begin{enumerate}
\item Download and install the latest version of R (was tested with R3.0.0): \\
\url{http://www.r-project.org/}
\item Download and install the Rggrunner \\ \url{http://rgg.r-forge.r-project.org/downloads.html}. \\  Detailed instructions can be found here: \\
\url{http://rgg.r-forge.r-project.org/gettingstarted.html})
\item Start R GUI (Windows: start the R.exe, Linux: type "R" in console), open the file in the installation folder "install\_packages.r", and run the code.

\end{enumerate}
Should be easy and fast, but I haven't tested it yet and the installer present are for the windows version only.
\begin{enumerate}
\item Install R and the rggrunner (windows version of the installers are in the "`installation"' folder): \\

\item Copy the "`R"' folder into your document folder (windows) or your /library folder (mac) \\

\item Do NOT run the "install\_packages.r" code or update the packages.

\end{enumerate}

On Linux systems you need to install the dev packets of libxml2 first.
(more information here: \\ \url{http://cran.r-project.org/web/packages/XML/index.html})

\subsection{Getting started with data from Buritrack}

\begin{enumerate}
\item Start the Rggrunner (in windows start: <rgg\_directory>/bin/rggrunner.exe)

\item Click "`Open RGG"' and load the CeTrAn/CeTrAn\_fromxml\_4.rgg

\item Follow the instructions of the GUI. You have to choose the folder containing the data, the {\bf .txt} file linking the data with group names, and the output folder. The name of your output can be changed using the top entry field.
You can then choose which analysis you want to do, in particular you can choose if you want to have the single fly analysis or not. If you get error messages, try to do the analysis without the PCA which is the least stable code. Some limit value has to be given at the bottom: this will be used as y limit value to draw the graphs.

\item Press the green arrow in the toolbar to execute the script.

\end{enumerate}

As stated above, you need a {\bf.txt} file with two tab separated columns. The first column contains the XML filenames of the data files, the second column contains a string which represents the group the file belongs to. You can load the file via the "Browse" button found underneath the matrix box.

\medskip

This is an example of what your file should contain:

\begin{lstlisting}
--------------
tbh1.xml	tbh
tbh2.xml	tbh
wt+1.xml	wt+
wt+2.xml	wt+
--------------
\end{lstlisting}

NB: you can also get data that is stored in different folders by choosing the folder containing the data
as the parent folder, and adding the subfolder to the data name, as in this example:

\begin{lstlisting}
--------------
nostripe/cs_1.xml	nostripe_cs
withstripes/cs_1.xml	stripe_cs
--------------
\end{lstlisting}

\subsection{CeTrAn with other data}

This is still in development. Some scripts in the "`other\_codes"' folder may help you to modify your data such that CeTrAn can use it, you then need to use the CeTrAn\_import\_4.rgg file. The data should be in 4 columns: time in seconds, x coordinate in mm, y coordinate in mm, burst.

The way the metadata should be is still work in progress. The minimum is the path to the data, a group entry and a time stamp in this format: YYYY-MM-DD HH:MM:SS
More to come, we hope.

\subsection{Function list (not exhaustive)}

What follows is a brief outline of functions and metrics that are calculated by the CeTrAn package.

Please refer also to the PlosOne paper. The manuscript can be found in the documentation. More detailed descriptions can be found there.

{\bf IMPORTANT:} The package contains a number of functions to analyse the trajectorie files. The first step is always to load and interpolate the trajectorie of the flies in a trajectory with a regular time difference of 100 ms (10 Hz) between all relocations. Movement smaller than the threshold value given in the GUI are eliminated.

\subsubsection{Individual test}
\label{sec:individualTest}

In the individual test pdf output, the trajectory of each fly in drawn. The color of the path changes after each walk, which eases the visualisation of the path. A histogram of the frequency of speed is also drawn on a logarithmic scale on the x axis. The next plot shows the speed over time. Next, the relative angle over time is shown where the color of the point represent the speed at that moment (also represented at the bottom with the same color code: black is slow, green is very fast.) The next histograms are self explanatory while the last one represents the absolute turning angle in red, and the absolute meander in green.

\subsubsection{Speed}

The speed is only measured when the fly is moving, which means if $|\Delta x| + |\Delta y| > 0 $. If the speed between two relocations is higher than 50 mm/s, it is assumed the fly jumped and the speed is disregarded from the median of speed calculation.

\subsubsection{Stripe deviation}

For the stripe deviation, the absolute angle of every relocation is read. For each position of the fly, we calculate the direction of the vector pointing from the fly's position towards all the black stripes.

If we take the angular difference between the fly's heading angle and the direction of the vectors pointing towards the stripes, we get the deviation from the middlepoints of the black stripes. Now we just find the stripe with the smallest deviation for each point and plot it in a histogram. This plot is not returned, the median value is returned for each fly.

\subsubsection{Activity}

For now, please refer to the paper.

\subsubsection{Turning angle}

For now, please refer to the paper.

\subsubsection{Calculation of the walks between the stripes}

For each stripe, we calculate a 2D plane (straight line) orthogonal to the vector between the arena middlepoint and the stripe position. The plane lies between the arena-middlepoint and the arena border (We took a distance of 0.8*arena-radius). Whenever the fly leaves the area defined by the transecting plane and arena border, the walk is started, if it passes any other plane, the walk is completed. The walks are stored together with the time and walk distance between passing the planes.

\subsubsection{Transition plot}

The transition plot is done with the {\it hexbin} package. The Arena is divided into 60*60 hexagons. The fly's current position raises the count of its corresponding hexagon by one. The matrix is smoothed with a Gaussian kernel and then plotted. You can untipped one box if you want all data to be taken into account, the default is to use position point only if the fly was moving at that time, such that long stays do not appear in the plot.

The scale starts at 0 (blue) and goes up till a value calculated by the 95\%-quantile of the count-distribution (red). This scale makes small differences clearly visible and leaves only a few spots (5\%), which are above the scale.

\subsection{Troubleshooting}

Regarding any other issues you may encounter, please use the sourceforge project website \\
\url{http://sourceforge.net/projects/buridan/support} \\
or alternatively you can email {\bf thrawny@users.sf.net}.

\newpage

\section{Buridan's assay}
On the next pages, we provide drawings by Reinhard Wolf for the Buridan's arena. We hope to provide better blueprints in the future.

\begin{figure}[h]
    	\mbox{\includegraphics[width=0.99\textwidth]{figures/Buridan_assay-01.eps}}
 	\caption{....}
  	\label{fig:buridan-01}
 \end{figure}

\begin{figure}[h]
    	\mbox{\includegraphics[width=0.99\textwidth]{figures/Buridan_assay-02.eps}}
 	\caption{....}
  	\label{fig:buridan-02}
 \end{figure}

 \begin{figure}[h]
    	\mbox{\includegraphics[width=0.99\textwidth]{figures/Buridan_assay-03.eps}}
 	\caption{....}
  	\label{fig:buridan-03}
 \end{figure}

 \begin{figure}[h]
    	\mbox{\includegraphics[width=0.9\textwidth]{figures/Buridan_assay-04.eps}}
 	\caption{....}
  	\label{fig:buridan-04}
 \end{figure}

\end{document}

max_stars_repo_name: brembslab/CeTrAn

max_issues_repo_name: brembslab/CeTrAn

max_forks_repo_name: brembslab/CeTrAn


text:
\subsection{Other}

masks in bitwise operations. take only desired part by doing and operation with mask

setting values. or operator with target values if want to set to 1.
what if want to set 0? invert map and use and. or just use xor

hexidecimal
4 bits

2**4 is 16

use 0 to 15, 0 to f

shift left is x2
shift right is /2

max_stars_repo_name: adamdboult/nodeHomePage

max_issues_repo_name: adamdboult/nodeHomePage

max_forks_repo_name: adamdboult/nodeHomePage


text:
\section{Acknowledgments}

We would like to thank Bart Botta, Jan Moringen, John Mercouris, and
Alastair Bridgewater for providing valuable feedback on early versions
of this paper.

max_stars_repo_name: gwerbin/SICL

max_issues_repo_name: gwerbin/SICL

max_forks_repo_name: gwerbin/SICL