\documentclass[11pt]{article}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{graphicx}
\usepackage[font=small,labelfont=bf]{caption}
\usepackage{subcaption}
\usepackage{float}
\usepackage[font={small}]{caption}
\usepackage{setspace}
\usepackage[margin=30mm]{geometry}
\usepackage{listings}

\usepackage{fancyhdr} % Custom headers and footers
\pagestyle{fancyplain} % Makes all pages in the document conform to the custom headers and footers
\fancyhead{} % No page header - if you want one, create it in the same way as the footers below
\fancyfoot[L]{} % Empty left footer
\fancyfoot[C]{\textit{spline\_slit} Documentation} % Empty center footer
\fancyfoot[R]{\thepage} % Page numbering for right footer
\renewcommand{\headrulewidth}{0pt} % Remove header underlines
\renewcommand{\footrulewidth}{0pt} % Remove footer underlines
\setlength{\headheight}{13.6pt} % Customize the height of the header

%\numberwithin{equation}{section} % Number equations within sections (i.e. 1.1, 1.2, 2.1, 2.2 instead of 1, 2, 3, 4)
%\numberwithin{figure}{section} % Number figures within sections (i.e. 1.1, 1.2, 2.1, 2.2 instead of 1, 2, 3, 4)
%\numberwithin{table}{section} % Number tables within sections (i.e. 1.1, 1.2, 2.1, 2.2 instead of 1, 2, 3, 4)

