%!TEX root = ../main.tex

\section{Dielectric Laser Acceleration}

In the public sphere, particle accelerators most commonly conjure images of giant facilities for performing particle physics experiments, such as the Large Hadron Collider.
However, in fact, most particle accelerators are used in other applications, such as radiotherapy, X-ray generation, and ion implantation for semiconductor device fabrication \cite{england2014dielectric}.
Conventional radio-frequency (RF) accelerators use a metal or superconducting cavity, driven with microwave radiation, to provide sustained acceleration to charged particles traversing the structure.
However, the amount of achievable acceleration per unit length is fundamentally limited by the material breakdown and damage limit of the cavity.
Therefore, for an accelerator already driven at its damage threshold, the only option to achieve high total energy gains from an accelerator is to make the device longer.
The largest current particle accelerators reach several of kilometers in length, requiring substantial resources to operate and maintain.

Dielectric laser acceleration (DLA) is an emerging method that seeks to revolutionize particle accelerator technology by exploiting the decades of progress in nanofabrication, materials science, and laser technology.
In DLA, instead of using metal structures driven by microwaves, dielectric structures are illuminated with infrared laser light, which creates an electromagnetic field pattern in their vicinity that may accelerate electrically charged particles, such as electrons.
When compared to metal surfaces at microwave frequencies, dielectric materials have very high damage thresholds at short pulse durations and infrared wavelengths \cite{mcneur2016elements, soong2012laser}.
This fact allows DLAs to achieve energy gains per length that are between 10 to 100 times higher than those found in conventional radio frequency (RF) accelerators.

Experimental demonstrations of these acceleration gradients have been made practical in recent years by the availability of robust nanofabrication techniques combined with modern solid state laser systems \cite{dawson2008analysis}.
As a result, the development of DLA may lead to compact particle accelerators that enable new applications.
By providing the potential for generating relativistic electron beams in relatively short length scales, DLA technology is projected to have numerous applications where tabletop accelerators may be useful, including medical imaging, radiation therapy, and X-ray generation \cite{plettner2008microstructure,england2014dielectric}.

Several recently demonstrated candidate DLA structures consist of a planar dielectric structure that is periodic along the particle axis with either an semi-open geometry or a narrow (micron to sub-micron) vacuum gap in which the particles travel \cite{plettner2006proposed, peralta2013demonstration, mcneur2016elements, leedle2015dielectric, chang_silicon_2014, breuer2014dielectric, breuer2014dielectric2, kozak2016dielectric}.
These structures are then side-illuminated by laser pulses.
\fig{DLA_def} shows a schematic of the setup, with a laser pulse incident from the bottom.

\figdef{DLA_definition.pdf}{DLA_def}{
    Diagram outlining the system setup for side-coupled DLA with an arbitrary die,lectric structure $\eps(x,y)$ (green).
    A charged particle moves through the vacuum gap with speed $\beta c_0$.
    The periodicity is set at $\beta \lambda$ where $\lambda$ is the central wavelength of the laser pulse.
}

The laser field may also be treated with a pulse front tilt \cite{hebling1996derivation, akturk2004pulse} to enable group velocity matching over a distance greater than the laser's pulse length.

\section{Adjoint Method for Accelerator}

To achieve high energy gain in a compact size, it is of principle interest to design structures that may produce the largest acceleration gradients possible without exceeding their respective damage thresholds.
Here we will discuss the use of the adjoint method and inverse design to design such a structure, as explained originally in Ref. \citenum{hughes_method_2017}.
To begin, we must first define the optimization figure of merit and design parameters.

\subsection{Mathematical Definition}

We first seek to maximize the \textit{acceleration gradient} of the device, which is defined as the amount of energy gain per unit length achieved by a particle that is phased correctly with the driving field.
For acceleration to occur, the dielectric structure must be designed such that the particle feels an electric field that is largely parallel to its trajectory over many optical periods.
Here we consider framing an optimization problem to maximize the acceleration gradient, which take as our figure of merit (labelled $J$ in previous discussions).
In a general DLA device, the acceleration gradient `$G$' over a time period `$T$' is defined mathematically as
%
\eqdef{Gintro}{
    G = \frac{1}{T}\int_0^{T}{ E_{||}(\vr(t),t)\ dt},
}
%
where $\vr(t)$ is the position of the electron over time and $E_{||}$ signifies the (real) electric field component parallel to the electron trajectory.

Since we assume the structure is invariant in the $\hat{z}$ direction, we may work in two dimensions, examining only the $H_z$, $E_x$ and $E_y$ field components.
While this approximation neglects fringing fields that will be present in any fabricated device, it is a good approximation for the fields experienced by particles traversing the center of the acceleration channel.
For an approximately monochromatic input laser source with angular frequency $\omega$, the electric fields are, in general, of the form
%
\eqdef{}{
    \vE(\vr,t) = \real{\tE(\vr)e^{i\omega t}},
}
where $\tE$ is complex-valued.
In the following chapter we discuss the generalization of this analysis to broadband light.

Let us assume the particle we wish to accelerate is moving on the line $y=0$ with velocity $\vec{v} = \beta c_0 \hat{x}$, where $c_0$ is the speed of light in vacuum and $\beta \leq 1$.
The $x$ position of the particle as a function of time is given by $x(t) = x_0 + \beta c_0 t$, where $x_0$ represents an arbitrary choice of initial starting position.
For normal incidence of the laser (laser propagating in the $+\hat{y}$ direction), phase velocity matching between the particle and the electromagnetic fields is established by introducing a spatial periodicity in our structure of period $\beta \lambda$ along $\hat{x}$ , where $\lambda$ is the laser wavelength.
In the limit of an infinitely long structure (or equivalently, $T \to \infty $) we may rewrite our expression for the gradient in Eq. (\ref{eq:Gintro}) as an integral over one spatial period, given by
%
\eqdef{}{
    G = \frac{1}{\beta\lambda}\real{ e^{-i\phi_0}\int_0^{\beta\lambda}{dx \ }E_x(x,0)e^{i\frac{2\pi}{\beta\lambda}x}}.
}
%
Here the quantity $\phi_0 = \frac{2\pi x_0}{\beta\lambda}$ is representative of the phase of the particle as it enters the spatial period.
In further calculations, we set $\phi_0 = 0$, only examining the acceleration gradients experienced by particles entering the accelerator with this specific phase.
Since we have arbitrary control over our input laser phase, this does not impose any constraint on the acceleration gradient attainable.

