\par
\section{Data Structure}
\label{section:IIheap:dataStructure}
\par
The {\tt IIheap} object has five fields.
\begin{itemize}
\item
{\tt int size}    : present size of the heap, {\tt 0 <= size < maxsize}
\item
{\tt int maxsize} : maximum size of the heap, set on initialization
\item
{\tt int *heapLoc} :
pointer to an {\tt int} vector of size {\tt maxsize},
{\tt heapLoc[i]} contains the location of item {\tt i},
{\tt heapLoc[i] = -1} if item {\tt i} is not in the heap
\item
{\tt int *keys} :
pointer to an {\tt int} vector of size {\tt maxsize},
{\tt keys[loc]} contains the key at location {\tt loc}
\item
{\tt int *values} :
pointer to an {\tt int} vector of size {\tt maxsize},
{\tt values[loc]} contains the value at location {\tt loc}
\end{itemize}
A correctly initialized and nontrivial {\tt IIheap} object
will have {\tt maxsize > 0} and {\tt 0 <= size < maxsize}.


%!TEX root = kPtx_paper.tex
\section*{Results}

Figure \ref{fig:ErrorMap} shows simulated excitation patterns and error maps for the reference spatial and k-space domain designs.
Both designs were performed with 16 parallel threads and the 64$\times$64$\times$48 grid size (3 mm isotropic resolution),
and the excitation patterns were evaluated against the target pattern on a 128$\times$128$\times$96 grid size (1.5 mm iso-resolution).
The k-space domain design used patch and inclusion widths of 4.
The calculated root-mean-squared errors (RMSEs) were 2.42\% (spatial domain) and 2.68\% (k-space domain),
respectively.
For both design methods, most of the errors appeared at the edges of the transition band,
and errors elsewhere were lower than 5\% of the target flip angle.
This indicates uniform inner volume excitation while maintaining the outer volume intact.
The parallelized k-space domain design required 2.9 seconds computation versus 31.8 seconds for the spatial domain method, a 91\% decrease.

\subsection*{k-Space Algorithm Parameters}
Figure \ref{fig:ComputationTime}a plots mean computation time versus number of parallel threads,
holding the patch and inclusion widths fixed at 4 cycles/FOV.
The computation time decreased rapidly with increasing thread number up to 12 threads,
and then plateaued, likely due to the overhead involved in initiating threads after that point.
Based on this result, the number of threads was held fixed at 16 for subsequent designs when off-resonance was not compensated.

\par Figure \ref{fig:ComputationTime}b plots mean computation time and RMSE with different patch widths.
The computation time decreased up to a patch width of 4 cycles/FOV (corresponding to $4^3 = 64$ simultaneously solved columns of $\bm{W}$)
and then increased sharply for larger patch widths.
RMSE decreased slowly as the patch width increased since the number of excitation trajectory points included in the calculation of weights for each
target point increases on average (and especially for target locations in the middle of each patch) as the patch width increases,
even when the inclusion width stays fixed.
Based on this result, a patch width of 4 cycles/FOV was used for subsequent designs.

\par Figure \ref{fig:ComputationTime}c plots mean computation time and RMSE with different inclusion widths.
The solid lines and dashed lines were obtained with patch widths of 4 and 8 cycles/FOV, respectively.
Computation time increased and error decreased with increasing inclusion width,
since more excitation trajectory points were included in each target location's calculation for increasing inclusion width,
corresponding to an increased $\bm{S}^H\bm{S}$ matrix size.
The RMSE was only slightly lower for a patch width of 8 versus 4 cycles/FOV,
but the computation time was much higher for 8 cycles/FOV, across all inclusion widths.
The knees in the curves occurred approximately at an inclusion width of 4 cycles/FOV,
so this value was used in subsequent designs.

\par Table \ref{fig:wsize} lists the size of the final matrix $\bm{W}$ in gigabytes,
versus inclusion width.
As inclusion width increases, more excitation trajectory points are used in the solution of the weights for each target location,
until the entire trajectory is used for each location (Inclusion width = $\infty$ in the table),
corresponding to a full solution.
With the inclusion width of 4 cycles/FOV used here,
the matrix size was 98\% smaller than that of a full solution.

