% !TeX spellcheck = en_EN
%\documentclass[12pt,a4paper]{article}
%\usepackage{import}
%\subimport{../}{uebung.tex}
%
%%\toggletrue{showSolution}
%
%
%\title{\thetitle{}\\Exercise 4}
%\date{\WeeksAfter{3}}
%
%
%\begin{document}

\BoSSSopen{quickStartCNS/IsentropicVortex}
\graphicspath{{quickStartCNS/IsentropicVortex.texbatch/}}
%\BoSSSopen{IsentropicVortex}
%\graphicspath{{IsentropicVortex.texbatch/}}

\BoSSScmd{
///\section*{What's new}
///\begin{itemize}
/// \item running a simple simulation with the CNS solver
/// \item the important input data to solve the Euler equations
/// \item generating a simple mesh by using the \BoSSS{} internal mesher
/// \item the post-processing of the data, i.e. visualization in Paraview or VisIt
///\end{itemize}
///
///\subsection*{Prerequisites}
///\begin{itemize}
/// \item the \BoSSS{} framework
/// \item a visualization tool, e.g Paraview or VisIt
/// \item the knowledge of how to setup a database for \BoSSS{}
///\end{itemize}
///
///\section*{Problem statement}
///We only briefly describe the non dimensional Euler equations in 2D
/// \begin{equation*}
///\del{\vec{U}}{t}+\del{\vec{F}^c_j(\vec{U})}{x_j}= 0,
///\label{eq:euler_sys}
///\end{equation*}
///where $\vec{U}$ are the conserved flow variables and $\vec{F}^c_x$  are the convective fluxes, i.e.
///\begin{align*}
///\vec{U} = \begin{pmatrix}
///  \density{}\\
///  \momentum_i\\
///  \energy{}
///\end{pmatrix}, \quad \textrm{and} \quad
///\vec{F}^c_i = \begin{pmatrix}
///  \momentum_i\\
///  \momentum_i \velocity_j + \frac{1}{\heatCapacityRatio \reference{\Mach}^2}\pressure \delta_{ij}\\
///  \velocity_j \left(\energy{}+\pressure{}\right)
///\end{pmatrix}.
///\end{align*}
///Note: In our non dimensional equations, we introduce $\reference{\Mach}$.
///
///These Quick Start tutorials are aimed to show some of the main features of the compressible flow
///solver (Compressible Navier-Stokes (CNS)) in the \BoSSS{} framework. As already mentioned
///in the introduction, \BoSSS{} uses a C\# code based input data and interprets these in
///the \emph{REPL} fashion. This gives us more flexibility in the way how we can start a
///simulation. We can have the traditional way of defining an input file, where we define all
///important parameters in C\# code, or we can also use some predefined functions in the framework
///to generate our input data and manipulate them interactively in the \BoSSSpad{}.\\
///
///As an example, we will simulate the well known isentropic vortex for the Euler equations.
///\section{Isentropic vortex}
 }
\BoSSSexeSilent
\BoSSScmd{
restart;
 }
\BoSSSexeSilent
\BoSSScmd{
/// \subsection{Interactive mode}
/// We start with the interactive mode and load the namespace.
 }
\BoSSSexe
\BoSSScmd{
/// We create, resp. open a \BoSSS database:
var myDatabase = OpenOrCreateDefaultDatabase();
 }
\BoSSSexe
\BoSSScmd{
using CNS;
 }
\BoSSSexe
\BoSSScmd{
typeof(CNS.Program).Assembly.Location;
 }
\BoSSSexe
\BoSSScmd{
/// We load the input data from some function within the Framework.
/// The class \verb|ControlExamples| provides some predefined control sets for
/// different typical test cases, i.a. the isentropic vortex.
/// For the isentropic vortex, you have to specify
/// \begin{itemize}
/// \item path to a database (here: EMPTY path)
/// \item number of cells in each direction (here: 20)
/// \item DG order (here: 2)
/// \item advection velcoity of the vortex (here: 1.0)
/// \end{itemize}
int noOfCellsPerDirection = 20;       \newline
var c = ControlExamples.IsentropicVortex(myDatabase.Path,      \newline
\btab \btab \btab \btab \btab \btab \btab \btab \btab \btab  noOfCellsPerDirection,2,1.0);\newline
c.savetodb = true;       \newline
/// Now, we have a set of input data stored in our variable \verb|c| and we
/// can have a look at different parameters directly via \code{BoSSSpad}.
 }
\BoSSSexe
\BoSSScmd{
/// \subsection{How to define/change input data}
/// In this section we will walk you through the most important parameters for
/// running the test case. We start with the grid and use the ability of \BoSSS\
/// to generate simple grids with its own mesh generator. Once we start the simulation,
/// the control object \verb|c| is parsed and the grid defined by the \verb|GridFunc|
/// is generated on the fly and stored in the database. Here, we defined a
/// \verb|delegate| function which returns a uniform cartesian grid. First, we have to
/// define a 1-D array, which spans from -10 to 10 and is divided into the number
/// of cells, which we previously set to \verb|int noOfCellsPerDirection = 20|.
/// The function \verb|Grid2D.Cartesian2DGrid| generates a
/// uniform 2-D grid out of this array by using it for x and y direction
/// Additionally we specify periodic boundary conditions in x and y direction
/// by setting \verb|periodicX: true| and \verb|periodicY: true|. \\
c.GridFunc = delegate \{       \newline
   double[] nodes = GenericBlas.Linspace(-10, 10, noOfCellsPerDirection + 1);       \newline
   var grid = Grid2D.Cartesian2DGrid(nodes, nodes,       \newline
\btab \btab \btab \btab \btab \btab \btab \btab \btab  periodicX: true, periodicY: true);       \newline
   return grid;       \newline
\};
 }
\BoSSSexe
\BoSSScmd{
/// The \code{CNS} solver is able to solve the Euler and the compressible Navier-Stokes equations. By setting
c.ActiveOperators;
 }
\BoSSSexe
\BoSSScmd{
/// we only use the convective fluxes, i.e the Euler equations, and set it to
c.ConvectiveFluxType;
 }
\BoSSSexe
\BoSSScmd{
/// Note: Optimized means in this case, that this is the classical HLLC flux, but implemented in an optimized version. \\
/// As initial conditions, we choose the analytical solution, which can be found in various publications, e.g. Hu (2006).
/// The Mach number is set in the following:
c.MachNumber
 }
\BoSSSexe
\BoSSScmd{
/// Further, we have to define a simulation time, i.e
c.Endtime;
 }
\BoSSSexe
\BoSSScmd{
/// Finally, we need a time stepping scheme
c.ExplicitScheme;
 }
\BoSSSexe
\BoSSScmd{
/// of order
c.ExplicitOrder;\newline
/// to run the simulation.
 }
\BoSSSexe
\BoSSScmd{
/// These are all predefined input values, which were set by calling \verb|ControlExamples.IsentropicVortex(...)|.
/// Since we are in the interactiv mode, we can change them directly in the \code{BoSSSPad}.
/// For example, we can reduce the order of our timestepping scheme to 3,
/// because we only use DG order 2:
c.ExplicitOrder = 3;      \newline
c.ExplicitOrder;
 }
\BoSSSexe
\BoSSScmd{
/// Or we can change the Mach number to
c.MachNumber = 0.7;    \newline
c.MachNumber
 }
\BoSSSexe
\BoSSScmd{
/// \subsection{Run a simulation}
/// We adjusted our input values and now we can run a simulation.
/// In the interactive mode, we can simply execute \code{Run()} on the control
/// object, which will execute the solver:
c.PrintInterval = 5;\newline
var SI          = c.Run();
 }
