%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                      %
% GLE - Graphics Layout Engine <http://www.gle-graphics.org/>          %
%                                                                      %
% Modified BSD License                                                 %
%                                                                      %
% Copyright (C) 2009 GLE.                                              %
%                                                                      %
% Redistribution and use in source and binary forms, with or without   %
% modification, are permitted provided that the following conditions   %
% are met:                                                             %
%                                                                      %
%    1. Redistributions of source code must retain the above copyright %
% notice, this list of conditions and the following disclaimer.        %
%                                                                      %
%    2. Redistributions in binary form must reproduce the above        %
% copyright notice, this list of conditions and the following          %
% disclaimer in the documentation and/or other materials provided with %
% the distribution.                                                    %
%                                                                      %
%    3. The name of the author may not be used to endorse or promote   %
% products derived from this software without specific prior written   %
% permission.                                                          %
%                                                                      %
% THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR   %
% IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED       %
% WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE   %
% ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY       %
% DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL   %
% DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE    %
% GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS        %
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER %
% IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR      %
% OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN  %
% IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                        %
%                                                                      %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\chapter{Programming Facilities}

\section{Expressions}
\index{variables}
\index{expressions}
Wherever GLE is expecting a number it can be replaced with an expression.  For
example

\preglecode{}
\begin{Verbatim}
     rline 3 2
\end{Verbatim}
\postglecode{}

and

\preglecode{}
\begin{Verbatim}
     rline 9/3 sqrt(4)
\end{Verbatim}
\postglecode{}

will produce the same result.

An expression in GLE is delimited by white space, so it may not contain any
spaces - `{\sf rline 3*3 2}' is valid but `{\sf rline 3 * 3 2}' will not work.

Or `{\sf let d2 = 3+sin(d1)}' will work and `{\sf let d2= 3 + sin(d1)}' won't.

Expressions may contain numbers, arithmetic operators ({\sf +}, {\sf -}, {\sf *},
{\sf /}, \verb+^+ (to the power of)), relational operators ($>$, $<$, $=>$, $<=$,
$=$, $<>$) Boolean operators ({\sf and}, {\sf or}), variables and built-in functions.