\subsection*{L-Curves}
Figure \ref{fig:LCurves} plots flip angle RMSE versus RF RMS amplitude for the spatial domain method
and different configurations of the k-space domain method.
The spatial domain method achieves the best overall tradeoff between error and RMS amplitude (dashed black curve),
which is matched by the k-space domain method when all target locations are solved simultaneously with
all excitation trajectory points included and exact $\bm{S}^H\bm{S}$ matrix construction (orange curve).
When the inclusion and patch widths are limited to 4 cycles/FOV but the $\bm{S}^H\bm{S}$
matrices are still constructed exactly, there is an increase in error and RMS amplitude (solid blue curve).
However, a larger penalty is incurred by interpolating the entries of the $\bm{S}^H\bm{S}$ matrices (dashed orange curve)
than by limiting the inclusion and patch widths.
Combining interpolation of the $\bm{S}^H\bm{S}$ matrix entries and patch and inclusion widths of 4 cycles/FOV yield
the dashed blue curve, which has a higher error and RF amplitude than when interpolation or small patch and inclusion widths are
used alone.
Overall, these results and the results in Figure \ref{fig:ComputationTime} and Table \ref{fig:wsize}
show that the k-space domain method allows a tradeoff between computation time and memory usage versus
excitation error and RMS RF amplitude.
The dots on the spatial domain and k-space domain curves indicate the knees of of the curves corresponding to
the $\lambda$ values used for the designs in Figures \ref{fig:ErrorMap}, \ref{fig:ComputationTime}, \ref{fig:kspace_PTX_Acceleration}, and \ref{fig:kspace_PTX_B0}.
Note that the RMSE's in Figure \ref{fig:LCurves} are slightly lower for the spatial domain designs
and slightly higher for the k-space domain designs compared to other figures,
because the flip angle errors in Figure \ref{fig:LCurves} were calculated using
spatial domain non-uniform fast Fourier transforms instead of Bloch equation simulations,
to provide a more direct measure of the design error.

\subsection*{Gibbs Ringing}
Figure \ref{fig:GibbsRing}a shows slices of the excitation error pattern produced by pulses designed by the spatial domain method
on a 32$\times$32$\times$24 grid, which were Bloch-simulated on the original 128$\times$128$\times$96 grid.
There is significant Gibbs ringing in the pattern (indicated by the red arrows),
and the pulses incur a higher RMSE (4.64\%) than pulses designed using either the spatial domain method with a finer 64$\times$64$\times$48 grid
(2.66\%; Figure \ref{fig:GibbsRing}b) or the k-space domain method with a 32$\times$32$\times$24 grid (3.00\%; Figure \ref{fig:GibbsRing}c).
Gibbs ringing is not apparent in either the 64$\times$64$\times$48 spatial domain error pattern or the 32$\times$32$\times$24 k-space domain error pattern.
The RMS RF amplitudes of the low resolution designs were both 0.005.
Note that the error of the 64$\times$64$\times$48 spatial domain design is slightly higher than designs presented in other figures
due to the lower-resolution excitation trajectory.
From a spatial domain point of view,
the Gibbs ringing in the low-resolution spatial domain design was caused by the design's inability to observe and limit the ringing in the low-resolution design grid.
From a k-space domain point of view, the Gibbs ringing in
Figure \ref{fig:GibbsRing}a was due to implicit circulant end conditions at the edges of excitation k-space in the low-resolution
spatial domain design,
which led RF samples at one edge of k-space to wrap-around and affect target locations at the opposite edge of k-space.
This effect is mitigated using a high-resolution spatial domain design grid, as illustrated in Figure \ref{fig:GibbsRing}b.
However, even for a low-resolution k-space domain design there is no wrap-around effect in excitation k-space
because the trajectory points that are incorporated in the weights solution for each patch of target locations are explicitly specified to be those in the immediate vicinity of
the target points, without circulant end conditions.
%Particularly, for the instance problems whose patches are at the edges of the k-space FOV, the excitation trajectory points at the other ends of the k-space FOV will not be incorporated into the design.

%Due to implicit circulant end conditions in k-space for the spatial domain design, t

\subsection*{Excitation k-Space Undersampling}
Figure \ref{fig:kspace_PTX_Acceleration} compares excitation error patterns produced by spatial domain-designed pulses (top row)
and k-space domain-designed pulses (middle row),
for different trajectory reduction factors which resulted in the SPINS trajectories plotted in the third row.
For each design the k-space domain-designed pulses had higher error,
but error increased smoothly with increasing reduction factor, as it did for the spatial domain designs.

