% Created 2015-06-13 Sat 17:49
\documentclass[integrals, nointegrals, article, 12pt, a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{fixltx2e}
\usepackage{wrapfig}
\usepackage{soul}
\usepackage{textcomp}
\usepackage{marvosym}
\usepackage{wasysym}
\usepackage{latexsym}
\usepackage{amssymb}
\usepackage{hyperref}
\usepackage{graphicx}
\usepackage{longtable}
\usepackage{float}
\usepackage{geometry}
\usepackage{amsmath}
\usepackage{clrscode3e}
\usepackage{palatino}
\usepackage{euler}
\setcounter{secnumdepth}{2}
\geometry{a4paper, textwidth=6.5in, textheight=10in, marginparsep=7pt, marginparwidth=.6in}
\usepackage{amsthm}
\newtheorem{theorem}{Theorem}[section]
\newtheorem{lemma}[theorem]{Lemma}
\date{}
\title{Cache Optimized error correction.}
\hypersetup{
  pdfkeywords={},
  pdfsubject={},
  pdfcreator={Emacs 24.5.1 (Org mode 8.2.8)}}
\begin{document}

\maketitle

\section{Algorithm}
\label{sec-1}
We assume that the index of array and the level number starts with
$0$.  We say a search tree \emph{complete}, if at every level $i$ of the
tree has exactly $m(m+1)^{i}$ elements. We also assume $n$ is a
multiple of $m$ and $m \geq 3$.

\begin{codebox}
\Procname{$\proc{Cache-Aware-Search-Tree}(X, m)$}
\zi \kw{Input : } List of Elements, $X$ ; No. of Elements in a cache line, $m$
\zi \kw{Output : } Cache-Aware Search Tree of the list $X$ of size $n$, $CT$
\li $l \gets \lceil \log_{m+1} (n+1) \rceil$
\li $\proc{Init-Global}(m, l)$
\li Initialize $CT$ as a vector of size $n$.
\li $i \gets 0$; $CT[0] \gets 0$; $CT[1] \gets l$; $CT[m - 1] \gets n - 1$
\li $l_{ptr} \gets 0$ \Comment Pointer to the last inserted node
\li $c_{ptr} \gets 0$ \Comment Pointer to the current node
\li \While $i < n$
    \Do
\zi      \Comment $[x,y]$ range of indices covered by this subtree.
\li      $x \gets CT[c_{ptr}]$
\li      $y \gets CT[c_{ptr} + m - 1]$
\zi      \Comment $k$ is no. levels of current subtree including root.
\li      $k \gets CT[c_{ptr} + 1]$
\li      $d \gets y - x + 1$
\li      \If $d == m$
         \Then
\li
\li      $ST \gets \proc{Subtree-Size}(y - x + 1, k)$
\li      $y \gets x$
\li      \For $j \gets 0 \To m - 1$ \Comment Update entries for current node.
         \Do
\li           $y \gets y + ST[j]$
\li           $CT[c_{ptr} + j] \gets y$
         \End
\li      \For $j \gets 0 \To m$ \Comment Insert indices for sub-trees.
         \Do
\li           \If $ST[j] > 0$
              \Do
\li               $y \gets x + ST[j]$
\li               $l_{ptr} \gets l_{ptr} + m$
\li               $CT[l_{ptr}] \gets x$
\li               $CT[l_{ptr} + 1] \gets k - 1$
\li               $CT[l_{ptr} + m - 1] \gets y - 1$
\li               $x \gets y + 1$
              \End
        \End
\li     $i = i + m$; $c_{ptr} = c_{ptr} + m$
    \End
\li \Return $CT$
\end{codebox}

\begin{codebox}
\Procname{$\proc{Init-Global}(m, l)$}
\zi $A_1, A_2$ are global arrays of size $l$ each.
\li Initialize $A_1$ with $A_1[i] = m(m+1)^{i}$.
\zi \quad $A_1[i]$ is the number of elements at level $i$ of a
    complete $m$-ary search tree.
\li Initialize $A_2$ with $A_2[i] = \sum_{j = 0}^i A_1[j]$.
\zi \quad $A_2[i]$ is the total number of elements at upto
    level $i$ of a complete $m$-ary search tree.
\end{codebox}

\begin{codebox}
\Procname{$\proc{Subtree-Size}(d,k)$}
\zi \kw{Input : } No. of elements with in this subtree, $d$
\zi \kw{Input : } No. of Levels in the current subtree incl. root, $k$
\zi \kw{Output : } Size of each of the $m+1$ subtree sizes, $ST$
\li \If $d == m$ \Comment Last row : All zeroes
\li \Do Initialize $ST$ to $m+1$ zeros.
\li     \Return $ST$ \End
\li $d_k \gets d - A_2[k - 2]$ \Comment No. of elements in the last level
\li $q = d_k / A_1[k - 2]$
\li $r = d_k \% A_1[k - 2]$
\zi \Comment $LS$, No. elements in last row of $m+1$ sub-trees.
\li \For $j \gets 0 \To m$
\li \Do \If $j < q$
\li        \Then $LS[j] \gets A_1[k - 2]$
\li      \ElseIf $j > q$
\li        \Then $LS[j] \gets 0$
\li      \Else
\li         $LS[j] \gets r$ \End
    \End
\zi \Comment $ST$, Size of $m+1$ sub-trees
\li \For $j \gets 0 \To m$
\li \Do $ST[j] = LS[j] + A_2[k-2]$ \End
\li \Return $ST$
\end{codebox}

\section{Experimental Results}
\label{sec-2}

In order to demonstate how the layout datastructures behave with real
datasets, we used the datasets listed in table
\ref{tab:datasets}. Datasets are the same as that one used in (TODO: Refer
parallel error correction paper) and are available from the NCBI Short
Read Archive.

\begin{table}[htb]
\caption{\label{tab:datasets}Datasets for experimental validation}
\centering
\begin{tabular}{llrrr}
\hline
Dataset & Genome & No. of Reads & Read Length & Coverage\\
 &  & (millions) & (base pairs) & \\
\hline
D2 & \emph{E.Coli} & 8.9 & 101 & 193x\\
D3A & \emph{Droso. M} & 37.9 & 95 & 30x\\
D3B & \emph{Droso. M} & 41.5 & 35 & 12x\\
D3C & \emph{Droso. M} & 18.8 & 75 & 12x\\
\hline
\end{tabular}
\end{table}

Datasets D3A (SRX023452), D3B (SRX001651) and D3C(SRX001652) are
combined into a single dataset D3, having 98.2 million
reads. D2(SRR034501$\backslash$$_{\text{1}}$) and D3 are used in all our experiments. Since we
use the same parameters as used in (TODO: refer to the error correction
paper), we don't evaluate the quality of error correction. We only
evaluate the runtime performace for error correction runs of the
datasets D2 and D3 with the three different -- sorted order layout,
cache aware layout and cache oblivious layout.

\section{Results}
\label{sec-3}
\subsection{Kmer Table Sizes}
\label{sec-3-1}

\begin{table}[htb]
\caption{\label{tab:spectrum}$k$-mer spectrum and tile spectrum size}
\centering
\begin{tabular}{lrr}
\hline
Dataset & Kmer Table Size & Tile Table Size\\
\hline
D2 & 1699218 & 8830856\\
D3 & 6092949 & 240045877\\
\hline
\end{tabular}
\end{table}

\subsection{Dataset D2 (Hamming Distance 1)}
\label{sec-3-2}
\subsubsection{Summary}
\label{sec-3-2-1}

\begin{table}[htb]
\caption{\label{tab:d2h1run}Results for dataset $D2$ with $h = 1$}
\centering
\begin{tabular}{rrrrrrr}
\hline
 & k-Spectrum & Error & Cache Aware &  & Cache Oblivious & \\
Procs & Construction & Correction & Error Correction & Speedup & Error Correction & Speedup\\
 & Time (seconds) & Time (seconds) & Time (seconds) &  & Time (seconds) & \\
\hline
2 & 74.94 & 1326.61 & 739.76 & 1.79x & 858.30 & 1.54x\\
4 & 42.61 & 761.65 & 451.68 & 1.68x & 475.62 & 1.60x\\
8 & 22.66 & 335.53 & 244.57 & 1.37x & 249.76 & 1.34x\\
16 & 13.12 & 189.28 & 133.60 & 1.41x & 130.01 & 1.44x\\
32 & 7.71 & 98.92 & 71.72 & 1.38x & 69.10 & 1.43x\\
64 & 4.90 & 52.46 & 36.42 & 1.46x & 35.79 & 1.46x\\
128 & 4.24 & 28.02 & 19.71 & 1.42x & 19.23 & 1.45x\\
256 & 5.90 & 14.25 & 10.40 & 1.37x & 10.06 & 1.42x\\
512 & 13.72 & 7.65 & 5.60 & 1.37x & 5.54 & 1.38x\\
\hline
\end{tabular}
\end{table}

\subsubsection{Default run results}
\label{sec-3-2-2}

\begin{center}
\begin{tabular}{rrrr}
\hline
Procs & Construction & Error Correction & Total\\
 & Time (seconds) & Time (seconds) & Time (seconds)\\
\hline
2 & 74.94 & 1326.61 & 1406.62\\
4 & 42.61 & 761.65 & 808.91\\
8 & 22.66 & 335.53 & 359.56\\
16 & 13.12 & 189.28 & 203.14\\
32 & 7.71 & 98.92 & 107.12\\
64 & 4.90 & 52.46 & 57.59\\
128 & 4.24 & 28.02 & 32.40\\
256 & 5.90 & 14.25 & 20.37\\
512 & 13.72 & 7.65 & 22.10\\
\hline
\end{tabular}
\end{center}

\subsubsection{Cache Aware results}
\label{sec-3-2-3}

\begin{center}
\begin{tabular}{rrrr}
\hline
Procs & Construction & Error Correction & Total\\
 & Time (seconds) & Time (seconds) & Time (seconds)\\
\hline
2 & 68.32 & 739.76 & 813.68\\
4 & 37.69 & 451.68 & 491.88\\
8 & 22.65 & 244.57 & 268.59\\
16 & 12.12 & 133.60 & 147.47\\
32 & 7.60 & 71.72 & 80.82\\
64 & 4.90 & 36.42 & 41.51\\
128 & 4.10 & 19.71 & 24.77\\
256 & 5.80 & 10.40 & 16.80\\
512 & 13.10 & 5.60 & 19.52\\
\hline
\end{tabular}
\end{center}

\subsubsection{Cache Oblivious results}
\label{sec-3-2-4}

\begin{center}
\begin{tabular}{rrrr}
\hline
Procs & Construction & Error Correction & Total\\
 & Time (seconds) & Time (seconds) & Time (seconds)\\
\hline
2 & 75.24 & 858.30 & 948.21\\
4 & 42.07 & 475.62 & 520.45\\
8 & 23.65 & 249.76 & 274.82\\
16 & 13.14 & 130.01 & 147.21\\
32 & 7.65 & 69.10 & 77.21\\
64 & 4.72 & 35.79 & 40.83\\
128 & 4.38 & 19.23 & 23.14\\
256 & 6.36 & 10.06 & 16.49\\
512 & 13.34 & 5.54 & 19.61\\
\hline
\end{tabular}
\end{center}

\subsection{Dataset D2 (Hamming Distance = 2)}
\label{sec-3-3}

\subsubsection{Summary}
\label{sec-3-3-1}

\begin{table}[htb]
\caption{\label{tab:d2h1run}Results for dataset $D2$ with $h = 1$}
\centering
\begin{tabular}{rrrrrrr}
\hline
 & k-Spectrum & Error & Cache Aware &  & Cache Oblivious & \\
Procs & Construction & Correction & Error Correction & Speedup & Error Correction & Speedup\\
 & Time (seconds) & Time (seconds) & Time (seconds) &  & Time (seconds) & \\
\hline
64 & 4.79 & 5820.63 & 2430.41 & 2.39 & 3430.27 & 1.69\\
128 & 4.06 & 2868.85 & 1315.91 & 2.18 & 1819.92 & 1.57\\
256 & 6.19 & 1627.04 & 740.60 & 2.19 & 1042.59 & 1.56\\
512 & 13.06 & 835.94 & 380.16 & 2.19 & 537.66 & 1.55\\
\hline
\end{tabular}
\end{table}

\subsubsection{Default run results}
\label{sec-3-3-2}

\begin{center}
\begin{tabular}{rrrr}
\hline
Procs & Construction & Error Correction & Total\\
 & Time (seconds) & Time (seconds) & Time (seconds)\\
\hline
64 & 4.79 & 5820.63 & 5287.87\\
128 & 4.06 & 2868.85 & 2874.39\\
256 & 6.19 & 1627.04 & 1693.27\\
512 & 13.06 & 835.94 & 908.36\\
\hline
\end{tabular}
\end{center}

\subsubsection{Cache Aware results}
\label{sec-3-3-3}

\begin{center}
\begin{tabular}{rrrr}
\hline
Procs & Construction & Error Correction & Total\\
 & Time (seconds) & Time (seconds) & Time (seconds)\\
\hline
64 & 4.83 & 2430.41 & 2495.45\\
128 & 4.10 & 1315.91 & 1321.59\\
256 & 5.86 & 740.60 & 747.63\\
512 & 14.1 & 380.16 & 394.61\\
\hline
\end{tabular}
\end{center}

\subsubsection{Cache Oblivious results}
\label{sec-3-3-4}

\begin{center}
\begin{tabular}{rrrr}
\hline
Procs & Construction & Error Correction & Total\\
 & Time (seconds) & Time (seconds) & Time (seconds)\\
\hline
64 & 4.80 & 3430.27 & 3435.68\\
128 & 4.07 & 1819.92 & 1825.67\\
256 & 6.83 & 1042.59 & 1050.28\\
512 & 13.01 & 537.66 & 551.67\\
\hline
\end{tabular}
\end{center}

\subsection{Dataset D3 (Hamming Distance 1)}
\label{sec-3-4}
\subsubsection{Default run results}
\label{sec-3-4-1}

\begin{center}
\begin{tabular}{rrrr}
\hline
Procs & Construction & Error Correction & Total\\
 & Time (seconds) & Time (seconds) & Time (seconds)\\
\hline
8 & 742.81 & 1393.49 & 2161.24\\
16 & 301.14 & 909.75 & 1242.94\\
32 & 95.42 & 521.19 & 622.65\\
64 & 56.96 & 268.58 & 328.34\\
128 & 36.03 & 139.88 & 177.49\\
256 & 27.98 & 89.03 & 117.85\\
512 & 32.55 & 53.81 & 87.44\\
\hline
\end{tabular}
\end{center}

\subsubsection{Cache Aware results}
\label{sec-3-4-2}

\begin{center}
\begin{tabular}{rrrr}
\hline
Procs & Construction & Error Correction & Total\\
 & Time (seconds) & Time (seconds) & Time (seconds)\\
\hline
8 &  &  & \\
16 & 325.56 & 597.92 & 959.25\\
32 & 95.07 & 339.56 & 440.89\\
64 & 56.71 & 177.45 & 237.06\\
128 & 36.47 & 95.91 & 133.95\\
256 & 27.65 & 57.54 & 85.99\\
512 & 31.31 & 36.12 & 68.50\\
\hline
\end{tabular}
\end{center}

\subsubsection{Cache Oblivious results}
\label{sec-3-4-3}

\begin{center}
\begin{tabular}{rrrr}
\hline
Procs & Construction & Error Correction & Total\\
 & Time (seconds) & Time (seconds) & Time (seconds)\\
\hline
8 &  &  & \\
16 & 277.21 & 591.01 & 895.64\\
32 & 95.85 & 343.65 & 442.24\\
64 & 56.62 & 175.89 & 241.81\\
128 & 36.34 & 93.65 & 135.92\\
256 & 28.24 & 60.75 & 89.78\\
512 & 31.28 & 47.29 & 81.26\\
\hline
\end{tabular}
\end{center}

\subsection{Dataset D3 (Hamming Distance = 2)}
\label{sec-3-5}
\subsubsection{Summary}
\label{sec-3-5-1}
\begin{table}[htb]
\caption{\label{tab:d3h2run}Results for dataset $D3$ with $h = 2$}
\centering
\begin{tabular}{rrrrrrr}
\hline
 & k-Spectrum & Error & Cache Aware &  & Cache Oblivious & \\
Procs & Construction & Correction & Error Correction & Speedup & Error Correction & Speedup\\
 & Time (seconds) & Time (seconds) & Time (seconds) &  & Time (seconds) & \\
\hline
256 & 27.49 & 5816.80 & 2633.96 & 2.21 & 3600.86 & 1.61\\
512 & 33.04 & 3503.59 & 1611.09 & 2.17 & 2184.29 & 1.60\\
1024 & 53.40 & 2156.35 & 1071.46 & 2.01 & 1313.32 & 1.64\\
\hline
\end{tabular}
\end{table}

\subsubsection{Default run results}
\label{sec-3-5-2}

\begin{center}
\begin{tabular}{rrrr}
\hline
Procs & Construction & Error Correction & Total\\
 & Time (seconds) & Time (seconds) & Time (seconds)\\
\hline
256 & 27.49 & 5816.80 & 5865.32\\
512 & 33.04 & 3503.59 & 3544.15\\
1024 & 53.40 & 2156.35 & 2215.19\\
\hline
\end{tabular}
\end{center}

\subsubsection{Cache Aware run results}
\label{sec-3-5-3}

\begin{center}
\begin{tabular}{rrrr}
\hline
Procs & Construction & Error Correction & Total\\
 & Time (seconds) & Time (seconds) & Time (seconds)\\
\hline
256 & 27.64 & 2633.96 & 2682.89\\
512 & 31.87 & 1611.09 & 1644.02\\
1024 & 53.62 & 1071.46 & 1130.10\\
\hline
\end{tabular}
\end{center}

\subsubsection{Cache Oblivious run results}
\label{sec-3-5-4}

\begin{center}
\begin{tabular}{rrrr}
\hline
Procs & Construction & Error Correction & Total\\
 & Time (seconds) & Time (seconds) & Time (seconds)\\
\hline
256 & 28.27 & 3600.86 & 3649.69\\
512 & 32.67 & 2184.29 & 2224.49\\
1024 & 56.61 & 1313.32 & 1373.40\\
\hline
\end{tabular}
\end{center}

\section{Work Distribution Notes}
\label{sec-4}

We will use a master-slave pattern to dynamically distribute
work. Suppose, we use p processes for the error correction, and each
process uses k + 1 shared memory threads.  In each process, we allocate
one thread completely dedicated to handle all the inter-process
communincations and work assignment. I call this thread 'the
co-ordination thread'. This thread doesn't do any error correction (EC)
work. The rest of the k worker threads will only do the EC work. In our
implementation, we will use the the root process for the master process.

In the mater process, the following are the reponsibilities of a
co-ordination thread:
\begin{enumerate}
\item Assign work to k local worker threads.
\item Poll for any work request from slave process. If any slave process
asks for work, assign work for them.
\item When there is no more work to assign, notify every one.
\end{enumerate}

In the slave process, a co-ordination thread's responsibilities are as
follows:
\begin{enumerate}
\item If we are running low on work assignment, ask work from master
process.
\item Recieve work from master process and distribute it to the local
worker threads.
\end{enumerate}

An EC work-item is represented by an offset in the input file. This is
position starting from which a worker thread starts reading and
continues to do error correction for a predifined chunk. Communication
between the co-ordination thread and the worker threads with in a
process is accomplished via a shared queue. The co-ordination thread
loads the work-item to queue, from which the worker threads pops the
item and proceeds to do the error correction. When the queue size is
below a given threshold, the co-ordination threads pre-emptively
requests work from the master process. The master process always sends k
work-items. Right now the threshold is kept as 2k, and hence the work
queue size is always bounded by 3k work items.

Worker thread is dumb in the sense that it goes on an infinite loop : it
does error correction, looks at the work queue for the next chunk and so
on. Worker processes break out of the loop, when a shared boolean
variable is set to true.

The state transitions of the co-ordination thread is as follows:
Initially, the co-ordination thread is at "ASSIGN$_{\text{WORK}}$" state. In this
state this thread in a slave process monitors the work queue, and if its
size falls below 2k, it requests work-items from the master
process. After receiving the work items, it pushes them into the work
queue. In the master process, this thread fulfills the slaves' requests,
and performs work-item assignment for local worker threads. When there
is no more work available for assignment, we move to the next state :
"PENDING$_{\text{WORK}}$". This state represents the situation that there is no
more work to assign, but the work-queue is not empty i.e., there are
still work-items left to be claimed by the dumb workers. In this state,
the co-ord thread in a slave process will just monitor the work queue
and wait for it to become empty. In the master process, the co-ord
thread at this state will poll for any slave requests, while monitoring
the work queue. This thread also sends the "No more work is available to
assign" signal by sending assigning 'zero work'. This thread can move to
next state only if it has sent 'zero work' signal to all the slave
processes. The next state is 'FINISHED$_{\text{WORK'}}$. At this state, there is
nothing more to do for the co-ord threads. It sets the shared boolean
variable to true and waits for the worker threads to finish the last
error correction work items.

