\chapter{Methods}
\subsection{Fetching the data}
The raw material of this thesis is coming from the \textit{International Association of Analysts}. Thirteen magmatic rocks were analyzed by approximately a hundred laboratories.

We began by converting the datasets in a clean $n\times p$ matrix :
\begin{align} \label{matrix}
X_{n,p} =
\begin{pmatrix}
x_{1,1} & x_{1,2} & \cdots & x_{1,p} \\
x_{2,1} & x_{2,2} & \cdots & x_{2,p} \\
\vdots  & \vdots  & \ddots & \vdots  \\
x_{n,1} & x_{m,2} & \cdots & x_{n,p}
\end{pmatrix}
\end{align}
With $n$ the number of laboratories which analyzed the rock sample, for January 2020, $n$ was 119. $p$ is the number of chemical elements found in the sample. Theoretically, $p$ can be as large as 94, the number of naturally-occurring chemical elements. In practice, the size of the database is approximately 60 (rocks) x 30 (elements) x 100 (labs).
\subsection{Filling missing-values}
We start by using the expectation-maximization algorithm.


In this chapter, we define the actual event detection algorithm. First, we describe the original method used by \cite{event-detection}. Then, we make a change to incorporate semantic similarity through the word embeddings obtained in \autoref{chap:data-preprocessing}. Finally, we introduce an alternative algorithm that utilizes word clustering using a custom distance function.

The original algorithm creates events as sets of related keywords by greedily minimizing a cost function combining temporal and semantical distance between words. However, the paper used only a simple notion of semantical distance, namely the document overlap between words. This demands that there exists at least one document containing all the words used to represent an event. This is a strong requirement, since the documents may use different vocabularies while conveying similar information.  As a result, the events are split into multiple keyword sets, leading to redundancy.

In an attempt to solve this problem, we modify the cost function, replacing the document overlap by a Word2Vec-based similarity. This does not require the words to appear in exactly the same documents, only that they have similar semantics. We refer to this method as \textit{embedded greedy approach}, as it is a modification to make the original greedy algorithm utilize word embeddings.

Realizing that the task of constructing keyword sets resembles the task of word clustering, we propose an alternative algorithm. Here, we apply a clustering algorithm to the words, using a modification of the cost function as a distance measure. This is a method referred to as \textit{cluster-based approach}.

First, we briefly describe the original method for reference. This will make it clear which parts of the function we modify. It will also allow us to make reference to the original method in \autoref{chap:evaluation}, where we compare all three algorithms.

\section{Original method}
As stated in the introduction, the original method performs greedy minimization of a cost function defined over sets of words. The cost function consists of trajectory distance measuring the word distance in temporal domain, and document overlap, standing for distance in the semantic domain. We first describe these two components and then combine them into the cost function.

\subsection{Trajectory distance}
Before measuring the trajectory distance, the trajectories are smoothened by fitting a probability density function to them. We adapt a similar technique in \autoref{chap:document-retrieval} where it is described in more detail. Our event detection modifications do not use the original smoothing though, and we refer the reader to the original paper for more details.

After normalization to unit sum, the (smoothened) trajectory $\vect{\trajn}_{w}$ of a word $w$ can be interpreted as a probability distribution over the stream days. The element $\trajn_{w}(i)$ then denotes the probability that $w$ appears in a random document published on day $i$. This interpretation allows to compare the trajectories using information-theoretic techniques, notably the information divergence \citep{information-theory}.

In the original paper, the authors first defined the distance between trajectories of two words $v$ and $w$ as $\trajdist{\vect{\trajn}_{v}}{\vect{\trajn}_{w}} = \max \left\{ \kl{\vect{\trajn}_{v}}{\vect{\trajn}_{w}}, \kl{\vect{\trajn}_{w}}{\vect{\trajn}_{v}} \right\}$, symmetrizing the Kullback-Leibler divergence KL \citep{kl-divergence}.

Then, the distance is generalized to a whole set of words $\featset$ as

\begin{equation} \label{eq:trajectory-distance}
	\text{Dist}( \featset ) = \max_{v, w \in \featset} \trajdist{\vect{\trajn}_{v}}{\vect{\trajn}_{w}}.
\end{equation}

\subsection{Document overlap}
The document overlap is again first defined for a pair of words $v$ and $w$ as $\text{DO}\left( v, w \right) = \frac{| \featset_{v} \cap \featset_{w} |}{\min \left\{ | \featset_{v} |, | \featset_{w} | \right\}}$, where $\featset_{j} = \{ i \mid \bowmat_{ij} = 1 \}$ is the set of all documents containing the word $j$. The higher the document overlap, the more documents do the two words have in common, which makes them more likely to be correlated.

The overlap is again generalized to a set of words $\featset$ as

\begin{equation} \label{eq:document-overlap}
	\text{DO}( \featset ) = \min_{v, w \in \featset} \text{DO}( v, w ).
\end{equation}

\subsection{Cost function}
The cost function is a combination of the trajectory distance and document overlap of a set of words $\featset$. It is defined as

\begin{equation} \label{eq:cost-function-original}
	\text{C}( \featset ) = \frac{\text{Dist}( \featset )}{\text{DO}( \featset ) \cdot \sum_{w \in \featset} \text{DPS}_{w}}.
\end{equation}

Since the algorithm attempts to minimize it, the intuitive result is a set of words with low trajectory distance and high document overlap. The algorithm will also prefer words of higher importance due to the last term of the denominator, counting in the power spectra.

\subsection{Event detection algorithm}
The algorithm, called \textit{unsupervised greedy event detection algorithm} in the original paper, produces events as structured objects $e$ consisting of:

\begin{itemize}
	\item $\kw{e}$: The event keyword set.
	\item $\doc{e}$: Documents concerning the event.
	\item $\bursts{e}$: Bursty periods of the event.
	\item $\domper{e}$: Dominant period of the event.
	\item $\annot{e}$: Human-readable annotation of the event.
\end{itemize}

Only the event keyword set $\kw{e}$ is initialized in this section. The other fields will be properly defined and filled in the rest of the thesis.

The algorithm itself is defined as follows:

\begin{algorithm}[H]
\begin{algorithmic}[1]
\caption{Unsupervised greedy event detection}
\label{alg:greedy-event-detection}
\Input $\text{Word set} ~ \text{EW obtained in \autoref{chap:word-analysis}, matrices } \bowmat \text{ and }\trajmat \text{, word DPS}$

\State $\text{Sort the words in descending DPS order: } \text{DPS}_{w_{1}} \geq \dots \geq \text{DPS}_{w_{\left\vert \text{EW} \right\vert}}$

\State $k = 0$

\ForEach{$w \in \text{EW}$}
	\State $k = k + 1$
	\State $\kw{e_{k}} = \{ w \}$
	\State $cost_{e_{k}} = \frac{1}{DPS_{w}}$
	\State $\text{EW} = \text{EW} \setminus w$

	\While{$\text{EW} \neq \emptyset$}
		\State $m = \argmin\limits_{m}{\text{C}( \kw{e_{k}} \cup w_{m} )}$

		\If{$\text{C}( \kw{e_{k}} \cup w_{m} ) < cost_{e_{k}}$}
			\State $cost_{e_{k}} = \text{C}( \kw{e_{k}} \cup w_{m} )$
			\State $\kw{e_{k}} = \kw{e_{k}} \cup w_{m}$
			\State $\text{EW} = \text{EW} \setminus w_{m}$
		\Else
			\Break
		\EndIf
	\EndWhile
\EndFor

\Output $\text{Events} ~ \{ e_{1}, \dots, e_{k} \}$
\end{algorithmic}
\end{algorithm}

The algorithm works by greedily minimizing the cost function \eqref{eq:cost-function-original}. Once it is minimized, an event is produced, consisting of all the words found since last event.

The words are sorted in descending DPS order before entering the minimization loop, so that the most important words are processed first. This assures that the most eventful words are assigned together, without wasting them to appear with low quality words.

\cite{event-detection} did not provide the time complexity of the algorithm, which we attempt to estimate now. The execution time is dominated by the main loop on lines 3 through 18. The outer loop must execute $\mathcal{O}(|\text{EW}|)$ times. In each of the iterations, the inner loop is executed at most $|\text{EW}|$ times, making it $\mathcal{O}(|\text{EW}|)$ as well. The argmin statement on line 9 must search through the whole remaining $|\text{EW}|$ words, also making it run $\mathcal{O}(|\text{EW}|)$ times.

If the number of eventful words is low enough, the pairwise trajectory distance and document overlap can be precomputed. This makes the cost function take $\mathcal{O}(|\text{M}|^{2})$ time when applied to a set M. If the distances are not precomputed, the cost function execution requires $\mathcal{O}(|\text{M}|^{3})$ time.

We were unable to precisely determine the cost function's complexity with respect to the set EW, as it is always applied on the currently composed event. However, during our experiments, the number of words comprising an event never exceeded 10 in the original method. This makes the cost function's asymptotic complexity negligible compared to the main loop.

The resulting complexity of the algorithm is therefore $\mathcal{O}(|\text{EW}|^{3} \cdot c)$, where $c$ is the complexity of the cost function.

In \autoref{fig:original-event}, we show an example of an event detected by the original method. We can see that it consists of four keywords with overlapping trajectories, sharing a common burst of activity around day 210. The event is likely related to the tension in the Middle East, though the keywords by themselves do not allow any closer interpretation. For this reason, we provide longer annotations in \autoref{chap:event-annotation}, so that we can examine the event more closely.

\begin{figure}
  \centering
  \includegraphics{original_event}  % original event
  \caption{Example of an event detected using the original method. The event consists of the words \textit{palestinian}, \textit{israeli}, \textit{Palestinian} and \textit{Israel}, respectively.}
  \label{fig:original-event}
\end{figure}

\section{Embedded greedy approach}
In this section, we modify the original method to use the Word2Vec model to measure semantic similarity between words. Unlike the document overlap \eqref{eq:document-overlap}, this new similarity measure is able to distinguish semantically similar words even when they do not appear in the same documents. This may happen, for instance, when different authors each use distinct vocabulary when referring to the same event.

\subsection{Semantic similarity}
Some of the astounding results of the Word2Vec model arise from semantically similar words forming clusters \citep{linguistic-regularities} in terms of cosine similarity, which is a standard measure used in information retrieval \citep{information-retrieval, cosine-similarity}.