\BoSSSexe
\BoSSScmd{
/// The \code{Run()} command finally returns a session info, which carries some
/// basic information on the solver run (mainly where ist was stored).
SI;
 }
\BoSSSexe
\BoSSScmd{
/// \subsection{Console mode}
/// We can also run this simulation in the ``traditional'' way, which most
/// of you are familiar with from other academical codes. We define an input file,
/// which is nothing else than the above C\# code. We can run it by calling
/// \verb|CNS.exe -c IsentropicVortex.cs|. You can find the input file in
/// ControlExamples folder in the doc directory.
 }
\BoSSSexe
\BoSSScmd{
/// \subsection{Postprocessing}
/// We saved our data in the database and lastly we want to postprocess it,
/// i.e visualize the individual fields like density, momentum or pressure.
/// Note: If you have run the simulation in the console mode, you now have to start
/// the \BoSSSpad{}.
/// In our example, we find the corresponding session in our first database as first session
//myDatabase.Sessions.First();
 }
\BoSSSexe
\BoSSScmd{
/// To convert data to the Tecplot format, we just need to export it:
//databases.First().Sessions.First().Export().Do()
 }
\BoSSSexe
\BoSSScmd{
/// We can open the folder directly by using
//databases.First().Sessions.First().OpenExportDirectory()
 }
\BoSSSexe
\BoSSScmd{
/// and here we find \verb|*plt| files with our data.
/// For more information about our databases and useful commands for postprocessing,
/// we refer to our tutorials about the database and the database command overview.
 }
\BoSSSexe


\subsection{Bertrand competition}

Each player decides what price to sell at.

Firms who price above the lowest have no sales. Prices converge to cost.


%**************************************************************
% Lab 11: Processor
%**************************************************************
\chapter{Processor}

\section{Purpose}

A \acf{CPU} is arguably one of the most important digital logic devices. \acp{CPU} are found in all computers and many other embedded logic devices. They are versatile circuits that can be used to control many processes and peripheral devices. The purpose of this lab is to lay the foundation of \ac{CPU} operation.

\subsection{A Definition}

When asked to define ``\ac{CPU}'' many students offer poetic definitions like ``it is the brain of the computer.'' This may be somewhat artistic but is not very helpful in defining \ac{CPU} for digital logic purposes. Here is a much better definition:

\begin{quote}
	A \acf{CPU} is a hardware device that is designed to translate binary codes stored in software into signals that control hardware. Thus, a \ac{CPU} is the interface between software and hardware.
\end{quote}

The purpose of this lab is to demonstrate how binary codes can be used to manipulate hardware devices, like registers and adders, to move data through a circuit and accomplish a purpose. While the circuit developed in this lab is not a practical start for a \ac{CPU} is does serve as an introduction to the concept of hardware manipulation by software codes.

\section{Procedure}

This processor contains only three subcircuits connected by several bus lines and each of the three subcircuits are reasonably simple to understand.

\subsection{Arithmetic-Logic Unit}

This processor starts with a simple \ac{ALU}, as in Figure \ref{fig:11-01}.

\begin{figure}[H]
	\centering
	\includegraphics[width=\maxwidth{.95\linewidth}]{gfx/11-01}
	\caption{Simple ALU}
	\label{fig:11-01}
\end{figure}

To be sure, this \ac{ALU} is not very complex but uses the same principles developed in Lab \ref{lab04}, \nameref{lab04}. It contains only three arithmetic functions, increment, add, and negate; four logic functions, \texttt{AND}, \texttt{OR}, \texttt{XOR}, \texttt{NOT}; and one constant zero output. There are two data input ports but note that some of the functions only use the lower input, and one output port. The multiplexer determines which of the functions will be connected to the output and that is controlled by a signal named \textit{ALUCtl}.

The \ac{ALU} is then expanded somewhat to make it usable in a \ac{CPU}. For simplicity, Figure \ref{fig:11-02} shows only the left side of the ALU.

\begin{figure}[H]
	\centering
	\includegraphics[width=\maxwidth{.95\linewidth}]{gfx/11-02}
	\caption{Left Side of ALU}
	\label{fig:11-02}
\end{figure}

Figure \ref{fig:11-03} shows the right side of the ALU.

\begin{figure}[H]
	\centering
	\includegraphics[width=\maxwidth{.95\linewidth}]{gfx/11-03}
	\caption{Full ALU}
	\label{fig:11-03}
\end{figure}

