%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Problem Set/Assignment Template to be used by the
%% Food and Resource Economics Department - IFAS
%% University of Florida's graduates.
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Version 1.0 - November 2019
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Ariel Soto-Caro
%%  - asotocaro@ufl.edu
%%  - arielsotocaro@gmail.com
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\documentclass[12pt]{article}
\usepackage{design_ASC}
\usepackage{amsmath}% http://ctan.org/pkg/amsmath

\theoremstyle{definition}
\usepackage{longtable}
\newtheorem{exmp}{Example}[section]
\newtheorem{slo}{Definition}[section]
\newcommand*{\Perm}[2]{{}^{#1}\!P_{#2}}%
\newcommand*{\Comb}[2]{{}^{#1}C_{#2}}%
\setlength\parindent{0pt} %% Do not touch this
\usepackage{amsmath}% http://ctan.org/pkg/amsmath
%% -----------------------------
%% TITLE
%% -----------------------------
\title{\textbf{Selected Problems}} %% Assignment Title

\author{\textbf{Ibrahim Abou Elenein}}

\date{\today} %% Change "\today" by another date manually
%% -----------------------------
%% -----------------------------

%% %%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}
\setlength{\droptitle}{-5em}
%% %%%%%%%%%%%%%%%%%%%%%%%%%
\maketitle
% --------------------------
% Start here
% --------------------------
\section{Midterm  2017}
% %%%%%%%%%%%%%%%%%%%
\subsection{Problem 4 a}
\begin{exmp}
    From a deck of 52 cards, a 5-card hand is dealt. Find the number of
    hands containing exactly one pair without considering the variation
    of the suits?

    \subsubsection{Answer}
    \textbf{Without considering the suits}, my approach would be:

    The pair can be one of 13 numbers, i.e. we need to pick 1 out of 13 candidates.

    For the remaining 3 cards,3 cards with different numbers. In this case we need to pick 3 out of 12 candidates.
    \[
        \overbrace{\Comb{13}{1}}^{\text{number of ways to select one pair}}
        \times \underbrace{\Comb{12}{3}}_{\text{number of ways to select other 3 cards}}
    \]
\end{exmp}
\subsection{Problem 3 b}
\begin{exmp}
    In how many ways can we distribute 9 identical picses of candy
    to four children, if each child must get at least one piece?
    \subsubsection{Answer}
    The first four candies will be distributed to the children.
    Now we have 5 candies to be distributed to the childern
    Imagine 3 divisors (or blocks) we will use to group the candies,
    for each arrangement of the divisors and candies is a distribution.
    Now we have $8!$ arrangement but removing the duplicates for the
    candies $5!$ and $3!$ for the divisors
    \[
        \frac{8!}{5!.3!}
    \]
\end{exmp}
\section{Midterm 16}
\subsection{Problem 3 b}
\begin{exmp}
    Three cards are drawn from a standard deck and lined on a table.
    Find the probability that the first (leftmost) card is a queen
    , the seconed is a jack, and the third (rightmost) is not a club.
    \subsubsection{Answer}
    First of all proving that choosing one queen or jack is independent of
    choosing not club
    \[
        P(Q) = \frac{1}{13}; \ \ \ P(!C) = \frac{3}{4}
    \]
    \[
        P(!C \cap Q) = \frac{3}{52} = P(Q) \times P(!C)
    \]
So the Probability will be as follows
\[
    \underbrace{P(Q)}_{\text{Probability of choosing queen}}
    \times \underbrace{P(J|Q)}_{\text{Probability of choosing jack given queen}}
    \times \underbrace{P(!C)}_{\text{Probability of choosing not club}}
\]
\[
    \frac{1}{13}\   \ \ \ \ \  \ \ \ \ \ \ \ \ \ \times \ \ \ \ \ \ \ \ \ \  \ \ \ \
    \frac{3}{51} \ \ \ \ \ \ \ \ \ \  \ \ \ \ \times  \ \ \ \ \ \ \ \ \ \  \ \ \ \ \frac{3}{4}
\]

\end{exmp}
\end{document}


\section{Constant Generators and Specs}

Sketching extends a simple procedural language with the ability to leave \emph{holes} in place of code fragments that are to be derived by the synthesizer. Each hole is marked by a generator which defines the set of code fragments that can be used to fill a hole. \Sk{} offers a rich set of constructs to define generators, but all of these constructs can be described as syntactic sugar over a simple core language that contains only one kind of generator: an unknown integer constant denoted by the token \C{??}.

From the point of view of the programmer, the integer generator is a placeholder that the synthesizer must replace with a suitable integer constant. The synthesizer ensures that the resulting code will avoid any assertion failures under any input in the input space under consideration. For example, the following code snippet can be regarded as the ``Hello World'' of sketching.
\begin{lstlisting}
harness void main(int x){
   int y = x * ??;
   assert y == x + x;
}
\end{lstlisting}
This program illustrates the basic structure of a sketch. It contains three elements you are likely to find in every sketch: (i) a \C{harness} procedure, (ii) holes marked by generators, and (iii) assertions.

The harness procedure is the entry point of the sketch, and together with the assertion it serves as an operational specification for the desired program. The goal of the synthesizer is to derive an integer constant $C$ such that when \C{??} is replaced by $C$, the resulting program will satisfy the assertion for all inputs under consideration by the verifier. For the sketch above, the synthesized code will look like this.
\begin{lstlisting}
void main(int x){
   int y = x * 2;
   assert y == x + x;
}
\end{lstlisting}

\subsection{Harnesses and function equivalence requirement}
A program in sketch can have multiple harness functions each encoding different requirements of the problem. Sketch will guarantee that all harnesses will run to completion without triggering assertion failures for all inputs within bounds. Harness functions are not allowed to take heap allocated objects as inputs and all global variables are reset to their initial values before the evaluation of each harness. Because of this, the order of evaluation of the harnesses does not matter.

Sketch also allows the programmer to express that a function---we call it the implementation---must be functionally equivalent to another function---the specification---by writing \C{implements $fname$} at the end of the signature of the implementation function. When the specification and implementation do not access global variables, the equivalence constraint created by implements can be seen as syntactic sugar for a harness that calls both the implementation and the specification and compares their results. However, using \C{implements} is preferable to writing such a harness because it lets the compiler know that it can replace one function for the other when reasoning about the program. The implements directive imposes stronger constraints than harness; same function cannot have a \C{harness} and an \C{implements} directive.

If the implementation or the specification access global variables, then their equivalence must hold for all possible values of those global variables---not just for their initial values---and they must leave the global variables in the same state after they terminate. This is to ensure that replacing the specification with its implementation will always be semantics preserving. For this same reason, the spec and the sketch cannot access global variables that point to heap allocated values.

\begin{Example}
As a simple example of the use of harnesses and \C{implements}, consider the following sketch.
\begin{lstlisting}
int count=0;
int twox(int x, int y){
	++count;
	return x + x;
}

int expr1(int x, int y){
	return x*?? + y*??;
}
int expr2(int x, int y) implements twox{
	count = count+??;
	return x*?? + y*??;
}

harness void foo(){
	assert expr1(5,2)*expr2(2,4)== 24;
}
\end{lstlisting}
The harness imposes a constraint on the product of the two functions. The \C{implements} in the declaration of \C{expr2} imposes the additional constraint that \C{expr2} must be equivalent to \C{twox}. Because \C{twox} modifies the global variable \C{count}, \C{expr2} must modify the variable in the same way.

\end{Example}

\paragraph{Implementation note} As of the current \Sk{} release, there is a requirement that the specification should not have any unknowns. It is likely that this requirement will be relaxed in future releases. Also, when two functions are related by an \C{implements} directive, the compiler assumes that the specification is simpler than the implementation. The compiler exploits this by replacing every call to the implementation with a call to the specification during the analysis phase. This generally leads to big performance improvements for the solver, but it means that if the implementation calls itself recursively the system will not catch bugs that lead to infinite recursion.

\subsection{Assumptions}
Starting in \Sk{} 1.6.7, the compiler supports standard \C{assume} statements. The semantics of \C{assume $cond$;} dictate that when the condition $cond$ is false, execution stops and any subsequent assertions are ignored. When a function is called by another function, any assumptions in the callee become assertions from the point of view of the caller; \ie{} the caller must guarantee that the inputs and environment it passes to the callee satisfy the assumptions. \emph{Note that this is not true of generator functions (\secref{generators})}; as we will describe later, generators get inlined into their calling context, so any \C{assume} statement in the generator is an assume statement in the function that invokes the generator.

Also, when a function implements a specification, its assumptions must be weaker than those of the specification. In other words, any input that is legal for the specification must be legal for the implementation.

\begin{Example}{Assume and implements}
\begin{lstlisting}
harness int foo(int x){
	assume x > 10;
	int t= x-10;
	assert t > 0;
	return t;
}

int moo(int x) implements foo{
	assume x > 3;
	int t = x-??;
	assert t > 0;
	return t;
}

harness void main(int x){
	assume x > 5;
	int t = ??;
	moo(x+t);
	minimize(t);
}
\end{lstlisting}
In the example above, the harness \C{foo} assumes \C{x>10}, which allows it to satisfy the assertion \C{t>0}. In the case of \C{moo}, the unknown will resolve to \C{10} because of the constraint of equivalence with \C{foo}. Note that the assumption in \C{moo} is not strong enough to prove the assertion, but because \C{moo} implements \C{foo}, it inherits its preconditions.
\end{Example}

\subsection{Types for Constant Generators}
The constant hole \C{??} can actually stand for any of the following different types of constants:
\begin{itemize}
	\item Integers (\C{int})
	\item Booleans (\C{bit})
	\item Constant sized arrays and nested constant sized arrays
\end{itemize}

The system will use a simple form of type inference to determine the exact type of a given hole.

\subsection{Ranges for holes}
When searching for the value of a constant hole, the synthesizer will only search values greater than or equal to zero and less than $2^N$, where $N$ is a parameter given by the flag \C{--bnd-ctrlbits}. If you wan to be explicit about the number of bits for a given hole, you can state it as \C{??(N)}, where \C{N} is an integer constant.

\flagdoc{bnd-ctrlbits}{
The flag \C{bnd-ctrlbits} tells the synthesizer what range of values to consider for all integer holes. If one wants a given integer hole to span a different range of values, one can use the extended notation \C{??(N)}, where \C{N} is the number of bits to use for that hole.
}

\subsection{Minimizing Hole Values}
In many cases, it is useful to ask the synthesizer for the smallest constant that will satisfy a specification. For such cases, the synthesizer supports a function \C{minimize($e$)}, which asks the synthesizer to make $e$ as small as possible. More specifically, the synthesizer will find a minimal $bnd$ such that $e < bnd$ for all inputs. If the program includes multiple \C{minimize} statements, the synthesizer will find a locally minimal set of bounds such that there is no other set of bounds that is strictly better than the one found.

\flagdoc{bnd-mbits}{
The flag \C{bnd-mbits} tells the synthesizer how many bits to use to represent all bounds introduced by \C{minimize(e)}(default 5). Note that the largest value of \C{(e)} will be less than the bound, so if \C{e} can have value $n$, the bound needs enough bits to be able to reach $n+1$.
}

\begin{Example}
For example, consider the following simple program:

\begin{lstlisting}
harness void main(int i, int j){
	int i_orig=i, j_orig=j;
	if(i > ??){ // we'll call this unknown u1
		i = ??; // u2
	}
	if(j > ??){ // u3
		j = ??; // u4
	}
	if(i_orig > 3 && j_orig > 3)
    	   assert 2*i + j > 6;
	minimize(i);
	minimize(j);
}
\end{lstlisting}
In the program above, synthesizer will try to minimize the upper bound on \C{i} (we'll call it $b_i$) and the upper bound on j ($b_j$). One possible solution is to have $u1=3$, $u2=4$, $u3=0$, $u4=0$. This will allow the upper bounds $(b_1, b_2)$ to be $(5,1)$. A different possible solution is to have $u1=0$, $u2=0$, $u3=0$, $u4=7$, which will allow the upper bounds to be $(1, 8)$. While the first set of bounds appears better than the second, they are actually incomparable. By contrast, a solution that had $(b_1, b_2)=(6,1)$ would not be allowed because the solution with bounds $(5,1)$ is strictly better.
\end{Example}

The synthesizer has some syntactic sugar on top of \C{minimize} to support the synthesis of a minimal number of statements, a common idiom in \Sk{}. For example, the code below will produce the minimal number of assignments required to swap \C{x} and \C{y}.
\begin{lstlisting}
void swap(ref bit[W] x, ref bit[W] y){
    minrepeat{
        if(??){ x = x ^ y;}else{ y = x ^ y; }
    }
}

harness void main(bit[W] x, bit[W] y){
    bit[W] tx = x; bit[W] ty = y;
    swap(x, y);
    assert x==ty && y == tx;
}
\end{lstlisting}

\section{Generator functions}
\seclabel{generators}
A generator describes a space of possible code fragments that can be used to fill a hole. The constant generator we have seen so far corresponds to the simplest such space of code fragments: the space of integers in a particular range. More complex generators can be created by composing simple generators into \emph{generator functions}.

As a simple example, consider the problem of specifying the set of linear functions of two parameters \C{x} and \C{y}. That space of functions can be described with the following simple generator function:
\begin{lstlisting}
generator int legen(int i, int j){
   return ??*i + ??*j+??;
}
\end{lstlisting}

The generator function can be used anywhere in the code in the same way a function would, but the semantics of generators are different from functions. In particular, every call to the generator will be replaced by a concrete piece of code in the space of code fragments defined by the generator. Different calls to the generator function can produce different code fragments. For example, consider the following use of the generator.

\begin{lstlisting}
harness void main(int x, int y){

  assert legen(x, y) == 2*x + 3;
  assert legen(x,y) == 3*x + 2*y;

}
\end{lstlisting}

Calling the solver on the above code produces the following output
\begin{lstlisting}
void _main (int x, int y){
  assert ((((2 * x) + (0 * y)) + 3) == ((2 * x) + 3));
  assert (((3 * x) + (2 * y)) == ((3 * x) + (2 * y)));
}
\end{lstlisting}

Note that each invocation of the generator function was replaced by a concrete code fragment in the space of code fragments defined by the generator.

The behavior of generator functions is very different from standard functions. If a standard function has generators inside it, those generators are resolved to produce code that will behave correctly in all the calling contexts of the function as illustrated by the example below.
\begin{lstlisting}
int linexp(int x, int y){
   return ??*x + ??*y + ??;
}
harness void main(int x, int y){
   assert linexp(x,y) >= 2*x + y;
   assert linexp(x,y) <= 2*x + y+2;
}
\end{lstlisting}
For the routines above, there are many different solutions for the holes in \C{linexp} that will satisfy the first assertion, and there are many that will satisfy the second assertion, but the synthesizer will chose one of the candidates that satisfy them both and produce the code shown below. Note that the compiler always replaces return values for reference parameters, but other than that, the code below is what you would expect.
\begin{lstlisting}
void linexp (int x, int y, ref int _out){
  _out = 0;
  _out = (2 * x) + (1 * y);
  return;
}
void _main (int x, int y){
  int _out = 0;
  linexp(x, y, _out);
  assert (_out >= ((2 * x) + y));
  int _out_0 = 0;
  linexp(x, y, _out_0);
  assert (_out_0 <= (((2 * x) + y) + 2));
}
\end{lstlisting}

\subsection{Recursive Generator Functions}

Generators derive much of their expressive power from their ability to recursively define a space of expressions. For example, the code below shows how to use a recursive generator to define a context free grammar of possible expressions.

\begin{Example}{Recursive Generator}
\begin{lstlisting}
generator int rec(int x, int y, int z){
   int t = ??;
   if(t == 0){return x;}
   if(t == 1){return y;}
   if(t == 2){return z;}

   int a = rec(x,y,z);
   int b = rec(x,y,z);

   if(t == 3){return a * b;}
   if(t == 4){return a + b;}
   if(t == 5){return a - b;}
}
harness void sketch( int x, int y, int z ){
   assert rec(x,y, z) == (x + x) * (y - z);
}
\end{lstlisting}
\end{Example}

One must be careful when defining recursive generators, however, because the way the generator is defined can have a dramatic impact on the solution time of the resulting code. In particular, there are two aspects that the writer must keep in mind when writing a generator: recursion and symmetries.

\paragraph{Recursion control in generators}
The compiler handles recursive generators by inlining them number of times as guided by the \C{bnd-inline-amnt} flag. This simple approach can cause problems if recursive generators are not written carefully. For example, an alternative way of writing the generator above is shown below.

\begin{Example}{Inefficient recursive generator}
\begin{lstlisting}
generator int rec(int x, int y, int z){
   int t = ??;
   if(t == 0){return x;}
   if(t == 1){return y;}
   if(t == 2){return z;}
   if(t == 3){return rec(x,y,z) * rec(x,y,z);}
   if(t == 4){return rec(x,y,z) + rec(x,y,z);}
   if(t == 5){return rec(x,y,z) - rec(x,y,z);}
}
harness void sketch( int x, int y, int z ){
   assert rec(x,y, z) == (x + x) * (y - z);
}
\end{lstlisting}
\end{Example}
Both generators describe the same grammar, and therefore in principle the same space of possible expressions, but the second generator will cause problems because each recursive call to \C{rec} will be inlined independently, so each level of inlining will increase the size of the program by a factor of six, instead of only a factor of two.

Another potential issue with recursive generators is that the amount of inlining is controlled by the same flag used to control inlining of functions during analysis. This can be problematic because recursive functions in the program will often require much more inlining than generators. To address this problem, the user can take additional control over inlining by explicitly adding a bound parameter into the generator as shown below.

\begin{Example}{Generator with manual inlining control}
\begin{lstlisting}
generator int rec(int x, int y, int z, int bnd){
   assert bnd >= 0;
   int t = ??;
   if(t == 0){return x;}
   if(t == 1){return y;}
   if(t == 2){return z;}

   int a = rec(x,y,z, bnd-1);
   int b = rec(x,y,z, bnd-1);
   ...
}
\end{lstlisting}
\end{Example}

The synthesizer performs partial evaluation in tandem with inlining, so if we call rec with a constant value for the \C{bnd} parameter, the synthesizer will stop inlining when it determines that this parameter will be less than zero.

\paragraph{Avoiding symmetries}
Another aspect to be careful with when defining recursive generators are symmetries. These happen when different assignments to unknown values can result in the exact same expression. An important source of symmetries are commutative and associative operations. For example, consider two generators shown below.

\begin{Example}{Effect of symmetries on generators}
\begin{lstlisting}
generator int sum(int x, int y, int z, int bnd){
    assert bnd > 0;
   generator int factor(){
       return {| x | y | z|} * {| x | y | z | ?? |};
   }
   if(??){ return factor(); }
   else{return sum(x,y,z, bnd-1) + sum(x,y,z, bnd-1);}
}

generator int sumB(int x, int y, int z, int bnd){
    assert bnd > 0;
    generator int factor(){
        return {| x | y | z|} * {| x | y | z | ?? |};
    }
    if(??){ return factor(); }
    else{ return factor() + sumB(x,y,z, bnd-1);}
 }
\end{lstlisting}
\end{Example}

Both represent the same space of expressions, but the generator \C{sumB} forces a right-associativity on the expression, whereas the generator \C{sum} can produce all possible associations, making the generator \C{sumB} more efficient than \C{sum}. Additionally, in \C{sumB} the \C{bnd} parameter has a clear meaning: it is the number of terms in the sum, whereas in generator \C{sum}, the parameter \C{bnd} is the depth of the AST, which is not as straightforward to map to something meaningful to the programmer.

\subsection{Regular Expression Generators}

Sketch provides some shorthand to make it easy to express simple sets of expressions. This shorthand is based on regular expressions. Regular expression generators describe to the synthesizer a set of choices from which to choose in searching for a correct solution to the sketch. The basic syntax is
\begin{lstlisting}
{| regexp |}
\end{lstlisting}

Where the regexp can use the operator | to describe choices, and the operator ? to define optional subexpressions.

For example, the sketch from the previous subsections can be made more succinct by using the regular expression shorthand.

\begin{lstlisting}
generator int rec(int x, int y, int z){
    if(??){
        return {| x | y | z |};
    }else{
        return {| rec(x,y,z) (+ | - | *) rec(x,y,z)  |};
    }
}

harness void sketch( int x, int y, int z ){
   assert rec(x,y, z) == (x + x) * (y - z);
}
\end{lstlisting}

Regular expression holes can also be used with pointer expressions. For example, suppose you want to create a method to push a value into a stack, represented as a linked list. You could sketch the method with the following code:

\begin{lstlisting}
push(Stack s, int val){
  Node n = new Node();
  n.val = val;
  {|  (s.head | n)(.next)? |} =   {|  (s.head | n)(.next)? |};
  {|  (s.head | n)(.next)? |} =   {|  (s.head | n)(.next)? |};
}
\end{lstlisting}

\subsection{Local Variables Construct}\seclabel{localvariablesconstruct}

Sketch supports the use of the \C{$\$$(type)} construct to instruct the synthesizer to consider all variables of the specified \C{type} within scope when searching for a solution.

\begin{lstlisting}
harness void main(int x) {
    int a = 2;
    double b = 2.3;

    assert x * $\$$(int) == x + x; $//$ $\$$(int) === {| 0  |  a  |  x |}
}
\end{lstlisting}

The value of \textit{type} can be any of the primitive types (see \secref{primitives}) or any user defined type. The default value of any primitive type will also be considered as one of the choices. Local variables inside a function and its formal parameters are considered within scope of the construct. If the construct is used inside a local function, the local variables and formal parameters of the functions where it is defined are also within scope of the construct.

\subsection{High order generators}\seclabel{high-ordergenerators}

Generators can take other generators as parameters, and they can be passed as parameters to either generators or functions. This can be very useful in defining very flexible classes of generators. For example, the generator rec above assumes that you want expressions involving three integer variables, but in some cases you may only want two variables, or you may want five variables. The following code describes a more flexible generator:

\begin{lstlisting}
generator int rec(fun choices){
    if(??){
        return choices();
    }else{
        return {| rec(choices) (+ | - | *) rec(choices)  |};
    }
}
\end{lstlisting}

We can use this generator in the context of the previous example as follows:
\begin{lstlisting}
harness void sketch( int x, int y, int z ){
   generator int F(){
	return {| x | y | z |};
   }
   assert rec(F) == (x + x) * (y - z);
}
\end{lstlisting}

In a different context, we may want an expression involving some very specific sub-expressions, but the same generator can be reused in the new context.
\begin{lstlisting}
harness void sketch( int N, int[N] A, int x, int y ){
   generator int F(){
	return {| A[x] | x | y |};
   }
   if(x<N){
	   assert rec(F) == (A[x]+y)*x;
   }
}
\end{lstlisting}

High order generators can also be used to describe patterns in the expected structure of the desired code. For example, if we believe the resulting code will have a repeating structure, we can express this with the following high-order generator:

\begin{lstlisting}
generator void rep(int n, fun f){
    if(n>0){
        f();
        rep(n-1, f);
    }
}
\end{lstlisting}

\subsection{\C{repeat} construct}
The pattern illustrated by the \C{rep} generator above---where the user wants to generate multiple statements, all of which can be generated from the same code with holes---is quite common. Sketch includes a repeat construct to do exactly this:
\begin{lstlisting}
repeat($N$){
     $stmt$
}
\end{lstlisting}
This construct is just syntactic sugar for the recursive $rep$ generator shown earlier. A big difference between using \C{repeat} and writing your own \C{rep} generator is that with repeat, the maximum number of repetitions will be dictated by the loop unrolling bound \C{bnd-unroll-amnt}, whereas if you write your own recursive generator, the maximum number of repetitions will be dictated by the inlining bound \C{bnd-inline-amnt}. Also note that if $N$ is not a constant or a constant hole, the result of using this construct will be a set of nested if statements.

There is also a convenient variant of this construct:
\begin{lstlisting}
repeat($i$ : $N$){
     $stmt$
}
\end{lstlisting}
Where $i$ is a fresh variable name, which will automatically be declared as an integer and can be used within $stmt$ to keep track of which copy you are in. The variable will have the value $n$ in the $n^{th}$ copy of $stmt$. As an example of how this may be used, consider the following code:

\begin{lstlisting}

  generator int add([int n, int k], int[n] A, int idx, int[k] offst){
    int res = 0;
    repeat(i: k){
         res += A[idx + offst[i]];
    }
    return res;
  }

  int[n] combine([int n], int[n] A){
         int[n] B;
         for(int i=1; i<n-1; ++i){
              int[3] offsts = {??-1, ??-1, ??-1}; //The -1 are necessary because ?? can only take positive values.
               B[i] = add(A, i, offsts);
         }
         return B;
  }

  harness void main(){
       assert combine({2, 4, 5}) == {0, 11, 0};
  }

\end{lstlisting}

Note that in the sketch above, the \C{-1} in the definition of offsts is necessary because constant holes \C{??} can only take non-negative values.
Given the harness, the combine function above will be synthed into the code below.

\begin{lstlisting}

void combine (int n, int[n] A, ref int[n] _out)
{
  _out = ((int[n])0);
  for(int i = 1; i < (n - 1); i = i + 1)
  {
    int _out_s3 = A[i];
    _out_s3 = _out_s3 + (A[i + -1]);
    _out_s3 = _out_s3 + (A[i + 1]);
    _out[i] = _out_s3;
  }
  return;
}

\end{lstlisting}

Note how the repeat is expanded into three separate statements that read from \C{A} and add the result to the output variable. The compiler is able to tell that the first one is adding to zero, so it simplifies it and folds it into the declaration of the variable.


\section{\module{operator} ---
         Standard operators as functions.}
\declaremodule{builtin}{operator}
\sectionauthor{Skip Montanaro}{skip@automatrix.com}

\modulesynopsis{All Python's standard operators as built-in functions.}

The \module{operator} module exports a set of functions implemented in C
corresponding to the intrinsic operators of Python.  For example,
\code{operator.add(x, y)} is equivalent to the expression \code{x+y}.  The
function names are those used for special class methods; variants without
leading and trailing \samp{__} are also provided for convenience.

The \module{operator} module defines the following functions:

\begin{funcdesc}{add}{a, b}
\funcline{__add__}{a, b}
Return \var{a} \code{+} \var{b}, for \var{a} and \var{b} numbers.
\end{funcdesc}

\begin{funcdesc}{sub}{a, b}
\funcline{__sub__}{a, b}
Return \var{a} \code{-} \var{b}.
\end{funcdesc}

\begin{funcdesc}{mul}{a, b}
\funcline{__mul__}{a, b}
Return \var{a} \code{*} \var{b}, for \var{a} and \var{b} numbers.
\end{funcdesc}

\begin{funcdesc}{div}{a, b}
\funcline{__div__}{a, b}
Return \var{a} \code{/} \var{b}.
\end{funcdesc}

\begin{funcdesc}{mod}{a, b}
\funcline{__mod__}{a, b}
Return \var{a} \code{\%} \var{b}.
\end{funcdesc}

\begin{funcdesc}{neg}{o}
\funcline{__neg__}{o}
Return \var{o} negated.
\end{funcdesc}

\begin{funcdesc}{pos}{o}
\funcline{__pos__}{o}
Return \var{o} positive.
\end{funcdesc}

\begin{funcdesc}{abs}{o}
\funcline{__abs__}{o}
Return the absolute value of \var{o}.
\end{funcdesc}

\begin{funcdesc}{inv}{o}
\funcline{__inv__}{o}
\funcline{__invert__}{o}
Return the inverse of \var{o}.  The names \function{invert()} and
\function{__invert__()} were added in Python 2.0.
\end{funcdesc}

\begin{funcdesc}{lshift}{a, b}
\funcline{__lshift__}{a, b}
Return \var{a} shifted left by \var{b}.
\end{funcdesc}

\begin{funcdesc}{rshift}{a, b}
\funcline{__rshift__}{a, b}
Return \var{a} shifted right by \var{b}.
\end{funcdesc}

\begin{funcdesc}{and_}{a, b}
\funcline{__and__}{a, b}
Return the bitwise and of \var{a} and \var{b}.
\end{funcdesc}

\begin{funcdesc}{or_}{a, b}
\funcline{__or__}{a, b}
Return the bitwise or of \var{a} and \var{b}.
\end{funcdesc}

\begin{funcdesc}{xor}{a, b}
\funcline{__xor__}{a, b}
Return the bitwise exclusive or of \var{a} and \var{b}.
\end{funcdesc}

\begin{funcdesc}{not_}{o}
\funcline{__not__}{o}
Return the outcome of \keyword{not} \var{o}.  (Note that there is no
\method{__not__()} method for object instances; only the interpreter
core defines this operation.)
\end{funcdesc}

\begin{funcdesc}{truth}{o}
Return \code{1} if \var{o} is true, and 0 otherwise.
\end{funcdesc}

\begin{funcdesc}{concat}{a, b}
\funcline{__concat__}{a, b}
Return \var{a} \code{+} \var{b} for \var{a} and \var{b} sequences.
\end{funcdesc}

\begin{funcdesc}{repeat}{a, b}
\funcline{__repeat__}{a, b}
Return \var{a} \code{*} \var{b} where \var{a} is a sequence and
\var{b} is an integer.
\end{funcdesc}

\begin{funcdesc}{contains}{a, b}
\funcline{__contains__}{a, b}
Return the outcome of the test \var{b} \code{in} \var{a}.
Note the reversed operands.  The name \function{__contains__()} was
added in Python 2.0.
\end{funcdesc}

\begin{funcdesc}{sequenceIncludes}{\unspecified}
\deprecated{2.0}{Use \function{contains()} instead.}
Alias for \function{contains()}.
\end{funcdesc}

\begin{funcdesc}{countOf}{a, b}
Return the number of occurrences of \var{b} in \var{a}.
\end{funcdesc}

\begin{funcdesc}{indexOf}{a, b}
Return the index of the first of occurrence of \var{b} in \var{a}.
\end{funcdesc}

\begin{funcdesc}{getitem}{a, b}
\funcline{__getitem__}{a, b}
Return the value of \var{a} at index \var{b}.
\end{funcdesc}

\begin{funcdesc}{setitem}{a, b, c}
\funcline{__setitem__}{a, b, c}
Set the value of \var{a} at index \var{b} to \var{c}.
\end{funcdesc}

\begin{funcdesc}{delitem}{a, b}
\funcline{__delitem__}{a, b}
Remove the value of \var{a} at index \var{b}.
\end{funcdesc}

\begin{funcdesc}{getslice}{a, b, c}
\funcline{__getslice__}{a, b, c}
Return the slice of \var{a} from index \var{b} to index \var{c}\code{-1}.
\end{funcdesc}

\begin{funcdesc}{setslice}{a, b, c, v}
\funcline{__setslice__}{a, b, c, v}
Set the slice of \var{a} from index \var{b} to index \var{c}\code{-1} to the
sequence \var{v}.
\end{funcdesc}

\begin{funcdesc}{delslice}{a, b, c}
\funcline{__delslice__}{a, b, c}
Delete the slice of \var{a} from index \var{b} to index \var{c}\code{-1}.
\end{funcdesc}

The \module{operator} also defines a few predicates to test the type
of objects.  \strong{Note:}  Be careful not to misinterpret the
results of these functions; only \function{isCallable()} has any
measure of reliability with instance objects.  For example:

\begin{verbatim}
>>> class C:
...     pass
...
>>> import operator
>>> o = C()
>>> operator.isMappingType(o)
1
\end{verbatim}

\begin{funcdesc}{isCallable}{o}
\deprecated{2.0}{Use the \function{callable()} built-in function instead.}
Returns true if the object \var{o} can be called like a function,
otherwise it returns false.  True is returned for functions, bound and
unbound methods, class objects, and instance objects which support the
\method{__call__()} method.
\end{funcdesc}

\begin{funcdesc}{isMappingType}{o}
Returns true if the object \var{o} supports the mapping interface.
This is true for dictionaries and all instance objects.
\strong{Warning:} There is no reliable way to test if an instance
supports the complete mapping protocol since the interface itself is
ill-defined.  This makes this test less useful than it otherwise might
be.
\end{funcdesc}

\begin{funcdesc}{isNumberType}{o}
Returns true if the object \var{o} represents a number.  This is true
for all numeric types implemented in C, and for all instance objects.
\strong{Warning:}  There is no reliable way to test if an instance
supports the complete numeric interface since the interface itself is
ill-defined.  This makes this test less useful than it otherwise might
be.
\end{funcdesc}

\begin{funcdesc}{isSequenceType}{o}
Returns true if the object \var{o} supports the sequence protocol.
This returns true for all objects which define sequence methods in C,
and for all instance objects.  \strong{Warning:} There is no reliable
way to test if an instance supports the complete sequence interface
since the interface itself is ill-defined.  This makes this test less
useful than it otherwise might be.
\end{funcdesc}

Example: Build a dictionary that maps the ordinals from \code{0} to
\code{256} to their character equivalents.

\begin{verbatim}
>>> import operator
>>> d = {}
>>> keys = range(256)
>>> vals = map(chr, keys)
>>> map(operator.setitem, [d]*len(keys), keys, vals)
\end{verbatim}


%  vim: set spell :
\documentclass[fleqn]{article}

\usepackage{acro}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{amssymb}
\usepackage{enumerate}
\usepackage[margin=1in]{geometry}
\usepackage{mathtools}
\usepackage{natbib}
\usepackage{siunitx}
\usepackage{graphicx}
\usepackage{slashbox}
\usepackage{listings}
\usepackage{xspace}
\usepackage[all]{xy}
\usepackage{tikz-cd}

% Typeface
\usepackage{tgpagella}
\usepackage[T1]{fontenc}
\usepackage{mathpazo}
\linespread{1.05}

\include{macros}

\usepackage{color}
\definecolor{my-blue}{RGB}{1,49,94}
\usepackage{hyperref}
\hypersetup{
  colorlinks=true,
  citecolor=my-blue,
  linkcolor=my-blue,
}

\DeclareAcronym{HoTT}{ short = HoTT, long = homotopy type theory }
\defcitealias{UFP2013}{UFP, 2013}

\newcommand{\card}{\mathsf{card}}
\newcommand{\gf}[1]{\abs{#1}\!(z)}
\newcommand{\fin}{\mathsf{Fin}}
\newcommand{\finset}{\mathsf{FinSet}}
\newcommand{\isfinset}{\mathsf{isFinSet}}
\newcommand{\isfinseq}{\mathsf{isFinSeq}}
\newcommand{\abs}[1]{\left\lvert #1 \right\rvert}
\newcommand{\Aut}{\mathrm{Aut}}
\newcommand{\sslash}{/\!\!/}
\newcommand{\inner}[2]{\langle #1, #2 \rangle}
\DeclareMathOperator{\SINH}{SINH}
\DeclareMathOperator{\COSH}{COSH}

\theoremstyle{theorem}
\newtheorem{thm}{Theorem}

\theoremstyle{definition}
\newtheorem{claim}{Claim}[section]
\newtheorem{defn}{Definition}[section]
\newtheorem{remark}{Remark}[section]
\newtheorem{example}{Example}[section]

\title{Species in HoTT}
\author{John Dougherty}
\begin{document}
\maketitle

\begin{abstract}
Combinatorial species were developed by \citet{Joyal1981} as an abstract
treatment of enumerative combinatorics, especially problems of counting the
number of ways of putting some structure on a finite set.  Many of the results
of species theory are special cases of more general properties of
homotopy types, making \ac{HoTT} a useful tool for dealing with species.  These tools become even more apposite when one generalizes
species to higher groupoids, as \citet{Baez2001} do.
What follows are notes I wrote while learning about species.  They're mainly
summary of the notes Derek Wise took during John Baez's ``Quantization and
Categorification'' seminar in AY2004~\citep{Baez2003,Baez2004a,Baez2004b}, with
some reference to \citet{Bergeron2013}, \citet{Baez2001}, and
\citet{Aguiar2010}.
\end{abstract}

\section{Defining species}

As originally defined by \citet{Joyal1981}, a species is an endofunctor of the
groupoid $\finset$ of finite sets and bijections between them.
\citet{Baez2001} generalized species to stuff types, which are functors $F : X
\to \finset$ for any groupoid $X$.  This formulation admits a natural
generalization to $\infty$-species, or homotopical species, by replacing the
groupoid $X$ with an $\infty$-groupoid---in other words, by working with
homotopy types.  So we can formulate species in \ac{HoTT} as follows.

\begin{defn}
  The canonical finite type with $n$ elements is defined by induction on
  $\mathbb{N}$ by
  \begin{align*}
    \fin(0) &\defeq \emptyt \\
    \fin(\suc(n)) &\defeq \fin(n) + \unit
  \end{align*}
\end{defn}
\begin{defn}
  The type of finite sets is
  \[
    \finset \defeq
    \sm{A : \UU}{n : \mathbb{N}} \merely{A = \fin(n)}
  \]
\end{defn}
\begin{defn}
  A species is a type $X : \UU$ equipped with a function $f : X \to \finset$.
\end{defn}

The definition of $\fin$ won't be unfolded, so you can use your favorite.  Its
role is to provide a standard set with $n$ elements, allowing us to define a
predicate $\isfinset$ such that $\finset \defeq \{A : \UU \mid \isfinset(A)\}$.
Since $\isfinset$ is a family of mere propositions, we'll often ignore it and
abusively write $A$ for both a term of type $\finset$ and its first component,
which is of type $\UU$, eliding reference to the inhabitant of $\isfinset(A)$.

Now, the intended interpretation of a species $f : X \to \finset$ is that for
some finite set $A$, an element of $\hfib{f}{A}$ is a way of equipping $A$ with
``$f$-stuff''.  This gives us a natural way to come up with examples of
species.  For some type family $\Phi : \finset \to \UU$, there is a
corresponding species $\fst : \sm{A : \finset}\Phi(A) \to \finset$.  By Lemma
4.8.2 of the \ac{HoTT} Book \citepalias{UFP2013}, any species is equal to one
of this form.  So we can specify a species up to equality by giving a family
$\Phi : \finset \to \UU$ and taking the first projection to be the map.

All of this is just setup for the main application of species: generating
functions.  Given a species $X$, we want to cook up a formal power series
\[
  \gf{X}
  =
  \sum_{n\geq0} X_{n}\, z^{n}
\]
where $X_{n} : [0, \infty)$.  Intuitively, $X_{n}$ should represent the
``number of ways of putting $X$ stuff on an $n$-element set''.  For a species
$f : X \to \finset$, this description picks out something like the cardinality
of $\hfib{f}{A}$, where $A$ is an $n$-element set.  There are two problems with
this: (i) we need a notion of cardinality, and (ii) we need some way to pick an
$A$ from all of the $n$-element sets.  To solve the first problem we use
groupoid cardinality $\abs{X}$ of $X$.

\begin{defn}
  For any $X : \UU$, if $\merely{X = \fin(n)}$ for some $n : \mathbb{N}$, then
  $\abs{X} = n$.
\end{defn}

\begin{defn}
  The groupoid cardinality $\abs{X}$ of a type $X$ is, if it converges, the sum
  \[
    \abs{X}
    = \sum_{[x] \in \pi_{0}(X)}\prod_{k\geq1}
        \abs{\pi_{k}(X, x)}^{(-1)^{k}}
    = \sum_{[x] \in \pi_{0}(X)}
        \frac{1}{\abs{\pi_{1}(X, x)}}\abs{\pi_{2}(X, x)}
        \frac{1}{\abs{\pi_{3}(X, x)}}\abs{\pi_{4}(X, x)}
        \dotsm
  \]
\end{defn}

\noindent
Via the homotopy hypothesis, this is equivalently the Euler characteristic of
a topological space presenting the type $X$.

This solves the problem of finding some notion of cardinality.  To solve
problem (ii), we avoid an arbitrary choice of $A$ by decategorifying and
regarding $f : X \to \finset$ as a fibration over $\mathbb{N}$, rather than
$\finset$.  Specifically, we consider the sequence
\[ \begin{tikzcd}
    X \ar[r, "f"] &
    \finset \ar[r, "\tproj{0}{\blank}"] \ar[rr, bend right, "\card"] &
    \trunc{0}{\finset} \ar[r, "\mathsf{ext}(\card)"] &
    \mathbb{N}
\end{tikzcd}  \]
where $\card \defeq \fst \circ \snd$, given our definition of $\finset$, and
$\mathsf{ext}$ is the extension along $\tproj{0}{\blank}$, the $0$-truncation
map.  The reason this counts as decategorification is that we're squashing
$\finset$ into a set, meaning that we're identifying all of the equinumerous
sets.  This produces a type $\eqv{\trunc{0}{\finset}}{\mathbb{N}}$.  So,
finally, we have the
\begin{defn}
  The generating function $\gf{X}$ of a species $f : X \to \finset$ is given by
  \[
    \gf{X}
    =
    \sum_{n\geq0}
    \abs{\hfib{\card \circ f}{n}}\,
    z^{n}
    =
    \sum_{n\geq0}
    X_{n}\, z^{n}
  \]
  where this expression defines $X_{n}$.
\end{defn}
\noindent
We'll variously write $\gf{f}$, $\gf{X}$, or $\gf{\Phi}$, as appropriate, for
species $f : X \to \finset$ or $\Phi : \finset \to \UU$.

\section{Computing cardinalities}

There are two kinds of results that simplify the computation of generating
functions.  First, one can compute the cardinality of composite types in terms
of the cardinalities of their components.  Second, the definition of the
generating function can be simplified to eliminate reference to $\card$.  I'm
going to be a bit sloppy about the scope of this section's discussion.
Everything works for essentially finite 1-types, which are going to be the ones
I'm mainly dealing with.

Four properties of the groupoid cardinality follow from the definition above.
In fact, these four axiomatically characterize the groupoid cardinality:

\begin{claim}
  $\abs{\unit} = 1$.
\end{claim}

\begin{claim}
  If $\merely{\eqv{X}{Y}}$, then $\abs{X} = \abs{Y}$.
\end{claim}

\begin{claim}\label{claim:gc_sum}
  $\abs{X + Y} = \abs{X} + \abs{Y}$
\end{claim}

\begin{claim}\label{claim:gc_fibration}
  If there is a map $f : X \to Y$ and $\lvert{\hfib{f}{y}}\rvert =
  \lvert{\hfib{f}{y'}}\rvert$
  for all $y, y' : Y$, then $\abs{X} = \lvert\hfib{f}{y}\rvert \cdot \abs{Y}$
  for any $y : Y$.
\end{claim}

\noindent
The first three of these are immediate.  The fourth follows from the homotopy
hypothesis.  If $p : A \to B$ is a fibration with fiber $F$ and $B$ is
path-connected, then the Euler characteristic $\chi(E)$ of $E$ is equal to
$\chi(F) \cdot \chi(B)$.  Since any function is equivalent to a fibration, for
any two points $y, y'$ connected by a path we have $\hfib{f}{y} \eqvsym
\hfib{f}{y'}$, translating this result into groupoid-speak and then into
\ac{HoTT}, then summing over the connected components gives
Claim~\ref{claim:gc_fibration}.

Similar properties for $\Sigma$-types and products follow from these axioms.
For $\Sigma$-types we have the
\begin{claim}
  For any type $X$ and family $P : X \to \UU$, if $\abs{P(x)} = \abs{P(x')}$
  for all $x, x' : X$ then
  \[
    \abs{\sm{y:X}P(y)}
    =
    \abs{P(x)} \cdot \abs{X}
  \]
  for any $x : X$.
\end{claim}
\noindent
This is a combination of the sum and fibration claims \ref{claim:gc_sum} and
\ref{claim:gc_fibration}.  If $X$ is $0$-connected, then we automatically get
$\prd{x, x' : X}(\eqv{P(x)}{P(x')})$ by transport.  If, more generally, $X$ is
essentially finite, then the further hypothesis is required.  For products, we
have the following
\begin{claim}
  The cardinality of the product $X \times Y$ is
  \[
    \abs{X \times Y} = \abs{X} \cdot \abs{Y}
  \]
\end{claim}
\noindent
which follows from the definition $X \times Y \defeq \sm{x:X}Y$ and the
property for $\Sigma$-types.

Now consider the definition of the generating function of some $f : X \to
\finset$.  Note first that, because $\card(\fin(n)) \equiv n$, we can write
\[
  \abs{\hfib{\card \circ f}{n}}
  \equiv
  \abs{\hfib{\card \circ f}{\card(\fin(n))}}
  =
  \abs{\sm{w : \hfib{\card}{\card(\fin(n))}}\hfib{f}{\fst{w}}}
  =
  \abs{\sm{w : \sm{A : \UU}\merely{A = \fin(n)}}\hfib{f}{\fst{w}}}
\]
by Exercise 4.4 of the \ac{HoTT} Book.  Since the type of $w$ is 0-connected,
we can replace $\fst(w)$ with $\fin(n)$:
\[
  X_{n} =
  \abs{\sm{w : \sm{A : \UU}\merely{A = \fin(n)}}\hfib{f}{\fin(n)}}
\]
so we can always calculate $X_{n}$ using the fiber of $f$ over $\fin(n)$.

This expression can be simplified further by considering the type $\sm{A :
  \UU}\merely{A = \fin(n)}$.  This is our representative of the type of
$n$-element sets, but it has a number of other descriptions.  In particular, it
is the delooping of the automorphism group of $\fin(n)$.  We have the following
definitions:
\begin{defn}
  The automorphism group of the type $X : \UU$ is $\Aut(X) \defeq (X = X)$.
\end{defn}
\begin{defn}
  The delooping of an automorphism group $\Aut(X)$ is
  \[
    B\Aut(X) \defeq \sm{A : \UU} \merely{A = X}
  \]
\end{defn}
\begin{defn}
  The action groupoid for the action of $\Aut(X)$ on itself is
  \[
    E\Aut(X) \defeq \sm{w : B\Aut(X)} (\fst(w) = X)
  \]
  Giving the canonical fibration
  \[
    \fst : E\Aut(X) \to B\Aut(X)
  \]
\end{defn}
By Theorem 7.3.9 of the \ac{HoTT} book, $B\Aut(C)$ is $0$-connected, so we can
write
\[
  X_{n} = \abs{B\Aut(\fin(n))} \cdot \abs{\hfib{f}{\fin(n)}}
\]
which can be further simplified by computing $B\Aut(\fin(n))$ once and for all.
Note that $E\Aut(X)$ is contractible for all $X$, since it's a type of based
paths, so we have
\[
 1
 = \abs{E\Aut(X)}
 = \abs{B\Aut(X)} \cdot \abs{\Aut(X)}
\]
reducing our problem to computing $\abs{\Aut(\fin(n))}$, the number of
permutations of an $n$-element set.  This is $n!$, so, finally,
\[
  X_{n} = \frac{1}{n!} \abs{\hfib{f}{\fin(n)}}
\]
This suggests the notation $1 \sslash n! \defeq B\Aut(\fin(n))$, which I will
sometimes use in the following.

Plugging this back into the definition of $\gf{X}$, we have
\[
  \gf{X} = \sum_{n\geq0} \abs{\hfib{f}{\fin(n)}}\, \frac{z^{n}}{n!}
\]
So, we could have defined $\gf{X}$ as an exponential generating function,
without first thinking of $X$ as a fibration over $\mathbb{N}$.  Doing it our
way is informative, however.  A common rule of thumb is that one should use
exponential generating functions when working with labeled structures and
ordinary generating functions when working with unlabeled structures.  In
our setup, a labeling of some $A : \finset$ is a path $A = \fin(\card(A))$.  In
other words, we replace the type of finite sets with the type of labeled finite
sets:
\[
  \sm{A : \UU}{n: \mathbb{N}} \merely{A = \fin(n)}
  \qquad\Longrightarrow\qquad
  \sm{A : \UU}{n : \mathbb{N}} (A = \fin(n))
\]
and then proceed as before.  Equivalently, we could write our species as a
fibration $\sm{A:\finset}\Phi(A)$ for some $\Phi : \finset \to \UU$ and then
work with the altered species $\Phi(A) \times (A = \fin(\card(A))$.  So
``labeled $\Phi$-stuff on a finite set'' is the same as ``$\Phi$-stuff on a
finite set and a labeling of the set''.  The cardinality of the $n$th fiber is
then
\[
  \frac{1}{n!}
  \abs{
    \Phi(\fin(n)) \times (\fin(n) = \fin(n))
  }
  =
  \abs{\Phi(\fin(n))}
\]
as the $\abs{\Aut(\fin(n))}$ cancels out the $1/n!$.  The idea, then, is that a
species generating function gives an exponential generating function when one
computes out the dependence on $\card$, and then a labeling turns it into an
ordinary generating function.

Another reason to define $\gf{X}$ as we do is that it allows the labeled and
unlabeled cases to be treated at once.  Working directly with the reduced
generating functions requires one to insert various factorials by hand to make
some equations hold, and similar bookkeeping is needed for working with labeled
and unlabeled structures differently.  Taking the $n$th generating function
coefficient to be the groupoid cardinality of the fiber over $n$ allows us to
define each operation on a species once, and the modifications required for
labels take care of themselves.

\section{Speciation}

One power of the species approach is that it allows one to combine structures
in a natural way.  As an example in the previous section, we took a structure
type $\Phi : \finset \to \UU$ and created a labeled version $\Phi(A) \times (A
= \fin(\card(A)))$, naturally read as ``the species of finite sets equipped
with $\Phi$-stuff and a labeling'', using the propositions-as-types
interpretation.  The other type formers allow for similar combinations.

Throughout this section, we suppose that $f : X \to \finset$ and $g : Y \to
\finset$ are two species, and that $\Phi, \Psi : \finset \to \UU$ are two
families of stuff on $\finset$.

\subsection{Coproduct}

The simplest example is the coproduct.  The recursion principle for the
coproduct gives us a species with type $X + Y \to \finset$.
\begin{defn}
  The coproduct species $(f + g) : X + Y \to \finset$ is given by
  \begin{align*}
    (f + g) &: X + Y \to \finset \\
    (f + g) &\defeq \rec{X+Y}(\finset, f, g)
  \end{align*}
\end{defn}
\noindent
For structure types $\Phi, \Psi : \finset \to \UU$, we have
\[
  \left(\sm{A : \finset}\Phi(A)\right) + \left(\sm{B : \finset}\Psi(B)\right)
  \eqvsym
  \sm{A : \finset}\left(\Phi(A) + \Psi(A)\right)
\]
and so we can think of the species $X + Y$ as ``the species of finite sets
equipped with $X$-stuff or $Y$ stuff'', though ``or'' here is un-truncated.

The generating function $\gf{X + Y}$ can be simply expressed in terms of
$\gf{X}$ and $\gf{Y}$.  We have
\begin{align*}
  (X+Y)_{n}
  &=
  \frac{1}{n!}\abs{\hfib{f+g}{\fin(n)}}
  \\&=
  \frac{1}{n!}\abs{
    \sm{x:X}(f(x) = \fin(n))
    +
    \sm{y:Y}(g(y) = \fin(n))
  }
  \\&=
  \frac{1}{n!}\abs{
    \hfib{f}{n} + \hfib{g}{n}
  }
  \\&=
  X_{n} + Y_{n}
\end{align*}
since $\abs{X + Y} = \abs{X} + \abs{Y}$ for all groupoids $X$ and $Y$.  So, the
generating function $\gf{X+Y}$ is the sum of the generating functions $\gf{X}
+ \gf{Y}$.

\subsection{Hadamard product}
We can tell a similar story with $\times$ instead of $+$.  Where $X + Y$ is
the species of ``$X$ stuff or $Y$ stuff on a finite set'', the product should
give ``$X$ stuff and $Y$ stuff on a finite set''.  But this is ambiguous: there are two ways to put
two kinds of stuff on a finite set.  The problem, essentially, is that while
the recursion principle for the coproduct takes two species and gives a new
one, the recursion principle for the product needs something of type $X \to Y
\to \finset$ to produce a species.  The two kinds of products on species
correspond to different ways of doing this.

One way is to ``superpose'' the
$X$ stuff and $Y$ stuff.  That is, we might take the fiber over $\fin(n)$ to be
\begin{align*}
  \hfib{f}{\fin(n)} \times \hfib{g}{\fin(n)}
  &\equiv
  \left(\sm{x : X}(f(x) = \fin(n))\right)
  \times
  \left(\sm{y : Y}(g(y) = \fin(n))\right)
  \\&\eqvsym
  \sm{x : X}{y : Y}\left(
    (f(x) = g(y))
    \times
    (f(x) = \fin(n))
  \right)
  \\&\eqvsym
  \sm{z : X \times_{\finset} Y} (f(\fst(z)) = \fin(n))
  \\&\equiv
  \hfib{\langle f, g \rangle}{\fin(n)}
\end{align*}
This leads us to
\begin{defn}
  The Hadamard product species $\langle f, g \rangle : X \times_{\finset} Y \to
  \finset$ is given by
  \begin{align*}
    \langle f, g \rangle &: X \times_{\finset} Y \to
    \finset \\
    \langle f, g \rangle &: (x, y, p) \mapsto f(x)
  \end{align*}
\end{defn}
\noindent
For our structure types, we have
\[
  \left(\sm{A:\finset}\Phi(A)\right)
  \times_{\finset}
  \left(\sm{B:\finset}\Psi(B)\right)
  \eqvsym
  \sm{A:\finset}(\Phi(A) \times \Psi(A))
\]
which is naturally understood as ``a finite set equipped with $\Phi$ stuff on
top of $\Psi$ stuff'', as we wanted.

The generating function for the Hadamard product is
\begin{align*}
  (X \times_{\finset} Y)_{n}
  &=
  \frac{1}{n!}\abs{\hfib{\langle f, g \rangle}{\fin(n)}}
  =
  \frac{1}{n!}\abs{\hfib{f}{\fin(n)}} \cdot \abs{\hfib{g}{\fin(n)}}
  =
  n! X_{n} \cdot Y_{n}
\end{align*}
This formula motivates another name for this species: the inner product.  When
the ring of formal power series is treated as Fock space, the Hadamard product
of two formal power series gives the inner product on Fock space.  The
relationship between the generating functions themselves is messy.

\subsection{Cauchy product}
A more natural relationship between generating functions would be some species
$X \cdot Y$ such that
\[
  \gf{X \cdot Y}
  =
  \gf{X} \cdot \gf{Y}
  =
  \left(\sum_{n\geq0} X_{n} z^{n}\right)
  \left(\sum_{m\geq0} Y_{m} z^{m}\right)
  =
  \sum_{n\geq0}
  \left(
    \sum_{k=0}^{n} X_{k}Y_{n-k}
  \right) z^{n}
\]
For this to obtain, we should have
\begin{align*}
  \abs{\hfib{f \cdot g}{\fin(n)}}
  &=
  \sum_{k=0}^{n}
  \binom{n}{k}
    \abs{\hfib{f}{\fin(k)}}
    \cdot
    \abs{\hfib{g}{\fin(n-k)}}
\end{align*}
Decategorifying this expression gives the
\begin{defn}
  The Cauchy product species $(f \cdot g) : X \cdot Y \to \finset$ is
  \begin{align*}
    (f \cdot g) &: X \times Y \to \finset \\
    (f \cdot g) &: (x, y) \mapsto f(x) + g(y)
  \end{align*}
\end{defn}
\noindent
And for our structure types,
\[
  \left(\sm{A : \finset}\Phi(A)\right)
  \cdot
  \left(\sm{B : \finset}\Psi(B)\right)
  \eqvsym
  \sm{A : \finset}\sm{U, V : \finset}{p : U + V = A} \left(
    \Phi(U) \times \Psi(V)
  \right)
\]
So, we can interpret the Cauchy product species as ``a finite set chopped in
two with $\Phi$ stuff on one part and $\Psi$ stuff on the other''.

The coefficients of the generating function are
\begin{align*}
  (X \cdot Y)_{n}
  &\equiv
  \frac{1}{n!}
  \abs{\sm{x:X}{y:Y}(f(x) + g(y) = \fin(n))}
  \\&=
  \frac{1}{n!}
  \abs{\sm{r, s : \mathbb{N}}
    \left(\sm{w : 1\sslash r!}\hfib{f}{\fin(r)}\right)
    \times
    \left(\sm{w : 1\sslash s!}\hfib{g}{\fin(s)}\right)
    \times
    (\fin(r) + \fin(s) = \fin(n))
    }
  \\&=
  \sum_{k=0}^{n}\frac{1}{k!}\abs{\hfib{f}{\fin(k)}}
    \cdot \frac{1}{(n-k)!}\abs{\hfib{g}{\fin(n-k)}}
  \\&\equiv
  \sum_{k=0}^{n}X_{k}Y_{n-k}
\end{align*}
and so we obtain the relation $\gf{X \cdot Y} = \gf{X} \cdot \gf{Y}$ between
the generating functions.

\subsection{Composition}
Continuing to take inspiration from nice relations between generating
functions, we look for some species $X \circ Y$ such that
\[
  \gf{X \circ Y} = \abs{X}\!(\gf{Y})
  =
  \sum_{n\geq0}\left(
    \sum_{k=0}^{n}\sum_{n_{1} + \dotsb + n_{k} = n}
    X_{k}\cdot \prod_{i=1}^{k}Y_{n_{i}}
  \right) z^{n}
\]
To categorify this equation, we replace the partition of $n$ with a partition
of the set $\fin(n)$, and we replace the product $\prod_{i}Y_{n_{i}}$ with a
dependent product type.  To do this, we first define partitions of a finite
set.
\begin{defn}
  For any $n : \mathbb{N}$ and $S : \fin(n) \to \finset$, the $\fin(n)$-indexed
  sum $\bigoplus_{i=1}^{n} S_{i}$ of the family $S$ is the type defined by
  induction on the naturals by
  \begin{alignat*}{2}
    \bigoplus_{i=1}^{0}S_{i} &\defeq \emptyt
    \qquad\qquad&
    \bigoplus_{i=1}^{\suc(n)}S_{i} &\defeq S_{n} + \bigoplus_{i=1}^{n} S_{i}
  \end{alignat*}
\end{defn}
\begin{defn}
  A partition of a finite set $A : \finset$ into $n : \mathbb{N}$ parts by a
  family $P : \fin(n) \to \finset$ is a term of type
  \[
    P \vdash_{n} A \defeq
    \left(A = \bigoplus_{i=1}^{n} P_{i}\right)
  \]
  That is, it is a family $P : \fin(n) \to \finset$ such that $A$ is equal
  to the $\fin(n)$-indexed sum of $P$.
\end{defn}

With these, we can now define
\begin{defn}
  For species $f : X \to \finset$ and $g : Y \to \finset$, the composite
  species is given by
  \begin{align*}
    (f \circ g) &: \left(
      \sm{x : X}(\fin(\card(f(x))) \to Y)
    \right)
    \to
    \finset
    \\
    (f \circ g) &: (x, P, p) \mapsto \bigoplus_{i=1}^{\card(f(x))}(g(P(i)))
  \end{align*}
\end{defn}
\noindent
For structure types, this gives
\begin{align*}
  &\left(\sm{A : \finset}\Phi(A)\right)
  \circ
  \left(\sm{B : \finset}\Psi(B)\right)
  \\&\eqvsym
  \sm{A : \finset}{C:\finset}
  \sm{B : \fin(\card(C)) \to \finset}
  \left(
    (B \vdash_{\card(C)} A)
    \times
    \Phi(C)
    \times
    \prd{k : \fin(\card(C))}\Psi(B_{k})
  \right)
\end{align*}
So, the composition of the species $\Phi$ and $\Psi$ is the species of ``a
partitioned finite set, with $\Phi$ stuff on the partition and $\Psi$ stuff on
each element of the partition''.

The $n$th coefficient of the generating function is
\begin{align*}
  (X \circ Y)_{n}
  &=
  \frac{1}{n!}\abs{
    \sm{x:X}{P : \fin(\card(f(x))) \to Y}
    \left(\fin(n) = \bigoplus_{i=1}^{\card(f(x))} g(P(i))\right)
  }
  \\&=
  \abs{
    \sm{k:\mathbb{N}}
    \sm{m : \fin(k) \to \mathbb{N}}{p : m_{1} + \dotsb + m_{k} = n}
      \left(\sm{w : 1 \sslash k!}\hfib{f}{\fin(k)}\right)
    \times
      \prd{i : \fin(k)}\sm{w : 1 \sslash m_{i}!}\hfib{g}{\fin(m_{i})}
  }
  \\&=
  \sum_{k=0}^{n}\sum_{m_{1} + \dotsb + m_{k} = n}
  \frac{1}{k!}\abs{\hfib{f}{\fin(k)}}
  \cdot
  \prod_{i=1}^{k}
  \frac{1}{m_{i}!}\abs{\hfib{g}{\fin(m_{i})}}
  \\&=
  \sum_{k=0}^{n}\sum_{m_{1} + \dotsb + m_{k} = n}
    X_{k} \cdot \prod_{i=1}^{k} Y_{m_{i}}
\end{align*}
And so $\gf{X \circ Y} = \abs{X}\!(\gf{Y})$.

\subsection{Differentiation}
Again, we would like to construct a species whose generating function has a
nice property.  Since
\[
  \frac{d}{dz}\sum_{n\geq0}X_{n}z^{n}
  =
  \sum_{n\geq1}n\, X_{n} z^{n-1}
  =
  \sum_{n\geq0} (n+1)X_{n+1} z^{n}
\]
we want to define a species $f' : X' \to \finset$ such that $\gf{X'} =
\frac{d}{dz}\gf{X}$.  Categorifying this equation gives the
\begin{defn}
  The derivative of a species $f : X \to \finset$ is
  \begin{align*}
    f' &: \sm{A : \finset}{x:X}(f(x) = A + \unit) \to \finset \\
    f' &: (A, x, p) \mapsto A
  \end{align*}
\end{defn}
\noindent
For structure types, we have
\[
  \left(\sm{A:\finset}\Phi(A)\right)'
  =
  \sm{A, B : \finset}\left(
    \Phi(B)
    \times
    (B = A + \unit)
  \right)
\]
So $\Phi'$ stuff on $A$ is ``$\Phi$ stuff on $A + \unit$''.

The $n$th coefficient of the generating function is
\begin{align*}
  X'_{n}
  &=
  \frac{1}{n!}\abs{
    \sm{A : \finset}{x:X} \left(
      (f(x) = A + \unit)
      \times
      (A = \fin(n))
    \right)
  }
  \\&=
  \frac{1}{n!}\abs{
    \sm{x:X} \left(
      (f(x) = \fin(n) + \unit)
    \right)
  }
  \\&=
  \frac{1}{n!}\abs{
    \hfib{f}{\fin(n + 1)}
  }
  \\&=
  (n+1) X_{n+1}
\end{align*}
giving
\begin{align*}
  \gf{X'}
  =
  \frac{d}{dz}\gf{X}
\end{align*}

\subsection{Pointing}
From generating function theory, we know that for any polynomial $P$, the
generating function of the sequence $P(n)\,X_{n}$ is given by
\[
  P(z\partial_{z})\gf{X} = \sum_{n\geq0} P(n)\, X_{n}\, z^{n}
\]
It suffices to consider the case $P(n) = n$, for which we have by
categorification the
\begin{defn}
  For any species $f : X \to \finset$, the pointing $\pointed{f} : \pointed{X}
  \to \finset$ is
  \begin{align*}
    f_{\bullet} &: \left(\sm{x:X}f(x)\right) \to \finset \\
    f_{\bullet} &: (x, w) \mapsto f(x)
  \end{align*}
\end{defn}
\noindent
For a structure type, we have
\[
  \pointed{\left(\sm{A:\finset}\Phi(A)\right)}
  \eqvsym
  \sm{A:\finset}(\Phi(A) \times A)
\]
So $\pointed{\Phi}$ stuff on $A$ is ``$\Phi$ stuff on $A$ and a distinguished
point of $A$''.

The $n$th coefficient of the generating function is
\begin{align*}
  (\pointed{X})_{n}
  &=
  \frac{1}{n!}\abs{
    \sm{x:X}{w:f(x)}(f(x)=\fin(n))
  }
  =
  \frac{1}{n!}\abs{\hfib{f}{\fin(n)}}\cdot\abs{\fin(n)}
  =
  n\, X_{n}
\end{align*}
And so $\gf{\pointed{X}} = (z\, \partial_{z})\gf{X}$.

\subsection{Inhabiting}
It's often useful to have a version of the species that only exists on
inhabited sets.  This is the easy
\begin{defn}
  For any species $f : X \to \finset$, the inhabited version of the species
  $f_{+} : X_{+} \to \finset$ is
  \begin{align*}
    f_{+} &: \left(\sm{x:X}\merely{f(x)}\right) \to \finset \\
    f_{+} &: (x, p) \mapsto f(x)
  \end{align*}
\end{defn}
\noindent
For a structure type,
\[
  \left(\sm{A \finset}\Phi(A)\right)_{+}
  \eqvsym
  \sm{A : \finset}(\Phi(A) \times \merely{A})
\]
So, as intended, $\Phi_{+}$ stuff on a set is ``being an inhabited set equipped
with $\Phi$ stuff''.

The $n$th coefficient of the generating function is
\[
  (X_{+})_{n}
  =
  \frac{1}{n!}\abs{\hfib{f}{\fin(n)}} \cdot \abs{\merely{\fin(n)}}
  =
  \begin{cases}
    0 & n = 0 \\
    X_{n} & n > 0
  \end{cases}
\]
since $\fin(n)$ is decidable and $\merely{\fin(n)}$ is a mere proposition.  So
$\gf{X_{+}} = \gf{X} - X_{0}$.

\section{Examples}
This section lists a handful of examples.

\subsection{$(-2)$-stuff}  The simplest structure to put on a finite set is a
contractible one.  For example, we know that $\isfinset(A)$ is a mere
proposition, and it is inhabited for all $A : \finset$, so it's contractible.
So the total space of the type is
\[
  \sm{A : \finset}\isfinset(A)
  \eqvsym
  \sm{A : \finset}\unit
  \eqvsym
  \finset
\]
So any species of contractible stuff on a finite set is equal to $\idfunc{} :
\finset \to \finset$, the species of finite sets.  Call this species $E \defeq
\idfunc{\finset}$, for the species of ensembles.
The fiber over $n$ is
\[
  \sm{A : \UU}\merely{A = \fin(n)} \equiv B\Aut(\fin(n))
\]
so the generating function of the species of ensembles is
\[
  \gf{E} = \sum_{n\geq0} \frac{z^{n}}{n!} = e^{z}
\]

\subsection{$(-1)$-stuff}  Moving up the hierarchy, a family of mere
propositions can produce more interesting examples.  Considered as an
exponential generating function, the generating function obtained from
$(-2)$-stuff has coefficients in $\{1\}$.  For $(-1)$-stuff, we can choose
coefficients from $\{0, 1\}$.  So for example, we have

\paragraph{Empty stuff}
A finite set equipped with the stuff $\Phi : A \mapsto \emptyt$ gives the
species
\[
  0 \defeq \rec{\emptyt}(\finset) : \emptyt \to \finset
\]
which has the generating function
\[
  \gf{0} = 0
\]

\paragraph{$n$-element sets}
The stuff of ``being an $n$-element set'' gives the species
\[
  (Z^{n} \sslash n!) \defeq
  \fst : \left(
    \sm{A : \finset}(\card(A) = n)
  \right) \to \finset
\]
and it has the generating function
\[
  \gf{Z^{n} \sslash n!} = \frac{z^{n}}{n}
\]
As a special case, for $n = 0$ we have $\gf{Z^{n} \sslash n!} = 1$, so we'll
also write
\[
  1 \defeq (Z^{0} \sslash 0!)
\]

\paragraph{Inhabited finite sets}
This is the species $E_{+}$, and we clearly have
\[
  \gf{E_{+}} = \sum_{n\geq1}\frac{z^{n}}{n!} = e^{z} - 1
\]

\paragraph{Even and odd sets}
The stuff $\Phi$ of ``being an even set'' gives us the species
\[
  \mathrm{COSH} \defeq \fst :
  \left(\sm{A : \finset}{n:\mathbb{N}}\merely{A = \fin(2n)}\right)
  \to
  \finset
\]
So the fiber over $n$ is
\[
  \sm{w : 1 \sslash n!}{m:\mathbb{N}}(2m = n)
\]
giving the generating function
\[
  \gf{\mathrm{COSH}} = \sum_{\text{$n$ even}}\frac{z^{n}}{n!} = \cosh(z)
\]
Similarly, ``being an odd set'' is the species $\SINH$ with generating
function
\[
  \gf{\SINH} = \sum_{\text{$n$ odd}} \frac{z^{n}}{n!} = \sinh(z)
\]

\subsection{0-stuff}
On the next rung of the ladder we have families of sets.  Now we obtain
exponential generating functions with coefficients in $\mathbb{N}$.  For
example,

\paragraph{Labeled $n$-element sets}
The stuff of ``being a labeled $n$-element set'' gives the species
\[
  Z^{n} \defeq \fst : \left(
    \sm{A : \finset} (A = \fin(n))
  \right) \to \finset
\]
with generating function
\[
  \gf{Z^{n}} = z^{n}
\]

\paragraph{Labeled finite sets}
This species is
\[
  \fst : \left(
    \sm{A : \finset}{n:\mathbb{N}}(A = \fin(n))
  \right) \to \finset
\]
and it has generating function
\[
  \sum_{n\geq0} z^{n} = \frac{1}{1 - z}
\]

\paragraph{Linear order}
A linear order on a set $A$ is a mere relation $\blank < \blank : A \to A \to
\prop$ that's transitive, antisymmetric, and total.  We have the species
\[
  L \defeq \fst : \left(
    \sm{A:\finset}{< : A \to A \to \prop}\left(
      \mathsf{Transitive}(<)
      \times \mathsf{Antisymmetric}(<)
      \times \mathsf{Total}(<)
    \right)
  \right)
  \to
  \finset
\]
It's not too hard to see that this species is equal to the species of labeled
finite sets; there is a natural total order on $\fin(\card(A))$, and the
elements of $A$ can be matched up with elements of $\fin(\card(A))$ by matching
the orders.  So the generating function of $L$ is also
\[
  \gf{L} = \sum_{n\geq0}z^{n} = \frac{1}{1-z}
\]

\paragraph{Permutations}
A permutation on $A$ is a bijection $\sigma : A \to A$.  Since $A$ is a set,
being a bijection is equivalent to being an equivalence, so we have by
univalence the species
\[
  \mathrm{Per} \defeq \fst : \left(
    \sm{A : \finset}(A = A)
  \right) \to \finset
\]
This has the same fiber over $n$ as the species of finite labeled sets, so we
again have
\[
  \gf{\mathrm{Per}} = \sum_{n\geq0}z^{n} = \frac{1}{1-z}
\]

\paragraph{$\finset$-coloring}
For $K$ a finite set, a $K$-coloring of $A$ is a map $\phi : A \to K$.  This gives the
species
\[
  \fst : \left(
    \sm{A : \finset}(A \to K)
  \right) \to \finset
\]
which has generating function
\[
  \gf{A \to K} = \sum_{n\geq0} \abs{K}^{n}\frac{z^{n}}{n!}
  = e^{\abs{K}z}
\]

Consider the property of being a $K$-colored, 1-element set.  This is the
species given by the stuff
\[
  \Phi(A) \defeq \merely{A = \fin(1)} \times (A \to K)
\]
which is equivalent to the species equipped with stuff
\[
  \tilde{\Phi}(A) \defeq K \times \merely{A = \fin(1)}
\]
and hence to the Cauchy product $K \cdot Z$.  Indeed, the generating function
is given by
\[
  \gf{\Phi} = \abs{K}z
\]
and so we can write $nZ$ for the species ``being a $\fin(n)$-colored 1-element
set''.  As the notation suggests,
\[
  \gf{E \circ nZ} = \abs{E}\!(\gf{nZ}) = e^{nz}
\]

\subsection{Fock space}
Consider the operators $a, a^{*} : \mathbb{C}[z] \to \mathbb{C}[z]$ defined by
\begin{align*}
  a\psi &= \psi' \\
  a^{*}\psi &= z\psi
\end{align*}
for all $\psi \in \mathbb{C}[z]$.  We equip $\mathbb{C}[z]$ with an inner
product by demanding that
\[
  \inner{a^{*}\psi}{\phi} = \inner{\psi}{a\phi}
  \qquad\qquad
  \lVert 1 \rVert = 1
\]
for all $\psi, \phi \in \mathbb{C}[z]$.  Completing $\mathbb{C}[z]$ in this
inner product gives Fock space $K[z]$.

\section{Cayley's Formula}
We recount \citeauthor{Joyal1981}'s proof of the following
\begin{thm}[Cayley's Formula]
  The number of labeled trees on $n$ vertices is $n^{n-2}$.
\end{thm}

Recall that a tree is a connected graph such that any two edges are connected
by exactly one path.  A graph on a finite set $A$ is a mere relation $R : A
\to A \to \prop$, so we're looking at the species
\[
  T \defeq \sm{A:\finset}{R : A \to A \to \prop}\left(
      \mathsf{isTree}(R) \times (A = \fin(\card(A)))
    \right)
\]
Pointing this species twice gives a species $V \defeq T_{\bullet\bullet}$ of
vertebrates, so-called because we can think of the path connecting the two
special points as a vertebral column, with a rooted tree at each vertebra.  By
the calculation above for pointed species, we have $V_{n} = n^{2}\, T_{n}$ so
Cayley's formula follows if we can show that $V_{n} = n^{n}$.

To show this, note that $V$ is equivalent to the species $L_{+} \circ
T_{\bullet}$, which are inhabited linear orders of rooted trees.  Given a
vertebrate $v : V$, we disconnect it by forgetting the links between vertebrae,
then we induce a linear order on the connected components using the linear
order on the vertebral column.  Since $L_{n} = \mathrm{Per}_{n}$, it suffices
to consider $S_{+} \circ T_{\bullet}$, which is equal to $\mathrm{End}_{+}$.
Since $\mathrm{End}_{n} = n^{n}$, for $n > 0$ we have $V_{n} = n^{n}$, from
which follows Cayley's formula.

\bibliographystyle{apalike-url}
\pdfbookmark{References}{References}
\bibliography{references}

\end{document}


\begin{table}[ht]
\centering
\begin{tabular}{|l|l|l|} \hline \hline
{\bf operator} & {\bf explanation} & {\bf reference} \\ \hline \hline
get\_val\_by\_idx & get value by index &
Section~\ref{get_val_by_idx} \\ \hline

set\_sclr\_val\_by\_idx & set scalar value by index &
Section~\ref{set_sclr_val_by_idx} \\ \hline

add\_vec\_val\_by\_idx & Accumulate vector value by index &
Section~\ref{add_vec_val_by_idx} \\ \hline

vvmul & vector-vector multiply & Section~\ref{vvmul} \\ \hline

vsleq & vector-scalar \(\leq\) comparison & Section~\ref{vsleq} \\ \hline

ifxthenyelsez & ternary operator \verb+ x ? y : z+ &
Section~\ref{ifxthenyelsez} \\ \hline

where & select rows where condition is true &
Section~\ref{where} \\ \hline

const & create constant vector Section~\ref{const} \\ \hline
\hline
\end{tabular}
\caption{Selected Q operators}
\label{tbl_q_ops}
\end{table}
\section{Details of Q Operators}
\label{Q_ops}

\subsection{get\_val\_by\_idx}
\label{get_val_by_idx}
\bi
\item Inputs: (1) \(x\), Vector  (2) \(y\), Vector

\item Outputs: \(z\), Vector, same length as \(x\)

\item Operation: \(z[i] \leftarrow y[x_i]\)
\ei

\subsection{set\_sclr\_val\_by\_idx}
\label{set_sclr_val_by_idx}
\bi
\item Inputs: (1) \(x\), Vector  (2) \(s\), Scalar

\item Modified: \(z\), Vector

\item Operation: \(x[i] = j \Rightarrow z[j] \leftarrow s\)
\ei

\subsection{add\_vec\_val\_by\_idx}
\label{add_vec_val_by_idx}
\bi
\item Inputs: (1) \(x\), Vector  (2) \(y\), Vector, same length

\item Modified: \(z\), Vector \(\forall i: 0 \leq y[i] \leq z:\mathrm{length}() - 1\)

\item Operation: \(x[i] = j \Rightarrow z[j] \leftarrow z[j] + y[i]\)
\ei

\subsection{vvmul}
\label{vvmul}
\bi
\item Inputs: (1) \(x\), Vector  (2) \(y\), Vector, same length as \(x\)

\item Outputs: \(z\), Vector, same length as \(x\)

\item Operation: \(z[i] \leq x[i] + y[i]\)
\ei

\subsection{vsleq}
\label{vsleq}
\bi
\item Inputs: (1) \(x\), Vector  (2) \(y\), Scalar

\item Outputs: \(z\), bit-Vector, same length as \(x\)

\item Operation: \(x[i] \leq y \Rightarrow z[i] = 1\); else, \(z[i] = 0\)
\ei

%% \subsection{ainb}
%% \bi
%% \item Inputs: (1) \(x\), Vector  (2) \(y\), Vector
%%
%% \item Outputs: \(z\), bit-Vector of same length as \(x\)
%%
%% \item Operation: \(z[i] = 1\) if \(\exists j: x[i] = y[j]\); else, 0
%%
%% \ei

\subsection{ifxthenyelsez}
\label{ifxthenyelsez}
\bi
\item Inputs: (1) \(x\), bit-Vector (2) \(y\), Scalar (3) \(z\), Vector, all of
the same length

\item Outputs: \(w\) Vector of same length and type as \(y\)

\item Operation: \(x[i] = 1 \Rightarrow w[i] \leftarrow y\); else, \(w[i]
\leftarrow z[i]\)

\ei

\subsection{where}
\label{where}
\bi
\item Inputs: (1) \(x\), Vector  (2) \(y\), bit-Vector, same length as \(x\)

\item Outputs: \(z\), Vector of same type as \(x\)

\item Operation: \(z\) contains \(x[i]\) only if
\(y[i] = 1\). Order of elements in  \(z\) same as \(x\)

\ei

\subsection{const}
\label{const}
\bi
\item Inputs: (1) \(s\), Scalar

\item Outputs: \(x\), Vector of same type as \(s\)

\item Operation: \(x[i] = s\)

\ei


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

\marginpar{Wednesday\\ 2021-11-24}

Each of the particle species in our plasma satisfy a Vlasov equation,
%
\begin{align}
\pdv{f_\alpha }{t} + \vec{v} \cdot \nabla_x f_\alpha + q_\alpha \qty[ \vec{E} + \frac{\vec{v}}{c} \times \vec{B}]_\beta  \pdv{f_\alpha }{p_\beta } = 0
\,,
\end{align}
%
where \(\alpha \) runs over electrons, ions, cosmic rays and so on: any collisionless particles; while the index \(\beta \) is a spatial index, to be interpreted in the Einstein summation convention.

The \(\vec{E}\) and \(\vec{B}\) fields do \emph{not} have an index \(\alpha\): they are produced by all the components of the plasma.

An astrophysically significant situation is one in which there is a ``baseline'' magnetic field, which adds to the one generated within the plasma.

We align our axes so that \(\vec{B}_0 = B_0  \hat{z}\).
The baseline electric field is \(\vec{E}_0 = 0\).

\begin{enumerate}
    \item We ask that \(\vec{B}_0\) is ordered: its variations should be on much larger scales than the scales of the plasma.
    \item The equilibrium phase space density, \(f_{0, \alpha }\), is assumed to be known: it could, for example, be a Maxwellian, or a delta-function on \(\vec{v} = 0\).
\end{enumerate}

Again, we will perturb this system in order to find a dispersion relation \(F(k, \omega ) \delta = 0\), where \(\delta \) is our perturbation.

\paragraph{Perturbing the Vlasov equation}

The perturbed components in our fields will read
%
\begin{align}
f_\alpha &= f_{0, \alpha } + \delta f_\alpha  \\
\vec{B} &= \vec{B}_0 + \delta \vec{B}  \\
\vec{E} &= \delta \vec{E}
\,.
\end{align}

The perturbed equation, to first order, reads
%
\begin{align}
\pdv{ \delta f_\alpha }{t} + \vec{v} \cdot \vec{\nabla} \delta f_\alpha + q_\alpha \delta \vec{E}_\beta \pdv{f_{0 \alpha }}{p_\beta } + q_\alpha \qty( \frac{\vec{v}}{c} \times \vec{B}_0)_\beta \pdv{ \delta f_\alpha }{p_\beta }
+ q_\alpha \qty( \frac{\vec{v}}{c} \times \delta \vec{B}) \pdv{f_{0 \alpha }}{t} = 0
\,,
\end{align}
%
and, as usual, we will move to Fourier space, without tildes for simplicity:
%
\begin{align} \label{eq:perturbed-fourier-space-vlasov}
- i \omega \delta f_\alpha
+ i \vec{k} \cdot \vec{v} \delta f_\alpha
+ \hlc{violet}{q_\alpha \delta \vec{E}_\beta \pdv{f_{0 \alpha }}{p_\beta }}
+ \hlc{orange}{q_\alpha \qty( \frac{\vec{v}}{c} \times \vec{B}_0)_\beta \pdv{ \delta f_\alpha }{p_\beta }}
+ \hlc{yellow}{q_\alpha \qty( \frac{\vec{v}}{c} \times \delta \vec{B})
\pdv{f_{0 \alpha }}{p_\beta }} = 0
\,.
\end{align}

\paragraph{Perturbed Maxwell equations}

The divergence of the electric field perturbation reads
%
\begin{align}
\vec{\nabla} \cdot \delta \vec{E} = 4 \pi \zeta = 4 \pi \sum _{\alpha } q_\alpha \int \dd[3]{p} \delta f_\alpha
\,,
\end{align}
%
where \(\zeta \) denotes the charge density (which is purely a perturbation, since its unperturbed value is zero due to charge neutrality).

The divergence of \(\vec{B}\) vanishes, but so does the divergence of the constant \(\vec{B}_0\), so we have \(\vec{\nabla} \cdot \delta \vec{B} = 0\) as well.

The other two equations read
%
\begin{align}
\vec{\nabla} \times \delta \vec{E} &= - \frac{1}{c} \pdv{ \delta \vec{B} }{t}  \\
\vec{\nabla} \times \delta \vec{B} &= \frac{4 \pi \vec{J}}{c} + \frac{1}{c} \pdv{ \delta \vec{E}}{t}
\,.
\end{align}

In Fourier space, these read
%
\begin{align}
i \vec{k} \cdot \delta \vec{E} &= 4 \pi q_\alpha \int \dd[3]{p} \delta f_\alpha  \\
i \vec{k} \cdot \delta \vec{B} &= 0  \\
i \vec{k} \times \delta \vec{E} &= \frac{i \omega }{c} \delta \vec{B}  \\
i \vec{k} \times \delta \vec{B} &= \frac{4 \pi }{c} \sum _{\alpha } q_\alpha \int \dd[3]{p} \vec{v} \delta f_\alpha - \frac{i \omega }{c} \delta \vec{E}
\,.
\end{align}

We are now in a position to make a further simplifying assumption.

\begin{enumerate}[resume]
    \item We restrict ourselves to perturbations moving parallel to the magnetic field, \(\vec{k} \parallel \vec{B}_0\).
\end{enumerate}

Boron, Beryllium and Lithium are absent in the ISM but present in cosmic rays: there must be spallation, but for them to have significant interaction chances they must move very slowly. Something must be deflecting them.

Since \(\vec{k} \cdot \delta \vec{B} = 0\), the magnetic field perturbation must be in the form \(\delta \vec{B} = (\delta B_x, \delta B_y, 0)\).
From Faraday's law, we find \(\omega \delta \vec{B} = c \vec{k} \times \delta \vec{E}\):
%
\begin{align}
\frac{\omega}{c} \left[\begin{array}{c}
\delta B_x \\
\delta B_y \\
0
\end{array}\right]
= \det \left[\begin{array}{ccc}
\hat{x} & \hat{y} & \hat{z} \\
0 & 0 & k \\
\delta E_x & \delta E_y & \delta E_z
\end{array}\right]
= \left[\begin{array}{c}
- k \delta E_y \\
k \delta E_x \\
0
\end{array}\right]
\,.
\end{align}

Therefore, \(\delta B_x = - (kc / \omega ) \delta E_y\) and \(\delta B_y = (kc / \omega ) \delta E_x\).

\paragraph{Manipulating the Lorentz terms in Vlasov}

Let us now try to simplify the last three terms in the perturbed, Fourier space Vlasov equation \eqref{eq:perturbed-fourier-space-vlasov}: they read
%
\begin{align}
\hlc{violet}{q_\alpha \delta \vec{E}_\beta \pdv{f_{0 \alpha }}{p_\beta } }
+ \hlc{orange}{q_\alpha \qty( \frac{\vec{v}}{c} \times \vec{B}_0)_\beta \pdv{ \delta f_\alpha }{p_\beta }}
+ \hlc{yellow}{q_\alpha \qty( \frac{\vec{v}}{c} \times \delta \vec{B})
\pdv{f_{0 \alpha }}{p_\beta }}
\,,
\end{align}
%
so, explicitly:
%
\begin{align}
\begin{split}
&\phantom{=}\  \hlc{yellow}{\frac{q_\alpha}{c} \det \left[\begin{array}{ccc}
\hat{x} & \hat{y} & \hat{z} \\
v_x & v_y & v_z \\
\delta B_x & \delta B_y & 0
\end{array}\right]_\beta
\pdv{f_{0 \alpha }}{p_\beta }} \\
&+ \hlc{orange}{\frac{q_\alpha}{c} \det \left[\begin{array}{ccc}
\hat{x} & \hat{y} & \hat{z} \\
v_x & v_y & v_z \\
0 & 0 & B_0
\end{array}\right]_\beta
\pdv{ \delta f_\alpha }{p_\beta }}
+ \hlc{violet}{q_\alpha
\qty(\delta E_x \pdv{f_{0 \alpha }}{p_x} + \delta E_y \pdv{f_{0 \alpha }}{p_y})} =
\end{split}  \\
\begin{split}
&= \hlc{yellow}{\frac{q_\alpha}{c} \qty( - v_z \delta B_y \pdv{f_{0 \alpha }}{p_x} + v_z \delta B_x \pdv{f_{0 \alpha }}{p_y} + \qty(v_x \delta B_y - v_y \delta B_x) \pdv{f_{0\alpha} }{p_z})}
\\
& + \hlc{orange}{\frac{q_\alpha}{c} \qty(
    v_y B_0 \pdv{ \delta f_\alpha }{p_x} - v_x B_0 \pdv{ \delta f_\alpha }{p_y}
)}
+ \hlc{violet}{q_\alpha \qty(
    \delta E_x \pdv{f_{0 \alpha }}{p_x} +
    \delta E_y \pdv{f_{0 \alpha }}{p_y}
)}
\,.
\end{split}
\end{align}

\paragraph{Moving to a circular polarization basis}

We can always do the calculations for a perturbation in terms of circularly polarized waves, and then add them together.
We will write this as \(\delta E_y = \pm i \delta E_x\).
The idea is then to rewrite everything in terms of \(\delta E_x\), which we can then just denote as \(\delta E\).
Thanks to this, we get:
%
\begin{align}
\delta E_x &= \delta E  &
\delta E_y &= \pm i \delta E  \\
\delta B_x &= \mp \frac{kc}{\omega } \delta E  &
\delta B_y &= \frac{kc}{\omega } \delta E
\,.
\end{align}
%
%  \(\delta B_x = \mp (k c / \omega ) \delta E\) and  \(\delta B_y = (kc / \omega ) \delta E\).

With these substitutions, the three terms read
%
\begin{align}
\begin{split}
& \hlc{yellow}{\frac{q_\alpha}{c} \qty( -v_z \frac{kc}{ \omega } \delta E \pdv{f_{0 \alpha }}{p_x}
-  v_z i \frac{kc}{\omega } \delta E
\pdv{f_{0 \alpha }}{p_y}
+ \qty[v_x \frac{ck}{\omega } \delta E \pm i v_y \frac{ck}{\omega } \delta E] \pdv{f_{0 \alpha }}{p_z})} +
\\
&\phantom{=}\
+ \hlc{violet}{q_\alpha \delta E \pdv{ f_{0 \alpha} }{p_x} \pm q_\alpha i \delta E \pdv{f_{0 \alpha }}{p_y}}
+ \hlc{orange}{\frac{q_\alpha}{c}
B_0 \qty[v_y \pdv{f_{0 \alpha }}{p_x} - v_x \pdv{ \delta f_\alpha }{p_y}]}
\,.
\end{split}
\end{align}

\paragraph{Moving to cylindrical coordinates}

The unperturbed distribution function \(f_{0 \alpha }\) cannot depend on the angle around the direction of the magnetic field \(\vec{B}_0 \)
because of the cylindrical symmetry: it will be written like \(f_{0 \alpha } = f_{0 \alpha } (p_{\parallel}, p_\perp)\), therefore it is useful to move to cylindrical coordinates.

From \(p_x, p_y, p_z\) we move to \(p_\parallel\), \(p_\perp\), \(\varphi \), where
%
\begin{align}
p_x &= p_\perp \cos \varphi \\
p_y &= p_\perp \sin \varphi \\
p_z &= p_\parallel
\,.
\end{align}

One can invert the Jacobian in order to get
%
\begin{align}
\dd{p_\perp} &= \cos \varphi \dd{p_x} + \sin \varphi \dd{p_z}  \\
\dd{\varphi } &= - \frac{1}{p_\perp} \sin \varphi \dd{p_x} + \frac{1}{p_z} \cos \varphi \dd{p_z}  \\
\dd{p_\parallel} &= \dd{p_z}
\,.
\end{align}

Therefore,
%
\begin{align}
\pdv{ f_{0 \alpha }}{p_x} = \pdv{ f_{0 \alpha }}{p_\perp} \cos \varphi
\qquad \text{and} \qquad
\pdv{ f_{0 \alpha }}{p_y} = \pdv{ f_{0 \alpha }}{p_\perp} \sin \varphi
\,,
\end{align}
%
since the term containing a derivative with respect to \(\varphi \) vanishes.

With this, the term reads
%
\begin{align}
\begin{split}
& \frac{q_\alpha }{c} v_z \frac{ck}{\omega } \delta E \qty(
    \pdv{f_{0 \alpha }}{p_\perp} \cos \varphi
    \pm i \pdv{f_{0 \alpha }}{p_\perp} \sin \varphi
)
+ \frac{q_\alpha}{c} \frac{ck}{\omega } \delta E
\qty(v_\perp \cos \varphi \pm i v_\perp \sin \varphi )
\pdv{f_{0 \alpha }}{p_\parallel}
\\
&\phantom{=}\
+ q_\alpha \delta E \pdv{f_{0 \alpha }}{p_\perp} \qty(\cos \varphi \pm i \sin \varphi )
- \frac{q_\alpha}{c} B_0 \frac{v_\perp}{p_\perp} \pdv{ \delta f_\alpha }{p}
\end{split}  \\
&= \frac{q_\alpha }{c} v_z \frac{ck}{\omega } \delta E
    \pdv{f_{0 \alpha }}{p_\perp} e^{\pm i \varphi }
+ \frac{q_\alpha}{c} \frac{ck}{\omega } \delta E
v_\perp e^{\pm i \varphi }
\pdv{f_{0 \alpha }}{p_\parallel}
+ q_\alpha \delta E \pdv{f_{0 \alpha }}{p_\perp} e^{\pm i \varphi }
- \frac{q_\alpha}{c} B_0 \frac{v_\perp}{p_\perp} \pdv{ \delta f_\alpha }{\varphi }
\,.
\end{align}

\paragraph{Recombining the Vlasov equation}

Now we just need to add in the two remaining terms of the Vlasov equation:
%
\begin{align}
\begin{split}
&
- i \omega \delta f_\alpha
+ i \vec{k} \cdot \vec{v} \delta f_\alpha +
\frac{q_\alpha }{c} v_z \frac{ck}{\omega } \delta E
    \pdv{f_{0 \alpha }}{p_\perp} e^{\pm i \varphi }
+ \frac{q_\alpha}{c} \frac{ck}{\omega } \delta E
v_\perp e^{\pm i \varphi }
\pdv{f_{0 \alpha }}{p_\parallel}
+ q_\alpha \delta E \pdv{f_{0 \alpha }}{p_\perp} e^{\pm i \varphi }
\\
&\phantom{=}\
- \frac{q_\alpha}{c} B_0 \frac{v_\perp}{p_\perp} \pdv{ \delta f_\alpha }{\varphi } = 0
\,.
\end{split}
\end{align}

The last term includes a factor in which we can recognize the cyclotron frequency corresponding to particle species \(\alpha \) moving in the magnetic field \(\vec{B}_0\):
%
\begin{align}
\frac{q_\alpha}{c} B_0 \frac{v_\perp}{p_\perp} = \frac{q_\alpha B_0 }{c} \frac{v_\perp}{m_\alpha v_\perp \gamma } = \Omega _{\text{gyr, }\alpha }
\,.
\end{align}

\paragraph{Making a rotating ansatz}

If \(\delta f_\alpha \) was in the form \(\delta g_\alpha e^{\pm i \varphi }\), then the equation would automatically be satisfied, if \(g_\alpha \) does not depend on the phase, since in that case the last derivative would read \(\mp i \delta g_\alpha e^{\pm i \varphi }\).

With this substitution all the phase factors would cancel, and we would find
%
\begin{align}
\delta g_\alpha = \frac{\frac{q_\alpha}{c} \delta E \qty[v_z \frac{ck}{\omega } \pdv{f_0 }{p_\perp} - v_\perp \frac{ck}{\omega } \pdv{f_0 }{p_\perp} - \pdv{f_0 }{p_\perp}]}{- i \omega + i k v_z \mp i \Omega _{\text{gyr}}}
\,.
\end{align}

\paragraph{Closing the system with the Ampére-Maxwell law}

We have one step left in order to close the system:
we need a relation between \(\delta f_\alpha \) and \(\delta E\); we know that
%
\begin{align}
i \vec{k} \times \delta \vec{B} = \frac{4 \pi }{c} \sum _{\alpha } q_\alpha \int \dd[3]{p } \vec{v} \delta f_\alpha
- i \frac{\omega}{c} \delta \vec{E}
\,.
\end{align}
%
However, we already know how to connect \(\delta \vec{B}\) and \(\delta \vec{E}\):
%
\begin{align}
- i k \frac{ck}{\omega } \delta E =
\frac{4 \pi }{c} \sum _{\alpha } q_\alpha \int \dd{p_\perp} p_\perp \int \dd{p_\parallel} \int \dd{\varphi } v_\perp \cos \varphi
- i \frac{\omega}{c} \delta E
\,,
\end{align}
%
where we are considering the \(x\) component only, which was what we called \(\delta E\).

If we decompose \(\delta f_\alpha  = \delta g_\alpha e^{\pm i \varphi }\), the integral in \(\varphi \) reads
%
\begin{align}
\int_0^{2 \pi } \dd{\varphi } \cos \varphi e^{\pm i \varphi } = \pi
\,,
\end{align}
%
so we get, substituting in what we know for \(\delta g_\alpha \):
%
\begin{align}
\frac{- i k^2 c}{\omega } \delta E = \frac{4 \pi }{c}
\sum _{\alpha } q_\alpha \int \dd{p_\perp} p_\perp v_\perp \int \dd{p_\parallel}
\frac{\frac{q_\alpha}{c} \delta E \qty[v_z \frac{ck}{\omega } \pdv{f_0 }{p_\perp} - v_\perp \frac{ck}{\omega } \pdv{f_0 }{p_\perp} - \pdv{f_0 }{p_\perp}]}{- i \omega + i k v_z \mp i \Omega _{\text{gyr, } \alpha }}
- i \frac{\omega}{c} \delta E
\,,
\end{align}
%
which looks like a dispersion relation: we just need to collect the generic \(\delta E\), to get
%
\begin{align}
\frac{k^2 c^2}{\omega^2} = 1 - \sum _{\alpha } \frac{4 \pi^2 q_\alpha^2}{\omega } \int \dd{p_\parallel} \int \dd{p_\perp} \qty( p_\perp v_\perp \qty(\frac{v_\parallel k}{\omega } - 1) \pdv{p_{0 \alpha }}{p_\perp} - \frac{k v_\perp}{\omega } \pdv{f_{0 \alpha }}{p_\parallel}) \qty[ \omega - k v_\parallel \pm \Omega _\alpha ]^{-1}
\,.
\end{align}

We can write an alternative version of this using \(v_\parallel = v \mu \) and \(v_\perp (1 - \mu^2)^{1/2} v\), where \(\mu = \cos \theta \):
\begin{align}
\frac{k^2 c^2}{\omega^2} = 1 - \sum _{\alpha } \frac{4 \pi^2 q_\alpha^2}{\omega } \int \dd{p} \int \dd{\mu } \frac{p^2 v (1 - \mu^2)}{\omega - kv \mu \pm \Omega _\alpha }
\qty[- \pdv{f_{0 \alpha }}{p} + \frac{1}{p} \pdv{f_{0 \alpha }}{\mu } \qty(\mu - \frac{kv}{\omega })]
\,.
\end{align}

\paragraph{Application: a cold electron-proton plasma}

This is very general, and we can specify it to the case in which we only have electrons and protons, at \(T = 0\).

This means that \(f_{0 \alpha } = \delta (p) n_\alpha / 4 \pi p^2\) for some constant.
This way, we have
%
\begin{align}
\int_0^{\infty } \dd{p} 4 \pi p^2 \frac{n_\alpha}{4 \pi p^2} \delta (p) = n_\alpha
\,.
\end{align}

This will be true for both protons and electrons, and their densities will be equal to preserve neutrality: \(n_e = n_p\).
There is no dependence on \(\mu \), so we are left with
%
\begin{align}
\frac{k^2 c^2}{\omega^2} &=
1 - \sum _{\alpha } \frac{4 \pi^2 q_\alpha^2}{\omega } \int \dd{p} \int \dd{\mu }
\frac{p^2 v (1 - \mu^2)}{\omega - kv \mu \pm \Omega _\alpha }
\qty(- \pdv{}{p} \frac{n_\alpha \delta (p)}{4 \pi p^2})  \\
&= 1 - \frac{4 \pi e^2 n}{\omega } \int \dd{p} \dd{\mu }
\frac{ \delta (p)}{4 \pi p^2} \pdv{}{p}  \qty[\frac{p^2 v (1 - \mu^2)}{\omega - k v \mu \pm \Omega _\alpha }]
\,.
\end{align}

Let us look at the integral with respect to momentum, using \(p = m_\alpha v\):
%
\begin{align}
\begin{split}
&\phantom{=}\ \int \dd{p} \dd{\mu }
\frac{ \delta (p)}{4 \pi p^2} \pdv{}{p}  \qty[\frac{p^2 v (1 - \mu^2)}{\omega - k v \mu \pm \Omega _\alpha }]= \\
&= \int \dd{p} \frac{ \delta (p)}{4 \pi p^2} \qty( \frac{3 p^2}{m_\alpha } (\omega - k v \mu \pm \Omega _\alpha ) + \frac{k_\mu }{m_\alpha } \frac{p^3}{m_\alpha }) \qty(\omega - k v \mu \pm \Omega_\alpha^2)^{-1}
\end{split}  \\
&= \frac{3}{4 \pi m_\alpha } \frac{1}{\omega \pm \Omega _\alpha }
\,.
\end{align}

The integral in \(\mu \) is just \(\int_{-1}^{1} \dd{\mu } (1 - \mu^2) = 4/3\).
This finally yields
%
\begin{align}
\frac{k^2c^2}{\omega^2} &= 1
- \frac{4 \pi e^2 n }{\omega m_p} \frac{1}{\omega \pm e B_0 / m_p c}
- \frac{4 \pi e^2 n }{\omega m_e} \frac{1}{\omega \mp e B_0 / m_e c}  \\
&= 1
\mp
\frac{4 \pi e^2 n}{\omega m_p} \frac{m_p c}{e B_0} \frac{1}{1 \pm \omega / \Omega _p}
\pm
\frac{4 \pi e^2 n}{\omega m_e} \frac{m_e c}{e B_0} \frac{1}{1 \mp \omega / \abs{\Omega _e}}
\marginnote{We can replace \(m_e / m_e\) by \(m_p / m_p\). }
\,,
\end{align}
%
so if we consider the case in which \(\omega \ll \Omega _p \ll \abs{\Omega _e}\), we get
%
\begin{align}
\frac{k^2 c^2}{\omega^2} &= 1 \mp
\frac{4 \pi e^2 n}{\omega m_p} \frac{m_p c}{e B_0 } \qty( 1 \mp \frac{\omega }{\Omega _p})
\pm \frac{4 \pi e^2n}{\omega m_p} \frac{1}{\Omega _p}  \\
&= 1 + \frac{4 \pi e^2 n }{\omega m_p } \frac{\omega}{\Omega _p^2}  \\
&= 1 + \frac{4 \pi e^2 n }{m_p } \frac{m_p^2 c^2}{e^2 B_0^2}  \\
&= 1 + 4 \pi \underbrace{n m_p }_{\rho } \frac{c^2}{B_0^2}  \\
&= 1 + 4 \pi \rho \frac{c^2}{B_0^2} = 1 + \qty( \frac{c}{v_A})^2
\,,
\end{align}
%
where we introduced
%
\begin{align}
v_A = \frac{B_0 }{\sqrt{4 \pi \rho }}
\,,
\end{align}
%
so in the galaxy, where \(B_0 \sim \SI{}{\micro G}\) and \(\rho \sim m_p / \SI{}{cm^3}\), we have \(v_A \sim \SI{2}{km/s}\).

This means that
%
\begin{align}
\frac{k^2c^2}{\omega^2} = \frac{c^2}{v_A^2} \implies \pm k v_A = \omega
\,.
\end{align}

These perturbations travel very slowly!
They are called Alfvén waves. They move with \(\vec{k}\) along \(\vec{B}_0 \) (well, we assumed so), and they have oscillating electric and magnetic fields, both perpendicular to the driving magnetic fields.

Without these, cosmic rays would be basically travelling at the speed of light all the time.
They also create a small, induction-generated electric field, which is interesting!

\end{document}