\subsection*{Off-Resonance}
Figure \ref{fig:kspace_PTX_B0}a shows the off-resonance maps containing a Gaussian distortion which was centered above the frontal sinus,
and scaled to peak amplitudes of 0, 200, and 400 Hz for the pulse designs and Bloch simulations.
Figure \ref{fig:kspace_PTX_B0}b shows excitation error patterns and RMSEs for spatial domain designs with off-resonance compensation,
and k-space domain designs without and with off-resonance compensation.
Without off-resonance compensation,
the k-space domain-designed pulses produced large ($>$ 10\% of $M_0$) excitation errors both inside and outside the target ellipse.
When the off-resonance map was incorporated in the spatial domain and k-space domain designs,
the distortion was nearly fully corrected when it had a peak amplitude of 200 Hz.
When the map was scaled to a peak of 400 Hz, some large errors remained, with the k-space domain-designed pulses achieving slightly lower RMSE.
%It was also able to provide excitation pattern comparable to spatial domain design with 400 Hz maximum off-resonance. The k-space domain design has a weaker performance with higher off-resonance due to the fact that the time segmentation approximation in Ref \cite{fessler2005toeplitz} was meant to approximate forward models from RF to excitation patterns and does not serve as an accurate approximation to the backward model as we need in the k-space domain design.


\chapter{Conclusions}
\label{ch:end}

We studied the effect of electrical noise on the identification and
reconstruction of output pulses in DarkSide20k silicon photomultipliers (SiPM)
Tiles in \autoref{ch:snr}, \ref{ch:timeres} and~\ref{ch:rate}, and measured the
correlated noise of a Tile in \autoref{ch:anal}. In the following paragraphs we
summarize and comment the results from all chapters.

The main takeaway from \autoref{ch:snr} is in \autoref{fig:changebs}. The
maximum signal to noise ratio (SNR) that can be reached with filtering on that
data is~19, shown on the left panel with the cross correlation filter and
precise baseline calculation. However the constraints of the available
resources on the digitizers may turn out to impose a moving average filter with
imprecise baseline, lowering the SNR to~13, as shown in the central panel. So
the SNR at the digitizer stage can be as low as \SI{65}\% of the optimal one.

In the DarkSide collaboration it was proposed to use an ``autoregressive moving
average'' (ARMA) filter to implement a long cross correlation filter in the
digitizers. The ARMA combines linearly two filters: 1)~a cross correlation with
a template only for the peak of the pulse, and 2)~an autoregressive filter, run
on the \emph{temporally reversed} waveform. This reproduces a cross correlation
with the peak template plus an exponentially decaying tail. Although the
asymptotical complexity of the algorithm is excellent on paper, the actual
amount of logic resources necessary for the implementation on FPGA may exceed
the available ones, mainly due to the necessity of keeping a buffer for the
temporal reversal, and to glue appropriately the reversed temporal slices with
dynamical boundary conditions or partially overlapping slices. From
\autoref{fig:changebs} it is clear that a simple moving average can achieve
performances comparable to a cross correlation filter, thus it may not be
necessary to devise a way to implement the cross correlation filter on the
digitizers.

In \autoref{ch:timeres} there are various things to learn:

\begin{itemize}

    \item The temporal resolution diverges below a certain SNR, giving a
    somewhat rigid bound on the working point, and the behavior at low SNR
    heavily depends on the noise spectrum, \autoref{fig:rescomp}. The
    DarkSide20k simulation currently implements only white noise.

    \item For what concerns temporal resolution, it is sufficient to extract
    \SI{1}{\micro s} of waveform per pulse from the digitizers,
    \autoref{fig:windowtempres}.

    \item Downsampling from \SI{125}{MSa/s} to \SI{62.5}{MSa/s} does not
    deteriorate the temporal resolution, \autoref{fig:tempresdowns} and
    \autoref{tab:filtsnrdowns}. If a compromise with the data rate is
    necessary, \SI{31.2}{MSa/s} might still be good enough.

    \item Upsampling is not necessary, \autoref{fig:rescomp}.

\end{itemize}