The simple \ac{ALU} functions are found in the center of Figure \ref{fig:11-02}. However, what started as \textit{DataInA} has been replaced by a register named \textit{ALUBuffer}.\footnote{IMPORTANT NOTE: All registers in this Processor circuit are triggered on the Falling Edge of the clock. The reason for this will become evident when the circuit is tested.} The \textit{ALUBuffer's} inputs are from Tunnels (\textit{Wiring} library) because those inputs are used in more than one location in the subcircuit.\footnote{Tunnels are used extensively in this circuit to simplify the diagrams and aid in tracing signals.}

The \ac{ALU} output is routed through a register named \textit{Acc}, for \textit{Accumulator}, which is the commonly-used name for the \ac{ALU} output in a \ac{CPU} circuit.

On the left side of the subcircuit are the three input ports. \textit{DataIn} is an eight-bit number that is sent to both the \textit{ALUBuffer} and the lower \textit{DataIn} bus. The \textit{ALUCtl} signal is split into two components. Bits 0-2 are sent to the multiplexer to select which of the eight functions will be output. Bit 3 of the \textit{ALUCtl} signal is sent to the \textit{AccEna} tunnel and when that is high the \textit{Acc} register will be enabled but when that signal is low then the \textit{ALUBuffer} register will be enabled. Finally, the clock input is sent to both registers.

\subsection{General Registers}

A \ac{CPU} must have several general registers available to hold data temporarily while an instruction is being carried out. For example, it may be necessary to hold the \textit{Acc} output until it is needed in a later step so that value can be stored in a register and then recovered when needed.

The processor circuit being built in this lab has four general registers. Figure \ref{fig:11-04} illustrates the \lstinline[columns=fixed]|GenReg| subcircuit.

\begin{figure}[H]
	\centering
	\includegraphics[width=\maxwidth{.95\linewidth}]{gfx/11-04}
	\caption{General Registers}
	\label{fig:11-04}
\end{figure}

The \lstinline[columns=fixed]|GenReg| subcircuit does not require any novel digital logic concepts. Starting on the left side of the circuit:

\begin{itemize}
	\item \textit{DataIn} is connected to the data bus and is the main input port for the registers. Note that \textit{DataIn} is connected to the \textit{Data} port on all four registers.
	\item The register that actually stores the input data is determined by the Decoder (\textit{Plexers} library) in the lower left corner of the subcircuit. The two low-order bits from the \textit{RegSel} signal activate one of the output lines from the Decoder and that line is tied to the Write Enable port of the register. On the next clock pulse that register will lock in the data present on the \textit{DataIn} port.
	\item The outputs from all of the registers are wired to a Multiplexer (\textit{Plexers} library). The select bits from the Decoder that are used to select the storage register are also used to select the register output line which is, in turn, wired to the \textit{DataOut} port.
	\item The high-order bit from the \textit{RegSel} control signal is used to determine if data are stored to or read from a register. When that bit is high the decoder is active and will select a storage register but when that bit is low the output multiplexer will be activated and send a register's stored value to the output port.
\end{itemize}

\subsection{Control}

The \lstinline[columns=fixed]|Control| subcircuit in this device is very simple and could, in all actuality, be eliminated. However, in a true \ac{CPU} the \lstinline[columns=fixed]|Control| subcircuit is rather complex and critical to the operation of the circuit so a \lstinline[columns=fixed]|Control| subcircuit is included in this lab as an example. Figure \ref{fig:11-05} illustrates the \lstinline[columns=fixed]|Control| subcircuit.

\begin{figure}[H]
	\centering
	\includegraphics[width=\maxwidth{.95\linewidth}]{gfx/11-05}
	\caption{Control Subcircuit}
	\label{fig:11-05}
\end{figure}

The \lstinline[columns=fixed]|Control| subcircuit includes a nine-bit input named \textit{mCode} (for ``Microcode''). That input is latched by a register\footnote{Note, as an exception to the other registers in the Processor circuit, the register in the control subcircuit must be set to trigger on the leading edge of the clock rather than the falling edge.} and the output of that register is split into three components.

\begin{description}
	\item[Bits 0-3] These are the \ac{ALU} control bits and they are sent to the \lstinline[columns=fixed]|ALU| subcircuit.
	\item[Bits 4-6] These are the register control bits and are sent to that subcircuit.
	\item[Bits 7-8] These are the \textit{dBus} (``Data Bus'') control bits. The data bus is found in the \lstinline[columns=fixed]|main| circuit and carries the data to each of the subcircuits. The dBus control is just a multiplexer that controls which subcircuit's output has control of the data bus.
\end{description}

\subsection{Main}

The \lstinline[columns=fixed]|main| circuit ties the three subcircuits together with three control busses and one data bus. Figure \ref{fig:11-06} illustrates the \lstinline[columns=fixed]|main| circuit.

\begin{figure}[H]
	\centering
	\includegraphics[width=\maxwidth{.95\linewidth}]{gfx/11-06}
	\caption{Main Circuit}
	\label{fig:11-06}
\end{figure}

There are no novel digital logic functions used in this circuit. The first input is \textit{mCode} which is the microcode used to control the flow of data in the dBus (``data bus''). the other input, \textit{LdImm} (``Load Immediate'') can contain an eight-bit number that is to be loaded into one of the registers for processing. In a full \ac{CPU} that input would be wired to a \ac{RAM} device.

\subsection{Testing the Circuit}

The circuit should be tested by inputting these signals and observing the output.

\subsubsection{Copy LdImm To R0}
%Checked
Enter some value in the \textit{LdImm} input port, set the \textit{mCode} input to 101000000 (the first three values in the table below), and then pulse the \textit{clk}. When completed, the \textit{dBus} and \textit{R0} should both contain the value of the \textit{LdImm} port.

\begin{table}[H]
	\sffamily
	\newcommand{\head}[1]{\textcolor{white}{\textbf{#1}}}
	\begin{center}
		\rowcolors{2}{gray!10}{white} % Color every other line a light gray
		\begin{tabular}{ccccl}
			\textbf{dBus} & \textbf{Reg} & \textbf{ALU} & \textbf{dBus} & \textbf{Notes} \\
			10 & 100 & 0000 & LdImm & R0 <- LdImm \\
		\end{tabular}
	\end{center}
	\caption{R0 <- LdImm}
	\label{tab:11-01}
\end{table}

\subsubsection{Copy LdImm To R1}
% Checked
Enter some value in the \textit{LdImm} input port, set the \textit{mCode} input to 101010000 (the first three values in the table below), and then pulse the \textit{clk}. When completed, the \textit{dBus} and \textit{R1} should both contain the value of the \textit{LdImm} port.

\begin{table}[H]
	\sffamily
	\newcommand{\head}[1]{\textcolor{white}{\textbf{#1}}}
	\begin{center}
		\rowcolors{2}{gray!10}{white} % Color every other line a light gray
		\begin{tabular}{ccccl}
			\textbf{dBus} & \textbf{Reg} & \textbf{ALU} & \textbf{dBus} & \textbf{Notes} \\
			10 & 101 & 0000 & LdImm & R1 <- LdImm
		\end{tabular}
	\end{center}
	\caption{R1 <- LdImm}
	\label{tab:11-02}
\end{table}

\subsubsection{Copy LdImm To ALUbuf}
%Checked
Enter some value in the \textit{LdImm} input port, set the \textit{mCode} input to 100000000 (the first three values in the table below), and then pulse the \textit{clk}. When completed, the \textit{dBus} and \textit{ALUbuf} should both contain the value of the \textit{LdImm} port.

\begin{table}[H]
	\sffamily
	\newcommand{\head}[1]{\textcolor{white}{\textbf{#1}}}
	\begin{center}
		\rowcolors{2}{gray!10}{white} % Color every other line a light gray
		\begin{tabular}{ccccl}
			\textbf{dBus} & \textbf{Reg} & \textbf{ALU} & \textbf{dBus} & \textbf{Notes} \\
			10 & 000 & 0000 & LdImm & ALU <- LdImm
		\end{tabular}
	\end{center}
	\caption{ALU <- LdImm}
	\label{tab:11-03}
\end{table}

\subsubsection{Increment R0}

\marginpar{Use the LdImm function to initialize R0.}Incrementing the value in R0 requires two steps. Set the \textit{mCode} input to the first three values in the table below and pulse the \textit{clk} for each of the steps. When completed, \textit{R0} will contain the original value of the \textit{R0}$ +1 $.

\begin{table}[H]
	\sffamily
	\newcommand{\head}[1]{\textcolor{white}{\textbf{#1}}}
	\begin{center}
		\rowcolors{2}{gray!10}{white} % Color every other line a light gray
		\begin{tabular}{ccccl}
			\textbf{dBus} & \textbf{Reg} & \textbf{ALU} & \textbf{dBus} & \textbf{Notes} \\
			01 & 000 & 1000 & R0 & Acc <- R0+1 \\
			00 & 100 & 0000 & Acc & R0 <- Acc \\
		\end{tabular}
	\end{center}
	\caption{R0 <- Inc(R0)}
	\label{tab:11-04}
\end{table}

\subsubsection{Add R0 And R1, Store In R0}

\marginpar{Use the LdImm function to initialize R0 and R1.}Adding the values of \textit{R0} and \textit{R1} and storing the result in \textit{R0} requires three steps. Set the \textit{mCode} input to the first three values in the table below and pulse the \textit{clk} for each of the steps. When completed, the sum of the original values of \textit{R0} and \textit{R1} will be stored in \textit{R0}.

\begin{table}[H]
	\sffamily
	\newcommand{\head}[1]{\textcolor{white}{\textbf{#1}}}
	\begin{center}
		\rowcolors{2}{gray!10}{white} % Color every other line a light gray
		\begin{tabular}{ccccl}
			\textbf{dBus} & \textbf{Reg} & \textbf{ALU} & \textbf{dBus} & \textbf{Notes} \\
			01 & 001 & 0001 & R1 & ALU <- R1 \\
			01 & 000 & 1001 & R0 & Acc <- R0 + R1 \\
			00 & 100 & 0001 & Acc & R0 <- Acc
		\end{tabular}
	\end{center}
	\caption{R0 <- R0 + R1}
	\label{tab:11-05}
\end{table}

\subsubsection{Subtract R1 From R0, Store In R0}

\marginpar{Use the LdImm function to initialize R0 and R1.}Subtracting the value of \textit{R1} from \textit{R0} and storing the result in \textit{R0} requires four steps. Set the \textit{mCode} input to the first three values in the table below and pulse the \textit{clk} for each of the steps. When completed, the difference of the original values of \textit{R0} and \textit{R1} will be stored in \textit{R0}.

\begin{table}[H]
	\sffamily
	\newcommand{\head}[1]{\textcolor{white}{\textbf{#1}}}
	\begin{center}
		\rowcolors{2}{gray!10}{white} % Color every other line a light gray
		\begin{tabular}{ccccl}
			\textbf{dBus} & \textbf{Reg} & \textbf{ALU} & \textbf{dBus} & \textbf{Notes} \\
			01 & 000 & 0010 & R0 & ALUbuf <- R0 \\
			01 & 001 & 1010 & R1 & Acc <- \textasciitilde R1 \\
			00 & 100 & 1001 & R0-R1 & dBus <- Acc \\
			00 & 100 & 0111 & dBus+1 & R0 <- R0 - R1
		\end{tabular}
	\end{center}
	\caption{R0 <- R0 - R1}
	\label{tab:11-06}
\end{table}

\subsubsection{Copy R0 to R1}

\marginpar{Use the LdImm function to initialize R0.}Copying the value of \textit{R0} to \textit{R1} requires four steps. Set the \textit{mCode} input to the first three values in the table below and pulse the \textit{clk} for each of the steps. When completed, the value of \textit{R0} will be stored in \textit{R1}.

\begin{table}[H]
	\sffamily
	\newcommand{\head}[1]{\textcolor{white}{\textbf{#1}}}
	\begin{center}
		\rowcolors{2}{gray!10}{white} % Color every other line a light gray
		\begin{tabular}{ccccl}
			\textbf{dBus} & \textbf{Reg} & \textbf{ALU} & \textbf{dBus} & \textbf{Notes} \\
			00 & 000 & 1111 & 0 & dBus <- 0 \\
			00 & 000 & 0100 & 0 & ALU <- dBus \\
			01 & 000 & 1100 & Acc & Acc <- ALU OR R0 \\
			00 & 101 & 0111 & Acc & R1 <- Acc
		\end{tabular}
	\end{center}
	\caption{R1 <- R0}
	\label{tab:11-07}
\end{table}

\subsubsection{Swap R0 And R1}

\marginpar{Use the LdImm function to initialize R0 and R1.}Swapping the values of \textit{R0} and \textit{R1} requires 12 steps. Set the \textit{mCode} input to the first three values in the table below and pulse the \textit{clk} for each of the steps. When completed, the values of \textit{R0} and \textit{R1} will exchanged.

\begin{table}[H]
	\sffamily
	\newcommand{\head}[1]{\textcolor{white}{\textbf{#1}}}
	\begin{center}
		\rowcolors{2}{gray!10}{white} % Color every other line a light gray
		\begin{tabular}{ccccl}
			\textbf{dBus} & \textbf{Reg} & \textbf{ALU} & \textbf{dBus} & \textbf{Notes} \\
			00 & 000 & 1111 & 0 & dBus <- 0 (Move R0 to R2)\\
			00 & 000 & 0100 & 0 & ALU <- dBus \\
			01 & 000 & 1100 & Acc & Acc <- ALU OR R0 \\
			00 & 110 & 0111 & Acc & R2 <- Acc \\
 			& & & & \\ %Empty line

			00 & 000 & 1111 & 0 & dBus <- 0 (Move R1 to R0)\\
			00 & 000 & 0100 & 0 & ALU <- dBus \\
			01 & 001 & 1100 & Acc & Acc <- ALU OR R1 \\
			00 & 100 & 0111 & Acc & R0 <- Acc \\
 			& & & & \\ %Empty line

			00 & 000 & 1111 & 0 & dBus <- 0 (Move R2 to R1)\\
			00 & 000 & 0100 & 0 & ALU <- dBus \\
			01 & 010 & 1100 & Acc & Acc <- ALU OR R2 \\
			00 & 101 & 0111 & Acc & R1 <- Acc
		\end{tabular}
	\end{center}
	\caption{R0 <-> R1}
	\label{tab:11-08}
\end{table}

\section{About Programming Languages}

The codes that were input for the last example (swap \textit{R0} and \textit{R1}) would create the following program.

\begin{Verbatim}[frame=lines,
xleftmargin=10mm,
xrightmargin=10mm]
000001111
000000100
010001100
001100111
000001111
000000100
010011100
001000111
000001111
000000100
010101100
001010111
\end{Verbatim}

This group of instructions would be considered ``CPU Microcode,'' which is a very highly specialized form of programming. It is the code that is built into a \ac{CPU} circuit and it determines what gates, registers, and other devices are active for each step of the code. When Intel, AMD, Motorola, or other manufacturers create a new \ac{CPU}, one of their main challenges is creating the microcode that will, for example, ``add the contents of register one to the contents of register two and store the result in register zero.'' The microcode must be able to activate and deactivate various devices within the \ac{CPU} so data appear on the appropriate bus at the right time in order to achieve the objective. Normally, microcode steps must be executed over several clock cycles in order to do a single job. For example, in one clock cycle the contents of register one may be placed on the data bus, the next clock cycle will load that data into the ALU register, and so forth until the entire process is complete.

Microcode is usually stored in \ac{ROM} that is built into the \ac{CPU}. This is typically called ``firmware'' since it is a string of ones and zeros, like software, but it cannot be changed, like hardware.

It is important to keep in mind the difference between instructions contained in a software program (like Word) and those contained in microcode. A single instruction in software is interpreted and executed by the \ac{CPU} using, perhaps, dozens of microcode steps. As an example, the software may want to move a single byte from \ac{RAM} to the video card. The \ac{CPU} may process that instruction by first moving the byte from \ac{RAM} to register one and then moving it from there to the video card's input register and then activating the video card input function. Those moves may require several clock cycles as various multiplexers and other devices are activated in the correct sequence to move the data to its destination.

A software program, like Word, is nothing more than a series of ones and zeros, organized into groups, commonly 64 in modern computers. Each group of bits forms a single ``word'' of information; or a single instruction which would then be used by the \ac{CPU} to trigger a microcode sequence. When viewed at the level of ones and zeros, a software program is said to be in ``machine code,'' and could look something like the following (note, only the first 32 bits of each word are shown).

\begin{Verbatim}[frame=lines,
xleftmargin=10mm,
xrightmargin=10mm]
10010100101100101001101011001010
01101001101011000111101011101011
00011011110010000111010111100101
\end{Verbatim}

If a programmer could master machine code, then those programs would be as concise and efficient as possible since they would be written in machine code the \ac{CPU} can execute directly. Of course, as it is easy to imagine, no one actually writes machine code due to its complexity.

The next level higher than machine code is called ``Assembly'' code. Assembly uses easy-to-remember abbreviations to represent the various \ac{CPU} instructions available; and it looks something like this:

\begin{Verbatim}[frame=lines,
xleftmargin=10mm,
xrightmargin=10mm]
INP
STA FIRST
INP
STA SECOND
LDA FIRST
SUB SECOND
OUT
HLT
FIRST DAT
SECOND DAT
\end{Verbatim}

Once the program has been written in Assembly, it must be ``assembled'' into machine code before it can be executed. An assembler is a fairly simply program that converts a file containing assembly codes into machine codes that can be executed by the \ac{CPU}.

Many programming languages have been developed that are considered ``higher'' than Assembly; for example, C++, Java, and Visual Basic. These languages tend to be easy to master and can enable a programmer to quickly create very complex programs. Programs written in each of these languages must be compiled, or changed into machine code, before they can be executed. Here is an example Java program:

\begin{Verbatim}[frame=lines,
xleftmargin=10mm,
xrightmargin=10mm]
public class HelloWorldExample{
  public static void main(String args[]){
  System.out.println("Hello World !");
  }
}
\end{Verbatim}

In the end, while there are dozens of different programming languages, they are all designed to be reduced into a series of machine codes which the \ac{CPU} can then execute.

\section{Challenge}

Using the examples in the ``Testing the Circuit'' section, create the microcode necessary to carry out these functions:

\begin{enumerate}
	\item Store the value contained in \textit{LdImm} in \textit{R2} (\textit{R2} <- \textit{LdImm}). (Assume that \textit{LdImm} is pre-loaded with the value to store.)

	\item Store the value contained in \textit{LdImm} in \textit{R3} (\textit{R3} <- \textit{LdImm}). (Assume that \textit{LdImm} is pre-loaded with the value to store.)

	\item Store the 2s complement of the value in \textit{R0} back into \textit{R0} (\textit{R0} <- \textasciitilde \textit{R0}). The subtraction example will help with this function.

	\item Store the bitwise NOT of the value in \textit{R0} back into \textit{R0} (\textit{R0} <- \textit{R0'}).
\end{enumerate}

\section{Deliverable}

To receive a grade for this lab, build the Processor circuit and then complete the Challenge. Be sure the standard identifying information is at the top left of the Processor \lstinline{main} circuit, similar to:

\bigskip
% The minipage environment keeps the three lines together - no page break.
\begin{minipage}{\linewidth}
	\begin{verbatim}
	George Self
	Lab 11: Processor
	April 5, 2018
	\end{verbatim}
\end{minipage}
\bigskip

Save the Processor circuit in a file with this name: \textit{Lab11\_Processor}. Complete the code required in the Challenge and store that in a text file with the name \textit{Lab11\_Code.txt}. Submit both files for grading.


\subsection{Locally compact spaces}


\subsection{Lévy's continuity theorem}


%%%%%%%%%%%%%%%%%%%%%definitions%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\input{../../doc/related_pages/header.tex}
\input{../../doc/related_pages/newcommands.tex}
\usepackage{minted}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%DOCUMENT%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}

\title{The esol project}
\author{M.~Held}
\maketitle

\begin{abstract}
  This is a program for 2d isothermal full-f gyro-fluid turbulence simulations
that cover the edge and scrape off layer and include different treatments of the
polarization charge
\end{abstract}

\section{Equations}
Currently we implemented $4$ slightly different sets of equations. $n$ is the
electron density, $N$ is the ion gyrocentre density. $\phi$ is the electric
potential. We
use Cartesian coordinates $x$, $y$.
\subsection{Models}
\subsubsection{Full-F gyro-fluid models}
The full-f models ("ff-O2-OB" \& "ff-lwl-OB" \& "ff-lwl" \& "ff-O2") share the
same evolution equations
\begin{subequations}
\begin{align}
 \frac{\partial n}{\partial t}     &=
    \frac{1}{B}\{ n, \phi\}
  + \kappa n\frac{\partial \phi}{\partial y}
  -\kappa \frac{\partial n}{\partial y} + \Lambda_{n,\parallel}
  - \nu \Delta_\perp^2 n  \\
  \frac{\partial N}{\partial t} &=
  \frac{1}{B}\{ N, \psi\}
  + \kappa N\frac{\partial \psi}{\partial y}
  + \tau \kappa\frac{\partial N}{\partial y} + \Lambda_{N,\parallel}-\nu
\Delta_\perp^2 N \\
   \vec{\nabla}\cdot \vec{P}_2 &= \Gamma_1 N-n
\end{align}
\end{subequations}
and are based upon a ``radially'' varying magnetic field magnitude
\begin{align}
 B(x)^{-1} = \kappa x +1-\kappa X
\end{align}
The full-f models differ only in the treatment the  polarization terms
\(\psi_2\) and \(\vec{P}_2\), given in Sec.~\ref{sec:polarization}
%%%%%
\subsubsection{Polarization and FLR terms}
\label{sec:polarization}
The FLR and polarization operators enter the gyro-fluid potential (\(\psi)\) as
well as the polarization density.
The operators and gyro-fluid potential are
\begin{align}
 \Gamma_1 &= ( 1- \tau/2 \Delta_{\perp})^{-1} &
 \Gamma_0 &= ( 1- \tau\Delta_{\perp})^{-1} &
   \psi = \Gamma_1 \phi + \psi_2
\end{align}
The  (negative) polarization charge is~\cite{Held2020}
\begin{align}
  \vec{\nabla}\cdot \vec{P}_2 &=
\begin{cases}
-\frac{N_0}{B_0^2}\Delta_{\perp} \phi ,
        &\ \text{if "ff-lwl-OB"} \\
-\frac{N_0}{B_0^2}\Gamma_0\Delta_{\perp} \phi,
      &\ \text{if "ff-O2-OB"} \\
-\nabla\cdot \left(\frac{N}{B^2} \nabla_\perp \phi\right)
       &\ \text{if "ff-lwl"} \\
-\sqrt{\Gamma_0}\nabla\cdot \left(\frac{N}{B^2} \nabla_\perp\sqrt{\Gamma_0}
\phi\right)
         &\ \text{if "ff-O2"}
\end{cases}
\end{align}
The polarization part of the gyro-fluid potential is
\begin{align}
\psi_2&=
\begin{cases}
0 ,
        &\ \text{if "ff-lwl-OB"} \\
0,
      &\ \text{if "ff-O2-OB"} \\
- \frac{1}{2} \frac{(\nabla\phi)^2}{B^2}
       &\ \text{if "ff-lwl"} \\
- \frac{1}{2} \frac{(\nabla\sqrt{\Gamma_0}\phi)^2}{B^2}
         &\ \text{if "ff-O2"}
\end{cases}
\end{align}
\subsubsection{Closure of the parallel dynamics}
\label{sec:parallelclosure}
The closure terms for the parallel dynamics exploit a two region
approach~\cite{HeldPhD}: a closed field line and an open field line region. The
transition between this regions is mimiced by the damping function \(
h_{\pm}(x)\)
where \(h_{+}\) is a polynomial Heaviside function (cf. feltor docu) and the
\(-\) refers to its reflection in x-direction. The polynomial Heaviside function
parameters are \(x_s\) and \(\sigma_s\).
Here, \(x_s\) represents the position of the separatrix and \(\sigma_s\) is the
width of the transition.
\\
The complete parallel closure consists then of two contributions:
\begin{align}
 \Lambda_{n,\parallel} &= \sum_{b \in \left\{+,-\right\}
}\Lambda_{n,\parallel,b} &
 \Lambda_{N,\parallel} &= \sum_{b \in \left\{+,-\right\} }
\Lambda_{N,\parallel,b}
\end{align}

\paragraph{Edge:} In the edge region we take the modified Hasegawa-Waktani
closure~\cite{Held2018}
\begin{align}
 \Lambda_{n,\parallel,-} &= \alpha h_{-}(x) \left[\widetilde{\phi} -
\widetilde{\ln(n)} \right] \\
 \Lambda_{N,\parallel,-} &= 0
\end{align}
with the fluctuation given by \(\widetilde{f} := f - \langle f\rangle_y\) and
the y-average \(\langle f\rangle_y:= \int dy f / L_y\). The adiabaticity
parameter is defined as \(\alpha := T_{e,\parallel}
k_\parallel^2/(\eta_\parallel e^2 n_{e,0} \Omega_{i,0} )\).

\paragraph{Scrape-off-Layer:} In the scrape off layer we assume Bohm sheath
boundary conditions~\cite{Mosetto2015}~\footnote{Note that strictly speaking the
boundary conditions for the density and electric potential are Neumann, in
particular \(\partial_s n_e (\vec{x}) |_{\pm L_\parallel /2 } =0 \) and
\(\partial_s  n_e (\vec{x}) |_{\pm L_\parallel /2 } = 0\).}
\begin{align}
n_e (x,y,\pm L_\parallel /2 ) &= n_e (\vec{x}) &
\phi (x,y,\pm L_\parallel /2 ) &= \phi (\vec{x})\\
 u_e (x,y,\pm L_\parallel /2 ) &= \pm \exp{(\Lambda_{sh} - \phi)} &
 U_i (x,y,\pm L_\parallel /2 ) &= \pm\sqrt{1+\tau}
\end{align}
where we introduced the constant (also known as sheath or Bohm potential)
\(\Lambda_{sh} := \ln \sqrt{m_i/(2 \pi m_e)} = \ln  (1/\sqrt{|\mu_e| 2 \pi})\).
With this we obtain for the closure terms~\cite{HeldPhD}
\begin{align}
 \Lambda_{n,\parallel,+} &:= -h_{+}(x) n \lambda \exp{(\Lambda_{sh} - \phi)} \\
 \Lambda_{N,\parallel,+} &:=  -\sqrt{1 + \tau} \lambda \Gamma_1^{-1} ( h_{+}(x)
n)
\end{align}
with the so called sheath dissipation parameter \(\lambda =
\rho_s/L_\parallel\).
Note that this results into the following term in the vorticity density equation
\begin{align}
 \Lambda_{\mathcal{W},\parallel,+} := \Gamma_1\Lambda_{N,\parallel,+} -
\Lambda_{n,\parallel,+} = -\lambda  h_{+}(x)  n \sqrt{1 + \tau} \left[1  -
\frac{1}{\sqrt{1 + \tau}}\exp{(\Lambda_{sh} - \phi)} \right]
\end{align}
\subsubsection{Sources}
The particle source is related to the the ion gyro-center source
and the electric potential via the transformation rule
\begin{align}
 S_n =\Gamma_1 S_N +
 \begin{cases}
0,
        &\ \text{if "ff-lwl-OB"} \\
0,
      &\ \text{if "ff-O2-OB"} \\
\nabla\cdot \left(\frac{S_N}{B^2} \nabla_\perp \phi\right)
       &\ \text{if "ff-lwl"} \\
\sqrt{\Gamma_0}\nabla\cdot \left(\frac{S_N}{B^2} \nabla_\perp\sqrt{\Gamma_0}
\phi\right)
         &\ \text{if "ff-O2"}
\end{cases}
\end{align}
Instead, we could use the long wavelength approximation \(
S_N =(1+\tau/2 \Delta_\perp) S_n + \vec{\nabla} \cdot \left(\frac{S_n}{B^2}
\vec{\nabla}_\perp \phi\right)\). However this transformation rule is not exact
and care has to be taken when short wavelength structures arise! \\
Another possibility is to neglect the polarization charge term in the exact transformation rule, which results in a vanishing source term in the evolution equation of the polarization charge density.
\paragraph{Forced profile (``forced'')}
The following source forces the poloidally averaged profile to a prescribed profile in a limited region if the averaged profile is below the prescribed profile.
\begin{align}
 S_N := \omega_s p \Theta\left(p \right)
\end{align}
with \(p = h_s (n_{prof,s} - \langle N \rangle_y)\) with \(h_s\) a polynomial heaviside function.

\paragraph{Constant influx (``flux'')}
\begin{align}
 S_N := \omega_s n_{prof,s}
\end{align}
with the source profile function
\begin{align}
 n_{prof,s}&:=
 \begin{cases}
   e^{1+\left(\frac{(x-x_s)^2}{2 \sigma_s^2}-1\right)^{-1}}, &\frac{(x-x_s)^2}{2
\sigma_s^2}<1  \\
   0, & else
 \end{cases}
\end{align}
with \(x_s:= l_x  f_s\)
\subsection{Initialization}
We follow the strategy to enforce the initial fields of the physical variables,
the electron density \(n\) and the electric potential \(\phi\), in order to
compute the initial ion gyro-center density.
\subsubsection{Non-rotating Gaussian ("blob")}
Initialization of $n$ is a Gaussian
\begin{align}
    n(x,y,0) &= 1 + A\exp\left( -\frac{(x-X)^2 + (y-Y)^2}{2\sigma^2}\right) \\
    \phi(x,y)&=const.
\end{align}
where $X = p_x l_x$ and $Y=p_yl_y$ are the initial centre of mass position
coordinates, $A$ is the amplitude and $\sigma$ the
radius of the blob.
We initialize
\begin{align}
    N &= \Gamma_1^{-1} n
\end{align}
\subsubsection{Gaussian with zero polarization charge density("blob")}
Initialization of $n$ is a Gaussian
\begin{align}
    n(x,y,0) &= 1 + A\exp\left( -\frac{(x-X)^2 + (y-Y)^2}{2\sigma^2}\right) \\
\end{align}
where $X = p_x l_x$ and $Y=p_yl_y$ are the initial centre of mass position
coordinates, $A$ is the amplitude and $\sigma$ the radius of the blob. We
initialize then
\begin{align}
    N &= n
\end{align}
so that the total polarization charge vanishes  \(\vec{\nabla}\cdot \vec{P}=0\).
\subsection{Diagnostics}
Diagnostics are the mass \(M\)
\begin{align}
    M(t) &:= \int dA (n)  \\
\end{align}
\section{Numerical methods}
discontinuous Galerkin on structured grid
\rowcolors{2}{gray!25}{white} %%% Use this line in front of longtable
\begin{longtable}{ll>{\RaggedRight}p{7cm}}
\toprule
\rowcolor{gray!50}\textbf{Term} &  \textbf{Method} & \textbf{Description}  \\
\midrule
coordinate system & Cartesian 2D & equidistant discretization of $[0,l_x] \times
[0,l_y]$, equal number of Gaussian nodes in x and y \\
matrix inversions & multigrid conjugate gradient &  \\
matrix functions & cauchy integral  method & \\
\ExB advection & centered upwind-scheme\\
curvature terms & centered difference & \\
time &  adaptive explicit RK or explicit multistep  &  \\
\bottomrule
\end{longtable}
\section{Compilation and useage}
There are two programs esol.cu and esol\_hpc.cu . Compilation with
\begin{verbatim}
make <esol esol_hpc esol_mpi> device = <omp gpu>
\end{verbatim}
Run with
\begin{verbatim}
path/to/feltor/src/esol/esol input.json
path/to/feltor/src/esol/esol_hpc input.json output.nc
echo np_x np_y | mpirun -n np_x*np_y path/to/feltor/src/esol/esol_mpi/
    input.json output.nc
\end{verbatim}
All programs write performance informations to std::cout.
The first is for shared memory systems (OpenMP/GPU) and opens a terminal window
with life simulation results.
 The
second can be compiled for both shared and distributed memory systems and uses
serial netcdf in both cases
to write results to a file.
For distributed
memory systems (MPI+OpenMP/GPU) the program expects the distribution of
processes in the
x and y directions as command line input parameters.

\subsection{Input file structure}
Input file format: json
\begin{minted}[texcomments]{js}
"grid":
{
    "n" :  5,    //Legendre polynomial order in x and y
    "Nx" : 32,   //grid points in x
    "Ny" : 32,   //grid points in y
    "lx"  : 64,  //Box size in x in units of $\rho_s$
    "ly"  : 64   //Box size in y in units of $\rho_s$
},
"timestepper":
{
    "type": "adaptive", //"adaptive" (explicit adaptive RK) or "multistep" (explicit multistep)
    "tableau": "Bogacki-Shampine-4-2-3", // recommended "Bogacki-Shampine-4-2-3" (default adaptive) or "TVB-3-3" (multistep)
    "rtol": 1e-10, //relative tolerance of adaptive time stepper
    "atol": 1e-12, //absolute tolerance of adaptive time stepper
    "dt" : 0.1   //time step in units of $c_s/\rho_s$ for multistep. Also determines together with itstep output step $dt_{out} = dt itstp$
},
"output":
{
    "type": "glfw",  // output format "glfw" & "netcdf",
    "itstp"  : 1,    //time steps between outputs
    "maxout" : 2,    //\# of netcdf outputs
    "n" : 5,         //Legendre polynomial order in x and y for netcdf output
    "Nx" : 32,       //grid points in x for netcdf output
    "Ny" : 32        //grid points in y for netcdf output
},
"elliptic":
{
    "stages"     : 3, //\# of stages of the multigrid solver for the (tensor) elliptic operator
    "eps_pol"    : [1e-6,1.0,1.0], //accuracy at each stage of the multigrid solver
    "jumpfactor": 1 //jump factor of the (tensor) elliptic operator
},
"helmholtz":
{
    "eps_gamma1" :   1e-8, //accuracy of the $\Gamma_1$ operator
    "eps_gamma0" :   1e-6, //accuracy of the $\Gamma_0$ or $\sqrt{\Gamma_0}$ operator
    "maxiter_sqrt":  200,  //max iterations of the $\sqrt{\Gamma_0}$ computation
    "maxiter_cauchy": 35,  //max iterations of the Cauchy terms in $\sqrt{\Gamma_0}$ computation
    "eps_cauchy" :  1e-12  //accuracy of the Cauchy integral in the $\sqrt{\Gamma_0}$ computation
},

"physical":
{
    "curvature"  : 0.00015, //$\kappa$
    "tau"  : 4.0,           //$\tau_i = T_{i0}/(T_{e0} Z_i)$
    "alpha"  : 0.005,       //adiabaticity $\alpha:= T_{e,\parallel} k_\parallel^2/(\eta_\parallel e^2 n_{e,0} \Omega_{i,0} )$
    "lambda"  : 0.000001,    //sheath dissipation $\lambda:= \rho_{s0}/L_\parallel$
    "mu_e"  : -0.000272121, //$\mu_e:=m_e/(Z_e m_i)$ negative electron to ion mass ratio
    "equations": "ff-O2",   //model $\in$ ("ff-lwl-OB" ,"ff-O2-OB" ,"ff-lwl" ,"ff-O2" ,"ff-O4" )
    "xfac_sep"  : 0.3,      //$f_s$ x-position of separatrix in units of $l_x$
    "sigma_sep"  : 0.5      //$sigma_s$ width of damping function $h_{pm}$ of separatrix in units of $\rho_{s0}$
},
"source":
{
     "source_type" : "flux",    //type of source $\in$ ("forced", "flux")
     "source_rel" : "zero_pol", //relation for source, $\in$ ("zero-pol", "finite-pol")
     "omega_s" : 0.005,         //source rate in units of $\Omega_i$
     "xfac_s": 0.1,             //position of source in units of the $l_x$
     "sigma_s" : 2.0              //width of source in units of $\rho_{s0}$
},
"profile":
{
     "bgprofamp" : 1.0, //amplitude of background in units of $n_{e0}$, typically 1
     "profamp": 0.0,    //amplitude of profile in units of $n_{e0}$
     "sigma_p": 20.0    //width of gradient region of the profile in units of $\rho_{s0}$
},
"init":
{
    "type"       : "blob",  // Gaussian blob initialization
    "amplitude"  :1.0,      //$A$ of the Gaussian blob
    "sigma"  : 5,           //$\sigma$ of Gaussian blob units of $\rho_s$
    "posX"  : 0.5,          //x initial position $\in (0,1)$
    "posY"  : 0.5           //y initial position $\in (0,1)$
},
"nu_perp"  : 0e-5,          //hyper-diffusion parameter
"bc_x"  : "DIR_NEU",        //Boundary condtion in x
"bc_y"  : "PER"             //Boundary condtion in y
\end{minted}
\subsection{Structure of output file}
Output file format: netcdf-4/hdf5
%
%Name | Type | Dimensionality | Description
%---|---|---|---|
\begin{longtable}{lll>{\RaggedRight}p{7cm}}
\toprule
\rowcolor{gray!50}\textbf{Name} &
 \textbf{Type} & \textbf{Dimension} & \textbf{Description}  \\ \midrule
inputfile  &             text attribute & 1 & verbose input file as a string \\
energy\_time             & Dataset & 1 & timesteps at which 1d variables are
written \\
time                     & Dataset & 1 & time at which fields are written \\
x                        & Dataset & 1 & x-coordinate  \\
y                        & Dataset & 1 & y-coordinate \\
electrons                & Dataset & 3 (time, y, x) & electon density $n$ \\
ions                     & Dataset & 3 (time, y, x) & ion density $N$ \\
potential                & Dataset & 3 (time, y, x) & electric potential $\phi$
\\
vorticity                & Dataset & 3 (time, y, x) & z-component of ExB
vorticity  $\Omega_E = \vec{\nabla}\cdot (B^{-1} \vec{\nabla}_{\perp}\phi)$  \\
lperpinv                 & Dataset & 3 (time, y, x) & inverse perp density gradient length scale $L_\perp^{-1} := |\nabla_\perp n| / n$ \\
lperpinvphi                 & Dataset & 3 (time, y, x) & inverse perp eletric potential gradient length scale $L_{\perp,\phi}^{-1} := |\nabla_\perp \phi| $ \\
% dEdt                     & Dataset & 1 (energy\_time) & change of energy per
% dissipation              & Dataset & 1 (energy\_time) & diffusion integrals
\\
% energy                   & Dataset & 1 (energy\_time) & total energy integral
\\
% mass                     & Dataset & 1 (energy\_time) & mass integral   \\
\bottomrule
\end{longtable}
%..................................................................
\bibliography{../../doc/related_pages/references}
%..................................................................
\bibliographystyle{aipnum4-1.bst}

\end{document}


\documentclass[12pt]{cdblatex}
\usepackage{eqtns}

\begin{document}

\section*{PhysRevD.67.084023 equation (19)}

\begin{cadabra}
   from shared import *
   import cdblib

   jsonfile = 'hamiltonian.json'
   cdblib.create (jsonfile)

   # --------------------------------------------------------------------------
   # Hamiltonian constraint

   Ham := R + K_{a b} g^{a b} K_{c d} g^{c d} - K_{a b} K_{c d} g^{a c} g^{b d}.  # cdb (Ham.101,Ham)

   defK2ABarD := K_{i j} -> \exp(4\phi) ABar_{i j} + (1/3) g_{i j} trK.
   defG2GBarD := g_{a b} -> \exp(4\phi) gBar_{a b}.
   defG2GBarU := g^{a b} -> \exp(-4\phi) gBar^{a b}.

   substitute     (Ham, defK2ABarD)   # cdb (Ham.102,Ham)
   substitute     (Ham, defG2GBarD)   # cdb (Ham.103,Ham)
   substitute     (Ham, defG2GBarU)   # cdb (Ham.104,Ham)
   distribute     (Ham)               # cdb (Ham.105,Ham)
   Ham = product_sort (Ham)           # cdb (Ham.106,Ham)
   rename_dummies (Ham)               # cdb (Ham.107,Ham)
   canonicalise   (Ham)               # cdb (Ham.108,Ham)
   map_sympy      (Ham, "simplify")   # cdb (Ham.109,Ham)

   foo := gBar_{a b} gBar^{a b} -> 3.
   bah := gBar_{a c} gBar^{b c} -> gBar_{a}^{b}.

   substitute (Ham, foo)              # cdb (Ham.110,Ham)
   substitute (Ham, bah)              # cdb (Ham.111,Ham)
   eliminate_kronecker (Ham)          # cdb (Ham.112,Ham)

   foo := gBar_{a b} gBar^{a b} -> 3.
   bah := gBar_{a}^{a} -> 3.
   moo := ABar_{a b} gBar^{a b} -> 0.

   substitute     (Ham, foo)          # cdb (Ham.113,Ham)
   substitute     (Ham, bah)          # cdb (Ham.114,Ham)
   substitute     (Ham, moo)          # cdb (Ham.115,Ham)

   foo := ABar_{c d} gBar^{c a} gBar^{d b} -> ABar^{a b}.

   substitute     (Ham, foo)          # cdb (Ham.116,Ham)
   rename_dummies (Ham)               # cdb (Ham.117,Ham)

   cdblib.put ('Ham',Ham,jsonfile)
\end{cadabra}

\clearpage

\begin{dgroup*}
   \begin{dmath*}
      {\cal H}
          = \Cdb*{Ham.101}
          = \Cdb*[\hskip2cm\hfill]{Ham.102}
          = \Cdb*{Ham.103}
          = \Cdb*{Ham.104}
          = \Cdb*[\hskip2cm\hfill]{Ham.105}
          = \Cdb*{Ham.106}
   \end{dmath*}
\end{dgroup*}

\clearpage

\begin{dgroup*}
   \begin{dmath*}
      {\cal H}
          = \Cdb*[\hskip2cm\hfill]{Ham.107}
          = \Cdb*[\hskip2cm\hfill]{Ham.108}
          = \Cdb*{Ham.109}
          = \Cdb*{Ham.110}
          = \Cdb*{Ham.111}
          = \Cdb*{Ham.112}
          = \Cdb*{Ham.113}
          = \Cdb*{Ham.114}
          = \Cdb*{Ham.115}
          = \Cdb*{Ham.116}
          = \Cdb*{Ham.117}
   \end{dmath*}
\end{dgroup*}

\clearpage

\begin{cadabra}
   # --------------------------------------------------------------------------
   # Check against prd67.

   foo := @(Ham).                                       # cdb(prd67.eq19.lcb,foo)
   bah  = cdblib.get('prd67.eq19.rhs','prd67.json')     # cdb(prd67.eq19.prd,bah)

   diff := @(foo) - @(bah).

   distribute     (diff)
   diff = product_sort (diff)
   rename_dummies (diff)
   map_sympy      (diff, "simplify")
   canonicalise   (diff)                                # cdb(prd67.eq19.chk,diff)
\end{cadabra}

% \clearpage

\begin{dgroup*}
   \begin{dmath*} \cdb*{prd67.eq19.lcb} \end{dmath*}
   \begin{dmath*} \cdb*{prd67.eq19.prd} \end{dmath*}
   \begin{dmath*} \cdb*{prd67.eq19.chk} \end{dmath*}
\end{dgroup*}

\end{document}


\section{Consistency of spectral clustering}
\label{ch:ulrike2008}

\textit{Consistency of spectral clustering} by Ulrike Von Luxburg.\\
Cited by 241. \textit{The Annals of Statistics, 2008}.
\newline

\textbf{Main point} is that \begin{inparaenum}[\itshape a\upshape)]
\item normalized spectral clustering converges under some very general conditions,
\item but unnormalized spectral clustering is only consistent under strong additional assumptions,
\end{inparaenum} thus it conclude normalized spectral clustering is superior in practical application


%!TEX root = ../main.tex
\documentclass[../main.tex]{subfiles}
\begin{document}
\subsection{Additional Tables and Figures} \label{app:tables_and_figures}
\subsubsection{Correlation Heatmap of Task Choices}
\begin{figure}[!htbp]
	\centering
	\includegraphics[scale=0.7]{./FIG/corr_heatmap.png}
	\caption{Heatmap of correlation coefficients of task choices in periods $t-1$ and $t$ of the base period as well as their squared values. Notice that the scale is compressed and only covers values between 0.95 and 1.0 to make the small differences visible.}
	\label{fig:corr_heatmap}
\end{figure}

\FloatBarrier
\subsubsection{Estimation Results in Base Period}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Table 1 %%%%%%%%%%%%%%%%%
\begin{table}[!htbp]
\begin{center}
\begin{tabular}{lclc}
\toprule
\textbf{Dep. Variable:}    & $\Delta w_{i,t}$ & \textbf{  R-squared (uncentered):}      &     0.999   \\
\textbf{No. Observations:} &       100        & \textbf{  Adj. R-squared (uncentered):} &     0.999   \\
\textbf{F-statistic:}      &  5.720e+04      & \textbf{  Prob (F-statistic):}          & 4.87e-151   \\
\bottomrule
\end{tabular}
\begin{tabular}{lcccccc}
                  & \textbf{coef} & \textbf{std err} & \textbf{t} & \textbf{P$> |$t$|$} & \textbf{[0.025} & \textbf{0.975]}  \\
\midrule
\textbf{$\lambda_{i, t-1}^{*}$}   &       -0.4989  &        0.002     &   -240.382  &         0.000        &        -0.503    &        -0.495     \\
\textbf{$\lambda_{i, t-1}^{*2}$} &        1.0001  &        0.004     &    278.381  &         0.000        &         0.993   &         1.007    \\
\bottomrule
\end{tabular}

\end{center}
\caption{Results of an OLS estimation of wage changes in the base period on both, $\lambda_{i, t-1}^{*}$ and $\lambda_{i, t-1}^{*2}$. This estimation result is from one of the $M = 1000$ simulated datasets used in the Monte Carlo estimation. Regressors do not include a constant because the true model intersects the point of origin due to the normalization of $w_{i,j=1,t} = 0$.}
\label{tab:base_period_regression_rlst_t-1}
\end{table}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Table 2 %%%%%%%%%%%%%%%%%
\begin{table}[!htbp]
\begin{center}
\begin{tabular}{lclc}
\toprule
\textbf{Dep. Variable:}    & $\Delta w_{i,t}$ & \textbf{  R-squared (uncentered):}      &      0.999   \\
\textbf{No. Observations:} &       100        & \textbf{  Adj. R-squared (uncentered):} &      0.999   \\
\textbf{F-statistic:}      &  7.081e+04       & \textbf{  Prob (F-statistic):}          & 1.42e-155   \\
\bottomrule
\end{tabular}
\begin{tabular}{lcccccc}
                  & \textbf{coef} & \textbf{std err} & \textbf{t} & \textbf{P$> |$t$|$} & \textbf{[0.025} & \textbf{0.975]}  \\
\midrule
\textbf{$\lambda_{i, t}^{*}$}   &        -0.4841  &        0.002     &    -264.802 &         0.000        &         -0.488   &         -0.480    \\
\textbf{$\lambda_{i, t}^{*2}$} &        	 0.9686  &        0.003     &     308.259  &         0.000        &          0.962    &          0.975    \\
\bottomrule
\end{tabular}

\end{center}
\caption{Results of an OLS estimation of wage changes in the base period on both, $\lambda_{i, t}^{*}$ and $\lambda_{i, t}^{*2}$. This estimation result is from one of the $M = 1000$ simulated datasets used in the Monte Carlo estimation. Regressors do not include a constant because the true model intersects the point of origin due to the normalization of $w_{i,j=1,t} = 0$.}
\label{tab:base_period_regression_rlst_t}
\end{table}
\FloatBarrier

\end{document}