\documentclass[12pt]{article}
\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage{amsthm}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{graphicx}
\usepackage{verbatim}

\renewcommand{\v}[1]{\texttt{#1}}

\author{ProgrammingAnimations}
\title{DFS Script}
\date{}

\begin{document}
\maketitle

%\section{Video 0. Introduction to graphs}
%\subsection{Walktrough of the series}
%\subsection{Graphs}
%\subsubsection{Definition}
%\subsubsection{Examples/Types of graphs}
%\subsection{Transversals}

\section{Video 1. DFS}

ADD SMALL PREVIEW OF THE ALGORITHM

\subsection{Intro/Motivation}

I'm sure you've been in this situation at some point.
You wake up a bit disoriented and you find yourself trapped
inside of a maze.

Obviously you don't remember anything about what happened
last night and you don't have your phone with you.

And to make matters worse
you REALLY need to go to the toilet. Like NOW.

Basically, you pretty much want to
escape from the maze as quickly as possible.

So, since you don't know exactly where you are,
and you don't know how the maze looks like,
you want to explore it in such a way, that you make sure
that you can visit every single part of the maze that you
can go to, since this way you will find an exit for sure,
but without making any redundant work.

So, is there a way, or more precisely, is there an algorithm
that allows you to move through the maze in such a way?
And how would you program a computer to do so?
Let me introduce you to the Depth-First Search algorithm.

\subsection{Main idea}

Let's try to model the maze in some meaningful way.
We will describe the maze as a rectangular grid.
Dark green squares will represent bushes,
or in other words, the forbidden positions of the maze.
Here, by `forbidden' we just mean that we cannot move across
such squares.

The rest of the squares will represent
the part of the maze along which we can move.
We will also represent in blue our starting
position, and in yellow the exit.

So here's what we want. We want an algorithm that makes
sure that we visit every square reachable from our initial position,
and that at the same time
avoids revisiting squares that we have already visited.

Bearing this in mind, we are ready to see the main idea of this algorithm.

But before, take in account that when we say that two squares are adjacent,
we mean that they completely share a side.

For example, for this particular square, these are
its adjacent squares.
And these are its reachable adjacent squares.

Now, here's the main idea. If we can make sure
that for every square of the maze
that we explore, we will also explore all its
reachable adjacent squares at some point,
this means that just by starting in some initial position,
that will ensure that we will eventually explore all the squares
in the maze reachable from that initial position.

So, let's see why this idea works.
Let's say that we start exploring at this particular square.
Then, the algorithm will ensure that we also explore its adjacent
squares. Then, the squares adjacent to those, and so on.

Note that the squares that we didn't mark here are not reachable,
since we said that to be adjacent, squares must completely share
a side, and as you see, none of the unmarked squares
completely share a side with
any of the marked ones.

By the way, the set of squares we marked forms what is called
a connected component, that is, a maximal
set of squares such that you can go from any of these to any other.

'Maximal' here just means that we cannot find a larger set
of squares containing it that still satisfies this property.
As you can see, for example, this graph has two connected components.

As a final note on the idea, take in account that we
are not talking yet about the order in which the algorithm
will explore the squares.

The animation you just saw only shows
that our idea will ensure that we visit the entire
connected component.

Having said this, we are ready to see how
to code this algorithm.

\subsection{Code}

Just a small caveat first.
When we talk about matrices, which we use for instance to represent grids,
we identify each element, or in our case, each square,
with two indices.

The first one represents the row.
As this is the vertical component, we will denote it
with a \v{y}. The uppermost row will be row 0, the row below
will be row 1, and so on.

As you can see, contrary to what is
usual, increasing \v{y} will be the same as moving downwards.

Then, the second index, will represent the column, and we will
denote in with an \v{x}. In this case, the column on the left
will be column 0, the next one column 1, and so on.

This means that we will use \v{y}'s before \v{x}'s,
which is the opposite order as you may be used to, but hey,
there's a good reason for that.

Having said that, we are ready for the code!
For this video,
I will not assume you have any previous knowledge on programming,
so I will try my best to explain what is going on here.

If you know some programming, but you don't know C++,
which is the language I use here, don't worry,
you will find it easy to translate the code to your favourite
language.

Our code will start with function named \v{explore},
which will just try to explore a single square.

Therefore
the only parameter that this function needs is the position,
which we will pass that as two integers,
first the row \v{y}, and then the column \v{x}.

Remember that one of the things we wanted was to avoid revisiting
any previously explored square.
We can convert this idea into this single
line of code. Let's explain it.

First of all, what is this \verb|is_explorable| thing?
This will be a matrix with the same dimensions as the grid,
in which each element will represent the corresponding square
of the grid.

Each of these elements will be a boolean,
that is, a \v{true} or a \v{false}
value, to indicate if the square is explorable or not.

To be explorable, a square must satisfy two conditions.
First, it must not be an obstacle. Second, and this
is the most important condition,
to be explorable, the square can't have been previously
explored.

So, at the beginning, we will say that all forbidden squares,
the ones representing the bushes, are not explorable,
whereas all the other squares will be.

However, every time
we explore a square, we will immediately mark it as not explorable
so that we never explore it again.

Now, we will try to explore the adjacent squares.
Let's try to explore the one on the right.
We will do the following. If the square on the right is
explorable, explore it recursively. A couple simple lines, right?

If you don't know what
`recursively' means, don't worry and wait till you see the
algorithm in action.

Let's do the same for the other squares.
If the square right above
is explorable, explore it. The same for the
square on the left, and for the one right below.

As you can see, these lines follow an identical structure,
and so we can,
and a good programmer would say we must,
merge them inside of a \v{for} loop.

However, for some extra clarity
in case you don't know C++, I will write this loop this way.

This \v{for} loop means that we will repeat the last two
lines
of code 4 times, the first time the variable \v{i} will have
a value of 0, the second time it will have a value of 1,
the third time, a value of 2 and in the
fourth and last iteration it will have a value of 3.

In case you are not familiar with programming, bear in mind
that we always start counting from 0.\footnote{Might probably add
an evil MATLAB reference or joke.}

So, what will \v{dy} and \v{dx} mean here.
This will be two small arrays to indicate directions.

For example, when \v{i} is 0, substituting
the first values of \v{dy} and \v{dx} we will be exploring
the square with coordinates \v{(y + 0, x + 1)},
that is, we will be exploring the position at the right
of our square.

If you do the same for the other \v{i}'s, you will realize
that we will explore east, north, west, and south, in this order.

This naming of variables by the way, is quite typical
in this sort of context, and is obviously borrowed from math,
although of course they are not used to talk about differential
displacements, as it's usual in the field,
but about minimum displacements.

So here we are! This is a basic scheme of a depth-first
search algorithm. We will end by adding some comments
to the code to make things more understandable.

So let's recap what this code is doing. We first have this
little line that ensures that we don't do redundant work,
and then we have this \v{for} loop, that tries to explore
every explorable adjacent square. Just the two ingredients
we needed.

Just one extra thing we will need to note here.
As you can see, this code does nothing special
when it finds an exit, and does not check that
the square we want to explore is inside of the maze,
which can make the program crash.

We will solve this issue later on when we come across it.

And now, let's see the algorithm in action!

\subsection{Animation}

(initial square $(2, 4)$). We'll start in our initial square.
As we will do in every square we explore, we start marking the square as not
explorable. And now, let's start exploring around!

Remember, what our algorithm does is: `first, let's explore east'.
The square at the right is not explorable, since it's an obstacle.

Therefore, we try exploring north. Now, our square is explorable!
So, let's recursively explore there.

$(1, 4)$. We are now exploring this new square.
First, we will mark it as no longer explorable.

Now, we will be able to move recursively to the right,
and one more time. And remember, at each new exploration we
mark the corresponding square as not explorable.

$(1, 6)$. Now, look at what happens at this square. We start
trying to explore east and we fail since it's an obstacle.
We then try going north and same thing happens.

And now, here's
the interesting part. The square at the left is not an obstacle,
but in the previous step we marked it as unexplorable. So,
we can't go there, and we can only advance south.

Let's fast-forward a little bit.

$(4, 6)$. In this new square, we see that we
can take two paths. But remember the order we follow.

The square east is already explored, the square north is an
obstacle, and the square west is explorable, so we will
first go there.

$(4, 4)$. Now, we get to this square. Our algorithm will tell
us to continue exploring north.

$(3, 4)$. But look at what we have now here. Each adjacent
square is not explorable, either because is an obstacle or
has already been explored. This means we cannot move anywhere.

In this case, the function will just end, and we'll resume
the function from the previous step.

Note that we have not completed exploring any of the squares
that still have arrows.

The exploration process on each of those squares is
frozen until we finish exploring the squares that we started
exploring later in time.

$(4, 4)$. So, we are again in this square. We had already tried
exploring right and up, so we try left, we fail, and then move
down.

$(5, 2)$. Now, at this point, we have another intersection,
and we start moving north.

$(1, 3)$. We come across a dead end, and just as before, the algorithm
will stop exploring the squares and stepping back.
Remember, we can't move diagonally!

$(5, 2)$. And now, we will move straight to the exit!

(exit $(7, 0)$).

As we said, the code we have is not meant to do anything special
when we find an exit. Here are a couple ways to solve this issue.

For example, if we want to stop when we find an exit
we can do the following change in the code.

This variable \verb|is_exit|, which will be similar to the
variable \verb|is_explorable|, will tell, for every square,
and no surprise, if it is an exit or not.

And this other variable \verb|found_exit|, which we'll use
to keep track of whether we found an exit, will be initialized
to \v{false}, and will be set to \v{true} when we find an exit.

Finally, these last two lines will abort any exploration once
we've found an exit.

Again, if you are not familiar with programming,
\v{return} just means stop the function and go back to whatever
you were doing when you called it.

By the way, the reason why we don't simply say something like
`if the square is an exit, return', is because although we would
abort the exploration in the exit square, the exploration
in the squares with arrows would continue as usual.

Another option, in case we wanted to keep exploring the maze,
would force us to check whether the square
is inside of the maze, which we could code this way.

This small function would first check if the square we want to explore is
inside of the maze, and if so, would return true if the square is explorable.

%Try to deduce what will the algorithm do in this case. You
%can check if you are right by looking at the plain animation that
%I will leave in the description.

\subsection{Observations}

Now, look at the algorithm again and pay attention to the arrows.
As you can see, in any moment of time,
if you follow the direction that the arrows point to,
you will see that they create a path from the initial
square to whatever square we are exploring at that moment.

Note the path only changes in two ways.
Either we add a new square to the end of the path,
or we eliminate the last square from the path.

If you are already a programmer with some experience,
this may sound familiar. The path is behaving as a stack!

If you don't know what stacks are, don't worry,
we'll devote a full video in this series to explain how they work,
and to see how they hold the key for an iterative version
of this algorithm.

By the way, if you still feel a bit confused about recursion,
there's a small detail you may want to pay attention to.

Note that at each step, in all squares with arrows,
with the exception of the one we are exploring,
the $i$'s in such squares don't change.

You can see this as an interesting way to think about recursion:
a function that calls itself, and that is frozen
while the recursively called function has not ended.

%If you don't know what stacks are, don't worry, we'll devote a full video in
%this series to explain what they are and how they work, and how we can implement
%with a few more lines of code an iterative version of the DFS algorithm,
%that is, a DFS that does not
%need recursion. Be sure to check it out, because it will hold the secret
%for the next algorithm, breath-first search, or just BFS.

%By the way, if you are still not very familiar with recursion, there's a small
%detail you may want to pay attention. Note that at each step, the $i$'s in each
%square are frozen, all but the one of the square we are exploring. You can find it
%an interesting way to think of recursion: just a function that uses the same function to compute itself, and that is frozen as long as the recursively called function
%has not ended.

% If we have not stored the map and just build it as we find it, it is the same
% Code things (like adding a return at the beginning, variations...)

\subsection{The right-hand rule}

Finally, we'll end this video with a nice little trick about
mazes. If the maze has no cycles, like this one,
touch the wall of the maze with one hand,
and walk along the maze while dragging your hand along
the wall without separating it.

If you do that, you will traverse the maze until you
eventually find an exit. If you don't find it, bad news,
your maze has some cycle, and it
will not be that easy to find an exit.

Or, even worse news, your maze doesn't have any (reachable) exit
and you will be trapped forever.

But hey, at least thanks to this video you will have found
your tragic fate optimally.

%\subsection{Stacks}
%\subsection{Implementing DFS with a stack}
%\section{Video 2. BFS}
%\subsection{Stacks and queues}
%\subsection{Explain Code}
%\subsection{Animation}
%\subsection{Observations}
%\section{Video 3. Dijkstra}
%\subsection{Generalizing DFS and BFS to all Graphs}
%\subsection{Weighted graphs}
%\subsection{Priority Queues}
%\subsection{Explain Code}
%\subsection{Animation}
%\subsection{Observations}
%\subsection{Conclusions}

\end{document}


\documentclass[12pt]{article}

% packages
\usepackage{setspace}
\usepackage{hyperref}
\usepackage{array}
\usepackage[margin=0.75in]{geometry}
\usepackage{amsmath,bm}
\usepackage{amssymb}
\usepackage{bbold}
\usepackage{physics}
\usepackage{xcolor}
\usepackage{indentfirst}
\usepackage{enumerate}
\usepackage{mathtools}
\usepackage{fancyhdr}
\usepackage[ruled,vlined]{algorithm2e}

\pagestyle{fancy}
\fancyhf{}
\rhead{Creative Destruction Lab}
\lhead{Introductions to Projects}
\rfoot{Page \thepage}

\allowdisplaybreaks

\title{Project 4: Ising Annealing}

\begin{document}

\maketitle

\thispagestyle{empty}

\subsection*{Motivation}

If we go back to a couple of weeks ago to Projects 1 and 2, you were able to simulate molecules in a couple of different ways: using machine learning (Restricted Boltzmann machines) and using the Variational Quantum Eigensolver (VQE). In Project 1, you were able to see that machine learning gives a huge advantage in data-driven problems in terms of outputting a compressed version of something quite large (exponential scaling -- $2^{100}$ -- versus a few hundred numbers). Not only this, you saw that if we needed to collaborate with an experimentalist in a lab, machine learning doesn't  demand much from experimentalists (we don't need that much data from them). In Project 2, you saw that solving chemistry problems via simulation on a quantum circuit also has compression benefits, but we didn't need any input data to actually solve our problem like in Project 1. Rather, the {\it variational method} just requires knowledge of the Hamiltonian, and a tunable {\it trial solution} to our problem that we then change based on how good of an energy it gives.

At the end of the day, VQE and machine learning are both extremely useful in different settings, but at heart of each is an {\it optimization problem}.\footnote{In machine learning we must optimize the cost function and in VQE we must optimize the energy.} Sometimes this optimization problem can be extremely difficult to tackle.
This week, we'll re-cast the problem into one that can be explored with the well-known simulation method called Monte Carlo (MC).
At the end of a Monte Carlo simulation we do not obtain a compressed version of something much larger (like the wavefunction).
Rather, we use a Monte Carlo procedure to produce samples, correctly distributed, from a low-energy state.

Thermal annealing exploits thermal fluctuations to discover the groundstate of a system. In a Monte Carlo simulation the temperature can be slowly decreased. If this decrease is slow enough the system remains close to equilibrium, and at the end of annealing the typical configurations encountered will be those typical of the system in its groundstate.\footnote{Of course, in addition to thermal fluctuations, one can envision the use of quantum fluctuations to accelerate the exploration of the configuration space in a similar manner}

Monte Carlo simulations can be {\it very, very} efficient and fast.\footnote{You now see the daily struggles of computational scientists: which algorithm or method do I use to solve my problem?!} This week, your tasks will involve the use of a single-spin-flip Metropolis-Hastings (MH) MC simulation. Let's dive into your tasks!

\subsection*{Your Tasks}

This week, you will be tasked with performing various MC simulations on the Ising model,
\begin{equation}
    H = -J\sum_{\langle i,j \rangle} \sigma_i \sigma_j,
\end{equation}
where $\sigma_i$ are classical spin-$1/2$ variables ($-1$ or $1$). You will be walked through a simulation we've provided along with an annealing procedure. Then, you'll be given slight variations to the Ising model where you must come up with an annealing procedure yourself!

\subsubsection*{Task \#1}

Navigate to the \texttt{Task\_1.ipynb} notebook. We've given you a full solution to a MC simulation employing the MH algorithm for a 2D ferromagnetic ($J > 0$) on a square lattice with periodic boundary conditions. Code blocks 1 to 5 outline a MC simulation for this system for a temperature $T = 1.0$. After this, we now wish to perform a simulation at a temperature $T_{\text{final}} = 0.01$ using an annealing procedure starting at $T_{\text{initial}} = 100$. Here, we employed an annealing procedure that decreases $T_{\text{initial}}$ exponentially (see code block 7). Run this notebook and make sure that you understand what is going on under the hood (see \texttt{abstract\_ising.py} and \texttt{ising\_animator.py}).

\subsubsection*{Task \#2}

Above, we used an exponential annealing ``schedule''.  However, there are many other functional forms that you could use to define the annealing procedure (e.g.~linear).
In this task you should explore different possibilities, to see what works best (by giving the lowest energy at the end of the anneal).
Navigate to \texttt{Task\_2.ipynb}. Here's what we'd like you to do!
\begin{enumerate}
    \item Having understood Task \#1, we're now going to task you with finding an annealing procedure for the random-bond Ising model in 1D,
    \begin{equation}
        H = J\sum_{\langle i,j \rangle} B_{ij}\sigma_i\sigma_j,
    \end{equation}
    where $B_{ij} = \pm 1$ are selected randomly at the start. Do this for various system sizes (10, 20, 50, 100).
    \item The fully-connected random bond Ising model
    \begin{equation}
        H = J \sum_{i < j} B_{ij}\sigma_i\sigma_j,
    \end{equation}
    is even a little harder to perform a good MC simulation for low temperatures. Find an annealing procedure for this model, as well.
\end{enumerate}
We've given you the required classes in order to get your started on these models in \texttt{Task\_2.ipynb}. In your annealing procedures, start with as high of a starting temperature as needed and get to as low of a temperature as you can!

\subsubsection*{Task \#3}
This is where things get fun!
We'll be applying what we've learned so far to calculate the ground state energy
of the Hydrogen molecule at various separation lengths.

There are several methods with which one can map the electronic structure Hamiltonian
of the Hydrogen molecule to a classical Ising Hamiltonian
\cite{iqcc,qcc,xia2016electronic,xia2017electronic} (all of these papers are available on the arXiv).
The Ising Hamiltonians we'll be handling here were produced using the
\textit{Iterative Qubit Coupled Cluster} method \cite{iqcc}. This method
in fact produces \textit{Generalized Ising Hamiltonians}, that is, Ising
Hamiltonians with $k$-local interactions (where $k > 2$).
In the case of the Hydrogen molecule, we need only 4-spins to encode the ground state and
hence, our Generalized Ising Hamiltonian has $k$-local interactions upto $k=4$.

$$
H = E_0
+ \sum_{i} h_{i}\sigma_i
+ \sum_{ij} J_{ij}\sigma_i\sigma_j
+ \sum_{ijk} K_{ijk}\sigma_i\sigma_j\sigma_k
+ \sum_{ijkl} L_{ijkl}\sigma_i\sigma_j\sigma_k\sigma_l
$$

The arrays $J_{ij}, K_{ijk}, L_{ijkl}$, encode the $k$-point
interaction strengths between different Ising spins, $h_i$ encodes the
external magnetic field applied to the $i$th spin, and $E_0$ is a constant
energy shift which is irrelevant for the Monte Carlo simulation but
necessary for computing the energy of the Hydrogen molecule.

Our goal is to perform an annealed Monte Carlo simulation of this
Hamiltonian in order to find the ground state energy of $H_2$.

\begin{enumerate}
    \item In \texttt{Task\_3.ipynb}, you'll find the function \texttt{read\_generalized\_ising\_hamiltonian}
          which will provide you with the Hamiltonian parameters above. Below that, you'll
          find a skeleton for a \texttt{GeneralizedIsingModel} class which you must complete.
          With this, you'll perform a Monte Carlo simulation at a fixed temperature for 1000 steps.

    \item Next, you'll devise an annealing procedure (or use one of the ones you came up with previously)
          to find the ground state of the system.

    \item As we only have 4 Ising spins, we can compute the ground state energy exactly.
          Do this by iterating over all possible spin configurations, computing the energy
          for each, and find the ground state. Compare this energy to the one you obtained
          using annealing.

    \item Last, you'll repeat the above for all the different Hydrogen separation lengths provided.
\end{enumerate}

\subsection*{Further Challenges} \label{sec:challenges}

\begin{enumerate}
    \item In \texttt{Task\_2.ipynb}, we also gave you some code to get you started on determining
          an annealing procedure for the fully-connected Mattis model. Try finding an annealing
          procedure for this model at various system sizes.

    \item Many existing quantum annealers don't support $k$-local interactions for $k > 2$.
          Reduce the $H_2$ generalized Ising Model from Task \#3 to a $2$-local Hamiltonian
          (see \cite{xia2017electronic}) and repeat Task \#3 for this $2$-local Hamiltonian.
          Compare the energies you get from annealing this Hamiltonian to the energies
          you got from applying annealing to the original $k$-local Hamiltonian. Does it seem to
          be more or less difficult to find the ground state with classical thermal annealing?

\item If you have a trustworthy $2$-local Hamiltonian from the above challenge, compare your home-grown
	thermal annealing procedure to open-source commercial software (e.g.~D-Wave Leap).  Benchmark
	performance.  Contrast and compare any differences in annealing approaches.

    \item Map your favorite NP-complete complete Hamiltonian to an Ising Hamiltonain, and perform
          a thermally-annealed MC simulation to try to solve to problem. See \cite{ising_np} for some
          inspiration. Benchmark against commercially available open-source optimization software.

\end{enumerate}

\subsection*{Acknowledgements}\label{sec:acknowledgements}
We thank the authors of \cite{iqcc} (particularly Ilya and Scott) for their help with Task \#3 and for
providing the Generalized Ising Hamiltonians for $H_2$.

\newpage

\nocite{*}
\bibliography{refs}
\bibliographystyle{unsrt}

\end{document}


\section{Teamwork contact center}
\label{sec:Teamwork}

This models a contact center with complex routing logic in which a
contact is processed by several agents.  This model contains a single
contact type but several agent groups.  Contacts arrive following
a non-homogeneous Poisson process with a mean arrival rate of $200/$h from
8AM to 9AM and $100/$h from 9AM to 5PM, and are served by several
agents sequentially.

When a contact enters the system, it is routed to one of the two
receptionists, or
queued if the receptionists are not available.  Service times are
i.i.d.\ variables following
the triangular distribution with minimum 0.5~minutes, mode 1~minute,
and maximum
5~minutes.  After the service is over,
with probability~$0.2$, a \emph{conference} is initiated with the
accounting department if the corresponding agent is free.
When a conference occurs, the contact still keeps the
receptionist busy and requests a communication with a secondary agent,
from the accounting agent group, if
available.  The service time with the accounting agent is uniform $2*U(0,
1)$~minutes.  The time spent with the receptionist is the sum of the
triangular
service time, and the uniform conference time if conferencing was
required
and succeeded.  After the communication is over, the receptionist
transfers the contact to the manager or to the
technical
support.  Before going idle or accepting a new contact, the agent
performs some after-contact work, e.g., updating a folder.  The
after-contact work has an
exponential duration with mean 1~minute, and starts after the contact
is transferred, not after it leaves the contact center.
After-contact work is also performed by the technical support and
manager with the same distribution, but it is not performed by
conferenced agents.

With probability~$0.05$, the contact is transferred to the manager by the
receptionist before after-contact work begins.  If the manager is
unavailable, the contact can be queued.  After being served by the
manager, the contact exits the system.  The service time with the
manager is generated from the same distribution as the service time
with the receptionist, but the generated value is multiplied by~3.

With probability~$0.95$, the receptionist transfers the contact it
has served to one
of the five technical support agents instead of the manager.
In contrast with the manger, if the contact cannot be served
immediately, it
disconnects without waiting in queue.  The service time with the technical
support is generated from the same triangular distribution as the
receptionist, but the obtained value is multiplied by~10.
After the service is done, with probability~$0.2$, a conference with
the
development agent is initiated. If the developer is available, the
conference time is uniform $5*U(0, 1)$.

%\subsection{Implementing the model}

\lstinputlisting[
caption={A simulation program for a teamwork model},%
emph={main,MyRouter},label=lst:Teamwork
]
{Teamwork.java}

Listing~\ref{lst:Teamwork} presents the complete source code for this
example.  In the program,
a class \texttt{Teamwork} is
created, and constants are declared for input data.  Most events are
counted using integers since the system supports a single contact
type.  The occupancy ratios of agents require arrays because the system
has five agent groups.

In previous examples, the different steps of a service were not
modeled explicitly.
An exponential or uniform service time was generated and
used, and the end of service was automatically scheduled by
ContactCenters.  In this example, the service of a contact is divided
in three
parts: the communication time with the
agent, the optional conference time with another agent, and the
after-contact
time.  The library supports after-contact time, but
conferencing must
be implemented by the user, because an infinity of
models can be imagined.

In ContactCenters, the service of a contact
is a two-pass process composed of the
communication with the agent (first phase), and the after-contact work
(second phase).
When the first phase is over, the contact is notified to
exited-contact listeners by the router for statistical purposes, but
the busy agent is not freed up until the second phase is over.
In previous examples, since there was no after-contact work, the two
steps were ending at the same time.

The \texttt{set\-Default\-Service\-Time} method of \texttt{Contact} we used in
previous examples sets the contact
time to the service time, and resets the after-contact time to 0.
The two durations can be changed separately by using the
\texttt{set\-Default\-Contact\-Time} and
\texttt{set\-Default\-After\-Contact\-Time} methods,
respectively.

In section~\ref{sec:occcor}, we used an agent-group listener to track
the number of agents in a group, in order to disable statistical
collecting when $N(t)=0$.  Because such a listener can be notified
about the end of a service, one could think about using this mechanism
to implement conferencing.
However, conferencing cannot be modeled with an agent-group listener
because
the listener is notified only after the phases of the
service are terminated.
It is not possible to conditionally extend the service duration as it
is needed in a conferencing model.
To model such complex services, automatic service termination must be
disabled.  By default, contact times are extracted from contact
objects and are infinite if unspecified.
As with the waiting queue which does not
schedule the dequeue event when the maximal queue time is infinite,
the end-service event is not scheduled if the obtained service time is
infinite.  The event can then be manually scheduled to simulate a
simple
service, or a wrapper event can be used to add logic before the
service termination.

Usually, a patience, a contact (or handle) and an after-contact times
are the
only random variables associated with a contact.  Here, additional
variables are required: the contact time for each agent group
(including conference times), the
after-contact times, as well as probabilistic
branching decision variables.  These variates can be generated when
needed, but to maximize random number synchronization, it is better to
generate all random variates at the creation of the contact object
since all the information is already available at this moment.
We do not know in advance the exact path of the contact, but we know
which random variates it might need during its lifecycle.
To support this extra information, a
subclass of \texttt{Contact} called \texttt{My\-Contact} is created.
The \texttt{My\-Contact\-Factory}
instantiates \texttt{My\-Contact} objects instead of \texttt{Contact}
objects as before.  Unfortunately, the library's classes manage
\texttt{Contact} instances which must be casted to \texttt{My\-Contact}
as needed.

For each agent group not used for conferencing, i.e., reception,
manager and technical support, an exponential after-contact time is
generated and stored in contacts.  A custom value generator is
assigned to each agent group in
order to extract the appropriate time from the contact objects.
The after-contact time generation works the same way as the service
time and maximal queue time generation.

The router is the most complex part of this contact center.  This time,
we define a completely custom router which extends the \texttt{Router}
abstract class.  The abstract router is constructed with the supported
number of contact types, agent groups, and waiting queues.  In this
example, there are two waiting queues: a first one for
receptionists, and a
second one for the manager.  There are five agent groups: Reception,
Accounting,
Manager, Technical support, and Development.
Every incoming contact is
sent to the Reception by \texttt{select\-Agent}.
If there is no free
receptionist, \texttt{select\-Agent} returns \texttt{null} and the contact
is queued by \texttt{select\-Waiting\-Queue}.

When the communication part of a service is terminated, the
appropriate
agent group notifies it to the router which calls its protected method
\texttt{end\-Contact}.  By default, this method simply calls
\texttt{exit\-Served} in order for the contact to leave the system after
service.  We can implement contact transfer by overriding this method
as follows.  The end-contact event is ignored for the Accounting and
Development agent
groups since the method will be called again to end the communication
with the associated Reception or Technical support agent groups. When
the communication between the contactor and the receptionist is
terminated, the transfer occurs: with probability~$0.05$, the contact is
sent to the manager.  If the contact center is closed at transfer time,
the contactor is disconnected by calling the \texttt{exit\-Blocked}
method.
The blocking-type indicator, given to \texttt{exit\-Blocked}, is set
to 5 in order to distinguish this disconnection from true
blocking because of no phone line.
If there is no free manager, the contact is put
in the queue for the manager, i.e., the second waiting queue.  Otherwise,
the second service of the contact begins.
If the contact is transferred to technical support,
the system applies the same algorithm as for the manager, except
that there is no waiting queue and a conference can occur.  If no
technical support agent is available, the service of
the contact ends at the receptionist (\texttt{exitBlocked} is called).
For any other agent group, the \texttt{end\-Contact} method
calls \texttt{exit\-Served} for the served contact to leave the system.

When the service of a
contact by an agent begins, whether it is started by agent or contact
selection, the protected \texttt{begin\-Service}
method is called.  We override the method in our custom router to
schedule the
end-service event appropriately, or to construct and schedule a
wrapper event for conferencing.  For the case of the receptionist,
with probability~$0.2$, a wrapper
\texttt{Conference\-Event} is scheduled to manage the service
termination.  The end-service event is kept inside the conference event
for future use.
With probability~$0.8$, the regular end-service event is scheduled and
no conference event is constructed.
Similar logic is used for the technical support, with a different
secondary agent group.  In the case of the manager, the regular
end-service event is always scheduled.
For Accounting and Development, nothing happens in that method,
because the service termination is managed by the conferencing event.

Conferencing is implemented using an auxiliary wrapper event
containing
three fields: \texttt{es} for the end-service event associated
with the main agent, \texttt{es\-Conf} for the end-service event
bound to the conferenced agent, and \texttt{target\-Group}, a
reference to the
conferenced agent group.  The end-service event objects are only used
as information containers instead of being scheduled as
simulation events.  The conference event happens at
most twice: one time to start the conference, and a second time to
terminate the communication with the main
agent as well as the conference.  The conference happens only if the
conferenced agent is free.

Automatic  waiting queue clearing must be redefined since there is no
default data structure in use.  The \texttt{check\-Waiting\-Queues}
method, which is called each time $N_i(t)=0$ for an agent group~$i$,
is responsible for this operation.  If it is called for a
Reception agent, the Reception waiting queue is cleared.  If it is called
for the Manager, the Manager waiting queue is cleared.  Otherwise, nothing
is done.  The waiting queue is cleared only if there is no available
agent in te corresponding group.

The average speed of answer and service level performance measures can
be computed several ways.  Each contact in the system can
sojourn in the reception's waiting queue, the
manager's waiting queue, or both queues.
Using the \texttt{get\-Total\-Queue\-Time} method
of the class \texttt{Contact} as in the previous examples gives
the cumulative waiting time in both queues.  We could also get the
queue time for each waiting queue.
Here, to keep the program as simple as possible, the speed of answer
is assumed to be the total waiting time in both queues for served
contacts.  The average handle time is
computed by taking the contact time for the last agent, which is
extracted from the end-service event given to the \texttt{served}
method of \texttt{My\-Contact\-Measures}.

There are two types of disconnections: when agents go off-duty or
when no technical support agent is free.  The first case is handled
in \texttt{dequeued} as usual.  The second case is handled in
\texttt{blocked} since the disconnection was performed using
\texttt{exit\-Blocked}, in the \texttt{end\-Contact} method of
\texttt{My\-Router}.  The blocking type is tested to distinguish this
event from a blocking due to no available phone line.

We can see from the statistical report on Listing~\ref{res:Teamwork}
that our results are different
from Arena Contact Center Edition~8.0's.  This is due to several
factors and possible bugs in Arena Contact Center Edition arising when
contacts are served by several agents sequentially.

First, there are several ways
to define the same performance measure and Rockwell's documentation
often does not clearly specify what is estimated when service is
performed by multiple agents.  By
experimenting with simplified models, it is sometimes but not always
possible to guess what computation is made.
Inconsistencies such as service levels greater than 100\%
 even arise in some extreme conditions.
Without accessing the definitions of the Contact Center Arena
templates, which cannot be done without the Professional edition, an
explanation for these inconsistencies cannot be found.

\lstinputlisting[caption={Results of the program \texttt{Teamwork}},
xleftmargin=-0.8cm,linewidth=17cm,breaklines,prebreak={\char92},
language={},label=res:Teamwork]{Teamwork.res}

\begin{comment}
\subsection{Different results from Arena Contact Center Edition}

We can see from the statistical report on Listing~\ref{res:Teamwork}
that our results are different
from Arena Contact Center Edition~8.0's.  This is due to several
factors and possible bugs in Arena Contact Center Edition arising when
contacts are served by several agents sequentially.

First, there are several ways
to define the same performance measure and Rockwell's documentation
often does not clearly specify what is estimated when service is
performed by multiple agents.  By
experimenting with simplified models, it is sometimes but not always
possible to guess what computation is made.
Inconsistencies such as service levels greater than 100\%
 even arise in some extreme conditions.
Without accessing the definitions of the Contact Center Arena
templates, which cannot be done without the Professional edition, an
explanation for these inconsistencies cannot be found.

Our first simplified model we will call $MM$
disables conferencing and sends every contact
to the manager after they are served by the receptionist.  This way,
the model becomes similar to preceding
examples, except that the service is performed by two agents
sequentially.
By simulating 10 replications in Arena Contact Center Edition, we
obtain a speed of
answer of $1.54\pm 0.03$.  If, as with the code of this example,
the average speed of answer is computed
using the cumulative queue time for contacts served by the manager
after being served by the receptionist only,
the Java program gives $3.30\pm 0.08$, which
is significantly higher than Arena Contact Center Edition.  If the
performance measure is computed by
summing the waiting times at the receptionist only for contacts served
by the manager, we obtain
$1.66\pm 0.05$, which is better but still significantly different from
Arena Contact Center Edition.
% We could try other variations such as including the waiting times for
% contacts having been served by the receptionist but having abandoned
% before being served at the manager; this gives a still different
% speed of answer of $1.68\pm 0.03$.

We now increase the talk time multiplier at
the manager, which increases the service time for this agent
group without affecting the receptionist.  During these
longer services, a queue at the manager should build up and the average
waiting time should increase.  If we increase the multiplier from 3 to
100, the average speed of answer effectively increases
to $1.703\pm 0.02$ when computed by Arena Contact Center
Edition.  As a result, the estimator takes the manager agent group into
account.

We then tried computing the number of services in each agent group
separately as follows.  If a contact abandons at the receptionist, its
waiting
time is not counted as it is usual for the speed of answer.  If a
contact is served by a receptionist but abandons before reaching the
manager, its waiting time at the receptionist as well as one service
are counted.  If a contact is served both by the receptionist and the
manager, the cumulative waiting time as well as two services are
counted.  The resulting speed of answer drops
at $0.317\pm 0.008$, which is still different from Arena Contact
Center Edition.
As a result, we cannot determine the exact formula being applied by
Arena Contact Center Edition to get the speed of answer when multiple
agents serve a contact sequentially.

With the service time, we have the same problem, with additional
inconsistencies from Arena Contact Center Edition.
In the simplified model $MM$,
if we set a constant service time in Arena Contact Center Edition, we
can suppose that the
handle time is given by the service time in the last agent group only,
not the sum of service times for all traversed agent groups.  If we
keep a random service time and set a 0 talk time multiplier for the
second agent group, we obtain a 0 handle time, which still verifies
our hypothesis.  However, problems appear if service times are random
for both agent groups.  The
expected triangular service time can be obtained by
\[\frac{0.5 + 1 + 5}{3}=2.1666.\]
For the manager, the expected service time should therefore be $6.5$
because
the service time multiplier is 3.  For the Java program, the expected
handle time falls into the confidence interval if all contacts go to
the manager.  However, it is
significantly smaller in Arena Contact Center Edition, i.e., $5.34\pm
0.03$.  As a result, the handle time estimator of Arena Contact Center
Edition suffers
from inconsistencies that could not be explained.

An additional test shows up inconsistencies with the service level.
If, in the original Teamwork model, all contacts are directed
to the technical support with conferencing still disabled, the
simplified model
has a single waiting queue since no customer can wait for a
technical support agent.
If we set the talk and after-contact times to 0, all services
become instantaneous.  No customer is waiting and the service level
should be 100\%.  However, Arena Contact Center Edition gives a
service level of
200\%, which is not what we expected.  The number of contacts meeting
the service level target reported by the program is $13888.40\pm
116.48$, which is twice the number of arrivals ($6944.2\pm 58.24$).
If we enable after-contact work back, the number of contacts in
target becomes $10572.20\pm 88.85$, which is still greater than the
offered load.
With non-zero service times, the number of contacts in target is still
greater than the number of handled contacts: the service level
estimator seems to include abandoned contacts.  However, if we include
abandoned contacts in the estimator, all preceding
Arena Contact Center examples return a significantly higher service
level.

Finally,
with the original model, Arena Contact Center Edition gives an average
of $664.40\pm 12.81$ handled and $6160.60\pm 47.50$ abandoned
contacts.  However, our Java example returns more handled and less
abandoned contacts.
In the Arena Contact Center Edition model, the receptionists serve
less contacts, which results in more abandonment.
It seems that the receptionist is unexpectedly kept busy for all the
sojourn time of the served contacts, even after they are transferred to
the technical support or manager, and the after-contact work is
completed.
\end{comment}


In this section we present our predictions for the population of detectable LISA sources for our fiducial model. In total we expect, on average, $124$ detections in a 4-year LISA mission, of which $\BHBHFourYear{}$, $\BHNSFourYear{}$ and $\NSNSFourYear{}$ are BHBHs, BHNSs and NSNSs respectively, based on our fiducial simulations. In the remainder of this section, we discuss where the sources are expected relative to LISA's sensitivity curve (Sec.~\ref{sec:dcos_on_sc}), their properties (Sec.~\ref{sec:fiducial_distributions}), their locations in the Milky Way (Sec.~\ref{sec:mw_detectable_distribution}), their formation channels (Sec.~\ref{sec:progenitors_and_formation}) and finally we discuss the expected SNR and how accurately we expect that the parameters can be measured (Sec.~\ref{sec:measurement_uncertainties}). Note that all results shown in this section are based on our fiducial simulations. A discussion of the impact of variations in the physics assumptions is provided in Sec.~\ref{sec:variations}.

\subsection{The LISA sensitivity curve and the population of detectable sources}\label{sec:dcos_on_sc}
\begin{figure*}[p]
    \centering
    \includegraphics[width=\textwidth]{fig2_dcos_on_sc.png}
    \caption{The LISA sensitivity curve is shown together with the density distribution of the characteristic strain and the dominant frequency for all detectable sources in our simulations (top) and separated by type (bottom). Contours show the percentage of the population enclosed. The remaining 2\% of the population is shown as dots with a size that scales with the sampling weight. To guide the interpretation, we show reference lines marking where a circular binary would reside for a given distance (diagonal line) and remaining inspiral time (vertical lines), assuming an average chirp mass $\avg{\mathcal{M}_c}$, orientation and sky location. The coloured lines in the bottom panels show a contour that encloses 90\% of the population that is circular. LISA verification binaries are overplotted in the top panel (star symbols).  See also Fig.~\ref{fig:dcos_on_sc_ecc_col} and Sec.~\ref{sec:dcos_on_sc} for a discussion. \href{https://github.com/TomWagg/detecting-DCOs-in-LISA/blob/main/paper/figures/fig2_dcos_on_sc.png}{\faFileImage} \href{https://github.com/TomWagg/detecting-DCOs-in-LISA/blob/main/paper/figure_notebooks/sensitivity_curve.ipynb}{\faBook}.}
    \label{fig:dcos_on_sc}
\end{figure*}
We show the expected LISA sensitivity curve \citep{Robson+2019} in Fig.~\ref{fig:dcos_on_sc}, which includes the confusion noise arising from the Galactic WDWD population, and overplot our predictions for the distribution of detectable sources. Eccentric systems emit gravitational waves in multiple harmonic frequencies ($n f_{\rm orb}$, with $n = 2, 3, \dots $). We choose to plot them at the $x$-coordinate that corresponds to the frequency of the harmonic that individually accumulates the largest SNR. For circular systems, the $x$-coordinate simply corresponds to $2 f_{\rm orb}$. The $y$-coordinate indicates the strength of the signal (or to be more precise, the amplitude spectral density, ASD), including the contribution from \textit{all} harmonics.

For reference, we show dotted lines to indicate where a hypothetical binary system would reside assuming a given distance from earth (diagonal lines) and a fixed remaining inspiral time (vertical lines). For each line we assume the binary is circular and has a chirp mass equal to the average of the sample ($\avg{\mathcal{M}_c}$, annotated in each panel). We also overplot the LISA verification binaries (star symbols, \citealt{Kupfer+2018}).

\vspace{1em}

We observe several features in Fig.~\ref{fig:dcos_on_sc} that are worth discussing and explaining. We note that some of these have also been described in earlier studies (see Sec.~\ref{sec:compare_studies}). Firstly, we note the empty band that separates the LISA sensitivity curve and the detectable population. This is the result of the criteria for detection where we require $\rm{SNR} > 7$.

We further note that the detectable population is concentrated on the left side of LISA's sensitivity window. The peak is located at a frequency of about $0.4 \unit{mHz}$, which is much lower than the frequency where LISA will be most sensitive (about $10 \unit{mHz}$). This can be understood from the acceleration of inspiraling DCOs as they evolve towards higher frequencies. DCOs typically form with wide orbits (low frequencies) that would not be detectable yet. Their orbits shrink as they lose angular momentum in the form of gravitational waves leading to an increase of their orbital frequency until they become detectable. These systems are increasingly rare because they evolve faster and faster towards higher frequency as the inspiral accelerates, even though the signal emitted by a more compact binary is stronger \citep{Peters+1964}. The vertical grid lines show these rapidly decreasing inspiral times at increasing frequencies. Most of the population is thus expected to reside at low frequencies.

In the lower three panels, we show the contributions of the different types of sources. Comparing them, one can observe the shift in the frequency at which the peak is located, at $0.3 \unit{mHz}$, $0.7 \unit{mHz}$ and $1 \unit{mHz}$ for BHBH, BHNS and NSNS systems respectively. This is a result of the difference in chirp mass. A higher mass system can emit at lower frequency and still produce the minimum SNR needed for detection. We note that this effect can be used to distinguish the heavier DCOs that we discuss in this work from WDWD systems, at least probabilistically (see Sec.~\ref{sec:WDWD_distinguish}). In the same way, this also explains the offset in frequency between the population of sources we predict and the LISA verification binaries.

Inspecting the dotted reference lines, we note that the peak of the density distribution of observable sources coincides with the location expected for circular systems at $8 \unit{kpc}$, which is the distance to the centre of the Milky Way. As can be seen best in the lower panels, the reference lines for $0.1$ and $30 \unit{kpc}$ enclose the majority of systems, as expected given the dimensions of the Milky Way.

There is a distinct subpopulation of binaries, most clearly visible in the lower panels as an offshoot that extends downwards to ASDs of $10^{-19} \unit{Hz}^{-1/2}$, especially around $2 \unit{mHz}$. This offshoot is almost uniquely composed of eccentric binaries, as can be seen in Fig.~\ref{fig:dcos_on_sc_ecc_col}, which shows a similar figure but colouring individual systems by their eccentricity. This can also be seen, albeit indirectly, from the contour lines shown in the bottom panels of Fig.~\ref{fig:dcos_on_sc}, which encompass 90\% of the \textit{circular} sources in each population. This contour does not include the offshoot. We conclude that eccentric sources occupy a very different region in this diagram.

\subsection{Properties of the detectable systems}\label{sec:fiducial_distributions}
In Fig.~\ref{fig:fiducial_pdf_distributions}, we show the 1D distribution of several individual parameters of the population of detectable binaries together with the 1- and 2-$\sigma$ uncertainties obtained via bootstrapping. These uncertainties represent the fluctuations in our results over different random instances of the Milky Way. The distributions shown here are approximated by kernel density estimators, corrected for edge effects by mirroring the sample \citep{Schuster+1985}.

\paragraph{Orbital Frequency} The orbital frequency distributions for BHBHs, BHNSs and NSNSs (Fig.~\ref{fig:fiducial_pdf_distributions}a) peak at progressively increasing frequencies. As mentioned in Sec.~\ref{sec:dcos_on_sc}, this is because a higher mass DCO at the same distance and eccentricity requires a lower frequency to produce the same signal-to-noise ratio and thus be detected. The distributions appear nearly symmetric, but closer inspections shows that the left hand side is more populated, which can be seen most clearly in the curve for the BHBHs. This is due to the contribution of highly eccentric binaries, which are most abundant in the BHBH population. These systems are still detectable by LISA, despite their low orbital frequency, as the high eccentricity means that the majority of the GW signal is emitted at higher harmonics, where LISA is more sensitive.

\begin{figure*}[t]
    \centering
    \includegraphics[width=\textwidth]{fig3_detectable_properties_4yr.pdf}
    \caption{Properties of detectable systems for a 4-year LISA mission in our fiducial model. Each panel shows a kernel density estimator for a single property, coloured by DCO type. Each curve has been individually normalised. The shaded areas show the 1- and 2-$\sigma$ sampling uncertainties (obtained via bootstrapping). The dotted lines in panel b show the individual primary and secondary mass distributions. The dotted line in panel e shows the star formation history we have assumed in our Milky Way model. See Sec.~\ref{sec:fiducial_distributions} for a discussion. \href{https://github.com/TomWagg/detecting-DCOs-in-LISA/blob/main/paper/figures/fig3_detectable_properties_4yr.pdf}{\faFileImage} \href{https://github.com/TomWagg/detecting-DCOs-in-LISA/blob/main/paper/figure_notebooks/fiducial.ipynb}{\faBook}.}
    \label{fig:fiducial_pdf_distributions}
\end{figure*}

\paragraph{Black Hole Mass}
In Fig.~\ref{fig:fiducial_pdf_distributions}b, we show the distribution masses of individual black holes that are part of BHNS and BHBH systems.
The distribution for BHBH shows a bimodality. This results from the two contributions of the more and less massive BHs in BHBH systems, which peak at around $8 \unit{M_{\odot}}$ and $3.5 \unit{M_{\odot}}$ respectively as shown by the dotted lines (see also our discussion of the mass ratios below).

For both the BHBHs and BHNSs, we see that the black hole mass distribution favours low masses. About $90\%$ of BHs have masses below $11 \unit{M_{\odot}}$, in our fiducial simulations shown here. This is in stark contrast with observations from ground-based GW detectors, where heavy BHs with masses of about $30\unit{M_{\odot}}$ and higher have been common. There are two main reasons for this discrepancy. First, the population of BHs in the Milky Way (and, in particular, those detectable by LISA due to their recent formation times, see Fig.~\ref{fig:fiducial_pdf_distributions}e) primarily come from progenitors that formed from high metallicity gas according to our simulations. Stellar winds are stronger at high metallicity leading to increased mass loss. This affects the mass of the most massive black holes that can be formed \citep{Belczynski+2010}. Secondly, ground-based detectors are strongly biased towards high mass systems, since they can be detected out to larger distances and thus a greater volume is probed. In contrast, LISA has no such bias and is, in principle, sensitive to inspiraling BHBHs throughout the entire Milky Way regardless of their mass, as long as we catch them when they are emitting in the LISA band. For this reason, LISA is more likely to detect the more common lower mass BHBHs.

We also note that our BH mass distribution extends down below $5\unit{M_{\odot}}$ to $2.5 \unit{M_{\odot}}$ which is our fiducial maximum neutron star mass. The BHs in this simulation fill the so-called ``lower mass gap'' marked as a grey band \citep{Ozel+2010,Farr+2011}, see also \citet{Shao+2021} who recently also pointed this out. This prediction is sensitive to adopted model for fallback during the SN explosion as we discuss this further in Section~\ref{sec:lower_mass_gap}.

\paragraph{Mass Ratio} The mass ratio distributions for each DCO type are very distinct from one another, as can be seen in Fig.~\ref{fig:fiducial_pdf_distributions}c. The majority of NSNSs have a mass ratio close to unity, with $\NSNSqAbovePointEight{}$ of systems having $q > 0.8$, where $q \equiv m_2 / m_1$. The reason for the concentration around equal masses is that most NSs are formed either through electron-capture supernovae (ECSN) or from low mass stars in our simulations. We assume a remnant mass for any NS formed through ECSN of $1.26 \unit{M_{\odot}}$ (see Sec.~\ref{app:fiducial_physics}). The remnant mass prescription that we use assumes a fixed fallback mass for any star with a CO core mass less than $2.5 \unit{M_\odot}$, such that many NSs end up with an identical mass of $1.278 \unit{M_\odot}$ \citep[see][Eq.~19]{Fryer+2012}. This means that many NSs are formed with equal masses and hence we see a mass ratio distribution peaked around unity.

In contrast, only $\BHBHqAbovePointEight{}$ of detectable BHBHs are formed with $q > 0.8$ and the distribution peaks around $q = 0.4$. We find that the strong stellar winds in our (typically high-metallicity) progenitors are the reason behind this.

BHBHs with unequal masses typically come from progenitors that also had more extreme mass ratios at birth ($90$ and $30\unit{M_{\odot}}$ are typical for the progenitors of detectable BHBH systems in our simulations. The primary in such systems experiences strong mass loss by winds before filling its Roche lobe. This mostly happens during its early hydrogen-shell burning phase. The wind mainly reduces the mass of the envelope, but does not have a very strong effect on the core. By the time the primary fills its Roche lobe, it has become less massive and the mass ratio is closer to one. This favours stable mass transfer. The massive core of the primary star typically becomes the more massive BH. Accretion on the secondary star is limited and the secondary eventually provides the less massive black hole.

At the same time, stellar wind mass loss disfavours the formation of black holes with comparable masses. Such systems would have originated from progenitors that also started with comparable masses. The rather massive secondaries in these systems (especially after they accreted from the primary) experience very strong stellar wind mass loss due to LBV-like eruptions. This limits the amount by which they can expand \citep[e.g.][]{vanSon+2021}. At the same time, wind mass loss (and also stable and more conservative mas transfer in these systems) lead to widening of the orbit. Both effects, the reduced expansion and increased widening of the orbit, tend to prevent the secondaries from being able to fill their Roche lobe. This thus limits the number of systems that experience the reverse mass transfer or common-envelope phase needed shrink the orbits and make them tight enough to be detected as gravitational-wave sources.

We find that detectable BHNSs have even more unequal mass ratios. Moreover, the mass ratio distribution is bimodal, where the two peaks arise from two distinct formation scenarios. Around two thirds of detectable BHNSs experience at least one common-envelope event, whilst the last third are formed through only stable mass transfer. The first peak at $q = 0.18$ is from systems that experience at least one common-envelope phase and occurs at the expected mass ratio, which approximately follows the mean BH mass (${\sim}6.5 \unit{M_\odot}$) and NS mass (${\sim}1.2 \unit{M_\odot}$). Yet we also see a second peak at higher mass ratios around $q = 0.34$, which arises from the fraction of the population that underwent only stable mass transfer phases. The stability of mass transfer depends on the mass ratio, preferentially forming systems with more equal masses, i.e.\ at higher $q$.

\paragraph{Eccentricity} In Fig.~\ref{fig:fiducial_pdf_distributions}d we show the eccentricity distributions. We find that most systems (73\%) will have eccentricities larger than $0.01$ during the LISA mission, which should in principle be detectable according to \citet{Nishizawa+2016}. This means that we will potentially be able to use eccentricity to distinguish these sources from WDWDs, which are expected to have little to no eccentricity (see Sec.~\ref{sec:WDWD_distinguish}). We note that several previous studies assumed all systems to be circular when calculating the detection rates \citep[e.g.][]{Liu+2014, Lamberts+2018, Sesana+2020}. We discuss the impact of this assumption in Section~\ref{sec:compare_studies}.

For systems with eccentricities higher than $e\gtrsim0.3$, most gravitational wave energy is emitted in higher harmonics. Such systems are more rare, but we find them to be significant among the BHBH population, where they account for \BHBHHighlyEccentric{} of systems. Detectable BHBHs in our simulation (and, in particular, those that are eccentric) are primarily systems formed through the stable mass transfer channel (see Fig.~\ref{fig:formation_channels}). These systems are still relatively wide (compared to those formed through the CE channel) immediately prior to formation of the second BH, which makes them more easily affected by kicks. If the kick is oriented roughly in opposite direction to the orbital motion and has a velocity that is of similar magnitude as the orbital velocity, it will lead to the formation of a highly eccentric system.

It is rare to get such a ``lucky kick'', but there are a few effects that favour this for BHBHs. The kicks of BHs are reduced by fallback and they are thus less likely to disrupt the system. Moreover, because of their higher masses, BHBHs can be observed already at lower orbital frequencies. This means that they have not had as much time to circularise and so still have significant eccentricity by the time of the LISA mission. Finally, LISA favours the detection of eccentric systems, if all other properties are held fixed. This is because the gravitational-wave emission is stronger (Eq.~\ref{eq:peters_f}) and the energy is emitted at higher frequencies \citep[Eq.~20]{Peters+1963} where LISA is more sensitive.

The lower abundance of highly eccentric systems among the NSNS and BHNS systems may seem counter-intuitive since neutron stars are lower mass and would be more strongly affected by natal kicks, which one may expect to lead to more eccentric systems. However, the majority of NSs in our simulations are formed through ECSN and USSN and for these types of supernovae we draw from a Maxwellian with $\sigma_{\rm rms}^{\rm 1D} = 30 \unit{km}{s^{-1}}$. Thus the kicks received by NSs in our simulations are often much smaller than for BHs.

\paragraph{Time since formation}
In Fig.~\ref{fig:fiducial_pdf_distributions}e we show how long ago the LISA detectable DCOs formed. Star formation was highest at early times $6-12\unit{Gyr}$ ago, after which it declined. In contrast, the LISA detectable DCOs primarily formed in the relatively \textit{recent} history of our Milky Way, about $2 \unit{Gyr}$ ago. This reflects the fact that binaries in our simulation typically take about a Gyr to merge.

When comparing the distribution of formation times for the three different DCO types we see that NSNSs are most strongly concentrated at recent times, followed by BHBHs and then BHNSs. To understand this it is helpful to consider how the inspiral time scales with various parameters \citep{Peters+1964}
\begin{equation}
    t_{\rm inspiral} \propto \frac{a^4}{(m_1 + m_2)^{3}} \cdot \frac{q}{(1+q)^2} \cdot (1 - e^2)^{-7/2}.
\end{equation}
The inspiral time depends most strongly on the separation at DCO formation, $a$, and this is where the three types also differ most strongly (see Fig.~\ref{fig:dco_formation_properties}). The detectable NSNS systems have the tightest orbits at DCO formation. The median of the distribution of separations at DCO formation, $\langle a_{\rm DCO} \rangle_{\rm med}$, relate as 8:3:1 for detectable BHBH:BHNS:NSNS in our simulations. This results in increase of the inspiral time by a factor of about 4000:80:1. The total masses affect the inspiral time to the third power and this where the heavier BHBH systems are favoured. The median total masses differ by ratios of 6:4:1 for detectable BHBH:BHNS:NSNS in our simulations, impacting the inspiral times such that they are a factor of 200:60:1 shorter, partially counteracting the effect of the separations. The term depending on the mass ratio $q$ only varies by about 30\% for the mass ratio ranges considered here and so is not of interest. The eccentricity term is not of importance for mildly eccentric systems, $f(e_{\rm DCO} \le 0.3)  \le 1.4$ but of large importance for the very eccentric  $f(e_{\rm DCO} \ge 0.9) \ge 300$. The fraction of highly eccentric systems with $e_{\rm DCO}>0.9$ is 33\%, 16\%, and 8\% of for BHBH, BHNS and NSNS respectively, see also Fig.~\ref{fig:dco_formation_properties}.

We conclude that the shorter median separations at DCO formation are the main reason why NSNS are most strongly peaked at short delay times. They are followed by BHBHs rather than BHNSs due to the high masses and substantial eccentricities of BHBHs.

\paragraph{Time until merger} Fig.~\ref{fig:fiducial_pdf_distributions}f shows the remaining time until merger for each of the DCO types at the start of LISA mission. The distributions are strikingly similar and peak with merger times of around a Myr.

The merger time is a function of the mass, frequency and eccentricity of the sources, such that more massive, higher frequency and more eccentric sources merge faster \citep[][Eq.~5.14]{Peters+1964}. So, despite the fact that each DCO type often has higher values in any one of these properties, the convolution of all three tends to negate the differences. For example, NSNSs have the highest orbital frequencies and are mildly eccentric whilst BHNSs have moderate orbital frequencies and are more circular. However, BHNSs are more massive in general and so the overall merger times are distributed very similarly for both DCO types.

\subsection{Distribution in the Milky Way}\label{sec:mw_detectable_distribution}
For our Milky way model we consider three different components, a low-\achem~(``thin'') disc, an older high-\achem~(``thick'') disc and a bulge/bar (see Sec.~\ref{sec:galaxy_synthesis}). In Table~\ref{tab:component_fractions} we summarise the number of detections originating from each of these components. Despite the fact that only $42.5\%$ of systems are formed in the low-\achem~disc, we find that $86\%$ of the detections originate from this component. This is because most detectable systems were formed relatively recently (see Fig.~\ref{fig:fiducial_pdf_distributions}e) and so the high-\achem~disc and bulge are effectively too old to contribute many detectable systems. Nevertheless, we do find a significant fraction of detectable systems originate in the high-\achem~disc and bulge, indicating that it is still important to include these components, as was ignored in some earlier works (see Sec.~\ref{sec:compare_studies}).

\begin{table}[tb]
    \centering
    \begin{tabular}{l|c|cccc}
        \hline
        \multirow{2}{*}{Component} & Formation & \multicolumn{4}{c}{Detectable} \\ \cline{2-6}
        & {\scriptsize All} & {\scriptsize All} & {\scriptsize BHBH} & {\scriptsize BHNS} & {\scriptsize NSNS} \\
        \hline
        Low-$\alpha$ disc & 42.5\% & 86\% & 89\% & 82\% & 85\%\\
        High-$\alpha$ disc & 42.5\% & 6\% & 5\% & 8\% & 12\%\\
        Bulge/bar & 15.0\% & 8\% & 6\% & 10\% & 3\%\\
    \end{tabular}
    \caption{Percentage of systems in each Galactic component.}
    \label{tab:component_fractions}
\end{table}
\begin{figure}[tb]
    \centering
    \includegraphics[width=\columnwidth]{fig4_1_galaxy_density_distribution.png}
    \includegraphics[width=\columnwidth]{fig4_2_detectable_distance_distribution_4yr.pdf}
    \caption{
    \textbf{Top:} A face-on view of the Galactic density distribution for detectable DCOs. We show the density distribution for the top 95\% of the sources, the rest are indicated by scatter points whose sizes correspond to their sampling weights. The coloured lines show the 75\% contour for each of the individual DCO types. The large cross passes through (0, 0) and helps to highlight the bias towards the position of the sun, which is indicated by the $\odot$.
    \textbf{Bottom:} As Fig.~\ref{fig:fiducial_pdf_distributions}, but for the luminosity distance. \href{https://github.com/TomWagg/detecting-DCOs-in-LISA/blob/main/paper/figures/fig4_1_galaxy_density_distribution.png}{\faFileImage} \href{https://github.com/TomWagg/detecting-DCOs-in-LISA/blob/main/paper/figure_notebooks/galaxy_creation_station.ipynb}{\faBook} \href{https://github.com/TomWagg/detecting-DCOs-in-LISA/blob/main/paper/figures/fig4_2_detectable_distance_distribution_4yr.pdf}{\faFileImage} \href{https://github.com/TomWagg/detecting-DCOs-in-LISA/blob/main/paper/figure_notebooks/fiducial.ipynb}{\faBook}.}
    \label{fig:detectable_distance_dist}
\end{figure}

In the top panel of Fig.~\ref{fig:detectable_distance_dist}, we show the density distribution for detectable DCOs in the galaxy. We see that most detectable sources are concentrated towards the Galactic centre, with a strong bias towards sources that are on our side of the Milky Way in the vicinity of the solar system (indicated with the $\odot$ symbol). In principle, systems are detectable out to large distances of about $20\unit{kpc}$ and more, although they become increasingly rare, as can be seen from the 95\% contour.

The differences between different DCO types can be seen more clearly in the bottom panel of Fig.~\ref{fig:detectable_distance_dist} where we show the distribution of the distances, $D$, from earth to the detectable systems. Each distribution peaks around $8\unit{kpc}$, which is the distance to the centre of the Milky Way. The distribution for BHBH and BHNS systems follow a very similar shape, favouring the detection of systems with distance $<8\unit{kpc}$, but with a tail extending out to about $20\unit{kpc}$.

The distribution for NSNS stands out by being flatter, making them more common nearby and, surprisingly, also at larger distances compared to the stellar density. This may seem counter intuitive as one might naively expect the less massive NSNS systems would not be observable out to larger distances than the more massive BHNS and NSNS systems. To understand the differences we need to consider not only the mass distribution of binaries, but also their eccentricity and frequency distributions. Since, each parameter contributes to the calculation of the SNR (and thus affects the maximum distance at which systems can be detected).

The reason that the NSNSs are favoured at higher distances is that the NSNS population has the highest fraction of ``mildly'' eccentric systems ($0.01 < e < 0.03$). In contrast, the BHNS population has a much higher fraction of effectively circular systems ($e < 0.01$), which emit weaker gravitational waves compared to equivalent eccentric systems. Therefore, despite their typically higher masses, the distance at which a BHNS source is detectable is generally lower than for the mildly eccentric NSNS.

Conversely, the BHBH population has the highest fraction of highly eccentric systems ($e > 0.3$). Although one may naively expect that this would result in stronger signals (and so further distances), for a system to have these high eccentricities in LISA, it must still be early in its evolution (otherwise it would have circularised) and thus have a low orbital frequency. The result of this is that highest eccentricity systems tend to have lower SNRs and so cannot be detected at large distances.

Overall we see that the eccentricity distribution of NSNSs occupies a ``sweet spot'' where the gravitational wave power is increased compared to circular systems, but it isn't too high that the frequency is significantly impacted. This means that NSNSs can be seen out to the largest distances of the three DCO types.

\subsection{Formation channels}\label{sec:progenitors_and_formation}
In our fiducial model, approximately two thirds of detectable BHBHs are formed through the `only stable mass transfer' channel, whilst the remaining third are primarily formed through the `classic' CE channel. Detectable BHNSs follow an inverse pattern, such that around two thirds are formed through the classic channel and the rest are mainly formed through only stable mass transfer.

In contrast, detectable NSNSs are very rarely formed through only stable mass transfer. Approximately half of systems are formed through the `classic' channel and the rest are formed through a double-core common-envelope event \citep{Brown+1995} where both progenitors evolve on a similar timescale and initiate a double-core common-envelope event whilst they are on the giant branch. All detectable DCOs show a small fraction of systems are formed through a channel that does not fit into the other categories and hence are labelled `other'. These systems tend to be formed through `lucky' supernova kicks that happen to shrink the binary significantly by chance.

The fraction of detectable DCOs that are formed through different formation channels in the other model variations are shown Fig.~\ref{fig:formation_channels}, where the first column in the plot corresponds to the fiducial model that we described above.

\subsection{How accurately will we be able to infer the parameters of detected systems?}\label{sec:measurement_uncertainties}
So far we have discussed the properties of the all detectable sources. However, only for a subset of systems we expect to get high enough SNR to obtain accurate and useful measurements of these parameters. Below we discuss the expected SNR distribution and the typical uncertainties expected for the most relevant parameters, namely, the chirp mass and sky localisation.

\paragraph{Signal-to-noise ratio}

\begin{figure}[tb]
    \centering
    \includegraphics[width=\columnwidth]{fig5_snr_cumulative_all.pdf}
    \caption{Cumulative number of LISA detections with a given signal-to-noise ratio. Colours indicate LISA mission length and shading shows 1- and 2-$\sigma$ uncertainties (obtained via bootstrapping). \href{https://github.com/TomWagg/detecting-DCOs-in-LISA/blob/main/paper/figures/fig5_snr_cumulative_all.pdf}{\faFileImage} \href{https://github.com/TomWagg/detecting-DCOs-in-LISA/blob/main/paper/figure_notebooks/fiducial.ipynb}{\faBook}.}
    \label{fig:snr_dist}
\end{figure}

In Fig.~\ref{fig:snr_dist} we show the cumulative number of detections with a given SNR. Although many a large fraction of sources have SNRs around our assumed detection threshold of 7, many systems are detected with very high SNRs. We find that on average for a 4(10)-year LISA mission, of the 124(202) detections, 85(138), 16(27) and 9(14) systems have SNRs greater than 10, 50 and 100, respectively. These high SNR systems are typically, but not only, the more massive BHBH systems.

\paragraph{Chirp mass}

The chirp mass is important for identifying the type of the source of a detected GW signal. The uncertainty of the chirp mass depends on the uncertainty in the measured orbital frequency, the time derivative of the orbital frequency and the eccentricity as detailed in Appendix~\ref{app:chirp_mass_uncertainty}.

We find that for a 4(10)-year LISA mission, approximately 41(105) detections have measurable chirp masses ($\Delta \mathcal{M}_c / \mathcal{M}_c < 1$, indicated by the dark shaded region in Fig.~\ref{fig:m_c_unc}) whilst 13(31) have chirp mass uncertainties below 10\% ($\Delta \mathcal{M}_c / \mathcal{M}_c < 0.1$, indicated by the light shaded region in Fig.~\ref{fig:m_c_unc}). This uncertainty is generally dominated by the uncertainty on the time derivative of the frequency, since most of the binaries are too early in their inspiral for LISA to measure a strong chirp.
%
Note from Fig.~\ref{fig:m_c_unc} that increasing the mission length significantly increases the number of detections for which the chirp mass uncertainty is below 100\%. The total number of detections only scales as $\sqrt{T_{\rm obs}}$, yet we find that the the total number of detections with a chirp mass uncertainty is below 100\% and 10\% both scale approximately as $T_{\rm obs}$.

\begin{figure}[tb]
    \centering
    \includegraphics[width=\columnwidth]{fig6_chirp_mass_uncertainty_all.pdf}
    \caption{As Fig.~\ref{fig:snr_dist}, but for the chirp mass uncertainty. The shaded areas indicate regions with more than 10\% and 100\% uncertainty. \href{https://github.com/TomWagg/detecting-DCOs-in-LISA/blob/main/paper/figures/fig6_chirp_mass_uncertainty_all.pdf}{\faFileImage} \href{https://github.com/TomWagg/detecting-DCOs-in-LISA/blob/main/paper/figure_notebooks/fiducial.ipynb}{\faBook}.}
    \label{fig:m_c_unc}
\end{figure}

\paragraph{Sky localisation}

An accurate sky localisation will be essential to possibly identify electromagnetic counterparts or distinguish sources that come from different components of our Milky Way.

We quantify the sky localisation of a source by estimating the angular resolution for the detectable sources. Since all potential sources are effectively stationary on the timescale of the LISA mission, we can follow \citet{Mandel+2018} and use the timing accuracy of LISA and the effective detector baseline to calculate the angular resolution, $\sigma_{\theta}$, as
\begin{equation}
    \sigma_{\theta} = 16.6^\circ \left(\frac{7}{\rho}\right) \left(\frac{5 \times 10^{-4} \unit{Hz}}{f_{\rm dom}}\right) \left( \frac{2 \unit{AU}}{L} \right),
\end{equation}
where $L$ is the effective detector baseline, which for LISA is 2 AU in the frame of the solar system, since it will orbit the Sun.

We plot the distribution of expected angular resolutions in Fig.~\ref{fig:ang_res}. We see that, for a 4(10)-year LISA mission, approximately 82(123) sources can be resolved to an angular resolution better than 10 degrees and only 16(23) better than 1 degree.

For comparison, the size of a pencil beam for a $15 \unit{m}$ diameter SKA dish observing at 1.4 GHz is roughly 0.67 square degrees \citep{Smits+2009}, corresponding to an angular resolution of $\sigma_\theta = \sqrt{(0.67 / \pi)} = 0.46^\circ$ (similar to the angular size of the moon). We will further discuss the prospects of matching LISA detections to radio pulsars with SKA in Sec.~\ref{sec:pulsar_matching}.

\begin{figure}[htb]
    \centering
    \includegraphics[width=\columnwidth]{fig7_angular_resolution_all.pdf}
    \caption{As Fig.~\ref{fig:snr_dist}, but for the angular resolution. \href{https://github.com/TomWagg/detecting-DCOs-in-LISA/blob/main/paper/figures/fig7_angular_resolution_all.pdf}{\faFileImage} \href{https://github.com/TomWagg/detecting-DCOs-in-LISA/blob/main/paper/figure_notebooks/fiducial.ipynb}{\faBook}.}
    \label{fig:ang_res}
\end{figure}


% -*- mode: latex; TeX-master: "Vorbis_I_spec"; -*-
%!TEX root = Vorbis_I_spec.tex
% $Id$
\section{Floor type 0 setup and decode} \label{vorbis:spec:floor0}

\subsection{Overview}

Vorbis floor type zero uses Line Spectral Pair (LSP, also alternately
known as Line Spectral Frequency or LSF) representation to encode a
smooth spectral envelope curve as the frequency response of the LSP
filter.  This representation is equivalent to a traditional all-pole
infinite impulse response filter as would be used in linear predictive
coding; LSP representation may be converted to LPC representation and
vice-versa.

\subsection{Floor 0 format}

Floor zero configuration consists of six integer fields and a list of
VQ codebooks for use in coding/decoding the LSP filter coefficient
values used by each frame.

\subsubsection{header decode}

Configuration information for instances of floor zero decodes from the
codec setup header (third packet).  configuration decode proceeds as
follows:

\begin{Verbatim}[commandchars=\\\{\}]
  1) [floor0\_order] = read an unsigned integer of 8 bits
  2) [floor0\_rate] = read an unsigned integer of 16 bits
  3) [floor0\_bark\_map\_size] = read an unsigned integer of 16 bits
  4) [floor0\_amplitude\_bits] = read an unsigned integer of six bits
  5) [floor0\_amplitude\_offset] = read an unsigned integer of eight bits
  6) [floor0\_number\_of\_books] = read an unsigned integer of four bits and add 1
  7) array [floor0\_book\_list] = read a list of [floor0\_number\_of\_books] unsigned integers of eight bits each;
\end{Verbatim}

An end-of-packet condition during any of these bitstream reads renders
this stream undecodable.  In addition, any element of the array
\varname{[floor0\_book\_list]} that is greater than the maximum codebook
number for this bitstream is an error condition that also renders the
stream undecodable.

\subsubsection{packet decode} \label{vorbis:spec:floor0-decode}

Extracting a floor0 curve from an audio packet consists of first
decoding the curve amplitude and \varname{[floor0\_order]} LSP
coefficient values from the bitstream, and then computing the floor
curve, which is defined as the frequency response of the decoded LSP
filter.

Packet decode proceeds as follows:
\begin{Verbatim}[commandchars=\\\{\}]
  1) [amplitude] = read an unsigned integer of [floor0\_amplitude\_bits] bits
  2) if ( [amplitude] is greater than zero ) \{
       3) [coefficients] is an empty, zero length vector
       4) [booknumber] = read an unsigned integer of \link{vorbis:spec:ilog}{ilog}( [floor0\_number\_of\_books] ) bits
       5) if ( [booknumber] is greater than the highest number decode codebook ) then packet is undecodable
       6) [last] = zero;
       7) vector [temp\_vector] = read vector from bitstream using codebook number [floor0\_book\_list] element [booknumber] in VQ context.
       8) add the scalar value [last] to each scalar in vector [temp\_vector]
       9) [last] = the value of the last scalar in vector [temp\_vector]
      10) concatenate [temp\_vector] onto the end of the [coefficients] vector
      11) if (length of vector [coefficients] is less than [floor0\_order], continue at step 6

     \}

 12) done.

