\section{Charge transfer rate}
\label{sec:rates}

Charge transfer rates\index{charge transfer rate} can be postulated based on intuitive physical considerations, as it is done in the Gaussian disorder models~\cite{walker_electrical_2002,baessler_charge_1993,borsenberger_charge_1991,pasveer_unified_2005}. Alternatively, charge transfer theories can be used to evaluate rates from quantum chemical calculations~\cite{bredas_molecular_2009,coropceanu_charge_2007,bredas_charge-transfer_2004,nelson_modeling_2009,baumeier_density-functional_2010,ruhle_microscopic_2011}. In spite of being significantly more computationally demanding, the latter approach allows to link the chemical and electronic structure, as well as the morphology, to charge dynamics.

\subsection{Classical charge transfer rate}
\label{sec:rate_classical}
\index{charge transfer rate!classical}

The high temperature limit of classical charge transfer  theory~\cite{marcus_electron_1993,hutchison_hopping_2005} is often used as a trade-off between theoretical rigor and computational complexity. It captures key parameters which influence charge transport while at the same time providing an analytical expression for the rate. Within this limit, the transfer rate for a charge to hop from a site $i$ to a site $j$ reads
%
\begin{equation}
\omega_{ij}  = \frac{2 \pi}{\hbar}  \frac{ J_{ij}^2 }{\sqrt{ 4 \pi \lambda_{ij} k_\text{B}T}} \exp \left[
-\frac{\left(\Delta E_{ij}-\lambda_{ij}\right)^2}{4 \lambda_{ij}
k_\text{B} T} \right],
\label{equ:marcus}
\end{equation}
%
where $T$ is the temperature, $\lambda_{ij} = \lambda_{ij}^\text{int} + \lambda_{ij}^\text{out}$ is the \slink{sec:reorganization}{reorganization energy}, which is a sum of intra- and inter-molecular (outersphere) contributions, $\Delta E_{ij}$ is the \slink{sec:site_energies}{site-energy difference}, or driving force, and $J_{ij}$ is the \slink{sec:transfer_integrals}{electronic coupling element}, or transfer integral.

\subsection{Semi-classical bimolecular rate}
\label{sec:rate_bimolecular}
\index{charge transfer rate!bimolecular}