The temporal resolution required by the specifications of DarkSide20k is
\SI{10}{ns} \cite[30]{aalseth2018}. A worse resolution would decrease the
selective power of pulse shape discrimination (PSD). With the noise spectrum of
the Proto0 prototype, we find that the temporal resolution reaches \SI{10}{ns}
at pre-filter SNR 2.6, to be compared with the SNR observed in the Proto0 data
of at least 3.3, see \autoref{fig:rescomp}.

Chapter~\ref{ch:rate} has its own summary in \autoref{sec:rateconcl}. In
general the formula for the fake rate is sufficiently precise, but there is an
exception with higher rate than expected that should be investigated better,
see \autoref{fig:fakerate}. With the tested filter, which matches the one
mentioned above for the $\mathrm{SNR} = 13$ figure, the fake rate is
\SI{10}{cps} with the threshold set at 5 filtered noise standard deviations
(including baseline subtraction), to be compared to the maximum total primary
noise rate required, \SI{250}{cps/PDM} \cite[30]{aalseth2018}.

The chapter on correlated noise contains more material, so it includes a rather
long discussion of the results in \autoref{sec:analconcl}. To summarize
further:

\begin{itemize}

    \item Compared to the Fondazione Bruno Kessler (FBK) Tiles, the analyzed
    LFoundry Tile has similar direct cross talk (DiCT) and much less
    afterpulsing (AP).

    \item The afterpulse models should be studied and validated better.

    \item It should be determined whether Tile~21 enters a nonlinear regime
    between \SI{7.5}{VoV} and \SI{9.5}{VoV}, or if the \SI{9.5}{VoV} data is
    mislabeled.

    \item Tile~21 should be analyzed with charge spectrum methods and the
    results compared to ours.

    \item The SiPM simulation must be consistent with the model used in the
    analysis of real data.

\end{itemize}

We put upper bounds on the dark count rate (DCR), respectively \SI{50}{cps},
\SI{170}{cps}, and~\SI{120}{cps} at overvoltages \SI{5.5}V, \SI{7.5}V,
and~\SI{9.5}V, to be compared with the required upper limit \SI{250}{cps}. We
give upper bounds for AP probabilities of \SI{2.5}\%, \SI{3.5}\% and
\SI{6.5}\%, and estimate DiCT probabilities \SI{20}\%, \SI{30}\% and~\SI{50}\%.
These are the probabilities of said noises being generated by a \SI1{PE} pulse.
The DarkSide20k specifications require the sum of correlated noise
probabilities to be less than \SI{60}\% \cite[30]{aalseth2018} in order to
avoid performance degradation, mainly dynamic range reduction on ionization
signals, where there is a lot of pile-up. Furthermore, some safety margin
should be considered for the aging of the SiPMs, which is not well studied, in
case the correlated noise probability turned out to increase with time. Recall
that, for a correlated noise probability $p$, the ratio of total pulses to
primary pulses is $1/(1-p)$, which diverges quite fast as $p$ goes to~1.
\cite[8]{gola2019} mention that in practice the maximum manageable probability
is \SI{50}\%.

\marginpar{Explain the stuff from Simone in the TF2 report.}


\section{\module{calendar} ---
         General calendar-related functions}

\declaremodule{standard}{calendar}
\modulesynopsis{Functions for working with calendars,
                including some emulation of the \UNIX\ \program{cal}
                program.}
\sectionauthor{Drew Csillag}{drew_csillag@geocities.com}

This module allows you to output calendars like the \UNIX{}
\program{cal} program, and provides additional useful functions
related to the calendar. By default, these calendars have Monday as
the first day of the week, and Sunday as the last (the European
convention). Use \function{setfirstweekday()} to set the first day of the
week to Sunday (6) or to any other weekday.  Parameters that specify
dates are given as integers.

Most of these functions rely on the \module{datetime} module which
uses an idealized calendar, the current Gregorian calendar indefinitely
extended in both directions.  This matches the definition of the
"proleptic Gregorian" calendar in Dershowitz and Reingold's book
"Calendrical Calculations", where it's the base calendar for all
computations.

\begin{funcdesc}{setfirstweekday}{weekday}
Sets the weekday (\code{0} is Monday, \code{6} is Sunday) to start
each week. The values \constant{MONDAY}, \constant{TUESDAY},
\constant{WEDNESDAY}, \constant{THURSDAY}, \constant{FRIDAY},
\constant{SATURDAY}, and \constant{SUNDAY} are provided for
convenience. For example, to set the first weekday to Sunday:

