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

% \marginpar{Friday\\ 2019-11-15, \\ compiled \\ \today}
% \section*{Fri Nov 15 2019}

% We start again from where we left off, with hydrogen recombination.

% We want to estimate the moment at which hydrogen first formed, which marks the point at which electrons and photons interact efficently: before, they interacted with Compton scattering which is very efficient; after they interact with hydrogen atoms in a way that is very inefficient.

% After this, then, we say that photons and matter are \emph{decoupled}.

% The scattering cross section (for Compton?) goes like the inverse square of the mass.

% This means that the universe is not only \emph{globally},  but also \emph{locally} neutral.

% This decoupling is what allows for star formation.
% Also, this is when the CMB starts.
% It is made of microwaves now, but it was higher earlier.

% The phase space distribution of photons is scale-invariant since they have zero mass: so we can say that the photons' distribution \emph{looks} thermal, but it is actually not technically since there are no interactions anymore.

% However the photons travel freely and are perceived as thermal, and they give an almost perfect blackbody! The errorbars in a plot for it must be magnified by \num{e4} in order to be seen.

% Neutrality implies \(n_e = n_p\).
Let us now introduce the total baryon density, \(n_b\).
In principle, we should account for Helium: as we will see, a couple of minutes after the Big Bang He-4 nuclei started to form, but they made up only something like \(25\%\) of the mass, which means \(6\%\) of the number density: so we ignore them and say that the number density of baryons is
%
\begin{align}
  n_b = n_p + n_H
\,.
\end{align}

% Our ansatz for the Boltzmann equation is \(\mu_e + \mu _p = \mu _H\) since photons have no chemical potential.

% \(i\) denotes a generic one in \(e\), \(p\) and \(H\).
% Then
% %
% \begin{align}
%   n_i = g_i\qty(\frac{m_i T}{2 \pi })^{3/2} \exp(\frac{\mu _i - m_i}{T})
% \,,
% \end{align}
% %
% we need to account for the chemical potential since it is the driver of this process.
The quantity we want to describe is how much hydrogen is still ionized: this is given by the ratio of the free electrons to the total baryons, \(n_e / n_b\). This is called the \textbf{ionization fraction} \(X_e\), and is also equal to \(n_p / n_b\) since the universe must be locally neutral.

We expect to have \(X_e = 1\) in the early universe, and \(X_e = 0\) after the end of reionization.

This is a good model to keep in mind although it is not precisely correct, since simulations show that there will be some \emph{residual ionization}: \(X_e\) only goes to around \(\num{e-4} \divisionsymbol \num{e-5}\) at the end of reionization.
Also, in the modern universe a large fraction of the hydrogen has become ionized again, especially in the intergalactic medium; this is likely due to the energy injected into it by structure formation, which definitely breaks the approximation of global thermal and chemical equilibrium.
This is not a concern for us: here, we only wish to describe the processes in the interval \(1000 \lesssim z \lesssim 2000\).

%  naively we'd expect it to get to 0, but actually there remains some residual ionization, some free protons and electrons.
% How much is \(n_e / n_b\)? the same as \(n_p / n_b\). We call this quantity \(X_e\), the ionization number.
% A proper calculation would account for the non-equilibrium contributions.
% However, we estimate the process as being in equilibrium: this will underestimate the number of electrons.

% Today, most of the hydrogen is ionized (there is a ***-Peterson effect which shows this): this means that matter and radiation interact again.

% This is the second important time in the history of the universe.

% Can we see the early stars? Not really, we see galaxies only up to \(z \sim 10\), these stars would be at something like \(z \sim 30\)\dots
% There might be more to this.

% Inserting this and the Saha equation we get
% So the number density of hydrogen atoms is given by:
%
% \begin{align}
%   n_H = g_H \qty(\frac{m_H T}{2 \pi })^{3/2} \exp(\frac{\mu_p - \mu_e - m_p - m_e + B}{T})
% \,,
% \end{align}
%
% and we can simplify things since \(m_p, m_H \gg m_e, B\), and substitute in the number densities for electrons and protons.
The binding energy of the hydrogen is \(B=m_p+m_e-m_H=\SI{13.6}{eV}\), so instead of \(m_H\) we can write \(m_H = m_p+m_e-B\).
Let us insert this expression and the Saha equation in the expression for the hydrogen number density; then we will recognize part of the expressions for the proton and electron number densities, which we can
%
\begin{subequations}
\begin{align}
  n_H &=  g_H \qty(\frac{m_H T}{2 \pi })^{3/2} \exp(\frac{\mu _H - m_H}{T})  \\
  &= g_H \qty(\frac{m_H T}{2 \pi })^{3/2} \exp(\frac{\mu_e + \mu _p - m_e - m_p + B}{T}) \\
  &= \underbrace{\frac{g_H}{g_e g_p}}_{= 1} \cancelto{}{\qty(\frac{m_H T}{2 \pi })^{3/2}}
  \qty(\frac{m_e T}{2 \pi })^{-3/2}
  \cancelto{}{\qty(\frac{m_p T}{2 \pi })^{-3/2}}
  n_e n_p
  \exp(\frac{B}{T}) \\
  \frac{n_H}{n_e n_p} &=  \qty(\frac{m_e T}{2 \pi })^{-3/2} \exp(\frac{B}{T})  \\
  \frac{n_b - n_p}{n_p^2} &= \qty(\frac{m_e T}{2 \pi })^{-3/2} \exp(\frac{B}{T})
\,,
\end{align}
\end{subequations}
%
which we can manipulate, using the following identity:
%
\begin{align}
  \frac{n_b - n_p}{n_p^2} = \frac{n_b \qty(1 - n_p/ n_b)}{n_b^2 X_e^2} = \frac{1}{n_b} \frac{1 - X_e}{X_e^2}
\,,
\end{align}
%
where we use \(n_e = n_p\) and the definition of \(X_e = n_p / n_b\). Then, we bring the \(n_b\) to the other side of the equation and multiply and divide by the photon number density, which is given by
%
\begin{align} \label{eq:n-gamma}
  n_{\gamma } = \frac{2 \zeta (3) T^3}{\pi^2}
\,.
\end{align}

With this, we can insert the baryon fraction \(\eta_b\) (which is conserved, so we can use its current value):
%
\begin{subequations}
\begin{align}
  \frac{1- X_e}{X_e^2} &= \underbrace{\frac{n_b}{n_\gamma }}_{\eta_p}
  n_\gamma
  \qty(\frac{m_e T}{2 \pi })^{-3/2} \exp(\frac{B}{T})   \\
  &= \eta_0 \frac{2 \zeta (3)T^3}{\pi^2} \qty(\frac{m_e T}{2 \pi })^{-3/2} \exp(\frac{B}{T})   \\
  &= \eta_0  \frac{4 \sqrt{2} \zeta (3)}{\sqrt{\pi }} \qty(\frac{T}{m_e})^{3/2} \exp(\frac{B}{T}) \label{eq:saha-equation-ionization}
\,,
\end{align}
\end{subequations}
%
which we can solve numerically to find \(X_e\) as a function of temperature, or of redshift. The results are shown in figure \ref{fig:ionization}.

\begin{figure}[ht]
\centering
\includegraphics[width=\textwidth]{figures/ionization}
\caption{Ionization fraction as a function of redshift: a numerical solution of equation \eqref{eq:saha-equation-ionization}.}
\label{fig:ionization}
\end{figure}

Let us try to understand what is going on. Roughly speaking, we get intermediate values for \(X_e\), like \(\num{.5}\), when the right-hand side is of order 1.
If the right-hand side only contained the terms \((T/m_e)^{3/2}\exp(B/T)\) without any multiplicative factor in front (meaning, roughly, that we had \(\eta_0 \sim 1\)), then we would see recombination starting to occur already at \(z \sim 4000\) (\(T \sim \SI{1}{eV}\)), and by \(z \sim 2000\) if would almost be over.
The reason this does not happen is that \(\eta_0 \) is \emph{very small}: there are a lot of photons, many more than the baryons, which are ready to dissociate any atoms which start to form.

So, hydrogen is truly formed only when \(T \sim \SI{0.3}{eV}\), much lower than its ionization energy.

\todo[inline]{But even with \(\eta_0 \sim 1\) we get formation at \(T \sim \SI{1}{eV}\), an order of magnitude less than \(B\)! is there an intuitive argument as to why this is the case?}

The estimates we gave do depend on the value we assign to \(\Omega_{0b}\) and \(h\), however within the currently accepted experimental ranges the main predictions do not vary substantially.

% Approximately, it occurred somewhere around \(z \sim 1100\) (we conventionally say that recombination happened when \(X_e = 0.1\)).
The process of recombination is gradual, but we can choose a conventional redshift as, for example, the time when we reach an arbitrary threshold like \(X_e = \num{.1}\).

The interaction rate between photons and free electrons is \(\Gamma_{\gamma } = n_e \sigma_T c\), where \(\sigma _T\) is the Thompson cross section while \(n_e\) is the number density of free electrons, which can be estimated as \(n_e = n_b X_e \approx \rho_C \Omega_{b} X_e / m_p\).
% After recombination, we have the \emph{last scattering}: the moment at which the CMB was formed.
Then, we can estimate the moment of the last scattering by checking the decoupling condition: \(\Gamma _\gamma < H\).
With the numbers given earlier, we find \(z \sim 1120\): a very good approximation to the currently accepted value \(z \sim 1089\)!

% One Nobel prize this year was awarded to Jim Peebles, a friend of Sabino's: together with his PhD supervisor Dicke, he was the first to calculate this stuff.

% Peebles in 1964 (?) did this calculation both in GR and in Brahms-Dicke theory, a modified gravity theory.

\todo[inline]{Then Pacciani has an argument as to why \(T \sim a^{-2}\) for matter, should this be included here? It basically comes from entropy conservation \(\dd{E} = - P \dd{V}\), the ideal gas law \(P = n_b k_B T\) and the equipartition theorem \(E = \frac{3}{2} n_b a^3 k_B T\).}

\section{Primordial nucleosynthesis}

Already in the 1940s it was noticed by Alpher, Bethe as well as Gamow that the abundances of certain nuclides could not be explained if they were formed in stellar interiors alone.
Specifically, the issue is with the abundances of light elements: deuterium \(\ce{^{2}H}\), as well as \(\ce{^{3}He}\) and \(\ce{^{4}He}\), while heavier nuclides (with mass number \(A \geq 7\)) could not form in the early universe \cite[sec.\ 8.6.1]{colespCosmology2002}.\footnote{Environments which allow their production (stellar interiors) have lower temperature but a higher density, since the main obstruction to their production is the absence of stable nuclides at \(A = 5\) and \(A= 8\) --- the environment needs to raise the odds of an unstable \ce{^{8}Be} nuclide colliding with an \(\alpha \) particle to form carbon before it decays.}

The most abundant of these light nuclides by far is \ce{^{4}He}, whose mass fraction is denoted as \(Y \approx \SI{25}{\percent}\), while its number fraction is approximately \SI{6}{\percent}. Our model will need to yield this many helium-4 nuclides after primordial nucleosynthesis.

A mechanism for the synthesis of these light nuclides in the early universe is needed.
% Let us describe the early universe, before the first nucleosynthesis.
% Important papers in this topic are by G. Gamow, and by Alpher, Bethe and Gamow.

We shall model this mechanism, under the following assumptions (which are, as far as we know, roughly verified):
%
\begin{enumerate}
    \item the universe passed through a very high temperature phase, with \(T > \SI{e12}{K}\), during which thermal equilibrium held;
    \item the universe at this stage is described by General Relativity and the Standard Model of particle physics, and it is homogeneous and isotropic;
    \item the chemical potentials for the neutrinos \(\mu_{\nu }\) have certain upper bounds, such that the number of neutrino types is approximately 3;
    \item there is no matter-antimatter separation (as in, antimatter ``bubbles'');
    \item there are no strong magnetic fields;
    \item the number of exotic particles has a certain upper bound (it is small compared to the number of photons).
\end{enumerate}

% There are magnetic fields in the universe, but they are not homogeneous and relatively weak.
% Exotic particles are predicted by certain unification theories, they are generically defined as ones which we have not observed yet.

% We have to explain the fact that we observe an excess of He-4 in the early universe: we define the yield
%
% \begin{align}
%   y \equiv \frac{m_{\ce{He-4}}}{m_b} > \num{.25}
% \,.
% \end{align}

% In terms of particle number, the ratio is more like \num{.06}.
% We do not produce Carbon or anything higher than it: the process which forms it is inefficient at high temperature, low density like the early universe.
% Higher \(Z\) elements are only produced in stars.

% Helium-4 is produced but also destroyed by stars.

The main formation channels in the early universe are:
%
\begin{enumerate}
    \item \(n+p \leftrightarrow d + \gamma \) (\(d= \ce{^{2}H}\) denotes deuterium);
    \item \(d + d \leftrightarrow \ce{^{3}He} + n\);
    \item \(\ce{^{3}He} + d \leftrightarrow \ce{^{4}He} + p\).
\end{enumerate}

Note that these processes, unlike the stellar ones, do not involve the weak interaction: neutrons and protons do not turn into each other.
In stars, there are no free neutrons so this process is not possible.

The slowest process of the three is the first, since it is heavily affected by photons, which destroy deuterium.
After we have produced deuterium, Helium-4 is readily produced.
% We cannot treat this properly, we only give a story.

% The binding energy of deuterium is around \SI{2.2}{MeV}.

In order to find out how much deuterium we have, we need the proton-to-neutron ratio.
We are working at energies of around \SI{1}{MeV}, so protons and neutrons are not relativistic anymore; \emph{as long as they are in equilibrium} through weak processes both will obey Boltzmann statistics, so for \(i = n, p\):
% his process takes place around three minutes after the beginning.
%
\begin{align}
  n_i = g_{i} \qty(\frac{m_i T}{2 \pi })^{3/2} \exp(\frac{\mu_i - m_i}{T})