When GLE is expecting a colour or marker name (like `green' or `circle')
it can be given a string variable, or an expression enclosed in braces.

\section{Functions Inside Expressions}

\begin{figure}[tb]
\centering
\mbox{\includegraphics{prog/fig/axisformat}}
\caption{\label{axformat:fig}Examples of number formatting options.}
\end{figure}

\begin{commanddescription}

\item[{\sf eval(str)}]
\index{eval()}
Evaluates the given string as if it was a GLE expression and returns the result. E.g., \texttt{eval("3+4")} returns 7.

\item[{\sf arg(i), arg\$(i), nargs()}]
\label{args:cmd}
\index{arg()}
\index{arg\$()}
\index{nargs()}
Provide access to the command line arguments that are passed to GLE. This is useful for generating multiple similar plots from a single script. arg(i) returns the i-the argument (as a number), arg\$(i) returns the i-the argument as a string, and nargs() returns the number of arguments. Only arguments that come after the name of the GLE script are counted. For example, if GLE is run as:

\begin{Verbatim}
     gle -o graph-1.eps graph.gle "Title" 0.5
\end{Verbatim}

\noindent{}then nargs() returns 2, arg\$(1) returns ``Title'', and arg(2) returns 0.5.

The typical use of these functions is to create a script ``graph.gle'' as follows:

\begin{Verbatim}
size 10 10
begin graph
   title arg$(1)
   data arg$(2)
   d1 line color red
end graph
\end{Verbatim}

\noindent{}and then creating different graphs by running GLE multiple times:

\begin{Verbatim}
     gle -o beans.eps graph.gle "Beans" "beans.csv"
     gle -o peas.eps graph.gle "Peas" "peas.csv"
\end{Verbatim}

\noindent{}This will create two graphs: ``beans.eps'' and ``peas.eps''. The arg() functions can be used at all places in the script where an expression is expected. They can even be used in place of GLE commands in a graph block by means of the $\backslash{}$expr() function. For example,

\begin{Verbatim}
     data "file.csv"
     d\expr{arg(1)} line color red
\end{Verbatim}

\noindent{}in the graph block will allow one to draw different datasets from a single file on multiple graphs. To do so, run:

\begin{Verbatim}
     gle -o d1.eps graph.gle 1
     gle -o d2.eps graph.gle 2
\end{Verbatim}

\item[{\sf dataxvalue({\it ds},{\it i}), datayvalue({\it ds},{\it i}), ndata({\it ds})}]
\index{dataxvalue}\label{dataxvalue}
\index{datayvalue}\label{datayvalue}
\index{ndata}\label{ndata}

These functions can be used to retrieve the data values from a given dataset. They only work after data has been loaded by means of a graph block (Ch.~\ref{graph:chap}).

A dataset is specified with a dataset identifier {\it ds} (a string of the form ``d$i$'', with $i$ an integer). The function `{\sf ndata}' returns the number of points in the dataset, and the functions `{\sf dataxvalue}' and `{\sf datayvalue}' return the $x$ and $y$ values of point {\it i}, where {\it i} ranges from 1 to {\sf ndata({\it ds})}.

The following example shows how these functions can be used to compute the maximum of a dataset:

\begin{Verbatim}
sub dmaxy ds$
   local crmax = datayvalue(ds$,1)
   for i = 2 to ndata(ds$)
      crmax = max(crmax, datayvalue(ds$,i))
   next i
   return crmax
end sub
\end{Verbatim}

This subroutine together with other subroutines for computing the minimum, mean, area, etc. of a dataset are defined in the include file `graphutil.gle', which is distributed together with GLE.

\item[{\sf format\$({\it exp},{\it format})}]
\index{format\$()} \label{formatnum:pg}

Returns a string representation of {\it exp} formatted as specified in {\it format}.

Basic formats:
\begin{itemize}
\item {\sf append {\it s}}: appends the string $s$ after the formatted number. This can be used to add a unit.

\item {\sf dec}, {\sf hex [upper|lower]}, {\sf bin}: format as decimal, hexadecimal (upper-case or lower-case), or binary.

\item {\sf fix} {\it places}: format with {\it places} decimal places.

\item {\sf percent} {\it places}: format as ({\it exp} $\cdot 100$)\% with {\it places} decimal places.

\item {\sf sci} {\it sig} {\sf [e,E,10]} {\sf [expdigits {\it num}]} {\sf [expsign]}: format in scientific notation with {\it sig} significant digits. Use `e', `E', or `10' as notation for the exponent. With the option {\sf expdigits} the number of digits in the exponent can be set and {\sf expsign} forces a sign in the exponent.

\item {\sf eng} {\it digits} {\sf [e,E,10]} {\sf [expdigits {\it num}]} {\sf [expsign]} {\sf [num]}: format in engineering notation. The options are similar to `sci'. If the option `num' is given, then numeric notation is used instead of, e.g., $\mu$, m, k, M.

\item {\sf round} {\it sig}: format a number with {\it sig} significant digits.

\item {\sf frac}: format the number as a fraction.

\item {\sf pi}: format the number as a fraction times $\pi$ (E.g., xaxis labels of Fig.~\ref{grscale:fig}).
\end{itemize}

Options for all formats:
\begin{itemize}
\item {\sf nozeroes}: remove unnecessary zeroes at the end of the number.

\item {\sf sign}: also include a sign for positive numbers.

\item {\sf pad {\it nb} [left] [right]}: pad the result with spaces from the left or right.

\item {\sf prefix {\it nb}}: prefix the number with zeroes so that {\it nb} digits are obtained.

\item {\sf prepend {\it s}}: prepends the string $s$ before the formatted number.

\item {\sf min {\it val}}: use format for numbers $\ge$ {\it val}.

\item {\sf max {\it val}}: use format for numbers $\le$ {\it val}.
\end{itemize}

Examples:
\begin{itemize}
\item format\$(3.1415, ``fix 2'') = 3.14
\item format\$(3756, ``round 2'') = 3800
\item format\$(3756, ``sci 2 10 expdigits 2'') = $3.8\cdot10^{03}$
\end{itemize}

Several formats can be combined into one string: "sci 2 10 min 1e2 fix 0" uses scientific notations for numbers above $10^2$ and decimal notation for smaller numbers. See Fig.~\ref{axformat:fig} for more examples.

\item[{\sf pagewidth(), pageheight()}]
\index{pagewidth()} \index{pageheight()}
These functions return the width and height of the output. These are the values set with the `\texttt{size}' command.

\item[{\sf pointx(), pointy()}]\label{fct:pointxy}
These functions return the x and y values of a named point.

\preglecode{}
\begin{Verbatim}
     begin box add 0.1 name mybox
         write "Hello"
     end box
     amove pointx(mybox.bc) pointy(mybox.bc)
     rline 0 -2 arrow end
\end{Verbatim}
\postglecode{}

\item[{\sf twidth(str), theight(str), tdepth(str)}]
\index{twidth()} \index{theight()}
These functions return the width, depth and height of a string, if it was
printed in the current font and size.

\item[{\sf width(obj), height(obj)}]\label{fct:wdhi}
\index{width()} \index{height()}
These functions return the width and height of a named object.

\item[{\sf xend(), yend()}]
\index{xend()} \index{yend()}
These functions return the end point of the last thing drawn. This is
of particular interest when drawing text.

\preglecode{}
\begin{Verbatim}
     text abc
     set color blue
     text def
\end{Verbatim}
\postglecode{}

This would draw the {\sf def} on top of the {\sf abc}.  To draw the {\sf def}
immediately following the {\sf abc} simply do the following (Note that
absolute move is used, not relative move):

\begin{minipage}[c]{8cm}
\begin{Verbatim}
set just left
text abc
set color gray20
amove xend() yend()
text def
\end{Verbatim}
\end{minipage}
\hfill
\begin{minipage}[c]{7cm}
\mbox{\includegraphics{primitives/fig/gc_xend}}
\end{minipage}

\item[{\sf xg(), yg()}]
\index{xg()} \index{yg()}
\index{functions}
With these functions it is possible to move to a position on a graph
using the graph's axis units.
To draw a filled box on a graph, at position x=948, y=.004  measured
on the graph axis:

\preglecode{}
\begin{Verbatim}
     begin graph
        xaxis min 100 max 2000
        yaxis min -.01 max .01
        ...
     end graph
     amove xg(948) yg(.004)
     box 2 2 fill gray10
\end{Verbatim}
\postglecode{}

\item[{\sf xpos(), ypos()}]
\index{xpos()} \index{ypos()}
Returns the current x and y points.
\end{commanddescription}

\noindent{}See Appendix~\ref{fct:sec} for an overview of all functions provided by GLE.

\section{Using Variables}
\index{variables}
\index{string!variables}

GLE has two types of variables,  floating point and string. String
variables always end with a dollar sign.  A string variable contains
text like ``Hello, this is text'', a floating point variable can
only store numbers like 1234.234.

\preglecode{}
\begin{Verbatim}
name$ = "Joe"
height = 6.5   ! Height of person
shoe = 0.05    ! shoe adds to height of person
amove 1 1
box 0.2 height+shoe
write name$
\end{Verbatim}
\postglecode{}

\section{String constants}
\index{string!constants}

String constants can be double quoted or single quoted. To include a double quote character in a double quoted string it should be doubled. The same holds for a single quoted string. Backslash characters are not interpreted in a special way by GLE's parser. (They are, however, interpreted by the built-in \TeX{} system used in the `{\sf write}' command.) Here are some examples:

\preglecode{}
\begin{Verbatim}
print "Double quoted string"
print 'Single quoted string'
print "Between ""double quotes"""
print "{\it hello}"
print "Three double quotes """""""
print """"
\end{Verbatim}
\postglecode{}

The result of these print commands is:

\preglecode{}
\begin{Verbatim}
Double quoted string
Single quoted string
Between "double quotes"
{\it hello}
Three double quotes """
"
\end{Verbatim}
\postglecode{}

\section{Programming Loops}
\index{loops}
\index{for}
\index{next}

The simple way to draw a 6 $\times$ 8 grid would be to use a whole mass
of line commands:

\preglecode{}
\begin{Verbatim}
amove 0 0
rline 0 8
amove 1 0
rline 1 8
...
amove 6 0
rline 6 8
\end{Verbatim}
\postglecode{}

this would be laborious to type in, and would become
impossible to manage with several grids.  By using a simple loop
this can be avoided:

\preglecode{}
\begin{Verbatim}
for x = 0 to 6
   amove x 0
   rline x 8
next x
for y = 0 to 8
   amove 0 y
   rline 6 y
next y
\end{Verbatim}
\postglecode{}

For-next loops, and all other control constructs, can also be used among others inside graph and key blocks. This is useful for drawing many similar functions (Fig.~\ref{fig:sqroot}). Besides for-next loops, GLE also supports while and until loops:

\index{while}
\preglecode{}
\begin{Verbatim}
i = 0
while i <= 10
   print "Value: " i
   i = i + 1
next
\end{Verbatim}
\postglecode{}

\index{until}
\preglecode{}
\begin{Verbatim}
i = 0
until i > 10
   print "Value: " i
   i = i + 1
next
\end{Verbatim}
\postglecode{}

\section{If-then-else}
\index{if}
\index{then}
\index{else}

GLE supports if-then-else statements as follows:

\preglecode{}
\begin{Verbatim}
if a < 1 then print a "is smaller than 1"
else if a < 2 then print a "is smaller than 2 but larger than 1"
else if a < 3 then print a "is smaller than 3 but larger than 2"
else print a "is larger than 3"
\end{Verbatim}
\postglecode{}

\noindent{}to create blocks of code for the `then' and `else' branches, instead use:

\preglecode{}
\begin{Verbatim}
if a < 1 then
   print a "is smaller than 1"
   ...
else
   ...
end if
\end{Verbatim}
\postglecode{}

More complex conditions can be created with the logic connectives `{\sf and}', `{\sf or}', and `{\sf not}' (note the parenthesis around the logical expressions):

\preglecode{}
\begin{Verbatim}
if (a >= 1) and (a <= 10) then print "a is between 1 and 10"
\end{Verbatim}
\postglecode{}

\section{Subroutines}
\index{subroutines}

To draw lots of grids all of different dimensions a subroutine can
be defined and then used again and again:

\preglecode{}
\begin{Verbatim}
sub grid nx ny
   local x, y
   begin origin
      for x = 0 to nx
         amove x 0
         aline x ny
      next x
      for y = 0 to ny
         amove 0 y
         aline nx y
      next y
   end origin
end sub

amove 2 4
grid  6 8
amove 2 2
grid  9 5
\end{Verbatim}
\postglecode{}

Inside a subroutine, the keyword `\texttt{local}'\index{local} can be used to define local variables. E.g., `\texttt{local x = 3}', defines the local variable `x' and assigns it the value 3. It is also possible to define several local variables at once, as is shown in the `grid' example above.

The keyword `\texttt{return}'\index{return} can be used to return a value from a subroutine. E.g.,

\preglecode{}
\begin{Verbatim}
sub gaussian x mu sigma
   return 1/(sigma*sqrt(2*pi))*exp(-((x-mu)^2)/(2*sigma^2))
end sub
\end{Verbatim}
\postglecode{}

The main GLE file will be much easier to manage if subroutine definitions are moved into a separate file:

\preglecode{}
\begin{Verbatim}
include "griddef.gle"

amove 2 4
grid  2 4
amove 2 2
grid  9 5
\end{Verbatim}
\postglecode{}

More information about the ``include''\index{include} command can be found on page~\pageref{incl:cmnd}.

\subsection{Default Arguments}

Given the following subroutine definition:

\preglecode{}
\begin{Verbatim}
sub mysub x y color$ fill$
   default color  "black"
   default fill   "clear"
   print "Color: " color$
   print "Fill:  " fill$
end sub
\end{Verbatim}
\postglecode{}

\noindent{}the following calls are valid:

\preglecode{}
\begin{Verbatim}
mysub 1 0
mysub 1 0 red
mysub 1 0 red green
mysub 1 0 fill blue
mysub 1 0 color red
mysub 1 0 color red fill blue
\end{Verbatim}
\postglecode{}

\section{Forward Declarations}

A forward declaration of a subroutine is possible with:

\preglecode{}
\begin{Verbatim}
declare sub mysub x y
\end{Verbatim}
\postglecode{}

\noindent{}Forward declarations are required for declaring mutually recursive subroutines.

\section{I/O Functions}
\index{I/O-functions}
\index{fopen} \index{fread} \index{freadln}
\index{fclose} \index{fwrite} \index{fwriteln}
\index{fgetline} \index{ftokenizer}

The following I/O functions are available:

\begin{commanddescription}
\item[{\sf fopen {\it name} {\it file} [read$|$write]}]

Open the file ``{\it name}'' for reading or for writing. The resulting file handle is stored in variable ``{\it file}'' and must be passed to all other I/O functions.

\item[{\sf fclose {\it file}}]

Close the given file.

\item[{\sf fread {\it file} {\it x1} $\ldots$}]
\item[{\sf freadln {\it file} {\it x1} $\ldots$}]

Read entries from ``{\it file}'' into given arguments {\it x1} $\ldots$

\item[{\sf fwrite {\it file} {\it x1} $\ldots$}]

Write given arguments to ``{\it file}''.

\item[{\sf fwriteln {\it file} {\it x1} $\ldots$}]

Write given arguments to ``{\it file}'' and start a new line.

\item[{\sf fgetline {\it file} {\it line\$}}]

Read an entire line from ``{\it file}'' and store it in the string ``{\it line\$}''.

\item[{\sf ftokenizer {\it file} {\it commentchar spacetokens singletokens}}]

Sets up the parameters of the tokenizer that controls the reading of ``{\it file}''. The {\it commentchar} parameter specifies the characters that are to be interpreted as line comments. It is a string, but each character of the string is assumed to be a separate comment character. The default is ``!''. If one would write ``!\%'', then both ``!'' and ``\%'' would be comment indicators. The {\sf fread} functions skip everything after a comment character to the end of the line. The {\it spacetokens} string represents the set of characters that are interpreted as spaces or delimiters. The default value is `` ,$\backslash$t$\backslash$r$\backslash$n'', i.e., space, comma, tab, carriage return, and newline are delimiters by default. Finally, the {\it singletokens} string identifies characters that should be returned as separate tokens, even if they are glued to other tokens. For example, if ``@'' would be a single char token, then the string ``me@myself.com'' would be returned in three tokens: ``me'', ``@'', and ``myself.com''.

\end{commanddescription}

For example:

\preglecode{}
\begin{Verbatim}
fopen "file.dat" f1 read
fopen "file.out" f2 write
until feof(f1)
        fread f1 x y z
        aline x y
        rline x z
        fwriteln f2 x*2 "y =" y
next
fclose f1
fclose f2
\end{Verbatim}
\postglecode{}

\section{Device Dependent Control}
\index{device control}
A built in function which returns a string describing
the device is available. \\e.g. \verb# DEVICE$() = "HARDCOPY, PS,"#\\
on the postscript driver.

This can be used to use particular fonts etc on appropriate
devices. E.g.:

\preglecode{}
\begin{Verbatim}
                if pos(device$(),"PS,",1)>0 then
                        set font psncsb
                end if
\end{Verbatim}
\postglecode{}


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

\marginpar{Wednesday\\ 2021-12-22}

Last time we derived the transport equation in pitch angle:
%
\begin{align}
\pdv{f}{t} + v \mu \pdv{f}{z} = \pdv{}{\mu } \left(D_{\mu \mu } \pdv{f}{\mu }\right)
\,,
\end{align}
%
where \(D_{\mu \mu} = (1/2) \expval{\Delta \mu \Delta \mu / \Delta t}\).

This already contains a lot of information about what scattering does to cosmic rays.

If we have the classic system with a ``gun'' of particle emitting them
into a plasma with Alfvén waves, those will be isotropized.

Because of this, after some time we expect to see the bulk velocity of the Alfvén waves and the cosmic rays to be the same.

This is not realistic in every situation: if the plasma is relativistic, the assumption of the particle velocity being much higher than that of the waves breaks down.
This can be treated, but we will not discuss it in the course; the professor can provide the necessary references upon request.

After integrating the aforementioned equation between \(-1\) and \(1\), as well as between \(-1\) and \(\mu \), we found
%
\begin{align}
\pdv{M}{t} &= \pdv{}{z} \left( k_{zz} \pdv{M}{z} \right)  \\
k_{zz} &= \frac{v^2}{8} \int \dd{\mu } \frac{(1 - \mu )^2}{D_{\mu \mu }}
\,,
\end{align}
%
where the first equation tells us that \(M\) changes in time due to a process of \emph{spatial} diffusion, which is caused (as the second equation tells us) by diffusion in pitch angle.

The second-order nature of this equation is a trademark of a diffusive process.
With a heuristic line of reasoning we got a typical time for diffusion by \SI{90}{\degree}, called
%
\begin{align}
\tau_{90} = \frac{1}{D_{\mu \mu }}
\,,
\end{align}
%
which allows us to define \(\lambda = v \tau_{90}\),
while the correct expression is the one for \(k_{zz }\) above.

One thing we are still missing is the effect of the plasma!
That is currently only described through the fact that the particles are diffusing in pitch angle due to Alfvén waves.

Can we not ignore the bulk velocity if we move to the correct frame?
Yes! But, we cannot do the same if there are velocity \emph{gradients}.

Suppose we have a nonrelativistic plasma velocity \(u(z)\).
The change in the particle velocity term \(v \mu \) can be approximated as \(v \mu \to u + v \mu \).

\todo[inline]{Risky! \(u + v \mu \) could be larger than \(c\)! Wouldn't a better approximation be \(v \mu \)? }

What about the momentum? We transform it as
%
\begin{align}
\left[\begin{array}{c}
E' \\
p_z'c
\end{array}\right]
=
\left[\begin{array}{cc}
\gamma  & -\beta \gamma  \\
- \beta \gamma  & \gamma
\end{array}\right]
\left[\begin{array}{c}
E \\
p_zc
\end{array}\right]
\,.
\end{align}

So, the \(z\)-axis momentum \(p_z\) changes to \(p_z'c = - \beta \gamma E + \gamma p_z c\), where \(\beta = u(z) / c\).

The derivative of the phase space distribution changes to
%
\begin{align}
\pdv{f}{z} \to \pdv{f'}{z'} &= \pdv{f'}{p'_z} \pdv{p'_z}{z'}  \\
&= \pdv{f'}{p_z'} \left( - \dv{u(z)}{c} \right) \frac{E'}{c}   \\
v \mu \pdv{f}{z} &\to - (u + v \mu ) \left( \pdv{f'}{p'} \frac{E'}{c} \dv{u(z)}{c} \right)  \\
&= (u + v \mu ) \pdv{f'}{z'} - (u + v \mu ) \pdv{f'}{p'} \frac{E'}{c^2} \dv{u}{z'}  \\
&\approx (u + v \mu ) \pdv{f'}{z'} - v \mu \pdv{f'}{p'} \frac{E'}{c^2} \dv{u}{z'}
\marginnote{ \(u \ll v \mu \)}
\,.
\end{align}

We neglect the derivative of \(\gamma \) since \(\gamma = 1 + \order{\beta^2}\), and we are working to first order around 0 in the \(\beta \) corresponding to the plasma.

The change of coordinates formulas read
%
\begin{align}
\dd{\mu } &= \frac{1 - \mu^2}{p} \dd{p_z} - \mu (1 - \mu^2)^{1/2} \dd{p_\perp }  \\
\dd{p} &= \mu \dd{p_z} + (1 - \mu^2)^{1/2} \dd{p_\perp}
\,,
\end{align}
%
which means we get
%
\begin{align}
\pdv{f}{p_z} = \pdv{f}{p} \mu + \pdv{f}{\mu } \frac{1 - \mu^2}{p}
\,,
\end{align}
%
therefore
%
\begin{align}
v \mu \pdv{f}{z} &\approx (u + v \mu ) \pdv{f}{z}- v \mu \frac{E'}{c^2} \dv{u}{z} \left( \pdv{f}{\mu } p + \pdv{f}{p} \frac{1 - \mu^2}{p} \right)
\,.
\end{align}

Now we can apply the exact same approach as before!
We just added the term \(u \pdv*{f}{z}\).

The term \(\pdv*{f}{\mu }\) can be neglected, because \(f\) is assumed to be close to isotropy. If we do not neglect it, we only get higher order corrections.

This yields
%
\begin{align}
\frac{v E'}{c^2} \pdv{\mu }{p } \frac{1}{2} \int_{-1}^{1} \dd{\mu } \mu^2 = \frac{1}{3} \frac{ v E'}{c^2} \pdv{\mu}{p}
\,.
\end{align}

The object in front can be written in terms of the Lorentz factor of the particle \(\Gamma \):
%
\begin{align}
\frac{v E'}{c^2} = \frac{v m_p c^2 \Gamma }{c^2} = p
\,,
\end{align}
%
so the final result is
%
\begin{align}
\pdv{M}{t} + u \pdv{M}{z} - \frac{1}{3} \dv{u}{z} p \pdv{M }{p }
= \pdv{}{z} \left( k_{zz} \pdv{M}{z} \right)
\,.
\end{align}

This is the transport equation for any non-thermal particles.
The assumption of those being non-thermal is implicit in the assumption that \(v \gg u\).
This is conceptually important, since we need to answer the mechanism by which these particles emerge out of the thermal distribution.

The \emph{injection problem} is about how we go from a thermal distribution to a thermal distribution with non-thermal particles.

The effect of the particles on the plasma is also something which we should consider.
This would be a dependence of \(u\) and \(k_{zz}\) on the distribution of non-thermal particles.

The term \(p \pdv*{M}{p}\) is sensitive to the \emph{spectrum} of the particles!
This can change the distribution of particles in \(p\).

\begin{extracontent}
    Exercise:  suppose we have a system with particles injected and removed from surfaces orthogonal to \(k\).
    Further, suppose that \(k_{zz}\) is very small: this means that there is a lot of diffusion, since \(D_{\mu \mu }\) is very large.

    This basically means that the particles are ``glued'' to the plasma.
    Therefore, we also get \(\pdv*{M}{t} = 0\).

    What happens to the distribution function in this case?
    Suppose there is a linear gradient in the plasma velocity,
    %
    \begin{align}
    u = u_0 + \frac{\Delta u}{L} z
    \,.
    \end{align}

    Hint: using the method of characteristics.

    The expected result is to get adiabatic compression.
    If the velocity decreases we get energy increasing, and vice versa. This is the same as cosmological redshift.
\end{extracontent}

The way this works is that since there is a velocity gradient, in some reference frame we need to transform the magnetic field, therefore we also get an electric field which does the work.

\subsection{Particle transport}

In nature there are basically two acceleration mechanisms:
\begin{enumerate}
    \item when \(\expval{\vec{E}} \neq 0\) --- \emph{regular processes};
    \item when \(\expval{\vec{E}} = 0\) but \(\expval{E^2} = 0\) --- \emph{stochastic processes}.
\end{enumerate}

Unipolar inductors are when we have a magnet spinning very fast generating an electric field.
This might happen, for example, near a pulsar!
In the ideal MHD approximation \(E\) is orthogonal to \(B\), but near a pulsar this can be broken!
Then, we get a parallel component.
Another way this can happen is the accretion of a black hole.

Near a neutron star the magnetic field is roughly dipolar;
if \(E \parallel B\) we get an electric field which is about 8 orders of magnitude larger than the gravitational field.
So, particles feeling this field are stripped off.

When this happens, the particles still feel the very strong magnetic field.
So, electrons undergoing this process with a tilted dipolar magnetic field emit curvature radiation (bremsstrahlung).

We need to give a quantum description of such a magnetic field;
the virtual photons of this field can do pair production.

This process can repeat for \(\num{e4}\) to \num{e6} times: electrons stripped from the star are multiplied, and we get a lot of positrons as well.
These particles form a plasma of their own!

This will not be really discussed in this course, but there will be a short course about it.

Ideal MHD is locally violated, giving rise to regular processes, in plasma reconnection as well.

Magnetic flux is not conserved anymore, and we get heating of particles.

The rest of this course will mainly be about \textbf{stochastic} processes.
We will discuss \emph{second order Fermi acceleration}, the first investigation of particle acceleration historically.

Fermi, after getting the Nobel in '38, moved to Chicago and then worked on the Manhattan Project.

After the war, he started to work on many new problems.
The professor has met the last student of Fermi, Simpson.

At uni Chicago there is a quadrangle, which in 1948 was used to hold important dinners.
Enrico Fermi was not there a few minutes from midnight on New Year's,
at which point he came running and sweaty, having understood how cosmic rays were accelerated.
The idea came to Fermi after Alfvén gave a talk about waves.

The model by Fermi does not really work, but it was important historically.

The momentum of the particles in an Alfvén wave will change by \(\Delta p / p \sim v_A / c\), but this will happen stochastically with
%
\begin{align}
D_{pp} = \expval{\frac{\Delta p \Delta p}{\Delta t}} = \frac{p^2}{T^2} \left( \frac{v_A}{c}\right)^2
\,,
\end{align}
%
so the acceleration timescale is \(\tau _{\text{acc}} =p^2 / D_{pp} = (c / v_A)^2 T\).
This is too long to actually be the origin of cosmic rays, but in 1948  this was not clear.

This is called second-order because of two reasons: the square in \((c / v_A)\), and the fact that the diffusive motion can both increase and decrease the momentum.

Suppose we have regions of plasma moving in different directions.
Also suppose we have an electric field \(E\) in the reference frame of the laboratory.
A particle will sometimes ``interact'' with one of these magnetized regions, in a purely elastic way.

We introduce \(\beta \) and \(\gamma \) for the plasma clouds, with \(\beta \ll 1\).

After the scattering with the cloud, the energy of the particle in the reference frame of the cloud will become
%
\begin{align}
E' = \gamma E + \beta \gamma p \mu
\,.
\end{align}

Suppose that the scattering is purely elastic: \(\mu \) is simply reversed. The cloud is acting like a mirror.
This is not really necessary, it is just a simplifying assumption.

The final energy in the lab frame will be
%
\begin{align}
E'' &= \gamma E' + \beta \gamma p'_z \mu
\marginnote{The momentum is reversed, hence the plus sign.}  \\
&= \gamma^2 E \left( 1 + p^2 + 2 \beta \mu  \frac{p}{E} \right)
\,,
\end{align}
%
where \(p / E\) is the velocity of the particle.

The quantity we are interested in is
%
\begin{align}
\frac{E'' - E}{E} &= \gamma^2 \left(  1 + 2 p v \mu + \beta^2 \right) - 1  \\
&\approx 2 \beta^2 + 2 \beta^2 + 2 \beta v \mu
\marginnote{In the relativistic approximation, \(\beta \ll 1\) but \(v \sim 1\).}
\,.
\end{align}

What is the mean value of this?
It can attain positive and negative values, depending on the scattering angle \(\mu \).
This is the reason this process does not work!

If there is a situation for which \(\mu \) is bound to only allow acceleration, that can work.

We need to average this, weighed by the probability to have an interaction with a given \(\mu \).
The probability will be proportional to the relative velocity,
\todo[inline]{Why? If the particle is chasing the cloud it will catch it!}
%
\begin{align}
\mathbb{P }(\mu ) = A v _{\text{rel}} = A \frac{\beta \mu + v}{1 + v \beta \mu } \approx A (1  + \beta \mu )
\,,
\end{align}
%
and \(A\) must be \(1/2\) for normalization.
We can then compute
%
\begin{align}
\expval{\frac{\Delta E}{E}} = \int_{-1}^{-1} \dd{\mu } \frac{1}{2} \left( 2 \beta^2 + 2 \beta^2 + 2 \beta v \mu  \right) \left(1 + \beta \mu \right) = \frac{8}{3} \beta^2
\,,
\end{align}
%
so we have a mechanism for acceleration, but it is \(\propto \beta^2\).
The typical velocity, as we know now, is of a few tens of \SI{}{km/s}, which means we have something of the order \num{e-9}.

If the plasma is relativistic, even second order processes can be important, and actually for long gamma ray bursts they are believed to be the main mechanism.

The problem of injection, as mentioned by Fermi, is about the fact that we have nuclei as well as protons in cosmic rays.
How do we deal with ionization losses?
There is no solution to this problem, the mechanism does not really work.

This was understood about 30 years later.
The thing we need to discuss are explosions and shock waves.

\end{document}


%\documentclass[12pt]{article}
\documentclass[12pt,landscape]{article}

\include{preamble}

\newcommand{\instr}{\small Your answer will consist of a string (e.g. \texttt{aebgd}) where the order of the letters does not matter nor does upper / lowercase. \normalsize}

\title{Math 368 / 621 Fall \the\year{} \\ Midterm Examination One}
\author{Professor Adam Kapelner}

\date{Wednesday, September 22, \the\year{}}

\begin{document}
\maketitle

%\noindent Full Name \line(1,0){410}

\thispagestyle{empty}

\section*{Code of Academic Integrity}

\footnotesize
Since the college is an academic community, its fundamental purpose is the pursuit of knowledge. Essential to the success of this educational mission is a commitment to the principles of academic integrity. Every member of the college community is responsible for upholding the highest standards of honesty at all times. Students, as members of the community, are also responsible for adhering to the principles and spirit of the following Code of Academic Integrity.

Activities that have the effect or intention of interfering with education, pursuit of knowledge, or fair evaluation of a student's performance are prohibited. Examples of such activities include but are not limited to the following definitions:

\paragraph{Cheating} Using or attempting to use unauthorized assistance, material, or study aids in examinations or other academic work or preventing, or attempting to prevent, another from using authorized assistance, material, or study aids. Example: using an unauthorized cheat sheet in a quiz or exam, altering a graded exam and resubmitting it for a better grade, etc.
\\

\noindent By taking this exam, you acknowledge and agree to uphold this Code of Academic Integrity. \\

%\begin{center}
%\line(1,0){250} ~~~ \line(1,0){100}\\
%~~~~~~~~~~~~~~~~~~~~~signature~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ date
%\end{center}

\normalsize

\section*{Instructions}

This exam is 75 minutes (variable time per question) and closed-book. You are allowed \textbf{one} page (front and back) of a \qu{cheat sheet}, blank scrap paper and a graphing calculator. Please read the questions carefully. No food is allowed, only drinks. %If the question reads \qu{compute,} this means the solution will be a number otherwise you can leave the answer in \textit{any} widely accepted mathematical notation which could be resolved to an exact or approximate number with the use of a computer. I advise you to skip problems marked \qu{[Extra Credit]} until you have finished the other questions on the exam, then loop back and plug in all the holes. I also advise you to use pencil. The exam is 100 points total plus extra credit. Partial credit will be granted for incomplete answers on most of the questions. \fbox{Box} in your final answers. Good luck!

\pagebreak

\problem\timedsection{7} These are questions about indicator functions.
\vspace{-0.2cm}\benum\truefalsesubquestionwithpoints{11}

\begin{enumerate}[(a)]
%\setcounter{enumi}{3}
\item $\sum_{x \in \reals} \indic{x \in \braces{17}} = 17$
\item $\sum_{x \in \reals} \indic{x \in \braces{17}} = 1$
\item $\prod_{x \in \reals} \indic{x \in \braces{17}} = 17$
\item $\prod_{x \in \reals} \indic{x \in \braces{17}} = 1$
\item $\sum_{x \in \reals} h(x) \indic{x \in \naturals} = \sum_{x \in \naturals} h(x)$ where $h$ is a function. \\

Let $X$ be a discrete rv with PMF $p(x)$, old-style PMF $p^{old}(x)$ and support $\support{X}$. For any $X$,
\item $\sum_{x \in \reals} \indic{x \in \support{X}} = 1$

\item $\sum_{x \in \reals} p^{old}(x) = 1$
\item $\sum_{x \in \support{X}} p^{old}(x) = 1$
\item $\sum_{x \in \reals} p^{old}(x) \indic{x \in \support{X}} = 1$

\item $\sum_{x \in \reals} p(x) = 1$
\item $\sum_{x \in \reals} p(x) \indic{x \in \support{X}} = 1$
\end{enumerate}
\eenum\instr\pagebreak

%%%%%%%%%%%%%%%%%%%%%%%%

\problem\timedsection{8} Let

\beqn
\X = \twovec{X_1}{X_2} \sim p_{\X}(\x), ~~ T := X_1 + X_2 \sim p_{T}(t),  ~~
X_1 \sim p_{X_1}(x) := \begin{cases}
5 \withprob 0.2 \\
10 \withprob 0.8
\end{cases}  \text{independent of} ~~
%
X_2 \sim p_{X_2}(x) :=\begin{cases}
-5 \withprob 0.1 \\
-10 \withprob 0.9
\end{cases}
\eeqn
\vspace{-0.2cm}\benum\truefalsesubquestionwithpoints{8}

\begin{enumerate}[(a)]
%\setcounter{enumi}{3}
\item $X_1, X_2$ are identically distributed
\item $\var{\X} = \var{T}$
\item $T = \a \X$ where $\a = [1~1]$
\item $p_{T}(t) = p_{X_1}(x) \star p_{X_2}(x)$
\item $p_{T}(t) = \sum_{x_1 \in \reals} \sum_{x_2 \in \reals} p_{\X}(x_1, x_2)$
\item $p_{T}(t) = \sum_{x_1 \in \reals} \sum_{x_2 \in \reals} p_{\X}(x_1, x_2) \indic{t = x_1 + x_2}$
\item $p_{T}(t) = \sum_{x_1 \in \reals} \sum_{x_2 \in \reals} p_{X_1}(x_1)p_{X_2}(x_2) \indic{t = x_1 + x_2}$
%\item $p_{T}(t) = \sum_{x \in \reals}  p_{\X}(x, t - x)$
\item $p_{T}(t) = \sum_{x \in \reals}  p_{X_1}(x)p_{X_2}(t - x)$
\end{enumerate}
\eenum\instr\pagebreak

%%%%%%%%%%%%%%%%%%%%%%%%

\problem\timedsection{10} Consider the same setup as the previous problem:
\beqn
\X = \twovec{X_1}{X_2} \sim p_{\X}(\x), ~~ T := X_1 + X_2 \sim p_{T}(t),  ~~
X_1 \sim p_{X_1}(x) := \begin{cases}
5 \withprob 0.2 \\
10 \withprob 0.8
\end{cases}  \text{independent of} ~~
%
X_2 \sim p_{X_2}(x) :=\begin{cases}
-5 \withprob 0.1 \\
-10 \withprob 0.9
\end{cases}
\eeqn
\vspace{-0.2cm}\benum\truefalsesubquestionwithpoints{10}

\begin{enumerate}[(a)]
%\setcounter{enumi}{3}
\item $T \sim \text{Deg}(0)$
\item $T \sim \binomial{2}{p}$ where $p$ can be computed from $p_{X_1}(x)$ and $p_{X_2}(x)$
\item $\support{T} = \braces{-10, -5, 5, 10}$
\item $p_{X_1}(x) = 0.2 \indic{x = 5} + 0.8 \indic{x = 10}$
\item $p_{X_1}(x) = 5 \indic{x = 0.2} + 10 \indic{x = 0.8}$
\item $p_{T}(t) = 0.2 \indic{t = 5} + 0.8 \indic{t = 10} + 0.1 \indic{t = -5} + 0.9 \indic{t = -10}$
\item $p_{T}(0) = p_{\X}(0, 0)$
\item $p_{T}(0) = p_{\X}(5, -5) + p_{\X}(10, -10)$
\item $p_{T}(0) = p_{X_1}(5) + p_{X_2}(-5) + p_{X_1}(10) + p_{X_2}(-10)$
\item $p_{T}(0) = 0.74$
\end{enumerate}
\eenum\instr\pagebreak

%%%%%%%%%%%%%%%%%%%%%%%%

\problem\timedsection{8} These are questions about rv's we studied in class. Consider $X_1, X_2, X_3, \ldots \iid \bernoulli{p}$.
\vspace{-0.2cm}\benum\truefalsesubquestionwithpoints{9}

\begin{enumerate}[(a)]
%\setcounter{enumi}{3}
\item $X_1 + X_{17} \sim \binomial{17}{p}$
\item $X_1 + X_{17} \sim \binomial{2}{p}$
\item $X_1 + X_2 + X_3 + \ldots$ is a geometric rv
\item $X_1 + X_2 + X_3 + \ldots$ is a negative binomial rv
\item $\bracks{X_1~ X_2~ X_3}^\top$ is a multinomial rv\\

Let $T_n := \sum_{i=1}^n X_i$ where $n \in \naturals$

\item $T_n \sim \binomial{n}{p}$
%\item $T_n + T_n \sim \binomial{2n}{p}$
\item $T_n$ will be approximately distributed as a Poisson($np$) rv if $n$ is large and $p$ is small.\\

Let $Y$ be the rv that counts the number of $X_t$'s that are realized to be zero before the first $X_t$ that is realized to be one i.e. $Y = \min{t\,:\, X_t = 1} - 1$.
\item $Y$ is a geometric rv
\item Given that $Y = 4$, then $X_3$ is degenerate.
\end{enumerate}
\eenum\instr\pagebreak

%\beqn
%\lim_{\sigma \rightarrow 0} POW(\theta_0, \theta_a, n, \sigma, \alpha) = \lim_{\sigma \rightarrow 0} \parens{1 - \Phi\parens{-\frac{\sqrt{n}}{\sigma} (\theta_a - \theta_0) + z_{1 - \alpha}}} = 1 - \lim_{\sigma \rightarrow 0} \parens{\Phi\parens{-\frac{\sqrt{n}}{\sigma} (\theta_a - \theta_0) + z_{1 - \alpha}}} = 1 - 0 = 1
%\eeqn

%%%%%%%%%%%%%%%%%%%%%%%%

\problem\timedsection{7} Consider $X_1, X_2, X_3, \ldots \iid \geometric{p}$. Let $T_n := \sum_{i=1}^n X_i$ and $T_m := \sum_{i=n+1}^{n+1+m} X_i$ where $n, m \in \naturals$.
\vspace{-0.2cm}\benum\truefalsesubquestionwithpoints{7}

\begin{enumerate}[(a)]
\item $\support{X_1} = \support{X_1 + X_2}$
\item $T_n \sim p_{T_n}(t) = p^2 \sum_{x=0}^\infty (1-p)^x (1-p)^{t-x} \indic{t-x \in \braces{0,1,2,\ldots}}$
\item $T_n \sim p_{T_n}(t) = p^2 \sum_{x=1}^\infty (1-p)^x (1-p)^{t-x} \indic{t-x \in \braces{1,2,\ldots}}$
\item $T_n + T_n \sim \negbin{2n}{p}$
\item $T_m \sim \negbin{m}{p}$
\item $T_m \sim \negbin{n+m}{p}$
\item $T_n + T_m \sim \negbin{n+m}{p}$
\end{enumerate}
\eenum\instr\pagebreak

%%%%%%%%%%%%%%%%%%%%%%%%

\problem\timedsection{6} Let $X_1, X_2, \ldots, X_n \iid \poisson{\lambda}$, $T_n := \sum_{i=1}^n X_i$ and $\X = \bracks{X_1 ~ X_2 ~ \ldots~ X_n}^\top \sim p_{\X}$.
\vspace{-0.2cm}\benum\truefalsesubquestionwithpoints{9}

\begin{enumerate}[(a)]
\item $p_{X_1}(x) = \frac{\lambda^x e^{-\lambda}}{x!}$
\item $p_{X_1}(x) = \frac{\lambda^x e^{-\lambda}}{x!} \indic{x \in \braces{1,2, ...}}$
\item $p_{X_1}(x) = \frac{\lambda^x e^{-\lambda}}{x!} \indic{x \in \braces{0,1,2, ...}}$
\item $p_{\X}(\x) = \displaystyle\prod_{i=1}^n \displaystyle\frac{\lambda^{x_i} e^{-\lambda}}{x_i!} \indic{x_i \in \braces{0,1,2, ...}}$
\item $T_n \sim \poisson{n\lambda}$
\item $T_n \sim \poisson{\lambda / n}$
\item $T_n \sim \poisson{\lambda}$
\item As $n \rightarrow \infty$, $T_n$ becomes more and more degenerate
\item As $n \rightarrow \infty$, $T_n$ becomes more and more like a $\binomial{n}{\lambda / n}$
\end{enumerate}
\eenum\instr\pagebreak

%%%%%%%%%%%%%%%%%%%%%%%%

\problem\timedsection{10} Consider a bag of marbles with 5 red marbles, 4 green marbles, 6 blue marbles and 3 purple marbles. You sample (pick) 19 marbles from the bag by picking one at a time, recording its color and then putting that marble bag into the bag. Let $X_1$ count the number of red marbles in your sample, let $X_2$ sample the number of green marbles in your sample, let $X_3$ sample the number of blue marbles in your sample and let $X_4$ count the number of purple marbles in your sample. Let $\X = \bracks{X_1 ~ X_2 ~ X_3~ X_4}^\top \sim p_{\X}$.
\vspace{-0.2cm}\benum\truefalsesubquestionwithpoints{11}

\begin{enumerate}[(a)]
\item $p_{\X}(\x) = p_{X_1}(x_1) p_{X_2}(x_2) p_{X_3}(x_3) p_{X_4}(x_4)$
\item $X_1$ is a binomial rv with $n = 19$
\item $X_1 + X_2 + X_3 + X_4$ is degenerate
\item $\X \sim \multinomial{4}{18}{\oneover{19}\bracks{5 ~4 ~6 ~3}^\top }$
\item $\X \sim \multinomial{4}{19}{\oneover{18}\bracks{5 ~4 ~6 ~3}^\top }$
\item $\X \sim \multinomial{18}{19}{\oneover{4}\bracks{5 ~4 ~6 ~3}^\top }$
\item $p_{\X}(9,2,2,6) = \oneover{18^4}\binom{19}{9,2,2,5} 5^6 4^2 6^2 3^2$
\item $p_{\X}(9,2,2,0) = \oneover{18^4}\binom{19}{9,2,2} 5^6 4^2 6^2$
\item $p_{\X}(9,2,0,0) = \oneover{18^4} \frac{19!}{2!} 5^6 4^2 $
\item $p_{\X}(19,0,0,0) = \oneover{18^4} \frac{19!}{19!} 5^{19}$
\item Given $X_1 = 3$ and $X_2 = 1$, $\bracks{X_3~X_4}^\top$ is a multinomial rv with $K=2$.
\end{enumerate}
\eenum\instr\pagebreak

%%%%%%%%%%%%%%%%%%%%%%%%

\problem\timedsection{8} Consider the same situation as the previous problem: \ingray{a bag of marbles with 5 red marbles, 4 green marbles, 6 blue marbles and 3 purple marbles. You sample (pick) 19 marbles from the bag by picking one at a time, recording its color and then putting that marble bag into the bag. Let $X_1$ count the number of red marbles in your sample, let $X_2$ sample the number of green marbles in your sample, let $X_3$ sample the number of blue marbles in your sample and let $X_4$ count the number of purple marbles in your sample.} Thus, $\X = \bracks{X_1 ~ X_2 ~ X_3~ X_4}^\top \sim p_{\X} = \multinomial{4}{19}{\oneover{18}\bracks{5 ~4 ~6 ~3}^\top}$.
\vspace{-0.2cm}\benum\truefalsesubquestionwithpoints{8}

\begin{enumerate}[(a)]
\item $\expe{X_1} = 5/19$
\item $\expe{X_1} = 19 \times 5/18  $
\item $\expe{X_2 + X_3} = 19 \times 5/18 + 19 \times 4/18 $
\item $\expe{X_2 + X_3} = 19 \times 6/18  + 19 \times 4/18  $ \\

Let $\c = [1 ~ 2 ~ 3 ~ 4]^\top$ i.e. a 4-dimensional column vector of constants.

\item $\expe{\c + \X} = \frac{19}{18}\bracks{1 \times 5 ~~~ 2 \times 4 ~~~ 3 \times 6 ~~~ 4 \times 3}^\top$
\item $\expe{\c + \X} = \frac{19}{18}(1 \times 5 + 2 \times 4 + 3 \times 6 + 4 \times 3)$

\item $\expe{\c^\top \X} = \frac{19}{18}\bracks{1 \times 5 ~~~ 2 \times 4 ~~~ 3 \times 6 ~~~ 4 \times 3}^\top$
\item $\expe{\c^\top \X} = \frac{19}{18}(1 \times 5 + 2 \times 4 + 3 \times 6 + 4 \times 3)$
\end{enumerate}
\eenum\instr\pagebreak

%%%%%%%%%%%%%%%%%%%%%%%%

\problem\timedsection{11} Consider the same situation as the previous two problems: \ingray{a bag of marbles with 5 red marbles, 4 green marbles, 6 blue marbles and 3 purple marbles. You sample (pick) 19 marbles from the bag by picking one at a time, recording its color and then putting that marble bag into the bag. Let $X_1$ count the number of red marbles in your sample, let $X_2$ sample the number of green marbles in your sample, let $X_3$ sample the number of blue marbles in your sample and let $X_4$ count the number of purple marbles in your sample. Thus, $\X = \bracks{X_1 ~ X_2 ~ X_3~ X_4}^\top \sim p_{\X} = \multinomial{4}{19}{\oneover{18}\bracks{5 ~4 ~6 ~3}^\top}$.}
\vspace{-0.2cm}\benum\truefalsesubquestionwithpoints{11}

\begin{enumerate}[(a)]
\item $\var{\X}$ is a symmetric and diagonal matrix
\item $\cov{X_1}{X_2 + X_3} = 2\cov{X_1}{X_2}$
\item $\cov{X_1}{X_2 + X_3} = -19 (50) / 18^2$
\item $\var{[1~1~1~1] \X} = 0$
\item $\var{[1~1~1~1] \X} = [1~1~1~1] \var{\X} [1~1~1~1]^\top$
\item $\var{\X} = \displaystyle\frac{19}{18^2}\bracks{\begin{array}{cccc}
a & e & f & g \\
e & b & h & i \\
f & h & c & j \\
g & i & j & d
\end{array}}$ where $a, b, c, d, e, f, g, h, i, j$ are integers.
\item $\var{\X}$ is the matrix in the previous question and $e, f, g, h, i, j$ are negative integers.
\item $\var{\X}$ is the matrix in the previous question and $g = -15$.
\item $\var{\X}$ is the matrix in the previous question and $b = -60$.
\item The number of red marbles minus the number of purple marbles has variance $\frac{19}{18^2}(5 \times 14 + 2 (5 \times 3) + 3 \times 16)$
\item The number of red marbles minus the number of purple marbles has variance $\frac{19}{18^2}(5 \times 14 - 2 (5 \times 3) + 3 \times 16)$
\end{enumerate}
\eenum\instr\pagebreak

%%%%%%%%%%%%%%%%%%%%%%%%

\end{document}


\chapter{High Performance Si Immersion Gratings Patterned with Electron Beam Lithography}
\label{chap_ebeam}

\section{INTRODUCTION}
\label{sec:intro}  % \label{} allows reference to this section

At the 2012 SPIE Astronomical Telescopes and Instrumentation meeting (volume 8450) we described the detailed performance of the immersion grating (part number CA-1a \cite{2012SPIE.8450E..2SG}) for the high resolution infrared spectrograph IGRINS \cite{2010SPIE.7735E..54Y}.  IGRINS saw first light at McDonald Observatory in March 2014.  Papers describing its performance appear in the current volume\cite{2014SPIE.CHANPARK.IGRINS,2014SPIE.9151E..1GB}.  The technical readiness of the immersion grating now rests on firm footing, and our group has now moved on to pushing the performance and design limitations of silicon diffractive optics.  The key limitation is phase coherence.  Phase coherence for a diffraction grating is the accuracy to which repeated grating facets are positioned to an integer multiple of $\sigma$, the groove constant (the desired constant spacing from groove to groove).  Specifically, the position, $x$ of the $n^{th}$ facet in a sequence of $N$ total facets is distributed as:

\begin{eqnarray}
x_n = n\sigma + \epsilon_n  \label{eqn:Epsilon}
\end{eqnarray}

where $\epsilon_n$ is the position error for facet $n$.  Discussion of the phase performance can be broadly separated by the correlations  of errors, $\epsilon_n$, and their impact on the monochromatic spectral purity.

There are large scale, smooth correlations:
\begin{eqnarray}
\epsilon_n = \epsilon_n(x, y) \label{eqn:smooth}
\end{eqnarray}
These errors manifest as low order optical aberrations and degrade the PSF and Strehl.  Operationally these smooth errors correspond to the first $M$ Zernike polynomials in an orthonormal expansion of the wavefront, where $M < 200$.  There is the especially pernicious repetitive error:
\begin{eqnarray}
\epsilon_n = A\sin{\frac{2\pi n\sigma}{P} - \phi} \label{eqn:Periodic}
\end{eqnarray}
where $n\sigma$ is the desired position of the $n^{th}$ groove, $A$ is the amplitude of the error (e.g. in nm), and $P$ is the period of the error (e.g. in mm).  These errors manifest as sidelobes of the PSF called Rowland ghosts.  Although we have listed a single harmonic periodic error, any periodic structure can be broken into its Fourier components, so each of these Fourier components will be affiliated with a sidelobe Rowland ghost.  Lastly there are small scale random errors:
\begin{eqnarray}
\epsilon_n \sim \mathcal{N}(0, c)
\end{eqnarray}
where $ \sim \mathcal{N}(0, c)$ denotes that the error is normally distributed with mean zero and standard deviation $c$.  This last type of error produces so-called spectral grass\cite{2007ApOpt..46.3400M}, which is scattered light filling the blaze.

\section{On-sky performance of Si immersion grating}

With the commissioning of IGRINS \cite{2010SPIE.7735E..54Y}, we have demonstrated that the immersion grating performance measured in the laboratory translates into performance in a real world instrument in the field.  IGRINS is a high resolution near-infrared astronomical spectrograph.  It employs an immersion grating as its primary dispersive element, and two cryogenic VPH gratings for cross-dispersion.  The instrument covers a wavelength range of 1.5$-$2.5 $\mu$m in two channels.  The design and early performance of IGRINS is described in this volume [talk 9147-48]\cite{2014SPIE.CHANPARK.IGRINS}.  The immersion grating for IGRINS is internal part number CA-1a.  Its lab-measured performance is summarized in Gully-Santiago et al. 2012\cite{2012SPIE.8450E..2SG}.

IGRINS has no measured performance limitation attributable to the immersion grating.  CA-1a is diffraction limited.  CA-1a has been thermally cycled $>10$ times at the time of writing, with no perceptible degradation in performance.  We expect no degradation from thermal cycling.  We have previously constrained the CA-1a blaze angle to $\delta = 71.5\pm 0.2^\circ$.  The overall instrument throughput is consistent with the expected throughput including the laboratory-measured diffraction efficiency of CA-1a.

One major open question is whether CA-1a meets its spectral ghost level specification.  Spectral ghosts are secondary images that arise from periodic facet positioning errors\cite{2007sdf..book.....J}. The ghosts in CA-1a where introduced from a cyclically varying position-dependent exposure dose in the UV photolithography patterning step.  The processing error causing the ghosts has since been eliminated.  As a result our most recent immersion grating prototypes show a dramatic reduction in high frequency spectral ghosts [this volume, talk number 9151-35]\cite{2014SPIE.9151E..1GB}.  The ghost level depends on the amplitude of the error (cf. Equation 14 of Marsh et al. 2007\cite{2007ApOpt..46.3400M}):
\begin{eqnarray}
	\frac{I_g}{I_0}=[ \frac{2\pi n}{\lambda}A \sin{\delta} ]^2	 \label{eqn:GLevel}
\end{eqnarray}
where $I_g/I_0$ is the ghost level relative to the main peak, $\lambda/n$ is the wavelength scaled in the refractive index, and $A$ is defined in Equation \ref{eqn:Periodic}.  We predicted an in-immersion ghost level of $I_g/I_0 \sim2\times10^{-3}$ at 1.5 $\mu$m based on visible laser metrology\cite{2012SPIE.8450E..2SG}.  At the time of writing the IGRINS commissioning team has constrained ghost levels at $\lambda=1.5 \; \mu$m to $I_g/I_0 < 1\times10^{-2}$.  The limitation of a direct ghost level measurement is the need to deconvolve the slit diffraction ringing from the spectral point spread function.

\section{Motivations for direct writing Si immersion gratings}
We have determined experimentally that the lithographic transfer step is the most important determinant of the optical quality of Si immersion gratings.  The prior steps: orienting, polishing, passivating and resist-coating the monolithic substrates is now routine and our process control for these steps is sufficient to limit their contribution to the error budget to the point where they have no effect on the quality of the final gratings\cite{2007ApOpt..46.3400M,2014SPIE.9151E..1GB}.  The subsequent steps: development of the resist, reactive ion etching of the passivation layer, and anisotropic etching of the V-grooves similarly contribute little to the overall errors.  We therefore concentrate our efforts on finding more effective and accurate ways to carry out the transfer or patterning step.

The JPL Microdevices Laboratory has an advanced electron beam writer (a JEOL model 9300FS) and has made an extensive effort to understand the nuances of using this device for precision patterning of small features over large spatial scales.  For the large-area immersion grating exposures we use the JEOL 9300FS at 100 kV accelerating voltage with 60 nA current, a spot size $\sim 100-150$ nm and spot step spacing of 50 nm. Our typical groove frequency for echelle grating prototypes is 40 - 12.5 grooves/mm (25-80 $\mu$m groove spacing) but groove frequencies higher than 1000 grooves/mm are possible. Experimental pattern sizes are up to 100 mm $\times$ 40 mm, but could be as large as 200 mm diameter.

\subsection{Motivation \#1: Higher precision than contact lithography}
\label{sec:Precis}
Electron beam lithography is more precise than contact lithography.  One figure of merit for precision in e-beam lithography is the \emph{spot size}, the typical diameter of the Gaussian e-beam current distribution at the location of the e-beam sensitive resist on the substrate surface.  E-beam spot sizes on the JEOL 9300FS tool can be as low as 4 nm at low currents (less than 1 nA).  To expose the required immersion spectrometer grating areas in reasonable times ($\sim$50 hours), tens of nA of current are needed, and $\sim 100 - 150$ nm spot sizes are typical.  The final precision is a small fraction of the spot size, since many adjacent spots are convolved together.  In later sections we directly compare the performance of immersion gratings produced with e-beam and contact lithography to show evidence that we have achieved much higher precision in e-beam lithography.

\subsection{Motivation \#2: Finer groove pitch capability}
Owing to its small achievable spot size, electron beam lithography can reach finer groove spacings than contact photolithography can.  Fine pitches are required for high dispersion in low order.  Our group is currently designing a fine pitch ($\sigma \; \sim$ 2 $\mu$m, line frequency $\sim 500$ lines/mm) pattern immersion grating for the NASA Earth Science Technology Office (ESTO) Advanced Component Technologies (ACT) program.  The ACT mission concept requires high spectral resolution at low order ($\sim1-10$).  The desired first and second order gratings cannot be made with contact lithography.  Higher order devices can be made with contact lithography, but suffer from order overlap and reduced bandwidth.

\section{e-beam patterning strategies}
E-beam patterning takes place within a hierarchy of increasing scale-sizes.  The relationships of these pattern scale sizes affect the relative power distributed among spectral and spatial scales in the delivered monochromatic PSF.

\subsection{e-beam patterning scale size hierarchy}

\begin{figure}
\begin{center}
 \begin{tabular}{c}
    \includegraphics[width=0.8\textwidth]{chSPIE_2014_ebeam/figs/Field_sizes_cascade_02.png}
   \end{tabular}
  \end{center}
  \caption[e-beam Hierarchy]{\label{fig:Hierarchy} Hierarchy of e-beam pattern scale sizes- in the left panel the grooves are black and the fields are thin blue lines, the middle inset shows subfields, and the right inset shows spots at a regular step spacing, though the spots are not to scale.  Spot sizes are typically about 2-3 times their spacing.}
\end{figure}

There are a five key pattern scale sizes in e-beam lithography.  These scales are typical among e-beam tools, though we focus our discussion to the scales relevant to the JEOL 9300FS.  The scale sizes in order of small to large scales are 1) step size, 2) spot size, 3) subfield deflector size, 4) field deflector size, and 5) stage range of motion.  Figure \ref{fig:Hierarchy} shows a cartoon of the hierarchy from left to right- field, subfields, and steps.

Table \ref{tab:D07andE12} lists the pattern size scales for two immersion grating prototypes, parts D07 and E12.  These prototypes are examples of successful pattern designs.  D07 and E12 were both patterned on 10 mm thick Si pucks.  A 10 mm thickness is sufficient for the piece to maintain its flatness after anisotropic etching of the grooves so that interferometric measurements will reflect accurately the effectiveness of the patterning step.

\begin{table}
	\begin{center}
	\caption{D07 and E12 e-beam pattern details. \label{tab:D07andE12}}
	\begin{tabular}{ccc}
	\toprule
	   &D07 & E12  \\
	\midrule
	substrate bias angle ($^\circ$) & 6.1 & 71.5 \\
	pattern size (mm) & 39.0 x 39.664 & 29.696 x 84.816 \\
	pitch ($\mu$m) & 7.8 & 27.36 \\
	line frequency (lines/mm) & 128.2 & 36.55 \\
	top width ($\mu$m) & 0.4 & 9.96 \\
	line width ($\mu$m) & 7.4 & 17.40 \\
	step size (nm) & 50 & 50 \\
	steps per linewidth & 148 & 348 \\
	subfield size ($\mu$m) & 3.7 & 2.9 \\
	subfields per linewidth & 2 & 6 \\
	steps per subfield & 74 & 58 \\
	\cline{1-1}
	 			      & 63: 491.4  & 17: 465.12 \\
	grooves per $x-$field and & 61: 475.8 & 15: 410.4 \\
	$x-$field sizes ($\mu$m) & 59: 460.2 & 13: 355.68 \\
	 				        & 55: 429.0 & 11: 300.96 \\
	\cline{1-1}
	 			      & 134: 495.8  &   \\
	subfields per $y-$field and & 133: 492.1 &   \\
	$y-$field sizes ($\mu$m) & 131: 484.7 & 160: 464.0 \\
	 				        & 127: 469.9 &   \\
	\cline{1-1}
	\bottomrule
	\end{tabular}
	\end{center}
\end{table}

\subsubsection{e-beam step size and spot size}
The e-beam step size is the center-to-center separation of the e-beam spots, controlled by the beam-deflection electronics of the writer.  Step sizes can range from roughly 2 to 100 nanometers.  We adopted a 50 nm step size for our immersion grating patterns.  The rationale for the step size depends on understanding the e-beam spot size.

The spot size controls the smallest achievable feature size.  Our spot size of $\sim 100 - 150$ nm is determined by operational properties of the electron gun and focusing column.  The spot size can be decreased by preferentially removing those electrons with large velocity components perpendicular to the bulk direction of motion.  This preferential removal of fast electrons is achieved with a grounded conductive circular aperture in the beam path prior to the spot formation.  The aperture is constricted to reduce the spot size.  The net current (e$^-$/s) consequently decreases, since the aperture has effectively thrown away electrons.  So there is a tradeoff between current and spot size.  This tradeoff is important in deciding optimal patterning strategies and sizes.  The economical need to limit the expensive e-beam write time necessitated a high current and hence the resulting large spot size.

The conductive aperture setting coarsely selects the range of spot size achievable, while the detailed spot size depends on fine adjustments made to the e-beam column before an exposure.  These adjustments are familiar for those who have used scanning electron microscopy- astigmatism, wobble, and focus, for example.  Poor calibration might deliver an elliptical, asymmetric spot shape.  In practice, a slightly asymmetric spot shape does not affect the performance of immersion gratings.

A key idea is that the step size (50 nm) is much smaller than the spot size so that adjacent steps convolve to form a fairly uniform exposure area.  Another key assumption is that the e-beam spot does not change significantly over the course of an exposure.  We expect that the e-beam spot is unchanged, so long as the e-beam column is unperturbed.

\subsubsection{Subfield deflector}
The subfield deflector is a component of the e-beam gun that directs the e-beam spot within a box of up to 4 $\mu$m $\times$ 4 $\mu$m, centered around a mean position set by the main field deflector.  For example we chose subfield sizes of 3.7 and 2.9 $\mu$m for D07 and E12, respectively.  For recent work on fine pitch ($\sim2\; \mu$m) gratings we have experimented with smaller subfield sizes.  The reason for these choices of subfield sizes of D07 and E12 is that these field sizes result in an integer number of subfield per linewidth, which avoids fractional e-beam spots at the boundaries.  Subfield boundaries are perceptible in the intentionally underexposed e-beam resist of sample TJ04, depicted in Figure \ref{fig:TJ04Zeiss}.  In general we have found subfield stitching boundaries do not cause measurable ghosts unless the choice of subfield size results in fractional spots at the subfield/field boundaries.

\subsubsection{Field deflector}
\label{sec:Field}
The field deflector, also sometimes called the main-field deflector, coarsely redirects the electron beam over a square up to 500 $\mu$m in size.  The main-field deflector positions the center of the subfields.  For example, the choice of a 500 $\mu$m square field size and 4 $\mu$m square subfield size would result in 125 $\times$ 125 subfields.

The fields are stitched together by the interferometrically controlled stage that steps between them once each field's pattern has been written.  The stage move speed is typically much slower than the field and subfield deflector speed, so small field sizes are inefficient in time-on-target compared to wall-clock time.  Even though the JEOL 9300FS dynamically corrects for beam position distortion (e.g. pincushion) and spot focus and astigmatism, the writing performance degrades slightly with distance from the center of the field.  So there is a tradeoff between write speed and performance.

The choice of field size is multifaceted.  Field size choice is one of the key strategies for mitigation of ghosts (see Section \ref{sec:Ghosts}).

\begin{figure}
\begin{center}
 \begin{tabular}{c}
    \includegraphics[width=0.96\textwidth]{chSPIE_2014_ebeam/figs/subfields_TJ04_Zeiss.pdf}
   \end{tabular}
  \end{center}
  \caption[TJ04 under Zeiss]{\label{fig:TJ04Zeiss} Subfield and field boundaries directly perceptible in optical microscopy of the e-beam resist on an intentionally underexposed sample, TJ04.  The groove pitch for this sample is 100 $\mu$m, with a 75 $\mu$m written linewidth.  The blue area is the linewidth portion of the grating which has e-beam resist already exposed to e-beam.  The orange line is the groove top, where the e-beam resist was unexposed and would have served as the wet etch dam, had the linewidth actually developed out.  The minute color differences within the exposed linewidth are attributable to tiny thickness differences of the resist, which originate from tiny differences in delivered e-beam dose.  The cylindrically symmetric color difference of teal to dark blue is attributable to the proximity effect as described elsewhere\cite{2005SPIE.5720...68W}.  The tiny boxes are subfields, which are only perceptible due to subtle subfield stitching errors.  Some subfields are more errant than others.  The thick horizontal stripe is a portion of a much larger field boundary, perceptible only because of main-field deflector stitching boundaries as discussed in the text.}
\end{figure}

\subsubsection{Interplay of hierarchy at boundaries and design rules}
\label{sec:Boundaries}
Undesirable repetitive patterns that can cause ghosts arise when there are discontinuities as one steps up the field hierarchy.  The e-beam spots, subfields, and fields must match up at the boundaries.  We learned many subtle design rules unique to high performance immersion gratings.  The main theme in all of the design rules is to avoid fractional steps in the writing process.  The JEOL pattern generation software inserts patterns of spaces and spots when it reaches a command for a fractional step.  The specific design rules below are probably unique to the JEOL pattern generation software.  Other e-beam tool software is likely to have different design rules, but the general principle is the same.
\begin{enumerate}
  \item Subfields must be an integer number of steps
  \item Fields should be an integer number of subfields.
  \item Linewidth should be an integer number of subfields.
  \item Field sizes and linewidths can be non-integer number of subfields only if the remainder fractional subfield plus one subfield divided by two is an integer number of step sizes.
\end{enumerate}

These rules ensure that all e-beam spots are equidistant.  Figure \ref{fig:Hierarchy}  shows the JEOL \emph{shot shape display} of a pattern that broke rules 2 and 4.  Metrology of a grating prototype that broke rules 2 and 4 resulted in cross-dispersion grating ghosts $>10^{-3}$.  The line-edge of contiguous spots lacked a solitary spot near the subfield boundary.  Such a periodic dearth in exposure manifested as a periodic divot along the length of the groove.  The detailed impact on optical phase depends on the relative step size, e-beam sensitive resist contrast, and sundry subsequent processing steps.  Rather than risk a performance degradation it is best practice to avoid the formation of subfield blips in the first place.  The main concern for a final application is probably scattered light, and not efficiency loss.

\subsection{Predicting the ghost level associated with field positioning errors}
\label{sec:Ghosts}

The field size is only a few times larger than our typical coarse echelle grating groove constants.  Figure \ref{fig:FieldCartoon} shows an exaggerated cartoon of the field size relative to grooves.  In a hypothetically perfect e-beam field stitch, the line positions are exactly as desired.  In reality there is some finite distortion, which is repeated each time the field is written into the e-beam resist.  We define the ratio, $G$, as the field size, $F$, divided by the groove pitch size, $\sigma$.  For example, there will be $G=500/100=5$ grooves per field for $\sigma = 100 \; \mu$m and $F = 500 \; \mu$m.  The omnipresent field deformations will be imprinted into each field, repeating every 5 grooves.  The cyclically varying facet positions manifest as ghosts with G-fold symmetry. We expect $G-1$ inter-order ghosts, separated by a fraction $1/G$ of the inter-order separation.

\begin{figure}
\begin{center}
 \begin{tabular}{c}
    \includegraphics[width=0.6\textwidth]{chSPIE_2014_ebeam/figs/Field_stitching_errors_alt2.pdf}
   \end{tabular}
  \end{center}
  \caption[Field Stitching Error Cartoon]{\label{fig:FieldCartoon} An exaggerated cartoon to demonstrate the repetitive nature of field stitching.  A typical field size is about 300-500 $\mu$m on a side, and typical groove periods, $\sigma$, are about 20-100 $\mu$m (50-10 lines/mm groove frequencies).  Here we show 5 grooves per field.  The distortion shown in the cartoon is highly exaggerated, and in reality the calibration is much, much better than depicted.  The center positions in the distorted fields are distributed around the target, demonstrating field stitching errors.  The actual morphology of the distortion is not well characterized and should be mostly corrected by the 9300FS dynamic distortion correction system.  We have depicted a pincushion shape, though the realized morphology could be more like barrel distortion or a parallelogram.  The fields could also be perfectly square and simply misplaced in their center positions, still causing errors.  The details of the morphology give rise to differing relative levels of harmonics, in a Fourier sense.  To put the scale in perspective, we coarsely estimate the repetitive position error amplitude A (cf. eq. \ref{eqn:Periodic}) as about 5-50 nm from experiments on e-beam wafers.  Compare this minuscule position error with the $\sim500 \; \mu$m field size, to see that the fractional position error is 1 part in $10^4$ or better.}
\end{figure}

In principle it is possible to predict the ghost levels relative to the main diffraction peak, given some information about the magnitude and shape of the field distortion.  As the amplitude of the field distortion is dialed up, the grating ghost level increases approximately as Equation \ref{eqn:GLevel}.  In practice, we have not directly mapped the field distortion, which we expect to be a function of both $x $ and $y$.

\subsection{Employ multiple field sizes rather than one field size}
\label{sec:MultipleFields}
There are two strategies for mitigating ghosts.  One is to reduce the overall power in ghosts, using a single field size.  The other is to redistribute the power into different spatial scales, by using a variety of field sizes.  The strategies can be combined.

We redistribute the field power into several different spatial scales following the method described in Wilson et al. 2005\cite{2005SPIE.5720...68W}.  Rather than use a single field size, say 500 $\mu$m, we break up the field into several fields, say 500, 450, 400, and 350 $\mu$m.  We array the fields on the pattern in the following way.  We divide up the overall grating pattern, for example 30 mm $\times$ 85 mm, into eight long thin stripes of 3.75 mm $\times$ 85 mm.  We then array the long thin stripes on top of each other, cycling through the patterns twice.  So if we have patterns A, B, C, D, with unique field sizes, we cycle through from top to bottom: A, B, C, D, A, B, C, D.  The reason for this periodic boundary condition is to make sure that the circular beam samples the patterns in roughly equal proportions.  Specifically, if we had simply written four arrays of dimension 7.5 mm $\times$ 30 mm, indexed as A, B, C, D, then the circular beam would underfill patterns A and D at the bottom and top.  The optimal strategy would probably be to randomly array fields, but in practice randomly arraying is non-trivial in existing software.

One way to reduce the overall power in a single field size is to select a small field size, say $F=$ 200 $\mu$m.   We know that the e-beam field performance is better in the center, and deviates towards the edge of the field.  The tradeoff with this strategy is that the stage move time is long compared to the e-beam field deflector time, so the write duration increases.  Another strategy for reducing the power in ghosts attributable to a single field size is to improve the intra-field calibration.   We could remove, for example, the minute pincushion or barrel distortion familiar from cathode ray tube computer monitors.  In practice it is tricky to measure, and therefore correct for, these minuscule distortions.  The absolute best way to eliminate inter-order ghosts is to use a field size equal to the pitch.  The choice of $F= \sigma$ is generally cost prohibitive for $\sigma <100$.  If long, inefficient write times can be tolerated, then in principle there is no limit to this strategy.  It is conceivable that driving the stage so much would make the stage fail over time.

Another strategy for reducing the overall power in spatial distortions of e-beam fields is to experimentally determine the optimal height offset for the e-beam focus.  For an unknown reason, the JEOL 9300FS selects a default writing height which is offset from the optimal height.  We experimentally verified an offset which reduces the overall distortion in the fields.

Lastly, there are some slightly obscure JEOL e-beam commands relevant to ghost mitigation.  These are the ``overlay'', ``gather'', and other affiliated commands.  The main idea behind these writing strategies is to re-write over a patch of grating so that it sees different portions of the field, and therefore the field distortions average down.  We experimented with these techniques but found that they roughly double the write times with negligible performance benefit.

\subsection{Strategies for mitigating facet position errors attributable to large scale stage drift}

The largest scale in the e-beam writing hierarchy is the stage motion.  Multiple tests have never revealed significant wander or runout error in the interferometrically controlled stage.  Secular drift of the e-beam stage, however, can cause large-scale facet position errors which manifest as optical aberrations.

\subsection{Characterization of e-beam stage drift}
We characterized the e-beam stage drift with built-in JEOL commands.  Specifically, we used the \emph{DRIFT} and \emph{CURRENT} commands.  The \emph{DRIFT} command checks the position of the stage by scanning a precision gold cross mark mounted to the stage.  The process ties the actual position to the predicted position to the precision of the stage mark's centroid, which is a small fraction of the spot size.  We measured a precision of about 15 nm in the centroid process.  Having determined the amplitude and direction of the drift, the \emph{DRIFT} command subtracts out the offset and continues writing with its updated coordinates.

The centroiding \emph{DRIFT} process can be automatically repeated on a desired frequency.  We set a frequency of 10 minutes.  For a typical 20 hour write we achieve 120 drift corrections.  The JEOL software logs these corrections, so we can reconstruct the path of the drift, had we not taken action to correct it.  Figure \ref{fig:ebeamDrift} shows one of these reconstructions for sample E12.  The amplitude of the drift is  $\Delta x = $ 206 nm and $\Delta y = $ 341 nm.  This amplitude is much larger than we can tolerate for diffraction limited performance in immersion the near-IR.

\begin{figure}
\begin{center}
 \begin{tabular}{c}
    \includegraphics[width=0.4\textwidth]{chSPIE_2014_ebeam/figs/E12_drift_ebeam.png}
   \end{tabular}
  \end{center}
  \caption[Drift amplitude]{\label{fig:ebeamDrift} The reconstructed drift of the JEOL 9300FS e-beam stage during the patterning of sample E12.  The write time was 20.9 hours, with drift samples every 10 minutes.  The $x$ and $y$ components are separated and plotted as a function of time.  The top curve is the $y$ drift.  The curves begin at 0 at time zero, and show a range of motion of $\Delta x = $ 206 nm and $\Delta y = $ 341 nm.  This amplitude of drift would have been catastrophic for a grating which has line edge specifications of $\lambda/10 \sim 60 $ nm for diffraction limited performance in $J-$ band.  The JEOL9300FS command \emph{DRIFT} automatically corrects out this drift, so the maximum realized drift is merely the minuscule difference that occurs over the 10 minute interval between corrections.  Figures \ref{fig:E12igram} and \ref{fig:E09igram} show a direct comparison of prototype gratings patterned with and without drift correction.}
\end{figure}

A possible explanation for the beam drift is that there is thermal expansion attributable to heat conduction from the warm Si puck and holder unit into the stage.  Specifically, there is some evidence that the drift rate is largest at the beginning of the writing, perhaps while thermal equilibration is still happening.  The thermal probes on the stage lend some credibility to this idea, since the probes asymptote to constant value after a few hours.  Owing to this possibility, we recommend delaying the start of a write until the sample and holder have come into thermal equilibrium with the stage.  Beyond this thermal explanation, there are many conceivable reasons why there could be drift.  At some level we do not care, as long as we can correct it out sufficiently well.  The cost of correction is merely a hit in extended write time for the same written area, i.e. a decrease in efficiency.  We found roughly a 10\% overhead associated with drift checking.

\section{Results: Test gratings produced with e-beam patterning}

\subsection{Measurement of ghost levels for a variety of writing strategies}
\label{sec:MeasGhost}
In Figure \ref{fig:GhostLevelFig} we show measurements of inter order ghosts for different trial runs of the writing process with internal designations TJ03 and TJ04.  Each grating received a different treatment for e-beam field and/or subfield sizes.  The grating pattern details are listed in Table \ref{tab:TJ04details}.  The first thing to notice is that virtually all ghosts are below 10$^{-3}$ of the main peak.  Some ghosts were expected but not detected (denoted ND in the plot legend).  The non-detections are probably related to instrumental limitations, though upper limits are not available.

\begin{landscape}

\begin{table}
	\caption{Wafer TJ04 pattern details.  \label{tab:TJ04details}}
	\begin{tabular}{lllcccccccccc}
	\toprule
	 &   & & \multicolumn{10}{c}{Grating Area} \\
	\cmidrule(l){4-13}
	Size Scale & & Unit & A  & B & C & D & E & F & G &  H &  I & J\\
	\midrule
	\multirow{2}{*}{Pattern length}& (x) & mm &  \multicolumn{10}{c}{15} \\
	 & (y) & mm & \multicolumn{10}{c}{10} \\
	Pitch && $\mu m$ & \multicolumn{6}{c |}{100} &\multicolumn{4}{c}{25}  \\
	Linewidth && $\mu m$ & \multicolumn{6}{c |}{75} & \multicolumn{4}{c}{22.5}  \\
	\multirow{2}{*}{Field}&(x) & $\mu m$ & 100 &  200 & 200 & 200 & 500 & Multi & 100 & 200 & 500 & Multi \\
	&(y)& $\mu m$ & 500 & 500 & 100 & 250 &  500 & 500 & 500 & 500 &500 & 500\\
	Subfield && $\mu m$ & 2.5 & 2.5 & 4.0 & 4.0 & 2.5 & 2.5 & 2.5 & 2.5 & 2.5 & 2.5 \\
	Spot && nm & \multicolumn{10}{c}{$\sim300$} \\
	Step && nm & \multicolumn{10}{c}{50} \\
	\bottomrule
	\end{tabular}
\end{table}

\end{landscape}

\begin{figure}
\begin{center}
 \begin{tabular}{c}
    \includegraphics[width=0.8\textwidth]{chSPIE_2014_ebeam/figs/TJ04_ghosts_pretty_alt.pdf}
   \end{tabular}
  \end{center}
  \caption[Ghost level measurements]{\label{fig:GhostLevelFig} Measurements of the levels of inter-order ghosts for different trial runs of the writing process with internal designations TJ03 and TJ04.  The levels are normalized to the brightest order.  A full order is shown, with the $x-$axis units normalized to an order spacing.  The grating sub-areas of TJ04 are described in Table \ref{tab:TJ04details}.  Some ghosts are not detected, noted as ND.  The non-detections are due to instrumental limitations or genuine absence of ghosts.  The key idea here is that field size choice determines the number of- and to some extent the intensity of- inter order ghosts.  The absolute best patterning strategy is to set your $x-$field size equal to your groove pitch $\sigma$, as in TJ04A, which has no inter order ghosts.  All other patterns have a finite, albeit low, intensity ghost.  }
\end{figure}

\subsection{Improvement in wavefront performance from drift correction}
In Figures \ref{fig:E09igram} and \ref{fig:E12igram} we show the dramatic impact of drift correction on the performance of our Si gratings.  The stark difference in final wavefront error of the complete grating with drift correction and without drift correction is the ``smoking gun'' that the e-beam must have drift correction enabled to achieve high performance diffraction limited performance.  At the time of writing we have produced and tested another grating, G07, with even higher performance than E12.  Specifically, we perform interferometry at 632 nm in reflection with a 25 mm circular beam on a grating with a blaze angle of 71.6$^\circ$.  The measured wavefront error is $<0.10$ waves peak to valley for G07.

\begin{figure}
   \subfloat[E12 Interferogram]{\label{fig:E12igram}\includegraphics[height=5cm]{chSPIE_2014_ebeam/figs/E12_fig_scl2.pdf}}
   \newline
  \subfloat[E09 Interferogram]{\label{fig:E09igram}\includegraphics[height=5cm]{chSPIE_2014_ebeam/figs/E09_fig_scl2.pdf}}
  \caption[Interferometry reveals dramatic improvement in performance of e-beam produced immersion gratings]{Comparison of immersion grating surfaces on samples E09 and E12 measured with $\lambda = 632.8 $ nm interferometry.  These are both e-beam produced immersion grating surface prototypes.  The color scale is reported in fractions of waves of surface deviation.  The patterns on E09 and E12 are identical: $\sigma = $ 27.36 $\mu$m.  The groove top is not shadowed in these measurements which are taken in reflection in air.  The interferometry is performed with a 25 mm circular beam, which is projected over an 80 mm $\times$ 25 mm ellipse at the R3 echelle blaze angle, $\delta = 71.5 ^\circ$.  The left panel is the measured interferometry.  The middle panel is a decomposition into the first $\sim 80$ Zernike terms.  The right panel is the residual.  The only difference between the samples is that E12 was written with \emph{DRIFT} and \emph{CURRENT} check protocols with the JEOL e-beam writing software.  E09 was written without \emph{DRIFT} and \emph{CURRENT} check protocols.  The outcome is dramatic- E12 has $\sim 4$ times lower surface deformation than E09.  Note that the vertical color bars are on the same scale to ease visual comparison.}
  \label{fig:igrams}
\end{figure}

\section{Limitations of direct writing Si immersion gratings}
Electron beam lithography outperforms UV contact mask photolithography, at least in terms of the important metric of large scale phase coherence.  There are tradeoffs in pursuing e-beam lithography over UV contact mask photolithography.  We highlight some of these tradeoffs here.

\subsection{Serial write process yields long write times}
One key tradeoff is that e-beam lithography is a serial write process, whereas UV contact mask photolithography is a parallel write process.  A contact mask exposure takes about 1-2 minutes, whereas a e-beam exposure takes about 20 hours, for 30 mm $\times$ 80 mm patterns.  The problem is even worse if you scale to larger areas, for the next generation immersion gratings.  The high hourly expense of e-beam time makes the writing process the dominant expense over all other preparation steps, despite the high per-part cost of the large precision-oriented and optically polished monolithic Si pucks.

\subsection{Large per-part investment cost yields heightened process risk}
In reality, the expensive e-beam writing process is not more expensive than procuring a custom high precision vendor-provided photomask.  E-beam lithography simply has a higher per-part risk than UV contact mask photolithography.  Processes after the e-beam step better be low-risk.  Specifically, the processes after exposure include: discharge layer removal, development, plasma etching, wet etching, and shaping.  We find that plasma etching responds differently to thick samples, probably due to the large difference in strike height and dielectric differences between vacuum and Si.  In one case, an overactive plasma etch burned away all the e-beam resist on a 30 mm thick Si sample.

\subsection{Experiments with negative resist}
There is an steep tradeoff in precision and write time.  There is not much way around this tradeoff except for one recent idea of replacing positive tone resist with negative tone resist.  Recently we have experimented with low order Si immersion gratings with groove pitches on the order of $2 \; \mu$m (groove frequency $\sim500$ lines/mm), and and groove tops on the order of 100 nm.   The small pitch and groove top require a small spot size, and therefore a small step size.  We decreased our step size from 50 nm to 10 nm.  This change alone drives up the write time by a factor of 25.  To counteract the otherwise impossibly high write time, we have experimented with negative tone resist.  Negative resist is cleared where the resist is unexposed, and remains only where the resist is exposed.  Since the fill factor of written to unwritten is a factor of 20, the negative resist makes possible the e-beam lithography of these fine pitch patterns.

In principle these gains from negative resist could be extended to immersion echelles.  Specifically our typically modus operandi has been to clear about 65\% of the open area for an R3 echelle, in order to avoid groove top shadowing in immersion \cite{2012SPIE.8450E..2SG}.  However we could write an exceptionally thin line in negative resist, so long as the line is thick enough to survive wet etching without disintegration.  We estimate that this threshold is about 5\% of the groove pitch.

\section{Conclusions}
Electron beam lithography is now the highest precision technique for producing diffraction limited silicon immersion gratings.  The one performance disadvantage is the high level Rowland ghosts attributable to field stitching.  These errors have been mitigated by breaking up the field sizes into several different field sizes, distributing the power among more inter-order ghosts of lower individual power.  We can achieve 10$^{-3}$ suppression with this multi-field technique.  Ultimately science requirements will have to drive the performance demand of immersion gratings to inform how low to push the inter-order ghost level.  The optimal sizes for e-beam fields, subfields, spots, and steps are nuanced- we lay out rules that avoid repetitive errors.  One key innovation is the e-beam stage drift characterization and compensation.  The correction of stage drift resulted in a $>4\times$ reduction in peak to valley wavefront error in an R3 immersion echelle grating.  Future experiments with negative tone resists will probably decrease write time and increase performance.


\vssub
\subsubsection{~Third-order scheme (UQ)}
\opthead{UQ}{\ws}{H. L. Tolman}

\noindent
The \uq\ scheme for the $\theta$-space is implemented similar to the scheme
for physical space, with the exception that the closed direction space does
not require boundary conditions. The variable grid spacing in $k$-space
requires some modifications to the scheme as outlined by
\cite[{Appendix}]{art:Leo79}. Equations~(\ref{eq:quick_1}) through
(\ref{eq:quick_4}) then become

% ------ QUICKEST scheme for k space---------- %
% eq:quick_1k        Basic flux
% eq:quick_2k        Boundary value
% eq:quick_3k        Divergence
% eq:quick_4k        CFL number

\begin{equation}
\cF_{m,-} = \left [ \dot{k}_{g,b} \: N_b \: \right ]^n_{i,j,l}
\: , \label{eq:quick_1k}\end{equation} \begin{equation}
\dot{k}_{g,b} = 0.5 \: \left ( \dot{k}_{g,m-1} + \dot{k}_{g,m}
\: \right )  \: , \label{eq:quick_1ak}
\end{equation} \begin{equation}
N_b = \frac{1}{2} \left [ \rule[0mm]{0mm}{\baselineskip} \:
(1+C)N_{i-1} + (1-C)N_i \: \right ] - \:
\frac{1-C^2}{6} \: {\cal CU} \: \Delta k^2_{m-1/2}, \label{eq:quick_2k} \end{equation} \begin{equation}
{\cal CU} =  \left \{ \begin{array}{ccc}
\frac{1}{\Delta k_{m-1}}
\left [ \frac{N_{ m }-N_{m-1}}{\Delta k_{m-1/2}} -
        \frac{N_{m-1}-N_{m-2}}{\Delta k_{m,-3/2}} \right ]
               & \mbox{for} & \dot{k}_b \geq 0 \\
\frac{1}{\Delta k_m}
\left [ \frac{N_{m+1}-N_{ m }}{\Delta k_{m+1/2}} -
       \frac{N_{ m }-N_{m-1}}{\Delta k_{m-1/2}} \right ]
               & \mbox{for} & \dot{k}_b   <  0
\end{array} \right . \: , \label{eq:quick_3k}
\end{equation} \begin{equation}
C = \frac{\dot{k}_{g,b} \: \Delta t}{\Delta k_{m-1/2}}
\: , \label{eq:quick_4k} \end{equation}

\noindent
where $\Delta k_m$ is the discrete band or cell width at grid point $m$, and
where $\Delta k_{m-1/2}$ is the distance between grid points with counters $m$
and $m-1$. The \ult\ limiter can be applied as in Eqs.~(\ref{eq:ult_1})
through (\ref{eq:ult_4}), if the \cfl\ number of Eq.~(\ref{eq:quick_4k}) is
used. At the low- and high-wavenumber boundaries the fluxes again are
estimated using a first-order upwind approach, with boundary conditions as
above defined for the first-order scheme. The final scheme in $k$-space
becomes

% eq:1uq_k_tot

\begin{equation}
N_{i,j,l,m}^{n+1} = N_{i,j,l,m}^n
 + \frac{\Delta t}{\Delta k_m} \left [ \cF_{m,-} - \cF_{m,+} \right ]
\: , \label{eq:uq_k_tot} \end{equation}


\section{Output Size}
\label{sec:value-size}

In Sophie, the protocol parameter $\var{minUTxOValue}$ is used to
disincentivize attacking nodes by putting many small outputs on the
UTxO, permanently blocking memory. Because members of the $\Value$
type can be arbitrary large, the ledger requires a $\UTxO$ entry to
contain a minimum amount of Bcc, proportional to its size.

There is also another $\Value$ size consideration with respect to spendability
of an output. The restriction on the total serialized size of the transaction (set
by the parameter $\var{maxTxSize}$) serves as an implicit upper bound on the
size of a $\Value$ contained in an output of a transaction. Without tighter
limits on the output $\Value$ size, one of the following situations could arise,
causing the output to be come unspendable (these are just a two examples) :

\begin{itemize}
  \item The script locking the very large $\Value$-containing UTxO is too large
  to fit inside the transaction alongside the $\Value$ itself while still respecting
  the max transaction size
  \item The large $\Value$ cannot be split into several outputs, because the
  outputs are impossible to fit inside a single transaction
\end{itemize}

Figure \ref{fig:size-helper} contains abstract and helper functions
used in calculating the in-memory and serialized representation
sizes of $\Value$ terms.

\begin{figure*}[h]
  \emph{Abstract Functions}
  %
  \begin{align*}
    & \fun{serSize} \in \Value \to \MemoryEstimate \\
    & \text{Gives the size of the serialized representation of a $\Value$}
    \nextdef
    & \fun{anameLen} \in \AssetName \to \MemoryEstimate \\
    & \text{Returns the length (in bytes) of an asset name}
  \end{align*}
  %
  \emph{Helper Functions}
  \begin{align*}
    & \fun{numAssets} \in \Value \to \N \\
    & \fun{numAssets}~{vl}~=~\|~\{~(pid, an)~\vert~pid~(\mapsto~(an~\mapsto~\wcard))~\in~vl~\}~\| \\
    & \text{Returns the number of distinct asset IDs in a $\Value$}
    & \nextdef
    & \fun{sumALs} \in \Value \to \N \\
    & \fun{sumALs}~{vl}~=~ \sum_{\{~an~\vert~\wcard~(\mapsto~(an~\mapsto~\wcard))~\in~vl~\}} \fun{anameLen}~an \\
    & \text{Returns the sum of the lengths (in bytes) of distinct asset names in a $\Value$}
    & \nextdef
    & \fun{numPids} \in \Value \to \N \\
    & \fun{numPids}~{vl} ~=~ \|~\supp~{vl}~\| \\
    & \text{The number of policy IDs in a $\Value$}
  \end{align*}
  \caption{Value Size}
  \label{fig:size-helper}
\end{figure*}

The function $\fun{serSize}$, unlike the functions $\fun{size}$ and $\fun{utxoEntrySize}$
    (explained below), is left abstract. It returns the actual number of bytes a $\Value$
    occupies in the serialized transaction (and hence is implementation-dependent).

    One reason for this design decision is that the $\fun{serSize}$ function is used constrain
    the serialized representation of the transaction (in particular, the size
    of $\Value$ terms in outputs), whereas the min-Bcc requirement is about
    the in-memory representation size. Moreover, a transparently-calculated size estimate
    is not necessary for limiting the size of values in outputs, since this size-bound
    check does not place any additional accounting/monetary constranits on transaction construction,
    unlike the min-Bcc requirement.

Figure \ref{fig:min-val-calc} gives the types of constants used in the estimation
of the size of a UTxO entry, and the associated min-Bcc-value.

\begin{figure*}[h]
  \emph{Constants}
  \begin{equation*}
    \begin{array}{lcl}
      (k_0, k_1, k_2, k_3, k_4) & \in & \N \times \N \times \N \times \N \times \N \\
      \mathsf{UtxoEntrySizeWithoutVal} & \in & \MemoryEstimate \\
      \mathsf{BccOnlyUTxOSize} & \in & \MemoryEstimate \\
      \mathsf{MaxValSize} & \in & \MemoryEstimate \\
    \end{array}
  \end{equation*}
  %
  \emph{Size and Min-Bcc Functions}
  \begin{align*}
    & \fun{size} \in \Value \to \MemoryEstimate \\
    & \fun{size}~\var{vl} ~=~
    \begin{cases}
      k_0 & \fun{bccOnly}~vl~=~vl \\
      k_1 + \lfloor~ (((\fun{numAssets}~vl) * k_2) + (\fun{sumALs}~vl) & \\
      ~~~~~~ + ((\fun{numPids}~vl) * k_3) + (k_4 - 1)))~ /~ k_4~\rfloor & \text{otherwise} \\
    \end{cases} \\
    & \text{Calculate the size of a $\Value$}
    \nextdef
    & \fun{bccPerUTxOWord}~\in \PParams \to \Coin \\
    & \fun{bccPerUTxOWord}~pp = \lfloor~ (\fun{minUTxOValue}~pp~/~ \mathsf{bccOnlyUTxOSize})~ \rfloor \\
    & \text{Calculate the cost of storing a memory unit of data as a UTxO entry}
    \nextdef
    & \fun{utxoEntrySize} \in \TxOut \to \MemoryEstimate \\
    & \fun{utxoEntrySize}~\var{out} = \mathsf{utxoEntrySizeWithoutVal} + \fun{size}~ (\fun{getValue}~out) \\
    & \text{Calculate the size of a UTxO entry}
\end{align*}
\caption{Value Size}
\label{fig:min-val-calc}
\end{figure*}

The $\fun{size}$ function returns the estimated size of a $\Value$ term. It is constant in the
case where the value contains only Bcc. If there are other types of tokens in the
term, the size depends on

\begin{itemize}
  \item the number of distinct asset types (asset IDs)
  \item the number of distinct policy IDs, and
  \item the sum of the lengths of distinct asset names of the tokens.
\end{itemize}

The parameter $\fun{minUTxOValue}$ specifies the min-Bcc value for a UTxO containing
only Bcc. This type of UTxO varies in size somewhat (eg. Cole style addresses
may be a different length than Sophie ones), but we estimate the size of the most commonly
used type of Bcc-only UTxO as the constant value $\mathsf{bccOnlyUTxOSize}$.
This constant is in fact an upper bound on UTxOs which have have only Sophie credentials.

We use this size estimate
to calculate what $\fun{minUTxOValue}$ implies to be the min-Bcc value requirement
\emph{per word} of UTxO data.

The function $\fun{bccPerUTxOWord}$ performs this calculation by dividing the
min-Bcc value by the Bcc-only UTxO size.

The $\mathsf{utxoEntrySizeWithoutVal}$ is the constant representing
the size of a UTxO entry, not counting the size of the $\Value$ term it contains.
Here, again, the actual size of a UTxO (excluding the $\Value$) can vary, but
we use an upper bound on the size of Sophie-credential UTxOs.

The function $\fun{utxoEntrySize}$ estimates the size of an arbitrary SophieMA-era
UTxO. It adds the size estimate of the $\Value$ term in a UTxO and the
$\mathsf{utxoEntrySizeWithoutVal}$ constant.

The constants used in the implementation of the Aurum era are as follows :

\begin{itemize}
  \item $(k_0, k_1, k_2, k_3, k_4) = (2, 6, 12, 28, 8)$
  \item $\mathsf{utxoEntrySizeWithoutVal} = 27$ words (8 bytes)
  \item $\mathsf{bccOnlyUTxOSize} = 27$ words (8 bytes)
  \item $\mathsf{MaxValSize} = 4000$ bytes, ie. 500 words.
\end{itemize}


\chapter{Annoyances}

\section{mathematics}

\section{computation}

\subsection{Java}
\lstset{language=Java}

Generics

Auto boxing/unboxing.

Sorted collections can't handle partial ordering.

BigDecimal.valueOf(x).doubleValue() != x.

\subsection{Clojure}
\lstset{language=Clojure}

Standard math notation:
enumerated finite set: $\Set{S} = \{0, 1, 2\}$
and cardinality $\#\{0, 1, 2\}
\rightarrow 3$.

\lstinline|#{0 1 2}| $\rightarrow$ \lstinline|java.util.Set|
\lstinline|(count #{0 1 2})| $\rightarrow$
\lstinline|3|.

and
\lstinline|{:x 1 :y 2}| $\rightarrow$ \lstinline|java.util.Map|.

(double (rationalize (double x))) != (double x)

Transducers compose in the reverse direction from functions:

\lstinline|((comp f g) x)| $\rightarrow$
\lstinline|(f (g x))|, but

\lstinline|((comp (filter f) (map m) (reduce r)) s)| $\rightarrow$
\lstinline|(reduce r (map m (filter f s)))|, or, to make clearer

\lstinline|((comp (partial reduce r) (partial map m) (partial filter f)) s)|
$\rightarrow$ \lstinline|(reduce r (map m (filter f s)))|.