\documentclass[12pt]{article}

\usepackage{natbib,amsfonts,graphics,amsmath}
\usepackage{graphicx}

\include{newcommands}

\begin{document}

	\title{The Froude number in stratified flow above topography}

	\author{Eric Mayer and Oliver Fringer}

	\maketitle

	\section{Abstract}

	There is a debate in the literature of stratified flows above topography over the correct dimensionless number to refer to as a Froude number. Common candidates include $U/ND$, $U/Nh_0$, and $Uk/N$.
%	where $U$ is the background horizontal velocity, $N$ the background buoyancy frequency, $D$ the background depth, $h_0$ the maximum height of the topography, and $k$ a characteristic wave number of the topography.
	Additionally, one can use the perturbation quantities $u_0$, $g'$, and $\delta$, to define an `internal' or `layer' Froude number $Fr_{\delta}=u_0/\sqrt{g'\delta}$. ~\citep{Rossby1951,Winters2012}.

	In this paper, we nondimensionalize the 2D boussinesq equations describing the flow of infinitly deep fluid over topography to determine a scaling relationship between inner and outer quantities. Our scaling shows that, although it looks like an inverse Froude number, $Nh_0/U$ is in fact the square of the internal Froude number, $Fr_{\delta}^2=\frac{u_0^2}{g'\delta}$.

	\section{Introduction}

	In its most generally accepted use, the Froude number represents a ratio of the speed with which two processes,  advection and wave propagation, carry information of a disturbance throughout a system. In the simple case of homogenous open channel flow, the Froude number is given by $Fr=q/\sqrt{gd}$, where $q$ is the  local depth-averaged velocity, $d$ is the local depth, and $g$ is the acceleration of gravity.

	In the case of stratified flow with a finite depth, $D$, over a ridge of height, $h_0$, and width, $2\pi/k$, with uniform upstream velocity, $U$, and buoyancy frequency $N^2=-\frac{g}{\rho_0}\D{\bar{\rho}}{z}$ (see sketch), one can form three dimensionless numbers that resemble the Froude number, $U/ND$, $U/Nh_0$, and $Uk/N$. However, not all of these numbers represent a ratio of advection to wave propagation, and thus calling all of these parameters Froude numbers robs the concept of its intuitive dynamic significance. In his seminal text on stratified flow over topography, Baines proposed that, as a solution to this ``Froude for everything syndrome,'' the literature should only refer to the most obvious extension of open channel flow as a Froude number; that is,  $Fr=U/ND$, where $ND$ is the speed of the first mode (fastest) internal gravity wave \citep{Baines1995}.

	For oceanic flows away from continents or mid-ocean ridges, however, $Fr=U/ND$ is often very small. For example, in the Drake Passage region of the Antarctic Circumpolar Current, where lee waves are predicted to be dynamically important, typical values for dimensional quantities are $U \approx 0.1$~m~s$^{-1}$, $N \approx 10^-3$~rad~s$^{-1}$, and $D \approx 4000$~m, giving $U/ND \approx 0.025$ \citep{Nikurashin2010a}. In these systems, the dynamics are captured better by considering the case of an infinitely deep ocean (e.g. \cite{Long1953}), for which solutions describe a stationary wave above the ridge, with energy propagating upwards to infinity.

	In this system, the dimensionless number of primary dynamical significance is $Nh_0/U$, which has various names in the literature. Miles refers to it as the Russel number, $Ru$, after the fluid mechanician John Scott Russel, who described the reduction in drag on a shipping vessels when propelled faster than the shallow water wave speed $\sqrt{gd}$ ~\citep{Miles1969}.
%	~\footnote{ In defense of the Russel number, the dynamics of this phenomenon are more closely related to the modern conception of the Froude number than are the dynamics of the system that Froude himself considered, where the length scale was the length of the ship rather than the depth of the channel ~\citep{Baines1995}. However, rectifying history so dramatically might cause more confusion than it is worth.}
	 Aguilar and Sutherland refer to it as the Long number, $Lo$, in honor of Robert Long's pioneering work on the lee wave problem \citep{Aguilar2006a,Long1953}. Nikurashin and Ferrari refer to it as a steepness parameter and use the symbol $\epsilon$, after showing that in the hydrostatic limit, it is identical to the ratio of topographic slope to wave ray slope, an important parameter in the internal tides literature \citep{Nikurashin2010a}. And predictably, much of the literature simply refers to $Nh_0/U$ an inverse Froude number \citep{Laprise1989,Legg2008a,Klymak2010,Eckermann2010,Winters2012}. By nondimensionalizing the equations describing this flow, we will show that regardless of its name,  $Nh_0/U$ is in fact the square of the internal Froude number, $Fr_{\delta}=u_0/\sqrt{g'\delta}$.

	This relation, however, breaks down if height of the topography is greater than the wavelength of the internal gravity wave, $N/U$, at which point the flow becomes hydraulically controlled, with the internal Froude number held constant at 1 \citep{Winters2012}. Thereafter, $Nh_0/U$ informs instead the degree of blocking. It is as if these hills larger than a buoyancy wavelength have squeezed all the juice out of the upstream stratified flow. Hence we term this square of an internal Froude number $J$ for Juice.

	\section{Nondimensional equations} \label{eq:equations}

	\begin{figure}
		\centering
		\includegraphics[width=1\textwidth]{system_sketch.png}
		\caption{Sketch of the system. Streamlines generated using the iterative solution to Long's model over a Witch of Agnesi as described in ~\cite{Laprise1989}, with $J=0.8$ and $\epsilon=0.1$. }
	\end{figure}

	The two-dimensional flow of an unbounded fluid over an isolated hill of height, $h_0$, and width, $2\pi/k$ is characterized by the dimensional quantities
	$U$, $k$, $N$, and $h_0$, where $U$ and $N$ are the constant horizontal velocity and buoyancy upstream of the hill. Choosing $U$ and $N$ to nondimensionalize $k$ and $h_0$, the governing
	nondimensional parameters are $J = N h_0/U$ and $\epsilon = k U/N$.

	Let $\ub_{\mbox{total}} = U {\bf e}_x + \ub'$, $\rho_{\mbox{total}} = \rhobar(z) + \rho'$, and
	$p_{\mbox{total}} = \rho_0 \overline{p}(z) + \rho_0 p'$, where the prime indicates a perturbation of the field from its background state. This notation permits a rigorous separation of external (background) quantities from internal (perturbation) quantities.
	Making the Boussinesq approximation, the steady momentum and density transport equations are given by
	\begin{eqnarray*}
	U \D{u'}{x} + \ub'\cdot\nabla u' &=& -\D{p'}{x}\,,\\
	U \D{w'}{x} + \ub'\cdot\nabla w' &=& -\D{p'}{z} - \frac{\rho'}{\rho_0} g\,,\\
	U \D{\rho'}{x} + \ub'\cdot\nabla\rho' &=& \frac{\rho_0 N^2}{g} w\,,
	\end{eqnarray*}
	where $N^2 = -g/\rho_0 \partial\rhobar/\partial z$, subject to continuity $\nabla\cdot\ub'=0$, and
	the kinematic bottom boundary condition
	\[
	U\D{h}{x} + u' \D{h}{x} = w'\,.
	\]
	Nondimensionalize with the internal quantities
	\begin{eqnarray*}
		u' &=& u_0 u^*\,,\\
		w' &=& w_0 w^*\,,\\
		\rho' &=& R \rho^*\,,\\
		p' &=& P p^*\,,\\
		x &=& k^{-1} x^*\,,\\
		z &=& \delta z^*\,.
	\end{eqnarray*}
	Nondimensionalizing the kinematic bottom boundary condition gives
	(omitting the $*$ on nondimensional variables)
	\[
	k U h_0 \D{h}{x} + k u_0 h_0 \D{h}{x} = w_0 w\,.
	\]
	If we require a balance between the linear terms, this implies $w_0 = k h_0 U$, giving
	\[
	\D{h}{x} + \frac{u_0}{U} \D{h}{x} = w\,.
	\]
	Now, the vertical scale of the flow as given by $\delta$ is not the
	same as the hill height $h_0$, since $\delta$ must be finite as $h_0\to 0$ (the linear limit). The
	vertical scale is thus dictated by continuity, which requires
	\[
	k u_0 \D{u}{x} + \frac{w_0}{\delta} \D{w}{z} = 0\,,
	\]
	or, since this implies $k u_0 = w_0/\delta$, then we must have $\delta = w_0/(k u_0) = k h_0 U/(k u_0) = h_0U/u_0$.
	Nondimensionalizing the $x$-momentum equation gives
	\begin{eqnarray*}
	k u_0 U \D{u}{x} + k u_0^2\ub\cdot\nabla u  &=& -k P \D{p}{x}\,.
	\end{eqnarray*}
	If we require a leading-order balance between the pressure gradient and the linear momentum advection term,
	we must have $P = u_0 U$, which gives
	\begin{eqnarray*}
	\D{u}{x} + \frac{u_0}{U} \ub\cdot\nabla u &=& -\D{p}{x}\,.
	\end{eqnarray*}
	The equation for the nondimensional density transport given by
	\[
	k U R \D{\rho}{x} + k u_0 R \ub\cdot\nabla\rho = \frac{k \rho_0 h_0 N^2 U}{g} w\,.
	\]
	If we require a balance between the linear advection terms, then the scale for the density
	perturbation is
	\[
	R = \frac{\rho_0 N^2 h_0}{g}\,,
	\]
	so that the nondimensional density equation is
	\[
	\D{\rho}{x} + \frac{u_0}{U} \ub\cdot\nabla\rho = w\,.
	\]
	Nondimensionalizing the vertical momentum equation, we have
	\[
	k^2 h_0 U^2 \D{w}{x} + k^2 h_0 u_0^2\ub\cdot\nabla w = -\frac{P}{\delta}\D{p}{z} - \frac{g R}{\rho_0} \rho\,.
	\]
	If we require a vertical hydrostatic balance to leading order, then we must have
	\[
	\frac{P}{\delta} = \frac{g R}{\rho_0}
	= N^2 h_0\,,
	\]
	and
	\[
	P = \delta N^2h_0
	= \frac{N^2h_0^2U}{u_0}.
	\]
	%\[
	%P = \frac{g R \delta}{\rho_0}
	%  = \frac{g}{\rho_0} \frac{\rho_0 N^2 h_0}{g} \frac{h_0}{F}
	%  = \frac{g}{\rho_0} \frac{\rho_0 N^2 h_0}{g} \frac{U}{N}
	%  = U N h_0\,.
	%\]
	which gives
	\[
	\epsilon^2 \left(\D{w}{x} + \frac{u_0}{U}\ub\cdot\nabla w\right) = -\D{p}{z} - \rho\,,
	\]
	where
	\[
	\epsilon = \frac{Uk}{N}
	\]
	is the nonhydrostatic parameter, and represents a ratio of the frequency with which the flow over the hill excites a wave, $Uk$, to the frequency of the buoyant response, $N$. A propagating wave is only possible if the excitation frequency is smaller than the buoyancy frequency ($\epsilon<1$). In other words, for the perturbation from flow over a hill to result in oscillations that buoyancy can carry away from the hill, it must allow buoyancy enough time to oscillate. Within this propagating regime, one can also think of $\epsilon$ as a ratio of the wavelength of the wave to the width of the hill. For waves much smaller than the hill is long ($\epsilon<<1$), the wave is approximately hydrostatic and the group velocity of the wave (in the reference frame of the hill) is oriented vertically.

	Now, returning to the pressure, since from the vertical momentum equation we
	require $P = N^2h_0^2U u_0^{-1}$ and from the horizontal momentum equation we require $P = u_0 U$, then equating the
	two implies that $u_0 = N h_0$ and thus
	\[
	\frac{u_0}{U} = \frac{N h_0}{U} \equiv J\,.
	\]
	Therefore, in terms of $J$, the governing nondimensional equations are given by
	\begin{eqnarray*}
		\D{u}{x} + J\ub\cdot\nabla u &=& -\D{p}{x}\,,\\
		\epsilon^2 \left(\D{w}{x} + J\ub\cdot\nabla w\right) &=& -\D{p}{z} - \rho\,,\\
		\D{\rho}{x} + J \ub\cdot\nabla\rho &=& w\,,
	\end{eqnarray*}
	subject to $\nabla\cdot\ub=0$ and the kinematic bottom boundary condition
	\[
	\left(1 + J \right)\D{h}{x} = w\,.
	\]
	These nondimensional equations are consistent with the original nondimensionalization which implied
	that the problem is uniquely characterized by $\epsilon$ and $J$.
	The relevant scales (nondimensionalized by $N$ and $U$) are given by
	\begin{eqnarray*}
		\frac{u_0}{U} &=& J\,,\\
		\frac{w_0}{U} &=& \epsilon J\,,\\
		\frac{gR}{\rho_0 U N} &=& J\,,\\
		\frac{P}{U^2} &=& J\,,\\
		\frac{\delta N}{U} &=& 1\,.
	\end{eqnarray*}
	If we define the internal Froude number as
	$Fr_\delta = u_0/\sqrt{g' \delta}$, where $g'\delta =g (R/\rho_0) \delta = J U^2$, this gives
	$Fr_{\delta} = J^{1/2}$. Thus although it looks like an inverse Froude number when expressed in external variables, this scaling shows that it is
	in fact appropriate to refer to $J$ as the square of an internal Froude number.

	\section{Discussion}

	That the outer and inner variable representations of $J$ should present velocity and gravity inversely results from the fact that the wavelength of the internal gravity wave is determined exclusively from the upstream quantities of the flow, $U$ and $N$. Dynamically, this is analogous to case of a simple pendulum, where the period of oscillation is set by the force of gravity and the length of the string, and is oblivious to the magnitude of the displacement that sets it swinging.  On the other hand, all other internal quantites in the flow scale with the ratio of the hill height to this wavelength, that is, with $J$. Thus in comparing ratios of internal advection to wave speed, the height of the hill enters linearly into the perturbation velocity, but only as a half-power in the wave speed. That is, $u_0=JU$ while $\sqrt{g'\delta} = J^{1/2} U$.

	That $J$ is the square of the internal Froude number begs for an energetic interpretation of the dynamics. Borrowing from the theory of homogenous open channel flow, a flow with a set amount of energy can conceivably partition its energy into a spectrum of configurations from entirely potential ($Fr=0$) to almost entirely kinetic ($Fr \to \infty$). However, the volume flux of the flow, $Q=qd$, is not constant over this spectrum, as clearly a system with all potential energy has no flux (velocity), and a system with all kinetic energy has no volume (depth). Rather, for a given energy, the flow achieves its maximum volume flux when $Fr=1$. Similarly, our scaling shows that the perturbation volume flux, $u_0\delta$, increases with $J$ from 0 when $h_0=0$ to $U^2/N$ when $h_0=U/N$.

	From the literature, however, it is clear that this the flow cannot physically sustain this maximal volume flux. A precondition on the wave solution to the flow is that it remain stable to both convective and shear instabilities ~\citep{Long1953,Miles1961}. Assymptotic and fully nonlinear solutions for the streamlines of the flow using Long's model ~\citep{Long1953} show both vertical streamlines (convective instability) and Richardson numbers smaller than 0.25 (shear instability) developing before $J$=1 for flow over a various ridge shapes (see, for example, ~\cite{Miles1969,Smith1977,Laprise1989}). Even our scaling suggests that shear instability should set in by the time $J=2$, since a reversal of flow occurs twice per wavelength, and thus $Ri\approx\frac{2g'/\delta}{(2u_0/\delta)^2}=\frac{1}{2J}$. For this reason, $J$ is generally interpreted as a nonlinearity parameter rather than the square of the internal Froude number ~\citep{Miles1969,Baines1995,Aguilar2006,Nikurashin2010a,Eckermann2010}.

%	Conceptually, we can picture a column of water headed for an isolated hill. As it approaches the hill, it enters the wave field, and the lowest elements are lifted in preparation for a race across the crest. The height of this lift must be enough to overtop the hill, and scales with $h_0$. Then buoyancy acts on these lifted parcels, translating the wave's potential energy into kinetic energy. This is the source of the perturbation velocity over the hill, as indicated by the scaling $u_0=JU=Nh_0$.  This lift is also the source of the perturbation to the density field, and thus the reduced gravity that the background velocity must work against to generate the wave also scales with $h_0$. We see this in the scaling $g'=g (R/\rho_0)=JUN=N^2h_0$. However, the length scale of this work against gravity is the wavelength, $\delta$, which is oblivious to $h_0$.

	Indeed, the identification of $J$ with the internal Froude number squared appears to have gone almost without notice the literature. However, an inquiry into the upper limit of this relationship recently emerged from consideration of blocked flow past a half cylinder \citep{Winters2012}. In the blocked regime, that is, for flow in which $J>O(1)$, the lowest fluid elements upstream of the obstacle lack sufficient kinetic energy to overtop the obstacle, and thus form a pool of stagnant fluid at the obstacle's base \citep{Baines1995}. As a result, the obstacle takes on the apparent height to the unblocked flow of U/N, that is, exactly the height of the flow's kinetic hill-climbing capacity, giving $J_{unblocked}=1$. In this case, Winter's and Armi show that the $Fr_{\delta}=1$ at the crest of the hill and, in analogy to hydraulic control of an unstratified river, the flow of the layer defined by the streamline that passes one wavelength above the crest of the hill exhibits a transition from subcritical flow upstream to a supercritical jet downstream followed by a dissipative hydraulic jump.

	In other words, the relation between $J$ and $Fr_{\delta}$ holds only up to $J=O(1)$. Below this limit, waves accommodate the disturbance of the hill adiabatically, and carry it away from the site of generation, just as in an unstratified river flowing over a sub-critical sill. As $J$ approaches $O(1)$, the advective component of the perturbation plays a more significant role, until the perturbation volume flux above the hill reaches the maximum value that the system can energetically support. All of this squares with the dynamical significance of a Froude number. Above this limit, however, the instabilities brought on by too great a perturbation velocity restabilize the system such that the jet flowing above the hill is under hydraulic control, $Fr_{\delta}^2$=1, and $J$ informs the depth of the stagnant layer upstream as well dissipative and mixing effects of the jump downstream \citep{Winters2012}.

	In this sense, the upstream characteristics of the flow present the system with a wave making capacity, and it is up top the hill to squeeze the wave into existence. But there is only so much juice in the fruit.

\section{Appendix: Rotation}
Including rotation in the nondimensional equations requires only slight modification. Because rotational effects necessarily involve a spanwise direction, we must now include an equation for the spanwise momentum.

We begin by aligning the $x$-direction with lines of latitude, and posit that the background currents are in geostrophic balance
\begin{eqnarray*}
	0 &=& -\D{P_G}{x} + fV \,,\\
	0 &=& -\D{P_G}{y} - fU \,,\\
\end{eqnarray*}
where $P_G$ is a geostrophic pressure field that is decoupled from the perturbation pressure due the lee wave.

To keep the system as simple as possible, we further assume: it is in steady state; the bathymytery varies only in the $x$-direction; and rotation has a constant rate $f=\Omega sin(\bar{\phi})$, where $\Omega$ is the earth's rate of rotation, and $\bar{\phi}$ is the average lattitude of the domain. The assumption of steady state filters out inertial oscillations, and may be invalid in regions of the ocean where rotation is strong, such as the ACC ~\citep{Nikurashin2010a}. However, in regions closer to the equator, such as Palau, this assumption is quite good, as the following scaling analysis will demonstrate.  In combination, these three assumptions allow us to neglect all spanwise gradients in the perturbation fields because the hill only perturbs the flow in the $x$-direction, there are no inertial oscillations to deflect the flow from its hill-perturbed state, and rotation remains constant at all locations in the domain. Thus, again making the Boussinesq approximation, the steady momentum and density transport equations that include (some representation of) rotation are given by
\begin{eqnarray*}
	U \D{u'}{x} +u' \D{u'}{x} + w' \D{u'}{z} &=& -\D{p'}{x} + fv' \,,\\
	U \D{v'}{x} + u' \D{v'}{x} + w' \D{v'}{z} &=& - fu' \,,\\
	U \D{w'}{x} + u' \D{w'}{x} + w' \D{w'}{z} &=& -\D{p}{z} - \frac{\rho}{\rho_0} g \,,\\
	U \D{\rho'}{x} + u' \D{\rho'}{x} + w' \D{\rho'}{z} &=& \frac{\rho_0 N^2}{g} w\,,
\end{eqnarray*}
where $N^2 = -g/\rho_0 \partial\rhobar/\partial z$, subject to continuity $\nabla\cdot\ub'=0$, and
the kinematic bottom boundary condition
\[
U\D{h}{x} + u' \D{h}{x} = w'\,.
\]
Note that these equations are unchanged from those in the irrotational case except for the addition of $+fv'$ to the $x$-momentum equation, and of course the presence of the $y$-momentum equation. Thus the scalings resulting from our irrotational work above hold in all cases except for these two equations.

Nondimensionalizing as above, with the addition of $v = v_0 v*$, the $y$-momentum equation becomes
\begin{eqnarray*}
	kUv_0 \D{v}{x} + ku_0v_0\left(u \D{v}{x} + w \D{v}{z}\right) &=& - fu_0u \,.\\
\end{eqnarray*}
Requiring a balance of lowest order terms, this gives $v_0 = \frac{fu_0}{Uk}=u_0/Ro$, where $Ro = Uk/f$ is the Rossby number, and
\begin{eqnarray*}
	 \D{v}{x} + J\left(u \D{v}{x} + w \D{v}{z}\right) &=& - u \,.\\
\end{eqnarray*}
Turning next to the $x$-momentum equation, we have
\begin{eqnarray*}
	k u_0 U \D{u}{x} + k u_0^2\left( u\D{u}{x} + w \D{u}{z}\right)  &=& -k P \D{p}{x} + fv_0v\,.
\end{eqnarray*}
Again balancing lowest order terms, we have $P=Uu_0$, and the $x$-momentum equation becomes
\begin{eqnarray*}
	\D{u}{x} +J\left( u\D{u}{x} + w \D{u}{z}\right)  &=& -\D{p}{x} + Ro^{-2}v\,.
\end{eqnarray*}
From this result, we can diagnose the frailty of our assumptions about rotational effects. Using characteristic values of the ACC, $U \approx 0.1$~m~s$^{-1}$, $N \approx 10^-3$~rad~s$^{-1}$,  $k \approx 2\pi/2$~km, and $f\approx10^{-4}$~rad~s$^{-1}$, and $h_0\approx60$~m, we have $Ro \approx 0.5$, $Ro^{-2}\approx4$ and $J\approx 0.6$ ~\citep{Nikurashin2010a}. In other words, in the ACC, rotational effects on the scale of lee waves are zeroth order, and our assumptions simplifying them were likely misguided. However, if we focus instead on a more equatorial region with equally strong geostrophic currents, such as Palau, $f$ becomes an order of magnitude smaller, and $Ro\approx5$ for the lee wave system, giving $Ro^{-2}\approx 0.04$. Here, then, is a part of the ocean where rotation might only enter the equations as meridional jets squirting out of the lee waves.

%	reflecting hydraulic control and a local energy sink, in analogy to a hydraulic jump downstream of open channel flow over a critical height.

%Winters an Armi's analysis highlights an essential difference between this problem and the single layer channel flow from which our standard understanding of the Froude number derives. Consider the subcritical limit, in which $h$ is much less than $U/N$. Here the ``depth'' of the fluid as it travels over bathymetry is oblivious to both the ocean's depth and the bathymetry's height, and is instead entirely specified according to the impinging flow's properties, namely U and N.

%	While we would  expect a larger $N$ to block the flow and
%	reduce the magnitude of the perturbation above the hill, the scaling shows that
%	$u_0 = J U$, implying that the perturbation velocity above the sill increases in step with
%	increasing $J$. However, the gravitational force resulting from the perturbation is
%	given by $\sqrt{g'\delta} = J^{1/2} U$, which grows more slowly than $u_0$ with increasing $J$.

%	(In the 2-D case, blocking is an adiabatic advective process while span wise vorticity generation and downslope winds are diabatic. In the 3-D case, horizontal splitting is an adiabatic advective response while vertical vorticity generation represents a nearly adiabatic advective non-linearity with the unique capacity to carry energy away from the site of generation.)

	%Understanding the kinetic energy in the wave is more nuanced. Beginning with the denominators in the relation $J^{1/2}=(Nh_0/U)^{1/2}=u_0/\sqrt{g'\delta}$, and multiplying $J=Nh_0/U$ by $U/U$ for dimensional consistency, we have $\sqrt{g'\delta}= U$, this expresses that the gravity wave response exists as a direct consequence of the background velocity. Indeed, in the frame of reference moving with the water, U is the magnitude of the group velocity of this wave (as both borne out in the math and evidenced by observation of the steady state hydrostatic wave standing motionless above a hill). Similarly, considering the numerators: $(Nh_0U)^{1/2}=u_0$, we see that perturbation velocity above the hill is a direct consequence of buoyancy's attempt to restore an element to its equilibrium position, where the maximum possible displacement is the height of the hill.

\bibliographystyle{elsarticle-harv}
\bibliography{bibliography}

\end{document}


\include{Preamble}

\begin{document}

\title{Draft description of NEMO wetting and drying scheme:     29 November 2017 }

\author{ Enda O'Dea, Hedong Liu, Jason Holt, Andrew Coward  and Michael J. Bell  }

%------------------------------------------------------------------------
% End of temporary latex header (to be removed)
%------------------------------------------------------------------------

% ================================================================
% Chapter Ocean Dynamics (DYN)
% ================================================================
\chapter{Ocean Dynamics (DYN)}
\label{DYN}
\minitoc

% add a figure for  dynvor ens, ene latices

$\ $\newline    % force a new ligne

% ================================================================
% Wetting and drying
% ================================================================

%----------------------------------------------------------------------------------------
%      The WAD test cases
%----------------------------------------------------------------------------------------
\section   [The WAD test cases (\textit{usrdef\_zgr})]
			{The WAD test cases (\mdl{usrdef\_zgr})}
\label{WAD_test_cases}

This section contains details of the seven test cases that can be run as part of the
WAD\_TEST\_CASES configuration. All the test cases are shallow (less than 10m deep),
basins or channels with 4m high walls and some of topography that can wet and dry up to
2.5m above sea-level. The horizontal grid is uniform with a 1km resolution and measures
52km by 34km. These dimensions are determined by a combination of code in the
\mdl{usrdef\_nam} module located in the WAD\_TEST\_CASES/MY\_SRC directory and setting
read in from the namusr\_def namelist. The first six test cases are closed systems with no
rotation or external forcing and motion is simply initiated by an initial ssh slope. The
seventh test case introduces and open boundary at the right-hand end of the channel which
is forced with sinousoidally varying ssh and barotropic velocities.

\namdisplay{nam_wad_usr}

The $\mathrm{nn\_wad\_test}$ parameter can takes values 1 to 7 and it is this parameter
that determines which of the test cases will be run. Most cases can be run with the
default settings but the simple linear slope cases (tests 1 and 5) can be run with lower
values of $\mathrm{rn\_wdmin1}$. Any recommended changes to the default namelist settings
will be stated in the individual subsections.

Test case 7 requires additional {\tt namelist\_cfg} changes to activate the open boundary
and lengthen the duration of the run (in order to demonstrate the full forcing cycle).
There is also a simple python script which needs to be run in order to generate the
boundary forcing files.  Full details are given in subsection (\ref{WAD_test_case7}).

\clearpage
\subsection [WAD test case 1 : A simple linear slope]
                    {WAD test case 1 : A simple linear slope}
\label{WAD_test_case1}

The first test case is a simple linear slope (in the x-direction, uniform in y) with an
adverse SSH gradient that, when released, creates a surge up the slope. The parameters are
chosen such that the surge rises above sea-level before falling back and oscillating
towards an equilibrium position. This case can be run with $\mathrm{rn\_wdmin1}$ values as
low as 0.075m. I.e. the following change may be made to the default values in {\tt
namelist\_cfg} (for this test only):

\namdisplay{nam_wad_tc1}

%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
\begin{figure}[htb] \begin{center}
\includegraphics[width=0.8\textwidth]{Fig_WAD_TC1}
\caption{ \label{Fig_WAD_TC1}
The evolution of the sea surface height in WAD\_TEST\_CASE 1 from the initial state (t=0)
over the first three hours of simulation. Note that in this time-frame the resultant surge
reaches to nearly 2m above sea-level before retreating.}
\end{center}\end{figure}
%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

\clearpage
\subsection [WAD test case 2 : A parabolic channel ]
                    {WAD test case 2 : A parabolic channel}
\label{WAD_test_case2}

The second and third test cases use a closed channel which is parabolic in x and uniform
in y.  Test case 2 uses a gentler initial SSH slope which nevertheless demonstrates the
ability to wet and dry on both sides of the channel. This solution requires values of
$\mathrm{rn\_wdmin1}$ at least 0.3m ({\it Q.: A function of the maximum topographic
slope?})

\namdisplay{nam_wad_tc2}

%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
\begin{figure}[htb] \begin{center}
\includegraphics[width=0.8\textwidth]{Fig_WAD_TC2}
\caption{ \label{Fig_WAD_TC2}
The evolution of the sea surface height in WAD\_TEST\_CASE 2 from the initial state (t=0)
over the first three hours of simulation. Note that in this time-frame the resultant sloshing
causes wetting and drying on both sides of the parabolic channel.}
\end{center}\end{figure}
%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

\clearpage
\subsection [WAD test case 3 : A parabolic channel (extreme slope) ]
                    {WAD test case 3 : A parabolic channel (extreme slope)}
\label{WAD_test_case3}

Similar to test case 2 but with a steeper initial SSH slope. The solution is similar but more vigorous.

\namdisplay{nam_wad_tc3}

%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
\begin{figure}[htb] \begin{center}
\includegraphics[width=0.8\textwidth]{Fig_WAD_TC3}
\caption{ \label{Fig_WAD_TC3}
The evolution of the sea surface height in WAD\_TEST\_CASE 3 from the initial state (t=0)
over the first three hours of simulation. Note that in this time-frame the resultant sloshing
causes wetting and drying on both sides of the parabolic channel.}
\end{center}\end{figure}
%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

\clearpage
\subsection [WAD test case 4 : A parabolic bowl ]
                    {WAD test case 4 : A parabolic bowl}
\label{WAD_test_case4}

Test case 4 includes variation in the y-direction in the form of a parabolic bowl. The
initial condition is now a raised bulge centred over the bowl. Figure \ref{Fig_WAD_TC4}
shows a cross-section of the SSH in the X-direction but features can be seen to propagate
in all directions and interfere when return paths cross.

\namdisplay{nam_wad_tc4}

%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
\begin{figure}[htb] \begin{center}
\includegraphics[width=0.8\textwidth]{Fig_WAD_TC4}
\caption{ \label{Fig_WAD_TC4}
The evolution of the sea surface height in WAD\_TEST\_CASE 4 from the initial state (t=0)
over the first three hours of simulation. Note that this test case is a parabolic bowl with
variations occurring in the y-direction too (not shown here).}
\end{center}\end{figure}
%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

\clearpage
\subsection [WAD test case 5 : A double slope with shelf channel ]
                    {WAD test case 5 : A double slope with shelf channel}
\label{WAD_test_case5}

Similar in nature to test case 1 but with a change in slope and a mid-depth shelf.

\namdisplay{nam_wad_tc5}

%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
\begin{figure}[htb] \begin{center}
\includegraphics[width=0.8\textwidth]{Fig_WAD_TC5}
\caption{ \label{Fig_WAD_TC5}
The evolution of the sea surface height in WAD\_TEST\_CASE 5 from the initial state (t=0)
over the first three hours of simulation. The surge resulting in this case wets to the full
depth permitted (2.5m above sea-level) and is only halted by the 4m high side walls.}
\end{center}\end{figure}
%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

\clearpage
\subsection [WAD test case 6 : A parabolic channel with central bar ]
                    {WAD test case 6 : A parabolic channel with central bar}
\label{WAD_test_case6}

Test cases 1 to 5 have all used uniform T and S conditions. The dashed line in each plot
shows the surface salinity along the y=17 line which remains satisfactorily constant. Test
case 6 introduces variation in salinity by taking a parabolic channel divided by a central
bar (gaussian) and using two different salinity values in each half of the channel. This
step change in salinity is initially enforced by the central bar but the bar is
subsequently over-topped after the initial SSH gradient is released. The time series in
this case shows the SSH evolution with the water coloured according to local salinity
values. Encroachment of the high salinity (red) waters into the low salinity (blue) basin
can clearly be seen.

\namdisplay{nam_wad_tc6}

%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
\begin{figure}[htb] \begin{center}
\includegraphics[width=0.8\textwidth]{Fig_WAD_TC6}
\caption{ \label{Fig_WAD_TC6}
The evolution of the sea surface height in WAD\_TEST\_CASE 6 from the initial state (t=0)
over the first three hours of simulation. Water is coloured according to local salinity
values. Encroachment of the high salinity (red) waters into the low salinity (blue) basin
can clearly be seen although the largest influx occurs early in the sequence between the
frames shown.}
\end{center}\end{figure}
%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

\clearpage
\subsection [WAD test case 7 : A double slope with shelf, open-ended channel ]
                    {WAD test case 7 : A double slope with shelf, open-ended channel}
\label{WAD_test_case7}

Similar in nature to test case 5 but with an open boundary forced with a sinusoidally
varying ssh. This test case has been introduced to emulate a typical coastal application
with a tidally forced open boundary. The bathymetry and setup is identical to test case 5
except the right hand end of the channel is now open and has simple ssh and barotropic
velocity boundary conditions applied at the open boundary. Several additional steps and
namelist changes are required to run this test.

\namdisplay{nam_wad_tc7}

In addition, the boundary condition files must be generated using the python script
provided.

\begin{verbatim}
python ./makebdy_tc7.py
\end{verbatim}

will create the following boundary files for this test (assuming a suitably configured
python environment: python2.7 with netCDF4 and numpy):

\begin{verbatim}
  bdyssh_tc7_m12d30.nc   bdyuv_tc7_m12d30.nc
  bdyssh_tc7_m01d01.nc   bdyuv_tc7_m01d01.nc
  bdyssh_tc7_m01d02.nc   bdyuv_tc7_m01d02.nc
  bdyssh_tc7_m01d03.nc   bdyuv_tc7_m01d03.nc
\end{verbatim}

These are sufficient for up to a three day simulation; the script is easily adapted if
longer periods are required.

%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
\begin{sidewaysfigure}[htb] \begin{center}
\includegraphics[width=0.8\textwidth]{Fig_WAD_TC7}
\caption{ \label{Fig_WAD_TC7}
The evolution of the sea surface height in WAD\_TEST\_CASE 7 from the initial state (t=0)
over the first 24 hours of simulation. After the initial surge the solution settles into a
simulated tidal cycle with an amplitude of 5m. This is enough to repeatedly wet and dry
both shelves.}

\end{center}\end{sidewaysfigure}
%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

% ================================================================

%\bibliographystyle{wileyqj}
%\bibliographystyle{../../../doc/latex/NEMO/main/ametsoc.bst}
%\bibliography{references}

\end{document}


\documentclass[12pt,a4paper]{article}
\usepackage[latin1]{inputenc}
\usepackage[dutch]{babel}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{amsthm}
\usepackage{enumerate}
\usepackage{tikz}
\usepackage{pgfplots}
\usepackage{todonotes}
\usepackage[left=2cm,right=2cm,top=2cm,bottom=2cm]{geometry}

\author{Tom Sydney Kerckhove}
\title{Oefeningen Numerieke Wiskunde:\\ Oefenzitting 9}
\date{29 maart 2014}

\begin{document}
\maketitle

\section{Probleem 1}
\[
a_{0}t_1^3+b_0t_1^2+c_0t_1+d_0-a_{1}t_1^3+b_1t_1^2+c_1t_1+d_1=0
\]
Het stelsel $A$ ziet er dus als volgt uit.
\[
A=
\left(
\begin{array}{ccccccccccccccccc}
t_1^3 & t_{1}^2 & t_{1} & 1 & -t_1^3 & -t_1^2 & -t_1 & -1 & 0 & 0 & 0 & 0 & \cdots \\
0 & 0 & 0 & 0 & t_2^3 & t_{2}^2 & t_{2} & 1 & -t_2^3 & -t_2^2 & -t_2 & -1 & \cdots\\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & t_3^3 & t_{3}^2 & t_{3} & 1 & \cdots\\
\vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \\
3t_1^2 & 2t_{1} & 1 & 0 & -3t_1^2 & -2t_1 & -1 & 0 & 0 & 0 & 0 & 0 & \cdots \\
0 & 0 & 0 & 0 & 3t_2^2 & 2t_{2} & 1 & 0 & -3t_2 & -2t_2 & -1 & 0 & \cdots\\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 3t_3^2 & 2t_{3} & 1 & 0 & \cdots\\
\vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \\
6t_1 & 2 & 0 & 0 & -6t_1 & -2 & 0 & 0 & 0 & 0 & 0 & 0 & \cdots \\
0 & 0 & 0 & 0 & 6t_2 & 2 & 0 & 0 & -6t_2 & -2 & 0 & 0 & \cdots\\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 6t_3 & 2 & 0 & 0 & \cdots\\
\vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \\
\end{array}
\right)
\]

\section{Probleem 2}
Zie matlab

\section{Probleem 3}
\todo{evalspline}

\section{Probleem 4}
Zie matlab

\section{Probleem 5}
\todo{fix scripts}

\end{document}


\section{Graph library}

The \EcoLab{} graph library is a library providing a simple and
lightweight structure for representing graphs (aka networks). A graph
consists of a set of nodes labelled $N=\{0\ldots n-1\}$, and a set of
edges $E\subset N\times N$, which have an optional weight factor
attached.

An edge is represented by\index{Edge}
\begin{verbatim}
struct Edge: public std::pair<unsigned,unsigned>
{
    unsigned source();
    unsigned target();
    float weight;
};
\end{verbatim}

The abstract Graph\index{Graph} interface has the following definition:
\begin{verbatim}
struct Graph
{
  struct const_iterator
  {
    Edge operator*() const;
    const Edge* operator->() const;
    const_iterator& operator++();
    bool operator==(const const_iterator& x) const;
    bool operator!=(const const_iterator& x) const;
  };

  virtual const_iterator begin() const;
  virtual const_iterator end() const;

  virtual unsigned nodes() const;
  virtual unsigned links() const;
  virtual void push_back(const Edge& e);
  virtual bool contains(const Edge& e) const;
  virtual bool directed() const;
  virtual void clear(unsigned nodes=0);
  const Graph& operator=(const Graph& x);
  void input(const std::string& format, const std::string& filename);
  void output(const std::string& format, const std::string& filename) const;
  template <class BG> Graph_back_insert_iterator<Graph,BG>
    back_inserter(const BG& bg);
}
\end{verbatim}

The \verb+begin/end+ methods allow one to iterate over the edges. Only a \verb+const_iterator+
is supplied, as it is an error to change the value of an edge. One can
only reset a graph to the empty graph via clear, and construct the
graph incrementally using the \verb+push_back()+ method.

The \verb+contains+ method allows one to test whether a given edge is
in the graph, and \verb+directed+ indicates whether the underlying graph
structure has directed edges or not. A bidirectional graph otherwise
appears as a directed graph where each edge appears twice, once for
each direction.

The input/output methods allow for the graph to be read/written
from/to a file, in a variety of formats, given by the format
parameter. Currently, the following formats are supported:
\begin{tabular}{|l|l|}
\hline
name & description\\
\hline
pajek\index{pajek} & Pajek's .net format\\
lgl\index{lgl} & LGL's .lgl format\\
dot\index{dot} & Graphviz\index{Graphviz} format\\
gengraph & Gengraph\index{Gengraph}\\
\hline
\end{tabular}
Also graphs can be streamed to/from standard I/O streams, and will appear
in dot format. In particular, this means that TCL scripts can access
Graph objects as strings containing the Graphviz representation. See
some of the examples in the \verb+models/netcomplexity_scripts+ directory.

\verb+back_inserter+ creates an output iterator suitable for use with
Boost Graph algorithms. As a simple example, to construct an \EcoLab{}
graph from a Boost Graph, do
\begin{verbatim}
  std::pair<BG::edge_iterator,BG::edge_iterator> r=edges(bg);
  ConcreteGraph<DiGraph> g1;
  copy(r.first, r.second, g1.back_inserter(bg));
\end{verbatim}

This interface can be used in both a dynamic polymorphism fashion (ie
Graph is an abstract base class) and in a static polymorphism fashion.

The \verb+graph.h+ header file provides two concrete graph types -
DiGraph\index{DiGraph} and BiDirectionalGraph\index{BiDirectionalGraph}, which differ just in whether each edge
is directed or not.

\subsection{Boost}

\EcoLab{} has a deliberate policy of not having a dependency on
Boost, but to be as compatible with Boost as far as it is
possible. The \EcoLab{} graph library has been designed to be
interoperable with the Boost Graph Library. The file
\verb+test/test_boostgraph.cc+ gives some examples of interoperation
with Boost.

\subsection{Graph Library Functions}

\verb+Degrees degrees(const G& g)+ returns array of node degrees
return as the following structure:
\begin{verbatim}
struct Degrees
{
  array<unsigned> in_degree, out_degree;
};
\end{verbatim}

\verb+void ErdosRenyi_generate(Graph& g, unsigned nodes, unsigned
links, urand& uni);+

Generate an Erd\"os-R\'enyi random graph with given nodes and
links. Links are attached randomly to the nodes, drawn from uni.

\verb+PreferentialAttach_generate(Graph& g, unsigned nodes, urand& uni,
                                 random_gen& indegree_dist=default_indegree)+

Barabasi-Albert Preferential attachment algorithm. For each node, an
indegree value is drawn from \verb+indegree_dist+ (defaults to a
constant value of 1). This many links are then preferentially attached
to other nodes, according to their outdegree.

\subsection{Network complexity}

\begin{verbatim}
class BitRep implements Graph
{
  BiDirectionalBitRep symmetrise() const;
  bool operator()(i,j);
  bool next_perm();
};

class BiDirectionalBitRep implements Graph
{
  bool operator()(i,j);
  bool next_perm();
};

class NautyRep implements Graph
{
  bool operator()(i,j);
  double lnomega() const;
  NautyRep canonicalise() const;
};

\end{verbatim}
These classes implement the Graph interface by storing the linklist as
a bitset. NautyRep specifically uses the bitset representation of the
Nauty package. One can freely convert between these types and others
implementing the Graph interface. All of these types support direct
setting/testing of the i,j th edge through the operator(i,j).

BitRep and BiDirectionalBitRep allow one to iterate through the
permutations (thus cycling over all graph representations of a given
edge count). This function returns false when no further permutations exist.

NautyRep has member functions for calling the Nauty library. If you
need both the lnomega and canonical representations, then it is more
efficient to call them at the same time via the \verb+ecolab_nauty()+
function.

\begin{verbatim}
void ecolab_nauty(const NautyRep& g, NautyRep& canonical, double& lnomega, bool do_canonical);
\end{verbatim}
call Nauty on g, returning a canonical representation canonical and
lnomega ($\ln\Omega$). If canonical is not needed, then set \verb+do_canonical+ to
false.

\begin{verbatim}
double canonical(BitRep& canon, const Graph& g);
\end{verbatim}
SuperNOVA canonical algorithm. Returns $\ln\Omega$ and canonical
representation (which needn't correspond to that returned by Nauty).

\begin{verbatim}
double complexity(const Graph& g);
\end{verbatim}
Network complexity. If all links have the same weight, this
corresponds to $2\lceil\log_2(n+1)\rceil+\lceil\log_2(n(n-1))\rceil+1+
\log_2\left(\begin{array}{c}n(n-1)\\l\end{array}\right) - \log_2\Omega$.


\section{Quantum Mechanics}
The state of a system is described by a ket in a Hilbert space $H$.
Every observable corresponds to a hermitian operator $A$ with
$A\ket{a}=a\ket{a}$,
where $a$ are possible outcomes of a measurement.
The probability of measuring $A=a$ is equal to
$|\braket{\psi}{a}|^2$.

The actual \emph{amplitude} is $\braket{\psi}{a}$ which is a projection onto
$\ket{a}$,
which is a complex number.
The modulus squared is the probability.

Every state has magnitude 1,
so the projection is smaller than one.

How do I calculate the probability if there is a degenerate state?
Well you project both.
If $\ket{\psi}$ is the state of the system at measurement,
and suppose I have a two-dimensional eigenspace with eigenvalue $a$.
Any vector in this space has eigenvalue $a$.
How do I calculate the probability?
I take $\ket{\psi}$ and project down onto this plane.
This probability is
\begin{align}
    \sum_{a\in\text{subspace}} |\braket{a}{\psi}|^2
\end{align}
So in the general case there is a sum here if the eigenvalue is degenerate.
Sometimes it's not so common,
so if you read Griffiths you may not have noticed.
Usual things apply,
it's a probabilistic theory, etc.

There is a misunderstood point.
Say I have a system, like my keys.
I measure the position of the car key.
Use your imagination.
It has a bunch of eigenvalues,
the angles my key makes with the vertical.
I look and I find my key here.
Good that's great.
What happens if immediately after that I make another measurement?
If the state of the system was in a state I started out,
there would be a probability.
Immediately afterwards,
there's no time for anything to happen.
What's the point of looking?
It's not like I can look and extend my 5 fingers to pick it up.
But when I move,
it's here and here.
What's the point of making a measurement?
This world would be chaos.
There would be nothing.
That's not how the universe works.

The universe works like this.
You measure something.
You measure again,
it's in the same darn place.
The world is not completely chaotic.
Of course if I take too long,
maybe they key may be in a different place.

How do I guarantee this in my formalism?

What happens is that you need this as well:
\begin{itemize}
    \item After a measurement $A=a$,
        then the state $\ket{\psi}$ magically instantaneously becomes
        \begin{align}
            \ket{\psi}\to \ket{a}
        \end{align}
\end{itemize}
But what happens immediately after?
I'll have probability $1$ of measuring $a$ again.
This has a few names.
It's called the \emph{reduction of the wave packet}.

Those eigenvectors can be thought of waves,
maybe a bump in space.
You measure and you no longer have a bump in space,
just a Fourier component for example.
That's the old lingo for that.
There's another name,
the \emph{collapse} of the wave packet,
or wave function, blah blah blah.

By the way, what happens if the eigenvalue is degenerate?
In principle I can go into any one of these.
It goes into the projection,
the closest one in the subspace.

People are immensely bothered by this,
so much that textbooks try to hide this.
They try to make you pay attention to the Schrodinger equation.
Because of this,
if some people do this lecture,
people leave this out in a lecture
because it's so embarrassing.

Have you learnt about a theory like EM where you didn't say why.
Hold this comment.

In Newtonian mechanics, you say $F=ma$,
particles accelerate, you calculate forces,
that gives me forces, etc.
Here,
the time evolution of the state of the system is given by a differential equation
that is very simple
\begin{align}
    i\hbar \frac{d}{dt} \ket{\psi(t)} = H\ket{\psi(t)}
\end{align}
where $H$ is the Hamiltonian.
I write this without the curly $H$ so it's not a Hilbert space.
The time-evolution is given by this magic operator.
The point is,
there are two ways the state of the system can evolve.
One,
according to this \emph{Schrodinger equation},
that's what it's called by the way.
That's what you do 100\% of the time in Griffiths.

Sometimes though,
Schrodinger equation stops working,
when you measure.
And then after that Schrodinger again.
For example,
if there is a guy in a white lab coat with a beer
and a lot of electronics,
and he's good at messing around with systems,
and a number pops up saying 42.
That's a measurement.
You measure the energy and got 42 Joules.
When I measure immediately afterwards I get 40 Joules.
So he with a lab coat he can stop Schrodinger equation,
and then it comes back.
What if he doesn't have a lab coat and doesn't have a beard?
Some graduate student?
So does that apply?
Yes of course,
grad students are people too.
What if they are an undergraduate?
You know in your heart they are people too.
What is it's a monkey.
You train the monkey,
he says 42,
he has no idea of what 42 means.
Do you think will the wave function will evolve.
Some people say no.
What about Neanderthals?
When did we evolve to have the ability to collapse wave functions?
That's ridiculous.

Of course the wave function collapses.
What if there's no monkey it's automatic.

People can find out it's 42.
When does the wave function collapse?
Does it collapse when the number pops up,
or when the human being looks at it?

Some say this stuff is this hippy dippy stuff.
They say
what causes this change is an interaction with the measurement apparatus.
For a while,
it's described not by the Hamiltonian of the system,
but the object and the system.
No.
It's easy to prove this is not true.

Because let's go back here.

The wave function in the future is automatically normalized.
If I write my state in the future,
in terms of state in the initial time,
there's going to be a linear operator relating those two things.
As we see, this thing is a unitary operator
\begin{align}
    \ket{\psi(t)} = U(t) \ket{\psi(0)}
\end{align}
which preserves lengths and angles.

Measurement operation is not unitary.
For example,
but part orthogonal to $\ket{a}$ got shrunk to zero,
but unitary just rotates things,
so it's not unitary.

It's too facile to say my apparatus interacted with the system,
because it's not unitary.
It's not enough.

Say my student says it was 42 measured.
When did it collapse?
When the student saw it or before that?

I make a measurement and I see a particular result.
I know there was some kind of collapse.
We can say this measurement axiom is not true,
because it poses this difficult question it is asking.

By the way,
no body has a better answer to this.

I tried my whole life to make a particular experiment
that depends whether the wave function
when the number pops up or when the grad student sees the result.
I also never seen a proof of either.
It's a hole in the literature.

There is no experiment that can explain that subtlety of when the collapse
happens.
The modern understanding is slightly better,
but only slightly.
You should do an analysis involving the system,
the apparatus,
and maybe the grad student.
This is not only unitary evolution,
but also deterministic.
I started in a state,
and there is no way to manipulate Schrodinger equation
to come up with a solution which says I collapse into this
and maybe this as well.
Think really hard about deterministic evolution
and somehow derive the measurement axiom.
You just have to live with it.
It could make you sleep bad at night,
but that's just philosophy.
I don't.
Something big and weird is happening there.

There's one more thing useful for quantum mechanics.
If you have a composite system and each one has a Hilbert space $\mathcal{H}_1$
and $\mathcal{H}_2$,
the composite system is going to have a Hilbert space
$\mathcal{H}_1\otimes\mathcal{H}_2$.
There's a lot of juice hidden here.

Say that $\mathcal{H}_1$ is 2-dimensional,
and $\mathcal{H}_2$ is 2-dimensional.
What is the composite system?
4 dimensions.
What if I had a third Hilbert space? 8.
So exponential growth.
With just 100, you have $2^{100}$.
It can be represented as a matrix,
like in kindergarten,
but how big is the matrix?
Can you write down the matrix?
Can the computer calculate?
If you transfer planet Earth,
take the galaxy,
universe,
turn it into disk space,
you still cannot write the Hamiltonian with 100 systems.
This exponential growth is a bummer,
well not really a bummer,
because then you'd be able to diagonalize everything
and I would lose my job.

That's my summary of QM,
it's really upstart,
but we're going to take this and apply to many cases.
It's very upstart,
but we've done all the work already.

We've done all the numbers already,
you know how to transform things into concrete equations,
because we spent two weeks.
Strictly speaking, we're actually done.
Go home class is over.

\begin{question}
    You call a hermitian operator measurable.
    Is that measurable the same as probability?
\end{question}
No, measurement in the physics sense.
Anything you can measure.
Go to Radio Shack, get a ruler,
that's a measurable device.

Measure is physicist lingo.

We have to distinguish things like momentum and energy for which there are
devices,
from things like kets.
I cannot by a ket-meter that tells me what the ket is.
There will never be such a thing.
That is not an observable.
That's the end of QM.
But before examples,
I want to make trivial generic comments.

\begin{itemize}
    \item An overall phase on $\ket{\psi}$ is unphysical.
        Look at my system and say this is $\ket{\psi}$,
        but my friends says no it's $e^{i\alpha}\ket{\psi}$,
        it's the same thing.
        More than that.
        Suppose I start with a state and evolve,
        but my friend has a space,
        in the end the phase doesn't matter.
        If you want to be nitty-picky,
        you should say it's not that states are represented by kets.
        It's not even represented by kets measured 1.
        It's represented by rays.
        You can take a vector,
        you can multiply by any number,
        including complex numbers.
        The whole set represents this thing.
        When I use the wave function to calculate a probability,
        we're going to get the same result.
    \item The Schrodinger equation is linear.
        If I have two solutions of the Schrodinger equation,
        I'm going to get another solution.
        It's like the Maxwell equations.
\end{itemize}
Should I stop to tell Schrodinger stories?
He was a great scientist,
but he fun part is his personal life of course.
He was Australian,
and compared to other people who invented QM
who were like 23,
he was in his 30s,
receding hairline already.
He was a
He didn't get along with the Nazis in the 30s.
He was not Jewish,
just cut his pie.
He became very uncomfortable,
and then German invaded Austria.
He could be killed.
He wrote a letter reneging his position with the Nazis,
He regretted,
so he decided to leave.
He needed visa, a job.
He had a wife and kids.
And the lover.
And the lover's husband.
He has a lot.
It was complicated.
A few years earlier he had written that equation.
So he got invitations for jobs.
So he went to Oxford.
The people look at the situation,
say don't think so.
He wants to leave with his kids, wife, lover, lover's husband.
Then at Princeton,
there is the Institute of Advanced Studies,
when they hire Einstein, Godel, von Neumann, etc.
So he goes the New Jersey.
People at the Institute are given houses,
If you get hired there they give you Einstein's house.
It's funny,
you have to buy it from them and then you have to sell when you leave.
Einstein's house is a dump.
Nice museum, but it's not nice to live in because it doesn't have all the modern
amenities.
Can you get a job for the husband of the lover?
He was a mathematician.
People in New Jersey were not happy with that.

There was another institute of advanced studies at the time in Dublin headed by
a Catholic priest.
You say there's no chance.
Turns out he went there,
don't know how many people.
The reality is very different from the perception by majority of Americans.
Everything was fine.
He got job, visa, for his wife, kids, husband of the lover,
husband had someone else too.
Everyone came to Ireland and everyone was happy.
The only unhappy thing was Schrodinger really disliked quantum mechanics.
He didn't like collapse axiom.
After trying to fix QM,
he gave up and tried to do other things.
Some people say,
especially physicists,
he was kind of one of the first ones to think about DNA,
and how genetic information can be stored in molecules
before DNA was discovered.
I heard,
his little book \textit{What's Life}
was influential for the people who discovered DNA.
By the time he wrote this book,
everything was either known to be right or known to be wrong.
Watson and Crick weren't even biologists,
they where X-Ray physicists.

\begin{question}
    Do you know Schrodinger?
    Or other famous people?
\end{question}
Schrodinger died before I was born.
I'm not that old!
He's not one of the elder kings of QM.
I met famous people,
but not physicists.
Does that count?
There are physicists famous among physicists.
Does that count?
At this stage,
you don't know the very old people who invented QM.
I know Heisenberg's son.
I taught QM to Neils Bohr's great grandson,
he was a student here at Maryland.
How can you go into physics?
His great grandfather won a Nobel prize,
his grandfather won a Nobel prize.
His father was a slacker.
Why would you do this to yourself?

I remember these people of that generation barely walking.
Our lives did not overlap on this planet.
I met Hans Bethe.
I met some Los Alamos people,
but they were very old.
After the war,
there were a bunch of them,
very old.
I met some Rock stars,
does that count?

After telling you those things
you knew forever anyway,
we can talk about the no cloning theorem from linearity.
But, that's for Friday.

Can I write a copy of something on a Xerox?
Of course I can.
What I'm going to argue is that I cannot do this with quantum sates.
Say that I start with a system $\ket{\psi}$,
which represents blank paper.
Now I'm going to put together with another system,
which is like blank paper.
Actually, let's make this more interesting.
Suppose $\ket{\psi}$ is money.
I want to copy it.
What's the Hilbert space of the whole system together?
So my state is $\ket{\psi}\otimes\ket{\phi}$
where $\ket{\phi}$ is like blank paper.
I'm going to evolve this,
and arrange my Hamiltonian such that my system is going to be money and money
like $\ket{\psi}\otimes\ket{\psi}$.
That's how you make money.
If you do this,
you've got it.
Make a good xerox machine,
you can do that.
Not possible.
Imagine you start with a linear superposition
\begin{align}
    \frac{\ket{\psi_1} + \ket{\psi_2}}{\sqrt{2}}
    \otimes\ket{\phi}
    \to
    \frac{\ket{\psi_1}\otimes\ket{\psi_1} + \ket{\psi_2}\otimes
    \ket{\psi_2}}{\sqrt{2}}
\end{align}
But that's not what I want,
I want
\begin{align}
    \frac{\ket{\psi_1} + \ket{\psi_2}}{\sqrt{2}}
    \otimes\ket{\phi}
    \to
    \frac{\ket{\psi_1} + \ket{\psi_2}}{\sqrt{2}}
    \otimes
    \frac{\ket{\psi_1} + \ket{\psi_2}}{\sqrt{2}}
\end{align}
and you can see this is not the same.
You can see there a bunch of cross-terms like
$\ket{\psi_1}\otimes\ket{\psi_2}$.
Even if I can make copies of one-dollar bills,
I can only print one-dollar bills,
but it's not a copier.
This little result here is called the no-cloning theorem.
It's a completely trivial result.
We don't give any importance to this until Zurek
and people found it interesting.
Even if this is interesting to prove,
people forget sometimes.

If I tried to send a secret to my friend,
someone can spy on us by intercepting it make a copy.
Suppose I encode that information in a quantum state.
If someone spies on us,
they can make a copy,
but the most they can do is kill the system.
No one can make a copy of a quantum system and run away with it.
QM is a good way to transfer secrets.
When you to build a quantum computer,
a normal computer depends on copying,
but a quantum computer can't do that
and that's a bummer.
People think it's really cool,
so I want to mention this.


\section{Introduction} \label{sec:intro}
Physical properties of galaxies are the building
blocks of our understanding of galaxies and their evolution.
We can determine properties such as stellar mass ($M_*$), star formation rate (SFR), metallicity
($Z$), and age ($t_{\rm age}$) of a galaxy by analyzing its
spectral energy distribution (SED).
Theoretical modeling of galaxy SEDs is currently based on stellar population
synthesis (SPS) and describes the SED as a composite stellar population
constructed
from isochrones, stellar spectra, an initial mass function (IMF), a star
formation and chemical evolution history, and dust
attenuation~\citep[\emph{e.g.}][see \citealt{walcher2011, conroy2013} for a
comprehensive review]{bruzual2003, maraston2005, conroy2009}.
Some models also include dust and nebular emissions as well as emissions from
active galactic nuclei~\citep[\emph{e.g.}][]{johnson2021}.
In state-of-the-art SED modeling, theoretical SPS models are compared to
observed SEDs using Bayesian inference, which accurately quantifies parameter
uncertainties and degeneracies among them~\citep{acquaviva2011,
chevallard2016, leja2017, carnall2018, johnson2021, hahn2022}.
The Bayesian approach also enables marginalization over nuisance parameters,
which are necessary to model the effects of observational systematics
(\emph{e.g.} flux calibration).

However, current Bayesian SED modeling methods, which use Markov Chain Monte
Carlo (MCMC) sampling techniques, take $10-100$ CPU hours per
galaxy~\citep[\emph{e.g.}][]{carnall2019a, tacchella2021}.
While this is merely very expensive with current data sets of hundreds of
thousands of galaxy SEDs, observed by the Sloan Digital Sky
Survey~\citep[SDSS;][]{york2000}, DEEP2~\citep{davis2003},
COSMOS~\citep{scoville2007}, and GAMA~\citep{baldry2018}, it is prohibitive for
the next generation of surveys.
Over the next decade, surveys with the
Dark Energy Spectroscopic Instrument~\citep[DESI;][]{desicollaboration2016},
the Prime Focus Spectrograph~\citep[PFS;][]{takada2014},
the Vera C. Rubin Observatory~\citep{ivezic2019},
the James Webb Space Telescope~\citep{gardner2006},
and the Roman Space Telescope~\citep{spergel2015}, will observe \emph{billions}
of galaxy SEDs.
The task of SED modeling alone for these surveys would amount to tens or
hundreds of billions of CPU hours, exceeding \emph{e.g.} the entire compute
allocation of the Legacy Survey of Space and Time (LSST) data release
production\footnote{$\approx$2 billion core hours
(\url{https://dmtn-135.lsst.io/})} by at least two orders of magnitude.
Recently, \cite{alsing2020} adopted neural emulators to accelerate SED model
evaluations by three to four orders of magnitude --- posterior inference takes
minutes per galaxy.
While this renders current data sets within reach, the next generation data
sets will still require tens or hundreds of millions of CPU hours whenever any
aspect of the SED model is altered.
Furthermore, this still practically precludes rapid analyses of upcoming
transient surveys, especially LSST, which will report $\sim$10,000 alerts per
minute\footnote{\url{https://dmtn-102.lsst.io/}}.

But Bayesian inference does not require MCMC sampling.
Simulation-based inference (SBI) is a rapidly developing class of inference
methods that offers alternatives for many applications~\citep[see][and
references therein]{cranmer2020}.
Many SBI methods leverage the latest developments in statistics and Machine
Learning for more efficient posterior estimation~\citep{papamakarios2017,
alsing2019a, hahn2019c, dax2021, huppenkothen2021, zhang2021}.
Of particular interest for SED modeling is a technique called Amortized
Neural Posterior Estimation (ANPE).
Instead of using MCMC to sample the posterior for every single galaxy
separately, ANPE uses neural density estimators (NDE) to build a model of the
posterior for \emph{all} observable galaxies.
Once the NDE is trained, generating the posterior requires only the observed
SED and no additional model evaluations.

In this work, we present \sedflow, a method that applies ANPE to Bayesian
galaxy SED modeling using the recent \cite{hahn2022} SED model.
We demonstrate that we can derive accurate posteriors with \sedflow~and make
Bayesian SED modeling fully scalable for the billions of galaxies that will be
observed by upcoming surveys.
As further demonstration, we apply \sedflow~to the optical photometry of
${\sim}33,000$ galaxies in the NASA-Sloan Atlas~(NSA).
We begin in Section~\ref{sec:sbi} by describing SBI using ANPE.
We then present how we design and train \sedflow~in Section~\ref{sec:sedflow}
and describe the NSA observations in Section~\ref{sec:obs}.
We validate the accuracy of the posteriors from \sedflow~in
Section~\ref{sec:results} and discuss the implications of our results in
Section~\ref{sec:discuss}.


\section{Statistical Analysis through RAVEN}
\label{sec:SAraven}
In order to perform a complete analysis of a system under uncertainties,
it is crucial to be able to compute all the statistical moments of one or even multiple
FOMs. In addition, it is essential to identify the correlation
among different FOMs toward a specific input space.

RAVEN is able to compute the most important statistical moments:
such as:
\begin{enumerate}
  \item \textit{Expected Value}
  \item \textit{Standard Deviation}
  \item \textit{Variance}
  \item \textit{variationCoefficient}
  \item \textit{Skewness}
  \item \textit{Kurtosis}
  \item \textit{Median}
  \item \textit{Percentile}.
\end{enumerate}
In addition, RAVEN fully supports the computation of all of the statistical moments defined to
``measure'' the correlation among variables/parameters/FOMs:
\begin{enumerate}
  \item \textit{Covariance matrix}
  \item \textit{Normalized Sensitivity matrix}
  \item \textit{Variance Dependent Sensitivity matrix}
  \item \textit{Sensitivity matrix}
  \item \textit{Pearson matrix}.
\end{enumerate}
The goals of this section is to show how to:
 \begin{enumerate}
   \item Set up a sampling strategy to perform a final statistical analysis
   perturbing a driven code
   \item Compute all the statistical moments and correlation/covariance
   metrics.
\end{enumerate}
In order to accomplish these tasks, the following RAVEN \textbf{Entities} (XML blocks in the input files) need to be defined:
\begin{enumerate}
   \item \textbf{\textit{RunInfo}}:
     \xmlExample{framework/user_guide/StatisticalAnalysis/statisticalAnalysis.xml}{RunInfo}
   As shown in the other examples, the \textit{RunInfo} \textbf{Entity} is intended  to set up the desired analysis. The number of steps specified in (\xmlNode{Sequence}) are sequentially run, two steps in this specific case, using the number of processors assigned in (\xmlNode{batchSize}).
   \\In the first step, the original physical model is sampled. The obtained results are  analyzed with the Statistical Post-Processor.
   \item \textbf{\textit{Models}}:
     \xmlExample{framework/user_guide/StatisticalAnalysis/statisticalAnalysis.xml}{Models}
 The goal of this example is to show how the
 principal statistical FOMs can be computed through RAVEN.
 \\We use an External model and specify a Post-Processor model (BasicStatistics). The post-process step is performed on all the output FOMs used in this example ($r and t$).
   \item \textbf{\textit{Distributions}}:
     \xmlExample{framework/user_guide/StatisticalAnalysis/statisticalAnalysis.xml}{Distributions}
  In the Distributions XML section, the stochastic model for the
  uncertainties are reported. In this case 2 distributions are defined:
  \begin{itemize}
    \item $vel\_dist \sim \mathbb{N}(30,5)$, used to model the uncertainties
    associated with  the \textit{velocity};
    \item  $angle\_dist \sim \mathbb{U}(5,85)$,  used to
    model the uncertainties associated with the \textit{angle}.
  \end{itemize}
   \item \textbf{\textit{Samplers}}:
     \xmlExample{framework/user_guide/StatisticalAnalysis/statisticalAnalysis.xml}{Samplers}
  In order to obtain the data-set on which the data mining algorithms are going to be applied, a \textit{MonteCarlo} sampling approach is employed here.
   \item \textbf{\textit{DataObjects}}:
     \xmlExample{framework/user_guide/StatisticalAnalysis/statisticalAnalysis.xml}{DataObjects}
  In this block, three \textit{DataObjects} are defined:
  1) PointSet named ``samples'' used to collect the final outcomes of
  the code,
  2) PointSet named ``dummyIN'' used as a placeholder for the \textit{Multirun} step,
  3) HistorySet named ``histories'' in which the full time responses of the
  variables $x,y,t$ are going to be stored.

   \item \textbf{\textit{Steps}}:
     \xmlExample{framework/user_guide/StatisticalAnalysis/statisticalAnalysis.xml}{Steps}

 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
   Finally, all the previously defined \textbf{Entities} can be combined in
   the \xmlNode{Steps} block. As inferable,
   2 \xmlNode{Steps} have been inputted:
   \begin{itemize}
     \item \xmlNode{MultiRun} named ``sampleMC'', used to run the
     multiple
     instances of the driven code and
     collect the outputs in the two \textit{DataObjects}. As it can be
     seen, the \xmlNode{Sampler} is inputted to communicate to the
     \textit{Step} that the driven code needs to
     be perturbed through the MonteCarlo sampling strategy.
     \item \xmlNode{PostProcess} named ``statisticalAnalysisMC'', used
     compute all the statistical moments and FOMs based on the
     data obtained through the sampling strategy. As it can be noticed,
     the \xmlNode{Output} of the ``sampleMC'' \textit{Step} is the
     \xmlNode{Input} of the ``statisticalAnalysisMC''  \textit{Step}.
   \end{itemize}
\end{enumerate}

Tables \ref{ScalarMoments}-\ref{SensitivityComputed} show all the results of the \textit{PostProcess}
step.

\begin{table}[h!]
\centering
\caption{Computed Moments and Cumulants}
\label{ScalarMoments}
\begin{tabular}{|c|c|c|}
\hline
{\ul \textit{\textbf{Computed Quantities}}} & \textbf{r} & \textbf{t} \\ \hline
\textit{expected value}                     & 65.88   & 3.94   \\ \hline
\textit{median}                             & 61.74   & 4.12   \\ \hline
\textit{variance}                           & 1022.01 & 3.53   \\ \hline
\textit{sigma}                              & 31.97   & 1.89  \\ \hline
\textit{variation coefficient}              & 0.48    & 0.48   \\ \hline
\textit{skewness}                           & 0.55    & -0.03  \\ \hline
\textit{kurtosis}                           & -0.01   & -0.96  \\ \hline
\textit{percentile 5\%}                     & 20.21   & 0.85   \\ \hline
\textit{percentile 95\%}                    & 122.83  & 6.90   \\ \hline
\end{tabular}
\end{table}
\begin{table}[h!]
\centering
\caption{Covariance matrix.}
\label{covarianceComputed}
\begin{tabular}{|c|c|c|}
\hline
{\ul \textit{\textbf{Covariance}}} & \textbf{r} & \textbf{t} \\ \hline
\textit{velocity}                     & 95.36   & 3.29   \\ \hline
\textit{angle}                        & 25.29   & 40.42   \\ \hline
\end{tabular}
\end{table}
\begin{table}[h!]
\centering
\caption{Correlation matrix}
\label{pearsonComputed}
\begin{tabular}{|c|c|c|}
\hline
{\ul \textit{\textbf{Correlation}}} & \textbf{r} & \textbf{t} \\ \hline
\textit{velocity}                     & 0.61   & 0.36   \\ \hline
\textit{angle}                        & 0.03   & 0.92   \\ \hline
\end{tabular}
\end{table}
\begin{table}[h!]
\centering
\caption{Variance Dependent Sensitivity matrix}
\label{VarDepSensitivityComputed}
\begin{tabular}{|c|c|c|}
\hline
{\ul \textit{\textbf{Variance Sensitivity}}} & \textbf{r} & \textbf{t} \\ \hline
\textit{velocity}                     & -1.69   & 0.08   \\ \hline
\textit{angle}                        & -3.31   & 0.07   \\ \hline
\end{tabular}
\end{table}
\begin{table}[h!]
\centering
\caption{Sensitivity matrix}
\label{SensitivityComputed}
\begin{tabular}{|c|c|c|}
\hline
{\ul \textit{\textbf{Sensitivity (I/O)}}} & \textbf{r} & \textbf{t} \\ \hline
\textit{velocity}                     & 3.95   & 0.12   \\ \hline
\textit{angle}                        & 0.01   & 0.07   \\ \hline
\end{tabular}
\end{table}


%In this section we provide details of the three datasets that we evaluate in this paper, as well as the methodology used.
%\subsection{Dataset description}

%\subsubsection{Twitter example (Detection of natural disasters)}
\textcolor{red}{The scenario we have chosen to evaluate our algorithms is related to the detection of natural disasters discussed in a collection of tweets.  We used the Twitter data described in  \cite{Iman2017}, which was curated collaboratively by  four students as follows: (1) the dataset was restricted to users located within the US, (2) non-English tweets were filtered out, (3) only the tweets related to 12 natural disasters were kept -- tweets related to other natural disasters were removed. These natural disasters are temporally, and geographically disjoint -- a storm, a hurricane,  a drought, two floods, two earthquakes, two tornadoes,  and three blizzards. Finally, (4) false positive tweets were intentionally included -- tweets mentioning natural disasters specific-keywords but are not related to a particular natural disaster, e.g., \textit{\textquotedblleft I'm flooded with questions from followers\textquotedblright{}}. The final dataset contains 39,486 tweets with 5,075 marked as relevant tweets (in this context, a relevant tweet is a tweet related to a natural disaster).
}

\textcolor{red}{In addition to comparing our algorithms to the optimal solution, we also propose to use X-Means \cite{Pelleg2000} as a baseline method for clustering. X-Means is an extension of K-Means which tries to  automatically determine the number of clusters. Starting with only one cluster, the X-Means algorithm goes into action after each run of K-Means, making local decisions about which subset of the current centroids should split themselves in order to better fit the data. Also, the distance metric we have used for X-Means is a linear combination of: (i) the Euclidean distance of time, (ii) the Euclidean distance of location, and (iii) the cosine distance of the textual content. This distance metric is defined as follows:}
\begin{equation}
d(i,j) = \alpha\times\textrm{[time dist.]}+\beta\times \textrm{[location dist.]}+\gamma\times \textrm{[text cosine dist.]}
\end{equation}
\textcolor{red}{\noindent where $\alpha$, $\beta$, and $\gamma$ are weights that sum to 1, set all to 1 in the off-line evaluation and set respectively to 0.1, 0.8,  and 0.1 in the user study -- values manually tuned by our four students. Finally, we used EF1 to rank clusters returned by X-Means. }

%We assume having an agent monitoring tweets, a topical tweets classifier (e.g., \cite{Iman2017}), and a display showing the locations of the tweets (See Figure \ref{Fig:TwitterData}).  We used the  2.5 TB of Twitter data described in  \cite{Iman2017}, for which we restricted our analysis to the 9M tweets of January 2014.

%\begin{figure}[t]
%\begin{centering}
%\subfigure[Twitter Networks.]{\includegraphics[width=2.8cm]{imgs/twitter_example_3}\label{Fig:TwitterData}}\subfigure[Enron Networks.]{\includegraphics[width=2.8cm]{imgs/enron_net_4}\label{Fig:EnronData}}\subfigure[Reddit Networks.]{\includegraphics[width=2.8cm]{imgs/srforum3}\label{Fig:RedditData}}
%\par\end{centering}
%\caption{Layouts used for the different datasets.}
%\end{figure}


\documentclass[main.tex]{subfiles}
\begin{document}

\marginpar{Monday\\ 2021-12-20}

\begin{extracontent}
    What is the capacitance of a cylinder with a wire?
    %
    \begin{align}
    C = \frac{2 \pi \epsilon  L}{\log R _{\text{cylinder}} / R _{\text{wire}}}
    \,.
    \end{align}
\end{extracontent}

Last time we were looking at some particle detectors.
We are looking at a detector with a cylindrical shape --- a wire within a cylinder.

We saw that for a \(\sim \SI{2}{MeV}\) particle there will be roughly 200 emitted electrons.

The drift time for a \SI{1}{cm} detector will roughly be \SI{200}{\nano\second},
since the drift time is roughly \SI{5}{cm/\micro\second}.

This means that the shape of the pulse, after an RC high-pass filter, is
%
\begin{align}
\overline{V}(t) = \overline{R} \overline{C} \dv{V(t)}{t} \approx \overline{R} \overline{C}
\frac{ \delta V}{T_D} = \overline{R}\frac{\overline{C}}{C} \frac{ \delta q}{T_D}
\,.
\end{align}

The current will roughly be \(\delta q / T_D \approx \SI{0.16}{nA}\).
The change in tension is roughly \(\Delta V \sim I R \approx \SI{8}{nV}\).

So, we need an amplification mechanism.

The anodic wire needs to be very thin, so that we have a large electric field,
which means that we get amplification by the emission of secondary electrons.
This gain can be a factor \num{e5}!
This means we get a charge \(\delta q \approx N _{\text{pair}} e \times \text{gain}\).

We get \(\Delta V \sim \SI{0.8}{mV}\); with better systems we typically get millivolt currents.

We should also aim to reduce the capacitance of the detector!

At low values for the high voltage we are in the ionization regime; this means that we
see exactly the number of charges produced by the particle. This is the ionization regime.
\(\delta q (V) = \text{constant}\).

At higher voltages, we will be getting a certain gain: this is the proportional regime.
\(\delta q(V) = \alpha \delta q\).

At even higher voltages, we will get a nonlinear profile, with saturation.
This is the limited proportional regime.

At even higher voltages, we fully saturate: this is the Geiger-Muller regime.
Here we do not have any information about the particle, we just know that
something has passed through.

This all depends on the charge of the particle: for \(\alpha \) particle the \(\delta q\) is
always \(Z^2 = 4\) times higher.

We can use many of these gas detectors to figure out where a particle passed through.

If this is the case, we can also get trajectory information!
The delay between the arrival time of the particle ionization in different wires tells us about
how close to the center of each of them it passed.
If we have a star, trigger that's even better!

This kind of thing is used in LHC.

An alternative is to have many HV wires in the same chamber.
This is called a \emph{wire chamber}.

The spatial resolution can be computed as \(\sigma _x \approx v _{\text{drift}} \sigma _t\),
so if we have millisecond timing we can get a few hundreds of microns.

Another component is a \emph{quencher}.
Some electrons and ions produced might recombine, producing UV photons.
Those can then ionize the gas again, in a place which is unrelated.
So, we need to quench these UV photons (absorb them) so that they do not mess up
our measurement.

If we also have a magnetic field, the trajectory of the particle passing through
will be bent; this allows us to measure the momentum and charge of the particle, but
it will also curve the trajectories of the electrons.

What to do when the interaction cross-section is very low?
We can increase the density of the gas, or even make it a liquid.

Those can be for example liquid Argon or liquid Xenon Time Projection Chambers.

\subsection{Scintillators}

A fraction of the energy from a particle is emitted as light.
Atoms are ionized and then recombine; the UV light they emit thus is
called \emph{scintillation light}.

If the total energy lost is \(\Delta E\), and \(W\)
is the energy required to produce a scintillation photon (\(W \approx \SI{100}{eV}\)).

For a \SI{2}{MeV} particle, we get about 20000 photons.
The wavelength of this light depends on the energy states of the material.
Typically the emission of these happens within a few nanoseconds.

We need the material to be transparent to the scintillation photons,
but we need to contain it within a reflective material so that the photons are not
going everywhere.

The mechanism for the absorption of these visible or UV photons will be the photoelectric effect.

The quantum efficiency of the detector describes the fraction of the photons which are detected.

We need to give energy to the electron emitted by the photon!
It will have low, order-\SI{}{eV} energy.
The way this is typically done is through a series of dynodes.
We connect the HV supply to a series of resistors, and have a uniformly decreasing
voltage between the dynodes.
The gain will depend on the number of secondary electrons produced by the dynode chain
per incident electron, which is denoted as \(\alpha \).

The dependence is roughly a powerlaw as a function of the HV.
The system is roughly saturated when the current due to the secondary electrons
roughly equals the HV/\(R\) current.

These are \emph{photomultipliers}.

We will have a certain efficiency for our collection \(\epsilon _{\text{coll}}\), as well as
a quantum efficiency \(\epsilon _q\).

The signal will be
%
\begin{align}
N_\gamma \epsilon _q \epsilon _{\text{coll}} \times \text{gain}
\,.
\end{align}

Typical numbers are about \(N_ \gamma \approx \num{2e4}\), and both efficiencies at \SI{20}{\percent}.

With this, we get about \(N = 800\) photoelectrons.

The time required for the detection is a few nanoseconds for the emission,
a few nanoseconds for the propagation, and a further few nanoseconds for
the collection by the photomultiplier.
In the end, the current will be roughly \(I \approx eN / (\SI{100}{ns})\);

With a \SI{50}{\ohm} resistor, this means a voltage of \SI{70}{nV} times the gain.

In order to get to the millivolt regime, we need a gain on the order of a million.
So, if each dynode allows for a doubling of the electrons we need about 20.

With these kinds of detectors we can do nuclear spectroscopy.

\end{document}


\documentclass{article}
\usepackage{hyperref}
\usepackage[USenglish]{babel}
%\usepackage{csquotes}
%\usepackage{dirtytalk}
%https://perso.imt-mines-albi.fr/~gaborit/latex/latex-in-french.html
%\usepackage[english,francais]{babel}
%\usepackage[english,french]{babel}

%https://tex.stackexchange.com/questions/248788/the-very-basics-of-french-accents
%\documentclass[12pt]{amsart}

\usepackage[utf8]{inputenc}

%entiers sets https://texblog.org/2007/08/27/number-sets-prime-natural-integer-rational-real-and-complex-in-latex/
%\usepackage{amsfonts}
% or
\usepackage{amssymb}

%Majuscules accentuees https://www.xm1math.net/doculatex/caracteres_speciaux.html
\usepackage{eurosym}
\usepackage{systeme}
\usepackage{enumerate}

\usepackage{physics}

%https://tex.stackexchange.com/questions/304155/%C2%B1-symbol-in-text
\usepackage[
  separate-uncertainty = true,
  multi-part-units = repeat
]{siunitx}

%numerotation https://www.xm1math.net/doculatex/structure.html
\renewcommand{\thesubsection}{\Roman{subsection}}

%\title{\textbf{PROPERTIES OF EXPANDING UNIVERSES.}}

%https://stackoverflow.com/questions/4262294/remove-default-date-in-latex-article
\date{1st february 1966}

\begin{document}

%https://perso.imt-mines-albi.fr/~gaborit/latex/latex-in-french.html
%\renewcommand{\contentsname}{Sommaire}

%https://tex.stackexchange.com/questions/59460/custom-title-page-in-report-or-book-class
%\textcolor{other}{TRINITY HALL}
%differential https://tex.stackexchange.com/questions/225523/how-to-write-partial-differential-equation-ex-dq-dt-ds-dt-with-real-partial-d

\section{}
the field-equations is admissible, but in the direct-particle

interaction theory only those solutios of the field-equations

are admissible that satisfy the additional requirement :

%physics
$M_0(x) = \sum_{}^{} M^{(a)}(x) =  \sum_{}^{}  \int_{}^{}  G*(x,a)  \,da $

$ = \frac{1}{2}  \cdot \sum_{}^{}  \int_{}^{}  G_{ret.}(x,a)  \,da + \frac{1}{2}  \cdot \sum_{}^{}  \int_{}^{}  G_{adv.}(x,a)  \,da$

%= \[ \sum_{}^{} G*(x,a) \cdot \it{d}a \]   $

This requirement is highly restrictive ; it will be shown

that it is not satisfied for the cosmological solutions of

the Einstein field-equations, and it appears that it cannot

be satisfied for any models of the universe that either

contain an infinite amount of matter or undergo infinite

expansion.

\section{}The difficulty is similar to that occurring in

  Newtonian theory when it is recognized that the universe

  might be infinite.

  \section{}
  The Newtonian potential $\phi$ obeys the equation :

%latex complex conjugate https://tex.stackexchange.com/questions/304155/%C2%B1-symbol-in-text

\footnote{Written by Peter MOUEZA}
\end{document}


\chapter{Summary and Outlook}
For the operational phase of \gls{flute}, a stable electron energy enabling stable \gls{thz} energies will be vital to perform scientific experiments. At the start of the thesis, the stability of the electron gun was unsatisfactory. As the main source of the instability, the cooling system of the electron gun's body was identified.

This thesis shows that with a control system that interacts with the low power input signal of the klystron, it is possible to improve the stability by creating a closed-loop feedback system using readouts from the \gls{epics} control system as sensors and a controllable \gls{rf} attenuator in the signal path as actuator. The system transfer function (plant) between the attenuator and the power in the electron gun cavity shows $PT_2$ behavior, so control with a \gls{pid} controller is possible and its positive effects on the stability are shown.

With the controller it is possible to achieve the goal of reducing the variations in the cavity \gls{rf} power significantly from $\op{\%STD}=\SI{0.11559}{\percent}$ to $\op{\%STD}=\SI{0.0599}{\percent}$, which is equals an improvement by about a factor of two.

However the studies here also show the limitations of a traditional linear control system. The controller should be designed with a fast response time and sufficient integral gain to reject disturbances quickly. This however leads to small safety margins in the gain and phase response, which makes it likely for the control system to become unstable if system parameters change slightly. Also, the parameterization of the necessary measurement filter is a trade-off between stability of the control system and measurement noise rejection. The control system could be further optimized by switching to a totally different controller architecture, such as model predictive control, which exploits the identified plant transfer function but determines the output through an optimization process.

At the moment of writing, \gls{flute} is shut down. With \gls{flute} operational again, measurements of the electron energies before and after the \gls{linac} can be performed. The method currently used is based on the electron bunch, which is steered with an electromagnet by the Lorentz force (see \autoref{eq:fl}). By adjusting the electromagnet's coil current in such a way that the electron beam hits a camera screen in the center, the electron energy can be calculated from the coil current. With this destructive and slow process it will be possible to show how much the stabilization of the cavity \gls{rf} power actually improves the energies of the accelerated electrons and if the approach using the Faraday cup is an improvement over the cavity \gls{rf} power solution.

In the near future, both the electron gun and the klystron are to be upgraded to new versions. Switching to another gun and/or a different \gls{rf} system could lead to an entirely different behavior of the whole system, but the techniques described in this thesis are universally applicable and the control system can easily be modified for usage with different components.


\chapter{{\tt ETree}: Elimination and Front Trees}
\label{chapter:ETree}
\par
The {\tt ETree} object is used to model an elimination tree or a
front tree for a sparse factorization with symmetric structure.
The tree is defined over a set of vertices in a graph --- the graph
can be unit weight or non-unit weight.
A ``node'' in the tree can be a single vertex (in the context of
an elimination tree) or a group of vertices (as for a front tree).
\par
The tree information is stored as a {\tt Tree} object.
In addition there are three {\tt IV} objects.
One stores the total size of the nodes in the fronts,
one stores the size of the boundaries of the fronts,
and one stores the map from the vertices to the fronts.
\par
There is a great deal of functionality embodied into the {\tt ETree}
object.
Given an elimination tree or a front tree, one can extract the
permutation vectors (for the fronts or the vertices), extract a
multisector based on several criteria, compress the front tree in
several ways, justify the tree (order children of a node in
meaningful ways), evaluate metric vectors on the tree (heights,
depths, subtree accumulators).
\par
The front tree we obtain from a low-fill matrix ordering is usually
not the front tree that drives the factorization.
We provide three methods that transform the former into the latter.
One method merges the fronts together in a
way that adds logical zeros to their structure.
One method splits large fronts into smaller fronts.
One method combines these two functionalities.


\appendix
\chapter{Code}

All the datasets, the notebooks and the results obtained are available at this public link: \url{https://drive.google.com/drive/folders/0AM8tHyzDct5GUk9PVA}

\section{Closed set authorship attribution code}
In \autoref{lst:TPOTpipeline} we can see how we built our TPOT pipeline to get the classifier model we did use later on in the training process.

\begin{lstlisting}[frame=none,caption={TPOT pipeline generation.},captionpos=b,label=lst:TPOTpipeline]
\end{lstlisting}
\begin{python}
	!pip install -q tpot
	from tpot import TPOTClassifier, TPOTRegressor
	pipeline_optimizer = TPOTClassifier(generations=5, population_size=20, cv=5,
	random_state=42, verbosity=2, scoring='accuracy', config_dict='TPOT sparse')
	pipeline_optimizer.fit(tfidf_train, df_train['target'])
	print(pipeline_optimizer.score(tfidf_test, df_test['target']))
	pipeline_optimizer.export('tpot_exported_pipeline.py')
\end{python}

\autoref{lst:D2Vtraining} shows how we adapted doc2vec method to our task and the hyperparameter used when training doc2vec model. In the last lines of code of \autoref{lst:D2Vtraining} we can see how to extract features vectors from the doc2vec model and the documents.
\begin{lstlisting}[frame=none,caption={D2V training and features extraction.},captionpos=b,label=lst:D2Vtraining]
\end{lstlisting}
\begin{python}
	from gensim.models.doc2vec import TaggedDocument
	import gensim
	from tqdm import tqdm
	from gensim.models import Doc2Vec

	def tag_dataset(df):
	return df.apply(lambda r: TaggedDocument(words=only_remove_quoting_tokenizer(r['articles']), tags=[r.author]), axis=1)

	df_train_tagged = tag_dataset(df_train)
	df_test_tagged = tag_dataset(df_test)

	import multiprocessing

	cores = multiprocessing.cpu_count()
	print(cores)
	model_dmm = Doc2Vec(dm=1, dm_mean=1, vector_size=300, window=10, negative=5, min_count=1, workers=cores, alpha=0.065, min_alpha=0.065)
	model_dmm.build_vocab([x for x in tqdm(df_train_tagged.values)])

	model_dbow = Doc2Vec(dm=0, vector_size=300, negative=5, hs=0, min_count=2, sample = 0, workers=cores)
	model_dbow.build_vocab([x for x in tqdm(df_train_tagged.values)])

	d2v_model = model_dmm

	from sklearn import utils

	# time
	def train_d2v_model(model, df):
		for epoch in range(30):
			model.train(utils.shuffle([x for x in tqdm(df.values)]), total_examples=len(df.values), epochs=1)
			model.alpha -= 0.002
			model.min_alpha = model_dmm.alpha
		model.save(os.path.join(base_dir, 'd2v_{}_model.vec'.format(PROJECT_NAME)))

	def vec_for_learning(model, tagged_docs):
		sents = tagged_docs.values
		targets, regressors = zip(*[(doc.tags[0], model.infer_vector(doc.words, steps=20)) for doc in sents])
		return targets, regressors
	training_target, training_features = vec_for_learning(d2v_model, df_train_tagged)
	testing_target, testing_features = vec_for_learning(d2v_model, df_test_tagged)

\end{python}

In \autoref{lst:train_svm} we reported the code use to train the support vector machine with the features vectors chosen and how we evaluate the main metrics shown in chapter 6.

\begin{lstlisting}[frame=none,caption={Training SVM model and retrieve score metrics.},captionpos=b,label=lst:train_svm]
\end{lstlisting}
\begin{python}
	def double_pipeline():
		exported_pipeline = make_pipeline(
		make_union(
		FunctionTransformer(copy),
		SelectFwe(score_func=f_classif, alpha=0.004)
		),
		LinearSVC(C=10.0, dual=True, loss="squared_hinge", penalty="l2", tol=0.000001, max_iter=10)
		)
		set_param_recursive(exported_pipeline.steps, 'random_state', 42)
		return exported_pipeline

	def single_pipeline():
		exported_pipeline = LinearSVC(C=20.0, dual=True, loss="hinge", penalty="l2", tol=0.0001)
		if hasattr(exported_pipeline, 'random_state'):
			setattr(exported_pipeline, 'random_state', 42)
		return exported_pipeline

	exported_pipeline.fit(training_features, training_target)
	predicted = exported_pipeline.predict(testing_features)

	accuracy_result = accuracy_score(testing_target, predicted)
	precision_result = precision_score(testing_target, predicted, average='macro')
	recall_result = recall_score(testing_target, predicted, average='macro')
	f1_result = f1_score(testing_target, predicted, average='macro')
	print(f"Accuracy: {accuracy_result}\nPrecision: {precision_result}\nRecall: {recall_result}\nF1_macro: {f1_result}")
\end{python}

Finally, \autoref{lst:crossvalidation} shows the piece of code we used to cross validate our model just trained with $StratifiedShuffleSplit$. We chose this type of split when cross validating because we wanted to end up with the same number of samples in the training set and in the testing set overall and also for each authors.

\begin{lstlisting}[frame=none,caption={Cross validation for balanced class.},captionpos=b,label=lst:crossvalidation]
\end{lstlisting}
\begin{python}
	from sklearn.model_selection import StratifiedKFold, KFold, StratifiedShuffleSplit
	import numpy as np

	skf = StratifiedShuffleSplit(n_splits=10, test_size=0.5, random_state=42)
	for train, test in skf.split(X, y):
		print('train -  {}   |   test -  {}'.format(
		np.bincount(y[train]), np.bincount(y[test])))

	# evaluate model
	scores = cross_val_score(exported_pipeline, X, y, scoring='accuracy', cv=skf, n_jobs=-1)

	# report performance
	print('Accuracy: %.3f (%.3f)' % (mean(scores), std(scores)))
\end{python}

\section{Open set authorship attribution code}

In \autoref{lst:train_test_split_open} we can see the code for splitting the training set from the testing set documents in the open set authorship attribution scenario.

\begin{lstlisting}[frame=none,caption={Training and Testing set split for open set autorship attribution.},captionpos=b,label=lst:train_test_split_open]
\end{lstlisting}
\begin{python}
	# Even split 50 & 50 per author and document
	df_train = dataset.groupby('author').head(N_DOCS/2).reset_index(drop=True)
	if OPEN_SET:
		df_train = df_train[df_train.groupby('author').ngroup() < (NUM_AUTHORS-OPEN_SET_NUM_AUTHORS)]
	print_stats_dataset(df_train)
	df_train.head()

	# get difference between dataset and df_train for df_test
	df_test = pd.concat([dataset,df_train]).drop_duplicates(keep=False)
	print_stats_dataset(df_test)
	df_test.head()
\end{python}

\listoffigures
\listoftables


\subsection{Sharp Distance Sensor}

\begin{figure}[htbp]
 \centerline{\epsfysize = 2.0in\epsffile{sensor/distance.eps}}
 \caption{Sharp Distance Sensor}
 \label{distance}
\end{figure}

The Sharp GP2D12 Distance Sensor is capable of precisely measuring
distances to walls or objects, using near-infrared light.
Commercially, devices like these are used in a variety of places, from
automatic toilets and sinks to photocopiers; your robot can use it to
follow walls and avoid obstacles. This sensor is the only one which can detect things more than a few inches away---it has a useful range from about~$6.5''$ to several feet.
The package has two parts:

\begin{enumerate}
\item an emitter that emits a narrow beam of barely visible light; and
\item an array of detectors that measure the angle of the spot the
      emitter projects on the wall.
\end{enumerate}

Unlike other devices used in 6.270, this device supplies an analog
value on its own, without the use of a pull-up resistor.  Therefore,
to use the sensor, you must make a slight, reversible modification to
the Handy Board---cut the trace on the bottom of the main board that
connects an analog input to its pull-up resistor.  Please see a member
of the staff for help with this procedure.

The sensor does not give you the distance in any type of standard
unit.  Instead, the value read on the analog input it is connected to
varies smoothly from~0 to~255 as the distance decreases.  Tests have
found that the function
$$ f[n] = -3.16'' + { 950.'' \over 8.58+n } $$
gives an accurate estimate of the distance as a function of the analog
value~$n$, and that the reading is fairly independent of lighting,
object color, or battery power level.  However, the numeric parameters
may have to be recalibrated for each individual sensor if an accurate
measurement is desired.