\documentclass{revtex4-2}

\usepackage{amsmath}
\usepackage{amsbsy}
\usepackage{amssymb}
\usepackage{graphicx}
\usepackage{bm,ulem,color}
\usepackage{natbib}

\include{gyrokinetics-macros}
\include{macros}

\usepackage[colorlinks=true]{hyperref}
\providecommand{\pitens}{\tensor{\pi}}
\begin{document}

\date{\today}

\title{\mctrans{} Reference Manual}
\author{Ian G. Abel}

\maketitle
\section{Introduction}

\mctrans{} is the scoping tool used by the CMFX project and others for designing centrifugal magnetic mirrors.

\section{\mctrans{}: A User's Guide}

\mctrans{} is driven from a configuration file. This file is written in the \href{https://github.com/toml-lang/toml}{TOML} language. This language endeavours
to be transparent and easy to use. The configuration file is broken up into blocks. ARRANGE THE BLOCKS (or finish writing this manual).

\section{The Physics Model of \mctrans{}}

\mctrans{} solves simplified transport equations for the centrifugally-confined plasma. The underlying models are all based on the assumption that the plasma is well-confined and that the thermal Mach number is large compared to one.

In many places we use formulae straight from the NRL Plasma Formulary.

\subsection{Fundamental Equations}

As with any transport solver, \mctrans{} solves equations for the fluid-like conserved quantities -- particles, energy, and momentum.
We work in the usual $(R,\tor,Z)$ cylindrical coordinate system.
The magnetic field lies purely in the $R-Z$ plane,\footnote{Estimates of ripple / mis-alignment induced transport can be computed, but it is currently out of scope for \mctrans{}.}
and is given by
\begin{equation}
\bm{B} = \grad\psi\times\grad \tor,
\end{equation}
where $\psi$ is the poloidal flux function (proportional to the toroidal component of the vector potential).
The electric field is given by
\begin{equation}
\bm{E} = -\grad \psi \frac{d \Phi}{d\psi} - \grad \pot,
\end{equation}
where we have split off the dominant radial electric field into the first term (which gives rise to the sonic rotation) and put all other electric field variation into the second term. Estimating the size of the two terms, we see that
\begin{equation}
\Phi \sim \frac{a M T_e}{e \rho_i} \gg \pot \sim \frac{T_e}{e},
\end{equation}
where $a$ is a typical radial scale length, $M$ the thermal Mach number, and $\rho_i$ the thermal ion Larmor radius.

We assume that the flow velocity $\bm{u}$ is the same for all species and given by
\begin{equation}
\bm{u} = \omega R^2 \grad\tor,
\end{equation}
where $\omega$ is the toroidal angular velocity. We also assume that the angular velocity is only a function of flux-surface-label $\psi$.

The underlying transport equations are thus:
\begin{eqnarray}
\label{parttrans}
\frac{d n_s}{dt} + \dv\bm{\Gamma}_s &=& S_{n\,s}\\
		\label{heattrans}
\frac{d}{dt} \left( \frac{3}{2} n_s T_s \right) + \dv\bm{q}_s &=& \left(\grad\psi \cdot \pitens \cdot \grad\tor\right) R^2 \frac{d\omega}{d \psi}   + Q_s + S_{E\,s}\\
	\label{momtrans}
\frac{d \omega}{dt} + \dv\left(\pitens\cdot R^2\grad\tor\right) &=& \bm{j} \times\bm{B} \cdot R^2\grad\tor + S_{\omega}.
\end{eqnarray}
In these equations the transport fluxes $\bm{\Gamma}_s$ and $\bm{q}_s$ are the particle and heat fluxes of each species, and the species-summed momentum flux tensor is denoted by $\pitens$. We have also included arbitrary sources of particles $S_{n\,s}$, energy $S_{E\,s}$, and angular momentum $S_{\omega\,s}$; these source terms will be used to account for collisionless parallel losses and energy sources such as alpha-particle heating.

Currently, \mctrans{} does not solve all these equations. In fact, we only solve for the transport of heat. The particle transport equation is assumed to contain a
source that is feedback controlled to maintain the electron density at a fixed value. This restiction may be lifted at a later date.

The momentum transport equation is more interesting. We know that the angular velocity is driven by $\bm{E}\times\bm{B}$ rotation, and so is given by
\begin{equation}
\omega = - \frac{d \Phi}{d\psi},
\end{equation}
where the effect of $\pot$ in $\bm{E}$ is small and can be neglected.  Due to the electrical configuration of a centrifugal mirror (see figure) we often
wish to consider the behaviour of a centrifugal plasma given a fixed input voltage. In this case, the momentum transport equation becomes an equation to determine
the radial current drawn from the power supply in terms of other quantities. We never need to solve \eref{momtrans} for $\omega$ in this setup. If we instead held the input power or current fixed then \eref{momtrans} would be solved as normal.

In steady-state operation, \mctrans{} sets the time derivatives to zero and solves the ensuing nonlinear algebraic equations to balance heat generation and heat losses.
In the following subsections we will explain the approximations used to calculate those heat losses explicitly in terms of the system state.

\subsection{Approximations to the Magnetic Geometry}
The simplest, and most transparent, geometric approximation is the ``square well'' model. In this model we assume the field lines to be straight, directed in the $Z$ direction, with a step-function shape and a step function in field strength. We demonstrate this in \Figref{squarewellplot}.
\begin{figure}
\includegraphics{SquareWell.pdf}
\caption{An example plot of field lines and the square-well approximation to the central field line}
\label{squarewellplot}
\end{figure}

\subsection{The Centrifugal Potential}

Many results have been derived for confinement in mirror machines which possess an electrostatic potential that varies along the field line. We can make use of these results by noting the following fact: the potential energy of a charged particle on a rotating field line at radius $R$ with angular velocity $\omega$ is
\begin{equation}
\Xi_s = Z_s e \pot - \frac{m_s}{2} \omega^2 R^2.
\end{equation}
We can thus reuse results from existing papers simply by making the substitution $Z_s e\pot \rightarrow \Xi_s$.

Physically, this electrostatic potential exists to keep the electrons (which are light and barely affected by the centrifugal force) next to the ions which are pushed to regions of large $R$ by the centrifugal force.
Hence, the potential $\pot$ has to be solved for by insisting that the plasma is quasineutral along field lines (and that the loss rate is ambipolar).
If we assume that the plasma rotates at a large Mach number $M \gg 1$, then the plasma is well-confined and the confinement time is long compared to the collision time (this can be checked \textit{a posteriori}). In such a situation the plasma is locally Maxwellian (equivalently it is in LTE) and we can write the density of species $s$ as~\cite{catto:2784,flowtome1}:
\begin{equation}
n_s = N_s(\psi) \exp\left( - \frac{\Xi_s}{T_s} \right).
\label{confinedDensity}
\end{equation}
If we now insist that the plasma is made up of ions (mass $m_i$ and charge $Z_i e$) and electrons (mass $m_e$ and charge $-e$) then quasineutrality reads
\begin{equation}
Z_i N_i \exp\left( - \frac{Z_i e\pot}{T_i} + \frac{m_i}{2T_i} \omega^2 R^2 \right) = N_e \exp\left( \frac{e\pot}{T_e} + \frac{m_e}{2T_e} \omega^2 R^2 \right).
\end{equation}
Without loss of generality, we can pick a baseline for $\pot$ such that $Z_i N_i = N_e$ (to see this, average along a field line, use the fact that neither $N_s$ nor $T_s$ varies along the field line). Furthermore, by neglecting the term containing the electron mass, we can solve the resulting equation for $\pot$:
\begin{equation}
\pot = \left( \frac{Z_i e}{T_i} + \frac{e}{T_e}\right)^{-1} \frac{m_i}{2 T_i} \omega^2 R^2,
\end{equation}
up to a possible constant offset. It is clear that this potential is $\Or(M^2T_e/e)$ and is, in fact, the leading order term in an asymptotic series in $M^{-1}$.\footnote{In computing the densities in \eref{confinedDensity}, we have integrated over a full Maxwellian distribution, neglecting the fact that some small number of high-energy particles are in fact lost alongt he field line. This is a consistent approximation as we have determined that the potential barrier is $\Or(M^2T_e)$, which to leading order is effectively infinite.}
To compute the next-order terms in this series we need to know about lost particles and hence parallel transport. This is tackled in the next section. We end with a convenient expression for the potential drop from the centre of a flux surface (at $R = R_{max}$) in terms of suitably normalized variables:

\begin{equation}
\frac{e \pot}{T_e} = \left( \frac{Z_i}{\tau} + 1 \right)^{-1} \frac{M^2}{2} \left( \frac{R^2}{R_{\mathrm{max}}^2} - 1 \right) + \Or(1),
\end{equation}
where we let $\tau = T_i/T_e$ be the temperature ratio, and we have defined the sonic Mach number $M = \omega R_{max} / \cs$ in terms of the sound speed $\cs^2 = T_e / m_i$.\footnote{This is not the speed at which sound waves propagate in a warm plasma, but provides a very convenient normalization. It is the cold-ion limit of the sound speed, and we will continue to call it the sound speed despite this abuse of terminology.}
This is only the leading-order term in a $M \gg 1$ expansion, and so we collect all higher-order terms and denote them by $\pot_0$.
Note that if $Z_i = \tau = 1$ then we get the usual $M^2/4$ scaling for the potential drop.
It is also useful to note that, as a consequence of flux conservation
	\begin{equation}
	\frac{B_{\mathrm{min}}}{B_{\mathrm{max}}} = \left(\frac{R_{\mathrm{max}}}{R_{\mathrm{min}}}\right)^2,
\end{equation}
and so we can relate the ratio of the radius of the flux surface at throat and in the central cell to the ``Mirror Ratio'' given by the ratio of magnetic field strengths.

For electrons, the only term in the potential energy is the electrostatic potential:
\begin{equation}
\Xi_e = \left( \frac{Z_i}{\tau} + 1 \right)^{-1} \frac{M^2}{2} T_e \left( 1 - \frac{R^2}{R_{\mathrm{max}}^2} \right) - e \phi_0,
\end{equation}
but for ions we need to include the centrifugal potential to obtain
\begin{equation}
\Xi_i = \left( \frac{Z_i}{\tau} + 1 \right)^{-1} \frac{M^2}{2} T_i \left( 1 - \frac{R^2}{R_{\mathrm{max}}^2} \right) + Z_i e \phi_0,
\end{equation}
where we have picked the constant offset of $\pot$ such that $\Xi_i = \Xi_e = 0$ at the midplane ($Z=0$, $R=R_{\mathrm{max}}$). Again, $\pot_0$ is the higher-order part of $\pot$ that must be determined by evaluating the parallel losses.

\textbf{N.B. In contrast to a tandem mirror, where the only confining potential is electric, the addition of the centrifugal term allows the
	potential to be confining for \textit{both} the species.}

\subsection{Parallel Transport}

We assume that the plasma is hot enough to be in the collisionless regime where the particle bounce time (inside the potential well formed by the centrifugal force) is extremely short compared to the particle collision time. This is manifestly true in reactor-grade plasmas ($\left.\nu_{ii} L_\parallel \right/ \vth \sim 10^{-5}$ or smaller) but is even valid for warm plasmas above a few hundred electron Volts in temperature. The collisionality parameter is reported and if it is not much less than one the results of \mctrans{} are not valid.

In this collisionless regime we use formulae that are derived in the manner originally used by Pastukhov~\cite{Pastukhov1974} for the case of a tandem mirror with an electron-confining electrostatic potential. Pastukhov originally derived his results for electrons alone. We need the result for a multispecies plasma.
We can find this result in \citet{CattoBernsteinMirror1} by taking the square-well limit of (40) of that work to obtain the particle loss rate in our notation:
\begin{equation}
\left(\pd{n_s}{t}\right)_{\mathrm{End Losses}} =
	- \left( \frac{2 n_s \Sigma}{\sqrt{\pi}} \right) \nu_s \frac{1}{\ln\left( R_{\mathrm{mirror}} \Sigma\right)} \frac{\exp\left( -\Xi_s/T_s \right)}{\Xi_s/T_s},
	\label{ParticleLossRate}
\end{equation}
where $\Sigma = Z_i + 1$ for electrons and $\Sigma = 1$ for ions, and $\nu_s$ is the appropriate collision frequency for species $s$. For electrons this is the combination of electron-electron and electron-ion collisions. For ions this is just the ion-ion collision frequency.

Note that this equation only agrees with the results of \citet{Pastukhov1974} and \citet{cohen1978collisional} in the limit of $R_{\mathrm{mirror}} \rightarrow \infty$. The error induced by not knowing this prefactor accurately is much smaller than the approximation by a square well, and is comparable with the effect of several other approximations made in the analytic work.

We anticipate upgrading \mctrans{} to use the full formulae of \citet{CattoBernsteinMirror1} in the near future, thereby including some effect of the actual magnetic geometry.

This particle loss rate can be used to compute heat losses by multiplying by $\Xi_s$ -- the energy loss is dominated by energetic particles, nullifying the extra power of $\Xi_s$ in the denominator of \eref{ParticleLossRate}. Similarly, loss of toroidal angular momentum can be computed by multiplying the particle loss rate by the angular momentum lost per ion (electrons carrying negligible momentum).

\subsubsection{Ambipolar Parallel Losses and Solving for $\pot$}
In the formula \eref{ParticleLossRate} for the losses we see that $\Xi_s$ appears in the exponential. The leading order part of $\Xi_s$ is $\Or(M^2 T_s)$, so this exponential is what strongly suppresses the collisional loss rate. Expanding this exponential schematically we have
\begin{equation}
\exp\left( -\frac{\Xi_s}{T_s} \right) \approx \exp\left[ - (\dots) M^2 \right] \exp\left( -Z_s e \pot_0 / T_s \right),
\end{equation}
and we see that even though $\pot_0$ is small compared to the leading-order part of the potential it has an $\Or(1)$ effect on the loss rate and must be accounted for.

We find $\pot_0$ by equating the electron and ion loss rates along the field line to enforce zero net charge loss along the field line. \textbf{N.B. This part of the code can be a little tempremental, and if you find a case that doesn't work it may be because you're starting to search for an equilibrium from a starting point that is so poorly confined that quasineutrality cannot be satisfied within the bounds that the code is searching.}

\subsection{Perpendicular Transport}

To completely evaluate the heat transport equations we need expressions for $\bm{q}_s$ and $\pitens$.
We consider only the classical collisional contribution to these transport fluxes. Turbulent transport should be fully suppressed by the flow shear.

We handle the heat flux first.
From (2.14) of \citet{braginskii1965tpp} the collisional ion heat flux in a strongly-magnetized plasma is
\begin{equation}
q_i = -\chi_{i\parallel} \bm{b}\bm{b}\dg T_i - \chi_{i\perp} \grad_\perp T_i + \frac{5}{2} \frac{n_i T_i}{m_i \cycfreq[i]} \bm{b}\times\grad T_i.
\end{equation}
Now, in the collisionless limit, $T_i = T_i(\psi)$ and so the first term vanishes, and the third term is purely toroidal. Thus, when we evaluate the divergence of the heat flux, we obtain (using axisymmetry)
\begin{equation}
\dv\bm{q}_i = \dv\left( \chi_{i\perp} \grad_\perp T_i \right).
\end{equation}
To estimate this term, we assume that all the plasma profiles vary on a scale $a$ that is related to the width of the plasma column $w$ by $a = w/2$, see \Figref{scales} for more details. Thus, we have that
\begin{equation}
\dv{\bm{q}_i} \approx \frac{1}{a^2} \chi_{i\perp} T_i = \frac{2 n_i T_i^2}{m_i \cycfreq[i]^2 \tau_i a^2},
\end{equation}
where we have used (2.16) of \citet{braginskii1965tpp} for $\chi_{i\perp}$ and $\tau_i$ is the ion-ion collision time.

For electrons, the same geometric algebra applies and we have
\begin{equation}
\dv{\bm{q}_e} \approx \frac{1}{a^2} \chi_{e\perp} T_e = \frac{4.66 n_e T_e^2}{m_e \cycfreq[e]^2 \tau_e a^2},
\end{equation}
which is approximately $\sqrt{m_e/m_i}$ smaller than the ion heat loss, and usually negligible.

\begin{figure}
\includegraphics{ScaleLengths.pdf}
\caption{Plasma column showing its width $w$, lenght $L$, and scale length $a$}
\label{scales}
\end{figure}

We only compute the stress tensor for the ions, electron perpendicular viscosity is at least $m_e/m_i$ smaller than the ion viscosity and always negligible.
To compute the Braginskii viscous stress tensor, we need to know the rate of strain tensor $\tensor{W}$:
\begin{equation}
\tensor{W} = \left(\grad\bm{u}\right) + \left(\grad\bm{u}\right)^{T} - \frac{2}{3} \left(\dv\bm{u}\right)\idmat,
\end{equation}
which, upon using $\bm{u} = \omega R^2 \grad\tor$, becomes
\begin{equation}
\tensor{W} = R^2 \frac{d \omega}{d\psi} \left( \grad\psi \grad \tor + \grad \tor \grad \psi\right) \approx \frac{R}{a} \omega
\end{equation}
Evaluating this on the midplane, we see that in Braginskii's cartesian coordinates (with $z$ along $\bm{b}$) the only nonzero component of $\tensor{W}$ is $W_{xy}$ (equivalently $W_{yx}$).
Thus, using (2.21) of Braginskii, we can compute the nonzero components of the stress tensor. The quantities we need are
\begin{equation}
\dv\left( \pitens\cdot R^2\grad\tor \right) \approx \frac{1}{a} \pi_{xy} R = - \frac{R}{a} \frac{3}{10} \frac{n_i T_i}{\cycfreq[i]^2 \tau_i} W_{xy} = - \frac{R}{a} \frac{3}{10} \frac{n_i T_i}{\cycfreq[i]^2 \tau_i} \frac{R}{a} \omega,
\end{equation}
and
\begin{equation}
\pitens \bm{:}\grad\bm{u} = \frac{1}{2} \pi_{xy} W_{xy} \approx - \frac{3}{10} \frac{n_i T_i}{\cycfreq[i]^2 \tau_i}\frac{R^2\omega^2}{a^2}.
\end{equation}

Note that, because we are using Braginskii's formulae, we also have to use his formula for the collision times (see \citet{braginskii1965tpp}) which differ by $\sqrt{2}$ from some other definitions of $\tau_i$.

\subsection{Alpha Particles and Nuclear Physics}
Our fundamental model for alpha particles is that they are all born with a delta-function distribution at the birth energy of $E_\alpha = 3.52$ MeV:
\begin{equation}
\left( \pd{f_\alpha}{t}\right)_{\mathrm{Source}} = \frac{S_\alpha \delta(v-v_*)}{4\pi v_*^2}
\end{equation}
where $v_*$ is the birth velocity corresponding to $E_\alpha$ and $S_\alpha$ is the birth rate of alphas per unit time per unit volume.

\subsubsection{Prompt Alpha Losses}
Alpha particles are born isotropically. Thus, a fraction of them are born directly into the unconfined region of velocity space.
The birth energy of alphas $E_\alpha$ is much greater than the centrifugal potential which is roughly $M^2 T_e / 4$ (at fusion temperatures and parameters this remains
less than $0.5$ MeV). We thus model the loss region for energetic alphas as a cone, and only classical mirror confinement applies, thus an alpha is lost if
\begin{equation}
\mu_\alpha B_{\mathrm{max}} > E_\alpha.
\end{equation}
Integrating this over all velocity space, we see that the fraction of alphas that is lost is
\begin{equation}
f_{\mathrm{lost}} = 1 - \sqrt{1 - \frac{1}{R_{\mathrm{mirror}}}}.
\end{equation}
This fraction of alpha particles is removed from \mctrans{} and hurled against the end plates.
This prompt loss of alpha particles is taken into account in assessing quasineutrality.

\subsubsection{Collisional Alpha Losses}
Currently, we do not have any explicit collisional losses of alpha particles. However, the approximate lifetime of alpha particles in the machine is (under the twin assumptions that of $R_{\mathrm{mirror}} \gg 1$ and that we can treat alphas like main ions, see e.g. \citet{ryutovOpenTraps})
\begin{equation}
\tau_\alpha \approx 0.4 \tau_{\alpha i} \ln R_{\mathrm{mirror}},
\end{equation}
where $\tau_{\alpha e}$ is the alpha-ion collision time (alpha-electron collisions do not change the pitch-angle of the alpha particles), which is marginally longer than the time it takes the alphas to deposit a reasonably large amount of their energy into electrons and ions.
Really we should solve the Fokker-Planck kinetic equation for alpha particles with a source and a loss cone as is done in \citet{santarius1982}.

\subsubsection{Alpha Heating}
Currently, all the energy in the retained alpha particles is deposited into the electron species as heating through collisions.
This is a pessimistic assumption as electron heating leads to a lower Mach number, faster electron losses, an increasingly electron-confining $\pot$, and hence increased ion losses.

\subsection{Neutral Transport}
We currently have no model of transport due to neutral particles. A first step towards this will be implementing a diagnostic for
the neutral mean free path in our plasma. In the limit of either very small or very long mean free path, we may be able to make further approximations to evaluate the
losses from charge exchange.
\\
\textbf{N.B. Until more neutral physics is implemented, we have no way to handle self-consistent fuelling scenarios. The only reasonable assumption
	is that losses due to neutrals are small and feedback control is used to target a fixed electron density.}

\subsection{Radiative Processes and Impurities}
There are two ways to model impurities in \mctrans{}. Firstly is a ``lumped impurity'' that only changes the effective charge state $Z_{\mathrm{eff}}$ and
provides \textit{only} bremsstrahlung radiation. It does not dilute the main ion species, so quasineutrality is enforced by only considering the main ions and
electrons.

\subsubsection{Bremsstrahlung and Synchrotron Radiation}
Taking the formulae for bremsstrahlung from the NRL formulary~\cite{nrlformulary} and writing it in convenient units we have
\begin{equation}
P_{\mathrm{rad}} =  5.34 \times 10^3\, Z_{\mathrm{eff}} \left(\frac{n_e}{10^{20} \mathrm{m}^{-3}}\right)^2 \left(\frac{T_e}{1 \mathrm{keV}}\right)^{1/2}\, \mathrm{W}/\mathrm{m}^3,
\end{equation}
where we have used the definition
\begin{equation}
Z_{\mathrm{eff}} = \frac{1}{n_e} \sum_{s} Z_s^2 n_s,
\end{equation}
of the effective charge state of the plasma (summation taken over all positively charged species).
Similarly, we can take the synchrotron radiation formula from the formulary~\cite{nrlformulary} and write it as
\begin{equation}
P_{\mathrm{rad}} =  6.21 \times 10^3 \,\left( \frac{B}{1\,\mathrm{T}} \right)^2 \left( \frac{n_e}{10^{20}\, \mathrm{m}^{-3}} \right) \left( \frac{T_e}{1\,\mathrm{keV}} \right)\, \mathrm{W}/\mathrm{m}^3.
\end{equation}

The plasma is assumed to be optically thin, and so all radiation is lost onto the first wall.

\subsubsection{Line Radiation}
 Without a better model for the impurity species that are present (including multiple charge states) we cannot reliably predict the amount of line radiation lost from the plasma.
\\
\textbf{N.B. Because of the lack of ionization and radiative cooling, one should view low-temperature outputs from \mctrans{} extremely sceptically!}

\appendix
\section{Full Syntax for \mctrans{} configuration files}

\section{Non-Physical Implementation}
The use of "fudge-factors" has been included to simulate arbitrarily better or worse confinement. The default value is 1, and values less than or greater than 1 result in better or worse confinement, respectively. The fudge factors are applied to loss rates (either particle or heat). There are separate fudge factors for perpendicular and parallel, and viscous and thermal transport.

\bibliographystyle{apsrev}
\bibliography{references}
\end{document}


\section{Spacecraft Model}

\subsection{RF Hardware Models}

The RF Hardware models in GMAT include transmitters, receiver, and transponders.  For each type of RF Hardware there are models for signal transmission/reception feasibility, received frequency, and transmitted frequency to name a few.  In the sections below we present these models for each type of RF Hardware.

\subsubsection{Receiver}

The receiver model supports a frequency model and a reception feasibility model.  The frequency model allows the user to specify the frequency capabilities of the receiver using different methods.  The feasibility model determines whether an RF signal sensed at the receiver can feasibly detected given the receivers capability as defined by the frequency model.

When the frequency model \st{CenterAndBandwidth} is selected, the feasibility test is as follows.  Define the frequency transmitted by the originating transmitter as $F_t$, the receiver's center frequency as $F_C$, the bandwidth as $\Delta F$, and the range rate between transmitter and receiver as $\dot{\rho}$ (which is positive when the distance $\rho$ is increasing).  The frequency at the receiver is calculated using
%
\begin{equation}
     F_r = F_t(1 - \frac{\dot{\rho}}{c})
\end{equation}
%
where $c$ is the speed of light.  Define the upper limit of the receiver as $F_u = F_c + \Delta F / 2$ and the lower limit as $F_l = F_c - \Delta F / 2$ .  If
%
\begin{equation}
       F_l \leq F_r \leq F_u
\end{equation}
%
then the received frequency is received by the receiver model.  If the above test fails, the receiver does not receive the signal.

\subsubsection{Transmitter}

\subsubsection{Transponder}

\subsubsection{Antenna}

\subsection{Thruster Models}

GMAT supports several thruster models.  The thruster models employ
physics and empirical data provided by the thruster manufacturer to
model thrust and mass flow rate used in orbit and attitude equations
of motion.   The thrust magnitude and $I_{sp}$ are assumed to be
functions of thruster inlet flow conditions including  pressure,
temperature, and for bi-propellant thrusters, the oxidizer to fuel
ratio.

In the following subsections we present models for thrust magnitude
and mass flow rates for several thruster types.  All thrusters have
a location and orientation.  The location is described in the
spacecraft body system.  The orientation can be described with
respect to any coordinate system known to GMAT. Let's define the
rotation matrix from the thruster frame $\mathcal{F}_T$ to Earth's
MJ2000 Equator as $\mathbf{R}_T$. Then, the thrust used in the orbit
equations of motion is
%
\begin{equation}
    \mathbf{F}_T = F_T \mathbf{R}_T \hat{\mathbf{T}}
\end{equation}
%
where $F_T$ is the thrust magnitude and is thruster dependent, and
$\hat{\mathbf{T}}$

Now let's look at how to calculate the thrust magnitude for a
mono-propellant chemical thruster.

\subsubsection{Mono-Propellant Chemical Thruster}

temperature.  The specific form of Eqs.~(\ref{Eq:MonoPropThrust})
and (\ref{Eq:MonoPropIsp}) are determined by fitting test data to
approximate thrust and $I_{sp}$ as function $T_i$ and $P_i$.  The
user can supply this relationship via a scripte
%
\begin{figure}[h!]
\centerline{
\begin{picture}(100,480)
\special{psfile= ./Images/MonoPropThruster.eps hoffset= -20 voffset= 250
hscale=25 vscale=25}
\makebox(100,540){$\dot{m}_e$,$P_e$,$v_e$}
%
\makebox(-105,710){$\dot{m}_c$,$T_c$,$P_c$}
%
\makebox(-105,920){$m_f$,$T_f$,$P_f$}
%
\makebox(-255,880){Catalyst Bed}
\end{picture}}\vskip -3.75 in  \caption{ Mono-Prop Thruster Diagram} \label{fig:MonoPropThruster}
\end{figure}

We assume thruster data is given as a function of thruster inlet
properties (as opposed to thrust chamber properties), and thrust
magnitude and $I_{sp}$ are modelled using
%
\begin{equation}
    F_T = f(P_i,T_i)\label{Eq:MonoPropThrust}
\end{equation}
%
\begin{equation}
    I_{sp} = f(P_i,T_i)\label{Eq:MonoPropIsp}
\end{equation}
%
where $P_i$ and $T_i$ are the thruster inlet pressure and
temperature.  The specific form of Eqs.~(\ref{Eq:MonoPropThrust})
and (\ref{Eq:MonoPropIsp}) are determined by fitting test data to
approximate thrust and $I_{sp}$ as function $T_i$ and $P_i$.  The
user can supply this relationship via a scripted equation or by
providing a function name.  After calculating $F_T$ and $I_{sp}$, we
calculate the mass flow rate using
%
\begin{equation}
   \dot{m}_e = \frac{F_T}{I_{sp}}
\end{equation}

\subsubsection{Bi-Propellant Chemical Thruster}

\begin{figure}[h!]
\centerline{
    \begin{picture}(100,470)
    \special{psfile= ./Images/BiPropThruster.eps hoffset= -20 voffset= 260
    hscale=25 vscale=25}
    \makebox(80,545){$\dot{m}_e$,}\makebox(-47,545){$P_e$,}
    \makebox(-30,545){$v_e$}
    \makebox(-70,730){$\dot{m}_c$,$m_r$,$T_c$,$P_c$}
    \makebox(-30,938){$m_f$,$T_f$,$P_f$}
    \makebox(-140,938){$m_o$,$T_o$,$P_o$}
    \end{picture}}\vskip -3.75 in  \caption{ Bi-Prop Thruster Diagram} \label{fig:BiPropThruster}
\end{figure}

\begin{equation}
    m_r = \frac{\dot{m}_o}{\dot{m}_f}
\end{equation}
%
\begin{equation}
    \dot{m}_c = \dot{m}_o + \dot{m}_f
\end{equation}
%
\begin{equation}
    T'=  \frac{\dot{m}_o T_o + \dot{m}_f T_f}{\dot{m}_o + \dot{m}_f}
\end{equation}
%
\begin{equation}
    P' =  \frac{\dot{m}_o P_o + \dot{m}_f P_f}{\dot{m}_o + \dot{m}_f}
\end{equation}
%
\begin{equation}
   F = f(P_c,T_c,of)
\end{equation}
%
\begin{equation}
   I_{sp} = f(P_c,T_c,of)
\end{equation}
%
\begin{equation}
   \dot{m}_e = \frac{\mathbf{F}_T}{I_{sp}}
\end{equation}

\subsubsection{Thruster Pulse Modelling}

\begin{equation}
T'=\frac{T(t)}{T_{max}} = \left\{\begin{array}{ll}
             \displaystyle\frac{t^2(t - t_{si})^2}{t_{si}^4} &
             \mbox{$t \leq t_{si}$}\\
             1 & \mbox{$t_{si}<t<t_{sf}$}\\
             \displaystyle\frac{(t - 2 t_{sf} + t_{f})^2(t - t_f)^2}{(t_f - t_{sf})^4}
             & \mbox{$t_{sf} \leq t \leq t_f$}\\
             \end{array}\label{eq:quartic}
      \right.
\end{equation}
%
\begin{figure}[ht]
\centerline{
    \begin{picture}(100,385)
    \special{psfile= ./Images/ThrustPulseProfile.eps hoffset= -150 voffset= 60
    hscale=65 vscale=65}
    \end{picture}}\vskip -3.75 in  \caption{ Sample Thrust Pulse Profile } \label{fig:ThrustPulseProfile}
\end{figure}
%
%
The time to the thrust centroid, $t_c$, is calculated using
%
\begin{equation}
     t_c = \displaystyle\frac{\displaystyle\int_0^{t_{f}} t \mbox{ }T'(t) dt}{\displaystyle\int_0^{t_{f}} T'(t)dt}
\end{equation}
%
performing the integral yields
%
\begin{equation}
    t_c = \frac{-4 t_{si}^2  + 4 t_{sf}^2  + 6 t_{sf} t_f + 5 t_f^2 }{-14 t_{si} + 14 t_{sf} + 16 t_f}
\end{equation}

\subsubsection{Thruster Hot Fire Test Data \\ and Thruster Models}

Thruster hot fire test data is used to develop empirical models that
describe thruster performance as a function of inlet conditions such
as fuel pressure and temperature.  In this section we'll discuss how
the empirical models are developed and discuss how the empirical
models are consistent with the physical models.  First we present
the physics model  for a thruster test stand experiment.  Next we
present what is measured during a thrust stand test, and show how
the measurements are used in combination with the physics model to
generate a model of thruster performance over  a given range of
thruster inlet conditions.

In Fig.~\ref{fig:ThrustStand} we see an illustration of a simple
thrust test setup.  The thruster is mounted to a rigid surface.
%
\begin{figure}[h!]
\centerline{
\begin{picture}(100,400)
\special{psfile= ./Images/ThrusterOnStand.eps hoffset= -35 voffset= 220
hscale=25 vscale=25}
\makebox(-120,700){$\dot{m}$}\makebox(-120,675){$T_i$}
\makebox(-125,650){$P_i$}\makebox(225,705){$\dot{m}$}\makebox(-190,680){$c^*=
I_{sp}g$}\makebox(-225,655){$P_e$}\makebox(-225,530){$F_T$}
\end{picture}}\vskip -3.5 in  \caption{ Thrust Stand Illustration} \label{fig:ThrustStand}
\end{figure}
%
The force due to thrust, $F_T$, can be written as
%
\begin{equation}
    F_T = \dot{m}v_e - (P_e - P_a)A_e
\end{equation}
%
where
\begin{tabbing}
    12345678 \= Reynolds number based on length $s$ \kill
    $\dot{m}$    \>  mass flow rate, kg/s \\
    $T_i$        \>  fuel inlet temperature, K$^{\circ}$\\
    $P_i$        \>  fuel inlet pressure, Pa\\
    $c^*$        \>  characteristic velcocity, m/s \\
    $I_sp$       \>  specific impulse, s \\
    $g_o$        \>  9.801 m/s$^2$ \\
    $P_e$        \>  nozzle exit pressure, Pa\\
    $A_e$        \>  nozzle exit area, m$^2$\\
    $F_T$        \>  force due to thrust, N\\
\end{tabbing}
%
we can rewrite this as
\begin{equation}
    F_T = \dot{m}\left(v_e - \frac{(P_e - P_a)A_e}{\dot{m}}\right)  \label{Eq:Fvsmv}
\end{equation}
%
From this equation we define the characteristic velocity, $c^*$,
using
%
\begin{equation}
    c^* = \left(v_e - \frac{(P_e - P_a)A_e}{\dot{m}}\right)
\end{equation}
%
In practice, $v_e$ or $P_e$ are not measured.  We'll assume the
tests are performed in a vacuum so $P_a = 0$.  To understand how we
relate the measurements to physical model, let's define a new
quantity $I_{sp}$, where
%
\begin{equation}
    I_{sp} = \frac{F_T}{\dot{m} g_o}
\end{equation}
%
we can rewrite this as
%
\begin{equation}
    F_T = \dot{m} I_{sp} g_o \label{Eq:IspVer2}
\end{equation}
%
Comparing Eq.s~(\ref{Eq:Fvsmv}) and (\ref{Eq:IspVer2}) we see that
%
\begin{equation}
     c^* = I_{sp} g_o = v_e - \frac{(P_e - P_a)A_e}{\dot{m}}
     \label{Eq:CstarIsp}
\end{equation}
%
Equation (\ref{Eq:CstarIsp}) shows that $I_{sp}$ is a measure of the
effective (characteristic) exhaust velocity.  $I_{sp}$ contains
information on the energy stored in the fuel and how that energy
translates to exit velocity.   When $I_{sp}$ is calculated from
measured thrust data, the $I_{sp}$ contains a correction for exhaust
velocity for force due to pressure $(P_e - P_a)A_e$.

The characteristic velocity, and hence $I_{sp}$, depend on the type
of fuel and the inlet temperature and pressure of the fuel.
Experimental data determines how
%
\begin{equation}
    I_{sp}(T_i,P_i) = \left.\frac{F_T}{\dot{m}g_o}\right|_{(T_i,P_i)}
\end{equation}
%
\begin{tabbing}
    12345678     \= Reynolds number based on length $s$ \kill
    $\dot{m}$    \>  Known      \\
    $T_i$        \>  Known      \\
    $P_i$        \>  Known      \\
    $g_o$        \>  Known      \\
    $F_T$        \>  Measured   \\
    $I_sp$       \>  Calculated \\
\end{tabbing}

\include{TankModels}

\subsection{Mass Properties}

\subsubsection{Spherical Tank}
\clearpage
\begin{figure}[ht]
\centerline{
    \begin{picture}(110,440)
    \special{psfile= ./Images/PartiallyFilledTank.eps hoffset= -110 voffset=
    90
    hscale=55 vscale=55}
    \makebox(-47,665){$h$}
    \makebox(135,620){$r$}
    \makebox(0,695){$\hat{y}$}
    \makebox(-165,850){$\hat{z}$}
    \makebox(-165,515){($\hat{x}$ is out of the page)}
    \end{picture}}\vskip -3.65 in  \caption{ Geometry For Mass Properties of Partially Filled Spherical Tank} \label{fig:PartiallyFilledTank}
\end{figure}

\begin{equation}
    V = \frac{1}{3}\pi \left( 3r - h \right)h^2
\end{equation}
%
\begin{equation}
    cg_z = \displaystyle\frac{-\displaystyle\frac{3}{4}h^2 + 3hr - 3r^2}{3r - h}
\end{equation}
%
\begin{equation}
    cg_x = cg_y = 0
\end{equation}
%
\begin{equation}
   I_{zz} = \frac{\pi \rho}{2}\left(\frac{1}{5}\left( h - r\right)^5 - \frac{2}{3}r^2\left( h - r\right)^3  + r^4(h-r) + \frac{8}{15}r^5 \right)
\end{equation}
%
\begin{equation}
   I_{xx} = \frac{\pi \rho}{2}\left(-\frac{3}{10}\left( h - r\right)^5 + \frac{1}{3}r^2\left( h - r\right)^3  + \frac{1}{2}r^4(h-r) + \frac{8}{15}r^5 \right)
\end{equation}
%
\begin{equation}
   I_{yy} = I_{xx}
\end{equation}
%
\begin{equation}
    \mathbf{I}' = \mathbf{R}_{bt}^T
    \left(\begin{array}{ccc}
         I_{xx} & 0 & 0 \\
         0 & I_{yy} & 0\\
         0 & 0 & I_{zz}\\
    \end{array}\right)
     \mathbf{R}_{bt} \
\end{equation}
%
Estey \cite{Estey:83} gives appoximate equations for the area of
different portions for a partially filled sphere. The area of the
spherical shell in contact with the gaseous region is given by
%
\begin{equation}
   A_g = 4.0675 \cdot V^{2/3}\left(\frac{V_g}{V}\right)^{0.62376}
\end{equation}
%
The area of the boundary between the liquid and the gaseous region
is given by
%
\begin{equation}
   A_b = A_g - 3.4211 \cdot V^{2/3}\left(\frac{V_g}{V}\right)^{1.24752}
\end{equation}
%
Finally, the area of the spherical shell in contact with the liquid
is given by
%
\begin{equation}
   A_l = \pi D^2 - A_g
\end{equation}
%

%\input{FlowModelling}


\subsection{The Lucas Aggregate Supply (AS) function}


\appchapter{Generated Data}
\label{appendix:data}
\section{Uniform}
\label{appendix:data:uniform}
\begin{figure}[H]
\centering
\begin{subfigure}{.8\textwidth}
	\includegraphics[width=.9\textwidth]{img/0_UNIFORM_plot.png}
\end{subfigure}%
\begin{subfigure}{.2\textwidth}
  \centering
  \begin{minipage}{1\textwidth}
\textbf{Widths:}
\\
min: 47
\\
max: 47
\\
mean: 47.00
\\
variance: 0.00
\\
std: 0.00
\\
skewness: 0.00
\\
kurtosis: $-3.00$
\\\\
\textbf{Heights:}
\\
min: 109
\\
max: 109
\\
mean: 109.00
\\
variance: 0.00
\\
std: 0.00
\\
skewness: 0.00
\\
kurtosis: $-3.00$
  \end{minipage}
\end{subfigure}
% \caption{Data distribution for 0\_Uniform.in}
% \source{Compiled by the authors}
\end{figure}
\section{Random}
\label{appendix:data:rand}
\begin{figure}[H]
\centering
\begin{subfigure}{.8\textwidth}
	\includegraphics[width=.9\textwidth]{img/1_RAND_plot.png}
\end{subfigure}%
\begin{subfigure}{.2\textwidth}
  \centering
  \begin{minipage}{1\textwidth}
\textbf{Widths:}
\\
min: 7
\\
max: 511
\\
mean: 259.78
\\
variance: 21293.52
\\
std: 145.92
\\
skewness: $-0.01$
\\
kurtosis: $-1.20$
\\\\
\textbf{Heights:}
\\
min: 13
\\
max: 1201
\\
mean: 606.26
\\
variance: 120065.68
\\
std: 346.50
\\
skewness: 0.00
\\
kurtosis: $-1.20$
  \end{minipage}
\end{subfigure}
% \caption{Data distribution for 1\_Rand.in}
% \source{Compiled by the authors}
\end{figure}

\section{Random with Constant Height}
\label{appendix:data:randconstheight}
\begin{figure}[H]
\centering
\begin{subfigure}{.8\textwidth}
	\includegraphics[width=.9\textwidth]{img/2_RANDCONSTHEIGHT_plot.png}
\end{subfigure}%
\begin{subfigure}{.2\textwidth}
  \centering
  \begin{minipage}{1\textwidth}
\textbf{Widths:}
\\
min: 7
\\
max: 511
\\
mean: 258.52
\\
variance: 21358.88
\\
std: 146.15
\\
skewness: $-0.00$
\\
kurtosis: $-1.20$
\\\\
\textbf{Heights:}
\\
min: 109
\\
max: 109
\\
mean: 109.00
\\
variance: 0.00
\\
std: 0.00
\\
skewness: 0.00
\\
kurtosis: $-3.00$
  \end{minipage}
\end{subfigure}
% \caption{Data distribution for 2\_Randconstheight.in}
% \source{Compiled by the authors}
\end{figure}

\section{Random with Constant Width}
\label{appendix:data:randconstwidth}
\begin{figure}[H]
\centering
\begin{subfigure}{.8\textwidth}
	\includegraphics[width=.9\textwidth]{img/3_RANDCONSTWIDTH_plot.png}
\end{subfigure}%
\begin{subfigure}{.2\textwidth}
  \centering
  \begin{minipage}{1\textwidth}
\textbf{Widths:}
\\
min: $47$
\\
max: $47$
\\
mean: $47.00$
\\
variance: $0.00$
\\
std: $0.00$
\\
skewness: $0.00$
\\
kurtosis: $-3.00$
\\\\
\textbf{Heights:}
\\
min: $13$
\\
max: $1201$
\\
mean: $607.04$
\\
variance: $119714.09$
\\
std: $346.00$
\\
skewness: $-0.00$
\\
kurtosis: $-1.20$
  \end{minipage}
\end{subfigure}
% \caption{Data distribution for 3\_Randconstwidth.in}
% \source{Compiled by the authors}
\end{figure}
\section{Skewed}
\label{appendix:data:skewed}
\begin{figure}[H]
\centering
\begin{subfigure}{.8\textwidth}
	\includegraphics[width=.9\textwidth]{img/4_SKEWED_plot.png}
\end{subfigure}%
\begin{subfigure}{.2\textwidth}
  \centering
  \begin{minipage}{1\textwidth}
\textbf{Widths:}
\\
min: 7
\\
max: 511
\\
mean: 60.90
\\
variance: 2490.82
\\
std: 49.91
\\
skewness: 5.19
\\
kurtosis: 40.29
\\\\
\textbf{Heights:}
\\
min: 13
\\
max: 1201
\\
mean: 195.35
\\
variance: 17598.95
\\
std: 132.66
\\
skewness: 2.40
\\
kurtosis: 14.07
  \end{minipage}
\end{subfigure}
% \caption{Data distribution for 4\_Skewed.in with 1\% total skewed options}
% \source{Compiled by the authors}
\end{figure}
\section{Skewed with Constant Height}
\label{appendix:data:skewedconstheight}
\begin{figure}[H]
\centering
\begin{subfigure}{.8\textwidth}
	\includegraphics[width=.9\textwidth]{img/5_SKEWEDCONSTHEIGHT_plot.png}
\end{subfigure}%
\begin{subfigure}{.2\textwidth}
  \centering
  \begin{minipage}{1\textwidth}
\textbf{Widths:}
\\
min: 7
\\
max: 511
\\
mean: 61.06
\\
variance: 2493.88
\\
std: 49.94
\\
skewness: 5.15
\\
kurtosis: 39.87
\\\\
\textbf{Heights:}
\\
min: 13
\\
max: 1201
\\
mean: 602.58
\\
variance: 121471.29
\\
std: 348.53
\\
skewness: 0.01
\\
kurtosis: $-1.22$
  \end{minipage}
\end{subfigure}
% \caption{Data distribution for 5\_Skewedconstheight.in with 1\% total skewed options}
% \source{Compiled by the authors}
\end{figure}
\section{Skewed with Constant Width}
\label{appendix:data:skewedconstwidth}
\begin{figure}[H]
\centering
\begin{subfigure}{.8\textwidth}
	\includegraphics[width=.9\textwidth]{img/6_SKEWEDCONSTWIDTH_plot.png}
\end{subfigure}%
\begin{subfigure}{.2\textwidth}
  \centering
  \begin{minipage}{1\textwidth}
\textbf{Widths:}
\\
min: 7
\\
max: 507
\\
mean: 254.24
\\
variance: 21164.27
\\
std: 145.48
\\
skewness: 0.02
\\
kurtosis: $-1.21$
\\\\
\textbf{Heights:}
\\
min: 13
\\
max: 1201
\\
mean: 194.23
\\
variance: 17615.88
\\
std: 132.72
\\
skewness: 2.41
\\
kurtosis: 14.05
  \end{minipage}
\end{subfigure}
% \caption{Data distribution for 6\_Skewedconstwidth.in with 1\% total skewed options}
% \source{Compiled by the authors}
\end{figure}


\documentclass{article}

\usepackage{graphicx}
\usepackage{hyperref}
\usepackage{tikz}
\usepackage{float}
\usepackage{pgfplots}
\usepackage{cleveref}
\usepackage[toc,page]{appendix}
\usepackage{amsmath}

\author{Pintilie Andrei, Tabarcea Augustus}
\title{Clinical Brain Computer Interfaces}

\begin{document}
\maketitle

\section{Introduction}
\subsection{Motivation}

\section{Method}

\subsection{1D Convolutional}

As we saw in\cite{Deep_series} a very successful approach to time series is to use a \textit{Convolutional neural network}\cite{Convolutional_neural_network}.
We used a popular architecture\autoref{Conv1D_Arhitecture} to create a goal for our NeuroEvolution algorithms.

\subsection{NEAT}

Following the paper\cite{NEAT} we applied topological evolution of the artificial neural network used.
NEAT recommendation is to start with a small network and evolve from there, so we started with just the input and output layers.
The mutation is made by changing a property (connections,weights,bias) of a chosen node to mutate.
NEAT handles crossover this by keeping track of the origins of the nodes, with an identifying number (new, higher numbers are generated for each additional node).
Those derived from a common ancestor (that are homologous) are matched up for crossover, and connections are matched if the nodes they connect have common ancestry.
The probabilities for mutation and crossover are underlying properties of the package that we use, but they let us choose the probability for a change in the network as follows:
\begin{itemize}
  \item A node can either be disable,deleted or enabled,added.
In our case this probability is $\mathcal{P}(N_+)=0.2$ and a $\mathcal{P}(N_-)=0.2, $ where $N_+=\text{adding a new node}$ and $N_-=\text{removing a node}$.
  \item A node can either gain a new connection or lose it.
In this case we use $\mathcal{P}(C_+)=0.5$ and a $\mathcal{P}(C_-)=0.4, $ where $C_+=\text{adding a new connection}$ and $C_-=\text{removing a connection}$.
  \item A node can modify its weights.
We use for that a $\mathcal{P}(W_C)=0.8$ and a $\mathcal{P}(W_R)=0.1, $
where $W_C=\textrm{change the weight by adding or subtracting}\\ \textrm{with value from a gaussian distribution centered on 0 }$\\
and $W_R=\text{replacing the weight value}$.
\end{itemize}

\section{Experiment}

\section{Results}

\subsection{Interpretation}

\section{Conclusions}

\begin{appendices}

\begin{figure}[!ht]
  \centering
  \includegraphics[width=\textwidth,height=\textheight,keepaspectratio]{model}
  \caption{Conv1D Arhitecture.}
  \label{Conv1D_Arhitecture}
\end{figure}

\end{appendices}

\begin{thebibliography}{9}
\bibliographystyle{plain}

\bibitem{Deep_series}
  Deep learning for time series classification by Hassan Ismail Fawaz, Germain Forestier,Jonathan Weber, Lhassane Idoumghar, Pierre-Alain Muller [2019]
  \url{https://arxiv.org/pdf/1809.04356.pdf}

\bibitem{Convolutional_neural_network}
  1D Convolutional Neural Networks and Applications by Serkan Kiranyaz, Onur Avci, Osama Abdeljaber, Turker Ince, Moncef Gabbouj, Daniel J. Inman [2019]
  \url{https://arxiv.org/ftp/arxiv/papers/1905/1905.03554.pdf}

\bibitem{NEAT}
  Efficient Reinforcement Learning through Evolving Neural Network Topologies by Kenneth O. Stanley and Risto Miikkulainen [2002]
  \url{http://nn.cs.utexas.edu/downloads/papers/stanley.gecco02_1.pdf}

\end{thebibliography}
\end{document}


%
% API Documentation for QSTK
% Module QSTK.qstkstrat.strategies
%
% Generated by epydoc 3.0.1
% [Mon Mar  5 00:49:20 2012]
%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%                          Module Description                           %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    \index{QSTK \textit{(package)}!QSTK.qstkstrat \textit{(package)}!QSTK.qstkstrat.strategies \textit{(module)}|(}
\section{Module QSTK.qstkstrat.strategies}

    \label{QSTK:qstkstrat:strategies}
Created on Sep 27, 2011

\textbf{Author:} John Cornwell

\textbf{Contact:} JohnWCornwellV@gmail.com

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%                               Functions                               %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

  \subsection{Functions}

    \label{QSTK:qstkstrat:strategies:stratGiven}
    \index{QSTK \textit{(package)}!QSTK.qstkstrat \textit{(package)}!QSTK.qstkstrat.strategies \textit{(module)}!QSTK.qstkstrat.strategies.stratGiven \textit{(function)}}

    \vspace{0.5ex}

\hspace{.8\funcindent}\begin{boxedminipage}{\funcwidth}

    \raggedright \textbf{stratGiven}(\textit{dtStart}, \textit{dtEnd}, \textit{dFuncArgs})

    \vspace{-1.5ex}

    \rule{\textwidth}{0.5\fboxrule}
\setlength{\parskip}{2ex}
    @summary Simplest strategy, weights are provided through args.

\setlength{\parskip}{1ex}
      \textbf{Parameters}
      \vspace{-1ex}

      \begin{quote}
        \begin{Ventry}{xxxxxxxxx}

          \item[dtStart]

          Start date for portfolio

          \item[dtEnd]

          End date for portfolio

          \item[dFuncArgs]

          Dict of function args passed to the function @return DataFrame
          corresponding to the portfolio allocations

        \end{Ventry}

      \end{quote}

    \end{boxedminipage}

    \label{QSTK:qstkstrat:strategies:strat1OverN}
    \index{QSTK \textit{(package)}!QSTK.qstkstrat \textit{(package)}!QSTK.qstkstrat.strategies \textit{(module)}!QSTK.qstkstrat.strategies.strat1OverN \textit{(function)}}

    \vspace{0.5ex}

\hspace{.8\funcindent}\begin{boxedminipage}{\funcwidth}

    \raggedright \textbf{strat1OverN}(\textit{dtStart}, \textit{dtEnd}, \textit{dFuncArgs})

    \vspace{-1.5ex}

    \rule{\textwidth}{0.5\fboxrule}
\setlength{\parskip}{2ex}
    @summary Evenly distributed strategy.

\setlength{\parskip}{1ex}
      \textbf{Parameters}
      \vspace{-1ex}

      \begin{quote}
        \begin{Ventry}{xxxxxxxxx}

          \item[dtStart]

          Start date for portfolio

          \item[dtEnd]

          End date for portfolio

          \item[dFuncArgs]

          Dict of function args passed to the function @return DataFrame
          corresponding to the portfolio allocations

        \end{Ventry}

      \end{quote}

    \end{boxedminipage}

    \label{QSTK:qstkstrat:strategies:stratMark}
    \index{QSTK \textit{(package)}!QSTK.qstkstrat \textit{(package)}!QSTK.qstkstrat.strategies \textit{(module)}!QSTK.qstkstrat.strategies.stratMark \textit{(function)}}

    \vspace{0.5ex}

\hspace{.8\funcindent}\begin{boxedminipage}{\funcwidth}

    \raggedright \textbf{stratMark}(\textit{dtStart}, \textit{dtEnd}, \textit{dFuncArgs})

    \vspace{-1.5ex}

    \rule{\textwidth}{0.5\fboxrule}
\setlength{\parskip}{2ex}
    @summary Markovitz strategy, generates a curve and then chooses a point
    on it.

\setlength{\parskip}{1ex}
      \textbf{Parameters}
      \vspace{-1ex}

      \begin{quote}
        \begin{Ventry}{xxxxxxxxx}

          \item[dtStart]

          Start date for portfolio

          \item[dtEnd]

          End date for portfolio

          \item[dFuncArgs]

          Dict of function args passed to the function @return DataFrame
          corresponding to the portfolio allocations

        \end{Ventry}

      \end{quote}

    \end{boxedminipage}

    \label{QSTK:qstkstrat:strategies:stratMarkSharpe}
    \index{QSTK \textit{(package)}!QSTK.qstkstrat \textit{(package)}!QSTK.qstkstrat.strategies \textit{(module)}!QSTK.qstkstrat.strategies.stratMarkSharpe \textit{(function)}}

    \vspace{0.5ex}

\hspace{.8\funcindent}\begin{boxedminipage}{\funcwidth}

    \raggedright \textbf{stratMarkSharpe}(\textit{dtStart}, \textit{dtEnd}, \textit{dFuncArgs})

    \vspace{-1.5ex}

    \rule{\textwidth}{0.5\fboxrule}
\setlength{\parskip}{2ex}
    @summary Calls stratMark with sharpe ratio point.

\setlength{\parskip}{1ex}
      \textbf{Parameters}
      \vspace{-1ex}

      \begin{quote}
        \begin{Ventry}{xxxxxxxxx}

          \item[dtStart]

          Start date for portfolio

          \item[dtEnd]

          End date for portfolio

          \item[dFuncArgs]

          Dict of function args passed to the function @return DataFrame
          corresponding to the portfolio allocations

        \end{Ventry}

      \end{quote}

    \end{boxedminipage}

    \label{QSTK:qstkstrat:strategies:stratMarkLowVar}
    \index{QSTK \textit{(package)}!QSTK.qstkstrat \textit{(package)}!QSTK.qstkstrat.strategies \textit{(module)}!QSTK.qstkstrat.strategies.stratMarkLowVar \textit{(function)}}

    \vspace{0.5ex}

\hspace{.8\funcindent}\begin{boxedminipage}{\funcwidth}

    \raggedright \textbf{stratMarkLowVar}(\textit{dtStart}, \textit{dtEnd}, \textit{dFuncArgs})

    \vspace{-1.5ex}

    \rule{\textwidth}{0.5\fboxrule}
\setlength{\parskip}{2ex}
    @summary Calls stratMark and uses lowest variance ratio point.

\setlength{\parskip}{1ex}
      \textbf{Parameters}
      \vspace{-1ex}

      \begin{quote}
        \begin{Ventry}{xxxxxxxxx}

          \item[dtStart]

          Start date for portfolio

          \item[dtEnd]

          End date for portfolio

          \item[dFuncArgs]

          Dict of function args passed to the function @return DataFrame
          corresponding to the portfolio allocations

        \end{Ventry}

      \end{quote}

    \end{boxedminipage}

    \label{QSTK:qstkstrat:strategies:stratMarkMaxRet}
    \index{QSTK \textit{(package)}!QSTK.qstkstrat \textit{(package)}!QSTK.qstkstrat.strategies \textit{(module)}!QSTK.qstkstrat.strategies.stratMarkMaxRet \textit{(function)}}

    \vspace{0.5ex}

\hspace{.8\funcindent}\begin{boxedminipage}{\funcwidth}

    \raggedright \textbf{stratMarkMaxRet}(\textit{dtStart}, \textit{dtEnd}, \textit{dFuncArgs})

    \vspace{-1.5ex}

    \rule{\textwidth}{0.5\fboxrule}
\setlength{\parskip}{2ex}
    @summary Calls stratMark and uses maximum returns.

\setlength{\parskip}{1ex}
      \textbf{Parameters}
      \vspace{-1ex}

      \begin{quote}
        \begin{Ventry}{xxxxxxxxx}

          \item[dtStart]

          Start date for portfolio

          \item[dtEnd]

          End date for portfolio

          \item[dFuncArgs]

          Dict of function args passed to the function @return DataFrame
          corresponding to the portfolio allocations

        \end{Ventry}

      \end{quote}

    \end{boxedminipage}

    \label{QSTK:qstkstrat:strategies:stratMarkMinRet}
    \index{QSTK \textit{(package)}!QSTK.qstkstrat \textit{(package)}!QSTK.qstkstrat.strategies \textit{(module)}!QSTK.qstkstrat.strategies.stratMarkMinRet \textit{(function)}}

    \vspace{0.5ex}

\hspace{.8\funcindent}\begin{boxedminipage}{\funcwidth}

    \raggedright \textbf{stratMarkMinRet}(\textit{dtStart}, \textit{dtEnd}, \textit{dFuncArgs})

    \vspace{-1.5ex}

    \rule{\textwidth}{0.5\fboxrule}
\setlength{\parskip}{2ex}
    @summary Calls stratMark and uses minimum returns.

\setlength{\parskip}{1ex}
      \textbf{Parameters}
      \vspace{-1ex}

      \begin{quote}
        \begin{Ventry}{xxxxxxxxx}

          \item[dtStart]

          Start date for portfolio

          \item[dtEnd]

          End date for portfolio

          \item[dFuncArgs]

          Dict of function args passed to the function @return DataFrame
          corresponding to the portfolio allocations

        \end{Ventry}

      \end{quote}

    \end{boxedminipage}

    \label{QSTK:qstkstrat:strategies:stratMarkSharpeAlpha}
    \index{QSTK \textit{(package)}!QSTK.qstkstrat \textit{(package)}!QSTK.qstkstrat.strategies \textit{(module)}!QSTK.qstkstrat.strategies.stratMarkSharpeAlpha \textit{(function)}}

    \vspace{0.5ex}

\hspace{.8\funcindent}\begin{boxedminipage}{\funcwidth}

    \raggedright \textbf{stratMarkSharpeAlpha}(\textit{dtStart}, \textit{dtEnd}, \textit{dFuncArgs})

    \vspace{-1.5ex}

    \rule{\textwidth}{0.5\fboxrule}
\setlength{\parskip}{2ex}
    @summary Calls stratMark and chooses the highest share point, uses
    future knowlege (alpha).

\setlength{\parskip}{1ex}
      \textbf{Parameters}
      \vspace{-1ex}

      \begin{quote}
        \begin{Ventry}{xxxxxxxxx}

          \item[dtStart]

          Start date for portfolio

          \item[dtEnd]

          End date for portfolio

          \item[dFuncArgs]

          Dict of function args passed to the function @return DataFrame
          corresponding to the portfolio allocations

        \end{Ventry}

      \end{quote}

    \end{boxedminipage}

    \label{QSTK:qstkstrat:strategies:stratMarkMaxRetAlpha}
    \index{QSTK \textit{(package)}!QSTK.qstkstrat \textit{(package)}!QSTK.qstkstrat.strategies \textit{(module)}!QSTK.qstkstrat.strategies.stratMarkMaxRetAlpha \textit{(function)}}

    \vspace{0.5ex}

\hspace{.8\funcindent}\begin{boxedminipage}{\funcwidth}

    \raggedright \textbf{stratMarkMaxRetAlpha}(\textit{dtStart}, \textit{dtEnd}, \textit{dFuncArgs})

    \vspace{-1.5ex}

    \rule{\textwidth}{0.5\fboxrule}
\setlength{\parskip}{2ex}
    @summary Calls stratMark chooses the highest returns point, uses future
    knowlege (alpha).

\setlength{\parskip}{1ex}
      \textbf{Parameters}
      \vspace{-1ex}

      \begin{quote}
        \begin{Ventry}{xxxxxxxxx}

          \item[dtStart]

          Start date for portfolio

          \item[dtEnd]

          End date for portfolio

          \item[dFuncArgs]

          Dict of function args passed to the function @return DataFrame
          corresponding to the portfolio allocations

        \end{Ventry}

      \end{quote}

    \end{boxedminipage}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%                               Variables                               %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

  \subsection{Variables}

    \vspace{-1cm}
\hspace{\varindent}\begin{longtable}{|p{\varnamewidth}|p{\vardescrwidth}|l}
\cline{1-2}
\cline{1-2} \centering \textbf{Name} & \centering \textbf{Description}& \\
\cline{1-2}
\endhead\cline{1-2}\multicolumn{3}{r}{\small\textit{continued on next page}}\\\endfoot\cline{1-2}
\endlastfoot\raggedright \_\-\_\-p\-a\-c\-k\-a\-g\-e\-\_\-\_\- & \raggedright \textbf{Value:}
{\tt \texttt{'}\texttt{QSTK.qstkstrat}\texttt{'}}&\\
\cline{1-2}
\end{longtable}

    \index{QSTK \textit{(package)}!QSTK.qstkstrat \textit{(package)}!QSTK.qstkstrat.strategies \textit{(module)}|)}


\documentclass[runningheads]{llncs}

\usepackage{graphicx}
\usepackage{placeins}
\usepackage{hyperref,xcolor}
\renewcommand\UrlFont{\color{blue}\rmfamily}
\usepackage{amsmath}

\begin{document}

\title{Alternatives for Neighborhood Function in Kohonen Maps \thanks{This work was supported by a private funding of Velbazhd Software LLC.}}
\titlerunning{Neighborhood in SOM}

\author{Iliyan Zankinski \and
Kolyu Kolev \and
Todor Balabanov\orcidID{0000-0003-3139-069X}}
\authorrunning{I. Zankinski et al.}

\institute{Institute of Information and Communication Technologies \\
Bulgarian Academy of Sciences \\
acad. Georgi Bonchev Str., Block 2, 1113 Sofia, Bulgaria \\
\email{iliyan@hsi.iccs.bas.bg} \\
\url{http://iict.bas.bg/}}

\maketitle

\begin{abstract}
In the field of the artificial intelligence artificial neural networks are one of the most researched topics. Multilayer perceptron has a reputation for the most used type of artificial neural network, but other types such as Kohonen maps, generalized nets\cite{tashev01} or combinations with Kalman filter\cite{alexandrov01,voort01} are also very interesting. Proposed by Teuvo Kohonen in the 1980s, self-organizing maps have application in meteorology, oceanography, project prioritization and selection, seismic facies analysis for oil and gas exploration, failure mode and effects analysis, creation of artwork and many other areas. Self-organizing maps are very useful for visualization by data dimensions reduction. Unsupervised competitive learning is used in self-organizing maps and the basic idea is the net to classify input data in predefined number of clusters. When the net has fewer nodes it achieve results similar to K-means clustering. One of the components in the self-organizing maps is the neighborhood function. It gives scaling factor for the distance between one neuron and other neurons in each step. The simplest form of a neighborhood function gives 1 for the closest nodes and 0 for all other, but the most used neighborhood function is a Gaussian function. In this research fading cosine and exponential regulated cosine functions are proposed as alternatives for neighborhood function.

\keywords{Artificial neural networks \and Self-organizing maps \and Neighborhood functions.}
\end{abstract}

\section{Introduction}

Self-organizing maps or Kohonen Neural Networks (KNNs) are networks with unsupervised training \cite{schreck01}. They are very useful in finding nonlinear dependencies when data are presented in very high dimensional spaces. The projection from the high-dimensional space is usually done in a rectangular lower-dimensional space \cite{macq01}. The main idea behind KNNs is the organization of unlabeled vectors with particular features in predefined number of groups called clusters \cite{cottrell01}. Grid of the self-organizing map is a handy tool for convenient visualization which can reveal different features of the network. SOMs are attractive when they consist of two or more separate regions. The real goal is not to find a perfect clustering but get good idea of the cluster structure.

\subsection{Clustering}

Clustering means a separation of the data set in set of groups. In separation where each data sample belongs exactly to only one group it is called straight clustering. If each data sample has varying degree of membership to different groups it is called fuzzy clustering.

Generally accepted concept of an optimal clustering is data set separation which minimizes the distance inside the cluster and maximizes the distance between the clusters. The most used form of distance measurement is the Euclidean norm \cite{lozano01}.

\subsection{SOM Training}

The network consists of a grid (usually two dimensional \cite{wehrens01}) with units. The units are connected to adjacent units with a neighborhood relation. The amount of grid units, which usually varies from a few dozen up to several thousand, gives the accuracy and generalization possibilities of the KNN. The network forms an elastic mesh that folds as a cloud formed by the input data during training phase. Data samples lying near each other in the input space are mapped into nearby grid units.

The network training is done iteratively. A data sample vector is randomly chosen from the input data set, as first step. As second step, distances between the selected vector and all the prototype vectors are computed. The best matching unit is the grid unit with prototype closest the selected vector. In the third step, the prototype vectors in the grid are updated. The best matching unit and its topological neighbors are moved closer to the input vector in the input space \cite{vesanto01,аmerijckx01}.

\section{Neighborhood Function}

The most used KNN's neighborhood function is the Gaussian function. In this research two alternative functions are proposed. The first function is fading cosine, which is shown in Fig.\ref{fig01}-Left. The second function is exponential regulated cosine, which is shown in FIg.\ref{fig01}-Right.

\begin{figure}
\includegraphics[width=1.0\textwidth]{fig01.png}
\centering
\caption{Left - Fading cosine neighborhood function. Right - Exponential regulated cosine neighborhood function.} \label{fig01}
\end{figure}
\FloatBarrier

The idea for the both functions is to stress grid nodes down and up. The exponential regulated cosine Eq.\ref{equ02} gives smoother stress than the fading cosine Eq.\ref{equ01}.

\begin{equation} \label{equ01}
f(x) =
	\begin{cases}
		cos(x) & -\pi/2 < x < \pi/2 \\
		\frac{cos(x)}{|x|} & +\pi/2 \geq x \leq -\pi/2 \\
	\end{cases}
\end{equation}

\begin{equation} \label{equ02}
f(x) = \frac{cos(x)}{e^{|x|}}
\end{equation}

\section{Experiments and Results}

All experiments were done on a single processor desktop machine - Intel Core i5, 2.3 GHz, 2 Cores, 8GB RAM and Mac OS X 10.13.6, Apple LLVM version 9.1.0.

\begin{figure}
\includegraphics[width=1.0\textwidth]{fig03.png}
\centering
\caption{Rents and living area data set \cite{garriga01}.} \label{fig03}
\end{figure}
\FloatBarrier

As experimental data set rents and living area (shown in Fig.\ref{fig03}) are taken from the open source project, which can be found at \cite{garriga01}.

Experiments are done with Gausssian neighborhood function Fig.\ref{fig02}-Left, fading cosine neighborhood function Fig.\ref{fig02}-Center and exponential regulated cosine neighborhood function Fig.\ref{fig02}-Right. Results show that fading cosine function performs less effective than exponential regulated cosine, but exponential regulated cosine gives sharper clusters separation than the Gaussian function. All three functions give clear clusterization. Data are separated in four common groups as it is shown on middle row of Fig. \ref{fig02}.

\begin{figure}
\includegraphics[width=1.0\textwidth]{fig02.png}
\centering
\caption{Left - Gausssian neighborhood function. Center - Fading cosine neighborhood function. Right - Exponential regulated cosine neighborhood function.} \label{fig02}
\end{figure}
\FloatBarrier

\section{Conclusions}

The proposed neighbor functions give promising results as it is shown in the experimental section. Stressing the neighboring nodes down and up leads to better separation between the formed clusters. As further research it will be interesting the proposed neighborhood functions to be combined with different distance norms. In some problems Hausdorff distance can be used for example. Situations in time series \cite{atanasova01} are also interesting for classification with KNN and the capabilities of the soft computing \cite{angelova01}.

\begin{thebibliography}{8}

\bibitem{tashev01}
Tashev, T., Hristov, H.: Modeling of synthesis of information processes with generalized nets. Cybernetics and Information Technologies, \textbf{3}(2), 92--104 (2003)

\bibitem{alexandrov01}
Alexandrov, A.: AD HOC Kalman filter based fusion algorithm for real-time Wireless Sensor Data Integration. In: FQAS-2015 Proceedings, pp. 151--160. Springer, Heidelberg (2015)

\bibitem{voort01}
van der Voort, M., Dougherty, M.,Watson, S.: Combining kohonen maps with arima time series models to forecast traffic flow. Transportation Research Part C: Emerging Technologies, \textbf{4}(5), 307--318 (1996)

\bibitem{schreck01}
Schreck, T., Bernard, J., Landesberger, T. von, Kohlhammer, J.: Visual Cluster Analysis of Trajectory Data with Interactive Kohonen Maps. Information Visualization, \textbf{8}(1), 14--29 (2009)

\bibitem{macq01}
Macq, D., Verleysen, M., Jespers, P., Legat, J.D.: Analog implementation of a Kohonen map with on-chip learning. IEEE Transactions on Neural Networks, \textbf{4}(3), 456--461 (1993)

\bibitem{cottrell01}
Cottrell M., Letremy P., Roy E.: Analysing a contingency table with Kohonen maps: A factorial correspondence analysis. In: Mira J., Cabestany J., Prieto A. (eds) New Trends in Neural Computation. Lecture Notes in Computer Science, pp. 305--311. Springer, Heidelberg (1993)

\bibitem{lozano01}
Lozano, S., Guerrero, F., Onieva, L., Larraneta, J.: Kohonen maps for solving a class of location-allocation problems. European Journal of Operational Research, \textbf{108}(1), 106--117 (1998)

\bibitem{wehrens01}
Wehrens, R., Buydens, L.: Self- and Super-organizing Maps in R: The kohonen Package. Journal of statistical software, \textbf{21}(5), 1--19 (2007)

\bibitem{vesanto01}
Vesanto, J., Alhoniemi, E.: Clustering of the Self-Organizing Map. IEEE Transactions on Neural Networks, \textbf{11}(3), 586--600 (2000)

\bibitem{аmerijckx01}
Amerijckx, C., Verleysen, M., Thissen, P., Legat, J.D.: Image compression by self-organized Kohonen map. IEEE Transactions on Neural Networks, \textbf{9}(3), 503--507 (1998)

\bibitem{garriga01}
Complete C implementation of the Kohonen Neural Network (SOM algorithm), \url{http://github.com/Coding-Sunday-Sofia/Kohonen}. Last accessed 01 Mar 2019

\bibitem{atanasova01}
Atanasova T., Barova M.: Exploratory analysis of Time Series for hypothesize feature values. In: UniTech17 Proceedings,  \textbf{16}(2), 399--403 (2017)

\bibitem{angelova01}
Angelova, V.: Investigations in the Area of Soft Computing Targeted State of the Art Report. Cybernetics and Information Technologies \textbf{9}(1), 18--24 (2009)

\end{thebibliography}
\end{document}


\section{Methodology}
%Description of D3ploy
In \Cyclus, developers have the option to design
agents using C++ or Python.
The \deploy \texttt{Institution} agent was
implemented in Python to enable the use of
well-developed time series forecasting Python packages.

During a \Cyclus simulation, at every time step, \deploy
predicts the supply and demand of each commodity for the next time
step.
It is assumed that facility deployment occurs
within one time step (month).
Commodities refer to materials in the nuclear fuel cycle such as
reactor fuel.
Upon undersupply for any commodity,
\deploy deploys facilities to meet its predicted demand.
Therefore, if the simulation begins with user-defined power
demand, \deploy deploys reactors to meet power demand,
followed by enrichment facilities to meet fuel demand, and so on,
to create the supply chain.
Based on the demand and supply trends of each commodity,
\deploy predicts their
future demand and supply, and deploys facilities
accordingly to meet the future demand to prevent demand
from surpassing supply.
Figure \ref{fig:flow} shows the logical flow of \deploy
at every time step.
In subsequent subsections, we describe how to set up a
transition scenario using \deploy and the input parameters
\deploy accepts.

\begin{figure}[]
	\centering
	\resizebox{0.8\textwidth} {0.8\height}{
    \begin{tikzpicture}[node distance=2.5cm]
    \tikzstyle{every node}=[font=\large]
	\node (Start) [bblock] {\textbf{Start time step ($t$).}};
	\node (Predict) [bblock, below of=Start] {\textbf{Calculate predicted $D(t+1)$ and $S(t+1)$ for a commodity}};
	\node (IsThere) [oblock, below of=Predict]{\textbf{$U(t+1) = S(t+1)-D(t+1)$}};
	\node (Deploy) [bblock, below of=IsThere, xshift = -3.5cm]{\textbf{Deploy Facilities}};
    \node (NoDeploy) [bblock, right of=Deploy, xshift = 3.5cm]{\textbf{No Deployment} };
    \node (All) [oblock, below of=Deploy, xshift = 3.5cm] {\textbf{Has $D(t+1)$ and \\ $S(t+1)$ been calculated for all commodities?}};
    \node (End) [bblock, below of=All] {\textbf{Proceed to next time step.}};

	\draw [arrow] (Start) -- (Predict);
	\draw [arrow] (Predict) -- (IsThere);
    \draw [arrow] (IsThere) -- node[anchor=east] {$U(t+1) <$ buffer} (Deploy);
    \draw [arrow] (IsThere) -- node[anchor=west] {$U(t+1) \geq$ buffer} (NoDeploy);
    \draw [arrow] (Deploy) -- (All);
    \draw [arrow] (NoDeploy) -- (All);
    \draw [arrow] (All) -- node[anchor=west] {yes} (End);
    \draw [arrow] (All) -- ([shift={(-4cm,0.8cm)}]All.south west)-- node[anchor=east] {no} ([shift={(-4cm,-0.8cm)}]Predict.north west)--(Predict);
    \draw [arrow] (End) |-([shift={(3cm,-0.5cm)}]End.south east)-- ([shift={(3cm,0.5cm)}]Start.north east)-|(Start);
	\end{tikzpicture}
	}
    \caption{\deploy logic flow at every time step in \Cyclus \cite{chee_demonstration_2019}.}
    \label{fig:flow}
\end{figure}

\deploy aims to minimize the undersupply of power:
\begin{align}
	\label{eq:pow}
	\textrm{obj} &= \min \sum_{t=1}^{t_{f}} |D_{t,p}-S_{t,p}|.
    \intertext{where:}
    t_f &= \mbox{Number of time steps [months]} \nonumber \\
    t &= \mbox{time [month]} \nonumber \\
	D &= \mbox{Demand} \nonumber\\
	S &= \mbox{Supply} \nonumber\\
	p &= \mbox{power [MW]} \nonumber
\end{align}
The sub-objectives are to minimize the number of time
steps of undersupply or under-capacity of any
commodity:
\begin{align}
	\label{eq:sub1}
    obj &= min \sum_{c=1}^{M}\sum_{t=1}^{t_f} |D_{t,c}-S_{t,c}|, \\
    \intertext{and to minimize excessive oversupply of all commodities: }
    obj &= min \sum_{c=1}^{M}\sum_{t=1}^{t_f} |S_{t,c}-D_{t,c}|. \\
    \intertext{where:}
    c &= \mbox{commodity type} \nonumber \\
	M &= \mbox{Number of commmodities} \nonumber
\end{align}

Minimizing excessive oversupply
reflects reality, in which utilities ensure grid availability
by ensuring power plants are never short of fuel while
avoiding expensive storage of excess fuel.
Nuclear fuel cycle simulations often face power shortages
due to lack of viable fuel, despite having sufficient installed
reactor capacity.
Using \deploy to automate the deployment of supporting
facilities prevents this.

\subsection{Structure}
Front-end facilities
meet the demand for commodities they produce, whereas back-end
facilities meet supply for the commodities they demand.
Therefore, in \deploy two distinct institutions control
front-end and back-end fuel cycle facilities:
\texttt{DemandDrivenDeploymentInst} and
\texttt{SupplyDrivenDeploymentInst}, respectively.
For example, when a reactor facility
demands fuel, \texttt{DemandDriven-}

\noindent
\texttt{DeploymentInst}
deploys fuel fabrication facilities to create fuel
supply.
For back-end facilities, the reactor generates spent fuel, and
\texttt{SupplyDrivenDeploymentInst} deploys
used fuel storage facilities to create capacity to store the spent fuel.
Figure \ref{fig:insts} depicts a simple once-through fuel cycle
and the \texttt{Institution} type governing each
facility's deployment.

\begin{figure}[]
	\centering
	\resizebox{\textwidth}{!}{
	\trimbox{0cm -.5cm 0cm 0cm}{
\begin{tikzpicture}[node distance=2.7cm,auto,>=latex']
	\tikzstyle{every node}=[font=\scriptsize]
    \node [bbslock] (a) {\textbf{Mine}};
    \node [bbslock] (b) [right of=a] {\textbf{Enrichment \\ Facility}};
	\node [bbslock] (c) [right of=b] {\textbf{Reactor}};
	\node [obslock] (d) [right of=c] {\textbf{Cooling \\ Pool}};
	\node [obslock] (e) [right of=d] {\textbf{Repository}};
    \path[->] (a) edge node {\shortstack{Natl \\ U}} (b);
    \draw [arrow] (b) -- ([xshift=0.5cm,yshift=0.9cm]b.north west)-- node[anchor=south] {Demand for Natl U} ([shift={(0cm,0.9cm)}]a.north)--(a);
    \draw [arrow] (c) -- ([shift={(0.5cm,0.9cm)}]c.north west)-- node[anchor=south] {Demand for Fuel} ([shift={(0cm,0.9cm)}]b.north)--(b);
    \draw [arrow] (c) -- ([shift={(1.5cm,0.9cm)}]c.north west)-- node[anchor=south] {\shortstack{Demand for Cooling \\ Pool Capacity}} ([shift={(0cm,0.9cm)}]d.north)--(d);
	\draw [arrow] (d) -- ([shift={(1.5cm,0.9cm)}]d.north west)-- node[anchor=south] {\shortstack{Demand for \\ Repository Capacity}} ([shift={(0cm,0.9cm)}]e.north)--(e);
    \draw[->] (b) edge node {Fuel} (c) ;
	\draw[->] (c) edge node {\shortstack{Used \\ Fuel}} (d) ;
	\draw[->] (d) edge node {\shortstack{Cooled \\ Used \\ Fuel}} (e) ;
\end{tikzpicture}
	}}

\resizebox{0.5\textwidth}{!}{
    \fbox{\begin{tabular}{ll}
        \textcolor{illiniblue}{$\blacksquare$} & Deployed by \texttt{DemandDrivenDeploymentInst}\\
        \textcolor{illiniorange}{$\blacksquare$} & Deployed by \texttt{SupplyDrivenDeploymentInst}
		\end{tabular}}}
		\caption{Simple once-through fuel cycle depicting which facilities are deployed by
		\texttt{DemandDrivenDeploymentInst} and \texttt{SupplyDrivenDeploymentInst}.}
\label{fig:insts}
\end{figure}

\subsubsection{Deployment-Driving Method}
\label{sec:ddm}
To prevent over-deployment of facilities with an intermittent
supply such as reactors that require refueling, and
to prevent infinite deployment of a facility that demands
a commodity no longer available in the simulation,
we introduced the capability to deploy facilities
based on the difference between predicted demand and installed capacity.
The user may deploy facilities based on the difference
between predicted demand and predicted supply, \textit{or}
predicted demand and installed capacity.
For example, a reprocessing plant that fabricates Sodium-Cooled Fast Reactor
(SFR) fuel demands for Pu after depletion of the existing Pu inventory and
decommissioning of the \glspl{LWR} that produce it.
If we used the deployment-driving method driven by
the difference in predicted demand and predicted supply, this results in
infinite deployment of reprocessing facilities in a futile attempt
to produce SFR fuel, crashing the simulation.
Instead, if we use the deployment-driving method driven by the
difference in predicted demand and installed capacity, only one reprocessing
facility will be deployed, the simulation will finish, and the user will see that
a large Pu inventory must be accumulated.
Therefore, using the deployment-driving method that deploys facilities based on
the difference between predicted demand and installed capacity is ideal for most
transition scenarios.

\subsection{Input Variables}
Table \ref{tab:inputs} lists and gives examples of the input
variables \deploy accepts.
The user must define the following input variables:
\begin{enumerate}
\item \textbf{The available facilities for \deploy to deploy in the simulation and their respective capacities.}
Users must define the facilities they want \deploy to deploy. It is the user's responsibility to
ensure the defined facilities create a supply chain to produce the demand driving commodity.
\item \textbf{The demand driving commodity and its demand equation.} For most simulations, the demand driving
commodity is power. The demand equation is defined by a mathematical equation with units of MW. For example,
a constant power demand equation is $10000$, while a linearly increasing power demand equation is $100t$.
\item \textbf{The deployment driving method}. This input variable is described in Section \ref{sec:ddm}.
\item \textbf{The prediction method}. This input variable is described in Section \ref{sec:pm}.
There are also optional input variables:
\item \textbf{Supply/capacity buffers for individual commodities.} This input variable is described in
section \ref{sec:buf}.
\item \textbf{Facility preferences.} This input variable is described in section \ref{sec:pref}.
\item \textbf{Facility fleet shares.} This input variable is described in section \ref{sec:pref}.
\end{enumerate}

\begin{table}[]
	\centering
    \caption{\deploy's required and optional input parameters with examples.}
    \label{tab:inputs}
        \begin{tabular}{l|ll}
        \hline
            & \textbf{Input Parameter}                                                           & \textbf{Examples}                                                                                \\ \hline
            \multirow{5}{*}{\textbf{Required}} & Demand driving commodity                                                           & Power                                                                                \\ \cline{2-3}
                                                      & Demand equation [MW]                                                                   & P(t) = $10000, sin(t), 10000t$                                                                                \\ \cline{2-3}
                                                      & Available Facilities                                                             & Mine, \gls{LWR}, Repository, etc.                                                                                \\ \cline{2-3}
                                                      & Capacities of the facilities                                                       & 3000 kg, 1000 MW, 50000 kg                                                                                \\ \cline{2-3}
                                                      & Prediction method                                                                  & \begin{tabular}[c]{@{}l@{}}Power: Fast Fourier Transform\\ Fuel: Moving Average\\ Spent fuel: Moving Average\end{tabular} \\ \cline{2-3}
                                                      & Deployment driven by & Installed Capacity                                                                                \\ \hline
            \multirow{4}{*}{\textbf{Optional}} & Supply/Capacity Buffer type                                                                        & Absolute                                                                                \\ \cline{2-3}
                                                      & Supply/Capacity Buffer size                                                                        & \begin{tabular}[c]{@{}l@{}}Power: 3000 MW\\ Fuel: 0 kg \\ Spent fuel: 0 kg\end{tabular}                                   \\ \cline{2-3}
                                                      & Facility preferences [month]                                                              & \begin{tabular}[c]{@{}l@{}}\gls{LWR} = 100-t\\ SFR = t-99 \end{tabular}          \\ \cline{2-3}
                                                      & Fleet share percentage [\%]                                                            & \begin{tabular}[c]{@{}l@{}}MOX \gls{LWR} = 85\%\\ SFR = 15\% \end{tabular}          \\ \hline
                    \end{tabular}
\end{table}
\subsubsection{Supply/Capacity Buffer}
\label{sec:buf}
The user has the option to specify a
supply buffer for each commodity; \deploy accounts for the buffer when
calculating predicted demand and deploys facilities accordingly.
The buffer is defined as a percentage:
\begin{align}
	S_{pwb} &= S_{p}(1+d)
\intertext{or an absolute value:}
    S_{pwb} &= S_{p}+b
\end{align}
    \begin{align}
	\intertext{where:}
	S_{pwb} &= \mbox{predicted supply/capacity with buffer} \nonumber\\
	S_p &= \mbox{predicted supply/capacity} \nonumber\\
	d &= \mbox{buffer's percentage value in decimal form} \nonumber\\
	b &= \mbox{buffer's absolute value} \nonumber
\end{align}

Using the buffer capability and
installed capacity to drive facility deployment in a transition
scenario simulation will effectively minimize undersupply of a
commodity while avoiding excessive oversupply.
This is demonstrated in Section \ref{sec:demo}.

\subsection{Facility Preference and Fleet Share}
\label{sec:pref}
The user can define time-dependent preference equations to facilities'
that supply the same commodity.
If there are two reactor types, \glspl{LWR} and \glspl{SFR}, in a simulation,
the user can make use of time-dependent
preferences to make the simulation deploy \glspl{LWR} at earlier times
in the simulation, and deploy SFRs at later times in the
simulation when there is a power demand.
In Table \ref{tab:inputs},
the user defined that the \gls{LWR} has a preference of $100-t$, while
the SFR has a preference of $t-99$.
Figure \ref{fig:prefplot} depicts how the preference for each reactor changes
with time.
When there is a power undersupply, \deploy will deploy the reactor that has a
larger preference at that time step.
At time step 100, \gls{LWR} preference is 0, while SFR preference is 1;
therefore an SFR is deployed if there is a power shortage.
Thus, the transition occurs at the $100^{th}$ time step.

\begin{figure}[]
	\begin{center}
		\includegraphics[width=\linewidth]{./figures/prefplot}
	\end{center}
		\caption{\deploy has a $100-t$ preference for \glspl{LWR} and a $t-99$ preference for SFRs.
		When there is a power undersupply, \deploy will deploy the reactor that has a
		larger preference at that time step.}
	\label{fig:prefplot}
\end{figure}

The user also has the option to specify percentage-share for facilities
that provide the same commodity.
For example, if there are two reactor types, \gls{MOX} \glspl{LWR} and SFRs, in a simulation,
the user can make use of percentage-share specifications to determine the
percentage of power supplied by each reactor.
When MOX \gls{LWR} has a share of $s\%$ and
\gls{SFR} has a share of $(100-s)\%$,
MOX \gls{LWR} deployment constrains to $s\%$ of total power demand
and SFR deployment constrains to $(100-s)\%$ of total power demand.

The transition year is selected by customizing facility
preferences to prefer advanced reactors at that year.
The fleet-share percentage determines the
share of each type of reactor to transition to.
Figure \ref{fig:deployflow} shows the logical flow of
which facility \deploy deploys when there are multiple facilities
offering the same commodity.

\begin{figure}[]
	\centering
	\resizebox{0.9\textwidth} {0.8\height}{
    \begin{tikzpicture}[node distance=3cm]
    \tikzstyle{every node}=[font=\large]
    \node (fs)[olblock]{\textbf{Are there fleet share constraints?}};
    \node (fsyes) [bbmlock, below of=fs, xshift = -3.5cm] {\textbf{Deploy facilities to meet fleet share $\%$}};
    \node (pref) [olblock, right of=fsyes, xshift = 3.5cm]{\textbf{Are there facility \\ preferences?}};
    \node (prefyes) [bbmmlock, below of=pref, xshift = -3cm] {\textbf{Deploy facilities in preference order to meet their fleet share \%}};
    \node (prefno) [bbmlock, right of=prefyes, xshift = 3cm, yshift=-0.05cm] {\textbf{Deploy facilities to minimize total no. of facilities and minimize oversupply.}};
	\draw [arrow] (fs) -- node[anchor=east] {yes} (fsyes);
    \draw [arrow] (fs) -- node[anchor=east] {no} (pref);
    \draw [arrow] (pref) -- node[anchor=east] {yes} (prefyes);
    \draw [arrow] (pref) -- node[anchor=east] {no} (prefno);
	\end{tikzpicture}}

    \caption{Logical flow of how \deploy
	selects which facility to deploy when there are multiple facilities
	offering the same commodity.}
	\label{fig:deployflow}
\end{figure}

\subsection{Prediction Methods}
\label{sec:pm}
\deploy records supply and demand at each time step for all
commodities. Time-series data informs \deploy's time series
forecasting methods which predict future supply and demand for each
commodity.
The time series forecasting methods investigated include non-optimizing,
deterministic-optimizing, and stochastic-optimizing methods.
Non-optimizing methods are techniques that harness
simple moving average and autoregression concepts which use
historical data to infer future supply and demand values.
Deterministic-optimizing and stochastic-optimizing
methods are techniques
that use an assortment of more sophisticated time series forecasting
concepts to predict future supply and demand values.
Deterministic-optimizing methods give deterministic solutions,
while stochastic-optimizing methods give stochastic solutions.

Depending on the scenario in question, each forecasting method
offers distinct benefits and disadvantages.
The various methods are compared for each type of simulation
to determine the most effective prediction method for
a given scenario.
The following sections describe the prediction methods.

\subsubsection{Non-Optimizing Methods}
Non-optimizing methods include: Moving Average (\texttt{MA}),
Autoregressive Moving Average (\texttt{ARMA}), and
Autoregressive Heteroskedasticity (\texttt{ARCH}).
The \texttt{MA} method calculates the average of
a user-defined number of previous entries in a commodity's
time series and returns it as the predicted value
(equation \ref{eq:ma}).

\begin{align}
	\label{eq:ma}
	PV &= \frac{\sum_{n=1}^N V_n}{n}
    \intertext{where:}
    PV &= \mbox{predicted value} \nonumber \\
	V_n &= \mbox{time series value} \nonumber\\
	N &= \mbox{length of time series} \nonumber
\end{align}

The \texttt{ARMA} method combines moving average and
autoregressive models (equation \ref{eq:arma}).
The first term is a constant, the second term is
white noise, the third term is the autoregressive
model, and the fourth term is the moving average
model.
The \texttt{ARMA} method is more accurate than the
\texttt{MA} method
because of the inclusion of the autoregressive term:
\begin{align}
	\label{eq:arma}
	X_t &= c + \epsilon_t +
	\sum_{i=1}^p\varphi_i X_{t-i} +
	\sum_{i=1}^q\theta_i\epsilon_{t-i}.
	\intertext{where:}
    c &= \mbox{a constant} \nonumber\\
    \epsilon_t &= \mbox{error terms (white noise)} \nonumber\\
    \varphi &= \mbox{the autoregressive model’s parameters} \nonumber\\
    \theta &= \mbox{the moving average model’s parameters} \nonumber \\
    p &= \mbox{order of the autoregressive polynomial} \nonumber \\
    q &= \mbox{order of the moving average polynomial} \nonumber
\end{align}

The \texttt{ARCH} method models time series data by describing the
variance of the current
error term as a function of the sizes of the previous time periods'
error terms \cite{engle_autoregressive_1982}.
This allows the method to support changes in the time dependent volatility,
such as increasing and decreasing volatility in the same series
\cite{engle_autoregressive_1982}.
The \texttt{ARCH} method is
better than the \texttt{ARMA} method for volatile
time-series data \cite{flanagan_methods_2019}.
The StatsModels \cite{seabold_statsmodels:_2010}
Python package is used to implement \texttt{ARMA} and
\texttt{ARCH} methods in \deploy.

\subsubsection{Deterministic-Optimizing Methods}
Deterministic methods include
Fast Fourier Transform (\texttt{FFT}),
Polynomial Fit (\texttt{POLY}),
Exponential Smoothing (\texttt{EXP-SMOOTHING}),
and Triple Exponential Smoothing (\texttt{HOLT-WINTERS}).
The \texttt{FFT} method uses the fast Fourier transform
algorithm to map a time series into the frequency domain.
The algorithm returns complex numbers from which frequency,
amplitude, and phase is extracted.
Future demand and supply values are predicted by summing
the significant components, then using the inverse
Fourier transform method to return it into a usable form.
The discrete Fourier transform (DFT) transforms a sequence of
N complex numbers ($X_k$) into another sequence of complex numbers
($x_n$) \cite{rao_fast_2011}:
\begin{align}
	\label{eq:fft}
	X_k &= \sum_{n=0}^{N-1}x_n e^{-i2\pi kn/N}.
    \intertext{where:}
    X &= \mbox{sequence of complex numbers} \nonumber \\
    k &= 0,...,N-1 \nonumber\\
    N &= \mbox{No. of complex numbers} \nonumber\\
    x &= \mbox{sequence of complex numbers} \nonumber \\
    n &= 0,...,N-1 \nonumber
\end{align}

\noindent
This method is implemented in \deploy using the
SciPy \cite{jones_scipy:_2016} Python package.

The \texttt{POLY} method fits the time series data
with a user-defined $n^{th}$ degree polynomial and uses
the fitted trend-line to determine future demand and
supply values:

\begin{align}
    Y_t &= \beta_0 + \sum_{n=1}^N \beta_n t^n + \varepsilon \\
    \intertext{where:}
    t &= \mbox{time index} \nonumber \\
    n &= \mbox{polynomial order} \nonumber \\
    \beta &= \mbox{fitted parameters} \nonumber \\
    \varepsilon &= \mbox{unobserved random error} \nonumber
\end{align}

\noindent
This method was implemented in \deploy using the
NumPy \cite{oliphant_guide_2006} Python package.

The \texttt{EXP-SMOOTHING} and \texttt{HOLT-WINTERS}
methods use a weighted average
of time-series data with exponentially decaying weights
for older time series values \cite{hyndman_forecasting:_2018}
to create a model to determine future demand and supply values.
The \texttt{EXP-SMOOTHING} method excels in
modeling univariate time series data without trend or seasonality
\cite{hyndman_forecasting:_2018}:

\begin{align}
    \label{eq:expsm}
    y_{t+1} &= \alpha y_i + (1-\alpha)y_t. \\
    \intertext{where:}
    y &= \mbox{timeseries value} \nonumber \\
    \alpha &= \mbox{smoothing factor } (0 < \alpha < 1) \nonumber
\end{align}

\noindent
The \texttt{HOLT-WINTERS} method applies triple exponential
smoothing, resulting in higher accuracy when
modeling seasonal time series data
\cite{sematech_engineering_2006}:

\begin{align}
    F_{t+m} &= (S_t +mb_t)I_{t-L+m} \\
    S_t &= \alpha \frac{y_t}{I_{t-L}}+(1-\alpha)(S_{t-1}+b_{t-1}) \nonumber \\
    b_t &= \gamma(S_t-S_{t-1})+)(1-\gamma)b_{t-1} \nonumber \\
    I_t &= \beta \frac{y_t}{S_t} + (1-\beta)I_{t-L} \nonumber \\
    \intertext{where:}
    F &= \mbox{forecast at m periods ahead} \nonumber \\
    t &= \mbox{time period index} \nonumber \\
    L &= \mbox{periods in a season} \nonumber \\
    S &= \mbox{smoothed observation} \nonumber \\
    y &= \mbox{the observation} \nonumber \\
    b &= \mbox{trend factor} \nonumber \\
    I &= \mbox{seasonal index} \nonumber \\
    \alpha, \beta, \gamma &= \mbox{constants} \nonumber
\end{align}

\noindent
The StatsModels \cite{seabold_statsmodels:_2010}
Python package was used to implement the \texttt{EXP-SMOOTHING}
and \texttt{HOLT-WINTERS} methods in \deploy.

\subsection{Stochastic-Optimizing Methods}
We implemented one stochastic-optimizing method: step-wise
seasonal method (\texttt{SW-SEASONAL}).
The method was implemented in \deploy by the \gls{ARIMA}
method in the pmdarima \cite{smith_pmdarima:_2017}
Python package.
The \gls{ARIMA} model is a dependent time series that is
modeled as a linear combination of its own past values
and past values of an error series \cite{institute_sas_1985}:

\begin{align}
    (1-B)^dY_t &= \mu + \frac{\theta(B)}{\phi(B)}a_t \\
    \intertext{where:}
    t &= \mbox{time index} \nonumber \\
    \mu &= \mbox{mean term} \nonumber \\
    B &= \mbox{backshift operator, such that } BX_t = X_{t-1} \nonumber \\
    d &= \mbox{no. of roots} \nonumber \\
    Y &= \mbox{timeseries data} \nonumber \\
    \phi(B) &= \mbox{autoregressive operator} \nonumber \\
    \theta(B) &= \mbox{moving average operator} \nonumber \\
    a_t &= \mbox{random error} \nonumber
\end{align}


\section{CurryVerify: A Tool to Support the Verification of Curry Programs}
\label{sec-curry2verify}

CurryVerify\index{CurryVerify}\index{verifying programs}\index{program!verification}
is a tool that supports the verification of Curry programs
with the help of other theorem provers or proof assistants.
Basically, CurryVerify extends CurryCheck (see Section~\ref{sec-currycheck}),
which tests given properties of a program,
by the possibility to verify these properties.
For this purpose, CurryVerify translates properties
into the input language of other theorem provers or proof assistants.
This is done by collecting all operations directly or indirectly
involved in a given property and translating them together with
the given property.

Currently, only Agda \cite{Norell09} is supported as
a target language for verification (but more target languages
may be supported in future releases).
The basic schemes to translate Curry programs into Agda programs
are presented in \cite{AntoyHanusLibby17EPTCS}.
That paper also describes the limitations of this approach.
Since Curry is a quite rich programming language,
not all constructs of Curry are currently supported
in the translation process (e.g., no case expressions,
local definitions, list comprehensions, do notations, etc).
Only a kernel language, where the involved rules
correspond to a term rewriting system, are translated into Agda.
However, these limitations might be relaxed in future releases.
Hence, the current tool should be considered as a first prototypical
approach to support the verification of Curry programs.

\subsection{Installation}

The current implementation of CurryVerify is a package
managed by the Curry Package Manager CPM
(see also Section~\ref{sec-cpm}).
Thus, to install the newest version of CurryVerify, use the following commands:
%
\begin{curry}
> cypm update
> cypm install verify
\end{curry}
%
This downloads the newest package, compiles it, and places
the executable \code{curry-verify} into the directory \code{\$HOME/.cpm/bin}.
Hence it is recommended to add this directory to your path
in order to execute CurryVerify as described below.

\subsection{Basic Usage}

To translate the properties of a Curry program stored
in the file \code{prog.curry} into Agda,
one can invoke the command\pindex{curry-verify}\pindex{verify}
%
\begin{curry}
curry-verify prog
\end{curry}
%
This generates for each property $p$ in module \code{prog}
an Agda program \ccode{TO-PROVE-$p$.agda}.
If one completes the proof obligation in this file,
the completed file should be renamed into
\ccode{PROOF-$p$.agda}.
This has the effect that CurryCheck does not test this property again
but trusts the proof and use this knowledge to simplify other tests.

As a concrete example, consider the following Curry module \code{Double},
shown in Figure~\ref{fig:double-curry},
which uses the Peano representation of natural numbers
(module \code{Nat}) to define an operation to double the value
of a number, a non-deterministic operation \code{coin}
which returns its argument or its incremented argument,
and a predicate to test whether a number is even.
Furthermore, it contains a property specifying that
doubling the coin of a number is always even.

\begin{figure}[t]
\begin{curry}

module Double(double,coin,even) where

import Nat
import Test.Prop

double x = add x x

coin x = x ? S x

even Z         = True
even (S Z)     = False
even (S (S n)) = even n

evendoublecoin x = always (even (double (coin x)))

\end{curry}
\caption{Curry program \code{Double.curry}\label{fig:double-curry}}
\end{figure}

In order to prove the correctness of this property,
we translate it into an Agda program by executing
%
\begin{curry}
> curry-verify Double
$\ldots$
Agda module 'TO-PROVE-evendoublecoin.agda' written.
If you completed the proof, rename it to 'PROOF-evendoublecoin.agda'.
\end{curry}
%
The Curry program is translated with
the default scheme (see further options below) based on
the ``planned choice'' scheme, described in \cite{AntoyHanusLibby17EPTCS}.
The result of this translation is shown in
Figure~\ref{fig:to-prove-evendoublecoin}.

\begin{figure}[t]
\begin{curry}
-- Agda program using the Iowa Agda library

open import bool

module TO-PROVE-evendoublecoin
  (Choice : Set)
  (choose : Choice $\to$ ${\mathbb B}$)
  (lchoice : Choice $\to$ Choice)
  (rchoice : Choice $\to$ Choice)
  where

open import eq
open import nat
open import list
open import maybe

---------------------------------------------------------------------------
-- Translated Curry operations:

add : ${\mathbb N}$ $\to$ ${\mathbb N}$ $\to$ ${\mathbb N}$
add zero x = x
add (suc y) z = suc (add y z)

coin : Choice $\to$ ${\mathbb N}$ $\to$ ${\mathbb N}$
coin c1 x = if choose c1 then x else suc x

double : ${\mathbb N}$ $\to$ ${\mathbb N}$
double x = add x x

even : ${\mathbb N}$ $\to$ ${\mathbb B}$
even zero = tt
even (suc zero) = ff
even (suc (suc x)) = even x

---------------------------------------------------------------------------

evendoublecoin : (c1 : Choice) $\to$ (x : ${\mathbb N}$) $\to$ (even (double (coin c1 x))) $\equiv$ tt
evendoublecoin c1 x = ?

\end{curry}
\caption{Agda program \code{TO-PROVE-evendoublecoin.agda}\label{fig:to-prove-evendoublecoin}}
\end{figure}

The Agda program contains all operations involved in the property
and the property itself.
Non-deterministic operations, like \code{coin}, have an additional
additional argument of the abstract type \code{Choice}
that represents the plan to execute some non-deterministic branch
of the program. By proving the property for all possible branches
as correct, it universally holds.

In our example, the proof is quite easy. First, we prove
that the addition of a number to itself is always even
(lemma \code{even-add-x-x}, which uses an auxiliary lemma
\code{add-suc}). Then, the property is an immediate consequence
of this lemma:
%
\begin{curry}
add-suc : $\forall$ (x y : ${\mathbb N}$) $\to$ add x (suc y) $\equiv$ suc (add x y)
add-suc zero    y = refl
add-suc (suc x) y rewrite add-suc x y = refl

even-add-x-x : $\forall$ (x : ${\mathbb N}$) $\to$ even (add x x) $\equiv$ tt
even-add-x-x zero    = refl
even-add-x-x (suc x) rewrite add-suc x x | even-add-x-x x = refl

evendoublecoin : (c1 : Choice) $\to$ (x : ${\mathbb N}$) $\to$ (even (double (coin c1 x))) $\equiv$ tt
evendoublecoin c1 x rewrite even-add-x-x (coin c1 x) = refl
\end{curry}
%
As the proof is complete, we rename this Agda program
into \code{PROOF-evendoublecoin.agda} so that the proof
can be used by further invocations of CurryCheck.

\subsection{Options}

The command \code{curry-verify} can be parameterized
with various options.
The available options can also be shown by executing
\begin{curry}
curry-verify --help
\end{curry}
The options are briefly described in the following.

\begin{description}
\item{\code{-h}, \code{-?}, \code{--help}}
These options trigger the output of usage information.

\item{\code{-q}, \code{--quiet}}
Run quietly and produce no informative output.
However, the exit code will be non-zero if some translation error occurs.

\item{\code{-v[$n$]}, \code{--verbosity[=$n$]}}
Set the verbosity level to an optional value.
The verbosity level \code{0} is the same as option \code{-q}.
The default verbosity level \code{1} shows the translation progress.
The verbosity level \code{2} (which is the same as omitting the level)
shows also the generated (Agda) program.
The verbosity level \code{3} shows also more details about
the translation process.

\item{\code{-n}, \code{--nostore}}
Do not store the translated program in a file but show it only.

\item{\code{-p $p$}, \code{--property=$p$}}
As a default, all properties occurring in the source program are
translated. If this option is provided, only property $p$ is translated.

\item{\code{-t $t$}, \code{--target=$t$}}
Define the target language of the translation.
Currently, only $t = \code{Agda}$ is supported, which is also the
default.

\item{\code{-s $s$}, \code{--scheme=$s$}}
Define the translation scheme used to represent Curry programs
in the target language.

For the target \code{Agda}, the following schemes are supported:
\begin{description}
\item[\code{choice}]
Use the ``planned choice'' scheme, see \cite{AntoyHanusLibby17EPTCS}
(this is the default).
In this scheme, the choices made in a non-deterministic computation
are abstracted by passing a parameter for these choices.
\item[\code{nondet}]
Use the ``set of values'' scheme, see \cite{AntoyHanusLibby17EPTCS},
where non-deterministic values are represented in a tree structure.
\end{description}

\end{description}

% LocalWords: CurryCheck