\newcommand{\horrule}[1]{\rule{\linewidth}{#1}} % Create horizontal rule command with 1 argument of height

\title{
\normalfont \normalsize
\textsc{Northumbria University: Mathematics and Information Sciences Solar group} \\ [25pt] % Your university, school and/or department name(s)
\horrule{0.5pt} \\[0.4cm] % Thin top horizontal rule
\huge Spline Slit Code Document \\ % The assignment title
\horrule{2pt} \\[0.5cm] % Thick bottom horizontal rule
}

\author{Krishna Mooroogen\\Oliver Scott\\Dr. Richard Morton} % Your name

\date{\normalsize\today} % Today's date or a custom date

\begin{document}

\maketitle % Print the title
\newpage
\section{Introduction}
The following document provides user documentation for the \textit{spline\_slit.pro} code, developed to create time-distance data from cross cuts perpendicular to the central axis of a feature in order track dynamics. The routine can be applied to both straight and curved features making it a versatile option for solar atmospheric physics where the feature can have a variety of different shapes, e.g., coronal loops, spicules, filaments. The code detailed in this document is developed in IDL for the use in (but not limited to) solar physics research. In this document you will find a step by step guide of the use and execution of the code along with image examples.

The code was initially developed by Oliver Scott as part of a summer project and is maintained and updated by Dr Richard Morton.

\section{Implementation}

The routine takes as input the coordinates of points along the feature of interest, which are supplied by the user either as an array or by `point and click'. The supplied coordinates are fit with a spline function (\textit{spline\_p}) to achieve a finer resolution of the features coordinates. The level of resolution can be set by the user. Once the spline fit has been obtained, the normal vectors are calculated at approximately equally spaced locations (see notes) along the features - with the distance between vectors able to be modified by the user. The normal vectors are used for the calculation of a cross-cut of certain length, from which time-distance diagrams are obtained. The coordinates of the cross-cut are obtained from a vector equation of the line and the data at the calculated coordinates are extracted via cubic interpolation (\textit{interpolate}). The length of the cross-cut can be specified by the user.

\section{Capabilities}

The Spline Slit code comes with a number of optional additions that further enhance its use. A summary of the key features of the code are:
\begin{itemize}
   \item Any complex shape of the feature can be fit, if a large enough number of initial coordinates are supplied.
  \item Feature selection can be defined manually with mouse click or by data coordinates.
    \item User defined images can be parsed into the routine for feature selection, e.g. the use of unsharp masking to enhance an image for feature selection but do not wish to use the unsharp masked image for further science.
   \item The user is able to define the spacing between points on the fitted spline curve - see section overview.
  \item Users are able to specify the length of the cross-cut they would like to apply.
  \item Option to use anchor points for complex shapes - only designed for implementation with fitting features that are semi-elliptical.
   \item Over plotting of normal vectors to show direction of time distance diagram/cross cut.
\end{itemize}

\section{Overview}
\subsection{Basic Use}

The following code segment describes the most basic use of Spline Slit.

\lstinputlisting[language=IDL,lastline=2]{laidl.pro}

\noindent Here, ``data" is the input and must be a data cube (x,y,t). It is important for the user to note that large data cubes will take longer to process and therefore is advised for a suitable region of interest (ROI) to be first defined before input. The displayed image is a summed image over the data time frames. The summed image gives the user an approximate ``feel" for where the feature appears most in time. The Keyword \texttt{slits} and the receiving variable ``td" will output the resulting time-distance diagrams. Entering the above code into the IDL terminal will result in a terminal prompt reading, ``Please select 6 points to make track" and an image plot to the screen with the summed input ROI displayed. The number of points used for fitting is specified via the \texttt{pickn} keyword.

%#####################################################################
\begin{figure}[t!]
\centering
\begin{subfigure}{7cm}
\includegraphics[scale=0.47, clip=true, viewport=1.5cm 1cm 18cm 13cm]{firstplot}
\caption{ROI image before point selection, the image is summed over the time frames available in the data cube.\tiny}
\label{firstplot}
\end{subfigure}
\hfill
\begin{subfigure}{7cm}
\includegraphics[scale=0.47, clip=true, viewport=1.5cm 1cm 18cm 13cm]{secondplot}
\caption{ROI summed image after the 6 points have been selected, the white line shows the polynomial fit through the 6 points across the axis of the selected feature.\tiny}
\label{secondplot}
\end{subfigure}
\caption{ROI images of before and after point selection. Dark fibrils can be seen in the image which are the target of interest.\tiny}
\end{figure}
%#####################################################################

After selecting six points with the mouse, the points will be fit with a spline. This will serve as the guideline along the features axis, to which perpendicular  cross-cuts will be calculated. The user is advised to use six points minimum for the guideline where available. The number of points is defined with the keyword \texttt{pickn}. The terminal prompt will change the requested number of points reflecting the input in the keyword \texttt{pickn}.

The output ``td" will be a data cube of intensity time-distance diagrams for the number of cross-cuts number along spline track. The number of time- distance diagrams depends on the number of points input or the spacing set by the \texttt{spacing} keyword. The routine will make a cross-cut at every available position in the fitted spline if the \texttt{spacing} keyword is not set. If the \texttt{spacing} keyword is set, it imposes a separation distance between each cross cut. It is suggested the user experiment with this feature to grasp the idea.

\medskip
It is important to note that due to the way the \textit{spline\_p} routine works in IDL the spacing between points will not exactly match the spacing interval set in the keyword. An estimate of the spacing can be obtained by calling the \texttt{curvepoints} keyword to obtain the x,y coordinates of the spline. To achieve an actual spacing as close as possible to the desired spacing, it is preferential to use the \texttt{oversample} keyword. This oversamples the spline fit increasing the point density and, using a linear approximation for the distance between spline points, cumulatively sums the inter-spline-point distance till the total length reaches the desired spacing. The more the curve is oversampled, the greater the accuracy of the linear approximation and also the desired spacing. Oversampling by a factor of two or three usually gives a reasonable accuracy, i.e. to 2-3 decimal places. The time for the routine to run obviously increases as the amount of oversampling increases. The keyword should be called as, e.g., \texttt{oversampling=2} for an increase of $10^2$ number of spline points.

%#####################################################################
\begin{figure}[t!]
\centering
\begin{subfigure}{7cm}
\includegraphics[scale=0.47, clip=true, viewport=1.5cm 1cm 18cm 13cm]{unsh}
\caption{ROI unsharped masked image supplied by user by the \texttt{intim} keyword. \tiny}
\label{unsh}
\end{subfigure}
\hfill
\begin{subfigure}{7cm}
\includegraphics[scale=0.47, clip=true, viewport=1.5cm 1cm 18cm 13cm]{vec}
\caption{ROI summed image between the time frames 0 and 227. Over plotted is the normal vectors showing the direction of the time distance diagrams along the feature.\tiny}
\label{vec}
\end{subfigure}
\caption{ROI images showing the use of the  optional keywords.\tiny}
\end{figure}
%#####################################################################

\newpage
\subsection{Example}
The following examples details a more advanced use of the routine using the optional keywords.

\lstinputlisting[language=IDL,firstline=5,lastline=7]{laidl.pro}

Here the keyword \texttt{intim} has been used to specify an unsharp masked image to use as a guide when selecting the spline points. The \texttt{distance} keyword is used to specify the length of the cross cut. The \texttt{gpoints} and \texttt{curvepoints} keywords output the data points of the selection points and the data points of the spline curve respectively. The \texttt{frames} keyword has been used here to define the time interval in which the display image will be summed over.

\lstinputlisting[language=IDL,firstline=3,lastline=5]{laidl.pro}

Here the \texttt{vector} keyword displays the normal vector on the plot indicating the direction of the time distance diagram.

%#####################################################################
\begin{figure}[t!]
\centering
\includegraphics[scale=1, clip=true, viewport=1.5cm 5cm 18cm 8cm]{td}
\caption{Image showing time distance diagram as an output of the routine. The image has been rotated and the aspect ratio increased.\tiny}
\label{td}
\end{figure}
%#####################################################################

\newpage
\subsection{Optional Keywords}

Here we list the optional keywords and their purpose.
\begin{itemize}
\item Inputs

\textit{distance} - Integer value variable. Sets the half length of the time distance slit, the default is set as ten. Change this variable to change displacement length of the time distance diagram.

\textit{frames} - The image used for point selection is an average of entire data set, enter array [t1,t2] to select specific frames for averaging. Input should be integer array within limits of data's third dimension.

\textit{pickn} - If set, will use the procedure \texttt{pick\_n} to enable the user to select points by clicking on an image. This should be set to an integer value of the number of points required to spline to. For example setting the value \texttt{pickn=6}, the routine will expect the user to click to define six points on the feature of interest.

\textit{gpoints} - Specifies guide values for/from the spline fit. Can be used as an input or an output. As an input, give the spline points values instead of picking them with \texttt{pickn}. The value of \texttt{gpoints} must be an integer array of dimensions (N,2). If both \texttt{gpoints} and \texttt{pickn} are set, the values of \texttt{gpoints} will be ignored and overwritten. As an output, returns the values from the picking of points used with the \texttt{pickn} routine.

\textit{vector} - Over plots normal vectors to the existing plot indicating the direction of the time distance diagram along the curved guideline.

\textit{spacing} - Integer scalar value that gives the spacing between points on the fitted curve. If unset, the default spacing will be used in accordance with the IDL routine \texttt{spline\_p}. NOTE: \texttt{spline\_p} intervals typically do not give the desired spacing value (normally smaller values). To get intervals close to desired spacing, use the oversample keyword.

\textit{oversample} - Over samples the curve in \texttt{spline\_p} by $10^oversample$ - obviously large values of oversample will take a long time.

\textit{anchor} - Will use first and last selected points as anchor points for defining a curve, not used in slit extraction.

\textit{intim} - User supplied image to use for picking the guide points. For example if the user would like to use a filtered image to track the feature but does not want to use the filtered image in the time distance diagram.

\item Outputs

\textit{curvepoints} - Outputs the spline data points.

\textit{slits} - Cube of time distance diagrams (displacement, time and time distance number).

\textit{gpoints} - As an output when used in combination with the \texttt{pickn} keyword, the output variable will contain the data points of the selected guide points.

\end{itemize}

\section{Notes}

Care needs to be taking with selecting points for the tracking. Clicking on the edge of the display window will register with the routine as a location. So, when switching computer windows ensure you click the grey bar above the x11 window and not on the plot area.

The default output will be displacement, time and time distance number and therefore the user may wish to rotate the time distance diagram. Depending on the slit length the aspect of the resulting plot may need changing to be visible.

Designed for time distance but in reality will work with any cube therefore can be utilised interestingly for different cases of tracking an image over the third image dimension.

\end{document}


ConFS API has 5 operations: create a file, delete a file, read from a file, write a file, extend a file, and change owner of a file. These operations are atomic and confidential.

ConFs consists of 5 basic layers: disk, crypto, cache, list, and authentication. Disk and crypto layers are used in implementing the log. Cache layer is used to implement log cache. List layer is used to provide transactional operations. Authentication layer is used to provide access control on file level.

Disk and crypto disk are composed to CryptoDisk composite layer. Log is implemented on top of CryptoDisk layer. CryptoDisk is composed with Cache layer to create CachedDisk layer. Log cache is implemented on CachedDisk layer.

Log cache's interface is abstracted into LoggedDisk layer. LoggedDisk layer includes one operation for each function in log cache's interfaces. Semantics of those are implemented to reflect effects of the underlying functions. This correspondence is proved with a simulation proof.

LoggedDisk is composed with List layer to form TransactionCache layer. Transaction interface is implemented on top of TransactionCache layer. Transaction interface also gets abstracted into TransactionalDisk layer in a similar fashion to log cache.

TransactionalDisk is composed with Authentication Layer to form AuthenticatedDisk layer. Block allocators, inodes, and files are implemented on top of AuthenticatedDisk layer. Finally, the file interface is abstracted into File layer, which is the ConFs API.

{\color{red} IMAGE HERE FOR LAYERS AND ORGANIZATION}

\section{Layer Operations}
\subsection{Disk}
Disk layer offers 3 operations: Read, Write and Sync. It is parameterized by a type of the address (A), a decidable equality over addresses (EqDec A), the type of data stored (V), and an address predicate to determine if an address is in domain (A -> Prop).

It models the disk itself with a total function (A -> (V, list V)). The first component represents the latest value on the disk, while the second component represents previous values on that address since the last sync operation. Old values are used to determine the state after a reboot.

Read takes an address and returns the latest value on the disk for that address if it is in the domain. If the input address is not in the domain, then the execution gets "stuck". A stuck execution can be thought of as throwing an exception.

Write takes an address and a data block and updates the disk for that address if the address is in the domain. If the input address is not in the domain, the execution gets "stuck".

Write a v : d ==> d[a] := (v, (fst d[a] :: snd d[a]))

Sync empties all the old values from the disk and leaves only the latest values, meaning that all the writes to the disk are made durable.

{\color{red} REBOOT BEHAVIOR HERE}

\subsection{Crypto}
Crypto layer offers 4 operations: GetKey, Encrypt, Decrypyt, and Hash. Its state consists of a list of generated keys and a map for hashed data and their hash values. A map for plain data is also present, along with the key that is used for encryption, and the encrypted data itself.

GetKey returns a new encryption key that has not been generated before.
Layer keeps track of the generated keys to ensure when a new key is created, it is unique. We use nondeterminism tokens to supply a new key every time the GetKey operation is called. If the key supplied by the token key has been generated before, the execution gets "stuck". This ensures a successful implication implies each returned key is unique.

Encrypt and Decrypt are symmetric key encryption and decryption operations.
We model the encryption and decryption function axiomatically. They are defined as abstract functions, and an axiom stating that they are inverse of each other for a given key is assumed.

Since these are abstract functions, Layer keeps track of provided and returned keys, plaintexts, and ciphertexts in its state to ensure consistency between calls. Layer stores all this information in a map with type (ciphertext -> option (key  * plaintext)). The operational semantics of Encrypt/Decrypt operations ensures that returned values are consistent with the encryption history of the system. Similar to GetKey, execution gets 'stuck' if there is an inconsistency.

The Hash operation also acts similarly to Encrypt/Decrypt.The Hash function is defined abstractly, and operational semantics enforce consistency and collision-freeness by keeping track of the hashed values and their hashes in a map.

{\color{red} REBOOT BEHAVIOR HERE}

\subsection{Cache}
The Cache layer offers 3 operations: Read, Write and Flush. Just like the disk layer, it is parameterized by a type of the address (A), a decidable equality over addresses (EqDec A), and the type of the data stored (V). It models the cache as a partial function (A -> option V).

Read takes an address and returns (Some V) if there is an entry for the input address, and returns None otherwise.

Write takes an address and a block of data, then updates the cache with the corresponding mapping. If an entry exists that corresponds with the input address, it gets overwritten.

Flush empties the cache, effectively removing all existing entries within it.

ConFs uses its cache layer as an in-memory log cache. Therefore when the system reboots, the cache state becomes empty.

\subsection{List}
The List layer offers 3 operations: Get, Put, and Delete. It is parameterized by the type of the data stored (V). It is used to model the active transaction as a list of (address, block) pairs. Get returns the stored list. Put appends its input to the stored list. Delete replaces the stored list with an empty one.

Since ConFs uses this layer to model in-memory transactions, its state becomes an empty list after a reboot. This corresponds to the fact that a crash wipes the contents of the memory.

\subsection{Authentication}
The Authentication layer has no state and a single operation: auth. It is used to enforce access control in the system. Auth operation takes a user as an argument and compares its input with the current user that is executing the operation. If they are the same user, then it returns true. Otherwise, it returns false.

Since this layer doesn't have any state, it reboots to the same state.

\section{Design}
ConFs consists of 3 components, where each component is abstracted with a layer before connecting to the component that depends on it. These three components are log, transaction, and file components. Log component consists of checksum-based log (Log.v) and in-memory log cache (LogCache.v) on top of it. Transaction component contains implementation of a transaction system (Transaction.v). File component includes block allocator (BlockAllocator.v), inode (Inode.v), and file (File.v) implementations.

\subsection{Log Component and Logged Disk}
\subsubsection{Log Component}
Log component consists of checksum-based, encrypted, write-ahead log and a log cache on top of it to speed up reads that are on the log.

\subsubsection*{Write-ahead Log}
Write-ahead log has a structure of a header block followed by a fixed number of log blocks. Whenever a new write comes in, it gets encrypted with a fresh key, written to the end of the valid portion of the log, and the header is updated to reflect the new state of the log.

Header consists of two parts: a current part and an old part. During normal operations, the current part is used. The old part is utilized during recovery top rollback of the log in case a partial write to the log happens.

Each part contains the following: a hash of the log, number of valid blocks in the log, and a list of transaction records. A transaction record contains an encryption key, start index of the transaction on the log and number of address and data blocks in the transaction. This information is used during applying the transaction and recovery.

\paragraph{Requirement for encryption.}
One unusual feature of ConFs is that blocks in the log are encrypted. This design choice was made to prevent a specific attack (or accidental leakage). The goal of the attacker is guessing what was sitting on the log before it was applied. Simplified attacks can be described as follows:

\begin{itemize}
    \item Attacker writes his guess to his file
    \item System crashed after writing the data block and new header to the disk but before a sync.
    \item New header makes to the disk but new data block doesn't.
    \item If the the what is already on the log before new data block is written is same with the new data block, then the hash of the new header will match with what is on the log.
    \item Attacker can observe this outcome by looking into the file contents.
\end{itemize}

{\color{red} DEMONSTRATING IMAGE HERE}

Encrypting each transaction with a new key makes finding such a collision exponentially unlikely. Even in the case of accidental collision, attacker cannot learn the contents of the block because even the cipher-texts are the same, because different keys are used for encryption, plain texts would be different with high probability.

\subsubsection*{Log Cache}
Since the blocks in the log are encrypted as well as exact location of newest block of an address is not known quickly, reading an address where its current value is in the log can incur a significant overhead. To mitigate this overhead, We implemented a log cache that stores (address, block) pairs of the log contents. Log cache has two operations: read and write. They both take input addresses relative to the start of the data region and convert them to the absolute disk addresses before executing required operations. This indirection allowed us to hide the log from upper components via abstraction.

Whenever there is an incoming read, system first reads the cache and it only issues a read to disk if the address is not found in the cache. Similarly, when a write is issued, system also writes the block to the cache after it writes the block to the log. This way, contents of the cache stays consistent with the contents of the log. Cache is flushed whenever the current log is applied.

Recovery restores the valid cache state by decrypting each valid transaction in the log and writing its contents to the cache.

\subsubsection{Logged Disk Abstraction}
Log component is abstracted into Logged Disk layer that has four operations: read, write, recover and init. all of the operations correspond to the operations provided by the log cache and they have the same semantics. Recover is used during the recovery to recover log to a valid state. Init is used to initialize the log during creation of the file system image.

Abstraction transforms the underlying state to hide crypto components as well as asynchronous nature of the disk. Just like the asynchronous disk, it uses a total function over a type with a decidable equality (addr -> value) to represent latest values of the underlying disk. It shifts addresses so that first data block of the disk becomes first block of this abstract disk, therefore hiding existence of the log on the disk. It is also parameterized by the log length and the disk size to enforce such limits.

This is also the first layer that takes advantage of tokens to define a non-trivial crash semantics. It uses two tokens, CrashBefore and CrashAfter, to distinguish between crashing at a state where latest values correspond to a successful write or not.

Layer connects to the underlying implementation by a refinement relation $R$ with three parts: token refinement ($R_t$) and state refinement ($R_s$) and reboot state refinement ($R_{rs}$). Due to complicated crash semantics of the log, token refinement relation of this abstraction is by far the most complicated of all.

\subsection{Transaction and Transactional Disk}
Transaction component is built on top of the composition of List and LoggedDisk layers.
It uses List state to store current transaction and uses LoggedDisk operations to interact with the disk.

Transaction API has 4 functions: read, write, commit, and abort.

Read first bound-check the given address. If it is out of bounds, it returns all 0 block. If it is in bounds, implementation first checks the transaction for the address and returns he block if it is found. Otherwise, it reads it from the disk and returns that.

Write, again, checks if the address is in bounds. If it is not, it returns None; indicating that write failed. If it is in bounds, it checks if there is enough space in transaction. If there isn't, again. it returns None. If there is room, then it adds provided address and data pair to the transaction and returns (Some tt) signaling a successful write.

Commit, first gets the transaction list. Then it de-duplicates it based on the address, i.e. it keeps the latest block for each address and discards the rest. It writes de-duplicated transaction to the disk and empties the transaction.

Abort just empties the transaction.

\subsubsection{Transactional Disk Abstraction}
{\color{red} XXXXXXX}

\subsection{Block Allocator}
ConFs contains a generic block allocator implementation that is used for both inode blocks and data blocks for the files. It uses TransactionalDisk layer as its base language. Implementation is parameterized by the starting address and the number of blocks contained. It assumes a layout that is a single bitmap block followed by num-of-blocks allocatable blocks.

It provides 4 functions: read, write, alloc, and free. All functions operate based on the index of the managed block, therefore making them independent from where these blocks stored on the disk.

Read takes an index as an input. It first checks if the given index is allocated. If the index is allocated, then it returns the block corresponding to that index. Otherwise returns None to indicate an error.

Write takes an index and a block as an input. It first checks if the given index is allocated. If the index is allocated, then it writes block to that location and returns Some tt to indicate success. Otherwise returns None to indicate an error.

Free takes an index as an input. It first checks if the given index is allocated. If the index is allocated, then it modifies the bitmap to mark it free and returns Some tt to indicate success. Otherwise returns None to indicate an error.

Alloc takes a block as an input. It first checks if there are any available blocks. If there are, then it writes the input block to the first available empty block, modifies the bitmap to indicate that new block is allocated then returns its index. Otherwise returns None to indicate an error. Alloc takes an input block to prevent leaking previous contents of the empty block.

\subsection{Inodes}
ConFs implements simple inode structure to keep track of the metadata of the files. It stores one inode per block for simplicity. Inodes contain the owner of the file and a list of block numbers, which are indexes to block allocator for data blocks. For simplicity, single block contains a single inode.

Inode implementation provides 7 functions: alloc, free, extend, change\_owner, get\_block\_number, get\_all\_block\_numbers, and get\_owner.

Alloc takes a user as an input, then allocates an inode where owner is the provided user. It returns the allocated inode's number, i. e. the index of the allocated inode block.

Free takes an inode number and frees it by marking it free on the bitmap.

Extend takes an inode number and a block number and appends the input block number to the list of the inode with the provided number.

Change\_owner takes an inode number and a user and sets owner of the inode that corresponds to the input number with the input user.

Get\_block\_number takes an inode number and an index to the block number list and returns the block number at input index.

Get\_all\_block\_numbers  takes an inode number and returns the block number list of the inode with the given number.

Get\_owner  takes an inode number and returns the owner of the inode with the given number.

\subsection{Files and File Disk}
\subsubsection{Files}
File component implements file system API. It implements access control and transactionality. Access control and transactionality is handled by a higher order function auth\_then\_exec. It authenticates the user then calls the requested function if user is permitted to do so. If called function successfully completes, then auth\_then\_exec commits the transaction and returns success. Otherwise, it aborts the transaction and returns failure.

Files are represented by their inode numbers. ConFs does not provide filename functionality or directory structures.

File components provides following functions: read, write, extend, create, delete, change\_owner.

Read takes an inode number and a block offset and returns the file contents of the block at the given offset.

Write takes an inode number, a block offset, and a block and overwrites the file contents of the block at the given offset with the input block.

Extend takes an inode number and a block and appends the input block to the end of the file with given number. To do so, it allocates a new data block then adds newly allocated block's number to the inode.

Create takes a user and creates an empty file where its owner is the given user. It returns the inode number of the file.

Delete takes an inode number and removes the file with the given number. It frees all the blocks of the file, then frees the inode of the file.

Change\_owner takes an inode number and a user and changes the owner of the file with the given number if the current owner of the file is the current user.

\subsubsection{File Disk}
{\color{red} XXXXXXXX}


\section{Extensions to Amulet}

This catalogues various extensions which could be added to Amulet on a later date.

\subsection{Active patterns}
One of the nice things about F$^\sharp$ is the ability to define custom patterns (such as \url{http://stackoverflow.com/a/2429874}).

Haskell has a similar feature ( \url{https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html\#view-patterns}) known as View patterns.

\subsection{Disposable types}
F$^\sharp$ adds the \texttt{use} binding. This will automatically call the destructor on the object when it falls out of scope. This would be really nice for things like file handles or sockets, though tricky as it has side effects. It could potentially be emulated by having a \texttt{withFile} method which acquires a file handle, applies a function over it, and destroys the handle.

\subsection{Dependent types}
Merge the type and term level to allow applying functions over types and using functions within types.
\todo[inline]{That's not dependent typing (though it often goes along with it). You just need types that depend on values. like $(x : \tau_1) \to \tau_2$ and $(x : \tau_1 $**$\,\tau_2)$ which are universal quantification and existential quantification respectively. I think technically just merging the type and term namespaces would actually give us dependent types. -cpup}


% !TEX root=/home/tavant/these/manuscript/src/manuscript.tex

\section{Insights from the PIC simulations}
  \label{sec-insights}

  As mentioned in \cref{sec-sheath_validation}, the sheath model of \cref{sec-sheath} uses two hypotheses\string:
  \begin{itemize}
    \item Maxwellian electrons,
    \item Isothermal electrons.
  \end{itemize}

  When collisions can be neglected, as it is usually assumed in the sheath, these two hypotheses are linked.
  Indeed, the \ac{1D} Maxwellian distribution function expressed as a function of the total energy is
  \begin{equation} \label{eq-maxw_total}
    f(\ek, \phi) \propto \exp \lp \frac{\ek - \phi}{\Te}  \rp  \propto \exp \lp \frac{\ek}{\Te} \rp \exp \lp \frac{-\phi}{\Te} \rp,
  \end{equation}
  where $\ek$ and $\Te$ are the electron kinetic energy and temperature expressed in Volt.
  We can see in \cref{eq-maxw_total} that the spatial variation (due to the plasma potential $\phi$) only affects the amplitude of the distribution function, not its distribution in the energy space.
  Hence, the electron temperature is uniform, i.e. the electrons are isothermal.
  In addition, we find that $n_e \propto \exp (- \phi / \Te)$, which is the definition of Boltzmann electrons.

  First we propose to check  if these two hypotheses are valid  in the \ac{2D} \ac{PIC}-\ac{MCC} simulation results

  \subsection{Electron distribution function}
    \label{subsec-eedf_2D}

    Using the kinetic information of the PIC simulations, we present in \Cref{fig-EEDF} the mean electron energy probability functions (EEPF) in the case $\crover = 200\,\volt$, for which the electron emission is of the order of $\rate=0.6$.
    \Cref{fig-EEDF}.{\bf a} shows the projections of the EEPF in the center of the simulations along the three directions.
    These projections are compared to the Maxwellian probability function of the same
    kinetic temperature.
    \Cref{fig-EEDF}.{\bf b} shows the total EEPF for both the bulk and the sheath populations.
    The sheath length is defined as the location where the ions reach the Bohm speed, which is located about 0.4mm from the wall.

     \begin{figure}[hbt]
       \centering
       \includegraphics[width=\textwidth]{EEDF_2.pdf}
       \caption{Normalized electron energy distribution function of the electrons ({\bf a}) in the bulk, in the three directions, and ({\bf b}) in the bulk and in the sheath. In ({\bf a})the red dotted line is  a Maxwellian distribution of $\Te=50\,\volt$. }
       \label{fig-EEDF}
     \end{figure}

    We see in \cref{fig-EEDF}.{\bf a} that the electron energy distribution function in the bulk is not Maxwellian.
    In particular the high energy tails are depleted.
    In order to evaluate the effect of the non Maxwellian EEPF on the \ac{SEE} rate $\rate$, we numerically integrate the EEPF from the PIC data using \cref{eq-seeyield}.
    The results (not shown) do not differ significantly from the values of $\ratemaxw$ obtained assuming a Maxwellian distribution, using \cref{eq-seemaxw}.
    Hence, we can conclude that even if the Maxwellian hypothesis is not verified in the PIC simulations, it does not explain  the differences observed on $\rate$ in \cref{fig-seeparamesMaxw}.

    \Cref{fig-EEDF}.{\bf b} presents the EEPF for the bulk population as well as for the sheath population.
    We can see that the sheath population is colder than the population at the center.
    This observation was not expected, and could explain the difference of \cref{fig-seeparamesMaxw}.
    This effect is assessed in the next section.

     Surprisingly, we do not observe in \cref{fig-EEDF} secondary electron beams in the radial  direction, unlike previous observations of \citet{sydorenko2006} with a 1D model or \citet{heron2013} with a 2D model.
     On the other hand, we do observe SEE beams when  we artificially remove the electron cyclotron drift instability by forcing $E_y = 0$\,V/m \citep{croes2017}.
     Hence, it seems that the ECDI, when simulated in 2D, quickly thermalizes the secondary electrons emitted from the walls.
     In addition, we can see in \cref{fig-EEDF}.{\bf a} that the radial EEPF is close to the EEPF in the other directions, i.e the electron are almost isotropic.
     For instance, for $\crover = 200\,\volt$  we measure $\Te_r = 41.5\,\volt$ while $\Te_{\theta} \sim \Te_z = 49\,\volt$.
     The cause of the difference with \citet{heron2013} is not clear yet, but their results were  obtained at early times when saturation of the instability has not necessarily been reached, and no electron loss in  the axial direction was accounted for.
     This is supported by \cref{fig-canon_Te_strat,fig-canon_Te_all} which show us that there is a larger anisotropy at the beginning of the simulation ($t<2\micro\second$) than later.
     It is possible that when the instability is fully saturated, during the quasi steady-state, the electrons had sufficient time to isotropize.
     The energy transfer from the axial and azimuthal directions to the radial direction is not clearly understood
     yet \citep{janhunen2018}, but we believe that it is due to the instability.

   \subsection{Radial evolution of the electron temperature}
     \label{subsec-Radial_Te}

     \Cref{fig-te_profile_see} shows the radial profile of the electron temperature $\Te$ averaged in time over $5\,\micro\second$ and over the azimuthal direction, for different emissivities.
     We can see that for all of the values of $\crover$ and even without electron emission, there is a steep gradient of the electron temperature in the sheath.
     Actually, the profile of $\Te$ looks very similar to the profile of the plasma potential $\phi$.

   \begin{figure}[!hbt]
     \centering
     \includegraphics[width=\defaultwidth]{Te_profiles}
     \caption{Radial profiles of the electron temperature measured in the \acs{PIC} simulations, without secondary electron emission (label "no SEE") and with different values of $\crover$.}
     \label{fig-te_profile_see}
   \end{figure}

   The significant difference between the value of the mean electron temperature in the whole simulation domain, used before in \cref{sec-sheath_validation}, and the electron temperature close to the wall can be responsible for the overestimation of $\rate$ compared to $\ratepic$ on \cref{fig-seeparamesMaxw}.
   Using this information, we compute an estimation of the electron emission rate $\rate$ with \cref{eq-seemaxw} using the electron temperature averaged over the last five cells of the PIC simulations.
   The results are presented in \Cref{fig-rate_pic_wall}.

   \begin{figure}[!hbt]
     \centering
     \includegraphics[width=\defaultwidth]{SEE_rates_withEEDF-eps-converted-to}
     \caption{Estimation of the electron emission rate $\rate$ as a function of $\crover$ using the values of the electron temperature close to the wall.}
     \label{fig-rate_pic_wall}
   \end{figure}

   We observe in \cref{fig-rate_pic_wall} that now, the electron emission rate is well predicted (error less than 5\%), except for $\crover=10\,\volt$ where a large error is still observed.
   As previously discussed, the case $\crover=10\,\volt$ presents a very high SEE rate which leads to a potential well close to the wall, the so-called \ac{SCL} regime.
   Consequently, some secondary electrons emitted at low energy would be reflected back to the wall.
   Hence, since \cref{eq-seemaxw} does not take into account this local effect, it is not surprising that the SEE rate calculated using the mean electron temperature in the sheath is too high.

   To summarize, \cref{fig-rate_pic_wall} shows that when the sheath  is not in the \ac{SCL} regime, the \ac{SEE} rate can be well predicted by \cref{eq-seemaxw} using the electron temperature close to the wall, which is lower than in the center of the domain.
   The particle and energy flux inducing the \ac{SEE} rate are not well described if we use the electron temperature of the bulk as in the isothermal sheath model.
   This explains the overestimation of both $\rate$ and and $\dphi$ presented in \cref{fig-seeparamesMaxw,fig-Tevsproba}.
   Hence, the isothermal hypothesis used in the sheath model of \Cref{sec-sheath} is denied by the PIC simulations.

   In the next sections, we use a simplified \ac{PIC} simulation to study in detail the origin of the electron temperature gradient in the sheath.


\chapter{Conclusions}

\section*{General considerations}
\addcontentsline{toc}{section}{General considerations}

\noindent
To sum up the results of our study project we must start from the motivations which has driven it along the path and follow the logical steps:

\begin{itemize}
	\item the project grows from the fact that helicopter crew and passenger comfort has recently gained increased emphasis and so vibration requirements have become more and more stringent.

	\item Consequently, treat the helicopters vibration problem only after the manufacturing phase adding suppression devices (absorbers) to overcome the inadequate vibration prediction capability has no more sense and it is not cost-efficient; \\
	\underline{The new challenge is to design helicopters with intrinsically low vibration level}.

	\item To reach this goal, a \textbf{precise FEM model of the helicopter have to be implemented} so it can provide a broad insight of its characteristics dynamical behaviour since the beginning.
	The need to precise modelling of the basic frame or the basic structure including the material properties and the cross sections is that it contributes to \underline{helicopter stiffness characteristics} which must be precisely modelled to investigate in vibration problems.

	\item Structural parts of the fuselage can be easily and accurately modelled with the Ansys most common structural elements; in fact, dynamic analysis yield satisfactorily results with simplified models. \\
	In fact, it is not advisable to build solid models or surfaces with many elements to represent the basic frame's parts of the airframe. \\
	\underline{Comparison with literature results showed that simple} \textbf{truss, beam, shells elements} \underline{models accurately predict the real system's behaviour}. In our case, in both models, longerons, cross members, stringers, stiffeners, bulkheads and outer skin have all been modelled with those simple type of elements.

	\item Then, \textbf{it is essential to add the secondary structural components} that have a critical role in the vibration characteristics of the model.

	So, in the case of considering the whole model of the helicopter, the fuselage skin, the cabin floor, the windscreen glass and doors with their assigned properties must be considered and added to the model.

    Furthermore, \textbf{also the non-structural components} have to be considered (for example tailrotor head, gearbox, aerodynamical stabilizers and, eventually, for the full model, also engines, fuel tank, landing skid, swash plate) and added to certain points on the model as lumped masses. \\
    In fact, as it can be appreciated in the results table, adding those components to the basic structure has a dramatical effect on the results values; structure's resonant frequencies results to be considerably lowered down.

    \item
    Unfortunately, \underline{the complete helicopter vibration problem is really difficult	to predict} \underline{accurately}, as yet, because of its structural, as well as aerodynamic, complexity. \\
    To let the problem to be more tractable, \emph{simplifying assumptions} must be imposed at the beginning. In our case, \textbf{we neglected aerodynamic loads} which typically introduce non-linearities on the problem. However, in the future studies, to extend our analysis, those loads must be considered.

    \item
    Nowadays, rotordynamics tools are not enough advanced to treat problems with asymmetric structures, because them are recently introduced in ANSYS and above all for a computational cost issue. As we seen before, the coupling rotor - fuselage analysis suffers troubles of geometrical asymmetry. So as to partially overcome this issue, one possibility is to simplify the rotor as a concentrated mass and inertia with torsional springs in order to simulate the gyroscopic effects. \\
    Results obtained from the analysis of the sole rotor (without coupling) are not reliable to give an overview of the tailboom dynamic behaviour. In this project, considerations about the rotor were made just as a matter of investigation.\\
    The dynamic studies relative to tailboom - rotor coupling, therefore, should have a future development using, for example, a software capable to treat multibody dynamic simulations.

\end{itemize}

\section*{Review of the main results}
\addcontentsline{toc}{section}{Review of the main results}

\noindent
Once defined each model, a free vibration analysis has been carried out to extract the natural frequencies of the basic frames up to its 20 modes, which is located around 61.6 Hz for the LAMA SA-315b helicopters model and 94.2 Hz for the Ecureuil AS-350.\\
\noindent The results on the natural frequencies of the full structures reasonably match with the literature (especially for lower modes) giving confidence in our simple models. However, in order to let our models to become a comprehensive design tool for analysing the real behaviour of the two helicopter's considered, it \textbf{is essential to add the non-linear contribution of aerodynamic loads and the rotor-fuselage dynamic coupling effects}.

%\clearpage
%
\begin{table}[h]
 \centering
 \pgfplotstableset{
 	column type=l,
 	every head row/.style={
 	before row={
 		\toprule
   		& \multicolumn{2}{c}{TRUSS} & \multicolumn{2}{c}{MONOCOQUE}\\
   	 	&  \multicolumn{1}{c}{simple} & \multicolumn{1}{c}{complete} & \multicolumn{1}{c}{simple} &\multicolumn{1}{c}{complete}\\
   	 	}, after row=\midrule,
   	 },
   	every last row/.style={after row=\bottomrule},
 % global config, for example in the preamble
 % these columns/<colname>/.style={<options>} things define a style
 % which applies to <colname> only.
 %every head row/.style={before row=\hline, after row=\hline},
 %every last row/.style={after row=\hline},
 display columns/0/.style={column name =Mode, int detect,column type=r},
 display columns/1/.style={column name =Frequence [Hz], column type=r, fixed,fixed zerofill,precision=5,set thousands separator={\,}},
 display columns/2/.style={column name =Frequence [Hz], column type=r,fixed,fixed zerofill,precision=5,set thousands separator={\,}},
 display columns/3/.style={column name =Frequence [Hz], column type=r,fixed,fixed zerofill,precision=5,set thousands separator={\,}},
 display columns/4/.style={column name =Frequence [Hz], column type=r,fixed,fixed zerofill,precision=5,set thousands separator={\,}},
		%other style option
	}
 %TRUSS MODEL - RESULT
 \pgfplotstableread{ModalFreq-Helicopter_tail.txt}{\dataA}
 \pgfplotstableread{ModalFreq-TrussTailLumped.txt}{\dataB}
 %SHELL MODEL - RESULT
 \pgfplotstableread{ModalFreq-Shellmodel.txt}{\dataC}
 \pgfplotstableread{ModalFreq-ShellmodelShaftLumped.txt}{\dataD}
 % concatenate table
 \pgfplotstablecreatecol[copy column from table={\dataB}{[index] 1}] {par2} {\dataA}
 \pgfplotstablecreatecol[copy column from table={\dataC}{[index] 1}] {par3} {\dataA}
 \pgfplotstablecreatecol[copy column from table={\dataD}{[index] 1}] {par4} {\dataA}
 %generate full table
 \pgfplotstabletypeset{\dataA}
 \caption{Result all natural frequencies}
 \label{tab:ResultRecap}
\end{table}
%

\smallskip
\noindent
FURTHER IMPORTANT NOTES:
\noindent
\begin{itemize}
	\item Since the exciting frequency of the tail rotor head is almost 33,35 Hz (2001 rpm), the first harmonic of the main rotor head (regarding the three bladed tail rotor) will be 66.70 Hz. So, \underline{the higher modes (from the number 10 on) will be critical modes} and have to be considered carefully in design stage in order to prevent
	resonance with the tail rotor excitation forces.

	\item \noindent
	The tail rotor speed has obviously influence on the tailboom natural frequencies; In fact they are expected to increase with the rotational velocity.\\
\end{itemize}

\medskip
\section*{Giving confidence to the FEM model by testing}
\addcontentsline{toc}{section}{Giving confidence to the FEM model by testing}
\noindent
As previously noted, FE modelling technique found wide application in helicopters vibrations problems investigation and results to be a very useful and powerful tool. However, in order to become applicable for real purposes, FE model should always be validated via experimental modal analysis results. \\
\noindent
Also literature's research led to the conclusion that helicopters vibrations problems might be effectively solved with use of the analytical and FEM models if their accuracy is improved by updating to the experimental results. \\

\noindent
Hence, the models can be experimentally verified by \textbf{ground} or \textbf{in-flight tests}.\\
\noindent
With ground tests, the effects of the rotating systems (e.g. rotors, engines, \dots) and the aerodynamic environment on the fuselage dynamic behaviour \underline{cannot be investigated}. This is the reason why \textbf{it is preferable to perform in-flight test} for helicopter structural dynamic investigation despite their higher costs and greater technical experiment complexity.
The ground modal test results to be only an approximation of the structural dynamics model description
for the in-flight conditions and in-flight modal testing is always considered superior.
%