\end{Verbatim}

Take note of the following properties of decode:
\begin{itemize}
 \item An \varname{[amplitude]} value of zero must result in a return code that indicates this channel is unused in this frame (the output of the channel will be all-zeroes in synthesis).  Several later stages of decode don't occur for an unused channel.
 \item An end-of-packet condition during decode should be considered a
nominal occruence; if end-of-packet is reached during any read
operation above, floor decode is to return 'unused' status as if the
\varname{[amplitude]} value had read zero at the beginning of decode.

 \item The book number used for decode
can, in fact, be stored in the bitstream in \link{vorbis:spec:ilog}{ilog}( \varname{[floor0\_number\_of\_books]} -
1 ) bits.  Nevertheless, the above specification is correct and values
greater than the maximum possible book value are reserved.

 \item The number of scalars read into the vector \varname{[coefficients]}
may be greater than \varname{[floor0\_order]}, the number actually
required for curve computation.  For example, if the VQ codebook used
for the floor currently being decoded has a
\varname{[codebook\_dimensions]} value of three and
\varname{[floor0\_order]} is ten, the only way to fill all the needed
scalars in \varname{[coefficients]} is to to read a total of twelve
scalars as four vectors of three scalars each.  This is not an error
condition, and care must be taken not to allow a buffer overflow in
decode. The extra values are not used and may be ignored or discarded.
\end{itemize}