We replace the document overlap in the cost function \eqref{eq:cost-function-original} by cosine similarity between Word2Vec embeddings, though with a small modification. The cosine similarity is bounded in $[-1, 1]$ with -1 denoting the least degree of similarity. This means that the cost function would reach negative values for highly dissimilar words. This would mean a problem, as Algorithm \ref{alg:greedy-event-detection} attempts to minimize it. Consequently, we will transform the cosine similarity into $[0, 1]$, just like the document overlap \eqref{eq:document-overlap}.

The similarity between a set of words $\featset$ and a word $w \notin \featset$ is defined as

\begin{equation}
	\semsim{\featset}{w} = \left( \frac{\inp[\big]{\bar{\embed}_{\featset}}{\embed_{w}}}{\| \bar{\embed}_{\featset} \| \cdot \| \embed_{w} \|} + 1 \right) /\ 2,
\end{equation}

where $\bar{\embed}_{\featset}$ is the mean of all vector embeddings of $\featset$ and $\embed_{w}$ is the vector embedding of $w$. Here, the mean vector virtually represents the central topic of words in $\featset$.

\subsection{Cost function}
We redefine the cost function \eqref{eq:cost-function-original} as

\begin{equation} \label{eq:cost-function}
	\cost{\featset}{w} = \frac{\text{Dist}( \featset \cup w )}{\semsim{\featset}{w} \cdot \sum_{u \in \featset \cup w}{\text{DPS}_{u}}},
\end{equation}

where $\text{Dist}(\cdot)$ is the original trajectory distance function \eqref{eq:trajectory-distance}.

In the original method, \cite{event-detection} defined the cost function \eqref{eq:cost-function-original} for a set of words. However, in Algorithm \ref{alg:greedy-event-detection}, it is always applied on the union of the keywords of an event constructed so far, and a newly added word. The new cost function must now be applied on such keyword set and word separately due to the nature of Word2Vec similarity definition.

Having constructed the cost function, we use Algorithm \ref{alg:greedy-event-detection} to detect events once again.

In \autoref{fig:greedy-event}, we show an event detected using the embedded greedy method. It is related to the same real-world event as the event in \autoref{fig:original-event}, though it consists of more keywords. Generally, events detected by the embedded greedy method contain more keywords, as we will see in \autoref{tab:events-overview}. The trajectory overlap is not perfect, the burst of the word \textit{American} being off compared to the rest of the words. It is possible that the semantic similarity of the word was so high that the word was deemed relevant nonetheless.

\begin{figure}
  \centering
  \includegraphics{greedy_event}  % greedy event
  \caption{Example of an event detected using the embedded greedy method. The event consists of the words \textit{rebel, missile, Israel, israeli, American} and \textit{humanitarian}, and is related to the same real event as \autoref{fig:original-event}.}
  \label{fig:greedy-event}
\end{figure}

\section{Cluster-based approach}
Realizing that the keyword-based event detection resembles word clustering and could be solved by an application of a clustering algorithm, we decided to investigate this idea. In the final method, we apply a clustering algorithm equipped with a custom distance function to the set of eventful words. The distance function is actually a modification of the cost function yet again, though some means have to be taken to make it usable in this context. First though, we need to consider a proper clustering algorithm.

The obvious requirement for the clustering algorithm is that it must require no prior knowledge of the desired number of clusters. Another requirement is that the algorithm must accept a custom distance measure.

We considered three candidate algorithms, all satisfying these requirements: Affinity propagation \citep{affinity-propagation}, DBSCAN \citep{dbscan} and its modification, HDBSCAN \citep{hdbscan}.

During our experimentation, Affinity propagation performed poorly, its clusters being often seemingly random and of low quality. The quality of HDBSCAN clusters was considerably better, though the algorithm took longer to converge as the number of eventful words grew. It also required to tune multiple parameters, which was difficult to do without any annotated data. We decided to use the DBSCAN algorithm, which outperformed Affinity propagation as well, and does not require to tune as many parameters as HDBSCAN.

In addition to the previously stated requirements, DBSCAN is also capable of filtering out noisy samples (in our case words), not fit for any of the clusters. This property will prove advantageous for our task, as will become clear during the evaluation in \autoref{sec:noise-evaluation}.

\subsection{Noise filtering} \label{subsec:noise-filtering}
Before we apply clustering, we filter out the noisy parts from the word trajectories. Most words are on some level reported all the time, though only a fraction of these reportings corresponds to notable events. Unlike the greedy optimization described previously, clustering is prone to such noise, and would yield clusters of poor quality, often with trajectories being put together only due to their noisy parts being similar. Additionaly, with DBSCAN capable of filtering out noisy samples, some high quality words could be discarded precisely due to this noise in their (otherwise eventful) trajectories.

We want to keep only those trajectory parts exceeding a certain frequency level, distinguishing notable bursts from the general noise. We do this by computing a cutoff value for each event trajectory and discarding the sectors falling under this cutoff. This procedure is adopted from \cite{online-search-queries}. The algorithm is based on computing a moving average along the trajectory, and works as follows:

\begin{algorithm}[H]
\begin{algorithmic}[1]
\caption{Burst filtering}
\label{alg:burst-filtering}
\Input $\text{Window-length} \ l,\ \text{word trajectory} \ \vect{\traj_{w}}$

\State $\vect{MA}_{l} = \text{Moving Average of length} ~ l ~ \text{for} ~ \vect{\traj}_{w} = \left[ \traj_{w}(1), \traj_{w}(2), \dots, \traj_{w}(\streamlen) \right]$

\State $\mathit{cutoff} = \text{mean} \left( \vect{MA}_{l} \right) + \text{std} \left( \vect{MA}_{l} \right)$

\State $\vect{bursts}_{w} = \left[ \traj_{w}(t) \mid \traj_{w	}(t) > \mathit{cutoff} \right]$

\Output $\vect{bursts}_{w}$
\end{algorithmic}
\end{algorithm}

We use the window length $l = 7$, looking 1 week back in the trajectory.

\subsection{Distance function}
We now define the distance function used by DBSCAN. It conveys similar information as the cost function in the previous two algorithms. We still need to measure the trajectory distance as well as semantic similarity between words, though the distance will now be defined strictly pairwise.

For a measure of trajectory distance, we replace the Kullback-Leibler divergence by the Jensen-Shannon divergence JSD \citep{js-divergence-1}, which is symmetric in its arguments. This is a necessary property of the distance function.

Although \cite{event-detection} did symmetrize the Kullback-Leibler divergence, they did not provide any source for their symmetrization form. We were unable to find a case where that particular form was used, though we discovered the Jensen-Shannon divergence, which comes from stronger mathematical background \citep{js-divergence-1, js-divergence-2}. It also tended to improve the clustering quality during our experimentation, as opposed to the original symmetrization. We then decided to replace the original paper's KL-divergence symmetrization by the JS-divergence.

Instead of semantic \textit{similarity}, we measure semantic \textit{distance} as the Euclidean distance between two word vector embeddings. The reason is that Euclidean distance is unbounded, which makes it possible for the samples to be spread farther apart. Since DBSCAN is a density-based clustering algorithm, having high density areas consisting of words with low trajectory distance and similar cosine similarities would cause them to appear in the same cluster. This would cluster the words only in terms of their trajectories, not semantics.

The distance between two words $v$ and $w$ with (normalized and filtered using Algorithm \ref{alg:burst-filtering}) trajectories $\vect{\trajn}_{v},\ \vect{\trajn}_{w}$ and Word2Vec embeddings $\embed_{v},\ \embed_{w}$ is now defined as

\begin{equation}
	\distfunc{v}{w} = \jsd{\vect{\trajn}_{v}}{\vect{\trajn}_{w}} \cdot \| \embed_{v} - \embed_{w}\|_{2},
\end{equation}

with $\jsd{\vect{p}}{\vect{q}} = \frac{1}{2} \left( \kl{\vect{p}}{\vect{m}} + \kl{\vect{q}}{\vect{m}} \right) ,\ \vect{m} = \frac{1}{2} \left( \vect{p} + \vect{q} \right)$.

\subsection{Event detection}
Now, we describe the cluster-based event detection algorithm, which is a direct application of the DBSCAN algorithm and consequent noise filtering.

\begin{algorithm}[H]
\begin{algorithmic}[1]
\caption{Cluster-based event detection}
\Input $\text{Word set EW obtained in \autoref{chap:word-analysis}, matrix } \trajmat \text{, word embeddings for EW}$

\State Precompute a distance matrix $\distmat \in \R^{\left\vert \text{EW} \right\vert \times \left\vert \text{EW} \right\vert}$ with $\distmat_{ij} = \distfunc{w_{i}}{w_{j}}$

\State Apply DBSCAN to $\distmat$, obtaining $k$ clusters and the noisy cluster

\ForEach{$(w, cluster) \in \text{DBSCAN.clusters}$}
	\If{$cluster \neq noise$}
		\State $\kw{e_{cluster}} = \kw{e_{cluster}} \cup w$
	\EndIf
\EndFor

\Output $\text{Events} ~ \{ e_{1}, e_{2}, \dots, e_{k} \}$
\end{algorithmic}
\end{algorithm}

In \autoref{fig:cluster-event}, we show an event detected using the cluster-based method. It is again related to the same real event as those in \autoref{fig:original-event} and \autoref{fig:greedy-event}. The main thing to note is that the word trajectories are clear of noise due to application of Algorithm \ref{alg:burst-filtering}. This made it possible to match words only based on their bursts, not any underlying noise. Compared to the event depicted in \autoref{fig:greedy-event}, the cleaned trajectories overlap almost perfectly.

\begin{figure}
  \centering
  \includegraphics{cluster_event}  % cluster event
  \caption{Example of an event detected using the cluster-based method. The event is related to the same real event as \autoref{fig:original-event} and \autoref{fig:greedy-event}.}
  \label{fig:cluster-event}
\end{figure}


A number of different numerical abstract domains have been studied in the literature, and they can be classified with respect to a number of different dimensions: finite versus infinite height, relational versus non-relational, convex versus possibly non-convex, and so on.

The computational cost raises when lifting from finite non–relational domains like \textit{Sign} or \textit{Parity}, to
infinite non–relational domains like \textit{Intervals}, to sophisticated infinite relational domains like \textit{Octagons} \cite{MIN06}, \textit{Polyhedra} \cite{CH78}, \textit{Pentagons} \cite{LF08}, and \textit{Stripes} \cite{F08}, or to donut-like non-convex domains \cite{G12}. Moreover, when considering possibly non-convex disjunctive domains, as obtained through the powerset operator \cite{FR99}, the complexity of the analysis is growing (as well as its accuracy) in a full orthogonal (exponential) way.