\,,
\end{align}
%
meaning that their number ratio is given by\footnote{We are neglecting the chemical potentials since, as explained by \textcite[sec.\ 8.6.2]{colespCosmology2002}, as long as both weak and electromagnetic interactions are in chemical equilibrium the chemical potentials are forced to be zero by all the balance equations.}
\todo[inline]{The explanation in \cite[]{colespCosmology2002} is not the same as the one given by \textcite[]{paccianiAppuntiCorsoPhysical2018}\dots I'm inclined to trust the former.}
%
\begin{align}
  \frac{n_n}{n_p} \sim \exp(-\frac{m_n - m_p}{T})
\,,
\end{align}
%
where \(m_n - m_p \approx \SI{1.3}{MeV} \approx \SI{1.5e10}{K}\).

The proton is the lightest baryon and is therefore stable; while the neutron is unstable: it can decay through the weak-interaction processes
\begin{enumerate}
    \item \(n + \nu _e \leftrightarrow p + e^{-}\);
    \item \(n + e^{+} \leftrightarrow p + \overline{\nu _e} \);
    \item \(n \rightarrow p + e^{-} + \overline{\nu _e} \).
\end{enumerate}

The neutron fraction keeps decreasing as \(T\) decreases and these processes keep happening, however as we have previously discussed at around \(T_{d \nu } \sim \SI{1}{MeV}\) neutrinos decouple, at which point the first two back-and-forth reactions stop, and we are left with \(n_n / n_p \approx \exp(- \Delta m / T_{d \nu }) \approx \num{.27}\).
% We can replace the temperature in the exponential by \(T \rightarrow T_{d_\nu }\), the decoupling temperature of the neutrinos, since that is the moment around which this happpens.

We define the number fraction of neutrons, which is approximately
%
\begin{align}
  X_n (t) \equiv \frac{n_n}{n_n+n_p} \approx \num{.21}
\,.
\end{align}

The third reaction, which is \(\beta^{-} \) decay, keeps occurring since it does not require the presence of neutrinos, so after the decoupling of neutrinos the number fraction decays exponentially as:
%
\begin{align}
  X_n(t) = X_n(t_{d_\nu }) \exp( - \frac{t - t_{d_\nu }}{\tau _n})
\,,
\end{align}
%
where \(\tau _n = \log 2 \tau_{1/2}\), and the half-life of neutrons is given by \(\tau_{1/2} \approx \SI{10.5+-0.2}{min}\).
So, each minute neutrons stay unbound some of them are decaying; the process of deuterium formation however is rather fast as we shall see, so not many of them are lost.

Let us then move to deuterium formation: its binding energy is around \(B_d = m_p + m_n - m_d \approx \SI{2.2}{MeV}\).
We proceed exactly like we did with hydrogen: since \(\mu _p + \mu _n = \mu _d\), the deuterium number density can be expressed as
%
\begin{align}
n_d &= g_d \qty(\frac{m_d T}{2 \pi })^{3/2}  \exp(\frac{\mu _d - m_d}{T})  \\
&= \frac{g_d}{g_p g_n} n_n n_p \qty(\frac{m_d}{m_n m_p})^{3/2} \qty(\frac{T}{2 \pi })^{-3/2} \exp( \frac{B_d}{T})
\,,
\end{align}
%
which, dividing through by \(n_b\) and using \(g_d = 3\) (since deuterium has spin 1) and \(g_p = g_n = 2\), can be expressed as:
%
\begin{subequations}
\begin{align}
  X_d &= \frac{3}{4} n_b X_n X_p \qty(\frac{m_d}{m_nm_p})^{3/2} \qty(\frac{T}{2 \pi })^{-3/2} \exp(\frac{B_d}{T}) \\
  &= \frac{3}{4} \eta_0 X_n X_p \qty(\frac{m_d}{m_nm_p})^{3/2}
  \frac{2 \zeta (3)}{\pi^2} (2 \pi T)^{3/2}  \exp(\frac{B_d}{T})
  \marginnote{Substituted \(n_b = \eta_0 n_\gamma \).}\\
  &\approx \frac{3}{4} \eta_0 X_n (1-X_n) \qty(\frac{m_d}{m_nm_p})^{3/2} \frac{2}{\pi^2} (2 \pi T)^{3/2} \zeta (3)  \exp(\frac{B_d}{T})
  \marginnote{Approximated \(X_p + X_n \approx 1\), ignoring heavier nuclides.}
\,,
\end{align}
\end{subequations}
% \todo[inline]{Check calculation.}
\todo[inline]{Does approximating \(X_p + X_n \approx 1\) not ignore deuterium as well? Or rather: by the definition given before \(X_n + X_p = 1\) is exact, and if we do normalize by \(n_n + n_p + n_d +\dots\) we should specify\dots}
%
which describes the \emph{deuterium bottleneck}: similarly to hydrogen recombination, the presence of many photons for each nuclide keeps compound particles from forming for quite a long time, and this precludes the formation of Helium.

\end{document}


%!TEX ROOT=sample-thesis.tex
%!TEX PROGRAM=xelatex

\chapter{List of Symbols}

{\renewcommand{\arraystretch}{2}
\begin{tabular}{@{} >{\bfseries\boldmath }l @{\hspace{1em}--\hspace{1em}} l@{}}

$\theta$ & temperature\\

$G$ & Gravitational acceleration $= \SI{9.81}{\meter\per\second}$

\end{tabular}
}


\documentclass[12pt]{article}

\usepackage{fullpage}
\usepackage{/home/nick/Documents/analysis}
\usepackage{listings}
\usepackage{verbatim}

\begin{document}
\title{FrameLab\\\small{Software for framelet-based numerical analysis}}
\author{Nick Henscheid\\\small{ University of Arizona Program in Applied Mathematics}}
\date{\today}
\maketitle

\paragraph{Goals}
The idea of this project is to develop a complete software suite for computational imaging via framelets.  The code will be sorted into the following general categories:

\begin{enumerate}
\item Framelet expansion code
\begin{itemize}
\item Fast single and multilevel decomposition and reconstruction for 1D through 3D
\item Signal sparsity analysis, best basis selection?
\item Computing framelet coefficients
\end{itemize}
\item Numerical optimization code
\begin{itemize}
\item $l_1$ compressed sensing via ADMM/AL/DAL
\item Comparison of different algorithms?
\item $l_0$ code
\end{itemize}
\item Utilities
\begin{itemize}
\item Graphics and figure creation
\item Shrinkage designer
\item PDEs for image processing
\item Forward/adjoint operators for imaging
\item Classical signal processing
\end{itemize}
\item Applications
\begin{itemize}
\item CT
\item MRI
\item SPECT
\item Segmentation
\item Registration?
\item Deblurring
\item Deconvolution
\item Integral equations?
\item Matrix factorization?
\item Matrix completion
\item BM3D
\end{itemize}
\end{enumerate}

\section{Implementation Details}

\paragraph{Programming languages and interfaces}
To do:
\begin{itemize}
\item GPU interface to python?  pycuda?  (e.g. python alternative to mex)
\end{itemize}

\paragraph{Data Types}

\section{Framelet Expansions}
The first task to create/modify functions to perform framelet decomposition and reconstruction

\section{Optimization Methods}
%\lstinputlisting[numbers=left,language=Matlab,frame=single,caption={}Matlab function to solve the analysis-based sparse recovery problem via Augmented Lagrangian.]{../optimization/ALsolve.m}

\section{Imaging Systems}
\subsection{2D Computed Tomography}

\subsection{3D Computed Tomography}

\section{Test Scripts}
\begin{enumerate}
\item testAdjoint.m
\item testBall.m
\item testCBCTCGLS.m
\item testCBCTInterp.m
\item testCBCTInterpAugmented.m
\item testCGLSClass.m
\item testConeBeamScanner.m
\item
\end{enumerate}

\end{document}


\chapter{Inference of Guarded Recursion}
\todo{Should we mention somewhere that we don't plan on running these? And can
  we even do that? What about evaluation in types?}
\label{cha:infer-guard-recurs}
As mentioned in Section~\ref{sec:less-restr-prod}, we wish to extend Idris with
a less restrictive productivity checker using guarded recursion. However, as
we saw in Section~\ref{sec:guarded-recursion}, defining guarded recursive
programs can be quite tedious and requires the user to thoroughly understand guarded
recursion in order to write provably productive programs. In this chapter, we propose a system
where we can check the productivity of programs using guarded recursion with
only a minimal amount of user involvement. The main focus will be
implementation, showing how we have put theory into practice.
\section{Intuition}
%##########
% Type-directed (undersøg præcis hvad dette betyder)
% Overgang fra teori til Idris - Hvilke praktiske hensyn tages der?
% Fix-punktet - hvordan forstås det?
% Kun eet ur!
% Kausale og ikke-kausale funktioner
%% Problemet bag: hvorfor er vi nødt til at skelne?
% Eksempel på inferens
%##########
Our system is divided into two parts: (1) An inference system that builds a
guarded recursive term from a user written term, and (2) an algorithm that
checks the structure of a term and its type according to the rules from
Figure~\ref{fig:guarded_recursion_rules_clocks}. While the general idea is that
these two parts work together, such that the inference system first builds a term
for the checking algorithm to check, it is our goal that these two should work
as disjoint modules. This is important as we want our checking algorithm to be a
general-purpose guarded recursion checker, not just an algorithm for checking
the output of the inference system.

Furthermore, it is important to note that our system is an extension of
Idris. This means that we do not add or change any core elements of the language, and
therefore do not jeopardise or tamper with the correctness of the Idris type system.

\subsection{Practical Considerations}
When realising a theoretical model such as guarded recursion in an existing
system, there are practical considerations to be taken. Because of the way Idris
is implemented, how we construe the theory might not be immediately obvious. In
the following we will lay out these practical considerations, and how they
relate to the theory.

\paragraph{Target}
As discussed in Chapter~\ref{cha:idris}, an Idris program is represented in
multiple different ways throughout compilation. The time and representation on
which to perform our analysis has great impact on how a solution
unfolds.

Discarding the representations obviously not useful for this analysis (namely
concrete Idris, IBC, and binaries), we are left with two options: \IdrisM and
TT. As guarded recursion is a typing discipline our system needs access to
the types of any term, and since \IdrisM does not contain all type information
our analysis is performed on the core language, TT.

\paragraph{Parameters}
In Section~\ref{sec:guarded-recursion} we discussed and used a guarded fixpoint
operator. Due to the type of this operator, ($(\later A \rightarrow A)
\rightarrow A$), the recursive reference will always have a $\later$-type. This
means that any application of a recursive reference to an argument must be done
using $\tensor ^{\kappa}$\todo{This operator must be given a human-readable name}.

Idris, like many other languages, have named parameters which influence the type
of a function. Looking at the rule for $\tensor ^{\kappa}$ in
Figure~\ref{fig:guarded_recursion_rules} we see that it does not take any type
substitution into account unlike the rules for regular application in Idris from
Figure~\ref{fig:TT_typing_rules}. This means that we cannot use $\tensor ^{\kappa}$ for
parameter application. To better understand this, consider the following example.

\begin{figure}[h]
  \begin{lstlisting}[mathescape]
repeat : $\forall \kappa$ ((a : Type) $\rightarrow$ a $\rightarrow$ Stream$^{\kappa}$ a)
repeat = $\Lambda\kappa.$ fix$^{\kappa}$($\lambda{}$rec$.\lambda{}$a$.\lambda{}$n$.$
             StreamCons a n ((rec $\tensor ^{\kappa}$ (Next$^{\kappa}$ a)) $\tensor ^{\kappa}$ (Next$^{\kappa}$ n)))
\end{lstlisting}
  \caption{An infinite stream of the same element.}
  \label{fig:repeat_guarded_example}
\end{figure}

In Figure~\ref{fig:repeat_guarded_example} an infinite stream \texttt{repeat} is
defined. It simply just repeats the same element infinitely. Note that even
though this problem also applies to implicit arguments, all arguments in the
example are explicit for simplicity. This means that \texttt{StreamCons} has
type \texttt{(a : Type) $\rightarrow$ a $\rightarrow$ $\later^{\kappa}$ Stream$^{\kappa}$ a $\rightarrow$ Stream$^{\kappa}$ a}.

When checking if this implementation conforms to the guarded rules we have to
check that \texttt{(rec $\tensor ^{\kappa}$ (Next$^{\kappa}$ a)) $\tensor ^{\kappa}$ (Next$^{\kappa}$ n)} has type
\texttt{$\later ^{\kappa}$Stream$^{\kappa}$a} we run into trouble. In order for this to hold,
according to the $\tensor ^{\kappa}$ rule, \texttt{rec $\tensor ^{\kappa}$ (Next$^{\kappa}$ a)} must have
type \texttt{$\later^{\kappa}$(a $\rightarrow$ Stream$^{\kappa}$ a)}. As shown in
Figure~\ref{fig:repeat_typing} we cannot show this as \texttt{rec} has a
different type in our environment to what we are trying to show.

\begin{figure}[h]
\[
\frac { \begin{matrix} \inference { \frac { ? }{ \Gamma '\, \vdash \, rec\, :\, \later
        ^{\kappa}(Type\, \rightarrow \, a\, \rightarrow \, Stream^{\kappa}\, a) } \,
      \frac {
        \frac {  }{ \Gamma '\, \vdash \, a\, :\, Type }
      }
      { \Gamma '\, \vdash \,
        Next^{\kappa}\, a\, :\, \later ^{\kappa}\, Type }
    }{ \, \Gamma '\, \vdash \, rec\,
      \tensor ^{\kappa} \, (Next^{\kappa}\, a)\, :\, \later ^{\kappa}(a\, \rightarrow \, Stream^{\kappa}\,
      a)\ }  & \inference { \inference {  }{ \Gamma '\, \vdash \, n\, :\, a }  }{
      \Gamma '\, \vdash \, Next^{\kappa}\, n\, :\, \later ^{\kappa} \, a }  \end{matrix} }{
  \Gamma '\, \vdash \, (rec\, \tensor ^{\kappa} \, (Next^{\kappa}\, a))\, \tensor ^{\kappa} \,
  (Next^{\kappa}\, n))\, :\, \later ^{\kappa} Stream^{\kappa}\, a }
\]
\[
\Gamma '\, =\, \Gamma ,\, rec\, :\, \later ^{\kappa}((a\, :\, Type)\, \rightarrow \,
a\, \rightarrow \, Stream^{\kappa}\, a),\, a\, :\, Type,\, n\, :\, a
\]
  \caption{Part of an attempt to type repeat.}
  \label{fig:repeat_typing}
\end{figure}

One way of solving this could be to have the $\tensor ^{\kappa}$-rule take substitution in
types into account as seen in Figure~\ref{fig:tensor_with_subst}. This, however,
is not yet backed by the theory, and is therefore not an option.

\begin{figure}[h]
\[
\inference { \Gamma \, \vdash \, t\, :\, \later^{\kappa} ((a\, :\, A)\,
  \rightarrow \, B)\quad \Gamma \, \vdash \, u\, :\, \later^{\kappa} A }{
  \Gamma \, \vdash \, t\, \tensor ^{\kappa} \, u\, :\, \later^{\kappa} B[{ u
  }/{ a }] }
\]
  \caption{Tensor with substitution in types.}
  \label{fig:tensor_with_subst}
\end{figure}

Instead we change what is fixed by the fixpoint. We pull any parameter out,
changing the fixed type, such that \texttt{rec} now has type \texttt{$\later
  ^{\kappa}$(a $\rightarrow$ Stream$^{\kappa}$ a)}. This gives us the definition seen in
Figure~\ref{fig:repeat_guarded_example_new}. Here the \texttt{a} is fixed and
not part of the recursive reference. This allows us to type part of
\texttt{repeat} as exemplified in Figure~\ref{fig:repeat_typing_new}.

\begin{figure}[h]
  \begin{lstlisting}[mathescape]
repeat : (a : Type) $\rightarrow$ $\forall \kappa$ (a $\rightarrow$ Stream$^{\kappa}$ a)
repeat a = $\Lambda \kappa$ fix$^{\kappa}$($\lambda{}$rec$.\lambda{}$n$.$
             StreamCons a n (rec $\tensor ^{\kappa}$ (Next$^{\kappa}$$^{\kappa}$ n)))
\end{lstlisting}
  \caption{Repeat with the type parameter fixed.}
  \label{fig:repeat_guarded_example_new}
\end{figure}

\begin{figure}[h]
\[
\frac { \frac {  }{ \Gamma '\, \vdash \, rec\, :\, \later ^{\kappa}(a\, \rightarrow
    \, Stream^{\kappa}\, a) } \, \frac { \Gamma '\, \vdash \, n\, :\, a }{ \Gamma '\,
    \vdash \, Next^{\kappa}\, n\, :\, \later ^{\kappa}\, a }  }{ \, \Gamma '\, \vdash \, rec\,
  \tensor ^{\kappa} \, (Next^{\kappa}\, n)\, :\, \later ^{\kappa}Stream^{\kappa}\, a }
\]
\[
 \Gamma '\, =\, \Gamma ,\, rec\, :\, \later ^{\kappa}(a\, \rightarrow \, Stream^{\kappa}\,
 a),\, a\, :\, Type,\, n\, :\, a
\]

  \caption{Part of typing repeat with fixed type parameter.}
  \label{fig:repeat_typing_new}