\newcommand{\indM}{l}
\newcommand{\indN}{m}
\newcommand{\lb}[1]{\langle #1 |}
\newcommand{\rb}[1]{| #1 \rangle}
\newcommand{\rbt}[1]{ #1 \rangle}

The main assumptions in eq.~(\ref{equ:marcus}) are non-adiabaticity (small electronic coupling and  charge transfer between two diabatic, non-interacting states), and harmonic promoting modes, which are treated classically. At ambient conditions, however, the intramolecular promoting mode, which roughly corresponds to C-C bond stretching, has a vibrational energy of $\hbar\omega \approx 0.2\, \unit{eV} \gg k_\text{B}T$ and should be treated quantum-mechanically. The outer-sphere (slow) mode has much lower vibrational energy than the intramolecular promoting mode, and therefore can be treated classically. The weak interaction between molecules also implies that each molecule has its own, practically independent, set of quantum mechanical degrees of freedom.

A more general, quantum-classical expression for a bimolecular multi-channel rate is derived in the Supporting Information of ref.~\cite{ruhle_microscopic_2011} and has the following form

\begin{align}
 \omega_{ij}= \frac{2\pi}{\hbar}  \frac{|J_{ij}|^2}{\sqrt{4\pi \lambda_{ij}^\text{out} k_\text{B}T}}
 \sum_{\indM',\indN'=0}^\infty
 |\lb{\chi_{i0}^c}\rbt{\chi_{i\indM'}^n}|^2 |\lb{\chi_{j0}^n}\rbt{\chi_{j\indN'}^c}|^2
%\nonumber \\&&
\exp
\left\{ -\frac{ \left[ \Delta E_{ij}-\hbar(\indM'\omega_i^n+\indN'\omega_j^c) -\lambda_{ij}^\text{out} \right]^2}{4\lambda_{ij}^\text{out} k_\text{B}T}
\right\} .
\label{equ:jjortner}
\end{align}
If the curvatures of intramolecular PES of charged and neutral states of a molecule are different, that is $\omega_i^c\neq\omega_i^n$, the corresponding reorganization energies, $\lambda_i^{cn}=\frac{1}{2}[\omega_i^n(q_i^n-q_i^c)]^2$ and $\lambda_i^{nc}=\frac{1}{2}[\omega_i^c(q_i^n-q_i^c)]^2$, will also differ. In this case the Franck-Condon (FC) factors for discharging of molecule $i$ read \cite{chang_new_2005}
\begin{align}
%\begin{split}
%&
|\lb{\chi_{i0}^c}\rbt{\chi_{i\indM'}^n}|^2 =
\frac{2}{2^{l'}l'!} \frac{\sqrt{\omega_i^c\omega_i^n}}{(\omega_i^c+\omega_i^n)} \exp\left( -|s_i| \right)
%\nonumber \\
%& \times
 \left[ \sum_{\substack{k=0\\k\,\text{even}}}^{\indM'} {\indM' \choose k}
\left( \frac{2 \omega_i^c }{\omega_i^c+\omega_i^n}\right)^{k/2} \frac{k!}{(k/2)!}
H_{\indM'-k} \left( \frac{s_{i}}{\sqrt{2S^{cn}_i}}\right)
\right]^2
\, ,
%\end{split}
\end{align}
where $H_n(x)$ is a Hermite polynomial, $s_i=2\sqrt{\lambda_i^{nc}\lambda_i^{cn}} / \hbar(\omega_i^c+\omega_i^n)$, and $S^{cn}_i=\lambda_i^{cn}/\hbar\omega_i^c$. The FC factors for charging of molecule $j$ can be obtained by substituting $(s_i,S^{cn}_i,\omega_i^c)$ with $(-s_j,S^{nc}_j, \omega_j^n)$. In order to evaluate the FC factors, the \slink{sec:eintramolecular}{internal reorganization energy} $\lambda_i^{cn}$ can be computed from the intramolecular PES.

\subsection{Semi-classical rate}
\label{sec:rate_semiclassical}
\index{charge transfer rate!semiclassical}

One can also use the quantum-classical rate with a common set of vibrational coordinates~\cite{may_charge_2011}
\begin{align}
 \omega_{ij} = \frac{2\pi}{\hbar}  \frac{|J_{ij}|^2}{\sqrt{4\pi \lambda_{ij}^\text{out} k_\text{B}T}}
 \sum_{N=0}^\infty \frac{1}{N!} \left( \frac{\lambda_{ij}^\text{int}}{\hbar\omega^\text{int}} \right)^{N}
  \exp \left( - \frac{\lambda_{ij}^\text{int}}{\hbar\omega^\text{int}}\right)
%\nonumber\\&&
\exp
\left\{ -\frac{ \left[ \Delta E_{ij}-\hbar N\omega^\text{int} -\lambda_{ij}^\text{out} \right]^2}{4\lambda_{ij}^\text{out} k_\text{B}T}
\right\} .
\label{equ:jortner}
\end{align}

Numerical estimates show that if  $\lambda_{ij}^\text{int} \approx \lambda_{ij}^\text{out}$ and $|\Delta E_{ij}| \ll \lambda_{ij}^\text{out}$ the rates are similar to those of ~\equ{marcus}. In general, there is no robust method to compute $\lambda_{ij}^\text{out}$~\cite{hoffman_reorganization_1996} and  both reorganization energies are often assumed to be of the same order of magnitude. In this case the second condition also holds, unless there are large differences in electron affinities or ionization potentials of neighboring molecules, e.g. in donor-acceptor blends.
\vskip 0.4cm
To calculate rates of the type specified in \xmloptions for all pairs in the \slink{sec:neighborlist}{neighbor list} and to save them into the \sqlstate file, run the \calc{rates} \calculator. Note that all required ingredients (\slink{sec:reorganization}{reorganization energies}, \slink{sec:transfer_integrals}{transfer integrals}, and \slink{sec:site_energies}{site energies} have to be calculated before).
\votcacommand{Calculation of transfer rates}{\cmdrates}


\section{Programming Markov Chain with Jaql}

Our final Jaql script for generating a Markov Chain index can be seen in listing \ref{jaqlmrkv}. In line 42 the script will call the self function \lstinline[language=jaql]!$markov!, defined in line 19--25, on an array of strings. Each string represents a line from the input file. All lines will be replaced with the results of \lstinline[language=jaql]!$markovLine! in line 21, which are tuples with four words each. Then identical tuples will be aggregated into an SQL expression, containing the tuple itself and number of appearances.

During development we have created multiple version of this script. Unfortunatly, we were not able to run any version on our Hadoop cluster with more than one map task\footnote{read: with no more than 64 MB of input data}, therefore we did only run benchmarks for Pig and Java.


% This LaTeX was auto-generated from an M-file by MATLAB.
% To make changes, update the M-file and republish this document.

\subsection*{covSum.m}

\begin{par}
\textbf{Summary:} Compose a covariance function as the sum of other covariance functions. This function doesn't actually compute very much on its own, it merely does some bookkeeping, and calls other covariance functions to do the actual work.
\end{par} \vspace{1em}

\begin{verbatim}   function [A, B] = covSum(covfunc, logtheta, x, z)\end{verbatim}
    \begin{par}
(C) Copyright 2006 by Carl Edward Rasmussen, 2006-03-20.
\end{par} \vspace{1em}

\begin{lstlisting}
function [A, B] = covSum(covfunc, logtheta, x, z)
\end{lstlisting}

\subsection*{Code}

\begin{lstlisting}
for i = 1:length(covfunc)                   % iterate over covariance functions
  f = covfunc(i);
  if iscell(f{:}), f = f{:}; end          % dereference cell array if necessary
  j(i) = cellstr(feval(f{:}));
end

if nargin == 1,                                   % report number of parameters
  A = char(j(1)); for i=2:length(covfunc), A = [A, '+', char(j(i))]; end
  return
end

[n, D] = size(x);

v = [];              % v vector indicates to which covariance parameters belong
for i = 1:length(covfunc), v = [v repmat(i, 1, eval(char(j(i))))]; end

switch nargin
case 3                                              % compute covariance matrix
  A = zeros(n, n);                       % allocate space for covariance matrix
  for i = 1:length(covfunc)                  % iteration over summand functions
    f = covfunc(i);
    if iscell(f{:}), f = f{:}; end        % dereference cell array if necessary
    A = A + feval(f{:}, logtheta(v==i), x);            % accumulate covariances
  end

case 4                      % compute derivative matrix or test set covariances
  if nargout == 2                                % compute test set cavariances
    A = zeros(size(z,1),1); B = zeros(size(x,1),size(z,1));    % allocate space
    for i = 1:length(covfunc)
      f = covfunc(i);
      if iscell(f{:}), f = f{:}; end      % dereference cell array if necessary
      [AA BB] = feval(f{:}, logtheta(v==i), x, z);   % compute test covariances
      A = A + AA; B = B + BB;                                  % and accumulate
    end
  else                                            % compute derivative matrices
    i = v(z);                                       % which covariance function
    j = sum(v(1:z)==i);                    % which parameter in that covariance
    f = covfunc(i);
    if iscell(f{:}), f = f{:}; end        % dereference cell array if necessary
    A = feval(f{:}, logtheta(v==i), x, j);                 % compute derivative
  end

end
\end{lstlisting}


\chapter{The Python Language}{The Python Language}
\label{Lab:PythonBasic}

In this lab we will focus on the bas ic constructs of the Python programming language.  This will serve as a basic introduction in using the core language.  Understanding this lab will be essential to your success in the following labs.

\section*{What is Python}
Python is a very powerful interpreted language.

Python is an interpreted language.  The advantage of this is quick development time and fast debugging.  However, speed is traded for these benefits.  When Python code is executed, it is translated into bytecode and run on a virtual machine.

Let us look a small example of Newton's Method.  We wrote a very na\"ive implementation of Newton's Method.
\begin{lstlisting}[style=python]
def NewtonsMethod(f, df, x0, tol=1e-7):
    while abs(f(x0)) >= tol:
        x0 -= float(f(x0))/df(x0)
    return x0
\end{lstlisting}
When executing this, the python interpreter first translates it into Python bytecode which is then executed by a virtual machine.  Often, this bytecode is stored as a \li{.pyc} file in the same directory.  Python understands our Newton's Method function as (the numbers on the far left correspond to line numbers):
\begin{verbatim}
  2           0 SETUP_LOOP              60 (to 63)
        >>    3 LOAD_GLOBAL              0 (abs)
              6 LOAD_FAST                0 (f)
              9 LOAD_FAST                2 (x0)
             12 CALL_FUNCTION            1
             15 CALL_FUNCTION            1
             18 LOAD_FAST                3 (tol)
             21 COMPARE_OP               5 (>=)
             24 POP_JUMP_IF_FALSE       62

  3          27 LOAD_FAST                2 (x0)
             30 LOAD_GLOBAL              1 (float)
             33 LOAD_FAST                0 (f)
             36 LOAD_FAST                2 (x0)
             39 CALL_FUNCTION            1
             42 CALL_FUNCTION            1
             45 LOAD_FAST                1 (df)
             48 LOAD_FAST                2 (x0)
             51 CALL_FUNCTION            1
             54 BINARY_DIVIDE
             55 INPLACE_SUBTRACT
             56 STORE_FAST               2 (x0)
             59 JUMP_ABSOLUTE            3
        >>   62 POP_BLOCK

  4     >>   63 LOAD_FAST                2 (x0)
             66 RETURN_VALUE
\end{verbatim}

\section*{Why Python?}
\begin{itemize}
\item Python is a robust, versitile object-oriented language.  It aims toward code that is easily written and more easily read and maintained.  The language is manages its own memory and is scalable and portable.  Python programs can run on any platform on which a Python interpreter can run.  Programs written on Windows, will run on Linux and Mac OSX, with little or no changes.
\item Interactive development model that allow fast prototyping and development of algorithms.
\item Many mature and very efficient scientific computing libraries exist for Python.  Numpy and Scipy provide many of the fast algorithms available in MATLAB.  Matplotlib is a mature plotting library that is capable of producing a wide range of plots, graphs, and other visualizations.
\item Python has a large, active community.  It is used in many
\item Free
\end{itemize}

\section*{Resources for Learning Python}
There already exist many well written introductions to the Python language.  We recommend you review the following sources if you are learning Python for the first time.

%List of Python Resources
Scipy Lecture Notes
http://scipy-lectures.github.com/

Dive into Python
Version 2: http://www.diveintopython.net/toc/index.html
Version 3: http://getpython3.com/diveintopython3/

\section*{Effiencent Workflows}
An efficient workflow is absolutely essential in scientific computing.  Few people wish to hindered by the tools they use.  In this section, we will propose a couple of workflows that have proven to work well.

\subsection*{Text editor + Python Interpreter/IPython}
This is the most basic workflow to use.  It involves using your favorite text editor to edit source files and then executing those scripts in your command terminal.  Some popular editors for python source code include
\begin{itemize}
\item Emacs
\item Vim
\item Notepad++ (Windows)
\end{itemize}

Typically, a working directory is created where scripts can be saved.

To run a script in the Python Interpeter, execute the following (for IPython, replace \li{python} with \li{ipython})
\begin{verbatim}
$ python myscript.py
\end{verbatim}

The Python interpreter can be used interactively.  In the interactive mode, statements will be executed one at a time as you enter them.  It is extremely useful and allows for very rapid programming.

\subsection*{Integrated Development Environments}
Integrated Development Environments provide a comprehensive environment for application development.  Most IDEs have many tightly integrated tools that are easily accessible.  Some popular IDEs for developing in Python are discussed in this section.

\subsubsection*{Eclipse + PyDev}

Eclipse: \url{http://www.eclipse.org/} \\
PyDev: \url{http://pydev.org/}

Eclipse is a general purpose IDE that supports many languages.  The PyDev plugin for Eclipse contains all the tools needed to start working in Python.  It includes a built-in debugger, and has a very nice code editor.  Eclipse + PyDev is available for Windows, Linux, and Mac OSX.

\subsubsection*{Spyder}

Spyder: \url{http://code.google.com/p/spyderlib/}

Spyder is a Python IDE that is designed specifically for scientific computing.  Its interface is reminescent of MATLAB.  Requires PyQT4 to be installed.  Spyder is available for Windows and Linux.  There is a version available for Mac OSX through MacPorts.

\subsubsection*{IPython Notebook}
The IPython Notebook is a web-based interface to Python.

% Try focusing on the underpinnings of Python:
% Interpreter/Instructions
% Execution Flow (Script, interpreter, bytecode, execution)
% Explain packages and libraries


\newpage

\section{Introduction}

AI is the new electricity that brings about a big transform in
the society, ranging from commercial advertising, health care,
auto driving, agriculture and many others. Deep Neural Networks
demonstrate its impressive power in mathematical problems, computer
vision, natural language processing etc. However, to most people
these state-of-the-art neural networks remain to be black-boxes even
they have successfully taken them into applications. Still, to bring
the potential of neural networks into full play, it is inevitable to
have a better command of what neural networks is doing and why neural
networks work so well?

\par This article aims to cast light on neural networks. In \autoref{sec:NN},
we first look into the foundation of neural networks including the
representation of a neuron, the process of forward propagation and
back propagation, and the basic intuition of gradient descent (GD).
In \autoref{sec:Problem}, we briefly summarize the most common
problems during training a neural network. Subsequently, in \autoref{sec:Solution},
we are going to introduce some effective tricks including a overview
of initialization and optimization, to overcome these problems. In
\autoref{sec:Question}, we take a short look at the three main parts in
neural networks theory, they cover: the power of approximation of
deep neural networks, the landscape of the empirical risk and the
generalization of GD.


\section{Conclusions \& Future Work}
In this paper, we describe our initial work towards performing MBSA using the AADL architecture description language using a failure effect modeling approach.  Our goal is to be able to perform safety analysis on common models used by systems and safety engineers for functional and non-functional analyses, schedulability, and perhaps system image generation.  To perform this analysis, we use existing capabilities within AADL to describe the structure of the system, and build on the existing AGREE framework for compositional analysis of components.

As part of our exploration, we are interested in examining the strengths and weaknesses of our FEM and the AADL Error Annex FLM-based approach.  We believe that the FEM approach has advantages both in terms of brevity of specifications and accuracy of results, and can build on existing analyses performed for systems engineering.  However, there are also risks in the FEM approach involving incomplete or mis-specified properties.

We illustrated the ideas using architecture models based on the Wheel Braking System model in SAE AIR 6110 \cite{AIR6110} and use this in the evaluation of our approach. Using assume-guarantee compositional reasoning techniques, we prove a top level property of the wheel brake system that states when the brake pedals are pressed in the absence of skidding, there will be hydraulic pressure supplied to the brakes.

Starting from the error model notions of error types, two main faults were defined: \textit{fail\_to} which will describe failures of valves and pressure regulators and \textit{inverted\_fail} which describes the failures occurring to components that output boolean values. Using the AADL behavioral model of the WBS, these permanent faults were tied into the nominal model in order to reason about how this model behaves in the presence of specific kinds of faults.

In order to demonstrate that the system was resilient to single faults, we modified the model to allow feedback from the wheel pressure to the BSCU.   This changed the way the system responded to faults that were further downstream of the BSCU or Selector and created a chance for the system to switch to alternate forms of hydraulic pressure. We also reasoned about the initialization values of the system in regards to which mode is the starting mode. It is crucial for the system to begin in Normal mode in order to function successfully in the presence of faults.  After model modification and a small weakening of our original property to account for feedback delay, the model does fulfill the top level contract even when a permanent fault of one of the high level components is introduced.

The current capabilities of AGREE are well-suited to specifying faults.  Our approach allows for scalar types of unbounded integers and reals, as well as composite types such as tuples and structures.  It is possible to model systems and reason about them in either discrete time or real-time.  However, adding faults to existing components is cumbersome and can obscure the nominal behaviors of the model.  We are currently examining several fault specification languages, giving special consideration to the xSAP modeling language.

Future research work will involve the continuation of development of the methods and tools needed to perform model-based safety analysis at the system architecture level. By introducing a common set of models for both nominal system design and safety analysis, we hope to reduce the cost of development and improve safety. Our hope is to demonstrate the practicality of formal analysis for early detection of safety issues that would be prohibitively expensive to find through testing and inspection. We will base this research on industry standard notations that are being used in airborne and ground-based avionics in order to ensure transition of this technology.

\subsection*{Acknowledgements} This research was funded by NASA AMASE NNL16AB07T and University of Minnesota College of Science and Engineering Graduate Fellowship.


\documentclass{elsart}
\usepackage{epsfig,amsmath}
\begin{document}

\subsection{Tracking performance}

The tracking performance depend on various variables:
The most important are following:
\begin{itemize}
\item The track topology - detector contributing to measurement.
      The different topologies has different error parameterization, and the scale of error
      can be  significantly different. E.g DCA resolution for tracks refitted with the
      ITS and TPC are by 2 orders of magnitude better than for TPC tracks only.

\item Multiple scaterring and energy loss are scaling with particle momenta and mean material budget.
      Typical -  behaviour smooth $p_{t}$ and $\theta$ scaling.
\end{itemize}

The multiple scattering in material:
\begin{equation}
\sigma^2_\alpha=\frac{k. xOverX0}{\beta^2.p^2}
\end{equation}

The energy loss correction error:
\begin{equation}
\sigma^2_E= k. (\frac{k_{bb}}{\beta^2} + k)^2
\end{equation}
The energy loss correction is particularly important for low momenta tracks.

The track paramterization - 5 parameters:
\begin{itemize}
\item P0 - local y
\item P1 - local z
\item P2 - sinus   of local inclination angle $\phi$ in y direction
\item P3 - tangent of inclination angle $\theta$ in z direction
\item P4 - curvature  - 1/$p_t$
\end{itemize}

The error scaling:
\begin{equation}
\begin{split}
C=1/p_t \\
\sigma^2_{yy} \approx   \sigma^2_{yy0}+ k_p.C^2 \\
\sigma^2_{zz} \approx   \sigma^2_{zz0}+ k_p.C^2 \\
\sigma^2_{\phi\phi}     \approx  \sigma^2_{\phi\phi0}+ k_a.C^2 \\
\sigma^2_{\theta\theta} \approx  \sigma^2_{\theta\theta0}+ k_a.C^2 \\
\sigma^2_{cc} \approx  \sigma^2_{cc0}+ k_c.C^4\\
\end{split}
\end{equation}

\subsection{Resolution histograming and parameterization}

The resolution of the track parameters depends strongly on the momenta,
respectivaly curvature.
There is roughly linear scaling roughly linear scaling in position and
angle, and parabolic scaling  for momentum resolution. The pread of the resolutions
because of the wide range of particle momenta is of the order of magnitude.
($p_t$ $<0.1,\inf>$, C $<0,10>$).

In order to save the space for histograms, the resolution can be appropriatetly
scaled. Following scaling function are used:

\begin{equation}
\begin{split}
C=1/p_t \\
sf_{pp} =   \sqrt{s_{pp}+C}   \\
sf_{aa} =   \sqrt{s_{aa}+C}   \\
sf_{cc} =   \sqrt{s_{cc}+C^2} \\
\end{split}
\end{equation}
Choosing appropriate scaling coeficient s, the scaled resolution as function of the
particle curvature is roughly constant.

\begin{thebibliography}{9}   % Use for  1-9  references

\bibitem{alice-ref}
ALICE tech. proposal CERN/LHCC 95-71.

\bibitem{aliroot-ref}
ALICE PPR v.1 CERN/LHCC 2003-049.

\bibitem{tpc-ref}
ALICE TPC TDR CERN/LHCC 2000-001.

\bibitem{its-ref}
ALICE ITS TDR CERN/LHCC 99-12.

\bibitem{trd-ref}
ALICE TRD TDR CERN/LHCC 2001-021.

\bibitem{tof-ref}
ALICE TOF TDR CERN/LHCC 2002-016.

\end{thebibliography}

\end{document}


\section{Script Constructors and Evaluation}
\label{sec:timelock-lang}

\begin{figure}[htb]
  \begin{align*}
    \fun{validateScript} & \in\Script\to\Tx\to\Bool \\
    \fun{validateScript} ~s~\var{tx}~& =~
                             \fun{evalTimelock}~\var{vhks} ~\var{itr}~\var{s} \\
                         & ~~~~\where \\
                         & ~~~~~~~~\var{vhks}\leteq \{\fun{hashKey}~vk \vert
                           vk \in \dom(\fun{txwitsVKey}~\var{tx})\} \\
                         & ~~~~~~~~\var{itr} \leteq \fun{txvldt}~ (\txbody~ \var{tx})
  \end{align*}
  \caption{Script Validation}
  \label{fig:functions-validate}
\end{figure}

In the ShelleyMA era, the
$\fun{validateScript}$ function performs validation of only timelock scripts,
see Figure~\ref{fig:functions-validate}. Note that while there is no explicit
support for validating multi-signature scripts in $\fun{validateScript}$,
these scripts remain effectively usable as the encodings of multi-sig and timelock
scripts are compatible. An existing multi-sig script-locked output is
spent by interpreting the encoded script as a timelock script (one without
any validity interval clauses), then validating it. For details, see the CDDL
specification.

The arguments that are passed to the $\fun{validateScript}$ function include all those
that are needed for $\Timelock$ script evaluation :

\begin{itemize}
\item The script getting evaluated
\item The transaction
\end{itemize}

The semantics of the Timelock language are specified in Figure~\ref{fig:defs:tx-mc-eval}.
The evaluation of the scripts constructed by $\type{Signature}, \type{AllOf},
\type{AnyOf}, \type{MOfN}$ is done the same as for their
$\ScriptNI$ counterparts. The $\type{RequireTimeStart}$ evaluation
checks that the start of the transaction validity interval is not $\Nothing$, and is in or after
the slot specified by the constructor. The $\type{RequireTimeExpire}$ evaluation
checks that the end of the transaction validity interval is not $\Nothing$, and is in or before
the slot specified by the constructor.

\begin{figure*}[htb]
  \emph{Timelock Script Constructor Types}
  \begin{align*}
    & \type{evalTimelock} & \in \powerset{\KeyHash}\to(\Slot^? \times \Slot^?)\to\Timelock \to \Bool & \\
    & \text{The type of the Timelock script evaluator} \\~\\
    %
    & \type{Signature} & \in \KeyHash \to \Timelock & \\
    %
    & \type{AllOf} & \in \seqof{\Timelock} \to \Timelock & \\
    %
    & \type{AnyOf} & \in \seqof{\Timelock} \to \Timelock & \\
    %
    & \type{MOfN} & \in \N \to \seqof{\Timelock} \to \Timelock & \\
    %
    & \type{RequireTimeStart} & \in \Slot \to \Timelock &\\
    %
    & \type{RequireTimeExpire} & \in \Slot \to \Timelock &\\
  \end{align*}
  %
  \emph{Timelock Script Evaluation}
  \begin{align*}
    \fun{evalTimelock} & ~(\type{Signature}~hk)~\var{vhks}~\wcard =  hk \in vhks \\
    \fun{evalTimelock} & ~(\type{AllOf}~ts)~\var{vhks}~\wcard =
                              \forall t \in ts: \fun{evalTimelock}~t~vhks\\
    \fun{evalTimelock} & ~(\type{AnyOf}~ts)~\var{vhks}~\wcard =
                              \exists t \in ts: \fun{evalTimelock}~t~vhks\\
    \fun{evalTimelock} & ~(\type{MOfN}~m~ts)~\var{vhks}~\wcard = \\
                             & m \leq \Sigma
                               (\textrm{card} \{ t s.t. t \leftarrow ts \wedge \fun{evalTimelock}~\var{t}~\var{vhks} \\
    \fun{evalTimelock} &~(\type{RequireTimeStart}~\var{lockStart})~\var{vhks}~\var{(\var{txStart}, \wcard)} \\
    & =~
    \begin{cases}
      \False & \var{txStart} = \Nothing \\
      \var{lockStart} \leq \var{txStart} & \text{otherwise}
    \end{cases} \\
    \fun{evalTimelock} &~(\type{RequireTimeExpire}~\var{lockExp})~\var{vhks}~\var{(\wcard, \var{txExp})} \\
    & =~
    \begin{cases}
      \False & \var{txExp} = \Nothing \\
      \var{txExp} \leq \var{lockExp} & \text{otherwise}
    \end{cases} \\
  \end{align*}
  \caption{Timelock Script Constructor Types and Evaluation}
  \label{fig:defs:tx-mc-eval}
\end{figure*}

% The Figures~\ref{fig:defs:tx-mc-eval},~\ref{fig:defs:tx-mc-eval-2},
% and~\ref{fig:whitelist-example} give
% possible constructors of the Timelock language.
%
% %% \begin{note}
% %%   sort out the constructors
% %% \end{note}
%
% \begin{figure*}[htb]
%   \begin{align*}
%     & \fun{evalTimelock} \in\Timelock\to\PolicyID\to\Slot\to\powerset\KeyHash \\
%     &~~~~\to\TxBody\to\UTxO \to\Bool  \\
%     & \text{UTxO is only for the outputs THIS tx is spending, not global UTxO, i.e.} \\
%     & \text{when called,}~\var{spentouts}~=~(\fun{txins}~\var{txb}) ~\restrictdom~\var{utxo} \\~\\
%     %
%     & \fun{evalTimelock}  ~(\type{JustMSig}~s)~\var{pid}~\var{slot}~\var{vhks}
%      ~\var{txb}~\var{spentouts} \\
%     &~~~~ =~ \fun{evalMultiSigScript}~s~\var{vhks} \\
%     & \text {checks the msig script}\\~\\
%     %
%     & \fun{evalTimelock}
%      ~\type{DoMint}~\var{pid}~ \var{slot}~\var{vhks} ~\var{txb}~\var{spentouts} \\
%     &~~~~ =~ \var{pid} \notin \dom~(\fun{mint}~\var{txb}) \\
%     & \text {checks that script hash of this script is not an asset ID being minted by tx}  \\~\\
%     %
%     & \fun{evalTimelock}
%      ~\type{SignedByPIDToken}~\var{pid}~ \var{slot}~\var{vhks} ~\var{txb}~\var{spentouts} \\
%     &~~~~ =~ \exists~t\mapsto ~\_~\in~ \fun{range}~(\var{pid}~ \restrictdom~(\fun{ubalance}~\var{spentouts})) ~:~ t~\in~\var{vhks} \\
%     & \text{checks that tx is signed by a key whose hash is the name of a token in this asset}
%     \\~\\
%     & \fun{evalTimelock}
%      ~(\type{SpendsCur}~\var{pid'})~\var{pid}~ \var{slot}~\var{vhks} ~\var{txb}~\var{spentouts} \\
%     &~~~~ =~ (\var{pid'}~\neq~\Nothing ~\wedge ~\var{pid'}~\in~ \dom~(\fun{ubalance}~\var{spentouts}))\\
%     &~~~~~~ \vee (\var{pid'}~=~\Nothing ~\wedge ~\var{pid}~\in~ \dom~(\fun{ubalance}~\var{spentouts})) \\
%     & \text{checks that this transaction spends asset pid' OR itself if}~\var{pid'}~=~\Nothing
%     \\~\\
%     &\fun{evalTimelock}~(\type{Not}~s)~\var{pid}~\var{slot}~\var{vhks}
%     ~\var{txb}~\var{spentouts}
%    \\
%     &~~~~ = \neg ~\fun{evalTimelock}~s~\var{pid}~\var{slot}~\var{vhks}
%     ~\var{txb}~\var{spentouts}\\~\\
%     %
%     &\fun{evalTimelock}~(\type{RequireAll}~ls)~\var{pid}~\var{slot}~\var{vhks}
%     ~\var{txb}~\var{spentouts}
%    \\
%     &~~~~ = \forall ~s'~ \in~ ls~:~\fun{evalTimelock}~s'~\var{pid}~\var{slot}~\var{vhks}
%     ~\var{txb}~\var{spentouts}\\~\\
%     %
%     &\fun{evalTimelock}~(\type{RequireOr}~ls)~\var{pid}~\var{slot}~\var{vhks}
%     ~\var{txb}~\var{spentouts}
%    \\
%     &~~~~ = \exists ~s'~ \in~ ls~:~\fun{evalTimelock}~s'~\var{pid}~\var{slot}~\var{vhks}
%     ~\var{txb}~\var{spentouts}\\
%   \end{align*}
%   \caption{Multi-asset Script Evaluation}
%   \label{fig:defs:tx-mc-eval}
% \end{figure*}
%
% \begin{figure*}[htb]
%   \begin{align*}
%     & \fun{evalTimelock}
%      ~(\type{AssetToAddress}~\var{pid'}~\var{addr})~\var{pid}~ \var{slot}~\var{vhks} ~\var{txb}~\var{spentouts} \\
%     &~~~~ =~ \forall~(a, v)~\in~\fun{range}~(\fun{outs}~txb),~\\
%     &~~~~~~ \var{c}~\in~\dom~v~\Rightarrow~(a~=~ \var{a'} ~\wedge~
%                        v~=~\var{c}~ \restrictdom~(\fun{ubalance}~(\fun{outs}~txb)) \\
%     & \where \\
%     & ~~~~~~~ \var{a'}~=~\fun{if}~ \var{addr}~\neq~\Nothing~\fun{then}~\var{addr}~\fun{else}~\var{(pid',pid')} \\
%     & ~~~~~~~ \var{c}~=~\fun{if}~ \var{pid'}~\neq~\Nothing~\fun{then}~\var{pid'}~\fun{else}~\var{pid} \\
%     & \text{checks that tx outputs any pid tokens by themselves to the specified address} \\
%     & \text {the script address of the given asset when addr unspecified} \\~\\
%     & \fun{evalTimelock}
%      ~(\type{TrancheTokens}~\var{tts}~\var{txin})~\var{pid}~\var{slot}~\var{vhks}
%      ~\var{txb}~\var{spentouts}  \\
%     &~~~~ =~(\var{pid}\mapsto\var{tts}~\in~\var{val})~ \wedge~(\var{txin}~\in~\fun{txins}~{txb}) \\
%     & \text{tranche tokens is incomplete} \\~\\
%     %
%     & \fun{evalTimelock}
%      ~(\type{FreshTokens})~\var{pid}~\var{slot}~\var{vhks}
%      ~\var{txb}~\var{spentouts}
%       \\
%     &~~~~ =~\forall~\var{pid}~ \mapsto ~tkns ~\in~ \var{val}~:~ \\
%     &~~~~ \forall~t~\in~\var{tkns},~
%         \fun{nameToken}~(\fun{indexof}~\var{t}~\var{tkns},~\fun{txins}~{txb})~=~t
%     \end{align*}
%     \caption{Multi-asset Script Evaluation, cont.}
%     \label{fig:defs:tx-mc-eval-2}
% \end{figure*}
%
% \begin{figure*}[htb]
%   \begin{align*}
%     & \fun{whitelist} \in\ScriptMSig\to\Script  \\~\\
%     %
%     & \type{whitelist}  ~\var{msig}~ =~ \type{RequireOr}~
%       (\type{RequireAll}~(\type{DoMint};~\type{JustMSig}~\var{msig});~\\
%     &~~~~~~ \type{RequireAll}~(\type{AssetToAddress}~\Nothing~\Nothing ;\\
%     &~~~~~~ (\type{Not}~\type{DoMint});~\type{SignedByPIDToken})) \\
%     %
%     & \text{msig is some MSig script containing signatures of some accreditation authority} \\
%     & \text{i.e. this authority can do any minting or spending of this token} \\~\\
%     %
%     & (\fun{hashScript}~(\type{SpendsCur}~(\fun{hashScript}~(\type{whitelist}~\var{msig}))),~ \var{tkns}) \\
%     & \text{an example of an output spending which requires to be on a whitelist made by msig authority}
%   \end{align*}
%   \caption{Whitelist Script Example}
%   \label{fig:whitelist-example}
% \end{figure*}


\section{Protocol Description}
\label{unity}

We keep and maintain the notion of difficulty provided by Proof of Work, as well as the general goal of the consensus protocol, which is agreement on canonical ordering of blocks. We introduce an alternative block generation scheme utilizing \textbf{stake} or \textbf{voting power} while maintaining the constructs own notion of difficulty. To facilitate this, we introduce a mechanism to obtain \textbf{stake} in the network by locking up network currency associated with each account. To maintain a split between the two types of blocks, we introduce a new rule that enforces the \textit{interleaving} behaviour, in that blocks must reference a parent of the opposing type. Finally, we introduce a fork choice rule that determines agreement on a canonical chain based upon an intermediate unit derived from the difficulty of both block generation algorithms. We show that this approach leads to an increase in security against certain attacks \S\ref{analysis}.

In order to forge a PoS block, a staker must have already registered some stake in a previous block. The exact mechanism of how stake is registered is an implementation detail; for a summary of how the Open Application Network manages staking, see \cite{unity_design_spec}, and \S\ref{staking_mechanism} for a very brief overview. A PoS block has some waiting time associated with it, and will only be accepted by the network once this wait time has elapsed (measured from the parent PoW block). Every staker has a random wait time calculated for each block they try to produce; however, the expected wait time is inversely proportional to the amount a staker has staked. In short, the more one stakes, the less their wait times are expected to be. The percentage of blocks a staker should expect to win is their percentage of the total stake in the network.

\subsection{Staking}
\label{staking_mechanism}

Staking in this context refers to \textbf{locking} ones assets in return for voting power (alternatively known as stake). In our model, the act of locking ones assets can be done immediately (for example in the next block), the act of \textbf{unlocking} ones assets however is associated with a waiting period before one can re-acquire the assets (for example, the assets can be re-acquired after $x$ blocks). We ignore concepts of transferring and delegating (in the context of the protocol) as described in \cite{unity_design_spec}.

\subsection{PoW Block Generation}
\label{pow_block_generation}

Miners performing Proof of Work to generate the next block use a scheme similar to the introduced by Nakamoto in \cite{nakamoto2008}. Assuming a mining difficulty parameter ($d_w$), miners solve the following cryptographic puzzle,

\begin{equation}
\label{eq:pow_puzzle_equation}
H(b) \leq 2^{256} / d_w.
\end{equation}

The hash function ($H()$) is a deterministic random oracle that returns a random number in $N_{256}$, given an arbitrary byte array $b$ as input ($b$ is usually referred to as the \textit{nonce}). As the cryptographic puzzle is independent of any miner, the probability of a miner proposing a block is proportional to their computational power (number of permutations of $H()$ the miner can evaluate per unit time). The difficulty parameter ($d_w$) is used by the network to stabilize it's block production rate in the presence of dynamic hash power (see \S\ref{difficulty_adjustment}).

\subsection{PoS Block Generation}
\label{pos_block_generation}

The generation of PoS blocks is largely based on the Nxt forging algorithm \cite{popov2016probabilistic}.

A PoS block has a field called \emph{seed}. A PoS block's seed is based on the seed of the previous PoS block in the chain, which is always the block's grandparent. The seed of block $n + 2$ is the block producer's signature upon the seed of block $n$ (i.e. in order to produce block $n+2$, the staker must obtain the seed for this block by signing the seed of the last PoS block (block $n$)).

Any time a staker is trying to produce a PoS block, there is a certain waiting time that must elapse before the block is valid. This wait time is measured from the timestamp of the parent block. The wait time is determined by three factors: the new block's seed, $s$, the staker's total stake, $V$, and the difficulty of the block, $d_s$. The difficulty is calculated as described in \S\ref{difficulty_adjustment}. The wait time, $\Delta$, is inversely proportional to $V$, and directly proportional to $d_s$. The seed, $s$, provides some randomness to this calculation. We calculate the wait time as,

$$\Delta = \frac{d_s \cdot \log (\frac{2^{256}}{H(s)})}{V},$$

where $H$ is some hash function producing a 256-bit output.

The timestamp of a PoS block must be greater than or equal to the parent block's timestamp plus this $\Delta$. Honest nodes should thus only accept PoS blocks once the waiting time has elapsed .Further more, honest nodes must reject blocks with timestamps that are greater than their system time, so as to not accept block \emph{in the future}.

\subsection{Fork choice rule}
\label{fork}

The \emph{fork choice rule} is the aspect of a consensus protocol that decides between two or more chains of valid blocks to decide what the ``canonical'' chain or ``main'' chain is. The fork choice rule for the protocol is to always choose the chain that maximises total difficulty, where total difficulty is simply the sum of the difficulties of all the blocks in the chain. Therefore, given a set of chains $D$, we denote the $i$th chain as $d_i$, and we denote $td_{s, d_i}$ and $td_{w, d_i}$ to be the total staking and work difficulties (respectively) for the $i$th chain. We recognize the main chain as the one that has in its prefix the genesis block, and that satisfies,

\begin{equation}
    M = \{td_{s, d_i} + td_{w, d_i} > td_{s, d_j} + td_{w, d_j} \forall j \neq i | d_i \in D \}
\end{equation}

In \S\ref{double_spend_attack} we examine why this fork choice rule is beneficial, compared to the one depicted in \cite{wu2019unifying}.

\subsection{Difficulty Adjustment}
\label{difficulty_adjustment}

We begin with the presumption that block arrival times for fast acting difficulty adjustment algorithms can be modelled using an exponential distribution. Note that this is not true in the case of a blockchain with a lagging difficulty adjustment algorithm such as Bitcoin \cite{block_arrivals}. This difficulty algorithm is applied identically to all blocks in the chain (i.e. both PoW and PoS blocks). Given that $\Delta$ represents the block arrival rates, the difficulty of the ($n+1$)th block (denoted $d_{n+1}$) is related the to the difficulty of the $n$th block (denoted $d_n$) via:

\begin{equation}
    d_{n+1} = \begin{cases}
        \frac{d_n}{1+\alpha}, & \Delta > -\frac{\log(1/2)}{\lambda} \\
        d_n, & \Delta = -\frac{\log(1/2)}{\lambda} \\
        d_{n} \cdot (1 + \alpha), & \Delta < -\frac{\log(1/2)}{\lambda} \\
    \end{cases}
\end{equation}

Where $\lambda$ represents the rate parameter for an exponential distribution. The $\alpha$ controls the learning rate, which further determines the responsiveness of the algorithm. The boundary value of $-\frac{\ln (0.5)}{\lambda}$ is calculated by solving,

\begin{equation}
    \label{eq:boundary}
    1-e^{(-\lambda x)}=0.5,
\end{equation}

where the left-hand side is the cumulative distribution function (cdf) of an exponential random variable. Where equation \ref{eq:boundary} refers to the time at which the probability of a block arriving or having already arrived is half. To give an example, in the live network we design our expected block time to be centered at 10 seconds, therefore we design the boundary to target an exponential distribution with a mean of 10. This gives us $\lambda^{-1}=10$. Solving $x$ for such a lambda gives us a boundary time of $x \approx 6.9314$.

Intuitively, this creates a negative feedback loop that stabilizes the system around 10 seconds. If the average difficulty is too high, it is reflected in the system by an increase in block time (on average), in which case the protocol responds by decreasing the difficulty. In the same vein, difficulty is adjusted upwards when the average block time is too low.


\documentclass[12pt, a4paper, footexclude, headexclude]{scrartcl}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Packages
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage[margin=0.5in]{geometry}

\usepackage[ngerman]{babel}
\usepackage{xcolor}
\usepackage[pdftex]{hyperref}
\usepackage{multicol}

\usepackage{xinttools}
\usepackage[nomessages]{fp}
\usepackage{tabularx}
\usepackage{tcolorbox}

\setlength{\parindent}{0pt}

\usepackage[pdftex]{insdljs}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Parameter
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\def\fieldWidth{20}
\def\fieldHeight{20}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Javascript
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{insDLJS}[]{JSDateiname}{gameoflife}

const GAME_DESC = "Conways game of life is a cellular automaton.\
After the initial input the application will run on itself and without further interaction.\
Dependent on the state the field will evolve based on certain rules.\
The rules use the neighbourhood of a cell to determine the state of it in the next step.";

% Outside variables
const FIELD_WIDTH = AFMakeNumber(\fieldWidth);
const FIELD_HEIGHT = AFMakeNumber(\fieldHeight);

% Constants
const DEAD = 0;
const ALIVE = 1;

% Globals
% Animation interval variable
var run;
% The game field arrays
var complField1 = new Array();
var complField2 = new Array();

var currStep = 0;
var fieldIdx = 0;
var currentShape = 8;
var shapeMode = true;
var animate = false;

% Color data
const COLORS = new Array(
    color.black,
    [ "RGB", 0.843, 0.078, 0.058 ],
    [ "RGB", 0.203, 0.603, 0.054 ],
    [ "RGB", 0.078, 0.305, 0.560 ],
    [ "RGB", 0.560, 0.078, 0.533 ]
);

% Shape array that can be added to the field
const SHAPES = new Array(
    % Still lifes
    [[0, 0]], % One
    [[0, 0], [1, 0], [0, 1], [1, 1]], % Block
    [[1, 0], [2, 0], [0, 1], [3, 1], [1, 2], [2, 2]], % Beehive
    [[1, 0], [2, 0], [0, 1], [3, 1], [1, 2], [2, 3], [3, 2]], % Loaf
    [[0, 0], [1, 0], [0, 1], [2, 1], [1, 2]], % Boat
    [[1, 0], [0, 1], [2, 1], [1, 2]], % Tub
    % Oscillators
    [[1, 0], [1, 1], [1, 2]], % Blinker
    [[1, 1], [2, 1], [3, 1], [0, 2], [1, 2], [2, 2]], % Toad
    [[0, 0], [1, 0], [0, 1], [3, 2], [2, 3], [3, 3]], % Beacon
    [[4, 2], [5, 2], [6, 2], [10, 2], [11, 2], [12, 2],
        [2, 4], [7, 4], [9, 4], [14, 4],
        [2, 5], [7, 5], [9, 5], [14, 5],
        [2, 6], [7, 6], [9, 6], [14, 6],
        [4, 7], [5, 7], [6, 7], [10, 7], [11, 7], [12, 7],
        [4, 9], [5, 9], [6, 9], [10, 9], [11, 9], [12, 9],
        [2, 10], [7, 10], [9, 10], [14, 10],
        [2, 11], [7, 11], [9, 11], [14, 11],
        [2, 12], [7, 12], [9, 12], [14, 12],
        [4, 14], [5, 14], [6, 14], [10, 14], [11, 14], [12, 14]
    ], % Pulsar
    [[5, 4], [5, 5], [4, 6], [6, 6], [5, 7], [5, 8], [5, 9],
     [5, 10], [4, 11], [6, 11], [5, 12], [5, 13]], % Pentadecathlon
    % Spaceships
    [[1, 0], [2, 1], [0, 2], [1, 2], [2, 2]], % Glider
    [[0, 0], [3, 0], [4, 1], [0, 2], [4, 2],
     [1, 3], [2, 3], [3, 3], [4, 3]], % Light-weight spaceship
    [[2, 0], [0, 1], [4, 1], [5, 2], [0, 3], [5, 3],
     [1, 4], [2, 4], [3, 4], [4, 4], [5, 4]], % Middle-weight spaceship
    [[2, 0], [3, 0], [0, 1], [5, 1], [6, 2], [0, 3], [6, 3],
     [1, 4], [2, 4], [3, 4], [4, 4], [5, 4], [6, 4]] % Heavy-weight spaceship
);

%%%%%%%%%%
% Helper %
%%%%%%%%%%
/**
 * Returns a random number between 0 and the param.
 * @param {Number} max The upperbound
 */
function getRandomInt(max) {
    return Math.floor(Math.random() * max);
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Initialisation and Restart %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
/**
 * Initialise the default game state.
 */
function initialise() {
    for (var row = 0; row < FIELD_HEIGHT; row++) {
        var tmp1 = new Array();
        var tmp2 = new Array();
        for (var column = 0; column < FIELD_WIDTH; column++) {
            tmp1.push(DEAD);
            tmp2.push(DEAD);
        }
        complField1.push(tmp1);
        complField2.push(tmp2);
    }

    % Init the GUI
    initialiseButtons();

    % Initial run
    runAll();
}

/**
 * Initialise all buttons from the GUI.
 * For example add callbacks and set the correct colors.
 */
function initialiseButtons() {
    % Assign each button the coresponding function and disable the highlights
    var funcName = "addShape";
    for (var x = 0; x < FIELD_WIDTH; x++) {
        for (var y = 0; y < FIELD_HEIGHT; y++) {
            var callbackName = funcName + "(" + x.toString() + "," + y.toString() + ");";
            this.getField("pos" + x + "-" + y).setAction("MouseDown", callbackName);
            this.getField("pos" + x + "-" + y).borderColor = color.transparent;
            this.getField("pos" + x + "-" + y).fillColor = color.transparent;
        }
    }

    this.getField("animate").setAction("MouseDown", "toggleAnimation();");
    this.getField("animate").highlight="none";
    this.getField("animatetxt").setAction("MouseDown", "toggleAnimation();");
    this.getField("animatetxt").fillColor = color.transparent;
    this.getField("animatetxt").borderColor = color.transparent;
    if (animate) {
        this.getField("animatetxt").value = "On";
    } else {
        this.getField("animatetxt").value = "Off";
    }

    this.getField("step").setAction("MouseDown", "runAll();");
    this.getField("step").highlight="none";

    this.getField("shapemode").setAction("MouseDown", "toggleMode();");
    this.getField("shapemode").highlight="none";
    this.getField("shapemodetxt").setAction("MouseDown", "toggleMode();");
    this.getField("shapemodetxt").fillColor = color.transparent;
    this.getField("shapemodetxt").borderColor = color.transparent;
    if (shapeMode) {
        this.getField("shapemodetxt").value = "On";
    } else {
        this.getField("shapemodetxt").value = "Off";
    }

    this.getField("shapeidx").currentValueIndices = 0;
    this.getField("shapeidx").fillColor = color.transparent;
    this.getField("shapeidx").borderColor = color.white;

    this.getField("fillrnd").setAction("MouseDown", "fillRandom();");
    this.getField("fillrnd").highlight="none";

    this.getField("percentage").currentValueIndices = 0;
    this.getField("percentage").fillColor = color.transparent;
    this.getField("percentage").borderColor = color.white;

    this.getField("clear").setAction("MouseDown", "clear();");
    this.getField("clear").highlight="none";

    this.getField("currstep").fillColor = color.transparent;
    this.getField("currstep").borderColor = color.transparent;

    % Info field setup
    this.getField("info").fillColor = color.transparent;
    this.getField("info").borderColor = color.transparent;

    % Tooltip setup
    this.getField("tooltipbtn").setAction("MouseDown", "tooltip(true);");
    this.getField("tooltipbtn").setAction("MouseUp", "tooltip(false);");
    this.getField("tooltipbtn").highlight="none";
}

/**
 * Enable or disable the tooltip
 *
 * @param {Boolean} on Enable or disable tooltip
 */
function tooltip(on) {
    if (on) {
        % Move the tooltip field to the center of the screen
        % and adjust the size so the text can be displayed
        var field = this.getField("tooltiptxt");
        field.delay = true;
        field.value = GAME_DESC;

        field.multiline = true;
        field.textSize = 16;
        field.fillColor = color.gray;
        % hight 842, width 596
        % upper-left x, upper-left y, lower-right x and lower-right y
        field.rect = [128, 581, 468, 381];

        field.delay = false;
    } else {
        % Remove the field such that it is not visible
        var field = this.getField("tooltiptxt");
        field.delay = true;
        field.value = "";

        field.multiline = false;
        field.fillColor = color.gray;
        field.rect = [0, 0, 0, 0];

        field.delay = false;
    }
}

%%%%%%%%%%%%%%%%%
% Toggle states %
%%%%%%%%%%%%%%%%%
/**
 * Start or stop the field animation.
 * Automatically disables the shapemode on switch.
 */
function toggleAnimation() {
    animate = !animate;

    var field = this.getField("animatetxt");
    field.delay = true;
    if (animate) {
        field.value = "On";

        % Animation interval
        run = app.setInterval("runAll()", 1000);
        printInfoText("Enabled animation.");

        if (shapeMode) {
            toggleMode();
            printInfoText("Enabled animation and disabled shape mode.");
        }
    } else {
        field.value = "Off";
        app.clearInterval(run);
        printInfoText("Disabled animation.");
    }
    field.delay = false;

}

/**
 * Enable or disable shapemode.
 * If the shapemode is enabled the user can add shapes to the field.
 * Automatically disables the animation on switch.
 */
function toggleMode() {
    shapeMode = !shapeMode;

    var field = this.getField("shapemodetxt");
    field.delay = true;
    if (shapeMode) {
        field.value = "On";
        printInfoText("Enabled shape mode.");

        if (animate) {
            toggleAnimation();
            printInfoText("Disabled animation and enabled shape mode.");
        }
    } else {
        field.value = "Off";
        printInfoText("Disabled shape mode.");
    }
    field.delay = false;
}

%%%%%%%%%%%%%%%%%%%%%%%
% Loop and processing %
%%%%%%%%%%%%%%%%%%%%%%%
/**
 * Main loop used for animation.
 */
function runAll() {
    process();

    fieldIdx = (fieldIdx + 1) \% 2;
    currStep++;
    this.getField("currstep").value = "Current step: " + currStep + ".";

    drawAll(fieldIdx);
}

/**
 * Calculates the next state of the gamefield, by locking at each spot
 * and writing the new state (determined by the neighbourhood) in the
 * next array.
 */
function process() {
    var state = DEAD;
    var result = DEAD;
    var n = 0;
    % Iterate all fields
    for (var x = 0; x < FIELD_WIDTH; x++) {
        for (var y = 0; y < FIELD_HEIGHT; y++) {
            if (fieldIdx == 1) {
                state = complField2[y][x];
            } else {
                state = complField1[y][x];
            }

            var n = getNeighbourCount(x, y);
            % Rules for when a slot is dead or alive
            if (state == DEAD && n == 3) {
                % Repopulation
                result = ALIVE;
            } else if (state == ALIVE) {
                if (n < 2) {
                    % Underpopulation
                    result = DEAD;
                } else if (n == 2 || n == 3) {
                    result = ALIVE;
                } else {
                    % Overpopulation
                    result = DEAD;
                }
            } else {
                result = DEAD;
            }

            if (fieldIdx == 1) {
                complField1[y][x] = result;
            } else {
                complField2[y][x] = result;
            }
        }
    }
}

/**
 * Calculates the amount of neighbours that are alive for the given slot x, y.
 *
 * @param {Number} pX The x coordinate.
 * @param {Number} pY The y coordinate.
 */
function getNeighbourCount(pX, pY) {
    var counter = 0;
    for (var x = pX - 1; x <= pX + 1; x++) {
        for (var y = pY - 1; y <= pY + 1; y++) {
            % Ignore own position and border
            if ((x == pX && y == pY) || x < 0 || y < 0 || x >= FIELD_WIDTH || y >= FIELD_HEIGHT) {
                continue;
            }
            if ((fieldIdx == 1 && complField2[y][x] == ALIVE) ||
                (fieldIdx == 0 && complField1[y][x] == ALIVE)
            ) {
                counter++;
            }
        }
    }
    return counter;
}

%%%%%%%%%%%%%%%%%%
% Fill and clear %
%%%%%%%%%%%%%%%%%%
/**
 * Clears both field arrays and stops animation.
 */
function clear() {
    currStep = 0;

    if (animate) {
        animate = false;
        var field = this.getField("animatetxt");
        field.delay = true;
        field.value = "Off";
        field.delay = false;

        app.clearInterval(run);

        printInfoText("Clear field and disabled animation.");
    } else {
        printInfoText("Clear field.");
    }

    % Clear all to dead
    for (var x = 0; x < FIELD_WIDTH; x++) {
        for (var y = 0; y < FIELD_HEIGHT; y++) {
            complField1[y][x] = DEAD;
            complField2[y][x] = DEAD;
        }
    }
    drawAll(fieldIdx);
}

/**
 * Adds the selected shape to the given coordinates, with its top left corner at
 * that position.
 *
 * @param {Number} x The x coordinate.
 * @param {Number} y The y coordinate.
 */
function addShape(x, y) {
    % Warning when shapemode is disabled
    if (!shapeMode) {
        printInfoText("Enable shape mode to add shapes.");
        return;
    }

    % Get the shape
    currentShape = this.getField("shapeidx").currentValueIndices;

    for (var pos = 0; pos < SHAPES[currentShape].length; pos++) {
        var eX = SHAPES[currentShape][pos][0] + x;
        var eY = SHAPES[currentShape][pos][1] + y;

        % Border check
        if (eX < 0 || eY < 0 || eX >= FIELD_WIDTH || eY >= FIELD_HEIGHT) {
            continue;
        }

        if (fieldIdx == 0) {
            complField1[eY][eX] = ALIVE;
        } else {
            complField2[eY][eX] = ALIVE;
        }
    };

    printInfoText("Added shape " + currentShape + ".");
    drawAll((fieldIdx + 1) \% 2);
}

/**
 * Randomise the content of the complete field given the
 * percentage specified in the gui.
 */
function fillRandom() {
    var percentage = this.getField("percentage").value;
    for (var x = 0; x < FIELD_WIDTH; x++) {
        for (var y = 0; y < FIELD_HEIGHT; y++) {
            if (getRandomInt(100) < percentage) {
                if (fieldIdx == 0) {
                    complField1[y][x] = ALIVE;
                } else {
                    complField2[y][x] = ALIVE;
                }
            }
        }
    }
    drawAll((fieldIdx + 1) \% 2);
}

%%%%%%%%
% Draw %
%%%%%%%%
/**
 * Redraw all fields.
 *
 * @param {Number} idx The index of the array to draw.
 */
function drawAll(idx) {
    var field;
    for (var x = 0; x < FIELD_WIDTH; x++) {
        for (var y = 0; y < FIELD_HEIGHT; y++) {
            field = this.getField("pos" + x + "-" + y);
            field.delay = true;
            var value = DEAD;
            if (idx == 1) {
                value = complField1[y][x];
            } else {
                value = complField2[y][x];
            }

            if (value > DEAD) {
                field.fillColor = COLORS[0];
                field.borderColor = COLORS[0];
            } else {
                field.fillColor = color.transparent;
                field.borderColor = color.transparent;
            }
            field.delay = false;
        }
    }
}

/**
 * Print information about the winner and the gamestate.
 */
function printInfoText(text) {
    var field = this.getField("info");
    field.delay = true;
    field.value = text;
    field.delay = false;
}

\end{insDLJS}

\OpenAction{/S /JavaScript /JS (initialise();)}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Dokument
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}

    \begin{Form}

        % Header
        \begin{multicols}{2}
            % Title
            \section*{Game of Life}
        \columnbreak
            % Tooltip object
            \begin{flushright}%
                \PushButton[name=tooltipbtn, bordercolor=white]{%
                    \begin{tcolorbox}[width=20pt, height=20pt, left=3pt, top=0pt]
                        \centering?\strut{}
                    \end{tcolorbox}%
                }
            \end{flushright}%
        \end{multicols}

        % Calculate the max width and height of a block
        \FPeval{\resultW}{(\fieldWidth * 4 + 3)}
        \def\blocksizeW{\dimexpr (\linewidth-\resultW pt)/\fieldWidth \relax}

        \FPeval{\resultH}{(\fieldHeight * 4 + 3)}
        \def\blocksizeH{\dimexpr (500 pt -\resultH pt)/\fieldHeight \relax}

        % Define the blocksize via the smaller amount
        \ifnum\blocksizeW<\blocksizeH
            \def\blocksize{\blocksizeW}
        \else
            \def\blocksize{\blocksizeH}
        \fi

        % The gamefield
        \begin{tcolorbox}
            \begin{flushright}
                \xintFor* #2 in {\xintSeq{0}{\fieldHeight-1}} \do {%
                    \xintFor* #1 in {\xintSeq{0}{\fieldWidth-1}} \do {%
                        \TextField[%
                            width=\blocksize, height=\blocksize,%
                            bordercolor=white, name=pos#1-#2, readonly=true]{}\hspace{3pt}%
                    }\vspace{3pt}
                    \newline%
                }%
            \end{flushright}%
        \end{tcolorbox}

        % Game related buttons
        \begin{center}%
            \begin{tabularx}{\textwidth}{@{} *{2}{X} @{}}%
                \PushButton[name=animate, bordercolor=white]{
                    \begin{tcolorbox}
                        \centering
                        \TextField[name=animatetxt, height=0.35cm, width=0.5cm, readonly=true]%
                            {Animation:}
                        \strut
                    \end{tcolorbox}
                } &
                \PushButton[name=step, bordercolor=white]{
                    \begin{tcolorbox}
                        \centering
                        Next step\strut
                    \end{tcolorbox}
                } \\
                \PushButton[name=shapemode, bordercolor=white]{
                    \begin{tcolorbox}
                        \centering
                        \TextField[%
                            name=shapemodetxt, height=0.35cm, width=0.5cm, readonly=true%
                        ]{Shape mode:}
                        \strut
                    \end{tcolorbox}
                } &
                \begin{tcolorbox}
                    \centering
                    \ChoiceMenu[%
                        name=shapeidx, height=0.35cm, width=0.5cm, combo, commitonselchange=true]%
                            {Shape name:}{%
                        One, Block, Beehive, Loaf, Boat, Tub,%
                        Blinker, Toad, Beacon, Pulsar, Pentadecathlon,%
                        Glider, Light-weight spaceship, Middle-weight spaceship,%
                        Heavy-weight spaceship%
                    }%
                    \strut
                \end{tcolorbox} \\[-0.5cm]% TODO why do we need -0.5 here
                \PushButton[name=fillrnd, bordercolor=white]{
                    \begin{tcolorbox}
                        \centering
                        \ChoiceMenu[name=percentage, height=0.35cm, width=0.5cm, combo,%
                            commitonselchange=true]{Fill random with \% alive:}{%
                            20, 40, 60, 80,%
                        }%
                        \strut
                    \end{tcolorbox}
                } &%
                \begin{tcolorbox}
                    \TextField[name=currstep, width=\linewidth, readonly=true]{}
                \end{tcolorbox} \\[-0.5cm]% TODO why do we need -0.5 here
                \PushButton[name=clear, bordercolor=white]{
                    \begin{tcolorbox}
                        \centering
                        Clear\strut
                    \end{tcolorbox}
                } &
                \begin{tcolorbox}
                    \TextField[name=info, width=\linewidth, readonly=true]{}
                \end{tcolorbox}
            \end{tabularx}
        \end{center}

        \TextField[bordercolor=white, name=tooltiptxt, readonly=true]{}

    \end{Form}

\end{document}


\documentclass[final]{siamltex}

\usepackage{hyperref} %BUG if put after
\usepackage{url}

\usepackage[english]{babel}

\usepackage{amsmath,amssymb} % define this before the line numbering.
\usepackage{xcolor}
\usepackage{gpeyre}
\usepackage{array}% http://ctan.org/pkg/array
\usepackage{rotating}
\usepackage{graphicx}

\DeclareGraphicsExtensions{.png,.pdf,.eps,.jpg}
\graphicspath{{./images/}}

\hypersetup{
   bookmarks=true,
   backref=true,
   pagebackref=false,
   colorlinks=true,
   linkcolor=blue,
   citecolor=red,
   urlcolor=blue,
   pdftitle={Regularized Optimal Transport},
   pdfauthor={S. Ferradans et al.},
   pdfsubject={Regularized Optimal Transport}
}

% vector with one
\newcommand{\U}{\mathbb{I}}
\newcommand{\vU}{{\mathcal I}}
% permutation set
\newcommand{\Perm}{\Pp}
\newcommand{\Bin}{\Bb}
% convexficiation of this set
\newcommand{\Matr}{\Ss}
% regularity penalty (L1, L1-L2, L2)
\newcommand{\regul}[1]{J_{p,q}(#1)}

% cost matrix (depends on the point set)
\newcommand{\cost}{C}
\newcommand{\Cost}[2]{ \cost_{#1,#2} }

% todo list
\newcommand{\todo}[1]{\textbf{TODO:} \textit{#1}}

\title{Regularized Discrete Optimal Transport}

\author{Sira Ferradans\footnotemark[1]
		\and
		Nicolas Papadakis\footnotemark[2]
		\and~\\
        Gabriel Peyr\'e\footnotemark[1]
        \and
        Jean-Fran\c{c}ois~Aujol\footnotemark[2] \ \footnotemark[3]
        }

\begin{document}

\maketitle

\renewcommand{\thefootnote}{\fnsymbol{footnote}}

\footnotetext[1]{CEREMADE, Universit\'e Paris-Dauphine, Place du Marechal De Lattre De Tassigny, 75775 PARIS CEDEX 16, FRANCE.}
\footnotetext[2]{IMB, UMR 5251, Universit\'e Bordeaux 1, 351 cours de la Lib\'eration F-33405 TALENCE, France}
\footnotetext[3]{Member of Institut Universitaire de France.}

\input{sections/sec-intro}
\input{sections/sec-transport}
\input{sections/sec-relaxed}
\input{sections/sec-regularized}
\input{sections/sec-applications}
\input{sections/sec-barycenters}
\input{sections/sec-application-bary}
\input{sections/sec-conclusion}

\section*{Acknowledgements}
The authors would like to thank Julien Rabin for advises on color transfer, stimulating discussions and comparison results.
S. Ferradans and G. Peyr\'e have been supported by the European Research Council (ERC project SIGMA-Vision) and the French National Research Agency (project NatImages).
 J-F. Aujol and N. Papadakis have carried out this study in the frame of “the Investments for the future” Programme IdEx Bordeaux – CPU (ANR-10-IDEX-03-02).
N. Papadakis also acknowledges partial support from the French Agence Nationale de la Recherche (ANR, Project TOMMI) under reference ANR-11-BS01-014-01.

%\label{app:perComponent}

\bibliographystyle{siam}
\bibliography{refs}
\end{document}


% --- [ Recovery of Pre-test Loops ] -------------------------------------------

\subsection{Recovery of Pre-test Loops}
\label{sec:recovery_of_pre_test_loops}

The control flow recovery results of the Hammock method, the Interval method, and for comparison the theoretical optimum when recovering \textit{pre-test loops} (e.g. \texttt{while}-loops) from the combined test programs of Coreutils and SQLite are presented in figure \ref{fig:total_results_pre_loop}.

The \textbf{Hammock method} correctly recovered $29.09\%$ of the pre-test loops present in the test programs (\textit{true positives}). On average, for every $10$ pre-test loops of the original source code, the Hammock method recovered $0.1$ pre-test loops that were \textit{not} present of the original source code (\textit{false positives}).

The \textbf{Interval method} correctly recovered $75.07\%$ of the pre-test loops present in the test programs (\textit{true positives}). On average, for every $10$ pre-test loops of the original source code, the Interval method recovered $4.7$ pre-test loops that were \textit{not} present of the original source code (\textit{false positives}).

Note, at this level of comparison, \textit{pre-test loops} and \textit{infinite loops} are both regarded as pre-test loops. Both the Hammock method and the Interval method distinguish pre-test loops from infinite loops. However, the C parsing script described in step \ref{itm:step_c_to_json} of section \ref{sec:evaluation_process} does not evaluate loop conditions, and can therefore not conclusively determine which conditions are always true (e.g. \texttt{while (TRUE)}). For this reason, no distinction is made between pre-test loops and infinite loops during the evaluation.

\begin{figure}[htbp]
	\centering
	\includegraphics[width=\textwidth]{inc/5_results/results_pre_loop.png}
	\caption{Comparison of control flow recovery results for each method when recovering \textit{pre-test loops}. The data is based on the combined test programs of Coreutils and SQLite.}
	\label{fig:total_results_pre_loop}
\end{figure}


\documentclass[11pt, letterpaper, twoside, final]{article}
\usepackage{risk_price_inference}
\addbibresource{riskpriceinference.bib}

\title{Characterizing the Structure of the Identification Problem in Continuous-Time}
\author{Paul Sangrey}

\begin{document}

\maketitle

To fully understand the price of volatility risk we need to understand how the physical change of measure
caused  by switching between $\F_t$ and $\F_{\sigma^2,t}$ interacts with the measure change caused from switching
between $\PP$ and $\QQ$.
Moving forward we will rely on a  specification for risks that depends exclusively on the mean and volatility
(i.e.\@ the first two moments.)
If higher moments, such as skewness and kurtosis are also priced factors, as in \textcites{harvey2000conditional,
conrad2012exante, chang2013market},  and we used higher sample moments as well to determine the price of our
risk-factors our resulting estimates would be biased, likely substantially so.

The question facing us is how to we prevent our model's potential misspecification regarding the risk prices of
higher-order moments from affecting our estimates of the volatility prices.
To answer this question, we turn to what our model specifies the continuous-time process, that our model is a
discretization of.

Imposing consistency with a continuous-time model is reasonable in our context because even though our model is
specified in discrete-time it is for an asset that is is continuously tradable.
A good discrete-time model for a continuously-tradable asset would is consistent with a continuous-time
generalization that rules our no-arbitrage.

Instead of using the log-Laplace transform as we did in discrete-time, we will tackle the change of measure
induced by the change of filtration for the log-price directly.
We will do by inducing some functions $\psi(t)$ and $\phi(t)$ which control the drift and volatility of $p(t)$
under $\F_{\sigma^2,t}$.
To be concrete, we will show that you can represent the log-price with respect to $\F_{\sigma^2,t}$ as follows,
where $\widetilde{M}_{\sigma}(t)$ has mean zero, and predictable quadratic variation  $t$.

\begin{restatable}[Log-Price Given Future Volatility]{theorem}{priceDGPGivenVol}
    \label{defn:logPriceGivenVol}

    Assume that volatility is an It\^{o} semimartingale without any predictable jumps, and the prices can be
    represented as follows.
    Further assume that all of the prices are locally-square integrable, and have the following representation.

    \begin{equation}
        \dif p(t) = \gamma(t) + \beta(t) \sigma^2(t) + \sigma(t) \sqrt{1 - \phi(t)^2} \dif W^p(t) + \phi(t)
        \sigma(t) \dif W^{\sigma}(t)
    \end{equation}

    Then we can represent the prices progressively enlarged by $\lim_{\Delta \to 0^{+}} \sigma(t + \Delta)$ for
    each $t$ as follows.

    \begin{equation}
        \label{eqn:eqn:price_process_decomp}
        \dif p(t) = \gamma(t) + \beta(t) \sigma^2(t) + \psi(t) \sigma^2(t) + \sigma(t) \sqrt{1 - \phi(t)^2} \dif
        W^p(t)
    \end{equation}

\end{restatable}

The structure here closely mimics the discrete-time structure in \textcite{khrapov2016affine}.
The two key differences are that it is on continuous-time, obviously, and that it is an exact nonparametric
representation.
Their representation only holds under some parametric assumptions, and so their discussion of identification is
parametric.

The $\psi(t)$ parameter governs how the drift changes once we condition on the volatility in the immediate
future.
To see this more fully consider the following, where we assume $\psi(t)$ and $\beta(t)$ are constant.
Note, $F_{t+1, \sigma^2}$ conditions on the entire path of volatility from $t$ to $t+1$.

\begin{align}
    &\phantom{=} \E_{\PP}\left[r_{t+1} \mvert \F_{t}\right]  - \E_{\PP}\left[\E_{\PP}\left[r_{t+1} \mvert \F_{t+1, \sigma^2} \right]
      \mvert \F_t \right]  \\
      %
      \intertext{Then by the law of iterated expectations.}
      %
    &=  \E_{\PP}\left[\beta(t) \sigma^2_{t+1} - \beta(t) \sigma^2_{t+1} + \psi \sigma^2_{t+1}  \mvert \F_t \right] \\
      \label{eqn:change_in_expected_rtn}
      &= \psi \E_{\PP}\left[\sigma^2_{t+1} \mvert \F_t \right]
\end{align}

The parameter $\phi(t)$, on the other hand, governs the correlation between $p(t)$ and $\sigma^2(t)$.
Consider their predictable quadratic variation of the part of the precises that is orthogonal to $\sigma^2(t)$.

By properties of Gaussian conditioning, we can split the Wiener process driving $p(t)$ into two parts.
One that drives $\sigma^2(t)$ --- $W^{\sigma}t)$ and one that is independent of $\sigma^2(t)$ --- $W^p(t)$.
Consequently, we can write the price process, with respect to $\F_t$ as follows.

\begin{equation}
    \predQV*{p(t), \sigma^2(t)}
    = \predQV*{\int^t_0 \phi(t) \sigma(t) \dif W^{\sigma}, \int^t_0 \sigma_{\sigma} \dif W^{\sigma}}
    = \int^t_0 \phi(s) \sigma(s) \sigma_{\sigma}(s) \dif s
\end{equation}

If all of the functions are  constant then the correlation between the price's and the volatility's diffusion part
is $\phi$, i.e.\@  $\mathrm{corr}\,(p(t), {\sigma^2(t)}^D) = \phi$.

\
In this section, we have the following two continuous-time processes.
The goal is to show that by using the first-two conditional moments in our identification strategy, the parameters
we are estimating converge to the true equity risk and volatility risk even in the presence of higher-order
time-variation in the price processes.
Our moment conditions we use in the estimation project the risk prices onto the information set generated by
$\E\left[r_{t+1}\mvert \F_{t-1}\right]$  and $\E\left[\sigma^2_{t-1} \mvert \F_{t-1}\right]$.
What we do here is the equivalent projection in population.
This procedure will give us a series of estimates $\hat{\pi}, \hat{\theta}$, etcetera.
These estimates will have some limiting values, as long as the moment conditions are sufficiently non-collinear.
This section characterizes precisely the role these limiting values play in population.
For example, we show that the risk-prices are the actual risk prices under some conditions, which we make
explicit.

The way by which we do this is by representing the processes in continuous-time.
Since the assets we are characterizing are continuously tradable they must satisfy some continuous-time
no-arbitrage conditions.
In other words, there exists a continuous-time DGP where the DGP we have been using so far is a discretization of.
This is useful because we can work with the first two moments of the process effectively without loss of
generality.
The linear-affine structure we have been using before will show up as certain terms being constant functions of
time in what follows.
The cost of doing this is that it requires more involved notation and more sophisticated mathematical tools.

It is not entirely obvious that volatility risk premia is even a well-defined concept if neither the volatility
nor the price process itself jumps.\footnote{In general, the predictable projection of the instantaneous
    volatility $\sigma^2(t-)$ is measurable with respect the filtration generated by the data $\F_t$. In addition,
    if both $\sigma^2(t)$ and $p(t)$ are continuous processes, their filtrations are predictable as well: $\F_t =
    \F_{t-}$. Consequently, all of four o the relevant filtrations coincide. Hence, changing filtrations is
    possible. It is not obvious how volatility risk and market risk can be distinguished if conditioning on
    volatility at time $t$ does not change the information set from $\F^p_{t-}$. The discrete-time
characterization of volatility risk is doing precisely this by using the log-Laplace transform.}
Consequently, we will adapt the following continuous-time data-generating process (DGP)
This is arguably the simplest DGP that allows for us to discuss these issues.
We follow \textcite{sangrey2018jumps} in modeling the jumps as an integral with respect to a variance-gamma
process.
The constraint that $\sigma^2(t) > 0$, will imply some dependence between $\sigma^2(t), \sigma_{\sigma}(t)$, and
$\gamma_{\sigma}(t)$, which we do not rule out.

\begin{defn}{Continuous-Time DGP}
    \label{defn:cont_time_dgp}

    \begin{align}
        \dif p(t) &= \gamma(t) \dif t + \beta(t) \sigma^2(t-) \dif t + \sigma(t) \dif W(t)  \\
        \dif \sigma^2(s)  &= \mu_{\sigma}(t) + \sigma_{\sigma}(t) \dif W_{\sigma}(t) +
        \frac{\gamma_{\sigma}(t)}{\sqrt{2}} \dif \Lap(t)
    \end{align}

\end{defn}

The other complication with \cref{defn:cont_time_dgp}, is that we split the drift into two parts $\gamma(t)\dif t$
and $\beta(t) \sigma(t-) \dif t$.
All of the terms here are finite-variation predictable processes.
It is not immediately obvious how to separate out $\gamma(t)$ and $\beta(t)$.
To get the correct discrete-time interpretation of the integrals of these processes, you can take the predictable
finite-variation (drift) of the ordinal process and project it onto $\sigma^2(t)$ without an intercept.
You can then define $\beta(t)$ to be the coefficient from this regression and $\gamma(t)$ to be the residual.
Intuitively, we are separating out the part of price drift driven by expectations of vitality from other sources
of variation.

We now define the relevant filtrations.
We will continue to use $\F_t$ to be the filtration generated by $p(t)$.
We will use $\F_{t-}$ to be the predictable filtration associated with $\F_t$, i.e.\@ the filtration generated by
the predictable processes adapted to $\F_t$.
In addition, we will define $\F_{\sigma^2, t}$ to be $\F_t$ augmented by the right-limits of the volatility.
You can view it as $\lim_{\Delta to 0} \F_t \cup \F^{\sigma^2}_{t+\Delta}$, where $\F^{\sigma^2}_t$ is the
filtrated generated by $\sigma^2(t)$.
In other words, we will look infinitesimally far into the future path of $\sigma^2(t)$ and add that information to
our filtration.

This is the continuous-time analogue of adding $\int_t^{t+1} \sigma^2(s) \dif s$ to your $\F_t$ information set.
In both cases you are adding the value of the volatility in the \textquote{next period} to the current information
set.
Another way to view this expansion of filtration is that in $\F_t$, $\int^t_{-\infty} \sigma^2(s) \dif s$ is an
optional process, and we are constructing the minimal filtration that makes $\int^t_{-\infty} \sigma^2(s) \dif s$
predictable.\footnote{The progressive enlargement of the filtrations we are considering is an augmentation of
    $\F_t$ with a series of honest times, since $\F^{\sigma^2}_{t}$ is generated by a left-continuous processes.
    Consequently, all of the adapted processes to $\F_t$ are semimartingales with respect to $\F_{\sigma^2,t}$,
    \parencite[Theorem C]{barlow1978study}.  We will further assume that all of the processes maintain the same
stochastic jump-diffusion structure under both filtrations. The relevant technical conditions under which this
structure is preserved is outside this scope of this paper.}

\subsubsection{Going from Continuous-Time to Discrete-Time}\label{sec:discrete_time_to_cont_time}

The data that we have are daily, not in continuous-time.
Consequently, we need to consider what the price process in  \cref{eqn:eqn:price_process_decomp} implies about the
daily data.
Thankfully, all of the infinite-activity components are independent by construction.
Consequently, we can time-aggregate \cref{eqn:eqn:price_process_decomp}, and get the following formula for the
discrete-time returns.
We can then use those returns to characterize the identification problem.
We can define the returns with respect to the following two filtrations.
First, we define $r_{t+1}$ with respect to the $\F_{t}$ filtration.

\begin{equation}
    \label{eqn:discrete_time_rtn}
    r_{t+1} = \int_t^{t+1} \gamma(s) \dif s + \int_{t}^{t+1} \beta(s) \sigma^2(s) \dif s +
    \int_t^{t+1} \sigma(s) \left[\sqrt{1 - \phi(s)^2} \dif W^{p}(s) + \phi(s) \dif W^{\sigma}(s)\right]
\end{equation}

If we knew the entire path of future volatility, we could use the following equation, where we characterize
$r_{t+1}$ with respect to the $\sigma\left(\F_{t}, \F_{\sigma^2_{t+1}}\right)$ filtration.

\begin{equation}
    \label{eqn:discrete_time_cond_rtn}
    r_{t+1} = \int_t^{t+1} \gamma(s) \dif s + \int_{t}^{t+1} [\beta(s) + \psi(s)] \sigma^2(s) \dif s +
    \int_t^{t+1} \sigma(s) \sqrt{1-\phi(s)^2} \dif W^{p}(s)
\end{equation}

In both \cref{eqn:discrete_time_rtn} and \cref{eqn:discrete_time_cond_rtn}, we have the random functions
$\gamma(t), \beta(t), \psi(t), \phi(t)$.
In addition, in we also condition on the entire path of future volatility in \cref{eqn:discrete_time_cond_rtn}
instead of just $\int_t^{t+1} \sigma^2(s) \dif s$.

However, since we are using long time-span asymptotics, and not infill asymptotics, the model we end up estimating
will have fixed parameters instead of continuous-time processes for each of these parameters.

%TODO Added assumption here.
We start by defining the means of $\gamma_0, \beta(t), \psi(t)$, and $\phi(t)$: $\gamma_0, \beta_0, \psi_0, \phi_0$.
We assume that all of the processes are ergodic and so time and cross-sectional means are the same.

%TODO Added assumption here.
By the intermediate value theorem, assuming the predictable functions are continuous, there exists an
$s_i^{\dagger}$ for each of these functions that function evaluated at $s^{\dagger}$ equals the mean over the
interval.
For example $\beta\left(s_i^{\dagger}\right) = \int_0^{\infty} \beta(s) \dif s$.
We can take mean value expansions for each of these functions.

\begin{alignat}{1}
    \label{eqn:price_decomp}
    \left. r_{t+1} \mvert \F_t \right.
    %
    &= \gamma_0 + \beta_0 \E_{\PP}\left[\int_t^{t+1} \sigma^2(s) \dif s \mvert \F_t\right] + \int_t^{t+1} \sigma(s)
       \left[\sqrt{1 - \phi_0^2} \dif W^{p}(s) + \phi_0 \dif W^{\sigma}(s)\right] + \eta_{1,t+1} \\
    \left. r_{t+1} \mvert \F_t, \sigma^2_{t+1} \right.
    %
    &= \gamma_0 + (\beta_0 + \psi_0) \int_t^{t+1} \sigma^2(s) \dif s + \int_t^{t+1} \sigma(s) \sqrt{1-\phi_0^2}
       \dif W^{p}(s) + \eta_{2, t+1}
\end{alignat}

To show identification of our results, we need to characterize the error terms in the expression above.
In particular, we need to show that they are mean-zero and conditionally mean-independent.
We can compute what the error terms are by adding and subtracting the relevant terms.

\begin{alignat}{1}
    \eta_{1,t+1}
    &= \int_t^{t+1}(\gamma(s) - \gamma_0) \dif s + \E_{\PP}\left[\int_t^{t+1} (\beta(s) - \beta_0) \sigma^2(s) \dif s
        \mvert \F_t\right] \\
    &+ \int_t^{t+1} \sigma(s) \left[\left(\sqrt{1 - \phi(s)^2} - \sqrt{1 - \phi_0^2}\right) \dif W^{p}(s) +
        \left(\phi(s) - \phi_0\right) \dif W^{\sigma}(s)\right] \nonumber \\
%
    \eta_{2,t+1}
    &= \int_t^{t+1}(\gamma(s) - \gamma_0) \dif s + \int_t^{t+1} (\beta(s) + \psi(s) - (\beta_0 + \psi_0))
       \sigma^2(s) \dif s \\
    &+ \int_t^{t+1} \sigma(s) \left(\sqrt{1 - \phi(s)^2} - \sqrt{1 - \phi_0^2}\right) \dif W^{p}(s) \nonumber
\end{alignat}

Clearly, all of the terms are  unconditionally mean zero.
The non-martingale terms are deviations from their global means, and the martingale terms are martingales.
To get them to be conditionally zero, we need to work a little harder.

Assume that the prices of volatility and market risk and the dependence of volatility on its past are fixed over
time.
That implies that approximate log-Laplace transform studied in \cref{sec:dynamics} is fixed.
Consequently, the $\gamma_0, \beta_0$, etc.\ functions are valid means for each day, e.g.\@ $\E_{\PP}\left[\int_t^{t+1}
\gamma(t) \mvert \F_t \right] = \gamma_0$.
Note, the length of the day does not entire in here because it equals $1$.

\begin{equation}
    \label{eqn:cond_zero_err_terms}
    \E_{\PP}\left[\eta_{i,t+1} \mvert \F_{t}\right] = 0
\end{equation}

The only question then is if the $\eta_{i,t+1}$ are correlated with the regressors.
If we were to use $\sigma^2_{t+1}$ directly as a regressors, they would be.
Consequently, we will solve this using the standard method --- instruments.
We have a collection of $Z_{i,t}$ that are $\F_t$ measurable, but correlated with $\sigma^2_{t+1}$.
Since $Z_{i,t+1} \in \F_t$, \cref{eqn:cond_zero_err_terms} implies they satisfy the necessary orthogonality
condition.
Any good predictor of $\sigma^2_{t+1}$ will satisfy this criterion.
In the empirical example, we will use lags of $\sigma^2_{t+1}$.

\begin{appendices}

\priceDGPGivenVol*

\begin{proof}

    We work directly with the martingale part of the price, $\sigma(t) \dif W(t)$, the drift part can just be
    added back to the price when we are finished because it is predictable.

    To model the additional information in a tractable way, consider a dense discrete grid of points over $\R$ ---
    the magnitudes of the prices.
    Define a set of times $\lbrace \tau_i\rbrace $ such that $\tau_i$ is the time at which the volatility crosses
    the $i$\textsuperscript{th} point, but not the $(i+1)$\textsuperscript{th} one.
    Note, since equality at a discrete dense set of points is sufficient to imply equality over any open set,
    equality over $\lbrace \tau_i \rbrace$ is sufficient for equality in probability since the opens sets generate
    the Borel measure.

    Now, each $\tau_i$ is an honest time with respect to the $\F_{t=\tau_i-}$ filtration, but not a stopping time
    because it is not contained within the $\F_{\tau_i-}$ filtration.
    Define $\F_{\sigma,t} \coloneqq \F_{\sigma, t+} \cap \sigma\left(\lbrace \tau_i \rbrace\right)$.
    Clearly, there is only one $\tau_i$ in that filtration, which we will refer to as $\tau$ in the sequel.

    We are augmenting the predictable filtration $\F_{t-}$ with an honest time --- $\tau$.
    Since, $p(t)$ is adapted to $\F_{t-}$, we can use formulas for augmenting the price with an honest time.
    Also, since there are at most countably many jumps and the prices and volatilities are locally square
    integrable, there is at most one jump in $\sigma^2(t)$ that is measurable with respect to $\F_{\sigma, t+}$.

    Since $\sigma^2(t)$ has no predictable jumps, $\tau$ avoid all stopping times of $\F_{t-}$.
    Hence, the optional and predictable projections coincide, and we can choose the following quantities to be
    continuous.
    Let $A^{\tau}(t)$ be the predictable projection of the process $1\lbrace \tau \leq t \rbrace$, define the
    c\'{a}dl\'{a}g martingale $\mu^{\tau}(t) \coloneqq \E_{\PP}\left[A^{\tau}(\infty) \mvert \F_{t-}
    \right]$.
    Then by \textcite[eqn 2.3]{nikeghbali2007nonstopping}, we can write the martingale part of the process stopped
    at $\tau$  as follows, where $M(t)$ is a martingale.

    \begin{align}
        \label{eqn:filtration_changed_martingale}
        \int_0^{t \wedge \tau} \sigma(s)  \dif W(s)
         &= M(t) + \int_0^{t \wedge \tau} \frac{1}{\Pr\left(\tau > s
            \mvert \F_{s-}\right)} \dif \predQV*{\int_0^s \sigma(u) \dif W(u), \mu^{\tau}(s) }
%
            \intertext{Since drifts do not affect quadratic variation and $\mu^{\tau}(t)$ is continuous. }
%
        &= M(t \wedge \tau) + \int_0^{t \wedge \tau} \frac{1}{\Pr\left(\tau > s \mvert \F_{s-}\right)} \dif
          \predQV*{\int_0^t \sigma(s) \dif W(s), \sigma_{\mu} \dif W^{\mu}(s)} (s)  \\
    %
        &= M(t \wedge \tau) + \int_0^{t \wedge \tau} \frac{\sigma(s) \sigma_{\mu}(s)}{\Pr\left(\tau > s \mvert
           \F_{s-}\right)} \dif s
    \end{align}

    We now let $\psi(t) \coloneqq \frac{\sigma_{\mu}(s) }{\Pr\left(\tau > s \mvert \F_{s-}\right)}$.
    Then we can write the drift as $\E_{\PP}\left[\dif p(t) \mvert \F_{t-}\right] = \psi(t) \sigma(s)$.

    In addition, $M(t)$ has some predictable quadratic variation that we assume is absolutely continuous.
    We will define $\phi(t)$ so that its diffusion part --- $M^D(t)$ -- has the appropriate relationship with the
    prices.
    Define $\phi(t) \coloneqq \frac{\dif \predQV*{M}(t)}{\sigma_{\sigma}(t)}$.

    $M(t)$ is still a martingale in $\mathcal{G}(t)$, which is the smallest filtration satisfying the standard
    conditions that is generated by the prices augmented with $\F_{t-}$.
    In addition, since $\predQV{M}(t)$ is predictable, and hence $\F_{t-}$ measurable, we can choose its
    instantaneous variance to be same in the two different filtrations.

    Martingales in a larger filtration are still martingales in a smaller filtration.
    Consequently, $M(t)$ is still a martingale in $\mathcal{G}(t)$.
    However, since only predictable processes are measurable with respect to $\mathcal{G}(t)$.
    Consequently, $M(t)$ is a predictable martingale, implying it has a continuous version.

    Hence $\predQV*{M}(t) <= \predQV*{p(t) \perp \sigma^2(t)}$ because conditioning in Gaussian environments does
    not decrease the variance.
    The reverse inequality holds because $p(t) \perp \sigma^2(t)$ is still a martingale in $\F_{\sigma,t}$.
    Consequently, the two processes are equivalent.

    Since $p(t) \perp \sigma^2(t) = \int^t \phi(s) \dif W^{p}(s)$, the result follows.

\end{proof}

\end{appendices}

\end{document}


%!TEX root = index.tex

\title{Symmetries \& Polynomials}
\author{\small{Apurva Nakade}}
\date{}
\maketitle
\section{Introduction}

A very natural question that one comes across very frequently in mathematics is:
  \begin{quote}
    \textbf{Q.} Given a polynomial $ p(x)$ find (all of) it's roots.
  \end{quote}
Mathematicians are especially interested in finding solutions which can be described using only algebraic operations like arithmetic operations and radicals $ \sqrt[n]{-}$. \\

When $ p(x)$ has degree 2 this is elementary. When $ p(x)$ has degree 3 or 4 the algebra is more complicated but still quite elementary. In practice it might not be possible to do this by hand but you could, for example, write a program to do it for you.\\

It then came as a big surprise then when Abel-Ruffini showed that there exists polynomials of degree 5 (quintic) which cannot be solved using radicals! Galois extended the theory further and explained the underlying reason using symmetry groups. (The wikipedia article on Galois theory is worth reading and it describes the interesting historical developments quite well.)\\

In this course we'll look at the solutions of a cubic (degree 3) and a quartic (degree 4) using methods inspired from Galois theory and then provide an introduction to the underlying theory. Galois' work as we understand it today established a connection, called \emph{Galois correspondence}, between two seemingly unrelated mathematical structures called \emph{fields} and \emph{groups}. The ``easier'' of these two is the theory of \emph{symmetry groups} which we'll explore as much or as little as time permits. There are no well-defined goals in this course.\\\\

\noindent \textbf{How to use these notes:}
These notes are meant for students who do not have any knowledge of group theory. Not everything in these notes is mathematically correct but the errors are there to minimize the length and keep the notes elementary.

Each page contains problems that you should solve before moving on to the next as the following pages sometimes contain answers to the questions on the previous pages.


\begin{algorithm}[H]
    \caption{Solve Sub model}\label{algo:solve-submodel}
    \begin{algorithmic}[1]
        \REQUIRE $submodel: \text{Submodel from \Cref{algo:submodel-build}},\ time: \text{Time limit}$
        \STATE {$lin\_model = MIPSolver::NewLP(submodel,\ time);$}
        \STATE {$lin\_solution,\ status = lin\_model.solve(); $}
        \IF {$ status\ \textbf{is}\ OPTIMAL $}
            \STATE $int\_model = MIPSolver::NewMIP(submodel,\ time);$
            \STATE $int\_model.solution\_count(1);$
            \STATE $int\_sol, status = lin\_model.solve();$
            \IF {$ status\ \textbf{is}\ INFEASIBLE $}
                \RETURN {$lin\_solution,  LIN\_FEASIBLE$}
            \ELSIF{$ status\ \textbf{id}\ TIMEOUT $}
                \RETURN {$\emptyset, TIMEOUT $}
            \ELSE
                \RETURN {$lin\_solution,  INT\_FEASIBLE$}
            \ENDIF
        \ELSE
            \RETURN {$\emptyset,  INFEASIBLE$}
        \ENDIF
    \end{algorithmic}
\end{algorithm}

\paragraph{Description} \Cref{algo:solve-submodel} requires as input a valid submodel, from \Cref{algo:submodel-build} and the current time limit. The module $MIPSolver$
is an abstraction of a general purpose MIP solver, it has two constructors:
\begin{itemize}
    \item NewLP : create a \emph{Model} object from the sub model, with the specified time limit. All integer constraints are ignored.
    \item NewMIP: create a \emph{Model} object from the sub model, with the specified time limit. All integer constraints are preserved.
\end{itemize}

This \emph{Model} object has the \emph{solve} method. This method solves the problems according to the model configuration, for example time limit or solution count limit.
\emph{solve} return two values: the first one is the model solution (i.e. a \href{https://en.wikipedia.org/wiki/Associative_array}{dictionary}),
the second is the optimization
status. The possible output\footnote{The actual MIP solver may support more than this statuses, but those are the strictly required to implement Feature Kernel } statuses are:
\begin{enumerate}
    \item OPTIMAL: the optimization ended with a proven optimal result,
    \item INFEASIBLE: the model is infeasible,
    \item TIMEOUT: the optimization took more then the given timeout
    \item SOLUTION\_COUNT: the optimization found the maximum number of feasible solution, but is not possible to prove that one of this solutions is optimal.
\end{enumerate}

Notice that the statuses from the MIP solver and the statuses returned by \Cref{algo:solve-submodel} are not the same: statuses from \Cref{algo:solve-submodel} can be
considered as inner constants.

The possible outcomes are straightforward as described in \Cref{sec:submodel-result}, according to the optimization status \Cref{algo:solve-submodel} returns the current
solution (if available) and the appropriate status.


Input to the Storage (STO) Package is read from the file that has type ``STO6'' in the Name File.  If the STO Package is not included for a model, then storage changes will not be calculated, and thus, the model will be steady state.  Only one STO Package can be specified for a GWF model.

\vspace{5mm}
\subsubsection{Structure of Blocks}

\vspace{5mm}
\noindent \textit{FOR EACH SIMULATION}
\lstinputlisting[style=blockdefinition]{./mf6ivar/tex/gwf-sto-options.dat}
\lstinputlisting[style=blockdefinition]{./mf6ivar/tex/gwf-sto-griddata.dat}
\vspace{5mm}
\noindent \textit{FOR ANY STRESS PERIOD}
\lstinputlisting[style=blockdefinition]{./mf6ivar/tex/gwf-sto-period.dat}

\vspace{5mm}
\subsubsection{Explanation of Variables}
\begin{description}
\input{./mf6ivar/tex/gwf-sto-desc.tex}
\end{description}

\vspace{5mm}
\subsubsection{Example Input File}
\lstinputlisting[style=inputfile]{./mf6ivar/examples/gwf-sto-example.dat}