\begin{verbatim}
import calendar
calendar.setfirstweekday(calendar.SUNDAY)
\end{verbatim}
\versionadded{2.0}
\end{funcdesc}

\begin{funcdesc}{firstweekday}{}
Returns the current setting for the weekday to start each week.
\versionadded{2.0}
\end{funcdesc}

\begin{funcdesc}{isleap}{year}
Returns \constant{True} if \var{year} is a leap year, otherwise
\constant{False}.
\end{funcdesc}

\begin{funcdesc}{leapdays}{y1, y2}
Returns the number of leap years in the range
[\var{y1}\ldots\var{y2}), where \var{y1} and \var{y2} are years.
\versionchanged[This function didn't work for ranges spanning
                a century change in Python 1.5.2]{2.0}
\end{funcdesc}

\begin{funcdesc}{weekday}{year, month, day}
Returns the day of the week (\code{0} is Monday) for \var{year}
(\code{1970}--\ldots), \var{month} (\code{1}--\code{12}), \var{day}
(\code{1}--\code{31}).
\end{funcdesc}

\begin{funcdesc}{weekheader}{n}
Return a header containing abbreviated weekday names. \var{n} specifies
the width in characters for one weekday.
\end{funcdesc}

\begin{funcdesc}{monthrange}{year, month}
Returns weekday of first day of the month and number of days in month,
for the specified \var{year} and \var{month}.
\end{funcdesc}

\begin{funcdesc}{monthcalendar}{year, month}
Returns a matrix representing a month's calendar.  Each row represents
a week; days outside of the month a represented by zeros.
Each week begins with Monday unless set by \function{setfirstweekday()}.
\end{funcdesc}

\begin{funcdesc}{prmonth}{theyear, themonth\optional{, w\optional{, l}}}
Prints a month's calendar as returned by \function{month()}.
\end{funcdesc}

\begin{funcdesc}{month}{theyear, themonth\optional{, w\optional{, l}}}
Returns a month's calendar in a multi-line string. If \var{w} is
provided, it specifies the width of the date columns, which are
centered. If \var{l} is given, it specifies the number of lines that
each week will use. Depends on the first weekday as set by
\function{setfirstweekday()}.
\versionadded{2.0}
\end{funcdesc}

\begin{funcdesc}{prcal}{year\optional{, w\optional{, l\optional{c}}}}
Prints the calendar for an entire year as returned by
\function{calendar()}.
\end{funcdesc}

\begin{funcdesc}{calendar}{year\optional{, w\optional{, l\optional{c}}}}
Returns a 3-column calendar for an entire year as a multi-line string.
Optional parameters \var{w}, \var{l}, and \var{c} are for date column
width, lines per week, and number of spaces between month columns,
respectively. Depends on the first weekday as set by
\function{setfirstweekday()}.  The earliest year for which a calendar can
be generated is platform-dependent.
\versionadded{2.0}
\end{funcdesc}

\begin{funcdesc}{timegm}{tuple}
An unrelated but handy function that takes a time tuple such as
returned by the \function{gmtime()} function in the \refmodule{time}
module, and returns the corresponding \UNIX{} timestamp value, assuming
an epoch of 1970, and the POSIX encoding.  In fact,
\function{time.gmtime()} and \function{timegm()} are each others' inverse.
\versionadded{2.0}
\end{funcdesc}

\begin{seealso}
  \seemodule{datetime}{Object-oriented interface to dates and times
                       with similar functionality to the
                       \refmodule{time} module.}
  \seemodule{time}{Low-level time related functions.}
\end{seealso}


%-----------------------------------------------------------------------------
%
%               Template for sigplanconf LaTeX Class
%
% Name:         sigplanconf-template.tex
%
% Purpose:      A template for sigplanconf.cls, which is a LaTeX 2e class
%               file for SIGPLAN conference proceedings.
%
% Guide:        Refer to "Author's Guide to the ACM SIGPLAN Class,"
%               sigplanconf-guide.pdf
%
% Author:       Paul C. Anagnostopoulos
%               Windfall Software
%               978 371-2316
%               paul@windfall.com
%
% Created:      15 February 2005
%
%-----------------------------------------------------------------------------

