\section{Introduction}
Many applications require the evaluation of multivariate polynomials over finite fields. For instance, the so called affine codes (also called evaluation or functional or algebraic geometry codes) are obtained evaluating a finite-dimensional linear subspace
of $\mathbb {F}_q[x_1,\dots ,x_r]$ at a finite set $S\subseteq \mathbb {F}_q^r$ (\cite{g}, \cite{h}, \cite{l} and several other papers).
When the degree $n$ of the polynomials is small, and/or the number $r$ of variables is also small the direct computation is
efficient, however as $n$, or $r$, or both become large, evaluation becomes an issue. The case of univariate polynomials was considered by several authors, see e.g \cite{patterson}, \cite{pan} and some recent papers (\cite{ers1}, \cite{ERS}).
In this paper we propose an evaluation method for multivariate polynomials
which reduces significantly the multiplicative complexity and hence
the computational burden.

\noindent
Set $M_r(n)=\binom{n+r}{r}$, and let $p(x_1, \ldots,x_r)$ be a polynomial of degree $n$ in $r$
 variables with coefficients in a finite field $\mathbb{F}_{p^s}$; the number of monomials occurring in
 $p(x_1, \ldots,x_r)$ is $M_r(n)$.
We will consider the evaluation of $p(x_1, \ldots,x_r)$ at a point
 $\mathbf a=(\alpha_1, \ldots, \alpha_r) \in F_{p^m}^{r}$, where $m$ is divisible by $s$.
A direct evaluation of $p(\alpha_1, \ldots, \alpha_r)$
 is obtained from the evaluation of the $M_r(n)$ distinct monomials, a task requiring $M_r(n)-r-1$
 multiplications. Therefore we perform $M_r(n)-1$ multiplications, and a total number
 $A_r(n)=M_r(n)-1$ of additions. The total number of required multiplications is
$$  P_r(n)= 2M_r(n)-r-2 = 2\frac{n^r}{r!}+\frac{r+1}{(r-1)!}n^{r-1}+ \cdots -1-r  \,, $$
however different computing strategies can require a significant smaller number of multiplications.
To the aim of developing some of these strategies, the polynomial $p(x_1, \ldots,x_r)$ is written as a sum
\begin{equation}
   \label{eqint}
   p(x_1, \ldots,x_r) = \sum_{i=0}^{s-1} \beta^i q_i(x_1, \ldots,x_r)
\end{equation}
of $s$ polynomials, where each $q_i(x_1, \ldots,x_r)$ is a polynomial of degree $n$ in $r$ variables
 with coefficients in the prime field $\mathbb {F}_p$, the value $p(\alpha_1, \ldots, \alpha_r)$ can be obtained from the $s$ values
 $q_i(\alpha_1, \ldots, \alpha_r)$, $2s-2$ multiplications, and $s$ additions in $\mathbb {F}_{p^m}$. In these
 computations $\beta$ and its powers constitute a basis of $\mathbb {F}_{p^m}$.
Therefore, we may restrict our attention to the evaluation at a point $\mathbf a \in \mathbb{F}_{p^m}^{r}$
 of a polynomial $q(x_1, \ldots,x_r)$, in $r$ variables, of degree $n$ over $\mathbb{F}_p$.

\vspace{3mm}
\noindent
As pointed out in \cite{ERS}, \S 2.1, the prime $2$ is particularly interesting because
of its occurrence in many practical applications, for example in error correction coding. Furthermore, in
 $\mathbb{F}_2$ multiplications are trivial.
Therefore, we give first a description of our method in the easiest
case, that is, over $\mathbb{F}_2$ and with two variables.
Later, we generalize to any setting.

\section{Our computational model}

There are two kinds of multiplications that are involved in our computations:
field multiplications in the coefficient field $\mathbb{F}_{p^s}$ and in extension
field $\mathbb{F}_{p^m}$.
We assign cost $1$ to any of these, except for the multiplications
by $0$ or $1$, that cost $0$ in our model.
\begin{remark}
There can be multiplications that cost much less, such as squares
in characteristic $2$, but we still treat them as cost $1$.
\end{remark}
As customary, we assign cost $0$ to any data reading.

We could count separately field sums, but our aim is to minimize
the number of field multiplications, and so we use as implicit upper
bound for the number of sums the value $2M_r(n)$, that is, twice the number of
all monomials.
We will not discuss of the number of sums any further.

We assume that an ordering on monomials is chosen once and for all,
e.g. the degree lexicographical ordering
(see \cite{CGC-cd-inbook-D1moratech}), so that
our input data can be modeled as an $\mathbb{F}_{p^s}$ string, any entry
corresponding to a polynomial coefficient.

\begin{remark} \label{qq}
A well-established method to evaluate all monomials up to degree $n$
at a given point is to start from degree-$1$ monomials and then
iterate from degree-$r$ monomials to degree-$r+1$ monomials,
since the computations of any degree-$r+1$ monomial requires only
one multiplication, once you have in memory all degree-$r$ monomials.
\end{remark}

We remark here that our algorithm accepts as input {\emph any} polynomial
of a given total degree and so our estimates are worst-case complexity,
which translates in considering dense polynomials.
Clearly, other faster methods could be derived for special classes of polynomials,
such as sparse polynomials or polynomials with a predetermined algebraic structure.

We will not discuss the memory requirement of our methods, but one can
see easily by inspecting the following algorithms that it is negligible
compared to their computational effort.

\section{The case $r=2$, $p=2$}
A polynomial $P(x, y)$ of degree $n$ in $2$ variables over the binary field may be decomposed
into a sum of $4$ polynomials as
\begin{eqnarray}
 \label{eq0}
P(x, y) &=& P_{0,0} (x^2, y^2)+ xP_{1,0} (x^2, y^2) + yP_{0,1} (x^2, y^2) + x yP_{1,1} (x^2, y^2) \nonumber \\
&=&  P_{0,0} (x, y)^2+ xP_{1,0} (x, y)^2 + yP_{0,1} (x, y)^2 + x yP_{1,1} (x, y)^2.
\end{eqnarray}
where $P_{i, j}(x, y)$ are polynomials of degree $\lfloor \frac{n-i-j}{2}\rfloor$.
Therefore the value of $P(x, y)$ in the point $\mathbf a = (\alpha_1, \alpha_2) \in \mathbb{F}_{2^m}^2$
 can be obtained by computing the $4$ numbers $P_{i, j} (\alpha_1, \alpha_2)$, the monomial
 $\alpha_1 \alpha_2$, performing $3$ products $\alpha_1 P_{1, 0} (\alpha_1, \alpha _2)$,
 $\alpha_2 P_{0, 1} (\alpha_1, \alpha_2)$, and $\alpha_1 \alpha_2 P_{1, 1} (\alpha_1, \alpha_2)$,
 and finally performing $3$ additions.
We observe that all $P_{i,j}$'s have the same possible monomials, i.e. all
monomials of degree up to $\lfloor \frac{n}{2}\rfloor$.
There is no need to store separately $P_{0,0},P_{0,1},P_{1,0},P_{1,1}$,
because the selection of any of these is obtained by a trivial indexing
rule.
 The polynomials $P_{i, j}(\alpha_1, \alpha_2)$ can be evaluated as sums of such monomials,
  which can be evaluated once for all.
Therefore, $P(\alpha_1, \alpha_2)$ is obtained performing (see Remark \ref{qq})
a total number of
  $$P_r(n)=4+3+ \frac{(\lfloor \frac{n}{2} \rfloor +2)(\lfloor \frac{n}{2} \rfloor +1) }{2} -3 \approx
       \frac{n^2}{8} $$
   multiplications, a figure considerably less than $\frac{n^2}{2}$ as required by the direct computation.
 However, the mechanism can be iterated, and the point is to find the number of steps yielding
  the maximum gain, that is to find the most convenient degree of the polynomials that should be
  directly evaluated. We have the following:
\begin{Theorem}
 \label{theo1}
 Let $P(x,y)$ be a polynomial of degree $n$ over $\mathbb{F}_2$, its evaluation at a point
  $(\alpha_1, \alpha_2) \in \mathbb{F}_{2^m}^2$ performed by applying repeatedly the
  decomposition (\ref{eq0}),  requires a number $G_2(n,2,L_{opt})$ of products which asymptotically is
$$
G_2(n,2,L_{opt}) \approx c \sqrt{\frac{7}{6} } n~~~~c < 5 ~~~~~~~~~~.
$$
where $L_{opt}$, the number of iterations yielding the minimum of $G_2(n,2,L)$,
 is an integer included into the interval
$$     -  \frac{1}{2} + \log_4 (\sqrt{\frac{6}{7}} n) +\epsilon < {L_{op}} <
          \log_4 ( \sqrt{\frac{6}{7}}) n +\epsilon' ~~, $$
where $\epsilon$ and $\epsilon'$ are less than $1$ and $O(\frac{1}{\sqrt n})$.
\end{Theorem}

\noindent
{\sc Proof}. The polynomial $P(x,y)$ is decomposed into the sum of $4$ polynomials that are
perfect squares over $\mathbb{F}_2$, each of which is the similarly decomposed.
 Let $P_{i, j}^{(L,h)} (x, y)$ denote the polynomials at the $L$-step of this iterative process,
 with $h$ varying from $1$ to $4^{L-1}$. The number of polynomials after $L$ steps is $4^L$,
 while their degrees are not greater than $\lfloor \frac{n}{2^L}\rfloor$.
The value $P(\alpha_1, \alpha_2)$ is obtained performing backward the reconstruction process
 obtaining at each step the values $P_{i,j}^{(\ell-1,h)} (\alpha_1, \alpha_2)$ from the values
 $P_{i,j}^{(\ell,h)} (\alpha_1, \alpha_2)$, whereas the $4^L$ numbers $P_{i,j}^{(L,h)} (\alpha_1, \alpha_2)$, $i,j \in \{0,1 \}$ and $h=0, \ldots , 4^{L-1}$,  are computed from the direct
 evaluation of $M_2(\lfloor \frac{n}{2^L}\rfloor )$ monomials using $M_2(\lfloor \frac{n}{2^L}\rfloor )-3$ multiplications.

 Therefore the total number of multiplications necessary to obtain $P(\alpha_1, \alpha_2)$ is a sum of
 $M_2(\lfloor \frac{n}{2^L}\rfloor)-3$ with
\begin{itemize}
  \item[-] the number of squares
$$  \frac{4}{3}(4^{L}-1) = [4^{L}+ 4^{L-1}+\cdots +4^{L-L+1} ]    $$
  \item[-] the number of multiplications of kind $x^iy^j P_{i,j}(\alpha_1, \alpha_2)$
$$ 4^{L}-1= 3 [4^{L-1}+ 4^{L-2}+\cdots +4^{L-L} ]   $$
\end{itemize}
 that is the total number is:
$$ G_2(n,2,L) = \frac{7}{3}(4^{L}-1)+\frac{(\lfloor \frac{n}{2^L} \rfloor +1)(\lfloor \frac{n}{2^L} \rfloor +2)}{2}-3  $$
The number of products required to evaluate $P(\alpha_1, \alpha_2)$ in this way is a function
 of $L$, and the values of $L$ that correspond to local minima are specified by the conditions
