% This file was converted to LaTeX by Writer2LaTeX ver. 1.4
% see http://writer2latex.sourceforge.net for more info
\documentclass[a4paper]{article}
%\usepackage[latin1]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[english]{babel}
\usepackage{amsmath}
\usepackage{amssymb,amsfonts,textcomp}
\usepackage{color}
\usepackage{xcolor,colortbl}
\usepackage{sectsty}
\usepackage{tocloft}
\usepackage{fancyhdr}
\usepackage{afterpage}
\fancyhf{}
\usepackage{lastpage}
\usepackage{datetime}
\usepackage{colortbl}
\usepackage{array}
%\usepackage[top=0.7882in,bottom=0.4917in,left=1.25in,right=1.25in,nohead,includefoot,foot=0.5083in,footskip=0.97720003in]{geometry}
\usepackage[headheight=110pt]{geometry}
%\usepackage{supertabular}
\usepackage{hhline}
\usepackage{caption}
\usepackage{hyperref}

\usepackage{graphicx}
\usepackage{verbatim}
\pagestyle{fancy}
%\usepackage{titlesec}
\afterpage{\cfoot{\thepage}}

%new packages & rules
\linespread{1.1} % Definition of the linespread
%\usepackage[square,sort,comma,numbers]{natbib}
\usepackage{amsmath}
\usepackage{amssymb}
\mathchardef\mhyphen="2D % Define a "math hyphen"
\usepackage{amsthm}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{amsthm}

\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{amsthm}
\theoremstyle{definition}
\newtheorem{definition}{Definition}
\newtheorem{example}{Example}

%\usepackage{eufrak}
\newcommand{\R}{\mathbb{R}}
\newcommand{\N}{\mathbb{N}}
\usepackage[ruled,vlined,noend]{algorithm2e}
\usepackage{natbib}
\usepackage{pgf}
\usepackage{tikz}
\usetikzlibrary{arrows,automata}
% to start new page for each new section
%\titlespacing*{\section}
%{0pt}{6.5ex plus 1ex }{6.3ex plus .2ex}
%\titlespacing*{\subsection}
%{0pt}{6.5ex plus 1ex }{6.3ex plus .2ex}

%\allsectionsfont{\centering}
\setlength{\headsep}{0.2in}

%\newdateformat{bkdate}{\twodigit{\THEDAY}-\twodigit{\THEMONTH}-\twodigit{\THEYEAR}}
%\dmyydate

\definecolor{datacroninner}{rgb}{0.0,0.0,0.5647059}
\newcommand{\datacroncolor}{\color{datacroninner}}
\chapterfont{\datacroncolor}  % sets colour of chapters
\sectionfont{\datacroncolor}  % sets colour of sections
\subsectionfont{\datacroncolor}  % sets colour of sections
\subsubsectionfont{\datacroncolor}
\hypersetup{colorlinks=true, linkcolor=datacroninner, citecolor=datacroninner, filecolor=datacroninner, urlcolor=blue}

\newcommand{\documenttitle}{\ Master Thesis Proposal}
%\newcommand{\horizongeneral}{\ H2020-ICT-2015 \dmyydate \today}
%\lhead{\includegraphics[width=122pt]{figures/datACRONDXYTemplate201512162-img001.png}}
\chead{\documenttitle}
%\rhead{\horizongeneral}
\lfoot{}
\fancyfoot[C]{Page \thepage \hspace{1pt}}
%\cfoot{Page \thepage \hspace{1pt} of \pageref{LastPage}}

\cfoot{Page \thepage}
\rfoot{}

%\makeatletter
\newcommand\arraybslash{\let\\\@arraycr}
%\makeatother
% Footnote rule
\setlength{\skip\footins}{0.0469in}
\renewcommand\footnoterule{\vspace*{-0.0071in}\setlength\leftskip{0pt}\setlength\rightskip{0pt plus 1fil}\noindent\textcolor{black}{\rule{0.0\columnwidth}{0.0071in}}\vspace*{0.0398in}}
\setlength\tabcolsep{1mm}
\renewcommand\arraystretch{1.3}
\newcounter{Table}
\renewcommand\theTable{\arabic{Table}}

\title{\documenttitle}
\author{Ehab Qadah \\\\Supervisor:
	PD Dr. Michael Mock}
\date{\dmyydate \today}
\begin{document}
\pagestyle{fancy}
\newcommand{\sectionbreak}{
\clearpage{\pagestyle{fancy}}}

\pagenumbering{gobble}

%\cfttoctitlefont{\datacroncolor}
%

%\title{\Huge Grant Agreement No: 687591}
%{\centering
%\par}
%\clearpage{\pagestyle{fancy}}
%%\setcounter{page}{1}
%\maketitle{\Huge}
%%\centering
%\title{\Large \textbf{ Predicting patterns of moving objects based
%	on contextual information with distributed online learning \\
%Distributed Online Learning for Forecasting Patterns of Moving Objects Events Streams \\
%Distributed Online Learning for Forecasting Patterns in Event Streams of Moving Objects}}
%{\centering
%\Large
%\par}
%\maketitle

%{\centering
%\includegraphics[width=2.5835in,height=0.6634in]{figures/datACRONDXYTemplate201512162-img001.png}
% \par}

%\begin{flushleft}
%\centering
%\begin{tabular}{lm{5.83516in}l}
%\hline
%%\centering
%\title{\documenttitle}
%\maketitle
%\\\hline
%\end{tabular}
%\end{flushleft}

%\begin{flushleft}
%\begin{tabular}{|m{0.25\textwidth}|m{0.75\textwidth}|}
%%\multicolumn{2}{|m{5.8350596in}|}{Deliverable Form}\\\hline
%\rowcolor{datacroninner}
%{\bfseries\color{white}Deliverable Form}& \\\hline
%Project Reference No. &
%H2020-ICT-2015 687591\\\hline
%Deliverable No.  & 8.1\\\hline
%Relevant Work Package: & WP 8\\\hline
%Nature: &R\\\hline
%Dissemination Level: &PU\\\hline
%Document version: &1.0\\\hline
%Due Date: &29/02/2016\\\hline
%Date of latest revision: &16/12/2015\\\hline
%Completion Date: &~\\\hline
%Lead partner: &UPRC\\\hline
%Authors: &
%George Vouros\\\hline
%Reviewers: &~\\\hline
%Document description: &
%This deliverable documents the main project procedures. These procedures have been presented and agreed at the kickoff
%
%meeting chaired by the coordinator.\\\hline
%Document location: &
%Desktop/Projects/datACRON/Project/Dels\\\hline
%\end{tabular}
%\end{flushleft}

%\clearpage

%\section*{HISTORY OF CHANGES}
%\thispagestyle{empty}
%\addcontentsline{toc}{section}{HISTORY OF CHANGES}
%\begin{flushleft}
%\begin{tabular}{|m{1.10in}|m{1.10in}|m{1.10in}|m{1.10in}|m{1.10in}|}
%\hline
%\rowcolor{datacroninner}
%{\bfseries\color{white} Version} &{\bfseries\color{white} Date} & {\bfseries\color{white} Changes} & {\bfseries\color{white} Author} & {\bfseries\color{white} Remarks}\\\hline
%~ &~ &~ &~ &~\\\hline
%\end{tabular}
%\end{flushleft}

%\clearpage

%\section*{EXECUTIVE SUMMARY}
%\addcontentsline{toc}{section}{EXECUTIVE SUMMARY}
%%\clearpage

%\section*{TABLE OF CONTENTS}
%\addcontentsline{toc}{section}{TABLE OF CONTENTS}
%
%
%
%\setcounter{tocdepth}{3}
%\renewcommand\contentsname{}
%\renewcommand{\cfttoctitlefont}{\datacroncolor}
%\tableofcontents
%\section*{TERMS \& ABBREVIATIONS}
%\addcontentsline{toc}{section}{TERMS \& ABBREVIATIONS}
%
%\section*{LIST OF FIGURES}
%\addcontentsline{toc}{section}{LIST OF FIGURES}
%%\cftloftitlefont{\datacroncolor}
%\listoffigures
%\section*{LIST OF TABLES}
%\addcontentsline{toc}{section}{LIST OF TABLES}
%
%\listoftables

\input{title}
\clearpage

\section*{Abstract}