\documentclass[nocopyrightspace,blockstyle,numbers]{sigplanconf}

% The following \documentclass options may be useful:

% preprint      Remove this option only once the paper is in final form.
% 10pt          To set in 10-point type instead of 9-point.
% 11pt          To set in 11-point type instead of 9-point.
% numbers       To obtain numeric citation style instead of author/year.

\usepackage{amsmath}
\usepackage[utf8]{inputenc}

\newcommand{\cL}{{\cal L}}

\begin{document}

\special{papersize=8.5in,11in}
\setlength{\pdfpageheight}{\paperheight}
\setlength{\pdfpagewidth}{\paperwidth}

\conferenceinfo{CONF 'yy}{Month d--d, 20yy, City, ST, Country}
\copyrightyear{20yy}
\copyrightdata{978-1-nnnn-nnnn-n/yy/mm}
\copyrightdoi{nnnnnnn.nnnnnnn}

% Uncomment the publication rights you want to use.
%\publicationrights{transferred}
%\publicationrights{licensed}     % this is the default
%\publicationrights{author-pays}

%\titlebanner{banner above paper title}        % These are ignored unless
%\preprintfooter{short description of paper}   % 'preprint' option specified.

\title{Coq's Prolog and application to defining semi-automatic tactics}
%\subtitle{Subtitle Text, if any}

\authorinfo{Théo Zimmermann \and Hugo Herbelin}
           {IRIF, Université Paris Diderot, Université Sorbonne Paris-Cité\\ $\Pi R ^2$, INRIA}
           {theo.zimmermann@univ-paris-diderot.fr / hugo.herbelin@inria.fr}
%\authorinfo{Name1}
%           {Affiliation1}
%           {Email1}
%\authorinfo{Name2\and Name3}
%           {Affiliation2/3}
%           {Email2/3}

\maketitle

\begin{abstract}
  We report on a work-in-progress to re-implement Coq's \texttt{apply}
  tactic in order to embed some form of simple automation. We design
  it in a declarative way, relying on \texttt{typeclasses eauto}, a tactic
  which gives access to the proof-search mechanism behind type classes.
  We qualify this mechanism of ``Coq's Prolog'' and describe it in a
  generic way and explain how it can be used to support the
  construction of automatic and semi-automatic tactics.
\end{abstract}

%\category{CR-number}{subcategory}{third-level}

% general terms are not compulsory anymore,
% you may leave them out
%\terms
%term1, term2

\keywords
apply, automation, Coq, proof assistant, reflection,
type theory, views.

\section{Introduction}

Since version 8.2 \cite{coq86manual}, Coq has included a type class
mechanism which can intervene during type-inference. The resolution
phase of this mechanism is also accessible via the user-side tactic
\texttt{typeclasses eauto}. In fact \texttt{typeclasses eauto}
implements a general Prolog-like proof-search mechanism that can be
instrumented to do much more. While by default, it uses the specific
\texttt{typeclass\_instances} hint database, one can use it with
alternative hint databases. In this case, despite the name of the
tactic, it has nothing to do with the type class mechanism anymore
(apart from the underlying implementation). It can be viewed as a
re-implementation of the former \texttt{eauto} tactic, dating back
from Coq version 5.10.

Many partially automated tactics have already been built upon Coq's type
class mechanism. One example is the re-implementation of the \texttt{rewrite}
tactic \cite{sozeau2010new}, which relies on the mechanism in
a second phase of constraint resolution. Another is our \texttt{transfer}
library \cite{zimmermann}. We argue that both of these applications (and
many others) abuse the type class mechanism, by polluting the
\texttt{typeclass\_\\instances} hint database, when they should instead
define their own disjoint hint databases and rely on the underlying
Prolog-like proof-search mechanism that is made accessible via the
\texttt{typeclasses eauto} tactic.

We demonstrate the usefulness of this ``Coq's Prolog'' with a small
re-implementation of the \texttt{apply} tactic. This tactic is parame\-trized
by a set of ``views'' à la SSReflect \cite{gonthier} which it is
able to apply automatically. It also demonstrates a new way of instrumenting
\texttt{typeclasses eauto} to progress on a goal instead of solving it
(``forward mode'', proposed in particular by Michael Soegtrop
on the Coq-Club mailing list).

\section{Presentation of Coq's Prolog}

The \texttt{typeclasses eauto} tactic is documented in the chapter on
type classes of Coq's user manual \cite[Chapter~20]{coq86manual}.
Like \texttt{eauto}, it is possible to specify on which hint database it
should operate using the \texttt{with myhintdb} clause.
By default, the proof-search depth is unbounded and the traversing
strategy is depth-first. It is also possible to limit the proof-search
depth, and an alternative iterative-deepening traversing strategy exists.

Most hints are lemmas which can be read as Prolog Horn clauses.
For instance:

\begin{verbatim}
Lemma or_introl : forall A B, A -> A \/ B.
\end{verbatim}
can be read as the clause\footnote{We introduce the Prolog predicate
  \texttt{prove} to denote the idea that the hints are used when looking
  for a proof of a statement. When using \text{typeclasses eauto} to
  solve type class goals, there is always a head-constant (the type class)
  which can serve the same role as \texttt{prove} but when using it on
  non-type-class goals, it is not necessarily the case.}:

\begin{verbatim}
prove(or(A,B)) :- prove(A).
\end{verbatim}
Such hints can be introduced with the \texttt{Hint Resolve} command:

\begin{verbatim}
Hint Resolve or_introl : myhintdb.
\end{verbatim}

Some more complex hints can be introduced thanks to the
\texttt{Hint Extern} command. One very special application of
such external hints is to put some sub-goals ``on the shelf'':

\begin{verbatim}
Hint Extern 0 (solveLater _) =>
  unfold solveLater; shelve : myhintdb.
\end{verbatim}

The shelf is a special place in the Coq proof engine which is
normally reserved to sub-goals that will be solved by solving other
sub-goals that depend on them. It can be instrumented to temporarily
store away some sub-goals that we want to keep for later (at which
time they will be ``unshelved'').
The ``unshelve'' tactical can be used to put back in the list of
sub-goals to solve those which had been shelved by the tactic it is
applied on.
Thus, a combination of the previous external hint plus a call to
\texttt{unshelve typeclasses eauto with myhintdb} is a way to use
this Prolog-like proof-search mechanism in forward mode, instead of
the normal solving mode.

Finally, a control operator on the search space is available. It is
not comparable to Prolog's cut operator in that it allows to specify
regular expressions of search-paths which should be cut but does
not restrict backtracking. It is still
limited in that regular expressions can only talk about hints
declared with \texttt{Hint Resolve} and not \texttt{Hint Extern}.
Additionally, there is no negative expressions and even if regular
expressions are known to be closed under complement, the construction
requires to know all the alphabet, which is not the case here since
new hints can be added dynamically. We can expect to see improvements
in control operators for \texttt{typeclasses eauto} in the next versions
of Coq. Here is an example\footnote{Be careful when using it that the
precedence levels are not what one would expect. They should get fixed
in Coq 8.7 but, in the meantime, the best way of writing
forward-compatible code is to parenthesize everything.}
of using this control operator to forbid any proof using \texttt{or\_introl} twice:

\begin{verbatim}
Hint Cut [(_*) or_introl (_*) or_introl] : myhintdb.
\end{verbatim}

\section{An \texttt{apply} tactic with views}

Our work is part of a larger effort to make the life of mathematicians
using Coq easier. The specific issue we address here is to design an
extension of the \texttt{apply} tactic which embeds some bits of
trivial reasoning, such as reasoning modulo symmetry of equations
(identifying \texttt{u = t} and \texttt{t = u}).
There is already a little bit of hard-coded trivial reasoning in the
current implementation (automatic decomposition of single-constructor
inductive types): for instance it supports applying a theorem
of the form \verb|A -> B /\ C| to a goal of the form \texttt{B}.

SSReflect defines views which are basically small theorems of
the form \texttt{A -> B} where \texttt{A} is a different way of
viewing \texttt{B}. Our re-implementation of \texttt{apply} tries to
solve the problem we were describing by allowing the user to
parametrize it with such ``views''. Without any view, it is less
powerful than the current implementation (because of the absence of
decomposition of single-constructor inductive types). With many
views, it can be much more powerful. The various levels of
parametrization could reveal especially useful for teaching (from a
level where everything must be done by hand, to a level where most
details are handled automatically).

Given the inspiration source we described in the previous paragraph,
an obvious application of our work will be to support automatic
insertion of views in the context of small scale reflection. In
particular, it will be possible to simply register the reflection
lemma:

\begin{verbatim}
Lemma andP : forall b1 b2 : bool, reflect
  (b1 = true /\ b2 = true) ((b1 && b2) = true).
\end{verbatim}
in a special hint database and \texttt{apply} will know about it
and use it when necessary.

There are two main ideas in our implementation. The first is that
we are launching a proof search to prove that the theorem
we wish to apply implies the current goal:

\begin{verbatim}
?prove : arrow theorem goal
\end{verbatim}
where \texttt{arrow} is a relation that is definitionally equal to Coq's implication.
We use it because otherwise the proof-search mechanism would introduce
the premise \texttt{theorem} in the proof context and then try
to prove \texttt{goal} with it, and this is not what we want.

The second is that although we cannot actually prove this implication
most of the time, we can provide an incomplete proof and let the
user fill the holes (this is after all the principle of
\texttt{apply}):

\begin{verbatim}
solveLater A -> arrow B C -> arrow (A -> B) C
\end{verbatim}
where \texttt{solveLater} is a dummy constant introduced to call the
external hint we described earlier, which will shelve the sub-goal
\texttt{A} until the full search succeeds and then unshelve it for the
user to prove. In fact, because the conclusion \texttt{B} might be
dependent on the premise \texttt{A}, we rather write:

\begin{verbatim}
forall (t : T), arrow (U t) V ->
  arrow (forall x : T, U x) V
\end{verbatim}
and then shelve \texttt{t}.
A few other generic rules are present, one of them allowing to
go under quantifiers and, of course, the reflexivity of arrow:

\begin{verbatim}
(forall x : A, arrow (f x) (g x)) ->
  arrow (forall x : A, f x) (forall x : A, g x)

arrow T T
\end{verbatim}

With these rules only, we can reproduce the behavior of
\texttt{apply}, except for the built-in handling of
single-constructor inductive types.
Actually already at that point, we do not reproduce the
exact same behavior because our implementation allows
applying a theorem \texttt{forall x y, P x y}
to a goal \texttt{forall x, P x 0}.

With this basic infrastructure in place, we can start
adding views, such as:

\begin{verbatim}
arrow P P' -> arrow (P /\ Q) P'
arrow Q Q' -> arrow (P /\ Q) Q'
\end{verbatim}
which will be useful in emulating the current behavior
of \texttt{apply}. We can also add a very simple rule to
handle symmetry (one could think of more complex and
powerful ways):

\begin{verbatim}
arrow (u = t) (t = u)
\end{verbatim}
and finally, we register some more generic rules like:

\begin{verbatim}
reflect P b -> arrow P (b = true)
reflect b P -> arrow (b = true) P
\end{verbatim}
so that people can easily extend the hint database with
existing reflection lemmas such as the one seen above.

\section{Conclusion}

This work is very preliminary but shows an interesting path
to removing some of the hindrances there are in using
both SSReflect and vanilla Coq.
It is also a demonstration of the power of
\texttt{typeclasses eauto}, even when not working with
type classes.
Sometimes, the type class mechanism has been used while what
was really wanted was this Coq's Prolog that it gives access to.
One such example is the implementation of \texttt{rewrite}:
it probably could and should be based on a specific hint
database instead of the \texttt{typeclass\_instances} database.

We are planning first to continue to test and improve our
re-implementation of \texttt{apply}. We would in particular like
to have views for applying a theorem modulo commutativity /
associativity. We are also planning to merge this work with our
previous work on applying theorems modulo isomorphisms
\cite{zimmermann}. A lot of ideas from this earlier work were
reused here and the two implementations could very likely be
combined together.

%\appendix
%\section{Appendix Title}

%This is the text of the appendix, if you need one.

%\acks

%Acknowledgments, if needed.

% We recommend abbrvnat bibliography style.

\bibliography{coq-prolog}
\bibliographystyle{abbrvnat}

% The bibliography should be embedded for final submission.

%\begin{thebibliography}{}
%\softraggedright

%\bibitem[Smith et~al.(2009)Smith, Jones]{smith02}
%P. Q. Smith, and X. Y. Jones. ...reference text...

%\end{thebibliography}

\end{document}