$$ G_2(n,2,L) \leq G_2(n,2, L-1) ~~\mbox{and}~~ G_2(n,2,L) \leq G_2(n,2,L + 1)   ~~, $$
from which, it is straightforward to obtain the conditions
$$ \begin{array}{l}
  4^L -  \frac{3}{56} \frac{n^2}{4^L} > \frac{n}{2^L14}( \frac{3}{2}-\{\frac{n}{2^L}\})+ (\{\frac{n}{2^L}\}- \{\frac{n}{2^L 2}\}) \left(\frac{-3}{14}+ \frac{1}{14} (\{\frac{n}{2^L}\}+\{\frac{n}{2^L 2}\})+ \frac{1}{2} \right)       \\
            \\
     4^L -  \frac{6}{7} \frac{n^2}{4^L} <
     \frac{4n}{2^L7} (\frac{3}{2}+\{\frac{n}{2^L}\}-2 \{\frac{2n}{2^L}\})- \frac{2}{7} (\{\frac{n}{2^L}\}^2-
      \{\frac{2n}{2^L}\}^2) +\frac{6}{7} (\{\frac{n}{2^L}\}- \{\frac{2n}{2^L}\}) \\
   \end{array} $$
where $\{x\}$ denotes the fractional part of $x$.
These inequalities show that there is only one minimum that corresponds to a value of $L$ such that
$$     -  \frac{1}{2} + \log_4 (\sqrt{\frac{6}{7}} n) +\epsilon < {L_{op}} <
          \log_4 ( \sqrt{\frac{6}{7}}) n +\epsilon' ~~, $$
where $\epsilon$ and $\epsilon'$ are $O(\frac{1}{\sqrt n})$.
Therefore, the minimum value of $G_2(n,2,L)$ is asymptotically
$$  G_2(n,2,L_{op}) \approx c \sqrt{\frac{7}{6}} n  $$
where $c$ is a constant less than $5$. \begin{flushright} $\Box$ \end{flushright}

\begin{remark}\label{b1}
In the computations of our bounds we essentially compute separately each monomial. Hence our approach seems to be very efficient for the computation of several polynomials at the same point. This fact is exploited
 in the computation of the required number of multiplications when the polynomial coefficients are in $\mathbb{F}_{2^s}$. An application of equation (\ref{eqint}) and Theorem \ref{theo1} would give
 the asymptotic estimate
$$  G_{2^s}(n,2,L_{op}) \approx c \sqrt{\frac{7}{6}} n  s~~. $$
since the evaluation of any $q_i$ would cost $c \sqrt{\frac{7}{6}}n$.
 However, the polynomials $q_i(x,y)$ can be evaluated contemporarily. Therefore, computing the power necessary
  to evaluate the polynomial at step $L$ only once, this lead to a total number or required multiplications
$$ G_{2^s}(n,2,L) = s\frac{7}{3}(4^{L}-1)+\frac{(\lfloor \frac{n}{2^L} \rfloor+1)(\lfloor \frac{n}{2^L} \rfloor+2)}{2}-3  $$
because only the reconstruction operations need to be repeated $s$ times. By repeating the argument outlined in the proof of Theorem \ref{theo1}, the conclusion is that the optimal value of $L$ depends also on $s$ and  asymptotically the required value of multiplications is
$$  G_{2^s}(n,2,L_{op}) \approx c' \sqrt{\frac{7}{6}} n \sqrt s ~~. $$
\end{remark}

\section{The case $r>2$, $p=2$}

The evaluation of a polynomial $P(x_1, \ldots, x_r)$ in $r$ variables can be done writing $P$, similarly to equation (\ref{eq0}),
this polynomial as a sum of $2^r$  polynomials
\begin{eqnarray}
  \label{eq1}
P(x_1, \ldots, x_r) &=& \sum_{i_1, \ldots, i_r \in \{0,1 \}}
x_1^{i_1} \ldots x_r^{i_r} P_{i_1, \ldots, i_r} (x_1^{2}, \ldots, x_r^{2})  \nonumber \\
&=&  \sum_{i_1, \ldots, i_r  \in  \{0,1\}} x_1^{i_1} \ldots x_r^{i_r}
\left( P_{i_1, \ldots, i_r} (x_1, \ldots, x_r) \right)^2\,,
\end{eqnarray}
where $P_{i_1, \ldots, i_r} (x_1, \ldots, x_r)$ is a polynomial of degree
$\frac{n-\sum i_j}{2}$.
The argument of Theorem \ref{theo1} still applies, and the minimum number of steps
 is obtained in the following theorem.
\begin{Theorem}
 \label{theo2}
 Let $L_{opt}$ be the number of steps of this method yielding the minimum number of products, $G_2(n,r,L_{op})$, required to evaluate a polynomial of degree $n$ in $r$ variables,
  with coefficients in $\mathbb{F}_2$. Then $L_{opt}$ is an integer that asymptotically is
  included into the interval
$$ -\frac{1}{2} + \frac{1}{2r} \log_2 \frac{2^r-1}{r!(2^{r+1}-1)} +\frac{\log_2 n}{2}  \leq  L_{op} \leq
   \frac{1}{2} + \frac{1}{2r} \log_2 \frac{2^r-1}{r!(2^{r+1}-1)} +\frac{\log_2 n}{2}   $$
that is $L_{op}$ is the integer closest to $\frac{1}{2r} \log_2 \frac{2^r-1}{r!(2^{r+1}-1)} +\frac{\log_2 n}{2}$.
Asymptotically the minimum $G_2(n,r,L_{op})$ is included into the interval:
$$ \frac{1}{\sqrt{2^r}} \sqrt{4\frac{2^{r+1}-1}{2^r-1} \frac{1}{r!}}  n^{r/2} <  G_2(n,r,L_{op}) <
            \sqrt{2^r}  \sqrt{4\frac{2^{r+1}-1}{2^r-1} \frac{1}{r!}}  n^{r/2}~~. $$
\end{Theorem}
\noindent
{\sc Proof}. Using equation (\ref{eq1}) the polynomial $P(x_1, \ldots, x_r)$ evaluated at the point
 $\mathbf a = (\alpha_1, \ldots, \alpha_r) \in \mathbb{F}_{2^m}^r$
 can be obtained from the evaluation of all $P_{i_1, \ldots, i_r} (x_1, \ldots, x_r)$ at $\mathbf a$,
 by  evaluating  $2^r$ monomials  $\alpha_1^{i_1} \ldots \alpha_r^{i_r}$ (which
 require $2^r-r-1$ multiplications),  performing $2^r$ squaring,
 combining these factors with $2^r-1$ multiplications, and finally
adding the results. \\
We can iterate this procedure: at each step the number of polynomials
$P_{i,j}$'s is multiplied by $2^r$ and their
degrees are divided at least by $2$. Therefore, after $L$ steps the number of polynomials is $2^{Lr}$ and their degrees are not greater than $\lfloor \frac{n}{2^L} \rfloor$. Once the $2^r$ numbers $P_{i_1, \ldots, i_r} (\alpha_1, \ldots, \alpha_r)$ are known, the total number of squaring is
$$   2^{rL}+ 2^{r(L-1)}+\cdots +2^{r(L-L+1))} = \frac{2^r}{2^r-1} (2^{rL}-1) $$
and  the number of products necessary to obtain $P(\alpha)$ is
$$  (2^r-1) [2^{r(L-1)}+ 2^{r(L-2)}+\cdots +2^{r(L-L))} ]=2^{rL}-1 \,, $$
hence the total number of required multiplications is
$$ \frac{2^{r+1}-1}{2^r-1} (2^{rL}-1)\,. $$
Since the total number of monomials in $r$ variables in a generic polynomial of degree
 $\lfloor \frac{n}{2^L} \rfloor$ is $M_r(\lfloor \frac{n}{2^L} \rfloor)$,
 then $M_r(\lfloor \frac{n}{2^L} \rfloor)-r-1$ is the number of products necessary to evaluate
 all independent monomials.
Therefore, the total number of multiplications for evaluating $P(\mathbf a)$ is
$$  G_2(n,r,L) = \frac{2^{r+1}-1}{2^r-1} (2^{rL}-1)+M_r(n)-r-1 ~~.  $$
We look for the optimal value $L_{op}$ giving the minimum $ G_2(n,r,L_{op})$.
Since
$$  M_r(\lfloor \frac{n}{2^L} \rfloor)=\frac{1}{r!} \left( \frac{n}{2^L}-\{ \frac{n}{2^L} \} \right)^r \prod_{j=1}^{r} \left( 1+ \frac{j}{\frac{n}{2^L}-\{ \frac{n}{2^L} \} } \right)  ~~,  $$
then $M_r(\lfloor \frac{n}{2^L} \rfloor)$ is an expression that is $\frac{1}{r!}(\frac{n}{2^L})^r+ O(\frac{2^L}{n})$ asymptotically in $n$. \\
The local optima are given by the values of $L$ such  the
$$ G_2(n,r,L) \leq G_2(n,r, L-1) ~~\mbox{and}~~ G_2(n,r,L) \leq G_2(n,r,L + 1)   \ . $$
Then, considering the asymptotic expression
$$ G_2(n,r,L) = \frac{2^{r+1}-1}{2^r-1} 2^{rL} + \frac{1}{r!} (\frac{n}{2^L})^r ~~, $$
it is immediate
 to obtain the conditions
$$ \begin{array}{l}
 \displaystyle 2^{2rL} > \frac{1}{r!}  \frac{n^r}{2^r} \frac{2^r-1}{2^{r+1}-1}   \\
            \\
 \displaystyle    2^{2rL} < 2^r n^r \frac{1}{r!} \frac{2^r-1}{2^{r+1}-1} ~~,  \\
   \end{array} $$
showing that asymptotically $L_{op}$ must satisfy the inequalities
$$ -\frac{1}{2} + \frac{1}{2r} \log_2 \frac{2^r-1}{r!(2^{r+1}-1)} +\frac{\log_2 n}{2}  < L_{op} <
   \frac{1}{2} + \frac{1}{2r} \log_2 \frac{2^r-1}{r!(2^{r+1}-1)} +\frac{\log_2 n}{2} ~~.  $$
Therefore $L_{op}$ is the closest integer to
  $\frac{1}{2r} \log_2 \frac{2^r-1}{r!(2^{r+1}-1)} +\frac{1}{2} \log_2 n  $,
and the total number of products asymptotically is included into the interval:
$$ \frac{1}{\sqrt{2^r}} \sqrt{4\frac{2^{r+1}-1}{2^r-1} \frac{1}{r!}}  n^{r/2} <  G_2(n,r,L_{op}) <  \sqrt{2^r}  \sqrt{4\frac{2^{r+1}-1}{2^r-1} \frac{1}{r!}}  n^{r/2}~~. $$
\begin{flushright} $\Box$ \end{flushright}

\section{The case $r\geq 2$, $p>2$}

A polynomial $P(x_1, \ldots, x_r)$ of degree $n$, in $r$ variables over the field $\mathbb{F}_p$,
 is simply decomposed into a sum of $p^r$ polynomials as
\begin{eqnarray}
  \label{eq2}