\subsubsection{curve computation} \label{vorbis:spec:floor0-synth}

Given an \varname{[amplitude]} integer and \varname{[coefficients]}
vector from packet decode as well as the [floor0\_order],
[floor0\_rate], [floor0\_bark\_map\_size], [floor0\_amplitude\_bits] and
[floor0\_amplitude\_offset] values from floor setup, and an output
vector size \varname{[n]} specified by the decode process, we compute a
floor output vector.

If the value \varname{[amplitude]} is zero, the return value is a
length \varname{[n]} vector with all-zero scalars.  Otherwise, begin by
assuming the following definitions for the given vector to be
synthesized:

   \begin{displaymath}
     \mathrm{map}_i = \left\{
       \begin{array}{ll}
          \min (
            \mathtt{floor0\texttt{\_}bark\texttt{\_}map\texttt{\_}size} - 1,
            foobar
          ) & \textrm{for } i \in [0,n-1] \\
          -1 & \textrm{for } i = n
        \end{array}
      \right.
    \end{displaymath}

    where

    \begin{displaymath}
    foobar =
      \left\lfloor
        \mathrm{bark}\left(\frac{\mathtt{floor0\texttt{\_}rate} \cdot i}{2n}\right) \cdot \frac{\mathtt{floor0\texttt{\_}bark\texttt{\_}map\texttt{\_}size}} {\mathrm{bark}(.5 \cdot \mathtt{floor0\texttt{\_}rate})}
      \right\rfloor
    \end{displaymath}

    and

    \begin{displaymath}
      \mathrm{bark}(x) = 13.1 \arctan (.00074x) + 2.24 \arctan (.0000000185x^2) + .0001x
    \end{displaymath}

The above is used to synthesize the LSP curve on a Bark-scale frequency
axis, then map the result to a linear-scale frequency axis.
Similarly, the below calculation synthesizes the output LSP curve \varname{[output]} on a log
(dB) amplitude scale, mapping it to linear amplitude in the last step:

\begin{enumerate}
 \item  \varname{[i]} = 0
 \item  \varname{[$\omega$]} = $\pi$ * map element \varname{[i]} / \varname{[floor0\_bark\_map\_size]}
 \item if ( \varname{[floor0\_order]} is odd ) {
  \begin{enumerate}
   \item calculate \varname{[p]} and \varname{[q]} according to:
           \begin{eqnarray*}
             p & = & (1 - \cos^2\omega)\prod_{j=0}^{\frac{\mathtt{floor0\texttt{\_}order}-3}{2}} 4 (\cos([\mathtt{coefficients}]_{2j+1}) - \cos \omega)^2 \\
             q & = & \frac{1}{4} \prod_{j=0}^{\frac{\mathtt{floor0\texttt{\_}order}-1}{2}} 4 (\cos([\mathtt{coefficients}]_{2j}) - \cos \omega)^2
           \end{eqnarray*}

  \end{enumerate}
  } else \varname{[floor0\_order]} is even {
  \begin{enumerate}[resume]
   \item calculate \varname{[p]} and \varname{[q]} according to:
           \begin{eqnarray*}
             p & = & \frac{(1 - \cos\omega)}{2} \prod_{j=0}^{\frac{\mathtt{floor0\texttt{\_}order}-2}{2}} 4 (\cos([\mathtt{coefficients}]_{2j+1}) - \cos \omega)^2 \\
             q & = & \frac{(1 + \cos\omega)}{2} \prod_{j=0}^{\frac{\mathtt{floor0\texttt{\_}order}-2}{2}} 4 (\cos([\mathtt{coefficients}]_{2j}) - \cos \omega)^2
           \end{eqnarray*}

  \end{enumerate}
  }

 \item calculate \varname{[linear\_floor\_value]} according to:
         \begin{displaymath}
           \exp \left( .11512925 \left(\frac{\mathtt{amplitude} \cdot \mathtt{floor0\texttt{\_}amplitute\texttt{\_}offset}}{(2^{\mathtt{floor0\texttt{\_}amplitude\texttt{\_}bits}}-1)\sqrt{p+q}}
                  - \mathtt{floor0\texttt{\_}amplitude\texttt{\_}offset} \right) \right)
         \end{displaymath}

 \item \varname{[iteration\_condition]} = map element \varname{[i]}
 \item \varname{[output]} element \varname{[i]} = \varname{[linear\_floor\_value]}
 \item increment \varname{[i]}
 \item if ( map element \varname{[i]} is equal to \varname{[iteration\_condition]} ) continue at step 5
 \item if ( \varname{[i]} is less than \varname{[n]} ) continue at step 2
 \item done
\end{enumerate}

\paragraph{Errata 20150227: Bark scale computation}

Due to a typo when typesetting this version of the specification from the original HTML document, the Bark scale computation previously erroneously read:

    \begin{displaymath}
      \hbox{\sout{$
      \mathrm{bark}(x) = 13.1 \arctan (.00074x) + 2.24 \arctan (.0000000185x^2 + .0001x)
      $}}
    \end{displaymath}

Note that the last parenthesis is misplaced.  This document now uses the correct equation as it appeared in the original HTML spec document:

    \begin{displaymath}
      \mathrm{bark}(x) = 13.1 \arctan (.00074x) + 2.24 \arctan (.0000000185x^2) + .0001x
    \end{displaymath}


\subsection{Value functions for POMDPs}

max of linear terms?


\documentclass[UKenglish]{beamer}

\usepackage[utf8]{inputenx} % For æ, ø, å
\usepackage{babel}          % Automatic translations
\usepackage{csquotes}       % Quotation marks
\usepackage{microtype}      % Improved typography
\usepackage{amssymb}        % Mathematical symbols
\usepackage{mathtools}      % Mathematical symbols
\usepackage[absolute, overlay]{textpos} % Arbitrary placement
\setlength{\TPHorizModule}{\paperwidth} % Textpos units
\setlength{\TPVertModule}{\paperheight} % Textpos units
\usepackage{tikz}
\usetikzlibrary{overlay-beamer-styles}  % Overlay effects for TikZ

\usetheme{MathDept}

\author{ABDELRAHMAN ABDELLATİF}
\title{MÜŞTERİ ÖMÜR DEĞERİ PERFORMANS VE DOĞRULUK ANALİZİ}
%\subtitle{Usage of the theme \texttt{MathDept}}

\begin{document}

% Use
%
%     \begin{frame}[allowframebreaks]
%
% if the TOC does not fit one frame.
\begin{frame}
    \frametitle{içindekiler listesi}
    \tableofcontents[currentsection]
\end{frame}
\section{Tanıtma}
\begin{frame}
    \frametitle{Tanıtma}

     \begin{itemize}
        \item
        (Müşteri İlişkileri Yönetimi)CRM
       \item
        (Yaşam boyu müşteri değeri)CLV
        \item
        (Destek Vektör Makinesi)SVM
    \end{itemize}

    It is easy to match the \structure{colour theme}.
\end{frame}

\section{Mathematics}
\subsection{Theorem}

\begin{frame}
    \frametitle{Mathematics}

    \begin{theorem}[Fermat's little theorem]
        For a prime~\(\omega \in \widehat{G}\)
    \end{theorem}

    \begin{proof}
        The invertible elements in a field form a group under multiplication.
        In particular, the elements
        \begin{equation*}
            1, 2, \ldots, p - 1 \in \mathbb{Z}_p
        \end{equation*}
        form a group under multiplication modulo~\(p\).
        This is a group of order \(p - 1\).
        For \(a \in \mathbb{Z}_p\) and \(a \neq 0\) we thus get \(a^{p-1} = 1 \in \mathbb{Z}_p\).
        The claim follows.
    \end{proof}
\end{frame}

\subsection{Example}

\begin{frame}
    \frametitle{Mathematics}

    \begin{example}
        The function \(\phi \colon \mathbb{R} \to \mathbb{R}\) given by \(\phi(x) = 2x\) is continuous at the point \(x = \alpha\),
        because if \(\epsilon > 0\) and \(x \in \mathbb{R}\) is such that \(\lvert x - \alpha \rvert < \delta = \frac{\epsilon}{2}\),
        then
        \begin{equation*}
            \lvert \phi(x) - \phi(\alpha)\rvert = 2\lvert x - \alpha \rvert < 2\delta = \epsilon.
        \end{equation*}
    \end{example}
\end{frame}

\section{Highlighting}

\begin{frame}
    \frametitle{Highlighting}

    Some times it is useful to \alert{highlight} certain words in the text.

    \begin{alertblock}{Important message}
        If a lot of text should be \alert{highlighted}, it is a good idea to put it in a box.
    \end{alertblock}

    It is easy to match the \structure{colour theme}.
\end{frame}

\section{Lists}

\begin{frame}
    \frametitle{Lists}

    \begin{itemize}
        \item
        Bullet lists are marked with a grey box.
    \end{itemize}

    \begin{enumerate}
        \item
        Numbered lists are marked with a white number inside a grey box.
    \end{enumerate}

    \begin{description}
        \item[Description]
        highlights important words with grey text.
    \end{description}

    \begin{example}
        \begin{itemize}
            \item
            Lists change colour after the environment.
        \end{itemize}
    \end{example}
\end{frame}

\section{Effects}

\begin{frame}{Effects}
    \begin{columns}[onlytextwidth]
        \begin{column}{0.49\textwidth}
            \begin{enumerate}[<+-|alert@+>]
                \item
                Effects that control

                \item
                when text is displayed

                \item
                are specified with <> and a list of slides.
            \end{enumerate}

            \begin{theorem}<2>
                This theorem is only visible on slide number 2.
            \end{theorem}
        \end{column}
        \begin{column}{0.49\textwidth}
            Use \textbf<2->{textblock} for arbitrary placement of objects.

            \pause
            \medskip

            It creates a box
            with the specified width (here in a percentage of the slide's width)
            and upper left corner at the specified coordinate (x, y)
            (here x is a percentage of width and y a percentage of height).
        \end{column}
    \end{columns}

    \only<1, 3>
    {
        \begin{textblock}{0.3}(0.45, 0.55)
            \includegraphics[width = \textwidth]{images/MathDept-apollon}
        \end{textblock}
    }
\end{frame}

\section{References}

\begin{frame}[allowframebreaks]
    \frametitle{References}

    \begin{thebibliography}{}

        % Article is the default.
        \setbeamertemplate{bibliography item}[book]

        \bibitem{Hartshorne1977}
        R.~Hartshorne.
        \newblock \emph{Algebraic Geometry}.
        \newblock Springer-Verlag, 1977.

        \setbeamertemplate{bibliography item}[article]

        \bibitem{Artin1966}
        M.~Artin.
        \newblock On isolated rational singularities of surfaces.
        \newblock \emph{Amer. J. Math.}, 80(1):129--136, 1966.

        \setbeamertemplate{bibliography item}[online]

        \bibitem{Vakil2006}
        R.~Vakil.
        \newblock \emph{The moduli space of curves and Gromov--Witten theory}, 2006.
        \newblock \url{http://arxiv.org/abs/math/0602347}

        \setbeamertemplate{bibliography item}[triangle]

        \bibitem{AM1969}
        M.~Atiyah og I.~Macdonald.
        \newblock \emph{Introduction to commutative algebra}.
        \newblock Addison-Wesley Publishing Co., Reading, Mass.-London-Don
        Mills, Ont., 1969

        \setbeamertemplate{bibliography item}[text]

        \bibitem{Fraleigh1967}
        J.~Fraleigh.
        \newblock \emph{A first course in abstract algebra}.
        \newblock Addison-Wesley Publishing Co., Reading, Mass.-London-Don Mills, Ont., 1967

    \end{thebibliography}
\end{frame}

\end{document}