\subsection{Tensor valence}


\documentclass[11pt]{article}
\usepackage{geometry} % see geometry.pdf on how to lay out the page. There's lots.
\usepackage{hyperref}
\usepackage{graphicx}
\usepackage{gensymb}
\usepackage[affil-it]{authblk}
\usepackage[toc,page]{appendix}
\usepackage{pifont}
\usepackage{amsmath}
\usepackage{draftwatermark}

\SetWatermarkText{DRAFT}
\SetWatermarkScale{6}
\SetWatermarkLightness{0.95}

% \geometry{letter} % or letter or a5paper or ... etc
% \geometry{landscape} % rotated page geometry

% See the ``Article customise'' template for come common customisations

\title{Cheating Tsiolkovsky's Equation with Highly Unrealizable Physical Approaches}
\author{Robert L. Read
  \thanks{read.robert@gmail.com}
}
\affil{Founder, Public Invention, an educational non-profit.}

\date{\today}

%%% BEGIN DOCUMENT
\begin{document}

\maketitle

%% \tableofcontents

\section{Introduction}

Squirting a bunch of hot gases out of a rocket seems wasteful.
Tsiolkovsky's equation:

\[
\tag{The Rocket Equation} \Delta v = v_e \ln \frac{m_0}{m_f}
\]

is so dreary in its demand that most of a rocket be devoted to fuel
that even its creator cheated it by inventing the multi-stage rocket.

If a rocket starts in free space,
is it possible to build a rocket which is more efficient in power or
conservative of propellant reaction mass by designing the form
of the remaining propellant?

\section{Conservation of Linear Momentum}

Although it is promising to consider powering a rocket with a beam
from a base station, we may be able to learn something interesting from
considering a rocket starting in free space. After all, the base station
itself or the planet it rests upon is simply a large object in free space.

A chemical rocket in free space without gravity is a system that can't
change its center of mass. As the rocket fires, the system spreads out
in space, with the part be call the propellant moving in one direction
and the rocket moving in the other.

Since we are primarily interested in going in one direction fast, we
can think of this as a one-dimensional problem. The fact that a cloud
of gas spreads a little from our single axis is an unfortunate inefficiency.

We choose coordinates so that the directions we wish to go is the positive $x$ axis.
The origin is at the center of mass of our starting machine, which includes the rocket
and its propellant.
Conservation of linear moment applies to whatever form the propellant takes.
If $\dot{P_x}$ is the velocity of the center of mass of the propellant (which will
likely be negative), and $\dot{R_x}$ is the velocity of the rocket:

\[
\label{conslinmom} \tag{CLM} \dot{R_x}\cdot M_R = - \dot{P_x} \cdot M_P
\]

What would happen if instead of throwing gas molecules behind ourselves
we threw solid objects? In other words, what if we used a ``mass driver'',
without specifying how it is powered, to throw a solid propellant?
Could we change Tsiolkovsky's equation in some favorable way?

\section{Extruded Forms}

Suppose that our rocket could extrude an object extremely quickly.
If we extruded an object in the opposite direction we wish to travel,
by the conservation of linear momentum our rocket will move forward.

\[
\tag{Linear Extrusion} R_x - P_x  = \frac{s t}{2}
\]

After doing a lot of math, we determine that the speed of the rocket
at time $t$, assume an extrusion rate of $s$ in $m /s$ and density
of extrusion of $k$ in $kg / $ linear meter,

\[
\dot{R_x} = \frac{k s^2 t}{2 m_0}
\]

where $m_0$ is the total inital mass of the rocket and the propellant:

\[
m_0 = m_R + m_P
\]

or, in terms or Tsiolkovsky's symols, $m_0 = T_m$ and $m_f = m_R$.

By solving for the time it takes to use up all of the propellant and
then substituting back into the form of the Tsiolkovsky equation:

\[
v_r = \frac{s (m_0-m_f)}{2 m_0}
\]

If we graph this against the Tsiolkovsky equation:

INSERT GRAPH HERE

we find that extruding a cylinder very quickly is not quite as
good as squirting gases at the same velocity behind us.
My interpretation of this is that being attached to the extruded
rod during until the momenet of separation holds the rocket back,
where as the acceleartion provided by each molecule of gas
allows the rocket to move forward without being attached.

\subsection{Develop Mathematics of Instantaneous Ejection and Relate}

\section{Constant Acceleration of Cylinder}

Suppose that we could extrude the rod not at a constant speed, but
at a constant acceleration? This is physically hard to engineer,
because as the mass of the rod behind us increases, the force required
to sustain a constant acceleration $A$ increases. Nonetheless if we
work out the math, we obtain:

\[
\tag{Constant Acceleration} R_x - P_x  = \frac{A t^2}{2}
\]

\label{Constant Acceleration} can be differentiated:

\[
\tag{Velocities under C.A.} \dot{R_x} - \dot{P_x}  = A \cdot t
\]

and the mass of the propellant will be:

\[
 M_P = (R_x - P_x)\cdot K \cdot 2
\]

or

\[
 M_P = A t^2 \cdot K
\]

Rearranging and using \eqref{conslinmom}, we obtain:

\[
\dot{R_x}(1 + \frac{M_R}{M_P} ) = A \cdot t
\]
\[
=
\]
\[
\dot{R_x}(\frac{M_P + M_R}{M_P} ) = A \cdot t
\]
\[
=
\]
\[
\dot{R_x} = A \cdot t \cdot (\frac{M_P}{M_P + M_R} )
\]
\[
=
\]
\[
\dot{R_x} = A \cdot t \cdot (\frac{M_P}{m_0} )
\]
\[
=
\]
\[
\dot{R_x} = A \cdot t \cdot (\frac{A t^2 \cdot K }{m_0} )
\]
\[
=
\]
\[
\dot{R_x} = \frac{A^2 t^3 K}{m_0}
\]

...where A is the acceleration we support. If we again solve for the
expulsion of all of the propellant, we obtain:

\[
v_r = \frac{(m_0 - m_f)^\frac{3}{2}\sqrt{\frac{A}{K}}}{m_0}
\]

This goes up as $A$ goes up, and goes up as we dedicated more mass to the propellant as we would expect.
Note that it also goes up as $K$ the denisty of our extrusion goes down, which is perhaps interesting:
the thinnner a rod we can extrude the more efficient our system is.

NEED TO compare to Tsiolkovsky.

But of course this is unrealistic in that we cannot have infinite power in our rocket.
My friend Mr. John Gibbons has criticized this equation as simply obscuring an unrelistic
way to obtain a higher exhaust velocity.

\section{Relate to A Plume of Bouncing Machines}

An alternative to producing a solid plume as a single unit is to eject discrete objects.
These objects can interact by bouncing off each other or potentially accelerating objects
in one direction or the other.  The conservation of linear momentum remains ironclad,
but we may now think of our rocket/propellant complex as a complicated machine which
is working to spread itself out in space. Hopefully we are working to send as much
mass behind us as quickly as possible.

Possibly our propellant could even be complete machines with their own power supply.
Thuse our rocket becomes a line of mass drivers spread out in space that may drive
objects with mass towards or away from the rocket.

The fact that it might be a little tricky to survice collision with or the ``catching'' and
``rethrowing'' of these objects we will ignore for the time being.

We assert that just as the Tsiolkovsky equation can be cheated by using a multi-stage
rocket, it can also be cheated by bouncing objects around in a line, reusing reaction mass.
This can potentially result in final propellant shape more efficient than a plume of
gas flying through and slowly spreading through space.

Even better, if one line of the mass drivers is anchored on a planet, we can
imagine a system in which the rocket is powered from the planet, where presumably power
is cheap, via the transfer or momentum to the rocket via objects driven to and fro from
the rocket to the planet.

\section{The Simulation Showing That Bouncing Leads to Higher Speed}

\section{TODO}

Fill out the math in a reasonable way.  Fill in graphs. Do dimensional analysis.

\end{document}


\chapter{Searching for PBH Candidates in \Fermi-LAT 3FGL Catalog}\label{chapter:pbh_analysis}

\Fermi-LAT surveys the entire sky approximately every three hours, and has relatively uniform exposure over long time scales; in our dataset of 4 years, the exposure above 1 GeV varies by approximately 40\% over the entire sky. Combined with a large effective area (approximately 1 m$^2$ between 1 GeV and 1 TeV), this makes it an ideal instrument for detecting a large number of gamma-ray point sources.
The most complete catalog of point sources is currently the third \Fermi point source catalog \citep[3FGL, ][]{2015ApJS..218...23A} (see Section \ref{sec:analysisTools} for a brief description of the methodology that the \Fermi-LAT collaboration uses to build catalogs).
The 3FGL contains sources that are significantly detected above 100 MeV and spans the first 4 years of the \Fermi mission.
%A complete description of the 3FGL can be found in \citep{2015ApJS..218...23A}. .
In this chapter, I use the 3FGL catalog to search for PBH candidates and to constrain the local PBH evaporation rate.

\section{Search Strategy}
\label{sec:search}
The first step in selecting PBH candidates in the 3FGL catalog was excluding from further consideration point sources associated with known astrophysical sources (such as blazars). Of 3033 sources in the 3FGL catalog, 1010 are unassociated sources. Also excluded were a further 468 unassociated sources that lie within $10^\circ$ of the Galactic plane. The analysis was restricted to high-latitude sources for three reasons: (a) detectable PBHs are expected be distributed isotropically given the detectability distances estimated in Section \ref{sec:sens}, while astrophysical sources are concentrated along the Galactic plane, (b) association of extragalactic sources such as blazars is easier at high latitude
\citep[see, e.g.][]{2015ApJ...810...14A}, and (c) the reduced Galactic diffuse emission at high latitude makes proper motion identification easier.

The spectra of the remaining unassociated 3FGL sources were next compared with the time-integrated PBH gamma-ray spectrum.
Spectra of the candidate sources are reported in the 3FGL as fluxes in 5 energy bands (0.1 -- 0.3, 0.3 -- 1, 1 -- 3, 3 -- 10, and 10 -- 100 GeV).
The time-integrated PBH spectrum depends on two parameters: initial mass (or temperature), and the distance to the Earth (equivalent to an overall normalization).
These two parameters were varied to obtain the best fit to the candidate source spectra in the five energy bands.
The quality of the fit to the 3FGL spectrum was determined by calculating the value of the $\chi ^2$ over the five energy bands:

\noindent
\begin{equation}
\chi^2 = \sum_{i = 1}^{5} \frac{(\Phi_i-\Psi_i )^2}{\sigma_i^2},
\end{equation}
where $\Phi_i$ is the PBH spectrum integrated over the width of bin $i$ and $\Psi_i$ is the flux in bin $i$ reported in the 3FGL. Here $\sigma_i$ represents the uncertainty on the flux in bin $i$.
In the 3FGL, flux uncertainty is represented by a 68\% confidence interval; the value of the uncertainty can then be written as the difference between the best-fit flux and either the upper or lower bound.
We set $\sigma_i$ to be the larger of the two in order to be conservative.
We require the value of the best-fit $\chi^2$ to be below the critical value of 11.3, which corresponds to 99\% exclusion for 5 degrees of freedom and 2 parameters. In other words, sources with a $\chi ^2$ value greater than 11.3 have only a 1\% chance of being spectrally consistent with a PBH. After the spectral consistency was computed, 318 sources out of the 542 unassociated candidates remained as plausible PBH candidates.
The candidate sources next underwent a check for proper motion.

\subsection{Proper Motion}\label{sec:propmotion}
Several algorithms were examined for the ability to discriminate between moving and stationary sources.
Inspired by the track reconstruction algorithms used in the \Fermi-LAT tracker, the first algorithm studied was a Kalman filter, implemented with a model of a moving source (with Gaussian uncertainty at each data point).
The Kalman filter was successful was successful in Monte Carlo simulations of reconstructing the velocity of a moving point source, but is not easily adapted to cases where the signal is subdominant to background.

Next studied was an algorithm which computed the moment of inertia tensor of the source photon locations.
Subsequent diagonalization of the moment of inertia tensor gave the spatial eigenvectors and eigenvalues associated with the source; any motion was assumed to take place along the larger of the two eigenvectors.
The photons were divided into two groups according to which side of the center of mass (along the eigenvector) they fell, and the mean arrival times of the two groups of photons were compared.
However, the moment of inertia depends on the square of the distance of each photon from the center of mass.
Therefore the algorithm was found to be too sensitive to the diffuse background, which is distributed isotropically across the region of interest, and nearby non-candidate point sources.

After further testing, an algorithm was built which uses the method of maximum likelihood estimation to (a) weight background photons given a model of the ROI, and (b) reconstruct the proper motion of the candidate source.
The algorithm works as follows:
\begin{enumerate}
\item
All source-class photons above 1 GeV within $5^\circ$ of the source's reported 3FGL location were collected.
The time range (August 2008 to July 2012) and data reconstruction (\texttt{P7REP\char`_SOURCE\char`_V15}) were consistent with that of the data used to construct the 3FGL.
Since the angular resolution of the \Fermi LAT decreases quickly below 1 GeV, including photons below 1 GeV did not have a significant impact on the final results.
\item
Data covering a longer time range (August 2008 to July 2017) and a more recent event reconstruction (\texttt{P8R2\char`_SOURCE\char`_V6}) were held in reserve for validation, and was used to test the PBH hypothesis for any sources that passed the proper motion cut.

\item
The expected number of photons $N$ from the source of interest was calculated by multiplying the flux in each energy bin by
the \Fermi-LAT exposure at the bin's midpoint energy, and summing over the three relevant bins (1 -- 3 GeV, 3 -- 10 GeV, 10 -- 100 GeV).
\item
\label{step:prop_motion_likelihood}
In order to estimate the velocity of a PS, the maxima of the likelihood function $\mathcal{L}(\vec{x_i},t_i,\vec{x_0},\vec{v_0})$ are compared in two cases:
fixed $\vec{v_0}=0$ and free $\vec{v_0}$.
The point spread function of \Fermi-LAT was approximated as a Gaussian for simplicity.
The likelihood function is given by multiplying over $N$ photons around the initial position of the source:

\noindent
\begin{equation}
\label{eq:vlike}
\mathcal{L} = \prod_{i=1}^{N}w_i\times \textup{exp} \big\{\frac{{-(\vec{x_i}-\vec{x_0}-\vec{v_0}t_i)^2}}{{\sigma_i^2}}\big\}
\end{equation}
where $\vec{x_i}$ is the coordinates of the photon, $\vec{v_0}$ is the proper motion of the source, $t_i$ is the photon arrival time, $\vec{x_0}$ is the source location at the beginning of the observation time, and $\sigma_i$ is the 68\% angular containment radius for a photon at energy $E_i$, which is $\sim 0.7^\circ$ at 1 GeV \citep{2013arXiv1304.5456B}.
Here $w_i$ is a weight assigned to each photon, the calculation of which is defined in Section \ref{sec:likelihood}.

In practice, the natural logarithm of the likelihood is used:
\begin{equation}
\label{eq:vloglike}
\log \mathcal{L} = \sum_{i=1}^{N}\log w_i-\frac{{(\vec{x_i}-\vec{x_0}-\vec{v_0}t_i)^2}}{{\sigma_i^2}}
\end{equation}

The main difficulty is separating the $N$ photons attributed to the source from background photons.
The algorithm chooses a 4-dimensional grid of points around an initial value of $\vec{x_0}$ and $\vec{v_0} = 0$, and for each grid point finds the $N$ photons
inside the $5^\circ$ ROI that have the highest contribution to $\log \mathcal{L}$, i.e. the photons which most likely belong to the source given a particular position and velocity.
Therefore the weights $w_i$ do not appear as a prefactor in Eqs \ref{eq:vlike} and \ref{eq:vloglike} because the $N$ best-fit photons change given different assumptions of $\vec{x_0}$ and $\vec{v_0}$.
The best-fit $\vec{x_0}$ and $\vec{v_0}$ are found by maximizing $\Delta \log \mathcal{L} = \log \mathcal{L} - \log \mathcal{L}(\vec{v_0}=0)$ on the grid.
With the additional degrees of freedom from allowing $\vec{v_0}$ to float, the value of $\Delta \log \mathcal{L}$ is always nonnegative.

MC simulations (described in Section \ref{sec:MClimit}) demonstrate that this algorithm tends to underestimate the input velocity by $\approx 25\%$;
the best-fit velocity should therefore be considered a lower bound on the true velocity and sufficient for our purpose of separation of moving and stationary sources.
The underestimation occurs because source photons that are far away from the average source position have lower weights and so are less often included in the likelihood calculation.
In their place are background photons, whose distribution in time is random, and therefore cause the algorithm to favor a slower overall velocity.
%The $N$ photons used in the calculation will generally change over the course of the maximization procedure, because it is not possible to discriminate between individual source and nearby background photons. However, the algorithm converges if the source is sufficiently brighter than the background.
\item
The significance of $\Delta \log \mathcal{L}$ for each source was found by assigning random times $t_i$ drawn from a flat distribution to each photon but fixing the positions $\vec{x_i}$ of all the photons, and reoptimizing $\Delta \log \mathcal{L}$.
This process was repeated 50 times for each source, and the original value of $\Delta \log \mathcal{L}$ was compared with the distribution of $\Delta \log \mathcal{L}$ for the data sets scrambled in time to find a local significance $\sigma$:

\noindent
\begin{equation}
\sigma = \frac{\Delta \log \mathcal{L}_0 - \overline{\Delta \log \mathcal{L}_s}}{\textup{std}(\Delta \log \mathcal{L}_s)},
\end{equation}
where $\Delta \log \mathcal{L}_0$ is the original value of the improvement in likelihood, $\overline{\Delta \log \mathcal{L}_s}$ is the mean of the scrambled likelihood improvements, and $\textup{std}(\Delta \log \mathcal{L}_s)$ is the standard deviation of the scrambled likelihood improvements.
\item
A cut on the local significance for each source was made at $3.6 \sigma$ which corresponds to a global significance of $2 \sigma$ for 318 sources.
\end{enumerate}

The key step in this process is the maximization of likelihood in Step \ref{step:prop_motion_likelihood}.
Because the algorithm only considers the $N$ best photons at each grid point, it is highly resistant to background photons in cases where the source is undergoing proper motion; background photons are generally distributed evenly across time which means they are unlikely to fit well to the reconstructed path of the source at the grid point under consideration.
Monte Carlo simulations of PBHs show that the algorithm is highly successful (See Figure X) at reconstructing the true velocity in cases where the PBH has a lifetime at least as long as the time considered.
In cases where the PBH evaporates before the end of the time period, the velocity reconstruction is not accurate, but the discrimination between moving and stationary sources is still sufficient.
Long-lived PBHs far outnumber short-lived ones due to the nonlinear nature of the evaporation process- see Equation \ref{eq:Tdistr}- so the algorithm was designed to maximize sensitivity to long-lived PBHs.

\begin{figure}
\begin{center}
\includegraphics[width=0.9\columnwidth]{figures/reconstructedVelocity.pdf}
\caption{
\label{fig:reconstruction}
Reconstructed velocities from MC simulations (described in Section \ref{sec:MClimit}). The reconstruction is not perfect due to the presence of background photons and statistical fluctuations, and works best for slow-moving sources. At high velocities, the reconstructed velocity is generally below the true velocity because of the photon weighting scheme (Section \ref{sec:likelihood}) which favors slow-moving sources. The coloring indicates distance, showing that distant sources must be moving relatively slowly to pass the selection criteria.
}
\end{center}
\end{figure}

A single source (3FGL J2310.1$-$0557, see Section \ref{sec:j2310} for a discussion of this source) exceeded this cut on local significance, and the standard deviation of the local significances of the entire set of candidates was 1.03, which is consistent with statistical fluctuations.
After examining the data held in reserve for J2310.1$-$0557 (described in Section \ref{sec:j2310}), it was concluded that no likely PBH candidates exist in the 3FGL catalog.

\subsection{Photon Weights}
\label{sec:likelihood}

The photon weights $w_i$ in equations \ref{eq:vlike} and \ref{eq:vloglike} are defined as the probability that a given photon originated from the candidate PS, and are calculated by performing a standard likelihood optimization with the \Fermi Science Tool {\tt gtlike}\footnote{Science Tools version v10r0p5, available at \url{http://fermi.gsfc.nasa.gov/ssc/data/analysis/software}}.
The model used includes all 3FGL PS within 5$^\circ$ of the candidate source, as well as the standard Pass 7 models for Galactic and isotropic diffuse emission.
The candidate source is modeled as an extended source with a radial Gaussian profile with $\sigma=0.25^\circ$ instead of a PS, in order to account for the possibility of small amounts of proper motion.
The data were binned into three logarithmically spaced energy bands between 1 GeV and 100 GeV and in $0.1^\circ \times 0.1^\circ$ spatial pixels.
After the model was optimized by {\tt gtlike}, weights were assigned to each photon (described its coordinates $x$, $y$, and energy $E$) by calculating the fraction of the flux belonging to the candidate source in each pixel:

\begin{equation}
w_{x,y,E} = \frac{\Phi'(x,y,E)}{\sum_i \Phi_i(x,y,E)}
\end{equation}
where $\Phi'(x,y,E)$ is the predicted flux from the candidate source in the pixel and $\Phi_i(x,y,E)$ are the fluxes from all the sources in the model.

In addition, the 3FGL PS were masked by assigning a weight of zero to all the photons which fell in a pixel more than 1$^\circ$ from the candidate source position where the summed contribution of the non-candidate PS fluxes exceeded 10\% of the total flux in that pixel.
This meant that all the photons in the calculation had a high probability of originating only from either the candidate source or the diffuse background.

The weighting has little impact on the reconstruction of proper motion because individual photon weights do not change as the likelihood maximization from step \ref{step:prop_motion_likelihood} optimizes $\vec{x_0}$ and $\vec{v_0}$.
However, weighting the photons in this way prevents the algorithm from interpreting photons from nearby sources as originating from the candidate source.
Without weighting, nearby flaring sources could mimic a moving source and therefore lead to false positives.

The radial Gaussian weighting of the candidate PS does reduce the accuracy of reconstructing the proper motion of fast-moving sources- see Figre X.
Because the main purpose of the algorithm is simply to discriminate between moving and non-moving sources, this was deemed an acceptable tradeoff for the improvement in background rejection that comes from the weighting.

\subsection{J2310.1$-$0557}
\label{sec:j2310}
The source J2310.1$-$0557 passed the proper motion cut with a significance of 4.2$\sigma$, and was therefore investigated further.
Approximately 9 years (August 2008 to July 2017) of Pass 8 (\texttt{P8\char`_SOURCE\char`_V6}) data above 1 GeV in an ROI of 5$^\circ$ around the source location were collected.
The increased statistics and improved angular resolution of the Pass 8 data set clearly indicated that J2310.1$-$0557 lies approximately 1$^\circ$ away from a separate, highly variable source of gamma rays which is not in the 3FGL catalog.
This source flared brightly (approximately 150 photons above 1 GeV) on 7 March 2011 (near the end of the 3FGL time period) but was quiet for the remainder of the period.
We found that the position of the source was consistent with the Sun, which flared brightly on the same date \citep{2011ATel.3214....1A}.
$\gamma$-ray emission from the Sun and Moon was not included in the models of the ROI.

The effect of the solar flare near a candidate PBH was to mimic a moving source, which explains why the proper motion algorithm returned a positive result.
Because the sources in the Monte Carlo simulation described in Section \ref{sec:MClimit} are placed at random points on the sky, similar false positives are expected to occur in the simulations.
Therefore,the upper limit on PBH evaporation rate is reported as if one source passed our criteria, even though J2310.1$-$0557 is not a good PBH candidate.
Incidentally after the publication of the 3FGL source list, J2310.1$-$0557 was found to be a millisecond pulsar\footnote{See https://confluence.slac.stanford.edu/display/SCIGRPS/LAT+Pulsations+from+PSR+J2310-0555}.

\begin{figure}
\begin{center}
\includegraphics[width=0.45\columnwidth]{figures/3fgl_overlay.pdf}
\includegraphics[width=0.45\columnwidth]{figures/4fgl_overlay.pdf}
\caption{
\label{fig:j2310}
{\it Left Panel:} 5$^\circ$ ROI around 3FGL J2310.1$-$0557, using the 4 years of data from the 3FGL analysis. The source at the center of the image appears to be extended due to the 7 March 2011 solar flare just to the upper-left of the candidate source.
{\it Right Panel:} The same ROI using 9 years of data and using the more recent Pass 8 reconstruction algorithms. The formerly extended source is clearly resolved as two separate sources.
}
\end{center}
\end{figure}
\section{Limits on PBH\MakeLowercase{s}}
\label{sec:MClimit}

An analytic derivation of the upper limit on the local PBH evaporation rate is difficult due to the complex nature of the variables in question.
For a PBH to pass all the cuts in Section \ref{sec:search}, it must have three main characteristics: (a) be listed as a PS in the 3FGL, (b) have a reconstructed spectrum which is consistent with a PBH, and (c) yield a significant proper motion when analyzed with the algorithm described in Section \ref{sec:propmotion}.
Each step in this process depends intimately on models of the background, as well as the temperature, distance, and velocity of the PBH.
Therefore, the efficiency for detecting PBHs was derived from Monte Carlo (MC) simulations.
Upper limits on the local PBH evaporation rate were then placed using the derived efficiency.

A sample of PBHs was generated within 0.08 pc of the Earth with uniform spatial density.
The PBH velocites were randomly sampled from a Gaussian distribution that had an average value of $250\rm\,km\, s^{-1}$, which is close to an upper bound on orbital velocity of the Sun around the Galactic center \citep{1999MNRAS.310..645W, 2008ApJ...684.1143X, 2009PASJ...61..227S, 2010ApJ...720L.108G, 2010MNRAS.402..934M, 2011MNRAS.414.2446M},
and dispersion equal to the local velocity dispersion of dark matter, $270\rm\,km\, s^{-1}$ \citep{2010JCAP...02..030K}.
At the end of this section, different assumptions about the PBH distribution (such as the relative velocity and velocity dispersion) are used to calculate an upper limit for the evaporation rate, providing an estimate of the systematic uncertainty.

The PBH population is assumed to have a constant rate of PBH evaporations, $\dot{\rho}_{\rm PBH} = const$ which is reasonable given the short time period of the search (4 years) compared with the age of the Universe.
A constant rate of evaporation implies that the derivative of the PBH density is related to the PBH temperature as:

\noindent
\begin{equation}
\label{eq:Tdistr}
\frac{d \rho_{\rm PBH}}{d T} \propto T^{-4}.
\end{equation}

This relation can be derived as follows: Let $\rho_{\rm PBH}(T)$ be the density of PBHs with temperature larger than $T$. If $\tau(T)$ is the lifetime of a PBH with temperature $T$, then all PBHs with $T' > T$ will evaporate during time $\tau$. Consequently,

\noindent
\begin{equation}
\label{eq:rho0}
\rho_{\rm PBH}(T) = \int_0^{\tau(T)} \dot{\rho}_{\rm PBH} dt = \dot{\rho}_{\rm PBH}\; \tau(T).
\end{equation}
Now taking into account that $\tau \propto T^{-3}$ and differentiating with respect to $T$ to get
Equation (\ref{eq:Tdistr}).

The following steps were performed in the derivation of the PBH evaporation rate limit:
\vspace{-2mm}
\begin{enumerate}
\item
\label{item:make_pbhs}
A sample of PBHs $(T_i, \vec{x}_i, \vec{v}_i)$ was simulated with temperatures $T_i>5\: {\rm GeV}$ and $T_i<60\: {\rm GeV}$ distributed according to Equation (\ref{eq:Tdistr}), and distances $R_i$ within $R < 0.08$ pc around the Earth.
The velocities $v_i$ of the sample PBHs were distributed with mean equal to the orbital velocity of the Sun,
$v_{\rm rot} = 250\; {\rm km\: s^{-1}}$,
and dispersion $v_{\rm disp} = 270\; {\rm km\: s^{-1}}$.
\item
The photons emitted by each PBH were simulated over the 4 year 3FGL time period, consistent with the parent PBH evolution.
A time step of $\Delta t = 1$ day was used in modeling the evolution of the PBH position and temperature since \Fermi LAT has relatively uniform exposure on time periods longer than 1 day; because the analysis takes place over 4 years the uneven exposure on timescales shorter than 1 day are negligible.
 The number of photons detected by the \Fermi LAT each day was given by a Poisson random value with a mean of

\noindent
\begin{equation}
\overline{N(t)} = \frac{ \Delta t}{4\pi R^2}\int_{\textup{E=100 MeV}}^{\textup{E=500 GeV}} {\Phi(E,t)} A(E) dE,
\end{equation}
where $A$ is defined as the average \Fermi-LAT exposure per unit time at the position of the simulated PBH, and $R$ is the distance from the Earth.
The energy of each photon was found by random sampling of $\Phi(E,t)\times A(E)$.
PBH emission spectra $\Phi(E,t)$ are discussed in Appendix \ref{chapter:pbh_spectrum}.
The positions of the photons were randomized according to the \Fermi-LAT point-spread function (modeled as a Gaussian distribution) at the photon energy.

\item
\label{item:detection}
The list of simulated PBH photons was concatenated to the real photons present within $5^\circ$ of the final location of the PBH, with the same data selection as the 3FGL. A likelihood fit using the \Fermi Science Tool {\tt gtlike} was performed in a $7^{\circ}\times7^{\circ}$ ROI centered at the same location, using a model of the sky which included all 3FGL sources within $5^\circ$ of the ROI center, as well as models of the isotropic diffuse and Galactic diffuse emission\footnote{The models used were the standard Pass 7 (for consistency with the 3FGL) diffuse emission models available from \url{https://fermi.gsfc.nasa.gov/ssc/data/access/lat/BackgroundModels.html}}. The PBH was modeled as a source with a LogParabola spectrum, with fitting parameters restricted to the ranges $1.2<\alpha<3.0$ and $0.0<\beta<1.0$. Once the likelihood maximization was complete, the PBH was considered detected if its TS value was greater than 25, which is consistent with the 3FGL cutoff.
\item
\label{item:spectrum}
If the PBH source was detected, the results from the likelihood fit were used to find the source flux in the five energy bins reported in the 3FGL catalog. The spectral consistency with a PBH spectrum was then calculated in the same way as described in Section \ref{sec:search}.
\item
\label{item:motion}
If the source was found to be spectrally consistent with a PBH, the significance of any proper motion was evaluated by the algorithm described in Section \ref{sec:search}. The combined efficiency of steps \ref{item:detection}$-$\ref{item:motion} is displayed in Figure \ref{fig:det_map}. We smoothed the results by convolving the detectability map with a 3$\times$3 matrix of ones, which had a minor ($\approx$ 8\%) impact on the resulting limit. The impact of fluctuations was quantified by observing the change in the limit as the number of simulations increased; we found that an increase of the number of simulations by 100\% had less than a 20\% change in the resulting limit.
\item

\label{step:eff}
To derive an upper limit on the number of PBH evaporations in our search region, we begin with the number of expected detections:

\noindent
\begin{equation}
\label{eq:N_det}
N = \rho \epsilon V,
\end{equation}
where $\rho$ is the true density of PBHs and $V$ is the volume searched.
$\epsilon$ is the average PBH detection efficiency in time $t = 4$ yr and within the search volume $V$ (a sphere with radius 0.08 pc, with the wedge corresponding to $|b|<10^\circ$ removed);
it is calculated by taking the mean over the pixels in Figure \ref{fig:det_map} with the weight $R^2 T^{-4}$:

\noindent
\begin{equation}
\epsilon = \frac{\iint \epsilon (R, T) \frac{R^2}{T^4} \,dR\,dT }{\iint \frac{R^2}{T^4}\,dR\,dT },
\end{equation}
where the integrals run over the space of parameters described in step \ref{item:make_pbhs}.
Equation \ref{eq:N_det} can be inverted to find the PBH density $\rho$ as a function of the number of detections $N$, or the upper limit on $\rho$ given an upper limit on $N$. Given that one PBH candidate passed the selection criteria described in Section \ref{sec:search}, we set an upper limit $N < 6.64$,
which is the 99\% confidence upper limit on the mean of a Poisson distribution with 1 observed event.

\item
\label{item:limit}
We convert the upper limit on $\rho$ to an upper limit on $\dot{\rho}$ by finding the fraction $f$ of PBHs that would have evaporated during the search time
$t$.
Given a time of observation of 4 years, we find that all PBHs with initial temperature above 16.4 GeV would evaporate. Therefore,

\noindent
\begin{equation}
f = \frac{\int_{\textup{16.4 GeV}}^{\textup{60 GeV}} T^{-4} \,dT}{\int_{\textup{5 GeV}}^{\textup{60 GeV}} T^{-4} \,dT}.
\end{equation}
We calculate the 99\% upper limit on $\dot{\rho}_{\rm PBH}$ to be:

\noindent
\begin{equation}
\dot{\rho}_{\rm PBH} < f\frac{6.64}{\epsilon V t} = 7.2 \times 10^3 \textup{ pc}^{-3} \textup{ year}^{-1}.
\end{equation}

\item
We estimated the systematic uncertainties arising from the uncertaintes in the PBH spectrum by varying the overall normalization of the PBH spectrum (see Appendix \ref{app:PBH_spectrum}) and varying the velocity distributions of the Milky Way disk and DM halo. We consider two scenarios (``aggressive" and ``conservative") which give the best and worst sensitivity, respectively. Steps \ref{item:make_pbhs}$-$\ref{item:limit} are then repeated to find the resulting limit. The parameters of the aggressive and conservative models, as well as the resulting limits, are listed in Table \ref{table:systematics}.
\begin{table}[h]
\begin{center}
\begin{tabular}{|c c c c c|}
\hline
Model & Spectrum Normalization & Orbital Velocity (${\rm km\: s^{-1}}$) & DM Halo Velocity (${\rm km\: s^{-1}}$) & Limit\\
\hline
Aggressive & $\frac{0.45}{0.35}$ & 100 & 150 & $4.8\times 10^3  \textup{ pc}^{-3}  \textup{yr}^{-1}$ \\
Conservative & $\frac{0.25}{0.35}$ & 300 & 350 & $15.3\times10^3 \textup{ pc}^{-3} \textup{ yr}^{-1}$ \\
\hline
\end{tabular}
\caption{Parameters used in estimation of systematic uncertainty.
To be more conservative in the estimates of the systematic uncertainties,
we have tested the ranges of orbital velocities and the DM dispersion velocities which are larger than most of the values reported
in the literature
\citep{1999MNRAS.310..645W, 2008ApJ...684.1143X, 2009PASJ...61..227S, 2010ApJ...720L.108G, 2010JCAP...02..030K,
2010MNRAS.402..934M, 2011MNRAS.414.2446M}.}
%e.g., $\sim 200 - 280\: {\rm km / s}$ in \cite{2010MNRAS.402..934M}.}
%The range of uncertainty in the orbital velocity is somewhat more conservative than the range given in \citep{2010MNRAS.402..934M}}
\label{table:systematics}
\end{center}
\end{table}

The limit including the systematic uncertainties is

\noindent
\begin{equation}
\label{eq:ev_rate}
%\dot{\rho}_{\rm PBH} < (19.2\pm 1.5 \textup{[stat]} ^{+14.8}_{-9.6} \textup{[syst]}) \times 10^3 \textup{ pc}^{-3} \textup{ yr}^{-1}.
\dot{\rho}_{\rm PBH} < (7.2^{+8.1}_{-2.4} ) \times 10^3 \textup{ pc}^{-3} \textup{ yr}^{-1}.
\end{equation}
\end{enumerate}

%For comparison, if we assume no candidate source had passed our selection criteria, the limit would be $\dot{\rho}_{\rm PBH} < (5.0^{+5.6}_{-1.6} ) \times 10^3 \textup{ pc}^{-3} \textup{ yr}^{-1}$.
\begin{figure}[htbp]
\begin{center}
\epsfig{figure = figures/detectability_map.pdf, scale=\onepic}
\noindent
\end{center}
\caption{\small
\label{fig:det_map}
Fraction of simulated PBHs which are detected as a point source with a spectrum compatible with a PBH evaporation spectrum and with significant proper motion. The detectability peaks for PBHs with initial temperatures above 16.4 GeV because the lifetime of a 16.4 GeV PBH is 4 years, which is the same as the observation period of the 3FGL. Few PBHs are detected past a distance of 0.05 pc or below 10 GeV.}

\end{figure}


\chapter{Performing Optimizations}
\label{chap:chapter8}

This chapter explains how to use the Herbrand Equivalence analysis
information to perform actual program optimizations.

\section{Available Variables}
\label{AvailableVariables}
A variable is said to be \textbf{available} at a basic block if
it is defined at some point along all the execution paths from the
start of the program that reaches the beginnning of that basic block.
It is forward data analysis problem and can be determined via fixed
point computation.

The universe $\mathcal U$ would be the set of all program variables.
Also, let $\mathcal B$ be the set of all basic blocks in the program.
Denote by $DEF[B]$ the set of variables defined in the basic block
$B \in \mathcal B$, and $IN[B]$ be corresponding set of available
variables. Initialise $OUT[B] = \mathcal U, \forall B \in \mathcal B$
and perform updates as follows till a fixed point is reached.
$$IN[B] = \cap_{B' \in Predecessors(B)} OUT[B']$$
$$OUT[B] = IN[B] \cup DEF[B]$$

Note that the definition of \textbf{available variables} is different
from that of \textbf{reaching definitions} and \textbf{available
expressions}. If a variable is available at the beginning of a given
basic block, then that variable can be used in the basic block without
defining it because by \textit{definition of avilable variables} it
would already be defined along every path from the start of the
program to that basic block.

The definition of available variables can be extended to that of any
instruction. Variables available at an instruction $I$ is the union
of variables available at the beginning of its basic block and any
variables defined by the instructions preceding it in that block.

\section{Performing Optimizations}
\label{PerformingOptimizations}
The results of Herbrand Equivalence and available variables analysis
can be used to perform optimizations involving redundant expression
elimination and some dead code elimination.

Suppose, there is an instruction $I : z \gets e$, where $e$ is an
expression (as already mentioned expression means either a constant,
or a variable or a length two expression). First find the Herbrand
equivalence class of $z$ at that program point. If the class represents
a constant valued expression ($partitions[I][z].isConst == true$), then
this instruction can be deleted and all uses of $z$ replaced by
$partitions[I][z].constVal$, till $z$ is redefined. Else if it is not
a constant valued expression,
$\mathcal S = (getClass(partitions[I], z) \cap IN[I])$
will be the set of variables, such that $z$ can be replaced by
$s \in \mathcal S$ (before $z$ and $s$ are redefined), without changing
the meaning of the program. \\
Pseudocode \ref{Optimize} is the precise formulation of the mentioned facts.

\begin{algorithm}
\caption{Performing Optimizations}\label{Optimize}
\begin{algorithmic}[1]
\Procedure{Optimize}{}
    \For{$B \in \mathcal B$}
        \State $Insts \gets$ \textbf{Instructions}$(B)$
        \State $AvailVars \gets IN[B]$
        \State
        \For{$I \in Insts$}
            \State $Insts.remove(I)$
            \State $z \gets$ \textbf{LValue}$(I)$
\algstore{Optimize}
\end{algorithmic}
\end{algorithm}

\begin{algorithm}
\begin{algorithmic}[1]
\algrestore{Optimize}
            \If{\textbf{Defined}$(z)$}
                \State \textbf{IDstruct*} $ptr \gets partitions[I][z]$
                \State
                \If{$ptr.isConst$}
                    \State \textbf{Bool} $reachedEnd \gets true$
                    \For{$I' \in Insts$}
                        \If{\textbf{LValue}$(I') == z$}
                            \State $reachedEnd \gets false$
                            \State \textbf{break}
                        \EndIf
                        \State \textbf{Replace}$(I',\ z,\ ptr.constVal)$
                    \EndFor
                    \If{$reachedEnd$}
                        \State $B.insert(z \gets ptr.constVal)$
                    \EndIf
                    \State
                    \State \textbf{DeleteInstruction}$(I)$
                \Else
                    \State \textbf{set}$<$\textbf{Expressions}$> curPart \gets$ \textbf{GetClass}$(partitions[I],\ z)$
                    \State $curPart \gets (curPart \cap AvailVars)$
                    \State
                    \If{not $curPart.empty()$}
                        \State \textbf{Bool} $reachedEnd \gets true$
                        \State $replacement \gets curPart.first()$
                        \State
                        \For{$I' \in Insts$}
                            \If{\textbf{LValue}$(I') == z$}
                                \State $reachedEnd \gets false$
                                \State \textbf{break}
                            \EndIf
                            \State $curPart = curPart \setminus \{$\textbf{LValue}$(I')\}$
                            \If{not $curPart.empty()$}
                                \State $replacement \gets curPart.first()$
                                \State \textbf{Replace}$(I',\ z,\ replacement)$
                            \Else
                                \State $B.insert(I', z \gets replacement)$
                                \State $AvailVars \gets AvailVars \cup \{z\}$
                                \State $reachedEnd \gets false$
                                \State \textbf{break}
                            \EndIf
                        \EndFor
                        \State
                        \If{$reachedEnd$}
                            \State $B.insert(z \gets replacement)$
                        \EndIf
                        \State \textbf{DeleteInstruction}$(I)$
                        \State
                    \Else
                        \State $AvailVars \gets AvarilVars \cup \{z\}$
                    \EndIf
                \EndIf
            \EndIf
        \EndFor
    \EndFor
\EndProcedure
\end{algorithmic}
\end{algorithm}

Also note the following functions whose details has not been provided.\\
\textbf{Instructions}$(B)$ :- Returns a list of instructions in the basic block $B$.\\
\textbf{Replace}$(I', z, replacement)$ :- Replaces variable $z$ in the instruction $I'$ with $replacement$ which can be a constant or another variable.\\
\textbf{B.insert}$(I)$ :- Inserts instruction $I$, at the end of basic block $B$.\\
\textbf{B.insert}$(I, I')$ :- Insert instruction $I'$ before instruction $I$ in basic block $B$.\\
\textbf{DeleteInstruction}$(I)$ :- Deletes instruction $I$ from the program.\\
\textbf{set.empty}$()$ :- Returns $true$ if $set$ is empty, else $false$.\\
\textbf{set.first}$()$ :- Returns first element from $set$.\\

\section{LLVM Implementation}
\label{LLVMImplementation}
The LLVM specific implementation of the pseudocodes mentioned can be found in
\href{https://github.com/himanshu520/HerbrandEquivalence}{this github repository}.


\documentclass[12pt]{article}

\usepackage[top=1in, bottom=1in, left=1in, right=1in]{geometry}
\usepackage{graphicx}
\usepackage{titling}
\usepackage{float}
\usepackage{bm}
%\usepackage[fleqn]{amsmath}
\usepackage{amssymb,amsmath}
\usepackage{listings}
\usepackage{color}
\usepackage{multirow}
\usepackage{enumitem}
\usepackage{fancyvrb}
\usepackage{hyperref}
\usepackage{setspace}
\usepackage{tabularx}
\usepackage{diagbox}
\geometry{letterpaper}
\linespread{1.1}% \geometry{landscape} % rotated page geometry

\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codepurple}{rgb}{0.58,0,0.82}
\definecolor{backcolour}{rgb}{0.95,0.95,0.92}
\definecolor{outcolor}{rgb}{0.545, 0.0, 0.0}

\lstdefinestyle{mystyle}{
	backgroundcolor=\color{backcolour},
	commentstyle=\color{codegreen},
	keywordstyle=\color{magenta},
	numberstyle=\tiny\color{codegray},
	stringstyle=\color{codepurple},
	basicstyle=\footnotesize,
	breakatwhitespace=false,
	breaklines=true,
	captionpos=b,
	keepspaces=true,
	numbers=left,
	numbersep=5pt,
	showspaces=false,
	showstringspaces=false,
	showtabs=false,
	tabsize=2
}

\lstset{style=mystyle}

\setlength{\droptitle}{-5em}
\title{CE 295 Project Proposal}
\date{9 Feb. 2018}
\author{Team 17}

\begin{document}

	\maketitle
	\renewcommand\theequation{\arabic{equation}}
	\renewcommand{\figurename}{Fig.}
	\renewcommand\thesection{\Roman{section}}
	\renewcommand\thesubsection{(\alph{subsection})}
	%\onehalfspacing

\section{Title \& Team Member Names}
\textbf{Title:} States Estimation of Li-ion Batteries with Electro-Thermal-Aging Dynamics\\
\textbf{Team Member:} Xin Peng, Junzhe Shi, Franklin Zhao, and Ruitong Zhu
\section{Abstract}
Batteries are ubiquitous in all forms of electronics and transportation, and also are a key to the store of clean and secure energy. In different kinds of batteries,  Li-ion battery is the most prominent one due to their superior gravimetric and volumetric energy density.  For the safe operation of Li-ion battery, the state of charge (SOC) and state of health (SOH) estimation is of great significance. Hence, the goal of the project is to design a robust observer which can estimate the SOC and SOH of Li-ion batteries. In the project, the equivalent-circuit model will be used for the battery modeling with current and ambient temperature as inputs and voltage as the measured output. The equivalent-circuit model will include three parts which are an electrical model, a thermal model, and an aging model. To ensure the accuracy of states estimation, both of Luenberger observer and Kalman filter will be used and examined in the project. The battery system will be built and simulated by MATLAB and/or Python. The robustness of designed observer will be tested by real Li-ion battery testing data.
\section{Introduction}
\subsection{Motivation \& Background}
The identification of battery operation and aging in real life has been a long-desired yet challenging goal, which includes multiple complex processes in complicated operating conditions and environments. An accurate method to observe SOC and SOH of Li-ion battery is in need. Meanwhile, batteries invariably work at varying thermal and aging conditions. Thus, it’s necessary for us to build a battery observation system to monitor operation and aging of battery. The potential challenges also exist. We need to express a multi-control problem via mathematical equations and combine electrical model, thermal model and aging model. Besides, since all team members are major in Civil System, a lack of background knowledge in Electrical Engineering can be a big challenge. However, our previous course CE 291F, Control and Optimization of Distributed Parameters Systems can be helpful for the project. It gave us a background knowledge of partial differential equations, conservation laws, linear stability, Kaman filter and so on. We all have experiences of building, controlling and optimizing systems, including quench process,  heat diffusion and Lighthill Whitham Richards model.
\subsection{Focus of this study}
In this project, we will focus on the SOC and SOH of LI-ion batteries. Based on equivalent-circuit, the electrical, thermal and aging models will be developed for the observing system. Since battery monitoring and management can be the key to allowing innovation in future designs because of their limit properties, our system may play an important role in such an area, and significantly contribute to the energy saving and efficiency.
\newpage
\section{Statement of Work}
The statement of work is shown in Table 1.
\begin{center}
Table 1: Statement of Work
\end{center}
\vspace{-23pt}
\begin{figure}[H]
	\centering
	\includegraphics[width=\linewidth]{tmp.jpg}
\end{figure}
\newpage
\section{Summary}
This project will basically develop an obeserving system with high efficiency and robustness. Eletrical, thermal, and aging models will be built based on the equivalent-circuit model. The accuracy will be tested using Luenberger observer and Kalman filter.
\section*{Relevant Literature}
\begin{itemize}[noitemsep, topsep=0pt]
	\item[{[1]}] Perez, Hector, et al. ``Optimal Charging of Li-Ion Batteries with Coupled Electro-Thermal-Aging Dynamics." \textit{IEEE Transactions on Vehicular Technology}, vol. 66, no. 9, pp. 99, 2017.
	\item[{[2]}] G. L. Plett, ``Extended Kalman filtering for battery management systems of LiPB-based HEV battery packs: Part 1. Background," \textit{Journal of Power Sources}, vol. 134, no. 2, pp. 252 – 61, 2004.
	\item[{[3]}] G. L. Plett, ``Extended Kalman filtering for battery management systems of LiPB-based HEV battery packs: Part 2. Modeling and identification," \textit{Journal of Power Sources}, vol. 134, no. 2, pp. 262 – 76, 2004.
	\item[{[4]}] G. L. Plett, ``Extended Kalman filtering for battery management systems of LiPB-based HEV battery packs: Part 3. State and parameter estimation," \textit{Journal of Power Sources}, vol. 134, no. 2, pp. 262 – 76, 2004.
	\item[{[5]}] Lin, Xinfan, et al. ``A lumped-parameter electro-thermal model for cylindrical batteries." \textit{Journal of Power Sources}, vol. 257, no. 0, pp. 1 – 11, 2014.
\end{itemize}
\end{document}


\subsubsection{\texorpdfstring{The 3\textsuperscript{rd} Law of Thermodynamics}{The 3rd Law of Thermodynamics}}
The third law of thermodynamics is that fix. It states that
\begin{center}
    \textbf{As the temperature of a system tends towards absolute zero, the entropy of the system tends towards a finite value.}
\end{center}
Great! That means that using zero as our reference point, we can calculate the entropy of the system at any other state.

But here's the thing (thing might be the 956\textsuperscript{th} time I've said this). We've figured our \textit{how} entropy behaves, and can use it to predict the future behaviour of the system. But we seem no closer to figuring out \textit{what} entropy is or \textit{why} it behaves the way it does. Luckily, someone else has already figured that out quite a while ago!


%========================================================================
%Beginning of Chapter 2
%========================================================================

\section{THE SOFTWARE COMPONENTS}\label{ch:overview}

\subsection{Introduction}\label{sec:chp2intro}

There are many issues to be addressed when using multiple libraries together.  The scope of the different components presented is quite vast and their dependencies and usage vary extensively.  Understanding the importance and the work involved in tying these together requires a thorough overview of each piece of software.  Some theory will be covered as well to explain what the libraries do or why they're necessary.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Finite Difference Vs. Finite Element}\label{sec:chp2grid}

Currently many glacial models, including the one used, that run large scale simulations use finite difference methods in order to solve the partial differential equations involved in the numerical approximations.  Finite difference methods are used primarily due to the ease of implementation with fluid dynamics, especially over large areas, and the computations are also less intensive than with finite element methods.

Finite element analysis provides a much more efficient way of calculating the solution with an area that is not of a fixed sized.  The difference can be summed up by a quote from Gershenfeld about finite elements: ``Instead of discretizing the space in which the problem is posed, this (finite element analysis) discretizes the form of the function used to represent the solution." \citep{Gershenfeld:1999}

As discussed later in chapter \ref{ch:verification} using finite difference methods, both for data and for the calculations, can introduce artifacts and erroneous results if not careful since the domain in ice-sheet modeling can change drastically, but the points at which the approximations are being made do not.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{GLIMMER-CISM}\label{sec:chp2cism}

GLIMMER-CISM is a three-dimensional thermo-mechanical ice-sheet model that is open source and is developed to better understand ice dynamics within glaciers and sea-rise consequences.  GLIMMER (GENIE Land Ice Model with Multiply-Enabled Regions) was originally developed as part of the GENIE (Grid-ENabled Integrated Earth system model) project in order to be the glacial modeling component of the larger model.\citep{glimmerdoc}

Beginning in 2002 GLIMMER was used as the basis for advancing current research of ice-sheet dynamics.  The current model, GLIMMER-CISM (Community Ice Sheet Model) has incorporated many new elements beyond the standard SIA (Shallow Ice Approximation) that the original model used.
\citep{cismwiki:website}

GLIMMER-CISM now has a higher-order model for mass-balance based on recent ideas by Pattyn \citep{Pattyn:2003}, some verification tools and test suites, more standardization, intermodel comparisons, and a lot of developers building an infrastructure to share data within the community.

GLIMMER-CISM is written primarily in Fortran and uses NetCDF (Network Common Data Form) files as the input and output to the model as well as configuration files for options, model size, simulation lengths, and many other parameters that can be set.  This makes the model very capable and adaptable for both small and large scale simulations.

%GLIMMER-CISM is based on a staggered grid.  blah

%should i talk about the sia or first order model mathematics?????????
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{PHAML}\label{sec:ch2phaml}

PHAML stands for ``Parallel Hierarchical Adaptive MultiLevel method", and it uses several hp-adaptive methods using triangle meshes to solve elliptical partial differential equations.  PHAML incorporates a lot more than just the solving methods though.  The software contains parallel libraries to run parts of the simulation over multiple processors, it has OpenGL bindings allowing the user to receive 3D representations of the solutions, and it is very extendible allowing other solvers to be used.

PHAML is designed to solve linear elliptical partial differential equations of the form:

\begin{equation}
    - \frac{\partial}{\partial x} \left (c_{xx}\frac{\partial u}{\partial x} \right ) - \frac{\partial}{\partial x} \left (c_{xy}\frac{\partial u}{\partial y} \right ) - \frac{\partial}{\partial y} \left (c_{yy}\frac{\partial u}{\partial y} \right ) + c_x \frac{\partial u}{\partial x} + c_y \frac{\partial u}{\partial y} + c_{u}u = f \; in \; \Omega
\label{eq:phamlmain}
\end{equation}

where $c_{xx},c_{yy},c_x,c_y$ and $f$ are functions of $x$ and $y$, and the domain $\Omega$ is a bounded, connected, region in $R^2$.\citep{phamldoc}  The boundary conditions can be Dirchlet, natural, or mixed.  Dirichlet boundary conditions are of the form:

\begin{equation}
u=g \; on \; \partial \Omega_D
\label{eq:dirbound}
\end{equation}

otherwise the boundary is defined by:
\begin{equation}
    \left ( c_{xx} \frac{\partial u}{\partial x} + c_{xy}\frac{\partial u}{\partial y} \right ) \frac{\partial y}{\partial s} - c_{yy} \frac{\partial u}{\partial y} \frac{\partial x}{\partial s} + c_{bc}u = g \; on \; \partial \Omega_N
\label{eq:phamlbound}
\end{equation}

where $g$ and $c_{bc}$ are also functions of $x$ and $y$ and everything else is as defined for the equation \eqref{eq:phamlmain}.  Here $s$ is some parameter going through some finite range to define the boundary as a function $(x(s),y(s))$.  These equations are explained thoroughly in the PHAML documentation as well as all of the different consequences of a chosen boundary condition. \citep{phamldoc}

%I should talk about lin. elliptical pdes in general.

PHAML works by allowing a custom PSLG (Planar Straight Line Graph) or mesh to be passed to the main program, and then it retrieves any information it needs about the solution (or the problem) by means of subroutine callbacks. These are listed in the appendix \ref{sec:libphamlcall}.  These callbacks allow you to specify any of the coefficients as well as functions of the elliptical PDE.  This makes the solver very flexible since different types of solutions can be found merely be changing one of the callback.  For instance, solving Poisson would have the source subroutine returning the functional value at a given point, but by changing the callback to return zero for all points changes the solution to the Laplacian.

The callbacks also allow for several interesting PDE characteristics to be achieved if desired such as non-homogeneous coefficients, using true solutions, derivative and second derivative based functions, etc.

The mesh geometry can also be generated once the program starts if a functional boundary exists.  There are callbacks that allow the program to define what the boundary is while PHAML is executing.  This is very beneficial when solving for solutions based on a dataset or a function.

One of the most beneficial aspects of PHAML are that it uses hp-adaptive finite element analysis methods.  This allows it to solve PDEs by using piece-wise polynomial approximations that employ elements of variable size (h) and polynomial degree (p). As demonstrated by W. Mitchell this allows hp-FEM methods to not only be more accurate than standard FEM, but that they can also achieve ``a convergence rate that is exponential in the number of degrees of freedom." \citep{mitchell:hp}

Having this amount of flexibility also means that PHAML has a lot of functionality that can be tweaked.  There are many options for nearly every facet of the solving process.  This can be very useful for solutions where a particular type of result is desired.  The options themselves will not be covered since they are listed and described in detail within the PHAML documentation.\citep{phamldoc}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Triangle}\label{sec:chp2triangle}

Triangle is summed up as ``a two-dimensional quality mesh generator and Delaunay triangulator".\citep{shewchuk96b}  The software is able to read in files describing a two-dimensional graph and build the data structure while adding useful functionality.  The software is also capable of dynamically refining the mesh, adding to the mesh, and providing instant feedback.  Triangle can generate ``exact Delaunay triangulations, constrained Delaunay triangulations, conforming Delaunay triangulations, Voronoi diagrams, and high-quality triangular meshes". \citep{Triangle:website} Most of the algorithms that Triangle depends upon are recent advanced triangulation methods as well as sorting and location algorithms.  Some algorithms stemming from this research, such as the robust geometric predicates, are also now used in many other areas of study. \citep{shewchuk97a}

Triangle is not used directly by the interface, but is used as the mesh component of PHAML.  The GLIMMER-CISM code uses the Triangle program simply to generate the mesh files needed by PHAML.  Since it is needed but not directly used, Triangle is not discussed as thoroughly.

\subsubsection{Showme}

Triangle also comes with a small mesh viewer called `showme' which is very useful for looking at the mesh files directly.  This program opens the .poly files and allows easy access to the properties of the mesh.  This is useful in testing the different generation algorithms by being able to view the output file.  The only drawback of the application is that it doesn't show the bmarks associated with each node.

%========================================================================
%End of Chapter 2
%========================================================================


\section{Conclusions}
A framework for up-scaling DEM simulations is presented in this article. Up-scaling is achieved by matching homogenized stress-strain curves from REV-scale DEM simulations to single element continuum models using PSO and LMA optimization algorithms. A Drucker-Prager plasticity model with ductile damage is implemented in the CDM model to empirically capture the effect of the degradation (damage) of the NFR as deformation takes place.

The Drucker-Prager model with ductile damage is shown to be a reasonable CDM model approach to represent NFR in a continuum context including effects of pressure dependent yield and the triaxiality based damage initiation criterion. Compared to a full DEM simulation, the CDM model shows a good fit pre-damage, but is unable to emulate the subtle post-yield oscillations arising from non-continuous yielding in the NFR.

Most importantly, with this up-scaling framework, very comparable results ($<5\%$ error) to full DEM solutions can be obtained with the CDM method but with two to three orders of magnitude less computational time.

The implementation of this up-scaling framework is presented in an illustrative context only. This specific formulation is formulated only for small strains, it is a purely mechanical formulation (no thermo-hydro-mechanical coupling), and only 2D is considered. However, the proposed framework can accommodate the large strain case, the hydro-mechanically coupled case, and the 3-D case by using appropriately designed modules. We suspect that in these more complex cases, the up-scaling from DEM to CDM will yield even greater increases in computational efficiency.

\clearpage


\documentclass[letterpaper,12pt]{article}

\usepackage{threeparttable}
\usepackage{geometry}
\geometry{letterpaper,tmargin=1in,bmargin=1in,lmargin=1.25in,rmargin=1.25in}
\usepackage[format=hang,font=normalsize,labelfont=bf]{caption}
\usepackage{amsmath}
\usepackage{multirow}
\usepackage{array}
\usepackage{delarray}
\usepackage{amssymb}
\usepackage{amsthm}
\usepackage{lscape}
\usepackage{natbib}
\usepackage{setspace}
\usepackage{float,color}
\usepackage[pdftex]{graphicx}
\usepackage{pdfsync}
\usepackage{verbatim}
\usepackage{placeins}
\usepackage{geometry}
\usepackage{pdflscape}
\synctex=1
\usepackage{hyperref}
\hypersetup{colorlinks,linkcolor=red,urlcolor=blue,citecolor=red}
\usepackage{bm}

\theoremstyle{definition}
\newtheorem{theorem}{Theorem}
\newtheorem{acknowledgement}[theorem]{Acknowledgement}
\newtheorem{algorithm}[theorem]{Algorithm}
\newtheorem{axiom}[theorem]{Axiom}
\newtheorem{case}[theorem]{Case}
\newtheorem{claim}[theorem]{Claim}
\newtheorem{conclusion}[theorem]{Conclusion}
\newtheorem{condition}[theorem]{Condition}
\newtheorem{conjecture}[theorem]{Conjecture}
\newtheorem{corollary}[theorem]{Corollary}
\newtheorem{criterion}[theorem]{Criterion}
\newtheorem{definition}{Definition} % Number definitions on their own
\newtheorem{derivation}{Derivation} % Number derivations on their own
\newtheorem{example}[theorem]{Example}
\newtheorem{exercise}[theorem]{Exercise}
\newtheorem{lemma}[theorem]{Lemma}
\newtheorem{notation}[theorem]{Notation}
\newtheorem{problem}[theorem]{Problem}
\newtheorem{proposition}{Proposition} % Number propositions on their own
\newtheorem{remark}[theorem]{Remark}
\newtheorem{solution}[theorem]{Solution}
\newtheorem{summary}[theorem]{Summary}
\bibliographystyle{aer}
\newcommand\ve{\varepsilon}
\renewcommand\theenumi{\roman{enumi}}
\newcommand\norm[1]{\left\lVert#1\right\rVert}

\begin{document}

This document outlines how we can us the first order conditions of the household to estimate the utility weights on the disutility of work and the warm glow bequest.

\section{Estimating the utility weight on the disutility of work, $\chi^{n}_{s}$}.

The household first order condition for the choice of hours worked yields:

        \begin{equation}\label{EqEulerLabGen}
      \begin{split}
        &(c_{j,s,t})^{-\sigma}\Biggl(w_t e_{j,s} - \frac{\partial T_{j,s,t}}{\partial n_{j,s,t}}\Biggr) = e^{g_y t(1-\sigma)}\chi^n_{s}\biggl(\frac{b}{\tilde{l}}\biggr)\biggl(\frac{n_{j,s,t}}{\tilde{l}}\biggr)^{v-1}\Biggl[1 - \biggl(\frac{n_{j,s,t}}{\tilde{l}}\biggr)\Biggr]^{\frac{1-v}{v}} \\
        &\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\forall j,t, \quad\text{and}\quad E+1\leq s\leq E+S \\
        &\qquad\text{where}\quad c_{j,s,t} = \left(1 + r_t\right) b_{j,s,t} + w_t e_{j,s}n_{j,s,t} + \frac{BQ_{j,t}}{\lambda_j\tilde{N}_t} - b_{j,s+1,t+1} - T_{j,s,t} \\
        &\qquad\text{and}\quad \frac{\partial T_{j,s,t}}{\partial n_{j,s,t}} = w_t e_{j,s}\biggl[\tau^I\bigl(F\hat{a}_{j,s,t}\bigr) + \frac{F\hat{a}_{j,s,t}CD\bigl[2A(F\hat{a}_{j,s,t})+B\bigr]}{\bigl[A(F\hat{a}_{j,s,t})^2+B(F \hat{a}_{j,s,t})+C\bigr]^2} + \tau^P\Biggr]
      \end{split}
    \end{equation}

    To simplify notation a bit, let $w_{t}e_{j,s}=\tilde{w}_{j,s,t}$, which is defined as the hourly earnings of household of ability type $j$, age $s$, at time $t$.  Further, we can write derivative of the tax function, $ \frac{\partial T_{j,s,t}}{\partial n_{j,s,t}}$ as $\tau^{l}(y_{j,s,t})\tilde{w}_{j,s,t}$, where $\tau^{l}(y_{j,s,t})$ is the marginal tax rate on labor income for an individual with taxable income $y_{j,s,t}$.  Now we can write the FOC as:

            \begin{equation}\label{EqEulerLabGen}
      \begin{split}
        &(c_{j,s,t})^{-\sigma}\Biggl(\tilde{w}_{j,s,t}(1-\tau^{l}(y_{j,s,t})\Biggr) = e^{g_y t(1-\sigma)}\chi^n_{s}\biggl(\frac{b}{\tilde{l}}\biggr)\biggl(\frac{n_{j,s,t}}{\tilde{l}}\biggr)^{v-1}\Biggl[1 - \biggl(\frac{n_{j,s,t}}{\tilde{l}}\biggr)\Biggr]^{\frac{1-v}{v}}
        \end{split}
        \end{equation}

        This problem is deterministic, but we can assume that their is some noise in the data, thus the data analog to the model FOC is:

  \begin{equation}\label{EqEulerLabGen}
      \begin{split}
        &(c_{j,s,t})^{-\sigma}\Biggl(\tilde{w}_{j,s,t}(1-\tau^{l}(y_{j,s,t})\Biggr) - e^{g_y t(1-\sigma)}\chi^n_{s}\biggl(\frac{b}{\tilde{l}}\biggr)\biggl(\frac{n_{j,s,t}}{\tilde{l}}\biggr)^{v-1}\Biggl[1 - \biggl(\frac{n_{j,s,t}}{\tilde{l}}\biggr)\Biggr]^{\frac{1-v}{v}} = \varepsilon_{j,s,t}
        \end{split}
        \end{equation}

And the moment condition for a GMM estimator for each $\chi^{n}_{s}$ would be:

  \begin{equation}\label{EqEulerLabGen}
      \begin{split}
        &\sum_{J}\sum_{T}\left[(c_{j,s,t})^{-\sigma}\Biggl(\tilde{w}_{j,s,t}(1-\tau^{l}(y_{j,s,t})\Biggr) - e^{g_y t(1-\sigma)}\chi^n_{s}\biggl(\frac{b}{\tilde{l}}\biggr)\biggl(\frac{n_{j,s,t}}{\tilde{l}}\biggr)^{v-1}\Biggl[1 - \biggl(\frac{n_{j,s,t}}{\tilde{l}}\biggr)\Biggr]^{\frac{1-v}{v}}\right] =\\
        &  \quad  \quad  \quad  \quad  \quad  \quad \sum_{J}\sum_{T}\varepsilon_{j,s,t}  = 0
        \end{split}
        \end{equation}

        Note that the above equation for each $s$ - and we can have more moment conditions if we wish to have an over-identified model.  We may also think about estimating the parameters of the ellipse via this method.

        To estimate, we need data on consumption, $c$, and labor supply, $n$, by lifetime income group, age, and year.  We can get this from the PSID - see \\
        \href{http://www.federalreserve.gov/pubs/feds/2007/200716/200716pap.pdf}{http://www.federalreserve.gov/pubs/feds/2007/200716/200716pap.pdf} for a document outlining the measurement of consumption from the PSID.  We can find $\tau^{l}(y_{j,s,t})$ by running the PSID observation through a tax calculator (e.g. the OSPC calculator).  The remaining parameters are calibrated elsewhere.

\section{Estimating the utility weight on the warm glow bequest motive, $\chi^{b}_{j}$}.

The household first order condition for the choice of savings yields:

    \begin{equation}\label{EqEulerSavGen}
      \begin{split}
        &(c_{j,s,t})^{-\sigma} = \rho_s\chi^b_j\bigl(b_{j,s+1,t+1}\bigr)^{-\sigma} + \beta(1-\rho_s)(c_{j,s+1,t+1})^{-\sigma}\Biggl[(1 + r_{t+1}) - \frac{\partial T_{j,s+1,t+1}}{\partial b_{j,s+1,t+1}}\Biggr] \\
        &\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\forall j,t,\quad\text{and}\quad E+1\leq s \leq E+S-1 \\
        &\qquad\text{where}\quad \frac{\partial T_{j,s+1,t+1}}{\partial b_{j,s+1,t+1}} = ...\\
        &\qquad\qquad r_{t+1}\Biggl(\tau^I(F\hat{a}_{j,s+1,t+1}) + \frac{F\hat{a}_{j,s+1,t+1}CD\left[2A(F\hat{a}_{j,s+1,t+1}) + B\right]}{\left[A(F\hat{a}_{j,s+1,t+1})^2 + B(F\hat{a}_{j,s+1,t+1}) + C\right]^2}\Biggr) ... \\
        &\qquad\qquad \tau^W(\hat{b}_{j,s+1,t+1}) + \frac{\hat{b}_{j,s+1,t+1}PHM}{\left(H\hat{b}_{j,s+1,t+1} + M\right)^2}
      \end{split}
    \end{equation}

    We can write derivative of the tax function, $ \frac{\partial T_{j,s,t}}{\partial b_{j,s,t}}$ as $\tau^{b}(y_{j,s,t})r_{t+1}$, where $\tau^{b}(y_{j,s,t})$ is the marginal tax rate on capital income for an individual with taxable income $y_{j,s,t}$.  Now we can write the FOC as:

            \begin{equation}\label{EqEulerLabGen}
        (c_{j,s,t})^{-\sigma} = \rho_s\chi^b_j\bigl(b_{j,s+1,t+1}\bigr)^{-\sigma} + \beta(1-\rho_s)(c_{j,s+1,t+1})^{-\sigma}\Biggl[(1 + (1-\tau^{b}_{j,s+1,t+1})r_{t+1}) \Biggr]
        \end{equation}

        This problem is deterministic, but we can assume that their is some noise in the data, thus the data analog to the model FOC is:

  \begin{equation}\label{EqEulerLabGen}
      \begin{split}
         (c_{j,s,t})^{-\sigma} - \rho_s\chi^b_j\bigl(b_{j,s+1,t+1}\bigr)^{-\sigma} + \beta(1-\rho_s)(c_{j,s+1,t+1})^{-\sigma}\Biggl[(1 + (1-\tau^{b}_{j,s+1,t+1})r_{t+1}) \Biggr] = \varepsilon_{j,s,t}
        \end{split}
        \end{equation}

And the moment condition for a GMM estimator for each $\chi^{b}_{j}$ would be:

  \begin{equation}\label{EqEulerLabGen}
      \begin{split}
        &\sum_{S}\sum_{T}\left[( (c_{j,s,t})^{-\sigma} - \rho_s\chi^b_j\bigl(b_{j,s+1,t+1}\bigr)^{-\sigma} + \beta(1-\rho_s)(c_{j,s+1,t+1})^{-\sigma}\Biggl[(1 + (1-\tau^{b}_{j,s+1,t+1}r_{t+1}) \Biggr]\right] = \\
        &    \quad\quad\quad\quad \quad \quad \sum_{S}\sum_{T}\varepsilon_{j,s,t}  = 0
        \end{split}
        \end{equation}

        Note that the above equation for each $j$ - and we can have more moment conditions if we wish to have an over-identified model.

        To estimate, we need data on consumption, $c$, and wealth, $b$, by lifetime income group, age, and year.  We can get consumption from the PSID, as noted above.  We can also get wealth from the PSID, at least for the years 1984-2005 - see \href{http://www.brookings.edu/~/media/research/files/papers/2009/2/saving-wealth-bosworth/02\_saving\_wealth\_bosworth.pdf}{http://www.brookings.edu/~/media/research/files/papers/2009/2/saving-wealth-bosworth/02\_saving\_wealth\_bosworth.pdf} for a document outlining the measurement of wealth from the PSID.  We can find $\tau^{b}(y_{j,s,t})$ by running the PSID observation through a tax calculator (e.g. the OSPC calculator).  The remaining parameters are calibrated elsewhere.

\end{document}


\section{Kinetic model algorithm.}

 The kinetic algorithm can be considered as a step by step
updating of a particle vector:
\begin{enumerate}
\item Create a vector of particles: assign initial
particle types, their coordinates and momenta etc. Assign initial value
for time evolution parameter;
\item  For choosen time evolution parameter step find pairs of particles
(according to a collision criterion), which are assumed to collide and
particles (according to their life times), which are assumed to decay;
\item  Perform particle collisions and particle decays. Collisions and
decays convert incoming particles  into outgoing particles. During this
step one should update also particle coordinates and momenta (particle
propagation);
\item Starting from (2) perform the next step.
\end{enumerate}

At any evolution parameter step one needs a possibility to interupt
"updating" process.
Thus at
 each evolution time step  for the system consisting
from $n$ particles we are looking for the particles, which will decay
according to their lifetimes and the pairs $(i,j)$, where $i\neq j$ and
$i,j = 1,2,...,n$, of particles, which will collide according to the
choosen collision criterion. The collision pairs are ordered
chronologically using their collision times.  This algorithm is very
simple and general enough but it is CPU time consuming if $n$ is large,
e. g. during
nucleus-nucleus collision at high energy, because at each time step we
need to perform $n(n-1)/2 \sim n^2$ computations.

If we neglect by field interaction and keep only particle collisions and
decays (the cascade option), when
particles move along straight trajectories, after each collision we
only have to look for the collisions between new produced particles and
the existing particles. We also do not need to use fixed time step. We
need to "shift" system on time between events of collisions or decays.
 Then the number of computations at given time
will be $n_{new}n$, where $n_{new}$ is the number of produced particles
during the former time step. It should be noted that in this case we
have to maintain
 the list of
potential particle collision or decay events.
Using "cascade" algorithm describing evolution of system we have the criterion
to stop calculation process: the list of potential particle collision or
decay events is empty.


\section{Introduction}
\label{sec:intro}

%We observe that the \UTXO\ ledger rules do not fundamentally depend on the fact that an output locks only a single integral value. Instead, all they require is that locked values follow the algebraic structure of a monoid. We exploit that insight by generalising the notion of locked values to cryptocurrency \emph{bundles.} Furthermore, we extend transactions by a \emph{forge} field, where user-defined tokens can be forged (or minted) and destroyed. That process is controlled by smart contract scripts called \emph{monetary policies.}

Distributed ledgers began by tracking just a single asset --- money.
The goal was to compete with existing currencies, and so they naturally started by focusing on their own currencies --- Bitcoin and its eponymous currency, Ethereum and Ether, and so on.
This focus was so clear that the systems tended to be identified with their primary currency.

More recently, it has become clear that it is possible and very useful to track other kinds of asset on distributed ledger systems.
Ethereum has led the innovation in this space, with ERC-20~\cite{erc20} implementing new currencies and ERC-721~\cite{erc721} implementing unique non-fungible tokens.

These have been wildly popular --- variants of ERC-20 are the most used smart contracts on Ethereum by some margin.
However, they have major shortcomings.
Notably, custom tokens on Ethereum are not native. This means that tokens do not live in a user's account, and in order to send another user ERC-20 tokens, the sender must interact with the governing smart contract for the currency.
That is, despite the fact that Ethereum's main purpose is to track ownership of assets and perform transactions, users have been forced to build their own \emph{internal ledger} inside a smart contract.

Other systems have learned from this and have made custom tokens native, such as Stellar, Waves,
Zilliqa, and more.
However, these typically rely on some kind of global state, such as a global currency registry, or special global accounts that must be created.
This is slow, and restricts creative use of custom tokens because of the high overhead in terms of time and money.
There have also been efforts to introduce native multi-assets into UTXO ledgers~\cite{mcledgers}, a precursor to our work.

We can do better than this through a combination of two ideas.
Firstly, we generalise the value type that the ledger works with to include \emph{token bundles} that freely and uniformly mix tokens from different custom assets, both fungible and non-fungible.
Secondly, we avoid any global state by ``eternally'' linking a currency to a governing forging policy via a hash.
Between them this creates a multi-asset ledger system (which we call \UTXOma) with native, lightweight custom tokens.

Specifically, this paper makes the following contributions:
%
\begin{itemize}
\item We introduce token bundles, represented as finitely-supported functions, as a uniform mechanism to generalise the existing \UTXO\ accounting rules to custom assets including fungible, non-fungible, and mixed tokens.
\item We avoid the need for global state in the form of a currency registry by linking custom forging policy scripts by way of their script hash to the name of asset groups.
\item We support a wide range of standard applications for custom assets without the need for general-purpose smart contracts by defining a simple domain-specific language for forging policy scripts.
\item We provide a formal definition of the \UTXOma\ ledger rules as a basis to formally reason about the resulting system, along with a mechanised version in Agda.\footnote{\url{\agdaRepo}}

\end{itemize}
%
Creating and transferring new assets in the resulting system is lightweight and cheap. It is lightweight as we avoid special setup transactions or registration procedures, and it is cheap as only standard transaction fees are required --- this is unlike the Ethereum gas model, where a script must
be run each time a custom asset is transferred, which incurs gas costs.

The proposed multi-asset system is not merely a pen and paper exercise. It forms the basis of the multi-asset support for the Bcc blockchain.
In a related work~\cite{eutxo-ma}, we further modify the native multi-asset ledger
presented in this paper to an extended UTxO ledger model, which additionally supports
the use of Zerepoch (Turing complete smart contract language) to define forging policies.
This ledger model extension allows the use of stateful smart contracts to define
state machines for output locking.


\chapter{3D source reconstruction: Imaging approach}
\label{ch:eeg_imaging}

Here is a brief help to the 3D reconstruction based on the Imaging approach. In the near future, this will be improved by including more theoretical details upon the different procedures as well as a practical tutorial that will guide the user through the SPM interface via the analysis of a sample dataset.

\section{Introduction}
\label{sec:imaginv_intro}
This chapter focuses on the imaging (or distributed) method for doing EEG/MEG source reconstruction in SPM.
Such an approach to spatial projection onto (3D) brain space consists in considering a large amount of dipolar sources all over the cortical sheet, with fixed locations and orientations. This renders the observation model linear, the unknown variables being the source amplitudes or power.\\
Given epoched and preprocessed data (see chapter ...), the evoked and/or induced activity for each dipolar source can be estimated, for a single time-sample or a wider peristimulus time window.\\
The obtained reconstructed activity is in 3D voxel space and enables mass-univariate analysis in SPM (see chapter...).

Contrary to PET/fMRI data reconstruction, EEG/MEG source reconstruction is a non trivial operation. Often compared to estimating a body shape from its shadow, inferring brain activity from scalp data is mathematically ill-posed and requires prior information such as anatomical, functional or mathematical constraints to isolate a unique and most probable solution~\cite{Baillet01}.

Distributed linear models have been around for more than a decade now~\cite{Dale93} and the proposed pipeline in SPM for 'Imaging' solution is classical and very similar to common approaches in the field. However, at least two aspects are quite original and should be emphasized here:
\begin{itemize}
\item Based on an empirical Bayesian formalism, the inversion is meant to be generic in the sense it can incorporate and estimate the relevance of multiple constraints of various nature; data-driven relevance estimation being made possible through Bayesian model comparison~\cite{peb1,Phillips05,Mattout06,karl_induced}.
\item The subject's specific anatomy is incorporated in the generative model of the data, in a fashion that eschews individual cortical surface extraction. The individual cortical mesh is obtained automatically from a canonical mesh in MNI space, providing a simple and efficient way of reporting results in stereotactic coordinates.
\end{itemize}

The EEG/MEG imaging pipeline is divided into four consecutive steps which characterize any inverse procedure. In this chapter, we go through each of those steps that all need to be completed when proceeding with a full inverse analysis:
\begin{enumerate}
	\item Source space modeling,
	\item Data co-registration,
	\item Forward computation,
	\item Inverse reconstruction.
\end{enumerate}

Whereas the three first steps are part of the whole generative model, the last step consists in the Bayesian inversion and is the only one involving the actual EEG/MEG data.\\

Everything which is described hereafter is a new feature in SPM and is accessible from SPM5 user-interface by choosing the 'EEG/MEG' application, '3D source reconstruction' and 'Imaging'.

\section{Data structure}
\label{sec:datastruct}
The Matlab structure describing a given EEG/MEG dataset in SPM is denoted as \textit{D}. Within that structure, each new inverse analysis will be described by a new cell of sub-structure field \textit{D.inv} and will be made of the following fields:

\begin{itemize}
	\item \textit{method}: character string indicating the method, either 'ECD' or 'Imaging' in present case;
	\item \textit{mesh}: sub-structure with relevant variables and filenames for source space and head modeling;
	\item \textit{datareg}: sub-structure with relevant variables and filenames for EEG/MEG data registration into MRI space;
	\item \textit{forward}: sub-structure with relevant variables and filenames for forward computation;
	\item \textit{inverse}: sub-structure with relevant variable, filenames as well as results files;
	\item \textit{comment}: character string provided by the user to characterize the present analysis;
	\item \textit{date}: date of the last modification made to this analysis.
\end{itemize}

\section{Source space modeling (\textit{mesh})}
The individual cortical mesh is obtained from a template mesh. Four Mesh sizes are available (3004, 4004, 5004 and 7204 vertices). If not yet obtained, the spatial normalization of the subject's T1 MRI into MNI space is performed (see \textit{spm\_preproc.m} based on tissue probability maps). The inverse of that transformation is computed and applied to the template mesh to furnish the individual cortical mesh.\\

Individual meshes for the inner-skull and scalp surfaces are also computed from the individual T1 MRI. They are obtained by performing a binary mask of the the volumes delimited by the inner-skull and scalp surface respectively. Then, using an initial spherical mesh, a realistic-shaped mesh is obtained for each of the two tissues and further regularized via an erosion and growing procedure.

The meshing module includes the following functions:
\begin{itemize}
	\item \textit{spm\_eeg\_inv\_mesh\_ui.m}: run the user interface for this module,
	\item \textit{spm\_eeg\_inv\_spatnorm.m}: normalize the T1 image if needed,
	\item \textit{spm\_eeg\_inv\_meshing.m}: main function to produce Cortex, Inner-skull and Scalp meshes,
	\item \textit{spm\_eeg\_inv\_getmasks.m}: produce masks of Inner-skull and Scalp,
	\item \textit{spm\_eeg\_inv\_ErodeGrow.m}: erosion and growing procedure,
	\item \textit{spm\_eeg\_inv\_getmeshes.m}: obtains the inner-skull and scalp meshes from correpsonding binary masks,
	\item \textit{spm\_eeg\_inv\_CtrBin.m}
	\item \textit{spm\_eeg\_inv\_TesBin.m}
	\item \textit{spm\_eeg\_inv\_ElastM.m}
	\item \textit{spm\_eeg\_inv\_checkmeshes.m}: displays the computed three meshes in the SPM main figure
\end{itemize}

\section{Data Registration (\textit{datareg})}
\label{sec:datareg}
There are two possible ways of coregistrating the EEG/MEG data into the structural MRI space.

\begin{enumerate}
	\item A Landmark based coregistration (using fiducials only).\\
	The rigid transformation matrices (Rotation and Translation) are computed such that they match each fiducial in the EEG/MEG space into the corresponding one in sMRI space. The same 					transformation is then applied to the sensor positions.
	\item Surface matching (between some headshape in MEG/EEG space and some sMRI derived scalp tesselation).
For EEG, the sensor locations can be used instead of the headshape. For MEG, the headshape is first coregistrated into sMRI space; the same transformation is then applied to the sensors.\\
Surface matching is performed using an Iterative Closest Point algorithm (ICP). The ICP algorithm~\cite{Besl_McKay} is an iterative alignment algorithm that works in three phases:
\begin{itemize}
	\item Establish correspondence between pairs of features in the two structures that are to be aligned based on proximity;
	\item Estimate the rigid transformation that best maps the first member of the pair onto the second;
	\item Apply that transformation to all features in the first structure. These three steps are then reapplied until convergence is concluded.
Although simple, the algorithm works quite effectively when given a good initial estimate.
\end{itemize}
\end{enumerate}

The data-registration module includes the following functions:
\begin{itemize}
	\item \textit{spm\_eeg\_inv\_datareg\_ui.m}: run the user interface for this module,
	\item \textit{spm\_eeg\_inv\_datareg.m}:	main co-registration function,
	\item \textit{spm\_eeg\_inv\_checkdatareg.m}: display meshes, sensor locations and fiducials in native MRI space to enable one checking the co-registration by eye.
\end{itemize}

\section{Forward computation (\textit{forward})}
Several methods are proposed, depending on the modality (EEG or MEG). All these approaches/functions are identical to the one initialy developed and provided by the BrainSTorm package (Matlab open-source and free software: http://neuroimage.usc.edu/brainstorm/).

For EEG~\cite{Ermer2001}:
\begin{enumerate}
	\item single sphere (scalp surface),
	\item three spheres (inner, outer skull and scalp surfaces),
	\item three spheres (+ Berg correction),
	\item overlapping spheres (one fitted sphere per sensor).
\end{enumerate}

For MEG~\cite{Huang1999}:
\begin{enumerate}
	\item single sphere,
	\item overlapping spheres
\end{enumerate}

The forward module includes the following functions:
\begin{enumerate}
	\item \textit{spm\_eeg\_inv\_forward\_ui.m}: run the user interface for this module,
	\item \textit{spm\_eeg\_inv\_BSTcreatefiles.m}:	create the structure and required files and parameters to interface SPM and BrainSTorm,
	\item \textit{spm\_eeg\_inv\_BSTfwdsol.m}:	compute the BrainSTorm forward solution, calling function \textit{bst\_headmodeler.m},
	\item \textit{spm\_eeg\_inv\_PCAgain}: compute the svd of the gain matrix.
\end{enumerate}

\section{Inverse reconstruction (\textit{inverse})}
The reconstruction is based on an empirical Bayesian approach to localize either the evoked response, the evoked power or the induced power, as measured by EEG or MEG.

The inverse module includes the following functions:
\begin{itemize}
	\item \textit{spm\_eeg\_inv\_inverse\_ui.m}: run the user interface for this module,
	\item \textit{spm\_eeg\_inv\_inverse.m}: main function,
	\item \textit{spm\_eeg\_inv\_evoked.m}:	compute the evoked response,
	\item \textit{spm\_eeg\_inv\_induced.m}:	compute the evoked and/or induced power,
	\item \textit{spm\_eeg\_inv\_msp.m}: Multivariate Source Prelocalisation~\cite{Mattout2005a}.
\end{itemize}