P(x_1, \ldots, x_r) &=& \sum_{i_1, \ldots, i_r \in \{0,1, \ldots, p-1 \}}
x_1^{i_1} \ldots x_r^{i_r} P_{i_1, \ldots, i_r} (x_1^{p}, \ldots, x_r^{p})  \nonumber \\
&=&  \sum_{i_1, \ldots, i_r  \in  \{0,1, \ldots, p-1\}} x_1^{i_1} \ldots x_r^{i_r}
\left( P_{i_1, \ldots, i_r} (x_1, \ldots, x_r) \right)^p
\end{eqnarray}
where $P_{i_1, \ldots, i_r} (x_1, \ldots, x_r)$ is a polynomial of degree
 $\lfloor \frac{n-\sum i_j}{p}\rfloor$.
Therefore the polynomial $P(x_1, \ldots, x_r)$ evaluated at the point
 $\mathbf a = (\alpha_1, \ldots, \alpha_r) \in \mathbb{F}_{p^m}^r$
can be obtained from the evaluation of all polynomials $P_{i_1, \ldots, i_r} (x_1, \ldots, x_r)$
 at $\mathbf a$, by  evaluating the $p^r$ monomials  $\alpha_1^{i_1} \ldots \alpha_r^{i_r}$ (which require $p^r-r-1$ multiplications),  performing $p^r$ computations of $p$-powers,
 combining these factors with $p^r$ multiplications, and finally adding all results.\\
The argument of Theorem \ref{theo1} and \ref{theo2} still applies, and the minimum number
 of steps is obtained in the following theorem.
\begin{Theorem}
 \label{theo3}
 Let $L_{opt}$ be the number of steps of this method yielding the minimum number of products, $G_p(n,r,L_{op})$, required to evaluate a polynomial of degree $n$ in $r$ variables,
  with coefficients in $\mathbb{F}_p$. Then $L_{opt}$ is an integer that asymptotically is
  included into the interval
$$ -\frac{1}{2} +B +\frac{\log_p n}{2} \leq L_{op}
 \leq \frac{1}{2} + B +\frac{\log_p n}{2}   $$
where $B=\frac{1}{2r} \log_p \frac{(p-1)(p^r-1)}{r!(2~ p^{r}-1)}$,
that is, $L_{op}$ is the integer closest to $B +\frac{\log_p n}{2}$.
Asymptotically the minimum $G_p(n,r,L_{op})$ is included into the interval:
$$ \frac{2}{\sqrt{p^r}} \sqrt{(p-1)\frac{2p^{r}-1}{p^r-1} \frac{1}{r!}}  n^{r/2} <  G_p(n,r,L_{op}) <
            2\sqrt{p^r}  \sqrt{(p-1)\frac{2p^{r}-1}{p^r-1} \frac{1}{r!}}  n^{r/2}~~. $$
\end{Theorem}
\noindent
{\sc Proof}. Using equation (\ref{eq2}) the polynomial $P(x_1, \ldots, x_r)$ evaluated at the point
 $\mathbf a = (\alpha_1, \ldots, \alpha_r) \in \mathbb{F}_{p^m}^r$
 can be obtained from the evaluation of all $P_{i_1, \ldots, i_r} (x_1, \ldots, x_r)$ at $\mathbf a$,
 by  evaluating  $p^r$ monomials  $\alpha_1^{i_1} \ldots \alpha_r^{i_r}$ (which
 require $p^r-r-1$ multiplications), computing $p^r$ $p$-powers,
 combining these factors with $p^r-1$ multiplications, and finally performing
the required additions. \\
We can iterate this procedure: at each step the number of polynomials is multiplied by $p^r$ and their
degrees are at least divided by $p$. Therefore, after $L$ steps the number of polynomials is $p^{rL}$ and their degrees are not greater than $\lfloor \frac{n}{p^L} \rfloor$. Once the $p^r$ numbers $P_{i_1, \ldots, i_r} (\alpha_1, \ldots, \alpha_r)$ are known, the total number of $p$-powers is
$$ p^{rL}+ p^{r(L-1)}+\cdots +p^{r(L-L+1))} =\frac{p^r}{p^r-1} (p^{rL}-1)  $$
and  the number of products necessary to obtain $P(\alpha)$ is
$$ (p^r-1) [p^{r(L-1)}+ p^{r(L-2)}+\cdots +p^{r(L-L))} ]=p^{rL}-1 ~~, $$
hence the total number of required multiplications is
$$ \frac{2p^{r}-1}{p^r-1} (p^{rL}-1)~~. $$
The total number of multiplications for computing all the monomials of all the polynomials arising at step $L$ is $M_r(\lfloor \frac{n}{2^L} \rfloor)-r-1$, and further $(p-2) (M_r(\lfloor \frac{n}{2^L} \rfloor)-r-1) $ products are necessary to provide every possible term
 occurring in the polynomials at step $L$. As a consequence the total number of multiplications necessary to evaluate
 $P(\mathbf a)$ is
$$   \frac{2p^{r}-1}{p^r-1} (p^{rL}-1) + (p-1) (M_r(\lfloor \frac{n}{2^L} \rfloor)-r-1) \,.$$
The same passages used in Theorem \ref{theo2} allow us to conclude that $L_{op}$ is asymptotically
 identified by the chain of inequalities
$$ \sqrt{\frac{1}{p^r}} \sqrt{\frac{(p-1)(p^r-1)n^r}{r!(2p^r-1)}} \leq p^{rL_{op}}  \leq \sqrt{\frac{(p-1)(p^r-1)n^r}{r!(2p^r-1)}} \sqrt{p^r} $$
which written in the form
$$ -\frac{1}{2} +B +\frac{\log_p n}{2} \leq L_{op}
 \leq \frac{1}{2} + B +\frac{\log_p n}{2}   $$
shows that the unique optimal value is the integer closest  to $ B +\frac{\log_p n}{2} $, where $B=\frac{1}{2r} \log_p \frac{(p-1)(p^r-1)}{r!(2~ p^{r}-1)}$.
The minimum number of multiplications is asymptotically included into the interval
$$ \frac{2}{\sqrt{p^r}} \sqrt{(p-1)\frac{2p^{r}-1}{p^r-1} \frac{1}{r!}}  n^{r/2} <  G_p(n,r,L_{op}) <
            2\sqrt{p^r}  \sqrt{(p-1)\frac{2p^{r}-1}{p^r-1} \frac{1}{r!}}  n^{r/2}~~. $$

\begin{remark}\label{b2}
Our proofs start with the evaluations of certain monomials. Hence they may be extended verbatim to other finite-dimensional linear subspaces
of $\mathbb {F}_{p}[x_1,\dots ,x_r]$, just taking their dimension $\alpha$ as vector spaces instead of the integer $\binom{n+r}{r}$. For a suitable
linear space $V$ in Theorem 3 we could get a bound of order
$c_3\sqrt{\alpha}$ with $c_3\sim 2\sqrt{2p^{r+1}}$. For instance, call
$V(r,n)$ the linear subspace of $\mathbb {F}_{p}[x_1,\dots ,x_r]$ formed by all polynomials whose degree in each variable is at most $n$.
We have $\dim (V(n,r)) = (n+1)^r$. In this case iterating this procedure we arrive at each step at a vector
space $V(\lceil n/p^L\rceil ,r)$. Taking $L$ such that $2p^{rL} \sim p\dim (V(\lceil n/p^L\rceil,r))$, i.e. taking $L\sim \log _p n/2 + B$
with $B\sim \frac{1}{2r}\log _p(p)/2 \sim \frac{1}{2r} \sim - \frac{1}{2r}\log _p 2$, we get an upper bound
of order $2\sqrt{2p^{r+1}}n^{r/2}$.
\end{remark}

\section{Further remarks}

The complexity of polynomial evaluation is crucial in the determination
of the complexity of several computational algebra methods, such as
the Buchberger-Moeller algorithm
(\cite{CGC-alg-art-buchmoeller,CGC-cd-inbook-D1morafglm}),
other commutative algebra methods (\cite{CGC-cd-inbook-D1moratech}),
the Berlekamp-Massey-Sakata algorithm (\cite{CGC-cd-art-sakata88,CGC-cd-inbook-D1sakata1}).

In turn, these algorithms are the main tools used in algebraic
coding theory (and in cryptography).
This justifies our special interest in the finite field case.
For example, the previous algorithms can be adapted naturally
to achieve  iterative decoding of algebraic codes and algebraic-geometry
codes, see e.g. \cite{CGC-cd-inbook-D1sakata2,CGC-cd-inbook-D1eleanna}.
Other versions can decode and construct more general geometric
codes, see e.g. \cite{g}.

\section{Acknowledgments}
The authors would like to thank C. Fontanari for valuable discussions.

The first author would like to thank MIUR and GNSAGA of INDAM.
The third author would like to thank MIUR for the programme
``Rientro dei cervelli''.

This work has been partially done while the second author was Visiting Professor
with the University of Trento, funded by CIRM.


\section{\label{intro}Introduction}

