\documentclass[twoside]{MATH77}
\usepackage{multicol}
\usepackage[fleqn,reqno,centertags]{amsmath}
\begin{document}
\hyphenation{SCPVAL}
\begmath 11.1 Polynomial Least-Squares Curve Fit

\silentfootnote{$^\copyright$1997 Calif. Inst. of Technology, \thisyear \ Math \`a la Carte, Inc.}

\subsection{Purpose}

This subroutine determines a univariate polynomial that fits a given discrete
set of data in the sense of minimizing the weighted sum of squares of residuals.
The fitted polynomial can be constrained to match some data points exactly
by appropriate setting of the a priori standard deviations of the data
errors.

Auxiliary subroutines, described in Chapter~11.2, may be used to evaluate,
differentiate, or integrate a polynomial produced by this fitting procedure.

\subsection{Usage}

\subsubsection{Program Prototype, Single Precision}
\begin{description}
\item[INTEGER]  \ {\bf M, NMAX, NDEG}

\item[REAL]  \ {\bf X}($\geq $M),{\bf Y}($\geq $M),{\bf SD}($\geq $M~or~=1),%
{\bf P}($\geq $NMAX+3), {\bf SIGFAC, W}($\geq$(NMAX+3)$\times $(NMAX+3))

\item[LOGICAL]  \ {\bf SEEKN, COMTRN, CHBBAS}
\end{description}
Assign values to M, X(), Y(), SD(), NMAX, SEEKN, COMTRN and CHBBAS. If
COMTRN = .FALSE. values must also be assigned to P(1) and P(2).%
\begin{center}
\fbox{\begin{tabular}{@{\bf }c}
CALL SPFIT (M, X, Y, SD, NMAX, SEEKN,\\
COMTRN, CHBBAS, P, NDEG,SIGFAC, W)\\
\end{tabular}}
\end{center}
Following the CALL to SPFIT one may wish to use SCPVAL or SMPVAL to evaluate
the fitted polynomial at specific points, SCPDRV or SMPDRV to differentiate
the polynomial, or SCPINT or SMPINT to integrate the polynomial. See Chapter
11.2 for descriptions of these subprograms.

\subsubsection{Argument Definitions}
\begin{description}
\item[M]  \ [in] Number of data points.

\item[X()]  \ [in] Array of values of the independent variable. Values need
not be ordered and may be repeated.

\item[Y()]  \ [in] Array of values of the dependent variable indexed to
correspond to the X() values.

\item[SD()]  \ [in] If SD($1)>0.$, each SD($i$) must be positive and will be
assumed to be the user's a priori estimate of the standard deviation of the
uncertainty (observational errors, etc.) in the corresponding data value
Y($i$).

If SD($1)<0.$, $|$SD(1)$|$ will be used as the a priori standard deviation
of each data value Y($i$). In this case the array SD() can be dimensioned
SD(1) since locations following SD(1) will not be used.

\item[NMAX]  \ [in] Specifies the maximum degree polynomial to be
considered. Require NMAX\ $\geq 0$. If NMAX $>$ M $-$ 1 the subroutine will
function as though NMAX = M $-$ 1.

\item[SEEKN]  \ [in] If SEEKN = .TRUE. the subroutine will determine the
optimum value of NDEG $\leq $ NMAX in the sense described below in Section D.

If SEEKN = .FALSE. the subroutine will set NDEG = NMAX unless this is a
singular or nearly singular problem, in which case NDEG will be reduced as
necessary.

\item[COMTRN]  \ [in] If COMTRN = .TRUE. the subroutine will determine the
transformation parameters P(1) and P(2) as described in Section D.

If COMTRN = .FALSE. the subroutine will use the values of P(1) and P(2) that
have been set by the user.

\item[CHBBAS]  \ [in] If CHBBAS = .TRUE. the subroutine will use the
Chebyshev basis. If CHBBAS = .FALSE. the subroutine will use the monomial
basis. The Chebyshev basis is recommended for better numerical stability,
when NMAX is greater than about six.

\item[P()]  \ [inout] Parameter vector defining a polynomial according to
Eqs.\,(1) and (2) or (3) and (4). Values of P(1) and P(2) may either be set
by the user, or by the subroutine, depending upon the value of COMTRN.
Values of P($j$+3), $j$ = 0, ..., NMAX will be computed by the subroutine. If
NDEG $<$ NMAX, the subroutine will set P($i$+3) = 0, for $i$ = NDEG + 1, ...,
NMAX.

\item[NDEG]  \ [out] Set by the subroutine to indicate the degree of the
fitted polynomial. On return NDEG will satisfy 0 $\leq $ NDEG $\leq $ NMAX
if the computation was successful and will be set to $-$1 if an error occurred.

\item[SIGFAC]  \ [out] Number computed by the subroutine. See discussion of
SIGFAC in Sections C and D following.

\item[W()]  \ [scratch] Array of working storage.
\end{description}
\subsubsection{Modifications for Double Precision}

For double precision usage change the REAL type statements to DOUBLE
PRECISION and change the subroutine name from SPFIT to DPFIT. Change the
names of the auxiliary subroutines mentioned above to DCPVAL, DMPVAL,
DCPDRV, DMPDRV, DCPINT, and DMPINT, respectively.

\subsection{Examples and Remarks}

\subsubsection{Example}

Given a set of 12~data pairs $(x_i$, $y_i)$, compute the
weighted least-squares polynomial fit to these data letting the subroutine
determine the preferred polynomial degree not to exceed~8. After computing
the least-squares polynomial $p(x)$, compute and tabulate the quantities $%
x_i $, $y_i$, $p(x_i)$, and $r_i = y_i - p(x_i).$

The program DRSPFIT carries out this computation using subroutines SPFIT and
SCPVAL. The output is shown in ODSPFIT. Note that the value of NDEG selected
by the subroutine is~7.

\subsubsection{Transformation of the Independent Variable}

For the best numerical accuracy, both in determining the best fitting
polynomial and in the later evaluation of the polynomial, it is generally
advisable to use transformation parameters P(1) and P(2) that cause the
transformed variable $u$ of Eqs.\,(1) or (3) to range from $-$1 to +1. This
condition can be obtained by setting COMTRN = .TRUE.

When fitting with polynomials of degree higher than about six, the Chebyshev
basis generally gives better numerical accuracy than the monomial basis. To
obtain the potential numerical advantages of the Chebyshev basis it is
essential to cause the transformed variable, $u$, to range from $-1$ to +1.

To force an identity transformation $(i.e.$, effectively no transformation)
of the independent variable, set COMTRN = .FALSE., P(1) = 0., and P(2) = 1.

\subsubsection{Interpretation of SIGFAC}

If the user has set all SD($i$) = 1.0, or equivalently, set SD(1) = $-$1.0,
SIGFAC can be interpreted as an a posteriori estimate of the standard
deviation of the error in each Y($i$) value. More generally, whatever values
the user has assigned to the SD($i$)'s, the a posteriori estimate of the
standard deviation of the error in Y($i$) is SIGFAC $\times $ SD($i$).

\subsubsection{Equality Constraints}

If the user wishes the fitted polynomial to agree to machine accuracy with
one or more of the data points, this can be accomplished by setting the SD()
value for such points much smaller than for the other points.

Let $\epsilon $ denote the machine precision, $i.e.$, $\epsilon =$
R1MACH(4) in single precision or $\epsilon =$ D1MACH(4) in double
precision, see Chapter~19.1.  For some value of $c$
in the range 0.5 $\leq c \leq 0.75$, we suggest setting SD($i) = \epsilon
^c$ for the points at which an exact fit is desired and SD($i) = 1.0$ for
all other points. For example if $\epsilon = 10^{-8}$ set SD($i$) in the
range $10^{-4}$ through $10^{-6}$ for the exact fit points.

Using $c < 0.5$ may not produce sufficiently small residuals at the desired
points of exact fit, whereas setting $c > 0.75$ may trip the
near-singularity test in these subroutines leading to an unwanted alteration
of the problem.

Note that it is not mathematically reasonable to attempt to force exact fits
at more than NMAX$+1$ points.

\subsection{Functional Description}

The user provides data $(x_i$, $y_i$, $s_i)$, for $i=1$, ..., M, and an
integer NMAX. If SEEKN = .FALSE. and the problem is not rank-deficient or
extremely ill-conditioned, the subroutine simply determines the polynomial $%
p_n(x)$ of degree $n=$ NMAX that minimizes the following weighted sum of
squares of residuals:
\begin{equation*}
\rho _n^2=\sum_{i=1}^M\left[ \frac{y_i-p_n(x_i)}{s_i}\right] ^2
\end{equation*}
The subroutine also computes%
\begin{equation*}
\sigma _n=\left[ \frac{\rho _n^2}{\max (1,M-n-1)}\right] ^{1/2}
\end{equation*}
and returns this value as SIGFAC.

The subroutine makes use of subroutines SROTMG and SROTM (or DROTMG and
DROTM) from the BLAS1 (See Chapter~6.3.) to implement a sequential
Modified Givens orthogonal transformation method of reducing the matrix of
the least-squares problem to triangular form \cite{Lawson:1974:SLS}, and
then solves the triangular system.  This method has excellent numerical
stability.

After triangularizing the matrix of the problem for degree NMAX, the
quantities $\rho ^2_n$ and $\sigma ^2_n$ may be computed inexpensively for
all degrees $n$ from zero through NMAX. Thus, if the user sets SEEKN =
.TRUE. the subroutine computes these values of $\rho ^2_n$ and computes
\begin{equation*}
\text{CMIN} = \min \{\sigma ^2_n : 0 \leq n \leq \text{NMAX}\}.
\end{equation*}
The quantity $\rho _n$ is a strictly nonincreasing function of $n$ whereas $%
\sigma _n$ typically decreases initially with increasing $n$ but then
oscillates and slowly increases as $n$ becomes so large that the polynomial $%
p_n(x)$ is fitting noise rather than a true polynomial signal in the data.

The subroutine sets NDEG to be the smallest value of $n$ for which $\sigma
^2_n \leq 1.01 \times $CMIN, and it sets SIGFAC $= \sigma _{NDEG}$. This
method of selecting NDEG is generally satisfactory when the ratio NMAX/M is
reasonably small, say less than $1/3$. If this ratio is larger there is a
tendency for the NDEG selected by this method to be larger than one might
pick if one viewed graphs of solution polynomials of different degrees.

Whatever the setting of SEEKN, if the problem for degree NMAX is
rank-deficient, or very ill-conditioned, the subroutine will restrict
consideration to lower degrees for which the problem is not extremely
ill-conditioned. In particular this reduction of degree will certainly occur
if NMAX$+1 > $ M.

\subparagraph{Parameterization of the polynomial, $p_n(x)$}

In this subroutine an $n^{th}$ degree polynomial $p_n(x)$ is represented in
one of two special parametric forms (monomial basis or Chebyshev basis),
both of which include the specification of a linear transformation of the
independent variable in the parameterization. The parameters defining an $%
n^{th}$ degree polynomial $p_n(x)$ are stored in the array P($i$), $i=1$, ...,
$n+3.$

Using the monomial basis these parameters define the polynomial $p_n(x)$ as
follows:
\begin{align}
\label{O1}u&=\frac{x-P(1)}{P(2)}\\
\label{O2}p_n(x)&=\sum_{i=0}^nP(i+3)u^i
\end{align}
whereas, if the Chebyshev basis is requested, $p_n(x)$ is defined as:
\begin{align}
\label{O3}u&=\frac{x-P(1)}{P(2)}\\
\label{O4}p_n(x)&=\sum_{i=0}^nP(i+3)T_i(u)
\end{align}
where $T_i(u)$ denotes the Chebyshev polynomial of degree $i$. The Chebyshev
polynomials may be defined as follows:%
\begin{gather*}
T_0(u)=1,\quad T_1(u)=u,\quad T_2(u)=2u^2-1\vspace{-4pt}\\
T_i(u)=2u\ T_{i-1}(u)-T_{i-2}(u)\quad i=3,4,...
\end{gather*}
The parameters P(1) and P(2) that occur in the transformation formula (1) or
(3) may be set by the user (COMTRN = .FALSE.) or else computed by this
subroutine (COMTRN = .TRUE.). In the latter case P(1) and P(2) will be
computed as\vspace{-2pt}%
\begin{align*}
\text{P}(1)&=(x_{\max }+x_{\min })/2\\
\text{P}(2)&=(x_{\max }-x_{\min })/2
\end{align*}
where $x_{\max }$ and $x_{\min }$ are respectively the maximum and minimum
values of $x$ in the data array X($i$), $i=1$, ..., M. This causes the
transformed variable $u$ of Eq.\,(1) or (3) to range from $-1$ to +1 as $x$
ranges from $x_{\min }$ to $x_{\max }.$

\bibliography{math77}
\bibliographystyle{math77}

\subsection{Error Procedures and Restrictions}

The use of the Chebyshev basis is effective in improving the conditioning of
the problem only if a transformation of the variable is used that maps the
interval of interest for both fitting and evaluation to an interval
approximately coincident with [$-1.$,~1.].

The automatic procedure for selecting the degree of the fitted polynomial,
used when SEEKN = .TRUE., tends to select the degree somewhat higher in some
cases than one would choose by looking at plots of fits of different degrees.

This subroutine will issue an error message using the error processor
in Chapter 19.2 at level 0, set NDEG $= -1$, and return if
any of the following erroneous conditions exists:
\begin{itemize}
\item[1.]  SD($1)=0$, or M $\leq $ 0, or NMAX $<$ 0.

\item[2.]  COMTRN = .FALSE. and P(2) = 0.

\item[3.]  SD($1)>0$. and some SD($i) \leq 0$. for $1< i \leq $ M.
\end{itemize}
\subsection{Supporting Information}

The source language is Fortran~77.

\begin{tabular}{@{\bf}l@{\hspace{5pt}}l}
\bf Entry & \hspace{.35in} {\bf Required Files}\vspace{2pt} \\
DPFIT & \parbox[t]{2.7in}{\hyphenpenalty10000 \raggedright
AMACH, DERM1, DERV1, DPFIT, DROTM, DROTMG, ERFIN, ERMSG, IERM1, IERV1\rule[-5pt]{0pt}{8pt}}\\
SPFIT & \parbox[t]{2.7in}{\hyphenpenalty10000 \raggedright
AMACH, ERFIN, ERMSG, IERM1, IERV1, SERM1, SERV1, SPFIT, SROTM, SROTMG}\\
\end{tabular}

Initially designed and programmed by C.~L.~Lawson, JPL, 1970. Modified by
Lawson and S.~Y.~Chiu, 1984, to use Modified Givens rather than Householder
transformations to reduce the storage requirement for W() and the complexity
of the program. Also, adapted the code to Fortran~77.

\begcodenp
\lstset{language=[77]Fortran,showstringspaces=false}
\lstset{xleftmargin=.8in}

\centerline{\bf \large DRSPFIT}\vspace{0pt}
\lstinputlisting{\codeloc{spfit}}
\newpage

\vspace{30pt}\centerline{\bf \large ODSPFIT}\vspace{10pt}
\lstset{language={}}
\lstinputlisting{\outputloc{spfit}}
\end{document}


\section{Strategic Classification}

 \begin{example}{\textbf {Strategic Classification} }
 Our first example is the strategic classification setting, a special case of our model, to show that the techniques in this paper apply to the version of the problem most frequently studied in the literature. The treatment $W_i$ is a classification label that does not impact outcomes, so $Y_i(1) = Y_i(0)$. $Y_i \in \{0, 1\}$ is a binary indicator where $Y_i =0$ indicates a borrower will default and $Y_i =1 $ indicates a borrower is credit-worthy. The goal is to predict $Y_i$ using a logistic regression that takes as input a single continuous score $X_i \in \mathbb R$. $W_i \sim \mbox{Bernoulli}{(\delta(X_i, \beta_i}$, where
   \[ \delta(x, \beta) = \frac{1}{1 + e^{- \beta x}}. \]
 Agents, however, benefit from a higher prediction, since everyone would prefer to be classified as credit-worthy. So, they choose $X_i$ strategically, to maximize their individual-specific utility function. We choose a utility specification that is increasing linearly in the probability that $W_i =1$. $\theta_i \sim \mbox{Normal}(0, 1)$ is the agents' inherent score, and $C_i \sim \mbox{Uniform}(1, 3)$ is a quadratic cost of manipulating the score from $\theta_i$, which varies by agent.

 \begin{equation*}
 \begin{split}
 & U(\delta(x, \beta), x) = \delta(x, \beta) - C_i(x - \theta_i)^2 \\
 & X_i(\beta) = \arg \max_{x} U(\delta(x, \beta), x)
 \end{split}
 \end{equation*}

 $Y_i$ is correlated with the unobserved type $\theta_i$. Manipulation incentivized by the prediction rule affects how correlated the observed score $X_i$ is with $Y_i$. The goal is to minimize the cross-entropy loss when the covariate distribution shifts in response to the logistic regression function implemented. Let $\hat Y_i = \delta(X_i, \beta)$.

 \[ \beta^* = \arg \min_{\beta} \mathbb E_{X_i \sim D(\beta)}  \Big[ -Y_i \log( \hat Y_i) - ( 1- Y_i) (1 - \log(1- \hat Y_i)) \Big]  \]

 \citet{frankel2019improving} show that when $\delta(X_i; \beta)$ is a linear model and $Y_i$ is continuous, then when $\beta^{FP}$ exists, then $\beta^* < \beta^{FP}$. The optimal treatment rule underweights characteristics that are susceptible to manipulation, in contrast to the stable point of a strategy that optimizes risk incorrectly assuming that the distribution of $X_i$ is fixed. In Section \ref{sec:sim} we use simulations to show that a similar conclusion holds in the non-linear binary setting.
 \end{example}

\subsection{Strategic Classification Simulation}
We impose the following assumptions on the framework in Example \ref{ex:class}, where the planner's goal is to find the MSE-minimizing prediction function. The assumptions imposed lead to a similar data generating process as the one analyzed in  \citet{frankel2019improving}.
First we assume that the unobserved type $\bm \theta_i = [Z_i, \gamma_i, R_i]$ has the following distribution:
\[ Z_i \sim \mbox{Normal}(0, 1), \qquad \gamma_i \sim \mbox{Uniform}(0, 1.5), \qquad R_i \sim \mbox{Normal}(0, 1) \]

The reported characteristics  are the result of the maximization of a linear - quadratic utility function that is increasing in the quality prediction $W_i = \beta_0 + X_i \beta_1$  and decreasing in the amount of manipulation of the  click-through-rate:
\[  X_i = \arg \max_{\tilde x_i} \beta_0 + \tilde x_i \beta_1 - \frac{(\tilde x_i-Z_i)^2}{2 \gamma_i}\]

Solving this leads to a reporting function of $ x(\beta, \theta_i) = Z_i + \gamma_i \beta_1$. The outcome, which is the realized content quality, is $y(\bm \theta_i) = Z_i + R_i $.

\begin{figure}[!ht]
    \centering
    \includegraphics[width=0.8\linewidth]{figures/sc_sim.pdf}
    \caption{Convergence of OT-DE to Optimal Prediction Function}
    \label{fig:sim}
\end{figure}

Figure \ref{fig:sim} plots the estimated $\beta_1$ for 1000 periods in which a batch of 1000 agents arrive in each period. $\beta_1$ indicates how much the prediction of the outcome $Y_i$ depends on the reported $X_i$.  The purple line is the estimated $\beta_1$ from OLS on a sample of data where  individuals are not rewarded based on $\beta_1 X_i$. When agents are strategic, this coefficient is too high. It places too much weight on $X_i$, which is susceptible to manipulation. The green line is the estimated $\beta_1$ when the planner updates $\beta_1$ at each step $t$ using OLS, and agents best-respond in the next period. The prediction functions reached by this adversarial game are still sub-optimal, with a higher realized mean-squared error than the full information solution. The blue line is the full information solution, where the planner has access to the manipulation ability of each agent and can solve for $\beta^*_1$ in one step using non-linear optimization. The orange line is the OT-DE estimate of $\beta^*_1$, which uses mean-zero perturbation of $\beta$ and observations of $X_i$ and $Y_i$ to take gradient steps towards the optimum. The risk minimization approaches induce a distribution of characteristics that is tainted by manipulation in a way that makes prediction more difficult. OT-DE induces a distribution that is more amenable to prediction, leading to a lower average MSE over the 1000 periods compared to the risk minimization approaches, despite taking some time to converge to the optimal value, see Table \ref{table:scmse}.

\begin{table}
    \centering
    \begin{tabular}{| c|r | }
    \hline
        \textbf{Method} & \textbf{Average MSE} \\
        \hline
         Full Information &  1.255  \\
         OT-DE & 1.257 \\
         Repeated Risk Minimization  & 1.281 \\
         Naive Risk Minimization & 4.021 \\
         \hline
    \end{tabular}
    \caption{Average MSE of Each Approach \label{table:scmse} }
    \end{table}


\documentclass[12pt]{article}

\usepackage[a4paper]{geometry}
\geometry{text={6.5in,9in}, top=1.2in, nohead}

\usepackage{times}

% \usepackage[math]{easyeqn}
% \usepackage{easybmat}
% \usepackage[definevectors]{easyvector}
% \usepackage{easybmat}
\usepackage{fancyvrb,color}

\newcommand{\NUMBER}[1]{\ensuremath{#1}}
\newcommand{\METHOD}[1]{\texttt{\color{blue}#1}}
\renewcommand{\verb}{\SaveVerb[aftersave=\texttt{\color{red}\UseVerb{verb}}]{verb}}

\DefineVerbatimEnvironment{code}{Verbatim}
{fontsize=\normalsize,formatcom=\color{blue},baselinestretch=1}

\DefineVerbatimEnvironment{ncode}{Verbatim}
{fontsize=\normalsize, baselinestretch=1,
 numberblanklines=false,numbersep=5pt,numbers=left}

\title{\verb|Calculator|: an Expression Evaluator Class}
\author{Enrico Bertolazzi}
\date{\normalfont\small\itshape
     Dipartimento di Ingegneria Industriale\\[0.25em]
     Universit\`a degli Studi di Trento\\[0.25em]
     Via Sommarive 9, I-38123, Povo, Trento\\[0.25em]
     \texttt{Enrico.Bertolazzi@unitn.it}\\[1em]
     Release 4.1}

\sloppy
\begin{document}
\maketitle

\begin{abstract}
    This document presents a C++ class for run-time evaluation of
    simple symbolic expressions.  This is particularly suitable to
    facilitates the input process from free format files.  The C++
    compiler must support templates, namespaces and exceptions.
\end{abstract}

\section{Including the class \texttt{Calculator$<$...$>$}}
%%
The software consists of a single header file \verb|calc.hh|. There is no
\verb|.a| or \verb|.so| files to be linked.
The \verb|calc.hh| facilities are available by the following inclusion
statement:
\begin{code}
  # include "calc.hh"
  using namespace calc_load ;
\end{code}
%%
\section{Instantiating an expression evaluator.}
%%
The instantiation process of an expression evaluator requires the
specification of its template type.  The statement
%%
\begin{code}
  Calculator<double> ee ;
\end{code}
%%
instantiates the object \verb|ee| which in this case is an
expression evaluator operating on \verb|double|s.

\section{Parsing a string}
%%
The object \verb|ee| can now be used to parse simple symbolic expressions
input as strings,
%%
\begin{code}
  bool err = ee . parse("1+sin(3.5)/4") ;
\end{code}
%%
the boolean variable \verb|err| is set \textit{true} when a parsing
error is found. The function \METHOD{get\_value()} returns the value
resulting from the parsing process:
%%
\begin{code}
  double res = ee . get_value() ;
\end{code}
%%
When an error is produced, an error report explaining what went wrong
can be print out by the class method \METHOD{report\_error}, as
for example in the following piece of source:
%%
\begin{code}
  ee . report_error(cout) ;
\end{code}
%%
The input string to the method \METHOD{parse} can contain
more than one expression. Individual expressions must be
separated by the end-of-statement separator "\verb|;|".
%%
\begin{code}
  err = ee . parse("a=1+sin(3) ; b=1-sin(3) ; sqrt(a*b)") ;
\end{code}
%%
In the case of a multiple expression parsing, the class method
\METHOD{get\_value()} returns only the last evaluated value.
In the previous example this is \verb|a*b|.
%%
Notice also that the assignement symbol "\verb|=|" makes possible the
memorization of intermediate expression values in other variables.

\section{Operators}
%%
The expression evaluator uses a fixed number of operators, that are
listed in order of precedence as follows
%%
\begin{itemize}
    \item[\verb|\#|]
    the rest of the string is a comment (and clearly ignored);

    \item[\verb|+|,\verb|-|]
    binary addition and subtraction, e.g. \verb|10+2; 3-4.2|;

    \item[\verb|*|,\verb|/|]
    binary multiplication and division, e.g. \verb|2.3*4.9; 2/4|;

    \catcode`\^11\relax
    \item[\verb|^|]
    \catcode`\^=7\relax
    power, e.g. \verb|10^4| (results $10000$);

    \item[\verb|+|,\verb|-|]
    unary \verb|+| and \verb|-|, e.g. \verb|+120; 12+-12|;

    \item[\verb|(|,\verb|)|]
    parenthesis are use to change operator precedence; for example
    the expression
    \verb|12-(2-2)| evaluates to \verb|12| while \verb|12-2-2| evaluates
    to \verb|8|;

    \item[\verb|;|]
    expression separator;

    \item[\verb|=|]
    assignement operator.
\end{itemize}

\section{Symbolic Constants}
%%
Two symbolic constants are available whose value is assigned by default:
%%
\begin{center}
  \begin{tabular}{|l|l|}
    \hline
    \verb|e|  & \texttt{2.71828182845904523536} \\
    \verb|pi| & \texttt{3.14159265358979323846} \\
    \hline
  \end{tabular}
\end{center}
%%
They can be used in symbolic expressions like the following one:
%%
\begin{code}
  e + sin(pi*0.5) ;
\end{code}
%%

\section{Predefined Functions}
%%
In the previous section we used the function \verb|sin|. There are a number of
predefined functions which can be used in symbolic expressions. The following
table lists them.
%%
\begin{center}
  \begin{tabular}{|l|l|}
    \hline
    \verb|abs(x)|     &   absolute value of \verb|x| \\
    \verb|pos(x)|     &   positive part of \verb|x| \\
    \verb|neg(x)|     &   negative part of \verb|x| \\
    \verb|cos(x)|     &   cosine of \verb|x| \\
    \verb|sin(x)|     &   sine of \verb|x| \\
    \verb|tan(x)|     &   tangent of \verb|x| \\
    \verb|asin(x)|    &   arcsin of \verb|x| \\
    \verb|acos(x)|    &   arccos of \verb|x| \\
    \verb|atan(x)|    &   arctan of \verb|x| \\
    \verb|cosh(x)|    &   hyperbolic cosine of \verb|x| \\
    \verb|sinh(x)|    &   hyperbolic sine of \verb|x| \\
    \verb|tanh(x)|    &   hyperbolic tangent of \verb|x| \\
    \verb|exp(x)|     &   exponential of \verb|x| \\
    \verb|log(x)|     &   natural logarithm of \verb|x| \\
    \verb|log10(x)|   &   base \NUMBER{10} logarithm of \verb|x| \\
    \verb|sqrt(x)|    &   square root of of \verb|x| \\
    \verb|ceil(x)|    &   least integer over \verb|x| \\
    \verb|floor(x)|   &   great integer under \verb|x| \\
    \hline
    \verb|max(x,y)|   &   maximum of \verb|{x,y}| \\
    \verb|min(x,y)|   &   minimum of \verb|{x,y}| \\
    \verb|atan2(x,y)| &   arctan of \verb|y/x| \\
    \verb|pow(x,y)|   &   power $x^{y}$ \\
    \hline
  \end{tabular}
\end{center}

\section{Defining new functions}
%%
A new function can be introduced into the expression
evaluator by defining it as static and then
passing the evaluator its name and address pointer
by using the two evaluator facilities \METHOD{set\_unary\_fun}
and \METHOD{set\_binary\_fun}.
%%
The following example illustrates the mechanism. Let us first
define the two static functions:
%%
\begin{code}
  static double power2(double const a)
  { return a*a ; }

  static double add(double const a, double const b)
  { return a+b ; }
\end{code}
%%
Then let us add \verb|power2| and \verb|add| to the current
expression evaluator as follows:
%%
\begin{code}
  ee . set_unary_fun("power2",power2) ;
  ee . set_binary_fun("add",add) ;
\end{code}
%%
These new functions can now be invoked in symbolic expressions
as the predefined ones:
%%
\begin{code}
  err = ee . parse("power2(add(2,e))") ;
\end{code}
%%
The expression evaluator is capable of handling only unary and
binary functions, i.e. functions with one or two arguments.

\section{Defining new variables}
%%
New variables can be introduced into the expression evaluator by using
the method \METHOD{set} or the assignement operator.
For example, the following piece of source code defines the new variable
\verb|abc| and initialize it to the value \verb|1/3|
%%
\begin{code}
  err = ee . parse("abc = 1/3") ;
  ee . set("abc",1.0/3.0) ;
\end{code}
%%
The first statements uses the parse method and the assignement operator
\verb|=| of the expression evaluator. The parse method evaluates the
expression on the right of \verb|=| and then assigns the parsing result
to the variable on the right.
%%
If the variable should not exist it would be created and assigned.

The second statement creates -- if needed -- and assigns directly the
variable. Once created and initilized, the variable can be used in
the next operations; for example
%%
\begin{code}
  err = ee . parse("zz = abc*sin(3)/(1+abc)") ;
\end{code}
%%
In this case the new variable \verb|zz| is also created.
A variable is a string which always begins with a letter and may be
followed by any sequence of alphanumeric characters, such as numbers, letters or
the underscore symbols like \verb|_|.

The \METHOD{exist} return true if its argument is a
defined variable, as in
%%
\begin{code}
  bool ex1 = ee . exist("abc") ;
  bool ex2 = ee . exist("pippo") ;
\end{code}
%%
In this case \verb|ex1| is set to true and \verb|ex2| to false.
It is possible to get out the value of a variable,
%%
\begin{code}
  double val1 = ee . get("abc") ;
  double val2 = ee . get("pippo") ;
\end{code}
%%
The value of \verb|val1| is 0.333333 while \verb|val2| is null
because the variable \verb|pippo| does not exist.

\section{Parsing a file}
%%
The expression evaluator can be used to parse a complete
file. The parsing process proceeds by reading the file
one line at a time and parsing it. Use the method
%%
\begin{code}
  ee . parse_file("filename", true) ;
\end{code}
%%
The boolean \verb|true| in the second entry asks the
expression evaluator for proceeding in verbose mode,
that is for printing out on \verb|cerr| input errors
when detected. If the flag was set to \verb|false|,
reading would proceed silently and errors ignored.

For example, consider the following input file:
%%
\begin{code}
# this is a comment line
gamma = 1.4
# set left state
rin = 1 # density
vin = 0 # velocity
pin = 1 # pressure
ein = rin*vin*vin/2+pin/(gamma-1)

# set right state
rout = 0.125
vout = 0
pout = 0.1
eout = rin*vin*vin/2+pout/(gamma-1)
\end{code}
%%
If a program needs as input parameters \verb|rin|, \verb|vin|,
\verb|ein|, \verb|rout|, \verb|vout|, \verb|eout| the following
piece of code
%%
\begin{code}
  ee . parse_file("file.data", true) ;
  double rin  = ee . get("rin") ;
  double vin  = ee . get("vin") ;
  double ein  = ee . get("ein") ;
  double rout = ee . get("rout") ;
  double vout = ee . get("vout") ;
  double eout = ee . get("eout") ;
\end{code}
%%
does the work. The advantages of using expression evaluators in reading
input files are multiples:
%%
\begin{itemize}
    \item a free input format is easily usable;
    \item comments can be added everywhere therein;
    \item simple computations may be inserted as part of an
          input file.
\end{itemize}
%%

\end{document}


% Copyright 2018 by Mark Wibrow
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Free Documentation License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\section{Additional Mathematical Commands}
\label{pgfmath-commands}

Instead of parsing and evaluating complex expressions, you can also use the
mathematical engine to evaluate a single mathematical operation. The macros
used for many of these computations are listed above in
Section~\ref{pgfmath-functions}. \pgfname{} also provides some additional
commands which are shown below:

\subsection{Basic arithmetic functions}
\label{pgfmath-commands-basic}

In addition to the commands described in Section~\ref{pgfmath-functions-basic},
the following command is provided:

\begin{command}{\pgfmathreciprocal\marg{x}}
    Defines |\pgfmathresult| as $1\div\meta{x}$. This provides greatest
    accuracy when \mvar{x} is small.
\end{command}

\subsection{Comparison and logical functions}

In addition to the commands described in
Section~\ref{pgfmath-functions-comparison}, the following command was provided
by Christian Feuers\"anger:

\begin{command}{\pgfmathapproxequalto\marg{x}\marg{y}}
    Defines |\pgfmathresult| 1.0 if $ \rvert \meta{x} - \meta{y} \lvert <
    0.0001$, but 0.0 otherwise. As a side-effect, the global boolean
    |\ifpgfmathcomparison| will be set accordingly.
\end{command}

\subsection{Pseudo-Random Numbers}
\label{pgfmath-random}

In addition to the commands described in
Section~\ref{pgfmath-functions-random}, the following commands are provided:

\begin{command}{\pgfmathgeneratepseudorandomnumber}
    Defines |\pgfmathresult| as a pseudo-random integer between 1 and
    $2^{31}-1$. This uses a linear congruency generator, based on ideas of
    Erich Janka.
\end{command}

\begin{command}{\pgfmathrandominteger\marg{macro}\marg{minimum}\marg{maximum}}
    This defines \meta{macro} as a pseudo-randomly generated integer from the
    range \meta{minimum} to \meta{maximum} (inclusive).
    %
\begin{codeexample}[]
\begin{pgfpicture}
   \foreach \x in {1,...,50}{
      \pgfmathrandominteger{\a}{1}{50}
      \pgfmathrandominteger{\b}{1}{50}
      \pgfpathcircle{\pgfpoint{+\a pt}{+\b pt}}{+2pt}
      \color{blue!40!white}
      \pgfsetstrokecolor{blue!80!black}
      \pgfusepath{stroke, fill}
   }
\end{pgfpicture}
\end{codeexample}
    %
\end{command}

\begin{command}{\pgfmathdeclarerandomlist\marg{list name}{\ttfamily\{}\marg{item-1}\marg{item-2}...{\ttfamily\}}}
    This creates a list of items with the name \meta{list name}.
\end{command}

\begin{command}{\pgfmathrandomitem\marg{macro}\marg{list name}}
    Select an item from a random list \meta{list name}. The
    selected item is placed in \meta{macro}.
\end{command}

\begin{codeexample}[]
\begin{pgfpicture}
   \pgfmathdeclarerandomlist{color}{{red}{blue}{green}{yellow}{white}}
   \foreach \a in {1,...,50}{
      \pgfmathrandominteger{\x}{1}{85}
      \pgfmathrandominteger{\y}{1}{85}
      \pgfmathrandominteger{\r}{5}{10}
      \pgfmathrandomitem{\c}{color}
      \pgfpathcircle{\pgfpoint{+\x pt}{+\y pt}}{+\r pt}
      \color{\c!40!white}
      \pgfsetstrokecolor{\c!80!black}
      \pgfusepath{stroke, fill}
   }
\end{pgfpicture}
\end{codeexample}

\begin{command}{\pgfmathsetseed\marg{integer}}
    Explicitly sets the seed for the pseudo-random number generator. By default
    it is set to the value of |\time|$\times$|\year|.
\end{command}

\subsection{Base Conversion}
\label{pgfmath-bases}

\pgfname{} provides limited support for conversion between
\emph{representations} of numbers. Currently the numbers must be positive
integers in the range $0$ to $2^{31}-1$, and the bases in the range $2$ to
$36$. All digits representing numbers greater than 9 (in base ten), are
alphabetic, but may be upper or lower case.

In addition to the commands described in Section~\ref{pgfmath-functions-base},
the following commands are provided:

\begin{command}{\pgfmathbasetodec\marg{macro}\marg{number}\marg{base}}
    Defines \meta{macro} as the result of converting \meta{number} from base
    \meta{base} to base 10. Alphabetic digits can be upper or lower case.

\medskip{\def\medskip{}

\begin{codeexample}[]
\pgfmathbasetodec\mynumber{107f}{16} \mynumber
\end{codeexample}

    \noindent Note that, as usual in \TeX, the braces around an argument can be
    omitted if the argument is just a single token (a macro name is a single
    token).
    %
\begin{codeexample}[]
\pgfmathbasetodec\mynumber{33FC}{20} \mynumber
\end{codeexample}

}\medskip
    %
\end{command}

\begin{command}{\pgfmathdectobase\marg{macro}\marg{number}\marg{base}}
    Defines \meta{macro} as the result of converting \meta{number} from base 10
    to base \meta{base}. Any resulting alphabetic digits are in \emph{lower
    case}.
    %
\begin{codeexample}[]
\pgfmathdectobase\mynumber{65535}{16} \mynumber
\end{codeexample}
    %
\end{command}

\begin{command}{\pgfmathdectoBase\marg{macro}\marg{number}\marg{base}}
    Defines \meta{macro} as the result of converting \meta{number} from base 10
    to base \meta{base}. Any resulting alphabetic digits are in \emph{upper
    case}.
    %
\begin{codeexample}[]
\pgfmathdectoBase\mynumber{65535}{16} \mynumber
\end{codeexample}
    %
\end{command}

\begin{command}{\pgfmathbasetobase\marg{macro}\marg{number}\marg{base-1}\marg{base-2}}
    Defines \meta{macro} as the result of converting \meta{number} from base
    \meta{base-1} to base \meta{base-2}. Alphabetic digits in \meta{number} can
    be upper or lower case, but any resulting alphabetic digits are in
    \emph{lower case}.
    %
\begin{codeexample}[]
\pgfmathbasetobase\mynumber{11011011}{2}{16} \mynumber
\end{codeexample}
    %
\end{command}

\begin{command}{\pgfmathbasetoBase\marg{macro}\marg{number}\marg{base-1}\marg{base-2}}
    Defines \meta{macro} as the result of converting \meta{number} from base
    \meta{base-1} to base \meta{base-2}. Alphabetic digits in \meta{number} can
    be upper or lower case, but any resulting alphabetic digits are in
    \emph{upper case}.
    %
\begin{codeexample}[]
\pgfmathbasetoBase\mynumber{121212}{3}{12} \mynumber
\end{codeexample}
    %
\end{command}

\begin{command}{\pgfmathsetbasenumberlength\marg{integer}}
    Sets the number of digits in the result of a base conversion to
    \meta{integer}. If the result of a conversion has less digits than this
    number, it is prefixed with zeros.
    %
\begin{codeexample}[]
\pgfmathsetbasenumberlength{8}
\pgfmathdectobase\mynumber{15}{2} \mynumber
\end{codeexample}
    %
\end{command}

\begin{command}{\pgfmathtodigitlist\marg{macro}\marg{number}}
    This command converts \meta{number} into a comma-separated list of digits
    and stores the result in \meta{macro}. The \marg{number} is \emph{not}
    parsed before processing.
    %
\begin{codeexample}[]
\pgfmathsetbasenumberlength{8}
\begin{tikzpicture}[x=0.25cm, y=0.25cm]
  \foreach \n [count=\y] in {0, 60, 102, 102, 126, 102, 102, 102, 0}{
    \pgfmathdectobase{\binary}{\n}{2}
    \pgfmathtodigitlist{\digitlist}{\binary}
    \foreach \digit [count=\x, evaluate={\c=\digit*50+15;}] in \digitlist
      \fill [fill=black!\c] (\x, -\y) rectangle ++(1,1);
  }
\end{tikzpicture}
\end{codeexample}
    %
\end{command}

\subsection{Angle Computations}

Unlike the rest of the math engine, which is a ``standalone'' package, the
following commands only work in conjunction with the core of \pgfname.

\begin{command}{\pgfmathanglebetweenpoints\marg{p}\marg{q}}
    Returns the angle of a line from \meta{p} to \meta{q} relative to a line
    going straight right from \meta{p}.
    %
\begin{codeexample}[]
\pgfmathanglebetweenpoints{\pgfpoint{1cm}{3cm}}{\pgfpoint{2cm}{4cm}}
\pgfmathresult
\end{codeexample}
    %
\end{command}

\begin{command}{\pgfmathanglebetweenlines\marg{$p_1$}\marg{$q_1$}\marg{$p_2$}\marg{$q_2$}}
    Returns the clockwise angle between a line going through $p_1$ and $q_1$
    and a line going through $p_2$ and $q_2$.
    %
\begin{codeexample}[]
\pgfmathanglebetweenlines{\pgfpoint{1cm}{3cm}}{\pgfpoint{2cm}{4cm}}
                         {\pgfpoint{0cm}{1cm}}{\pgfpoint{1cm}{0cm}}
\pgfmathresult
\end{codeexample}
    %
\end{command}


\chapter{Summary of Gulwani and Necula}
\label{chap:chapter3}

Gulwani showed that there is a family of acyclic programs for which
the set of all Herbrand equivalences requires requires an exponential
sized (with respect to the size of the program) value graph
representation - the data structure used by Kildall in his algorithm.
He also showed that Herbrand Equivalences among program sub
expressions can always be represented using linear sized value graph.
This explains the reason for exponential complexity of Kildall's
algorithm which cannot be improved to polynomial and imprecise nature
of existing polynomial time algorithms.

So contrasting to Kildall's algorithm, which finds \textit{all the
Herbrand Equivalent classes} corresponding to constants, variables
and operators occurring in the program, Gulwani's algorithm discovers
\textit{equivalences among program subexpressions} (expressions that
can occur syntactically in a program), in linear time with respect to
parameter $s$, the maximum size of an expression in terms of number
of operators used. For global value numbering, $s$ can be safely
taken to be $N$, the size of the program and hence the algorithm is
linear in the program size.

Also, he proved that the lattice of sets of Herbrand equivalences has
finite height $k$, which is the number of program variables. So, an
abstract interpretation over the lattice of Herbrand equivalences
will terminate in at most $k$ iterations even for cyclic programs.

\section{Brief overview of the algorithm}
The program expressions considered can be represented as
$$e\; ::=\; x\: |\: c\: |\:F(e_1, e_2)$$
Here, $c$ and $x$ are constants and variables occurring in the
program.

The data structure used is called \textit{Strong Equivalence DAG
(SED)}. Each node is of the form $<V,t>$ where $V$ is a set of
program variables and $t$ is either $\perp$ or $c$ for leaf nodes and
$F(n_1, n_2)$ where $n_1$ and $n_2$ are SED nodes for non leaf nodes
(also indicating that the node has two ordered successors). $\perp$
means that the variables in the node have undefined values.

There is a SED associated with each program point and the algorithm
starts with the following initial SED
$$G_0\; =\; \{<x,\perp>\: |\: x \text{ is a program variable}\}$$
Two functions $Join(G_1, G_2, s')$ and $Assignment(G_1, x := e)$ are
used to compute SEDs for other points in the flow graph node
corresponding to the program, as shown in figure
\ref{fig:GulwaniAlgorithm}. $s'$ in the argument of \textit{Join} is
a positive integer, and it returns equivalences between expressions of
size atmost $s'$.

\begin{figure}[!h]
    \centering {
        \setlength{\fboxsep}{8pt}
        \fbox{\includegraphics[scale=0.5]{GulwaniAlgorithm.png}}
    }
    \caption{Computation of SED for flowgraph nodes of a program}
    \label{fig:GulwaniAlgorithm}
\end{figure}

For detailed implementation of \textit{Join} and \textit{Assignment}
and correctness proof of the algorithm, see \cite{Gulwani}.

\section{Complexity of the algorithm}
The complexity of the algorithm is $O(k^{3} * N * j)$, where $k$ is
the total number of program variables, $N$ is the size of the program
and $j$ is the number of join operations in the program. $k$ and $j$
are bounded by $N$, making the whole algorithm polynomial in $N$.


\section{Computation}

The synthesis process in WhetStone is one of \textit{refinement}:
users start out with a high-level specification which can be
implemented in any number of different ways and iteratively reduces
the possible implementations until they have produced a (hopefully
efficient) fully computational implementation.

The \textsf{Comp} data type shown in
Figure~\ref{fig:Comp+Defs}\footnote{This section's core notions of
  computational refinement are found in \textsf{Computation/Core.v}.}
defines the set of computations with three constructors while
Figure~\ref{fig:ComputesTo+Defs} gives the semantics of each
constructor defined by the values it can can produce.

\begin{itemize}
\item \textsf{Return} computes to a singular value \textsf{a}, and is
  thus fully deterministic.
\item\textsf{Pick}, in contrast, represents a nondeterministic
  computation which can compute to \textit{any} value \textsf{a}
  satisfying some predicate \textsf{P} (defined as an
  \textsf{Ensemble}).
\item \textsf{Bind} builds composite computations, computing to any
  value \textsf{b} produced by binding any value \textsf{a} yielded by
  the first computation $\mathsf{c_a}$ in the second computation
  $\mathsf{c_b}$.
\end{itemize}

\begin{figure}[h]
  \begin{tabbedcodeblock}
    Inductive Comp : Type $\rightarrow$ Type := \+\\
    $|$ Return : forall A, A $\rightarrow$ Comp A \\
    $|$ Pick : forall A, Ensemble A $\rightarrow$ Comp A \\
    $|$ Bind : forall A B, Comp A $\rightarrow$ (A $\rightarrow$ Comp B) $\rightarrow$ Comp B.
  \end{tabbedcodeblock}
  \caption{The definition of computations. }
  \label{fig:Comp+Defs}
\end{figure}

\begin{figure}[h]
  \begin{tabular}{cc}
    \begin{minipage}{.5\columnwidth}
      \infrule{}{\mathsf{Comp a} \leadsto \mathsf{a}}
    \end{minipage}
    &
    \begin{minipage}{.5\columnwidth}
      \infrule{\mathsf{P~a}}{\mathsf{Pick P} \leadsto \mathsf{a}}
    \end{minipage}
  \end{tabular}
  \infrule{\mathsf{c_a} \leadsto \mathsf{a} \andalso
    \mathsf{c_b~a} \leadsto \mathsf{b}}
  {\mathsf{Bind~c_a~c_b} \leadsto \mathsf{b}}
  \caption{The semantics of computations. }
  \label{fig:ComputesTo+Defs}
\end{figure}

We can define refinement as a partial order on computations: a
computation $\mathsf{c_a}$ is a refinement of a computation
$\mathsf{c_b}$ iff $\mathsf{c_a}$ computes to a subset of the values
that $\mathsf{c_b}$ computes to:
\begin{align*}
  \mathsf{c_a \subset c_b} & \quad\quad\quad \longleftrightarrow  &
  \mathsf{\forall a, c_a \leadsto a \rightarrow
    c_b \leadsto a}
\end{align*}
\textsf{Comp} obeys the monad laws using both $\leadsto$ and $\subset$
as the notion of equivalence.

The essence of the refinement process is to refine computations by
incrementally replacing the nondeterministic parts with more
deterministic ones. We accomplish this using setoid rewriting, which
extends Coq's rewriting machinery with support relations other than
Leibniz equality\footnote{The
  \href{http://coq.inria.fr/distrib/current/refman/Reference-Manual029.html}{\underline{Coq
      documentation}} has a full explanation of the machinery
  involved.}. In particular, we can use facts about the refinement
relation $\leadsto$ to refine computations. Given a hypothesis
$\mathsf{c_a} \subset \mathsf{c_a'}$, for example, we can use the
\textsf{setoid\_rewrite} tactic to transform the goal
$\mathsf{Bind~c_a~c_b}$ into
$\mathsf{Bind~c_a'~c_b}$. \textsf{Computation/SetoidMorphisms.v}
registers $\leadsto$ as a \textsf{Parametric Relation} and also proves
that a number of different computations are \textsf{Parametric
  Morphism}s which respect this relation, allowing us to refine them
using setoid rewriting.  \textsf{ComputationExamples.v} includes an
example derivation which uses this machinery to refine a computation
which folds a binary operation, \textsf{bin\_op}, over a list.

\subsubsection{Finding the minumum element in a list}


\section{Evolution of dark solitons in a homogeneous 1D Bose gas}

We start our analysis by initializing the density distribution on a spatial grid of length $L = 240$ with $2048$ grid points, containing $2048$ particles.

We took to analytic solution from equation (\ref{eqn:analytic}) at $t=0$ and used our implementation of the Split-Step Fourier method to determine its evolution, using a step size of $\dd t = 0.01$. In total, we computed $N_{\text{steps}} = 800$ time steps. To discuss the results, we included some pictures of different time steps in the following. The animated evolution can be found in the corresponding Python notebook.

\subsection{Single black soliton}
We initialize a black soliton at $z_0 = 0$.
 \begin{figure}[H]
 \centering
 \begin{subfigure}{0.42\textwidth}
 	\includegraphics[width= \textwidth]{figures/single_black_0}
 	\subcaption{Initial state}
 \end{subfigure}
 \begin{subfigure}{0.42\textwidth}
 	\includegraphics[width= \textwidth]{figures/single_black_150}
 	\subcaption{After $N_{\text{steps}} = 150$.}
 \end{subfigure}
 \caption{Dynamics of a single black soliton}
 \end{figure}
 \newpage
\subsection{Single grey soliton}
We initialize a soliton with greyness $\nu = 0.8$ at $z_0 = 0$.
 \begin{figure}[H]
 \centering
 \begin{subfigure}{0.42\textwidth}
 	\includegraphics[width= \textwidth]{figures/single_grey_0}
 	\subcaption{Initial state}
 \end{subfigure}
 \begin{subfigure}{0.42\textwidth}
 	\includegraphics[width= \textwidth]{figures/single_grey_400}
 	\subcaption{After $N_{\text{steps}} = 400$.}
 \end{subfigure}
 \caption{Dynamics of a single grey soliton}
 \end{figure}

\subsection{Two grey solitons moving in opposite directions}
We initialize two solitons with greyness $\nu_1 = \nu_2 = 0.8$ at $z_{1,2} = \pm \ 3.5$.
 \begin{figure}[H]
 \centering
  \begin{subfigure}{0.42\textwidth}
 	\includegraphics[width= \textwidth]{figures/two_grey_3_5_0}
 	\subcaption{Initial state}
 \end{subfigure}
 \begin{subfigure}{0.42\textwidth}
 	\includegraphics[width= \textwidth]{figures/two_grey_3_5_400}
 	\subcaption{After $N_{\text{steps}} = 400$.}
 \end{subfigure}
 \begin{subfigure}{0.42\textwidth}
 	\includegraphics[width= \textwidth]{figures/two_grey_3_5_600}
 	\subcaption{After $N_{\text{steps}} = 600$.}
 \end{subfigure}
 \begin{subfigure}{0.42\textwidth}
 	\includegraphics[width= \textwidth]{figures/two_grey_3_5_800}
 	\subcaption{After $N_{\text{steps}} = 800$.}
 \end{subfigure}

 \caption{Dynamics of two grey solitons. The green line shows the superposition of both curves. It seems that the disturbing oscillations cancel each other out.}
 \end{figure}


\subsubsection{Common}
	This are some common axioms, included in every \spass problem generated.

	Table \ref{table:axioms_common} reports the uses of each axiom when proving each invariant.

	\begin{axiomdescription}[next-error--is--null]
		\label{ax::next_error__is__null}
		\explanation{ The field \fNext of the \fError \cell is the \fNull address.
		}
		\begin{formula}
			\forall \ast \;\; next(error) = null
		\end{formula}
	\end{axiomdescription}

	\begin{table}[hbtp]
		\centering
		\begin{tabular}{c|cccccc}
			axiom & disjoint & locks & nexts & order & preserve & region
			\\\hline
			next-error--is--null & 0 & 1 & 194 & 142 & 0 & 8
			\\
		\end{tabular}
		\label{table:axioms_common}
		\caption{Uses of the common subset of axioms.}
	\end{table}

\subsubsection{Arithmetic}

	This subset of the axioms refers to the arithmetical axioms needed at the proofs.

	Table \ref{table:axiom_arithmetic} reports the uses of each axiom when \spass proves each invariant.

	\begin{axiomdescription}[nums-are-different]
		\label{ax::nums_are_different}
		\explanation{ All numbers are different one another. \footnote{This axiom is necessary because \spass only includes the equality theory. Thus, 0,1,...,55 are 0-ary functions that could potentially be the same number.}
		}
		\begin{formula}
			\forall \ast \;\; (0 \neq 1) \andcond (0 \neq 2) \andcond ... \andcond (1\neq 2) \andcond ... (54 \neq 55)
		\end{formula}
	\end{axiomdescription}

	\begin{table}[hbtp]
		\centering
		\begin{tabular}{c|cccccc}
		axiom & disjoint & locks & nexts & order & preserve & region
		\\\hline
				nums-are-different & 118 & 1 & 109 & 1 & 0 & 44
				\\
		\end{tabular}
		\caption{Uses of the arithmetic subset of axioms.}
		\label{table:axiom_arithmetic}
	\end{table}

\subsubsection{Set theory}

	This set of axioms models some rudiments of set theory. As there are 3 types of sets in \TLLpL, this subset of axioms are replicated for $\Sigma_{\sSetAddr},\Sigma_{\sSetElem}$ and $\Sigma_{\sSetTid}$.

	Table \ref{table:axiom_set} reports the uses of each group of 3 axioms in each invariant.

	\begin{axiomdescription}[union-def]
		\label{ax::union_def}
		\explanation{ Let $x$ be a generic, and $se1,se2$ set of generics. Then $x$ belongs to the union of $se1,se2$ iff $x$ is in $se1$ or $se2$.
		}
		\begin{formula}
			\forall \ast \;\; ((in(x,se) \vee in(x,se2)) \dimplies in(x,union(se,se2)))
		\end{formula}
	\end{axiomdescription}

		\begin{axiomdescription}[set-equal]
		\label{ax::set_equal}
		\explanation{
			Two set are equal iff there not exists a generic that is in one set but not in the other.
			%
			This axiom is called in literature \cite{yellowbook} \concept{set extensionability}.
		}
		\begin{formula}
			\forall \ast \;\; [\nexists \;a\;  (in(a,se2) \dimplies in(a,se1))] \dimplies se1 = se2
		\end{formula}
	\end{axiomdescription}

	\begin{axiomdescription}[union-conmutative]
		\label{ax::union_conmutative}
		\explanation{
			The union of set is a commutative operation.
		}
		\begin{formula}
			\forall \ast \;\; union(se,se2) = union(se2,se)
		\end{formula}
	\end{axiomdescription}

	\begin{axiomdescription}[in-set--def]
		\label{ax::in_set__def}
		\explanation{
			Let $a,b$ be generics and $se$ a set of generics. If $a$ is not in the set but $b$ is in the set, then $a$ and $b$ can not be equal.
		}
		\begin{formula}
			\forall \ast \;\; ((\neg\;  in(a,se)) \implies in(b,se) \implies (\neg\;  b = a))
		\end{formula}
	\end{axiomdescription}

	\begin{axiomdescription}[a--in--singl-a]
		\label{ax::a__in__singl_a}
		\explanation{
			Let $se$ be the singleton set built from the generic element $a$.
			%
			Then, there are no other address different from $a$ in $se$.
			%
			We call $se = \fSingl(a)$.
		}
		\begin{formula}
			\forall \ast \;\; (((\neg\;  a = b) \implies (\neg\;  in(b,\fSingl(a)))) \wedge in(a,\fSingl(a)))
		\end{formula}
	\end{axiomdescription}

	\begin{axiomdescription}[emptySet-is-empty]
		\label{ax::emptySet_is_empty}
		\explanation{
			The generic empty set does not contain any generic.
		}
		\begin{formula}
			\forall \ast \;\; (\neg\;  in(a,empty))
		\end{formula}
	\end{axiomdescription}

	\begin{axiomdescription}[set-exten-inv]
		\label{ax::set_exten_inv}
		\explanation{
			The inverse of set extensionability, described above  (\ref{ax::set_equal}).
		}
		\begin{formula}
			\forall \ast \;\; \left((\forall a\;\; in(a,se1) \dimplies in(a,se2)) \implies se1 = se2\right)
		\end{formula}
	\end{axiomdescription}

	\begin{axiomdescription}[a-not--in-se-dif-a]
		\label{ax::a_not__in_se_dif_a}
		\explanation{
			A generic element is not in the difference of any set with $\fSingl(a)$
		}
		\begin{formula}
			\forall \ast \;\; in(a,se) \implies (\neg\;  in(a,\mathit{diff}(se,\fSingl(a))))
		\end{formula}
	\end{axiomdescription}

	\begin{table}[hbtp]
		\centering
		\begin{tabular}{c|cccccc}
		axiom & disjoint & locks & nexts & order & preserve & region
		\\\hline
				union-def & 0 & 1 & 223 & 0 & 1 & 15
				\\
%				set-equal & 0 & 0 & 0 & 0 & 0 & 0
%				\\
				union-conmutative & 0 & 1 & 2 & 0 & 0 & 1
				\\
%				in-set--def & 0 & 0 & 0 & 0 & 0 & 0
%				\\
				a--in--singl-a & 0 & 1 & 778 & 16 & 0 & 71
				\\
				emptySet-is-empty & 0 & 1 & 139 & 0 & 0 & 2
				\\
				% EXTENSION:
				set-exten-inv & 0 & 1 & 136 & 0 & 0 & 0
				\\
				a-not--in-se-dif-a & 0 & 1 & 47 & 0 & 0 & 12
				\\
		\end{tabular}
		\label{table:axiom_set}
		\caption{Uses of the set subset of axioms.}
	\end{table}

\subsubsection{Memory}

	These set of axioms model $\Sigma_{\mem}$, i.e. the axioms related with the updates of a heap memory \mem.
	%
	Table \ref{table:axiom_upd} reports the uses of each axiom when proving each invariant.

	\begin{axiomdescription}[rd-mem--def]
		\label{ax::rd_mem__def}
		\explanation{
			The \cell returned when reading the position \fNull of any memory $m$ is the \fError \cell.
		}
		\begin{formula}
			\forall \ast \;\; rd(m,null) = error
		\end{formula}
	\end{axiomdescription}

	\begin{axiomdescription}[upd--def--not-null]
		\label{ax::upd__def__not_null}
		\explanation{(Update definition)
			\\
			Let $a$ be an \addr different from \fNull, $m$ a \mem and $c$ a \cell. We call $m2$ the result of the \fUpd statement.
			%
			Then, updating the value of $m$ stored at address $a$ with a \cell $c$ implies that $c$ is the value returned when reading in the resulting memory the stored at $a$.
		}
		\begin{formula}
			\forall \ast \;\; ((\neg\;  a = null) \implies upd(m,a,c) = m2 \implies rd(m2,a) = c)
		\end{formula}
	\end{axiomdescription}

	\begin{axiomdescription}[upd--def--one-at-the-time]
		\label{ax::upd__def__one_at_the_time}
		\explanation{
			Let $a$ be an \addr different from \fNull, $m$ a memory. We call $m2$ the result of the \fUpd statement.
			%
			An \fUpd statement that only modifies the cell at $a$, preserves all other values.
		}
		\begin{formula}
			\forall \ast \;\; (((\neg\;  a = null) \wedge (\neg\;  a = b)) \implies upd(m,a,c) = m2 \implies rd(m,b) = rd(m2,b))
		\end{formula}
	\end{axiomdescription}

	\begin{table}[hbtp]
			\centering
			\begin{tabular}{c|cccccc}
			axiom & disjoint & locks & nexts & order & preserve & region
			\\\hline
					rd-mem--def & 0 & 1 & 194 & 1729 & 1 & 8
					\\
					upd--def--not-null & 0 & 1 & 283 & 1729 & 17 & 6
					\\
					upd--def--one-at-the-time & 0 & 1 & 451 & 1803 & 19 & 10
					\\
			\end{tabular}
		\label{table:axiom_upd}
		\caption{Uses of the subset of update axioms.}
	\end{table}

\subsubsection{Element Arithmetic}

	This set of axiom models $\Sigma_{\elem}$, i.e., the axioms related with the arithmetic of the \elem.
	%
	Table \ref{table:axiom_elemarith} reports the uses of each axiom when proving each invariant.

	\begin{axiomdescription}[less-trans]
		\label{ax::less_trans}
		\explanation{
			Transitivity of the order relation on $\mathsf{elems}$.
		}
		\begin{formula}
			\forall \ast \;\; ((x < y \wedge y < z) \implies x < z)
		\end{formula}
	\end{axiomdescription}

	\begin{axiomdescription}[ls-xy--not-ls-yx]
		\label{ax::ls_xy__not_ls_yx}
		\explanation{
			The order relation $\mathsf{elems}$ is total.
		}
		\begin{formula}
			\forall \ast \;\; (\fLselem(x,y) \dimplies ((\neg\;  x = y) \wedge (\neg\;  \fLselem(y,x))))
		\end{formula}
	\end{axiomdescription}

	\begin{axiomdescription}[lowest--less-than-highest]
		\label{ax::lowest__less_than_highest}
		\explanation{
			The \fLowest is less than the \fHighest (according to the order relation defined among elements).
		}
		\begin{formula}
			\forall \ast \;\; \fLselem(lowestElem,highestElem)
		\end{formula}
	\end{axiomdescription}

	\begin{axiomdescription}[lowestElem--def-tll]
		\label{ax::lowestElem__def_tll}
		\explanation{(Definition of \fLowest)\\
			Any other element is great or equal than the \fLowest.
		}
		\begin{formula}
			\forall \ast \;\; (e = lowestElem \vee lowestElem < e)
		\end{formula}
	\end{axiomdescription}

	\begin{axiomdescription}[highestElem--def-tll]
		\label{ax::highestElem__def_tll}
		\explanation{(Definition of \fHighest)\\
			Any other element is less or equal than the \fHighest.
		}
		\begin{formula}
			\forall \ast \;\; (e = highestElem \vee e < highestElem)
		\end{formula}
	\end{axiomdescription}

	\begin{table}
	        \centering
	        \begin{tabular}{c|cccccc}
	        axiom & disjoint & locks & nexts & order & preserve & region
	        \\\hline
	                less-trans & 0 & 1 & 0 & 1271 & 0 & 0
	                \\
	                ls-xy--not-ls-yx & 0 & 1 & 6 & 1513 & 0 & 0
	                \\
	                lowest--less-than-highest & 0 & 1 & 0 & 1535 & 0 & 0
	                \\
	                lowestElem--def-tll & 0 & 1 & 13 & 1164 & 0 & 0
	                \\
	                highestElem--def-tll & 0 & 1 & 6 & 1554 & 0 & 0
	                \\
	        \end{tabular}
	\label{table:axiom_elemarith}
	\caption{Uses of the subset of the element arithmetic axioms.}
	\end{table}

\subsubsection{Addr2set}

This subset of axioms and the following are specific axioms introduced this thesis.
%
These are  more complex than the previous axioms because they have the substance of the theories of liked list in the heap.

	\begin{axiomdescription}[nextreg]
		\label{ax::nextreg}
		\explanation{
			Let $a$ be an \addr reachable from another \addr $b$.
			%
			If $a$ is different from \fNull, then the node pointed by $a$ is also reachable from $b$.
		}
		\begin{formula}
			\forall \ast \;\; ((in(a,se) \wedge se = addr2set(m,b) \wedge c = next(rd(m,a)) \wedge (\neg\;  a = null))\implies in(c,se))
		\end{formula}
	\end{axiomdescription}

	\begin{axiomdescription}[lock-keeps-addr2set]
		\label{ax::lock_keeps_addr2set}
		\explanation{
			The set of \addr reachable from an \addr $hd$ is preserved after a \fLock statement targeting another (or the same) \addr $a$.
			%
			This is true because a \fLock statement does not change connectivity properties but only the thread using the \addr.
			%
			Even if the \fLock statement targets \fError, the reachable \addr are preserved.
		}
		\begin{formula}
			\begin{array}{r}
			\forall \ast \;\; (hp_p = upd(hp,a,mkcell(data(rd(hp,a)),next(rd(hp,a)),t)))
			\\
			\implies (addr2set(p,hd) = addr2set(hp_p,hd))
			\end{array}
		\end{formula}
	\end{axiomdescription}

	\begin{axiomdescription}[addr2set-null-is-singl-null]
		\label{ax::addr2set_null__is__singl_null}
		\explanation{
			The set of \addr reachable from \fNull is the \sSetAddr with just the \addr \fNull.
			%
			This is true as a consequence of previous axioms, because the \fNext of \fError is \fNull for every memory.
		}
		\begin{formula}
			\forall \ast \;\; addr2set(m,null) = \fSingl(null)
		\end{formula}
	\end{axiomdescription}

	\begin{table}
        \centering
        \begin{tabular}{c|cccccc}
        axiom & disjoint & locks & nexts & order & preserve & region
        \\\hline
                nextreg & 0 & 1 & 112 & 0 & 1 & 68
                \\
                lock-keeps-addr2set & 0 & 0 & 0 & 0 & 17 & 0
                \\
%                addr2set-null-is-singl-null & 0 & 0 & 0 & 0 & 0 & 0
 %               \\
        \end{tabular}
	\label{table:axiom_addr2set}
	\caption{Uses of the subset of axioms related with $\Sigma_{\path}$, i.e., the reachability of the \addr.}
	\end{table}

\subsubsection{Important}

	\begin{axiomdescription}[lock-keeps-heap--data \& lock-keeps-heap--next]
		\label{ax::lock_keeps_heap__data}\label{ax::lock_keeps_heap__next}
		\explanation{
			In the same way a \fLock statement preserves the \sSetAddr reachable from a given \addr, the same principle applies to some other functions apart from \fAddrToSet.
			%
			A \fLock statement does not change the \fData and \fNext values of a \cell.
		}
		\begin{formula}
		\begin{array}{r}
			\forall \ast \;\; (hp_p = upd(hp,a,mkcell(data(rd(hp,a)),next(rd(hp,a)),t)))
			\\
			\implies (data(r(hp,a)) = data(rd(hp_p,a)) \andcond next(r(hp,a)) = next(rd(hp_p,a)))
		\end{array}
		\end{formula}
	\end{axiomdescription}

	\begin{axiomdescription}[addr2set-rec-def]
		\label{ax::addr2set_rec_def}
		\explanation{
			Recursive definition of \fAddrToSet.
			%
			As the \fAddrToSet is used to get the reachable \addr from another \addr $a$, it is to expect that the \fAddrToSet of the \fNext of $a$ would be the same \sSetAddr excluding $a$.
			%
			This definition additionally states that an \addr is reachable from itself.
		}
		\begin{formula}
			\forall \ast \;\; addr2set(m,a) = union(\fSingl(a),addr2set(m,next(rd(m,a))))
		\end{formula}
	\end{axiomdescription}

	\begin{axiomdescription}[addr2set-primim]
		\label{ax::addr2set_primim}
		\explanation{
			This axiom is the base of the recursion in the definition of \fAddrToSet.
		}
		\begin{formula}
			\forall \ast \;\; ((data(rd(hp,hd)) < data(rd(hp,tl)) \wedge next(rd(hp,hd)) = tl \wedge next(r(hp,tl)) = null) \implies addr2set(hp,hd) = union(union({ hd },{ tl }),\fSingl(\fNull)))
		\end{formula}
	\end{axiomdescription}

	\begin{axiomdescription}[not-in-region--not-change-heap-addr]
		\label{ax::not_in_region__not_change_heap_addr}
		\explanation{
			Let $hd$ be an \addr and $hp$ a \mem.
			%
			Then, modifying a \mem in an \addr which is not reachable from $hd$ preserves the \sSetAddr of reachable \addr from $hd$.
		}
		\begin{formula}
			\forall \ast \;\; ((\neg\;  in(a,addr2set(hp,hd))) \implies addr2set(hp,hd) = addr2set(upd(hp,a,c),hd))
		\end{formula}
	\end{axiomdescription}

	\begin{axiomdescription}[insert--keeps-addr2set]
		\label{ax::insert__keeps_addr2set}
		\explanation{
			This axiom allows to \fUpd a \mem preserving the \fAddrToSet.
			%
			This \fUpd correspond to an insertion in the list.
			\\
			Let $hp$ be a \mem. Let $hd$ be an \addr.
			%
			We call \region the set of address reachable from $hd$ as captured by \fAddrToSet.
			%
			Let $prev$ be an \addr reachable from $hd$ (in the \fAddrToSet of $hp,hd$) and $curr,aux$ two other \addr.
			%
			Let the three addresses ($prev,curr,aux$) be different from one another and all of them different from null.
			\\
			If prev points curr and aux points curr, then making prev point to aux has the following effect on \region: aux now is in \region and every reachable address before the \fUpd is still reachable.
		}
		\begin{formula}
			\begin{array}{l}
				\forall \ast \;\; (reg = addr2set(hp,hd) \wedge union(reg,\fSingl(aux) ) = reg_p \wedge \\
				next(rd(hp,prev)) = curr \wedge (\neg\;  prev = curr) \wedge next(rd(hp,aux)) = curr \wedge (\neg\;  aux = null)\wedge \\
				(\neg\;  prev = null) \wedge (\neg\;  curr = null) \wedge
				in(prev,addr2set(hp,hd)) \wedge
				\\ hp_p = upd(hp,prev,mkcell(data(rd(hp,prev)),aux,rd(hp,prev).lockid))) \\
				\;\;\;\;\implies reg_p = addr2set(hp_p,hd)
			\end{array}
		\end{formula}
	\end{axiomdescription}

%%%%%%%%%%%%%%%%%%%%%R
%%%%%%%%%%%%%%%%%%%%%R
%%%%%%%%%%%%%%%%%%%%%R
%%%%%%%%%%%%%%%%%%%%%R
%%%%%%%%%%%%%%%%%%%%%R
%%%%%%%%%%%%%%%%%%%%%R

	\begin{axiomdescription}[remove--keeps-addr2set]
		\label{ax::remove__keeps_addr2set}
		\explanation{
			In a similar way to (\ref{ax::insert__keeps_addr2set}), this axioms allows to \fUpd a \mem preserving the \fAddrToSet, but this time corresponding to a removal in the list.
			\\
			Let $hp$ be a \mem. Let $hd$ be an \addr.
			%
			We call \region the set of addresses reachable from $hd$.
			%
			Let $prev$ be reachable from $hd$ and $curr,aux$ two other \addr,
			%
			such that the three address ($prev,curr,aux$) are different from each other and all of them are not null.
			%
			If prev points to curr, aux points to curr, then making prev point to aux has the following effect in the \region: curr is now not reachable but every \addr reachable before the \fUpd is still reachable.
		}
		\begin{formula}
			\forall \ast \;\; ((next(rd(hp,curr)) = aux \wedge next(rd(hp,prev)) = curr \wedge (\neg\;  aux = next(rd(hp,prev))) \wedge hp_p = upd(hp,prev,mkcell(data(rd(hp,prev)),aux,rd(hp,prev).lockid)) \wedge (\neg\;  aux = null) \wedge in(curr,addr2set(hp,hd)) \wedge in(null,addr2set(hp,hd)) \wedge in(prev,addr2set(hp,hd))) \implies \mathit{diff}(addr2set(hp,hd),\fSingl(curr)) = addr2set(hp_p,hd))
		\end{formula}
	\end{axiomdescription}

	\begin{axiomdescription}[order-primim]
		\label{ax::order_primim}
		\explanation{
			This axiom is the base of the recursion in the definition of \fOrderlist.
			%
			Let $hp$ be a \mem and $hd,tl$ be two \addr.
			%
			If the \elem stored in $hp$ at $hd$ is less than the \elem stored in $hp$ at $tl$ and $hd$ point to $tl$, then the list from $hd$ to $tl$ is ordered.
		}
		\begin{formula}
			\forall \ast \;\; (ls\_elem(data(rd(hp,hd)),data(rd(hp,tl))) \andcond tl = next(rd(hp,hd)) \andcond next(rd(hp,tl)) = \fNull ) \implies orderlist(hp,hd,tl)
		\end{formula}
	\end{axiomdescription}

	\begin{axiomdescription}[insert--keeps-orderlist]
		\label{ax::insert__keeps_orderlist}
		\explanation{
			This axioms allows to update a \mem preserving the \fOrderlist predicate.
			%
			This update preserves the predicate if certain conditions are satisfied.
			\\
			Let $hp$ be a \mem and $hd,tl$ be two \addr which satisfy $\fOrderlist(hp,hd,tl)$; let $tl$ be different from \fNull, but pointing to \fNull. Let $prev,aux,curr$ be \addr with ordered elements, i.e. the \elem stored in $hp$ at $prev$ is less than the one at $aux$, which is less than the one at $curr$. In addition, $curr$ is pointed by $aux$ and $prev$.
			\textbf{Then}, updating $hp$ so that $prev$ points to $aux$ preserve \fOrderlist$(hp',hd,tl)$.
		}
		\begin{formula}
			\forall \ast \;\; ((orderlist(hp,hd,tl) \wedge (\neg\;  tl = null) \wedge next(rd(hp,tl)) = null \wedge data(rd(hp,prev)) < data(rd(hp,aux)) \wedge data(rd(hp,aux)) < data(rd(hp,curr)) \wedge next(rd(hp,aux)) = curr \wedge next(rd(hp,prev)) = curr \wedge hp_p = upd(hp,prev,mkcell(data(rd(hp,prev)),aux,rd(hp,prev).lockid))) \implies orderlist(hp_p,hd,tl))
		\end{formula}
	\end{axiomdescription}

	\begin{axiomdescription}[remove--keeps-orderlist]
		\label{ax::remove__keeps_orderlist}
		\explanation{
			In a similar way to (\ref{ax::insert__keeps_orderlist}), this axiom allows to update a \mem preserving the \fOrderlist predicate, but this update corresponds to a removal in the list.
			%
			This update preserves the predicate if certain conditions are satisfied.
			\\
			Let $hp$ be a \mem and $hd,tl$ be two \addr which satisfy $\fOrderlist(hp,hd,tl)$ and that $tl$ points to \fNull. Let $prev,aux,curr$ satisfy that $aux$ is pointed by $curr$, which is pointed by $prev$. In addition, $curr,prev,aux$ must be reachable from $hd$.
			\textbf{Then}, updating $hp$ so that $hp$ stores at $prev$ the same cell stored at $aux$ is an action that preserves \fOrderlist for the new $hp$ from $hd$ to $tl$.
		}
		\begin{formula}
			\forall \ast \;\; ((aux = next(rd(hp,curr)) \wedge curr = next(rd(hp,prev)) \wedge (\neg\;  aux = null) \wedge null = next(rd(hp,tl)) \wedge (\neg\;  aux = next(rd(hp,prev))) \wedge hp_p = upd(hp,prev,mkcell(data(rd(hp,prev)),aux,rd(hp,prev).lockid)) \wedge in(prev,addr2set(hp,hd)) \wedge in(curr,addr2set(hp,hd)) \wedge in(null,addr2set(hp,hd)) \wedge in(aux,addr2set(hp,hd)) \wedge orderlist(hp,hd,tl)) \implies orderlist(hp_p,hd,tl))
		\end{formula}
	\end{axiomdescription}

	\begin{axiomdescription}[next-is-not-same--if-ordered]
		\label{ax::next_is_not_same__if_ordered}
		\explanation{
			Let $hd,tl$ and $a$ be \addr reachable from $hd$ in the \mem $hp$, with $hp,tl$ and $a$ different from \fNull.
			%
			In addition, let $tl$ point to \fNull.
			\textbf{Then} a can not point to itselt.
		}
		\begin{formula}
			\forall \ast \;\; ((in(a,addr2set(hp,hd)) \wedge in(tl,addr2set(hp,hd)) \wedge (\neg\;  hd = null) \wedge (\neg\;  tl = null) \wedge (\neg\;  a = null) \wedge next(rd(hp,tl)) = null) \implies (\neg\;  next(rd(hp,a)) = a))
		\end{formula}
	\end{axiomdescription}

\begin{table}
        \centering
        \begin{tabular}{c|cccccc}
        axiom & disjoint & locks & nexts & order & preserve & region
        \\\hline
                lock-keeps-heap--data & 0 & 0 & 0 & 98 & 0 & 0
                \\
                lock-keeps-heap--next & 0 & 1 & 2749 & 0 & 0 & 1
                \\
                addr2set-rec-def & 0 & 1 & 63 & 0 & 1 & 4
                \\
                addr2set-primin & 0 & 0 & 0 & 0 & 1 & 0
                \\
                not-in-region--not-change-heap-addr & 0 & 1 & 7 & 16 & 2 & 0
                \\
                insert--keeps-addr2set & 0 & 1 & 52 & 0 & 0 & 53
                \\
                remove--keeps-addr2set & 0 & 1 & 0 & 0 & 0 & 6
                \\
  	            order-primin & 0 & 0 & 0 & 0 & 1 & 0
                \\
                insert--keeps-orderlist & 0 & 1 & 5 & 0 & 0 & 5
                \\
                remove--keeps-orderlist & 0 & 1 & 5 & 0 & 0 & 5
                \\
%                next-injective-if-ordered & 0 & 0 & 0 & 0 & 0 & 0
 %               \\
                next-is-not-same--if-ordered & 0 & 1 & 7 & 0 & 0 & 0
                \\
%                just-tail--points-null & 0 & 0 & 0 & 0 & 0 & 0
 %               \\
        \end{tabular}
\label{table:axiom_important}
\caption{Uses of the important subset of axioms}
\end{table}

	%\vskip 1cm


\section{Conclusion\label{sec:conclusion}}
We have shown that our parallel platform for the simulation of red
blood cell flows is capable of accurately resolved long-time
simulation of red blood cell flows in complex vessel networks. We are
able to achieve realistic cell volume fractions of over 47\%, while avoiding
collisions between cells or with the blood vessel
walls. Incorporating blood vessels into red blood cell
simulations requires solving a
boundary integral equation, for which we use \gmres.
Each \gmres iteration computes a matrix-vector product,
which in turn involves singular quadrature and an \fmm
evaluation; the latter dominates the computation time. To avoid collisions,
we solve a nonlinear complementarity problem in the implicit part of
each time step. This requires repeated assembly of sparse matrices that, in
principle, couple all cells globally. Nevertheless, solving this
complementarity system yields close-to-optimal strong
and weak scaling in our tests.

\iffalse
\section{Acknowledgements}
We would like to thank
Dhairya Malhotra,
Michael Shelley and
Shenglong Wang
for support and various discussions throughout about various aspects of this work.
\fi


\section{Formal Model and Verification Approach}
\label{sec:approach}

We model the Algorand consensus protocol in Coq as an inductive binary relation on global protocol states, and then express key properties as \emph{invariants} that hold for all protocol states that are (transitively) reachable, according to the relation, from some initial state. Ultimately, we state and prove the \emph{asynchronous safety} property of our model in this way.

Our verification approach is similar to that used for the Raft consensus protocol~\cite{Woos2016} and the Toychain blockchain formalization~\cite{Pirlea2018}, but is different from, for example, the approach based on reasoning on Lamport's happens-before relation used to verify the PBFT protocol~\cite{Rahli2018}. We also elide distributed separation logic, which has been used recently for consensus protocol verification in Coq~\cite{Sergey2018}.

As outlined below, our protocol model, properties, and proofs rely heavily on data structures and results from the Mathematical Components project~\cite{MathComp}, and in particular its libraries for finite sets and finite maps~\cite{Cohen2019}. In total, our Coq development contains around 2000 lines of Gallina code for the specification of the model and its properties, and around 4000 lines of proof scripts that build the formal proofs.
%The source files also contain almost 1000 lines of comments that motivate and explain the specifications and lemmas.

%The modeling effort involved primarily:
%\begin{itemize}
%\item Defining all the needed data types and structures, such as message types and records, using the inductive constructions facilitated by the logic underlying Coq. Definitions were designed to utilize various existing infrastructure components, provided as Coq libraries, including most prominently the Mathematical Components (MathComp) library. These definitions specify the structure of the protocol's state.
%\item Defining both: (1) utility functions, such as computing the number of soft-votes seen by a user so far or identifying the proposal with the least credential, and (2) logical propositions asserting, for example, the preconditions for a cert-voting action or whether some event (like cert-voting) had taken place along an execution path. Functions and propositions constitute the basic building blocks using which other more complex (inductive) definitions and statements are formed.
%\item Stating and proving basic structural properties about these definitions to ensure their correctness with respect to their intended behavior, for example, showing that a defined relation is a complete order or that a function that updates user timers preserves the set of users in the system. These properties are crucial for building up other proofs of more elaborate statements. We note that definitions imported from external libraries, such as MathComp, come equipped with many useful properties already proved, which are also heavily used in our model.
%\item Formalizing the argument for safety and proving the safety theorem, which in turn required designing a proof plan and identifying the intermediate results that will need to be shown as proof obligations. This process is iterative, since many intermediate results were deep enough that they required breaking them down into smaller, more manageable pieces. The whole process was guided by the informal proof arguments documented in the protocol description by Algorand[add pointers]. We highlight some of the details of this proof later in the report.
%\end{itemize}

\subsection{Assumptions}

Most formalizations of programs and protocols are parameterized in specific ways, to be valid across a wide range of configuration choices and scenarios that may occur in practice. Our Algorand model is parameterized on a finite set of \emph{user identifiers} (e.g., names of network nodes), and on a finite set of \emph{values} used in message payloads, abstractly representing blocks and block hashes.

\begin{lstlisting}[language=Coq]
Parameters (UserId : finType) (Value : finType).
\end{lstlisting}

Values are assumed to be checkable for validity. We also consider an arbitrary, but totally ordered, datatype of credentials owned by users, and assume there is some way, given a credential, to say whether its owner is a committee member. Finally, we parameterize on delays and Algorand-specific configuration parameters such as number of votes required to move between periods. For example, these real-number parameters represent, respectively, the non-block message delivery delay, the block message delivery day, and the recovery time:
\begin{lstlisting}[language=Coq]
Parameters (lambda : R) (big_lambda : R) (L : R).
\end{lstlisting}

Besides these and other parameters (16 in total), we also express assumptions, most related to our parameters, in the form of axioms. We use four kinds of axioms:
(1) standard axioms from classical logic, (2) axioms about credentials, (3) axioms on limits of message delays, and (4) axioms on the composition of groups (quorums) of users satisfying certain conditions.

We use the first kind of axiom (three in total) to facilitate simpler use of and reasoning about real numbers.
One example of the second kind of axiom (out of two in total), expresses the uniqueness of credentials
across different users:
\begin{lstlisting}[language=Coq]
Axiom credentials_different :
 forall (u u' : UserId) (r r' p p' s s' : nat), u <> u' ->
 credential u r p s <> credential u' r' p' s'.
\end{lstlisting}
In other words, any two distinct user identifiers \lstinline{u} and \lstinline{u'} will have distinct credentials no matter what the round, period and step values are.
The two axioms of the third kind specify how the small message delivery delay, the block message delivery delay, and the recovery time period are all related:
\begin{lstlisting}[language=Coq]
Axiom delays_order : (3 * lambda <= big_lambda < L)%R.
Axiom delays_positive : (lambda > 0)%R.
\end{lstlisting}

As one example of the fourth kind of axiom, the assumption that ``any two large-enough cert-voting committees for a given round-period-step triple must share at least one honest user'', which captures the honest supermajority assumption in Algorand for the cert-voting case, is specified as:
\begin{lstlisting}[language=Coq]
Axiom quorums_c_honest_overlap :
 quorum_honest_overlap_statement tau_c.
\end{lstlisting}
where \lstinline{quorum_honest_overlap_statement} is a definition parameterized by the committee size threshold value \lstinline{tau}:
\begin{lstlisting}[language=Coq]
Definition quorum_honest_overlap_statement (tau : nat) :=
 forall (trace : seq GState) (r p s : nat) (q1 q2:{fset UserId}),
  q1 `<=` committee r p s -> #|` q1 | >= tau ->
  q2 `<=` committee r p s -> #|` q2 | >= tau ->
  exists (honest_voter : UserId),
   honest_voter \in q1 /\ honest_voter \in q2 /\
   honest_during_step (r,p,s) honest_voter trace.
\end{lstlisting}
In other words, if for any two quorums of users, each of size at least \lstinline{tau}, and who are all committee members for the given \lstinline{(r,p,s)} triple, there is an honest user for the step \lstinline{(r,p,s)} who belongs to both quorums. In total, there are six axioms of this kind.

Our axioms either capture statements accepted by mathematicians (1 above) or assumptions made by Algorand designers on the runtime environment (2-4 above).

\subsection{Local and Global State}

We model local (user) state as an inductive datatype that holds information such as the current round and period, as well as blocks and votes seen during the round.

\begin{lstlisting}[language=Coq]
Record UState := mkUState {
  corrupt : bool;
  round : nat;
  period : nat;
  step : nat;
  timer : R;
  deadline : R;
  p_start : R;
  proposals     : nat -> nat -> seq PropRecord;
  stv           : nat -> option Value;
  blocks        : nat -> seq Value;
  softvotes     : nat -> nat -> seq Vote;
  certvotes     : nat -> nat -> seq Vote;
  nextvotes_open: nat -> nat -> nat -> seq UserId;
  nextvotes_val : nat -> nat -> nat -> seq Vote
}.
\end{lstlisting}

We model the global state as an inductive datatype that holds the current time, whether the network is partitioned, current state for all users, messages in transit, and received messages. In particular, the state of users in the global state is represented as a finite map from user identifier to state, and messages in transit as a finite map from user identifier to multisets of pairs of message deadlines and messages.

\begin{lstlisting}[language=Coq]
Record GState := mkGState {
  now : R;
  network_partition : bool;
  users : {fmap UserId -> UState};
  msg_in_transit : {fmap UserId -> {mset R * Msg}};
  msg_history : {mset Msg}
}.
\end{lstlisting}

\subsection{The Global Transition Relation}
The global state transition relation is defined over the \lstinline{GState} type, and denoted \lstinline{g ~~> g'} in Coq when it holds for \lstinline{g} and \lstinline{g'}. We distinguish three kinds of transitions: (a) node-internal transitions, (b) node message delivery transitions, and (c) network transitions.

Examples of the first transition (12 total) include a user proposing a block or a user certifying a block. There are eight transitions of the second form, such as a user delivering a next-vote for a block and advancing its period. The six network transitions include advancing the users' timers, entering and exiting a partition, and adversarial actions such as replaying a message.

%The global state transition relation is denoted \lstinline{g ~~> g'}, where $g$ and $g'$ are global states of the protocol. This relation defines inductively how the protocol's global state transitions into another state in one step. For example, the global state may transition into another by advancing time, having one of its users make an internal transition or by having the adversary partition the network, and so on. Each transition is guarded by certain preconditions that need to be satisfied for the transition to be enabled. Therefore, the statement that \lstinline{g ~~> g'} tells us that the preconditions for one of these global transition cases were enabled and that transition was taken to transform $g$ into $g'$.

To chain global states together, we define a \emph{trace} as a non-empty sequence of global states, where each adjacent pair belongs to the global transition relation, i.e. if state \lstinline{g$_i$} is the $i$th state in the sequence and \lstinline{g$_{i+1}$} is the $(i+1)$th state, then the pair \lstinline{g$_i$} and \lstinline{g$_{i+1}$} belongs to the global transition relation.

By specifying path properties as propositions on traces, we are able to define generically what the property is without having to assume a fully concrete initial state. Any conditions required for the property to hold can be specified as constraints on the states of the trace being considered.

For example, the property that a block was certified in a period is captured by the following proposition:
\begin{lstlisting}[language=Coq]
Definition certified_in_period trace (r p:nat) (v:Value) :=
  exists (certvote_quorum : {fset UserId}),
  certvote_quorum `<=` committee r p 3 /\
  #|` certvote_quorum | >= tau_c /\
  forall (voter : UserId), voter \in certvote_quorum ->
   certvoted_in_path trace voter r p v.
\end{lstlisting}
It states that the proposition holds for a trace if there exists a large-enough quorum of users selected for cert-voting who actually published cert-votes along that trace for the given period (the proposition \lstinline{certvoted_in_path}).


\subsection{Processing as a Complex Number}

The transfer function that a virtual microphone applies to the signal is applied in the time and amplitude domains. This can be represented as a complex number in the form:

\begin{equation}\label{vMicFunction}
m(S) = \Delta{}v + \Delta{}t
\end{equation}

Where $\Delta v$ is the change in amplitude, and $\Delta t$ is the change in time

\subsection{$\Delta{}v$ Calculation}

\input{deltavcalc.tex}

\subsection{$\Delta{}t$ Calculation}

\input{deltatcalc.tex}

\subsection{$M(S)$ Array processing}

It then follows that the complex-number formulation of the function $m(S)$ can be written out:

\begin{equation}
	m(S) = S\left[\left(1 - p_m\right) + p\cos(\theta_{mS})\right] + \hat{t}\frac{d_{\vec{v}}}{343 + \Delta{}c}
\end{equation}

Which is comprised of two components: the adjusted amplitude of $S$, and the time-domain shift of $S$.

The virtual microphone function (\ref{vMicFunction}) can be applied for each element in $M$ to find the effect of the total microphone array:

\begin{equation}
M(S) = \{m_1(S) ... m_n(S)\}
\end{equation}

The elements of $M(S)$ can be apportioned to the mixdown channels following:

\begin{equation}\label{output}
\begin{bmatrix} L(M(S)_n) \\ R(M(S)_n) \end{bmatrix} = gM(S)_n \begin{bmatrix} k_L \\ k_R \end{bmatrix}
\end{equation}

Where $g$ is a scalar constant, and $k_L$ and $k_R$ are related proportionality constants to determine the level of the element $M(S)_n$ within the encoded left and right channels.

\subsubsection{Output implementation}

For purposes of this implementation, $g$ is a scalar value applied per pair (or to the center microphone). The proportionality constants $k$ for the flanks follow a standard sine-cosine panning function. The center microphone uses $k = 1$.

The $g$ scalar is exposed to the user as a value $\alpha$, where $\alpha$ is a number in decibels and $\alpha = [-20,0]$.

Converting $\alpha_m$ to a scalar $g_m$ can be done:

\begin{equation}\label{dbscalarconvert}
g_m = 10^{\frac{\alpha}{20}}
\end{equation}

For the apportionment of the signal to the mixdown channels, the user inputs a value, $\beta$, where $\beta = [0, 1]$. The value for $\beta$ is used to indicate the separation of the virtual microphone pair into their corresponding mixdown channels. Lower values of $\beta$ indicate that both microphones in the pair should increasingly come out of both mixdown channels; whereas higher values indicate more separation into their corresponding channel. The relationship with $k$ can be shown as:

\begin{equation}\label{pairsPanning}
\begin{bmatrix} k_1 \\ k_2 \end{bmatrix} = \begin{bmatrix} \sin{k(\beta)} \\ \cos{k(\beta)} \end{bmatrix} \; | \; k(\beta) = \beta\frac{pi}{4} + \frac{pi}{4}
\end{equation}

Following this, for any virtual microphone pair in $M$, the placement of the encoded sounds within the output mixdown follows:

\begin{equation}\label{centerPanning}
\begin{bmatrix} y(L) \\ y(R) \end{bmatrix} = \begin{bmatrix} \sin{k(\beta)} & \cos{k(\beta)} \\ \cos{k(\beta)} & \sin{k(\beta)} \end{bmatrix} \cdot g\begin{bmatrix} m(S)_L \\ m(S)_R \end{bmatrix}
\end{equation}

While $m(S)_{center}$ is simply:

\begin{equation}
\begin{bmatrix} y(L) \\ y(R) \end{bmatrix} = gm(S)_{c}J_{2,1}
\end{equation}

Thus, the final, encoded output of the processor can be represented as:

\begin{equation}\label{output}
y(M, S) = \sum\limits_{i=1}^{|M|} y(M(S)_i)
\end{equation}

Which, when taken with the relationship to the UI in (\ref{pairsPanning}) and (\ref{centerPanning}), (\ref{output}) can be expanded to:

\begin{equation}
y(M, S) = \begin{bmatrix} y(L)_\text{mains} \\ y(R)_\text{mains} \end{bmatrix} + \begin{bmatrix} y(L)_\text{flanks} \\ y(R)_\text{flanks} \end{bmatrix} + \begin{bmatrix} y(L)_\text{center} \\ y(R)_\text{center} \end{bmatrix}
\end{equation}


\documentclass[12point]{article}

\usepackage{hyperref}

\begin{document}

\section{v2 prototype}

\subsection{Transport}
We model external virus as a concentration that diffuses and can be uptake or exported. We use the standard PhysiCell equations:

\begin{eqnarray}
\frac{\partial \rho }{\partial t} & = &
D \nabla^2 \rho - \lambda \rho +
\sum_{\textrm{cells }i}
\delta( \vec{x} - \vec{x}_i ) \left[
-V_i U_i \rho + E_i
\right]
\end{eqnarray}
where $D$ is the diffusion coefficient, $\lambda$ is the decay and/or removal rate,
$U$ is the cell's uptake rate (see more below), and $E$ is the net export rate (see more below).

We use a PDE like this for viral particles $V$, uncoated virus $U$ (which might be released by dead cells), viral RNA $R$ (might be released by dead cells), viral protein $P$ (might be released by dead cells), and also
release assembled virus (used as a technical assist on viral internalization and export dynamics--all virions in this last equation are immediately transferred to the viral concentration. See below).

\subsection{Internal virus model}
Let's define the following variables: \\

\begin{centering}
\begin{tabular}{rl}
$V$ & virions that have been released from internalized ACE2 receptors in the cell (more below). \\
$U$ & viruses that have been uncoated \\
$R$ & RNA that has been delivered from uncoated virus $U$ \\
$P$ & (full sets) of viral proteins that have been synthesized from RNA $R$ \\
$A$ & assembled virions that are ready for export.
\end{tabular}
\end{centering}
% Let's model just the internal processes, noting that PhysiCell automatically takes care of virus intake (source for $V$) and export (sink for $A$).

Our placeholder model of this is a system of ODEs:
\begin{eqnarray}
\frac{dV}{dt} & = & -r_\textrm{uncoat} V  + \overbrace{ \textrm{Source}_V }^\textrm{from receptor submodel} \\
\frac{dU}{dt} & = & r_\textrm{uncoat} V - r_\textrm{prep} U \\
\frac{dR}{dt} & = & r_\textrm{prep} U - \lambda_R R \\
\frac{dP}{dt} & = & r_\textrm{synth} R - \lambda_P P - r_\textrm{assemble} P \\
\frac{dA}{dt} & = & r_\textrm{assemble} P \underbrace{- E_{A,i} }_{\textrm{automatically done by PhysiCell}}
\end{eqnarray}

\subsubsection{Exocytosis}
Next, we need to figure out net virus export. We use PhysiCell's standard form. If $\rho_A$ is the external concentration of exported (and assembled) viral particles, then:
\begin{eqnarray}
\frac{d\rho_A}{dt} = ... \sum_{\textrm{cells } i} \delta( \vec{x}-\vec{x}_i ) E_{A,i}
\end{eqnarray}
where $\delta$ is the Dirac delta function centered at the cell's position
$\vec{x}_i$, and $E_{A,i}$ is the net export rate (in assembled virions per time). Integrating this,
the rate change in exported assembled virions is

\begin{eqnarray}
\frac{dA_\textrm{external}}{dt} = ... \sum_{\textrm{cells } i} E_{A,i}.
\end{eqnarray}

We use the following constitutive relation:
\begin{eqnarray}
E_A & = & r_\textrm{exo} A.
\end{eqnarray}

As one final note: we want exported $A$ diffuse and be able to infect other cells. We do this with a ``cleanup'' step at each PhysiCell diffuison time step: in each voxel, we move all of $\rho_A$ to $\rho_V$ (the concentration
of viral particles).

\subsection{Receptor binding, endocytosis, and trafficking}
Define: \\

\begin{centering}
\begin{tabular}{rl}
$R_{EU}$ & external unbound ACE2 receptor \\
$R_{EB}$ & external bound ACE2 receptor (bound to virus) \\
$R_{IB}$ & internal bound ACE2 receptor (bound to virus, in an endosome) \\
$R_{IU}$ & internal unbound ACE2 receptor (released virus, on way back to membrane)
\end{tabular}
\end{centering}

External virus binds to $R_{EU}$ to create $R_{EB}$. We assume that only one virus can bind a single ACE2 receptor.
$R_{EB}$ is trafficked inside to become $R_{IB}$. Virus is released from endosomes (when leaving $R_{IB}$) are a
source term for $V$ above.

Let's use this system of ODEs. If $n$ is the number of virions within interactoin distance of the
cell's unbound receptors,
\begin{eqnarray}
\frac{d R_{EU}}{dt} & = &  - r_\textrm{bind} n_V R_{EU} + \textrm{recycle} R_{IU} \\
\frac{d R_{EB}}{dt} & = &   r_\textrm{bind} n_V R_{EU} - r_\textrm{endo} R_{EB}  \\
\frac{d R_{IB}}{dt} & = &   r_\textrm{endo} R_{EB} - r_\textrm{release} R_{IB} \\
\frac{d R_{IU}}{dt} & = & r_\textrm{release} R_{IB} - r_\textrm{recycle} R_{IU}
\end{eqnarray}

Matching the uptake term in the PDE to the binding term, we have
\begin{equation}
r_\textrm{bind} n_V R_{EU} = U_i V_i \rho ,
\end{equation}
and so
\begin{eqnarray}
n_V & \approx & V_i \rho \\
U_i & = & r_\textrm{bind} R_{EU}.
\end{eqnarray}
This gives us a constitutive relation where the uptake rate is modulated by available ACE2 receptors.

Next, note that the release term gives the source rate of internalized virions for the virion model:
\begin{equation}
\textrm{Source}_V  = r_\textrm{release} R_{IB} .
\end{equation}

\subsubsection{Implementation detail}
By setting the uptake rate $U_i = r_\textrm{bind} R_{EU}$, PhysiCell will automatically
remove the correct amount of virions from the diffusing field and deliver them to
internalized virions (in \verb|phenotype.molecular.internalized_total_substrates|).

If this amount is cleared at each time step, then the amount in the internalized variable
represents
\begin{equation}
dR_{EB} = \Delta t r_\textrm{bind} n_V R_{EU} = \Delta t U_i V_i \rho.
\end{equation}
Thus, we call that $dR_{EB}$, deduct it from $R_{EU}$, add it to $R_{EB}$, and then
set the ``internalized substrate'' quantity to zero.

\subsubsection{Very preliminary ballpark parameter estimates}
\href{https://www.nature.com/articles/cr200815#MOESM255}{https://www.nature.com/articles/cr200815\#MOESM255} states about 3 hours to see endocytosed receptors, 13 hours (3 + 10 additional hours) to see few receptors in vessicles, and 14 hours to see recycled receptors.

Based on this, let's say it takes 3 hours to move from $R_{EU}$ to $R_{EB}$ to $R_{IB}$, so that
\begin{equation}
% \frac{ R_{EU}(0) }{ r_\textrm{bind}} + \frac{1}{r_\textrm{endo}} = 180 \textrm{ min}.
\frac{ 1 }{ r_\textrm{bind} R_{EU}(0) } + \frac{1}{r_\textrm{endo}} = 180 \textrm{ min}.
\end{equation}
(We scale the first parameter by initial number of receptors to acount for the fact that this rate holds early when there are many free receptors.)
Supposing that binding is relatively fast compared to endocytosis, let's suppose binding take on the order of 1 minute (for plentiful free receptors), and endocytosis requires on the order of 180 minutes.

Continuing, we need 13-3 = 10 hours = 600 min to transit from $R_{IB}$ to $R_{IU}$, so $r_\textrm{release} = \frac{1}{600}$.

Then, we need and additional 60 minutes to recycle the freed receptor (14 hours from start to finish), so $r_\textrm{recycle} = \frac{1}{60}.$

Since these are rough estimates, let's use only one significant digits:
\begin{eqnarray}
R_{EU}(0) r_\textrm{bind} & = & 1 \textrm{ min}^{-1} \\
r_\textrm{endo} & = & \frac{1}{175} \sim 0.006 \textrm{ min}^{-1} \\
r_\textrm{release} & = & \frac{1}{600} \sim 0.002 \textrm{ min}^{-1} \\
r_\textrm{recycle} & = & \frac{1}{60} \sim 0.02 \textrm{ min}^{-1} \\
\end{eqnarray}
Assuming there are 1000 to 10000 receptors per cell, we will use a default 1000 receptors and set $r_\textrm{bind} = 0.001 $. Because the other estimates are rough, we wil round to nearest order of magnitude. Thus,
\begin{eqnarray}
r_\textrm{bind} & = & 0.001 \textrm{ min}^{-1} \\
r_\textrm{endo} & = & 0.01 \textrm{ min}^{-1} \\
r_\textrm{release} & = & 0.001 \textrm{ min}^{-1} \\
r_\textrm{recycle} & = & 0.01 \textrm{ min}^{-1} \\
\end{eqnarray}

The paper states that viral proteins were expressed by about 18 hours. So, this will help constrain teh viral dynamics parameters.  Supposing it takes about 13 hours to release virion, the process of uncoating, preparing RNA, and synthesizing proteins takes on the order of 18-13 = 5 hours. Let's divide the time evening among these points, so that takes 100 minutes in each step. Then we will for now set
\begin{eqnarray}
r_\textrm{uncoat} & = & 0.01 \textrm{ min}^{-1} \\
r_\textrm{prep} & = & 0.01 \textrm{ min}^{-1} \\
r_\textrm{synth} & = & 0.01 \textrm{ min}^{-1}
\end{eqnarray}
Let us suppose for now that $r_\textrm{assemble} = r_\textrm{exo} = 0.01 \textrm{ min}^{-1}$.

\subsection{Cell apoptotic response (PD)}
We use a fairly standard Hill function: let $e$ be the effect, which we model as increasing with assembled viral particles:
\begin{eqnarray}
e & - & \frac{ A^n  }{ A^n + A_{\frac{1}{2}}^n  }
\end{eqnarray}
where $A_{\frac{1}{2}}$ is the half max, and $n$ is the Hill coefficient.

Then, the cell's apoptosis rate is
\begin{eqnarray}
r_{\textrm{apoptosis}} = \overline{r}_\textrm{max} e.
\end{eqnarray}

At death, some fraction $f$ of the cell's $V$, $U$, $R$, $P$, and $A$ are released into the microenvironment. These can potentially be individually specified.

\subsection{Later}
Use a molecular-scale model of ACE2 to model how the uptake rate changes.

Use a receptor trafficking model to also modulate virion uptake.

Better parameter estimates of viral replication.

Add immune response with more cell types. Cell death can release immunostimulatory factors that bring in macrophages. Those cause more damage and feedback. Connect that to ARDS.

\section{v1 prototype}

\subsection{Diffusion}
We model external virus as a concentration that diffuses and can be uptake or exported. We use the standard PhysiCell equations:

\begin{eqnarray}
\frac{\partial \rho }{\partial t} & = &
D \nabla^2 \rho - \lambda \rho +
\sum_{\textrm{cells }i}
\delta( \vec{x} - \vec{x}_i ) \left[
-V_i U_i \rho + E_i
\right]
\end{eqnarray}
where $D$ is the diffusion coefficient, $\lambda$ is the decay rate, $U$ is the cell's uptake rate, and $E$ is the net export rate (see more below).

We use a PDE like this for viral particles $V$, uncoated virus $U$ (which might be released by dead cells), viral RNA $R$ (might be released by dead cells), viral protein $P$ (might be released by dead cells), and also
release assembled virus (used as a technical assist on viral internalization and export dynamics--all virions in this last equation are immediately transferred to the viral concentration. See below).

\subsection{Internal virus model}
Let's define the following variables:
\begin{enumerate}
\item
$V$ are viruses that are bound to the cell surface and in the process of endocytosis / adsorption.

\item
$U$ are viruses that have been fully endocytoses and coated.

\item
$R$ is RNA that has been delivered from uncoated virus $U$

\item
$P$ are (full sets) of viral proteins that have been synthesized from RNA $R$

\item
$A$ are assembled virions that are ready for export.

\end{enumerate}
Let's model just the internal processes, noting that PhysiCell automatically takes care of virus intake (source for $V$) and export (sink for $A$).

Our first model of this will be a system of ODEs:
\begin{eqnarray}
\frac{dV}{dt} & = & -r_U V \\
\frac{dU}{dt} & = & r_U V - r_P U \\
\frac{dR}{dt} & = & r_P U - \lambda_R R \\
\frac{dP}{dt} & = & r_S R - \lambda_P P - r_A P \\
\frac{dA}{dt} & = & r_A P
\end{eqnarray}

Next, we need to figure out net virus export. We use PhysiCell's standard form. If $\rho_A$ is the external concentration of exported (and assembled) viral particles, then:
\begin{eqnarray}
\frac{d\rho_A}{dt} = ... \sum_{\textrm{cells } i} \delta( \vec{x}-\vec{x}_i ) E_{A,i}
\end{eqnarray}
where $\delta$ is the Dirac delta function centered at the cell's position
$\vec{x}_i$, and $E_{A,i}$ is the net export rate (in assembled virions per time).

We use the following constitutive relation:
\begin{eqnarray}
E_A & = & r_E A.
\end{eqnarray}

As one final note: we want exported $A$ diffuse and be able to infect other cells. We do this with a ``cleanup'' step at each PhysiCell diffuison time step: in each voxel, we move all of $\rho_A$ to $\rho_V$ (the concentration
of viral particles).

\subsection{Cell apoptotic response (PD)}
We use a fairly standard Hill function: let $e$ be the effect, which we model as increasing with assembled viral particles:
\begin{eqnarray}
e & - & \frac{ A^n  }{ A^n + A_{\frac{1}{2}}^n  }
\end{eqnarray}
where $A_{\frac{1}{2}}$ is the half max, and $n$ is the Hill coefficient.

Then, the cell's apoptosis rate is
\begin{eqnarray}
r_{\textrm{apoptosis}} = \overline{r}_\textrm{max} e.
\end{eqnarray}

At death, some fraction $f$ of the cell's $V$, $U$, $R$, $P$, and $A$ are released into the microenvironment. These can potentially be individually specified.

\subsection{Later}
Use a molecular-scale model of ACE2 to model how the uptake rate changes.

Use a receptor trafficking model to also modulate virion uptake.

Better parameter estimates of viral replication.

Add immune response with more cell types. Cell death can release immunostimulatory factors that bring in macrophages. Those cause more damage and feedback. Connect that to ARDS.

\end{document}