To simplify the following derivations, we define the following inner product operation involving the integral over two vector quantities $\va$ and $\vb$ over a single period volume $V'$
%
\eqdef{}{
    \bracket{\va}{\vb} = \int_{V'} dv
    \left(\va \cdot \vb \right) = \int_0^{\beta\lambda}dx\int_{-\infty}^\infty dy \left(\va\cdot\vb\right).
}
%
With this definition, we then may express the gradient simply as
%
\eqdef{G}{
    G = \real{\bracket{\vE}{\veta}},
}
%
where we define the vector field `$\veta$' to signify the position and phase of the moving electron as
\eqdef{}{
    \veta(x,y) = \frac{1}{\beta\lambda}e^{i\frac{2\pi}{\beta\lambda}x}\delta(y)\hat{x}.
}
The physical interpretation of $\veta$ is digrammed in \fig{eta_def}.

\figdef{DLA_eta_definition.png}{eta_def}{
    Definition of the vector field, $\veta$, which defines the position of the electron in the frequency domain.
    The green regions represent domains where we will optimize the material properties using the adjoint method.
    The central gap is constrained to vacuum to allow passage of the electron beam.
    The red arrow signifies the driving laser.
}

Our goal in designing the accelerator for maximum acceleration gradient is to create a permittivity distribution that maximizes $G$ subject to a few constraints.
We assume geometry of the DLA structure is represented by a spatially varying dielectric constant $\eps(x,y)$.
As mentioned, we assume invariance in one coordinate ($\hat{z}$) in keeping with the planar symmetry of most current designs.
However the methodology we present can be extended to include a third dimension.
We consider performing this optimization in a small design region surrounding a small gap defined for the electron to travel through the structure.
Secondly, we assume that the structure has a finite extent along the direction of the incoming laser beam.
We also consider realizing this device through the patterning of a material with permittivity $\eps_\textrm{max}$.
Therefore, the final device should have permittivity of either 1 or $\eps_\textrm{max}$ at all points.

To perform this optimization task, we discretize our entire spatial domain into a rectangular grid, which will be necessary for numerical simulation.
We define our design parameters, $\bfphi$, as the relative permittivity of each grid cell within the design region.
Our problem then becomes finding the permittivity of each cell that will maximize the acceleration gradient, subject to each grid cell having a permittivity value of either 1 or $\eps_\textrm{max}$.

To accomplish this, the most naive approach would involve performing a direct search over the full design space.
For example, one could label each cell within the design region with an identifier `0' or `1' corresponding to `vaccuum' and `material', respectively.
Then, one would generate all possible structures and check their respective acceleration gradients.
However, this method would be far too computationally expensive to perform in practice.
For example, even considering a very small design region consisting of 10 $\times$ 10 = 100 grid cells would result in $2^{100} \approx 10^{30}$ device simulations, which is far too many to realistically perform.
While one may consider more efficient ways of searching through this device space without checking each structure, for example using global optimization approaches such as genetic algorithms \cite{whitley_genetic_1994} or particle swarm optimization \cite{noauthor_particle_nodate}, this problem is still quite computationally expensive and the size of design space becomes exponentially larger as the number of design parameters are increased.

As mentioned, a more effective approach involves performing $\textit{gradient-based optimization}$, in which we search the design space according to the local gradient of the figure of merit with respect to each of the parameters.
For example, we may start with an initially random device, compute how the performance will change with respect to a change in the permittivity of each cell in the design region, and make a small update.
This process may be repeated until convergence on a locally optimal solution.
If the design space contains several local optima, then this whole process may be repeated several times with different initial conditions.

For gradient-based optimization to be useful, one would like an efficient means to compute the gradient of the figure of merit with respect to the design parameters.
For photonic devices, one may achieve this using the \textit{adjoint method}, which allows one to analytically compute the gradient directly from Maxwell's Equations and evaluate the result with only one additional electromagnetic simulation.
This remarkable efficiency is largely responsible for the success of inverse design in photonics.

\subsection{Adjoint Formalism}

The adjoint method is typically introduced for linear optical systems, although, as we will show in a later chapter, it may be extended to nonlinear systems without much additional complication.
In the frequency domain, Maxwell's equations may be written as
%
\eqdef{FDFD_analytical}{
    \dcurl \vE (\vr)\ -\ k_0^2\ \eps_r(\vr)\ \vE(\vr) \equiv A\vE(\vr) = -i\mu_0\omega\vJ(\vr),
}
%
Here, $\vE(\vr)$ and $\vJ(\vr)$ are the electric field and electric current distributions, respectively. $k_0 = \omega/c_0$, $\eps_r$ is the relative permittivity and a non-magnetic material is assumed ($\mu = \mu_0$).
\eq{FDFD_analytical} can be solved with the \textit{finite-difference frequency-domain} (FDFD) method \cite{shin2012choice, taflove2000computational}, where both the structure and the fields are discretized on a finite-difference grid.

More abstractly, we may write \eq{FDFD_analytical} as
%
\eqdef{FDFD_simple}{
    A \bfx = \bfb,
}
%
where $A$ is a sparse, complex symmetric matrix that encodes Maxwell's equations in the presence of the device.
$\bfx$ is a vector containing the electromagnetic fields at each position in the domain, which are the solution to \eq{FDFD_simple} given the vector $\bfb$ describing the electric current source distribution in the domain.
When the number of grid points is small, \eq{FDFD_simple} is typically solved using lower-upper (LU) decomposition techniques.
However, in several cases, it must be solved using iterative methods instead \cite{shin2012choice}.

Our device is described by a set of design variables $\bm{\phi}$, which influence the system matrix, $A = A(\bfphi)$.
Differentiating \eq{FDFD_analytical} with respect to $\bfphi$, and assuming that the current source, $\bfb$, does not depend on $\bfphi$, we may recover the change in the solution with respect to the parameters as
%
\eqdef{dEdgamma}{
    \ddfrac{\bfx}{\bfphi} = -\invA \pfrac{A}{\bfphi} \invA \bfb = -\invA \pfrac{A}{\bfphi}\bfx
}

Now, we consider differentiating an objective function $J = J(\bfx)$ that depends explicitly on the field solution.
By the chain rule, this gives
%
\eqdef{dGdgamma_2}{
    \ddfrac{J}{\bfphi} =
    - \real{ \pfrac{J}{\bfx} \ddfrac{\bfx}{\bfphi} } = 2 \real{ -\pfrac{J}{\bfx} A^{-1} \pfrac{A}{\bfphi} \bfx }.
}
We note that the factor of $2\real{\cdot}$ comes from the fact that $\bfx$ is complex-valued, and therefore in taking the derivative of (real-valued) $J$, one must consider the dependence on both $\bfx$ and $\bfx^*$.

To evaluate \eq{dGdgamma_2}, we define a second simulation with source term $-\pfrac{J}{\bfx}^T$,
%
\eqdef{adjoint_source}{
    A^T\bfx_\aj = A\bfx_\aj = -\pfrac{J}{\bfx}^T,
}
where we have used the fact that $A$ is symmetric.
Then, the field solution, $\bfx_\aj = -A^{-1}\pfrac{J}{\bfx}^T$, can be easily identified in \eq{dGdgamma_2}, which gives the expression
%
\eqdef{final_form_DGdgamma}{
    \ddfrac{G}{\bfphi} = 2 \real{ \bfx_\aj^T \pfrac{A}{\bfphi} \bfx }.
}
%
The only quantity in this expression that depends on the parameter $\bfphi$ is $\pfrac{A}{\bfphi}$.
As we will soon discuss, this quantity will generally be trivial to compute.
On the other hand, the full field calculations of $\bfx$ and $\bfx_\aj$ are computationally expensive, but may be computed once and used for an arbitrarily large set of parameters $\bfphi_i$.
This gives the adjoint method a significant scaling advantage with respect to traditional direct sensitivity methods, such as the numerical, 'finite-difference' differentiation approach, in which each parameter is independently perturbed a small amount and the resulting change in objective function is measured.

Previously, we expressed the acceleration gradient as the inner product of the electric fields $\vE(\vr)$ and our vector field $\veta(\vr)$ as
%
\eqdef{G2}{
    G = \real{\bracket{\vE}{\veta}},
}
%
which we may express in matrix notation as
%
\eqdef{G2}{
    G = \real{\bfeta^T \bfx},
}
%
where $\bfeta$ is a vector representing $\veta$ on the finite difference grid and $\bfx$ is a vector containing the electric fields, as before.

In this notation, the adjoint problem is therefore
%
\eqdef{adjoint_DLA}{
    A^T \bfx_\aj = -\pfrac{G}{\bfx}^T = -\bfeta.
}
%

\subsection{Interpretation of the Adjoint Field as Radiation}

Intuitively, the adjoint source, $-\bfeta$, represents a line of electric current located at the central gap where the accelerator is traversing the structure.
To make this connection to radiation more explicit, let us now consider the fields radiated by a point particle of charge $q$ flowing through our domain at $y = 0$ with velocity $\vec{v} = \beta c_0 \hat{x}$.
In the time domain, we can represent the current density of this particle as
%
\eqdef{point-current-setup}{
    \vJ_\textrm{rad}(x,y;t) = q \beta c_0 \delta(x-x_0-c_0\beta t)\delta(y)\hat{x}.
}
%
To express this in the frequency domain, we take the Fourier transform of $\vJ_\textrm{rad}$ with respect to time, giving
%
\begin{align}
    \vec{J}_{rad}(x,y;\omega) &= q \beta c_0 \delta(y)\hat{x}\int _{-\infty}^{\infty}{dt\ }\exp(i\omega t)\delta(x-x_0-c_0\beta t)\\
    &= q\ \exp\Big(i\frac{\omega\ (x-x_0)}{c_0 \beta}\Big)\delta(y)\hat{x}\\
    &= q\ \exp\Big(i\frac{2\pi}{ \beta\lambda}x\Big)\ \exp(-i\phi_0)\delta(y)\hat{x}.
\label{eq:point-current}
\end{align}
%
Comparing with the source of our adjoint problem, $\vJ_\aj = \frac{-i}{\omega\mu_0}\veta$, we see that
%
\eqdef{J-eta}{
    \vec{J}_{aj} = \frac{-i\ \exp(i\phi_0)}{2\pi q\beta c_0\mu_0}\vJ_\textrm{rad}.
}

This finding shows that the adjoint field solution ($\vE_\aj$) corresponds (up to a complex constant) to the field radiating from a test particle flowing through the accelerator structure.
To put this another way, in order to calculate the acceleration gradient sensitivity with the adjoint method, we must simulate the same structure operating both as an accelerator ($A\vE=-i\omega\mu_0\vJ_\textrm{acc}$) and as a radiator ($A\vE_\aj=-i\omega\mu_0\vJ_\aj$).

It is understood that one way to create acceleration is to run a radiative process in reverse.
Indeed, this is the working principle behind accelerator schemes such as inverse free electron lasers \cite{musumeci2005high, courant1985high}, inverse Cherenkov accelerators \cite{kimura1995laser, fontana1983high}, and inverse Smith-Purcell accelerators \cite{bae1992experimental, mizuno1987experimental}.
Here, we see that this relationship can be expressed in an elegant fashion using the adjoint method.

\subsection{Application to Design Parameters}

To test our adjoint formalism, we examine a simple accelerator geometry composed of two opposing dielectric squares each of relative permittivity $\epsilon$.
We take a single $\phi$ parameter to be the relative permittivity of the entire square region.
Because we only change the region inside the dielectric square, we may identify the $\pfrac{A}{\bfphi}$ operator from \eq{FDFD_analytical} as
%
\eqdef{dAdepsilon}{
    \ddfrac{A}{\epsilon}(\vr) = \Bigg\{
    \begin{array}{ll}
        -2k_0^2 &\textrm{if } \vr \textrm{ in square} \\
        0 &\textrm{otherwise}
    \end{array}.
}

Thus, given the form of the sensitivity of the acceleration gradient from \eq{final_form_DGdgamma}, combined with \eq{dAdepsilon}, the change in acceleration gradient with respect to changing the entire square permittivity is simply given by the integral of the two field solutions over the square region, labeled `$sq$'
%
\eqdef{}{
    \ddfrac{G}{\epsilon_{sq}} = -2k_0^2 \ \real{\int_{sq}{d^2\vr}.
    \vE(\vr) \cdot \vE_\aj(\vr)}.
}

In Fig. \fig{DLA_test} we compare this result with the direct sensitivity calculation where the system is manually changed and simulated again, using a finite difference derivative.
The two methods agree with excellent precision, which confirms that the adjoint formalism is giving the correct results.

\figdef{DLA_test}{DLA_test}{
    Demonstration of adjoint method in calculating accelerator sensitivities.
    (a) The acceleration gradient ($G$) of a square accelerator structure (inset) as a function of the square's relative permittivity.
    We express the acceleration gradient in its dimensionless form, normalized by the electric field amplitude of the incident plane wave $(E_0)$.
    The particle traverses along the dotted line with a velocity of $c_0$ ($\beta = 1$) and a plane wave is incident from the bottom of the structure.
    (b) The sensitivity $\ddfrac{G}{\epsilon}$ of the gradient with respect to changing the square relative permittivity for direct central difference (solid line) $\ddfrac{G}{\epsilon} = \frac{G(\epsilon+\Delta\epsilon)-G(\epsilon-\Delta\epsilon)}{2\Delta\epsilon}$ and using the adjoint method (circles).
    The two calculations agree with excellent precision.
    The dotted line at $\ddfrac{G}{\epsilon}=0$, corresponds to local minima and maxima of $G(\epsilon)$ above.
}

Extending this example to the general case of perturbing the permittivity at an arbitrary position $\vr$, we see that
%
\begin{align}
    \ddfrac{G}{\epsilon}(\vr) &= -k_0^2 \ \real{ \int{d^2\vr'}.
    \vE(\vr') \cdot \vE_\aj(\vr')~
    \delta(\vr-\vr') } \\
    &= -2k_0^2 \ \real{ \vE(\vr) \cdot \vE_\aj(\vr) }.
\end{align}
%
\section{Inverse Design of Accelerator}

\subsection{Maximization of Acceleration Gradient}

With the mathematical form of the adjoint problem discussed, now we focus on the optimization and inverse design of the DLA device.
In our FDFD simulation, we use a grid spacing that corresponds to 200 grid points per free space wavelength in each dimension.
Perfectly matched layers are implemented as absorbing regions on the edges parallel to the electron trajectory, with periodic boundary conditions employed on boundaries perpendicular to the electron trajectory.
A total-field scattered-field \cite{taflove2000computational} formalism is used to create a perfect plane wave input for the acceleration mode.

Since the adjoint method gives us a highly efficient method to calculate $\ddfrac{G}{\epsilon_{i}}$, we use this information in an iterative optimization procedure.
During each iteration, we first calculate $\ddfrac{G}{\epsilon_{i}}$ for all pixels `$i$' within some specified design region.
Then, we update the $\epsilon_i$ of each grid cell as follows
%
\eqdef{}{
    \epsilon_{i} := \epsilon_{i} + \alpha\ddfrac{G}{\epsilon_{i}}.
}
%
Here, $\alpha$ is a step parameter that we can tune.
We need $\alpha$ to be small enough to find local maxima, but large enough to have the optimization run in reasonable amount of time.
This process is repeated until convergence on $G$, as diagrammed in \fig{opt_loop}.

\figdef{DLA_optimization_routine.png}{opt_loop}{Optimization routine for DLA.}

During the course of optimization, the permittivity distribution is considered as a continuous variable, which is not realistic in physical devices.
To address this issue, we employ a permittivity capping scheme during optimization.
We define a maximum permittivity `$\epsilon_m$' corresponding to a material of interest.
During the iterative process, if the relative permittivity of any cell becomes either less than $1$ (vacuum) or greater than $\epsilon_m$, that cell is pushed back into the acceptable range.
It was found that with this capping scheme, the structures converged to binary (each pixel being either vacuum or material with a permittivity of $\epsilon_m$) after a number of iterations without specifying this choice of binary materials as a requirement of the optimization.
Therefore, only minimal post-processing of the structures was required.
Since high index contrast is favorable for maximizing the acceleration gradient, the optimization often favors increasing index contrast within the structure, which leads to each pixel being pushed towards either $1$ or $\epsilon_m$.
This is a possible explanation for why the structures converge to binary distributions under our optimization procedure.

The results of this optimization scheme are shown in Figs. \ref{fig:optimization-results_beta0.5}(b)-\ref{fig:optimization-results_beta0.5}(d) for three different $\epsilon_m$ values corresponding to commonly explored DLA materials.
The design region was taken to be a rectangle fully surrounding but not including the particle gap.
The design region was made smaller for higher index materials, since making it too large led to divergence during the iteration.
We found that a totally vacuum initial structure worked well for these optimizations.
However, initially random values between 1 and $\epsilon_m$ for each pixel within the design region also gave reasonable results.
For materials of Si, Si$_3$N$_4$, and SiO$_2$, the achieved gradients (normalized by the incident field, $E_0$) were 0.90, 0.56, and 0.31 ($E_0$), respectively.
Assuming incident field values consistent with the laser damage thresholds given in Ref. \cite{soong2012laser}, these correspond to acceleration gradients of 0.25, 0.83, and 1.33 $\textrm{GV}\,\textrm{m}^{-1}$, respectively.
Without the dielectric mirrors, these structures give normalized acceleration gradients of 0.28, 0.15, and 0.07 ($E_0$), respectively.
For comparison, the Si dual pillar structures presented in Ref. \cite{leedle2015dielectric} give gradients of around 0.3 $(E_0)$.
Therefore, the adjoint optimized structures show about a three-fold improvement in acceleration gradient over established structures.

\figdef{DLA_Adjoint.png}{optimization-results_beta0.5}{
    Demonstration of the structure optimization for $\beta=0.5$, laser wavelength $\lambda=2\,\mu$m, and a gap size of $400$\,nm.
    A plane wave is incident from the bottom in all cases.
    (a) Acceleration gradient as a function of iteration number for different maximum relative permittivity values, corresponding to those of Si, Si$_3$N$_4$, and SiO$_2$ at the laser wavelength.
    The acceleration gradient is normalized by the electric field amplitude of the incident plane wave $(E_0)$.
    The optimizations converge after about five-hundred iterations.
    (b-d) Final structure permittivity distributions (white = vacuum, black = $\epsilon_m$) corresponding to the three curves in (a).
    Eight periods are shown, corresponding to four laser wavelengths.
    For each (b-d), design region widths on each side of the particle gap were given by $1$, $2$, and $4\,\mu$m for Si, Si$_3$N$_4$, and SiO$_2$, respectively.
}

This optimization scheme seems to favor geometries consisting of a staggered array of field-reversing pillars surrounding the vacuum gap, which is already a popular geometry for DLA.
However, these optimal designs also include reflective mirrors on either side of the pillar array, which suggests that for strictly higher acceleration gradients, it is useful to use dielectric mirrors to resonantly enhance the fields in the gap.

It was observed that for random initial starting permittivity distributions, the same structures as shown in \fig{optimization-results_beta0.5} are generated every time.
Furthermore, as shown in \fig{DLA_sim}, the geometries found using this method are remarkably similar to those recently proposed through human design using physical intuition \cite{ACHIP_meeting3}.
These findings together suggest that the proposed structures may be close to the globally optimal structure for maximizing $G$.

\figdef{DLA_Similarity.png}{DLA_sim}{Similarity between DLA structures designed using adjoint method (left) and those independently proposed using human intuition.}

There are several variants of gradient descent which speed up the optimization in most cases. ‘Momentum’ is one such technique in which the design parameters are updated not only from the gradient information at the current iteration, but also a weighted sum of previous gradients.
Intuitively, this means if an optimization has been trending in a given direction, it will be more likely to continue in this direction, which can improve speed and stability.
Specifically, the momentum term term corresponds to the sensitivity calculated at the last iteration multiplied by a constant, $\alpha' < 1$. For iteration number `$j$' and pixel `$i$' the update is defined as

\eqdef{}{
    \epsilon_i^{ (j+1) } := \epsilon_i^{ (j) } + \alpha\Bigg[ \ddfrac{G}{\epsilon_i}^{ (j) } + \alpha'\ddfrac{G}{\epsilon_i}^{ (j-1) }\Bigg].
}

\subsection{Maximization of Acceleration Factor}

DLAs are often driven with the highest input field possible before damage occurs.
Therefore, another highly relevant quantity to maximize is the \textit{acceleration factor}, given by the acceleration gradient divided by the maximum electric field amplitude in the system.
This quantity will ultimately limit the amount of acceleration gradient we can achieve when running at damage threshold.
Explicitly, the acceleration factor is given by

\eqdef{}{
    f_{A} = \frac{G}{\max\{|\vec{E}|\}}.
}
%
Here, $|\vec{E}|$ is a vector of electric field amplitudes in our system, which are normalized, as in the case of $G$, by the electric field amplitude of the incident plane wave ($E_0$).
The $\max\{\}$ function is designed to pick out the highest value of this vector in either our design or material region, depending on the context.
The \textit{design region} is defined as the total region outside of the particle gap where the permittivity is updated.
The \textit{material region} is defined as any region where the permittivity is equal to $\epsilon_m$.
We would like to use the same basic formalism to maximize $f_{A}$.
However, since the $\max\{\}$ function is not differentiable, this is not possible directly.
Instead we may use a `smooth-max' function to approximate $\max\{\}$ as a weighted sum of vector components
%
\eqdef{}{
    \max\{|\vec{E}|\} \approx \frac{\sum_i |\vec{E}_i| \ \textrm{exp}\big({a|\vec{E}_i|}\big)} {\sum_i \textrm{exp}\big({a|\vec{E}_i|}\big)}.
}
%
Here, the parameter $a \geq 0$ controls the relative strength of the exponential sum terms, for $a = 0$, this function simply gives the average value of the field amplitudes.
By sweeping $a$ and examining the acceleration factors of the resulting optimized structures, we determined that $a = 3$ gave the best improvement in $f_A$.
If $a$ is too large, the calculation may induce floating point overflow or rounding error issues.

Using this smooth-max function, one may calculate $\ddfrac{f_{A}}{\epsilon_i}$ analytically and perform structure optimizations in the same way that was discussed previously.
Two structures with identical parameters but optimized, respectively, for maximum $G$ and $f_A$ are shown in Fig. \ref{fig:optimization-results_fAC}.
On the left, we see that the $G$ maximized structure shows the characteristic dielectric mirrors, giving resonant field enhancement.
On the right is the structure optimized for $f_A$, which has eliminated most of its dielectric mirrors and also introduces interesting pillar shapes.
In Table \ref{tb:table} the main DLA performance quantities of interest are compared between these two structures.
Whereas the acceleration gradient is greatly reduced when maximizing for $f_A$, the $f_A$ value itself is improved by about 25\% or 23\% depending on whether one measures the maximum field in the design region or the material region, respectively.
As a comparison with the geometry from Ref. \cite{leedle2015dielectric}, a SiO$_2$ dual pillar structure with a 400 nm gap was optimized for acceleration gradient, giving an acceleration gradient of 0.025 ($E_0$) with a pillar radius of 670 nm.
This structure was found to have $\max\{|\vec{E}|\}$ in the design region of 1.612 ($E_0$) and $\max\{|\vec{E}|\}$ in the material region of 1.209 ($E_0$), leading to acceleration factors of 0.016 and 0.021, respectively.
Comparing these numbers to those in Table \ref{tb:table}, it is apparent that the optimized structures perform better than the dual pillar structures in terms of both gradient and acceleration factor.

These findings suggest that the inverse design strategy is effective in designing not only resonant, high acceleration gradient structures, but also non-resonant structures that are more damage resistant.
In the future, when more components of DLA are moved on-chip (such as the optical power delivery), it will be important to have control over the resonance characteristics of the DLA structures to prevent damage breakdown at the input facet.
Our technique may be invaluable in designing structures with tailor-made quality factors for this application.

\figdef{DLA_Adjoint_fA}{optimization-results_fAC}{
    Demonstration of the final structures after optimization for (a) maximizing gradient only, (b) maximizing the acceleration factor.
    $\beta = 0.5$, laser wavelength $\lambda=2\,\mu$m, gap size of $400$\,nm.
    $\epsilon_m = 2.1$, corresponding to SiO$_2$.
    In (a), the high gradients are achieved using reflective dielectric mirrors to confine and enhance the fields in the center region.
    In (b), these dielectric mirrors are removed and the pillar structures are augmented.
    The structure in (b) shows a 23\% increase in the acceleration factor in the material region when compared to (a).
}

\begin{table}[ht!]
\centering
\caption{Acceleration factor ($f_A$) before and after maximization.}
\begin{tabular}{lccc}
\hline
Quantity & Value (max $G$) & Value (max $f_A$) & Chang.
\\ \hline
Gradient ($E_0$) & 0.1774 & 0.0970 & -45.32\%\\
$\max\{|\vec{E}|\}$ in design region ($E_0$) & 4.1263 & 1.7940 & -56.52\%\\
$\max\{|\vec{E}|\}$ in material region ($E_0$) & 2.7923 & 1.2385 & -55.84\% \\
$f_A$ in design region & 0.0430 & 0.0541 & +25.81\% \\
$f_A$ in material region & 0.0635 & 0.0783 & +23.31\% \\ \hline
\end{tabular}
\label{tb:table}
\end{table}

\section{Conclusions}

%1. Major findings
We found that the adjoint method is a reliable method for optimizing DLA structures for both maximum acceleration gradient and also acceleration factor.
The optimization algorithm discussed shows good convergence and rarely requires further post-processing of structures to create binary permittivity distributions.
Therefore, it is a simple and effective method for designing DLAs.
%2. What is new and novel
Whereas most structure optimization in this field uses parameter sweeps to search the design space, the efficiency of our method allows us to more intelligently find optimal geometries without shape parameterization.
Furthermore, the structures that we design are fabricable.

%3. How does it compare with literature?
Although no DLA structures have been tested at the proposed wavelength of $2\, \mu$m, both simulations \cite{plettner2006proposed} and experimental results from other wavelengths \cite{leedle2015dielectric} show gradients far below those presented here.
%4. What are the limitations?
We had limited success designing DLA structures in the regime of $\beta > 1 / n$, where $n$ is the refractive index of the DLA structure.  In this regime, the electron is moving faster than the speed of light in the material region, which leads to stronger coupling between the electron beam and incident plane wave.  This fact causes optimizations that are more unstable and do not converge on the same structure for several starting parameters.

In addition to the side-incident geometry explored, this technique is applicable to designing other dielectric-based accelerator structures.
This includes particle-laser co-propagating schemes \cite{cowan2008three} and dielectric wakefield acceleration
\cite{zhang1997stimulated}, among others.
Therefore, we expect that our results may find use in the larger advanced accelerator community.

In this chapter, we have introduced the adjoint variable method as a powerful tool for designing dielectric laser accelerators for high gradient acceleration and high acceleration factor.
We have further shown that the adjoint simulation is sourced by a point charge flowing through the accelerator, which quantifies the reciprocal relationship between an accelerator and a radiator.

Optimization algorithms built on this approach allow us to search a substantially larger design space and generate structures that give acceleration gradients far above those normally used for each material.
Furthermore, the structures designed by adjoint are fundamentally not constrained by shape parameterization, allowing never-before-seen geometries to be generated and tested.
This theme will continue to be explored in other chapters.


% Neutrino physics
% Target length: 30 pages

\chapter{Neutrino Physics}\label{chap:NeutrinoPhysics}

Neutrino physics will be discussed! \\
\\
-- Theory\\
-- Experiments\\
-- Future Experiments\\
\\
It may make sense to discuss the experiments as we go along...\\
\\
I think the chapter will work best with both past, present and future woven together.\\
And no distinct separation between theory and experiment (this is an experimental thesis after all...).\\
Can discuss the `neutrino problems' to motivate the theory of neutrino oscillations, and include the SNO and Kamiokande results within.\\
Then something similar with mass.\\
And as we get onto unanswered questions, can weave the propsed experiments into this.\\
I feel a section on the technology and concept of LAr TPCs will fit nicely into this setup.\\

%----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
\section{Neutrino Theory}\label{sec:NeutrinoTheory}

\subsection{Neutrino Oscillations}\label{sec:NeutrinoOscillations}

Derive 2-flavour case.\\
Extend to 3 flavour.\\
Discuss CP violation.\\

\subsection{Neutrino Mass}\label{sec:NeutrinoMass}

Mass hierarchy.\\
Absolute mass.\\

%----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
\section{Future Neutrino Experiments}\label{sec:FutureNeutrinoExperiments}

%----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
\section{The LAr TPC Concept}\label{sec:LArTPC}

The use of a liquid argon time projection chamber (LArTPC) as a high-precision fine-grained detector medium holds much promise for the successful resolution of the open questions in neutrino physics.  A great amount of R\&D work has taken place to advance the maturity of the technology and pioneering experiments, such as ICARUS \cite{ICARUS2004}, have further increased the understanding of the neutrino community of the detector techniques.  Past and currently running experiments at Fermilab, such as ArgoNeuT [], LArIAT [] and MicroBooNE [], are successfully using LArTPCs to take and analyse data and it seems certain to be the future of neutrino physics in the U.S.

This section will provide a brief history of LArTPC technology and motivate its potential when used in a huge experiment such as DUNE.  The basic operation of such a detector will also be described to provide background for discussion of the DUNE and 35t experiments, and of reconstruction in LArTPCs, in future chapters.

\subsection{A Brief History of Time (Projection Chambers)}\label{sec:LArTPCHistory}

The use of a time projection chamber as a potential particle detector was put forward by David Nygren in 1974 \cite{Nygren1974}.  He envisioned bubble-chamber quality data but with the possiblity of digital readout of the data, fascilitating extremely fine spatial resolution, good timing resolution and fast recovery after triggering.  The basic concept is a drift chamber containing a noble gas placed within a field to drift ionisation electrons created by a propagating particle towards a multielectron array.  This setup allows full three-dimensional reconstruction by combining information from the two-dimensional readout plane with the drift time.  Nygren also included a magnetic field to assist particle identification in his design, shown in Fig. \ref{fig:NygrenTPC}.

\begin{figure}[ht]
  \centering
  \includegraphics[width=10cm]{NygrenTPC.png}
  \caption{The original concept of the time projection chamber particle detector, drawn by David Nygren in 1974 \cite{Nygren1974}.}
  \label{fig:NygrenTPC}
\end{figure}

The extension of this concept to a liquid argon TPC and it potential as a high-precision fine-grained detector medium in neutrino physics was proposed by Carlo Rubbia in 1977 \cite{Rubbia1977}.  The use of a noble liquid rather than gas is necessary in neutrino experiments to provide a high enough target mass to increase the probability of a neutrino interaction.  Noble liquids have high electron mobility and low diffusion, favourable properties as the detection of particles is from the ionisation and scintillation light created by the particles.  Given the necessity of a high electric field in order to drift these electrons to the readout places, excellent dielectric properties are also required; noble liquids possess such qualities.  The properties of liquid argon which make it almost perfect for this use are demonstrated in the table in Table \ref{tab:NobleProperties}.

\begin{table}[ht]
  \caption{Properties of noble elements relevant when considering a TPC medium for a neutrino experiment.}
  \label{tab:NobleProperties}
  \centering
  \begin{tabular}{ m{5cm} || m{1.5cm} | m{1.5cm} | m{1.5cm} | m{1.5cm} | m{1.5cm} | m{1.5cm} }
     & Water & He & Ne & \color{red} Ar & Kr & Xe \\
    \hline\hline
    Boiling point [K] @ 1 atm & 373 & 4.2 & 27.1 & \color{red} 87.3 & 120.0 & 165.0 \\
    \hline
    Density [g/cm$^3$] & 1 & 0.125 & 1.2 & \color{red} 1.4 & 2.4 & 3.0 \\
    \hline
    Radiation length [cm] & 36.1 & 755.2 & 24.0 & \color{red} 14.0 & 4.9 & 2.8 \\
    \hline
    Scintillation [$\gamma$/MeV] & - & 19 000 & 30 000 & \color{red} 40 000 & 25 000 & 42 000 \\
    \hline
    dE/dx [MeV/cm] & 1.9 & & 1.4 & \color{red} 2.1 & 3.0 & 3.8 \\
    \hline
    Scintillation $\lambda$ [nm] & & 80 & 78 & \color{red} 128 & 150 & 175 \\
    \hline
    Natural abundance (Earth atm) [ppm] & & 5.2 & 18.2 & \color{red} 9340.0 & 1.10 & 0.09 \\
    \hline
    Electron mobility [cm$^2$/Vs] & & low & low & \color{red} 400 & 1200 & 2200 \\
    \hline\hline
  \end{tabular}
\end{table}

An additional advantage of this technology is the low threshold for detection; this is set by the ionisation threshold of liquid argon and is only $23.6 \pm 0.5$ eV [].  Rubbia realised that a LArTPC could be the digital replacement for the high quality particle detection methods used in bubble chambers, very common in neutrino physics in the 1970s.  He proposed the first LArTPC detector design, shown in Fig. \ref{fig:RubbiaLArTPC}, which bears a striking resemblense to the LArTPC used in experiments today.

\begin{figure}[ht]
  \centering
  \includegraphics[width=10cm]{RubbiaLArTPC.png}
  \caption{The LArTPC detector proposed by Carlo Rubbia in 1977 \cite{Rubbia1977}.}
  \label{fig:RubbiaLArTPC}
\end{figure}

Constructing and operating such a detector was beyond the technology of the time, and is still being understood today.  The operation of a LArTPC detector and the challenges associated with this are the subject of section \ref{sec:LArTPCOperation}.

\subsection{LAr TPC Operation}\label{sec:LArTPCOperation}

explain how they work

new subsubsection

[FIND OR MAKE A FIGURE TO GO WITH THE FOLLOWING DESCRIPTION...]

A LArTPC typically consists of a single, or multiple anode and cathode, at either end of an active drift region.  An ionising particle passing through a LArTPC causes electrons to become free from argon atoms and, in the presence of a field, drift towards an anode where they are read out.

The readout consists of multiple wires planes with different orientations to facilitate the reconstruction.  The wires are either `induction' wires, which allow the electrons to deposit charge but continue past, or `collection' wires, on which the electric field lines end and all the charge on the electron is collected.  Each wire plane is therefore held at a different `bias voltage' to prevent any field lines ending on the induction wire, thus creating local electric fields which promote the continuing forward motion of the electrons.  The signal seen is therefore dependent on the type of wire plane; a bipolar pulse on an induction plane wire and unipolar on a collection plane wire.  It is also common, though not essential, to make use of a `grid plane' upstream of the signal planes in order to shield them from the electron charge until they are close.  Without such a plane, the bipolar pulse would be highly asymmetric, though would still have zero integral.  It also makes changing the drift voltage (controlling the electric field) slightly easier as the signal planes are somewhat shielded from its effects.  MicroBooNE does not operate with a grid plane and, although the 35t and the DUNE reference design make use of a grid plane, it is uncertain whether the benefit outweighs the cost for a huge LArTPC detector such as the DUNE far detector.  It is worth mentioning alternative readout possibilities have been suggested but, given the scale of future LArTPCs, it is highly unlikely a viable solution which delivers superior readout at a comparable cost will be found.

Given the positive ions that are left in the medium, there is the possibility of recombination at a later time and therefore a loss of information about the initial interaction.

This is however accompanied by a flash of scintillation light which is hugely useful as a means of determining the event `start time' ($t_0$); without this information it would be impossible to place an absolute time scale on the interaction and we would therefore not be able to resolve the coordinate along the drift direction.  The magnitude of the electric field applied is the key to both processes and there is thus a compromise which must be struck in order to preserve as much information as possible.  The graph in Fig. \ref{fig:ElectricFieldScintillationIonisation} demonstrates this; a field of $500$ V/cm is often chosen in current LAr neutrino experiments.

\begin{figure}[ht]
  \centering
  \includegraphics[width=12cm]{ElectricFieldScintillationIonisation.png}
  \caption{Demonstration of the competing effect the electric field has on the luminosity of the ionisation electrons and scintillation light arriving at the detector readout.  Since both are essential in reconstructing the complete interactions, a balance must be found. [PLACEHOLDER IMAGE].}
  \label{fig:ElectronFieldScintiallationIonisation}
\end{figure}

A cathode is held at a high voltage

Flesh this stuff out...

U plane, V plane and collection all held at different fields.  Slightly increasing in order to promote forward motion of the electrons.  V held at 0V because it's cheaper (don't need crazy voltages, just some negative (still quite high, ~100V), 0V and some positive.
Grid plane (also held at potential) is to sheild the APAs from the electrons until they are close.  Not needed, but if not present then pulse wouldn't be very bipolar! The charge in both portions will still equate but the leading end will be muchhhh longer.  All electric field lines (generated from movement of electrons) end on the cathode; don't want them to end on the induction wires (hence making sure the field increases).  We want them to end on the collection planes, which collects the charge.  Signal shaping time (along with gain, the two front-end ASIC parameters) is to let the charge leave the wire before being hit again (or something like this!).  Deconvolution I still need to understand...

In 35t, we have FE ASICs which are the very front end and apply the signal shaping and gain.  Have regulators to control the power these receive (these are noisy...).  Also ADC ASICs to do digitisation in the cold.  MicroBooNE don't do this, this just have the front end and do everything else in the warm.  FE ASICs are the problem, same for uBooNE and 35t.  ADC ASIC has stuck code problem.


\section{MEG analysis \label{multimodal:data:meg}}

\subsection{Preprocessing the MEG data\label{multimodal:data:meg:preproc}}

First change directory to the MEG subdirectory (either in \matlab\, or via the ``CD'' option in the SPM ``Utils'' menu)

\subsection{Adjust trigger latency}

For the EEG data, the faces were displayed directly via a CRT monitor. For the MEG data on the other hand, the faces were displayed inside the MSR via a projector. This projector produces a delay of 1.5 screen refreshes, which at 60Hz, is 25ms. This means that the subject actually saw the stimuli 25ms after the trigger was sent to the MEG acquisition machine. To correct for this visual delay, we will illustrate how to manipulate ``trial'' structures\footnote{Alternatively, you could correct by 1 refresh, to match the delay in the EEG data.}. First, we need to read in the triggers from the MEG data (unlike the EEG dataset, the MEG dataset contains information about trial type so we can define the correct condition labels already at this stage). To do this, type the following in the \matlab\ window:

\begin{verbatim}
    [trl, conditionlabels, S] = spm_eeg_definetrial;
\end{verbatim}

and follow these steps:
\begin{itemize}
 \item Select the \texttt{SPM\_CTF\_MEG\_example\_faces1\_3D.ds/SPM\_CTF\_MEG\_example\_faces1\_3D.meg4} file.
 \item Enter \texttt{-200} for ``Start of trial in PST [ms]'' and \texttt{600} to ``End of trial in PST [ms]''.
 \item Enter 2 for ``How many conditions?''.
 \begin{itemize}
  \item Enter ``\texttt{faces}'' for ``Label of condition 1''. A dialog with a list of events will come up and Select the event with type \texttt{UPPT001\_up} and Value 1.
  \item Enter ``\texttt{scrambled}'' for ``Label of condition 2''. Select the even with type \texttt{UPPT001\_up} and Value 2.
 \end{itemize}
 \item Answer ``no'' to the question about reviewing trials.
 \item Answer ``yes'' to the prompt to save the trial definition.
 \item Enter a filename like \texttt{trials\_run1.mat} and save in the MEG directory.
\end{itemize}

Then type \texttt{load trials\_run1.mat} in \matlab\, to see the contents of the file you just saved. It contains two variables, \texttt{trl} and \texttt{conditionlabels}. The \texttt{trl} variable contains as many rows as triggers were found (across all conditions) and three columns: the initial sample of the epoch, the final sample of the epoch and the offset in samples corresponding to a peristimulus time of 0. The sampling rate for the MEG data was 480Hz (as can be found in the \texttt{S.fsample} field of the structure \texttt{S} returned by the \texttt{spm\_eeg\_definetrial} call above). Thus the figure of -96 samples in the third column corresponds to the 200ms baseline period that you specified. Now we need to shift the initial and final samples of the epochs by 25ms. You can do this by typing:

\begin{verbatim}
    trl(:,1:2) = trl(:,1:2) + round(25*S.fsample/1000);
    save trials_run1 trl conditionlabels
\end{verbatim}

The new trial definition is thus resaved, and we can use this file when next converting the data.

\subsection{Convert}

Press the \textsc{Convert} button, and in the file selection window again select the \texttt{SPM\_CTF\_MEG\_example\_\-faces1\_3D.ds} subdirectory and the \texttt{\hyphenchar\font45\relax SPM\_CTF\_MEG\_example\_faces1\_3D.meg4} file. At the prompt ``Define settings?'' select ``yes''. Here we will use the option to define more precisely the part of data that should be read during conversion. Answer ``trials'' to ``How to read?'', and ``file'' to ``Where to look for trials?''. Then in the file selector window, select the new \texttt{trials\_run1.mat} file. Press ``no'' to ``Read across trials?'' and select ``meg'' for ``What channels?''. Press ``no'' to avoid saving the channel selection. Press ``Enter'' to accept the default suggestion for the name of the output dataset. Two files will be generated \texttt{espm8\_SPM\_CTF\_MEG\_example\_faces1\_3D.mat} and \texttt{espm8\_SPM\_CTF\_MEG\_example\_faces1\_3D.dat}. After the conversion is complete the data file will be automatically opened in the SPM8 reviewing tool. If you click on the ``MEG'' tab you will see the MEG data which is already epoched. By pressing the ``intensity rescaling'' button (with arrows pointing up and down) several times you will start seeing MEG activity.

\subsection{Baseline correction}

We need to perform baseline correction as it is not done automatically during conversion. This will prevent excessive edge artefacts from appearing after subsequent filtering and downsampling. Select \textsc{Baseline correction} from the ``Other'' drop-down menu and select the \texttt{espm8\_SPM\_CTF\_MEG\_example\_faces1\_3D.mat} file. Enter $[-200\: 0]$ for ``Start and stop of baseline [ms]''. The progress bar will appear and the resulting data will be saved to dataset \texttt{bespm8\_SPM\_\-CTF\_\-MEG\_\-example\_faces1\_3D.\{mat,dat\}}.

\subsection{Downsample}

Select \textsc{Downsample} from the ``Other'' drop-down menu and select the \texttt{bespm8\_SPM\_CTF\_\-MEG\_\-example\_\-faces1\_3D.mat} file. Choose a new sampling rate of 200 (Hz). The progress bar will appear and the resulting data will be saved to dataset \texttt{dbespm8\_SPM\_CTF\_MEG\_example\_faces1\_3D.\{mat,dat\}}.

\subsection{Batch preprocessing}

Here we will preprocess the second half of the MEG data using using the SPM8 batch facility to demonstrate this third (after interactive GUI and Matlab script) possibility. First though, we have to correct the visual onset latency for the second run, repeating the above steps that you did for the first run:

\begin{verbatim}
    [trl, conditionlabels, S] = spm_eeg_definetrial;
\end{verbatim}

and select the \texttt{SPM\_CTF\_MEG\_example\_faces2\_3D.ds} subdirectory and the \texttt{SPM\_\-CTF\_\-MEG\_\-example\_\-faces2\_3D.meg4} file. Then enter \texttt{-200} for ``Start of trial in PST [ms]'' and \texttt{600} to ``End of trial in PST [ms]''. Enter \texttt{2} for ``How many conditions?''. Enter ``\texttt{faces}'' for ``Label of condition 1''. A dialog with a list of events will come up. Select the event with type ``\texttt{UPPT001\_up}'' and Value 1. Enter \texttt{scrambled} for ``Label of condition 2''. Select the event with type ``\texttt{UPPT001\_up}'' and Value 2. Answer ``no'' to the question about reviewing trials, but ``yes'' to the prompt to save the trial definition. Enter a filename like \texttt{trials\_run2.mat} and save in the MEG directory. Then type:

\begin{verbatim}
    load trials_run2
    trl(:,1:2) = trl(:,1:2)+round(25*S.fsample/1000);
    save trials_run2 trl conditionlabels
\end{verbatim}

Now press the \textsc{Batch} button (lower right corner of the SPM8 menu window). The batch tool window will appear. We will define exactly the same settings as we have just done using the interactive GUI. From the ``SPM'' menu, ``M/EEG'' submenu select ``M/EEG Conversion''. Click on ``File name'' and select the \texttt{SPM\_CTF\_MEG\_example\_faces2\_3D.meg4} file from \texttt{SPM\_CTF\_\-MEG\_\-example\_\-faces2\_3D.ds} subdirectory. Click on ``Reading mode'' and switch to ``Epoched''. Click on ``Epoched'' and choose ``Trial file'', double-click on the new ``Trial file'' branch and then select the \texttt{trials\_run2.mat} file.  Then click on ``Channel selection'' and select MEG from the menu below. Finally enter \texttt{espm8\_SPM\_CTF\_MEG\_example\_faces2\_3D} for ``Output filename'' to be consistent with the file preprocessed interactively.

Now select ``M/EEG Baseline correction'' from the ``SPM'' menu, ``M/EEG'' submenu. Another line will appear in the Module list on the left. Click on it. The baseline correction configuration branch will appear. Select ``File name'' with a single click. The file that we need to downsample has not been generated yet but we can use the ``Dependency'' button. A dialog will appear with a list of previous steps (in this case just the conversion) and we can set the output of one of these steps as the input to the present step. Now just enter enter $-200\: 0$ for ``Baseline''. Similarly we can now add ``M/EEG Downsampling'' to the module list, define the output of baseline correction step for ``File name'' and 200 for the ``New sampling rate''. This completes our batch. We can now save it for future use (e.g, as \texttt{batch\_meg\_preprocess} and run it by pressing the green ``Run'' button. This will generate all the intermediate datasets and finally \texttt{dbespm8\_SPM\_CTF\_MEG\_example\_faces2\_3D.\{mat,dat\}}.

\subsection{Merge}

We will now merge the two epoched files we have generated until now and continue working on the merged file. Select the \textsc{Merge} command from the ``Other'' drop-down menu. In the selection window that comes up click on \texttt{dbespm8\_SPM\_CTF\_MEG\_example\_faces1\_3D.mat} and \texttt{dbespm8\_SPM\_CTF\_MEG\_example\_faces2\_3D.mat}. Press ``done''. Answer ``Leave as they are'' to ``What to do with condition labels?''. A new dataset will be generated called \texttt{cdbespm8\_SPM\_CTF\_\-MEG\_\-example\_\-faces1\_\-3D.\{mat,dat\}}.

\subsection{Reading and preprocessing data using Fieldtrip}
Yet another even more flexible way to pre-process data in SPM8 is to use the Fieldtrip toolbox (\url{http://www.ru.nl/neuroimaging/fieldtrip/}) that is distributed with SPM. All the pre-processing steps we have done until now can also be done in Fieldtrip and the result can then be converted to SPM8 dataset. An example script for doing so can be found in the
\texttt{man$\backslash$example\_scripts$\backslash$spm\_ft\_multimodal\_preprocessing.m}. The script will generate a merged dataset and save it under the name \texttt{ft\_SPM\_CTF\_\-MEG\_\-example\_\-faces1\_\-3D.\{mat,dat\}}. The rest of the analysis can then be done as below. This option is more suitable for expert users well familiar with Matlab. Note that in the script \texttt{ft\_} prefix is added to the names of all Fieldtrip functions. This is a way specific to SPM8 to call the functions from Fieldtrip version included in SPM distribution and located under \texttt{external$\backslash$fieldtrip}.

\subsection{Prepare}

In this section we will add the separately measured headshape points to our merged dataset. This is useful when one wants to improve the coregistration using head shape measured outside the MEG. Also in some cases the anatomical landmarks detectable on the MRI scan and actual locations of MEG locator coils do not coincide and need to be measured in one common coordinate system by an external digitizer (though this is not the case here). First let's examine the contents of the headshape file. If you load it into \matlab\ workspace (type \texttt{load headshape.mat}), you will see that it contains one \matlab\ structure called \texttt{shape} with the following fields:
\begin{itemize}
\item \texttt{.unit} - units of the measurement (optional)
\item \texttt{.pnt} - Nx3 matrix of headshape points
\item \texttt{.fid} - substruct with the fields .pnt - Kx3 matrix of points and .label -Kx1 cell array of point labels.
\end{itemize}

The difference between \texttt{shape.pnt} and \texttt{shape.fid.pnt} is that the former contains unnamed points (such as continuous headshape measurement) whereas the latter contains labeled points (such as fiducials). Note that this Polhemus space (which will define the ``head space'') has the X and Y axes switched relative to MNI space.

Now select \textsc{Prepare} from the ``Other'' menu and in the file selection window select \texttt{cdbespm8\_\-SPM\_\-CTF\_\-MEG\_\-example\_\-faces1\_3D.mat}. A menu will appear at the top of SPM interactive window (bottom left window). In the ``Sensors'' submenu choose ``Load MEG Fiducials/Headshape''. In the file selection window choose the \texttt{headshape.mat} file and save the dataset with \texttt{File/Save}.

If you do not have a separately measured headshape and are planning to use the original MEG fiducials for coregistration, this step is not necessary. As an exercise, you can skip it for the tutorial dataset and later do the coregistration without the headshape and see if it affects the results.

\subsection{Basic ERFs}

Press the \textsc{Averaging} button and select the \texttt{cdbespm8\_SPM\_CTF\_MEG\_example\_faces1\_3D.mat} file. Answer ``yes'' to ``Use robust averaging?''. You can either save the weights if you want to examine them or not save if you want the averaging to work faster since the weights dataset that needs to be written is quite large. Answer ``no'' to ``weight by condition'' and accept the default ``Offset of the weighting function''. A new dataset will be created in the MEG directory called \texttt{mcdbespm8\_SPM\_CTF\_MEG\_example\_faces1\_3D.\{mat,dat\}} (``m'' for ``mean'').

As before, you can display these data by ``Display: M/EEG'' and selecting the \texttt{mcdbespm8\_\-SPM\_\-CTF\_\-MEG\_\-example\_\-faces1\_3D.mat}. In the MEG tag with the scalp radio button selected, hold the Shift key and select trial-type 2 with the mouse in the bottom right of the window to see both conditions superimposed (as Figure~\ref{multimodal:fig:10}).

\begin{figure}
\begin{center}
\includegraphics[width=100mm]{multimodal/figures/meg_scalp_erf}
\caption{\em SPM Display window for mean, smoothed ERF (\texttt{mcdbespm8\_\-SPM\_\-CTF\_\-MEG\_\-example\_\-faces1\_\-3D.mat}) for all 275 MEG channels. \label{multimodal:fig:10}}
\end{center}
\end{figure}

Select ``Contrast'' from the ``Other'' pulldown menu on the SPM window. This function creates linear contrasts of ERPs/ERFs. Select the \texttt{mcdbespm8\_SPM\_CTF\_MEG\_example\_faces1\_3D.mat} file, enter $[1\: -1]$ as the first contrast and label it ``\texttt{Difference}'', answer ``yes'' to ``Add another'',  enter $[1/2\: 1/2]$ as the second contrast and label it ``\texttt{Mean}''. Press ``no'' to the question ``Add another'' and not to ``weight by num replications''. This will create new file \texttt{wmcdbespm8\_\-SPM\_\-CTF\_\-MEG\_\-example\_\-faces1\_\-3D.mat}, in which the first trial-type is now the differential ERF between faces and scrambled faces, and the second trial-type is the average ERF for faces and scambled faces.

To see the topography of the differential ERF, select ``Display: M/EEG'', MEG tab and click on Trial 1, press the ``topography'' button at the top of the window and scroll to 180ms for the latency to produce Figure~\ref{multimodal:fig:12}.

You can move the slider left and right to see the development of the M170 over time.

\begin{figure}
\begin{center}
\includegraphics[width=100mm]{multimodal/figures/meg_topo180}
\caption{\em 2D topography of the ERF of faces minus scrambled faces at 180ms. \label{multimodal:fig:12}}
\end{center}
\end{figure}

\subsection{Time-Frequency Analysis}

SPM can use several methods for time-frequency decomposition. We will use Morlet wavelets for our analyses.

Select the \textsc{time-frequency} option under the ``Other'' pull-down menu. SPM batch tool with time-frequency configuration options will apear. Double-click on ``File name'' and select the \texttt{cdbespm8\_\-SPM\_\-CTF\_\-MEG\_\-example\_\-faces1\_\-3D.mat} file. Then click on ``Channel selection'' and in the box below click on ``Delete: All(1)'' and then on ``New: Custom channel''. Double-click on ``Custom channel'' and enter ``MLT34''.\footnote{You can of course obtain time-frequency plots for every channel, but it will take much longer (and result in a large file).} Double-click on ``Frequencies of interest'' and type [5:40] (Hz). Click on ``Spectral estimation'' and select ``Morlet wavelet transform''. Change the number of wavelet cycles from 7 to 5. This factor effectively trades off frequency vs time resolution, with a lower order giving higher temporal resolution. Select ``yes'' for ``Save phase?''.

This will produce two new datasets, \texttt{tf\_\-cdbespm8\_\-SPM\_\-CTF\_\-MEG\_\-example\_\-faces1\_3D.\{mat,dat\}} and  \texttt{tph\_\-cdbespm8\_\-SPM\_\-CTF\_\-MEG\_\-example\_\-faces1\_\-3D.\{mat,dat\}}. The former contains the power at each frequency, time and channel; the latter contains the corresponding phase angles.

Here we will not baseline correct the time-frequency data because for frequencies as low as 5Hz, one would need a longer pre-stimulus baseline, to avoid edge-effects\footnote{For example, for 5Hz, one would need at least N/2 x 1000ms/5, where N is the order of the Morlet wavelets (i.e, number of cycles per Gaussian window), e.g, 600ms for a 6th-order wavelet.}. Later, we will compare two trial-types directly, and hence any pre-stimulus differences will become apparent.

Press the \textsc{Averaging} button and select the \texttt{tf\_\-cdbespm8\_\-SPM\_\-CTF\_\-MEG\_\-example\_\-faces1\_\-3D.mat} file. You can use straight (or robust if you prefer) averaging to compute the average time-frequency representation. A new file will be created in the MEG directory called \texttt{mtf\_cdbespm8\_\-SPM\_\-CTF\_\-MEG\_\-example\_\-faces1\_\-3D.\{mat,dat\}}. Note that you can use the reviewing tool to review the time-frequency datasets.

This contains the power spectrum averaged over all trials, and will include both ``evoked'' and ``induced'' power. Induced power is (high-frequency) power that is not phase-locked to the stimulus onset, which is therefore removed when averaging the amplitude of responses across trials (i.e, would be absent from a time-frequency analysis of the \texttt{mcdbespm8\_SPM\_\-CTF\_\-MEG\_\-example\_\-faces1\_\-3D.mat} file).

The power spectra for each trial-type can be displayed using the usual Display button and selecting the \texttt{mtf\_\-cdbespm8\_\-SPM\_\-CTF\_\-MEG\_\-example\_\-faces1\_3D.mat} file. This will produce a plot of power as a function of frequency (y-axis) and time (x-axis) for Channel MLT34. If you use the ``trial'' slider to switch between trial(types) 1 and 2, you will see the greater power around 150ms and 10Hz for faces than scrambled faces (click on the magnifying glass icon and on the single channel to get scales for the axes, as in Figure~\ref{multimodal:fig:13}). This corresponds to the M170 again.

\begin{figure}
\begin{center}
\includegraphics[width=60mm]{multimodal/figures/meg_pow_faces}
\includegraphics[width=60mm]{multimodal/figures/meg_pow_scrambled}
\caption{\em  Total power spectra for faces (left) and scrambled faces (right) for channel MLT34\label{multimodal:fig:13}}
\end{center}
\end{figure}

We can also look at evidence of phase-locking of ongoing oscillatory activity by averaging the phase angle information. We compute the vector mean (by converting the angles to vectors in Argand space), which yelds  complex numbers. We can generate two kinds of images from these numbers. The first is an image of the angles, which shows the mean phase of the oscillation (relative to the trial onset) at each time point. The second is an image of the absolute values (also called ``Phase-Locking Value'', PLV) which lie between 0 for no phase-locking across trials and 1 for perfect phase-locking.

Press the \textsc{Averaging} button and select the \texttt{tph\_\-cdbespm8\_\-SPM\_\-CTF\_\-MEG\_\-example\_\-faces1\_\-3D.mat} file. This time you will be prompted for either ``angle'' or ``abs(PLV)'' average, for which you should select ``abs(PLV)''. The \matlab\ window will echo:

\begin{verbatim}
  mtph_cdbespm8_SPM_CTF_MEG_example_faces1_3D.mat: Number of replications per contrast:
  average faces: 168 trials, average scrambled: 168 trials
\end{verbatim}

and a new file will be created in the MEG directory called \texttt{mtph\_\-cdbespm8\_\-SPM\_\-CTF\_\-MEG\_\-example\_\-faces1\_\-3D.mat}.

If you now display the file \texttt{mtph\_\-cdbespm8\_\-SPM\_\-CTF\_\-MEG\_\-example\_\-faces1\_\-3D.mat} file, you will see PLV as a function of frequency (y-axis) and time (x-axis) for Channel MLT34. Again, if you use the ``trial'' slider to switch between trial(types) 1 and 2, you will see greater phase-locking around for faces than scrambled faces at lower frequencies, as in Figure~\ref{multimodal:fig:14}. Together with the above power analysis, these data suggest that the M170 includes an increase both in power and in phase-locking of ongoing oscillatory activity in the alpha range (Henson et al, 2005b).

\begin{figure}
\begin{center}
\includegraphics[width=60mm]{multimodal/figures/meg_plv_faces}
\includegraphics[width=60mm]{multimodal/figures/meg_plv_scrambled}
\caption{\em Phase-Locking Values for faces (left) and scrambled faces (right) for channel MLT34 \label{multimodal:fig:14}}
\end{center}
\end{figure}

\subsection{2D Time-Frequency SPMs}

Analogous to Section~\ref{multimodal:eeg:3DSPM}, we can also use Random Field Theory to correct for multiple statistical comparisons across the 2-dimensional time-frequency space.

Select \textsc{Convert to images} in the ``Other'' pulldown menu, and select the \texttt{tf\_cdbespm8\_\-SPM\_\-CTF\_\-MEG\_\-example\_\-faces1\_\-3D.mat} file. Usually you would be asked whether you want to average over channels or frequencies. In this case there is only one channel in this dataset, so the ``channels'' option will be selected automatically.

This will create 2D time-frequency images for each trial of the two types with dimensions $36\times 161\times 1$, as for the example shown in Figure~\ref{multimodal:fig:15}. These images can be found in the subdirectories \texttt{1ROI\_TF\_\-trialtype\_\-faces} and \texttt{1ROI\_TF\_\-trialtype\_\-scrambled} of the new directory created \texttt{tf\_\-cdbespm8\_\-SPM\_\-CTF\_\-MEG\_\-example\_\-faces1\_3D}, and examined by pressing ``Display: images'' on the main SPM window.

\begin{figure}
\begin{center}
\includegraphics[width=100mm]{multimodal/figures/meg_TFimage}
\caption{\em  3D image for trial 2 within \texttt{1ROI\_TF\_trialtype\_faces} subdirectory. The bottom left section is through frequency (x) and time (y) (the other images are strips because there is only one value in the z dimension, i.e, this is really a 2D image).\label{multimodal:fig:15}}
\end{center}
\end{figure}

As in Section~\ref{multimodal:eeg:3Dsmooth}, these images can be further smoothed in time and frequency if desired.

Then as in Section~\ref{multimodal:eeg:3DSPM}, we then take these images into an unpaired t-test across trials to compare faces versus scrambled faces. We can then use classical SPM to identify times and frequencies in which a reliable difference occurs, correcting across the multiple comparisons entailed (Kilner et al, 2005).

First create a new directory, eg. \texttt{mkdir TFstatsPow}.

Then press the \textsc{specify 2nd level} button, select ``two-sample t-test'' (unpaired t-test), and define the images for ``group 1'' as all those in the subdirectory \texttt{trialtype\_faces} (using right click, and ``select all'') and the images for ``group 2'' as all those in the subdirectory \texttt{trialtype\_scrambled}. Finally, specify the new \texttt{TFstatsPow} directory as the output directory. (Note that this will be faster if you saved and could load an SPM job file from Section~\ref{multimodal:eeg:3DSPM} in order to just change the input files and output directory.) Then add an ``Estimate'' module from the ``SPM'' tab, and select the output from the previous factorial design specification stage as the dependency input. Press ``Run'' (green arrow button).

Press \textsc{Results} and define a new T-contrast as $[1\: -1]$. Keep the default contrast options, but threshold at $p<.05$ FWE corrected for the whole search volume, and then select ``Time-Frequency'' for the ``Data Type''. Then press ``whole brain'', and the Graphics window should now look like that in Figure~\ref{multimodal:fig:16}.

\begin{figure}
\begin{center}
\includegraphics[width=100mm]{multimodal/figures/meg_TF_results}
\caption{\em 2D time-frequency SPM{T} at $p<.05$ FWE-corrected for the power difference between face and scrambled faces at Channel MLT34.\label{multimodal:fig:16}}
\end{center}
\end{figure}

This will list two ``regions'' within the 2D time-frequency space in which faces produce greater power than scrambled faces, having corrected for multiple T-tests across pixels. The larger one has a maximum at 5 Hz and 185 ms post-stimulus, corresponding to the M170 seen earlier in the averaged files (but now with a statistical test of its significance, in terms of evoked and induced power). The second, smaller region has a maximum at 12 Hz and 100 ms, possibly corresponding to a smaller but earlier effect on the M100 (also sometimes reported, depending on what faces are contrasted with).

\subsection{``Imaging'' reconstruction of total power for each condition \label{multimodal:data:meg:recon_pow}}

In Section~\ref{multimodal:eeg:3D} we localised the differential evoked potential difference in EEG data corresponding to the N170.  Here we will localise the total power of faces, and of scrambled faces, ie including potential induced components (see Friston et al, 2006).

Press the ``3D source reconstruction'' button, and press the ``load'' button at the top of the new window. Select the \texttt{cdbespm8\_SPM\_CTF\_MEG\_example\_faces1\_3D.mat} file and type a label (eg \texttt{M170}) for this analysis.

Press the ``MRI'' button, select the \texttt{smri.img} file within the \texttt{sMRI} sub-directory and select the ``normal'' mesh.

If you have not used this MRI image for source reconstruction before, this step will take some time while the MRI is segmented and the deformation parameters computed (see Section~\ref{multimodal:eeg:3D} for more details on these files). When meshing has finished, the cortex (blue), inner skull (red) and scalp (orange) meshes will also be shown in the Graphics window with slices from the sMRI image. This makes it possible to verify that the meshes indeed fit the original image well. The field \texttt{D.inv\{1\}.mesh} will be updated. Press ``save'' in top right of window to update the corresponding mat file on disk.

Both the cortical mesh and the skull and scalp meshes are not created directly from the segmented MRI, but rather are determined from template meshes in MNI space via inverse spatial normalisation (Mattout et al, 2007; Henson et al, 2009a).

Press the ``Co-register'' button. You will be asked for each of the 3 fiducial points to specify its location on the MRI images. This can be done by selecting a corresponding point from a hard-coded list (``select''). These points are inverse transformed for each individual image using the same deformation field that is used to create the meshes. The other two options are typing the MNI coordinates for each point (``type'') or clicking on the corresponding point in the image (``click''). Here, we will type coordinates based on where the experimenter defined the fiducials on the \texttt{smri.img}. These coordinates can be found in the \texttt{smri\_fid.txt} file also provided. So press ``type'' and for ``nas'', enter [0  91  -28]; for ``lpa'' press ``type'' and enter [-72   4  -59]; for ``rpa'' press ``type'' and enter [71  -6  -62]. Finally, answer ``no'' to ``Use headshape points?'' (see EEG Section~\ref{multimodal:eeg:3D}).

This stage coregisters the MEG sensor positions with the structural MRI and cortical mesh, via an approximate matching of the fiducials in the two spaces, followed by a more accurate surface-matching routine that fits the head-shape function (measured by Polhemus) to the scalp that was created in the previous meshing stage via segmentation of the MRI. When coregistration has finished, the field \texttt{D.inv\{1\}.datareg} will be updated. Press ``save'' in top right of window to update the corresponding mat file on disk. With the \matlab\ Rotation tool on (from the ``Tools'' tab in the SPM Graphics window, if not already on), right click near the top image and select ``Go to X-Z'' view. This should produce a figure like that in Figure~\ref{multimodal:fig:17}, which you can rotate with the mouse to check all sensors. Note that the data are in head space (not MNI space), in this case corresponding to the Polhemus space in which the X and Y dimensions are swapped relative to MNI space.

\begin{figure}
\begin{center}
\includegraphics[width=70mm]{multimodal/figures/meg_coreg.png}
\caption{\em  Graphical output of registration of MEG and sMRI data, showing (upper panel) cortex (blue) and scalp (black) meshes, sensor locations (green), MRI and Polhemus fiducials (cyan/magneta), and headshape (red dots).\label{multimodal:fig:17}}
\end{center}
\end{figure}

Press the ``Forward Model'' button. Choose ``MEG Local Spheres'' (you may also try the other options; see Henson et al, 2009a). A figure will be displaying showing the local (overlapping) spheres fit to each sensor, and final the set of all spheres.

Press ``Invert'', select ``Imaging'', select ``yes'' to ``All conditions or trials?'', and ``Standard'' for the model (i.e, to use defaults; you can customise a number of options if you press Custom instead) (see Friston et al, 2008, for more details about these parameters). There will be lead field computation followed by the actual inversion. A summary plot of the results will be displayed at the end.

You can now explore the results via the 3D reconstruction window. If you type 180 into the box in the bottom right (corresponding to the time in ms) and press ``mip'', you should see several ventral temporal hotspots, as in Figure~\ref{multimodal:fig:18}. Note that this localisation is different from the previous EEG localisation because 1) condition 1 now refers to faces, not the difference between faces and scrambled faces, and 2) the results reflect total power (across trials), induced and evoked, rather than purely evoked\footnote{Though in reality, most of the power is low-frequency and evoked}. The timecourses come from the peak voxel (with little evidence of a face/scrambled difference for this particular maximum). The red curve shows the condition currently being shown (corresponding to the ``Condition 1'' toggle bar in the reconstruction window); the grey curve(s) will show all other conditions. If you press the "condition 1" toggle, it will change to Condition 2, which is the total power for scrambled faces, then press ``mip'' again and the display will update (note the colours of the lines have now reversed from before, with red now corresponding to scrambled faces).

\begin{figure}
\begin{center}
\includegraphics[width=90mm]{multimodal/figures/meg_msp.png}
\caption{\em  Graphic output for MSP-estimated activity at 159ms for faces.\label{multimodal:fig:18}}
\end{center}
\end{figure}

If press ``movie'', you will see the changes in the source strengths over peristimulus time (from the limits 0 to 300ms currently chosen by default).

If you press ``render'' it will open a graphical interface that is very useful to explore the data (the buttons are fairly self-explanatory).

You can also explore the other inversion options, like COH and IID, which you will note give more superficial solutions (a known problem with standard minimum norm; see also Friston et al, 2008; Henson et al, 2009a). To do this quickly (without repeating the MRI segmentation, coregistration and forward modelling), press the ``new'' button in the reconstruction window, which by default will copy these parts from the previous reconstruction.

In the following we will concentrate on how one prepares this single subject data for subsequent entry into a group analysis.

Press the ``Window'' button in the reconstruction window, enter ``150 200'' as the timewindow of interest and ``5 15'' as the frequency band of interest (from the SPM time-frequency analysis, at least from one channel). Then choose the ``induced'' option. After a delay (as SPM calculates the power across all trials) the Graphics window will show the mean activity for this time/frequency contrast (for faces alone, assuming the condition toggle is showing ``condition 1'').

If you then press ``Image'', SPM will write 3D NIfTI images corresponding to the above contrast for each condition:

\begin{verbatim}
    cdbespm8_SPM_CTF_MEG_example_faces1_3D_1_t150_200_f5_15_1.nii
    cdbespm8_SPM_CTF_MEG_example_faces1_3D_1_t150_200_f5_15_2.nii
\end{verbatim}

The last number in the file name refers to the condition number; the number following the dataset name refers to the reconstruction number (i.e. the number in red in the reconstruction window, i.e, \texttt{D.val}, here 1).

The smoothed results for Condition 1 will also be displayed in the Graphics window, together with the normalised structural. Note that the solution image is in MNI (normalised) space, because the use of a canonical mesh provides us with a mapping between the cortex mesh in native space and the corresponding MNI space.

You can also of course view the image with the normal SPM ``Display:image'' option, and locate the coordinates of the ``hotspots'' in MNI space. Note that these images contain RMS (unsigned) source estimates (see Henson et al, 2007).

If you want to see where activity (in this time/freq contrast) is greater for faces and scrambled faces, you can use SPM \texttt{ImCalc} facility to create a difference image of \texttt{cdbespm8\_\-SPM\_\-CTF\_\-MEG\_\-example\_\-faces1\_\-3D\_\-1\_\-t150\_\-200\_\-f5\_\-15\_\-1.nii} - \texttt{cdbespm8\_\-SPM\_\-CTF\_\-MEG\_\-example\_\-faces1\_\-3D\_\-1\_\-t150\_\-200\_\-f5\_\-15\_\-2.nii}: you should see bilateral fusiform. For further discussion of localising a differential effect (as in Section~\ref{multimodal:eeg:3D} with ERPs), vs taking the difference of two localisations, as here, see Henson et al (2007). The above images can then be used at the second level (assuming one also has data from other subjects) to look for effects that are consistent over a group of subjects.


\section{Introduction}

Age is one of the most elusive stellar parameters, particularly for stars on
the main sequence.
Isochrone fitting methods suffer from poor precision, especially when only
photometric information is available, and asteroseismology is limited to a
small sample of bright \kepler\ short cadence targets.
Stellar rotation is often used to infer ages via gyrochronology, however it
remains relatively untested at old ages due to the sparsity of precise data.
The data in hand tell an intriguing story: they indicate that magnetic braking
may cease altogether for old, slowly rotating stars.
Here we investigate another dating method: galactic kinematics.

Observations of stars with a range of ages reveal that older stars have
greater velocity dispersions than younger stars \citep[\eg][]{casagrande2011,
aumer2011}
% Aumer M., Binney J. J., 2011, MNRAS, 397, 1286
% Casagrande L., Scho ̈nrich R., Asplund M., Cassisi S., Ram ́ırez I., Mele ́ndez
J., Bensby T.,
% Feltzing S., 2011, A&A, 530, A138
We calculate the dispersion in vertical action for Gaia DR1 targets in the
\kepler\ field.
Although expected to be a weak tracer of age, vertical action dispersion
should be an accurate one as the underlying physical processes are relatively
simple and well understood.
We test the potential of vertical action dispersion as a clock, by comparing
age predictions to asteroseismic ages.
Using the rotation periods of \kepler\ stars we also test the gyrochronology
relations: does magnetic braking cease at late ages?

The processes behind the formation of the galaxy and the formation of
exoplanets are two complex topics in astrophysics connected by a common theme:
stellar ages.
Main sequence (MS) stars comprise the majority of our galaxy but unfortunately
their ages are notoriously difficult to measure \citep[see][for a
review]{Soderblom2010}.
Their positions on the HR diagram don't change significantly during their
hydrogen burning lifetimes, a fact that is convenient for life on Earth but
inconvenient for galactic archaeologists.
Now, due to the abundance of rotation periods for MS stars provided by Kepler
and to-be provided by TESS, LSST and Wfirst, rotation-dating has the potential
to be the most readily available precise method for inferring stellar ages.
Rotation-dating works well for young stars but its accuracy is questionable
for stars older than the Sun: old \kepler\ asteroseismic stars rotate more
rapidly than expected given their age \citep{Angus2015, Vansaders2016,
Metcalfe2016}.
\citet{Vansaders2016} attribute this to an evolving magnetic dynamo: as stars
reach an critical Rossby number (the ratio of rotation period to the
convective overturn timescale), their magnetic field `switches off' and stars
maintain a constant rotation period after that time.
The data sets typically used to test the age-rotation relations are highly
heterogeneous and each set has its own detection and selection biases.
For example, asteroseismology favours quiet stars whereas rotation periods are
easiest to measure for active stars.
Here, we test the age-rotation relations by comparing rotational (gyrochronal)
age with dynamical age.
Data from the first \Gaia\ data release (DR1) provides kinematic ages for
several MS \Kepler\ stars with detectable rotation periods.
We use these kinematic ages to test the gyrochronology relations at all ages.
% We use the vertical action-age relation for red giants to test the
%     vertical action-age relation for MS stars.

% A history of rotation-dating.
\subsection{The status of gyrochronology}
The phenomenon of magnetic braking in MS stars was first observed almost fifty
years ago by \citet{Skumanich1972} who noticed that the rotation periods of
the Sun and young cluster stars decayed with the square-root of time.
% Later, a mass-dependence was added to the relation between age and rotation
% period --- less massive stars lose angular momentum faster than more massive
% one.
\citet{Kawaler1988} derived a formalism for this angular momentum loss.
 % and his
% relation depended on the mass loss rate, the ....
More recently, \citet{Barnes2003} demonstrated that a simple relation could be
used to describe `gyrochronology', the method of rotation-dating, and further
works \citep[\eg][]{Barnes2007, Mamajek2008, Barnes2010, Meibom2011},
demonstrated that the relation between rotation period and age holds true
while theorists \citep[\eg][]{Matt2012, Epstein2014, Vansaders2013,
Vansaders2015} modify and extend physical models that reproduce the
observations.

As discussed above, the performance of the age-rotation relations for old
stars was recently called into question \citep{Angus2015, Vansaders2016,
Metcalfe2016}.
A simple straight-line model for rotational age does not reproduce the ages
predicted by asteroseismology for stars older than the Sun.
This phenomenon is attributed to a transitioning magnetic dynamo at a critical
Rossby number, $Ro$, of 2.6, the solar value \citep{Vansaders2016}.
As rotation periods slow, $Ro$ decreases until it hits the critical value and
magnetic braking switches off: stars maintain their rotation period from that
point onward.
This restricts the applicability of gyrochronology to young, rapidly rotating
stars only.
This hypothesis is supported by the existing data, however these data are
sparse~---~the analyses demonstrating the discrepancies were conducted on the
small number of main sequence, Solar-like oscillators observed by Kepler in
short cadence mode with detectable rotation periods: a sample size of around
20.
% Furthermore, asteroseismology favors stars with low surface gravities since
% they show the largest amplitudes of oscillation and the majority of stars in
% this sample were slightly evolved.
A larger sample of old main sequence stars with precise ages is required to
confirm and further characterize the Rossby saturation mechanism introduced by
\citep{Vansaders2016}.
However, old main sequence stars are difficult to age-date with any other
method than asteroseismology.
We use the age gradients in the kinematic properties of stars to investigate
the \citet{Vansaders2016} model.

\subsection{Kinematic ages}
The age-velocity dispersion relations are based on relatively simple physics.
There is evidence to suggest that stars in the Milky Way form in the thin disc
of the galaxy with relatively small vertical velocities and angular momenta
\racomment{add citations}.
As time passes these stars are scattered via close encounters with other
stars and interactions with galactic spiral arms.
The more time passes, the more scattering events, and stars slowly accumulate
angular momentum in the vertical direction, known as vertical action.
This results in a slow heating of stellar orbits.
Older stars can be identified in Gaia DR1 by integrating their orbits in the
potential of the Milky Way to convert their proper motions, positions and
parallaxes into vertical actions.
It is the {\it dispersion} in vertical action that truly traces age, far
better than vertical action itself.
However for single stars only the individual's vertical action is available.
Nonetheless, $J_z^2$ increases over time for any given star, and is a weak
tracer of age.


\subsection{Velocity}

\subsection{Momentum}

\subsection{Moving to 3 dimensions}

\subsection{The action integral}

\subsection{Renormalisation}


% The presented approach has been implemented and is planned to be released at the
% conference (this paper is currently under review).

% In this section we discuss our design choices and achieved
% results, comparing them with the project's initial goals: (i)~providing a unified
% specification, testing, and formal verification framework that is (ii)~understandable
% and convenient to use by the REDFIN engineering team, and (iii)~allows the team
% to co-develop REDFIN software and hardware, by extending and modifying the
% default instruction semantics.

% \subsection{From hardware to untyped assembly to typed software}

% The proposed approach covers two levels of organisation of computer systems: the
% hardware microarchitecture (the state monad \hs{Redfin},~\S\ref{sec-transformer}),
% and the instruction set architecture (the assembly monad
% \hs{Script},~\S\ref{sec-verification}). These two levels are very different: the
% former allows hardware engineers to precisely capture the semantics of
% instructions (and has proven useful in exposing underspecified behaviours),
% whereas the latter does not have a direct access to the microarchitectural level
% and is used to symbolically \emph{execute} the semantics, allowing software
% engineers to \emph{observe} the results and \emph{reason} about program
% correctness.

As the previous section~\S\ref{sec-verification} demonstrates, the presented
approach provides a unified specification, testing, and formal verification
framework. It allows the REDFIN engineering team to co-develop REDFIN software
and hardware, by extending and modifying the default instruction semantics.
By using Haskell as a metalanguage, one can implement higher-level languages on
top of the REDFIN assembly, such as our simple statically-typed language for
arithmetic expressions.

Static typing, polymorphism, \textsf{do}-notation, and availability of a mature
symbolic manipulation library~(SBV) were the key factors for choosing Haskell
for this project. We also have a prototype implementation in the
dependently-typed language Idris~\cite{JFP:9060502} that allows us to verify
more sophisticated properties at the type level, however at the time of writing
there is no equivalent of the SBV library in Idris, which is a significant
practical disadvantage.
% Dependent Haskell~\cite{weirich2017dependent} is a
% pos alternative.

% \subsection{Uniform development, testing and verification environment}

The \hs{Script} monad was engineered to provide familiar assembly mnemonics and
directives (e.g. labels), which allows engineers to start
using the framework for developing REDFIN programs even without prior Haskell
experience, hopefully increasing the uptake of the framework.

Thanks to symbolic simulation, we can uniformly handle both concrete and
symbolic values, reusing the same code base and infrastructure for testing and
formal verification.
Testing yields trivial SMT problems that can be solved in sub-second time.
Formal verification is more expensive: in our experiments,
programs of realistic sizes (typical REDFIN programs have hundreds of
instructions) required 10-15 minutes, but one can
easily construct tiny programs that will grind any SMT solver to a halt:
for example, analysis of a single multiplication instruction can take half an
hour if it is required to factor 64-bit numbers --- try to factor
4611686585363088391 with an SMT solver! In such cases, conservatively proving
some of the correctness properties at the type level can significantly increase
the productivity. As a microbenchmark, we verified the correctness of an array
summation program, reporting the number of SMT clauses and Z3 runtime for
low-level (LL) and high-level (HL) programs:

\vspace{2mm}
\noindent
{\smaller\begin{tabular}{l||c|c|c|c|c}
\hline
Benchmark        & Array & Clauses & Clauses & Time    & Time    \\
                 & size  & LL      & HL      & LL      & HL      \\\hline
Overflow:        & 9     & 286     & 260     & 1.482s  & 0.443s  \\
values not       & 12    & 492     & 453     & 3.604s  & 1.365s  \\
constrained      & 15    & 740     & 688     & 49.969s & 7.362s  \\
                 & 18    & 1030    & 965     & 76.757s & 88.458s \\\hline
No overflow:     & 9     & 318     & 292     & 0.467s  & 0.119s  \\
all values       & 12    & 549     & 510     & 0.739s  & 0.682s  \\
in $[1,1000]$    & 15    & 828     & 776     & 1.839s  & 6.408s  \\
                 & 18    & 1155    & 1090    & 9.944s  & 72.880s \\\hline
Equivalence      & 9     & 258     & 261     & 0.039s  & 0.097s  \\
to the \hs{sum}  & 12    & 495     & 459     & 0.053s  & 0.647s  \\
function         & 15    & 708     & 702     & 0.311s  & 7.322s  \\
                 & 18    & 1005    & 990     & 2.633s  & 71.896s \\\hline
\end{tabular}
}

% {\smaller
% \begin{tabular}{c||c|c|c|c|c}
% Array size & 6 & 9 & 12 & 15 & 18 \\\hline
% Low-level & 0.022s & 0.039s & 0.053s & 0.311s & 2.633s \\
% High-level & 0.040s & 0.097s & 0.647s & 7.322s & 71.896s \\
% \end{tabular}
% }

% Although proving properties about the hardware implementation is left for future
% work, the developed infrastructure provides a way to generate testsuites for the
% processing core from the formal semantics of REDFIN instructions. Furthermore,
% one can use the semantics to generate parts of the hardware
% implementation~\cite{reid2016cav} or synthesise efficient instruction
% subsets~\cite{mokhov2014synthesis}.

% \begin{table*}[t]
% \vspace{-1mm}
% \smaller
% \centering
% \begin{tabular}{l||c|c|c|c|c}
% \hline
% Benchmark        & Array & Formula & Formula & Time    & Time    \\
%                  & size  & size LL & size HL & LL      & HL      \\\hline
% Positive         & 9     & 286     & 260     & 1.482s  & 0.443s  \\
% overflow         & 12    & 492     & 453     & 3.604s  & 1.365s  \\
% check            & 15    & 740     & 688     & 49.969s & 7.362s  \\
%                  & 18    & 1030    & 965     & 76.757s & 88.458s \\\hline\hline
% Negative         & 9     & 318     & 292     & 0.467s  & 0.119s  \\
% overflow         & 12    & 549     & 510     & 0.739s  & 0.682s  \\
% check            & 15    & 828     & 776     & 1.839s  & 6.408s  \\
%                  & 18    & 1155    & 1090    & 9.944s  & 72.880s \\\hline\hline
% Equivalent       & 9     & 258     & 261     & 0.039s  & 0.097s  \\
% to the \hs{sum}  & 12    & 495     & 459     & 0.053s  & 0.647s  \\
% function         & 15    & 708     & 702     & 0.311s  & 7.322s  \\
%                  & 18    & 1005    & 990     & 2.633s  & 71.896s \\\hline
% \end{tabular}
% \caption{Verification of low-level and high-level array summation procedures
% \label{tab-sum-benchmark}}
% \caption*{\\$^{(*)}$assuming the summands are in range $[1, 1000]$.
% $^{(**)}$procedure is functionally equivalent to the Haskell's \hs{sum} function.}
% \vspace{-8mm}
% \end{table*}

% Benchmark        & Array & Formula & Formula & Time    & Time    \\
%                  & size  & size LL & size HL & LL      & HL      \\\hline
% Positive         & 6     & 122     & 109     & 0.503s  & 0.288s  \\
% overflow         & 9     & 286     & 260     & 1.482s  & 0.443s  \\
% check            & 12    & 492     & 453     & 3.604s  & 1.365s  \\
%                  & 15    & 740     & 688     & 49.969s & 7.362s  \\
%                  & 18    & 1030    & 965     & 76.757s & 88.458s \\\hline\hline
% Negative         & 6     & 135     & 122     & 0.171s  & 0.070s  \\
% overflow         & 9     & 318     & 292     & 0.467s  & 0.119s  \\
% check            & 12    & 549     & 510     & 0.739s  & 0.682s  \\
%                  & 15    & 828     & 776     & 1.839s  & 6.408s  \\
%                  & 18    & 1155    & 1090    & 9.944s  & 72.880s \\\hline\hline
% Equivalent       & 6     & 105     & 108     & 0.022s  & 0.040s  \\
% to the \hs{sum}  & 9     & 258     & 261     & 0.039s  & 0.097s  \\
% function         & 12    & 495     & 459     & 0.053s  & 0.647s  \\
%                  & 15    & 708     & 702     & 0.311s  & 7.322s  \\
%                  & 18    & 1005    & 990     & 2.633s  & 71.896s \\\hline