The study of the strong suppression and substructure modification of high energy jets created in heavy-ion collisions offers the opportunity to characterise the properties of the medium they traversed. These phenomena, typically referred to as jet quenching \cite{Mehtar-Tani:2013pia,Qin:2015srf}, have so far been analysed mainly by modelling the interaction of colored partons with the deconfined, high temperature phase of the medium, the strongly coupled liquid known as the quark-gluon plasma (QGP) (for a recent review on the main open questions about our current understanding of QGP see \cite{Busza:2018rrf}). It is well known that at lower temperatures the fluid experiences a process of `particlization' and the system is well described by the dynamics of a hadron resonance gas \cite{Petersen:2014yqa}. Nevertheless, the vast majority of studies that address jet quenching phenomenology have so far omitted, without any compelling quantitative justification, the effects of the interaction of the hadronic components of the jet with this lower temperature phase of the medium.

Jet quenching physics is a very active field within that of heavy-ion collisions, partly due to the wealth of experimental jet data that has been produced in recent times at RHIC and LHC. Jets are sprays of hadrons which are clustered together according to a specific reconstruction algorithm with a given jet radius parameter $R$. They are the result of the fragmentation of parton showers that are developed through the relaxation of the virtuality scale $Q^2 \sim \mathcal{O}(p_{T, \rm{jet}}^2)$ via successive splittings down to the hadronization scale. In heavy-ion collisions, the dynamically evolving parton shower interacts with the strongly coupled QGP, which has a temperature $T$ of the order of the non-perturbative scale $\Lambda_{\rm QCD}$. The complicated nature of this multi-scale, multi-partonic problem makes it difficult to achieve a unified, self-consistent picture of jet quenching physics, and for this reason several theoretical descriptions of the jet/medium interplay have been pursued, both from a perturbative (see \cite{Mehtar-Tani:2013pia,Qin:2015srf} and references therein) and non-perturbative (see \cite{Chesler:2015lsa} and references therein) perspective. Each of these descriptions inherently makes assumptions on the nature of the relevant degrees of freedom of the QGP to which an energetic jet is sensitive to, and thus allow for the falsification of different pictures of the inner workings of the plasma through the comparison between models and experimental data. However, without the inclusion of the potentially important observable effects due to the hadron gas phase, any conclusion drawn from such phenomenological studies cannot be definitive.

In \cite{Cassing:2003sb} the nuclear modification factor at RHIC has been studied within a purely hadronic approach achieving a qualitative description of the experimental data including a significant suppression. More recently similar studies are carried out within Angantyr+UrQMD at LHC energies and confirm significant suppression effects within the hadronic stage \cite{Bierlich:2018xfw}. More complete dynamical approaches including soft and hard contributions in the same approach like \cite{Werner:2012xh,Werner:2012sv} show that qualitative differences in the nuclear modification factor and elliptic flow are expected in the intermediate momentum region from $p_{\perp} = 2-6$ GeV.

The precise way in which the products of the fragmentation of a parton shower start being sensitive to the presence of the hadronic medium is, in fact, not so well understood. This question involves both the space-time picture associated to the formation of the parton shower as well as the time associated to the process of hadronization itself, which could in turn result from the recombination of partons from the jet with those from the thermal medium \cite{Fries:2003vb,Han:2016uhh}. Studying the implications of this modelling is beyond the scope of this paper and will be left for future work. The goal of the current work consists instead in quantifying the effects of the hadronic medium on energetic hadrons in a controlled scenario. In this way, we are able to provide the first solid indications of the importance of quenching in the hadronic gas phase through the analysis of angular energy distributions, which is an observable analogous to those usually used in jet quenching phenomenology to characterise how energy is spread away from the jet axis due to medium interactions \cite{Chatrchyan:2013kwa,Aad:2019igg,Acharya:2019ssy}. We further parametrise the magnitude of the effect in terms of the newly defined $\tilde q$ and $\tilde e$, the average transverse momentum and longitudinal momentum transferred per unit of mean free path, respectively. Even though their size will be shown to be around 3 to 4 times smaller than their QGP counterparts, namely $\hat{q}$ and $\hat{e}$, there is no reason why they should be neglected, and therefore their impact on jet observables, especially on jet substructure observables, is predicted to be sizeable.

The rest of the paper is organised as follows: in Section~\ref{smash} the hadronic transport model SMASH used in this work is presented. Then, in Section~\ref{shapes} we show results on the angular energy distributions for incoming hadrons with different energies and species traversing an expanding hadronic medium of different lengths. In Section~\ref{qhat} we parametrise the relevant quantities $\tilde q$ and $\tilde e$ in terms of momentum and temperature by carrying out a detailed microscopic analysis for individual collisions. Finally, in Section~\ref{conclusion} we summarise our findings and discuss their potential relevance in the understanding of jet quenching observables.

\section{\label{smash}Hadronic transport: SMASH}

In this work we use SMASH v1.6 \cite{Weil:2016zrk,SMASHwebsite,SMASH1.6DOI}, a newly developed transport approach, to describe the hadronic medium. This model has been shown \cite{Tindall:2016try} to effectively solve the Boltzmann equation
\begin{equation} \label{eq:boltzmann}
 p^\mu \frac{ \partial f_i (t,{\bf x},{\bf p})}{\partial x^\mu}  = C_{coll} [f_i,f_j] \ ,
\end{equation}
where $f_i$ is a one-particle distribution function for species $i$ and $C_{coll}$ is the collision integral describing the interaction of the various species.

Particles in SMASH propagate according to their equations of motion (no potentials are used in this work, so this corresponds to straight lines), and collide according to a geometric criterion
\begin{equation}
d_{trans} \le \sqrt{\frac{\sigma_{tot}}{\pi}},
\label{eq:coll_crit}
\end{equation}
with $d_{trans}$ the distance between two particles and $\sigma_{tot}$ their total cross-section, which depends on the incoming particle species and momenta. Degrees of freedom include all confirmed particles from the PDG 2018 list \cite{Tanabashi:2018oca} up to masses of $\sim$2.3 GeV. As can be seen for example in the $\pi^-$-proton cross-section (Fig.~\ref{pip_xsec}), at low energies inelastic interactions happen through resonance formation, and after a transition region, the high energy regime uses a string excitation and fragmentation model. Soft strings are excited directly within SMASH according to single-diffractive direct excitation, double-diffractive gluon exchange or non-diffractive quark exchange, and subsequently fragmented using PYTHIA 8.235 \cite{Andersson:1983ia, Sjostrand:2014zea}; hard strings are both excited and fragmented directly within PYTHIA (see \cite{Mohs:2019iee} for the full information on the treatment of strings in SMASH).

\begin{figure}
 \includegraphics[width=85mm]{pi-p_xsec_high.png}
\caption{Total $\pi^- p$ cross-section in SMASH, decomposed according to the various partial contributions. Taken from \cite{Mohs:2019iee}}
\label{pip_xsec}
\end{figure}

Note that although some cross-sections such as the $\pi^- p$ shown in Fig.~\ref{pip_xsec} are quite well known experimentally, SMASH features a very high number of particle pairs for which experimental cross-section data is scarce or altogether inexistent. Thus we use the Additive Quark Model (AQM) \cite{Goulianos:1982vk} as a prescription for the prediction of unknown cross-sections. In the AQM, the high-energy cross-section of species $i$ and $j$ can be scaled from a known elastic or total cross-section, for example such that
\begin{equation}
\sigma_{ij} = \frac{\sigma_{ij}^{AQM}}{\sigma_{\pi p}^{AQM}} \sigma_{\pi p},
\end{equation}
where
\begin{equation}
\sigma^{AQM} = 40 \cdot \left( \frac{2}{3} \right)^{n_M} \cdot (1-0.4x^s_1) \cdot (1-0.4x^s_2).
\label{sigma_aqm}
\end{equation}
In this last formula, $n_M$ is the number of incoming mesons in the reaction, and $x^s$ is the fraction of strange quarks in the considered hadron. In SMASH, baryon-baryon interactions follow the nucleon-nucleon cross-section, while baryon-meson and meson-meson interactions follow the pion-nucleon cross-section.

In the following sections we will consider two initialization schemes for the study of high-$p_T$ particles within SMASH. The first one, used in Section \ref{shapes}, is a uniformly dense sphere of radius $r$ initialized with thermal multiplicities and momenta. This sphere expands over time and eventually freezes out as the density decreases, reaching a state of outwards free-streaming particles at large times. The second initialization, used in Section \ref{qhat} corresponds to an infinite medium in the form of a box with periodic boundary conditions, and is uniformly filled in the same way as the sphere. This system conserves density and thermodynamic quantities such as temperature over the volume for longer times, provided detailed balance is enforced\footnote{This is not strictly the case if strings are enabled (which is necessary for the current study to be sensible) leading to a gradual decrease in the temperature. Since we are however only interested in what happens at relatively early times (typically less than 10-20 fm), we will simply neglect this effect (over such times, the temperature typically will not decrease by more than 3\%).}.

\section{\label{shapes}Jet Shapes}

\begin{figure*}
\centering
 \includegraphics[width=85mm]{jetshape_energies_10.pdf}
 \includegraphics[width=85mm]{jetshape_particles_10.pdf}
 \includegraphics[width=85mm]{jetshape_spheresizes_10GeV.pdf}
 \includegraphics[width=85mm]{jetshape_comparison_10fm.pdf}
\caption{Jet shapes as a function of leading particle energy (top left), leading particle species (top right), medium size (bottom left). The bottom right plot compares the full hadron gas jet shape to a pion gas with constant cross-section jet shape.}
\label{jetshapes}
\end{figure*}

In this section we add a high-$p_T$ particle in the middle of the previously described thermally initialized sphere at a temperature of $T=150$ MeV, and measure the angular distribution at large times, after freeze-out. To some extent, one can consider this scenario as similar to what would happen to a high-$p_T$ particle in the late stages of a heavy ion collision, after the hadronization has taken place: at that point, it crosses a rapidly cooling and decreasingly dense hadronic medium.

We determine the so-called "jet shapes" shown in Fig.~\ref{jetshapes} by measuring the amount of energy such a high-$p_T$ particle adds on average at an angle $\theta$ of its original propagation direction. Specifically, this is done by simulating both a set of spheres in which this high-$p_T$ particle is present and and one in which it is absent. At a given angle $\theta$ corresponding to a solid angle $\Omega$, the momentum $dp/d\Omega$ of the latter is subtracted from the momentum of the first, in what can be thought of as a background subtraction. We then normalize this by dividing it by the maximum value it could take, i.e. if all the momentum was still at $\theta=0$ (which corresponds to the case where the particle flies out of the medium without interacting). This gives us a quantity which can be compared for a wide variety of scenarios.

The top left panel of Fig.~\ref{jetshapes} explores the energy dependence of the high-$p_T$ particle. As one can readily see, less energetic particles tend to affect the momentum distribution at wider angles than their more energetic counterparts. This is expected, as we would indeed expect that a 100 GeV particle, even if it does interact with the medium, should retain or transfer most of its momentum in the initial direction of propagation when colliding elastically or inelastically with a medium component with energy of the order of 1-3 GeV. Conversely, using the same considerations, a much larger part of the momentum goes to wider angles in the case of a 10 GeV particle. The peak around zero angle, e.g. for the 10 GeV probe, reflects the particles that escape from the medium without any disturbance.

We see in the top right panel of Fig.~\ref{jetshapes} that different species of particles are differently affected by the hadronic expansion. This is due to different hadrons having on average larger or smaller cross-sections with the particles of the medium. Remembering Eq.~\eqref{sigma_aqm}, we then see that the proton, as a baryon, typically has larger cross-section with the medium, and its jet shape is more skewed towards larger angles; the pion shape is less affected, but still slightly more so than the strange kaon one, with the smallest average cross-section.

The medium size dependence (here probed through varying the radius of the initial expanding sphere) is inspected in the bottom left panel of Fig.~\ref{jetshapes}. As one would expect, increasing the size of the medium (and thus the number of possible collisions between the high-$p_t$ and medium particles) generally broadens the angular distribution. Note that while the size of the hadronic part of the medium in heavy ion collisions is not precisely known, estimations usually place it between 10 and 15 fm \cite{Petersen:2008gy}.

Finally, the bottom right panel compares shooting a high-$p_T$ pion through a full hadron gas as described in the previous section, and through a much simpler pion gas interacting only through constant cross-sections (this corresponds in essence to the hard spheres scenario). Although the 30mb case is much closer to the actual average cross-section the pion would encounter in a full hadron gas, we see that the angular distribution of the 100 mb case is in fact much closer to that of the full hadron gas due to the much larger density than in the pure pion gas. In order to get an intuition of the degree at which the 30 mb and 100 mb cases differ, we calculate the proportion of volume at thermal densities which is occupied by particles in this hard sphere scenario. For an initial temperature of 150 MeV, we thus see that $\sim 5\%$ of the volume is occupied in the case of the 30 mb cross-sections, whereas $\sim 33 \%$ of space is filled in the case of the 100 mb cross-sections. Although this is a simplified model, it should provide the reader with some sense of how dense such a hadron gas really is at the time of hadronization.

This explorative investigation shows that the angular distributions can be affected by the hadronic phase rescatterings in a significant manner. In particular, let us note that fully reconstructed jets rely on information of particles at much lower transverse momenta as well. Since the probe hadron would be of similar energy as the medium particles, making it hard to distinguish it clearly, in our radially expanding sphere it does not make sense to lower the momenta beyond the displayed 10 GeV. However hadrons around 2 GeV of energy would certainly be re-shuffled and found at different angles than without hadronic rescattering, sizeably affecting the tail of the distributions of observables such as the `jet shapes' computed in \cite{Chien:2015hda,Casalderrey-Solana:2016jvj,Tachibana:2017syd,KunnawalkamElayavalli:2017hxo,Park:2018acg,Tachibana:2018yae}.

\section{\label{qhat_section}Jet Quenching}