Noticeable efforts have been put both to reduce the loss of precision due to the upper bound operation, and to accelerate the convergence of the Kleene iterative algorithm. Some ways to reduce the space dimension in polyhedra computations relying on variable elimination and Cartesian factoring are introduced in \cite{HMG06}.
Seladji and Bouissou \cite{SB13} designed refinement tools based on convex analysis to express the convergence of convex sets using support functions, and on numerical analysis to accelerate this convergence applying sequence transformations.
On the other hand, Sankaranarayanan et al. \cite{SISG06} faced the issue of reducing the computational cost of the analysis using a powerset domain, by adopting restrictions based on \textquotedblleft on the fly elaborations\textquotedblright\ of the program's control flow graph. Efficiency issues about convergence acceleration by widening in the case of a powerset domain have been studied by Bagnara et al. in \cite{BHZ07}. All these domains do not track disjunctive information.

Finally, the trace partitioning technique designed by Mauborgne and Rival \cite{MR05} provides automatic procedures to build suitable partitions of the traces yielding to a refinement that has great impact both on the accuracy and on the efficiency of the analysis. This approach tracks disjunctive information, and it works quite well when the single partitions are carefully designed by an expert user. Unluckily, given the high number of hypercubes tracked by our analysis, this approach is definitely too slow for the scenario we are targeting.

The Parametric Hypercubes proposal presented in this paper can be seen as a selection and a combination of most of these techniques, tailored to get a solution that properly suits the features of Computer Games Software applications. In this scenario, we had to track precisely a lot of disjunctive information. Therefore, we needed to introduce a targeted domain \adomain\ for physics simulations. On the other hand, some of the domain's features (like width parameter tuning, and interval offsets) may also be applied in other domains.

\subsection{Future work}

We observe that our approach offers plenty of venues in order to improve its results, thanks to its flexible and parametric nature. In particular, we could: (i) increase the precision by intersecting our hypercubes with arbitrary bounding volumes which restrict the relationships between variables (the offsets presented in Section \ref{sec:tuning} are the simplest version of this extension); (ii) increase the performance of Algorithm \ref{alg:widthAdjusting} by halving the widths only on some axes, chosen through an analysis of the distribution of hypercubes in the \emph{yes,no,maybe} sets; and (iii) study the derivative with respect to time of the iterations of the main loop in order to define temporal trends to refine the widening operator.
In addition, our domain is modular w.r.t. the non-relational abstract domain adopted to represent the hypercube dimensions. By using other abstract domains it is possible to track relationships between variables which do not necessarily represent physical quantities.

12. Hypercubes Domain/HC/Sections/versione SAS2013/7_related_work.tex

12. Hypercubes Domain/Sections/versione SAS2013/7_related_work.tex


\chapter{Noise in Detectors}
\textit{Poisson noise, shot noise, and photon noise} are often used interchangeably.  Shot noise in simple term, is the noise associated with the random arrival of discrete electrons, and photon noise is often similarly ascribed to the random arrival of discrete photons.  photon noise can also be described as shot noise with photo-electrons.  So photons arrive discretely, which create shot noise, discrete electrons created by discrete arrival of photons.  Assume both photo-electrons and photons are Poisson random processes.


\subsection{Representing real numbers}

store as two integers \((x,y)\)
evaluate as \(x*2^y\)
this is binary floating point
this means you get inaccuracies
eg \((0.1+0.2-0.3)*10^20\) is not zero
alternative is decimal floating point
store as \(x*10^y\)
\subsection{Addition, sub, mult, div of real}

\subsection{Powers, log, exp}

\subsection{Floor and ceiling}


\subsubsection{dataObjectLabelFilter}
\label{dataObjectLabelFilter}

This PostProcessor allows to filter the portion of a dataObject, either PointSet or HistorySet, with a given clustering label.
A clustering algorithm associates a unique cluster label to each element of the dataObject (PointSet or HistorySet).
This cluster label is a natural number ranging from $0$ (or $1$ depending on the algorithm) to $N$ where $N$ is the number of obtained clusters.
Recall that some clustering algorithms (e.g., K-Means) receive $N$ as input while others (e.g., Mean-Shift) determine $N$ after clustering has been performed.
Thus, this Post-Processor is naturally employed after a data-mining clustering techniques has been performed on a dataObject so that each clusters
can be analyzed separately.

\ppType{dataObjectLabelFilter}{dataObjectLabelFilter}

In the \xmlNode{PostProcessor} input block, the following XML sub-nodes are required,
independently of the \xmlAttr{subType} specified:

\begin{itemize}
   \item \xmlNode{label}, \xmlDesc{string, required field}, name of the clustering label
   \item \xmlNode{clusterIDs}, \xmlDesc{integers, required field}, ID of the selected clusters. Note that more than one ID can be provided as input
\end{itemize}


\documentclass{article}

\usepackage[hidelinks]{hyperref}
%\usepackage[capitalize]{cleveref}
\usepackage{tikz}
\usepackage[all]{xy}
%\usepackage[foot]{amsaddr}
\usepackage{amsmath,amsfonts,amssymb,amsthm}
\usepackage{xcolor}
\usepackage{tabularx}
\usepackage{booktabs}

