\documentclass{article}
\usepackage[utf8]{inputenc}

\title{MAT257 Notes}
\author{Jad Elkhaleq Ghalayini}
\date{September 7 2018}

\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{amsthm}
\usepackage{mathtools}
\usepackage{enumitem}
\usepackage{graphicx}
\usepackage{cancel}

\usepackage[margin=1in]{geometry}

\newtheorem{theorem}{Theorem}
\newtheorem{lemma}{Lemma}

\newcommand{\reals}[0]{\mathbb{R}}
\newcommand{\nats}[0]{\mathbb{N}}
\newcommand{\ints}[0]{\mathbb{Z}}
\newcommand{\rationals}[0]{\mathbb{Q}}
\newcommand{\brac}[1]{\left(#1\right)}
\newcommand{\sbrac}[1]{\left[#1\right]}
\newcommand{\eval}[3]{\left.#3\right|_{#1}^{#2}}
\newcommand{\ip}[2]{\left\langle#1,#2\right\rangle}

\begin{document}

\maketitle

Today, I want to make some introductory remarks for motivation, and I want to show from the beginning why linear algebra will be important to us.
\section*{Differentiability}
Let's recall for a moment what it means for a function to be differentiable at a point:
\[\exists f'(a) = \lim_{h \to 0}\frac{f(a + h) - f(a)}{h}\]
Of course, we can bring everything to the right and write
\[\lim_{h \to 0}\frac{f(a + h) - (f(a) + f'(a)h)}{h} = 0\]
The advantage of stating it this way is that we see that the linear function
\[f(a) + f'(a)h\]
is the \textit{best linear approximation} to \(f(a + h)\) at \(h = 0\). In fact, it's the unique linear function \(y = b + mh\) such that
\[\lim_{h \to 0}\frac{f(a + h) - (b + mh)}{h} = 0\]
Should this be called linear? I don't know. Maybe it would be better to call it affine.

From the point of view of linear algebra, we would say that a function which takes
\[h \mapsto f'(a) \times h\]
is a linear transformation. So the derivative can be thought of as a number, but it can also be thought of as a linear transformation from the real line to itself. And this is how we're going to define, and work with, derivatives in higher dimensions.

\section*{Functions of several variables}

We're not going to be working on the real line, instead, we'll be working on \(\reals^n\): the space of \(n\)-tuples of real numbers. Instead of functions \(f(x)\) of a single real variable \(x\), we will hence be working with functions of \(n\) real variables, or if you like, functions of a single vector variable, where \(x \in \reals^n\), of the form
\[f(x) = f(x_1,...,x_n)\]
Such a function is differentiable at a point \(a = (a_1,...,a_n)\) if ``there's a thing that plays the role of the derivative.'' We could think about a deriative in \(\reals\) as a real number, but we could also think about it as a linear transformation, which is what we're going to do. That is, a derivative exists, if there exists a linear transformation
\[\lambda: \reals^n \to \reals\]
such that
\[\lim_{h \to 0}\frac{f(a + h) - (f(a) + \lambda(h))}{|h|} = 0\]
What's a linear transformation from \(\reals^n \to \reals\). Well first of all, what's \(h\)? \(h = (h_1,...,h_n)\) is a vector. So \(\lambda\) can be thought of as a sort of row matrix such that
\[\lambda(h) = \begin{pmatrix}\lambda_1 & ... & \lambda_n\end{pmatrix}\begin{pmatrix} h_1 \\ \vdots \\ h_n\end{pmatrix}\]
Sometimes, we'll write \(\lambda(h)\) simply as \(\lambda h\). This right away is why linear algebra is important. As you can imagine, if we want to analyze the effect of a given derivative on this function, we're going to need to analyze this matrix, so linear algebra is going to be really crucial. In fact, a lot of the things that we do in the course can be done and were done classically with a really minimal amount of linear algebra. In fact this \(\lambda\) is a matrix, but it's entries are what we call the partial derivatives of \(f\), so we can work only with a collection of partial derivatives. However, what we'll see is, from a conceptual perspective, there's a lot to be gained from the linear agebraic approach.

Analysis involves making approximations and estimations, like \(\epsilon-\delta\) proofs in calculus. Of course, \(\epsilon-\delta\) proofs involve measuring the size of a quantity or distance, and those are going to be really essential concepts in this course. That already shows up in the \(|h|\) in the equation above, which is defined
\[|h| = \sqrt{h_1^2 + ... + h_n^2}\]
the \underline{norm} of \(h\). It's a measure of the size of \(h\). If we write the norm
\[|x - y|\]
this is a measure of the size of the difference between \(x\) and \(y\), or the \underline{distance} between \(x\) and \(y\). But especially in high dimension, even in one dimension but especially in high dimensions, there may be many different ways of measuring distance which are essentially equivalent.

\section*{Equivalent Norms}
This is one norm, but in fact there are many different but equivalent norms. For example, some norms include
\[|x| = \left(\sum_{i = 1}^nx_i^2\right)^{1/2}\]
\[||x|| = \max\{|x_1|,...,|x_n|\}\]
\[|||x||| = \sum_{i = 1}^n|x_i|\]
These are all equivalent, which means that if you pick any two of them, the first one is less than or equal to a constant times the second one. Why is that? What's the relationship between them?

It's a very good idea, in, anything, I guess, to understand things geometrically. And this actually can be seen just on the level of a picture of \(\reals^2\). After all, what if we take our first norm. What does it mean to say that the norm is less than or equal to \(r\)? It means that our point is inside a circle of radius \(r\). On the other hand, what does it mean for the \textit{second} norm to be less than or equal to \(r\)? It means that both norms have to be inside the square of side length \(r\) centered at the origin. And finally, what does it mean for the third norm to be less than or equal to \(r\)? That means we're inside the smaller square, or diamond, formed by the points
\[(0, r), (0, -r), (r, 0), (-r, 0)\]
Of course, there would be \(n\)-dimensional versions of this picture. But what does this picture say about the relationship between these norms? It tells us that
\[||x|| \leq |x| \leq |||x|||\]
How do we prove this analytically? We just take the square of everything!

Now how do we show that
\[|||x||| \leq a|x|\]
for some constant \(a\)? We can also think about this geometrically: take our circle of radius \(r\). We need the first diamond which is outside of the circle. And what distance is the corner of the diamond from the origin? In the plane, it's \(\sqrt{2}r\). In higher dimensions, it's \(\sqrt{n}r\). So what this tells us is that
\[|||x||| \leq \sqrt{n}|x|\]
or, analytically,
\[|||x||| = \ip{x}{u(x)} \leq |x||u(x)|\]
where
\[u_i(x) = \text{sgn}(x_i) = \left\{\begin{array}{ccc} 1 & \text{if} & x_i \geq 0 \\ -1 & \text{if} & x_i < 0 \end{array}\right.\]
Now, how do we show that
\[|x| \leq a||x||\]
Well, let's again look at our square of side \(r\). Clearly, the circle circumscribing this square has radius \(\sqrt{n}r\), in \(n\) dimensions. We should finish this by doing the exercise of proving this analytically
\end{document}


\section{Gamma interaction model algorithm.}

\hspace{1.0em}
At intermediate energies $\gamma$-nucleon and $\gamma$-nucleus interactions are
performed within the hadron kinetic model similarly as the hadron-nucleon and
hadron-nucleus interactions.

At high energies the Monte Carlo procedure
 in the case of $\gamma$--nucleon collision can be
outlined as following:
\begin{itemize}
\item At given c.m. energy squared and at given virtuality $Q^2$ sample
mass $M^2$ of
hadronic $q\bar{q}$ fluctuation according to ($\ref{HEGI2}$)
and sample its flavor
according to statistical weights: $\omega_{u\bar{u}}= 1/2$,
$\omega_{d\bar{d}}= 1/4$ and $\omega_{s\bar{s}}= 1/4$ are derived from
($\ref{HEGI3}$);
\item Sample the momentum fraction $x$ of a valence quark inside
 a hadronic fluctuation
according to
\begin{equation}
\label{GIMA1} \rho(x) \sim \frac{1}{\sqrt{x(1-x)}}
\end{equation}
and transverse momentum of a quark according to the Gaussian
distribution as for hadrons;
\item Split nucleon into quark and diquark as it was described
 for hadron-nucleon
interaction;
\item Create two strings spanned between quark from a hadronic fluctuation and
diquark from nucleon and between antiquark from a hadronic
 fluctuation and quark from nucleon;
\item Decay string into hadrons as it was described for
 hadron-nucleon interactions.
\end{itemize}

In the case of $\gamma$--nucleus collision the MC procedure is following:
\begin{itemize}
\item At given c.m. energy squared and at given virtuality
 $Q^2$ sample mass $M^2$ of
hadronic $q\bar{q}$ fluctuation and sample its flavor as it is done for
$\gamma$--nucleon collision;

\item Calculate coherence length $d$;

\item If coherence length less than internucleon distance
then simulate inelastic
hadron fluctuation-nucleon collission at choosen impact
parameter $B$ as was described
above;

\item If coherence length more than internucleon distance then
 perform simulation of hadron fluctuation-nucleus collision at choosen
impact parameter $B$ using parton string model similarly as for meson-nucleus
interactions. For this case the probability of inelastic collision of
a  hadron fluctuation with nucleon
$i$  at given impact parameter ${\bf b}_i$ is calculated according to
\begin{equation}
\label{GIMA3} p_{VN}(s,b^2) = 1 - exp{[-2u(s, b^2)]};
\end{equation}
with  the eikonal $u(s,b^2)$ defined by Eq. ($\ref{HEGI7}$) at
$Q^2 = 0$ and $M^2=M_{\rho}$.
\end{itemize}


\chapter{Results and Evaluation}
In this chapter we are going to show the best results obtained by setting up the training phase as described in the previous chapters. Most of the parameter tuning was done on just one dataset\footnote{The Reuters Corpus, RCV1}, and then the same setup was used to produce results for all our datasets.

\section{Confusion matrix}
A confusion matrix is a table that is often used to describe the performance of a classification model (or \enquote{classifier}) on a set of test data for which the true values are known.
To help the reader better understand what this is all about, we can give a practical example with authorship attribution. Suppose we have an unknown document and we have a verification problem where we have to indicate whether Shakespeare is the author of the unknown document or not.
The confusion matrix takes the form it has in \autoref{fig:confusion_matrix} and 4 types of values show up:

\begin{itemize}
	\item \textbf{true positives (TP)}: These are cases in which we predicted yes (Shakespeare is the author of the unknown document), and he really was the author of that document.
	\item \textbf{true negatives (TN)}: We predicted no, and he didn't write that document.
	\item \textbf{false positives (FP)}: We predicted yes, but he didn't actually write that document. (Also known as a "Type I error.")
	\item \textbf{false negatives (FN)}: We predicted no, but in reality he did write that document. (Also known as a "Type II error.")
\end{itemize}

These aforementioned definitions will come in very handy to better understand all the metrics used to evaluate the model we built.

\begin{figure}[ht]
	\centering
	\includegraphics[width=.8\textwidth, height=0.8\textheight, keepaspectratio]{confusion_matrix}
	\caption[Confusion matrix example]{A confusion matrix example with 4 classes of values: true positive, true negative, false positive and false negative.}
	\label{fig:confusion_matrix}
\end{figure}

\section{Metrics used}
In order to evaluate the performance of the model being built, we computed for each training phase, 2 different scores on the testing set: the \textit{accuracy score} and the \textit{F1 score}\footnote{\url{http://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html}}.\\
The accuracy score, one of the more obvious metrics, is the measure of all the correctly identified authors of each documents. It's mostly used when all the classes are equally important.
\begin{equation}
Accuracy = \frac{True Positive + True Negative}{(True Positive + False Positive + True Negative + False Negative)}
\end{equation}
The F1 score can be interpreted as a weighted average of the precision\footnote{The measure of the correctly identified positive cases from all the predicted positive cases.} and recall\footnote{The measure of the correctly identified positive cases from all the actual positive cases.}, where an F1 score reaches its best value at 1 and worst score at 0. The relative contribution of precision and recall to the F1 score are equal.\\The formula for the F1 score is:\\
\begin{equation}
F1 = \frac{2 * (precision * recall)}{(precision + recall)}
\end{equation}
where:
\begin{itemize}
	\item \textbf{Precision:} is the fraction of relevant instances among the retrieved instances.
	\item \textbf{Recall:} is the fraction of relevant instances that have been retrieved over the total amount of relevant instances.
\end{itemize}

To summarise the differences between the F1 and the accuracy:
\begin{itemize}
	\item Accuracy is used when the True Positives and True negatives are more important while F1 is used when the False Negatives and False Positives are crucial.
	\item Accuracy can be used when the class distribution is similar while F1 is a better metric when there are imbalanced classes.
	\item In most real-life classification problems, imbalanced class distribution exists and thus F1 is a better metric to evaluate our model on.
\end{itemize}

\section{Results obtained over different datasets}

In this section we will present and discuss the best results obtained for the different datasets selected, with particular attention to the type of feature representation, the number of authors, the choice of division between training and testing sets, and whether or not the authors' documents belong to different categories.

\subsection{Reuters Corpus results}

The first results we show refer to the Reuters Corpus as it was the dataset on which we did cross validation and hyperparameters tuning. In fact both the choices of features representation, the parameters and the tokenizer, the classifier parameters were all chosen according to the performance of this corpus, especially in the portion that we called RCV1-50, that is the selection of 100 documents per author, for the 50 most prolific authors of the Reuters corpus, for the CCAT category.\\
Precisely for this reason in \autoref{tab:tableRCV1_50} are shown the 3 best results on this portion of the dataset in terms of both accuracy score and F1. As can be seen from the table, the best results were obtained with the linear SVM classifier, with tfidf as the method of feature representation, and gradually increasing results were obtained thanks to the study of a better selection of words on the tokenizer.
In fact we denote \textit{\enquote{stock\_tokenizer}} the standard tokenizer of the python library
\textit{sklearn.feature\_extraction.text.TfidfVectorizer}. While in the other two approaches we changed the tokenizer, setting a \enquote{custom} one, at first leaving all words except the text between double quotes. The best result was obtained with a variation of this custom tokenizer, called \textit{\enquote{only-remove-quotes-tokenizer}}, removing the words between double quotes but with a length of greater than one word (i.e. the single words between double quotes were left intact) and in addition we used not only the representation of a word ngram, but we also chose to represent the pair of neighboring words to better identify the author of a text.
The reasoning behind this type of representation and the reason why we got the best result is because the use of words between double quotes could better distinguish the author of a text, while the sentences enclosed by double quotes were discarded because they certainly belong to a quote, and therefore do not distinguish the style of an author.

\begin{table}[h!]
	\begin{center}
		\caption[Reuters Corpus Results - 50 authors]{Accuracy score and F1 macro score for Reuters Corpus 50 authors CCAT category.}
		\label{tab:tableRCV1_50}
		%\resizebox{\linewidth}{!}{  %
		\begin{tabular}{| p{5 cm} | c | c |}
			\hline
			Model & Accuracy & F1\\
			\hline
			LinearSVC (combinedDFs), tfidf, stock tokenizer & 0.7644 & 0.7600 \\ \hline
			LinearSVC (combinedDFs), tfidf, only-remove-quotes-tokenizer & 0.7884 & 0.7842 \\ \hline
			\textbf{LinearSVC (combinedDFs), tfidf, only-remove-quotes-tokenizer (threshold 1),
			ngram=(1,2)} & \textbf{0.7984} & \textbf{0.7949} \\ \hline
			%\bottomrule
		\end{tabular}
		%}
	\end{center}
\end{table}

In \autoref{tab:tableRCV1_10} we can see the results of the same models on the portion of the reuters corpus dataset, of the 100 documents extracted by each author, selecting the 10 most prolific authors with the documents belonging to the CCAT category.\\

\begin{table}[h!]
	\begin{center}
		\caption[Reuters Corpus Results - 10 authors]{Accuracy score and F1 macro score for Reuters Corpus 10 authors CCAT category.}
		\label{tab:tableRCV1_10}
		%\resizebox{\linewidth}{!}{  %
		\begin{tabular}{| p{5 cm} | c | c |}
			\hline
			Model & Accuracy & F1 \\
			\hline
			LinearSVC (combinedDFs), tfidf, simple tokenizer & 0.8780 & 0.8760 \\ \hline
			LinearSVC (combinedDFs), tfidf, only-remove-quotes-tokenizer & 0.9080 & 0.9060 \\ \hline
			\textbf{LinearSVC (combinedDFs), tfidf, only-remove-quotes-tokenizer (threshold 1),
			ngram=(1,2)} & \textbf{0.9220} & \textbf{0.9210} \\ \hline
			%\bottomrule
		\end{tabular}
		%}
	\end{center}
\end{table}

The Reuters dataset being frequently used in other authorship attribution studies, also allows us to compare the results in terms of accuracy with other models that we are aware of.
In \autoref{tab:tableRCV1_10_benchmark} we can see some of the models that achieved the best results for the authorship attribution task on the Reuters Corpus both for the RCV1-10 portion and for the RCV1-50 portion.
At the end of the table we reported the best result achieved with our method, that for both of the portion of the dataset (i.e. the 10 authors and the 50 authors) showed the highest accuracy score to the best of our knowledge.
\begin{table}[h!]
	\begin{center}
		\caption[Reuters Corpus Benchmark - 10 and 50 authors]{Accuracy score for Reuters Corpus 10 and 50 authors in the CCAT category.}
		\label{tab:tableRCV1_10_benchmark}
		%\resizebox{\linewidth}{!}{  %
		\begin{tabular}{| p{5 cm} | c | c |}
			\hline
			Model & RCV1-10 & RCV1-50 \\
			\hline
			D2V words\cite{posadas2017application} & 0.8280 & 0.7524 \\ \hline
			Local histograms \cite{sari2017continuous} & 0.8640 & - \\ \hline
			Tensor space models \cite{plakias2008tensor} & 0.8080 & - \\ \hline
			Character and word n-grams \cite{sapkota2015not} & 0.7940 & - \\ \hline
			N-gram feature selection \cite{houvardas2006n} & - & 0.7404 \\ \hline
			\textbf{Our approach} & \textbf{0.9220} & \textbf{0.7984} \\ \hline
			%\bottomrule
		\end{tabular}
		%}
	\end{center}
\end{table}

For the RCV1-10 portion of the reuters corpus the results of our approach improved the best accuracy score achieved with local histograms method in \cite{sari2017continuous} by $6,71\%$ and for the RCV1-50 we improved by $6,11\%$ the results obtained in \cite{posadas2017application} with the doc2vec words model.

\subsection{GDELT Corpus results}
Regarding the dataset downloaded from the GDELT project, composed of documents belonging to Victorian era books belonging to 45 authors, the 3 best results obtained are shown in \autoref{tab:tableGDELT}.

\begin{table}[h!]
	\begin{center}
		\caption[GDELT Results - 45 authors]{Accuracy score and F1 macro score for GDELT 45 authors.}
		\label{tab:tableGDELT}
		%\resizebox{\linewidth}{!}{  %
		\begin{tabular}{| p{5 cm} | c | c |}
			\hline
			Model & Accuracy & F1 \\
			\hline
			LinearSVC (combinedDFs), tfidf, stock tokenizer & 0.7355 & 0.7090 \\ \hline
			LinearSVC (combinedDFs), tfidf, only-remove-quotes-tokenizer & 0.7426 & 0.7173 \\ \hline
			\textbf{LinearSVC (combinedDFs), d2v dmm} & \textbf{0.7716} & \textbf{0.7489} \\ \hline
			%\bottomrule
		\end{tabular}
		%}
	\end{center}
\end{table}

As can be seen from the results, in this only case for this type of dataset the best method for text representation was not tfidf, although the tfidf model along with the \enquote{custom} tokenizer of \textit{only-remove-quotes-tokenizer} still performed well.
The best method for the representation of documents in vectors, fell on the Distributed Memory Mean (dmm) model that obtained the highest accuracy score.
The reason why tfidf didn't get the best result is not clear to us, but we point out that this type of dataset differs from the others for the style of writing (Old English of the mid-nineteenth century), the length of the documents, on average they contain about 1000 characters more than the reuters dataset and about 3000 more than the amazon reviews dataset.
In addition, the authors' documents were extracted from books, whose style is very different from the style of news or reviews, where grammatical errors or abbreviations are nil and where quotations are hardly present, except in the form of dialogue of the characters in the story. Unfortunately, to the best of our knowledge we do not have similar previous studies to compare the results obtained on the same type of task and dataset. However, being a similar context (50 vs 45 authors) and similar training methodology (100 documents per author, 50 documents for the training phase and 50 for the testing phase), we can safely say that the results obtained with this type of dataset are lower than those obtained with the same methodology with the Reuters corpus and proved to be the lowest results in terms of accuracy compared to all the datasets that we previously selected for this task.

\subsection{Amazon Food Reviews Corpus results}
The dataset of amazon product review collections in the food category showed the best results in the context of author attribution for a group of 50 authors with 100 documents each, 50 in the training phase and 50 in the testing phase. The best results obtained in terms of accuracy and F1 are shown in \autoref{tab:tableAFR}.

\begin{table}[h!]
	\begin{center}
		\caption[Amazon Food Reviews Results - 50 authors]{Accuracy score and F1 macro score for Amazon Food Reviews 50 authors dataset.}
		\label{tab:tableAFR}
		%\resizebox{\linewidth}{!}{  %
		\begin{tabular}{| p{5 cm} | c | c |}
			\hline
			Model & Accuracy & F1 \\
			\hline
			LinearSVC (combinedDFs), tfidf, simple tokenizer & 0.7704 & 0.7674 \\ \hline
			LinearSVC (combinedDFs), tfidf, stock tokenizer & 0.7836 & 0.7817 \\ \hline
			\textbf{LinearSVC (combinedDFs), tfidf, only-remove-quotes-tokenizer,
				ngram=(1,2)} & \textbf{0.8388} & \textbf{0.8368} \\ \hline
			%\bottomrule
		\end{tabular}
		%}
	\end{center}
\end{table}

Why our proposed model resulted in better performance on this dataset is not 100\% clear to us, but we may give the reader some observation we made after evaluating this results. It is a given and established fact now that the length of the text in a task such as authorship attribution is crucial for the successful authorship attribution of an anonymous text. Yet the average length of this dataset is much shorter than that of the other datasets compared; the average length of a review (i.e. an author's document in this dataset) is in fact about 66\% shorter than a news document in the Reuters corpus and about 75\% shorter than a text in the GDELT corpus. The lexicon of the reviews in this corpus is more mundane, including abbreviations, punctuation, grammatical errors, and short, disconnected periods. Probably because of the characteristic of being short texts, the use of one or two common keywords across product reviews means that the author is better recognized than in other contexts.
Also for this dataset, to the best of our knowledge, there are no studies on authorship attribution that would allow us to compare the metrics of our approach in terms of performance.

\subsection{The Guardian Corpus results}
Although our study primarily focused on authorship attribution on single-category documents, we wanted to collect one of the datasets widely used in previous studies to compare how our approach performs on cross-topic datasets compared to single-topic datasets and how much better or worse it performs compared to models from previous studies specifically designed to address the problem of authorship attribution in the context of cross-topic documents.
The dataset in question is selected from The Guardian newspaper. The context is very different from previous ones for the number of authors in the entire dataset (13) and the selection of author papers (that was described in \autoref{ssec:guardian}).
We followed this approach by using the authors' papers in the Politics category as training and then performed testing on 4 portions of the testing set with the authors' papers belonging to the Books, World, Uk, and Society categories.

\begin{table}[h!]
	\begin{center}
		\caption[The Guardian Corpus Results]{Accuracy score and F1 macro score for The Guardian Corpus with LinearSVC (combinedDFs), tfidf, only-remove-quotes-tokenizer.}
		\label{tab:tableTGC}
		%\resizebox{\linewidth}{!}{  %
		\begin{tabular}{| p{5 cm} | c | c |}
			\hline
			Training topic vs Test topic & Accuracy & F1 \\
			\hline
			Politics vs Books & 0.7446 & 0.7640 \\ \hline
			Politics vs World & 0.7560 & 0.7470 \\ \hline
			Politics vs Uk & 0.7890 & 0.7010 \\ \hline
			Politics vs Society & 0.8863 & 0.7430 \\ \hline
			\textbf{Average} & \textbf{0.7940} & \textbf{0.7388} \\ \hline
			%\bottomrule
		\end{tabular}
		%}
	\end{center}
\end{table}

In the \autoref{tab:tableTGC} we can see the results obtained with the linearSVC(combinedDFs) model, with feature extraction method tfidf and with the \enquote{custom} tokenizer \textit{only-remove-quotes-tokenizer}.
In the last row we can see the calculated average accuracy score and F1 obtained.
Taking the work of \cite{posadas2017application} as a benchmark for this dataset, we can state that the results obtained with our approach in the context of cross-topic authorship attribution did not come close to the benchmark, thus demonstrating that the two types of authorship attribution tasks probably need different approaches in order to obtain performances adequate to the case study and the dataset with which they are to be compared.\\

\paragraph{}
In \autoref{fig:results_across_datasets} we can see the metrics evaluated for each dataset on the best scoring models. The metrics shown are: accuracy, precision macro, recall macro, F1 macro.
In blue we can see the result of the reuters dataset on the portion composed of 50 authors, while in yellow the best result obtained on the dataset of amazon food reviews.
\begin{figure}[ht]
	\centering
	\includegraphics[width=1.0\textwidth, height=1.0\textheight, keepaspectratio]{Results_across_datasets}
	\caption[Best performance across all datasets]{Accuracy, precision, recall and F1 for every dataset showing only the best result achieved for each one.}
	\label{fig:results_across_datasets}
\end{figure}


% When using TeXShop on the Mac, let it know the root document. The following must be one of the first 20 lines.
% !TEX root = ../design.tex

\chapter{Sampling}

\begin{moduleinfo}
\item[Author] \href{mailto:Florian.Schoppmann@emc.com}{Florian Schoppmann}
\item[History]
	\begin{modulehistory}
		\item[v0.5] Initial revision
	\end{modulehistory}
\end{moduleinfo}

\section{Sampling without Replacement} \label{sec:SampingWOReplacement}

Given a list of known size $n$ through that we can iterate with arbitrary increments, sampling $m$ elements without replacement can be implemented in time $O(m)$, i.e., proportional to the sample size and independent of the list size \cite{V84a}. Even if the list size $n$ is unknown in advance, sampling can still be implemented in time $O(m(1 + \log \frac nm))$ \cite{V85a}.

While being able to iterate through a list with arbitrary increments might seem like a very modest requirement, it is still not always an option in real-world databases (e.g., in PostgreSQL). It is therefore important to also consider more constrained algorithms.

\subsection{Probabilistic Sampling}

Probabilistic sampling selects each element in the list with probability $p$. Hence, the sample size is a random variable with Binomial distribution $B(n, p)$ and expectation $np$. The standard deviation is $\sqrt{np(1 - p)}$, i.e., approximately $\sqrt{np}$ if $p$ is small. In many applications a fixed sample size $m$ is needed, however. In this case, we could choose $p$ slightly larger than $m/n$, so that with high probability at least $m$ items are selected. Items in excess of $m$ are then discarded.

\subsubsection{Formal Description}

In the following, we discuss how to choose $p$ so that with high probability at least $m$ elements are sampled, but also not ``much'' more than $m$ (in fact, only $O(\sqrt m)$ more in expectation).

In mathematical terms: What is a lower bound on the probability $p$ so that for a random variable $X \sim B(n,p)$ we have that $\Pr[X < m] \leq \epsilon$? We use the Chernoff bound for a fairly good estimate. It says
%
\begin{align*}
	\Pr[X < (1 - \delta) \cdot \mu] \leq \exp\left( \frac{-\delta^2}{2} \cdot \mu \right)
	\SiM,
\end{align*}
where $\mu = np$ is the expectation of $X$, and $\delta \geq 0$. We set $m = (1 - \delta) \cdot \mu$, or equivalently $\delta = \frac{\mu - m}{\mu}$.
%
This yields
\begin{align}
	\Pr[X < m] \leq \exp\left( \frac{-(\mu - m)^2}{2 \mu} \right)
	\SiM. \label{eq:SamplingWOReplacent:GP:2}
\end{align}
%
We want the right-hand side of \eqref{eq:SamplingWOReplacent:GP:2} to be bounded by $\epsilon$ from above. Rearranging this gives
\begin{align*}
	\mu \geq m - \ln(\epsilon) + \sqrt{\ln^2(\epsilon) - 2 m \ln(\epsilon)}
	\SiM.
\end{align*}
Since $p = \mu / n$, this immediately translates into a lower bound for $p$. For instance, suppose we require $\epsilon = 10^{-6}$, i.e., we want the probability of our sample being too small to be less than one in a million. $\ln(10^{-6}) \approx -13.8$, so we could choose
\begin{align*}
	p \geq \frac{m + 14 + \sqrt{196 + 28m}}{n}
	\SiM.
\end{align*}

Note that the bound on $\mu$ does not depend on $n$. So in expectation, only $O(m + \sqrt m)$ items are selected. At the same time, at least $m$ items are selected with very high probability.

\subsubsection{Implementation in SQL}

In real-world DBMSs, probabilistic sampling has the advantage that it is trivially data-parallel. Discarding excessive items can be done using the well-known \texttt{ORDER BY random() LIMIT} idiom. Tests show that PostgreSQL is very efficient in doing the sorting (today's CPUs can easily sort 1 million numbers in less than a couple hundred milliseconds). In fact, the sorting cost is almost not measurable if the sample size is only at the scale of several million or less. Since \texttt{ORDER BY random() LIMIT} is an often-used idiom, there is also hope that advanced optimizers might give it special treatment. Put together, in order to sample $m$ random rows uniformly at random, we write:
\begin{sql}
	SELECT * FROM list WHERE random() < p ORDER BY random() LIMIT m
\end{sql}
If necessary, checks can be added that indeed $m$ rows have been selected.

\subsection{Generating a Random Variate According to a Discrete Probability Distribution}

In practice, probability distributions are often induced by weights (that are not necessarily normalized to add up to 1). The following algorithm is a special case of the ``unequal probability sampling plan'' proposed by \textcite{C82a}. Its idea is very similar to reservoir sampling \cite{MB83a}.

\subsubsection{Formal Description}

\begin{algorithm}[WeightedSample$(A, w)$] \label{alg:WeightedSample}
\alginput{Finite set $A$, Mapping $w$ of each element $a \in A$ to its weight $w[a] \geq 0$}
\algoutput{Random element $\Sample \in A$ sampled according to distribution induced by $w$}
\begin{algorithmic}[1]
	\State $W \set 0$
	\For{$a \in A$}
		\State $W \set W + w[a]$ \label{alg:WeightedSample:UpdateWeight}
		\With{probability $\frac{w[a]}{W}$} \label{alg:WeightedSample:Prob}
			\State $\Sample \set a$ \label{alg:WeightedSample:SetSample}
		\EndWith
	\EndFor
\end{algorithmic}
\end{algorithm}

\begin{description}
	\item[Runtime] $O(n)$, single-pass streaming algorithm
	\item[Space] $O(1)$, constant memory
	\item[Correctness]
		Let $a_1, \dots, a_n$ be the order in which the algorithm processes the elements. Denote by $\Sample_t$ the value of $\Sample$ at the end of iteration $t \in \Nupto n$. We prove by induction over $t$ that it holds for all $i \in \Nupto t$ that $\Pr[\Sample_t = a_i] = \frac{w[a_i]}{W_t}$ where $W_t := \sum_{j=1}^t w[a_j]$.

		The base case $t = 1$ holds immediately by lines~\ref{alg:WeightedSample:Prob}--\ref{alg:WeightedSample:SetSample}. To see the induction step $t - 1 \to t$, note that $\Pr[\Sample_t = a_t] = \frac{w[a_t]}{W_t}$ (again by lines~\ref{alg:WeightedSample:Prob}--\ref{alg:WeightedSample:SetSample}) and that for all $i \in \Nupto{t-1}$
		\begin{align*}
			\Pr[\Sample_t = a_i]
			=	\Pr[\Sample_t \neq a_t] \cdot \Pr[\Sample_{t-1} = a_i]
			\stackrel{\text{IH}}{=}
				\left(1 - \frac{w[a_t]}{W_t}\right) \cdot \frac{w[a_i]}{W_{t-1}}
			=	\frac{w[a_i]}{W_t}
			\SiM.
		\end{align*}
	\item[Scalability]
		The algorithm can easily be transformed into a divide-and-conquer algorithm, as shown in the following.
\end{description}

\begin{algorithm}[RecursiveWeightedSample$(A_1, A_2, w)$] \label{alg:RecursiveWeightedSample}
\alginput{Disjoint finite sets $A_1, A_2$, Mapping $w$ of each element $a \in A_1 \cup A_2$ to its weight $w[a] \geq 0$}
\algoutput{Random element $\Sample \in A_1 \cup A_2$ sampled according to distribution induced by $w$}
\begin{algorithmic}[1]
	\State $\tilde A \set \emptyset$
	\For{$i = 1,2$}
		\State $\Sample_i \set \texttt{WeightedSample}(A_i, w)$
		\State $\tilde A \set \tilde A \cup \{ \Sample_i \}$
		\State $\tilde w[\Sample_i] \set \sum_{a \in A_i} w[a]$
	\EndFor
	\State $\Sample \set \texttt{WeightedSample}(\tilde A, \tilde w)$
\end{algorithmic}
\end{algorithm}

\paragraph{Correctness}

Define $W_i := \sum_{a \in A_i} w[a]$. Let $a \in A_i$ be arbitrary. Then $\Pr[\Sample = a] = \Pr[\Sample_i = a] \cdot \Pr[\Sample \in A_i] = \frac{w[a]}{W_i} \cdot \frac{W_i}{W} = \frac{w[a]}{W}.$

\paragraph{Numerical Considerations}

\begin{itemize}
	\item When Algorithm~\ref{alg:WeightedSample} is used for large sets $A$, line~\ref{alg:WeightedSample:UpdateWeight} will eventually add two numbers that are very different in size. Compensated summation should be used \cite{ORO05a}.
\end{itemize}

\subsubsection{Implementation as User-Defined Aggregate}

Algorithm~\ref{alg:WeightedSample} is implemented as the user-defined aggregate \symlabel{weighted\_sample}{sym:weighted_sample}. Data-parallelism is implemented as in Algorithm~\ref{alg:RecursiveWeightedSample}.

\paragraph{Input} The aggregate expects the following arguments:

\begin{center}
	\begin{tabularx}{\linewidth}{lXl}
		\toprule%
		\textbf{Column} & \textbf{Description} & \textbf{Type}
		\\\otoprule
		\texttt{value} &
		Row identifier, each row corresponds to an $a \in A$. There is no need to enforce uniqueness. If a value occurs multiple times, the probability of sampling this value is proportional to the sum of its weights. &
		\textit{generic}
		\\\midrule
		\texttt{weight} &
		weight for row, corresponds to $w[a]$ &
		floating-point
		\\\bottomrule
	\end{tabularx}
\end{center}
%
While it would be desirable to define a user-defined aggregate with a first argument of generic type, this would require a generic transition type (see below). Unfortunately, this is currently not supported in PostgreSQL and Greenplum. However, the internal C++ accumulator type is a generic template class, i.e., only the SQL interface contains redundancies.

\paragraph{Output}

Value of column \texttt{id} in row that was selected.

\paragraph{Components}

\begin{itemize}
	\item Transition State:
		\begin{center}
			\begin{tabularx}{\linewidth}{lXl}
				\toprule%
				\textbf{Field Name} & \textbf{Description} & \textbf{Type}
				\\\otoprule
				\texttt{weight\_sum} &
				corresponds to $W$ in Algorithm~\ref{alg:WeightedSample} &
				floating-point
				\\\midrule
				\texttt{sample} &
				corresponds to $\Sample$ in Algorithm~\ref{alg:WeightedSample}, takes value of column \texttt{value} &
				\textit{generic}
				\\\bottomrule
			\end{tabularx}
		\end{center}
	\item Transition Function (\texttt{state, id, weight}): Lines~\ref{alg:WeightedSample:UpdateWeight}--\ref{alg:WeightedSample:SetSample} of Algorithm~\ref{alg:WeightedSample}
	\item Merge Function (\texttt{state1, state2}): It is enough to call the transition function with arguments (\texttt{state1, state2.sample\_id, state2.weight\_sum})
\end{itemize}

\paragraph{Tool Set}

While the user-defined aggregate is simple enough to be implemented in plain SQL, we choose a C++ implementation for performance. \todo{In the future, we want to use compensated summation. (Not documented yet.)}

\section{Sampling with Replacement} % (fold)
\label{sec:SamplingWithReplacement}
In Postgres, with the help of the \texttt{row\_number()} window function, we could achive sampling with replacement by joining the input table with a list of randomly-generated numbers using row numbers.

\lstset{numbers=none}

\subsection{Assign Row Numbers for Input Table}
\begin{sql}
    SELECT (row_number() OVER ())::integer AS rn, * FROM $input_table;
\end{sql}

\subsection{Generate A Row Number Sample Randomly}
\begin{sql}
    SELECT ceiling((1 - random()) * $size)::integer AS rn FROM generate_series(1, $size) s;
\end{sql}

\subsection{Join to Generate Sample}
\begin{sql}
    SELECT *
    FROM
    (
        SELECT (row_number() OVER ())::integer AS rn, * FROM $input_table
    ) src
    JOIN
    (
        SELECT ceiling((1 - random()) * $size)::integer AS rn FROM generate_series(1, $size) s
    ) sample_rn
    USING (rn);
\end{sql}

\lstset{numbers=left}


\chapter{Symmetry Groups}


\documentclass[12pt, titlepage]{article}

% Author's up-front packages
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{longtable}

%Packages from template
\usepackage{amsmath, mathtools}
%\usepackage[round]{natbib}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{graphicx}
\usepackage{colortbl}
\usepackage{xr-hyper}
\usepackage{hyperref}
\usepackage{xfrac}
\usepackage{tabularx}
\usepackage{float}
\usepackage{siunitx}
\usepackage{booktabs}
\usepackage{multirow}
\usepackage[section]{placeins}
\usepackage{caption}
\usepackage{fullpage}

% Author's packages

\usepackage{cite}
\usepackage{indentfirst}
\usepackage{csquotes}
\usepackage{cleveref}

\hypersetup{
%bookmarks=true,     % show bookmarks bar?
colorlinks=true,       % false: boxed links; true: colored links
linkcolor=red,          % color of internal links (change box color with linkbordercolor)
citecolor=blue,      % color of links to bibliography
filecolor=magenta,  % color of file links
urlcolor=cyan          % color of external links
}

\usepackage{array}

\input{../../Comments}

\newcommand{\progname}{STEM Moir{\'e} GPA}
\externaldocument[SRS:]{../../SRS/SRS}
\externaldocument[TP:]{../../TestPlan/TestPlan}
\externaldocument[MG:]{../MG/MG}

%Set the custom referencing syste
	% Module
\newtheorem{M}{M}
\crefname{M}{M}{Ms}
	% Module Interface Specification
\newtheorem{MIS}{MIS}
\crefname{MIS}{MIS}{MISs}
	% Requirements
\newtheorem{R}{R}
\crefname{R}{R}{Rs}
	% Instance Model
\newtheorem{IM}{IM}
\crefname{IM}{IM}{IMs}

\begin{document}

\title{Module Interface Specification for \progname{}}

\author{Alexandre Pofelski \\
		macid: pofelska \\
		github: slimpotatoes}

\date{\today}

\maketitle

\pagenumbering{roman}

\section{Revision History}

\begin{table}[h]
\caption{\bf Revision History}
\begin{tabularx}{\textwidth}{p{3cm}p{2cm}X}
\toprule {\bf Date} & {\bf Version} & {\bf Notes}\\
\midrule
29/11/2017 & 1.0 & MIS First Draft\\
15/12/2017 & 1.1 & Correction of matrices expression in
\cref{MIS_StrainCalc}\\
\bottomrule
\end{tabularx}
\end{table}

~\newpage

\section{Symbols, Abbreviations and Acronyms}

The same Symbols, Abbreviations and Acronyms as in the SRS, the TestPlan and the
MG (available in
\href{https://github.com/slimpotatoes/STEM_Moire_GPA}{\progname{}} repository)
are used in the Module Interface Specifications document.

\newpage

\tableofcontents

\newpage

\pagenumbering{arabic}

\section{Introduction}

The following document details the Module Interface Specifications for
\progname{}. The full documentation and implementation can be found in
\href{https://github.com/slimpotatoes/STEM_Moire_GPA}{\progname{}} repository.

\section{Notation}

The structure of the MIS for modules comes from \cite{HoffmanAndStrooper1995},
with the addition that template modules have been adapted from
\cite{GhezziEtAl2003}. The following table summarizes the primitive data types
used by \progname.

\begin{center}
\renewcommand{\arraystretch}{1.2}
\noindent
\begin{tabular}{l l p{7.5cm}}
\toprule
\textbf{Data Type} & \textbf{Notation} & \textbf{Description}\\
\midrule
character & char & a single symbol or digit\\
integer & $\mathbb{Z}$ & an integer number \\
natural & $\mathbb{N}$ & a natural number \\
real & $\mathbb{R}$ & a real number \\
complex & $\mathbb{C}$ & a complex number \\
image space & $\mathbb{I}$ & subset of $\mathbb{N}^2$ such that
$\mathbb{I}=\{(x,y)\in \mathbb{N} \times \mathbb{N} : 0 \leq x \leq N-1 \wedge 0
\leq y \leq N-1 \} $ with $N \in \mathbb{N}$ representing the number of pixels
of the image in one direction\\
\bottomrule
\end{tabular}
\end{center}

\wss{I like the introduction of the image space type.  This will help with the
  specification.}

\noindent
The specification of \progname{} uses some derived data types: sequences,
strings, and
tuples. Sequences are lists filled with elements of the same data type. Strings
are sequences of characters. Tuples contain a list of values, potentially of
different types. In addition, \progname \ uses functions, which
are defined by the data types of their inputs and outputs. Local functions are
described by giving their type signature followed by their specification.

\section{Module Decomposition}

The following table is taken directly from the Module Guide document for this
project.

\begin{table}[H]
\centering
\begin{tabular}{p{0.3\textwidth} p{0.6\textwidth}}
\toprule
\textbf{Level 1} & \textbf{Level 2}\\
\midrule

{Hardware-Hiding Module} & ~ \\
\midrule

\multirow{9}{0.3\textwidth}{Behaviour-Hiding Module}
& \progname{} Control (\cref{MG:M_Control}, \cref{MIS_Control})\\
& \progname{} GUI (\cref{MG:M_GUISMG}, \cref{MIS_GUISMG})\\
& Input (\cref{MG:M_InputFormat}, \cref{MIS_Input})\\
& SMH simulation (\cref{MG:M_SMHSim}, \cref{MIS_SMHSim})\\
& GPA (\cref{MG:M_GPA}, \cref{MIS_GPA})\\
& Mask (\cref{MG:M_Mask}, \cref{MIS_Mask})\\
& Unstrained region (\cref{MG:M_URef}, \cref{MIS_URef})\\
& Conversion (\cref{MG:M_MtoCConv}, \cref{MIS_MtoCConv})\\
& 2D strain tensor (\cref{MG:M_StrainCalc}, \cref{MIS_StrainCalc})\\
\midrule

\multirow{6}{0.3\textwidth}{Software Decision Module} & Fourier Transform
(\cref{MG:M_FT}, \cref{MIS_FT}) \\
& Gradient (\cref{MG:M_Gradient}, \cref{MIS_Gradient}) \\
& Least square fitting method (\cref{MG:M_LSFM}, \cref{MIS_LSFM})  \\
& Phase Operation (\cref{MG:M_Phase}, \cref{MIS_Phase}) \\
& Data structure (\cref{MG:M_DataStruct}, \cref{MIS_DataStruct}) \\
& Generic GUI/Plot (\cref{MG:M_GUIGene}, \cref{MIS_GUIGene}) \\
\bottomrule

\end{tabular}
\caption{Module Hierarchy}
\label{TblMH}
\end{table}

\newpage

\section{MIS of STEM Moir{\'e} GPA Control Module (\texorpdfstring{\cref{MG:M_Control}}))} \label{MIS_Control}

\subsection{Module}
main
\subsection{Uses}
\begin{itemize}
\item STEM Moir{\'e} GPA GUI (\cref{MG:M_GUISMG}, \cref{MIS_GUISMG})
\item Processing modules \begin{itemize}
	\item Unstrained region (\cref{MG:M_URef}, \cref{MIS_URef})
	\item Conversion (\cref{MG:M_MtoCConv}, \cref{MIS_MtoCConv})
	\item SMH Simulation (\cref{MG:M_SMHSim}, \cref{MIS_SMHSim})
	\item GPA(\cref{MG:M_GPA}, \cref{MIS_GPA})
	\item 2D Strain Tensors (\cref{MG:M_StrainCalc}, \cref{MIS_StrainCalc})
\end{itemize}
\item Input (\cref{MG:M_InputFormat}, \cref{MIS_Input})
\item Data Structure (\cref{MG:M_DataStruct}, \cref{MIS_DataStruct})
\end{itemize}

\subsection{Syntax}

\subsubsection{Exported Access Programs}

\begin{center}
\begin{tabular}{p{2cm} p{3cm} p{3cm} p{3cm}}
\hline
\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\
\hline
main & - & - & - \\
\hline
\end{tabular}
\end{center}

\subsection{Semantics}

\progname{} is designed to have the process flow driven by user directly through
GUI{\_}SMG. The STEM Moir{\'e} GPA Control Module uses the events in STEM
Moi{\'e} GPA GUI to use the processing modules in the order defined by the user.

\subsubsection{State Variables}

None

\subsubsection{Access Routine Semantics}

\noindent main():
\begin{itemize}
\item transition:

GUIFlow()
\noindent\textit{{\#} Software permanently running until user abort it by
closing the GUI.} \medskip
GUI{\_}Conv()
\noindent\textit{{\#} Open the entry field GUI for the conversion process.}
\medskip

If one of the event below is triggered by the user, an action is performed by
\progname{}. The possible events are:
	\begin{itemize}
	\item $\text{event{\_}Input()} \\ \rightarrow \text{Get the path pathISMH and
pathIC from the user} \  \rightarrow \\
\text{load{\_}files(pathISMH,pathIC)})\rightarrow \text{GUI{\_}SMHexp}()$
	\item $\text{event{\_}SimSMH()} \rightarrow \text{SMHsim}() \rightarrow
\text{GUI{\_}SMHsim}()$
	\item $\text{For each circle GUI object } C_j \text{ with } j=\{1,2\} \\ \text{
drawn by the user in the of GUI{\_}SMHsim() window }: $
		\begin{enumerate}
		\item $\text{event{\_}GPA()} \rightarrow
\text{verifyM}(\text{collect{\_}circ}(C_j)) \rightarrow \\
\text{gpa}(\text{collect{\_}circ}(C_j),\text{id}(C_j)) \rightarrow
\text{GUI{\_}Phase}()$
		\item $\text{event{\_}URef()} \rightarrow
\text{verifyU}(\text{collect{\_}rect}(Rec))\rightarrow \\ \text{ZeroStrain}(
\text{collect{\_}rect}(Rec),\text{id}(C_j))\rightarrow \text{update
GUI{\_}Phase}()$
		\item $\text{event{\_}Conversion()} \rightarrow \text{Read the $n$ and $m$
entry fields in GUI{\_}Conv} \rightarrow \\ \text{verifyNM}(n,m)\rightarrow
\text{conversion}(n,m,\text{id}(C_j)$
		\end{enumerate}
	\item $\text{event{\_}StrainCalc()} \rightarrow
\text{verifyMdiff}(\text{collect{\_}circ}(C_1),\text{collect{\_}circ}(C_2))
\rightarrow \\
	 \text{CalcStrain}(\text{id}(C_1),\text{id}(C_2))\rightarrow
\text{GUI{\_}Strain}()$
	\end{itemize}
\end{itemize}

\an{At current state, the MIS of the control module is not elegant. It is again
due to a poor design (or poor understanding) of the control module and its
interface with the other modules. The case with the GUI id is not optimum.
Ideally, I would like to have the possibility to draw multiple masks and see
their intermediate results to only choose the two best ones for the final
calculation (StrainCalc(id1,id2)). For that, I would need a new module that
could reference the different maks and enable the user to navigate through them.
I didn't thought about that enough in advance and got stuck with that version. I
will improve that in the future.}
\wss{An environment variable for the GUI would help your specification.  The
  environment variable could have fields for SelectInput, SelectSimSMH, Close,
  etc.  You could then write your specification in terms of the values of the
  GUI environment variable.}

\wss{This document is easier to read if every module starts on a new page.}

\section{MIS of STEM Moir{\'e} GPA GUI Module (\texorpdfstring{\cref{MG:M_GUISMG}}))} \label{MIS_GUISMG}

\noindent\textit{{\#} Specific GUI module to respect the requirements from the
SRS}\medskip

\wss{I'm confused by there being both a control module and a GUI module.  It
  seems that the GUI module has an environment variable like I was suggesting
  above, which makes me think I missed the point of the previous module, or you
  don't need the previous module?}

\subsection{Module}
GUI{\_}SMG
\subsection{Uses}
\begin{itemize}
\item Generic GUI/Plot (\cref{MG:M_GUIGene}, \cref{MIS_GUIGene})
\item Data Structure (\cref{MG:M_DataStruct}, \cref{MIS_DataStruct})
\end{itemize}

\subsection{Syntax}

\subsubsection{Exported Access Programs}

\noindent\textit{{\#} For the moment, the GUI exceptions are not mentioned to
cover the other aspects of \progname{}.}\medskip

\begin{center}
\begin{tabular}{p{4cm} p{3cm} p{3cm} p{3cm}}
\hline
\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\
\hline
GUIFlow & - & - & - \\
GUI{\_}SMHexp & - & - & - \\
GUI{\_}SMHSim & - & - & - \\
GUI{\_}Phase & - & - & - \\
GUI{\_}Conv & - & - & - \\
GUI{\_}Strain & - & - & - \\
event{\_}Input & - & - & - \\
event{\_}SMHSim & - & - & - \\
event{\_}GPA & - & - & - \\
event{\_}URef & - & - & - \\
event{\_}StrainCalc & - & - & - \\
collect{\_}circ & GUI object & $(x_c,y_c)\in\mathbb{I}$,$R \in\mathbb{R}^{+*}$ &
- \\
collect{\_}rect & GUI object & $U \subset \mathbb{I}$ & -\\
id & GUI object & id of GUI object & - \\
\hline
\end{tabular}
\end{center}

\subsection{Semantics}

\progname{} process flow is driven by user through GUI{\_}SMG. User triggers the
events that start the selected processing step.

\subsubsection{State Variables}
None

\subsubsection{Environment Variables}

\noindent Win{\_}Flow: GUI object\\
Win{\_}SMHexp: GUI object\\
Win{\_}SMHSim: GUI object\\
Win{\_}Phase: GUI object\\
Win{\_}FTSMH: GUI object\\
Win{\_}Conv: GUI object\\
Win{\_}Deltag: GUI object\\
Win{\_}Strain: GUI object\\
button{\_}Input: GUI object\\
button{\_}SMHSim: GUI object\\
button{\_}GPA: GUI object\\
button{\_}URef: GUI object\\
button{\_}StrainCalc: GUI object\\

\subsubsection{Access Routine Semantics}

\noindent\textit{{\#} GUI embedding the process flow into buttons triggering
events. It is the user role to execute the process flow.}\medskip

\noindent GUIFlow():
\begin{itemize}
\item transition:
	\begin{enumerate}
	\item Win{\_}Flow=fig('Win{\_}Flow')
	\item button(Win{\_}Flow,5,'Input','SMHSim','GPA','URef','StrainCalc')
	\item plot()
	\end{enumerate}
\end{itemize}
\bigskip

\noindent\textit{{\#} Events triggered by each button pressed by the
user.}\medskip

\noindent event{\_}Input():
\begin{itemize}
\item transition: Trigger event{\_}Input when button{\_}Input pressed.
\end{itemize}
\bigskip
\noindent event{\_}SMHSim():
\begin{itemize}
\item transition: Trigger event{\_}SMHSim when button{\_}SMHSim pressed.
\end{itemize}
\bigskip
\noindent event{\_}GPA():
\begin{itemize}
\item transition: Trigger event{\_}GPA when button{\_}GPA pressed.
\end{itemize}
\bigskip
\noindent event{\_}URef():
\begin{itemize}
\item transition: Trigger event{\_}URef when button{\_}URef pressed.
\end{itemize}
\bigskip
\noindent event{\_}StrainCalc():
\begin{itemize}
\item transition: Trigger event{\_}StrainCalc when button{\_}StrainCalc press.
\end{itemize}
\bigskip

\noindent\textit{{\#} GUI to display the display the input files
$I_{\mathit{SMH}_{\text{exp}}}$, $I_{C_{\text{ref}}}$.}\medskip

\noindent GUI{\_}SMHexp():
\begin{itemize}
\item transition:
	\begin{enumerate}
	\item Win{\_}SMHexp=fig('Win{\_}SMHexp',load($I_{\mathit{SMH}_{\text{exp}}}$),
load($I_{C_{\text{ref}}}$))
	\item plot()
	\end{enumerate}
\end{itemize}
\bigskip

\noindent\textit{{\#} GUI to display the simulated STEM Moir{\'e} hologram using
the reference image and to let the user input $M$ on the experimental STEM
Moir{\'e} hologram (from \cref{SRS:R_4}, \cref{SRS:R_5}).}\medskip

\noindent GUI{\_}SMHSim():
\begin{itemize}
\item transition:
	\begin{enumerate}
	\item
Win{\_}SMHSim=fig('Win{\_}SMHSim',load(FTISMHexp), \\
load(FTISMHsim),circle($M$))
	\item plot()
	\end{enumerate}
\end{itemize}
\bigskip

\noindent\textit{{\#} GUI to display the phase resulting from the GPA algorithm
and to let the user input $U$ (from \cref{SRS:R_8}).}\medskip

\noindent GUI{\_}Phase($id$):
\begin{itemize}
\item transition:
	\begin{enumerate}
	\item Win{\_}Phase=fig('Win{\_}Phase',load{\_}g($id$)(PhasegM),rectangle($U$))
	\item Win{\_}Deltag=fig('Win{\_}Deltag',load{\_}g($id$)(deltagM))
	\item plot()
	\end{enumerate}
\end{itemize}
\bigskip

\noindent\textit{{\#} GUI to display the window to let the user input $n$ and
$m$ (from \cref{SRS:R_11}).}\medskip

\noindent GUI{\_}Conv():
\begin{itemize}
\item transition:
	\begin{enumerate}
	\item Win{\_}Conv=fig('Win{\_}Conv',entry{\_}field($n$),entry{\_}field($m$))
	\item plot()
	\end{enumerate}
\end{itemize}
\bigskip

\noindent\textit{{\#} GUI to display the window showing the final strain maps
(from \cref{SRS:R_14}).}\medskip

\noindent GUI{\_}Strain():
\begin{itemize}
\item transition:
	\begin{enumerate}
	\item
Win{\_}Strain=fig('Win{\_}Strain',load(Exx),load(Eyy),load(Exy),load(Rxx))
	\item plot()
	\end{enumerate}
\end{itemize}
\bigskip

\noindent\textit{{\#} Reader of the GUI objects drawn by the user (circle $M$ or
rectangle $U$).} \medskip

\noindent collect{\_}circ($A$)
\begin{itemize}
\item output: $C$ such that
	\begin{enumerate}
	\item Execute read{\_}user{\_}GUI($A$)
	\item Verify the type of the object read{\_}user{\_}GUI($A$) to match a circle
	\item Output $C$=$(x_c,y_c,R)$ with $(x_c,y_c)$ the coordinate (pixel number)
of the center of the circle $A$ and $R$ the radius of the circle $A$.
	\end{enumerate}
\end{itemize}
\bigskip

\noindent collect{\_}rect($A$)
\begin{itemize}
\item output: $S$ such that
	\begin{enumerate}
	\item Execute read{\_}user{\_}GUI($A$)
	\item Verify the type of the object read{\_}user{\_}GUI($A$) to match a
rectangle
	\item Get the coordinate of the upper left corner $(x_0,y_0)$ and the
coordinate of the bottom right corner $(x_1,y_1)$.
	\item output $S=([x_0,x_1],[y_0,y_1])$
	\end{enumerate}
\end{itemize}
\bigskip

\noindent\textit{{\#} Function to read the unique id of a GUI object.} \medskip

\noindent id($A$)
\begin{itemize}
\item output: $B$ such that $B$ is the id part of the read{\_}user{\_}GUI($A$)
output from the Generic GUI/Plot Module.
\end{itemize}
\bigskip

\section{MIS of Input Module (\texorpdfstring{\cref{MG:M_InputFormat}}))}
\label{MIS_Input}

\an{I made lots of changes with the Input Module between the MG and the MIS. The
original design was not optimal and I tried to fit every verification step of
the inputs in
this input module. It seems to work but I keep in mind the possibility to verify
(M,U,n and m) separately in another module}

\subsection{Module}
Input
\subsection{Uses}
\begin{itemize}
\item Data Structure (\cref{MG:M_DataStruct}, \cref{MIS_DataStruct})
\end{itemize}

\subsection{Syntax}

\subsubsection{Exported Access Programs}

\begin{center}
\begin{tabular}{p{2cm} p{3cm} p{1cm} p{7cm}}
\hline
\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\
\hline
load{\_}files & string & - & badFilePath, badPixelP, badPixelPref, badIC,
badISMH, badFileFormat \\
verifyI & $I:\mathbb{I}\rightarrow\mathbb{R}$ & - & Not2Darray, NotReal\\
verifyp & $p \in \mathbb{R}^{+*}$ & - & BadPixelP\\
verifyM & $M \in \mathbb{I} \times \mathbb{R}$ & - & NoMask, BadMask \\
verifyU & $U \subset \mathbb{I}$ & - & BadSizeU, NoU \\
verifyMdiff & $(M \in \mathbb{I} \times \mathbb{R})^2$ & - & SameMask \\
verifyNM & $(n,m)\in\mathbb{N}^2$ & - & BadNM\\
\hline
\end{tabular}
\end{center}

\subsection{Semantics}

\subsubsection{State Variables}

data : object

\subsubsection{Access Routine Semantics}

\noindent\textit{{\#} Function to load, verify and store
$I_{\mathit{SMH}_{\text{exp}}}$, $I_{C_{\text{ref}}}$, $p$ and $p_{\text{ref}}$
(see \cref{SRS:R_1} and \cref{SRS:R_2} from the SRS).}
\medskip

\noindent load{\_}files(pathISMH,pathIC):
\begin{itemize}
\item transition: pathISMH and pathIC are the file paths for the input files.
The following procedure is performed:
\begin{enumerate}
\item Verify the format of the files to be .dm3
\item From the .dm3 metafile, $I_{\mathit{SMH}_{\text{exp}}}$,
$I_{C_{\text{ref}}}$, $p$ and $p_{\text{ref}}$ are extracted.
\item verifyI($I_{\mathit{SMH}_{\text{exp}}}$), verifyI($I_{C_{\text{ref}}}$)
\item verifyp($p$), verifyp($p_{\text{ref}}$)
\item The variables $I_{\mathit{SMH}_{\text{exp}}}$, $I_{C_{\text{ref}}}$, $p$
and $p_{\text{ref}}$ are stored in the data structure:
\begin{itemize}
\item store(ISMHexp, $I_{\mathit{SMH}_{\text{exp}}}$)
\item store(pISMexp, $p$)
\item store(ICref, $I_{C_{\text{ref}}}$)
\item store(pICref, $p_{\text{ref}}$)
\end{itemize}
\end{enumerate}
\item exception:
\noindent \begin{longtable*}[l]{l l}
$\neg (p > 0)$ & $\Rightarrow$ badPixelP\\
$\neg (p_{\text{ref}} > 0)$ & $\Rightarrow$ badPixelP\\
($\exists \vec{r} \in \mathbb{I}:I_{\mathit{SMH}_{\text{exp}}}(\vec{r}) \notin
\mathbb{R})$ & $\Rightarrow$ NotReal\\
($\exists \vec{r} \in \mathbb{I}:I_{C_{\text{ref}}}(\vec{r}) \notin \mathbb{R})$
& $\Rightarrow$ NotReal\\
If the file targeted by pathISMH or pathIC doesn't exist & $\Rightarrow$
badFilePath\\
If the file format is not appropriate & $\Rightarrow$ badFileFormat\\
\end{longtable*}
\end{itemize}

\wss{Your document has proven easy to navigate.  I was wondering what the type
  is for $I_{\mathit{SMH}_{\text{exp}}}$, and following your documentation, I
  easily found the answer in Section 19.  Since ISMHexp is a function from I to
  R, how will it be possible for the resulting type to be anything other than R?
  Thinking about this further, it is probably because for certain inputs the
  function evaluation will not be real, like the square root of a negative
  number.  This does seem like a situation that would come up, and your
  programming language is going to generate an exception in those cases, so you
  will be able to implement your proposed interface.  Looks good.}

\noindent verifyp($p$):
\begin{itemize}
\item output: None
\item exception:\newline
$\neg (p > 0 )\Rightarrow \text{badPixelP}$
\end{itemize}
\bigskip

\noindent verifyI($I$):
\begin{itemize}
\item output: None
\item exception:\newline
$(\exists \vec{r} \in \mathbb{I}: I(\vec{r}) \notin \mathbb{R}) \Rightarrow
\text{NotReal}$\\
$\neg(I:\mathbb{I} \rightarrow \mathbb{R})\Rightarrow \text{Not2Darray}$
\end{itemize}
\bigskip

\noindent\textit{{\#} Functions to verify the size of the unstrained reference
input $U$ (see \cref{SRS:R_9}), the size of the mask input $M_j$ and if both
masks are different (see \cref{SRS:R_6}).}
\medskip

\noindent verifyU($U$):
\begin{itemize}
\item output: None
\item exception:\newline
$(U=\emptyset)\Rightarrow\text{NoU}$\\
$\neg (U \subset \mathbb{I}) \Rightarrow \text{BadSizeU}$
\end{itemize}
\bigskip

\noindent verifyM($M_j$):
\begin{itemize}
\item output: None
\item exception:\newline
$(M_j=\emptyset)\Rightarrow\text{NoMask}$\\
$\neg((x_j,y_j) \in \mathbb{I})\Rightarrow \text{BadMask}$\\
\end{itemize}
\bigskip

\noindent verifyMdiff($M_1,M_2$):
\begin{itemize}
\item output: None
\item exception:\newline
$(M_1=M_2)\Rightarrow\text{SameMask}$
\end{itemize}
\bigskip

\noindent verifyMN($M_1,M_2$):
\begin{itemize}
\item output: None
\item exception:\newline
$\neg (n \in \mathbb{N} \wedge m \in \mathbb{N}) \Rightarrow \text{BadNM}$
\end{itemize}

\section{MIS of SMH Simulation (\texorpdfstring{\cref{MG:M_SMHSim}}))}
\label{MIS_SMHSim}

\noindent\textit{{\#} Module simulating the STEM Moir{\'e} hologram using a
reference image (see \cref{SRS:R_3} in the SRS).}

\subsection{Module}
SMHSimCalc
\subsection{Uses}
\begin{itemize}
\item Fourier Transform (\cref{MG:M_FT}, \cref{MIS_FT})
\item Data Structure (\cref{MG:M_DataStruct}, \cref{MIS_DataStruct})
\end{itemize}

\subsection{Syntax}

\subsubsection{Exported Access Programs}

\begin{center}
\begin{tabular}{p{3cm} p{3cm} p{3cm} p{4cm}}
\hline
\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\
\hline
SMHsim & - & - & WarnNlimzero\\
\hline
\end{tabular}
\end{center}

\subsection{Semantics}

\subsubsection{State Variables}

data : object

\subsubsection{Access Routine Semantics}

\noindent SMHsim():
\begin{itemize}
\item transition: \wss{The idea of your data object providing a load method (or
    read method) is fine.  However, if you want to simplify your documentation,
    you could use the dot notation directly to access fields of your ADT.  You
    could just write data.$I_{\mathit{SMH}_{\text{exp}}}$.  Since you have the
    correct uses clause and state variable (data), you could think about
    skipping the data part and just go with the name of the field directly.
    Given the number of symbols you have though, your approach might be better
    because it makes the connection explicit.}
	\begin{enumerate}
	\item Load the inputs from the data object
	\begin{itemize}
	\item $I_{\mathit{SMH}_{\text{exp}}}$=load(ISMHexp)
	\item $I_{C_{\text{ref}}}$=load(ICref)
	\item $p$=load(pISMHexp)
	\item $p_{\text{ref}}$=load(pICref)
	\end{itemize}
	\item store(FTISMHexp, $\widetilde{I}_{\mathit{SMH}_{\text{exp}}}$) such that
	\begin{equation*}
\widetilde{I}_{\mathit{SMH}_{\text{exp}}}(\vec{\nu})=\mathcal{FT}[I_{\mathit{SMH}_{\text{exp}}}(\vec{r})]
	\end{equation*}
	\item store(FTISMHsim, $\widetilde{I}_{\mathit{SMH}_{\text{sim}}}$) such that
	\begin{equation*}
	\begin{gathered}
\widetilde{I}_{\mathit{SMH}_{\text{sim}}}(\vec{\nu})=\frac{1}{p^2}\sum_{\vec{q}\in
Q_{lim}}\mathcal{FT}[I_{C_{\text{ref}}}(\vec{\nu}-\frac{\vec{q}}{p})] \\
	\text{with } Q_{\text{lim}}=\{\forall (n,m) \in
\mathbb{Z}^{2}\cap[-N_{\text{lim}},N_{\text{lim}}]^2, \
\vec{q}=n\vec{u_x}+m\vec{u_y}\} \\
	\text{and } N_{\text{lim}}=\Xi(\frac{p}{p_{\text{ref}}}) \text{ with } \Xi
\text{ the floor function }
	\end{gathered}
	\end{equation*}
	\end{enumerate}

\item exception:
\newline
$(N_{lim}=0) \Rightarrow \text{WarnNlimzero}$
\textit{{\#} Exception warns the user that the sampling parameter chosen is
oversampling the crystal periodicity. Classic HRSTEM GPA case !! It's not a STEM
Moir{\'e} interferometry experiment but the software still works for the classic
case.}

\end{itemize}

\section{MIS of GPA Module (\texorpdfstring{\cref{MG:M_GPA}}))} \label{MIS_GPA}

\noindent\textit{{\#} Module performing the GPA algorithm to isolate one spatial
frequency and output the phase component (see \cref{SRS:R_7} in the SRS).}

\subsection{Module}
GPACalc
\subsection{Uses}
\begin{itemize}
\item Mask (\cref{MG:M_Mask}, \cref{MIS_Mask})
\item Fourier Transform (\cref{MG:M_FT}, \cref{MIS_FT})
\item Phase (\cref{MG:M_Phase}, \cref{MIS_Phase})
\item Gradient (\cref{MG:M_Gradient}, \cref{MIS_Gradient})
\item Data Structure (\cref{MG:M_DataStruct}, \cref{MIS_DataStruct})
\end{itemize}

\subsection{Syntax}

\subsubsection{Exported Access Programs}

\begin{center}
\begin{tabular}{p{2cm} p{4cm} p{4cm} p{3cm}}
\hline
\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\
\hline
gpa & $C \in \mathbb{I}\times\mathbb{R}$ , $id : \text{id of GUI object}$ & -
& - \\
\hline
\end{tabular}
\end{center}

\subsection{Semantics}

\subsubsection{State Variables}

data : object

\subsubsection{Access Routine Semantics}

\noindent gpa($C$,$id$):
\begin{itemize}
\item transition:
	\begin{enumerate}
	\item $M,\overrightarrow{g}^{M_{\text{exp}}}=\text{MCirc}(C)$
	\item store{\_}g($id$, Mask, $C$), store{\_}g($id$, gMuns,
$\overrightarrow{g}^{M_{\text{exp}}}$)
	\item $\widetilde{I}_{\mathit{SMH}_{\text{exp}}}$=load(FTISMHexp)
	\item Calculate $P_{\vec{g}}$ such that
	\begin{equation*}
	\forall \vec{r} \in \mathbb{R}^2, \
P_{\vec{g}}(\vec{r})=\text{arg}(i\mathcal{FT}[M\times\widetilde{I}_{\mathit{SMH}_{\text{exp}}}])
	\end{equation*}
	\item store{\_}g($id$,deltagM,$\overrightarrow{\Delta g}$) such that
	\begin{equation*}
	\forall \vec{r} \in \mathbb{I}, \ \Delta
\overrightarrow{g}(\vec{r})=\frac{1}{2\pi}\text{grad}(\text{unwrap}(P_{\vec{g}}(\vec{r})))-\overrightarrow{g}^{M_{\text{exp}}}(\vec{r})
	\end{equation*}
	\item store{\_}g($id$,PhasegM,$P_{\Delta \vec{g}}$) such that
	\begin{equation*}
	\forall \vec{r} \in \mathbb{I}, \ P_{\Delta
\vec{g}}(\vec{r})=\text{wrap}(\text{unwrap}[P_{\vec{g}}(\vec{r})]-2\pi\overrightarrow{g}^{M_{\text{exp}}}(\vec{0})\cdot
\vec{r})
	\end{equation*}
	\end{enumerate}
\item exception: none
\end{itemize}

\section{MIS of Mask Module (\texorpdfstring{\cref{MG:M_Mask}}))}
\label{MIS_Mask}

\noindent\textit{{\#} Module transforming the circle drawn to a mask function
usable by the GPA module.}

\subsection{Module}
Mask
\subsection{Uses}
None

\subsection{Syntax}

\subsubsection{Exported Access Programs}

\begin{center}
\begin{tabular}{p{2cm} p{4cm} p{5cm} p{3cm}}
\hline
\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\
\hline
MCirc & $(x_c,y_c) \in \mathbb{I}$ , $R \in \mathbb{R}^{+*}$ &
$M:\mathbb{I}\rightarrow\mathbb{R}$ , $\overrightarrow{g_0}
:\mathbb{I}\rightarrow\mathbb{R}^2$ & BadRadius, BadCenter\\
\hline
\end{tabular}
\end{center}

\subsection{Semantics}

\subsubsection{State Variables}
None

\subsubsection{Access Routine Semantics}

\noindent MCirc($x_c,y_c,R$):
\begin{itemize}
\item output: $M$,$\overrightarrow{g_0}$
	\begin{itemize}
	\item $M$ such that
	\begin{equation*}
	\forall \vec{r} \in \mathbb{I}, \ M(x,y)=\begin{cases}
	1, \ (x-x_c)^2+(y-y_c)^2\leq R^2 \\
	0, \ (x-x_c)^2+(y-y_c)^2> R^2
	\end{cases}
	\end{equation*}
	\item $\overrightarrow{g_0}$ such that
	\begin{equation*}
	\forall \vec{r} \in \mathbb{I}, \ \overrightarrow{g_0}(\vec{r})=\begin{bmatrix}
	x_c\\
	y_c
	\end{bmatrix}
	\end{equation*}
	\end{itemize}
\item exception:
\newline
$\neg (R>0) \Rightarrow \text{BadRadius}$\\
$\neg ((x_c,y_c) \in \mathbb{I}) \Rightarrow \text{BadCenter}$
\end{itemize}

\section{MIS of Unstrained region Module (\texorpdfstring{\cref{MG:M_URef}}))}
\label{MIS_URef}

\noindent\textit{{\#} Module correcting the g vector of reference using the user
input U (see \cref{SRS:R_10} in the SRS).}

\subsection{Module}
URefCalc
\subsection{Uses}
\begin{itemize}
\item Least Square Fit (\cref{MG:M_LSFM}, \cref{MIS_LSFM})
\item Data Structure (\cref{MG:M_DataStruct}, \cref{MIS_DataStruct})
\end{itemize}

\subsection{Syntax}

\subsubsection{Exported Access Programs}

\begin{center}
\begin{tabular}{p{2.5cm} p{5cm} p{2cm} p{3cm}}
\hline
\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\
\hline
ZeroStrain & $U \subset \mathbb{I}$ , $id :$ id of GUI object & - & - \\
\hline
\end{tabular}
\end{center}

\subsection{Semantics}

\subsubsection{State Variables}

data : object

\subsubsection{Access Routine Semantics}

\noindent ZeroStrain($U$, $id$):
\begin{itemize}
\item transition:
	\begin{enumerate}
	\item $\overrightarrow{\Delta g}^{M_{\text{exp}}}$=load{\_}g($id$, deltag),
$\overrightarrow{g}^{M_{\text{exp}}}$=load{\_}g($id$, gMuns)
	\item store(U, $U$)
	\item store($id$, deltagM, $\overrightarrow{\Delta
g}_{\text{cor}}^{M_{\text{exp}}}$) such that
	\begin{equation*}
\overrightarrow{\Delta g}_{\text{cor}}^{M_{\text{exp}}} = \overrightarrow{\Delta
g}^{M_{\text{exp}}} - \text{lsfm}(\overrightarrow{\Delta g}^{M_{\text{exp}}},U)
	\end{equation*}
	\item store($id$, gMuns, $\overrightarrow{g}_{\text{uns}}^{M_{\text{exp}}}$)
such that
	\begin{equation*}
\overrightarrow{g}_{\text{uns}}^{M_{\text{exp}}} =
\overrightarrow{g}^{M_{\text{exp}}} + \text{lsfm}(\overrightarrow{\Delta g}^M,U)
	\end{equation*}
	\end{enumerate}
\item exception:\newline
$(\neg U \subset \mathbb{I} \Rightarrow \text{BadSizeU})$
\end{itemize}

\section{MIS of Conversion Module (\texorpdfstring{\cref{MG:M_MtoCConv}}))}
\label{MIS_MtoCConv}

\noindent\textit{{\#} Module converting the Moire g vector into the crystalline
g vector (see \cref{SRS:R_12} in the SRS).}

\subsection{Module}
MtoCConv
\subsection{Uses}
\begin{itemize}
\item Data Structure (\cref{MG:M_DataStruct}, \cref{MIS_DataStruct})
\end{itemize}

\subsection{Syntax}

\subsubsection{Exported Access Programs}

\begin{center}
\begin{tabular}{p{2cm} p{4cm} p{4cm} p{3cm}}
\hline
\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\
\hline
conversion & $(n,m) \in \mathbb{N}^2$ , $id : \text{id GUI object}$  & - & - \\
\hline
\end{tabular}
\end{center}

\subsection{Semantics}

\subsubsection{State Variables}
data : object

\subsubsection{Access Routine Semantics}

\noindent conversion($n,m,id$):
\begin{itemize}
\item transition:
	\begin{enumerate}
\item store{\_}g($id$, shift, $(n,m)$)
\item
$\overrightarrow{g_{j}}_{\text{uns}}^{M_{\text{exp}}}$=load{\_}g($id$,gMuns),
$p$=load(pISMHref)
\item
store{\_}g($id$,gCuns,$\overrightarrow{g_{j}}_{\text{uns}}^{C_{\text{exp}}}$)
such that
		\begin{equation*}
		\forall \vec{r} \in \mathbb{I}, \
\overrightarrow{g_{j}}_{\text{uns}}^{C_{\text{exp}}}(\vec{r})=
\overrightarrow{g_{j}}_{\text{uns}}^{M_{\text{exp}}}(\vec{r}) + \frac{1}{p}
\times \begin{bmatrix}
	n \\
	m
	\end{bmatrix}
		\end{equation*}
		\end{enumerate}
\item exception:
\end{itemize}

\section{MIS of 2D Strain Tensor Module (\texorpdfstring{\cref{MG:M_StrainCalc}}))} \label{MIS_StrainCalc}

\noindent\textit{{\#} Module calculating the strain and rotation tensors using
two non collinear crystalline wave vectors (see \cref{SRS:R_13} in the SRS).}

\subsection{Module}
2D{\_}Strain
\subsection{Uses}
Data Structure (\cref{MG:M_DataStruct}, \cref{MIS_DataStruct})
\subsection{Syntax}

\subsubsection{Exported Access Programs}

\begin{center}
\begin{tabular}{p{3cm} p{4.5cm} p{3cm} p{3cm}}
\hline
\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\
\hline
CalcStrain & $(id:\text{id of GUI object})^{2}$  & - & MissingGInfo \\
\hline
\end{tabular}
\end{center}

\subsection{Semantics}

\subsubsection{State Variables}
data : object

\subsubsection{Access Routine Semantics}

\noindent CalcStrain($id1,id2$):
\begin{itemize}
\item transition:
\begin{enumerate}
\item Load the variables from the data structure
	\begin{itemize}
	\item $g_{1_{{\text{uns}}}}^{C_{\text{exp}}}$ = load{\_}g($id1$, gCuns)
	\item $\Delta g_{1_{{\text{uns}}}}^{C_{\text{exp}}}$ = load{\_}g($id1$,
deltagM)
	\item $g_{2_{{\text{uns}}}}^{C_{\text{exp}}}$ = load{\_}g($id2$, gCuns)
	\item $\Delta g_{2_{{\text{uns}}}}^{C_{\text{exp}}}$ = load{\_}g($id2$,
deltagM)
	\end{itemize}
\item Form ${{G_{\text{uns}}^{\text{exp}}}}$ and $\Delta G^{\text{exp}}$
matrices such that
\begin{equation*}
\begin{gathered}
G_{\text{uns}}^{\text{exp}} =
	\begin{bmatrix}
	g_{1_{{\text{uns}}_x}}^{C_{\text{exp}}} &
g_{2_{{\text{uns}}_x}}^{C_{\text{exp}}} \\
	g_{1_{{\text{uns}}_y}}^{C_{\text{exp}}} &
g_{2_{{\text{uns}}_y}}^{C_{\text{exp}}}
	\end{bmatrix}, \
\Delta G^{\text{exp}}(\vec{r})=
	\begin{bmatrix}
	\Delta g_{1_{x}}^{C_{\text{exp}}} & \Delta g_{2_{x}}^{C_{\text{exp}}}\\
	\Delta g_{1_{y}}^{C_{\text{exp}}} & \Delta g_{2_{y}}^{C_{\text{exp}}}
	\end{bmatrix}
\end{gathered}
\end{equation*}
\item Calculate $\nabla u^{\text{exp}}$ such that
\begin{equation*}
\nabla u^{\text{exp}} = ({[{G_{\text{uns}}^{\text{exp}}}+\Delta
G^{\text{exp}}}]^{T})^{-1}{{G_{\text{uns}}^{\text{exp}}}}^{T}-I_{d}
\end{equation*}
\item Calculate $\varepsilon^{\text{exp}}$ and $\omega^{\text{exp}}$
\begin{equation*}
\begin{gathered}
\varepsilon^{\text{exp}} = \frac{1}{2}(\nabla u^{\text{exp}}+(\nabla
u^{\text{exp}})^{T})= \begin{bmatrix}
	\varepsilon_{\mathit{xx}} & \varepsilon_{\mathit{xy}} \\
	\varepsilon_{\mathit{xy}} & \varepsilon_{\mathit{yy}}
	\end{bmatrix} \\
\omega^{\text{exp}} = \frac{1}{2}(\nabla u^{\text{exp}}-(\nabla
u^{\text{exp}})^{T})= \begin{bmatrix}
	0 & \omega_{\mathit{xy}} \\
	-\omega_{\mathit{xy}} & 0
	\end{bmatrix}
\end{gathered}
\end{equation*}
\item store(Exx,$\varepsilon_{\mathit{xx}}$),
store(Eyy,$\varepsilon_{\mathit{yy}}$), store(Exy,$\varepsilon_{\mathit{xy}}$),
store(Rxy,$\omega_{\mathit{xy}}$)
\end{enumerate}
\item exception:\newline
$(g_{1_{{\text{uns}}}}^{C_{\text{exp}}}=\emptyset \vee
g_{2_{{\text{uns}}}}^{C_{\text{exp}}}=\emptyset \vee \Delta
g_{1_{{\text{uns}}}}^{C_{\text{exp}}}=\emptyset \vee \Delta
g_{2_{{\text{uns}}}}^{C_{\text{exp}}}=\emptyset) \Rightarrow
\text{MissingGinfo}$
\end{itemize}

\section{MIS of Fourier Transform Module (\texorpdfstring{\cref{MG:M_FT}}))}
\label{MIS_FT}
\textit{{\#} 2D Fourier transform}
\subsection{Module}
FTCalc
\subsection{Uses}
None
\subsection{Syntax}

\subsubsection{Exported Access Programs}

\begin{center}
\begin{tabular}{p{2cm} p{4cm} p{4cm} p{3cm}}
\hline
\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\
\hline
$\mathcal{FT}$ & $f:\mathbb{R}^2\rightarrow\mathbb{R}$ &
$f:\mathbb{R}^2\rightarrow\mathbb{C}$ & - \\
i$\mathcal{FT}$ & $f:\mathbb{R}^2\rightarrow\mathbb{C}$ &
$f:\mathbb{R}^2\rightarrow\mathbb{R}$ & - \\
\hline
\end{tabular}
\end{center}

\subsection{Semantics}

\subsubsection{State Variables}
None

\subsubsection{Access Routine Semantics}

\noindent\textit{{\#} Calculate the 2D Fourier transform of a function $f$}
\medskip

\noindent $\mathcal{FT}$($f(x,y)$):
\begin{itemize}
\item output: $\widetilde{f}(\nu,\mu)$ such that
\begin{equation*}
\forall (\nu,\mu) \in \mathbb{R}^2 \wedge \forall (x,y) \in \mathbb{R}^2, \
\widetilde{f}(\nu,\mu)=\int_{-\infty}^{\infty}\int_{-\infty}^{\infty}f(x,y)e^{-2i\pi(\nu
x+\mu y)}dxdy
\end{equation*}
\item exception:
\end{itemize}

\noindent\textit{{\#} Calculate the 2D inverse Fourier transform of a function
$\widetilde{f}$}\medskip

\noindent i$\mathcal{FT}$($\widetilde{f}(\nu,\mu)$):
\begin{itemize}
\item output: $f(x,y)$ such that
\begin{equation*}
\forall (x,y) \in \mathbb{R}^2 \wedge \forall (\nu,\mu) \in \mathbb{R}^2 , \
f(x,y)=\int_{-\infty}^{\infty}\int_{-\infty}^{\infty}\widetilde{f}(\nu,\mu)e^{2i\pi(\nu
x+\mu y)}dxdy
\end{equation*}
\item exception:
\end{itemize}

\section{MIS of Gradient Module (\texorpdfstring{\cref{MG:M_Gradient}}))}
\label{MIS_Gradient}

\textit{{\#} 2D Gradient} \medskip

\subsection{Module}
GradCalc
\subsection{Uses}
None
\subsection{Syntax}

\subsubsection{Exported Access Programs}
\begin{center}
\begin{tabular}{p{2cm} p{4cm} p{4cm} p{3cm}}
\hline
\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\
\hline
grad & $f:\mathbb{R}^2\rightarrow\mathbb{R}$  &
$f:\mathbb{R}^2\rightarrow\mathbb{R}^2$ & -\\
\hline
\end{tabular}
\end{center}

\subsection{Semantics}

\subsubsection{State Variables}
None

\subsubsection{Access Routine Semantics}

\noindent\textit{{\#} Calculate the gradient of a 2D function $f$.} \medskip

\noindent grad($f$):
\begin{itemize}
\item output:$ \nabla f(x,y)$ such that
\begin{equation*}
\forall (x,y) \in \mathbb{R}^2, \ \nabla f(x,y) = \begin{bmatrix}
\frac{\partial f}{\partial x}(x,y) \\
\frac{\partial f}{\partial y}(x,y)
\end{bmatrix}
\end{equation*}
\item exception:
\end{itemize}

\section{MIS of Least Square Fit Method Module
(\texorpdfstring{\cref{MG:M_LSFM}}))} \label{MIS_LSFM}

\textit{{\#} 2D linear least square method to fit a function $f$.} \medskip

\subsection{Module}
LSFMCalc
\subsection{Uses}
None
\subsection{Syntax}

\subsubsection{Exported Access Programs}

\begin{center}
\begin{tabular}{p{2cm} p{4cm} p{4cm} p{3cm}}
\hline
\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\
\hline
lsfm & $f:\mathbb{R}^2\rightarrow\mathbb{R}^2$, $U \in \mathbb{R}^2$ &
$f:\mathbb{R}^2\rightarrow\mathbb{R}^2$ & - \\
\hline
\end{tabular}
\end{center}

\subsection{Semantics}

\subsubsection{State Variables}
None

\subsubsection{Access Routine Semantics}

\noindent\textit{{\#} Calculate the 2D fit of a function $f$ using the linear
least square method on a domain $U=([x_0,x_1];[y_0,y_1]) \in \mathbb{R}^2$.}
\medskip

\noindent lsfm(f,U):
\begin{itemize}
\item output: $fit(x,y)=ax + by$ such that
\begin{equation*}
\begin{gathered}
\forall (x,y) \in U, \
E(a,b)=\int_{x_0}^{x_1}\int_{y_0}^{y_1}[f(x,y)-fit(x,y)]^2dxdy \ \ \text{is
minimized} \\
\Rightarrow \frac{\partial E}{\partial a} =0 \wedge \frac{\partial E}{\partial
b} =0
\Rightarrow a =
\frac{\int_{x_0}^{x_1}\int_{y_0}^{y_1}xf(x,y)dxdy}{\int_{x_0}^{x_1}\int_{y_0}^{y_1}x^2dxdy}
\wedge  b=
\frac{\int_{x_0}^{x_1}\int_{y_0}^{y_1}yf(x,y)dxdy}{\int_{x_0}^{x_1}\int_{y_0}^{y_1}y^2dxdy}
\end{gathered}
\end{equation*}
\item exception:
\end{itemize}

\section{MIS of Phase Operation Module (\texorpdfstring{\cref{MG:M_Phase}}))}
\label{MIS_Phase}

\noindent\textit{{\#} Module embedding a few functions to make possible some
mathematical operations on the phase (parameter bound between $]-\pi,\pi]$).}
\medskip

\subsection{Module}
PhaseCalc
\subsection{Uses}
None
\subsection{Syntax}

\subsubsection{Exported Access Programs}

\begin{center}
\begin{tabular}{p{2cm} p{4cm} p{4cm} p{3cm}}
\hline
\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\
\hline
unwrap & $f:\mathbb{R}^2\rightarrow]-\pi,\pi]$ &
$f:\mathbb{R}^2\rightarrow\mathbb{R}$ & NotPhase  \\
wrap & $f:\mathbb{R}^2\rightarrow\mathbb{R}$ &
$f:\mathbb{R}^2\rightarrow]-\pi,\pi]$ & - \\
arg & $z \in \mathbb{C}$ & $\phi \in ]-\pi,\pi]$ &  - \\
\hline
\end{tabular}
\end{center}

\subsection{Semantics}

\subsubsection{State Variables}
None

\subsubsection{Access Routine Semantics}

\noindent wrap($f$):
\begin{itemize}
\item output: $g$ such that
\begin{equation*}
\forall (x,y) \in \mathbb{R}^2, \exists k \in \mathbb{Z} | g(x,y) =f(x,y)+ 2k\pi
\wedge g(x,y) \in ]-\pi,\pi]
\end{equation*}
\item exception:\newline
$(\exists (x_0,y_0) \in \mathbb{R}^2 : f(x_0,y_0) \notin ]-\pi,\pi])\Rightarrow
\text{BadPhase}$
\end{itemize}

\noindent unwrap($f$):
\begin{itemize}
\item output: $g$ such that
\begin{equation*}
\begin{gathered}
\forall (x,y) \in \mathbb{R}^2, \exists k \in \mathbb{Z} | g(x,y) =f(x,y) +
2k\pi \wedge g \ \text{is} \  \text{continous}\\
\Rightarrow \forall (x,y) \in \mathbb{R}^2, \exists k \in \mathbb{Z} |
\lim_{(x,y)\to (x_0,y_0)} g(x,y) = g(x_0,y_0) = f(x_0,y_0) + 2k\pi
\end{gathered}
\end{equation*}
\item exception:
\end{itemize}

\noindent arg($z$):
\begin{itemize}
\item output: $\phi$ such that
\begin{equation*}
\phi=\text{arg}(z) \text{ with } z=e^{i\phi}
\end{equation*}
\item exception:
\end{itemize}

\section{MIS of Data Structure Module
(\texorpdfstring{\cref{MG:M_DataStruct}}))} \label{MIS_DataStruct}

\wss{The role of your data structure module isn't entirely clear to me.  Many of
  your modules have a data object as a state variable.  As far as I can tell,
  each module only changes a few of the fields of the data object.  I don't see
  a way to access the state variable data from outside the modules.  For
  instance, the 2D\_Strain module calculates the strain and modifies the data
  object, but the external world doesn't have an interface to actually get the
  values from the data object.  Should your data object actually be a parameter
  that is passed between modules?  You have documented data as an abstract
  object, not an ADT, so this implies to me that there is only one data object
  for the life of your program.  If this is the case, then you probably want to
  remove data as a state variable.  The modules can change the state of the one
  data object and anyone that needs to can read and write the data fields, as
  appropriate.}

\subsection{Module}
DataStruct
\subsection{Uses}
None
\subsection{Syntax}

\subsubsection{Exported Access Programs}

\begin{center}
\begin{tabular}{p{3cm} p{4cm} p{3cm} p{3cm}}
\hline
\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\
\hline
store & string $\times$ object & - & - \\
read & string & object & - \\
store{\_}g & id GUI object $\times$ string $\times$ object & - & - \\
read{\_}g & id GUI object $\times$ string & object & - \\
\hline
\end{tabular}
\end{center}

\wss{I think in your spec  you changed read to load.}

\subsection{Semantics}

\subsubsection{State Variables}

\noindent\textit{{\#} Structure of the object carrying the data
information.}\medskip

data : object
\begin{itemize}
\item
data(ISMHexp)=$I_{\mathit{SMH}_{\text{exp}}}:\mathbb{I}\rightarrow\mathbb{R}$
\item data(pISMHexp)= $p \in \mathbb{R}^{+*}$
\item data(ICref)=$I_{\mathit{C}_{\text{ref}}}:\mathbb{I}\rightarrow\mathbb{R}$
\item data(pICref)=$p_{\text{ref}} \in \mathbb{R}^{+*}$
\item
data(FTISMHexp)=$\widetilde{I}_{\mathit{SMH}_{\text{exp}}}:\mathbb{I}\rightarrow\mathbb{C}$
\item
data(FTISMHsim)=$\widetilde{I}_{\mathit{SMH}_{\text{sim}}}:\mathbb{I}\rightarrow\mathbb{C}$
\item data(URef)=$U \subset \mathbb{I}$
\item for each $j=\{1,2\}$ data(M$j$) : object
	\begin{itemize}
	\item data(M$j$)(mask)=$x_c,y_c,R \in
\mathbb{N}\times\mathbb{N}\times\mathbb{R}^{+*}$
	\item
data(M$j$)(gMuns)=$\overrightarrow{g_{j}}_{\text{uns}}^{M_{\text{exp}}}:\mathbb{I}\rightarrow\mathbb{R}^2$
	\item data(M$j$)(deltagM)=$\Delta
\overrightarrow{g_{j}}^{M_{\text{exp}}}:\mathbb{I}\rightarrow\mathbb{R}^2$
	\item data(M$j$)(PhasegM)=$P_{\Delta
\overrightarrow{g_{j}}^{M_{\text{exp}}}}:\mathbb{I}\rightarrow\mathbb{R}$
	\item data(M$j$)(shift)=$(n_j,m_j)\in\mathbb{N}^2$
	\item
data(M$j$)(gCuns)=$\overrightarrow{g_{j}}_{\text{uns}}^{C_{\text{exp}}}:\mathbb{I}\rightarrow\mathbb{R}^2$
	\end{itemize}
\item data(Exx)=$\varepsilon_{\text{xx}}:\mathbb{I}\rightarrow\mathbb{R}$
\item data(Eyy)=$\varepsilon_{\text{yy}}:\mathbb{I}\rightarrow\mathbb{R}$
\item data(Exy)=$\varepsilon_{\text{xy}}:\mathbb{I}\rightarrow\mathbb{R}$
\item data(Rxy)=$\omega_{\text{xy}}:\mathbb{I}\rightarrow\mathbb{R}$
\end{itemize}

\subsubsection{Access Routine Semantics}

\noindent store($a$,$b$):
\begin{itemize}
\item transition: data($a$)=$b$
\end{itemize}

\noindent load($a$):
\begin{itemize}
\item output: data($a$)
\end{itemize}

\noindent store{\_}g($id$,$a$,$b$):
\begin{itemize}
\item transition: data($id$)($a$)=$b$
\end{itemize}

\noindent load{\_}g($id$,$a$):
\begin{itemize}
\item output: data($id$)($a$)
\end{itemize}

\section{MIS of Generic GUI/Plot Module (\texorpdfstring{\cref{MG:M_GUIGene}}))}
\label{MIS_GUIGene}

\an{The description of this module is pretty sparse ... I didn't want to go
through all the possible interaction a GUI and a plotter can do. I also think
that it is not the major element for the course. On the other hand, a nice GUI
makes lots of difference from the user perspective.}

\subsection{Module}
GUIGene
\subsection{Uses}
Hardware-Hiding (\cref{MG:M_Hardware})
\subsection{Syntax}

\subsubsection{Exported Access Programs}

\begin{center}
\begin{tabular}{p{3cm} p{4cm} p{4cm} p{3cm}}
\hline
\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\
\hline
plot & GUI objects & - & - \\
fig & string $\times$ GUI objects &  GUI object & - \\
button & $k \in \mathbb{N}$ , {string}$^{k}$ &  GUI object & - \\
entry{\_}field & string &  GUI object & - \\
circle & - &  GUI object & - \\
rectangle & - & GUI object & - \\
read{\_}user{\_}GUI & GUI object & object \\
\hline
\end{tabular}
\end{center}

\subsection{Semantics}

\subsubsection{State Variables}
None

\subsubsection{Access Routine Semantics}

\noindent plot():
\begin{itemize}
\item output: Display on the Hardware all the GUI objects.
\end{itemize}

\noindent fig('label', optional GUI objects):
\begin{itemize}
\item output: Create a window GUI object with the optional GUI objects.
\end{itemize}

\noindent button($number$,'labels'):
\begin{itemize}
\item output: Create $number$ buttons GUI objects with their respective
'labels'.
\end{itemize}

\noindent entry{\_}field($b$):
\begin{itemize}
\item output: Create a entry field GUI object to collect the input $b$ from the
user.
\end{itemize}

\noindent circle($C$(user{\_}param)):
\begin{itemize}
\item output: Create a circle $C$ GUI object drawn by the user.
\end{itemize}

\noindent rectangle($R$(user{\_}param)):
\begin{itemize}
\item output: Create a rectangle $R$ GUI object drawn by the user.
\end{itemize}

\noindent read{\_}user{\_}GUI($A$):
\begin{itemize}
\item output:  $B$ such that B includes the id of the GUI and the type of the
GUI.
\end{itemize}
\bigskip

\iffalse
\section{MIS of Navigation Mask Module (\texorpdfstring{\cref{MG:M_GUIInputVerif}}))} \label{MIS_GUIInputVerif}

\an{Module to allow the user to select a specific mask to perform the calculation on this specific mask. NEED TO THINK ABOUT IT FIRST.}

\subsection{Module}
GUIInputVerif
\subsection{Uses}
\item STEM Moir{\'e} GPA GUI (\cref{MG:M_GUISMG}, \cref{MIS_GUISMG})
\subsection{Syntax}

\subsubsection{Exported Access Programs}

\begin{center}
\begin{tabular}{p{3cm} p{4cm} p{4cm} p{3cm}}
\hline
\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\
\hline
blabla & - & - & - \\
\hline
\end{tabular}
\end{center}

\subsection{Semantics}

\subsubsection{State Variables}

MaskList

\subsubsection{Access Routine Semantics}
\noindent blabla():
\begin{itemize}
\item output:
\end{itemize}

\fi

\wss{Great work!  I do not have the time (or the expertise) to review the
  details, but everything I looked at had the required detail and the pieces fit
  together.  My only real question is about the data object, as mentioned above
  (in Section 19).  It would be great to do a proper review of the pieces of
  your design with an actual expert.  If there is anyone in your lab that has an
  interest, you might want to get their feedback.}

\newpage

\bibliographystyle{ieeetr}
\bibliography{MIS}

\wss{Missing bib items}

\end{document}


\input{latex-report/include/header}

%%% include custom packages here
% \usepackage{..}

%%% meta data and settings
\newcommand{\lrTitle}{Report Title}
\newcommand{\lrAuthor}{Report Author}
\newcommand{\lrDate}{\today}

% \toggletrue{lrHideToc}
% \toggletrue{lrHideTitle}
% \toggletrue{lrSmallHeadings}
% \toggletrue{lrHeaderDate}

\begin{document}

\section{First section}
Some text and an important definition
\begin{align}
    f(x) = 42 + \integralb{0}{x}{s} g(s)
\end{align}
where $g(s)=a \bb{1 + \ef{i s}}$.

\subsection{First subsection}
And some more text.

\end{document}


\documentclass{article}%
\usepackage[T1]{fontenc}%
\usepackage[utf8]{inputenc}%
\usepackage{lmodern}%
\usepackage{textcomp}%
\usepackage{lastpage}%
%
\input{common_symbols_and_format.tex}%
\usepackage{tocloft}%
\renewcommand{\cfttoctitlefont}{\Large\bfseries}%
%
\begin{document}%
\normalsize%
\logo%
\rulename{Rolling Difference Regression}%
\tableofcontents%

\newpage

\ruledescription{Regresses the one-day price changes against the \% gap between the research value and the price value. Assuming the regression gives a positive relationship the strategy takes bigger positions when the research is higher than the price series.}%

\howtotrade
{In order to trade with the rules InferTrade provides, we calculate allocations for each day. We then allocate that fraction of our total portfolio value (cash and securities) to the market we are trading - to do this we buy or sell securities to reach the target allocation.}%
{
\begin{figure}[H]
\begin{multicols}{2}
  \centering
    \begin{subfigure}{\linewidth}
        \includegraphics[width=\linewidth]{\graphdir{market.png}}
        \caption{Market series data}
        \label{fig:01}
    \end{subfigure}
  \par
  \vspace{5mm}
  \begin{subfigure}{\linewidth}
    \includegraphics[width=\linewidth]{\graphdir{research.png}}
    \caption{Research series data}
    \label{fig:02}
  \end{subfigure}
  \par
  \begin{subfigure}{\linewidth}
    \includegraphics[width=\linewidth]{\graphdir{pa(RollingDifferenceRegression).png}}
    \caption{ Suggested volume to buy or sell}
    \label{fig:03}
  \end{subfigure}
  \par
  \vspace{5mm}
  \begin{subfigure}{\linewidth}
    \includegraphics[width=\linewidth]{\graphdir{pr(RollingDifferenceRegression).png}}
    \caption{Portfolio return}
    \label{fig:04}
  \end{subfigure}
  \end{multicols}
  \caption{Graphical depiction of the Rolling Difference Regression algorithm. 20 Days of trading data is visualized in the graphs (\ref{fig:01}) A line chart showing changes in the market price for multiple trading days.(\ref{fig:02}) A chart displaying the research series data. (\ref{fig:03})Positive values indicate that buying the security by x\%. The negative values mean you are shorting the security by x\% (\ref{fig:04})Chart showing the portfolio return when using the Rolling Difference Regression as the trading rule.}
  \label{fig:cps_graph}
\end{figure}
}

\ruleparameters{Kelly Fraction}{0.1}{Amplitude weighting. 1.0 is maximum growth if regression is exact. <1.0 scales down positions taken.}{Symbol}{Regression Length}{50}{This is the number of days used to estimate the regression coefficients.}{Symbol}%
\stoptable

\section{Equation}
The following equations describe the rolling level rule:

\begin{equation}
    \regressionprice_\currenttime= \amplitudecoefficient(\research_\currenttime-P_\currenttime) + \constantc
\end{equation}

\begin{equation}
    \position_\currenttime = \kellyfraction \frac{\regressionprice_\currenttime}{ \rmserror_{\regressionprice}^{2}}
\end{equation}

\hspace{200mm}
\\

where

$\research_\currenttime$: is the value of the research series.

$\regressionprice_\currenttime$: is the predicted price at time $\currenttime$

$\rmserror_\regressionprice$: is the standard error.

$\kellyfraction$: is the Kelly Fraction.

$\position$: is the resultant fractional portfolio investment.

\hspace{200mm}
\hspace{200mm}

\assumptions%
\keyterms%
\furtherlinks%
\end{document}


\title{Sample lecture}
\subtitle{Prime numbers and Euler's identity}
\date{\today}
\author{John Doe, Ph.D.}
\institute{%
University of Scholastics\\%
Department of \LaTeX\ Studies\\%
\par%
LS101\\%
Lecture Preparation with Beamer}

\graphicspath{{./graphics/}}

\titlegraphic{\includegraphics[width=2.5cm]{logo.png}}

\mode<article>{\lecturenumber{1}}

\begin{document}

\maketitle

\mode*  % ignore text outside frame in presentation mode

This is your lecture abstract. It should contain a short description of the lecture contents, what its goals are, and preferably not exceed a few dozen words.\marginnote{Do not forget to use margin notes to add more context to your material.}

\section{The largest prime number}

\begin{frame}
  \begin{theorem}
    There is no largest prime number.
  \end{theorem}%
  \pause
  \mode<article>{The proof uses reductio ad absurdum. Although this comment is inside a \texttt{beamer} frame, it only appears in the handout.}
  \begin{block}{Proof}
    \begin{enumerate}
      \item<alert@2> Suppose $p$ were the largest prime number.
      \item<alert@3> Let $\Pi$ be the product of the first $p$ primes.
      \item<alert@4> Then $\Pi + 1$ is not divisible by any prime.
      \item<alert@5> Therefore, $\Pi + 1$ is also a prime. \qedhere
    \end{enumerate}
  \end{block}
\end{frame}

You should restrain references to the bibliography outside frame environments, e.g.~\citet{newton1687} states that ``when arithmetical addition has been defined [it follows that] 1 + 1 = 2.''\cite{newton1687}

\section{The most beautiful equation}

\begin{frame}{Euler's identity}
  \begin{equation}
    e^{i\pi} + 1 = 0
  \end{equation}
\end{frame}

\begin{frame}<beamer>[standout]
  Thank you.
\end{frame}

\bibliographystyle{plainnat}
\bibliography{references}

\end{document}


\section{River at rest with varying width and topography}

This is a test if the method is well-balanced. Furthermore, we test if the wet/dry interface has been correctly treated for steep river banks. This test is taken from the work of Goutal and Maurel~\cite{GM1997}.

The initial condition is a river at rest with water depth $12.0$. Boundary conditions are solid wall. The width and topography of the river are defined as piecewise linear interpolations of the data presented in Table~\ref{tab:width_topo}.
\begin{table}
	\centering
	\caption{River width and topography (see Goutal and Maurel~\cite{GM1997}).}
	\begin{tabular}{c|c|c}	\hline
	$x$&      topography  & width                                                       \\	\hline \hline
0 &0& 40 \\
50 &0& 40\\
100 &2.5& 30\\
150 &5& 30\\
250 &5& 30\\
300 &3& 30\\
350 &5& 25\\
400 &5& 25\\
425 &7.5& 30\\
435 &8& 35\\
450 &9& 35\\
470 &9& 40\\
475 &9& 40\\
500 &9.1& 40\\
505 &9& 45\\
530 &9& 45\\
550 &6& 50\\
565 &5.5& 45\\
575 &5.5& 40\\
600 &5& 40\\
650 &4& 30\\
700 &3& 40\\
750 &3& 40\\
800 &2.3& 5\\
820 &2& 40\\
900 &1.2& 35\\
950 &0.4& 25\\
1000 &0& 40\\
1500 &0& 40 \\ \hline
	\end{tabular}

	\label{tab:width_topo}
\end{table}
The analytical solution is the river at rest, that is, $w=12.0$ and $u=v=0$.

\subsection{Results}

Old versions of \anuga{} might not treat the wet/dry interface appropriately,
but the discontinuous-elevation and tsunami algorithms should do this
correctly. The following figures show the stage, $x$-momentum, and $x$-velocity
respectively, after we run the simulation for some time. The first three show a
slice in the x direction (down the river) and the last three figures show a
cross section across the river. We should see excellent agreement between the
analytical and numerical solutions if the method is well-balanced and if the
wet/dry interface has been correctly treated. Note the scale of the figures
(since in cases that are accurate to numerical precision, the figure scale will
only vary over a tiny range).

\begin{figure}
\begin{center}
\includegraphics[width=0.9\textwidth]{stage_plot.png}
\end{center}
\caption{Stage results down the river}
\end{figure}

\begin{figure}
\begin{center}
\includegraphics[width=0.9\textwidth]{xmom_plot.png}
\end{center}
\caption{Xmomentum results down the river}
\end{figure}

\begin{figure}
\begin{center}
\includegraphics[width=0.9\textwidth]{xvel_plot.png}
\end{center}
\caption{Xvelocity results down the river}
\end{figure}

\begin{figure}
\begin{center}
\includegraphics[width=0.9\textwidth]{stage_plot_y.png}
\end{center}
\caption{Stage results across the river}
\end{figure}

\begin{figure}
\begin{center}
\includegraphics[width=0.9\textwidth]{xmom_plot_y.png}
\end{center}
\caption{Xmomentum results across the river}
\end{figure}

\begin{figure}
\begin{center}
\includegraphics[width=0.9\textwidth]{xvel_plot_y.png}
\end{center}
\caption{Xvelocity results accros the river}
\end{figure}

\endinput