Now that it has been demonstrated that the hadronic medium has an effect on the angular momentum distribution of shooting a single high-$p_T$ particle through it, we try to quantify this effect by calculating the transverse and longitudinal energy losses $\hat q$ and $\hat e$.

In the following we introduce a high-$p_T$ particle in the box simulating infinite matter described in Section \ref{smash} and analyse its first interaction with the medium averaged over many simulations. The reason for this is twofold. First, in a hadronic transport approach, inelastic collisions are not only possible but frequent (typically in the form of a string excitation, see Fig.~\ref{pip_xsec}), resulting in the loss of the original particle and thus making it impossible to continue to follow it. Second, even in the cases where the first interaction is elastic, it will typically not be in the form usually modeled at higher energies, where the medium is assumed to perform many relatively small kicks to the particle; in this case, a single collision can very strongly affect the momentum of the high-$p_T$ particle, and as such its final longitudinal momentum can vary a lot, making it difficult to compare subsequent collisions. By only studying the first collision the control parameters are kept fixed.

In the QGP phase, $\hat q$ is typically estimated from kinetic theory \cite{Baier:2008js},
\begin{equation}
\hat q = \rho \int q_\perp^2 \frac{d\sigma}{dq_\perp^2} dq_\perp^2,
\label{qhat_kinetic}
\end{equation}
where $\rho$ is the density of the system, $q_\perp$ is the transverse momentum transfer and $d\sigma /dq_\perp^2$ is the differential cross-section of the particle with the medium. Since in SMASH the cross-section only depends on the properties of the incoming particles, the quantity $d\sigma /dq_\perp^2$ in this definition is consistent with zero, leading to the conclusion that Eq. \eqref{qhat_kinetic} should not be used in this context. This does not however mean that it is not possible to describe the energy loss in the hadronic medium. At the most fundamental level, the transverse and longitudinal energy losses are simply
\begin{equation}
\hat q = \frac{\langle q_\perp^2 \rangle_L}{L}, \qquad \hat e = \frac{\langle q_\parallel^2 \rangle_L}{L},
\label{qhat}
\end{equation}
where $\langle q_\perp^2 \rangle_L$ and $\langle q_\parallel^2 \rangle_L$ are the average cumulative transverse and longitudinal momentum change suffered by a propagating particle in a medium over a length $L$. As previously mentioned, this typically assumes that the medium acts through many small elastic kicks on the particle; this is not quite valid in the case of the hadron gas, as we rather usually observe one very large (and likely inelastic) momentum influx. To account for these differences in the description, we propose the following definitions for similar quantities denoted as $\tilde q$ and $\tilde e$,
\begin{equation}
\tilde q = \frac{\langle q_\perp^2 \rangle}{\lambda_{mfp}}, \qquad \tilde e = \frac{\langle q_\parallel^2 \rangle}{\lambda_{mfp}},
\label{qtilde}
\end{equation}
where $\langle q_\perp^2 \rangle$ and $\langle q_\parallel^2 \rangle$ are now the average transverse and longitudinal momentum of the first collision with the medium, and $\lambda_{mfp}$ is the mean free path of the high-$p_T$ particle before this first interaction.

\begin{figure}
  \includegraphics[width=85mm]{averageqperp.pdf}
  \hspace{0mm}
  \includegraphics[width=85mm]{averageqpara.pdf}
  \caption{Transverse (top) and longitudinal (bottom) momentum vs temperature for various high-$p_T$ particle momenta.}
  \label{qperp_qpara}
\end{figure}

\begin{figure}
  \includegraphics[width=85mm]{lambdaT.pdf}
  \caption{Mean free path vs temperature for various high-$p_T$ particle species.}
  \label{lambda_mfp}
\end{figure}

The top panel of Fig.~\ref{qperp_qpara} shows the effect of varying the energy of the high-$p_T$ particle on $\langle q_\perp^2 \rangle$, which is shown to increase with temperature at every energy; moreover, the effect of  temperature appears to be markedly more important as the energy of the particle increases. The bottom panel shows a similar picture for the case of $\langle q_\parallel^2 \rangle$, where we also see it increase with temperature at every energy; note however that in this case there is already a pretty strong temperature dependence even at low beam energies. Fig.~\ref{lambda_mfp} shows that the choice of species for the high-$p_T$ particle has a large impact on its mean free path, which mainly comes from the fact that cross-sections depend quite strongly on the type of particle. Although not shown here, the dependence of the transverse and longitudinal momenta are very similar for each species pointing to a main kinematic effect. In fact, the longitudinal momentum transfer is much smaller than the transverse one due to momentum conservation. Since the high momentum probe has initially rather high momentum, there has to be a significant amount maintained in the longitudinal direction, while any re-distribution into the transverse plane implies a large change since the transverse momentum is zero before the scattering. The mean free path on the other hand is rather insensitive to the energy of the particle as expected from the invariance of the string fragmentation versus the particle species and from the fact that the average cross-section only slightly varies with the energy of the particle (see for example Fig.~\ref{pip_xsec}).

\begin{figure*}
  \includegraphics[width=85mm]{qT_momenta_2d.pdf}
  \includegraphics[width=85mm]{qp_temperature_2d.pdf}
  \includegraphics[width=85mm]{eT_momenta_2d.pdf}
  \includegraphics[width=85mm]{ep_temperature_2d.pdf}
  \caption{Medium modification factor $\tilde q$ as a function of temperature and high-$p_T$ pion momentum. Lines show the fit of parametrizations \eqref{param_qtilde} and \eqref{param_etilde}.}
  \label{qtilde_etilde_vs_params}
\end{figure*}

As a final note, we explore the temperature and particle energy dependence of $\tilde q$ and $\tilde e$ for the specific case of a pion high-$p_T$ particle (Fig.~\ref{qtilde_etilde_vs_params}). As one readily sees, we observe that both $\tilde q$ and $\tilde e$ increase significantly both with temperature and particle energy. This parameter space exploration allows us to introduce the following parametrizations (also shown on the figures) to estimate the value of the hadronic transverse and longitudinal energy losses at temperatures between 100 and 175 MeV, for particles with momenta between 1 and 120 GeV:
\begin{align}
\tilde{q}_\pi (p_T, T) &= 5.14 \cdot 10^{-18} \frac{\text{GeV}^2}{\text{fm}} \Big( \frac{p_T}{\text{GeV}}\Big)^{0.87} \Big( \frac{T}{\text{MeV}} \Big)^{7.35}, \label{param_qtilde}\\
\tilde{e}_\pi (p_T, T) &= 9.31 \cdot 10^{-19} \frac{\text{GeV}^2}{\text{fm}} \Big( \frac{p_T}{\text{GeV}}\Big)^{0.17} \Big( \frac{T}{\text{MeV}} \Big)^{7.59}. \label{param_etilde}
\end{align}
We observe that while both of these quantities depend on the momentum of the high-energy particle, the dependence is much stronger in the case of the transverse coefficient. These parametrizations can be directly employed in future studies of hadronic jet quenching.

\section{\label{conclusion}Summary and Discussion}

We showed in Section \ref{shapes} that shooting a high-$p_T$ particle through a hadron gas does result in a broadening of the angular momentum distribution, or jet shape. As previously mentioned, this is a similar situation as to what should happen in the late stages of a typical heavy ion collision; the main difference is here the absence of flow. It is not trivial to predict how flow would affect these distributions at all energies. On the one hand, such an outwards movement of the particles will lead to a faster cooling and eventual freeze-out of the sphere; on the other, depending on the momentum of the high-$p_T$ particle, there are some cases in which lower $p_T$ particles would have a larger average cross-section with the medium since they would now be more likely to be (at least partially) comoving (see Fig.~\ref{pip_xsec} at $\sqrt s = 10$ GeV or lower, for example). Thus, while in the high-$p_T$ limit our results should represent a maximum as to what effect can be expected, the situation is not so clear at lower momentum.

We attempted to quantify those results through the calculation of the transverse and longitudinal energy losses in Section~\ref{qhat_section}. Although our results show that the kinetic expression for $\hat q$ is insufficient to obtain a physical result using our current calculation of the hadron gas, we proposed alternative definitions for the hadronic medium energy loss in the form of $\tilde q$ and $\tilde e$. Although it is not yet completely clear that the hat and tilde definitions are equivalent, we attempt a comparison between numerical values. In the QGP, a cross-model study has recently found that $\hat q = 1.9 \pm 0.7$ GeV$^2$/fm at T=470 MeV and $\hat q = 1.2 \pm 0.3$ GeV$^2$/fm at T=370 MeV \cite{Burke:2013yra} for a 10 GeV quark traveling through the medium. Our approach shows that for a pion with the same energy in a relatively hot hadronic medium at 150 MeV (i.e. just below the phase transition), we obtain from \eqref{param_qtilde} that $\tilde q = 0.38$ GeV$^2$/fm. This result, while as expected below its QGP counterpart, does remain significant.

While this is beyond the scope of this exploratory study, the logical next step to verifying whether hadronic considerations are relevant to the jet quenching framework would be to perform full heavy ion simulations, complete with jets that first go through a QGP phase and then move on to cross a hadronic afterburner, for example within the JETSCAPE framework \cite{Putschke:2019yrg}.

\begin{acknowledgments}
The authors would like to thank Rainer Fries, Sangyong Jeon and J\"orn Putschke for extended discussions at the EMMI Rapid reaction task force on "The space-time structure of jet quenching: Theory and Experiment" in August 2019. This work was initiated during a visit in the context of the PPP exchange project with McGill University supported by the DAAD funded by BMBF (Project-ID 57314610). This work was supported by the Helmholtz International
Center for the Facility for Antiproton and Ion Research (HIC for FAIR) within the
framework of the Landes-Offensive zur Entwicklung Wissenschaftlich-Oekonomischer Exzellenz (LOEWE) program launched by the State of Hesse. Computational resources have been provided by the Center
for Scientific Computing (CSC) at the Goethe-University of Frankfurt. DP was supported by a grant from the Trond Mohn Foundation (project no. BFS2018REK01).
\end{acknowledgments}


\section{Introduction}
OODIDA is a modular system for concurrent distributed data analytics for the automotive domain, targeting fleets of reference vehicles~\cite{ulm2019oodida}. Its main purpose is to process telemetry data at its source as opposed to transferring all data over the network and processing it on a central cloud server (cf.~Fig.~\ref{fig:whole_fleet}). A data analyst interacting with this system uses a Python library that assists in creating and validating assignment specifications. Updating this system with new computational methods necessitates terminating and redeploying software. However, we would like to perform updates without terminating ongoing tasks. We have therefore extended our system with the ability to execute user-defined code both on client devices (on-board) and the cloud server (off-board), without having to redeploy any part of it. As a consequence, OODIDA is now highly suited for rapid prototyping. The key aspect of our work is that active-code replacement of Python modules piggybacks on the existing Erlang/OTP infrastructure of OODIDA for sending assignments to clients, leading to a clean design. This paper is a condensed version of a work-in-progress paper~\cite{ulm2019active}, giving an overview of our problem (Sect.~\ref{problem}) and its solution (Sect.~\ref{solution}), followed by an evaluation (Sect.~\ref{eval}) and related work~(Sect.~\ref{related}).