Predicting full matches of complex patterns from various real-time event streams is an important utility for the decision maker in many application domains such as maritime surveillance, financial services, and sensor networks. Such a utility allows him/her to proactively react to the new situations and enhances the operational decision making. An event stream is an unbounded collection of timely ordered data observations in the form of an attribute tuple that is composed of a value from finite event types along with other categorical and numerical features. For example, in the context of maritime surveillance, patterns prediction over real-time tracking streams of moving vessels is useful to alert maritime operation mangers about suspicious activities (e.g., fast sailing vessels near ports) before they happen, in this scenario, the event stream of a moving vessel consists of spatial-temporal and kinematic information along with the vessel's identification and its trajectory related event types. However, processing real-time streaming data is challenging since data streams are large in nature and continuously keep on coming at a high rate.
% we describe the design and implementation of a system called%
\par To this end, in this thesis, we present an online, distributed and scalable patterns prediction system over massive input event streams. The proposed approach is based on a novel approach that combines the  distributed online prediction protocol \citep{kamp2014communication} with the event forecasting with Pattern Markov Chain system\citep{alevizos2017event}, in order to provide an online and large-scale patterns prediction system over distributed real-time event streams.

 \par We leverage an existing online probabilistic forecasting model, which consists of the event forecasting with Pattern Markov Chain~\citep{alevizos2017event}. This system gives the ability to predicate when a pattern within a stream of events will be fully matched. In addition, we integrate the distributed online synchronization protocol \citep{kamp2014communication} to provide distributed online learning capabilities between the prediction models in a communication-efficient manner. This protocol enables us to dynamically synchronize the distributed local prediction models of the multiple input event streams.

  In some practical applications the input event streams may belong to different distributions, we propose to divide the input event streams into similar groups, in order to combine the corresponding predictions models to construct a representative global model in each group. The aggregation operation refers to the synchronization operation (e.g., joint average of the local models) in the distributed online learning protocol, which is performed by a central coordinator that constructs and distributes a global prediction model for the input event streams based on the  local models. In addition, we are using one of the modern Big Data frameworks for stream processing i.e., Apache Flink \footnote{\url{https://flink.apache.org/}} to implement the proposed system.
\par We aim to provide an architecture and implementation of a system for large-scale patterns prediction over multiple input event streams. Our approach exploits the collaborative learning from multiple input streams by combing their associated predication models in a dynamic way.

\par We will analysis and develop the proposed approach, and evaluate the effectiveness through empirical experiments over synthetic event streams and real-word data streams of moving objects, in particular, events streams related to trajectories of moving vessels, which are provided in the context of the datAcron project\footnote{\url{http://www.datacron-project.eu/}}.

%Furthermore, we will try to provide probabilistic guarantees for the new proposed %method by performing theoretical analysis procedures.

{\large\textbf{\\ \\ Acknowledgment\\\\}}
This work is supported by the EU H2020 datAcron project (grant agreement No 6875).

{\large\textbf{\\ Keywords\\\\}}
Big Event Data Streams, Stream processing,Large-scale Patterns Prediction, Maritime Surveillance, Apache Flink, Distributed Pattern Markov Chain\\

\pagenumbering{arabic}
\setcounter{page}{1}
\thispagestyle{fancy}
\input{introduction}
\input{related_work}
\input{implementation}
\input{experimental_evaluation}
\input{work_plan}

%\input{extra_rources}

%{\centering
%\includegraphics[width=4.972in,height=3.5693in]{figures/datACRONDXYTemplate201512162-img002.png}
% \par}
%
%\captionof{figure}{datACRON Overall Architecture }
%
%
%
%\begin{flushleft}
%\begin{tabular}{m{0.48in}|m{3.29in}|m{1.89in}c|}
%\hline
%\rowcolor{datacroninner}
%{\bfseries\color{white}lala}&{\bfseries\color{white} Bla} &{\bfseries\color{white} bla}\\\hline
%1 &~ &~\\\hline
%2 &~ &~\\\hline
%\end{tabular}
%\end{flushleft}

\clearpage
%\nocite{*}
%\bibliographystyle{plain-annote}
%\bibliographystyle{plainnat}
 \bibliographystyle{agsm}
\bibliography{myrefs}
\end{document}


\chapter{Reusing Classes}

In Chapter~\ref{conway}, we developed classes to implement Conway's Game of Life.
%As an exercise, you had a chance to implement Langton's Ant.
We can reuse the \java{Cell} and \java{GridCanvas} classes to implement other simulations.
One of the most interesting zero-player games is {\it Langton's Ant}, which models an ``ant'' that walks around a grid.
The ant follows only two simple rules:

\begin{enumerate}
\item If the ant is on a white cell, it turns to the right, makes the cell black, and moves forward.
\item If the ant is on a black cell, it turns to the left, makes the cell white, and moves forward.
\end{enumerate}

Because the rules are simple, you might expect the ant to do something simple, like make a square or repeat a simple pattern.
But starting on a grid with all white cells, the ant makes more than 10,000 steps in a seemingly random pattern before it settles into a repeating loop of 104 steps.
You can read more about it at \url{http://en.wikipedia.org/wiki/Langton's_ant}.

%Reusing the classes we developed in this chapter, write an implementation of Langton's Ant.
%We present a solution to this exercise in Appendix~\ref{app:langton}.

In this chapter, we present a solution to Langton's Ant and use it to demonstrate more advanced object-oriented techniques.

\section{Langton's Ant}

We begin by defining a \java{Langton} class that has a grid and information about the ant.
The constructor takes the grid dimensions as parameters.

\begin{code}
public class Langton {
    private GridCanvas grid;
    private int xpos;
    private int ypos;
    private int head; // 0=North, 1=East, 2=South, 3=West

    public Langton(int rows, int cols) {
        grid = new GridCanvas(rows, cols, 10);
        xpos = rows / 2;
        ypos = cols / 2;
        head = 0;
    }
}
\end{code}

\java{grid} is a \java{GridCanvas} object, which represents the state of the cells.
\java{xpos} and \java{ypos} are the coordinates of the ant, and \java{head} is the ``heading'' of the ant, that is, what direction it is facing.
\java{head} is an integer with four possible values, where 0 means the ant is facing ``north'', that is, toward the top of the screen, 1 means ``east'', etc.

Here's an \java{update} method that implements the rules for Langton's ant:

\begin{code}
public void update() {
    flipCell();
    moveAnt();
}
\end{code}

The \java{flipCell} method gets the \java{Cell} at the ant's location, figures out which way to turn, and changes the state of the cell.

\begin{code}
private void flipCell() {
    Cell cell = grid.getCell(xpos, ypos);
    if (cell.isOff()) {
        head = (head + 1) % 4;    // turn right
        cell.turnOn();
    } else {
        head = (head + 3) % 4;    // turn left
        cell.turnOff();
    }
}
\end{code}

We use the remainder operator, \verb"%", to make \java{head} wrap around: if \java{head} is 3 and we turn right, it wraps around to 0; if \java{head} is 0 and we turn left, it wraps around to 3.

Notice that to turn right, we add 1 to \java{head}.
To turn left, we could subtract 1, but \verb"-1 % 4" is \verb"-1" in Java.
So we add 3 instead, since one left turn is the same as three right turns.

The \java{moveAnt} method moves the ant forward one square, using \java{head} to determine which way is forward.

\begin{code}
private void moveAnt() {
    if (head == 0) {
        ypos -= 1;
    } else if (head == 1) {
        xpos += 1;
    } else if (head == 2) {
        ypos += 1;
    } else {
        xpos -= 1;
    }
}
\end{code}

Here is the \java{main} method we use to create and display the \java{Langton} object:

\begin{code}
public static void main(String[] args) {
    String title = "Langton's Ant";
    Langton game = new Langton(61, 61);
    JFrame frame = new JFrame(title);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.add(game.grid);
    frame.pack();
    frame.setVisible(true);
    game.mainloop();
}
\end{code}

Most of this code is the same as the \java{main} we used to create and run \java{Conway}, in Section~\ref{conwaymain}.
It creates and configures a \java{JFrame} and runs \java{mainloop}.

And that's everything!
If you run this code with a grid size of 61x61 or larger, you will see the ant eventually settle into a repeating pattern.

Because we designed \java{Cell} and \java{GridCanvas} to be reusable, we didn't have to modify them at all.
However, we now have two copies of the \java{main} method---one on \java{Conway}, and one in \java{Langton}.

\section{Refactoring}

Whenever you see repeated code like \java{main}, you should think about ways to remove it.
In the Chapter~\ref{eights}, we used inheritance to eliminate repeated code.
We'll do something similar with \java{Conway} and \java{Langton}.

First, we define a superclass named \java{Automaton} where we will put the code that \java{Conway} and \java{Langton} have in common.

\begin{code}
public class Automaton {
    private GridCanvas grid;

    public void run(String title, int rate) {
        JFrame frame = new JFrame(title);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.add(this.grid);
        frame.pack();
        frame.setVisible(true);
        this.mainloop(rate);
    }
}
\end{code}

\java{Automaton} declares \java{grid} as an instance variable, so every \java{Automaton} ``has~a'' \java{GridCanvas}.
It also provides \java{run}, which contains the code that creates and configures the \java{JFrame}.

The \java{run} method takes two parameters: the window \java{title} and the frame \java{rate}, that is, the number of time steps to show per second.
It uses \java{title} when creating the \java{JFrame}, and it passes \java{rate} to \java{mainloop}:

\begin{code}
private void mainloop(int rate) {
    while (true) {

        // update the drawing
        this.update();
        grid.repaint();

        // delay the simulation
        try {
            Thread.sleep(1000 / rate);
        } catch (InterruptedException e) {
            // do nothing
        }
    }
}
\end{code}

\java{mainloop} contains the code we first saw in Section~\ref{mainloop}.
It runs a \java{while} loop forever (or until the window closes).
Each time through the loop, it runs \java{update} to update \java{grid} and then \java{repaint} to redraw the grid.

Then it calls \java{Thread.sleep} with a delay that depends on \java{rate}.
For example, if {\tt rate} is 2, we should draw two frames per second, so the delay is a half second, or 500 milliseconds.

\index{refactoring}

This process of reorganizing existing code, without changing its behavior, is known as {\bf refactoring}.
We're almost finished; we just need to redesign \java{Conway} and \java{Langton} to extend \java{Automaton}.

\section{Abstract Classes}

So far the implementation works, and if we are not planning to implement any other zero-person games, we could leave well enough alone.
But there are a few problems with the current design:

\begin{enumerate}

\item The \java{grid} attribute is \java{private}, making it inaccessible in \java{Conway} and \java{Langton}.
We could make it \java{public}, but then other (unrelated) classes would have access to it as well.

\item The \java{Automaton} class has no constructors, and even if it did, there would be no reason to create an instance of this class.

\item The \java{Automaton} class does not provide an implementation of \java{update}.
In order to work properly, subclasses need to provide one.

\end{enumerate}

\index{protected}
\index{abstract}

Java provides language features to solve these problems:

\begin{enumerate}

\item We can make the \java{grid} attribute \java{protected}, which means it's accessible to subclasses but not other classes.

\item We can make the class \java{abstract}, which means it cannot be instantiated.
If you attempt to create an object for an abstract class, you will get a compiler error.

\item We can declare \java{update} as an \java{abstract} method, meaning that it must be overridden in subclasses.
If the subclass does not override an abstract method, you will get a compiler error.
\end{enumerate}

Here's what \java{Automaton} looks like as an abstract class:

\begin{code}
public abstract class Automaton {
    protected GridCanvas grid;

    public abstract void update();

    public void run(String title, int delay) {
        // body of this method omitted
    }

    private void mainloop(int rate) {
        // body of this method omitted
    }
}
\end{code}

Notice that the \java{update} method has no body.
The declaration specifies the name, arguments, and return type.
But it does not provide an implementation, because it is an abstract method.

Notice also the word \java{abstract} on the first line, which declares that \java{Automaton} is an abstract class.
In order to have any abstract methods, a class must be declared as abstract.

Any class that extends \java{Automaton} must provide an implementation of \java{update}; the declaration here allows the compiler to check.

Here's what \java{Conway} looks like as a subclass of \java{Automaton}:

\begin{code}
public class Conway extends Automaton {

    // same methods as before, except mainloop is removed

    public static void main(String[] args) {
        String title = "Conway's Game of Life";
        Conway game = new Conway("pulsar.cells", 2);
        game.run(title, 2);
    }
}
\end{code}

\java{Conway} extends \java{Automaton}, so it inherits the \java{protected} instance variable \java{grid} and the methods \java{run} and \java{mainloop}.
But because \java{Automaton} is abstract, \java{Conway} has to provide \java{update} and a constructor (which it has already).

Abstract classes are essentially ``incomplete'' class definitions that specify methods to be implemented by subclasses.
But they also provide attributes and methods to be inherited, thus eliminating repeated code.

\section{UML Diagram}

At the beginning of the chapter, with had three classes: \java{Cell}, \java{GridCanvas}, and \java{Conway}.
We then developed \java{Langton}, which had almost the same \java{main} method as \java{Conway}.
So we refactored the code and created \java{Automaton}.
Figure~\ref{fig:uml2} summarizes the final design.

\begin{figure}[!ht]
\begin{center}
\includegraphics[width=0.75\textwidth]{figs/uml2.png}
\caption{UML class diagram of \java{Conway} and \java{Langton} applications.}
\label{fig:uml2}
\end{center}
\end{figure}

\index{IS-A}
\index{HAS-A}

The diagram shows three examples of inheritance: \java{Conway} is an \java{Automaton}, \java{Langton} is an \java{Automaton}, and \java{GridCanvas} is a Canvas.
It also shows two examples of composition: \java{Automaton} has a \java{GridCanvas}, and \java{GridCanvas} has a 2D array of \java{Cell}s.

The diagram also shows that \java{Automaton} uses \java{JFrame}, \java{GridCanvas} uses \java{Graphics}, and \java{Cell} uses \java{Graphics} and \java{Color}.

\java{Automaton} is in italics to indicate that it is an abstract class.
As it happens, \java{Graphics} is an abstract class, too.

%According to the documentation, its design ``allows an application to draw onto components that are realized on various devices, as well as onto off-screen images.''
%That's the beauty of abstraction; our code works regardless how and where it's drawn.

One of the challenges of object-oriented programming is keeping track of a large number of classes and the relationships between them.
UML class diagrams can help.

\section{Vocabulary}

\begin{description}

\term{refactor}
The process of restructuring or reorganizing existing code without changing its behavior.

\term{abstract class}
A class that is declared as \java{abstract}; it cannot be instantiated, and it may (or may not) include abstract methods.

\term{concrete class}
A class that is {\em not} declared as \java{abstract}; each of its methods must have an implementation.

\end{description}

\section{Exercises}

\begin{exercise}

The last section of this chapter introduced \java{Automaton} as an abstract class and rewrote \java{Conway} as a subclass of \java{Automaton}.
Now it's your turn: rewrite \java{Langton} as a subclass of \java{Automaton}, removing the code that's no longer needed.

\end{exercise}

\begin{exercise}

Mathematically speaking, Game of Life and Langton's Ant are cellular automata, where ``cellular'' means it has cells, and ``automaton'' means it runs itself.
See \url{https://en.wikipedia.org/wiki/Cellular_automaton} for more discussion.

Implement another cellular automaton of your choice.
You may have to modify \java{Cell} and/or \java{GridCanvas}, in addition to extending \java{Automaton}.
For example, Brian's Brain (\url{https://en.wikipedia.org/wiki/Brian's_Brain}) requires three states: ``on'', ``dying'', and ``off''.

\end{exercise}


\section*{New Clock Stability Application}

\gpstkapp{Clock Tools}, a recent addition to the GPSTk, allows for
basic clock stability analyses.  \gpstkapp{Clock Tools} implement
clock time-domain frequency stability metrics as well as data editing,
noise identification, and plotting routines.  The \gpstkapp{Clock
  Tools} are interoperable with other GPSTk programs, allowing clock
analyses to be easily run alongside other GPS analyses.

Given RINEX GPS observation and navigation files, clock estimates may
be generated using the GPSTk \gpstkapp{Observed Range Deviation (ORD) Tools}.
Kalman filter and time interval analyzer data-sets provide another
source of clock data.  For instance, the TSC 5110A Time Interval
Analyzer (TIA) compares two input clocks and outputs the phase
difference between them at a 10- to 100-Hz sampling rate.  These clock
estimates are used for time-domain frequency stability analysis.

Frequency stability measures the ability of a clock to maintain its nominal frequency over a given period of time.  From input clock data, both short-term and long-term stability can be assessed.  The Allan variance represents the variance of a clock from its nominal value over a range of averaging times.  The Allan variance is an IEEE standard for stability analysis~\cite{ieee1139}.  An Allan variance plot is often helpful in stability analysis.

The \gpstkapp{Clock Tools} suite currently computes the Allan, overlapping Allan, modified Allan, total Allan, overlapping Hadamard, and dynamic Allan deviation stability metrics.  These \gpstkapp{Clock Tools} may be run from the command line with their output piped to other GPSTk programs.  Data formatting and outlier removal routines for GPS and time interval analyzer data-sets facilitate compatibility with the \gpstkapp{Clock Tools} stability programs.

\subsection*{Design}

The \gpstkapp{Clock Tools} applications are encapsulated, so that the output of
one tool acts as the input to the next.  By using redirection and
piping the user is able to connect the \gpstkapp{Clock Tools} together in a way
that allows for flexibility in analysis and ease of use.

Routines within the \gpstkapp{Clock Tools} suite fall into four functional categories: input parsing, data grooming, data analysis, and plotting.  Input parsing takes data generated outside of \gpstkapp{Clock Tools} and puts it in a format understood within the suite.  Data grooming cleans the data of outliers before analysis.  Data analysis performs the frequency stability calculations.  Plotting creates a graphical representation of the frequency stability.

\subsection*{Implementation}

As mentioned, \gpstkapp{Clock Tools} has four functional categories: input
parsing, data grooming, data analysis, and plotting.
Table~\ref{table:clockapps} presents a description and example use of
each tool.  Note that \gpstkapp{ordClock} makes an estimate of the receiver’s
clock offset by averaging the ORDs of all the GPS satellites at each
epoch.  An epoch is an instant in time in which GPS data is recorded.
%
\begin{table*}
\centering
\caption{Description and example invocations of \gpstkapp{Clock Tools}.}
\label{table:clockapps}
\begin{tabular}{lll} \hline \hline
\emph{Tool} & \emph{Description} & \emph{Example} \\ \hline
\gpstkapp{ORDPhaseParser} & Parses data generated by the \gpstkapp{ORD Tools} & \gpstkcommand{ordGen –o input.o –e input.n | } \\
 & &\gpstkcommand{ordClock|ORDPhaseParser>parsed.dat} \\ \hline
\gpstkapp{TIAPhaseParser} & Parses data generated by the & \gpstkcommand{TIAPhaseParser < raw.dat > parsed.dat} \\
   &  TSC 5110A Timing Interval Analyzer. & \\ \hline
\gpstkapp{rmoutlier} & Removes outlier data within a set of  data. & \gpstkcommand{rmoutlier < parsed.dat} \\ \hline
\gpstkapp{nallandev} & Computes the Allan deviation. & \gpstkcommand{nallandev < parsed.dat} \\ \hline
\gpstkapp{oallandev} & Computes the overlapping Allan deviation. & \gpstkcommand{oallandev < parsed.dat} \\ \hline
\gpstkapp{mallandev} & Computes the modified Allan deviation. & \gpstkcommand{mallandev < parsed.dat} \\ \hline
\gpstkapp{totvar} & Computes the total Allan deviation. & \gpstkcommand{totvar < parsed.dat} \\ \hline
\gpstkapp{ohadamarddev} & Computes the overlapping Hadamard & \gpstkcommand{ohadamarddev < parsed.dat} \\
& deviation. & \\ \hline
\gpstkapp{dallandev} & Computes the dynamic Allan deviation. & \gpstkcommand{dallandev < parsed.dat} \\ \hline
\gpstkapp{allanplot} & Plots the output of \gpstkapp{nallandev}, \gpstkapp{oallandev}, & \gpstkcommand{nallandev < parsed.dat | allanplot} \\
& \gpstkapp{ohadamarddev}, \gpstkapp{totvar}, and \gpstkapp{mallandev}. & \\ \hline
\gpstkapp{ddevplot.m} & Plots the output of dallandev. & \gpstkcommand{octave ddevplot.m} \\ \hline \hline
\end{tabular}
\end{table*}
%
The input parsers are the classes \gpstkapp{ORDPhaseParser} and
\gpstkapp{TIAPhaseParser}.  The data grooming tool is
\gpstkapp{rmoutlier}.  The data analysis tools are
\gpstkapp{nallandev}, \gpstkapp{oallandev}, \gpstkapp{mallandev},
\gpstkapp{totvar}, \gpstkapp{ohadamarddev}, and \gpstkapp{dallandev}.
The plotting scripts are \gpstkapp{allanplot} and
\gpstkapp{ddevplot.m}.  Data flows from the parsers to data grooming
to data analysis and finally to plotting.

\subsection*{Example Usage and Plots}

Two example command lines are given below.  The first command
generates clock estimates using the GPSTk ORD tools (\gpstkapp{ordGen} and
\gpstkapp{ordClock}), parses the data (\gpstkapp{ORDPhaseParser}), then removes outliers
(\gpstkapp{rmoutlier}), computes the overlapping Allan deviation (\gpstkapp{oallandev}), and
finally writes the data to a file (\gpstkcommand{output.oadev}).  The second example
takes data in from a file produced by the Timing Interval Analyzer
(\gpstkcommand{raw.dat}), parses the data (\gpstkapp{TIAPhaseParser)}, computes the overlapping
Hadamard variance (\gpstkcommand{ohadamard}), and plots the output (\gpstkcommand{allanplot}).
%
\begin{scriptsize}
\begin{lstlisting}
ordGen –o input.o –e input.n | ordClock
| ORDPhaseParser | rmoutlier |
oallandev > output.oadev

raw.dat | TIAPhaseParser |
ohadamard | allanplot
\end{lstlisting}
\end{scriptsize}
%
Another example is shown below.  This example is an analysis performed on a reference station that is part of the NGA GPS Monitor Station Network (MSN).

This analysis compares the results of running an overlapping Allan
deviation calculation on data generated by \gpstkapp{ordClock} from
unsmoothed raw RINEX files versus data output by the NGA Kalman
filter. The \gpstkapp{ordClock} and Kalman filter data sets cover
different time periods, but both data sets are good representatives of
nominal MSN data. The overlapping Allan deviation of the \gpstkapp{ordClock}
generated data is represented by the blue line.  The overlapping Allan
deviation of the Kalman filter generated data is represented by the
green line.  The lighter slanted red line shows the 5071A CFS
time-domain stability specification.  The darker red line along the
bottom represents the cesium’s flicker floor.  Note that drift removal
may be necessary depending on the input dataset and the deviation
computation performed.
%
\begin{figure*}
  \centering
  \includegraphics[width=5in,bb=65 387 547 727]{clockapps.eps}
  \caption{Frequency Stability of \gpstkapp{ordClock} and Kalman Filter Data}
  \label{fig:clockapps}
\end{figure*}
%
Figure~\ref{fig:clockapps} shows that the frequency stability of the
clock estimates generated by the Kalman filter lies within the CFS
specifications, but that the frequency stability of the output
generated by \gpstkapp{ordClock} from the raw data does not.  Using
raw GPS data and \gpstkapp{ordClock} a stability trend is apparent,
but further filtering and smoothing of the data is necessary to get
more accurate clock stability estimates.


% !TeX spellcheck = en_GB

\section{Mean error and mean absolute error}%\hfill}
\label{app:mean_error}

%%% image bias %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{figure}[h]%\ContinuedFloat
		\centering
        % pres
		\begin{subfigure}[b]{0.49\textwidth}
			\includegraphics[width=\textwidth]{./fig_sfc_pressure/ME_20161220_26_00}
			\caption{}\label{fig:bias:pres}
		\end{subfigure}
        \begin{subfigure}[b]{0.49\textwidth}
			\includegraphics[width=\textwidth]{./fig_sfc_pressure/MAE_20161220_26_00}
			\caption{}\label{fig:MAE:pres}
		\end{subfigure}
		% temp
		\begin{subfigure}[b]{0.49\textwidth}
			\includegraphics[width=\textwidth]{./fig_sfc_temp/ME_20161220_26_00}
			\caption{}\label{fig:bias:temp}
		\end{subfigure}
        \begin{subfigure}[b]{0.49\textwidth}
			\includegraphics[width=\textwidth]{./fig_sfc_temp/MAE_20161220_26_00}
			\caption{}\label{fig:MAE:temp}
		\end{subfigure}
        % wd
		\begin{subfigure}[b]{0.49\textwidth}
			\includegraphics[width=\textwidth]{./fig_sfc_wd/ME_20161220_26_00}
			\caption{}\label{fig:bias:wd}
		\end{subfigure}
        \begin{subfigure}[b]{0.49\textwidth}
			\includegraphics[width=\textwidth]{./fig_sfc_wd/MAE_20161220_26_00}
			\caption{}\label{fig:MAE:wd}
		\end{subfigure}
\caption{Mean error (\protect\subref{fig:bias:pres}, \protect\subref{fig:bias:temp}, \protect\subref{fig:bias:wd}, \protect\subref{fig:bias:ws}, \protect\subref{fig:bias:precip}) and mean absolute error (\protect\subref{fig:MAE:pres}, \protect\subref{fig:MAE:temp}, \protect\subref{fig:MAE:wd}, \protect\subref{fig:MAE:ws}, \protect\subref{fig:MAE:precip}) of surface variables for all ten ensemble members at Haukeliseter, initialisations at \SI{0}{\UTC}, valid for \SI{48}{\hour}. From top to bottom, sea level pressure (\protect\subref{fig:bias:pres}, \protect\subref{fig:MAE:pres}), \SI{2}{\metre} air temperature (\protect\subref{fig:bias:temp}, \protect\subref{fig:MAE:temp}), \SI{10}{\metre} wind direction (\protect\subref{fig:bias:wd}, \protect\subref{fig:MAE:wd}).}\label{fig:bias_MAE}
\end{figure}
\begin{figure}\ContinuedFloat
	\centering
		% ws
		\begin{subfigure}[b]{0.49\textwidth}
			\includegraphics[width=\textwidth]{./fig_sfc_ws/ME_20161220_26_00}
			\caption{}\label{fig:bias:ws}
		\end{subfigure}
        \begin{subfigure}[b]{0.49\textwidth}
			\includegraphics[width=\textwidth]{./fig_sfc_ws/MAE_20161220_26_00}
			\caption{}\label{fig:MAE:ws}
		\end{subfigure}
% \end{figure}
% \begin{figure}\ContinuedFloat
% \centering
        % precip
		\begin{subfigure}[b]{0.49\textwidth}
			\includegraphics[width=\textwidth]{./fig_sfc_precip/ME_20161220_26_00}
			\caption{}\label{fig:bias:precip}
		\end{subfigure}
        \begin{subfigure}[b]{0.49\textwidth}
			\includegraphics[width=\textwidth]{./fig_sfc_precip/MAE_20161220_26_00}
			\caption{}\label{fig:MAE:precip}
		\end{subfigure}
        % precip 12h
        \begin{subfigure}[b]{0.49\textwidth}
			\includegraphics[width=\textwidth]{./fig_sfc_precip/ME12_20161220_26_00}
			\caption{}\label{fig:bias:precip12}
		\end{subfigure}
        \begin{subfigure}[b]{0.49\textwidth}
			\includegraphics[width=\textwidth]{./fig_sfc_precip/MAE12_20161220_26_00}
			\caption{}\label{fig:MAE:precip12}
		\end{subfigure}
	\caption{\textit{(Continued from previous page.)} ,  \SI{10}{\metre} wind speed (\protect\subref{fig:bias:ws}, \protect\subref{fig:MAE:ws}), precipitation accumulation for \SI{48}{\hour} (\protect\subref{fig:bias:precip}, \protect\subref{fig:MAE:precip}) and \SI{12}{\hour} surface accumulation (\protect\subref{fig:bias:precip12}, \protect\subref{fig:MAE:precip12}). }
\end{figure}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


\chapter{Introduction}

The constraints, that we are talking about here, are not like the constraints in classical mechanics. They appear when we try to get from the Lagrange to the Hamilton formalism.
\begin{itemize}
\item $L(q_i,\dot{q}_i)$, \ where $i = 1, ..., n$ degrees of freedom \\
The mechanical properties of a system are completly described by the Lagrangian.
\end{itemize}
We will study constraints from a mathematical point of view, not a physical:
\begin{itemize}
\item Classical mechanics: physical constraints lead to changes in the mathematical description.
\item Now: most general description of Hamiltonian theory. The constraints will follow from the Lagrangian.
\end{itemize}

Why do we need the Hamilton formalism? \\
The most important fact is that a Hamiltonian system (described by coordinates $q_i$ and momenta $p_i$) can be quantized in a canonical way:
\begin{align}
L(q_i,\dot{q}_i) \ \longrightarrow \ H(q_i,p_i) \ \longrightarrow \ H(\hat{q}_i,\hat{p}_i) .
\end{align}
Nowadays, there are of course other methods of quantization, like the Feynman path integral, but we won't focus on quantization here. For us, it is important to know what happens when we try to get from the Lagrangian to the Hamiltonian. \\

How does it work?
\begin{enumerate}
\item Calculate the generalized momenta
\begin{align}\label{eq:momentum}
q_i \ \longrightarrow \ p_i \equiv \frac{\partial L(q_i,\dot{q}_i)}{\partial \dot{q}_i}.
\end{align}
This step is always possible, it results in $p_i(q_i,\dot{q}_i)$.
\item Build the Hamiltonian
\begin{align}\label{eq:hamilton}
H(q_i,p_i) = \sum_{i = 1}^n p_i \dot{q}_i - L(q_i,\dot{q}_i).
\end{align}
The expression on the right side still contains the velocities $\dot{q}_i$, so we have to express them through the generalized coordinates and momenta, by inverting \eqref{eq:momentum}
\begin{align}
p_i(q_i,\dot{q}_i) \longrightarrow \dot{q}_i = \dot{q}_i(q_i,p_i),
\end{align}
and insert in the equation \eqref{eq:hamilton}. Sometimes (if the Lagrangian is degenerate), this step is not possible. We will investigate, what to do in this cases.
\end{enumerate}

We will start with discrete and finite dimensional systems and then move on to continuous systems by introducing field theoretical aspects.


\chapter{{\tt BKL}: Block Kernighan-Lin Object}
\label{chapter:BKL}
\par
Our {\tt BKL} object is used to find an initial separator of a
graph.
Its input is a {\tt BPG} bipartite graph object that represents the
domain-segment graph of a domain decomposition of the graph.
After a call to the {\tt BKL\_fidmat()} method, the object contains
a two-color partition of the graph that is accessible via the
{\tt colors[]} and {\tt cweights[]} vectors of the object.


\documentclass[preprint]{sigplanconf}

\usepackage{graphicx}
\usepackage{comment}
\usepackage{amsmath}
\usepackage{xspace}
\usepackage{amssymb}
\usepackage{stmaryrd}
\usepackage{proof}
\usepackage{multicol}
\usepackage[nodayofweek]{datetime}
\usepackage{etex}
\usepackage[all, cmtip]{xy}
\usepackage{xcolor}
\usepackage{listings}
\usepackage{multicol}
\newcommand\hmmax{0} % default \newcommand\bmmax{0} % default 4
\usepackage{bm}
\usepackage{cmll}

\newcommand{\fname}[1]{\ulcorner #1 \urcorner}
\newcommand{\fconame}[1]{\llcorner #1 \lrcorner}

\newcommand{\xcomment}[2]{\textbf{#1:~\textsl{#2}}}
\newcommand{\amr}[1]{\xcomment{Amr}{#1}}
\newcommand{\roshan}[1]{\xcomment{Roshan}{#1}}

\newcommand{\asterix}[0]{*}

\newcommand{\ie}{\textit{i.e.}\xspace}
\newcommand{\eg}{\textit{e.g.}\xspace}

\newcommand{\lcal}{\ensuremath{\lambda}-calculus\xspace}
\newcommand{\G}{\ensuremath{\mathcal{G}}\xspace}

\newcommand{\code}[1]{\lstinline[basicstyle=\small]{#1}\xspace}
\newcommand{\name}[1]{\code{#1}}

\def\newblock{}

\newenvironment{floatrule}
    {\hrule width \hsize height .33pt \vspace{.5pc}}
    {\par\addvspace{.5pc}}

\newtheorem{theorem}{Theorem}[section]
\newtheorem{lemma}[theorem]{Lemma}
\newtheorem{definition}[theorem]{Definition}
\newtheorem{proposition}[theorem]{Proposition}
\newenvironment{proof}[1][Proof.]{\begin{trivlist}\item[\hskip \labelsep {\bfseries #1}]}{\end{trivlist}}

\newcommand{\arrow}[1]{\mathtt{#1}}

\newcommand{\dgm}[2][0.95]{
\begin{center}
\scalebox{#1}{
\includegraphics{diagrams/#2.pdf}
}
\end{center}
}

%subcode-inline{bnf-inline} name langRev
%! swap+ = \mathit{swap}^+
%! swap* = \mathit{swap}^*
%! dagger =  ^{\dagger}
%! assocl+ = \mathit{assocl}^+
%! assocr+ = \mathit{assocr}^+
%! assocl* = \mathit{assocl}^*
%! assocr* = \mathit{assocr}^*
%! identr* = \mathit{uniti}
%! identl* = \mathit{unite}
%! dist = \mathit{distrib}
%! factor = \mathit{factor}
%! eta = \eta
%! eps = \epsilon
%! eta+ = \eta^+
%! eps+ = \epsilon^+
%! eta* = \eta^{\times}
%! eps* = \epsilon^{\times}
%! trace+ = trace^+
%! trace* = trace^{\times}
%! ^^^ = ^{-1}
%! (o) = \circ
%! (;) = \fatsemi
%! (*) = \times
%! (+) = +
%! LeftP = L^+
%! RightP = R^+
%! LeftT = L^{\times}
%! RightT = R^{\times}
%! alpha = \alpha
%! bool = \textit{bool}
%! color = \textit{color}
%! Gr = G

%subcode-inline{bnf-inline} regex \{\{(((\}[^\}])|[^\}])*)\}\} name main include langRev
%! Gx = \Gamma^{\times}
%! G = \Gamma
%! [] = \Box
%! |-->* = \mapsto^{\asterix}
%! |-->> = \mapsto_{\ggg}
%! |--> = \mapsto
%! <--| = \mapsfrom
%! |- = \vdash
%! <><> = \approx
%! ==> = \Longrightarrow
%! <== = \Longleftarrow
%! <=> = \Longleftrightarrow
%! <-> = \leftrightarrow
%! ~> = \leadsto
%! -o+ = \multimap^{+}
%! -o* = \multimap^{\times}
%! -o = \multimap
%! ::= = &::=&
%! /= = \neq
%! @@ = \mu
%! [^ = \lceil
%! ^] = \rceil
%! forall = \forall
%! exists = \exists
%! empty = \epsilon
%! Pi = \Pi
%! Pi0 = \Pi^{o}
%! PiEE* = \Pi^{\eta\epsilon}_{*}
%! PiEE+ = \Pi^{\eta\epsilon}_{+}
%! PiEE = \Pi^{\eta\epsilon}
%! CatSet = \textbf{Set}
%! theseus = Theseus
%! sqrt(x) = \sqrt{#x}
%! surd(p,x) = \sqrt[#p]{#x}
%! inv(x) = \frac{1}{#x}
%! frac(x,y) = \frac{#x}{#y}
%! * = \times

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

\conferenceinfo{POPL'13}{}
\CopyrightYear{}
\copyrightdata{}
\titlebanner{}
\preprintfooter{}

\title{Fractional Types}

\authorinfo{*}{*}{*}
\maketitle

\begin{abstract}

\end{abstract}

\category{D.3.1}{Formal Definitions and Theory}{}
\category{F.3.2}{Semantics of Programming Languages}{}
\category{F.3.3}{Studies of Program Constructs}{Type structure}

\terms
Languages, Theory

\keywords continuations, information flow, linear logic, logic programming,
quantum computing, reversible logic, symmetric monoidal categories, compact
closed categories.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{The Game}

We start with a type {{A}} and build terms of the types {{A}}, {{Id_A}},
{{Id_{Id_a} }}, etc.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Level of Atoms}

We start with the kind {{type}} and terms of kind {{type}}:

%subcode{bnf} include main
% kinds, k ::= type
% value types, b ::= 0 | 1 | b + b | b * b

%subcode{proof} include main
%@  ~
%@@ 0 : type
%
%@  ~
%@@ 1 : type
%
%@  b1 : type
%@  b2 : type
%@@ b1 + b2 : type
%
%@  b1 : type
%@  b2 : type
%@@ b1 * b2 : type

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{ {{Pi}} Combinators}

Now we introduce isomorphisms between terms of kind {{type}}. This is where
the {{Pi}} combinators appear.

%subcode{bnf} include main
% kinds, k ::= type
% value types, b ::= 0 | 1 | b + b | b * b
%
% identity types, t0 ::= Id_k(b1,b2)
% iso ::= zeroe | zeroi
%     &|& swap+ | assocl+ | assocr+
%     &|& identl* | identr*
%     &|& swap* | assocl* | assocr*
%     &|& dist | factor
% comb., c ::= iso | id | sym c | c (;) c | c (+) c | c (*) c

%subcode{proof} include main
%@  b : k
%@@ zeroe : Id_k(0+b,b)
%
%@  b : k
%@@ zeroi : Id_k(b,0+b)
%---
%@  b1 : k
%@  b2 : k
%@@ swap+ : Id_k(b1+b2,b2+b1)
%---
%@  b1 : k
%@  b2 : k
%@  b3 : k
%@@ assocl+ : Id_k(b1+(b2+b3),(b1+b2)+b3)
%---
%@  b1 : k
%@  b2 : k
%@  b3 : k
%@@ assocr+ : Id_k((b1+b2)+b3,b1+(b2+b3))
%---
%@  b : k
%@@ unite : Id_k(1 * b, b)
%
%@  b : k
%@@ uniti : Id_k(b, 1 * b)
%---
%@  b1 : k
%@  b2 : k
%@@ swap* : Id_k(b1 * b2,b2 * b1)
%---
%@  b1 : k
%@  b2 : k
%@  b3 : k
%@@ assocl* : Id_k(b1*(b2*b3),(b1*b2)*b3)
%---
%@  b1 : k
%@  b2 : k
%@  b3 : k
%@@ assocr* : Id_k((b1*b2)*b3,b1*(b2*b3))
%---
%@  b1 : k
%@  b2 : k
%@  b3 : k
%@@ distrib : Id_k((b1+b2)*b3,(b1*b3)+(b2*b3))
%---
%@  b1 : k
%@  b2 : k
%@  b3 : k
%@@ factor : Id_k((b1*b3)+(b2*b3),(b1+b2)*b3)
%---
%@ b : k
%@@ id : Id_k(b,b)
%
%@ c : Id_k(b1,b2)
%@@ sym c : Id_k(b2,b1)
%---
%@ c1 : Id_k(b1,b2)
%@ c2 : Id_k(b2,b3)
%@@ c1(;)c2 : Id_k(b1,b3)
%---
%@ c1 : Id_k(b1,b3)
%@ c2 : Id_k(b2,b4)
%@@ c1(+)c2 : Id_k(b1+b2,b3+b4)
%---
%@ c1 : Id_k(b1,b3)
%@ c2 : Id_k(b2,b4)
%@@ c1(*)c2 : Id_k(b1*b2,b3*b4)

We will give the semantics in an usual style to simplify the presentation of
next section. First we define values and clauses:

%subcode{bnf} include main
% values, v ::= () | left v | right v | (v,v)
% clauses, m ::= (1/v,v)

%subcode{proof} include main
%@  ~
%@@ () : 1
%
%@  v : b1
%@@ left v : b1 + b2
%
%@  v : b2
%@@ right v : b1 + b2
%---
%@  v1 : b1
%@  v2 : b2
%@@ (v1,v2) : b1 * b2

The intuition behind clauses is the following: if applying
{{c : Id_k(b1,b2)}} to {{v1 : b1}} yields {{v2 : b2}}, we say that
the clause {{ (1/v1, v2) }} has type {{c}}.

%subcode{proof} include main
%@ zeroe : Id_k(0+b,b)
%@ v : b
%@@ (1/right v, v) : zeroe
%
%@ zeroi : Id_k(b,0+b)
%@ v : b
%@@ (1/v, right v) : zeroi
%---
%@ swap+ : Id_k(b1+b2,b2+b1)
%@ v : b1
%@@ (1/left v, right v) : swap+
%---
%@ swap+ : Id_k(b1+b2,b2+b1)
%@ v : b2
%@@ (1/right v, left v) : swap+
%---
%@ assocl+ : Id_k(b1+(b2+b3),(b1+b2)+b3)
%@ v : b1
%@@ (1/ left v, left (left v)) : assocl+
%---
%@ assocl+ : Id_k(b1+(b2+b3),(b1+b2)+b3)
%@ v : b2
%@@ (1/ right (left v), left (right v)) : assocl+
%---
%@ assocl+ : Id_k(b1+(b2+b3),(b1+b2)+b3)
%@ v : b3
%@@ (1/ right (right v), right v) : assocl+
%---
%@ assocr+ : Id_k((b1+b2)+b3,b1+(b2+b3))
%@ v : b1
%@@ (1/ left (left v), left v) : assocr+
%---
%@ assocr+ : Id_k((b1+b2)+b3,b1+(b2+b3))
%@ v : b2
%@@ (1/ left (right v), right (left v)) : assocr+
%---
%@ assocr+ : Id_k((b1+b2)+b3,b1+(b2+b3))
%@ v : b3
%@@ (1/ right v, right (right v)) : assocr+
%---
%@ unite : Id_k(1 * b, b)
%@ v : b
%@@ (1/((),v), v) : unite
%
%@ uniti : Id_k(b, 1 * b)
%@ v : b
%@@ (1/v, ((),v)) : uniti
%---
%@ swap* : Id_k(b1 * b2,b2 * b1)
%@ v1 : b1
%@ v2 : b2
%@@ (1/(v1,v2), (v2,v1)) : swap*
%---
%@ assocl* : Id_k(b1*(b2*b3),(b1*b2)*b3)
%@ v1 : b1
%@ v2 : b2
%@ v3 : b3
%@@ (1/(v1,(v2,v3)), ((v1,v2),v3)) : assocl*
%---
%@ assocr* : Id_k((b1*b2)*b3,b1*(b2*b3))
%@ v1 : b1
%@ v2 : b2
%@ v3 : b3
%@@ (1/((v1,v2),v3), (v1,(v2,v3))) : assocr*
%---
%@ distrib : Id_k((b1+b2)*b3,(b1*b3)+(b2*b3))
%@ v1 : b1
%@ v3 : b3
%@@ (1/(left v1,v3), left (v1,v3)) : distrib
%---
%@ distrib : Id_k((b1+b2)*b3,(b1*b3)+(b2*b3))
%@ v2 : b2
%@ v3 : b3
%@@ (1/(right v2,v3), right (v2,v3)) : distrib
%---
%@ factor : Id_k((b1*b3)+(b2*b3),(b1+b2)*b3)
%@ v1 : b1
%@ v3 : b3
%@@ (1/(left (v1,v3)), (left v1,v3)) : factor
%---
%@ factor : Id_k((b1*b3)+(b2*b3),(b1+b2)*b3)
%@ v2 : b2
%@ v3 : b3
%@@ (1/(right (v2,v3)), (right v2,v3)) : factor
%---
%@ id : Id_k(b,b)
%@ v : b
%@@ (1/v,v) : id
%
%@ c : Id_k(b2,b1)
%@ (1/v2, v1) : c
%@@ (1/v1, v2) : sym c
%---
%@ c1 : Id_k(b1,b2)
%@ c2 : Id_k(b2,b3)
%@ (1/v1, v2) : c1
%@ (1/v2, v3) : c2
%@@ (1/v1, v3) : c1 (;) c2
%---
%@ c1 : Id_k(b1,b3)
%@ (1/v1, v3) :: c1
%@@ (1/left v1, left v3) : c1 (+) c2
%
%@ c2 : Id_k(b2,b4)
%@ (1/v2, v4) :: c2
%@@ (1/right v2, right v4) : c1 (+) c2
%---
%@ c1 : Id_k(b1,b3)
%@ c2 : Id_k(b2,b4)
%@ (1/v1, v3) :: c1
%@ (1/v2, v4) :: c2
%@@ (1/(v1,v2), (v3,v4)) : c1 (*) c2

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{ {{Pi}} semantics I}

Now we introduce isomoprhisms between terms of type {{Id_k(b1,b2)}}. This is
where we start reasoning about equivalence of the {{Pi}}-combinators
themselves. For {{c1 : Id_k(b1,b2)}} and {{c2 : Id_k(b1,b2)}}, terms of type
{{Id_{Id_k(b1,b2)}(c1,c2)}} would witness that {{c1}} and {{c2}} are
isomorphic (up to equivalence at the next level).

For example, given the combinator {{uniti}} at type {{bool = 1+1}}:

%subcode{proof} include main
%@ uniti : Id_k(1+1, 1 * (1+1))
%@ v : 1+1
%@@ (1/v, ((),v)) : uniti

when viewed as a type, the elements of {{uniti}} are:
{{ (1/left (), ((), left ())) }}
and
{{ (1/right (), ((), right ())) }}

Using our isomorphisms we can apply {{ id (*) unite }} to the above to
produce
{{ (1/left (), left ()) }}
and
{{ (1/right (), right ()) }}.

In other words, there is an isomorphism {{alpha = id (*) unite}} beween
{{uniti}} and {{id}} at type {{bool}}. We now need to generalize this idea to
the full language. We possibly (probably) need to add the meadow rules so
that we can convert a clause to a regular value, use the isomorphisms on it,
and then translate it back to a clause.

%subcode{bnf} include main
% kinds, k ::= type
% value types, b ::= 0 | 1 | b + b | b * b
%
% identity types, t0 ::= Id_k(b1,b2)
% iso ::= zeroe | zeroi
%     &|& swap+ | assocl+ | assocr+
%     &|& identl* | identr*
%     &|& swap* | assocl* | assocr*
%     &|& dist | factor
% comb., c ::= iso | id | sym c | c (;) c | c (+) c | c (*) c
%
% identity types, t1 ::= Id_{t0}(c1,c2)
% alpha ::= ...

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

\end{document}

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


\XtoCBlock{Sqrt}
\label{block:Sqrt}
\begin{figure}[H]\includegraphics{Sqrt}\end{figure}

\begin{XtoCtabular}{Inports}
In & Input u\tabularnewline
\hline
\end{XtoCtabular}

\begin{XtoCtabular}{Outports}
Out & Result of sqrt(|u|)\tabularnewline
\hline
\end{XtoCtabular}

\subsubsection*{Description:}
Square root computation of absolute input value.

% include optional documentation file
\InputIfFileExists{\XcHomePath/Library/Math/Doc/Sqrt_Info.tex}{\vspace{1ex}}{}

\subsubsection*{Implementations:}
\begin{tabular}{l l}
\textbf{FiP8} & 8 Bit Fixed Point Implementation\tabularnewline
\textbf{FiP16} & 16 Bit Fixed Point Implementation\tabularnewline
\textbf{FiP32} & 32 Bit Fixed Point Implementation\tabularnewline
\textbf{Float32} & 32 Bit Floating Point Implementation\tabularnewline
\textbf{Float64} & 64 Bit Floating Point Implementation\tabularnewline
\end{tabular}

\XtoCImplementation{FiP8}
\index{Block ID!4816}
\nopagebreak[0]
% Implementation details
\begin{tabular}{l l}
\textbf{Name} & FiP8 \tabularnewline
\textbf{ID} & 4816 \tabularnewline
\textbf{Revision} & 0.1 \tabularnewline
\textbf{C filename} & Sqrt\_FiP8.c \tabularnewline
\textbf{H filename} & Sqrt\_FiP8.h \tabularnewline
\end{tabular}
\vspace{1ex}

8 Bit Fixed Point Implementation

% Implementation data structure
\XtoCDataStruct{Data Structure:}
\begin{lstlisting}
typedef struct {
     uint16        ID;
     int8          *In;
     int8          Out;
} SQRT_FIP8;
\end{lstlisting}

\ifdefined \AddTestReports
\InputIfFileExists{\XcHomePath/Library/Math/Doc/Test_Sqrt_FiP8.tex}{}{}
\fi
\XtoCImplementation{FiP16}
\index{Block ID!4817}
\nopagebreak[0]
% Implementation details
\begin{tabular}{l l}
\textbf{Name} & FiP16 \tabularnewline
\textbf{ID} & 4817 \tabularnewline
\textbf{Revision} & 0.1 \tabularnewline
\textbf{C filename} & Sqrt\_FiP16.c \tabularnewline
\textbf{H filename} & Sqrt\_FiP16.h \tabularnewline
\end{tabular}
\vspace{1ex}

16 Bit Fixed Point Implementation

% Implementation data structure
\XtoCDataStruct{Data Structure:}
\begin{lstlisting}
typedef struct {
     uint16        ID;
     int16         *In;
     int16         Out;
} SQRT_FIP16;
\end{lstlisting}

\ifdefined \AddTestReports
\InputIfFileExists{\XcHomePath/Library/Math/Doc/Test_Sqrt_FiP16.tex}{}{}
\fi
\XtoCImplementation{FiP32}
\index{Block ID!4818}
\nopagebreak[0]
% Implementation details
\begin{tabular}{l l}
\textbf{Name} & FiP32 \tabularnewline
\textbf{ID} & 4818 \tabularnewline
\textbf{Revision} & 0.1 \tabularnewline
\textbf{C filename} & Sqrt\_FiP32.c \tabularnewline
\textbf{H filename} & Sqrt\_FiP32.h \tabularnewline
\end{tabular}
\vspace{1ex}

32 Bit Fixed Point Implementation

% Implementation data structure
\XtoCDataStruct{Data Structure:}
\begin{lstlisting}
typedef struct {
     uint16        ID;
     int32         *In;
     int32         Out;
} SQRT_FIP32;
\end{lstlisting}

\ifdefined \AddTestReports
\InputIfFileExists{\XcHomePath/Library/Math/Doc/Test_Sqrt_FiP32.tex}{}{}
\fi
\XtoCImplementation{Float32}
\index{Block ID!4819}
\nopagebreak[0]
% Implementation details
\begin{tabular}{l l}
\textbf{Name} & Float32 \tabularnewline
\textbf{ID} & 4819 \tabularnewline
\textbf{Revision} & 0.1 \tabularnewline
\textbf{C filename} & Sqrt\_Float32.c \tabularnewline
\textbf{H filename} & Sqrt\_Float32.h \tabularnewline
\end{tabular}
\vspace{1ex}

32 Bit Floating Point Implementation

% Implementation data structure
\XtoCDataStruct{Data Structure:}
\begin{lstlisting}
typedef struct {
     uint16        ID;
     float32       *In;
     float32       Out;
} SQRT_FLOAT32;
\end{lstlisting}

\ifdefined \AddTestReports
\InputIfFileExists{\XcHomePath/Library/Math/Doc/Test_Sqrt_Float32.tex}{}{}
\fi
\XtoCImplementation{Float64}
\index{Block ID!4820}
\nopagebreak[0]
% Implementation details
\begin{tabular}{l l}
\textbf{Name} & Float64 \tabularnewline
\textbf{ID} & 4820 \tabularnewline
\textbf{Revision} & 0.1 \tabularnewline
\textbf{C filename} & Sqrt\_Float64.c \tabularnewline
\textbf{H filename} & Sqrt\_Float64.h \tabularnewline
\end{tabular}
\vspace{1ex}

64 Bit Floating Point Implementation

% Implementation data structure
\XtoCDataStruct{Data Structure:}
\begin{lstlisting}
typedef struct {
     uint16        ID;
     float64       *In;
     float64       Out;
} SQRT_FLOAT64;
\end{lstlisting}

\ifdefined \AddTestReports
\InputIfFileExists{\XcHomePath/Library/Math/Doc/Test_Sqrt_Float64.tex}{}{}
\fi


\maketitle

\setlength{\epigraphwidth}{0.6\textwidth}
\epigraph{\it Mathematics is a process of staring hard enough with enough perseverance at the fog of muddle and confusion to eventually break through to improved clarity. I’m happy when I can admit, at least to myself, that my thinking is muddled, and I try to overcome the embarrassment that I might reveal ignorance or confusion. }{William Thurston}

\section*{How to use these notes.}
\label{sec:intro}
\addcontentsline{toc}{section}{\nameref{sec:intro}}

Linear algebra is the study of linearity. The main players of this story are the vectors, but instead of studying vectors individually, we study collections of vectors, called {\bf vector spaces}, and maps between vector spaces, called {\bf linear transformations}.

Because linearity is such a simple condition (Section \ref{section:VectorSpaces}), linear algebra is one of the most widely applied branches of mathematics.\\\\

These notes provide a very, very brief introduction to linear algebra.
You'll learn enough to be able to continue the study of the subject on your own.

Each day you will be given a set of problems to solve in class.
You should attempt as many problems as you can, and it is ok to not finish all the problems before the next class.
However, you should make an honest attempt to read and understand the various definitions and theorems.\footnote{These notes are likely to contain \sout{a few} several \sout{typos} mistakes. Please do tell if you find any, thanks in advance.}


\documentclass{sigplanconf}
\usepackage{url}
\usepackage{proof}
\usepackage{amssymb}
\usepackage{stmaryrd}
\usepackage{listings}
\usepackage{graphicx}
\usepackage{comment}

\newcommand{\dgm}[2][1.5]{
\begin{center}
\scalebox{#1}{
\includegraphics{diagrams/#2.pdf}
}
\end{center}
}
\newcommand{\todo}[1]{\textbf{TODO:} #1}
\newcommand{\jacques}[1]{\textsc{Jacques says:} #1}
\newcommand{\amr}[1]{\textsc{Amr says:} #1}

\newtheorem{theorem}{Theorem}[section]
\newtheorem{lemma}[theorem]{Lemma}
\newtheorem{definition}[theorem]{Definition}
\newtheorem{proposition}[theorem]{Proposition}

%subcode-inline{bnf-inline} name Pi
%! swap+ = \mathit{swap}^+
%! swap* = \mathit{swap}^*
%! dagger =  ^{\dagger}
%! assocl+ = \mathit{assocl}^+
%! assocr+ = \mathit{assocr}^+
%! assocl* = \mathit{assocl}^*
%! assocr* = \mathit{assocr}^*
%! identr* = \mathit{uniti}
%! identl* = \mathit{unite}
%! dist = \mathit{distrib}
%! factor = \mathit{factor}
%! (o) = \fatsemi
%! (;) = \fatsemi
%! (*) = \times
%! (+) = +
%! foldB = fold_B
%! unfoldB = unfold_B
%! foldN = fold_N
%! unfoldN = unfold_N
%! trace+ = \mathit{trace}^{+}
%! trace* = \mathit{trace}^{\times}
%! :-* = \multimap
%! :-+ = \multimap^{+}
%! emptyset = \emptyset

%subcode-inline{bnf-inline} regex \{\{(((\}[^\}])|[^\}])*)\}\} name main include Pi
%! [^ = \ulcorner
%! ^] = \urcorner
%! [v = \llcorner
%! v] = \lrcorner
%! [[ = \llbracket
%! ]] = \rrbracket
%! ^^^ = ^{\dagger}
%! eta* = \eta
%! eps* = \epsilon
%! Union = \bigcup
%! in = \in
%! |-->* = \mapsto^{*}
%! |-->> = \mapsto_{\ggg}
%! |-->let = \mapsto_{let}
%! |--> = \mapsto
%! <--| = \mapsfrom
%! |- = \vdash
%! <=> = \Longleftrightarrow
%! <-> = \leftrightarrow
%! -> = \rightarrow
%! ~> = \leadsto
%! ::= = ::=
%! amp = \&
%! /= = \neq
%! vi = v_i
%! di = d_i
%! si = s_i
%! sj = s_j
%! F = \texttt{F}
%! T = \texttt{T}
%! forall = \forall
%! exists = \exists
%! empty = \emptyset
%! Sigma = \Sigma
%! eta = \eta
%! where = \textbf{where}
%! epsilon = \varepsilon
%! least = \phi
%! loop+ = loop_{+}
%! loop* = loop_{\times}
%! CatC = {\mathcal C}
%! CatA = {\mathcal A}
%! gamma = \gamma
%! {[ = \{
%! ]} = \}
%! elem = \in
%! dagger = ^\dagger
%! alpha = \alpha
%! beta = \beta
%! rho = \rho
%! @@ = \mu
%! @ = \,@\,
%! Pow = \mathcal{P}
%! Pi = \Pi
%! PiT = \Pi^{o}
%! PiEE = \Pi^{\eta\epsilon}_{+}
%! PiT = \Pi^{o}
%! PiTF = \Pi^{/}
%! bullet = \bullet
%! * = \times

\begin{document}
\conferenceinfo{POPL '14}{date, City.}
\copyrightyear{2014}
\copyrightdata{[to be supplied]}

\title{\ldots}
\authorinfo{\ldots}
           {\ldots}
           {\ldots}

\maketitle

\begin{abstract}
\ldots
\end{abstract}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Background: {{Pi}} }
\label{sec:pi}

We review our language {{Pi}} providing the necessary background and
context for our higher-order extension.\footnote{The presentation in this
  section focuses on the simplest version of {{Pi}}. Other versions
  include the empty type, recursive types, and trace operators but these
  extensions are orthogonal to the higher-order extension emphasized in this
  paper.} The terms of {{Pi}} are not classical values and functions;
rather, the terms are isomorphism witnesses.  In other words, the terms of
{{Pi}} are proofs that certain ``shapes of values'' are isomorphic.
And, in classical Curry-Howard fashion, our operational semantics shows how
these proofs can be directly interpreted as actions on ordinary values which
effect this shape transformation. Of course, ``shapes of values'' are very
familiar already: they are usually called \emph{types}.  But frequently one
designs a type system as a method of classifying terms, with the eventual
purpose to show that certain properties of well-typed terms hold, such as
safety.  Our approach is different: we start from a type system, and then
present a term language which naturally inhabits these types, along with an
appropriate operational semantics.

\paragraph*{Data.}
We view {{Pi}} as having two levels:  it has traditional values, given by:
%subcode{bnf} include main
% values, v ::= () | left v | right v | (v, v)

\noindent and these are classified by ordinary types:
%subcode{bnf} include main
% value types, b ::= 1 | b + b | b * b

\noindent
Types include the unit type {{1}}, sum types {{b1+b2}}, and product types
{{b1*b2}}.  Values include {{()}} which is the only value of type {{1}},
{{left v}} and {{right v}} which inject~{{v}} into a sum type, and
{{(v1,v2)}} which builds a value of product type.  These values should be
regarded as largely ancillary: we do not treat them as first-class citizens,
and they only occur when observing the effect of an isomorphism.

\paragraph*{Isomorphisms.} The important terms of {{Pi}} are witnesses to
(value) type isomorphisms.  They are also typed, by the shape of the (value)
type isomorphism they witness {{b <-> b}}.  Specifically, they are witnesses
to the following isomorphisms:
%subcode{bnf} include main
%! columnStyle = r@{\hspace{-0.5pt}}r c l@{\hspace{-0.5pt}}l
%swap+ :&  b1 + b2 & <-> & b2 + b1 &: swap+
%assocl+ :&  b1 + (b2 + b3) & <-> & (b1 + b2) + b3 &: assocr+
%identl* :&  1 * b & <-> & b &: identr*
%swap* :&  b1 * b2 & <-> & b2 * b1 &: swap*
%assocl* :&  b1 * (b2 * b3) & <-> & (b1 * b2) * b3 &: assocr*
%dist :&~ (b1 + b2) * b3 & <-> & (b1 * b3) + (b2 * b3)~ &: factor

\noindent Each line of the above table introduces a pair of dual
constants\footnote{where {{swap*}} and {{swap+}} are self-dual.} that witness
the type isomorphism in the middle.  These are the base (non-reducible) terms
of the second, principal level of {{Pi}}. Note how the above has two
readings: first as a set of typing relations for a set of constants. Second,
if these axioms are seen as universally quantified, orientable statements,
they also induce transformations of the (traditional) values. The
(categorical) intuition here is that these axioms have computational content
because they witness isomorphisms rather than merely stating an extensional
equality.

The isomorphisms are extended to form a congruence relation by adding the
following constructors that witness equivalence and compatible closure:

%subcode{proof} include main
%@  ~
%@@ id : b <-> b
%
%@ c : b1 <-> b2
%@@ sym c : b2 <-> b1
%
%@ c1 : b1 <-> b2
%@ c2 : b2 <-> b3
%@@ c1(;)c2 : b1 <-> b3
%---
%@ c1 : b1 <-> b3
%@ c2 : b2 <-> b4
%@@ c1 (+) c2 : b1 + b2 <-> b3 + b4
%
%@ c1 : b1 <-> b3
%@ c2 : b2 <-> b4
%@@ c1 (*) c2 : b1 * b2 <-> b3 * b4
\noindent The syntax is overloaded: we use the same symbol at the value-type level
and at the isomorphism-type level for denoting sums and products.  Hopefully
this will not cause undue confusion.

It is important to note that ``values'' and ``isomorphisms'' are completely
separate syntactic categories which do not intermix. The semantics of the
language come when these are made to interact at the ``top level'' via
\emph{application}:
%subcode{bnf} include main
% top level term, l ::= c v

\noindent
To summarize, the syntax of {{Pi}} is given as follows.

\begin{definition}{(Syntax of {{Pi}})}
\label{def:Pi}
%subcode{bnf} include main
% value types, b ::= 1 | b+b | b*b
% values, v ::= () | left v | right v | (v,v)
%
% iso.~types, t ::= b <-> b
% base iso ::= swap+ | assocl+ | assocr+
%     &|& unite | uniti | swap* | assocl* | assocr*
%     &|& dist | factor
% iso comb., c ::= iso | id | sym c | c (;) c | c (+) c | c (*) c
% top level term, l ::= c v
\end{definition}

The language presented above, at the type level, models a commutative ringoid
where the multiplicative structure forms a commutative monoid, but the
additive structure is just a commutative semigroup.  Note that the version of
{{Pi}} that includes the empty type with its usual laws exactly captures, at
the type level, the notion of a \emph{semiring} (occasionally called a
\emph{rig}) where we replace equality by isomorphism.  Semantically, {{Pi}}
models a \emph{bimonoidal category} whose simplest example is the category of
finite sets and bijections. In that interpretation, each value type denotes a
finite set of a size calculated by viewing the types as natural numbers and
each combinator {{c : b1 <-> b2}} denotes a bijection between the sets
denoted by~{{b1}} and~{{b2}}.

Operationally, the semantics of {{Pi}} is given using two mutually recursive
interpreters: one going forward and one going backwards. The use of {{sym}}
switches control from one evaluator to the other. We will present the
operational semantics in the next section along with the extension with
fractional types and values. For now, we state without proof that the
evaluation of well-typed combinators always terminates and that {{Pi}} is
logically reversible, i.e., that for all combinators {{c : b1 <-> b2}} and
values {{v1 : b1}} and {{v2 : b2}} we have the forward evaluation of {{c v1}}
produces {{v2}} iff the backwards evaluation of {{c v2}} produces {{v1}}.

As is usual with type theories, the coherence conditions (pentagonal and
triangle identity) are not explicit, but would correspond to certain identity
types being trivial.

\section{ {{Pi}} with trace}

In order to take a step toward being able to write the Int construction in
{{Pi}} to give it fractional types, we want to add a trace combinator to it,
with the following type:

%subcode{proof} include main
%@  c : b1 * b <-> b2 * b
%@@ trace c : b1 <-> b2

This kind of combinator allows us to cancel out a common factor. When the type
{{0}} is removed from the language, it is always possible to do this, but adding
computational content becomes tricky. For example, consider permutations on the
finite set of size {{6}}. If we wish to trace one of these to get a permutation
on the set of size {{3}}, we are able to, but which set of size {{3}}? There
are several different ways to do this, but there is no obvious canonical answer.

More concretely, suppose we have a combinator {{c : 3 * 2 <-> 3 * 2}}. The
combinator {{trace c : 3 <-> 3}} can be constructed in two obvious ways: let
{{(trace c) v}} run {{c}} on {{(v, true)}} or on {{(v, false)}}. It is possible
to choose {{c}} so that depending on which default value of type {{2}} is used,
a different combinator results.

To fix this, we parameterize {{trace}} with a value {{v : b}}, as follows:

%subcode{proof} include main
%@  c : b1 * b <-> b2 * b
%@  v : b
%@@ trace_v c : b1 <-> b2

It remains to show that this is ``well-behaved''; that is, we want it to obey
some (ideally all) of the trace properties, or at the very least some subset of
them that is sufficient to prove some necessary properties for {{Pi}} extended
with fractional types, as presented in the next few sections.

\subsection{Alternatives}

If this formulation of trace does not work, we have a few alternatives:

\begin{itemize}

\item Don't bother choosing a default element at all. We did this previously
with the relational semantics, without much success, but perhaps there's a
better way of looking at it.

\item Choose a canonical representative of the type {{b}} that's being traced
out. This seems like it's a strictly worse option than parameterizing it, but
it's still on the table, at least for now.

\item Focus on the combinator. Jacques pointed out that our old version of trace
``worked'' whenever the part of {{c}} acting on {{b}} was equivalent to the
identity. This seems promising, but I'm not quite sure how to think about it
yet, so I'm ignoring it for now. It's definitely something we want to look at,
though, especialy if the current approach doesn't work.

\end{itemize}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Syntax of Fractionals}

The types of {{Pi}} correspond to the natural numbers. Our goal is to have a
type system that corresponds to the (positive) rational numbers.

\begin{definition}{(Syntax of {{PiTF}})}
\label{def:PiTF}
%subcode{bnf} include main
% value types, r ::= b1 / b2
% values, f ::= (v1 |--> v2, c)
%
% iso.~types, t ::= r <=> r
% base iso ::= swap+ | assocl+ | assocr+
%     &|& unite | uniti | swap* | assocl* | assocr*
%     &|& dist | factor
%     &|& eta | epsilon
% iso comb., c ::= iso | id | sym c | c (;) c | c (+) c | c (*) c
% top level term, l ::= c v
\end{definition}

If we restrict our attention to types {{b / 1}} and values {{ () |--> v amp id}},
we recover {{Pi}}.

In algebra, the rational number {{a/b}} denotes
$\{ (a','b) ~|~ a * b' = a' * b \}$. We essentially use the same denotation but
add computational content, i.e., the type {{a/b}} denotes
$\{ (a',b',c) ~|~ c : a * b' \leftrightarrow a' * b \}$ where $c$ is a {{Pi}}
combinator witnessing the equivalence of {{a * b'}} and {{a' * b}}.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Higher-Order Reversible Functions}

To get from {{Pi}}~\cite{James:2012:IE:2103656.2103667} types and combinators
to a higher order setting, we hope to add \emph{fractional types} to the
language. Recall that to construct the (positive) rational numbers {{Q}}, we
can take pairs of positive integers {{(m, n)}} and quotient by the
equivalence relation that says {{(m1, n1)}} is equal to {{(m2, n2)}} if
{{m1 * n2 = m2 * n1}}. We can write this as an inference rule as follows:

%subcode{proof} include main
%@ m1 * n2 = m2 * n1
%@@ (m1, n1) = (m2, n2)

\noindent
Adding in computational content, pi-style, suggests that we want something like:

%subcode{proof} include main
%@ c : A1 * B2 <-> B1 * A2
%@@ {[c]} : (B1 |--> A1) <=> (B2 |--> A2)

\noindent
However, this does not quite work. To see why, recall that we want to treat the
pair {{(m, n)}} (written here as {{A |--> B}}) as an internalization of the
reversible function space. Thus, the type {{(B1 |--> A1) <=> (B2 |--> A2)}}
should be a transformation of a {{Pi}} combinator of type {{B1 <-> A1}} into a
{{Pi}} combinator of type {{B2 <-> A2}}. In order to do this, we need a trace
combinator (TODO: draw a diagram that demonstrates this) with the type

%subcode{proof} include main
%@ c : A * C <-> B * C
%@@ trace c : A <-> B

\noindent
This is an issue, since prior attempts at defining an adequate trace operator
failed: we got a language that could express all relations, but was no longer
reversible in a meaningful sense.

%%%%%%%%%%%%%%%%%%%
\subsection{Defining trace}

The trace operator had two problems: it allowed arbitrary function definition,
and it would not work in a language that contained the empty type {{0}}. The
former problem arose due to the logic programming-style interpretation we
assigned to trace: it would create *all* possible values of type {{C}}, then run
the given combinator on them and throw away the branches that did not return the
same {{C}} value.

We can solve this problem by parameterizing the trace operator with a value {{v
: C}}. This results in the following new typing rule for trace:

%subcode{proof} include main
%@ c : A * C <-> B * C
%@ v : C
%@@ trace_v c : A <-> B

\noindent
This ends up solving both problems: we give the trace a default value, and
prevent it from running on the empty type (since {{C}} now must be inhabited).
However, we still must assign dynamic semantics to trace. The na\"ive solution
of running {{c}} on the pair of the input value and {{v}} does not work, as this
is trivially irreversible---consider, for example, {{trace_v swap*}}, which
takes any value of the same type as {{v}} and returns {{v}}. Thus, the semantics
for {{trace}} must be slightly more complicated.

Recall that in {{Pi}}, combinators can be viewed as permutations on finite sets.
A combinator of type {{A * C <-> B * C}} can be seen as two separate
permutations: one on {{A}} (or equivalently, B, since they must have the same
size and thus the same denotation as a finite set) and one on {{C}}. If we
apply the fragment of the combinator that acts on {{C}} enough times, we will
eventually get out the same value that we started with\footnote{I want to prove
that this is actually true; having the extra {{A}} there seems like it might
complicate things.}. Thus, the semantics that we want is for {{(trace_v c) v'}}
to run {{c}} on the pair of {{v'}} and the last {{C}} value (starting with
{{v}}) until the {{C}} value matches {{v}}, at which point it returns the {{B}}
value returned by the combinator. In pseudocode:

\begin{verbatim}
TODO: figure out how to do the code
environment in subcode

trace v c vin =
  v0 = v
  <vout, v'> = c <vin, v>

  while (v' != v)
    <vout, v'> := c <vin, v'>

  return vout
\end{verbatim}

A more concise formulation as an inference rule is as follows:

%subcode{proof} include main
%@ exists v0 : C. c <v_{in}, v> = <v_{out}, v>
%@@ (trace_v c) v_{in} = v_{out}

This is easily reversible: {{(trace_v c)dagger = trace_v (c dagger)}}
\footnote{Also need to prove this.}.

%%%%%%%%%%%%%%%%%%%
\subsection{Higher-Order Combinators}

Now that we have the trace combinator defined, we can proceed with defining
higher-order combinators. Note that this parameterizes our definition of
$\{c\}$ by {{v}}, the value of type {{A}} (or equivalently, type {{B}}) used
in the trace:

%subcode{proof} include main
%@ c : A1 * B2 <-> B1 * A2
%@@ {[c]}_v : (B1 |--> A1) <=> (B2 |--> A2)

\noindent
We want this to be a transformation on combinators, taking a combinator of type
{{B1 <-> A1}} to a combinator of type {{B2 <-> A2}}. This can be achieved by
letting the combinator {{{[c]}_v c'}} be {{trace_v (c ; c' * id)}}, where
{{c : B1 <-> A1}} and {{v : A1}}.

From here, we want to define bifunctors {{/}}, {{*}}, and {{+}}, to make sure
that our definition of functions is truly higher-order.

\begin{itemize}

\item {{(B |--> A) / (D |--> C) = (A * D) |--> (B * C)}}, with

{{{[c1]}_{v1} : ((B |--> A) <=> (D |--> C)) / {[c2]}_{v_2} : ((B' |--> A') <=> (D' |--> C')) = {[shuffle ; c1 * c2dagger ; shuffle]}_{<v1, c2 v2>}}}
%%: B1 * A2 |--> A1 * B2 <=> D1 * C2 |--> C1 * D2}},
where
{{shuffle : (A * B) * (C * D) <-> (A * C) * (B * D)}}.

\item {{(B |--> A) * (D |--> C) = (B * D) |--> (A * C)}}, with

\end{itemize}

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

\bibliographystyle{abbrvnat}
\bibliography{cites}
\end{document}


\newpage
\subsection{Time Domain Results}
    \begin{table}[h!]
        \begin{tabular}{*{2}{L{3cm}C{3cm}C{1cm}}}
            % Basic NNI Parameters
            % --------------------------------------------------------------------------------------
            \hline
            \rowcolor{LightBlue}
            \textbf{Parameter}                      & \textbf{Value}    & \textbf{Unit} &
            \textbf{Parameter}                      & \textbf{Value}    & \textbf{Unit} \\\hline
            % --------------------------------------------------------------------------------------
            \multicolumn{6}{l}{\gcell{}\textbf{NNI Parameters}}                                 \\
            \gcell{NNI}                             & \nnicounter       & -             &
            \gcell{}$\overline{\text{NNI}}$         & \nnimean          & ms            \\
            \gcell{}\text{$NNI_{min}$}              & \nnimin           & ms            &
            \gcell{}\text{$NNI_{max}$}              & \nnimax           & ms            \\
            \gcell{}SDNN                            & \sdnn             & ms            &
            \gcell{}RMSSD                           & \rmssd            & ms            \\
            \gcell{}SDANN                           & \sdann            & ms            &
            \gcell{}\text{$SDNN_{index}$}           & \sdnnindex        & ms            \\
            \gcell{}NN20                            & \nntwenty         & -             &
            \gcell{}pNN20                           & \pnntwenty        & -             \\
            \gcell{}NN50                            & \nnfifty          & -             &
            \gcell{}pNN50                           & \pnnfifty         & -             \\
            \hline
            % Delta NNI
            % --------------------------------------------------------------------------------------
            \multicolumn{6}{l}{\gcell{}\textbf{NNI Differences Parameters}}             \\
            \gcell{}\text{$\overline{\Delta NNI}$}       & \nnidiffmean      & ms            &
            \gcell{}\text{$\Delta NNI_{min}$}            & \nnidiffmin       & ms            \\
            \gcell{}\text{$\Delta NNI_{max}$}            & \nnidiffmax       & ms            &
            \gcell{}SDSD                                 & \sdsd             & ms       \\\hline
            % HR Parameters
            % --------------------------------------------------------------------------------------
            \multicolumn{6}{l}{\gcell{}\textbf{HR Parameters}}                          \\
            \gcell{}\text{$\overline{HR}$}          & \hrmean           & bpm           &
            \gcell{}\text{$HR_{min}$}               & \hrmin            & bpm           \\
            \gcell{}\text{$HR_{max}$}               & \hrmax            & bpm           &
            \gcell{}\text{$\sigma(HR)$}                  & \hrstd            & bpm           \\\hline
            % HR Parameters
            % --------------------------------------------------------------------------------------
            \multicolumn{6}{l}{\gcell{}\textbf{Geometrical Parameters}}                 \\
            \gcell{}Triangular Index                & \triindex         & ms            &
            \gcell{}TINN                            & n/a$^1$ & -            \\\hline
            \multicolumn{6}{l}{}
        \end{tabular}
    \end{table}
    \vspace{-5mm}
    \footnotesize{$^1$TINN function is not working properly in the current pyHRV version and computes incorrect results, reason for which it is not shown in this report}
    \begin{figure}[h!]
        \includegraphics[width=\textwidth]{figures/histogram.png}
        \caption{Histogram of the NNI series.}
    \end{figure}
    \vfill


\section{Reduced formulation to local variables.}

\subsection{Formulation}

Let us start with
\begin{equation}
  \label{eq:AC-L7}
  \begin{array}{l}
  \varPhi_1(U,P) =  - U_{k+1}  + \widehat W P_{k+1}  + U_{\mathrm{free}}\\ \\
  \varPhi_2(U,P) =  P_{\n} - \proj_{\nbR^{a}_+} (P_{\n} - \rho_{\n}\circ (U_{\n} +e \circ  U_{\n,k}) ) \\ \\
  \varPhi_3(U,P) =  P_{\t} - \proj_{\widehat {\bf D}(P_{\n},U_{\n})} (P_{{\t}} - \rho_{\t}\circ \,U_{\t} )
\end{array}
\end{equation}
where the modified friction disk for a contact $\alpha$ is
\begin{equation}\label{eq:AC-L3}
  \widehat {\bf D}^\alpha(P^\alpha_{\n,k+1},U_{\n,k+1}^{\alpha}) = {\bf D}(\mu(\proj_{\nbR_+} (P^\alpha_{\n,k+1} - \rho^\alpha_{\n}\,(U_{\n,k+1}^{\alpha}+e^\alpha U_{\n,k}^{\alpha}) )).
\end{equation}
\subsection{Structure of the Jacobians}

Let us denote the one element of the  generalized Jacobian by  $ H(U,P) \in \partial \Phi(U,P)$ which has the structure
\begin{equation}
  \label{eq:AC-L6}
   H(U,P) =
   \left[\begin{array}{cccc}
       - I & 0 &  \widehat W_{\n\n} & \widehat W_{\n\t} \\ \\
       0  & -I  &  \widehat W_{\t\n} & \widehat W_{\t\t} \\ \\
       \partial_{U_{\n}} \Phi_2(U,P) & 0 &   \partial_{P_{\n}} \Phi_2(U,P) & 0 \\ \\
       \partial_{U_{\n}} \Phi_3(U,P) &  \partial_{U_{\t}} \Phi_3(U,P) &  \partial_{P_{\n}} \Phi_3(U,P)  & \partial_{P_{\t}} \Phi_3(U,P)
   \end{array}\right]
\end{equation}

\subsection{Computation of the gradients}

Let us consider the single contact case.
\paragraph{Computation of the gradients of $\Phi_2$}
\begin{equation}
  \label{eq:AC-T1}
  \begin{array}{l}
  \varPhi_2(U,P) =  P_{\n} - \proj_{\nbR^{a}_+} (P_{\n} - \rho_{\n} (U_{\n} +e  U_{\n,k}) ) \\ \\
\end{array}
\end{equation}
\begin{itemize}
\item \textbf{If} $P_{\n} - \rho_{\n} (U_{\n} +e  U_{\n,k}) \geq 0 $, we get
  \begin{equation}
    \label{eq:AC-T2}
    \begin{array}{l}
      \varPhi_2(U,P) =  + \rho_{\n} (U_{\n} +e  U_{\n,k})
    \end{array}
  \end{equation}
  and
  \begin{equation}
    \label{eq:AC-T3}
    \begin{array}{l}
     \partial_{U_{\n}} \varPhi_2(U,P) =  + \rho_{\n} \\ \\
     \partial_{P_{\n}} \varPhi_2(U,P) =  0 \\ \\
    \end{array}
  \end{equation}
\item \textbf{If} $P_{\n} - \rho_{\n} (U_{\n} +e  U_{\n,k})  < 0 $, we get
  \begin{equation}
    \label{eq:AC-T4}
    \begin{array}{l}
      \varPhi_2(U,P) =  P_{\n}
    \end{array}
  \end{equation}
  and
  \begin{equation}
    \label{eq:AC-T5}
    \begin{array}{l}
     \partial_{U_{\n}} \varPhi_2(U,P) =  0 \\ \\
     \partial_{P_{\n}} \varPhi_2(U,P) =  1 \\ \\
    \end{array}
  \end{equation}
\end{itemize}
\paragraph{Computation of the gradients of $\Phi_3$}
\begin{equation}
  \label{eq:AC-TT1}
  \begin{array}{l}
  \varPhi_3(U,P) =  P_{\t} - \proj_{\widehat {\bf D}(P_{\n},U_{\n})} (P_{\t} - \rho_{\t} U_{\t} ) \\ \\
\end{array}
\end{equation}
\begin{itemize}
\item \textbf{If} $\|P_{\t} - \rho_{\t} U_{\t}\| \leq \mu \max (0 ,P_{\n} - \rho_{\n} (U_{\n} +e  U_{\n,k}) ) $  , we get
\begin{equation}
  \label{eq:AC-TT2}
  \begin{array}{l}
  \varPhi_3(U,P) =  + \rho_{\t} U_{\t}
\end{array}
\end{equation}
and
 \begin{equation}
    \label{eq:AC-TT3}
    \begin{array}{l}
     \partial_{U_{\n}} \varPhi_3(U,P) =  0 \\ \\
     \partial_{P_{\n}} \varPhi_3(U,P) =  0 \\ \\
     \partial_{U_{\t}} \varPhi_3(U,P) =  + \rho_{\t} \\ \\
     \partial_{P_{\t}} \varPhi_3(U,P) =  0 \\ \\
    \end{array}
  \end{equation}
\item \textbf{If} $\|P_{\t} - \rho_{\t} U_{\t}\| > \mu \max (0 ,P_{\n} - \rho_{\n} (U_{\n} +e  U_{\n,k}) ) $  , we get
\begin{equation}
  \label{eq:AC-TT4}
  \begin{array}{l}
  \varPhi_3(U,P) =  P_{\t} - \mu \max(0,P_{\n} - \rho_{\n} (U_{\n} +e  U_{\n,k}) )  \Frac{P_{\t} - \rho_{\t} U_{\t} }{ \| P_{\t} - \rho_{\t} U_{\t}\| }
\end{array}
\end{equation}

\begin{itemize}
\item  \textbf{If} $P_{\n} - \rho_{\n} (U_{\n} +e  U_{\n,k}) \leq 0$, we get
  \begin{equation}
  \label{eq:AC-TT5}
  \begin{array}{l}
  \varPhi_3(U,P) =   P_{\t}
\end{array}
\end{equation}
and
 \begin{equation}
   \label{eq:AC-TT6}
   \begin{array}{l}
     \partial_{U_{\n}} \varPhi_3(U,P) =  0 \\ \\
     \partial_{P_{\n}} \varPhi_3(U,P) =  0 \\ \\
     \partial_{U_{\t}} \varPhi_3(U,P) =  0 \\ \\
     \partial_{P_{\t}} \varPhi_3(U,P) =  I_2 \\ \\
   \end{array}
 \end{equation}
\item  \textbf{If} $P_{\n} - \rho_{\n} (U_{\n} +e  U_{\n,k}) > 0$, we get
\begin{equation}
  \label{eq:AC-TT7}
  \begin{array}{l}
  \varPhi_3(U,P) =  P_{\t} - \mu (P_{\n} - \rho_{\n} (U_{\n} +e  U_{\n,k}) )  \Frac{P_{\t} - \rho_{\t} U_{\t} }{ \| P_{\t} - \rho_{\t} U_{\t}\| }
\end{array}
\end{equation}
and
 \begin{equation}
   \label{eq:AC-TT8}
   \begin{array}{l}
     \partial_{U_{\n}} \varPhi_3(U,P) =  \mu \rho_{\n}  \Frac{P_{\t} - \rho_{\t} U_{\t} }{ \| P_{\t} - \rho_{\t} U_{\t}\| }\text{{\bf WARNING} case was not taken into account}\\ \\
     \partial_{P_{\n}} \varPhi_3(U,P) =  -\mu  \Frac{P_{\t} - \rho_{\t} U_{\t} }{ \| P_{\t} - \rho_{\t} U_{\t}\| } \\ \\
     \partial_{U_{\t}} \varPhi_3(U,P) =  \mu\rho_{\t}(P_{\n} - \rho_{\n} (U_{\n} +e  U_{\n,k}) ) \Gamma(P_{\t} - \rho_{\t} U_{\t})  \\ \\
     \partial_{P_{\t}} \varPhi_3(U,P) =  I_2-\mu(P_{\n} - \rho_{\n} (U_{\n} +e  U_{\n,k}) ) \Gamma(P_{\t} - \rho_{\t} U_{\t})  \\ \\
   \end{array}
 \end{equation}
\end{itemize}

\end{itemize}

\subsection{Rearranging the cases}

{\bf TO BE COMPLETED}
\section{Formulation with global variables.}

\subsection{Formulation}
Let us start with
\begin{equation}
  \label{eq:GAC-L1}
  \begin{array}{l}
  \Psi_{1}^{a}(v,U,P) =  - \widehat M v_{k+1}  +  H P_{k+1}  + q \\ \\
  \Psi_{1}^{b}(v,U,P) =  - U_{k+1}  + H^\top v _{k+1}  + b \\ \\
  \Psi_2(v,U,P) =  P_{\n} - \proj_{\nbR^{a}_+} (P_{\n} - \rho_{\n}\circ (U_{\n} +e \circ  U_{\n,k}) ) \\ \\
  \Psi_3(v,U,P) =  P_{\t} - \proj_{\widehat {\bf D}(P_{\n},U_{\n})} (P_{{\t}} - \rho_{\t}\circ \,U_{\t} )
\end{array}
\end{equation}
where the modified friction disk for a contact $\alpha$ is
\begin{equation}\label{eq:GAC-L2}
  \widehat {\bf D}^\alpha(P^\alpha_{\n,k+1},U_{\n,k+1}^{\alpha}) = {\bf D}(\mu(\proj_{\nbR_+} (P^\alpha_{\n,k+1} - \rho^\alpha_{\n}\,(U_{\n,k+1}^{\alpha}+e^\alpha U_{\n,k}^{\alpha}) )).
\end{equation}

\subsection{Structure of the Jacobians}

 Let us denote the one element of the  generalized Jacobian by  $ H(v,U,P) \in \partial \Psi(s,U,P)$ which has the structure
\begin{equation}
  \label{eq:GAC-L3}
   H(v,U,P) =
   \left[\begin{array}{ccccc}
       - \widehat M & 0 & 0 & H_{\n} & H_{\t} \\ \\
        H_{\n}^\top &  - I & 0 & 0 &0 \\ \\
        H_{\t}^\top &  0  & -I & 0 &0 \\ \\
        0 & \partial_{U_{\n}} \Psi_2(v,U,P) & 0 &   \partial_{P_{\n}} \Psi_2(v,U,P) & 0 \\ \\
        0 & \partial_{U_{\n}} \Psi_3(v,U,P) &  \partial_{U_{\t}} \Psi_3(v,U,P) &  \partial_{P_{\n}} \Psi_3(v,U,P)  & \partial_{P_{\t}} \Psi_3(v,U,P)
   \end{array}\right]
\end{equation}

We clearly have
\begin{equation}
  \label{eq:equivalentJacobian}
  \begin{array}{lcl}
     \partial_{U} \Psi_2(v,U,P) &=& \partial_{U} \Phi_2(U,P) \\
     \partial_{P} \Psi_2(v,U,P) &=& \partial_{P} \Phi_2(U,P) \\
     \partial_{U} \Psi_3(v,U,P) &=& \partial_{U} \Phi_3(U,P) \\
     \partial_{P} \Psi_3(v,U,P) &=& \partial_{P} \Phi_3(U,P) \\
  \end{array}
\end{equation}
and we get
\begin{equation}
  \label{eq:GAC-L4}
   H(v,U,P) =
   \left[\begin{array}{ccccc}
       - \widehat M & 0 & 0 & H_{\n} & H_{\t} \\ \\
        H_{\n}^\top &  - I & 0 & 0 &0 \\ \\
        H_{\t}^\top &  0  & -I & 0 &0 \\ \\
        0 & \partial_{U_{\n}} \Phi_2(U,P) & 0 &   \partial_{P_{\n}} \Phi_2(U,P) & 0 \\ \\
        0 & \partial_{U_{\n}} \Phi_3(U,P) &  \partial_{U_{\t}} \Phi_3(U,P) &  \partial_{P_{\n}} \Phi_3(U,P)  & \partial_{P_{\t}} \Phi_3(U,P)
   \end{array}\right]
\end{equation}

\subsection{Simplification ?}
Since the second line $\Psi_1^b$ is linear, we should be able to derive a reduced Jacobian using the chain rule. Let us define $\widetilde \Psi$
\begin{equation}
  \label{eq:chainrule}
  \widetilde \Psi(v,P)  = \Psi(v,H^\top v +b,P)
\end{equation}

\begin{equation}
  \label{eq:GAC-L5}
  \begin{array}{l}
  \widetilde \Psi_{1}(v,P) =  - \widehat M v_{k+1}  +  H P_{k+1}  + q \\ \\
  \widetilde \Psi_2(v,P) =  P_{\n} - \proj_{\nbR^{a}_+} (P_{\n} - \rho_{\n}\circ (H^\top_{\n}v+b_{\n} +e \circ  U_{\n,k}) ) \\ \\
  \widetilde \Psi_3(v,P) =  P_{\t} - \proj_{\widehat {\bf D}(P_{\n},U_{\n})} (P_{{\t}} - \rho_{\t}\circ \,(H^\top_\t v + b_\t) )
\end{array}
\end{equation}

\paragraph{Chain rule}
\begin{equation}
  \label{eq:chainrule1}
  \begin{array}{lcl}
  \partial_v \widetilde \Psi_{2,3}(v,P) &=&  \partial_v \Psi_{2,3}(v,H^\top v +b,P)  \\ \\
  &=& H_{\n}^\top \partial_{U_\n} \Phi_{2,3}(H^\top v + b,P) + H_{\t}^\top \partial_{U_\t} \Phi_{2,3}(H^\top v + b,P)
\end{array}
\end{equation}

\begin{equation}
  \label{eq:GAC-L6}
   H(v,P) =
   \left[\begin{array}{ccc}
       - \widehat M &   H_{\n} & H_{\t} \\ \\
       H_{\n}^\top \partial_{U_\n} \Phi_{2}(H^\top v + b,P) &   \partial_{P_{\n}} \Phi_2(H^\top v + b,P) & 0 \\ \\
       \begin{array}{c}
         H_{\n}^\top \partial_{U_\n} \Phi_{3}(H^\top v + b,P) \\
         \quad \quad + H_{\t}^\top \partial_{U_\t} \Phi_{3}(H^\top v + b,P)\\
     \end{array}
     &  \partial_{P_{\n}} \Phi_3(H^\top v + b,P)  & \partial_{P_{\t}} \Phi_3(H^\top v + b,P)
   \end{array}\right]
\end{equation}

\paragraph{discussion}
\begin{itemize}
\item Formulae has to be checked carefully
\item I do not known if there an interest in the simplification. With sparse matrices, it is perhaps easier to deal with~(\ref{eq:GAC-L4})
\end{itemize}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: t
%%% End:


\chapter{Evaluation}
\section{Correctness}
For correctness, we create two virtual topologies : Vt1($h1,h2,h3$) and Vt2($h4,h5,h6$). Hosts in Vt1 and Vt2 must be able to talk to each other. And, since tenants are \emph{isolated} from each other, hosts of Vt1 should not be able to talk to Vt2 and vice-versa. The results of a \verb|pingall| operation in Mininet gives the following results, thus verifying correctness.
\begin{verbatim}
	> pingall
	h1 -> h2 h3 X X X
	h2 -> h1 h3 X X X
	h3 -> h1 h2 X X X
	h4 -> X X X h5 h6
	h5 -> X X X h4 h6
	h6 -> X X X h4 h5
\end{verbatim}
\section{Virtual Topology Mapping}
We create a \verb|TopologyCreator| class to create ring and tree topologies of custom length and depth respectively. To analyse the time complexity of mapping the virtual topology onto the physical topology, we create a tree topology of depth 10 as our physical topology and map virtual topologies of varying size and measure the time taken for the mapping. As we can observe in Figure 6.1 and 6.2, the time taken to calculate the mapping is constant across different virtual topologies(and less than 0.1 of a second). This follows from the algorithm as well, as the time complexity depends on the size of the physical topology.
\begin{figure}
	\noindent
	\makebox[\textwidth]{\includegraphics[width=15cm]{Figures/vtmt.png}}%
	\caption{Virtual Topology Mapping for varying tree topologies}
\end{figure}

\begin{figure}
	\noindent
	\makebox[\textwidth]{\includegraphics[width=15cm]{Figures/vmtr.png}}%
	\caption{Virtual Topology Mapping for varying ring topologies}
\end{figure}

\section{Network Route Calculation}
The next step is to calculate the \emph{complete} network routes between every pair of hosts in the virtual topology. We can infer that this time will be dependent on the sizes of both the virtual topology and physical topologies and the mapping heuristic used. Since we try to minimise the diameter of the mapped virtual network graph, we would obtain better results than other mapping schemes. The physical topology is a tree topology of depth 10 and we vary the mapped virtual topology sizes. Figures 6.3 and 6.4 plot the time taken to calculate the network routes for the varying virtual topologies.

\begin{figure}
	\noindent
	\makebox[\textwidth]{\includegraphics[width=15cm]{Figures/nrt.png}}%
	\caption{Network Route Calculation for varying tree topologies}
\end{figure}

\begin{figure}
	\noindent
	\makebox[\textwidth]{\includegraphics[width=15cm]{Figures/nrr.png}}%
	\caption{Network Route Calculation for varying ring topologies}
\end{figure}


\section{STM Version Manual}
\subsection{Read the time}
\begin{center}
\includegraphics[width=0.6\textwidth]{../Graphics/Time3_15}
\end{center}
To read the Watch it is necessary to activate the Display this can be either done via double tapping the Housing or raising the arm to take a look on the watch(tilt it by a minimum of 12 degrees with the Watchface facing up and holding it steady for about one second)

\paragraph{Analog}
The analog Version an be read equally to a normal Watch.
In the inner Ring the Hours from 1 to 12 are displayed.
In the outer Ring the minutes are displayed from 0 to 59,
since there are only 30 LEDs in the outer ring for uneven minutes the nearest two LEDs are lit up.
For example for 3:15 the LEDs signalling 14 and 16 are lit up.

\paragraph{Binary}
in the Binary Version the LEDs are read columnwise as BCD code starting with 1 at the bottom. So the right two columns are showing the Minutes. If an LED is litone have to add its Value to the Minutes if not then nothing is added. So for the full hour no led in the right two columns will be lit.
In the example above in the first column no LED is lit. In the second column the LED for 1 and 2 are lit. In the third column the LED for 1 is lit and in the last column the LED for 1 and 4 are lit.
So it is 3:15.
\subsubsection{setting the Time}
To enter the Time setting mode you have to turn the Watch in show time mode upside down, Watchface facing the ground an double Tap it. The Watch enters debouncing mode.
In debouncing mode the Hours 80 and Minutes 80 are blinking for the binary version for the Analog Version Hours 12 and 6 are blinking. (Blinking leds are displayed brighter in the graphic.
\begin{center}
\includegraphics[width=0.6\textwidth]{../Graphics/Time3_15_debouncing}
\end{center}
While in debouncing mode turn the watch around again (Watchface facing up)  and double Tap it again to enter Set Hour mode.
\begin{center}
\includegraphics[width=0.6\textwidth]{../Graphics/Time3_15_SetHour}
\end{center}
In the set hour mode the hour can be increased by leaning the Watch away from you and decreased by leaning the watch towards you. In the Analog Version the LED signalling 10 Minutes is blinking, when the current hour setting is PM.
Once the hour is set correctly double Tap the Watch again to enter Set Minute Mode.
\begin{center}
\includegraphics[width=0.6\textwidth]{../Graphics/Time3_15_SetMinute}
\end{center}
The Set hour mode works exactly like to set hour mode. Increasing and decreasing is done via leaning the Watch fowrward an backward. Once finished a double Tap sets the Seconds to 0 and starts the Watch again.
\subsection{Read the Date}
\begin{center}
\includegraphics[width=0.6\textwidth]{../Graphics/Date25_Dez}
\end{center}
To enter the Date display mode tilt the Watch in Time Mode to the Front(Facing away from you) at least 10 degrees and double Tap it.
\paragraph{Analog}
On the analog Version The Minutes 40 and 50 are lit up to signal Date Display.
On the Hours Ring the Month is displayed as Hour and the Day is Displayed as Minutes.

\paragraph{Binary}
On the binary Version the first column is showing 3 to signal Date Display.
In the second and third column the Day is displayed as BCD Code and the Month is displayed in binary code(it does not stop on 9)\\
\\
A double Tap with the watch facing up switches back to show time mode.

\subsubsection{setting the Date}
To enter the Date setting mode you have to turn the Watch in show date mode upside down, Watchface facing the ground an double Tap it. The Watch enters debouncing mode.
In debouncing mode the Hours 8 and Minutes 80 are blinking for the binary version for the Analog Version Minutes 40 and 50 are blinking. (Blinking leds are displayed brighter in the graphic.
\begin{center}
\includegraphics[width=0.6\textwidth]{../Graphics/Date25_Dez_debouncing}
\end{center}
While in debouncing mode turn the watch around again (Watchface facing up)  and double Tap it again to enter set day mode.
\begin{center}
\includegraphics[width=0.6\textwidth]{../Graphics/Date25_Dez_SetDay}
\end{center}
Setting the Day works exactly like setting the hour. Increasing and decreasing is done via leaning the Watch fowrward an backward. Once finished a double Tap switches to set month mode.
\begin{center}
\includegraphics[width=0.6\textwidth]{../Graphics/Date25_Dez_SetMonth}
\end{center}
Setting the Month works exactly like setting the hour. Increasing and decreasing is done via leaning the Watch fowrward an backward. Once finished a double Tap switches to set year mode.
\begin{center}
\includegraphics[width=0.6\textwidth]{../Graphics/Date25_Dez_SetYear21}
\end{center}
The year is only used for the leap year calculation and can be only set between 0 and 99.
\paragraph{Analog}
In the Analog Version the Set year mode is signalized by blinking both minute LEDs 30 and 50. The Year tens are shown in the inner ring with one LED per Counter and the ones are shown in the outer ring with one LED per counter. In this example XX21.
\paragraph{Binary}
Setting Year mode is displayed by showing 3 in the first column and blinking all LEDs in the second column. The year is displayed in columns 3 and 4. In this example XX21.\\
\\
Setting the Month works exactly like setting the hour. Increasing and decreasing is done via leaning the Watch fowrward an backward. Once finished a double Tap sets the Seconds to 0 and starts the Watch again.
\subsection{Todays Steps}
\begin{center}
\includegraphics[width=0.6\textwidth]{../Graphics/ShowSteps32768}
\end{center}
To enter Step display mode tilt the Watch in Time Mode to the Back(Facing you) at least 10 degrees and double Tap it.
\paragraph{Analog}
On the Analog Watch the hour LED 11 is lit up with the overflow counter (from 0(12 o'clock) to 3. The overflow counter counts the number of whole rounds on the Stepcounter. An overflow occurs on 15000. The current Stepcounter without overflow is displayed in the outer Ring. Each LED signalizes 500 Steps. The value is rounded to 500.
In the Example the overflow counter shows 2 and the counter itself shows 6.
$2*15000+6*500 = 33000$
\paragraph{Binary}
On the binary Watch the Step Counter is signalized by the forst column showing 7. Column 2 to 4 shows the steps in 100 counts rounded to 100 counts. So 32768 in the exmample will be shown as (7)328\\
\\
A double Tap with the watch facing up switches back to show time mode.

\subsection{Show steps history}
To enter the steps history mode you have to turn the Watch in show steps mode upside down, Watchface facing the ground an double Tap it.
\begin{center}
\includegraphics[width=0.6\textwidth]{../Graphics/ShowStepsHist_2Days_ago_7500}
\end{center}
The history counter can be increased and decreased by leaning the watch back and forth.
\paragraph{Analog}
The steps history mode looks like the Show steps mode, but there is an additional LEDas Hitory Counter lit up. The History counter starts at Hour 4 and increases depending on how far ago the Date is. In the Example Hour 5 is shown, so the history is from 2 days ago. The steps are show as in the Show Steps mode, so there were 7500 Steps done two days ago.
\paragraph{Binary}
The steps hitory mode is signalized by the H80 LED. The LEDs below show how long ago the Steps were counted, the counter starts yesterday with 0. so the example shows the Data from 2 Days ago. The steps are displayed as in the show steps mode. so the example shows 7500 Steps 2 days ago.\\
\\
to leave this mode double tap changes to the show Battery Voltage.
\subsection{show battery voltage}
To enter the steps history mode you have to double tap the Watch in show steps history mode.
\begin{center}
\includegraphics[width=0.6\textwidth]{../Graphics/ShowUBatt_2950mV}
\end{center}
\paragraph{Analog}
The show battery voltage is signalized by the Hour 11 and 12 lighting up together. The voltage is shown on the minutes ring, scaled from 3.5V to 1,5V, so each quarter is 0,5V. The Watch in the example is showing 2,95V.

\paragraph{Binary}
The show battery voltage is signalized by the Hour 40 LED. Column 2 to 4 are showing the Battery voltage in 10mV granularity. So the Example shows $2950mV=2,95V$\\
\\
A double Tap with the watch facing up switches back to show steps mode.