\end{figure}

\paragraph{Multiple clauses}
Another problem occurs when we consider functions with multiple clauses,
e.g. functions defined with pattern matching. To understand the problem we must
first step out of the guarded recursive world for a moment and consider the
function \texttt{cycle} in Figure~\ref{fig:cycle_non_guarded}. Note that it is
not a guarded recursive definition, but a standard Idris definition.

\begin{figure}[h]
  \begin{lstlisting}[mathescape]
cycle : Nat $\rightarrow$ Nat $\rightarrow$ Stream Nat
cycle Z m = Z :: (cycle m m)
cycle (S n) m = (S n) :: (cycle n m)
\end{lstlisting}
  \caption{A function cycle in standard Idris}
  \label{fig:cycle_non_guarded}
\end{figure}

When transforming this to a guarded recursive form we want to make the fixed
point over both clauses. An intuitive way to get around this could be to
convert the pattern matching match into case-expressions. This is not possible
as TT does not have case-expressions, only top-level pattern
matching. Furthermore, a case-expression based solution would make even less
sense when we consider dependent pattern matching, since we by removing the
dependent pattern match change the type of the left hand side.

Instead, we can define cycle as two functions: One with the fixed point, and one
with the pattern match, as seen in Figure~\ref{fig:cycle_guarded}. This way, all
clauses of \texttt{cycle} are part of the same fixpoint. The recursive reference
\texttt{ref} is handed to \texttt{cycle} as a parameter. Note that this way of
handling the fixed point also works for functions with only one clause.

\begin{figure}[h]
\begin{lstlisting}[mathescape]
cycle : $\later ^{\kappa}$ (Nat $\rightarrow$ Nat $\rightarrow$ Stream$^{\kappa}$ Nat) $\rightarrow$
             Nat $\rightarrow$ Nat $\rightarrow$ Stream$^{\kappa}$ Nat
cycle rec    Z  m =
         StreamCons Z     (rec $\tensor ^{\kappa}$ (Next$^{\kappa}$ m)) $\tensor ^{\kappa}$ (Next$^{\kappa}$ m)
cycle rec (S n) m =
         StreamCons (S n) (rec $\tensor ^{\kappa}$ (Next$^{\kappa}$ n)) $\tensor ^{\kappa}$ (Next$^{\kappa}$ m)

cycle$'$ : $\forall \kappa$ (Nat $\rightarrow$ Nat $\rightarrow$ Stream$^{\kappa}$ Nat)
cycle$'$ = $\Lambda \kappa$ fix$^{\kappa}$($\lambda$rec.$\lambda$n.$\lambda$m. cycle rec n m)
\end{lstlisting}
  \caption{A guarded definition of cycle}
  \label{fig:cycle_guarded}
\end{figure}

Again, this solution has short comings. We fix the recursive
reference as \texttt{ref} and thereby also fix its type. This works out fine in
the simply typed case, but once we consider higher-order and especially
dependent types we run into problems. If we consider the function prepend from
Figure~\ref{fig:guarded_prepend}, the \texttt{n} in the type of \texttt{rec} is
fixed, e.g. in the second clause to \texttt{S n}. Since \texttt{xs} has type
\texttt{Vect n a}, this term is not well-typed.