Page 3:
Add SRX027713 and SRX027583 as the references for the human dataset.

Page 4: (right column: 2nd paragraph)
\begin{itemize}
\item The work-queue can hold up to 3 × M chunks at any given time.
\end{itemize}
Page 4: (right column: 4th paragraph)
\begin{itemize}
\item Each local-master is responsible for maintaining a work-queue of size
3 x M chunks.
\end{itemize}

Comment: We maintain only 2 x M work-chunks in the queue at a
time. However, the initial queue size is 3 x M work-chunks because we
want to avoid work requests from local masters as soon as the error
correction is started. Suppose if the initial queue size is less than 3
x M, which implies that after M work-chunks are taken up by the worker
threads, we will have less than 2 x M left in the queue. This
immediately causes the local master to request the global master for
work. By keeping the initial queue size 3 x M, we avoid the initial
flood of requests.

Page 4: (right column: 3rd paragraph)
\begin{itemize}
\item After communicating the no−more−work message to all the local-masters,
\end{itemize}
the global master waits for all the local-masters to complete the work
previously requested by them.

Comment : No, global-master doesn't wait for the local-master. It waits
to make sure only two things:
\begin{enumerate}
\item All local-masters have recieved the "no-more-work" message. This is
done by counting how many times "no-more-work" message has been sent.
\item global-masters' own local workers have completed their work.
\end{enumerate}
If the above two are done, global-master just go ahead and does
MPI$_{\text{finalize}}$. Here, also it doesn't wait for local-masters -- only that
it announces that there is nothing more to do.

Page 5:(left column: 1st paragraph)
\begin{itemize}
\item The local-master then sends a pending − work − done message to the
global-master and exits.
\end{itemize}

Comment : No, the local-master doesn't send any message to global
master. The "pending-work" is just a state maintained by local masters
to no longer request work from the master and just wait until every
local worker is done error correction.

Page 5:(right column: 1st paragraph)
\begin{itemize}
\item By taking the network-latency of our cluster into account, a choice of
500 reads for the chunk size achieves a good trade-off between the two
conflicting requirements.
\end{itemize}

Comment: Also, note that it also depends on the dataset on how much work
500 reads consume.

Page 7:(results)

Comment: Do we have to mention that we don't use the parallel
cache-aware construction algorithm in our experiments ?
% Emacs 24.5.1 (Org mode 8.2.8)
\end{document}


\newtheorem{cscexample}{Example}

\achapter{\protect{Generalized rewriting}}
\aauthor{Matthieu Sozeau}
\label{setoids}

This chapter presents the extension of several equality related tactics
to work over user-defined structures (called setoids) that are equipped
with ad-hoc equivalence relations meant to behave as equalities.
Actually, the tactics have also been generalized to relations weaker
then equivalences (e.g. rewriting systems). The toolbox also extends the
automatic rewriting capabilities of the system, allowing the specification of
custom strategies for rewriting.