\newcommand{\SM}[1]{\color{blue}#1\color{black}}
\newcommand{\ZZ}[1]{\color{cyan}#1\color{black}}
\newcommand{\AS}[1]{\color{red}#1\color{black}}

\newcommand{\Q}{\ensuremath{\mathbb Q}}
\newcommand{\Z}{\ensuremath{\mathbb Z}}
\newcommand{\Fp}{\ensuremath{\mathbb F_p}}
\newcommand{\End}{\ensuremath{\text{End}}}

\theoremstyle{definition}
\newtheorem*{remark}{Remark}

\title{Bandersnatch: a fast elliptic curve built over the BLS12-381
  scalar field}
\author{Simon Masson${}^\text{1}$, Antonio Sanso${}^\text{2,3}$ and
  Zhenfei Zhang${}^\text{2}$\\
  \ \\
  ${}^\text{1}$\href{https://anoma.network}{Anoma}\\
  ${}^\text{2}$Ethereum Foundation\\
  ${}^\text{3}$Ruhr Universit{\"a}t Bochum\\
}
\date{}

\makeatletter
\newcommand{\verbatimfont}[1]{\renewcommand{\verbatim@font}{\ttfamily#1}}
\makeatother

\begin{document}

\verbatimfont{\small}%

\maketitle
\medskip
\begin{abstract}
 In this short note, we introduce Bandersnatch, a new elliptic curve
 built over the BLS12-381 scalar field. The curve is equipped with an efficient
 endomorphism, allowing a fast scalar multiplication algorithm.
 Our benchmark shows that the multiplication is 42\% faster,
 and 21\% reduction in terms of circuit size in the
 form of rank 1 constraint systems (R1CS),
 compared to another curve, called Jubjub, having similar
 properties. Nonetheless, Bandersnatch does not provide any
 performance improvement for multi scalar multiplications,
 compared to the Jubjub curve.
\end{abstract}

\section{Introduction}
%BLS12-381
BLS12-381 is a pairing-friendly curve created by Sean
Bowe~\href{https://electriccoin.co/blog/new-snark-curve/}{here} in 2017.
Currently, BLS12-381 is undergoing a standardization process
from the
IRTF Crypto Forum Research Group, and is
universally used for digital
signatures and zero-knowledge proofs by many projects orbiting in the
blockchain universe: Zcash, Ethereum 2.0, \href{https://anoma.network}{Anoma}, Skale, Algorand, Dfinity,
Chia, and more.
%jubjub
The ZCash team
introduced Jubjub~\href{https://z.cash/technology/jubjub/}{here}, an
elliptic curve built over the BLS12-381 scalar field $\mathbb
F_{r_\text{BLS}}$.
This curve is not pairing-friendly, but leads to constructions where
$\mathbb F_{r_\text{BLS}}$ arithmetic circuits can be manipulated
using the BLS12-381 curve.
The Jubjub curve can be represented in the twisted Edwards
coordinates, allowing efficiency inside zk-SNARK circuits.
In order for some cryptographic applications to scale, it is necessary to
have efficient scalar multiplication on the non-pairing-friendly
curve.
The main drawback of Jubjub is the slow scalar multiplication
algorithm compared, for example, with the ``Bitcoin curve''
(SECP256k1).
It comes from the fact that the curve does not have an efficiently
computable endomorphism, necessary for computing scalar
multiplications using the GLV method~\cite{C:GalLamVan01} (a technique
protected by a US patent until Sep 2020~\cite{glvpatent}, but that
expired and is
freely usable now).

\paragraph{Our contribution.}
The Jubjub curve is a curve with a large discriminant, meaning that
the GLV method is not possible on this curve.
We performed an exhaustive search of curves of small discriminant,
defined over the BLS12-381 scalar field. This way, we obtain an
elliptic curve using the Complex Multiplication
method~\cite{MC:AtkMor93}, where the scalar multiplication algorithm
is efficient thanks to the GLV method~\cite{C:GalLamVan01}.

We implement this curve in Rust, using
the~\href{http://arkworks.rs}{Arkworks framework}, and release our
code to the open domain~\cite{bandersnatch-rust}.
Table~\ref{tab:comp} shows a comparison of Bandersnatch curve
and Jubjub curve.
Details deferred to Section~\ref{sec:comparison}.

\begin{table}[ht] %\small
  \centering

  \begin{tabular}{|l|c|c|}\hline
      & multiplication cost & R1CS constraints  \\\hline\hline
    Jubjub & 75 $\mu$s  & 3177 \\\hline
    Bandersnatch & 44 $\mu$s  & 2621 \\\hline\hline
    Improvement & 42\% & 21\%\\\hline
  \end{tabular}
  \caption{Bandersnatch vs Jubjub}
  \label{tab:comp}
\end{table}

We also report the number of
% , in terms of both group multiplications and
% the number of
constraints one needs to express a group multiplication
in the form of rank one constraint system (R1CS),
a common approach for expressing circuits for zero-knowledge
proof systems.
A group multiplication takes
2621
constraints when the point is in affine form over the
twisted Edwards curve,
%, and
%2361
%constraints when the point is in the projective form
%over the short Weierstrass from.
%Both figures
% This matches what we have for Jubjub curve.
yielding a 21\% improvement over the Jubjub curve.

\paragraph{Organization of the paper.}
In Section~\ref{sec:small-disc-curves}, we describe how we obtained
several curves allowing the GLV method together with cryptographic
security.
Then, we introduce in Section~\ref{sec:bandersnatch} the Bandersnatch
curve in different models (in Weierstrass, Montgomery and twisted Edwards
coordinates).
Finally, we compare the scalar multiplication algorithm over
the Bandersnatch and the Jubjub curves in
Section~\ref{sec:comparison} from a practical point of view.

\section{Small discriminant curves}\label{sec:small-disc-curves}

The GLV method~\cite{C:GalLamVan01} is a well known trick for accelerating
scalar multiplication over particular curve. In a nutshell, it applies
to elliptic curves where an endomorphism $\psi$ can be efficiently computed.
The GLV method applies in particular for $j$-invariant $j=0$
(resp. $j=1728$) curves because a non-trivial automorphism can be
computed using only one modular multiplication. % (see Example~\ref{ex:psi-j0}).
The method also applies for other curves where the endomorphism is
slightly more expensive, called \emph{small discriminant} curves.

% notations
Let $E$ be an elliptic curve defined over $\Fp$ of trace $t$. $E$ and
its quadratic twist $E^t$ are $\mathbb F_{p^2}$-isomorphic curves and
their orders over $\Fp$ are closely related with the trace
$t$:
$$\#E(\Fp) = p+1-t\qquad \#E^t(\Fp) = p+1+t.$$
See~\cite{Silverman86} for a complete introduction to elliptic curves.
In this work, we are looking for cryptographic applications based on
ordinary elliptic curves, meaning that we look for $t\not\equiv 0
\bmod p$. The endomorphism ring of these curves have a particular
structure: $\End(E)$ is an order of the imaginary quadratic field
$\Q(\sqrt{t^2-4p})$.
From now, we denote $-D$ to be the discriminant of $\End(E)$, and
$\{\text{Id},\psi\}$ a basis of the endomorphism ring.
The fundamental discriminant corresponds to the discriminant of the
maximal order containing $\End(E)$.
This way, $\psi$ is of degree $\frac{D+1}4$ or $D/4$ depending on the
value of $D$ modulo $4$, and $\psi$ can be defined using polynomials
of degree $O(D)$ thanks to the Vélu's formulas~\cite{velu71}.
Thus, the evaluation of $\psi$ is efficient only for curves of small
discriminant.

In this work, we restrict to curves defined over the BLS12-381 scalar
field $\mathbb F_{r_\text{BLS}}$. From now, we denote $p=r_\text{BLS}$
and we look for curves with a $128$-bit cryptographic security.
Curves with $-D=-3$ and $-4$ do not have a large prime subgroup
defined over $\Fp$.
Hence, we look for small discriminant $-D<-4$ curves with subgroup and
twist-subgroup security. It means that $\#E(\Fp)$ has a roughly 256-bit
prime factor, as well as $\#E^t(\Fp)$.

As the endomorphism cost is closely related to the discriminant, we
restrict to $-D \geq -388$ so that $\psi$ can be efficiently computed.
Moreover, we restrict on fundamental discriminants (discriminants
of the maximal orders of imaginary quadratic fields). We denote
$\mathcal O_{-D}$ the maximal order of discriminant $-D$. Elliptic
curves with $\End(E) \subset \mathcal O_{-D}$ are isogenous curves,
meaning that there is a rational map between them. Isogenous curves
have the same order so that we can restrict on fundamental
discriminants for our search.

We compute an exhaustive search among all the possible (fundamental)
discriminants ($-292 \leq -D \leq -3$).
Given a discriminant $-D$, roughly half of the curves are
supersingular and hence not relevant to our cryptographic
applications.
We list in Table~\ref{tab:group-order-factorization} the ordinary
curves we obtained. In this table, $p_n$ denotes a prime of $n$ bits.
The generation of these curves is reproducible
using~\href{https://github.com/asanso/Bandersnatch/blob/main/python-ref-impl/small-disc-curves.py}{this
  file}.
We finally obtain an interesting curve for $-D = -8$ with large prime
order subgroups on both the curve and its twist.
We present in Section~\ref{sec:bandersnatch} the curve in several
models, together with the endomorphism in order to apply the GLV
scalar multiplication algorithm.

\begin{table*}[!ht]
    \centering\footnotesize
    \begin{tabularx}{\textwidth}{ccl}
        \toprule
        $\mathbf{-D}$    & \textbf{Curve sec.}  & \textbf{Curve order} \\
        \midrule
$-3$ & $65$-bit & $2^{2}  \cdot 3  \cdot 97  \cdot 19829809  \cdot 2514214987  \cdot 423384683867248993  \cdot p_{131}$\\
 & $14$-bit & $2^{64}  \cdot 906349^{4}  \cdot p_{28}^{4}$\\
 & $77$-bit & $7  \cdot 43  \cdot 1993  \cdot 2137  \cdot 43558993  \cdot 69032539613749  \cdot p_{154}$\\
 & $41$-bit & $3  \cdot 7  \cdot 13  \cdot 79  \cdot 2557  \cdot 33811
        \cdot 1645861201  \cdot 75881076241177 \cdot$\\
 &          & $86906511869757553  \cdot p_{82}$\\
 & $13$-bit & $3^{2}  \cdot 11^{2}  \cdot 19^{2}  \cdot 10177^{2}  \cdot 125527^{2}  \cdot 859267^{2}  \cdot 2508409^{2}  \cdot 2529403^{2}  \cdot p_{26}^{2}$\\
 & $118$-bit & $836509  \cdot p_{236}$\\
$-4$ & $59$-bit & $2^{32}  \cdot 5  \cdot 73  \cdot 906349^{2}  \cdot 254760293^{2}  \cdot p_{119}$\\
 & $37$-bit & $2^{2}  \cdot 29  \cdot 233  \cdot 34469  \cdot
        1327789373  \cdot 19609848837063073 \cdot$\\
 &          & $159032890827948314857  \cdot p_{74}$\\
 & $37$-bit & $2  \cdot 3^{2}  \cdot 11^{2}  \cdot 13  \cdot 1481  \cdot 10177^{2}  \cdot 859267^{2}  \cdot 52437899^{2}  \cdot 346160718017  \cdot p_{74}$\\
 & $57$-bit & $2  \cdot 5  \cdot 19^{2}  \cdot 1709  \cdot 125527^{2}  \cdot 2508409^{2}  \cdot 2529403^{2}  \cdot p_{114}$\\
$\mathbf{-8}$ & $\mathbf{122}$\textbf{-bit} & $\mathbf{2^{7}  \cdot 3^{3}  \cdot p_{244}}$\\
 & $\mathbf{126}$\textbf{-bit} & $\mathbf{2^{2}  \cdot p_{253}}$\\
$-11$ & $69$-bit & $5  \cdot 191  \cdot 5581  \cdot 18793  \cdot 48163  \cdot 46253594704380463613  \cdot p_{138}$\\
 & $73$-bit & $3^{3}  \cdot 11^{2}  \cdot 9269797  \cdot 17580060420191283788101  \cdot p_{147}$\\
$-19$ & $110$-bit & $7  \cdot 11^{2}  \cdot 19  \cdot 23  \cdot 397  \cdot 419  \cdot p_{220}$\\
 & $74$-bit & $3^{2}  \cdot 5  \cdot 503  \cdot 10779490483  \cdot 433275286013779991  \cdot p_{149}$\\
$-24$ & $53$-bit & $2^{2}  \cdot 3^{2}  \cdot 7  \cdot 19^{2}  \cdot 127  \cdot 29402034080953  \cdot 2970884754778276642175743  \cdot p_{106}$\\
 & $86$-bit & $2^{5}  \cdot 5  \cdot 39628279  \cdot 1626653036429383  \cdot p_{172}$\\
$-51$ & $112$-bit & $3^{2}  \cdot 5  \cdot 61223923  \cdot p_{224}$\\
 & $120$-bit & $23^{2}  \cdot 41  \cdot p_{241}$\\
$-67$ & $67$-bit & $3479887483  \cdot 56938338857  \cdot 8474085246072233  \cdot p_{135}$\\
 & $79$-bit & $3^{2}  \cdot 8478452882270519617659314063  \cdot p_{159}$\\
$-88$ & $61$-bit & $2^{2}  \cdot 11  \cdot 16984307  \cdot 24567897636186592260640293583411  \cdot p_{122}$\\
 & $66$-bit & $2^{9}  \cdot 3^{2}  \cdot 31  \cdot 6133  \cdot 116471  \cdot 69487476515565975361139  \cdot p_{133}$\\
$-132$ & $73$-bit & $2  \cdot 1753  \cdot 101235113104036296384208928969  \cdot p_{147}$\\
 & $92$-bit & $2  \cdot 3^{2}  \cdot 7^{2}  \cdot 11  \cdot 23  \cdot 587  \cdot 701  \cdot 32299799971  \cdot p_{184}$\\
$-136$ & $62$-bit & $2^{3}  \cdot 7^{3}  \cdot 19^{3}  \cdot 10939  \cdot 11131315086725327441688173207  \cdot p_{125}$\\
 & $87$-bit & $2^{2}  \cdot 5  \cdot 5741  \cdot 30851  \cdot 533874022134253  \cdot p_{175}$\\
$-228$ & $114$-bit & $2  \cdot 3^{2}  \cdot 19  \cdot 89  \cdot 5189  \cdot p_{228}$\\
 & $81$-bit & $2  \cdot 947  \cdot 277603  \cdot 28469787063396608749  \cdot p_{162}$\\
$-244$ & $89$-bit & $2^{2}  \cdot 13  \cdot 523  \cdot 1702319  \cdot 2827715661581  \cdot p_{179}$\\
 & $88$-bit & $2^{8}  \cdot 3^{2}  \cdot 5  \cdot 71  \cdot 907  \cdot 2749  \cdot 146221  \cdot 2246269  \cdot p_{176}$\\
$-264$ & $83$-bit & $2^{3}  \cdot 11  \cdot 131  \cdot 12543757399  \cdot 2818746796297  \cdot p_{167}$\\
 & $82$-bit & $2^{2}  \cdot 3  \cdot 5^{2}  \cdot 2287  \cdot 2134790941497418864559  \cdot p_{165}$\\
$-276$ & $70$-bit & $2  \cdot 11^{2}  \cdot 8839  \cdot 78797899  \cdot 323360863688748558301  \cdot p_{140}$\\
 & $88$-bit & $2  \cdot 3  \cdot 5  \cdot 6197  \cdot 138617  \cdot 16664750312513  \cdot p_{177}$\\
$-292$ & $92$-bit & $2  \cdot 54983  \cdot 5220799  \cdot 2671917733  \cdot p_{185}$\\
 & $86$-bit & $2  \cdot 11^{2}  \cdot 149  \cdot 354689  \cdot
24012883  \cdot 32483123  \cdot p_{172}$\\
\bottomrule
    \end{tabularx}
    \caption{Curves for discriminants $-3 \geq -D \geq -292$.}
    \label{tab:group-order-factorization}
\end{table*}

\section{Bandersnatch}\label{sec:bandersnatch}

The Bandersnatch is obtained from a discriminant $-D = -8$, meaning
that the endomorphism ring is $\Z[\sqrt{-2}]$.
We obtain the curve $j$-invariant using the Complex Multiplication
method, based on the Hilbert class polynomial $H_{-D}(X)$.
The roots of $H_{-D}$ are $j$-invariants of elliptic curves whose
endomorphism ring is of discriminant $-D$.
From a $j$-invariant, we obtain the curve equation in different
models. Before looking into the details of three different representations,
we briefly recall how to exhibit the degree $2$ endomorphism $\psi$.

\paragraph{Degree 2 endomorphism.}
The endomorphism $\psi$ has a kernel generated by a $2$-torsion
point. Hence, we can obtain the rational maps defining $\psi$ by
looking at the curves $2$-isogenous to Bandersnatch. Only one has the
same $j$-invariant, meaning that up to an isomorphism, the Vélu's
formulas~\cite{velu71} let us obtain compute $\psi$.
For cryptographic use-cases, we are interested in computing $\psi$ on
the $p_{253}$-order subgroup of the curve. On these points, $\psi$
acts as a scalar multiplication by the eigenvalue
$$\lambda = \text{\small{\tt
    0x13b4f3dc4a39a493edf849562b38c72bcfc49db970a5056ed13d21408783df05}}.$$
By construction, $\psi$ is the endomorphism $\sqrt{-2}\in \mathcal
O_{-8}$. Thus, $\lambda$ satisfies
$\lambda^2+2 = 0 \bmod p_{253}$.
In the following sections, we provide details on the curve equation,
the $\psi$ rational maps, and a generator of the $p_{253}$-order
subgroup in the case of the affine Weierstrass, projective Montgomery
and projective twisted Edwards representations.
The parameters are reproducible using the script
of~\href{https://github.com/asanso/Bandersnatch/blob/main/python-ref-impl/get\_params.py}{this
  file}.

\subsection{Weierstrass curve}\label{sec-w-curve}
\paragraph{Curve equation.}
The Bandersnatch curve can be represented in the Weierstrass model
using the equation
$$E_W:y^2 = x^3 -3763200000x -78675968000000.$$
%% \begin{verbatim}
%% p=0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001
%% E=EllipticCurve(GF(p), [-3763200000, -78675968000000])
%% \end{verbatim}

\paragraph{Endomorphism.}
The endomorphism $\psi$ can obtained using the method detailed above.
We obtain the following expression:
$$\psi_\text{W}(x,y) = \left(u^2\cdot \frac{x^2+44800x+2257920000}{x+44800}, u^3\cdot
y\cdot \frac{x^2+2\cdot 44800x+t_0}{(x+44800)^2}\right).$$
\begin{verbatim}
u=0x50281ac0f92fc1b20fd897a16bf2b9e132bdcb06721c589296cf82245cf9382d
t0=0x73eda753299d7d483339d80809a1d80553bda402fffe5bfefffffffef10be001.
\end{verbatim}

\paragraph{Subgroup generator.}
The generator of the $p_{253}$-order subgroup is computed by finding the
lexicographically smallest valid $x$-coordinate of a point of the
curve, and scaling it by the cofactor $4$ such that the result is not
the point at infinity. From a point with $x=2$, we obtain a generator $E_W(x_W,y_W)$ where:
\input{params-W.tex}

\subsection{Twisted Edwards curve}
\paragraph{Curve equation.}
Bandersnatch can also be represented in twisted Edwards coordinates,
where the group law is complete.
In this model, the Bandersnatch curve can be defined by the equation
$$E_\text{TE}:-5x^2+y^2 = 1 +
dx^2y^2, d=\frac{138827208126141220649022263972958607803}{171449701953573178309673572579671231137}.$$
Twisted Edwards group law is more efficient with a coefficient
$a = -1$ (see~\cite{AC:HWCD08} for details).
In our case, $-5$ is not a square in $\Fp$. Thus, the curve with
equation $-x^2+y^2 = 1 -dx^2y^2/5$ is the quadratic twist of
Bandersnatch. We provide a representation with $a=-5$, leading to a
slightly more expensive group law because multiplying by $-5$ is more
expensive than a multiplication by $-1$, but this cost will be
neglected compared to the improvement of the GLV method. See
Section~\ref{sec:comparison} for details.

\paragraph{Endomorphism.}
From this representation, we exhibit the degree $2$ endomorphism in
twisted Edwards coordinates:
$$
\psi_\text{TE}(x,y,z) = \left(f(y)h(y), g(y)xy, h(y)xy\right)\qquad
\left\{\begin{array}{r}
f(y) = c(z^2-y^2),\\
g(y) = b(y^2+bz^2),\\
h(y) = y^2-bz^2.
\end{array}\right.$$

\begin{verbatim}
b=0x52c9f28b828426a561f00d3a63511a882ea712770d9af4d6ee0f014d172510b4
c=0x6cc624cf865457c3a97c6efd6c17d1078456abcfff36f4e9515c806cdf650b3d.
\end{verbatim}
This map can be computed in 3 additions and 9 multiplications by
first computing $xy$, $y^2$, $z^2$ and $bz^2$.

\paragraph{Subgroup generator.}
The generator of the $p_{253}$-order subgroup obtained in
Section~\ref{sec-w-curve} has twisted coordinates
of the form $E_\text{TE}(x_\text{TE},y_\text{TE},1)$ with
\input{params-TE.tex}

\subsection{Montgomery curve}
\paragraph{Curve equation.}
A twisted Edwards curve is always birationally equivalent to a
Montgomery curve. We obtain the mapping between these two
representations following~\cite{JCEng:CosSmi18}.
While the twisted Edwards model fits better for $\mathbb F_p$ circuit
arithmetic and more generally for the zero-knowledge proof context, we
provide here the Montgomery version because the scalar multiplication
is more efficient in this model:
$$E_M: By^2 = x^3 + Ax^2 + x$$
\begin{verbatim}
B=0x300c3385d13bedb7c9e229e185c4ce8b1dd3b71366bb97c30855c0aa41d62727
A=0x4247698f4e32ad45a293959b4ca17afa4a2d2317e4c6ce5023e1fd63d1b5de98.
\end{verbatim}

\paragraph{Endomorphism.}
Montgomery curves allow efficient scalar multiplication using the
Montgomery ladder. We provide here the endomorphism $\psi$ in this
model:
$$\psi_\text{M}(x,-,z) = (-(x-z)^2 - cxz, -, 2xz)$$
\begin{verbatim}
c=0x4247698f4e32ad45a293959b4ca17afa4a2d2317e4c6ce5023e1fd63d1b5de9a.
\end{verbatim}

\paragraph{Subgroup generator.}
The generator of the $p_{253}$-order subgroup given above is of the
form $E_M(x_M,-,1)$ with:
\input{params-M.tex}

\subsection{Security of Bandersnatch}

The Bandersnatch curve order is $2^2\cdot r$ for a $253$-bit long
prime $r$.
% 13108968793781547619861935127046491459309155893440570251786403306729687672801
Its quadratic twist has order
$2^7 \cdot 3^3 \cdot r'$, where $r'$ is another prime of $244$ bits.
%15172417585395309745210573063711216967055694857434315578142854216712503379
Hence, the Bandersnatch curve satisfies twist security after a quick cofactor
check.
We estimate that the Bandersnatch curve (resp. its quadratic twist)
has $126$ bits of security (resp. $122$ bits of security).

% \ZZ{TODOs: 1. expand the security section 2. hash to curve (not essential, but nice to have)
% 3. serialization (required by a spec rather than an academic paper. may be borrow
% some ed25519 trick where the cofactor is 8?)}

\section{Comparison}\label{sec:comparison}

%### Scalar multiplication improvement
The twisted Edwards representation is mostly used in practice, and we
now focus on the comparison between Jubjub and Bandersnatch in this
model.

\subsection{Scalar multiplications for a variable base point}
% Jubjub scalar multiplication
Because of its large discriminant, the scalar multiplication on Jubjub
is a basic double-and-add algorithm, meaning that it computes a
multiplication by $n$ in $\log n$ doublings and $\log n/2$
additions (in average) on the curve.

% Bandersnatch scalar multiplication
The endomorphism $\psi$ lets us compute the scalar multiplication
faster than a double-and-add algorithm with few precomputations. For a
point $P$ and a scalar $n$, we first evaluate $\psi$ at $P$ and
decompose $n = n_1 + \lambda n_2$. Then a multi scalar multiplication
is computed in $\log n/2$ doublings and $3\log n/8$ additions (in average) on the curve.

% Benchmarks
We benchmarked our implementation with both GLV enabled and disabled, and
compared it with Arkworks' own Jubjub implementation.
Our benchmark is conducted over an AMD 5900x CPU, with Ubuntu 20.04,
rust 1.52 stable version, and Arkwork 0.3.0 release version.
We used~\href{https://docs.rs/criterion}{\texttt{criterion}
  micro-benchmark toolchain},  version 0.3.0, for data collection. We
compile Arkworks with two options, namely \texttt{default} and
\texttt{asm}, respectively.
The \texttt{default} setup relies on \texttt{num\_bigint} crate for
large integer arithmetics, while \texttt{asm} turns on assembly for
finite field multiplication.

Arkworks use the aforementioned double-and-add
multiplication methodology, without side channel protections such
as Montgomery ladders. Our non-GLV implementation also follows
this design. For our GLV implementation, there are three components,
namely, the endomorphism, the scalar decomposition, and the
multi scalar multiplication (MSM). We implement those schemes and
present the micro-benchmarks in Table~\ref{tab:comp_full}.
Specifically, we do not use the MSM implementation in Arkworks:
our scalars, after the decomposition, contain roughly 128 bits
of leading zeros, and our own MSM implementation is
optimized for this setting.

Table~\ref{tab:comp_full} presents the full picture of the benchmark.
When GLV is disabled, we observe a similar but a little worse
performance for Bandersnatch curve, compared to
the Jubjub curve, due to the slightly larger coefficient
$a=-5$ and a larger scalar field of 253 bits (Jubjub curve has $a=-1$
and a scalar field of 252 bits).
When GLV is enabled, we report a 45\% improvement of the Bandersnatch
curve, and a 42\% improvement over the Jubjub curve.

\begin{table}[ht] %\small
  \centering

  \begin{tabular}{|l|c|c|}\hline
      & \texttt{default} & \texttt{asm}\\\hline\hline
    Jubjub & 75 $\mu$s & 69 $\mu$s \\\hline\hline
    Bandersnatch without GLV & 78 $\mu$s & 72 $\mu$s  \\\hline\hline
    Bandersnatch with GLV& 44 $\mu$s & 42 $\mu$s \\\hline
    \ \ \ Endomorphism & 2.4 $\mu$s& 1.8 $\mu$s\\\hline
    \ \ \ Scalar decomposition & 0.75 $\mu$s & 0.7 $\mu$s \\\hline
    \ \ \ multi scalar multiplication & 42 $\mu$s &  40.8 $\mu$s\\\hline\hline
    Overall Improvement & 42\% & 39\% \\\hline
  \end{tabular}
  \caption{Bandersnatch vs Jubjub: Performance}
  \label{tab:comp_full}
\end{table}

To make a meaningful comparison, we benchmark
the cost of the group multiplication over the default generators.
Note that Arkworks do not implement optimizations for
fixed generators nonetheless. We then sample field elements
uniformly at random, for each new iteration, and the benchmark
result is consolidated over 100 iterations.

\subsection{Multi scalar multiplications}
This section reports the performance of variable base
multi scalar multiplications (MSM). Note that this MSM is
compatible, but
different
from the MSM inside the GLV.
In particular, for a sum of $k$ scalar multiplications,
we report the data point for:
\begin{itemize}
  \item invoking the MSM over the $k$ base scalars randomly sampled,
    expected to be around 256 bits;
  \item using GLV endomorphism to break the $k$ base scalars into $2k$
    new base scalars, of halved size, i.e.~of 128 bits.
\end{itemize}
The data is presented in Figure~\ref{fig:msm}. Specifically,
as a baseline, the trivial solution, captained by
{\em GLV without
MSM}, is the product of the number of bases and the cost of
doing a single GLV multiplication.
Note that the MSM algorithms incur an overhead to build some
tables, which make them less favorable compared to the trivial
solution when dimension is really small. For a dimension greater
than 4, MSM algorithms begin to out-perform trivial solutions.
For dimension greater than 128, it is more efficient to
invoke the MSM directly, rather than doing it over the GLV basis.
The reason is that the size of the basis becomes too large, so
that the gain we get from halving the scalars is offset from the
gain we get from halving the basis. We remark that this threshold
point is platform dependent.
\begin{figure}[h]\centering \label{fig:msm}
  \includegraphics[width=12cm]{fig/msm.pdf}
\end{figure}

\subsection{R1CS constraints}
The Bandersnatch curve is zk-SNARK friendly: its
base field matches the scalar field for the BLS12-381 curve, a
pairing-friendly curve, on top of which people build zk-SNARK
systems, such as Groth16 \cite{EC:Groth16} or Plonk \cite{EPRINT:GabWilCio19}.
In such a setting, the prover can sufficiently argue certain
relationships over arithmetic circuits rather than binary
circuits.
The circuit is expressed in a form of Rank-1 constraint system
(R1CS), and in general, the complexity is determined by the
number of constraints in an R1CS.

We evaluate the number of constraints for a
variable base group multiplication. For a double-and-add
algorithm,
our code reports 3177 constraints in
total.
As a sanity check, within the core logic,
it takes 6 constraints per addition, 5 constraints
per doubling and 2 constraints per bit selection. This adds
up to 13 constraints per bit, or 3177 constraints per
group multiplication (and we reasonably assume some system overhead
consumes another 10 constraints).

Now, in the case of GLV,
% Let us first explain the obstacle of implementing the GLV
%with R1CS. T
the endomorphism is almost free: it requires
6 constraints. The MSM inside the GLV can also be done
with $2176$ constraints using the above double-then-add
techniques.
The difficult part is the circuit for scalar decomposition,
which is to prove $n = n_1 +\lambda n_2 \bmod r$ where
$n$ and $\lambda$ are around 256 bits,
$n_1$ and $n_2$ are around 128 bits, and
$r$
is the order of the scalar field.
We implemented this part of the code with $405$ constraints
via hand optimized circuits.
% We therefore report the number of constraints to perform
% a group operation on both Jubjub curve and Bandersnatch
% curve. We observe that it takes 3177 constraints for the
% Jubjub curve, for which the statement is argued over
% the Edwards affine form coordinates.
Precisely, we list the breakdown numbers in Table~\ref{tab:r1cs_full};
the  Bandersnatch with GLV constraints count is a little higher than
the sum of its components due to some overhead during setup phase.

\begin{table}[h] %\small
  \centering

  \begin{tabular}{|l|c|}\hline
      & \texttt{Number of Constraints} \\\hline\hline
      jubjub& 3177 \\\hline
      Bandersnatch without GLV& 3177 \\\hline\hline
    Endomorphism & 6 \\\hline
    Scalar decomposition &  405 \\\hline
    multi scalar multiplication & 2176 \\\hline
    Bandersnatch with GLV&  2621\\\hline\hline
    Overall Improvement & 21\%   \\\hline
  \end{tabular}
  \caption{Bandersnatch vs Jubjub: R1CS}
  \label{tab:r1cs_full}
\end{table}

The \href{https://github.com/zhenfeizhang/bandersnatch-glv}{Rust implementation} of the Bandersnatch scalar multiplication
algorithm confirms our estimations: the GLV method is $21\%$ faster
than the Jubjub implementation.

\section{Conclusion}
Tne last decade has seen great improvements on practical zk-SNARK systems.
An essential stepping stone of these schemes is an efficient elliptic
curve whose base field matches the scalar field for some pairing-friendly curve.
On this note, we present Bandersnatch as an alternative to the commonly used
base curve Jubjub. Due to the existence of an efficiently computable
endomorphism, the scalar multiplication over this curve is 42\% times
faster than the Jubjub curve.
For multi scalar multiplications, we report a narrowed advantage over Jubjub
curve when the dimension is small, but it vanishes for larger
dimensions.
We also do not observe any improvement in terms of number of constraints in
the corresponding R1CS circuit.

\bigskip
\paragraph*{\textbf{Acknowledgments.}} We would like to thank Weikeng
Chen, Luca De Feo, Justin Drake, Youssef El Housni, Dankrad Feist,
Gottfried Herold and Daira Hopwood for fruitful discussions.

\bibliography{bandersnatch,cryptobib/abbrev3,cryptobib/crypto}
\bibliographystyle{unsrt}
\end{document}


\subsection{Charge carrier transport}
To describe charge carrier transport, the bi-polar drift-diffusion equations are solved in position space
for electrons,
\begin{equation}
\label{eq:ndrive}
\boldsymbol{J_n} = q \mu_e n_{f}  {\nabla E_{c}}  + q D_n  {\nabla n_{f}},
\end{equation}
and holes,
\begin{equation}
\label{eq:pdrive}
\boldsymbol{J_p} = q \mu_h p_{f}  {\nabla E_{v}}  - q D_p {\nabla p_{f}}.
\end{equation}

Conservation of charge carriers is forced by solving the charge carrier continuity equations for both electrons,
\begin{equation}
\label{eq:contn}
\nabla \boldsymbol{J_n}  = q (R-G+\frac{\partial n}{\partial t}),
\end{equation}
and holes
\begin{equation}
\label{eq:contp}
\nabla \boldsymbol{J_p} = - q (R-G+\frac{\partial p}{\partial t}).
\end{equation}

where $R$ and $G$ are the net recombination and generation rates per unit volume respectively.


\documentclass{article}
\usepackage{theorem}

\DeclareMathAlphabet{\mathsc}{OT1}{cmr}{m}{sc}

\newcommand{\implies}{\Rightarrow}
\newcommand{\have}{{.~}}
\newcommand{\bstate}{{\mathcal{S}}}
\newcommand{\blocks}{{\mathcal{B}}}
\newcommand{\tabtop}{{\mathsc{t}}}
\newcommand{\tblocks}{{\blocks_\tabtop}}
\newcommand{\bclear}{{\mathsc{clear}}}
\newcommand{\bon}{{\mathsc{on}}}
\newcommand{\babove}{{\mathsc{above}}}
\newcommand{\bstack}{{\mathsc{stack}}}
\newcommand{\bbase}{{\mathsc{base}}}
\newcommand{\st}{~|}

\begin{document}

\section{Definitions}

\begin{itemize}
\item Let
  $$ \blocks = \{ 1, \ldots, N \} $$
represent a set of $N$ blocks in a blocks-world problem.
We represent the table top with the symbol $\tabtop$, and
define $$ \tblocks \equiv \blocks \cup \{ \tabtop \} $$

\item Call any
  $$ \bstate \subseteq \blocks \times \tblocks $$
a {\em part-state} of the blocks-world problem. The pairs of blocks in
$\bstate$ represent {\em on} relations.

\item A part-state $\bstate$ is {\em legal} iff
  \begin{itemize}
  \item No block is on two things. $$
    \forall i \in \blocks \have
      \langle i , j \rangle \in \bstate \implies
      \not\exists j' \in \tblocks \have
	j \neq j' \wedge \langle i , j' \rangle \in \bstate
  $$
  \item No two blocks are on the same block. $$
    \forall j \in \blocks \have
      \langle i , j \rangle \in \bstate \implies
      \not\exists i' \in \blocks \have
	i \neq i' \wedge \langle i' , j \rangle \in \bstate
  $$
  \end{itemize}

\item Define the partial functions
$\bon_i(\bstate)$ mapping legal part-states to
blocks such that
$\bon_i(\bstate) = j$ when $\langle i, j \rangle \in \bstate$;
$\bon_i$ is undefined elsewhere.
(In other words, $\bon_i$ says
which block block $i$ is on in a given state.)
By the definition of a legal part-state, these functions are well-defined.

\item A part-state is a {\em total state} or just a {\em state}
iff it is legal and every block is on something. $$
    \forall i \in \blocks \have
      \exists j \in \tblocks \have
	\langle i , j \rangle \in \bstate
$$

\item The {\em above} relation is the transitive closure of
the {\em on} relation: A block $i$ is above a block $j$ in a
legal part-state $\bstate$ if either $i$ is on $j$, or $i$ is on
a block which is above $j$.  $$
  \babove_i(\bstate) = \left \{ \begin{array}{ll}
    \{ j \} \cup \babove_j(\bstate) &
      j = \bon_i(\bstate) \wedge j \neq \tabtop \\
    \emptyset & \mbox{otherwise}
  \end{array} \right .
$$

\item A block $j$ is {\em clear} in a legal part-state $\bstate$ iff no block
is above it. $$
  \bclear(\bstate) = \{ j \in \bstate \st
  \not\exists i \have \langle i , j \rangle \in \bstate \}
$$

\item A legal part-state $\bstate$ is {\em realizable} iff
no block is above itself. $$
  \not\exists i \in \blocks \have
    i \in \babove_i(\bstate)
$$

\item {\em Moves} are functions $m_{ij}$ which take a realizable part-state in
which blocks $i$ and $j$ are clear to a
realizable part-state in which $i$ is on $j$.

Let $i \in \blocks$ and $j \in \tblocks$, and let $\mathcal{C}_{ij}$ be the set
of realizable part-states
in which $i$ is clear, and either $j = \tabtop$ or $j$ is clear.
Then the domain of $m_{ij}$ is
$\mathcal{C}_{ij}$, and the range is the set of all realizable part-states.

We define the partial function $m_{ij}$ by $$
  m_{ij}(\bstate) \equiv
    \left ( \bstate - \{ \langle i, \bon_i(\bstate) \rangle \} \right )
    \cup \{ \langle i, j \rangle \}
$$
when $i$ and $j$ are clear in $\bstate$; $m_{ij}$ is undefined
elsewhere.  A move is {\em legal} iff $m_{ij}$ is defined.

\item A {\em move sequence} $M$
of length $k$ from state $\bstate^1$ to state $\bstate^2$ consists of
a sequence of pairs $$
  \langle i_1, j_1 \rangle , \langle i_2 , j_2 \rangle , \ldots ,
  \langle i_k , j_k \rangle \in \left ( \blocks \times \tblocks \right ) ^ \ast
$$
such that $$
  \left ( m_{i_k j_k} \circ \cdots \circ m_{i_2 j_2} \circ
  m_{i_1 j_1} \right ) (\bstate^1) = \bstate^2
$$
We allow ourselves the liberty of writing $M(\bstate^1) = \bstate^2$.
A move sequence $M$ is {\em legal} for a state $\bstate$ iff
$M(\bstate)$ is defined.

\item A {\em primitive-blocks-world} (PBW) {\em problem} consists of two
realizable states: an
initial state $I$ and a goal state $G$.
A {\em solution} to the problem is a move sequence $M$ such that $M(I) = G$.
We say that a solution is {\em optimal} if there is no solution
of shorter length.

\item A {\em stack} of blocks starting at $i$ in a
legal part-state $\bstate$ is just
$i$ plus the set of blocks $i$ is above. $$
  \bstack_i(\bstate) = \{ i \} \cup \babove_i(\bstate)
$$
We call $i$ the {\em top} of the stack.
If $\bstate$ is a realizable part-state, the {\em base}
of the stack is the block in the stack which is
above no other blocks in the stack. $$
  \bbase_i(\bstate) = j \in \bstack_i(\bstate) \have
    \babove_j(\bstate) \subseteq \{ \tabtop \}
$$
(The lemma that every stack in any realizable part state
has a base is proved by tracing through the definitions.)

\item A {\em tower} is a stack which is a subset of no other
stack.

\end{itemize}

\section{Flexibility}

A legal part-state $\bstate^2$ is {\em as flexible} as
a legal part-state $\bstate^1$ iff no block in $\bstate^2$
is above some block in $\bstate^2$ which it is not above in
$\bstate^1$, i.e. $$
  \babove_i (\bstate^2) \subseteq \babove_i(\bstate^1)
$$
We notate this by writing $\bstate^2 \sqsubseteq \bstate^1$.

An observation about states related by flexibility is in order.
\begin{lemma}{flexible-clear}{Flexibility And Clear Blocks}
\given
States $\bstate^1$ and $\bstate^2$ with $\bstate^2 \sqsubseteq \bstate^1$.
\prove
Any block clear in $\bstate^1$ is clear in $\bstate^2$: $$
  \bclear(\bstate^2) \supseteq \bclear(\bstate^1)
$$
\proof
Consider some block $j$ in $\bstate^2$.  If it is not clear,
then there is a block $i$ above it in $\bstate^2$.  But,
by definition of flexibility, this means that $i$ is above $j$
in $\bstate^1$, so $j$ is not clear in $\bstate^1$, either.
\end{lemma}

We now justify the terminology ``as flexible as''
by means of Lemma \ref{flexible-move}:
\begin{lemma}{flexible-move}{Flexibility And Move Sequences}
\given
States $\bstate^1$ and $\bstate^2$ with $\bstate^2 \sqsubseteq \bstate^1$.
A legal move sequence $M$ starting at $S^1$.
\prove
\begin{description}
\item[i)~] $M$ is also a legal move sequence starting at $\bstate^2$.
\item[ii)~] $M(\bstate^2) \sqsubseteq M(\bstate^1)$.
\end{description}
\proof
By induction on prefixes of $M$.
\basecase
The theorem is true for the empty prefix of $M$.
\indcase
Decompose $M$ such that the prefix $M^1$ before
some move $m = \langle i, j \rangle$ satisfies the lemma $$
  M = M^1 \cdot \langle i, j \rangle \cdot M^2
$$
and let
\begin{eqnarray*}
  \bstate^1_1 &=& M^1(\bstate^1) \\
  \bstate^1_2 &=& \langle i, j \rangle(\bstate^1_1) \\
  \bstate^2_1 &=& M^1(\bstate^2) \\
  \bstate^2_2 &=& \langle i, j \rangle(\bstate^2_1)
\end{eqnarray*}

By hypothesis we have $\bstate^2_1 \sqsubseteq \bstate^1_1$.
By Lemma \ref{flexible-clear}, this means that $$
  \bclear(\bstate^1_1) \subseteq \bclear(\bstate^2_1)
$$
This means that since $\langle i, j \rangle$ is a legal
move in $\bstate^1_1$, it must also be a legal move in
$\bstate^2_1$.  Thus, condition (i) of the lemma holds
for the prefix $M^1 \cdot \langle i, j \rangle$ of $M$.

To see that condition (ii) of the Lemma holds on the extended
prefix, we note that the only block possibly above other blocks in
$\bstate^2_2$ but not in $\bstate^2_1$ is $i$.  We then note that
by definition of flexibility
\begin{eqnarray*}
  \babove_i(\bstate^2_2) &=& \babove_j(\bstate^2_1) \cup \{j\} \\
  &\subseteq& \babove_j(\bstate^1_1) \cup \{j\} \\
  &=& \babove_i(\bstate^1_2)
\end{eqnarray*}
\end{lemma}

\section{Solution Optimization}

In the search for an algorithm giving optimal solutions for PBW
problems, we make use of the following lemmas, most of which
have been proved previously elsewhere in the literature.  All
of these lemmas are proved using essentially the same
reasoning:  If $\bstate$ is a solution, and we can construct
from $\bstate$ a solution $\bstate'$ which is the same as
$\bstate$ except for deletion of one or more elements, then
$\bstate$ is not an optimal solution.

\begin{lemma}{table-to-table}{Table-To-Table Moves}
\given
A PBW problem $\langle I, G \rangle$.
An optimal solution $M$ to $\langle I, G \rangle$.
\prove
No block moves from the table to the table in $M$.
\proof
Assume the contrary of the lemma, i.e., that there is
some table-to-table move in $M$.
Use this move to split $M$
$$
  M = M^1 \cdot \langle i, \tabtop \rangle \cdot M^2
$$
where $$
  \bon_i(M^1(I)) = \tabtop
$$
Let $\bstate^1 = M^1(I)$.
Applying the definitions of the previous section yields
\begin{eqnarray*}
  \langle i, \tabtop \rangle(\bstate^1)
  &\equiv& m_{i \tabtop}(\bstate^1) \\
  &=& \left ( \bstate^1 - \{ \langle i, \bon_i(\bstate^1) \rangle \} \right )
  \cup \{ \langle i, \tabtop \rangle \} \\
  &=& \left ( \bstate^1 - \{ \langle i, \tabtop \rangle \} \right )
  \cup \{ \langle i, \tabtop \rangle \} \\
  &=& \bstate^1
\end{eqnarray*}
This says that the state at the start of the table-to-table
move is the same as the state at the end, and thus by the
definition of a solution, the sequence obtained by deleting
this move from $M$ is also a solution.  But by the definition
of optimality $M$ is therefore not optimal, and thus we have
a condradiction.

Therefore, no such move can be in $M$.
\end{lemma}

\begin{lemma}{tabled}{Correctly Tabled Blocks}
\given
A PBW problem $\langle I, G \rangle$, such that
a block $i$ is on the table in both $I$ and $G$.
An optimal solution $M$ to $\langle I, G \rangle$.
\prove
$i$ doesn't move in $M$, i.e. $$
  \not\exists j \in \tblocks \have
    M = \ldots, \langle i, j \rangle, \ldots
$$
\proof
Assume the contrary, i.e., that $i$ moves in $M$.

We first split $M$ such that $$
  M = M^1 \cdot \langle i, j \rangle \cdot M^2 \cdot
  \langle i, j' \rangle \cdot M^3
$$
where $M^2$ and $M^3$ contain no moves of $i$.
To see that this split is possible, let
\begin{eqnarray*}
\bstate^1 &=& M^1(I) \\
\bstate^2 &=& \langle i, j \rangle(\bstate^1) \\
\bstate^3 &=& (M^2 \cdot \langle i, \tabtop \rangle)(\bstate^2)
\end{eqnarray*}
We first note
that since by assumption $i$ moves in $M$, the first
move in the split exists.  Further, by Lemma
\ref{table-to-table}, $j \neq \tabtop$.
Finally, since $i$ is on the table in $G$, and
$j$ is not the table in $\bstate^2$, then $i$ must move
to the table, so the second move in the split exists, and $j' = \tabtop$.

Now consider the subproblem $\langle \bstate^1, \bstate^3 \rangle$
and its known and presumably optimal solution $$
  M' = \langle i, j \rangle \cdot M^2 \cdot \langle i, \tabtop \rangle
$$
We will construct a shorter solution to the problem from this
solution.

For any solution $M$ to $\langle I, G \rangle$,
let $M_i$ be the sequence of moves obtained as follows:
Consider any move $m = \langle j, i \rangle$ in $M$, and the
state $\bstate$ just before that move.  Replace $m$ with the two-move
sequence $$
  m' = \langle i, tabtop \rangle, \langle j, \bon_i(\bstate) \rangle
$$
We note that $M_i$ is still a sequence of
legal moves by Lemma \ref{flexible-move}, since the state after $m'$
is as flexible as the state after $m$.

Now consider $M'_i$.  Since $i$ doesn't move $M^2$, the last
move in $M'_i$ moves $i$ from the table to the table, and can
thus be deleted.  And since the only $\babove$ relations that
have changed anywhere in the two move sequences involve $i$,
and since $i$ is on the table at the end of both $M'_i$ and $M_i$,
$M'_i(\bstate) = M_i(\bstate)$.

Thus, we now have a sequence
\end{lemma}

\end{document}


\chapter{Demodulation of 802.15.4}
\section{Demodulation equation}
The receiver uses the following equation to demodulate the signal.
\begin{equation}
d(t) = R_Q(t)\times R_I(t-\tau) - R_Q(t-\tau)\times R_I(t)
\end{equation}

where the $R_I(t)/R_Q(t)$ are received In-phase/Quad-phase signals, $\tau$ is the sampling period. Bit decoding depends on
the sign of $d(t)$. If $d(t)>0$, the decoded bit equals 1 and vice versa.

\section{Decoding principle}
The 802.15.4 standard uses OQPSK modulation. The In-phase and Quad-phase are shifted by 1/2 symbol time. The symbol time
is 1/2 period of sine wave. Namely, the In-phase and Quad-phase are shifted by 1/4 period of sine wave. Thus, the In-phase
and Quad-phase can be expressed as $\pm sin(t + \theta)$ and $\pm cos(t + \theta)$. Where $\theta \in \{0, \tfrac{\pi}{2}\}$.

For example, one combination of In-phase/Quad-phase is $cos(t)$ and $sin(t), 0<t<\tfrac{pi}{2}$. By applying the demodulation
equation,
\begin{align}
d(t)&= sin(t)\times cos(t-\tau) - sin(t-\tau)\times cos(t) \\
d(t)&= sin(t)\left[cos(t)cos(\tau) + sin(t)sin(\tau)\right] - cos(t)\left[sin(t)cos(\tau) - cos(t)sin(\tau)\right] \\
d(t)&= sin^2(t)sin(\tau) + cos^2(t)sin(\tau) = sin(\tau)
\end{align}
Therefore, $d(t)$ depends on the sampleing period only. In this example, $d(t)$ is greater than 0 and remains constant
during the half-symbol period. The following table lists the total combination of I/Q signals.

\begin{table}[h!]
\centering
	\begin{tabular}{|c|c|c|}
		\hline
		In-phase & Quad-phase 	& decoded equation \\ \hline
		$cos(t)$ & $sin(t)$		& $sin(\tau)$\\ \hline
		$cos(t)$ & $-sin(t)$	& $-sin(\tau)$\\ \hline
		$-cos(t)$ & $sin(t)$	& $-sin(\tau)$\\ \hline
		$-cos(t)$ & $-sin(t)$	& $sin(\tau)$\\ \hline
		$sin(t)$ & $cos(t)$		& $-sin(\tau)$\\ \hline
		$sin(t)$ & $-cos(t)$	& $sin(\tau)$\\ \hline
		$-sin(t)$ & $cos(t)$	& $sin(\tau)$\\ \hline
		$-sin(t)$ & $-cos(t)$	& $-sin(\tau)$\\ \hline
	\end{tabular}
	\label{tab:demux}
	\caption{}
\end{table}

Therefore, the receiver simply determines the incoming bit from the sign of $d(t)$. Note that the I/Q signals coming
at the symbol rate of 1$\mu$s, and the I/Q shift by 0.5$\mu$s. Every 0.5$\mu$s generates a bit. Bit rate is 2MHz and
half-byte is mapped to 32 bits chip sequence, which is 16$\mu$s.


\input{../header_function}

%---------- start document ---------- %
 \section{poly.factor -- polynomial factorization}\linkedzero{poly.factor}
 The factor module is for factorizations of integer coefficient univariate polynomials.

 This module using following type:
 \begin{description}
   \item[polynomial]\linkedone{poly.factor}{polynomial}:\\
     \param{polynomial} is the polynomial generated by function poly.uniutil.polynomial.
 \end{description}

%
  \subsection{brute\_force\_search -- search factorization by brute force}\linkedone{poly.factor}{brute\_force\_search}
   \func{brute\_force\_search}
   {%
     \hiki{f}{poly.uniutil.IntegerPolynomial},\ %
     \hiki{fp\_factors}{list},\ %
     \hiki{q}{integer}%
   }{%
     \out{[factors]}%
   }\\
   \spacing
   % document of basic document
   \quad Find the factorization of \param{f} by searching a factor which is a product of some combination in \param{fp\_factors}. The combination is searched by brute force.
   \spacing
   % added document
   The argument \param{fp\_factors} is a list of poly.uniutil.FinitePrimeFieldPolynomial .
   \spacing
   % input, output document
   %\quad \\
%
  \subsection{divisibility\_test -- divisibility test}\linkedone{poly.factor}{divisibility\_test}
   \func{divisibility\_test}
        {\hiki{f}{polynomial},\ %
         \hiki{g}{polynomial}%
        }
        {\out{bool}}\\
   \spacing
   % document of basic document
   \quad Return Boolean value whether \param{f} is divisible by \param{g} or not, for polynomials.
   \spacing
   % added document
   %\quad \negok Note that this function returns Hilbert class polynomial as a list of coefficients.\\
   %\spacing
   % input, output document
   %\quad \param{D} must be negative int or long. See \cite{Pomerance}.\\
%
  \subsection{minimum\_absolute\_injection -- send coefficients to minimum absolute representation }\linkedone{poly.factor}{minimum\_absolute\_injection}
   \func{minimum\_absolute\_injection}
        {\hiki{f}{polynomial}}
        {\out{F}}\\
   \spacing
   % document of basic document
   \quad Return an integer coefficient polynomial F by injection of a $\mathbf{Z}/p\mathbf{Z}$ coefficient polynomial \param{f} with sending each coefficient to minimum absolute representatives.
   \spacing
   % added document
   %\quad \negok
   %\spacing
   % input, output document
   \quad The coefficient ring of given polynomial \param{f} must be \linkingone{intresidue}{IntegerResidueClassRing} or \linkingone{finitefield}{FinitePrimeField}.\\
%
  \subsection{padic\_factorization -- p-adic factorization}\linkedone{poly.factor}{padic\_factorization}
   \func{padic\_factorization}
        {\hiki{f}{polynomial}}
        {\out{p}, \out{factors}}\\
   \spacing
   % document of basic document
   \quad Return a prime \param{p} and a p-adic factorization of given integer coefficient squarefree polynomial \param{f}. The result \param{factors} have integer coefficients, injected from $\mathbb{F}_p$ to its minimum absolute representation.
   \spacing
   % added document
   \quad \negok The prime is chosen to be:
   \begin{enumerate}
   \item \param{f} is still squarefree mod \param{p},
   \item the number of factors is not greater than with the successive prime.
   \end{enumerate}
   %\spacing
   % input, output document
   \quad The given polynomial \param{f} must be poly.uniutil.IntegerPolynomial .\\
%
  \subsection{upper\_bound\_of\_coefficient --Landau-Mignotte bound of coefficients}\linkedone{poly.factor}{upper\_bound\_of\_coefficient}
   \func{upper\_bound\_of\_coefficient}
        {\hiki{f}{polynomial}}
        {\out{long}}\\
   \spacing
   % document of basic document
   \quad Compute Landau-Mignotte bound of coefficients of factors, whose degree is no greater than half of the given \param{f}.
   \spacing
   % added document
   %\quad \negok Additional argument \param{floatpre} specifies the precision of calculation in decimal digits.
   %\spacing
   % input, output document
   \quad The given polynomial \param{f} must have integer coefficients.\\
%
  \subsection{zassenhaus -- squarefree integer polynomial factorization by Zassenhaus method}\linkedone{poly.factor}{zassenhaus}
   \func{zassenhaus}
        {\hiki{f}{polynomial}}
        {\out{list of factors f}}\\
   \spacing
   % document of basic document
   \quad Factor a squarefree integer coefficient polynomial \param{f} with Berlekamp-Zassenhaus method.
   \spacing
   % added document
   %\quad
   %\spacing
   % input, output document
   %\quad output must be list of factors.
%
  \subsection{integerpolynomialfactorization -- Integer polynomial factorization}\linkedone{poly.factor}{integerpolynomialfactorization}
   \func{integerpolynomialfactorization}
        {\hiki{f}{polynomial}}
        {\out{factor}}\\
   \spacing
   % document of basic document
   \quad Factor an integer coefficient polynomial \param{f} with Berlekamp-Zassenhaus method.
   \spacing
   % added document
   %\quad \param{p} must be a prime integer and \param{d} be an integer such that 0 < \param{d} < 4\param{p} with $-\mathtt{d} \equiv 0, 1 \pmod{4}$.
   \spacing
   % input, output document
   \quad factor output by the form of list of tuples that formed (factor, index). \\
%
%\begin{ex}
%>>> module.func1(1, 0.1, "a", [], (1, 2))
%(2, "b")
%>>> module.func2()
%1
%\end{ex}%Don't indent!(indent causes an error.)
\C

%---------- end document ---------- %

\input{../footer}