\vspace{-2.3em}
\newsavebox{\tempbox}
\begin{figure}
\sbox{\tempbox}{\includegraphics[width=0.45\textwidth, trim=2cm 2.5cm 2cm 2.5cm, clip]{context.pdf}}
\subfloat[OODIDA in context]{\usebox{\tempbox}\label{fig:context}}%
\qquad
\subfloat[Whole-fleet assignment]{\vbox to \ht\tempbox{%
  \vfil
  \hbox to 0.45\textwidth{
  \includegraphics[width=0.45\textwidth, trim=2cm 2.5cm 2cm 2.5cm, clip]{exec_3.pdf}
  }
  \vfil}\label{fig:whole_fleet_assignment}}%

\caption{OODIDA overview and details: In (a) user nodes $\boldsymbol{u}$ connect to a central cloud $b$, which connects to clients $\boldsymbol{c}$. The shaded nodes are implemented in Erlang/OTP; the other nodes are external Python applications, i.e.\ the user front-ends $\boldsymbol{f}$, the external server application $a$, and external client applications $\boldsymbol{a}$. In (b) the core of OODIDA is shown with permanent nodes (dark) and temporary handlers (light) in an instance of a whole-fleet assignment. Cloud node $b$ spawned an assignment handler $b'$. After receiving an incoming task, clients $x, y$ and $z$ spawned task handlers $x'$, $y'$, and $z'$ that interact with external applications. Nodes $x$ and $x'$ correspond to $c_1$ in (a) etc.}
\label{fig:whole_fleet}
\end{figure}

\section{Problem}
\label{problem}
OODIDA has been designed for rapid prototyping, which implies that it frequently needs to be extended with new computational methods, both for on-board and off-board data processing. To achieve this goal, Python applications on the cloud and clients have to be updated. Assuming that we update both, the following steps are required: The user front-end $f$ needs to be modified to recognize the new off-board and on-board keywords for the added methods, including checks of assignment parameter values. In addition, the cloud and client applications have to be extended with the new methods. All ongoing assignments need to be terminated and the cloud and clients shut down. Afterwards, we can redeploy and restart the system. This is disruptive, even without taking into account potentially long-winded software development processes in large organizations. On the other hand, the turn-around time for adding custom methods would be much shorter if we could do so at runtime. Active-code replacement targets this particular problem, with the goal of further improving the suitability of OODIDA for rapid prototyping.

\section{Solution}
\label{solution}
With active-code replacement, the user can define a custom Python module for the cloud and for client devices. It is implemented as a special case of an assignment. The front-end $f$ performs static and dynamic checks, attempting to verify correctness of syntax and data types. If these checks succeed, the provided code is turned into a JSON object and ingested by user node $u$ for further processing. Within this JSON object, the user-defined code is stored as an encoded text string. It is forwarded to cloud node $b$, which spawns an assignment handler $b'$ for this particular assignment. Custom code can be used on the cloud and/or clients. Assuming clients have been targeted with active-code replacement, node $b'$ turns the assignment specification into tasks for all clients $\boldsymbol{c}$ specified in the assignment. Afterwards, task specifications are sent to the specified client devices. There, the client process spawns a task handler for the current task, which monitors task completion. The task handler sends the task specification in JSON to an external Python application, which turns the given code into a file, thus recreating the Python module the data analyst initially provided. The resulting files are tied to the ID of the user who provided it. After the task handler is done, it notifies the assignment handler $b'$  and terminates. Similarly, once the assignment handler has received responses from all task handlers, it sends a status message to the cloud node and terminates. The cloud node sends a status message to inform the user that their custom code has been successfully deployed. Deploying custom code to the cloud is similar, the main difference being that $b'$ communicates with the external Python application on the cloud.

If a custom on-board or off-board computation is triggered by a special keyword in an assignment specification, Python loads the user-provided module. The user-specified module is located at a predefined path, which is known to the Python application. The custom function is applied to the available data after the user-specified number of values has been collected. When an assignment uses custom code, external applications reload the custom module with each iteration of an assignment. This leads to greater flexibility: Consider an assignment that runs for an indefinite number of iterations. As external applications can process tasks concurrently, and code replacement is just another task, the data analyst can react to intermediate results of an ongoing assignment by deploying custom code with modified algorithmic parameters while this assignment is ongoing. As custom code is tied to a user ID, there is furthermore no interference due to custom code that was deployed by other users. The description of active-code replacement so far indicates that the user can execute custom code on the cloud server and clients, as long as the correct inputs and outputs are consumed and produced. What may not be immediately obvious, however, is that we can now create \emph{ad hoc} implementations of even the most complex OODIDA use cases in custom code, such as federated learning~\cite{mcmahan2016communication}.

Inconsistent updates are a problem in practice, i.e.~results sent from clients may have been produced with different custom code modules in the same iteration of an assignment. This happens if not all clients receive the updated custom code before the end of the current iteration. To solve this problem, each provided module with custom code is tagged with its md5 hash signature, which is reported together with the results from the clients. The cloud only uses the results tagged with the signature that achieves a majority. Consequently, results are never tainted by using different versions of custom code in the same iteration.

\section{Evaluation}
\label{eval}

The main benefit of active-code replacement is that code for new computational methods can be deployed right away and executed almost instantly, without affecting other ongoing tasks. In contrast, a standard update of the cloud or client installation necessitates redeploying and restarting the respective components of the system. In an idealized test setup, where the various workstations that run the user, cloud and client components of OODIDA are connected via Ethernet, it takes a fraction of a second for a custom on-board or off-board method to be available for the user to call when deployed with active-code replacement, as shown in Table~\ref{tab:comparison}. On the other hand, automated redeployment of the cloud and client installation takes roughly 20 and 40 seconds, respectively. The runtime difference between a standard update and active-code replacement amounts to three orders of magnitude. Of course, real-world deployment via a wireless or 4G connection would be slower as well as error-prone. Yet, the idealized evaluation environment reveals the relative performance difference of both approaches, eliminating potentially unreliable data transmission as a source of error.

This comparison neglects that, compared to a standard update, active-code replacement is less bureaucratic and less intrusive as it does not require interrupting any currently ongoing assignments. Also, in a realistic industry scenario, an update could take days or even weeks due to software development and organizational processes. However, it is not the case that active-code replacement fully sidesteps the need to update the library of computational methods on the cloud or on clients as OODIDA enforces restrictions on custom code. For instance, some parts of the Python standard library are off-limits. Also, the user cannot install external libraries. Yet, for typical algorithmic explorations, which users of our system regularly conduct, active-code replacement is a vital feature that increases user productivity far more than the previous comparison may imply. That being said, due to the limitations of active-code replacement, it is complementary to the standard update procedure rather than a competitive approach.

\begin{table}[]
\centering{
\caption{Runtime comparison of active-code replacement of a moderately long Python module versus regular redeployment in an idealized setting. The former has a significant advantage. Yet, this does not factor in that a standard update is more invasive but can also be more comprehensive. The provided figures are the averages of five runs.\\}
\label{tab:comparison}
\begin{tabular}{@{}lll@{}}
\toprule
& Cloud & Client \\ \toprule
Active-code replacement \phantom{aaaaaaa}
&  20.3 ms   \phantom{aaaaaaa} & 45.4 ms        \\
Standard redeployment
& 23.6 s  &  40.8 s\\
\bottomrule
\end{tabular}
}
\end{table}

\section{Related Work}
\label{related}
The feature described in this paper is an extension of the OODIDA platform~\cite{ulm2019oodida}, which originated from \texttt{ffl-erl}, a framework for federated learning in Erlang/OTP~\cite{ulm2019b}. In terms of descriptions of systems that perform active-code replacement, Polus by Chen et al.~\cite{chen2007polus} deserves mention. A significant difference is that it replaces larger units of code instead of isolated modules. It also operates in a multi-threading environment instead of the highly concurrent message-passing environment of OODIDA. We also noticed a similarity between our approach and Javelus by Gu et al.~\cite{gu2012javelus}. Even though they focus on updating a stand-alone Java application as opposed to a distributed system, their described "lazy update mechanism" likewise only has an effect if a module is indeed used. This mirrors our approach of only loading a custom module when it is needed.

\subsubsection*{Acknowledgements.}
\small{
This research was financially supported by the project On-board/Off-board Distributed Data Analytics (OODIDA) in the funding program FFI: Strategic Vehicle Research and Innovation (DNR 2016-04260), which is administered by VINNOVA, the Swedish Government Agency for Innovation Systems. It took place in the Fraunhofer Cluster of Excellence "Cognitive Internet Technologies." Simon Smith and Adrian Nilsson helped with a supplementary part of the implementation of this feature and carried out the performance evaluation. Ramin Yahyapour (University of G{\"o}ttingen) provided insightful comments during a poster presentation.
}
\bibliographystyle{splncs04}


\section{Introduction}

Declarative programming in general and logic programming (LP) in particular
when compared to other paradigms, present a much higher level at
which programs can be composed. The resulting programs are typically
written with less programming effort and are easier to understand.

Interfaces for relational databases are usually the subject of
corporate development and absorb substantial programming effort.
It is often the case, that the languages these are implemented in
are more suitable for the graphical aspects of presentation
rather than for capturing the underlying declarative model of the databases.
The HTML language, (see for instance \cite{Html99}),
presents a structured approach to user interaction. By design,
it is meant for the focus to be on the content and the relations
across content rather than on exact graphical coordination.

We constructed a high level web-based interface by exploiting
two libraries of the \sw{SWI-Prolog} engine.
The first library facilitates the seamless integration of
databases via the \sw{odbc} interface. Prolog is particularly well
suited both for manipulating database meta-data (table structure
and fields) and for reasoning with the primary data.
The second library presents a uniform way for translating between terms
and HTML code and an interface for low level communication with the
operating system.
The former facilitates web-page composition via term manipulation
while the latter deals with non-logical aspects of the interaction with
the web-services. In tandem the two libraries allow a comfortable
high-level style of programming used for rapid-prototyping and
the refinement to a stable system that is fully implemented in Prolog.

Logic programming for web services have been advocated in a number
of approaches. Notably, in the Pillow library
(\cite{CabezaD_HermenegildoM_2001}) which is available
for a number of logic engines. Representing HTML code as term
structures is an appealing proposition. Prolog programs can
construct these at run-time with correct HTML code generated
by library predicates.

The suitability of HTML as an interface platform for databases is not
unique to our approach. It is a very popular choice particularly
through the PHP scripting language, \cite{Php5}. The benefits of our approach
relative to PHP is its relational and high-level nature and
the fact that Prolog is a general purpose programming language.
On the other hand PHP provides more dedicated features and
a large community of practitioners.

The paper is structured as follows. The main components of the
system are presented in Section 2 followed by its main
database-independent functions in Section 3.
Section 4 presents some specific characteristics of using
the interface for biochemical data.
The concluding remarks are in Section 5.

\section{System architecture}

\begin{figure}[t]
  \includegraphics[width=1\textwidth]{arch}
  \caption{System architecture and interactions}
  \label{fig:arch}
\end{figure}

This section describes the architecture of our system (\emph{hdb}) and
its interaction with the operating system.
The overall flow of data is shown in Fig.~\ref{fig:arch}.
Semi-circles show interaction software between systems.
The round-edged rectangular labelled `hdb' depicts our system
and the three rectangular boxes show its main components.

Requests to service a page arrive at the server machine.
The operating system invokes \sw{hdb} via \sw{xinetd} and the \sw{http}
library is used to collect the request. This is parsed and
in turn \sw{SQL} or queries about meta-data are constructed.
Using \sw{odbc} the system interacts with the databases and
the results of this interaction are processed into term structures
that will form the HTML page to serve. The page is generated
by the \sw{http} library. In the specific application we have
employed the generic interface, \sw{http} requests are also parsed
for references to statistical analysis to be performed by \swt{R}
\cite{R2006}.
This is typically the scenario when either a new mass spectrometry
experiment is uploaded, or a comparative analysis table entry is
requested by the user.
The \sw{R.pl} library will handle any such interactions communicating
any results from the analysis that need to be saved, to the SQL
generator.

The system presented here is fully implemented within \sw{SWI-Prolog}
(see \cite{WielemakerJ_2007}).
The two crucial parts of this Prolog engine that enable this approach
are the \sw{http} and \sw{odbc} libraries. As can be seen in
Fig.~\ref{fig:arch} the \sw{http} library plays two complementary
roles. On one hand it provides the server machinery for reading
in requests, while its other role is to translate special Herbrand terms
to HTML documents. The full capabilities of \sw{SWI-Prolog} with regard
to web-services is discussed in detail in \cite{WielemakerJ+2007}.

The \emph{hdb}  server is based on the \sw{http} library and can be started
in two ways.
The simpler method is by presenting a call to the engine, such as:
\[ \mbox{\pl{ ?- http_server(reply, port(8080),timeout(30)] ).}} \]
As long as the engine that runs this query is active, the port 8080
will be serviced by the predicate \pl{reply(+Request)}.
The library instantiates \pl{Request} to a Prolog representation of the
incoming request.
This method is particularly useful during software development as
it provides a terminal at which messages about the computation in
progress can be delivered to.

\begin{figure}[t]
\begin{tabular}{llcl}
service hdb \\
\{ \\
        & port            & = & 8080 \\
        & socket\_type     & = & stream \\
        & protocol        & = & tcp \\
        & wait            & = & no \\
        & user            & = & nicos \\
        & server          & = & /srv/www/html/hdb/hdb\_xinetd \\
        & log\_on\_failure  & += & USERID \\
        & log\_on\_success  & += & PID HOST EXIT \\
\} \\
\end{tabular}
\caption{A typical \sw{hdb xinetd} file}
\label{fig:xinetd}
\end{figure}

Alternatively and more conveniently for non-developmental deployments,
the server can be started through
an intermediary piece of software such as \sw{inetd} or as is common
in our set-up and as illustrated in Fig.\ref{fig:arch}, by \swt{xinetd}.
These are daemons in the terminology of operating systems, programs
that run continuously listening to the internet ports.
A typical \sw{xinetd} entry will reside in \url{/etc/xinetd.d/hdb} and
contain the entries shown in Fig.~\ref{fig:xinetd}.

Requests to the relevant port (8080 in our example) need to be
allowed connection to the server. Typically this is via an entry to the
services (\url{/etc/services'}) file such as
`hdb         8080/tcp' \cite{PostelJ_80}.

Once the request has been passed to \emph{hdb}  and parsed, generation of a
reply page will
typically instigate some interaction with the serviced databases.
The actual interaction is facilitated by the \sw{odbc} library.
There are two major types of requests to be served.
Ones that require meta-data and ones that manipulate primary data.

The facilities of the \sw{odbc} with regard to meta-data are
particularly useful as it means the core interface is completely
free of references to any specific database.
For instance by using:\\
\begin{eqnarray*}
  \lefteqn{} & \lefteqn{} & \mbox{\pl{odbc_current_connection(-Connection, -DSN)}}
  \\
  \lefteqn{} & \lefteqn{} & \mbox{\pl{odbc_get_connection(+Connection, database_name(-DB))}}
\end{eqnarray*} \\

all open connections can be found and via that all the related databases.
Similarly, use of \\
\begin{eqnarray*}
  \lefteqn{} & \lefteqn{} & \mbox{\pl{odbc_current_table(+Connection, -Table)}}
  \\
  \lefteqn{} & \lefteqn{} & \mbox{\pl{odbc_table_column(+Connection, +Table, -Column)}}
\end{eqnarray*} \\
provides access to the database dictionary. With these calls,
the database structure and standard operations can be displayed
without any hard-wired dependencies. In the following Section we will
show in detail how these are used in our system.
The \sw{odbc} library depends on operating system connectivity to \sw{ODBC}
(open database connectivity) software. An instance of such software
is \sw{unixODBC} \cite{unixODBC2007}. In our experience this has worked well
with the Prolog libraries discussed here.

The organisation of the code reflects the two main components of the
system. Core functionality predicates are stored in directory \pl{src}
while extensibility predicates are in directory \pl{site}.
The distributed code is ready
to be deployed as soon as a minimal site specific configuration is set-up.
This should describe the location of the databases to be served and
the users of the interface. Note that no information about the
database schemata is needed for the core interface to operate
correctly.

Our final note in this section is that \sw{SWI-Prolog} in tandem with other
open source software provides a powerful platform for serving HTML pages. The
high-level of programming, the independence of specific data-sources and the
structured nature of Herbrand terms which maps well to correct HTML code
ensure that effective interfaces can be built with minimal programming effort.

\section{Core functionality}

In this Section we describe the main functions of the interface.
We present and discuss features that are generic and can be employed
as-is in any installation of the system. We distinguish six types of pages
in this category: (a) authentication, (b) overview of databases
(c) view of database, (d) single table, (e) single view and (f)
profile data. In what follows we detail these six categories.

The first point of contact a user will have with the interface
is the authentication page, where they are asked for a username
and password.
There are two types of authentication services provided.
The site administrator must choose one of them at installation.
The first, uses the Prolog internal mechanism that keeps a thread
alive for a specified amount of time. Usually the amount of time is set to
a few minutes. Within that period
the connection is authenticated and the user can interact with
the system. Each interaction resets the thread to the start of the
interval. If there is inactivity for a period longer than the interval
the process dies and the user will need to log-in again.

\begin{figure}[t]
  \includegraphics[width=1\textwidth]{home_nd}
  \caption{Home page}
  \label{fig:home}
\end{figure}

The second type of authentication services is IP address based.
In this mode of operation, the credentials of a user are associated to
the IP address from which they last log-in. The interval during which this
activation is valid is usually set to a few hours, typically
the duration of a working day. This provides a less
secure model but which is much easier to use in practice.
In both authentication scenarios, \emph{hdb}  is by necessity of a more or equal
restrictiveness to that of the underlying databases with regard to
database operations.
Each \emph{hdb}  user is assigned to a db user in a modular way
and the exact mapping is a matter of site administration, although
typically both credentials will be identical.
It is worth noting that authentication has been designed with ease of
use in mind rather than maximal security from determined attacks.

Once users have tackled authentication and gained access to the system they
are presented with the home \emph{hdb}  page which shows an overview
of the resources they can access. An example is shown in Fig.~\ref{fig:home}.
At the top right, there are persistent navigation options that allow
logging-out, access to session profile and a link to the home page.
The main body of the page gives access to the databases and views
accessible to the user.

Each database page presents the tables which are contained in the
database source along with a subset of standard operations that can
be performed on each. A partial example is shown below:

\begin{tabular}{llllll}
Experiment		& [input]& 	 [update]	&  [delete]& 	 [query]& 	 [all] \\
ExternalDataSource& 		[input]& 	 [update]& 	 [delete]& 	 [query]	&  [all] \\
Input& 		[query]& 	 [all] \\
Mix	& 	[input]& 	 [update]	&  [delete]	&  [query]	&  [all] \\
MixIngredient& 		[input]& 	 [update]& 	 [delete]& 	 [query]	&  [all] \\
Plate	& 	[input]& 	 [update]	&  [delete]& 	 [query]& 	 [all] \\
\end{tabular}

\noindent Note that in our example table `Input' is read-only and it is
thus only associated with read operations. This table
is dedicated to recording the changes that occur to the databases from
within the \emph{hdb}  interface.
Our system supports explicit storage of such information.
Navigating via the table name will present a single table page while
the link on each operation links to the operation page for the
specified table.

A page detailing a single table shows the fields of the table
along with their types and provides access to operations on the table.
These are identical to those that appear along side the table name in the
database page. They will usually be a subset of: `input', `update',
'delete', 'query' and 'all'. Typically it will be the maximal subset,
and it is also possible to hook table or database specific operations.
An extract from a table page is as follows:

\begin{figure}[t]
  \includegraphics[width=1\textwidth]{input_table_nd}
  \caption{Input data to a table.}
  \label{fig:input}
\end{figure}

\vspace{0.3cm}
\begin{tabular}{llllll}
scibsdb.Compound	 & has 210 rows. \\
Table columns:	 \\
Name	      &	Defn. Type     & Null	& Key  & Def & Extra \\
CompID      & bigint(20) uns.	& NO	   & PRI	 &	    & autoinc \\
CompName		& tinytext	      & YES	\\
CompMr		& float uns.	   & NO  \\
pKa		   & float	         & YES	\\
EduID		   & bigint(20) uns.	& YES	\\
CompNote		& text	         & YES \\
\end{tabular}

\vspace{0.3cm}
The first line gives the database and table name along with its
population size.
The headings of the columns appearing on the third line of the example
above are, in left-to-right order: the field name, the type of the field,
a Boolean value signifying whether or not a null value is allowed,
 a value reflecting whether field is a key for the table,
 the default value for the field and finally, any extra information about
 the field.
In our example the first field, `CompID', is an auto-incrementing
integer field. Also note that `uns' is an abbreviation for unsigned.

Most operations follow intuitively after their name. The `all' operation
is the maximal query that allows the user to view all data in the table.
(Standard site-wide defaults of presentation style apply.) One of the more
useful operations is inserting data into tables. An example is shown
in Fig.~\ref{fig:input}. The interface automatically handles auto increment
fields (integer fields which are routinely used as unique identifiers) and
enumeration types that are displayed as dropped down menus.

\begin{figure}[t]
  \centerline{\includegraphics[width=0.8\textwidth]{day_obs_crop_nd}}
  \caption{Input of multiple experiments.}
  \label{fig:obs}
\end{figure}

Returning to describing the `home' page, we have another type
of object, namely, views. Views are convenient higher level
objects which allow operations that
manipulate more than one table, or more than one row of
a single table within a single step. In Fig.~\ref{fig:home}
a number of specialised views are offered to the user.
For instance `sdf\_3d' displays the 3D representation of an SDF entry.
Each SDF is a textual representation of a chemical substance
(\cite{DalbyA+1992}).
The view `observations' has one operation which allows
results from many experiments taken at a single time-point
to be inputted together. As most of the views and operations are
specific to a given site and makes extensive use of the extensibility
features of our system they will be discussed in further detail
in the next section. An example of an operation to such
a view is given in Fig.~\ref{fig:obs}, the details of which will also
be discussed in what follows.
It suffices here to say that \emph{hdb}  provides convenient hooks for new
views and associated operations to be defined within Prolog.

Finally, the user has access to information profiling his session.
Information regarding the user names, IP address, session ID and
the server associated with this session is presented, as illustrated
in the following example:

\begin{tabular}{l}
\\
User Profile \\
 \\
Logged-in on hdb server: Scibs DBs 0.2 \\
With user name: nicos \\
Database user name: nicos \\
Login time: at(2007, 8, 24, 14, 22, 40, 10) \\
Peer: 129.215.137.168 \\
 \\
Pages are served by : hdb  0:0:2 \\
Server: scibsfs.bch.ed.ac.uk:8080 \\
Session: 5807-da08-fbaa-fe69 \\
\end{tabular}
\vspace{0.5cm}

Warnings and errors about \emph{hdb}'s operation are reported by the
system at the top of the first generated page after the error was
caught. Messages are asserted as \pl{diagnostic/1} terms via the
\pl{http_session_assert/1} primitive. The example message
\[ \mbox{\pl{unable_to_connect_to_db_source(nilhhloc-ni_lhh)}} \]
informs of the unavailability of database \pl{ni_lhh}
right after log-in. The message appears near the top of the page
in orange colour as to draw the user's attention and is non persistent.

\section{Storing biochemical data}

The interface can be tailored to a site's specific needs through a
number of hooks and handlers. Both of these can alter the HTML generated
by the system.
Hooks are optional parts that when present alter a specific part of the
interaction. For instance, a particular field's output can
be linked automatically to a live HTML link, or certain fields for
a table are auto-filled by some scripts. Hooks are appropriate
in extending the system in a way that allows database table evolution.
The addition of extra tables or columns (fields) will usually require
no changes to hooks of existing columns.
Handlers on the other
hand, are predicates that deliver more substantial extensions to
the interface.
For instance a handler may produce the HTML code from a non-standard
operation on a view (such as the `disp' operation on view `sdf\_3d'
detailed below).

\begin{figure}[t]
\begin{verbatim}
hdb_hook_column_input_def_value(ni_lhh, _, Column, Date) :-
     atom_concat( _, 'Date', Column),
     get_time(Time),
     convert_time(Time, Yr, Mo, Dy, _Hr, _Mn, _Se, _Ml),
     number_codes(Yr, YrCs),
     number_codes(Mo, MoCs),
     number_codes(Dy, DyCs),
     flatten([YrCs,"-",MoCs,"-",DyCs], DateCs),
     atom_codes(Date, DateCs).
\end{verbatim}
\caption{Date default values in database `ni\_lhh'.}
\label{fig:defvalue}
\end{figure}

For example, hooks are used in views to declare the participating columns
(\pl{db_view_has_column( +View, +DB, +Table, +Columns, +JnKeys)})
and the operations defined on a particular view
(\pl{db_view_has_ops( +View, +Op )}). For tables, hooks are very useful
in defining input, output settings that can take into account
local administration issues. For instance,
\pl{hdb_hook_column_input_textarea(+DB, +Table, +Clmn, -Rows, -Cols)}
can be used to overwrite the default size for the input text box at
an insert operations.
For a more concrete example, consider the code in Fig.~\ref{fig:defvalue}.
Predicate \pl{hdb_hook_column_input_def_value(+DB, +Table, +Column, -Def )}
when defined for a specific column, table and database combination, it
dictates a default input value for the said column. The shown code
defines the current date as the default value for each column in database
`ni\_lhh' that has a name containing `Date' as a suffix. In our example this
is true irrespective of the table's name.

In the remainder of this Section we will present some database-specific
aspects of the system and our local installation which
stores lab results and biochemical data.
Briefly described the main requirements are:
storage of experimental data from (a) C. elegans growth,
(b)micro-array and spectrometry data for samples resulting from the
C. elegans experiments, and (c) information about associated molecules.

\begin{figure}[t]

  \centerline{\includegraphics[width=0.6\textwidth]{nemadipineA_whbkg}}
  \caption{Jmol invocation. NemadipineA, (hdb) Eduliss ID: 108525. }
  \label{fig:jmol}
\end{figure}

Although a limited number of target ligands are used in our experiments
we are able to include into our system a much broader
selection of chemical substances. In total 1.7 million are available
and they are drawn from the EDULISS database \cite{HintonCA_2005} (version 1.0).
A structured schema has been devised for
storing the atomic information that reside in flat format SDF files.
Individual molecules can then be inspected by retrieving all relevant
entries writing those out in the usual flat file format and call
the Jmol java applet, \cite{Jmol}, to display the three or two dimensional representation
of the molecule. An example of a displayed ligand (small molecule) is in
Fig.~\ref{fig:jmol}. The display operation is labelled `disp' and is
available for views `sdf\_2d' and `sdf\_3d'. The example shown is
Nemadipine-A and was shown to induce a marked phenotype in C. elegans
(\cite{KwokTCYK+2006}).

It is often the case that complications of database interfaces
arise from the disparity between the best way to hold the data
in the database and the users' way of organising the data in their minds.
Inputting data is one crucial part in which a reconciliation is vital.
In our system views can be used to insert data in ways that are more
intuitive and faster for the user.
As an example consider Fig.~\ref{fig:obs}.
The user is able to input a number of observations corresponding
to `well' experiments that were started at the same time. This is an
intuitive way of viewing the set of experiments as all wells
come from a single plate and have synchronised start times.
On submitting the
data a number of separate table entries will be stored in the database.
The majority of the entries in Fig.\ref{fig:obs} are in the form of
selection menus as they are of enumeration type further easing
the input process.

A major consideration in experimental settings is the management of
raw datafiles as well as the tracking of large files as they
go through various stages of analysis.
Our approach is to use the uploading capabilities of the \sw{http} library
and store the files in canonical locations with a file link stored
in the actual database. The library has been performing robustly and
has coped with files of substantial sizes.

\begin{figure}[t]
   \begin{tabular}{cc}
   \includegraphics[width=0.6\textwidth]{autofill_2} &
   \begin{minipage}[b]{0.35\textwidth}
   \includegraphics[width=1\textwidth]{2}
   \\
   \includegraphics[width=1\textwidth]{rc}
   \end{minipage}
   \\
   \end{tabular}
   \caption{Left: automatically filled fields. Right: generated averaged ion count (top) and retention time correction (bottom).}
   \label{fig:autofill}
\end{figure}

In addition to storing primary data we have used auto filling capabilities
in the system to automatically generate store derived information on the
data. In particular output from mass-spectrometry experiments that are
exported in NetCDF format are uploaded to the database. The
\sw{xmcs} \cite{xcms} part of the \sw{Bioconductor} \cite{Bioconductor2007}
package for the \sw{R} \cite{R2006} statistical system is started
through a Prolog interface. We have built a simple \sw{Prolog} to $R$
interface that runs the latter as a slave with the command:
\begin{tabular}{@{\hspace{1cm}}l}
\\
\verb+R --slave --no-environment+
\\
\vspace{0.02cm}
\end{tabular}

\noindent The input, output and error streams of this process are handled by
Prolog as to enable interaction with the \sw{R} shell. The in-house library
facilitates the translation of term structures to atoms that are
written on to the \sw{R} process' input. Also it reads in and translates
output that appears in the \sw{R} process' output and error streams.
It thus allows Prolog to access the vast wealth of functions
and packages available in \swt{R}. The Prolog-to-R interface is also made
available as an independent module (\cite{rsession})
and is included into \sw{SWI} main source distribution
as a contributed package.

Fig.~\ref{fig:autofill} shows an example of automatically filled table entries.
In entering data to table `SpecScan' the user can only input values for
7 out of the 18 fields. The remaining are filled with:
(a) visual summaries of the data- a postscript output of the averaged
ion count for each scan (ScanAICLoc) and a heatmap image (ScanIMGLoc),
(b) information about the sample that exist in the bundled input
(fields SpectraNof to MassMax) and basic parameters for some of the
visual summary fields- here PrfMethod	and PrfStep for the heatmap generation.
All derived information are produced by invoking the \sw{xcms} \sw{R} package
on the data uploaded by the mass-spectrometrist (field ScanLoc).

Our approach has the benefit that output from specialised software
is stored in accessible forms that can be viewed by all partners
in the project.
It is also the case that it improves quality control tasks
and that by automatically filling the form
there is less mundane typing and data-entry and thus less chances of
an error to occur. Additionally in the scenario we have employed the
interface, the statistical analysis with \sw{xcms} takes a substantial
amount of time to run. By storing the results of the analysis in a central
repository with all associated information managed automatically, we
ensured that subsequent inspections of the analysis are handled
promptly and correctly.

The top left of Fig.~\ref{fig:autofill} shows the main part of an input
operation with the values of the fields that can be changed filled.
At the top right is the generated averaged ion count (AIC) which
plots average ion count against time and provides an overall picture
of activity within the spectra. The bottom right of Fig.~\ref{fig:autofill}
shows the retention time correction as generated by \sw{xcms}
when creating a comparison among spectra from two conditions.
Retention time correction is performed as to align multiple
mass-spectra from two distinct conditions so that their peaks can
be compared in a meaningful way. Visual inspection of the correction
is a good indicator for the quality of the alignment and thus a
crucial information to include in the stored derived information information.

\section{Conclusions}

We presented a system that implements a high level interface for
data sources by exploiting two \sw{SWI-Prolog} libraries. The two main
advantages of our implementation platform are the relational
nature of Prolog and the compositional nature of Herbard terms.
The former allows seamless integration of relational databases
and the latter facilitates construction of structured HTML
code.

To our experience the main benefits of \sw{hdb} are (a) that it implements
a well separated organisation of what is generic and what must be
tailored for a particular installation, and (b) that the generic part
of the system is schema-driven in the sense that it is automatically
constructed from the underlying databases with no hard-wired dependencies.

Our work has demonstrated the usefulness of a relational
programming language for providing interfaces to databases via served
HTML pages. The generic part of the interface can be deployed directly
to any existing database. The installation can then slowly be ramified
and tailored to the particular site via a number of extensibility
features the system provides.

We have identified four directions in which we will direct
future work. First is the ability to have communication between different
pages via collections of database items. These can be through tick boxes
at query result pages. Also to provide generic mechanisms for
background processes filling of derived information. This will allow
the interface to work as a front-end and hiding a lot of dedicated
background processing. In our databases, for instance, we can allow
mass-spectrometry staff to create views that explore differentially
expressed mass over charge peaks from a set of controls against a set
of screens. The third direction in which to develop the system is
in providing simpler query mechanisms such as ability to choose a
list of fields and provide values or regular expressions for those.
Finally, to modularising the database access and
allowing alternative methods of interaction such as via the BerkleyDB
interface (package `db' in \swt{SWI-Prolog}).

The source for the system described in this paper can be downloaded from
\url{http://scibsfs.bch.ed.ac.uk/~nicos/sware/hdb}. It has been developed
and tested on Linux systems.
The in-house library
that handles communication with \swt{R}, \sw{r\_session,}
is included as a contributed package in current releases of
\swt{SWI-Prolog} (\swt{library('R')}).

\section{Acknowledgements}
This work was funded by BBSRC via grant BB/D00604 X/1 which is part of
the SCIBS (Selective Chemical Intervention in Biological Systems)
initiative.
We would like to thank Prof Malcolm Walkinshaw for his encouragement
and project leadership and Kun-Yi Hsin for help with the SDF files
and EDULISS database. We are indebted to Jan Wielemaker, the developer
of \swt{SWI-Prolog},
for developing a very stable and powerful core system with two exemplary
libraries.
Also we thank him for his prompt replies in resolving technical issues
and for included our \sw{R} interface to the \swt{SWI}'s main source branch.