\begin{figure}[h]
\begin{lstlisting}[mathescape]
prepend : (Later' (Vect n a -> Stream a -> Stream a)) -> Vect n a -> Stream a -> Stream a
prepend rec [] s = s
prepend rec (x :: xs) s = StreamCons x (compose {n=Now} (compose {n=Now} rec (Next xs)) (Next s))

prepend' : Forall (Vect n a -> Stream a -> Stream a)
prepend' = LambdaKappa (fix(\rec, xs, s => prepend rec xs s))
\end{lstlisting}
  \caption{A function prepending a vector on a stream.}
  \label{fig:guarded_prepend}
\end{figure}\todo{Prettify and verify figure}

To circumvent this we eliminate the \texttt{fix} operator all together according
to the elimination rules in Figure~\ref{fig:fix_elim_rules}. By eliminating the
fixpoint, we no longer fix the type of the recursive reference. Because of the
type of the guarded fixed point operator, the type of \texttt{rec} is
$\later^{\kappa}$A, which is also the type of \texttt{Next f}.

\begin{figure}[h]
  \[
\frac { \Delta ,\, \kappa ; \, \Gamma \, \vdash \, f\, =\, { fix }^{ \kappa  }(\lambda
  rec.\, e)\, :\, A }{ \Delta ,\, \kappa \, ; \Gamma \vdash \, f\, =\, e[{ (Next^{ \kappa
    }\, f) }/{ rec }]\, :\, A } fix_{E_1}
\]

\[
\frac { \Delta \, ; \Gamma \vdash \, f\, =\, \Lambda \kappa .{ fix }^{ \kappa  }(\lambda
  rec.\, e)\, :\, \forall \kappa .A }{ \Delta \, ; \Gamma \vdash \, f\, =\, \Lambda
  \kappa .e[{ (Next^{ \kappa  }\, f[\kappa ]) }/{ rec }]\, :\, \forall \kappa .A
} fix_{E_2}
\]
  \caption{Rules for fix elimination}
  \label{fig:fix_elim_rules}
\end{figure}

\paragraph{Singleton Clock}
To simplify the implementation we have limited our system to only have one
clock, rather than a clock environment. Either the clock is open, or the clock
is closed. This changes the rules we discussed in
Section~\ref{sec:guarded-recursion}, as seen in
Figure~\ref{fig:gr_rules_sin_clock}\todo{insert one clock rules}. Here
$\sqcup$ denotes the open clock, and $\sqcap$ the closed. \todo{Explain how we
  came to these rules}

\begin{figure}[h]

  \caption{Guarded Recursion rules with singleton clock.}
  \label{fig:gr_rules_sin_clock}
\end{figure}

While deriving this rule set from the original one has not followed a specific
methodology, a general trend is:

\begin{itemize}
\item If a rule required a specific clock in the environment, it now requires an
  open clock.
\item Side conditions talking about a specific clock being not being free in the
  environment are transformed to that no free clocks are allowed in the
  environment at all.
\end{itemize}

Note that the $\kappa$ has gone from a lot of the types and terms. This is
because we no longer talk about specific clocks, but about the
clock. I.e. $\later$ is always on the same clock and as such there is no need to
specify which. Also note that the $\kappa$ remains on some $\forall \kappa$ and
$\Lambda \kappa$. While these still only mention the singleton clock, the
$\kappa$ is kept to disambiguate these from regular quantification and
abstraction.

This change of course limits the set of programs for which we can infer guarded
recursion, and thereby ensure productivity. In Section~\ref{cha:evaluation} we
discuss how this limitation affects our system.

\paragraph{Modality of Functions}
In general, when defining a guarded recursive function, one has to consider how
to quantify over clocks. For example, in the definition of \texttt{repeat} from
Figure~\ref{fig:repeat_guarded_example_new} the clock quantification is on the
entire type, where as in the definition of \texttt{evens} from
Figure~\ref{fig:guarded_recursion_evens}, the clock quantification is on each
individual \texttt{Stream}. As there we increase the number of arguments we also
increase the number of different way we could quantify the function, making it
increasingly difficult to infer how to place them.

Because of this we have simplified to the problem. A function is either
\emph{causal} or \emph{not causal}. We call this the \emph{modality} of a
function. If a function is causal it means that the quantification is on the
entire type. In this sense \texttt{repeat} is said to be causal. If a function
is not causal the quantification is on each individual guarded type, meaning
that \texttt{evens} is \emph{not} causal.

While inferring the modality of a function is indeed be possible, simply by
trial and error, there might exist not guarded function with both a causal and
not causal guarded implementation. In such a situation the system would have no
way of knowing which modality to assign the function.

Instead of attempting to infer the modality, we let the user assign a modality
to a function. By doing this we ensure that the system does not infer a function
with the wrong modality.\todo{Explain what this means for recursive ref}

\section{Implementation}
In this section we go over how we have realized the above intuition into an
actual Idris implementation. We start by presenting the overall additions to the
Idris compiler environment, and then how the inference and checker systems have
been implemented.

\paragraph{Guarded Recursion Library}
The first step to adding guarded recursion to Idris is to add the guarded
recursive types and functions. We have added these to the Idris built-in
library, and not as a part of the prelude. This is because the user should be
able to check functions for productivity using our guarded recursion checker
without having to rely on the standard library.  While most of the
implementations are straight forward, and can be found in Appendix\todo{Add ref
  to appendix. And add appendix!}, there are interesting parts to discuss. We
have added the notion of \emph{how much later} something is, through the idea of
\texttt{Availability}, seen in Figure~\ref{fig:availability}. This is, in
conjunction with \texttt{Later} done so that we can many $\later$ applications
as a single \texttt{Later} applications.

\begin{figure}[h]
  \begin{lstlisting}[mathescape]
data Availability = Now | Tomorrow Availability

data Later' : Type -> Type where
  Next : {a : Type} -> a -> Later' a

Later : Availability -> Type -> Type
Later Now a = a
Later (Tomorrow n) a = Later' (Later n a)
\end{lstlisting}
  \caption{Availability.}
  \label{fig:availability}
\end{figure}

\paragraph{Guarded Names}
As we want to infer new types and terms, and not override the existing ones, we
need a system for creating a guarded name from an existing user written
name. While this is fairly trivial, it is an important part of our system. We
will hence forth refer to these as the \emph{guarded names} as oppose to their
original \emph{Idris names}. We will mark these guarded names with a subscript
$g$, such that a name $Name$ becomes $_gName$.

During compilation we keep a map from Idris names to their guarded names. This
means that we can for any Idris name find their guarded name, and vice
versa. This comes in handy when we infer the guarded terms.

\paragraph{Clocked Types}
These are made by inferring a new data declaration for any codata or corecord
declaration. This new data declaration is simply constructed during the
elaboration of the original and then elaborated by itself. This means that for
any user written codata or corecord declaration a guarded version is an
intrinsic part of the program.

A such guarded version of a declaration is fairly straight forward. Guarded
names are given to the type and to all constructors. Any recursive reference in
the type of the constructor is placed under a $\later$-type, in a similar
fashion to how Idris already handles lazy evaluation. The type constructor
remains unchanged. An example of this inferences for a codata declaration can be
seen in Figure~\ref{fig:guarded_stream_inf}. Note that the inferred declaration
is a data declaration, not codata. This is because we do not need both Idris's
built in laziness (\texttt{Inf}), and the guarded recursion laziness ($\later$)
\todo{Explain why these are not the same}.

\begin{figure}[h]
\begin{lstlisting}[mathescape]
codata Stream : Type -> Type where
  MkStream : a -> Stream a -> Stream a

data $_g$Stream : Type -> Type where
  $_g$MkStream : a -> $\later_g$Stream a -> $_g$Stream a
\end{lstlisting}
  \caption{Inference of the guarded stream declaration.}
  \label{fig:guarded_stream_inf}
\end{figure}

In the corecord case, we take a similar approach. However, instead of
constructors we have to guard projections. Again, any recursive projection is
guarded such that $A \rightarrow A$ becomes $A \rightarrow \later A$, and all
projections are given a guarded name. Figure~\ref{fig:guarded_tree_inf} shows an
example of such an inference.

\begin{figure}[h]
\begin{lstlisting}[mathescape]
corecord Tree a where
  left : Tree a -> Tree a
  value : Tree a -> a
  right : Tree a -> Tree a

record $_g$Tree a where
  $_g$left : $_g$Tree a -> $\later_g$Tree a
  $_g$value : $_g$Tree a -> a
  $_g$right : $_g$Tree a -> $\later_g$Tree a
\end{lstlisting}
  \caption{Inference of the guarded tree declaration.}
  \label{fig:guarded_tree_inf}
\end{figure}

Furthermore, for each projection we also generate what we call a \emph{forall
  projection}, henceforth denoted as $_\forall Name$. We use this for
projections on quantified types. Consider a coinductive type $A$ with a
projection $p$ of type $A \rightarrow A$, and a variable $x$ of type $\forall
\kappa.A$. In order to perform $p$ on $x$ and maintain the quantification in the
type, we must first apply the clock to $x$, apply $_gp$, and then abstract over the
clock again using $\Lambda \kappa$. This gives us:

\[
\Lambda \kappa . _gp (apply\,x) : \forall \kappa . \later A
\]

The type of the above is isomorphic with $\forall \kappa . A$ according to the
isomorphism described by Rasmus M\o gelberg\,\cite{Mogelberg:2014} seen in
Figure~\ref{fig:quantified_later_iso}. As a short for all of this we simply use
$_\forall p$ which has type $\forall A \rightarrow \forall A$, giving us the
same result. As such these \emph{forall projections} do not add anything new,
they are just a simpler way for us to perform projections on terms of quantified
type. The intuition is that because of Figure~\ref{fig:quantified_later_iso} we
can perform projections on quantified types without having to worrying about
their lateness. Because they are quantified over clocks, they are always available.

\begin{figure}[h]
\[
\forall \kappa .A\cong \forall \kappa .\rhd ^\kappa A
\]
  \caption{A type isomorphism describe by Rasmus M\o gelberg\,\cite{Mogelberg:2014}.}
  \label{fig:quantified_later_iso}
\end{figure}

\subsection{Inference}
% Regler - forklar (også notation)
% Rekursive referencer
% Eksempel - zeros?
% Preprocessing
% Renaming
% Forskel på causal og non causal

%(1) Gennemgang af interessante regler
%(2) Eksempel
%(3) Implementation details, e.g. when Next and tensor rules clash
%%(3.1) Preprocessing, herunder renaming
%%(3.2) Forskel på causal og non causal

Inference of guarded recursive TT terms from elaborated TT terms happens by a
bottom-up, type-directed derivation according to the rules given in Figure~\ref{fig:epsilon_rules}\todo{Behøver vi tjekke :Type præmisserne her?}. Let
$c$ be the singleton clock, $\Gamma$ be a typing environment, $\rho$ be a tuple matching an Idris name $n$ to a
guarded name $_gn$ (and for projections, a name for its forall-projection, $_{\forall}n$) and $\phi$ be a (possibly empty) collection of such tuples:
\begin{align*}
   c,\,c^\prime &::=\,\sqcup\,|\,\sqcap \\
   \rho &::= (n,\, _gn)\,|\,(n,\, _gn,\, _{\forall}n)  \\
   \phi &::=\,\cdot\,|\,\rho\,\phi \\
   IE,\,IE^\prime &::= \phi;\,c;\,\Gamma
\end{align*}
The singleton clock can appear either as open ($\sqcup$), closed ($\sqcap$), or
irrelevant ($c$). Then guarded recursive terms are derived in an inference environment $IE$, such that
${IE\vdash e : A \overset{B}{\Longrightarrow} IE^\prime \vdash e^\prime : B}$ describes the
transformation ($\overset{B}{\Longrightarrow}$) of an elaborated TT term $e$ of type
$A$ in $IE$ to a guarded recursive TT term $e^\prime$ of type $B$ in
$IE^\prime$. The $B$ in $\overset{B}{\Longrightarrow}$ implies that the transformation
is type-directed, since it denotes that the desired output type $B$ is input to
the transformation function.

In Figure~\ref{fig:epsilon_rules}, the $\Longrightarrow_{Next^\kappa}$ rule follows directly from the $Next$ rule in Figure~\ref{fig:guarded_recursion_rules_clocks}. The
$\Longrightarrow_{\Lambda\kappa}$ and $\Longrightarrow_{apply^\kappa}$ rules have a
similar structure, but here the clock changes state from premise to conclusion
(e.g. from open to closed). For handling guarded names, the
$\Longrightarrow_{\phi}$ rule says that if some Idris name has type $A$, and its
guarded version has type $A^\prime$, then we can insert the guarded name in its
place. Note that the type $A^\prime$ of the guarded name is not arbitrary, but follows the
rules for causal and non-causal function types (see Section~\todo{insert ref
  here}). Renaming is important for the $\Longrightarrow_{App}$ rule, since it
is often used for the transformations required in the premises. This reasoning
also applies to the $\Longrightarrow_{\tensor^{\kappa}_{n}}$ rule. Here,
the $n$ is a natural number denoting the required ``lateness'' of both input and
output, where $n \ge 1$. Specifically, ${\laterkappa_{\!\!1} B \cong \laterkappa B}, {\laterkappa_{\!\!2}
\cong \laterkappa\laterkappa B}$ and so on. For trivial cases, the
$\Longrightarrow_{Refl}$ rule is used. \todo{Say something about abstraction and
let-rules here, when they have been formulated.}

\begin{figure}
\textbf{The transformation to guarded recursive terms}$\hfill \boxed{IE\vdash e : A \overset{B}{\Longrightarrow} IE^\prime \vdash e^\prime : B}$
\input{figures/epsilon_next_rule.tex}
\input{figures/epsilon_lambdakappa_rule.tex}
\input{figures/epsilon_apply_rule.tex}
\input{figures/epsilon_renaming_rule.tex}
\input{figures/epsilon_app_rule.tex}
\input{figures/epsilon_tensor_rule.tex}
\input{figures/epsilon_refl_rule.tex}
\input{figures/epsilon_lambda_rule.tex}
  \caption{Rules for inferring guarded recursive terms.}
  \label{fig:epsilon_rules}
\end{figure}

\paragraph{An Example}

Figure~\ref{fig:epsilon_zeros} shows how a guarded recursive version of
\texttt{zeros} can be inferred using the rules presented in Figure~\ref{fig:epsilon_rules}. The
derivation proceeds by continually pushing type requirements down into the
syntax tree, until these can be resolved either trivially (using the
$\Longrightarrow_{Refl}$ rule), or by renaming (using the
$\Longrightarrow_{\phi}$ rule). Note that all premises ensuring type consistency
have been omitted for brevity. A full example, along with a more advanced one,
can be found in Appendix~\ref{app:infer-guard-recurs}.\todo{Make this appendix}
\begin{figure}
\begin{lstlisting}[mathescape]
causal zeros : Stream Nat
zeros = Z :: zeros

$_g$zeros : $\forall\kappa.$ $_g$Stream Nat
$_g$zeros = $\Lambda\kappa.$ Z $_g$:: (Next (apply $_g$zeros))
\end{lstlisting}
  % \[
  % \frac{x}{\eps{IE}{Z :: zeros}{Stream Nat}{IE}{Z :: gzeros}{gStream Nat}}
  % \]
\input{figures/epsilon_zeros}
  \caption{Above: The user-provided program \texttt{zeros}, along with the
    inferred program $_g$\texttt{zeros}. Below: Inferring $_g$\texttt{zeros} from \texttt{zeros} using the rules from
  Figure~\ref{fig:epsilon_rules}.}
  \label{fig:epsilon_zeros}
\end{figure}

\subsubsection{Implementing the Inference System}

\paragraph{Preprocessing} Two aspects of the inference system, renaming and
delaying the recursive reference, are mandatory, and these
are therefore handled in a separate preprocessing step. Both must take modality
into account.

Renaming, i.e. all applications of the $\Longrightarrow_{\phi}$ rule, is
performed by substituting all Idris names in $\phi$ with their guarded
versions. Special care must be taken when substituting names of projection
functions, since the modality of the function in question, $f$, influences the choice
of guarded name. If $f$ is causal,

Delaying the recursive reference
%Preprocessing
%Modality and Recursive reference
%When rules clash

\subsection{Checking}
To check that what we infer actually conforms to the guarded recursion rules, we
have implemented a checker. This algorithm simply checks a term to have a given
type within the rule from Figure~\ref{fig:gr_rules_sin_clock}. To the algorithm
less error prone it is implemented in the simplest fashion possible and as
attempts to stick strictly to the typing rules. This means that the checking
algorithm is very simple, conservative, and rigid. It expect types and terms to
be of a specific structure, and it discards anything it can guarantee the
correctness off.

The checker traverses a term, and unfolds them according to the rules. Any rules
that requires a type equality is done by asking the Idris type system for
conversion equality, and if the type of a term is needed it is checked using the
Idris type checker.

The structure of the code itself aims to take care of as much as the check using
pattern matching. While not always possible, ideally the conclusion of a rule
should be represented by a pattern match, and the premise(s) by a right-hand
side. By doing this we can, through different patterns, be very selective about
what is accepted by the checker and discard anything that does not match the
conclusion of a rule.

Getting more into the actual implementation the checking algorithm is a function
\texttt{check}, with the type signature seen in Figure~\ref{fig:check_type}. The
parameters are as follows:\todo{Is this too low level?}

\begin{itemize}
\item \texttt{Clock} is the clock under which we are checking the term. A clock
  is simply either open or closed.
\item \texttt{Env} is the local environment, usually generated from the
  left-hand side of the clause being checked.
\item \texttt{(Name, Type)} is name and the type of the recursive
  reference.
\item \texttt{Term} is the term being checked.
\item \texttt{Type} is the type the term is being checked to have.
\item \texttt{Idris Totality} is the result of the algorithm wrapped in the
  Idris monad\todo{Is the Idris monad explained at this point?}.
\end{itemize}

\begin{figure}[h]
\begin{lstlisting}
check :: Clock ->
         Env ->
         (Name, Type) ->
         Term ->
         Type ->
         Idris Totality
\end{lstlisting}
  \caption{Checking algorithm type.}
  \label{fig:check_type}
\end{figure}

The majority of the conclusions of the rules can be reflected as patterns. If we
wish to e.g. delay a term, the $Next_i$-rule requires that, (1) the clock is
open, (2) the term is on the form $Next t$, and (3) the type is on the form
$\later A$. These requirements are expressed as a pattern in
Figure~\ref{fig:next_pattern}. The view-patterns can be read as regular pattern
match, such that \texttt{next -> Extracted t} is \texttt{Next t}. The premise
from the rule is reflected on the right-hand side. simply check that given the
same environments \texttt{t} has type \texttt{a}.

\begin{figure}[h]
\begin{lstlisting}
check Open g n (next -> Extracted t) (later -> Extracted a)
     =
     check Open g n t a
\end{lstlisting}
  \caption{$Next_{i}$ pattern. Note the use of view-patterns (the -> syntax).}
  \label{fig:next_pattern}
\end{figure}

\paragraph{No Free Clocks in Environment}
% No free clocks in finished definitions.
% Check everything in local environment with closed clock.
Some rules have a side condition dictating that there must no free clocks in the
variable environment. These are checked by checking that every term in the
variable can be checked under a closed clock. This is the same as no clocks
being free, because any term or type with a free clock would require the clock
to be open in order to be well-formed.
\paragraph{Identifying the Recursive Reference}
\todo{This paragraph needs more implementation to be written}
%##########
% To faser: Inferens og check - bør kunne beskrives separat
% Inferens - regler
% Check - regler
% Correctness claim - Hvordan kan vi være sikre på at vi inferer guarded
% recursion?
% Preservation of semantics - Har den infererede term samme semantik som
% input-termen?
% Tensor-regel og parametre
%##########

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "../copatterns-thesis"
%%% End:


\chapter[Bremstrahlung]{Bremstrahlung}

Bremstrahlung dominates other muon interaction processes in the region of
catastrophic collisions ($v \geq 0.1$ ); at "moderate" muon
energies - above knock onelectron production kinematic limit.

\section{Differential cross section }

The differential cross section for muon bremstrahlung (in units $cm^{2}/(g~GeV)$)
can be written as :

\begin{eqnarray}
    \frac{d \sigma (E, \epsilon, Z, A )} {d \epsilon} &=&
  \frac{16}{3} \alpha N_{A} (\frac{m}{\mu} r_{e} )^2 \frac{1}{ \epsilon A} Z
  (Z \Phi_{n}+ \Phi_{e})(1-v+\frac{3}{4}v^{2})   \\
    \frac{d \sigma (E, \epsilon, Z, A )} {d \epsilon} &=& 0 \quad
    if \quad \epsilon \geq \epsilon_{max} = E- \mu  \nonumber
\end{eqnarray}
%
where $\mu$ and $m$ are the muon and  electron masses,
$Z$ and $A$ are the atomic number and atomic weight of the material
and $N_{A}$ is Avogadro's number.
 If we indicate with $E$ and $T$ the initial total and kinetic energy of muon,
$\epsilon$--emitted photon energy we have: $\epsilon = E - E'$ and
relative energy transfer $v = \epsilon /E$.

Functions $\Phi_{n}$ and $\Phi_{e}$ represent contribution
of nuclear and electrons and can be expressed as :

\begin{eqnarray*}
 \Phi_{n} &=& \ln \frac {BZ^{-1/3}(\mu + \delta (D_{n}' \sqrt{e} -2))}
    {D_{n}'(m+ \delta \sqrt{e}BZ^{-1/3})} ; \\
   &=&  0 \quad if \quad negative;
\end{eqnarray*}

\begin{eqnarray*}
  \Phi_{e} &=& \ln \frac {B'Z^{-2/3} \mu }
   {(1+ \frac{\delta \mu}{m^{2} \sqrt{e}})(m+ \delta \sqrt{e} B'Z^{-2/3}) }  \\
   &=&  0 \quad if \quad \epsilon \geq \epsilon'_{max} = E/(1+ \mu^{2}/2mE) \\
   &=&  0 \quad if \quad negative
\end{eqnarray*}
%
\begin{eqnarray*}
\delta &=& \mu^{2} \epsilon /2EE' = \mu^{2} v/2(E- \epsilon) \\
D'_{n} &=& D_{n}^{(1-1/Z)}, \quad D_{n}= 1.54A^{0.27}  \\
B &=& 183, \quad B'=1429, \quad \sqrt{e}=1.648(721271).
\end{eqnarray*}
%
Special case for hydrogen ($Z$=1): $B = 202.4,\: B' = 446, \: D_{n}' = D_{n}$.

Formulae are mostly taken from (\cite{brem.kel95}) and (\cite{brem.kel97}).
They include improved (in the region $v \sim 1$ and low $Z$,
 in comparison with
(\cite{brem.petr68}) correction for nuclear size. Bremstrahlung on atomic
electrons (taking into account target recoil and atomic binding) is
introduced instead of a rough substitution $Z(Z+1) $. Also  (\cite{brem.andr94})
correction for processes with nuclear excitation is included here.

\subsection{Aplicability and restrictions of the method}

1. $E \gg \mu $, ultrarelativistic approximation used in this method; \\
2. $E \leq 10^{20}$ eV, above LPM cross section suppression can be expected;\\
3. $v \geq 10^{-6}$ , below , Ter-Mikaelyan suppression can be expected.
However, in this region cross section of muon bremstrahlung is many
orders of magnitude less then for other processes.\\
4. Coulomb corrections is not included. However Bugaev's calculations
show that it is small for muon bremstrahlung.

\section{Continuous energy loss}

The restricted energy loss for muon bremsrahlung $(d E/ dx)_{rest}$
 with relative transfers $v = \epsilon / (T+ \mu) \leq v_{cut}$
can be calculated as follows :
$$
\frac{d E}{d x}
= \int_{0}^{\epsilon_{cut}}  \epsilon \sigma (E,\epsilon )  \: d \epsilon  =
(T+ \mu ) \int_{0}^{v_{cut}}  v \sigma (E, v )  \: d v
$$
%
If user's cut $v_{cut} \geq v_{max}=T/(T+ \mu)$, total average
energy loss is calculated. Integration is done on the basis of Gauss quadratures,
binnig provides  the accuracy better
than about 0.03\% for $T = 1$ GeV, $Z=1$ (rapidly improving with increasing $T$
and $Z$).

\section{Total cross-section}

The integration of differential cross section  (1) over
$d\epsilon$ gives the total cross-section for muon bremstrahlung:

\begin{equation}
\sigma_{tot} (E, \epsilon_{cut})
= \int_{\epsilon_{cut}}^{\epsilon_{max}}  \sigma (E,\epsilon )  \: d \epsilon  =
 \int_{\ln v_{cut}}^{\ln v_{max}}  v \sigma (E, v )  \: d (\ln v)\:,
\end{equation}
where $v_{max}=T/(T+ \mu)$. If $v_{cut} \geq v_{max}$ , $\sigma_{tot}$ = 0.

\section{Sampling}

Random photon energy $\epsilon_{p}$ is found from the numerical solution
of the equation :
$$ P \:= \int_{\epsilon_{p}}^{\epsilon_{max}}  \sigma (E,\epsilon,Z,A )  \: d \epsilon \:
 / \: \int_{\epsilon_{cut.}}^{\epsilon_{max}}  \sigma (E,\epsilon,Z,A )  \: d \epsilon .
$$
%
Here $P$ is random uniform probability, $\epsilon_{max}=T$,
$\epsilon_{cut}=(T+\mu) \cdot v_{min.cut}$;
$v_{min.cut}=10^{-5}$ being a relative transfer cut adopted
in the algorithm.

For fast sampling, solution of (2) is tabulated at initialization
for a set of $Z,T,P$. In simulation, sampling subroutine returns random
$\epsilon_{p}$ corresponding to probability $P$,
interpolation in the table being used.

Tabulation subroutine uses function (1) for differential
cross section. The table contains the values :
\begin{equation}
 x_{p} = \ln (v_{p} / v_{max})/\ln (v_{max}/v_{min.cut}),
\end{equation}
where $v_{p}= \epsilon_{p}/(T+ \mu),\: v_{max} = T/(T+ \mu).$
The table parameters are : $Z_{min}=1, \: Z_{max}=128; \:
T_{min}=1$ GeV, $T_{max}=10^{6}$ GeV ;
$P_{min}=10^{-5}, \: P_{max}=1.$

Atomic weight (which is the necessary parameters in (1)) is estimated
here with iterative solution of the known relation (approximate) :
$$ A = Z (2+0.015 A^{2/3}),$$
for $Z=1$ it is used $A=1$ .
%
To  find $x_{p}$ (and, respectively, $\epsilon_{p}$) corresponding to
a given probability $P$, in sampling subroutine the linear
interpolation in $\ln Z, \: \ln T$, and cubic (4 points Lagrange) interpolation
in $\ln P$ is realised. For $P \leq P_{min}$ , linear interpolation
in $(P,x)$ - coordinates is used, noticeably, $x = 0$ at $P = 0$.
Then, random energy $\epsilon_{p}$ is obtained from the inverse
transformation of (3) :
%
$$\epsilon_{p} = (T+ \mu ) v_{max} (v_{max}/v_{min})^{x_{p}} $$
%
The algorithm with the parameters described above has been
tested for various $Z$ and $T$. It provides the reproduction
of the differential cross section with about 0.2 - 0.7 \%
accuracy for $T \geq 10$ GeV, the average total energy loss
being kept within 0.3\%. Accuracy improves with the increase
of $T$, satisfactory results are obtained also for
$1 \leq T \leq 10$ GeV.

It is important to note that this sampling scheme allows
to generate $\epsilon_{p}$ for different user's cuts on $v$
grater then $v_{min.cut}$.
To realize such simulation, it is sufficient to
re-define probability variable :
%
$$P' = P \: \sigma_{tot} \: (v_{user.cut}) / \sigma_{tot} (v_{min.cut})$$
%
and just use $P'$ in sampling subroutine.
Thus, time consuming re-calculation of 3-dimensional table
is not required (only calculation
of $\sigma_{tot}(v_{user.cut})$ is needed).

After the successful sampling of $\epsilon$,  the direction
 of the emitted photon is generated with respect to the direction of the
incident particle. The azimuthal angle $\phi$ is generated isotropically;
the polar angle
$\theta$ is calculated from the energy momentum conservation.
This information
is used to calculate the energy and momentum of both scattered
particles and to transform them into the {\em global} coordinate system.

\section{Status of this document}
 9.10.98 created by R.Kokoulin and A.Rybin .

\begin{thebibliography}{99}

\bibitem[Keln95]{brem.kel95}
  S.R.Kelner, R.P.Kokoulin, A.A.Petrukhin. Preprint MEPhI 024-95, Moscow, 1995.
\bibitem[Keln97]{brem.kel97}
  S.R.Kelner, R.P.Kokoulin, A.A.Petrukhin. Phys. Atomic Nuclei, 60(1997)576.
\bibitem[Petr68]{brem.petr68}
  A.A.Petrukhin, V.V.Shestakov. Canad.J.Phys., 46(1968)S377.
\bibitem[Andr94]{brem.andr94}
  Yu.M.Andreyev, L.B.Bezrukov, E.V.Bugaev. Phys. Atomic Nuclei, 57(1994)2066.
\end{thebibliography}


\documentclass[english]{../thermomemo/thermomemo}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{array}% improves tabular environment.
\usepackage{dcolumn}% also improves tabular environment, with decimal centring.
\usepackage{booktabs}
\usepackage{todonotes}
\usepackage{subcaption,caption}
\usepackage{xspace}
\usepackage{tikz}
\usetikzlibrary{arrows}
\usetikzlibrary{snakes}
\usepackage{verbatim}
\usepackage{hyperref}
\usepackage{xcolor}
\hypersetup{
  colorlinks,
  linkcolor={red!50!black},
  citecolor={blue!50!black},
  urlcolor={blue!80!black}
}
%
% Egendefinerte
%
% Kolonnetyper for array.sty:
\newcolumntype{C}{>{$}c<{$}}
\newcolumntype{L}{>{$}l<{$}}
%
\newcommand*{\unit}[1]{\ensuremath{\,\mathrm{#1}}}
\newcommand*{\uunit}[1]{\ensuremath{\mathrm{#1}}}
%\newcommand*{\od}[3][]{\frac{\mathrm{d}^{#1}#2}{\mathrm{d}{#3}^{#1}}}% ordinary derivative
\newcommand*{\od}[3][]{\frac{\dif^{#1}#2}{\dif{#3}^{#1}}}% ordinary derivative
\newcommand*{\pd}[3][]{\frac{\partial^{#1}#2}{\partial{#3}^{#1}}}% partial derivative
\newcommand*{\pdc}[3]{\frac{\partial^{2}#1}{\partial{#2}\partial{#3}}}% partial derivative
\newcommand*{\pdt}[3][]{{\partial^{#1}#2}/{\partial{#3}^{#1}}}% partial
                                % derivative for inline use.
\newcommand{\pone}[3]{\frac{\partial #1}{\partial #2}_{#3}}% partial
                                % derivative with information of
                                % constant variables
\newcommand{\ponel}[3]{\frac{\partial #1}{\partial #2}\bigg|_{#3}} % partial derivative with informatio of constant variable. A line is added.
\newcommand{\ptwo}[3]{\frac{\partial^{2} #1}{\partial #2 \partial
    #3}} % partial differential in two different variables
\newcommand{\pdn}[3]{\frac{\partial^{#1}#2}{\partial{#3}^{#1}}}% partial derivative

% Total derivative:
\newcommand*{\ttd}[2]{\frac{\mathrm{D} #1}{\mathrm{D} #2}}
\newcommand*{\td}[2]{\frac{\mathrm{d} #1}{\mathrm{d} #2}}
\newcommand*{\ddt}{\frac{\partial}{\partial t}}
\newcommand*{\ddx}{\frac{\partial}{\partial x}}
% Vectors etc:
% For Computer Modern:

\DeclareMathAlphabet{\mathsfsl}{OT1}{cmss}{m}{sl}
\renewcommand*{\vec}[1]{\boldsymbol{#1}}%
\newcommand*{\vektor}[1]{\boldsymbol{#1}}%
\newcommand*{\tensor}[1]{\mathsfsl{#1}}% 2. order tensor
\newcommand*{\matr}[1]{\tensor{#1}}% matrix
\renewcommand*{\div}{\boldsymbol{\nabla\cdot}}% divergence
\newcommand*{\grad}{\boldsymbol{\nabla}}% gradient
% fancy differential from Claudio Beccari, TUGboat:
% adjusts spacing automatically
\makeatletter
\newcommand*{\dif}{\@ifnextchar^{\DIfF}{\DIfF^{}}}
\def\DIfF^#1{\mathop{\mathrm{\mathstrut d}}\nolimits^{#1}\gobblesp@ce}
\def\gobblesp@ce{\futurelet\diffarg\opsp@ce}
\def\opsp@ce{%
  \let\DiffSpace\!%
  \ifx\diffarg(%
    \let\DiffSpace\relax
  \else
    \ifx\diffarg[%
      \let\DiffSpace\relax
    \else
      \ifx\diffarg\{%
        \let\DiffSpace\relax
      \fi\fi\fi\DiffSpace}
\makeatother
%
\newcommand*{\me}{\mathrm{e}}% e is not a variable (2.718281828...)
%\newcommand*{\mi}{\mathrm{i}}%  nor i (\sqrt{-1})
\newcommand*{\mpi}{\uppi}% nor pi (3.141592...) (works for for Lucida)
%
% lav tekst-indeks/subscript/pedex
\newcommand*{\ped}[1]{\ensuremath{_{\text{#1}}}}
\newcommand*{\ap}[1]{\ensuremath{^{\text{#1}}}}
\newcommand*{\apr}[1]{\ensuremath{^{\mathrm{#1}}}}
\newcommand*{\pedr}[1]{\ensuremath{_{\mathrm{#1}}}}
%
\newcommand*{\volfrac}{\alpha}% volume fraction
\newcommand*{\surften}{\sigma}% coeff. of surface tension
\newcommand*{\curv}{\kappa}% curvature
\newcommand*{\ls}{\phi}% level-set function
\newcommand*{\ep}{\Phi}% electric potential
\newcommand*{\perm}{\varepsilon}% electric permittivity
\newcommand*{\visc}{\mu}% molecular (dymamic) viscosity
\newcommand*{\kvisc}{\nu}% kinematic viscosity
\newcommand*{\cfl}{C}% CFL number

\newcommand*{\cons}{\vec U}
\newcommand*{\flux}{\vec F}
\newcommand*{\dens}{\rho}
\newcommand*{\svol}{\ensuremath v}
\newcommand*{\temp}{\ensuremath T}
\newcommand*{\vel}{\ensuremath u}
\newcommand*{\mom}{\dens\vel}
\newcommand*{\toten}{\ensuremath E}
\newcommand*{\inten}{\ensuremath e}
\newcommand*{\press}{\ensuremath p}
\renewcommand*{\ss}{\ensuremath a}
\newcommand*{\jac}{\matr A}
%
\newcommand*{\abs}[1]{\lvert#1\rvert}
\newcommand*{\bigabs}[1]{\bigl\lvert#1\bigr\rvert}
\newcommand*{\biggabs}[1]{\biggl\lvert#1\biggr\rvert}
\newcommand*{\norm}[1]{\lVert#1\rVert}
%
\newcommand*{\e}[1]{\times 10^{#1}}
\newcommand*{\ex}[1]{\times 10^{#1}}%shorthand -- for use e.g. in tables
\newcommand*{\exi}[1]{10^{#1}}%shorthand -- for use e.g. in tables
\newcommand*{\nondim}[1]{\ensuremath{\mathit{#1}}}% italic iflg. ISO. (???)
\newcommand*{\rey}{\nondim{Re}}
\newcommand*{\acro}[1]{\textsc{\MakeLowercase{#1}}}%acronyms etc.
\newcommand*{\ousum}[2]{\overset{#1}{\underset{#2}{\sum}}}

\newcommand{\nto}{\ensuremath{\mbox{N}_{\mbox{\scriptsize 2}}}}
\newcommand{\chfire}{\ensuremath{\mbox{CH}_{\mbox{\scriptsize 4}}}}
%\newcommand*{\checked}{\ding{51}}
\newcommand{\coto}{\ensuremath{\text{CO}_{\text{\scriptsize 2}}}}
\newcommand{\celsius}{\ensuremath{^\circ\text{C}}}
\newcommand{\clap}{Clapeyron~}
\newcommand{\subl}{\ensuremath{\text{sub}}}
\newcommand{\spec}{\text{spec}}
\newcommand{\sat}{\text{sat}}
\newcommand{\sol}{\text{sol}}
\newcommand{\liq}{\text{liq}}
\newcommand{\vap}{\text{vap}}
\newcommand{\amb}{\text{amb}}
\newcommand{\tr}{\text{tr}}
\newcommand{\crit}{\text{crit}}
\newcommand{\entr}{\ensuremath{\text{s}}}
\newcommand{\fus}{\text{fus}}
\newcommand{\flash}[1]{\ensuremath{#1\text{-flash}}}
\newcommand{\spce}[2]{\ensuremath{#1\, #2\text{ space}}}
\newcommand{\spanwagner}{\text{Span--Wagner}}
\newcommand{\triplepoint}{\text{TP triple point}}
\newcommand{\wrpt}{\text{with respect to}\xspace}
\newcommand{\excess}{\text{E}\xspace}
\newcommand{\comb}{\text{comb}\xspace}
\newcommand{\FH}{\text{FH}\xspace}
\newcommand{\SG}{\text{SG}\xspace}
\newcommand{\NC}{\text{NC}\xspace}
\newcommand{\NGr}{\text{NG}\xspace}
\newcommand{\res}{\text{R}\xspace}

\title{UNIFAC excess gibbs mixing rules}
\author{Morten Hammer}

\graphicspath{{gfx/}}

\begin{document}
\frontmatter
\tableofcontents
\section{Introduction}
The UNIFAC (\textit{UNI}QUAC \textit{F}unctional-group \textit{A}ctivity
\textit{C}oefficients) model \cite{Fredenslund1975}, is a group
contribution model, and a further development of the UNIQUAC model
\cite{Abrams1975}. Being a group contribution model, it accounts for
molecular groups like $\text{C-H}_2$ and $\text{C-H}_3$,
that can be thought upon as monomers in a polymer.

The UNIFAC excess Gibbs mixing rule have found application in the
predictive SRK, PSRK \cite{Holderbaum1991}, model, and VTPR
\cite{Collinet2006}. It is also used as the universal mixing rule
(UMR) \cite{Voutsas2004} togther with t-mPR
\cite{Magoulas1990,Avlonitis1994}. The combined model is denoted
UMR-PR.

\section{UNIFAC model}
The UNIFAC model \cite{Fredenslund1975} is given as follows,
\begin{equation}
  \frac{A^\res}{RT} = \frac{A^\excess}{RT} - \frac{A^\excess}{RT_0} = - \ousum{\NC}{i} n_i \ousum{\NGr}{k}  v_k^i Q_k(\Lambda_k - \Lambda_k^i).
  \label{eq:Ae}
\end{equation}
The symbols and formalism of Michelsen \cite{Michelsen2007} is
used. $A^\excess/(RT_0)$ is the combinatorial term and is described in
a later sub section. It is assumed that $A^\excess = G^\excess$.

The different symbols are defined as follows,
\begin{align}
  \Lambda_k &= \ln \ousum{\NGr}{j}  \Theta_j \tilde{E}_{jk},\label{eq:Lambda_k}\\
  \Lambda_k^i &= \ln \ousum{\NGr}{j}  \Theta_j^i \tilde{E}_{jk}, \label{eq:Lambda_ki}\\
  \tilde{E}_{jk} &= \exp \left(-\frac{\tilde{U}_{jk}}{RT}\right), \label{eq:E_jk}\\
  \Theta_j &= \frac{Q_j \ousum{\NC}{l}n_lv_j^l}{\ousum{\NC}{l}n_l\ousum{\NGr}{m}v_m^lQ_m}, \label{eq:Theta_j}\\
  \Theta_j^i &= \frac{Q_j v_j^i}{\ousum{\NGr}{k}v_k^iQ_k}. \label{eq:Theta_ji}
\end{align}
Here $Q_k$ is the group surface area of group $k$, and $v_k^i$ is the
number of groups $k$ in molecule $i$. Both $Q_k$ and $v_k^i$ are
constants. $\tilde{U}_{jk}$ is the interaction energy per unit surface
area of the $j-k$ group interaction. $\tilde{U}_{jk}$ can be a
constant, or a temperature function.

\subsection{Differentials}
Differentiating \ref{eq:Ae} \wrpt $n_\alpha$ we get,
\begin{equation}
  \frac{1}{RT}\pd{A^\res}{n_\alpha} = \frac{A^\res_\alpha}{RT} = - \ousum{\NGr}{k}  v_k^\alpha Q_k(\Lambda_k - \Lambda_k^\alpha) - \ousum{\NC}{i} n_i \ousum{\NGr}{k}  v_k^i Q_k \pd{\Lambda_k}{n_\alpha}.
  \label{eq:dAedna}
\end{equation}
Michelsen \cite[Chap.~5,Eq.~56]{Michelsen2007} show that
\begin{equation}
  \ousum{\NC}{i} n_i \ousum{\NGr}{k}  v_k^i Q_k \pd{\Lambda_k}{n_\alpha} = \ousum{\NGr}{j}v_j^\alpha Q_j\left(\ousum{\NGr}{k}\frac{\Theta_j \tilde{E}_{jk}}{\ousum{\NGr}{l}\Theta_l \tilde{E}_{lk}} -1\right).
  \label{eq:sumdLambdadna}
\end{equation}
But since second differentials are required, it do not help much for
the compositional differentials. Using
\begin{equation}
  \Lambda_k = \ln \ousum{\NGr}{j}  \Theta_j \tilde{E}_{jk} = \ln \ousum{\NC}{l}n_l \ousum{\NGr}{j} v_j^l Q_j \tilde{E}_{jk} -\ln \ousum{\NC}{l}n_l\ousum{\NGr}{m}v_m^lQ_m,
\end{equation}
we get
\begin{equation}
  \pd{\Lambda_k}{n_\alpha} = \frac{\ousum{\NGr}{j} v_j^\alpha Q_j \tilde{E}_{jk}}{\ousum{\NC}{l}n_l \ousum{\NGr}{j} v_j^l Q_j \tilde{E}_{jk}} - \frac{\ousum{\NGr}{m}v_m^\alpha Q_m}{\ousum{\NC}{l}n_l\ousum{\NGr}{m}v_m^lQ_m}.
  \label{eq:dLambdadna}
\end{equation}
Differentiating \ref{eq:dAedna} further \wrpt $n_\beta$ we get,
\begin{align}
  \frac{A^\res_{\alpha\beta}}{RT} &= - \ousum{\NGr}{k}  Q_k \left(v_k^\alpha  \pd{\Lambda_k}{n_\beta} + v_k^\beta \pd{\Lambda_k}{n_\alpha}\right) - \ousum{\NC}{i} n_i \ousum{\NGr}{k}  v_k^i Q_k \ptwo{\Lambda_k}{n_\alpha}{n_\beta}, \label{eq:d2Aedna2}\\
&= - \ousum{\NGr}{k}  Q_k \left(v_k^\alpha  \pd{\Lambda_k}{n_\beta} + v_k^\beta \pd{\Lambda_k}{n_\alpha}\right) - \ousum{\NGr}{k}  \left(\ousum{\NC}{i} n_i v_k^i\right) Q_k \ptwo{\Lambda_k}{n_\alpha}{n_\beta}.
\end{align}
Differentiating Equation \ref{eq:dLambdadna} we get the second differential of $\Lambda_k$,
\begin{equation}
  \ptwo{\Lambda_k}{n_\alpha}{n_\beta} = -\frac{\left(\ousum{\NGr}{j} v_j^\alpha Q_j \tilde{E}_{jk}\right) \left(\ousum{\NGr}{j} v_j^\beta Q_j \tilde{E}_{jk}\right)}{\left(\ousum{\NC}{l}n_l \ousum{\NGr}{j} v_j^l Q_j \tilde{E}_{jk}\right)^2} + \frac{\left(\ousum{\NGr}{m}v_m^\alpha Q_m\right) \left(\ousum{\NGr}{m}v_m^\beta Q_m\right)}{\left(\ousum{\NC}{l}n_l\ousum{\NGr}{m}v_m^lQ_m\right)^2}.
  \label{eq:ddLambdadnadnb}
\end{equation}
We immediately see that \ref{eq:ddLambdadnadnb} give a symmetric matrix of the second differentials.

Differentiating \ref{eq:Ae} \wrpt $T$ we get,
\begin{align}
  \pd{\left(\frac{A^\res}{RT}\right)}{T} &= - \ousum{\NC}{i} n_i \ousum{\NGr}{k}  v_k^i Q_k\left(\pd{\Lambda_k}{T} - \pd{\Lambda_k^i}{T}\right), \label{eq:dAedT} \\
  \pdn{2}{\left(\frac{A^\res}{RT}\right)}{T} &= - \ousum{\NC}{i} n_i \ousum{\NGr}{k}  v_k^i Q_k\left(\pdn{2}{\Lambda_k}{T} - \pdn{2}{\Lambda_k^i}{T}\right). \label{eq:d2AedT2}
\end{align}
Here,
\begin{align}
  \pd{\Lambda_k}{T} &= \frac{\ousum{\NC}{l}n_l \ousum{\NGr}{j} v_j^l Q_j \pd{\tilde{E}_{jk}}{T}}{\ousum{\NC}{l}n_l \ousum{\NGr}{j} v_j^l Q_j \tilde{E}_{jk}},\label{eq:dLkdT} \\
  \pd{\Lambda_k^i}{T} &= \frac{\ousum{\NGr}{j} Q_j v_j^i \pd{\tilde{E}_{jk}}{T}}{\ousum{\NGr}{j} Q_j v_j^i \tilde{E}_{jk}},\label{eq:dLikdT} \\
  \pdn{2}{\Lambda_k}{T} &= \frac{\ousum{\NC}{l}n_l \ousum{\NGr}{j} v_j^l Q_j \pdn{2}{\tilde{E}_{jk}}{T}}{\ousum{\NC}{l}n_l \ousum{\NGr}{j} v_j^l Q_j \tilde{E}_{jk}} - \left(\pd{\Lambda_k}{T}\right)^2,\label{eq:d2LkdT2} \\
  \pdn{2}{\Lambda_k^i}{T} &= \frac{\ousum{\NGr}{j} Q_j v_j^i \pdn{2}{\tilde{E}_{jk}}{T}}{\ousum{\NGr}{j} Q_j v_j^i \tilde{E}_{jk}} - \left(\pd{\Lambda_k^i}{T}\right)^2.\label{eq:d2LikdT2} \\
\end{align}

Differentiating Equation \ref{eq:dAedna} we get
\begin{equation}
  \pd{\left(\frac{A^\res_\alpha}{RT}\right)}{T} = - \ousum{\NGr}{k}  v_k^\alpha Q_k\left(\pd{\Lambda_k}{T} - \pd{\Lambda_k^\alpha}{T}\right) -  \ousum{\NGr}{k} \left(\ousum{\NC}{i} n_i v_k^i\right) Q_k \ptwo{\Lambda_k}{n_\alpha}{T}. \label{eq:d2AednadT}
\end{equation}
The cross differential of $\Lambda_k$ is found by differentiating Equation \ref{eq:dLambdadna} \wrpt $T$,
\begin{equation}
  \ptwo{\Lambda_k}{n_\alpha}{T} = \frac{\ousum{\NGr}{j} v_j^\alpha Q_j \pd{\tilde{E}_{jk}}{T}}{\ousum{\NC}{l}n_l \ousum{\NGr}{j} v_j^l Q_j \tilde{E}_{jk}} - \frac{\left(\ousum{\NGr}{j} v_j^\alpha Q_j \tilde{E}_{jk}\right) \left(\ousum{\NC}{l}n_l \ousum{\NGr}{j} v_j^l Q_j \pd{\tilde{E}_{jk}}{T}\right)}{\left(\ousum{\NC}{l}n_l \ousum{\NGr}{j} v_j^l Q_j \tilde{E}_{jk}\right)^2} .
  \label{eq:d2LambdadnadT}
\end{equation}
\subsection{The combinatorial term}
The combinatorial term is comprised of a Flory-Huggins (\FH) and a
Staverman-Guggenheim (\SG) contribution,

\begin{align}
  G^{\excess,\comb} &= G^{\excess,\FH} + G^{\excess,\SG},\label{eq:comb}\\
  G^{\excess,\FH} &= \underset{i}{\sum} x_i \ln \frac{\phi_i}{x_i}, \label{eq:fh}\\
  G^{\excess,\SG} &= \frac{z}{2} \underset{i}{\sum} x_i q_i \ln \frac{\theta_i}{\phi_i}\label{eq:sg}.
\end{align}
Where $z=10$,
\begin{align}
  \phi_i &= \frac{x_i r_i}{\underset{j}{\sum} x_j r_j},\label{eq:phii}\\
  \theta_i &= \frac{x_i q_i}{\underset{j}{\sum} x_j q_j}.\label{eq:thetai}\\
\end{align}
$r_i$ and $q_i$ are molecule paramaters and non of the parameters are temperature dependent. $r_i$ is the molecular van der Waals volume and $q_i$ is the molecular van der Waals surface area. They are calculated from the group paramaters as follows,
\begin{align}
  r_i &= \ousum{\NGr}{k}v_k^i R_k,\label{eq:ri}\\
  q_i &= \ousum{\NGr}{k}v_k^i Q_k.\label{eq:qi}\\
\end{align}

\subsubsection{Differentials of the Flory-Huggins combinatorial term}
Writing Equation \ref{eq:fh} as a function of mole numbers, we get,
\begin{align}
  G^{\excess,\FH} &= \ousum{\NC}{i} n_i \left(\ln \phi_i - \ln n_i + \ln \ousum{\NC}{j}n_j\right), \\
  &= \ousum{\NC}{i} n_i \left(\ln n_i r_i - \ln \ousum{\NC}{j} n_j r_j - \ln n_i + \ln \ousum{\NC}{j}n_j\right) = \ousum{\NC}{i} n_i \ln r_i -n\ln \ousum{\NC}{j}n_jr_j  + n\ln n. \label{eq:fhn}
\end{align}
Differentiating $G^{\excess,\FH}$ \wrpt $n_\alpha$ we get,
\begin{align}
  G^{\excess,\FH}_\alpha &= \ln r_\alpha -\ln \ousum{\NC}{j}n_jr_j  + \ln \ousum{\NC}{j}n_j + 1-\frac{r_\alpha\ousum{\NC}{i} n_i}{\ousum{\NC}{j}n_jr_j},\\
  &= \ln r_\alpha -\ln \ousum{\NC}{j}n_jr_j  + \ln n + 1-\frac{n r_\alpha}{\ousum{\NC}{j}n_jr_j}, \label{eq:dfhndna}\\
  &= \ln \left(\frac{n r_\alpha}{\ousum{\NC}{j}n_jr_j}\right) + 1-\frac{n r_\alpha}{\ousum{\NC}{j}n_jr_j}\\
  &= \ln \left(\frac{\phi_\alpha}{x_\alpha}\right) + 1-\frac{\phi_\alpha}{x_\alpha}
\end{align}
Differentiating \ref{eq:dfhndna} \wrpt $n_\beta$ we get,
\begin{align}
  G^{\excess,\FH}_{\alpha\beta} &= -\frac{r_\alpha + r_\beta}{\ousum{\NC}{j}n_jr_j}  + \frac{1}{n} + \frac{n r_\alpha r_\beta}{\left(\ousum{\NC}{j}n_jr_j\right)^2}. \label{eq:d2fhndnadnb}
\end{align}
\subsubsection{Differentials of the Staverman-Guggenheim combinatorial term}
Writing Equation \ref{eq:sg} as a function of mole numbers, we get,
\begin{align}
  G^{\excess,\SG} &= \frac{z}{2} \ousum{\NC}{i} n_i q_i \left(\ln \theta_i - \ln \phi_i\right),\\
  &= \frac{z}{2} \ousum{\NC}{i} n_i q_i \left(\ln \frac{q_i}{r_i} - \ln \ousum{\NC}{j} n_j q_j + \ln \ousum{\NC}{j} n_j r_j \right)\label{eq:sgn}.
\end{align}
Differentiating $G^{\excess,\SG}$ \wrpt $n_\alpha$ we get,
\begin{align}
  G^{\excess,\SG}_\alpha &= \frac{z}{2} q_\alpha \left( \ln \frac{q_\alpha}{r_\alpha} - \ln \ousum{\NC}{j} n_j q_j + \ln \ousum{\NC}{j} n_j r_j - 1 + \frac{r_\alpha \ousum{\NC}{i} n_i q_i}{q_\alpha\ousum{\NC}{j} n_j r_j}\right), \label{eq:dsgnda}\\
  &= \frac{z}{2} q_\alpha \left( - \ln \left(\frac{r_\alpha \ousum{\NC}{j} n_j q_j}{q_\alpha \ousum{\NC}{j} n_j r_j}\right) - 1 + \frac{r_\alpha \ousum{\NC}{i} n_i q_i}{q_\alpha\ousum{\NC}{j} n_j r_j}\right),\\
  &= \frac{z}{2} q_\alpha \left( \ln \left(\frac{\theta_\alpha}{\phi_\alpha}\right) - 1 + \frac{\phi_\alpha}{\theta_\alpha}\right).
\end{align}
Differentiating \ref{eq:dsgnda} \wrpt $n_\beta$ we get,
\begin{align}
  G^{\excess,\SG}_{\alpha\beta} &= \frac{z}{2} \left( - \frac{q_\alpha q_\beta}{\ousum{\NC}{j} n_j q_j} + \frac{q_\alpha r_\beta + q_\beta r_\alpha}{\ousum{\NC}{j} n_j r_j} - \frac{r_\alpha r_\beta \ousum{\NC}{i} n_i q_i}{\left(\ousum{\NC}{j} n_j r_j\right)^2}\right). \label{eq:dssgndadb}
\end{align}
\subsubsection{Comparing to combinatorial activity coefficient of Fredenslund et al.}
Fredenslund et al. \cite{Fredenslund1975} uses the following expression for the activity combinatorial coefficient,
\begin{align}
  \ln \gamma_{\text{c}} &= \ln \frac{\phi_i}{x_i} + \frac{z}{2} q_i \ln \frac{\theta_i}{\phi_i} + l_i - \frac{\phi_i}{x_i}\ousum{\NC}{j} x_j l_j , \label{eq:gamma_c} \\
  l_i &= \frac{z}{2} \left(r_i - q_i\right) - \left(r_i - 1\right) . \label{eq:li}
\end{align}
Inserting for $l_i$ in the last term of Equation \ref{eq:gamma_c}, we get,
\begin{align}
  \frac{\phi_i}{x_i}\ousum{\NC}{j} x_j l_j &= \frac{z\phi_i}{2x_i}\left(\ousum{\NC}{j} x_j r_j - \ousum{\NC}{j}x_jq_j\right) - \frac{\phi_i}{x_i}\left(\ousum{\NC}{j} x_j r_j - 1\right), \\
  &= \frac{z}{2}\left(r_i - \frac{q_i\phi_i}{\theta_i}\right) - r_i + \frac{\phi_i}{x_i}. \label{eq:second_term}
\end{align}
Inserting Equation \ref{eq:second_term} and Equation \ref{eq:li} into Equation \ref{eq:gamma_c} we get,
\begin{align}
  \ln \gamma_{\text{c}} &= \ln \frac{\phi_i}{x_i} + 1 - \frac{\phi_i}{x_i} + \frac{z}{2} q_i \left(\ln \frac{\theta_i}{\phi_i} -1 + \frac{\phi_i}{\theta_i}\right).
\end{align}
We see that
\begin{equation}
  \ln \gamma_{\text{c}} = G^{\excess,\FH}_\alpha + G^{\excess,\SG}_\alpha.
\end{equation}
\section{UMR-PR model}
The UMR-PR model is developed by Voutsas et al \cite{Voutsas2004}, and
uses the UNIFAC mixing rules together with a volume translated
Peng-Robinson EOS, t-mPR \cite{Avlonitis1994}.

UMR-PR applies the following covolume mixing rule,
\begin{align}
  b &= \underset{i}{\sum} \underset{j}{\sum} x_i x_j b_{ij},\\
  b_{ij} &= \left[\frac{b_i^{\frac{1}{s}} + b_j^{\frac{1}{s}}}{2}\right]^s,
  \label{eq:bij}
\end{align}
with $s=2$.

UMR-PR ignores the Flory-Huggins contribution, Equation \ref{eq:fh},
of the combinatorial term, Equation \ref{eq:comb}.

UMR-PR uses the original temperature independent UNIFAC parameters published by Hansen et al \cite{Hansen1991} and Dortmund Data Bank, Wittig et al \cite{Wittig2003}.

Data source:
\url{https://en.wikipedia.org/wiki/UNIFAC}

\url{http://www.ddbst.com/unifacga.html}

\url{http://www.aim.env.uea.ac.uk/aim/info/UNIFACgroups.html}

The volume correction temperature differentials used in UMR is not
continous. This might be a good reason not to use the model.

\subsection{t-mPR model}
t-mPR \cite{Avlonitis1994} is an extension of the t-PR
\cite{Magoulas1990} to mixtures.

The t-mPR model take the following form,
\begin{equation}
  \label{eq:t-mPR}
  P = \frac{RT}{V+t-b} - \frac{a}{(V+t)(V+t+b) + b(V+t-b)},
\end{equation}
where,
\begin{equation}
  \label{eq:tmix}
  t = t(\vektor{x},T) = \underset{i}{\sum} x_i t_i(T).
\end{equation}
We see that by introducing $\tilde{V} = V + t$, the relations for this
equation of state can be related to the standard Peng-Robinson
equation of state. The translation is slightly more complicated than
the P{\'e}neloux \cite{Peneloux1982} volume shift, due to the
temperature dependency, and the lack of correction to the covolume.

\section{PSRK model}
PSRK \cite{Holderbaum1991} uses SRK with Mathias-Copeman
$\alpha$-correlation \cite{Mathias1983}, and a UNIFAC excess Gibbs
energy model.

The zero pressure limit, Equation \ref{eq:zero_limit},
is used when including the mixing rules into the SRK EOS.
$h_{\text{PSRK}}(\beta_0) = 0.64663$ is used.

The zero pressure limit is used when including the excess Gibbs energy into the equation of state,
\begin{equation}
  \label{eq:zero_limit}
  \frac{a}{RTb} = \underset{i}{\sum} x_i \frac{a_i}{RTb_i} - \frac{1}{h(\beta_0)}\left(\underset{i}{\sum} x_i \ln \frac{b}{b_i} + \frac{G^\excess}{RT} \right),
\end{equation}
where $h(\beta_0)$ is a constant that depend on the EOS. We have $h_{\text{PR}}(\beta_0) = 0.53$.

The linear mixing of the covolume is used in PSRK,
\begin{equation}
  \label{eq:linbmix}
  b  = \underset{i}{\sum} x_i b_i.
\end{equation}

\textcolor{red}{Parameters: \cite{Horstmann2005,Holderbaum1991,Horstmann2000,Fischer1996,Gmehling1997}}

\section{VTPR model}
The Volume-Translated-Peng-Robinson (VTPR) EOS \cite{Collinet2006}, uses a constant volume correction for each component. The correction in volume therefore don't depend on temperature. The Twu, Bluck, Cunningham and Coon $\alpha$-correlation \cite{Twu1991} is used.

For the excess Gibbs energy, the UNIFAC model is used without the combinatorial term, Equation \ref{eq:comb}. The infinite pressure limit is used when including the activity coefficient model into the EOS.

Covolume mixing uses Equation \ref{eq:bij} with $s=4/3$.

\textcolor{red}{Parameters: \cite{Schmid2014}}

\section{The general mixing rule for the covolume}
The general mixing rules for the covolume take the following form,
\begin{align}
  nB = n^2 b &= \underset{i}{\sum} \underset{j}{\sum} n_i n_j b_{ij}, \label{eq:B}\\
  b_{ij}^{\frac{1}{s}} &= (1 - l_{ij}) \frac{b_i^{\frac{1}{s}} + b_j^{\frac{1}{s}}}{2}.
  \label{eq:bij_mod}
\end{align}
Where $l_{ij}$ is assumed constant, symmetric, and have a default value of zero.

Differentiating and manipulating Equation \ref{eq:B}, $B_{i}$ and
$B_{ij}$ become,
\begin{align}
  n B_i = &= 2\underset{j}{\sum} n_j b_{ij} -B, \label{eq:Bi}\\
  n B_{ij} = &= 2b_{ij} - B_i - B_j.
  \label{eq:Bij}
\end{align}
\clearpage
\bibliographystyle{plain}
\bibliography{../thermopack}

\end{document}


\chapter{Comparison with othert ISAs}

\hrulefill

\textbf{IMPORTANT NOTE:} Some of the discussions below refer to an older draft of the
RISC-V Bitmanip extension and are now out-of-date.

\hrulefill

\section{Comparison with x86 Bit Manipulation ISAs}
\label{x86comp}

The following code snippets implement all instructions from the x86 bit manipulation
ISA extensions ABM, BMI1, BMI2, and TBM using RISC-V code that does not spill any
registers and thus could easily be implemented in a single instruction using macro-op
fusion. (Some of them simply map directly to instructions in this spec and so no
macro-op fusion is needed.) Note that shorter RISC-V code sequences are
sometimes possible if we allow spilling to temporary registers.

ABM added x86 encodings for POPCNT, LZCNT, and TZCNT.\footnote{Depending on if
you ask Intel or AMD you will get different opinion regarding whether LZCNT
and/or TZCNT are part of ABM or BMI1.} The difference between LZCNT and the
80386 instruction BSR, and between TZCNT and the 80386 instruction BSF, is that
the new instructions return the operand size when the input operand is zero,
while BSR and BSF were undefined in that case. The ABM instructions map 1:1 to
Bitmanip instructions. Table~\ref{abm-comp} lists ABM instructions and regular
x86 bit manipulation instructions.

\begin{table}[h]
\centering
\begin{tabular}{lrrl}
\multirow{2}{*}{x86 Instruction} & \multicolumn{2}{c}{Bytes} & \multirow{2}{*}{RISC-V Code} \\
& x86 & RV & \\
\hline
POPCNT       &   5 &  4 & {\tt cpop a0, a0} \\
\hline
LZCNT / BSR  &   5 &  4 & {\tt clz a0, a0} \\
\hline
TZCNT / BSF  &   5 &  4 & {\tt ctz a0, a0} \\
\hline
BSWAP        &   3 &  4 & {\tt bswap} \\
\hline
ROL          &   4 &  4 & {\tt roli} \\
\hline
ROR          &   4 &  4 & {\tt rori} \\
\hline
BT           &   5 &  4 & {\tt c.srl a0, N} \\
             &     &    & {\tt c.andi a0, 1} \\
\hline
BTC          &   5 & 16 & {\tt rori a0, N} \\
             &     &    & {\tt andi a1, a0, 1} \\
             &     &    & {\tt xori a0, a0, 1} \\
             &     &    & {\tt rori a0, XLEN-N} \\
\hline
BTR          &   5 & 16 & {\tt rori a0, N} \\
             &     &    & {\tt andi a1, a0, 1} \\
             &     &    & {\tt andi a0, a0, -2} \\
             &     &    & {\tt rori a0, XLEN-N} \\
\hline
BTS          &   5 & 16 & {\tt rori a0, N} \\
             &     &    & {\tt andi a1, a0, 1} \\
             &     &    & {\tt ori a0, a0, 1} \\
             &     &    & {\tt rori a0, XLEN-N} \\
\end{tabular}
\caption{Comparison of x86+ABM with Bitmanip}
\label{abm-comp}
\end{table}

BMI1 adds some instructions for trailing bit manipulations, an add-complement instruction,
and a bit field extract instruction that expects the length and start position packed in one
register operand. Our version expects the length in a0, start position in a1, and source
value in a2. See Table~\ref{bmi1-comp}.

\begin{table}[h]
\centering
\begin{tabular}{lrrl}
\multirow{2}{*}{x86 Instruction} & \multicolumn{2}{c}{Bytes} & \multirow{2}{*}{RISC-V Code} \\
& x86 & RV & \\
\hline
ANDN    & 5 &  4 & {\tt andn a0, a2, a1} \\
\hline
BEXTR (regs)  & 5 & 12 & {\tt c.add a0, a1} \\
              &   &    & {\tt slo a0, zero, a0} \\
              &   &    & {\tt c.and a0, a2} \\
              &   &    & {\tt srl a0, a0, a1} \\
\hline
BLSI          & 5 &  6 & {\tt neg a0, a1} \\
              &   &    & {\tt c.and a0, a1} \\
\hline
BLSMSK        & 5 &  6 & {\tt addi a0, a1, -1} \\
              &   &    & {\tt c.xor a0, a1} \\
\hline
BLSR          & 5 &  6 & {\tt addi a0, a1, -1} \\
              &   &    & {\tt c.and a0, a1} \\
\end{tabular}
\caption{Comparison of x86 BMI1 with Bitmanip}
\label{bmi1-comp}
\end{table}

BMI2 adds a few \texttt{*X} instructions that just perform the indicated
operation without changing any flags. RISC-V does not use flags, so this
instructions trivially just map to their regular RISC-V counterparts. In
addition to those instructions, BMI2 adds bit extract and deposit instructions
and an instruction to clear high bits above a given bit index. See Table~\ref{bmi2-comp}.

\begin{table}[h]
\centering
\begin{tabular}{lrrl}
\multirow{2}{*}{x86 Instruction} & \multicolumn{2}{c}{Bytes} & \multirow{2}{*}{RISC-V Code} \\
& x86 & RV & \\
\hline
BZHI     & 5 &  6 & {\tt slo a0, zero, a2} \\
         &   &    & {\tt c.and a0, a1} \\
\hline
PDEP     & 5 &  4 & {\tt bdep} \\
\hline
PEXT     & 5 &  4 & {\tt bext} \\
\hline
MULX     & 5 &  4 & {\tt mul} \\
\hline
RORX     & 6 &  4 & {\tt rori} \\
\hline
SARX     & 5 &  4 & {\tt sra} \\
\hline
SHRX     & 5 &  4 & {\tt srl} \\
\hline
SHLX     & 5 &  4 & {\tt sll} \\
\end{tabular}
\caption{Comparison of x86 BMI2 with Bitmanip}
\label{bmi2-comp}
\end{table}

Finally, TBM was a short-lived x86 ISA extension introduced by AMD in
Piledriver processors, complementing the trailing bit manipulation instructions
from BMI1. See Table~\ref{tbm-comp}.

\begin{table}[h]
\centering
\begin{tabular}{lrrl}
\multirow{2}{*}{x86 Instruction} & \multicolumn{2}{c}{Bytes} & \multirow{2}{*}{RISC-V Code} \\
& x86 & RV & \\
\hline
BEXTR (imm)  & 7 &  4 & {\tt c.slli a0, (32-START-LEN)} \\
             &   &    & {\tt c.srli a0, (32-LEN)} \\
\hline
BLCFILL      & 5 &  6 & {\tt addi a0, a1, 1} \\
             &   &    & {\tt c.and a0, a1} \\
\hline
BLCI         & 5 &  8 & {\tt addi a0, a1, 1} \\
             &   &    & {\tt c.not a0} \\
             &   &    & {\tt c.or a0, a1} \\
\hline
BLCIC        & 5 & 10 & {\tt addi a0, a1, 1} \\
             &   &    & {\tt andn a0, a1, a0} \\
             &   &    & {\tt c.not a0} \\
\hline
BLCMSK       & 5 &  6 & {\tt addi a0, a1, 1} \\
             &   &    & {\tt c.xor a0, a1} \\
\hline
BLCS         & 5 &  6 & {\tt addi a0, a1, 1} \\
             &   &    & {\tt c.or a0, a1} \\
\hline
BLSFILL      & 5 &  6 & {\tt addi a0, a1, -1} \\
             &   &    & {\tt c.or a0, a1} \\
\hline
BLSIC        & 5 & 10 & {\tt addi a0, a1, -1} \\
             &   &    & {\tt andn a0, a1, a0} \\
             &   &    & {\tt c.not a0} \\
\hline
T1MSKC       & 5 & 10 & {\tt addi a0, a1, +1} \\
             &   &    & {\tt andn a0, a1, a0} \\
             &   &    & {\tt c.not a0} \\
\hline
T1MSK        & 5 &  8 & {\tt addi a0, a1, -1} \\
             &   &    & {\tt andn a0, a0, a1} \\
\end{tabular}
\caption{Comparison of x86 TBM with Bitmanip}
\label{tbm-comp}
\end{table}

\section{Comparison with RI5CY Bit Manipulation ISA}

The following section compares Bitmanip with the RI5CY bit manipulation
instructions as documented in~\cite{Ri5cy}. All RI5CY bit manipulation
instructions (or something very close to their behavior) can be emulated with
Bitmanip using 3 instructions or less.

\subsubsection{RI5CY Instructions {\tt p.extract}, {\tt p.extractu}, {\tt p.extractr}, and {\tt p.extractur}}

These four RI5CY instructions extract bit-fields. The non-{\tt u}-versions sign-extend
the extracted bit-field. This operations can be performed with two shift-immediate
operations. It even fits in a 32-bit word when using compressed instructions (requires
{\tt rd} $=$ {\tt rs}).

\begin{verbatim}
  p.extract rd, rs, len, pos:
    slli rd, rs, (XLEN-pos-len)
    srai rd, rd, (XLEN-len)

  p.extractu rd, rs, len, pos:
    slli rd, rs, (XLEN-pos-len)
    srli rd, rd, (XLEN-len)
\end{verbatim}

The {\tt r}-versions expect the bit-field size in bits 9:5 of the second source
register and the bit-field start in bits 4:0. Instead we use two registers,
$\texttt{rx} = XLEN-pos-len$ and $\texttt{ry} = XLEN-len$.

\begin{verbatim}
  p.extractr:
    sll rd, rs, rx
    sra rd, rd, ry

  p.extractur:
    sll rd, rs, rx
    srl rd, rd, ry
\end{verbatim}

Alternatively, instead of packing length and position into a register, we
can create a mask in a register and then use this mask with {\tt bext}. This
has the advantage over the {\tt sll}+{\tt srl} sequence that the mask only needs
to be generated once and can then be re-used many times, effectively implementing
{\tt p.extractur} in a single instruction.

\begin{verbatim}
  p.extractur:
    slo rMask, zero, rLen
    sll rMask, rMask, rPos
    bext rd, rs, rMask
\end{verbatim}

{\tt p.extractu} can be efficiently emulated with a single XBitfield {\tt bfxp}
instruction (see Chapter~\ref{bfxp}):

\begin{verbatim}
  p.extract rd, rs, len, pos:
    bfxp rd, rs, zero, pos, len, 0
\end{verbatim}

\subsubsection{RI5CY Instructions {\tt p.insert} and {\tt p.insertr}}

These instructions OR the destination register with the {\tt len} LSB bits
from the source register, shifted up by {\tt pos} bits. This can easily
be achieved using three instructions and a temporary register {\tt rt}:

\begin{verbatim}
  p.insert rd, rs, len, pos, rt:
    slli rt, rs, (XLEN-len)
    srli rt, rt, (XLEN-len-pos)
    or rd, rd, rt
\end{verbatim}

The {\tt r}-version of the instruction expects {\tt len} in bits 9:5 of the
second source register and {\tt pos} in bits 4:0. Instead we use two registers,
$\texttt{rx} = XLEN-pos-len$ and $\texttt{ry} = XLEN-len$.

\begin{verbatim}
  p.insertr:
    slli rt, rs, ry
    srli rt, rt, rx
    or rd, rd, rt
\end{verbatim}

Alternatively, instead of packing length and position into a register, we
can create a mask in a register and then use this mask with {\tt bdep}. This
has the advantage over the {\tt sll}+{\tt srl} sequence that the mask only needs
to be generated once and can then be re-used many times.

\begin{verbatim}
  p.extractur:
    slo rMask, zero, rLen
    sll rMask, rMask, rPos
    bdep rt, rs, rMask
    or rd, rd, rt
\end{verbatim}

{\tt p.insert} can be efficiently emulated with a single XBitfield {\tt bfxp}
instruction (see Chapter~\ref{bfxp}), if target region in {\tt rd} contains
only zeros ({\tt bfxp} clears the target region before performing the OR):

\begin{verbatim}
  p.insert rd, rs, len, pos:
    bfxp rd, rs, rd, 0, len, pos
\end{verbatim}

\subsubsection{RI5CY Instructions {\tt p.bclr} and {\tt p.bclrr}}

These instructions clear {\tt len} bits starting with bit {\tt pos}. Using a
temporary register {\tt rt}:

\begin{verbatim}
  p.bclr rd, rs, len, pos, rt:
    sloi rt, zero, len
    slli rt, rt, pos
    andn rd, rs, rt
\end{verbatim}

Or using two registers {\tt rLen} and {\tt rPos}:

\begin{verbatim}
  p.bclrr rd, rs, rLen, rPos, rt:
    slo rt, zero, rLen
    sll rt, rt, rPos
    andn rd, rs, rt
\end{verbatim}

If the mask in {\tt rt} can be pre-computed then a single {\tt andn} instruction
can emulate {\tt p.bclrr}, or a single {\tt and}/{\tt c.and} instruction if the
mask is already inverted.

Or using {\tt bfxp} with $\texttt{rd} = \texttt{rs}$ (see Chapter~\ref{bfxp}):

\begin{verbatim}
  p.bclr rd, len, pos:
    bfxp rd, zero, rd, 0, len, pos
\end{verbatim}

\subsubsection{RI5CY Instructions {\tt p.bset} and {\tt p.bsetr}}

These instructions set {\tt len} bits starting with bit {\tt pos}. They can be
implemented similar to {\tt p.bclr} and {\tt p.bclrr} by replacing {\tt andn}
with {\tt or}:

\begin{verbatim}
  p.bset rd, rs, len, pos, rt:
    sloi rt, zero, len
    slli rt, rt, pos
    or rd, rs, rt

  p.bsetr rd, rs, rLen, rPos, rt:
    slo rt, zero, rLen
    sll rt, rt, rPos
    or rd, rs, rt
\end{verbatim}

If the mask in {\tt rt} can be pre-computed then a single {\tt or}/{\tt c.or} instruction
can emulate {\tt p.bsetr}.

Or using {\tt bfxpc} with $\texttt{rd} = \texttt{rs}$ (see Chapter~\ref{bfxp}):

\begin{verbatim}
  p.bset rd, len, pos:
    bfxpc rd, zero, rd, 0, len, pos
\end{verbatim}

\subsubsection{RI5CY Instructions {\tt p.ff1}, {\tt p.cnt}, and {\tt p.ror}}

These instructions map directly to the Bitmanip instructions {\tt ctz}, {\tt cpop}, and {\tt ror}.

\subsubsection{RI5CY Instructions {\tt p.fl1}}

This instruction returns the index of the last set bit in {\tt rs}. If {\tt rs} is 0, {\tt rd} will be 0.

Using the arguably more useful definition that the operation should return -1 when {\tt rs} is 0:

\begin{verbatim}
  p.fl1 rd, rs:
    clz rd, rs
    neg rd, rd
    addi rd, rd, 31
\end{verbatim}

Converting a -1 result to 0 to match the exact {\tt p.fl1} behavior:

\begin{verbatim}
    slt rt, rd, zero
    add rd, rd, rt
\end{verbatim}

\subsubsection{RI5CY Instructions {\tt p.clb}}

This instruction counts the number of consecutive 1s or 0s from MSB. If {\tt rs} is 0, {\tt rd} will be 0.

Using the arguably more useful definition that the operation should return XLEN when {\tt rs} is 0 or -1,
and assuming {\tt rd} $\ne$ {\tt rs1}:

\begin{verbatim}
  p.clb:
    srai rd, rs, XLEN-1
    xor rd, rd, rs
    clz rd, rd
\end{verbatim}

Simply add {\tt andi rd, rd, XLEN-1} if {\tt rd} should be 0 when {\tt rs} is 0 or -1.

\section{Comparison with Cray XMT bit operations}

Cray XMT is the 3rd generation of the Cray MTA architecture, a supercomputer
using a barrel processor architecture. The Cray XMT instruction set contains
a few bit manipulation instructions~\cite{CrayXMT}. In this section we compare
the Cray XMT bit manipulation instructions with Bitmanip.

\subsubsection{Bitwise boolean operations}

Cray XMT provides the following instructions for bitwise boolean operations:
{\tt BIT\_AND}, {\tt BIT\_IMP}, {\tt BIT\_NAND}, {\tt BIT\_NIMP}, {\tt
BIT\_NOR}, {\tt BIT\_OR}, {\tt BIT\_XNOR}, and {\tt BIT\_XOR}.

These can trivially emulated using basic RISC-V instructions. (Some of those
XMT instructions have a direct RISC-V equivalent. The others can be emulated
by combining the {\tt not} pseudoinstruction with {\tt and}, {\tt or}, or {\tt xor}.)

\subsubsection{Count Leading/Trailing Zeros/Ones}

The Cray XMT instructions {\tt BIT\_LEFT\_ZEORS} and {\tt BIT\_RIGHT\_ZEORS} are
equivalent to the Bitmanip {\tt clz} and {\tt ctz} instructions.

The {\tt BIT\_LEFT\_ONES} and {\tt BIT\_RIGHT\_ONES} instructions can be emulated
by combining the {\tt not} pseudoinstruction with {\tt clz} and {\tt ctz}.

\subsubsection{Mask generation}

The Cray XMT instruction {\tt BIT\_MASK dest top bot} generates a bitmask
that has the bits in the range $[\texttt{bot} \dots \texttt{top}]$ set
and the rest cleared iff $\texttt{bot} \le \texttt{top}$, and those
bits cleared and the rest set otherwise.

Similar masks can be generated using two instructions in Bitmanip,
using the regular shift instructions and the ``shift ones'' instructions.

\subsubsection{Cmix equivalent}

The Cray XMT {\tt BIT\_MERGE} instruction is equivalent to the XTernarybits
{\tt cmix} instruction, or the {\tt and-andn-or} MIX pattern.

\subsubsection{Population count}

The Cray XMT {\tt BIT\_TALLY} instruction and the Bitmanip {\tt cpop}
instruction are equivalent.

\subsubsection{Parity instructions}

The Cray XMT {\tt BIT\_ODD\_AND}, {\tt BIT\_ODD\_NIMP}, {\tt BIT\_ODD\_OR},
and {\tt BIT\_ODD\_XOR} instruction perform the indicated bitwise boolean
operation and then compute the parity of the result.

With Bitmanip the parity can be calculated with {\tt cpop dst, src} followed
by {\tt andi dst, dst, 1}.

\subsubsection{Bit pack/unpack instruction}

The Cray XMT {\tt BIT\_PACK} instruction and the Bitmanip {\tt bext}
instruction are equivalent.

The Cray XMT {\tt BIT\_UNPACK\_1}, {\tt BIT\_UNPACK\_2}, {\tt BIT\_UNPACK\_3},
instruction sequence, when used as intended, is equivalent to the Bitmanip
{\tt bdep} instruction.

\subsubsection{Bit matrix instructions}

The Cray XMT {\tt BIT\_MAT\_} instructions treat a 64-bit value as a 8x8 bit
matrix.

{\tt BIT\_MAT\_TRANSPOSE} is used to transpose such a bit matrix. With
Bitmanip instructions on RV64 this bit permutation can be performed by
applying the {\tt zip} operation three times to the register holding the
matrix (see also~\ref{transposebitboard}).

The Cray XMT instructions {\tt BIT\_MAT\_OR} and {\tt BIT\_MAT\_XOR} perform a
matrix-matrix multiply between such bit matrices, where AND replaces scalar
multiply and OR/XOR replaces scalar addition.

Bitmanip does not provide a similar operation. However, the two example
applications given in the Cray XMT documentation~\cite[p.~81]{CrayXMT}
are reversing the byte order in a word and reversing the bit order in
each byte. In Bitmanip those operations are performed by the {\tt bswap}
and the {\tt brev.b} {\tt grevi}-pseudoinstructions.