This documentation is adapted from the previous setoid documentation by
Claudio Sacerdoti Coen (based on previous work by Cl\'ement Renard).
The new implementation is a drop-in replacement for the old one,\footnote{Nicolas
Tabareau helped with the gluing.} hence most of the documentation still applies.

The work is a complete rewrite of the previous implementation, based on
the type class infrastructure. It also improves on and generalizes
the previous implementation in several ways:
\begin{itemize}
\item User-extensible algorithm. The algorithm is separated in two
  parts: generations of the rewriting constraints (done in ML) and
  solving of these constraints using type class resolution. As type
  class resolution is extensible using tactics, this allows users to define
  general ways to solve morphism constraints.
\item Sub-relations. An example extension to the base algorithm is the
  ability to define one relation as a subrelation of another so that
  morphism declarations on one relation can be used automatically for
  the other. This is done purely using tactics and type class search.
\item Rewriting under binders. It is possible to rewrite under binders
  in the new implementation, if one provides the proper
  morphisms. Again, most of the work is handled in the tactics.
\item First-class morphisms and signatures. Signatures and morphisms are
  ordinary Coq terms, hence they can be manipulated inside Coq, put
  inside structures and lemmas about them can be proved inside the
  system. Higher-order morphisms are also allowed.
\item Performance. The implementation is based on a depth-first search for the first
  solution to a set of constraints which can be as fast as linear in the
  size of the term, and the size of the proof term is linear
  in the size of the original term. Besides, the extensibility allows the
  user to customize the proof search if necessary.
\end{itemize}

\asection{Introduction to generalized rewriting}

\subsection{Relations and morphisms}

A parametric \emph{relation} \texttt{R} is any term of type
\texttt{forall ($x_1$:$T_1$) \ldots ($x_n$:$T_n$), relation $A$}. The
expression $A$, which depends on $x_1$ \ldots $x_n$, is called the
\emph{carrier} of the relation and \texttt{R} is
said to be a relation over \texttt{A}; the list $x_1,\ldots,x_n$
is the (possibly empty) list of parameters of the relation.

\firstexample
\begin{cscexample}[Parametric relation]
It is possible to implement finite sets of elements of type \texttt{A}
as unordered list of elements of type \texttt{A}. The function
\texttt{set\_eq: forall (A: Type), relation (list A)} satisfied by two lists
with the same elements is a parametric relation over \texttt{(list A)} with
one parameter \texttt{A}. The type of \texttt{set\_eq} is convertible with
\texttt{forall (A: Type), list A -> list A -> Prop}.
\end{cscexample}

An \emph{instance} of a parametric relation \texttt{R} with $n$ parameters
is any term \texttt{(R $t_1$ \ldots $t_n$)}.

Let \texttt{R} be a relation over \texttt{A} with $n$ parameters.
A term is a parametric proof of reflexivity for \texttt{R} if it has type
\texttt{forall ($x_1$:$T_1$) \ldots ($x_n$:$T_n$),
 reflexive (R $x_1$ \ldots $x_n$)}. Similar definitions are given for
parametric proofs of symmetry and transitivity.

\begin{cscexample}[Parametric relation (cont.)]
The \texttt{set\_eq} relation of the previous example can be proved to be
reflexive, symmetric and transitive.
\end{cscexample}

A parametric unary function $f$ of type
\texttt{forall ($x_1$:$T_1$) \ldots ($x_n$:$T_n$), $A_1$ -> $A_2$}
covariantly respects two parametric relation instances $R_1$ and $R_2$ if,
whenever $x, y$ satisfy $R_1~x~y$, their images $(f~x)$ and $(f~y)$
satisfy $R_2~(f~x)~(f~y)$ . An $f$ that respects its input and output relations
will be called a unary covariant \emph{morphism}. We can also say that $f$ is
a monotone function with respect to $R_1$ and $R_2$.
The sequence $x_1,\ldots x_n$ represents the parameters of the morphism.

Let $R_1$ and $R_2$ be two parametric relations.
The \emph{signature} of a parametric morphism of type
\texttt{forall ($x_1$:$T_1$) \ldots ($x_n$:$T_n$), $A_1$ -> $A_2$} that
covariantly respects two instances $I_{R_1}$ and $I_{R_2}$ of $R_1$ and $R_2$ is written $I_{R_1} \texttt{++>} I_{R_2}$.
Notice that the special arrow \texttt{++>}, which reminds the reader
of covariance, is placed between the two relation instances, not
between the two carriers. The signature relation instances and morphism will
be typed in a context introducing variables for the parameters.

The previous definitions are extended straightforwardly to $n$-ary morphisms,
that are required to be simultaneously monotone on every argument.

Morphisms can also be contravariant in one or more of their arguments.
A morphism is contravariant on an argument associated to the relation instance
$R$ if it is covariant on the same argument when the inverse relation
$R^{-1}$ (\texttt{inverse R} in Coq) is considered.
The special arrow \texttt{-{}->} is used in signatures
for contravariant morphisms.

Functions having arguments related by symmetric relations instances are both
covariant and contravariant in those arguments. The special arrow
\texttt{==>} is used in signatures for morphisms that are both covariant
and contravariant.

An instance of a parametric morphism $f$ with $n$ parameters is any term
\texttt{f $t_1$ \ldots $t_n$}.

\begin{cscexample}[Morphisms]
Continuing the previous example, let
\texttt{union: forall (A: Type), list A -> list A -> list A} perform the union
of two sets by appending one list to the other. \texttt{union} is a binary
morphism parametric over \texttt{A} that respects the relation instance
\texttt{(set\_eq A)}. The latter condition is proved by showing
\texttt{forall (A: Type) (S1 S1' S2 S2': list A), set\_eq A S1 S1' ->
 set\_eq A S2 S2' -> set\_eq A (union A S1 S2) (union A S1' S2')}.

The signature of the function \texttt{union A} is
\texttt{set\_eq A ==> set\_eq A ==> set\_eq A} for all \texttt{A}.
\end{cscexample}

\begin{cscexample}[Contravariant morphism]
The division function \texttt{Rdiv: R -> R -> R} is a morphism of
signature \texttt{le ++> le -{}-> le} where \texttt{le} is
the usual order relation over real numbers. Notice that division is
covariant in its first argument and contravariant in its second
argument.
\end{cscexample}

Leibniz equality is a relation and every function is a
morphism that respects Leibniz equality. Unfortunately, Leibniz equality
is not always the intended equality for a given structure.

In the next section we will describe the commands to register terms as
parametric relations and morphisms. Several tactics that deal with equality
in \Coq\ can also work with the registered relations.
The exact list of tactic will be given in Sect.~\ref{setoidtactics}.
For instance, the
tactic \texttt{reflexivity} can be used to close a goal $R~n~n$ whenever
$R$ is an instance of a registered reflexive relation. However, the tactics
that replace in a context $C[]$ one term with another one related by $R$
must verify that $C[]$ is a morphism that respects the intended relation.
Currently the verification consists in checking whether $C[]$ is a syntactic
composition of morphism instances that respects some obvious
compatibility constraints.

\begin{cscexample}[Rewriting]
Continuing the previous examples, suppose that the user must prove
\texttt{set\_eq int (union int (union int S1 S2) S2) (f S1 S2)} under the
hypothesis \texttt{H: set\_eq int S2 (nil int)}. It is possible to
use the \texttt{rewrite} tactic to replace the first two occurrences of
\texttt{S2} with \texttt{nil int} in the goal since the context
\texttt{set\_eq int (union int (union int S1 nil) nil) (f S1 S2)}, being
a composition of morphisms instances, is a morphism. However the tactic
will fail replacing the third occurrence of \texttt{S2} unless \texttt{f}
has also been declared as a morphism.
\end{cscexample}

\subsection{Adding new relations and morphisms}
A parametric relation
\textit{Aeq}\texttt{: forall ($y_1 : \beta_!$ \ldots $y_m : \beta_m$), relation (A $t_1$ \ldots $t_n$)} over
\textit{(A : $\alpha_i$ -> \ldots $\alpha_n$ -> }\texttt{Type})
can be declared with the following command:

\comindex{Add Parametric Relation}
\begin{quote}
  \texttt{Add Parametric Relation} ($x_1 : T_1$) \ldots ($x_n : T_k$) :
  \textit{(A $t_1$ \ldots $t_n$) (Aeq $t'_1$ \ldots $t'_m$)}\\
  ~\zeroone{\texttt{reflexivity proved by} \textit{refl}}\\
  ~\zeroone{\texttt{symmetry proved by} \textit{sym}}\\
  ~\zeroone{\texttt{transitivity proved by} \textit{trans}}\\
  \texttt{~as} \textit{id}.
\end{quote}
after having required the \texttt{Setoid} module with the
\texttt{Require Setoid} command.

The identifier \textit{id} gives a unique name to the morphism and it is
used by the command to generate fresh names for automatically provided lemmas
used internally.

Notice that the carrier and relation parameters may refer to the context
of variables introduced at the beginning of the declaration, but the
instances need not be made only of variables.
Also notice that \textit{A} is \emph{not} required to be a term
having the same parameters as \textit{Aeq}, although that is often the
case in practice (this departs from the previous implementation).

\comindex{Add Relation}
In case the carrier and relations are not parametric, one can use the
command \texttt{Add Relation} instead, whose syntax is the same except
there is no local context.

The proofs of reflexivity, symmetry and transitivity can be omitted if the
relation is not an equivalence relation. The proofs must be instances of the
corresponding relation definitions: e.g. the proof of reflexivity must
have a type convertible to \texttt{reflexive (A $t_1$ \ldots $t_n$) (Aeq $t'_1$ \ldots
  $t'_n$)}. Each proof may refer to the introduced variables as well.

\begin{cscexample}[Parametric relation]
For Leibniz equality, we may declare:
\texttt{Add Parametric Relation (A : Type) :} \texttt{A (@eq A)}\\
~\zeroone{\texttt{reflexivity proved by} \texttt{@refl\_equal A}}\\
\ldots
\end{cscexample}

Some tactics
(\texttt{reflexivity}, \texttt{symmetry}, \texttt{transitivity}) work only
on relations that respect the expected properties. The remaining tactics
(\texttt{replace}, \texttt{rewrite} and derived tactics such as
\texttt{autorewrite}) do not require any properties over the relation.
However, they are able to replace terms with related ones only in contexts
that are syntactic compositions of parametric morphism instances declared with
the following command.

\comindex{Add Parametric Morphism}
\begin{quote}
  \texttt{Add Parametric Morphism} ($x_1 : \T_!$) \ldots ($x_k : \T_k$)\\
  (\textit{f $t_1$ \ldots $t_n$})\\
  \texttt{~with signature} \textit{sig}\\
  \texttt{~as id}.\\
  \texttt{Proof}\\
  ~\ldots\\
  \texttt{Qed}
\end{quote}

The command declares \textit{f} as a parametric morphism of signature
\textit{sig}. The identifier \textit{id} gives a unique name to the morphism
and it is used as the base name of the type class instance definition
and as the name of the lemma that proves the well-definedness of the morphism.
The parameters of the morphism as well as the signature may refer to the
context of variables.
The command asks the user to prove interactively that \textit{f} respects
the relations identified from the signature.

\begin{cscexample}
We start the example by assuming a small theory over homogeneous sets and
we declare set equality as a parametric equivalence relation and
union of two sets as a parametric morphism.
\begin{coq_example*}
Require Export Setoid.
Require Export Relation_Definitions.
Set Implicit Arguments.
Parameter set: Type -> Type.
Parameter empty: forall A, set A.
Parameter eq_set: forall A, set A -> set A -> Prop.
Parameter union: forall A, set A -> set A -> set A.
Axiom eq_set_refl: forall A, reflexive _ (eq_set (A:=A)).
Axiom eq_set_sym: forall A, symmetric _ (eq_set (A:=A)).
Axiom eq_set_trans: forall A, transitive _ (eq_set (A:=A)).
Axiom empty_neutral: forall A (S: set A), eq_set (union S (empty A)) S.
Axiom union_compat:
 forall (A : Type),
  forall x x' : set A, eq_set x x' ->
  forall y y' : set A, eq_set y y' ->
   eq_set (union x y) (union x' y').
Add Parametric Relation A : (set A) (@eq_set A)
 reflexivity proved by (eq_set_refl (A:=A))
 symmetry proved by (eq_set_sym (A:=A))
 transitivity proved by (eq_set_trans (A:=A))
 as eq_set_rel.
Add Parametric Morphism A : (@union A) with
signature (@eq_set A) ==> (@eq_set A) ==> (@eq_set A) as union_mor.
Proof. exact (@union_compat A). Qed.
\end{coq_example*}

\end{cscexample}

It is possible to reduce the burden of specifying parameters using
(maximally inserted) implicit arguments. If \texttt{A} is always set as
maximally implicit in the previous example, one can write:

\begin{coq_eval}
Reset Initial.
Require Export Setoid.
Require Export Relation_Definitions.
Parameter set: Type -> Type.
Parameter empty: forall {A}, set A.
Parameter eq_set: forall {A}, set A -> set A -> Prop.
Parameter union: forall {A}, set A -> set A -> set A.
Axiom eq_set_refl: forall {A}, reflexive (set A) eq_set.
Axiom eq_set_sym: forall {A}, symmetric (set A) eq_set.
Axiom eq_set_trans: forall {A}, transitive (set A) eq_set.
Axiom empty_neutral: forall A (S: set A), eq_set (union S empty) S.
Axiom union_compat:
 forall (A : Type),
  forall x x' : set A, eq_set x x' ->
  forall y y' : set A, eq_set y y' ->
   eq_set (union x y) (union x' y').
\end{coq_eval}

\begin{coq_example*}
Add Parametric Relation A : (set A) eq_set
 reflexivity proved by eq_set_refl
 symmetry proved by eq_set_sym
 transitivity proved by eq_set_trans
 as eq_set_rel.
Add Parametric Morphism A : (@union A) with
  signature eq_set ==> eq_set ==> eq_set as union_mor.
Proof. exact (@union_compat A). Qed.
\end{coq_example*}

We proceed now by proving a simple lemma performing a rewrite step
and then applying reflexivity, as we would do working with Leibniz
equality. Both tactic applications are accepted
since the required properties over \texttt{eq\_set} and
\texttt{union} can be established from the two declarations above.

\begin{coq_example*}
Goal forall (S: set nat),
 eq_set (union (union S empty) S) (union S S).
Proof. intros. rewrite empty_neutral. reflexivity. Qed.
\end{coq_example*}

The tables of relations and morphisms are managed by the type class
instance mechanism. The behavior on section close is to generalize
the instances by the variables of the section (and possibly hypotheses
used in the proofs of instance declarations) but not to export them in
the rest of the development for proof search. One can use the
\texttt{Existing Instance} command to do so outside the section,
using the name of the declared morphism suffixed by \texttt{\_Morphism},
or use the \texttt{Global} modifier for the corresponding class instance
declaration (see \S\ref{setoid:first-class}) at definition time.
When loading a compiled file or importing a module,
all the declarations of this module will be loaded.

\subsection{Rewriting and non reflexive relations}
To replace only one argument of an n-ary morphism it is necessary to prove
that all the other arguments are related to themselves by the respective
relation instances.

\begin{cscexample}
To replace \texttt{(union S empty)} with \texttt{S} in
\texttt{(union (union S empty) S) (union S S)} the rewrite tactic must
exploit the monotony of \texttt{union} (axiom \texttt{union\_compat} in
the previous example). Applying \texttt{union\_compat} by hand we are left
with the goal \texttt{eq\_set (union S S) (union S S)}.
\end{cscexample}

When the relations associated to some arguments are not reflexive, the tactic
cannot automatically prove the reflexivity goals, that are left to the user.

Setoids whose relation are partial equivalence relations (PER)
are useful to deal with partial functions. Let \texttt{R} be a PER. We say
that an element \texttt{x} is defined if \texttt{R x x}. A partial function
whose domain comprises all the defined elements only is declared as a
morphism that respects \texttt{R}. Every time a rewriting step is performed
the user must prove that the argument of the morphism is defined.

\begin{cscexample}
Let \texttt{eqO} be \texttt{fun x y => x = y $\land$ ~x$\neq$ 0} (the smaller PER over
non zero elements). Division can be declared as a morphism of signature
\texttt{eq ==> eq0 ==> eq}. Replace \texttt{x} with \texttt{y} in
\texttt{div x n = div y n} opens the additional goal \texttt{eq0 n n} that
is equivalent to \texttt{n=n $\land$ n$\neq$0}.
\end{cscexample}

\subsection{Rewriting and non symmetric relations}
When the user works up to relations that are not symmetric, it is no longer
the case that any covariant morphism argument is also contravariant. As a
result it is no longer possible to replace a term with a related one in
every context, since the obtained goal implies the previous one if and
only if the replacement has been performed in a contravariant position.
In a similar way, replacement in an hypothesis can be performed only if
the replaced term occurs in a covariant position.

\begin{cscexample}[Covariance and contravariance]
Suppose that division over real numbers has been defined as a
morphism of signature \texttt{Z.div: Z.lt ++> Z.lt -{}-> Z.lt} (i.e.
\texttt{Z.div} is increasing in its first argument, but decreasing on the
second one). Let \texttt{<} denotes \texttt{Z.lt}.
Under the hypothesis \texttt{H: x < y} we have
\texttt{k < x / y -> k < x / x}, but not
\texttt{k < y / x -> k < x / x}.
Dually, under the same hypothesis \texttt{k < x / y -> k < y / y} holds,
but \texttt{k < y / x -> k < y / y} does not.
Thus, if the current goal is \texttt{k < x / x}, it is possible to replace
only the second occurrence of \texttt{x} (in contravariant position)
with \texttt{y} since the obtained goal must imply the current one.
On the contrary, if \texttt{k < x / x} is
an hypothesis, it is possible to replace only the first occurrence of
\texttt{x} (in covariant position) with \texttt{y} since
the current hypothesis must imply the obtained one.
\end{cscexample}

Contrary to the previous implementation, no specific error message will
be raised when trying to replace a term that occurs in the wrong
position. It will only fail because the rewriting constraints are not
satisfiable. However it is possible to use the \texttt{at} modifier to
specify which occurrences should be rewritten.

As expected, composing morphisms together propagates the variance annotations by
switching the variance every time a contravariant position is traversed.
\begin{cscexample}
Let us continue the previous example and let us consider the goal
\texttt{x / (x / x) < k}. The first and third occurrences of \texttt{x} are
in a contravariant position, while the second one is in covariant position.
More in detail, the second occurrence of \texttt{x} occurs
covariantly in \texttt{(x / x)} (since division is covariant in its first
argument), and thus contravariantly in \texttt{x / (x / x)} (since division
is contravariant in its second argument), and finally covariantly in
\texttt{x / (x / x) < k} (since \texttt{<}, as every transitive relation,
is contravariant in its first argument with respect to the relation itself).
\end{cscexample}

\subsection{Rewriting in ambiguous setoid contexts}
One function can respect several different relations and thus it can be
declared as a morphism having multiple signatures.

\begin{cscexample}
Union over homogeneous lists can be given all the following signatures:
\texttt{eq ==> eq ==> eq} (\texttt{eq} being the equality over ordered lists)
\texttt{set\_eq ==> set\_eq ==> set\_eq} (\texttt{set\_eq} being the equality
over unordered lists up to duplicates),
\texttt{multiset\_eq ==> multiset\_eq ==> multiset\_eq} (\texttt{multiset\_eq}
being the equality over unordered lists).
\end{cscexample}

To declare multiple signatures for a morphism, repeat the \texttt{Add Morphism}
command.

When morphisms have multiple signatures it can be the case that a rewrite
request is ambiguous, since it is unclear what relations should be used to
perform the rewriting. Contrary to the previous implementation, the
tactic will always choose the first possible solution to the set of
constraints generated by a rewrite and will not try to find \emph{all}
possible solutions to warn the user about.

\asection{Commands and tactics}
\subsection{First class setoids and morphisms}
\label{setoid:first-class}

The implementation is based on a first-class representation of
properties of relations and morphisms as type classes. That is,
the various combinations of properties on relations and morphisms
are represented as records and instances of theses classes are put
in a hint database.
For example, the declaration:

\begin{quote}
  \texttt{Add Parametric Relation} ($x_1 : T_1$) \ldots ($x_n : T_k$) :
  \textit{(A $t_1$ \ldots $t_n$) (Aeq $t'_1$ \ldots $t'_m$)}\\
  ~\zeroone{\texttt{reflexivity proved by} \textit{refl}}\\
  ~\zeroone{\texttt{symmetry proved by} \textit{sym}}\\
  ~\zeroone{\texttt{transitivity proved by} \textit{trans}}\\
  \texttt{~as} \textit{id}.
\end{quote}

is equivalent to an instance declaration:

\begin{quote}
  \texttt{Instance} ($x_1 : T_1$) \ldots ($x_n : T_k$) \texttt{=>}
  \textit{id} : \texttt{@Equivalence} \textit{(A $t_1$ \ldots $t_n$) (Aeq
    $t'_1$ \ldots $t'_m$)} :=\\
  ~\zeroone{\texttt{Equivalence\_Reflexive :=} \textit{refl}}\\
  ~\zeroone{\texttt{Equivalence\_Symmetric :=} \textit{sym}}\\
  ~\zeroone{\texttt{Equivalence\_Transitive :=} \textit{trans}}.
\end{quote}

The declaration itself amounts to the definition of an object of the
record type \texttt{Coq.Classes.RelationClasses.Equivalence} and a
hint added to the \texttt{typeclass\_instances} hint database.
Morphism declarations are also instances of a type class defined in
\texttt{Classes.Morphisms}.
See the documentation on type classes \ref{typeclasses} and
the theories files in \texttt{Classes} for further explanations.

One can inform the rewrite tactic about morphisms and relations just by
using the typeclass mechanism to declare them using \texttt{Instance}
and \texttt{Context} vernacular commands.
Any object of type \texttt{Proper} (the type of morphism declarations)
in the local context will also be automatically used by the rewriting
tactic to solve constraints.

Other representations of first class setoids and morphisms can also
be handled by encoding them as records. In the following example,
the projections of the setoid relation and of the morphism function
can be registered as parametric relations and morphisms.
\begin{cscexample}[First class setoids]

\begin{coq_example*}
Require Import Relation_Definitions Setoid.
Record Setoid: Type :=
{ car:Type;
  eq:car->car->Prop;
  refl: reflexive _ eq;
  sym: symmetric _ eq;
  trans: transitive _ eq
}.
Add Parametric Relation (s : Setoid) : (@car s) (@eq s)
 reflexivity proved by (refl s)
 symmetry proved by (sym s)
 transitivity proved by (trans s) as eq_rel.
Record Morphism (S1 S2:Setoid): Type :=
{ f:car S1 ->car S2;
  compat: forall (x1 x2: car S1), eq S1 x1 x2 -> eq S2 (f x1) (f x2) }.
Add Parametric Morphism (S1 S2 : Setoid) (M : Morphism S1 S2) :
 (@f S1 S2 M) with signature (@eq S1 ==> @eq S2) as apply_mor.
Proof. apply (compat S1 S2 M). Qed.
Lemma test: forall (S1 S2:Setoid) (m: Morphism S1 S2)
 (x y: car S1), eq S1 x y -> eq S2 (f _ _ m x) (f _ _ m y).
Proof. intros. rewrite H. reflexivity. Qed.
\end{coq_example*}
\end{cscexample}

\subsection{Tactics enabled on user provided relations}
\label{setoidtactics}
The following tactics, all prefixed by \texttt{setoid\_},
deal with arbitrary
registered relations and morphisms. Moreover, all the corresponding unprefixed
tactics (i.e. \texttt{reflexivity}, \texttt{symmetry}, \texttt{transitivity},
\texttt{replace}, \texttt{rewrite})
have been extended to fall back to their prefixed counterparts when
the relation involved is not Leibniz equality. Notice, however, that using
the prefixed tactics it is possible to pass additional arguments such as
\texttt{using relation}.
\medskip

\tacindex{setoid\_reflexivity}
\texttt{setoid\_reflexivity}

\tacindex{setoid\_symmetry}
\texttt{setoid\_symmetry} \zeroone{\texttt{in} \textit{ident}}

\tacindex{setoid\_transitivity}
\texttt{setoid\_transitivity}

\tacindex{setoid\_rewrite}
\texttt{setoid\_rewrite} \zeroone{\textit{orientation}} \textit{term}
~\zeroone{\texttt{at} \textit{occs}} ~\zeroone{\texttt{in} \textit{ident}}

\tacindex{setoid\_replace}
\texttt{setoid\_replace} \textit{term} \texttt{with} \textit{term}
~\zeroone{\texttt{in} \textit{ident}}
~\zeroone{\texttt{using relation} \textit{term}}
~\zeroone{\texttt{by} \textit{tactic}}
\medskip

The \texttt{using relation}
arguments cannot be passed to the unprefixed form. The latter argument
tells the tactic what parametric relation should be used to replace
the first tactic argument with the second one. If omitted, it defaults
to the \texttt{DefaultRelation} instance on the type of the objects.
By default, it means the most recent \texttt{Equivalence} instance in
the environment, but it can be customized by declaring new
\texttt{DefaultRelation} instances. As Leibniz equality is a declared
equivalence, it will fall back to it if no other relation is declared on
a given type.

Every derived tactic that is based on the unprefixed forms of the tactics
considered above will also work up to user defined relations. For instance,
it is possible to register hints for \texttt{autorewrite} that are
not proof of Leibniz equalities. In particular it is possible to exploit
\texttt{autorewrite} to simulate normalization in a term rewriting system
up to user defined equalities.

\subsection{Printing relations and morphisms}
The \texttt{Print Instances} command can be used to show the list of
currently registered \texttt{Reflexive} (using \texttt{Print Instances Reflexive}),
\texttt{Symmetric} or \texttt{Transitive} relations,
\texttt{Equivalence}s, \texttt{PreOrder}s, \texttt{PER}s, and
Morphisms (implemented as \texttt{Proper} instances). When
 the rewriting tactics refuse to replace a term in a context
because the latter is not a composition of morphisms, the \texttt{Print Instances}
commands can be useful to understand what additional morphisms should be
registered.

\subsection{Deprecated syntax and backward incompatibilities}
Due to backward compatibility reasons, the following syntax for the
declaration of setoids and morphisms is also accepted.

\comindex{Add Setoid}
\begin{quote}
  \texttt{Add Setoid} \textit{A Aeq ST} \texttt{as} \textit{ident}
\end{quote}
where \textit{Aeq} is a congruence relation without parameters,
\textit{A} is its carrier and \textit{ST} is an object of type
\texttt{(Setoid\_Theory A Aeq)} (i.e. a record packing together the reflexivity,
symmetry and transitivity lemmas). Notice that the syntax is not completely
backward compatible since the identifier was not required.

\comindex{Add Morphism}
\begin{quote}
  \texttt{Add Morphism} \textit{f}:\textit{ident}.\\
  Proof.\\
  \ldots\\
  Qed.
\end{quote}

The latter command also is restricted to the declaration of morphisms without
parameters. It is not fully backward compatible since the property the user
is asked to prove is slightly different: for $n$-ary morphisms the hypotheses
of the property are permuted; moreover, when the morphism returns a
proposition, the property is now stated using a bi-implication in place of
a simple implication. In practice, porting an old development to the new
semantics is usually quite simple.

Notice that several limitations of the old implementation have been lifted.
In particular, it is now possible to declare several relations with the
same carrier and several signatures for the same morphism. Moreover, it is
now also possible to declare several morphisms having the same signature.
Finally, the replace and rewrite tactics can be used to replace terms in
contexts that were refused by the old implementation. As discussed in
the next section, the semantics of the new \texttt{setoid\_rewrite}
command differs slightly from the old one and \texttt{rewrite}.

\asection{Extensions}
\subsection{Rewriting under binders}

\textbf{Warning}: Due to compatibility issues, this feature is enabled only when calling
the \texttt{setoid\_rewrite} tactics directly and not \texttt{rewrite}.

To be able to rewrite under binding constructs, one must declare
morphisms with respect to pointwise (setoid) equivalence of functions.
Example of such morphisms are the standard \texttt{all} and \texttt{ex}
combinators for universal and existential quantification respectively.
They are declared as morphisms in the \texttt{Classes.Morphisms\_Prop}
module. For example, to declare that universal quantification is a
morphism for logical equivalence:

\begin{coq_eval}
Reset Initial.
Require Import Setoid Morphisms.
\end{coq_eval}
\begin{coq_example}
Instance all_iff_morphism (A : Type) :
  Proper (pointwise_relation A iff ==> iff) (@all A).
Proof. simpl_relation.
\end{coq_example}
\begin{coq_eval}
Admitted.
\end{coq_eval}

One then has to show that if two predicates are equivalent at every
point, their universal quantifications are equivalent. Once we have
declared such a morphism, it will be used by the setoid rewriting tactic
each time we try to rewrite under an \texttt{all} application (products
in \Prop{} are implicitly translated to such applications).

Indeed, when rewriting under a lambda, binding variable $x$, say from
$P~x$ to $Q~x$ using the relation \texttt{iff}, the tactic will generate
a proof of \texttt{pointwise\_relation A iff (fun x => P x) (fun x => Q
x)} from the proof of \texttt{iff (P x) (Q x)} and a constraint of the
form \texttt{Proper (pointwise\_relation A iff ==> ?) m} will be
generated for the surrounding morphism \texttt{m}.

Hence, one can add higher-order combinators as morphisms by providing
signatures using pointwise extension for the relations on the functional
arguments (or whatever subrelation of the pointwise extension).
For example, one could declare the \texttt{map} combinator on lists as
a morphism:
\begin{coq_eval}
Require Import List Setoid Morphisms.
Set Implicit Arguments.
Inductive list_equiv {A:Type} (eqA : relation A) : relation (list A) :=
| eq_nil : list_equiv eqA nil nil
| eq_cons : forall x y, eqA x y ->
  forall l l', list_equiv eqA l l' -> list_equiv eqA (x :: l) (y :: l').
Generalizable All Variables.
\end{coq_eval}
\begin{coq_example*}
Instance map_morphism `{Equivalence A eqA, Equivalence B eqB} :
  Proper ((eqA ==> eqB) ==> list_equiv eqA ==> list_equiv eqB) (@map A B).
\end{coq_example*}

where \texttt{list\_equiv} implements an equivalence on lists
parameterized by an equivalence on the elements.

Note that when one does rewriting with a lemma under a binder
using \texttt{setoid\_rewrite}, the application of the lemma may capture
the bound variable, as the semantics are different from rewrite where
the lemma is first matched on the whole term. With the new
\texttt{setoid\_rewrite}, matching is done on each subterm separately
and in its local environment, and all matches are rewritten
\emph{simultaneously} by default. The semantics of the previous
\texttt{setoid\_rewrite} implementation can almost be recovered using
the \texttt{at 1} modifier.

\subsection{Sub-relations}

Sub-relations can be used to specify that one relation is included in
another, so that morphisms signatures for one can be used for the other.
If a signature mentions a relation $R$ on the left of an arrow
\texttt{==>}, then the signature also applies for any relation $S$ that
is smaller than $R$, and the inverse applies on the right of an arrow.
One can then declare only a few morphisms instances that generate the complete set
of signatures for a particular constant. By default, the only declared
subrelation is \texttt{iff}, which is a subrelation of \texttt{impl}
and \texttt{inverse impl} (the dual of implication). That's why we can
declare only two morphisms for conjunction:
\texttt{Proper (impl ==> impl ==> impl) and} and
\texttt{Proper (iff ==> iff ==> iff) and}. This is sufficient to satisfy
any rewriting constraints arising from a rewrite using \texttt{iff},
\texttt{impl} or \texttt{inverse impl} through \texttt{and}.

Sub-relations are implemented in \texttt{Classes.Morphisms} and are a
prime example of a mostly user-space extension of the algorithm.

\subsection{Constant unfolding}

The resolution tactic is based on type classes and hence regards user-defined
constants as transparent by default. This may slow down the resolution
due to a lot of unifications (all the declared \texttt{Proper}
instances are tried at each node of the search tree).
To speed it up, declare your constant as rigid for proof search
using the command \texttt{Typeclasses Opaque} (see \S
\ref{TypeclassesTransparency}).

\asection{Strategies for rewriting}

\subsection{Definitions}
The generalized rewriting tactic is based on a set of strategies that
can be combined to obtain custom rewriting procedures. Its set of
strategies is based on Elan's rewriting strategies
\cite{Luttik97specificationof}. Rewriting strategies are applied using
the tactic \texttt{rewrite\_strat $s$} where $s$ is a strategy
expression. Strategies are defined inductively as described by the
following grammar:

\def\str#1{\texttt{#1}}

\def\strline#1#2{& \vert & #1 & \text{#2}}
\def\strlinea#1#2#3{& \vert & \str{#1}~#2 & \text{#3}}

\[\begin{array}{lcll}
  s, t, u & ::= & ( s ) & \text{strategy} \\
  \strline{c}{lemma} \\
  \strline{\str{<-}~c}{lemma, right-to-left} \\

  \strline{\str{fail}}{failure} \\
  \strline{\str{id}}{identity} \\
  \strline{\str{refl}}{reflexivity} \\
  \strlinea{progress}{s}{progress} \\
  \strlinea{try}{s}{failure catch} \\

  \strline{s~\str{;}~u}{composition} \\
  \strline{\str{choice}~s~t}{left-biased choice} \\

  \strlinea{repeat}{s}{iteration (+)} \\
  \strlinea{any}{s}{iteration (*)} \\

  \strlinea{subterm}{s}{one subterm} \\
  \strlinea{subterms}{s}{all subterms} \\
  \strlinea{innermost}{s}{innermost first} \\
  \strlinea{outermost}{s}{outermost first}\\
  \strlinea{bottomup}{s}{bottom-up} \\
  \strlinea{topdown}{s}{top-down} \\

  \strlinea{hints}{hintdb}{apply hint} \\
  \strlinea{terms}{c \ldots c}{any of the terms}\\
  \strlinea{eval}{redexpr}{apply reduction}\\
  \strlinea{fold}{c}{fold expression}
\end{array}\]

Actually a few of these are defined in term of the others using
a primitive fixpoint operator:

\[\begin{array}{lcl}
  \str{try}~s & = & \str{choice}~s~\str{id} \\
  \str{any}~s & = & \str{fix}~u. \str{try}~(s~\str{;}~u) \\
  \str{repeat}~s & = & s~\str{;}~\str{any}~s \\
  \str{bottomup}~s & = &
  \str{fix}~bu. (\str{choice}~(\str{progress}~(\str{subterms}~bu))~s)~\str{;}~\str{try}~bu \\
  \str{topdown}~s & = &
  \str{fix}~td. (\str{choice}~s~(\str{progress}~(\str{subterms}~td)))~\str{;}~\str{try}~td \\
  \str{innermost}~s & = &  \str{fix}~i. (\str{choice}~(\str{subterm}~i)~s) \\
  \str{outermost}~s & = &
  \str{fix}~o. (\str{choice}~s~(\str{subterm}~o))
\end{array}\]

The basic control strategy semantics are straightforward: strategies are
applied to subterms of the term to rewrite, starting from the root of
the term. The lemma strategies unify the left-hand-side of the
lemma with the current subterm and on success rewrite it to the
right-hand-side. Composition can be used to continue rewriting on the
current subterm. The fail strategy always fails while the identity
strategy succeeds without making progress. The reflexivity strategy
succeeds, making progress using a reflexivity proof of
rewriting. Progress tests progress of the argument strategy and fails if
no progress was made, while \str{try} always succeeds, catching
failures. Choice is left-biased: it will launch the first strategy and
fall back on the second one in case of failure. One can iterate a
strategy at least 1 time using \str{repeat} and at least 0 times using
\str{any}.

The \str{subterm} and \str{subterms} strategies apply their argument
strategy $s$ to respectively one or all subterms of the current term
under consideration, left-to-right. \str{subterm} stops at the first
subterm for which $s$ made progress. The composite strategies
\str{innermost} and \str{outermost} perform a single innermost our outermost
rewrite using their argument strategy. Their counterparts
\str{bottomup} and \str{topdown} perform as many rewritings as possible,
starting from the bottom or the top of the term.

Hint databases created for \texttt{autorewrite} can also be used by
\texttt{rewrite\_strat} using the \str{hints} strategy that applies any
of the lemmas at the current subterm. The \str{terms} strategy takes the
lemma names directly as arguments. The \str{eval} strategy expects a
reduction expression (see \S\ref{Conversion-tactics}) and succeeds if it
reduces the subterm under consideration. The \str{fold} strategy takes a
term $c$ and tries to \emph{unify} it to the current subterm, converting
it to $c$ on success, it is stronger than the tactic \texttt{fold}.

\subsection{Usage}
\tacindex{rewrite\_strat}

\texttt{rewrite\_strat}~\textit{s}~\zeroone{\texttt{in} \textit{ident}}:

  Rewrite using the strategy \textit{s} in hypothesis \textit{ident}
  or the conclusion.

  \begin{ErrMsgs}
  \item  \errindex{Nothing to rewrite}. If the strategy failed.
  \item  \errindex{No progress made}. If the strategy succeeded but
    made no progress.
  \item  \errindex{Unable to satisfy the rewriting constraints}.
    If the strategy succeeded and made progress but the corresponding
    rewriting constraints are not satisfied.
  \end{ErrMsgs}

The \texttt{setoid\_rewrite}~c tactic is basically equivalent to
\texttt{rewrite\_strat}~(\str{outermost}~c).

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "Reference-Manual"
%%% End:


\vsssub
\subsubsection{~Second-order spectrum and free infragravity waves} \label{sec:IG1}
\vsssub

\opthead{IG1}{\ws}{F. Ardhuin}

\noindent
WARNING: {\it A bug has been identified with IG wave sources in unstructured grids.
A model patch using an older version of the code will be provided shortly.}

The linear dispersion relation used in section \ref{sec:intro} is a good
approximation for most of the wave energy but a significant part of the
spectrum at high frequencies, with typical frequencies above three times the
windsea wave peak \citep[e.g.][]{rep:Lec13}.  In shallow water, another
strongly nonlinear part of the spectrum is found at very low frequencies,
which are called infragravity waves.

In the case of horizontally homogeneous conditions over a flat bottom, both
low and high frequency non-linear components can be estimated from the linear
wave spectrum, using perturbation theory \citep[e.g.][]{art:Has62}. Also, the
non-linear evolution of a homogeneous wave field is better described in terms
of this `linearized spectrum'. It is thus practical to work with this
`linearized spectrum' and convert to the observable spectrum that contains
non-linear components when post-processing the model results. One method to
perform this transformation is a canonical transformation proposed by
\cite{art:Kra94}. The properties of this transformation were further explored
by \cite{art:Jan09} and implemented for post-processing in the ECMWF version
of the WAM model.

The code for the canonical transform written by P. Janssen was interfaced with
\ws.  Using the {\code IG1} switch and setting the parameter {\code IGADDOUTP
= 2} in the {\F SIG1} namelist, this canonical transformed, which conserves
energy, will be used for the output point spectra.  If {\code IGADDOUTP = 1},
then the second-order spectrum is added on top of the model spectrum using the
theory \citep[e.g.][]{art:Has62}. That option does not conserve energy and
is not consistent at high frequency because the quasi-linear term in the
second-order spectrum are ignored \citep{art:Jan09}.

However, when comparing to measurements, one should be aware that different
measuring devices have different responses to the nonlinear part of the
spectrum. In particular, surface-following buoys also linearize the spectrum,
and the second-order pressure field is not related to the second-order
elevation via the relations used for linear waves. The canonical transform is
thus only applicable for wave gauges that measure elevation at a fixed
location.

When the wave field is not homogeneous, the nonlinear properties of the waves
lead to an exchange of energy between different modes. In shallow water this
usually results in the transfer of energy to infragravity waves, that are
released along shorelines and travel as free waves. The {\code IG1} switch
allows the parameterization of that effect with several methods.  These are
very crude parameterizations compared to the full hydrodynamic solution that
would require solving the bispectral evolution across the surf zone at a very
high spatial resolution \citep[e.g.][]{art:HB97}. The default namelist settings
correspond to the parameterization presented by \cite{art:Aea14}, with minor adjustments in version 6.06.
The power in the definition of $\widehat{E}_{IG}(f)$ was changed from $f^{1.5}$ to $f^{1.0}$, with
an associated adjuspent of the constant fro 0.015 to 0.013.

 In practice the free infragravity wave energy is
added via the $S_{ref}$ source term, by setting the {\code SIG1} namelist
{\code IGSOURCE} to 1 or 2.

In the first method, activated with {\code IGSOURCE =1}, the second-order
spectrum is computed using either the Hasselmann perturbation ({\code IGMETHOD
= 1}) or the canonical transform (any other value of {\code IGMETHOD}) as described
in \cite{art:Jan09}. This
approach may lead to better directional distribution of IG wave energy but it
is still being tested.  The second method, activated with {\code IGSOURCE =
2}, and the free IG spectrum is given by the following expressions,

\begin{eqnarray}
 A_{IG} & =&    H_s T_{m0,-2}^2\label{eq:IGfit0}, \\
\widehat{E}_{IG}(f)& = & 1.2 \alpha_1^2 \frac{k g^2}{c_g 2 \pi f} \frac{(A_{IG}/4)^2}{\Delta_f}
\left[\min( 1., 0.013\mathrm{Hz}/ f)\right]^{1.0}, \label{eq:IGfit1} \\
 \widehat{E}_{IG}(f,\theta) & = & \widehat{E}_{IG}(f) / (2 \pi ),
\label{eq:fit2}
\end{eqnarray}

\noindent
where the mean period is defined as $ T_{m0,-2} =\sqrt{m_{-2}/m_{0}}$ with the
moments

\begin{equation}
 m_n= \int_{f_{min}~\mathrm{Hz}}^{0.5~\mathrm{Hz}} E(f) f^n {\mathrm d}f,\label{eq:mn}
\end{equation}

\noindent
and the empirical coefficient $\alpha_1$ is of the order of
$10^{-3}$~s$^{-1}$, and is set by the {\code SIG1} namelist parameter {\code
IGEMPIRICAL}. The minimum frequency $f_{min}$ used to define $ T_{m0,-2}$ is
set by the namelist parameter {\code IGMAXFREQ} and it is also the maximum
frequency of the IG band over which this source of energy is applied.  Also,
in this band the IG energy at the coast can be added on top of pre-existing
energy, or the pre-existing energy can be reset to zero. That latter behavior
is the default and controlled by {\code IGBCOVERWRITE = 1}. For other choices,
({\code IGBCOVERWRITE = 0}), the results are very sensitive to the maximum
shoreline reflection coefficient allowed ({\code REFRMAX} parameter in
namelist {\F REF1}).

Finally, IG energy can also be added for frequencies beyond $f_{min}$, this is the default behavior
and it is activated by setting {\code IGSWELLMAX = TRUE}.  For that part of the IG wave
field, the IG wave source is now reduced by a factor 4 which is now hard-coded
in {\file w3ref1md.ftn}. This should be adjusted together with the maximum reflection
which is defined by the {\F REF1} namelist parameter {\code
REFRMAX}. In the present version, the option {\code IGSWELLMAX = TRUE} does
not work well with unstructured grids. We thus advise to use
{\code IGSWELLMAX = FALSE} for these grids, this will unfortunately lead
to a spectral gap between the IG band and the swell-windsea band.


\subsection{Gaussian basis sets}
\label{sec:gaussianbasis}

In this section we describe the use of localized basis sets to expand the \texttt{sposet}. The general form of a single particle orbital in this case is given by:
\begin{equation}
\phi_i(\vec{r}) = \sum_k C_{i,k} \ \eta_k(\vec{r}),
\end{equation}
where $\{\eta_k(\vec{r})\}$ is a set of M atom-centered basis
functions and $C_{i,k}$ is a coefficient matrix. This \texttt{sposet}
should be used in calculations of finite systems employing an
atom-centered basis set and is typically generated by the
\textit{convert4qmc} converter.  Examples include calculations of
molecules using gaussian basis sets or slater-type basis
functions. Initial support for periodic systems is described in Sec.
\ref{chap:LCAO}. Even though this section is called "Gaussian basis
sets" (by far the most common atom-centered basis set), QMCPACK works
with any atom-centered basis set built based on either spherical
harmonic angular functions or cartesian angular expansions. The radial
functions in the basis set can be expanded in either gaussian
functions, slater-type functions or numerical radial functions.

In this section we describe the input sections for the atom-centered basis set and the \texttt{sposet} for a single slater determinant trial wavefunction. The input sections for multideterminant trial wavefunctions are described in section \ref{sec:multideterminants}. The basic structure for the input block of a single slater determinant is given in Listing \ref{listing:lcaosposet}.
A list of options for \texttt{determinantset} associated with this \texttt{sposet} is given in Table \ref{table:determinantset}.

\begin{minipage}{\linewidth}
\begin{lstlisting}[style=XML,caption=Basic input block for a single determinant trial wavefunction using a sposet expanded on an atom-centered basis set. \label{listing:lcaosposet}]
<wavefunction id="psi0" target="e">
    <determinantset>
      <basisset>
        ...
      </basisset>
      <slaterdeterminant>
        ...
      </slaterdeterminant>
    </determinantset>
</wavefunction>
\end{lstlisting}
\end{minipage}

\begin{table}[h]
\begin{center}
\begin{tabularx}{\textwidth}{l l l l l l }
\hline
\multicolumn{6}{l}{\texttt{determinantset} element} \\
\hline
\multicolumn{2}{l}{parent elements:} & \multicolumn{4}{l}{\texttt{wavefunction}}\\
\multicolumn{2}{l}{child  elements:} & \multicolumn{4}{l}{\texttt{basisset,slaterdeterminant,sposet,multideterminant}}\\
\multicolumn{2}{l}{attribute      :} & \multicolumn{4}{l}{}\\
   &   \bfseries name              & \bfseries datatype & \bfseries values & \bfseries default   & \bfseries description \\
   &   \texttt{name}/\texttt{id}   &  text              &  \textit{any}    &  ""             & Name of determinant set. \\
   &   \texttt{type}                    &  text               &   see below   &   ""            &  Type of \texttt{sposet}. \\
   &   \texttt{keyword}             &  text               &   NMO,GTO,STO   &  NMO        & Type of orbital set generated. \\
   &   \texttt{transform}           &  text               &   yes/no          &  yes         &  Transform to numerical radial functions?  \\
   &   \texttt{source}               &  text               &   \textit{any}    &  ion0        & Particle set with the position of atom centers. \\
   &   \texttt{cuspCorrection}  &  text               &   yes/no          &  no         & Apply cusp correction scheme to \texttt{sposet}? \\
%   &   \texttt{cuspInfo}               &  text               &   \textit{any}    &  ""             & File with saved cusp data. \\
  \hline
\end{tabularx}
\end{center}
\caption{Options for the \texttt{determinantset} xml-block associated with atom-centered single particle orbital sets.}
\label{table:determinantset}
\end{table}

The definition of the set of atom-centered basis functions is given by the \texttt{basisset} block, while the sposet is defined within \texttt{slaterdeterminant}. The basisset input block is composed from a collection of \texttt{atomicBasisSet} input blocks, one for each atomic species in the simulation where basis functions are centered. The general structure for \texttt{basisset} and \texttt{atomicBasisSet} are given in Listing \ref{listing:basisset}, while the corresponding lists of options are given in Tables \ref{table:basisset} and \ref{table:atomicBasisSet}.

\begin{minipage}{\linewidth}
\begin{lstlisting}[style=XML,caption=Basic input block for \texttt{basisset}.\label{listing:basisset}]
      <basisset name="LCAOBSet">
        <atomicBasisSet name="Gaussian-G2" angular="cartesian" elementType="C" normalized="no">
          <grid type="log" ri="1.e-6" rf="1.e2" npts="1001"/>
          <basisGroup rid="C00" n="0" l="0" type="Gaussian">
            <radfunc exponent="5.134400000000e-02" contraction="1.399098787100e-02"/>
            ...
          </basisGroup>
          ...
        </atomicBasisSet>
        <atomicBasisSet name="Gaussian-G2" angular="cartesian" type="Gaussian" elementType="C" normalized="no">
          ...
        </atomicBasisSet>
        ...
      </basisset>
\end{lstlisting}
\end{minipage}

\begin{table}[h]
\begin{center}
\begin{tabularx}{\textwidth}{l l l l l l }
\hline
\multicolumn{6}{l}{\texttt{basisset} element} \\
\hline
\multicolumn{2}{l}{parent elements:} & \multicolumn{4}{l}{\texttt{determinantset}}\\
\multicolumn{2}{l}{child  elements:} & \multicolumn{4}{l}{\texttt{atomicBasisSet}}\\
\multicolumn{2}{l}{attribute      :} & \multicolumn{4}{l}{}\\
   &   \bfseries name              & \bfseries datatype & \bfseries values & \bfseries default   & \bfseries description \\
   &   \texttt{name}/\texttt{id}   &  text              &  \textit{any}    &  ""                & Name of atom-centered basis set. \\
  \hline
\end{tabularx}
\end{center}
\caption{Options for the \texttt{basisset} xml-block associated with atom-centered single particle orbital sets.}
\label{table:basisset}
\end{table}

\begin{table}[h]
\begin{center}
\begin{tabularx}{\textwidth}{l l l l l l }
\hline
\multicolumn{6}{l}{\texttt{atomicBasisSet} element} \\
\hline
\multicolumn{2}{l}{parent elements:} & \multicolumn{4}{l}{\texttt{basisset}}\\
\multicolumn{2}{l}{child  elements:} & \multicolumn{4}{l}{\texttt{grid,basisGroup}}\\
\multicolumn{2}{l}{attribute      :} & \multicolumn{4}{l}{}\\
   &   \bfseries name              & \bfseries datatype & \bfseries values & \bfseries default   & \bfseries description \\
   &   \texttt{name}/\texttt{id}   &  text              &  \textit{any}    &  ""                & Name of atomic basis set. \\
   &   \texttt{angular}               &  text              &  see below    &  default       & Type of angular functions.  \\
%   &   \texttt{type}                    &  text              &  see below    &  ""                &  Type of input radial function. \\
   &   \texttt{expandYlm}         &  text              &  see below   &  yes                &  Expand Ylm shells? \\
   &   \texttt{expM}                  &  text              &  see below   &  yes                &  Add sign for $(-1)^{m}$? \\
   &   \texttt{elementType/species}   &  text  &  \textit{any}    &  e                &  Atomic species where functions are centered. \\
   &   \texttt{normalized}         &  text              &  yes/no   &  yes                &  Are single particle functions normalized? \\
  \hline
\end{tabularx}
\end{center}
\caption{Options for the \texttt{atomicBasisSet} xml-block.}
\label{table:atomicBasisSet}
\end{table}

\begin{table}[h]
\begin{center}
\begin{tabularx}{\textwidth}{l l l l l l }
\hline
\multicolumn{6}{l}{\texttt{basisGroup} element} \\
\hline
\multicolumn{2}{l}{parent elements:} & \multicolumn{4}{l}{\texttt{atomicBasisSet}}\\
\multicolumn{2}{l}{child  elements:} & \multicolumn{4}{l}{\texttt{radfunc}}\\
\multicolumn{2}{l}{attribute      :} & \multicolumn{4}{l}{}\\
   &   \bfseries name              & \bfseries datatype & \bfseries values & \bfseries default   & \bfseries description \\
   &   \texttt{rid}/\texttt{id}   &  text              &  \textit{any}    &  ""                & Name of the basisGroup. \\
   &   \texttt{type}                    &  text            &  \textit{any}    &  ""                & Type of basisGroup. \\
   &   \texttt{n/l/m/s}                 &  integer           &  \textit{any}    &  0                & Quantum numbers of basisGroup. \\
  \hline
\end{tabularx}
\end{center}
\caption{Options for the \texttt{basisGroup} xml-block.}
\label{table:basisGroup}
\end{table}

\begin{minipage}{\linewidth}
\begin{lstlisting}[style=XML,caption=Basic input block for \texttt{slaterdeterminant} with an atom-centered \texttt{sposet}.\label{listing:slaterdeterminant}]
      <slaterdeterminant>
      </slaterdeterminant>
\end{lstlisting}
\end{minipage}

\begin{table}[h]
\begin{center}
\begin{tabularx}{\textwidth}{l l l l l l }
\hline
\multicolumn{6}{l}{\texttt{} element} \\
\hline
\multicolumn{2}{l}{parent elements:} & \multicolumn{4}{l}{\texttt{}}\\
\multicolumn{2}{l}{child  elements:} & \multicolumn{4}{l}{\texttt{}}\\
\multicolumn{2}{l}{attribute      :} & \multicolumn{4}{l}{}\\
   &   \bfseries name              & \bfseries datatype & \bfseries values & \bfseries default   & \bfseries description \\
   &   \texttt{name}/\texttt{id}   &  text              &  \textit{any}    &  ""                & Name of determinant set \\
   &   \texttt{}                    &  text              &  \textit{any}    &  ""                &  \\
  \hline
\end{tabularx}
\end{center}
\end{table}

\subsubsection{Detailed description of attributes:}

In the following, we give a more detailed description of all the options presented in the various xml-blocks described in this section. Only non-trivial attributes are described below. Those with simple yes/no options and whose description above is enough to explain the intended behavior are not included.

\hspace{1mm} \\

\texttt{determinantset} attributes:

\begin{itemize}
\item \texttt{type} \\
Type of sposet. For atom-centered based sposets, use type="MolecularOrbital" or type="MO". Other options describe elsewhere in this manual are "spline", "composite", "pw", "heg", "linearopt", etc.
\item \texttt{keyword}/\texttt{key} \\
Type of basis set generated, which doesn't necessarily match the type of the basis set on the input block. The three possible options are: NMO (numerical molecular orbitals), GTO (gaussian-type orbitals), STO (slater-type orbitals). The default option is NMO. By default, QMCPACK will generate numerical orbitals from both GTO and STO types and use cubic or quintic spline interpolation to evaluate the radial functions. This is typically more efficient than evaluating the radial functions in the native basis (gaussians or exponents) and allows for arbitrarily large contractions without any additional cost. To force the use of the native expansion (not recommended), use GTO or STO for each type of input basis set.
\item \texttt{transform}\\
Request (or avoid) a transformation of the radial functions to NMO type. The default and recommended behavior is to transform to numerical radial functions. If \texttt{transform} is set to \textit{"yes"}, the option \texttt{keyword} is ignored.
\item \texttt{cuspCorrection}\\
Enable (disable) the use of the cusp correction algorithm (CASINO REFERENCE) for a \texttt{basisset} built with GTO functions. The algorithm is implemented as described in (CASINO REFERENCE) and only works with transform="yes" and an input GTO basis set. No further input is needed.
\end{itemize}

\texttt{atomicBasisSet} attributes:

\begin{itemize}
\item \texttt{name/id}\\
Name of the basis set. Names should be unique.
\item \texttt{angular}\\
Type of angular functions used in the expansion. In general, two angular basis functions are allowed: "spherical" (for spherical Ylm functions) and "cartesian" (for functions of the type $x^{n}y^{m}z^{l}$).
%\item \texttt{type}\\ Type of input radial functions. Options are: "Numerical" (for radial functions on a numerical radial grid), "Gaussian" (for an expansion in gaussian functions) and ""
\item \texttt{expandYlm}\\
Determines whether each basis group is expanded across the corresponding shell of m values (for spherical type) or consistent powers (for cartesian functions). Options:
\begin{itemize}
\item "No": Do not expand angular functions across corresponding angular shell.
\item "Gaussian": Expand according to Gaussian03 format. This function is only compatible with angular="spherical". For a given input (l,m), the resulting order of the angular functions becomes: (1,-1,0) for l=1 and (0,1,-1,2,-2,...,l,-l) for general l.
\item "Natural": Expand angular functions according to (-l,-l+1,...,l-1,l).
\item "Gamess": Expand according to Gamess' format for cartesian functions. Notice that this option is only compatible with angular="cartesian". If angular="cartesian" is used, this option is not necessary.
\end{itemize}
\item \texttt{expM}\\
Determines whether the sign of the spherical Ylm function associated with m ($-1^{m}$) is included in the coefficient matrix or not.
\item \texttt{elementType/species}\\
Name of the species where basis functions are centered. Only one atomicBasisSet block is allowed per species. Additional blocks are ignored. The corresponding species must exist in the \texttt{particleset} given as the \texttt{source} option to \texttt{determinantset}. Basis functions for all the atoms of the corresponding species are included in the basis set, based on the order of atoms in the \texttt{particleset}.
\end{itemize}

\texttt{basisGroup} attributes:

\begin{itemize}
\item \texttt{type}\\
  Type of input basis radial function. Notice that this refers to the type of radial function in the input xml-block, which might not match the radial function generated internally and used in the calculation (if \texttt{transform} is set to "yes"). Also notice that different \texttt{basisGroup} blocks within a given \texttt{atomicBasisSet} can have different \texttt{type}.
\item \texttt{n/l/m/s}\\
  Quantum numbers of the basis function. Notice that if \texttt{expandYlm} is set to \textit{"yes"} in \texttt{atomicBasisSet}, a full shell of basis functions with the appropriate values of \textit{"m"} will be defined for the corresponding value of \textit{"l"}. Otherwise a single basis function will be given for the specific combination of \textit{"(l,m)"}.
\end{itemize}

\texttt{radfunc} attributes for \texttt{type}=\textit{"Gaussian"}:

\begin{itemize}
\item \texttt{}\\
\end{itemize}

\texttt{slaterdeterminant} attributes:

\begin{itemize}
\item \texttt{}\\
\end{itemize}


\documentclass{juliacon}
\setcounter{page}{1}
\lstset{numbers=left}
\usepackage{amsmath}
\usepackage{xspace}
\usepackage{booktabs}
\usepackage{upgreek}
\usepackage[most]{tcolorbox}
\tcbset{on line,boxsep=1pt,left=0pt,right=0pt,top=0pt,bottom=0pt,
        colframe=white,colback=gray!10,highlight math style={enhanced}}
\usepackage[labelformat=simple]{subfig}
\renewcommand{\thesubfigure}{(\alph{subfigure})}
\usepackage{tikz}

\input{macros}

\begin{document}

\input{header}

\maketitle

\begin{abstract}
\input{abstract}
\end{abstract}

\renewcommand{\thefootnote}{\fnsymbol{footnote}}
\footnotetext[1]{Both authors contributed equally.}
\renewcommand{\thefootnote}{\arabic{footnote}}

\section{Introduction}

\input{introduction}

\section{Basic sets and operations} \label{sec:basic}

\input{basic}

\section{The LazySets paradigm} \label{sec:lazy}

\input{lazy}

\section{Conversion between set types} \label{sec:approx}

\input{approx}

\section{Ecosystem} \label{sec:applications}

\input{applications}

\section{Conclusion and Perspectives} \label{sec:conclusion}

\input{conclusion}

\section*{Acknowledgments}

\input{acks}

\input{bib.tex}

\input{appendix}

\end{document}


\section{Configuration file}
\label{S:CFGFile}
The configuration file is a \MATLAB{} script utilized for initializing the project (see Figure \ref{fig:cfgfile}).
The name of a configuration file can be given as an input to the function   \lstinline[basicstyle = \mlttfamily \small ]!OpenBLDM_main.m!, as mentionned in Section~\ref{SS:OpenBDLMinput}.
The configuration file must follow a specific structures, which includes 6 sections: Project name, Data, Model structure, Model parameters, Initial states values and Options.
The first three sections are mandatory, while the last three sections are optional.
\begin{figure}[h!]
\centering
\includegraphics[width=140mm]{docfigs/Example_DISPSIM/listing/config_file_1.pdf}
\caption{Exemple of configuration file}
\label{fig:cfgfile}
\end{figure}

\subsection{Project name}
This section of the configuration file defines the name of the project as a vector of characters stored in the field \lstinline[basicstyle = \mlttfamily \small ]!ProjectName! of the \MATLAB{} variable \lstinline[basicstyle = \mlttfamily \small ]!misc!.

\subsection{Data}

This section of the configuration file defines information required for loading the data from a \lstinline[basicstyle = \mlttfamily \small ]!DATA_! file located in ``/data/mat'' subfolder.
The file must follow the format described in Section~\ref{SS:MATInput}.
The timestamp values, the amplitude values and the label values must be stored in the fields \lstinline[basicstyle = \mlttfamily \small]!timestamps!, \lstinline[basicstyle = \mlttfamily \small]!values!, and \lstinline[basicstyle = \mlttfamily \small]!labels! of the \MATLAB{} structure named \lstinline[basicstyle = \mlttfamily \small]!data!.

\subsection{Model structure}
\label{SS:ModelComponents}
This part of the configuration file defines the model in a \MATLAB{} structure named \lstinline[basicstyle = \mlttfamily \small]!model.component!.
The structure \lstinline[basicstyle = \mlttfamily \small]!model.component! must have three fields, named \lstinline[basicstyle = \mlttfamily \small]!model.component.block!, \lstinline[basicstyle = \mlttfamily \small]!model.component.ic!, and \lstinline[basicstyle = \mlttfamily \small]!model.component.const!.

\begin{itemize}

\item \lstinline[basicstyle = \mlttfamily \small ]!model.component.block!: it defines the block components associated with each time series.
The field \lstinline[basicstyle = \mlttfamily \small ]!block! stores $1\times \mathtt{S}$ cell array, where $\mathtt{S} = \{1,2 \}$ is the number of model classes.
Each cell array is a $1\times \mathtt{D}$ cell array of matrice, where $\mathtt{D}$ is the number of time series.
Each block component is associated with a reference number:
\begin{itemize}
\item 11: Local level
\item 12: Local trend
\item 13: Local acceleration
\item 21: Local level compatible with local trend
\item 22: Local level compatible with local acceleration
\item 23: Local trend compatible with local acceleration
\item 31: Periodic
\item 41: First-order autoregressive
\item 51: Kernel regression
\item 61: Level intervention
\end{itemize}

\item  \lstinline[basicstyle = \mlttfamily \small ]!model.component.const!: it constrains model parameters between the block components from different model classes.
The field \lstinline[basicstyle = \mlttfamily \small ]!const! stores a $1\times \mathtt{S}$ cell array, where $\mathtt{S} = \{1, 2 \}$ is the total number of model classes.
It is defined only if $\mathtt{S} = 2$.
The first cell is empty, and the second cell is a $1\times \mathtt{D}$ cell array of array, where $\mathtt{D}$ is the number of time series.
The array contains $0$ and $1$ to indicate which block components of the second model class has the same model parameters than the corresponding component of the first model class.
A value of $1$ indicates that the model parameters are constrained between the block components of the two model classes, $0$ otherwise.

\item  \lstinline[basicstyle = \mlttfamily \small ]!model.component.ic!:  it defines the dependencies among the time series.
The field \lstinline[basicstyle = \mlttfamily \small ]!ic! stores a $1\times \mathtt{D}$ cell array of $1\times (\mathtt{D}-1)$ matrix, where $\mathtt{D}$ is the number of time series.
Each time series depend on the time series corresponding to the indexes given in the $\mathtt{D}$ arrays.
If the array is empty, the time series are considered independent by default.

\end{itemize}

\subsection{Model parameters}
\label{SS:ModelParamProperties}
This part of the configuration file aims at defining the model parameter properties which are stored in the field named \lstinline[basicstyle = \mlttfamily \small ]!model.param_properties! of the \MATLAB{} structure \lstinline[basicstyle = \mlttfamily \small ]!model!.
The field \lstinline[basicstyle = \mlttfamily \small ]!model.param_properties! stores $\mathtt{K} \times 10$ cell array, where $\mathtt{K}$ is the total number of model parameters.
\begin{itemize}
\item column 1 must be a character vector that gives the name of the model parameters (e.g.  \lstinline[basicstyle = \mlttfamily \small ]!sigma_w!).
\item column 2 must be a character vector that gives the reference name of the block associated with the parameter (e.g \lstinline[basicstyle = \mlttfamily \small ]!LL!, see Section~\ref{SS:BlockComponent}).
\item column 3 must be a character vector that gives the index corresponding to the model class associated with the parameter (e.g  either \lstinline[basicstyle = \mlttfamily \small ]!1! or \lstinline[basicstyle = \mlttfamily \small ]!2!) (see~\ref{SS:THSKF}).
\item column 4 must be a character vector that gives the index corresponding to the observation associated with the parameter (e.g \lstinline[basicstyle = \mlttfamily \small ]!3!).
\item column 5 must be a $1\times2$ array that gives the bound of the parameter (e.g \lstinline[basicstyle = \mlttfamily \small ]![NaN, NaN]!,  \lstinline[basicstyle = \mlttfamily \small ]![0, Inf]!, \lstinline[basicstyle = \mlttfamily \small ]![0, 1]!).
The bounds are used to transform (if necessary) model parameters from a bounded to  an unbounded space during the optimization process (see Sections~\ref{S:PARAMESTIMATION} and~\ref{SS:THModelParameterEstimation}).
\item column 6 must be a character vector that gives the type of the prior used during the optimization process (e.g  either \lstinline[basicstyle = \mlttfamily \small ]!N/A! or \lstinline[basicstyle = \mlttfamily \small ]!normal!).
\lstinline[basicstyle = \mlttfamily \small ]!N/A! indicates that no prior is used (see Sections~\ref{S:PARAMESTIMATION} and~\ref{SS:THModelParameterEstimation}).
\item column 7 must be a real number that gives the mean of the prior when a prior of type \lstinline[basicstyle = \mlttfamily \small ]!normal! is used, otherwise it must be set to \lstinline[basicstyle = \mlttfamily \small ]!NaN! (see Sections~\ref{S:PARAMESTIMATION} and~\ref{SS:THModelParameterEstimation}).
\item column 8 must be a real number that gives the standard deviation of the prior when a prior of type \lstinline[basicstyle = \mlttfamily \small ]!normal! is used, otherwise it must be set to \lstinline[basicstyle = \mlttfamily \small ]!NaN! (see Sections~\ref{S:PARAMESTIMATION} and~\ref{SS:THModelParameterEstimation}).
\item column 9 must be a real number that gives the value of the model parameters.
\item column 10 must be an integer that gives the reference number of the model parameters. The model parameters which share the same reference number are constrained to each other.
\end{itemize}

\subsection{Initial states values}
\label{SS:InitialHS}
This part of the configuration file defines the initial states values (at time $t=0$).
The initial mean and covariance hidden states values are stored in the \lstinline[basicstyle = \mlttfamily \small ]!model.initX! and \lstinline[basicstyle = \mlttfamily \small ]!model.initV! fields.
The initial probability for the model class is stored in the field \lstinline[basicstyle = \mlttfamily \small ]!model.initS!.

\begin{itemize}
\item \lstinline[basicstyle = \mlttfamily \small ]!model.initX!: $1\times \mathtt{S}$ cell array of array, where $\mathtt{S} \in \{1, 2 \}$ is the total number of model classes.
Each array is $\mathtt{L}\times1$ array of real number that stores the initial mean values associated with each hidden states variables, where $\mathtt{L}$ is the total number of hidden states variables associated with the model.
\item \lstinline[basicstyle = \mlttfamily \small ]!model.initV!: $1\times \mathtt{S}$ cell array of array, where $\mathtt{S} \in \{1, 2 \}$ is the total number of model classes.
Each array is $\mathtt{L}\times\mathtt{L}$ array of real number that stores the initial variance and covariances values associated with each hidden states variables.
\item \lstinline[basicstyle = \mlttfamily \small ]!model.initS!: $1\times \mathtt{S}$ cell array of array, where $\mathtt{S} \in \{1, 2 \}$ is the total number of model classes.
Each array is $1\times1$ array of real number that gives the initial probability for the model class.
\end{itemize}

\subsection{Options}
\label{SS:options}
This part of the configuration file defines the options that control different aspect of the software regarding the data pre-processing, optimization, hidden states estimation, and aspects related to graphical outputs.
The options are stored in the field named \text{options} of the \MATLAB{} variable \lstinline[basicstyle = \mlttfamily \small ]!misc!.
\begin{itemize}

\item Options for the data pre-processing

\begin{itemize}
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.NaNThreshold!: real number that gives, in percent, the amount of missing data allowed at each time slice.\\Default: \lstinline[basicstyle = \mlttfamily \small ]!100!.
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.Tolerance!: real number that gives the duration (in number of days) after which two timestamps are not considered equal. \\Default: $10^{-6}$.

\end{itemize}

\item Options for the model parameters estimation

\begin{itemize}
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.trainingPeriod!:  $1\times2$ array of real number that defines the training period, given in number of days since the first timestamp. \\Default: \lstinline[basicstyle = \mlttfamily \small ]![1 Inf]!.
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.isParallel!: logical that triggers or not the parallel computation for approximating the gradient in the optimization procedure. Note that parallel computation requires the \MATLAB{} \emph{Parallel Computing Toolbox}. \\Default: \lstinline[basicstyle = \mlttfamily \small ]!true!.
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.maxIterations!: integer that gives the maximum number of iterations for the optimization procedure. Newton-Raphson only. \\Default: \lstinline[basicstyle = \mlttfamily \small ]!100!.
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.maxTime!: real number that gives, in minutes, the maximum amount of  time to spend for the optimization procedure. \\Default: \lstinline[basicstyle = \mlttfamily \small ]!60!.
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.isMAP!: logical that triggers or not the Maximum A Posteriori (MAP) estimation of the model parameters during the optimization procedure. MAP estimation includes prior information about the model parameters. \\Default: \lstinline[basicstyle = \mlttfamily \small ]!false!.
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.isPredCap!: logical so that if \lstinline[basicstyle = \mlttfamily \small ]!isPredCap=true!, the Prediction Capacity (i.e. the log-likelihood over a test dataset) is used to drive the optimization process, otherwise the log-likelihood over the full dataset is used. This option is used only for Stochastic Gradient optimization. \\Default: \lstinline[basicstyle = \mlttfamily \small ]!false!.
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.isLaplaceApprox!: logical so that if \lstinline[basicstyle = \mlttfamily \small ]!isLaplaceApprox=true! the posterior covariance matrix is estimated using Laplace approximation around the optimized model parameters values. This option is used only for Newton-Raphson optimization. \\Default: \lstinline[basicstyle = \mlttfamily \small ]!false!.
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.NRTerminationTolerance!: real value determining the termination tolerance for the Newton-Raphson algorithm. \\Default: $10^{-7}$.
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.NRLevelsLambdaRef!: integer that controls the number of trial loop for a parameter being optimized for theNewton-Raphson algorithm. \\Default: $4$.
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.isMute!: logical so that if \lstinline[basicstyle = \mlttfamily \small ]!isMute=true!, no message are displayed on screen during the optimization procedure. \\Default: \lstinline[basicstyle = \mlttfamily \small ]!false!.
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.maxEpochs!: integer that gives the maximum number of epochs the optimization procedure. This option is used only for Stochastic Gradient optimization. \\Default: \lstinline[basicstyle = \mlttfamily \small ]!50!.
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.Optimizer!: vector of character that defines the optimizer for Stochastic Gradient algorithm. It must be either \lstinline[basicstyle = \mlttfamily \small ]!'MMT'!, \lstinline[basicstyle = \mlttfamily \small ]!'ADAM'!, \lstinline[basicstyle = \mlttfamily \small ]!'MMTbeta'!, \lstinline[basicstyle = \mlttfamily \small ]!'ADAMbeta'!. This option is used only for Stochastic Gradient optimization. \\Default: \lstinline[basicstyle = \mlttfamily \small ]!'MMT'!.
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.SplitPercent!: real number that defines defines in percent the portion of the training data used for validation. \\Default: \lstinline[basicstyle = \mlttfamily \small ]!30!.
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.MiniBatchSizePercent!: real number that defines defines the size of mini-batch, in percent of the training data. \\Default: \lstinline[basicstyle = \mlttfamily \small ]!20!.
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.SGTerminationTolerance!: termination tolerance for the Stochastic gradient algorithm. This option is used only for Stochastic Gradient optimization. \\Default: \lstinline[basicstyle = \mlttfamily \small ]!0.95!.
\end{itemize}

\item Options for the estimation

\begin{itemize}
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.MaxSizeEstimation!: real number that gives the maximum size, in Mb, for which the hidden states estimations are saved in the \lstinline[basicstyle = \mlttfamily \small ]!PROJ_! file at the end of the analysis. \\Default: \lstinline[basicstyle = \mlttfamily \small ]!100!.
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.MethodStateEstimation!: vector of character. It must be either \lstinline[basicstyle = \mlttfamily \small ]!'kalman'! or \lstinline[basicstyle = \mlttfamily \small ]!'UD'!. it gives the method used for the estimation of the hidden states. \\Default: \lstinline[basicstyle = \mlttfamily \small ]!'kalman'!.
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.DataPercent!: real number that gives in percent the amount of data, starting at $t=1$ used for the estimation of the initial hidden states. \\Default: \lstinline[basicstyle = \mlttfamily \small ]!100!.
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.KRNumberControlPoints!: integer that gives the number of control points used for the periodic kernel regression component (see Section~\ref{SS:BlockComponent}). \\Default: \lstinline[basicstyle = \mlttfamily \small ]!100!.
\end{itemize}

\item Options for the synthetic data creation

\begin{itemize}
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.Seed!: integer that controls the random number generation used to create synthetic data. Synthetic data created with the same seed are identical (useful to replicate results). If  \lstinline[basicstyle = \mlttfamily \small ]!misc.options.Seed=[]!, the seed is based on current time and therefore, a different sequence of random number  is generated at each run. \\Default: \lstinline[basicstyle = \mlttfamily \small ]!12345!.
\end{itemize}

\item Options for the graphical outputs

\begin{itemize}
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.isPlotEstimations!: logical. if \lstinline[basicstyle = \mlttfamily \small ]!isPlotEstimations=true!, figures plotting the estimation results popup on screen each time the hidden states are estimated. \\Default: \lstinline[basicstyle = \mlttfamily \small ]!true!.
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.FigurePosition!: $1\times4$ array of real number that gives the location and size of the drawable area, specified as a vector of the form [left bottom width height] in the current units of \MATLAB{}. \\Default: \lstinline[basicstyle = \mlttfamily \small ]![100, 100, 1300, 270]!
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.isSecondaryPlot!: logical. if \lstinline[basicstyle = \mlttfamily \small ]!isSecondaryPlot=true!, a closeup over two weeks is plotted at the right of each figure. \\Default: \lstinline[basicstyle = \mlttfamily \small ]!false!.
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.Subsample!: integer that controls the number of points that are displayed in the plots. The number of points to plot is divided by a factor given by the values of \lstinline[basicstyle = \mlttfamily \small ]!misc.options.Subsample!. \\Default: \lstinline[basicstyle = \mlttfamily \small ]!1!.
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.Linewidth!: real number that controls the width of the line plotted in the figure. \\Default: \lstinline[basicstyle = \mlttfamily \small ]!1!.
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.ndivx!: integer that controls the number of labels for abscissa x-axis in each figure. \\Default: \lstinline[basicstyle = \mlttfamily \small ]!4!.
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.ndivy!: integer that controls the number of labels for ordinate y-axis in each figure. \\Default: \lstinline[basicstyle = \mlttfamily \small ]!3!.
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.Xaxis_lag!: real number that gives in number of days the amount of time by which the x-axis is shifted on each figure. \\Default: \lstinline[basicstyle = \mlttfamily \small ]!0!.
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.isExportTEX!: logical so that if \lstinline[basicstyle = \mlttfamily \small ]!isExportTEX=true!, figures are exported in \LaTeX{} format. \\Default: \lstinline[basicstyle = \mlttfamily \small ]!false!.
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.isExportPNG!: logical so that if \lstinline[basicstyle = \mlttfamily \small ]!isExportPNG=true!,  figures are exported in PNG format. \\Default: \lstinline[basicstyle = \mlttfamily \small ]!false!.
\item \lstinline[basicstyle = \mlttfamily \small ]!misc.options.isExportPDF!: logical so that if \lstinline[basicstyle = \mlttfamily \small ]!isExportPDF=true!,  figures are exported in PDF format. \\Default: \lstinline[basicstyle = \mlttfamily \small ]!false!.
\end{itemize}
\end{itemize}