text
stringlengths
28
935k
meta
stringlengths
137
139
red_pajama_subset
stringclasses
1 value
\section{Introduction} Evaluating whether a given configuration of a robot manipulator is in a feasible position, such as for motion planning applications, typically involves a collision detector that produces a binary output: in-collision or collision-free \cite{Das2020}. However, it is often far more useful to know the distance to collision in the workspace, as closer proximities may suggest that the robot is more at risk to colliding with an obstacle. This distance to collision is useful in defining robot control rules for safe robot motion in potentially unpredictable, partially observed, or nonstationary environments \cite{Flacco2012}, such as in cases where the robots are working in close proximity with humans \cite{Schiavi2009}. In addition to collision avoidance for robots \cite{Flacco2012}, applications requiring accurate representation of the distance between two objects include contact resolution in simulation (where objects must respond to collisions realistically) \cite{Pan2013} and force feedback in haptic rendering (where forces are generated for a human manipulating a virtual or teleoperated tool) \cite{Lin2003}. \begin{figure}[t] \centering \subfloat[Workspace\label{fig:distWorkspace}] { \includegraphics[width=0.46\linewidth, trim={3cm 2cm 2.2cm 1.5cm}, clip]{images/distExampleWorkspace}} \hfill \subfloat[Distances in C-space\label{fig:distCspace}] { \includegraphics[width=0.51\linewidth, trim={0cm 0cm 0cm 0cm}, clip]{images/distExampleCspace}} \caption{(a) A 2 DOF robot and a square obstacle. (b) A C-space representation where the workspace distance to collision for each configuration is shown. The axes represent each DOF of the robot.} \label{fig:distExample} \end{figure} A robot's distance to collision is typically defined to be the minimum distance between all of the robot's links and all of the workspace obstacles \cite{Flacco2012,Han2019}. Assuming that the $i^{th}$ link of a robot in configuration $\vec{x}$ is represented as ${\mathcal{R}}_i(\vec{x})$ and the $j^{th}$ workspace obstacle is $o_j$, we define $d_{\mathcal{R}}(\cdot)$ as \begin{equation} d_{\mathcal{R}}(\vec{x}) = \min_{i,j}dist({\mathcal{R}}_i(\vec{x}), o_j) \end{equation} where $dist(\cdot, \cdot)$ provides a positive scalar distance between two non-intersecting bodies. When the two bodies are in collision, $dist(\cdot, \cdot)$ provides the penetration depth (the minimum amount intersecting bodies must move to be out of collision \cite{Lin2003}) as a negative value. Fig. \ref{fig:distWorkspace} shows a 2 degrees-of-freedom (DOF) robot with an obstacle, and its corresponding configuration space (or C-space) representation in Fig. \ref{fig:distCspace}. For each point in the C-space, the workspace distance to collision is shown. As with collision detection, distance estimation is a time-consuming operation, with time complexity as high as $\mathcal{O}(m^6n^6)$ for generalized distance calculations, where $m$ and $n$ are the number of vertices in two different bodies \cite{Pan2012}. Furthermore, reliable collision avoidance often requires the extensive use of external sensors \cite{Flacco2012}. The sensors that provide obstacle information, such as cameras or depth sensors, are a source of uncertainty in the distance measurements \cite{Kyriakopoulos1990}, and thus allow us to acquire only noisy evaluations of distance, which we represent as $\tilde{d}_\mathcal{R}(\cdot)$. Accounting for this uncertainty is a necessity in distance estimation, yet few strategies exist that consider these imperfections in distance sensing. As there are many applications that utilize distances, in this work, we seek to create a model to efficiently and accurately estimate $d_{\mathcal{R}}(\cdot)$ while accounting for potential uncertainty in the distance measurements. \subsection{Contributions} In this work, we describe a modeling approach to estimate a robot manipulator's distance to collision given noisy measurements. More specifically, we employ Gaussian process (GP) regression with the forward kinematics (FK) kernel, a similarity function designed for robot manipulators, to estimate $d_{\mathcal{R}}(\vec{x})$. We demonstrate that the GP model with the FK kernel has significantly better modeling accuracy than other comparable regression techniques and show that querying the proposed GP is orders of magnitude faster than the standard geometric approach for distance evaluation. We utilize our proposed technique in trajectory optimization applications and realize a 9 times improvement in optimization time compared to a noise-free geometric approach yet with similar final results. Finally, we show how a hybrid model, which considers the confidence of the model, can switch from GP-based predictions to sensor-based distance estimation in areas of low confidence. \subsection{Related Work} The standard approach to calculating distances involves first using sensors to obtain the locations of obstacles, and then approximating the robot geometry and workspace obstacles to actually compute the distance, which is a considerably expensive process if there are many pairwise checks to perform \cite{Han2019,Safeea2017}. Some techniques attempt to reduce this computational effort through approximate methods, such as by using values from a depth sensor to approximate a distance or by creating a proxy machine learning model using exemplar data. This section describes some geometric, depth perception-based, and machine learning techniques. \subsubsection{Geometric Approaches} A standard approach to calculating distance to collision is to approximate the objects and use a geometric distance method between them. For example, Han et al. \cite{Han2019} estimate $d_\mathcal{R}(\cdot)$ by first representing each link of a robot arm as a cylinder and converting point clouds acquired from a depth camera into multiple small cubes, and then using the GJK algorithm \cite{Gilbert1988} to compute the distances. While their technique can accurately represent distances for a robot and obstacles observed with a depth camera, breaking obstacles into numerous small polyhedra may increase the potential number of pairwise checks that need to be performed, and there is no measure of uncertainty with this approach. \subsubsection{Perception-Based Distance Fields} Flacco et al. create a method to estimate distance to collision for robot manipulators based on depth sensors \cite{Flacco2012}. For any point in the workspace, distance equations are defined using a depth map, which is an image with depth values evaluated for each pixel. The distances are used to create artificial repulsive forces to drive the robot away from obstacles. The authors claim that the distance values computed with their technique are satisfactory for the purpose of collision avoidance but are not to be considered as actual Cartesian distances. This limitation precludes the usage of this technique beyond the purpose of defining repulsive forces. Furthermore, their distance estimation technique has no measure of sensor or model noise. However, as the primary purpose of their technique is to define repulsive forces away from obstacles, the authors take an average over all obstacles' repulsive fields to reduce any potential noise originating from the depth sensor. \subsubsection{Support Vector Machines} Pan et al. use a support vector machine (SVM) to model the collision region in C-space between two bodies. Binary collision checks are performed on random configurations of one object relative to the other to form a decision boundary. By determining the distance between a query configuration and the decision boundary, their SVM model is used to estimate distance. Since there is no closed-form solution for the distance to the boundary for a nonlinear SVM, sequential quadratic programming, a constrained nonlinear optimization technique, is used to find this distance \cite{Pan2013}. As distances in the C-space do not generally equate to distances in the workspace, a different distance metric is used (the displacement distance metric), which involves determining application-specific weighting terms \cite{Pan2013}. Additionally, this approach requires a unique SVM model between each pair of obstacles, which may make applying this technique to robot manipulators or environments with multiple obstacles more computationally expensive. Finally, this technique assumes the state of each object is perfectly known, which means there is no measure of uncertainty in this model. \subsubsection{Neural Networks} RelaxedIK estimates self-collision costs by using line segments to represent the links. Distances between the links are used to approximate the distances. These distance computations are further approximated using a neural network \cite{Rakita2018}. Their method successfully estimates these self-collision costs which enables usage in optimization problems. However, as with many neural network approaches, this technique requires a large amount of labeled data and a significant amount of time to train, precluding this approach from being applied to instances beyond distance to self-collision. ClearanceNet is a promising neural network-based approach to estimate $d_{\mathcal{R}}(\cdot)$. The input to this network is the robot configuration and a parameterized representation of the environment. Their approach achieves over $90\%$ accuracy if the network's output is used to predict the collision status \cite{Kew2019}. Neural networks, however, are of fixed size and complexity, often require a large amount of data to train, and since the locations of the workspace obstacles are parameterized, generalizing the implementation to new types of environments may require a restructuring of this specific neural network implementation. \section{Background} \subsection{Kernel Functions} A kernel function $k:\mathbb{R}^D \times \mathbb{R}^D\rightarrow \mathbb{R}$ is a function that produces a similarity score between two objects, such as $D$-dimensional robot configurations. A kernel function is a fundamental tool for learning-based algorithms including binary classification, probability density estimation, and dimensionality reduction \cite{Hofmann2008}. Kernel functions are often employed in nonparametric models, which are models that make no strong assumptions on the structure of the model and whose complexity scales with the data \cite{Altman1992}, which is desired for modeling distance fields given that many of the environments in which a manipulator is used is nonstationary. A kernel matrix $\vec{K}\in\mathbb{R}^{N\times N}$ can be defined for a set of $N$ points $\mathcal{X}$ where $\vec{K}_{ij} = k(\mathcal{X}_i,\mathcal{X}_j)$. A positive definite kernel is one that yields a positive definite $\vec{K}$. Positive definiteness is an important property because it guarantees nonsingularity for the kernel matrix, represents an implicit mapping to some higher-dimensional feature space according to Mercer's theorem \cite{Minh}, and is a requirement in some machine learning algorithms including Gaussian processes \cite{Rasmussen2006}. There are various positive definite kernel functions, and the one employed in the model should be selected to capture meaningful similarities between the data \cite{BelancheMunoz2013}. Two kernels that we will use in this paper are the Gaussian kernel and the forward kinematics kernel, which are described below. \begin{figure}[!t] \centering \subfloat[Gaussian Kernel\label{fig:gaussianKernel}]{% \includegraphics[width=0.32\linewidth, trim={0 0 0 0}, clip]{images/gaussianKernel}} \hfill \subfloat[FK Kernel\label{fig:fkKernel}]{% \includegraphics[width=0.32\linewidth, trim={0 0 0 0}, clip]{images/fkKernel}} \hfill \subfloat[2 DOF Robot\label{fig:controlPointPlacement}]{% {\includegraphics[width=0.32\linewidth, trim={1cm 1.1cm 1.2cm 0.2cm}, clip]{images/controlPointPlacement}}} \caption[Different levels of confidence of the GP models for $d_{\mathcal{R}}(\cdot)$ being greater than 0 for a 2 DOF robot are shown.]{Visualizations of (a) the Gaussian kernel and (b) the FK kernel for the configuration of the 2 DOF robot specified in (c). The FK kernel is based on the control point locations marked with red circles.} \label{fig:kernelShapes} \end{figure} \subsubsection{Gaussian Kernel} A common positive definite kernel function to use in kernel-based models is the Gaussian kernel $k_G(\vec{x},\vec{x'}) = \exp\left(-\gamma\|\vec{x} - \vec{x'}\|^2\right)$, where $\gamma$ is a parameter dictating the width of the kernel \cite{Rasmussen2006}. Fig. \ref{fig:gaussianKernel} shows a topological visualization of the Gaussian kernel for the 2 DOF robot in Fig. \ref{fig:controlPointPlacement}. The Gaussian kernel is often considered the default kernel to use if there is limited prior knowledge of the underlying structure of the data \cite{Smola1998}. \subsubsection{Forward Kinematics Kernel} The forward kinematics (FK) kernel was designed to compare robot manipulators \cite{Das2020a}. Rather than comparing the joint angles representing the robot configuration directly, the locations of $M$ control points along the arm are compared. This avoids measuring distances directly in joint space, where proximal joint displacement has far greater effect than distal joint displacement to the Cartesian shape of the robot. The FK kernel is defined as $k_{FK}(\vec{x}, \vec{x'}) = \sum_{m=1}^{M}{\left(1+\frac{\gamma}{2}\|FK_m(\vec{x}) - FK_m(\vec{x'})\|^2\right)}^{-2}$, where $FK_m(\vec{x})$ is the location of the $m^{th}$ control point in the workspace for configuration $\vec{x}$ and $\gamma$ is a parameter dictating kernel width. Fig. \ref{fig:fkKernel} shows a topological visualization of the FK kernel for a 2 DOF robot with control points placed at the end of each link. Significant improvement to classification performance was realized with the FK kernel \cite{Das2020a} over other kernels \cite{Das2020,Das2017}, and thus the FK kernel is a worthwhile avenue to explore when creating a model for distance estimation. \subsection{Regression} Regression models can produce a continuous scalar output given a possibly multi-dimensional input. A common perspective of regression analysis is to view the true output as a sum of its input-dependent expected value and some error term, and using the expected value as a predictor of the output for new queries \cite{Fahrmeir2013}. In the context of distance evaluation, we can assume that the measured, sensor-based distance is a sum of the true distance and a noise term: $\tilde{d}_\mathcal{R}(\vec{x}) = d_{\mathcal{R}}(\vec{x}) + \epsilon$, where $\epsilon \sim \mathcal{N}(0,\eta^2)$ and $\eta^2$ is the measurement noise variance. Choosing nonparametric models such as kernel regression and Gaussian processes allow for distance maps to scale to the complexity of the environment and to account for changing environments over time. This is the ideal scenario as many environments a robot must work in are nonstationary and may include other agents. \subsubsection{Kernel Regression} Kernel regression (KR) \cite{Nadaraya1964,Watson1964} is one example of a nonparametric regression technique, where a probability distribution is estimated and used to compute an expected value. A training set of $N$ input samples $\mathcal{X}$ and their corresponding outputs $\vec{y}$ can be used to estimate a probability distribution of the outputs conditioned on the inputs. This probability distribution may then be used to calculate the expected value of query inputs by taking a weighted sum of all training datapoints to predict the output of a query point. The equation for prediction for a single query point $\vec{x}$ is \begin{equation} \mu_{KR}\left(\vec{x}\right) = \frac{\sum_{i=1}^Nk(\mathcal{X}_i,\vec{x})\vec{y}_i}{\sum_{i=1}^Nk(\mathcal{X}_i,\vec{x})} \label{eq:kr} \end{equation} where $k(\cdot, \cdot)$ is some kernel function. KR does not need to learn any weights to estimate the expected value of $d_{\mathcal{R}}(\cdot)$, so a training procedure is not required. KR typically uses a kernel that has equal influence in each direction, such as the Gaussian kernel \cite{Rasmussen2006}. The FK kernel is not a function of the distance between its inputs and changes shape depending on where the kernel is evaluated, so it is not well suited for the KR formulation in Eq. \ref{eq:kr} \subsubsection{Gaussian Process Regression} \label{sec:gp} Gaussian processes (GPs) can be used for regression problems. GPs are nonparametric kernel-based models that fit a Gaussian distribution over the functions that can potentially fit a set of training data \cite{Rasmussen2006}. A GP is completely defined by a mean and covariance (or kernel) function. The prior distribution considers the space of all possible functions that can be defined using a prior mean (which is sometimes, but not always, 0) and a positive definite kernel function $k(\cdot, \cdot)$. A posterior distribution is defined given training data to condition the prior distribution. Assuming that $\mathcal{X}$ is a training dataset, $\vec{y}$ is a vector of corresponding training outputs, the posterior distribution for the regression output $y$ for a query $\vec{x}$ is \begin{equation} \begin{split} P&\left(y|\mathcal{X},\vec{y},\vec{x}\right) = \mathcal{N}\left(k(\vec{x}, \mathcal{X})[k(\mathcal{X}, \mathcal{X}) +\eta^2\vec{I}]^{-1}\vec{y}, \right.\\ &\left. k(\vec{x}, \vec{x}) - k(\vec{x}, \mathcal{X})[k(\mathcal{X}, \mathcal{X}) + \eta^2\vec{I}]^{-1}k(\mathcal{X},\vec{x})\right) \end{split} \label{eq:gpEquation} \end{equation} where $\eta^2$ is the measurement noise variance in the measurements of $\vec{y}$ \cite{Rasmussen2006}. This noise term can either be selected prior to model fitting if it is known or estimated in advance, or it can be treated as a hyperparameter that can be estimated based on the training dataset \cite{Rasmussen2006}. For a single query $\vec x$, the posterior mean according to Eq. \ref{eq:gpEquation}, $\mu(\vec x)$, can serve as the regression output. A benefit of GPs is some measure of confidence may be obtained with the variance of the posterior distribution in Eq. \ref{eq:gpEquation}, represented now as $\sigma^2(\vec x)$. A confidence intervals (CI) is a set of bounds containing the true output with some probability. The bounds of a two-sided CI are $\mu(\vec x) \pm z\,\sigma(\vec x)$, where $z$ corresponds to a number of standard deviations from the mean. $z$ can be selected to contain a certain proportion of the area under a standard Gaussian distribution and may be determined from Gaussian distribution tables \cite{Altman1988} or statistics software. For example, if $z=1.96$, the two-sided CI contains 95\% of the area, which intuitively means the CI has a probability of 95\% of containing the true regression output \cite{Altman1988}. Selecting larger $z$ values to increase the probability of containing the true output will have a tradeoff of looser bounds on the CI The inversion that occurs in Eq. \ref{eq:gpEquation} may be costly for larger training datasets. This issue has been addressed by reduced rank approximations or using subsets of the training dataset \cite{Rasmussen2006}, which are handled by many GP software libraries, and for which robot-specific GP modeling strategies have been proposed \cite{Wilcox2020}. \section{Methods} In this section, we define a model $f : \mathbb{R}^D\rightarrow \mathbb{R}$ that accurately estimates $d_{\mathcal{R}}(\vec{x})$ for a given robot configuration $\vec{x}$ and accounts for potential uncertainty in the estimation. \subsection{Gaussian Process Regression Model Fitting} We propose to fit a GP model to a training set of configurations $\mathcal{X}$ because of a GP's flexibility in modeling arbitrary datasets and its capability in accounting for uncertainty. We further propose the use of the FK kernel in the GP due to the boost in performance this kernel has proven to provide in binary proxy collision checking applications \cite{Das2020a}. Uniformly randomly sampled robot configurations are used as the training set $\mathcal{X}$. Each configuration in the set is labeled with a noisy distance measurement (calculated using the GJK/EPA \cite{Gilbert1988,VandenBergen2001} geometric methods in our implementation), and the labels are stored in vector $\vec{y}$. To simulate noisy, sensor-based measurements, each label in $\vec{y}$ is created by taking a sum of the true distance and Gaussian noise: $\tilde{d}_\mathcal{R}(\vec{x}) = d_{\mathcal{R}}(\vec{x}) + \epsilon$, where $\epsilon \sim \mathcal{N}(0,\eta^2)$. All methods were written in MATLAB. In the implementation of the FK kernel, a control point is placed at the distal end of each link in the manipulator as was done in \cite{Das2020a}. \subsection{Confidence-Based Hybrid Model} \label{sec:hybrid} As described in Section \ref{sec:gp}, two-sided CIs may be defined based on the posterior distribution standard deviation. Similarly, a one-sided CI may be defined, e.g., $[\mu(\vec x) - z\,\sigma(\vec x), \infty)$ is the CI with a lower bound on what the true regression output is for configuration $\vec{x}$ with some degree of confidence. In this case, $z=1.64$ means that there is 95\% probability that the true regression output is greater than $\mu(\vec x) - 1.64\,\sigma(\vec x)$. A one-sided lower-bounded CI may be used when a bound tighter than in the two-sided CI case is desired and an upper bound on the true value is not as important as a lower bound. \begin{figure}[!t] \centering \subfloat[GP (Gaussian)\label{fig:ciRBF}]{% \includegraphics[width=0.49\linewidth, trim={0 0 0 0}, clip]{images/ciRBF}} \hfill \subfloat[GP (FK)\label{fig:ciFK}]{% \includegraphics[width=0.49\linewidth, trim={0 0 0 0}, clip]{images/ciFK}} \caption[Different levels of confidence of the GP models for $d_{\mathcal{R}}(\cdot)$ being greater than 0 for a 2 DOF robot are shown.]{The colored regions represent different levels of confidence of the GP models for $d_{\mathcal{R}}(\cdot)$ being greater than 0 for a 2 DOF robot, where each axis represents one DOF. The ground truth is shown in Fig. \ref{fig:distExample}. The dashed black curve is where $d_{\mathcal{R}}(\cdot)=0$ using GJK. The GPs use (a) the Gaussian kernel and (b) the FK kernel.} \label{fig:ci} \end{figure} In Fig. \ref{fig:ci}, we visualize the levels of confidence for a 2 DOF robot having $d_{\mathcal{R}}(\vec{x})\ge 0$ when using either GP (Gaussian) or GP (FK). The dashed black curve is where $d_{\mathcal{R}}(\vec{x}) = 0$. We can see that the confidence regions for GP (FK) closely align with the C-space obstacle contour, while GP (Gaussian) does not match as closely. In fact, GP (Gaussian) has pockets of inappropriate confidence, such as decreased confidence in the corners of the shown C-space or high confidence at the bottom of the C-space obstacle. On the other hand, GP (FK) does not have these issues and has increasing confidence of $d_{\mathcal{R}}(\vec{x})$ truly being greater than 0 for configurations farther away from the C-space obstacle. GP (FK)'s more appropriate assignment of confidence suggests that we can create a hybrid model that switches distance estimation methods depending on the GP's level of confidence Using the lower-bounded CI, we define a hybrid distance estimation technique that uses the GP mean as the predicted distance in areas with a high confidence of being collision-free and a more expensive method in other areas: \begin{equation} \mu^{(P)}(\vec{x}) = \begin{cases} \mu(\vec{x}), & \text{if }\mu(\vec{x}) - z\,\sigma(\vec{x}) \ge 0 \\ \frac{1}{N_{\tilde{d}}}\sum_{i=1}^{N_{\tilde{d}}}\tilde{d}_\mathcal{R}(\vec{x}), & \text{otherwise} \end{cases} \label{eq:hybrid} \end{equation} where $P$ denotes the desired level of confidence associated with the number of standard deviations $z$ (e.g., $P=95\%$ for $z=1.64$), and $N_{\tilde{d}}$ is the number of samples to collect from $\tilde{d}_\mathcal{R}(\cdot)$ to potentially reduce the effects of sensor noise. The lower bound in Eq. \ref{eq:hybrid} may of course be nonzero if a more conservative model is desired. This hybrid model may be useful when cheaper distance evaluations from the GP may be used when working far from the obstacle, but more meticulous methods may be required when in close proximity with obstacles. \section{Results} We evaluate the performance of our proposed GP-based distance estimation technique against three other approaches: the geometric approach GJK/EPA (ground truth), a GP with a typical Gaussian kernel, and KR. We begin by comparing the accuracy and timing of each technique before applying these techniques to path optimization. In each experiment, a 7 DOF planar robot manipulator is modeled with unit length link and a rectangular link profile, and a polygonal workspace obstacle is randomly placed in the manipulator's reachable workspace. We set the measurement noise to be $\eta = 0.05$ when creating each dataset. To get an idea of the level of this noise, for an obstacle one link length away from the robot (i.e., $d_{\mathcal{R}}(\vec{x}) = 1$), 99\% of the measured values could be anywhere in the range $[0.85,1.15]$. We assume the scale of the robot and environments are arbitrary, so units for any measurements of length are omitted. \subsection{Accuracy and Query Timing} In this section, we evaluate the GP model's performance in terms of its accuracy and computation timing. Metrics that we utilize to evaluate performance include mean squared error (MSE) and model query time. MSE is defined as \begin{equation} MSE = \textstyle \frac{1}{\widehat{N}}\sum_{i=1}^{\widehat{N}}{\left|\widehat{\vec{y}}_i-\mu\left(\widehat{\mathcal{X}}_i\right)\right|^2} \label{eq:mse} \end{equation} where the test set $\widehat{\mathcal{X}}$ has $\widehat{N}$ elements, $\widehat{\vec{y}}$ is the set of true labels for $\widehat{\mathcal{X}}$, and $\mu(\cdot)$ provides the predicted distance using one of the approximation techniques. Note that while each model is trained on noisy distance evaluations (i.e., $\tilde{d}_\mathcal{R}(\cdot)$), we use noise-free distance evaluations (i.e., $d_{\mathcal{R}}(\cdot)$) to obtain $\widehat{\vec{y}}$ when computing the MSE. \begin{figure}[!t] \centering \includegraphics[width=\linewidth, trim={.5cm 0cm 1.4cm 0.1cm}, clip]{images/errorHist7DOF} \caption{Histogram of absolute errors in distance estimation of $d_{\mathcal{R}}(\cdot)$ when using KR and GP models with the Gaussian and FK kernel. Models with a higher proportion of lower error are better.} \label{fig:errorHist} \end{figure} Because the volumes of the in-collision and collision-free regions in the C-space may not be equal, the overall MSE may misrepresent the MSE within each region. Thus, we also evaluate MSE on subsets of the test data for which $\widehat{\vec{y}}$ is either positive (collision-free) or negative (in-collision), which we refer to as true positive MSE (TPMSE) and true negative MSE (TNMSE), respectively. TPMSE and TNMSE are defined as \begin{align} TPMSE = \textstyle \frac{1}{\widehat{N}_+}\sum_{i:\widehat{\vec{y}}_i>0}{\left|\widehat{\vec{y}}_i-\mu\left(\widehat{\mathcal{X}}_i\right)\right|^2} \\ TNMSE = \textstyle \frac{1}{\widehat{N}_-}\sum_{i:\widehat{\vec{y}}_i<0}{\left|\widehat{\vec{y}}_i-\mu\left(\widehat{\mathcal{X}}_i\right)\right|^2} \end{align} where $\widehat{N}_+$ and $\widehat{N}_-$ denote the sizes of the subsets for TPMSE and TNMSE, respectively. Table \ref{table:gp7DOF} shows the performance of the models in terms of MSE and query time of each of the methods. Note that the average distance to collision is 1.7. We can see the MSEs when using the GP method with the FK kernel are significantly lower (i.e., closer to the GJK/EPA ground truth values) than the other two approximation methods. The FK kernel gives a large boost in modeling accuracy compared to the Gaussian kernel, as was expected \cite{Das2020a}, due to the FK kernel's strong relation with locations in the workspace. The KR method performs worse than GP (Gaussian) in terms of MSE, probably because all points in $\mathcal{X}$ have equal importance with the KR method while GPs assign weights to each point. Fig. \ref{fig:errorHist} shows histograms of absolute errors in estimation of $d_{\mathcal{R}}(\cdot)$ for GP (Gaussian), GP (FK), and KR. We can see that GP (FK) has a larger proportion of lower errors compared to the other methods. \begin{table}[!t] \centering \begin{tabular*}{0.95\columnwidth}{lllll} \toprule Method & MSE & TPMSE & TNMSE & Query Time ($\mu$s) \\ \midrule GJK/EPA & --- & --- & --- & 466.9 \\ KR & 0.78 & 0.71 & 2.76 & 10.4 \\ GP (Gaussian) & 0.50 & 0.41 & 2.92 & \textbf{1.8} \\ GP (FK) & \textbf{0.06} & \textbf{0.05} & \textbf{0.12} & 6.7 \\ \bottomrule \end{tabular*} \caption{Performance in terms of MSE and query time for noise-free GJK/EPA, KR, GP (Gaussian), and GP (FK).} \label{table:gp7DOF} \end{table} \begin{figure*}[!b] \centering \subfloat[GJK/EPA]{ \includegraphics[width=0.18\linewidth, trim={0.8cm 1cm 0.6cm .7cm}, clip]{images/Traj7DOFMethodGJK} } \hfill \subfloat[GJK/EPA (Noisy)]{ \includegraphics[width=0.18\linewidth, trim={0.8cm 1cm 0.6cm .7cm}, clip]{"images/Traj7DOFMethodGJKNoisy"} } \hfill \subfloat[KR]{ \includegraphics[width=0.18\linewidth, trim={0.8cm 1cm 0.6cm .7cm}, clip]{"images/Traj7DOFMethodKR_RBF"} } \hfill \subfloat[GP (Gaussian)]{ \includegraphics[width=0.18\linewidth, trim={0.8cm 1cm 0.6cm .7cm}, clip]{"images/Traj7DOFMethodGP_RBF"} } \hfill \subfloat[GP (FK)]{ \includegraphics[width=0.18\linewidth, trim={0.8cm 1cm 0.6cm .7cm}, clip]{"images/Traj7DOFMethodGP_FK"} } \caption[Examples of end effector paths before and after optimization when using GJK, GP with Gaussian kernel, GP with FK kernel, and KR for distance estimation.]{Examples of end effector paths before (black curves) and after (colored curves) optimization of Eq. \ref{eq:trajOptimization} (clearance constraint of 0.2) when using (a) GJK/EPA, (b) GJK/EPA with noise, (c) KR, (d) GP with Gaussian kernel, (e) GP with FK kernel for distance estimation. The configuration along the path with the worst distance to collision and the amount of clearance required from the obstacle are also shown.} \label{fig:gpPaths} \end{figure*} GP (FK) is about 3.7 times slower to query than GP (Gaussian) because the FK kernel involves an extra step of evaluating the forward kinematics of the robot and thus takes longer to evaluate than the Gaussian kernel. Also, while the KR method does not require any training time, its query times are longer because the entire training set is used during querying while only a subset of the training set needed for the GP methods. The GP and KR methods used datasets of size $N = 500$, which took approximately 229 ms to create. The training time for the GP (Gaussian) method is about 2.2 seconds, which is approximately 1 second faster than when using the FK kernel. While GP (FK) is not as fast for training and querying compared to the GP (Gaussian), its MSE is significantly lower. GP (FK) has better modeling performance most likely because the FK kernel has a shape that more appropriately fits the structure of the data, as can be seen by comparing Fig. \ref{fig:fkKernel} to Fig. \ref{fig:distCspace}. Due to the greater accuracy of the GP (FK) model over GP (Gaussian) and KR and the fact that the query time of GP (FK) is still 70 times faster than the ground truth method, GP (FK) is a strong candidate for accurately and efficiently modeling $d_{\mathcal{R}}(\cdot)$. \subsection{Path Optimization with Clearance Constraint} \label{sec:gpOptimizationPerformance} In this section, we utilize the distance estimation techniques described above in a path optimization application. One purpose of path optimization is to minimize a cost, such as path length, while satisfying constraints, such as keeping a certain distance from obstacles, given a motion plan generated by some other method \cite{Schulman2013}. In our experiment, we structure our optimization problem similar to the trajectory optimization formulation in TrajOpt \cite{Schulman2013}. More specifically, the cost is defined as a sum of distances between waypoints under the inequality constraint of distance to collision. In our implementation, we minimize the manipulator's end effector trajectory rather than the C-space trajectory in order to avoid trivial solutions such as rotating the manipulator the other way around an obstacle. In this section, we represent the Cartesian position of the end effector in configuration $\vec{x}$ as $FK_{EE}(\vec{x})$. Our optimization problem to find a sequence of $T$ configurations $\Theta=[\theta_1,\ldots,\theta_T]$ where $\theta_t \in \mathbb{R}^D$ is thus \begin{equation} \begin{aligned} \Theta^* = \argmin_{\Theta} \quad & L\left(\Theta\right)\\ \qquad \text{subject to}\quad & \theta_1 = \theta_{start}, \\ \quad & \theta_T = \theta_{goal}, \\ \quad & \|\theta_{t+1} - \theta_t\| \le \Delta\theta\ \forall t \in [1, \ldots, T-1], \\ \quad & \min_{t\in[1,\ldots,T]}{d_{\mathcal{R}}(\theta_{t})} \ge d_{min} \end{aligned} \label{eq:trajOptimization} \end{equation} where $\Theta^*$ is the optimized motion plan, $L\left(\Theta\right)=\sum_{t=1}^{T-1}\|FK_{EE}(\theta_{t+1}) - FK_{EE}(\theta_t)\|$ is the distance traveled by the end effector when executing motion plan $\Theta$, $\theta_{start}$ and $\theta_{goal}$ are desired start and goal configurations, $\Delta\theta$ prevents large joint changes, and $d_{min}$ is a desired amount of clearance to maintain from a workspace obstacle. $d_{\mathcal{R}}(\theta_t)$ in the constraint is replaced by each model's estimate. \begin{table}[!b] \footnotesize \centering \begin{tabular}{llll} \toprule Method & Optim. Time (s) & $L(\Theta)$ & $\min d_{\mathcal{R}}(\Theta) - d_{min}$ \\ \midrule GJK/EPA & 864.1 & 14.4 & 0.16 \\ GJK/EPA (Noisy) & 240.4 & 16.5 & 0.23 \\ KR & \textbf{29.1} & 26.9 & \textbf{0.29} \\ GP (Gaussian) & 49.2 & 16.1 & -0.12 \\ GP (FK) & 106.8 & \textbf{13.7} & 0.06 \\ \bottomrule \end{tabular} \caption{Average optimization time, end effector path length, and minimum satisfaction of clearance constraint after optimization of Eq. \ref{eq:trajOptimization} (clearance constraint) when using GJK/EPA, GJK/EPA with noise, GP (Gaussian kernel), GP (FK kernel), and KR to estimate $d_{\mathcal{R}}(\cdot)$.} \label{table:gpOpt7DOF} \end{table} The constrained optimization problem solver $\mathrm{fmincon}()$ in MATLAB is used to solve Eq. \ref{eq:trajOptimization}. $\theta_{start}$ and $\theta_{goal}$ are randomized on either side of the obstacle to require obstacle avoidance in the motion plan. The initial motion plan is acquired using a Rapidly-Exploring Random Tree motion planner \cite{LaValle2008}, which is then used as the initial seed for the optimization. $d_{min}$ is set to be 0.2 in these experiments. Table \ref{table:gpOpt7DOF} shows optimization times, optimized path lengths, and the worst satisfaction of the clearance constraint $\min d_{\mathcal{R}}(\Theta)-d_{min}$. Note that $\min d_{\mathcal{R}}(\Theta)-d_{min}$ is positive if the constraint is satisfied. While optimization with GP (Gaussian) and KR is faster than when optimizing with GP (FK), the optimized result is often either in collision or has a long end effector path length. All learning-based methods are significantly faster than GJK/EPA, but using the GP (FK) provides the safest results. Fig. \ref{fig:gpPaths} shows various examples of the optimized paths using the various methods to approximate $d_{\mathcal{R}}(\cdot)$ in Eq. \ref{eq:trajOptimization}, including a case where the noisy distance measurements are used directly. The original unoptimized end effector path is shown as the dotted curve while the optimized paths are the thicker, colored curves. The configuration along each optimized path with the lowest distance to collision (according to GJK) is displayed, and the amount of desired clearance is represented as the dotted box around the workspace obstacle. It is evident that the optimized trajectories when using the GP (FK) is fairly similar to those when using GJK/EPA, while the other methods yield less optimal paths such as ones with collisions or with longer path lengths. \begin{figure*}[t] \centering \subfloat[GJK/EPA]{ {\includegraphics[width=0.18\linewidth, trim={0.7cm 2.2cm 0.4cm 1.9cm}, clip]{images/Traj7DOFMethodGJKNewOpt}} } \hfill \subfloat[GJK/EPA (Noisy)]{ \includegraphics[width=0.18\linewidth, trim={0.7cm 2.2cm 0.4cm 1.9cm}, clip]{"images/Traj7DOFMethodGJKNoisyNewOpt"} } \hfill \subfloat[KR]{ \includegraphics[width=0.18\linewidth, trim={0.7cm 2.2cm 0.4cm 1.9cm}, clip]{"images/Traj7DOFMethodKR_RBFNewOpt"} } \hfill \subfloat[GP (Gaussian)]{ \includegraphics[width=0.18\linewidth, trim={0.7cm 2.2cm 0.4cm 1.9cm}, clip]{"images/Traj7DOFMethodGP_RBFNewOpt"} } \hfill \subfloat[GP (FK)]{ \includegraphics[width=0.18\linewidth, trim={0.7cm 2.2cm 0.4cm 1.9cm}, clip]{"images/Traj7DOFMethodGP_FKNewOpt"} } \caption[Examples of end effector paths before and after optimization when using GJK, GP with Gaussian kernel, GP with FK kernel, and KR for distance estimation.]{Examples of end effector paths before (black curves) and after (colored curves) optimization of Eq. \ref{eq:trajOptimization2} (clearance maximization) when using (a) GJK/EPA, (b) GJK/EPA with noise, (c) KR, (d) GP with Gaussian kernel, (e) GP with FK kernel for distance estimation. The configuration along the path with the worst distance to collision is also shown.} \label{fig:gpPaths2} \end{figure*} \begin{figure*}[!b] \centering \subfloat[Optimized Path\label{fig:hybridModel}]{% {\includegraphics[width=0.48\linewidth, trim={0.6cm 0.6cm 0cm 0.1cm}, clip]{images/hybridModel}}} \hfill \subfloat[Distances\label{fig:hybridDistances}]{% {\includegraphics[width=0.48\linewidth, trim={0cm 0.1cm 1cm 0.6cm}, clip]{images/hybridDistances}}} \caption{(a) The optimized path determined using the hybrid model $\mu^{(95)}_{FK}(\cdot)$ is shown, where the GP's confidence level that the true distance to collision is greater than 0 is represented by the color of the optimized path. The plotted robot configuration marks the point where the hybrid model switches from the GP-based predictions to the sensor-based method. (b) The distances based on the GP model with the FK kernel ($\mu_{FK}(\cdot)$), the hybrid model ($\mu^{(95)}_{FK}(\cdot)$), and the noise-free geometric method $d_{\mathcal{R}}(\cdot)$ for the trajectory $\Theta$ are shown. The shaded region represents the lower-bounded CI for the GP model, and the vertical line shows where the hybrid model switches from GP-based to sensor-based predictions.} \label{fig:hybrid} \end{figure*} \subsection{Path Optimization with Clearance Maximization} In this section, we once again apply the distance estimation techniques to path optimization. However, rather than utilizing the distance to collision as a constraint, we include distance in the objective function to increase a trajectory's clearance. We weight the path length objective function used in Eq. \ref{eq:trajOptimization} with an exponentiated distance, which changes the optimization problem to \begin{equation} \begin{aligned} \Theta^* = \argmin_{\Theta} \quad & C\left(\Theta\right)L\left(\Theta\right)\\ \qquad \text{subject to}\quad & \theta_1 = \theta_{start}, \\ \quad & \theta_T = \theta_{goal}, \\ \quad & \|\theta_{t+1} - \theta_t\| \le \Delta\theta\ \forall t \in [1, \ldots, T-1] \end{aligned} \label{eq:trajOptimization2} \end{equation} where $C\left(\Theta\right) = \exp(-\mind_{\mathcal{R}}(\Theta))$. $d_{\mathcal{R}}(\Theta)$ in $C(\Theta)$ is replaced by each distance method's estimate. The exponentiation makes $C(\Theta)$ large for trajectories causing egregious penetration into an obstacle and small for trajectories with larger clearances. \begin{table}[t] \footnotesize \centering \begin{tabular}{llll} \toprule Method & Optim. Time (s) & $L(\Theta)$ & $\min d_{\mathcal{R}}(\Theta)$ \\ \midrule GJK/EPA & 481.9 & \textbf{4.3} & \textbf{1.73} \\ GJK/EPA (Noisy) & 56.4 & 32.3 & 0.47 \\ KR & 28.7 & 9.3 & 0.03 \\ GP (Gaussian) & \textbf{15.7} & 4.5 & -0.25 \\ GP (FK) & 51.0 & 4.9 & 1.24 \\ \bottomrule \end{tabular} \caption[Results for optimal paths using GJK \cite{Gilbert1988,VandenBergen2001}, GP (Gaussian kernel) \cite{Rasmussen2006}, GP (FK kernel) \cite{Rasmussen2006, Das2020a}, KR \cite{Nadaraya1964,Watson1964} to calculate $d_{\mathcal{R}}(\cdot)$ are presented. We include the average times to achieve the optimized plan, the average final cost, and the average worst distance to collision in each optimized path.]{Average optimization time, end effector path length, and minimum distance to collision after optimization of Eq. \ref{eq:trajOptimization2} (clearance maximization) when using GJK/EPA, GJK/EPA with noise, GP (Gaussian kernel), GP (FK kernel), and KR to estimate $d_{\mathcal{R}}(\cdot)$. \label{table:gpOpt7DOF2} \end{table} Table \ref{table:gpOpt7DOF2} shows average optimization times, path lengths, and minimum distances to collision for each method. GP (FK) has a higher amount of clearance than GP (Gaussian), KR, and noisy GJK/EPA methods, and in fact achieves results closer to the noise-free geometric method both in terms of clearance and path length despite being trained on noisy measurements. The noisy version of GJK/EPA yielded suboptimal solutions with large end effector path lengths and smaller clearances than GP (FK). GP (Gaussian) and KR have shorter optimization times because the optimization solver often quickly converges to an invalid solution (as can be seen from the lower minimum distances to collision). The paths in Fig. \ref{fig:gpPaths2} exemplify these results. \subsection{Confidence-Based Hybrid Model} We apply our proposed hybrid model to a scenario involving a narrow passage, where the manipulator must reach between two nearby obstacles. Inaccuracy in the distance estimation model may inadvertently lead to collision between these obstacles, so the hybrid model's predictions can potentially handle this scenario by switching to the geometric method if the GP model is not confident. Fig. \ref{fig:hybridModel} shows an example optimized trajectory achieved with the hybrid model $\mu^{(95)}_{FK}(\cdot)$. The plotted robot configuration denotes the transition point where the hybrid model switches from GP-based predictions to noisy, sensor-based distance evaluations $\tilde{d}_\mathcal{R}(\cdot)$. We used $N_{\tilde{d}}=5$ evaluations of $\tilde{d}_\mathcal{R}(\cdot)$ per configuration when the hybrid model did not use a GP-based prediction. The colors of the path denote the confidence level of the GP that the true distance to collision is greater than 0, which we determine via MATLAB's $\mathrm{normcdf}()$. We can observe that the GP model is fairly confident when far from the obstacles, but the confidence level rapidly drops when the manipulator needs to move into the narrow passage. Fig. \ref{fig:hybridDistances} shows the GP-based distance estimates $\mu_{FK}(\Theta)$, the hybrid estimates $\mu^{(95)}_{FK}(\Theta)$, and the true distance to collision $d_{\mathcal{R}}(\Theta)$. The shaded region represents the lower-bounded CI for the GP model. We can see that $\mu_{FK}(\Theta)$ deviates from $d_{\mathcal{R}}(\Theta)$ as the distance decreases, but the hybrid model $\mu^{(95)}_{FK}(\Theta)$ manages to produce accurate measurements of distance by switching to the noisy distance measurements when the GP loses confidence. \section{Conclusion} In this paper, we propose a method to create a model for evaluating a robot manipulator's distance to collision. Our approach utilizes GP regression and the FK kernel, a similarity function designed to compare configurations of a robot manipulator. Noisy distance measurements are used to train the models. Querying the GP model with the FK kernel obtained up to 70 times faster distance estimates than the geometric method. The accuracy of this GP model significantly surpassed that of other regression techniques with up to 13 times lower MSE, even when trained on noisy distance values. The GP model with the FK kernel achieved optimized paths 9 times faster but of similar quality as was achieved by a noise-free geometric method. We also introduce a confidence-based hybrid model that uses the GP mean as a predicted distance in areas of high confidence and an averaging method over sensor-based distances in areas of lower confidence. We demonstrate the capability of this technique in a narrow passage environment and realize the hybrid model switches to the sensor-based method as it gets closer to the obstacles. Using GP regression with the FK kernel is thus a promising approach for creating a model for distance evaluation, even when working with noisy measurements. More efficient sampling, online training and updating, and parallelization are left for future work. \bibliographystyle{IEEEtran}
{'timestamp': '2020-06-01T02:06:44', 'yymm': '2005', 'arxiv_id': '2005.14391', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14391'}
arxiv
\section{Introduction} At least 1.5 million preventable adverse drug events (ADE) occur each year in the U.S.~\cite{IoM2006}. Medication errors related to ADEs can occur while writing or filling prescriptions, or even when taking or managing medications~\cite{aronson2009medication}. For example, pharmacists must verify thousands of pills dispensed daily in the pharmacy, a process that is largely manual and prone to error. Chronically-ill and elderly patients often separate pills from their original prescription bottles, which can lead to confusion and misadministration. % Many errors are preventable; however, pills with visually similar characteristics are difficult to identify or distinguish, increasing error potential.% The pill images available for vision-based approaches fall into two categories: reference and consumer images (Figure~\ref{fig:ref_cons_examples}). The reference images are taken with controlled lighting and backgrounds, and with professional equipment. For most of the pills, one image per side (two images per pill type) is available from the National Institutes of Health (NIH) Pillbox dataset~\cite{pillbox}. The consumer images are taken with real-world settings including different lighting, backgrounds, and equipment. Building pill-image datasets, especially for prescription medications, is costly and has additional regulatory obstacles as prescription medications require a clinician's order to be dispensed. A labeled dataset is scarce and even unlabeled images are hard to collect. This setup requires the model to learn representations from very few training examples. Existing benchmarks are either not publicly available or smaller scale, which are not suitable for developing real-world pill identification systems. \begin{figure}[t!] \begin{center} \includegraphics[width=0.8\linewidth]{ref_cons_images-crop.pdf} \end{center} \caption{\textbf{Representative examples of reference images (top row) and corresponding consumer images (bottom row)} Both sides (front and back) of the two pill types (NDC:00093-7180 and NDC:50111-0441, respectively) are shown. } \label{fig:ref_cons_examples} \end{figure} Over the years, deep learning has achieved unprecedented performance on image recognition tasks with efforts from both large-scale labeled datasets~\cite{imagenet,zhou2014learning} and modeling improvements~\cite{ResNet50CVPR2015,krizhevsky2012imagenet,simonyan2014very}; however, fine-grained visual categorization (FGVC) is still a challenging task, which needs to distinguish subtle differences within visually similar categories. FGVC tasks mainly include natural categories (e.g., birds~\cite{van2015building,wah2011caltech}, dogs~\cite{khosla2011novel} and plants~\cite{nilsback2008automated,wegner2016cataloging}) and man-made objects (e.g., cars~\cite{krause20133d,yang2015large} and airplanes~\cite{maji2013fine}). In this work, we target the pill identification task, which is an under-explored FGVC task yet important and frequent in healthcare settings. The distributions of pill shape and color are skewed to certain categories (Figure~\ref{fig:shape_color_heatmap}), highlighting the importance of distinguishing subtle differences such as materials, imprinted text and symbols. The main contribution of this paper is introducing ePillID, a new pill identification benchmark with a real-world low-shot recognition setting. Leveraging two existing NIH datasets, our benchmark is composed of 13k images representing 9804 appearance classes (two sides for 4902 pill types). This is a low-shot fine-grained challenge because (1) for most of the appearance classes there exist only one image and (2) many pills have extremely similar appearances. % Furthermore, we empirically evaluate various approaches with the benchmark to serve as baselines. The baseline models include standard image classification approaches and metric learning based approaches. Finally, we present error analysis to motivate future research directions. \begin{figure}[!t] \centering \includegraphics[width=0.8\linewidth]{pill_shape_color_heatmap-crop.pdf} \caption{\textbf{The distribution of shape and color of pills.} For pills registered with multiple colors, we grouped them as OTHER. The combinations less than $0.1\%$ are omitted.} \label{fig:shape_color_heatmap} \end{figure} \section{Related Work} \paragraph{Image-based Pill Identification:} In 2016, the NIH held a pill image recognition challenge~\cite{yaniv2016national}, and released a dataset composed of 1k pill types. The challenge winner~\cite{zeng2017mobiledeeppill} proposed a deep similarity-based approach~\cite{DeepRankingCVPR2014} and developed a mobile-ready version using knowledge-distillation techniques~\cite{hinton2015distilling}. Following the competition, classification-based approaches were applied, with higher recognition performance reported~\cite{delgado2019fast, szegedy2015going, wong2017development}. Aside from deep neural networks, various approaches with feature engineering have been proposed~\cite{caban2012automatic,cunha2014helpmepills,lee2012pill,neto2018cofordes,wong2017development}. For instance, the Hu moment~\cite{hu1962visual} was applied~\cite{cunha2014helpmepills,lee2012pill}, because of its rotation-invariant properties. Other methods~\cite{chen2013new,suntronsuk2016pill,yu2014pill,yu2015accurate} were proposed to generate imprint features, recognizing the importance of imprints for pill identification. The past methods achieved remarkable success; however, the lack of benchmarks prevents us from developing methods for real-world low-shot settings. Wong \textit{et al.}~\cite{wong2017development} created a 5284-image dataset of 400 pill types with a QR-like board to rectify geometric and color distortions. Yu \textit{et al.}~\cite{yu2014pill} collected 12,500 images of 2500 pill categories. Unfortunately, neither of these datasets are publicly available. \paragraph{Fine-Grained Visual Categorization (FGVC):} In many FGVC datasets~\cite{bossard2014food,beery2019iwildcam,kaur2019foodx,cui2018large}, the number of categories is not extremely large, often less than 200. Recent large-scale datasets ~\cite{imatproduct,fieldguide,van2018inaturalist} offer large numbers of categories with many images (e.g., \num{675170} training images for 5089 categories~\cite{van2018inaturalist}) with challenging long-tailed distributions. Compared to other FGVC benchmarks, the data distribution on the ePillID benchmark imposes a low-shot setting (one image for most of the classes) with a large number of classes (8k appearance classes). Among many algorithms~\cite{yang2018learning,wang2018learning,zheng2019looking} proposed for FGVC tasks, bilinear models~\cite{kong2017low,li2018towards,zheng2019learning} achieved remarkable performances by capturing higher-order interactions between feature channels. B-CNN~\cite{lin2015bilinear} is one of the first approaches, which obtains full bilinear features by calculating outer product at each location of the feature map, followed by a pooling across all locations; however, the full bilinear features can be very high dimensional (e.g., over 250k when the input has 512 channels). Compact Bilinear Pooling (CBP)~\cite{gao2016compact} addresses the dimensionality issue by approximating bilinear features with only a few thousand dimensions, which was shown to outperform B-CNN in few-shot scenarios. Another line of work is metric learning~\cite{qian2015fine,cui2016fine,sun2018multi}, where an embedding space that captures semantic similarities among classes and images is learned. Metric learning has been also successfully used in few- and low-shot settings~\cite{wang2019cvpr,sungflood2018cvpr}, making it suitable for our ePillID benchmark. % \begin{figure}[t!] \begin{center} \includegraphics[width=0.8\linewidth]{ePillID_diagram-crop.pdf} \end{center} \caption{\textbf{The distribution of reference and consumer images on the ePillID benchmark.} The reference images are available for 4902 pill types, while the consumer images are only available for 960 pill types. The dataset includes 9804 reference images (two images, front and back, for each pill type) and 3728 consumer images.} \label{fig:ePillID} \end{figure} \section{ePillID Benchmark} We construct a new pill identification benchmark, ePillID, by leveraging the NIH challenge dataset~\cite{NIHpillcomp} and the NIH Pillbox dataset~\cite{pillbox}. We use the challenge dataset, which offers consumer images, as a base dataset and extend it with the reference images from the Pillbox dataset. In total, the ePillID dataset includes 3728 consumer images for 1920 appearance classes (two sides for 960 pill types) and 9804 reference images (two sides for 4902 pill types). This requires a fine-grained low-shot setup, where models have access to one reference image for all the 9804 appearance classes; however, there only exists a few consumer images for 1920 appearance classes (Figure~\ref{fig:ePillID}). \paragraph{Experimental Setup:} The consumer images are split into 80\% training and 20\% holdout sets in such a way that the pill types are mutually exclusive. The training set is further split on pill types for 4-fold cross-validation. The models have access to reference images for all of the 4902 pill types, but consumer images are unavailable for most pill types during training. To evaluate the performance in situations where both front- and back-sides are available as input, we construct two-sided queries by enumerating all possible consumer image pairs for each pill type. \paragraph{Evaluation Metrics:} For each query, a model calculates an ordered list of pill types with confidence scores. Note that, for the experiments with both sides of a pill, a query consists of a pair of front and back images. We consider Mean Average Precision (MAP) and Global Average Precision (GAP) for the model performance evaluation. % For MAP, the average precision score is calculated separately for each query, and the mean value is calculated. MAP measures the ability to predict the correct pill types given queries. For GAP, all the query and pill-type pairs are treated independently, and the average precision score is calculated globally. GAP measures both the ranking performance and the consistency of the confidence scores i.e.\ the ability to use a common threshold across different queries~\cite{perronnin2009family}. We also calculate MAP@1 and GAP@1, where only the top pill type per query is considered. % \begin{table}[!t] \centering \scalebox{0.65}{ \begin{tabular}{lcccc} \toprule Model & GAP & GAP@1 & MAP & MAP@1 \\ \toprule \multicolumn{5}{c}{\bf{Plain Classification: Both-sides input}} \\ \midrule DenseNet121 & $30.05 \pm 2.04$ & $38.53 \pm 4.42$ & $60.03 \pm 1.05$ & $41.21 \pm 1.89$ \\ DenseNet201 & $33.30 \pm 1.27$ & $42.64 \pm 3.40$ & $64.38 \pm 0.85$ & $46.61 \pm 1.11$ \\ DenseNet161 & $34.78 \pm 2.80$ & $44.47 \pm 4.26$ & $64.87 \pm 2.27$ & $46.85 \pm 2.72$ \\ DenseNet161 B-CNN & $36.35 \pm 1.67$ & $47.08 \pm 2.16$ & $67.07 \pm 1.36$ & $50.84 \pm 2.47$ \\ DenseNet161 BCP & $39.47 \pm 1.90$ & $48.72 \pm 1.92$ & $69.77 \pm 1.01$ & $52.72 \pm 1.42$ \\ \midrule ResNet18 & $24.13 \pm 1.99$ & $33.13 \pm 2.34$ & $54.70 \pm 2.13$ & $35.70 \pm 2.79$ \\ ResNet34 & $29.07 \pm 2.45$ & $38.53 \pm 2.54$ & $58.88 \pm 2.26$ & $40.34 \pm 2.01$ \\ ResNet50 & $35.16 \pm 3.46$ & $45.43 \pm 4.22$ & $65.79 \pm 1.85$ & $48.32 \pm 2.34$ \\ ResNet50 B-CNN & $38.15 \pm 2.73$ & $48.13 \pm 4.17$ & $68.68 \pm 2.23$ & $51.92 \pm 3.23$ \\ ResNet50 CBP & $38.97 \pm 2.74$ & $48.63 \pm 3.94$ & $68.35 \pm 3.08$ & $51.60 \pm 4.24$ \\ ResNet101 & $36.15 \pm 3.21$ & $46.96 \pm 5.29$ & $65.50 \pm 2.95$ & $48.20 \pm 5.02$ \\ ResNet152 & $39.57 \pm 1.23$ & $49.97 \pm 1.58$ & $68.51 \pm 1.09$ & $51.64 \pm 2.31$ \\ ResNet152 B-CNN & $44.75 \pm 2.11$ & $55.14 \pm 3.67$ & $72.65 \pm 1.69$ & $56.75 \pm 2.51$ \\ ResNet152 CBP & $ 41.45 \pm 2.15$ & $52.43 \pm 2.07$ & $69.12 \pm 2.10$ & $52.64 \pm 2.29$ \\ \midrule \multicolumn{5}{c}{\bf{Multi-head Metric Learning: Both-sides input}} \\ \midrule DenseNet121 & $74.04 \pm 2.32$ & $90.15 \pm 2.63$ & $93.42 \pm 0.42$ & $87.58 \pm 0.87$ \\ DenseNet201 & $74.19 \pm 2.08$ & $87.69 \pm 2.58$ & $92.52 \pm 0.91$ & $86.42 \pm 1.56$ \\ DenseNet161 & $76.60 \pm 2.35$ & $88.86 \pm 2.88$ & $93.41 \pm 0.72$ & $87.78 \pm 1.55$ \\ DenseNet161 B-CNN & $75.27 \pm 4.65$ & $88.24 \pm 2.83$ & $93.11 \pm 0.81$ & $87.22 \pm 1.57$ \\ DenseNet161 BCP & $77.15 \pm 2.89$ & $89.11 \pm 2.36$ & $94.03 \pm 1.03$ & $88.98 \pm 1.78$ \\ \midrule ResNet18 & $66.58 \pm 1.91$ & $87.87 \pm 2.86$ & $91.16 \pm 0.75$ & $84.38 \pm 1.36$ \\ ResNet34 & $73.61 \pm 3.17$ & $89.22 \pm 3.35$ & $92.74 \pm 1.95$ & $87.10 \pm 2.96$ \\ ResNet50 & $78.27 \pm 2.35$ & $90.71 \pm 2.55$ & $94.02 \pm 0.66$ & $89.06 \pm 1.05$ \\ ResNet50 B-CNN & $79.95 \pm 1.96$ & $90.26 \pm 1.56$ & $94.59 \pm 0.23$ & $89.66 \pm 0.62$ \\ ResNet50 CBP & $78.44 \pm 1.48$ & $91.36 \pm 2.83$ & $95.27 \pm 0.43$ & $91.01 \pm 0.97$ \\ ResNet101 & $79.83 \pm 2.11$ & $92.23 \pm 1.12$ & $94.99 \pm 0.40$ & $90.65 \pm 0.60$ \\ ResNet152 & $78.63 \pm 2.75$ & $90.54 \pm 1.96$ & $95.71 \pm 0.83$ & $91.93 \pm 1.56$ \\ ResNet152 B-CNN & $80.45 \pm 1.09$ & $89.61 \pm 1.83$ & $95.01 \pm 0.43$ & $90.65 \pm 0.81$ \\ ResNet152 CBP & $81.20 \pm 1.47$ & $91.19 \pm 0.28$ & $95.76 \pm 0.40$ & $92.01 \pm 0.67$ \\ \midrule \multicolumn{5}{c}{\bf{Multi-head Metric Learning: Single-side input}} \\ \midrule ResNet34 & $54.70 \pm 2.58$ & $78.69 \pm 2.37$ & $80.52 \pm 1.76$ & $70.61 \pm 2.11$ \\ ResNet50 & $61.75 \pm 1.40$ & $81.63 \pm 2.15$ & $82.34 \pm 0.79$ & $72.56 \pm 1.35$ \\ ResNet101 & $63.93 \pm 1.71$ & $84.51 \pm 1.68$ & $84.18 \pm 1.23$ & $75.72 \pm 1.48$ \\ ResNet152 & $64.61 \pm 2.45$ & $82.67 \pm 1.17$ & $85.25 \pm 0.91$ & $76.42 \pm 1.54$ \\ \bottomrule \end{tabular} } \caption{\textbf{Recognition results on the ePillID benchmark.} Mean and standard deviations of the holdout metrics from the 4-fold cross-validation are reported in percentages. } \label{tab:results} \end{table} \section{Experiments} \label{sec:experiments} We first introduce our baseline approaches, then present quantitative and qualitative results. \subsection{Baseline Models} We use ResNet~\cite{ResNet50CVPR2015} and DenseNet~\cite{densenet} as base networks pretrained on ImageNet~\cite{imagenet} for initial weights. In addition to the global average pooling layer as features, we evaluate two bilinear methods, B-CNN~\cite{lin2015bilinear} and CBP~\cite{gao2016compact}, applied to the final pooling layer of the base network. For CBP, we use their Tensor Sketch projection with 8192 dimensions, which was suggested for reaching close-to maximum accuracy. We insert a 1x1 convolutional layer before the pooling layer to reduce the dimensionality to 256. \paragraph{Plain Classification:} As a first set of baselines, we train the models with the standard softmax cross-entropy loss. For regularization, we add a dropout layer~\cite{srivastava2014dropout} with probability 0.5 before the final classification layer. We use the appearance classes as target labels during training, and take the max of the softmax scores for calculating pill-type confidence scores. For the two-sides evaluation, the mean confidence score is used for a score between a two-sided input and a pill type. \paragraph{Multi-head Metric Learning:}\label{sec:metric_losses} As another set of baselines, we employ a combination of four losses to learn an embedding space optimized for fine-grained low-shot recognition. The set up is a multi-task training procedure: \begin{equation} L_{final} = \lambda_{SCE} L_{SCE} + \lambda_{\eta} L_{\eta} + \lambda_{\rho} L_{\rho} + \lambda_{\Gamma} L_{\Gamma}, \end{equation} where $L_{SCE}$ indicates softmax cross-entropy, $L_{\eta}$ cosine-softmax loss (ArcFace~\cite{deng2019cvpr}), $L_{\rho}$ triplet loss~\cite{schroff2015cvpr}, and $L_{\Gamma}$ contrastive loss~\cite{chopra2005learning}. The loss weights, $\lambda_{SCE}$, $\lambda_{\eta}$, $\lambda_{\rho}$, and $\lambda_{\Gamma}$ are chosen empirically with a ResNet50 model~(Section~\ref{sec:impl}). In order to compute the loss for every mini-batch, the triplet and contrastive loss requires additional sampling and pairing procedures. We apply online hard-example mining to find informative negatives for the triplets and pairs respectively evaluated by these losses. % The trained model is used for generating embeddings for the query consumer images and all the reference images. We calculate cosine similarities between the query and reference embeddings and use them as confidence scores. \paragraph{Implementation Details:}\label{sec:impl} The images are cropped and resized to $224 \times 224$. Extensive data augmentation is employed to mimic consumer-image-like variations, including rotation and perspective transformation. The Adam optimizer~\cite{adam2014} is used with an initial learning rate of $\num{1e-4}$. The learning rate is halved whenever a plateau in the validation GAP score is detected. The model hyper-parameters are chosen to optimize the average validation GAP score using the 4-fold cross-validation. The loss weights for the metric learning are determined based on the ResNet50 experiment~(Table~\ref{tab:loss_weights}). The training is done with the mini-batch of 48 images in a machine equipped with Intel Xeon E5-2690, 112GB RAM, one NVIDIA Tesla P40, CUDA 8.0 and PyTorch 0.4.1. \begin{table}[t!] \centering \scalebox{0.65}{ \begin{tabular}{ccccc} \toprule Contrastive~($\lambda_{\Gamma}$) & Triplet~($\lambda_{\rho}$) & SCE~($\lambda_{SCE}$) & CSCE~($\lambda_{\eta}$) & Validation GAP \\ \midrule 1.0 & 1.0 & 1.0 & 0.1 & $77.18 \pm 1.90$ \\ 1.0 & 1.0 & 1.0 & 0.3 & $74.07 \pm 2.29$ \\ 1.0 & 1.0 & 1.0 & 0.0 & $75.48 \pm 1.02$ \\ 1.0 & 0.0 & 1.0 & 0.0 & $74.40 \pm 2.93$ \\ 0.0 & 1.0 & 1.0 & 0.0 & $73.89 \pm 2.16$ \\ 1.0 & 1.0 & 0.0 & 0.1 & $71.38 \pm 4.52$ \\ 0.0 & 0.0 & 1.0 & 0.0 & $61.78 \pm 3.24$ \\ \bottomrule \end{tabular} } \caption{\textbf{Validation GAP scores from the corss-validation for comparing the metric-learning loss weights.} The ResNet50 baseline model is used.} \label{tab:loss_weights} \end{table} \subsection{Quantitative Results} In Table~\ref{tab:results}, we report the baseline results on the ePillID benchmark. The plain classification baselines performed much worse than the metric learning baselines, suggesting the difficulty of the low-shot fine-grained setting. The performance differences among the models are consistent with the ImageNet pretraining performance~\cite{bianco2018benchmark}. The multi-head metric leraning models performed remarkably well, achieving over 95\% MAP and 90\% GAP@1. In most of the cases, bilinear pooling methods outperformed the global average pooling counterpart, showing the representation power of the bilinear features. As an ablation study, we report single-side experiment results i.e.\ only one image per query. The ResNet152 metric learning approach achieved over 85\% MAP and 82\% GAP@1; however, the results indicate that both sides are required for accurate identification. \subsection{Qualitative Results} Figure~\ref{fig:qualitative} depicts qualitative comparisons from examples of the ePillID holdout dataset with confidence scores. In (a), the plain classification approaches misclassified, whereas the metric learning approaches identified successfully, even with the challenging lighting and background variations in the query images. In (b), only the metric learning with CBP approach identified correctly, suggesting CBP was effective for capturing the small difference in the imprinted text. For (c) and (d), all the four models failed to identify the correct types. In (c), the consumer images are affected by the lighting variations with the shiny pill material. In (d), the pill types share extremely similar appearances, except the one character difference in the imprinted text. \begin{figure}[!t] \begin{center} \includegraphics[width=0.9\linewidth]{qualitative_vl3-crop.pdf} \end{center} \caption{\textbf{Qualitative results from the ePillID holdout dataset.} For each query, top confidence scores are shown from the four ResNet152 baselines. The reference images of \textbf{correct} and \underline{wrong} pill types are shown with the input consumer images in the left.} \label{fig:qualitative} \end{figure} \section{Conclusion} We introduced ePillID, a low-shot fine-grained benchmark on pill image recognition. To our knowledge, this is the first publicly available benchmark that can be used to develop pill identification systems in a real-world low-shot setting. We empirically evaluated various baseline models with the benchmark. The multi-head metric learning approach performed remarkably well; however, our error analysis suggests that these models still cannot distinguish confusing pill types reliably. In the future, we plan to integrate optical character recognition~(OCR) models. OCR integration has been explored for storefronts and product FGVC tasks~\cite{karaoglu2016words,bai2018integrating} and recent advances in scene text recognition are promising~\cite{karatzas2015icdar,gomez2017icdar2017,liu2018fots}; however, existing OCR models are unlikely to perform reliably on pills as they stand. Challenging differences include low-contrast imprinted text, irregular-shaped layouts, lexicon, and pill materials such as capsules and gels. Finally, we plan to extend the benchmark further with more pill types and images as we collect more data. By releasing this benchmark, we hope to support further research in this under-explored yet important task in healthcare. {\small \bibliographystyle{ieee_fullname}
{'timestamp': '2020-09-09T02:04:58', 'yymm': '2005', 'arxiv_id': '2005.14288', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14288'}
arxiv
\section{Introduction} Human visual attention comes in two forms. One is bottom-up, where prioritization is based solely on processing of the visual input. The other is top-down, where prioritization is based on a myriad of top-down information sources (the object context of a scene, the semantic relationships between objects, etc.~\cite{wolfe2017five,eckstein2011visual,nakayama2011situating}). When your food arrives at a restaurant, among your very first movements of attention will likely be to the fork and knife (\Fref{fig:teaser}), because these objects are important to your goal of having dinner. Goal-directed attention control underlies all the tasks that we {\bf try} to do, thereby making its prediction a vastly more challenging and important problem than predicting the bottom-up control of attention by a visual input. Perhaps the strongest form of top-down attention control is in the definition of a target goal, with visual search being arguably the simplest goal-directed tasks---there is a target goal and the task is to find it. Humans are highly efficient and flexible in the image locations that they choose to fixate while searching for a target-object goal, making the prediction of human search behavior important for both behavioral and computer vision, and in particular for robotic visual systems such as robotic search~\cite{elder2006attentive, narayanan2016perch}. In this paper, we introduce Inverse Reinforcement Learning as a computational model of human attention in visual search. \begin{figure}[t] \centering \includegraphics[width=1.0\linewidth]{images/teaser2.pdf} \vskip -0.1in \caption{{\bf Predicting fixations in a visual search task}. Left: behavioral scanpath shown in yellow. Right: predicted scanpath in green. The search target is the fork, shown in the yellow bounding box. } \label{fig:teaser} \vskip -0.2in \end{figure} \myheading{Gaze prediction in visual search}. The aim of gaze prediction is to predict the patterns of fixations made by people during image viewing. These patterns can be either spatial (fixation density maps) or spatial+temporal (scanpaths). Most fixation-prediction models are in the context of a free-viewing task, where the prioritization of locations for fixation is believed to be controlled by bottom-up saliency. Since the seminal work by \citet{IttiPAMI98}, the use of saliency maps to predict free-viewing fixations has grown into a sizeable literature \cite{borji2013state, kummerer2017understanding, kruthiventi2017deepfix, huang2015salicon, kummerer2014deep, cornia2018predicting,jiang2015salicon,jetley2016end, borji2015salient, masciocchi2009everyone, berg2009free}. However, the predictions of saliency models do not generalize to fixations made in goal-directed attention tasks, such as the search for a target object~\cite{henderson2007visual, koehler2014saliency}. A critical difference between a search task and a free-viewing task is that search fixations are guided towards a target-object goal, whereas in free viewing there are no explicit goals. Target guidance during search was first quantified using simple targets having simple features that were known to the searcher~\cite{wolfe1994guided}. This work was followed by computational models that used images of objects and scenes as inputs~\cite{ehinger2009modelling, zelinsky2008theory, zelinsky2013modeling}, which further expanded to include target spatial relationships~\cite{aydemir2011search} and global scene context~\cite{torralba2006contextual}. Target spatial relationships and scene context are important factors that substantially affect human search efficiency. When searching for objects in scenes, scene context can guide attention to the target. To date, there have been very few deep network models attempting to predict human search fixations \cite{zhang2018finding, adeli2018deep,Wei-etal-NIPS16}. What all of these models have in common, however, is that they use some algorithm, and knowledge about a particular source of information (target features, meaning, context, etc), to prioritize image locations for fixation selection. \myheading{Inverse Reinforcement Learning}. Our approach to search-fixation prediction is exactly the opposite. Rather than using an algorithm to prioritize locations in an image, here we use Inverse Reinforcement Learning (IRL)~\cite{Ng-Russell-ICML00, Abbeel-etal-ICML04,Ziebart-etal-AAAI08,ho2016generative,fu2017learning} to learn sequences of search fixations by treating each as a potential source of reward. IRL, a form of imitation learning, refers to the recovery of an expert's underlying reward function through repeated observation. Most IRL algorithms \cite{Ziebart-etal-AAAI08,fu2017learning,wulfmeier2015maximum} simultaneously learn an optimal policy and the reward function on which the policy is optimized. Although early IRL algorithms \cite{Ng-Russell-ICML00,Ziebart-etal-AAAI08} were often restricted to problems having low-dimensional state spaces, \citet{wulfmeier2015maximum} proposed deep maximum entropy IRL to handle raw image inputs. Recent work~\cite{ho2016generative,fu2017learning} applies adversarial training \cite{Goodfellow-etal-NIPS14} to learn the underlying reward function and the policy, treating each as (part of) the discriminator and the generator in adversarial training, respectively. The discriminator assigns high reward to an expert's behavior and low reward to a non-expert's behavior, where behavior is represented as state-action pairs. The generator/policy is optimized using a reinforcement learning algorithm to get higher reward by behaving more like the expert. In this work, we use the GAIL (generative adversarial imitation learning) algorithm~\cite{ho2016generative}, given its ability to imitate behaviors in complex and high-dimensional environments \cite{ho2016generative}. Using this approach, a unified information-maximization framework is defined for combining diverse sources of information for the purpose of selecting maximally-rewarding locations to fixate, thus increasing both the accuracy and applicability of predicting human search fixations. \begin{table}[] \begin{center} \setlength{\tabcolsep}{2pt} \begin{tabular}{lcrrrr} \toprule Dataset & Search & Image & Class & Subj/img & Fixation\\ \midrule SALICON \cite{jiang2015salicon} & \ding{55} & 10000 & - & 60 & 4600K* \\ POET \cite{papadopoulos2014training} & \ding{55} & 6270 & 10 & 5 & 178K \\ People900 \cite{ehinger2009modelling} & \ding{51} & 912 & 1 & 14 & 55K \\ MCS \cite{zelinsky2019benchmarking} & \ding{51} & 2183 & 2 & 1-4 & 16K \\ PET \cite{gilani2015pet} & \ding{51} & 4135 & 6 & 4 & 30K \\ COCO-Search18 & \ding{51} & 6202 & 18 & 10 & 300K \\ \bottomrule \end{tabular} \vskip -0.1in \caption{{\bf Comparison of fixation datasets}. Previous datasets either did not use a search task, or had very few target-object classes, subjects, or fixations. *: Fixations are approximated by mouse clicks. } \label{table: dataset cmp} \end{center} \vskip -0.3in \end{table} \myheading{Search Fixation Datasets}. Another significant contribution of our work is the introduction of the COCO-Search18 dataset, which is currently the world's largest dataset of images that have been annotated with the gaze fixations made by humans during search. COCO-Search18 is needed because the best models of goal-directed attention will likely be models trained on goal-directed behavior. Using free-viewing as an example, the currently best model of free-viewing fixations is DeepGaze II \cite{kummerer2017understanding}, which is a deep network trained on SALICON \cite{jiang2015salicon}. SALICON is a crowd-sourced dataset consisting of images that were annotated with human mouse clicks indicating attentionally salient image locations. Without SALICON, DeepGaze II and models like it, would not have been possible, and our understanding of free-viewing behavior, widely believed to reflect bottom-up attention control, would be greatly diminished. There is nothing comparable to SALICON for training models of goal-directed attention. Moreover, those suitably large datasets that do exist, each suffer from some weakness that limits their usefulness (\Tref{table: dataset cmp}), with the most common weakness being that the task used to collect the fixation behavior was not visual search (as in \cite{mathe2014actions, papadopoulos2014training}). Other datasets did use a search task, but either had people search for multiple targets simultaneously~\cite{gilani2015pet} or used only one target category (people; \cite{ehinger2009modelling}) or two (microwaves and clocks; \cite{zelinsky2019benchmarking}). All these inadequacies demand a new, larger, and higher-quality dataset of search fixations for model training. We use multiple fixation-based behavioral search metrics to interrogate COCO-Search18, which we attempt to predict using our IRL model and other state-of-the-art methods. \myheading{Contributions}. This study makes several important contributions: \textbf{(1)} We apply Inverse Reinforcement Learning (GAIL) to the problem of predicting fixation scanpaths during visual search, the first time this has been done for a goal-directed attention. \textbf{(2)} In order to apply IRL to scanpath prediction we needed to integrate changes in fixation location with changes in the state representation, a problem that we solved using Dynamic Contextual Beliefs. DCB is a novel state encoder that updates beliefs about peripherally-viewed objects (an object context) based on the movements of a simulated fovea. This is a technical novelty of our method. \textbf{(3)} We introduce COCO-Search18, a large-scale, high-quality dataset of COCO images annotated with the fixations of 10 people searching for 18 target-object categories. COCO-Search18 makes possible the deep network modeling of goal-directed attention. \textbf{(4)} We show through model comparison and with multiple metrics that our IRL model outperforms other state-of-the-art methods in predicting search scanpaths. We also show that the IRL model (i) learns an object's scene context; (ii) generalizes to predict the behavior of new subjects, and (iii) needs less data to achieve good performance compared to other models. \textbf{(5)} Finally, we learned how to quantify a reward function for the fixations in a search task. This will make possible a new wave of experimental investigation that will ultimately result in a better understanding of goal-directed attention. \section{Scanpath Prediction Framework} We propose an IRL framework (Fig.~\ref{fig:irl_pipeline}) to model human visual search behavior. A person performing a visual search task can be considered a goal-directed agent, with their fixations being a sequential decision process of the agent. At each time step, the agent attends to (fixates) a specific location within the image and receives a version of the image that is blurred to approximate the human viewer's visual state, what we call a retina-transformed image. This is an image that has high-resolution (non-blurred) information surrounding the attended location, and lower-resolution information outside of this central simulated fovea~\cite{perry2002gaze}. The state of the agent is determined by the sequence of visual information that accumulates over fixations toward the search target (\Sref{sec:state_rep}), with each action of the agent depending on the state at that time during the evolving state representation. The goal of the agent is to maximize internal rewards through changes in gaze fixation. While it is difficult to behaviorally measure how much reward is received from these fixations, with IRL this reward can be assumed to be a function of the state and the action, and this function can be jointly learned using the imitation policy (\Sref{sec:learning}). \begin{figure}[t] \centering \includegraphics[width=.95\linewidth]{images/IRL_pipe.pdf} \vskip -0.1in \caption{{\bf Overview of the IRL framework}. The generator (policy) generates fake state-action pairs $\{B^f_t, a^f_t\}$ by sampling eye movements from given images and tasks. The discriminator (reward function) is trained to differentiates real human state-action pairs $\{B^r_t, a^r_t\}$ from the generated ones and provides reward to train the generator. The states $B^f_t$ and $B^r_t$ use DCB representations.} \label{fig:irl_pipeline} \vskip -0.15in \end{figure} \begin{figure}[t] \centering \includegraphics[width=.95\linewidth]{images/DCB_pipe.pdf} \vskip -0.1in \caption{{\bf Overview of DCB}. First, an input image and its low-res image counterpart are converted into the high-res beliefs and low-res beliefs. The initial state $B_0$ is set as the low-res belief. At each fixation which is discretized into a binary fixation mask $M_t$ with 1's at the fixation location and 0's elsewhere, a new state is generated by applying \Eref{eq:heuristic-update}.} \label{fig:belief_pipeline} \vskip -0.2in \end{figure} \subsection{State Representation Modeling}\label{sec:state_rep} To model the state of a viewer we propose a novel state representation for accumulating information through fixations that we term a \textbf{Dynamic-Contextual-Belief (DCB)}. As shown in \Fref{fig:belief_pipeline}, DCB is composed of three components:~1) Fovea, which receives a high-resolution visual input only from the image region around the fixation location; 2) Contextual beliefs, which represent a person's gross ``what'' and ``where'' understanding of a scene in terms of level of class confidence; and 3) Dynamics, which actively collects information with each fixation made during search. We discuss each component in greater detail below. \myheading{Fovea:} The primate visual system has a fovea, which means that high-resolution visual information is available only at a central fixated location. To accumulate information from the visual world, it is therefore necessary to selectively fixate new image locations. Visual inputs outside of the fovea have lower resolution, with the degree of blur depending on the distance between the peripherally-viewed input and the fovea. Rather than implementing a full progressive blurring of an image input (i.e., a complete retina-transformed image, as in \cite{zelinsky2019benchmarking}), for computational efficiency here we use a local patch from the original image as the high-resolution foveal input and a blurred version of the entire image to approximate low-resolution input from peripheral vision. \myheading{Contextual Belief:} Attention is known to be guided to target (and target-like) objects during search, but more recently it has been suggested that attention is also guided to ``anchor objects'' \cite{boettcher2018anchoring, vo2019reading}, defined as those objects having a learned spatial relationship to a target that can help in the efficient localization of that target. For example, people often look at the wall when searching for a TV because TVs are often found hanging on the wall. Inspired by this, we propose to model, not only the target features (as in \cite{zhang2018finding}), but also other objects and background information in the state. We hypothesize that people have an internal scene parser that takes an image input and generates belief maps for that image based on all the objects and background classes in that person's knowledge structure. We believe these belief maps also guide movements of the fovea for the purpose of capturing high-resolution information and forming better beliefs. We approximate these belief maps using a Panoptic-FPN~\citep{kirillov2019panopticfpn} for panoptic segmentation \cite{kirillov2019panoptic}. Given an image, Panoptic-FPN generates a pixel-level mask for each ``thing'' class (object) and each ``stuff'' class (background) in the image. There are 80 ``thing'' categories (including a single ``other'' class for the 80 ``thing'' classes) and 54 ``stuff'' categories \cite{lin2014microsoft, caesar2018coco, kirillov2019panoptic}. We create a mask for each category by grouping all mask instances belonging to the same category and use the belief maps of the 134 categories as the primary component of the state representation. We term these belief maps {\it contextual beliefs} because the collective non-target beliefs constitute a context of spatial cues that might affect the selection of fixations during the search for a target. \myheading{Dynamics} refers to the change in the state representation that occurs following each fixation. We propose a simple yet effective heuristic to model state dynamics (see \Fref{fig:belief_pipeline}). Initially, the state is based on the contextual beliefs on the low-resolution image corresponding to a peripheral visual input. For each fixation by the searcher, we update the state by replacing the portion of the low-resolution belief maps with the corresponding high-resolution portion obtained at the new fixation location. The state is updated as follows: \begin{align} B_0 = L \ \textrm{and } B_{t+1} = M_t\odot H + (1-M_t)\odot B_t, \label{eq:heuristic-update} \end{align} where $B_t$ is the belief state after $t$ fixations, $M_t$ is the circular mask generated from the $t^{th}$ fixation, $L$ and $H$ are the belief maps of ``thing'' and ``stuff'' locations for low-resolution and high-resolution images, respectively. Humans have different search behaviors on the same image given different search targets. To capture this, we augment the state by concatenating it with a one-hot task vector. Please refer to the supplementary material for more detail. \subsection{Reward and Policy Learning}\label{sec:learning} We learn the reward function and the policy for visual search behavior using Generative Adversarial Imitation Learning (GAIL) \cite{ho2016generative}. As shown in \Fref{fig:irl_pipeline}, GAIL is an adversarial framework with a discriminator and a generator. The policy is the generator that aims to generate state-action pairs that are similar to human behavior. The reward function maps a state-action pair to a numeric value, and this function is formulated as the logarithm of the discriminator output. The policy and reward functions are obtained by training the generator and discriminator with an adversarial optimization framework. Let $D$ and $G$ denote the discriminator and the generator, respectively. The discriminator aims to differentiate human state-action pairs from fake state-action pairs generated by the policy. This corresponds to maximizing the following objective function: \begin{align} \mathcal{L}_{D} = & \mathbb{E}_r [\log(D(S, a))] + \mathbb{E}_f [\log(1-D(S,a))] \nonumber \\ & - \lambda \mathbb{E}_r [\left\| \nabla D(S, a))\right\|^2]. \end{align} In the above objective function, $\mathbb{E}_r$ denotes the expectation over the distribution of real state-action pairs, while $\mathbb{E}_f$ denotes the expectation over the fake samples generated by the generator (i.e., the policy). The last term of the above objective is the expected squared norm of the gradients, which is added for faster convergence \cite{roth2017stabilizing}. The reward function is defined based on the discriminator: \begin{equation} r(S, a) = \log (D(S, a)). \label{eq:rwd_fun} \end{equation} The generator aims to fool the discriminator, and its objective is to maximize the log likelihood of the generated state-action pairs, i.e., to maximize: $\mathcal{L}_{G} = \mathbb{E}_f [\log(D (S, a))] = \mathbb{E}_f[r(S, a)]. $ The generator is an RL policy, hence its objective can be equivalently reformulated as an RL objective and optimized by Proximal Policy Optimization \cite{schulman2017proximal}: \begin{align} &\mathcal{L}_{\pi} = \mathbb{E}_{\pi} [\log(\pi(a|S)) A(S, a)] + H(\pi). \end{align} We use GAE \cite{schulman2015high} to estimate the advantage function $A$ which measures the gain of taking action $a$ over the policy’s default behavior. $H({\pi}) = - \mathbb{E}_{\pi} [\log(\pi(a| S))]$, the entropy in max-entropy IRL \cite{Ziebart-etal-AAAI08}. \section{COCO-Search18 Dataset} COCO-Search18 is a large-scale and high-quality dataset of search fixations obtained by having 10 people viewing~6202 images in the search for each of 18 target-object categories. Half of these images depicted an instance of the designated target object and the other half did not, meaning that we adopted a standard target-present (TP) or target-absent (TA) search task. All images in COCO-Search18 were selected from the COCO trainval set \cite{lin2014microsoft}. Five criteria were imposed when selecting the TP images: \textbf{(1)} No images depicting a person or an animal (to avoid known strong biases to these categories that might skew our measures of attention control~\cite{cerf2008predicting, judd2009learning}). \textbf{(2)} The image should include one and only one instance of the target. \textbf{(3)} The size of the target, measured by the area of its bounding box, must be $>$1\% and \textless10\% of the area of the search image. \textbf{(4)} The target should not be at the center of the image, enforced by excluding an image if the target bounding box overlapped with the center cell of a 5x5 grid. \textbf{(5)} The original image ratio (width/height) must be between 1.2 and 2.0 to accommodate the display screen ratio of 1.6. After applying these exclusion criteria, and excluding object categories that had less than 100 images of exemplars, we were left with 32 object categories (out of COCO's 80) to use as search targets. To exclude images in which the target was highly occluded or otherwise difficult to recognize, we trained a patch-based classifier for target recognition and only selected images in which the cropped target-object patch had a classification confidence in the top 1\%. Finally, we manually excluded images depicting digital clocks from the clock target category (because the features of analog and digital clocks are very different and this would be expected to reduce data quality by creating variability in the search behavior), as well as images depicting objectionable content. This left us with 3101 TP images over 18 target categories. To select the same number of TA images for each of these 18 categories, we randomly sampled COCO trainval images with the following constraints: \textbf{(1)} The image should not depict an instance of the target, and \textbf{(2)} The image must include at least two instances of the target's siblings, as defined in COCO. For example, a microwave sibling can be an oven, a toaster, a refrigerator, or a sink, which are under the parent category of appliance. We did this to discourage TA responses from being based on scene type (e.g., a city street scene would be unlikely to contain a microwave). \begin{figure} \centering \includegraphics[width=1.\linewidth]{images/human_matrix_new2.pdf} \vskip -0.1in \caption{Normalized gaze data [0,1] on response error, reaction time, number of fixations (NumFix), time to target (T2T), and number of fixations to target (NumFix2T) averaged over 10 subjects searching for 18 categories in TP images. Redder color indicates harder search targets, bluer color indicates easier search.} \label{fig:gaze_data} \vskip -0.2in \end{figure} Each of the 10 student participants (6 males, age range 18-30, normal or corrected-to-normal vision) viewed all 6202 images, and their eye position throughout was sampled at 1000Hz using an EyeLink 1000 eyetracker (SR Research) in tower-mount configuration under controlled laboratory conditions. For each subject, data collection was distributed over six sessions in six days, with each session having equal number TP trials and TA trials ($\sim$500 each) randomly interleaved. Each session required $\sim$2 hours. For each image, subjects made a TP or TA judgment by pressing a `yes' or `no' button on a game pad. They searched all the images for one target category before preceding to next category. A total of 299,037 fixations were extracted from the eye position data, over the 10 subjects, although only data from the TP fixations will be reported here (\Fref{fig:gaze_data}). TP fixations occurring on error trials, or after fixation on the target, were discarded. This left 100,232 TP search fixations to use for training and testing. All model evaluations are based on 70\% training, 10\% validation, and 20\% test, random splits of COCO-Search18, within each target category. \section{Experiments} We evaluate the proposed framework and its constituent components in multiple experiments. We first compare the scanpath predictions by the IRL-based algorithm to predictions from various heuristic methods and behavior cloning methods using ConvNets and convolutional LSTM. We then study the algorithm's ability to generalize to new human subjects. Finally, we analyze a context effect, the value of having more training data, and report the results of an ablation study. Here we used only the target-present trials from COCO-Search18, leaving analyses of the target-absent data for future study. \subsection{Comparing Scanpath Prediction Models}\label{sec:policy_cmpr} \myheading{Comparison methods}. We compare the IRL algorithm for predicting scanpaths to several baselines, heuristics, and behavior cloning methods: (1) \textbf{Random scanpath}: we predict the scanpath for an input image by randomly selecting a human scanpath for the same search target but in a different input image. (2) \textbf{Detector}: we sample a sequence of fixation locations based on the detection confidence map over the image. Regions with higher confidence scores are more likely to be sampled. (3) \textbf{Fixation heuristics}: rather than sampling from a detector's confidence map, here we generate fixations by sampling from a fixation density map produced by a ConvNet trained on human fixation density maps. (4) {\bf BC-CNN} is a behavior cloning method, where we train a ConvNet to predict the next fixation location from the DCB state representation. Note that this state representation and network structure are identical to the one used by the IRL policy described in \Sref{sec:state_rep}. (5) {\bf BC-LSTM} is a behavior cloning method similar to BC-CNN, but the state representation and update are done with a convolutional LSTM. Instead of having the simple predefined update rule used by both IRL and BC-CNN, as shown in \Eref{eq:heuristic-update}, BC-LSTM aims to learn a recurrent update rule automatically with an LSTM: $B_{t+1} = ConvLSTM(B_t, I_t)$, where $ConvLSTM$ denotes a convolutional LSTM cell~\cite{ballas2015delving}, $B_t$ is the hidden state of the LSTM cell and also the searcher's belief state after $t$ fixations. $I_t$ is the input to the LSTM at time $t$, and it is defined as $I_t = M_t\odot H + (1-M_t)\odot L$. Recall that $M_t$ is the circular mask generated from the $t^{th}$ fixation, $L$ and $H$ are the predicted maps from the Panoptic-FPN \cite{kirillov2019panoptic} for the 80 COCO objects and 54 ``stuff'' classes for low- and high-resolution input images, respectively. \begin{figure}[t] \centering \includegraphics[width=.9\linewidth]{images/search_efficiency.pdf} \vskip -0.1in \caption{{\bf Cumulative probability of fixating the target} for human searchers and all predictive methods. X-axis is the number of fixations until the fovea moves to the target object; Y-axis is the percentage of scanpaths that succeed in locating the target. Means and standard errors are first computed over target categories, and then over searchers.} \label{fig:cdf} \vskip -0.2in \end{figure} \myheading{Results}. \label{sec:results} Fig. \ref{fig:cdf} shows the cumulative probability of gaze landing on the target after each of the first 6 fixations made by humans and the algorithms in our model comparison. First, note that even the most predictive models have a performance ceiling lower than that of humans, whose ceiling over this range is nearly 1. These lower ceilings likely reflect a proportion of trials in which the models search was largely unguided. Second, note the steep increase in target fixation probability after the first and second fixations. The slopes of these functions indicate strong target guidance. The target was fixated in the very first movement on about half of the images, with the IRL model replicating human search guidance slightly better than its nearest competitors: the Detector and BC-CNN models. We quantify the patterns from Fig. \ref{fig:cdf} using several metrics. Two of these metrics follow directly from Fig. \ref{fig:cdf} and capture aggregate measures combining search guidance and accuracy. The first of these computes the area under the cumulative probability of the target fixation curve, a metric we refer to as {\bf Target Fixation Probability AUC} or TFP-AUC. Second, we compute the sum of the absolute differences between the human and model cumulative probability of target fixation in a metric that we refer to as {\bf Probability Mismatch}. We also report the {\bf Scanpath Ratio}, which is a widely used metric for search efficiency. It is computed by the ratio of Euclidean distance between the initial fixation location and the center of the target to the summed Euclidean distances between fixations to the target~\citep{hout2015target}. Finally, we compute two metrics for scanpath prediction success, that both capture the scanpath similarity between fixation sequences generated by humans and sequences generated by the model. The first of these computes a {\bf Sequence Score} by first converting a scanpath into a string of fixation cluster IDs and then use a string matching algorithm \cite{Needleman-Wunsch-JMB70} to measure similarity between two strings. Finally, we use {\bf MultiMatch}~\cite{anderson2015comparison, dewhurst2012depends} to measure the scanpath similarity at the pixel level. MultiMatch measures five aspects of scanpath similarity: shape, direction, length, position, and duration. We exclude the duration metric because the studied models do not predict fixation duration. Unless otherwise specified, each model generates 10 scanpaths of maximum length 6 (excluding the first fixation) for each testing image by sampling from the predicted action map at each fixation, with the results averaged over scanpaths. As seen from \Tref{table:all_results}, the IRL algorithm outperforms the other methods on all metrics. The performance of IRL is closest to {\it Human}, an oracle method where the scanpath of a subject is used to predict the scanpath of another subject for the same input image. \Fref{fig:rwd_maps} also shows that {\bf reward maps} recovered by the IRL model depend greatly on the category of the search target. In the top row, higher reward was assigned to the laptop when searching for a mouse, while for the same image greater reward was expected from fixating on the monitor when searching for a tv. Similarly, the search for a car target in the bottom image resulted in the expectation of reward from the other cars on the road but almost not at all from the highly-salient stop sign, which becomes intensely prioritized when the stop sign is the target. \begin{table*}[t] \begin{center} \begin{tabular}{l|c|c|c|c|cccc} & \multirow{2}{*}{TFP-AUC $\bm{\uparrow}$} & \multirow{2}{1.8cm}{Probability Mismatch $\bm{\downarrow}$} & \multirow{2}{1.5cm}{Scanpath Ratio $\bm{\uparrow}$} & \multirow{2}{1.5cm}{Sequence Score $\bm{\uparrow}$} & \multicolumn{4}{c}{MultiMatch $\bm{\uparrow}$} \\ \cline{6-9} & & & & & shape & direction & length & position \\ \Xhline{1.2pt} Human & 5.200 & - & 0.862 & 0.490 & 0.903 & 0.736 & 0.880 & 0.910 \\ \hline Random scanpath & 0.795 & 4.407 & - & 0.295 & 0.869 & 0.558 & 0.849 & 0.849 \\ Detector & 4.046 & 1.166 & 0.687 & 0.414 & 0.877 & 0.676 & 0.853 & 0.863 \\ Fixation heuristic & 2.154 & 3.046 & 0.545 & 0.342 & 0.873 & 0.614 & \textbf{0.870} & 0.850 \\ BC-CNN & 3.893 & 1.328 & 0.706 & 0.409 & 0.880 & 0.669 & 0.865 & 0.874 \\ BC-LSTM & 1.702 & 3.497 & 0.406 & 0.324 & 0.834 & 0.567 & 0.818 & 0.770 \\ IRL(Ours) & \textbf{4.509} & \textbf{0.987} & \textbf{0.826} & \textbf{0.422} & \textbf{0.886} & \textbf{0.695} & 0.866 & \textbf{0.885} \end{tabular} \end{center} \vskip -0.2in \caption{ {\bf Comparing scanpath prediction algorithms} (rows) using multiple scanpath metrics (columns) on the COCO-Search18 test dataset. In the case of Sequence Score and Multimatch, \enquote{Human} refers to an oracle method where one searcher's scanpath is used to predict another searcher's scanpath; \enquote{Human} for all other metrics refers to observed behavior.} \label{table:all_results} \vskip -.2in \end{table*} \myheading{Implementation details.} We resize each input image to $\htimesw{320}{512}$ and obtain a low-resolution image by applying a Gaussian filter with standard deviation \mbox{$\sigma = 2$}. To compute the contextual beliefs, we use a Panoptic-FPN with backbone network ResNet-50-FPN pretrained on COCO2017 \cite{kirillov2019panoptic}. Panoptic-FPN outputs a feature map of 134 channels, corresponding to 80 object categories and 54 background classes in COCO, and it is resized to $\htimesw{20}{32}$ spatially. For IRL and BC-CNN, we use the same policy network architecture: a network composed of four convolutional (conv) layers and a softmax layer. IRL model has two additional components---critic network and discriminator network. The \textbf{critic network} has two convolutional layers and two fully-connected (fc) layers. The discriminator network shares the same sturcture with the IRL policy network except the last layer which is a sigmoid layer. Each conv layer and fc layer in BC-CNN and IRL is followed by a ReLU layer. BC-LSTM has the same policy network as the BC-CNN, with the difference being the use of a convolutional LSTM~\cite{ballas2015delving} to update the states. BC-CNN and BC-LSTM use the KL divergence between predicted spatial distribution and ground truth as loss. The prediction of both behavior cloning models and IRL is conditioned on the search target. We implement the target conditioning by introducing an additional bias term based on the search task to the input features at each layer \cite{perez2018film}. The human visual system employs Inhibition-of-Return~(IOR) to spatially tag previously attended locations with inhibition to discourage attention from returning to a region where information has already been depleted~\cite{wang2010searching}. To capture this mechanism, we enforce IOR on the policy by setting the predicted probability map to 0 at each attended location using a \htimesw{3}{3} grid. See the supplementary for more detail. \begin{figure}[t] \begin{center} \includegraphics[width=.48\textwidth]{images/rwd_maps_diff_targets.pdf} \end{center} \vskip -0.2in \caption{Initial {\bf reward maps} learned by the IRL model for two different search targets in two test images. Top row: original image (left), mouse target (middle), and tv target (right). Bottom row: original image (left), car target (middle), stop sign target (right). Redder color indicates the expectation of higher reward for fixating a location. } \label{fig:rwd_maps} \vskip -.2in \end{figure} \subsection{Group Model vs Individual Model} The previous subsection described the IRL model's ability to predict a searcher's scanpath on unseen test images, but how well can this model predict the scanpaths of a new unseen searcher without training on that person's scanpaths? To answer this question, we perform ten leave-one-subject-out experiments, with each experiment corresponding to a test subject. For every subject we train two models: (1) a group model using the scanpaths of the 9 other subjects; and (2) an individual model using the scanpaths of the test subject on the training images. We evaluate the performance of these models on the scanpaths of each test subject on the unseen test images. \Fref{fig:group vs indv} shows that both models perform well, with an insignificant performance gap between them. This suggests that there is good agreement between group and individual behaviors, and that a group model can generalize well to new searchers. \begin{figure}[t!] \begin{center} \includegraphics[width=.48\textwidth]{images/group_indv2.pdf} \end{center} \vskip -0.25in \caption{No significant differences were found between a group model (solid), trained with 9 subjects, and an individual model (striped), trained with one subject. } \label{fig:group vs indv} \vskip -0.2in \end{figure} \subsection{Context Effects}\label{sec:context} \myheading{Search efficiency}. With DCB we can ask how an object from category $A$ affects the search for a target from category~$B$. This effect can either increase (guidance) or decrease (distraction) search efficiency. To study this, we first zero out the belief map of category $A$ in the DCB state representation and then measure the TFP-AUC (see \Sref{sec:results}) on test images for category $B$. We compute the difference between the TFP-AUC obtained with and without switching off the belief map for category $A$ in DCB. A positive value indicates that an object in category $A$ helps to guide search for a target in category $B$, while a negative value indicates the opposite (that the object is distracting). We did this for the 134 COCO objects and stuff non-target categories $A$ and the 18 target categories $B$. \Fref{fig:ctx_effect} shows the six most guiding and distracting objects for the knife and car searches. Note that the fork was highly distracting when searching for a knife, likely because the two look similar in periphery vision, but that the cake facilitated the knife search. Similarly for the car search, pavement provided the strongest guidance whereas trucks were the most distracting. \begin{figure} \centering \includegraphics[width=1.0\linewidth]{images/context_bar_new.pdf} \vskip -0.1in \caption{{\bf Context effect}. The six most influential context objects (grey bars) for knife and car search tasks. The y-axis is the context object category and the x-axis is a measure of how much the belief map for a context object contributed to search efficiency, as measured by TFP-AUC. Larger positive values mean that the context object improved search guidance to the target, more negative values mean that the object distracted attention from the search.} \label{fig:ctx_effect} \vskip -0.1in \end{figure} \myheading{Directional Prior}. Can an object from category $A$ serve as a directional spatial cue in the search for a target from category $B$? Suppose $M$ is the probability map produced by the policy network of our IRL model, and let $M'$ be the modified probability map from the policy network but with the belief map of category $A$ in the DCB state representation being switched off. By computing the difference between~$M'$ and~$M$ which we call a \textit{context map} (as depicted in the top row of \Fref{fig:spatial}), we can see the spatial relationship between the context object $A$ and the target object $B$ (see \Fref{fig:spatial} for examples). \begin{figure}[t] \centering \includegraphics[width=1.0\linewidth]{images/spatial.pdf} \vskip -0.1in \caption{{\bf Spatial relations} between context and target objects learned by the model. Top row shows individual context maps for a dining table (left) and a refrigerator (middle) in a microwave search, and a keyboard (right) in a mouse search. Bottom row are the belief maps of the corresponding context objects. Gaze is guided to the top of the dinning table and refrigerator when searching for a microwave, and to the right of the keyboard when searching for a mouse.} \vskip -0.15in \label{fig:spatial} \end{figure} \subsection{Ablation Study on State Representation}\label{sec:state_cmpr} DCB is a rich representation that uses top-down, bottom-up, and history information. Specifically, it consists of 136 belief maps, divided into five factor groups: target object (1 map), context objects (79 maps), ``stuff'' (54 maps), saliency (1 map, extracted using DeepGaze2 \cite{kummerer2017understanding}), and history (1 binary map for the locations of previous fixations). To understand the contribution of a factor group, we remove the group from the full state representation and measure the effect on performance. As we describe in the supplementary material, the most important factor groups were target and context objects, followed by stuff, whereas saliency and history weakly impacted model performance. In addition, an alternative state representation to DCB is the Cumulative Foveated Image (CFI)~\cite{zelinsky2019benchmarking}, but replacing DCB with CFI degrades the performance of IRL Full results can be found in the supplementary material. \subsection{Data Efficiency} \Fref{fig: data_eff} shows IRL and BC-CNN performance as we vary the number of training images per object category. Both methods use DCB as the state representation. IRL is more data efficient than BC-CNN, achieving comparable or better results using less training data. A likely reason for this is that the GAIL-based~\cite{ho2016generative} IRL method includes an adversarial component that generates augmented training data, leading to a less prone to overfitting policy network. Data efficiency is crucial for training for new categories, given the time and cost of collecting human fixations. \begin{figure} \centering \includegraphics[width=1.0\linewidth]{images/data_efficiency3.pdf} \vskip -0.1in \caption{Performance of IRL (solid line) and BC-CNN (dashed line) as the number of training images per category increases from 5 to 20. IRL is more data efficient than BC-CNN, likely due to an adversarial data generator.} \label{fig: data_eff} \vskip -0.2in \end{figure} \section{Conclusions} We proposed a new model for predicting search fixation scanpaths that uses IRL to jointly recover the reward function and policy used by people during visual search. The IRL model uses a novel and highly explainable state representation, \textit{dynamic contextual beliefs (DCB)}, which updates beliefs about objects to obtain an object context that changes dynamically with each new fixation. To train and test this model we also introduced COCO-Search18, a large-scale dataset of images annotated with the fixations of people searching for target-object goals. Using COCO-Search18, we showed that the IRL model outperformed comparable models in predicting search scanpaths. Better predicting human search behavior means better robotic search applications and human-computer systems that can interact with users at the level of their attention movements \cite{park2019advancing}. It may also be possible to use reward maps from the IRL model to annotate and index visual content based on what is likely to attract a person's attention. Finally, our work impacts the behavioral vision literature, where the visual features guiding human goal-directed attention are still poorly understood for real images \cite{zelinsky2013modeling}. \myheading{Acknowledgements}. This project is supported by US National Science Foundation Award IIS-1763981, the Partner University Fund, the SUNY2020 Infrastructure Transportation Security Center, and a gift from Adobe. {\small \setlength{\bibsep}{0pt} \bibliographystyle{plainnat} \section{Appendix} This section provides further details about the COCO-Search18 dataset (\Sref{sec:dataset}), Dynamic Contextual Beliefs (\Sref{sec:DCB}), and implementation (\Sref{sec:impl_details}). We also include additional results from experiments and ablation studies, and interpretation (\Sref{sec:results}). \subsection{Details about COCO-Search18 Dataset}\label{sec:dataset} \myheading{Data source:} The COCO-Search18 dataset annotates COCO \cite{lin2014microsoft} with human gaze fixations made during a standard target-present (TP) or target-absent (TA) search task, where on each trial the search image either depicted the target (TP) or it did not (TA). All of the images were selected from the {\it trainval} set, and detailed descriptions of TP and TA image selection and gaze collection methods are provided below. \myheading{Target present image selection:} In addition to the exclusion criteria described in the main text, we also excluded images in which the target was highly occluded or otherwise difficult to recognize. Specifically, we only selected images in which the cropped target-object patch had a classification confidence $>$.99. To train this classifier, we cropped the target in each image (by bounding box) and used these image patches as positive samples. Same-sized image patches of non-target objects were used as negative samples. Negative samples were constrained to intersect with the target by 25\% (area of intersection divided by area of target) so that they could serve as hard negatives for specific targets. More than 1 million cropped patched were collected and resized to 224x224 pixels, while keeping the original aspect ratio by padding. The classifier is fine-tuned from an ImageNet-pretrained ResNet-50 model with the last fully connected layer changed from 1000 outputs to 33 (32+``Negative''). Images with a classification score for the cropped target patch that was \textless.99 were excluded. This resulted in 18 categories with at least 100 images in each category, and 3131 images in total. As described in the main text, we conducted a final manual checking of the dataset to exclude images depicting digital clocks (5 images), so as to make the clock target category specific to analog clocks, and to remove images depicting content that participants might find objectionable. This latter criterion resulting in the exclusion of 30 images, 22 of which were from the toilet category. \begin{table} \begin{center} \begin{tabular}{lcccc} \toprule Category & TP images & ACC & TA images & ACC \\ \midrule bottle & 166 & 0.84 & 166 & 0.92 \\ bowl & 141 &0.80 & 141 & 0.90\\ car & 104 &0.89 & 104 & 0.91\\ chair & 253 &0.89 & 253 & 0.64\\ clock & 119 &0.99 & 119 & 0.97\\ cup & 276 &0.92 & 276 & 0.76\\ fork & 230 &0.96 & 230 & 0.98\\ keyboard & 184 &0.92 & 184 & 0.98\\ knife & 141 &0.89 & 141 & 0.97\\ laptop & 123 &0.95 & 123 & 0.95\\ microwave & 156 &0.97 & 156 & 0.95\\ mouse & 109 &0.97 & 109 & 0.97\\ oven & 101 &0.91 & 101 & 0.93\\ potted plant & 154 &0.84 & 154 & 0.95\\ sink & 279 &0.97 & 279 & 0.94\\ stop sigh & 126 &0.95 & 126 & 0.99\\ toilet & 158 &0.99 & 158 & 1.00\\ tv & 281 &0.96 & 281 & 0.93\\ \midrule total/mean & 3101 & 0.92 & 3101 & 0.92\\ \bottomrule \end{tabular} \caption{Number of images and response accuracy (ACC) for TP and TA images grouped by target category.} \label{table: image numbers} \end{center} \end{table} \begin{figure*}[t] \centering \includegraphics[width=1.\linewidth]{images/gaze_example.pdf} \vskip -0.05in \caption{Examples of human scanpaths during target-present (top 3 rows) and target-absent (bottom 3 rows) visual search. From left to right and top to bottom, the 18 target categories are: bottle, bowl, car, chair, clock, cup, fork, keyboard, knife, laptop, microwave, mouse, oven, potted plant, sink, stop sign, toilet, and tv. Each yellow line represents the scanpath of one behavioral searcher, with numbers indicating fixation order. } \label{fig:scanpath_example} \end{figure*} After implemented all exclusion criteria, we selected 3101 target-present images from 18 categories: bottle, bowl, car, chair, clock, cup, fork, keyboard, knife, laptop, microwave, mouse, oven, potted plant, sink, stop sign, toilet, tv. See Table \ref{table: image numbers} for the specific number of images in each category and the average response accuracy (ACC). There were an equal number of TA images (for a total of 6202 images), which were all resized and padded to fit the ${1050}\times{1680}$ resolution of the display monitor. \myheading{Gaze data collection procedure:} Ten university undergraduate and graduate students (6 males, age range 18--30) with normal or corrected to normal vision participated in this study, which was approved by the Institutional Review Board. They were naive with respect to experimental question and design, and were compensated with course credits or money for their participation. Informed consent was obtained at the beginning of the experiment, and every participant read and understood the consent form before signing it. The 6202 images were divided into six days of experiment sessions with each session consisting of $\sim$500 TP images and the same number of TA images, randomly interleaved. Images for a given target category were grouped and presented sequentially in an experiment block (i.e., target type was blocked). Preceding each block was a calibration procedure needed to map eye position obtained from the eye-tracker to screen coordinates, and a calibration was not accepted until the average calibration error was $\leq$.51 and the maximal error was $\leq$.94. Each trial began with a fixation dot appearing at the center of the screen. To start a trial, the subject should press the ``X'' button on a gamepad while carefully looking at the fixation dot. A scene would then be displayed and their task was to answer ``yes'' or ``no'' whether an exemplar of the target category for that block appears in the displayed scene. The subject registered a ``yes'' target judgment by pressing the right rigger of the gamepad, and a ``no'' judgment by pressing the left trigger. They were told that there were equal number of target present and absent trials, and that they should respond as quickly as possible while remaining accurate. Participants were allowed to take multiple breaks between and within each block. Image presentation and data collection was controlled by Experiment Builder (SR research Ltd., Ottawa, Ontario, Canada). Images were presented on a 22-inch LCD monitor (resolution: 1050x1680), and subjects viewed these stimuli in a distance of 47cm from the monitor, enforced by both chin rest and head rest. Eye movements were recorded using an EyeLink 1000 eye tracker in tower-mount configuration (SR research Ltd., Ottawa, Ontario, Canada). The experiment was conducted in a quiet and dimmed laboratory room. \Fref{fig:scanpath_example} shows some TP and TA images from the 18 object categories, with overlaid human scanpaths. \subsection{Detailed Description of DCB}\label{sec:DCB} \begin{figure*}[t] \centering \includegraphics[width=1.0\linewidth]{images/DCB_detail.pdf} \vskip -0.1in \caption{{\bf Detailed illustration of Dynamic-Contextual-Belief}. First, an input image and its low-res image counterpart are converted into high-res beliefs and low-res beliefs. At each fixation, which is discretized into a binary fixation history map with 1's around the fixation location and 0's elsewhere, a new state is generated by concatenating the output of \Eref{eq:dcb} with a one-hot task embedding (best viewed in color).} \label{fig:dcb_detail} \vskip -0.2in \end{figure*} \myheading{DCB:} An input image is resized to $\htimesw{320}{512}$ for computational efficiency (the original image is \htimesw{1050}{1680}), while the blurred image is obtained by applying a Gaussian filter on the original image with the standard deviation $\sigma = 2$. Both images are passed through a Panoptic-FPN with backbone network ResNet-50-FPN pretrained on COCO2017 \cite{kirillov2019panoptic}. The output of the Panoptic-FPN has 134 feature maps, consisting of 80 ``thing'' categories (objects) and 54 ``stuff'' categories (background) in COCO. Feature maps are then resized to $\htimesw{20}{32}$ spatially, same as the discretization of fixation history. At a given time step $t$, feature maps $H$ for the original image and feature maps $L$ for the blurred image are combined for DCB: \begin{equation}\label{eq:dcb} B_t = M_t\odot H + (1-M_t)\odot L \end{equation} where $\odot$ is element-wise product and $M_t$ is the mask generated from fixation history and repeated over feature channels (see \Fref{fig:dcb_detail}). Note that the above equation is equivalent to Eq. (1) in the main paper which is written in a recurrent form. \myheading{Encoding the target object category:} The task embedding used in our model is the one-hot encoding maps which spatially repeat the one-hot vector. To make predictions conditioned on the task, inputs of each convolutional layer are concatenated with this embedding. This is equivalent to adding a task-dependent bias term for every convolutional layer. \subsection{Implementation details}\label{sec:impl_details} \myheading{Action Space}. Our goal is to predict the pixel location where the person is looking in the image during visual search. To reduce the complexity of prediction, we discretize the image into a $\htimesw{20}{32}$ grid, with each patch corresponding to $\htimesw{16}{16}$ pixels in the original image coordinates. This descretized grid defines the action space for all models tested in this paper. At each step, the policy chooses one out of 640 patches and the center location of that selected patch in the original image coordinates is used as an action. The maximum approximation error due to this discretization procedure is $1.75$ degrees visual angle. \myheading{IRL}. The IRL model is composed of three components---the policy network, the critic network and the discriminator network. The \textbf{policy network} consists of four convolutional layers whose kernel sizes are 5, 3, 3, 1 with padding 2, 1, 1, 0 and output channels are 128, 64, 32 and 1, and a softmax layer to output a final probability map. The \textbf{critic network} has two convolutional layers of kernel size 3 and two fully-connected (fc) layers whose output sizes are 64 and 1. The convolutional layers have output sizes 128 and 256, respectively, and each is followed by a max pooling layer of kernel size 2 to compress the feature maps into a vector. Then this feature vector is regressed to predict the value of the state through two fc layers . The \textbf{discriminator network} shares the same structure with the IRL policy network except that the last layer is a sigmoid layer. Note that all convolutional layers and fully-connected layers are followed by a ReLU layer except the output layer. \begin{figure*}[t!] \begin{center} \includegraphics[width=.9\textwidth]{images/seq_score_spvis.pdf} \end{center} \vskip -0.2in \caption{Left: cumulative distribution of the sequence scores of the proposed IRL scanpath prediction method. Right: Four qualitative examples. Human scanpaths are colored in yellow, and the IRL-generated scanpaths are in green. The sequence score for the generated scanpaths are 0.33, 0.40, 0.50, and 0.75, from top to bottom.} \label{fig:seq_score_cdf} \end{figure*} The critic network is jointly trained with the policy network to estimate the value of a state (i.e., expected return) using smoothed $L_1$ loss. The estimated value is used to compute the advantage $A(S, a)$ (note that the state $S$ is represented by the proposed DCB in our approach) in Eq. (4) of the main paper using the Generalized Advantage Estimation (GAE) algorithm \cite{schulman2015high}. At each iteration, the policy network first generates two scanpaths by sampling fixations from the current policy outputs for each image in a batch. Second, we break the generated scanpaths into state-action pairs and sample the same number of state-action pairs from ground-truth human fixations to train the discriminator network which discriminates the generated fixation from behavioral fixations. Lastly, we update the policy and critic network jointly using the PPO algorithm \cite{schulman2017proximal} by maximizing the total expected rewards which are given by the discriminator (see Eq. (3) of the main paper). \myheading{Training:} The IRL model was trained for 20 epochs with an image batch size of 128. The batch sizes used for training the discriminator and policy networks were 64. For the PPO algorithm, the reward discount factor, the clip ratio and number of epochs were set to 0.99, 0.2, and 10, respectively. The extra discount factor in the GAE algorithm was set to 0.96. Both the policy network and the discriminator network were trained with a learning rate of $0.0005$. It took approximately 40 minutes to train the proposed IRL model (for 20 epochs) on a single NVIDIA Tesla V100 GPU. The training procedure consumed about 5.6GB GPU memory. Note that the segmentation maps used to construct the DCB state representation had been computed beforehand. \myheading{Additional details on two baseline methods}. \textbf{Detector}: The detector network consists of a feature pyramid network (FPN) for feature extraction (1024 channels) with a ResNet50 pretrained on ImageNet as the backbone and a convolution layer for detection of 18 different targets. The detector network predicts a 2D spatial probability map of the target from the image input and is trained using the ground-truth location of the target. Another similar baseline is \textbf{Fixation Heuristics}. This network shares exactly the same network architecture with the detector baseline but it is trained with behavioral fixations in the form of spatial fixation density map (FDM), which is generated from 10 subjects on the training images. \myheading{Scanpath Generation}. When generating scanpaths, a fixation location is sampled from the probability map that the models have produced and Inhibition-of-Return is applied to prevent revisiting previously attended locations. All predictive methods including IRL, behavior cloning, and heuristic methods, generate a new spatial probability map at every step, while the predicted probability map is fixed over all steps for the Detector and Fixation Heuristic baselines. \begin{table*}[t!] \begin{center} \begin{tabular}{l|c|c|c|c|cccc} \multirow{2}{2.2cm}{State Representation} & \multirow{2}{1.3cm}{\centering Sequence Score $\bm{\uparrow}$} & \multirow{2}{1.3cm}{\centering Scanpath Ratio $\bm{\uparrow}$} & \multirow{2}{1.2cm}{\centering TFP- AUC $\bm{\uparrow}$} & \multirow{2}{1.7cm}{\centering Probability Mismatch $\bm{\downarrow}$} & \multicolumn{4}{c}{MultiMatch $\bm{\uparrow}$} \\ \cline{6-9} & & & & & shape & direction & length & position\\ \Xhline{1.2pt} DCB & {\bf 0.422} & {\bf 0.826} & {\bf 4.509} & {\bf 0.987} & {\bf 0.886} & {\bf 0.695} & 0.866 & {\bf 0.885}\\ CFI & 0.402 & 0.619 & 3.412 & 1.797 & 0.875 & 0.666 & 0.864 & 0.857\\ \end{tabular} \end{center} \vskip -0.2in \caption{{\bf Dynamic contextual belief (DCB) vs. cumulative foveated image (CFI)} under the framework of IRL.} \label{table:cfi_cmpr} \end{table*} \begin{table*}[t!] \begin{center} \begin{tabular}{l|c|c|c|c|cccc} \multirow{2}{1.8cm}{State Representation} & \multirow{2}{1.3cm}{\centering Sequence Score $\bm{\uparrow}$} & \multirow{2}{1.3cm}{\centering Scanpath Ratio $\bm{\uparrow}$} & \multirow{2}{1.2cm}{\centering TFP- AUC $\bm{\uparrow}$} & \multirow{2}{1.7cm}{\centering Probability Mismatch $\bm{\downarrow}$} & \multicolumn{4}{c}{MultiMatch $\bm{\uparrow}$} \\ \cline{6-9} & & & & & shape & direction & length & position\\ \Xhline{1.2pt} DCB with all components & 0.422 & 0.803 & 4.423 & 1.029 & 0.880 & 0.676 & 0.841 & 0.888\\ w/o history map & 0.419 & 0.800 & 4.397 & 1.042 & 0.882 & 0.672 & 0.844 & 0.887\\ w/o saliency map & 0.419 & 0.795 & 4.403 & 1.029 & 0.880 & 0.675 & 0.840 & 0.887\\ w/o stuff maps & 0.407 & 0.777 & 4.111 & 1.248 & 0.876 & 0.662 & 0.836 & 0.875\\ w/o thing maps & 0.331 & 0.487 & 2.047 & 3.152 & 0.855 & 0.605 & 0.852 & 0.818 \\ w/o target map & 0.338 & 0.519 & 2.274 & 2.926 & 0.866 & 0.613 & 0.837 & 0.820 \\ \end{tabular} \end{center} \vskip -0.2in \caption{{\bf Ablation study of the proposed state representation---dynamic contextual belief}. The full state consists of 1 history map, 1 saliency map, 54 stuff maps, 79 context maps and 1 target map. We mask out one part by setting the map(s) to zeros at each time.} \label{table:abalation} \end{table*} \begin{table*}[t!] \begin{center} \begin{tabular}{l|c|c|c|c|cccc} \multirow{2}{2.5cm}{Scanpath generation policy} & \multirow{2}{1.3cm}{\centering Sequence Score $\bm{\uparrow}$} & \multirow{2}{1.3cm}{\centering Scanpath Ratio $\bm{\uparrow}$} & \multirow{2}{1.2cm}{\centering TFP- AUC $\bm{\uparrow}$} & \multirow{2}{1.7cm}{\centering Probability Mismatch $\bm{\downarrow}$} & \multicolumn{4}{c}{MultiMatch $\bm{\uparrow}$} \\ \cline{6-9} & & & & & shape & direction & length & position\\ \Xhline{1.2pt} Based on total reward & {\bf 0.422} & {\bf 0.826} & {\bf 4.509} & {\bf 0.987} & {\bf 0.886} & {\bf 0.695} & 0.866 & {\bf 0.885}\\ Based on immediate reward & 0.375 & 0.704 & 3.893 & 2.143 & 0.886 & 0.648 & {\bf 0.873} & 0.852 \\ \end{tabular} \end{center} \vskip -0.2in \caption{{\bf IRL model predictions using Greedy (immediate reward) and Non-greedy (total reward) policy}.} \label{table:greedy_cmpr} \end{table*} \begin{table*}[t!] \begin{center} \begin{tabular}{l|c|c|c|c|cccc} & \multirow{2}{1.3cm}{\centering Sequence Score $\bm{\uparrow}$} & \multirow{2}{1.3cm}{\centering Scanpath Ratio $\bm{\uparrow}$} & \multirow{2}{1.2cm}{\centering TFP- AUC $\bm{\uparrow}$} & \multirow{2}{1.7cm}{\centering Probability Mismatch $\bm{\downarrow}$} & \multicolumn{4}{c}{MultiMatch $\bm{\uparrow}$} \\ \cline{6-9} & & & & & shape & direction & length & position\\ \Xhline{1.2pt} IRL, 20 ipc & 0.415 & 0.808 & 4.324 & 1.140 & 0.875 & 0.672 & 0.832 & 0.879\\ CNN, 20 ipc & 0.408 & 0.723 & 3.906 & 1.325 & 0.884 & 0.664 & 0.849 & 0.878\\ \hline IRL, 10 ipc & 0.409 & 0.774 & 4.029 & 1.318 & 0.881 & 0.591 & 0.851 & 0.819\\ CNN, 10 ipc & 0.397 & 0.678 & 3.542 & 1.657 & 0.877 & 0.594 & 0.847 & 0.821\\ \hline IRL, 5 ipc & 0.389 & 0.723 & 3.696 & 1.603 & 0.876 & 0.588 & 0.844 & 0.813\\ CNN, 5 ipc & 0.388 & 0.678 & 3.484 & 1.731 & 0.886 & 0.594 & 0.862 & 0.828\\ \end{tabular} \end{center} \vskip -0.2in \caption{{\bf Data efficiency of IRL and CNN}. ``ipc'' means images per category used for training. For exmaple, IRL 10 ipc means we train the IRL model using 10 images from each category which are randomly selected from the training data. CNN and IRL are trained and tested on the same images for fair comparison.} \label{table:data_efficiency} \end{table*} \subsection{Additional Experiment Results}\label{sec:results} \myheading{Cumulative distribution of sequence scores}. In the main paper we reported the {\it average} Sequence Score of 0.422 for the scanpaths generated by the IRL model. To put this in perspective, \Fref{fig:seq_score_cdf} plots the cumulative distribution of the sequence scores and shows four qualitative examples that have sequence scores of 0.33, 0.40, 0.50, and 0.75, respectively. \myheading{Comparing different state representations}. To evaluate the benefits of having DCB as the state representation, we compared its predictive performance with the Cumulative Foveated Image (CFI)~\cite{zelinsky2019benchmarking} under the same IRL framework. CFI is created by extracting CNN feature maps on the retina-transformed images which are progressively more blurred based on the distance away from the currently fixated location. On the other hand, the DCB is created by extracting panoptic segmentations~\cite{kirillov2019panopticfpn} on uniform-blur images which are uniformly blurred except around the fixated region (the level of blurriness applied in DCB is close to the middle level in the blur pyramid of CFI \cite{zelinsky2019benchmarking,huang2015salicon,perry2002gaze}). For a fair comparison, we extract features for CFI using the backbone ResNet-50-FPN network from the Panoptic-FPN \cite{kirillov2019panopticfpn} that was used in DCB. Both DCB and CFI have the same spatial resolution of \htimesw{20}{32}. As shown in \Tref{table:cfi_cmpr}, the IRL model with DCB achieves significantly higher search efficiency and scanpath similarity than when using CFI as state representation. Specifically, DCB reduces the search gap by approximately 45\% and improves the scanpath ratio from 61.9\% to 82.6\%, much closer to the human behavioral ratio of 86.2\%. This result is even more impressive considering the size differences between the policy network used with DCB and CFI: DCB is trained with a smaller policy network, since it is comprised of 134 channels, nearly 8x smaller than CFI of 1024 channels. In our experiment, the policy network with CFI state representation has 29.6M parameters, while the policy network with DCB state representation only has 0.3M parameters. Relatedly, another benefit of having DCB as state representation is that it is memory and operation efficient. Creating DCB requires a smaller computational cost than creating CFI, since there's only a single level of blurriness in DCB and extracted panoptic segmentation maps are smaller by an order of magnitude than the feature maps extracted for CFI. Given that IRL models are particularly difficult to train in high dimensional environments~\cite{tucker2018inverse}, having an efficient representation like DCB can be very helpful. \myheading{State Ablation}. DCB is a rich representation that incorporates top-down, bottom-up, and history information. The full representation consists of 136 belief maps, which can be divided into five groups: target object (1 map), ``thing'' (object, 79 maps), ``stuff'' (background classes, 54 maps), saliency (1 map, extracted using DeepGaze2 \cite{kummerer2017understanding}), and history (1 binary map for the locations of previous fixations). To understand the contribution of each factor, we removed the maps of each group one at a time and compared the resulting model's performance. As shown in \Tref{table:abalation}, target object and ``thing'' maps are the most critical for generating human-like scanpaths, followed by ``stuff'' maps, whereas saliency and history do not have strong impact to the model performance. \myheading{Greedy vs. Non-greedy search behavior}. How does human search behavior compare to generated scanpaths reflecting either Greedy or Non-greedy reward policies? Under the greedy policy, the selection of each location to fixate during search reflects a maximization of immediate reward. But the greedy policy is highly short-sighted -- it only seeks reward in the short term. Non-greedy reward seeks to maximize the total reward that would be acquired over the sequence of fixations comprising a scanpath. This policy therefore does not maximize reward in the near term, but rather allows more exploration that leads to higher total reward. As shown in \Tref{table:greedy_cmpr}, we generated greedy and non-greedy policies from our IRL model and compared their predictive performance on human scanpaths. The results show that 1) models using greedy vs. non-greedy policy produce different search behaviors, with the model using non-greedy policy generating more human-like scanpaths by all tested metrics. This is an interesting finding. Despite the high efficiency of human search in our study (1-2 sec), the search process was strategic in that the fixations maximized total reward, even over that short period of time. \myheading{Data Efficiency}. Table \ref{table:data_efficiency} shows the full results of IRL and BC-CNN given different numbers of training images across different metrics. Both use DCB as the state representation. The results are consistent with the results presented in the main paper and suggest that IRL is more data-efficient when compared to the CNN -- IRL achieved comparable or better results than the CNN using less training data.
{'timestamp': '2020-06-26T02:12:40', 'yymm': '2005', 'arxiv_id': '2005.14310', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14310'}
arxiv
\section*{Abstract} Perceptual illusions based on the spatial correspondence between objects and displayed images have been pursued by artists and scientists since the 15th century, mastering optics to create crucial techniques as the linear perspective and devices as the \textit{Magic Lantern}. Contemporary video projection mapping inherits and further extends this drive to produce perceptual illusions in space by incorporating the required real time capabilities for dynamically superposing the imaginary onto physical objects under fluid real world conditions. A critical milestone has been reached in the creation of the technical possibilities for all encompassing, untethered synthetic reality experiences available to the plain senses, where every surface may act as a screen and the relation to everyday objects is open to perceptual alterations. \section*{Introduction} The advancement and popularization of computer technologies over the past three decades has had a significant effect not only on the way images are created, but also on the techniques and technologies which enable their presentation. One of the most popular emerging practices is video projection mapping, also referred as video mapping or 3D mapping, a terminology which stands for a set of imaging techniques in service of the spatially coherent projection of bi dimensional images onto physical three dimensional objects~\cite{yun,naimark1}. Despite its seemingly novelty in its use in the fields of communication, advertising and visual arts in the recent years, the current practice of video projection mapping is the result of several centuries of development and perfecting of a vast set of techniques derived from optics and the sciences of human perception, as well as mathematical operations for image transformations, and the evolution projection devices. Across all these periods in history, the production of perceptual illusions remains as the fundamental shared goal, of which important milestones are the invention of linear perspective techniques and its application in \textit{Trompe l'oeil} and \textit{Quadratura} installations during the Renassaince, the immersive theatrical qualities of \textit{Panorama} and \textit{Phantasmagoria} in the 18th century, the development of real time 3D computer rendering capabilities and the popularization of video projection mapping during the last part of the 20th century. The present article analyzes the evolution of video projection mapping in relation to the history of perceptual illusion practices, considering common design methodologies, tools, and implemented techniques, in a transversal selection of scientific and artistic practices, spreading from static compositions on a canvas, to dynamic substitutions in three dimensional space. A commentary on the emerging perceptual and cognitive phenomena as a result of the spatial distribution of synthetic contents is provided, presenting the notion that the current stance of real time dynamic forms of video projection mapping constitutes a turning point in the quest for replacing the real world with synthetic versions that would offer unprecedented means for visual identity and meaning transformations beyond material constraints. \section*{Spatial illusion in the Renassaince} Before the 14th Century few attempts were made to create the illusion of three dimensional space and to realistically depict the spatial world in art. The Italian masters Giotto and Duccio during the late thirteenth and early fourteenth centuries, began to explore the idea of depth and volume in their artwork, and may be credited with introducing an early form of three dimensional painting, using shadows and contrasts in colors to create the perceived illusion of depth~\cite{giotto,schet}. Although it was still very far from the accurate and robust three dimensional representations popular in imagery today, this technique known as \textit{Chiaroscuro} helped artists to create the illusion of volume and depth. Popularized during the beginning of the fifteenth century, Chiaroscuro was mastered especially for the processes of modeling and representing the human body and was extensively used during the sixteenth and seventeenth centuries in the Mannerism and Baroque eras as one of the standards for approximating three dimensional representation. Not satisfied with the state of the art, Florentine painters of the early fifteenth century, wanted to develop painting as a science derived from Euclidean geometry influenced by the Neoplatonic intellectual postulates. In this sense, they did not conform with the intuitive Chiaroscuro technique, but sought scientific methods of representing reality based on mathematical laws, thus giving birth to the knowledge that ultimately led to the devise of the linear perspective system. The linear perspective system projected the illusion of depth onto a two dimensional plane by use of vanishing points to which all lines converged at eye level on the horizon, accurately reproducing the way that objects appear smaller when they are further away, and the way parallel lines appear to meet each other at a point in the distance. Between 1415 and 1420, the Italian architect Filippo Brunelleschi, considered one of the founding figures of the Renassaince, conducted and documented a series of experiments which helped him develop the correct perspective techniques for accurately representing three dimensional volumes on a flat canvas. One of its results portrayed in accurate spatial proportion and organization, the Florence Baptistery and the Palazzo Vecchio building seen from the front gate of the unfinished cathedral, affording to the spectator the full illusion of being present in the scene. These technical advancements where later systematized by Leon Battista Alberti in his 1436 work \textit{De Pictura}, one of the most important treatises on painting of the Renaissance, enabling artists for the first time to paint imaginary scenes with perfectly accurate three dimensional realism by following the set of rules of perspective studied by Brunelleschi~\cite{albert, alberti2,dunning, brock15}. Gradually, a standardized model of human visual perception was consolidated, from which a set of mathematical rules was derived and applied to govern the disposition of pictorial elements in order to produce a credible illusion of three dimensionality. \\ For the next five centuries, Brunelleschi’s system of perspective and its derived techniques were used to create the illusion of depth on the picture plane, and served as the basis of some of the great art of Western culture~\cite{gablik,gombrich, verstegen}. Among the earliest of those, The Brera Madonna created between 1472 and 1474 by the Italian artist Piero della Francesca. It is a large painting depicting a group of religious figures and icons at a fictitious apse of the church, meticulously rendered using the innovations of linear perspective techniques. But not only did perspective techniques allowed to produce a coherent illusion of space on a flat surface, but perspective was also used to organize and highlight particular elements of the composition, thus allocating meaning in relation to specific spatial positions in the canvas~\cite{banker, shw}. For example, the geometric center of the face of the main character coincides with the vanishing point of the perspective system used in the scene, as well as the egg which hangs from a shell - shaped element below the apse, is perfectly aligned with the scene's vanishing point and marks a perpendicular line to the scene's horizon. Tommaso di Ser Giovanni di Simone, best known as \textit{Masaccio} and regarded as the first great Italian painter of the \textit{Quattrocento} period of the Italian Renaissance, painted \textit{The Holy Trinity} in 1425 in the dominican church of Santa Maria Novella in Florence. This pioneering mural painting not only accurately presented the illusion of three dimensions using linear perspective techniques, but also engaged in a coherent composition with the pre existing architectural elements that surrounded the mural, mixing three dimensional painted and architectural elements to enhance the illusory effect. This specific type of illusion supported by the coherent merger between painting techniques and architectural elements was known as Quadratura~\cite{masa}. Artist Andrea Mantegna further experimented developing illusionistic ceiling paintings using perspective techniques to create the perceptual illusions and was responsible in 1465 for one of the most significant examples of Quadratura. Located in the Camera degli Sposi in the Ducal Palace of Mantua, this Trompe l'oeil was applied to ceiling paintings to be seen by spectators from below and upward and presented the illusionistic painting of an oculus that opens to the sky and a number of fictional characters who look down towards the spectators~\cite{wade}. Performed by Andrea Pozzo in 1688, \textit{The Apotheosis of St Ignatius} in Sant Ignazio in Rome is another remarkable example of Quadratura, presenting in a 55 feet wide ceiling a composition combining fictional characters and architectural elements. A new type of site specific art form began maturing, unifying architecture, painting and sculpture, and being conveyed to spectators by means of a full body spatial experience. In a sense, this almost theatrical experience was prescient of the aesthetic ideals of \textit{Gesamtkunstwerk}, postulated years later in mid nineteenth century by the German opera composer Richard Wagner. \section*{Panorama and Phantasmagoria} Baroque painters from seventeenth century, notably Caravaggio, Bernini, Rubens, Rembrandt, Velazquez and Vermeer, used the now long established three dimensional representation system in hundreds of varied approaches, as did the painters from the Neoclassicist movement, of whom a notable example is the work of Giovanni Batista Piranesi. \textit{Carceri d'invenzione}, a series prints produced between 1745 and 1761 by Piranesi depicting somber fictional scenes full of mysterious characters, bridges, stairs and mechanisms, trough meticulous utilization of the perspective technique. However, few artists during these decades shared the interest for the experimentation and development of perceptual illusions via spatial experience. In this sense, a major referent is the work of Robert Barker, an Irish painter that developed the idea of erecting a circular plan building to house near real scale paintings featuring panoramic landscapes. In 1792 the Panorama was born, supported on the knowledge on perspective and color contrast practiced during the last two centuries, its paintings covered 360 degrees around the spectator in the horizontal plane and reached 15 meter of height. Soon, Barker's Panorama grew in size and complexity, and the circular plan installation incorporated topographies and architectural and elements intended to match the painted scene thus increasing its illusory effect in a similar way as Quadratura incorporated architectural elements to its composition. This way, flooring, stairs, railings, water fountains or other urban furniture, not only to regulate the displacements of spectators inside the building, but more importantly, to serve as immersive cues, formal and semantic links between the depicted scenes and the notion of what was accountable as real world experience~\cite{panorama, flieth}. The Panorama continued its popularization in most of Western Europe and North America as an entertainment form, successfully hosting the representation of famous historical battles for the great public. In a time when few people could afford to travel, the Panorama allowed to walk through distant landscapes and contemplate historical events from privileged points of view, pioneering in a primitive form of narrative distributed in space and time, in a sense similar as it is now possible to explore in a virtual reality experience or a video game~\cite{finn,finn2}. During the precedent decades, the rapid increase of knowledge in optics was not only useful for development and use of perspective related techniques, but also supported a number of relevant inventions regarding optical instruments, among those, light reflection and projection devices. The Jesuit Athanasius Kircher in his book \textit{Ars Magna Lucis et Umbrae} from 1645, described a primitive projection system with a focusing lens and a concave mirror reflecting sunlight that served as canvas to display text or pictures known as the \textit{Steganographic Mirror}. Further elaborating, dutch scientist Christiaan Huygens in 1659 documented the invention of the \textit{Magic Lantern}, an early type of image projector that used semi transparent, hand painted glass plates, one or more lenses, and a light source~\cite{swan}. The Magic Lantern was then consolidated, and increasingly used for education and entertainment purposes during the 18th century~\cite{kember}. In this period, although the basic design of the Magic Lantern suffered various modifications in relation to the light source capabilities and the characteristics of lenses in use, its main fundamental concept remain unchanged as well as its basic operation. By the end of 18th century, Belgian Physicist and cleric Ettiene Gaspar Robert, and one of the first lanternists of all time Paul Philidor, created a new form of illusion performance in the form of a Magic Lantern show known as Phantasmagoria, a theatrical show that consisted of a mixture of frontal and retro projection of images, from simultaneous magic lanterns, on canvases and solid elements in front of the sitting public~\cite{hecht, barber, phanta}. During the 19th century, the invention was further sophisticated, with more powerful light sources, incorporation of photographic impressions onto glass plates, improvements in optics, and mechanisms that allow the projection of sequences of images, helping consolidate the expressive maturity of a new type visual spectacle still greatly influenced by the use of perspective and contrast in colors to achieve volumetric realism~\cite{clarke}. Following this theatrical illusory tradition, Louis Daguerre in 1822 developed the \textit{Diorama} for a light based type of scene representation device, that featured two immense paintings and various interchangeable moving elements, such as human figures, animals or fictional characters, lit from the front and through the back inside an otherwise pitch black, rotating auditorium. The Diorama combined techniques of opaque and translucent painting and manipulating light in a live spectacle, with color contrast and perspective techniques, to produce a plausible scene with accurate spatial representation. In a large scale version, the Diorama frame could reach 10 meter wide and feature interposing translucent elements of different opacities and colors, actuated by means of ropes that affect the color tone of selective parts of the frame, for example, to simulate intense fog or the shining sun~\cite{Hankins}. A few decades later, the German theater director and producer Erwin Piscator developed the most consistent scenography experiments using the technological possibilities of the early 20th century to support epic theater works emphasizing the socio political content of drama. Notably, his early production \textit{St\"urmflut} from 1926 the stage was composed by a translucent background screen in a solid black frame with variable aperture serving as background displaying supporting images from four retro projectors for performing artists. \section*{Performatic spacetime} Although most of the works of Impressionist painters such as Renoir, Sisley, Monet and Pissarro and Post Impressionists such as Van Gogh, Gauguin and Seurat also depended on these mimetic spatial representation techniques, a significant transformation took place in the broad scientific and artistic domains at the end of the nineteenth century. It challenged the absolute centralized perspective standard, in which the images orbited around the static spectator's eye, increasingly giving way to the development of the multiple viewpoints systems, which aimed to capture time lapses in which the scene should be considered not as static but in motion. The idea of multiplicity in viewpoints was mainly developed in the arts by the Cubist movement, fundamentally Picasso and Braque in their invention of techniques such as faceting, passage and multiple perspective. This type of representations of multiple viewpoints in space and time, fused in one single image, consolidated as one of the movement's most acclaimed traits. Importantly, these innovations may be interpreted as the movements' critical philosophical stance regarding perspective and the capacity of human beings to faithfully grasp and represent reality. For the Cubists, art would not serve to be a mimesis of reality, as an objective mirror snapshot of \textit{what is there}, but would serve to represent things as experienced in space and time, a subjective snapshot of \textit{what is sensed}. This new method aimed to account for change and flux in a scene, and create a performative situation in which the interpretative role of the spectator becomes central to the evocative power of the Cubist's images~\cite{edgerton}. Following these lines, Albert Gleizes and Jean Metzinger in the 1912 book \textit{Du "Cubisme"}, the first major text on Cubism, explicitly related the pursue of multiple perspective to an attempt to understand time as a continuum. This may be interpreted as giving symbolic expression to the notion of duration proposed by the philosopher Henri Bergson, according to which, life is subjectively experienced as a continuum, with the past flowing into the present and the present merging into the future~\cite{cubisme,bergson}. Early Futurist paintings by Umberto Boccioni, Giacomo Balla or Gino Severini where also highly influenced by this search for multiple perspective and simultaneity. This technique of representing multiple viewpoints in space and time is advanced in complexity and scale in Gleizes' \textit{Le Dépiquage des Moissons}, displayed at the 1912 \textit{Salon de la Section d'Or}, and Robert Delaunay's City of Paris, exhibited at the \textit{Indépendants} in 1912. As the invention of linear perspective in fifteenth century Renaissance was a major manifestation of the establishment of the strong anthropocentric interpretation of the world, in which the whole of its Science and Philosophy was founded upon, the multiple perspective paradigm that arrived at the dawn of the 20th century marked the ultimate disenchantment of human as the measure of all things, welcoming novel ideas from Physics regarding the nature of space and time, as well as the atom and atomic dynamics, which ultimately favored many of the ideas that shaped the following decades: The relative over the absolute, multiplicity over centralization, dynamic co creation over pre determination~\cite{lepenies}. Whereas Renaissance artists strove to represent the real by offering viewers an archetypical perceptual illusion, Cubist illusionism subverts this kind of realistic representation by calling attention to its own artifice, to its own perspectival manipulations, and thus to the problematic nature of representation and illusion. \section*{Expanded cinema} During the 1950's The Czech artist Josef Svoboda pursued a type of non verbal theatrical format where actors perform in harmony along with moving images projected by a set of Magic Lanterns and elements of the scenography that supported the performative meaning production. This poetic synthesis of traditional methods with technical innovation including architecture, dance, cinema and theater, that in a sense revived Richard Wagner's \textit{Gesamtkunstwerk}, secured Czechoslovakia's best score in the Brussels World Exhibition of 1958. Svoboda not only mastered the classical perspective and color contrast techniques to put adequate spatial illusion in action on the stage, but also multiplied its evocative power by profiting from the emerging interactions between the characteristics of the selected physical elements, the performing actors and the content of the projected images in the composition~\cite{burian}. Moreover, part of this new theatrical format was Svoboda's \textit{Polyekran}, a multi projection system, consisting of screens of various shapes and dimensions suspended with steel cables in arbitrary angulations on a black background. Eight projectors of slides and seven movie projectors, along with synchronized stereo helped completing this instrument in service of the total work of art.\\ The immersive quality of spatially distributed images was also among the interests of the experimental filmmaker Stan VanDerBeek , who between 1963 and 1965 developed his \textit{Movie Drome}, a type of semi spherical theater where people would lie down and experience movies all around them. Notably, influenced by Buckminster Fuller’s dome constructions and Robert Barker's Panorama public installations, VanDerBeek envisioned the Movie Drome as a prototype for a global two way communication system consisting of a network of Movie Dromes linked to orbiting satellites that would store and transmit images between them. Although far from fully accomplishing it vision, Movie Dromes did put in place a new set of challenges for the traditional use of perspective and linear narratives to represent reality. Instead, VanDerBeek presented a multiple perspective design, that achieved multiple gazes over multiple simultaneous events, resulting in a fragmented non linear narrative, a spatially distributed moving image collage~\cite{sutton,ferguson}. Distinct from traditional cinema, this new type of experience sometimes characterized as \textit{Expanded Cinema}~\cite{youngblood} had a clear emphases on breaking the cinematography from its linear and concentrated constraints to give way to a non linear, distributed in space, multi sensory experience, aimed at a type of audience engagement that anticipates contemporary art's interactivity and participatory practices. Audience engagement produced by carefully controlled perceptual illusions was also researched for popular entertainment purposes. As a proof, on 9 august 1969 the doors to the \textit{Haunted Mansion} spectacle at Disneyland opened to the public, featuring a number of light based perceptual illusions placed inside a three story Victorian house structure built in the New Orleans Square in Disney's Adventure Park in California. The project gathered the works of artists and storytellers Yale Gracey, Marc Davis, Claude Coats, Xavier Atencio and among those, Rolly Crump's innovative \textit{Singing Busts} installation~\cite{disney}. This work consisted of five singing busts, brougth to life by the \textit{Grim Grinning Ghosts} actors, pre recorded in 16mm film singing the theme song of the ride, and then projected onto the plaster busts modeled after each character. By controlling the lighting and contrast of the scene, together with the predetermined path and vantage point of user's, the designers could obtain an unprecedented multi sensory illusion that may be considered as direct precursor of current virtual and augmented reality paradigms.\\ Since the mid 1980s, numerous examples exist of re enactment of cinematographic scenes by the use of video sequences in combination with immersive objects and architectures. Among those the works of Tony Oursler who as one of the key figures in the development of video art experimented early on with the moving image that extended beyond the borders of the TV monitor~\cite{kaye}. Oursler used projections on sculptures and specially crafted scenographic installations. His early 1990s dolls and dummy works or \textit{Troubler} from 1996, rely entirely in the spatial and semantic correspondence between projected film and dolls which are strongly anthropomorphized~\cite{london}. Using centuries old knowledge on optics and perception, controlling light and shadow and the spectator's point of view Oursler mastered a unique type of cinematographic composition based on the combination of found objects, life-like moving faces and archetypal elements coming into life by virtue of the superimposed projected narratives~\cite{malt}.\\ Michael Naimark, is one key multimedia artist and researcher who has also explored spatialized representation. His \textit{Displacements} intallation, developed from 1980 to 1984, further advanced the spatial and semantic interactions between images and surfaces, and is considered among the most important seminal works in this domain. An immersive installation that projected a pre recorded 16mm film on an archetypal living room completely covered in white paint, matching the spatial location of the projected images with selected objects of the living room. The projector located on a rotating turntable at the room's center slowly directed the spectators' gaze towards the unwrapping narrative, with the appearance of the characters and objects as three dimensional. Artist Jeffrey Shaw has also undertaken since the late 1960s, research on types of Expanded Cinema and the development of various innovative spatial illusion strategies. For example \textit{Corpocinema} from 1967, involved projection into a dome, and the {Diadrama} from 1974 was projected onto a 180 degree screen surrounding the audience. In its theatrical form, an example of the combination of ancient perspective and contrast techniques with contemporary spatialized narratives to bring three dimensional realism to life is the opera \textit{Le Grande Macabre} by Fura dels Baus. Premiered in Brussels in March 2009, the company made use of the correspondence of projected images and physical objects, profiting from the emerging frictions between the projected images and a large scale anthropomorphic figure that mutates in identity and function within the play. The proposal of Fura dels Baus intends to avoid mimesis, and rather than repeat reality, aims at constructing a type of illusory live experience~\cite{fura}. Several remarkable examples are found in the works of Robert Lepage, and among them, \textit{Needles and Opium}, which narratively relies on an strong engagement with the space, thus the need for a careful representation of location and context within a semi cubic structure that serves as a group of screens that mutate according to the needs of each scene~\cite{pluta}. The use of these types of neutral spatial cavities that serve as immersive screens has grown in popularity during the last decade. In 2012, as part of a marketing campaign for the Sony Playstation products, the agency Marshmallow Laser Feast presented the video mapping of an entire living room using choreographed live puppetry, controlling every element in the scene and performed in front of a non stop recording camera. The resulting recorded performances offered a high degree of illusion while consolidating the archetypical centralized and predetermined viewpoint, in this case, the viewpoint of the non stop recording camera. \subsection*{Interactive virtuality} The advent and popularization of the interactive computing technologies, a variety of spatialized works of art speculate in the direction of producing full body perceptual illusions no longer tied to the spectator's spatial positions and viewpoints predetermined beforehand, but affording contents that interact with the user, whose three dimensional representations are dynamically adjusted to the view point of the user in real time~\cite{svoboda, szel, majum}. From this point on, a significant part of research from academic and industry related fields, coincided in the aim for developing techniques and devices for visually compositing virtual objects within real environments, with ever increasing interactive faculties for spectators to become co participants. A significant advance was made in this regard by Carolina Cruz Neira, Daniel J. Sandin, and Thomas A. DeFanti at the University of Illinois, Chicago Electronic Visualization Laboratory in 1992. They presented the notion of \textit{CAVE} acronym for \textit{Cave automatic virtual environment}, a semi cubic installation made up of rear high resolution projection screen walls and floor, and a motion capture system that allowed users to interact by physical movements~\cite{cruz, cruz2,prince}. In 1995 a team of researchers from The University of North Carolina at Chapel Hill, including Ramesh Raskar, Greg Welch, and Henry Fuchs presented The office of the future a type of CAVE application not supported on retro projected surfaces but projection on real office surfaces and objects, moreover incorporated real time computer vision techniques to dynamically extract per pixel depth and reflectance information for the visible surfaces in the office including walls, furniture, objects, and people, and then to either project images on the surfaces, render images of the surfaces, or interpret changes in the surfaces~\cite{raskar, raskar3, wye}. In 2006 Shaw initiated research into a fully 360 degree 3D projection system at the UNSW iCinema Research Centre, a centre directed by Shaw and co founded with Dennis Del Favero. AVIE \textit{Advanced Visualisation and Interaction Environment} was first installed in the UNSW Scientia building in 2003 and presented a paradigm that allowed the exploration of 360 degree panoramic projected images, within an architectural framework that correlated the design of the virtual landscape with that of the installation itself, thus simultaneously co activating the virtual representations and the real materials of the projection space. This installation also introduced a fundamental level of user control, allowing the viewer to control the rotation of a projected window. The design of AVIE follows the traditions of the Panorama, as well as the search for embodied impact of the Baroque Tromp l'oeil fresco painting techniques ~\cite{shaw2, Shaw2003}. One remarkable implementation example is \textit{The Pure Land: Inside the Mogao Grottoes}, a project by Sarah Kenderdine and Jeffrey Shaw working in the University City Honk Kong in 2012. Using digitization data from the Mogao Grottoes in China this installation emphasizes the spatial illusion via pano­ramic immersion and coherent image display techniques~\cite{mogao}. The contents are staged in a 10 meter diameter by 4 meter high cylindrical AVIE theater, while a handheld interface provides interaction with the rendered images, allowing the user to volitionally reveal key parts of the mural paintings on its walls. These real scale interactive visual display systems allowed the research on the domain of the spatial illusion of reality and helped set the foundations for projector based \textit{Augmented Reality} in the following decades. As defined, Augmented reality aims at building systems that enhances the real world by superimposing computer generated information on top of it, in one or more sensory modalities~\cite{wellner,asselin,billin, caudell}. In its projector based form, Augmented Reality shares the aim to generate perceptual illusion untethered and available to the plain senses, by using synthetic information displayed on real world locations, but distinguishing from mere spatialized motion image in the strong interactive component of the experience~\cite{bimber1, bimber2}. \section*{Living virtuality} In the last decades one of the most interesting objects for projector based synthetic augmentation has been the human body. In a collaboration between 1998 and 2002 choreographer Chris Haring and Vienna based director and composer Klaus Obermaier, created two multimedia dance performances, D.A.V.E and Vivisector, that have used the dancer's body as the primary projection surface pre choreographed projections on performers skins that led spectators to believe that the bodies of performers were dramatically reshaped and altered in real time~\cite{ ploe, emph,Dourish2001}. In 2004 together with Ars Electronica Futurelab, Obermaier developed and premiered Apparition, an interactive dance and media performance featuring Desirée Kongerød and Rob Tannion whose movements on stage are captured using an infrared camera and suited with adequate images generated in realtime.\\ At the 8th IEEE International Symposium on Mixed and Augmented Reality ISMAR in 2009, a team of researchers including Greg Welch, Henry Fuchs from The University of North Carolina at Chapel Hill, introduced Shader Lamps Avatars as a new approach for creating a video projected three dimensional avatar using faces of real people. Based on cameras and projectors to capture and map the dynamic motion and appearance of a real person onto a humanoid life sized styrofoam head mounted on an animatronic device, the system delivers a dynamic, real time representation of a person to multiple viewers~\cite{ismar1,ismar2}. In a similar quest, a collaboration between Japanese media artist Nobumichi Asai, make up artist Hiroto Kuwahara and digital image engineer Paul Lacroix resulted in the Omote project in 2014, using projection mapping techniques to put make up and effects onto a model's face in real time. By using a set of infrared markers painted on the model's face, the team was able to capture and process marker position, estimating face position and orientation, rendering face CG model with animated texture upon, and finally send the image through the projector. This face changing system brings to life a fluid stance of identity in a way similar to the ancient Bian Lian techniques that allow Sichuan Opera's performers to unperceivably change masks in front of spectators. Further advancing these achievements, The Ichikawa Senoo Laboratory from the University of Tokio aimed in 2015 at overcoming the limited static or quasi static conditions required for video projection mapping. A dynamic projection mapping system was developed, capable of adjusting images in real time onto deforming non rigid surfaces. To this end, the team led by Gaku Narita, Yoshihiro Watanabe, and Masatoshi Ishikawa developed two set of technologies addressing the system's main challenges~\cite{narita, narita2}. First, \textit{Deformable Dot Cluster Marker}, a robust infrared acquisition method for capturing deformations from the surface, even capable of handling large deformation and occlusions. Second, a high speed projector system was developed, \textit{DynaFlash}, capable of displaying 8 bit images in frame rates up to 1,000fps with unprecedented 3 milliseconds latencies. These two innovations mark a breakpoint in the quest for spatially distributed illusion, achieving the perceptual effect as if the projected images were printed onto the target surface. The Ichikawa Senoo Laboratory further demonstrated in 2016 their dynamic projection mapping systems actuating onto a deformed sheet of paper and T shirt on one or multiple targets. Considering the possibility for embedding active or passive markers in clothing and everyday objects~\cite{fibar}, these advancements could represent the novel technical feasibility for most surfaces in the real world to become screens, displaying perceptual illusions coherently and seamlessly~\cite{kott, jasch, borra, landi}. \section*{Conclusions} Video projection mapping has been an important step in the evolution of spatially based perceptual illusionism, and on the base of the evolution of its associated techniques and idiosyncrasies a great variety of research lines have been developed, as well as entertainment and artistic applications. Having mastered linear perspective, color contrast, and vantage point control in order to produce static realistic spatial three dimensional representations, in recent years video projection mapping systems paired with computer vision systems have acquired the capability of user interaction and of dynamically adjusting the spatial characteristics of the images in order to achieve almost perfect correspondence between projected contents and physical space. Considering video projection mapping as an intermediate stance in the reality - virtuality continuum~\cite{Milgram1994}, it has been shown to produce at least two types of observable results that occur almost simultaneously~\cite{Pfeiffer2013Multisensory,yun2011}. The first occurs at a sensory level, in which the shape, color and texture properties of the physical surfaces are incorporated by the superimposed images or wane in its benefit. For example the visitors of the Camera degli Sposi are deceived into believing that a two dimensional solid surface such as a brick wall disappears to give way to a different landscape in perfect harmony with the existing architecture. The face in the Omote's models can be suddenly full of make up, and the performers in Obermaier's works may seem to be suddenly in raw flesh. The second observable phenomena concerns the semantic level of interaction between imaginary contents and physical objects. Depending on the semantic load of each of the interacting elements, the merger between superimposed images and material supports may yield a varying degree of identity transference, as such, physical objects may contrast with projected images or completely assume its identity and its network of semantic associations. In these semantic agreement and opposition relationships, the visitors of the Camera degli Sposi may fall under the impression of being at the residence of a powerful dynasty whose decorated oculus attracts angels from the skies. The models in Omote project can suddenly appear to be skeletons or android humanoids, or it may result unimaginable to think on the bodies in Obermaier's Vivisector as human due to their unprecedented flexibility. Many steps have been taken in making the real world wane in favor of synthetic superpositions that increasingly become more present, in that every surface acts as a screen and every object contains potential of fluid identity and meaning hosted in the domain of virtual representations. As the production of perceptual illusions appear to be in full effect, new possibilities arise for new entertainment paradigms, spatially distributed learning applications, or massive dataset exploration tools that profit from the embodied cognition that results from spatial interaction with digital contents~\cite{Stahl2006,Stahl13}. Importantly, the relentless idea that fueled the quest for perceptual illusion and pervaded across centuries of artistic and scientific experimentation, seems to gain momentum at the current juncture in history: reality does not satisfy desire. \section*{Acknowledgments} Support provided Virtual Sense Systems and Hangar Centre for artistic research and production in Barcelona was greatly appreciated.
{'timestamp': '2020-06-01T02:03:58', 'yymm': '2005', 'arxiv_id': '2005.14317', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14317'}
arxiv
\section{Introduction} \begin{figure}[t] \centering \includegraphics*[scale=0.625, viewport=73 83 454 469]{figures/DWT-max_pooling.pdf} \caption{Comparison of max-pooling, max-unpooling, and wavelet transforms. Max-pooling is a common down-sampling operation in the deep networks, which easily removes the data details (the window boundary in area A) and breaks the object structure (the pole in area B). Based on the pooling indices, max-unpooling recovers the data resolution, but not the details. DWT keeps the object structure and saves the data details, while IDWT precisely recovers the original data using the DWT output. }\label{fig_MaxPooling_DWT_IDWT} \end{figure} Due to the advantage of deep network in extracting high-level features, deep learning has achieved high performances in various tasks, particular in the computer vision. However, the current deep networks are not good at extracting and processing data details. While deep networks with more layers are able to fit more functions, the deeper networks are not always associated with better performances \cite{he2016deep_resnet}. An important reason is that the details will be lost as the data flow through the layers. In particular, the lost data details significantly degrade the performacnes of the deep networks for the image segmentation. Various techniques, such as condition random field, \`atrous convolution \cite{chen2014semantic_deeplabv1,chen2018encoder_deeplabv3+}, PointRend \cite{kirillov2019pointrend}, are introduced into the deep networks to improve the segmentation performance. However, these techniques do not explicitly process the data details. Wavelets \cite{daubechies1992ten,mallat1989a_wavelet}, well known as ``mathematical microscope'', are effective time-frequency analysis tools, which could be applied to decompose an image $\textbf{\emph{X}}$ into the low-frequency component $\textbf{\emph{X}}_{ll}$ containing the image main information and the high-frequency components $\textbf{\emph{X}}_{lh}, \textbf{\emph{X}}_{hl}, \textbf{\emph{X}}_{hh}$ containing the details (Fig. \ref{fig_MaxPooling_DWT_IDWT}). In this paper, we rewrite Discrete Wavelet Transform (DWT) and Inverse DWT (IDWT) as the general network layers, which are applicable to 1D/2D/3D data and various wavelets. One can flexibly design end-to-end architectures using them, and directly process the data details in the deep networks. We design wavelet integrated deep networks for image segmentation, termed WaveSNets, by replacing the down-sampling with DWT and the up-sampling with IDWT in the U-Net \cite{ronneberger2015u_net}, SegNet \cite{badrinarayanan2017segnet}, and DeepLabv3+ \cite{chen2018encoder_deeplabv3+}. When Haar, Cohen, and Daubechies wavelets are used, we evaluate WaveSNets using dataset CamVid \cite{brostow2009semantic_CamVid}, Pascal VOC \cite{everingham2015pascal}, and Cityscapes \cite{cordts2016cityscapes}. The experimental results show that WaveSNets achieve better performances in semantic image segmentation than their vanilla versions, due to the effective segmentation for the fine and similar objects. In summary: \begin{itemize} \item We rewrite DWT and IDWT as general network layers, which are applicable to various wavelets and can be applied to design end-to-end deep networks for processing the data details during the network inference; \item We design WaveSNets using various network architectures, by replacing the down-sampling with DWT layer and up-sampling with IDWT layer; \item WaveSNets are evaluated on the dataset of CamVid, Pascal VOC, Cityscapes, and achieve better performance for semantic image segmentation. \end{itemize} \section{Related works} \subsection{Sampling operation} Down-sampling operations, such as max-pooling, average-pooling, and strided-convolution, are introduced into the deep networks for local connectivity and weight sharing. These down-sampling operations usually ignore the chassic sampling theorem \cite{nyquist1928certain}, which result in aliasing among the data components in different frequency intervals. As a result, the data details presented by the high-frequency components are totally lost, and random noises showing up in the same components could be sampled into the low resolution data. In addition, the object basic structures presented by the low-frequency component will be broken. Fig. \ref{fig_MaxPooling_DWT_IDWT} shows a max-pooling example. In the signal processing, the low-pass filtering before the down-sampling is the standard method for anti-aliasing. Anti-aliased CNNs \cite{zhang2019making} integrate the low-pass filtering with the down-sampling in the deep networks, which achieve increased classification acccuracy and better shift-robustness. However, the filters used in anti-aliased CNNs are empirically designed based on the row vectors of Pascal's triangle, which are ad hoc and no theoretical justifications are given. As no up-sampling operation, i.e., reconstruction, of the low-pass filter is available, the anti-aliased U-Net \cite{zhang2019making} has to apply the same filtering after normal up-sampling to achieve the anti-aliasing effect. Up-sampling operations, such as max-unpooling \cite{badrinarayanan2017segnet}, deconvolution \cite{ronneberger2015u_net}, and bilinear interpolation \cite{chen2014semantic_deeplabv1,chen2018encoder_deeplabv3+}, are widely used in the deep networks for image-to-image translation tasks. These up-sampling operations are usually applied to gradually recover the data resolution, while the data details can not be recovered from them. Fig. \ref{fig_MaxPooling_DWT_IDWT} shows a max-unpooling example. The lost data details would significantly degrade the network performance for the image-to-image tasks, such as the image segmentation. Various techniques, including \`atrous convolution \cite{chen2014semantic_deeplabv1,chen2018encoder_deeplabv3+}, PointRend \cite{kirillov2019pointrend}, etc., are introduced into the design of deep networks to capture the fine details for performance improvement of image segmentation. However, these techniques try to recover the data details from the detail-unrelated information. Their ability in the improvement of segmentation performance is limited. \subsection{Wavelet} Wavelets are powerful time-frequency analysis tools, which have been widely used in signal analysis, image processing, and pattern recognition. A wavelet is usually associated with scaling function and wavelet functions. The shifts and expansions of these functions compose stable basis for the signal space, with which the signal can be decomposed and reconstructed. The functions are closely related to the low-pass and high-pass filters of the wavelet. In practice, these filters are applied for the data decomposition and reconstruction. As Fig. \ref{fig_MaxPooling_DWT_IDWT} shows, 2D Discrete Wavelet Transform (DWT) decompose the image $\textbf{\emph{X}}$ into its low-frequency component $\textbf{\emph{X}}_{ll}$ and three high-frequency components $\textbf{\emph{X}}_{lh}, \textbf{\emph{X}}_{hl}, \textbf{\emph{X}}_{hh}$. While $\textbf{\emph{X}}_{ll}$ is a low resolution version of the image, keeping its main information, $\textbf{\emph{X}}_{lh}, \textbf{\emph{X}}_{hl}, \textbf{\emph{X}}_{hh}$ save its horizontal, vertical, and diagonal details, respectively. 2D Inverse DWT (IDWT) could reconstruct the image using the DWT output. Various wavelets, including orthogonal wavelets, biorthogonal wavelets, multiwavelets, ridgelet, curvelet, bandelet and contourlet, etc., have been designed, studied, and applied in signal processing, numerical analysis, pattern recognition, computer vision and quantum mechanics, etc. The \`atrous convolution used in DeepLab \cite{chen2014semantic_deeplabv1,chen2018encoder_deeplabv3+} is originally developed in the wavelet theory. In the deep learning, while wavelets are widely applied as data preprocessing or postprocessing tools, wavelet transforms are also introduced into the design of deep networks by taking them as substitutes of sampling operations. Multi-level Wavelet CNN (MWCNN) \cite{liu2019multi_MWCNN} integrates Wavelet Package Transform (WPT) into the deep network for image restoration. MWCNN concatenates the low-frequency and high-frequency components of the input feature map, and processes them in a unified way. The details stored in the high-frequency components would be largely wiped out via this processing mode, because the data amplitude in the components is significantly weaker than that in the low-frequency component. Convolutional-Wavelet Neural Network (CWNN) \cite{duan2017sar} applies the redundant dual-tree complex wavelet transform (DT-CWT) to suppress the noise and keep the object structures for extracting robust features from SAR images. The architecture of CWNN contains only two convolution layers. While DT-CWT discards the high-frequency components output from DT-CWT, CWNN takes as its down-sampling output the average value of the multiple low-frequency components. Wavelet pooling proposed in \cite{williams2018wavelet} is designed using a two-level DWT. Its back-propagation performs a one-level DWT with a two-level IDWT, which does not follow the mathematical principle of gradient. Recently, the application of wavelet transform in image style transfer \cite{yoo2019photorealistic} is studied. In these works, the authors evaluate their methods using only one or two wavelets, because of the absence of the general wavelet transform layers; the data details presented by the high-frequency components are abandoned or processed together with the low-frequency component, which limits the detail restoration in the image-to-image translation tasks. \section{Our method} Our method is to replace the sampling operations in the deep networks with wavelet transforms. We firstly rewrite Discrete Wavelet Transform (DWT) and Inverse DWT (IDWT) as the general network layers. Although the following analysis is mainly for orthogonal wavelet and 1D data, it can be generalized to other wavelets and 2D/3D data with slight changes. \subsection{Wavelet transform} For a given 1D data $\textbf{\emph{x}} \in \mathbb{R}^n$, DWT decomposes it, using two filters, i.e., low-pass filter $\textrm{f}_l$ and high-pass filter $\textrm{f}_h$ of an 1D orthogonal wavelet, into its low-frequency component $\textbf{\emph{x}}_l$ and high-frequency component $\textbf{\emph{x}}_h$, where \begin{equation}\label{eq_DWT_1D} \textbf{\emph{x}}_c = (\downarrow2)(\textrm{f}_c \ast \textbf{\emph{x}}), \quad c \in \{l,h\}, \end{equation} and $\ast$, $(\downarrow2)$ denote the convolution and naive down-sampling, respectively. In theory, the length of every component is $1/2$ of that of $\textbf{\emph{x}}$, i.e., \begin{equation} \textbf{\emph{x}}_c \in \mathbb{R}^{\lfloor \frac{n}{2} \rfloor}, \quad c \in \{l,h\}. \end{equation} Therefore, $n$ is usually even number. IDWT reconstructs the original data $\textbf{\emph{x}}$ based on the two components, \begin{equation}\label{eq_IDWT_1D} \textbf{\emph{x}} = \textrm{f}_l \ast (\uparrow2)\,\textbf{\emph{x}}_l + \textrm{f}_h \ast (\uparrow2)\,\textbf{\emph{x}}_h, \end{equation} where $(\uparrow2)$ denotes the naive up-sampling operation. For high-dimensional data, high dimensional DWT could decomposes it into one low-frequency component and multiple high-frequency components, while the corresponding IDWT could reconstructs the original data from the DWT output. For example, for a given 2D data $\textbf{\emph{X}} \in \mathbb{R}^{m\times n}$, 2D DWT decomposes it into four components, \begin{equation}\label{eq_DWT_2D} \textbf{\emph{X}}_{c_0c_1} = (\downarrow2)(\textrm{f}_{c_0c_1} \ast \textbf{\emph{X}}), \quad c_0, c_1 \in \{l,h\}, \end{equation} where $\textrm{f}_{ll}$ is the low-pass filter and $\textrm{f}_{lh}, \textrm{f}_{hl}, \textrm{f}_{hh}$ are the high-pass filters of the 2D orthogonal wavelet. $\textbf{\emph{X}}_{ll}$ is the low-frequency component of the original data which is a low-resolution version containing the data main information; $\textbf{\emph{X}}_{lh}, \textbf{\emph{X}}_{hl}, \textbf{\emph{X}}_{hh}$ are three high-frequency components which store the vertical, horizontal, and diagonal details of the data. 2D IDWT reconstruct the original data from these components, \begin{equation}\label{eq_IDWT_2D} \textbf{\emph{X}} = \sum_{c_0, c_1 \in \{l,h\}}\textrm{f}_{c_0c_1} \ast (\uparrow2)\,\textbf{\emph{X}}_{c_0c_1}. \end{equation} Similarly, the size of every component is $1/2$ size of the original 2D data in terms of the two dimensional direction, i.e., \begin{equation} \textbf{\emph{X}}_{c_0c_1} \in \mathbb{R}^{\lfloor\frac{m}{2}\rfloor\times\lfloor\frac{n}{2}\rfloor},\quad c_0,c_1\in\{l,h\}. \end{equation} Therefore, $m,n$ are usually even numbers. Generally, the filters of high-dimensional wavelet are tensor products of the two filters of 1D wavelet. For 2D wavelet, the four filters could be designed from \begin{equation}\label{eq_filter_2D} \textrm{f}_{c_0c_1} = \textrm{f}_{c_1} \otimes \textrm{f}_{c_0}, \quad c_0, c_1 \in \{l,h\}, \end{equation} where $\otimes$ is the tensor product operation. For example, the low-pass and high-pass filters of 1D Haar wavelet are \begin{equation}\label{eq_filter_2D} \textrm{f}_l^{\textrm{H}} = \frac{1}{\sqrt{2}} (1,1)^T, \quad \textrm{f}_h^{\textrm{H}} = \frac{1}{\sqrt{2}} (1,-1)^T. \end{equation} Then, the filters of the corresponding 2D Haar wavelet are \begin{align} \textrm{f}_{ll}^{\textrm{H}} &= \textrm{f}_l^{\textrm{H}} \otimes \textrm{f}_l^{\textrm{H}} = \frac{1}{2}\left[ \begin{array}{cc} 1&1\\1&1 \end{array}\right]\\ \textrm{f}_{hl}^{\textrm{H}} &= \textrm{f}_l^{\textrm{H}} \otimes \textrm{f}_h^{\textrm{H}} = \frac{1}{2}\left[ \begin{array}{cc} 1&-1\\1&-1 \end{array}\right]\\ \textrm{f}_{lh}^{\textrm{H}} &= \textrm{f}_h^{\textrm{H}} \otimes \textrm{f}_l^{\textrm{H}} = \frac{1}{2}\left[ \begin{array}{cc} 1&1\\-1&-1 \end{array}\right]\\ \textrm{f}_{hh}^{\textrm{H}} &= \textrm{f}_h^{\textrm{H}} \otimes \textrm{f}_h^{\textrm{H}} = \frac{1}{2}\left[ \begin{array}{cc} 1&-1\\-1&1 \end{array}\right] \end{align} Eqs. (\ref{eq_DWT_1D}), (\ref{eq_IDWT_1D}), (\ref{eq_DWT_2D}) and (\ref{eq_IDWT_2D}) present the forward propagations for 1D/2D DWT and IDWT. It is onerous to deduce the gradient for the backward propagations from these equations. Fortunately, the modern deep learning framework PyTorch \cite{paszke2017automatic} could automatically deduce the gradients for the common tensor operations. We have rewrote 1D/2D DWT and IDWT as network layers in PyTorch, which will be publicly available for other researchers. In the layers, we do DWT and IDWT channel by channel for multi-channel data. \subsection{WaveSNet} We design wavelet integrated deep networks for image segmentation (WaveSNets), by replacing the down-sampling operations with 2D DWT and the up-sampling operations with 2D IDWT. In this paper, we take U-Net, SegNet, and DeepLabv3+ as the basic architectures. \begin{figure}[bpt] \centering \subfigure[PDDS]{ \label{fig_dual_structure_Pooling_Deconv} \includegraphics*[scale=0.525, viewport=72 685 285 767]{figures/dual_structures.pdf} }\hspace{7pt} \subfigure[PUDS]{ \label{fig_dual_structure_Pooling_Unpooling} \includegraphics*[scale=0.525, viewport=72 479 285 561]{figures/dual_structures.pdf} } \caption{The dual structures used in U-Net and SegNet.}\label{fig_dual_structures} \end{figure} \begin{figure}[bpt] \centering \includegraphics*[scale=0.7, viewport=72 380 285 462]{figures/dual_structures.pdf} \caption{The wavelet based dual structure (WADS).}\label{fig_dual_structures_wavelet} \end{figure} \textbf{WSegNets}\quad SegNet and U-Net share a similar symmetrical encoder-decoder architecture, but differ in their sampling operations. We name the pair of connected down-sampling and up-sampling operations and the associated convolutional blocks as \textbf{dual structure}, where the convolutional blocks process the feature maps with the same size. Fig. \ref{fig_dual_structure_Pooling_Deconv} and Fig. \ref{fig_dual_structure_Pooling_Unpooling} show the dual structures used in U-Net and SegNet, which are named as PDDS (Pooling Deconvolution Dual Structure) and PUDS (Pooling-Unpooling Dual Structure), respectively. U-Net and SegNet consist of multiple nested dual structures. While they apply the max-pooling during their down-sampling, PDDS and PUDS use deconvolution and max-unpooling for the up-sampling, respectively. As Fig. \ref{fig_dual_structure_Pooling_Deconv} shows, PDDS copys and transmits the feature maps from encoder to decoder, concatenating them with the up-sampled features and extracting detailed information for the object boundaries restoration. However, the data tensor injected to the decoder might contain redundant information, which interferes with the segmentation results and introduces more convolutional paramters. PUDS transmits the pooling indices via the branch path for the upgrading of the feature map resolution in the decoder. As Fig. \ref{fig_MaxPooling_DWT_IDWT} shows, the lost data details can not be restored from the pooling indices. To overcome the weaknesses of PDDS and PUDS, we adopt DWT for down-sampling and IDWT for up-sampling, and design WADS (WAvelet Dual Structure, Fig. \ref{fig_dual_structures_wavelet}). During its down-samping, WADS decomposes the feature map into low-frequency and high-requency components. Then, WADS injects the low-frequency component into the following layers in the deep networks to extract high-level features, and transmits the high-frequency components to the up-sampling layer for the recovering of the feature map resolution using IDWT. IDWT could also restore the data details from the high-frequency components during the up-sampling. We design wavelet integrated encoder-decoder networks using WADS, termed WSegNets, for imag segmentation. Table \ref{Tab_network_configuration} illustrates the configuration of WSegNets, together with that of U-Net and SegNet. In this paper, the U-Net consists of eight more convolutional layers than the original one \cite{ronneberger2015u_net}. \begin{table}[!t] \scriptsize \begin{center} \setlength{\tabcolsep}{1.5mm}{ \begin{tabular}{c||l|r||c|c|c}\hline \multirow{3}{*}{data size} & \multicolumn{2}{c||}{the number of channels} & \multicolumn{3}{c}{networks} \\ \cline{2-6} & \multicolumn{1}{c|}{encoder} & \multicolumn{1}{c||}{decoder} &SegNet & U-Net & WSegNet \\ \hline $512\times512$ & 3, 64 & 64, 64 & PUDS & PDDS & WADS \\ $256\times256$ & 64, 128 & 128, 64 & PUDS & PDDS & WADS \\ $128\times128$ & 128, 256, 256 & 256, 256, 128 & PUDS & PDDS & WADS \\ $64\times64$ & 256, 512, 512 & 512, 512, 256 & PUDS & PDDS & WADS \\ $32\times32$ & 512, 512, 512 & 512, 512, 512 & PUDS & PDDS & WADS \\ \hline \end{tabular}} \caption{Configurations of U-Net, SegNet, and WSegNet.} \label{Tab_network_configuration} \end{center} \end{table} In Table \ref{Tab_network_configuration}, the first column shows the input size, though these networks can process images with arbitrary size. Every number in the table corresponds to a convolutional layer followed by a Batch Normalization (BN) and Rectified Linear Unit (ReLU). While the number in the column ``encoder'' is the number of the input channels of the convolution, the number in the column ``decoder'' is the number of the output channels. The encoder of U-Net and SegNet consists of 13 convolutional layers corresponding to the first 13 layers in the VGG16bn \cite{simonyan2014very_VGG}. A convolutional layer with kernel size of $1\times1$ converts the decoder output into the predicted segmentation result. \textbf{WDeepLabv3+}\quad DeepLabv3+ \cite{chen2018encoder_deeplabv3+} employs an unbalanced encoder-decoder architecture. The encoder applys an \`atrous convolutional version of CNN to alleviate the detailed information loss due to the common down-sampling operations, and an \`Atrous Spatial Pyramid Pooling (ASPP) to extract image multiscale representations. At the begin of the decoder, the encoder feature map is directly upsampled using a bilinear interpolation with factor of 4, and then concatenated with a low-level feature map transmitted from the encoder. DeepLabv3+ adopts a dual structure connecting its encoder and decoder, which differs with PDDS only on the up-sampling and suffers the same drawbacks. \begin{figure}[bpt] \centering \includegraphics*[scale=0.475, viewport=27 473 534 713]{figures/WDeepLabv3+.pdf} \caption{WDeepLabv3+ structure.} \label{fig_WDeepLabv3+} \end{figure} We design WDeepLabv3+, a wavelet integrated version of DeepLabv3+, by applying two wavelet version of dual structures. As Fig. \ref{fig_WDeepLabv3+} shows, the encoder applys a wavelet integrated \`atrous CNN followed by the ASPP, which output encoder feature map and two sets of high-frequency components. The encoder feature map is up-sampled by two IDWT, integrated with the detail information contained in the high-frequency components, while the two IDWT are connected with a convolutional block. The decoder then apply a few $3\times3$ convolutions to refine the feature map, followed by a bilinear interpolation to recover the resolution. \section{Experiment} We evaluate the WaveSNets (WSegNet, WDeepLabv3+) on the image dataset of CamVid, Pascal VOC, and Cityscapes, in terms of mean intersection over union (mIoU). \subsection{WSegNet} \textbf{CamVid}\quad CamVid contains 701 road scene images (367, 101 and 233 for the training, validation and test respectively) with size of $360\times480$, which was used in \cite{badrinarayanan2017segnet} to quantify SegNet performance. Using the training set, we train SegNet, U-Net, and WSegNet when various wavelets are applied. The trainings are supervised by cross-entropy loss. We employ SGD solver, initial learning rate of $0.007$ with ``poly'' policy and $power = 0.9$, momentum of $0.9$ and weight decay of $0.0005$. With a mini-batch size of $20$, we train the networks 12K iterations (about 654 epochs). The input image size is $352 \times 480$. For every image, we adopt random resizing between $0.75$ and $2$, random rotation between $-20$ and $20$ degrees, random horizontal flipping and cropping with size of $352 \times 480$. We apply a pre-trained VGG16bn model for the encoder initialization and initialize the decoder using the technique proposed in \cite{he2015delving_initilization}. We do not tune above hyper-parameters for a fair comparison. \begin{table}[!tbp] \scriptsize \centering \setlength{\tabcolsep}{0.35mm}{ \begin{tabular}{r|c|c|c|cccc|ccccc}\hline &\multirow{2}{*}{SegNet}&\multirow{2}{*}{U-Net}&\multicolumn{10}{c}{WSegNet}\\\cline{4-13} &&&haar&ch2.2&ch3.3&ch4.4&ch5.5&db2&db3&db4&db5&db6\\\hline sky &90.50 &\textbf{91.52} &91.31 &91.38 &91.29 &91.39 &91.24 &91.35 &91.48 &90.99 &90.89 &90.63\\ building &77.80 &\textbf{80.28} &79.90 &79.27 &78.82 &79.37 &78.65 &79.48 &79.60 &78.52 &78.58 &77.84\\ pole &~~9.14 &27.97 &27.99 &\textbf{29.38} &27.90 &28.96 &27.26 &27.91 &28.38 &28.04 &26.66 &25.96\\ road &92.69 &93.71 &93.69 &93.47 &93.47 &93.77 &93.78 &93.72 &\textbf{93.91} &92.57 &92.12 &92.11\\ sidewalk &78.05 &80.05 &80.33 &79.44 &79.34 &79.89 &80.08 &79.67 &\textbf{80.58} &76.95 &75.62 &76.65\\ tree &72.40 &73.51 &73.34 &73.27 &73.21 &73.07 &71.60 &73.61 &\textbf{73.68} &72.90 &72.28 &71.92\\ symbol &37.61 &43.07 &44.44 &42.68 &40.42 &43.57 &42.33 &\textbf{44.72} &44.01 &41.06 &41.72 &39.69\\ fence &19.92 &27.50 &\textbf{32.59} &24.62 &25.59 &28.40 &28.85 &25.52 &29.60 &26.90 &24.15 &29.00\\ car &79.31 &\textbf{85.04} &83.21 &84.43 &82.63 &84.57 &84.14 &84.30 &83.97 &81.92 &81.07 &78.38\\ walker &39.93 &50.35 &49.35 &\textbf{50.98} &50.52 &50.43 &49.09 &50.15 &49.39 &47.69 &48.02 &43.17\\ bicyclist &39.48 &44.45 &50.38 &47.94 &48.69 &47.93 &\textbf{52.64} &51.15 &47.73 &46.08 &43.53 &38.96\\\cdashline{1-13}[3pt/1pt] mIoU &57.89 &63.40 &\textbf{64.23} &63.35 &62.90 &63.76 &63.61 &63.78 &63.85 &62.15 &61.33 &60.39\\\hline gl. acc. &91.04 &92.19 &92.08 &92.04 &91.98 &92.10 &91.73 &92.06 &\textbf{92.40} &91.60 &91.30 &91.14\\\hline para.(e6) &29.52 &37.42&\multicolumn{10}{c}{\textbf{29.52}}\\\hline \end{tabular}} \caption{WSegNet results on CamVid test set}\label{tab_mIoU_CamVid_WSegNet} \end{table} Table \ref{tab_mIoU_CamVid_WSegNet} shows the mIoU and global accuracy on the CamVid test set, together with the parameter numbers of U-Net, SegNet, and WSegNet with various wavelets. In the table, ``dbx'' represents orthogonal Daubechies wavelet with approximation order $x$, and ``chx.y'' represents biorthogonal Cohen wavelet with approximation orders $(x,y)$. Their low-pass and high-pass filters can be found in \cite{daubechies1992ten}. The length of these filters increase as the order increases. While Haar and Cohen wavelets are symmetric, Daubechies are not. The mIoU of WSegNet decreases from $63.78\%$ to $60.39\%$ as asymmetric wavelet varies from ``db2'' to ``db6'', while it varies from $63.35\%$ to $63.61\%$ as symmetric wavelet varies from ``ch2.2'' to ``ch5.5''. It seems that the performances among different asymmetric wavelets are much diverse than that among various symmetric wavelets. In the wavelet integrated deep networks, we truncate the DWT output to make them to be $1/2$ size of input data. As a result, IDWT with asymmetric wavelet can not fully restore an image in the region near the image boundary, and the region width increases as the wavelet filter length increases. With symmetric wavelet, however, one can fully restore the image based on symmetric extension of the DWT output. Consequently, WSegNet with Cohen wavelets performs better than that with Daubechies ones near the image boundary. Fig. \ref{Fig_CamVid_Comparison_Boundary} shows an example image, its manual annotation, a region consisting of ``building'', ``road'' and ``sidewalk'' and the segmentation results achieved using different wavelets. The region is located close to the image boundary and has been enlarged with colored segmentation results for better illustration. One can observe from the results of ``db5'' and ``db6'' that a long line of ``sidewalk'' pixels, located near the image boundary, are classified as ``road''. In comparison, the results of ``ch4.4'' and ``ch5.5'' match well with the ground truth. \begin{figure}[bpt] \centering \includegraphics*[scale=0.55, viewport=41 430 474 570]{figures/detail_comparison.pdf} \caption{Boundary comparison for images segmented by WSegNet with different wavelets.} \label{Fig_CamVid_Comparison_Boundary} \end{figure} In \cite{badrinarayanan2017segnet}, the authors train the SegNet using an extended CamVid training set containing 3433 images, which achieved $60.10\%$ mIoU on the CamVid test set. We train SegNet, U-Net and WSegNet using only 367 CamVid training images. From Table \ref{tab_mIoU_CamVid_WSegNet}, one can find WSegNet achieves the best mIoU ($64.23\%$) using Haar wavelet, and the best global accuracy ($92.40\%$) using ``db3'' wavelet. WSegNet is significantly superior to SegNet in terms of mIoU and the global accuracy, while they require the same amount of parameters ($29.52\times10^6$). The segmentation performance of WSegNet is also better than that of U-Net, while it requires much less parameters than U-Net ($37.42\times10^6$). Table \ref{tab_mIoU_CamVid_WSegNet} also lists the IoUs for the 11 categories in the CamVid. Compared with U-Net and WSegNet, SegNet performs very poor on the fine objects, such as ``pole'', ``symbol'', and ``fence'', as that the max-pooling indices used in SegNet are not helpful for restoring the image details. While U-Net achieves comparable or even better IoUs on the easily identifiable objects, such as the ``sky'', ``building'', and ``car'', it does not discriminate well similar objects like``walker'' and ``bicyclist'', or ``building'' and ``fence''. The feature maps of these two pairs of objects might look similar to the decoder of U-Net, as the data details are not separately provided. Table \ref{tab_confusion_matrices} shows the confusion matrices on these four categories. The proportion of ``building'' in the predicted ``fence'' decreases from $34.11\%$ to $30.16\%$, as the network varies from SegNet to WPUNet, while that of ``bicyclist'' in the predicted ``walker'' decreases from $2.54\%$ to $1.90\%$. These results suggest that WSegNet is more powerful than SegNet and U-Net in distinguishing similar objects. \begin{table} \scriptsize \centering \setlength{\tabcolsep}{1.25mm}{ \begin{tabular}{r|cc|cc|cc} \hline & \multicolumn{2}{|c|}{SegNet} &\multicolumn{2}{c|}{U-Net} &\multicolumn{2}{c}{WSegNet(haar)}\\\cline{2-7} & building & fence & building & fence & building & fence\\ \hline building & 88.01 & ~~1.30 & 89.91 & ~~1.19 & 90.22 & ~~1.08\\ fence & \underline{34.11} & 29.12 & \underline{30.64} & 40.16 & \underline{30.16} & 44.65\\ \hline\hline & walker& bicyclist& walker& bicyclist& walker& bicyclist\\ \hline walker & 53.30 & \underline{~~2.54} & 66.83 & \underline{~~1.95}& 68.74 & \underline{~~1.90}\\ bicyclist & 13.69 & 49.66 & 16.73 & 51.45 & 12.52 & 59.80 \\ \hline \end{tabular}} \caption{Confusion matrices for the CamVid test set. \label{tab_confusion_matrices} \end{table} \begin{figure}[bpt] \centering \includegraphics*[scale=0.675, viewport=40 616 382 776]{figures/detail_comparison.pdf} \caption{Comparison of SegNet and WSegNet segmentations.} \label{fig_segmentation_comparison_CamVid} \end{figure} Fig. \ref{fig_segmentation_comparison_CamVid} presents a visual example for various networks, which shows the example image, its manual annotation, a region consisting of ``building'', ``tree'', ``sky'' and ``pole'', and the segmentation results achieved using SegNet, U-Net and WSegNet. The region is enlarged with colored segmentation reults for better illustration. From the figure, one can find in the segmentation result that WSegNet keeps the basic structure of ``tree'', ``pole'', and ``building'' and restores the object details, such as the ``tree'' branches and the ``pole''. The segmentation result of WSegNet matches the image region much better than that of SegNet and U-Net, even corrects the annotation noises about ``building'' and “tree” in the ground truth. \begin{table}[!tbp] \scriptsize \centering \setlength{\tabcolsep}{0.75mm}{ \begin{tabular}{cr|c|c|c|cccc|c}\hline &&\multirow{2}{*}{SegNet}&\multirow{2}{*}{U-Net}&\multicolumn{6}{c}{WSegNet}\\\cline{5-10} & & & & haar& ch2.2& ch3.3& ch4.4& ch5.5& db2\\\hline \multirow{2}{*}{Pascal VOC}&mIoU &61.33 &63.64 &\textbf{63.95} &63.50 &63.46 &63.48 &63.62 &63.48\\\cdashline{2-10}[1pt/1pt] &gl. acc.&90.14 &\textbf{90.82} &90.79 &90.72 &90.72 &90.73 &90.76 &90.75\\\hline \multirow{2}{*}{Cityscapes}&mIoU &65.75 &70.05 &70.09 &69.86 &69.73 &70.13 &\textbf{70.63} &70.37 \\\cdashline{2-10}[1pt/1pt] &gl. acc.&94.65 &\textbf{95.21} &95.20 &95.18 &95.09 &95.17 &95.15 &95.20 \\\hline \multicolumn{2}{r|}{parameters (e6)}& 29.52&37.42 &\multicolumn{6}{c}{\textbf{29.52}}\\\hline \end{tabular}} \caption{WSegNet results on Pascal VOC and Cityscapes \textit{val} set.}\label{tab_mIoU_VOC_Cityscapes_WSegNet} \end{table} \textbf{Pascal VOC and Cityscapes}\quad The original Pascal VOC2012 semantic segmentation dataset contains 1464 and 1449 annotated images for training and validation, respectively, and contains 20 object categories and one background class. The images are with various sizes. We augment the training data to 10582 by extra annotations provided in \cite{hariharan2011semantic}. We train SegNet, U-Net, and WSegNet with various wavelets on the extended training set 50 epochs with batch size of 16. During the training, we adopt random horizontal flipping, random Gaussian blurring, and cropping with size of $512\times512$. The other hyper-parameters are the same with that used in CamVid training. Table \ref{tab_mIoU_VOC_Cityscapes_WSegNet} presents the results on the validation set for the trained networks. Cityscapes contains 2975 and 500 high quality annotated images for the training and validation, respectively. The images are with size of $1024\times2048$. We train the networks on the training set 80 epochs with batch size of 8 and initial learning rate of $0.01$. During the training, we adopt random horizontal flipping, random resizing between 0.5 and 2, and random cropping with size of $768\times768$. Table \ref{tab_mIoU_VOC_Cityscapes_WSegNet} presents the results on the validation set. From Tabel \ref{tab_mIoU_VOC_Cityscapes_WSegNet}, one can find the segmentation performance of SegNet is significant inferior to that of U-Net and WSegNet. While WSegNet achieves better mIoU ($63.95\%$ for Pascal VOC and $70.63\%$ for Cityscapes) and requires less parameters ($29.52\times10^6$), the global accuracies of WSegNet on the two dataset are a little lower than that of U-Net. This result suggest that, compared with U-Net, WSegNet could more precisely classify the pixels at the ``critical'' locations. \subsection{WDeepLabv3+} \begin{table}[!tbp] \scriptsize \centering \setlength{\tabcolsep}{1.25mm}{ \begin{tabular}{r|c|c|cccc|c}\hline &\multirow{2}{*}{DeepLabv3+}&\multicolumn{6}{c}{WDeepLabv3+}\\\cline{3-8} & & haar& ch2.2& ch3.3& ch4.4& ch5.5& db2\\\hline background &93.83 &93.82 &93.85 &\textbf{93.94} &93.91 &93.86 &93.87 \\ aeroplane &92.29 &93.14 &92.50 &91.56 &\textbf{93.21} &92.73 &92.41 \\ bike &41.42 &43.08 &42.19 &42.21 &\textbf{43.42} &42.59 &42.84 \\ bird &91.47 &90.47 &\textbf{91.60} &90.34 &91.24 &90.81 &90.73 \\ boat &75.39 &\textbf{75.47} &72.04 &75.19 &74.20 &72.40 &72.90 \\ bottle &82.05 &80.18 &81.14 &82.12 &79.55 &\textbf{82.23} &81.89 \\ bus &\textbf{93.64} &93.25 &93.25 &93.20 &93.07 &93.52 &93.31 \\ car &89.30 &90.36 &90.00 &\textbf{90.67} &88.79 &86.31 &87.11 \\ cat &93.69 &92.80 &93.31 &92.62 &93.56 &93.84 &\textbf{93.97} \\ \underline{chair} &38.28 &40.80 &40.75 &39.32 &39.79 &\textbf{43.27} &41.60 \\ \textbf{\emph{cow}} &86.60 &89.72 &89.04 &90.49 &88.42 &\textbf{92.04} &88.17 \\ \underline{table} &61.37 &63.24 &62.67 &65.49 &64.93 &\textbf{67.31} &65.58 \\ dog &\textbf{91.16} &90.24 &91.04 &89.54 &89.97 &90.38 &90.65 \\ \textbf{\emph{horse}} &86.60 &88.86 &88.88 &90.23 &89.00 &\textbf{91.02} &89.19 \\ motorbike &88.47 &87.94 &87.89 &\textbf{88.61} &88.36 &87.30 &87.58 \\ person &86.71 &86.88 &86.61 &86.35 &86.59 &86.32 &\textbf{86.96} \\ \underline{plant} &64.48 &64.33 &64.69 &\textbf{68.45} &65.50 &68.01 &65.41 \\ \textbf{\emph{sheep}} &83.04 &87.45 &86.50 &87.43 &85.70 &\textbf{88.14} &85.95 \\ sofa &49.24 &47.43 &48.06 &49.85 &46.74 &\textbf{51.94} &50.19 \\ train &85.49 &84.18 &83.88 &85.47 &83.88 &85.16 &\textbf{86.69} \\ monitor &77.80 &76.55 &78.31 &79.04 &78.32 &78.78 &\textbf{79.11} \\\cdashline{1-8}[3pt/1pt] mIoU &78.68 &79.06 &78.96 &79.62 &78.96 &\textbf{79.90} &79.34 \\\hline gl. acc. &94.64 &94.69 &94.68 &94.75 &94.68 &\textbf{94.77} &94.75 \\\hline para. (e6) &\textbf{59.34} &\multicolumn{6}{c}{60.22} \\\hline \end{tabular}} \caption{WDeepLabv3+ results on Pascal VOC \textit{val} set.}\label{tab_mIoU_VOC_WDeepLabv3+} \end{table} Taking ResNet101 as the backbone, we build DeepLabv3+ and WDeepLabv3+ with $output\ stride = 16$, and train them on the Pascal VOC using the same training policy with that used in the training of WSegNet. Table \ref{tab_mIoU_VOC_WDeepLabv3+} shows the segmentation results on the validation set. We achieve $78.68\%$ mIoU using DeepLabv3+ on the Pascal VOC validation set, which is comparable to that ($78.85\%$) obtained by the inventors of this network \cite{chen2018encoder_deeplabv3+}. With a few increase of parameter ($0.88 \times 10^6,~1.48\%$), the segmentation performance of WDeepLabv3+ with various wavelet is always better than that of DeepLabv3+, in terms of mIoU and global accuracy. Using ``ch5.5'' wavelet, WDeepLabv3+ achieves the best performance, $79.90\%$ mIoU and $94.77\%$ global accuracy. From Table \ref{tab_mIoU_VOC_WDeepLabv3+}, one can find that the better performance of WDeepLabv3+ is mainly resulted from its better segmentation for the fine objects (``chair'', ``table'', and ``plant'') and similar objects (``cow'', ``horse'', and ``sheep''). The above results justify the high efficiency of DWT/IDWT layers in processing data details. \begin{figure}[bpt] \centering \includegraphics*[scale=0.415, viewport=22 260 581 810]{figures/segmentation_comparison.pdf} \caption{Comparison of DeepLabv3+ and WDeepLabv3+ results.} \label{fig_comparison_WDeepLabv3+_VOC} \end{figure} Fig. \ref{fig_comparison_WDeepLabv3+_VOC} shows four visual examples of segmentation results for DeepLabv3+ and WDeepLabv3+. The first and second columns present the original images and the segmentation ground truth, while the third and fourth columns show the segmentation results of DeepLabv3+ and WDeepLabv3+ with ``ch5.5'' wavelet, respectively. We show the segmentation results with colored pictures for better illustration. For the example image in Fig. \ref{fig_comparison_WDeepLabv3+_VOC}(a), DeepLabv3+ falsely classifies the pixels in some detail regions on the cow and her calfs as ``background'' or ``horse'', i.e., the regions for the cow's left horn, the hind leg of the brown calf, and some fine regions on the two calfs. While WDeepLabv3+ correctly classifies the horse and the sheep in the Fig. \ref{fig_comparison_WDeepLabv3+_VOC}(b) and Fig. \ref{fig_comparison_WDeepLabv3+_VOC}(c), DeepLabv3+ classifies them as ``cow'' because of the similar object structures. In Fig. \ref{fig_comparison_WDeepLabv3+_VOC}(d), the ``table'' segmented by WDeepLabv3+ is more complete than that segmented by DeepLabv3+. These results illustrate that WDeepLabv3+ performs better on the detail regions and the similar objects. \section{Conclusion} Our proposed general DWT and IDWT layers are applicable to various wavelets, which can be used to extract and process the data details during the network inference. We design WaveSNets (WSegNet and WDeepLabv3+) by replacing the down-sampling with DWT and replacing the up-sampling with IDWT, in U-Net, SegNet, and DeepLabv3+. Experimental results on the CamVid, Pascal VOC, and Cityscapes show that WaveSNets could well recover the image details and perform better for segmenting similar objects than their vanilla versions. \bibliographystyle{named}
{'timestamp': '2020-06-01T02:09:10', 'yymm': '2005', 'arxiv_id': '2005.14461', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14461'}
arxiv
\section{Appendix} \subsection{Bounding the Error of Monte Carlo Estimation} \label{apx:MC} As shown in Proposition~\ref{pro:cAcB}, the smoothed model $f^\rs$ is certified robust at an input $\X$ in the sense of \eqref{equ:certified} if \begin{align*} \Delta_\X & = {\ell^\rs}(\X, y) -{\ell^\rs}(\X, y_B) -2 q_\X \\ & = {\ell^\rs}(\X, y) - \max_{c\ne y {\ell^\rs}(\X, c) -2q_\X > 0, \end{align*} where $y$ is the true label of $\X$, and $$ {\ell^\rs}(\X, c) := \mathbb{P}_{\Z\sim\Pi_{\X}}\left(f(\Z)=c\right) = \mathbb{E}_{\Z\sim\Pi_{\X}}\left[\mathbb I\{ f(\Z)=c\}\right]. $$ Assume $\{\Z^{(i)}\}_{i=1}^n$ is an i.i.d. sample from $\Pi_{\X}$. By Monte Carlo approximation, we can estimate ${\ell^\rs}(\X, c)$ for all $c\in\mathcal{Y}$ jointly, via $$ {\hat{\ell}^\rs}(\X, c ):=\frac{1}{n}\sum_{i=1}^{n}\mathbb{I}\left\{ f(\Z^{(i)})=c\right\},$$ and estimate $\Delta_\X$ via $$ \hat \Delta_\X := \frac{1}{n}\sum_{i=1}^{n}\mathbb{I}\left\{ f(\Z^{(i)})=y\right\} - \max_{c\ne y}\frac{1}{n}\sum_{i=1}^{n}\mathbb{I}\left\{ f(\Z^{(i)})=c\right\} - 2 q_\X. $$ To develop a rigorous procedure for testing $\Delta_\X >0$, we need to bound the non-asymptotic error of the Monte Carlo estimation, which can be done with a simple application of Hoeffding's concentration inequality and union bound. \begin{proposition}\label{pro:concentration} Assume $\{\Z^{(i)}\}$ is i.i.d. drawn from $\Pi_\X$. For any $\delta\in (0,1)$, with probability at least $1-\delta$, we have \begin{align*} \Delta_\X \ge & \hat\Delta_\X - 2\sqrt{\frac{\log\frac{1}{\delta}+\log\left|\mathcal{Y}\right|}{2n}}. \end{align*} \end{proposition} We can now frame the robustness certification problem into a hypothesis test problem. Consider the null hypothesis $\text{H}_0$ and alternatively hypothesis $\text{H}_a$: \begin{align*} \text{H}_{0}: & \Delta_\X \leq 0~~~ (f^{\rs}\text{\ is\ not\ certified\ robust\ to\ }\X)\\ \text{H}_{a}: & \Delta_\X > 0~~~ (f^{\rs}\text{\ is\ certified\ robust\ to\ }\X). \end{align*} Then according to Proposition~\ref{pro:concentration}, we can reject the null hypothesis $\text{H}_0$ with a significance level $\delta$ if \[ \hat\Delta_\X - 2\sqrt{\frac{\log\frac{1}{\delta}+\log\left|\mathcal{Y}\right|}{2n}} > 0. \] In all the experiments, we set $\delta = 0.01$ and $n=5000$. \subsection{Proof of the Main Theorems} \label{apx:pf} In this section, we give the proofs of the theorems in the main text. \newcommand{{\X'\in S_\X}}{{\X'\in S_\X}} \renewcommand{\H}{\mathcal{H}_{[0,1]}} \subsubsection{Proof of Proposition \ref{pro:cAcB}} According to the definition of $f^\rs$, it is certified robust at $\X$, that is, $y = f^\rs(\X')$ for $\forall \X' \in S_\X$, if \begin{align} \label{equ:grddfdi} {\ell^\rs}(\X', ~ y) \geq \max_{c\neq y}{\ell^\rs}(\X', c),~~~~~ \X' \in S_\X. \end{align} Obviously \begin{align*} {\ell^\rs}(\X', ~ y) - \max_{c\neq y}{\ell^\rs}(\X', c) & \geq \min_{\X'\in S_\X}{\ell^\rs}(\X', ~ y) - \max_{c\neq y} \max_{\X' \in S_\X}{\ell^\rs}(\X', c) \\ & \geq \left ({\ell^\rs}(\X, ~ y) - q_\X \right) - \max_{c\neq y} \left ({\ell^\rs}(\X, c) + q_\X \right) ~~~\text{//by Theorem~\ref{thm:lb}.} \\ & = \Delta_\X. \end{align*} Therefore, $\Delta_\X > 0$ must imply \eqref{equ:grddfdi} and hence certified robustness. \subsubsection{Proof of Theorem \ref{thm:lb}} Our goal is to calculate the upper and lower bounds $\max_{\X'\sim \Pi_\X}{\ell^\rs}(\X', c)$ and $\min_{\X'\sim \Pi_\X}{\ell^\rs}(\X', c)$. Our key idea is to frame the computation of the upper and lower bounds into a variational optimization. \begin{lemma}\label{lem:first} Define $\H$ to be the set of all bounded functions mapping from $\mathcal{X}$ to $[0,1]$, For any $h \in \H$, define \[ \Pi_{\X}[h]=\mathbb{E}_{\Z\sim\Pi_{\X}}[h(\Z)]. \] Then we have for any $\X$ and $c \in \mathcal Y$, \begin{align*} & \min_{\X'\sim \Pi_\X}{\ell^\rs}(\X', c) \geq \min_{h \in \H }\min_{\X'\sim \Pi_\X} \left \{ \Pi_{\X'}[h] ~~~s.t.~~~ \Pi_{\X}[h] = {\ell^\rs}(\X, c) \right\} : = g^{\rs}_{low}(\X, c), \\ & \max_{\X'\sim \Pi_\X}{\ell^\rs}(\X', c) \leq \max_{h \in \H }\max_{\X'\sim \Pi_\X} \left \{ \Pi_{\X'}[h] ~~~s.t.~~~ \Pi_{\X}[h] = {\ell^\rs}(\X, c) \right\} : = g^{\rs}_{up}(\X, c). \end{align*} \end{lemma} \begin{proof}[Proof of Lemma~\ref{lem:first}] The proof is straightforward. Define $h_0(\X)= \mathbb I\{ f(\X)=c\}$. Recall that $$ {\ell^\rs}(\X, c) = \mathbb{P}_{\Z\sim\Pi_{\X}}\left(f(\Z)=c\right) = \Pi_{\X}[h_0]. $$ Therefore, $h_0$ satisfies the constraints in the optimization, which makes it obvious that $$ {\ell^\rs}(\X', c) = \Pi_{\X'}[h_0] \geq \min_{h \in \H }\left \{ \Pi_{\X'}[h] ~~~s.t.~~~ \Pi_{\X}[h] = {\ell^\rs}(\X, c) \right\}. $$ Taking $\min_{\X' \in S_\X}$ on both sides yields the lower bound. The upper bound follows the same derivation. \end{proof} Therefore, the problem reduces to deriving bounds for the optimization problems. \begin{theorem} \label{thm:constrain} Under the assumptions of Theorem~\ref{thm:lb}, for the optimization problems in Lemma~\ref{lem:first}, we have \begin{align*} g^{\rs}_{low}(\X, c) \geq \max ({\ell^\rs}(\X,c) - q_\X,~ 0), && g^{\rs}_{up}(\X, c) \leq \min({\ell^\rs}(\X, c) + q_\X, ~ 1). \end{align*} where $q_\X$ is the quantity defined in Theorem \ref{thm:lb} in the main text. \end{theorem} Now we proceed to prove Theorem \ref{thm:constrain}. \begin{proof}[Proof of Theorem~\ref{thm:constrain}] We only consider the minimization problem because the maximization follows the same proof. For notation, we denote $p = {\ell^\rs}(\X, c)$. Applying the Lagrange multiplier to the constraint optimization problem and exchanging the min and max, we have \begin{align*} g^{\rs}_{low}(\X, c) = & \min_{{\X'\in S_\X}}\min_{h\in\H}\mathrm{\max_{\lambda\in \mathbb{R}}}\ \Pi_{\X'}[h]-\lambda\Pi_{\X}[h]+\lambda p\\ \ge & \mathrm{\max_{\lambda\in \mathbb{R}}}\min_{{\X'\in S_\X}}\min_{h\in\H}\ \Pi_{\X'}[h]-\lambda\Pi_{\X}[h]+\lambda p\\ = & \mathrm{\max_{\lambda\in \mathbb{R}}}\min_{{\X'\in S_\X}}\min_{h\in\H}\ \int h(\Z)\left(d\Pi_{\X'}(\Z)-\lambda d\Pi_{\X}(\Z)\right)+\lambda p\\ = & -\mathrm{\max_{\lambda\in \mathbb{R}}}\max_{{\X'\in S_\X}}\int\left(\lambda d\Pi_{\X}(\Z)-d\Pi_{\X'}(\Z)\right)_{+}+\lambda p \\ = & -\mathrm{\max_{\lambda\ge0}}\max_{{\X'\in S_\X}}\int\left(\lambda d\Pi_{\X}(\Z)-d\Pi_{\X'}(\Z)\right)_{+}+\lambda p. \end{align*} Here $d\Pi_{\X}^{0}(\Z)$ and $d\Pi_{\X'}^{0}(\Z)$ is the counting measure and $(s)_{+}=\max(s,0)$. Now we calculate $\int\left(\lambda d\Pi_{\X}(\Z)-d\Pi_{\X'}(\Z)\right)_{+}$. \begin{lemma} \label{lem:analytic} Given $\x,\x'$, define $n_{\x}=\left|P_{\x}\right|$, $n_{\x'}=\left|P_{\x'}\right|$ and $n_{\x,\x'}=\left|P_{\x}\cap P_{\x'}\right|$. We have the following identity \begin{align*} & \int\left(\lambda d\Pi_{\X}(\Z)-d\Pi_{\X'}(\Z)\right)_{+} \\ = & \lambda\left[1-\prod_{j\in[L],\x_{j}\neq\x'_{j}}\frac{n_{\x_{j},\x_{j}'}}{n_{\x_{j}}}\right]+\left[\prod_{j\in[L],\x_{j}\neq\x'_{j}}\frac{n_{\x_{j},\x_{j}'}}{n_{\x_{j}}}\right]\left[\lambda-\prod_{j\in[L],\x_{j}\ne\x'_{j}}\frac{n_{\x_{j}}}{n_{\x'_{j}}}\right]_{+}. \end{align*} As a result, under the assumption that $n_x=\left|P_{\x}\right|=\left|P_{\x'}\right|=n_{x'}$ for every word $x$ and its synonym $\x'\in S_{\x}$, we have \begin{align*} \int \left(\lambda d\Pi_{\X}(\Z)-d\Pi_{\X'}(\Z)\right)_{+} = & \lambda\left[1-\prod_{j\in[L],\x_{j}\neq\x'_{j}} \frac{n_{\x_{j},\x_{j}'}}{n_{\x_{j}}} \right]+\left[\prod_{j\in[L],\x_{j}\neq\x'_{j}} \frac{n_{\x_{j},\x_{j}'}}{n_{\x_{j}}} \right]\left(\lambda-1\right)_{+}. \end{align*} \end{lemma} We now need to solve the optimization of $\max_{{\X'\in S_\X}}\int\left(\lambda d\Pi_{\X}(\Z)-d\Pi_{\X'}(\Z)\right)_{+}$. \newcommand{\tilde{\x}^*}{\tilde{\x}^*} \begin{lemma} \label{lem:optperterb} For any word $\x$, define $\tilde{\x}^*=\underset{\x'\in S_{\x}}{\arg\min}\ n_{\x,\x'}/n_{\x}$. For a given sentence $\X = x_1,\ldots, x_L$, we define an ordering of the words $x_{\ell_1}, \ldots, x_{\ell_L}$ such that $n_{\x_{\ell_{i}},\tilde{\x}^*_{\ell_{i}}}/n_{\x_{\ell_{i}}}\le n_{\x_{\ell_{j}},\tilde{\x}^*_{\ell_{j}}}/n_{\x_{\ell_{j}}}$ for any $i\le j$. For a given $\X$ and $R$, we define an adversarial perturbed sentence $ \X^* = x^*_1,\ldots, x^*_L, $ where $$ x_i^* = \begin{cases} \tilde{\x}_{i}^{*} & \text{if $i \in [\ell_1, \ldots, \ell_R]$} \\ {\x}_{i} & \text{if $i \notin [\ell_1, \ldots, \ell_R]$}. \\ \end{cases} $$ Then for any $\lambda\ge0$, we have that $\X^*$ is the optimal solution of $\max_{{\X'\in S_\X}}\int\left(\lambda d\Pi_{\X}(\Z)-d\Pi_{\X'}(\Z)\right)_{+}$, that is, \[ \max_{{\X'\in S_\X}}\int\left(\lambda d\Pi_{\X}(\Z)-d\Pi_{\X'}(\Z)\right)_{+}=\int\left(\lambda d\Pi_{\X}(\Z)-d\Pi_{\X^*}(\Z)\right)_{+}. \] \end{lemma} Now by Lemma \ref{lem:optperterb}, the lower bound becomes \begin{align} g^{\rs}_{low}(\X, c) = ~& -\mathrm{\max_{\lambda\ge0}}\max_{{\X'\in S_\X}}\int\left(\lambda d\Pi_{\X}(\Z)-d\Pi_{\X'}(\Z)\right)_{+}+\lambda p \notag \\ =~ & - \mathrm{\max_{\lambda\ge0}}\int\left(\lambda d\Pi_{\X}(\Z)-d\Pi_{\X^*}(\Z)\right)_{+}+\lambda p\notag \\ = ~& \mathrm{\max_{\lambda\ge0}}\mathrm{\ }(p-q_\X)\lambda-(1-q_\X)(\lambda-1)_{+} \label{equ:dfdfdjijiojioj}\\ = ~ & \max( p - q_{\X}, ~ 0 ), \notag \end{align} where $q_\X$ is consistent with the definition in Theorem~\ref{thm:lb}: \[ q_\X=1-\prod_{j\in[L],\x_{j}\neq\tilde{\x}_{j}^{*}}\frac{n_{\x_{j},\tilde{\x}_{j}^{*}}}{n_{\x_{j}}} = 1- \prod_{j=1}^R q_{x_{\ell_j}}. \] Here equation (\ref{equ:dfdfdjijiojioj}) is by calculation using the assumption of Theorem \ref{thm:lb}. The optimization of $\max_{\lambda\geq 0}$ in \eqref{equ:dfdfdjijiojioj} is an elementary step: if $p\le q$, we have $\lambda^{*}=0$ with solution $0$; if $p\ge q$, we have $\lambda^{*}=1$ with solution $(p-q_\X)$. This finishes the proof of the lower bound. The proof the upper bound follows similarly. \end{proof} \paragraph{Proof of Lemma \ref{lem:analytic}} Notice that we have \begin{align*} \int\left(\lambda d\Pi_{\X}(\Z)-d\Pi_{\X'}(\Z)\right)_{+} = & \sum_{\Z\in S_{\X'}\cap S_{\X}}\left(\lambda\left|S_{\X}\right|^{-1}-\left|S_{\X'}\right|^{-1}\right)_{+} + \lambda\sum_{\Z\in S_{\X}-S_{\X'}}\left|S_{\X}\right|^{-1}\\ = & \left|S_{\X'}\cap S_{\X}\right|\left(\lambda\left|S_{\X}\right|^{-1}-\left|S_{\X'}\right|^{-1}\right)_{+} + \lambda\left|S_{\X}-S_{\X'}\right|\left|S_{\X}\right|^{-1}. \end{align*} Also notice that $\left|S_{\X}\right| =\prod_{j=1}^{L}n_{\x_{j}}$; $\left|S_{\X'}\right| =\prod_{j=1}^{L}n_{\x_{j}'}$; $\left|S_{\X'}\cap S_{\X}\right| = \prod_{j=1}^{L}n_{\x_{j},\x_{j}'}$ and $\left|S_{\X}-S_{\X'}\right| =\prod_{j=1}^{L}n_{\x_{j}}-\prod_{j=1}^{L}n_{\x_{j},\x_{j}'}$. Plugging in the above value, we have \begin{align*} \left|S_{\X}-S_{\X'}\right|\left|S_{\X}\right|^{-1} = & \frac{\prod_{j=1}^{L}n_{\x_{j}}-\prod_{j=1}^{L}n_{\x_{j},\x_{j}'}}{\prod_{j=1}^{L}n_{\x_{j}}}\\ = & 1-\prod_{j=1}^{L}\frac{n_{\x_{j},\x_{j}'}}{n_{\x_{j}}}\\ = & 1-\prod_{j\in[L],\x_{j}\neq\x'_{j}}\frac{n_{\x_{j},\x_{j}'}}{n_{\x_{j}}}. \end{align*} And also, \begin{align*} \left(\lambda\left|S_{\X}\right|^{-1}-\left|S_{\X'}\right|^{-1}\right)_{+} = & \left(\lambda\prod_{j=1}^{L}n_{\x_{j}}^{-1}-\prod_{j=1}^{L}n_{\x_{j}'}^{-1}\right)_{+}\\ = & \left(\lambda\prod_{j\in[L],\x_{j}=\x'_{j}}n_{\x_{j}}^{-1}\prod_{j\in[L],\x_{j}\ne\x'_{j}}n_{\x_{j}}^{-1}-\prod_{j\in[L],\x_{j}=\x'_{j}}n_{\x_{j}}^{-1}\prod_{j\in[L],\x_{j}\ne\x'_{j}}n_{\x'_{j}}^{-1}\right)_{+}\\ = & \prod_{j\in[L],\x_{j}=\x'_{j}}n_{\x_{j}}^{-1}\left(\lambda\prod_{j\in[L],\x_{j}\ne\x'_{j}}n_{\x_{j}}^{-1}-\prod_{j\in[L],\x_{j}\ne\x'_{j}}n_{\x'_{j}}^{-1}\right)_{+}. \end{align*} Plugging in the above value, we have \begin{align*} \left|S_{\X'}\cap S_{\X}\right|\left(\lambda\left|S_{\X}\right|^{-1}-\left|S_{\X'}\right|^{-1}\right)_{+} = & \prod_{j=1}^{L}n_{\x_{j},\x_{j}'}\left(\lambda\left|S_{\X}\right|^{-1}-\left|S_{\X'}\right|^{-1}\right)_{+}\\ = & \prod_{j\in[L],\x_{j}=\x'_{j}}n_{\x_{j}}\prod_{j\in[L],\x_{j}\neq\x'_{j}}n_{\x_{j},\x_{j}'}\left(\lambda\left|S_{\X}\right|^{-1}-\left|S_{\X'}\right|^{-1}\right)_{+}\\ = & \prod_{j\in[L],\x_{j}\neq\x'_{j}}n_{\x_{j},\x_{j}'}\left(\lambda\prod_{j\in[L],\x_{j}\ne\x'_{j}}n_{\x_{j}}^{-1}-\prod_{j\in[L],\x_{j}\ne\x'_{j}}n_{\x'_{j}}^{-1}\right)_{+}\\ = & \prod_{j\in[L],\x_{j}\neq\x'_{j}}n_{\x_{j},\x_{j}'}\prod_{j\in[L],\x_{j}\ne\x'_{j}}n_{\x_{j}}^{-1}\left(\lambda-\prod_{j\in[L],\x_{j}\ne\x'_{j}}\frac{n_{\x_{j}}}{n_{\x'_{j}}}\right)_{+}\\ = & \left(\prod_{j\in[L],\x_{j}\neq\x'_{j}}\frac{n_{\x_{j},\x_{j}'}}{n_{\x_{j}}}\right)\left(\lambda-\prod_{j\in[L],\x_{j}\ne\x'_{j}}\frac{n_{\x_{j}}}{n_{\x'_{j}}}\right)_{+}. \end{align*} Combining all the calculation, we get \begin{align*} & \int\left(\lambda d\Pi_{\X}(\Z)-d\Pi_{\X'}(\Z)\right)_{+} \\ = & \lambda\left[1-\prod_{j\in[L],\x_{j}\neq\x'_{j}}\frac{n_{\x_{j},\x_{j}'}}{n_{\x_{j}}}\right]+\left[\prod_{j\in[L],\x_{j}\neq\x'_{j}}\frac{n_{\x_{j},\x_{j}'}}{n_{\x_{j}}}\right]\left[\lambda-\prod_{j\in[L],\x_{j}\ne\x'_{j}}\frac{n_{\x_{j}}}{n_{\x'_{j}}}\right]_{+}. \end{align*} \paragraph{Proof of Lemma \ref{lem:optperterb}} It is sufficient to proof that, for any $\X'\neq\X^*$, we have \[ \int\left(\lambda d\Pi_{\X}(\Z)-d\Pi_{\X^*}(\Z)\right)_{+}\ge\int\left(\lambda d\Pi_{\X}(\Z)-d\Pi_{\X'}(\Z)\right)_{+}. \] Notice that for any $\lambda\ge0$, define \[ Q(\X,\X'')=\lambda\left[1-\prod_{j\in[L],\x_{j}\neq\x'_{j}}\frac{n_{\x_{j},\x_{j}''}}{n_{\x_{j}}}\right]+\left[\prod_{j\in[L],\x_{j}\neq\x'_{j}}\frac{n_{\x_{j},\x_{j}''}}{n_{\x_{j}}}\right]\left(\lambda-1\right)_{+}. \] Given any \X, we can view $Q(\X,\X'')$ as the function of $n_{\x_{i},\x_{i}''}/n_{\x_{i}}$, $i\in[L]$. And $Q(\X,\X'')$ is a decreasing function of $n_{\x_{i},\x_{i}''}/n_{\x_{i}}$ for any $i\in[L]$ when fixing $\frac{n_{\x_{j},\x_{j}''}}{n_{\x_{j}}}$ for all other $j \neq i$. Suppose $\tilde{r}_k$ is the $k$-th smallest quantities of $n_{\x_{i},\tilde{\x}_{i}^{*}}/n_{\x_{i}}$, $i\in[L]$ and $r'_k$ is the $k$-th smallest quantities of $n_{\x_{j},\tilde{\x}_{j}^{*}}/n_{\x_{i}}$, $i\in[L]$. By the construction of $\X^*$, we have $\tilde{r}_k \le r'_k$ for any $k\in[L]$. This implies that \[ Q(\X,\X^*)\ge Q(\X,\X'). \] \subsubsection{Proof of Theorem \ref{thm:tight}} We denote ${\ell^\rs}(\X, y) = p_A$, ${\ell^\rs}(\X, y_B) = p_B$ and $q = q_\X$ in this proof for simplicity. The $\X^*$ below is the one defined in the proof of Lemme \ref{lem:optperterb}. Our proof is based on constructing a randomized smoothing classifier that satisfies the desired property we want to prove. \paragraph{Case 1 $p_{A}\ge q$ and $p_{B}+q\le1$} Note that in this case $\left|S_{\X}\cap S_{\X^{*}}\right|/\left|S_{\X}\right|=1-q\ge(p_{A}-q)+p_{B}$, where the inequality is due to $p_{A}+p_{B}\le1$. Therefore, we can choose set $U_{1}$ and $U_{2}$ such that $U_{1}\subseteq S_{\X}\cap S_{\X^{*}}$; $U_{2}\subseteq S_{\X}\cap S_{\X^{*}}$; $U_{1}\cap U_{2}=\emptyset$; $\left|U_{1}\right|/\left|S_{\X}\right|=p_{A}-q$ and $\left|U_{2}\right|/\left|S_{\X}\right|=p_{B}$. We define the classifier: \[ f^{*}(\Z)=\begin{cases} y & \text{if}\ \Z\in\left(S_{\X}-S_{\X^{*}}\right)\cap U_{1}\\ y_B & \text{if}\ \Z\in \left(S_{\X^{*}}-S_{\X}\right) \cup U_{2} \\ \text{other class ($c \neq y$ or $y_B$)} & \text{if}\ \Z\in S_{\X}\cap S_{\X^{*}}-\left(U_{1}\cup U_{2}\right)\\ \text{any\ class ($c\in \mathcal Y$)} & \text{otherwise} \end{cases} \] This classifier is well defined for binary classification because $S_{\X}\cap S_{\X^{*}}-\left(U_{1}\cup U_{2}\right)=\emptyset$. \paragraph{Case 2 $p_{A}<q$ and $p_{B}+q\le1$} In this case, we can choose set $U_{1}$ and $U_{2}$ such that $U_{1}\subseteq S_{\X}-S_{\X^{*}}$; $U_{2}\subseteq S_{\X}\cap S_{\X^{*}}$; $\left|U_{1}\right|/\left|S_{\X}\right|=p_{A}$ and $\left|U_{2}\right|/\left|S_{\X}\right|=p_{B}$. We define the classifier: \[ f^{*}(\Z)=\begin{cases} y & \text{if}\ \Z\in U_{1}\\ y_B & \text{if}\ \Z\in U_{2}\cup\left(S_{\X^{*}}-S_{\X}\right)\\ \text{other class ($c \neq y$ or $y_B$)} & \text{if}\ \Z\in S_{\X}-\left(U_{1}\cup U_{2}\right)\\ \text{any\ class ($c\in \mathcal Y$)} & \text{otherwise} \end{cases} \] This classifier is well defined for binary classification because $S_{\X}-\left(U_{1}\cup U_{2}\right)=\emptyset$. \paragraph{Case 3 $p_{A}\ge q$ and $p_{B}+q>1$} This case does not exist since we would have $p_{A}+p_{B}>1$. \paragraph{Case 4 $p_{A}<q$ and $p_{B}+q>1$} We choose set $U_{1}$ and $U_{2}$ such that $U_{1}\subseteq S_{\X}-S_{\X^{*}}$; $U_{2}\in S_{\X}-S_{\X^{*}}$; $U_{1}\cap U_{2}=\emptyset$; $\left|U_{1}\right|/\left|S_{\X}\right|=p_{A}$ and $\left|U_{2}\right|/\left|S_{\X}\right|=p_{B}-(1-q)$. Notice that the intersect of $U_{1}$ and $U_{2}$ can be empty as $\left|U_{1}\right|/\left|S_{\X}\right|+\left|U_{2}\right|/\left|S_{\X}\right|=p_{A}+p_{B}-(1-q)\le1-(1-q)=q=\left|S_{\X}-S_{\X^{*}}\right|/\left|S_{\X}\right|$. We define the classifier: \[ f^{*}(\Z)=\begin{cases} y & \text{if}\ \Z\in U_{1}\\ y_B & \text{if}\ \Z\in U_{2}\cup S_{\X^{*}}\\ \text{other class ($c \neq y$ or $y_B$)} & \text{if}\ \Z\in\left(S_{\X}-S_{\X^{*}}\right)-\left(U_{1}\cup U_{2}\right)\\ \text{any\ class ($c\in \mathcal Y$)} & \text{otherwise} \end{cases} \] This classifier is well defined for binary classification because $S_{\X}-S_{\X^{*}}-\left(U_{1}\cup U_{2}\right)=\emptyset$. It can be easily verified that for each case, the defined classifier satisfies all the conditions in Theorem \ref{thm:tight}. \section{Additional Experiment Details} We set $R = L$ in adversarial attacking, that is, all words in the sentence can be perturbed simultaneously by the attacker. We use 5,000 random draws in the Monte Carlo estimation of $\Delta_\X$, and use the same method in \citet{jia2019certified} to tune the hyper-parameters when training the base models {e.g. learning rate, batch size and the schedule of loss function}. For the IMDB dataset, we train the IBP models and ours for 60 and 10 epochs, respectively. For the Amazon dataset, we train the IBP models and ours for 100 and 20 epochs, respectively. We test our algorithm on two different datasets, IMDB and Amazon. The IMDB movie review dataset~\citep{maas2011imdb} is a sentiment classification dataset. It consists of 50,000 movie review comments with binary sentiment labels. The Amazon review dataset~\citep{mcauley2013hidden} is an extremely large dataset that contains 34,686,770 reviews with 5 different types of labels. Similar to \citet{cohen2019certified}, we test the models on randomly selected subsets of the test set with 1,250 and 6,500 examples for IMDB and Amazon dataset, respectively. \section{Conclusion} We proposed a robustness certification method, which provably guarantees that all the possible perturbations cannot break down the system. Compared with previous work such as \citet{jia2019certified, huang2019achieving}, our method is structure-free and thus can be easily applied to any pre-trained models (such as BERT) and character-level models (such as Char-CNN). The construction of the perturbation set is of critical importance to our method. In this paper, we used a heuristic way based on the synonym network to construct the perturbation set, which may not be optimal. In further work, we will explore more efficient ways for constructing the perturbation set. We also plan to generalize our approach to achieve certified robustness against other types of adversarial attacks in NLP, such as the out-of-list attack. An na\"ive way is to add the ``OOV" token into the synonyms set of every word, but potentially better procedures can be further explored. \section*{Acknowledgement} This work is supported in part by NSF CRII 1830161 and NSF CAREER 1846421. \section{Experiments} \label{sec:exp} We test our method on both IMDB~\citep{maas2011imdb} and Amazon~\citep{mcauley2013hidden} text classification tasks, with various types of models, including text CNN~\citep{kim2014textcnn}, Char-CNN~\citep{zhang2015charnn} and BERT~\citep{devlin2018bert}. We compare with the recent IBP-based methods \citep{jia2019certified, huang2019achieving} as baselines. Text CNN ~\citep{kim2014textcnn} was used in \citet{jia2019certified} and achieves the best result therein. All the baseline models are trained and tuned using the schedules recommended in the corresponding papers. We consider the case when $R=L$ during attacking, which means all words in the sentence can be perturbed simultaneously by the attacker. Code for reproducing our results can be found in \url{https://github.com/lushleaf/Structure-free-certified-NLP}. \paragraph{Synonym Sets} Similar to \citet{jia2019certified, alzantot2018generating}, we construct the synonym set $S_x$ of word $x$ to be the set of words with $\geq 0.8$ cosine similarity in the GLOVE vector space. The word vector space is constructed by post-processing the pre-trained GLOVE vectors~\citep{pennington2014glove} using the counter-fitted method \citep{mrkvsic2016counter} and the ``all-but-the-top'' method \citep{mu2018allbutthetop} to ensure that synonyms are near to each other while antonyms are far apart. \paragraph{Perturbation Sets} We say that two words $x$ and $ x'$ are connected synonymously if there exists a path of words $x = x_1, x_2, \ldots, x_\ell = x'$, such that all the successive pairs are synonymous. Let $B_x$ to be the set of words connected to $x$ synonymously. Then we define the perturbation set $P_x$ to consist of the top $K$ words in $B_x$ with the largest GLOVE cosine similarity if $|B_x| \geq K$, and set $P_x = B_x$ if $|B_x| < K$. Here $K$ is a hyper-parameter that controls the size of $P_x$ and hence trades off the smoothness and accuracy of $f^\rs$. We use $K=100$ by default and investigate its effect in Section \ref{apx:trades}. \paragraph{Evaluation Metric} We evaluate the certified robustness of a model $f^\rs$ on a dataset with the \emph{certified accuracy} \citep{cohen2019certified}, which equals the percentage of data points on which $f^\rs$ is certified robust, which, for our method, holds when $\Delta_\X > 0$ can be verified. \cutforspace{ For the IBP-based methods \citep{jia2019certified, huang2019achieving}, the certified accuracy is calculated similarly, with certified robustness holds when the lower bound of the logits of the true labels are larger than the upper bounds of all the other classes based on IBP. } \subsection{Main Results} We first demonstrate that adversarial word substitution is able to give strong attack in our experimental setting. Using IMDB dataset, we attack the vanilla BERT \citep{devlin2018bert} with the adversarial attacking method of \citet{jin2019bert}. The vanilla BERT achieves a $91\%$ clean accuracy (the testing accuracy on clean data without attacking), but only a $20.1\%$ adversarial accuracy (the testing accuracy under the particular attacking method by \citet{jin2019bert}). We will show later that our method is able to achieve $87.35\%$ certified accuracy and thus the corresponding adversarial accuracy must be higher or equal to $87.35\%$. We compare our method with IBP ~\citep{jia2019certified, huang2019achieving}. in Table~\ref{tab:textcnn}. We can see that our method clearly outperforms the baselines. In particular, our approach significantly outperforms IBP on Amazon by improving the $14.00\%$ baseline to $24.92\%$. Thanks to its structure-free property, our algorithm can be easily applied to any pre-trained models and character-level models, which is not easily achievable with \citet{jia2019certified} and \citet{huang2019achieving}. Table ~\ref{tab:model} shows that our method can further improve the result using Char-CNN (a character-level model) and BERT~\citep{devlin2018bert}, achieving an $87.35\%$ certified accuracy on IMDB. In comparison, the IBP baseline only achieves a $79.74\%$ certified accuracy under the same setting. \begin{table}[btp] \begin{center}\scalebox{.9}{ \begin{tabular}{l|cc} \toprule \bf Method & \bf IMDB & \bf Amazon \\ \hline \citet{jia2019certified} & 79.74 & 14.00 \\ \citet{huang2019achieving} & 78.74 & 12.36 \\ Ours & \bf 81.16 & \bf 24.92 \\ \bottomrule \end{tabular}} \end{center} \caption{\label{tab:textcnn} The certified accuracy of our method and the baselines on the IMDB and Amazon dataset.} \end{table} \begin{table}[btp] \begin{center}\scalebox{.9}{ \begin{tabular}{l|l|c} \toprule \bf Method & \bf Model & \bf Accuracy \\ \hline \citet{jia2019certified} & CNN & 79.74 \\ \citet{huang2019achieving} & CNN & 78.74 \\ \hline \multirow{3}{*}{Ours} & CNN & 81.16 \\ & Char-CNN & 82.03 \\ & BERT & \bf 87.35 \\ \bottomrule \end{tabular}} \end{center} \caption{\label{tab:model} The certified accuracy of different models and methods on the IMDB dataset.} \end{table} \subsection{Trade-Off between Clean Accuracy and Certified Accuracy} \label{apx:trades} We investigate the trade-off between smoothness and accuracy while tuning $K$ in Table \ref{tab:trades}. We can see that the clean accuracy decreases when $K$ increases, while the gap between the clean accuracy and certified accuracy, which measures the smoothness, decreases when $K$ increases. The best certified accuracy is achieved when $K=100$. \begin{table}[hbtp] \begin{centering} \begin{tabular}{l|ccccc} \toprule $K$ & 20 & 50 & 100 & 250 & 1000 \\ \hline \small{Clean (\%)} & \small{88.47} & \small{88.48} & \small{88.09} & \small{84.83} & \small{67.54} \\ \small{Certified (\%)} & \small{65.58} & \small{77.32} & \small{81.16} & \small{79.98} & \small{65.13} \\ \bottomrule \end{tabular}\caption{\label{tab:trades}Results of the smoothed model $f^\rs$ with different $K$ on IMDB using text CNN. ``Clean" represents the accuracy on the clean data without adversarial attacking and ``Certified" the certified accuracy. } \par\end{centering} \end{table} \section{Introduction} Deep neural networks have achieved state-of-the-art results in many NLP tasks, but also have been shown to be brittle to carefully crafted adversarial perturbations, such as replacing words with similar words ~\citep{alzantot2018generating}, adding extra text ~\citep{wallace2019universal}, and replacing sentences with semantically similar sentences ~\citep{ribeiro2018semantically}. These adversarial perturbations are imperceptible to humans, but can fool deep neural networks and break their performance. Efficient methods for defending these attacks are of critical importance for deploying modern deep NLP models to practical automatic AI systems. In this paper, we focus on defending the synonymous word substitution attacking ~\citep{alzantot2018generating}, in which an attacker attempts to alter the output of the model by replacing words in the input sentence with their synonyms according to a synonym table, while keeping the meaning of this sentence unchanged. A model is said to be \emph{certified robust} if such an attack is guaranteed to fail, no matter how the attacker manipulates the input sentences. Achieving and verifying certified robustness is highly challenging even if the synonym table used by the attacker is known during training \citep[see][]{jia2019certified}, because it requires to check every possible synonymous word substitution, whose number is exponentially large. Various defense methods against synonymous word substitution attacks have been developed ~\citep[e.g.,][]{wallace2019universal, ebrahimi2017hotflip}, most of which, however, are not {certified robust} in that they may eventually be broken by stronger attackers. Recently, \citet{jia2019certified, huang2019achieving} proposed the first certified robust methods against word substitution attacking. Their methods are based on the interval bound propagation (IBP) method \citep{dvijotham2018ibp} which computes the range of the model output by propagating the interval constraints of the inputs layer by layer. However, the IBP-based methods of \citet{jia2019certified, huang2019achieving} are limited in several ways. First, because IBP only works for certifying neural networks with continuous inputs, the inputs in \citet{jia2019certified} and \citet{huang2019achieving} are taken to be the word embedding vectors of the input sentences, instead of the discrete sentences. This makes it inapplicable to character-level~\citep{zhang2015charnn} and subword-level~\citep{bojanowski2017subword} model, which are more widely used in practice \citep{wu2016google}. \cutforspace{ Secondly, IBP requires to access the structures of the models, and needs to be derived and implemented at a model-by-model basis, which makes it difficult to use complex models, especially large-scale pre-trained models such as BERT ~\citep{devlin2018bert}. Finally, the embedding vectors in NLP models can be non-local and hence make the IBP bounds relatively loose, because semantically similar words can have very different embedding vectors~\citep{mu2018allbutthetop}. In comparison, the adversarial perturbations in image classifications are constrained in small balls (e.g., $\ell_2$ or $\ell_1$), on which IBP can provide tighter bounds. } In this paper, we propose a \emph{structure-free} certified defense method that applies to arbitrary models that can be queried in a black-box fashion, without any requirement on the model structures. Our method is based on the idea of randomized smoothing, which smooths the model with random word substitutions build on the synonymous network, and leverage the statistical properties of the randomized ensembles to construct provably certification bounds. Similar ideas of provably certification using randomized smoothing have been developed recently in deep learning \citep[e.g.,][]{cohen2019certified, salman2019provably, zhang2020black, lee2019tight}, but mainly for computer vision tasks whose inputs (images) are in a continuous space \citep{cohen2019certified}. Our method admits a substantial extension of the randomized smoothing technique to discrete and structured input spaces for NLP. We test our method on various types of NLP models, including text CNN \citep{kim2014textcnn}, Char-CNN \citep{zhang2015charnn}, and BERT \citep{devlin2018bert}. Our method significantly outperforms the recent IBP-based methods \citep{jia2019certified, huang2019achieving} on both IMDB and Amazon text classification. In particular, we achieve an 87.35\% certified accuracy on IMDB by applying our method on the state-of-the-art BERT, on which previous certified robust methods are not applicable. \section{Adversarial Word Substitution} \label{sec:background} In a text classification task, a model $f(\X)$ maps an input sentence $\X\in\mathcal{X}$ to a label $c$ in a set $\mathcal{Y}$ of discrete categories, where $\X = \x_{1},\ldots, \x_{L}$ is a sentence consisting of $L$ words. In this paper, we focus on adversarial word substitution in which an attacker arbitrarily replaces the words in the sentence by their synonyms according to a synonym table to alert the prediction of the model. Specifically, for any word $\x$, we consider a pre-defined synonym set $S_{\x}$ that contains the synonyms of $\x$ (including $\x$ itself). We assume the synonymous relation is symmetric, that is, $\x$ is in the synonym set of all its synonyms. The synonym set $S_{\x}$ can be built based on GLOVE~\citep{pennington2014glove}. With a given input sentence $\X = \x_{1}$,\ldots, $\x_{L}$, the attacker may construct an adversarial sentence ${\X'}=\x'_{1},\ldots,\x'_{L}$ by perturbing at most $R\le L$ words $x_i$ in $\X$ to any of their synonyms $ x'_i \in S_{x_i}$ \begin{align* \begin{split} & S_{\X} := \left \{ {\X'}\colon \norm{\X' - \X}_{0} \leq R, ~~\x'_{i}\in S_{\x_{i}}, \forall i \right\}, \end{split} \end{align*} where $S_{\X}$ denotes the candidate set of adversarial sentences available to the attacker. Here $\norm{ \X' - \X}_{0} := \sum_{i=1}^{L}\mathbb{I}\left\{ \x'_{i}\ne\x_{i}\right\}$ is the Hamming distance, with $\mathbb{I}\{\cdot\}$ the indicator function. It is expected that all $ \X' \in S_{\X}$ have the same semantic meaning as $\X$ for human readers, but they may have different outputs from the model. The goal of the attacker is to find $ \X' \in S_{\X}$ such that $f(\X) \neq f( \X')$. \paragraph{Certified Robustness} Formally, a model $f$ is said to be \emph{certified robust} against word substitution attacking on an input $\X$ if it is able to give consistently correct predictions for all the possible word substitution perturbations, i.e, \begin{align}\label{equ:certified} \text{$y = f(\X) = f( \X')$,~~~~ for all $ \X' \in S_\X,$} \end{align} where $y$ denotes the true label of sentence $\X$. Deciding if $f$ is certified robust can be highly challenging, because, unless additional structural information is available, it requires to exam all the candidate sentences in $S_\X$, whose size grows exponentially with $R$. In this work, we mainly consider the case when $R = L$, which is the most challenging case. \section{Certifying Smoothed Classifiers} Our idea is to replace $f$ with a more smoothed model that is easier to verify by averaging the outputs of a set of randomly perturbed inputs based on random word substitutions. The smoothed classifier $f^{\rs}$ is constructed by introducing random perturbations on the input space, \begin{align*} & f^{\rs}(\X)=\underset{c\in\mathcal{Y}}{\arg\max}\ \mathbb{P}_{\Z\sim\Pi_{\X}}\left(f(\Z)=c\right), \end{align*} where $\Pi_{\X}$ is a probability distribution on the input space that prescribes a random perturbation around $\X$. For notation, we define $$ {\ell^\rs}(\X, c) :=\mathbb{P}_{\Z\sim\Pi_{\X}}\left(f(\Z)=c\right) , $$ which is the ``soft score'' of class $c$ under $f^\rs$. The perturbation distribution ${\Pi_\X}$ should be chosen properly so that $f^\rs$ forms a close approximation to the original model $f$ (i.e., $f^\rs(\X) \approx f(\X)$), and is also sufficiently random to ensure that $f^\rs$ is smooth enough to allow certified robustness (in the sense of Theorem~\ref{thm:lb} below). \cutforspace{ For vision tasks, Gaussian distribution is a natural choice for $\Pi_{\X}$ as the input is in a continuous Euclidean space \cite{cohen2019certified}. However, Gaussian perturbation can not be directly applied on discrete sentence inputs. } In our work, we define $\Pi_\X$ to be the uniform distribution on a set of random word substitutions. Specifically, let $P_{\x}$ be a \emph{perturbation set} for word $\x$ in the vocabulary, which is different from the \emph{synonym set} $S_\x$. In this work, we construct $P_{\x}$ based on the top $K$ nearest neighbors under the cosine similarity of GLOVE vectors, where $K$ is a hyperparameter that controls the size of the perturbation set; see Section \ref{sec:exp} for more discussion on $P_x$. For a sentence $\X=\x_{1},\ldots,\x_{L}$, the sentence-level perturbation distribution $\Pi_\X$ is defined by randomly and independently perturbing each word $x_i$ to a word in its perturbation set $P_{x_i}$ with equal probability, that is, \vspace{-10pt} \[ \Pi_{\X}(\Z)=\prod_{i=1}^{L}\frac{\mathbb{I}\left\{ z_{i}\in P_{\x_{i}}\right\} }{\left|P_{\x_{i}}\right|}, \] \vspace{-10pt} \noindent where $\Z = z_{1},\ldots, z_{L}$ is the perturbed sentence and $|P_{x_i}|$ denotes the size of $P_{x_i}$. Note that the random perturbation $\Z$ and the adversarial candidate $\X' \in S_\X$ are different. \begin{figure*} \vspace{-15pt} \centering \includegraphics[scale = 0.55]{img/figure_new3.pdf \vspace{-5pt} \caption{A pipeline of the proposed robustness certification approach.} \vspace{-15pt} \label{fig:framework} \end{figure*} \subsection{Certified Robustness} We now discuss how to certify the robustness of the smoothed model $f^{\rs}$. Recall that $f^\rs$ is certified robust if $y = f^\rs(\X')$ for any $\X' \in S_{\X}$, where $y$ is the true label. A sufficient condition for this is $$ \min_{\X'\in S_{\X}} {\ell^\rs}(\X', y) \geq \max_{\X' \in S_{\X}}{\ell^\rs}({\X'}, c) ~~~~~\forall c \neq y, $$ where the lower bound of ${\ell^\rs}(\X', y)$ on $\X' \in S_\X$ is larger than the upper bound of ${\ell^\rs}(\X', c)$ on $\X' \in S_\X$ for every $c\neq y$. The key step is hence to calculate the upper and low bounds of $ {\ell^\rs}(\X', c) $ for $\forall c\in \mathcal Y$ and $\X'\in S_\X$, which we address in Theorem~\ref{thm:lb} below. All proofs are in Appendix \ref{apx:pf}. \begin{theorem} \textbf{(Certified Lower/Upper Bounds)} \label{thm:lb} Assume the perturbation set $P_{\x}$ is constructed such that $\left|P_{\x}\right|=\left|P_{{\x'}}\right|$ for every word $x$ and its synonym ${\x'}\in S_{\x}$. Define \[ q_{\x}=\min_{{\x'}\in S_{\x}}{\left|P_{\x}\cap P_{{\x'}}\right|}/{\left|P_{\x}\right|}, \] where $q_{\x}$ indicates the overlap between the two different perturbation sets. For a given sentence $\X=\x_{1},\ldots,\x_{L}$, we sort the words according to $q_{\x}$, such that $q_{\x_{i_{1}}}\le q_{\x_{i_{2}}}\le\cdots\le q_{\x_{i_{L}}}$. Then \begin{align*} \min_{\X'\in S_{\X}} {\ell^\rs}(\X', c) & \ge\max({\ell^\rs}(\X, c) -q_\X,0)\\ \max_{\X'\in S_{\X}} {\ell^\rs}(\X', c) & \le\min({\ell^\rs}(\X, c) + q_\X,1). \end{align*} where $q_\X:=1-\prod_{j=1}^{R}q_{\x_{i_{j}}}$. Equivalently, this says \begin{align*} \left | {\ell^\rs}(\X', c) - {\ell^\rs}(\X, c) \right | \leq q_\X,~~~~ \text{any label $c \in \mathcal Y$}. \end{align*} \end{theorem} The idea is that, with the randomized smoothing, the difference between ${\ell^\rs}(\X', c)$ and ${\ell^\rs}(\X, c)$ is at most $q_\X$ for any adversarial candidate $\X' \in S_\X$. Therefore, we can give adversarial upper and lower bounds of ${\ell^\rs}(\X', c)$ by ${\ell^\rs}(\X, c)\pm q_\X$, which, importantly, avoids the difficult adversarial optimization of ${\ell^\rs}(\X', c)$ on ${\X' \in S_\X}$, and instead just needs to evaluate ${\ell^\rs}(\X, c)$ at the original input $\X$. We are ready to describe a practical criterion for checking the certified robustness. \begin{proposition} \label{pro:cAcB} For a sentence $\X$ and its label $y$, we define \begin{align*} & y_B = \arg\max_{c\in \mathcal Y, c \neq y} {\ell^\rs}(\X, c). \end{align*} Then under the condition of Theorem~\ref{thm:lb}, we can certify that $f(\X') = f(\X) = y$ for any $\X' \in S_{\X}$ if \begin{align} \label{equ:DeltaX} \Delta_\X \overset{def}{=} {\ell^\rs}(\X, y) - {\ell^\rs}(\X, y_B) - 2q_{\X} > 0. \end{align} \end{proposition} Therefore, certifying whether the model gives consistently correct prediction reduces to checking if $\Delta_{ \X}$ is positive, which can be easily achieved with Monte Carlo estimation as we show in the sequel. \paragraph{Estimating ${\ell^\rs}(\X, c)$ and $\Delta_\X$} Recall that ${\ell^\rs}(\X, c)= \mathbb{P}_{\Z\sim\Pi_{\X}}(f(\Z)=c)$. We can estimate ${\ell^\rs}(\X, c)$ with a Monte Carlo estimator $\sum_{i=1}^{n}\mathbb{I} \{ f(\Z^{(i)})=c\}/n$, where $\Z^{(i)}$ are i.i.d. samples from $\Pi_{\X}$. And $\Delta_\X$ can be approximated accordingly. Using concentration inequality, we can quantify the non-asymptotic approximation error. This allows us to construct rigorous statistical procedures to reject the null hypothesis that $f^\rs$ is not certified robust at $\X$ (i.e., $\Delta_{\X} \leq 0$) with a given significance level (e.g., $1\%$). See Appendix \ref{apx:MC} for the algorithmic details of the testing procedure. We can see that our procedure is \emph{structure-free} in that it only requires the black-box assessment of the output $f(\Z^{(i)})$ of the random inputs, and does not require any other structural information of $f$ and $f^\rs$, which makes our method widely applicable to various types of complex models. \paragraph{Tightness} A key question is if our bounds are sufficiently tight. The next theorem shows that the lower/upper bounds in Theorem \ref{thm:lb} are tight and can not be further improved unless further information of the model $f$ or $f^\rs$ is acquired. \begin{theorem} \textbf{(Tightness)} \label{thm:tight} Assume the conditions of Theorem \ref{thm:lb} hold. For a model $f$ that satisfies $f^\rs(\X) = y$ and $y_B$ as defined in Proposition~\ref{pro:cAcB}, there exists a model $f_*$ such that its related smoothed classifier ${{\ell}^\rs_*}$ satisfies ${{\ell}^\rs_*}(\X, c)={\ell^\rs}(\X, c)$ for $c = y$ and $c = y_B$, and \begin{align*} \min_{\X'\in S_{\X}} {{\ell}^\rs_*}(\X', y) & =\max({{\ell}^\rs_*}(\X, y)-q_\X,0)\\ \max_{\X'\in S_{\X}} {{\ell}^\rs_*}(\X',y_B) & =\min({{\ell}^\rs_*}(\X, y_B) +q_\X,1), \end{align*} where $q_\X$ is defined in Theorem~\ref{thm:lb}. \end{theorem} In other words, if we access ${\ell^\rs}$ only through the evaluation of ${\ell^\rs}(\X, y)$ and ${\ell^\rs}(\X, y_B)$, then the bounds in Theorem~\ref{thm:lb} are the tightest possible that we can achieve, because we can not distinguish between ${\ell^\rs}$ and the ${{\ell}^\rs_*}$ in Theorem~\ref{thm:tight} with the information available. \subsection{Practical Algorithm} \label{sec:prac} Figure \ref{fig:framework} visualizes the pipeline of the proposed approach. Given the synonym sets $S_\X$, we generate the perturbation sets $P_\X$ from it. When an input sentence $\X$ arrives, we draw perturbed sentences $\{\Z^{(i)}\}$ from $\Pi_\X$ and average their outputs to estimate $\Delta_\X$, which is used to decide if the model is certified robust for $\X$. \paragraph{Training the Base Classifier $f$} Our method needs to start with a base classifier $f$. Although it is possible to train $f$ using standard learning techniques, the result can be improved by considering that the method uses the smoothed $f^\rs$, instead of $f$. To improve the accuracy of $f^\rs$, we introduce a data augmentation induced by the perturbation set. Specifically, at each training iteration, we first sample a mini-batch of data points (sentences) and randomly perturbing the sentences using the perturbation distribution $\Pi_\X$. We then apply gradient descent on the model based on the perturbed mini-batch. Similar training procedures were also used for Gaussian-based random smoothing on continuous inputs \citep[see e.g.,][]{cohen2019certified}. Our method can easily leverage powerful pre-trained models such as BERT. In this case, BERT is used to construct feature maps and only the top layer weights are finetuned using the data augmentation method.
{'timestamp': '2020-06-01T02:07:45', 'yymm': '2005', 'arxiv_id': '2005.14424', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14424'}
arxiv
\section{Conclusions} \bibliographystyle{IEEEtran} \subsection{Dynamic program to compute $\mathbf F(\cdot)$} \label{app:F_compute} We here describe how to compute $\mathbf F(p,v)$ in $O(mn)$ time and space complexity, where $p=(p_1,...,p_n)$ and $v=v_1...v_m$, via a dynamic programming approach. We first define \begin{align*} &\mathbf G^{for}(k,j)\triangleq \mathbf F(p_{[1:k]},v_{[1:j]}). \numberthis \label{eq:G} \end{align*} Using Lemma~\ref{lemma:F_decomposition} with $i=n$, we get \begin{align*} \mathbf F(p,v) = \mathbf F(p_{[n-1]},v) + p_n^{v_m} (1-p_n)^{(1-v_m)} \mathbf F(p_{[n-1]},v_{[m-1]}). \end{align*} \noindent This translates to the following dynamic program for $\mathbf G^{for}$: \begin{align*} \mathbf G^{for}(k,j) = \mathbf G^{for}(k-1,j)+ p_{k}^{v_j}(1-p_{k})^{1-v_j}&\mathbf G^{for}(k-1,j-1),\numberthis \label{eq:approx_smap_dpfor} \end{align*} with the boundary conditions $\mathbf G^{for}(k,0)=1\ \forall\ k \geq 0$ and $\mathbf G^{for}(k,j)=0\ \forall\ k<j$. The algorithm is now summarized as Alg.~\ref{alg:F_comp}. \begin{algorithm}[h!] \caption{Computing $\mathbf F(p,v)$}\label{alg:F_comp} \begin{algorithmic}[1] \State Inputs: $p \in [0,1]^n$, $v \in \{0,1\}^m$ \State Outputs: $\mathbf F(p_{[1:k]},v_{[1:j]})$ for all $k \in [n]$ and $j\in[m]$ \State Initialize $\mathbf G^{for}(k,0)=1\ \forall\ k$ and $\mathbf G^{for}(k,j)=0\ \forall\ k<j$ \For {$k = 1:n$ and $j = 1:m$} \State Use \eqref{eq:approx_smap_dpfor} to update $\mathbf G^{for}(k,j)$ \EndFor \State return $\mathbf G^{for}(k,j)\ \forall\ k,j$ \end{algorithmic} \end{algorithm} We note that a similar dynamic programming approach yields $\mathbf F(p_{[k:n]},v_{[j:m]})$ for all $k \in [n]$ and $j\in[m]$ in $O(mn)$ time and space complexity by defining \begin{align*} &\mathbf G^{rev}(k,j)\triangleq \mathbf F(p_{[k:n]},v_{[j:m]}). \end{align*} \subsection{An algebraic definition of the infiltration product.} \label{app:infil_def} We now give a more formal definition of the infiltration product (see \cite{lothaire1997combinatorics} for the equivalence of the two definitions and a more rigorous treatment). A \textit{formal series} with indeterminates (or variables) in a set $\mathcal A$ and coefficients in a commutative ring $\mathcal R$, is a mapping of $\mathcal A^*$ onto $\mathcal R$. Recall that a commutative ring is a set which forms an abelian group under an \textit{addition} operation, is a monoid under a \textit{multiplication} operation which commutes, and the multiplication operation distributes over addition. Here we consider $\mathbb Z$, the set of integers as the commutative ring $\mathcal{R}$. A formal series is called a \textit{polynomial} if only a finite number of sequences are mapped to non-zero values, the rest of the sequences map to zero. Consider two polynomials $\sigma,\tau: \mathcal{A}^*\rightarrow \mathbb Z$. The value taken by a sequence $w\in \mathcal A^*$ on $\sigma$ (or the coefficient of $w$ in $\sigma$) is denoted by $\langle \sigma,w\rangle \in \mathbb R$. We also define binary addition ($\oplus$) and multiplication operations ($\times$) on the set of polynomials as follows: \begin{align} \langle \sigma\oplus \tau,w\rangle \triangleq \langle \sigma,w\rangle + \langle \tau,w \rangle \quad \forall w\in \mathcal A^*,\label{eq:polynomial_add}\\ \langle \sigma\times \tau,w\rangle \triangleq \sum_{\substack{f,g\in \mathcal A^*:\\ f.g=w}}\langle \sigma,f\rangle \langle \tau,g \rangle \quad \forall w\in \mathcal A^*.\label{eq:polynomial_prod} \end{align} We will use the usual symbols $+$ and $.$ in place of $\oplus$ and $\times$ in this work for convenience. The meaning of the operation would be clear depending on the operands. With these operations the set of polynomials form a non-commutative ring, and is denoted by $\mathbb Z\langle\mathcal A \rangle$, also called the free $\mathbb Z$-algebra on $\mathcal A$ in ring theory. Note that the addition and multiplication operations defined in \eqref{eq:polynomial_add} and \eqref{eq:polynomial_prod} are similar to the operations defined on commutative polynomials, except that the multiplication operation under the summation in \eqref{eq:polynomial_prod} ($f.g=w$) is actually concatenation and is non-commutative. The multiplication inside the summation in \eqref{eq:polynomial_prod} is multiplication in the real field and hence commutative. It is also easy to prove that the multiplication defined in \eqref{eq:polynomial_prod} distributes over addition defined in \eqref{eq:polynomial_add}. Thus, a polynomial in $\mathbb Z\langle\mathcal A \rangle$ can be represented as a sum of monomials in $\mathcal A^*$ each with an associated coefficient in $\mathbb Z$, i.e., $\sigma=\sum\limits_{w\in \mathcal A^*} \langle\sigma,w \rangle w$. Define the \textit{degree} of a polynomial to be equal to the length of a longest sequence with a non-zero coefficient in the polynomial and the \textit{number of terms} of a polynomial as the number of sequences with non-zero coefficients in the polynomial. Note that a degree $d$ polynomial could have a number of terms upto $2^{d+1}-1$. With this, the \textit{infiltration product} (in general, for two polynomials) is defined as follows: \begin{align} \forall f\in \mathcal{A}^*,& \quad f\uparrow e = e\uparrow f=f.\nonumber \\ \forall f,g\in \mathcal{A}^*&,\quad \forall a,b\in \mathcal{A}, \nonumber\\ fa\uparrow gb=(f\uparrow gb)a&+(fa\uparrow g)b+\mathbbm{1}_{a=b}(f\uparrow g)a.\nonumber \\ \forall \sigma,\tau \in \mathbb{Z}\langle\mathcal{A} \rangle, \quad &\sigma\uparrow \tau=\sum_{f,g\in \mathcal{A}^*} \langle \sigma,f \rangle \langle \tau,g \rangle (f\uparrow g). \label{def:infiltforseq} \end{align} \subsection{Proof of the channel equivalence in Theorem~\ref{thm:channel_equiv}.} \label{app:channel_equiv} We first state a lemma (introduced in \cite{Srini2019}) which is closely related to the channel equivalence. The proof of the Lemma is relegated to Appendix~\ref{app:bin_inf_lemma}. \begin{restatable}{lemma}{bininfrelation} \label{lemma:bin_inf_relation} For $h,f_1,f_2,...,f_m \in \mathcal{A}^*$,\\ $${h \choose f_1} {h \choose f_2}...{h \choose f_m}=\sum_{w\in \mathcal{A}^*}\langle f_1\uparrow f_2\uparrow ...\uparrow f_m,w \rangle{h \choose w}.$$ \end{restatable The channel equivalence can essentially be tied to this lemma as follows: consider the two channel models in Fig.~\ref{fig:channel_equiv}. The probability of observations given the input in both cases is proportional to the number of ways of obtaining the observations given the input. \begin{itemize} \item For the $t$-trace deletion channel model in Fig.~\ref{fig:channel_equiv} (a), the number of ways to obtain the traces given the input is equal to ${X \choose \tilde{Y}^{(1)}}{X \choose \tilde{Y}^{(2)}}...{X \choose \tilde{Y}^{(t)}}$. \item For the cascade model in Fig.~\ref{fig:channel_equiv} (b), the number of ways to obtain the traces given the input is equal to $\sum_{z} {X \choose z} \langle \tilde Y^{(1)}\uparrow \tilde Y^{(2)} \uparrow...\uparrow \tilde Y^{(t)},z \rangle$ (this is shown in the proof of the theorem). \end{itemize} Clearly by Lemma~\ref{lemma:bin_inf_relation}, the above two are equal, thus proving the equivalence of the two channel models. On the contrary, this equivalence provides a nice physical interpretation of Lemma~\ref{lemma:bin_inf_relation}. \channelequiv* \begin{proof} We show the probabilistic equivalence between the two channel models in Fig.~\ref{fig:channel_equiv}: 1) $t$ independent deletion channels 2) cascade of a deletion channel with parameter $\delta^t$ with the \textit{remnant} channel with parameter $\delta$ defined as follows: an input symbol to the remnant channel is included in $k>0$ given outputs and deleted in the rest with a probability $\frac{\delta^{t-k}(1-\delta)^k}{1-\delta^t}$. Given this definition, we now first compute the probability of a given set of output sequences given an input sequence for the remnant channel, namely $\Pr(\tilde Y^{(1)},\tilde Y^{(2)},...,\tilde Y^{(t)}|Z)$. First, note that there can be multiple deletion patterns corresponding to outputs $\tilde Y^{(1)},\tilde Y^{(2)},...,\tilde Y^{(t)}$ resulting from a given input $Z$. The number of such patterns is equal to $\langle \tilde Y^{(1)}\uparrow \tilde Y^{(2)} \uparrow...\uparrow \tilde Y^{(t)},Z \rangle$, which essentially follows from the definition of the infiltration product. Consider one such valid deletion pattern, i.e., a deletion pattern $\mathcal{D}$ that is a mapping of the symbols in $Z$ onto the symbols in $\tilde Y^{(1)},\tilde Y^{(2)},...,\tilde Y^{(t)}$: $\mathcal{D}=\{(1,S_1),(2,S_2),...,(|Z|,S_{|Z|})\}$. Here $(i,S_i)$ represents the fact that $Z_i$ is not deleted in the output set $\tilde{Y}^{(S_i)}$ and is deleted in the rest. Clearly, $|S_i|>0$ from the definition of the remnant channel. Also $\sum_{i=1}^{|Z|}|S_i|=\sum_{j=1}^t|\tilde{Y}^{(j)}|$ since every symbol of each output is associated with exactly one input symbol and hence corresponds to one particular $S_i$. Thus, \begin{align*} \Pr(&\tilde Y^{(1)},\tilde Y^{(2)},...,\tilde Y^{(t)}|Z) \\&= \langle \tilde Y^{(1)}\uparrow \tilde Y^{(2)} \uparrow...\uparrow \tilde Y^{(t)},Z \rangle \Pr(\tilde Y^{(1)},\tilde Y^{(2)},...,\tilde Y^{(t)}|Z,\mathcal{D})\\ &=\langle \tilde Y^{(1)}\uparrow \tilde Y^{(2)} \uparrow...\uparrow \tilde Y^{(t)},Z \rangle \prod_{i=1}^{|Z|}\frac{(1-\delta)^{|S_i|}\delta^{t-|S_i|}}{1-\delta^t}\\ &=\langle \tilde Y^{(1)}\uparrow \tilde Y^{(2)} \uparrow...\uparrow \tilde Y^{(t)},Z \rangle \frac{(1-\delta)^{\sum|S_i|}\delta^{|Z|t-\sum |S_i|}}{(1-\delta^t)^{|Z|}}\\ &=\langle \tilde Y^{(1)}\uparrow \tilde Y^{(2)} \uparrow...\uparrow \tilde Y^{(t)},Z \rangle \frac{(1-\delta)^{\sum|\tilde{Y}^{(j)}|}\delta^{|Z|t-\sum |\tilde{Y}^{(j)}|}}{(1-\delta^t)^{|Z|}}. \end{align*} We can then compute the probability of the output given the input for the cascade channel as \begin{align*} \Pr(&\tilde Y^{(1)},\tilde Y^{(2)},...,\tilde Y^{(t)}|X)\\ &= \sum_{z} \Pr(\tilde Y^{(1)},\tilde Y^{(2)},...,\tilde Y^{(t)},Z=z|X)\\ &= \sum_{z} \Pr(Z=z|X)\Pr(\tilde Y^{(1)},\tilde Y^{(2)},...,\tilde Y^{(t)}|Z=z)\\ &= \sum_{z} \Bigg[{X \choose z} \delta^{t(|X|-|z|)}(1-\delta^t)^{|z|}\langle \tilde Y^{(1)}\uparrow \tilde Y^{(2)} \uparrow...\uparrow \tilde Y^{(t)},z \rangle \frac{(1-\delta)^{\sum|\tilde{Y}^{(j)}|}\delta^{|z|t-\sum |\tilde{Y}^{(j)}|}}{(1-\delta^t)^{|z|}}\Bigg]\\ &= \left[\sum_{z} {X \choose z} \langle \tilde Y^{(1)}\uparrow \tilde Y^{(2)} \uparrow...\uparrow \tilde Y^{(t)},z \rangle\right] \delta^{t|X|-\sum |\tilde{Y}^{(j)}|} {(1-\delta)^{\sum|\tilde{Y}^{(j)}|}}\\ &={X \choose \tilde{Y}^{(1)}}{X \choose \tilde{Y}^{(2)}}...{X \choose \tilde{Y}^{(t)}} \delta^{t|X|-\sum |\tilde{Y}^{(j)}|} {(1-\delta)^{\sum|\tilde{Y}^{(j)}|}}\\ &=\prod_{j=1}^t {X \choose \tilde{Y}^{(j)}} \delta^{|X|-|\tilde{Y}^{(j)}|} {(1-\delta)^{|\tilde{Y}^{(j)}|}}\\ &=\Pr(Y^{(1)}, Y^{(2)},..., Y^{(t)}|X), \end{align*} proving the equivalence. \end{proof} \subsection{Proof of Lemma~\ref{lemma:F_decomposition}.} \label{app:F_lemma_proof} \deletionMLrellemma* \begin{proof} The proof of this lemma uses a similar approach as the proof of Thm.~\ref{thm:approx_smap_postprob}. First, in the expression for $\mathbf F(\cdot )$, we separate out the subsets that contain index $i$: \begin{align*} \mathbf F(p,Y) &= \sum\limits_{\substack{\mathcal S|\mathcal S\subseteq [n],\\|\mathcal S|=m}} \quad \prod\limits_{j=1}^m p_{\mathcal S_j}^{Y_j} (1-p_{\mathcal S_j})^{1-Y_j}\\ &= \sum\limits_{\substack{\mathcal S|\mathcal S\subseteq [n],\\|\mathcal S|=m, \\ i \notin \mathcal S}} \quad \prod\limits_{j=1}^m p_{\mathcal S_j}^{Y_j} (1-p_{\mathcal S_j})^{1-Y_j} + \sum\limits_{\substack{\mathcal S|\mathcal S\subseteq [n],\\|\mathcal S|=m,\\ i \in \mathcal S}} \quad \prod\limits_{j=1}^m p_{\mathcal S_j}^{Y_j} (1-p_{\mathcal S_j})^{1-Y_j}\\ &= \mathbf F(p_{[n]\backslash \{i\}},Y) + \sum\limits_{\substack{\mathcal S|\mathcal S\subseteq [n],\\|\mathcal S|=m,\\ i \in \mathcal S}} \quad \prod\limits_{j=1}^m p_{\mathcal S_j}^{Y_j} (1-p_{\mathcal S_j})^{1-Y_j}. \numberthis \label{eq:Flemma_proof1} \end{align*} Now the second term can be further split as, \begin{align*} \sum\limits_{\substack{\mathcal S|\mathcal S\subseteq [n],\\|\mathcal S|=m,\\ i \in \mathcal S}} \quad \prod\limits_{j=1}^m p_{\mathcal S_j}^{Y_j} (1-p_{\mathcal S_j})^{1-Y_j} &= \sum_{k=1}^m\sum\limits_{\substack{\mathcal S|\mathcal S\subseteq [n],\\|\mathcal S|=m,\\ \mathcal S_k = i}} \quad \prod\limits_{j=1}^m p_{\mathcal S_j}^{Y_j} (1-p_{\mathcal S_j})^{1-Y_j}. \end{align*} One could express the set $\mathcal S$ as the union $\mathcal S = \mathcal S' \cup \{i\} \cup \mathcal S''$ such that $\mathcal S' \subseteq [i-1]$ and $\mathcal S'' \subseteq [i+1:n]$ to get \begin{align*} &\sum_{k=1}^m\sum\limits_{\substack{\mathcal S|\mathcal S\subseteq [n],\\|\mathcal S|=m,\\ \mathcal S_k = i}} \quad \prod\limits_{j=1}^m p_{\mathcal S_j}^{Y_j} (1-p_{\mathcal S_j})^{1-Y_j}\\ &= \sum_{k=1}^m\sum_{\substack{\mathcal S'|\\ \mathcal S'\subseteq [i-1]\\ |\mathcal S'|=k-1}}\sum_{\substack{\mathcal S''|\\ \mathcal S'' \subseteq [i+1:n]\\ |\mathcal S''|=m-k}} \left( \prod\limits_{j=1}^{k-1} p_{\mathcal S'_j}^{Y_j} (1-p_{\mathcal S'_j})^{1-Y_j} \right) \left( p_{i}^{Y_k} (1-p_{i})^{1-Y_k} \right) \left( \prod\limits_{j=1}^{m-k} p_{\mathcal S''_j}^{Y_{j+k}} (1-p_{\mathcal S''_j})^{1-Y_{j+k}} \right)\\ &= \sum_{k=1}^m p_{i}^{Y_k} (1-p_{i})^{1-Y_k}\left(\sum_{\substack{\mathcal S'|\\ \mathcal S'\subseteq [i-1]\\ |\mathcal S'|=k-1}} \prod\limits_{j=1}^{k-1} p_{\mathcal S'_j}^{Y_j} (1-p_{\mathcal S'_j})^{1-Y_j} \right) \left( \sum_{\substack{\mathcal S''|\\ \mathcal S'' \subseteq [i+1:n]\\ |\mathcal S''|=m-k}} \prod\limits_{j=1}^{m-k} p_{\mathcal S''_j}^{Y_{j+k}} (1-p_{\mathcal S''_j})^{1-Y_{j+k}} \right)\\ &= \sum_{k=1}^m p_{i}^{Y_k} (1-p_{i})^{1-Y_k} \mathbf F(p_{[i-1]},Y_{[k-1]}) \mathbf F(p_{[i+1:n]},Y_{[k+1:m]}). \end{align*} The $\sum_{k=1}^m$ summation in the above expression could further be split into the two cases depending on whether $Y_k=0$ or $Y_k=1$, which simplifies the term $p_{i}^{Y_k} (1-p_{i})^{1-Y_k}$ to either $1-p_i$ or $p_i$ respectively. Thus, \begin{align*} &\sum\limits_{\substack{\mathcal S|\mathcal S\subseteq [n],\\|\mathcal S|=m,\\ i \in \mathcal S}} \quad \prod\limits_{j=1}^m p_{\mathcal S_j}^{Y_j} (1-p_{\mathcal S_j})^{1-Y_j}\\ &= (1-p_i)\sum_{k|Y_k=0} \mathbf F(p_{[i-1]},Y_{[k-1]}) \mathbf F(p_{[i+1:n]},Y_{[k+1:m]}) + p_i\sum_{k|Y_k=1} \mathbf F(p_{[i-1]},Y_{[k-1]}) \mathbf F(p_{[i+1:n]},Y_{[k+1:m]}).\numberthis \label{eq:Flemma_proof2} \end{align*} \noindent Plugging \eqref{eq:Flemma_proof2} in \eqref{eq:Flemma_proof1} concludes the proof of the Lemma. \end{proof} \subsection{Symbolwise posterior probabilities for the remnant channel} \label{app:remnant_postprob} Consider the remnant channel shown below, and let $Z=Z_1Z_2...Z_n$. Also let $Z_i \sim \text{Ber}(0.5)$. We aim to compute $\Pr(Z_i=1|\tilde Y^{(1)},\tilde Y^{(2)},...,\tilde Y^{(t)})$. \begin{figure}[!h] \centering \includegraphics[scale=0.4]{remnant_channel.pdf} \caption{The remnant channel} \end{figure} As seen in appendix~\ref{app:channel_equiv}, the input-output relation for this channel is given by: \begin{align*} \Pr(\tilde Y^{(1)},\tilde Y^{(2)},...,\tilde Y^{(t)}|Z) =\langle \tilde Y^{(1)}\uparrow \tilde Y^{(2)} \uparrow...\uparrow \tilde Y^{(t)},Z \rangle \frac{(1-\delta)^{\sum|\tilde{Y}^{(j)}|}\delta^{nt-\sum |\tilde{Y}^{(j)}|}}{(1-\delta^t)^{n}}. \end{align*} Now, one could write the symbolwise posterior probabilities for $Z$ as: \begin{align*} \Pr(Z_i=1&|\tilde Y^{(1)},\tilde Y^{(2)},...,\tilde Y^{(t)}) = \sum_{\substack{z||z|=n,\\z_i=1}} \Pr(z|\tilde Y^{(1)},\tilde Y^{(2)},...,\tilde Y^{(t)})\\ &{=} \frac{1}{2^n \Pr(\tilde Y^{(1)}...,\tilde Y^{(t)})} \sum_{\substack{z||z|=n,\\z_i=1}} \Pr(\tilde Y^{(1)},\tilde Y^{(2)},...,\tilde Y^{(t)}|z)\\ &{=} \frac{{(1-\delta)^{\sum|\tilde{Y}^{(j)}|}\delta^{nt-\sum |\tilde{Y}^{(j)}|}}}{(1-\delta^t)^{n} 2^n \Pr(\tilde Y^{(1)},...,\tilde Y^{(t)})} \sum_{\substack{z||z|=n,\\z_i=1}} \langle \tilde Y^{(1)}\uparrow \tilde Y^{(2)} \uparrow...\uparrow \tilde Y^{(t)},z \rangle. \numberthis \label{eq:remant_map_prob_1} \end{align*} A similar expression can be obtained for the case when $Z_i=0$ as \begin{align*} \Pr(Z_i=0&|\tilde Y^{(1)},\tilde Y^{(2)},...,\tilde Y^{(t)})\\ &{=} \frac{{(1-\delta)^{\sum|\tilde{Y}^{(j)}|}\delta^{nt-\sum |\tilde{Y}^{(j)}|}}}{(1-\delta^t)^{n} 2^n \Pr(\tilde Y^{(1)},...,\tilde Y^{(t)})} \sum_{\substack{z||z|=n,\\z_i=0}} \langle \tilde Y^{(1)}\uparrow \tilde Y^{(2)} \uparrow...\uparrow \tilde Y^{(t)},z \rangle. \numberthis \label{eq:remant_map_prob_0} \end{align*} We could further simplify \eqref{eq:remant_map_prob_1} and \eqref{eq:remant_map_prob_0} using the fact that \begin{align*} \Pr(Z_i=1|\tilde Y^{(1)},...,\tilde Y^{(t)}) &= \frac{\Pr(Z_i=1|\tilde Y^{(1)},...,\tilde Y^{(t)})}{\Pr(Z_i=0|\tilde Y^{(1)},...,\tilde Y^{(t)})+\Pr(Z_i=1|\tilde Y^{(1)},...,\tilde Y^{(t)})} \\ &= \frac{\sum\limits_{\substack{z||z|=n,\\z_i=1}} \langle \tilde Y^{(1)}\uparrow \tilde Y^{(2)} \uparrow...\uparrow \tilde Y^{(t)},z \rangle}{\sum\limits_{\substack{z||z|=n}} \langle \tilde Y^{(1)}\uparrow \tilde Y^{(2)} \uparrow...\uparrow \tilde Y^{(t)},z \rangle}. \numberthis \label{eq:remnant_map_prob} \end{align*} We precisely describe the algorithm which computes the terms in \eqref{eq:remnant_map_prob} in section~\ref{sec:exactsmap}, by exploiting the edit graph interpretation of the infiltration product, but give a high level idea below. The complexity of such an algorithm is $O((2n)^t)$ which is equal to the number of edges in the edit graph. Note that for a fixed number of traces, this algorithm is polynomial in the blocklength as opposed to a naive approach of iterating through all the $n$-length sequences. Recall that $\langle \tilde Y^{(1)}\uparrow \tilde Y^{(2)} \uparrow...\uparrow \tilde Y^{(t)},z \rangle$ is the number of paths from origin to destination of the edit graph $\mathcal G(\tilde Y^{(1)}, ..., \tilde Y^{(t)})$ which correspond to $z$. Therefore, $\sum_{\substack{z||z|=n}}\langle \tilde Y^{(1)}\uparrow \tilde Y^{(2)} \uparrow...\uparrow \tilde Y^{(t)},z \rangle$ is equal to the number of $n$-length paths in $\mathcal G(\tilde Y^{(1)}, ..., \tilde Y^{(t)})$ from the origin to the destination. Note that the edit graph has no cycles, so this quantity can be efficiently computed via the following dynamic program -- the number of $n$ length paths from the origin to a vertex $v$ is equal to the sum of the number of $n-1$ length paths from the origin to the in-neighbors of $v$. Such a procedure iterates over the vertex set of $\mathcal G(\tilde Y^{(1)}, ..., \tilde Y^{(t)})$ exactly once. The numerator term $\sum_{\substack{z||z|=n\\z_i=1}}\langle \tilde Y^{(1)}\uparrow \tilde Y^{(2)} \uparrow...\uparrow \tilde Y^{(t)},z \rangle$ can be interpreted in a similar way: it is equal to the number of $n$-length paths in $\mathcal G(\tilde Y^{(1)}, ..., \tilde Y^{(t)})$ from the origin to the destination such that the $i^{th}$ edge of the path corresponds to a `1'. The algorithm for this, therefore, follows a similar principle but has an extra step. For each vertex $v$, we compute \begin{itemize} \item the number of paths from the origin to $v$ of length $0,1,...,n$, \item the number of paths from $v$ to the destination of length $0,1,...,n$. \end{itemize} Next we iterate over all edges in $\mathcal G(\tilde Y^{(1)}, ..., \tilde Y^{(t)})$ corresponding to a `1' and accumulate the number of $n$ length paths which have this particular edge as its $i^{th}$ edge. Thus, this algorithm iterates over the vertex set twice and the edge set of $\mathcal G(\tilde Y^{(1)}, ..., \tilde Y^{(t)})$ once. \subsection{Proof of Lemma~\ref{lemma:bin_inf_relation}} \label{app:bin_inf_lemma} \bininfrelation* \begin{proof} We use induction to prove the statement. The statement is trivially true when $m=1$ since, $\sum_{w}{h \choose w}\langle f_1,w \rangle={h \choose f_1}$ as $\langle f,w \rangle=\mathbbm{1}_{f=w}$. We refer the reader to \cite{lothaire1997combinatorics} for a proof of the proposition for the case when $m=2$. Assume that the statement is true for $m=k \in \mathbb{Z}, k\geq 2$. We next prove the validity when $m=k+1$. \\ Consider \begin{align} {h \choose f_1} {h \choose f_2}...{h \choose f_k}{h \choose f_{k+1}}\nonumber\\=\sum_{w}{h \choose w}\langle f_1\uparrow f_2\uparrow ...\uparrow f_k,w \rangle {h \choose f_{k+1}}\nonumber\\ =\sum_{w}\left[{h \choose w} {h \choose f_{k+1}}\right]\langle f_1\uparrow f_2\uparrow ...\uparrow f_k,w \rangle\nonumber\\ =\sum_{w}\left[\sum_v \langle w\uparrow f_{k+1},v \rangle {h \choose v}\right]\langle f_1\uparrow f_2\uparrow ...\uparrow f_k,w \rangle\nonumber\\ =\sum_{v}{h \choose v}\left[\sum_w \langle w\uparrow f_{k+1},v \rangle \langle f_1\uparrow f_2\uparrow ...\uparrow f_k,w \rangle\right]. \label{eq:prop2proof} \end{align} To evaluate the term in the square bracket, we use \eqref{def:infiltforseq}. For the case where $\tau \in \mathcal{A}^*,\sigma \in \mathbb{Z}\langle \mathcal{A} \rangle$ in \eqref{def:infiltforseq}, we have $$\sigma\uparrow \tau=\sum_{f\in \mathcal{A}^*} \langle \sigma,f \rangle (f\uparrow \tau),$$ and thus \begin{equation} \langle \sigma \uparrow \tau,u \rangle=\sum_{f\in \mathcal{A}^*} \langle \sigma,f \rangle \langle f\uparrow \tau,u\rangle. \label{eq:prop2proof2} \end{equation} We use \eqref{eq:prop2proof2} to replace the term in the square bracket in \eqref{eq:prop2proof}, i.e., \begin{align} {h \choose f_1} {h \choose f_2}...{h \choose f_k}{h \choose f_{k+1}}\nonumber\\ =\sum_{v}{h \choose v}\langle (f_1\uparrow f_2\uparrow ...\uparrow f_k) \uparrow f_{k+1},v \rangle, \end{align} and the proposition follows from the associativity property of the infiltration product. \end{proof} \subsection{Proof of Lemma~\ref{lemma:smapsum}} \label{app:smapsum} \begin{restatable}{lemma}{smapsum} \label{lemma:smapsum} \begin{align*} \sum_{\substack{f||f|{=}n\\f_i{=}a}}{f \choose g} = 2^{n-|g|}\Bigg(\frac{1}{2}{n-1 \choose |g|} &+\sum_{j|g_j=a}{i-1 \choose j-1}{n-i \choose |g|-j}\Bigg), \end{align*} where $j\in\Big[\max\{1,|g|+i-n\}:\min\{i,|g|\}\Big]$. \end{restatable} \begin{proof} First, observe that $${f \choose g} = \sum_{\substack{S\subseteq [n]:\\|S|=|g|}} \mathbbm 1_{f_S=g},$$ where the summation is over all ordered subsets of $[n]=\{1,2,...,n\}$ of size $|g|$ and $f_S$ corresponds to the subsequence of $f$ indexed by $S$. Thus, \begin{align*} \sum_{\substack{f\in\mathcal{A}^n|\\f_i=a}}&{f \choose g} = \sum_{\substack{f\in\mathcal{A}^n|\\f_i=a}} \sum_{\substack{S\subseteq [n]|\\|S|=|g|}} \mathbbm 1_{f_S=g} = \sum_{\substack{S\subseteq [n]|\\|S|=|g|}} \sum_{\substack{f\in\mathcal{A}^n|\\f_i=a}} \mathbbm 1_{f_S=g}\\ &=\sum_{\substack{S\subseteq [n]|\\|S|=|g|\\i \notin S}} \sum_{\substack{f\in\mathcal{A}^n|\\f_i=a}} \mathbbm 1_{f_S=g} + \sum_{\substack{S\subseteq [n]|\\|S|=|g|\\i \in S}} \sum_{\substack{f\in\mathcal{A}^n|\\f_i=a}} \mathbbm 1_{f_S=g}\\ &=\sum_{\substack{S\subseteq [n]|\\|S|=|g|\\i \notin S}} \sum_{\substack{f\in\mathcal{A}^n|\\f_i=a}} \mathbbm 1_{f_S=g} + \sum_{j=1}^m \sum_{\substack{S\subseteq [n]|\\|S|=|g|\\S_j=i}} \sum_{\substack{f\in\mathcal{A}^n|\\f_i=a}} \mathbbm 1_{f_S=g}. \numberthis \label{eq:lemmasmapsum} \end{align*} \begin{figure}[!h] \begin{center} \includegraphics[scale=0.25]{lemma1.pdf} \vspace*{-2mm} \caption{Figure illustrating proof of Lemma~\ref{lemma:smapsum}.} \label{fig:lemmasmapsum} \end{center} \end{figure} The two terms in \eqref{eq:lemmasmapsum} can be visualized as the number of ways to fill up the blank spaces (spaces without arrows pointing to it in $f$) in Fig.~\ref{fig:lemmasmapsum}(a) and (b) respectively. Solving this counting problem is easy and we get, $$\sum_{\substack{f\in\mathcal{A}^n|\\f_i=a}}{f \choose g}=2^{n-|g|}\left(\frac{1}{2}{n-1 \choose |g|}+\sum_{j|g_j=a}{i-1 \choose j-1}{n-i \choose |g|-j}\right).$$ \end{proof} \section{Conclusions} \label{sec:conclusions} In this work we gave, to the best of our knowledge, the first results and techniques to compute posterior distributions over single and multiple deletion channels. We also provided a new perspective on the maximum-likelihood for the deletion channel by showing an equivalence between a discrete optimization problem and its relaxed version. In this process, we introduced a variety of tools (the relaxed binomial coefficient, edit graph and infiltration product) and demonstrated their use for analyzing deletion channels. We also presented numerical evaluations of our algorithms. \section{Introduction} \label{sec:intro} Sequence reconstruction over deletion channels, both with and without a codebook, has received considerable attention in the information theory as well as in the theoretical computer science literature. From an information theory perspective, reconstruction over the deletion channel, or more specifically a maximum-likelihood (ML) argument for the deletion channel, would give further insight on the capacity of the deletion channel, a long-standing open problem (see \cite{mitzenmacher2009survey}). To quote \cite{mitzenmacher2009survey} -- ``at the very least, progress in this direction would likely surpass previous results on the capacity of the deletion channels''. Yet, there are no results on reconstruction over a deletion channel with statistical guarantees -- in this work, we take a step in this direction. On the other hand, the problem of \textit{trace reconstruction}, as introduced in \cite{Batu2004}, has received renewed interest in the past few years (see \cite{Holenstein2008}, \cite{Peres2017}, \cite{De2017}, \cite{holden18}, \cite{Nazarov:2017}, \cite{holden2018lower}, \cite{chase2019new}). The problem of trace reconstruction can be stated simply as follows: consider a sequence $X$ which is simultaneously passed through $t$ independent deletion channels to yield $t$ deleted observations (also called \textit{traces}) of $X$ (see Fig.~\ref{fig:tdeletion}). How many such traces are needed to reconstruct $X$ perfectly? A variety of upper and lower bounds for this problem have been proposed, both for worst case and average case reconstruction. Our problem definition, stated in the following paragraph, is closely related to the average case trace reconstruction. \begin{figure}[!h] \begin{center} \includegraphics[scale=0.2]{tdeletion.pdf} \caption{$t$-deletion channel model: sequence $X$ passed through $t$ independent deletion channels to yield $t$ \textit{traces}. We aim to estimate $X$ from the $Y^{(i)}$s.} \label{fig:tdeletion} \end{center} \end{figure} \noindent \textbf{Problem definition.} Given an input sequence of length $n$ (known apriori), the independently and identically distributed (i.i.d.) deletion channel deletes each input symbol indepedently with probability $\delta$, producing at its output a subsequence of the input sequence. Consider a sequence $X$ passed through $t$ ($t$ is fixed) such deletion channels as shown in Fig.~\ref{fig:tdeletion}. We call this the $t$-deletion channel model. We ask two questions: \begin{enumerate} \item For $t=1$ (see Fig.~\ref{fig:1deletion}, also called the single deletion channel model), and when $X_i \sim\ \text{ind. Ber}(p_i)$, compute the posterior distributions of $X_i$ given the trace $Y$. \begin{figure}[!h] \begin{center} \includegraphics[scale=0.25]{1deletion.pdf} \caption{The single deletion channel model. We assume $X_i \sim\ \text{ind. Ber}(p_i)$.} \label{fig:1deletion} \end{center} \end{figure} \item In the $t$ deletion channel model, for a fixed $t$ assume that $X_i \sim\ \text{i.i.d. Ber}(0.5)$ and compute the posterior distributions of $X_i$ given all traces $Y^{(1)}, Y^{(2)},...,Y^{(t)}$. \end{enumerate} Note that solving 1) above doesn't lead to a natural solution for 2). This is because for a memoryless channel, we have $Y^{(j)} - X_i - Y^{(k)}$ and hence $\Pr(X_i=\alpha|Y^{(j)}, Y^{(k)}) \propto \Pr(X_i=\alpha|Y^{(j)}) \Pr(X_i=\alpha|Y^{(k)})$; so one could independently combine the posterior probabilities from each noisy observation. This is not the case for deletion channels since the markov chain $Y^{(j)} - X_i - Y^{(k)}$ no longer holds. More intuitively, one needs to first ``align'' the traces for computing the likelihoods. We point out that the problem considered in 2) asks a question complementary to the trace reconstruction: given a fixed (possibly a few) number of traces, what is our ``best'' guess of $X$? We provide algorithms which do this. Unlike trace reconstruction, we are not concerned with perfect reconstruction (since perfect reconstruction may not be possible with just a few traces), although it should also be obvious that performance guarantees for our algorithms (not a part of this work) would naturally lead to upper bounds for trace reconstruction. Deletion channel by itself is known to be notoriously difficult to analyse. As stated earlier, the capacity of a single deletion channel is still unknown (\cite{diggavi2007capacity,diggavi2006information,diggavi2001transmission}); as are optimal coding schemes. Recent works have looked at the design of codes for deletion channels (\cite{ratzer2005marker,ratzer2000codes,thomas2017polar}); these works consider use of a codebook (we do not). As a result, statistical estimation over deletion channels is also a difficult problem due its highly combinatorial nature. To the best of our knowledge, as yet there are no efficient estimation algorithms over deletion channels with statistical guarantees; not even for ML over a single deletion channel. \noindent \textbf{Biological motivation.} Trace reconstruction in itself was motivated, in part, by problems DNA sequence reconstruction. One such problem was to infer the DNA sequence of a common ancestor from the samples of its descendants. We argue that our problem definition fits more naturally in such a scenario since perfect reconstruction may not be feasible or even possible. Our motivation for considering this problem also comes from a recent DNA sequencing technology called \textit{nanopore sequencing}. The $t$-deletion channel model is a simplistic model to approximately capture the process of a DNA sequence passed through a nanopore sequencer\footnote{As seen in \cite{Mao2017},\cite{MDK17} there are more complicated effects of the nanopore reader not captured in this simple representation.}. Very recently, a variant of the trace reconstruction problem called \textit{coded trace reconstruction} has been proposed, motivated by portable DNA-based data storage systems using DNA nanopores (see \cite{abroshan2019coding}, \cite{cheraghchi2019coded}, \cite{brakensiek2019coded}) and we believe that the ideas in this work may prove useful in such a setting. There are other works on sequence assembly (see for example, \cite{Li09fastand}, \cite{Shomorony2016}), where multiple short reads (from different segments of a sequence) are used to reconstruct the bigger sequence. This work differs from sequence assembly since we are interested to infer the entire length sequence and not just small segments of it (which are then ``stitched'' together in sequence assembly). \noindent \textbf{Tools and techniques.} In terms of theoretical tools, the series of books by Lothaire (\cite{lothaire1997combinatorics,lothaire2002algebraic,lothaire2005applied}) extensively use algebraic tools for problems in the combinatorics of sequences (or \textit{words}), and our work is inspired by such techniques. We borrow many of their notations and results for our work. \noindent \textbf{Contributions.} {\color{red}} Our main contribution is to provide tools to visualize and analyze error events (described in the next section) for the multiple deletion channel model in Fig.~\ref{fig:tdeletion}. We also provide algorithms to solve the problems stated in 1) and 2) earlier in the section. \begin{itemize}[wide=5pt] \item In section~\ref{sec:1deletion}, for the single deletion channel model, we provide an $O(n^2)$ algorithm to calculate the symbolwise posterior probabilities $\Pr(X_i=1|Y)\ \forall\ i$ when $X_i \sim \text{ind. Ber}(p_i)$. \item In Section~\ref{sec:exactsmap}, for the $t$-deletion channel model, we give an $O(2^t n^{t+2})$ algorithm to calculate the symbolwise posterior probabilities $\Pr(X_i = 1|Y_1,...,Y_t)$ when $X_i \sim \text{ind. Ber}(0.5)$. \end{itemize} \section{Introduction} \label{sec:intro} Sequence reconstruction over deletion channels, both with and without a codebook, has received considerable attention in the information theory as well as in the theoretical computer science literature. From an information theory perspective, reconstruction over the deletion channel, or more specifically a maximum-likelihood (ML) argument for the deletion channel, would give further insight on the capacity of the deletion channel, a long-standing open problem (see \cite{mitzenmacher2009survey}). To quote \cite{mitzenmacher2009survey} -- ``at the very least, progress in this direction would likely surpass previous results on the capacity of the deletion channels''. Yet, there are no results on reconstruction over a deletion channel with statistical guarantees. In this work, we take steps in this direction. In this space, the problem of \textit{trace reconstruction}, as introduced in \cite{Batu2004}, has also received renewed interest in the past few years (see \cite{Holenstein2008,Peres2017}, \cite{De2017}, \cite{holden18}, \cite{Nazarov:2017}, \cite{holden2018lower}, \cite{chase2019new}). The problem of trace reconstruction can be stated simply as follows: consider a sequence $X$ which is simultaneously passed through $t$ independent deletion channels to yield $t$ output subsequences (also called \textit{traces}) of $X$ (see Fig.~\ref{fig:tdeletion}). How many such traces are needed to reconstruct $X$ perfectly? A variety of upper and lower bounds for this problem have been proposed, both for worst case and average case reconstruction. Our problem formulation is complementary to this, as we discuss next. \begin{figure}[!h] \begin{center} \includegraphics[scale=0.2]{tdeletion.pdf} \caption{The $t$-trace deletion channel model: the sequence $X$ is passed through $t$ independent deletion channels to yield $t$ \textit{traces}. We aim to estimate $X$ from the $Y^{(i)}$s.} \label{fig:tdeletion} \end{center} \end{figure} \noindent \textbf{Problem formulation.} Given an input sequence of length $n$ (known apriori), the independently and identically distributed (i.i.d.) deletion channel deletes each input symbol indepedently with probability $\delta$, producing at its output a subsequence of the input sequence. Consider a sequence $X$ passed through $t$ ($t$ is fixed) such deletion channels as shown in Fig.~\ref{fig:tdeletion}. We call this the $t$-trace deletion channel model. We ask three main questions: \begin{enumerate} \item For $t=1$ (also called \textit{single-trace deletion channel}, see Fig.~\ref{fig:1deletion}), what is the maximum-likelihood estimate of $X$ having observed $Y$, i.e., a solution to $\argmax\limits_{x\in \{0,1\}^n}\Pr(Y|X)$. \begin{figure}[!h] \begin{center} \includegraphics[scale=0.2]{1deletion.pdf} \caption{The single-trace deletion channel model.} \label{fig:1deletion} \end{center} \end{figure} \item For $t=1$ and $X_i \sim\ \text{ind. Ber}(p_i)$ in Fig.~\ref{fig:1deletion}, what are the posterior distributions of $X_i$ given the trace $Y$, i.e., compute $\Pr(X_i=\alpha|Y)$. \item For a fixed $t$, with $t>1$ and $X_i \sim\ \text{i.i.d. Ber}(0.5)$ in Fig.~\ref{fig:tdeletion}, what are the posterior distributions of $X_i$ given all traces $Y^{(1)}, Y^{(2)},...,Y^{(t)}$, i.e., compute $\Pr(X_i=\alpha|Y^{(1)}, Y^{(2)},...,Y^{(t)})$. \end{enumerate} We make two observations:\\ {\bf I.} An answer to 2) above doesn't lead to a natural solution for 3) since the deletion channel is not memoryless. In particular, for a memoryless channel, we have $Y^{(j)}_i - X_i - Y^{(k)}_i$ and hence $\Pr(X_i=\alpha|Y^{(j)}, Y^{(k)}) = \Pr(X_i=\alpha|Y^{(j)}_i, Y^{(k)}_i) \propto \Pr(X_i=\alpha|Y^{(j)}_i) \Pr(X_i=\alpha|Y^{(k)}_i)$; so one could first obtain the posterior probabilities from each independent observation and combine them after. However, this is not the case for deletion channels since the markov chain $Y^{(j)}_i - X_i - Y^{(k)}_i$ no longer holds. As a result, one first needs to ``align'' all the observations in order to compute the likelihoods. \\ {\bf II.} Solving 3) naturally leads to an algorithm for trace reconstruction, that selects the most likely value for each $X_i$. However, the problem formulation in 3) asks a question complementary to the trace reconstruction: given a fixed (possibly a few) number of traces, what is our ``best'' guess of $X$? Unlike trace reconstruction, we are not concerned with perfect reconstruction (since perfect reconstruction may not be possible with just a few traces). We also note that error rate guarantees for our algorithms (not a part of this work) would naturally lead to upper bounds for trace reconstruction.\\ \noindent \textbf{Contributions.} Our main contributions are as follows. \begin{itemize}[leftmargin=5mm] \item We introduce mathematical tools and constructs to visualize and analyze single-trace and $t$-trace deletion error events (see Section~\ref{sec:notation}). \item For the single-trace deletion channel, we establish an equivalence between finding the optimal ML decoder and a continuous optimization problem we introduce (see Section~\ref{sec:1deletion_ML}). \item In Section~\ref{sec:1deletion}, we prove the following: \begin{theorem} For the single-trace deletion channel model with priors $X_i \sim \text{ind. Ber}(p_i)$ and observed trace $Y$, the symbolwise posterior probabilities $\Pr(X_i=1|Y)\ \forall\ i$ can be computed in $O(n^2)$ time complexity. \end{theorem} \item In Section~\ref{sec:exactsmap}, we prove the following: \begin{theorem} For the $t$-trace deletion channel model with priors $X_i \sim \text{i.i.d. Ber}(0.5)$ and observed traces $Y^{(1)},...,Y^{(t)}$, the symbolwise posterior probabilities $\Pr(X_i = 1|Y^{(1)},...,Y^{(t)})\ \forall\ i$ can be computed in $O(2^t n^{t+2})$ time complexity.\\ \end{theorem} \end{itemize} \noindent \textbf{Tools and techniques.} In terms of theoretical tools, the series of books by Lothaire (\cite{lothaire1997combinatorics,lothaire2002algebraic,lothaire2005applied}) extensively use algebraic tools for problems in the combinatorics of sequences (or \textit{words}), and our work is inspired by such techniques. We borrow some notation and leverage a few of their results in our work. \\ \noindent \textbf{Biological motivation.} Trace reconstruction in itself was motivated, in part, by problems in DNA sequence reconstruction. One such problem was to infer the DNA sequence of a common ancestor from the samples of its descendants. Our problem definition, that considers a fixed value of $t$, would fit naturally in a scenario with a fixed number of descendants where perfect reconstruction may not be possible. Our motivation for considering this problem also comes from a recent DNA sequencing technology called \textit{nanopore sequencing}. The $t$-trace deletion channel model is a simplistic model to approximately capture the process of a DNA sequence passed through a nanopore sequencer\footnote{As seen in \cite{Mao2017},\cite{MDK17} there are more complicated effects of the nanopore reader not captured in this simple representation.}. \\ \noindent \textbf{More related work.} Our work falls under the general umbrella of sequence reconstruction over deletion channels, where we offer, to the best of our knowledge, the first non-trivial results on maximum likelihood and maximum aposteriori estimates for the single and multiple deletion channel. As mentioned earlier, the complementary problem of trace reconstruction falls closest to this work. The deletion channel by itself is known to be notoriously difficult to analyse. As stated earlier, the capacity of a single deletion channel is still unknown (\cite{diggavi2007capacity,diggavi2006information,diggavi2001transmission}); as are optimal coding schemes. Prior works have looked at the design of codes for deletion channels (\cite{ratzer2005marker,ratzer2000codes,thomas2017polar}); these works consider use of a codebook (we do not). Statistical estimation over deletion channels is a difficult problem to analyze due its highly combinatorial nature. To the best of our knowledge, as yet there are no efficient estimation algorithms over deletion channels with statistical guarantees. Very recently, a variant of the trace reconstruction problem called \textit{coded trace reconstruction} has been proposed, motivated by portable DNA-based data storage systems using DNA nanopores (see \cite{abroshan2019coding}, \cite{cheraghchi2019coded}, \cite{brakensiek2019coded}) and we believe that the ideas in this work may prove useful in such a setting. There are other works on sequence assembly (see for example, \cite{Li09fastand}, \cite{Shomorony2016}), where multiple short reads (from different segments of a sequence) are used to reconstruct the bigger sequence. This work differs from sequence assembly since we are interested in inferring the entire length sequence and not just small segments of it (which are then ``stitched'' together in sequence assembly).\\ \noindent \textbf{Paper Organization.} Section~\ref{sec:notation} introduces our notation and visualization tools for the single and $t$-trace channel error events; Section~\ref{sec:1deletion_ML} provides a result concerning question 1) wherein we prove the equivalence of ML decoding to solving a continuous optimization problem; Section~\ref{sec:1deletion} answers question 2) for the single-trace channel; Section~\ref{sec:exactsmap}) answers question 3) for the $t$-deletion channel; Section~\ref{sec:Numerics} gives numerical evaluations; and Section~\ref{sec:conclusions} concludes the paper. \section{Symbolwise posterior probabilities for the $t$-trace deletion channel} \label{sec:exactsmap} In this section, we put to use the ideas and constructs introduced in section~\ref{sec:notation} to exactly compute the symbolwise posterior probabilities given $t$-traces, which in turn gives a symbolwise MAP estimate (with uniform priors) of the input sequence. In Appendix~\ref{app:remnant_postprob}, we also provide a method to compute the symbolwise posterior probabilities for the remnant channel -- we encourage the reader to use this appendix as a warm-up. For the $t$-trace deletion channel, similar expressions arise due to the channel equivalence result of Theorem~\ref{thm:channel_equiv}. Let $\mathcal A = \{0,1\}$, and assume that $X\sim $ Uniform $\mathcal A^n$. Our goal is to compute the symbolwise posterior probabilities $\Pr(X_i{=}1|Y^{(1)},...,Y^{(t)})$, where $Y^{(j)}$ is the $j^{th}$ trace. Our proposed algorithm is provided in Alg.~\ref{alg:exact_smap} and estimates the symbolwise MAP (with uniform priors). We can directly leverage Alg.~\ref{alg:exact_smap} to reconstruct the input as follows: for each index $i$, compute $\Pr(X_i{=}1|Y^{(1)},...,Y^{(t)})$ and decide \begin{align*} \hat{X}_i = \begin{cases} 1,\quad &$if$\ \Pr(X_i{=}1|Y^{(1)},...,Y^{(t)})\geq 0.5 \\ 0, \quad &$otherwise$. \end{cases} \end{align*} Through the rest of this section, we show how to compute $\Pr(X_i{=}1|Y^{(1)},...,Y^{(t)})$\footnote{Symbolwise MAP with non-uniform priors is part of on-going work.} in two steps: \begin{itemize} \item We first give an expression for $\Pr(X_i{=}1|Y^{(1)},...,Y^{(t)})$ which sums over potentially an exponential number of terms. \item We then show that this summation can be computed in polynomial time (polynomial in the blocklength $n$). \end{itemize} \noindent \textbf{Step 1: An expression for $\Pr(X_i{=}1|Y^{(1)},...,Y^{(t)})$.} \begin{theorem} \label{thm:exactSMAP_posteriorprob} Assume $X\sim $ Uniform $\mathcal A^n$ or equivalently $X_i \sim\ \text{Ber}(0.5)$. The posterior probability of the $i^{th}$ bit given the $t$ traces can be expressed as \begin{align*} \Pr(X_i=1|Y^{(1)},&...,Y^{(t)}) &\\ = & \Bigg[ \sum_{k=0}^n 2^{n-k-1}{n-1 \choose k} \sum_{w||w|=k} \langle Y^{(1)} \uparrow ... \uparrow Y^{(t)},w \rangle \\ &+ \sum_{k=0}^n \sum_{j=1}^k 2^{n-k}{i-1 \choose j-1}{n-i \choose k-j} \sum_{\substack{w| |w|=k,\\w_j=1}} \langle Y^{(1)} \uparrow ... \uparrow Y^{(t)},w \rangle \Bigg] \Big/ \\ &\Bigg[ \sum_{k=0}^n 2^{n-k} {n \choose k} \sum_{\substack{w| |w|=k}} \langle Y^{(1)} \uparrow ... \uparrow Y^{(t)},w \rangle \Bigg]. \numberthis \label{eq:posterior_prob} \end{align*} \end{theorem} Note that the summation index, $w| |w|{=}k$ is over all sequences $w$ of length $k$; this is an alternate expression for $w|w{\in}\mathcal A^k$. We follow this convention throughout the rest of the paper. \begin{proof} \begin{align*} \Pr(X_i=1&|Y^{(1)},...,Y^{(t)}) = \sum_{\substack{x||x|=n,\\x_i=1}} \Pr(x|Y^{(1)},...,Y^{(t)})\\ &\overset{(a)}{=} \frac{1}{2^n \Pr(Y^{(1)},...,Y^{(t)})} \sum_{\substack{x||x|=n,\\x_i=1}} \Pr(Y^{(1)},...,Y^{(t)}|x)\\ &\overset{(b)}{=} \frac{1}{2^n \Pr(Y^{(1)},...,Y^{(t)})} \sum_{\substack{x||x|=n,\\x_i=1}} \prod_{j=1}^t\Pr(Y^{(j)}|x), \end{align*} where $(a)$ uses Bayes' principle and $(b)$ is because each deletion channel acts independently. Recall that for a deletion channel with deletion probability $\delta$, $\Pr(Y|X=x)={x \choose Y}\delta^{|x|-|Y|}(1-\delta)^{|Y|}$. Also, using the fact that $\Pr(Y^{(1)},...,Y^{(t)})=\sum\limits_{\substack{x||x|=n}}\Pr(x) \Pr(Y^{(1)},...,Y^{(t)}|x)$ we have, \begin{align*} \Pr(X_i=1|Y^{(1)},...,Y^{(t)})= \frac{\sum\limits_{\substack{x||x|=n,\\x_i=1}} {x \choose Y^{(1)}}...{x \choose Y^{(t)}}}{\sum\limits_{\substack{x||x|=n}} {x \choose Y^{(1)}}...{x \choose Y^{(t)}}}. \numberthis \label{eq:thmexactsmap_proofterm0} \end{align*} We first simplify the numerator $\sum\limits_{\substack{x||x|=n,\\x_i=1}} {x \choose Y^{(1)}}...{x \choose Y^{(t)}}$; the denominator can be simplified using the same approach. Now, \begin{align*} \sum\limits_{\substack{x||x|=n,\\x_i=1}} {x \choose Y^{(1)}}...{x \choose Y^{(t)}} &\overset{(a)}{=} \sum_{\substack{x||x|=n,\\x_i=1}} \sum_{w\in \{0,1\}^*} {x \choose w} \langle Y^{(1)} \uparrow Y^{(2)} \uparrow ... \uparrow Y^{(t)},w \rangle \\ &=\sum_{w\in \mathcal A^*} \langle Y^{(1)} \uparrow Y^{(2)} \uparrow ... \uparrow Y^{(t)},w \rangle \sum_{\substack{x||x|=n,\\x_i=1}}{x \choose w}\\ &\overset{(b)}{=}\sum_{w\in \mathcal A^*} \langle Y^{(1)} \uparrow Y^{(2)} \uparrow ... \uparrow Y^{(t)},w \rangle \\ & \hspace{2cm} \times 2^{n-|w|}\left(\frac{1}{2}{n-1 \choose |w|}+\sum_{j|w_j=1}{i-1 \choose j-1}{n-i \choose |w|-j}\right) \end{align*} where $(a)$ is due to Lemma~\ref{lemma:bin_inf_relation} and $(b)$ due to Lemma~\ref{lemma:smapsum} (both introduced in \cite{Srini2018}); see Appendix~\ref{app:bin_inf_lemma} and Appendix~\ref{app:smapsum} for the statement and proof. Note that Lemma~\ref{lemma:bin_inf_relation} is an alternate mathematical outlook of the channel equivalence in Theorem~\ref{thm:channel_equiv} (see Appendix~\ref{app:channel_equiv}). \noindent Therefore we have, \begin{align*} \sum\limits_{\substack{x||x|=n,\\x_i=1}} {x \choose Y^{(1)}}...{x \choose Y^{(t)}} &\overset{(a)}{=} \sum_{k=0}^{\infty} 2^{n-k-1}{n-1 \choose k} \sum_{w| |w|=k} \langle Y^{(1)} \uparrow ... \uparrow Y^{(t)},w \rangle \\ &\hspace{1cm}+ \sum_{k=0}^{\infty} \sum_{j=1}^k 2^{n-k}{i-1 \choose j-1}{n-i \choose k-j} \sum_{\substack{w| |w|=k,\\w_j=1}} \langle Y^{(1)} \uparrow ... \uparrow Y^{(t)},w \rangle \\ &\overset{(b)}{=} \sum_{k=0}^n 2^{n-k-1}{n-1 \choose k} \sum_{w| |w|=k} \langle Y^{(1)} \uparrow ... \uparrow Y^{(t)},w \rangle \\ &\hspace{1cm}+ \sum_{k=0}^n \sum_{j=1}^k 2^{n-k}{i-1 \choose j-1}{n-i \choose k-j} \sum_{\substack{w| |w|=k,\\w_j=1}} \langle Y^{(1)} \uparrow ... \uparrow Y^{(t)},w \rangle, \numberthis \label{eq:thmexactsmap_proofterm1} \end{align*} where in $(a)$ we first fix $|w|$ and then sum over all $w$ of the given length and $(b)$ holds because the combinatorial terms are $0$ when $k>n$. A similar analysis gives \begin{align*} \sum\limits_{x| |x|=n} &{x \choose Y^{(1)}}...{x \choose Y^{(t)}} = \sum_{k=0}^n 2^{n-k} {n \choose k} \sum_{\substack{w| |w|=k}} \langle Y^{(1)} \uparrow ... \uparrow Y^{(t)},w \rangle.\numberthis \label{eq:thmexactsmap_proofterm2} \end{align*} Plugging \eqref{eq:thmexactsmap_proofterm1} and \eqref{eq:thmexactsmap_proofterm2} in \eqref{eq:thmexactsmap_proofterm0}, we get the expression in Theorem~\ref{thm:exactSMAP_posteriorprob}, \begin{align*} \Pr(X_i=1|Y^{(1)},&...,Y^{(t)}) &\\ = & \Bigg[ \sum_{k=0}^n 2^{n-k-1}{n-1 \choose k} \sum_{w||w|=k} \langle Y^{(1)} \uparrow ... \uparrow Y^{(t)},w \rangle \\ &+ \sum_{k=0}^n \sum_{j=1}^k 2^{n-k}{i-1 \choose j-1}{n-i \choose k-j} \sum_{\substack{w| |w|=k,\\w_j=1}} \langle Y^{(1)} \uparrow ... \uparrow Y^{(t)},w \rangle \Bigg] \Big/ \\ &\Bigg[ \sum_{k=0}^n 2^{n-k} {n \choose k} \sum_{\substack{w| |w|=k}} \langle Y^{(1)} \uparrow ... \uparrow Y^{(t)},w \rangle \Bigg]. \end{align*} \end{proof} \noindent \textbf{Step 2: Dynamic program to compute $\sum\limits_{w| |w|=k} \langle Y^{(1)} \uparrow ... \uparrow Y^{(t)},w \rangle$ and $\sum\limits_{\substack{w| |w|=k,\\w_j=1}} \langle Y^{(1)} \uparrow ... \uparrow Y^{(t)},w \rangle$.} Note that the number of sequences $w| |w|=k$ is $O(2^k)$ so a naive evaluation is exponential in the blocklength $n$. We can, however, exploit the edit graph to come up with a dynamic program resulting in an algorithm which is polynomial in $n$. Recall that in the edit graph, $\langle Y^{(1)} \uparrow ... \uparrow Y^{(t)},w \rangle$ is equal to the number of distinct paths from the origin $(0,...,0)$ to the destination $(|Y^{(1)}|,...,|Y^{(t)}|)$ and which correspond to $w$. Hence, \begin{enumerate}[wide=0pt] \item[(a)] $\sum\limits_{w| |w|=k} \langle Y^{(1)} \uparrow ... \uparrow Y^{(t)},w \rangle$ is the number of distinct paths of length $k$ from origin to destination and, \item[(b)] $\sum\limits_{\substack{w| |w|=k,\\w_j=1}} \langle Y^{(1)} \uparrow ... \uparrow Y^{(t)},w \rangle$ is the number of such paths of length $k$ such that the $j^{th}$ edge of the path corresponds to a `1'. \end{enumerate} \noindent With this interpretation, the dynamic program for (a) follows naturally -- the number of $k$-length paths from the origin to any vertex is the sum of the number of $(k{-}1)$-length paths from the origin to all incoming neighbors of the vertex. To make this formal, associate a polynomial (in $\lambda$) for each vertex, such that the coefficient of $\lambda^k$ is equal to the number of paths of length $k$ from the origin to $v$: we call it the "forward-potential" polynomial $p^{for}_v(\lambda)$ for vertex $v$, the coefficient of $\lambda^k$ as earlier is denoted by $\langle p^{for}_v(\lambda),\lambda^k \rangle $. The dynamic program to compute $p^{for}_v(\lambda)$ for all $v$ can be expressed as: \begin{equation} p^{for}_v(\lambda) = \sum_{u|u\rightarrow v} \lambda p^{for}_u(\lambda). \end{equation} With this definition, we have $$\sum\limits_{w| |w|=k} \langle Y^{(1)} \uparrow ... \uparrow Y^{(t)},w \rangle =\langle p^{for}_{destination}(\lambda),\lambda^k \rangle.$$ In the example in Fig.~\ref{fig:editgraph_smap1}, one could do the following: order the vertices $(0,0)$ to $(3,3)$ lexicographically and then compute $p^{for}_v(\lambda)$ in the same order. Because of the directed grid nature of the edit graph, every vertex has incoming neighbors which are lexicographically ahead of itself. Also we initialize $p^{for}_{(0,0)}(\lambda)=1$. For the example in Fig.~\ref{fig:editgraph_smap1}, the forward-potentials are shown in Fig.~\ref{fig:editgraph_smap2}. The complexity of this dynamic program is $O(2^tn^{t+1})$ as it goes over $O(n^t)$ vertices and for each vertex it sums $O(2^t)$ polynomials, each of degree $O(n)$. \begin{figure}[!h] \centering \includegraphics[scale=0.25]{editgraph_smap2.pdf} \caption{The forward-potential $p^{for}_v(\lambda)$ at each vertex.} \label{fig:editgraph_smap2} \end{figure} We compute (b) as follows: pick an edge $(u{\rightarrow}v)$ which corresponds to `1', count the number of $(j{-}1)$-length paths from origin to $u$ and multiply it with the number of $(k{-}j)$-length paths from $v$ to the destination -- this is exactly the number of paths of length $k$ such that its $j^{th}$ edge is $(u{\rightarrow}v)$. Summing this term for all such edges which correspond to 1 gives us the term in (b). Note that we have already computed the number of $k$-length paths ($\forall k$) from origin to every vertex in $p^{for}_v(\lambda)$ . We can similarly compute the number of $k$-length paths ($\forall k$) from every vertex to the destination as $p^{rev}_v(\lambda)$ -- the "reverse potential" polynomial. The dynamic program for $p^{rev}_v(\lambda)$ is: \begin{equation} p^{rev}_v(\lambda) = \sum_{u|v\rightarrow u} \lambda p^{rev}_u(\lambda), \end{equation} with $p^{rev}_{destination}(\lambda)=1$. The reverse potentials for the example in Fig.~\ref{fig:editgraph_smap1} is shown in Fig.~\ref{fig:editgraph_smap3}. Like in the case of forward potential, we first order the vertices reverse lexicographically and then invoke the dynamic program above sequentially to compute the reverse potential polynomial at each vertex. \begin{algorithm}[t!] \caption{Computing the forward-potentials $p^{for}_u(\lambda)$ }\label{alg:forward_pot} \begin{algorithmic}[1] \item Input: Edit graph {$\mathcal G(Y^{(1)},...,Y^{(t)})$}\\ Outputs: $p^{for}_v(\lambda)\ \forall\ v$ \State Order the vertices from $(0,0,...,0)$ to $(|Y^{(1)}|,|Y^{(2)}|,...,|Y^{(t)}|)$ lexicogaphically; let the ordered list be $\mathcal V$ \State Initialise $p^{for}_{(0,...,0)}(\lambda)\gets 1$ \For{$v\ \in\ \mathcal V$} \State \textbf{assign} $p^{for}_v(\lambda)\gets \sum_{u|u\rightarrow v} \lambda p^{for}_u(\lambda)$ \EndFor \end{algorithmic} \end{algorithm} \begin{algorithm}[t!] \caption{Computing the reverse-potentials $p^{rev}_u(\lambda)$ }\label{alg:reverse_pot} \begin{algorithmic}[1] \item Input: Edit graph {$\mathcal G(Y^{(1)},...,Y^{(t)})$}\\ Outputs: $p^{rev}_v(\lambda)\ \forall\ v$ \State Order the vertices from $(|Y^{(1)}|,|Y^{(2)}|,...,|Y^{(t)}|)$ to $(0,0,...,0)$ reverse lexicogaphically; let the ordered list be $\mathcal V$ \State Initialise $p^{rev}_{(|Y^{(1)}|,|Y^{(2)}|,...,|Y^{(t)}|)}(\lambda)\gets 1$ \For{$v\ \in\ \mathcal V$} \State \textbf{assign} $p^{rev}_v(\lambda) \gets \sum_{u|v\rightarrow u} \lambda p^{rev}_u(\lambda)$ \EndFor \end{algorithmic} \end{algorithm} \begin{figure}[!h] \centering \includegraphics[scale=0.25]{editgraph_smap3.pdf} \caption{The reverse-potential $p^{rev}_v(\lambda)$ at each vertex.} \label{fig:editgraph_smap3} \end{figure} With this, the term in (b) can be expressed as: \begin{align*} \sum\limits_{\substack{w| |w|=k,\\w_j=1}} \langle Y^{(1)} \uparrow ... \uparrow Y^{(t)},w \rangle =\hspace{-2mm} \sum_{\substack{(u,v)|\\s(u\rightarrow v)=1}} \hspace{-2mm}\langle p^{for}_u(\lambda),\lambda^{j-1} \rangle \langle p^{rev}_v(\lambda),\lambda^{k-j} \rangle. \end{align*} Alg.~\ref{alg:exact_smap} now summarizes the computation of the posterior probabilities. This algorithm iterates over all the edges (we have $O((2n)^t)$ of these), and also $k,j$ ($O(n)$ each). The time complexity of Alg.~\ref{alg:exact_smap} hence is $O(2^tn^{t+2})$. \begin{algorithm}[t!] \caption{Symbolwise posterior probabilities with $t$ traces} \label{alg:exact_smap} \begin{algorithmic}[1] \item Input: Traces {$Y^{(1)},Y^{(2)},...,Y^{(t)}$, input length $n$}\\ Output: $\Pr(X_i=1|Y^{(1)},Y^{(2)},...,Y^{(t)})\ \forall\ i \State Construct edit graph $\mathcal G(Y^{(1)},...,Y^{(t)})$ \State Use Alg.~\ref{alg:forward_pot} and Alg.~\ref{alg:reverse_pot} on $\mathcal G(Y^{(1)},...,Y^{(t)})$ to calculate $p^{for}_v(\lambda)$ and $p^{rev}_v(\lambda)$ $\forall\ v$ \For{$k \in\ [0:n]$} \State \textbf{assign} $\sum\limits_{w| |w|=k} \langle Y^{(1)} \uparrow ... \uparrow Y^{(t)},w \rangle \gets \langle p^{for}_{destination}(\lambda),\lambda^k \rangle.$ \For{each $j \in\ [1:n]$} \State Initialize $temp \leftarrow $ 0 \For{each edge $u\rightarrow v\ \in\ \mathcal G$} \If{$s(u{\rightarrow} v)=$ `1'} \State $temp\ += \langle p^{for}_u(\lambda),\lambda^{j-1} \rangle \langle p^{rev}_v(\lambda),\lambda^{k-j} \rangle$ \EndIf \EndFor \State \textbf{assign} $\sum\limits_{\substack{w| |w|=k,\\w_j=1}} \langle Y^{(1)} \uparrow ... \uparrow Y^{(t)},w \rangle \gets temp$ \EndFor \EndFor \For{$i \in\ [1:n]$} \State Use \eqref{eq:posterior_prob} to compute $\Pr(X_i=1|Y^{(1)},Y^{(2)},...,Y^{(t)})$ \EndFor \end{algorithmic} \end{algorithm} \section{Notation and Tools} \label{sec:notations} \noindent \textbf{Basic notations:} In this work, we borrow a majority of the notation and tools from \cite{lothaire1997combinatorics} which deals with non-commutative algebra. We restate the definitions here for convenience. Calligraphic letters refer to sets, capitalized letters correspond to random variables and bold letters are used for functions. Let $\mathcal{A}$ be the set of all symbols. Throughout this work, we will focus on the case where $\mathcal{A}=\{0,1\}$, though our methods extend to arbitrarily large sets of finite size. Define $\mathcal{A}^n$ to be the set of all $n$-length sequences and $\mathcal{A}^*$ to be the set of all finite length sequences with symbols in $\mathcal{A}$. For a sequence $f$, $|f|$ denotes the length of $f$. For integers $i,j$, we define $[i:j] \triangleq \{i,i+1,...,j\}$ if $j\geq i$ and $[i:j] \triangleq \emptyset$ otherwise. Also define $[i] \triangleq [1:i]$.\\ \noindent \textbf{Binomial coefficient:} Given sequences $f$ and $g$ in $\mathcal{A}^*$, the number of subsequence patterns of $f$ that are equal to $g$ is called the \textit{binomial coefficient} of $g$ in $f$ and is denoted by $f \choose g$. For example, ${'apple' \choose 'ape'} = 2$ since $'ape'$ can be obtained from two (overlapping) subsequences of $'apple'$. When the alphabet $\mathcal{A}$ is of cardinality 1, ${f \choose g} = {|f| \choose |g|}$, the classical binomial coefficient with their respective lengths as the parameters. This definition hence could be thought of as a generalization of the classical binomial coefficients. We will denote by $e$ the sequence of length 0, and {define ${f \choose e} \triangleq 1\ \forall\ f\ \in\ \mathcal{A}^*$.} We also define the classical binomial coefficient ${a \choose b}\triangleq 0,$ whenever $b>a$ or $b<0$ for ease of use. The binomial coefficient is an integral aspect of this work and for analyzing error events in deletion channels because the input-output relation for a deletion channel (with deletion probability $\delta$, input $X$ and output $Y$) can be expressed as \begin{equation} \label{eq:in-out_relation} \Pr(Y=y|X=x) = {x \choose y} \delta^{|x|-|y|} (1-\delta)^{|y|}. \end{equation} The proof is straight-forward -- the number of distinct error events that give rise to $y$ from $x$ is exactly the number of subsequences of $x$ which are equal to $y$. Each of these error events has a probability $\delta^{|x|-|y|} (1-\delta)^{|y|}$, wherein the exponent of $\delta$ corresponds to the deleted symbols and the exponent of $1-\delta$ to the undeleted symbols. Given the definition of the binomial coefficient, the maximum-likelihood (ML) estimate over a deletion channel with observed output $Y$ can be cast in the following form: \begin{align*} \argmax_{x \in \mathcal C} {x \choose Y},\numberthis \label{eq:ML_deletion} \end{align*} where $\mathcal C$ is the chosen codebook. In the case of multiple deletion channels with observed traces $Y^{(1)},...,Y^{(t)}$, the ML formulation is similar: \begin{align*} \argmax_{x \in \mathcal C} \prod_{j=1}^{t} {x \choose Y^{(j)}}.\numberthis \label{eq:ML_multiple_deletion} \end{align*} As yet, there is no known efficient way to come up with a solution for the above two formulations, even for \eqref{eq:ML_deletion} with $\mathcal C = \{0,1\}^n$ (see \cite{mitzenmacher2009survey}). In this work, we attempt to take a step in this direction by showing that a continuous relaxation of \eqref{eq:ML_deletion} is equivalent to \eqref{eq:ML_deletion}. However, an efficient algorithm to solve the optimization \eqref{eq:ML_deletion} remains open. In the context of trace reconstruction, the ultimate pursuit would be an algorithm for \eqref{eq:ML_multiple_deletion} with $\mathcal C = \{0,1\}^n$ and error analysis thereof. \noindent We now describe a function which can be thought of as a real-valued extension of the binomial coefficient. This function is used in sections~\ref{sec:1deletion_ML} and \ref{sec:1deletion}. Consider the function $\mathbf F(\cdot)$ defined as: \begin{definition} \label{def:f} \begin{align*} &\mathbf F: \mathbb{R}^k \times \{0,1\}^l \rightarrow \mathbb{R},\\ \mathbf F(q, v)\triangleq &\begin{cases} \sum\limits_{\substack{\mathcal S|\mathcal S\subseteq [k],\\|\mathcal S|=l}} \quad \prod\limits_{i=1}^l q_{\mathcal S_i}^{v_i} (1-q_{\mathcal S_i})^{1-v_i} & 1 \leq l\leq k \\ 1 & 0=l\leq k \\ 0 & \text{else}. \end{cases} \end{align*} \noindent An alternate definition is as follows: consider a random vector $Z\in\{0,1\}^k$ such that $Z_i\sim$ ind. Ber$(q_i)$, let $q$ be the vector of probabilities of length $k$, $\mathcal S\subseteq [k]$ a subset of the indices of size $l$, and ${v}$ a binary vector of length $l$. Then, $$\mathbf F(q,v)=\sum_{\substack{\mathcal S||\mathcal S|=l}} \Pr(Z_{\mathcal S}= v).$$ Note that if $q$ is a vector of $0$'s and $1$'s, then $\mathbf F( q, v)={q \choose v}$, the binomial coefficient of $v$ in $q$. Thus, $\mathbf F(\cdot)$ could be interpreted as an extension of the binomial coefficient where one of the parameters can take values in $[0,1]^n$ instead of $\{0,1\}^n$. \end{definition} Though at first sight, $\mathbf F(q,v)$ sums over an exponential number of subsets, a dynamic programming approach can be used to compute it in $O(|v|^2)$ time complexity. The dynamic program is described in section~\ref{sec:1deletion}. \iffalse \noindent \textbf{Edit distance:} The edit distance $d_e(f,g)$ measures similarity between two sequences of possibly different lengths \cite{Navarro2001}. $d_e(f,g)$ is the minimum number of operations needed to transform $f$ to $g$, where the permitted operations are insertion, deletion or substitution of a symbol. In this work, we quantify the performance of algorithms in Section \ref{sec:Numerics} using the edit distance metric. \fi The following definitions and ideas are relevant only for \ref{sec:exactsmap} and can be omitted for the sections on single deletion channel. Before getting to the mathematical definitions, we first state a result of ours that aids in thinking about error events in multiple deletion channels. \subsection{An alternate interpretation of multiple deletion channel model} The events occurring in the $t$-deletion channel model can be categorized into two groups: \begin{enumerate} \item an input symbol is deleted in \textit{all} the $t$-traces, \item an input symbol is reflected in at least one of the traces. \end{enumerate} The error events of the first kind are in some sense ``not correctable" or even ``detectable" since it is impossible to tell what and where the deleted symbol could have been (although the probabilities need not be uniform). The events of the second kind, however, can still be detected although they could likely be confused with a large set of similar events. This thought process gives rise to a natural decomposition of the $t$-deletion channel model into a cascade of two channels: the first one being a deletion channel which captures error events of the first kind and the second one is what we call the \textit{remnant channel} which captures events of the second kind (see Fig.~\ref{fig:channel_equiv}). More precisely, the remnant channel is defined as follows: \begin{definition} \textit{Remnant channel:} an input symbol to the remnant channel is reflected in $k>0$ given outputs and deleted in the rest with a probability $\frac{\delta^{t-k}(1-\delta)^k}{1-\delta^t}$. \end{definition} It is easy to note that probability of the union of all possible events here is $\sum_{k=1}^t {t \choose k} \frac{\delta^{t-k}(1-\delta)^k}{1-\delta^t}=1$, validating our definition. \begin{restatable}{theorem}{channelequiv} \label{thm:channel_equiv} The $t$-deletion channel model and the cascade of the deletion channel with remnant channel shown in Fig.~\ref{fig:channel_equiv} are probabilistically equivalent, i.e., $$\Pr({Y}^{(1)},{Y}^{(2)},...,{Y}^{(t)}|X = x) = \Pr(\tilde{Y}^{(1)},\tilde{Y}^{(2)},...,\tilde{Y}^{(t)}|X = x).$$ \end{restatable} The formal proof of the theorem requires few more definitions and is relegated to the appendix. \begin{figure}[!h] \begin{center} \includegraphics[scale=0.4]{channel_equiv.pdf} \caption{A channel equivalence result: the $t$-deletion channel model in (a) is probabilistically equivalent to the the cascade of a deletion channel with the \textit{remnant channel} ($ \mathcal C_2$) in (b).} \label{fig:channel_equiv} \end{center} \end{figure} \noindent\textbf{Edit graph} (as defined in \cite{Gusfield1997}): We now define a graph construct which is closely related to the error events in the remnant channel. We start with a simple case and generalize subsequently. Define an \textit{edit graph} given two sequences $f$ and $g$, where every path connecting the ``origin'' to the ``destination'' on the edit graph yields a supersequence $h$ of $f,g$, where $h$ is ``covered'' by $f,g$ -- i.e., each symbol of $h$ comes from either $f$ or $g$ or both. In other words, given that $f$ and $g$ are the outputs of the remnant channel (with two outputs), each path from the origin of the edit graph to the destination corresponds to a possible input $h$ to the remnant channel and to an error event which resulted in $f$ and $g$ with input $h$. For $f$ and $g$ in $\mathcal A^*$, we form a graph $\mathcal{G}(f,g)$ with $(|f|+1)(|g|+1)$ vertices each labelled with a distinct pair $(i,j), 0\leq i\leq |f|,\ 0\leq j\leq |g|$. A directed edge $(i_1,j_1)\rightarrow(i_2,j_2)$ exists iff at least one of the following holds: \begin{enumerate} \item$i_2-i_1=1$ and $j_1=j_2$, or \item $j_2-j_1=1$ and $i_1=i_2$, or \item $i_2-i_1=1$, $j_2-j_1=1$ and $f_{i_2}=g_{j_2}$, \end{enumerate} where $f_i$ is the $i^{th}$ symbol of the sequence $f$. The origin is the vertex $(0,0)$ and the destination $(|f|,|g|)$. \begin{figure}[!h] \centering \includegraphics[scale=0.25]{editgraph_smap1.pdf} \caption{ Edit graph for sequences $f=$ `001' and $g=$ `101'. An easy way to think about this is to write down $f$ vertically with each symbol aligned to a vertical set of edges and $g$ horizontally likewise. A diagonal edge in a small square exists if the corresponding $f$ and $g$ symbols are equal. The thick red edges form a path from the origin to the destination; this path corresponds to the sequence `0101' -- append the corresponding symbol at the left of an edge if it's vertical or diagonal, otherwise append the symbol at the top. It is also easy to verify that 0101 is a supersequence of both $f$ and $g$, and could be obtained as a covering of $f$ and $g$; the path itself gives one such covering. This covering also corresponds to an error event in the remnant channel which would result in outputs $f$ and $g$ with input $h=$ `0101' -- more precisely, the error event is one in which the first symbol of $h$ is deleted only in $g$, the second symbol is deleted only in $f$ and the third and fourth symbols not deleted in either $f$ or $g$.} \label{fig:editgraph_smap1} \end{figure} Let $p=((i_1,j_1),(i_2,j_2),...,(i_m,j_m))$ be a path in $\mathcal{G}(f,g)$. We define $ s(p)$ to be the sequence corresponding to the path. Intuitively, $s(p)$ is formed by appending symbols in the following way: append the corresponding $f$ symbol for a vertical edge, $g$ symbol for horizontal edge, and $f$ or $g$ symbol for diagonal edge (see example Fig.~\ref{fig:editgraph_smap1}). Any path from $(0,0)$ to $(|f|,|g|)$ corresponds to a supersequence of $f$ and $g$ and which is ``covered" by $f$ and $g$. More formally, define $ s(p)\triangleq x_1x_2...x_{m-1}$ where $$x_k = \begin{cases} f_{i_{k+1}} \quad\text{if }j_{k}=j_{k+1},\\ g_{j_{k+1}} \quad\text{if }i_{k}=i_{k+1},\\ f_{i_{k+1}} \quad\text{else.} \end{cases} $$ The construct of edit graph can be extended to more than 2 sequences with the same idea. For sequences $f_1,f_2,...,f_t$, construct a $t$-dimensional grid with a number of vertices $(|f_1|+1)(|f_2|+1)...(|f_t|+1)$ labeled from $(0,0,...,0)$ to $(|f_1|,|f_2|,...,|f_t|)$. A vertex $u=(i_1,i_2,...,i_t)$ is connected to $v=(j_1,j_2,...,j_t)$ (we say $u \rightarrow v$) iff both of the following conditions are met: \begin{itemize} \item $j_l=i_l$ or $j_l=i_l+1$ $\forall\ l\in [t]$, i.e., $(i_1,...,i_t)$ and $(j_1,...,j_t)$ are vertices of a particular unit cube. Only these type of vertices can share an edge in the grid graph. \item Let $\mathcal T \subseteq [t]$ be the collection of indices where $j_l=i_l+1$. Then $f_{i_l}$ is same $\forall\ l \in \mathcal T$. For instance, if $\mathcal T=\{1,3,5\}$, then $f_{i_1}=f_{i_3}=f_{i_5}$. \end{itemize} Define the vertex $(0,...,0)$ to be the origin of this graph and the vertex $(|f_1|,...,|f_t|)$ to be the destination. If $|f_j|=O(n)\ \forall\ j$, this graph has a number of vertices $O(n^t)$ and a maximum number of edges $O((2n)^t)$ since each vertex has at most $2^t$ outgoing edges.\\ \noindent\textbf{Infiltration product} (introduced in \cite{lothaire1997combinatorics}): The infiltration product has been extensively used in \cite{lothaire1997combinatorics}, as a tool in non-commutative algebra. Here we give an edit-graph interpretation of this tool. We also give a formal definition later in this section. Using the edit graph we can construct the set of possible supersequences $\mathcal{S}(f,g)$ of $f,g$ which are covered by it. Clearly multiple paths could yield the same supersequence and we can count the number of distinct ways $\mathbf N(h;f,g)$ one can construct the same supersequence $h$ from $f,g$. We can informally define the \emph{infiltration product $f\uparrow g$} of $f$ and $g$, as a polynomial with monomials the supersequences $h$ in $\mathcal{S}(f,g)$ and coefficients $\langle f\uparrow g,h\rangle$ equal to $\mathbf N(h;f,g)$. In Fig.~\ref{fig:editgraph_smap1}, it is easy to verify that there is exactly one path corresponding to `101001' and hence $\langle 001\uparrow 101,101001 \rangle=1$ and similarly $\langle 001\uparrow 101,01001 \rangle=2$. One could find these coefficients for all relevant sequences and form the polynomial as described. More examples: Let $\mathcal{A}=\{a,b\}$, then \begin{itemize}[wide=2pt] \item $ab\uparrow ab=ab+2aab+2abb+4aabb+2abab$, \item $ab\uparrow ba=aba+bab+abab+2abba+2baab+baba.$ \end{itemize} The infiltration operation is commutative and associative, and infiltration of two sequences $f\uparrow g$ is a polynomial with variables of length (or \textit{degree}) at most $|f|+|g|$; see \cite{lothaire1997combinatorics}. The definition of infiltration extends to two polynomials via distributivity (precisely defined in later), and consequently to multiple sequences as well. For multiple sequences, infiltration has the same edit graph interpretation: $\langle f_1\uparrow f_2 \uparrow...\uparrow f_t, w \rangle$ is the number of distinct ways of constructing $w$ as a supersequence of $f_1, f_2, ... ,f_t$ so that the construction covers $w$, i.e., construct the $t$-dimensional edit graph of $f_1, f_2, ... ,f_t$ and count the number of paths corresponding to $w$. \subsection{Formal definition of infiltration product} We now give a more formal definition of the infiltration product (see \cite{lothaire1997combinatorics} for the equivalence of the two definitions and a more rigorous treatment). A \textit{formal series} with indeterminates (or variables) in a set $\mathcal A$ and coefficients in a commutative ring $\mathcal R$, is a mapping of $\mathcal A^*$ onto $\mathcal R$. Recall that a commutative ring is a set which forms an abelian group under an \textit{addition} operation, is a monoid under a \textit{multiplication} operation which commutes, and the multiplication operation distributes over addition. Here we consider $\mathbb Z$, the set of integers as the commutative ring $\mathcal{R}$. A formal series is called a \textit{polynomial} if only a finite number of sequences are mapped to non-zero values, the rest of the sequences map to zero. Consider two polynomials $\sigma,\tau: \mathcal{A}^*\rightarrow \mathbb Z$. The value taken by a sequence $w\in \mathcal A^*$ on $\sigma$ (or the coefficient of $w$ in $\sigma$) is denoted by $\langle \sigma,w\rangle \in \mathbb R$. We also define binary addition ($\oplus$) and multiplication operations ($\times$) on the set of polynomials as follows: \begin{align} \langle \sigma\oplus \tau,w\rangle \triangleq \langle \sigma,w\rangle + \langle \tau,w \rangle \quad \forall w\in \mathcal A^*,\label{eq:polynomial_add}\\ \langle \sigma\times \tau,w\rangle \triangleq \sum_{\substack{f,g\in \mathcal A^*:\\ f.g=w}}\langle \sigma,f\rangle \langle \tau,g \rangle \quad \forall w\in \mathcal A^*.\label{eq:polynomial_prod} \end{align} We will use the usual symbols $+$ and $.$ in place of $\oplus$ and $\times$ in this work for convenience. The meaning of the operation would be clear depending on the operands. With these operations the set of polynomials form a non-commutative ring, and is denoted by $\mathbb Z\langle\mathcal A \rangle$, also called the free $\mathbb Z$-algebra on $\mathcal A$ in ring theory. Note that the addition and multiplication operations defined in \eqref{eq:polynomial_add} and \eqref{eq:polynomial_prod} are similar to the operations defined on commutative polynomials, except that the multiplication operation under the summation in \eqref{eq:polynomial_prod} ($f.g=w$) is actually concatenation and is non-commutative. The multiplication inside the summation in \eqref{eq:polynomial_prod} is multiplication in the real field and hence commutative. It is also easy to prove that the multiplication defined in \eqref{eq:polynomial_prod} distributes over addition defined in \eqref{eq:polynomial_add}. Thus, a polynomial in $\mathbb Z\langle\mathcal A \rangle$ can be represented as a sum of monomials in $\mathcal A^*$ each with an associated coefficient in $\mathbb Z$, i.e., $\sigma=\sum\limits_{w\in \mathcal A^*} \langle\sigma,w \rangle w$. Define the \textit{degree} of a polynomial to be equal to the length of a longest sequence with a non-zero coefficient in the polynomial and the \textit{number of terms} of a polynomial as the number of sequences with non-zero coefficients in the polynomial. Note that a degree $d$ polynomial could have a number of terms upto $2^{d+1}-1$. With this, the \textit{infiltration product} (in general, for two polynomials) is defined as follows: \begin{align} \forall f\in \mathcal{A}^*,& \quad f\uparrow e = e\uparrow f=f.\nonumber \\ \forall f,g\in \mathcal{A}^*&,\quad \forall a,b\in \mathcal{A}, \nonumber\\ fa\uparrow gb=(f\uparrow gb)a&+(fa\uparrow g)b+\mathbbm{1}_{a=b}(f\uparrow g)a.\nonumber \\ \forall \sigma,\tau \in \mathbb{Z}\langle\mathcal{A} \rangle, \quad &\sigma\uparrow \tau=\sum_{f,g\in \mathcal{A}^*} \langle \sigma,f \rangle \langle \tau,g \rangle (f\uparrow g). \label{def:infiltforseq} \end{align} \textbf{Summary of definitions and ideas introduced in this section:} \begin{itemize} \item The binomial coefficient captures the likelihood of observations for deletion channels. \item An extension of the binomial coefficient function where one of the parameters can take real values has been introduced; this function is pivotal for our results on the single-trace deletion channel. \item For multiple deletion channels, the error events can be categorized into two groups -- one where an input symbol is deleted in all the traces, and second, the complement of this event. This categorization results in a natural decomposition of multiple deletion channel model into a cascade model involving the remnant channel. \item The remnant channel disregards the error events where a symbol is deleted in all the traces. \item The edit graph provides a way to visualize all the possible error events and input sequences to a remnant channel given its outputs. \item The infiltration product serves the same purpose as the edit graph, but has an algebraic flavor and provides rigor for proofs and analyses. The edit graph, on the other hand, is more helpful in designing reconstruction algorithms over deletion channels. \end{itemize} \section{Notation and Tools} \label{sec:notation} \noindent \textbf{Basic notation:} We borrow some notation from \cite{lothaire1997combinatorics} which deals with non-commutative algebra; we restate them here for convenience. Calligraphic letters refer to sets, capitalized letters correspond to random variables and bold letters are used for functions. Let $\mathcal{A}$ be the set of all symbols. Throughout this work, we will focus on the case where $\mathcal{A}=\{0,1\}$, though our methods extend to arbitrarily large sets of finite size. Define $\mathcal{A}^n$ to be the set of all $n$-length sequences and $\mathcal{A}^*$ to be the set of all finite length sequences with symbols in $\mathcal{A}$. For a sequence $f$, $|f|$ denotes the length of $f$. For integers $i,j$, we define $[i:j] \triangleq \{i,i+1,...,j\}$ if $j\geq i$ and $[i:j] \triangleq \emptyset$ otherwise. We also define $[i] \triangleq [1:i]$. For a vector or sequence $x=(x_1,x_2,...,x_{i-1},x_i,x_{i+1},...,x_n)$, define $$x^{(i\rightarrow s)}\triangleq (x_1,x_2,...,x_{i-1},s,x_{i+1},...,x_n),$$ where the $i^{th}$ coordinate of $x$ is replaced by symbol $s$. \\ \noindent \textbf{Binomial coefficient \cite{lothaire1997combinatorics}:} Given sequences $f$ and $g$ in $\mathcal{A}^*$, the number of subsequence patterns of $f$ that are equal to $g$ is called the \textit{binomial coefficient} of $g$ in $f$ and is denoted by $f\choose g$. For example, ${'apple' \choose 'ape'} = 2$ since $'ape'$ can be obtained from two (overlapping) subsequences of $'apple'$. When the alphabet $\mathcal{A}$ is of cardinality 1, ${f \choose g} = {|f| \choose |g|}$, the classical binomial coefficient with their respective lengths as the parameters. This definition hence could be thought of as a generalization of the classical binomial coefficients. We will denote by $e$ the sequence of length 0, and {define ${f \choose e} \triangleq 1\ \forall\ f\ \in\ \mathcal{A}^*$.} We also define the classical binomial coefficient ${a \choose b}\triangleq 0,$ whenever $b>a$ or $b<0$ for ease of use. The binomial coefficient forms the backbone for the probabilistic analysis of deletion channels since the input-output relation for a deletion channel (with deletion probability $\delta$, input $X$ and output $Y$) can be expressed as \begin{equation} \label{eq:in-out_relation} \Pr(Y=y|X=x) = {x \choose y} \delta^{|x|-|y|} (1-\delta)^{|y|}. \end{equation} The proof is straightforward -- the number of distinct error events that give rise to $y$ from $x$ is exactly the number of subsequences of $x$ which are equal to $y$. Each of these error events has a probability $\delta^{|x|-|y|} (1-\delta)^{|y|}$, wherein the exponent of $\delta$ corresponds to the deleted symbols and the exponent of $1-\delta$ to the undeleted symbols. \\ \noindent \textbf{Maximum Likelihood (ML) estimate:} Given the definition of the binomial coefficient, the maximum-likelihood (ML) estimate over a deletion channel with observed output $Y$ can be cast in the following form: \begin{align*} \argmax_{x \in \{0,1\}^n} {x \choose Y}.\numberthis \label{eq:ML_deletion} \end{align*} In the case of multiple deletion channels with observed traces $Y^{(1)},...,Y^{(t)}$, the ML formulation is similar: \begin{align*} \argmax_{x \in \{0,1\}^n} \prod_{j=1}^{t} {x \choose Y^{(j)}}.\numberthis \label{eq:ML_multiple_deletion} \end{align*} As yet, there is no known efficient way to come up with a solution for either of the above two formulations (see \cite{mitzenmacher2009survey}).\\ \noindent \textbf{Relaxed binomial coefficient.} We now introduce the function $\mathbf F(\cdot)$ which can be thought of as a real-valued relaxation of the binomial coefficient. This function is used in sections~\ref{sec:1deletion_ML} and~\ref{sec:1deletion}. An intuitive definition is as follows: Consider a random vector $Z\in\{0,1\}^n$ such that $Z_i\sim$ ind. Ber$(p_i)$, let $p$ be the vector of probabilities of length $n$, $\mathcal S\subseteq [n]$ a subset of the indices of size $m$, and ${v}$ a binary vector of length $m$. Then, $$\mathbf F(p,v)=\sum_{\substack{\mathcal S||\mathcal S|=m}} \Pr(Z_{\mathcal S}= v).$$ It is easy to see that $\mathbf F(p,v)=\mathbb E_{Z\sim p}\ {Z \choose v}$; in words, suppose $Z$ is sampled from a Bernoulli distribution parametrized by $p$, $\mathbf F(p,v)$ is the expected number of times $v$ appears as a subsequence of $Z$. Clearly if $p \in \{0,1\}^n$, then $Z=p$ with probability 1 and $\mathbf F(p,v) = {p \choose v}$. More precisely, $\mathbf F(\cdot)$ is defined as: \begin{definition} \label{def:f} \begin{align*} &\mathbf F: [0,1]^n \times \{0,1\}^m \rightarrow \mathbb{R},\\ \mathbf F(p, v)\triangleq &\begin{cases} \sum\limits_{\substack{\mathcal S|\mathcal S\subseteq [n],\\|\mathcal S|=m}} \quad \prod\limits_{i=1}^m p_{\mathcal S_i}^{v_i} (1-p_{\mathcal S_i})^{1-v_i} & 1 \leq m\leq n \\ 1 & 0=m\leq n \\ 0 & \text{else}. \end{cases} \end{align*} \end{definition} Though at first sight $\mathbf F(p,v)$ sums over an exponential number of subsets, a dynamic programming approach can be used to compute it in $O(nm)$ time complexity (see Appendix~\ref{app:F_compute}).\\ \noindent \textbf{Decomposition of the $t$-trace deletion channel:} The following definitions and ideas are relevant only for Section \ref{sec:exactsmap} and can be omitted for the sections on single-trace deletion channel. We first state a result of ours that aids in thinking about error events in multiple deletion channels. The events occurring in the $t$-deletion channel model can be categorized into two groups: \begin{enumerate} \item an input symbol is deleted in \textit{all} the $t$-traces, \item an input symbol is reflected in at least one of the traces. \end{enumerate} The error events of the first kind are in some sense ``not correctable'' or even ``detectable'' in any situation since it is impossible to tell with absolute certainty what and where the deleted symbol could have been (although the probabilities need not be uniform). The events of the second kind, however, can be detected and corrected in some situations. This thought process gives rise to a natural decomposition of the $t$-deletion channel model into a cascade of two channels: the first one being a deletion channel which captures error events of the first kind and the second one is what we call the \textit{remnant channel} which captures events of the second kind (see Fig.~\ref{fig:channel_equiv}). More precisely, we define the remnant channel as follows: \begin{definition} \textit{Remnant channel:} an input symbol to the remnant channel is reflected in $k>0$ given outputs and deleted in the rest with a probability $\frac{\delta^{t-k}(1-\delta)^k}{1-\delta^t}$. \end{definition} It is easy to note that probability of the union of all possible events here is $\sum_{k=1}^t {t \choose k} \frac{\delta^{t-k}(1-\delta)^k}{1-\delta^t}=1$, validating our definition. \begin{restatable}{theorem}{channelequiv} \label{thm:channel_equiv} The $t$-deletion channel model and the cascade of the deletion channel with remnant channel shown in Fig.~\ref{fig:channel_equiv} are probabilistically equivalent, i.e., $$\Pr({Y}^{(1)},{Y}^{(2)},...,{Y}^{(t)}|X = x) = \Pr(\tilde{Y}^{(1)},\tilde{Y}^{(2)},...,\tilde{Y}^{(t)}|X = x).$$ \end{restatable} An algebraic proof of the theorem requires a few more definitions and is relegated to Appendix~\ref{app:channel_equiv}. \begin{figure}[!h] \begin{center} \includegraphics[scale=0.4]{channel_equiv.pdf} \caption{A channel equivalence result: the $t$-trace deletion channel model in (a) is probabilistically equivalent to the the cascade of a deletion channel with the \textit{remnant channel} ($ \mathcal C_2$) in (b).} \label{fig:channel_equiv} \end{center} \end{figure} \noindent\textbf{Edit graph} (\cite{Gusfield1997}): Similar graph constructs have been defined in related problems on common supersequences and subsequences (see \cite{Nicosia2001} for example). This graph is closely related to the error events in the remnant channel. We start with a simple case and generalize subsequently. Define an \textit{edit graph} given two sequences $f$ and $g$, where every path connecting the ``origin'' to the ``destination'' on the edit graph yields a supersequence $h$ of $f,g$, where $h$ is ``covered'' by $f,g$ -- i.e., each symbol of $h$ comes from either $f$ or $g$ or both. In other words, given that $f$ and $g$ are the outputs of the remnant channel (with two outputs), each path from the origin of the edit graph to the destination corresponds to a possible input $h$ to the remnant channel and to an error event which resulted in outputs $f,g$ with input $h$. For $f$ and $g$ in $\mathcal A^*$, we form a graph $\mathcal{G}(f,g)$ with $(|f|+1)(|g|+1)$ vertices each labelled with a distinct pair $(i,j), 0\leq i\leq |f|,\ 0\leq j\leq |g|$. A directed edge $(i_1,j_1)\rightarrow(i_2,j_2)$ exists iff at least one of the following holds: \begin{enumerate} \item$i_2-i_1=1$ and $j_1=j_2$, or \item $j_2-j_1=1$ and $i_1=i_2$, or \item $i_2-i_1=1$, $j_2-j_1=1$ and $f_{i_2}=g_{j_2}$, \end{enumerate} where $f_i$ is the $i^{th}$ symbol of the sequence $f$. The origin is the vertex $(0,0)$ and the destination $(|f|,|g|)$. \begin{figure}[!h] \centering \includegraphics[scale=0.25]{editgraph_smap1.pdf} \caption{ Edit graph for sequences $f=$ `001' and $g=$ `101'. Make a grid so the vertical edges are aligned with a symbol in $f$ and horizontal edges with $g$ as shown. A diagonal edge $(i{-}1,j{-}1)\rightarrow (i,j)$ exists if $f_i = g_j$. The thick red edges form a path from the origin to the destination; this path corresponds to $h=$`0101' -- sequentially append the corresponding symbol to which each edge is aligned. It is also easy to verify that $h$ is a supersequence of both $f$ and $g$, and could be obtained as a covering of $f$ and $g$; the path itself gives one such covering. This covering also corresponds to an error event (or a deletion pattern) in the remnant channel which would result in outputs $f$ and $g$ with input $h=$ `0101' -- the deletion pattern is shown in the figure.} \label{fig:editgraph_smap1} \end{figure} Let $p=((i_1,j_1),(i_2,j_2),...,(i_m,j_m))$ be a path in $\mathcal{G}(f,g)$. We define $ s(p)$ to be the sequence corresponding to the path. Intuitively, $s(p)$ is formed by appending symbols in the following way: append the corresponding $f$ symbol for a vertical edge, $g$ symbol for horizontal edge, and $f$ or $g$ symbol for diagonal edge (see example Fig.~\ref{fig:editgraph_smap1}). Any path from $(0,0)$ to $(|f|,|g|)$ corresponds to a supersequence of $f$ and $g$ and which is covered by $f$ and $g$. More formally, define $ s(p)\triangleq x_1x_2...x_{m-1}$ where $$x_k = \begin{cases} f_{i_{k+1}} \quad\text{if }j_{k}=j_{k+1},\\ g_{j_{k+1}} \quad\text{if }i_{k}=i_{k+1},\\ f_{i_{k+1}} \quad\text{else.} \end{cases} $$ The construct of edit graph can be extended to more than 2 sequences with the same idea. For sequences $f_1,f_2,...,f_t$, construct a $t$-dimensional grid with a number of vertices $(|f_1|+1)(|f_2|+1)...(|f_t|+1)$ labeled from $(0,0,...,0)$ to $(|f_1|,|f_2|,...,|f_t|)$. A vertex $u=(i_1,i_2,...,i_t)$ is connected to $v=(j_1,j_2,...,j_t)$ (we say $u \rightarrow v$) iff both of the following conditions are met: \begin{itemize} \item $j_l=i_l$ or $j_l=i_l+1$ $\forall\ l\in [t]$, i.e., $(i_1,...,i_t)$ and $(j_1,...,j_t)$ are vertices of a particular unit cube. Only these type of vertices can share an edge in the grid graph. \item Let $\mathcal T \subseteq [t]$ be the collection of indices where $j_l=i_l+1$. Then ${f_l}_{j_l}$ is equal $\forall\ l \in \mathcal T$. For example in 4 dimensional grid, consider the two vertices $(10,5,8,2)$ and $(10,6,9,2)$. In this case $\mathcal T = \{2,3\}$ since the second and third coordinates differ by 1. Therefore $(10,5,8,2)\rightarrow (10,6,9,2)$ iff ${f_2}_{5}={f_3}_{9}$. Note that if only one coordinate differs by 1 in the two vertices, a directed edge always exists (in other words all non-diagonal edges exist). \end{itemize} Define the vertex $(0,...,0)$ to be the origin of this graph and the vertex $(|f_1|,...,|f_t|)$ to be the destination. If $|f_j|=O(n)\ \forall\ j$, this graph has a number of vertices $O(n^t)$ and a maximum number of edges $O((2n)^t)$ since each vertex has at most $2^t-1$ outgoing edges.\\ \noindent\textbf{Infiltration product} (introduced in \cite{lothaire1997combinatorics}): The infiltration product has been extensively used in \cite{lothaire1997combinatorics}, as a tool in non-commutative algebra. Here, we give an edit-graph interpretation of this tool. A formal algebraic definition of the infiltration product is in Appendix~\ref{app:infil_def}. Using the edit graph we can construct the set of possible supersequences $\mathcal{S}(f,g)$ of $f$, $g$ that are covered by the symbols in $f$ and $g$. Clearly multiple paths could yield the same supersequence and we can count the number of distinct ways $\mathbf N(h;f,g)$ one can construct the same supersequence $h$ from $f$, $g$. We can informally define the \emph{infiltration product $f\uparrow g$} of $f$ and $g$, as a polynomial with monomials the supersequences $h$ in $\mathcal{S}(f,g)$ and coefficients $\langle f\uparrow g,h\rangle$ equal to $\mathbf N(h;f,g)$. For the example in Fig.~\ref{fig:editgraph_smap1}, it is easy to verify that there is exactly one path corresponding to `101001' and hence $\langle 001\uparrow 101,101001 \rangle=1$ and similarly $\langle 001\uparrow 101,01001 \rangle=2$. One could find these coefficients for all relevant sequences and form the polynomial as described. As additional examples, let $\mathcal{A}=\{a,b\}$, then \begin{itemize}[wide=2pt] \item $ab\uparrow ab=ab+2aab+2abb+4aabb+2abab$, \item $ab\uparrow ba=aba+bab+abab+2abba+2baab+baba.$ \end{itemize} The infiltration operation is commutative and associative, and infiltration of two sequences $f\uparrow g$ is a polynomial with variables of length (or \textit{degree}) at most $|f|+|g|$; see \cite{lothaire1997combinatorics}. The definition of infiltration extends to two polynomials via distributivity (precisely defined in Appendix~\ref{app:infil_def}), and consequently to multiple sequences as well. For multiple sequences, infiltration has the same edit graph interpretation: $\langle f_1\uparrow f_2 \uparrow...\uparrow f_t, w \rangle$ is the number of distinct ways of constructing $w$ as a supersequence of $f_1, f_2, ... ,f_t$ so that the construction covers $w$, i.e., construct the $t$-dimensional edit graph of $f_1, f_2, ... ,f_t$ and count the number of paths corresponding to $w$.\\ \noindent \textbf{Summary of definitions and ideas introduced in this section:} \begin{itemize} \item The binomial coefficient captures the likelihood of observations for deletion channels. \item A real-valued extension of the binomial coefficient function is introduced; this function is pivotal to our results on the single-trace deletion channel. \item For multiple deletion channels, the error events can be categorized into two groups -- one where an input symbol is deleted in all the traces, and second, the complement of this event. This categorization results in a natural decomposition of multiple deletion channel model into a cascade model involving the remnant channel. \item The remnant channel disregards the error events where a symbol is deleted in all the traces. \item The edit graph provides a way to visualize and construct all the possible error events and input sequences to a remnant channel given its outputs. \item The infiltration product serves the same purpose as the edit graph, but has an algebraic flavor and provides rigor for proofs and analysis. The edit graph, on the other hand, is more helpful in designing algorithms. \end{itemize} \section{Maximum likelihood for the single-trace deletion channel} \label{sec:1deletion_ML} Consider the ML formulation for the single-trace deletion channel given non-empty trace $Y$ and all possible $n$-length inputs allowed, restated here for convenience: \begin{equation} \argmax_{x\in \{0,1\}^n} {x \choose Y}. \label{eq:1deletion_ML} \end{equation} To the best of our knowledge, the only known method to solve \eqref{eq:1deletion_ML} involves iterating over all possible choices of $x$ and computing the objective value for each of the choices. We here show that it is sufficient to solve a continuous relaxation of above problem to obtain a solution to \eqref{eq:1deletion_ML}. Note that there could be multiple solutions to \eqref{eq:1deletion_ML}. Before going in the main result, we first state a useful lemma which factors out a given coordinate $p_i$ out of $\mathbf F(p,Y)$. The proof of the lemma is relegated to the appendix. \begin{restatable}{lemma}{deletionMLrellemma} For $p=[p_1,p_2,..,p_i,...,p_n]$ and $Y=Y_1Y_2...Y_m$ with $n \geq m > 0$, we have \begin{align*} \mathbf F(p,Y) = \mathbf F( p_{[n]\backslash \{i\}},Y) + p_i \sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]})\\ + (1-p_i) \sum\limits_{k|Y_k=0}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}). \end{align*} \label{lemma:F_decomposition} \end{restatable} \begin{theorem} An alternative optimization to characterize ML for the single-trace deletion channel. \begin{equation} \max_{x\in \{0,1\}^n} {x \choose Y} = \max_{p\in [0,1]^n} \mathbf F(p,Y). \label{eq:ml_opt_equiv} \end{equation} Furthermore, given any non-integral $p^* \in [0,1]^n$ that maximizes $\mathbf F(p,Y)$, one could construct a corresponding integral solution $x^* \in \{0,1\}^n$ that maximizes $\mathbf F(p,Y)$ and consequently is also a solution to $\max_{x\in \{0,1\}^n} {x \choose Y}$. \end{theorem} \begin{proof} As noted earlier, we have ${x \choose Y} = \mathbf F(x,Y)$. Therefore, we are interested in proving the following: \begin{align*} \max_{x\in \{0,1\}^n} \mathbf F(x,Y) \equiv \max_{p\in [0,1]^n} \mathbf F(p,Y).\numberthis \label{eq:ml_opt_equiv_proof1} \end{align*} To show this and also the second statement, we prove that given $p=(p_1,p_2,...,p_i,...,p_n)$, at least one of the following holds true: \begin{itemize} \item$\mathbf F(p^{(i\rightarrow 0)},Y) \geq \mathbf F(p,Y)$, where $p^{(i\rightarrow 0)}=(p_1,p_2,...,p_{i-1},0,p_{i+1}...,p_n)$ is the vector where the $i^{th}$ coordinate is replaced by 0. \item $\mathbf F(p^{(i\rightarrow 1)},Y) \geq \mathbf F(p,Y)$, where $p^{(i\rightarrow 0)}=(p_1,p_2,...,p_{i-1},1,p_{i+1}...,p_n)$ is the vector where the $i^{th}$ coordinate is replaced by 1. \end{itemize} Thus if $p^*$ is an optimal solution to $\max_{p\in [0,1]^n} \mathbf F(p,Y)$ with $p_i\in (0,1)$, then at least one of $p^{(i\rightarrow 0)}$ or $p^{(i\rightarrow 1)}$ is also an optimal solution. Sequentially applying this argument for each coordinate of $p$ shows that there exists a point in $\{0,1\}^n$ which is also an optimal solution to $\max_{p\in [0,1]^n} \mathbf F(p,Y)$ and consequently to $\max_{x\in \{0,1\}^n} \mathbf F(x,Y)$. Now to prove our claim, we use Lemma~\ref{lemma:F_decomposition} to factor out $p_i$ terms in $\mathbf F(p,Y)$: \begin{align*} \mathbf F(p,Y) = \mathbf F( p_{[n]\backslash \{i\}},Y) + p_i \sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]})\\ + (1-p_i) \sum\limits_{k|Y_k=0}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}). \end{align*} There are 3 cases \begin{enumerate} \item $$\sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}) = \sum\limits_{k|Y_k=0}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}).$$ \\In this case it is easy to verify that $\mathbf F(p^{(i\rightarrow 0)},Y) = \mathbf F(p,Y) = \mathbf F(p^{(i\rightarrow 1)},Y).$ \item $$\sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}) > \sum\limits_{k|Y_k=0}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}).$$ \\In this case it is easy to verify that $\mathbf F(p^{(i\rightarrow 0)},Y) \leq \mathbf F(p,Y) \leq \mathbf F(p^{(i\rightarrow 1)},Y).$ \item $$\sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}) < \sum\limits_{k|Y_k=0}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}).$$ \\In this case it is easy to verify that $\mathbf F(p^{(i\rightarrow 0)},Y) \geq \mathbf F(p,Y) \geq \mathbf F(p^{(i\rightarrow 1)},Y).$ \end{enumerate} Thus in each of the 3 cases, we see that at least one of $\mathbf F(p^{(i\rightarrow 0)},Y)$ or $\mathbf F(p^{(i\rightarrow 1)},Y)$ is at least as large as $\mathbf F(p,Y)$ thus proving the theorem. Note that the proof gives a natural way to find an optimal lattice point $p_{lattice}^*$ given a non-lattice point $p^*$ by iterating through each coordinate of $p^*$ and switching them to $0$ or $1$ by comparing $\sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]})$ with $\sum\limits_{k|Y_k=0}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}).$ \end{proof} \section{Numerical results} \label{sec:Numerics} In this section we show numerics supporting our theoretical results. The metric we use to measure the performance of different reconstruction algorithms is \textit{Hamming error rate}, which is defined as the average Hamming distance (the Hamming distance between the actual and estimated input sequence divided by the input sequence length).\\ \noindent \textbf{Single-trace deletion channel.} \begin{itemize}[leftmargin=3mm] \item Fig.~\ref{fig:numerics_single1} compares the error rate for reconstruction via ML heuristic (Alg.~\ref{alg:cood_switch}) when the initialization is a random lattice point and when the initialization is a random interior point, and also the symbolwise MAP via Alg.~\ref{alg:apprx_smap_dp} for a small blocklength $n=10$. For Alg.~\ref{alg:cood_switch}, we start with 5 random initializations and choose the one that gives the maximum objective value. As can be seen, initialization with an interior point far outperforms initialization with lattice point, thus validating the usefulness of our relaxation. \end{itemize} \begin{figure}[t!] \centering \includegraphics[scale=0.48]{ml_int_vs_ver_error.eps} \caption{Hamming error rate for reconstruction via coordinate switch ML heuristic (Alg.~\ref{alg:cood_switch}) when the initialization is a random lattice point and when the initialization is a random interior point, and reconstruction via symbolwise MAP (Alg.~\ref{alg:apprx_smap_dp}) for a blocklength $n=10$.} \label{fig:numerics_single1} \end{figure} \vspace{10pt} \noindent \textbf{$t$-trace deletion channel model.} Fig.~\ref{fig:numerics1} and Fig.~\ref{fig:numerics2} show results comparing reconstruction via symbolwise MAP for $t$-trace deletion channel model (Alg.~\ref{alg:exact_smap}), reconstruction via sequentially updating posterior probabilities over the traces (Alg.~\ref{alg:apprx_smap}), reconstruction via independently combining posteriors from each of the traces (described as Alg.~\ref{alg:ind_comb}) and a trace reconstruction algorithm from \cite{Batu2004} called the \textit{Bitwise Majority Alignment (BMA)} reproduced here as Alg.~\ref{alg:bitwise_majority}. We next make two observations, related to two of these algorithms. \noindent \textbf{Independent posterior combination:} As pointed in the introduction, computing the posterior probabilities for each deletion channel and combining them as if they came from independent observations does not provide a natural solution for computing the posterior probabilities for the $t$-trace deletion channel. One could, however, check how such a naive combination of posteriors compares with our reconstruction algorithms for $t$-traces. \noindent \textbf{Bitwise Majority Alignment:} BMA reconstructs the input sequence by first ``aligning'' the traces using a pointer for each trace, and then taking the majority of the pointed symbols. We note that the state-of-the-art trace reconstruction algorithms in the literature are applicable in the asymptotic regime where the blocklength $n$ and the number of traces $t$ approach $\infty$; it is not clear how to adapt such algorithms for a finite blocklength and a small number of traces. \begin{algorithm}[t!] \caption{Trace reconstruction via independent posterior combination}\label{alg:ind_comb} \begin{algorithmic}[1] \item Input: Traces {$Y^{(1)},...,Y^{(t)}$}, input length $n$ \\ Outputs: Estimate of the input $\hat X$ \State Initialize priors $p^{old} \gets (0.5,0.5,...,0.5)$ \For {$l=1:t$} \State Use Alg.~\ref{alg:apprx_smap_dp} with $p^{old}$ and $Y^{(l)}$ to compute posteriors $p^{(l),new}$ \EndFor \For {$i=1:n$} \If {$\prod_{l=1}^t p^{(l),new}_i \geq \prod_{l=1}^t (1-p^{(l),new}_i)$} $\ \hat X_i \gets 1$ \Else $\ \hat X_i \gets 0$ \EndIf \EndFor \State \textbf{return} $\hat X_1 \hat X_2 ... \hat X_n$ \end{algorithmic} \end{algorithm} \begin{algorithm}[!t] \caption{Bitwise Majority Alignment} \label{alg:bitwise_majority} \begin{algorithmic}[1] \item Input: Traces {$Y^{(1)},Y^{(2)},...,Y^{(t)}$, input length $n$}\\ Output: estimate of input $\hat X = \hat X_1 \hat X_2...\hat X_n$. \State Initialize $c_j=1$ for $j\in [t]$. \State Initialize $\hat X_i = 1$ for $i \in [n]$. \For{$i \in\ [0:n]$} \State Let $b$ be the majority over all $t$ of $Y^{(j)}_{c_j}$ \State $\hat X_i \gets b$ \State Increment $c_j$ for each $j$ such that $Y^{(j)}_{c_j} = b$ \EndFor \State \textbf{return} $\hat X_1 \hat X_2 ... \hat X_n$ \end{algorithmic} \end{algorithm} Our numerical evaluation results are as follows. \begin{itemize}[leftmargin=3mm] \item Fig.~\ref{fig:numerics1} compares symbolwise MAP for the $t$-trace deletion channel model (Alg.~\ref{alg:exact_smap}), trace reconstruction heuristic via sequentially updating posterior probabilities (Alg.~\ref{alg:apprx_smap}) with BMA (Alg.~\ref{alg:bitwise_majority}) for a small blocklength $n=10$. As seen, both of our algorithms significantly outperform BMA. Moreover, the heuristic Alg.~\ref{alg:apprx_smap} is not much worse than Alg.~\ref{alg:exact_smap}, at least for this blocklength. Note that Alg.~\ref{alg:apprx_smap} is polynomial in $n$ and $t$ ($O(tn^2)$) while Alg.~\ref{alg:exact_smap} is exponential in $t$ ($O(2^tn^{t+2})$). \item Fig.~\ref{fig:numerics2} compares the reconstruction heuristic via sequentially updating posterior probabilities (Alg.~\ref{alg:apprx_smap}) with reconstruction via independently combining posteriors from each of the traces (Alg.~\ref{alg:ind_comb}) and BMA (Alg.~\ref{alg:bitwise_majority}), over a larger blocklength of $n=100$. Clearly, Alg.~\ref{alg:apprx_smap} outperforms both the others, indicating that it is an interesting heuristic for trace reconstruction. \begin{figure}[t!] \centering \includegraphics[width=16cm]{errors_BL10.eps} \caption{Hamming error rate comparison for symbolwise MAP for the $t$-trace deletion channel model (Alg.~\ref{alg:exact_smap}), trace reconstruction heuristic via sequentially updating posterior probabilities (Alg.~\ref{alg:apprx_smap}) with BMA (Alg.~\ref{alg:bitwise_majority}) for a blocklength $n=10$.} \label{fig:numerics1} \end{figure} \item We note that with the number of traces, though the performance of all algorithms improves, the returns tend to diminish. This intuitively makes sense because not all the information in each additional trace is ``new''; some of it is already conveyed by existing traces. \item Even when the deletion probability is $\delta = 0.5$, the error rate is still less than $0.5$. This is not unexpected since the observed deleted sequence still carries some information about each of the input bits. \end{itemize} \begin{figure}[t!] \centering \includegraphics[width=16cm]{errors_BL100.eps} \caption{Hamming error rate comparison for reconstruction heuristic via sequentially updating posterior probabilities (Alg.~\ref{alg:apprx_smap}) with reconstruction via independently combining posteriors from each of the traces (Alg.~\ref{alg:ind_comb}) and BMA (Alg.~\ref{alg:bitwise_majority}) for a larger blocklength of $n=100$.} \label{fig:numerics2} \end{figure} \section{Introduction} \label{sec:intro} Sequence reconstruction over deletion channels, both with and without a codebook, has received considerable attention in the information theory as well as in the theoretical computer science literature. From an information theory perspective, reconstruction over the deletion channel, or more specifically a maximum-likelihood (ML) argument for the deletion channel, would give further insight on the capacity of the deletion channel, a long-standing open problem (see \cite{mitzenmacher2009survey}). To quote \cite{mitzenmacher2009survey} -- ``at the very least, progress in this direction would likely surpass previous results on the capacity of the deletion channels''. Yet, there are no results on reconstruction over a deletion channel with statistical guarantees -- in this work, we take a step in this direction. On the other hand, the problem of \textit{trace reconstruction}, as introduced in \cite{Batu2004}, has received renewed interest in the past few years (see \cite{Holenstein2008}, \cite{Peres2017}, \cite{De2017}, \cite{holden18}, \cite{Nazarov:2017}, \cite{holden2018lower}, \cite{chase2019new}). The problem of trace reconstruction can be stated simply as follows: consider a sequence $X$ which is simultaneously passed through $t$ independent deletion channels to yield $t$ deleted observations (also called \textit{traces}) of $X$ (see Fig.~\ref{fig:tdeletion}). How many such traces are needed to reconstruct $X$ perfectly? A variety of upper and lower bounds for this problem have been proposed, both for worst case and average case reconstruction. Our problem definition, stated in the following paragraph, is closely related to the average case trace reconstruction. \begin{figure}[!h] \begin{center} \includegraphics[scale=0.2]{tdeletion.pdf} \caption{$t$-deletion channel model: sequence $X$ passed through $t$ independent deletion channels to yield $t$ \textit{traces}. We aim to estimate $X$ from the $Y^{(i)}$s.} \label{fig:tdeletion} \end{center} \end{figure} \noindent \textbf{Problem definition.} Given an input sequence of length $n$ (known apriori), the independently and identically distributed (i.i.d.) deletion channel deletes each input symbol indepedently with probability $\delta$, producing at its output a subsequence of the input sequence. Consider a sequence $X$ passed through $t$ ($t$ is fixed) such deletion channels as shown in Fig.~\ref{fig:tdeletion}. We call this the $t$-deletion channel model. We ask two questions: \begin{enumerate} \item For $t=1$ (see Fig.~\ref{fig:1deletion}, also called the single deletion channel model), and when $X_i \sim\ \text{ind. Ber}(p_i)$, compute the posterior distributions of $X_i$ given the trace $Y$. \begin{figure}[!h] \begin{center} \includegraphics[scale=0.25]{1deletion.pdf} \caption{The single deletion channel model. We assume $X_i \sim\ \text{ind. Ber}(p_i)$.} \label{fig:1deletion} \end{center} \end{figure} \item In the $t$ deletion channel model, for a fixed $t$ assume that $X_i \sim\ \text{i.i.d. Ber}(0.5)$ and compute the posterior distributions of $X_i$ given all traces $Y^{(1)}, Y^{(2)},...,Y^{(t)}$. \end{enumerate} Note that solving 1) above doesn't lead to a natural solution for 2). This is because for a memoryless channel, we have $Y^{(j)} - X_i - Y^{(k)}$ and hence $\Pr(X_i=\alpha|Y^{(j)}, Y^{(k)}) \propto \Pr(X_i=\alpha|Y^{(j)}) \Pr(X_i=\alpha|Y^{(k)})$; so one could independently combine the posterior probabilities from each noisy observation. This is not the case for deletion channels since the markov chain $Y^{(j)} - X_i - Y^{(k)}$ no longer holds. More intuitively, one needs to first ``align'' the traces for computing the likelihoods. We point out that the problem considered in 2) asks a question complementary to the trace reconstruction: given a fixed (possibly a few) number of traces, what is our ``best'' guess of $X$? We provide algorithms which do this. Unlike trace reconstruction, we are not concerned with perfect reconstruction (since perfect reconstruction may not be possible with just a few traces), although it should also be obvious that performance guarantees for our algorithms (not a part of this work) would naturally lead to upper bounds for trace reconstruction. Deletion channel by itself is known to be notoriously difficult to analyse. As stated earlier, the capacity of a single deletion channel is still unknown (\cite{diggavi2007capacity,diggavi2006information,diggavi2001transmission}); as are optimal coding schemes. Recent works have looked at the design of codes for deletion channels (\cite{ratzer2005marker,ratzer2000codes,thomas2017polar}); these works consider use of a codebook (we do not). As a result, statistical estimation over deletion channels is also a difficult problem due its highly combinatorial nature. To the best of our knowledge, as yet there are no efficient estimation algorithms over deletion channels with statistical guarantees; not even for ML over a single deletion channel. \noindent \textbf{Biological motivation.} Trace reconstruction in itself was motivated, in part, by problems DNA sequence reconstruction. One such problem was to infer the DNA sequence of a common ancestor from the samples of its descendants. We argue that our problem definition fits more naturally in such a scenario since perfect reconstruction may not be feasible or even possible. Our motivation for considering this problem also comes from a recent DNA sequencing technology called \textit{nanopore sequencing}. The $t$-deletion channel model is a simplistic model to approximately capture the process of a DNA sequence passed through a nanopore sequencer\footnote{As seen in \cite{Mao2017},\cite{MDK17} there are more complicated effects of the nanopore reader not captured in this simple representation.}. Very recently, a variant of the trace reconstruction problem called \textit{coded trace reconstruction} has been proposed, motivated by portable DNA-based data storage systems using DNA nanopores (see \cite{abroshan2019coding}, \cite{cheraghchi2019coded}, \cite{brakensiek2019coded}) and we believe that the ideas in this work may prove useful in such a setting. There are other works on sequence assembly (see for example, \cite{Li09fastand}, \cite{Shomorony2016}), where multiple short reads (from different segments of a sequence) are used to reconstruct the bigger sequence. This work differs from sequence assembly since we are interested to infer the entire length sequence and not just small segments of it (which are then ``stitched'' together in sequence assembly). \noindent \textbf{Tools and techniques.} In terms of theoretical tools, the series of books by Lothaire (\cite{lothaire1997combinatorics,lothaire2002algebraic,lothaire2005applied}) extensively use algebraic tools for problems in the combinatorics of sequences (or \textit{words}), and our work is inspired by such techniques. We borrow many of their notations and results for our work. \noindent \textbf{Contributions.} {\color{red}} Our main contribution is to provide tools to visualize and analyze error events (described in the next section) for the multiple deletion channel model in Fig.~\ref{fig:tdeletion}. We also provide algorithms to solve the problems stated in 1) and 2) earlier in the section. \begin{itemize}[wide=5pt] \item In section~\ref{sec:1deletion}, for the single deletion channel model, we provide an $O(n^2)$ algorithm to calculate the symbolwise posterior probabilities $\Pr(X_i=1|Y)\ \forall\ i$ when $X_i \sim \text{ind. Ber}(p_i)$. \item In Section~\ref{sec:exactsmap}, for the $t$-deletion channel model, we give an $O(2^t n^{t+2})$ algorithm to calculate the symbolwise posterior probabilities $\Pr(X_i = 1|Y_1,...,Y_t)$ when $X_i \sim \text{ind. Ber}(0.5)$. \end{itemize} \section{Notation and Tools} \label{sec:notations} \noindent \textbf{Basic notations:} In this work, we borrow a majority of the notation and tools from \cite{lothaire1997combinatorics} which deals with non-commutative algebra. We restate the definitions here for convenience. Calligraphic letters refer to sets, capitalized letters correspond to random variables and bold letters are used for functions. Let $\mathcal{A}$ be the set of all symbols. Throughout this work, we will focus on the case where $\mathcal{A}=\{0,1\}$, though our methods extend to arbitrarily large sets of finite size. Define $\mathcal{A}^n$ to be the set of all $n$-length sequences and $\mathcal{A}^*$ to be the set of all finite length sequences with symbols in $\mathcal{A}$. For a sequence $f$, $|f|$ denotes the length of $f$. For integers $i,j$, we define $[i:j] \triangleq \{i,i+1,...,j\}$ if $j\geq i$ and $[i:j] \triangleq \emptyset$ otherwise. Also define $[i] \triangleq [1:i]$.\\ \noindent \textbf{Binomial coefficient:} Given sequences $f$ and $g$ in $\mathcal{A}^*$, the number of subsequence patterns of $f$ that are equal to $g$ is called the \textit{binomial coefficient} of $g$ in $f$ and is denoted by $f \choose g$. For example, ${'apple' \choose 'ape'} = 2$ since $'ape'$ can be obtained from two (overlapping) subsequences of $'apple'$. When the alphabet $\mathcal{A}$ is of cardinality 1, ${f \choose g} = {|f| \choose |g|}$, the classical binomial coefficient with their respective lengths as the parameters. This definition hence could be thought of as a generalization of the classical binomial coefficients. We will denote by $e$ the sequence of length 0, and {define ${f \choose e} \triangleq 1\ \forall\ f\ \in\ \mathcal{A}^*$.} We also define the classical binomial coefficient ${a \choose b}\triangleq 0,$ whenever $b>a$ or $b<0$ for ease of use. The binomial coefficient is an integral aspect of this work and for analyzing error events in deletion channels because the input-output relation for a deletion channel (with deletion probability $\delta$, input $X$ and output $Y$) can be expressed as \begin{equation} \label{eq:in-out_relation} \Pr(Y=y|X=x) = {x \choose y} \delta^{|x|-|y|} (1-\delta)^{|y|}. \end{equation} The proof is straight-forward -- the number of distinct error events that give rise to $y$ from $x$ is exactly the number of subsequences of $x$ which are equal to $y$. Each of these error events has a probability $\delta^{|x|-|y|} (1-\delta)^{|y|}$, wherein the exponent of $\delta$ corresponds to the deleted symbols and the exponent of $1-\delta$ to the undeleted symbols. Given the definition of the binomial coefficient, the maximum-likelihood (ML) estimate over a deletion channel with observed output $Y$ can be cast in the following form: \begin{align*} \argmax_{x \in \mathcal C} {x \choose Y},\numberthis \label{eq:ML_deletion} \end{align*} where $\mathcal C$ is the chosen codebook. In the case of multiple deletion channels with observed traces $Y^{(1)},...,Y^{(t)}$, the ML formulation is similar: \begin{align*} \argmax_{x \in \mathcal C} \prod_{j=1}^{t} {x \choose Y^{(j)}}.\numberthis \label{eq:ML_multiple_deletion} \end{align*} As yet, there is no known efficient way to come up with a solution for the above two formulations, even for \eqref{eq:ML_deletion} with $\mathcal C = \{0,1\}^n$ (see \cite{mitzenmacher2009survey}). In this work, we attempt to take a step in this direction by showing that a continuous relaxation of \eqref{eq:ML_deletion} is equivalent to \eqref{eq:ML_deletion}. However, an efficient algorithm to solve the optimization \eqref{eq:ML_deletion} remains open. In the context of trace reconstruction, the ultimate pursuit would be an algorithm for \eqref{eq:ML_multiple_deletion} with $\mathcal C = \{0,1\}^n$ and error analysis thereof. \noindent We now describe a function which can be thought of as a real-valued extension of the binomial coefficient. This function is used in sections~\ref{sec:1deletion_ML} and \ref{sec:1deletion}. Consider the function $\mathbf F(\cdot)$ defined as: \begin{definition} \label{def:f} \begin{align*} &\mathbf F: \mathbb{R}^k \times \{0,1\}^l \rightarrow \mathbb{R},\\ \mathbf F(q, v)\triangleq &\begin{cases} \sum\limits_{\substack{\mathcal S|\mathcal S\subseteq [k],\\|\mathcal S|=l}} \quad \prod\limits_{i=1}^l q_{\mathcal S_i}^{v_i} (1-q_{\mathcal S_i})^{1-v_i} & 1 \leq l\leq k \\ 1 & 0=l\leq k \\ 0 & \text{else}. \end{cases} \end{align*} \noindent An alternate definition is as follows: consider a random vector $Z\in\{0,1\}^k$ such that $Z_i\sim$ ind. Ber$(q_i)$, let $q$ be the vector of probabilities of length $k$, $\mathcal S\subseteq [k]$ a subset of the indices of size $l$, and ${v}$ a binary vector of length $l$. Then, $$\mathbf F(q,v)=\sum_{\substack{\mathcal S||\mathcal S|=l}} \Pr(Z_{\mathcal S}= v).$$ Note that if $q$ is a vector of $0$'s and $1$'s, then $\mathbf F( q, v)={q \choose v}$, the binomial coefficient of $v$ in $q$. Thus, $\mathbf F(\cdot)$ could be interpreted as an extension of the binomial coefficient where one of the parameters can take values in $[0,1]^n$ instead of $\{0,1\}^n$. \end{definition} Though at first sight, $\mathbf F(q,v)$ sums over an exponential number of subsets, a dynamic programming approach can be used to compute it in $O(|v|^2)$ time complexity. The dynamic program is described in section~\ref{sec:1deletion}. \iffalse \noindent \textbf{Edit distance:} The edit distance $d_e(f,g)$ measures similarity between two sequences of possibly different lengths \cite{Navarro2001}. $d_e(f,g)$ is the minimum number of operations needed to transform $f$ to $g$, where the permitted operations are insertion, deletion or substitution of a symbol. In this work, we quantify the performance of algorithms in Section \ref{sec:Numerics} using the edit distance metric. \fi The following definitions and ideas are relevant only for \ref{sec:exactsmap} and can be omitted for the sections on single deletion channel. Before getting to the mathematical definitions, we first state a result of ours that aids in thinking about error events in multiple deletion channels. \subsection{An alternate interpretation of multiple deletion channel model} The events occurring in the $t$-deletion channel model can be categorized into two groups: \begin{enumerate} \item an input symbol is deleted in \textit{all} the $t$-traces, \item an input symbol is reflected in at least one of the traces. \end{enumerate} The error events of the first kind are in some sense ``not correctable" or even ``detectable" since it is impossible to tell what and where the deleted symbol could have been (although the probabilities need not be uniform). The events of the second kind, however, can still be detected although they could likely be confused with a large set of similar events. This thought process gives rise to a natural decomposition of the $t$-deletion channel model into a cascade of two channels: the first one being a deletion channel which captures error events of the first kind and the second one is what we call the \textit{remnant channel} which captures events of the second kind (see Fig.~\ref{fig:channel_equiv}). More precisely, the remnant channel is defined as follows: \begin{definition} \textit{Remnant channel:} an input symbol to the remnant channel is reflected in $k>0$ given outputs and deleted in the rest with a probability $\frac{\delta^{t-k}(1-\delta)^k}{1-\delta^t}$. \end{definition} It is easy to note that probability of the union of all possible events here is $\sum_{k=1}^t {t \choose k} \frac{\delta^{t-k}(1-\delta)^k}{1-\delta^t}=1$, validating our definition. \begin{restatable}{theorem}{channelequiv} \label{thm:channel_equiv} The $t$-deletion channel model and the cascade of the deletion channel with remnant channel shown in Fig.~\ref{fig:channel_equiv} are probabilistically equivalent, i.e., $$\Pr({Y}^{(1)},{Y}^{(2)},...,{Y}^{(t)}|X = x) = \Pr(\tilde{Y}^{(1)},\tilde{Y}^{(2)},...,\tilde{Y}^{(t)}|X = x).$$ \end{restatable} The formal proof of the theorem requires few more definitions and is relegated to the appendix. \begin{figure}[!h] \begin{center} \includegraphics[scale=0.4]{channel_equiv.pdf} \caption{A channel equivalence result: the $t$-deletion channel model in (a) is probabilistically equivalent to the the cascade of a deletion channel with the \textit{remnant channel} ($ \mathcal C_2$) in (b).} \label{fig:channel_equiv} \end{center} \end{figure} \noindent\textbf{Edit graph} (as defined in \cite{Gusfield1997}): We now define a graph construct which is closely related to the error events in the remnant channel. We start with a simple case and generalize subsequently. Define an \textit{edit graph} given two sequences $f$ and $g$, where every path connecting the ``origin'' to the ``destination'' on the edit graph yields a supersequence $h$ of $f,g$, where $h$ is ``covered'' by $f,g$ -- i.e., each symbol of $h$ comes from either $f$ or $g$ or both. In other words, given that $f$ and $g$ are the outputs of the remnant channel (with two outputs), each path from the origin of the edit graph to the destination corresponds to a possible input $h$ to the remnant channel and to an error event which resulted in $f$ and $g$ with input $h$. For $f$ and $g$ in $\mathcal A^*$, we form a graph $\mathcal{G}(f,g)$ with $(|f|+1)(|g|+1)$ vertices each labelled with a distinct pair $(i,j), 0\leq i\leq |f|,\ 0\leq j\leq |g|$. A directed edge $(i_1,j_1)\rightarrow(i_2,j_2)$ exists iff at least one of the following holds: \begin{enumerate} \item$i_2-i_1=1$ and $j_1=j_2$, or \item $j_2-j_1=1$ and $i_1=i_2$, or \item $i_2-i_1=1$, $j_2-j_1=1$ and $f_{i_2}=g_{j_2}$, \end{enumerate} where $f_i$ is the $i^{th}$ symbol of the sequence $f$. The origin is the vertex $(0,0)$ and the destination $(|f|,|g|)$. \begin{figure}[!h] \centering \includegraphics[scale=0.25]{editgraph_smap1.pdf} \caption{ Edit graph for sequences $f=$ `001' and $g=$ `101'. An easy way to think about this is to write down $f$ vertically with each symbol aligned to a vertical set of edges and $g$ horizontally likewise. A diagonal edge in a small square exists if the corresponding $f$ and $g$ symbols are equal. The thick red edges form a path from the origin to the destination; this path corresponds to the sequence `0101' -- append the corresponding symbol at the left of an edge if it's vertical or diagonal, otherwise append the symbol at the top. It is also easy to verify that 0101 is a supersequence of both $f$ and $g$, and could be obtained as a covering of $f$ and $g$; the path itself gives one such covering. This covering also corresponds to an error event in the remnant channel which would result in outputs $f$ and $g$ with input $h=$ `0101' -- more precisely, the error event is one in which the first symbol of $h$ is deleted only in $g$, the second symbol is deleted only in $f$ and the third and fourth symbols not deleted in either $f$ or $g$.} \label{fig:editgraph_smap1} \end{figure} Let $p=((i_1,j_1),(i_2,j_2),...,(i_m,j_m))$ be a path in $\mathcal{G}(f,g)$. We define $ s(p)$ to be the sequence corresponding to the path. Intuitively, $s(p)$ is formed by appending symbols in the following way: append the corresponding $f$ symbol for a vertical edge, $g$ symbol for horizontal edge, and $f$ or $g$ symbol for diagonal edge (see example Fig.~\ref{fig:editgraph_smap1}). Any path from $(0,0)$ to $(|f|,|g|)$ corresponds to a supersequence of $f$ and $g$ and which is ``covered" by $f$ and $g$. More formally, define $ s(p)\triangleq x_1x_2...x_{m-1}$ where $$x_k = \begin{cases} f_{i_{k+1}} \quad\text{if }j_{k}=j_{k+1},\\ g_{j_{k+1}} \quad\text{if }i_{k}=i_{k+1},\\ f_{i_{k+1}} \quad\text{else.} \end{cases} $$ The construct of edit graph can be extended to more than 2 sequences with the same idea. For sequences $f_1,f_2,...,f_t$, construct a $t$-dimensional grid with a number of vertices $(|f_1|+1)(|f_2|+1)...(|f_t|+1)$ labeled from $(0,0,...,0)$ to $(|f_1|,|f_2|,...,|f_t|)$. A vertex $u=(i_1,i_2,...,i_t)$ is connected to $v=(j_1,j_2,...,j_t)$ (we say $u \rightarrow v$) iff both of the following conditions are met: \begin{itemize} \item $j_l=i_l$ or $j_l=i_l+1$ $\forall\ l\in [t]$, i.e., $(i_1,...,i_t)$ and $(j_1,...,j_t)$ are vertices of a particular unit cube. Only these type of vertices can share an edge in the grid graph. \item Let $\mathcal T \subseteq [t]$ be the collection of indices where $j_l=i_l+1$. Then $f_{i_l}$ is same $\forall\ l \in \mathcal T$. For instance, if $\mathcal T=\{1,3,5\}$, then $f_{i_1}=f_{i_3}=f_{i_5}$. \end{itemize} Define the vertex $(0,...,0)$ to be the origin of this graph and the vertex $(|f_1|,...,|f_t|)$ to be the destination. If $|f_j|=O(n)\ \forall\ j$, this graph has a number of vertices $O(n^t)$ and a maximum number of edges $O((2n)^t)$ since each vertex has at most $2^t$ outgoing edges.\\ \noindent\textbf{Infiltration product} (introduced in \cite{lothaire1997combinatorics}): The infiltration product has been extensively used in \cite{lothaire1997combinatorics}, as a tool in non-commutative algebra. Here we give an edit-graph interpretation of this tool. We also give a formal definition later in this section. Using the edit graph we can construct the set of possible supersequences $\mathcal{S}(f,g)$ of $f,g$ which are covered by it. Clearly multiple paths could yield the same supersequence and we can count the number of distinct ways $\mathbf N(h;f,g)$ one can construct the same supersequence $h$ from $f,g$. We can informally define the \emph{infiltration product $f\uparrow g$} of $f$ and $g$, as a polynomial with monomials the supersequences $h$ in $\mathcal{S}(f,g)$ and coefficients $\langle f\uparrow g,h\rangle$ equal to $\mathbf N(h;f,g)$. In Fig.~\ref{fig:editgraph_smap1}, it is easy to verify that there is exactly one path corresponding to `101001' and hence $\langle 001\uparrow 101,101001 \rangle=1$ and similarly $\langle 001\uparrow 101,01001 \rangle=2$. One could find these coefficients for all relevant sequences and form the polynomial as described. More examples: Let $\mathcal{A}=\{a,b\}$, then \begin{itemize}[wide=2pt] \item $ab\uparrow ab=ab+2aab+2abb+4aabb+2abab$, \item $ab\uparrow ba=aba+bab+abab+2abba+2baab+baba.$ \end{itemize} The infiltration operation is commutative and associative, and infiltration of two sequences $f\uparrow g$ is a polynomial with variables of length (or \textit{degree}) at most $|f|+|g|$; see \cite{lothaire1997combinatorics}. The definition of infiltration extends to two polynomials via distributivity (precisely defined in later), and consequently to multiple sequences as well. For multiple sequences, infiltration has the same edit graph interpretation: $\langle f_1\uparrow f_2 \uparrow...\uparrow f_t, w \rangle$ is the number of distinct ways of constructing $w$ as a supersequence of $f_1, f_2, ... ,f_t$ so that the construction covers $w$, i.e., construct the $t$-dimensional edit graph of $f_1, f_2, ... ,f_t$ and count the number of paths corresponding to $w$. \subsection{Formal definition of infiltration product} We now give a more formal definition of the infiltration product (see \cite{lothaire1997combinatorics} for the equivalence of the two definitions and a more rigorous treatment). A \textit{formal series} with indeterminates (or variables) in a set $\mathcal A$ and coefficients in a commutative ring $\mathcal R$, is a mapping of $\mathcal A^*$ onto $\mathcal R$. Recall that a commutative ring is a set which forms an abelian group under an \textit{addition} operation, is a monoid under a \textit{multiplication} operation which commutes, and the multiplication operation distributes over addition. Here we consider $\mathbb Z$, the set of integers as the commutative ring $\mathcal{R}$. A formal series is called a \textit{polynomial} if only a finite number of sequences are mapped to non-zero values, the rest of the sequences map to zero. Consider two polynomials $\sigma,\tau: \mathcal{A}^*\rightarrow \mathbb Z$. The value taken by a sequence $w\in \mathcal A^*$ on $\sigma$ (or the coefficient of $w$ in $\sigma$) is denoted by $\langle \sigma,w\rangle \in \mathbb R$. We also define binary addition ($\oplus$) and multiplication operations ($\times$) on the set of polynomials as follows: \begin{align} \langle \sigma\oplus \tau,w\rangle \triangleq \langle \sigma,w\rangle + \langle \tau,w \rangle \quad \forall w\in \mathcal A^*,\label{eq:polynomial_add}\\ \langle \sigma\times \tau,w\rangle \triangleq \sum_{\substack{f,g\in \mathcal A^*:\\ f.g=w}}\langle \sigma,f\rangle \langle \tau,g \rangle \quad \forall w\in \mathcal A^*.\label{eq:polynomial_prod} \end{align} We will use the usual symbols $+$ and $.$ in place of $\oplus$ and $\times$ in this work for convenience. The meaning of the operation would be clear depending on the operands. With these operations the set of polynomials form a non-commutative ring, and is denoted by $\mathbb Z\langle\mathcal A \rangle$, also called the free $\mathbb Z$-algebra on $\mathcal A$ in ring theory. Note that the addition and multiplication operations defined in \eqref{eq:polynomial_add} and \eqref{eq:polynomial_prod} are similar to the operations defined on commutative polynomials, except that the multiplication operation under the summation in \eqref{eq:polynomial_prod} ($f.g=w$) is actually concatenation and is non-commutative. The multiplication inside the summation in \eqref{eq:polynomial_prod} is multiplication in the real field and hence commutative. It is also easy to prove that the multiplication defined in \eqref{eq:polynomial_prod} distributes over addition defined in \eqref{eq:polynomial_add}. Thus, a polynomial in $\mathbb Z\langle\mathcal A \rangle$ can be represented as a sum of monomials in $\mathcal A^*$ each with an associated coefficient in $\mathbb Z$, i.e., $\sigma=\sum\limits_{w\in \mathcal A^*} \langle\sigma,w \rangle w$. Define the \textit{degree} of a polynomial to be equal to the length of a longest sequence with a non-zero coefficient in the polynomial and the \textit{number of terms} of a polynomial as the number of sequences with non-zero coefficients in the polynomial. Note that a degree $d$ polynomial could have a number of terms upto $2^{d+1}-1$. With this, the \textit{infiltration product} (in general, for two polynomials) is defined as follows: \begin{align} \forall f\in \mathcal{A}^*,& \quad f\uparrow e = e\uparrow f=f.\nonumber \\ \forall f,g\in \mathcal{A}^*&,\quad \forall a,b\in \mathcal{A}, \nonumber\\ fa\uparrow gb=(f\uparrow gb)a&+(fa\uparrow g)b+\mathbbm{1}_{a=b}(f\uparrow g)a.\nonumber \\ \forall \sigma,\tau \in \mathbb{Z}\langle\mathcal{A} \rangle, \quad &\sigma\uparrow \tau=\sum_{f,g\in \mathcal{A}^*} \langle \sigma,f \rangle \langle \tau,g \rangle (f\uparrow g). \label{def:infiltforseq} \end{align} \textbf{Summary of definitions and ideas introduced in this section:} \begin{itemize} \item The binomial coefficient captures the likelihood of observations for deletion channels. \item An extension of the binomial coefficient function where one of the parameters can take real values has been introduced; this function is pivotal for our results on the single-trace deletion channel. \item For multiple deletion channels, the error events can be categorized into two groups -- one where an input symbol is deleted in all the traces, and second, the complement of this event. This categorization results in a natural decomposition of multiple deletion channel model into a cascade model involving the remnant channel. \item The remnant channel disregards the error events where a symbol is deleted in all the traces. \item The edit graph provides a way to visualize all the possible error events and input sequences to a remnant channel given its outputs. \item The infiltration product serves the same purpose as the edit graph, but has an algebraic flavor and provides rigor for proofs and analyses. The edit graph, on the other hand, is more helpful in designing reconstruction algorithms over deletion channels. \end{itemize} \section{Maximum likelihood for the single-trace deletion channel} \label{sec:1deletion_ML} Consider the ML formulation for the single-trace deletion channel given non-empty trace $Y$ and all possible $n$-length inputs allowed, restated here for convenience: \begin{equation} \argmax_{x\in \{0,1\}^n} {x \choose Y}. \label{eq:1deletion_ML} \end{equation} To the best of our knowledge, the only known method to solve \eqref{eq:1deletion_ML} involves iterating over all possible choices of $x$ and computing the objective value for each of the choices. We here show that it is sufficient to solve a continuous relaxation of above problem to obtain a solution to \eqref{eq:1deletion_ML}. Note that there could be multiple solutions to \eqref{eq:1deletion_ML}. Before going in the main result, we first state a useful lemma which factors out a given coordinate $p_i$ out of $\mathbf F(p,Y)$. The proof of the lemma is relegated to the appendix. \begin{restatable}{lemma}{deletionMLrellemma} For $p=[p_1,p_2,..,p_i,...,p_n]$ and $Y=Y_1Y_2...Y_m$ with $n \geq m > 0$, we have \begin{align*} \mathbf F(p,Y) = \mathbf F( p_{[n]\backslash \{i\}},Y) + p_i \sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]})\\ + (1-p_i) \sum\limits_{k|Y_k=0}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}). \end{align*} \label{lemma:F_decomposition} \end{restatable} \begin{theorem} An alternative optimization to characterize ML for the single-trace deletion channel. \begin{equation} \max_{x\in \{0,1\}^n} {x \choose Y} = \max_{p\in [0,1]^n} \mathbf F(p,Y). \label{eq:ml_opt_equiv} \end{equation} Furthermore, given any non-integral $p^* \in [0,1]^n$ that maximizes $\mathbf F(p,Y)$, one could construct a corresponding integral solution $x^* \in \{0,1\}^n$ that maximizes $\mathbf F(p,Y)$ and consequently is also a solution to $\max_{x\in \{0,1\}^n} {x \choose Y}$. \end{theorem} \begin{proof} As noted earlier, we have ${x \choose Y} = \mathbf F(x,Y)$. Therefore, we are interested in proving the following: \begin{align*} \max_{x\in \{0,1\}^n} \mathbf F(x,Y) \equiv \max_{p\in [0,1]^n} \mathbf F(p,Y).\numberthis \label{eq:ml_opt_equiv_proof1} \end{align*} To show this and also the second statement, we prove that given $p=(p_1,p_2,...,p_i,...,p_n)$, at least one of the following holds true: \begin{itemize} \item$\mathbf F(p^{(i\rightarrow 0)},Y) \geq \mathbf F(p,Y)$, where $p^{(i\rightarrow 0)}=(p_1,p_2,...,p_{i-1},0,p_{i+1}...,p_n)$ is the vector where the $i^{th}$ coordinate is replaced by 0. \item $\mathbf F(p^{(i\rightarrow 1)},Y) \geq \mathbf F(p,Y)$, where $p^{(i\rightarrow 0)}=(p_1,p_2,...,p_{i-1},1,p_{i+1}...,p_n)$ is the vector where the $i^{th}$ coordinate is replaced by 1. \end{itemize} Thus if $p^*$ is an optimal solution to $\max_{p\in [0,1]^n} \mathbf F(p,Y)$ with $p_i\in (0,1)$, then at least one of $p^{(i\rightarrow 0)}$ or $p^{(i\rightarrow 1)}$ is also an optimal solution. Sequentially applying this argument for each coordinate of $p$ shows that there exists a point in $\{0,1\}^n$ which is also an optimal solution to $\max_{p\in [0,1]^n} \mathbf F(p,Y)$ and consequently to $\max_{x\in \{0,1\}^n} \mathbf F(x,Y)$. Now to prove our claim, we use Lemma~\ref{lemma:F_decomposition} to factor out $p_i$ terms in $\mathbf F(p,Y)$: \begin{align*} \mathbf F(p,Y) = \mathbf F( p_{[n]\backslash \{i\}},Y) + p_i \sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]})\\ + (1-p_i) \sum\limits_{k|Y_k=0}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}). \end{align*} There are 3 cases \begin{enumerate} \item $$\sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}) = \sum\limits_{k|Y_k=0}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}).$$ \\In this case it is easy to verify that $\mathbf F(p^{(i\rightarrow 0)},Y) = \mathbf F(p,Y) = \mathbf F(p^{(i\rightarrow 1)},Y).$ \item $$\sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}) > \sum\limits_{k|Y_k=0}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}).$$ \\In this case it is easy to verify that $\mathbf F(p^{(i\rightarrow 0)},Y) \leq \mathbf F(p,Y) \leq \mathbf F(p^{(i\rightarrow 1)},Y).$ \item $$\sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}) < \sum\limits_{k|Y_k=0}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}).$$ \\In this case it is easy to verify that $\mathbf F(p^{(i\rightarrow 0)},Y) \geq \mathbf F(p,Y) \geq \mathbf F(p^{(i\rightarrow 1)},Y).$ \end{enumerate} Thus in each of the 3 cases, we see that at least one of $\mathbf F(p^{(i\rightarrow 0)},Y)$ or $\mathbf F(p^{(i\rightarrow 1)},Y)$ is at least as large as $\mathbf F(p,Y)$ thus proving the theorem. Note that the proof gives a natural way to find an optimal lattice point $p_{lattice}^*$ given a non-lattice point $p^*$ by iterating through each coordinate of $p^*$ and switching them to $0$ or $1$ by comparing $\sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]})$ with $\sum\limits_{k|Y_k=0}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}).$ \end{proof} \section{Symbolwise posterior probabilities for the single-trace deletion channel} \label{sec:1deletion} We here develop an algorithm to compute the symbolwise posterior probabilities for the single-trace deletion channel when the input symbols are independently generated with arbitrary priors. Consider the single deletion channel model in Fig.~\ref{fig:1deletion}, where $X=X_1...X_n$, each input symbol is generated $X_i \sim \text{ind. Ber}\ (p_i)$, and we observe at the output the trace $Y = Y_1Y_2...Y_m$ with $m\leq n$. Define the vector of priors as $p\triangleq(p_1,p_2,...,p_n)$. We first give an $O(n^2)$ algorithm to calculate the posterior probabilities $\Pr(X_i=1|Y)$, which in turn provides the symbolwise MAP estimate for the considered model. We then show how this algorithm can be used for trace reconstruction. We take three steps to present the algorithm. \noindent \textbf{An expression for $\Pr(X_i=1|Y)$.} Let $\Pr(X_i=1)=p_i$. As a first step, we have \vspace{6pt} \begin{align*} \Pr(X_i=1|{Y}) &= \frac{\Pr(X_i=1,Y)}{\Pr(Y)} = \frac{ \sum\limits_{\substack{ x| x_i=1}} \Pr({X=x}) \Pr(Y|X=x)}{ \sum_{\substack{x}} \Pr({X=x}) \Pr(Y|X=x)} \\ &\overset{(a)}{=} \frac{ \sum\limits_{\substack{ x| x_i=1}} \Pr({X=x}) { x \choose Y}}{ \sum_{\substack{x}} \Pr({X=x}) { x \choose Y}}, \numberthis \label{eq:approx_smap_1} \end{align*} where $(a)$ is because for a deletion channel $\Pr(Y|X=x)={x \choose Y} \delta^{|x|-|Y|}(1-\delta)^{|Y|}$. To proceed, we need to evaluate the summation in the numerator and the denominator. Theorem~\ref{thm:approx_smap_postprob} expresses \eqref{eq:approx_smap_1} in terms of relaxed binomial coefficient terms $\mathbf F(\cdot)$. Recall one way to define $\mathbf F(p,Y) \triangleq \mathbb E_{X\sim p} {X \choose Y}$, which is the denominator term in \eqref{eq:approx_smap_1}. \begin{theorem} \label{thm:approx_smap_postprob} Let $X=X_1...X_n$ where $X_i \sim \text{ind. Ber}\ (p_i)$, and let $Y$ be the observed trace when $X$ is passed through a deletion channel. Then, \begin{align*} \Pr(X_i&=1|{Y}) = \frac{p_i}{\mathbf F( p, Y)} \left( \mathbf F( p_{[n]\backslash \{i\}}, Y) + \sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}) \right) \numberthis \label{eq:smap_postprob_thm} \end{align*} where $\mathbf F(\cdot)$ is as given in Definition~\ref{def:f}. \end{theorem} \begin{proof} The proof of this theorem employs the same trick used in the proof of Lemma~\ref{lemma:F_decomposition}. Let $|Y|=m$. From \eqref{eq:approx_smap_1} \begin{align*} \Pr(X_i = 1 | Y) = \frac{ \sum\limits_{\substack{ x| x_i=1}} \Pr({X=x}) { x \choose Y}}{\mathbf F(p,Y)}. \end{align*} Now, \begin{align*} \sum_{\substack{ x| x_i=1}} & \Pr({X=x}) { x \choose Y} =\sum_{\substack{ x|x_i=1}} \Pr({X=x}) \sum_{\substack{\mathcal S\subseteq [n]\\ |\mathcal S|=m}} \mathbbm{1}\{ x_{\mathcal S}= Y\}\\ &=\sum_{\substack{\mathcal S\subseteq [n]\\ |\mathcal S|=m}} \sum_{\substack{ x|x_i=1\\x_{\mathcal S}=Y}} \Pr({X=x}).\numberthis \label{eq:smapiter1} \end{align*} We first separate the outer summation into two cases: (a) $\mathcal S|i \notin \mathcal S$ and (b) $\mathcal S|i\in \mathcal S$. We can express the first case as \begin{align*} &\hspace{-1cm}\sum_{\substack{\mathcal S\subseteq [n] \\ |\mathcal S|=m,i\notin \mathcal S}}\sum_{\substack{ x|x_i=1\\x_{\mathcal S}=Y}} \Pr({X=x}) =\sum_{\substack{\mathcal S\subseteq [n]\backslash \{i\}\\ |\mathcal S|=m}} \sum_{\substack{ x|x_i=1\\x_{\mathcal S}=Y}} \Pr({X=x})\\ &=\sum_{\substack{S\subseteq [n]\backslash \{i\}\\ |\mathcal S|=m}} \sum_{\substack{ x|x_i=1\\ x_{\mathcal S}= Y}} \Big(\Pr(X_i=1)\Pr( X_{\mathcal S}= Y) \Pr( X_{[n]\backslash \mathcal S\cup\{i\}}= x_{[n]\backslash \mathcal S\cup\{i\}}) \Big)\\ &=\sum_{\substack{\mathcal S\subseteq [n]\backslash \{i\}\\ |\mathcal S|=m}} p_i \Pr( X_{\mathcal S}= Y) \left(\sum_{\substack{ x|x_i=1\\ x_{\mathcal S}= Y}} \Pr( X_{[n]\backslash \mathcal S\cup\{i\}}= x_{[n]\backslash \mathcal S\cup\{i\}})\right)\\ &=\sum_{\substack{\mathcal S\subseteq [n]\backslash \{i\}\\ |\mathcal S|=m}} p_i \Pr( X_{\mathcal S}= Y) \left(\sum_{(x_j|j\in [n]\backslash \mathcal S\cup \{i\})} \Pr( X_{[n]\backslash \mathcal S\cup\{i\}}= x_{[n]\backslash \mathcal S\cup\{i\}})\right)\\ &=p_i \sum_{\substack{\mathcal S\subseteq [n]\backslash \{i\}\\ |\mathcal S|=m}} \Pr( X_{\mathcal S}= Y) = p_i \mathbf F( p_{[n]\backslash \{i\}}, Y).\numberthis \label{eq:lemma3proof1} \end{align*} For the second term, we express the set $\mathcal S$ as a union $\mathcal S = \mathcal S' \cup \{i\} \cup \mathcal S''$ such that $\mathcal S' \subseteq [i-1]$ and $\mathcal S'' \subseteq [i+1:n]$ to get: \begin{align*} &\sum_{\substack{\mathcal S\subseteq [n]\\ |\mathcal S|=m,\\i\in \mathcal S}} \sum_{\substack{ x|x_i=1\\x_{\mathcal S}=Y}} \Pr({X=x})= \sum_{k=1}^m\sum\limits_{\substack{\mathcal S\subseteq [n],\\|\mathcal S|=m,\\ \mathcal S_k = i}} \sum_{\substack{ x|x_i=1\\x_{\mathcal S}=Y}} \Pr({X=x})\\ &=\sum_{k=1}^m\sum_{\substack{\mathcal S'\subseteq [i-1]\\ |\mathcal S'|=k-1}}\sum_{\substack{\mathcal S''\subseteq [i+1:n]\\ |\mathcal S''|=m-k}} \sum_{\substack{ x|x_i=1\\x_{\mathcal S}=Y}}\mathbbm{1}_{\{Y_k=1\}} \Pr({X=x}) \\ &=\sum_{k:Y_k=1}\sum_{\substack{\mathcal S'\subseteq [i-1]\\ |\mathcal S'|=k-1}}\sum_{\substack{\mathcal S''\subseteq [i+1:n]\\ |\mathcal S''|=m-k}} \sum_{\substack{ x|x_i=1\\ x_{\mathcal S'}= Y_{[1:k-1]}\\ x_{\mathcal S''}= Y_{[k+1:m]}}} \Bigg ( \Pr(X_i=1) \Pr( X_{\mathcal S'}= Y_{[1:k-1]}) \Pr( X_{\mathcal S''}= Y_{[k+1:m]}) \\&\hspace{7cm} \Pr( X_{[n]\backslash \mathcal S'\cup \mathcal S''\cup \{i\}}= x_{[n]\backslash \mathcal S'\cup \mathcal S'' \cup\{i\}})\Bigg )\\ &=p_i\sum_{k:Y_k=1}\Bigg ( \Big( \sum_{\substack{\mathcal S'\subseteq [i-1]\\ |\mathcal S'|=k-1}}\Pr( X_{\mathcal S'}= Y_{[1:k-1]})\Big) \Big(\sum_{\substack{\mathcal S''\subseteq [i+1:n]\\ |\mathcal S''|=m-k}}\Pr( X_{\mathcal S''}= Y_{[k+1:m]})\Big ) \\ & \hspace{5cm} \Big( \sum_{\substack{ x|x_i=1\\ x_{\mathcal S'}= Y_{[1:k-1]}\\ x_{\mathcal S''}= Y_{[k+1:m]}}} \Pr( X_{[n]\backslash \mathcal S'\cup \mathcal S''\cup \{i\}}= x_{[n]\backslash \mathcal S'\cup \mathcal S'' \cup\{i\}})\Big) \Bigg )\\ &=p_i\sum_{k|Y_k=1}\Bigg(\Big( \sum_{\substack{\mathcal S'\subseteq [i-1]\\ |\mathcal S'|=k-1}}\Pr( X_{\mathcal S'}= Y_{[1:k-1]})\Big) \Big( \sum_{\substack{\mathcal S''\subseteq [i+1:n]\\ |\mathcal S''|=m-k}}\Pr( X_{\mathcal S''}= Y_{[k+1:m]}) \Big)\Bigg)\\ &=p_i \sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}). \numberthis \label{eq:lemma3proof2} \end{align*} Plugging in \eqref{eq:lemma3proof1} and \eqref{eq:lemma3proof2} in \eqref{eq:approx_smap_1} proves the theorem. \end{proof} Alg.~\ref{alg:apprx_smap_dp} summarizes the computation of $\Pr(X_i=1|Y)$. The complexity of the algorithm is $O(n^2)$ which is also the complexity of computing $\mathbf F(p,Y)$; note that $m=O(n)$ since $Y$ is a deleted version of the input. \begin{algorithm}[t!] \caption{Symbolwise posterior probabilities with one trace}\label{alg:apprx_smap_dp} \begin{algorithmic}[1] \item Input: Trace {$Y$}, priors $p$\\ Outputs: Posteriors $\Pr(X_i=1|Y)\ \forall\ i$ \State Compute $\mathbf F(p_{[1:k]},Y_{[1:j]})\ \forall\ k,j$ and $\mathbf F(p_{[k:n]},Y_{[j:m]})\ \forall\ k,j$ via Alg.~\ref{alg:F_comp} \For {$i=1:n$} \State Use \eqref{eq:smap_postprob_thm} to compute $\Pr(X_i=1|Y)$ \EndFor \end{algorithmic} \end{algorithm} \noindent\textbf{A trace reconstruction heuristic with $t$ traces.} The posterior probability computation in Alg.~\ref{alg:apprx_smap_dp} naturally gives rise to a trace reconstruction heuristic that updates the symbolwise statistics sequentially on the traces, where we use Alg.~\ref{alg:apprx_smap_dp} with one trace at a time to continually update $\Pr(X_i=1|Y)$. The overall heuristic is described in Alg.~\ref{alg:apprx_smap}. The complexity of the algorithm is $O(tn^2)$ since Alg.~\ref{alg:apprx_smap} amounts to just $t$ uses of Alg.~\ref{alg:apprx_smap_dp}. \begin{algorithm}[t!] \caption{Trace reconstruction via iterative single-trace posterior probabilities}\label{alg:apprx_smap} \begin{algorithmic}[1] \item Input: Traces {$Y^{(1)},...,Y^{(t)}$}, input length $n$ \\ Outputs: Estimate of the input $\hat X$ \State Initialize priors $p^{old}=p^{new} \gets (0.5,0.5,...,0.5)$ \For {$l=1:t$} \State Use Alg.~\ref{alg:apprx_smap_dp} with $p^{old}$ and $Y^{(l)}$ to update $p^{new}$ \State $p^{old}\gets p^{new}$ \EndFor \For {$i=1:n$} \If {$p^{new}_i\geq 0.5$} $\ \hat X_i \gets 1$ \Else $\ \hat X_i \gets 0$ \EndIf \EndFor \State \textbf{return} $\hat X_1 \hat X_2 ... \hat X_n$ \end{algorithmic} \end{algorithm} \section{On Maximum Likelihood Decoding For The Single-Trace Deletion Channel} \label{sec:1deletion_ML} We here consider the single-trace ML decoding in (\ref{eq:ML_deletion}), assuming that the output sequence $Y$ is non-empty. To the best of our knowledge, the only known method to solve \eqref{eq:ML_deletion} involves solving a combinatorial optimization, essentially iterating over all possible choices of $x$ and computing the objective value for each of the choices. We here show that one could equivalently solve the continuous relaxation of \eqref{eq:ML_deletion} to obtain a solution of \eqref{eq:ML_deletion}. Before presenting the main result, we first state a useful lemma which factors a given coordinate $p_i$ out of the relaxed binomial coefficient $\mathbf F(p,Y)$ we introduced in Definition~\ref{def:f}. \begin{restatable}{lemma}{deletionMLrellemma} For $p=(p_1,p_2,..,p_i,...,p_n)$ and $Y=Y_1Y_2...Y_m$ with $n \geq m > 0$, we have \begin{align*} \mathbf F(p,Y) = \mathbf F( p_{ [n]\backslash \{i\}},Y) + p_i \sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]})\\ + (1-p_i) \sum\limits_{k|Y_k=0}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}). \end{align*} \label{lemma:F_decomposition} \end{restatable} Recall that $\mathbf F(p,Y)$ sums over all $m$-length subsets $\mathcal S$ and associates $p_{\mathcal S}$ with $Y.$ Intuitively, this recursive relationship considers separately the cases where \begin{itemize} \item $i \notin \mathcal S$, \item $i \in \mathcal S$ and is associated with a particular $Y_k$ where $Y_k = 1$, \item $i \in \mathcal S$ and is associated with a particular $Y_k$ where $Y_k = 0$. \end{itemize} The detailed proof can be found in Appendix~\ref{app:F_lemma_proof}. It is clear from Lemma~\ref{lemma:F_decomposition} that $\mathbf F(p,Y)$ is affine when projected onto each coordinate $p_i$. Thus, the extrema of $\mathbf F(p,Y)$ must occur at the boundary of the support set of $p_i$; i.e., at either $p_i = 0$ or $p_i = 1$. Combining this with the fact that $\mathbf F(\cdot)$ is a relaxed version of the binomial coefficient, we observe that the maximization problem in \eqref{eq:ML_deletion} is equivalent to its real-valued relaxation. The following result makes this precise. \begin{theorem} The ML decoding problem for the single-trace deletion channel \begin{equation} \max_{x\in \{0,1\}^n} {x \choose Y} \label{eq:ml_opt_equiv1} \end{equation} is equivalent to the problem \begin{equation} \max_{p\in [0,1]^n} \mathbf F(p,Y). \label{eq:ml_opt_equiv2} \end{equation} Furthermore, given any non-integral $p^* \in [0,1]^n$ that maximizes $\mathbf F(p,Y)$, we can construct a corresponding integral solution $x^* \in \{0,1\}^n$ that maximizes $\mathbf F(x,Y)$ and consequently also maximizes ${x \choose Y}$. \label{thm:ML_relaxation} \end{theorem} \begin{proof} As noted earlier, we have ${x \choose Y} = \mathbf F(x,Y)$. Therefore, we are interested in proving the following: \begin{align*} \max_{x\in \{0,1\}^n} \mathbf F(x,Y) \equiv \max_{p\in [0,1]^n} \mathbf F(p,Y),\numberthis \label{eq:ml_opt_equiv_proof1} \end{align*} where $\equiv$ refers to that the two problems are equivalent (have the same optimal objective value). We prove this by applying the following claim.\\ \textbf{Claim:} Given any feasible $p=(p_1,p_2,...,p_i,...,p_n)$, at least one of the following holds true: \begin{itemize} \item$\mathbf F(p^{(i\rightarrow 0)},Y) \geq \mathbf F(p,Y)$. Recall from notation that $p^{(i\rightarrow 0)}=(p_1,p_2,...,p_{i-1},0,p_{i+1}...,p_n)$ is the vector where the $i^{th}$ coordinate is replaced by $0$. \item $\mathbf F(p^{(i\rightarrow 1)},Y) \geq \mathbf F(p,Y)$. \end{itemize} Thus if $p^*$ is an optimal solution to \eqref{eq:ml_opt_equiv2} with $p_i\in (0,1)$, then at least one of $p^{(i\rightarrow 0)}$ or $p^{(i\rightarrow 1)}$ is also an optimal solution. Sequentially applying this argument for each coordinate of $p$ shows that there exists a point in $\{0,1\}^n$ which is an optimal solution to \eqref{eq:ml_opt_equiv2} and consequently to \eqref{eq:ml_opt_equiv1}. It remains to prove our claim. We use Lemma~\ref{lemma:F_decomposition} to factor out $p_i$ terms in $\mathbf F(p,Y)$: \begin{align*} \mathbf F(p,Y) = \mathbf F( p_{[n]\backslash \{i\}},Y) + p_i \sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]})\\ + (1-p_i) \sum\limits_{k|Y_k=0}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}). \end{align*} Now we express $\mathbf F(p^{(i\rightarrow 0)},Y)$ and $\mathbf F(p^{(i\rightarrow 1)},Y)$ as $$\mathbf F(p^{(i\rightarrow 0)},Y) = \mathbf F( p_{[n]\backslash \{i\}},Y) + \sum\limits_{k|Y_k=0}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}),$$ $$\mathbf F(p^{(i\rightarrow 1)},Y) = \mathbf F( p_{[n]\backslash \{i\}},Y) + \sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}).$$ \noindent Because $0\leq p_i\leq 1$ it directly follows that $$\min \left\{\mathbf F(p^{(i\rightarrow 0)},Y),\mathbf F(p^{(i\rightarrow 1)},Y)\right\} \leq \mathbf F(p,Y) \leq \max \left\{\mathbf F(p^{(i\rightarrow 0)},Y),\mathbf F(p^{(i\rightarrow 1)},Y)\right\},$$ thus proving our claim. Note that the proof gives a natural way to find an optimal lattice point $p_{lattice}^*$ given an optimal interior point $p^*$ by iterating through each coordinate of $p^*$ and switching them to $0$ or $1$ by comparing $\mathbf F(p^{(i\rightarrow 0)},Y)$ and $\mathbf F(p^{(i\rightarrow 1)},Y)$. \end{proof} The real-valued optimization problem in \eqref{eq:ml_opt_equiv2} falls under the umbrella of signomial optimization which is, in general, NP-hard (see for example, \cite{xu2014signomial}, \cite{chand2016signomial}). With a slight change of variables, \eqref{eq:ml_opt_equiv2} could also be expressed as a maximization of a convex function in a convex set. However, it is unclear if \eqref{eq:ml_opt_equiv2} is solvable in polynomial time or inherently hard to solve. \begin{algorithm}[t!] \caption{Coordinate switch ML heuristic}\label{alg:cood_switch} \begin{algorithmic}[1] \item Input: Blocklength $n$, Trace {$Y$}, Initial point $p = (p_1,p_2,...,p_n)$ \\ Outputs: Estimated sequence $\hat X$ \State Initialize visited set $\mathcal V = \emptyset$ \While {True} \State Compute $\mathcal F_i = |\mathbf F(p^{(i\rightarrow 1)},Y)- \mathbf F(p^{(i\rightarrow 0)},Y)|\ \forall\ i$ and let $\mathcal F = (\mathcal F_1,\mathcal F_2,...,\mathcal F_n)$. \State Define the ordered list $\mathcal S =$ \texttt{argsort}$(\mathcal F)$ where \texttt{argsort}$(\mathcal F)$ returns the index set $[n]$ sorted by descending order of $\mathcal F$, i.e., $\mathcal F_{\mathcal S_1}\geq \mathcal F_{\mathcal S_2}\geq ... \geq \mathcal F_{\mathcal S_n}$. \For {$i \in \mathcal S$ (ordered traversal)} \If {$\mathbf F(p^{(i\rightarrow 1)},Y)- \mathbf F(p^{(i\rightarrow 0)},Y) \geq 0$} \State update $p \leftarrow p^{(i\rightarrow 1)}$ \Else \State update $p \leftarrow p^{(i\rightarrow 0)}$ \EndIf \EndFor \If {$p \in \mathcal{V}$} break \EndIf \State $\mathcal V = \mathcal V \cup \{p\}$ \EndWhile \State \textbf{return} $\hat X = p$ \end{algorithmic} \end{algorithm} The proof of Theorem~\ref{thm:ML_relaxation} inspires a heuristic for sequence reconstruction (see Alg.~\ref{alg:cood_switch}): \begin{itemize} \item Start from a given point $p = (p_1,...,p_n) \in [0,1]^n$. \item One round of iteration is defined as follows: fix a traversal order for the indices $\{1,2,...,n\}$. Traverse through the indices $i$ in order and make $p_i$ either 0 or 1 depending on whether $\mathbf F(p^{(i\rightarrow 0)},Y)$ or $\mathbf F(p^{(i\rightarrow 1)},Y)$ is larger. This ensures that $\mathbf F(p,Y)$ never decreases. \item At the end of the round, check if the resultant $p$ was already obtained at the end of a previous round: if so, end the algorithm (to prevent it from going into an endless cycle). Otherwise, start a new round from the resultant $p$. \end{itemize} Clearly the resultant $p$ at the end of a round is a lattice point since we make each $p_i$ to be 0 or 1. Therefore, the algorithm will end after a finite number of steps; in the worst case it will iterate through all $2^n$ sequences, although in practice we observe that it ends in 4-5 rounds (tested upto a blocklength of 100). We also note that the complexity of each round is $O(n^3)$ since it iterates through $n$ coordinates and for each coordinate computes $\mathbf F(\cdot)$, which is $O(n^2)$. A natural question is whether it makes a difference if Alg.~\ref{alg:cood_switch} starts from an interior point ($p = (p_1,...,p_n) \in [0,1]^n$ where $\exists\ p_i \in (0,1)$) as compared to starting from a lattice point ($p = (p_1,...,p_n) \in \{0,1\}^n$). In Section~\ref{sec:Numerics} we show that starting from an interior point results in better estimation accuracy, thus supporting the usefulness of the ML relaxation. \subsection{Proofs.} \subsubsection{Proof of Theorem~\ref{thm:channel_equiv}} \label{app:channel_equiv} \iffalse We first state a lemma (introduced in \cite{Srini2019}) which is closely related to the channel equivalence. The proof of the Lemma is relegated to Appendix~\ref{app:bin_inf_lemma}. \bininfrelation* The channel equivalence can essentially be tied to this lemma as follows: consider the two channel models in Fig.~\ref{fig:channel_equiv}. The probability of observations given the input in both cases is proportional to the number of ways of obtaining the observations given the input. \begin{itemize} \item For the $t$-trace deletion channel model in Fig.~\ref{fig:channel_equiv} (a), the number of ways to obtain the traces given the input is equal to ${X \choose \tilde{Y}^{(1)}}{X \choose \tilde{Y}^{(2)}}...{X \choose \tilde{Y}^{(t)}}$. \item For the cascade model in Fig.~\ref{fig:channel_equiv} (b), the number of ways to obtain the traces given the input is equal to $\sum_{z} {X \choose z} \langle \tilde Y^{(1)}\uparrow \tilde Y^{(2)} \uparrow...\uparrow \tilde Y^{(t)},z \rangle$ (this is shown in the proof of the theorem). \end{itemize} Clearly by Lemma~\ref{lemma:bin_inf_relation}, the above two are equal, thus proving the equivalence of the two channel models. On the contrary, this equivalence provides a nice physical interpretation of Lemma~\ref{lemma:bin_inf_relation}. \channelequiv* \begin{proof} We show the probabilistic equivalence between the two channel models in Fig.~\ref{fig:channel_equiv}: 1) $t$ independent deletion channels 2) cascade of a deletion channel with parameter $\delta^t$ with the \textit{remnant} channel with parameter $\delta$ defined as follows: an input symbol to the remnant channel is included in $k>0$ given outputs and deleted in the rest with a probability $\frac{\delta^{t-k}(1-\delta)^k}{1-\delta^t}$. Given this definition, we now first compute the probability of a given set of output sequences given an input sequence for the remnant channel, namely $\Pr(\tilde Y^{(1)},\tilde Y^{(2)},...,\tilde Y^{(t)}|Z)$. First, note that there can be multiple deletion patterns corresponding to outputs $\tilde Y^{(1)},\tilde Y^{(2)},...,\tilde Y^{(t)}$ resulting from a given input $Z$. The number of such patterns is equal to $\langle \tilde Y^{(1)}\uparrow \tilde Y^{(2)} \uparrow...\uparrow \tilde Y^{(t)},Z \rangle$, which essentially follows from the definition of the infiltration product. Consider one such valid deletion pattern, i.e., a deletion pattern $\mathcal{D}$ that is a mapping of the symbols in $Z$ onto the symbols in $\tilde Y^{(1)},\tilde Y^{(2)},...,\tilde Y^{(t)}$: $\mathcal{D}=\{(1,S_1),(2,S_2),...,(|Z|,S_{|Z|})\}$. Here $(i,S_i)$ represents the fact that $Z_i$ is not deleted in the output set $\tilde{Y}^{(S_i)}$ and is deleted in the rest. Clearly, $|S_i|>0$ from the definition of the remnant channel. Also $\sum_{i=1}^{|Z|}|S_i|=\sum_{j=1}^t|\tilde{Y}^{(j)}|$ since every symbol of each output is associated with exactly one input symbol and hence corresponds to one particular $S_i$. Thus, \begin{align*} \Pr(&\tilde Y^{(1)},\tilde Y^{(2)},...,\tilde Y^{(t)}|Z) \\&= \langle \tilde Y^{(1)}\uparrow \tilde Y^{(2)} \uparrow...\uparrow \tilde Y^{(t)},Z \rangle \Pr(\tilde Y^{(1)},\tilde Y^{(2)},...,\tilde Y^{(t)}|Z,\mathcal{D})\\ &=\langle \tilde Y^{(1)}\uparrow \tilde Y^{(2)} \uparrow...\uparrow \tilde Y^{(t)},Z \rangle \prod_{i=1}^{|Z|}\frac{(1-\delta)^{|S_i|}\delta^{t-|S_i|}}{1-\delta^t}\\ &=\langle \tilde Y^{(1)}\uparrow \tilde Y^{(2)} \uparrow...\uparrow \tilde Y^{(t)},Z \rangle \frac{(1-\delta)^{\sum|S_i|}\delta^{|Z|t-\sum |S_i|}}{(1-\delta^t)^{|Z|}}\\ &=\langle \tilde Y^{(1)}\uparrow \tilde Y^{(2)} \uparrow...\uparrow \tilde Y^{(t)},Z \rangle \frac{(1-\delta)^{\sum|\tilde{Y}^{(j)}|}\delta^{|Z|t-\sum |\tilde{Y}^{(j)}|}}{(1-\delta^t)^{|Z|}}. \end{align*} We can then compute the probability of the output given the input for the cascade channel as \begin{align*} \Pr(&\tilde Y^{(1)},\tilde Y^{(2)},...,\tilde Y^{(t)}|X)\\ &= \sum_{z} \Pr(\tilde Y^{(1)},\tilde Y^{(2)},...,\tilde Y^{(t)},Z=z|X)\\ &= \sum_{z} \Pr(Z=z|X)\Pr(\tilde Y^{(1)},\tilde Y^{(2)},...,\tilde Y^{(t)}|Z=z)\\ &= \sum_{z} \Bigg[{X \choose z} \delta^{t(|X|-|z|)}(1-\delta^t)^{|z|}\langle \tilde Y^{(1)}\uparrow \tilde Y^{(2)} \uparrow...\uparrow \tilde Y^{(t)},z \rangle \frac{(1-\delta)^{\sum|\tilde{Y}^{(j)}|}\delta^{|z|t-\sum |\tilde{Y}^{(j)}|}}{(1-\delta^t)^{|z|}}\Bigg]\\ &= \left[\sum_{z} {X \choose z} \langle \tilde Y^{(1)}\uparrow \tilde Y^{(2)} \uparrow...\uparrow \tilde Y^{(t)},z \rangle\right] \delta^{t|X|-\sum |\tilde{Y}^{(j)}|} {(1-\delta)^{\sum|\tilde{Y}^{(j)}|}}\\ &={X \choose \tilde{Y}^{(1)}}{X \choose \tilde{Y}^{(2)}}...{X \choose \tilde{Y}^{(t)}} \delta^{t|X|-\sum |\tilde{Y}^{(j)}|} {(1-\delta)^{\sum|\tilde{Y}^{(j)}|}}\\ &=\prod_{j=1}^t {X \choose \tilde{Y}^{(j)}} \delta^{|X|-|\tilde{Y}^{(j)}|} {(1-\delta)^{|\tilde{Y}^{(j)}|}}\\ &=\Pr(Y^{(1)}, Y^{(2)},..., Y^{(t)}|X), \end{align*} proving the equivalence. \end{proof} \fi The intuition behind the theorem is that the cascade model splits the error events in the $t$-trace deletion channel into 2 parts:\\ - When an input symbol is deleted in all the traces, which is captured by the deletion channel with parameter $\delta^t$.\\ - When an input symbol is not deleted in at least one of the traces, captured by the remnant channel. \begin{figure}[!h] \centering \includegraphics[scale=0.4]{channel_equiv_proof.pdf} \caption{The deletion error events occurring in the two channel models. Here `$-$' corresponds to a symbol being deleted and `$+$' corresponds to a transmission. The deletion pattern $D_i$ corresponds to the input symbol $X_i$.} \end{figure} In order to prove the theorem, we need to prove that the deletion patterns arising in the $t$-trace channel model and in the cascade model have the same distribution, i.e., \begin{align*} \Pr(D_1=d_1,D_2=d_2,...,D_n=d_n) = \Pr(\widetilde D_1=d_1,\widetilde D_2=d_2,...,\widetilde D_n=d_n), \end{align*} where $d_i \in \{-,+\}^t$, where a $-$ corresponds to a deletion and a $+$ corresponds to a transmission. Also from the definition of our channel models, the deletions act independently on each input symbol i.e., $D_i\ \raisebox{0.05em}{\rotatebox[origin=c]{90}{$\models$}}\ D_j$ for $i\neq j$. So it is sufficient to prove that the distributions of each $D_i$ and $\widetilde D_i$ are the same. \begin{figure}[!h] \centering \includegraphics[scale=0.5]{channel_equiv_proof_2.pdf} \caption{The error events of the cascade model, expressed in terms of the error events of its components.} \end{figure} Consider $\widetilde D_i$ -- this is influenced by $\breve {D^0_i}$ which is the deletion in channel $\mathcal C_1$ and by $\breve D_i$ which are the deletion in the remnant channel $\mathcal C_2$. To prove the equivalence, we consider 2 cases: \begin{itemize} \item $d_i = (-,-,-,...,-)$, the error event where a symbol is deleted in all the observations. It can be seen that $\Pr(D_i = d_i)$ for this case is $\delta^t$. On the other hand, to compute $\Pr(\widetilde D_i = d_i)$, we note that this event is possible if and only if $\breve {D^0_i} = -$, since by definition, the remnant channel cannot delete the input symbol in all the $t$ observations. Therefore, $\Pr(\widetilde D_i = d_i)=\Pr(\breve D^0_i = -) = \delta^t$. \item $d_i \neq (-,-,-,...,-)$, i.e., the input symbol is not deleted in at least one trace. Also let us define $k$ to be the count of $-$ in $d_i$. In this case, $\Pr(D_i = d_i)=\delta^{\text{Count(-) in } d_i}(1-\delta)^{\text{Count(+) in } d_i} = \delta^k (1-\delta)^{t-k}$. For the cascade model, this event requires that $\breve {D^0_i} = +$ and $\breve {D_i}=d_i$. Thus, $$\Pr(\tilde D_i=d_i)=\Pr(\breve {D^0_i} = +)\cdot \Pr(\breve {D_i}=d_i) = (1-\delta^t) \frac{\delta^k (1-\delta)^{t-k}}{1-\delta^t}=\delta^k (1-\delta)^{t-k}.$$ \end{itemize} In both cases, the distributions of $D_i$ and $\widetilde D_i$ are the same, proving the equivalence. \subsubsection{Proof of Lemma~\ref{lemma:F_decomposition}} \label{app:F_lemma_proof} \deletionMLrellemma* \begin{proof} The proof of this lemma uses a similar approach as the proof of Thm.~\ref{thm:approx_smap_postprob}. First, in the expression for $\mathbf F(\cdot )$, we separate out the subsets that contain index $i$: \begin{align*} \mathbf F(p,y) &= \sum\limits_{\substack{\mathcal S|\mathcal S\subseteq [n],\\|\mathcal S|=m}} \quad \prod\limits_{j=1}^m p_{\mathcal S_j}^{y_j} (1-p_{\mathcal S_j})^{1-y_j}\\ &= \sum\limits_{\substack{\mathcal S|\mathcal S\subseteq [n],\\|\mathcal S|=m, \\ i \notin \mathcal S}} \quad \prod\limits_{j=1}^m p_{\mathcal S_j}^{y_j} (1-p_{\mathcal S_j})^{1-y_j} + \sum\limits_{\substack{\mathcal S|\mathcal S\subseteq [n],\\|\mathcal S|=m,\\ i \in \mathcal S}} \quad \prod\limits_{j=1}^m p_{\mathcal S_j}^{y_j} (1-p_{\mathcal S_j})^{1-y_j}\\ &= \mathbf F(p_{[n]\backslash \{i\}},y) + \sum\limits_{\substack{\mathcal S|\mathcal S\subseteq [n],\\|\mathcal S|=m,\\ i \in \mathcal S}} \quad \prod\limits_{j=1}^m p_{\mathcal S_j}^{y_j} (1-p_{\mathcal S_j})^{1-y_j}. \numberthis \label{eq:Flemma_proof1} \end{align*} Now the second term can be further split as, \begin{align*} \sum\limits_{\substack{\mathcal S|\mathcal S\subseteq [n],\\|\mathcal S|=m,\\ i \in \mathcal S}} \quad \prod\limits_{j=1}^m p_{\mathcal S_j}^{y_j} (1-p_{\mathcal S_j})^{1-y_j} &= \sum_{k=1}^m\sum\limits_{\substack{\mathcal S|\mathcal S\subseteq [n],\\|\mathcal S|=m,\\ \mathcal S_k = i}} \quad \prod\limits_{j=1}^m p_{\mathcal S_j}^{y_j} (1-p_{\mathcal S_j})^{1-y_j}. \end{align*} One could express the set $\mathcal S$ as the union $\mathcal S = \mathcal S' \cup \{i\} \cup \mathcal S''$ such that $\mathcal S' \subseteq [i-1]$ and $\mathcal S'' \subseteq [i+1:n]$ to get \begin{align*} &\sum_{k=1}^m\sum\limits_{\substack{\mathcal S|\mathcal S\subseteq [n],\\|\mathcal S|=m,\\ \mathcal S_k = i}} \quad \prod\limits_{j=1}^m p_{\mathcal S_j}^{y_j} (1-p_{\mathcal S_j})^{1-y_j}\\ &= \sum_{k=1}^m\sum_{\substack{\mathcal S'|\\ \mathcal S'\subseteq [i-1]\\ |\mathcal S'|=k-1}}\sum_{\substack{\mathcal S''|\\ \mathcal S'' \subseteq [i+1:n]\\ |\mathcal S''|=m-k}} \left( \prod\limits_{j=1}^{k-1} p_{\mathcal S'_j}^{y_j} (1-p_{\mathcal S'_j})^{1-y_j} \right) \left( p_{i}^{y_k} (1-p_{i})^{1-y_k} \right) \left( \prod\limits_{j=1}^{m-k} p_{\mathcal S''_j}^{y_{j+k}} (1-p_{\mathcal S''_j})^{1-y_{j+k}} \right)\\ &= \sum_{k=1}^m p_{i}^{y_k} (1-p_{i})^{1-y_k}\left(\sum_{\substack{\mathcal S'|\\ \mathcal S'\subseteq [i-1]\\ |\mathcal S'|=k-1}} \prod\limits_{j=1}^{k-1} p_{\mathcal S'_j}^{y_j} (1-p_{\mathcal S'_j})^{1-y_j} \right) \left( \sum_{\substack{\mathcal S''|\\ \mathcal S'' \subseteq [i+1:n]\\ |\mathcal S''|=m-k}} \prod\limits_{j=1}^{m-k} p_{\mathcal S''_j}^{y_{j+k}} (1-p_{\mathcal S''_j})^{1-y_{j+k}} \right)\\ &= \sum_{k=1}^m p_{i}^{y_k} (1-p_{i})^{1-y_k} \mathbf F(p_{[i-1]},y_{[k-1]}) \mathbf F(p_{[i+1:n]},y_{[k+1:m]}). \end{align*} The $\sum_{k=1}^m$ summation in the above expression could further be split into the two cases depending on whether $y_k=0$ or $y_k=1$, which simplifies the term $p_{i}^{y_k} (1-p_{i})^{1-y_k}$ to either $1-p_i$ or $p_i$ respectively. Thus, \begin{align*} &\sum\limits_{\substack{\mathcal S|\mathcal S\subseteq [n],\\|\mathcal S|=m,\\ i \in \mathcal S}} \quad \prod\limits_{j=1}^m p_{\mathcal S_j}^{y_j} (1-p_{\mathcal S_j})^{1-y_j}\\ &= (1-p_i)\sum_{k|y_k=0} \mathbf F(p_{[i-1]},y_{[k-1]}) \mathbf F(p_{[i+1:n]},y_{[k+1:m]}) + p_i\sum_{k|y_k=1} \mathbf F(p_{[i-1]},y_{[k-1]}) \mathbf F(p_{[i+1:n]},y_{[k+1:m]}).\numberthis \label{eq:Flemma_proof2} \end{align*} \noindent Plugging \eqref{eq:Flemma_proof2} in \eqref{eq:Flemma_proof1} concludes the proof of the Lemma. \end{proof} \subsubsection{Proof of Lemma~\ref{lemma:bin_inf_relation}} The following Lemma forms the backbone of the analyses for multiple traces. This lemma is also closely related to the channel equivalence in Theorem~\ref{thm:channel_equiv}. \label{app:bin_inf_lemma} \bininfrelation* \begin{proof} The channel equivalence can essentially be tied to this lemma as follows: consider the two channel models in Fig.~\ref{fig:channel_equiv}. The probability of observations given the input in both cases is proportional to the number of ways of obtaining the observations given the input. \begin{itemize} \item For the $t$-trace deletion channel model in Fig.~\ref{fig:channel_equiv} (a), the number of ways to obtain the traces given the input is equal to ${X \choose {Y}^{1}}{X \choose {Y}^{2}}...{X \choose {Y}^{t}}$. \item For the cascade model in Fig.~\ref{fig:channel_equiv} (b), the number of ways to obtain the traces given the input is equal to $\sum_{z} {X \choose z} \langle \tilde Y^{1}\uparrow \tilde Y^{2} \uparrow...\uparrow \tilde Y^{t},z \rangle$, which we show below. \end{itemize} The above two are expression must be equal since the two channel models are equivalent. We now first compute the probability of a given set of output sequences given an input sequence for the remnant channel, namely $\Pr(\tilde Y^{1},\tilde Y^{2},...,\tilde Y^{t}|Z)$. First, note that there can be multiple deletion patterns corresponding to outputs $\tilde Y^{1},\tilde Y^{2},...,\tilde Y^{t}$ resulting from a given input $Z$. The number of such patterns is equal to $\langle \tilde Y^{1}\uparrow \tilde Y^{2} \uparrow...\uparrow \tilde Y^{t},Z \rangle$, which essentially follows from the definition of the infiltration product. Consider one such valid deletion pattern, i.e., a deletion pattern $\mathcal{D}$ that is a mapping of the symbols in $Z$ onto the symbols in $\tilde Y^{1},\tilde Y^{2},...,\tilde Y^{t}$: $\mathcal{D}=\{(1,S_1),(2,S_2),...,(|Z|,S_{|Z|})\}$. Here $(i,S_i)$ represents the fact that $Z_i$ is not deleted in the output set $\tilde{Y}^{S_i}$ and is deleted in the rest. From the definition of the remnant channel, we have $|S_i|>0$ . Also $\sum_{i=1}^{|Z|}|S_i|=\sum_{j=1}^t|\tilde{Y}^{j}|$ since every symbol of each output is associated with exactly one input symbol and hence corresponds to one particular $S_i$. Thus, \begin{align*} \Pr(\tilde Y^{1},\tilde Y^{2},...,\tilde Y^{t}|Z) &= \langle \tilde Y^{1}\uparrow \tilde Y^{2} \uparrow...\uparrow \tilde Y^{t},Z \rangle \Pr(\tilde Y^{1},\tilde Y^{2},...,\tilde Y^{t}|Z,\mathcal{D})\\ &=\langle \tilde Y^{1}\uparrow \tilde Y^{2} \uparrow...\uparrow \tilde Y^{t},Z \rangle \prod_{i=1}^{|Z|}\frac{(1-\delta)^{|S_i|}\delta^{t-|S_i|}}{1-\delta^t}\\ &=\langle \tilde Y^{1}\uparrow \tilde Y^{2} \uparrow...\uparrow \tilde Y^{t},Z \rangle \frac{(1-\delta)^{\sum|S_i|}\delta^{|Z|t-\sum |S_i|}}{(1-\delta^t)^{|Z|}}\\ &=\langle \tilde Y^{1}\uparrow \tilde Y^{2} \uparrow...\uparrow \tilde Y^{t},Z \rangle \frac{(1-\delta)^{\sum|\tilde{Y}^{j}|}\delta^{|Z|t-\sum |\tilde{Y}^{j}|}}{(1-\delta^t)^{|Z|}}. \end{align*} We can then compute the probability of the output given the input for the cascade channel as \begin{align*} \Pr(&\tilde Y^{1},\tilde Y^{2},...,\tilde Y^{t}|X)\\ &= \sum_{z} \Pr(\tilde Y^{1},\tilde Y^{2},...,\tilde Y^{t},Z=z|X)\\ &= \sum_{z} \Pr(Z=z|X)\Pr(\tilde Y^{1},\tilde Y^{2},...,\tilde Y^{t}|Z=z)\\ &= \sum_{z} \Bigg[{X \choose z} \delta^{t(|X|-|z|)}(1-\delta^t)^{|z|}\langle \tilde Y^{1}\uparrow \tilde Y^{2} \uparrow...\uparrow \tilde Y^{t},z \rangle \frac{(1-\delta)^{\sum|\tilde{Y}^{j}|}\delta^{|z|t-\sum |\tilde{Y}^{j}|}}{(1-\delta^t)^{|z|}}\Bigg]\\ &= \left[\sum_{z} {X \choose z} \langle \tilde Y^{1}\uparrow \tilde Y^{2} \uparrow...\uparrow \tilde Y^{t},z \rangle\right] \delta^{t|X|-\sum |\tilde{Y}^{j}|} {(1-\delta)^{\sum|\tilde{Y}^{j}|}}. \numberthis \label{eq:lemma2_proof_1} \end{align*} For the $t$-trace deletion channel model, we have: \begin{align*} \Pr(Y^1,Y^2,...,Y^t|X) &= \prod_{j=1}^t {X \choose Y^j} \delta^{|X|-|Y^j|}(1-\delta)^{|Y_j|} \\ &= {X \choose {Y}^{1}}{X \choose {Y}^{2}}...{X \choose {Y}^{t}} \delta^{t|X|-\sum |{Y}^{j}|} {(1-\delta)^{\sum|{Y}^{j}|}}. \numberthis \label{eq:lemma2_proof_2} \end{align*} Equating \eqref{eq:lemma2_proof_1} and \eqref{eq:lemma2_proof_2} with $X = h$ and traces as $Y^j = \tilde Y^j = f_j$ proves the Lemma. Alternatively, we use also induction to prove the statement as we do below. The statement is trivially true when $m=1$ since, $\sum_{w}{h \choose w}\langle f_1,w \rangle={h \choose f_1}$ as $\langle f,w \rangle=\mathbbm{1}_{f=w}$. We refer the reader to equation 6.3.25 in \cite{lothaire1997combinatorics} for the proof of the lemma for the case $m=2$. Assume that the statement is true for $m=k \in \mathbb{Z}, k\geq 2$. We next prove the validity when $m=k+1$. \\ Consider \begin{align} {h \choose f_1} {h \choose f_2}...{h \choose f_k}{h \choose f_{k+1}}&=\sum_{w}{h \choose w}\langle f_1\uparrow f_2\uparrow ...\uparrow f_k,w \rangle {h \choose f_{k+1}}\nonumber\\ &=\sum_{w}\left[{h \choose w} {h \choose f_{k+1}}\right]\langle f_1\uparrow f_2\uparrow ...\uparrow f_k,w \rangle\nonumber\\ &=\sum_{w}\left[\sum_v \langle w\uparrow f_{k+1},v \rangle {h \choose v}\right]\langle f_1\uparrow f_2\uparrow ...\uparrow f_k,w \rangle\nonumber\\ &=\sum_{v}{h \choose v}\left[\sum_w \langle w\uparrow f_{k+1},v \rangle \langle f_1\uparrow f_2\uparrow ...\uparrow f_k,w \rangle\right]. \label{eq:prop2proof} \end{align} To evaluate the term in the square bracket, we use \eqref{def:infiltforseq}. For the case where $\tau \in \mathcal{A}^*,\sigma \in \mathbb{Z}\langle \mathcal{A} \rangle$ in \eqref{def:infiltforseq}, we have $$\sigma\uparrow \tau=\sum_{f\in \mathcal{A}^*} \langle \sigma,f \rangle (f\uparrow \tau),$$ and thus \begin{equation} \langle \sigma \uparrow \tau,u \rangle=\sum_{f\in \mathcal{A}^*} \langle \sigma,f \rangle \langle f\uparrow \tau,u\rangle. \label{eq:prop2proof2} \end{equation} We use \eqref{eq:prop2proof2} to replace the term in the square bracket in \eqref{eq:prop2proof}, i.e., \begin{align} {h \choose f_1} {h \choose f_2}...{h \choose f_k}{h \choose f_{k+1}}\nonumber\\ =\sum_{v}{h \choose v}\langle (f_1\uparrow f_2\uparrow ...\uparrow f_k) \uparrow f_{k+1},v \rangle, \end{align} and the lemma follows from the associativity property of the infiltration product. \end{proof} \subsubsection{Proof of Lemma~\ref{lemma:smapsum}} \label{app:smapsum} \begin{restatable}{lemma}{smapsum} \label{lemma:smapsum} \begin{align*} \sum_{\substack{f||f|{=}n\\f_i{=}a}}{f \choose g} = 2^{n-|g|}\Bigg(\frac{1}{2}{n-1 \choose |g|} &+\sum_{j|g_j=a}{i-1 \choose j-1}{n-i \choose |g|-j}\Bigg), \end{align*} where $j\in\Big[\max\{1,|g|+i-n\}:\min\{i,|g|\}\Big]$. \end{restatable} \begin{proof} First, observe that $${f \choose g} = \sum_{\substack{S\subseteq [n]:\\|S|=|g|}} \mathbbm 1_{f_S=g},$$ where the summation is over all ordered subsets of $[n]=\{1,2,...,n\}$ of size $|g|$ and $f_S$ corresponds to the subsequence of $f$ indexed by $S$. Thus, \begin{align*} \sum_{\substack{f\in\mathcal{A}^n|\\f_i=a}}&{f \choose g} = \sum_{\substack{f\in\mathcal{A}^n|\\f_i=a}} \sum_{\substack{S\subseteq [n]|\\|S|=|g|}} \mathbbm 1_{f_S=g} = \sum_{\substack{S\subseteq [n]|\\|S|=|g|}} \sum_{\substack{f\in\mathcal{A}^n|\\f_i=a}} \mathbbm 1_{f_S=g}\\ &=\sum_{\substack{S\subseteq [n]|\\|S|=|g|\\i \notin S}} \sum_{\substack{f\in\mathcal{A}^n|\\f_i=a}} \mathbbm 1_{f_S=g} + \sum_{\substack{S\subseteq [n]|\\|S|=|g|\\i \in S}} \sum_{\substack{f\in\mathcal{A}^n|\\f_i=a}} \mathbbm 1_{f_S=g}\\ &=\sum_{\substack{S\subseteq [n]|\\|S|=|g|\\i \notin S}} \sum_{\substack{f\in\mathcal{A}^n|\\f_i=a}} \mathbbm 1_{f_S=g} + \sum_{j=1}^m \sum_{\substack{S\subseteq [n]|\\|S|=|g|\\S_j=i}} \sum_{\substack{f\in\mathcal{A}^n|\\f_i=a}} \mathbbm 1_{f_S=g}. \numberthis \label{eq:lemmasmapsum} \end{align*} \begin{figure}[!h] \begin{center} \includegraphics[scale=0.25]{lemma1.pdf} \vspace*{-2mm} \caption{Figure illustrating proof of Lemma~\ref{lemma:smapsum}.} \label{fig:lemmasmapsum} \end{center} \end{figure} The two terms in \eqref{eq:lemmasmapsum} can be visualized as the number of ways to fill up the blank spaces (spaces without arrows pointing to it in $f$) in Fig.~\ref{fig:lemmasmapsum}(a) and (b) respectively. Solving this counting problem, we get $$\sum_{\substack{f\in\mathcal{A}^n|\\f_i=a}}{f \choose g}=2^{n-|g|}\left(\frac{1}{2}{n-1 \choose |g|}+\sum_{j|g_j=a}{i-1 \choose j-1}{n-i \choose |g|-j}\right).$$ \end{proof} \subsection{Dynamic program to compute $\mathbf F(\cdot)$ and $\nabla \mathbf F(\cdot)$} \subsubsection{Computation of $\mathbf F(p,v)$} \label{app:F_compute} We here describe how to compute $\mathbf F(p,v)$ in $O(mn)$ time and space complexity, where $p=(p_1,...,p_n)$ and $v=v_1...v_m$, via a dynamic programming approach. Note that $m \leq n$ otherwise $\mathbf F(p,v)=0$. We first define \begin{align*} &\mathbf G^{for}(k,j)\triangleq \mathbf F(p_{[1:k]},v_{[1:j]}). \numberthis \label{eq:G} \end{align*} Using Lemma~\ref{lemma:F_decomposition} with $i=n$, we get \begin{align*} \mathbf F(p,v) = \mathbf F(p_{[n-1]},v) + p_n^{v_m} (1-p_n)^{(1-v_m)} \mathbf F(p_{[n-1]},v_{[m-1]}). \end{align*} \noindent This translates to the following dynamic program for $\mathbf G^{for}$: \begin{align*} \mathbf G^{for}(k,j) = \mathbf G^{for}(k-1,j)+ p_{k}^{v_j}(1-p_{k})^{1-v_j}&\mathbf G^{for}(k-1,j-1),\numberthis \label{eq:approx_smap_dpfor} \end{align*} with the boundary conditions $\mathbf G^{for}(k,0)=1\ \forall\ k \geq 0$ and $\mathbf G^{for}(k,j)=0\ \forall\ k<j$. The algorithm is now summarized as Alg.~\ref{alg:F_comp}. \begin{algorithm}[h!] \caption{Computing $\mathbf F(p,v)$}\label{alg:F_comp} \begin{algorithmic}[1] \State Inputs: $p \in [0,1]^n$, $v \in \{0,1\}^m$ \State Outputs: $\mathbf F(p_{[1:k]},v_{[1:j]})$ for all $k \in [n]$ and $j\in[m]$ \State Initialize $\mathbf G^{for}(k,0)=1\ \forall\ k$ and $\mathbf G^{for}(k,j)=0\ \forall\ k<j$ \For {$k = 1:n$ and $j = 1:m$} \State Use \eqref{eq:approx_smap_dpfor} to update $\mathbf G^{for}(k,j)$ \EndFor \State return $\mathbf G^{for}(k,j)\ \forall\ k,j$ \end{algorithmic} \end{algorithm} We note that a similar dynamic programming approach yields $\mathbf F(p_{[k+1:n]},v_{[j+1:m]})$ for all $k \in [n]$ and $j\in[m]$ in $O(mn)$ time and space complexity by defining \begin{align*} &\mathbf G^{rev}(k,j)\triangleq \mathbf F(p_{[k+1:n]},v_{[j+1:m]}). \end{align*} \noindent The following dynamic program can be used for $\mathbf G^{rev}$: \begin{align*} \mathbf G^{rev}(k,j) = \mathbf G^{rev}(k+1,j)+ p_{k+1}^{v_{j+1}}(1-p_{k+1})^{1-v_{j+1}}&\mathbf G^{rev}(k+1,j+1),\numberthis \label{eq:approx_smap_dprev} \end{align*} with the boundary conditions $\mathbf G^{rev}(k,m)=1\ \forall\ k \geq 0$ and $\mathbf G^{rev}(k,j)=0\ \forall\ k,j: n-k<m-j$. \\ \subsubsection{Computation of $\nabla_p \mathbf F(p,v)$} \label{app:F_grad_comp} First, from Lemma~\ref{lemma:F_decomposition}, we have \begin{align*} \mathbf F(p,v) = \mathbf F(p_{[n]\backslash \{i\}},v) +& (1-p_i)\sum_{k|v_k=0} \mathbf F(p_{[i-1]},v_{[k-1]}) \mathbf F(p_{[i+1:n]},v_{[k+1:m]}) \\&+ p_i\sum_{k|v_k=1} \mathbf F(p_{[i-1]},v_{[k-1]}) \mathbf F(p_{[i+1:n]},v_{[k+1:m]}). \end{align*} Differentiating with respect to $p_i$, we get \begin{align*} \frac{\partial \mathbf F(p,v)}{\partial p_i} &= \sum_{k|v_k=1} \mathbf F(p_{[i-1]},v_{[k-1]}) \mathbf F(p_{[i+1:n]},v_{[k+1:m]}) - \sum_{k|v_k=0} \mathbf F(p_{[i-1]},v_{[k-1]}) \mathbf F(p_{[i+1:n]},v_{[k+1:m]}) \\ &= \sum_{k|v_k=1} \mathbf G^{for}(i{-}1,k{-}1)\mathbf G^{rev}(i,k) - \sum_{k|v_k=0}\mathbf G^{for}(i{-}1,k{-}1)\mathbf G^{rev}(i,k). \numberthis \label{eq:F_grad_comp} \end{align*} Thus, computing the $\mathbf G^{for}$ and $\mathbf G^{rev}$ terms is sufficient to compute the gradient. As discussed above, this computation requires $O(nm)$ operations. Given $\mathbf G^{for}$ and $\mathbf G^{rev}$, the computation of each partial derivative $\frac{\partial \mathbf F(p,v)}{\partial p_i}$ requires $O(m)$ operations, and we need to compute $n$ such partial derivatives. Thus, the complexity of computing $\nabla_p \mathbf F(p,v)$ can be done in $O(nm)$ time and space complexity. \begin{algorithm}[h!] \caption{Computing $\nabla_p \mathbf F(p,v)$}\label{alg:F_grad_comp} \begin{algorithmic}[1] \State Inputs: $p \in [0,1]^n$, $v \in \{0,1\}^m$ \State Outputs: $\nabla_p \mathbf F(p,v)$ \State Initialize $\mathbf G^{for}(k,0)=1\ \forall\ k$ and $\mathbf G^{for}(k,j)=0\ \forall\ k<j$ \State Initialize $\mathbf G^{rev}(k,m)=1\ \forall\ k$ and $\mathbf G^{rev}(k,j)=0\ \forall\ k,j: n-k<m-j$ \For {$k = 1:n$ and $j = 1:m$} \State Use \eqref{eq:approx_smap_dpfor} and \eqref{eq:approx_smap_dprev} to compute $\mathbf G^{for}(k,j)$ and $\mathbf G^{rev}(k,j)$ \EndFor \For {$i = 1:n$} \State Use \eqref{eq:F_grad_comp} to compute $\frac{\partial \mathbf F(p,v)}{\partial p_i} $ \EndFor \State return $\nabla_p \mathbf F(p,v)$ \end{algorithmic} \end{algorithm} \subsection{An algebraic definition of the infiltration product.} \label{app:infil_def} For completeness, we reproduce the formal definition of the infiltration product from Section 6.3 of \cite{lothaire1997combinatorics} (also see there for the equivalence of the two definitions). A \textit{formal series} with indeterminates (or variables) in a set $\mathcal A$ and coefficients in a commutative ring $\mathcal R$, is a mapping of $\mathcal A^*$ onto $\mathcal R$. Recall that a commutative ring is a set which forms an abelian group under an \textit{addition} operation, is a monoid under a \textit{multiplication} operation which commutes, and the multiplication operation distributes over addition. Here we consider $\mathbb Z$, the set of integers as the commutative ring $\mathcal{R}$. A formal series is called a \textit{polynomial} if only a finite number of sequences are mapped to non-zero values, the rest of the sequences map to zero. Consider two polynomials $\sigma,\tau: \mathcal{A}^*\rightarrow \mathbb Z$. The value taken by a sequence $w\in \mathcal A^*$ on $\sigma$ (or the coefficient of $w$ in $\sigma$) is denoted by $\langle \sigma,w\rangle \in \mathbb R$. We also define binary addition ($\oplus$) and multiplication operations ($\times$) on the set of polynomials as follows: \begin{align} \langle \sigma\oplus \tau,w\rangle \triangleq \langle \sigma,w\rangle + \langle \tau,w \rangle \quad \forall w\in \mathcal A^*,\label{eq:polynomial_add}\\ \langle \sigma\times \tau,w\rangle \triangleq \sum_{\substack{f,g\in \mathcal A^*:\\ f.g=w}}\langle \sigma,f\rangle \langle \tau,g \rangle \quad \forall w\in \mathcal A^*.\label{eq:polynomial_prod} \end{align} We will use the usual symbols $+$ and $.$ in place of $\oplus$ and $\times$ in this work for convenience. The meaning of the operation would be clear depending on the operands. With these operations the set of polynomials form a non-commutative ring, and is denoted by $\mathbb Z\langle\mathcal A \rangle$, also called the free $\mathbb Z$-algebra on $\mathcal A$ in ring theory. Note that the addition and multiplication operations defined in \eqref{eq:polynomial_add} and \eqref{eq:polynomial_prod} are similar to the operations defined on commutative polynomials, except that the multiplication operation under the summation in \eqref{eq:polynomial_prod} ($f.g=w$) is actually concatenation and is non-commutative. The multiplication inside the summation in \eqref{eq:polynomial_prod} is multiplication in the real field and hence commutative. The multiplication defined in \eqref{eq:polynomial_prod} distributes over addition defined in \eqref{eq:polynomial_add}. Thus, a polynomial in $\mathbb Z\langle\mathcal A \rangle$ can be represented as a sum of monomials in $\mathcal A^*$ each with an associated coefficient in $\mathbb Z$, i.e., $\sigma=\sum\limits_{w\in \mathcal A^*} \langle\sigma,w \rangle w$. Define the \textit{degree} of a polynomial to be equal to the length of a longest sequence with a non-zero coefficient in the polynomial and the \textit{number of terms} of a polynomial as the number of sequences with non-zero coefficients in the polynomial. Note that a degree $d$ polynomial could have a number of terms upto $2^{d+1}-1$. With this, the \textit{infiltration product} (in general, for two polynomials) is defined as follows: \begin{align} \forall f\in \mathcal{A}^*,& \quad f\uparrow e = e\uparrow f=f.\nonumber \\ \forall f,g\in \mathcal{A}^*&,\quad \forall a,b\in \mathcal{A}, \nonumber\\ fa\uparrow gb=(f\uparrow gb)a&+(fa\uparrow g)b+\mathbbm{1}_{a=b}(f\uparrow g)a.\nonumber \\ \forall \sigma,\tau \in \mathbb{Z}\langle\mathcal{A} \rangle, \quad &\sigma\uparrow \tau=\sum_{f,g\in \mathcal{A}^*} \langle \sigma,f \rangle \langle \tau,g \rangle (f\uparrow g). \label{def:infiltforseq} \end{align} \subsection{Symbolwise posterior probabilities for the remnant channel} \label{app:remnant_postprob} Consider the remnant channel shown below, and let $Z=Z_1Z_2...Z_n$. Also let $Z_i \sim \text{Ber}(0.5)$. We aim to compute $\Pr(Z_i=1|\tilde Y^{1}=y^1,\tilde Y^{2}=y^2,...,\tilde Y^{t}=y^t)$. \begin{figure}[!h] \centering \includegraphics[scale=0.4]{remnant_channel.pdf} \caption{The remnant channel} \end{figure} From the definition of the infiltration product, the input-output relation for this channel can be derived to be: \begin{align*} \Pr(\tilde Y^{1}=y^1,\tilde Y^{2}=y^2,...,\tilde Y^{t}=y^t|Z) =\langle y^1\uparrow y^2 \uparrow...\uparrow y^t,Z \rangle \frac{(1-\delta)^{\sum|y^j|}\delta^{nt-\sum |y^j|}}{(1-\delta^t)^{n}}. \end{align*} Now, one could write the symbolwise posterior probabilities for $Z$ as: \begin{align*} \Pr(Z_i=1&|\tilde Y^{1}=y^1,\tilde Y^{2}=y^2,...,\tilde Y^{t}=y^t) = \sum_{\substack{z||z|=n,\\z_i=1}} \Pr(z|\tilde Y^{1}=y^1,\tilde Y^{2}=y^2,...,\tilde Y^{t}=y^t)\\ &{=} \frac{1}{2^n \Pr(\tilde Y^{1}=y^1,\tilde Y^{2}=y^2,...,\tilde Y^{t}=y^t)} \sum_{\substack{z||z|=n,\\z_i=1}} \Pr(\tilde Y^{1}=y^1,\tilde Y^{2}=y^2,...,\tilde Y^{t}=y^t|z)\\ &{=} \frac{{(1-\delta)^{\sum|y^{j}|}\delta^{nt-\sum |y^{j}|}}}{(1-\delta^t)^{n} 2^n \Pr(\tilde Y^{1}=y^1,\tilde Y^{2}=y^2,...,\tilde Y^{t}=y^t)} \sum_{\substack{z||z|=n,\\z_i=1}} \langle y^1 \uparrow y^2 \uparrow ... \uparrow y^t,z \rangle. \numberthis \label{eq:remant_map_prob_1} \end{align*} A similar expression can be obtained for the case when $Z_i=0$ as \begin{align*} \Pr(Z_i=0&|\tilde Y^{1}=y^1,\tilde Y^{2}=y^2,...,\tilde Y^{t}=y^t)\\ &{=} \frac{{(1-\delta)^{\sum|y^{j}|}\delta^{nt-\sum |y^{j}|}}}{(1-\delta^t)^{n} 2^n \Pr(\tilde Y^{1}=y^1,\tilde Y^{2}=y^2,...,\tilde Y^{t}=y^t)} \sum_{\substack{z||z|=n,\\z_i=0}} \langle y^1 \uparrow y^2 \uparrow ... \uparrow y^t,z \rangle. \numberthis \label{eq:remant_map_prob_0} \end{align*} We could further simplify \eqref{eq:remant_map_prob_1} and \eqref{eq:remant_map_prob_0} using the fact that the expressions in \eqref{eq:remant_map_prob_1} and \eqref{eq:remant_map_prob_0} must sum to 1, leading us to \begin{align*} \Pr(Z_i=1|\tilde Y^{1}=y^1,\tilde Y^{2}=y^2,...,\tilde Y^{t}=y^t) = \frac{ \sum\limits_{\substack{z||z|=n,\\z_i=1}} \langle y^1 \uparrow y^2 \uparrow ... \uparrow y^t,z \rangle}{\sum\limits_{\substack{z||z|=n}} \langle y^1 \uparrow y^2 \uparrow ... \uparrow y^t,z \rangle}. \numberthis \label{eq:remnant_map_prob} \end{align*} We precisely describe the algorithm which computes the terms in \eqref{eq:remnant_map_prob} in section~\ref{sec:exactsmap}, by exploiting the edit graph interpretation of the infiltration product, but give a high level idea below. The complexity of such an algorithm is $O((2n)^t)$ which is equal to the number of edges in the edit graph. Note that for a fixed number of traces, this algorithm is polynomial in the blocklength as opposed to a naive approach of iterating through all the $n$-length sequences. Recall that $\langle y^1 \uparrow y^2 \uparrow ... \uparrow y^t,z \rangle$ is the number of paths from origin to destination of the edit graph $\mathcal G(y^1,y^2,...,y^t)$ which correspond to $z$. Therefore, $\sum_{\substack{z||z|=n}} \langle y^1 \uparrow y^2 \uparrow ... \uparrow y^t,z \rangle$ is equal to the number of $n$-length paths in $\mathcal G(y^1,y^2,...,y^t)$ from the origin to the destination. Note that the edit graph has no cycles, so this quantity can be efficiently computed via the following dynamic program -- the number of $n$ length paths from the origin to a vertex $v$ is equal to the sum of the number of $n-1$ length paths from the origin to the in-neighbors of $v$. Such a procedure iterates over the vertex set of $\mathcal G(y^1,y^2,...,y^t)$ exactly once. The numerator term $\sum_{\substack{z||z|=n\\z_i=1}}\langle y^1 \uparrow y^2 \uparrow ... \uparrow y^t,z \rangle$ can be interpreted in a similar way: it is equal to the number of $n$-length paths in $\mathcal G(y^1,y^2,...,y^t)$ from the origin to the destination such that the $i^{th}$ edge of the path corresponds to a `1'. The algorithm for this, therefore, follows a similar principle but has an extra step. For each vertex $v$, we compute \begin{itemize} \item the number of paths from the origin to $v$ of length $0,1,...,n$, \item the number of paths from $v$ to the destination of length $0,1,...,n$. \end{itemize} Next we iterate over all edges in $\mathcal G(y^1,y^2,...,y^t)$ corresponding to a `1' and accumulate the number of $n$ length paths which have this particular edge as its $i^{th}$ edge. Thus, this algorithm iterates over the vertex set twice and the edge set of $\mathcal G(y^1,y^2,...,y^t)$ once. \subsection{A heuristic for ML optimization with a single trace.} {The proof of Theorem~\ref{thm:ML_relaxation} inspires a heuristic for sequence reconstruction (see Alg.~\ref{alg:cood_switch}): \begin{itemize} \item Start from a given point $p = (p_1,...,p_n) \in [0,1]^n$. \item One round of iteration is defined as follows: fix a traversal order for the indices $\{1,2,...,n\}$. Traverse through the indices $i$ in order and make $p_i$ either 0 or 1 depending on whether $\mathbf F(p^{(i\rightarrow 0)},y)$ or $\mathbf F(p^{(i\rightarrow 1)},y)$ is larger. This ensures that $\mathbf F(p,y)$ never decreases. \item At the end of the round, check if the resultant $p$ was already obtained at the end of a previous round: if so, end the algorithm (to prevent it from going into an endless cycle). Otherwise, start a new round from the resultant $p$. \end{itemize} The resultant $p$ at the end of a round is a lattice point since we make each $p_i$ to be 0 or 1. Therefore, the algorithm will end after a finite number of steps; in the worst case it will iterate through all $2^n$ sequences, although in practice we observe that it ends in 4-5 rounds (tested up to a blocklength of 100). We also note that the complexity of each round is $O(n^3)$ since it iterates through $n$ coordinates and for each coordinate computes $\mathbf F(\cdot)$, which is $O(n^2)$.} \begin{algorithm}[t!] \caption{Coordinate switch ML heuristic}\label{alg:cood_switch} \begin{algorithmic}[1] \item Input: Blocklength $n$, Trace {$Y=y$}, Initial point $p = (p_1,p_2,...,p_n)$ \\ Outputs: Estimated sequence $\hat X$ \State Initialize visited set $\mathcal V = \emptyset$ \While {True} \State Compute $\mathcal F_i = |\mathbf F(p^{(i\rightarrow 1)},y)- \mathbf F(p^{(i\rightarrow 0)},y)|\ \forall\ i$ and let $\mathcal F = (\mathcal F_1,\mathcal F_2,...,\mathcal F_n)$. \State Define the ordered list $\mathcal S =$ \texttt{argsort}$(\mathcal F)$ where \texttt{argsort}$(\mathcal F)$ returns the index set $[n]$ sorted by descending order of $\mathcal F$, i.e., $\mathcal F_{\mathcal S_1}\geq \mathcal F_{\mathcal S_2}\geq ... \geq \mathcal F_{\mathcal S_n}$. \For {$i \in \mathcal S$ (ordered traversal)} \If {$\mathbf F(p^{(i\rightarrow 1)},y)- \mathbf F(p^{(i\rightarrow 0)},y) \geq 0$} \State update $p \leftarrow p^{(i\rightarrow 1)}$ \Else \State update $p \leftarrow p^{(i\rightarrow 0)}$ \EndIf \EndFor \If {$p \in \mathcal{V}$} break \EndIf \State $\mathcal V = \mathcal V \cup \{p\}$ \EndWhile \State \textbf{return} $\hat X = p$ \end{algorithmic} \end{algorithm} A natural question is whether it makes a difference if Alg.~\ref{alg:cood_switch} starts from an interior point ($p = (p_1,...,p_n) \in [0,1]^n$ where $\exists\ p_i \in (0,1)$) as compared to starting from a lattice point (for instance, we could start from $p = (y,0,...,0) \in \{0,1\}^n$) which is the $n$-length sequence obtained via appending $y$ with zeros. It turns out that starting from an interior point results in better accuracy on both Hamming and edit error rate metrics, thus supporting the usefulness of our ML relaxation result. In Fig.~\ref{fig:singletrace}, we compare the performance of Coordinate switch heuristic with the other trace reconstruction heuristics in Section~\ref{sec:Numerics}. We see that the coordinate switch with interior point initialization performs very similar to the true ML sequence (obtained via exhaustive search), in terms of both the Hamming error rate as well as the edit error rate. This intuitively supports the idea that this is a good heuristic for the ML optimization problem. However, at this point the heuristic is applicable for reconstruction using just a single trace and it is unclear on how to extend it to multiple traces. \begin{figure}[!h] \centering \includegraphics[scale=0.5]{Numerics/single_trace.pdf} \caption{Numerics for reconstruction from a single trace for a blocklength $n=20$. This plot compares the performance of coordinate switch heuristic (abbreviated ``Coodsw. interior init.'' and ``Coodsw. lattice init.'') with other trace reconstruction algorithms from Section~\ref{sec:Numerics}. ``ML'' refers to the true ML sequence obtained via an exhaustive search on all 20 length binary sequences. The interior point initialization initializes $p=(0.5,0.5,...,0.5)$ while the lattice point initialization appends the trace $y$ with zeros to obtain an $n$-length vector $p=(y,0,...,0)$.} \label{fig:singletrace} \end{figure} \subsection{Symbolwise MAP as the minimizer of Hamming error rate} \label{app:smap_hamming} Symbolwise MAP is an optimal estimator for minimizing the Hamming error rate for any channel, regardless of whether it is memoryless or not. This fact can be seen from the following argument: Consider a fixed observation $y$ (note that $y$ here can also be a collection of multiple observations, our arguments which follow remain unchanged) and that we aim to estimate a binary input sequence $X$; let the estimate of the input be $\hat X(y)$. Note that the estimate is a function of observation $y$ alone. Now the Hamming error rate of any estimator given $y$ is the expectation (over all inputs) of number of symbol mismatches divided by the blocklength, i.e., \begin{align*} \frac{1}{n}\E \left[ \sum_{i=1}^n \mathbbm{1} \{X_i \neq \hat X_i(y)\} \Big| Y=y \right ] &= \frac{1}{n} \sum_{i=1}^n \E \left [ \mathbbm{1}\{X_i \neq \hat X_i(y)\} \Big| Y=y \right ]\\ & = \frac{1}{n} \sum_{i=1}^n \Pr\left ( X_i \neq \hat X_i(y)\Big| Y=y \right ) \\ & = \frac{1}{n} \sum_{i=1}^n \Bigg( \Pr(X_i = 0|Y=y)\Pr(\hat X_i(y) = 1|X_i = 0,Y=y) \\ & \hspace{1cm}+ \Pr(X_i = 1|Y=y)\Pr(\hat X_i(y) = 0|X_i = 1,Y=y) \Bigg ). \end{align*} But, $\hat X_i$ is a function of only $y$ and hence is conditionally independent of $X_i$ given $y$, which implies the following: \begin{align*} \frac{1}{n}\E \left[ \sum_{i=1}^n \mathbbm{1} \{X_i \neq \hat X_i(y)\} \Big| Y=y \right ] & = \frac{1}{n} \sum_{i=1}^n \Bigg( \Pr(X_i = 0|Y=y)\Pr(\hat X_i(y) = 1|Y=y) \\ & \hspace{2cm}+ \Pr(X_i = 1|Y=y)\Pr(\hat X_i(y) = 0|Y=y)\Bigg ). \end{align*} To simplify notation, let the posterior probabilities be $q_i(y) \triangleq \Pr(X_i = 1|Y=y)$ and let $\alpha_i(y) \triangleq \Pr(\hat X_i(y) = 1|Y=y)$. Note that $q_i(y)$ is a property of the channel and is fixed given $y$, while $\alpha_i(y)$ depends on the design of our estimator. With this, the above expression can be re-written as $$\frac{1}{n}\E \left[ \sum_{i=1}^n \mathbbm{1} \{X_i \neq \hat X_i(y)\} \Big| Y=y \right ] = \frac{1}{n} \sum_{i=1}^n \Bigg( (1-q_i(y)) \alpha_i(y) + q_i(y) (1-\alpha_i(y))\Bigg ).$$ The optimal assignment of $\alpha_i(y)$ to minimize this expression is $\alpha_i(y) = 1$ if $q_i(y) \geq 0.5$ and $\alpha_i(y) = 0$ otherwise, which coincides with the symbolwise MAP estimate. This proves the optimality of symbolwise MAP for minimizing the Hamming error rate given any observation $y$, for any channel. \section{Conclusions} \label{sec:conclusions} In this work we gave, to the best of our knowledge, the first results and techniques to compute posterior distributions over single and multiple deletion channels. We also provided a new perspective on the maximum-likelihood for the deletion channel by showing an equivalence between a discrete optimization problem and its relaxed version. In this process, we introduced a variety of tools (the relaxed binomial coefficient, edit graph and infiltration product) and demonstrated their use for analyzing deletion channels. We also presented numerical evaluations of our algorithms and showed performance improvements over existing trace reconstruction algorithms. \section{Introduction} \label{sec:intro} Sequence reconstruction over deletion channels, both with and without a codebook, has received considerable attention in the information theory as well as in the theoretical computer science literature. From an information theory perspective, reconstruction over the deletion channel, or more specifically a maximum-likelihood (ML) argument for the deletion channel, would give further insight on the capacity of the deletion channel, a long-standing open problem (see \cite{mitzenmacher2009survey}). To quote \cite{mitzenmacher2009survey} -- ``at the very least, progress in this direction would likely surpass previous results on the capacity of the deletion channels''. Yet, there are no results on reconstruction over a deletion channel with statistical guarantees -- in this work, we take a step in this direction. On the other hand, the problem of \textit{trace reconstruction}, as introduced in \cite{Batu2004}, has received renewed interest in the past few years (see \cite{Holenstein2008}, \cite{Peres2017}, \cite{De2017}, \cite{holden18}, \cite{Nazarov:2017}, \cite{holden2018lower}, \cite{chase2019new}). The problem of trace reconstruction can be stated simply as follows: consider a sequence $X$ which is simultaneously passed through $t$ independent deletion channels to yield $t$ deleted observations (also called \textit{traces}) of $X$ (see Fig.~\ref{fig:tdeletion}). How many such traces are needed to reconstruct $X$ perfectly? A variety of upper and lower bounds for this problem have been proposed, both for worst case and average case reconstruction. Our problem definition, stated in the following paragraph, is closely related to the average case trace reconstruction. \begin{figure}[!h] \begin{center} \includegraphics[scale=0.2]{tdeletion.pdf} \caption{$t$-deletion channel model: sequence $X$ passed through $t$ independent deletion channels to yield $t$ \textit{traces}. We aim to estimate $X$ from the $Y^{(i)}$s.} \label{fig:tdeletion} \end{center} \end{figure} \noindent \textbf{Problem definition.} Given an input sequence of length $n$ (known apriori), the independently and identically distributed (i.i.d.) deletion channel deletes each input symbol indepedently with probability $\delta$, producing at its output a subsequence of the input sequence. Consider a sequence $X$ passed through $t$ ($t$ is fixed) such deletion channels as shown in Fig.~\ref{fig:tdeletion}. We call this the $t$-deletion channel model. We ask two questions: \begin{enumerate} \item For $t=1$ (see Fig.~\ref{fig:1deletion}, also called the single deletion channel model), and when $X_i \sim\ \text{ind. Ber}(p_i)$, compute the posterior distributions of $X_i$ given the trace $Y$. \begin{figure}[!h] \begin{center} \includegraphics[scale=0.25]{1deletion.pdf} \caption{The single deletion channel model. We assume $X_i \sim\ \text{ind. Ber}(p_i)$.} \label{fig:1deletion} \end{center} \end{figure} \item In the $t$ deletion channel model, for a fixed $t$ assume that $X_i \sim\ \text{i.i.d. Ber}(0.5)$ and compute the posterior distributions of $X_i$ given all traces $Y^{(1)}, Y^{(2)},...,Y^{(t)}$. \end{enumerate} Note that solving 1) above doesn't lead to a natural solution for 2). This is because for a memoryless channel, we have $Y^{(j)} - X_i - Y^{(k)}$ and hence $\Pr(X_i=\alpha|Y^{(j)}, Y^{(k)}) \propto \Pr(X_i=\alpha|Y^{(j)}) \Pr(X_i=\alpha|Y^{(k)})$; so one could independently combine the posterior probabilities from each noisy observation. This is not the case for deletion channels since the markov chain $Y^{(j)} - X_i - Y^{(k)}$ no longer holds. More intuitively, one needs to first ``align'' the traces for computing the likelihoods. We point out that the problem considered in 2) asks a question complementary to the trace reconstruction: given a fixed (possibly a few) number of traces, what is our ``best'' guess of $X$? We provide algorithms which do this. Unlike trace reconstruction, we are not concerned with perfect reconstruction (since perfect reconstruction may not be possible with just a few traces), although it should also be obvious that performance guarantees for our algorithms (not a part of this work) would naturally lead to upper bounds for trace reconstruction. Deletion channel by itself is known to be notoriously difficult to analyse. As stated earlier, the capacity of a single deletion channel is still unknown (\cite{diggavi2007capacity,diggavi2006information,diggavi2001transmission}); as are optimal coding schemes. Recent works have looked at the design of codes for deletion channels (\cite{ratzer2005marker,ratzer2000codes,thomas2017polar}); these works consider use of a codebook (we do not). As a result, statistical estimation over deletion channels is also a difficult problem due its highly combinatorial nature. To the best of our knowledge, as yet there are no efficient estimation algorithms over deletion channels with statistical guarantees; not even for ML over a single deletion channel. \noindent \textbf{Biological motivation.} Trace reconstruction in itself was motivated, in part, by problems DNA sequence reconstruction. One such problem was to infer the DNA sequence of a common ancestor from the samples of its descendants. We argue that our problem definition fits more naturally in such a scenario since perfect reconstruction may not be feasible or even possible. Our motivation for considering this problem also comes from a recent DNA sequencing technology called \textit{nanopore sequencing}. The $t$-deletion channel model is a simplistic model to approximately capture the process of a DNA sequence passed through a nanopore sequencer\footnote{As seen in \cite{Mao2017},\cite{MDK17} there are more complicated effects of the nanopore reader not captured in this simple representation.}. Very recently, a variant of the trace reconstruction problem called \textit{coded trace reconstruction} has been proposed, motivated by portable DNA-based data storage systems using DNA nanopores (see \cite{abroshan2019coding}, \cite{cheraghchi2019coded}, \cite{brakensiek2019coded}) and we believe that the ideas in this work may prove useful in such a setting. There are other works on sequence assembly (see for example, \cite{Li09fastand}, \cite{Shomorony2016}), where multiple short reads (from different segments of a sequence) are used to reconstruct the bigger sequence. This work differs from sequence assembly since we are interested to infer the entire length sequence and not just small segments of it (which are then ``stitched'' together in sequence assembly). \noindent \textbf{Tools and techniques.} In terms of theoretical tools, the series of books by Lothaire (\cite{lothaire1997combinatorics,lothaire2002algebraic,lothaire2005applied}) extensively use algebraic tools for problems in the combinatorics of sequences (or \textit{words}), and our work is inspired by such techniques. We borrow many of their notations and results for our work. \noindent \textbf{Contributions.} {\color{red}} Our main contribution is to provide tools to visualize and analyze error events (described in the next section) for the multiple deletion channel model in Fig.~\ref{fig:tdeletion}. We also provide algorithms to solve the problems stated in 1) and 2) earlier in the section. \begin{itemize}[wide=5pt] \item In section~\ref{sec:1deletion}, for the single deletion channel model, we provide an $O(n^2)$ algorithm to calculate the symbolwise posterior probabilities $\Pr(X_i=1|Y)\ \forall\ i$ when $X_i \sim \text{ind. Ber}(p_i)$. \item In Section~\ref{sec:exactsmap}, for the $t$-deletion channel model, we give an $O(2^t n^{t+2})$ algorithm to calculate the symbolwise posterior probabilities $\Pr(X_i = 1|Y_1,...,Y_t)$ when $X_i \sim \text{ind. Ber}(0.5)$. \end{itemize} \section{Introduction} \label{sec:intro} Sequence reconstruction over deletion channels, both with and without a codebook, has received considerable attention in the information theory as well as in the theoretical computer science literature. From an information theory perspective, reconstruction over the deletion channel, or more specifically a maximum-likelihood (ML) argument for the deletion channel, would give further insight on the capacity of the deletion channel, a long-standing open problem (see \cite{mitzenmacher2009survey}). To quote \cite{mitzenmacher2009survey} -- ``at the very least, progress in this direction would likely surpass previous results on the capacity of the deletion channels''. Yet, there are no results on reconstruction over a deletion channel with statistical guarantees. In this work, we take steps in this direction. In this space, the problem of \textit{trace reconstruction}, as introduced in \cite{Batu2004}, has also received renewed interest in the past few years (see \cite{Holenstein2008,Peres2017}, \cite{De2017}, \cite{holden18}, \cite{Nazarov:2017}, \cite{holden2018lower}, \cite{chase2019new}). The problem of trace reconstruction can be stated simply as follows: consider a sequence $X$ which is simultaneously passed through $t$ independent deletion channels to yield $t$ output subsequences (also called \textit{traces}) of $X$ (see Fig.~\ref{fig:tdeletion}). How many such traces are needed to reconstruct $X$ perfectly? A variety of upper and lower bounds for this problem have been proposed, both for worst case and average case reconstruction. Our problem formulation is complementary to this, as we discuss next. \begin{figure}[!h] \begin{center} \includegraphics[scale=0.2]{tdeletion.pdf} \caption{The $t$-trace deletion channel model: the sequence $X$ is passed through $t$ independent deletion channels to yield $t$ \textit{traces}. We aim to estimate $X$ from the $Y^{i}$s.} \label{fig:tdeletion} \end{center} \end{figure} \noindent \textbf{Problem formulation.} Given an input sequence of length $n$ (known apriori), the independently and identically distributed (i.i.d.) deletion channel deletes each input symbol indepedently with probability $\delta$, producing at its output a subsequence of the input sequence. Consider a sequence $X$ passed through $t$ ($t$ is fixed) such deletion channels as shown in Fig.~\ref{fig:tdeletion}. We call this the $t$-trace deletion channel model. We ask four main questions: \begin{figure}[!h] \begin{center} \includegraphics[scale=0.2]{1deletion.pdf} \caption{The single-trace deletion channel model.} \label{fig:1deletion} \end{center} \end{figure} \begin{enumerate}[leftmargin = *] \item \textbf{Sequencewise maximum-likelihood with one trace:} For $t=1$ (also called \textit{single-trace deletion channel}, see Fig.~\ref{fig:1deletion}), what is the maximum-likelihood estimate of $X$ having observed $Y=y$, i.e., a solution to $\argmax\limits_{x\in \{0,1\}^n}\ \Pr(Y=y|X=x)$. \vspace{8pt} \item \textbf{Sequencewise maximum-likelihood with multiple traces:} For a fixed $t$, with $t>1$, what is the maximum-likelihood estimate of $X$ having observed $Y^{1}=y^1,Y^{2}=y^2,...,Y^{t}=y^t $, i.e., $$\argmax\limits_{x\in \{0,1\}^n}\ \Pr(Y^{1}=y^1,Y^{2}=y^2,...,Y^{t}=y^t|X=x).$$ \vspace{-12pt} \item \textbf{Symbolwise MAP with one trace:} For $t=1$ and $X_i \sim\ \text{ind. Ber}(p_i)$ in Fig.~\ref{fig:1deletion}, what are the posterior distributions of $X_i$ given the trace $Y=y$, i.e., compute $\Pr(X_i=\alpha|Y=y)$. \item \textbf{Symbolwise MAP with multiple traces:} For a fixed $t$, with $t>1$ and $X_i \sim\ \text{i.i.d. Ber}(0.5)$ in Fig.~\ref{fig:tdeletion}, what are the posterior distributions of $X_i$ given all traces $Y^{1}=y^1, Y^{2}=y^2,...,Y^{t}=y^t$, i.e., compute $\Pr(X_i=\alpha|Y^{1}=y^1, Y^{2}=y^2,...,Y^{t}=y^t)$. \end{enumerate} \vspace{5mm} \noindent We make a few notes. \begin{itemize}[leftmargin = *] \item For a channel with memory such as the deletion channel, the symbolwise MAP/ML estimate and sequencewise MAP/ML estimate are not equivalent. For example, consider $t=1$, $n =6$ in Fig.~\ref{fig:1deletion} and say we observe the trace $Y = 1010$. The symbolwise MAP estimate with uniform priors for this case can be computed to be $\hat X_{smap} = 100110$ whereas the sequencewise ML estimate is $\hat X_{ml} = 101010$. \item An answer to 3) above doesn't lead to a natural solution for 4) which is also due to deletion channels possessing memory. In particular, for a memoryless channel, we have $Y^{j}_i - X_i - Y^{k}_i$ and hence $\Pr(X_i=\alpha|Y^{j}, Y^{k}) \propto \Pr(Y^{j}_i, Y^{k}_i|X_i=\alpha) = \Pr(Y^{j}_i|X_i=\alpha) \Pr(Y^{k}_i|X_i=\alpha)\propto \Pr(X_i=\alpha| Y^{j}) \Pr(X_i=\alpha | Y^{k})$; so one could first obtain the posterior probabilities from each independent observation and combine them after. However, this is not the case for deletion channels since the markov chain $Y^{j}_i - X_i - Y^{k}_i$ no longer holds. As a result, one first needs to ``align'' all the observations in order to compute the likelihoods. \item Solving 2) and 4) naturally leads to two different algorithms for average-case trace reconstruction -- one that selects the most likely sequence $X$ and the other that selects the most likely value for each symbol $X_i$. However, the problem formulations in 3) and 4) ask a question complementary to that of trace reconstruction: given a fixed (possibly a few) number of traces, what is our ``best'' guess of $X$? The two problems 2) and 4) have different quantification of the word ``best''. Unlike trace reconstruction, we are not concerned with perfect reconstruction (since perfect reconstruction may not be possible with just a few traces). We also note that error rate guarantees for our algorithms (not a part of this work) would naturally lead to upper bounds for trace reconstruction. \item The challenges associated with solving 1) and 2) and solving 3) and 4) are very different. On the one hand, solving 1) and 2) amounts to discovering alternate, equivalent or approximate formulations for the seemingly difficult discrete optimization problems. On the other hand, the challenge with 3) and 4) involves the design of efficient algorithms that are capable of exactly computing/approximating the symbolwise posterior probabilities, for which ``closed form'' expressions can be derived. \end{itemize} \vspace{5mm} \noindent \textbf{Contributions.} Our main contributions are as follows. \begin{itemize}[leftmargin=*] \item We introduce mathematical tools and constructs to visualize and analyze single-trace and $t$-trace deletion error events (see Section~\ref{sec:notation}). \item For the single-trace deletion channel, we establish an equivalence between finding the optimal ML decoder and a continuous optimization problem we introduce (see Section~\ref{sec:1deletion_ML}). This equivalence allows for the use of existing techniques for continuous optimization to be employed for a seemingly difficult discrete optimization problem. This continuous optimization problem also turns out to be a signomial optimization. Furthermore we also provide a polynomial time trace reconstruction heuristic with multiple traces that exploits this formulation. \item In Section~\ref{sec:1deletion}, we prove the following: \begin{theorem} For the single-trace deletion channel model with priors $X_i \sim \text{ind. Ber}(p_i)$ and observed trace $Y=y$, the symbolwise posterior probabilities $\Pr(X_i=1|Y=y)\ \forall\ i$ can be computed in $O(n^2)$ time complexity. \end{theorem} \item In Section~\ref{sec:exactsmap}, we prove the following: \begin{theorem} For the $t$-trace deletion channel model with priors $X_i \sim \text{i.i.d. Ber}(0.5)$ and observed traces $Y^{1}=y^1,...,Y^{t}=y^t$, the symbolwise posterior probabilities $\Pr(X_i = 1|Y^{1}=y^1,...,Y^{t}=y^t)\ \forall\ i$ can be computed in $O(2^t n^{t+2})$ time complexity.\\ \end{theorem} \end{itemize} \noindent \textbf{Tools and techniques.} In terms of theoretical tools, the series of books by Lothaire (\cite{lothaire1997combinatorics,lothaire2002algebraic,lothaire2005applied}) extensively use algebraic tools for problems in the combinatorics of sequences (or \textit{words}), and our work is inspired by such techniques. We borrow some notation and leverage a few of their results in our work. \\ \noindent \textbf{Biological motivation.} Trace reconstruction in itself was motivated, in part, by problems in DNA sequence reconstruction. One such problem was to infer the DNA sequence of a common ancestor from the samples of its descendants. Our problem definition, that considers a fixed value of $t$, would fit naturally in a scenario with a fixed number of descendants where perfect reconstruction may not be possible. Our motivation for considering this problem also comes from a recent DNA sequencing technology called \textit{nanopore sequencing}. The $t$-trace deletion channel model is a simplistic model to approximately capture the process of a DNA sequence passed through a nanopore sequencer\footnote{As seen in \cite{Mao2017},\cite{MDK17} there are more complicated effects of the nanopore reader not captured in this simple representation.}. \\ \noindent \textbf{More related work.} Our work falls under the general umbrella of sequence reconstruction over deletion channels (also see Levenshtein's work \cite{levenshtein2001efficient}), where we offer, to the best of our knowledge, the first non-trivial results on maximum likelihood and maximum aposteriori estimates for the single and multiple deletion channel. As mentioned earlier, the complementary problem of trace reconstruction falls closest to this work. The deletion channel by itself is known to be notoriously difficult to analyse. As stated earlier, the capacity of a single deletion channel is still unknown (\cite{diggavi2007capacity,diggavi2006information,diggavi2001transmission}); as are optimal coding schemes. Prior works have looked at the design of codes for deletion channels (\cite{ratzer2005marker,ratzer2000codes,thomas2017polar}); these works consider use of a codebook (we do not). Statistical estimation over deletion channels is a difficult problem to analyze due its highly combinatorial nature. To the best of our knowledge, as yet there are no efficient estimation algorithms over deletion channels with statistical guarantees. Very recently, a variant of the trace reconstruction problem called \textit{coded trace reconstruction} has been proposed, motivated by portable DNA-based data storage systems using DNA nanopores (see \cite{abroshan2019coding}, \cite{cheraghchi2019coded}, \cite{brakensiek2019coded}) and we believe that the ideas in this work may prove useful in such a setting. There are other works on sequence assembly (see for example, \cite{Li09fastand}, \cite{Shomorony2016}), where multiple short reads (from different segments of a sequence) are used to reconstruct the bigger sequence. This work differs from sequence assembly since we are interested in inferring the entire length sequence and not just small segments of it (which are then ``stitched'' together in sequence assembly).\\ \noindent \textbf{Paper Organization.} Section~\ref{sec:notation} introduces our notation and visualization tools for the single and $t$-trace channel error events; Section~\ref{sec:1deletion_ML} provides a result concerning questions 1) and 2) wherein we prove the equivalence of ML decoding in question 1) to solving a continuous optimization problem; Section~\ref{sec:1deletion} answers question 3) for the single-trace channel; Section~\ref{sec:exactsmap}) answers question 4) for the $t$-deletion channel; Section~\ref{sec:Numerics} gives numerical evaluations; and Section~\ref{sec:conclusions} concludes the paper. \section{Symbolwise MAP for the $t$-trace deletion channel} \label{sec:exactsmap} In this section, we put to use the ideas and constructs introduced in section~\ref{sec:notation} to exactly compute the symbolwise posterior probabilities given $t$-traces, which in turn gives a symbolwise MAP estimate with uniform input priors (motivated by average case trace reconstruction). With this formulation the symbolwise MAP with uniform priors can be seen as a minimizer of the symbol error rate in the context of average case trace reconstruction. In Appendix~\ref{app:remnant_postprob}, we also provide a method to compute the symbolwise posterior probabilities for the remnant channel -- we encourage the reader to use this appendix as a warm-up. For the $t$-trace deletion channel, similar expressions arise due to the channel equivalence result of Theorem~\ref{thm:channel_equiv}. Let $\mathcal A = \{0,1\}$, and assume that $X\sim $ Uniform $\mathcal A^n$. Our goal is to compute the symbolwise posterior probabilities $\Pr(X_i=1|Y^1=y^1,...,Y^t=y^t)$, where $Y^j$ is the $j^{th}$ trace. Our proposed algorithm is provided in Alg.~\ref{alg:exact_smap} and estimates the symbolwise MAP (with uniform priors). We can directly leverage Alg.~\ref{alg:exact_smap} to reconstruct the input as follows: for each index $i$, compute $\Pr(X_i =1|Y^1=y^1,...,Y^t=y^t)$ and decide \begin{align*} \hat{X}_i = \begin{cases} 1,\quad &$if$\ \Pr(X_i =1|Y^1=y^1,...,Y^t=y^t)\geq 0.5 \\ 0, \quad &$otherwise$. \end{cases} \end{align*} Through the rest of this section, we show how to compute $\Pr(X_i =1|Y^1=y^1,...,Y^t=y^t)$\footnote{Symbolwise MAP with non-uniform priors is part of on-going work.} in two steps: \begin{itemize} \item We first give an expression for $\Pr(X_i =1|Y^1=y^1,...,Y^t=y^t)$ which sums over potentially an exponential number of terms. \item We then show that this summation can be computed in polynomial time (polynomial in the blocklength $n$). \end{itemize} \noindent \textbf{Step 1: An expression for $\Pr(X_i =1|Y^1=y^1,...,Y^t=y^t)$.} \begin{theorem} \label{thm:exactSMAP_posteriorprob} Assume $X\sim $ Uniform $\mathcal A^n$ or equivalently $X_i \sim\ \text{Ber}(0.5)$. The posterior probability of the $i^{th}$ bit given the $t$ traces can be expressed as \begin{align*} \Pr(X_i =1|Y^1=y^1,...,Y^t&=y^t) \\ = & \Bigg[ \sum_{k=0}^n 2^{n-k-1}{n-1 \choose k} \sum_{w||w|=k} \langle y^1 \uparrow ... \uparrow y^t,w \rangle \\ &+ \sum_{k=0}^n \sum_{j=1}^k 2^{n-k}{i-1 \choose j-1}{n-i \choose k-j} \sum_{\substack{w| |w|=k,\\w_j=1}} \langle y^1 \uparrow ... \uparrow y^t,w \rangle \Bigg] \Big/ \\ &\Bigg[ \sum_{k=0}^n 2^{n-k} {n \choose k} \sum_{\substack{w| |w|=k}} \langle y^1 \uparrow ... \uparrow y^t,w \rangle \Bigg]. \numberthis \label{eq:posterior_prob} \end{align*} \end{theorem} Note that the summation index, $w| |w|{=}k$ is over all sequences $w$ of length $k$; this is an alternate expression for $w|w{\in}\mathcal A^k$. We follow this convention throughout the rest of the paper. \begin{proof} \begin{align*} \Pr(X_i=1&|Y^1=y^1,...,Y^t=y^t) = \sum_{\substack{x||x|=n,\\x_i=1}} \Pr(X=x|Y^1=y^1,...,Y^t=y^t)\\ &\overset{(a)}{=} \frac{1}{2^n \Pr(Y^1=y^1,...,Y^t=y^t)} \sum_{\substack{x||x|=n,\\x_i=1}} \Pr(Y^1=y^1,...,Y^t=y^t|X=x)\\ &\overset{(b)}{=} \frac{1}{2^n \Pr(Y^1=y^1,...,Y^t=y^t)} \sum_{\substack{x||x|=n,\\x_i=1}} \prod_{j=1}^t\Pr(Y^{j}=y^j|X=x), \end{align*} where $(a)$ uses Bayes' principle and $(b)$ is because each deletion channel acts independently. Recall that for a deletion channel with deletion probability $\delta$, $\Pr(Y=y|X=x)={x \choose y}\delta^{|x|-|y|}(1-\delta)^{|y|}$. Also, using the fact that $\Pr(Y^1=y^1,...,Y^t=y^t)=\sum\limits_{\substack{x||x|=n}}\Pr(x) \Pr(Y^1=y^1,...,Y^t=y^t|X=x)$ we have, \begin{align*} \Pr(X_i=1|Y^1=y^1,...,Y^t=y^t)= \frac{\sum\limits_{\substack{x||x|=n,\\x_i=1}} {x \choose y^1}...{x \choose y^t}}{\sum\limits_{\substack{x||x|=n}} {x \choose y^1}...{x \choose y^t}}. \numberthis \label{eq:thmexactsmap_proofterm0} \end{align*} We first simplify the numerator $\sum\limits_{\substack{x||x|=n,\\x_i=1}} {x \choose y^1}...{x \choose y^t}$; the denominator can be simplified using the same approach. Now, \begin{align*} \sum\limits_{\substack{x||x|=n,\\x_i=1}} {x \choose y^1}...{x \choose y^t} &\overset{(a)}{=} \sum_{\substack{x||x|=n,\\x_i=1}} \sum_{w\in \{0,1\}^*} {x \choose w} \langle y^1 \uparrow ... \uparrow y^t,w \rangle \\ &=\sum_{w\in \mathcal A^*} \langle y^1 \uparrow ... \uparrow y^t,w \rangle \sum_{\substack{x||x|=n,\\x_i=1}}{x \choose w}\\ &\overset{(b)}{=}\sum_{w\in \mathcal A^*} 2^{n-|w|} \langle y^1 \uparrow ... \uparrow y^t,w \rangle \left(\frac{1}{2}{n-1 \choose |w|}+\sum_{j|w_j=1}{i-1 \choose j-1}{n-i \choose |w|-j}\right) \end{align*} where $(a)$ is due to Lemma~\ref{lemma:bin_inf_relation} and $(b)$ due to Lemma~\ref{lemma:smapsum} (both introduced in \cite{Srini2018}); see Appendix~\ref{app:bin_inf_lemma} and Appendix~\ref{app:smapsum} for the statement and proof. \noindent Therefore we have, \begin{align*} \sum\limits_{\substack{x||x|=n,\\x_i=1}} {x \choose y^1}...{x \choose y^t} &\overset{(a)}{=} \sum_{k=0}^{\infty} 2^{n-k-1}{n-1 \choose k} \sum_{w| |w|=k} \langle y^1 \uparrow ... \uparrow y^t,w \rangle \\ &\hspace{1cm}+ \sum_{k=0}^{\infty} \sum_{j=1}^k 2^{n-k}{i-1 \choose j-1}{n-i \choose k-j} \sum_{\substack{w| |w|=k,\\w_j=1}} \langle y^1 \uparrow ... \uparrow y^t,w \rangle \\ &\overset{(b)}{=} \sum_{k=0}^n 2^{n-k-1}{n-1 \choose k} \sum_{w| |w|=k} \langle y^1 \uparrow ... \uparrow y^t,w \rangle \\ &\hspace{1cm}+ \sum_{k=0}^n \sum_{j=1}^k 2^{n-k}{i-1 \choose j-1}{n-i \choose k-j} \sum_{\substack{w| |w|=k,\\w_j=1}} \langle y^1 \uparrow ... \uparrow y^t,w \rangle, \numberthis \label{eq:thmexactsmap_proofterm1} \end{align*} where in $(a)$ we first fix $|w|$ and then sum over all $w$ of the given length and $(b)$ holds because the combinatorial terms are $0$ when $k>n$. A similar analysis gives \begin{align*} \sum\limits_{x| |x|=n} &{x \choose y^1}...{x \choose y^t} = \sum_{k=0}^n 2^{n-k} {n \choose k} \sum_{\substack{w| |w|=k}} \langle y^1 \uparrow ... \uparrow y^t,w \rangle.\numberthis \label{eq:thmexactsmap_proofterm2} \end{align*} Plugging \eqref{eq:thmexactsmap_proofterm1} and \eqref{eq:thmexactsmap_proofterm2} in \eqref{eq:thmexactsmap_proofterm0}, we get the expression in Theorem~\ref{thm:exactSMAP_posteriorprob}, \begin{align*} \Pr(X_i =1|Y^1=y^1,...,&Y^t=y^t) \\ = & \Bigg[ \sum_{k=0}^n 2^{n-k-1}{n-1 \choose k} \sum_{w||w|=k} \langle y^1 \uparrow ... \uparrow y^t,w \rangle \\ &+ \sum_{k=0}^n \sum_{j=1}^k 2^{n-k}{i-1 \choose j-1}{n-i \choose k-j} \sum_{\substack{w| |w|=k,\\w_j=1}} \langle y^1 \uparrow ... \uparrow y^t,w \rangle \Bigg] \Big/ \\ &\Bigg[ \sum_{k=0}^n 2^{n-k} {n \choose k} \sum_{\substack{w| |w|=k}} \langle y^1 \uparrow ... \uparrow y^t,w \rangle \Bigg]. \end{align*} \end{proof} \noindent \textbf{Step 2: Dynamic program to compute $\sum\limits_{w| |w|=k} \langle y^1 \uparrow ... \uparrow y^t,w \rangle$ and $\sum\limits_{\substack{w| |w|=k,\\w_j=1}} \langle y^1 \uparrow ... \uparrow y^t,w \rangle$.} Note that the number of sequences $w$ such that $|w|=k$ is $O(2^k)$ so a naive evaluation is exponential in the blocklength $n$. We can, however, exploit the edit graph to come up with a dynamic program resulting in an algorithm which is polynomial in $n$. Recall that in the edit graph, $\langle y^1 \uparrow ... \uparrow y^t,w \rangle$ is equal to the number of distinct paths from the origin $(0,...,0)$ to the destination $(|y^1|,...,|y^t|)$ and which correspond to $w$. Hence, \begin{enumerate}[wide=0pt] \item[(a)] $\sum\limits_{w| |w|=k} \langle y^1 \uparrow ... \uparrow y^t,w \rangle$ is the number of distinct paths of length $k$ from origin to destination and, \item[(b)] $\sum\limits_{\substack{w| |w|=k,\\w_j=1}} \langle y^1 \uparrow ... \uparrow y^t,w \rangle$ is the number of such paths of length $k$ such that the $j^{th}$ edge of the path corresponds to a `1'. \end{enumerate} \noindent With this interpretation, the dynamic program for (a) follows naturally -- the number of $k$-length paths from the origin to any vertex is the sum of the number of $(k{-}1)$-length paths from the origin to all incoming neighbors of the vertex. To make this formal, associate a polynomial (in $\lambda$) for each vertex, such that the coefficient of $\lambda^k$ is equal to the number of paths of length $k$ from the origin to $v$: we call it the "forward-potential" polynomial $p^{for}_v(\lambda)$ for vertex $v$, the coefficient of $\lambda^k$ as earlier is denoted by $\langle p^{for}_v(\lambda),\lambda^k \rangle $. The dynamic program to compute $p^{for}_v(\lambda)$ for all $v$ can be expressed as: \begin{equation} p^{for}_v(\lambda) = \sum_{u|u\rightarrow v} \lambda p^{for}_u(\lambda). \end{equation} With this definition, we have $$\sum\limits_{w| |w|=k} \langle y^1 \uparrow ... \uparrow y^t,w \rangle =\langle p^{for}_{destination}(\lambda),\lambda^k \rangle.$$ In the example in Fig.~\ref{fig:editgraph_smap1}, one could do the following: order the vertices $(0,0)$ to $(3,3)$ lexicographically and then compute $p^{for}_v(\lambda)$ in the same order. Because of the directed grid nature of the edit graph, every vertex has incoming neighbors which are lexicographically ahead of itself. Also we initialize $p^{for}_{(0,0)}(\lambda)=1$. For the example in Fig.~\ref{fig:editgraph_smap1}, the forward-potentials are shown in Fig.~\ref{fig:editgraph_smap2}. The complexity of this dynamic program is $O(2^tn^{t+1})$ as it goes over $O(n^t)$ vertices and for each vertex it sums $O(2^t)$ polynomials, each of degree $O(n)$. \begin{figure}[!h] \centering \includegraphics[scale=0.25]{editgraph_smap2.pdf} \caption{The forward-potential $p^{for}_v(\lambda)$ at each vertex.} \label{fig:editgraph_smap2} \end{figure} We compute (b) as follows: pick an edge $(u{\rightarrow}v)$ which corresponds to `1', count the number of $(j{-}1)$-length paths from origin to $u$ and multiply it with the number of $(k{-}j)$-length paths from $v$ to the destination -- this is exactly the number of paths of length $k$ such that its $j^{th}$ edge is $(u{\rightarrow}v)$. Summing this term for all such edges which correspond to 1 gives us the term in (b). Note that we have already computed the number of $k$-length paths ($\forall k$) from origin to every vertex in $p^{for}_v(\lambda)$ . We can similarly compute the number of $k$-length paths ($\forall k$) from every vertex to the destination as $p^{rev}_v(\lambda)$ -- the "reverse potential" polynomial. The dynamic program for $p^{rev}_v(\lambda)$ is: \begin{equation} p^{rev}_v(\lambda) = \sum_{u|v\rightarrow u} \lambda p^{rev}_u(\lambda), \end{equation} with $p^{rev}_{destination}(\lambda)=1$. The reverse potentials for the example in Fig.~\ref{fig:editgraph_smap1} is shown in Fig.~\ref{fig:editgraph_smap3}. Like in the case of forward potential, we first order the vertices reverse lexicographically and then invoke the dynamic program above sequentially to compute the reverse potential polynomial at each vertex. \begin{algorithm}[t!] \caption{Computing the forward-potentials $p^{for}_u(\lambda)$ }\label{alg:forward_pot} \begin{algorithmic}[1] \item Input: Edit graph {$\mathcal G(y^1,...,y^t)$}\\ Outputs: $p^{for}_v(\lambda)\ \forall\ v$ \State Order the vertices from $(0,0,...,0)$ to $(|y^1|,|y^2|,...,|y^t|)$ lexicogaphically; let the ordered list be $\mathcal V$ \State Initialise $p^{for}_{(0,...,0)}(\lambda)\gets 1$ \For{$v\ \in\ \mathcal V$} \State \textbf{assign} $p^{for}_v(\lambda)\gets \sum_{u|u\rightarrow v} \lambda p^{for}_u(\lambda)$ \EndFor \end{algorithmic} \end{algorithm} \begin{algorithm}[t!] \caption{Computing the reverse-potentials $p^{rev}_u(\lambda)$ }\label{alg:reverse_pot} \begin{algorithmic}[1] \item Input: Edit graph {$\mathcal G(y^1,...,y^t)$}\\ Outputs: $p^{rev}_v(\lambda)\ \forall\ v$ \State Order the vertices from $(|y^1|,|y^2|,...,|y^t|)$ to $(0,0,...,0)$ reverse lexicogaphically; let the ordered list be $\mathcal V$ \State Initialise $p^{rev}_{(|y^1|,|y^2|,...,|y^t|)}(\lambda)\gets 1$ \For{$v\ \in\ \mathcal V$} \State \textbf{assign} $p^{rev}_v(\lambda) \gets \sum_{u|v\rightarrow u} \lambda p^{rev}_u(\lambda)$ \EndFor \end{algorithmic} \end{algorithm} \begin{figure}[!h] \centering \includegraphics[scale=0.25]{editgraph_smap3.pdf} \caption{The reverse-potential $p^{rev}_v(\lambda)$ at each vertex.} \label{fig:editgraph_smap3} \end{figure} With this, the term in (b) can be expressed as: \begin{align*} \sum\limits_{\substack{w| |w|=k,\\w_j=1}}\langle y^1 \uparrow ... \uparrow y^t,w \rangle =\hspace{-2mm} \sum_{\substack{(u,v)|\\s(u\rightarrow v)=1}} \hspace{-2mm}\langle p^{for}_u(\lambda),\lambda^{j-1} \rangle \langle p^{rev}_v(\lambda),\lambda^{k-j} \rangle. \end{align*} Alg.~\ref{alg:exact_smap} now summarizes the computation of the posterior probabilities. This algorithm iterates over all the edges (we have $O((2n)^t)$ of these), and also $k,j$ ($O(n)$ each). The time complexity of Alg.~\ref{alg:exact_smap} hence is $O(2^tn^{t+2})$. \begin{algorithm}[t!] \caption{Symbolwise MAP with $t$ traces} \label{alg:exact_smap} \begin{algorithmic}[1] \item Input: Traces {$Y^1=y^1,...,Y^t=y^t$, input length $n$}\\ Output: $\hat X = \hat X_1\hat X_2...\hat X_n \State Construct edit graph $\mathcal G(y^1,...,y^t)$ \State Use Alg.~\ref{alg:forward_pot} and Alg.~\ref{alg:reverse_pot} on $\mathcal G(y^1,...,y^t)$ to calculate $p^{for}_v(\lambda)$ and $p^{rev}_v(\lambda)$ $\forall\ v$ \For{$k \in\ [0:n]$} \State \textbf{assign} $\sum\limits_{w| |w|=k} \langle y^1 \uparrow ... \uparrow y^t,w \rangle \gets \langle p^{for}_{destination}(\lambda),\lambda^k \rangle.$ \For{each $j \in\ [1:n]$} \State Initialize $temp \leftarrow $ 0 \For{each edge $u\rightarrow v\ \in\ \mathcal G$} \If{$s(u{\rightarrow} v)=$ `1'} \State $temp\ += \langle p^{for}_u(\lambda),\lambda^{j-1} \rangle \langle p^{rev}_v(\lambda),\lambda^{k-j} \rangle$ \EndIf \EndFor \State \textbf{assign} $\sum\limits_{\substack{w| |w|=k,\\w_j=1}} \langle y^1 \uparrow ... \uparrow y^t,w \rangle \gets temp$ \EndFor \EndFor \For{$i \in\ [1:n]$} \State Use \eqref{eq:posterior_prob} to compute $\Pr(X_i=1|Y^1=y^1,...,Y^t=y^t)$ \State $\hat X_i \leftarrow 1$ if $\Pr(X_i=1|Y^1=y^1,...,Y^t=y^t) > 0.5$ and $\hat X_i \leftarrow 0$ otherwise \EndFor \State \textbf{return} $\hat X_1\hat X_2...\hat X_n$ \end{algorithmic} \end{algorithm} \section{Notation and Tools} \label{sec:notations} \noindent \textbf{Basic notations:} In this work, we borrow a majority of the notation and tools from \cite{lothaire1997combinatorics} which deals with non-commutative algebra. We restate the definitions here for convenience. Calligraphic letters refer to sets, capitalized letters correspond to random variables and bold letters are used for functions. Let $\mathcal{A}$ be the set of all symbols. Throughout this work, we will focus on the case where $\mathcal{A}=\{0,1\}$, though our methods extend to arbitrarily large sets of finite size. Define $\mathcal{A}^n$ to be the set of all $n$-length sequences and $\mathcal{A}^*$ to be the set of all finite length sequences with symbols in $\mathcal{A}$. For a sequence $f$, $|f|$ denotes the length of $f$. For integers $i,j$, we define $[i:j] \triangleq \{i,i+1,...,j\}$ if $j\geq i$ and $[i:j] \triangleq \emptyset$ otherwise. Also define $[i] \triangleq [1:i]$.\\ \noindent \textbf{Binomial coefficient:} Given sequences $f$ and $g$ in $\mathcal{A}^*$, the number of subsequence patterns of $f$ that are equal to $g$ is called the \textit{binomial coefficient} of $g$ in $f$ and is denoted by $f \choose g$. For example, ${'apple' \choose 'ape'} = 2$ since $'ape'$ can be obtained from two (overlapping) subsequences of $'apple'$. When the alphabet $\mathcal{A}$ is of cardinality 1, ${f \choose g} = {|f| \choose |g|}$, the classical binomial coefficient with their respective lengths as the parameters. This definition hence could be thought of as a generalization of the classical binomial coefficients. We will denote by $e$ the sequence of length 0, and {define ${f \choose e} \triangleq 1\ \forall\ f\ \in\ \mathcal{A}^*$.} We also define the classical binomial coefficient ${a \choose b}\triangleq 0,$ whenever $b>a$ or $b<0$ for ease of use. The binomial coefficient is an integral aspect of this work and for analyzing error events in deletion channels because the input-output relation for a deletion channel (with deletion probability $\delta$, input $X$ and output $Y$) can be expressed as \begin{equation} \label{eq:in-out_relation} \Pr(Y=y|X=x) = {x \choose y} \delta^{|x|-|y|} (1-\delta)^{|y|}. \end{equation} The proof is straight-forward -- the number of distinct error events that give rise to $y$ from $x$ is exactly the number of subsequences of $x$ which are equal to $y$. Each of these error events has a probability $\delta^{|x|-|y|} (1-\delta)^{|y|}$, wherein the exponent of $\delta$ corresponds to the deleted symbols and the exponent of $1-\delta$ to the undeleted symbols. Given the definition of the binomial coefficient, the maximum-likelihood (ML) estimate over a deletion channel with observed output $Y$ can be cast in the following form: \begin{align*} \argmax_{x \in \mathcal C} {x \choose Y},\numberthis \label{eq:ML_deletion} \end{align*} where $\mathcal C$ is the chosen codebook. In the case of multiple deletion channels with observed traces $Y^{(1)},...,Y^{(t)}$, the ML formulation is similar: \begin{align*} \argmax_{x \in \mathcal C} \prod_{j=1}^{t} {x \choose Y^{(j)}}.\numberthis \label{eq:ML_multiple_deletion} \end{align*} As yet, there is no known efficient way to come up with a solution for the above two formulations, even for \eqref{eq:ML_deletion} with $\mathcal C = \{0,1\}^n$ (see \cite{mitzenmacher2009survey}). In this work, we attempt to take a step in this direction by showing that a continuous relaxation of \eqref{eq:ML_deletion} is equivalent to \eqref{eq:ML_deletion}. However, an efficient algorithm to solve the optimization \eqref{eq:ML_deletion} remains open. In the context of trace reconstruction, the ultimate pursuit would be an algorithm for \eqref{eq:ML_multiple_deletion} with $\mathcal C = \{0,1\}^n$ and error analysis thereof. \noindent We now describe a function which can be thought of as a real-valued extension of the binomial coefficient. This function is used in sections~\ref{sec:1deletion_ML} and \ref{sec:1deletion}. Consider the function $\mathbf F(\cdot)$ defined as: \begin{definition} \label{def:f} \begin{align*} &\mathbf F: \mathbb{R}^k \times \{0,1\}^l \rightarrow \mathbb{R},\\ \mathbf F(q, v)\triangleq &\begin{cases} \sum\limits_{\substack{\mathcal S|\mathcal S\subseteq [k],\\|\mathcal S|=l}} \quad \prod\limits_{i=1}^l q_{\mathcal S_i}^{v_i} (1-q_{\mathcal S_i})^{1-v_i} & 1 \leq l\leq k \\ 1 & 0=l\leq k \\ 0 & \text{else}. \end{cases} \end{align*} \noindent An alternate definition is as follows: consider a random vector $Z\in\{0,1\}^k$ such that $Z_i\sim$ ind. Ber$(q_i)$, let $q$ be the vector of probabilities of length $k$, $\mathcal S\subseteq [k]$ a subset of the indices of size $l$, and ${v}$ a binary vector of length $l$. Then, $$\mathbf F(q,v)=\sum_{\substack{\mathcal S||\mathcal S|=l}} \Pr(Z_{\mathcal S}= v).$$ Note that if $q$ is a vector of $0$'s and $1$'s, then $\mathbf F( q, v)={q \choose v}$, the binomial coefficient of $v$ in $q$. Thus, $\mathbf F(\cdot)$ could be interpreted as an extension of the binomial coefficient where one of the parameters can take values in $[0,1]^n$ instead of $\{0,1\}^n$. \end{definition} Though at first sight, $\mathbf F(q,v)$ sums over an exponential number of subsets, a dynamic programming approach can be used to compute it in $O(|v|^2)$ time complexity. The dynamic program is described in section~\ref{sec:1deletion}. \iffalse \noindent \textbf{Edit distance:} The edit distance $d_e(f,g)$ measures similarity between two sequences of possibly different lengths \cite{Navarro2001}. $d_e(f,g)$ is the minimum number of operations needed to transform $f$ to $g$, where the permitted operations are insertion, deletion or substitution of a symbol. In this work, we quantify the performance of algorithms in Section \ref{sec:Numerics} using the edit distance metric. \fi The following definitions and ideas are relevant only for \ref{sec:exactsmap} and can be omitted for the sections on single deletion channel. Before getting to the mathematical definitions, we first state a result of ours that aids in thinking about error events in multiple deletion channels. \subsection{An alternate interpretation of multiple deletion channel model} The events occurring in the $t$-deletion channel model can be categorized into two groups: \begin{enumerate} \item an input symbol is deleted in \textit{all} the $t$-traces, \item an input symbol is reflected in at least one of the traces. \end{enumerate} The error events of the first kind are in some sense ``not correctable" or even ``detectable" since it is impossible to tell what and where the deleted symbol could have been (although the probabilities need not be uniform). The events of the second kind, however, can still be detected although they could likely be confused with a large set of similar events. This thought process gives rise to a natural decomposition of the $t$-deletion channel model into a cascade of two channels: the first one being a deletion channel which captures error events of the first kind and the second one is what we call the \textit{remnant channel} which captures events of the second kind (see Fig.~\ref{fig:channel_equiv}). More precisely, the remnant channel is defined as follows: \begin{definition} \textit{Remnant channel:} an input symbol to the remnant channel is reflected in $k>0$ given outputs and deleted in the rest with a probability $\frac{\delta^{t-k}(1-\delta)^k}{1-\delta^t}$. \end{definition} It is easy to note that probability of the union of all possible events here is $\sum_{k=1}^t {t \choose k} \frac{\delta^{t-k}(1-\delta)^k}{1-\delta^t}=1$, validating our definition. \begin{restatable}{theorem}{channelequiv} \label{thm:channel_equiv} The $t$-deletion channel model and the cascade of the deletion channel with remnant channel shown in Fig.~\ref{fig:channel_equiv} are probabilistically equivalent, i.e., $$\Pr({Y}^{(1)},{Y}^{(2)},...,{Y}^{(t)}|X = x) = \Pr(\tilde{Y}^{(1)},\tilde{Y}^{(2)},...,\tilde{Y}^{(t)}|X = x).$$ \end{restatable} The formal proof of the theorem requires few more definitions and is relegated to the appendix. \begin{figure}[!h] \begin{center} \includegraphics[scale=0.4]{channel_equiv.pdf} \caption{A channel equivalence result: the $t$-deletion channel model in (a) is probabilistically equivalent to the the cascade of a deletion channel with the \textit{remnant channel} ($ \mathcal C_2$) in (b).} \label{fig:channel_equiv} \end{center} \end{figure} \noindent\textbf{Edit graph} (as defined in \cite{Gusfield1997}): We now define a graph construct which is closely related to the error events in the remnant channel. We start with a simple case and generalize subsequently. Define an \textit{edit graph} given two sequences $f$ and $g$, where every path connecting the ``origin'' to the ``destination'' on the edit graph yields a supersequence $h$ of $f,g$, where $h$ is ``covered'' by $f,g$ -- i.e., each symbol of $h$ comes from either $f$ or $g$ or both. In other words, given that $f$ and $g$ are the outputs of the remnant channel (with two outputs), each path from the origin of the edit graph to the destination corresponds to a possible input $h$ to the remnant channel and to an error event which resulted in $f$ and $g$ with input $h$. For $f$ and $g$ in $\mathcal A^*$, we form a graph $\mathcal{G}(f,g)$ with $(|f|+1)(|g|+1)$ vertices each labelled with a distinct pair $(i,j), 0\leq i\leq |f|,\ 0\leq j\leq |g|$. A directed edge $(i_1,j_1)\rightarrow(i_2,j_2)$ exists iff at least one of the following holds: \begin{enumerate} \item$i_2-i_1=1$ and $j_1=j_2$, or \item $j_2-j_1=1$ and $i_1=i_2$, or \item $i_2-i_1=1$, $j_2-j_1=1$ and $f_{i_2}=g_{j_2}$, \end{enumerate} where $f_i$ is the $i^{th}$ symbol of the sequence $f$. The origin is the vertex $(0,0)$ and the destination $(|f|,|g|)$. \begin{figure}[!h] \centering \includegraphics[scale=0.25]{editgraph_smap1.pdf} \caption{ Edit graph for sequences $f=$ `001' and $g=$ `101'. An easy way to think about this is to write down $f$ vertically with each symbol aligned to a vertical set of edges and $g$ horizontally likewise. A diagonal edge in a small square exists if the corresponding $f$ and $g$ symbols are equal. The thick red edges form a path from the origin to the destination; this path corresponds to the sequence `0101' -- append the corresponding symbol at the left of an edge if it's vertical or diagonal, otherwise append the symbol at the top. It is also easy to verify that 0101 is a supersequence of both $f$ and $g$, and could be obtained as a covering of $f$ and $g$; the path itself gives one such covering. This covering also corresponds to an error event in the remnant channel which would result in outputs $f$ and $g$ with input $h=$ `0101' -- more precisely, the error event is one in which the first symbol of $h$ is deleted only in $g$, the second symbol is deleted only in $f$ and the third and fourth symbols not deleted in either $f$ or $g$.} \label{fig:editgraph_smap1} \end{figure} Let $p=((i_1,j_1),(i_2,j_2),...,(i_m,j_m))$ be a path in $\mathcal{G}(f,g)$. We define $ s(p)$ to be the sequence corresponding to the path. Intuitively, $s(p)$ is formed by appending symbols in the following way: append the corresponding $f$ symbol for a vertical edge, $g$ symbol for horizontal edge, and $f$ or $g$ symbol for diagonal edge (see example Fig.~\ref{fig:editgraph_smap1}). Any path from $(0,0)$ to $(|f|,|g|)$ corresponds to a supersequence of $f$ and $g$ and which is ``covered" by $f$ and $g$. More formally, define $ s(p)\triangleq x_1x_2...x_{m-1}$ where $$x_k = \begin{cases} f_{i_{k+1}} \quad\text{if }j_{k}=j_{k+1},\\ g_{j_{k+1}} \quad\text{if }i_{k}=i_{k+1},\\ f_{i_{k+1}} \quad\text{else.} \end{cases} $$ The construct of edit graph can be extended to more than 2 sequences with the same idea. For sequences $f_1,f_2,...,f_t$, construct a $t$-dimensional grid with a number of vertices $(|f_1|+1)(|f_2|+1)...(|f_t|+1)$ labeled from $(0,0,...,0)$ to $(|f_1|,|f_2|,...,|f_t|)$. A vertex $u=(i_1,i_2,...,i_t)$ is connected to $v=(j_1,j_2,...,j_t)$ (we say $u \rightarrow v$) iff both of the following conditions are met: \begin{itemize} \item $j_l=i_l$ or $j_l=i_l+1$ $\forall\ l\in [t]$, i.e., $(i_1,...,i_t)$ and $(j_1,...,j_t)$ are vertices of a particular unit cube. Only these type of vertices can share an edge in the grid graph. \item Let $\mathcal T \subseteq [t]$ be the collection of indices where $j_l=i_l+1$. Then $f_{i_l}$ is same $\forall\ l \in \mathcal T$. For instance, if $\mathcal T=\{1,3,5\}$, then $f_{i_1}=f_{i_3}=f_{i_5}$. \end{itemize} Define the vertex $(0,...,0)$ to be the origin of this graph and the vertex $(|f_1|,...,|f_t|)$ to be the destination. If $|f_j|=O(n)\ \forall\ j$, this graph has a number of vertices $O(n^t)$ and a maximum number of edges $O((2n)^t)$ since each vertex has at most $2^t$ outgoing edges.\\ \noindent\textbf{Infiltration product} (introduced in \cite{lothaire1997combinatorics}): The infiltration product has been extensively used in \cite{lothaire1997combinatorics}, as a tool in non-commutative algebra. Here we give an edit-graph interpretation of this tool. We also give a formal definition later in this section. Using the edit graph we can construct the set of possible supersequences $\mathcal{S}(f,g)$ of $f,g$ which are covered by it. Clearly multiple paths could yield the same supersequence and we can count the number of distinct ways $\mathbf N(h;f,g)$ one can construct the same supersequence $h$ from $f,g$. We can informally define the \emph{infiltration product $f\uparrow g$} of $f$ and $g$, as a polynomial with monomials the supersequences $h$ in $\mathcal{S}(f,g)$ and coefficients $\langle f\uparrow g,h\rangle$ equal to $\mathbf N(h;f,g)$. In Fig.~\ref{fig:editgraph_smap1}, it is easy to verify that there is exactly one path corresponding to `101001' and hence $\langle 001\uparrow 101,101001 \rangle=1$ and similarly $\langle 001\uparrow 101,01001 \rangle=2$. One could find these coefficients for all relevant sequences and form the polynomial as described. More examples: Let $\mathcal{A}=\{a,b\}$, then \begin{itemize}[wide=2pt] \item $ab\uparrow ab=ab+2aab+2abb+4aabb+2abab$, \item $ab\uparrow ba=aba+bab+abab+2abba+2baab+baba.$ \end{itemize} The infiltration operation is commutative and associative, and infiltration of two sequences $f\uparrow g$ is a polynomial with variables of length (or \textit{degree}) at most $|f|+|g|$; see \cite{lothaire1997combinatorics}. The definition of infiltration extends to two polynomials via distributivity (precisely defined in later), and consequently to multiple sequences as well. For multiple sequences, infiltration has the same edit graph interpretation: $\langle f_1\uparrow f_2 \uparrow...\uparrow f_t, w \rangle$ is the number of distinct ways of constructing $w$ as a supersequence of $f_1, f_2, ... ,f_t$ so that the construction covers $w$, i.e., construct the $t$-dimensional edit graph of $f_1, f_2, ... ,f_t$ and count the number of paths corresponding to $w$. \subsection{Formal definition of infiltration product} We now give a more formal definition of the infiltration product (see \cite{lothaire1997combinatorics} for the equivalence of the two definitions and a more rigorous treatment). A \textit{formal series} with indeterminates (or variables) in a set $\mathcal A$ and coefficients in a commutative ring $\mathcal R$, is a mapping of $\mathcal A^*$ onto $\mathcal R$. Recall that a commutative ring is a set which forms an abelian group under an \textit{addition} operation, is a monoid under a \textit{multiplication} operation which commutes, and the multiplication operation distributes over addition. Here we consider $\mathbb Z$, the set of integers as the commutative ring $\mathcal{R}$. A formal series is called a \textit{polynomial} if only a finite number of sequences are mapped to non-zero values, the rest of the sequences map to zero. Consider two polynomials $\sigma,\tau: \mathcal{A}^*\rightarrow \mathbb Z$. The value taken by a sequence $w\in \mathcal A^*$ on $\sigma$ (or the coefficient of $w$ in $\sigma$) is denoted by $\langle \sigma,w\rangle \in \mathbb R$. We also define binary addition ($\oplus$) and multiplication operations ($\times$) on the set of polynomials as follows: \begin{align} \langle \sigma\oplus \tau,w\rangle \triangleq \langle \sigma,w\rangle + \langle \tau,w \rangle \quad \forall w\in \mathcal A^*,\label{eq:polynomial_add}\\ \langle \sigma\times \tau,w\rangle \triangleq \sum_{\substack{f,g\in \mathcal A^*:\\ f.g=w}}\langle \sigma,f\rangle \langle \tau,g \rangle \quad \forall w\in \mathcal A^*.\label{eq:polynomial_prod} \end{align} We will use the usual symbols $+$ and $.$ in place of $\oplus$ and $\times$ in this work for convenience. The meaning of the operation would be clear depending on the operands. With these operations the set of polynomials form a non-commutative ring, and is denoted by $\mathbb Z\langle\mathcal A \rangle$, also called the free $\mathbb Z$-algebra on $\mathcal A$ in ring theory. Note that the addition and multiplication operations defined in \eqref{eq:polynomial_add} and \eqref{eq:polynomial_prod} are similar to the operations defined on commutative polynomials, except that the multiplication operation under the summation in \eqref{eq:polynomial_prod} ($f.g=w$) is actually concatenation and is non-commutative. The multiplication inside the summation in \eqref{eq:polynomial_prod} is multiplication in the real field and hence commutative. It is also easy to prove that the multiplication defined in \eqref{eq:polynomial_prod} distributes over addition defined in \eqref{eq:polynomial_add}. Thus, a polynomial in $\mathbb Z\langle\mathcal A \rangle$ can be represented as a sum of monomials in $\mathcal A^*$ each with an associated coefficient in $\mathbb Z$, i.e., $\sigma=\sum\limits_{w\in \mathcal A^*} \langle\sigma,w \rangle w$. Define the \textit{degree} of a polynomial to be equal to the length of a longest sequence with a non-zero coefficient in the polynomial and the \textit{number of terms} of a polynomial as the number of sequences with non-zero coefficients in the polynomial. Note that a degree $d$ polynomial could have a number of terms upto $2^{d+1}-1$. With this, the \textit{infiltration product} (in general, for two polynomials) is defined as follows: \begin{align} \forall f\in \mathcal{A}^*,& \quad f\uparrow e = e\uparrow f=f.\nonumber \\ \forall f,g\in \mathcal{A}^*&,\quad \forall a,b\in \mathcal{A}, \nonumber\\ fa\uparrow gb=(f\uparrow gb)a&+(fa\uparrow g)b+\mathbbm{1}_{a=b}(f\uparrow g)a.\nonumber \\ \forall \sigma,\tau \in \mathbb{Z}\langle\mathcal{A} \rangle, \quad &\sigma\uparrow \tau=\sum_{f,g\in \mathcal{A}^*} \langle \sigma,f \rangle \langle \tau,g \rangle (f\uparrow g). \label{def:infiltforseq} \end{align} \textbf{Summary of definitions and ideas introduced in this section:} \begin{itemize} \item The binomial coefficient captures the likelihood of observations for deletion channels. \item An extension of the binomial coefficient function where one of the parameters can take real values has been introduced; this function is pivotal for our results on the single-trace deletion channel. \item For multiple deletion channels, the error events can be categorized into two groups -- one where an input symbol is deleted in all the traces, and second, the complement of this event. This categorization results in a natural decomposition of multiple deletion channel model into a cascade model involving the remnant channel. \item The remnant channel disregards the error events where a symbol is deleted in all the traces. \item The edit graph provides a way to visualize all the possible error events and input sequences to a remnant channel given its outputs. \item The infiltration product serves the same purpose as the edit graph, but has an algebraic flavor and provides rigor for proofs and analyses. The edit graph, on the other hand, is more helpful in designing reconstruction algorithms over deletion channels. \end{itemize} \section{Notation and Tools} \label{sec:notation} \noindent \textbf{Basic notation:} We borrow some notation from \cite{lothaire1997combinatorics} which deals with non-commutative algebra; we restate them here for convenience. Calligraphic letters refer to sets, capitalized letters correspond to random variables and bold letters are used for functions. Let $\mathcal{A}$ be the set of all symbols. Throughout this work, we will focus on the case where $\mathcal{A}=\{0,1\}$, though our methods extend to arbitrarily large sets of finite size. Define $\mathcal{A}^n$ to be the set of all $n$-length sequences and $\mathcal{A}^*$ to be the set of all finite length sequences with symbols in $\mathcal{A}$. For a sequence $f$, $|f|$ denotes the length of $f$. For integers $i,j$, we define $[i:j] \triangleq \{i,i+1,...,j\}$ if $j\geq i$ and $[i:j] \triangleq \emptyset$ otherwise. We also define $[i] \triangleq [1:i]$. For a vector or sequence $x=(x_1,x_2,...,x_{i-1},x_i,x_{i+1},...,x_n)$, define $$x^{(i\rightarrow s)}\triangleq (x_1,x_2,...,x_{i-1},s,x_{i+1},...,x_n),$$ where the $i^{th}$ coordinate of $x$ is replaced by symbol $s$. \\ \noindent \textbf{Binomial coefficient (section 6.3 in \cite{lothaire1997combinatorics}):} Given sequences $f$ and $g$ in $\mathcal{A}^*$, the number of subsequence patterns of $f$ that are equal to $g$ is called the \textit{binomial coefficient} of $g$ in $f$ and is denoted by $f\choose g$. For example, ${'apple' \choose 'ape'} = 2$ since $'ape'$ can be obtained from two (overlapping) subsequences of $'apple'$. This quantity has also been referred to as the \textit{embedding number} by another line of work \cite{elzinga2008algorithms}. For two sequences of lengths $n$ and $m$, the binomial coefficient can be computed using a dynamic programming approach in $O(nm)$ (see \cite{elzinga2008algorithms} or Proposition 6.3.2 in \cite{lothaire1997combinatorics}). When the alphabet $\mathcal{A}$ is of cardinality 1, ${f \choose g} = {|f| \choose |g|}$, the classical binomial coefficient with their respective lengths as the parameters. This definition hence could be thought of as a generalization of the classical binomial coefficients. We will denote by $e$ the sequence of length 0, and {define ${f \choose e} \triangleq 1\ \forall\ f\ \in\ \mathcal{A}^*$.} We also define the classical binomial coefficient ${a \choose b}\triangleq 0,$ whenever $b>a$ or $b<0$ for ease of use. The binomial coefficient forms the backbone for the probabilistic analysis of deletion channels since the input-output relation for a deletion channel (with deletion probability $\delta$, input $X$ and output $Y$) can be expressed as \begin{equation} \label{eq:in-out_relation} \Pr(Y=y|X=x) = {x \choose y} \delta^{|x|-|y|} (1-\delta)^{|y|}. \end{equation} The proof is straightforward -- the number of distinct error events that give rise to $y$ from $x$ is exactly the number of subsequences of $x$ which are equal to $y$. Each of these error events has a probability $\delta^{|x|-|y|} (1-\delta)^{|y|}$, wherein the exponent of $\delta$ corresponds to the deleted symbols and the exponent of $1-\delta$ to the undeleted symbols. \\ \noindent \textbf{Maximum Likelihood (ML) estimate:} Given the definition of the binomial coefficient, the maximum-likelihood (ML) estimate over a deletion channel with observed output $Y=y$ can be cast in the following form: \begin{align*} \argmax_{x \in \{0,1\}^n} {x \choose y}.\numberthis \label{eq:ML_deletion} \end{align*} In the case of multiple deletion channels with observed traces $Y^{1}=y^1,...,Y^{t}=y^t$, the ML formulation is similar: \begin{align*} \argmax_{x \in \{0,1\}^n} \prod_{j=1}^{t} {x \choose y^{j}}.\numberthis \label{eq:ML_multiple_deletion} \end{align*} As yet, there is no known efficient way to come up with a solution for either of the above two formulations (see \cite{mitzenmacher2009survey}).\\ \noindent \textbf{Relaxed binomial coefficient.} We now introduce the function $\mathbf F(\cdot)$ which can be thought of as a real-valued relaxation of the binomial coefficient. This function is used in sections~\ref{sec:1deletion_ML} and~\ref{sec:1deletion}. An intuitive definition is as follows: Consider a random vector $Z\in\{0,1\}^n$ such that $Z_i\sim$ ind. Ber$(p_i)$, and let $p$ be the vector of probabilities of length $n$. Then $\mathbf F(p,v)=\mathbb E_{Z\sim p}\ {Z \choose v}$, i.e., $\mathbf F(p,v)$ is the expected number of times $v$ appears as a subsequence of $Z$. If $p \in \{0,1\}^n$, then $Z=p$ with probability 1 and $\mathbf F(p,v) = {p \choose v}$. More precisely, $\mathbf F(\cdot)$ is defined as: \begin{definition} \label{def:f} \begin{align*} &\mathbf F: [0,1]^n \times \{0,1\}^m \rightarrow \mathbb{R},\\ \mathbf F(p, v)\triangleq &\begin{cases} \sum\limits_{\substack{\mathcal S|\mathcal S\subseteq [n],\\|\mathcal S|=m}} \quad \prod\limits_{i=1}^m p_{\mathcal S_i}^{v_i} (1-p_{\mathcal S_i})^{1-v_i} & 1 \leq m\leq n \\ 1 & 0=m\leq n \\ 0 & \text{else}. \end{cases} \end{align*} \end{definition} Though at first sight $\mathbf F(p,v)$ sums over an exponential number of subsets, a dynamic programming approach can be used to compute it in $O(nm)$ time complexity (see Appendix~\ref{app:F_compute}). Note that this is the same complexity as computing the binomial coefficient.\\ \noindent \textbf{Decomposition of the $t$-trace deletion channel:} The following definitions and ideas are relevant to the results pertaining to multiple traces. We first state a result that aids in thinking about error events in multiple deletion channels. The events occurring in the $t$-deletion channel model can be categorized into two groups: \begin{enumerate} \item an input symbol is deleted in \textit{all} the $t$-traces, \item an input symbol is reflected in at least one of the traces. \end{enumerate} The error events of the first kind are in some sense ``not correctable'' or even ``detectable'' in any situation since it is impossible to tell with absolute certainty what and where the deleted symbol could have been (although the probabilities need not be uniform). The events of the second kind, however, can be detected and corrected in some situations. This thought process gives rise to a natural decomposition of the $t$-deletion channel model into a cascade of two channels: the first one being a deletion channel which captures error events of the first kind and the second one is what we call the \textit{remnant channel} which captures events of the second kind (see Fig.~\ref{fig:channel_equiv}). More precisely, we define the remnant channel as follows: \begin{definition} \textit{Remnant channel:} an input symbol to the remnant channel is reflected in any $k>0$ uniformly random traces and deleted in the rest with a probability ${t \choose k} \frac{\delta^{t-k}(1-\delta)^k}{1-\delta^t}$. Thus, the probability of an input symbol reflected in a \textit{fixed} set of $k>0$ traces is equal to $\frac{\delta^{t-k}(1-\delta)^k}{1-\delta^t}$. \end{definition} Note that probability of the union of all possible events here is $\sum_{k=1}^t {t \choose k} \frac{\delta^{t-k}(1-\delta)^k}{1-\delta^t}=1$, validating our definition. \vspace{-5mm} \begin{figure}[!h] \begin{center} \includegraphics[scale=0.4]{channel_equiv.pdf} \caption{A channel equivalence result: the $t$-trace deletion channel model in (a) is probabilistically equivalent to the the cascade of a deletion channel with the \textit{remnant channel} ($ \mathcal C_2$) in (b).} \label{fig:channel_equiv} \end{center} \end{figure} \vspace{-10mm} \begin{restatable}{theorem}{channelequiv} \label{thm:channel_equiv} The $t$-deletion channel model and the cascade of the deletion channel with remnant channel shown in Fig.~\ref{fig:channel_equiv} are probabilistically equivalent, i.e., $$\Pr({Y}^{1}=y^1,{Y}^{2}=y^2,...,{Y}^{t}=y^t|X = x) = \Pr(\tilde{Y}^{1}=y^1,\tilde{Y}^{2}=y^2,...,\tilde{Y}^{t}=y^t|X = x).$$ \end{restatable} A rigorous proof of this theorem for arbitrary length sequences can be found in Appendix~\ref{app:channel_equiv}. A similar, though not equivalent, decomposition has been exploited in \cite{haeupler2014repeated} albeit for the purpose of characterizing the capacity of multiple deletion channels -- there the authors consider deletion patterns which are ``undetectable''; for example, a deletion in the deletion channel $\mathcal C_1$ in the cascade model is undetectable since none of the traces will reflect that input symbol. However, our channel decomposition result does not appear in \cite{haeupler2014repeated}.\\ \noindent\textbf{Edit graph} (\cite{Gusfield1997}): Similar graph constructs have been defined in related problems on common supersequences and subsequences (see \cite{Nicosia2001} for example). This graph is closely related to the error events in the remnant channel. We start with a simple case and generalize subsequently. Define a directed graph called \textit{edit graph} given two sequences $f$ and $g$, where every path connecting the ``origin'' to the ``destination'' on the edit graph yields a supersequence $h$ of $f,g$, where $h$ is ``covered'' by $f,g$ -- i.e., each symbol of $h$ comes from either $f$ or $g$ or both. In other words, given that $f$ and $g$ are the outputs of the remnant channel (with two outputs), each path from the origin of the edit graph to the destination corresponds to a possible input $h$ to the remnant channel and to an error event which resulted in outputs $f,g$ with input $h$. For $f$ and $g$ in $\mathcal A^*$, we form a directed graph $\mathcal{G}(f,g)$ with $(|f|+1)(|g|+1)$ vertices each labelled with a distinct pair $(i,j), 0\leq i\leq |f|,\ 0\leq j\leq |g|$. A directed edge $(i_1,j_1)\rightarrow(i_2,j_2)$ exists iff at least one of the following holds: \begin{enumerate} \item$i_2-i_1=1$ and $j_1=j_2$, or \item $j_2-j_1=1$ and $i_1=i_2$, or \item $i_2-i_1=1$, $j_2-j_1=1$ and $f_{i_2}=g_{j_2}$, \end{enumerate} where $f_i$ is the $i^{th}$ symbol of the sequence $f$. The origin is the vertex $(0,0)$ and the destination $(|f|,|g|)$. \begin{figure}[!h] \centering \includegraphics[scale=0.25]{editgraph_smap1.pdf} \caption{ Edit graph for sequences $f=$ `001' and $g=$ `101'. Make a grid so the vertical edges are aligned with a symbol in $f$ and horizontal edges with $g$ as shown. A diagonal edge $(i{-}1,j{-}1)\rightarrow (i,j)$ exists if $f_i = g_j$. The thick red edges form a path from the origin to the destination; this path corresponds to $h=$`0101' -- sequentially append the corresponding symbol to which each edge is aligned. It can also be verified that $h$ is a supersequence of both $f$ and $g$, and could be obtained as a covering of $f$ and $g$; the path itself gives one such covering. This covering also corresponds to an error event (or a deletion pattern) in the remnant channel which would result in outputs $f$ and $g$ with input $h=$ `0101' -- the deletion pattern is shown in the figure.} \label{fig:editgraph_smap1} \end{figure} Let $p=((i_1,j_1),(i_2,j_2),...,(i_m,j_m))$ be a path in $\mathcal{G}(f,g)$. We define $ s(p)$ to be the sequence corresponding to the path. Intuitively, $s(p)$ is formed by appending symbols in the following way: append the corresponding $f$ symbol for a vertical edge, $g$ symbol for horizontal edge, and $f$ or $g$ symbol for diagonal edge (see example Fig.~\ref{fig:editgraph_smap1}). Any path from $(0,0)$ to $(|f|,|g|)$ corresponds to a supersequence of $f$ and $g$ and which is covered by $f$ and $g$. More formally, define $ s(p)\triangleq x_1x_2...x_{m-1}$ where $$x_k = \begin{cases} f_{i_{k+1}} \quad\text{if }j_{k}=j_{k+1},\\ g_{j_{k+1}} \quad\text{if }i_{k}=i_{k+1},\\ f_{i_{k+1}} \quad\text{else.} \end{cases} $$ The construct of edit graph can be extended to more than 2 sequences with the same idea. For sequences $f_1,f_2,...,f_t$, construct a $t$-dimensional grid with a number of vertices $(|f_1|+1)(|f_2|+1)...(|f_t|+1)$ labeled from $(0,0,...,0)$ to $(|f_1|,|f_2|,...,|f_t|)$. A vertex $u=(i_1,i_2,...,i_t)$ is connected to $v=(j_1,j_2,...,j_t)$ (we say $u \rightarrow v$) iff both of the following conditions are met: \begin{itemize} \item $j_l=i_l$ or $j_l=i_l+1$ $\forall\ l\in [t]$, i.e., $(i_1,...,i_t)$ and $(j_1,...,j_t)$ are vertices of a particular unit cube. Only these type of vertices can share an edge in the grid graph. \item Let $\mathcal T \subseteq [t]$ be the collection of indices where $j_l=i_l+1$. Then ${f_l}_{j_l}$ is equal $\forall\ l \in \mathcal T$. For example in 4 dimensional grid, consider the two vertices $(10,5,8,2)$ and $(10,6,9,2)$. In this case $\mathcal T = \{2,3\}$ since the second and third coordinates differ by 1. Therefore $(10,5,8,2)\rightarrow (10,6,9,2)$ iff ${f_2}_{5}={f_3}_{9}$. Note that if only one coordinate differs by 1 in the two vertices, a directed edge always exists (in other words all non-diagonal edges exist). \end{itemize} Define the vertex $(0,...,0)$ to be the origin of this graph and the vertex $(|f_1|,...,|f_t|)$ to be the destination. If $|f_j|=O(n)\ \forall\ j$, this graph has a number of vertices $O(n^t)$ and a maximum number of edges $O((2n)^t)$ since each vertex has at most $2^t-1$ outgoing edges.\\ \noindent\textbf{Infiltration product} (introduced in section 6.3 of \cite{lothaire1997combinatorics}): The infiltration product has been extensively used in \cite{lothaire1997combinatorics}, as a tool in non-commutative algebra. Here, we give an edit-graph interpretation of this tool. A formal algebraic definition of the infiltration product is in Appendix~\ref{app:infil_def}. Using the edit graph we can construct the set of possible supersequences $\mathcal{S}(f,g)$ of $f$, $g$ that are covered by the symbols in $f$ and $g$. Indeed, multiple paths could yield the same supersequence and we can count the number of distinct ways $\mathbf N(h;f,g)$ one can construct the same supersequence $h$ from $f$, $g$. We can informally define the \emph{infiltration product $f\uparrow g$} of $f$ and $g$, as a polynomial with monomials the supersequences $h$ in $\mathcal{S}(f,g)$ and coefficients $\langle f\uparrow g,h\rangle$ equal to $\mathbf N(h;f,g)$. For the example in Fig.~\ref{fig:editgraph_smap1}, there is exactly one path corresponding to `101001' and hence $\langle 001\uparrow 101,101001 \rangle=1$ and similarly $\langle 001\uparrow 101,01001 \rangle=2$. One could find these coefficients for all relevant sequences and form the polynomial as described. We now give additional examples (see 6.3.14 in \cite{lothaire1997combinatorics}). Let $\mathcal{A}=\{a,b\}$, then \begin{itemize}[wide=2pt] \item $ab\uparrow ab=ab+2aab+2abb+4aabb+2abab$, \item $ab\uparrow ba=aba+bab+abab+2abba+2baab+baba.$ \end{itemize} The infiltration operation is commutative and associative, and infiltration of two sequences $f\uparrow g$ is a polynomial with variables of length (or \textit{degree}) at most $|f|+|g|$; see \cite{lothaire1997combinatorics}. The definition of infiltration extends to two polynomials via distributivity (precisely defined in Appendix~\ref{app:infil_def}), and consequently to multiple sequences as well. For multiple sequences, infiltration has the same edit graph interpretation: $\langle f_1\uparrow f_2 \uparrow...\uparrow f_t, w \rangle$ is the number of distinct ways of constructing $w$ as a supersequence of $f_1, f_2, ... ,f_t$ so that the construction covers $w$, i.e., construct the $t$-dimensional edit graph of $f_1, f_2, ... ,f_t$ and count the number of paths corresponding to $w$. \\ {\small \begin{center} \begin{tabular}{ |P{3cm}|P{10cm}| } \hline \multicolumn{2}{|c|}{Table of notation} \\ \hline $\mathcal A$ & A set \\ \hline $X$ & A random variable or a random vector \\ \hline $x$ & A scalar or a vector variable\\ \hline $|x|$ & Length of the sequence $x$\\ \hline $[i:j]$ & $\{i,i+1,...,j\}$\\ \hline $x^{(i\rightarrow s)}$ & $(x_1,x_2,...,x_{i-1},s,x_{i+1},...,x_n)$ \\ \hline ${f \choose g}$& Binomial coefficient: number of subsequence patters of $f$ equal to $g$ \\ \hline $\mathbf F(p,v)$ & Relaxed binomial coefficient: $\mathbb E_{Z\sim p} {Z \choose v}$ \\ \hline $\langle f \uparrow g,h \rangle$ & Infiltration product: number of ways of obtaining sequence $h$ as a ``covered'' supersequence of $f$ and $g$ \\ \hline \end{tabular} \end{center}} \vspace{2mm} \section{Maximum likelihood for the single-trace deletion channel} \label{sec:1deletion_ML} Consider the ML formulation for the single-trace deletion channel given non-empty trace $Y$ and all possible $n$-length inputs allowed, restated here for convenience: \begin{equation} \argmax_{x\in \{0,1\}^n} {x \choose Y}. \label{eq:1deletion_ML} \end{equation} To the best of our knowledge, the only known method to solve \eqref{eq:1deletion_ML} involves iterating over all possible choices of $x$ and computing the objective value for each of the choices. We here show that it is sufficient to solve a continuous relaxation of above problem to obtain a solution to \eqref{eq:1deletion_ML}. Note that there could be multiple solutions to \eqref{eq:1deletion_ML}. Before going in the main result, we first state a useful lemma which factors out a given coordinate $p_i$ out of $\mathbf F(p,Y)$. The proof of the lemma is relegated to the appendix. \begin{restatable}{lemma}{deletionMLrellemma} For $p=[p_1,p_2,..,p_i,...,p_n]$ and $Y=Y_1Y_2...Y_m$ with $n \geq m > 0$, we have \begin{align*} \mathbf F(p,Y) = \mathbf F( p_{[n]\backslash \{i\}},Y) + p_i \sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]})\\ + (1-p_i) \sum\limits_{k|Y_k=0}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}). \end{align*} \label{lemma:F_decomposition} \end{restatable} \begin{theorem} An alternative optimization to characterize ML for the single-trace deletion channel. \begin{equation} \max_{x\in \{0,1\}^n} {x \choose Y} = \max_{p\in [0,1]^n} \mathbf F(p,Y). \label{eq:ml_opt_equiv} \end{equation} Furthermore, given any non-integral $p^* \in [0,1]^n$ that maximizes $\mathbf F(p,Y)$, one could construct a corresponding integral solution $x^* \in \{0,1\}^n$ that maximizes $\mathbf F(p,Y)$ and consequently is also a solution to $\max_{x\in \{0,1\}^n} {x \choose Y}$. \end{theorem} \begin{proof} As noted earlier, we have ${x \choose Y} = \mathbf F(x,Y)$. Therefore, we are interested in proving the following: \begin{align*} \max_{x\in \{0,1\}^n} \mathbf F(x,Y) \equiv \max_{p\in [0,1]^n} \mathbf F(p,Y).\numberthis \label{eq:ml_opt_equiv_proof1} \end{align*} To show this and also the second statement, we prove that given $p=(p_1,p_2,...,p_i,...,p_n)$, at least one of the following holds true: \begin{itemize} \item$\mathbf F(p^{(i\rightarrow 0)},Y) \geq \mathbf F(p,Y)$, where $p^{(i\rightarrow 0)}=(p_1,p_2,...,p_{i-1},0,p_{i+1}...,p_n)$ is the vector where the $i^{th}$ coordinate is replaced by 0. \item $\mathbf F(p^{(i\rightarrow 1)},Y) \geq \mathbf F(p,Y)$, where $p^{(i\rightarrow 0)}=(p_1,p_2,...,p_{i-1},1,p_{i+1}...,p_n)$ is the vector where the $i^{th}$ coordinate is replaced by 1. \end{itemize} Thus if $p^*$ is an optimal solution to $\max_{p\in [0,1]^n} \mathbf F(p,Y)$ with $p_i\in (0,1)$, then at least one of $p^{(i\rightarrow 0)}$ or $p^{(i\rightarrow 1)}$ is also an optimal solution. Sequentially applying this argument for each coordinate of $p$ shows that there exists a point in $\{0,1\}^n$ which is also an optimal solution to $\max_{p\in [0,1]^n} \mathbf F(p,Y)$ and consequently to $\max_{x\in \{0,1\}^n} \mathbf F(x,Y)$. Now to prove our claim, we use Lemma~\ref{lemma:F_decomposition} to factor out $p_i$ terms in $\mathbf F(p,Y)$: \begin{align*} \mathbf F(p,Y) = \mathbf F( p_{[n]\backslash \{i\}},Y) + p_i \sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]})\\ + (1-p_i) \sum\limits_{k|Y_k=0}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}). \end{align*} There are 3 cases \begin{enumerate} \item $$\sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}) = \sum\limits_{k|Y_k=0}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}).$$ \\In this case it is easy to verify that $\mathbf F(p^{(i\rightarrow 0)},Y) = \mathbf F(p,Y) = \mathbf F(p^{(i\rightarrow 1)},Y).$ \item $$\sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}) > \sum\limits_{k|Y_k=0}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}).$$ \\In this case it is easy to verify that $\mathbf F(p^{(i\rightarrow 0)},Y) \leq \mathbf F(p,Y) \leq \mathbf F(p^{(i\rightarrow 1)},Y).$ \item $$\sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}) < \sum\limits_{k|Y_k=0}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}).$$ \\In this case it is easy to verify that $\mathbf F(p^{(i\rightarrow 0)},Y) \geq \mathbf F(p,Y) \geq \mathbf F(p^{(i\rightarrow 1)},Y).$ \end{enumerate} Thus in each of the 3 cases, we see that at least one of $\mathbf F(p^{(i\rightarrow 0)},Y)$ or $\mathbf F(p^{(i\rightarrow 1)},Y)$ is at least as large as $\mathbf F(p,Y)$ thus proving the theorem. Note that the proof gives a natural way to find an optimal lattice point $p_{lattice}^*$ given a non-lattice point $p^*$ by iterating through each coordinate of $p^*$ and switching them to $0$ or $1$ by comparing $\sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]})$ with $\sum\limits_{k|Y_k=0}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}).$ \end{proof} \section{Numerical results} \label{sec:Numerics} In this section we show numerics supporting our theoretical results. In all of our experiments, we generate the input sequence uniformly at random (motivated by average case trace reconstruction), and obtain the $t$ traces by passing the input through a deletion channel (with a deletion probability $\delta$) $t$ times. We then reconstruct the input from the obtained traces and measure how \textit{close} the reconstructed sequence is, to the actual input sequence. We use two metrics to measure the performance of the reconstruction algorithms: 1. \textit{Hamming error rate}, which is defined as the average Hamming distance between the actual input and the estimated sequence divided by the length of the input sequence and 2. \textit{Edit error rate}, which is defined as the average edit distance between the actual input and the estimated sequence divided by the length of the input sequence. The reason for using Hamming error rate is that our goal is to reconstruct a \textit{known-length} sequence, which has been the problem formulation throughout this work. Moreover, the Hamming error rate is also of special interest to us since the symbolwise MAP is an optimal estimator for minimizing the Hamming error rate (see Appendix~\ref{app:smap_hamming} for a proof). We also use edit error rate as it is a typical metric used in the context of insertion/deletion channels. {\small \begin{center} \begin{tabular}{ |P{3cm}|P{9.5cm}|P{2.5cm}| } \hline \multicolumn{3}{|c|}{List of trace reconstruction algorithms compared in this work.} \\ \hline \bf Abbreviation & \bf Description & \bf Complexity\\ \hline Ind. post. comb. & Independent posterior combination (Alg.~\ref{alg:ind_comb}) & $O(n^2t)$\\ \hline BMA & Bitwise majority alignment of \cite{Batu2004} (Alg.~\ref{alg:bitwise_majority}) & $O(nt)$ \\ \hline Trace stats. & Algorithm based on trace symbolwise statistics from \cite{Holenstein2008} (Alg.~\ref{alg:trace_statistics}) & $O(n^{3.37}+nt)$\\ \hline Grad asc. & Projected gradient ascent (Alg.~\ref{alg:grad_asc_traces}) & $O(n^2t)$\\ \hline SMAP seq. & Sequential symbolwise MAP heuristic (Alg.~\ref{alg:apprx_smap}) & $O(n^2t)$ \\ \hline SMAP exact & Exact symbolwise MAP (Alg.~\ref{alg:exact_smap}) & $O(n^{t+2}2^t)$\\ \hline \end{tabular} \end{center}} \vspace{5mm} \noindent \textbf{Baseline algorithms:} \begin{enumerate}[leftmargin = *] \item \textbf{Independent posterior combination:} As pointed in the introduction, computing the posterior probabilities for each deletion channel and combining them as if they came from independent observations does not provide a natural solution for computing the posterior probabilities for the $t$-trace deletion channel. One could, however, check how such a naive combination of posteriors compares with our reconstruction algorithms for $t$-traces. This is detailed as Alg.~\ref{alg:ind_comb}. The complexity of this algorithm is $O(n^2t)$ since computing the posteriors takes $O(n^2)$ and we compute posteriors for $t$ traces. \item \textbf{Bitwise Majority Alignment (introduced in \cite{Batu2004}):} BMA reconstructs the input sequence by first ``aligning'' the traces using a pointer for each trace, and then taking the majority of the pointed symbols. BMA is detailed as Alg.~\ref{alg:bitwise_majority}. From an efficiency standpoint, BMA is the most efficient of all the algorithms since it is linear in the blocklength as well as the number of traces ($O(nt)$). \item \textbf{Trace statistics algorithm:} An algorithm based on trace symbol statistics (also called mean-based algorithms and summary statistics algorithms) has been extensively studied for worst-case trace reconstruction (see \cite{Holenstein2008}, \cite{De2017}, \cite{Nazarov:2017}). In essence, the algorithm first estimates the ``trace symbol statistics'' -- $\Pr(Y_i=1)\ \forall\ i$ -- from the obtained traces and uses only these estimates to reconstruct $X$. However, it uses a new set of traces for every position $i$, thus requiring at least $n$ traces (see (3.6) and the paragraph below (3.8) in \cite{Holenstein2008}). Here we modify the algorithm to adapt them for an arbitrary number of traces; in particular, we reuse the traces while estimating $\Pr(Y_i=1)\ \forall\ i$. The algorithm is detailed in Alg.~\ref{alg:trace_statistics}. The complexity analysis for this gets tricky since it depends on the algorithm used to solve the set of $2n$ linear programs. The state-of-the-art algorithm for solving a linear program in $n$ variables takes approximately $O(n^{2.37})$ (see \cite{cohen2019solving}); thus the complexity of Trace statistics algorithm is $O(n^{3.37}+nt)$, where the $nt$ term corresponds to the complexity of computing $\hat p_j$. However, in our implementation we use the solver from the "SciPy" Python library which uses primal-dual interior point methods for solving linear programs. The complexity of such methods is typically $O(n^3)$ making our implementation $O(n^4+nt)$. Also note that these are iterative methods and have many hidden constants (such as the number of iterations for convergence). \end{enumerate} We note that the state-of-the-art average-case trace reconstruction algorithms in the literature are applicable in the asymptotic regime where the blocklength $n$ and the number of traces $t$ approach $\infty$; it is not clear how to adapt such algorithms for a finite blocklength and a small number of traces. It is for this reason that we chose to compare against BMA and Trace statistics algorithm, which can be easily adapted for the finite blocklength regime and for a small number of traces. It should also be noted that the performance of the above two algorithms may not be reliable with a small number of traces (as they are not designed for this regime), yet we include them owing to the lack of better baselines.\\ \begin{algorithm}[t!] \caption{Trace reconstruction via independent posterior combination}\label{alg:ind_comb} \begin{algorithmic}[1] \item Input: Traces {$Y^{1}=y^1,...,Y^{t}=y^t$}, input length $n$ \\ Outputs: Estimate of the input $\hat X$ \State Initialize priors $p^{old} \gets (0.5,0.5,...,0.5)$ \For {$l=1:t$} \State Use Alg.~\ref{alg:apprx_smap_dp} with $p^{old}$ and $y^l$ to compute posteriors $p^{l,new}$ \EndFor \For {$i=1:n$} \If {$\prod_{l=1}^t p^{l,new}_i \geq \prod_{l=1}^t (1-p^{l,new}_i)$} $\ \hat X_i \gets 1$ \Else $\ \hat X_i \gets 0$ \EndIf \EndFor \end{algorithmic} \end{algorithm} \begin{algorithm}[!t] \caption{Bitwise Majority Alignment} \label{alg:bitwise_majority} \begin{algorithmic}[1] \item Input: Traces {$Y^{1}=y^1,...,Y^{t}=y^t$, input length $n$}\\ Output: estimate of input $\hat X = \hat X_1 \hat X_2...\hat X_n$. \State Initialize $c_j=1$ for $j\in [t]$. \State Initialize $\hat X_i = 1$ for $i \in [n]$. \For{$i \in\ [1:n]$} \State Let $b$ be the majority over all $t$ of $y^j_{c_j}$ \State $\hat X_i \gets b$ \State Increment $c_j$ for each $j$ such that $y^j_{c_j} = b$ \EndFor \end{algorithmic} \end{algorithm} \begin{algorithm}[!t] \caption{Trace statistics heuristic} \label{alg:trace_statistics} \begin{algorithmic}[1] \item Input: Traces {$Y^{1}=y^1,...,Y^{t}=y^t$, input length $n$}\\ Output: estimate of input $\hat X = \hat X_1 \hat X_2...\hat X_n$. \State Append each trace $y^j$ with zeros until each of them is of length $n$. \State Assign $\hat p_j \leftarrow \frac{|\{y^l:y^l_j=1\}|}{t}$. \For{$i \in\ [1:n]$} \State Solve the 2 linear programs (3.6) in \cite{Holenstein2008} by fixing $x_i=0$ and $x_i=1$: let the optimum value in the two cases be $m_0$ and $m_1$ respectively. \State If $m_0<m_1$, assign $\hat X_i = x_i \leftarrow 0$. Else fix $\hat X_i = x_i \leftarrow 1$. \EndFor \end{algorithmic} \end{algorithm} \newpage \noindent \textbf{Algorithms introduced in this paper:} \begin{enumerate}[leftmargin = *] \item \textbf{Projected gradient ascent:} Alg.~\ref{alg:grad_asc_traces} used as described, with max iterations $M=100$ and convergence criteria $C$ set as follows: the percentage difference in $\sum_j \mathbf F(p,y^j)$ over two consecutive iterations is less than 0.1\%. \item \textbf{Symbolwise MAP sequentially used one trace at a time:} Alg.~\ref{alg:apprx_smap} used as described. \item \textbf{Exact symbolwise MAP:} Alg.~\ref{alg:exact_smap} used as described. \end{enumerate} \vspace{7mm} \textbf{Observations:} In Fig.~\ref{fig:numerics_hamming} and Fig.~\ref{fig:numerics_edit}, we compare the Hamming and edit error rates for the different algorithms described above. \begin{itemize}[leftmargin = *] \item The 3 algorithms introduced in this work outperform the 3 baselines in most cases. The Hamming error rate of Grad asc. with 2 and 3 traces is a notable exception as it does worse than Ind. post. comb. However, it improves rapidly as we increase the number of traces as seen in Fig.~\ref{fig:numerics_hamming}. \item Both Ind. post. comb. as well as our SMAP seq. struggle with the problem of \textit{diminishing returns} for Hamming error rate as they do not improve much with the number of traces. This could indicate that considering traces one at a time could fail to accumulate extrinsic information (for instance, it completely neglects the possible alignments given multiple traces); one needs to simultaneously consider multiple traces in order to accomplish this. SMAP seq. however, improves with the number of traces with respect to edit error rate. \item The Grad asc. is the ``champion'' amongst the algorithms we compare here, when it comes to the edit error rate as illustrated by Fig.~\ref{fig:numerics_edit}. The Grad asc. was constructed with the aim of maximizing the likelihood of the observed traces, and this in turn seems to have some correlation with minimizing the edit distance -- it is not clear why this is the case. \item As seen in Fig.~\ref{fig:numerics_hamming} (a) and (b), SMAP exact has the minimum Hamming error rate. This supports the fact that symbolwise MAP is the minimizer of the Hamming error rate. However, note that this does not necessarily minimize the edit error rate, as seen from Fig.~\ref{fig:numerics_edit} (a) and (b). \end{itemize} \begin{figure}[!t] \centering \includegraphics[scale=0.85]{Numerics/hamming_error_rates.pdf} \caption{Comparison of Hamming error rates for a blocklength $n=100$ illustrated with 2,3,5 and 10 observed traces. Note that we do not run SMAP exact. for 5 and 10 traces since its complexity grows exponentially with the number of traces. All the subplots are plotted on the same scale to aid comparability across subplots. Few of the subplots which contain algorithms with similar error rates also contain a zoomed-in inset view.} \label{fig:numerics_hamming} \end{figure} \clearpage \begin{figure}[!t] \centering \includegraphics[scale=0.85]{Numerics/edit_error_rates.pdf} \caption{Comparison of edit error rates for a blocklength $n=100$ illustrated with 2,3,5 and 10 observed traces. Note that we do not run SMAP exact. for 5 and 10 traces since its complexity grows exponentially with the number of traces. All the subplots are plotted on the same scale to aid comparability across subplots. Few of the subplots which contain algorithms with similar error rates also contain a zoomed-in inset view.} \label{fig:numerics_edit} \end{figure} \clearpage \section{Introduction} \label{sec:intro} Sequence reconstruction over deletion channels, both with and without a codebook, has received considerable attention in the information theory as well as in the theoretical computer science literature. From an information theory perspective, reconstruction over the deletion channel, or more specifically a maximum-likelihood (ML) argument for the deletion channel, would give further insight on the capacity of the deletion channel, a long-standing open problem (see \cite{mitzenmacher2009survey}). To quote \cite{mitzenmacher2009survey} -- ``at the very least, progress in this direction would likely surpass previous results on the capacity of the deletion channels''. Yet, there are no results on reconstruction over a deletion channel with statistical guarantees -- in this work, we take a step in this direction. On the other hand, the problem of \textit{trace reconstruction}, as introduced in \cite{Batu2004}, has received renewed interest in the past few years (see \cite{Holenstein2008}, \cite{Peres2017}, \cite{De2017}, \cite{holden18}, \cite{Nazarov:2017}, \cite{holden2018lower}, \cite{chase2019new}). The problem of trace reconstruction can be stated simply as follows: consider a sequence $X$ which is simultaneously passed through $t$ independent deletion channels to yield $t$ deleted observations (also called \textit{traces}) of $X$ (see Fig.~\ref{fig:tdeletion}). How many such traces are needed to reconstruct $X$ perfectly? A variety of upper and lower bounds for this problem have been proposed, both for worst case and average case reconstruction. Our problem definition, stated in the following paragraph, is closely related to the average case trace reconstruction. \begin{figure}[!h] \begin{center} \includegraphics[scale=0.2]{tdeletion.pdf} \caption{$t$-deletion channel model: sequence $X$ passed through $t$ independent deletion channels to yield $t$ \textit{traces}. We aim to estimate $X$ from the $Y^{(i)}$s.} \label{fig:tdeletion} \end{center} \end{figure} \noindent \textbf{Problem definition.} Given an input sequence of length $n$ (known apriori), the independently and identically distributed (i.i.d.) deletion channel deletes each input symbol indepedently with probability $\delta$, producing at its output a subsequence of the input sequence. Consider a sequence $X$ passed through $t$ ($t$ is fixed) such deletion channels as shown in Fig.~\ref{fig:tdeletion}. We call this the $t$-deletion channel model. We ask two questions: \begin{enumerate} \item For $t=1$ (see Fig.~\ref{fig:1deletion}, also called the single deletion channel model), and when $X_i \sim\ \text{ind. Ber}(p_i)$, compute the posterior distributions of $X_i$ given the trace $Y$. \begin{figure}[!h] \begin{center} \includegraphics[scale=0.25]{1deletion.pdf} \caption{The single deletion channel model. We assume $X_i \sim\ \text{ind. Ber}(p_i)$.} \label{fig:1deletion} \end{center} \end{figure} \item In the $t$ deletion channel model, for a fixed $t$ assume that $X_i \sim\ \text{i.i.d. Ber}(0.5)$ and compute the posterior distributions of $X_i$ given all traces $Y^{(1)}, Y^{(2)},...,Y^{(t)}$. \end{enumerate} Note that solving 1) above doesn't lead to a natural solution for 2). This is because for a memoryless channel, we have $Y^{(j)} - X_i - Y^{(k)}$ and hence $\Pr(X_i=\alpha|Y^{(j)}, Y^{(k)}) \propto \Pr(X_i=\alpha|Y^{(j)}) \Pr(X_i=\alpha|Y^{(k)})$; so one could independently combine the posterior probabilities from each noisy observation. This is not the case for deletion channels since the markov chain $Y^{(j)} - X_i - Y^{(k)}$ no longer holds. More intuitively, one needs to first ``align'' the traces for computing the likelihoods. We point out that the problem considered in 2) asks a question complementary to the trace reconstruction: given a fixed (possibly a few) number of traces, what is our ``best'' guess of $X$? We provide algorithms which do this. Unlike trace reconstruction, we are not concerned with perfect reconstruction (since perfect reconstruction may not be possible with just a few traces), although it should also be obvious that performance guarantees for our algorithms (not a part of this work) would naturally lead to upper bounds for trace reconstruction. Deletion channel by itself is known to be notoriously difficult to analyse. As stated earlier, the capacity of a single deletion channel is still unknown (\cite{diggavi2007capacity,diggavi2006information,diggavi2001transmission}); as are optimal coding schemes. Recent works have looked at the design of codes for deletion channels (\cite{ratzer2005marker,ratzer2000codes,thomas2017polar}); these works consider use of a codebook (we do not). As a result, statistical estimation over deletion channels is also a difficult problem due its highly combinatorial nature. To the best of our knowledge, as yet there are no efficient estimation algorithms over deletion channels with statistical guarantees; not even for ML over a single deletion channel. \noindent \textbf{Biological motivation.} Trace reconstruction in itself was motivated, in part, by problems DNA sequence reconstruction. One such problem was to infer the DNA sequence of a common ancestor from the samples of its descendants. We argue that our problem definition fits more naturally in such a scenario since perfect reconstruction may not be feasible or even possible. Our motivation for considering this problem also comes from a recent DNA sequencing technology called \textit{nanopore sequencing}. The $t$-deletion channel model is a simplistic model to approximately capture the process of a DNA sequence passed through a nanopore sequencer\footnote{As seen in \cite{Mao2017},\cite{MDK17} there are more complicated effects of the nanopore reader not captured in this simple representation.}. Very recently, a variant of the trace reconstruction problem called \textit{coded trace reconstruction} has been proposed, motivated by portable DNA-based data storage systems using DNA nanopores (see \cite{abroshan2019coding}, \cite{cheraghchi2019coded}, \cite{brakensiek2019coded}) and we believe that the ideas in this work may prove useful in such a setting. There are other works on sequence assembly (see for example, \cite{Li09fastand}, \cite{Shomorony2016}), where multiple short reads (from different segments of a sequence) are used to reconstruct the bigger sequence. This work differs from sequence assembly since we are interested to infer the entire length sequence and not just small segments of it (which are then ``stitched'' together in sequence assembly). \noindent \textbf{Tools and techniques.} In terms of theoretical tools, the series of books by Lothaire (\cite{lothaire1997combinatorics,lothaire2002algebraic,lothaire2005applied}) extensively use algebraic tools for problems in the combinatorics of sequences (or \textit{words}), and our work is inspired by such techniques. We borrow many of their notations and results for our work. \noindent \textbf{Contributions.} {\color{red}} Our main contribution is to provide tools to visualize and analyze error events (described in the next section) for the multiple deletion channel model in Fig.~\ref{fig:tdeletion}. We also provide algorithms to solve the problems stated in 1) and 2) earlier in the section. \begin{itemize}[wide=5pt] \item In section~\ref{sec:1deletion}, for the single deletion channel model, we provide an $O(n^2)$ algorithm to calculate the symbolwise posterior probabilities $\Pr(X_i=1|Y)\ \forall\ i$ when $X_i \sim \text{ind. Ber}(p_i)$. \item In Section~\ref{sec:exactsmap}, for the $t$-deletion channel model, we give an $O(2^t n^{t+2})$ algorithm to calculate the symbolwise posterior probabilities $\Pr(X_i = 1|Y_1,...,Y_t)$ when $X_i \sim \text{ind. Ber}(0.5)$. \end{itemize} \section{Notation and Tools} \label{sec:notations} \noindent \textbf{Basic notations:} In this work, we borrow a majority of the notation and tools from \cite{lothaire1997combinatorics} which deals with non-commutative algebra. We restate the definitions here for convenience. Calligraphic letters refer to sets, capitalized letters correspond to random variables and bold letters are used for functions. Let $\mathcal{A}$ be the set of all symbols. Throughout this work, we will focus on the case where $\mathcal{A}=\{0,1\}$, though our methods extend to arbitrarily large sets of finite size. Define $\mathcal{A}^n$ to be the set of all $n$-length sequences and $\mathcal{A}^*$ to be the set of all finite length sequences with symbols in $\mathcal{A}$. For a sequence $f$, $|f|$ denotes the length of $f$. For integers $i,j$, we define $[i:j] \triangleq \{i,i+1,...,j\}$ if $j\geq i$ and $[i:j] \triangleq \emptyset$ otherwise. Also define $[i] \triangleq [1:i]$.\\ \noindent \textbf{Binomial coefficient:} Given sequences $f$ and $g$ in $\mathcal{A}^*$, the number of subsequence patterns of $f$ that are equal to $g$ is called the \textit{binomial coefficient} of $g$ in $f$ and is denoted by $f \choose g$. For example, ${'apple' \choose 'ape'} = 2$ since $'ape'$ can be obtained from two (overlapping) subsequences of $'apple'$. When the alphabet $\mathcal{A}$ is of cardinality 1, ${f \choose g} = {|f| \choose |g|}$, the classical binomial coefficient with their respective lengths as the parameters. This definition hence could be thought of as a generalization of the classical binomial coefficients. We will denote by $e$ the sequence of length 0, and {define ${f \choose e} \triangleq 1\ \forall\ f\ \in\ \mathcal{A}^*$.} We also define the classical binomial coefficient ${a \choose b}\triangleq 0,$ whenever $b>a$ or $b<0$ for ease of use. The binomial coefficient is an integral aspect of this work and for analyzing error events in deletion channels because the input-output relation for a deletion channel (with deletion probability $\delta$, input $X$ and output $Y$) can be expressed as \begin{equation} \label{eq:in-out_relation} \Pr(Y=y|X=x) = {x \choose y} \delta^{|x|-|y|} (1-\delta)^{|y|}. \end{equation} The proof is straight-forward -- the number of distinct error events that give rise to $y$ from $x$ is exactly the number of subsequences of $x$ which are equal to $y$. Each of these error events has a probability $\delta^{|x|-|y|} (1-\delta)^{|y|}$, wherein the exponent of $\delta$ corresponds to the deleted symbols and the exponent of $1-\delta$ to the undeleted symbols. Given the definition of the binomial coefficient, the maximum-likelihood (ML) estimate over a deletion channel with observed output $Y$ can be cast in the following form: \begin{align*} \argmax_{x \in \mathcal C} {x \choose Y},\numberthis \label{eq:ML_deletion} \end{align*} where $\mathcal C$ is the chosen codebook. In the case of multiple deletion channels with observed traces $Y^{(1)},...,Y^{(t)}$, the ML formulation is similar: \begin{align*} \argmax_{x \in \mathcal C} \prod_{j=1}^{t} {x \choose Y^{(j)}}.\numberthis \label{eq:ML_multiple_deletion} \end{align*} As yet, there is no known efficient way to come up with a solution for the above two formulations, even for \eqref{eq:ML_deletion} with $\mathcal C = \{0,1\}^n$ (see \cite{mitzenmacher2009survey}). In this work, we attempt to take a step in this direction by showing that a continuous relaxation of \eqref{eq:ML_deletion} is equivalent to \eqref{eq:ML_deletion}. However, an efficient algorithm to solve the optimization \eqref{eq:ML_deletion} remains open. In the context of trace reconstruction, the ultimate pursuit would be an algorithm for \eqref{eq:ML_multiple_deletion} with $\mathcal C = \{0,1\}^n$ and error analysis thereof. \noindent We now describe a function which can be thought of as a real-valued extension of the binomial coefficient. This function is used in sections~\ref{sec:1deletion_ML} and \ref{sec:1deletion}. Consider the function $\mathbf F(\cdot)$ defined as: \begin{definition} \label{def:f} \begin{align*} &\mathbf F: \mathbb{R}^k \times \{0,1\}^l \rightarrow \mathbb{R},\\ \mathbf F(q, v)\triangleq &\begin{cases} \sum\limits_{\substack{\mathcal S|\mathcal S\subseteq [k],\\|\mathcal S|=l}} \quad \prod\limits_{i=1}^l q_{\mathcal S_i}^{v_i} (1-q_{\mathcal S_i})^{1-v_i} & 1 \leq l\leq k \\ 1 & 0=l\leq k \\ 0 & \text{else}. \end{cases} \end{align*} \noindent An alternate definition is as follows: consider a random vector $Z\in\{0,1\}^k$ such that $Z_i\sim$ ind. Ber$(q_i)$, let $q$ be the vector of probabilities of length $k$, $\mathcal S\subseteq [k]$ a subset of the indices of size $l$, and ${v}$ a binary vector of length $l$. Then, $$\mathbf F(q,v)=\sum_{\substack{\mathcal S||\mathcal S|=l}} \Pr(Z_{\mathcal S}= v).$$ Note that if $q$ is a vector of $0$'s and $1$'s, then $\mathbf F( q, v)={q \choose v}$, the binomial coefficient of $v$ in $q$. Thus, $\mathbf F(\cdot)$ could be interpreted as an extension of the binomial coefficient where one of the parameters can take values in $[0,1]^n$ instead of $\{0,1\}^n$. \end{definition} Though at first sight, $\mathbf F(q,v)$ sums over an exponential number of subsets, a dynamic programming approach can be used to compute it in $O(|v|^2)$ time complexity. The dynamic program is described in section~\ref{sec:1deletion}. \iffalse \noindent \textbf{Edit distance:} The edit distance $d_e(f,g)$ measures similarity between two sequences of possibly different lengths \cite{Navarro2001}. $d_e(f,g)$ is the minimum number of operations needed to transform $f$ to $g$, where the permitted operations are insertion, deletion or substitution of a symbol. In this work, we quantify the performance of algorithms in Section \ref{sec:Numerics} using the edit distance metric. \fi The following definitions and ideas are relevant only for \ref{sec:exactsmap} and can be omitted for the sections on single deletion channel. Before getting to the mathematical definitions, we first state a result of ours that aids in thinking about error events in multiple deletion channels. \subsection{An alternate interpretation of multiple deletion channel model} The events occurring in the $t$-deletion channel model can be categorized into two groups: \begin{enumerate} \item an input symbol is deleted in \textit{all} the $t$-traces, \item an input symbol is reflected in at least one of the traces. \end{enumerate} The error events of the first kind are in some sense ``not correctable" or even ``detectable" since it is impossible to tell what and where the deleted symbol could have been (although the probabilities need not be uniform). The events of the second kind, however, can still be detected although they could likely be confused with a large set of similar events. This thought process gives rise to a natural decomposition of the $t$-deletion channel model into a cascade of two channels: the first one being a deletion channel which captures error events of the first kind and the second one is what we call the \textit{remnant channel} which captures events of the second kind (see Fig.~\ref{fig:channel_equiv}). More precisely, the remnant channel is defined as follows: \begin{definition} \textit{Remnant channel:} an input symbol to the remnant channel is reflected in $k>0$ given outputs and deleted in the rest with a probability $\frac{\delta^{t-k}(1-\delta)^k}{1-\delta^t}$. \end{definition} It is easy to note that probability of the union of all possible events here is $\sum_{k=1}^t {t \choose k} \frac{\delta^{t-k}(1-\delta)^k}{1-\delta^t}=1$, validating our definition. \begin{restatable}{theorem}{channelequiv} \label{thm:channel_equiv} The $t$-deletion channel model and the cascade of the deletion channel with remnant channel shown in Fig.~\ref{fig:channel_equiv} are probabilistically equivalent, i.e., $$\Pr({Y}^{(1)},{Y}^{(2)},...,{Y}^{(t)}|X = x) = \Pr(\tilde{Y}^{(1)},\tilde{Y}^{(2)},...,\tilde{Y}^{(t)}|X = x).$$ \end{restatable} The formal proof of the theorem requires few more definitions and is relegated to the appendix. \begin{figure}[!h] \begin{center} \includegraphics[scale=0.4]{channel_equiv.pdf} \caption{A channel equivalence result: the $t$-deletion channel model in (a) is probabilistically equivalent to the the cascade of a deletion channel with the \textit{remnant channel} ($ \mathcal C_2$) in (b).} \label{fig:channel_equiv} \end{center} \end{figure} \noindent\textbf{Edit graph} (as defined in \cite{Gusfield1997}): We now define a graph construct which is closely related to the error events in the remnant channel. We start with a simple case and generalize subsequently. Define an \textit{edit graph} given two sequences $f$ and $g$, where every path connecting the ``origin'' to the ``destination'' on the edit graph yields a supersequence $h$ of $f,g$, where $h$ is ``covered'' by $f,g$ -- i.e., each symbol of $h$ comes from either $f$ or $g$ or both. In other words, given that $f$ and $g$ are the outputs of the remnant channel (with two outputs), each path from the origin of the edit graph to the destination corresponds to a possible input $h$ to the remnant channel and to an error event which resulted in $f$ and $g$ with input $h$. For $f$ and $g$ in $\mathcal A^*$, we form a graph $\mathcal{G}(f,g)$ with $(|f|+1)(|g|+1)$ vertices each labelled with a distinct pair $(i,j), 0\leq i\leq |f|,\ 0\leq j\leq |g|$. A directed edge $(i_1,j_1)\rightarrow(i_2,j_2)$ exists iff at least one of the following holds: \begin{enumerate} \item$i_2-i_1=1$ and $j_1=j_2$, or \item $j_2-j_1=1$ and $i_1=i_2$, or \item $i_2-i_1=1$, $j_2-j_1=1$ and $f_{i_2}=g_{j_2}$, \end{enumerate} where $f_i$ is the $i^{th}$ symbol of the sequence $f$. The origin is the vertex $(0,0)$ and the destination $(|f|,|g|)$. \begin{figure}[!h] \centering \includegraphics[scale=0.25]{editgraph_smap1.pdf} \caption{ Edit graph for sequences $f=$ `001' and $g=$ `101'. An easy way to think about this is to write down $f$ vertically with each symbol aligned to a vertical set of edges and $g$ horizontally likewise. A diagonal edge in a small square exists if the corresponding $f$ and $g$ symbols are equal. The thick red edges form a path from the origin to the destination; this path corresponds to the sequence `0101' -- append the corresponding symbol at the left of an edge if it's vertical or diagonal, otherwise append the symbol at the top. It is also easy to verify that 0101 is a supersequence of both $f$ and $g$, and could be obtained as a covering of $f$ and $g$; the path itself gives one such covering. This covering also corresponds to an error event in the remnant channel which would result in outputs $f$ and $g$ with input $h=$ `0101' -- more precisely, the error event is one in which the first symbol of $h$ is deleted only in $g$, the second symbol is deleted only in $f$ and the third and fourth symbols not deleted in either $f$ or $g$.} \label{fig:editgraph_smap1} \end{figure} Let $p=((i_1,j_1),(i_2,j_2),...,(i_m,j_m))$ be a path in $\mathcal{G}(f,g)$. We define $ s(p)$ to be the sequence corresponding to the path. Intuitively, $s(p)$ is formed by appending symbols in the following way: append the corresponding $f$ symbol for a vertical edge, $g$ symbol for horizontal edge, and $f$ or $g$ symbol for diagonal edge (see example Fig.~\ref{fig:editgraph_smap1}). Any path from $(0,0)$ to $(|f|,|g|)$ corresponds to a supersequence of $f$ and $g$ and which is ``covered" by $f$ and $g$. More formally, define $ s(p)\triangleq x_1x_2...x_{m-1}$ where $$x_k = \begin{cases} f_{i_{k+1}} \quad\text{if }j_{k}=j_{k+1},\\ g_{j_{k+1}} \quad\text{if }i_{k}=i_{k+1},\\ f_{i_{k+1}} \quad\text{else.} \end{cases} $$ The construct of edit graph can be extended to more than 2 sequences with the same idea. For sequences $f_1,f_2,...,f_t$, construct a $t$-dimensional grid with a number of vertices $(|f_1|+1)(|f_2|+1)...(|f_t|+1)$ labeled from $(0,0,...,0)$ to $(|f_1|,|f_2|,...,|f_t|)$. A vertex $u=(i_1,i_2,...,i_t)$ is connected to $v=(j_1,j_2,...,j_t)$ (we say $u \rightarrow v$) iff both of the following conditions are met: \begin{itemize} \item $j_l=i_l$ or $j_l=i_l+1$ $\forall\ l\in [t]$, i.e., $(i_1,...,i_t)$ and $(j_1,...,j_t)$ are vertices of a particular unit cube. Only these type of vertices can share an edge in the grid graph. \item Let $\mathcal T \subseteq [t]$ be the collection of indices where $j_l=i_l+1$. Then $f_{i_l}$ is same $\forall\ l \in \mathcal T$. For instance, if $\mathcal T=\{1,3,5\}$, then $f_{i_1}=f_{i_3}=f_{i_5}$. \end{itemize} Define the vertex $(0,...,0)$ to be the origin of this graph and the vertex $(|f_1|,...,|f_t|)$ to be the destination. If $|f_j|=O(n)\ \forall\ j$, this graph has a number of vertices $O(n^t)$ and a maximum number of edges $O((2n)^t)$ since each vertex has at most $2^t$ outgoing edges.\\ \noindent\textbf{Infiltration product} (introduced in \cite{lothaire1997combinatorics}): The infiltration product has been extensively used in \cite{lothaire1997combinatorics}, as a tool in non-commutative algebra. Here we give an edit-graph interpretation of this tool. We also give a formal definition later in this section. Using the edit graph we can construct the set of possible supersequences $\mathcal{S}(f,g)$ of $f,g$ which are covered by it. Clearly multiple paths could yield the same supersequence and we can count the number of distinct ways $\mathbf N(h;f,g)$ one can construct the same supersequence $h$ from $f,g$. We can informally define the \emph{infiltration product $f\uparrow g$} of $f$ and $g$, as a polynomial with monomials the supersequences $h$ in $\mathcal{S}(f,g)$ and coefficients $\langle f\uparrow g,h\rangle$ equal to $\mathbf N(h;f,g)$. In Fig.~\ref{fig:editgraph_smap1}, it is easy to verify that there is exactly one path corresponding to `101001' and hence $\langle 001\uparrow 101,101001 \rangle=1$ and similarly $\langle 001\uparrow 101,01001 \rangle=2$. One could find these coefficients for all relevant sequences and form the polynomial as described. More examples: Let $\mathcal{A}=\{a,b\}$, then \begin{itemize}[wide=2pt] \item $ab\uparrow ab=ab+2aab+2abb+4aabb+2abab$, \item $ab\uparrow ba=aba+bab+abab+2abba+2baab+baba.$ \end{itemize} The infiltration operation is commutative and associative, and infiltration of two sequences $f\uparrow g$ is a polynomial with variables of length (or \textit{degree}) at most $|f|+|g|$; see \cite{lothaire1997combinatorics}. The definition of infiltration extends to two polynomials via distributivity (precisely defined in later), and consequently to multiple sequences as well. For multiple sequences, infiltration has the same edit graph interpretation: $\langle f_1\uparrow f_2 \uparrow...\uparrow f_t, w \rangle$ is the number of distinct ways of constructing $w$ as a supersequence of $f_1, f_2, ... ,f_t$ so that the construction covers $w$, i.e., construct the $t$-dimensional edit graph of $f_1, f_2, ... ,f_t$ and count the number of paths corresponding to $w$. \subsection{Formal definition of infiltration product} We now give a more formal definition of the infiltration product (see \cite{lothaire1997combinatorics} for the equivalence of the two definitions and a more rigorous treatment). A \textit{formal series} with indeterminates (or variables) in a set $\mathcal A$ and coefficients in a commutative ring $\mathcal R$, is a mapping of $\mathcal A^*$ onto $\mathcal R$. Recall that a commutative ring is a set which forms an abelian group under an \textit{addition} operation, is a monoid under a \textit{multiplication} operation which commutes, and the multiplication operation distributes over addition. Here we consider $\mathbb Z$, the set of integers as the commutative ring $\mathcal{R}$. A formal series is called a \textit{polynomial} if only a finite number of sequences are mapped to non-zero values, the rest of the sequences map to zero. Consider two polynomials $\sigma,\tau: \mathcal{A}^*\rightarrow \mathbb Z$. The value taken by a sequence $w\in \mathcal A^*$ on $\sigma$ (or the coefficient of $w$ in $\sigma$) is denoted by $\langle \sigma,w\rangle \in \mathbb R$. We also define binary addition ($\oplus$) and multiplication operations ($\times$) on the set of polynomials as follows: \begin{align} \langle \sigma\oplus \tau,w\rangle \triangleq \langle \sigma,w\rangle + \langle \tau,w \rangle \quad \forall w\in \mathcal A^*,\label{eq:polynomial_add}\\ \langle \sigma\times \tau,w\rangle \triangleq \sum_{\substack{f,g\in \mathcal A^*:\\ f.g=w}}\langle \sigma,f\rangle \langle \tau,g \rangle \quad \forall w\in \mathcal A^*.\label{eq:polynomial_prod} \end{align} We will use the usual symbols $+$ and $.$ in place of $\oplus$ and $\times$ in this work for convenience. The meaning of the operation would be clear depending on the operands. With these operations the set of polynomials form a non-commutative ring, and is denoted by $\mathbb Z\langle\mathcal A \rangle$, also called the free $\mathbb Z$-algebra on $\mathcal A$ in ring theory. Note that the addition and multiplication operations defined in \eqref{eq:polynomial_add} and \eqref{eq:polynomial_prod} are similar to the operations defined on commutative polynomials, except that the multiplication operation under the summation in \eqref{eq:polynomial_prod} ($f.g=w$) is actually concatenation and is non-commutative. The multiplication inside the summation in \eqref{eq:polynomial_prod} is multiplication in the real field and hence commutative. It is also easy to prove that the multiplication defined in \eqref{eq:polynomial_prod} distributes over addition defined in \eqref{eq:polynomial_add}. Thus, a polynomial in $\mathbb Z\langle\mathcal A \rangle$ can be represented as a sum of monomials in $\mathcal A^*$ each with an associated coefficient in $\mathbb Z$, i.e., $\sigma=\sum\limits_{w\in \mathcal A^*} \langle\sigma,w \rangle w$. Define the \textit{degree} of a polynomial to be equal to the length of a longest sequence with a non-zero coefficient in the polynomial and the \textit{number of terms} of a polynomial as the number of sequences with non-zero coefficients in the polynomial. Note that a degree $d$ polynomial could have a number of terms upto $2^{d+1}-1$. With this, the \textit{infiltration product} (in general, for two polynomials) is defined as follows: \begin{align} \forall f\in \mathcal{A}^*,& \quad f\uparrow e = e\uparrow f=f.\nonumber \\ \forall f,g\in \mathcal{A}^*&,\quad \forall a,b\in \mathcal{A}, \nonumber\\ fa\uparrow gb=(f\uparrow gb)a&+(fa\uparrow g)b+\mathbbm{1}_{a=b}(f\uparrow g)a.\nonumber \\ \forall \sigma,\tau \in \mathbb{Z}\langle\mathcal{A} \rangle, \quad &\sigma\uparrow \tau=\sum_{f,g\in \mathcal{A}^*} \langle \sigma,f \rangle \langle \tau,g \rangle (f\uparrow g). \label{def:infiltforseq} \end{align} \textbf{Summary of definitions and ideas introduced in this section:} \begin{itemize} \item The binomial coefficient captures the likelihood of observations for deletion channels. \item An extension of the binomial coefficient function where one of the parameters can take real values has been introduced; this function is pivotal for our results on the single-trace deletion channel. \item For multiple deletion channels, the error events can be categorized into two groups -- one where an input symbol is deleted in all the traces, and second, the complement of this event. This categorization results in a natural decomposition of multiple deletion channel model into a cascade model involving the remnant channel. \item The remnant channel disregards the error events where a symbol is deleted in all the traces. \item The edit graph provides a way to visualize all the possible error events and input sequences to a remnant channel given its outputs. \item The infiltration product serves the same purpose as the edit graph, but has an algebraic flavor and provides rigor for proofs and analyses. The edit graph, on the other hand, is more helpful in designing reconstruction algorithms over deletion channels. \end{itemize} \section{Maximum likelihood for the single-trace deletion channel} \label{sec:1deletion_ML} Consider the ML formulation for the single-trace deletion channel given non-empty trace $Y$ and all possible $n$-length inputs allowed, restated here for convenience: \begin{equation} \argmax_{x\in \{0,1\}^n} {x \choose Y}. \label{eq:1deletion_ML} \end{equation} To the best of our knowledge, the only known method to solve \eqref{eq:1deletion_ML} involves iterating over all possible choices of $x$ and computing the objective value for each of the choices. We here show that it is sufficient to solve a continuous relaxation of above problem to obtain a solution to \eqref{eq:1deletion_ML}. Note that there could be multiple solutions to \eqref{eq:1deletion_ML}. Before going in the main result, we first state a useful lemma which factors out a given coordinate $p_i$ out of $\mathbf F(p,Y)$. The proof of the lemma is relegated to the appendix. \begin{restatable}{lemma}{deletionMLrellemma} For $p=[p_1,p_2,..,p_i,...,p_n]$ and $Y=Y_1Y_2...Y_m$ with $n \geq m > 0$, we have \begin{align*} \mathbf F(p,Y) = \mathbf F( p_{[n]\backslash \{i\}},Y) + p_i \sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]})\\ + (1-p_i) \sum\limits_{k|Y_k=0}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}). \end{align*} \label{lemma:F_decomposition} \end{restatable} \begin{theorem} An alternative optimization to characterize ML for the single-trace deletion channel. \begin{equation} \max_{x\in \{0,1\}^n} {x \choose Y} = \max_{p\in [0,1]^n} \mathbf F(p,Y). \label{eq:ml_opt_equiv} \end{equation} Furthermore, given any non-integral $p^* \in [0,1]^n$ that maximizes $\mathbf F(p,Y)$, one could construct a corresponding integral solution $x^* \in \{0,1\}^n$ that maximizes $\mathbf F(p,Y)$ and consequently is also a solution to $\max_{x\in \{0,1\}^n} {x \choose Y}$. \end{theorem} \begin{proof} As noted earlier, we have ${x \choose Y} = \mathbf F(x,Y)$. Therefore, we are interested in proving the following: \begin{align*} \max_{x\in \{0,1\}^n} \mathbf F(x,Y) \equiv \max_{p\in [0,1]^n} \mathbf F(p,Y).\numberthis \label{eq:ml_opt_equiv_proof1} \end{align*} To show this and also the second statement, we prove that given $p=(p_1,p_2,...,p_i,...,p_n)$, at least one of the following holds true: \begin{itemize} \item$\mathbf F(p^{(i\rightarrow 0)},Y) \geq \mathbf F(p,Y)$, where $p^{(i\rightarrow 0)}=(p_1,p_2,...,p_{i-1},0,p_{i+1}...,p_n)$ is the vector where the $i^{th}$ coordinate is replaced by 0. \item $\mathbf F(p^{(i\rightarrow 1)},Y) \geq \mathbf F(p,Y)$, where $p^{(i\rightarrow 0)}=(p_1,p_2,...,p_{i-1},1,p_{i+1}...,p_n)$ is the vector where the $i^{th}$ coordinate is replaced by 1. \end{itemize} Thus if $p^*$ is an optimal solution to $\max_{p\in [0,1]^n} \mathbf F(p,Y)$ with $p_i\in (0,1)$, then at least one of $p^{(i\rightarrow 0)}$ or $p^{(i\rightarrow 1)}$ is also an optimal solution. Sequentially applying this argument for each coordinate of $p$ shows that there exists a point in $\{0,1\}^n$ which is also an optimal solution to $\max_{p\in [0,1]^n} \mathbf F(p,Y)$ and consequently to $\max_{x\in \{0,1\}^n} \mathbf F(x,Y)$. Now to prove our claim, we use Lemma~\ref{lemma:F_decomposition} to factor out $p_i$ terms in $\mathbf F(p,Y)$: \begin{align*} \mathbf F(p,Y) = \mathbf F( p_{[n]\backslash \{i\}},Y) + p_i \sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]})\\ + (1-p_i) \sum\limits_{k|Y_k=0}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}). \end{align*} There are 3 cases \begin{enumerate} \item $$\sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}) = \sum\limits_{k|Y_k=0}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}).$$ \\In this case it is easy to verify that $\mathbf F(p^{(i\rightarrow 0)},Y) = \mathbf F(p,Y) = \mathbf F(p^{(i\rightarrow 1)},Y).$ \item $$\sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}) > \sum\limits_{k|Y_k=0}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}).$$ \\In this case it is easy to verify that $\mathbf F(p^{(i\rightarrow 0)},Y) \leq \mathbf F(p,Y) \leq \mathbf F(p^{(i\rightarrow 1)},Y).$ \item $$\sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}) < \sum\limits_{k|Y_k=0}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}).$$ \\In this case it is easy to verify that $\mathbf F(p^{(i\rightarrow 0)},Y) \geq \mathbf F(p,Y) \geq \mathbf F(p^{(i\rightarrow 1)},Y).$ \end{enumerate} Thus in each of the 3 cases, we see that at least one of $\mathbf F(p^{(i\rightarrow 0)},Y)$ or $\mathbf F(p^{(i\rightarrow 1)},Y)$ is at least as large as $\mathbf F(p,Y)$ thus proving the theorem. Note that the proof gives a natural way to find an optimal lattice point $p_{lattice}^*$ given a non-lattice point $p^*$ by iterating through each coordinate of $p^*$ and switching them to $0$ or $1$ by comparing $\sum\limits_{k|Y_k=1}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]})$ with $\sum\limits_{k|Y_k=0}\mathbf F( p_{[1:i-1]}, Y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, Y_{[k+1,m]}).$ \end{proof} \section{Symbolwise MAP for the single-trace deletion channel} \label{sec:1deletion} We here develop an algorithm to compute the symbolwise posterior probabilities for the single-trace deletion channel when the input symbols are independently generated with arbitrary priors. Consider the single deletion channel model in Fig.~\ref{fig:1deletion}, where $X=X_1...X_n$, each input symbol is generated $X_i \sim \text{ind. Ber}\ (p_i)$, and we observe the trace $Y = y = y_1y_2...y_m$ with $m\leq n$. Define the vector of priors as $p\triangleq(p_1,p_2,...,p_n)$. We first give an $O(n^2)$ algorithm to calculate the posterior probabilities $\Pr(X_i=1|Y=y)$, which in turn provides the symbolwise MAP estimate for the considered model. We then show how this algorithm can be used for trace reconstruction. We take three steps to present the algorithm. \noindent \textbf{An expression for $\Pr(X_i=1|Y=y)$.} Let $\Pr(X_i=1)=p_i$. As a first step, we have \vspace{6pt} \begin{align*} \Pr(X_i=1|{Y=y}) &= \frac{\Pr(X_i=1,Y=y)}{\Pr(Y=y)} = \frac{ \sum\limits_{\substack{ x| x_i=1}} \Pr({X=x}) \Pr(Y=y|X=x)}{ \sum_{\substack{x}} \Pr({X=x}) \Pr(Y=y|X=x)} \\ &\overset{(a)}{=} \frac{ \sum\limits_{\substack{ x| x_i=1}} \Pr({X=x}) { x \choose y}}{ \sum_{\substack{x}} \Pr({X=x}) { x \choose y}}, \numberthis \label{eq:approx_smap_1} \end{align*} where $(a)$ is because for a deletion channel $\Pr(Y=y|X=x)={x \choose y} \delta^{|x|-|y|}(1-\delta)^{|y|}$. To proceed, we need to evaluate the summation in the numerator and the denominator. Theorem~\ref{thm:approx_smap_postprob} expresses \eqref{eq:approx_smap_1} in terms of relaxed binomial coefficient terms $\mathbf F(\cdot)$. Recall that $\mathbf F(p,y) \triangleq \mathbb E_{X\sim p} {X \choose y}$, which is the denominator term in \eqref{eq:approx_smap_1}. \begin{theorem} \label{thm:approx_smap_postprob} Let $X=X_1...X_n$ where $X_i \sim \text{ind. Ber}\ (p_i)$, and let $Y=y$ be the observed trace when $X$ is passed through a deletion channel. Then, \begin{align*} \Pr(X_i&=1|Y=y) = \frac{p_i}{\mathbf F( p, y)} \left( \mathbf F( p_{[n]\backslash \{i\}}, y) + \sum\limits_{k|y_k=1}\mathbf F( p_{[1:i-1]}, y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, y_{[k+1,m]}) \right). \numberthis \label{eq:smap_postprob_thm} \end{align*} \end{theorem} \begin{proof} The proof of this theorem employs the same trick used in the proof of Lemma~\ref{lemma:F_decomposition}. From \eqref{eq:approx_smap_1}, we have \begin{align*} \Pr(X_i = 1 | Y=y) = \frac{ \sum\limits_{\substack{ x| x_i=1}} \Pr({X=x}) { x \choose y}}{\mathbf F(p,y)}. \end{align*} Now, \begin{align*} \sum_{\substack{ x| x_i=1}} & \Pr({X=x}) { x \choose y} =\sum_{\substack{ x|x_i=1}} \Pr({X=x}) \sum_{\substack{\mathcal S\subseteq [n]\\ |\mathcal S|=m}} \mathbbm{1}\{ x_{\mathcal S}= y\}\\ &=\sum_{\substack{\mathcal S\subseteq [n]\\ |\mathcal S|=m}} \sum_{\substack{ x|x_i=1\\x_{\mathcal S}=y}} \Pr({X=x}).\numberthis \label{eq:smapiter1} \end{align*} We first separate the outer summation into two cases: (a) $\mathcal S|i \notin \mathcal S$ and (b) $\mathcal S|i\in \mathcal S$. We can express the first case as \begin{align*} &\hspace{-1cm}\sum_{\substack{\mathcal S\subseteq [n] \\ |\mathcal S|=m,i\notin \mathcal S}}\sum_{\substack{ x|x_i=1\\x_{\mathcal S}=y}} \Pr({X=x}) =\sum_{\substack{\mathcal S\subseteq [n]\backslash \{i\}\\ |\mathcal S|=m}} \sum_{\substack{ x|x_i=1\\x_{\mathcal S}=y}} \Pr({X=x})\\ &=\sum_{\substack{S\subseteq [n]\backslash \{i\}\\ |\mathcal S|=m}} \sum_{\substack{ x|x_i=1\\ x_{\mathcal S}= y}} \Big(\Pr(X_i=1)\Pr( X_{\mathcal S}= y) \Pr( X_{[n]\backslash \mathcal S\cup\{i\}}= x_{[n]\backslash \mathcal S\cup\{i\}}) \Big)\\ &=\sum_{\substack{\mathcal S\subseteq [n]\backslash \{i\}\\ |\mathcal S|=m}} p_i \Pr( X_{\mathcal S}= y) \left(\sum_{\substack{ x|x_i=1\\ x_{\mathcal S}= y}} \Pr( X_{[n]\backslash \mathcal S\cup\{i\}}= x_{[n]\backslash \mathcal S\cup\{i\}})\right)\\ &=\sum_{\substack{\mathcal S\subseteq [n]\backslash \{i\}\\ |\mathcal S|=m}} p_i \Pr( X_{\mathcal S}= y) \left(\sum_{(x_j|j\in [n]\backslash \mathcal S\cup \{i\})} \Pr( X_{[n]\backslash \mathcal S\cup\{i\}}= x_{[n]\backslash \mathcal S\cup\{i\}})\right)\\ &=p_i \sum_{\substack{\mathcal S\subseteq [n]\backslash \{i\}\\ |\mathcal S|=m}} \Pr( X_{\mathcal S}= y) = p_i \mathbf F( p_{[n]\backslash \{i\}}, y).\numberthis \label{eq:lemma3proof1} \end{align*} For the second term, we express the set $\mathcal S$ as a union $\mathcal S = \mathcal S' \cup \{i\} \cup \mathcal S''$ such that $\mathcal S' \subseteq [i-1]$ and $\mathcal S'' \subseteq [i+1:n]$ to get: \begin{align*} &\sum_{\substack{\mathcal S\subseteq [n]\\ |\mathcal S|=m,\\i\in \mathcal S}} \sum_{\substack{ x|x_i=1\\x_{\mathcal S}=y}} \Pr({X=x})= \sum_{k=1}^m\sum\limits_{\substack{\mathcal S\subseteq [n],\\|\mathcal S|=m,\\ \mathcal S_k = i}} \sum_{\substack{ x|x_i=1\\x_{\mathcal S}=y}} \Pr({X=x})\\ &=\sum_{k=1}^m\sum_{\substack{\mathcal S'\subseteq [i-1]\\ |\mathcal S'|=k-1}}\sum_{\substack{\mathcal S''\subseteq [i+1:n]\\ |\mathcal S''|=m-k}} \sum_{\substack{ x|x_i=1\\x_{\mathcal S}=y}}\mathbbm{1}_{\{y_k=1\}} \Pr({X=x}) \\ &=\sum_{k:y_k=1}\sum_{\substack{\mathcal S'\subseteq [i-1]\\ |\mathcal S'|=k-1}}\sum_{\substack{\mathcal S''\subseteq [i+1:n]\\ |\mathcal S''|=m-k}} \sum_{\substack{ x|x_i=1\\ x_{\mathcal S'}= y_{[1:k-1]}\\ x_{\mathcal S''}= y_{[k+1:m]}}} \Bigg ( \Pr(X_i=1) \Pr( X_{\mathcal S'}= y_{[1:k-1]}) \Pr( X_{\mathcal S''}= y_{[k+1:m]}) \\&\hspace{7cm} \Pr( X_{[n]\backslash \mathcal S'\cup \mathcal S''\cup \{i\}}= x_{[n]\backslash \mathcal S'\cup \mathcal S'' \cup\{i\}})\Bigg )\\ &=p_i\sum_{k:y_k=1}\Bigg ( \Big( \sum_{\substack{\mathcal S'\subseteq [i-1]\\ |\mathcal S'|=k-1}}\Pr( X_{\mathcal S'}= y_{[1:k-1]})\Big) \Big(\sum_{\substack{\mathcal S''\subseteq [i+1:n]\\ |\mathcal S''|=m-k}}\Pr( X_{\mathcal S''}= y_{[k+1:m]})\Big ) \\ & \hspace{5cm} \Big( \sum_{\substack{ x|x_i=1\\ x_{\mathcal S'}= y_{[1:k-1]}\\ x_{\mathcal S''}= y_{[k+1:m]}}} \Pr( X_{[n]\backslash \mathcal S'\cup \mathcal S''\cup \{i\}}= x_{[n]\backslash \mathcal S'\cup \mathcal S'' \cup\{i\}})\Big) \Bigg )\\ &=p_i\sum_{k|y_k=1}\Bigg(\Big( \sum_{\substack{\mathcal S'\subseteq [i-1]\\ |\mathcal S'|=k-1}}\Pr( X_{\mathcal S'}= y_{[1:k-1]})\Big) \Big( \sum_{\substack{\mathcal S''\subseteq [i+1:n]\\ |\mathcal S''|=m-k}}\Pr( X_{\mathcal S''}=y_{[k+1:m]}) \Big)\Bigg)\\ &=p_i \sum\limits_{k|y_k=1}\mathbf F( p_{[1:i-1]}, y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, y_{[k+1,m]}). \numberthis \label{eq:lemma3proof2} \end{align*} Plugging in \eqref{eq:lemma3proof1} and \eqref{eq:lemma3proof2} in \eqref{eq:approx_smap_1} proves the theorem. \end{proof} Alg.~\ref{alg:apprx_smap_dp} summarizes the computation of $\Pr(X_i=1|Y=y)$. \begin{algorithm}[t!] \caption{Symbolwise posterior probabilities with one trace}\label{alg:apprx_smap_dp} \begin{algorithmic}[1] \item Input: Trace {$Y=y$}, priors $p$\\ Outputs: Posteriors $\Pr(X_i=1|Y=y)\ \forall\ i$ \State Compute $\mathbf F(p_{[1:k]},y_{[1:j]})\ \forall\ k,j$ and $\mathbf F(p_{[k:n]},y_{[j:m]})\ \forall\ k,j$ via Alg.~\ref{alg:F_comp} \For {$i=1:n$} \State Use \eqref{eq:smap_postprob_thm} to compute $\Pr(X_i=1|Y=y)$ \EndFor \end{algorithmic} \end{algorithm} \noindent\textbf{A trace reconstruction heuristic with $t$ traces.} The posterior probability computation in Alg.~\ref{alg:apprx_smap_dp} naturally gives rise to a trace reconstruction heuristic that updates the symbolwise statistics sequentially on the traces, where we use Alg.~\ref{alg:apprx_smap_dp} with one trace at a time to continually update $\Pr(X_i=1|Y=y)$. The overall heuristic is described in Alg.~\ref{alg:apprx_smap}. Note that the algorithm first needs to compute $\mathbf F(p_{[1:k]},y_{[1:j]})\ \forall\ k,j$ and $\mathbf F(p_{[k:n]},y_{[j:m]})\ \forall\ k,j$ which requires $O(n^2)$ operations, as described in Appendix~\ref{app:F_compute}. Given this, the algorithm iterates over the $n$ indices and computes the posteriors in $O(n)$ for each of the index. Thus, the complexity of the algorithm is $O(n^2)$; note that $m=O(n)$ since $y$ is a deleted version of the input. \begin{algorithm}[t!] \caption{Trace reconstruction via iterative single-trace posterior probabilities}\label{alg:apprx_smap} \begin{algorithmic}[1] \item Input: Traces {$Y^{1}=y^1,...,Y^{t}=y^t$}, input length $n$ \\ Outputs: Estimate of the input $\hat X$ \State Initialize priors $p^{old}=p^{new} \gets (0.5,0.5,...,0.5)$ \For {$l=1:t$} \State Use Alg.~\ref{alg:apprx_smap_dp} with $p^{old}$ and $y^{l}$ to update $p^{new}$ \State $p^{old}\gets p^{new}$ \EndFor \For {$i=1:n$} \If {$p^{new}_i\geq 0.5$} $\ \hat X_i \gets 1$ \Else $\ \hat X_i \gets 0$ \EndIf \EndFor \State \textbf{return} $\hat X_1 \hat X_2 ... \hat X_n$ \end{algorithmic} \end{algorithm} \section{Sequencewise ML for the deletion channel} \label{sec:1deletion_ML} \subsection{A continuous optimization formulation for the single trace ML} We here consider the single-trace ML decoding in (\ref{eq:ML_deletion}), assuming that the output sequence $Y=y$ is non-empty. To the best of our knowledge, the only known method to solve \eqref{eq:ML_deletion} involves solving a combinatorial optimization, essentially iterating over all possible choices of $x$ and computing the objective value for each of the choices. The reason is that there seems to be no discernible pattern exhibited by the true ML sequence; as we see in the table below, the true ML sequence at times extends a few runs, and at times even introduces new runs! Here, we list a few examples of the trace and the corresponding 10-length ML sequences. \begin{center} \begin{tabular}{ | c | c| } \hline $y$ & The set of all $x_{ml}$ sequences \\ \hline 10111 & 1100111111 \\ \hline 1010 & 1101010100 \\ \hline 000100 & 0000001000, \quad 0000010000, \quad 0000011000 \\ \hline 111101 & 1111111001,\quad 1111111011 \\ \hline \end{tabular} \end{center} \vspace{5mm} In this section, we show that one could equivalently solve the continuous relaxation of \eqref{eq:ML_deletion} to obtain a solution for \eqref{eq:ML_deletion}. Before presenting the main result, we first state a useful lemma which factors a given coordinate $p_i$ out of the relaxed binomial coefficient $\mathbf F(p,y)$ we introduced in Definition~\ref{def:f}. \begin{restatable}{lemma}{deletionMLrellemma} For $p=(p_1,p_2,..,p_i,...,p_n)$ and $Y=y=y_1...y_m$ with $n \geq m > 0$, we have \begin{align*} \mathbf F(p,y) = \mathbf F( p_{ [n]\backslash \{i\}},y) + p_i \sum\limits_{k|y_k=1}\mathbf F( p_{[1:i-1]}, y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, y_{[k+1,m]})\\ + (1-p_i) \sum\limits_{k|y_k=0}\mathbf F( p_{[1:i-1]}, y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, y_{[k+1,m]}). \end{align*} \label{lemma:F_decomposition} \end{restatable} Recall that $\mathbf F(p,y)$ sums over all $m$-length subsets $\mathcal S$ and associates $p_{\mathcal S}$ with $y.$ Intuitively, this recursive relationship considers separately the cases where \begin{itemize} \item $i \notin \mathcal S$, \item $i \in \mathcal S$ and is associated with a particular $y_k$ where $y_k = 1$, \item $i \in \mathcal S$ and is associated with a particular $y_k$ where $y_k = 0$. \end{itemize} The detailed proof can be found in Appendix~\ref{app:F_lemma_proof}. It is clear from Lemma~\ref{lemma:F_decomposition} that $\mathbf F(p,y)$ is affine when projected onto each coordinate $p_i$. Thus, the extrema of $\mathbf F(p,y)$ must occur at the boundary of the support set of $p_i$; i.e., at either $p_i = 0$ or $p_i = 1$. Combining this with the fact that $\mathbf F(\cdot)$ is a relaxed version of the binomial coefficient, we observe that the maximization problem in \eqref{eq:ML_deletion} is equivalent to its real-valued relaxation. The following result makes this precise. \begin{theorem} The ML decoding problem for the single-trace deletion channel \begin{equation} \max_{x\in \{0,1\}^n} {x \choose y} \label{eq:ml_opt_equiv1} \end{equation} is equivalent to the problem \begin{equation} \max_{p\in [0,1]^n} \mathbf F(p,y). \label{eq:ml_opt_equiv2} \end{equation} Furthermore, given any non-integral $p^* \in [0,1]^n$ that maximizes $\mathbf F(p,y)$, we can construct a corresponding integral solution $x^* \in \{0,1\}^n$ that maximizes $\mathbf F(x,y)$ and consequently also maximizes ${x \choose y}$. \label{thm:ML_relaxation} \end{theorem} \begin{proof} As noted earlier, we have ${x \choose y} = \mathbf F(x,y)$. Therefore, we are interested in proving the following: \begin{align*} \max_{x\in \{0,1\}^n} \mathbf F(x,y) \equiv \max_{p\in [0,1]^n} \mathbf F(p,y),\numberthis \label{eq:ml_opt_equiv_proof1} \end{align*} where $\equiv$ refers to that the two problems are equivalent (have the same optimal objective value). We prove this by applying the following claim.\\ \textbf{Claim:} Given any feasible $p=(p_1,p_2,...,p_i,...,p_n)$, at least one of the following holds true: \begin{itemize} \item$\mathbf F(p^{(i\rightarrow 0)},y) \geq \mathbf F(p,y)$. Recall from notation that $p^{(i\rightarrow 0)}=(p_1,p_2,...,p_{i-1},0,p_{i+1}...,p_n)$ is the vector where the $i^{th}$ coordinate is replaced by $0$. \item $\mathbf F(p^{(i\rightarrow 1)},y) \geq \mathbf F(p,y)$. \end{itemize} Thus if $p^*$ is an optimal solution to \eqref{eq:ml_opt_equiv2} with $p_i\in (0,1)$, then at least one of $p^{(i\rightarrow 0)}$ or $p^{(i\rightarrow 1)}$ is also an optimal solution. Sequentially applying this argument for each coordinate of $p$ shows that there exists a point in $\{0,1\}^n$ which is an optimal solution to \eqref{eq:ml_opt_equiv2} and consequently to \eqref{eq:ml_opt_equiv1}. It remains to prove our claim. We use Lemma~\ref{lemma:F_decomposition} to factor out $p_i$ terms in $\mathbf F(p,Y)$: \begin{align*} \mathbf F(p,y) = \mathbf F( p_{[n]\backslash \{i\}},y) + p_i \sum\limits_{k|y_k=1}\mathbf F( p_{[1:i-1]}, y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, y_{[k+1,m]})\\ + (1-p_i) \sum\limits_{k|y_k=0}\mathbf F( p_{[1:i-1]}, y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, y_{[k+1,m]}). \end{align*} Now we express $\mathbf F(p^{(i\rightarrow 0)},y)$ and $\mathbf F(p^{(i\rightarrow 1)},y)$ as $$\mathbf F(p^{(i\rightarrow 0)},y) = \mathbf F( p_{[n]\backslash \{i\}},y) + \sum\limits_{k|y_k=0}\mathbf F( p_{[1:i-1]}, y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, y_{[k+1,m]}),$$ $$\mathbf F(p^{(i\rightarrow 1)},y) = \mathbf F( p_{[n]\backslash \{i\}},y) + \sum\limits_{k|y_k=1}\mathbf F( p_{[1:i-1]}, y_{[1:k-1]})\mathbf F( p_{[i+1:n]}, y_{[k+1,m]}).$$ \noindent Because $0\leq p_i\leq 1$ it directly follows that $$\min \left\{\mathbf F(p^{(i\rightarrow 0)},y),\mathbf F(p^{(i\rightarrow 1)},y)\right\} \leq \mathbf F(p,y) \leq \max \left\{\mathbf F(p^{(i\rightarrow 0)},y),\mathbf F(p^{(i\rightarrow 1)},y)\right\},$$ thus proving our claim. \end{proof} The real-valued optimization problem in \eqref{eq:ml_opt_equiv2} falls under the umbrella of signomial optimization which is, in general, NP-hard (see for example, \cite{xu2014signomial}, \cite{chand2016signomial}). A standard technique for signomial optimization uses convexification strategies to approximate the optimal value. In particular, as stated in \cite{chand2016signomial}, the main observation underlying their methods is that certifying the nonnegativity of a signomial with at most \textit{one negative coefficient} can be accomplished efficiently. However, there are two problems with this approach in relation to our work -- 1. when expressed as a signomial optimization problem, \textit{all} the coefficients are negative in the ML optimization objective function, and 2. the objective function has an exponential number of signomial terms as can be seen from Definition~\ref{def:f}. As a result, such strategies turn out to not be useful for the ML optimization problem. For instance, the techniques in \cite{chand2016signomial} resulted in the bound $\mathbf F(p,Y) \leq {|p| \choose |Y|}$ for most instances of $p$ and $Y$, where $|\cdot|$ denotes the length of the vector/sequence. This is a trivial bound that uses no information about $p$ and $Y$ other than their lengths. Moreover, with a slight change of variables, \eqref{eq:ml_opt_equiv2} could also be expressed as a maximization of a convex function in a convex set. With that being said, it is still unclear if \eqref{eq:ml_opt_equiv2} is solvable in polynomial time or not. \subsection{ML via gradient ascent} Given the continuous variable formulation of the ML problem in \eqref{eq:ml_opt_equiv2}, a natural heuristic to find an estimate of the ML sequence is to employ \textit{projected gradient ascent} to solve \eqref{eq:ml_opt_equiv2}. The algorithm, in short, can be described as follows (the exact algorithm is detailed as Alg.~\ref{alg:grad_asc}):\\ Step I: Start from a randomly chosen interior point (in our case, we start from $p=(0.5,0.5,...,0.5)$, the point corresponding to the uniform distribution).\\ Step II: Take a small step in the direction of the gradient $\nabla_p\ \mathbf F(p,y)$.\\ Step III: If the gradient step results in $p$ moving out of $[0,1]^n$, project it back onto $[0,1]^n$. Repeat Steps II and III until convergence.\\ Step IV: From the final $p$, determine the closest binary sequence to be the reconstructed sequence. Moreover in Appendix~\ref{app:F_grad_comp}, we show using Lemma~\ref{lemma:F_decomposition} that $\nabla_p\ \mathbf F(p,y)$ can be computed in $O(n^2)$ as a ``by-product'' of computing $\mathbf F(p,y)$. \begin{algorithm}[t!] \caption{Single trace projected gradient ascent for ML}\label{alg:grad_asc} \begin{algorithmic}[1] \item Input: Blocklength $n$, Trace {$Y=y$}, Initial point $p = (p_1,p_2,...,p_n)$, step-size $\epsilon$, Max iterations $M$, Convergence criteria $C$ \\ Outputs: Estimated sequence $\hat X$ \State Iteration count $j=0$ \While {$C$ is FALSE and $j<M$} \State $p \leftarrow p + \epsilon \frac{\nabla_p \mathbf F(p,y)}{\mathbf F(p,y)}$ \State Replace $p_i \leftarrow 1$ for all $i:p_i > 1$ \State Replace $p_i \leftarrow 0$ for all $i:p_i < 0$ \State $j\leftarrow j+1$ \EndWhile \State For each $i$, set $\hat X_i = \mathbbm 1 \{p_i>0.5\}$. \State \textbf{return} $\hat X = \hat X_1 \hat X_2 ... \hat X_n$ \end{algorithmic} \end{algorithm} \newpage \subsection{A heuristic for multiple traces} The continuous variable ML formulation in \eqref{eq:ml_opt_equiv2} optimizes over the distributions $p$, instead of sequences $x$. In particular, we proved the following: \begin{equation*} \max_{x\in \{0,1\}^n} {x \choose y} \equiv \max_{p\in [0,1]^n} \mathbf F(p,y) \equiv\ \max_{p\in [0,1]^n}\ \mathbb E_{Z \sim p} {Z \choose y}. \end{equation*} At this point, one could ask how this formulation extends to multiple traces $Y^1=y^1,Y^2=y^2,...,Y^t=y^t$. The following theorem gives such a continuous optimization formulation with multiple traces. \begin{theorem} The ML decoding with multiple traces \begin{equation} \max_{x\in \{0,1\}^n} {x \choose y^1}{x \choose y^2}...{x \choose y^t} \label{eq:ml_opt_traces1} \end{equation} is equivalent to \begin{equation} \max_{p\in [0,1]^n} \mathbb E_{Z\sim p} \left[{Z \choose y^1}{Z \choose y^2}...{Z \choose y^t} \right]. \label{eq:ml_opt_traces2} \end{equation} Furthermore, given any non-integral $p^* \in [0,1]^n$ that maximizes $\mathbb E_{Z\sim p} \left[{Z \choose y^1}{Z \choose y^2}...{Z \choose y^t} \right]$, we can construct a corresponding integral solution $x^* \in \{0,1\}^n$ that also maximizes ${x \choose y^1}{x \choose y^2}...{x \choose y^t} $. \label{thm:ML_multi_traces} \end{theorem} \begin{proof} This theorem can be proved in the same way as Theorem~\ref{thm:ML_relaxation}, by showing that \\ $\mathbb E_{Z\sim p} \left[{Z \choose y^1}{Z \choose y^2}...{Z \choose y^t} \right]$ is an affine function of each $p_i$; here we only prove this fact and the rest of the arguments follow exactly as in the proof of Theorem~\ref{thm:ML_relaxation}. To show this we use Lemma~\ref{lemma:bin_inf_relation} stated below; this Lemma is also closely related to the channel equivalence of Theorem~\ref{thm:channel_equiv} (see Appendix~\ref{app:bin_inf_lemma}). \begin{restatable}{lemma}{bininfrelation} \label{lemma:bin_inf_relation} For $h,f_1,f_2,...,f_m \in \mathcal{A}^*$,\\ $${h \choose f_1} {h \choose f_2}...{h \choose f_m}=\sum_{w\in \mathcal{A}^*}\langle f_1\uparrow f_2\uparrow ...\uparrow f_m,w \rangle{h \choose w}.$$ \end{restatable Using Lemma~\ref{lemma:bin_inf_relation}, we now have \begin{align*} \mathbb E_{Z\sim p} \left[{Z \choose y^1}{Z \choose y^2}...{Z \choose y^t}\right] &= \mathbb E_{Z\sim p} \sum_{w\in \mathcal{A}^*}\langle y^1\uparrow y^2\uparrow ...\uparrow y^t,w \rangle{Z \choose w}\\ &= \sum_{w\in \mathcal{A}^*}\langle y^1\uparrow y^2\uparrow ...\uparrow y^t,w \rangle \mathbb E_{Z\sim p} {Z \choose w}\\ & = \sum_{w\in \mathcal{A}^*}\langle y^1\uparrow y^2\uparrow ...\uparrow y^t,w \rangle \mathbf F(p,w). \end{align*} Note that $\mathbf F(p,w)$ is affine in each $p_i$. Thus $\mathbb E_{Z\sim p} \left[{Z \choose y^1}{Z \choose y^2}...{Z \choose y^t}\right]$ is a linear combination of affine functions of each $p_i$, and hence is also affine in each $p_i$. \end{proof} The formulation of \eqref{eq:ml_opt_traces2}, by itself, is not very useful as it is unclear on how to efficiently compute $\mathbb E_{Z\sim p} \left[{Z \choose y^1}{Z \choose y^2}...{Z \choose y^t}\right]$. Indeed, if ${Z \choose y^i}\ \raisebox{0.05em}{\rotatebox[origin=c]{90}{$\models$}}\ {Z \choose y^j}$, the expectation of products would decompose into the product $\prod_{j} \mathbb E_{Z\sim p} {Z \choose y^j} = \prod_{j} \mathbf F(p,y^j)$, and each of the terms in the product can be computed in $O(n^2)$ as detailed in Appendix~\ref{app:F_compute} -- this is however not the case as ${Z \choose y^i}$ and ${Z \choose y^j}$ are not independent. Having said that, we can now solve the maximization problem $\argmax_{p\in [0,1]^n} \prod_{j=1}^t \mathbf F(p,y^j)$ and hope that the resultant solution is also a good solution for $\argmax_{p\in [0,1]^n} \mathbb E_{Z\sim p} \left[{Z \choose y^1}...{Z \choose y^t}\right]$; Algorithm~\ref{alg:grad_asc_traces} makes this idea precise. Moreover, instead of maximizing $\prod_{j=1}^t \mathbf F(p,y^j)$, we can further simplify the gradient computations by taking the log of the objective function, i.e., we solve $\argmax_{p\in [0,1]^n} \sum_{j=1}^t \log \mathbf F(p,y^j)$. This heuristic turns out to perform well in a variety of situations, as illustrated in Section~\ref{sec:Numerics}. As for the complexity, note that Alg.~\ref{alg:grad_asc_traces} involves the computation of $t$ gradients (each of which takes $O(n^2)$) at each gradient iteration. For a fixed number of max iterations $M$, the complexity of the algorithm is $O(n^2t)$. \begin{algorithm}[t!] \caption{Trace reconstruction heuristic via projected gradient ascent}\label{alg:grad_asc_traces} \begin{algorithmic}[1] \item Input: Blocklength $n$, Traces {$Y^1=y^1,Y^2=y^2,...,Y^t=y^t$}, Initial point $p = (p_1,p_2,...,p_n)$, step-size $\epsilon$, Max iterations $M$, Convergence criteria $C$ \\ Outputs: Estimated sequence $\hat X$ \State Iteration count $j=0$ \While {$C$ is FALSE and $j<M$} \State $p \leftarrow p + \epsilon \sum_{j=1}^t \frac{\nabla_p \mathbf F(p,y^j)}{\mathbf F(p,y^j)}$ \State Replace $p_i \leftarrow 1$ for all $i:p_i > 1$ \State Replace $p_i \leftarrow 0$ for all $i:p_i < 0$ \State $j\leftarrow j+1$ \EndWhile \State For each $i$, set $\hat X_i = \mathbbm 1 \{p_i>0.5\}$. \State \textbf{return} $\hat X = \hat X_1 \hat X_2 ... \hat X_n$ \end{algorithmic} \end{algorithm}
{'timestamp': '2020-06-01T02:06:38', 'yymm': '2005', 'arxiv_id': '2005.14388', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14388'}
arxiv
\section{Introduction} Computer-aided thoracic disease diagnosis based on chest X-ray has been significantly advanced by deep convolutional neural networks (DCNNs) in recent years~\cite{wang2017chestx,tang2018attention,sedai2018deep,wang2018chestnet}. Most of these approaches are formulated as a multi-task binary classification problem, where a CNN is trained to predict the risk probabilities of different thoracic diseases. In clinical practices, visual localization of the lesions on chest X-ray, such as heatmaps or segmentation masks, is also preferred to provide interpretable supports for the classification results. Precise lesion localization often requires training CNNs with strong supervision, such as bounding boxes~\cite{wang2017chestx}, beyond merely image-level labels. However, accurately annotating lesion locations is difficult, time-consuming, and infeasible to practice in large-scale. For example, one of the largest publicly available chest X-ray datasets ChestX-ray14~\cite{wang2017chestx} contains more than one hundred thousands images with image-level labels, among which only less than one thousand images are further annotated with bounding boxes for benchmarking. Therefore, weakly supervised lesion localization on chest X-ray based on image-level labels remains a challenge but vital problem for computer-aided thoracic disease diagnosis. The recent work of Class Activation Map (CAM)~\cite{zhou2016learning} demonstrates the excellent localization ability of CNNs trained on nature images with only image-level supervision. On chest X-ray images, CAM and its variations have also been used for lesions localization~\cite{wang2017chestx,tang2018attention,sedai2018deep,wang2018chestnet}. However, most of these approaches utilize CAM as a post-processing technique to first generate lesion localization heatmaps, then threshold the heatmap scores and generate lesion bounding boxes. We argue that it may be beneficial to leverage CAM even during training given its excellent localization ability. \begin{figure}[t] \begin{center} \includegraphics[width=0.95\linewidth]{fig1.png} \end{center} \caption{The framework of Probabilistic-CAM (PCAM) pooling.} \label{fig1} \end{figure} In this work, we propose a novel and simple extension to the CAM-based framework for lesion localization on chest X-ray with image-level supervision. Specifically, we propose a new global pooling operation that explicitly leverages CAM for localization during training in a probabilistic fashion, namely Probabilistic-CAM (PCAM) pooling. Figure~\ref{fig1} shows the framework of PCAM pooling. A fully convolutional backbone network first processes the input chest X-ray image and generates a feature map. Then, for a particular label of thoracic disease, e.g. ``Pneumonia'', each feature embedding within the feature map goes through a fully connected (fc) layer implemented as a $1 \times 1$ convolutional layer and generates the class activation score that monotonically measure the disease likelihood of each embedding. Unlike the standard practice that directly uses the class activation score for localization, we further bound it with the sigmoid function and interpret the output as the disease probability of each embedding. Finally, the output probability map is normalized to attention weights of each embedding, following the multiple-instance learning (MIL) framework~\cite{ilse2018attention,yao2018weakly}, which are used to pool the original feature map by weighted average pooling. The pooled embedding goes through the same fc layer introduced above and generates the image-level disease probability for training. During inference time, we directly use the probability map for lesion localization, and apply a simple probability thresholding to obtain disease regions and bounding boxes. PCAM pooling does not introduce any additional training parameters and is easy to implement. We experiment the efficacy of PCAM pooling for lesion localization with image-level supervision on the ChestX-ray14~\cite{wang2017chestx} dataset. A ResNet-34~\cite{he2016deep} model trained with PCAM pooling significantly outperforms the ChestX-ray14 baseline\cite{wang2017chestx} in both the classification task and the localization task. Qualitative visual examination shows the probability maps generated by PCAM pooling tend to have clear and sharp boundaries around lesion regions compared to the typical class activation map. \section{Related work} \subsection{Weakly supervised lesion localization} Various methods have been proposed to localize lesions on chest X-ray through image-level supervision~\cite{wang2017chestx,tang2018attention,sedai2018deep,yao2018weakly,wang2018chestnet}. Wang et al.~\cite{wang2017chestx} introduce the ChestX-ray14 dataset, together with a baseline for evaluating weakly supervised lesion localization. Instead of the typical global average pooling, Wang et al. use the Log-Sum-Exp (LSE) pooling~\cite{pinheiro2015image} to encourage model training focusing more on the discriminative regions of the chest X-ray. Sedai et al.~\cite{sedai2018deep} utilize the intermediate feature maps from CNN layers at different scales together with learned layer reference weights to improve the localization performance of small lesions. Tang et al.~\cite{tang2018attention} combine CNN with attention-guided curriculum learning to gradually learn distinctive convolutional features for localization. Most of these approaches utilize the standard CAM technique to localize lesions, where our proposed PCAM pooling serves as an extension to the standard CAM to improve lesion localization with image-level supervision. \subsection{Global pooling}\label{sec2.2} Global average pooling is arguably the most widely used global pooling operation for image classification. While it is less prone to overfitting as the network tries to identify all discriminative regions of an object in natural images~\cite{zhou2016learning}, it may also fail to highlight the most discriminative regions within a chest X-ray, given most chest X-ray images share the same anatomic structures and may only differ in fine-grained lesion regions. Therefore, different global pooling operations have also been used to analyze chest X-rays. For example, Wang et al.~\cite{wang2017chestx} uses LSE pooling, which can be viewed as an adjustable operation between max pooling and average pooling by controlling the hyper-parameter $\gamma$. We summarize the mathematical differences and correlations between different global pooling operations in Table~\ref{tab1}. Particularly, $X$ with shape $(C, H, W)$ denotes the feature map from the last convolutional layer of a CNN. $x$ denotes the feature embedding of length $C$ after global pooling. $C$ denotes the channel dimension, $H$ and $W$ denote the height and width of the feature map. \begin{table} \centering \caption{Different types of global pooling.}\label{tab1} \begin{tabular}{|l|l|} \hline Pooling type & Formulation\\ \hline Average & $x_c = \sum_{i,j}^{H,W} w_{c,i,j} X_{c,i,j} ,\ w_{c,i,j} = \frac{1}{H*W}$ \\ Linear~\cite{wang2019comparison} & $x_c = \sum_{i,j}^{H,W} w_{c,i,j} X_{c,i,j} ,\ w_{c,i,j} = \frac{X_{c,i,j}}{\sum_{i,j}^{H,W} X_{c,i,j}}$ \\ Exponential~\cite{wang2019comparison} & $x_c = \sum_{i,j}^{H,W} w_{c,i,j} X_{c,i,j} ,\ w_{c,i,j} = \frac{\exp(X_{c,i,j})}{\sum_{i,j}^{H,W} \exp(X_{c,i,j})}$ \\ LSE~\cite{pinheiro2015image} & $x_c = \frac{1}{\gamma} \log\left[ \frac{1}{H*W} \sum_{i,j}^{H,W} \exp(\gamma X_{c,i,j}) \right]$ \\ LSE-LBA~\cite{yao2018weakly} & $s = \frac{1}{\gamma_0 + \exp(\beta)} \log\left[ \frac{1}{H*W} \sum_{i,j}^{H,W} \exp\left[(\gamma_0 + \exp(\beta)) S_{i,j}\right] \right]$ \\ Attention~\cite{ilse2018attention} & $x = \sum_{i,j}^{H,W} w_{i,j} X_{i,j} ,\ w_{i,j} = \frac{\exp\left[\mathbf{w}^\intercal\tanh(\mathbf{V} X_{i,j})\right]}{\sum_{i,j}^{H,W} \exp\left[\mathbf{w}^\intercal\tanh(\mathbf{V} X_{i,j})\right]} $ \\ \hline \end{tabular} \end{table} We can see that, global pooling operations differ mainly in the ways to compute the weights for feature map averaging. Note that, most of the pooling is performed for each channel $X_{c,i,j}$ independently, except for Attention pooling~\cite{ilse2018attention} that computes the attention weight at embedding level $X_{i,j}$ with extra trainable parameters, i.e. $\mathbf{V}, \mathbf{w}$ in Table~\ref{tab1}. All the channels within the same embedding share the same weight. The basic assumption of Attention pooling follows the multiple-instance learning (MIL) framework, that treats each embedding as an instance, and the chest X-ray as a bag of instances is positive, e.g. certain thoracic disease, as long as one of the instance is positive. PCAM pooling follows the same MIL framework, but uses a different method to compute the attention weight for each embedding based on the localization ability of CAM without introducing extra trainable parameters. LSE-LBA~\cite{yao2018weakly} also falls within the MIL framework, but it performs the pooling operation on the saliency map $S$ of shape $(H, W)$ instead of the feature map $X$ to obtain a saliency score $s$ for training. \section{Probabilistic-CAM (PCAM) Pooling} The main idea of PCAM pooling is to explicitly leverage the localization ability of CAM~\cite{zhou2016learning} through the global pooling operation during training. Using the same notation from Section~\ref{sec2.2}, given a fully convolutional network trained for multi-task binary classification, the class activation map of a particular thoracic disease is given by $\{s_{i,j} = \mathbf{w}^\intercal X_{i,j} + b|i,j \in H,W\}$. $X_{i,j}$ is the feature embedding of length $C$ at the position $(i, j)$ of a feature map $X$ with shape $(C, H, W)$ from the last convolutional layer. $\mathbf{w}, b$ are the weights and bias of the last fc layer for binary classification. In other words, $s_{i,j}$ is the logit before sigmoid function under the binary classification setting. $s_{i,j}$ monotonically measures the disease likelihood of $X_{i,j}$, and is used to generate the localization heatmap after the model is trained in the standard CAM framework. PCAM pooling utilizes $s_{i,j}$ to guide lesion localization during training through the global pooling operation under the MIL framework~\cite{ilse2018attention}. The MIL framework assumes the chest X-ray as a bag of embeddings is positive, as long as one of the embedding is positive. To measure each embedding's contribution to the whole bag, the MIL framework assigns normalized attention weights to each embedding for weighted global average pooling~\cite{ilse2018attention}. Because the numerical range of $s_{i,j}$ is unbounded, i.e. $s_{i,j} \in (-\infty, +\infty)$ in theory, it's neither interpretable nor directly applicable to compute the attention weights. Therefore, we further bound $s_{i,j}$ with the sigmoid function, $p_{i,j} = \text{sigmoid}(s_{i,j})$, and normalize $p_{i,j}$ as the attention weights. In summary, PCAM pooling can be formulated as \begin{eqnarray}\label{eq1} x = \sum_{i,j}^{H,W} w_{i,j} X_{i,j} ,\ w_{i,j} = \frac{\text{sigmoid}(\mathbf{w}^\intercal X_{i,j} + b)}{\sum_{i,j}^{H,W} \text{sigmoid}(\mathbf{w}^\intercal X_{i,j} + b)} \end{eqnarray} where $w_{i,j}$ is the attention weight for $X_{i,j}$ and $x$ is the pooled feature embedding which goes through the same fc layer for final image level classification. During the inference time, we interpret the sigmoid-bounded $p_{i,j}$ as the probability of embedding $X_{i,j}$ being positive, thus named Probabilistic-CAM, and we use the probability map $\{p_{i,j}|i,j \in H,W\}$ as the localization heatmap. We use a simple probability thresholding on the probability map to obtain regions of interest. In comparison, because $s_{i,j}$ is unbounded with different numerical ranges in different chest X-ray images, it is usually normalized into $[0, 255]$ within each image and thresholded with some ad-hoc ranges, e.g. $[60, 180]$ in~\cite{wang2017chestx}, to generate regions of interest. We show in Section~\ref{sec4.3} section that PCAM pooling generates localization heatmaps with better visual quality around lesion boundary regions compared to the standard CAM. \section{Experiments} \subsection{Dataset and experiments setup}\label{sec4.1} We evaluate lesion localization with image-level supervision on the ChestX-ray14~\cite{wang2017chestx} dataset, which contains 112,120 frontal-view chest X-ray images with 14 thoracic disease labels. 8 out of the 14 diseases are further annotated with 984 bounding boxes. We randomly split the official train\_valid set into $75\%$ for training and $25\%$ for validation. On the official test set, we evaluate the classification task on the 14 diseases and the localization task on the 8 diseases that have bounding boxes. Note that the 984 bounding boxes are not used for training. We use ResNet-34~\cite{he2016deep} as the backbone network and process the input images on the original $1024 \times 1024$ scale following~\cite{wang2017chestx}. The network is trained with a batch size of 36 and a learning rate of $1e^{-4}$ for 10 epoches. We balance the binary cross entropy loss of positive and negative samples within each batch following~\cite{wang2017chestx}. For the localization task, we first apply a probability of 0.9 to threshold the probability maps from PCAM pooling, then generate bounding boxes that cover the isolated regions in the binary masks. To compare the visual quality of localization heatmaps from PCAM pooling with previous methods, we also train a ResNet-34 with LSE pooling following~\cite{wang2017chestx}. We normalize the class activation maps from LSE pooling into $[0, 255]$ for each image individually, and then apply a threshold of 180 following~\cite{wang2017chestx}. Note that the performances of LSE pooling reported in Table~\ref{tab2} and Table~\ref{tab3} are from Wang et al.~\cite{wang2017chestx}. \subsection{Classification task}\label{sec4.2} \begin{table} \centering \caption{Classification AUCs of the 14 diseases on the ChestX-ray14 test set.}\label{tab2} \begin{tabular}{|l|c|c|c|c|c|} \hline Method & LSE~\cite{wang2017chestx} & LSE-LBA~\cite{yao2018weakly} & AGCL~\cite{tang2018attention} & ChestNet~\cite{wang2018chestnet} & PCAM pooling \\ \hline Atelectasis & 0.700 & 0.733 & 0.756 & 0.743 & \textbf{0.772} \\ Cardiomegaly & 0.810 & 0.856 & \textbf{0.887} & 0.875 & 0.864 \\ Effusion & 0.759 & 0.806 & 0.819 & 0.811 & \textbf{0.825} \\ Infiltration & 0.661 & 0.673 & 0.689 & 0.677 & \textbf{0.694} \\ Mass & 0.693 & 0.777 & \textbf{0.814} & 0.783 & 0.813 \\ Nodule & 0.669 & 0.718 & 0.755 & 0.698 & \textbf{0.783} \\ Pneumonia & 0.658 & 0.684 & \textbf{0.729} & 0.696 & 0.721 \\ Pneumothorax & 0.799 & 0.805 & 0.850 & 0.810 & \textbf{0.868} \\ Consolidation & 0.703 & 0.711 & 0.728 & 0.726 & \textbf{0.732} \\ Edema & 0.805 & 0.806 & \textbf{0.848} & 0.833 & 0.833 \\ Emphysema & 0.833 & 0.842 & 0.908 & 0.822 & \textbf{0.931} \\ Fibrosis & 0.786 & 0.743 & 0.818 & 0.804 & \textbf{0.819} \\ Pleural Thickening & 0.684 & 0.724 & 0.765 & 0.751 & \textbf{0.788} \\ Hernia & 0.872 & 0.775 & 0.875 & \textbf{0.900} & 0.784 \\ \hline \end{tabular} \end{table} Table~\ref{tab2} shows the Area Under the receiver operating characteristic Curves (AUCs) of the classification task on the 14 thoracic diseases from the ChestX-ray14 official test set. PCAM pooling outperforms most of the other state-of-the-art methods including the baseline reported in ChestX-ray14~\cite{wang2017chestx}. We suspect explicitly utilizing CAM for localization during training may also benefit the classification task. Note the results from AGCL~\cite{tang2018attention} are obtained by training with additional severity-level information. \subsection{Localization task}\label{sec4.3} \begin{table} \centering \caption{Localization accuracies and average false positives of the 8 diseases that have bounding boxes on the ChestX-ray14 test set.}\label{tab3} \begin{tabular}{|l|c|c|c|c|c|c|c|c|} \hline Method & AT & CM & EF & IF & MS & ND & PMN & PMT \\ \hline \multicolumn{9}{|c|}{Localization accuracy, IoBB $>$ 0.5} \\ \hline LSE-baseline~\cite{wang2017chestx} & 0.2833 & 0.8767 & 0.3333 & 0.4227 & 0.1411 & 0.0126 & 0.3833 & 0.1836 \\ PCAM pooling & \textbf{0.3500} & \textbf{0.9657} & \textbf{0.5359} & \textbf{0.7642} & \textbf{0.4118} & \textbf{0.0759} & \textbf{0.7667} & \textbf{0.1939} \\ \hline \multicolumn{9}{|c|}{Average false positive} \\ \hline LSE-baseline~\cite{wang2017chestx} & 1.020 & 0.563 & \textbf{0.927} & \textbf{0.659} & \textbf{0.694} & \textbf{0.619} & \textbf{1.013} & \textbf{0.529} \\ PCAM pooling & \textbf{0.867} & \textbf{0.021} & 1.137 & 1.805 & 1.000 & 1.228 & 1.200 & 1.684 \\ \hline \end{tabular} \begin{tablenotes} \small \item AT: Atelectasis, CM: Cardiomegaly, EF: Effusion, IF: Infiltration, MS: Mass, ND: Nodule, PMN: Pneumonia, PMT: Pneumothorax. \end{tablenotes} \end{table} Table~\ref{tab3} shows the localization accuracies and the average false positives of the localization task on the 8 thoracic diseases that have bounding boxes. We use Intersection over the predicted B-Box area ratio (IoBB) to measure the overlap between predicted bounding boxes and ground truth bounding boxes annotated by radiologists following~\cite{wang2017chestx}. A correct localization is defined as at least one predicted bounding box is overlapped with the ground truth bounding box with IoBB $>$ 0.5~\cite{wang2017chestx}. PCAM pooling outperforms the baseline localization accuracy~\cite{wang2017chestx} by a significant margin on all of the diseases, demonstrating its efficacy in weakly supervised lesion localization. Figure~\ref{fig2} shows a few selected examples of the probability maps generated by PCAM pooling and the class activation maps generated by LSE pooling together with the predicted bounding boxes. Compared to the class activation maps, the probability maps are visually more clear with sharp boundaries around lesion regions. We attribute the improved visual quality to the probabilistic interpretation of the sigmoid-bounded class activation map and explicitly using it for training with global pooling. We notice the probability maps generated by PCAM pooling tend to enlarge regions of interest in general than class activation maps from LSE pooling, especially when the ground truth regions are small, such as ``Nodule'' in Figure~\ref{fig2}. This may explain the fact that PCAM pooling has relatively larger average false positives than CAM with LSE pooling. \begin{figure} \centering \begin{subfigure}[b]{0.48\linewidth} \includegraphics[width=\linewidth]{Atelectasis.jpg} \caption{Atelectasis} \label{fig2:a} \end{subfigure} ~ \begin{subfigure}[b]{0.48\linewidth} \includegraphics[width=\linewidth]{Cardiomegaly.jpg} \caption{Cardiomegaly} \label{fig2:b} \end{subfigure} ~ \begin{subfigure}[b]{0.48\linewidth} \includegraphics[width=\linewidth]{Effusion.jpg} \caption{Effusion} \label{fig2:c} \end{subfigure} ~ \begin{subfigure}[b]{0.48\linewidth} \includegraphics[width=\linewidth]{Pneumonia.jpg} \caption{Pneumonia} \label{fig2:d} \end{subfigure} ~ \begin{subfigure}[b]{0.48\linewidth} \includegraphics[width=\linewidth]{Mass.jpg} \caption{Mass} \label{fig2:e} \end{subfigure} ~ \begin{subfigure}[b]{0.48\linewidth} \includegraphics[width=\linewidth]{Nodule.jpg} \caption{Nodule} \label{fig2:f} \end{subfigure} ~ \caption{Selected samples of localization heatmaps and their bounding boxes generated by LSE pooling and PCAM pooling on the test set of ChestX-ray14~\cite{wang2017chestx}. In each subfigure, the left panel is the original chest X-ray with the ground truth bounding boxes (green), the middle panel is the class activation map and predicted bounding boxes (blue) by LSE pooling, the right panel is the probability map and predicted bounding boxes (blue) by PCAM pooling.} \label{fig2} \end{figure} \section{Conclusion} In this work, we present Probabilistic-CAM (PCAM) pooling, a new global pooling operation to explicitly leverage the localization ability of CAM for training. PCAM pooling is easy to implement and does not introduce any additional training parameters. Experiments of weakly supervised lesion localization on the ChestX-ray14~\cite{wang2017chestx} dataset demonstrate its efficacy in improving both the classification task and the localization task compared to several state-of-the-art baselines. Visual inspection of the probability maps generated by PCAM pooling shows clear and sharp boundaries around lesion regions compared to the standard class activation maps. Currently, PCAM pooling tends to generate localization maps that enlarge regions of interest, which may increase false positives especially for small lesions. We are working on reducing this effect as our future direction. \small \bibliographystyle{abbrv} \input{document.bbl} \end{document}
{'timestamp': '2020-06-01T02:09:46', 'yymm': '2005', 'arxiv_id': '2005.14480', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14480'}
arxiv
\section{Introduction} Most existing captioning models learn an autoregressive model, either LSTM or transformer, in which explicit control of generation process is difficult. In particular, the length of the caption is determined only after the End Of Sentence ($<$eos$>$) is generated. It is hard to know and control the length beforehand. However, length can be an important property of a caption. A model that allows control of output length would provide more options for the end users of the captioning model. By controling the length, we can influence the style and descriptiveness of the caption: short, simple captions vs. longer, more complex and detailed descriptions for the same image. Previous work includes captioning models that allow control for other aspects. \cite{cornia2019show} controls the caption by inputting a different set of image regions. \cite{deshpande2019fast} can generate a caption controlled by assigning POS tags. Length control has been studied in abstract summarization~\cite{kikuchi2016controlling,fan2017controllable,takase2019positional}, but to our knowledge not in the context of image capitoning. To control the length of the generated caption, we build the model borrowing existing ideas from summarization work, by injecting length information into the model. To generate captions without an explicit length specification, we add a \emph{length prediction module} that can predict the optimal length for the input image at hand. We show that the length models can successfully generate catpion ranging from 7 up to 28 words long. We also show that length models perform better than non-controled model (with some special decoding methods)\gscom{the last phrase is vague at this point} when asked to generate long captions. \section{Models} We consider repurposing existing methods in summarization for captioning. In general, the length is treated as an intermediate \rtcom{latetnt variable is not correct, it's not latent} variable: $P(c|I) = P(c|I,l)*P(l|I)$. $c$, $I$ and $l$ are caption, image and length, respectively. We introduce how we build $P(c|I,l)$ and $P(l|I)$ as follows. Note that, the following methods can be used in conjunctions with any standard captioning model. \subsection{LenEmb\cite{kikuchi2016controlling}} We take LenEmb from \cite{kikuchi2016controlling} and make some small change according to \cite{takase2019positional}. Given desired length $T$ and current time step $t$, we embed the remaining length $T-t$ into a vector that is the same size as the word embedding. Then the word embedding of the previous word $w_{t-1}$, added with the length embedding (rather than concatenated, as in \cite{kikuchi2016controlling}), is fed as the input to the rest of the LSTM model. \begin{align} x_t = E_w[w_{t-1}] + E_l[T-t];\ \ P(w_t) = LSTM(x_t, h_{t-1}) \nonumber \end{align} \noindent\textbf{Learning to predict length} We add a length prediction module to predict the length given the image features (in this case the averaging region features) while no desired length is provided. We treat it as a classification task and train it with the reference caption length. \subsection{Marker\cite{fan2017controllable}} We also implement Marker model from \cite{fan2017controllable}. The desired length is fed as a special token at the beginning of generation as the ``first word''. At training time, the model needs to learn to predict the length at the first step the same way as other words (no extra length predictor needed). At test time, the length token is sampled in the same way as other words if no desired length specified. \section{Experiments} We use COCO~\cite{lin2014microsoft} to evaluate our models. For train/val/test split we follows \cite{karpathy2015deep}. The base captioning model is Att2in~\cite{rennie2017self}. The images features are bottom-up features\cite{anderson2018bottom}. For evaluation, we use BLEU~\cite{papineni2002bleu}, METEOR~\cite{denkowski2014meteor}, ROUGE~\cite{lin2004rouge}, CIDEr~\cite{vedantam2015cider}, SPICE~\cite{anderson2016spice} and bad ending rate~\cite{guo2018improving,self-critical-code}. We train the models with cross-entropy loss. Unless specified otherwise, decoding is beam search with beam size 5, and evaluation on Karpthy test set. \subsection{Generation with predicted lengths} For fair comparison on general image captioning task, we predict the length and generate the caption conditioned on the predicted length for length models. Results in Table \ref{tab:pred_perf} show that the length models are comparable to the base model. \begin{table}[htbp] \footnotesize \centering \begin{tabular}{lccccccc} & B4 & R & M & C & S & BER & LenMSE\\ \hline Att2in & 35.9 & 56.1 & 27.1 & 110.6 & 20.0 & 0.1 & N/A\\ \hline LenEmb & 34.9 & 56.2 & 27.0 & 110.0 & 20.0 & 0.0 & 0\\ Marker & 35.2 & 56.2 & 26.9 & 109.8 & 19.9 & 0.0 & 0\\ \hline \end{tabular}% \caption{\small Performance on COCO Karpathy test set. B4=BLEU4, R=ROUGE, M=METEOR, C=CIDEr, S=SPICE, BER=bad ending rate, LenMSE=length mean square error. Numbers all in percentage(\%) except LenMSE.} \label{tab:pred_perf}% \end{table}% \noindent\textbf{Length distribution(Fig.\ref{fig:length_dist})} While the scores are close, the length distribution is quite different. Length models tend to generate longer captions than normal auto-regressive models. However neither is close to the real caption length distribution(``test'' in the figure). \begin{figure}[t] \centering \begin{minipage}[b]{.6\linewidth} \includegraphics[width=\linewidth]{figures/length_dist.pdf} \end{minipage} \begin{minipage}[b]{.38\linewidth} \captionof{figure}{\small Length distribution of captions generated by different models. For length models, the length is obtained within the beam search process as a special token.} \label{fig:length_dist} \end{minipage} \end{figure} \subsection{Generation with controlled lengths} For baseline model, we use the method fixLen in \cite{kikuchi2016controlling} where probability manipulation are used to avoid generating eos token until desired length. The original CIDEr-D promotes short and generic captions because it computes average similarity between the generated and the references. We report a modified CIDEr (mCIDEr): 1) removing length penalty term in the CIDEr-D; 2) combining the ngram counts from all the reference captions to compute similarity~\cite{coco-caption-code}. \noindent\textbf{Fluency} The high bad ending rate for Att2in indicates it can't generate fluent sentences; when increasing beam size, the bad ending rate becomes lower. For length models, Marker performs well when length is less than 20 but collapse after, while LenEmb performs consistently well. \noindent\textbf{Accuracy} The length models perform better than base model when length$<10$. The base model performs better between 10-16 which are the most common lengths in the dataset. For larger length, the LenEmb performs the best on both mCIDEr and SPICE, incidcating it's covering more information in the reference captions. \noindent\textbf{Controllability} We use the mean square error between the desired length and the actual length (LenMSE) to evaluate the controllability. When using predicted length, the length models perfectly achieve the predicted length (in Table \ref{tab:pred_perf}). When desired length is fed, Fig. \ref{fig:scores} shows that LenEmb can perfectly obey the length while Marker fails for long captions probabily due to poor long-term dependency. \noindent\textbf{Quatlitative results(Fig. \ref{fig:qualitative})} show that the LenEmb model, when generating longer captions, changes the caption structure and covers more detail, while the base model tends to have the same prefix for different lengths and repetition. More results can be browsed onine~\cite{colab}. \begin{figure}[t] \centering \includegraphics[width=0.45\linewidth]{figures/length_CIDEr.pdf} \includegraphics[width=0.45\linewidth]{figures/length_SPICE.pdf} \includegraphics[width=0.45\linewidth]{figures/length_bad_count_rate.pdf} \includegraphics[width=0.45\linewidth]{figures/length_length_var.pdf} \caption{\small The performance of models with different desired length. Att2in+BSx is Att2in+fixLen with beam size x.} \label{fig:scores} \end{figure} \begin{figure}[!th] {\footnotesize \centering \begin{tabular}{p{0.01\linewidth}p{0.95\linewidth}} \multicolumn{2}{c}{ \includegraphics[width=\linewidth]{figures/000000354533.jpg}}\\ 7 & a motorcycle parked on a dirt road\\ 10 & a motorcycle is parked on the side of a road\\ 16 & a motorcycle parked on the side of a dirt road with a fence in the background\\ 22 & a motorcycle parked on the side of a dirt road in front of a fence with a group of sheep behind it\\ 28 & a motorcycle is parked in a dirt field with a lot of sheep on the side of the road in front of a fence on a sunny day\\ \hline 7 & a motorcycle parked on a dirt road\\ 10 & a motorcycle parked on a dirt road near a fence\\ 16 & a motorcycle parked on a dirt road in front of a group of people behind it\\ 22 & a motorcycle parked on a dirt road in front of a group of people on a dirt road next to a fence\\ 28 & a motorcycle parked on a dirt road in front of a group of people on a dirt road in front of a group of people in the background\\ \end{tabular} \begin{tabular}{p{0.01\linewidth}p{0.95\linewidth}} \multicolumn{2}{c}{ \includegraphics[width=\linewidth]{figures/000000348881.jpg}}\\ 7 & an airplane is parked at an airport\\ 10 & an airplane is parked on the tarmac at an airport\\ 16 & an airplane is parked on a runway with a man standing on the side of it\\ 22 & an airplane is parked on a runway with a man standing on the side of it and a person in the background\\ 28 & an airplane is parked on the tarmac at an airport with a man standing on the side of the stairs and a man standing next to the plane\\ \hline 7 & a plane is sitting on the tarmac\\ 10 & a plane is sitting on the tarmac at an airport\\ 16 & a plane that is sitting on the tarmac at an airport with people in the background\\ 22 & a plane is sitting on the tarmac at an airport with people in the background and a man standing in the background\\ 28 & a plane is sitting on the tarmac at an airport with people in the background and a man standing on the side of the road in the background\\ \end{tabular} } \caption{\small Generated captions of different lengths. Top: LenEmb; Bottom: Att2in+BS10} \label{fig:qualitative} \end{figure} \subsection{Failure on CIDEr optimization} We apply SCST\cite{rennie2017self} training for length models. However, SCST doesn't work well. While the CIDEr scores can be improved, the generated captions tend to be less fluent, including bad endings (ending with 'with a') or repeating words (like 'a a'). \section{Conclusions} We present two captioning models that can control the length and shows their effectiveness to generate good captions of different lengths. The code will be released at link\footnote{\url{https://github.com/ruotianluo/self-critical.pytorch/tree/length_goal}}. {\small \bibliographystyle{ieee_fullname} \section{Introduction} Most existing captioning models learn an autoregressive model, either LSTM or transformer, in which explicit control of generation process is difficult. In particular, the length of the caption is determined only after the End Of Sentence ($<$eos$>$) is generated. It is hard to know and control the length beforehand. However, length can be an important property of a caption. A model that allows control of output length would provide more options for the end users of the captioning model. By controling the length, we can influence the style and descriptiveness of the caption: short, simple captions vs. longer, more complex and detailed descriptions for the same image. Previous work includes captioning models that allow control for other aspects. \cite{cornia2019show} controls the caption by inputting a different set of image regions. \cite{deshpande2019fast} can generate a caption controlled by assigning POS tags. Length control has been studied in abstract summarization~\cite{kikuchi2016controlling,fan2017controllable,takase2019positional}, but to our knowledge not in the context of image capitoning. To control the length of the generated caption, we build the model borrowing existing ideas from summarization work, by injecting length information into the model. To generate captions without an explicit length specification, we add a \emph{length prediction module} that can predict the optimal length for the input image at hand. We show that the length models can successfully generate catpion ranging from 7 up to 28 words long. We also show that length models perform better than non-controled model (with some special decoding methods)\gscom{the last phrase is vague at this point} when asked to generate long captions. \section{Models} We consider repurposing existing methods in summarization for captioning. In general, the length is treated as an intermediate \rtcom{latetnt variable is not correct, it's not latent} variable: $P(c|I) = P(c|I,l)*P(l|I)$. $c$, $I$ and $l$ are caption, image and length, respectively. We introduce how we build $P(c|I,l)$ and $P(l|I)$ as follows. Note that, the following methods can be used in conjunctions with any standard captioning model. \subsection{LenEmb\cite{kikuchi2016controlling}} We take LenEmb from \cite{kikuchi2016controlling} and make some small change according to \cite{takase2019positional}. Given desired length $T$ and current time step $t$, we embed the remaining length $T-t$ into a vector that is the same size as the word embedding. Then the word embedding of the previous word $w_{t-1}$, added with the length embedding (rather than concatenated, as in \cite{kikuchi2016controlling}), is fed as the input to the rest of the LSTM model. \begin{align} x_t = E_w[w_{t-1}] + E_l[T-t];\ \ P(w_t) = LSTM(x_t, h_{t-1}) \nonumber \end{align} \noindent\textbf{Learning to predict length} We add a length prediction module to predict the length given the image features (in this case the averaging region features) while no desired length is provided. We treat it as a classification task and train it with the reference caption length. \subsection{Marker\cite{fan2017controllable}} We also implement Marker model from \cite{fan2017controllable}. The desired length is fed as a special token at the beginning of generation as the ``first word''. At training time, the model needs to learn to predict the length at the first step the same way as other words (no extra length predictor needed). At test time, the length token is sampled in the same way as other words if no desired length specified. \section{Experiments} We use COCO~\cite{lin2014microsoft} to evaluate our models. For train/val/test split we follows \cite{karpathy2015deep}. The base captioning model is Att2in~\cite{rennie2017self}. The images features are bottom-up features\cite{anderson2018bottom}. For evaluation, we use BLEU~\cite{papineni2002bleu}, METEOR~\cite{denkowski2014meteor}, ROUGE~\cite{lin2004rouge}, CIDEr~\cite{vedantam2015cider}, SPICE~\cite{anderson2016spice} and bad ending rate~\cite{guo2018improving,self-critical-code}. We train the models with cross-entropy loss. Unless specified otherwise, decoding is beam search with beam size 5, and evaluation on Karpthy test set. \subsection{Generation with predicted lengths} For fair comparison on general image captioning task, we predict the length and generate the caption conditioned on the predicted length for length models. Results in Table \ref{tab:pred_perf} show that the length models are comparable to the base model. \begin{table}[htbp] \footnotesize \centering \begin{tabular}{lccccccc} & B4 & R & M & C & S & BER & LenMSE\\ \hline Att2in & 35.9 & 56.1 & 27.1 & 110.6 & 20.0 & 0.1 & N/A\\ \hline LenEmb & 34.9 & 56.2 & 27.0 & 110.0 & 20.0 & 0.0 & 0\\ Marker & 35.2 & 56.2 & 26.9 & 109.8 & 19.9 & 0.0 & 0\\ \hline \end{tabular}% \caption{\small Performance on COCO Karpathy test set. B4=BLEU4, R=ROUGE, M=METEOR, C=CIDEr, S=SPICE, BER=bad ending rate, LenMSE=length mean square error. Numbers all in percentage(\%) except LenMSE.} \label{tab:pred_perf}% \end{table}% \noindent\textbf{Length distribution(Fig.\ref{fig:length_dist})} While the scores are close, the length distribution is quite different. Length models tend to generate longer captions than normal auto-regressive models. However neither is close to the real caption length distribution(``test'' in the figure). \begin{figure}[t] \centering \begin{minipage}[b]{.6\linewidth} \includegraphics[width=\linewidth]{figures/length_dist.pdf} \end{minipage} \begin{minipage}[b]{.38\linewidth} \captionof{figure}{\small Length distribution of captions generated by different models. For length models, the length is obtained within the beam search process as a special token.} \label{fig:length_dist} \end{minipage} \end{figure} \subsection{Generation with controlled lengths} For baseline model, we use the method fixLen in \cite{kikuchi2016controlling} where probability manipulation are used to avoid generating eos token until desired length. The original CIDEr-D promotes short and generic captions because it computes average similarity between the generated and the references. We report a modified CIDEr (mCIDEr): 1) removing length penalty term in the CIDEr-D; 2) combining the ngram counts from all the reference captions to compute similarity~\cite{coco-caption-code}. \noindent\textbf{Fluency} The high bad ending rate for Att2in indicates it can't generate fluent sentences; when increasing beam size, the bad ending rate becomes lower. For length models, Marker performs well when length is less than 20 but collapse after, while LenEmb performs consistently well. \noindent\textbf{Accuracy} The length models perform better than base model when length$<10$. The base model performs better between 10-16 which are the most common lengths in the dataset. For larger length, the LenEmb performs the best on both mCIDEr and SPICE, incidcating it's covering more information in the reference captions. \noindent\textbf{Controllability} We use the mean square error between the desired length and the actual length (LenMSE) to evaluate the controllability. When using predicted length, the length models perfectly achieve the predicted length (in Table \ref{tab:pred_perf}). When desired length is fed, Fig. \ref{fig:scores} shows that LenEmb can perfectly obey the length while Marker fails for long captions probabily due to poor long-term dependency. \noindent\textbf{Quatlitative results(Fig. \ref{fig:qualitative})} show that the LenEmb model, when generating longer captions, changes the caption structure and covers more detail, while the base model tends to have the same prefix for different lengths and repetition. More results can be browsed onine~\cite{colab}. \begin{figure}[t] \centering \includegraphics[width=0.45\linewidth]{figures/length_CIDEr.pdf} \includegraphics[width=0.45\linewidth]{figures/length_SPICE.pdf} \includegraphics[width=0.45\linewidth]{figures/length_bad_count_rate.pdf} \includegraphics[width=0.45\linewidth]{figures/length_length_var.pdf} \caption{\small The performance of models with different desired length. Att2in+BSx is Att2in+fixLen with beam size x.} \label{fig:scores} \end{figure} \begin{figure}[!th] {\footnotesize \centering \begin{tabular}{p{0.01\linewidth}p{0.95\linewidth}} \multicolumn{2}{c}{ \includegraphics[width=\linewidth]{figures/000000354533.jpg}}\\ 7 & a motorcycle parked on a dirt road\\ 10 & a motorcycle is parked on the side of a road\\ 16 & a motorcycle parked on the side of a dirt road with a fence in the background\\ 22 & a motorcycle parked on the side of a dirt road in front of a fence with a group of sheep behind it\\ 28 & a motorcycle is parked in a dirt field with a lot of sheep on the side of the road in front of a fence on a sunny day\\ \hline 7 & a motorcycle parked on a dirt road\\ 10 & a motorcycle parked on a dirt road near a fence\\ 16 & a motorcycle parked on a dirt road in front of a group of people behind it\\ 22 & a motorcycle parked on a dirt road in front of a group of people on a dirt road next to a fence\\ 28 & a motorcycle parked on a dirt road in front of a group of people on a dirt road in front of a group of people in the background\\ \end{tabular} \begin{tabular}{p{0.01\linewidth}p{0.95\linewidth}} \multicolumn{2}{c}{ \includegraphics[width=\linewidth]{figures/000000348881.jpg}}\\ 7 & an airplane is parked at an airport\\ 10 & an airplane is parked on the tarmac at an airport\\ 16 & an airplane is parked on a runway with a man standing on the side of it\\ 22 & an airplane is parked on a runway with a man standing on the side of it and a person in the background\\ 28 & an airplane is parked on the tarmac at an airport with a man standing on the side of the stairs and a man standing next to the plane\\ \hline 7 & a plane is sitting on the tarmac\\ 10 & a plane is sitting on the tarmac at an airport\\ 16 & a plane that is sitting on the tarmac at an airport with people in the background\\ 22 & a plane is sitting on the tarmac at an airport with people in the background and a man standing in the background\\ 28 & a plane is sitting on the tarmac at an airport with people in the background and a man standing on the side of the road in the background\\ \end{tabular} } \caption{\small Generated captions of different lengths. Top: LenEmb; Bottom: Att2in+BS10} \label{fig:qualitative} \end{figure} \subsection{Failure on CIDEr optimization} We apply SCST\cite{rennie2017self} training for length models. However, SCST doesn't work well. While the CIDEr scores can be improved, the generated captions tend to be less fluent, including bad endings (ending with 'with a') or repeating words (like 'a a'). \section{Conclusions} We present two captioning models that can control the length and shows their effectiveness to generate good captions of different lengths. The code will be released at link\footnote{\url{https://github.com/ruotianluo/self-critical.pytorch/tree/length_goal}}. {\small \bibliographystyle{ieee_fullname}
{'timestamp': '2020-06-01T02:06:36', 'yymm': '2005', 'arxiv_id': '2005.14386', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14386'}
arxiv
\subsection{IR-Based Code Search}\label{back_ir} Traditional code search models (e.g., CodeHow \cite{lv2015codehow}) mainly depend on IR techniques. Generally, the IR-based model builds an index for terms (i.e., each word token) in code methods, so that the keywords generated from search query can match the expected code methods quickly by checking the index. Afterward, the model recommends the top-n relevant code methods according to a designed keywords-terms matching degree. During the indexing, the method name and body are commonly regarded as two different components for a method \cite{lv2015codehow}. This is because method name (e.g., "readTextLineByLine()") is often defined in natural language whose semantic representation is close to the query (e.g., "how to read a text line by line"). But the method body implements the goal of the method name in programming languages (e.g., "new Buffered Reader()" and "br.close()"). Therefore, when matching keywords for a code method, a weighted sum of matching degrees on two different method components is utilized \cite{lv2015codehow}. Due to the success of existing search engines (e.g., Elasticsearch \cite{gormley2015elasticsearch}), code search researchers can easily build an IR-based model using the APIs provided by a search engine. The researchers can focus more on query understanding to address the semantic gap between query and code method. Namely, the IR-based models take more effort on how to generate correct keywords and how to calculate the keywords-terms matching degree. As illustrated in Table \ref{tab_example}, two code methods may contain many keywords related to the search query, but how to identify the relevant code and exclude the irrelevant one is still a challenging issue. CodeHow \cite{lv2015codehow} is an IR-based model. It leverages an Extended boolean model \cite{salton1983extended} to measure the degree to which query keywords match a method name and body respectively, and sort code methods based on a weighted sum of matching degrees for method name and body. \bl{To spot representative methods in the searched candidate methods, some models cluster candidates based on code patterns \cite{keivanloo2014spotting,mishne2012typestate,xie2006mapo}. For example, Keivanloo et al. \cite{keivanloo2014spotting} represented a method by an encoded pattern in terms of a set of code entities (e.g., method blocks). After retrieving a list of candidate methods for a query, they transformed them into vectors within a latent space where the methods with similar code patterns can be easily clustered. Afterward, they reranked representative methods in clusters based on their features (e.g., code conciseness and completeness).} \subsection{DL-Based Code Search}\label{back_deepcs} Gu et al. \cite{gu2018deep} indicated that existing IR-based models (e.g., CodeHow) do not work well because they have difficulties in query understanding. They cannot effectively address irrelevant/noisy keywords in the queries, so that the IR-based models cannot find code methods that highly related to a query \cite{gu2018deep}. To overcome this challenge, Gu et al. \cite{gu2018deep} provided a model DeepCS that leverages the DL technique to better understand query semantics and correctly search related code from a large scale of the codebase. Generally, to map the semantics of a search query and code methods, DeepCS aims to leverage DL the technique to vectorize queries and methods at first, and learn their semantic relationships directly. In this way, the methods relevant to a query can be easily identified by calculating the cosine similarities. In specific, the DL-based model DeepCS \cite{gu2018deep} encoded a pair of query and method into vectors with a fixed-size of vocabulary, and input the vectorized query-method pairs into different long-short term memory networks (LSTMs) \cite{hochreiter1997long}. The LSTM model aims to capture the sequential relationship between words in query or method. The parameters in the networks are optimized by a ranking loss function, which rewards the related query-method pairs and penalizes the unrelated ones. As the ground-truth query-method pair is not easy to obtain, DL-based models used the first line of method comment to represent the corresponding query. Similarly, the unrelated query to a method is the comment randomly selected from other commented methods. More details on DeepCS can be found in \cite{gu2018deep}. \subsection{Qualitative Analysis}\label{qualitative_analysis} This subsection performs a qualitative analysis of CodeMatcher, DeepCS, CodeHow\bl{, and UNIF}. To compare these models, we classified all their returned methods into seven categories\bl{, namely whether the query can match the semantics of method name/body}. Table \ref{fig_classify} illustrates that the definitions and real query-code examples for each category. \bl{To be specific, the categories identified whether the method name or body of a searched code can reflect the semantics in query;} whether a code's method body is useless, i.e., an abstract method or a getter/setter; whether a method is a duplication of previously inspected one in the top-10 code list. Table \ref{tb_classify} lists the classification results for different models. \begin{table} \centering \small \caption{Definitions of seven categories on search results and their query-code examples.} \begin{tabular}{|l|} \toprule \textbf{1. MM: Matched method name and Matched method body.}\\ \bl{Query: create arraylist from array}\\ public void \rd{createArrayListFromArray}()\{\\ \quad{}\rd{String[] dogs = \{"Puppy", "Julie", "Tommy"\};}\\ \quad{}\rd{List<String> doglist = Arrays.asList(dogs);}\\ \quad{}assertEqual(3, dogsList.size());\\ \}\\ \midrule \textbf{2. NM: Not-matched method name but matched method body.}\\ \bl{Query: how to declare an array}\\ public void arrayCardinality(ParameterRegistration parameterRegistration)\{\\ \quad{}\rd{Integer[] array = new Integer[]\{1, 2, 3\};}\\ \quad{}Int arrayCardinality = procedures(parameterRegistration).arrayCardinality(array);\\ \quad{}assertEquals(array.length, arrayCardinality);\\ \}\\ \midrule \textbf{3. MN: Matched method name but Not-matched method body.}\\ \bl{Query: converting string to int in java}\\ static Int \rd{convert}Status\rd{StringToInt}(String statusVal)\{\\ \quad{}if (statusVal.equalsIgnoreCase(STATUS\_REGRESSION)) ||\\ \quad{}\quad{}statusVal.equalsIgnoreCase(STATUS\_FAILED)\{\\ \quad{}\quad{}return -1;\\ \quad{}\} else if (statusVal.equalsIgnoreCase(STATUS\_PASSED))\{\\ \quad{}\quad{}return 1;\\ \quad{}\}\\ \quad{}return 0;\\ \}\\ \midrule \textbf{4. MU: Matched method name but Useless method body.}\\ \bl{Query: how can I initialise a static map}\\ private void \rd{initialiseMap}(GoogleMap googleMap)\{\\ \quad{}mMap = googleMap;\\ \}\\ \midrule \textbf{5. NU: Not-matched method name and Useless method body.}\\ \bl{Query: converting iso 8601-compliant string to date}\\ public static String convertDate2String(Date date)\{\\ \quad{}return convertDate2String(date);\\ \}\\ \midrule \textbf{6. NN: Not-matched method name and Not-matched method body.}\\ \bl{Query: how to read a large text file line by line using java}\\ private String textLine(String name, long version, String value)\{\\ \quad{}return String.format("name: \%s version: \%d value: \%s", name, version, value);\\ \}\\ \midrule \textbf{7. RM: Repeated Method.}\\ \bl{Query: convert an inputstream to a string}\\ public static String \rd{convertInputStreamToString}(InputStream inputStream)\{...\}\\ private String \rd{convertInputStreamToString}(InputStream inputStream)\{...\}\\ \bottomrule \end{tabular} \label{fig_classify} \end{table} \begin{table}[] \small \caption{Classification of \bl{1740} code search results into 7 categories for different models.} \begin{tabular}{|c|l|rr|rrrrr|} \toprule \textbf{Queries} & \textbf{Model} & \textbf{MM} & \textbf{NM} & \textbf{MN} & \textbf{MU} & \textbf{NU} & \textbf{NN} & \textbf{RM} \\ \midrule \multirow{4}{*}{$Queries_{50}$} & DeepCS & 93 (18.6\%) & 12 (2.4\%) & 25 (5.0\%) & 53 (10.6\%) & 97 (19.4\%) & 218 (43.6\%) & 2 (0.4\%) \\ & CodeHow & 34 (6.8\%) & 73 (14.6\%) & 2 (0.4\%) & 1 (0.2\%) & 4 (0.8\%) & 331 (66.2\%) & 55 (11.0\%) \\ & UNIF & 60 (12.0\%) & 23 (4.6\%) & 0 (0.0\%) & 7 (1.4\%) & 18 (3.6\%) & 392 (78.4\%) & 0 (0.0\%) \\ & CodeMatcher & 285 (57.0\%) & 0 (0.0\%) & 32 (6.4\%) & 27 (5.4\%) & 28 (5.6\%) & 125 (25.0\%) & 3 (0.6\%) \\ \midrule \multirow{4}{*}{$Queries_{99}$} & DeepCS & 59 (6.0\%) & 48 (4.8\%) & 0 (0.0\%) & 3 (0.3\%) & 69 (7.0\%) & 811 (81.9\%) & 0 (0.0\%) \\ & CodeHow & 31 (3.1\%) & 155 (15.7\%) & 0 (0.0\%) & 0 (0.0\%) & 3 (0.3\%) & 781 (78.9\%) & 20 (2.0\%) \\ & UNIF & 118 (11.9\%) & 38 (3.8\%) & 5 (0.5\%) & 4 (0.4\%) & 84 (8.5\%) & 741 (74.8\%) & 0 (0.0\%) \\ & CodeMatcher & 367 (37.1\%) & 0 (0.0\%) & 52 (5.3\%) & 89 (8.9\%) & 0 (0.0\%) & 473 (47.8\%) & 9 (0.9\%) \\ \midrule \multirow{4}{*}{$Queries_{25}$} & DeepCS & 6 (2.4\%) & 8 (3.2\%) & 0 (0.0\%) & 1 (0.4\%) & 15 (6.0\%) & 220 (8.0\%) & 0 (0.0\%) \\ & CodeHow & 6 (2.4\%) & 29 (11.6\%) & 0 (0.0\%) & 0 (0.0\%) & 0 (0.0\%) & 213 (85.2\%) & 2 (0.8\%) \\ & UNIF & 28 (11.2\%) & 10 (4.0\%) & 2 (0.8\%) & 0 (0.0\%) & 15 (6.0\%) & 195 (78.0\%) & 0 (0.0\%) \\ & CodeMatcher & 47 (18.8\%) & 1 (0.4\%) & 8 (3.2\%) & 3 (1.2\%) & 0 (0.0\%) & 191 (76.4\%) & 0 (0.0\%) \\ \midrule \multirow{4}{*}{$Queries_{all}$} & DeepCS & 158 (9.1\%) & 68 (3.9\%) & 25 (1.4\%) & 57 (3.3\%) & 181 (10.4\%) & 1249 (71.8\%) & 2 (0.1\%) \\ & CodeHow & 71 (4.1\%) & 257 (14.8\%) & 2 (0.1\%) & 1 (0.1\%) & 7 (0.4\%) & 1325 (76.1\%) & 77 (4.4\%) \\ & UNIF & 206 (11.8\%) & 71 (4.1\%) & 7 (0.4\%) & 11 (0.6\%) & 117 (6.7\%) & 1328 (76.3\%) & 0 (0.0\%) \\ & CodeMatcher & 699 (40.2\%) & 1 (0.1\%) & 92 (5.3\%) & 119 (6.8\%) & 28 (1.6\%) & 789 (45.3\%) & 12 (0.7\%) \\ \bottomrule \end{tabular} \label{tb_classify} \end{table} \subsubsection{The Reasons Why DeepCS \bl{and UNIF} Succeeded and Failed} From the Table \ref{tb_classify}, we observed that the DeepCS\bl{/UNIF} obtained a \bl{13\%/15.9\%} success (MM and NM), where \bl{9.1\%/11.8\%} of success in MM was due to a correct semantic matching between query and method, as Table \ref{fig_classify}(1); the \bl{3.9\%/4.1\%} of success in NM implies that DeepCS\bl{/UNIF} can somewhat capture the semantics in code (i.e., API sequence and tokens) although the method name does not relate to the goal of a query as Table \ref{fig_classify}(2). However, there are \bl{87\%/88.2\%} of failed results, where \bl{0.1\%/0.0\%} of failures were caused by returning repeated methods (RM). The source code provided by Gu et al. \cite{gu2018deep} excluded the methods whose cosine similarity differences with related queries are larger than 0.01. But we observed that this judgment could not clear out repeated methods for \bl{the DL-based models} with some negligible difference, e.g., the modifier difference, as shown in Table \ref{fig_classify}(7). Meanwhile, \bl{1.4\%/0.4\%} of failures (MN) were caused by unmatched method body, because two methods for different usages may have the same method name, as exemplified in Table \ref{fig_classify}(3). Moreover, for the \bl{10.7\%/7.3\%} of failures (MU and NU), we found that DeepCS\bl{/UNIF} returned some useless methods that can be a getter/setter for a class, or contain abstract APIs with insufficient context to understand, such as the examples in Table \ref{fig_classify}(4-5). In this way, useless methods do not satisfy the requirement of the method-level code search since developers need to search and jump to related code. And the manual code jump will increase developers' code inspection time, and it is also uncertain how many jumps they need. Thus, the self-contained source code is advantageous for the method-level code search. In addition, for the most part \bl{(71.8\%/76.3\%)} of features (NN), DeepCS\bl{/UNIF} completely mismatched the code to queries, as illustrated in Table \ref{fig_classify}(6). We attribute these failures to the insufficient model training, because (1) DeepCS\bl{/UNIF} was optimized by pairs of method and Javadoc comment, but 500 epochs of training with randomly selected pairs cannot guarantee its sufficiency; (2) DeepCS\bl{/UNIF} assumed that the first line of Javadoc comment could well describe the goal of related code, but it is uncertain whether the used line is a satisfactory label or a noise; (3) during the model training, the optimization never stop because of the convergence of its loss function values. \OB{1}{\bl{The DL-based models (DeepCS and UNIF)} can capture the semantics between queries and code methods. But its unsatisfactory performance is likely derived from the gap between the training data and our codebase.} \subsubsection{CodeMatcher vs. DeepCS\bl{/UNIF}} For the proposed model CodeMatcher that matches keywords in query with a method, Table \ref{tb_classify} shows that \bl{40.2\%} of code search succeeded due to the well-matched method name and body. However, there is no success from NM because wrongly combining keywords in the query only leads to unmatched code, i.e., MN \bl{(5.3\%)} and NN \bl{(45.3\%)}. This is because CodeMatcher cannot handle complex queries like DeepCS\bl{/UNIF} via the embedding technique. The \bl{8.4\%} of failures (MU and NU) on useless methods indicate that boosting the useful methods on a higher rank in terms of the percentage of JDK APIs is not the optimal solution, and directly removing those useless methods may be a better substitution. \bl{Moreover, we can observe that as CodeMatcher searched code methods based on how the tokens in methods matched the important query words sequentially, this sequential requirement would substantially exclude many duplicated methods for a query. After filtering out the redundant methods by simply comparing their MD5 hash values, the CodeMatcher can only return a limited number of repeated methods (RM=12).} \bl{Comparing with DeepCS/UNIF,} CodeMatcher returned more repeated methods. Thus, simply filtering redundant methods by their MD5 hash values, as described in Section \ref{method}, is not enough. A better choice would be comparing the API usages, data structure, and working flow in the method body. Comparing with DeepCS\bl{/UNIF}, the main advantage of CodeMatcher is the correct keywords matching between query and code, i.e., a high percentage of MM. However, CodeMatcher \bl{can hardly} handle partial matching only on the code body (i.e., \bl{NM=1}). But this is what DL-based models are good at (NM=\bl{68} for DeepCS \bl{and NM=71 for UNIF}) because they can capture high-level intent between query and method by joint embedding\bl{, although the NM are much smaller than MM for DeepCS/UNIF (MM=158 for DeepCS while MM=206 for UNIF).} Therefore, \bl{the advantages of DeepCS/UNIF} are good to compensate for CodeMatcher's disadvantages. \OB{2}{CodeMatcher cannot address complex queries like \bl{DL-based models (DeepCS and UNIF)}. Meanwhile, CodeMatcher can accurately find code methods for simple queries and avoid the out-of-vocabulary issue in DeepCS \bl{and UNIF}.} \subsubsection{CodeMatcher vs. CodeHow} By analyzing the classification of these search results in Table \ref{tb_classify}, we can observe that CodeHow is good at matching a query with the method body (\bl{14.8\%} for NM), because it extends query with related official APIs so that method body can be well filtered in terms of internal APIs. However, the main reason for the failures is the unmatched keywords (\bl{76.1\%} for NN) since CodeHow ignores the importance of programming words and their sequence. The other main reason is that it does not exclude repeated methods (\bl{4.4\%} for RM). However, we can observe that CodeHow can compensate for the disadvantages of CodeMatcher, i.e., the difficulty in matching a query with the method body. \OB{3}{The IR-based models CodeMatcher and CodeHow compensate with each other as they are good at matching a query with method name and body respectively.} \subsection{\bl{Conciseness and Completeness}}\label{concise_complete} \bl{Keivanloo et al. \cite{keivanloo2014spotting} indicated that, for a searched code, although the correctness (i.e., whether it is relevant to the search query) is important, developers also care about two other features. One feature is the conciseness, the ratio of irrelevant lines to the total lines. Lower conciseness indicates that a code contains no irrelevant lines. The other feature is the completeness, the number of addressed tasks divided by the total number of tasks, where the task includes the intent of the search query and other missed statements (well-typed, variable initialization, control flow, and exception handling) \cite{keivanloo2014spotting}. Besides, Keivanloo et al. \cite{keivanloo2014spotting} indicated that the code readability (whether the variable names are well-chosen) is also important. However, the readability is not easy to measure and the conciseness is the key component of readability (namely the searched code should use "as little code as possible" and show "the most basic version of the problem") \cite{buse2012synthesizing}. This is also the reason why Keivanloo et al. \cite{keivanloo2014spotting} only measured the conciseness and completeness of code.} \bl{Figs. \ref{fig_concise}-\ref{fig_complete} showed these two features of all the code searched by the CodeMatcher and baseline models (DeepCS, CodeHow, and UNIF). Fig. \ref{fig_concise} shows that the average conciseness of DeepCS, CodeHow, and UNIF are 0.88, 0.83, and 0.85 respectively. The proposed model CodeMatcher achieves a value of 0.61, outperforming the baselines by 30.7\%, 26.5\%, and 28.2\% respectively. After performing the Wilcoxon signed-rank test \cite{wilcoxon1945individual} between the results of CodeMatcher and a baseline model, the statistical result indicates that the advantages of CodeMatcher over baselines are significant (p-value<0.05). Moreover, Fig. \ref{fig_complete} shows that CodeMatcher also outperforms baseline models significantly in terms of the completeness with an average value of 0.33.} \bl{To investigate why CodeMatcher shows substantially better conciseness and completeness over baselines, we excluded the searched results irrelevant to the 174 queries for each model. As the left searched results are different for CodeMatcher and baselines, we applied the two-sample Kolmogorov-Smirnov test \cite{massey1951kolmogorov} at a 5\% significance level to estimate the statistical difference. Figs. \ref{fig_concise_short}-\ref{fig_complete_short} show that the CodeMatcher and baselines have no significant difference on conciseness and completeness for the relevant code. These results indicate that the number of returned code relevant to the query strongly affects the total conciseness and completeness. However, these results also implied that all the studied code search models do not consider the conciseness and completeness in the model. Therefore, we suggest that further studies take efforts to improve the quality of the searched code.} \begin{figure} \centering \includegraphics[width=0.8\columnwidth]{concise.eps} \caption{\bl{The conciseness of baseline models (DeepCS, CodeHow, UNIF, and CodeMatcher) for all the searched results; '*' indicates the significant difference (p-value $<$ 0.05) between a model and CodeMatcher, which is tested by the Wilcoxon signed-rank test \cite{wilcoxon1945individual}.}} \label{fig_concise} \end{figure} \begin{figure} \centering \includegraphics[width=0.8\columnwidth]{complete.eps} \caption{\bl{The completeness of baseline models (DeepCS, CodeHow, UNIF, and CodeMatcher) for all the searched results; '*' indicates the significant difference (p-value $<$ 0.05) between a model and CodeMatcher, which is tested by the Wilcoxon signed-rank test \cite{wilcoxon1945individual}.}} \label{fig_complete} \end{figure} \begin{figure} \centering \includegraphics[width=0.8\columnwidth]{concise-short.eps} \caption{\bl{The conciseness of baseline models (DeepCS, CodeHow, UNIF, and CodeMatcher) for all the correctly searched results; no baseline showed significant difference (p-value $>$ 0.05) with CodeMatcher, which is tested by the two-sample Kolmogorov-Smirnov test \cite{massey1951kolmogorov} at a 5\% significance level.}} \label{fig_concise_short} \end{figure} \begin{figure} \centering \includegraphics[width=0.8\columnwidth]{complete-short.eps} \caption{\bl{The completeness of baseline models (DeepCS, CodeHow, UNIF, and CodeMatcher) for all the correctly searched results; no baseline showed significant difference (p-value $>$ 0.05) with CodeMatcher, which is tested by the two-sample Kolmogorov-Smirnov test \cite{massey1951kolmogorov} at a 5\% significance level.}} \label{fig_complete_short} \end{figure} \subsection{Why DeepCS \bl{and UNIF} Did Not Work Well on Our New Dataset?}\label{why} One may notice that the performance of DeepCS \bl{and UNIF} are lower than the ones reported by Gu et al. \cite{gu2018deep} \bl{and Cambronero et al. \cite{cambronero2019deep} respectively}. To verify the validity of our re-ran DeepCS \bl{and re-implemented UNIF}, we tested our trained DeepCS \bl{and UNIF} not on our new testing data but the original testing data shared by Gu et al. \cite{gu2018deep}; we refer to the results of our experiment as DeepCS$_{old}$ and UNIF$_{old}$. Table \ref{tab_why} shows that the performance of DeepCS$_{old}$ is close to the one reported by Gu et al. \cite{gu2018deep} in terms of MRR (0.59 vs. 0.6)\bl{; the MRR of UNIF$_{old}$ is also close to the one reported by Cambronero et al. \cite{cambronero2019deep} (0.54 vs. 0.58)}. Thus, these results confirm the validity of the re-ran DeepCS model \bl{and our re-implemented UNIF model}. Moreover, not like \bl{Gu et al.'s} testing data, our testing data shares no overlap with \bl{their} training data. Therefore, the reduced performance on our testing data implies that the overlap affects the generalizability of DeepCS \bl{and UNIF}. Ideally, the performance of DeepCS \bl{and UNIF} can be improved by tuning with more training data. To reach the goal, we built the models DeepCS$_{tune}$ and UNIF$_{tune}$ tuned with more training data extracted from our codebase. Totally, we collected 1,283,445 commented code methods as training data instances following the training data extraction process described in \cite{gu2018deep}. In the model optimization step, we tuned the pre-trained DeepCS \bl{and UNIF} with the new training data in default settings, i.e., 500 epochs. Table \ref{tab_why} shows that DeepCS$_{tune}$ achieves a better performance with MRR \bl{0.38 (an improvement of 15.2\% over DeepCS) while the MRR of UNIF$_{tune}$ is 0.46 (an improvement of 12.2\% over UNIF)}. The experimental results imply that DeepCS \bl{and UNIF} did not work due to the gap between \bl{Gu et al.'s} training and our testing data. Tuning DeepCS \bl{and UNIF} with data generated from the testing data can mitigate the generalizability issue. However, their tuned performance (MRR = 0.38 \bl{for DeepCS and MRR = 0.46 for UNIF}) are still far from the result of CodeMatcher (MRR = \bl{0.60}). We observed that this case is likely attributed to the limited training data and a fixed size of vocabulary. As shown in Table \ref{codebase}, our new testing data contains about 16 million methods in total but only 21.91\% of them have Javadoc comments. Moreover, only 7.73\% of the total methods can be used to tune DeepCS\bl{/UNIF} due to the limited vocabulary size. Therefore, DeepCS\bl{/UNIF} would have difficulty in comprehending the semantics of methods and their relationship to related Javadoc comments. To further analyze the impacts of the vocabulary, we investigate how it covers the words in the new testing data. Table \ref{tab:vocab} shows that more than 95\% of words in method components (API, name, and tokens) cannot be covered. In terms of the word frequency, there are 42.95\%, 6.22\%, and 12.75\% of new words that appeared in method API, name, and token respectively. Due to the out-of-vocabulary issue, more than half (52.91\%) of methods in testing data contain new words. Therefore, the trained DeepCS\bl{/UNIF} would have difficulty in understanding the semantics of methods in the new testing data. \begin{table}[] \caption{Performance comparison of DeepCS in different settings \bl{(old, testing model on DeepCS' original testing data \cite{gu2018deep}; tune, tuning model with data collected from our testing data and testing model on our testing data)}, where the model performance is measured by SuccessRate@1/5/10 (SR@1/5/10), Precision@1/5/10 (P@1/5/10), and MRR.} \begin{tabular}{|c|l|ccc|ccc|c|} \toprule \textbf{Query} & \textbf{Model} & \textbf{SR@1} & \textbf{SR@5} & \textbf{SR@10} & \textbf{P@1} & \textbf{P@5} & \textbf{P@10} & \textbf{MRR} \\ \midrule \multirow{2}{*}{$Queries_{50}$} & $DeepCS_{old}$ & 0.44 & 0.72 & 0.82 & 0.44 & 0.42 & 0.41 & 0.59 \\ & $UNIF_{old}$ & 0.38 & 0.72 & 0.80 & 0.38 & 0.39 & 0.33 & 0.54 \\ \midrule \multirow{2}{*}{$Queries_{50}$} & $DeepCS_{tune}$ & 0.30 & 0.62 & 0.72 & 0.30 & 0.31 & 0.30 & 0.44 \\ & $UNIF_{tune}$ & 0.26 & 0.56 & 0.64 & 0.26 & 0.26 & 0.19 & 0.41 \\ \midrule \multirow{2}{*}{$Queries_{99}$} & $DeepCS_{tune}$ & 0.24 & 0.42 & 0.47 & 0.24 & 0.20 & 0.15 & 0.36 \\ & $UNIF_{tune}$ & 0.33 & 0.64 & 0.71 & 0.33 & 0.32 & 0.26 & 0.49 \\ \midrule \multirow{2}{*}{$Queries_{25}$} & $DeepCS_{tune}$ & 0.16 & 0.36 & 0.40 & 0.16 & 0.18 & 0.10 & 0.30 \\ & $UNIF_{tune}$ & 0.36 & 0.52 & 0.52 & 0.36 & 0.22 & 0.17 & 0.48 \\ \midrule \multirow{2}{*}{$Queries_{all}$} & $DeepCS_{tune}$ & 0.24 & 0.47 & 0.53 & 0.25 & 0.23 & 0.19 & 0.38 \\ & $UNIF_{tune}$ & 0.32 & 0.60 & 0.66 & 0.32 & 0.29 & 0.23 & 0.46 \\ \bottomrule \end{tabular} \label{tab_why} \end{table} \begin{table} \centering \caption{Statistics of words in our new testing data covered by DeepCS' \bl{and UNIF's} vocabulary, where \bl{DeepCS represents code by API, name, and token; meanwhile, UNIF represents code by name and token.}.} \begin{tabular}{|l|rrr|} \toprule \textbf{Item} & \textbf{Count} & \textbf{New} & \textbf{Percentage} \\ \midrule Unique Words in API & 2,406,547 & 2,397,969& 99.64\%\\ Unique Words in Name & 270,084 & 261,113 & 96.68\%\\ Unique Words in Token & 1,610,147 & 1,602,435 & 99.52\%\\ Words in API & 64,754,427 & 27,811,106 & 42.95\%\\ Words in Name & 44,194,936 & 2,749,420 & 6.22\%\\ Words in Token & 177,572,258 & 22,633,682 & 12.75\%\\ Method & 16,611,025 & 8,788,967 & 52.91\%\\ \bottomrule \end{tabular} \label{tab:vocab} \end{table} \subsection{\bl{Why is the Word Sequence Important?}} \bl{To capture the sequential relationship between important words in query, the proposed model CodeMatcher considered it in the fuzzy search component and reranking strategies. However, one major question is that whether the sequence frequently occurred. To investigate this research question, we analyzed the studied 174 queries. We found that for 79 queries, the order of words that appear in the query plays an important role -- if the words in the query are reordered, the meaning will change. To analyze the root causes, we classified these 79 queries into four cases: \textit{1) the order of multiple tasks,} the query "read from file A and write to file B" is different from the one "write from file A and read to file" because exchanging the phrases "read from" and "write to" will change the intent of two tasks; \textit{2) data conversion,} "convert int to string" and "convert string to int" work differently; \textit{3) conditional job,} "sort map by values" contradicts with the semantics "sort values by map"; \textit{4) the exchanged core word,} "read property file" and "read file property" would be implemented in two ways because "property file" and "file property" are two completely different objects. The statistics in Table \ref{table_word_sequence} shows that among these 4 cases, the data conversion is the most frequent one.} \begin{table}[] \caption{\bl{Classification of cases with sequentially important query words.}} \begin{tabular}{|c|l|l|c|r|} \toprule \textbf{No.}&\textbf{Case} & \textbf{Description} & \textbf{Count} & \textbf{Percentage} \\ \midrule 1&The order of multiple tasks & do A and B & 9 & 11.4\% \\ 2&Data conversion & do (from) A to B & 38 & 48.1\% \\ 3&Conditional job & do A with/via/in/over/based/by/when/if B & 17 & 21.5\% \\ 4&The exchanged core word & do A B & 15 & 19.0\% \\ -&\textbf{Total} & - & 79 & 100.0\% \\ \bottomrule \end{tabular} \label{table_word_sequence} \end{table} \subsection{Research Questions}\label{rqs} To verify the validity of the proposed model, this study investigates the following research questions (RQs): \RQ{1}{Can CodeMatcher outperform \bl{the baseline} models?} The proposed model CodeMatcher aims to leverage IR technique to simplify the complexity of DeepCS while retaining its advantages, namely its capability of addressing irrelevant/noisy keywords in queries and recognizing semantically related words between queries and code methods as described by Gu et al. \cite{gu2018deep}. To verify the validity of the proposed model, this RQ investigates whether the CodeMatcher outperforms the relevant models, \bl{including two DL-based model DeepCS \cite{gu2018deep} and UNIF \cite{cambronero2019deep}, and an IR-based model CodeHow \cite{lv2015codehow}.} \RQ{2}{Is CodeMatcher faster than \bl{the baseline} models?} We observed that training and testing the DL-based model DeepCS is time-consuming due to its high complexity. Therefore, we intend to analyze whether the simplified model CodeMatcher works faster than DeepCS substantially. Besides, we also compare the time-efficiency of CodeMatcher with \bl{UNIF \cite{cambronero2019deep} and CodeHow \cite{lv2015codehow}}. \RQ{3}{\bl{How do the CodeMatcher components contribute to the code search performance?}} CodeMatcher consists of three important components: \bl{the fuzzy search component retrieves an initial set of candidate relevant code from the indexed codebase, the reranking component sorts the candidate list based on the designed strategy, and the query understanding component collects metadata for the previous two components.} They largely determine the performance of the code search. Thus, this RQ aims to analyze how much these components contribute to the model performance. The result can also help analyze the necessity of these components. \RQ{4}{Can CodeMatcher outperform existing online code search engines?} GitHub search\footnote{https://github.com/search} and Google search\footnote{https://google.com} are two commonly used search engines for developers to find code in practice. To measure the performance of GitHub/Google search, all the search engines are tested with the same queries as CodeMatcher and they are set to search only GitHub repositories; for Google search, we use the following advanced settings: "site:github.com" and "filetype:java". \subsection{Dataset}\label{data} \vspace{5pt}\noindent\textbf{Codebase.} Originally, Gu et al. \cite{gu2018deep} collected 9,950 Java projects that have at least 20 stars in GitHub as the testing data of DeepCS. However, we cannot use their testing data to verify our IR-based model CodeMatcher, because Gu et al. \cite{gu2018deep} just provided a preprocessed data that can be used for DeepCS only. Therefore, we built a new and larger scale testing data for model evaluation. We crawled 41,025 Java repositories from GitHub created from Jul. 2016 to Dec. 2018 with more than five stars. The number of stars filter ($>$5 stars) which is different from Gu et al.'s \cite{gu2018deep} setting (i.e., at least 20 stars) is used so that the testing data includes more Java projects. Besides, the time duration (Jul. 2016 to Dec. 2018) of our new testing data can ensure the non-overlapping with DeepCS' training data (created from Aug. 2008 to Jun. 2016). Table \ref{codebase} shows that the new codebase contains \textasciitilde{}17 million methods, and 21.91\% of them have Javadoc comments that describe the corresponding methods. \begin{table} \centering \caption{Statistics of the constructed codebase.} \begin{tabular}{|cccc|} \toprule \textbf{$\#$Project} & \textbf{$\#$Method} & \textbf{$\#$Javadoc} & \textbf{\#LOC} \\ \midrule 41,025 & 16,611,025 & 3,639,794 & 70,332,245\\ \bottomrule \end{tabular} \label{codebase} \end{table} \vspace{5pt}\noindent\textbf{Queries.} To simulate a real-world code search scenario, we validated a code search model \bl{with three query sets in total of 174 queries} as listed in \bl{Tables \ref{queries50}-\ref{queries25}}: \begin{itemize} \item \textit{$Queries_{50}$.} \bl{The first query set was} manually collected by Gu et al. \cite{gu2018deep} from Stack Overflow in a systematic way. These queries are top-50 voted Java programming questions\footnote{https://stackoverflow.com/questions/tagged/java?sort=votes} following three criteria: \textit{(1) concrete,} a question should be a specific programming task, such as "How can I concatenate two arrays in Java?"; \textit{(2) well-answered,} the accepted answers corresponding to the question should contain at least one code snippet; \textit{(3) non-duplicated,} the question is not a duplicate of another question in the same collection.\vspace{5pt} \item \textit{$Queries_{99}$.} \bl{The second query set was collected from the CodeSearchNet challenge\footnote{https://github.com/github/CodeSearchNet} that was built by Husain et al. \cite{husain2019codesearchnet}. The contained 99 queries\footnote{https://github.com/github/CodeSearchNet/blob/master/resources/queries.csv} were common search queries from Bing that have high clickthrough rates to code with clearly technical keywords \cite{husain2019codesearchnet}.}\vspace{5pt} \item \textit{$Queries_{25}$.} \bl{The third query set has 25 queries based on the studies of Mishne et al. \cite{mishne2012typestate} and Keivanloo et al. \cite{keivanloo2014spotting}. Note that these two studies used API names as code search input. However, our study focused on the queries written in natural language. Therefore, we used the natural language descriptions provided in these two studies \cite{mishne2012typestate,keivanloo2014spotting} as our model inputs.} \end{itemize} \begin{table}[b] \scriptsize \caption{\bl{The Queries$_{50}$ collected from Gu et al. \cite{gu2018deep}} and the Evaluation Results (NF: Not Found within the top 10 returned results, DCS: DeepCS \cite{gu2018deep}, CM: CodeMatcher, CH: CodeHow \cite{lv2015codehow}, UNIF \cite{cambronero2019deep}.)} \begin{tabular}{|c|l|cccc|} \toprule \textbf{No.} & \textbf{Query} & \textbf{DCS} & \textbf{CM} & \textbf{CH} & \textbf{UNIF} \\ \midrule 1 & convert an inputstream to a string & 2 & 1 & 2 & 2 \\ 2 & create arraylist from array & 8 & 1 & 1 & 4 \\ 3 & iterate through a hashmap & 1 & 1 & 1 & NF \\ 4 & generating random integers in a specific range & 1 & 1 & 5 & 4 \\ 5 & converting string to int in java & 8 & 1 & 2 & 1 \\ 6 & initialization of an array in one line & 1 & 1 & 1 & 2 \\ 7 & how can I test if an array contains a certain value & NF & 1 & 1 & 9 \\ 8 & lookup enum by string value & NF & 1 & 1 & NF \\ 9 & breaking out of nested loops in java & NF & 3 & NF & NF \\ 10 & how to declare an array & 1 & 1 & 1 & NF \\ 11 & how to generate a random alpha-numeric string & 1 & 1 & NF & 5 \\ 12 & what is the simplest way to print a java array & 1 & 1 & NF & 5 \\ 13 & sort a map by values & 5 & 1 & 1 & 1 \\ 14 & fastest way to determine if an integer’s square root is an integer & NF & NF & NF & NF \\ 15 & how can I concatenate two arrays in java & 9 & 1 & NF & 3 \\ 16 & how do I create a java string from the contents of a file & 3 & NF & 5 & 2 \\ 17 & how can I convert a stack trace to a string & 2 & 1 & 1 & 2 \\ 18 & how do I compare strings in java & NF & 1 & 1 & NF \\ 19 & how to split a string in java & 1 & 1 & 10 & 9 \\ 20 & how to create a file and write to a file in java & NF & 3 & 4 & 8 \\ 21 & how can I initialise a static map & 2 & 2 & 1 & 4 \\ 22 & iterating through a collection, avoiding concurrent modification exception when removing in loop & 5 & NF & 10 & 2 \\ 23 & how can I generate an md5 hash & 4 & 1 & 1 & 1 \\ 24 & get current stack trace in java & 1 & 1 & 1 & 1 \\ 25 & sort arraylist of custom objects by property & 2 & NF & 7 & 8 \\ 26 & how to round a number to n decimal places in java & 1 & 1 & 3 & 2 \\ 27 & how can I pad an integers with zeros on the left & 8 & NF & 10 & 2 \\ 28 & how to create a generic array in java & 3 & 1 & NF & 2 \\ 29 & reading a plain text file in java & 4 & 3 & 3 & 1 \\ 30 & a for loop to iterate over enum in java & NF & 1 & NF & NF \\ 31 & check if at least two out of three booleans are true & NF & NF & NF & NF \\ 32 & how do I convert from int to string & 10 & 1 & 4 & 10 \\ 33 & how to convert a char to a string in java & 6 & 1 & NF & 1 \\ 34 & how do I check if a file exists in java & NF & 1 & 3 & 1 \\ 35 & java string to date conversion & NF & 1 & 1 & NF \\ 36 & convert inputstream to byte array in java & 1 & 1 & 4 & 1 \\ 37 & how to check if a string is numeric in java & 2 & 1 & NF & 1 \\ 38 & how do I copy an object in java & NF & 5 & 7 & NF \\ 39 & how do I time a method's execution in java & NF & 1 & NF & 4 \\ 40 & how to read a large text file line by line using java & 8 & NF & NF & 1 \\ 41 & how to make a new list in java & 4 & 1 & 1 & NF \\ 42 & how to append text to an existing file in java & 1 & NF & NF & NF \\ 43 & converting iso 8601-compliant string to date & 9 & NF & 5 & 2 \\ 44 & what is the best way to filter a java collection & NF & 2 & NF & NF \\ 45 & removing whitespace from strings in java & NF & 1 & NF & 1 \\ 46 & how do I split a string with any whitespace chars as delimiters & NF & NF & 1 & 2 \\ 47 & in java, what is the best way to determine the size of an objects & NF & 1 & NF & NF \\ 48 & how do I invoke a java method when given the method name as a string & NF & NF & NF & NF \\ 49 & how do I get a platform dependent new line character & NF & NF & NF & NF \\ 50 & how to convert a map to list in java & 7 & 1 & NF & 4 \\ \bottomrule \end{tabular} \label{queries50} \end{table} \begin{table}[] \scriptsize \caption{\bl{The Queries$_{99}$ collected from Husain et al. \cite{husain2019codesearchnet}} and the Evaluation Results (NF: Not Found within the top 10 returned results, DCS: DeepCS \cite{gu2018deep}, CM: CodeMatcher, CH: CodeHow \cite{lv2015codehow}, UNIF \cite{cambronero2019deep}.)} \begin{tabular}{|c|L{80pt}|cccc||c|L{120pt}|cccc|} \toprule \textbf{No.} & \textbf{Query} & \textbf{DCS} & \textbf{CM} & \textbf{CH} & \textbf{UNIF} & \textbf{No.} & \textbf{Query} & \textbf{DCS} & \textbf{CM} & \textbf{CH} & \textbf{UNIF} \\ \midrule 1 & convert int to string & 2 & 1 & 6 & 2 & 51 & how to randomly pick a number & 6 & 5 & NF & 1 \\ 2 & priority queue & NF & NF & NF & 1 & 52 & normal distribution & NF & 1 & NF & NF \\ 3 & string to date & 9 & 1 & 1 & 6 & 53 & nelder mead optimize & NF & NF & NF & NF \\ 4 & sort string list & 1 & 1 & NF & 7 & 54 & hash set for counting distinct elements & 7 & NF & NF & NF \\ 5 & save list to file & 2 & 1 & NF & NF & 55 & how to get database table name & NF & 2 & NF & NF \\ 6 & postgresql connection & NF & 1 & 3 & NF & 56 & deserialize json & 1 & 1 & 1 & 1 \\ 7 & confusion matrix & NF & 6 & NF & 2 & 57 & find int in string & 5 & 1 & NF & 1 \\ 8 & set working directory & NF & 1 & NF & 1 & 58 & get current process id & 6 & 1 & NF & 1 \\ 9 & group by count & NF & 2 & 2 & NF & 59 & regex case insensitive & NF & 2 & NF & 10 \\ 10 & binomial distribution & NF & 7 & NF & 1 & 60 & custom http error response & 7 & 1 & 2 & NF \\ 11 & aes encryption & 5 & 1 & 3 & 7 & 61 & how to determine a string is a valid word & NF & NF & NF & NF \\ 12 & linear regression & NF & 2 & 4 & 1 & 62 & html entities replace & NF & NF & 1 & 1 \\ 13 & socket recv timeout & NF & 1 & 5 & 1 & 63 & set file attrib hidden & NF & NF & NF & NF \\ 14 & write csv & 1 & 2 & 6 & 1 & 64 & sorting multiple arrays based on another arrays sorted order & 5 & NF & 7 & NF \\ 15 & convert decimal to hex & 1 & 1 & NF & 1 & 65 & string similarity levenshtein & NF & 2 & 6 & 1 \\ 16 & export to excel & NF & 1 & 3 & 4 & 66 & how to get html of website & NF & 5 & 3 & NF \\ 17 & scatter plot & NF & 1 & 4 & NF & 67 & buffered file reader read text & 1 & 1 & 1 & NF \\ 18 & convert json to csv & NF & NF & 4 & NF & 68 & encrypt aes ctr mode & NF & NF & 1 & NF \\ 19 & pretty print json & 1 & 1 & NF & 1 & 69 & matrix multiply & NF & 1 & 1 & 1 \\ 20 & replace in file & 1 & 1 & NF & 2 & 70 & print model summary & NF & NF & NF & NF \\ 21 & k means clustering & NF & 3 & 1 & 3 & 71 & unique elements & 1 & 1 & NF & 1 \\ 22 & connect to sql & 1 & 1 & 1 & 1 & 72 & extract data from html content & 4 & NF & 2 & 1 \\ 23 & html encode string & 1 & 2 & 4 & 1 & 73 & heatmap from 3d coordinates & NF & NF & 3 & NF \\ 24 & finding time elapsed using a timer & NF & 1 & NF & 5 & 74 & get all parents of xml node & NF & 3 & 1 & NF \\ 25 & parse binary file to custom class & NF & NF & NF & NF & 75 & how to extract zip file recursively & NF & 1 & 7 & 4 \\ 26 & get current ip address & 2 & 1 & NF & 1 & 76 & underline text in label widget & NF & NF & NF & NF \\ 27 & convert int to bool & 2 & 1 & NF & 8 & 77 & unzipping large files & NF & 1 & 2 & NF \\ 28 & read text file line by line & 5 & NF & 1 & 1 & 78 & copying a file to a path & NF & 1 & 1 & NF \\ 29 & get executable path & 1 & 8 & 1 & 1 & 79 & get the description of a http status code & 5 & 1 & 4 & 1 \\ 30 & httpclient post json & 2 & 3 & 1 & NF & 80 & randomly extract x items from a list & 1 & NF & NF & NF \\ 31 & get inner html & 4 & 3 & 2 & 2 & 81 & convert a date string into yyyymmdd & 1 & 1 & 4 & 2 \\ 32 & convert string to number & 8 & 1 & 1 & 2 & 82 & convert a utc time to epoch & NF & NF & NF & NF \\ 33 & format date & 1 & 1 & 1 & 1 & 83 & all permutations of a list & NF & 1 & NF & 1 \\ 34 & readonly array & NF & NF & NF & NF & 84 & extract latitude and longitude from given input & 5 & NF & NF & 2 \\ 35 & filter array & 2 & 1 & 1 & 1 & 85 & how to check if a checkbox is checked & NF & 2 & NF & 2 \\ 36 & map to json & 2 & 3 & 2 & 3 & 86 & converting uint8 array to image & 1 & NF & NF & NF \\ 37 & parse json file & NF & 1 & NF & 2 & 87 & memoize to disk - persistent memoization & NF & NF & NF & NF \\ 38 & get current observable value & NF & NF & NF & NF & 88 & parse command line argument & 1 & 1 & 3 & 1 \\ 39 & get name of enumerated value & NF & NF & NF & 1 & 89 & how to read the contents of a .gz compressed file? & NF & NF & 1 & NF \\ 40 & encode url & 1 & 1 & 4 & 3 & 90 & sending binary data over a serial connection & NF & NF & NF & NF \\ 41 & create cookie & 1 & 1 & NF & NF & 91 & extracting data from a text file & 6 & NF & 9 & 1 \\ 42 & how to empty array & NF & NF & NF & NF & 92 & positions of substrings in string & 1 & 1 & 1 & 6 \\ 43 & how to get current date & NF & 2 & 1 & NF & 93 & reading element from html - \textless{}td\textgreater{} & NF & 1 & NF & NF \\ 44 & how to make the checkbox checked & NF & 1 & 2 & NF & 94 & deducting the median from each column & NF & NF & 1 & NF \\ 45 & initializing array & 2 & 1 & 10 & 4 & 95 & concatenate several file remove header lines & NF & 1 & NF & NF \\ 46 & how to reverse a string & NF & 1 & 1 & 5 & 96 & parse query string in url & 2 & NF & 9 & 2 \\ 47 & read properties file & 1 & 1 & NF & 1 & 97 & fuzzy match ranking & NF & NF & NF & NF \\ 48 & copy to clipboard & 1 & 1 & 1 & 3 & 98 & output to html file & NF & NF & 2 & NF \\ 49 & convert html to pdf & NF & 1 & 2 & NF & 99 & how to read .csv file in an efficient way & NF & NF & NF & NF \\ 50 & json to xml conversion & NF & 1 & NF & NF & \multicolumn{1}{l|}{} & & \multicolumn{4}{l|}{} \\ \bottomrule \end{tabular} \label{queries99} \end{table} \begin{table} \scriptsize \caption{\bl{The Queries$_{25}$ collected from Mishne et al. \cite{mishne2012typestate} and Keivanloo et al. \cite{keivanloo2014spotting}}, and the Evaluation Results (NF: Not Found within the top 10 returned results, DCS: DeepCS \cite{gu2018deep}, CM: CodeMatcher, CH: CodeHow \cite{lv2015codehow}, UNIF \cite{cambronero2019deep}.)} \begin{tabular}{|c|l|cccc|} \toprule \textbf{No.} & \textbf{Query} & \textbf{DCS} & \textbf{CM} & \textbf{CH} & \textbf{UNIF} \\ \midrule 1 & upload a file & 1 & 3 & 5 & 1 \\ 2 & parse a command-line and get values from it & NF & 1 & 1 & NF \\ 3 & prepare the executable and argument of a command-line & NF & 2 & NF & NF \\ 4 & create a path element and append it to existing and boot paths & NF & NF & NF & NF \\ 5 & run a query and iterate over the results & NF & NF & NF & NF \\ 6 & commit and then rollback a transaction & NF & 2 & 1 & 1 \\ 7 & get the key of an array element type & 1 & NF & 6 & NF \\ 8 & get the description and nature IDs of a Java project & NF & NF & NF & NF \\ 9 & create a new action & 2 & 1 & 1 & 6 \\ 10 & get the input for the current editor & NF & 2 & NF & NF \\ 11 & retrieve arguments from command line & NF & 1 & 1 & 6 \\ 12 & check user selection & 6 & 1 & NF & 1 \\ 13 & set up a ScrollingGraphicalViewer & NF & NF & NF & NF \\ 14 & create a project & 1 & 2 & NF & 3 \\ 15 & successfully login and logout & NF & 1 & NF & NF \\ 16 & click an Element & 1 & 1 & 1 & 2 \\ 17 & commit and rollback a statement & NF & NF & NF & 3 \\ 18 & send a HTTP request via URLConnection & 6 & 1 & 2 & 1 \\ 19 & redirect Runtime exec() output with System & NF & NF & NF & NF \\ 20 & get OS Level information such as memory & NF & NF & NF & 1 \\ 21 & SSH Connection & NF & 5 & NF & 3 \\ 22 & download and save a file from network & NF & 1 & NF & 1 \\ 23 & generate a string-based MD5 hash value & NF & NF & 6 & 2 \\ 24 & read the content of a HttpResponse object line by line & NF & NF & NF & NF \\ 25 & search via Lucene and manipulate the hits & NF & NF & 1 & NF \\ \bottomrule \end{tabular} \label{queries25} \end{table} \subsection{Baseline Models and Replication Package.}\label{baselines} In the experiment, \bl{three} models are selected as our baseline models, including Gu et al.'s \cite{gu2018deep} DeepCS, Lv et al.'s \cite{lv2015codehow} CodeHow\bl{, and Cambronero et al.'s UNIF \cite{cambronero2019deep}}. To test baseline models on our codebase, we first preprocessed Java code files within all projects by our tool JAnalyzer\footnote{https://github.com/liuchaoss/janalyzer}. It first parses the abstract syntax tree of each Java code file by leveraging the Javaparser\footnote{https://github.com/javaparser/javaparser} library, and extracts all necessary method components as the inputs of baselines, such as method name, comment, Javadoc, APIs in the method body, etc. Note that we do not test these models on DeepCS' original testing data but our new data, because DeepCS provides no raw data (i.e., no source code) but preprocessed data that can be only used by DeepCS. To mitigate the replication difficulty for our study, we provide a replication package\footnote{\textbf{Replication Package: https://bitbucket.org/ChaoLiuCQ/codematcher}} to share our codebase, and source code of CodeMatcher and baseline models. The compared baseline models are described as follows. \vspace{5pt}\noindent\textbf{DeepCS,} the DL-based model proposed by Gu et al. \cite{gu2018deep}: We trained DeepCS by re-running the source code\footnote{https://github.com/guxd/deep-code-search} and pre-processed training data\footnote{https://pan.baidu.com/s/1U$\_$MtFXqq0C-Qh8WUFAWGvg} provided by the authors. To test DeepCS on our codebase, we first did some natural language processing (e.g., stemming) following the description in Gu et al.'s paper \cite{gu2018deep}, then encoded data using DeepCS' vocabulary, and saved the encoded data into the required format by using DeepCS' internal APIs in source code. \vspace{5pt}\noindent\textbf{CodeHow,} the IR-based model developed by Lv et al. \cite{lv2015codehow}: It expands a query with words in related official APIs and matches it with code methods. As Lv et al. \cite{lv2015codehow} provide no source code and data for replication, we re-implemented CodeHow strictly following their paper. Our implementation can be found in our shared replication package. Note that as CodeHow was used for searching C\# projects while our targets are Java repositories, we thus used the JDK (Java development kit) as the source of official APIs. \vspace{5pt}\noindent\textbf{\bl{UNIF,}} \bl{the DL-based model proposed by Cambronero et al. \cite{cambronero2019deep}: Similar to DeepCS, the UNIF transforms code and query into vectors and it is trained by pairs of code and natural language description. However, the main differences are that: UNIF represents code by method name and a bag of tokens, which is a subset of DeepCS' input; the UNIF used the pre-trained fastText \cite{bojanowski2017enriching} as its embedding layer. Details can be found in \cite{cambronero2019deep}. As the author provided no source code, we re-implemented it by ourselves strictly following the description in the original study, which is also provided in our replication package.} \subsection{Evaluation Criteria}\label{criteria} To measure the effectiveness of code search models, we need to identify the relevancy of a returned code method to a query. Following Gu et al. \cite{gu2018deep}, the relevancy is manually identified by two independent developers, and the disagreements are resolved by open discussions. During the relevance identification, developers only consider the top-10 returned code methods. Based on the identified relevancy, we measure model performance using four widely used evaluation metrics following Gu et al. \cite{gu2018deep}, including FRank, SuccessRate@k, Precision@k, and Mean Reciprocal Rank (MRR). Note that FRank is defined only for one query while the other metrics are defined on all queries. \vspace{5pt}\noindent\textbf{FRank}, is the rank of the first correct result in the result list \cite{gu2018deep}. It measures users' inspection efforts for finding a relevant method when scanning the candidate list from top to bottom. A smaller FRank value implies fewer efforts and better effectiveness of a code search tool for a particular query. \vspace{5pt}\noindent\textbf{SuccessRate}@k, the percentage of queries for which more than one correct result exists in the top-k ranked results \cite{gu2018deep}. Specifically, $SuccessRate@k=Q^{-1}\sum_{q=1}^{Q}\delta(FRank_{q}\leq{k})$, where $Q$ is the total number of tested queries; $\delta(\cdot)$ is an indicator function that returns 1 if the input is true and 0 otherwise. Higher SuccessRate@k means better code search performance, and users can find desired method by inspecting fewer returned method list. \vspace{5pt}\noindent\textbf{Precision@k}, is the average percentage of relevant results in top-k returned method list for all queries. It is calculated by $Precision@k=Q^{-1}\sum_{q=1}^{Q}r_{q}/k$, where $Q$ is the total number of queries; $r_{q}$ is the number of related results for a query $q$ \cite{gu2018deep}. Precision@k is useful and important because users often check many returned results for learning different code usages \cite{raghothaman2016swim}. Larger Precision@k indicates that a code search model returns less noisy results. \vspace{5pt}\noindent\textbf{MRR}, the average of the reciprocal ranks for all queries, where the reciprocal rank of a query is the inverse of the rank of the first relevant result ($FRank$) \cite{gu2018deep}. Thus, the formula is $MRR=Q^{-1}\sum_{q=1}^{Q}FRank_{q}^{-1}$. Larger MRR value means a higher ranking for the first relevant methods. \subsection{The Importance of Model Simplification} \subsection{Pros and Cons of DL-based Model and IR-Based Model}\label{pros} The DL-based model has three major advantages over the IR-based model. One is language processing ability. By leveraging the embedding technique, it can better address complex queries and tolerate errors to some extent according to Section \ref{disucss}. The second is the bilingual learning ability. With the joint embedding framework between a query written in natural language and a code implemented in programming language, their mapping relationship can be well learned as described in Section \ref{rq1}. At last, the DL-based model may require less upfront cost than IR-based model, because the former requires much less domain knowledge and feature engineering like the IR-based model. However, \bl{the DL-based models (DeepCS and UNIF) have} a limitation on a new and dynamic codebase, because \bl{the studied models} suffer from overfitting and out-of-vocabulary issues as discussed in Section \ref{why}. But these problems do not occur for the IR-based models (CodeHow and CodeMatcher). Meanwhile, running the IR-based model is substantially more efficient over the DL-based model, because the IR-based model requires no model training and can speed up the code search process using a framework like Elasticsearch, as shown in Section \ref{codematcher_evaluation}. To sum up, the two kinds of studied code search models complement each other, therefore it is suggested to balance their pros and cons and make a fusion in the future. \SG{1}{Combine the advantages of IR-based and DL-based models.} \subsection{The Importance of Method Name} Section \ref{why_well} indicates that CodeMatcher works well mainly because it can precisely match the \bl{semantics between query and the method name}, where CodeMatcher assigns higher importance on programming words (e.g., Inputstream or String) and considers their sequence in the query. Besides, Section \ref{disucss} also shows that if a method precisely matched \bl{the semantics} in query such method is likely to contain expected implementation in the method body. This is because the method name is very similar to the query: \textit{(1) writing in natural language.} There is \bl{less} semantic gap between query and method name; \textit{(2) short in text.} They usually use the same keywords in order; \textit{(3) specific to code implementation.} Their semantic relationship to code implementation is usually the same and straightforward. Therefore, a code search engine should assign higher weights on method names, no matter for the DL-based or IR-based model. Moreover, although CodeMatcher is capable of handling synonyms in a query by using the WordNet as described in Section \ref{method}, it has three limitations: \textit{(1) abbreviation.} It cannot match the word 'initialize' in a query to the method named with 'ini'; \textit{(2) Acronym.} The method named with 'RMSD' should be missed for a query with the keyword "root mean square deviation"; \textit{(3) low quality of method naming.} The method name is not a correct abstraction on its code implementation. Meanwhile, other code search models (e.g., DeepCS and CodeHow) also do not consider these situations. One solution to these limitations is to increase the scale of the codebase, because the increased search space may include the methods whose names are similar to search queries (e.g, using abbreviations or acronyms). However, to solve these challenges, maybe the best way is to require developers strictly following a method naming standard in the beginning. For example, a developer follows the Google Java style guide\footnote{https://google.github.io/styleguide/javaguide.html\#s5-naming} and writes method name in verb (phases) with commonly used words, instead of self-defined synonym, acronym, and abbreviation. As to the existing large-scale source code in GitHub, maybe a better solution is to format their method names in a standard and unified way. \SG{2}{Method name has a significant role in code search; improving the quality of developers' method names helps code search.} \section{Introduction}\label{intro} \input{introduction.tex} \section{Background}\label{back} \input{background.tex} \section{CodeMatcher}\label{method} \input{method.tex} \section{Experiment Setup}\label{exp} \input{experiment.tex} \section{Results}\label{result} \input{results.tex} \section{Discussion}\label{disucss} \input{discussion.tex} \section{Implication}\label{implication} \input{implication.tex} \section{Threats to Validation and Model Limitation}\label{threat} \input{threat.tex} \section{Related Work}\label{related} \input{related.tex} \section{conclusion}\label{conclude} \input{conclusion.tex} \bibliographystyle{ACM-Reference-Format} \subsection{Motivation.} Different from the existing IR-based models, the DL-based model DeepCS can: (1) understand irrelevant/noisy keywords by word embedding technique, including synonyms and the words that have never appeared in the code methods; (2) capture sequential relationships between words in query and code methods via the LSTM model; and (3) map query intent to the semantics of code methods by measuring their semantic similarity \cite{gu2018deep}. However, due to the high complexity of DeepCS, it takes hours for model training and the code search is also time-consuming for practical usage. Therefore, it is necessary to find a way to simplify the model complexity but retain the beneficial features of the DL-based model. In this study, we simplify the DL-based model DeepCS into an IR-based model called CodeMatcher that maintains the advantages of DeepCS. Generally, we remove noisy keywords according to some collected metadata; replaces irrelevant keywords with appropriate synonyms extracted from codebase; design a code reranking approach by measuring the semantic similarity between query and code, which also considers the sequential relationship between words in query/code. The following subsection presents the implementation details of CodeMatcher. \subsection{Implementation}\label{implementation} The proposed model CodeMatcher performs code search in two phases following existing IR-based models, namely code indexing and code search, as described in Section \ref{back_ir}. Fig. \ref{fig_workflow} illustrates the overall framework of CodeMatcher. \begin{figure} \centering \includegraphics[width=0.9\linewidth]{workflow.eps} \caption{Overall framework of CodeMatcher.} \label{fig_workflow} \end{figure} \vspace{5pt}\noindent\textbf{Phase-I: Codebase Preprocessing and Indexing.} The first phase leverages the Elasticsearch \cite{gormley2015elasticsearch}, a Lucene-based text search engine for code indexing. Similar to existing IR-based models, we represent a code method as two components (i.e., method name and method body) and create an index for the method by calling the APIs provided by Elasticsearch. To extract method components from source code files, we developed a tool JAnalyzer\footnote{https://github.com/liuchaoss/janalyzer}, which transforms a method into an abstract syntax tree (AST) with the Javaparser\footnote{https://github.com/javaparser/javaparser} \cite{hosseini2013javaparser} library and extracts method name (e.g., "convertInputStreamToString()" in Table \ref{tab_example}) and body by traversing the AST. \bl{As JAnalyzer is depended on the Javaparser tool, thus it can only support the Java language instead of other programming languages.} Similar to the IR-based model CodeHow \cite{lv2015codehow}, the method body is parsed as a sequence of fully qualified tokens (e.g., Java.lang.String or System.io.File.readlines()) in method parameters, method body, and returned parameter. \vspace{5pt}\noindent\textbf{Phase-II: Code Search.} CodeMatcher takes three steps to perform code search on the indexed code methods for a query. The first step extracts some metadata for query understanding, and addresses noisy and irrelevant query words. The second step quickly finds a pool of highly related code methods from the codebase according to the collected metadata for query words. The last step reranks the searched methods in the second step according to the matching degrees between the query and candidate methods. \underline{\textit{Step-1: Query understanding.}} To address noisy words in a query, we removed the words that are not commonly used for programming. Specifically, we first identified word property (e.g., verb or noun) by using the Stanford Parser\footnote{https://nlp.stanford.edu/software/lex-parser.shtml} \cite{chen2014fast,zhang2017mining}. Then, we filtered out the question words and related auxiliary verb (e.g., how do), and excluded the verb-object/adpositional phrase on the programming language (e.g., in Java) as it is only used for the identification of programming language while our study only focuses on Java projects as Gu et al. \cite{gu2018deep}. Afterward, we removed the words that are not the verbs, nouns, adjectives, adverbs, prepositions, or conjunctions, since the removed words (e.g., 'a', 'the', and non-English symbols) are rarely used for coding \cite{arnold2000java}. Moreover, to identify the irrelevant words in a query, we counted the frequency of each word occurring in the method names of the codebase. We replaced the irrelevant words (i.e., the words not appeared in codebase) by their synonyms generated by the WordNet \cite{miller1998wordnet}. If the WordNet generates multiple synonyms for a word, we choose the synonym with the highest frequency in the codebase. Subsequently, we stemmed\footnote{https://pythonprogramming.net/stemming-nltk-tutorial/} the rest of query words to improve their generalizability in code search. Moreover, except for the words property (e.g., verb or noun) and frequency, we identified the third metadata named 'importance' for query words before performing code search. The word importance refers to how important a word used for programming. It can help CodeMatcher identify related important keywords between query and code methods. The importance is categorized by five levels as shown in Table \ref{tb_level}. For example, the most important one (i.e., level 5) is the JDK noun, e.g., "InputStream" or "readLine()". These metadata can help query understanding and forming keywords for code search. \bl{Verbs and nouns are important (level 4) as they can represent most of the semantics in code methods. This is because method/API names are typically made of verbs or verb phrases (such as "stop" or "sendMessage") while variable names are often written in nouns (e.g., "student" or "processor"), as described in the Google Java Style Guide\footnote{https://google.github.io/styleguide/javaguide.html}. We assigned JDK nouns with higher importance (level 5), because they are unique (namely it cannot be replaced by synonyms) and important to represent the semantics in code methods. For example, the JDK nouns "Inputstream" and "String" are important for the code with the semantics "convert Inputstream to String". Adjectives and adverbs are assigned lower importance (level 3) because they cannot indicate precise meaning without their corresponding noun/verb. Next, we assigned preposition/conjunction with the importance level 2. Finally, we assigned the other (often meaningless) symbols the lowest importance level (level 1).} \begin{table} \centering \caption{Five word importance levels for programming based on the word property (e.g., verb or noun) and whether the word is a class name in JDK.} \begin{tabular}{|cll|} \toprule \textbf{Level} & \textbf{Condition} & \textbf{Examples} \\ \midrule 5 & JDK Noun & "Inputstream" and "readLine()"\\ 4 & Verb or Non-JDK Noun & "convert" and "whitespace"\\ 3 & Adjective or Adverb & "numeric" and "decimal"\\ 2 & Preposition or Conjunction & "from" and "or"\\ 1 & Other & Number and Non-English Symbols\\ \bottomrule \end{tabular} \label{tb_level} \end{table} \underline{\textit{Step-2: Iterative fuzzy search.}} To map the semantics of the preprocessed query and indexed code methods, we utilized the filtered query words in Step-1 to generate keywords for code search. Here we only match the keywords with indexed method names to quickly narrow the search space. To perform code search, we launched an iterative fuzzy match on indexed method names with a regular string\footnote{https://docs.python.org/3/library/re.html}. The string is formed by all remaining query words in order as "$.*word_{1}.*\cdots.*word_{n}.*$". We used the regular match instead of the term match to capture the sequential relationship between words as DeepCS \cite{gu2018deep}. For example, "convert int to string" should be different from "convert string to int". Afterward, if the total number of returned methods is no more than ten, we removed the least important word with lower frequency one at a time according to their metadata, and performed the fuzzy search again until only no query word left. For each search round, we filtered out the repeated method by comparing the MD5 hash\footnote{https://docs.python.org/2/library/hashlib.html} values of their source code. \underline{\textit{Step-3: Reranking.}} To refine the method rankings returned from Step-2, we designed a metric ($S_{name}$) to measure the matching degree between query and method name as Eq. (\ref{eq_score}). A larger value of $S_{name}$ indicates a higher-ranked method with more overlapped tokens between query and method name in order. Moreover, if equal $S_{name}$ exists, we boosted the rank of a method with a higher matching score ($S_{body}$) between query and method body, as calculated in Eq. (\ref{eq_score2}). Similar to $S_{name}$, a higher $S_{body}$ value implies better token matching between query and tokens in method body orderly. However, different from $S_{name}$, we added the last term in $S_{body}$ to represent the ratio of JDK APIs in method, in terms of the fully qualified tokens, because developers favor a method with more basic APIs (e.g., JDK) \cite{sadowski2015developers,martie2015sameness}. After the above two rounds of ranking refinement, we returned the top-10 methods in the list. \bl{Note that, although our tool JAnalyzer can extract Javadocs and comments for code, the CodeMatcher did not consider them when reranking the searched code following all the related studies \cite{gu2018deep,lv2015codehow, cambronero2019deep,feng2020codebert,husain2019codesearchnet}. This is because the code search task aims to solve the semantic gap between the query in natural language and the code in programming language. Besides, whether the comments and Javadocs written in natural language are helpful for code search is highly dependent on their quality and number. However, in practical usage, we cannot assume that any code always contains high-quality comment or Javadoc.} \begin{equation}\label{eq_score} \begin{split} S_{name} &= \frac{\#query\ words\ as\ keywords}{\#query\ words} \\ &\times{} \frac{\#characters\ in\ name\ orderly\ matched\ keywords}{\# characters\ in\ name}\\ \end{split} \end{equation} \begin{equation}\label{eq_score2} \begin{split} S_{body} &= \frac{\#API\ words\ matched\ query\ words}{\#query\ words} \\ &\times{} \frac{Max[\#API\ words\ orderly\ matched\ query\ words]}{\#query\ words}\\ &\times{} \frac{\#JDK APIs}{\#APIs}\\ \end{split} \end{equation} \vspace{5pt}\noindent\textbf{Example.} Fig. \ref{codematcher_example} illustrated an example for the first query \textit{"convert an inputstream to a string"} in Table \ref{queries50}. From the token metadata, we can notice that both 'inputstream' and 'string' have level-5 importance (i.e., they are JDK objects), and they are frequently used for method naming (frequency$>$3442). With this metadata, CodeMatcher successively generates four candidate regular match strings on indexed method names. For the two returned methods, the first one ranked higher due to its larger matching scores on method name ($S_{name}$) and body ($S_{body}$). \begin{table} \centering \caption{An example for CodeMatcher} \begin{tabular}{|l|} \begin{tabular}{|l|c|c|c|c|c|c|} \toprule \mc{7}{\textbf{Query:} convert an inputstream to a string} \\ \midrule \mc{7}{\textbf{(0) Indexed Codebase}} \\ \midrule \mc{7}{\bl{Source Code 1:}}\\ \mc{7}{ public String \textbf{convertInputStreamToString}(InputStream is)\{}\\ \mc{7}{\quad{}InputStreamReader isr = new InputStreamReader(is);}\\ \mc{7}{\quad{}BufferedReader r = new BufferedReader(isr);}\\ \mc{7}{StringBuilder sb = new StringBuilder();}\\ \mc{7}{\quad{}String line;}\\ \mc{7}{\quad{}while ((line = r.readLine()) != null)\{}\\ \mc{7}{\quad{}\quad{}sb.append(line);}\\ \mc{7}{\quad{}\}}\\ \mc{7}{\quad{}return sb.toString();}\\ \mc{7}{\}}\\ \mc{7}{\bl{Method Name: }\rd{convertInputStreamToString}}\\ \mc{7}{\bl{API Sequence: }java.io.\rd{InputStream}, java.io.\rd{InputStream}Reader, java.lang.\rd{String}Builder,}\\ \mc{7}{java.lang.\rd{String}, java.lang.\rd{String}Builder.readline(), java.lang.\rd{String}Builder.append(),}\\ \mc{7}{java.lang.\rd{String}Builder.\rd{toString}(), java.io.\rd{String}}\\ \midrule \mc{7}{\bl{Source Code 2:} public String convertInputStream2String(InputStream is)\{}\\ \mc{7}{\quad{}return convert(is);}\\ \mc{7}{\}}\\ \mc{7}{\bl{Method Name: }\rd{convertInputStream}2\rd{String}}\\ \mc{7}{\bl{API Sequence: }java.io.\rd{InputStream}, Util.\rd{convert}(), java.lang.\rd{String}}\\ \midrule \mc{7}{\textbf{(1) Token Metadata}}\\ \midrule \bl{Token} & convert & an & inputstream & to & a & string\\ \midrule \bl{Property} & verb & other & noun & prep & other & noun \\ \midrule \bl{Frequency} & 39292 & 0 & 3442 & 22 & 0 & 52369\\ \midrule \bl{Importance} & 4 & 1 & 5 & 2 & 1 & 5\\ \midrule \mc{7}{\textbf{(2) Keywords for Code Search}}\\ \midrule \mc{7}{\bl{Regular Match String 1:} .*convert.*inputstream.*to.*string.*}\\ \mc{7}{\bl{Regular Match String 2:} .*convert.*inputstream.*string.*}\\ \mc{7}{\bl{Regular Match String 3:} .*inputStream.*string.*}\\ \mc{7}{\bl{Regular Match String 4:} .*String.*}\\ \midrule \mc{7}{\textbf{(3) Reranking}}\\ \midrule \mc{7}{\bl{Rank = 1, }\textbf{convertInputStreamToString()\{...\}}}\\ \mc{7}{\rd{$S_{name}=\frac{4}{6}\times\frac{26}{26}=0.67$}, \rd{$S_{body}=\frac{3}{6}\times\frac{3}{6}\times\frac{8}{8}=0.25$}}\\ \midrule \mc{7}{\bl{Rank = 2, }\textbf{convertInputStream2String()\{...\}}}\\ \mc{7}{\rd{$S_{name}=\frac{3}{6}\times\frac{24}{25}=0.48$}, \rd{$S_{body}=\frac{3}{6}\times\frac{2}{6}\times\frac{2}{3}=0.11$}}\\ \bottomrule \end{tabular} \end{tabular} \label{codematcher_example} \end{table} \subsection{Can CodeMatcher Outperform the \bl{Baseline} Models?}\label{rq1} \begin{table}[] \caption{Performance comparison of CodeMatcher and baseline models (DeepCS, CodeHow, and UNIF), where the model performance is measured by SuccessRate@1/5/10 (SR@1/5/10), Precision@1/5/10 (P@1/5/10), and MRR.} \begin{tabular}{|c|l|ccc|ccc|c|} \toprule \textbf{Queries} & \textbf{Model} & \textbf{SR@1} & \textbf{SR@5} & \textbf{SR@10} & \textbf{P@1} & \textbf{P@5} & \textbf{P@10} & \textbf{MRR} \\ \midrule \multirow{4}{*}{$Queries_{50}$} & DeepCS & 0.22 & 0.46 & 0.64 & 0.22 & 0.23 & 0.22 & 0.36 \\ & CodeHow & 0.30 & 0.52 & 0.62 & 0.30 & 0.23 & 0.21 & 0.41 \\ & UNIF & 0.22 & 0.58 & 0.68 & 0.22 & 0.21 & 0.17 & 0.40 \\ & CodeMatcher & 0.64 & 0.76 & 0.76 & 0.64 & 0.58 & 0.57 & 0.71 \\ \midrule \multirow{4}{*}{$Queries_{99}$} & DeepCS & 0.20 & 0.38 & 0.45 & 0.20 & 0.14 & 0.11 & 0.33 \\ & CodeHow & 0.22 & 0.45 & 0.54 & 0.22 & 0.21 & 0.19 & 0.36 \\ & UNIF & 0.33 & 0.49 & 0.56 & 0.33 & 0.21 & 0.15 & 0.43 \\ & CodeMatcher & 0.48 & 0.65 & 0.68 & 0.48 & 0.42 & 0.37 & 0.58 \\ \midrule \multirow{4}{*}{$Query_{25}$} & DeepCS & 0.16 & 0.20 & 0.28 & 0.16 & 0.06 & 0.06 & 0.26 \\ & CodeHow & 0.24 & 0.32 & 0.40 & 0.24 & 0.15 & 0.14 & 0.34 \\ & UNIF & 0.24 & 0.44 & 0.52 & 0.24 & 0.22 & 0.15 & 0.38 \\ & CodeMatcher & 0.28 & 0.56 & 0.56 & 0.28 & 0.26 & 0.19 & 0.46 \\ \midrule \multirow{4}{*}{$Queries_{all}$} & DeepCS & 0.20 & 0.38 & 0.48 & 0.20 & 0.15 & 0.13 & 0.33 \\ & CodeHow & 0.25 & 0.45 & 0.54 & 0.25 & 0.20 & 0.19 & 0.37 \\ & UNIF & 0.29 & 0.51 & 0.59 & 0.29 & 0.21 & 0.16 & 0.41 \\ & CodeMatcher & 0.50 & 0.67 & 0.68 & 0.50 & 0.44 & 0.40 & 0.60 \\ \bottomrule \end{tabular} \label{tab:results} \end{table} \begin{figure} \centering \includegraphics[width=0.9\linewidth]{baseline.eps} \caption{Violin plots of FRank for CodeMatcher and baseline models (DeepCS, CodeHow, and UNIF), where red squares and white dots indicate the mean and median FRank respectively; the values denote the mean FRank for each model; '*' indicates the significant difference (p-value $<$ 0.05) between a model and CodeMatcher, which is tested by the Wilcoxon signed-rank test \cite{wilcoxon1945individual} at a 5\% significance level.} \label{fig_frank_baseline} \end{figure} Table \ref{tab:results} compares the experimental results between the proposed model CodeMatcher and \bl{three baseline models (i.e., DeepCS, CodeHow, and UNIF)} on our large-scale testing data. We can notice that, for the studied 174 queries ($Queries_{all}$), DeepCS obtains an \bl{MRR of 0.33, where SuccessRate@1/5/10 = 0.20/0.38/0.48 and Precision@1/5/10 = 0.20/0.15/0.13.} Meanwhile, CodeHow achieves an \bl{MRR of 0.37 with SuccessRate@1/5/10 = 0.25/0.45/0.54 and Precision@1/5/10 = 0.25/0.20/0.19.} Besides, \bl{UNIF gains a better search performance with MRR = 0.41, where SuccessRate@1/5/10 = 0.29/0.51/0.59 and Precision@1/5/10 = 0.29/0.21/0.16.} Table \ref{tab:results} shows that the proposed model CodeMatcher achieves an \bl{MRR of 0.60 with SuccessRate@1/5/10 = 0.50/0.67/0.68 and Precision@1/5/10 = 0.50/0.44/0.40.} Comparing with the baseline models \bl{(DeepCS, Codehow, and UNIF)}, the MRR improved by \bl{81.8\%, 62.2\%, and 46.3\%} respectively; SuccessRate@1/5/10 increased by \bl{150\%/76.3\%/41.7\%, 100\%/48.9\%/25.9\%, and 72.4\%/31.4\%/15.3\%} respectively; Precision@1/5/10 boosted by \bl{150\%/193.3\%/207.7\%, 100\%/120\%/110.5\%, and 72.4\%/109.5\%/150\%} respectively. Moreover, Fig. \ref{fig_frank_baseline} shows the violin plots of FRank between models, where CodeMatcher obtains better mean FRank (4.55) over the other baselines ($>$6). CodeMatcher's advantage in FRank is also statistically significant (p-value$<$0.05), after we tested the FRank between CodeMatcher and a model with the Wilcoxon signed-rank test \cite{wilcoxon1945individual} at a 5\% significance level. The above experimental results imply that the CodeMatcher performs well and clearly outperforms existing solutions. \RS{1}{Our CodeMatcher outperforms the baseline models \bl{(DeepCS, CodeHow, and UNIF)} substantially, indicating the simplification from DeepCS to CodeMatcher is reasonable and valuable.} \subsection{Is CodeMatcher Faster than \bl{the Baseline} Models?}\label{codematcher_evaluation} Table \ref{tb_time} compares the time efficiency between CodeMatcher and baseline models \bl{(DeepCS, CodeHow, and UNIF)}. All these models ran on a server with an Intel-i7 CPU and an Nvidia Geforce GTX1060 GPU. \bl{In the practical usage, developers expect that code search models can quickly respond their search query, namely short searching time. For the IR-based models (CodeMatcher and CodeHow), they can quickly retrieve a small subset of methods from codebase by leveraging the indexing technique (commonly with <1s for a query) and sort the candidates with a light-weight ranking strategy. Note that the indexing technique needs to build indexing for all methods in advance to facilitate the code search. Although building indexing may take a long time, it is acceptable as building indexing commonly works offline. Meanwhile, to return the top-n relevant methods for a query, the DL-based models (DeepCS and UNIF) have to compute the cosine similarities between query and all methods among codebase in terms of high-dimension vectors. As DL-based models cannot accelerate the search time like the IR-based models with the indexing technique, they have to leverage the multi-threading technique to boost their performance.} The results show that DeepCS took 58.16h to train, 24.51h to preprocess codebase (i.e., parse, encode, and vectorize method name/APIs/tokens), and 376.4s to search code for each query. \bl{In contrast, UNIF only spent 4.1h for model training because its network is simple which contains only embedding and attention layers instead of the complex LSTM layer used in DeepCS. However, UNIF required 455.3s to complete the searching task for a query, much slower than DeepCS, because UNIF represented code/query into vector with 500 dimensions \cite{cambronero2019deep} while DeepCS only needed vectors with 400 dimensions \cite{gu2018deep}. Although the dimension just increased by 25\%, UNIF takes 21\% more time for code search as the codebase is large with more than 16 million code as described in Table \ref{codebase}. Therefore, the similarity computation for the higher dimensional vectors takes much more time, even if the UNIF has a simple network.} Comparing with DeepCS \bl{and UNIF}, our IR-based model CodeMatcher ran faster and \bl{substantially decreased the code search time from 370+s to 0.3s per query.} We can notice that CodeMatcher did not need a long-time training \bl{as DL-based models, although the training usually happens rarely (or just once).} As to the searching time, CodeMatcher only required 23.5h to preprocess code (23.2h for code parsing and 0.3h for code indexing). \bl{We found that the DL-based models work slowly mainly because it is time-consuming ($>$300s for a query) to load the 23+GB vectorized codebase (with 16m methods) for computing their cosine similarities with the query even using the multi-threading technique. But the IR-based models do not have this issue, because they leveraged the indexing technique to quickly ($<$1s for a query) reduce the search space scale (from 16m methods to hundreds of methods or less) so that the code search can be done in a very short time. Therefore, further DL-based studies need to consider ways to solve this bottleneck.} Additionally, CodeMatcher works \bl{8 times faster than} the IR-based model CodeHow mainly because \bl{the fuzzy search component in CodeMatcher only retrieved a limited number of candidate code from codebase as described in Section \ref{implementation}.} \begin{table} \centering \caption{Time efficiency comparison between CodeMatcher and baseline models in three different phases.} \setlength{\tabcolsep}{12pt}{ \begin{tabular}{|l|rrr|} \toprule \textbf{Model} & \textbf{Train} & \textbf{Preprocess} & \textbf{Search}\\ \midrule DeepCS & 58.2h & 24.5h & 376.4s/query\\ UNIF & 4.1h & 24.2h & 455.3s/query \\ CodeHow & - & 23.5h & 2.4s/query\\ CodeMatcher & - & 23.5h & 0.3s/query \\ \bottomrule \end{tabular}} \label{tb_time} \end{table} The 23.5 hours of code preprocessing seems time-consuming for CodeMatcher. However, there are about 17 million methods, as shown in Table \ref{tb_time}, and each method only takes about 0.005s for code preprocessing on average. \bl{The low preprocessing time for the IR-based models means that the model can quickly parse and index the update or added methods in codebase.} Thus, CodeMatcher can support the dynamic and rapidly expanding code scale of GitHub as this model requires no optimization, where changed or new methods can be rapidly parsed and indexed. \RS{2}{Our model CodeMatcher is faster than the DL-based models DeepCS \bl{and UNIF}, because CodeMatcher requires no model training and it can process a query with \bl{more than 1.2k times} speedup. Meanwhile, the CodeMatcher works \bl{8 times faster than} the IR-based model CodeHow.} \subsection{\bl{How do the CodeMatcher Components Contribute to the Code Search Performance?}}\label{why_well} \bl{Generally, the CodeMatcher consists of three components: query understanding, fuzzy search, and reranking, As described in Section \ref{implementation}. The query understanding aims to collect metadata for fuzzy search and reranking. Note that the query understanding component leveraged the Stanford Parser to identify the property of query words (e.g., noun and verb). However, the property cannot be precisely identified due to the limitation of the Stanford Parser. We found that the parser failed to work for 124 words in 7 cases, which affects 55.2\% of the 174 queries. To investigate how the parser's accuracy affects the model performance. We manually corrected the wrong cases, and applied them to the code search (CodeMatcher+SP$^{+}$). Table \ref{tab:components} shows that CodeMatcher+SP$^{+}$ obtains an MRR of 0.61, outperforming CodeMatcher by only 2\%. Fig. \ref{fig_frank_component} also indicates that the mean FRank (4.47 vs. 4.55) between CodeMatcher+SP$^{+}$ and CodeMatcher is not significantly different (p-value$>$0.05) after performing the Wilcoxon signed-rank test \cite{wilcoxon1945individual} at a 5\% significance level. We found that the optimization seldom improved the search performance because of two reasons. One is that some failed identifications do not influence the importance level for words as described in Table \ref{tb_level}, including "Noun->Verb" and "Verb->Noun". The other reason is that many queries are short with a limited number of words so that the other two components can still find the expected code. Thus, under this situation, the accuracy of the used Stanford Parser is acceptable for CodeMatcher.} \bl{Moreover, to investigate how the key components (fuzzy search and reranking) affect the model performance, we tested the CodeMatcher by excluding the reranking (CodeMatcher-Rerank). Table \ref{tab:components} shows that the MRR of CodeMatcher-Rerank is 0.47, which is reduced by 21.7\% comparing with the MRR of CodeMatcher. Besides, Fig. \ref{fig_frank_component} shows that the mean FRank value is increased from 4.55 to 6.0, where the difference is significant (p-value$<$0.05). These results indicate that the reranking plays an important role in searching code. Besides, we can observe that even though the fuzzy search component outperforms the other baseline models (DeepCS, CodeHow, and UNIF) in terms of MRR (<0.42) by 42.4\%, 27.0\%, and 14.7\% respectively.} \begin{table}[] \caption{Performance comparison of CodeMatcher with different component settings (\bl{-Rerank, excluding the reranking component; -S$_{body}$, excluding the ranking strategy $S_{body}$ in the reranking component; +SP$^{+}$, using the corrected results generated by the Stanford Parser}), where the model performance is measured by SuccessRate@1/5/10 (SR@1/5/10), Precision@1/5/10 (P@1/5/10), and MRR.} \begin{tabular}{|c|l|ccc|ccc|c|} \toprule \textbf{Queries} & \textbf{Model} & \textbf{SR@1} & \textbf{SR@5} & \textbf{SR@10} & \textbf{P@1} & \textbf{P@5} & \textbf{P@10} & \textbf{MRR} \\ \midrule \multirow{4}{*}{$Queries_{50}$} & CodeMatcher & 0.64 & 0.76 & 0.76 & 0.64 & 0.58 & 0.57 & 0.71 \\ & CodeMatcher-Rerank & 0.54 & 0.68 & 0.68 & 0.54 & 0.42 & 0.40 & 0.63 \\ & CodeMatcher-$S_{body}$ & 0.60 & 0.72 & 0.74 & 0.60 & 0.53 & 0.50 & 0.68 \\ & CodeMatcher+$SP^+$ & 0.66 & 0.76 & 0.76 & 0.66 & 0.59 & 0.58 & 0.72 \\ \midrule \multirow{4}{*}{$Queries_{99}$} & CodeMatcher & 0.48 & 0.65 & 0.68 & 0.48 & 0.42 & 0.37 & 0.58 \\ & CodeMatcher-Rerank & 0.33 & 0.51 & 0.58 & 0.33 & 0.29 & 0.25 & 0.45 \\ & CodeMatcher-$S_{body}$ & 0.45 & 0.62 & 0.67 & 0.45 & 0.37 & 0.33 & 0.56 \\ & CodeMatcher+$SP^+$ & 0.49 & 0.66 & 0.69 & 0.49 & 0.42 & 0.38 & 0.60 \\ \midrule \multirow{4}{*}{$Queries_{25}$} & CodeMatcher & 0.28 & 0.56 & 0.56 & 0.28 & 0.26 & 0.19 & 0.46 \\ & CodeMatcher-Rerank & 0.12 & 0.16 & 0.24 & 0.12 & 0.11 & 0.09 & 0.21 \\ & CodeMatcher-$S_{body}$ & 0.32 & 0.52 & 0.52 & 0.32 & 0.28 & 0.22 & 0.46 \\ & CodeMatcher+$SP^+$ & 0.32 & 0.56 & 0.56 & 0.32 & 0.30 & 0.26 & 0.48 \\ \midrule \multirow{4}{*}{$Queries_{all}$} & CodeMatcher & 0.50 & 0.67 & 0.68 & 0.50 & 0.44 & 0.40 & 0.60 \\ & CodeMatcher-Rerank & 0.36 & 0.51 & 0.56 & 0.36 & 0.30 & 0.27 & 0.47 \\ & CodeMatcher-$S_{body}$ & 0.48 & 0.63 & 0.67 & 0.48 & 0.40 & 0.37 & 0.58 \\ & CodeMatcher+$SP^+$ & 0.52 & 0.67 & 0.69 & 0.52 & 0.45 & 0.42 & 0.61 \\ \bottomrule \end{tabular} \label{tab:components} \end{table} \begin{figure} \centering \includegraphics[width=0.9\linewidth]{component.eps} \caption{Violin plots of FRank for CodeMatcher \bl{with different settings (-Rerank, excluding the reranking component; -S$_{body}$, excluding the ranking strategy $S_{body}$ in the reranking component; +SP$^{+}$, using the corrected results generated by the Stanford Parser)}, where red squares and white dots indicate the mean and median FRank respectively; the values denote the mean FRank for each model; '*' indicates the significant difference (p-value $<$ 0.05) between a model and CodeMatcher, which is tested by the Wilcoxon signed-rank test \cite{wilcoxon1945individual} at a 5\% significance level.} \label{fig_frank_component} \end{figure} \begin{table}[] \caption{\bl{Wrong cases that the Stanford Parser in CodeMatcher identified the property of query words.}} \begin{tabular}{|c|c||c|c|} \toprule \textbf{Wrong Case} & \textbf{No.} & \textbf{Wrong Case} & \textbf{No.} \\ \midrule Noun-\textgreater{}Verb & 67 & Noun-\textgreater{}Adjective & 7 \\ Verb-\textgreater{}Noun & 23 & Verb-\textgreater{}Adjective & 2 \\ Adjective-\textgreater{}Verb & 18 & Conjective-\textgreater{}Noun & 1 \\ Adjective-\textgreater{}Noun & 6 & \textbf{Total} & 124 \\ \bottomrule \end{tabular} \label{wrong_cases_for_sp} \end{table} For CodeMatcher described in Section \ref{method}, $S_{name}$ and $S_{body}$ are two matching scores to determine the ranks of searched results, but it is unknown how much they attributed to the performance of CodeMatcher. Thus, we used CodeMatcher for code search but removing the matching score $S_{body}$. Table \ref{tab:results} shows that the model only using $S_{name}$ (CodeMatcher-$S_{body}$) obtains \bl{MRR = 0.47}. Comparing with standard CodeMatcher, MRR is reduced by \bl{21.7\%}. Besides, the violin plots in Fig. \ref{fig_frank_component} shows that the mean FRank \bl{(4.55 vs. 4.81)} between CodeMatcher and CodeMatcher-$S_{body}$ are not significantly different (p-value $>$ 0.05 for the Wilcoxon signed-rank test \cite{wilcoxon1945individual} at a 5\% significance level). These results indicate that the score $S_{name}$ that matches query keywords with method name dominated the performance of CodeMatcher, and implies that method name is a significant bridge for the semantic gap between query and code. Furthermore, although the influence of $S_{body}$ that matches query keywords with method body is low, we cannot ignore its contribution. We observed that $S_{body}$ did not work as well as $S_{name}$ because it cannot fully connect the semantics of query and method body, which are written in natural language and programming language respectively. Therefore, the $S_{body}$ part requires further improvement. \RS{3}{\bl{All the CodeMatcher components are necessarily required.} CodeMatcher works well mainly because it can precisely match the query with relevant methods in names by considering the importance of the programming words in the query and the order of query tokens.} \subsection{Can CodeMatcher Outperform Existing Online Code Search Engines?}\label{rq4} \begin{table}[] \caption{Performance comparison of CodeMatcher and online search engines (Google and GitHub search), where the model performance is measured by SuccessRate@1/5/10 (SR@1/5/10), Precision@1/5/10 (P@1/5/10), and MRR.} \begin{tabular}{|c|l|ccc|ccc|c|} \toprule \textbf{Queries} & \textbf{Model} & \textbf{SR@1} & \textbf{SR@5} & \textbf{SR@10} & \textbf{P@1} & \textbf{P@5} & \textbf{P@10} & \textbf{MRR} \\ \midrule \multirow{4}{*}{$Queries_{50}$} & CodeMatcher & 0.64 & 0.76 & 0.76 & 0.64 & 0.58 & 0.57 & 0.71 \\ & GitHub Search & 0.28 & 0.60 & 0.64 & 0.28 & 0.21 & 0.17 & 0.44 \\ & Google Search & 0.32 & 0.80 & 0.90 & 0.32 & 0.34 & 0.30 & 0.51 \\ & CodeMatcher+Google & 0.72 & 0.90 & 0.94 & 0.72 & 0.42 & 0.34 & 0.80 \\ \midrule \multirow{4}{*}{$Queries_{99}$} & CodeMatcher & 0.48 & 0.65 & 0.68 & 0.48 & 0.42 & 0.37 & 0.58 \\ & GitHub Search & 0.27 & 0.57 & 0.64 & 0.27 & 0.21 & 0.17 & 0.42 \\ & Google Search & 0.27 & 0.56 & 0.66 & 0.27 & 0.29 & 0.24 & 0.42 \\ & CodeMatcher+Google & 0.49 & 0.71 & 0.76 & 0.49 & 0.34 & 0.26 & 0.61 \\ \midrule \multirow{4}{*}{$Queries_{25}$} & CodeMatcher & 0.28 & 0.56 & 0.56 & 0.28 & 0.26 & 0.19 & 0.46 \\ & GitHub Search & 0.16 & 0.40 & 0.48 & 0.16 & 0.14 & 0.14 & 0.31 \\ & Google Search & 0.28 & 0.52 & 0.60 & 0.28 & 0.24 & 0.24 & 0.41 \\ & CodeMatcher+Google & 0.32 & 0.56 & 0.68 & 0.32 & 0.25 & 0.24 & 0.45 \\ \midrule \multirow{4}{*}{$Queries_{all}$} & CodeMatcher & 0.50 & 0.67 & 0.68 & 0.50 & 0.44 & 0.40 & 0.60 \\ & GitHub Search & 0.26 & 0.55 & 0.61 & 0.26 & 0.20 & 0.17 & 0.41 \\ & Google Search & 0.29 & 0.62 & 0.72 & 0.29 & 0.30 & 0.26 & 0.45 \\ & CodeMatcher+Google & 0.53 & 0.74 & 0.80 & 0.53 & 0.35 & 0.28 & 0.64 \\ \bottomrule \end{tabular} \label{tab:search_engine} \end{table} \begin{figure} \centering \includegraphics[width=0.9\linewidth]{online.eps} \caption{Violin plots of FRank for CodeMatcher and compared models (GitHub search, Google search, CodeMatcher + Google), where red squares and white dots indicate the mean and median FRank respectively; the values denote the mean FRank for each model; '*' indicates the significant difference (p-value $<$ 0.05) between a model and CodeMatcher, which is tested by the Wilcoxon signed-rank test \cite{wilcoxon1945individual}.} \label{fig_frank_engine} \end{figure} GitHub\footnote{https://github.com/search} and Google\footnote{https://www.google.com/} search engines are what developers commonly used for code search in the real world. Comparing CodeMatcher with GitHub/Google search is helpful for understanding the usefulness of CodeMatcher. To investigate the advantages of CodeMatcher over the GitHub/Google search, we used the \bl{174 queries in Tables \ref{queries50}-\ref{queries25}} as their inputs and performed code search on the whole Java code methods in GitHub. To work on GitHub codebase, the Google search engine performs code search with the following advanced settings: "site:github.com" and "filetype:java". However, we need to note that GitHub and Google search engines are different from CodeMatcher in three aspects: \textit{(1) Larger-scale codebase.} the codebase of GitHub and Google contains more repositories, because these two online search engines cannot control the search scope as our collected codebase for CodeMatcher. \textit{(2) Wider context.} GitHub/Google search matches keywords in a query on all text in code files (e.g., method, comment, and Javadoc) while CodeMatcher only uses texts on methods. \textit{(3) Code snippet vs. method.} GitHub/Google search returns a list of code snippets, but they would not necessarily be a method as what CodeMatcher returns. When using the GitHub and Google search engines for code search, both of them return a list of code snippets with matched keywords, and then we inspect top-10 code snippets to check whether the snippets are relevant to the corresponding queries. We excluded the snippet that was returned just because its comment records the Stack Overflow link (e.g., \textit{"https://stackoverflow.com/questions/157944/create-arraylist-from-array"}) with the same string as the search query (e.g., "create arraylist from array"). This is because the query is also collected from the question title of that link, so that this kind of code snippet will overestimate the performance of GitHub/Google search. \bl{As CodeMatcher searches code not based on comment or Javadoc, we do not need to filter the Stack Overflow links as GitHub and Google searchers.} Table \ref{tab:search_engine} shows that the GitHub search achieves \bl{MRR = 0.41 with SuccessRate@1/5/10 = 0.26/0.55/0.61 and Precision@1/5/10 = 0.26/0.20/0.17.} Meanwhile the Google search obtains an \bl{MRR of 0.45, where SuccessRate@1/5/10 = 0.29/0.62/0.72 while Precision@1/5/10 = 0.29/0.30/0.26} respectively. We can notice that CodeMatcher outperforms GitHub and Google search engines by \bl{46.3\% and 33.3\%} respectively in terms of MRR; by \bl{92.3\%/21.8\%/11.5\% and 72.4\%/8.1\%/-5.6\%} in terms of SuccessRate@1/5/10; by \bl{92.3\%/120\%/135.3\% and 72.4\%/46.7\%/53.8\%} in terms of Precision@1/5/10. Additionally, as illustrated in Fig. \ref{fig_frank_engine}, CodeMatcher achieves better mean FRank \bl{(4.55)} over GitHub/Google search (mean FRank $>$ 5.1); the difference is statistically significant (p-value$<$0.05 tested by the Wilcoxon signed-rank test \cite{wilcoxon1945individual} at a 5\% significance level). These results indicate that CodeMatcher shows advantages in SuccessRate@1/5, Precision@1/5/10, and MRR as compared with the existing two online search engines. These experimental results indicate the practical merit of the CodeMatcher over the GitHub/Google search. Moreover, we can notice that although Google cannot achieve high precision as CodeMatcher if returning only one method for a query, it can successfully recommend at least one relevant method for more queries. Due to this observation, we investigate the code search performance of combining CodeMatcher and Google together, where the first method returned by Google is replaced by the one recommended by CodeMatcher. The last row in Table \ref{tab:search_engine} shows that the combined model (CodeMatcher+Google) gains the best SuccessRate@1/5/10 \bl{(0.53/0.74/0.80), Precision@1 (0.53), and MRR (0.64)} compared with other models in the Table, even if there are some sacrifices in Precision@5/10 \bl{(0.35/0.28)}. \bl{We found that CodeMatcher+Google gains higher SuccessRate@1 than CodeMatcher because CodeMatcher cannot find any results for some queries which can be compensated by Google's results. Specifically, the CodeMatcher and Google cannot return any correct code for 31.6\% and 28.2\% of total queries respectively when we inspected the top-10 returned results. But the adopted combination strategy (CodeMatcher+Google) can reduce the failure rate to 20\%.} We can also notice that the combined model (CodeMatcher+Google) improved the mean FRanks of CodeMatcher \bl{(4.55) and Google (5.16) to 3.78} as illustrated in Fig. \ref{fig_frank_engine}, although the improvement over CodeMatcher is not statistically significant (p-value$>$0.05 tested by the Wilcoxon signed-rank test \cite{wilcoxon1945individual} at a 5\% significance level). This case implies that it is beneficial to incorporate the proposed model CodeMatcher into the Google search engine. \RS{4}{CodeMatcher is also advantageous over existing online search engines, GitHub and Google search. It is beneficial to incorporate CodeMatcher into the Google search for practical usage.} \subsection{Threats to Validity \rs{and Limitations}} There are some threats affecting the validity of our experimental results and conclusions. \vspace{5pt}\noindent\textbf{Manual Evaluation.} The relevancy of returned code methods to the studied queries was manually identified, which could suffer from subjectivity bias. To mitigate this threat, the manual analysis was performed independently by two developers from Baidu inc. \bl{For the first query set ($Queries_{50}$),} they reach a substantial agreement in terms of the value (0.62) of Cohen's Kappa static \cite{viera2005understanding}; and if developers disagreed on a relevancy identification, they performed an open discussion to resolve it. \bl{For the second and third query sets ($Queries_{99}$ and $Queries_{25}$), the agreement was improved to 0.72 in terms of the Cohen's Kappa static due to developers' increased evaluation experiences.} In the future, we will mitigate this threat by inviting more developers. Moreover, in the relevancy identification, we only consider the top-10 returned code results following Gu et al. \cite{gu2018deep}. However, in the real-world code search, this setting is reasonable because developers would like to inspect the top-10 results and ignore the remaining due to the impacts of developers' time and patience. \vspace{5pt}\noindent\textbf{Limited Queries and Java Codebase.} Following Gu et al. \cite{gu2018deep}, we evaluated the model with popular questions from Stack Overflow, which may not be representative of all possible queries for code search engines. To mitigate this threat, the selected top-50 queries are the most frequently asked questions collected by Gu et al. \cite{gu2018deep} in a systematic procedure, as referred to in Section \ref{exp}. \bl{We also extended 99 more queries that provided in the CodeSearchNet challenge \cite{husain2019codesearchnet} and 25 more queries from two related studies \cite{mishne2012typestate,keivanloo2014spotting}.} \bl{Besides, many studied queries are highly related to popular APIs, so that the CodeMatcher may not work for queries with less popular APIs. In this case, the performance of CodeMatcher could be overestimated.} In the future, we will extend the \bl{scale, scope, and variety} of the code search queries. \bl{We also plan to investigate how to automatically evaluate model performance on a large-scale codebase}. Furthermore, we performed the experiments with large-scale open-source Java repositories. But we have not evaluated repositories in other programming languages, though the idea of extending CodeMatcher to any language is easy and applicable. Moreover, we collected about 41k GitHub projects with high-quality code (i.e., more than 5 stars) as the codebase. But such search space is likely to overestimate a model, because such projects are going to have more accurate Javadoc and generally cleaner, easier to understand code that is more likely to be commented. Although we extended Gu et al.'s \cite{gu2018deep} codebase (around 1k projects with at least 20 stars) on a larger scale, this situation cannot be ignored. We plan to extend our codebase more in the near future. \vspace{5pt}\noindent\textbf{Baseline Reproduction.} To estimate DeepCS on our testing data, we preprocessed the testing data according to Gu et al. \cite{gu2018deep} although the source code and training data have no difference. Meanwhile, we re-implemented the baseline CodeHow \bl{and UNIF strictly following the paper \cite{lv2015codehow} and \cite{cambronero2019deep} respectively} because their authors provide no source code. Our baseline reproductions may threaten the validity of our model. To mitigate this threat, we double-checked our code and also present all the replication packages in public as described in Section \ref{baselines}. \vspace{5pt}\noindent\textbf{Model Limitation.} Like all the existing code search models, the proposed solution CodeMatcher may not work if a search query shares no irrelevant words with the methods in codebase. To address this limitation, CodeMatcher replaced the words that do not appeared in a codebase by their synonyms extracted from the codebase. This limitation could be further mitigated by combining CodeMatcher with a DL-based model as described in Section \ref{pros}. We intend to investigate this research in the near future. \bl{Section \ref{rq4} indicated the Stanford Parser used in CodeMatcher is not accurate. Although the corrected results only improve the model performance slightly for our studies, we cannot ignore this limitation in the further studies.}
{'timestamp': '2022-02-23T02:15:21', 'yymm': '2005', 'arxiv_id': '2005.14373', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14373'}
arxiv
\section*{\large\refname} \small\@mkboth{\MakeUppercase\refname}{\MakeUppercase\refname} \list{\@biblabel{\@arabic\c@enumiv}} {\settowidth\labelwidth{\@biblabel{#1}} \leftmargin\labelwidth \advance\leftmargin\labelsep \@openbib@code \usecounter{enumiv}% \let\p@enumiv\@empty \renewcommand\theenumiv{\@arabic\c@enumiv}} \sloppy \clubpenalty4000 \@clubpenalty \clubpenalty \widowpenalty4000% \sfcode`\.\@m} {\def\@noitemerr {\@latex@warning{Empty `thebibliography' environment}} \endlist} \setlength{\parskip}{\baselineskip} \makeatother \title{Multiresolution Decomposition of Areal Count Data} \titlerunning{Multiresolution Decomposition of Areal Count Data} \author{R. Flury$^1$ and R. Furrer$^2$} \authorrunning{R. Flury \emph{et al.}} \address{$^1$ Department of Mathematics, University of Zurich, Switzerland; roman.flury@math.uzh.ch\\ $^2$ Department of Mathematics \& Department of Computational Science, University of Zurich, Switzerland; reinhard.furrer@math.uzh.ch} \abstract{ Multiresolution decomposition is commonly understood as a procedure to capture scale-dependent features in random signals. Such methods were first established for image processing and typically rely on raster or regularly gridded data. In this article, we extend a particular multiresolution decomposition procedure to areal count data, i.e.~discrete irregularly gridded data. More specifically, we incorporate in a new model concept and distributions from the so-called Besag--York--Molli\'{e} model to include a priori demographical knowledge. These adaptions and subsequent changes in the computation schemes are carefully outlined below, whereas the main idea of the original multiresolution decomposition remains. Finally, we show the extension's feasibility by applying it to oral cavity cancer counts in Germany.} \keywords{ Spatial scales; Lattice data; Intrinsic GMRF; Besag--York--Molli\'{e} model; MCMC. } \begin{document} \maketitle \thispagestyle{empty} \section{Introduction} Decomposing an observed signal or spatial field into scale-dependent components allows recognizing its inherent and prominent features. Those features give insight to where local or global phenomena manifest themselves and assist in understanding the structure of hierarchical information. Holmstr\"om et al.~(2011) proposed a procedure in the tradition of image processing that hence is applicable to Gaussian data distributed on regular grids~\cite{H01}. We extend this method to count data which is potentially observed on an irregular grid, often termed \lq{areal count data}\rq~\cite{C93}. The original multiresolution decomposition approach can be divided into three individual steps: 1)~spatial field resampling based on a Bayesian hierarchical model, 2)~smoothing on multiple scales, then calculating differences between these smooths to specify details for each resampled field separately, and 3)~posterior credibility analysis. In the following paragraphs we summarize a) the Bayesian hierarchical model for step 1) and b) how to calculate differences between smooths in step 2). Those are the relevant parts in the procedure for the proposed extension, outlined in Section~2. The original multiresolution decomposition assumes that an observed field $\boldsymbol{y}$ consists of the true field $\boldsymbol{x}$ and additive noise. Based on these flexible model assumptions the hierarchical model is constructed. a) Bayesian hierarchical model: the true field $\boldsymbol{x}$ is presumed to follow a Gaussian distribution, which implies a selfsame likelihood function. Its positive valued variance is modeled with a scaled--inv--$\chi^2$ prior and the spatial component of the field $\boldsymbol{x}$ is captured with an intrinsic Gaussian Markov random field (IGMRF) using a precision matrix $\boldsymbol{Q}$~\cite{R05}. With those choices, the resulting marginal posterior is of closed form and corresponds to a multivariate t-distribution~\cite{E05}. b) Calculate differences between smooths: the proposed penalty smoother is defined as $\boldsymbol{S}_{\lambda} = (\mathbf{I} + \lambda\boldsymbol{Q})^{-1}$, where $\lambda$ is the scale or smoothing parameter, such that $0 = \lambda_1 < \lambda_2 < \ldots < \lambda_L = \infty$. The spatial field $\boldsymbol{x}$ is interpreted as random vector, $\boldsymbol{S}_{\lambda_1}\boldsymbol{x} = \boldsymbol{x}$ defines the identity mapping and $\boldsymbol{S}_{\lambda_L}\boldsymbol{x} =~\boldsymbol{S}_{\infty}\boldsymbol{x}$ the mean field. On the ground of those preliminaries, $\boldsymbol{x}$ can be decomposed as differences of consecutive smooths: $\boldsymbol{x} = \sum_{l=1}^{L-1} \left( \boldsymbol{S}_{\lambda_l} - \boldsymbol{S}_{\lambda_{l+1}} \right)\boldsymbol{x} + \boldsymbol{S}_{\infty}\boldsymbol{x}$. Scale-dependent details are then formalized as $\boldsymbol{z}_l = \left(\boldsymbol{S}_{\lambda_l} - \boldsymbol{S}_{\lambda_{l+1}} \right)\boldsymbol{x}$ for $l = 1, \ldots, L-1$ and $\boldsymbol{z}_L = \boldsymbol{S}_{\infty}\boldsymbol{x}$. Pivotal for a) and b) is the definition of the precision matrix~$\boldsymbol{Q}$: \begin{equation} \boldsymbol{x}^\top\boldsymbol{Qx} = \sum_j \bigg( \sum\limits_{i \sim j} x_i - 4 x_j \biggr)^2, \end{equation} where $i{\sim}j$ denotes neighboring grid locations. To ensure four neighbors at every grid location $i$, the boundary values of $\boldsymbol{x}$ are extended across the initial grid. This definition inherently demands the data allocated to a regular grid but bears the advantage that individual computational steps can be optimized based on $\boldsymbol{Q}$'s fast eigendecomposition, such that large dimensional problems can be solved efficiently. \section{Extension}\label{sec:method} To decompose areal count data, first the resampling pattern described in a) needs modification. Assuming the $n$ observed counts $\boldsymbol{y}=(y_1,\dots,y_n)^\top$ are realizations from a conditionally independent Poisson distribution and the expected counts $\boldsymbol{e}=(e_1,\dots,e_n)^\top$ are known for every location in the spatial field. The Poisson's rate for a location $i$, is defined as the product of the expected count $e_i$ and the respective relative risk, denoted as $\exp{(\eta_i)}$. We construct the hierarchical model, to resample the spatial field, with the likelihood function \begin{equation} \pi(\boldsymbol{y}|\eta_1,\dots,\eta_n) \propto \prod_{i=1}^{n} \exp{\bigl(y_i\eta_i - e_i\exp{(\eta_i)\bigr)}}, \end{equation} which corresponds to the classical Besag--York--Molli{\'e} (BYM) model~\cite{B91}. Whereat $\boldsymbol{\eta}$ is modeled as the composition of the true log-relative risk $\boldsymbol{u}$ and a normal zero-mean noise term $\boldsymbol{v}$, with unknown precision parameter $\kappa_{\boldsymbol{v}}$. Analogous to the original model, we use a first order IGMRF process to model the spatial component with accompanying precision parameter $\kappa_{\boldsymbol{u}}$, such that \begin{equation} \pi(\boldsymbol{u}|\kappa_{\boldsymbol{u}}) \propto \kappa_{\boldsymbol{u}}^{\frac{n-1}{2}} \exp{\left( -\frac{\kappa_{\boldsymbol{u}}}{2} \sum_{i \sim j} (u_i - u_j)^2 \right)} = \kappa_{\boldsymbol{u}}^{\frac{n-1}{2}} \exp{\left( -\frac{\kappa_{\boldsymbol{u}}}{2} \boldsymbol{u}^\top \boldsymbol{R} \boldsymbol{u} \right)}. \end{equation} Again $i{\sim}j$ denotes neighboring lattice locations but here in terms of regions sharing a common border. Assigning Gamma priors for both precision parameters implies a posterior distribution of non-closed form. Hence, we use a Gibbs sampler with a Metropolis-Hastings (MH) step to resample the log-relative risks $\boldsymbol{u}$, the noise components $\boldsymbol{v}$ and parameters~\cite{G15}. Finally, we exploit that the mean of a Poisson distribution is equivalent to its rate and reconstruct the spatial field with $\boldsymbol{e} \cdot \exp{(\boldsymbol{u} + \boldsymbol{v})}$, for every sampled field $\boldsymbol{u}$ and $\boldsymbol{v}$. We form the scale-dependent details still relying on a penalty smoother. Instead of using the matrix $\boldsymbol{Q}$ from the original model, we include the precision matrix $\boldsymbol{R}$ of the first order IGMRF~\cite{R05}. The definition of $\boldsymbol{R}$ does not limit the data to be associated with a regular grid and can be constructed based on adjacency relations of the respective observations. Since we use a different precision matrix, the optimized implementation relying on $\boldsymbol{Q}$ cannot be employed but we alternatively take advantage of the precision's sparse structure and apply tailored algorithms~\cite{F10}. \section{Application}\label{sec:application} The extension's feasibility is demonstrated on the German oral cavity cancer dataset~\cite{K00}. This data includes cancer counts for 544 districts of Germany over 1986--1990, as well as the expected number of cases derived demographically. The main bulk of the oral cavity counts range between one and hundred counts per district but single highly populated districts have up to 500. The data including additional relevant information is available via the \textsc{R} package \textbf{spam}~\cite{F10}. Following the multiresolution decomposition steps, we first resample the areal counts using suitable sampler specifications~\cite{G15} and verify the convergence of the MH sampler with common diagnostic tools~\cite{B98}. Figure~\ref{fig1} shows how well the reconstructed field corresponds to the original data. Only in northeast Germany, where the field is less smooth, the differences are larger. Since the BYM model was designed not to be oversensitive to extreme counts, part of the resampling difference can be explained through its damping effect~\cite{W10}. \begin{figure}[!htb] \centerline{\includegraphics[scale=0.53]{germany_yanderror.png}} \caption{Oral cavity cancer data on logarithmic scale. Left: the observed number of cases; middle: the mean of the reconstructed fields; right: the difference between the left and the middle panels.} \label{fig1} \end{figure} In the second step, we choose suitable scales~(\cite{P13}) $\lambda_1 = 0$, $\lambda_2 = 1$ and $\lambda_3 = 25$ and form scale-dependent details (Figure~\ref{fig2}). Completing the decomposition, we calculate pointwise probability maps~\cite{H01} (Figure~\ref{fig3}). The detail $\boldsymbol{z}_1$ reflects spatial noise as well as the relatively low or high counts in the data. This is also supported by its pointwise probability map, where no large red or blue clusters are visible. $\boldsymbol{z}_2$ catches larger patches of districts and shows local peculiarities. Detail $\boldsymbol{z}_3$ consists of the largest scale range and shows the east-west or nationwide trend but this trend is less distinct compared to the more local ones, indicated by the legends of each panel. \begin{figure}[!htb] \centerline{\includegraphics[scale=0.53]{germany_smMean.png}} \caption{Scale dependent details $\boldsymbol{z}_l=\boldsymbol{S}_{\lambda_l}{\log(\boldsymbol{e} \cdot \exp{(\boldsymbol{u} + \boldsymbol{v})} ) } - \boldsymbol{S}_{\lambda_l+1}{\log(\boldsymbol{e} \cdot \exp{(\boldsymbol{u} + \boldsymbol{v})} )}$, summarized by their posterior means. Left:~$\text{E}(\boldsymbol{z}_1|\boldsymbol{y})$; middle:~$\text{E}(\boldsymbol{z}_2|\boldsymbol{y})$; right:~$\text{E}(\boldsymbol{z}_3|\boldsymbol{y})$.} \label{fig2} \end{figure} \begin{figure}[!htb] \centerline{\includegraphics[scale=0.53]{germany_pw.png}} \caption{Pointwise probability maps. Left:~$\boldsymbol{z}_1$; middle:~$\boldsymbol{z}_2$; right:~$\boldsymbol{z}_3$. The map indicates which features are jointly credible: blue and red areas indicate jointly credibly negative and positive areas, respectively.} \label{fig3} \end{figure} \section{Discussion}\label{sec:discussion} We extended the multiresolution decomposition approach from Holmstr\"om et al. (2011), which originally processes data coming from a Gaussian distribution on a regular grid, to areal count data. Establishing an MH sampling model makes it possible to resample count data and use an arbitrary precision matrix. Employing the BYM model to include prior demographical knowledge, in the form of the known expected counts, enables us to model the data without being oversensitive to possible outliers. The \textsc{R} code to reproduce this example is available at https://git.math.uzh.ch/roflur/bymresa. \bibliographystyle{plain}
{'timestamp': '2020-06-01T02:09:36', 'yymm': '2005', 'arxiv_id': '2005.14473', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14473'}
arxiv
\section{Introduction} We study learning the best possible single neuron that captures the relationship between the input $x\in \mathbb{R}^d$ and the output label $y\in \mathbb{R}$ as measured by the expected square loss over some unknown but fixed distribution $(x,y)\sim \mathcal{D}$. In particular, for a given activation function $\sigma:\mathbb{R}\to \mathbb{R}$, we define the population risk $F(w)$ associated with a set of weights $w$ as \begin{equation} F(w) := (1/2) \mathbb{E}_{(x,y) \sim \mathcal{D}} \l[ \l( \sigma(w^\top x) - y \r)^2\r]. \label{eq:optim.obj} \end{equation} The activation function is assumed to be non-decreasing and Lipschitz, and includes nearly all activation functions used in neural networks such as the rectified linear unit (ReLU), sigmoid, $\tanh$, and so on. In the agnostic PAC learning setting \citep{kearns.agnostic}, no structural assumption is made regarding the relationship of the input and the label, and so the best-fitting neuron could, in the worst case, have nontrivial population risk. Concretely, if we denote \begin{equation} v := \mathrm{argmin}_{\pnorm w2 \leq 1} F(w),\quad \mathsf{OPT}:= F(v), \label{def:v.pop.risk.minimizer} \end{equation} then the goal of a learning algorithm is to (efficiently) return weights $w$ such that the population risk $F(w)$ is close to the best possible risk $\mathsf{OPT}$. The agnostic learning framework stands in contrast to the \textit{realizable} PAC learning setting, where one assumes $\mathsf{OPT}=0$, so that there exists some $v$ such that the labels are given by $y=\sigma(v^\top x)$. The learning algorithm we consider in this paper is empirical risk minimization using vanilla gradient descent. We assume we have access to a set of i.i.d. samples $\{(x_i,y_i)\}_{i=1}^n\sim \mathcal{D}^n$, and we run gradient descent with a fixed step size on the empirical risk $\hat F(w) = (1/2n)\textstyle \summ i n (\sigma(w^\top x_i)-y_i)^2$. A number of early neural network studies pointed out that the landscape of the empirical risk of a single neuron has unfavorable properties, such as a large number of spurious local minima~\citep{brady1989,auer1995}, and led researchers to instead study gradient descent on a convex surrogate loss~\citep{helmbold95worstcase,helmbold99relativeloss}. Despite this, we are able to show that gradient descent on the empirical risk itself finds weights that not only have small empirical risk but small population risk as well. Surprisingly little is known about neural networks trained by minimizing the empirical risk with gradient descent in the agnostic PAC learning setting. We are aware of two works \citep{allenzhu.3layer,allenzhu.kernel} in the \textit{improper} agnostic learning setting, where the goal is to return a hypothesis $h\in \mathcal{H}$ that achieves population risk close to $\hat \mathsf{OPT}$, where $\hat \mathsf{OPT}$ is the smallest possible population risk achieved by a different set of hypotheses $\hat \mathcal{H}$. Another work considered the random features setting where only the final layer of the network is trained and the marginal distribution over $x$ is uniform on the unit sphere~\citep{vempala}. But none of these address the simplest possible neural network: that of a single neuron $x\mapsto \sigma(w^\top x)$. We believe a full characterization of what we can (or cannot) guarantee for gradient descent in the single neuron setting will help us understand what is possible in the more complicated deep neural network setting. Indeed, two of the most common hurdles in the analysis of deep neural networks trained by gradient descent---nonconvexity and nonsmoothness---are also present in the case of the single neuron. We hope that our analysis in this relatively simple setup will be suggestive of what is possible in more complicated neural network models. Our main contributions can be summarized as follows. \begin{enumerate}[1)] \item \textbf{Agnostic setting} (Theorem \ref{theorem:agnostic}). Without any assumptions on the relationship between $y$ and $x$, and assuming only boundedness of the marginal distributions of $x$ and $y$, we show that for any $\varepsilon>0$, gradient descent finds a point $w_t$ with population risk $O(\mathsf{OPT}) + \varepsilon$ with sample complexity $O(\varepsilon^{-2})$ and runtime $O(\varepsilon^{-1})$ when $\sigma(\cdot)$ is strictly increasing and Lipschitz. When $\sigma$ is ReLU, we obtain a population risk guarantee of $O(\mathsf{OPT}^{1/2})+\varepsilon$ with sample complexity $O(\varepsilon^{-4})$ and runtime $O(\varepsilon^{-2})$ when the marginal distribution of $x$ satisfies a nondegeneracy condition (Assumption \ref{assumption:marginal.spread}). The sample and runtime complexities are independent of the input dimension for both strictly increasing activations and ReLU \item \textbf{Noisy teacher network setting} (Theorem \ref{theorem:glm}). When $y = \sigma(v^\top x) + \xi$, where $\xi|x$ is zero-mean and sub-Gaussian (and possibly dependent on $x$), we demonstrate that gradient descent finds $w_t$ satisfying $F(w_t) \leq \mathsf{OPT} + \varepsilon$ for activation functions that are strictly increasing and Lipschitz assuming only boundedness of the marginal distribution over $x$. The same result holds for ReLU under a marginal spread assumption (Assumption \ref{assumption:marginal.spread}). The runtime and sample complexities are of order $\tilde O(\varepsilon^{-2})$, with a logarithmic dependence on the input dimension. When the noise is bounded, our guarantees are dimension independent. If we further know $\xi \equiv 0$, i.e. the learning problem is in the realizable rather than agnostic setting, we can improve the runtime and sample complexity guarantees from $O(\varepsilon^{-2})$ to $O(\varepsilon^{-1})$ by using online stochastic gradient descent (Theorem \ref{theorem:gd.loss}). \end{enumerate} \section{Related work} Below, we provide a high-level summary of related work in the agnostic learning and teacher network settings. Detailed comparisons with the most related works will appear after we present our main theorems in Sections \ref{sec:agnostic} and \ref{sec:noisy}. In Appendix \ref{appendix:comparisons}, we provide tables that describe the assumptions and complexity guarantees of our work in comparison to related results. \noindent \textbf{Agnostic learning:} The simplest version of the agnostic regression problem is to find a hypothesis that matches the performance of the best \textit{linear} predictor. In our setting, this corresponds to $\sigma$ being the identity function. This problem is completely characterized:~\citet{shamir15} showed that any algorithm that returns a linear predictor $v$ has risk $\mathsf{OPT} + \Omega(\varepsilon^{-2}\wedge d\varepsilon^{-1})$ when the labels satisfy $|y|\leq 1$ and the marginal distribution over $x$ is supported on the unit ball, matching upper bounds proved by~\citet{srebro.mirror} using mirror descent. When $\sigma$ is not the identity, related works are scarce.~\citet{goel2017relupoly} studied agnostic learning of the ReLU on distributions supported on the unit sphere but had runtime and sample complexity exponential in $\varepsilon^{-1}$. In another work on learning a single ReLU,~\citet{goel2019relugaussian} showed that learning up to risk $\mathsf{OPT}+\varepsilon$ in polynomial time is as hard as the problem of learning sparse parities with noise, long believed to be computationally intractable. Additionally, they provided an approximation algorithm that could learn up to $O(\mathsf{OPT}^{2/3})+\varepsilon$ risk in $\poly(d, \varepsilon^{-1})$ time and sample complexity when the marginal distribution over $x$ is a standard Gaussian. In a related but incomparable set of results in the improper agnostic learning setting,~\citet{allenzhu.3layer} and \citet{allenzhu.kernel} showed that multilayer ReLU networks trained by gradient descent can match the population risk achieved by multilayer networks with smooth activation functions.~\citet{vempala} studied agnostic learning of a one-hidden-layer neural network when the first layer is fixed at its (random) initial values and the second layer is trained. A very recent work by \citet{diakonikolas2020approximation} showed that population risk $O(\mathsf{OPT})+\varepsilon$ can be achieved for the single ReLU neuron by appealing to gradient descent on a convex surrogate for the empirical risk. \noindent\textbf{Teacher network:} The literature refers to the case of $y= \sigma(v^\top x) + \xi$ for some possible zero mean noise $\xi$ variously as the ``noisy teacher network'' or ``generalized linear model'' (GLM) setting, and is related to the probabilistic concepts model~\citep{kearns.probabilistic}. In the GLM setting, $\sigma$ plays the role of the inverse link function; in the case of logistic regression, $\sigma$ is the sigmoid function. The results in the teacher network setting can be broadly characterized by (1) whether they cover arbitrary distributions over $x$ and (2) the presence of noise (or lackthereof). The GLMTron algorithm proposed by~\citet{kakade2011}, itself a modification of the Isotron algorithm of~\citet{kalai2009isotron}, is known to learn a noisy teacher network up to risk $\mathsf{OPT}+\varepsilon$ for any Lipschitz and non-decreasing $\sigma$ and any distribution with bounded marginals over $x$.~\citet{mei2016landscape} showed that gradient descent learns the noisy teacher network under a smoothness assumption on the activation function for a large class of distributions.~\citet{foster2018} provided a meta-algorithm for translating $\varepsilon$-stationary points of the empirical risk to points of small population risk in the noisy teacher network setting. A recent work by~\citet{mukherjee} develops a modified SGD algorithm for learning a ReLU with bounded adversarial noise on distributions where the input is bounded. Of course, any guarantee that holds for a neural network with a single fully connected hidden layer of arbitrary width holds for the single neuron, so in this sense our work can be connected to a larger body of work on the analysis of gradient descent used for learning neural networks. The majority of such works are restricted to particular input distributions, whether it is Gaussian or uniform distributions~\citep{soltanolkotabi2017relus,tian2017relu,soltanolkotabi2019theoretical,zhanggu2019,goel.convotron,cao2019cnn}.~\citet{du2017} showed that in the noiseless (a.k.a. realizable) setting, a single neuron can be learned with SGD if the input distribution satisfies a certain subspace eigenvalue property.~\citet{yehudai20} studied the properties of learning a single neuron for a variety of increasing and Lipschitz activation functions using gradient descent, as we do in this paper, although their analysis was restricted to the noiseless setting. \section{Agnostic learning setting} \label{sec:agnostic} We begin our analysis by assuming there is no \textit{a priori} relationship between $x$ and $y$, so the population risk $\mathsf{OPT}$ of the population risk minimizer $v$ defined in \eqref{def:v.pop.risk.minimizer} may, in general, be a large quantity. If $\mathsf{OPT} =0$, then $\sigma(v^\top x) = y$ a.s. and the problem is in the realizable PAC learning setting. In this case, we can use a modified proof technique to get stronger guarantees for the population risk; see Appendix \ref{appendix:realizable} for the complete theorems and proofs in this setting. We will thus assume without loss of generality that $0 < \mathsf{OPT} \leq 1$. The gradient descent method we use in this paper is as follows. We assume we have a training sample $\{(x_i,y_i)\}_{i=1}^n\stackrel{\rm i.i.d.}{\sim} \mathcal{D}^n$, and define the empirical risk for weight $w$ by \[ \hat F(w) = (1/2n)\textstyle \summ i n (\sigma(w^\top x_i) - y_i)^2.\] We perform full-batch gradient updates on the empirical risk using a fixed step size $\eta$, \begin{equation} w_{t+1} = w_t - \eta \nabla \hat F(w_t) = w_t - (\eta/n) \textstyle \summ i n (\sigma(w_t^\top x_i) - y_i) \sigma'(w_t^\top x_i) x_i, \label{eq:gd.updates} \end{equation} where $\sigma'(\cdot)$ is the derivative of $\sigma(\cdot)$. If $\sigma$ is not differentiable at a point $z$, we will use its subderivative. We begin by describing one set of activation functions under consideration in this paper. \begin{assumption} \begin{enumerate}[(a)] \item $\sigma$ is continuous, non-decreasing, and differentiable almost everywhere. \item For any $\rho > 0$, there exists $\gamma >0$ such that $\inf_{|z| \leq \rho} \sigma'(z) \geq \gamma > 0$. If $\sigma$ is not differentiable at $z\in[-\rho,\rho]$, assume that every subderivative $g$ on the interval satisfies $g(z)\geq \gamma$. \item $\sigma$ is $L$-Lipschitz, i.e. $|\sigma(z_1)-\sigma(z_2)|\leq L|z_1-z_2|$ for all $z_1,z_2$ \end{enumerate} \label{assumption:activation.fcn} \end{assumption} We note that if $\sigma$ is strictly increasing and continuous, then $\sigma$ satisfies Assumption \ref{assumption:activation.fcn}(b) since its derivative is never zero. In particular, the assumption covers the typical activation functions in neural networks like leaky ReLU, softplus, sigmoid, tanh, etc., but excludes ReLU. \citet{yehudai20} recently showed that when $\sigma$ is ReLU, there exists a distribution $\mathcal{D}$ supported on the unit ball and unit length target neuron $v$ such that \textit{even in the realizable case} of $y = \sigma(v^\top x)$, if the weights are initialized randomly using a product distribution, there exists a constant $c_0$ such that with high probability, $F(w_t) \geq c_0 >0$ throughout the trajectory of gradient descent. This suggests that gradient-based methods for learning ReLUs are likely to fail without additional assumptions. Because of this, they introduced the following marginal spread assumption to handle the learning of ReLU. \begin{assumption} There exist constants $\alpha, \beta >0$ such that the following holds. For any $w\neq u$, denote by $\mathcal{D}_{w,u}$ the marginal distribution of $\mathcal{D}$ on $\mathrm{span}(w,u)$, viewed as a distribution over $\mathbb{R}^2$, and let $p_{w,u}$ be its density function. Then $\inf_{z\in \mathbb{R}^2:\norm{z}\leq \alpha} p_{w,u}(z) \geq \beta$. \label{assumption:marginal.spread} \end{assumption} This assumption covers, for instance, log-concave distributions like the Gaussian and uniform distribution with $\alpha, \beta = O(1)$~\citep{lovasz}. We note that a similar assumption was used in recent work on learning halfspaces with Massart noise~\citep{diakonikolas2020}. We will use this assumption for all of our results when $\sigma$ is ReLU. Additionally, although the ReLU is not differentiable at the origin, we will denote by $\sigma'(0)$ its subderivative, with the convention that $\sigma'(0)=1$. Such a convention is consistent with the implementation of ReLUs in modern deep learning software packages With the above in hand, we can describe our main theorem. \begin{theorem}\label{theorem:agnostic} Suppose the marginals of $\mathcal{D}$ satisfy $\pnorm{x}2\leq B_X$ a.s. and $|y|\leq B_Y$ a.s. Let $a:=(|\sigma(B_X)|+B_Y)^2$. When $\sigma$ satisfies Assumption \ref{assumption:activation.fcn}, let $\gamma>0$ be the constant corresponding to $\rho=2B_X$ and fix a step size $\eta \leq (1/8)\gamma L^{-3} B_X^{-2}$. For any $\delta>0$, with probability at least $1-\delta$, gradient descent initialized at the origin and run for $T = \ceil{\eta^{-1}\gamma^{-1} L^{-1} B_X^{-1} [\mathsf{OPT} + a n^{-1/2} \log^{1/2}(4/\delta)]^{-1}}$ iterations finds weights $w_t$, $t<T$, such that \begin{equation} F(w_t) \leq C_1 \mathsf{OPT} + C_2 n^{-1/2}, \label{eq:agnostic.F.bound} \end{equation} where $C_1 = 12\gamma^{-3} L^3 + 2$ and $C_2 = O(L^3 B_X^2\sqrt{\log(1/\delta)} + C_1 a \sqrt{\log(1/\delta)})$. When $\sigma$ is ReLU, further assume that $\mathcal{D}_x$ satisfies Assumption \ref{assumption:marginal.spread} for constants $\alpha, \beta >0$, and let $\nu = \alpha^4 \beta / 8 \sqrt 2$. Fix a step size $\eta \leq (1/4) B_X^{-2}$. For any $\delta>0$, with probability at least $1-\delta$, gradient descent initialized at the origin and run for $T = \ceil{\eta^{-1}B_X^{-1}[\mathsf{OPT} +an^{-1/2}\log^{1/2}(4/\delta)]^{-1/2}}$ iterations finds a point $w_t$ such that \begin{equation} F(w_t) \leq C_1 \mathsf{OPT}^{1/2} + C_2 n^{-1/4}+ C_3 n^{-1/2}, \label{eq:agnostic.F.bound} \end{equation} where $C_1 = O(B_X \nu^{-1})$, $C_2 = O( C_1 a^{1/2} \log^{1/4} (1/\delta))$, and $C_3 = O(B_X^2 \nu^{-1} \log^{1/2}(1/\delta))$. \end{theorem} We remind the reader that the optimization problem for the empirical risk is highly nonconvex~\citep{auer1995} and thus any guarantee for the empirical risk, let alone the population risk, is nontrivial. This makes us unsure if the suboptimal guarantee of $O(\mathsf{OPT}^{1/2})$ for ReLU is an artifact of our analysis or a necessary consequence of nonconvexity. In comparison to recent work,~\citet{goel2019relugaussian} considered the agnostic setting for the ReLU activation when the marginal distribution over $x$ is a standard Gaussian and showed that learning up to risk $\mathsf{OPT}+\varepsilon$ is as hard as learning sparse parities with noise. By using an approximation algorithm of~\citet{awasthi}, they were able to show that one can learn up to $O(\mathsf{OPT}^{2/3})+\varepsilon$ with $O(\mathrm{poly}(d, \varepsilon^{-1}))$ runtime and sample complexity. In a very recent work, \citet{diakonikolas2020approximation} improved the population risk guarantee for the ReLU to $O(\mathsf{OPT}) + \varepsilon$ when the features are sampled from an isotropic log-concave distribution by analyzing gradient descent on a convex surrogate loss. Projected gradient descent on this surrogate loss produces the weight updates of the GLMTron algorithm of~\citet{kakade2011}. Using the solution found by gradient descent on the surrogate loss, they proposed an improper learning algorithm that improves the population risk guarantee from $O(\mathsf{OPT})+\varepsilon$ to $(1+\delta) \mathsf{OPT} + \varepsilon$ for any $\delta>0$. By contrast, we show that gradient descent on the empirical risk learns up to a population risk of $O(\mathsf{OPT})+\varepsilon$ for \textit{any} joint distribution with bounded marginals when $\sigma$ is strictly increasing and Lipschitz, even though the optimization problem is nonconvex. In the case of ReLU, our guarantee holds for the class of bounded distributions over $x$ that satisfy the marginal spread condition of Assumption \ref{assumption:marginal.spread} and hence covers (bounded) log-concave distributions, although the guarantee is $O(\mathsf{OPT}^{1/2})$ in this case. For all activation functions we consider, the runtime and sample complexity guarantees do not have (explicit) dependence on the dimension.\footnote{We note that for some distributions, the $B_X$ term may hide an implicit dependence on $d$; more detailed comments on this are given in Appendix \ref{appendix:comparisons}.} Moreover, we shall see in the next section that if the data is known to come from a noisy teacher network, the guarantees of gradient descent improve to $\mathsf{OPT}+\varepsilon$ for both strictly increasing activations and ReLU. In the remainder of this section we will prove Theorem \ref{theorem:agnostic}. Our proof relies upon the following auxiliary errors for the true risk $F$: \begin{align} \nonumber G(w) &:= (1/2) \mathbb{E}_{(x,y)\sim \mathcal{D}} \l[ \l( \sigma(w^\top x) - \sigma(v^\top x) \r)^2 \r],\\ \label{def:auxiliary.loss} H(w) &:= (1/2)\mathbb{E}_{(x,y)\sim \mathcal{D}} \l[ \l( \sigma(w^\top x) - \sigma(v^\top x) \r)^2 \sigma'(w^\top x) \r]. \end{align} We will denote the corresponding empirical risks by $\hat G(w)$ and $\hat H(w)$. We first note that $G$ trivially upper bounds $F$: this follows by a simple application of Young's inequality and, when $\mathbb{E}[y|x]~=~\sigma(v^\top x)$, by using iterated expectations. \begin{claim} \label{claim:Gbound:implies:Fbound} For any joint distribution $\mathcal{D}$, for any vector $u$, and any continuous activation function $\sigma$, $F(u) \leq 2 G(u) + 2 F(v)$. If additionally we know that $\mathbb{E}[y|x] = \sigma(v^\top x)$, we have $F(u)~=~G(u)~+~F(v)$. \end{claim} This claim shows that in order to show the population risk is small, it suffices to show that $G$ is small. It is easy to see that if $\inf_{z\in \mathbb{R}} \sigma'(z) \geq \gamma > 0$, then $H(w)\leq \varepsilon$ implies $G(w) \leq \gamma^{-1} \varepsilon$, but the only typical activation function that satisfies this condition is the leaky ReLU. Fortunately, when $\sigma$ satisfies Assumption \ref{assumption:activation.fcn}, or when $\sigma$ is ReLU and $\mathcal{D}$ satisfies Assumption \ref{assumption:marginal.spread}, Lemma \ref{lemma:Hsurrogate} below shows that $H$ is still an upper bound for $G$. The proof is deferred to Appendix~\ref{appendix:Hsurrogate}. \begin{lemma} \label{lemma:Hsurrogate} \label{lemma:relu.of.implies.f} If $\sigma$ satisfies Assumption \ref{assumption:activation.fcn}, $\pnorm{x}2\leq B$ a.s., and $\pnorm{w}2\leq W$, then for $\gamma$ corresponding to $\rho = W B$, $H(w)\leq \varepsilon$ implies $G(w)\leq \gamma^{-1} \varepsilon$. If $\sigma$ is ReLU and $\mathcal{D}$ satisfies Assumption \ref{assumption:marginal.spread} for some constants $\alpha, \beta >0$, and if for some $\varepsilon>0$ the bound $H(w)\leq \beta \alpha^4 \varepsilon / 8 \sqrt 2$ holds, then $\pnorm{w-v}2 \leq 1$ implies $G(w) \leq \varepsilon$. \end{lemma} Claim \ref{claim:Gbound:implies:Fbound} and Lemma \ref{lemma:Hsurrogate} together imply that if gradient descent finds a point with auxiliary error $H(w_t) \leq O(\mathsf{OPT}^\alpha)$ for some $\alpha \leq 1$, then gradient descent achieves population risk $O(\mathsf{OPT}^\alpha)$. In the remainder of this section, we will show that this is indeed the case. In Section \ref{sec:strictly.increasing.activation}, we first consider activations satisfying Assumption \ref{assumption:activation.fcn}, for which we are able to show $H(w_t) \leq O(\mathsf{OPT})$. In Section \ref{sec:relu.activation}, we show $H(w_t)\leq O(\mathsf{OPT}^{1/2})$ for the ReLU. \subsection{Strictly increasing activations}\label{sec:strictly.increasing.activation} In Lemma \ref{lemma:agnostic.key.strictly.increasing} below, we show that $\hat H(w_t)$ is a natural quantity of the gradient descent algorithm that in a sense tells us how good a direction the gradient is pointing at time $t$, and that $\hat H(w_t)$ can be as small as $O(\hat F(v))$. Our proof technique is similar to that of~\citet{kakade2011}, who studied the GLMTron algorithm in the (non-agnostic) noisy teacher network setup. \begin{lemma}\label{lemma:agnostic.key.strictly.increasing} Suppose that $\pnorm{x}2 \leq B_X$ a.s. under $\mathcal{D}_x$. Suppose $\sigma$ satisfies Assumption \ref{assumption:activation.fcn}, and let $\gamma$ be the constant corresponding to $\rho=2B_X$. Assume $\hat F(v)>0$. Gradient descent with fixed step size $\eta \leq (1/8) \gamma L^{-3} B_X^{-2}$ initialized at $w_0=0$ finds weights $w_t$ satisfying $\hat H(w_t) \leq 6 L^3\gamma^{-2} \hat F(v)$ within $T = \ceil{ \eta^{-1} \gamma^{-1} L^{-1} B_X^{-1} \hat F(v)^{-1}}$ iterations, with $\pnorm {w_t-v}2 \leq 1$ for each $t=0, \dots, T-1$. \end{lemma} Before beginning the proof, we first note the following fact, which allows us to connect terms that appear in the gradient to the square loss. \begin{fact}\label{fact:sigma.strictly.increasing} If $\sigma$ is strictly increasing on an interval $[a,b]$ with $\sigma'(z) \geq \gamma>0$ for all $z\in [a,b]$, and if $z_1,z_2\in [a,b]$, then, it holds that \begin{equation} \gamma (z_1 - z_2)^2 \leq \l( \sigma(z_1 ) - \sigma(z_2) \r) (z_1 -z_2). \label{eq:lb.identity.zs} \end{equation}\end{fact} \begin{proof}[Proof of Lemma \ref{lemma:agnostic.key.strictly.increasing}] The proof comes from the following induction statement. We claim that for every $t\in \mathbb{N}$, either (a) $\hat H(w_\tau) \leq 6 L^3 \gamma^{-2} \hat F(v)$ for some $\tau < t$, or (b) $\pnorm{w_t-v}2^2 \leq \pnorm{w_{t-1}-v}2^2 - \eta L\hat F(v)$ holds. If this claim is true, then until gradient descent finds a point where $\hat H(w_t) \leq 6 L^3 \gamma^{-2} \hat F(v)$, the squared distance $\pnorm{w_t-v}2^2$ decreases by $\eta L \hat F(v)$ at every iteration. Since $\pnorm{w_0-v}2^2 = 1$, this means there can be at most $1/(\eta L\hat F(v)) = \eta^{-1} L^{-1} \hat F(v)^{-1}$ iterations until we reach $\hat H(w_t) \leq 6 L^3 \gamma^{-2} \hat F(v)$. So let us now suppose the induction hypothesis holds for $t$, and consider the case $t+1$. If (a) holds, then we are done. So now consider the case that for every $\tau \leq t$, we have $\hat H(w_\tau) > 6 L^3 \gamma^{-2} \hat F(v)$. Since (a) does not hold, $\pnorm{w_\tau -v}2^2 \leq \pnorm{w_{\tau-1}-v}2^2 - \eta L \hat F(v)$ holds for each $\tau=1, \dots, t$, and so $\pnorm{w_0-v}2=1$ implies \begin{equation} \pnorm{w_\tau - v}2 \leq 1\ \forall \tau \leq t. \label{eq:bounded.weights.agnostic} \end{equation} In particular, $\pnorm {w_\tau}2 \leq 1 + \pnorm{v}2 \leq 2$ holds for all $\tau\leq t$. By Cauchy--Schwarz, this implies $|w_\tau^\top x|\vee |v^\top x| \leq 2 B_X$ a.s. By defining $\rho = 2 B_X$ and letting $\gamma$ be the constant from Assumption \ref{assumption:activation.fcn}, this implies $\sigma'(z) \geq \gamma>0$ for all $|z|\leq 2 B_X$. Fact \ref{fact:sigma.strictly.increasing} therefore implies \begin{equation} \sigma'(w_\tau^\top x) \geq \gamma > 0 \quad \text { and } \quad (\sigma(w_\tau^\top x) - \sigma(v^\top x))\cdot(w_\tau^\top x - v^\top x) \geq \gamma (w_\tau^\top x- v^\top x)^2 \quad \forall \tau \leq t. \label{eq:lb.identity} \end{equation} We proceed with the proof by demonstrating an appropriate lower bound for the quantity \[ \pnorm{w_t-v}2^2 - \pnorm{w_{t+1}-v}2^2 = 2\eta \ip{\nabla \hat F(w_t)}{w_t-v} - \eta^2 \pnorm{\nabla \hat F(w_t)}2^2.\] We begin with the inner product term. We have \begin{align} \nonumber \big \langle \nabla \hat F(w_t) , w_t-v\big \rangle &= (1/n) \summ i n \l( \sigma(w_t^\top x_i) - \sigma(v^\top x_i) \r) \sigma'(w_t^\top x_i) (w_t^\top x_i - v^\top x_i) \\ \nonumber &\quad + (1/n) \summ i n \l( \sigma(v^\top x_i) - y_i \r) \gamma^{-1/2} \cdot \gamma^{1/2} \sigma'(w_t^\top x_i)(w_t^\top x_i -v^\top x_i)\\ \nonumber &\geq (\gamma/n) \summ i n \l( w_t^\top x_i - v^\top x_i \r)^2 \sigma'(w_t^\top x_i)\\ \nonumber &\quad - \frac {\gamma^{-1}}{2n} \summ i n \l( \sigma(v^\top x_i) - y_i\r)^2 \sigma'(w_t^\top x_i) - \frac \gamma {2n} \summ i n \l( w_t^\top x_i - v^\top x_i\r)^2 \sigma'(w_t^\top x_i)\\ \nonumber &\geq \frac \gamma 2 \summ i n (w_t^\top x_i-v^\top x_i)^2 \sigma'(w_t^\top x_i) - L \gamma^{-1} \hat F(v)\\ &\geq \gamma L^{-2} \hat H(w_t) - L \gamma^{-1} \hat F(v). \label{eq:ip.lb.strictly.increasing} \end{align} In the first inequality we used \eqref{eq:lb.identity} for the first term and Young's inequality for the second (and that $\sigma'\geq 0$). For the final two inequalities, we use that $\sigma$ is $L$-Lipschitz. For the gradient upper bound, \begin{align} \nonumber \norm{\nabla \hat F(w)}^2 &\leq 2 \norm{\frac 1n \summ i n (\sigma(w^\top x_i) - \sigma(v^\top x_i)) \sigma'(w^\top x_i) x_i}^2 \\ \nonumber &\quad + 2 \norm{\frac 1 n \summ i n (\sigma(v^\top x_i) - y_i) \sigma'(w^\top x_i) x_i}^2 \\ \nonumber &\leq \frac 2n \summ i n (\sigma(w^\top x_i) - \sigma(v^\top x_i))^2 \sigma'(w^\top x_i)^2 \pnorm{x_i}2^2 \\ \nonumber &\quad + \frac 2 n \summ i n (\sigma(v^\top x_i) - y_i)^2 \sigma'(w^\top x_i)^2 \pnorm{ x_i}2^2 \\ \nonumber &\leq \frac {2L B_X^2} n \summ i n (\sigma(w^\top x_i)- \sigma(v^\top x_i))^2\sigma'(w^\top x_i) + 4L^2 B_X^2 \hat F(v)\\ &= 4L B_X^2 \hat H(w) + 4L^2 B_X^2 \hat F(v). \label{eq:grad.ub.strictly.increasing} \end{align} The first inequality is due to Young's inequality, and the second is due to Jensen's inequality. The last inequality holds because $\sigma$ is $L$-Lipschitz and $\pnorm{x}2\leq B_X$ a.s. Putting \eqref{eq:ip.lb.strictly.increasing} and \eqref{eq:grad.ub.strictly.increasing} together and taking $\eta \leq (1/8) L^{-3} B_X^{-2} \gamma$, \begin{align*} \norm{w_t-v}^2 - \norm{w_{t+1}-v}^2 &\geq 2 \eta ( \gamma L^{-2} \hat H(w_t) - L\gamma^{-1} \hat F(v)) - 4\eta^2 (L B_X^2 \hat H(w_t) + L^2 B_X^2 \hat F(v))\\ &\geq 2 \eta \l( \frac {\gamma L^{-2}} 2 \hat H(w_t) - \frac 5 2 L \gamma^{-1} \hat F(v)\r)\\ &\geq \eta \gamma L \hat F(v). \end{align*} The last inequality uses the induction assumption that $\hat H(w_t) \geq 6 L^3 \gamma^{-2} \hat F(v)$, completing the proof. \end{proof} Since the auxiliary error $\hat H(w)$ is controlled by $\hat F(v)$, we need to bound $\hat F(v)$. When the marginals of $\mathcal{D}$ are bounded, Lemma \ref{lemma:F(v).opt.concentration} below shows that $\hat F(v)$ concentrates around $F(v)=\mathsf{OPT}$ at rate $n^{-1/2}$ by Hoeffding's inequality; for completeness, the proof is given in Appendix \ref{appendix:simple.proofs}. \begin{lemma}\label{lemma:F(v).opt.concentration} If $\pnorm{x}2 \leq B_X$ and $|y|\leq B_Y$ a.s. under $\mathcal{D}_x$ and $\mathcal{D}_y$ respectively, and if $\sigma$ is non-decreasing, then for $a := \l( |\sigma(B_X)| + B_Y\r)^2$ and $\pnorm{v}2\leq 1$, we have with probability at least $1-\delta$, \begin{align*} |\hat F(v) - \mathsf{OPT}| \leq 3a \sqrt{n^{-1} \log(2/\delta)}. \end{align*} \end{lemma} The final ingredient to the proof is translating the bounds for the empirical risk to one for the population risk. Since $\mathcal{D}_x$ is bounded and we showed in Lemma \ref{lemma:agnostic.key.strictly.increasing} that $\pnorm{w_t-v}2\leq 1$ throughout the gradient descent trajectory, we can use standard properties of Rademacher complexity to get it done. The proof for Lemma \ref{lemma:rademacher.complexity} can be found in Appendix \ref{appendix:simple.proofs}. \begin{lemma}\label{lemma:rademacher.complexity} Suppose $\sigma$ is $L$-Lipschitz and $\pnorm{x}2\leq B_X$ a.s. Denote $\ell(w; x) := (1/2) \l( \sigma(w^\top x) - \sigma(v^\top x)\r)^2$. For a training set $S\sim \mathcal{D}^n$, let $\mathfrak{R}_S(\mathcal{G})$ denote the empirical Rademacher complexity of the following function class \[ \mathcal{G} := \{ x\mapsto w^\top x : \pnorm{w-v}2\leq 1, \ \pnorm v 2 = 1 \}. \] Then we have \[ \mathfrak R(\ell \circ \sigma \circ \mathcal{G}) = \mathbb{E}_{S\sim \mathcal{D}^n} \mathfrak R_S(\ell \circ \sigma \circ \mathcal{G}) \leq 2L^3 B_X^2/\sqrt n.\] \end{lemma} With Lemmas \ref{lemma:agnostic.key.strictly.increasing}, \ref{lemma:F(v).opt.concentration} and \ref{lemma:rademacher.complexity} in hand, the bound for the population risk follows in a straightforward manner. \begin{proof}[Proof of Theorem \ref{theorem:agnostic} for strictly increasing activations.] By Lemma \ref{lemma:agnostic.key.strictly.increasing}, there exists some $w_t$ with $t<T$ and $\pnorm{w_t-v}2\leq 1$ such that $\hat H(w_t) \leq 6L^3 \gamma^{-2} \hat F(v)$. By Lemmas \ref{lemma:Hsurrogate} and Lemma \ref{lemma:F(v).opt.concentration}, this implies that with probability at least $1-\delta/2$, \begin{equation} \hat G(w_t) \leq 6 L^3 \gamma^{-3} \l( \mathsf{OPT} + 3a n^{-1/2} \log^{1/2}(4/\delta)\r).\label{eq:agnostic.nonrelu.hatG.bound} \end{equation} Since $\pnorm{w-v}2\leq 1$ implies $\ell(w; x) = (1/2)(\sigma(w^\top x) - \sigma(v^\top x))^2 \leq L^2 B_X^2/2$, standard results from Rademacher complexity (e.g., Theorem 26.5 of~\cite{shalevschwartz}) imply that with probability at least $1-\delta/2$, \[ G(w_t) \leq \hat G(w_t) + \mathbb{E}_{S\sim \mathcal{D}^n} \mathfrak{R}_S(\ell \circ \sigma \circ \mathcal{G}) + 2 L^2 B_X^2 \sqrt{\frac{ 2 \log(8/\delta)}{n}},\] where $\ell$ is the loss and $\mathcal{G}$ is the function class defined in Lemma \ref{lemma:rademacher.complexity}. We can combine \eqref{eq:agnostic.nonrelu.hatG.bound} with Lemma \ref{lemma:rademacher.complexity} and a union bound to get that with probability at least $1-\delta$, \[ G(w_t) \leq 6 L^3 \gamma^{-3} \l( \mathsf{OPT} + 3a\sqrt{\frac{ \log(4/\delta)}{n}}\r)+ \frac{ 2 L^3 B_X^2}{\sqrt n} + \frac{ 2L^2 B_X^2 \sqrt{2\log(8/\delta)}}{\sqrt n} .\] This shows that $G(w_t) \leq O(\mathsf{OPT} + n^{-1/2})$. By Claim \ref{claim:Gbound:implies:Fbound}, we have \[ F(w_t) \leq 2 G(w_t) + 2 \mathsf{OPT} \leq O(\mathsf{OPT} + n^{-1/2}),\] completing the proof for those $\sigma$ satisfying Assumption \ref{assumption:activation.fcn}.\end{proof} \subsection{ReLU activation}\label{sec:relu.activation} The proof above crucially relies upon the fact that $\sigma$ is strictly increasing so that we may apply Fact \ref{fact:sigma.strictly.increasing} in the proof of Lemma \ref{lemma:agnostic.key.strictly.increasing}. In particular, it is difficult to show a strong lower bound for the gradient direction term in \eqref{eq:ip.lb.strictly.increasing} if it is possible for $(z_1-z_2)^2$ to be arbitrarily large when $(\sigma(z_1)-\sigma(z_2))^2$ is small. To get around this, we will use the same proof technique wherein we show that the gradient lower bound involves a term that relates the auxiliary error $\hat H(w_t)$ to $\hat F(v)$, but our bound will involve a term of the form $O(\hat F(v)^{1/2})$ rather than $O(\hat F(v))$. To do so, we will use the following property of non-decreasing Lipschitz functions. \begin{fact}\label{fact:sigma.L.lipschitz} If $\sigma$ is non-decreasing and $L$-Lipschitz, then for any $z_1, z_2$ in the domain of $\sigma$, it holds that $(\sigma(z_1) - \sigma(z_2))(z_1 - z_2) \geq L^{-1}(\sigma(z_1)-\sigma(z_2))^2$. \end{fact} With this fact we can present the analogue to Lemma \ref{lemma:agnostic.key.strictly.increasing} that holds for a general non-decreasing and Lipschitz activation and hence includes the ReLU. \begin{lemma}\label{lemma:agnostic.key.relu} Suppose that $\pnorm{x}2 \leq B_X$ a.s. under $\mathcal{D}_x$. Suppose $\sigma$ is non-decreasing and $L$-Lipschitz. Assume $\hat F(v) \in (0,1)$. Gradient descent with fixed step size $\eta \leq (1/4) L^{-2} B_X^{-2}$ initialized at $w_0=0$ finds weights $w_t$ satisfying $\hat H(w_t) \leq 2 L^2 B_X \hat F(v)^{1/2}$ within $T = \ceil{\eta^{-1} L^{-1} B_X^{-1} \hat F(v)^{-1/2}}$ iterations, with $\pnorm {w_t-v}2 \leq 1$ for each $t=0, \dots, T-1$. \end{lemma} \begin{proof} Just as in the proof of Lemma \ref{lemma:agnostic.key.strictly.increasing}, the lemma is proved if we can show that for every $t\in \mathbb{N}$, either (a) $\hat H(w_\tau) \leq 2 L^2 B_X \hat F(v)^{1/2}$ for some $\tau < t$, or (b) $\pnorm{w_t-v}2^2 \leq \pnorm{w_{t-1}-v}2^2 - \eta LB_X \hat F(v)^{1/2}$ holds. To this end we assume the induction hypothesis holds for some $t\in \mathbb{N}$, and since we are done if (a) holds, we assume (a) does not hold and thus for every $\tau \leq t$, we have $\hat H(w_\tau) > 2 L^2 B_X\hat F(v)^{1/2}$. Since (a) does not hold, $\pnorm{w_\tau -v}2^2 \leq \pnorm{w_{\tau-1}-v}2^2 - \eta L B_X \hat F(v)^{1/2}$ holds for each $\tau=1, \dots, t$ and hence the identity \begin{equation} \pnorm{w_\tau - v}2 \leq 1 \quad \forall \tau \leq t, \label{eq:bounded.weights.agnostic.relu} \end{equation} holds. We now proceed with showing the analogues of \eqref{eq:ip.lb.strictly.increasing} and \eqref{eq:grad.ub.strictly.increasing}. We begin with the lower bound, \begin{align} \nonumber \big \langle \nabla \hat F(w_t) , w_t-v\big \rangle &= (1/n) \summ i n \l( \sigma(w_t^\top x_i) - \sigma(v^\top x_i) \r) \sigma'(w_t^\top x_i) (w_t^\top x_i - v^\top x_i) \\ \label{eq:agnostic.glm.key.difference} &\quad + \big \langle (1/n) \summ i n \l( \sigma(v^\top x_i) - y_i \r) \sigma'(w_t^\top x_i) x_i , w_t-v\big \rangle\\ \nonumber &\geq (1/Ln) \summ i n \l( \sigma(w_t^\top x_i) - \sigma(v^\top x_i) \r)^2 \sigma'(w_t^\top x_i)\\ \nonumber &\quad - \pnorm{w_t-v}2 \bigg \| (1/n) \summ i n \l( \sigma(v^\top x_i) - y_i \r) \sigma'(w_t^\top x_i) x_i \bigg\|_2 \\ &\geq 2 L^{-1} \hat H(w_t) - L B_X \hat F(v)^{1/2}. \label{eq:agnostic.glm.ip.lb} \end{align} In the first inequality, we have used Fact \ref{fact:sigma.L.lipschitz} and that $\sigma'(z) \geq 0$ for the first term. For the second term, we use Cauchy--Schwarz. The last inequality is a consequence of \eqref{eq:bounded.weights.agnostic.relu}, Cauchy--Schwarz, and that $\sigma'(z) \leq L$ and $\pnorm{x}2\leq B_X$. As for the gradient upper bound at $w_t$, the bound \eqref{eq:grad.ub.strictly.increasing} still holds since it only uses that $\sigma$ is $L$-Lipschitz. The choice of $\eta\leq (1/4) L^{-2} B_X^{-2}$ then ensures \begin{align} \nonumber \pnorm{w_t-v}2^2 - \pnorm{w_{t+1}-v}2^2 &\geq 2 \eta \l( 2 L^{-1} \hat H(w_t) - L B_X\hat F(v)^{1/2} \r) \\ \nonumber &\quad - \eta^2 \l( 4B_X^2 L \hat H(w_t) + 4L^2 B_X^2 \hat F(v)\r) \\ \nonumber &\geq \eta \l( 3L^{-1} \hat H(w_t) - 3 L B_X \l( \hat F(v) \vee \hat F(v)^{1/2} \r)\r)\\ &\geq \eta L B_X \hat F(v)^{1/2}, \end{align} where the last line comes from the induction hypothesis that $\hat H(w_t) \geq 2 L^2 B_X \hat F(v)^{1/2}$ and since $\hat F(v)\in (0,1)$. This completes the proof. \end{proof} With this lemma in hand, the proof of Theorem \ref{theorem:agnostic} follows just as in the strictly increasing case. \begin{proof}[Proof of Theorem \ref{theorem:agnostic} for ReLU] We highlight here the main technical differences with the proof for the strictly increasing case. Although Lemma \ref{lemma:rademacher.complexity} applies to the loss function $\ell(w; x) = (1/2) \l(\sigma(w^\top x) - \sigma(v^\top x)\r)^2$, the same results hold for the loss function $\tilde \ell(w; x) = \ell(w; x) \sigma'(w^\top x)$ for ReLU, since $\nabla \sigma'(w^\top x) \equiv 0$ a.e. Thus $\tilde \ell$ is still $B_X$-Lipschitz, and we have \begin{equation} \mathbb{E}_{S\sim \mathcal{D}^n} \mathfrak{R}_S \l( \tilde \ell \circ \sigma \circ \mathcal{G} \r) \leq \frac{ 2 B_X^2}{\sqrt n}. \label{eq:rademacher.relu} \end{equation} With this in hand, the proof is essentially identical: By Lemmas \ref{lemma:agnostic.key.relu} and \ref{lemma:F(v).opt.concentration}, with probability at least $1-\delta/2$ gradient descent finds a point with \begin{equation} \hat H(w_t) \leq 2 B_X \hat F(v)^{1/2} \leq 2 B_X \l( \mathsf{OPT}^{1/2} + \frac{ \sqrt {3a} \log^{1/4} (4/\delta)}{n^{1/4}}\r). \end{equation} We can then use \eqref{eq:rademacher.relu} to get that with probability at least $1-\delta$, \begin{equation} H(w_t) \leq 2 B_X \l( \mathsf{OPT}^{1/2} + \frac{ \sqrt {3a} \log^{1/4} (4/\delta)}{n^{1/4}}\r) + \frac{ 2B_X^2}{\sqrt n} + 2B_X^2 \sqrt{\frac{ 2\log(8/\delta)}n}. \end{equation} Since $\mathcal{D}_x$ satisfies Assumption \ref{assumption:marginal.spread} and $\pnorm{w_t-v}2\leq 1$, Lemma \ref{lemma:Hsurrogate} yields $G(w_t)\leq 8 \sqrt 2 \alpha^{-4} \beta^{-1} H(w_t)$. Then applying Claim \ref{claim:Gbound:implies:Fbound} completes the proof. \end{proof} \begin{remark} An examination of the proof of Theorem \ref{theorem:agnostic} shows that when $\sigma$ satisfies Assumption \ref{assumption:activation.fcn}, any initialization with $\pnorm{w_0-v}2$ bounded by a universal constant will suffice. In particular, if we use Gaussian initialization $w_0\sim N(0,\tau^2 I_d)$ for $\tau^2=O(1/d)$, then by concentration of the chi-square distribution the theorem holds with (exponentially) high probability over the random initialization. For ReLU, initialization at the origin greatly simplifies the proof since Lemma \ref{lemma:agnostic.key.relu} shows that $\pnorm{w_{t}-v}2\leq \pnorm{w_0-v}2$ for all $t$. When $w_0=0$, this implies $\pnorm{w_t-v}2\leq 1$ and allows for an easy application of Lemma \ref{lemma:Hsurrogate}. For isotropic Gaussian initialization, one can show that with probability approaching 1/2 that $\pnorm{w_0-v}2<1$ provided its variance satisfies $\tau^2 = O(1/d)$ (see e.g. Lemma 5.1 of~\citet{yehudai20}). In this case, the theorem will hold with constant probability over the random initialization. \end{remark} \section{Noisy teacher network setting} \label{sec:noisy} In this section, we consider the teacher network setting, where the joint distribution of $(x,y)\sim \mathcal{D}$ is given by a target neuron $v$ (with $\pnorm{v}2\leq 1$) plus zero-mean $s$-sub-Gaussian noise, \[ y | x \sim \sigma(v^\top x) + \xi,\quad \mathbb{E}\xi|x =0.\] We assume throughout this section that $\xi\not \equiv 0$; we deal with the realizable setting separately (and achieve improved sample complexity) in Appendix \ref{appendix:realizable}. We note that this is precisely the setup of the generalized linear model with (inverse) link function $\sigma$. We further note that we only assume that $\mathbb{E}[y|x] = \sigma(v^\top x)$, i.e., the noise is \textit{not} assumed to be independent of the input $x$, and thus falls into the probabilistic concept learning model of~\citet{kearns.probabilistic}. With the additional structural assumption of a noisy teacher, we can improve the agnostic result from $O(\mathsf{OPT})+\varepsilon$ (for strictly increasing activations) and $O(\mathsf{OPT}^{1/2})+\varepsilon$ (for ReLU) to $\mathsf{OPT}+\varepsilon$. The key difference from the proof in the agnostic setting is that when trying to show the gradient points in a good direction as in \eqref{eq:ip.lb.strictly.increasing} and \eqref{eq:agnostic.glm.key.difference}, since we know $\mathbb{E}[y|x] = \sigma(v^\top x)$, the average of terms of the form $a_i (\sigma(v^\top x_i) - y_i)$ with fixed and bounded coefficients $a_i$ will concentrate around zero. This allows us to improve the lower bound from $\langle\nabla \hat F(w_t), w_t-v\rangle \geq C( \hat H(w) - \hat F(v)^{\alpha})$ to one of the form $\geq C( \hat H(w) - \varepsilon)$, where $C$ is an absolute constant. The full proof of Theorem \ref{theorem:glm} is given in Appendix \ref{appendix:glm}. \begin{theorem}\label{theorem:glm} Suppose $\mathcal{D}_x$ satisfies $\pnorm{x}2\leq B_X$ a.s. and $\mathbb{E}[y | x] = \sigma(v^\top x)$ for some $\pnorm{v}2 \leq 1$. Assume that $\sigma(v^\top x) - y$ is $s$-sub-Gaussian. Assume gradient descent is initialized at $w_0=0$ and fix a step size $\eta \leq (1/4) L^{-2} B_X^{-2}$. If $\sigma$ satisfies Assumption \ref{assumption:activation.fcn}, let $\gamma$ be the constant corresponding to $\rho = 2B_X$. There exists an absolute constant $c_0>0$ such that for any $\delta >0$, with probability at least $1-\delta$, gradient descent for $T = \eta^{-1} \sqrt n / (c_0 LB_x s\sqrt{\log(4d/\delta)})$ iterations finds weights $w_t$, $t<T$, satisfying \begin{equation} F(w_t) \leq \mathsf{OPT} + C_1 n^{-1/2} + C_2 n^{-1/2} \sqrt{\log(8/\delta) }+ C_3 n^{-1/2}\sqrt{ \log(4d/\delta)}, \label{eq:glm.thm.bound} \end{equation} where $C_1 = 4 L^3 B_X^2$, $C_2 = 2\sqrt 2 L^2 B_X^2 \sqrt 2$, and $C_3 = 4 c_0 \gamma^{-1} L^2 sB_X$. When $\sigma$ is ReLU, further assume that $\mathcal{D}_x$ satisfies Assumption \ref{assumption:marginal.spread} for constants $\alpha, \beta>0$, and let $\nu = \alpha^{4}\beta/8\sqrt 2$. Then \eqref{eq:glm.thm.bound} holds for $C_1 = B_X^2\nu^{-1}$, $C_2 = 2C_1$, and $C_3 = 4 c_0 s \nu^{-1} B_X$. \end{theorem} We first note that although \eqref{eq:glm.thm.bound} contains a $\log(d)$ term, the dependence on the dimension can be removed if we assume that the noise is bounded rather than sub-Gaussian; details for this are given in Appendix \ref{appendix:glm}. As mentioned previously, if we are in the realizable setting, i.e. $\xi \equiv 0$, we can improve the sample and runtime complexities to $O(\varepsilon^{-1})$ by using online SGD and a martingale Bernstein bound. For details on the realizable case, see Appendix \ref{appendix:realizable}. In comparison with existing literature,~\citet{kakade2011} proposed GLMTron to show the learnability of the noisy teacher network for a non-decreasing and Lipschitz activation $\sigma$ when the noise is bounded.\footnote{A close inspection of the proof shows that sub-Gaussian noise can be handled with the same concentration of norm sub-Gaussian random vectors that we use for our results.} In GLMTron, updates take the form $w_{t+1} = w_t - \eta \tilde g_t$ where $\tilde g_t = ( \sigma(w_t^\top x) - y)x$, while in gradient descent, the updates take the form $w_{t+1} = w_t - \eta g_t$ where $g_t = \tilde g_t \sigma'(w_t^\top x)$. Intuitively, when the weights are in a bounded region and $\sigma$ is strictly increasing and Lipschitz, the derivative satisfies $\sigma'(w_t^\top x) \in [\gamma, L]$ and so the additional $\sigma'$ factor will not significantly affect the algorithm. For ReLU this is more complicated as the gradient could in the worst case be zero in a large region of the input space, preventing effective learnability using gradient-based optimization, as was demonstrated in the negative result of~\citet{yehudai20}. For this reason, a type of nondegeneracy condition like Assumption \ref{assumption:marginal.spread} is essential for gradient descent on ReLUs. In terms of other results for ReLU, recent work by~\citet{mukherjee} introduced another modified version of SGD, where updates now take the form $w_{t+1}=w_t - \eta \hat g_t$, with $\hat g_t = \tilde g_t \sigma'(y>\theta)$, and $\theta$ is an upper bound for an adversarial noise term. They showed that this modified SGD recovers the parameter $v$ of the teacher network under the nondegeneracy condition that the matrix $\mathbb{E}_x [ xx^\top {\mathbbm{1}}(v^\top x\geq 0)]$ is positive definite. A similar assumption was used by~\citet{du2017} in the realizable setting. Our GLM result is also comparable to recent work by~\citet{foster2018}, where the authors provide a meta-algorithm for translating guarantees for $\varepsilon$-stationary points of the empirical risk to guarantees for the population risk provided that the population risk satisfies the so-called ``gradient domination'' condition and the algorithm can guarantee that the weights remain bounded (see their Proposition 3). By considering GLMs with bounded, strictly increasing, Lipschitz activations, they show the gradient domination condition holds, and any algorithm that can find a stationary point of an $\ell^2$-regularized empirical risk objective is guaranteed to have a population risk bound. In contrast, our result concretely shows that vanilla gradient descent learns the GLM, even in the ReLU setting. \section{Conclusion and remaining open problems} In this work, we considered the problem of learning a single neuron with the squared loss by using gradient descent on the empirical risk. We first analyzed this in the agnostic PAC learning framework and showed that if the activation function is strictly increasing and Lipschitz, then gradient descent finds weights with population risk $O(\mathsf{OPT}) + \varepsilon$, where $\mathsf{OPT}$ is the smallest possible population risk achieved by a single neuron. When the activation function is ReLU, we showed that gradient descent finds a point with population risk at most $O(\mathsf{OPT}^{1/2})+\varepsilon$. Under the more restricted noisy teacher network setting, we showed the population risk guarantees improve to $\mathsf{OPT}+\varepsilon$ for both strictly increasing activations and ReLU. Our work points towards a number of open problems. Does gradient descent on the empirical risk provably achieve population risk with a better dependence on $\mathsf{OPT}$ than we have shown in this work, or are there distributions for which this is impossible? Recent work by~\citet{goel2020sqlowerbounds} provides a statistical query lower bound for learning a sigmoid with respect to the correlation loss $\mathbb{E}[\ell(y \sigma(w^\top x))]$, but we are not aware of lower bounds for learning non-ReLU single neurons under the squared loss. It thus remains a possibility that gradient descent (or another algorithm) can achieve $\mathsf{OPT}+\varepsilon$ risk for such activation functions. For ReLU,~\cite{diakonikolas2020approximation} showed that gradient descent on a convex surrogate for the empirical risk can achieve $O(\mathsf{OPT}) + \varepsilon$ population risk for log concave distributions; it would be interesting if such bounds could be shown for gradient descent on the empirical risk itself \section*{Acknowledgement} We thank Adam Klivans for his helpful comments on our work. We also thank Surbhi Goel for pointing out how to extend the results of~\citet{diakonikolas2020approximation} to more general distributions and to leaky-ReLU-type activation functions.
{'timestamp': '2020-09-01T02:36:50', 'yymm': '2005', 'arxiv_id': '2005.14426', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14426'}
arxiv
\section*{Robot HSR Hardware Description} \section*{Appendix 1: Competition results} \begin{table}[t] \begin{center} \caption{Results of recent competitions. [DSPL, domestic standard-platform league; JSAI, Japanese Society for Artificial Intelligence; METI, Ministry of Economy, Trade and Industry (Japan); OPL, open-platform league; RSJ, Robotics Society of Japan]} \label{tab:result} \begin{tabular}{l|l|l} \hline \multicolumn{1}{c|}{Country} & \multicolumn{1}{c|}{Competition} & \multicolumn{1}{c}{Result} \\ \hline \hline Japan & RoboCup 2017 Nagoya & {\bf @Home DSPL 1st} \\ && @Home OPL 5th \\ \hline Japan & RoboCup Japan Open 2018 Ogaki & @Home DSPL 2nd \\ && @Home OPL 1st \\ && JSAI Award \\ \hline Canada & RoboCup 2018 Montreal & {\bf @Home DSPL 1st} \\ && P\&G Dishwasher Challenge Award \\ \hline Japan & World Robot Challenge 2018 & {\bf Service Robotics Category} \\ && {\bf Partner Robot Challenge Real Space 1st} \\ && METI Minister's Award, RSJ Special Award \\ \hline Australia & RoboCup 2019 Sydney & @Home DSPL 3rd \\ \hline Japan & RoboCup Japan Open 2019 Nagaoka & @Home DSPL 1st \\ && @Home OPL 1st \\ \hline \end{tabular} \end{center} \end{table} Table \ref{tab:result} shows the results achieved by our team in recent competitions. We have participated in the RoboCup and World Robot Challenge for several years, and as a result, our team has won prizes and academic awards. \par Notably, we participated in the RoboCup 2019 Sydney using the system described herein. We were able to demonstrate the performance of HSR and our technologies. Thanks to these results, we were awarded the third prize in that competition. \section*{Appendix 2: Link to Team Video, Team Website} \begin{itemize} \item Team Video \\ \url{https://www.youtube.com/watch?v=0loNuukvOec} \\ \item Team Website \\ \url{http://www.brain.kyutech.ac.jp/~hma/wordpress/} \\ \item GitHub \\ \url{https://github.com/hibikino-musashi-athome} \\ \item Facebook \\ \url{https://www.facebook.com/HibikinoMusashiAthome/} \\ \item YouTube \\ \url{https://www.youtube.com/channel/UCJEeZZiDXijz6PidLiOtvwQ} \end{itemize} \section*{Appendix 3: Robot's Software Description} For our robot we are using the following software: \begin{itemize} \item OS: Ubuntu 16.04. \item Middleware: ROS Kinetic. \item State management: SMACH (ROS). \item Speech recognition (English): \begin{itemize} \item rospeex \cite{rospeex}. \item Web Speech API. \item Kaldi. \end{itemize} \item Morphological Analysis Dependency Structure Analysis (English): SyntaxNet. \item Speech synthesis (English): Web Speech API. \item Speech recognition (Japanese): Julius. \item Morphological Analysis (Japanese): MeCab. \item Dependency structure analysis (Japanese): CaboCha. \item Speech synthesis (Japanese): Open JTalk. \item Sound location: HARK. \item Object detection: point cloud library (PCL) and you only look once (YOLO) \cite{redmon2016you}. \item Object recognition: YOLO. \item Human detection / tracking: \begin{itemize} \item Depth image + particle filter. \item OpenPose \cite{cao2017realtime}. \end{itemize} \item Face detection: Convolutional Neural Network. \item SLAM: hector\_slam (ROS). \item Path planning: move\_base (ROS). \end{itemize} \section{Introduction} Our team, Hibikino-Musashi@Home (HMA), was founded in 2010, and we have been competing annually in the RoboCup@Home Japan Open competition in the open platform league (OPL). Our team is developing a home-service robot, and we intend to demonstrate our robot in this event in 2020 to present the outcome of our latest research. In RoboCup 2017 Nagoya, we participated both in the OPL and the domestic standard platform league (DSPL) and in the RoboCup 2018 Montreal and RoboCup 2019 Sydney we participated in the DSPL. Additionally, in the World Robot Challenge (WRC) 2018, we participated in the service-robotics category of the partner-robot challenge (real space). In the RoboCup 2017, 2018 and 2019 competitions and in the WRC 2018, we used a Toyota human support robot (HSR) \cite{toyota_hsr}. We were awarded the first prize at the WRC 2018 and third prize at the RoboCup 2019. In this paper, we describe the technologies used in our robot. In particular, this paper outlines our object recognition system that uses deep learning \cite{hinton2006fast}, improves the speed of HSR, and has a brain-inspired artificial intelligence model, which was originally proposed by us and is installed in our HSR. \section{System overview} Figure \ref{fig:softOverview} presents an overview of our HSR system. We have used an HSR since 2016. In this section, we will introduce the specifications of our HSR. \subsection{Hardware overview} We participated in RoboCup 2018 Montreal and 2019 Sydney with this HSR. The computational resources built into the HSR were inadequate to support our intelligent systems and were unable to extract the maximum performance from the system. To overcome this limitation, using an Official Standard Laptop for DSPL that can fulfill the computational requirements of our intelligent systems has been permitted since RoboCup 2018 Montreal. We use an ALIENWARE (Intel Core i7-8700K CPU, 32GB RAM, and GTX-1080 GPU) as the Official Standard Laptop for DSPL. Consequently, the computer equipped inside the HSR can be used to run basic HSR software, such as sensor drivers, motion planning and, actuator drivers. This has increased the operational stability of the HSR. \subsection{Software overview} \begin{figure}[bt] \begin{center} \includegraphics[scale=0.5]{systemblock.png} \caption{Block diagram overview of our HSR system. [HSR, human-support robot; ROS, robot operating system]} \label{fig:softOverview} \end{center} \end{figure} In this section, we introduce the software installed in our HSR. Figure \ref{fig:softOverview} shows the system installed in our HSR. The system is based on the Robot Operating System \cite{ros}. In our HSR system, laptop computer and a cloud service, if a network connection is available, are used for system processing. The laptop is connected to a computer through an Hsrb interface. The built-in computer specializes in low-layer systems, such as HSR sensor drivers, motion planning, and actuator drivers, as shown in Fig. \ref{fig:softOverview} (c) and (d). Furthermore, the built-in computer has a sound localization system that use HARK \cite{hark}, as shown in Fig. \ref{fig:softOverview} (e). \section{Object recognition} In this section, we explain the object recognition system (shown in Fig. \ref{fig:softOverview} (a)), which is based on you look only once (YOLO) \cite{redmon2016you}. To train YOLO, a complex annotation phase is required for annotating labels and bounding boxes of objects. In the RoboCup@Home competition, predefined objects are typically announced during the setup days right before the start of the competition days. Thus, we have limited time to train YOLO during the competition, and the annotation phase impedes the use of the trained YOLO during the competition days. We utilize an autonomous annotation system for YOLO using a three-dimensional (3D) scanner. Figure \ref{fig:annotation1} shows an overview of the proposed system. \begin{figure}[b] \begin{center} \includegraphics[scale=0.5]{annotation1.png} \caption{Overview of proposed autonomous annotation system for YOLO.} \label{fig:annotation1} \end{center} \end{figure} In this system, QLONE \cite{qlone}, a smartphone application capable of 3D scanning, is used. QLONE makes it easy to create 3D models by placing objects on dedicated markers and shooting them. We placed the marker and object on a turntable and created a 3D model. In this method, the bottom surface of the object could not be shoot; thus, two 3D models can be created for each object by acquiring the flipped upside-down object. Figure \ref{fig:annotation2} shows the processing flow to generate training images for YOLO. \begin{figure}[tb] \begin{center} \includegraphics[scale=0.5]{annotation2.png} \caption{Processing flow for generating training images for YOLO.} \label{fig:annotation2} \end{center} \end{figure} Multi-viewpoint images are automatically generated from the created two 3D models (Fig. \ref{fig:annotation2} (a)). Then, we remove image backgrounds (Fig. \ref{fig:annotation2} (b)). For backgrounds of the training images, we shoot background images, for example, a table, shelf, and other items. To adapt to various lighting conditions, we apply the automatic color equation algorithm \cite{RIZZI20031663} to the background images (Fig. \ref{fig:annotation2} (c)). To incorporate the object images into the background images, we define 20-25 object locations on the background images (the number of object locations depends on the background images). Then, by placing the object images on the defined object locations autonomously, the training images for YOLO are generated (Fig. \ref{fig:annotation2} (d)). If there are 15 class objects and 306 background images, 400,000 training images are generated. Additionally, annotation data for the training images are generated autonomously because object labels and positions are known. Image generation requires ~15 min (using six CPU cores in parallel), and training of YOLO requires approximately 6 h when using the GTX1080 GPU on a standard laptop. Even though the generated training data are artificial, recognition of YOLO in actual environments works. The accuracy when learning 10,000 epochs is 60.72\% in a mean average precision (mAP) evaluation. \section{High-speed behavioral synthesis} We are working to improve the speed of HSR from two viewpoints: behavioral synthesis and software processing speed. Regarding behavioral synthesis, we reduce the wasted motion by combining and synthesizing several behaviors for the robot. For instance, by moving each joint of the arm during navigation, the robot can move to the next action such as grasping without wasting any time as soon as the robot reaches an interim target location. Regarding the processing speed, we aim to operate all software at 30 Hz or higher. To reduce the waiting time for software processing, which causes the robot to stop, the essential functions of the home service robot, such as object recognition and object grasping-point estimation, need to be executed in real time. We optimized these functions for the Tidy Up Here task. We used two optimized methods for that task in the WRC 2018 (Fig. \ref{fig:synthesis}). In the WRC 2018 results, for which we won first place, our achieved speedup was approximately 2.6 times the prior record. Our robot can tidy up within 34 s per object; thus, so we expect that it can tidy up approximately 20 objects in 15 min. \begin{figure}[bt] \begin{center} \includegraphics[scale=0.65]{synthesis.jpg} \caption{Speed comparison between a conventional system and the proposed high-speed system.} \label{fig:synthesis} \end{center} \end{figure} \section{Brain-inspired artificial intelligence model} In this section, we explain a brain-inspired artificial intelligence model that consists of a visual cortex model, an amygdala model, a hippocampus model, and a prefrontal cortex model \cite{tanaka2019biai}. It is expected that home service robots have local knowledge which is based on the experiences of the robots. In the case of acquiring local knowledge, its learning is executed during the daily life of the robots. Thus, applying only deep learning \cite{hinton2006fast} to acquire local knowledge is not effective because the robot cannot prepare big data of the local knowledge. To acquire local knowledge, we propose an artificial intelligence model that is inspired by the structure of the brain because our brain can acquire local knowledge from only few data. Mainly, we focus on an amygdala, a hippocampus, and a prefrontal cortex, and the proposed model integrates functions of these parts of the brain. In addition, we integrated a deep neural network as a visual cortex model into the proposed model. Figure \ref{fig:biai1} shows the proposed model. \begin{figure}[tb] \begin{center} \includegraphics[scale=0.4]{biai1.png} \caption{A brain-inspired artificial intelligence model that consists of a visual cortex model, an amygdala model, a hippocampus model, and a prefrontal cortex model.} \label{fig:biai1} \end{center} \end{figure} The visual cortex model consists of YOLO and a Point Cloud Library (PCL) \cite{rusu2011pcl}. The visual cortex model recognizes an environment and outputs the label of detected object and its position. The object label is input into the amygdala model. We use the amygdala model for value judgments. The amygdala model consists of a lateral nucleus (LA) model and a central nucleus (CE) model \cite{tanaka2019amygdala}. The LA and the CE judge the value of the object. Only if the value of the object is high enough, the object label and the object position are input into the hippocampus model. We use the hippocampus model for event coding. The hippocampus model consists of cue cells, time cells and social place cells as an internal model of detected events. The cue cells and time cells represent what and when events happen, respectively. The social place cells represent where events happen. The cue cells receive the object label and the social place cell receives the object position. Then, the hippocampus model integrates the outputs of these cells and computes an event vector. The event vector is input into the prefrontal cortex model. We use the prefrontal cortex model for event predictions. The prefrontal cortex model is an echo state network (ESN) \cite{jaeger2001echostate}. The ESN trains the time-series event vector to predict future events. After training, the ESN predicts time-series events without input from environments. We evaluated the proposed model using the following experiment. A person walked across in front of a robot, as shown in Fig. \ref{fig:biai2}. The robot detected the person and learned the trajectory of the person which was a type of local knowledge. Subsequently, the robot predicted the trajectory. In addition, the robot added the predicted trajectory as an imaginary potential of a map for SLAM. Figure \ref{fig:biai3} shows the imaginary potential of the predicted trajectory. By using the imaginal potential, the robot was able to avoid the person who walked across in front of the robot. Therefore, the proposed model acquired the local knowledge. \begin{figure}[tb] \begin{center} \includegraphics[scale=0.7]{biai2.png} \caption{Trajectory of a person.} \label{fig:biai2} \end{center} \end{figure} \begin{figure}[tb] \begin{center} \includegraphics[scale=0.7]{biai3.png} \caption{Imaginary potential of the predicted trajectory.} \label{fig:biai3} \end{center} \end{figure} \vspace{-0.3cm} \section{Conclusions} In this paper, we summarized the available information about our HSR, which we entered into RoboCup 2019 Sydney. The object recognition and improved speed of the HSR that we built into the robot were also described. Currently, we are developing many different pieces of software for an HSR that will be entered into RoboCup 2020 Bordeaux. \vspace{-0.3cm} \section*{Acknowledgment} This work was supported by Ministry of Education, Culture, Sports, Science and Technology, Joint Graduate School Intelligent Car \& Robotics course (2012-2017), Kitakyushu Foundation for the Advancement of Industry Science and Technology (2013-2015), Kyushu Institute of Technology 100th anniversary commemoration project : student project (2015, 2018-2019) and YASKAWA electric corporation project (2016-2017), JSPS KAKENHI grant number 17H01798 and 19J11524, and the New Energy and Industrial Technology Development Organization (NEDO). \newpage
{'timestamp': '2020-06-01T02:08:46', 'yymm': '2005', 'arxiv_id': '2005.14451', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14451'}
arxiv
\section{Introducntion} The present COVID-19 pandemic is a dynamic and volatile process with often unpredictable ups and downs in the infected populations that make it difficult to predict its future course. In the absence of any vaccine or definitive drug in the immediate future \cite{Chen2020} the fight against COVID-19 is a hard and long drawn bitter battle, with two strategies being put forward. The first is the widely enforced lockdown, quarantine, and social distancing where the spread of the disease is contained at its inception and only a limited fraction of population is allowed to be infected.\cite{Prem2020} This model appears to be successful in South Korea and China, and some other Asian countries.\cite{Shen2020} The other model is to allow the virus to have a relatively unconstrained transmission so that a large fraction of the people develops the immunity.\cite{Kamikubo2020} This is called the herd immunity (HI) that is favoured by Sweden, and was initially discussed by Germany and England, but largely discarded later. HI can be achieved by two ways- (i) by vaccination, and (ii) by infection. The HI approach is based on the understanding that one can obtain the herd immunity in the society if 60-70\% of the population gets immunized. Needless to say this herd immunity is preferable through vaccination as happened in small pox and measles. Implementation of both the models has difficulties. Implementation of lockdown and social distancing requires enormous effort, backed up by resources. On the other hand, the HI model could have adverse consequence on the vulnerable citizens, a subject not adequately discussed. In fact, experiences in Italy and Spain show that the demography can be altered in some regions if HI is given an unconstrained run. Herd immunity ensures an indirect protection from COVID-19 (or any other infectious disease) when a large fraction of the population becomes immunized to the disease.\cite{Fine1993,Anderson1985,John2000} Herd immunity drastically decreases the probability of the presence of an uninfected individual in the vicinity of a presently infected individual. That is, the infected person is effectively quarantined by the surrounding immunized population. Hence, the chain of propagation breaks. In Fig. \ref{fig1} we pictorially explain the phenomenon of herd immunity. \begin{figure}[H] \centering \includegraphics[width=3.2in,keepaspectratio=true]{Figures/fig1.jpg} \caption{A pictorial representation of the herd immunity phenomenon. In the left we have a region with the susceptible population and one infected person. The total susceptibles are further divided into vulnerables and resilients. The infection propagates in an unconstrained manner and after a certain period the region possesses a large fraction of immunized population (right). After this immunisation any further infection cannot propagate and indirectly protects the susceptibles. In addition to that, multiple infected persons cannot do further harm. The colour codes are maintained throughout this paper.} \label{fig1} \end{figure} This can happen by providing the population with a vaccine or by getting cured after being infected. In the case of COVID-19 pandemic, as of now, we are unsure regarding the success of a vaccine and the latter is the only option to attain HI. However, the herd immunity threshold (HIT), that is the minimum fraction of population needs to get immunized in order to eradicate the disease, is different for different infectious diseases.\cite{Georgette2009,McBryde2009} For example, HIT for measles is ~92-95\% and for that of SARS-1 it is in the range of 50-80\%. Researchers around the world are exploring mainly two aspects of this disease- (i) the microscopic and clinical aspects which would eventually lead to drug discovery and vaccine preparation,\cite{Chen2020,Wrapp2020} (ii) the demographic aspects which lead to policy making and timeline prediction.\cite{Prem2020,Shen2020,Singh2020,Mukherjee2020} The latter requires effective mathematical modelling and crowd simulations. However, these models fail to predict the real scenario because of some inherent assumptions and limitations. Although a lot of interesting new studies are emerging in both categories in the context of the recent coronavirus pandemic, the issue of herd immunity and its fatality are not studied. There are several mathematical models which have been employed in the context of epidemic modelling, for example, the famous Kermack-McKendrick (KM) model which has been used extensively to study the spread of infectious diseases like measles, small pox etc.\cite{Daley2001,Kermack1927} At the core of this model lies a system of three coupled differential equations for susceptible (S), infected (I) and removed (R) (cured and dead) populations, that is, the famous SIR model (Eq. \ref{eq1}).\cite{Skvortsov2007,Jones2009,Anderson1979} At the onset of an epidemic S becomes I and I eventually becomes R, but R can never become S or I because of acquired immunity. \begin{equation} \begin{split} \frac{dS}{dt}& =-k_{S\rightarrow I}SI\\ \frac{dI}{dt}& =k_{S\rightarrow I}SI-k_{I\rightarrow R}I\\ \frac{dR}{dt}& =k_{I\rightarrow R}I \end{split} \label{eq1} \end{equation} Eq. \ref{eq1} describes the three coupled non-linear differential equations of the KM model where $k_{S\rightarrow I}$ is the rate of infection and $k_{I\rightarrow R}$ is the rate of removal (recovery and death). In the conventional SIR model $k_{S\rightarrow I}$ and $k_{I\rightarrow R}$ are written as $\alpha$ and $\beta$ respectively. In principle the rate constants should be time and space dependent, that is, non-local in nature. But it is difficult to predict the functional form of the rate constants with time- it could be periodic, decaying or stochastic in nature. The applicability of this model is for a homogeneous population distribution and mass transmission at a large scale.\cite{Daley2001} An important quantity is the basic reproduction number ($R_0$) which is an estimate of the number of secondary infection from one primary infection.\cite{Dietz1993} The value of $R_0$ is intimately connected with the herd immunity threshold ($H_t$) discussed above.\cite{McBryde2009,Diekmann1995} (Eq. \ref{eq2}) Hence a correct determination of the basic reproduction parameter, $R_0$, is important. \begin{equation} H_t=\left(1-\frac{1}{R_0}\right)\times 100 \% \label{eq2} \end{equation} It is clear from Eq. \ref{eq2} that a higher value of $R_0$ increases the herd immunity threshold. For SARS-Cov2 the value of $R_0$ shows a large dispersion and as a consequence we cannot predict the value of $H_t$. For COVID-19 the average value of $R_0$ is estimated to be in the range of $\sim$2.0-3.0 but it can possess spatial heterogeneity and time dependence in reality.\cite{Zhang2020,Tang2020} If one considers $R_0$ to be in the range of 2.0-3.0 the value of $H_t$ would be in between 50\%-66\%. In the light of SIR model [Eq.(1)] $R_0$ can be defined as \begin{equation} R_0=\frac{k_{S\rightarrow I}}{k_{I\rightarrow R}} S \label{eq3} \end{equation} Eq. \ref{eq3} provides a different definition of $R_0$ and can be understood as follows. If we assume that (the S the fraction of susceptible population) is near 1.0 at the beginning (as there are very few infections compared to a huge population), then $R_0$ could be equal to unity if the two rate constants are equal. This means that the number of infection and recovery are same at any time. In this situation the disease remains under control. $R_0 > 1$ causes an epidemic as it challenges the capacity of the healthcare facilities. However, for different region the value of $R_0$ could be different depending on the intensity of region wise preventive and healthcare measures. In this work we ask the following questions- (i) what are the relative magnitude of the fatality to the vulnerable and resilient populations if we attempt to achieve HI without a vaccine? (ii) What is the dependence of the fraction of survival on the rate of the attainment of HI? These two issues are widely discussed all over the world. Here we seek answers to these two important questions by employing a modified Susceptible-Infected-Removed (SIR) model and cellular automata (CA) simulations. The rest of the paper is organised as follows. In section \ref{sec2} we describe the mathematical model and the CA simulation protocols. Section \ref{sec3} consists of the results from numerical solutions of the modified SIR model and simulations, accompanied by detailed discussions. This section is further divided into several sub sections. In section IV we summarize and conclude our study. \section{Theoretical Formalism} \label{sec2} \subsection{Mathematical Modelling} We modify the celebrated SIR (Susceptible-Infected-Removed) model by dividing the entire susceptible population into two parts, namely vulnerable (Vul) and resilient (Res). In the context of the corona virus disease, the vulnerable category consists of persons who are above 60 years of age or have pre-existing medical conditions like diabetes, heart and kidney disease, and lung conditions.\cite{Yang2020} The rest of the population is termed as resilient who have a greater chance of getting cured. We achieve such classification by employing different rate constants associated with their recovery. This is based on the available data on the coronavirus disease. The scheme of this classification is described in Fig. \ref{fig2}. \begin{figure}[ht] \centering \includegraphics[width=3in,keepaspectratio=true]{Figures/fig2.jpg} \caption{Schematic representation of the modified SIR network model. Here the susceptible (S) population is divided into $S_V$ and $S_R$ that represent elderly and younger people respectively. A part of the fraction $S_V$ gets infected and creates $I_O$ fraction of infected population. A part of the remaining fraction of the population, that is, $S_R$ gets infected and creates $I_R$ fraction of the infected population. Both $I_V$ and $I_R$ get either cured (C) or dead (D). Naturally the rate of recovery for the younger fraction of the population is more than that of the older infected population. On the other hand, the rate of death for the older population is more than that of the younger invectives.} \label{fig2} \end{figure} We follow the scheme described in Fig. \ref{fig2} and formulate a system of eight coupled non-linear differential equations [Eqs. \ref{eq4} - \ref{eq11}]. \begin{equation} \frac{dS_{Vul}(t)}{dt} = -k_{S_{Vul}\rightarrow I_{Vul}}(t)S_{Vul}(t)I(t) \label{eq4} \end{equation} \begin{equation} \frac{dS_{Res}(t)}{dt} = -k_{S_{Res}\rightarrow I_{Res}}(t)S_{Res}(t)I(t) \label{eq5} \end{equation} \begin{equation} \begin{split} \frac{dI_{Vul}(t)}{dt} = k_{S_{Vul}\rightarrow I_{Vul}}(t)S_{Vul}(t)I(t)\\ -(k_{I_{Vul}\rightarrow C_{Vul}}(t)+k_{I_{Vul}\rightarrow D_{Vul}}(t))I_{Vul}(t) \end{split} \label{eq6} \end{equation} \begin{equation} \begin{split} \frac{dI_{Res}(t)}{dt} = k_{S_{Res}\rightarrow I_{Res}}(t)S_{Res}(t)I(t)\\ -(k_{I_{Res}\rightarrow C_{Res}}(t)+k_{I_{Res}\rightarrow D_{Res}}(t))I_{Res}(t) \end{split} \label{eq7} \end{equation} \begin{equation} \frac{dC_{Vul}(t)}{dt} = k_{I_{Vul}\rightarrow C_{Vul}}(t)I_{Vul}(t) \label{eq8} \end{equation} \begin{equation} \frac{dC_{Res}(t)}{dt} = k_{I_{Res}\rightarrow C_{Res}}(t)I_{Res}(t) \label{eq9} \end{equation} \begin{equation} \frac{dD_{Vul}(t)}{dt} = k_{I_{Vul}\rightarrow D_{Vul}}(t)I_{Vul}(t) \label{eq10} \end{equation} \begin{equation} \frac{dD_{Res}(t)}{dt} = k_{I_{Res}\rightarrow D_{Res}}(t)I_{Res}(t) \label{eq11} \end{equation} In the following, we explain the complex set of equations. Here I(t) is the number of total infectives at any time t, that is $I(t)=I_{Vul}(t)+I_{Res}(t)$. This is the variable that couples the two population sub-categories. $k(t)$ are the rate constants associated with processes that are described in the subscript with an arrow. We would like to point out that the rates in above equations of motion are all assumed to be time dependent. These rate constants contain all the basic information and also connected with $R_0$. In our earlier study, we employed a time dependent rate to produce certain features observed in the time dependence of new cases such a double peaked population structure.\cite{Mukherjee2020} The time dependence of rate can be employed to include certain dynamical features like crossover from local contact to community transmission. It is worth stressing that the modelling of these time dependent rate constants plays a pivotal role in the SIR scheme. We propagate these equations numerically to obtain the respective temporal evolution of each kind of population fraction. From the temporal profiles we can extract several important quantities after a long time (that is, the end of the spread), for example, (i) the peak height of the active infected cases, (ii) the fraction of cured population, (iii) the fraction of dead population, (iv) the fraction of uninfected population, (v) time required to reach the immunity threshold etc. We can regard these equations together to form a system of reacting species, as in a system of chemical reactions. We solve these equations with two different sets of the rate constant values and aim to understand the relative damages to the vulnerable and resilient population. The values of rate constants are provided in Table \ref{tab1}. We keep $k_{S_{Vul}\rightarrow I_{Vul}}$ and $k_{S_{Res}\rightarrow I_{Res}}$ the same which depicts the same probability of getting infected for both the sub-categories. However, the rate constants associated with recovery and death differs in orders of magnitude between Vul and Res. We now discuss the procedure we follow to assign different rate constants to the vulnerables and resilients. In a previous study we estimated the values of $k_{S\rightarrow I}$ and $k_{I\rightarrow R}$ by fitting the infected/cured/death vs. time data for India (source: www.covid19india.org).\cite{Mukherjee2020} We plot the rate of change of the cured ($dC/dt$) and dead ($dD/dt$) population against the infected population to find the slope that gives the rate. This procedure provides us with required estimates of $k_{I\rightarrow C}$ and $k_{I\rightarrow D}$. For India, till $27^{th}$ May, the estimated values are $k_{I\rightarrow C} = 0.026 \:day^{-1}$ and $k_{I\rightarrow D} = 0.0013 \:day^{-1}$. That is, $k_{I\rightarrow C}$ is approximately 20 times of $k_{I\rightarrow D}$. However, for countries like Italy, Spain, and USA $k_{I\rightarrow D}$ was significantly higher. This comparison however takes no cognition of the relative time scales, and therefore should be taken with care. These values are mean field in nature and contain enormous spatial heterogeneity. If we see the state wise (or district wise) statistics we find a large dispersion. On the other hand, the determination of $k_{S\rightarrow I}$ is not that straight forward as the equations containing $k_{S\rightarrow I}$ are non-linear in nature in the SIR model. Hence one needs to obtain a good estimate of $R_0$ and calculate $k_{S\rightarrow I}$ from Eq. \ref{eq3}. As mentioned above, $R_0$ also exhibits spatiotemporal heterogeneity which makes the problem of estimating the rate constants even more challenging. For example, in Italy $R_0$ has been estimated to be $\sim$3.0-6.0 and in the Hunan province of China it is $\sim$1.73-5.25.\cite{Wangping2020} In a recent study on Wuhan, the transmission rate ($k_{S\rightarrow I}$) is assumed to vary from 0.59 to $1.68 \:day^{-1}$.\cite{Lin2020} However, the data required to extract the rate constants associated with the two individual sub-categories, namely, vulnerable and resilient, are not available separately. As the values of the rate constants are connected to the basic reproduction number ($R_0$), we choose the inputs, by preserving the basic features, such that the average value of $R_0$ yields an acceptable number, in light of acquired information. Next we tune the parameters such that the maximum of the active cases falls in the range of $\sim$60-90 days, as observed for most countries. We note that we consider these values only to study the trends and do not strictly correspond to any particular region in reality. \begin{table}[ht] \caption{The values of rate constants used to solve the system of coupled differential equations [Eq.\ref{eq4} - \ref{eq11}]. The unit of the rate constants is $day^{-1}$.} \centering \begin{tabular}{|c|c|c|} \hline Rate Const. & Set-1 & Set-2\\ \hline \hline $k_{S_{Vul}\rightarrow I_{Vul}}$ & 0.50 & 0.78\\ \hline $k_{I_{Vul}\rightarrow C_{Vul}}$ & 0.05 & 0.05\\ \hline $k_{I_{Vul}\rightarrow D_{Vul}}$ & 0.10 & 0.10\\ \hline $k_{S_{Res}\rightarrow I_{Res}}$ & 0.50 & 0.78\\ \hline $k_{I_{Res}\rightarrow C_{Res}}$ & 0.50 & 0.50\\ \hline $k_{I_{Res}\rightarrow D_{Res}}$ & 0.05 & 0.05\\ \hline \end{tabular} \label{tab1} \end{table} We invoke two different values of $R_0$ for the two different sub-categories. For set-1 $R_0^{Vul} = 3.33$ and $R_0^{Res} = 3.33$. The larger value of $R_0$ for vulnerables arise from slower rate of recovery, Eq. \ref{eq3}. On the other hand, for set-2 $R_0^{Vul} = 5.20$ and $R_0^{Res} = 1.42$. We obtain these values by considering each of the population to be individually normalised (that is ~100\%). In such a situation the effective $R_0$ can be calculated as follows (Eq. \ref{eq12}). \begin{equation} R_0^{eff} = \frac{R_0^{Vul}N_{Vul}+R_0^{Res}N_{Res}}{N_{Vul}+N_{Res}} \label{eq12} \end{equation} Here $N_{Vul}$ and $N_{Res}$ represent the number of people in the vulnerable and resilient category respectively. In all our calculations we start with total infected fraction as 0.001 and vary the percentage of vulnerable populations from 5\%-40\%. By using Eq. \ref{eq12} we calculate the effective $R_0$ values for different ratio of vulnerable to resilient population. We find $R_0$ varies from 1.03 to 1.88 for set-1 and 1.61 to 2.93 for set-2. In a way, set-1 represents a more controlled situation compared to set-2 (Table \ref{tab2}). \begin{table}[ht] \caption{The basic reproduction number ($R_0$) for the parameters described in Table \ref{tab1} (set-1 and set-2) for various ratios of vulnerable to resilient population.} \centering \begin{tabular}{|c|c|c|c|} \hline \% & \% & \multicolumn{2}{c|}{$R_0$} \\ \cline{3-4} vulnerble & resilient & Set-1 & Set-2 \\ \hline \hline 5 & 95 & 1.031 & 1.609 \\ \hline 10 & 90 & 1.152 & 1.798 \\ \hline 15 & 85 & 1.273 & 1.987 \\ \hline 20 & 80 & 1.394 & 2.176 \\ \hline 25 & 75 & 1.515 & 2.365 \\ \hline 30 & 70 & 1.636 & 2.554 \\ \hline 35 & 65 & 1.757 & 2.743 \\ \hline 40 & 60 & 1.878 & 2.932 \\ \hline \end{tabular} \label{tab2} \end{table} \subsection{Stochastic Cellular Automata Simulation} Stochastic cellular automata (CA) simulations give a microscopic and nonlocal picture of the problem at hand. Such simulations are often used to model several physical phenomena.\cite{Hollingsworth2004, Seybold1998, Wolfram1983, Bartolozzi2004, Soares-Filho2002, Goltsev2010, Almeida2011} Unlike the mathematical model, CA simulations can directly establish a physical map of the disease-spread. Moreover, we incorporate several region specific and disease specific parameters in our CA simulations that give a general outlook to our investigations. A detailed list of the parameters and associated symbols can be found in our previous work.\cite{Mukherjee2020} The spread of COVID-19 is strongly inhomogeneous. So, a homogeneous model fails to capture many aspects. In a real-world scenario, the non-local description may often become important in determining the fate of a pandemic in a given geographical region. In such a case, the population parameters are space-dependent. Moreover, the rate constants also have a spatial distribution. Hence, solutions of these equations are highly non-trivial and a large scale cellular automata simulation may capture these inherent spatiotemporal heterogeneities. In this work, we neglect the effects of social distancing and quarantine, since we aim at establishing a relation between the percentage of mortality and immunization by an unhindered transmission of the disease within the whole population. Calculation of the rates of transmission and recovery/death can often be difficult due to several reasons like unavailability of data, political or demographic complications etc. This becomes particularly nontrivial when we consider the process with respect to a given population distribution of vulnerable and resilient individuals. The probabilistic approach employed in our simulations makes it easier to study the process, since obtaining an average probability for each of the processes is much more practical. We use the Moore definition \cite{Fu2003, White2007, Sirakoulis2000} to denote the neighbourhood of a given person. The salient features of our simulation are detailed in our previous work.\cite{Mukherjee2020} Here, we summarize our CA simulation methodology. We start we a land randomly occupied by susceptibles and infectives. The population distribution is such that 5\% and 0.05\% of the total available land is covered by susceptibles and infectives respectively. We divide the population into vulnerable and resilient individuals with respect to their probabilities of recovery ($P_R^{Vul}$ and $P_R^{Res}$). Vulnerables primarily include people above the age of 60. This also includes people with serious health issues, who are more prone to get deceased if infected.\cite{Remuzzi2020, Ruan2020, Wu2020} The resilients, on the other hand, are the young fraction of the society with no severe health conditions. When an infective comes in the neighbourhood of a susceptible, the latter is converted to an infective with a given probability of transmission which is considered to be equal and time independent (constant) for both vulnerables and resilients. The time period of infection is determined by probability of recovery and the probability of remaining infected in a given simulation step. In this work, we consider the latter to be 0.99.\cite{Mukherjee2020} An individual, once cured from infection, becomes immune to the disease. We run our simulations for a given number of steps ($N$). It should be noted that the time unit is not well-defined for this simulations. To get an estimate of time, the results need to be compared with our theoretical model. \section{Results and Discussion} \label{sec3} \subsection{Numerical solutions of the SIR model} \label{sec3A} \begin{figure}[ht] \centering \includegraphics[width=3.4in,keepaspectratio=true]{Figures/fig3.jpg} \caption{Population disease progression as obtained from the solution of the system of eight coupled non-linear differential equations presented in Eqs. \ref{eq4} - \ref{eq11} as function of time for two different situations described in Table \ref{tab1}. Plots show the increase in the total immunity (blue) with the decrease in the populations of vulnerable population (maroon) and resilient population (green) for (a) Set-1 and (b) Set-2. In these two calculations we start with $V:R=1:4$. In both the two cases the percentage demise in the vulnerable population is significantly higher.} \label{fig3} \end{figure} Here we present the results from the numerical solutions of Eqs. \ref{eq4} - \ref{eq11} in Fig. \ref{fig3}. We choose two sets of rate constants, set-1 (Fig. \ref{fig3}a) and set-2 (Fig. \ref{fig3}b) and obtain the changes in the population of vulnerables and resilients. With our choice of parameters (Table \ref{tab1}) for set-1 we observe 40.8\% increase in the immuned population. In order to achieve the 40.8\% immunity a region loses 4.7\% of its resilient population and 34.3\% vulnerable population. On the other hand, for set-2 a region loses 7.9\% of its resilient population and 57.1\% of its vulnerable population in order to achieve $\sim$68\% immunity (that could be the HIT for COVID-19). Hence, it is clear that for both the two cases the vulnerables are significantly affected. We note that with an increased infection rate the timescale of the saturation of the temporal profiles are drastically reduced. The graphs that are presented in Fig. \ref{fig3} are obtained for 20\% initial vulnerable population. In Fig. \ref{fig4}a, we show the time evolution of the total immunity percentage. In order to study the effect of fast (early) vs slow (late) achievement of the immunity saturation, we plot the percentage survival of the total population against the time required to attain the immunity threshold ($t_{Im}$) for different values of $k_{S\rightarrow I}$ (Fig. \ref{fig4}b). We find that the percentage of survival increases linearly with increasing $t_{Im}$. This indicates that a quick achievement of immunity saturation could lead to fatal consequences. \textit{If a society opts for herd immunity, it has to be a slow process}. \begin{figure}[h] \centering \includegraphics[width=3.2in,keepaspectratio=true]{Figures/fig4.jpg} \caption{The effect of different rates of attaining herd immunity on the total population. (a) Plot of the time evolution of the percentage of total immunized population for different values of susceptible to infected rate-constants. With increasing $k_{S\rightarrow I}$ we see an increase in the percentage immunity and decrease the time required to reach saturation ($t_{Im}$). (b) Percentage survival (uninfected and cured population) of the total population against $t_{Im}$. The two quantities show linear dependence. That is, the percentage survival increases as we take more time to reach immunity saturation. Note that both the X and the Y axes are the outcome of the numerical solution and not provided as inputs. The calculations are done using a fixed Vul:Res=1:4 and the rate constants associated with recovery/death are also kept same as given in Table \ref{tab1}.} \label{fig4} \end{figure} To make the immunity gaining process slow (which leads to relatively less casualty), the rate of infection ($k_{S\rightarrow I}$) needs to be brought down. On the other hand, the rate of removal (recovery and death), $k_{I\rightarrow R}$, depends primarily on the disease and partly on the presently available healthcare facilities. $k_{S\rightarrow I}$ can be controlled by employing effective strategies like lockdown, quarantine, and social distancing. \begin{figure}[H] \centering \includegraphics[width=3.2in,keepaspectratio=true]{Figures/fig5.jpg} \caption{The effect of the change in the initial percentage of the vulnerable population on the relative infection and recovery for the sub-categories, namely, vulnerables and resilients. Plots show the dependence of infection peak, percentage cured and dead population for vulnerable (maroon) and resilient (green) population with the initial fraction of vulnerable population as obtained from the solution of the modified SIR model described in Eqs. \ref{eq4} - \ref{eq11}. For figures (a)-(c) set-1 and for (d)-(f) set-2. The quantities show a non-linear dependence and enhanced fatality for the vurnerables.} \label{fig5} \end{figure} Next we vary the \% of initial vulnerable population from 5\% to 40\% and obtain the \% of highest active cases (that is the maxima in the temporal variation of $I_V(t)$ or $I_R(t)$), \% of cured population and \% of death. The range is chosen in order to represent different regions/countries. For example, in India only $\sim8\%$ of the entire population is above 60 years whereas, in countries like Italy and Germany the number is over 20\%. We obtain Fig. \ref{fig5}a - \ref{fig5}c for set-1 and Fig. \ref{fig5}d - \ref{fig5}f for set-2. In both the cases the variation of the infected peak maxima with \% vulnerable shows nearly linear increase with a higher slope for the vulnerables (Fig. \ref{fig5}a and \ref{fig5}d). Interestingly the \% cured (Fig. \ref{fig5}b and \ref{fig5}e) and \% dead (Fig. \ref{fig5}c and \ref{fig5}f) shows a nonlinear dependence on \% vulnerable. It clearly shows that the damage is huge to the vulnerable population when the \% of vulnerables increases. We plot (Fig. \ref{fig6}) the percentage of deaths for both the subcategories against the herd immunity threshold for a given Vul:Res composition (1:4). This is to show the increasing damage with respect to Ht. We find that the trend is linear for both the sets of parameters and the relative fatality is substantially higher for the vulnerables. \begin{figure}[H] \centering \includegraphics[width=3.2in,keepaspectratio=true]{Figures/fig6.jpg} \caption{Percentage outcome of different herd immunity thresholds ($H_t$) on the vulberable and resilient population. Plot of percentage deaths against $H_t$ calculated from Eq. \ref{eq2} for (a) set-1, and (b) set-2. In both the two cases the dependence is linear with substantially more damage to the vulnerable population. The values on the Y axes are individually normalised.} \label{fig6} \end{figure} \subsection{(Stochastic Cellular Automata Simulations} \label{sec3B} \subsubsection{Dependence on the initial population distribution} Here, we keep the probability of transmission of disease time-independent and equal for both resilients and vulnerables. We change the initial fraction of the vulnerable section of the total population from 5\% to 40\%. In Fig. \ref{fig7} we plot the \% of cured individuals (resilients and vulnerables) against \% of total immunization when the temporal progression of the population reaches saturation. As discussed earlier, herd immunity is obtained when a major section of the population becomes immune, post infection. However, apart from gaining immunity, this process involves the death of many infected individuals according to their survival probability. The probability of recovery of the resilients is higher than that of the vulnerables. Here, these two probabilities are taken as 0.95 and 0.8 respectively.\cite{Verity2020,Ruan2020} In Fig. \ref{fig7} the abscissa is the percentage of the total population that becomes immune after recovering from the infection. The ordinate quantifies the percentage of cured resilients and vulnerables with respect to the total initial population. \textit{With increase in the immunity attained in the society, a significant decrease in the percentage of cured vulnerable individuals is observed}. This implies that higher the percentage of immunization in the total population, greater is the probability of death of the vulnerable section. Hence herd immunity results in the death of a major fraction of the vulnerable population. This stratum of the society includes mainly the old people (age greater than years) and people with serious health conditions or comorbidity.\cite{Fang2020,Yang2020} The geographical regions with demographic distributions having higher fraction of the people of age above $\sim$60 years are among the worst affected. For example, Italy suffered the loss of many aged people as a result of the COVID-19 pandemic.\cite{Livingston2020,Onder2020} \begin{figure}[H] \centering \includegraphics[width=2.5in,keepaspectratio=true]{Figures/fig7.jpg} \caption{Percentage of cured resilient and vulnerables in the population on the course of attaining herd immunity. The percentage of cured individuals is shown as a function of the percentage of total population immunized after getting infected. This is obtained by averaging over 100 CA simulations. Green shows the percentage of death for the resilient fraction of the society and maroon denotes the same for the vulnerable people.} \label{fig7} \end{figure} In Fig. \ref{fig8}a , we show the time evolution of the fraction of vulnerables and resilients in the total population for different \% of initial number of vulnerables. The fractions are calculated with respect to the total initial population. We see that with increase in the initial \% of vulnerables, the number of resilients dying show a slight decrease, whereas the number of dead vulnerables increases significantly. This observation is clarified in Fig. \ref{fig8}b. Here we plot the absolute change in the fraction of resilients and vulnerables as functions of the initial \% of vulnerables. Both show linear dependence. The gradient (slope) is negative for resilients and positive for vulnerables. However, we find that the absolute value of the slope for the latter is $\sim$5 times higher than that of the former. This denotes that countries with higher population of elderly and vulnerable people in the society incur a greater loss in the number of vulnerable individuals. \begin{figure}[H] \centering \includegraphics[width=3.4in,keepaspectratio=true]{Figures/fig8.jpg} \caption{(a) Population dynamics represented as the temporal evolution of the fraction of resilient and vulnerable sections of the population are shown with varying initial distribution of resilients and vulnerables. The colour bar on the right hand side shows the initial \% of vulnerables in the total population. (b) The absolute decrease in the resilient (green) and vulnerable (maroon) fractions of the total population as functions of the initial percentage of vulnerables.} \label{fig8} \end{figure} \subsubsection{Dependence on the probability of recovery} Now, we keep the initial population distribution fixed at 20\% vulnerable and 80\% resilient individuals. We change the probability of recovery of these two categories ($P_R^{Vul}$ and $P_R^{Res}$) with the constraint $P_R^{Vul} \leq P_R^{Res}$. Accordingly, we change these two probabilities from 0.6 to 0.8 and 0.8 to 0.95 respectively. We choose these values according to reported case fatality ratios for the SARS-CoV-2 pandemic.\cite{Verity2020, Ruan2020} \begin{figure}[ht] \centering \includegraphics[width=3in,keepaspectratio=true]{Figures/fig9.png} \caption{Interdependence of different fractions of the population as the immunity evolves. Percentage of immunized (colour coded) represented as a function of the percentage of survival for vulnerables and resilients. The proportions are with respect to the total initial population. The primary variables are the probabilities of recovery of the vulnerables and the resilients. The results are obtained after averaging over 100 simulations.} \label{fig9} \end{figure} For every pair of $P_R^{Vul}$ and $P_R^{Res}$ we get a value of percentage of vulnerables and resilients who survive and a fraction of the population that gets immunized. In Figure 9 we plot the survival \% of vulnerables and resilients in the two perpendicular axes and represent the \% immunized as colour codes according to the colour gradation bar on the right hand side. In this contour representation, red denotes low immunity and blue denotes higher immunity. The survival \% of the vulnerables is lower than that of the resilients. The percentage of immunized population is higher (blue) for maximum survival of the resilients as compared to that of the vulnerables. This means that to attain higher immunity in the population, greater number of old and vulnerable people suffer death as compared to resilients. Hence, attainment of herd immunity comes with the cost of a higher mortality of the vulnerable section of the society. \section{Summary and Conclusion} Any epidemic is a dynamic process where time dependence plays a crucial role in the control of the spread and the damage, that is, the outcome. COVID-19 is a pandemic which is currently under intense scrutiny by all and sundry, and many aspects are yet to be understood. Every move by the government, and the population in general, is of crucial importance. Each pandemic comes with unique characteristics that deserve special treatments, not just medical and clinical but also sociological. In each such epidemic, immunity plays a critical role. Spanish Flu mainly attacked the age group between 20 and 30 years of age. This is the age group with maximum immunity. In the case of COVID-19, again we face the sad reality that certain section of the society is substantially more vulnerable than other sections. The vulnerable section consists of age groups which are above 60-65 years of age, and people with comorbidity. There is yet to further classification, although it is conceivable that as we understand the disease better and more precisely, better perception of danger would emerge. An epidemic often starts by a process of nucleation which is an important phenomenon often studied in physics and chemistry. The process of nucleation is initiated by a sudden appearance of a group of infected individuals in a region. This may be triggered a laboratory accident, or infection from eating wild animals like bats, pangolin etc. or by arrival of infected tourists and so on. The process may be dependent on the nature of the geography and demography of the country or region. The initial period of the process is often slow. After the initial nucleation, the disease spreads by a diffusion process into the susceptible population. Hence, it is a percolation with a temporal evolution. In order to address the issue of vulnerability of the population and the outcome with the progression of the epidemic, we carry out a theoretical analysis with the objective to analyze the consequences of aiming for herd immunity without vaccine, or a good drug, in the context of the present COVID-19 pandemic. We develop and solve a modified SIR model numerically and by employing cellular automata simulations. We particularly probed the following question: what is dependence of mortality on the rate of herd immunity? One of the key results of the present study is the dependence of the percentage survival on the rate of attainment of the immunity threshold. We find that a late attainment of the immunity saturation leads to relatively lesser fatality. We show that approximately 50-60\% of the vulnerables might lose their lives in order to attain ~70\% total immunized population. On the contrary the mortality of the resilient fraction of population is relatively low, may be just about 10\%. We find a non-linear trend in the dependence of the cured and dead population on the initial population of the vulnerables. This is because as the number of vulnerables increases, the immunity by infection from a larger fraction of population which cannot protect the vulnerables unless deliberate efforts are made that requires intervention. While we discuss herd immunity by infection in this work, the other, more sustainable option is herd immunity by vaccination. For example, diseases like small pox, polio etc. have been wiped off the face of earth by vaccination. This is particularly crucial for diseases with high mortality rates. However, for any novel disease, preparation of a vaccine can take years. In case of the present COVID-19 pandemic, for instance, extensive research is going on globally in search of a vaccine.\cite{Chen2020} However, no promising result has been obtained in almost five months and researchers believe it may take more than a year to prepare the vaccine. \begin{acknowledgments} We thank Prof. Sarika Bhattacharyya (NCL, Pune) and Prof. Suman Chakrabarty (SNCNCBS, Kolkata) for several fruitful discussions and comments. The authors thank the Department of Science and Technology (DST), India for financial support. BB thanks sir J. C. Bose fellowship for partial financial support. S. Mo. thanks Universities Grants Commission (UGC), India for research fellowship. S. Mu. thanks DST-INSPIRE programme for providing research fellowship. \end{acknowledgments} \section{Introducntion} The present COVID-19 pandemic is a dynamic and volatile process with often unpredictable ups and downs in the infected populations that make it difficult to predict its future course. In the absence of any vaccine or definitive drug in the immediate future \cite{Chen2020} the fight against COVID-19 is a hard and long drawn bitter battle, with two strategies being put forward. The first is the widely enforced lockdown, quarantine, and social distancing where the spread of the disease is contained at its inception and only a limited fraction of population is allowed to be infected.\cite{Prem2020} This model appears to be successful in South Korea and China, and some other Asian countries.\cite{Shen2020} The other model is to allow the virus to have a relatively unconstrained transmission so that a large fraction of the people develops the immunity.\cite{Kamikubo2020} This is called the herd immunity (HI) that is favoured by Sweden, and was initially discussed by Germany and England, but largely discarded later. HI can be achieved by two ways- (i) by vaccination, and (ii) by infection. The HI approach is based on the understanding that one can obtain the herd immunity in the society if 60-70\% of the population gets immunized. Needless to say this herd immunity is preferable through vaccination as happened in small pox and measles. Implementation of both the models has difficulties. Implementation of lockdown and social distancing requires enormous effort, backed up by resources. On the other hand, the HI model could have adverse consequence on the vulnerable citizens, a subject not adequately discussed. In fact, experiences in Italy and Spain show that the demography can be altered in some regions if HI is given an unconstrained run. Herd immunity ensures an indirect protection from COVID-19 (or any other infectious disease) when a large fraction of the population becomes immunized to the disease.\cite{Fine1993,Anderson1985,John2000} Herd immunity drastically decreases the probability of the presence of an uninfected individual in the vicinity of a presently infected individual. That is, the infected person is effectively quarantined by the surrounding immunized population. Hence, the chain of propagation breaks. In Fig. \ref{fig1} we pictorially explain the phenomenon of herd immunity. \begin{figure}[H] \centering \includegraphics[width=3.2in,keepaspectratio=true]{Figures/fig1.jpg} \caption{A pictorial representation of the herd immunity phenomenon. In the left we have a region with the susceptible population and one infected person. The total susceptibles are further divided into vulnerables and resilients. The infection propagates in an unconstrained manner and after a certain period the region possesses a large fraction of immunized population (right). After this immunisation any further infection cannot propagate and indirectly protects the susceptibles. In addition to that, multiple infected persons cannot do further harm. The colour codes are maintained throughout this paper.} \label{fig1} \end{figure} This can happen by providing the population with a vaccine or by getting cured after being infected. In the case of COVID-19 pandemic, as of now, we are unsure regarding the success of a vaccine and the latter is the only option to attain HI. However, the herd immunity threshold (HIT), that is the minimum fraction of population needs to get immunized in order to eradicate the disease, is different for different infectious diseases.\cite{Georgette2009,McBryde2009} For example, HIT for measles is ~92-95\% and for that of SARS-1 it is in the range of 50-80\%. Researchers around the world are exploring mainly two aspects of this disease- (i) the microscopic and clinical aspects which would eventually lead to drug discovery and vaccine preparation,\cite{Chen2020,Wrapp2020} (ii) the demographic aspects which lead to policy making and timeline prediction.\cite{Prem2020,Shen2020,Singh2020,Mukherjee2020} The latter requires effective mathematical modelling and crowd simulations. However, these models fail to predict the real scenario because of some inherent assumptions and limitations. Although a lot of interesting new studies are emerging in both categories in the context of the recent coronavirus pandemic, the issue of herd immunity and its fatality are not studied. There are several mathematical models which have been employed in the context of epidemic modelling, for example, the famous Kermack-McKendrick (KM) model which has been used extensively to study the spread of infectious diseases like measles, small pox etc.\cite{Daley2001,Kermack1927} At the core of this model lies a system of three coupled differential equations for susceptible (S), infected (I) and removed (R) (cured and dead) populations, that is, the famous SIR model (Eq. \ref{eq1}).\cite{Skvortsov2007,Jones2009,Anderson1979} At the onset of an epidemic S becomes I and I eventually becomes R, but R can never become S or I because of acquired immunity. \begin{equation} \begin{split} \frac{dS}{dt}& =-k_{S\rightarrow I}SI\\ \frac{dI}{dt}& =k_{S\rightarrow I}SI-k_{I\rightarrow R}I\\ \frac{dR}{dt}& =k_{I\rightarrow R}I \end{split} \label{eq1} \end{equation} Eq. \ref{eq1} describes the three coupled non-linear differential equations of the KM model where $k_{S\rightarrow I}$ is the rate of infection and $k_{I\rightarrow R}$ is the rate of removal (recovery and death). In the conventional SIR model $k_{S\rightarrow I}$ and $k_{I\rightarrow R}$ are written as $\alpha$ and $\beta$ respectively. In principle the rate constants should be time and space dependent, that is, non-local in nature. But it is difficult to predict the functional form of the rate constants with time- it could be periodic, decaying or stochastic in nature. The applicability of this model is for a homogeneous population distribution and mass transmission at a large scale.\cite{Daley2001} An important quantity is the basic reproduction number ($R_0$) which is an estimate of the number of secondary infection from one primary infection.\cite{Dietz1993} The value of $R_0$ is intimately connected with the herd immunity threshold ($H_t$) discussed above.\cite{McBryde2009,Diekmann1995} (Eq. \ref{eq2}) Hence a correct determination of the basic reproduction parameter, $R_0$, is important. \begin{equation} H_t=\left(1-\frac{1}{R_0}\right)\times 100 \% \label{eq2} \end{equation} It is clear from Eq. \ref{eq2} that a higher value of $R_0$ increases the herd immunity threshold. For SARS-Cov2 the value of $R_0$ shows a large dispersion and as a consequence we cannot predict the value of $H_t$. For COVID-19 the average value of $R_0$ is estimated to be in the range of $\sim$2.0-3.0 but it can possess spatial heterogeneity and time dependence in reality.\cite{Zhang2020,Tang2020} If one considers $R_0$ to be in the range of 2.0-3.0 the value of $H_t$ would be in between 50\%-66\%. In the light of SIR model [Eq.(1)] $R_0$ can be defined as \begin{equation} R_0=\frac{k_{S\rightarrow I}}{k_{I\rightarrow R}} S \label{eq3} \end{equation} Eq. \ref{eq3} provides a different definition of $R_0$ and can be understood as follows. If we assume that (the S the fraction of susceptible population) is near 1.0 at the beginning (as there are very few infections compared to a huge population), then $R_0$ could be equal to unity if the two rate constants are equal. This means that the number of infection and recovery are same at any time. In this situation the disease remains under control. $R_0 > 1$ causes an epidemic as it challenges the capacity of the healthcare facilities. However, for different region the value of $R_0$ could be different depending on the intensity of region wise preventive and healthcare measures. In this work we ask the following questions- (i) what are the relative magnitude of the fatality to the vulnerable and resilient populations if we attempt to achieve HI without a vaccine? (ii) What is the dependence of the fraction of survival on the rate of the attainment of HI? These two issues are widely discussed all over the world. Here we seek answers to these two important questions by employing a modified Susceptible-Infected-Removed (SIR) model and cellular automata (CA) simulations. The rest of the paper is organised as follows. In section \ref{sec2} we describe the mathematical model and the CA simulation protocols. Section \ref{sec3} consists of the results from numerical solutions of the modified SIR model and simulations, accompanied by detailed discussions. This section is further divided into several sub sections. In section IV we summarize and conclude our study. \section{Theoretical Formalism} \label{sec2} \subsection{Mathematical Modelling} We modify the celebrated SIR (Susceptible-Infected-Removed) model by dividing the entire susceptible population into two parts, namely vulnerable (Vul) and resilient (Res). In the context of the corona virus disease, the vulnerable category consists of persons who are above 60 years of age or have pre-existing medical conditions like diabetes, heart and kidney disease, and lung conditions.\cite{Yang2020} The rest of the population is termed as resilient who have a greater chance of getting cured. We achieve such classification by employing different rate constants associated with their recovery. This is based on the available data on the coronavirus disease. The scheme of this classification is described in Fig. \ref{fig2}. \begin{figure}[ht] \centering \includegraphics[width=3in,keepaspectratio=true]{Figures/fig2.jpg} \caption{Schematic representation of the modified SIR network model. Here the susceptible (S) population is divided into $S_V$ and $S_R$ that represent elderly and younger people respectively. A part of the fraction $S_V$ gets infected and creates $I_O$ fraction of infected population. A part of the remaining fraction of the population, that is, $S_R$ gets infected and creates $I_R$ fraction of the infected population. Both $I_V$ and $I_R$ get either cured (C) or dead (D). Naturally the rate of recovery for the younger fraction of the population is more than that of the older infected population. On the other hand, the rate of death for the older population is more than that of the younger invectives.} \label{fig2} \end{figure} We follow the scheme described in Fig. \ref{fig2} and formulate a system of eight coupled non-linear differential equations [Eqs. \ref{eq4} - \ref{eq11}]. \begin{equation} \frac{dS_{Vul}(t)}{dt} = -k_{S_{Vul}\rightarrow I_{Vul}}(t)S_{Vul}(t)I(t) \label{eq4} \end{equation} \begin{equation} \frac{dS_{Res}(t)}{dt} = -k_{S_{Res}\rightarrow I_{Res}}(t)S_{Res}(t)I(t) \label{eq5} \end{equation} \begin{equation} \begin{split} \frac{dI_{Vul}(t)}{dt} = k_{S_{Vul}\rightarrow I_{Vul}}(t)S_{Vul}(t)I(t)\\ -(k_{I_{Vul}\rightarrow C_{Vul}}(t)+k_{I_{Vul}\rightarrow D_{Vul}}(t))I_{Vul}(t) \end{split} \label{eq6} \end{equation} \begin{equation} \begin{split} \frac{dI_{Res}(t)}{dt} = k_{S_{Res}\rightarrow I_{Res}}(t)S_{Res}(t)I(t)\\ -(k_{I_{Res}\rightarrow C_{Res}}(t)+k_{I_{Res}\rightarrow D_{Res}}(t))I_{Res}(t) \end{split} \label{eq7} \end{equation} \begin{equation} \frac{dC_{Vul}(t)}{dt} = k_{I_{Vul}\rightarrow C_{Vul}}(t)I_{Vul}(t) \label{eq8} \end{equation} \begin{equation} \frac{dC_{Res}(t)}{dt} = k_{I_{Res}\rightarrow C_{Res}}(t)I_{Res}(t) \label{eq9} \end{equation} \begin{equation} \frac{dD_{Vul}(t)}{dt} = k_{I_{Vul}\rightarrow D_{Vul}}(t)I_{Vul}(t) \label{eq10} \end{equation} \begin{equation} \frac{dD_{Res}(t)}{dt} = k_{I_{Res}\rightarrow D_{Res}}(t)I_{Res}(t) \label{eq11} \end{equation} In the following, we explain the complex set of equations. Here I(t) is the number of total infectives at any time t, that is $I(t)=I_{Vul}(t)+I_{Res}(t)$. This is the variable that couples the two population sub-categories. $k(t)$ are the rate constants associated with processes that are described in the subscript with an arrow. We would like to point out that the rates in above equations of motion are all assumed to be time dependent. These rate constants contain all the basic information and also connected with $R_0$. In our earlier study, we employed a time dependent rate to produce certain features observed in the time dependence of new cases such a double peaked population structure.\cite{Mukherjee2020} The time dependence of rate can be employed to include certain dynamical features like crossover from local contact to community transmission. It is worth stressing that the modelling of these time dependent rate constants plays a pivotal role in the SIR scheme. We propagate these equations numerically to obtain the respective temporal evolution of each kind of population fraction. From the temporal profiles we can extract several important quantities after a long time (that is, the end of the spread), for example, (i) the peak height of the active infected cases, (ii) the fraction of cured population, (iii) the fraction of dead population, (iv) the fraction of uninfected population, (v) time required to reach the immunity threshold etc. We can regard these equations together to form a system of reacting species, as in a system of chemical reactions. We solve these equations with two different sets of the rate constant values and aim to understand the relative damages to the vulnerable and resilient population. The values of rate constants are provided in Table \ref{tab1}. We keep $k_{S_{Vul}\rightarrow I_{Vul}}$ and $k_{S_{Res}\rightarrow I_{Res}}$ the same which depicts the same probability of getting infected for both the sub-categories. However, the rate constants associated with recovery and death differs in orders of magnitude between Vul and Res. We now discuss the procedure we follow to assign different rate constants to the vulnerables and resilients. In a previous study we estimated the values of $k_{S\rightarrow I}$ and $k_{I\rightarrow R}$ by fitting the infected/cured/death vs. time data for India (source: www.covid19india.org).\cite{Mukherjee2020} We plot the rate of change of the cured ($dC/dt$) and dead ($dD/dt$) population against the infected population to find the slope that gives the rate. This procedure provides us with required estimates of $k_{I\rightarrow C}$ and $k_{I\rightarrow D}$. For India, till $27^{th}$ May, the estimated values are $k_{I\rightarrow C} = 0.026 \:day^{-1}$ and $k_{I\rightarrow D} = 0.0013 \:day^{-1}$. That is, $k_{I\rightarrow C}$ is approximately 20 times of $k_{I\rightarrow D}$. However, for countries like Italy, Spain, and USA $k_{I\rightarrow D}$ was significantly higher. This comparison however takes no cognition of the relative time scales, and therefore should be taken with care. These values are mean field in nature and contain enormous spatial heterogeneity. If we see the state wise (or district wise) statistics we find a large dispersion. On the other hand, the determination of $k_{S\rightarrow I}$ is not that straight forward as the equations containing $k_{S\rightarrow I}$ are non-linear in nature in the SIR model. Hence one needs to obtain a good estimate of $R_0$ and calculate $k_{S\rightarrow I}$ from Eq. \ref{eq3}. As mentioned above, $R_0$ also exhibits spatiotemporal heterogeneity which makes the problem of estimating the rate constants even more challenging. For example, in Italy $R_0$ has been estimated to be $\sim$3.0-6.0 and in the Hunan province of China it is $\sim$1.73-5.25.\cite{Wangping2020} In a recent study on Wuhan, the transmission rate ($k_{S\rightarrow I}$) is assumed to vary from 0.59 to $1.68 \:day^{-1}$.\cite{Lin2020} However, the data required to extract the rate constants associated with the two individual sub-categories, namely, vulnerable and resilient, are not available separately. As the values of the rate constants are connected to the basic reproduction number ($R_0$), we choose the inputs, by preserving the basic features, such that the average value of $R_0$ yields an acceptable number, in light of acquired information. Next we tune the parameters such that the maximum of the active cases falls in the range of $\sim$60-90 days, as observed for most countries. We note that we consider these values only to study the trends and do not strictly correspond to any particular region in reality. \begin{table}[ht] \caption{The values of rate constants used to solve the system of coupled differential equations [Eq.\ref{eq4} - \ref{eq11}]. The unit of the rate constants is $day^{-1}$.} \centering \begin{tabular}{|c|c|c|} \hline Rate Const. & Set-1 & Set-2\\ \hline \hline $k_{S_{Vul}\rightarrow I_{Vul}}$ & 0.50 & 0.78\\ \hline $k_{I_{Vul}\rightarrow C_{Vul}}$ & 0.05 & 0.05\\ \hline $k_{I_{Vul}\rightarrow D_{Vul}}$ & 0.10 & 0.10\\ \hline $k_{S_{Res}\rightarrow I_{Res}}$ & 0.50 & 0.78\\ \hline $k_{I_{Res}\rightarrow C_{Res}}$ & 0.50 & 0.50\\ \hline $k_{I_{Res}\rightarrow D_{Res}}$ & 0.05 & 0.05\\ \hline \end{tabular} \label{tab1} \end{table} We invoke two different values of $R_0$ for the two different sub-categories. For set-1 $R_0^{Vul} = 3.33$ and $R_0^{Res} = 3.33$. The larger value of $R_0$ for vulnerables arise from slower rate of recovery, Eq. \ref{eq3}. On the other hand, for set-2 $R_0^{Vul} = 5.20$ and $R_0^{Res} = 1.42$. We obtain these values by considering each of the population to be individually normalised (that is ~100\%). In such a situation the effective $R_0$ can be calculated as follows (Eq. \ref{eq12}). \begin{equation} R_0^{eff} = \frac{R_0^{Vul}N_{Vul}+R_0^{Res}N_{Res}}{N_{Vul}+N_{Res}} \label{eq12} \end{equation} Here $N_{Vul}$ and $N_{Res}$ represent the number of people in the vulnerable and resilient category respectively. In all our calculations we start with total infected fraction as 0.001 and vary the percentage of vulnerable populations from 5\%-40\%. By using Eq. \ref{eq12} we calculate the effective $R_0$ values for different ratio of vulnerable to resilient population. We find $R_0$ varies from 1.03 to 1.88 for set-1 and 1.61 to 2.93 for set-2. In a way, set-1 represents a more controlled situation compared to set-2 (Table \ref{tab2}). \begin{table}[ht] \caption{The basic reproduction number ($R_0$) for the parameters described in Table \ref{tab1} (set-1 and set-2) for various ratios of vulnerable to resilient population.} \centering \begin{tabular}{|c|c|c|c|} \hline \% & \% & \multicolumn{2}{c|}{$R_0$} \\ \cline{3-4} vulnerble & resilient & Set-1 & Set-2 \\ \hline \hline 5 & 95 & 1.031 & 1.609 \\ \hline 10 & 90 & 1.152 & 1.798 \\ \hline 15 & 85 & 1.273 & 1.987 \\ \hline 20 & 80 & 1.394 & 2.176 \\ \hline 25 & 75 & 1.515 & 2.365 \\ \hline 30 & 70 & 1.636 & 2.554 \\ \hline 35 & 65 & 1.757 & 2.743 \\ \hline 40 & 60 & 1.878 & 2.932 \\ \hline \end{tabular} \label{tab2} \end{table} \subsection{Stochastic Cellular Automata Simulation} Stochastic cellular automata (CA) simulations give a microscopic and nonlocal picture of the problem at hand. Such simulations are often used to model several physical phenomena.\cite{Hollingsworth2004, Seybold1998, Wolfram1983, Bartolozzi2004, Soares-Filho2002, Goltsev2010, Almeida2011} Unlike the mathematical model, CA simulations can directly establish a physical map of the disease-spread. Moreover, we incorporate several region specific and disease specific parameters in our CA simulations that give a general outlook to our investigations. A detailed list of the parameters and associated symbols can be found in our previous work.\cite{Mukherjee2020} The spread of COVID-19 is strongly inhomogeneous. So, a homogeneous model fails to capture many aspects. In a real-world scenario, the non-local description may often become important in determining the fate of a pandemic in a given geographical region. In such a case, the population parameters are space-dependent. Moreover, the rate constants also have a spatial distribution. Hence, solutions of these equations are highly non-trivial and a large scale cellular automata simulation may capture these inherent spatiotemporal heterogeneities. In this work, we neglect the effects of social distancing and quarantine, since we aim at establishing a relation between the percentage of mortality and immunization by an unhindered transmission of the disease within the whole population. Calculation of the rates of transmission and recovery/death can often be difficult due to several reasons like unavailability of data, political or demographic complications etc. This becomes particularly nontrivial when we consider the process with respect to a given population distribution of vulnerable and resilient individuals. The probabilistic approach employed in our simulations makes it easier to study the process, since obtaining an average probability for each of the processes is much more practical. We use the Moore definition \cite{Fu2003, White2007, Sirakoulis2000} to denote the neighbourhood of a given person. The salient features of our simulation are detailed in our previous work.\cite{Mukherjee2020} Here, we summarize our CA simulation methodology. We start we a land randomly occupied by susceptibles and infectives. The population distribution is such that 5\% and 0.05\% of the total available land is covered by susceptibles and infectives respectively. We divide the population into vulnerable and resilient individuals with respect to their probabilities of recovery ($P_R^{Vul}$ and $P_R^{Res}$). Vulnerables primarily include people above the age of 60. This also includes people with serious health issues, who are more prone to get deceased if infected.\cite{Remuzzi2020, Ruan2020, Wu2020} The resilients, on the other hand, are the young fraction of the society with no severe health conditions. When an infective comes in the neighbourhood of a susceptible, the latter is converted to an infective with a given probability of transmission which is considered to be equal and time independent (constant) for both vulnerables and resilients. The time period of infection is determined by probability of recovery and the probability of remaining infected in a given simulation step. In this work, we consider the latter to be 0.99.\cite{Mukherjee2020} An individual, once cured from infection, becomes immune to the disease. We run our simulations for a given number of steps ($N$). It should be noted that the time unit is not well-defined for this simulations. To get an estimate of time, the results need to be compared with our theoretical model. \section{Results and Discussion} \label{sec3} \subsection{Numerical solutions of the SIR model} \label{sec3A} \begin{figure}[ht] \centering \includegraphics[width=3.4in,keepaspectratio=true]{Figures/fig3.jpg} \caption{Population disease progression as obtained from the solution of the system of eight coupled non-linear differential equations presented in Eqs. \ref{eq4} - \ref{eq11} as function of time for two different situations described in Table \ref{tab1}. Plots show the increase in the total immunity (blue) with the decrease in the populations of vulnerable population (maroon) and resilient population (green) for (a) Set-1 and (b) Set-2. In these two calculations we start with $V:R=1:4$. In both the two cases the percentage demise in the vulnerable population is significantly higher.} \label{fig3} \end{figure} Here we present the results from the numerical solutions of Eqs. \ref{eq4} - \ref{eq11} in Fig. \ref{fig3}. We choose two sets of rate constants, set-1 (Fig. \ref{fig3}a) and set-2 (Fig. \ref{fig3}b) and obtain the changes in the population of vulnerables and resilients. With our choice of parameters (Table \ref{tab1}) for set-1 we observe 40.8\% increase in the immuned population. In order to achieve the 40.8\% immunity a region loses 4.7\% of its resilient population and 34.3\% vulnerable population. On the other hand, for set-2 a region loses 7.9\% of its resilient population and 57.1\% of its vulnerable population in order to achieve $\sim$68\% immunity (that could be the HIT for COVID-19). Hence, it is clear that for both the two cases the vulnerables are significantly affected. We note that with an increased infection rate the timescale of the saturation of the temporal profiles are drastically reduced. The graphs that are presented in Fig. \ref{fig3} are obtained for 20\% initial vulnerable population. In Fig. \ref{fig4}a, we show the time evolution of the total immunity percentage. In order to study the effect of fast (early) vs slow (late) achievement of the immunity saturation, we plot the percentage survival of the total population against the time required to attain the immunity threshold ($t_{Im}$) for different values of $k_{S\rightarrow I}$ (Fig. \ref{fig4}b). We find that the percentage of survival increases linearly with increasing $t_{Im}$. This indicates that a quick achievement of immunity saturation could lead to fatal consequences. \textit{If a society opts for herd immunity, it has to be a slow process}. \begin{figure}[h] \centering \includegraphics[width=3.2in,keepaspectratio=true]{Figures/fig4.jpg} \caption{The effect of different rates of attaining herd immunity on the total population. (a) Plot of the time evolution of the percentage of total immunized population for different values of susceptible to infected rate-constants. With increasing $k_{S\rightarrow I}$ we see an increase in the percentage immunity and decrease the time required to reach saturation ($t_{Im}$). (b) Percentage survival (uninfected and cured population) of the total population against $t_{Im}$. The two quantities show linear dependence. That is, the percentage survival increases as we take more time to reach immunity saturation. Note that both the X and the Y axes are the outcome of the numerical solution and not provided as inputs. The calculations are done using a fixed Vul:Res=1:4 and the rate constants associated with recovery/death are also kept same as given in Table \ref{tab1}.} \label{fig4} \end{figure} To make the immunity gaining process slow (which leads to relatively less casualty), the rate of infection ($k_{S\rightarrow I}$) needs to be brought down. On the other hand, the rate of removal (recovery and death), $k_{I\rightarrow R}$, depends primarily on the disease and partly on the presently available healthcare facilities. $k_{S\rightarrow I}$ can be controlled by employing effective strategies like lockdown, quarantine, and social distancing. \begin{figure}[H] \centering \includegraphics[width=3.2in,keepaspectratio=true]{Figures/fig5.jpg} \caption{The effect of the change in the initial percentage of the vulnerable population on the relative infection and recovery for the sub-categories, namely, vulnerables and resilients. Plots show the dependence of infection peak, percentage cured and dead population for vulnerable (maroon) and resilient (green) population with the initial fraction of vulnerable population as obtained from the solution of the modified SIR model described in Eqs. \ref{eq4} - \ref{eq11}. For figures (a)-(c) set-1 and for (d)-(f) set-2. The quantities show a non-linear dependence and enhanced fatality for the vurnerables.} \label{fig5} \end{figure} Next we vary the \% of initial vulnerable population from 5\% to 40\% and obtain the \% of highest active cases (that is the maxima in the temporal variation of $I_V(t)$ or $I_R(t)$), \% of cured population and \% of death. The range is chosen in order to represent different regions/countries. For example, in India only $\sim8\%$ of the entire population is above 60 years whereas, in countries like Italy and Germany the number is over 20\%. We obtain Fig. \ref{fig5}a - \ref{fig5}c for set-1 and Fig. \ref{fig5}d - \ref{fig5}f for set-2. In both the cases the variation of the infected peak maxima with \% vulnerable shows nearly linear increase with a higher slope for the vulnerables (Fig. \ref{fig5}a and \ref{fig5}d). Interestingly the \% cured (Fig. \ref{fig5}b and \ref{fig5}e) and \% dead (Fig. \ref{fig5}c and \ref{fig5}f) shows a nonlinear dependence on \% vulnerable. It clearly shows that the damage is huge to the vulnerable population when the \% of vulnerables increases. We plot (Fig. \ref{fig6}) the percentage of deaths for both the subcategories against the herd immunity threshold for a given Vul:Res composition (1:4). This is to show the increasing damage with respect to Ht. We find that the trend is linear for both the sets of parameters and the relative fatality is substantially higher for the vulnerables. \begin{figure}[H] \centering \includegraphics[width=3.2in,keepaspectratio=true]{Figures/fig6.jpg} \caption{Percentage outcome of different herd immunity thresholds ($H_t$) on the vulberable and resilient population. Plot of percentage deaths against $H_t$ calculated from Eq. \ref{eq2} for (a) set-1, and (b) set-2. In both the two cases the dependence is linear with substantially more damage to the vulnerable population. The values on the Y axes are individually normalised.} \label{fig6} \end{figure} \subsection{(Stochastic Cellular Automata Simulations} \label{sec3B} \subsubsection{Dependence on the initial population distribution} Here, we keep the probability of transmission of disease time-independent and equal for both resilients and vulnerables. We change the initial fraction of the vulnerable section of the total population from 5\% to 40\%. In Fig. \ref{fig7} we plot the \% of cured individuals (resilients and vulnerables) against \% of total immunization when the temporal progression of the population reaches saturation. As discussed earlier, herd immunity is obtained when a major section of the population becomes immune, post infection. However, apart from gaining immunity, this process involves the death of many infected individuals according to their survival probability. The probability of recovery of the resilients is higher than that of the vulnerables. Here, these two probabilities are taken as 0.95 and 0.8 respectively.\cite{Verity2020,Ruan2020} In Fig. \ref{fig7} the abscissa is the percentage of the total population that becomes immune after recovering from the infection. The ordinate quantifies the percentage of cured resilients and vulnerables with respect to the total initial population. \textit{With increase in the immunity attained in the society, a significant decrease in the percentage of cured vulnerable individuals is observed}. This implies that higher the percentage of immunization in the total population, greater is the probability of death of the vulnerable section. Hence herd immunity results in the death of a major fraction of the vulnerable population. This stratum of the society includes mainly the old people (age greater than years) and people with serious health conditions or comorbidity.\cite{Fang2020,Yang2020} The geographical regions with demographic distributions having higher fraction of the people of age above $\sim$60 years are among the worst affected. For example, Italy suffered the loss of many aged people as a result of the COVID-19 pandemic.\cite{Livingston2020,Onder2020} \begin{figure}[H] \centering \includegraphics[width=2.5in,keepaspectratio=true]{Figures/fig7.jpg} \caption{Percentage of cured resilient and vulnerables in the population on the course of attaining herd immunity. The percentage of cured individuals is shown as a function of the percentage of total population immunized after getting infected. This is obtained by averaging over 100 CA simulations. Green shows the percentage of death for the resilient fraction of the society and maroon denotes the same for the vulnerable people.} \label{fig7} \end{figure} In Fig. \ref{fig8}a , we show the time evolution of the fraction of vulnerables and resilients in the total population for different \% of initial number of vulnerables. The fractions are calculated with respect to the total initial population. We see that with increase in the initial \% of vulnerables, the number of resilients dying show a slight decrease, whereas the number of dead vulnerables increases significantly. This observation is clarified in Fig. \ref{fig8}b. Here we plot the absolute change in the fraction of resilients and vulnerables as functions of the initial \% of vulnerables. Both show linear dependence. The gradient (slope) is negative for resilients and positive for vulnerables. However, we find that the absolute value of the slope for the latter is $\sim$5 times higher than that of the former. This denotes that countries with higher population of elderly and vulnerable people in the society incur a greater loss in the number of vulnerable individuals. \begin{figure}[H] \centering \includegraphics[width=3.4in,keepaspectratio=true]{Figures/fig8.jpg} \caption{(a) Population dynamics represented as the temporal evolution of the fraction of resilient and vulnerable sections of the population are shown with varying initial distribution of resilients and vulnerables. The colour bar on the right hand side shows the initial \% of vulnerables in the total population. (b) The absolute decrease in the resilient (green) and vulnerable (maroon) fractions of the total population as functions of the initial percentage of vulnerables.} \label{fig8} \end{figure} \subsubsection{Dependence on the probability of recovery} Now, we keep the initial population distribution fixed at 20\% vulnerable and 80\% resilient individuals. We change the probability of recovery of these two categories ($P_R^{Vul}$ and $P_R^{Res}$) with the constraint $P_R^{Vul} \leq P_R^{Res}$. Accordingly, we change these two probabilities from 0.6 to 0.8 and 0.8 to 0.95 respectively. We choose these values according to reported case fatality ratios for the SARS-CoV-2 pandemic.\cite{Verity2020, Ruan2020} \begin{figure}[ht] \centering \includegraphics[width=3in,keepaspectratio=true]{Figures/fig9.png} \caption{Interdependence of different fractions of the population as the immunity evolves. Percentage of immunized (colour coded) represented as a function of the percentage of survival for vulnerables and resilients. The proportions are with respect to the total initial population. The primary variables are the probabilities of recovery of the vulnerables and the resilients. The results are obtained after averaging over 100 simulations.} \label{fig9} \end{figure} For every pair of $P_R^{Vul}$ and $P_R^{Res}$ we get a value of percentage of vulnerables and resilients who survive and a fraction of the population that gets immunized. In Figure 9 we plot the survival \% of vulnerables and resilients in the two perpendicular axes and represent the \% immunized as colour codes according to the colour gradation bar on the right hand side. In this contour representation, red denotes low immunity and blue denotes higher immunity. The survival \% of the vulnerables is lower than that of the resilients. The percentage of immunized population is higher (blue) for maximum survival of the resilients as compared to that of the vulnerables. This means that to attain higher immunity in the population, greater number of old and vulnerable people suffer death as compared to resilients. Hence, attainment of herd immunity comes with the cost of a higher mortality of the vulnerable section of the society. \section{Summary and Conclusion} Any epidemic is a dynamic process where time dependence plays a crucial role in the control of the spread and the damage, that is, the outcome. COVID-19 is a pandemic which is currently under intense scrutiny by all and sundry, and many aspects are yet to be understood. Every move by the government, and the population in general, is of crucial importance. Each pandemic comes with unique characteristics that deserve special treatments, not just medical and clinical but also sociological. In each such epidemic, immunity plays a critical role. Spanish Flu mainly attacked the age group between 20 and 30 years of age. This is the age group with maximum immunity. In the case of COVID-19, again we face the sad reality that certain section of the society is substantially more vulnerable than other sections. The vulnerable section consists of age groups which are above 60-65 years of age, and people with comorbidity. There is yet to further classification, although it is conceivable that as we understand the disease better and more precisely, better perception of danger would emerge. An epidemic often starts by a process of nucleation which is an important phenomenon often studied in physics and chemistry. The process of nucleation is initiated by a sudden appearance of a group of infected individuals in a region. This may be triggered a laboratory accident, or infection from eating wild animals like bats, pangolin etc. or by arrival of infected tourists and so on. The process may be dependent on the nature of the geography and demography of the country or region. The initial period of the process is often slow. After the initial nucleation, the disease spreads by a diffusion process into the susceptible population. Hence, it is a percolation with a temporal evolution. In order to address the issue of vulnerability of the population and the outcome with the progression of the epidemic, we carry out a theoretical analysis with the objective to analyze the consequences of aiming for herd immunity without vaccine, or a good drug, in the context of the present COVID-19 pandemic. We develop and solve a modified SIR model numerically and by employing cellular automata simulations. We particularly probed the following question: what is dependence of mortality on the rate of herd immunity? One of the key results of the present study is the dependence of the percentage survival on the rate of attainment of the immunity threshold. We find that a late attainment of the immunity saturation leads to relatively lesser fatality. We show that approximately 50-60\% of the vulnerables might lose their lives in order to attain ~70\% total immunized population. On the contrary the mortality of the resilient fraction of population is relatively low, may be just about 10\%. We find a non-linear trend in the dependence of the cured and dead population on the initial population of the vulnerables. This is because as the number of vulnerables increases, the immunity by infection from a larger fraction of population which cannot protect the vulnerables unless deliberate efforts are made that requires intervention. While we discuss herd immunity by infection in this work, the other, more sustainable option is herd immunity by vaccination. For example, diseases like small pox, polio etc. have been wiped off the face of earth by vaccination. This is particularly crucial for diseases with high mortality rates. However, for any novel disease, preparation of a vaccine can take years. In case of the present COVID-19 pandemic, for instance, extensive research is going on globally in search of a vaccine.\cite{Chen2020} However, no promising result has been obtained in almost five months and researchers believe it may take more than a year to prepare the vaccine. \begin{acknowledgments} We thank Prof. Sarika Bhattacharyya (NCL, Pune) and Prof. Suman Chakrabarty (SNCNCBS, Kolkata) for several fruitful discussions and comments. The authors thank the Department of Science and Technology (DST), India for financial support. BB thanks sir J. C. Bose fellowship for partial financial support. S. Mo. thanks Universities Grants Commission (UGC), India for research fellowship. S. Mu. thanks DST-INSPIRE programme for providing research fellowship. \end{acknowledgments}
{'timestamp': '2020-06-01T02:10:14', 'yymm': '2005', 'arxiv_id': '2005.14496', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14496'}
arxiv
\section{Introduction} Recently, deployments of \glspl{mav} are gaining increasing attention, especially in the mining industry~\cite{mansouri2020deploying}. The autonomous navigation of the \gls{mav}, equipped with a sensor suite has the ability to collect information, such as images, gas level, dust level, monitor the personnel, explore unknown and production areas, and minimize service times. At the same time, the deployments of \glspl{mav} increase the production and the overall safety in the mining industry, while reducing the overall operation costs aligned with the envisioned mine of \gls{zepa}~\cite{NIKOLAKOPOULOS201566}. Furthermore, the harsh mining environments are characterized from a lack of illumination, narrow passages, wind gusts, dust and in general conditions that have a direct affect the performance of the platforms and in the worse case may cause failure in system components or even result to collision and crashes. Moreover, the commercially available \glspl{mav} rely on \gls{gps} or visual sensors, or both for performing a position estimation, however underground mines are \gls{gps}-denied environments and due to lack of any natural illumination and prominent visual and geometric features, the vision-based positioning methods are not reliable. Additionally, commercially available platforms provide manual or semi-autonomous flights, which require a pilot with a direct line of sight to the platform, a case which cannot be guaranteed in dark tunnels with multiple turns and crosses. The main objective of this article is to propose a low cost and modular \gls{mav} platform, as depicted in Figure~\ref{fig:quadcopter}, for autonomous navigation in dark tunnels. The platform is equipped with a 2D lidar, a single beam laser range finder, LED light bars, a PX4 optical flow, a forward looking camera, a flight controller and an on-board computer, while the software architecture is developed based on the equipped sensor suites to establish fully autonomous navigation. The proposed configuration of the \gls{mav} has been specifically designed for a direct deployed in underground mines, without a natural illumination and by that demonstrating the capability for fully autonomous \glspl{mav} navigation in such environments. Finally, this article discusses all the needed components in order to enable further hardware developments towards the autonomous navigation in dark tunnels. Although this work showcases the platform in tunnel navigation, the system can be deployed in similar missions including subterranean exploration~\cite{rogers2017distributed}, or Mars canyon exploration~\cite{matthaei2013swarm}. \begin{figure}[htbp] \centering \includegraphics[width=1\linewidth]{quad_angle_axis_new.png} \caption{The proposed low-cost \glspl{mav} platform with attached body fixed frame $\mathbb{B}$.} \label{fig:quadcopter} \end{figure} The rest of the article is structured as it follows. Initially, the state of the art of \gls{mav} development is presented in Section~\ref{sec:relatedworks}, followed by the platform architecture in Section~\ref{sec:platformartichecture}, which discusses the corresponding hardware and software components. In Section~\ref{sec:platformperformance} the performance of the proposed platform is evaluated in an underground mine tunnel and finally in Section~\ref{Conclusions} a summary of the findings is provided. \section{Related Works} \label{sec:relatedworks} Nowadays, industry and academic sectors develop \glspl{mav} for different applications. The majority of the developed platforms by commercial companies do not provide access to raw sensor measurements or tuning parameters of the controllers. Additionally, these platforms do not allow for hardware modifications and their performance is limited to semi-autonomous navigation especially in indoor environments. These factors limit their usage and functionality in challenging environments, such as underground mine tunnels, where the platform should be modified based on the application requirements. As an example, the commercially available quad-copter Parrot Bebop 2~\cite{parrot2016parrot} is equipped with a forward looking camera, an optical flow sensor and a sonar sensor facing down, it weights $\unit[0.5]{kg}$ and it able to provide $\unit[25]{mins}$ of flight time. The platform is \gls{ros} compatible and can be used for research or teaching purposes. However, it does not have an onboard computer and provides a WiFi link so that all the computations should be on a ground station. Moreover, the user cannot modify or add extra sensors to the system, while there is no access to the low-level control architecture and sensor measurements. Another commercial product is the DJI Matrice 100~\cite{DJI}, which is a fully customizable and programmable flight platform that can be equipped with sensors required for performing an autonomous underground navigation, however it does not allow access to the low-level controllers and the raw sensor data, thus increasing the overall complexity for the fusion of new sensor measurements. Moreover, the basic price of the platform without the sensor suites and computing unit starts from $\unit[3300]{USD}$. Table~\ref{table:industrymav} compares commercial \glspl{mav} with the proposed platform, emphasizing on important factors such as cost, \gls{ros} compatibility, sensor measurement accessibility, etc. {\renewcommand{\arraystretch}{1.3} \begin{table}[htbp!] \centering \caption{The comparison of the existing \glspl{mav} with proposed platform.} \label{table:industrymav} \resizebox{\linewidth}{!}{ \begin{tabular}{cccccccc} \hline Platform & \rotatebox{90}{\parbox{1.5cm}{Cost}} & \rotatebox{90}{\parbox{2cm}{Sensors for autonomy}} & \rotatebox{90}{\parbox{2cm}{Computer unit}} & \rotatebox{90}{\parbox{2cm}{ROS}} & \rotatebox{90}{\parbox{2cm}{Data accessibility}} & \rotatebox{90}{\parbox{2cm}{Hardware Modification}} & \rotatebox{90}{\parbox{2cm}{Spare part availability}} \\ \hline \textbf{Proposed Platform} & Low & \checkmark & \checkmark & \checkmark & \checkmark & \checkmark & High \\ \hline Intel Aero & Low & Moderate & \checkmark & Moderate & \checkmark & \checkmark & Low \\ \hline DJI Matrice 100 & High & \xmark & \xmark & \checkmark & Moderate & \checkmark & High \\ \hline Yuneec H520 & High & Moderate & \xmark & \xmark & \xmark & \xmark & Moderate \\ \hline AscTec Neo & Very high & \xmark & \checkmark & \checkmark & \checkmark & \checkmark & Moderate \\ \hline \end{tabular}} \end{table} } There are multiple open-source platforms developed for teaching proposes, such as the CrazyFlie~\cite{giernacki2017crazyflie}, the Parrot Minidrone~\cite{MDrone} and the PiDrone~\cite{brand2018pidrone}. The CrazyFlie is a small quad-copter, which provides $\unit[4]{min}$ of flight time, without pay-load and due to its size, it cannot compensate wind-gusts. The parrot Minidrone has the same drawbacks as the CrazyFlie, while the platform is not \gls{ros} compatible, a factor that is drastically limiting its usage. The PiDrone is a \gls{ros} compatible quad-copter with an onboard Raspberry Pi that runs Python and provides a $\unit[7]{min}$ flight time. Additionally, the PiDrone provides an accessible and inexpensive platform for introducing students to robotics. The drawback of this platform is lack of proper sensor suites for dark tunnels and the corresponding limited computational power for advanced algorithms and methods such as \gls{vio}. Furthermore, within the related literature of \glspl{mav} in underground mining operations, few research efforts have been reported trying to address challenging tasks within the mine. In~\cite{schmid2014autonomous} a visual-inertial navigation framework has been proposed, while the system was experimentally evaluated in a real-scale tunnel environment, simulating a coal mine, where the illumination challenge was assumed solved, while the platform is based on Ascending Technologies Pelican quad-copter and the authors have performed a low-level adaptation of a commercial platform, which is a complex task. In~\cite{gohl2014towards}, a more realistic approach, compared to~\cite{schmid2014autonomous}, regarding the underground localization has been performed. The FireFly hexacopter from Ascending Technologies, equipped with a \gls{vi} and a Hokuyo URG-04LX 2D laser scanner was used and it was manually guided across a vertical mine shaft to collect data for post-processing. In~\cite{ozaslan2017autonomous}, the authors addressed the problem of estimation, control, navigation and mapping for autonomous inspection of tunnels using a DJI F550 platform equipped with a Velodyne PuckLITE lidar, four Chameleon3 cameras, a PixHawk optical flow and an Intel core i7 NUC PC. The overall approach was validated through field trials, however in this case a high-end and expensive sensor suit was utilized while flying. \section{Platform Architecture} \label{sec:platformartichecture} In this article, the proposed quad-copter is designed to be inexpensive, modular, autonomous, while it provides access to all the onboard raw sensor measurements. In the sequel, the hardware and software components of the overall architectures are discussed. \subsection{Hardware Components} The Enzo330 V2 330mm Wheelbase frame is selected, due to a dense market availability, low cost, durability and customizability. Figure~\ref{fig:frame} presents the corresponding frame structure. \begin{figure}[htbp] \centering \includegraphics[width=1\linewidth]{frame_s.png} \caption{The quad-copter frame.} \label{fig:frame} \end{figure} However, few modifications are performed to improve the frame functionality and durability as depicted in Figure~\ref{fig:top_frame}. The top part of the frame has been redesigned to allow installation of the computing unit, power modules and additional sensors. For durability reasons, the top part has been made out of carbon fiber. Additionally, extra damping for the flight controller was introduced to reduce the vast amount of vibrations generated by the motors. \begin{figure}[htbp] \centering \includegraphics[width=0.9\linewidth]{dampingWithComponents.png} \caption{Modified top part of the frame with components installed} \label{fig:top_frame} \end{figure} The landing gear has been designed and 3D printed to provide sufficient space for the sensors located on the bottom, such as an optical flow sensor and a front facing camera. Figure~\ref{fig:LTUplatfrom} depicts the modified proposed frame, equipped with sensor suits, while highlighting the dimensions of the platform. Moreover, the Multistar Elite 2308-1400 motors, carbon fiber T-Style 8x2.7 propellers and the Turnigy Multistar BLheli 32 ARM 4 in 1 32bit 31A \glspl{esc} have been selected based on the frame dimensions, estimated weight of the complete platform and the power required by the motors. \begin{figure*}[htbp!] \centering \includegraphics[width=1\linewidth]{pixy_new.png} \caption{The developed quad-copter equipped with a forward looking camera, LED lights, an optical flow, a 2D lidar and a single beam laser range finder.} \label{fig:LTUplatfrom} \end{figure*} Furthermore, to establish the autonomous flight, the proposed quad-copter is equipped with the hardware modules depicted in Figure~\ref{fig:hwmodule}, while Table~\ref{table:parts} provides the cost of each component and the total cost of the platform. In the following Table~\ref{table:parts} the core hardware components are discussed. \begin{figure}[htbp!] \centering \includegraphics[width=0.9\linewidth]{diagram4_new.png} \caption{The proposed quad-copter hardware components.} \label{fig:hwmodule} \end{figure} \begin{table}[htbp!] \caption{List of the components} \label{table:parts} \begin{tabular}{ccc} \hline \textbf{Subsystem} & \textbf{Item} & \textbf{Cost} \\ \hline Computation & Aaeon UP-Board & \$190.00 \\ Avionics & NAZE 32 REV 6 FCU & \$35.00 \\ Avionics & 4x Multistar Elite 2308-1400 Motors & \$85.00 \\ Avionics & Turnigy Multistar 4-in-1 ESC & \$45.00 \\ Avionics & 4x 8x2.7 carbon fiber propellers & \$10.00 \\ Avionics & Enzo330 Frame with upgraded top plate & \$30.00 \\ Sensors & RPLidar A2M8 & \$280.00 \\ Sensors & LIDAR-Lite 3 & \$130.00 \\ Sensors & PX4FLOW & \$135.00 \\ Sensors & PS3 Eye Camera & \$30.00 \\ Power & Battery and DC-DC converter & \$50.00 \\ Light & LED bars and current drivers & \$75.00 \\ \hline & \textbf{Total cost:} & \textbf{\$1095.00} \\ \hline \end{tabular} \end{table} \subsubsection{Flight Controller and On-board Computer} The ROSFlight~\cite{jackson2016rosflight} is an embedded autopilot system that provides high-rate sensor data to \gls{ros} and a simple \gls{api} for sending commands. Thus, the AfroFlight Naze32 Rev6 has been used as \gls{fcu} in the proposed platform. Moreover, the selection of the on-board computer is based on trade-off between the cost, performance, and weight. The on-board computer should provide enough computation power to execute an autonomous navigation, a state estimation, and proper vision algorithms. Based on the requirements, the \gls{sbc} Up-Board UP-CHT01 manufactured by Aaeon was selected. The Aaeon is equipped with a Quad Core Intel Atom x5-z8350 Processor, 4GB DDR3L-1600 memory and provides six USB 2.0 and one USB 3.0 \gls{otg} ports, while it weights $\unit[195]{g}$ \subsubsection{Sensor Suite} The main component and cost of the platform is the sensor suite. The 2D lidar scanner, the PX4 optical flow, the PlayStation 3 Eye camera and the single beam laser range finder have been selected to provide the required information for the algorithms to establish the autonomous navigation. The RPLidar A2M8 360 Degree Laser Scanner is the sensor that provides distance measurements of the surrounding. It uses a laser with a wavelength: $\unit[775]{nm}$ to $\unit[795]{nm}$ and provides an up to $\unit[15]{hz}$ scan frequency. The distance range is from $\unit[0.15]{m}$ to $\unit[12]{m}$, but measurements above $\unit[8]{m}$ are not reliable. Thus, above the $\unit[7]{m}$ the measurement data is not considered. In order to provide accurate altitude measurements, the LIDAR-Lite 3 Laser Rangefinder has been used as the main altitude sensor. It provides a range up to $\unit[40]{m}$ with the accuracy of $\unit[2.5]{cm}$. The sampling rate is set to $\unit[300]{hz}$. The rangefinder utilizes a laser $\unit[905]{nm}$ wavelength with a power of $\unit[1.3]{W}$. It should be highlighted that due to low temperature of the mine tunnels and vibrations of the frame, the PX4FLOW sonar sensor measurements are not reliable thus one beam range finder is used, although it has a higher cost. The autonomous navigation in the unknown environment requires a pose estimation, however in low-illumination environments the pose estimation may not be reliable. Thus, velocity estimation is provided by the PX4FLOW optical flow and it includes a synchronized MT9V034 machine vision CMOS sensor with a global shutter, together with a L3GD20 3D Gyroscope. The sensor allows processing images at $\unit[250]{hz}$ based on the on-board 168MHz Cortex M4F micro-controller. Finally, for collecting visual data, the PlayStation 3 Eye camera has been used that has the ability to capture a video stream with a resolution of $\unit[640 \times 480]{ pixels}$ with $\unit[60]{fps}$ or $\unit[320 \times 240]{ pixels}$ with $\unit[120]{fps}$. The camera has 56-75 degrees of horizontal field of view and the image stream can be used as \gls{ar} for human operator or vision based algorithms. \subsubsection{Additional light sources} Several extra light sources have been installed on the aerial platform to provide illumination for the visual sensors. Two $\unit[10]{W}$ LED bars have been installed on the front part of the quad-copters' arms and the constant current is provided by dedicated power LED drivers Recom RCD-24-0.70/W/X3. The drivers allow to modify the constant current, which will indicate a change in the light luminosity by \glspl{pwm} and analogue input signals. The measured light illumination on the $\unit[1]{m}$ distance from the \glspl{mav} with the maximum power utilized was $\unit[2200]{lux}$. Furthermore, the power LED bars and the drivers are placed under the propellers to utilize the airflow during the flight as a forced cooling. Additionally, 4 low power $\unit[10]{mm}$ LEDs have been installed on the bottom side of the \glspl{mav} for creating an optical flow sensor. \subsubsection{Battery} After multiple tests, the optimal battery has been selected given parameters such as size, weight, voltage and energy stored. Proposed battery, ZIPPY Compact 3300mAh 14.8V 40C 4S1P with weight of 360g provide flight time of $\unit[12]{min}$ in no wind conditions. \subsection{Software Architecture} \label{ref:softwareartichecture} The general scheme of the proposed software architecture is presented in Figure~\ref{fig:schematic}. The software architecture of the developed platform consists of the navigation, control, state estimation and visual feedback components. \begin{figure}[htbp] \centering \includegraphics[width=1\linewidth]{software_arch_new.png} \caption{The overall proposed software architecture for the navigation in the mine; For simplicity the sub-components are not shown.} \label{fig:schematic} \end{figure} The navigation component, based on the authors previous works~\cite{mansouri2020deploying, mansouri2018dl_tunnel} and~\cite{raad2018_tunnel}, incorporates data from the on-board front facing camera or the 2D lidar for following the tunnel axis. The output of the navigation component includes the heading rate command for the \gls{mav} to correct the \gls{mav} heading towards the tunnel axis and the velocity and altitude references for controller components to hover at a fixed altitude and to avoid collision in case the platform flies close to obstacles. Furthermore, a state estimation module provides estimated values for altitude $z$, velocities along $x,y,z$ axes and attitude (roll and pitch) of the platform from the IMU, the optical flow sensor and the downward looking laser range finder measurements. It should be highlighted that an accurate estimation of the heading angle is not possible as magnetometer is not reliable, especially in an underground mine and \gls{gnss} is not available for underground areas. Moreover, the navigation commands, as well as the state estimation outcome, are sent to the \gls{nmpc} controller~\cite{small_panoc_2018} component, which generates control commands (thrust, roll, pitch, yaw-rate) for the flight controller. Finally, the visual feedback component consists of the sequential stream of the on-board camera images, which can be used for \gls{ar}. \section{Platform Performance} \label{sec:platformperformance} This section describes the platform performance and results from each component, while the platform performs autonomous navigation in a real scale underground mine in Sweden~\cite{mansouri2019autonomous,mansouri2019vision}. Link: \url{https://youtu.be/dxMUx49a_uo} provides a video summary of the obtained results. The location of the field trials was $\unit[790]{m}$ deep, without any natural illumination sources and with a tunnel width of $\unit[6]{m}$ and a height of $\unit[4]{m}$. The area does not have strong corrupting magnetic fields, which could affect the platform sensors, while Figure~\ref{fig:mineboliden} depicts one part of the visited underground mine. \begin{figure}[htbp] \centering \includegraphics[width=1\linewidth]{tunnel1.png} \caption{Photo of a visited underground mine in Sweden.} \label{fig:mineboliden} \end{figure} During the performed experiment, the desired altitude was selected as $\unit[1]{m}$ with a constant velocity of $\unit[0.1]{m/s}$ aligned with the $x$-axis, while the platform is equipped with a PlayStation 3 Eye Camera and the LED light bars that provide a $\unit[460]{lux}$ illumination in $\unit[1]{m}$ distance. Moreover, a potential field method based on a 2D lidar was utilized for avoiding collisions to the tunneling walls, while measurements from a 2D lidar or a camera was used to correct the heading of the platform towards the open spaces or the tunnel axes respectively. The downward looking single beam laser range finder can be directly used for altitude regulation and Figure~\ref{fig:altitude} depicts the controlled achieved altitude over time for the proposed quad-copter during field trials in an underground tunnel. In this experimental case, there were no accurate height references available in the mine to evaluate the range finder measurements. However, from the overall performance of the platform, a constant altitude during the mission was successfully achieved. \begin{figure}[htbp!] \centering \includegraphics[width=1\linewidth]{rangefinder.png} \caption{Altitude measurements from the downward facing range finder over time during a test flight in an underground tunnel.} \label{fig:altitude} \end{figure} The 2D laser scanner was used by algorithms for obstacle avoidance and heading correction. The collected range measurements, during the flight, can be post processed to provide a 2D map of the area. The laser scans are processed from a Lidar SLAM method~\cite{hess2016real} that is available in the ROS framework, to generate a 2D occupancy map. The map characterizes the occupied and free space of the visited underground tunnel, while it is generated online with a 1Hz update rate and a resolution of $\unit[0.05]{m/pixel}$, while the robot covered an approximate distance of (x,y)=($\unit[70]{m}$,$\unit[85]{m}$) provided from the 2D lidar processing. Figure~\ref{fig:map} depicts the 2D map of the area. The platform successfully avoids collisions from the tunnel walls and corrects its heading towards the open spaces in multiple field tests in the mine\footnote{\url{https://youtu.be/dxMUx49a_uo}}. \begin{figure}[htbp!] \centering \includegraphics[width=1\linewidth]{lidar_cartographer.png} \caption{Obtained 2D map from laser scans while flying.} \label{fig:map} \end{figure} The velocity estimation for the developed system is provided from the optical flow system, however due to lack of features and illumination it is corrupted from noise measurements, thus the raw measurements were passed through low-pass filter. Figure~\ref{fig:flow} demonstrates the velocity state estimate during the field trials in the underground tunnel \begin{figure}[htbp] \centering \includegraphics[width=\linewidth]{rawfilter.png} \caption{Time evolution of the $v_x$ and $v_y$ raw (red) and filtered (blue) corresponding velocities measurements from the downward facing optical flow sensor during a test flight in an underground tunnel.} \label{fig:flow} \end{figure} \begin{figure}[htbp] \centering \includegraphics[width=\linewidth]{fig11.png} \caption{Example images collected from optical flow sensor.} \label{fig:optimg} \end{figure} The online information from the on-board sensors like the current altitude, \gls{mav} status, the 2D top down lidar map and the collision prediction can be overlaid to the image stream and displays to the operator as depicted in the attached video. \section{Conclusions\label{Conclusions}} In this work, a low-cost high-performance quad-copter has been proposed. The developed solution is ready to fly in underground tunnels while accomplishing inspection tasks. The operator of the platform has access to all sensor measurements, as well as the information for the \gls{mav} status, assisting the algorithm development, the software implementation and the overall operation both in the preparation of the mission as well as during the mission. Finally, the developed \gls{mav} has been deployed in an unknown dark underground tunnel and successfully performs fully autonomous navigation.
{'timestamp': '2020-06-01T02:08:05', 'yymm': '2005', 'arxiv_id': '2005.14433', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14433'}
arxiv
\section{Introduction} With 5G mobile systems being commercially rolling out gradually, research discussions into next-generation mobile systems, i.e., 6G, have started \cite{Latva-Aho2019}. 5G will incur 10 times energy consumption of 4G due to increased density of cells and that of antennas, though energy efficiency per bit has increased. With 6G going towards higher spectrum (such as Tera-Hertz or THz) and thus resulting in even denser networks and smaller cells, energy consumption will become a big hurdle on the way to 6G success. On the infrastructure side, a huge amount of energy will be consumed for powering numerous RF chains connected to a vast number of antennas, for extraordinary wideband signal processing, for maintaining a satisfactory coverage and for tracking mobile devices with super-narrow beams. Therefore, reducing energy consumption and jointly coordinating distributed infrastructure to achieve network-wide optimal energy efficiency constitute the first challenge in future 6G. On the other hand, the Internet of Everything (IoE), as envisioned as a major 6G application, means that a vast number of small devices will be connected to networks. These devices are typically either battery-powered or battery-less. However, conventional RF chain enabled communication as well as handshaking based access are both battery killers. In order to extend life-cycle of IoE devices, their energy harvesting capabilities from the ambient environment have to be activated. However, the communication performance of IoE devices is largely constrained by intermittent energy supplies. Therefore, designing super-low-power IoE transceivers and enabling an on-demand and cost-effective manner of energy supply to these IoE devices constitute the second challenge in future 6G. We envision 6G mobile systems have to be energy self-sustainable, both at the infrastructure side (such as traditional base stations) and at the device side (may it be in the form of smart phones or implanted brain computer interface devices), in order to be deployed at large and to achieve commercial success. There is a consensus that visible light (VL) communications will be an integral part of 6G in addition to the traditional medium/spectrum of radio frequency (RF) due to VL's unique properties like massive bandwidth, information security, economical, no harm to humans, etc. This paper serves to bring these two currently separate research domains, i.e., RF and VL, together to provide a full-spectrum 6G mobile system. A joint design that inherently considers both RF and visible light, shall be the methodology to be taken from the onset and in particular with energy self-sustainability borne in mind. Rather than reinventing new technologies into the already crowded family of 6G enabling technologies, this paper aims to explore how the existing members of this family such as THz, VL, intelligence reflecting surface (IRS) and AI can be explored for the energy self-sustainability. And this exploration needs to be conducted in a systematic and holistic manner at the design stage of 6G. Fortunately, each of these 6G candidate technologies provides promising potentials to empower energy self-sustainability. This paper endeavours to shed some light on potential solutions to energy supply issues in 6G with the hope to spark more discussion and research into this critical aspect of 6G mobile systems. It is this article's belief that 6G systems need to be energy self-sustainable and this feature decides 6G's wide commercial success in the future. For this purpose, this article firstly organizes the key 6G enabling technologies into a hierarchical system architecture for future 6G mobile systems, as presented in Section II. Without losing generosity, the presentation of the architecture is more tilted towards the angle of energy supply, which is the focus of this article. Guided by this architecture, mechanisms to potentially enable energy self-sustainability are discussed from two aspects: infrastructure side and IoE device side, respectively in Section III and IV. The infrastructure side focuses on the distributed access network layer with particular focus on three new features of 6G, namely, cell-free access networks and airborne access networks (the organization of the network) as well as smart surface (the composing materials of the network). On the IoE device side, discussions are given to high-resolution signal processing based wireless information and power transfer (WIPT), multifunctional IoE devices and human-in-the-loop based transceiver adaptation. \begin{figure}[t] \centering \includegraphics[width=0.9\linewidth]{figure/Structure.eps} \caption{Technical challenges and solutions towards energy self-sustainable 6G.}\label{fig:Structure} \setlength{\belowcaptionskip}{0pt} \setlength{\abovecaptionskip}{0pt} \end{figure} The contribution of the article lies in twofold. Firstly, it proposes a 6G mobile system architecture for the first time where the traditional base stations are decomposed into two complementing layers: central units (CUs) and distributed units (DUs). CUs are analogous to today's base stations in terms of their deployment locations but with more intelligence. DUs reside at very close proximity to end devices due to the employment of much higher frequency spectrum in 6G. DUs may be formed as a small cell-free network and using IRS. Secondly, these 6G enabling technologies are reinvestigated together with other new proposals, from the angle of energy self-sustainability by giving insightful discussions towards a commercially viable future 6G mobile systems. These investigations are centred around two complementing aspects: reducing energy consumption (i.e., energy efficiency) and opening new energy supplies. The technical challenges and solutions towards energy self-sustainable 6G are summarised in Fig. \ref{fig:Structure}. \section{Architecture of Energy self-sustainable 6G} \begin{figure}[t] \centering \includegraphics[width=0.9\linewidth]{figure/Architecture.eps} \caption{Architecture of energy self-sustainable 6G network}\label{fig:Arch} \setlength{\belowcaptionskip}{0pt} \setlength{\abovecaptionskip}{0pt} \end{figure} In order to achieve more stringent quality of service (QoS), 6G has to move up to even higher spectral bands than mmWave, such as THz and visible light band. However, 6G may still utilise sub-6 GHz and mmWave band, which are the legacy of 5G. Therefore, 6G is foreseen as a \emph{full-spectrum} mobile communication system. Different spectrum will be exploited for various objectives and applications: $1)$ \textit{Sub-6 GHz band} is used for large coverage and seamless handover; $2)$ \textit{mmWave band} is leveraged both for wireless backhaul and fronthaul to fixed targets and for satisfying high-rate requirement of mobile targets; $3)$ \textit{THz band} is used to provide ultra-high data rate and low-latency service for applications such as pervasive XR; $4)$ \textit{VL band} with extra bandwidth can be further exploited for delivering holographic tele-presence with other support of high-resolution imaging and sensing. VL cannot penetrate blockage and it is capable of creating a secure wireless communication. In this work, we focus on the access part of full-spectrum 6G networks. Our proposed energy self-sustainable architecture for 6G networks, as shown in Fig.~\ref{fig:Arch}, consists of three layers: 1) Central unit (CU), e.g., AI-empowered software RAN, 2) Distributed units (DUs), e.g. self-organised attocells and 3) zero-energy IoE device. The AI-empowered CU determines which spectrum and which DUs are used to serve a group of IoE devices. Based on the dynamics at the IoE devices and surrounding environments, the DUs form the exact cells to serve IoE devices. Each layer in the architecture, from different dimensions, can contribute to the energy sustainability of future 6G networks. The target of a CU is to provide demanded services to the IoE devices in an energy-efficient manner and/or with green energy (e.g., produced by nearby solar panel), all contributing to the network energy self-sustainability. For example, if the IoE device is within the indoor area where dense visible light or THz attocells are deployed, the IoE device can be served by these attocells which have the capability to provide both fast, ultra-reliable, and energy-efficient wireless connectivity. If the IoE device is approaching a passive DU that is equipped with intelligent surfaces, the IoE device could be guided by the AI-empowered central unit to switch to the cell of the passive DU, which could provide low- or even zero-energy wireless connectivity. If an outdoor IoE device requires high-speed wireless connections for applications such as XR, while in the surroundings a fixed-location and high-rate DU is not available, the AI-power CU can schedule a high-rate mobile DU to serve the IoE device. Drones or mobile robots can host the mobile DU. The backhaul enables WIPT to mobile DUs for achieving energy self-sustainability. Due to the complexity of decision making, new AI techniques such as deep reinforcement learning (DRL) is a necessity for problem solving. To avoid overwhelming the CU, some processing and decision making will be conducted at DUs under the coordination of the CU. A right balance between the CU and DU processing is a multi-objective optimization problem that may need DRL. Software defined networking (SDN) and network function virtualization (NFV) will continue to be evolved and then employed to dynamically deploy new QoS (Quality of Service) algorithms or controller on the fly. For most of the 6G DUs, we envision that a massive number of distributed antennas will be densely deployed to achieve both ultra-high reliability and wide coverage. As a result, many ground-breaking techniques could be enabled and leveraged in 6G. One of them is cell-free networking that can provide ultra-reliable and energy-efficient connectivity \cite{DenseVLC2020}. Also, cells formed by the DUs must adapt to surrounding dynamics to perform energy-efficient communication. For example, the attocells must react to dynamic blockages in the surroundings. IoE devices play essential roles in an energy self-sustainable 6G network. First, zero-energy IoE devices, which are powered by wideband WIPT, could be primarily deployed to provide massive connections and to realize IoE. For example, a large number of backscattering nodes can be connected to IRS enabled DUs to create an Internet of Trees, as illustrated in Fig.~\ref{fig:Arch}. Second, in our proposed architecture for future energy self-sustainable 6G networks, it is essential for IoE devices to adapt to the surrounding environment. The adaptation can be performed without the involvement of human beings, such as physically adjusting the receiving antennas to a better position to achieve higher data rates with less energy. Another possibility is the involvement of human beings. With wireless communications moving to THz and VL, the human body can easily block the surrounding wireless links. Therefore, the future 6G network could quickly become more energy-efficient if it guides human beings to position their bodies to recoup the blocked wireless communication links. \section{Distributed Units for Smart Access} Towards energy self-sustainability, every Joule of energy in 6G should be efficiently consumed in access networks by adopting the following methods: 1) Breaking cellular boundaries for globally scheduling DUs to deliver seamless services and to achieve network-wide energy efficiency; 2) Deploying flexible airborne access network to increase energy efficiency by further considering the vertical dimension and to realise wireless charging for battery-powered or batteryless devices from the sky; 3) Actively changing adverse wireless environment to be beneficial by implementing IRSs so as to substantially increase the efficiency of WIPT. \subsection{Cell-Free Access} In a cell-free massive MIMO (CFM-MIMO) system, a large number of DUs are connected to a CU via wired/wireless fronthaul. Joint coordination among these DUs results in cell-free access networks, where IoE devices are simultaneously served by cooperative BSs. Therefore, handover in a cell-free access network is different, since cellular boundaries are broken. Furthermore, joint coordination of a CU may achieve a network-wide energy efficiency \cite{Jiang2018}. However, full-cooperation among DUs may result in heavy tele-traffic load on fronthaul, since it requires the exchange of network state information, the transmission of transmit beamformers and requested information. In higher spectral bands of 6G, such as THz and VL, signal propagation suffers from significant penetration loss, if a lot of opaque obstacles are distributed in wireless environments. By further considering the increasing path-loss in high frequency bands, super-dense DUs have to be deployed for reducing distances and for ensuring line of sight (LoS) between DUs and IoE devices. However, more energy has to be consumed for powering such large-scale access network, while increased interference imposed by super-dense DUs has to be carefully managed and controlled. Furthermore, low-cost DUs can be equipped with solar panels for harvesting energy from ambient environment. They can be connected to smart grid to enable energy trade among their peers. As a result, global energy cooperation may result in an improved network-wide energy efficiency. As the number of DUs grows exponentially in cell-free access networks of 6G, wireless fronthaul is indispensable since the expense of deploying wired fronthaul cannot be afforded. RF signal based WIPT \cite{8421584} is an economic approach to transfer both information and energy from the CU to low-cost DUs via fronthaul in order to maintain energy self-sustainability. Due to hardware limitations, we only have limited RF chains at a THz based transmitter, which is far lower than the number of antennas compacted. Therefore, the accuracy of transmit beams cannot be guaranteed. Energy efficient hybrid transceiver consisting of both digital and analog beamformers is compromised for trying to achieve closest performance to the ideal full-digital solution \cite{8733134}. Moreover, in both THz and VL based cell-free access network, the assignment of DUs and that of antennas to IoE devices can be formulated as a network-wide energy efficiency maximisation problem, while satisfying various QoS requirements of devices, suppressing interference imposed by large-scale DUs and their associated antennas. Handover of mobile devices in cell-free access networks with densely deployed DUs faces novel challenges. Since the number of mobile devices is much lower than that of DUs, user-centric networking is the primary principle in a cell-free access network. Different from conventional handover, where mobile devices traverse across cells, a virtual cell dynamically formed by cooperative DUs tracks the movement of a mobile device, which constitutes a mobile cell serving a specific mobile device. Therefore, the formation of a dynamic virtual cell needs to be completed in real-time in order to provide seamless service experience, which calls for low-complexity heuristic algorithms with near-optimal performance. By exploiting up-to-date location information of mobile devices, we may significantly reduce the complexity of algorithms and increase the energy efficiency for virtual cell formation as well as for DUs/antennas assignment. Moreover, in a cell-free access network, synchronising densely deployed DUs is also essential. By exploiting the deterministic reflection of THz waves and VL, we may achieve over-the-air synchronisation among all the DUs. \subsection{Airborne Access} \begin{figure}[!t] \centering \includegraphics[width=0.8\linewidth]{figure/A_RAN.eps} \caption{Hierarchical aerial access network} \label{fig:ARAN} \end{figure} Different sorts of aircraft constitute hierarchical airborne access networks (AANs) by carrying RF/VL transceivers on board, as illustrated in Fig.~\ref{fig:ARAN}. Generally, based on their flying height, aircraft in AANs are classified into high-altitude platforms (HAPs) (e.g., high-altitude balloons and aircrafts) and low-altitude platforms (LAPs) (e.g., drones). AANs have to be energy self-sustainable, since we cannot provide stable power supply from the ground. Joint coordination among heterogeneous aircraft is capable of extending coverage of air-to-ground communication and of realising flexible network deployment as well as of providing efficient WIPT services. LAPs are mainly constituted by energy-constraint devices powered by embedded batteries, as portrayed in Fig.~\ref{fig:ARAN}. Therefore, 3D trajectories and flight control should be carefully designed in order to reduce energy consumption of aircraft, while achieving efficient-efficient downlink wireless power transfer (WPT) services, downlink/uplink wireless information transfer (WIT) services and computation offloading services to battery-powered or batteryless ground devices \cite{8805125}. Moreover, the energy consumption of ground devices can be substantially reduced, since flying LAPs reduce signal propagation distances to them. In addition, laser charging is an efficient way to power LAPs so as to extend their flight time, since it may focus a high amount of energy in a narrow beam. Laser beams are normally formed by ground stations or aircraft in HAPs. HAPs can be aloft in the air for a relatively long time, as illustrated in Fig.~\ref{fig:ARAN}. A key advantage of HAPs is their self-adjustable positions in order to maintain efficient WIPT towards LAPs. Moreover, HAPs can harvest stable solar energy for powering their engines and transceivers, since they are floating in the stratosphere \cite{9013552}. Careful coordination among aircraft in different layers may result in a network-wide optimal energy efficiency and it may provide significant performance gain in the vertical dimension of energy self-sustainable 6G. \subsection{Holographic Environment} Radiated RF/VL signals are weakened as they propagate in wireless channels, which may substantially degrade both WIPT performance. They may be absorbed, reflected and scattered by obstacles distributed in wireless environment. Signals from different propagation paths may be destructively combined, which results in substantial fading. Wireless channels become even worse in THz and VL band, since signals can be easily absorbed by large molecules and they can only be reflected \cite{Sheikh2020}. Therefore, in order to overcome more serious channel attenuation in THz and VL band, line-of-sight transmission path has to be guaranteed between a transmitter and receiver pair, while more energy has to be consumed for achieving satisfactory WIPT performance. In all classic communication systems, only transmission or receiving strategies at transceivers can be designed for efficient WIPT, such as beamforming, adaptive modulation and coding design at transmitters as well as signal combining and iterative decoding design at receivers, which all aim for counteracting signal attenuation and fading in wireless channels. This is because characteristics of wireless channels cannot be changed as exemplified in Fig. \ref{fig:Surfaces}. As electronic materials rapidly progress, IRSs can be exploited for actively changing characteristics of wireless channels. For example, based on signals' frequencies, phases and amplitudes, IRss can be intelligently adjusted, so that signals reflected by them can be constructively combined at receivers, as illustrated in Fig. \ref{fig:Surfaces}. As a result, we may artificially create a line-of-sight (LoS) transmission path in THz and VL band, when no actual LoS path exists between a transmitter and receiver pair. Therefore, received signal strength can be substantially increased without extra energy consumption, which results in more energy efficient WIPT. \begin{figure}[t] \centering \includegraphics[width=0.8\linewidth]{figure/Surfaces.eps} \caption{Basic back-end structure of IRSs and signal propagation with/without smart wireless environment.}\label{fig:Surfaces} \setlength{\belowcaptionskip}{0pt} \setlength{\abovecaptionskip}{0pt} \end{figure} IRSs are not equipped with any active RF chains, while they are not connected to any stable energy sources. As shown in Fig. \ref{fig:Surfaces}, a 2-dimensional IRS consists of a range of passive reflectors. Signals received by a reflector are then transferred to a programmable impedance matching network (IMN). By adjusting electronic components in this IMN, we may arbitrarily adjust its reflection coefficient. Therefore, A portion of received signals penetrate and their energy is harvested and stored in super-capacitors, as illustrated in Fig. \ref{fig:Surfaces}. The other portion are reflected via a programmable analog phase-shifter. Carefully designed phase-shifters may result in a constructive combination of reflected signals at the receiver. Note that programmable analog phase shifters and IMN have to be powered by energy harvested. Therefore, it is essential to design reflection coefficients for all reflectors. Higher reflection coefficients generate more strong reflected signals but limited energy can be harvested by the surface. Given insufficient energy harvested, we are only able to adjust several phase-shifters not all. Therefore, we have to jointly select which phase-shifters to be activated and how they change the phases of reflected signals in order to maximise the signal strength at the receiver. By contrast, lower reflection coefficients result in more energy harvested by the surface. Therefore, more phase-shifters can be activated, which results in well-tuned reflected signals. However, the strengths of the reflected signals are weak, which may degrade WIPT performance. In a nutshell, given an IRS, we need to jointly design reflection coefficients of all the reflectors, activation of phase-shifters and how they tune reflected signals. Furthermore, transmit beamforming at transmitters, intelligent reflecting at IRSs and receive combining at receivers can be jointly designed to create a holographic wireless environment in energy self-sustainable 6G \cite{Holographic}. \section{Zero-Energy IoE Devices} In energy self-sustainable 6G, battery-powered or batteryless IoE devices requires controllable and on-demand WPT for maintaining seamless service experience, while their energy consumption has to be kept as low as possible. Moreover, these IoE devices should also intelligently adapt their transceivers to environments for achieving more efficient information reception and energy harvesting. \begin{figure}[t] \centering \includegraphics[width=0.9\linewidth]{figure/Zero-Energy.eps} \caption{Wideband signal propagation and functional modules of zero-energy devices}\label{fig:Zero-Energy} \setlength{\belowcaptionskip}{0pt} \setlength{\abovecaptionskip}{0pt} \end{figure} \subsection{High-resolution Signal Processing based WIPT} RF signals can be exploited for flexible, controllable and on-demand WPT in any time and anywhere. On infrastructure side, we do not need any additional hardware implementation. Unmodulated and modulated RF signals can be relied upon for WIPT. We have to fully exploit characteristics of wideband signals for WIPT in energy self-sustainable 6G. There are full of scatters and reflectors in the propagation of RF/VL signals, which results in multi-path transmissions from a transmitter to a receiver. The number of identified paths at the receiver is determined by the following factors: \begin{itemize} \item Signal power $P_t$: a higher signal power results in a higher signal-to-noise-ratio (SNR) and clearer channel impulsive responses at the receiver. \item Signal bandwidth $W$: If the signal propagation delay between two transmission paths is higher than the coherence time $1/W$, this pair of paths cannot be identified. Otherwise, the receiver is capable of identifying these two transmission paths. \item Geographic positions of scatters and reflectors: Given a pair of transmission paths, if their distance have a difference of $c/W$, where $c$ is the speed of light, they can be identified at the receiver, otherwise they cannot. \end{itemize} Therefore, if we have an extremely high bandwidth $W$, more scatters and reflectors may generate more identified transmission paths \cite{Xu2018}. We do not rely upon coarse-grained signal processing on the basis of antenna-to-antenna. Instead, wide-bandwidth transmission in 6G creates a chance of high-resolution signal processing on the basis of identified transmission paths, which provides substantial spatial multiplexing and diversity gains for WIPT, as illustrated in Fig. \ref{fig:Zero-Energy}. By fully exploiting this additional degree of freedom in signal design and the resultant performance gain, we may also substantially reduce energy consumption of transmitters. \subsection{Multifunctional Transceiver} IoE devices should have ability of gleaning energy from downlink RF/VL signals, while their energy consumption has to be suppressed. Therefore, as portrayed in Fig. \ref{fig:Zero-Energy}, the following functional modules have to be implemented at IoE devices: 1) an IMN, which is a circuit to guarantee the alternative current (AC) energy carried by the received RF signals can be delivered to the back-end by matching the impedance of antennas and that of back-end's circuits; 2) an energy harvester, which is a circuit for rectifying AC energy carried by RF/VL signals to direct current (DC) in order to drive electronic loads or to charge energy storage units. Key electronic elements in rectifiers are diodes; 3) an energy storage unit can be either a battery or a super capacitor. Batteries have long-term energy storage capabilities, but its charging efficiency is low. Super-capacitors can only store energy for a short-term but its charging efficiency is very high. Corresponding to different QoS, we have the following pair of designs for batteryless IoE devices: \begin{itemize} \item High-rate wireless powered communication: IoE devices adopt a harvest-store-then-transmit protocol. In order to increase energy harvesting efficiency, we should guarantee a perfect impedance matching. Only when they have sufficient energy in their storage units, their active information transmissions commence via RF/VL chains. Therefore, IoE devices can obtain high-rate information transmissions \cite{7982605}. However, powering RF/VL chains is an energy-consuming task. \item Low-rate backscatter communication: IoE devices deliberately mismatch the impedance of the receiving antennas and the back-end circuits. Therefore, RF/VL signals received by antennas cannot penetrate to the back-end but backscattered instead. IoE devices can flexibly modulate their own information on backscattered signals in frequency and time domains. Therefore, IoE devices do not need any RF/VL chains for information transmission, which may substantially reduce energy consumption \cite{10.1145/3300061.3345451}. Furthermore, we can fully exploit the abundant full-spectrum of 6G by intelligently changing the frequencies of backscattered signals in order to avoid congested bands. However, IoE devices also need to harvest energy for powering their signal processing modules. Therefore, backscattering coefficients need to be carefully designed for allowing some of the received RF/VL signals flowing into the back-end for energy harvesting. The IMN of IoE devices should also be programmable. \end{itemize} Furthermore, we may integrate the above-mentioned designs into a single IoE, as exemplified in Fig. \ref{fig:Zero-Energy}. Therefore, low-rate control signalling or sporadic information transmissions can be completed by passive backscatter communication, while high-rate data transmissions can be completed by active wireless powered communication. \subsection{Human-in-the-loop} Signal propagation in these bands heavily relies on LoS between transmitters and receivers. If no LoS link exists, WIPT performance would severely degrade. In both indoor and outdoor scenarios, many objects in surrounding wireless environments may block LoS links, such as walls, cabinets, moving objects and etc. Moreover, human bodies are mostly neglected as critical blockages in the design of a communication system operating in high frequency bands, especially when hand-held communication devices are taken into account. \begin{figure}[t] \centering \includegraphics[width=0.9\columnwidth]{figure/adaptationtoenvironment.eps} \caption{Human-in-the-loop adaptation to the surrounding environment (BX: blockage)} \label{fig:adaptationtoenvironment} \end{figure} In order to improve WIPT performance, it is crucial for IoE devices to possess abilities of intelligently adapting their transceivers to dynamic wireless environments. This adaptation can be achieved without/with intervention from human users. For instance, reconfigurable antennas of IoE devices can be automatically adjusted to better positions in order to gain a higher information rate and to harvest more energy. Interactions between devices and human users may also result in environmental adaptation. These interactions are known as ``human-in-the-loop''. As illustrated in Fig.~\ref{fig:adaptationtoenvironment}, human users may rotate their bodies to enable LoS links. In a case study of VL based communication network, observe from the right part of Fig.~\ref{fig:adaptationtoenvironment} that allowing a rotation angle of $76^{\circ}$ achieve a system throughput gain of $81\%$~\cite{NutVLC}. The involvement of human users in transceiver adaptation becomes normal in our daily life. Human users holding devices always try to rotate their bodies to gain high information rates. This is more efficient in VL band of future 6G, since VL can be easily captured by human eyes. Human users may readily aim their devices to intensive VL. Autonomous transceiver adaptations naturally find wireless channels having lowest channel attenuation. Therefore, energy consumed by infrastructure to radiate RF/VL signals can be significantly reduced. Based on surrounding wireless environments, IoE devices may decide how to adapt themselves to reduce energy consumption in information transmission and reception as well as to increase energy harvested in downlink WPT, which is also a key step towards zero-energy devices. \section{Conclusion} This article provides a layered architecture of energy self-sustainable 6G in full-spectrum which consists of AI-empowered CUs, massively deployed DUs and IoE devices. In order to deal with a tremendous amount of energy consumed for satisfying unprecedented QoS requirements, key solutions are provided to cell-free access for joint coordination of DUs, airborne access for 3D networking and holographic environmental design enabled by IRSs for counteracting severe channel attenuation in THz and VL. Furthermore, we provide vital approaches to realise zero-energy IoE devices, such as high-resolution signal processing based WIPT, multifunctional transceivers without any batteries and active transceiver adaptation to dynamic environments. However, there are still numerous challenges of making energy self-sustainable 6G a practice, which calls for a joint effort from both academia and industry.
{'timestamp': '2020-06-01T02:07:53', 'yymm': '2005', 'arxiv_id': '2005.14430', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14430'}
arxiv
\section{Introduction} \IEEEPARstart{I}{n} machine learning, computer vision, data mining, and other fields, with the increase of the difficulty of research objects, we have to deal with some high-dimensional data, such as text data, image data, and various gene expression data. When processing high-dimensional data, we are confronted with the curse of dimensionality and some other difficulties caused by too many features, which not only makes the prediction results inaccurate, but also consumes the calculation time. So it is very important to process high dimensional data. There are three approaches to deal with high-dimensional data, i.e., feature extraction, feature compression and feature selection. Feature extraction generally maps data from high-dimensional space to low-dimensional space, such as principal component analysis (PCA), linear discriminant analysis (LDA) and neural networks. Feature compression compresses the original feature value to 0 or 1 by quantization. Feature selection uses some evaluation criteria to select feature subsets from the original feature set. In general, the features selected by feature selection method are more interpretable. In addition, the discrimination ability of the selected features is not weaker than that of the extracted or compressed features. As an effective mean to remove irrelevant features from high-dimensional data without reducing performance, feature selection has attracted many attentions in recent years. \par According to whether it is independent of the classification algorithm used later, the feature selection method can be categorized as filter, wrapper, and embedded methods \cite{wang2016sparse}. Filter method \cite{liu2013global, MingkuiMinimax} first selects features and then the feature subset obtained by filtering operation is used to train the classifier, so filter method is fully independent of the classifier. The essence of this method is to use some indexes in mathematical statistics to rank feature subsets, some popular evaluation criteria of filter methods include fisher score, correlation coefficient, mutual information, information entropy, and variance threshold. According to the objective function, wrapper method \cite{freeman2013feature}, \cite{xue2012particle} selects or excludes several features at a time until the best subset is selected. In other words, wrapper method wraps the classifier and feature selection into a black box, and evaluates the performance of the selected feature according to its accuracy on the feature subset. Embedded methods \cite{nie2014clustering}, \cite{mohsenzadeh2013relevance} get the weight coefficients of each feature by learning, and rank features according to the coefficients. The difference between the embedded and filter methods is whether determines the selection of features through training. \begin{figure*}[t] \centering \includegraphics[width=16cm]{fig2/fig1.png} \caption{High dimensional data (a) can preserve structure by multi-step Markov transition probability, through the corresponding minimum transition probability to connect more points or the maximum transition probability to fewer points to obtain the relationship between data points (b), and different structure preservation algorithms will get different relationship between data points (c). For the negative side (MMFS\_minP), the path connecting most data points will be discarded; while for the positive side (MMFS\_maxP), the path connecting minimum data points will be kept. After feature selection, these two algorithms can not only keep the intrinsic data structure, but also shorten the distance between data points in the same class (d) by the obtained relationships.} \label{Fig.main} \end{figure*} \par Since any tiny part of manifold can be regarded as Euclidean space, assuming that the data is a low dimensional manifold uniformly sampled in a high dimensional Euclidean space, manifold learning is to recover the low dimensional manifold structure from the high dimensional sampled data, that is, to find the low dimensional manifold in the high dimensional space, and find out the corresponding embedded mapping to achieve dimension reduction or data visualization. Some popular manifold learning methods include isometric feature mapping (ISOMAP) \cite{tenenbaum2000global}, Locally Linear Embedding (LLE) \cite{roweis2000nonlinear} and Laplacian eigenmaps (LE) \cite{belkin2002laplacian}, \cite{belkin2003laplacian}. From this research line, many unsupervised feature selection methods are proposed, such as \cite{zhao2007spectral}, \cite{he2006laplacian} and \cite{cai2010unsupervised}, which select features by the local structure information of data points, and these methods show that the local structure information is helpful to select the effective feature subset. However, most of these methods only use the structure information between adjacent data points, and the manifold structure of the whole data is not sufficiently employed. \par In this paper, inspired by the above analysis, we propose a new unsupervised feature selection approach called MMFS (Multi-step Markov transition probability for Feature Selection). As shown in Fig. 1, the core idea is to use multi-step transition probability to characterize data relationships on manifold. Based on the idea of keeping data structure, we do feature selection from both positive and negative aspects. On the positive side, the maximum multi-step transition probability that can be reached in a certain number of steps between any data pair is used to describe the compact data structure. The features which can better keep this data structure are selected. On the negative side, to characterize the loose data structure, the minimal multi-step transition probability that can be reached in a certain number of steps between any data pair is used. The features that least maintain this loose data structure are selected. These two ways are also be combined to form a new algorithm which can obtain average performance. Thus, three algorithms are proposed. The main contributions of our work can be summarized as follows. \par 1) A novel unsupervised feature selection approach is proposed, which can sufficiently use and keep data structure on manifold. Instead of directly using Euclidean distance, multi-step Markov transition probability is used to describe the data structure. \par 2) Different from the existing solutions, we design two algorithms from both positive and negative viewpoints. Features which better and least keep the corresponding data structures are selected. After feature selection, the data in the low-dimensional space will be more compact. \par 3) Comprehensive experiments are performed on eight benchmark data sets, which show the good performance of the proposed approach compared with the state-of-the-art unsupervised feature selection methods. \par The rest of this paper is organized as follows. Section \uppercase\expandafter{\romannumeral2} reviews some related work, and Section \uppercase\expandafter{\romannumeral3} presents the notations and definitions used in this paper. In Section \uppercase\expandafter{\romannumeral4}, we propose the new approach MMFS. The optimization method is presented in Section \uppercase\expandafter{\romannumeral5} and the experimental results are presented and analyzed in Section \uppercase\expandafter{\romannumeral6}. Finally, conclusions are given in Section \uppercase\expandafter{\romannumeral7}. \section{RELATED WORK} According to whether to use label information or not, feature selection methods can be divided into three different types: supervised feature selection, semi-supervised feature selection and unsupervised feature selection. Supervised feature selection methods with ground-truth class labels usually make full use of these ground-truth class labels to select more discriminative features. Most supervised methods valuate feature relevance based on the correlations of the features with the labels. e.g., Fisher Score \cite{gu2012generalized}, Relief-F \cite{robnik2003theoretical}, spectral analysis \cite{zhao2007semi}, trace ratio \cite{nie2008trace}, information entropy \cite{yu2003feature}, Pearson correlation coefficients \cite{lee1988thirteen}, mutual information \cite{peng2005feature}, \cite{yang2012effective}, and Hilbert Schmidt independence criterion \cite{song2007supervised}. Recently, some methods \cite{he20122}, \cite{cai2011multi} apply $l_{2,1}$-norm to improve the performance. A number of semi-supervise feature selection methods have been presented during the past ten years. Semi-supervised feature selection focuses on the problem of using a small number of labeled data and a large number of unlabeled data for feature selection. Most semi-supervised feature selection methods score the features based on a ranking criterion, such as Laplacian score, Pearson's correlation coefficient and so on. For example, Zhao et al. \cite{zhao2007semi} presented a semi-supervised feature selection method based on spectral analysis. The method proposed by Doquire et al. \cite{doquire2013graph} introduced a semi-supervised feature selection algorithm that relies on the notion of Laplacian score. And Xu et al. \cite{xu2016semisupervised} combined a max-relevance and min-redundancy criterion based on Pearson's correlation coefficient with semi-supervised feature selections. \par Unsupervised feature selection without any label information is more difficult and challenging. Because ground-truth class labels are costly to be obtained, it is desirable to develop unsupervised feature selection methods. Our method belongs to this category which will be detailed in the following. \subsection{Unsupervised Feature Selection Method} An important approach to achieving unsupervised feature selection is to select features by local structure information of data points. There are many ways to apply the local structure information of data points. In the early stage, the methods usually construct the affinity graph to get the local structure information first, and then select the features. For example, Zhao et al. \cite{zhao2007spectral} proposed a unified framework for feature selection based on spectral graph theory, which is based on general similarity matrix. \par In the later stage, these methods are able to simultaneously obtain structural information and do feature selection. Gu et al. \cite{gu2012locality} proposed a locality preserving feature selection method; it aims to minimize the locality preserving criterion based on a subset of features by learning a linear transformation. Hou et al.\cite{hou2013joint} defined a novel unsupervised feature selection framework, in which the embedding learning and sparse regression perform jointly. Nie et al. \cite{nie2016unsupervised} came up with an unsupervised feature selection framework, which can simultaneously performs feature selection and local structure learning. Shi et al. \cite{shi2016cluster} incorporated spectral clustering, discriminative analysis, and correlation information between multiple views into a unified framework. Zhao et al. \cite{zhao2015graph} presented an unsupervised feature selection approach, which selects features by preserving the local structure of the original data space via graph regularization and reconstructing each data point approximately via linear combination. An et al. \cite{an2017unsupervised} preserved locality information by a probabilistic neighborhood graph to select features and combined feature selection and robust joint clustering analysis. The method proposed by Fan et al. \cite{fan2017structure} can select more informative features and learn the structure information of data points at the same time. Dai et al. \cite{dai2018unsupervised} proposed method that each feature is represented by linear combination of other features while maintaining the local geometrical structure and the ordinal locality of original data. \par Adaptive methods are also introduced to select more effective features. The method proposed by Luo et al. \cite{luo2017adaptive} selects features by an adaptive reconstruction graph to learn local structure information, and imposing a rank constraint on the corresponding Laplacian matrix to learn the multi-cluster structure. Chen et al. \cite{chen2018local} came up with a local adaptive projection framework that can simultaneously learns an adaptive similarity matrix and a projection matrix. Zhang et al. \cite{zhang2019unsupervised} proposed a method that can make the similarities under different measure functions unify adaptively and induced $l_{2,0}$ constraint to select features. \par In addition, various methods are also used to achieve unsupervised feature selection. Some unsupervised feature selection methods removed redundant features to improve the performance. Li et al. \cite{li2018generalized} removed the redundant features and embedded the local geometric structure of data into the manifold learning to preserve the most discriminative information. Wang et al. \cite{wang2018hierarchical} selected features hierarchically to prune redundant features and preserve useful features. Nie et al. \cite{nie2018general} defined an auto-weighted feature selection framework via global redundancy minimization to select the non-redundant features. Xue et al. \cite{xue2019self} presented a self-adaptive algorithm based on EC method to solve the local optimal stagnation problem caused by a large number of irrelevant features. \subsection{Markov Walk} \par Our method MMFS is also closely related to the methods based on Markov random walks. Szummer et al. \cite{szummer2002partially} combined a limited number of labeled samples with Markov random walk representation on unlabeled samples to classify a large number of unlabeled samples. Haeusser et al. \cite{haeusser2017associative} used a two-steps Markov random walk on this graph that starts from the source domain samples and return to the same kind of samples through the target domain data in the embedded space. Sun et al. \cite{sun2019neural} proposed a method, which applying random walker to define the diffusion distance modules for measuring the distance among nodes on graph. Instead of their approaches, we use multi-step transition probability to characterize the data structure and try to select the feature subset which can keep the original data structure. \section{NOTATIONS AND DEFINITIONS} We summarize the notations and the definitions used in our paper. We denote all the matrices with boldface uppercase letters and vectors with boldface lowercase letters. For a matrix $\mathbf{M}$, the element in the $ {i_{th}} $ row and $ {j_{th}} $ column is represented as ${m_{ij}}$ , and the transpose of matrix $\mathbf{M}$ is denoted as ${\mathbf{M}^T} $. Its Frobenius norm is denoted by $ ||\mathbf{M}|{|_F} = \sqrt {\sum\nolimits_{i = 1}^n {\sum\nolimits_{j = 1}^m {m_{ij}^2} } } $. The $l_{2,1}$-norm of the matrix $\mathbf{M}$ is denoted as $ ||\mathbf{M}|{|_{2,1}} = \sum\nolimits_{i = 1}^n {\sqrt {\sum\nolimits_{j = 1}^m {m_{ij}^2} } } $. \begin{table}[] \caption{Notations with Descriptions} \centering \begin{tabular}{ll} \hline Notation & Description \\ \hline d & Dimensionality of data point \\ N & Number of instances in data matrix \\ \textbf{X} $\in {\mathbb{R}^{{\rm{d}} \times {\rm{N}}}}$ & Data matrix \\ \textbf{F} $\in {\mathbb{R}^{{\rm{N}} \times {\rm{d}}}}$ & Templates for feature selection \\ \hline \end{tabular} \end{table} \section{The Proposed Approach} Let $\mathbf{X} = [{{\mathbf{x}}_1}, \cdots, {{\mathbf{x}}_N}]$ denotes a $d$-dimensional data matrix consisting of $N$ instances. In this paper, we want to learn the spatial structure around each point, so that the final selected features can also reflect the spatial structure of the original data in high-dimensional space. In order to obtain the relationship between any two points, we achieve our purpose from negative and positive sides respectively. Multi-step transition probability is used to characterize the data spatial structure. Assume each data point in the high dimensional space is a node (state). Transition probability refers to the conditional probability that a Markov chain is in one state at a certain time, and then it will reach another state in another certain time. The one-step transition probability $ {\mathbf{P}_{ij}} $ from node $i$ to node $j$ can be defined as follows: \begin{equation} {\mathbf{P}_{ij}} = \displaystyle\frac{{{\mathbf{M}_{ij}}}}{{\sum\nolimits_{m = 1}^N {{\mathbf{M}_{im}}} }} \end{equation} where \begin{equation} \displaystyle\textbf{M}\mathop{{}}\nolimits_{{ij}}=\frac{{1}}{{{ \left( {{\left. {\frac{{\textbf{D}\mathop{{}}\nolimits_{{ij}}}}{{{\mathop{ \sum }\nolimits_{{m=1}}^{{N}}{\textbf{D}\mathop{{}}\nolimits_{{im}}}}}}+ \alpha } \right) }}\right. }}}. \end{equation} Furthermore, the self transition probability $\textbf{P}_{ii} = 0$ for any $i$ data point. Here, \textbf{D} is a matrix of Euclidean distances between data points and $\alpha$ is a very small constant to avoid the denominator becoming zero. The closer the distance is, the larger the transition probability is. It is well known that Euclidean distance does not make sense in high dimensional space. Fortunately, any tiny part of manifold can be regarded as Euclidean space, so the one-step transition probability can be computed between the data points that are very close to each other. Naturally, this problem can be converted to select the nearest $k$ points around any data point to calculate the transition probability. So we redefine the one-step probability $ {\mathbf{P}_{ij}}$. That is $\textbf{M}_{ii}$ = 0 and $ \textbf{M}_{ij} $ = 0 when the data point $j$ is not one of the $k$ nearest neighbors of data point $i$. Naturally, the $n$-step transition probability matrix can be calculated as \begin{equation} {\textbf{P}^{(n)}} = {\textbf{P}^{(n - 1)}}{\textbf{P}^{(1)}}. \end{equation} In the remaining parts, we will try to preserve the original data structure from the positive and negative sides and thus propose three algorithms. First, the algorithm based on the negative viewpoint is illustrated. Then, the algorithm from the positive side is presented. In the end, the third algorithm combing the positive and negative algorithms is proposed. \subsection{Unsupervised Feature Selection based on Minimum Multi-step Transition Probability} \par The first algorithm is called MMFS$\_$minP (Multi-step Markov transition probability for feature selection based on minimum probability). The relationship between a node and any other $n$-step reachable point is described by using the minimum transition probability, i.e., the minimum transition probability at some $t$ step, for $t\leq n$, where $n$ is a parameter. In this way, we can get a matrix $ \mathbf{V_{1}} \in {\mathbb{R}^{{\rm{N}} \times {\rm{N}}}}$ that each element represents the actual distance relationships between each data point and their $n$-step reachable points. Please note that $ {\mathbf{ {V_{1}}}_{ii}} $ = 0. In order to ensure that the sum of each row of the matrix $\mathbf{V}_1$ is $1$, we perform row-wise normalization over $\mathbf{V_{1}}$. Based on the minimum reachable relation matrix $V_1$ in $n$ steps, the data relationships are characterized. Thus, we have a template for feature selection as follows, \begin{equation} \mathbf{F_1} = \mathbf{V_1}{\mathbf{X}^T}. \end{equation} Since we select the $k$ nearest points of each data point to determine the actual distance relationship between the two points, this allows our template naturally maintains the manifold structure. So, we have the following objection, \begin{equation} \mathop {\min }\limits_\textbf{w} ||{\textbf{X}^T}\textbf{W} - \mathbf{F_1}||_F^2 + \lambda ||\textbf{W}||_{2,1}^2 \end{equation} where $\mathbf{W}\in {\mathbb{R}^{{\rm{d}} \times {\rm{d}}}} $ is the weight matrix to make the original data approach to the constructed template $ \mathbf{F_{1}} $. The first term denotes the error between each weighted sample and the template. The second regularization term is used to force the weight matrix \textbf{W} to be row sparse for feature selection. $ \lambda > $ 0 is a regularization parameter used to balance the first and second terms. Since the minimum transition probability is used to construct the relationship matrix $ \mathbf{V_1} $, we actually obtain the loose relationship between data points. We should choose those features which do not keep these relationships. Thus, after feature selection, the distance between data points in the same class should be shorten. So we arrange the row vectors of the optimized \textbf{W} in ascending order according to the value of $l_2$ norm; the first $s$ features are selected. \begin{table}[t] \centering \begin{tabular}{p{8cm}} \hline \textbf{Algorithm 1} MMFS\_minP \\ \hline \textbf{Input:} Data matrix \textbf{X}, the parameter $ \lambda $, the steps $n$ and the selected feature number $s$. \\ \textbf{Initialize:} \textbf{Q} as an identity matrix. \\ \textbf{while} not converge \textbf{do} \\ \quad 1. Update $ {\textbf{W}_{t + 1}} = {\left( {\textbf{X}{\textbf{X}^T} + \lambda \textbf{Q}} \right)^{ - 1}}\textbf{X}\mathbf{F_1} $ . \\ \quad 2. Update the diagonal matrix $ {\textbf{Q}_{t + 1}} $ , where the $ {j_{th}} $ diagonal element is $ \frac{{\sum\nolimits_{i = 1}^d {\sqrt {||{\textbf{W}^i}||_2^2 + \varepsilon } } }}{{\sqrt {||{\textbf{W}^{\rm{j}}}||_2^2 + \varepsilon } }} $ \\ \quad 3. $t = t + 1$. \\ \textbf{ end while} \\ \textbf{Output:} Obtain optimal matrix \textbf{W} and calculate each $\|{\textbf{W}^i}|{|_2},i = 1,2,\cdots,d$, then sort in ascending order and select the $s$ top ranking features.\\ \hline \end{tabular} \end{table} \subsection{Unsupervised Feature Selection based on Maximum Multi-step Transition Probability} \par The second algorithm is called MMFS$\_$maxP (Multi-step Markov transition probability for feature selection based on maximum probability). Instead of the first algorithm, we use the maximum transition probability to express the relationship between the data point and any other reachable points in $n$ steps, i.e., the corresponding step is recorded as $t$ where $t \leq n$. As the same as above subsection, we can get a relational matrix $ \mathbf{V_2} $, and normalize the matrix $ \mathbf{V_2} $ by rows. Finally, we get the template as the following, \begin{equation} \mathbf{F_2} = \mathbf{V_2}{\textbf{X}^T}. \end{equation} Then the objective function of the proposed MMFS\_maxP method is \begin{equation} \mathop {\min }\limits_\textbf{w} ||{\textbf{X}^T}\textbf{W} - \mathbf{F_2}||_F^2 + \lambda ||\textbf{W}||_{2,1}^2. \end{equation} Different from the method MMFS\_minP, since we use the corresponding maximum transition probability to construct the relationship matrix $\mathbf{V_2} $ which represents a more compact relationship, we should choose features from the positive viewpoint. In order to shorten the distance between data points in the same class, we should select the first $s$ features in descending order according to the value of $l_2$ norm of the optimized matrix \textbf{W}. \subsection{The Combination of Two Algorithms } In order to combine the above two algorithms, we propose an algorithm called MMFS\_inter. We first find the intersection of the features selected by MMFS\_minP and MMFS\_maxP, and set the number of features in the intersection as $s_1$. Suppose the number of features required to be selected is $s$, when the number of features from the intersection is not enough, we select the first $(s-s_1)/2 $ features from the feature sequences selected by the above two algorithms. \begin{table}[t] \centering \begin{tabular}{p{8cm}} \hline \textbf{Algorithm 2} MMFS\_maxP \\ \hline \textbf{Input:} Data matrix \textbf{X}, the parameter $ \lambda $, the steps $n$ and the selected feature number $s$. \\ \textbf{Initialize:} \textbf{Q} as an identity matrix. \\ \textbf{while} not converge \textbf{do} \\ \quad 1. Update $ {\textbf{W}_{t + 1}} = {\left( {\textbf{X}{\textbf{X}^T} + \lambda \textbf{Q}} \right)^{ - 1}}\textbf{X}\mathbf{F_2} $ . \\ \quad 2. Update the diagonal matrix $ {\textbf{Q}_{t + 1}} $, where the $j$th diagonal element is $ \frac{{\sum\nolimits_{i = 1}^d {\sqrt {||{\textbf{W}^i}||_2^2 + \varepsilon } } }}{{\sqrt {||{\textbf{W}^{\rm{j}}}||_2^2 + \varepsilon } }} $ \\ \quad 3. $t = t + 1$. \\ \textbf{ end while} \\ \textbf{Output:} Obtain optimal matrix \textbf{W} and calculate each $\|{\textbf{W}^i}|{|_2},i = 1,2,\cdots,d $, then sort in descending order and select the $s$ top ranking features.\\ \hline \end{tabular} \end{table} \section{optimization} In this section, a common model is applied to describe the optimization steps for the above two objectives: \begin{equation} \mathop {\min }\limits_\textbf{w} ||{\textbf{X}^T}\textbf{W} - \textbf{F}||_F^2 + \lambda ||\textbf{W}||_{2,1}^2. \end{equation} Obviously, $ ||\textbf{W}||_{2,1} $ can be zero in theory, but this will cause the problem (8) to be non-differentiable. To avoid this situation, $ ||\textbf{W}||_{2,1}^2 $ is regularized as $ {\left( {\sum\nolimits_{j = 1}^d {\sqrt {||{\textbf{W}^{\rm{j}}}||_2^2 + \varepsilon } } } \right)^2} $ where $ \varepsilon $ is a small enough constant. It follows that \begin{equation} \mathop {\min }\limits_\textbf{w} \left( {||{\textbf{X}^T}\textbf{W} - \textbf{F}||_F^2 + \lambda {{\left( {\sum\nolimits_{j = 1}^d {\sqrt {||{\textbf{W}^{\rm{j}}}||_2^2 + \varepsilon } } } \right)}^2}} \right). \end{equation} This problem is equal to problem (8) when $ \varepsilon $ is infinitely close to zero. Assume the function \begin{equation} L(\textbf{W}) = ||{\textbf{X}^T}\textbf{W} - \textbf{F}||_F^2 + \lambda {\left( {\sum\nolimits_{j = 1}^d {\sqrt {||{\textbf{W}^{\rm{j}}}||_2^2 + \varepsilon } } } \right)^2}. \end{equation} \par Finding the partial derivative of L (\textbf{W}) with respect to \textbf{W}, and setting it to zero, we have \begin{equation} \frac{{\partial L(\textbf{W})}}{{\partial \textbf{W}}} = 2\textbf{X}({\textbf{X}^T}\textbf{W} - \textbf{F}) + 2\lambda \textbf{Q}\textbf{W} = 0, \end{equation} where \textbf{Q} is a diagonal matrix whose $ {j_{th}}$ diagonal element is \begin{equation} {q_{jj}} = \frac{{\sum\nolimits_{i = 1}^d {\sqrt {||{\textbf{W}^i}||_2^2 + \varepsilon } } }}{{\sqrt {||{\textbf{W}^{\rm{j}}}||_2^2 + \varepsilon } }}. \end{equation} The matrix \textbf{Q} is unknown and depends on \textbf{W}, we solve \textbf{Q} and \textbf{W} iteratively. With the matrix \textbf{W} fixed, \textbf{Q} can be obtained by Eq. (12). When the matrix \textbf{Q} fixed, according to Eq. (11), we can get $\mathbf{W}$ as follows, \begin{equation} \textbf{W} = {\left( {\textbf{X}{\textbf{X}^T} + \lambda \textbf{Q}} \right)^{ - 1}}\textbf{X}\textbf{F}. \end{equation} We presents an iterative algorithm to find the optimal solution of \textbf{W}. In each iteration, \textbf{W} is calculated with the current \textbf{Q}, and the \textbf{Q} is updated according to the current calculated \textbf{W}. The iteration procedure is repeated until the algorithm converges. \par Based on the above analysis, we summarize the whole procedure for solving problem (5) in Algorithm 1 and the procedure for solving problem (7) in Algorithm 2. \begin{table}[t] \caption{Descriptions of Data Sets} \centering \begin{tabular}{llllll} \hline ID &Data set &\# Instances &\# Features &\# Classes &Data type\\ \hline 1 & Isolet1 & 1560 & 617 & 26 &Speech data\\ 2 & COIL20 & 1440 & 1024 & 20 &Object image\\ 3 & TOX-171 & 171 & 5748 & 4 &Microarray\\ 4 & Lung & 203 & 3312 & 5 &Microarray\\ 5 & AT\&T & 400 & 644 & 40 &Face image\\ 6 & ORL10P & 100 & 10304 & 10 &Face image\\ 7 & YaleB & 2414 & 1024 & 38 &Face image\\ 8 & USPS & 9298 & 256 & 10 &Digit\\ \hline \end{tabular} \end{table} \begin{table*}[t] \caption{Accuracy (acc\%$ \pm $std\%) of different unsupervised feature selection methods. \protect\\ The best result are enlighten in bold and the second best is underlined.} \centering \begin{tabular}{lllllllll} \hline Datasets & Isolet1 & COIL20 & AT\&T & YaleB & USPS & ORL10P & Lung & TOX\-171 \\ \hline All Features & 58.21 $ \pm $ 3.48 & 58.77 $ \pm $ 5.05 & 60.84 $ \pm $ 3.63 & 9.61 $ \pm $ 0.64 & 65.63 $ \pm $ 2.75 & 67.04 $ \pm $ 7.92 & 69.23 $ \pm $ 9.11 & 42.16 $ \pm $ 2.63 \\ LS & 59.36 $ \pm $ 3.60 & 54.97 $ \pm $ 4.39 & 59.71 $ \pm $ 3.28 & 9.98 $ \pm $ 0.48 & 62.49 $ \pm $ 4.16 & 61.91 $ \pm $ 6.86 & 60.44 $ \pm $ 9.26 & 39.60 $ \pm $ 4.38 \\ MCFS & 60.74 $ \pm $ 3.88 & 58.93 $ \pm $ 4.76 & 61.13 $ \pm $ 3.62 & 9.73 $ \pm $ 0.71 & 64.96 $ \pm $ 4.04 & 68.31 $ \pm $ 8.03 & 64.66 $ \pm $ 7.93 & 40.58 $ \pm $ 3.07 \\ UDFS & 57.92 $ \pm $ 3.33 & 59.79 $ \pm $ 4.34 & 60.75 $ \pm $ 3.40 & 11.36 $ \pm $ 0.62 & 63.46 $ \pm $ 1.69 & 65.27 $ \pm $ 6.83 & 66.13 $ \pm $ 9.57 & 43.29 $ \pm $ 3.10 \\ NDFS & 64.50 $ \pm $ 4.19 & 59.54 $ \pm $ 4.52 & 60.53 $ \pm $ 3.35 & 12.12 $ \pm $ 0.69 & 65.05 $ \pm $ 3.41 & 67.23 $ \pm $ 7.98 & 66.79 $ \pm $ 8.81 & \textbf{45.12 $ \pm $ 3.27} \\ RUFS & 62.48 $ \pm $ 3.97 & 60.14 $ \pm $ 4.45 & 61.28 $ \pm $ 3.35 & \textbf{14.66 $ \pm $ 0.91} & \underline{65.78 $ \pm $ 2.88} & 68.52 $ \pm $ 7.79 & 68.38 $ \pm $ 8.44 & 44.39 $ \pm $ 2.84 \\ AUFS & 48.77 $ \pm $ 2.69 & 57.23 $ \pm $ 4.31 & 61.82 $ \pm $ 3.14 & 11.17 $ \pm $ 0.48 & 63.37 $ \pm $ 3.11 & 66.82 $ \pm $ 6.78 & 70.14 $ \pm $ 9.62 & 44.19 $ \pm $ 2.49 \\ MMFS\_minP & \textbf{70.39 $ \pm $ 2.25} & 59.08 $ \pm $ 3.99 & \underline{68.51 $ \pm $ 2.83} & \underline{14.50 $ \pm $ 0.67} & 65.52 $ \pm $ 2.99 & 65.20 $ \pm $ 5.93 & 57.41 $ \pm $ 7.54 & \underline{44.47 $ \pm $ 3.26} \\ MMFS\_maxP & 64.87 $ \pm $ 3.35 & \textbf{65.60 $ \pm $ 2.87} & 68.20 $ \pm $ 2.28 & 9.50 $ \pm $ 0.34 & \textbf{68.13 $ \pm $ 2.70} & \textbf{81.60 $ \pm $ 6.54} & \textbf{73.20 $ \pm $ 9.98} & 42.78 $ \pm $ 3.62 \\ MMFS\_inter & \underline{67.20 $ \pm $ 3.09} & \underline{65.14 $ \pm $ 2.86} & \textbf{69.58 $ \pm $ 2.57} & 12.47 $ \pm $ 0.35 & 65.24 $ \pm $ 3.45 & \underline{78.70 $ \pm $ 4.26} & \underline{70.76 $ \pm $ 7.86} & 43.95 $ \pm $ 3.53\\ \hline \end{tabular} \end{table*} \begin{table*}[t] \caption{NMI (NMI\%$ \pm $STD\%) of different unsupervised feature selection methods. \protect\\the best result are enlighten in bold and the second best is underlined.} \centering \begin{tabular}{lllllllll} \hline Datasets & Isolet1 & COIL20 & AT\&T & YaleB & USPS & ORL10P & Lung & TOX-171 \\ \hline All Features & 74.35 $ \pm $ 1.58 & 73.71 $ \pm $ 2.44 & 80.51 $ \pm $ 1.82 & 12.98 $ \pm $ 0.80 & 60.88 $ \pm $ 0.92 & 75.82 $ \pm $ 5.19 & 57.58 $ \pm $ 5.55 & 13.65 $ \pm $ 3.31 \\ LS & 74.71 $ \pm $ 1.60 & 69.99 $ \pm $ 1.99 & 78.75 $ \pm $ 1.63 & 14.77 $ \pm $ 0.74 & 59.62 $ \pm $ 1.95 & 68.30 $ \pm $ 4.11 & 43.05 $ \pm $ 4.75 & 8.36 $ \pm $ 2.95 \\ MCFS & 74.60 $ \pm $ 1.77 & 73.35 $ \pm $ 2.35 & 80.16 $ \pm $ 1.85 & 14.16 $ \pm $ 0.91 & 60.98 $ \pm $ 1.75 & 75.54 $ \pm $ 5.24 & 45.79 $ \pm $ 4.71 & 10.18 $ \pm $ 2.01 \\ UDFS & 73.30 $ \pm $ 1.88 & 72.63 $ \pm $ 2.11 & 79.70 $ \pm $ 1.71 & 17.61 $ \pm $ 0.70 & 58.24 $ \pm $ 0.74 & 73.29 $ \pm $ 4.12 & 47.72 $ \pm $ 6.59 & 15.31 $ \pm $ 5.09 \\ NDFS & 77.86 $ \pm $ 1.66 & 73.88 $ \pm $ 2.29 & 79.80 $ \pm $ 1.66 & 19.29 $ \pm $ 0.79 & 60.62 $ \pm $ 1.39 & 75.06 $ \pm $ 4.94 & 48.35 $ \pm $ 4.94 & \underline{18.12 $ \pm $ 4.31} \\ RUFS & 76.70 $ \pm $ 1.75 & 73.93 $ \pm $ 2.32 & 80.54 $ \pm $ 1.70 & \underline{23.00 $ \pm $ 0.77} & 61.50 $ \pm $ 1.34 & 77.32 $ \pm $ 4.69 & 50.12 $ \pm $ 5.42 & 16.41 $ \pm $ 4.06 \\ AUFS & 65.67 $ \pm $ 1.50 & 72.36 $ \pm $ 2.27 & 81.02 $ \pm $ 1.66 & 17.93 $ \pm $ 1.01 & 59.60 $ \pm $ 1.18 & 77.15 $ \pm $ 4.78 & 51.78 $ \pm $ 4.85 & 15.89 $ \pm $ 3.94 \\ MMFS\_minP & \underline{79.32 $ \pm $ 1.1}3 & 74.38 $ \pm $ 1.54 & 84.74 $ \pm $ 1.38 &\textbf{24.60 $ \pm $ 0.68} & \underline{61.69 $ \pm $ 0.74} & 73.27 $ \pm $ 3.39 & 45.51 $ \pm $ 4.08 & \textbf{20.72 $ \pm $ 3.59} \\ MMFS\_maxP & 78.42 $ \pm $ 0.98 & \textbf{78.03 $ \pm $ 1.71} & \underline{85.35 $ \pm $ 0.85/} & 14.95 $ \pm $ 0.33 & \textbf{64.13 $ \pm $ 1.52} & \textbf{85.96 $ \pm $ 2.85} & \textbf{61.56 $ \pm $ 4.96} & 15.10 $ \pm $ 3.77 \\ MMFS\_inter & \textbf{79.49 $ \pm $ 1.30} & \underline{77.02 $ \pm $ 1.68} & \textbf{85.73 $ \pm $ 1.06} & 20.76 $ \pm $ 0.38 & 61.36 $ \pm $ 0.93 & \underline{84.34 $ \pm $ 2.20 }& \underline{60.16 $ \pm $ 3.55} & 17.55 $ \pm $ 7.11\\ \hline \end{tabular} \end{table*} \section{Experiments} In this section, we test the proposed feature selection method in publicly available data sets and compare our methods with several state-of-the-art methods. \subsection{Data Sets} In order to validate the method proposed in this paper, the experiments are conducted on 8 benchmark data sets. The details of these 8 data sets are also summarized in Table \uppercase\expandafter{\romannumeral2}. \subsubsection{Isolet1 \cite{fanty1991spoken}} It contains 1560 voice instaces for the name of each letter of the 26 alphabets. \subsubsection{COIL20 \cite{nene1996columbia}} It contains 20 objects. The images of each objects were taken 5 degrees apart as the object is rotated on a turntable and each object has 72 images. The size of each image is 32$ \times $32 pixels, with 256 grey levels per pixel. Thus, each image is represented by a 1024-dimensional vector. \subsubsection{AT\&T \cite{samaria1994parameterisation}} It contains 40 classes, and each person has 10 images. We simply use the cropped images and the size of each image is 28$ \times $23 pixels. \subsubsection{YaleB \cite{georghiades1998illumination}} It contains 2414 images for 38 individuals. We simply use the cropped images and the size of each image is 32$ \times $32 pixels. \subsubsection{USPS \cite{hull1994database}} The USPS handwritten digit database. It contains 9298 16$ \times $16 handwritten images of ten digits in total. \subsubsection{ORL10P \cite{samaria1994parameterisation}} It contains 100 instances for 10 classes. And each image is represented by a 10304-dimensional vector. \subsubsection{Lung \cite{bhattacharjee2001classification}} It contains 5 classes and 203 instances in total, where each instance consists of 3312 features. \subsubsection{TOX-171 \cite{stienstra2010kupffer}} It contains 171 instances in four categories and each instance has 5748 features. \subsection{Experimental Setting} In order to prove the efficiency of the proposed approach, on each data set, we compare the proposed algorithms with the following six unsupervised feature selection methods. \subsubsection{Baseline} All features. \subsubsection{Laplacian Score (LS) \cite{he2006laplacian}} It evaluated the importance of features according to the largest Laplacian scores, which used to measure the power of locality preservation. \subsubsection{Multi-Cluster Feature Selection (MCFS) \cite{cai2010unsupervised}} According to the spectral analysis of the data and $L_1$-regularized models for subset selection, it select those features that the multi-cluster structure of the data can be best preserved. \subsubsection{Unsupervised Discriminative Feature Selection (UDFS) \cite{yang2011l2}} It selects features through a joint framework that combines the discriminative analysis and $l_{2,1}$-norm-norm minimization. \subsubsection{Nonnegative Discriminative Feature Selection (NDFS) \cite{li2012unsupervised}} In order to select the most discriminative features, NDFS performs spectral clustering to learn the cluster labels of the input samples and adds $l_{2,1}$-norm minimization constraint to reduce the redundant or even noisy features. \subsubsection{Robust Unsupervised Feature Selection (RUFS) \cite{qian2013robust}} It selects features by a joint framework of local learning regularized robust nonnegative matrix factorization and $l_{2,1}$-norm minimization. \subsubsection{Adaptive Unsupervised Feature Selection (AUFS) \cite{qian2015joint}} It uses a joint adaptive loss for data fitting and a $l_{2,0}$ minimization for feature selection. \par For LS, MCFS, UDFS, NDFS, RUFS, AUFS, and MMFS, we fixed the number of neighbors as 5 for all data sets. As for regularization parameter $ \lambda $ in problem (9), the optimal parameter is selected at the candidate set \{0.001, 0.01, 0.1, 1, 10, 100, 1000\}, and parameter $n$ is selected at the set \{5, 6, 7, ..., 18, 19, 20\}. In order to make a fair comparison between different unsupervised feature selection methods, we fix the number of the selected features as {50, 100, ..., 250, 300} for all data sets except the USPS data set. For USPS, the number of the selected features was set to {50, 80, ..., 170, 200}, because its total number of features is 256. \begin{figure*} \centering \subfigure[]{ \label{Fig.sub.a} \includegraphics[width=3.9cm]{fig2/acc_isolet.png}} \subfigure[]{ \label{Fig.sub.b} \includegraphics[width=3.9cm]{fig2/acc_coil.png}} \subfigure[]{ \label{Fig.sub.c} \includegraphics[width=3.9cm]{fig2/acc_att.png}} \subfigure[]{ \label{Fig.sub.d} \includegraphics[width=3.9cm]{fig2/acc_yale.png}} \subfigure[]{ \label{Fig.sub.e} \includegraphics[width=3.9cm]{fig2/acc_usps.png}} \subfigure[]{ \label{Fig.sub.f} \includegraphics[width=3.9cm]{fig2/acc_orl.png}} \subfigure[]{ \label{Fig.sub.g} \includegraphics[width=3.9cm]{fig2/acc_lung.png}} \subfigure[]{ \label{Fig.sub.h} \includegraphics[width=3.9cm]{fig2/acc_tox.png}} \caption{ACC of various feature selection methods with different number of selected features. (a) Isolet1. (b) COIL20. (c) AT\&T. (d) YaleB. (e) USPS. (f) ORL10P. (g) Lung. (h)TOX-171} \label{Fig.main} \end{figure*} \begin{figure*}[t] \centering \subfigure[]{ \label{Fig.sub.a} \includegraphics[width=3.9cm]{fig2/nmi_isolet.png}} \subfigure[]{ \label{Fig.sub.b} \includegraphics[width=3.9cm]{fig2/nmi_coil.png}} \subfigure[]{ \label{Fig.sub.c} \includegraphics[width=3.9cm]{fig2/nmi_att.png}} \subfigure[]{ \label{Fig.sub.d} \includegraphics[width=3.9cm]{fig2/nmi_yale.png}} \subfigure[]{ \label{Fig.sub.e} \includegraphics[width=3.9cm]{fig2/nmi_usps.png}} \subfigure[]{ \label{Fig.sub.f} \includegraphics[width=3.9cm]{fig2/nmi_orl.png}} \subfigure[]{ \label{Fig.sub.g} \includegraphics[width=3.9cm]{fig2/nmi_lung.png}} \subfigure[]{ \label{Fig.sub.h} \includegraphics[width=3.9cm]{fig2/nmi_tox.png}} \caption{NMI of various feature selection methods with different number of selected features. (a) Isolet1. (b) COIL20. (c) AT\&T. (d) YaleB. (e) USPS. (f) ORL10P. (g) Lung. (h)TOX-171} \label{Fig.main} \end{figure*} \par We use K-means clustering algorithm to perform the clustering task. Since K-means clustering is sensitive to its initialization of the clustering seeds, we repeat the experiments 20 times with random initialization of the seeds, and record the mean and standard deviation of ACC and NMI. Given a data set, let $ {p_i}$ and $ {q_i}$ be the labels obtained by clustering algorithm and the labels provided by data set respectively. And the ACC \cite{wang2016sparse} can be defined as follows: \begin{equation} ACC = \frac{{\sum\nolimits_{i = 1}^n {\delta \left( {{p_i},\mbox{map}\left( {{q_i}} \right)} \right)} }}{n} \end{equation} where if $a = b$, then $ \delta (a, b) = 1$, otherwise $ \delta (a, b) = 0$. The map($\cdot$) represents an optimal permutation mapping function that matches the clustering label obtained by clustering algorithm with the label of ground-truth. The construction of mapping function can refer to the Kuhn-Munkres algorithm \cite{lovasz2009matching}. The higher the ACC is, the better the clustering performance is. Normalized Mutual Information (NMI) is an normalization of the Mutual Information (MI) score to scale the results between 0 and 1. NMI is the similarity between the clustering results and the ground-truth labels of the data sets. The higher the NMI is, the better the clustering performance is. Scikit-learn (sklearn) \cite{scikit-learn} is a third-party module in machine learning, which encapsulates the common machine learning methods. In our experiment, we calculate NMI by a method in package sklearn as follows: sklearn.metrics.normalized\_mutual\_info\_score (labels\_true, labels\_pred). \subsection{Experimental Results and Analysis} We conclude the experimental results in Table \uppercase\expandafter{\romannumeral3} and \uppercase\expandafter{\romannumeral4}. And the clustering accuracy and NMI with different number of features are shown in Fig. 2 and Fig.3. The results of the compared methods in the figures and tables refer to some experimental data from the previous method \cite{han2018unified}, while our experimental settings are the same as \cite{han2018unified}, such as the number of neighboring parameter, the number of repetition of the experiment and the number of selected features. The higher the mean is and the smaller the standard deviation is, the better the clustering performance is. \begin{figure*} \centering \subfigure[]{ \label{Fig.sub.a} \includegraphics[width=5.3cm]{fig2/lung.png}} \subfigure[]{ \label{Fig.sub.b} \includegraphics[width=5.3cm]{fig2/lung_min.png}} \subfigure[]{ \label{Fig.sub.c} \includegraphics[width=5.3cm]{fig2/lung_max.png}} \caption{The distribution of Lung data after using different algorithms. (a) Initial state (b) MMFS\_minP. (c) MMFS\_maxP.} \label{Fig.main} \end{figure*} \par According to Tables \uppercase\expandafter{\romannumeral3} and \uppercase\expandafter{\romannumeral4}, it can be observed that our methods are significantly better than all other methods on two data sets, i.e., AT\&T, and Isolet1 data sets. On other data sets, the performances of MMFS\_minP and MMFS\_maxP are different. In general, when the original data distribution is closer to the ideal situation (most of the data in the same category distributed together), the performance of MMFS\_maxP will be better, such as COIL20, USPS, ORL10P and Lung. Otherwise, when the data distribution is more chaotic, the performance of MMFS\_minP will be better, such as Isolet1, YaleB, TOX-171. The reason is that these two algorithms of MMFS keep the original data manifold structure in different ways accordingly; they retain a compact or loose structure. Our algorithms do not perform very well on YaleB and TOX-171 data sets; one possible reason is that our methods cannot adapt to all kinds of data distributions, so they cannot retain more accurate data structure information. \par As we can see from Figs. 2 and 3, the proposed algorithms MMFS\_minP, MMFS\_maxP and MMFS\_inter have better performance than other methods on most of data sets. However, in some data sets, such as Isolet1 and COIL20, the performance of MMFS\_minP is not effective enough when the number of selected features is not large enough. The performance of MMFS\_inter is usually between that of MMFS\_minP and MMFS\_maxP except USPS, a possible reason is that the way we combine the two methods is not flexible enough so that we can not get a better feature subset. At the same time, we also observe that feature selection technology improves the clustering performance. For example, when the ratio of the number of features used to the total number of features is very small, but its accuracy is much higher than that of using all features in most data sets. Even in the datasets YaleB and Tox-171, ACC with fewer features is also much better than that observed with all features. In most cases, the structural information is helpful to select the more effective features. MCFS, UDFS, NDFS, RUFS and AUFS all apply local structure information. However, the algorithms we proposed not only retain the local structural information, but also obtain the association information between non-adjacent points, and make more sufficient use of the obtained structure information, which is an important reason for our algorithms to obtain good results. Fig. 4 presents the two-dimensional data distribution after adding the relations obtained by the algorithms MMFS\_minP and MMFS\_maxP on the Lung data set. The dimension reduction method used for visualization refers to t-SNE method \cite{maaten2008visualizing}. The first part of Fig. 4 is obtained by projecting data matrix \textbf{X} into a two-dimensional plane, which depicts the original two-dimensional data distribution of the Lung data set. The second and third parts of Fig. 4 are obtained by projecting $ \textbf{X}^T\textbf{W} $ into a two-dimensional plane, where \textbf{W} is the optimal weight matrix obtained by MMFS\_minP and MMFS\_maxP respectively. Therefore, the second and third parts respectively describe the two-dimensional data distribution of the Lung data set under the effect of the relationship obtained by the algorithms MMFS\_minP and MMFS\_maxP. It is observed that some data points in the two-dimensional projection are obviously shortened or even overlapped by the influence of the relationship. Thus, the proposed algorithms MMFS\_minP and MMFS\_maxP can get the relationship of data that makes the data points in the same class more closer. \begin{figure}[t] \centering \subfigure[]{ \label{Fig.sub.a} \includegraphics[width=3.9cm]{fig2/acc_attmin.png}} \subfigure[]{ \label{Fig.sub.b} \includegraphics[width=3.9cm]{fig2/nmi_attmin.png}} \subfigure[]{ \label{Fig.sub.c} \includegraphics[width=3.9cm]{fig2/acc_attmax.png}} \subfigure[]{ \label{Fig.sub.d} \includegraphics[width=3.9cm]{fig2/nmi_attmax.png}} \subfigure[]{ \label{Fig.sub.e} \includegraphics[width=3.9cm]{fig2/acc_isoletmin.png}} \subfigure[]{ \label{Fig.sub.f} \includegraphics[width=3.9cm]{fig2/nmi_isoletmin.png}} \subfigure[]{ \label{Fig.sub.g} \includegraphics[width=3.9cm]{fig2/acc_isoletmax.png}} \subfigure[]{ \label{Fig.sub.h} \includegraphics[width=3.9cm]{fig2/nmi_isoletmax.png}} \caption{Parameter sensitivity demonstration on different data sets on top 200 features. (a)-(d) AT\&T. (e)-(h) Isolet1. (a), (b), (e) and (f) MMFS\_minP. (c), (d), (g) and (h) MMFS\_maxP.} \label{Fig.main} \end{figure} \subsection{Parameter Sensitivity} We use AT\&T and Isolet1 data sets to measure the sensitivity of the algorithms MMFS\_minP and MMFS\_maxP to parameters ($ \lambda $ and $n$), and the results (ACC mean and NMI mean) are shown in Fig. 5. It shows the performances of MMFS\_minP (the four subplots on the left, (a), (b), (e) and (f)) and MMFS\_maxP (the four subplots on the right, (c), (d), (g) and (h)) on AT\&T (the first four subplots, (a)-(d)) and Isolet1 (the last four subplots, (e)-(h)) data sets respectively when the parameters $ \lambda $ and $n$ take different values. From the first four subplots, we can observe that our methods are not significantly sensitive to the regularization parameter $ \lambda $ and the number of step $n$ for the data set AT\&T. However, for the data set Isolet1, our methods are more sensitive to $ \lambda $ than $n$. For example, In the subfigure (e) of Fig. 5, when the parameter $n$ is fixed, the change of $ \lambda $ has a significant impact on the performance. The reason is that $ \lambda $ controls the sparsity of \textbf{W}. On the other hand, when the parameter $ \lambda $ is fixed, the change of $n$ has little impact on the performance. This confirm that the proposed new parameter $n$ is rather robust to our algorithms. For the selection of the parameter $\lambda $, we follow the traditional way \cite{han2018unified}, i.e., a grid search strategy from the candidate set is used to select the best parameter. \section{Conclusion} We proposed a new feature selection approach, MMFS, which can preserve the manifold structure of high dimensional data. There are two ways to achieve our purpose, MMFS\_minP and MMFS\_maxP, and we also combine these two algorithms into an algorithm MMFS\_inter. The new framework learns a weight matrix $\mathbf{W}$ which projects the data to close the data structure constructed by multi-step Markov transition probability; $l_{2,1}$-norm is applied to make $\mathbf{W}$ to be row sparse for feature selection. An iterative optimization algorithm is proposed to optimize the new model. We perform comprehensive experiments on eight public data sets to validate the effectiveness of the proposed approach. \appendices \ifCLASSOPTIONcaptionsoff \newpage \fi \bibliographystyle{IEEEtran}
{'timestamp': '2020-06-01T02:05:14', 'yymm': '2005', 'arxiv_id': '2005.14359', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14359'}
arxiv
\section{Introduction} \emph{Quantum computing} \cite{nc2010,a2017,aazksw2019part1} is one of the hot topics in computer science of last decades. There are many problems where quantum algorithms outperform the best known classical algorithms \cite{dw2001,quantumzoo,ks2019,kks2019}. One of such problems are problems for strings. Researchers show the power of quantum algorithms for such problems in \cite{m2017,bbbv1997,rv2003,ki2019}. In this paper, we consider the problem of constructing text from dictionary strings with possible intersections. We have a text $t$ of length $n$ and a dictionary $s=s^1,\dots, s^m$. The problem is constricting $t$ only from strings of $s$ with possible intersections. The problem is connected with the sequence assembly method for reconstructing a long DNA sequence from small fragments \cite{msdd2000,bt2013}. We suggest a classical algorithm with running time $O\left(n+L +m(\log n)^2\right)=\tilde{O}(n+L)$, where $L=|s^1|+\dots+|s^m|$, $|s^i|$ is a length of $s^i$ and $\tilde{O}$ does not consider log factors. The algorithm uses segment tree\cite{l2017guide} and suffix array\cite{mm90} data structures, concepts of comparing string using rolling hash\cite{kr87,Fre79} and idea of prefix sum \cite{cormen2001}. The second algorithm is quantum. It uses similar ideas and quantum algorithm for comparing two strings with quadratic speed-up comparing to classical counterparts \cite{ki2019}. The running time for our quantum algorithm is $O\left(n +\log n\cdot(\log m+\log\log n)\cdot \sqrt{m\cdot L}\right)=\tilde{O}\left(n +\sqrt{m\cdot L}\right)$. Additionally, we show the lower bound in a classical case that is $\Omega(n+L)$. Thus, we get the optimal classical algorithm in a case of $m(\log n)^2=O(L+n)$. It is true, for example, in a case of $O(m)$ strings form $s$ has length at least $\Omega\left((\log n)^2\right)$ or in a case of $m=o\left(n/(\log n)^2\right)$. In the general case, the algorithm is an optimal algorithm up to a log factor. The quantum algorithm is better than any classical counterparts in a case of $ \log n\cdot(\log m+\log\log n)\cdot \sqrt{m\cdot L}=o(L)$. It happens if $O(m)$ strings from $s$ has length at least $\Omega(\log n\cdot(\log m+\log\log n))$. Our algorithm uses some quantum algorithms as a subroutine, and the rest part is classical. We investigate the problems in terms of query complexity. The query model is one of the most popular in the case of quantum algorithms. Such algorithms can do a query to a black box that has access to the sequence of strings. As a running time of an algorithm, we mean a number of queries to the black box. The structure of the paper is the following. We present tools in Section \ref{sec:tools}. Then, we discuss the classical algorithm in Section \ref{sec:classical} and quantum algorithm in Section \ref{sec:quantum}. Section \ref{sec:lower} contains lower bound. \section{Tools}\label{sec:tools} Our algorithms uses several data structures and algorithmic ideas like segment tree\cite{l2017guide}, suffix array\cite{mm90}, rolling hash\cite{kr87} and prefix sum \cite{cormen2001}. Let us describe them in this section. \subsection{Preliminaries} Let us consider a string $u=(u_1,\dots,u_l)$ for some integer $l$. Then, $|u|=l$ is the length of the string. $u[i,j]=(u_i,\dots,u_j)$ is a substring of $u$. In the paper, we compare strings in lexicographical order. For two strings $u$ and $v$, the notation $u<v$ means $u$ precedes $v$ in lexicographical order. \subsection{Rolling Hash for Strings Comparing}\label{sec:roll-hash} The rolling hash was presented in \cite{kr87}. It is a hash function \[h_p(u)=\left(\sum\limits_{i=1}^{|u|}index(u_i)\cdot K^{i-1}\right)\mbox{ mod }p,\] where $p$ is some prime integer, $K=|\Sigma|$ is a size of the alphabet and $index(u_i)\in\{0,\dots,K-1\}$ is the index of a symbol $u_i$ in the alphabet. For simplicity we consider binary alphabet. So, $K=2$ and $index(u_i)=u_i$. We can use rolling hash and the fingerprinting method \cite{Fre79} for comparing two strings $u,v$. Let us randomly choose $p$ from the set of the first $r$ primes, such that $r\leq \frac{\max(|u|,|v|)}{\varepsilon}$ for some $\varepsilon>0$. Due to Chinese Theorem and \cite{Fre79}, the following statements are equivalent $h_p(u)=h_p(v)$ and $u=v$ with error probability at most $\varepsilon$. If we have $\delta$ invocations of comparing procedure, then we should choose $\frac{\delta \cdot \max(|u|,|v|)}{\varepsilon}$ primes. Due to Chebishev's theorem, the $r$-th prime number $p_r\approx r\ln r$. So, if our data type for integers is enough for storing $\frac{\delta \cdot \max(|u|,|v|)}{\varepsilon}\cdot (\ln(\delta) + \ln(\max(|u|,|v|))-\ln(\varepsilon))$, then it is enough for computing the rolling hash. Additionally, for a string $u$, we can compute prefix rolling hash, that is $h_p(u[1,i])$. It can be computed in $O(|u|)$ running time using formula \[h_p(u[1,i])=\left(h_p(u[1,i-1])+(2^{i-1}\mbox{ mod }p)\cdot u_i\right)\mbox{ mod }p\mbox{ and }h_p(u[1:0])=0.\] Assume, that we store ${\cal K}_i=2^{i-1}$ mod $p$. We can compute all of them in $O(|u|)$ running time using formula ${\cal K}_i={\cal K}_{i-1}\cdot 2$ mod $p$. Using precomputed prefix rolling hash for a string $u$ we can compute rolling hash for any substring $u[i,j]$ in $O(1)$ running time by formula \[h_p(u[i,j])=\left(\sum\limits_{q=j}^{i}u_q\cdot 2^{q-1-(j-1)}\right)\mbox{ mod }p=\left(\sum\limits_{q=j}^{i}u_q\cdot 2^{q-1}\right)\cdot 2^{-(j-1)}\mbox{ mod }p=\] \[=\left(\left(\sum\limits_{q=1}^{i}u_q\cdot 2^{q-1}\right) - \left(\sum\limits_{q=1}^{j-1}u_q\cdot 2^{q-1}\right)\right)\cdot 2^{-(j-1)}\mbox{ mod }p =\]\[= \left(h_p(u[1,i])-h_p(u[1,j-1])\right)\cdot(2^{-(j-1)} ) \mbox{ $($mod }p).\] For computing the formula in $O(1)$ we should precompute ${\cal I}_i=2^{-i}$ mod $p$. We can compute it in $O(\log p+|u|)$ by the formula ${\cal I}_i={\cal I}_{i-1}\cdot 2^{-1}$ mod $p$ and ${\cal I}_{0}=1$. Due to Fermat's little theorem $2^{-1}$ mod $p=2^{p-2}$ mod $p$. We can compute it with $O(\log p)$ running time using Exponentiation by squaring algorithm. Let $\textsc{ComputeKI}(\beta,p)$ be a procedure that computes ${\cal K}$ and ${\cal I}$ up to the power $\beta$ with $O(\beta+\log p)$ running time. Let $\textsc{ComputePrefixRollingHashes}(u,p)$ be a procedure that computes all prefix rolling hashes for a string $u$ and store them. Assume, that we have two strings $u$ and $v$ and already computed prefix rolling hashes. Then, we can compare these strings in lexicographical order in $O(\log \min(|u|,|v|))$ running time. The algorithm is following. We search the longest common prefix of $u$ and $v$, that is $lcp(u,v)$. We can do it using binary search. \begin{itemize} \item If a $mid\leq lcp(u,v)$, then $h_p(u[1,mid])=h_p(v[1,mid])$. \item If a $mid> lcp(u,v)$, then $h_p(u[1,mid])\neq h_p(v[1,mid])$. \end{itemize} Using binary search we find the last index $x$ such that $h_p(u[1,x])=h_p(v[1,x])$ and $h_p(u[1,x+1])\neq h_p(v[1,x+1])$. In that case $lcp(u,v)=x$ After that, we compare $u_{t}$ and $v_t$ for $t=lcp(u,v)+1$. If $u_t<v_t$, then $u<v$; if $u_t>v_t$, then $u>v$; if $|u|=|v|=lcp(u,v)$, then $u=v$. Binary search works with $O(\log (\min(|u|,|v|)))$ running time because we have computed all prefix rolling hashes already. Let $\textsc{Compare}(u,v)$ be a procedure that compares $u$ and $v$ and returns $-1$ if $u<v$; $1$ if $u>v$; and $0$ if $u=v$. \subsection{Segment Tree with Range Updates}\label{sec:segment-tree} We consider a standard segment tree data structure \cite{l2017guide} for an array $a=(a_1,\dots, a_l)$ for some integer $l$. A segment tree for and array $a$ can be constructed in $O(l)$ running time. The data structure allows us to invoke the following requests in $O(\log l)$ running time. \begin{itemize} \item {\bf Update.} Parameters are three integers $i, j, x$ ($1\leq i\leq j\leq l$). We assign $a_q=\max(a_q,x)$ for $i\leq q\leq j$. \item {\bf Push.} We push all existing range updates. \item {\bf Request.} For an integer $i$ ($1\leq i\leq l$), we should return $a_i$. \end{itemize} Let $\textsc{ConstructSegmentTree}(a)$ be a function that constructs and returns a segment tree for an array $a$ in $O(l)$ running time. Let $\textsc{Update}(st,i,j,x)$ be a procedure that updates a segment tree $st$ in $O(\log l)$ running time. Let $\textsc{Push}(st)$ be a procedure that push all existing range updates for a segment tree $st$ in $O(l)$ running time. Let $\textsc{Request}(st,i)$ be a function that returns $a_i$ from a segment tree $st$. The running time of the procedure is $O(\log l)$. At the same time, if we invoke $\textsc{Push}$ procedure and after that do not invoke $\textsc{Update}$ procedure, then the running time of $\textsc{Request}$ is $O(1)$. \subsection{Suffix Array} Suffix array \cite{mm90} is an array $suf=(suf_1,\dots,suf_{l})$ for a string $u$ and $l=|u|$. The suffix array is a lexicographical order for all suffixes of $u$. Formally, $u[suf_i,l]<u[suf_{i+1},l]$ for any $i\in\{1,\dots,l-1\}$. The suffix array can be computed in $O(l)$ running time. \begin{lemma}[\cite{llh2018}]\label{lm:suf-arr} A suffix array for a string $u$ can be constructed in $O(|u|)$ running time. \end{lemma} Let $\textsc{ConstructSuffixArray}(u)$ be a procedure that constructs a suffix array for a string $u$. \section{Algorithms}\label{sec:algos} Let us formally present the problem. {\bf Problem.} For some positive integers $n$ and $m$, we have a sequence of strings $s=(s^1,\dots,s^m)$. Each $s^i=(s^i_1,\dots,s^i_{l})\in \Sigma^l$ where $\Sigma$ is some finite size alphabet and $l=|s^i|$. We call $s$ dictionary. Additionally, we have a string $t$ of length $n$, where $t=(t_1,\dots,t_n)\in \Sigma^n$. We call $t$ text. The problem is searching a subsequence $s^{i_1},\dots,s^{i_z}$ and positions $q_1,\dots,q_z$ such that $q_1=1$, $q_z=n-|s^{i_z}|+1$, $q_j\leq q_{j-1}+|s^{i_{j-1}}|$ for $j\in\{2,\dots,z\}$. Additionally, $t[q_j,q_j+|s^{i_j}|-1]=s^{i_j}$ for $j\in\{1,\dots,z\}$. For simplicity, we assume that $\Sigma=\{0,1\}$, but all results are right for any finite alphabet. Informally, we want to construct $t$ from $s$ with possible intersections. Firstly, let us present a classical algorithm. \subsection{A Classical Algorithm}\label{sec:classical} Let us present the algorithm. Let $long_i$ be an index of a longest string from $s$ that can start in position $i$. Formally, $long_i=j$ if $s^j$ is a longest string from $s$ such that $t[i,i+|s^j|-1]=s^j$. Let $long_i=-1$ if there is no such string $s^j$. If we construct such array, then we can construct $Q=(q_1,\dots,q_z)$ and $I = (i_1,\dots,i_z)$ that is solution of the problem in $O(n)$. A procedure $\textsc{ConstructQI}(long)$ from Algorithm \ref{alg:qi} shows it. If there is no such decomposition of $t$, then the procedure returns $NULL$. \begin{algorithm} \caption{$\textsc{ConstructQI}(long)$. Constructing $Q$ and $I$ from $last$}\label{alg:qi} \begin{algorithmic} \State $t \gets 1$ \State $i_1\gets long_1$ \State $q_1\gets 1$ \State $left\gets 2$ \State $right\gets |s^{i_1}|+1$ \While{$q_t<n$} \State{$max\_i\gets left$} \State{$max\_q\gets -1$} \If{$long_{left}>0$} \State{$max\_q\gets left + |s^{long_{left}}|-1$} \EndIf \For{$j\in \{left+1,\dots,right\}$} \If{$long_j>0$ and $j + |s^{long_j}|-1>max\_q$} \State{$max\_i\gets j$} \State{$max\_q\gets j + |s^{long_j}|-1$} \EndIf \EndFor \If{$max\_q= -1$ or $max\_q< right$} \State Break the While loop and \Return $NULL$ \Comment{We cannot construct other part of the string $t$} \EndIf \State $t\gets t+1$ \State $i_t\gets long_{max\_i}$ \State $q_t\gets max\_i$ \State $left\gets right+1$ \State $right\gets max\_q+1$ \EndWhile \State \Return $(Q,I)$ \end{algorithmic} \end{algorithm} Let us discuss how to construct $long$ array. As a first step, we choose a prime $p$ that is used for rolling hash. We choose $p$ randomly from the first $z=n\cdot m \cdot 4\lceil\log_2 n\rceil^2\cdot \frac{1}{\varepsilon}$ primes. In that case, due to results from Section \ref{sec:roll-hash}, the probability of error is at most $\varepsilon$ in a case of at most $m \cdot 4\lceil\log_2 n\rceil$ strings comparing invocations. As a second step, we construct a suffix array $suf$ for $t$. Then, we consider an array $a$ of pairs $(len, ind)$. One element of $a$ corresponds to one element of the suffix array $suf$. After that, we construct a segment tree $st$ for $a$ and use $len$ parameter of pair for maximum. As a next step, we consider strings $s^i$ for $i\in\{1,\dots m\}$. For each string $s^i$ we find the smallest index $low$ and the biggest index $high$ such that all suffixes $t[suf_j,n]$ for $low\leq j \leq high$ has $s^i$ as a prefix. We can use binary search for this action. Because of sorted order of suffixes in suffix array, all suffixes with the prefix $s^i$ are situated sequently. As a comparator for strings, we use $\textsc{Compare}$ procedure. Let us present this action as a procedure $\textsc{SearchSegment}(u)$ in Algorithm \ref{alg:search}. The algorithm returns $(NULL,NULL)$ if no suffix of $t$ contains $u$ string as a prefix. \begin{algorithm} \caption{$\textsc{SearchSegment}(u)$. Searching a indexes segment of suffixes for $t$ that have $u$ as a prefix}\label{alg:search} \begin{algorithmic} \State $low\gets NULL$, $high\gets NULL$ \State $l\gets 1$ \State $r\gets n$ \State $Found\gets False$ \While{$Found=False$ and $l\leq r$} \State $mid\gets (l+r)/2$ \State $pref\gets t[suf_{mid},\min(n,suf_{mid}+|u|-1)]$ \State $pref1\gets t[suf_{mid-1},\min(n,suf_{mid-1}+|u|-1)]$ \State $compareRes \gets \textsc{Compare}(pref,u), compareRes1 \gets \textsc{Compare}(pref1,u)$ \If {$compareRes=0$ and $compareRes1=-1$} \State $Found\gets true$ \State $low\gets mid$ \EndIf \If {$compareRes< 0$} \State $l\gets mid+1$ \EndIf \If {$compareRes\geq 0$} \State $r\gets mid-1$ \EndIf \EndWhile \If{$Found=True$} \State $l\gets 1$ \State $r\gets n$ \State $Found\gets False$ \While{$Found=False$ and $l\leq r$} \State $mid\gets (l+r)/2$ \State $pref\gets t[suf_{mid},\min(n,suf_{mid}+|u|-1)]$ \State $pref1\gets t[suf_{mid+1},\min(n,suf_{mid+1}+|u|-1)]$ \State $compareRes \gets \textsc{Compare}(pref,u), compareRes1 \gets \textsc{Compare}(pref1,u)$ \If {$compareRes=0$ and $compareRes1=+1$} \State $Found\gets true$ \State $high\gets mid$ \EndIf \If {$compareRes\leq 0$} \State $l\gets mid+1$ \EndIf \If {$compareRes> 0$} \State $r\gets mid-1$ \EndIf \EndWhile \EndIf \State \Return $(low, high)$ \end{algorithmic} \end{algorithm} Then, we update values in the segment tree $st$ by a pair $(|s^i|,i)$. After processing all strings from $(s^1,\dots,s^m)$, the array $a$ is constructed. We can construct $long$ array using $a$ and the suffix array $suf$. We know that $i$-th element $(len,ind)$ stores the longest possible string $s^{ind}$ that starts from $suf_i$. It is almost definition of $long$ array. So we can put $long_{suf_i}=ind$, if $a_i=(ind,len)$. Finally, we get the following Algorithm \ref{alg:classical} for the text constructing from a dictionary problem. \begin{algorithm} \caption{The classical algorithm for the text $t$ constructing from a dictionary $s$ problem for an error probability $\varepsilon>0$}\label{alg:classical} \begin{algorithmic} \State $\alpha\gets m \cdot 4\lceil\log_2 n\rceil^2$ \State $r\gets n\cdot \alpha/\varepsilon$ \State $p\in_R \{p_1,\dots,p_r\}$\Comment{$p$ is randomly chosen from $\{p_1,\dots,p_r\}$} \State $\textsc{ComputeKI}(n,p)$ \State $\textsc{ComputePrefixRollingHashes}(t,p)$ \For{$j\in\{1,\dots,m\}$} \State $\textsc{ComputePrefixRollingHashes}(s^j,p)$ \EndFor \State $suf\gets\textsc{ConstructSuffixArray}(t)$ \State $a\gets[(0,-1),\dots,(0,-1)]$\Comment{Initialization by $0$-array} \State $st \gets\textsc{ConstructSegmentTree}(a)$ \For{$j\in\{1,\dots,m\}$} \State $(low,high)\gets \textsc{SearchSegment}(s^j)$ \If{$(low,heigh)\neq (NULL,NULL)$} \State $\textsc{Update}(st,low,high,(|s^j|,j))$ \EndIf \EndFor \State $\textsc{Push}(st)$ \For{$i\in\{1,\dots,n\}$} \State $(len,ind)\gets \textsc{Request}(st,i)$ \State $long_{suf_i}\gets ind$ \EndFor \State $(Q,I)\gets\textsc{ConstructQI}(long)$ \State\Return $(Q,I)$ \end{algorithmic} \end{algorithm} Let us discuss properties of Algorithm \ref{alg:classical}. \begin{theorem}\label{th:classical} Algorithm \ref{alg:classical} solves the text $t$ constructing from a dictionary $s=(s^1,\dots,s^m)$ problem with $O\left(n+L +m(\log n)^2 -\log\varepsilon\right)$ running time end error probability $\varepsilon$ for some $\varepsilon>0$, $n=|t|$ and $L=|s^1|+\dots + |s^m|$. The running time is $O\left(n+L +m(\log n)^2\right)$ in a case of $\varepsilon=const$. \end{theorem} \begin{proof} The correctness of the algorithm follows from construction. Let us discuss running time of the algorithm. Note, that $m\leq L=\sum_{j=1}^m|s^j|$ and $1\leq |s^j|\leq n$ for $j\in\{1,\dots,m\}$. Due to results from Section \ref{sec:roll-hash}, $\textsc{ComputeKI}$ works with $O(n+\log p)$ running time. Let us convert this statement. \[O(n+\log p)=O(n+\log (n\cdot \alpha/\varepsilon))=\] \[=O(n + \log n + \log\alpha - \log\varepsilon)=O(n + \log\alpha - \log\varepsilon)=\]\[= O(n + \log(m \cdot 4\lceil\log_2 n\rceil^2) - \log\varepsilon) =O(n + \log m +\log\log n - \log\varepsilon)=\]\[= O(n+\log m - \log\varepsilon)\] Due to results from Section \ref{sec:roll-hash}, $\textsc{ComputePrefixRollingHashes}$ works in linear running time. Therefore, all invocations of $\textsc{ComputePrefixRollingHashes}$ procedure works in $O(n+\sum_{j=1}^m|s^j|)=O(n+L)$ running time. Due to Lemma \ref{lm:suf-arr}, $\textsc{ConstructSuffixArray}$ works in $O(n)$ running time. Initializing of $a$ does $O(n)$ steps. Due to results from Section \ref{sec:segment-tree}, $\textsc{ConstructSegmentTree}$ works in $O(n)$ running time. $\textsc{SearchSegment}$ procedure invokes $\textsc{Compare}$ procedure $O(\log n)$ times due to binary search complexity. $\textsc{Compare}$ procedure works in $O(\log n)$ running time. Therefore, $\textsc{SearchSegment}$ works in $O((\log n)^2)$ running time. Due to results from Section \ref{sec:segment-tree}, $\textsc{Update}$ procedure works in $O(\log n)$ running time. Hence, the total complexity of processing all strings from the dictionary $s$ is $O\left(m\cdot((\log n)^2+\log n)\right)=O\left(m\cdot(\log n)^2\right)$. The invocation of $\textsc{Push}$ works in $O(n)$ running time due to results from Section \ref{sec:segment-tree}. The invocation of $\textsc{Request}$ works in $O(1)$ running time because we do not invoke $\textsc{Update}$ after $\textsc{Push}$. Therefore, constructing of the array $long$ takes $O(n)$ steps. The running time of $\textsc{ConstructQI}$ is $O(n)$ because we pass each element only once. So, the total complexity of the algorithm is \[O\left(n+\log m - \log\varepsilon+n+L+n+n+n+m(\log n)^2 +n+n+n\right)=\]\[=O\left(n+L +m(\log n)^2 -\log\varepsilon\right).\] Let us discuss the error probability. We have $4 \cdot m\lceil\log_2 n\rceil$ invocations of $\textsc{Compare}$ procedure. Each invocation of $\textsc{Compare}$ procedure compares rolling hashes at most $\lceil\log_2 n\rceil$ times. Due to results from Section \ref{sec:roll-hash}, if we compare strings of length at most $n$ using rolling hash $4 \cdot m\lceil\log_2 n\rceil^2$ times and choose $p$ from $r$ primes, then we get error probability at most $\varepsilon$. \hfill$\Box$\\ \end{proof} \subsection{A Quantum Algorithm}\label{sec:quantum} Firstly, let us discuss a quantum subroutine. There is a quantum algorithm for comparing two strings in a lexicographical order with the following property: \begin{lemma}[\cite{ki2019}]\label{lm:str-compr}There is a quantum algorithm that compares two strings of length $k$ in lexicographical order with query complexity $O(\sqrt{k}\log \gamma)$ and error probability $O\left(\frac{1}{ \gamma^3}\right)$ for some positive integer $\gamma$. \end{lemma} Let $\textsc{QCompare\_strings\_base}(u,v,l)$ be a quantum subroutine for comparing two strings $u$ and $v$ of length $l$ in lexicographical order. We choose $\gamma = m\log n$. In fact, the procedure compares prefixes of $u$ and $v$ of length $l$. $\textsc{QCompare\_strings\_base}(u,v,l)$ returns $1$ if $u>v$; it returns $-1$ if $u<v$; and it returns $0$ if $u=v$. Next, we use a $\textsc{QCompare}(u,v)$ that compares $u$ and $v$ string in lexicographical order. Assume that $|u|<|v|$. Then, if $u$ is a prefix of $v$, then $u<v$. If $u$ is not a prefix of $v$, then the result is the same as for $\textsc{QCompare\_strings\_base}(u,v,|u|)$. In the case of $|u|>|v|$, the algorithm is similar. The idea is presented in Algorithm \ref{alg:compare}. \begin{algorithm} \caption{The quantum algorithm for comparing two string in lexicographical order }\label{alg:compare} \begin{algorithmic} \If{$|u|=|v|$} \State $Result \gets\textsc{QCompare\_strings\_base}(u,v,|u|) $ \EndIf \If{$|u|<|v|$} \State $Result \gets\textsc{QCompare\_strings\_base}(u,v,|u|) $ \If{$Result=0$} \State $Result = -1$ \EndIf \EndIf \If{$|u|>|v|$} \State $Result \gets\textsc{QCompare\_strings\_base}(u,v,|v|) $ \If{$Result=0$} \State $Result = 1$ \EndIf \EndIf \State \Return $Result$ \end{algorithmic} \end{algorithm} Let us present a quantum algorithm for the text constructing form a dictionary problem. For the algorithm, we use the same idea as in the classical case, but we replace $\textsc{Compare}$ that uses the rolling hash function by $\textsc{QCompare}$. In that case, we should not construct rolling hashes. Let $\textsc{QSearchSegment}$ be a quantum counterpart of $\textsc{SearchSegment}$ that uses $\textsc{QCompare}$. The quantum algorithm is presented as Algorithm \ref{alg:quantum}. \begin{algorithm} \caption{The quantum algorithm for the text $t$ constructing from a dictionary $s$ problem}\label{alg:quantum} \begin{algorithmic} \State $suf\gets\textsc{ConstructSuffixArray}(t)$ \State $a\gets[(0,-1),\dots,(0,-1)]$\Comment{Initialization by $0$-array} \State $st \gets\textsc{ConstructSegmentTree}(a)$ \For{$j\in\{1,\dots,m\}$} \State $(low,high)\gets \textsc{QSearchSegment}(s^j)$ \State $\textsc{Update}(st,low,high,(|s^j|,j))$ \EndFor \State $\textsc{Push}(st)$ \For{$i\in\{1,\dots,n\}$} \State $(len,ind)\gets \textsc{Request}(st,i)$ \State $long_{suf_i}\gets ind$ \EndFor \State $(Q,I)\gets\textsc{ConstructQI}(long)$ \State\Return $(Q,I)$ \end{algorithmic} \end{algorithm} Let us discuss properties of Algorithm \ref{alg:quantum}. \begin{theorem} Algorithm \ref{alg:quantum} solves the text $t$ constructing from a dictionary $s=(s^1,\dots,s^m)$ problem in $O\left(n +\log n\cdot(\log m+\log\log n)\cdot \sqrt{m\cdot L}\right)$ running time end error probability $O\left(\frac{1}{m+\log n}\right)$. \end{theorem} \begin{proof} The algorithm does almost the same actions as the classical counterpart. That is why the correctness of the algorithm follows from Theorem \ref{th:classical}. Let us discuss the running time. Due to Theorem \ref{th:classical}, the running time of the procedure $\textsc{ConstructSuffixArray}$ is $O(n)$, the running time of the procedure $\textsc{ConstructSegmentTree}$ is $O(n)$, the running time of the procedure $\textsc{Push}$ is $O(n)$, the running time of the array $long$ construction is $O(n)$, the running time of $\textsc{ConstructQI}$ is $O(n)$. Due to Lemma \ref{lm:str-compr}, the running time of $\textsc{QCompare}$ for $s^j$ is $O(\sqrt{|s^j|}(\log m+\log\log n))$. The procedure $\textsc{QSearchSegment}$ invokes $\textsc{QCompare}$ procedure $O(\log n)$ times for each string $s^1,\dots s^m$. So, the complexity of processing all strings from $s$ is \[O\left(\log n\cdot(\log m+\log\log n)\cdot \sum_{j=1}^m\sqrt{|s^j|}\right)\] Let us use the Cauchy-Bunyakovsky-Schwarz inequality and $L=\sum_{j=1}^m|s^j|$ equality for simplifying the statement. \[\leq O\left(\log n\cdot(\log m+\log\log n)\cdot \sqrt{m\sum_{j=1}^m|s^j|}\right)=O\left(\log n\cdot(\log m+\log\log n)\cdot \sqrt{m\cdot L}\right).\] The total running time is \[O\left(n+n+n +\log n\cdot(\log m+\log\log n)\cdot \sqrt{m\cdot L}\right)=\]\[=O\left(n +\log n\cdot(\log m+\log\log n)\cdot \sqrt{m\cdot L}\right)\] Let us discuss the error probability. The algorithm invokes $\textsc{QCompare}$ procedure $2m\lceil\log_2 n \rceil\leq 2m(1+\log_2 n)$ times. The success probability is \[O\left(\left(1-\frac{1}{(m\log n)^3}\right)^{2m(1+\log_2 n)}\right)=O\left(\frac{1}{m\log n}\right).\] \hfill$\Box$\\ \end{proof} \section{Lower Bound}\label{sec:lower} Let us discuss the lower bound for the running time of classical algorithms. \begin{theorem}\label{th:dfreq-compl} Any randomized algorithm for the text $t$ constructing from a dictionary $s=(s^1,\dots,s^m)$ problem works in $\Omega(n+L)$ running time, where $L=|s^1|+\dots+|s^m|$. \end{theorem} \begin{proof} Assume $L>n$. Let us consider $t=(t_1,\dots,t_n)$ such that $t_{\lfloor n/2\rfloor}=1$ and $t_{i}=0$ for all $i\in\{1,\dots, n\}\backslash\{\lfloor n/2\rfloor\}$. Let $|s^i|\leq n/2$ for each $i\in\{1,\dots,m\}$. Note, that in a general case $|s^i|\leq n$. Therefore, we reduce the input data only at most twice. Assume that we have two options: \begin{itemize} \item all $s^i$ contains only $0$s; \item there is $z$ such that we have two conditions: \begin{itemize} \item all $s^i$ contains only $0$s, for $i\in\{1,\dots, m\}\backslash\{ z\}$; \item for $j_0<|s^z|$, $s^z_{j_0}=1$ and $s^z_{j}=0$ for $j\in\{1,\dots, |s^z|\}\backslash\{ j_0\}$. \end{itemize} \end{itemize} In a case of all $0$s, we cannot construct the text $t$. In a case of existing $0$ in the first half, we can construct $t$ by putting $s^z$ on the position $j_0-\lfloor n/2\rfloor+1$ and we get $1$ of the required position. Then, we complete $t$ by other $0$-strings. Therefore, the solution of the problem is equivalent to the search of $1$ in unstructured data of size $L$. The randomized complexity of this problem is $\Omega(L)$ due to \cite{bbbv1997}. Assume $L<n$. Let $m=1$, $|s^1|=1$ and $s^1_1=1$. Assume that we have two options: \begin{itemize} \item $t$ contains only $1$s; \item there is $g$ such that $t_g=0$ and $t_j=1$ for all $j\in\{1,\dots,n\}\backslash\{g\}$. \end{itemize} In the first case, we can construct $t$ from $s$. In the second case, we cannot do it. Here the problem is equivalent to search $0$ among $n$ symbols of $t$. Therefore, the problem's randomized complexity is $\Omega(n)$. Finally, the total complexity is $\Omega(\max(n,L))=\Omega(n+L)$. \hfill$\Box$\\ \end{proof} \bibliographystyle{psc}
{'timestamp': '2020-06-01T02:04:21', 'yymm': '2005', 'arxiv_id': '2005.14335', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14335'}
arxiv
\section{Introduction} A large portion of the empirical methods in Natural Language Processing (NLP) are defined over canonical text interpretation tasks such as Named Entity Recognition (NER), Semantic Role Labeling (SRL), Sentiment Analysis (SA), among others. The systematic creation of benchmarks and the comparative performance analysis of resources, representations and algorithms is instrumental for moving the boundaries of natural language interpretation. SemEval \cite{semeval-2019-international,semeval-2018-international,semeval-2017-international,semeval-2016-international,semeval-2015-international,semeval-2014-international,semeval-2013-joint-lexical,semeval-2012-sem} is the primary venue in the NLP community for the organisation of shared NLP tasks and challenges. SemEval is organised as an annual workshop co-located with the main NLP conferences and has attracted a large and growing audience of task organisers and participants. Despite its recognition as a major driver in the creation of gold-standards and evaluation campaigns, there is no existing meta-analysis which interprets the overall contribution of SemEval as a collective effort. This paper aims to address this gap by performing a systematic descriptive quantitative analysis of 96 tasks encompassing the SemEval campaigns between 2012-2019. This study targets understanding the evolution of SemEval over this period, describing the core patterns with regard to task popularity, impact, task format (inputs, outputs), techniques, target languages and evaluation metrics. This paper is organised as follows: section 2 describes related work; 3 describes the methodology; 4 defines the underlying task macro-categories; 5 and 6 presents the number of tasks and popularity in 2012-2019; 7 discusses SemEval impact in terms of citations; 8 shows targeted languages; then, sections 9, 10, 11 analyse input, output and evaluation metrics; 11 focuses on sentiment analysis architectures and representations; this is followed by a Discussion section; we close the paper with Recommendations and Conclusions. \section{Related work} Each SemEval task is described by an \textit{anthology}, which contains: a summary of previous editions or similar tasks, references to previous works, detailed task description, evaluation methods, available resources, overview of submitted systems and final results of the competition. It is worth noting, there is a variation, or even inconsistency, in the structure and the level of detail in the description. Participants are also encouraged to submit papers with systems architecture explanations. However, there is a lack of overall analysis across different tasks and years in SemEval. There are existing studies on the analysis of specific SemEval tasks. \cite{Nakov2016} focuses on developing Sentiment Analysis tasks in 2013-2015. \cite{Sygkounas2016} is an example of a replication study of the top performing systems, in this case systems used in SemEval Twitter Sentiment Analysis (2013-2015), and focuses on architectures and performance. Evolution and challenges in semantics similarity were described in \cite{JIMENEZ2015}. This is an example of a study on the performance of a given type of architecture across tasks of the same type. There also exist studies on shared tasks in given domain, specially in clinical application of NLP \cite{PMID:30157522}, \cite{10.1136/amiajnl-2011-000465}. However, they refer to tasks outside the SemEval and are more result oriented rather than task organization. Some studies discuss ethical issues in the organisation and participation of shared tasks. An overview focusing on task competitive nature and fairness can be found in \cite{parra-escartin-etal-2017-ethical}. In \cite{nissim-etal-2017-last} authors also relate to these issues, yet giving the priority to advancing the field over fair competition. Comparatively, this paper covers a wider range of NLP topics, and compares sentiment analysis and semantic similarity as well as other task types/groups in a systematic manner. To the best to our knowledge this is the first systematic analysis on SemEval. \section{Analysis methodology} We build a corpus based on the ACL anthology archive from the SemEval workshops between the years 2012-2019. Reference material included ACL anthology papers covering the task description, tasks' websites and papers describing the participating systems. All the reference papers included in this analysis are reported at the Appendix B. The pre-processing analysis consisted in manually extracting the target categories for the analysis which includes: task types, input and output types, as well as evaluation metrics, number of teams, languages and system architectures. Tasks were grouped based on the similarity between task types similarity. If the same team took part in several tasks the same year, we considered each participation as distinct. There are four missing tasks in the plotted indexes, due to cancellation (2015-16, 2019-11), task-sharing (2013-6) or lack of supporting task description (2013-14). Numbers of citations are the numbers returned by Google Scholar, using \textit{Publish and Perish} supporting API \cite{publish-and-perish}. The list of citations were manually validated and noisy entries were filtered out. A final table with all the values extracted from the corpus is included in the Appendix B. \begin{figure*}[ht] \centering \begin{subfigure}[b]{0.475\textwidth} \centering \includegraphics[width=0.93\textwidth]{Task_in_years.png} \caption[]% {{\small Number of tasks in SemEval 2012-2019}} \label{fig:tasks_in_years} \end{subfigure} \hfill \begin{subfigure}[b]{0.475\textwidth} \centering \includegraphics[width=0.9\textwidth]{Teams.png} \caption[]% {{\small Number of teams participating in SemEval}} \label{fig:teams} \end{subfigure} \vskip\baselineskip \begin{subfigure}[b]{0.475\textwidth} \centering \includegraphics[width=0.9\textwidth]{cumulative_citations.png} \caption[]% {{\small Cumulative number of task citations, except for citations in SemEval proceedings}} \label{fig:cum} \end{subfigure} \quad \begin{subfigure}[b]{0.475\textwidth} \centering \includegraphics[width=0.9\textwidth]{cumulative_citations_internal.png} \caption[]% {{\small Cumulative number of task citations in SemEval proceedings}} \label{fig:cum_int} \end{subfigure} \caption[ AAA ] {\small Overall plots for SemEval editions 2012-2019} \label{fig:overall_plots} \end{figure*} \section{Task types and groups} Based on task description we group each task within a macro-category. Then, due to a large number of task types, tasks were clustered within 6 groups: \textit{Sentiment Analysis} (\textbf{SA}); \textit{Semantic Analysis} (\textbf{SEM}): semantic analysis, semantic difference, semantic inference, semantic role labeling, semantic parsing, semantic similarity, relational similarity; \textit{Information Extraction} (\textbf{IE}): information extraction, temporal information extraction, argument mining, fact checking; \textit{Machine Translation} (\textbf{MT}); \textit{Question Answering} (\textbf{QA}); \textit{Other} (\textbf{OT}): hypernym discovery, entity linking, lexical simplification, word sense disambiguation, taxonomy extraction, taxonomy enrichment. There are also macro-categories defined by the SemEval organizers, starting from 2015, but we found them not consistent enough for the purpose of this analysis. \section{SemEval tasks in years} Within 8 editions of SemEval, a total of 96 tasks were successfully announced. The number of tasks within one group is roughly similar every year (except for MT), as well as distribution of tasks in each edition. According to Fig.\ref{fig:tasks_in_years}, we observe decreasing number of SEM tasks: 5 on average in 2012-2017, and only 2 in 2018-2019. Moreover, there were no machine translation tasks in the last 2 years, and a low number of MT tasks in general (only 4 tasks in 8 years). Although SA has a relatively limited task complexity when compared to SEM or IE, which reflects a higher variety of task types and an abundance of more specific interpretation challenges, the number of SA tasks each year is high (4, 3, 3 and 4 in years 2016-2019). It is worth mentioning, that there are other 6 SA tasks in the forthcoming SemEval 2020. The absence of some task types may be caused by the emergence of specialized workshops or conferences, e.g. low number of MT tasks in SemEval is caused by the presence a separate venue for MT: the Conference On Machine Translation \cite{barrault-EtAl:2019:WMT}, which attracts more participants than SemEval in this field. \section{Task popularity} As a measure of task popularity, we analysed how many teams participated in a given task. As the number of teams signed up to the task is usually much higher than the number submitting a system result, we consider only the latter. The number of teams increased significantly from 62 in 2012 to 646 in 2019, which shows not only a popularity boost for SemEval, but an increase in the general interest for NLP. So far, a total of 1883 teams participated in this period. In Fig.\ref{fig:teams}, we observe a gradual increase in SemEval popularity, 30\% on average each year to 2018, with a +129\% jump in 2019. This is associated mainly with a dramatic increase of interest for SA: 542 teams (84\% of total) in 2019. However, at the same time, number of teams in non-SA tasks decreased from 132 in 2017, to 115 in 2018 and 104 in 2019. The most popular tasks groups along the years are SA and SEM, which gather more than 75\% of teams on average each year. The third most popular is IE, in which total of 235 teams participated in SemEval from 2012 (12\% of total). As a contrast, we observe a relatively low interest in QA and OT tasks. Only 41 teams participated in the last 3 years (3\% of a total of 1148 in 2017-2019). Especially in OT tasks, which concentrates novel tasks, in many cases including novel formats. In the last 2 years, SA shows a major increase in popularity (76\% of all teams, compared to 40\% in 2013-2017). At the same time, in tasks such as 2019-10, 2018-4 and 2018-6, which are mathematical question answering, entity linking on multiparty dialogues and parsing time normalization, respectively, only 3, 4 and 1 teams submitted results. This divergence may be associated with an emergence of easily applicable ML systems and libraries, which better fit to standard classification tasks more prevalent in SA (in contrast to OT, QA nor IE). \section{The impact of SemEval papers} As a measure of the impact of SemEval outcomes in the NLP community, we analysed the numbers of citations per task description in Google Scholar. The task description paper was used as a proxy to analyse the task impact within the NLP community. Papers submitted by participating teams describing systems and methods were not included on this analysis. We considered the cumulative citations from 2012 to 2019 (Fig.\ref{fig:cum}), with additional distinction on citations of task description papers published in a given year (Fig.\ref{fig:cit_year}). Citations within SemEval proceedings were treated separately, as we focused on the impact both outside (Fig.\ref{fig:cum}) and inside (Fig.\ref{fig:cum_int}) the SemEval community. In other words, citations found in Google Scholar are split into numbers of papers \textit{out} and \textit{in} the SemEval proceedings. SA and SEM have the highest impact, being the most cited tasks along the years both inside and outside SemEval community, what can be attributed to their high popularity. Considering the external impact, in 2019 SA and SEM anthologies contributed with 2847 (41\%) and 2426 (35\%) citations respectively. IE has 985 citations (14\%) and QA contributed with 148 citations (2\%). The OT group, which consists of less canonical tasks, accumulated 468 citations (7\%). The impact of MT papers is noticeably lower - 84 (1\%). In terms of citations within the SemEval community (in all SemEval 2012-2019 proceedings), we observe a similar pattern: 41\% and 37\% citations in 2019 come from SA and SEM (357 and 322), and for remaining task groups proportions are almost identical as in citations outside community (Chi.sq. \textit{p-value}=0.06). The number of citations outside is 8 times higher than inside the community. This proves the scientific impact and coverage, which leads to beneficial effect of SemEval on the overall NLP community. A total of 6958 citations from 2019 are depicted in Fig.\ref{fig:cit_year} with distinction on the year in which the task was published (e.g. tasks from 2016 are cited 1682 times (23\%)). Similarly, a total of 876 citations in the SemEval proceedings are presented in Fig.\ref{fig:cit_int} (e.g. anthologies published in 2015 are cited 163 times in all SemEval proceedings so far). SA tasks from 2016, SEM from 2014 and IE from 2013 have the highest impact compared within groups (40\%, 28\% and 42\% respectively). One could expect higher numbers of citations for older papers, however, we do not observe this pattern. \section{Languages in tasks} We analysed SemEval it terms of languages used in the tasks (Fig.\ref{fig:languages}). We can distinguish 3 clusters: English-only (except for 3 tasks entirely in Chinese); multi-lingual, which define identical subtasks for several languages; cross-lingual (targeting the use of semantic relation across languages). In total of 96 tasks, 30 investigated more than one language (multi-lingual and cross-lingual tasks) and 63 tasks were using only English. The five most popular languages, excluding English are: Spanish (16), French (10), Italian (10), Arabic (8), German (8). Although Chinese is the 1st language in number of speakers, only 4 tasks were organised for Chinese. Most of multi-lingual or cross-lingual tasks are related to SA (5 in 2016-2018) or SEM (15 in 2012-2019), and obviously on MT tasks (3 in 2012-2014). There were 3 OT tasks, only one QA task, and no IE tasks. Task 11 in 2017 concerning program synthesis, aiming to translate commands in English into (program) code, attracted only one team. In 2018 and 2019 the interest of other languages is lower compared to previous years. Languages other than English were proposed only 5 and 3 times, respectively, whereas in 2016 and 2017 we observed the occurrence of respectively 10 and 14 times. \section{Input and Output Analysis} In order to better understand the evolution of the semantic complexity of the tasks, we analysed them in terms of the types used to represent input and output data in all subtasks. Based on their descriptions, we devised a list of 25 different abstract types used, then assigning each subtask the most appropriate Input and Output Types. \subsection{Types and Clusters} Taking into consideration both their complexity and purpose, we split the type list into 5 clusters: \textit{cluster 1}: document, text, paragraph, sentence, phrase, word, number; \textit{cluster 2}: score, score real value, score whole value, class label, probability distribution; \textit{cluster 3}: entity, attribute, topic, tree, Directed Acyclic Graph (DAG); \textit{cluster 4}: question, answer, query; \textit{cluster 5}: Knowledge Base (KB), program, time interval, timeline, semantic graph, syntactic labeled sentence. \begin{figure*} \centering \begin{subfigure}[b]{0.475\textwidth} \centering \includegraphics[width=0.9\textwidth]{Languages.png} \caption[]% {{\small Languages used in 96 SemEval tasks from 2012 to 2019}} \label{fig:languages} \end{subfigure} \hfill \begin{subfigure}[b]{0.475\textwidth} \begin{subfigure}[b]{\textwidth} \centering \includegraphics[width=0.9\textwidth]{Citations.png} \caption[]% {{\small Number of task citations published in given year, except for citations in SemEval proceeding}} \label{fig:cit_year} \end{subfigure} \vfill \begin{subfigure}[b]{\textwidth} \centering \includegraphics[width=0.9\textwidth]{Citations_internal.png} \caption[]% {{\small Number of task citations from given year in SemEval proceedings}} \label{fig:cit_int} \end{subfigure} \begin{subfigure}[b]{\textwidth} \centering \includegraphics[width=0.9\textwidth]{architectures.png} \caption[]% {{\small Models used in SA tasks from 2012 to 2019 at SemEval}} \label{fig:models} \end{subfigure} \end{subfigure} \caption[ AAA ] {\small } \label{fig:languages_cit_models} \end{figure*} \subsection{Input Types} As expected, types from \textit{cluster 1} (sequential tokens) make up for 76\% of overall input types used in all tasks (depicted in the Appendix A, Fig.\ref{fig:input}). Most popular input type is paragraph, for which about 60\% of cases represents a tweet. The remaining 24\% is split across \textit{clusters 2, 3, 4 and 5}. A subtle divergence towards the right-hand side can be noticed, starting with 2015, driven mostly by tasks from SA and IE task groups. The most dominant Input Types from each cluster are paragraph, class label, entity, question and KB. \subsection{Output Types} As shown in Fig.\ref{fig:output}, data types from \textit{clusters 2 and 3} are the majority in this case, accounting for 68\% of used representations. Class labels are repeatedly employed, especially by SA tasks. \textit{Cluster 1} types are constantly used across the years, fully dependent on the task types given in a certain year, 78\% of them coming from SEM, IE and OT. Rarely used are typed from \textit{clusters 4 and 5}, accounting for just 10\% of the total, half of which occur in SEM tasks during 2016 and 2017, complex tasks such as Community Question Answering and Chinese Semantic Dependency Parsing. We also found a possible relation between output type and popularity. In 2012-2017 tasks where outputs were in \textit{cluster 4 or 5}, attracted 8.3 teams per task on average, while in \textit{clusters 1-3} 13.9 teams/task. However, despite major increase in SemEval popularity, in 2018-2019 the former attracted only 7 teams/task, and the latter 43.5 teams/task. The group with most type variety is SEM, covering types across all clusters. On the other side of the spectrum, SA has the least variety, despite it being the most popular task group. The most dominant Output Types from each cluster are paragraph, class label, entity, answer and semantic graph. \begin{figure*} \centering \begin{subfigure}[b]{0.475\textwidth} \centering \includegraphics[height=0.9\textheight]{Output.png} \caption[]% {{\small Output Types}} \label{fig:output} \end{subfigure} \hfill \begin{subfigure}[b]{0.475\textwidth} \centering \includegraphics[height=0.9\textheight]{Evaluation_Metrics.png} \caption[]% {{\small Evaluation Metrics}} \label{fig:eval_metrics} \end{subfigure} \caption[ AAA ] {\small 96 SemEval tasks from 2012-2019} \label{fig:overall_plots_output_and_eval} \end{figure*} \section{Evaluation Metrics} We counted a total of 29 different evaluation metrics used in SemEval (Fig.\ref{fig:eval_metrics}). At a subtask level, the most frequent metric is F1-score, with 105 usages, followed by recall and precision, with 51 and 49 usages respectively, and accuracy, with 26 usages. F1, recall and precision are frequently jointly used, the last two playing the role of supporting break-down metrics for F1 in 95\% of cases. This combination is very popular, especially for IE tasks, almost half of the use coming from this task group. The top 5 evaluation metrics make up 84\% of the total number of metrics used in all years, last 12 (almost half) being only used once. In 89\% of cases when rare evaluation metrics (from Kendall's T to the right) are used, they occur in SA and SEM tasks e.g. Jaccard index in Affect in Tweets (2018) or Smatch in Meaning Representation Parsing (2016). Furthermore, 67\% of the least used evaluation metrics (only used 3 times or less) appear in 2015-2017, the same period when we could see tasks experimenting the most with input and output types. \subsection{Evaluation Metrics against Output Types} F1, recall and precision (depicted in Appendix A, Fig.\ref{fig:heatmap}) are mostly used for output types such as class label, paragraph and entity (each of which is the top output type from their clusters). Meanwhile, for output types represented by score, most used evaluation metrics are Pearson Correlation, Kendall's T, cosine similarity and Spearman Correlation. MAP, the 6th most used evaluation metric, is mostly used for ranked questions/answers either in recurring tasks such as Community Question Answering. Human judgment was only used twice, in Taxonomy Extraction Evaluation (2016) and Abstract Meaning Representation Parsing and Generation (2017). For further reference, see Appendix A. \section{Zooming in into Sentiment Analysis} \subsection{System architectures} The systematic analysis of the prevalent methods and architectures imposed particular challenges with regard to the data extraction process due to the intrinsic complexity of tasks (many systems include the composition of pre-processing techniques, rules, hand-crafted features and combinations of algorithms). Additionally, for the majority of task description papers, there is no systematic comparison between systems within a task, and consequently within group or years. Due to the consistent presence of SA along all years, we present an overview of the evolution of system architectures used in SA from 2013 to 2019 (Fig.\ref{fig:models}). In this analysis we focus on the best performing architectures. More than one best model in a task signifies best models in subtasks or that the final system was an ensemble of several algorithms. \textit{Regression based} model encompasses linear, logistic, or Gaussian regression, and \textit{Other} includes all rule-based or heavily hand-crafted models. We observe a drift in popularity of architectures from ML algorithms (2013-2016) to deep learning (DL) models (2017-2019). Despite the major adoption of DL models, traditional ML algorithms are consistently in use, both as separate models and as ensembles with DL. This is also true for other types of tasks. In many task description papers from 2018-2019, one can find ML-based systems as top performing participants. SVM-based models are still popular and in some tasks outperforms DL (2018-2, 2019-5). In the analysis of system architectures one needs to take into account that best system depends not only on the core algorithm but also on the team expertise and supporting feature sets and language resources. \begin{figure}[b!] \centering \includegraphics[width= 0.95\textwidth]{input_output_timeline.jpg} \caption{Timeline of Input Types (upper row) and Output Types (lower row) in Sentiment Analysis tasks at SemEval 2013-2019.} \label{fig:timeline} \end{figure} \subsection{Representations} The output of the SA related tasks provide an account of the evolution of sentiment and emotion representation in this community from 2013 until 2019 (Fig.\ref{fig:timeline}). At a discrete level, the number of maximum class labels representing sentiment intensity grew from 3 in 2013 to 7 in 2019. At a continuous score level, real-valued scores associated with sentiment was first used in 2015; in 2016 it switched to sentiment intensity; in 2017 it was being used as a way to determine the intensity of an emotion component out of 11 emotion types (rather than a single one, or the generic emotional intensity of a sentence). In terms of targeted subject, the tasks grew more granular over time: paragraph/word (2013), aspect terms (2014), sentence topic (2015), person (2016). Additionally, discourse evolved from simpler opinionated text in the direction of figurative language, for example: handling irony and metaphor in SA (2015), phrases comparison/ranking in terms of sense of humor (2017), irony detection (2018) and contextual emphasis (2019). \section{Discussion: What is SemEval evaluating?} The results of the analysis substantiate the following core claims, which summarises some of the trends identified in this paper: \begin{itemize} \item There is evidence of significant impact of SemEval in the overall NLP community. \item SemEval contributed to the construction of a large and diverse set of challenges with regard to semantic representation, supporting resources and evaluation methodologies and metrics. \item SemEval is becoming heavily biased towards solving classification/regression problems. We observe a major interest in tasks where the expected output is a binary or multi-class label or within a continuous real valued score. \item Sentiment Analysis tasks accounts for a disproportional attention from the community. \item There are two parallel narratives running on SemEval: low entry barrier and state-of-the-art defining. SemEval contains a rich corpus of unaddressed and complex NLP tasks, which are eclipsed by the easier low entry barrier tasks. This points to the double function of SemEval which performs a pedagogical task, serving as an entry point for early career researchers to engage within the NLP community and a state-of-the-art forum for pushing the boundaries of natural language interpretation. With the popularity of NLP applications and Deep Learning, the former function is eclipsing the latter. \item There is a significant trend to decrease the variety in the output and evaluation metrics in the recent years. While in previous years, tasks focused more on novel and exploratory tasks, recent tasks have explored, probably due to emergence of out-of-the-box DL models, this variety significantly decreased. Consequently, participants focus on easier tasks, which in part dissipates the community potential to address long-term challenges. \item Despite the recent interest in neural-based architectures, there is clear evidence of the longevity and lasting impact of older NLP methods. \end{itemize} \section{Recommendations} We believe that this paper can serve as a guideline for the selection and organisation of future SemEval tasks. Based on the analyses performed on this paper, these are the main recommendations: \begin{itemize} \item Prioritise tasks which have a clear argument on semantic and methodological challenges and novelty. \item Differentiate challenges which have a competition/pedagogical purpose from research tasks. \item Support the systematic capture of task metadata and submission data in a structured manner. This will allow for an efficient comparison between SemEval tasks and deriving insights for future SemEval editions. \end{itemize} \section{Conclusions} This paper reported a systematic quantitative analysis of SemEval, one of the primary venues for the empirical evaluation of NLP systems. The analysis, which provides a detailed breakdown of 96 tasks in the period between 2012-2019, provided quantitative evidence that: (i) SemEval has a significant impact in the overall NLP community, (ii) there is a recent drift towards a bias in the direction of Deep Learning classification methods which is eclipsing the research function of SemEval and (iii) that there is longevity and impact of older NLP methods in comparison to Deep Learning methods. \bibliographystyle{coling}
{'timestamp': '2020-06-01T02:03:32', 'yymm': '2005', 'arxiv_id': '2005.14299', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14299'}
arxiv
\section{Introduction \label{section intro}} In biostatistics, many models for survival and reliability analysis are two-state stochastic processes which lead to a particular event such as death, or the outcome of a particular drug treatment. However, applying a multi-state stochastic process allows the modeller to provide a richer and more accurate model by adding more details. These details allow to capture alternative paths to the event of interest, specify all the intermediate events, and also allow to understand partial failure modes in a progressive disease. In our context, a multi-state stochastic process is a process $X(t)$ for $t \geq 0$, where $X(t)$ can take a finite number of values $ 1,2, \ldots ,\ell$. This process can be considered as a family of random variables $X(t)$ indexed by $t$. The quantities of interest are often the probability of being in a state at a given time and the distribution of first passage times (the time until the process reaches a given state for the first time from a particular starting state). In some applications of multi-state stochastic processes, the dependence on the history of the process is negligible. Therefore, for the sake of mathematical tractability, assuming the Markov property (where future transitions between states depend only upon the current state) is convenient. For instance, continuous time Markov chains, which we refer to here as {\em Markov processes}, are widely used in modelling the movements of patients between units of a hospital or between stages of a disease, see for instance \cite{broyles2010statistical, taylor1998using}, or in the prediction of the incidence rate of diseases, see \cite{aalen1997markov}. However, in certain cases, the Markov assumption is unrealistic. For instance, in the study of human sleep stages, the sleep stages usually do not follow an exponential distribution (constant hazard rate), but can rather have other forms such as a Weibull distribution, see \cite{wang2013computational}. Further, some aspects of systems' behavior can not be captured by Markov processes. For instance, the risk of chronic diseases such as AIDS essentially depends on the time since infection, see \cite{joly1999penalized}. For these cases, applying the class of \textit{semi-Markov processes}\index{semi-Markov process} (SMP), as an extension of Markov processes, is fruitful. Here, future probability transitions depend on the sojourn time (the time spent in the current state), and the clock of each sojourn time is reset to zero after each transition into a new state. SMPs have a variety of applications in healthcare. For instance, for predicting a disease progression \cite{goshu2013modelling}, health care manpower supply prediction \cite{trivedi1987semi}, and recovery progress of patients with a specific type of disease \cite{polesel1986application}. For biomedical applications, especially those concerned with characterizing an individual's progression through various stages of a disease, a three-state semi-Markov process known as the \textit{illness-death model }is very popular (see for instance \cite{joly1999penalized, boucquemont2014should}). The illness-death model may also be applied for modelling the trajectory of patients in intensive care units (ICUs) of hospitals (see \cite{liquet2012investigating, coeurjolly2012attributable}). Here, our main focus is on the statistical methodology of semi-Markov processes and more precisely on parametric models of SMPs. We compare and contrast two approaches for defining SMPs which we denote via, {\bf I - sojourn times}, and {\bf II - intensity transition functions}. Approach I is based on the specification of the {\em sojourn time distribution,} together with a transition probability matrix of a discrete time Markov chain, which we call the {\em embedded chain}. Approach II, is based on {\em intensity transition functions} which when multiplied by an infinitesimal quantity, specify the instantaneous probability of transition between states. Note that in the literature, these are sometimes also called hazard rate functions of the SMP, however they should not be confused with hazard functions of probability distributions (such as for example the sojourn time distributions). While from a probabilistic perspective, both Approach I and Approach II are equivalent ways for describing an SMP, from a statistical perspective there are differences. In this paper, we highlight that when it comes to parameter estimation, Approach II has significant advantages over Approach I. Intrinsically this is because Approach II can be expressed by using fewer parameters. Further, we can show that the likelihood function of Approach II can be written as the product of likelihoods of two-state models. This is very helpful for reducing the computational effort for likelihood-based parameter estimation. Nevertheless, depending on the application at hand, using either approach may be useful and in certain cases researchers have chosen to use Approach~I because it focuses directly on the underlying distributions. We highlight the associated tradeoffs in the paper. The remainder of this paper is structured as follows. In Section~\ref{section:SMP}, we introduce semi-Markov processes (SMP) via both Approach I and Approach II. We also present the probabilistic relationships between the approaches. We continue with Section~\ref{section:inference} focusing on inference and specify the likelihood function for both approaches. In Section~\ref{sec:application}, we illustrate inference on two available datasets and present how to implement both approaches (for both datasets) using several contemporary R software packages. For both datasets, we compare results of fully parametric models based on both approaches and highlight the implications of each modelling choice. Section~\ref{sec:conclusion} presents some concluding remarks. All the numerical results (tables and figures) from the paper are freely reproducible via R code in a comprehensive detailed vignette available in \cite{Liq_github}. \section{Semi-Markov Processes} \label{section:SMP} A multi-state model is a continuous time stochastic process with values in a discrete set that is often applied for longitudinal medical studies, where the patients may experience several events and their related information is collected over time. The complexity of a model greatly depends on the number of states and also on the possible transitions. Figure~\ref{Fig:Multi} demonstrates a general multi-state model. See \cite{andersen2012statistical} as a classical reference for multi-state models. \begin{figure}[h] \center \includegraphics[scale=0.6]{images/Multi_state.pdf} \caption{{{\small An Illustration of a multi-state Model. }}} \label{Fig:Multi} \end{figure} A specific class of examples of multi-state models is the class of Markov processes where the state evolution jumps between levels and the process adheres to the Markov property. However, in many real-world applications, we need a stochastic process that exhibits dependence between jump times. For instance, in biostatistics, where the trajectory of patients in a hospital is considered, using a Markov process as a multi-state model imposes a stringent limitation on the sojourn time distribution in each state. This is because a key consequence of using Markov processes is the fact that state sojourn times follow the exponential distribution and is ``non-ageing'' with a constant hazard rate. In contrast, in Semi-Markov processes this assumption can be relaxed. Hence with Markov processes one is often lacking the desired degrees of freedom for modeling the dependence between jump times. Extending the modelling from Markov processes to the class of SMPs removes the restriction of memoryless (exponential) state sojourn times and at the same time, preserves the usefulness of treating the data as jump processes in continuous time. In fact, for semi-Markov processes we consider a relaxation of the Markov property for sojourn times and only the embedded chain of states is required to follow the Markov property. For this reason, SMPs are applied for modelling a variety of phenomena in different areas such as economics, reliability, and health care, see \cite{janssen2013semi}. To define an SMP, consider a homogeneous Markov chain $\{J_n\}_{n \ge 0}$ on states $\{1,2,\ldots, \ell\}$ where the probability of $n$-th ($n\geq 1$) jump from state $i$ to state $j$ for $i \neq j$ is $p_{ij}$. That is, \begin{equation} \label{eq:pij} p_{ij}=\mathbb{P}(J_{n}=j ~|~ J_{n-1}=i). \end{equation} Based on the directed graph associated with these probabilities (where arc $i \to j$ exists only if $p_{ij} > 0$) states can be classified as either transient or recurrent. {A state $i$ is {\em absorbing} if $p_{ij} = 0$ for all $j \neq i$. Note that under this definition \[ \sum_{j \neq i} p_{ij} = \begin{cases} 1 & \text{for non-absorbing}~i, \\ 0 & \text{for absorbing}~i. \end{cases} \] } Denote the increasing sequence of jump times by $T_0=0< T_1< T_2 < T_3 <\ldots$ and {define} $N(t) = \max \,\{n : T_n \leq t\}$ for $t\geq 0$. This is a count of the number of transitions up to time $t$. The stochastic process $X(t):= J_{N(t)}$ is said to be a {\em semi-Markov process (SMP)} if whenever the process enters state $i$, the next state is $j$ with probability $p_{ij}$ and given that the next state to be entered is $j$, the time until the transition from $i$ to $j$ is a random variable with cumulative distribution function $F_{ij}(t)$: \begin{equation} \label{eq:Fij} F_{ij}(t)=\mathbb{P}(\tau_n \leq t ~|~ J_{n-1}=i, J_{n}=j), \quad t\geq 0, \end{equation} where $\tau_n= T_n-T_{n-1}$, see Chapter 4 of \cite{ross1996stochastic}. Hence in general, SMPs are not Markov processes as they do not posses the Markov property. Further, a semi-Markov process allows arbitrarily distributed sojourn times in any state but retains the Markov property for the embedded (discrete time) Markov chain, $\{J_n\}_{n \ge 0}$. In many applications of SMPs in healthcare, a very popular three state semi-Markov process known as the \textit{illness-death model} \index{illness-death model} is applied, see for instance \cite{polesel1986application}. \begin{figure}[h] \center \includegraphics[scale=0.6]{images/IllnessDeathModel.pdf} \caption{\label{Fig:IllD}{{\small The Illness-Death Model. }}} \end{figure} \paragraph{Illness-death model} The illness-death model is the most common model in epidemiology (see Figure~\ref{Fig:IllD}), where it is often applied in studying chronic diseases. In this model, we have three states ``Health'', ``Illness' and ``Death', denoted by 1, 2 and 3, respectively. There are three kinds of transitions: $1 \to 2 $, $2 \to 3 $ and $1 \to 3$ and state $3$ is absorbing. Since this model is often used to describe severe illnesses, there is no possibility of recovery, and therefore the model is irreversible\footnote{To avoid confusion, note that this term is also used for the different concept of a ``reversible'' Markov chain appearing in a different setting.}. In cases where treatments may yield remission, it is more appropriate to construct a model with an additional state ``Remission'' rather than to consider that there is a possibility of moving back to the ``Healthy'' state. Here, we consider the general multi-state model with all possible transitions as illustrated in Figure~\ref{Fig:Multi} which includes both illness-death model and its reversible version (see Figure~\ref{Fig:33}). We now arrive at our key point dealing with SMPs. Here we contrast the two approaches which we denote via, {\bf I - sojourn times}, and {\bf II - intensity transition functions}. Approach I was already used to define SMPs above. We spell out further details of Approach I and then continue to introduce Approach II. \begin{figure}[h] \center \includegraphics[scale=0.6]{images/IllnessDeathModel_G.pdf} \caption{\label{Fig:33}{{\small The Reversible Illness-Death Model. }}} \end{figure} \subsection{Approach I: Sojourn Times} As defined above, an SMP, $X(t)$, can be constructed via the sequence $\{(J_n, T_n)\}_{n\ge 0}$, of states and jump times respectively. The underlying parameters of this construction involve the transition probabilities of the embedded chain, $p_{ij}$ presented in \eqref{eq:pij}, as well as the distributions of the sojourn times for each transition $i \to j$, presented in \eqref{eq:Fij}. {The transition probabilities of the embedded chain are often organized in a matrix, $P = [p_{ij}]$ (where we set $p_{ii} = 0$). Note that $P$ restricted to the non-absorbing states is a stochastic matrix.} Further, assuming the sojourn time distributions are continuous, they are often represented in different forms including the probability density function, the survival function or the hazard rate function. We now present the details. The \textit{probability density function} of the sojourn time is \begin{equation} \label{eq:fijI} f_{ij}(t) = \lim_{\bigtriangleup t \rightarrow 0} \frac{1}{\bigtriangleup t}\mathbb{P}(\tau_n\in (t, t+\bigtriangleup t) ~|~J_{n-1}=i, J_{n}=j). \end{equation} % The corresponding \textit{survival function} is \begin{equation} \label{eq:SijI} S_{ij}(t) = \mathbb{P}(\tau_n>t ~|~ J_{n-1}=i, J_{n}=j)=1-F_{ij}(t). \end{equation} (Note that $S_{ij}(t)$ is a decreasing function, that is $S_{ij}(0)=1$ and $\lim_{t \rightarrow +\infty} S_{ij}(t)=~0$). The \textit{hazard function} \index{hazard rate function} which is often thought of as the probability that a jump occurs in a specified interval $(t, t+\bigtriangleup t) $ given no jump before time $t$, is \begin{equation} \label{eq:alphaijI} {\alpha}_{ij}(t) = \lim_{\bigtriangleup t \rightarrow 0} \frac{1}{\bigtriangleup t}\mathbb{P}\big(\tau_n \in (t, t+\bigtriangleup t) ~|~ J_{n-1}=i, J_n=j, \tau_n>t). \end{equation} Here, note that by definition of conditional probability we have \begin{equation}\label{eq:m} \alpha_{ij}(t)=\frac{f_{ij}(t)}{S_{ij}(t)}, \qquad \mbox{and} \qquad f_{ij}(t)= \alpha_{ij}(t) e^{-\int_0^t \alpha_{ij}(u) du}. \end{equation} It is also useful to define the probability of staying in a current state $i$ for at least $t$ time units. We call this the survival function of the waiting/holding time in state $i$, and denote it via \begin{equation} \label{eq:S-i} S_{i}(t)= \mathbb{P}(\tau_n>t ~|~ J_n=i) = \sum_{j \neq i} p_{ij} S_{ij}(t). \end{equation} \subsection{Approach II, Intensity Transition Functions} The first approach required specification of the parameters using two types of objects, transition probabilities of the embedded Markov chain, and the distribution of sojourn times given a transition $i \to j$. The second approach which we present now is more succinct in that it only requires one type of object: {\em intensity transition functions}. These functions are defined via \begin{equation} \label{eq:alphaTildeij} \tilde{\alpha}_{ij}(t) = \lim_{\bigtriangleup t \rightarrow 0} \frac{1}{\bigtriangleup t}\mathbb{P}( \tau_n \in (t, t+\bigtriangleup t), J_{n}=j ~|~ J_{n-1}=i, \tau_n>t), \end{equation} and are similar in nature to hazard rates. However, they should not be treated as hazard rate functions of a probability distribution. They rather indicate the instantaneous probability of making a transition from state $i$ to state $j$ after spending $t$ time units in state $i$ since the last transition. However summing up over all target states $j$, we do obtain a hazard rate of a probability distribution which we denote via $ \tilde{\alpha}_i(t) = \sum_{j \neq i} \tilde{\alpha}_{ij}(t). $ This is the hazard rate of the waiting/holding time in state $i$. We can use this approach to obtain an alternative expression to $S_i(t)$ of \eqref{eq:S-i}. \begin{equation} \label{eq:SiFromAlphaTilde} S_i(t) = e^{-\int_0^t \tilde{\alpha}_i(u) \, du} = e^{-\int_0^t \sum_{j \neq i} \tilde{\alpha}_{ij}(u) \, du}. \end{equation} Using Approach II, more formally, the meaning of the intensity transition functions is \begin{equation} \label{eq:uglyDef} \lim_{\Delta t \to 0} \frac{\mathbb{P}\big(X(t+u + \Delta t) = j ~|~ X(t) =i, X(t^-) \neq i, \tau_{N(t)+1} > u\big)}{\Delta t} = \tilde{\alpha}_{ij}(u), \end{equation} where using the notation defined previously, $\tau_{N(t)+1}$ is the time elapsed since the last transition, measured at time $t$. The conditional probability in \eqref{eq:uglyDef} is conditional on the fact that the last transition was at time $t$ into state $i$ and up to time $t+u$ there have not been any further transitions. Given this condition, it indicates the instantaneous probability of: (i) making a transition at time $t+u$. (ii) Making the transition into state $j$. It can be shown that specification of the intensity transition functions $\tilde{\alpha}_{ij}(\cdot)$ completely specify the probability law of an SMP. See \cite{breuer2005introduction} for a formal description where one can also use the notation ${\cal H}(t^-)$ to define the history of the process just before time $t$, i.e. up to $t^-$. This can formally be defined as the sigma algebra in a {filtration} associated with the stochastic process. Related notation often used in the literature is the (conditional on history) transition probability to be in state $j$ at time $t+u$, after being in state $i$ in time $t$. This is often {denoted by} $P_{ij}(t, t+u)=\mathbb{P}\big(X(t+u) = j ~|~ X(t) =i, {\cal H}(t^-)\big)$. {We note that Approach~II can be viewed as a collection of competing risk models where at the instance of arriving to a new state, a new set of cause-specific hazard rates is defined. See for example \cite{andersen2002competing} where a competing risk model is presented as a multi-state model and the cause-specific hazard rates terminology is used. \subsection{Relations Between the Two Approaches} \label{sec:relations} We now wish to show how for the same SMP, one can use either the parameters of Approach~I or the parameters of Approach~II and interchange between them. A key relationship is the following \begin{equation} \label{eq:relation-alpha-alphatilde} \tilde{\alpha}_{ij}(t)= \frac{p_{ij}S_{ij}(t)}{S_{i}(t)} \alpha_{ij}(t) = p_{ij} \frac{f_{ij}(t)}{S_i(t)}. \end{equation} It is established using the conditional probabilities, defined in \eqref{eq:pij}, \eqref{eq:SijI}, \eqref{eq:S-i}, and \eqref{eq:alphaijI}. This key relationship also yields an interpretation of the {\em cumulative incidence function} for the $i \to j$ transition which we denote via $\text{CIF}_{ij}(\cdot)$. This is a common measure used in the field of competing risks, see for example \cite{koller2012comp}, that determines the probability of transitioning into $j$ before or at time $t$. By rearranging and integrating both sides of \eqref{eq:relation-alpha-alphatilde} we obtain the following representation of the cumulative incidence function. \begin{equation} \label{eq:cumulativeIncidence} \text{CIF}_{ij}(t) = \int_0^t S_i(u) \tilde{\alpha}_{ij}(u) \, du = \int_0^t f_{ij}(u) p_{ij} \, du = p_{ij} F_{ij}(t). \end{equation} We can now convert between the parameterizations of both approaches as follows. {\bf Approach I $\to$ Approach II.} Given $\alpha_{ij}(\cdot)$ and $p_{ij}$, obtain $\tilde{\alpha}_{ij}(\cdot)$ as follows. \begin{equation} \label{eq:ItoII} \tilde{\alpha}_{ij}(t)= p_{ij} \frac{ e^{-\int_0^t \alpha_{ij}(u) \, du}}{\sum_{k \neq i} p_{ik} e^{-\int_0^t \alpha_{ik}(u) \, du}} \alpha_{ij}(t). \end{equation} This follows directly from \eqref{eq:relation-alpha-alphatilde}. {\bf Approach II $\to$ Approach I.} Given $\tilde{\alpha}_{ij}(\cdot)$ obtain $p_{ij}$ and $\alpha_{ij}(\cdot)$: First we have, \begin{equation} \label{eq:pijIItoI} p_{ij} = \int_0^\infty \tilde{\alpha}_{ij}(t) e^{-\int_0^t \sum_{k \neq i} \tilde{\alpha}_{ik}(u) \, du} \, dt. \end{equation} This can also be obtained from \eqref{eq:cumulativeIncidence} by taking $t \to \infty$. Once $p_{ij}$ values are at hand we again use \eqref{eq:relation-alpha-alphatilde} and isolate $f_{ij}(t)$ to obtain, \begin{equation} \label{eq:densTildeTrans} f_{ij}(t) = \tilde{\alpha}_{ij}(t) \, \frac{e^{-\int_0^t \sum_{k \neq i} \tilde{\alpha}_{ik}(u) \, du}}{p_{ij}}, \end{equation} from which we can obtain $\alpha_{ij}(t)$ using \eqref{eq:m} in the standard manner. \subsection{Examples} \label{sec:examples} We now present three examples illustrating the relationship between the two approaches. \noindent \paragraph{Example 1: Continuous Time Markov Chains (CTMC)} A (finite state) CTMC is a multi-state stochastic process on states $\{1,\ldots,\ell\}$ that is time homogenous and satisfies the Markov property. That is, $ {\mathbb P}\big(X(s+t) = j ~|~ X(s) = i, {\cal H}(s^-)\big) = {\mathbb P}\big(X(t) = j ~|~ X(0) = i \big). $ {For simplicity of notation we restrict attention to CTMCs without absorbing states.} Such chains can be parameterized in several ways, two of which are reminiscent of Approach~I, and Approach~II above: \begin{itemize} \item CTMC Approach I: Define a $\ell \times \ell$ stochastic transition probability matrix $P$ (non-negative entries and rows sum to $1$) with $0$ entries in the diagonal. Denote the entries via $P_{ij}$. This is often called the transition probability matrix of the embedded discrete time Markov chain. Then define a vector of rates of length $\ell$, {\color{blue}$\boldsymbol {\lambda}$}, where $\lambda_i^{-1}$ denotes the mean holding time of state $i$. Then from the theory of CTMCs, see for example \cite{breuer2005introduction}, the process evolves as follows. If at time $t$ the process is in state $i$, an exponential random variable with parameter $\lambda_i$ is generated to determine a holding duration. After that duration passes a transition from state $i$ to state $j$ occurs with probability $P_{ij}$. The durations and the transition choice are independent. The process then repeats. It is now evident that such a description of a CTMC is a special case of {\bf Approach I} for SMPs, where \begin{equation} \label{eq:CTMC1asSMP} \alpha_{ij}(t) = \lambda_i \qquad \mbox{and} \qquad p_{ij} = P_{ij}. \end{equation} Observe that $\alpha_{ij}(t)$ is independent of $t$ and independent of the target state $j$. \item CTMC Approach II: Define a $\ell \times \ell$ generator matrix $Q$ (non-negative entries on the off-diagonal, {negative} entries on the diagonal, and rows sum to $0$). Denote the entries via $q_{ij}$. Then treat the process as an SMP using {\bf Approach II} with \begin{equation} \label{eq:CTMC2asSMP} \tilde{\alpha}_{ij}(t) = q_{ij}, \end{equation} Observe that $\alpha_{ij}(t)$ is independent of $t$. \end{itemize} It is well known from the theory of CTMCs the two parameterizations {are equivalent}. \noindent {\bf CTMC Approach I $\to$ CTMC Approach II}: \[ q_{ij} = \begin{cases} \lambda_i P_{ij} & i \neq j,\\ -\lambda_i & i=j, \end{cases} \] {\bf CTMC Approach II $\to$ CTMC Approach I}: \[ P_{ij} = \frac{q_{ij}}{ \sum_{k \neq i} q_{ik}}, \qquad \mbox{and} \qquad \lambda_i = \sum_{k \neq i} q_{ik} = -q_{ii}. \] We now verify that these transformations directly agree with the relationship between Approach I of the SMP and Approach II of the SMP. Using \eqref{eq:ItoII} and \eqref{eq:CTMC1asSMP} we have, \begin{equation} \label{eq:benoitGivingCourseInDenemark} \tilde{\alpha}_{ij}(t) = P_{ij} \frac{e^{-\int_0^t \lambda_i \, du}}{\sum_{k \neq i} P_{ik} e^{-\int_0^t \lambda_i \, du}} \lambda_i = P_{ij} \lambda_i = q_{ij}. \end{equation} Going in the other direction using \eqref{eq:pijIItoI} and remembering that since $Q$ is a generator matrix, $q_{ii} = - \sum_{k \neq i} q_{ij} < 0$, we have, \[ p_{ij} = \int_0^\infty q_{ij} e^{-\int_0^t \sum_{k \neq i} q_{ik} \, du} \, dt = q_{ij} \int_0^\infty e^{q_{ii} t} \, dt = \frac{q_{ij}}{-q_{ii}}. \] Now using \eqref{eq:densTildeTrans} we have, \[ f_{ij}(t) = -q_{ij} \frac{e^{\int_0^t q_{ii} \, du }}{q_{ij} / q_{ii}} = -q_{ii} e^{q_{ii}t} = \lambda_i e^{-\lambda_i t}. \] This is an exponential density and hence it has a constant hazard rate $\alpha_{ij}(t) = \lambda_{i}$. \noindent \paragraph{Example 2: Exponential Sojourn Times} The example above illustrates that an SMP parameterized via Approach I where $\alpha_{ij}(t)$ is constant in time and also independent of $j$ yields constant (Approach II) transition intensity functions, $\tilde{\alpha}_{ij}(t)$. That is, constant (Approach~I) hazard rates yield constant transition intensity functions, but under the condition that ${\alpha}_{ij}(t)$ is the same for all target states $j$. We now show that this condition is necessary for having constant transition intensity functions. To see this, use \eqref{eq:ItoII} with $\alpha_{ij}(t) = \lambda_{ij}$ where for some $j_1$ and $j_2$, $\lambda_{ij_1} \neq \lambda_{i j_2}$. Now, \begin{equation} \label{eq:nonConstantTildeAlphaSurrr} \tilde{\alpha}_{ij}(t)= p_{ij} \frac{ e^{-\lambda_{ij} t}}{\sum_{k \neq i} p_{ik} e^{- \lambda_{ik}t}} \lambda_{ij}. \end{equation} Since $\lambda_{ij_1} \neq \lambda_{i j_2}$ we are not able to cancel out the exponent as was done in \eqref{eq:benoitGivingCourseInDenemark}. Interestingly, the converse does not hold. The previous example showed that time independent transition intensity functions always yield a CTMC and hence constant (Approach I) hazard rates. \noindent \paragraph{Example 3: Weibull Distributions} The Weibull continuous univariate distribution of a non-negative random variable is parameterized by a shape parameter $\eta>0$ and a scale parameter $\mu>0$. It has density, survival function, and hazard rate functions respectively given via, \[ f(t) = \frac{\eta}{\mu} \Big(\frac{t}{\mu} \Big)^{\eta-1} e^{-(t/\mu)^\eta}, \qquad S(t) = e^{-(t/\mu)^\eta}, \qquad \alpha(t) = \frac{\eta}{\mu} \Big(\frac{t}{\mu} \Big)^{\eta-1} . \] It is appealing in survival analysis and reliability analysis because if $\eta<1$ the hazard rate is monotonically decreasing; if $\eta=1$ the hazard rate is constant (an exponential distribution) and if $\eta>1$ the hazard rate is monotonically increasing. Say now that we are using Approach I and parameterize all of the sojourn time distributions as Weibull distributions, where for transition $i \to j$ we have respective scale and shape parameters $\mu_{ij}$ and $\eta_{ij}$. Now, if we were to consider the Approach II representation, then from \eqref{eq:ItoII} the transition intensity functions are \begin{equation} \label{eq:benoitGivingCourseInDenemark1} \tilde{\alpha}_{ij}(t) = p_{ij} \frac{ e^{-(t/\mu_{ij})^{\eta_{ij}}}}{\sum_{k \neq i} p_{ik} e^{-(t/\mu_{ik})^{\eta_{ik}}}} \frac{{\eta_{ij}}}{\mu_{ij}} \Big(\frac{t}{\mu_{ij}} \Big)^{{\eta_{ij}}-1} = K_{ij}(t) t^{\eta_{ij} - 1}, \end{equation} where we use the notation $K_{ij}(t)$ to represent all of the components of $\tilde{\alpha}_{ij}(t)$ excluding $t^{\eta_{ij} - 1}$. Now the form of $K_{ij}(t)$ can determine if the Approach II representation is of a Weibull type or not. A Weibull type representation will follow if $K_{ij}(t)$ is independent of $t$, otherwise it is not. We now see that if for a fixed $i$ and every $j_1$ and $j_2$ with $j_1 \neq j_2$ we have that \begin{equation} \label{eq:conditionForIandIIWeibullTogether} \eta_{ij_1} = \eta_{ij_2}, \qquad \mbox{and} \qquad \mu_{ij_1} = \mu_{ij_2}, \end{equation} then, $K_{ij}(t)$ is independent of $t$ and we obtain a Weibull type Approach II representation with, \begin{equation} \label{eq:dudesInBordouxDoWeibull} \tilde{\alpha}_{ij}(t) = p_{ij} \frac{{\eta_{ij}}}{\mu_{ij}} \Big(\frac{t}{\mu_{ij}} \Big)^{{\eta_{ij}}-1} = \frac{\eta_{ij}}{p_{ij}^{-1/\eta_{ij}}\mu_{ij}} \Bigg(\frac{t}{p_{ij}^{-1/\eta_{ij}}\mu_{ij}} \Bigg)^{\eta_{ij}-1}, \end{equation} and hence the scale parameter is modified to $p_{ij}^{-1/\eta_{ij}}\mu_{ij}$ and the shape parameter keeps the same form. Otherwise (if there exists $j_1$ and $j_2$ such that \eqref{eq:conditionForIandIIWeibullTogether} does not hold), then $\tilde{\alpha}_{ij}(t)$ cannot be of the Weibull type as in \eqref{eq:dudesInBordouxDoWeibull}. Going the other way, assume we are using Approach II with Weibull type transition intensity functions, \[ \tilde{\alpha}_{ij}(t) = \frac{\eta_{ij}}{\mu_{ij}} \Big(\frac{t}{\mu_{ij}} \Big)^{\eta_{ij}-1} . \] Then by integrating \eqref{eq:pijIItoI} we can in principle obtain $p_{ij}$. It turns out that if for a given state $i$, the shape parameters of all the transition intensity functions is the same (denote it via $\eta_i$) then the integration yields an explicit form, \begin{equation} \label{eq:manMan7} p_{ij} = \frac{\mu_{ij}^{\eta_{i} }}{\sum_{k \neq i} \mu_{ik}^{\eta_{i}} }, \end{equation} otherwise, there is not an explicit solution. In such a case where $\eta_{ij} = \eta_i$ for all $j$, we also have from equation \eqref{eq:densTildeTrans}, \begin{equation} \label{eq:fijStopMan} f_{ij}(t) = \frac{\eta_{i}}{\mu_{ij}} \Big(\frac{t}{\mu_{ij}} \Big)^{\eta_{i}-1} \, \frac{ e^{ -\sum_{k \neq i} \big(\frac{t}{\mu_{ik}}\big)^{\eta_i} } } { \frac{\mu_{ij}^{\eta_{i} }}{\sum_{k \neq i} \mu_{ik}^{\eta_{i}} }}. \end{equation} Further, if $\mu_{ij} = \mu_i$ for all $j$ then $p_{ij}$ of \eqref{eq:manMan7} reduces to $\ell_i^{-1}$ where $\ell_i < \ell$ is the number of possible target states from state $i$. Note that this form is not specific to the Weibull type intensity transition function, but will hold whenever the intensity transition functions out of state $i$ are the same. However, with the Weibull case we can continue further and \eqref{eq:fijStopMan} can be represented as, \[ f_{ij}(t) =\ell_i \frac{\eta_{i}}{\mu_{i}} \Big(\frac{t}{\mu_{i}} \Big)^{\eta_{i}-1} \, { e^{ -\ell_i \big(\frac{t}{\mu_{i}}\big)^{\eta_i}}} = \frac{\eta_{i}}{\ell_i^{-1/\eta_{i}} \mu_{i}} \Big(\frac{t}{\ell_i^{-1/\eta_{i}}\mu_{i}} \Big)^{\eta_{i}-1} \, { e^{ - \big(\frac{t}{\ell_i^{-1/\eta_{i}}\mu_{i}}\big)^{\eta_i}}}, \] which denotes a Weibull distribution with same shape parameter as the transition intensity function and a scale parameter equal to $\ell_i^{-1/\eta_{i}}\mu_{i}$. \section{Likelihood and Inference} \label{section:inference} Here we focus on inference for the fully-parametric semi-Markov model defined by the two above mentioned approaches. Survival analysis usually applies for cohort or clinical studies, hence the data is usually gathered from the same subjects repeatedly during a time interval $[0,{\cal T}]$. A key issue in survival analysis and event history analysis is the occurrence of incomplete or sparse observations. For instance, in the case of chronic diseases, when the event of study is death, time of occurrence of this event is not observed for the subjects still alive at time~${\cal T}$. This type of incomplete observation is called \textit{right-censoring}. There are other kinds of incomplete data like left-censoring and interval censoring, see \cite{andersen2005censored,commenges2015dynamical}. \cite{andersen2002multi} present different incomplete data forms which can be handled in multi-state frameworks. Our focus in this paper is right censored data corresponding to when at the end of the observation period, not all individuals under study have reached an absorbing state. As our focus is on the fully-parametric case we now present the likelihood functions for both Approach~I and Approach~II. We assume there are $n$ subjects denoted via $h=1,\ldots,n$, for which data is collected and we assume independence between subjects. For each subject, we distinguish between two cases depending on if the subject is in an absorbing state at time ${\cal T}$ or not. {Note that in principle we can set ${\cal T}$ to be subject specific, but for simplicity we do not do so here.} This is recorded via $\delta_h$ where $\delta^{(h)} = 1$ implies no right censoring (subject is in an absorbing state at time ${\cal T}$), and $\delta^{(h)} = 0$ implies right censoring. Further, we record the state evolution denoted via the sequence $\{J\}$ and the sojourn times denoted via the sequence $\{\tau\}$. For simplicity, we assume that all subjects start at the same fixed and known state, denoted via $J_0$. This can be easily generalized. For subject $h$ during $[0,{\cal T}]$, we use $N^{(h)}$ to denote the number of state transitions up to time ${\cal T}$. The data of the subject is represented via \[ {\cal H}^{(h)}=\big(J_{0},J^{(h)}_{1}, \ldots, J^{(h)}_{N^{(h)}}, \tau^{(h)}_{1}, \ldots, \tau^{(h)}_{N^{(h)}} , \delta^{(h)}\big). \] Note that if $\delta^{(h)} = 0$ and there is right censoring then we are also interested in the time duration $U^{(h)}$ after the last state is visited. This quantity is represented via, \begin{equation} \label{eq:uDefThing} U^{(h)} = {\cal T} - \sum_{i=1}^{N^{(h)}} \tau^{(h)}_{i}. \end{equation} As our subjects are independent we can consider the likelihood contribution of each subject $h$ in isolation, and after denoting it via ${\cal L}^{(h)}$, the full likelihood is \begin{equation} \label{eq:oneHundredPercentCorrect} {\cal L}=\prod_{h=1}^n {\cal L}^{(h)}. \end{equation} The specific form of ${\cal L}^{(h)}$ now depends on if we are using Approach~I or Approach~II and as we show below, in Approach~II, it can further be decomposed as in \eqref{eq:decomposeAppII}. \subsection{Likelihood for Approach~I} The form of ${\cal L}^{(h)}$ based on ${\cal H}^{(h)}$ is, \begin{equation} \label{eq:approachIlikelihood} {\cal L}^{(h)}= \Big( \prod_{k=1}^{N^{(h)}} p_{J_{k-1} \,J_{k}} \, f_{J_{k-1} \,J_{k}}(\tau_{k}) \Big)\,\Big(S_{J_{N^{(h)}}}(U^{(h)})\Big)^{1- \delta^{(h)}}, \end{equation} where for brevity we omit the $(h)$ superscripts for the state and sojourn time sequences $\{J\}$ and $\{\tau\}$. To further understand \eqref{eq:approachIlikelihood} consider a recursive construction where each transition without censoring based on $J_{k-1} \to J_k$ with a sojourn time of $\tau_k$ has a likelihood contribution $p_{J_{k-1} \,J_{k}} \, f_{J_{k-1} \,J_{k}}(\tau_{k})$. Further, in case of censoring the last censored transition has likelihood contribution $S_{J_{N^{(h)}}}(U^{(h)})$ based on the survival function of the holding time \eqref{eq:S-i}, corresponding to the last observed state $J_{N^{(h)}}$. \subsection{Likelihood for Approach II} We refer to the key relationship \eqref{eq:relation-alpha-alphatilde} and replace $p_{ij}f_{ij}(u)$ in \eqref{eq:approachIlikelihood} with $\tilde{\alpha}_{ij}(u) S_{i}(u)$ to obtain, \begin{equation} \label{eq:approach2likelihoodA} {\cal L}^{(h)}= \Big( \prod_{k=1}^{N} \tilde{\alpha}_{J_{k-1} J_k}(\tau_k) S_{J_{k-1}}(\tau_k) \Big) \,\Big(S_{J_{N}}(U)\Big)^{1- \delta}, \end{equation} where for brevity we omit all superscripts $(h)$. Further, we manipulate the likelihood contribution of each subject as follows: \begin{equation} \label{eq:approach2likelihoodC} \begin{array}{ll} \displaystyle{\cal L}^{(h)} = \Big( \prod_{k=1}^{N} \tilde{\alpha}_{J_{k-1} J_k}(\tau_k) e^{-\int_0^{\tau_k} \tilde{\alpha}_{J_{k-1}}(u) \, du} \Big) \Big(e^{-\int_0^{U} \tilde{\alpha}_{J_N}(u) \, du}\Big)^{1-\delta} \\[12pt] \,\qquad= \displaystyle \prod_{k=1}^{N+1} \big(\tilde{\alpha}_{J_{k-1} J_k}(\tau_k)\big)^{ \mathbbm{1}_{\{k\neq N+1\}}} \, e^{-\int_0^{\tau_k} \tilde{\alpha}_{J_{k-1}}(u) \, du}. \end{array} \end{equation} In the first line we use the representation in \eqref{eq:SiFromAlphaTilde}. For the second line, by increasing the summation from $N$ to $N+1$ we are able to remove $\delta$ by defining $\tau_{N+1} = U$, $J_{N+1} \equiv -1$, and using the fact that $\tilde{\alpha}_{ij}(u) \equiv 0$ in cases where $i$ is an absorbing state and $0^0 \equiv 1$. Now, we are able to separate ${\cal L}^{(h)}$ into the form \begin{equation} \label{eq:decomposeAppII} {\cal L}^{(h)} = \prod_{i=1}^\ell \prod_{j=1}^\ell {\cal L}^{(h)}_{ij}, \end{equation} following similar ideas as those initially presented in \cite{hougaard1999multi}. To achieve such a separation, it is useful to define the indicators \[ \delta^{k-1}_{i \to j} =\mathbbm{1}_{\{J_{k-1}=i,\, J_k=j\} }, \qquad \mbox{and} \qquad \delta^{k-1}_{i \not \to j} = \mathbbm{1}_{\{J_{k-1}=i,\, J_k \neq j\}}. \] We may now manipulate \eqref{eq:approach2likelihoodC} to obtain \begin{equation} \label{eq:niceNiceCorrectEquation} {\cal L}^{(h)}_{ij} = \prod_{k=1}^{N+1}\Big(\tilde{\alpha}_{ij}(\tau_k) e^{-\int_0^{\tau_k} \tilde{\alpha}_{ij}(u)\,du}\Big)^{\delta^{k-1}_{i \to j} } \Big( e^{-\int_0^{\tau_k} \tilde{\alpha}_{ij}(u)\,du}\Big)^{\delta^{k-1}_{i \not \to j}}. \end{equation} The form of \eqref{eq:oneHundredPercentCorrect}, \eqref{eq:decomposeAppII}, and \eqref{eq:niceNiceCorrectEquation} allows us to treat each transition separately as if each transition intensity transition function $\tilde{\alpha}_{ij}(\cdot)$ has its own set of parameters. \subsection{Parametric forms and Covariate Information} \label{sec:thePlaceToBe} In carrying out inference, we assume a parametric form for $\alpha_{ij}(\cdot)$ in Approach~I or $\tilde{\alpha}_{ij}(\cdot)$ in Approach~II. We also allow for covariate information where the natural way to introduce covariates in a multi-state model is a \textit{Cox-like proportional hazard model} which can be defined by using either the hazard function of the sojourn times or by intensity transitions, see \cite{meira2009multi}. Hence for a vector of covariates $Z$, we have \begin{equation} \label{Eq:covariate-sojourn} {\alpha_{ij}}(t ~|~ Z)={\alpha}^{({\theta}_{ij})}_{ij,0}(t) e^{\beta_{ij}^TZ}, \end{equation} for Approach~I. Further we have \begin{equation} \label{Eq:covariate-approachII} \tilde{\alpha}_{ij}(t~|~ Z)={\tilde{\alpha}}^{(\tilde{\theta}_{ij})}_{ij,0}(t) e^{\tilde{\beta}_{ij}^TZ}, \end{equation} for Approach~II. Here ${\alpha}^{({\theta}_{ij})}_{ij,0}(\cdot)$ and ${\tilde{\alpha}}^{(\tilde{\theta}_{ij})}_{ij,0}(\cdot)$ are the baseline functions for the hazard rate and transition intensity functions respectively. They each follow a parametric form, determined via $\theta_{ij}$ and $\tilde{\theta}_{ij}$ respectively. Further, $\beta_{ij}$ and $\tilde{\beta}_{ij}$ are the regression parameters for transition $i \to j$ associated with the covariates of the subject. Observe that there are major differences in the interpretation of the regression coefficients $\beta_{ij}$ of Approach~I and $\tilde{\beta}_{ij}$ of Approach~II. The { former determine} the hazard ratios dealing with sojourn times and bear no effect on the actual transitions of the SMP. The latter, determine the hazard ratios dealing with risks and also affect the instantaneous rate of transitioning. When estimating the parameters for such a model, with Approach~I, we also need to estimate $p_{ij}$, whereas with Approach~II this is not needed as $p_{ij}$ is implicitly determined via \eqref{eq:pijIItoI}. Interestingly, via Approach~II, we have that the covariates implicitly affect $p_{ij}$ ,whereas with Approach~I, we may wish to set $p_{ij}(Z)$ using multinomial regression, however it isn't common practice. \subsection{Contrasting Inference for Approach~I and Approach~II} The key difference in the likelihood expressions between Approach~I \eqref{eq:approachIlikelihood} and Approach~II \eqref{eq:decomposeAppII} and \eqref{eq:niceNiceCorrectEquation} is in computational tractability. As noted by \cite{Krol} the optimization of the likelihood for Approach~I could be challenging when the number of covariates and parameters is large due to a complex form of the sojourn time distribution. This is especially the case when the number of variables is large compared to the size of the data. It should further be noted that modeling using Approach~I requires the embedded chain parameters in addition to the parameters involved in \eqref{Eq:covariate-sojourn}. This means that for a model with $\ell$ states, there may be up to $\ell^2 -\ell$ more parameters to estimate when using Approach~I, in comparison to Approach~II, where all the parameters appear in \eqref{Eq:covariate-approachII}. With Approach~II, the decoupling in \eqref{eq:decomposeAppII} allows to optimize the likelihood for each transition $i \to j$ separately if each hazard intensity transition function \eqref{Eq:covariate-approachII} has its own set of parameters $\tilde{\theta}_{ij}$ and $\tilde{\beta}_{ij}$. In such a framework, the full likelihood of the SMP can be maximized separately by maximizing the likelihood of the different separate two-state models, see \cite{meira2009multi}. Also, the inference of the SMP can be easily handled by using survival models like the Cox model as the separate likelihood arising in survival analysis. Hence Approach~II enables fitting SMP models using survival analysis methods and software, see for example \cite{therneau2000cox,cook2007statistical,jackson2016flexsurv}. This also applies to the case where extensions to the proportional hazard assumption are needed. The forms in \eqref{Eq:covariate-sojourn} and \eqref{Eq:covariate-approachII} are clearly based on a proportional hazard assumption with fixed covariates where there is only a multiplicative effect on the baseline hazard functions independent of time. An extension is to consider time-dependent covariates $Z(t)$ as in \cite{andersen2000multi,andersen2002multi}. Further, in both proportional models the effect of variables is assumed to have a linear (or log-linear) functional form. A more flexible model is to consider non-linear effects using smooth functions of the covariates such as the Generalized Additive Model (GAM) presented by \cite{hastie1990exploring}. With such extensions, using Approach~II is much more straightforward than using Approach~I due to the decoupling and because there is ample statistical software available for survival analysis. One may also wish to incorporate random effects in the models using frailty models. In this case, both \eqref{Eq:covariate-sojourn} and \eqref{Eq:covariate-approachII} could also include random effect to take into account the correlation between observations/subjects. This has been handled in \cite{liquet2012investigating} for Approach~II by exploiting the decoupling of the likelihood. Such random effects may also be incorporated in Approach~I, however the computational effort will be greater. \section{Semi-Markov Application in Practice}\label{sec:application} In this section, we illustrate the inference of the semi-Markov model on two real datasets. {Our purpose with these examples is to help practitioners see how the mathematical details presented above interact with statistical software. In light of this, we chose datasets that have been analyzed previously with a one sided view (either Approach~I or Approach~II but not both). These datasets are readily available in the R ecosystem.} All the numerical results including tables and figures, are freely reproducible through R codes in a comprehensible detail vignette available in \cite{Liq_github}. For both datasets, we compare results of full parametric models based on Approach~I where we estimate sojourn time distributions and transition probabilities of the embedded chain, and based on Approach~II where we estimate transition intensity functions. To carry out estimation using Approach~I we use the { \texttt{SemiMarkov}} package, see \cite{listwon2015semimarkov}. This package implements inference using the likelihood \eqref{eq:oneHundredPercentCorrect} with \eqref{eq:approachIlikelihood} while allowing to use different parametric forms for the sojourn time distribution including exponential, Weibull, and exponentiated Weibull, see \cite{foucher2005semi}. It also supports covariates with standard inference for the covariate coefficients $\beta_{ij}$, including the Wald test. It allows the possibility to include different covariates for each transition. While the focus of the inference with this package is Approach~I, as output, the package can automatically provide the intensity transition functions $\tilde{\alpha}_{ij}(\cdot)$, referred to as the ``hazard function of the SMP''. For Approach~II, the decoupling in \eqref{eq:decomposeAppII} with \eqref{eq:niceNiceCorrectEquation} allows us to use any package that implements inference for survival analysis since for each transition $i \to j$ we can maximize, \[ {\cal L}_{ij} = \prod_{h=1}^n {\cal L}_{ij}^{(h)} \] separately if each hazard intensity transition function \eqref{Eq:covariate-approachII} is assumed to have its own set of parameters $\tilde{\theta}_{ij}$ and $\tilde{\beta}_{ij}$. For this we can use different R packages including \texttt{flexsurv} (\cite{jackson2016flexsurv}), \texttt{survival} (\cite{survival-package}), and \texttt{eha} (\cite{ehapack}). In the examples here, we mainly use \texttt{flexsurv} which offers an easy way to run different parametric forms for $\tilde{\alpha}_{ij}(\cdot)$ including exponential, Weibull, gamma, and generalized gamma (see \cite{Prent1975}) among many other forms. It also supports covariates with standard inference for the covariate coefficients $\tilde{\beta}_{ij}$. We note that the purpose of this section is not to be an extensive survey of all of the R packages that can be used for inference in multi-state models. For a comprehensive software survey, see the survival task view from R (\cite{survivaltaskview}). Our focus here is to illustrate how the aforementioned packages can be used to easily carry out inference, while we also illustrate a few key points. \subsection{Progressive Three-State Model for the Stanford Heart Transplant data} As an illustrative example, we revisit the analysis of the Stanford Heart Transplant data, freely available through the \texttt{survival} package. A full description of the data can be found in \cite{Crow77}. The dataset presents the survival of patients on the waiting list for the Stanford heart transplant program. We analyze the data similarly to \cite{meira2011p3state} which use their R package \texttt{p3state} and propose an illness-death model similar to Figure~\ref{Fig:IllD}. Their states represent ``alive without transplant'', ``alive with transplant'', and ``dead''. We consider the same dataset, where patients' records from October 1967 (start of the program) until April 1974 includes the information of $103$ patients where $69$ received heart transplants, and $75$ died. Three fixed covariates for each patient are available. These include the age at acceptance (\texttt{age}), the year of acceptance (\texttt{year}), and previous surgery (\texttt{surgery}: coded as \texttt{1} = yes; \texttt{0} = no). We first use the data without taking into account any covariate effects to show that an exponential distribution on the baseline hazard rate of the sojourn time, $\alpha_{ij}(\cdot)$ does not produce constant intensity transition functions, $\tilde{\alpha}_{ij}(\cdot)$. This point was shown theoretically in Example~2, of Section~\ref{sec:examples} and we now illustrate it using data and the { \texttt{SemiMarkov}} package. Using the package we obtain both $\alpha_{ij}(\cdot)$ and $\tilde{\alpha}_{ij}(\cdot)$ for $(i,j) = (1,2)$ and $(i,j) = (1,3)$. The results are in Figure \ref{Fig:hazardAppli1} where we see that while $\alpha_{ij}(\cdot)$ are constant, $\tilde{\alpha}_{ij}(\cdot)$ are clearly not constant across time. These curves in fact follow a form like \eqref{eq:nonConstantTildeAlphaSurrr}. \begin{figure}[h!] \center \includegraphics[scale=0.3]{images/hazard_12_appli1.pdf} \includegraphics[scale=0.3]{images/hazard_13_appli1.pdf} \caption{ \small Baseline hazard rate of the sojourn times (Approach-I: $\alpha_{ij}(\cdot)$) and baseline hazard rate of the semi-Markov process (Approach-II: $\tilde{\alpha}_{ij}(\cdot)$) for transition $1\to 2$ (top plot) and $1\to 3$ (bottom plot) } \label{Fig:hazardAppli1} \end{figure} We now continue to analyze the data fully with Approach~I using the { \texttt{SemiMarkov}} package where we compare different parametric forms and covariates in the model. Table~1 presents the inference results of $6$ different models investigated depending on the distribution and covariates chosen for each transition. For each model we present the $\hat{\beta}_{ij}$ estimates and their estimated standard error. We also point out that the { \texttt{SemiMarkov}} package yields $p$-values for the associated Wald tests. We also present the estimates of the transition probabilities of the embedded chain, $\hat{p}_{ij}$. It is evident that these are outputs from likelihood estimation as they don't fully agree across models (they are not proportion estimates). For the final two models, {\em Weibull + Select} and {\em Weibull/Exp + Select} are based on model selection of the significant covariates with more details in the vignette, see \cite{Liq_github}. Observe that the final model, {\em Weibull/Exp + Select}, incorporates two different distributions. \begin{figure}[h!] \center \includegraphics[scale=0.7]{images/Table1.pdf} \end{figure} For choosing between the different proposed models, we use the \textit{Expected Kullbak-Leibler} (EKL) risk as in \cite{liquet2012investigating}. This is done via the \textit{Akaike Information Criterion} (AIC) which is an estimate of the EKL risk in a parametric framework using maximum likelihood method, see \cite{liquet2003bootstrap,commenges2008estimating}. For each of the $6$ models described above, we obtain the AIC using output from { \texttt{SemiMarkov}} and present it in the first part of Table~2. The best model according to the AIC is given by the {\em Exponentiated Weibull} model. However, due to convergence issues during the optimization (see the vignette \cite{Liq_github}), we select the second best result given by the {\em Weibull/Exp + Select} model as the most appropriate model for this dataset according to AIC using Approach~I. \begin{figure}[h!] \center \includegraphics[scale=0.7]{images/Table2.pdf} \end{figure} Moving onto inference using Approach~II, we investigate and estimate different models by specifying different proportional intensity transition models as defined in equation \eqref{Eq:covariate-approachII}. We use \texttt{flexsurv} to estimate $\tilde{\alpha}_{ij}(\cdot)$ for several models which we present in the second part of Table~2. The models {\em Exponential}, {\em Weibull}, {\em Gamma}, and {\em Generalized Gamma} are all estimated with all three covariates in the model. The additional two models, {\em Weibull+Select}, and {\em Generalized Gamma + Select}, have a reduced set of covariates with a procedure consistent with that used for Approach~I above. More details are in the vignette (see \cite{Liq_github}). The AIC based performance of each of these models is presented in the second part of Table~2. The best model according to the AIC is {\em Generalized Gamma + select}. In this model only the \texttt{age} covariate {is used} for transition $1 \to 2$, only the \texttt{year} covariate is used for transition $1\to 3$, and both the \texttt{surgery} and \texttt{age} covariates are used for transition $2 \to 3$. % For this dataset, the best model based on Approach~I presents a better AIC value ($1639.73$) in comparison to the best model based on Approach~II ($1701.03$). As discussed in Section~\ref{sec:thePlaceToBe} the regression coefficients of Approach~I and those of Approach~II do not have the same interpretation. Indeed for the hazard rate of the sojourn time, the regression coefficients can be interpreted in terms of relative risk on the waiting time (i.e.\, given an $i \to j$ transition). {For example the positive coefficient for 'surgery' for the $1 \to 3$ transition, as appearing in Table~1, can be interpreted as an indication that death without getting a heart transplant is less favorable for those that had previous surgery}. While the hazard rate of the SMP based on transition intensity functions can be interpreted as the subject's risk of passing from state $i$ to state $j$. {Interpretation of the regression coefficients using both Approach~I and Approach~II is further discussed in the second example below.} Since a key object of a Semi-Markov process is the transition intensity function, generally called the hazard rate of the SMP, it is also useful to visualize estimates of these functions based on both Approach~I and Approach~II. Further insight may be gained by plotting these against non-parametric estimators. For this, we used the Breslow estimator \cite{breslow1972discussion}, which yields an estimate for the baseline cumulative risk function of a cox-regression type model of each transition. Figure \ref{Fig:cumul} plots the cumulative baseline (all covariates are set to $0$) estimated transition intensity functions, estimated via Approach~I and Approach~II, against the Breslow estimator. These cumulative functions are based on the parameter estimates for the best model of Approach~I ({\em Weibull/Exp + Select}) vs. the best model of Approach~II ({\em Generalized Gamma + Select}). In this case, the plots in Figure \ref{Fig:cumul} hint at a better fit (closer to the non-parametric estimation) of the SMP using Approach~I in accordance with the results of the AIC values discussed above. \begin{figure}[h] \center \includegraphics[scale=0.25]{images/cumul_12.pdf} \includegraphics[scale=0.25]{images/cumul_13.pdf} \includegraphics[scale=0.25]{images/cumul_23.pdf} \caption{\small Cumulative of the baseline hazard rate of the SMP (intensity transition function) estimated from best AIC model of Approach-I and Approach-II. A semi-parametric estimation is presented as benchmark} \label{Fig:cumul} \end{figure} \subsection{Reversible Semi-Markov Model for the Asthma Control Data} \begin{figure} \center \includegraphics[scale=0.6]{images/IllnessDeathModel_reversible.pdf} \caption{{{\small The Reversible three-state Model. }}}\label{Fig:rev3} \end{figure} We revisit the analysis of the asthma control data which has been used to illustrate the { \texttt{SemiMarkov}} R package in \cite{listwon2015semimarkov}. {See also the related papers using the same data,\cite{saint2006overweight} and \cite{saint2003analysis}.} The data consists of the follow-up of severe asthmatic patients consulting at varied times according to their perceived needs. At each visit, several covariates were recorded and asthma was evaluated. The available data (\texttt{asthma}) from the \texttt{SemiMarkov} package presents a random selection of the $371$ patients with at least two visits. In this illustration, we only use the BMI (Body Mass Index) covariate coded: \texttt{1} if BMI $\geq 25$ and \texttt{0} otherwise. Similarly to the analysis in \cite{listwon2015semimarkov}, we use a reversible three-state model as presented in Figure~\ref{Fig:rev3}. This investigates the evolution of asthma based on, ``optimal control'' (State 1), ``sub-optimal control'' (State 2) and ``unacceptable control'' (State 3). More details about concepts of control scores can be found in \cite{saint2003analysis}. Observe that in this model, none of the states are absorbing and hence the model is said to be {\em reversible}. {We note that this data is based on scheduled visits every three months or according to patients' perceived needs, \cite{saint2006overweight}, and is thus potentially interval censored since the exact times of state transitions are approximated to be at visit times. This aspect of the analysis was not the focus of \cite{listwon2015semimarkov} and the related papers. While dealing with such interval censoring is important we do not focus on it here further and refer the reader to \cite{commenges2002inference} and \cite{van2016multi}.} For illustration purposes, we concentrate on a Weibull model as proposed in \cite{listwon2015semimarkov}. We perform a first full parametric proportional Weibull model for the sojourn times (Approach~I) with the BMI covariate for each transition. This yields significant results of BMI covariate for the transitions $1 \to 3$ and $3 \to 1$. Then, we decide to run a sparse model including BMI only for these transitions to facilitate the convergence of the model which can be difficult for a model with too many parameters as reported in \cite{listwon2015semimarkov}. For this new model, BMI regression coefficients remain significant for transitions $1 \to 3$ and $3 \to 1$ with $\widehat{\beta}_{13}=-0.88$ and $\widehat{\beta}_{31}=-0.448$, and respective $p$-values $0.012$, and $0.023$. The fact that hazard ratio of the sojourn time associated with these covariates is less than unity (estimated coefficients are negative), indicates that BMI $\geq 25$ generally lengthens the duration of the sojourn time in state~1 when making a $1 \to 3$ transition and generally lengthens the duration of the sojourn time in state~3 when making a $3 \to 1$ transition. This can also be interpreted as a decrease of the risk of leaving ``optimal control'' state to ``unacceptable control'' as well as a decrease of the risk of leaving ``unacceptable control'' state to ``optimal control''. However, the magnitude of the estimated coefficients cannot be used to evaluate the change in the hazard ratio on the risk (recall equations \eqref{Eq:covariate-sojourn} and \eqref{Eq:covariate-approachII} and the differences between $\beta_{ij}$ and $\tilde{\beta}_{ij}$). We may also visualize the effect of BMI covariate on the associated risks by plotting the hazard rate of the semi-Markov model (intensity transition functions), deduced from the sojourn times. See Figure~\ref{Fig:illustration2} where we also plot estimated transition intensity functions using Approach~II estimation, which we describe now. \begin{figure}[h!] \center \includegraphics[scale=0.22]{images/hazard_13.pdf} \includegraphics[scale=0.22]{images/hazard_12.pdf} \includegraphics[scale=0.22]{images/hazard_32.pdf} \includegraphics[scale=0.22]{images/hazard_31.pdf} \includegraphics[scale=0.22]{images/hazard_21.pdf} \includegraphics[scale=0.22]{images/hazard_23.pdf} \caption{ \small Hazard rate of the semi-Markov process for each transition from the sojourn time and intensity transition approaches.} \label{Fig:illustration2} \end{figure} Approach~II presented in this paper offer a direct way to model the intensity transition functions and has the advantage of a split likelihood which facilitates an efficient optimization procedure. In the vignette available in \cite{Liq_github}, we present the results of the full Weibull proportional semi-Markov model using this Approach. For illustration, we do this in two ways: (i) Optimizing the full likelihood. (ii) Splitting the likelihood for each transition and optimizing individually. As expected, both ways yield the same likelihood estimates. This highlight the advantage of the intensity transition based approach for overcoming potential computational issues in the optimization. Moreover, in some applications, some transitions of interest could then be further explored with any sophisticated survival model of choice as the estimation for each transition is performed separately. See for example \cite{therneau2000cox,royston2002flexible,liquet2012investigating,jackson2016flexsurv}. We augment the plots in Figure \ref{Fig:illustration2} with the estimated transition intensity functions using Approach~II. Note that similarly to Approach~I, the BMI effects are in the same direction. However, the interpretation of the regression coefficients is different. For the intensity transition based estimation (Approach~II), the BMI regression coefficient estimates are $\hat{\tilde{\beta}}_{13} = -0.5$ and $\hat{\tilde{\beta}}_{31} = -0.67$. Here, in contrast to the Approach~I estimates, the exact magnitude of the coefficients may be interpreted as the change in the hazard ratios associated with BMI $\geq 25$. \section{Concluding Remarks} \label{sec:conclusion} We have surveyed the two main approaches for modeling and inference using semi-Markov processes in a parametric setting. These are Approach~I based on sojourn time distributions and the embedded Markov chain, and Approach~II based on transition intensity functions. Each approach has its advantages and drawbacks when carrying out inference and analysis and these were described in the paper. We further summarized the formulation of these two approaches and showed relations between them, where we focused on inference for each of the approaches. In general, the intensity transition based approach (Approach~II) allows the likelihood to be split when each transition has its own set of parameters. Such separation into two-state models facilitates more efficient optimization as well as usage of additional modeling tools. The large scale impact of such separation on bigger datasets and/or simulated data as part of a simulation study remains to be carried out in future work. However, even putting the computational aspects aside, there is great value in such separation as it allows to use many survival analysis R packages directly within the context of semi-Markov processes. Such packages include \texttt{flexsurv} \cite{jackson2016flexsurv} which allows to fit various shapes of transition intensity functions including the Royston-Parmar spline model \cite{royston2002flexible}. Further, in a semi-parametric framework the \texttt{mstate} package \cite{de2011mstate} is popular for running multi-state models including the SMP. By exploiting the separation of the likelihood, \texttt{mstate} provides the estimation of covariate effects using Cox regression models. In addition, non-linear effects of the covariates could be investigated through smooth functions using the \texttt{mgcv} package which enables to run GAM models with survival data, see \cite{Rwood}. Further, with Approach~II, we can easily handle random effects using the \texttt{frailtypack} package \cite{frailtyypack}, as has been exploited by \cite{liquet2012investigating}. Further, in presence of high dimensional data, elastic-net penalty \cite{coxnet} can be used via the package \texttt{glmnet} to fit Cox regression models. Such benefits of using the intensity transition based approach have previously been reported and exploited for general Markov multi-state models as in \cite{hougaard1999multi,andersen2002multi} and \cite{meira2009multi}. Our purpose here was to survey these benefits and compare to Approach~I as is popularly used with the { \texttt{SemiMarkov}} package providing a flexible tool for inference of semi-Markov models based on sojourn time hazard rates in a parametric framework \cite{listwon2015semimarkov}. {The focus in this paper was purely on time-homogenous SMP in which the absolute time or date is assumed not to affect the probabilistic behavior. In certain situations one should consider time-inhomogeneous models allowing the absolute calendar time to play a role in the probabilistic model and the inference. Such situations can occur if seasonal (periodic) phenomena are present, or in long term longitudinal studies where the nature of the cohort is assumed to vary during the study. In a future study, it may be of interest to contrast Approach~I and Approach~II in a time-inhomogeneous setting.} Of further interest, we highlight the fact that PH (Phase Type) distributions may fit naturally in an SMP framework. Such approaches have been previously proposed in \cite{latouche1982phase}, \cite{malhotra1993selecting}, \cite{titman2010semi} and \cite{aalen1995phase}. Interestingly, as PH distributions provide a dense semi-parameteric approximation of any distribution of a non-negative random variable, it may be of interest to approximate semi-Markov processes with continuous time Markov chains constructed via PH distributions, where there are potentially more than $\ell$ states in the approximating Markov chain. To the best of our knowledge, such a semi-parametric inference setup has still not been explored. Such a setup may work well with the EM algorithm for parameter estimation of this type of PH distributions, see \cite{asmussen1996fitting}. We leave this for future work. \section*{Acknowledgements} AA and BL are supported by the Australian Research Council (ARC) Centre of Excellence for Mathematical and Statistical Frontiers (ACEMS) under grant number CE140100049. YN is supported by Australian Research Council (ARC) under grant number DP180101602. \vspace{-0.28cm}
{'timestamp': '2021-01-01T02:05:40', 'yymm': '2005', 'arxiv_id': '2005.14462', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14462'}
arxiv
\section{Introduction} \IEEEPARstart{T}{he} rapid development of the worldwide mobile communication technologies has been witnessed in recent years. After the 4th generation (4G) mobile communications became universal around the world, the initial 5th generation (5G) standard was completed in 2018 and the 5G commercial networks were already employed in part in the first quarter of 2020. For supporting huge mobile data traffic and high-speed communications required by a growing number of {\color{black}the} mobile devices accessed to the wireless networks, a variety of innovative techniques including millimeter wave (mmWave), ultra-dense network (UDN) and massive multiple-input multiple-output (MIMO) are implemented in 5G wireless transmission systems \cite{M.Agiwal2016(CST)}. These techniques exhibit great advantages in helping the communication systems improve spectral efficiency (SE) \cite{W.Yan2019(WCL)}, but {\color{black}face} challenging problems such as: 1) the mmWave is susceptible to blockage and suffers from severe power attenuation during the long-distance propagation in the atmosphere \cite{X.Lin2015(WCL)}, so that the wireless communication system will bear poor reliability when the received signals are substantially weak; 2) the UDN is composed of numerous intensively distributed base stations (BS) \cite{W.Sun2018(TWC)} while the massive MIMO requests the signal transceivers to be equipped with large-scale antenna arrays \cite{S.Hu2018(TSP)}, which {\color{black}lead} to high hardware cost (HWC). One mature technological solution to these problems is utilizing relays to establish a multi-hop transmission mode. Conventional wireless cooperative communication systems mostly employ relays \cite{S.Cheng2018(TVT), P.K.Sharma2016(CL), X.Xia2015(TSP), A.K.Mishra2018(TVT)} to process on the signals received halfway and retransmit the signals to the destination terminals actively through an uncontrollable propagation environment. Relays are validated to be effective on improving system reliability \cite{P.K.Sharma2016(CL)}, but are still active retransmitting facilities that require high energy consumption (EC) and HWC. Recently, another state of the art approach, which is named Intelligent Reflecting Surface (IRS) \cite{O.Ozdogan2019(WCL), Q.Wu2019(ICASSP)}, Large Intelligent Surface (LIS) \cite{W.Yan2019(WCL)} or Large Intelligent Metasurface (LIM) \cite{Z.He2020(WCL)}, has attracted {\color{black}considerable attention} from wireless communication researchers. An IRS is a planar array composed of a large number of low-cost passive reconfigurable reflecting elements, each of which induces an adjustable phase shift on the coming signal wave and reflects the signal to the destination terminal \cite{Q.Wu2019(TWC), C.Huang2019(JSAC), C.Huang2020(WCM), Liuyiming(arXiv)}. It is {\color{black}distinct} from the ordinary physical reflecting surfaces which simply reflect the signal waves without any parameter adjustment, and also different from the traditional relays which actively retransmit the received signals. As a passive reflecting apparatus, the IRS is envisioned as a promising hardware solution to EC and HWC in the future communication networks. There have already been studies that focused on the achievable rate (ACR) maximization, energy efficiency improvement, modulation scheme, secure communication realization, phase shift optimization, channel estimation and capacity {\color{black}analysis for} the IRS-aided wireless communication systems \cite{E.Basar2020(TCOM), M.Cui2019(WCL), H.Shen2019(CL), W.Yan2019(WCL), Q.Nadeem2020(arXiv), E.Bjornson2020(WCL), C.Huang2018(ICASSP), C.Huang2019(TWC)}. For instance, C. Huang, \textit{et al}. \cite{C.Huang2018(ICASSP), C.Huang2019(TWC)} employed the IRS to maximize the ACR \cite{C.Huang2018(ICASSP)} and the energy efficiency \cite{C.Huang2019(TWC)} of the wireless communication systems. E. Basar \cite{E.Basar2020(TCOM)} proposed an IRS-based index modulation scheme which enabled high data rate and low bit-error-rate (BER). M. Cui, \textit{et al}. \cite{M.Cui2019(WCL)} and H. Shen, \textit{et al}. \cite{H.Shen2019(CL)} developed IRS-aided secure wireless communication systems where the IRS was employed to maximize the rate gap (secrecy rate) between the desired transmission path from the source to the legitimate user and the undesired one from the source to the eavesdropper. W. Yan, \textit{et al}. \cite{W.Yan2019(WCL)} developed a passive beamforming and information transferring method and optimized the phase shifts with different state values to improve the average signal-to-noise ratio (SNR). Q. Nadeem, \textit{et al}. \cite{Q.Nadeem2020(arXiv)} outlined an IRS-aided multiple-user MIMO communication system and estimated the cascaded channel matrix within each time interval. E. Björnson, \textit{et al}. \cite{E.Bjornson2020(WCL)} analysed and compared the channel capacities of the IRS-supported, the decode-and-forward (DF) relay assisted and the single-input-single-output (SISO) communication systems, and derived the least required number of {\color{black}the} IRS reflecting elements which allowed {\color{black}the} IRS to outperform the DF relay and SISO. It is noted that the aforementioned works are carried out under the assumption of perfect hardware. However, in most practical situations, the inherent hardware impairment (HWI), e.g. phase noise, quantization error, amplifier non-linearity, \textit{et al}., which {\color{black}will} generally limit the system performance, cannot be neglected due to the non-ideality of the communication devices in the real world \cite{X.Zhang2015(TCOM), K.Xu2015(IEEE PACRIM), X.Xia2015(TSP)}. Although the effect of the HWI on the system performance can be mitigated by compensation algorithms \cite{T.Schenk2008(book)}, there will still exist residual HWI due to the imprecisely estimated time-variant hardware characteristic and the random noise. As a result, it is of great significance to probe into the system performance in the presence of HWI. Some researchers \cite{E.Bjornson2014(TIT), Q.Zhang2018(TWC), E.Bjornson2013(CL)} analysed the channel capacity of the massive MIMO communication systems with HWI, which they modelled as additive Gaussian distributed distortion noise. But to the best of our knowledge, there were only a few studies that analysed the IRS-aided communication systems with the HWI at the IRS \cite{S.Hu2018(GlobalCom), M.A.Badiu2020(WCL),D.Li2020(CL)}. Among these studies, the researchers performed some important initial works by modelling {\color{black}the HWI at the IRS} as an additive variable {\color{black}with respect to} the distance between {\color{black}the} reflecting point and the reflecting surface center \cite{S.Hu2018(GlobalCom)}, or as the uniformly distributed phase noise generated by the reflecting units \cite{M.A.Badiu2020(WCL),D.Li2020(CL)}. However, {\color{black} these works still left several research gaps to be filled. First,} the HWI of the transmitting devices and receiving terminals was not simultaneously taken into consideration, which would jointly influence the performance of the IRS-aided communication systems as well. {\color{black} Second, the phase shift optimization was not implemented when there existed HWI, which was indispensable for one to acquire the optimal IRS configuration with hardware imperfections. Third, the performance comparisons between the IRS and the conventional approaches, e.g. DF relay, which also contributed to the wireless data transmission enhancement, needed to be further explored in the presence of HWI.} Up to now, we have not found the {\color{black} related works that inquired into the above three aspects}. Therefore, in this article, we will provide the ACR {\color{black}analysis} and phase shift optimization on the IRS-aided communication system in consideration of {\color{black}the HWI at both the IRS and transceivers}, and present performance comparisons with the existing multiple-antenna DF relay assisted {\color{black}communication} system with the HWI at the DF relay and transceivers. Our contributions are summarized as follows. \begin{itemize} \item[•] By referring to \cite{M.A.Badiu2020(WCL)}, we model the {\color{black}HWI at the IRS} as a phase error matrix, in which the random phase errors generated by the IRS reflecting units are uniformly distributed. By referring to \cite{E.Bjornson2014(TIT),E.Bjornson2015(TWC)}, {\color{black}we model the transceiver HWI as the additive distortion noise as well as the phase drift and the thermal noise}. When the IRS phase shifts are adjusted to compensate for the phase shifts in the {\color{black}source-IRS} channel and the {\color{black}IRS-destination} channel, we mathematically derive the closed-form expression of the average ACR {\color{black}and the IRS utility} with respect to the number of the reflecting elements, denoted by $N$. From the theoretical and the numerical results, we confirm that {\color{black}the HWI decreases the average ACR and the IRS utility, and imposes more severe impact on the ACR performance as $N$ becomes larger.} \item[•] In order to optimize the IRS phase shifts and obtain the maximum average ACR with {\color{black}HWI}, we formulate the optimization problems and transform the non-convex problems into convex semidefinite programming (SDP) problems, then obtain the solution numerically by exploiting CVX toolbox with SDPT3 solver in the MATLAB simulation. {\color{black}Besides, we evaluate the impact of the channel estimation errors and the residual phase noises on the optimization performance, after which we conclude that both of the two unavoidable factors result in performance degradation to some extent.} \item[•] {\color{black}When the HWI appears at the IRS, the DF relay and the transceivers}, we compare the performance of the IRS with that of the {\color{black}multiple-antenna} DF relay in terms of the ACR {\color{black}and the utility}, and derive the condition where the IRS can always surpass the DF relay for all $N>0$. The results illustrate that if $N$ is large enough {\color{black}or the transmitting power is sufficiently high}, the IRS with $N$ passive reflecting elements is able to outperform the DF relay with the same number of antennas in the presence of HWI. \end{itemize} The rest of this article is organized as follows. In Section II, we introduce the IRS-aided {\color{black}wireless} communication system with HWI by showing the system model. In Section III, we analyse the ACR {\color{black}and the IRS utility} in the considered wireless communication system. In Section IV, we {\color{black}narrate the problem formulation and transformation} when optimizing the IRS phase shifts {\color{black}in the presence of HWI}. In Section V, we compare the performance of the IRS with that of the multiple-antenna DF relay in terms of the ACR {\color{black}and the utility}. In Section VI, we provide numerical results to verify the theoretical {\color{black}analysis and present discussions on the channel estimation errors and the residual phase noises}. In Section VII, we draw the overall conclusions. \textit{Notations}: Italics denote the variables or constants, while boldfaces denote the vectors or matrices. $\mathbf{A}^*$, $\mathbf{A}^T$, $\mathbf{A}^H$ and $ \mathbf{A}^{-1}$ symbolize the conjugate, transpose, conjugate-transpose and inverse of matrix $\mathbf{A}$, respectively. $tr(\mathbf{A})$ and $rank(\mathbf{A})$ stand for the trace and the rank of $\mathbf{A}$. $diag(\mathbf{a})$ represents an $n\times n$ sized diagonal matrix whose diagonal elements are $(a_1,a_2,\ldots,a_n)$ in vector $\mathbf{a}$. $||.||_2$ represents $\ell_2$ norm. {\color{black}$\odot$ symbolizes the Hadamard product.} $\mathbf{A}\in\mathbb{C}^{m\times n}$ or $\mathbf{A}\in\mathbb{R}^{m\times n}$ means that $\mathbf{A}$ is an $m\times n$ sized complex or real-number matrix. $\mathbf{A}\sim\mathcal{CN}(\mathbf{0},\mathbf{V})$ or $\mathbf{A}\sim\mathcal{N}(\mathbf{0},\mathbf{V})$ illustrates that $\mathbf{A}$ obeys complex normal or normal distribution with mean of zero and covariance matrix of $\mathbf{V}$. $\mathbf{A}\succeq\mathbf{0}$ means that $\mathbf{A}$ is positive semidefinite. $\mathbb{E}_\mathbf{x}[\mathbf{A}]$ denotes the expectation of $\mathbf{A}$ on the random variable $\mathbf{x}$ if $\mathbf{A}$ is a stochastic matrix in relation to $\mathbf{x}$. $\mathbf{I}_n$ and $\mathbf{\Gamma}_n$ symbolize $n\times n$ sized identity matrix and $n\times n$ sized matrix with all elements of 1, respectively. $\mathbf{1}$ stands for the unit row vector with all elements of 1. $\Delta=b^2-4ac$ represents the discriminant of the quadratic function $f\left(x\right)=ax^2+bx+c$. {\color{black}$g(x)=\mathcal{O}(f(x))$ signifies that $|g(x)/f(x)|$ is bounded when $x\rightarrow\infty$. $\lim_{x\to\infty}f(x)$ is represented by $f(x)|_{x\rightarrow\infty}$ throughout the whole paper.} \section{Communication System Model} In this article, the considered wireless communication system (Figure \ref{Fig-1}) includes a signal-emitting source (e.g. the base station, BS), an IRS with $N$ passive reflecting elements, an IRS controller and a signal-receiving destination (e.g. the user equipment, UE). The signal-emitting source, assumed to be equipped with single antenna, transmits the modulated signals with an average signal power of $\sqrt{P}$. The IRS induces reconfigurable phase shifts, which are adjusted by the IRS controller based on the channel state information (CSI), on the impinging signals, and reflects the coming signal waves to the destination. The signal-receiving destination, also equipped with single antenna, receives the directly arrived signals from the source and passively reflected signals from the IRS. \begin{figure}[!t] \includegraphics[width=4.0in]{Fig_1_R1.jpg} \centering \caption{The considered IRS-aided wireless communication system, including a single-antenna signal-emitting source, a single-antenna signal-receiving destination, an IRS with $N$ passive reflecting elements, and an IRS controller.} \label{Fig-1} \end{figure} Generally, due to the non-ideality of the hardware, the received signal is disturbed by the HWI which universally exists in the real-world communication devices. In this considered system, {\color{black} the HWI appears at both the IRS and the signal transceivers}. First, {\color{black} the HWI at the IRS} is modelled as a random diagonal phase error matrix, which involves $N$ random phase errors induced by {\color{black} the} intrinsic hardware {\color{black} imperfection} of the passive reflectors, or by {\color{black} the} imprecision of the channel estimation \cite{M.A.Badiu2020(WCL)}. It is expressed as {\color{black}\begin{equation} \mathbf{\Theta}_E=diag\left(e^{j\theta_{E1}},e^{j\theta_{E2}},\ldots,e^{j\theta_{EN}}\right) \end{equation} where} {\color{black}$j^2=-1$}; $\theta_{Ei}$, for $i=1,2,\ldots,N$, are random phase errors uniformly distributed on $\left[-\pi/2,\pi/2\right]$. {\color{black} Then, the HWIs at the signal transceivers primarily include the additive distortion noise, the multiplicative phase drift and the amplified thermal noise \cite{E.Bjornson2013(CL), E.Bjornson2014(TIT), E.Bjornson2015(TWC), Q.Zhang2018(TWC)}, which create a mismatch between the intended signal and the practically generated signal, or create a distortion on the received signal during the reception processing. The distortion noises, generated by the transmitter and the receiver due to the insufficiency of the accurate modelling, the time-variant characteristics, \textit{et al}., are modelled as $\eta_t(t)\sim\mathcal{CN}(0,\Upsilon_t)$ and $\eta_r(t)\sim\mathcal{CN}(0,V_r)$, respectively, where $\Upsilon_t$ and $V_r$ will be given in (\ref{Upsilon_t}) and (\ref{V_r}). The multiplicative phase drift caused by the local oscillator at the receiver is modelled as $\phi(t)=e^{j\psi(t)}$, with its expectation given by $\mathbb{E}[\phi(t)]=e^{-\frac{1}{2}\delta t}$ \cite{Q.Zhang2018(TWC)}, where $\delta$ denotes the oscillator quality, and $\psi(t)$ follows a Wiener process: \begin{equation} \psi(t)\sim\mathcal{N}(\psi(t-1),\delta) \end{equation} The amplified thermal noise, aroused by the mixers at the receiver and by the interference leakage from other frequency bands or wireless networks \cite{E.Bjornson2015(TWC)}, is modelled as $w'(t)\sim\mathcal{CN}(0,\sigma_{w'}^2)$, with $\sigma_{w'}^2$ being the thermal noise variance. } Therefore, referring to Eq. (2) in \cite{E.Bjornson2014(TIT)} and {\color{black} Eq. (3) in \cite{E.Bjornson2015(TWC)}}, the received signal disturbed by {\color{black} HWI} is modelled as {\color{black}\begin{equation}\label{eq2-12} y(t)=\phi(t)\left(\mathbf{h}_{IU}^T\mathbf{\Phi}\mathbf{\Theta}_E\mathbf{h}_{SI}+h_{SU}\right)\left[\sqrt Ps(t)+\eta_t(t)\right]+\eta_r(t)+w(t) \end{equation} where} $s(t)$ stands for the unit-power signal symbol at time $t$ with $\mathbb{E}\left[s(t)s^*(t)\right]=1$; $w(t)\sim\mathcal{CN}\left(0,\sigma_w^2\right)$ denotes the receiver noise, whose {\color{black} variance $\sigma_w^2$, according to \cite{E.Bjornson2015(TWC)}, satisfies $\sigma_w^2=F\sigma_{w'}^2$, with $F>1$ being the noise amplification factor}; $\mathbf{\Phi}=\alpha\times diag\left(e^{j\theta_1},e^{j\theta_2},\ldots,e^{j\theta_N}\right)$ represents the phase shifting matrix of the IRS, where $\alpha\in(0,1]$ is the fixed amplitude reflection coefficient and $\theta_i$, for $i=1,2,\ldots,N$, are the adjustable phase-shift variables of the IRS; $h_{SU}=\sqrt{\mu_{SU}}e^{j\varphi_{SU}}$ represents the channel coefficient from the source to the destination, where $\sqrt{\mu_{SU}}$ and $\varphi_{SU}$ are the power attenuation coefficient and the phase shift of $h_{SU}$; $\mathbf{h}_{IU}\in\mathbb{C}^{N\times 1}$ and $\mathbf{h}_{SI}\in\mathbb{C}^{N\times1}$ are the channel coefficients from the IRS to the destination and from the source to the IRS, respectively, which are expressed as{\color{black}\cite{E.Bjornson2020(WCL)}} \begin{equation} \mathbf{h}_{IU}=\sqrt{\mu_{IU}}\left(e^{j\varphi_{IU,1}},e^{j\varphi_{IU,2}},\ldots,e^{j\varphi_{IU,N}}\right)^T \end{equation} \begin{equation} \mathbf{h}_{SI}=\sqrt{\mu_{SI}}\left(e^{j\varphi_{SI,1}},e^{j\varphi_{SI,2}},\ldots,e^{j\varphi_{SI,N}}\right)^T \end{equation} where $\sqrt{\mu_{IU}}$ and $\sqrt{\mu_{SI}}$ are the power attenuation coefficients of $\mathbf{h}_{IU}$ and $\mathbf{h}_{SI}$; $\varphi_{IU,i}$ and $\varphi_{SI,i}$, for $i=1,2,\ldots,N$, are the phase shifts of $\mathbf{h}_{IU}$ and $\mathbf{h}_{SI}$. {\color{black} As the distortion noises are proportional to the signal power, we have \begin{equation}\label{Upsilon_t} \Upsilon_t=\kappa_tP \mathbb{E}\left[s(t)s^*(t)\right] \end{equation} \begin{equation}\label{V_r} V_r=\kappa_rP\left|\phi(t)\left(\mathbf{h}_{IU}^T\mathbf{\Phi}\mathbf{\Theta}_E\mathbf{h}_{SI}+h_{SU}\right)\right|^2 \mathbb{E}\left[s(t)s^*(t)\right] \end{equation} where} $\kappa_t$ and $\kappa_r$ represent the proportionality coefficients which describe the severities of the distortion noises at the transmitter and the receiver, respectively. For this communication system, we {\color{black} will} {\color{black} derive the approximate closed-form ACR expression and the IRS utility in relation to $N$ in the presence of HWI, and analyse the ACR and utility degradations caused by HWI in the next section}. \section{ACR Analysis with HWI} Based on the signal model in {\color{black} (\ref{eq2-12})}, we {\color{black} will} analyse the ACR {\color{black} and the IRS utility} of the considered IRS-aided communication system in the presence of {\color{black} HWI}. Here we assume that the phase information in the cascaded source-IRS-destination channel model \cite{Q.Nadeem2020(arXiv)} is already estimated before $\mathbf{\Phi}$ is adjusted, so that $\left(\varphi_{IU,i}+\varphi_{SI,i}\right)$, for $i=1,2,\ldots,N$, are known for the IRS phase shift controller. This can be realized via some existing channel estimation techniques in e.g. \cite{B.Zheng2020(WCL),Q.Nadeem2020(arXiv)}, which estimated the cascaded channel, {\color{black}and \cite{L.Wei2020(Arxiv),L.Wei2020(IEEE SAM)}, which designed robust and effective channel estimation frameworks based on the PARAllel FACtor (PARAFAC)}. In {\color{black} (\ref{eq2-12})}, $\mathbf{h}_{IU}^T\mathbf{\Phi}\mathbf{\Theta}_E\mathbf{h}_{SI}$ is maximized if each phase shift of the IRS is adjusted into $\theta_i=-\left(\varphi_{IU,i}+\varphi_{SI,i}\right)$, for $i=1,2,\ldots,N$, to compensate for the phase shifts in $\mathbf{h}_{IU}$ and $\mathbf{h}_{SI}$ \cite{E.Bjornson2020(WCL)}. As a result, when $\theta_i=-\left(\varphi_{IU,i}+\varphi_{SI,i}\right)$, the received signal affected by {\color{black} HWI} is expressed as {\color{black} \begin{equation}\label{eq2-7} y(t)=\phi(t)\left(\alpha\mathbf{g}_{IU}^T\mathbf{\Theta}_E\mathbf{g}_{SI}+h_{SU}\right)\left[\sqrt Ps(t)+\eta_t(t)\right]+\eta_r(t)+w(t) \end{equation} where} $\mathbf{g}_{IU}=\sqrt{\mu_{IU}}\mathbf{1}^T$ and $\mathbf{g}_{SI}=\sqrt{\mu_{SI}}\mathbf{1}^T$. {\color{black}Accordingly}, the ACR with {\color{black} HWI} is expressed as {\color{black} \begin{equation}\label{eq2-16} \begin{split} R_{HWI}\left(N\right)&=\log_2\left\{1+\frac{P\left|\phi(t)\left(\alpha\mathbf{g}_{IU}^T\mathbf{\Theta}_E\mathbf{g}_{SI}+h_{SU}\right)\right|^2}{P(\kappa_t+\kappa_r)\left|\phi(t)\left(\alpha\mathbf{g}_{IU}^T\mathbf{\Theta}_E\mathbf{g}_{SI}+h_{SU}\right)\right|^2+\sigma_w^2}\right\} \end{split} \end{equation}} Based on (\ref{eq2-16}), we obtain the following theorem. {\color{black} \begin{theorem} When $\theta_i=-\left(\varphi_{IU,i}+\varphi_{SI,i}\right)$ and $\theta_{Ei}$ is uniformly distributed on $\left[-\pi/2,\pi/2\right]$, the approximate average ACR with {\color{black} HWI} is expressed as \begin{equation}\label{eq2-17} \overline{R_{HWI}}\left(N\right)=\log_2\left\{1+\frac{\beta N^2+\lambda N+\mu_{SU}} {\left(\kappa_t+\kappa_r\right)\left(\beta N^2+\lambda N+\mu_{SU}\right)+\frac{\sigma_w^2}{P}}\right\} \end{equation} where \begin{equation}\label{eq-revision-1} \beta=\frac{4\alpha^2\mu_{IU}\mu_{SI}}{\pi^2} \end{equation} \begin{equation}\label{eq-revision-2} \lambda=\left(1-\frac{4}{\pi^2}\right)\alpha^2\mu_{IU}\mu_{SI}+\frac{4\alpha}{\pi}\mu_{IU}^{\frac{1}{2}}\mu_{SI}^{\frac{1}{2}}\mu_{SU}^{\frac{1}{2}}\cos{(\varphi_{SU})} \end{equation} The IRS utility with HWI, defined by $\gamma_{HWI}(N)=\frac{\partial\overline{R_{HWI}}\left(N\right)}{\partial N}$ according to the Definition 1 in \cite{S.Hu2018(GlobalCom)}, is expressed as \begin{equation}\label{Utility Expression} \begin{split} \gamma_{HWI}(N)=\frac{\sigma_w^2}{P}(2\beta N+\lambda)\left\{\left[(\kappa_t+\kappa_r)(\beta N^2+\lambda N+\mu_{SU})+\frac{\sigma_w^2}{P}\right]\times\right.\\ \left. \left[(\kappa_t+\kappa_r+1)(\beta N^2+\lambda N+\mu_{SU})+\frac{\sigma_w^2}{P}\right]\ln 2\right\}^{-1} \end{split} \end{equation} \end{theorem} \begin{proof} The proof is given in Appendix A. \end{proof}} {\color{black} Subsequently, for theoretically evaluating the impact that the HWI has on the ACR and the IRS utility, we further calculate the rate gap, defined by $\delta_R(N)=R(N)-\overline{R_{HWI}}\left(N\right)$, and the utility gap, defined by $\delta_{\gamma}(N)=\gamma(N)-\gamma_{HWI}(N)$ in the following \textbf{Lemma 1}, where $R(N)$ and $\gamma(N)$, denoting the ACR and the IRS utility without HWI, will be given in the proof.} \begin{lemma} When $\theta_i=-\left(\varphi_{IU,i}+\varphi_{SI,i}\right)$ and $\theta_{Ei}$ is uniformly distributed on $\left[-\pi/2,\pi/2\right]$, the rate gap {\color{black}$\delta_R\left(N\right)$} between the average ACR{\color{black}s} with and without HWI is expressed as {\color{black}\begin{equation}\label{eq2-18} \delta_R\left(N\right)\!=\!\log_2\left\{\frac{P\left(\kappa_t+\kappa_r\right)\chi+\sigma_w^2+P^2\chi\varpi\left(\frac{\kappa_t}{\sigma_w^2}+\frac{\kappa_r}{\sigma_w^2}\right)+P\varpi}{P(\kappa_t+\kappa_r+1)\chi+\sigma_w^2}\right\} \end{equation} where \begin{equation}\label{eq-revision-3} \varpi=\frac{\pi^2}{4}\beta N^2+\rho N+\mu_{SU} \end{equation} \begin{equation}\label{eq-revision-4} \chi=\beta N^2+\lambda N+\mu_{SU} \end{equation} with $\rho$ given by $\rho=2\alpha\mu_{IU}^{\frac{1}{2}}\mu_{SI}^{\frac{1}{2}}\mu_{SU}^{\frac{1}{2}}\cos{(\varphi_{SU})}$. The utility gap $\delta_{\gamma}(N)$ between the IRS utilities with and without HWI is expressed as \begin{equation}\label{Utility Degradation} \begin{split} \delta_\gamma(N)=& \left[P^3\chi^2(\kappa_t+\kappa_r+1)\left(\frac{\kappa_t}{\sigma_w^2}+\frac{\kappa_r}{\sigma_w^2}\right)\frac{\partial\varpi}{\partial N}+ P^2(\kappa_t+\kappa_r+1)\left(\frac{\partial\varpi}{\partial N}\chi-\frac{\partial\chi}{\partial N}\varpi\right)+\right.\\ &\left. P^2\left(\kappa_t+\kappa_r\right)\left(\frac{\partial\varpi}{\partial N}\chi+\frac{\partial\chi}{\partial N}\varpi\right)+ P\sigma_w^2\left(\frac{\partial\varpi}{\partial N}-\frac{\partial\chi}{\partial N}\right)\right]\times \left\{ \left[P(\kappa_t+\kappa_r)\chi+\sigma_w^2+\right.\right.\\ &\left.\left.P^2\varpi\chi\left(\frac{\kappa_t}{\sigma_w^2}+\frac{\kappa_r}{\sigma_w^2}\right)+P\varpi\right] \left[P(\kappa_t+\kappa_r+1)\chi+\sigma_w^2\right]\ln 2 \right\}^{-1} \end{split} \end{equation} where $\frac{\partial\varpi}{\partial N}=\frac{\pi^2}{2}\beta N+\rho$ and $\frac{\partial\chi}{\partial N}=2\beta N+\lambda$ are the partial derivatives of $\varpi$ and $\chi$, respectively.} \end{lemma} {\color{black} \begin{proof} According to \cite{E.Bjornson2020(WCL)}, $R\left(N\right)$ is expressed as \begin{equation}\label{eq2-11} R\left(N\right)=\log_2\left\{1+\frac{P\left[\alpha^2N^2\mu_{IU}\mu_{SI}+2\alpha N\sqrt{\mu_{IU}\mu_{SI}\mu_{SU}}\cos{\left(\varphi_{SU}\right)}+\mu_{SU}\right]}{\sigma_w^2}\right\} \end{equation} Then, the corresponding $\gamma(N)$, defined by $\gamma(N)=\frac{\partial R(N)}{\partial N}$, is given by \begin{equation}\label{Utility Expression 2} \begin{split} \gamma(N)&=\frac{\frac{P}{\sigma_w^2}\left[2\alpha^2\mu_{IU}\mu_{SI}N+2\alpha\sqrt{\mu_{IU}\mu_{SI}\mu_{SU}}\cos{\left(\varphi_{SU}\right)}\right]} {\left\{1+\frac{P}{\sigma_w^2}\left[\alpha^2 N^2\mu_{IU}\mu_{SI}+2\alpha N\sqrt{\mu_{IU}\mu_{SI}\mu_{SU}}\cos{\left(\varphi_{SU}\right)}+\mu_{SU}\right]\right\}\ln 2} \end{split} \end{equation} Thereupon, by calculating $\delta_R(N)=R(N)-\overline{R_{HWI}}\left(N\right)$ and $\delta_{\gamma}(N)=\gamma(N)-\gamma_{HWI}(N)=\frac{\partial R(N)}{\partial N}-\frac{\partial \overline{R_{HWI}}(N)}{\partial N}=\frac{\partial \delta_R(N)}{\partial N}$, we derive the above (\ref{eq2-18}) and (\ref{Utility Degradation}). \end{proof}} {\color{black}\textbf{Theorem 1} demonstrates that: 1) although the $\overline{R_{HWI}}\left(N\right)$ increases with $N$, the proportionality coefficient $\beta$ on $N^2$ in $\overline{R_{HWI}}\left(N\right)$ is smaller than $\alpha^2\mu_{IU}\mu_{SI}$ in $R(N)$, hinting that $\overline{R_{HWI}}\left(N\right)$ rises more slowly than $R(N)$. 2) When $N\rightarrow\infty$, the $\overline{R_{HWI}}\left(N\right)$ is limited by \begin{equation}\label{R_HWI Upper Bound} \left.\overline{R_{HWI}}\left(N\right)\right|_{N\rightarrow\infty}=\log_2\left(1+\frac{1}{\kappa_t+\kappa_r}\right) \end{equation} which signifies that even if $N$ becomes significantly large or tends to be infinite, the potential growth of $\overline{R_{HWI}}\left(N\right)$ will be primarily restricted by $\kappa_t$ and $\kappa_r$ of the HWI at the signal transceivers. On the contrary, $R(N)$ continuously ascends without bound as $N$ grows. 3) The $\gamma_{HWI}(N)$ is inversely proportional to $\mathcal{O}(N^3)$, which indicates that the IRS utility with HWI descends as $N$ grows, and is close to zero when $N\rightarrow\infty$. This implies that if $N$ is extremely large or nearly infinite, adding more passive reflecting elements will contribute to little ACR improvement when there exists HWI. \textbf{Lemma 1} illustrates that: 1) the rate gap $\delta_R(N)>0$ for $N>0$, which indicates that the ACR is degraded by HWI. 2) The $\delta_R(N)$ increases with $N$, because the numerator inside $\log_2(.)$ contains $\chi\varpi$ which is proportional to $\mathcal{O}(N^4)$, while the denominator inside $\log_2(.)$ merely involves $\chi$ which is proportional to $\mathcal{O}(N^2)$. This implies that as $N$ grows, the IRS-aided wireless communication system will suffer from more serious ACR degradation. 3) The utility gap $\delta_{\gamma}(N)>0$, because by expanding $\left(\frac{\partial\varpi}{\partial N}\chi-\frac{\partial\chi}{\partial N}\varpi\right)$ and $\left(\frac{\partial\varpi}{\partial N}-\frac{\partial\chi}{\partial N}\right)$ in (\ref{Utility Degradation}), we have \begin{equation} \begin{split} &\left(\frac{\partial\varpi}{\partial N}\chi-\frac{\partial\chi}{\partial N}\varpi\right)= \frac{4\alpha^2\mu_{IU}\mu_{SI}N^2}{\pi^2}\left[\left(\frac{\pi^2}{4}-1\right)\alpha^2\mu_{IU}\mu_{SI}+(\pi-2)\alpha\mu_{IU}^{\frac{1}{2}}\mu_{SI}^{\frac{1}{2}}\mu_{SU}^{\frac{1}{2}}\cos{(\varphi_{SU})} \right]+\\ &\left[\left(2-\frac{8}{\pi^2}\right)N+\frac{4}{\pi^2}-1\right]\alpha^2\mu_{IU}\mu_{SI}\mu_{SU}+ \left(2-\frac{4}{\pi}\right)\alpha\mu_{IU}^{\frac{1}{2}}\mu_{SI}^{\frac{1}{2}}\mu_{SU}^{\frac{3}{2}}\cos{(\varphi_{SU})}>0 \end{split} \end{equation} \begin{equation} \begin{split} \left(\frac{\partial\varpi}{\partial N}-\frac{\partial\chi}{\partial N}\right)=(2N-1)\left(1-\frac{4}{\pi^2}\right)\alpha^2\mu_{IU}\mu_{SI}+\left(2-\frac{4}{\pi}\right)\alpha\mu_{IU}^{\frac{1}{2}}\mu_{SI}^{\frac{1}{2}}\mu_{SU}^{\frac{1}{2}}\cos{(\varphi_{SU})}>0 \end{split} \end{equation} This reveals that the IRS utility will be also degraded by HWI to some extent.} It is notable that the results in \textbf{Theorem 1} and \textbf{Lemma 1} are derived on the basis of $\theta_i=-\left(\varphi_{IU,i}+\varphi_{SI,i}\right)$, which is configured to compensate for the phase shifts in $\mathbf{h}_{IU}$ and $\mathbf{h}_{SI}$ \cite{E.Bjornson2020(WCL)}. However, $\theta_i=-\left(\varphi_{IU,i}+\varphi_{SI,i}\right)$ might not be optimal in this considered wireless propagation environment, as it does not take the phase shift in $h_{SU}$ into account. Thus, in Section IV, we will optimize the IRS phase shifts and reconfigure the phase shifting matrix to obtain the maximum ACR in the presence of HWI. \section{Phase Shift Optimization} Instead of configuring $\theta_i=-\left(\varphi_{IU,i}+\varphi_{SI,i}\right)$ to evaluate the ACR, we {\color{black} will} formulate the optimization problem to optimize the IRS phase shifts with {\color{black} HWI} in this section. {\color{black}\subsection{Problem Formulation and Transformation}} Here, we retrospect {\color{black} (\ref{eq2-12})}, from which we obtain the ACR with {\color{black} HWI}: {\color{black} \begin{equation}\label{original ACR with HWI} \begin{split} R_{\mathbf{\Phi},HWI}\left(N\right)&=\log_2\left\{1+\frac{P\left|\phi(t)\left(\mathbf{h}_{IU}^T\mathbf{\Phi}\mathbf{\Theta}_E\mathbf{h}_{SI}+h_{SU}\right)\right|^2}{P(\kappa_t+\kappa_r)\left|\phi(t)\left(\mathbf{h}_{IU}^T\mathbf{\Phi}\mathbf{\Theta}_E\mathbf{h}_{SI}+h_{SU}\right)\right|^2+\sigma_w^2}\right\} \end{split} \end{equation} Therefore, aiming at maximizing the received SNR, we can formulate the phase shift optimization problem as \begin{subequations}\label{original problem} \begin{align} (\mathrm{P1}):\ \mathop{\max}\limits_{\mathbf{\Phi}}&\frac{P\left|\phi(t)\left(\mathbf{h}_{IU}^T\mathbf{\Phi}\mathbf{\Theta}_E\mathbf{h}_{SI}+h_{SU}\right)\right|^2}{P(\kappa_t+\kappa_r)\left|\phi(t)\left(\mathbf{h}_{IU}^T\mathbf{\Phi}\mathbf{\Theta}_E\mathbf{h}_{SI}+h_{SU}\right)\right|^2+\sigma_w^2} \\s.t.\ &\left|\left[\mathbf{\Phi}\right]_{(n,n)}\right|=\alpha,\ n=1,2\ldots N \end{align} \end{subequations} However, the objective function (OBF) in (\ref{original problem}a) is non-concave with respect to $\mathbf{\Phi}$, and the constraint in (\ref{original problem}b) is non-convex. Thus, inspired by \cite{M.Cui2019(WCL)}, we will convert (P1) into another solvable form.} Let $\mathbf{D}_{IU}$ denote a diagonal matrix expressed as $\mathbf{D}_{IU}=diag\left(\mathbf{h}_{IU}\right)$, and $\bm{\theta}$ denote a column vector expressed as $\bm{\theta}=\alpha\left(e^{j\theta_1},e^{j\theta_2},\ldots,e^{j\theta_N}\right)^T$. Then, we have $\bm{\theta}^T\mathbf{D}_{IU}=\mathbf{h}_{IU}^T\mathbf{\Phi}$. By replacing $\mathbf{h}_{IU}^T\mathbf{\Phi}$ with $\bm{\theta}^T\mathbf{D}_{IU}$, we expand (\ref{original ACR with HWI}) into {\color{black} \begin{equation}\label{eq2-22} R_{\bm{\theta},HWI}\left(N\right)=\log_2{\left\{1+\frac{P\left(Z+||h_{SU}||_2^2\right)}{P(\kappa_t+\kappa_r)\left(Z+||h_{SU}||_2^2\right)+\sigma_w^2}\right\}} \end{equation} where} $Z=\mathbf{h}_{SI}^H\mathbf{\Theta}_E^H\mathbf{D}_{IU}^H\bm{\theta}^*\bm{\theta}^T\mathbf{D}_{IU}\mathbf{\Theta}_E\mathbf{h}_{SI}+\mathbf{h}_{SI}^H\mathbf{\Theta}_E^H\mathbf{D}_{IU}^H\bm{\theta}^*h_{SU}+h_{SU}^*\bm{\theta}^T\mathbf{D}_{IU}\mathbf{\Theta}_E\mathbf{h}_{SI}$. Let $\mathbf{a}$ be defined by $\mathbf{a}=\left(\bm{\theta}^T,1\right)^H$. We can rewrite $Z$ as $Z=\mathbf{a}^H\mathbf{\Xi}\mathbf{a}$, where \begin{equation}\label{eq2-24} \mathbf{\Xi}=\left(\begin{matrix}\mathbf{D}_{IU}\mathbf{\Theta}_E\mathbf{h}_{SI}\mathbf{h}_{SI}^H\mathbf{\Theta}_E^H\mathbf{D}_{IU}^H&h_{SU}^*\mathbf{D}_{IU}\mathbf{\Theta}_E\mathbf{h}_{SI}\\\mathbf{h}_{SI}^H\mathbf{\Theta}_E^H\mathbf{D}_{IU}^Hh_{SU}&0\\\end{matrix}\right) \end{equation} Therefore, {\color{black} $R_{\bm{\theta},HWI}\left(N\right)$} can be simplified into {\color{black}\begin{equation}\label{eq2-25} \begin{split} R_{\bm{\theta},HWI}\left(N\right)=&\log_2{\left\{1+\frac{P\left(\mathbf{a}^H\mathbf{\Xi}\mathbf{a}+||h_{SU}||_2^2\right)}{P(\kappa_t+\kappa_r)\left(\mathbf{a}^H\mathbf{\Xi}\mathbf{a}+||h_{SU}||_2^2\right)+\sigma_w^2}\right\}} \\ =&\log_2{\left\{1+\frac{P\left[tr(\mathbf{\Xi}\mathbf{X})+||h_{SU}||_2^2\right]}{P(\kappa_t+\kappa_r)\left[tr(\mathbf{\Xi}\mathbf{X})+||h_{SU}||_2^2\right]+\sigma_w^2}\right\}} \end{split} \end{equation} where } \begin{equation}\label{eq2-26} \mathbf{X}=\mathbf{a}\mathbf{a}^H=\left(\begin{matrix}\bm{\theta}^*\bm{\theta}^T&\bm{\theta}^*\\\bm{\theta}^T&1\\\end{matrix}\right)\in\mathbb{C}^{\left(N+1\right)\times\left(N+1\right)} \end{equation} Then, the optimization problem is formulated as {\color{black}\begin{subequations}\label{converted problem 1} \begin{align} (\mathrm{P2}):\ \mathop{\max}\limits_{\bm{\theta}}&\frac{P\left[tr(\mathbf{\Xi}\mathbf{X})+||h_{SU}||_2^2\right]}{P(\kappa_t+\kappa_r)\left[tr(\mathbf{\Xi}\mathbf{X})+||h_{SU}||_2^2\right]+\sigma_w^2} \\s.t.\ &\left|\left[\bm{\theta}\right]_{n}\right|=\alpha,\ n=1,2\ldots N \end{align} \end{subequations} which is still non-convex due to the complicated non-concave OBF in (\ref{converted problem 1}a) and the non-convex module constraint in (\ref{converted problem 1}b). Here, from $\bm{\theta}^*\bm{\theta}^T$ in (\ref{eq2-26}), it can be realized that the diagonal entries in $\mathbf{X}$ embody the modules of the elements in $\bm{\theta}$. Thus, we define a simple matrix $\mathbf{E}_n$, whose $(i,j)$-th element is given by \begin{equation}\label{eq2-28} \left[\mathbf{E}_n\right]_{(i,j)}=\left\{\begin{matrix}1,\ \ \ \ \ i=j=n\\0,\ \ \ \ otherwise\\\end{matrix}\right. \end{equation} As a result, the optimization problem is converted into \begin{subequations}\label{converted problem 2} \begin{align} (\mathrm{P3}):\ \mathop{\max}\limits_{\mathbf{X}\succeq\mathbf{0}}&\frac{P\left[tr(\mathbf{\Xi}\mathbf{X})+||h_{SU}||_2^2\right]}{P(\kappa_t+\kappa_r)\left[tr(\mathbf{\Xi}\mathbf{X})+||h_{SU}||_2^2\right]+\sigma_w^2} \\s.t.\ &tr\left(\mathbf{E}_n\mathbf{X}\right)=\alpha^2,\ n=1,2\ldots N \\&tr\left(\mathbf{E}_{N+1}\mathbf{X}\right)=1 \\&rank(\mathbf{X})=1 \end{align} \end{subequations} where the constraint in (\ref{converted problem 2}b) is transformed from the module constraint of $\left|\left[\bm{\theta}\right]_n\right|^2=\left[\bm{\theta}^*\bm{\theta}^T\right]_{(n,n)}=\mathbf{a}^H\mathbf{E}_n\mathbf{a}=tr\left(\mathbf{E}_n\mathbf{X}\right)=\alpha^2$, for $n=1,2\ldots N$; the constraint in (\ref{converted problem 2}c) is transformed from $\left[\mathbf{X}\right]_{(N+1,N+1)}=1$; the constraint in (\ref{converted problem 2}d) is responsible for strictly guaranteeing that 1) the resolved $\mathbf{X}$ can be decomposed into $\mathbf{X}=\mathbf{a}\mathbf{a}^H$, and 2) the solution of the phase shift in $\bm{\theta}$ in the resolved $\mathbf{X}$ is equivalent to the solution of the phase shift in $\mathbf{\Phi}$ in (P1). Nevertheless, (P3) is still non-convex and is difficult to solve. Therefore, the problem transformation should be further performed. Thanks to the Charnes-Cooper transformation \cite{L.Liu2014(TSP), Charnes1962}}, let $\mathbf{Y}$ and $\mu$ be defined by $\mathbf{Y}=\mu\mathbf{X}$ and $\mu=\frac{1}{tr(\mathbf{\Xi}\mathbf{X})+||h_{SU}||_2^2+\frac{\sigma_w^2}{P\left(\kappa_t+\kappa_r\right)}}$. Then, the OBF in (\ref{converted problem 2}a) is expressed as $\frac{1}{\left(\kappa_t+\kappa_r\right)}\times\left[tr(\mathbf{\Xi}\mathbf{Y})+\mu||h_{SU}||_2^2\right]$. Therefore, (P3) is transformed into \begin{subequations}\label{converted problem 3} \begin{align} (\mathrm{P4}):\ \mathop{\max}\limits_{\mathbf{Y}\succeq\mathbf{0},\mu\geq 0}&\frac{1}{\left(\kappa_t+\kappa_r\right)}\times\left[tr(\mathbf{\Xi}\mathbf{Y})+\mu||h_{SU}||_2^2\right] \\s.t.\ &tr\left(\mathbf{E}_n\mathbf{Y}\right)=\mu\alpha^2,\ n=1,2\ldots N \\&tr\left(\mathbf{E}_{N+1}\mathbf{Y}\right)=\mu \\&tr\left(\mathbf{\Xi Y}\right)+\mu\left[||h_{SU}||_2^2+\frac{\sigma_w^2}{P\left(\kappa_t+\kappa_r\right)}\right]=1 \\&rank(\mathbf{Y})=1 \end{align} \end{subequations} {\color{black} Although (P4) is still non-convex due to the non-convex (\ref{converted problem 3}e), it can be relaxed if the constraint of $rank(\mathbf{Y})=1$ is omitted. Hence, the relaxed problem is formulated as} \begin{subequations}\label{eq2-43} \begin{align} (\mathrm{P5}):\ \mathop{\max}\limits_{\mathbf{Y}\succeq\mathbf{0},\mu\geq 0}&\frac{1}{\left(\kappa_t+\kappa_r\right)}\times\left[tr(\mathbf{\Xi}\mathbf{Y})+\mu||h_{SU}||_2^2\right] \\s.t.\ &tr\left(\mathbf{E}_n\mathbf{Y}\right)=\mu\alpha^2,\ n=1,2\ldots N \\&tr\left(\mathbf{E}_{N+1}\mathbf{Y}\right)=\mu \\&tr\left(\mathbf{\Xi Y}\right)+\mu\left[||h_{SU}||_2^2+\frac{\sigma_w^2}{P\left(\kappa_t+\kappa_r\right)}\right]=1 \end{align} \end{subequations} which is currently a SDP problem and can be solved by existing techniques \cite{A.Nemirovski2008(ActaNumerica)}. {\color{black} However, the matrix $\mathbf{\Xi}$ involves the stochastic phase errors, which are generally unknown due to their randomness and prevent us from predetermining $\mathbf{\Xi}$ and obtaining the solution in reality. In view of this issue, we will further calculate the expectation of $\mathbf{\Xi}$, denoted by $\mathbb{E}_{\mathbf{\Theta}_E}\left[\mathbf{\Xi}\right]$, in order to facilitate the optimization procedure and achieve a statistical average optimization result.} {\color{black}\subsection{Expectation of $\mathbf{\Xi}$}} According to (\ref{eq2-24}), $\mathbb{E}_{\mathbf{\Theta}_E}\left[\mathbf{\Xi}\right]$ can be written as \begin{equation}\label{eq2-29} \mathbb{E}_{\mathbf{\Theta}_E}\left[\mathbf{\Xi}\right]= \mathbb{E}_{\mathbf{v}_E}\left[\mathbf{\Xi}\right]= \left(\begin{matrix}\mathbf{D}_{IU}\mathbf{D}_{SI}\mathbb{E}_{\mathbf{v}_E}\!\!\left[\mathbf{v}_E\mathbf{v}_E^H\right]\mathbf{D}_{SI}^H\mathbf{D}_{IU}^H&h_{SU}^*\mathbf{D}_{IU}\mathbf{D}_{SI}\mathbb{E}_{\mathbf{v}_E}\!\!\left[\mathbf{v}_E\right]\\\mathbb{E}_{\mathbf{v}_E}\!\!\left[\mathbf{v}_E^H\right]\mathbf{D}_{SI}^H\mathbf{D}_{IU}^Hh_{SU}&0\\\end{matrix}\right) \end{equation} where $\mathbf{D}_{SI}=diag(\mathbf{h}_{SI})$ and $\mathbf{v}_E=\left(e^{j\theta_{E1}},e^{j\theta_{E2}},\ldots,e^{j\theta_{EN}}\right)^T$. $\mathbb{E}_{\mathbf{v}_E}\left[\mathbf{v}_E\mathbf{v}_E^H\right]$, which is expressed as \begin{equation}\label{eq2-30} \begin{split} \mathbb{E}_{\mathbf{v}_E}\left[\mathbf{v}_E\mathbf{v}_E^H\right]= \left(\begin{matrix}\begin{matrix}1&\mathbb{E}_{\delta_{\theta}}\!\!\left[e^{j\theta_{E1}-j\theta_{E2}}\right]\\\mathbb{E}_{\delta_{\theta}}\!\!\left[e^{j\theta_{E2}-j\theta_{E1}}\right]&1\\\end{matrix}&\begin{matrix}\cdots&\mathbb{E}_{\delta_{\theta}}\!\!\left[e^{j\theta_{E1}-j\theta_{EN}}\right]\\\cdots&\mathbb{E}_{\delta_{\theta}}\!\!\left[e^{j\theta_{E2}-j\theta_{EN}}\right]\\\end{matrix}\\\begin{matrix}\vdots&\vdots\\\mathbb{E}_{\delta_{\theta}}\!\!\left[e^{j\theta_{EN}-j\theta_{E1}}\right]&\mathbb{E}_{\delta_{\theta}}\!\!\left[e^{j\theta_{EN}-j\theta_{E2}}\right]\\\end{matrix}&\begin{matrix}\ddots&\ \ \ \ \ \ \ \ \ \vdots\ \ \ \ \ \ \ \ \ \\\cdots&\ \ \ 1\ \ \ \\\end{matrix}\\\end{matrix}\right) \end{split} \end{equation} represents the autocorrelation matrix of $\mathbf{v}_E$, where $\delta_{\theta}=\theta_{Ei}-\theta_{Ej}$ obeys triangular distribution on $[-\pi,\pi]$ as $\theta_{Ei}$ obeys uniform distribution on $\left[-\pi/2,\pi/2\right]$ (detailed in Appendix A). {\color{black} Because $\mathbb{E}_{\delta_{\theta}}\left[e^{j\theta_{Ei}-j\theta_{Ej}}\right]=\mathbb{E}_{\delta_{\theta}}\left[e^{j\delta_{\theta}}\right]=\int_{-\pi}^{\pi}{f\left(\delta_{\theta}\right)e^{j\delta_{\theta}}d\delta_{\theta}}=4/\pi^2$, where $f\left(\delta_{\theta}\right)$, expressed as (\ref{eq-A6}) in Appendix A, is the probability density function of $\delta_{\theta}$, we have $\mathbb{E}_{\mathbf{v}_E}\left[\mathbf{v}_E\mathbf{v}_E^H\right]=\mathbf{I}_N+\mathbf{J}$, where the $(i,j)$-th element in the matrix $\mathbf{J}$ is expressed as \begin{equation} \left[\mathbf{J}\right]_{(i,j)}=\left\{ \begin{matrix} 0,\ \ \ i=j\\ \frac{4}{\pi^2},\ \ i\neq j \end{matrix} \right. \end{equation} Moreover}, because $\mathbb{E}_{\mathbf{v}_E}\left[\mathbf{v}_E\right] =\left(\mathbb{E}_{\theta_{Ei}}\!\!\left[e^{j\theta_{E1}}\right],\mathbb{E}_{\theta_{Ei}}\!\!\left[e^{j\theta_{E2}}\right],\ldots,\mathbb{E}_{\theta_{Ei}}\!\!\left[e^{j\theta_{EN}}\right]\right)^T$ and $\mathbb{E}_{\theta_{Ei}}\left[e^{j\theta_{Ei}}\right] =\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}}{f(\theta_{Ei})e^{j\theta_{Ei}}d\theta_{Ei}} =\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}}{f(\theta_{Ei})(cos\theta_{Ei}+jsin\theta_{Ei})d\theta_{Ei}} =2/\pi$ for $i=1,2,...,N$, where $f\left(\theta_{Ei}\right)=1/\pi$ is the probability density function of $\theta_{Ei}$, we have $\mathbb{E}_{\mathbf{v}_E}\left[\mathbf{v}_E\right]=\left(2/\pi\right)\mathbf{1}^T$. By substituting {\color{black}$\mathbb{E}_{\mathbf{v}_E}\left[\mathbf{v}_E\mathbf{v}_E^H\right]=\mathbf{I}_N+\mathbf{J}$} and $\mathbb{E}_{\mathbf{v}_E}\left[\mathbf{v}_E\right]=\left(2/\pi\right)\mathbf{1}^T$ into (\ref{eq2-29}), we have {\color{black}\begin{equation}\label{eq2-35} \mathbb{E}_{\mathbf{\Theta}_E}\left[\mathbf{\Xi}\right]=\left(\begin{matrix}\mathbf{D}_{IU}\mathbf{D}_{SI}(\mathbf{I}_N+\mathbf{J})\mathbf{D}_{SI}^H\mathbf{D}_{IU}^H&\frac{2}{\pi}h_{SU}^*\mathbf{D}_{IU}\mathbf{D}_{SI}\mathbf{1}^T\\\frac{2}{\pi}\mathbf{1}\mathbf{D}_{SI}^H\mathbf{D}_{IU}^Hh_{SU}&0\\\end{matrix}\right) \end{equation} Consequently}, by replacing $\mathbf{\Xi}$ in (P5) with $\mathbb{E}_{\mathbf{\Theta}_E}\left[\mathbf{\Xi}\right]$, we obtain \begin{subequations}\label{eq2-44} \begin{align} (\mathrm{P6}):\ \mathop{\max}\limits_{\mathbf{Y}\succeq\mathbf{0},\widetilde{\mu}\geq 0}&\frac{1}{\left(\kappa_t+\kappa_r\right)}\times\left[tr(\mathbb{E}_{\mathbf{\Theta}_E}\left[\mathbf{\Xi}\right]\mathbf{Y})+\widetilde{\mu}||h_{SU}||_2^2\right] \\s.t.\ &tr\left(\mathbf{E}_n\mathbf{Y}\right)=\widetilde{\mu}\alpha^2,\ n=1,2\ldots N \\&tr\left(\mathbf{E}_{N+1}\mathbf{Y}\right)=\widetilde{\mu} \\&tr\left(\mathbb{E}_{\mathbf{\Theta}_E}\left[\mathbf{\Xi}\right]\mathbf{Y}\right)+\widetilde{\mu}\left[||h_{SU}||_2^2+\frac{\sigma_w^2}{P\left(\kappa_t+\kappa_r\right)}\right]=1 \end{align} \end{subequations} where $\widetilde{\mu}=\frac{1}{tr(\mathbb{E}_{\mathbf{\Theta}_E}\left[\mathbf{\Xi}\right]\mathbf{X})+||h_{SU}||_2^2+\frac{\sigma_w^2}{P\left(\kappa_t+\kappa_r\right)}}$. {\color{black}Currently, because the matrix $\mathbb{E}_{\mathbf{\Theta}_E}\left[\mathbf{\Xi}\right]$ in the OBF and constraints only includes the channel coefficients, which can be estimated via existing channel estimation techniques, it is easy for us to configure $\mathbb{E}_{\mathbf{\Theta}_E}\left[\mathbf{\Xi}\right]$, which assists us in completing the phase shift optimization in terms of maximizing the average SNR in the presence of HWI.} It is remarkable that after (P6) is solved, the $\bm{\theta}^T$ in the $(N+1)$-th row of the $\mathbf{X}=\widetilde{\mu}^{-1}\mathbf{Y}$ in the solution can be extracted to reconstruct $\mathbf{Y}$ based on (\ref{eq2-26}) and $\mathbf{Y}=\widetilde{\mu}\mathbf{X}$. If the reconstructed $\mathbf{Y}$, denoted by $\mathbf{Y}_r$, {satisfies} $\mathbf{Y}_r=\mathbf{Y}$ and $rank(\mathbf{Y}_r)=1$, the $\bm{\theta}^T$ can be regarded as the optimal phase shift vector. As a result, {\color{black}we will test the values in $\mathbf{Y}_r$ and the rank of $\mathbf{Y}_r$ in the simulations in Section VI, in order to investigate whether} the optimal IRS phase shifts can be acquired from $\bm{\theta}^T$ in the $(N+1)$-th row of the $\mathbf{X}=\widetilde{\mu}^{-1}\mathbf{Y}$ in the solution of the relaxed problem. {\color{black} In addition, after the phase shift optimization process, two possible factors may still remain and influence the performance. 1) Most channel estimation methods suffer from estimation errors, which lead to imperfect CSI of $\mathbf{h}_{IU}$, $\mathbf{h}_{SI}$ and $h_{SU}$. Based on the imperfect CSI, we can only construct an inaccurate $\mathbb{E}_{\mathbf{\Theta}_E}\left[\mathbf{\Xi}\right]$, and then acquire a non-optimal phase shift vector. 2) Due to the inherent hardware imperfection, synchronization offset and estimation accuracy limit in the real world, the optimized phase values may not be precisely obtained. In this case, we may actually obtain $\widetilde{\bm{\theta}}^T=\bm{\theta}^T\odot\bm{\theta}_p^T$ instead of $\bm{\theta}^T$ after the optimization, where $\bm{\theta}_p=(e^{j\theta_{p1}},e^{j\theta_{p2}},...,e^{j\theta_{pN}})^T$ denotes a residual phase noise vector with $\theta_{pi}$ being the $i$-th random residual phase noise, which may disturb $\bm{\theta}^T$ and affect the optimization performance. The performance degradation caused by the aforementioned two factors is worth to be discussed. Thus, we will present the discussions on them in Section VI.} $\ $ \section{Comparisons with DF Relay} The DF relay is a conventional active {\color{black}approach} which is also applied for data transmission enhancement in the wireless communication network. Hence, it is {\color{black}necessary} to compare the performance of the IRS with that of the DF relay in the same situation. It was already confirmed that the ideal-hardware IRS equipped with a large number of reflecting units could help the wireless communication system provide higher ACR than the ideal-hardware DF relay equipped with one antenna \cite{E.Bjornson2020(WCL)}. {\color{black} However, the comparisons in \cite{E.Bjornson2020(WCL)} were made in consideration of single-antenna DF relay and multiple-unit IRS without HWI. Note that as $N$ grows, the average ACR of the multiple-unit IRS-aided communication system increases, while that of the single-antenna DF relay assisted communication system remains constant under a certain condition. This might be unfair for the DF relay during the comparisons. Therefore, in this section, we will compare the performances of the IRS with $N$ passive reflecting units and the DF relay with $N$ active antennas,} for the purpose of exploring whether the IRS can still possess advantages in ACR {\color{black}and utility} over the {\color{black}multiple-antenna DF relay} when there exists HWI. {\color{black} Before the comparisons, determining the exact closed-form ACR of the multiple-antenna DF relay assisted communication system with respect to $N$ in the presence of HWI, is a hard nut to crack,} as the channel coefficients include random phase shifts, which cannot be compensated by the DF relay. {\color{black} Fortunately, we realize that the source-to-relay and the relay-to-destination channels can similarly be regarded as the uplink and downlink channels modelled in \cite{E.Bjornson2014(TIT)}, which assists us in establishing the \textit{closed-form upper bound} of the ACR in relation to $N$ for the multiple-antenna DF relay supported communication system. } Let {\color{black}$\mathbf{h}_{SR}$, $\mathbf{h}_{RU}$} and $h_{SU}$ denote the source-to-relay, relay-to-destination and source-to-destination channels, respectively. For comparing, we assume that {\color{black}$\mathbf{h}_{SR}=\mathbf{h}_{SI}$, $\mathbf{h}_{RU}=\mathbf{h}_{IU}$}, and the receiver noises at the DF relay and the destination terminal have the same variance of $\sigma_w^2$. If the HWI appears at the source transmitter, the DF relay and the destination receiver, {\color{black}according to Eq. (6) and Eq. (2) in \cite{E.Bjornson2014(TIT)},} the signals received by the DF relay and the destination terminal are modelled as {\color{black}\begin{equation}\label{eq2-47} \mathbf{y}_{DF}(t)=\mathbf{h}_{SR}\left[\sqrt{P_1}s(t)+\eta_t(t)\right]+\bm{\eta}_{r_{DF}}(t)+\mathbf{w}_{DF}(t) \end{equation} and \begin{equation}\label{eq2-48} y_{U1}(t)=\mathbf{h}_{RU}\left[\sqrt{P_2}\mathbf{s}(t)+\bm{\eta}_{t_{DF}}(t)\right]+\eta_{r1}(t)+w(t) \end{equation} \begin{equation}\label{eq2-49} y_{U2}(t)=h_{SU}\left[\sqrt{P_1}s(t)+\eta_t(t)\right]+\eta_{r2}(t)+w(t) \end{equation} where} $P_1$ and $P_2$ are the transmitting powers of the source and the DF relay under the constraint of $P=\frac{P_1+P_2}{2}$ \cite{E.Bjornson2020(WCL)}; $y_{U1}(t)$ and $y_{U2}(t)$ are the signals received by the destination terminal through channel {\color{black}$\mathbf{h}_{RU}$} and $h_{SU}$, respectively; $\mathbf{w}_{DF}(t)\sim\mathcal{CN}(\mathbf{0},\sigma_w^2\mathbf{I})$ and $w(t)\sim\mathcal{CN}(0,\sigma_w^2)$ are the receiver noises at the DF relay and the destination terminal; {\color{black} $\eta_t(t)\sim\mathcal{CN}(0,\Upsilon_t)$, $\bm{\eta}_{r_{DF}}(t)\sim\mathcal{CN}(\mathbf{0},\mathbf{V}_{r_{DF}})$, $\bm{\eta}_{t_{DF}}(t)\sim\mathcal{CN}(\mathbf{0},\mathbf{\Upsilon}_{t_{DF}})$, $\eta_{r1}(t)\sim\mathcal{CN}(0,V_{r1})$ and $\eta_{r2}(t)\sim\mathcal{CN}(0,V_{r2})$} are the distortion noises at the source transmitter, the DF-relay receiver, the DF-relay transmitter and the destination receiver, respectively, with {\color{black} $\Upsilon_t$, $\mathbf{V}_{r_{DF}}$, $\mathbf{\Upsilon}_{t_{DF}}$, $V_{r1}$ and $V_{r2}$ given by \begin{equation} \Upsilon_t=\kappa_tP_1\mathbb{E}[s(t)s^*(t)] \end{equation} \begin{equation} \mathbf{V}_{r_{DF}}=\kappa_{r_{DF}}P_1\mathbb{E}[s(t)s^*(t)]\times diag(|h_{SR,1}|^2,...,|h_{SR,N}|^2) \end{equation} \begin{equation} \mathbf{\Upsilon}_{t_{DF}}=\kappa_{t_{DF}}P_2\times diag\{\mathbb{E}[s_1(t)s_1^*(t)],...,\mathbb{E}[s_N(t)s_N^*(t)]\} \end{equation} \begin{equation} V_{r1}=\kappa_{r1}P_2\mathbf{h}_{RU}^T\mathbb{E}[\mathbf{s}(t)\mathbf{s}^H(t)]\mathbf{h}_{RU}^* \end{equation} \begin{equation} V_{r2}=\kappa_{r2}P_1 |h_{SU}|^2\mathbb{E}[s(t)s^*(t)] \end{equation} where $\mathbf{s}(t)$ denotes the signal transmitted by the DF relay at time $t$; $s_i(t)$, for $i=1,2,...,N$, represents the $i$-th transmit symbol in $\mathbf{s}(t)$, with $\mathbb{E}[s_i(t)s_i^*(t)]=1$;} $\kappa_t$, $\kappa_{r_{DF}}$, $\kappa_{t_{DF}}$, $\kappa_{r1}$ and $\kappa_{r2}$ are the proportionality factors. For simple {\color{black}analysis}, we consider that $\kappa_{t_{DF}}=\kappa_t$ and $\kappa_{r1}=\kappa_{r2}=\kappa_{r_{DF}}=\kappa_r$, as the hardware characteristics of the transceivers in the DF relay are similar to those in the source equipment and the destination terminal. Therefore, {\color{black}referring to Eq. (26), Eq. (27) in \cite{E.Bjornson2014(TIT)}, and Eq. (15) in \cite{J.N.Laneman2004(TIT)},} the {\color{black}upper bound} of the ACR of the multiple-antenna DF relay assisted communication system with HWI is expressed as \begin{equation}\label{eq2-55} R_{HWI}^{DF}(N)= \frac{1}{2}\min{\left\{\mathfrak{A}(N),\mathfrak{B}(N)\right\}} \end{equation} where {\color{black}\begin{equation}\label{eq-A} \mathfrak{A}(N)=\log_2\left(1+\frac{N\mu_{SI}}{\kappa_r\mu_{SI}+N\kappa_t\mu_{SI}+\frac{\sigma_w^2}{P_1} }\right) \end{equation} \begin{equation}\label{eq-B} \mathfrak{B}(N)=\log_2\left(1+\frac{\mu_{SU}}{(\kappa_t+\kappa_r)\mu_{SU}+\frac{\sigma_w^2}{P_1}}+ \frac{N\mu_{IU}}{\kappa_t\mu_{IU}+N\kappa_r\mu_{IU}+\frac{\sigma_w^2}{P_2} }\right) \end{equation} Correspondingly, the utility of the multiple-antenna DF relay is expressed as \begin{equation}\label{eq-DF Utility} \gamma_{HWI}^{DF}(N)= \left\{\begin{matrix} \frac{\kappa_r\mu_{SI}^2+\frac{\sigma_w^2}{P_1}\mu_{SI}} {2\left(\kappa_r\mu_{SI}+N\kappa_t\mu_{SI}+\frac{\sigma_w^2}{P_1}\right)\left(\kappa_r\mu_{SI}+N\kappa_t\mu_{SI}+\frac{\sigma_w^2}{P_1}+N\mu_{SI}\right)\ln2}, \ \ \mathfrak{A}(N)<\mathfrak{B}(N) \\ \frac{\kappa_t\mu_{IU}^2+\frac{\sigma_w^2}{P_2}\mu_{IU}} {2\left(1+\frac{\mu_{SU}}{(\kappa_t+\kappa_r)\mu_{SU}+\frac{\sigma_w^2}{P_1}}+ \frac{N\mu_{IU}}{\kappa_t\mu_{IU}+N\kappa_r\mu_{IU}+\frac{\sigma_w^2}{P_2}}\right) \left(\kappa_t\mu_{IU}+N\kappa_r\mu_{IU}+\frac{\sigma_w^2}{P_2}\right)^2 \ln2}, \ \ \mathfrak{A}(N)>\mathfrak{B}(N) \end{matrix}\right. \end{equation} For analysis convenience and symbol unification, we assume that $\kappa_t+\kappa_r=\kappa$ with $\kappa_t=\kappa_r=\frac{1}{2}\kappa$ \cite{E.Bjornson2014(TIT)}, and} the total transmitting power of the DF relay assisted communication system ($P_1+P_2=2P$) is allocated by $P_1=P_2=P$. {\color{black} Subsequently, in order to investigate whether the IRS is potentially capable of outperforming the DF relay in the presence of HWI, we will compare $R_{HWI}^{DF}(N)$ in (\ref{eq2-55}) with $\overline{R_{HWI}}(N)$ in (\ref{eq2-17}) from the perspective of scaling law, by considering first $N\rightarrow\infty$ and then $P\rightarrow\infty$ in the following \textbf{Lemma 2} and \textbf{Lemma 3}. } {\color{black} \begin{lemma} When $N\rightarrow\infty$, we have \begin{equation}\label{N_inf_ACR_Compare} \left.\overline{R_{HWI}}(N)\right|_{N\rightarrow\infty}>\left.R_{HWI}^{DF}(N)\right|_{N\rightarrow\infty} \end{equation} \begin{equation}\label{N_inf_Utility_Compare} \left.\gamma_{HWI}(N)\right|_{N\rightarrow\infty}=\left.\gamma_{HWI}^{DF}(N)\right|_{N\rightarrow\infty}=0 \end{equation} \end{lemma} \begin{proof} The proof is given in Appendix B. \end{proof} \begin{lemma} When $P\rightarrow\infty$, we have \begin{equation}\label{P_inf_ACR_Compare} \left.\overline{R_{HWI}}(N)\right|_{P\rightarrow\infty}>\left.R_{HWI}^{DF}(N)\right|_{P\rightarrow\infty} \end{equation} \begin{equation}\label{P_inf_Utility_Compare_IRS} \left.\gamma_{HWI}(N)\right|_{P\rightarrow\infty}=0 \end{equation} \begin{equation}\label{P_inf_Utility_Compare_DF} \left.\gamma_{HWI}^{DF}(N)\right|_{P\rightarrow\infty} =\frac{\kappa}{(\kappa+N\kappa+2N)(\kappa+N\kappa)\ln 2} \end{equation} \end{lemma} \begin{proof} The proof is given in Appendix C. \end{proof} \textbf{Lemma 2} and \textbf{Lemma 3} demonstrate that: 1) when $N$ becomes large enough, or when $P$ is sufficiently high, the IRS can surpass the conventional multiple-antenna DF relay in terms of the ACR performance in the presence of HWI. 2) If $N\rightarrow\infty$, both the utilities of the IRS and the multiple-antenna DF relay verge on zero, hinting that adding one more reflecting element on the IRS or one more antenna on the DF relay hardly improves the ACR. 3) When $P$ is nearly infinite, the utility of the IRS is close to zero, while that of the multiple-antenna DF relay converges to a positive value, which indicates that adding one more antenna on the DF relay can still improve the ACR. This is because the IRS is passive and almost useless when $P\rightarrow\infty$, which makes the line-of-sight (LoS) link infinitely strong, while the DF relay is active and consumes power when retransmitting the wireless signals, so that when $P\rightarrow\infty$, each active antenna can always possess positive transmitting power and contribute to the data transmission enhancement. On this point, the multiple-antenna DF relay is more advantageous. } Moreover, it can be predicted that the IRS may possibly always outperform the multiple-antenna DF relay when the level of the transceiver HWI is high, because the HWI at the IRS is modelled as a phase error matrix which does not contain $\kappa_t$ or $\kappa_r$, while the HWI at the DF relay involves the distortion noises which contain the two terms. The DF relay may perform worse with higher $\kappa_t+\kappa_r$ while the IRS may maintain the performance due to the fixed uniform distribution of the phase errors. {\color{black}Therefore, we will also derive the interval of $\kappa_t+\kappa_r$, in which the IRS can always surpass the DF relay for all $N>0$ in the following \textbf{Lemma 4}. } \begin{lemma} The IRS will always outperform the {\color{black}multiple-antenna} DF relay for all $N>0$, when $\kappa_t+\kappa_r$ satisfies {\color{black}\begin{equation}\label{eq2-69} \kappa_t+\kappa_r>2\sigma_w^4 \left[P^2(\beta+\lambda+\mu_{SU})^2-2\sigma_w^2P(\beta+\lambda+\mu_{SU})\right]^{-1} =\kappa_{th} \end{equation} where $\beta$ and $\lambda$ have been defined in (\ref{eq-revision-1}) and (\ref{eq-revision-2}), respectively.} \end{lemma} \begin{proof} The proof is given in Appendix D. \end{proof} \textbf{Lemma 4} demonstrates that $\kappa_t+\kappa_r$ determines whether the IRS can always outperform the DF relay for all $N>0$ by a threshold $\kappa_{th}$ in (\ref{eq2-69}), {\color{black}which is mainly} decided by $\mu_{SI}$, $\mu_{IU}$, $\mu_{SU}$, $P$ and $\sigma_w^2$. {\color{black} If $P\rightarrow\infty$, we have $\kappa_{th}\rightarrow 0$, which makes (\ref{eq2-69}) always hold and makes the IRS perform better for all $N>0$ and $\kappa_t+\kappa_r>0$ in terms of the ACR. The outcome is consistent with (\ref{P_inf_ACR_Compare}) in \textbf{Lemma 3}.} \section{Simulation Results} \subsection{System Setup and Parameter Setting} This section will numerically elaborate the results of the ACR {\color{black} and the IRS utility} with or without HWI, and compare the performances of the IRS and the DF relay. As shown in Figure \ref{Fig-coordinate}, a two-dimensional plane in meters is established to indicate the positions of the source, the IRS and the destination, \begin{figure}[!t] \includegraphics[width=3.6in]{Fig_Coordinate.jpg} \centering \caption{Communication system design in the simulations. Three dashed lines which indicate $d_{SI}$, $d_{IU}$ and $d_{SU}$ constitute a right triangle, where $d_{SU}=\sqrt{d_{SI}^2+d_{IU}^2}$.} \label{Fig-coordinate} \end{figure} which are placed at $(0,15)$, $(50,15)$ and $(50,0)$. Regardless of the height, the distances between the source and the IRS ($d_{SI}$), the IRS and the destination ($d_{IU}$) and the source and the destination ($d_{SU}$) are $d_{SI}=50$ $m$, $d_{IU}=15$ $m$ and $d_{SU}=\sqrt{d_{SI}^2+d_{IU}^2}\approx52.2$ $m$, respectively. According to \cite{M.Cui2019(WCL),E.Bjornson2014(TIT)}, the other parameters are set {\color{black}in Table I. Based on Table I}, the power attenuation coefficients of channel $\mathbf{h}_{IU}$ (or $\mathbf{h}_{RU}$), $\mathbf{h}_{SI}$ (or $\mathbf{h}_{SR}$) and $h_{SU}$ are derived by $\sqrt{\mu_{IU}}=\sqrt{\zeta_0(d_0/d_{IU})^{\alpha_{IU}}}$, $\sqrt{\mu_{SI}}=\sqrt{\zeta_0(d_0/d_{SI})^{\alpha_{SI}}}$ and $\sqrt{\mu_{SU}}=\sqrt{\zeta_0(d_0/d_{SU})^{\alpha_{SU}}}$ \cite{M.Cui2019(WCL)}. \begin{table} \renewcommand{\arraystretch}{1.3} \caption{{\color{black}Parameter configurations.}} \label{Table_Parameters} \centering {\color{black} \begin{small} \begin{tabular}{ccc} \hline Parameters & Definitions & Values\\ \hline Amplitude Reflection Coefficient & $\alpha$ & $1$\\ Signal Power & $P$ & $20$ dBm\\ Receiver Noise Power & $\sigma_w^2$ & $-80$ dBm\\ Path Loss & $\zeta_0$ & $-20$ dB\\ Reference Distance & $d_0$ & $1$ m\\ Path Loss Exponents & $\alpha_{IU}=\alpha_{SI}=\alpha_{SU}$ & $3$\\ Phase Shift in $\mathbf{h}_{IU}$ & $\varphi_{IU,i}$ & Random in $[0,2\pi]$\\ Phase Shift in $\mathbf{h}_{SI}$ & $\varphi_{SI,i}$ & Random in $[0,2\pi]$\\ Phase Shift in $h_{SU}$ & $\varphi_{SU}$ & $\frac{\pi}{4}$\\ Proportionality Coefficients of Distortion Noises & $\kappa_t=\kappa_r$ & $0.05^2$\\ Oscillator Quality & $\delta$ & $1.58\times 10^{-4}$\\ \hline \end{tabular} \end{small} } \end{table} During the comparisons with DF relay, $d_{SI}$, $d_{IU}$ and $d_{SU}$ are also regarded as the distances between the source and the DF relay, the DF relay and the destination, and the source and the destination, respectively, which still adhere to $d_{SU}=\sqrt{d_{SI}^2+d_{IU}^2}$. The proportionality coefficients can be changed for diverse observations, but still satisfy $\kappa_t=\kappa_r$. {\color{black}\subsection{Numerical Illustrations for \textbf{Theorem 1} and \textbf{Lemma 1}}} {\color{black} For further discussing and validating the theoretical analysis in Section III}, we carry out the simulations via the following steps: \textit{B-Step 1}: We calculate $\overline{R_{HWI}}(N)$ in (\ref{eq2-17}) {\color{black}and $\gamma_{HWI}(N)$ in (\ref{Utility Expression})}, and record the results with HWI from {\color{black} $N=1$ to $N=5000$}. \textit{B-Step 2}: We calculate $R(N)$ in (\ref{eq2-11}) {\color{black}and $\gamma(N)$ in (\ref{Utility Expression 2})}, and record the results without HWI from {\color{black} $N=1$ to $N=5000$}. \textit{B-Step 3}: {\color{black}We calculate the rate gap $\delta_R(N)$ in (\ref{eq2-18}) and the utility gap $\delta_{\gamma}(N)$ in (\ref{Utility Degradation}), and record the results from $N=1$ to $N=5000$.} \textit{B-Step 4}: We calculate and record the numerical results of $R_{HWI}(N)$ in (\ref{eq2-16}) from {\color{black} $N=1$ to $N=5000$}. Due to the randomness of the phase errors generated by the IRS, the ACR is averaged on 1000 Monte Carlo trials {\color{black}every 500 points}. The average ACRs and {\color{black}IRS utilities} as functions of $N$ from $N=1$ to $N=5000$ are described in Figure \ref{Fig-For_IRS_ACR_and_Utility}. It is indicated that: 1) the experimental results fit well with the theoretical ones from $N=1$ to $N=5000$, which verifies the tightness of (\ref{eq2-17}). 2) The average ACR with HWI is lower and increases more slowly than that without HWI, and the rate gap {\color{black}widens} as $N$ grows. {\color{black}This phenomenon implies that when $N$ grows, the HWI accumulates and begets more severe ACR degradation. 3) When $N$ becomes pretty large, the ACR with HWI verges on $\log_2\left(1+\frac{1}{\kappa_t+\kappa_r}\right)=7.6511$, which testifies the correctness of (\ref{R_HWI Upper Bound}). 4) The IRS utility with HWI is lower than that without HWI, which demonstrates that the HWI reduces the IRS utility as well. Besides, both the IRS utility and the utility gap descend as $N$ grows, which reveals that the influence of the HWI on the IRS utility becomes slighter when $N$ is larger.} \begin{figure*}[!t] \centering \subfloat[]{\includegraphics[width=3.2in]{For_Average_ACR-eps-converted-to.pdf}} \label{For_Average_ACR} \subfloat[]{\includegraphics[width=3.2in]{For_Utility-eps-converted-to.pdf}} \label{For_Utility} \hfil \caption{{\color{black} Average ACRs and IRS utilities as functions of $N$ with or without HWI. (a) Average ACRs with respect to $N$, the curves marked with "$\square$", "$\bigcirc$", "$\bigtriangledown$" and "$*$", represent the results obtained in \textit{B-Step 1} to \textit{B-Step 4}, respectively. (b) IRS utilities with respect to $N$, the curves marked with "$\square$", "$\bigcirc$" and "$\bigtriangledown$", represent the results obtained in \textit{B-Step 1} to \textit{B-Step 3}, respectively.}} \label{Fig-For_IRS_ACR_and_Utility} \end{figure*} $\ $ {\color{black} \subsection{Phase Shift Optimization}} {\color{black}For giving insights into the phase shift optimization approach in Section IV, we carry out the simulations through the following steps: \textit{C-Step 1}: We solve (P6) by adopting CVX Toolbox with SDPT3 Solver, and obtain the maximum average SNR from the solution of the OBF in (\ref{eq2-44}a). Based on this solution, we calculate and record the ACRs at $N=1,13,25,37$. \textit{C-Step 2}: We solve (P6) and obtain the optimized matrix $\mathbf{Y}$ and variable $\widetilde{\mu}$. Next, we extract the $\bm{\theta}^T$ in the $(N+1)$-th row of $\mathbf{X}=\widetilde{\mu}^{-1}\mathbf{Y}$. Then, we utilize $\bm{\theta}^T$ to reconstruct $\mathbf{X}$ according to (\ref{eq2-26}) and $\mathbf{Y}$ according to $\mathbf{Y}=\widetilde{\mu}\mathbf{X}$, and denote the reconstructed $\mathbf{X}$ and $\mathbf{Y}$ by $\mathbf{X}_r$ and $\mathbf{Y}_r$, respectively. Finally, we substitute $\mathbf{Y}_r$ into the OBF in (\ref{eq2-44}a) and obtain the average SNR, based on which we calculate and record the ACRs at $N=1,13,25,37$. \textit{C-Step 3}: Based on the extracted $\bm{\theta}^T$, we obtain the optimized IRS phase shift matrix $\mathbf{\Phi}$ according to $\mathbf{\Phi}=diag(\bm{\theta}^T)$. Then, we substitute $\mathbf{\Phi}$ into (\ref{original ACR with HWI}) and obtain the ACRs with HWI, which are averaged on 1000 Monte Carlo trials at $N=1,13,25,37$. \begin{figure}[!t] \includegraphics[width=3.2in]{For_Optimization-eps-converted-to.pdf} \centering \caption{{\color{black}Average ACRs as functions of $N$ with HWI. The curves marked with "$\Diamond$", "+" and "$\bigcirc$" represent the results obtained in \textit{C-Step 1} to \textit{C-Step 3}, respectively. The curves marked with "$\square$" and "$*$" are copied from Figure \ref{Fig-For_IRS_ACR_and_Utility} (a) for comparisons.}} \label{Fig-Optimization} \end{figure} The average ACRs as functions of $N$ with HWI are depicted in Figure \ref{Fig-Optimization}. Results in Figure \ref{Fig-Optimization} show that: 1) the curves obtained in \textit{C-Step 1} and \textit{C-Step 2} coincide, indicating that $\mathbf{Y}_r=\mathbf{Y}$. Moreover, we calculate the rank of $\mathbf{Y}_r$ and obtain $rank(\mathbf{Y}_r)=1$. Because $\mathbf{Y}_r$ is constructed by $\bm{\theta}^T$ in the $(N+1)$-th row of $\mathbf{X}=\widetilde{\mu}^{-1}\mathbf{Y}$ in the solution, $\bm{\theta}^T$ is testified to be the optimal IRS phase shift vector. 2) The curves obtained in \textit{C-Step 1} and \textit{C-Step 3} coincide, confirming that the mathematical derivations for $\mathbb{E}_{\mathbf{\Theta}_E}\left[\mathbf{\Xi}\right]$ in (\ref{eq2-35}) are correct. 3) The average ACRs with the optimized IRS phase shifts exceed the average ACRs with $\theta_i=-\left(\varphi_{IU,i}+\varphi_{SI,i}\right)$, demonstrating that $\theta_i=-\left(\varphi_{IU,i}+\varphi_{SI,i}\right)$ is not the optimal phase shift as it does not take $h_{SU}$ into account.} $\ $ {\color{black} \subsection{Discussions on Channel Estimation Errors and Residual Phase Noises}} {\color{black}Because most IRS-aided communication systems suffer from channel estimation errors, and the optimized IRS phase shifts may generally be affected by residual phase noises, as narrated at the end of Section IV, we will probe into the influence of the two factors on the optimization performance. The channel estimation errors are set to be additive complex variables according to Eq. (2) in \cite{J.Zhang2020(CL)}, which follow the zero-mean complex Gaussian distribution with the variance of $\sigma_w^2$. More detailed information about the CSI uncertainty models and simulation parameters can be found in \cite{J.Zhang2020(CL)}. The residual phase noises $\theta_{pi}$ in $\bm{\theta}_p$, for $i=1,2,...,N$, are also set to be uniformly distributed on $[-\pi/2,\pi/2]$. \begin{figure}[!t] \includegraphics[width=3.2in]{For_Optimization_Other_Source_HWI-eps-converted-to.pdf} \centering \caption{{\color{black} Influences of the channel estimation errors and residual phase noises on the optimization results. The ACRs are derived by substituting $\mathbf{\Phi}=diag(\bm{\theta}^T)$ or $\mathbf{\Phi}=diag(\bm{\theta}^T\odot\bm{\theta}_p^T)$ into (\ref{original ACR with HWI}) and are averaged on 1000 Monte Carlo trials. "Imperfect CSI" means that there are channel estimation errors, while "Perfect CSI" represents the opposite.}} \label{Fig-For_Optimization_Other_Source_HWI} \end{figure} In the simulations, for investigating the average ACR with channel estimation errors, we first adopt the CSI with errors to construct $\mathbb{E}_{\mathbf{\Theta}_E}\left[\mathbf{\Xi}\right]$ and solve (P6), and then substitute $\mathbf{\Phi}=diag(\bm{\theta}^T)$ into (\ref{original ACR with HWI}) which contains the actual CSI. For investigating the average ACR with residual phase noises, we first solve (P6) and exert the influence of $\bm{\theta}_p$ on $\bm{\theta}^T$ by constructing $\bm{\theta}^T\odot\bm{\theta}_p^T$, and then substitute $\mathbf{\Phi}=diag(\bm{\theta}^T\odot\bm{\theta}_p^T)$ into (\ref{original ACR with HWI}). Figure \ref{Fig-For_Optimization_Other_Source_HWI} depicts the influences of the channel estimation errors and residual phase noises on the optimization results. It is demonstrated that: 1) both the channel estimation errors and the residual phase noises reduce the average ACR and degrade the optimization performance. 2) The residual phase noises impose more serious negative impact on the performance than the channel estimation errors, manifesting that the inherent hardware imperfection, synchronization offset and estimation accuracy limit in the real world, are key potential factors that affect the optimization performance. } $\ $ \subsection{Comparisons with DF Relay} In order to {\color{black}validate} the theoretical {\color{black}analysis} in Section V, we {\color{black}will} numerically compare the ACRs {\color{black}and the utilities} for the IRS-aided and the conventional multiple-antenna DF relay assisted wireless communication systems in the presence of HWI. {\color{black} Following Section V, we will compare the performances by varying $N$ and $P$. $\ $ \textit{1) Comparisons by varying $N$}: \begin{figure*}[!t] \centering \subfloat[]{\includegraphics[width=3.2in]{For_N_ACR_Comparison_DF-eps-converted-to.pdf}} \label{Fig-For_N_ACR_Comparison_DF} \subfloat[]{\includegraphics[width=3.2in]{For_N_Utility_Comparison_DF-eps-converted-to.pdf}} \label{Fig-For_N_Utility_Comparison_DF} \hfil \caption{{\color{black}Comparisons with DF relay by varying $N$. (a) Average ACRs as functions of $N$, with $P=20$ dBm and $\kappa_t=\kappa_r=0.05^2,0.07^2,0.09^2$. (b) Utilities as functions of $N$, with $P=20$ dBm and $\kappa_t=\kappa_r=0.05^2,0.07^2,0.09^2$.}} \label{Fig-C1} \end{figure*} First, considering the transmitting power to be fixed ($P=20$ dBm), we compare the average ACR in (\ref{eq2-17}) with that in (\ref{eq2-55}) by varying $N$, and observe the simulation results at $\kappa_t=\kappa_r=0.05^2,0.07^2,0.09^2$. Figure \ref{Fig-C1} (a) displays the average ACRs of the IRS-aided and the DF relay assisted wireless communication systems in relation to $N$, from $N=1$ to $N=5000$. It is indicated that: 1) the ACRs decrease when $\kappa_t$ and $\kappa_r$ grow, which verifies that more severe HWI is concomitant with more serious ACR reduction. 2) Although it might not be realistic for the IRS and the DF relay to be equipped with such a large number (e.g. 5000) of reflecting elements and antennas in practical implementations, the result testifies (\ref{N_inf_ACR_Compare}) in \textbf{Lemma 2} and confirms the possibility that when $N$ is extremely large, the IRS is capable of outperforming the DF relay in terms of the ACR performance. It is worth noting that when $\kappa_t=\kappa_r=0.05^2,0.07^2,0.09^2$, the IRS always performs better for all $N\in[1,5000]$. This is because with the system parameters set in Section VI-A, the $\kappa_{th}$ in (\ref{eq2-69}) in \textbf{Lemma 4} is computed as $\kappa_{th}=4.0451\times10^{-6}$, which is smaller than $\kappa=\kappa_t+\kappa_r=0.05^2+0.05^2,\ 0.07^2+0.07^2,\ 0.09^2+0.09^2$. 3) As $N$ grows, the ACRs do not continuously increase appreciably. Instead, the ACRs of the IRS-aided communication system are approximately limited by 7.6511 bps/Hz at $\kappa_t=\kappa_r=0.05^2$, 6.6871 bps/Hz at $\kappa_t=\kappa_r=0.07^2$ and 5.9710 bps/Hz at $\kappa_t=\kappa_r=0.09^2$; while those of the DF relay assisted communication system are approximately limited by 4.3237 bps/Hz at $\kappa_t=\kappa_r=0.05^2$, 3.8400 bps/Hz at $\kappa_t=\kappa_r=0.07^2$ and 3.4798 bps/Hz at $\kappa_t=\kappa_r=0.09^2$. The values are consistent with what are computed from $\left.\overline{R_{HWI}}\left(N\right)\right|_{N\rightarrow\infty}=\log_2\left(1+\frac{1}{\kappa_t+\kappa_r}\right)$ and $R_{HWI}^{DF}(N)|_{N\rightarrow\infty}=\frac{1}{2}\log_2\left(1+\frac{2}{\kappa}\right)$. 4) The ACRs of the DF relay assisted communication system increase rapidly when $N<100$, illustrating that the ACR performance of the DF relay can be significantly improved by increasing the quantity of the antennas when $N$ is small. Then, we compare the utility in (\ref{Utility Expression}) with that in (\ref{eq-DF Utility}) by varying $N$. Figure \ref{Fig-C1} (b) describes the utilities of the IRS and the DF relay in relation to $N$. The observation interval is shrunk ($N\in[1,16]$), for clearly viewing the details on the utility reduction of the DF relay. The results show that: 1) when $\kappa_t$ and $\kappa_r$ grow, the utilities decrease, which confirms that more severe HWI is concomitant with more serious utility degradation. 2) The IRS utility is lower than the DF-relay utility when $N$ is small, and both of them decrease to zero as $N$ grows. This is consistent with what is given in (\ref{N_inf_Utility_Compare}) in \textbf{Lemma 2}. $\ $ \textit{2) Comparisons by varying $P$}: \begin{figure*}[!t] \centering \subfloat[]{\includegraphics[width=3.2in]{For_P_ACR_Comparison_DF-eps-converted-to.pdf}} \label{Fig-For_P_ACR_Comparison_DF} \subfloat[]{\includegraphics[width=3.2in]{For_P_Utility_Comparison_DF-eps-converted-to.pdf}} \label{Fig-For_P_Utility_Comparison_DF} \hfil \caption{{\color{black}Comparisons with DF relay by varying $P$. (a) Average ACRs as functions of $P$, with $N=256$ and $\kappa_t=\kappa_r=0.05^2,0.07^2,0.09^2$. (b) Utilities as functions of $P$, with $N=256$ and $\kappa_t=\kappa_r=0.05^2,0.07^2,0.09^2$.}} \label{Fig-C2} \end{figure*} First, considering the number of the reflecting elements or the DF-relay antennas to be fixed ($N=256$), we compare the average ACR in (\ref{eq2-17}) with that in (\ref{eq2-55}) by varying $P$, and observe the numerical results at $\kappa_t=\kappa_r=0.05^2,0.07^2,0.09^2$. Figure \ref{Fig-C2} (a) plots the average ACRs of the IRS-aided and the DF relay assisted wireless communication systems with respect to $P$, from $P=1$ dBm to $P=50$ dBm. It is indicated that: 1) when $P<2$ dBm and $N=256$, the IRS performs worse than the DF relay if $\kappa_t=\kappa_r=0.05^2,0.07^2$, but better if $\kappa_t=\kappa_r=0.09^2$. This phenomenon reveals that when $P$ is low, the transceiver HWI influences the performance of the DF relay more seriously than the performance of the IRS. 2) The ACRs of the IRS-aided communication system increase faster as $P$ rises, and exceed the ACRs of the DF relay assisted communication system when $P>5$ dBm. 3) Both the ACRs of the IRS-aided and the DF relay assisted communication systems are bounded when $P$ is high. Specifically, the ACRs of the IRS-aided communication system are approximately bounded by 7.6511 bps/Hz at $\kappa_t=\kappa_r=0.05^2$, 6.6871 bps/Hz at $\kappa_t=\kappa_r=0.07^2$ and 5.9710 bps/Hz at $\kappa_t=\kappa_r=0.09^2$; while the ACRs of the DF relay assisted communication system are approximately bounded by 4.3209 bps/Hz at $\kappa_t=\kappa_r=0.05^2$, 3.8372 bps/Hz at $\kappa_t=\kappa_r=0.07^2$ and 3.4770 bps/Hz at $\kappa_t=\kappa_r=0.09^2$. The values coincide with what can be derived from $\overline{R_{HWI}}(N)|_{P\rightarrow\infty}=\log_2\left(1+\frac{1}{\kappa}\right)$ and $R_{HWI}^{DF}(N)|_{P\rightarrow\infty}=\frac{1}{2}\log_2\left(1+\frac{2N}{\kappa+\kappa N} \right)$. Then, we compare the utility in (\ref{Utility Expression}) with that in (\ref{eq-DF Utility}) by varying $P$. Figure \ref{Fig-C2} (b) depicts the utilities of the IRS and the DF relay with respect to $P$. The results demonstrate that: 1) when $P$ is relatively low, the utilities of the IRS outstrip those of the DF relay, but both of them descend as $P$ grows. 2) The utilities of the IRS decrease to zero, while those of the DF relay converge to certain positive values (around $1.09\times10^{-5}$), which are consistent with what are calculated from $\left.\gamma_{HWI}^{DF}(N)\right|_{P\rightarrow\infty}=\frac{\kappa}{(\kappa+N\kappa+2N)(\kappa+N\kappa)\ln 2}$. These results validate (\ref{P_inf_Utility_Compare_IRS}) and (\ref{P_inf_Utility_Compare_DF}) in \textbf{Lemma 3}, and reveal that in terms of the utility, although the IRS is preferable to the DF relay at a low system power, the DF relay becomes more advantageous if $P$ is significantly high. } {\color{black} \section{Conclusion and Future Works}} In this article, for the purpose of evaluating the performance of the IRS in consideration of {\color{black} the hardware non-ideality at both the IRS and the signal transceivers}, we first analyse the average ACR {\color{black}and the IRS utility} for the IRS-aided SISO communication system, then optimize the IRS phase shifts by converting the original non-convex problem into a SDP problem, {\color{black}subsequently investigate the impact of the channel estimation errors and the residual phase noises on the optimization performance}, and finally compare the IRS with the conventional {\color{black}multiple-antenna} DF relay {\color{black}in terms of the ACR and the utility} in the presence of HWI. The results illustrate that: 1) as the number of the reflecting units grows, the average ACR of the IRS-aided communication system increases, {\color{black}while the utility of the IRS decreases}. 2) The HWI degrades {\color{black}both the ACR and the utility, and it causes more severe ACR reduction when more reflecting elements are equipped.} 3) If the number of the reflecting units is large enough or {\color{black} the transmitting power is sufficiently high}, the IRS can surpass the conventional DF relay in terms of the ACR, {\color{black} although the DF relay is relatively more advantageous in terms of the utility.} Consequently, the IRS is proved to be still an effective facility for data transmission enhancement in the future wireless communication networks with imperfect hardware in the real world. {\color{black}As in most actual circumstances, the BS is generally equipped with multiple antennas and is responsible for serving multiple users, it is meaningful to dissect the system performance in the IRS-aided multiple-user MISO communication scenario in the presence of HWI. In view of the complex-matrix form of the BS-IRS channel, deriving the closed-form average ACR as a function of the number of the reflecting elements is a challenging task and deserves more effort. In addition, forasmuch as the typical amplify-and-forward (AF) relay is also widely utilized to assist the wireless communication, the insightful theoretical comparison with this conventional approach in the presence of HWI is challenging but worth to be performed in depth as well in the future.} \appendices \section{Proof of Theorem 1} In Appendix A, we will mathematically prove \textbf{Theorem 1} in Section III. {\color{black} First, based on (\ref{eq2-16}), the exact average ACR can be derived from \begin{equation}\label{Exact Ergodic} \begin{split} \overline{R_{HWI}}\left(N\right)=& \mathbb{E}_{\mathbf{\Theta}_E}\left[R_{HWI}\left(N\right)\right]\\=& \mathbb{E}_{\mathbf{\Theta}_E}\left\{\log_2\left\{1+\frac{P\left|\phi(t)\left(\alpha\mathbf{g}_{IU}^T\mathbf{\Theta}_E\mathbf{g}_{SI}+h_{SU}\right)\right|^2}{P(\kappa_t+\kappa_r)\left|\phi(t)\left(\alpha\mathbf{g}_{IU}^T\mathbf{\Theta}_E\mathbf{g}_{SI}+h_{SU}\right)\right|^2+\sigma_w^2}\right\}\right\} \end{split} \end{equation} However, as illustrated in \cite{D.Li2020(CL)}, it is difficult, if not impossible, to obtain the exact closed-form expression for $\mathbb{E}_{\mathbf{\Theta}_E}\left[R_{HWI}\left(N\right)\right]$. Therefore, inspired by \cite{D.Li2020(CL), Y.Han2019(TVT), M.Matthaiou2009(TCOM), Q.T.Zhang2005(TWC), S.Sanayei2007(TWC)}, we will also find an approximation to $\mathbb{E}_{\mathbf{\Theta}_E}\left[R_{HWI}\left(N\right)\right]$. Fortunately, according to Eq. (35) in \cite{E.Bjornson2013(TCOM)}, which is given by \begin{equation}\label{eq35_in_[R4.2]} \mathbb{E}\left\{\log_2\left(1+\frac{x}{y}\right)\right\}\approx \log_2\left(1+\frac{\mathbb{E}\{x\}}{\mathbb{E}\{y\}}\right) \end{equation} a simpler closed-form expression for the average ACR can be achieved by the approximation in (\ref{eq35_in_[R4.2]}). Hence, based on (\ref{eq35_in_[R4.2]}), the $\overline{R_{HWI}}\left(N\right)$ in (\ref{Exact Ergodic}) can be approximated by \begin{equation}\label{aver_ACR_IT-HWI-approx} \begin{split} \overline{R_{HWI}}\left(N\right)\approx& \log_2\left\{1+\frac{P\mathbb{E}_{\mathbf{\Theta}_E}\left[\left|\phi(t)\left(\alpha\mathbf{g}_{IU}^T\mathbf{\Theta}_E\mathbf{g}_{SI}+h_{SU}\right)\right|^2\right]}{P(\kappa_t+\kappa_r)\mathbb{E}_{\mathbf{\Theta}_E}\left[\left|\phi(t)\left(\alpha\mathbf{g}_{IU}^T\mathbf{\Theta}_E\mathbf{g}_{SI}+h_{SU}\right)\right|^2\right]+\sigma_w^2}\right\} \\ =&\log_2\left(1+\frac{P\mathcal{Q}}{P(\kappa_t+\kappa_r)\mathcal{Q}+\sigma_w^2}\right) \end{split} \end{equation} where $\mathcal{Q}=\mathbb{E}_{\mathbf{\Theta}_E}\left[\left|\phi(t)\left(\alpha\mathbf{g}_{IU}^T\mathbf{\Theta}_E\mathbf{g}_{SI}+h_{SU}\right)\right|^2\right]$. From (\ref{aver_ACR_IT-HWI-approx}), the problem of deriving the closed-form expression for $\mathbb{E}_{\mathbf{\Theta}_E}\left[R_{HWI}\left(N\right)\right]$ is converted into that for $\mathcal{Q}$, which is expanded into \begin{equation}\label{Expansion of E} \begin{split} \mathcal{Q}=& \mathbb{E}_{\mathbf{\Theta}_E}\left\{\left[\phi(t)\left(\alpha\mathbf{g}_{IU}^T\mathbf{\Theta}_E\mathbf{g}_{SI}+h_{SU}\right)\right]^*\left[\phi(t)\left(\alpha\mathbf{g}_{IU}^T\mathbf{\Theta}_E\mathbf{g}_{SI}+h_{SU}\right)\right]\right\} \\ =&\mathbb{E}_{\mathbf{\Theta}_E}\left[\left(\alpha\mathbf{g}_{IU}^T\mathbf{\Theta}_E\mathbf{g}_{SI}+h_{SU}\right)^*\left(\alpha\mathbf{g}_{IU}^T\mathbf{\Theta}_E\mathbf{g}_{SI}+h_{SU}\right)\right] \end{split} \end{equation} Subsequently,} let $\mathbf{G}_{IU}$ and $\mathbf{v}_{E}$ be defined by $\mathbf{G}_{IU}=diag\left(\mathbf{g}_{IU}\right)=\sqrt{\mu_{IU}}\mathbf{I}_N$ and $\mathbf{v}_{E}=\left(e^{j\theta_{E1}},e^{j\theta_{E2}},\ldots,e^{j\theta_{EN}}\right)^T$. Because we have $\mathbf{v}_{E}^T\mathbf{G}_{IU}=\mathbf{g}_{IU}^T\mathbf{\Theta}_E$, $\mathbf{G}_{IU}^*=\mathbf{G}_{IU}$ and $\mathbf{g}_{SI}^*=\mathbf{g}_{SI}$, from (\ref{Expansion of E}) we obtain \begin{small} \begin{equation}\label{Convert Q} \begin{split} \mathcal{Q}&=\mathbb{E}_{\mathbf{\Theta}_E}\left[{\alpha^2\mathbf{g}}_{SI}^T\mathbf{G}_{IU}^T\mathbf{v}_{E}^*\mathbf{v}_{E}^T\mathbf{G}_{IU}\mathbf{g}_{SI}+\alpha\mathbf{g}_{SI}^T\mathbf{G}_{IU}^T\mathbf{v}_{E}^*h_{SU}+\alpha h_{SU}^*\mathbf{v}_{E}^T\mathbf{G}_{IU}\mathbf{g}_{SI}+||h_{SU}||_2^2\right] \\ &=\alpha^2\mu_{IU}\mu_{SI}\mathbb{E}_{\theta_{Ei}}\left[tr\left(\mathbf{v}_{E}^T\mathbf{\Gamma}_N\mathbf{v}_{E}^*\right)\right]+\alpha\sqrt{\mu_{IU}\mu_{SI}\mu_{SU}}\mathbb{E}_{\theta_{Ei}}\left\{\sum_{i=1}^{N}\left[e^{j{{(\varphi}_{SU}+\theta}_{Ei})}+e^{-j{{(\varphi}_{SU}+\theta}_{Ei})}\right]\right\}+||h_{SU}||_2^2 \end{split} \end{equation} \end{small} where $i=1,2,...,N$. In (\ref{Convert Q}), we can expand $tr\left(\mathbf{v}_{E}^T\mathbf{\Gamma}_N\mathbf{v}_{E}^*\right)$ into \begin{small} \begin{equation}\label{eq-A3} \begin{split} tr\left(\mathbf{v}_{E}^T\mathbf{\Gamma}_N\mathbf{v}_{E}^*\right)&=N+\sum_{i\neq1}^{N}e^{j{{(\theta}_{E1}-\theta}_{Ei})}+\sum_{i\neq2}^{N}e^{j{{(\theta}_{E2}-\theta}_{Ei})}+\ldots+\!\!\sum_{i\neq N-1}^{N}e^{j{{(\theta}_{E\left(N-1\right)}-\theta}_{Ei})}+\sum_{i\neq N}^{N}e^{j{{(\theta}_{EN}-\theta}_{Ei})}\\ &=N+2\sum_{i=2}^{N}{cos{{(\theta}_{E1}-\theta}_{Ei})}+2\sum_{i=3}^{N}{cos{{(\theta}_{E2}-\theta}_{Ei})}+\ldots+2\sum_{i=N}^{N}{cos{{(\theta}_{E\left(N-1\right)}-\theta}_{Ei})}\\ &=N+{\mathbf{1M1}}^T \end{split} \end{equation} \end{small} where the matrix $\mathbf{M}$ is expressed as \begin{small} \begin{equation}\label{eq-A4} \mathbf{M}=\left(\begin{matrix}2\cos{\left({\theta_{E1}-\theta}_{E2}\right)}&2\cos{\left({\theta_{E2}-\theta}_{E3}\right)}&\begin{matrix}\cdots\ &2\cos{\left({\theta_{E\left(N-1\right)}-\theta}_{EN}\right)}\\\end{matrix}\\2\cos{\left({\theta_{E1}-\theta}_{E3}\right)}&2\cos{\left({\theta_{E2}-\theta}_{E4}\right)}&\begin{matrix}\cdots\ \ \ \ \ \ &\ \ \ \ 0\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \\\end{matrix}\\\begin{matrix}\vdots\\\begin{matrix}2\cos{\left({\theta_{E1}-\theta}_{E\left(N-1\right)}\right)}\\2\cos{\left({\theta_{E1}-\theta}_{EN}\right)}\\\end{matrix}\\\end{matrix}&\begin{matrix}\vdots\\\begin{matrix}2\cos{\left({\theta_{E2}-\theta}_{EN}\right)}\\0\\\end{matrix}\\\end{matrix}&\begin{matrix}\begin{matrix}\iddots\ \ \ \ \ \ \ \ \ \ &\ \vdots\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \\\end{matrix}\\\begin{matrix}0&\ \ \ \ \ \ \ \ \ \ \ 0\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \\\end{matrix}\\\begin{matrix}0&\ \ \ \ \ \ \ \ \ \ \ 0\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \\\end{matrix}\\\end{matrix}\\\end{matrix}\right) \end{equation} \end{small} We can also utilize Euler formula to expand $\sum_{i=1}^{N}\left[e^{j{{(\varphi}_{SU}+\theta}_{Ei})}+e^{-j{{(\varphi}_{SU}+\theta}_{Ei})}\right]$ and then obtain $\sum_{i=1}^{N}\left[e^{j{{(\varphi}_{SU}+\theta}_{Ei})}+e^{-j{{(\varphi}_{SU}+\theta}_{Ei})}\right]=2\sum_{i=1}^{N}\cos{\left({\varphi_{SU}+\theta}_{Ei}\right)}$. As $\theta_{Ei}$, for $i=1,2,...,N$, are random variables which are uniformly distributed on $\left[-\pi/2,\pi/2\right]$, we should calculate the expectations of $2\sum_{i=1}^{N}\cos{\left({\varphi_{SU}+\theta}_{Ei}\right)}$ and $tr\left(\mathbf{v}_{E}^T\mathbf{\Gamma}_N\mathbf{v}_{E}^*\right)$ in order to obtain a statistical average ACR. First, we calculate $\mathbb{E}_{\theta_{Ei}}\left[2\sum_{i=1}^{N}\cos{\left({\varphi_{SU}+\theta}_{Ei}\right)}\right]$ and have \begin{small} \begin{equation}\label{eq-A5} \begin{split} \mathbb{E}_{\theta_{Ei}}\!\!\left[2\sum_{i=1}^{N}\cos{\left({\varphi_{SU}+\theta}_{Ei}\right)}\right] &=2\mathbb{E}_{\theta_{Ei}}\!\!\left[\sum_{i=1}^{N}{\cos{\varphi_{SU}}\cos{\theta_{Ei}}}-\sum_{i=1}^{N}{\sin{\varphi_{SU}}\sin{\theta_{Ei}}}\right]\\ &=2N\!\cos{\varphi_{SU}}\!\!\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}}\!\!\!{f\left(\theta_{Ei}\right)\cos{\theta_{Ei}{d\theta}_{Ei}}}-2N\sin{\varphi_{SU}}\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}}{f\left(\theta_{Ei}\right)\sin{\theta_{Ei}{d\theta}_{Ei}}}\\ &=\frac{4}{\pi}N\cos{\varphi_{SU}} \end{split} \end{equation} \end{small}where $f\left(\theta_{Ei}\right)=1/\pi$ is the probability density function of variable $\theta_{Ei}$. Subsequently, we calculate $\mathbb{E}_{\theta_{Ei}}\left[tr\left(\mathbf{v}_{E}^T\mathbf{\Gamma}_N\mathbf{v}_{E}^*\right)\right]=N+\mathbb{E}_{\theta_{Ei}}\left[{\mathbf{1M1}}^T\right]$. It is notable that the elements in $\mathbf{M}$ are either 0, or $2\cos(\theta_{Ei}-\theta_{Ej})$ for $i<j$. Therefore, let $\delta_{\theta}$ be defined by $\delta_{\theta}=\theta_{Ei}-\theta_{Ej}$. Because $\theta_{Ei}$ obeys uniform distribution on $\left[-\pi/2,\pi/2\right]$, $\delta_{\theta}$ obeys triangular distribution on $[-\pi,\pi]$ whose probability density function is expressed as \begin{equation}\label{eq-A6} f\left(\delta_{\theta}\right)=\left\{\begin{matrix}\frac{1}{\pi^2}\delta_{\theta}+\frac{1}{\pi},\ \delta_{\theta}\in\left[-\pi,0\right]\\-\frac{1}{\pi^2}\delta_{\theta}+\frac{1}{\pi},\ \delta_{\theta}\in\left[0,\pi\right]\\\end{matrix}\right. \end{equation} Thus, we have {\color{black} \begin{small} \begin{equation}\label{eq-A7} \begin{split} N+\mathbb{E}_{\theta_{Ei}}\left[{\mathbf{1M1}}^T\right]&=N+\mathbb{E}_{\theta_{Ei}}\left[2\sum_{i<j}^{N}\cos{\left({\theta_{Ei}-\theta}_{Ej}\right)}\right]\\ &=N+N\left(N-1\right)\left[\int_{-\pi}^{0}{\left(\frac{1}{\pi^2}\delta_{\theta}+\frac{1}{\pi}\right)\cos{\left(\delta_{\theta}\right)}d\delta_{\theta}}+\int_{0}^{\pi}{\left(-\frac{1}{\pi^2}\delta_{\theta}+\frac{1}{\pi}\right)\cos{\left(\delta_{\theta}\right)}d\delta_{\theta}}\right]\\ &=N+\frac{1}{\pi^2}N(N-1)\left[\int_{-\pi}^0\delta_{\theta}\cos{(\delta_{\theta})}d\delta_{\theta}-\int_0^{\pi}\delta_{\theta}\cos{(\delta_{\theta})}d\delta_{\theta}\right]\\ &=N+\frac{4}{\pi^2}N(N-1)=\frac{4N^2}{\pi^2}+\left(1-\frac{4}{\pi^2}\right)N \end{split} \end{equation} \end{small}} By substituting (\ref{eq-A5}) and (\ref{eq-A7}) into (\ref{Convert Q}), and substituting (\ref{Convert Q}) into (\ref{aver_ACR_IT-HWI-approx}), we finally prove (\ref{eq2-17}). {\color{black} Then, by calculating $\gamma_{HWI}(N)=\frac{\partial\overline{R_{HWI}}\left(N\right)}{\partial N}$, we finally prove (\ref{Utility Expression}).} \section{Proof of Lemma 2} In Appendix B, we will prove \textbf{Lemma 2} in Section V. On the assumption that $\kappa_t=\kappa_r=\frac{1}{2}\kappa$ and $P_1=P_2=P$, {\color{black}when $N\rightarrow\infty$, from (\ref{eq-A}) and (\ref{eq-B}), we have \begin{equation} \mathfrak{A}(N)|_{N\rightarrow\infty}=\log_2\left(1+\frac{2}{\kappa}\right) \end{equation} \begin{equation} \mathfrak{B}(N)|_{N\rightarrow\infty}=\log_2\left(1+\frac{1}{\kappa+\frac{\sigma_w^2}{P\mu_{SU}}}+\frac{2}{\kappa}\right) \end{equation} Because $1+\frac{2}{\kappa}<1+\frac{1}{\kappa+\frac{\sigma_w^2}{P\mu_{SU}}}+\frac{2}{\kappa}$, according to (\ref{eq2-55}), we have \begin{equation} R_{HWI}^{DF}(N)|_{N\rightarrow\infty}=\frac{1}{2}\mathfrak{A}(N)|_{N\rightarrow\infty}=\frac{1}{2}\log_2\left(1+\frac{2}{\kappa}\right) \end{equation} Given $\overline{R_{HWI}}(N)|_{N\rightarrow\infty}$ in (\ref{R_HWI Upper Bound}), we calculate $\overline{R_{HWI}}(N)|_{N\rightarrow\infty}-R_{HWI}^{DF}(N)|_{N\rightarrow\infty}$ and obtain \begin{equation} \overline{R_{HWI}}(N)|_{N\rightarrow\infty}-R_{HWI}^{DF}(N)|_{N\rightarrow\infty} =\frac{1}{2}\log_2\left(1+\frac{1}{\kappa^2+2\kappa}\right)>0 \end{equation} from which we prove (\ref{N_inf_ACR_Compare}). Then, based on (\ref{Utility Expression}) and (\ref{eq-DF Utility}), we consider $N\rightarrow\infty$ and prove (\ref{N_inf_Utility_Compare}). } \section{Proof of Lemma 3} In Appendix C, we will prove \textbf{Lemma 3} in Section V. Similar to the proof of \textbf{Lemma 2} in Appendix B, {\color{black} when $P\rightarrow\infty$, we have \begin{equation} \mathfrak{A}(N)|_{P\rightarrow\infty}=\log_2\left(1+\frac{2N}{\kappa+\kappa N} \right) \end{equation} \begin{equation} \mathfrak{B}(N)|_{P\rightarrow\infty}=\log_2\left(1+\frac{1}{\kappa}+\frac{2N}{\kappa+\kappa N} \right) \end{equation} Because $1+\frac{2N}{\kappa+\kappa N}<1+\frac{1}{\kappa}+\frac{2N}{\kappa+\kappa N}$, according to (\ref{eq2-55}), we have \begin{equation} R_{HWI}^{DF}(N)|_{P\rightarrow\infty}=\frac{1}{2}\mathfrak{A}(N)|_{P\rightarrow\infty}=\frac{1}{2}\log_2\left(1+\frac{2N}{\kappa+\kappa N} \right) \end{equation} Based on (\ref{eq2-17}), we have \begin{equation} \overline{R_{HWI}}(N)|_{P\rightarrow\infty}=\log_2\left(1+\frac{1}{\kappa}\right) \end{equation} Hence, we calculate $\overline{R_{HWI}}(N)|_{P\rightarrow\infty}-R_{HWI}^{DF}(N)|_{P\rightarrow\infty}$ and obtain \begin{equation} \overline{R_{HWI}}(N)|_{P\rightarrow\infty}-R_{HWI}^{DF}(N)|_{P\rightarrow\infty} =\frac{1}{2}\log_2\left\{1+\frac{2\kappa+N+1}{(N+1)\kappa^2+2N\kappa} \right\}>0,\ \ \forall N>0 \end{equation} from which we prove (\ref{P_inf_ACR_Compare}). Then, on the basis of (\ref{Utility Expression}) and (\ref{eq-DF Utility}), we consider $P\rightarrow\infty$ and prove (\ref{P_inf_Utility_Compare_IRS}) and (\ref{P_inf_Utility_Compare_DF}). } \section{Proof of Lemma 4} In Appendix D, we will prove \textbf{Lemma 4} in Section V. {\color{black} It is noted that $\overline{R_{HWI}}(N)$ in (\ref{eq2-17}) is a monotonically increasing function with respect to $N>0$. Thus, its minimum lies on \begin{equation} \overline{R_{HWI}}\left(1\right)=\log_2\left\{1+\frac{\beta+\lambda+\mu_{SU}} {\kappa\left(\beta+\lambda+\mu_{SU}\right)+\frac{\sigma_w^2}{P}}\right\} \end{equation} Besides, $R_{HWI}^{DF}(N)$ in (\ref{eq2-55}) is also a monotonically increasing function in relation to $N>0$, which is limited by $R_{HWI}^{DF}(N)|_{N\rightarrow\infty}=\frac{1}{2}\log_2\left(1+\frac{2}{\kappa}\right)$. Therefore, for the IRS to always outperform the DF relay in terms of the ACR for all $N>0$, the following relationship should hold: \begin{equation}\label{Condition_of_IRS_to_always_outperform} \overline{R_{HWI}}\left(1\right)>R_{HWI}^{DF}(N)|_{N\rightarrow\infty} \end{equation} From (\ref{Condition_of_IRS_to_always_outperform}), after a few manipulations, we obtain \begin{equation} \kappa>2\sigma_w^4 \left[P^2(\beta+\lambda+\mu_{SU})^2-2\sigma_w^2P(\beta+\lambda+\mu_{SU})\right]^{-1} \end{equation} and consequently prove \textbf{Lemma 4}. } \ifCLASSOPTIONcaptionsoff \newpage \fi
{'timestamp': '2020-12-08T02:10:00', 'yymm': '2005', 'arxiv_id': '2005.14411', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14411'}
arxiv
\section{Introduction and related works} A Bayesian Network (BN) is a type of a probabilistic graphical model that can be viewed as a Directed Acyclic Graph (DAG), where nodes represent uncertain variables and arcs represent dependency or causal relationship between variables. The structure of a BN can be learned from data, and there are three main classes of structure learning: constraint-based, score-based and hybrid learning. The first type relies on conditional independence tests to construct the skeleton and orient edges, whereas the second type searches over the space of possible graphs and returns the graph that maximises a fitting score. Hybrid learning refers to algorithms that combine both constraint-based and score-based learning. \par A common problem when learning BNs from data is that of causal insufficiency, where data fail to capture all the relevant variables. Variables not captured by data are referred to as latent variables (also known as unobserved or unmeasured variables). In the real world, latent variables are impossible to avoid either because data may not be available or simply because some variables are unknown unknowns for which we will never seeks to record data. A special case of a latent variable, referred to as a latent confounder, is an unobserved common cause of two or more observed variables in a BN. While known latent variables pose less of a problem in knowledge-based BNs, where methods exist that enable users to model latent variables not present in the data under the assumption the statistical outcomes are already influenced by the causes an expert might identify as variables missing from the dataset \citep{constantinou}, they can be a problem in structure learning. This is because child nodes that share an unobserved common cause will be found to be directly related, even when they are not, and this is a widely known problem that gives rise to spurious correlations in the presence of confounding. \par The traditional DAG has proven to be unsuitable when structure learning is performed under the assumption that some variables are latent. This is because a DAG assumes causal sufficiency and does not capture latent variables. Ancestral graphs have been proposed as a solution to this problem, and represent an extension of DAGs that capture hidden variables. Specifically, the Maximal Ancestral Graph (MAG) \citep{richardson} is a special case of a DAG where arcs indicate direct or ancestral relationships, and bi-directed edges represent confounding. Moreover, a Partial Ancestral Graph (PAG) represents a set of Markov equivalent MAGs \citep{RePEc:mtp:titles:0262194406}, in the same way a Complete Partial Directed Acyclic Graph (CPDAG) represents a set of Markov equivalent DAGs. Fig 1 illustrates an example of a DAG with latent variables $L_1$ and $L_2$, along with its corresponding Markov equivalent MAGs and the PAG of Markov equivalent MAGs. Both types of ancestral graph, MAGs and PAGs, can be used to represent causally insufficient systems. \begin{figure}[h] \centering \includegraphics[scale=0.5]{figure1.jpg} \end{figure} \par The most popular BN structure learning algorithm for causally insufficient systems is the constraint-based FCI, which is based on the PC algorithm \citep{RePEc:mtp:titles:0262194406}. Various modified versions of FCI have been published in the literature and include the augmented FCI which improves the orientation phase by extending the orientation rules of FCI from four to ten \citep{zhang}, the conservative FCI (cFCI) which uses additional conditional independence tests to restrict unambiguous orientations and improve the identification of definite colliders \citep{DBLP:journals/corr/RamseyZS12}, and the RFCI which skips some of the orientation rules in FCI and performs fewer conditional independence tests that make the algorithm faster and more suitable to problems of 1000s of variables, in exchange for minor accuracy \citep{colombo}. These constraint-based algorithms assume the joint probability distribution is a perfect map with a faithful graph, and this is often not practical when working with real data. Moreover, the orientation phase depends on the accuracy of the skeleton and hence, any errors from the first phase are propagated to the orientation phase. GFCI relaxes these issues by incorporating the score-based approach of FGS \citep{DBLP:journals/corr/Ramsey15a}, which is an enhanced version of Greedy Equivalence Search (GES), thereby producing a hybrid learning algorithm that outperforms the constraint-based versions of FCI \citep{pmlr-v52-ogarrio16}. \par In addition to the FCI variants, other algorithms have been proposed that are based on different approaches to structure learning. These include the GSPo, the M\textsuperscript{3}HC and the GSMAG algorithms. Specifically, the GSPo is an ordering-based search algorithm that uses greedy search over the space of independence maps (IMAPs) to determine the minimal IMAP \citep{Bernstein2019OrderingBasedCS}. This is achieved by defining a partial ordered set (poset) that is linked to the IMAP, expressed as a discrete optimisation problem. However, GSPo uses a random starting point for a poset, and this makes the algorithm non-deterministic since each run is likely to produce a different result. On the other hand, the M\textsuperscript{3}HC is a hybrid learning algorithm \citep{tsirlis} that adds a constraint-based learning phase to the greedy search of the GSMAG algorithm \citep{Triantafillou2016ScorebasedVC}. Both M\textsuperscript{3}HC and GSMAG assume the data are continuous and normally distributed, and Tsirlis et al. \citep{tsirlis} showed that hybrid algorithms such as M\textsuperscript{3}HC and GFCI demonstrate better performance over the other relevant constraint-based algorithms. \par The paper is organised as follows: Section 2 describes the CCHM algorithm, Section 3 describes the evaluation process, Section 4 presents the results, and we provide our concluding remarks and a discussion for future work in Section 5. \section {Conservative rule and Causal effect Hill-climbing for MAG (CCHM)} CCHM is a hybrid structure learning algorithm defined as a Structural Equation Model (SEM), under the assumption the data are continuous and follow a multivariate Gaussian distribution. The process of CCHM can be divided into two phases. The first phase adopts the conditional independence steps from cFCI to construct the skeleton of the graph, and to further classify definite colliders as whitelist and definite non-colliders as blacklist. The second phase involves score-based learning that uses the Bayesian Information Criterion (BIC) as the objective function, adjusted for MAGs, where edge orientation is augmented with causal effect measures. These steps are described in more detail in the subsections that follow. \subsection{Definite colliders (whitelist) and definite non-colliders (blacklist)} Conditional independence tests are used to determine the edges between variables and to produce the skeleton graph. A p-value associates with each statistical test result, which is used to sort conditional independencies in ascending order. An alpha hyperparameter is then used as the cut-off threshold in establishing independence. For each conditional independency $A$$\mathrel{\text{\scalebox{1.07}{$\perp\mkern-10mu\perp$}}}$$B$$\mid$$Z$, $Z$ is recorded as the separation set (Sepset) of variables $A$ and $B$. The orientation of edges is determined by a method inherited from cFCI, where extra conditional independence tests over all unshielded triples determine the classification of each of those triples as either a definite collider or a definite non-collider: \begin{itemize} \item Given unshielded triple $A$-$C$-$B$, perform conditional independence tests on $A$ and $B$ over all neighbours of $A$ and $B$. \item If $C$ is \textbf{NOT} in all Sepsets of $A$ and $B$, add $A$-$C$-$B$ to the whitelist as a definite collider. \item If $C$ is in \textbf{ALL} Sepsets of $A$ and $B$, add $A$-$C$-$B$ to the blacklist as a definite non-collider. \end{itemize} \subsection{Bayesian Information Criterion (BIC) for MAG} The score-based learning part of CCHM involves hill-climbing greedy search that minimises the BIC score, which is a function for goodness-of-fit in BNs based on Occam’s razor principle \citep{adnan}. The BIC score balances the Log-Likelihood (LL) fitting against a penalty term for model dimensionality. CCHM adopts the BIC function used in the M\textsuperscript{3}HC and GSMAG algorithms, and which is adjusted for MAGs \citep{tsirlis}. Formally, given a dataset over vertices $V$ with a distribution $\mathcal{N}\left(0,\Sigma\right)$ where $\Sigma$ is a covariance matrix calculated from the dataset, a unique solution $Y$ is found where $\hat{\Sigma}=\left(I-\mathcal{B}\right)^{-1}{\Omega\left(I-\mathcal{B}\right)}^{-t}$. MAG $\mathcal{G}$ is constructed from linear equations $Y=\mathcal{B}\cdot Y+\epsilon$, where $Y=\left\{Y_i\middle|i\in V\right\}$, $\mathcal{B}$ is a $V\times V$ coefficient matrix for the directed edge $j$ to $i$ $\left\{\beta_{ij}\right\}$, I is an identity matrix, $\epsilon$ is a positive random error vector for the bidirected edge $j$ to $i$ $\left\{\omega_{ij}\right\}$, and the error covariance matrix $\Omega=Cov\left(\epsilon\right)=\left\{\omega_{ii}\right\}$. The BIC score is then calculated as follows \citep{richardson}: \[ BIC\left(\hat{\sum}\middle|\mathcal{G}\right)=-2\ln{\left(l_\mathcal{G}\left(\hat{\sum}\middle|\mathcal{G}\right)\right)}+\ln{\left(N\right)\left(2\left|V\right|+\left|E\right|\right)} \qquad (1) \] where $l_\mathcal{G}$ is likelihood function, $\left|V\right|$ and $\left|E\right|$ are the size of nodes and edges that are part of the complexity penalty term, and $N$ is the sample size. Similar to the factorisation property of DAGs, the score $l_\mathcal{G}\left(\hat{\sum}\middle|\mathcal{G}\right)$ can be decomposed into c-components ${(S}_k)$ of $\mathcal{G}$ which refer to the connected components that are partitioned by removing all directed edges \citep{nowzohour}: \[ l_\mathcal{G}\left(\hat{\sum}\middle|\mathcal{G}\right)=-\frac{N}{2}\sum_{k}S_k \qquad (2) \] \begin{center} where $ S_k=\left|C_k\right|\cdot\ln{\left(2\pi\right)}+ln\left(\frac{\left|{\hat{\Sigma}}_{\mathcal{G}_k}\right|}{\prod_{j\in{\rm Pa}_{\mathcal{G}_k}}\sigma_{kj}^2}\right)+\frac{N-1}{N}\cdot tr\left[{\hat{\Sigma}}_{\mathcal{G}_k}^{-1}S_{\mathcal{G}_k}-\left|{\rm Pa}_\mathcal{G}\left(C_k\right)\setminus\left\{C_k\right\}\right|\right]$ \end{center} and where $C_k$ denotes the set of nodes for each c-component$\ k, \mathcal{G}_k$ is the marginalisation from $C_k$, with all their parent nodes are defined as ${\rm Pa}_\mathcal{G}\left(C_k\right)$ in $C_k, \sigma_{kj}^2$ represents the diagonal ${\hat{\Sigma}}_{\mathcal{G}_k}$ of the parent node k. The likelihood $\hat{\Sigma}$ is estimated by the RICF algorithm \citep{drton}. \subsection{Direct causal criteria for CCHM} Because the BIC is a Markov equivalent score, it is incapable of orientating all edges from statistical observations. Optimising for BIC under causal insufficiency returns a PAG, or one of the MAGs that are part of the equivalence class of the optimal PAG. In this paper, we are interested in orientating all edges and discovering a MAG. We achieve this using Pearl’s do-calculus \citep{causality} to measure the direct causal effect on edges that remain undirected by BIC. The direct causal effect is estimated by intervention that renders the intervening variable independent of its parents. \section*{Theorem: Single-door criterion for direct effect} Single-Door Criterion for direct effect \citep{causality}: Given $X$$\to$$Y$, path coefficient is identifiable and equal to the regression coefficient if \begin{itemize} \item There existed a set of variable $Z$ such that $Z$ contains no descendant of $Y$ \item $Z$ is d-separated set of $X$ and $Y$ in subgraph removing $X$$\to$$Y$ \end{itemize} The interpretation of the path coefficient $(\beta)$ in the regression of Theorem can be expressed as the direct causal effect determined by the rate of change of $E\left[Y\right]$ given intervention $X$ \citep{Maathuis2009EstimatingHI} as follows. \begin{center} $ \beta=\frac{\partial}{\partial x}E\left[Y|\ do(x)\right] =E[Y|do(X\ =x+1)] - E[Y|do(X= x)] $ for any value of $x$ \end{center} This assumes that all casual effect parameters are identifiable, and that the path coefficient or the direct causal effect is the regression coefficient estimated from the likelihood function. Let $A$$\to$$B$ be the edge in the ground truth graph, the SEM $B=\beta_AA+\epsilon_B$, if we assume that we have $A\sim\mathcal{N}\left(\mu_A,\sigma^2_A\right),\epsilon_B\sim\mathcal{N}(0,\sigma_{\epsilon_B}^2)$, and $\epsilon_B$ and $A$ are independent. Thus, $E\left[B\right]=\beta_AE\left[A\right],\ {\sigma^2}_B={\beta_A}^2{\sigma^2}_A+\sigma_{\epsilon_B}^2$. For every pair $A$ and $B$ in the learned graph, two causal graphs where $A$$\to$$B$ and $A$←$B$ need to be constructed to measure the direct causal effects. Specifically, \begin{itemize} \item For graphs $A$$\to$$B$, do the intervention on A; i.e., $do(a)$ \citep{causality} (page 161) \[ {\ \ \beta}_A\ =\ \frac{E\left[BA\right]}{E\left[A^2\right]} \qquad (3) \] \item For graphs $B$$\to$$A$, do the intervention on B; i.e., $do(b)$. \[ \beta_B\ =\ \frac{E\left[AB\right]}{E\left[B^2\right]} \qquad (4) \] \end{itemize} From (3) and (4); \[ \frac{\beta_A}{\beta_B}=\ \frac{E\left[B^2\right]}{E\left[A^2\right]}\ =\ \frac{{E\left[B\right]}^2+{\sigma^2}_B}{{E\left[A\right]}^2+{\sigma^2}_A}\ \] Substitute$\ E\left[B\right]=\beta_AE\left[A\right],\ {\sigma^2}_B={\beta_A}^2{\sigma^2}_A+\sigma_{\epsilon_B}^2 $ from the graph, \[ \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,=\ \frac{\beta_A^2{E\left[A\right]}^2+{\beta_A}^2{\sigma^2}_A+\sigma_{\epsilon_B}^2}{{E\left[A\right]}^2+{\sigma^2}_A}\ =\ \beta_A^2+\frac{\sigma_{\epsilon_B}^2}{{E\left[A\right]}^2+{\sigma^2}_A}\ \ \ \ \ \qquad (5) \] If $E\left[A\right]\ =\mu_A=0,{\sigma^2}_A=1\ $and $\ {\sigma^2}_{\epsilon_B}=1\ $in$\ \ (5) $ \\ \begin{center} $ \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, \frac{\beta_A}{\beta_B}=\ {\beta_A}^2+1$; we have the probability $(\left|\beta_A\right|>\left|\beta_B\right|)=1$ \end{center} Algorithm 1 describes the steps of CCHM in detail. \begin{figure}[H] \centering \includegraphics[scale=0.5]{algorithm1.jpg} \end{figure} \section{Evaluation} The accuracy of the CCHM algorithm is compared to the outputs of the M\textsuperscript{3}HC, GSPo, GFCI, RFCI, FCI, and cFCI algorithms, when applied to the same data. The M\textsuperscript{3}HC algorithm was tested using the MATLAB implementation by Triantafillou \citep{causalgraphs}, the GFCI and RFCI algorithms were tested using the Tetrad-based rcausal package in R \citep{rcausal}, and the GSPo algorithm was tested using the causaldag Python package by Squires \citep{causaldag}. The computational time of CCHM is compared to the M\textsuperscript{3}HC, FCI and cFCI, which are based on the same MATLAB package. \par All experiments are based on synthetic data. However, we divide them into experiments based on data generated from BNs which had their structure and dependencies randomised, and data generated from real-world BNs. Randomised BNs were generated using Triantafillou’s \citep{causalgraphs} MATLAB package. We created a total of 600 random Gaussian DAGs that varied in variable size, max in-degree, and sample size. Specifically, 50 DAGs were generated for each combination of variables $V$ and max in-degree settings $\mathcal{D}$, where $V$ = \{10, 20, 50, 70, 100, 200\} and $\mathcal{D}$=\{3, 5\}. Each of those 600 graphs was then used to generate two datasets of sample size 1,000 and 10,000, for a total of 1,200 datasets. Data were generated assuming linear Gaussian parameters $\mu$=0 and $\sigma^2$=1 and uniformly random coefficients $\pm$[0.1,0.9] for each parent set to avoid very weak or very strong edges. Approximately 10\% of the variables in the data are made latent in each of the 600 datasets. \par In addition to the randomised networks, we made use of four real-world Gaussian BNs taken from the bnlearn repository \citep{bnlearn}. These are the a) \emph{MAGIC-NIAB} (44 nodes) which captures genetic effects and phenotypic interactions for Multiparent Advanced Generation Inter-Cross (MAGIC) winter wheat population, b) \emph{MAGIC-IRRI} (64 nodes) which captures genetic effects and phenotypic interactions for MAGIC indica rice population, c) \emph{ECOLI70} (46 nodes) which captures the protein-coding genes of \emph{E. coli}, and d) \emph{ARTH150} (107 nodes) which captures the gene expressions and proteomics data of \emph{Arabidopsis Thaliana}. Each of these four BNs was used to generate data, with the sample size set to 10,000. For each of the four datasets, we introduced four different rates of latent variable: 0\%, 10\%, 20\% and 50\%. This made the total number of real-world datasets 16; four datasets per BN. \par The following hyperparameter settings are used for all algorithms: a) alpha=0.01 for the fisher’s z hypothesis test for datasets generated by the randomised \footnote{The large number of datasets produced by the randomised graphs (i.e., 600) meant that we had to restrict the alpha parameter to alpha=0.01 for all algorithms in those experiments.} BNs, b) alpha =0.05, 0.01, 0.001 (all cases tested) for datasets generated by the real-world BNs, and c) the max Sepset size of the conditioning set is set to 4 so that runtime is maintained at reasonable levels. The maximum length of discriminating paths is also set to 4 in the four FCI-based algorithms (this is the same as the max Sepset size). For GSPo, the depth of depth-first search is set to 4 and the randomised points of posets equal to 5 (these are the default settings). Because GSPo is a non-deterministic algorithm that generates a different output each time it is executed, we report the average scores obtained over five runs. Lastly, all algorithms were restricted to a four-hour runtime limit. \par Further, because the algorithms will output either a PAG or a MAG, we convert all MAG outputs into the corresponding PAGs. The accuracy of the learned graphs is then assessed with respect to the true PAG. The results are evaluated using the traditional measures of Precision and Recall, the Structural Hamming Distance (SHD) which represents the difference in the number of edges and edge orientations between the learned and the true graphs, and the Balance Scoring Function (BSF) which returns a balanced score by taking into consideration all four confusion matrix parameters as follows \citep{DBLP:journals/corr/abs-1905-12666}: $BSF=0.5\left(\frac{TP}{a}+\frac{TN}{i}-\frac{FP}{i}-\frac{FN}{a}\right) $ where $a$ is the numbers of edges and $i$ is the number of direct independences in the ground true graph, and $i=\frac{n(n-1)}{2}-a$. The BSF score ranges from -1 to 1, where 1 refers to the most accurate graph (i.e., matches the true graph), 0 refers to a baseline performance that is equal to that of a fully connected or an empty graph, and -1 refers to the worst possible graph (i.e., the reverse result of the true graph). \section{Results} \subsection{Random Gaussian Bayesian Networks} Fig 2 presents the Precision and Recall scores the algorithms achieve on the datasets generated by the randomised BNs. The scores are averaged across the different settings of variable size and max in-degree. Note that because there was no noteworthy difference between the overall results obtained from the two different data sample sizes, we only report the results based on sample size 10,000. The results and conclusions based on the datasets with sample size 10,000 also hold for the datasets with sample size 1,000. \par Overall, the results show that, the CCHM outperforms all other algorithms in terms of both Precision and Recall, and across all settings excluding Recall under max in-degree 5 where GSPo ranks highest (Fig 2b). While GSPo appears to perform best when the number of variables is smallest, its performance decreases sharply with the number of variables, and fails to produce a result within the 4-hour time limit when the number of variables is largest. \begin{figure} [H] \centering \includegraphics[scale=0.4]{figure2.jpg} \end{figure} \par The results show no noticeable difference between FCI and its variant RFCI, whereas the cFCI and GFCI show strong improvements over FCI, with cFCI outperforming all FCI-based algorithms. Moreover, the performance of cFCI is on par with that of M\textsuperscript{3}HC. Note that while CCHM employs the BIC objective function of M\textsuperscript{3}HC, CCHM outperforms M\textsuperscript{3}HC in both sparse (Fig 2a) and dense (Fig 2b) graphs. This result provides empirical evidence that a) the conservative rules used in the constraint-based phase of CCHM, and b) the do-calculus used in the score-based phase of CCHM, have indeed improved structure learning performance. \par Fig 3 compares the average runtime of CCHM to the runtimes of the other algorithms. The runtime comparison is restricted to algorithms that are based on the same MATLAB implementation on which CCHM is based. The results show that CCHM is marginally faster than cFCI and slower than the other algorithms, with the worst case scenario observed when the number of variables is largest, where CCHM is approximately two times slower than FCI. \par Fig 4 presents the SHD and BSF scores, along with the corresponding numbers of edges generated by each algorithm. Both the SHD and BSF metrics rank CCHM highest, and these results are consistent with the Precision and Recall results previously depicted in Fig 2. The number of edges produced by CCHM is in line with the number of edges produced by the other algorithms, and this observation provides confidence that CCHM achieves the highest scores due to accuracy rather than due to the number of edges, which may sometimes bias the result of a metric \citep{DBLP:journals/corr/abs-1905-12666}. One inconsistency between the SHD and other metrics involves the GFCI algorithm, where SHD ranks lower than all the other FCI-based algorithms, something which contradicts the results of Precision, Recall, and BSF. Interestingly, while GSPo produces the highest BSF scores when the number of variables is just 10, its performance diminishes drastically with the number of variables and quickly becomes the worst performer (refer to the BFS scores in Fig 4a); an observation that is largely consistent with the results in Fig 2. \begin{figure} [H] \centering \includegraphics[scale=0.4]{figure4.jpg} \end{figure} \subsection{Real-world Gaussian Bayesian Networks} The reduced number of experiments that associate with the real-world GBNs, with respect to the random GBNs (i.e., 16 instead of 600), enabled us to also test the sensitivity of the algorithms on the alpha hyperparameter, which reflects the significance cut-off point in establishing independence. Fig 5 presents the SHD scores for each of the four real-world GBNs, and over different rates of latent variables in the data. The results in each case study are restricted to the top three algorithms, and this is because we report three different results for each of the top three algorithms which are derived from the corresponding three different hyperparameter inputs alpha specified in Fig 5. \begin{figure} [H] \centering \includegraphics[scale=0.38]{figure5.jpg} \end{figure} \par Only four algorithms (CCHM, M\textsuperscript{3}HC, cFCI and GSPo) achieved a top-three performance in any of the four networks, and this suggests that the relative performance between algorithms is rather consistent across different case studies. While there is no clear relationship between the rate of latent variables and SHD score, the results do suggest that the accuracy of the algorithms decreases with the rate of latent variables in the data. This is because while we would expect the SHD score to decrease with less variables in the data, since less variables lead to potentially fewer differences between the learned and the true graph (refer to Fig 4), the results in Fig 5 reveal a weak increasing trend in SHD core with the rate of latent variables in the data. \par Overall, the CCHM algorithm was part of the top three algorithms in all the four case studies. Specifically, CCHM generated the lowest SHD error in networks (a) and (b). The results in network (c) were less consistent, with GSPo ranked 1\textsuperscript{st} at latent variable rates of 10\% and 20\%, and CCHM ranked 1\textsuperscript{st} at latent variable rates of 0\% and 50\%. In contrast, the results based on network (d) show no noteworthy differences in the performance between the three top algorithms. Overall, the results suggest that cFCI and GSPo are much more sensitive to the alpha hyperparameter compared to the CCHM and M\textsuperscript{3}HC algorithms, and that CCHM generally performs best when alpha=0.01. \section{Discussion and future works} This paper builds on recent developments in BN structure learning under causal insufficiency with a novel structure learning algorithm, called CCHM, that combines constraint-based and score-based learning with causal effects to learn GBNs. The constraint-based part of CCHM adopts features from the state-of-the-art cFCI algorithm, whereas the score-based part is based on traditional hill-climbing greedy search that minimises the BIC score. CCHM applies Pearl’s do-calculus as a method to orientate the edges that both constraint-based and score-based learning fail to do so from observational data. The results show that CCHM outperforms the state-of-the-art algorithms in the majority of the experiments, which include both randomised and real-world GBNs. \par A limitation of this work is that the algorithm assumes linear GBNs and that the data are continuous. Future work will extend this approach to discrete BNs, where causal insufficiency remains an important open problem \citep{inbook}. Other directions include investigating different strategies in the way the do-calculus effect is applied to the process of structure learning; e.g., it can be applied directly to the calculation of the BIC score during score-based learning, or computed as the total causal effect of the graph using do-calculus rules or via back-door adjustment with graph surgery. Lastly, causal insufficiency represents just one type of data noise that exist in real-world datasets, and future work will also investigate the effects of causal insufficiency when combined with other types of noise in the data. \acks{This research was supported by the ERSRC Fellowship project EP/S001646/1 on \emph{Bayesian Artificial Intelligence for Decision Making under Uncertainty} \citep{anthony2018}, by The Alan Turing Institute in the UK under the EPSRC grant EP/N510129/1, and by the Royal Thai Government Scholarship offered by Thailand’s Office of Civil Service Commission (OCSC).}
{'timestamp': '2020-08-19T02:09:37', 'yymm': '2005', 'arxiv_id': '2005.14381', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14381'}
arxiv
\section{Introduction} Miniaturization and advances in WiFi technologies have led to the emergence of Web-enabled devices. Interconnected devices are typically referred to as the \emph{Internet of Things (IoT)}. More formally, IoT represents the network of \emph{things} that exchange data, essentially enabling a wide variety of applications such as smart homes and smart cities \cite{gubbi2013internet}. A potential application is a crowdsourcing platform whereby IoT devices \emph{crowdsource} services for the benefit of other IoT devices. Crowdsourced services are generally defined as services provided by the crowd to the crowd \cite{brabham2008crowdsourcing}. In \emph{IoT service crowdsourcing}, IoT devices provision services to other nearby IoT devices. We refer to such services as \emph{crowdsourced IoT services}. IoT devices can crowdsource a wide range of service types such as \emph{computing services} \cite{habak2015femto}, \emph{green energy services} \cite{lakhdari2018crowdsourcing}, and \emph{WiFi hotspot services} \cite{Neiat2017caas}. For example, computing services involves IoT devices offering their computational resources (service providers) to other devices. IoT devices with limited computational capabilities (service consumers) may request and consume such services to perform complex tasks that may not be easily achieved otherwise. Crowdsourcing IoT services pose several trust-related challenges. For instance, let us assume a crowdsourcing environment where \emph{computing services} are provided by IoT devices \cite{habak2015femto}. In such an environment, IoT providers offer their computing resources (CPU, memory) to perform processing tasks for other IoT devices. A potential IoT service consumer may have concerns regarding the service's trust. For example, an untrustworthy service might not protect the privacy of the consumers' data or provide unreliable performance. Similarly, an IoT service provider may have concerns regarding their consumers' trustworthiness. Malicious consumers may misuse IoT services by sending malicious software. Such concerns can be alleviated by ascertaining the trustworthiness of both the service provider and service consumer. IoT environments, however, exhibit certain characteristics that make assessing trust rather challenging. One crucial challenge is the \emph{dynamic nature} of IoT environments. IoT devices are inherently expected to come and go and their existence may not be for long periods. For example, wearables like shirts and shoes have a limited lifespans as people tend to replace them frequently. Additionally, IoT devices can have different owners at any given time. For instance, an IoT shirt can be worn by different people (e.g., bothers). These dynamic characteristics may lead to unreliable historical records that might result in an inaccurate trust assessment. \begin{figure*} \centering \includegraphics[width=0.7\textwidth]{images/motivation_scenario.pdf} \caption{Crowdsourcing WiFi hotspots using IoT devices.} \label{fig:motivation_scenario} \end{figure*} Previous trust management frameworks relied mainly on historical data to evaluate the trustworthiness of service providers \cite{saied2013trust,chen2011trm}. IoT environments are highly dynamic; i.e., new devices are deployed and removed every day \cite{kyriazis2013smart}. New devices do not generally have prior interactions with other IoT devices. Service consumers, as a result, may not be able to assess the trustworthiness of services provided by new devices. Therefore, the majority of existing trust frameworks cannot be applied to such environments due to the lack of historical records. We introduce the concept of \emph{just-in-time memoryless trust} to overcome these challenges. The trustworthiness of the provider is evaluated \emph{without} relying on historical data (memoryless). We propose to leverage the characteristics of an active IoT service session to compute an accurate trust value for the service. As a result, the assessment would provide an accurate measure of a service's trustworthiness, given a specific service session (just-in-time). We propose a framework that assesses the trustworthiness of IoT services using service-session-related data. Our approach exploits existing IoT devices (bystanders) to assess the trustworthiness of IoT services in their vicinity. We achieve this by using a \emph{collaborative model} where users of the crowdsourcing platform are also expected to participate in assessing the trustworthiness of the services. In that respect, IoT devices that wish to consume IoT services are to contribute to the platform by evaluating IoT services for other consumers. It is worth noting that such a model is used in other popular applications, specifically in peer-to-peer applications, such as Skype and Window 10's Delivery Optimization. For example, Skype users contribute to the platform by acting as relay stations to forward calling packets for other Skype users. The rest of the paper is organized as follows. Section \ref{section:problem_definition} presents preliminaries and problem definition. Section \ref{section:framework} introduces our just-in-time memoryless trust management framework. Section \ref{section:experiments} discusses the experimental results. Section \ref{section:literature} surveys related work. Section \ref{section:conclusion} concludes the paper and highlights future work. \subsection*{Motivation Scenario} We use the following motivation scenario to illustrate the significance of our work (Fig. \ref{fig:motivation_scenario}). Assume a crowdsourcing environment where IoT devices are used to provide/consume services to/from other IoT devices. The provided services in this scenario are WiFi hotspots. In other words, an IoT service provider shares their device's Internet access using an application like WiFiMapper\footnote{https://www.wifimap.io}. Service providers $B$, $C$, and $D$ in Fig. \ref{fig:motivation_scenario} use their smartphones or smartwatches to share their Internet with other nearby IoT devices. Service consumer $A$ wishes to consume one of the available nearby services. Service consumer $A$ is presented with the potential service providers $B$, $C$, and $D$. The available providers are unknown to consumer $A$ and, therefore, consumer $A$ has no knowledge about their trustworthiness. Additionally, service providers $B$, $C$, and $D$ do not have historical records that reveal their previous behaviors. Consumer $A$, therefore, fails to ascertain the level of trust from such providers. Service provision/consumption, as a result, does not occur due to the absence of trust. We, therefore, propose a framework that assesses the trustworthiness of the providers \emph{despite the lack of historical records}. It is worth noting that trust management is not limited to WiFi hotspot services. Other IoT services require trust assurance prior to service consumption. For example, assume an IoT crowdsourcing environment, whereby IoT devices offer their computing resources (e.g., CPU and memory) to other less-capable IoT devices \cite{habak2015femto}. Suppose an IoT device owner $A$ wishes to use their smartphone to provision compute services to other nearby devices. Let us assume that provider $A$ has not provisioned any services before. Provider $A$, therefore, lacks historical data that can describe their performance. Assume a consumer $B$ who has some compute tasks to perform on their confidential data. Provider $A$ is a potential candidate to receive consumer $B$'s task. Consumer $B$, however, may not use the available computing service since provider $A$ is unknown to them. Additionally, Provider $A$ does not have any previous historical records that allow consumer $C$ to deduce a trust value for them. \begin{figure*} \centering \includegraphics[width=0.80\textwidth]{images/framework.pdf} \caption{The proposed framework.} \label{fig:framework} \end{figure*} \section{Preliminaries and Problem Definition} \label{section:problem_definition} We model a \emph{crowdsourced IoT service} $S$ provided and consumed by an \emph{IoT device} $d$ as a tuple of $<id, l, t, d, o, f, q>$ where, \begin{itemize} \item $id$ is a unique service ID. \item $l$ is a GPS location where the service $S$ is provided. \item $t$ is the time interval at which the service $S$ is provided. It is represented as a tuple $<t_s, t_e>$ , where \begin{itemize} \item $t_s$ is the start-time of $S$, \item $t_e$ is the end-time of $S$. \end{itemize} \item $d$ is the IoT device that offers the service $S$ (e.g., smartphone). \item $o$ is the owner of the IoT device. An owner can be an individual or any other cooperation or business (e.g., universities or restaurants). In this paper, we assume that a service provider is an owner of the IoT device (i.e., $sp = o$). \item $f$ is a set of functions offered by $S$ (e.g., providing WiFi hotspot). \item $q$ is a set of all non-functional parameters of $S$ (e.g., signal strength). \end{itemize} \label{section:framework} \subsection{Problem Definition} As stated earlier, IoT environments are highly dynamic. As a result, the majority of IoT services lack historical records, which are generally used to ascertain their trustworthiness. It is, therefore, crucial to consider other aspects of IoT services to establish their trustworthiness $\mathcal{T}$. The purpose of our work is to identify a function $\mathcal{F}$ that utilizes the properties of a service's environment $\mathcal{E}_S$ to assess its trust. In other words: \begin{equation} \mathcal{T} \approx \mathcal{F}(\mathcal{E}) \end{equation} \section{Just-in-Time Memoryless Trust Management Framework} We introduce a just-in-time memoryless trust management framework for assessing a service's trustworthiness without relying on historical records (see Fig. \ref{fig:framework}). The framework exploits the service session characteristics and its surrounding environment to infer the service's trustworthiness. The framework is divided into three phases: (1) IoT service initiation, (2) IoT service monitoring, and (3) trustworthiness assessment. During the IoT service initiation, an IoT service provider decides to offer their services to nearby devices. Nearby IoT devices monitor the performance of the service during the IoT service monitoring phase. A new consumer relies on existing IoT devices to build a just-in-time memoryless trust value for the potential service provider. \subsection{IoT Service Session Initiation} A service provider $S_p$ starts service provisioning by initiating a \emph{service session} $S_{sess}$. A service session is confined by a geographical area and time duration, e.g., a coffee place between 5:00pm and 7:00pm. Additionally, a service session includes the type of the service being provided, e.g., computing service, WiFi hotspots, etc. The service provider also broadcasts a \emph{promise vector} $\vv{P_S}$ to potential nearby IoT consumers. The promise vector describes the expected behavior of the IoT service. For example, in WiFi hotspot crowdsourcing, a service's trust can be evaluated based on the service's speed, security, and availability. A possible promise vector can be $[10mbps, Medium, 90\%]$. The vector indicates the service's expected speed is 10mbps, security is medium, and availability is 90\%. \subsection{Bystanders-Based Trust Assessment} A service session $S_{sess}$ is limited by space and time. IoT consumers cannot consume the service if they are not within the service session's area and period. For example, IoT consumers at a restaurant cannot consume services from a provider at a coffee shop. Similarly, an IoT service session running between 7:00pm and 8:00pm cannot be consumed between 9:00pm 10:00pm. Many IoT devices may exist within a service's area and periods other than IoT consumers. We refer to such devices as \emph{bystanders}. More formally, we define \emph{IoT service bystanders} as the non-consumer devices that exist within the vicinity of a service session $S_{sess}$ in terms of area and time. We leverage IoT service bystanders to assess the trustworthiness of a service $S$ during its session $S_{sess}$. A set of bystanders $B$ receive the promise vector $\vv{P_S}$ from the service provider $S_p$. Additionally, the bystanders assess the service's performance by invoking dummy tasks periodically. For instance, a bystander for a WiFi hotspot service can download a file using a particular service. Each bystander $b \in B$ generates an \emph{observation vector} $\vv{O_S^b}$ based on their task invocation. The observation vector contains information regarding the actual performance of the service at a specific time. For example, an observation vector $\vv{O_S} = [9mbps, Medium, 80\%]$ for a WiFi hotspot service indicates that the service has a speed of 9mbps, a medium security level, and 80\% availability. An \emph{instantaneous trust} $T_{inst}^b$ is computed by each bystander $b \in B$ using their observation vector $\vv{O_S^b}$ and the IoT service provider's promise vector $\vv{P_S}$. The instantaneous trust reflects the trustworthiness of a particular provider at a time instant from a bystander's perspective. A bystander $b \in B$ evaluates their instantaneous trust $T_{inst}^b$ using the following equation: \begin{equation} T_{inst}^b = \frac{1}{|\vv{P_S}|}\sum\limits_{i=0}^{|\vv{P_S}|-1} \min\left(1, \frac{\vv{O_S^b}(i)}{\vv{P_S}(i)}\right) \label{eq:t_inst} \end{equation} where $|\vv{P_S}|$ is the number of elements in the vector $\vv{P_S}$, and $\vv{O_S^b}(i)$ and $\vv{P_S}(i)$ are the $i^{th}$ elements in the vectors $\vv{O_S^b}$ and $\vv{P_S}$, respectively. The value of $T_{inst}^b$ ranges between zero and one, one being highly trusted. For example, assume a WiFi hotspot service provider with a promise vector $\vv{P_S} = [10mbps, Medium, 90\%]$, which represents a service with a speed of 10mbps, Medium security, and 90\% availability. In this example, the security level can either be Low, Medium, or High for simplicity. A representative numerical value can then be given to the security level when used in equation \ref{eq:t_inst} (0 = Low, 1 = Medium, and 2 = High). Additionally, assume a bystander that has an observation vector $\vv{O_S} = [9mbps, High, 80\%]$. The instantaneous trust $T_{inst}$ equals 0.93 after applying equation \ref{eq:t_inst}. \subsection{Consumer-Based Trust Assessment} An IoT service provider can offer and provision its services to more than one consumer. We exploit the set of existing consumers $C$ to assess their IoT provider's trust. Similar to IoT service bystanders, IoT consumers receive the provider's promise vector $\vv{P_S}$. Consumers monitor their providers while using the service. Unlike bystanders, consumers can offer a more accurate observation of the IoT service. Consumers perform their monitoring over \emph{periods} rather than single time instances. They, therefore, can capture the behavior of the IoT service over time more accurately and form a better representation for the service's trustworthiness. Each consumer $c \in C$ generates an observation vector $\vv{O_S^c}$. The observation vector is generated based on the consumer's experience while using the IoT service. The elements of the vector are similar to that of the bystanders' observation vectors; i.e., each represents one aspect of the service's performance. Each consumer $c \in C$ computes the \emph{accumulated trust} $T_{acc}^c$. We define the accumulated trust $T_{acc}^c$ as the trustworthiness of an IoT service from the perspective of the consumer $c \in C$ over their consumption period. Consumers keep updating their accumulated trust as they use the service. The updated accumulated trust utilizes earlier accumulated trust values to increase the accuracy of the service's trust over time. The consumer $c \in C$ evaluates the accumulated trust $T_{acc}^c$ using the following equation: \begin{equation} T_{acc}^c(t+1) = \alpha T_{acc}^c(t) + (1 - \alpha) T_{inst}^c \label{eq:t_acc} \end{equation} where $T_{acc}^c(t+1)$ is the updated accumulated trust, $T_{acc}^c(t)$ is the current accumulated trust, and $\alpha$ is a weighting factor from zero to one. The $T_{inst}^c$ is the instantaneous trust from consumer $c \in C$'s perspective. The value of $T_{inst}^c$ is computed using equation \ref{eq:t_inst}. \begin{figure*} \centering \begin{minipage}{.47\textwidth} \centering \includegraphics[width=0.90\linewidth]{images/results/instantaneous_and_accumulated_trust.pdf} \caption{Accuracy in detecting the instantaneous and accumulated trust by existing consumers and bystanders.} \label{fig:instantaneous_accumulated_trust} \end{minipage}% \hspace{0.5cm} \begin{minipage}{.47\textwidth} \centering \includegraphics[width=0.90\linewidth]{images/results/variable_bystanders_number.pdf} \caption{The effect of bystanders/consumers number on the accuracy of the overall trust.} \label{fig:bystanders_consumers_effect} \end{minipage} \end{figure*} \subsection{Overall IoT Service Trust Assessment} A new consumer relies on IoT service bystanders and existing consumers to evaluate an IoT service's trustworthiness. The accumulated and instantaneous trust values are sent to the new consumer. The new consumer aggregates the trust values to assess the overall trustworthiness of the service using the following equation: \begin{equation} \mathcal{T}_S = \frac{1}{|C| + |B|} \left(\sum\limits_{c \in C} T_{acc}^c + \sum\limits_{b \in B} T_{inst}^b\right) \label{eq:trust_basic} \end{equation} where $|C|$ is the number of existing consumers, and $|B|$ is the number of bystanders. Equation \ref{eq:trust_basic} assesses the trust by weighting instantaneous and accumulated trust values equally. The time at which the instantaneous trust is evaluated should be considered. A \emph{fresher} trust value reflects the service's trustworthiness more accurately. Additionally, the duration that is \emph{covered} by the accumulated trust is crucial. Higher weights should be given to accumulated trust values that cover longer periods. We, therefore, formulate the \emph{freshness} $F_{T_{inst}}$ of the instantaneous trust as follows: \begin{equation} F_{T_{inst}^b} = \frac{ts_b}{TS_B} \label{eq:freshness} \end{equation} where $ts_b$ is the timestamp at which the instantaneous trust $T_{inst}^b$ is evaluated, and $TS_B$ as the summation of all timestamps from all bystanders in $B$. The freshness value takes a value from zero to one, one indicating a newer trust value. For example, assume three bystanders $A$, $B$, and $C$, which computed the instantaneous trust at different time instances. The three bystanders recorded the timestamp of their observation vectors as an offset from the beginning of the service session. Assume the timestamps are as follows: 2, 8, 20 minutes for bystanders $A$, $B$, and $C$, respectively. The freshness scores for the three bystanders are 0.07, 0.27, 0.67 for bystanders $A$, $B$, and $C$, respectively, according to equation \ref{eq:freshness}. Bystander $C$ has the highest freshness scores since their computed trust is the newest among the three. Similarly, we evaluate the \emph{coverage} $G_{T_{acc}}$ of the accumulated trust as follows: \begin{equation} G_{T_{acc}^c} = \frac{d_c}{D_C} \label{eq:coverage} \end{equation} where $d_c$ is the duration that is covered by the accumulated trust, and $D_C$ is the summation of all durations covered by all the consumers in $C$. The value of the coverage can take a value between zero and one, where larger values indicate the accumulated trust covered longer periods. For instance, assume a service that is being consumed by three consumers $A$, $B$, and $C$. Each consumer used the service for different periods. Suppose that consumers $A$, $B$, and $C$ used the service for 45, 20, 5 minutes, respectively. The coverage is 0.64, 0.29, and 0.07 for consumers $A$, $B$, and $C$, respectively. Consumer $A$ is awarded the highest coverage since they used the service the longest. We use the freshness and coverage measures in equation \ref{eq:trust_basic} as follows: \begin{equation} \mathcal{T}_S = \beta \sum\limits_{c \in C} G_{T_{acc}^c} T_{acc}^c + (1 - \beta) \sum\limits_{b \in B} F_{T_{inst}^b} T_{inst}^b \label{eq:trust_freshness_coverage} \end{equation} where $\beta$ is a user-defined weighting factor between zero and one. In some scenarios, a bystander/consumer may report inaccurate or wrong trust assessments to the new consumer (e.g., biased or malicious bystander). We introduce the \emph{credibility} measure to overcome this issue. The basic intuition is that biased/malicious bystanders/consumers are special cases. In other words, the majority of consumers/bystanders behave as expected, while only a subset may produce invalid assessments. We, therefore, compare the trust assessments from different bystanders and consumers. The credibility of each bystander/consumer can then be inferred from such comparison. For example, assume, for simplicity, four bystanders with four instantaneous trust values: 0.9, 0.85, 1.0, and 0.1. The first three trust values are close to each other, while the last is significantly different. It can be deduced that the forth bystander may have invalid trust assessment since the majority produced different values. We, therefore, evaluate the credibility of a bystander/consumer $\mathcal{C}_{b|c}$ as follows: \begin{equation} \mathcal{C}_{b|c} = 1 - |T - T_{avg}| \label{eq:credibility} \end{equation} where $T$ is the instantaneous or the accumulated trust and $T_{avg}$ is the average of all trust values from bystanders and consumers. The credibility value takes a value between zero and one, one indicating high credibility. Using our earlier example, the credibilities for the four bystanders using equation \ref{eq:credibility} are 0.8125, 0.8625, 0.7125, and 0.3875. The first three bystanders got relatively high scores since they provide similar assessments. The fourth bystander is given the lowest since its trust assessment deviates from the majority. We use the credibility of the bystanders/consumers by applying equation \ref{eq:credibility} into equation \ref{eq:trust_freshness_coverage} as follows: \begin{equation} \mathcal{T}_S = \beta \sum\limits_{c \in C} \mathcal{C}_c G_{T_{acc}^c} T_{acc}^c + (1 - \beta) \sum\limits_{b \in B} \mathcal{C}_b F_{T_{inst}^b} T_{inst}^b \label{eq:trust} \end{equation} \begin{figure*} \centering \begin{minipage}{.47\textwidth} \centering \includegraphics[width=0.90\linewidth]{images/results/accuracy.pdf} \caption{Accuracy, Precision, and recall for the proposed framework.} \label{fig:experiment_accuracy} \end{minipage}% \hspace{0.5cm} \begin{minipage}{.47\textwidth} \centering \includegraphics[width=0.90\linewidth]{images/results/credibility_vs_no_credibility.pdf} \caption{The effect of credibility on the trust accuracy.} \label{fig:credibility_effect} \end{minipage} \end{figure*} \section{Experiments} \label{section:experiments} We evaluate the effectiveness of the framework in terms of accuracy. More specifically, we examine the accuracy of the just-in-time memoryless trust for IoT services. Additionally, we evaluate the accuracy of the instantaneous and accumulated trust discussed in Section \ref{section:framework}. We run the experiments on a 3.60GHz Intel(R) Core(TM) i7-7700 and 8 GB of RAM. \subsection{Dataset Description} Amazon Mechanical Turk\footnote{https://www.mturk.com/} (MTruk) is used to collect the dataset for our experiments. We divided MTurk workers into three categories: bystanders, existing consumers, and new consumers. Workers in all categories are asked to assume that they are at a public place, e.g., a restaurant, where other nearby users are sharing their Internet via WiFi hotspots using smartphones and smartwatches. In such an environment, potential consumers can use an application on their smartphones/smartwatches to get a list of nearby WiFi hotspots. Each provider in the application sets its expected performance, i.e., promise vector. Each worker is presented with a specific WiFi hotspot, with its promise vector. Workers in the bystanders' category are asked to assume that they are given some monetary rewards to monitor the performance of service providers. Monitoring is carried out by using the service at specific time instances and recording their actual performance, i.e., observation vector. The performance of the service at different timestamps is given to the workers. The workers are asked to rate the service based on the given performance. Existing consumes category consists of workers that are treated as current consumers for the presented service. Similar to bystanders category, workers in this category are presented with a list of performance records of the service, i.e., observation vector. Each performance record represents the performance of the service during a period rather than at timestamps. The workers are asked to rate the service based on the given performance. Workers in the new consumers' category are those who wish to compute the just-in-time memoryless trust. Each worker is presented with two lists of ratings. The first list represents the service's ratings from consumers who use it. The second list contains bystanders who monitor the service and report their ratings. The workers are asked to consider the ratings from both lists and give an expected rate for the service. All workers are asked to give their rating for the services as a value between zero to ten, ten being the highest. The data has been collected using the results from a total of 5000 workers for each category. \subsection{Experimental Results} We use \emph{precision}, \emph{recall}, and \emph{accuracy} \cite{Olson2008ADM1795943} to determine the efficiency of our work. We assume that trust can be at one of three levels: \emph{highly trusted}, \emph{moderately trusted}, and \emph{lowly trusted}. Given a trust level $l$, e.g., moderately trusted, \emph{precision} $l$ is defined as the ratio between the number of samples correctly detected as $l$ to the total number of samples detected as $l$: \begin{equation} \label{eq:precision} Precision_l =\frac{|correct_l|}{|detected_l|} \end{equation} \emph{Recall} for $l$ is the ratio between the correctly detected samples as $l$ to the total number of actual $l$ samples: \begin{equation} \label{eq:recall} Recall_l =\frac{|correct_l|}{|actual_l|} \end{equation} The \emph{accuracy} in detecting $l$ is the ratio between the number of correctly detected samples as $l$ and the number of correctly detected samples as not $l$ to the total samples number: \begin{equation} \label{eq:accuracy} Accuracy_l =\frac{|correct_l|+|correct\_not_l|}{|samples|} \end{equation} The first experiment set evaluates the overall accuracy of the whole framework, see Fig. \ref{fig:experiment_accuracy}. The framework achieves high accuracy, precision, and recall scores: 88.40\%, 82.78\%, and 82.54\%, respectively. The second experiment evaluates the credibility measure influence on the accuracy scores. Fig. \ref{fig:credibility_effect} shows the results for this experiment. The framework scores higher in terms of accuracy (around 88.40\%) when the credibility measure is used. The accuracy of the framework reduces significantly when the credibility of the bystander/consumer is not considered (around 59.03\%). Recall that the credibility measures the truthfulness of the trust values provided by the bystanders/consumers. The measure is used to weight the significance of the reported trust from the bystanders/consumers. The absence of the credibility results in treating all reported trust values equally. As a result, biased/malicious bystanders and consumers can greatly disrupt the accuracy of the assessed trust as evident in Fig. \ref{eq:credibility}. The overall trust value of the service is computed based on the instantaneous and accumulated trust. We evaluate the accuracy in assessing such trust values in the next experiment (see Fig. \ref{fig:instantaneous_accumulated_trust}. The accuracy in computing the instantaneous trust is around 85.04\%, whereas a higher accuracy is achieved when evaluating the accumulated trust; around 90.31\%. The accumulated trust has higher accuracy due to how it is computed. The instantaneous trust is computed from a single observation vector given a specific timestamp. However, computing the accumulated trust utilizes previously computed instantaneous trust values to get a more accurate assessment for the service. The last experiment studies the effect of the number of bystanders/consumers on the overall trust of the service. Fig. \ref{fig:bystanders_consumers_effect} shows the results for this experiment. The accuracy of the framework has significantly lower scores when a small number of bystanders and consumers is considered. For example, the accuracy is around 20\% when only one bystander or consumer is used. The accuracy increases exponentially as the number of bystanders and consumers increases. High accuracy scores are reached when six bystanders/consumers are considered (about 82\%). A lower number of bystanders/consumers might not represent the actual service trustworthiness accurately. For example, biased/malicious bystanders/consumers have a greater influence when the total number of bystanders/consumer is low. As a result, the computed trust value does not accurately represent the service's actual trustworthiness. \section{Related Work} \label{section:literature} Trust assessment in crowdsourced IoT service environment is fairly new. Most of the proposed approaches can be grouped into two main categories: \emph{previous experiences-based trust evaluation}, and \emph{social networks-based trust evaluation}. \subsection{Measuring Trust Using Previous Experiences} A centralized trust management system (TMS) is proposed to evaluate the trustworthiness of an IoT device based on its past behavior \cite{saied2013trust}. The TMS has four phases: information gathering, entity selection, transaction and evaluation, and learning. The information gathering phase involves collecting data about the executed services by the IoT device. In the entity selection phase, the TMS returns the most trustworthy IoT device for requested services. Performing the task by the IoT service provider happens at the transaction and evaluation phase. The requester gives a score to the provider based on the executed service outcome. In the learning phase, the TMS learns the credibility of the requesters to weight their scores. While TMS performed well according to the conducted experiments, their choice of a centralized solution may act as a bottleneck. A trust model is proposed for evaluating the trustworthiness and reputation of nodes in Wireless Sensor Networks (WSNs) \cite{chen2011trm}. The node's reputation is computed based on its performance characteristics: packet delivery, forwarding ratio, and energy consumption. The reputation is later used to evaluate the trustworthiness of the node. The proposed model uses WSN-specific characteristics (e.g., packet delivery which makes it unsuitable for other applications). Social IoT network is used to measure the trust between two IoT devices in \cite{nitti2012subjective}. A social IoT network is a type of social networks where nodes are IoT devices. Relationships between IoT devices indicate one or more of the following relations: similar owner, co-location, co-work, social relation, or brand. Each node computes the trust of its friends. The trust is measured based on the individual's and friends' previous experiences. A trust model is also proposed in \cite{wang2016toward} that uses social IoT to manage the interactions between IoT service consumers and providers. The social IoT network is used to search for candidate service providers. Reputation-based trustworthiness is used to evaluate the service providers using previous interactions. A trust management protocol is proposed in \cite{bao2012dynamic} \cite{bao2012trust} to assess the trustworthiness of IoT devices based on honesty, cooperativeness, and community-interest. Honesty is measured using the direct observation of an IoT device (high recommendation discrepancy, delays, etc.). Cooperativeness and community-interest are computed using data from social networks. Common friends between two IoT owners indicate high cooperativeness between their IoT devices. Community-interest depends on the common communities number between two IoT owners. A framework is proposed for crowdsourcing services to IoT devices based on their mobility and trustworthiness \cite{kantarci2014mobility}. A central authority exists to manage interactions between the consumer and provider. The trustworthiness of a service provider is computed based on their reputation. Basically, when the central authority receives a task request from the consumer, the task is submitted to multiple service providers. The server then computes the anomalies among the results from the service providers. Service providers with deviated results are marked and their reputation is decreased. Aforementioned approaches use historical data (i.e., previous experiences) to asses the trust. On the other hand, one key characteristic of crowdsourced IoT service environments is their high dynamism in terms of IoT devices deployment. Every day a large number of IoT services are being added. Newly added services do not have previous records. If those previous experiences are missing, the evaluated trust cannot be accurate. Therefore, these approaches cannot be utilized to accurately measure IoT services' trust. \subsection{Measuring Trust Using Social Networks} A social compute cloud framework is proposed in \cite{Caton2014} where users in a social network can share and consume services from other users. The framework leverages the social structure of the network. Relation types between users (e.g., family, colleagues, etc.) are also utilized to determine the level of trust between them. A framework is proposed in \cite{Cao2015} that aims at eliminating the privacy risks accompanied with public WiFi hotspots. Social WiFi utilizes social networks relationships to match hotspot users to trusted hotspot providers. The proposed framework lacks generality as it can only be used for WiFi hotspot services. An approach for evaluating the trust between users in social networks is presented in \cite{adali2010measuring}. Behavioral interactions are used to indicate the level of trust (i.e., conversations between users and message propagation). A conversation between two users can indicate a higher level of trust if: (1) it happens many times, (2) it lasts for a long duration, and (3) there is a balanced contribution of messages from both users. The message propagation indicates the willingness of a user $B$ to forward a message received by another user $A$. A large number of forwarded messages reflect a higher trust value for the sender. The above work focuses on social networks' relationships which is not sufficient to evaluate the trust between the IoT service provider and consumer. For example, two friends on a social network do not necessitate mutual trust between them \cite{sherchan2013survey}. \section{Conclusion} \label{section:conclusion} We presented just-in-time memoryless trust, a trust evaluation specifically suited for IoT services. The just-in-time memoryless trust accounts for the high dynamism exhibited in IoT environments. Such a dynamic nature causes the lack of \emph{historical records}, a crucial cornerstone for computing the trustworthiness in the majority of existing trust management frameworks. A novel framework was proposed to measure IoT services' trustworthiness \emph{without} relying on previous historical data. The framework exploits session-related data to assess the trustworthiness of IoT services. More specifically, we leverage the experience of IoT bystanders and consumers to build an accurate trust value for a given IoT service. The proposed framework achieved high accuracy scores in our experiments. Future directions can be investigating the trustworthiness of the IoT service consumer. \bibliographystyle{IEEEtran}
{'timestamp': '2020-06-01T02:07:24', 'yymm': '2005', 'arxiv_id': '2005.14413', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14413'}
arxiv
\subsection{Model-Free Policy Search} In model-free policy search, sampled trajectories are used directly to update the policy parameters. The discussion will follow the three main steps followed by the algorithms: % (i) how they {\em explore} the space of policies, % (ii) how they {\em evaluate} policies, and % (iii) how policies are {\em updated}. \subsubsection{Policy Exploration} Exploring the space of policies implies either sampling the parameter vector the policy depends on, or perturbing the action choice of the policy. Often, the sampling of parameters takes place at the beginning of each episode (in episodic scenarios), and action perturbations are different at each time step, but other options are possible. Stochastic policies can be seen as naturally performing a step-based exploration in action space. Otherwise, the exploration strategy can be modeled as an {\em upper-level policy} $\pi_{\omega}(\theta)$---sampling $\theta$ according to a probability distribution governed by parameter vector $\omega$---, while the actual policy $\pi_{\theta}(a|s)$ is refered to as a {\em \PW{lower}-level policy}. In this setting, the policy search aims at finding the parameter vector $\omega$ that maximizes the expected return given this vector. If $\pi_{\omega}(\theta)$ is a Gaussian distribution (common in robotics), then its covariance matrix can be diagonal---typically in step-based exploration---or not---which leads to more stability, but requires more samples---, meaning that the various parameters in $\theta$ can be treated in a correlated manner or not. \subsubsection{Policy Evaluation} Policy evaluation can also be step-based or episode-based. Step-based approaches evaluate each state-action pair. They have low variance and allow crediting several parameter vectors. They can rely on $Q$-value estimates, which can be biased and prone to approximation errors, or Monte-Carlo estimates, which can suffer from high variance. Episode-based approaches evaluate parameters using complete trajectories. They allow more performance criteria than step-based approaches---\textit{e.g.}, minimizing the final distance to the target. They also allow for more sophisticated exploration strategies, but suffer all the more from noisy estimates and high variance that the dynamics are more stochastic. \subsubsection{Policy Update} Finally, the policy can be updated in rather different manners. We will discuss approaches relying on gradient ascents, inference-based optimization, information-theoretic ideas, stochastic optimization and path-integral optimal control. {\bf Policy Gradient} (PG) algorithms first require estimating the gradient. Some (episode-based) PG algorithms perform this estimate using a finite difference (FD) method by perturbing the parameter vector. Other algorithms instead exploit the {\em Likelihood ratio} trick, which allows estimating the gradient from a single trajectory, but requires a stochastic policy. These can be step-based as REINFORCE \cite{Williams-ml92} or G(PO)MDP \cite{BaxBar-jmlr01,BaxBarWea-jmlr01}, or episode-based as PEPG \cite{SehEtAl-nn10}. Policy gradients also include natural gradient algorithms (NPG), i.e., algorithms that try to limit the distance between distributions $P_{\theta}(h)$ and $P_{\theta+\delta\theta}(h)$ using the KL divergence (estimated through the Fisher information matrix (FIM)). In step-based NPGs \cite{BagSch-ijcai03,PetSch-nn08}, using appropriate (``{\em compatible}'') function approximation removes the need to estimate the FIM, but requires estimating the value function, which can be difficult. On the contrary, episodic Natural Actor-Critic (eNAC) \cite{PetSch-nc08} uses complete episodes, and thus only estimates $v(s_1)$. NAC \cite{PetSch-nn08} addresses infinite horizon problems, the lack of episodes leading to the use of Temporal Difference methods to estimate values. Policy gradient usually applies to randomized policies. Recent work \cite{SilverLeverHeessDegrisWierstraRiedmiller14,LillicrapHuntPritzelHeessErezTassaSilverWierstra16} has adapted it to deterministic policies with a continuous action space, which can potentially facilitate the gradient estimation. Building on DQN, actor-critic methods have been extended to asynchronous updates with parallel actors and neural networks as approximators \cite{MnihBadiaMirzaGravesLillicrapHarleySilverKavukcuoglu16}. {\bf Inference-based algorithms} avoid the need to set learning rates. They consider that (i) the return $R$ is an observed binary variable ($1$ meaning success),\footnote{Transformations can bring us in this setting.} (ii) the trajectory $h$ is a latent variable, and (iii) one looks for the parameter vector that maximizes the probability of getting a return of $1$. Then, an Expectation-Maximization algorithm can address this Bayesian inference problem. Variational inference can be used in the E-step of EM \cite{Neumann-icml11}, but most approaches rely on Monte-Carlo estimates instead, despite the fact that they perform maximum likelihood estimates over several modes of the reward function (and thus do not distinguish them). These can be episode-based algorithms as RWR \cite{PetSch-esann07} (uses a linear upper-level policy) or CrKR \cite{KobOztPet-rss10} (a kernelized version of RWR, i.e., which does not need to specify feature vectors, but cannot model correlations). These can also be step-based algorithms as PoWER \cite{KobPet-ml10}, which allows a more structured exploration strategy, and gives more influence to data points with less variance. {\bf Information-theoretic} approaches (see Chapter 2 of Volume 3) try to limit changes in trajectory distributions between two consecutive time steps, which could correspond to degradations rather than improvements in the policy. Natural PGs have the same objective, but need a user-defined learning rate. % Instead, REPS \cite{PetMueAlt-aaai10} combines advantages from NPG (smooth learning) and EM-based algorithms (no learning-rate). % Episode-based REPS \cite{DanNeuPet-aistats12} learns a higher-level policy while bounding parameter changes by solving a constrained optimization problem. % Variants are able to adapt to multiple contexts or learn multiple solutions. % Step-based REPS \cite{PetMueAlt-aaai10} solves an infinite horizon problem (rather than an episodic one), optimizing the average reward per time step. % It requires enforcing the stationarity of state features, and thus solving another constrained optimization problem. A related recent method, TRPO \cite{SchulmanLevineAbbeelJordanMoritz15}, which notably constrains the changes of $\pi(\cdot \,|\, s)$ instead of those of state-action distributions, proves to work well in practice. {\bf Stochastic Optimization} relies on black-box optimizers, and thus can easily be used for episode-based formulations, i.e., working with an upper-level policy $\pi_{\omega}(\theta)$. % Typical examples are CEM \cite{BoeKroManRub-aor05,SziLor-nc05}, CMA-ES \cite{HanMulKou-ec03,HeiIge-joa09}, and NES \cite{WierstraSchaulGlasmachersSunPetersSchmidhuber14}, three evolutionary algorithms that maintain a parametric probability distribution (often Gaussian) $\pi_{\omega}(\theta)$ over the parameter vector. % They sample a population of candidates, evaluate them, and use the best ones (weighted) to update the distribution. % Many rollouts may be required for evaluation, as examplified with the game of Tetris \cite{SziLor-nc05}. {\bf Path Integral} (PI) approaches were introduced for optimal control, i.e., to handle non-linear continuous-time systems. They handle squared control costs and arbitrary state-dependent rewards. % {\em Policy Improvement with PIs} (PI$^2$) applies PI theory to optimize Dynamic Movement Primitives (DMPs), i.e., representations of movements with parameterized differential equations, using Monte-Carlo rollouts instead of dynamic programming. \subsection{Model-Based Policy Search} Typical model-based policy-search approaches repeatedly % (i) sample real-world trajectories using a fixed policy; % (ii) learn a forward model of the dynamics based on these samples (and previous ones); % (iii) optimize this policy using the learned model (generally as a simulator). As can be noted, this process does not explicitly handle the exploration-exploitation trade-off as policies are not chosen so as to improve the model where this could be appropriate. We now discuss three important dimensions of these approaches: how to learn the model, how to make reliable long-term predictions, and how to perform the policy updates. Model learning often uses probabilistic models. They first allow accounting for uncertainty due to sparse data (at least in some areas) or an inappropriate model class. In robotics, where action and state spaces are continuous, non-parametric probabilistic methods can be used such as Linearly Weighted Bayesian Regression (LWBR) of Gaussian Processes (GPs), which may suffer from increasing time and memory requirements. But probabilistic models can also be employed to represent stochastic dynamics. An example is that of propositional problems, which are often modeled as Factored MDPs \cite{BouDeaGol-ijcai95}, where the dynamics and rewards are DBNs whose structure is {\em a priori} unknown. A variety of approaches have been proposed, which rely on different representations (such as rule sets, decision trees, Stochastic STRIPS, or PPDDL) \cite{DegSigWui-icml06,PasZetKae-jair07,WalSziDiuLit-uai09,LesZan-ewrl11}. See Chapter 10 of Volume 2. Long-term predictions are usually required to optimize the policy given the current forward model. While the real world is its own best (unbiased) model, using a learned model has the benefit of allowing to control these predictions. A first approach, similar to paired statistical tests, is to always use the same random initial states and the same sequences of random numbers when evaluating different policies. It has been introduced for policy-search in the PEGASUS framework \cite{NgJor-uai00} and drastically reduces the sampling variance. Another approach is, when feasible, to compute a probability distribution over trajectories using deterministic approximations such as linearization \cite{AndMoo-of05}, sigma-point methods (e.g., \citep{JulUhl-ieee04}) or moment-matching. Policy updates can rely % on gradient-free optimization (e.g., Nelder-Mead method or hill-climbing) \citep{BagSch-icra01}, % on sampling-based gradients (e.g., finite difference methods), as in model-free approaches, although they require many samples, % or on analytical gradients \citep{DeiRas-icml11}, which require the model as well as the policy to be differentiable, scale favorably with the number of parameters, but are computationally involved. \section{Introduction} Reinforcement learning (RL) is a general framework for building autonomous agents (physical or virtual), which are systems that make decisions without human supervision in order to perform a given task. Examples of such systems abound: expert backgammon player \cite{Tesauro95}, dialogue systems \cite{SinghKearnsLitmanWalker99}, acrobatic helicopter flight \cite{AbbeelCoatesNg10}, human-level video game player \cite{MnihKavukcuogluSilverRusuVenessBellemareGravesRiedmillerFidjelandOstrovskiPetersenBeattieSadikAntonoglouKingKumaranWierstraLeggHassabis15}, go player \cite{SilverHuangMaddisonGuezSifreDriesscheSchrittwieserAntonoglouPanneerschelvamLanctotDielemanGreweNhamKalchbrennerSutskeverLillicrapLeachKavukcuogluGraepelHassabis16} or autonomous driver \cite{BojarskiTestaDworakowskiFirnerFleppGoyalJackelMonfortMullerZhangZhangZhao16}. See also Chapter 11 of Volume 2 and Chapters 10 and 12 of Volume 3. In all those examples, an agent faces a sequential decision-making problem, which can be represented as an interaction loop between an agent and an environment. After observing its current situation, the agent selects an action to perform. As a result, the environment changes its state and provides a numeric reward feedback about the chosen action. In RL, the agent needs to learn how to choose good actions based on its observations and the reward feedback, without necessarily knowing the dynamics of the environment. In this chapter, we focus on the basic setting of RL that assumes a single learning agent with full observability. Some work has investigated the partial observability case (see \cite{Spaan12} for an overview of both the model-based and model-free approaches). The basic setting has also been extended to situations where several agents interact and learn simultaneously (see \cite{BusoniuBabuskaDeSchutter10} for a survey). RL has also been tackled with Bayesian inference techniques, which we do not mention here for space reasons (see \cite{GhavamzadehMannorPineauTamar15} for a survey). In Section~\ref{sec:basics}, we recall the Markov decision process model on which RL is formulated and the RL framework, along with some of their classic solution algorithms. We present two families of approaches that can tackle large-sized problems for which function approximation is usually required. The first, which is value-based, is presented in Section~\ref{sec:approx}. It consists in estimating the value function of an optimal policy. The second, called policy search, is presented in Section~\ref{sec:policysearch}. It searches for an optimal policy directly in a policy space. In Section~\ref{sec:extension}, we present some extensions of the standard RL setting, namely extensions to the case of unknown rewards and risk-sensitive RL approaches. Finally, we conclude in Section~\ref{sec:conclusion}. \section{Background for RL} \label{sec:basics} Before presenting the RL framework, we recall the Markov decision process (MDP) model, on which RL is based. See also Chapter 17 of this volume and Chapter 10 of Volume 2. {\em Markov decision process.} MDPs and their multiple variants (e.g., Partially Observable MDP or POMDP) \cite{Puterman94} have been proposed to represent and solve sequential decision-making problems under uncertainty. An MDP is defined as a tuple $\mathcal M = \langle \mathbf{S}, \mathbf{A}, T, R, \gamma, H\rangle$ where $\mathbf{S}$ is a set of states, $\mathbf{A}$ is a set of actions, transition function $T(s, a, s')$ specifies the probability of reaching state $s'$ after performing action $a$ in state $s$, reward function $R(s, a) \in \mathbb R$ yields the immediate reward after performing action $a$ in state $s$, $\gamma \in [0, 1]$ is a discount factor and $H \in \mathbb{N} \cup \{\infty\}$ is the horizon of the problem, which is the number of decisions to be made. An immediate reward, which is a scalar number, measures the value of performing an action in a state. In some problems, it can be randomly generated. In that case, $R(s, a)$ is simply the expectation of the random rewards. In this MDP formulation, the environment is assumed to be stationary. Using such an MDP model, a system designer needs to define the tuple $\mathcal M$ such that an optimal policy performs the task s/he wants. Solving an MDP (i.e., {\em planning}) amounts to finding a controller, called a {\em policy}, which specifies which action to take in every state of the environment in order to maximize the expected discounted sum of rewards (standard decision criterion). A policy $\pi$ can be deterministic (i.e., $\pi(s) \in A$) or randomized (i.e., $\pi(\cdot \,|\, s)$ is a probability distribution over $\mathbf{A}$). It can also be stationary or time-dependent, which is useful in finite-horizon or non-stationary problems. A $t$-step history (also called trajectory, rollout or path) $h = (s_1, a_1, s_2, \ldots, s_{t+1}) \in (\mathbf{S}\times\mathbf{A})^t \times \mathbf{S}$ is a sequence of past states and actions. In the standard case, it is valued by its return defined as $\sum_t \gamma^{t-1}R(s_t, a_t)$. As a policy induces a probability distribution over histories, the {\em value function} $v^\pi : \mathbf{S} \to \mathbb{R}$ of a policy $\pi$ is defined by: \begin{align*} v^\pi_H(s) = \mathbb{E}_{\pi}\big[ \sum_{t=1}^H \gamma^{t-1}R(S_t, A_t) \,|\, S_1 = s \big], \end{align*} where $\mathbb{E}_{\pi}$ is the expectation with respect to the distribution induced by $\pi$ in the MDP, and $S_t$ and $A_t$ are random variables respectively representing a state and an action at a time step $t$. We will drop subscript $H$ if there is no risk of confusion. The value function can be computed recursively. For deterministic policy $\pi$, we have: \begin{align*} v^\pi_0(s) & = 0,\\ v^\pi_t(s) & = R(s, \pi(s)) + \gamma \sum_{s'\in\mathbf{S}} T(s, \pi(s), s') v^\pi_{t-1}(s'). \end{align*} In a given state, policies can be compared via their value functions. Interestingly, in standard MDPs, there always exists an optimal deterministic policy whose value function is maximum in every state. Its value function is said to be optimal. In the infinite horizon case, when $\gamma<1$, $v^\pi_t$ is guaranteed to converge to $v^\pi$, which is the solution of the {\em Bellman evaluation equations}: \begin{align} v^\pi(s) & = R(s, \pi(s)) + \gamma \sum_{s'\in\mathbf{S}} T(s, \pi(s), s') v^\pi(s'). \label{eq:bellmanevaluation} \end{align} Given $v^\pi$, a better policy can be obtained with the following improvement step: \begin{align} \pi'(s) = \operatorname*{argmax}_{a \in \mathbf{A}} R(s, a) + \gamma \sum_{s'\in\mathbf{S}} T(s, a, s') v^\pi(s'). \label{eq:improvement} \end{align} The policy iteration algorithm consists in alternating between a policy evaluation step (\ref{eq:bellmanevaluation}) and a policy improvement step (\ref{eq:improvement}), which converges to the optimal value function $v^* : \mathbf{S} \to \mathbb R$. Alternatively, the optimal value function $v^*_H : \mathbf{S} \to \mathbb{R}$ can also be iteratively computed for any horizon $H$ by: \begin{align} v^*_0(s) & = 0 \nonumber\\ v^*_t(s) & = \max_{a \in \mathbf{A}}R(s, a) + \gamma \sum_{s'\in\mathbf{S}} T(s, a, s') v^*_{t-1}(s'). \label{eq:vi} \end{align} In the infinite horizon case, when $\gamma<1$, $v^*_t$ is guaranteed to converge to $v^*$, which is the solution of the {\em Bellman optimality equations}: \begin{align} v^*(s) & = \max_{a \in \mathbf{A}}R(s, a) + \gamma \sum_{s'\in\mathbf{S}} T(s, a, s') v^*(s'). \label{eq:bellmanoptimality} \end{align} In that case, (\ref{eq:vi}) leads to the value iteration algorithm. Two other related functions are useful when solving an RL problem: the action-value function $Q^\pi_t(s, a)$ (resp. the optimal action-value function $Q^*_t(s, a)$) specifies the value of choosing an action $a$ in a state $s$ at time step $t$ and assuming policy $\pi$ (resp. an optimal policy) is applied thereafter, i.e., \begin{align*} Q^x_t(s, a) = R(s, a) + \gamma \sum_{s'\in\mathbf{S}} T(s, a, s') v^x_{t-1}(s') \quad \mbox{ where } x \in \{\pi, *\}. \end{align*} {\em Reinforcement learning.} In the MDP framework, a complete model of the environment is assumed to be known (via the transition function) and the task to be performed is completely described (via the reward function). The RL setting has been proposed to tackle situations when those assumptions do not hold. An RL agent searches for (i.e., during the {\em learning phase}) a best policy while interacting with the unknown environment by trial and error. In RL, the standard decision criterion used to compare policies is the same as in the MDP setting. Although the reward function is supposed to be unknown, the system designer has to specify it. In RL, value and action-value functions have to be estimated. For $v^\pi$ of a given policy $\pi$, this can be done with the standard TD(0) evaluation algorithm, where the following update is performed after applying $\pi$ in state $s$ yielding reward $r$ and moving to new state $s'$: \begin{align} v^\pi_t(s) = v^\pi_{t-1}(s) - \alpha_t(s) \left( v^\pi_{t-1}(s) - \left(r + v^\pi_{t-1}(s')\right)\right),\label{eq:td update rule} \end{align} where $\alpha_t(s) \in [0, 1]$ is a learning rate. For $Q^\pi$, the update is as follows, after the agent executed action $a$ in state $s$, received $r$, moved to new state $s'$ and executed action $a'$ (chosen by $\pi$): \begin{align} Q^\pi_t(s, a) = Q^\pi_{t-1}(s, a) - \alpha_t(s, a) \big( Q^\pi_{t-1}(s, a) - \big(r + \gamma Q^\pi_{t-1}(s', a')\big) \big),\label{eq:sarsa update rule} \end{align} where $\alpha_t(s, a) \in [0, 1]$ is a learning rate. This update leads to the SARSA algorithm (named after the variables $s, a, r, s', a'$). In the same way that the policy iteration algorithm alternates between an evaluation step and a policy improvement step, one can use the SARSA evaluation method and combine it with a policy improvement step. In practice, we do not wait for the SARSA evaluation update rule to converge to the actual value of the current policy to make a policy improvement step. We rather continuously behave according to the current estimate of the $Q$-function to generate a new transition. One common choice is to use the current estimate in a softmax (Boltzmann) function of temperature $\tau$ and behave according to a randomized policy: \[\pi_t(a \,|\,s)=\frac{e^{Q_{\theta_t}(s, a)/\tau}}{\sum_b e^{Q_{\theta_t}(s, b)/\tau}}.\] Notice that we chose to use the Bellman evaluation equations to estimate the targets. However we could also use the Bellman optimality equations in the case of the $Q$-function and replace $r + \gamma Q(s', a')$ by $r + \max_b Q(s',b)$. Yet this only holds if we compute the value $Q^*$ of the optimal policy $\pi^*$. This gives rise to the $Q$-learning update rule, which directly computes the value of the optimal policy. It is called an {\em off-policy} algorithm (whereas SARSA is {\em on-policy}) because it computes the value function of another policy than the one that selects the actions and generates the transitions used for the update. The following update is performed after the agent executed action $a$ (e.g., chosen according to the softmax rule) in state $s$, received $r$ and moved to new state $s'$: \begin{align} Q^*_t(s, a) = Q^*_{t-1}(s, a) - \alpha_t(s, a) \big( Q^*_{t-1}(s, a) - (r + \gamma \max_{a'} Q^*_{t-1}(s', a')) \big) .\label{eq:qlearning update rule} \end{align} Updates (\ref{eq:td update rule}), (\ref{eq:sarsa update rule}) and (\ref{eq:qlearning update rule}) can be proved to converge if the learning rates satisfy standard stochastic approximation conditions (i.e., $\sum_t \alpha_t = \infty$ and $\sum_t \alpha_t^2 < \infty$). Besides, for (\ref{eq:sarsa update rule}), temperature $\tau$ would also need to converge to $0$ while ensuring sufficient exploration in order for SARSA to converge to the optimal Q-function. In practice, $\alpha_t(s, a)$ is often chosen constant, which would also account for the case where the environment is non-stationary. Those two general framework (MDP and RL) have been successfully applied in many different domains. For instance, MDPs or their variants have been used in finance \cite{BauerleRieder11} or logistics \cite{ZhaoChenLeungLai10}. RL has been applied to soccer \cite{BaiWuChen13} or power systems \cite{YuZhang13}, to cite a few. To tackle real-life large-sized problems, MDP and RL have to be completed with other techniques, such as compact representations \cite{BoutilierDeardenGoldszmidt00,GuestrinHauskrechtKveton04,Otterlo09} or function approximation \cite{de-FariasVan-Roy03,GeistPietquin11,MnihKavukcuogluSilverRusuVenessBellemareGravesRiedmillerFidjelandOstrovskiPetersenBeattieSadikAntonoglouKingKumaranWierstraLeggHassabis15}. \section{Value-Based Methods with Function Approximation}\label{sec:approx} In many cases, the state-action space is too large so as to be able to represent exactly the value functions $v^\pi$ or the action-value function $Q^\pi$ of a policy $\pi$. For this reason, function approximation for RL has been studied for a long time, starting with the seminal work of~\citet{BellmanPoly}. In this framework, the functions are parameterized by a vector of $d$ parameters $\bm\theta=[\theta_j]_{j=1}^{d}$, with $\bm\theta \in \Theta \subset \mathbb{R}^d$ (we will always consider column vectors) and the algorithms will aim at learning the parameters from data provided in the shape of transitions $\{s_t, a_t, s'_t, r_t\}_{t=1}^N$ where $s'_t$ is the successor state of $s_t$ drawn from $T(s_t, a_t, \cdot)$. We will denote the parameterized versions of the functions as $v_{\bm\theta}$ and $Q_{\bm\theta}$. Popular approximation schemes are linear function approximation and neural networks. The former gave birth to a large literature in the theoretical domain as it allows studying convergence rates and bounds (although it remains non-trivial). The latter, although already used in the 90's~\cite{Tesauro95}, has known a recent growth in interest following the Deep Learning successes in supervised learning. The case of neural networks will be addressed in Section~\ref{sec:deep} but we will start with linear function approximation. In this particular case, a set of basis functions $\bm\phi(\cdot) = [\phi_j(\cdot)]_{j=1}^{d}$ has to be defined by the practitioner (or maybe learned through unsupervised learning) so that the value functions can be approximated by: $$v_{\bm\theta}(s) = \sum_j \theta_j \phi_j(s) = \bm\theta^\intercal \bm\phi(s) \quad \text{ or } \quad Q_{\bm\theta}(s, a) = \sum_j \theta_j \phi_j(s, a) = \bm\theta^\intercal \bm\phi(s, a).$$ The vector space defined by the span of $\bm\phi$ is denoted $\Phi$. Notice that the exact case in which the different values of the value functions can be stored in a table (tabular case) is a particular case of linear function approximation. Indeed, if we consider that the state space is finite and small $\left( s =\{s_k\}_{k=1}^{|\mathbf{S}|} \in \mathbf{S} \right)$, then the value function can be represented in a table of $|\mathbf{S}|$ values $\{v_k \,|\, v_k = v(s_k)\}_{k=1}^{|\mathbf{S}|}$ where $|\mathbf{S}|$ is the number of states. This is equivalent to defining a vector of $|\mathbf{S}|$ parameters $\bm{v}=[v_k]_{k=1}^{|\mathbf{S}|}$ and a vector of $|\mathbf{S}|$ basis functions $\bm\delta(s)=[\delta_k(s)]_{k=1}^{|\mathbf{S}|}$ where $\delta_k(s)=1$ if $s = s_k$ and $0$ otherwise. The value function can thus be written $v(s)=\sum_k v_k \delta_k(s) = \bmv^\intercal \bm\delta(s)$. \subsection{Stochastic Gradient Descent Methods} \subsubsection{Bootstrapped Methods}\label{sec:bootstrap} If one wanted to cast the Reinforcement Learning problem into a supervised learning problem (see Chapter 11 of this Volume and Chapter 12 of Volume 2), one could want to fit the parameters to the value function directly. For instance, to evaluate the value of a particular policy $\pi$, one would solve the following regression problem (for some $\ell_p$-norm and distribution $\mu$ over states): $$\bm\theta^* = \operatorname*{argmin}_{\bm\theta} \|v^\pi_{\bm\theta} - \varv^\pi \|_{p, \mu} = \operatorname*{argmin}_{\bm\theta} \|v^\pi_{\bm\theta} - \varv^\pi \|_{p, \mu}^p$$ where $\|\cdot\|_{p, \mu}$ \PW{denotes the weighted $\ell_p$-norm defined by $ \big(\mathbb{E}_\mu |\cdot|^p\big)^{1/p}$}, $\mathbb{E}_\mu$ is the expectation with respect to $\mu$\PW{} Yet, as said before, we usually cannot compute these values everywhere and we usually only have access to some transition samples $\{s_t, a_t, s'_t, r_t\}_{t=1}^N$ generated according to distribution $\mu$. So we could imagine casting the RL problem into the following minimization problem: $$\bm\theta^* = \operatorname*{argmin}_{\bm\theta} \frac{1}{N} \sum_{t=1}^N \PW{|v_{\bm\theta}^\pi(s_t) - \varv^\pi(s_t) |^p}.$$ This cost function can be minimized by stochastic gradient descent (we will consider an $\ell_ 2$-norm): \begin{align*} \bm\theta_t &= \bm\theta_{t-1} - \frac{\alpha}{2} \nabla_{\bm\theta_{t-1}} \PW{\big(v_{\bm\theta_{t-1}}^\pi(s_t) - \varv^\pi(s_t)\big)^2} \\ & = \bm\theta_{t-1} - \alpha \nabla_{\bm\theta_{t-1}} v_{\bm\theta_{t-1}}^\pi(s_t) \left(v_{\bm\theta_{t-1}}^\pi(s_t) - \varv^\pi(s_t) \right). \end{align*} Of course, it is not possible to apply this update rule as it is since we do not know the actual value $\varv^\pi(s_t)$ of the states we observe in the transitions. But, from the Bellman evaluation equations (\ref{eq:bellmanevaluation}), we can obtain an estimate by replacing $\varv^\pi(s_t)$ by $r_t + \gamma v^\pi_{\bm\theta_{t-1}}(s_{t+1})$. Notice that this replacement uses bootstrapping as we use the current estimate of the target to compute the gradient. We finally obtain the following update rule for evaluating the current policy $\pi$: $$\bm\theta_t = \bm\theta_{t-1} - \alpha \nabla_{\bm\theta_{t-1}} v_{\bm\theta_{t-1}}^\pi(s_t) \left(v_{\bm\theta_{t-1}}^\pi(s_t) - \left(r_t + \gamma v^\pi_{\bm\theta_{t-1}}(s'_{t})\right)\right).$$ In the case of linear function approximation, i.e., $v^\pi_{\bm\theta}(s) = \bm\theta^\intercal \bm\phi(s)$, we obtain: $$\bm\theta_t = \bm\theta_{t-1} - \alpha \bm\phi(s_t) \left(\bm\theta_{t-1}^\intercal \bm\phi(s_t) - \left(r_t + \gamma \bm\theta_{t-1}^\intercal \bm\phi(s'_{t})\right)\right).$$ Everything can be written again in the case of the action-value function, which leads to the SARSA update rule with linear function approximation $Q^\pi_{\bm\theta}(s, a) = \bm\theta^\intercal \bm\phi(s, a)$: $$\bm\theta_t = \bm\theta_{t-1} - \alpha \bm\phi(s_t, a_t) \left( \bm\theta_{t-1}^\intercal \bm\phi(s_t, a_t) - \left(r_t + \gamma \bm\theta_{t-1}^\intercal \bm\phi(s'_{t}, a'_{t})\right)\right).$$ Changing the target as in the Q-learning update, we obtain for $Q^*_{\bm\theta}(s, a) = \bm\theta^\intercal \bm\phi(s, a)$: $$\bm\theta_t = \bm\theta_{t-1} - \alpha \bm\phi(s_t, a_t) \left( \bm\theta_{t-1}^\intercal \bm\phi(s_t, a_t) - \left(r_t + \gamma \max_b \bm\theta_{t-1}^\intercal \bm\phi(s'_{t},b)\right)\right).$$ \subsubsection{Residual Methods}\label{sec:residual} Instead of using the Bellman equations to provide an estimate of the target after deriving the update rule, one could use it directly to define the loss function to be optimized. We would then obtain the following minimization problem: $$\bm\theta^* = \operatorname*{argmin}_{\bm\theta} \frac{1}{N} \sum_{t=1}^N \PW{\big( v_{\bm\theta}^\pi(s_t) - \left(r_t + \gamma v^\pi_{\bm\theta} (s'_{t})\right) \big)^2}.$$ This can also be seen as the minimization of the Bellman residual. Indeed the Bellman evaluation equations ($v^\pi(s) = \mathbb{E}_\pi[R(s, A)+\gamma v^\pi(S')]$) can be rewritten as $v^\pi(s) - \mathbb{E}_\pi[R(s, A)+\gamma v^\pi(S')] = 0$. So by minimizing the quantity $v^\pi(s) - \mathbb{E}_\pi[R(s, A)+\gamma v^\pi(S')]$, called the Bellman residual, we reach the objective of evaluating $v^\pi(s)$. Here, we take the observed quantity $r+\gamma v^\pi(s')$ as an unbiased estimate of its expectation. The Bellman residual can also be minimized by stochastic gradient descent as proposed by~\citet{baird1995residual} and the update rule becomes: $$\bm\theta_t = \bm\theta_{t-1} - \alpha \nabla_{\bm\theta_{t-1}} \left( v_{\bm\theta_{t-1}}^\pi(s_t) - \left( r_t + \gamma v_{\bm\theta_{t-1}}^\pi (s'_{t})\right) \right) \left(v_{\bm\theta_{t-1}}^\pi(s_t) - \left(r_t + \gamma v^\pi_{\bm\theta_{t-1}}(s'_{t})\right)\right).$$ In the case of a linear approximation, we obtain: $$\bm\theta_t = \bm\theta_{t-1} - \alpha \left( \bm\phi(s_t) - \gamma \bm\phi(s'_{t}) \right) \left( \bm\theta_{t-1}^\intercal \bm\phi(s_t) - \left(r_t + \gamma \bm\theta_{t-1}^\intercal \bm\phi(s'_{t})\right)\right).$$ This approach, called R-SGD (for residual stochastic gradient descent), has a major flaw as it computes a biased estimate of the value-function. Indeed, $v_{\bm\theta}^\pi(s_t)$ and $v_{\bm\theta}^\pi(s'_t)$ are correlated as $s'_t$ is the result of having taken action $a_t$ chosen by $\pi(s_t)$ \cite{Werbos90}. To address this problem,~\citet{baird1995residual} suggest to draw two different next states $s'_{t}$ and $s''_{t}$ starting from the same state $s_t$ and to update as follows: $$\bm\theta_t = \bm\theta_{t-1} - \alpha \nabla_{\bm\theta_{t-1}} \left( v_{\bm\theta_{t-1}}^\pi(s_t) - \left( r_t + \gamma v_{\bm\theta_{t-1}}^\pi (s'_{t})\right) \right) \left(v_{\bm\theta_{t-1}}^\pi(s_t) - \left(r_t + \gamma v^\pi_{\bm\theta_{t-1}}(s''_{t})\right)\right).$$ Of course, this requires that a generative model or a simulator is available and that transitions can be generated on demand. The same discussions as in previous section can apply to learning an action-value function. For instance, one could want to solve the following optimization problem to learn the optimal action-value function: \begin{align} \bm\theta^* = \operatorname*{argmin}_{\bm\theta} \frac{1}{N} \sum_{t=1}^N \PW{\left( Q_{\bm\theta}^*(s_t, a_t) - \big(r_t + \gamma \max_b Q^*_{\bm\theta} (s'_{t}, b)\big) \right)^2}. \label{eq:qres} \end{align} Yet this optimal residual cannot directly be minimized in the case of the $Q$-function as the $\max$ operator is not differentiable. Notice that a sub-gradient method can still be used. \subsection{Least-Squares Methods} Gradient descent was used to minimize the empirical norm of either the bootstrapping error or the Bellman residual in the previous section. As the empirical norm is generally using the $\ell_2$-norm and that linear function approximation is often assumed, another approach could be to find the least squares solution to these problems. Indeed, least squares is a powerful approach as it is a second-order type of method and offers a closed-form solution to the optimization problem. Although there is no method that explicitly applies least squares to the two aforementioned empirical errors, one can see the fixed-point Kalman Filter (FPKF) algorithm~\cite{choi2006generalized} as a recursive least squares method applied to the bootstrapping error minimization. Also, the Gaussian Process Temporal Difference (GPTD)~\cite{GPTD} or the Kalman Temporal Difference (KTD)~\cite{KTD} algorithms can be seen as recursive least squares methods applied to Bellman residual minimization. We invite the reader to refer to~\citet{geist2013algorithmic} for further discussion on this. Yet, the most popular method inspired by least squares optimization does apply to a different cost function. The Least-Squares Temporal Difference (LSTD) algorithm~\citep{bradtke1996linear} aims at minimizing: $$\bm\theta^* = \operatorname*{argmin}_{\bm\theta} \frac{1}{N} \sum_{i=1}^N \left(v^\pi_{\bm\theta}(s_i) - v^\pi_{\bm\omega^*}(s_i) \right)^2,$$ where $\bm\omega^* = \operatorname*{argmin}_{\bm\omega} \frac{1}{N} \sum_{i=1}^N \left(v^\pi_{\bm\omega}(s_i) - \left(r_i + \gamma v^\pi_{\bm\theta}(s'_i) \right)\right)^2$ can be understood as a projection on the space $\Phi$ spanned by the family of functions $\bm\phi_j$'s used to approximate $v^\pi$. It can be seen as the composition of the Bellman operator and of a projection operator. This cost function is the so-called {\em projected Bellman residual}. When using linear function approximation, this optimization problem admits a closed-form solution: $$\bm\theta^* = \left[\sum_{i=1}^N \bm\phi(s_i) \left[\bm\phi(s_i) - \gamma \bm\phi(s'_i)\right]^\intercal \right]^{-1} \sum_{i=1}^N \bm\phi(s_i) r_i.$$ Note that the projected Bellman residual can also be optimized with a stochastic gradient approach \cite{SuttonMaeiPrecupBhatnagarSilverSzepesvariWiewiora09}. Extensions to non-linear function approximation exist and rely on the kernel trick~\citep{xu2007kernel} or on statistical linearization~\cite{geist2010statistically}. LSTD can be used to learn an approximate $Q$-function as well and can be combined with policy improvement steps into an iterative algorithm, similar to policy iteration, to learn an optimal policy from a dataset of sampled transitions. This gives rise to the so-called Least Squares Policy Iteration (LSPI) algorithm \citep{lagoudakis2003least}, which is one of the most popular batch-RL algorithm. \subsection{Iterative Projected Fixed-Point Methods} As we have seen earlier, dynamic programming offers a set of algorithms to compute value functions of a policy in the case the dynamics of the MDP is known. One of these algorithms, Value Iteration, relies on the fact that the Bellman equations define contraction operators when $\gamma<1$. For instance, if we define the Bellman evaluation operator $B^\pi$ such that $B^\pi Q(s, a) = R(s, a) + \gamma \mathbb{E}_{\pi}\big[Q(S', A') \,|\, S = s, A=a\big]$, one can show that iteratively applying $B^\pi$ to a random initialization of $Q$ converges to $Q^\pi$, because $B^\pi$ defines a contraction for which the only fixed point is $Q^\pi$~\citep{Puterman94}. The Bellman optimality operator $B^*$, defined as $B^*Q(s, a) = R(s, a) + \gamma \mathbb{E}\big[\max_b Q(S', b) \,|\, S = s, A = a\big]$, is also a contraction. The same holds for the sampled versions of the Bellman operators. For instance, let us define the sampled evaluation operator $\hat{B}^*$ such that $\hat{B}^* Q(s, a) = r + \gamma \max_b Q(s', b)$, where the expectation has been removed (the sampled operator applies to a single transition). Unfortunately, there is no guarantee that this remains a contraction when the value functions are approximated. Indeed when applying a Bellman operator to an approximate $Q_{\bm\theta}$, the result might not lie in the space spanned by $\bm\theta$. One has thus to project back on the space $\Phi$ spanned by $\bm\phi$ using a projection operator $\Pi_\Phi$, i.e., $\Pi_\Phi f = \operatorname*{argmin}_{\bm\theta} \| \bm\theta^\intercal \bm\phi - f \PW{\|_2} $. If the composition of $\Pi_\Phi$ and $\hat{B}^\pi$ (or $\hat{B}^*$) is still a contraction, then recursively applying this composition to any initialization of $\bm\theta$ still converges to a good approximate $Q^\pi_{\bm\theta}$ (or $Q^*_{\bm\theta}$). Unfortunately, the exact projection is often impossible to get as it is a regression problem. For instance, one would need to use least squares methods or stochastic gradient descent to learn the best projection from samples. Therefore the projection operator itself is approximated and will result in some $\hat{\Pi}_\Phi$ operator. So the iterative projected fixed-point process is defined as: $$ Q_{\bm\theta_t} = \hat{\Pi}_\Phi \hat{B}^\pi Q_{\bm\theta_{t-1}} \quad \text{ or } \quad Q_{\bm\theta_t} = \hat{\Pi}_\Phi \hat{B}^* Q_{\bm\theta_{t-1}}.$$ In practice, the algorithm consists in collecting transitions (e.g., $\{s_i, a_i, r_i, s'_i\}_{i=1}^N $), initialize $\bm\theta_0$ to some random value, compute a regression database by applying the chosen sampled Bellman operator (e.g., $\{\hat{B}^*Q_{\bm\theta_0}(s_i, a_i) = r_i + \gamma \max_b Q_{\bm\theta_0}(s_i, b)\}_{i=1}^N$), apply a regression algorithm to find the next value of parameters (e.g., $Q_{\bm\theta_1} = \hat{\Pi}_\Phi \hat{B}^* Q_{\bm\theta_{0}} = \operatorname*{argmin}_{\bm\theta} \frac{1}{N} \sum_{i=1}^N \PW{\big(Q_{\bm\theta}(s_i, a_i) - \hat{B}^*Q_{\bm\theta_0}(s_i, a_i) \big)^2}$) and iterate. This method finds its roots in early papers on dynamic programming~\citep{samuel1959some,bellman1963polynomial} and convergence properties have been analyzed by ~\citet{gordon1995stable}. The most popular implementations use regression trees~\citep{ernst2005tree} or neural networks~\citep{riedmiller2005neural} as regression algorithms and have been applied to many concrete problems such as robotics~\citep{antos2008fitted}. \subsection{Value-Based Deep Reinforcement Learning} \label{sec:deep} Although the use of Artificial Neural Networks (ANN, see Chapter 12 of Volume 2) in RL is not new~\citep{Tesauro95}, there has been only a few successful attempts to combine RL and ANN in the past. Most notably, before the recent advances in Deep Learning (DL)~\citep{lecun2015deep}, one can identify the work by~\citet{riedmiller2005neural} as the biggest success of ANN as a function approximation framework for RL. There are many reasons for that, which are inherently due to the way ANN learns and assumptions that have to be made for both gradient descent and most value-based RL algorithms to converge. Especially, Deep ANNs (DNN) require a tremendous amount of data as they contain a lot of parameters to learn (typically hundreds of thousands to millions). To alleviate this issue, \PW{~\citet{Tesauro95}} trained his network to play backgammon through a self-play procedure. The model learned at iteration $t$ plays again itself to generate data for training the model at iteration $t+1$. It could thus reach super-human performance at the game of backgammon using RL. This very simple and powerful idea was reused in~\citep{SilverHuangMaddisonGuezSifreDriesscheSchrittwieserAntonoglouPanneerschelvamLanctotDielemanGreweNhamKalchbrennerSutskeverLillicrapLeachKavukcuogluGraepelHassabis16} to build the first artificial Go player that consistently defeated a human Go master. Yet, this method relies on the assumption that games can easily be generated on demand (backgammon and Go rules are simple enough even though the game is very complex). In more complex settings, the agent faces an environment for which it does not have access to the dynamics, maybe it cannot start in random states and has to follow trajectories, and it can only get transitions through actual interactions. This causes two major issues for learning with DNNs (in addition to intensive usage of data). First, gradient descent for training DNNs assume the data to be independent and identically distributed (i.i.d. assumption). Second, the distribution of the data should remain constant over time. Both these assumptions are normally violated by RL since transitions used to train the algorithms are part of trajectories (so next states are functions of previous states and actions, violating the i.i.d. assumption) and because trajectories are generated by a policy extracted from the current estimate of the value function (learning the value function influences the distribution of the data generated in the future). In addition, we also have seen in Section~\ref{sec:residual} that Bellman residual minimization suffers from the correlation between estimates of value functions of successive states. All these problems make RL unstable~\citep{gordon1995stable}. To alleviate these issues,~\citet{MnihKavukcuogluSilverRusuVenessBellemareGravesRiedmillerFidjelandOstrovskiPetersenBeattieSadikAntonoglouKingKumaranWierstraLeggHassabis15} used two tricks that allowed to reach super-human performances at playing Atari 2600 games from pixels. First, they made use of a biologically inspired mechanism, called experience replay~\citep{lin1992self}, that consists in storing transitions in a Replay Buffer $D$ before using them for learning. Instead of sequentially using these transitions, they are shuffled in the buffer and randomly sampled for training the network (which helps breaking correlation between successive samples). \PW{The buffer is filled on a first-in-first-out basis so that the distribution of the transitions is nearly stationary (transitions generated by old policies are discarded first). Second, the algorithm is based on asynchronous updates of the network used for generating the trajectories and a slow learning network. The slow learning network, called the target network, will be updated less often than the network that actually learns from the transitions stored in the replay buffer (the $Q$-network). This way, }the update rule of the $Q$-network is built such that correlation between estimates of $Q(s,a)$ and $Q(s',a')$ is reduced. Indeed, the resulting algorithm (Deep Q-Network or DQN) is inspired by the gradient-descent update on the optimal Bellman residual (\ref{eq:qres}). But instead of using the double-sampling trick mentioned in Section~\ref{sec:residual}, two different estimates of the $Q$-function are used. One according to the target network parameters ($\bm\theta^-$) and the other according to $Q$-network parameters ($\bm\theta$). The parameters of the $Q$-network are thus computed as: $$\bm\theta^* = \operatorname*{argmin}_{\bm\theta} \sum_{(s_t, a_t, s'_t, r_t) \in D} \left[\left(r_t + \gamma \max_b Q_{\bm\theta^-}(s_t', b)\right) - Q_{\bm\theta}(s_t, a_t) \right]^2,$$ With this approach, the problem of non-differentiability of the $\max$ operator is also solved as the gradient is computed w.r.t. $\bm\theta$ and not $\bm\theta^-$. Once in a while, the target network parameters are updated with the $Q$-network parameters ($\bm\theta^- \leftarrow \bm\theta^* $) and new trajectories are generated according to the policy extracted from $Q_{\bm\theta^-}$ to fill again the replay buffer and train again the $Q$-network. The target network policy is actually a softmax policy based on $Q_{\bm\theta^-}$ (see Section~\ref{sec:bootstrap}). Many improvements have been brought to that method since its publication, such as a prioritized replay mechanism~\citep{schaul2016prioritized} that allows to sample more often from the replay buffer transitions for which the Bellman residual is larger, or the Double-DQN trick~\citep{van2016deep} used to provide more stable estimates of the $\max$ operator. \section{Policy-Search Approaches} \label{sec:policysearch} \input{ChapterRL-policy-search} \section{Extensions: Unknown Rewards and Risk-sensitive Criteria} \label{sec:extension} In the previous sections, we recalled different techniques for solving RL problems, with the assumption that policies are compared with the expected cumulated rewards as a decision criterion. However, rewards may not be scalar, known or numeric, and the standard criterion based on expectation may not always be suitable. For instance, multiobjective RL has been proposed to tackle situations where an action is evaluated over several dimensions (e.g., duration, length, power consumption for a navigation problem). The interested reader may refer to \cite{RoijersVamplewWhitesonDazeley13} for a survey and refer to Chapter 16 of this volume for an introduction to multicriteria decision-making. For space reasons, we focus below only on three extensions: reward learning (Section~\ref{sec:rewardlearning}), preference-based RL (Section~\ref{sec:preferencebased}) and risk sensitive RL (Section~\ref{sec:risksensitive}). \subsection{Reward Learning} \label{sec:rewardlearning} From the system designer's point of view, defining the reward function can be viewed as programming the desired behavior in an autonomous agent. A good choice of reward values may accelerate learning \cite{MatignonLaurentLe-Fort-Piat06} while an incorrect choice may lead to unexpected and unwanted behaviors \cite{RandlovAlstrom98}. Thus, designing this function is a hard task (e.g., robotics \cite{ArgallChernovaVelosoBrowning09}, natural language parsers \cite{NeuSzepesvari09} or dialogue systems \cite{El-AsriLarochePietquin12}). When the reward signal is not known, a natural approach is to learn from demonstration. Indeed, in some domains (e.g., autonomous driving), it is much simpler for an expert to demonstrate how to perform a task rather than specify a reward function. Such an approach has been called apprenticeship learning \cite{AbbeelNg04}, learning from demonstration \cite{ArgallChernovaVelosoBrowning09}, behavior cloning or imitation learning \cite{HusseinGaberElyanJayne17}. Two families of techniques have been developed to solve such problems. The first group tries to directly learn a good policy from (near) optimal demonstrations \cite{ArgallChernovaVelosoBrowning09,Pomerleau89} while the second, called inverse RL (IRL) \cite{NgRussell00,russell1998learning}, tries to first recover a reward function that explains the demonstrations and then computes an optimal policy from it. The direct methods based on supervised learning usually suffer when the reward function is sparse and even more when dynamics is also perturbed \cite{PiotGeistPietquin13}. As the reward function is generally considered to be a more compact, robust and transferable representation of a task than a policy \cite{AbbeelNg04,russell1998learning}, we only discuss reward learning approaches here. As for many inverse problems, IRL is ill-posed: any constant function is a trivial solution that makes all policies equivalent and therefore optimal. Various solutions were proposed to tackle this degeneracy issue, differing on whether a probabilistic model is assumed or not on the generation of the observation. When the state and/or action spaces are large, the reward function is generally assumed to take a parametric form: $R(s, a) = f_{\bm\theta}(s, a)$ for $f_{\bm\theta}$ a parametric function of $\bm\theta$. One important case, called {\em linear features}, is when $f$ is linear in $\bm\theta$, i.e., $R(s, a) = \sum_i \theta_i \phi_i(s, a)$ where $\phi_i$ are basis functions. {\bf No generative model assumption.} As underlined by \textcite{NeuSzepesvari09}, many IRL methods can be viewed as finding the reward function $R$ that minimizes a dissimilarity measure between the policy $\pi_R^*$ optimal for $R$ and the expert demonstrations. Most work assume a linear-feature reward function, with some exceptions that we mention below. \textcite{AbbeelNg04} introduced the important idea of expected feature matching, which says that the expected features of $\pi_R^*$ and those estimated from the demonstrations should be close. Thus, they notably proposed the projection method, which amounts to minimizing the Euclidean distance between those two expected features. \textcite{NeuSzepesvari07} proposed a natural gradient method for minimizing this objective function. \textcite{SyedSchapire08} reformulated the projection method problem as a zero-sum two-player game, with the nice property that the learned policy may perform better than the demonstrated one. \textcite{AbbeelNg04}'s work was extended to the partially observable case \cite{ChoiKim11}. Besides, \textcite{RatliffBagnellZinkevich06} proposed a max-margin approach enforcing that the found solution is better than any other one by at least a margin. Interestingly, the method can learn from multiple MDPs. It was later extended to the non-linear feature case \cite{RatliffBradleyBagnellChestnutt07}. Another technique \cite{KleinGeistPiotPietquin12,PiotGeistPietquin14} consists in learning a classifier based on a linearly parametrized score function to predict the best action for a state given the set of demonstrations. The learned score function can then be interpreted as a value function and can be used to recover a reward function. Traditional IRL methods learn from (near) optimal demonstration. More recent approaches extend IRL to learn from other types of observations, e.g., a set of (non-necessarily optimal) demonstrations rated by an expert \cite{El-AsriPiotGeistLarochePietquin16,BurchfieldTomasiParr16}, bad demonstrations \cite{SebagAkrourMayeurSchoenauer16} or pairwise comparisons \cite{da-SilvaCostaLima06,WirthNeumann15}. In the latter case, the interactive setting is investigated with a reliable expert \cite{ChernovaVeloso09} or unreliable one \cite{WengBusaFeketeHullermeier13}. {\bf Generative model assumption.} Another way to tackle the degeneracy issue is to assume a probabilistic model on how observations are generated. Here, most work assumes that the expert policy is described by Boltzmann distributions, where higher-valued actions are more probable. Two notable exceptions are the work of \textcite{GrollmanBillard11}, which shows how to learn from failed demonstration\PW{s} using Gaussian mixture models, and the Bayesian approach of \textcite{RamachandranAmir07}, with the assumption that state-action pairs in demonstrations follow such a Boltzmann distribution. This latter approach has been extended to Boltzmann distribution-based expert policy and for multi-task learning \cite{DimitrakakisRothkopf11}, and to account for multiple reward functions \cite{ChoiKim12}. This Bayesian approach has been investigated to interactive settings where the agent can query for an optimal demonstration in a chosen state \cite{LopesMeloMontesano09} or for a pairwise comparison \cite{WilsonFernTadepalli12,AkrourSchoenauerSebag13,AkrourSchoenauerSoupletSebag14}. Without assuming a prior, \textcite{Babes-VromanMarivateSubramanianLittman11} proposed to recover the expert reward function by maximum likelihood. The approach is able to handle the possibility of multiple intentions in the demonstrations. Furthermore, \textcite{NguyenLowJaillet15} suggested an Expectation-Maximization approach to learn from demonstration induced by locally consistent reward functions. To tackle the degeneracy issue, \textcite{ZiebartMaasBagnellDey10} argued for the use of the maximum entropy principle, which states that among all solutions that fit the observations, the least informative one (i.e., maximum entropy) should be chosen, with the assumption that a reward function induces a Boltzmann probability distribution over trajectories. When the transition function is not known, \textcite{BoulariasKoberPeters11} extended this approach by proposing to minimize the relative entropy between the probability distribution (over trajectories) induced by a policy and a baseline distribution under an expected feature matching constraint. \textcite{WulfmeierOndruskaPosner15} extended this approach to the case where a deep neural network is used for the representation of the reward function, while \textcite{BogertLinDoshiKulic16} took into account non-observable variables. \subsection{Preference-Based Approaches} \label{sec:preferencebased} Another line of work redefines policy optimality directly based on pairwise comparisons of histories without assuming the existence of a scalar numeric reward function. This notably accounts for situations where reward values and probabilities are not commensurable. In this context, different decision criteria (e.g., quantile \cite{GilbertWeng16}) may be used. One popular decision model (\cite{YueBroderKleinbergJoachims12,FurnkranzHullermeierChengPark12}) is defined as follows: a policy $\pi$ is preferred to another policy $\pi'$ if \begin{align} \mathbb{P}[h^\pi \succsim h^{\pi'}] \ge \mathbb{P}[h^{\pi'} \succsim h^\pi], \label{eq:probabilisticdominance} \end{align} where $\succsim$ is a preorder over histories, $h^\pi$ is a random variable representing the history generated by policy $\pi$ and therefore $\mathbb{P}[h^\pi \succsim h^{\pi'}]$ is the probability that a history generated by $\pi$ is not less preferred than a history generated by $\pi'$. Based on (\ref{eq:probabilisticdominance}), \textcite{FurnkranzHullermeierChengPark12} proposed a policy iteration algorithm. However, one crucial issue with (\ref{eq:probabilisticdominance}) is that the concept of optimal solution is not well-defined as (\ref{eq:probabilisticdominance}) can lead to preference cycles \cite{GilbertSpanjaardViappianiWeng15}. \textcite{BusaFeketeSzorenyiWengChengHullermeier14} circumvented this problem by refining this decision model with criteria from social choice theory. In \cite{GilbertSpanjaardViappianiWeng15}, the issue was solved by considering mixed solutions: an optimal mixed solution is guaranteed to exist by interpreting it as a Nash equilibrium of a two-player zero-sum game. \textcite{GilbertZanuttiniViappianiWengNicart16} proposed a model-free RL algorithm based on a two-timescale technique to find such a mixed optimal solution. \subsection{Risk-Sensitive Criteria} \label{sec:risksensitive} Taking into account risk is important in decision-making under uncertainty (see Chapter 17 of this volume). The standard criterion based on expectation is risk-neutral. When it is known that a policy will only be used a few limited number of times, variability in the obtained rewards should be penalized. Besides, in some hazardous domains, good policies need to absolutely avoid bad or error states. In those two cases, preferences over policies need to be defined to be risk-sensitive. In its simplest form, risk can directly be represented as a probability. For instance, \textcite{GeibelWysotzky05} adopted such an approach and consider MDP problems with two objectives where the first objective is the standard decision criterion and the second objective is to minimize the probability of reaching a set of bad states. A more advanced approach is based on risk-sensitive decision criteria \cite{BarberaHammondSeidl99}. Variants of Expected Utility \cite{Machina88}, which is the standard risk-sensitive criterion, were investigated in two cases when the utility function is exponential \cite{Borkar10,MoldovanAbbeel12} and when it is quadratic \cite{TamarDi-CastroMannor12,TamarDi-CastroMannor13,Gosavi14}. In the latter case, the criterion amounts to penalizing the standard criterion by the variance of the cumulated reward. While the usual approach is to transform the cumulated reward, \textcite{MihatschNeuneier02} proposed to directly transform the temporal differences during learning. Other approaches consider risk measures \cite{DenuitDhaeneGoovaertsKaasLaeven06} and in particular coherent risk measures \cite{ArtznerDelbaenEberHeath99}. Value-at-risk, popular in finance, was considered in \cite{GilbertWeng16}. Policy gradient methods \cite{ChowGhavamzadeh14,TamarGlassnerMannor15} were proposed to optimize Conditional Value-at-Risk (CVaR) and were extended to any coherent risk measure \cite{TamarChowGhavamzadehMannor15}. \textcite{JiangPowell16} proposed dynamic quantile-based risk measures, which encompasses VaR and CVaR, and investigated an approximate dynamic programming scheme to optimize them. In risk-constrained problems, the goal is to maximize the expectation of return while bounding a risk measure. For variance-constrained problems, \textcite{PrashanthGhavamzadeh16} proposed an actor-critic algorithm. For CVaR-constrained problems, \textcite{BorkarJain14} proposed a two-timescale stochastic approximation technique, while \textcite{ChowGhavamzadehJansonPavone16} investigated policy gradient and actor-critic methods. One important issue to consider when dealing with risk-sensitive criteria is that the Bellman optimality principle generally does not hold anymore: a sub-policy of an optimal risk-sensitive policy may not be optimal. However, in most cases, the Bellman optimality principle may be recovered by considering a state-augmented MDP, where the state includes the rewards cumulated so far \cite{LiuKoenig06}. \section{Conclusion}\label{sec:conclusion} Recently, thanks to a number of success stories, reinforcement learning (RL) has become a very active research area. In this chapter, we recalled the basic setting of RL. Our focus was to present an overview of the main techniques, which can be divided into value-based and policy search methods, for solving large-sized RL problems with function approximation. We also presented some approaches for tackling the issue of unknown rewards that a system designer would encounter in practice and recalled some recent work in RL when risk-sensitivity needs to be taken into account in decision-making. Currently RL still has too large sample and computational requirements for many practical domains (e.g., robotics). Research work is very active on improving RL algorithms along those two dimensions, notably by exploiting the structure of the problem \cite{KulkarniNarasimhanSaeediTenenbaum16} or other a priori knowledge, expressed in temporal logic \cite{WenPapushaTopcu17} for instance, or by reusing previous learning experience with transfer learning \cite{TaylorStone09}, lifelong learning \cite{Bou-AmmarTutunovEaton15}, multi-task learning \cite{WilsonFernRayTadepalli07} or curriculum learning \cite{WuTian17}, to cite a few. Having more efficient RL algorithms is important as it will pave the way to more applications in more realistic domains.
{'timestamp': '2020-06-16T02:06:48', 'yymm': '2005', 'arxiv_id': '2005.14419', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14419'}
arxiv
\section{Introduction}\label{sec1} Publication bias is one of the most important concerns in systematic reviews and meta-analyses. Part of the issue is that authors and scientific journals are likely to publish studies with statistically significant results than inconclusive studies\cite{thornton2000}. To be statistically significant, the studies with small sample size need to show larger treatment effects, which is known as the small-study effect\cite{sterne2000}. Thus, this may force us to analyze selective samples from the population of interest, and the standard meta-analysis techniques may suffer from this selection bias, which is referred to as publication bias. The funnel plot is a simple and widely-used graphical tool to check for publication bias, which is defined by plotting the estimate of the effect size such as the log-odds ratio or the log-hazard ratio as the horizontal axis and the related measure of precision such as the square root of the sample size or the inverse of the standard error as the vertical axis. One can address the publication bias by examining asymmetry of the funnel plot visually and more formal statistical evaluation of the funnel-plot asymmetry can be made with a regression based test\cite{egger1997,macaskill2001} or a rank-based test \cite{begg1994, schwarzer2007}. The trim-and-fill method is a nonparametric method to adjust publication bias utilizing the funnel-plot asymmetry\cite{duval2000}. All these methods are simple to apply and are widely used in practice. However, publication bias is not the only reason for asymmetry of the funnel plot; Egger et al.\cite{egger1997} listed different potential reasons for the funnel-plot asymmetry including the between-study heterogeneity and others. Then, detection of the publication bias by the funnel plot may be subjective and the trim-and-fill method may not work well\cite{terrin2003, peters2007}. Alternatively, several sensitivity analysis methods have been developed. Copas and colleagues introduced the Heckman-type parametric selection model, which was originally proposed in the econometrics literature\cite{heckman1979}, to describe a selective publication process in meta-analysis. In this paper, this selection model is referred as the Copas selection model\cite{copas2000,copas2001}. The sensitivity analysis with the Copas selection model has several advantages over existing alternative sensitivity analysis methods\cite{copas2013,copas2004,henmi2007}; a user-friendly \emph{R} package \emph{metasens} is available for the Copas-Shi selection model\cite{copas2000,copas2001}, and its performance was empirically examined\cite{carpenter2009, schwarzer2010}. Thus, we focus on this selection model in this paper. The Copas selection model consists of a pair of models; one is for the outcome, such as the log-odds ratio or the log-hazard ratio reported in publications, and the other is a model for the latent variable describing a selective publication process. It's hard to estimate all the parameters in the Copas selection model, and thus a series of papers by Copas and colleagues took a sensitivity analysis approach; some parameters were fixed as sensitivity parameters in a certain range, and the impact on the estimate of interest was studied. However, it's not easy to define an appropriate range for the sensitivity parameters. Prospective registration of study protocols in clinical trial registries is a useful non-statistical approach for publication bias. The International Committee of Medical Journal Editors (ICMJE) initiated a trials-registration policy as a condition for publication in its member journals in July 2005\cite{deangelis2005}, which promoted the development and utilization of the clinical trial registries. ClinicalTrials.gov (\url{https://clinicaltrials.gov/ct2/home}) is one of the early examples which was established in 2000 and is nowadays a very popular registry with 334,954 registered studies in April 2019. World Health Organization's (WHO) International Clinical Trials Registry Platform (ICTRP) (\url{http://apps.who.int/trialsearch/}) is another well-known clinical trials registry which was constructed after the initiation of ICMJE's policy and has been supported by the WHO. FDA (US Food and Drug Administration) database (\url{https://www.accessdata.fda.gov/scripts/cder/daf/}) contains information about products approved by the FDA for human use in the United States. Besides, EU clinical trials register (\url{https://www.clinicaltrialsregister.eu/ctr-search/search}) and ISRCTN (\url{https://www.isrctn.com/}) are also well-developed and widely used in recent years as well as many national registries that often also provide lay summaries in the local language\cite{viergever2015,ogino2014}. Baudard et al. \cite{baudard2017} investigated 14 meta-analyses and showed that by incorporating the information from clinical trial registries, the effect size estimates might change by 29\%. It indicated that searching clinical trial registries may be useful to reduce the bias due to selective publication. On the other hand, although clinical trial registries provide potentially useful information of the registered clinical trials (e.g., study design, target sample size, development phase), they are used only as a tool to search for studies\cite{jones2014}. Information on unpublished studies provided by clinical trial registries is not formally incorporated in the analyses. To the best of knowledge, only two papers mentioned the use of clinical trial registries in statistical inference. Matsuoka et al. \cite{matsuoka2011} proposed a publication bias detection method by utilizing the planned sample size from World Health Organization's (WHO) International Clinical Trials Registry Platform (ICTRP). Mavridis et al. \cite{mavridis2013}utilized FDA database to construct a prior distribution of parameters in their Bayesian Copas-type model for sensitivity analysis in network meta-analysis. In this paper, we improve statistical inference for the Copas-Shi selection model utilizing the information from clinical trial registries. To be specific, utilizing the planned sample size of unpublished studies, which are provided by most clinical trial registries, we propose a method that fit by the maximum likelihood method. All the unknown parameters can be estimated from data, and statistical inference can be conducted according to the standard maximum likelihood theory. In addition to the confidence interval with the normal quantile according to the maximum likelihood theory, we also propose two modified confidence intervals aiming improvement of performance with the small number of studies. Through numerical studies, we observed that our method outperformed existing methods with smaller biases and coverage probabilities closer to the nominal level. Thus, by utilizing the information of unpublished studies from clinical trial registries, inference based on the Copas selection model can be improved. The remainder of this paper is organized as follows. In Section 2, we introduce two motivating meta-analyses. In Section 3, we briefly review the sensitivity analysis method of Copas and Shi\cite{copas2000,copas2001}, and then introduce our new inference procedure by utilizing clinical trial registries. In Section 4, we conduct a series of simulation studies motivated by the tiotropium study to evaluate the performance of our proposed method in comparison to other competitive approaches. In Section 5, we revisit the two studies in Section 2 to illustrate the proposed method. Finally, we discuss some limitations and further research in Section 6. \section{Motivating examples}\label{sec2} \subsection{Tiotropium study} Karner et al.\cite{karner2014}conducted a Cochrane review of tiotropium versus placebo in COPD. The primary outcome was COPD exacerbations, which was defined as a complex of respiratory events or symptoms (new onset or an increase in at least one of cough, sputum, dyspnoea or wheeze) that lasted at least three days and required treatment with antibiotics and/or systemic corticosteroids. In each study, the odds ratio for the event of one or more exacerbations was used to compare the treatment and placebo groups. In the meta-analysis by Karner et al.\cite{karner2014}, 22 studies were analyzed using a random-effects model, and the pooled odds ratio was reported as 0.78 with a 95\% confidence interval of [0.70, 0.87]. To assess the potential risk of publication bias, Karner et al.\cite{karner2014}conducted the Egger's test with the p-value of 0.22 and concluded no serious concern of publication bias. However, our additional application of the Macaskill's regression test\cite{macaskill2001} gave a p-value of 0.06, suggesting the funnel-plot asymmetry. Then, publication bias might be a concern. Karner et al. \cite{karner2014}made their efforts to search the studies with results submitted on ClinicalTrials.gov. We conducted a more comprehensive search of multiple registries, including ClinicalTrials.gov, World Health Organization's (WHO) International Clinical Trial Registry, EU clinical trials register, FDA database, and ISRCTN platform. We used the following terms: \emph{Tiotropium} or \emph{Spiriva} or \emph{HandiHaler} or \emph{Respimat} for the search. They were the same as used in the meta-analysis of Karner et al. \cite{karner2014}, and we also set primary completion date before February 28, 2012, which aimed to be consistent with the original meta-analysis. We detected 10 related studies on these registries, among which 8 came from ClinicalTrials.gov, 1 came from EU clinical trials register, and 1 came from World Health Organization's (WHO) International Clinical Trials Registry. Two of them reported the outcome measure and were incorporated with published studies, and 8 studies without results were deemed as unpublished studies. Finally, we got the tiotropium dataset with 24 published studies and 8 unpublished studies with information of sample size only (see Table S1 in Web-appendix A). \subsection{Clopidogrel study} The second example is about the comparison of high and standard maintenance-dose clopidogrel on major adverse cardiovascular/cerebrovascular events (MACE/ MACCE) by Chen et al.\cite{chen2013}. The original meta-analysis included 12 studies and reported pooled odds ratio as 0.6 based on the fixed-effect model with a 95\% CI of [0.43, 0.83], and no significant bias was concluded with the Egger's test (p=0.25). However, we rerun the Macaskill's test, which suggested funnel-plot asymmetry with a P value of 0.02. We took the procedure as given in the first example and identified 3 unpublished studies from ClinicalTrials.gov by following terms: \emph{Clopidogrel} or \emph{Plavix} or \emph{Iscover}, with completion date before August 31, 2013. The resulting dataset was presented in Table S2 in Web-appendix A. \section{Inference procedures for the Copas selection model}\label{sec3} \subsection{Brief review of the sensitivity analysis method by Copas and Shi} In order to evaluate the potential impact of publication bias on estimation of the treatment effect, Copas and Shi \cite{copas2000} introduced a sensitivity analysis method. Suppose we conduct a meta-analysis of \emph{N} studies. Let $\hat{\theta_i}$ be the estimated treatment effect of the $i$th study such as the log-odds ratio or the log-hazard ratio, and $s_i$ be an estimate of its standard error. We assume that $(\hat{\theta_i}, s_i)$ is available for $i=1,2,..., N$. To integrate the treatment effects over the studies, we consider the standard random-effects model with \begin{eqnarray} \hat{\theta_i}=\theta_i+\sigma_i\epsilon_i, \ \ \ \theta_i \sim N(\theta,\tau^2), \ \ \ \ \epsilon_i \sim N(0,1), \label{mixed} \end{eqnarray} where $\theta_i$ is the study-specific treatment effect of the \emph{i}th study, which is a random-effect following a normal distribution with mean $\theta$ and between-study variance $\tau^2$, and $\sigma_i^2$ is the true within-study variance of the outcome $\hat {\theta_i} $. The random elements $\theta_i$ and $\epsilon_i$ are assumed to be independent. To describe the selective publication process, Copas and Shi \cite{copas2000,copas2001} considered the following model \begin{equation} Y_i=\alpha_0+\alpha_1 / s_i+\delta_i, \ \ \ \delta_i \sim N(0,1), \ \ \ corr(\epsilon_i,\delta_i)=\rho, \label{selection} \end{equation} where $corr(\epsilon_i,\delta_i)$ denotes the correlation coefficient between $\epsilon_i$ and $\delta_i$. The \emph{i}th study is assumed to be published if and only if $Y_i>0$. The term $\alpha_0+\alpha_1 / s_i$ models the small study effect. That is, studies of high precision are more likely to be pulished. The correlation coefficient $\rho$ is responsible for describing the influence of the outcome $\hat{\theta_i}$ on likelihood of publication. Copas and Shi\cite{copas2000} considered to make inference by maximizing the likelihood function conditional on the study being published. The conditional likelihood function is given by \begin{eqnarray} && L_{obs}(\theta,\tau,\rho,\alpha_0,\alpha_1;s_i)=\sum_{i=1}^{N}\left[log f(\hat{\theta_i}|Y_i>0,s_i)\right] \nonumber \\ &&= \sum_{i=1}^{N}\left[-\frac{1}{2}log(\tau^2+\sigma_i^2)-\frac{(\hat{\theta_i}-\theta)^2}{2(\tau^2+\sigma_i^2)}-log\Phi(\alpha_0+\alpha_1/s_i)+log\Phi(v_i)\right], \label{lik_obs} \end{eqnarray} where $f(\cdot|Y_i>0,s_i)$ is the probability density function of $\hat{\theta_i}$ conditional on $Y_i>0$ and $s_i$. $ \Phi(\cdot)$ is the cumulative distribution function of the standard normal distribution, and $v_i=\left\{\alpha_0+\alpha_1/s_i +\rho \sigma_i(\hat{\theta_i}-\theta) / (\tau^2+\sigma_i^2) \right\} / \sqrt {1-\rho^2 \sigma_i^2 / (\tau^2+ \sigma_i^2)}$. In meta-analysis literatures, $s_i$ is usually regarded as being equal to $\sigma_i$ and known. This is relevant approximately at least when the number of subjects is sufficiently large. Copas and Shi\cite{copas2000,copas2001}took care of underestimation of $\sigma_i$ due to publication bias, and then they utilized the quantity $var(\theta_i|s_i,Y_i>0)$ to estimate $\sigma_i^2$ in inference of their selection model. As argued by Copas and Shi\cite{copas2000,copas2001}, the log-likelihood function ($\ref{lik_obs}$) may take its maximum over a very flat plateau, and then it may be computationally very challenging to estimate all the parameters simultaneously. Thus Copas and Shi\cite{copas2000,copas2001} proposed that the vector $(\alpha_0,\alpha_1)$ was fixed as sensitivity parameters, and $(\theta,\tau,\rho)$ was estimated by maximizing the conditional log-likelihood function ($\ref{lik_obs}$). One can examine how the estimate $\hat{\theta}$ for the overall treatment effect $\theta$ would be influenced by the assumed selective publication process. Since we do not know the true value of $(\alpha_0,\alpha_1)$, we should apply this method with various choices for the parameter vector $(\alpha_0,\alpha_1)$ in a certain range. According to the formula by Copas and Shi\cite{copas2000}, one can translate $(\alpha_0,\alpha_1)$ into the expected numbers of unpublished studies by $ M=\sum_{i=1}^{N}\left\{1-P(Y_i>0|s_i)\right\}/P(Y_i>0|s_i)$, which is more interpretable. Then, one can evaluate how biased the estimate of the treatment effect $\theta$ is with a certain number of unpublished studies behind. Although such a consideration provides nice insights about robustness of meta-analysis results, it is still unclear what range of the number of unpublished studies is sufficient to be considered. \subsection{Proposed inference procedure utilizing clinical trial registries} In addition to the \emph{N} published studies, we suppose that there are \emph{M} unpublished studies identified by searching clinical trial registries. Without loss of generality, the first \emph{N} studies are published and the last \emph{M} studies are unpublished. Items required at registration are not necessarily common among clinical trial registries. For example, FDA database provides the sample size of each experimental group in its summary review PDF document, but other clinical trial registries may not give it. However, all the clinical trial registries we referred provide the planned total sample size (not separately by the experimental groups) of each study. Thus, we suppose the triple $(n_i,\hat{\theta_i},s_i)$ is available for \emph{i}=1,2,...,\emph{N} (published studies), and only $n_i$ is available for \emph{i}=\emph{N}+1,..,\emph{N+M} (unpublished studies). A binary variable $D_i=I(Y_i>0)$ denotes the publication status (published/unpublished) of each study. Instead of the model ($\ref{selection}$), we employ an alternative selection model \begin{eqnarray} Y_i=\alpha_0+\alpha_1\sqrt{n_i}+\delta_i, \ \ \ \delta_i \sim N(0,1), \label{selection2} \end{eqnarray} which was used by Copas\cite{copas1999}. For the models ($\ref{mixed}$) and ($\ref{selection2}$), we introduce the maximum likelihood approach as follows. Considering the likelihood function of the published and the unpublished studies, the log likelihood is given by \begin{align} L_{full}(\theta,\tau,\rho,\alpha_0,\alpha_1)&=\sum_{i=1}^{N}\left[log f(\hat{\theta_i}|Y_i>0;n_i)+log P(Y_i>0;n_i)\right]\nonumber \\&+\sum_{i=N+1}^{N+M}\left[log P(Y_i<0;n_i)\right]\nonumber \\ &=\sum_{i=1}^{N}\left[-\frac{1}{2}log(\tau^2+\sigma_i^2)-\frac{(\hat{\theta_i}-\theta)^2}{2(\tau^2+\sigma_i^2)}+log\Phi(\tilde{v_i})\right]\nonumber \\&+\sum_{i=N+1}^{N+M}\left\{log [1-\Phi(\alpha_0+\alpha_1\sqrt{n_i})]\right\}, \label{lik_full} \end{align} where $\tilde{v_i}=\left\{\alpha_0+\alpha_1\sqrt{n_i} +\rho \sigma_i(\hat{\theta_i}-\theta) / (\tau^2+\sigma_i^2) \right\} / \sqrt {1-\rho^2 \sigma_i^2 / (\tau^2+ \sigma_i^2)}$. Following the treatment often made in meta-analysis literature, we suppose that $\sigma_i=s_i$. By maximizing this log-likelihood function ($\ref{lik_full}$), we can estimate all the parameters $(\theta,\tau,\rho,\alpha_0,\alpha_1)$ simultaneously, and the resulting maximum likelihood estimator is denoted by $(\hat{\theta},\hat{\tau},\hat{\rho},\hat{\alpha_0},\hat{\alpha_1})$. Maximization of the log-likelihood function can be implemented with the standard non-linear optimization techniques. Here, we employ the constraint optimizer L-BFGS-B method in the nlminb() function in \emph{R} (package stats, version 3.6.2) to do this. Statistical inference can be conducted following the standard maximum likelihood theory. \section{Simulation study}\label{sec4} \subsection{Methods to be compared} Simulation studies were carried out to evaluate the performance of our new inference procedure. We investigated whether or not the proposed method outperforms the Copas sensitivity analysis method. For reference, we also compared it with standard random-effects meta-analysis using the restricted maximum likelihood (REML) estimation, which did not account for selective publication process. In addition to the standard REML confidence interval based on normal quantiles, the Hartung and Knapp method\cite{hartung2001,hartung2001refined} was applied using \emph{t}-quantiles and rescaled standard errors, which is referred to as REML.KnHa in the following. As outlined in Section 3, the Copas method is a sensitivity analysis approach resulting in multiple estimates under several settings of the number of unpublished studies. For comparison with other methods, we took the estimate of the treatment effect with the smallest number of unpublished studies of the p-value of the goodness-of-fit test larger than 0.1\cite{copas2000}, which is presented in the output of \emph{Copas} function in \emph{metasens} package\cite{carpenter2009r}. For the REML, we used the commonly used \emph{metafor} package with method option equal to ``REML'' and test equal to ``knha'' to obtain the CI with the Hartung and Knapp method. \subsection{Data generation} We mimicked meta-analyses motivated by the tiotropium study. Suppose each study aimed to compare two groups of the treatment group and the control group with respect to a binary outcome. The log-odds ratio was used as the summary measure of the treatment effect between two groups. Let $\hat{\theta_i}$ in the model ($\ref{mixed}$) denoted the empirical log-odds ratio of the $i$th study. We set $\theta=-0.25$ and $\tau$=0.05, 0.15 or 0.3. The total number of studies including published and unpublished was set as 15, 25, 50 or 100. We generated datasets according to the models ($\ref{mixed}$) and ($\ref{selection2}$) as follows. At first, we generated $\theta_i \sim N(\theta,\tau^2)$, which was the true log-odds ratio of the \emph{i}th study. Next, we generated individual participant data of the two groups with the log-odds ratio of $\theta_i$. We set the true event rate of the control group from the uniform distribution \emph{U(0.2,0.9)}, and then set the event rate of treatment group satisfying the log-odds ratio of $\theta_i$. Similarly to Kuss\cite{kuss2015}, the total sample size of each study was generated from \emph{LN(5,1)}, the log-normal distribution with the location parameter 5 and scale parameter 1, and the minimum sample size was restricted to 20 patients (values below 20 were rounded up to 20). Subjects were allocated to the two groups with probability of 0.5. With the generated individual participant data, we calculated an empirical log odds ratio $\hat{\theta_i}$ and its standard error $s_i$. $Y_i$ in the model ($\ref{selection2}$) was generated according to the conditional distribution, \begin{equation} Y_i|\hat{\theta_i}\sim N(\alpha_0+\alpha_1 \sqrt n_i+\rho\sigma_i (\hat{\theta_i}-\theta)/(\tau^2+\sigma_i^2),1-\rho^2\sigma_i^2/(\tau^2+\sigma_i^2)) \end{equation} and set $D_i=I(Y_i>0)$, which entailed us to generate $(\hat{\theta_i},Y_i)$ from the joint distribution defined by the models ($\ref{mixed}$) and ($\ref{selection2}$). The parameters $(\alpha_0,\alpha_1)$ were set based on our consideration for the publication rate of a study with the minimum sample size of 20 and that with a large sample size of 500, which were denoted by $P_{20}$ and $P_{500}$, respectively. Set $P_{500}=0.99$, reflecting our belief that a study with 500 patients had sufficiently large probability to be published, and $P_{20}$ was set to 0.1, 0.3 or 0.5, which represented our different concern to the publication rate of a small study with sample size of 20. Thus according to the model (4), we could derive the parameters $(\alpha_0,\alpha_1)$ by solving the equations $P_{20}=\Phi(\alpha_0+\alpha_1\sqrt20)$ and $P_{500}=\Phi(\alpha_0+\alpha_1\sqrt500)$. Then we got three pairs of $(\alpha_0,\alpha_1)$ as (-2.18,0.20), (-1.24,0.16) and (-0.58,0.13), which resulted in 40\%, 27\% and 19\% unpublished studies on average in the simulated meta-analyses. The parameter of $\rho$ was set to -0.4 or -0.8, and for each $\rho$ we investigated 3 scenarios of $\tau$ (0.05, 0.15 or 0.3). For each scenario, we generated 1000 simulated meta-analyses. In Figure 1, we presented funnel plots of randomly selected simulated meta-analyses under different settings of $(\rho,\tau)$ when the total number of published and unpublished studies was 50. The filled and open circles represent published and unpublished studies, respectively, and we observed our simulation setting successfully simulated the selective publication process often observed in practice. The bold vertical line represents the true $\theta$ and the dashed vertical line is the REML estimate with published studies. They were certainly different and thus publication bias had certain impacts in simulated data. \subsection{Simulation results} The properties of each method were assessed by evaluating biases and standard errors of the estimates for $\theta$ and average lengths and coverage probabilities of two-tailed $95\%$ confidence intervals of $\theta$. Following the standard maximum likelihood theory, we constructed the two-tailed 95\% confidence interval for the estimates of $\theta$ with our new proposal by $\hat{\theta}\pm$$Z_{1-\frac{\alpha}{2}}\times$ S.E.$(\hat{\theta})$, where $Z_{1-\frac{\alpha}{2}}$ denoting the $1-\frac{\alpha}{2}$ quantile of the standard normal distribution, and S.E.$(\hat{\theta})$ is calculated by the inverse of the Fisher information matrix. The results for this confidence interval were denoted by MLE(N) in the summary table. All these methods were implemented with non-linear optimization techniques, thus we also summarized the number of converged cases (\emph{NOC}) in each scenario. For our method, the non-convergence was defined as a failure in optimization with negative hessian matrix or unsuccessful convergence based on the convergence indicator in the output of \emph{nlminb} function. For the Copas sensitivity analysis method, we followed the rule of \emph{Copas} function\cite{carpenter2009, carpenter2009r}. Results of the simulation studies with ($\alpha_0,\alpha_1$)=(-2.18,0.2) were reported in Table 1 ($\rho=-0.4$) and Table 2 ($\rho=-0.8$), respectively. The datasets for Tables 1 and 2 had around 40\% unpublished studies on average. In almost all the simulated datasets, the log-likelihood was successfully maximized and then gave estimates. In all the scenarios, the REML had considerable biases. With $\rho=-0.8$ (Table 2), biases were larger, reflecting that $\rho=-0.8$ modeled a more selective publication process. Both the Copas method and our new proposal decreased biases and ours had the smallest biases in most scenarios. With larger number of studies (N=50 and 100), the maximum likelihood estimator tended to have very negligible biases, and the confidence intervals based on the maximum likelihood theory (MLE(N)) had empirical coverage probabilities close to the nominal level of 95\%. With smaller number of the studies (N=15 and 25), our method successfully decreased biases. However, coverage probabilities might not be close to the nominal level and were not satisfactory when between-study heterogeneity was moderate or substantial ($\tau=0.15$ and 0.3). We demonstrated results of the simulation studies with ($\alpha_0,\alpha_1$)=(-1.24,0.16) in Tables S3 and S4, and that with ($\alpha_0,\alpha_1$)=(-0.58,0.13) in Tables S5 and S6 in Web-appendix B. Findings were very similar to discussed above based on Tables 1 and 2. \subsection{Modified confidence intervals} To improve the coverage probabilities with smaller number of studies, we introduced two modifed confidence intervals. As suggested by Follmann and Proschan\cite{follmann1999}, an alternative confidence interval $\hat{\theta}\pm$$t_{(N-1);(1-\frac{\alpha}{2})}\times$ S.E.$(\hat{\theta})$ may be used, where $t_{(N-1);(1-\frac{\alpha}{2})}$ denoting the $1-\frac{\alpha}{2}$ quantile of Student\emph{-t} distribution with $N-1$ degree of freedom. Further modification was also considered by mimicking the idea of the improved estimator of variance which was proposed by Knapp and Hartung\cite{knapp2003}in the meta-regression context; we modified the standard error of $\hat{\theta}$ by S.E.$(\hat{\theta})^\sharp$=Max(S.E.$(\hat{\theta})_{MLE}$, S.E.$(\hat{\theta})_{REML-KnHa}$) , where S.E.$(\hat{\theta})_{REML-KnHa}$ was the estimator of standard error with HK-adjusted REML method, reflecting our belief that the standard error of our proposal should be no less than the estimator of methods without considering the selcetive publication process for the additional uncentainty of unpublished studies. That is, a more conservative confidence interval was calculated by $\hat{\theta}\pm$$t_{(N-1);(1-\frac{\alpha}{2})}\times$S.E.$(\hat{\theta})^\sharp$. We applied these two confidence intervals to the simulated meta-analyses, results were also shown in Tables 1 and 2 and Tables S3-S6 in Web-appendix B, referring as MLE(T) and MLE($SE^\sharp$), respectively. We observed that these two confidence intervals MLE(T) and MLE($SE^\sharp$) gave certain improvement. In particular, MLE($SE^\sharp$) had much improved emprical coverage probabilities with \emph{N=15}. \section{Re-analysis of two motivating examples with clinical trial registries}\label{sec5} In this section, we applied our new inference procedure to the two case studies of the tiotropium study and clopidogrel study introduced in Section 2. To present data of unpublished studies as well as that of published studies, we propose to use a modified funnel-plot adding information of the planned sample size of unpublished studies with horizontal lines passing the y-axis at $\sqrt{n_i}$. The modified funnel-plots for tiotropium study and clopidogrel study were presented in Figures 2 and 3, respectively. We could observe that for both of the two motivation cases, all the unpublished studies concentrated on the lower part of the funnel-plot. To the data, we applied our proposed method, as well as other related methods used in the simulation section, and the results for the two motivation cases were summarized in Tables 3 and 4, respectively. As presented in Subsection 2.1, for the tiotropium study, we identified 24 published and 8 unpublished studies. By applying the linear mixed-effect model for the log-odds ratios with the REML method, the integrated odds ratio was obtanied as 0.768 with a two-tailed 95\% CI of [0.697,0.847] based on the normal approximation. The Knapp and Hartung modification gave a similar CI of [0.691, 0.854]. According to the sensitivity analysis by the Copas model, one can observe that as increasing the number of unpublished studies, the odds ratio increased up to 0.811, which was corresponding to the case of 13 unpublished studeis. The overall treatment effect was significantly different from unity even with 13 unpublished studies. Suppose we have 8 published studies behind which was same with our findings from the clinical trial registries, Copas sensitivity analysis method gave the pooled odds rato as 0.803 with a 95\% CI of [0.717, 0.898]. Our proposed method gave the integrated estimate of 0.787 with two-tailed 95\% confidence intervals [0.710, 0.873] and [0.706, 0.878] based on the standard normal quantile and t-quantile, respectively. In this case, the standard error from our method was larger than the standard error from REML with the Knapp and Hartung modification, so the modified confidence interval MLE($SE^\sharp$) was same with MLE(T). To summary, all the methods provided statistically significant effect of tiotropium, indicating that selective publication might have not been much of an issue here. For the clopidogrel study which we introduced in Subsection 2.2, with only 3 unpublished studies identified from the clinical trial registries, the estimates with and without consideration of publication bias were considerably different. By applying the REML with 12 published studies, the estimator of the pooled odds ratio was 0.579 and with two-tailed 95\% CIs of [0.375, 0.892] and [0.385, 0.871] based on the normal quantile and the Knapp and Hartung modification, respectively. Both of them supported the conclusion that the high maintenance-dose clopidogrel significantly reduced the incidence of MACE/MACCE in comparison to the standard-maintenance-dose clopidogrel. However, the sensitivity analysis by the Copas model showed that as the number of unpublished studies increased up to 4, the statistical significance of the High-maintenance-dose clopidogrel disappeared, and as high as 39\% change in estimates of odds ratio could be observed with 6 unpublished studies. Our proposed method gave the integrated estimate of 0.692, and a two-tailed 95\% CI based on the normal approximation was given as [0.496, 0.967], whose upper bound was very close to 1. The modified CIs introduced in Subsection 4.4 could be obtained as [0.476, 1.007] (MLE(T)) and [0.460, 1.041] (MLE($SE^\sharp$)), respectively. These results suggested that the significant effect of the high maintenance-dose clopidogrel might be marginal and should be interpreted with caution. \section{Discussion}\label{sec6} By utilizing the information on unpublished studies obtained from the clinical trial registries, we proposed a new inference procedure for the Copas selection model, which provides more objective evaluation of publication bias than the widely-used funnel plot and trim-and-fill method\cite{carpenter2009, schwarzer2010}. All the unknown parameters in the Copas selection model can be estimated from data with the proposed method. It resolved the issue of the sensitivity analysis approach that some unknown parameters had to be fixed in a certain range, and then gave a more insightful interpretation. Recently, Ning et al. \cite{ning2017}proposed a method to estimate all the unknown parameters. Whereas their method strongly relied on an imputation based on funnel-plot symmetry, our method does not. Here, we would like to address some issues in clinical trial registries. Firstly, different clinical trial registries may give inconsistent information. A comparison of results between ClinicalTrials.gov and FDA database by Schwartz et al.\cite{schwartz2016}showed the planned sample size registered on the clinical trial registries were not always consistent with the final sample size for statistical analysis. Besides, as acknowledged by Fleminger et al.\cite{fleminger2018} the status of the studies might be inconsistent between EUCTR and ClinicalTrials.gov, the studies registered on EUCTR which marked with ``completed'' may marked with ``onging'' in ClinicalTrials.gov. Secondly, no clinical trial registry could cover all the related studies\cite{glanville2014,tse2018,adam2018}. Thirdly, it is hard to integrate multiple clinical trial registries automatically since unique identifier of a study is not available among registries (e.g. World Health Organization's (WHO) International Clinical Trial Registry Platform (ICTRP)). Due to these issues of clinical trial registries, comprehensive search of multiple clinical trial registries was recommended in practice. Clinical trial registries provide various information other than sample size. ClinicalTrials.gov's search result contains 26 items in the list and analysis result if the investigator submitted, ICTRP contains 40 items in the result file, and FDA database provide much more details about the registered clinical trials. As acknowledged by several cross-sectional studies, information such as funding type (government, industry or academic) and region may possibly play important roles in the publication status\cite{loder2018}. In addition, information of ongoing studies are also available, although we did not use them in this paper. How to take a further utilization of the clinical trial registry would deserve more attention. \section*{Acknowledgments} The last author's research was partly supported by Grant-in-Aid for Challenging Exploratory Research (16K12403) and for Scientific Research (16H06299, 18H03208) from the Ministry of Education, Science, Sports and Technology of Japan.
{'timestamp': '2020-06-01T02:06:57', 'yymm': '2005', 'arxiv_id': '2005.14396', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14396'}
arxiv
\section{Appendix}\label{s:appendix} For writing compactness we use the following shorthand notations for the transition and observation functions thoughout the next two subsections: $\ensuremath{T}\xspace = \ensuremath{T(s, a, s')}\xspace$, $\ensuremath{\widehat{T}}\xspace = \ensuremath{\widehat{T}(s, a, s')}\xspace$ and $\ensuremath{Z}\xspace = \ensuremath{Z(s, a, o)}\xspace$, $\ensuremath{\widehat{Z}}\xspace = \ensuremath{\widehat{Z}(s, a, o)}\xspace$. Additionally in section Section~\ref{ssec:proofLem4} we use the notations $\ensuremath{T}\xspace_{k} = T(\ensuremath{s}\xspace_k, \ensuremath{a}\xspace, \ensuremath{s'}\xspace)$ and $\ensuremath{\widehat{T}}\xspace_{k} = \widehat{T}(\ensuremath{s}\xspace_k, \ensuremath{a}\xspace, \ensuremath{s'}\xspace)$. \subsection{Proof of Lemma \ref{lem:lem0}}\label{ssec:lemma_0_proof} Consider any $\sigma \in \Gamma$ with its action $\ensuremath{a}\xspace \in \ensuremath{A}\xspace$ and observation strategy $\nu$. Then for any $\ensuremath{s}\xspace\in\ensuremath{S}\xspace$ \begin{align}\label{eq:first_lemma_0} &&&\left | \alpha_{\sigma}(\ensuremath{s}\xspace) - \widehat{\alpha}_{\sigma}(\ensuremath{s}\xspace) \right | \nonumber \\ &&=&\left | \rewFuncComp{\ensuremath{s}\xspace}{\ensuremath{a}\xspace} + \gamma \ensuremath{\int_{s' \in S}}\xspace \ensuremath{\int_{o \in O}}\xspace \ensuremath{T}\xspace \ensuremath{Z}\xspace \alpha_{\nu(\ensuremath{o}\xspace)}(\ensuremath{s'}\xspace)\ensuremath{d}\xspace\ensuremath{o}\xspace \ensuremath{d}\xspace\ensuremath{s'}\xspace \right. \nonumber\\ &&&\left. -\rewFuncComp{\ensuremath{s}\xspace}{\ensuremath{a}\xspace} - \gamma \ensuremath{\int_{s' \in S}}\xspace \ensuremath{\int_{o \in O}}\xspace \ensuremath{\widehat{T}}\xspace \ensuremath{\widehat{Z}}\xspace \widehat{\alpha}_{\nu(\ensuremath{o}\xspace)}(\ensuremath{s'}\xspace) \ensuremath{d}\xspace\ensuremath{o}\xspace \ensuremath{d}\xspace\ensuremath{s'}\xspace \right | \nonumber \\ &&=&\gamma \left | \ensuremath{\int_{s' \in S}}\xspace \ensuremath{\int_{o \in O}}\xspace \ensuremath{T}\xspace \ensuremath{Z}\xspace \alpha_{\nu(\ensuremath{o}\xspace)}(\ensuremath{s'}\xspace) - \ensuremath{\widehat{T}}\xspace\ensuremath{\widehat{Z}}\xspace \widehat{\alpha}_{\nu(\ensuremath{o}\xspace)}(\ensuremath{s'}\xspace) \ensuremath{d}\xspace\ensuremath{o}\xspace \ensuremath{d}\xspace\ensuremath{s'}\xspace \right | \nonumber \\ &&\leq&\gamma \left ( \left |\ensuremath{\int_{s' \in S}}\xspace \ensuremath{\int_{o \in O}}\xspace \ensuremath{T}\xspace \ensuremath{Z}\xspace \left [\alpha_{\nu(\ensuremath{o}\xspace)}(\ensuremath{s'}\xspace) -\widehat{\alpha}_{\nu(\ensuremath{o}\xspace)}(\ensuremath{s'}\xspace) \right ] \ensuremath{d}\xspace\ensuremath{o}\xspace \ensuremath{d}\xspace\ensuremath{s'}\xspace \right | \right. \nonumber \\ & && + \left. \left |\ensuremath{\int_{s' \in S}}\xspace \ensuremath{\int_{o \in O}}\xspace \widehat{\alpha}_{\nu(\ensuremath{o}\xspace)}(\ensuremath{s'}\xspace) \left [\ensuremath{T}\xspace\ensuremath{Z}\xspace -\ensuremath{\widehat{T}}\xspace \ensuremath{\widehat{Z}}\xspace \right ] \ensuremath{d}\xspace\ensuremath{o}\xspace \ensuremath{d}\xspace\ensuremath{s'}\xspace\right | \right ) \end{align} Let's have a look at the second term on the right-hand side of \eref{eq:first_lemma_0}, that is \begin{align}\label{eq:first_lemma_1} &&term2(\ensuremath{s}\xspace, \ensuremath{a}\xspace) =& \left | \ensuremath{\int_{s' \in S}}\xspace \ensuremath{\int_{o \in O}}\xspace \widehat{\alpha}_{\nu(\ensuremath{o}\xspace)}(\ensuremath{s'}\xspace) \left [\ensuremath{T}\xspace \ensuremath{Z}\xspace - \ensuremath{\widehat{T}}\xspace \ensuremath{\widehat{Z}}\xspace \right ] \ensuremath{d}\xspace\ensuremath{o}\xspace \ensuremath{d}\xspace\ensuremath{s'}\xspace \right | \end{align} We can expand this term as follows: \begin{align}\label{eq:first_lemma_2} &&&term2(\ensuremath{s}\xspace, \ensuremath{a}\xspace) \nonumber \\ &&=& \left | \ensuremath{\int_{s' \in S}}\xspace \ensuremath{\int_{o \in O}}\xspace \widehat{\alpha}_{\nu(\ensuremath{o}\xspace)}(\ensuremath{s'}\xspace) \left [ \ensuremath{T}\xspace \ensuremath{Z}\xspace - \ensuremath{\widehat{T}}\xspace\ensuremath{Z}\xspace + \ensuremath{\widehat{T}}\xspace\ensuremath{Z}\xspace - \ensuremath{\widehat{T}}\xspace \ensuremath{\widehat{Z}}\xspace\right ] \ensuremath{d}\xspace\ensuremath{o}\xspace \ensuremath{d}\xspace\ensuremath{s'}\xspace \right |\nonumber \\ &&\leq& \left | \ensuremath{\int_{s' \in S}}\xspace \left [ \ensuremath{T}\xspace - \ensuremath{\widehat{T}}\xspace\right ] \ensuremath{\int_{o \in O}}\xspace \widehat{\alpha}_{\nu(\ensuremath{o}\xspace)}(\ensuremath{s'}\xspace)\ensuremath{Z}\xspace \ensuremath{d}\xspace\ensuremath{o}\xspace \ensuremath{d}\xspace\ensuremath{s'}\xspace\right | \nonumber \\ & && + \left |\ensuremath{\int_{s' \in S}}\xspace \ensuremath{\widehat{T}}\xspace \ensuremath{\int_{o \in O}}\xspace \widehat{\alpha}_{\nu(\ensuremath{o}\xspace)}(\ensuremath{s'}\xspace)\left [\ensuremath{Z}\xspace - \ensuremath{\widehat{Z}}\xspace \right ] \ensuremath{d}\xspace\ensuremath{o}\xspace\ensuremath{d}\xspace\ensuremath{s'}\xspace\right | \nonumber \\ &&\leq& \ensuremath{\int_{s' \in S}}\xspace \left |\ensuremath{T}\xspace- \ensuremath{\widehat{T}}\xspace \right | \ensuremath{\int_{o \in O}}\xspace \left | \widehat{\alpha}_{\nu(\ensuremath{o}\xspace)}(\ensuremath{s'}\xspace) \right | \ensuremath{Z}\xspace \ensuremath{d}\xspace\ensuremath{o}\xspace\ensuremath{d}\xspace\ensuremath{s'}\xspace \nonumber \\ & && + \ensuremath{\int_{s' \in S}}\xspace \ensuremath{\widehat{T}}\xspace \ensuremath{\int_{o \in O}}\xspace \left | \widehat{\alpha}_{\nu(\ensuremath{o}\xspace)}(\ensuremath{s'}\xspace) \right | \left |\ensuremath{Z}\xspace - \ensuremath{\widehat{Z}}\xspace \right | \ensuremath{d}\xspace\ensuremath{o}\xspace\ensuremath{d}\xspace\ensuremath{s'}\xspace \end{align} The term $\left | \widehat{\alpha}_{\nu(\ensuremath{o}\xspace)}(\ensuremath{s'}\xspace) \right |$ can be upper-bounded via $\left | \widehat{\alpha}_{\nu(\ensuremath{o}\xspace)}(\ensuremath{s'}\xspace)\right | \leq \frac{R_{m}}{1-\gamma}$ for any $\ensuremath{s}\xspace \in \ensuremath{S}\xspace$, which yields \begin{align}\label{eq:first_lemma_3} &&&term2(\ensuremath{s}\xspace, \ensuremath{a}\xspace) \nonumber \\ &&\leq& \frac{R_{m}}{1-\gamma} \left [\ensuremath{\int_{s' \in S}}\xspace \left |\ensuremath{T}\xspace - \ensuremath{\widehat{T}}\xspace \right | \ensuremath{d}\xspace\ensuremath{s'}\xspace + \ensuremath{\int_{s' \in S}}\xspace\ensuremath{\widehat{T}}\xspace\ensuremath{\int_{o \in O}}\xspace\left | \ensuremath{Z}\xspace - \ensuremath{\widehat{Z}}\xspace \right | \ensuremath{d}\xspace\ensuremath{o}\xspace\ensuremath{d}\xspace\ensuremath{s'}\xspace \right ] \end{align} From the definition of the total variation distance, it follows that $\ensuremath{\int_{s' \in S}}\xspace \left | \ensuremath{T}\xspace - \ensuremath{\widehat{T}}\xspace\right |\ensuremath{d}\xspace\ensuremath{s'}\xspace = 2D_{TV}^{\ensuremath{s}\xspace, \ensuremath{a}\xspace}(\ensuremath{T}\xspace, \ensuremath{\widehat{T}}\xspace)$ for any given $\ensuremath{s}\xspace \in \ensuremath{S}\xspace$ and $\ensuremath{a}\xspace \in \ensuremath{A}\xspace$ and $\ensuremath{\int_{o \in O}}\xspace \left |\ensuremath{Z}\xspace - \ensuremath{\widehat{Z}}\xspace \right | \ensuremath{d}\xspace\ensuremath{o}\xspace= 2D_{TV}^{\ensuremath{s'}\xspace, \ensuremath{a}\xspace}(\ensuremath{Z}\xspace, \ensuremath{\widehat{Z}}\xspace)$ for any given $\ensuremath{s'}\xspace \in \ensuremath{S}\xspace$. Substituting these equalities into \eref{eq:first_lemma_3} and taking the supremum over the conditionals $\ensuremath{s}\xspace, \ensuremath{s'}\xspace$ and $\ensuremath{a}\xspace$ allows us to upper-bound \eref{eq:first_lemma_3} by \begin{equation} term2(\ensuremath{s}\xspace, \ensuremath{a}\xspace) \leq 2\frac{R_{m}}{1-\gamma} \nm{\ensuremath{P}\xspace}{\ensuremath{\widehat{P}}\xspace} \end{equation} Substituting this upper bound into \ref{eq:first_lemma_0} yields \begin{align}\label{eq:lemm2_eq_5} &&&\left | \alpha_{\sigma}(\ensuremath{s}\xspace) - \widehat{\alpha}_{\sigma}(\ensuremath{s}\xspace) \right | \nonumber \\ &&\leq& \gamma\biggl | 2\frac{R_{m}}{1-\gamma} \nm{\ensuremath{P}\xspace}{\ensuremath{\widehat{P}}\xspace} \biggr. \nonumber \\ &&&\left. + \ensuremath{\int_{s' \in S}}\xspace\ensuremath{\int_{o \in O}}\xspace \ensuremath{T}\xspace \ensuremath{Z}\xspace \left [\alpha_{\nu(\ensuremath{o}\xspace)}(\ensuremath{s'}\xspace) - \widehat{\alpha}_{\nu(\ensuremath{o}\xspace)}(\ensuremath{s'}\xspace) \right] \ensuremath{d}\xspace\ensuremath{o}\xspace \ensuremath{d}\xspace\ensuremath{s'}\xspace \right | \nonumber \\ &&\leq& \gamma \biggl ( 2 \frac{R_{m}}{1-\gamma} \nm{\ensuremath{P}\xspace}{\ensuremath{\widehat{P}}\xspace} \biggr.\nonumber \\ &&&\left. + \ensuremath{\int_{s' \in S}}\xspace\ensuremath{\int_{o \in O}}\xspace \ensuremath{T}\xspace \ensuremath{Z}\xspace \left |\alpha_{\nu(\ensuremath{o}\xspace)}(\ensuremath{s'}\xspace) - \widehat{\alpha}_{\nu(\ensuremath{o}\xspace)}(\ensuremath{s'}\xspace) \right| \ensuremath{d}\xspace\ensuremath{o}\xspace \ensuremath{d}\xspace\ensuremath{s'}\xspace \right ) \end{align} The last term on the right hand side of \ref{eq:lemm2_eq_5} is essentially a recursion. Unfolding this recursion yiels \begin{equation} \left | \alphaPiS{\ensuremath{s}\xspace} - \alphaPiHatS{\ensuremath{s}\xspace} \right | \leq 2\gamma\frac{R_{m}}{(1-\gamma)^2} \nm{\ensuremath{P}\xspace}{\ensuremath{\widehat{P}}\xspace} \end{equation} which is Lemma \ref{lem:lem0} $\square$ \subsection{Proof of \lref{lem:lemApprox}}\label{ssec:proofLem4} We can write the absolute difference between the SNM\xspace-values conditioned on two states $\ensuremath{s}\xspace_1, \ensuremath{s}\xspace_2 \in \ensuremath{S}\xspace_i$ as \begin{align} &&&\left | \ensuremath{\Psi_T}\xspace(\ensuremath{s}\xspace_1) - \ensuremath{\Psi_T}\xspace(\ensuremath{s}\xspace_2) \right | \nonumber \\ &&=& \left | \sup_{\ensuremath{a}\xspace \in \ensuremath{A}\xspace} D_{TV}(\ensuremath{T}\xspace_1, \ensuremath{\widehat{T}}\xspace_1) - \sup_{\ensuremath{a}\xspace \in \ensuremath{A}\xspace} D_{TV}(\ensuremath{T}\xspace_2, \ensuremath{\widehat{T}}\xspace_2) \right | \nonumber \\ &&=&\left |\frac{1}{2} \sup_{\ensuremath{a}\xspace \in \ensuremath{A}\xspace} \sup_{\left |f \right | \leq 1} \left | \ensuremath{\int_{s' \in S}}\xspace f(\ensuremath{s'}\xspace) \left [\ensuremath{T}\xspace_1 - \ensuremath{\widehat{T}}\xspace_1 \right ] \ensuremath{d}\xspace\ensuremath{s'}\xspace \right| \right. \nonumber \\ &&&\left. - \frac{1}{2} \sup_{\ensuremath{a}\xspace \in \ensuremath{A}\xspace} \sup_{\left |f \right | \leq 1}\left |\ensuremath{\int_{s' \in S}}\xspace f(\ensuremath{s'}\xspace) \left [\ensuremath{T}\xspace_2 - \ensuremath{\widehat{T}}\xspace_2 \right ]\ensuremath{d}\xspace\ensuremath{s'}\xspace\right | \right | \end{align} Manipulating the algebra allows us to write \begin{align}\label{e:lem3_eq2} &&&\left | \ensuremath{\Psi_T}\xspace(\ensuremath{s}\xspace_1) - \ensuremath{\Psi_T}\xspace(\ensuremath{s}\xspace_2) \right | \nonumber \\ &&\leq& \frac{1}{2}\sup_{\ensuremath{a}\xspace\in\ensuremath{A}\xspace}\left | \sup_{\left |f \right | \leq 1} \left ( \ensuremath{\int_{s' \in S}}\xspace f(\ensuremath{s'}\xspace) \left [\ensuremath{T}\xspace_1 - \ensuremath{T}\xspace_2 \right ] \ensuremath{d}\xspace\ensuremath{s'}\xspace \right. \right.\nonumber \\ &&&\left.\left. + \ensuremath{\int_{s' \in S}}\xspace f(\ensuremath{s'}\xspace)\left [\ensuremath{\widehat{T}}\xspace_1 - \ensuremath{\widehat{T}}\xspace_2 \right] \ensuremath{d}\xspace\ensuremath{s'}\xspace \right ) \right |\nonumber \\ &&\leq& \frac{1}{2}\sup_{\ensuremath{a}\xspace \in \ensuremath{A}\xspace} \left (\sup_{\left |f \right | \leq 1}\ensuremath{\int_{s' \in S}}\xspace f(\ensuremath{s'}\xspace) \left |\ensuremath{T}\xspace_1 - \ensuremath{T}\xspace_2 \right | \ensuremath{d}\xspace\ensuremath{s'}\xspace \right. \nonumber \\ &&&\left. + \sup_{\left |f \right | \leq 1} \ensuremath{\int_{s' \in S}}\xspace f(\ensuremath{s'}\xspace) \left |\ensuremath{\widehat{T}}\xspace_1 - \ensuremath{\widehat{T}}\xspace_2 \right |\ensuremath{d}\xspace\ensuremath{s'}\xspace\right ) \nonumber \\ &&\leq& \frac{1}{2}D_{S}(\ensuremath{s}\xspace_1, \ensuremath{s}\xspace_2)\left [C_{\ensuremath{T}\xspace_i} + C_{\ensuremath{\widehat{T}}\xspace_i} \right ] \end{align} For the last inequality we bound the terms $\left | \ensuremath{T}\xspace_1 - \ensuremath{T}\xspace_2 \right |$ and $\left |\ensuremath{\widehat{T}}\xspace_1 - \ensuremath{\widehat{T}}\xspace_2 \right |$ using \dref{d:partition}. Furthermore we use the fact that $\sup_{\left |f \right | \leq 1} \ensuremath{\int_{s' \in S}}\xspace f(\ensuremath{s'}\xspace) \ensuremath{d}\xspace\ensuremath{s'}\xspace = 1$, assuming that the state space $\ensuremath{S}\xspace$ is normalized. This concludes the proof of \lref{lem:lemApprox}. $\square$ \section{Introduction } \label{section:introduction} An autonomous robot must be able to compute reliable motion strategies, despite various errors in actuation and prediction on its effect on the robot and its environment, and despite various errors in sensors and sensing. Computing such robust strategies is computationally hard even for a 3 DOFs point robot\ccite{Can87:New},\ccite{Nat88:Complexity}. Conceptually, this problem can be solved in a systematic and principled manner when framed as the Partially Observable Markov Decision Process (POMDP)\ccite{Kae98:Planning}. A POMDP represents the aforementioned errors as probability distribution functions and estimates the state of the system as probability distribution functions called \emph{beliefs}. It then computes the best motion strategy with respect to beliefs rather than single states, thereby accounting the fact that the actual state is never known due to the above errors. Although the concept of POMDPs was proposed in the '60s\ccite{Son71:The}, only recently that POMDPs started to become practical for robotics problems (e.g.\ccite{Hoe19:POMDP,Hor13:Interactive,Tem09:Unmanned}). This advancement is achieved by trading optimality with approximate optimality for speed and memory. But even then, in general, computing close to optimal POMDP solutions for systems with complex dynamics remains difficult. Several general POMDP solvers ---solvers that do not restrict the type of dynamics and sensing model of the system, nor the type of distributions used to represent uncertainty--- can now compute good motion strategies on-line with a 1-10Hz update rate for a number of robotic problems\ccite{Kur13:An,Sil10:Monte,Som13:Despot,Sei15:An}. However, their speed degrades when the robot has complex non-linear dynamics. To compute a good strategy, today's POMDP solvers forward simulate the effect of many sequences of actions from different beliefs are simulated. For problems whose dynamics have no closed-form solutions, a simulation run generally invokes many numerical integrations, and complex dynamics tend to increase the cost of each numerical integration, which in turn significantly increases the total planning cost of these methods. Of course, this cost will increase even more for problems that require more or longer simulation runs, such as in problems with long planning horizons. Many linearized-based POMDP solvers have been proposed\ccite{Sun15:High,Agh13:Firm,Ber10:LQGMP,Ber12:LQG,Pre10:The}. They rely on many forward simulations from different beliefs too, but use a linearized model of the dynamics and sensing for simulation. Together with linearization, many of these methods assume that beliefs are Gaussian distributions. This assumption improves the speed of simulation further, because the subsequent belief after an action is performed and an observation is perceived can be computed in closed-form. In contrast, the aforementioned general solvers typically represent beliefs as sets of particles and estimate subsequent beliefs using particle filters. Particle filters are particularly expensive when particle trajectories have to be simulated and each simulation run is costly, as is the case for motion-planning of systems with complex dynamics. As a result, the linearization-based planners require less time to estimate the effect of performing a sequence of actions from a belief, and therefore can \emph{potentially} find a good strategy faster than the general method. However, it is known that linearization in control and estimation performs well only when the system's non-linearity is ``weak"\ccite{Li12:Measure}. The question is, what constitute ``weak" non-linearity in motion planning under uncertainty? Where will it be useful and where will it be damaging to use linearization (and Gaussian) simplifications? This paper extends our previous work\ccite{Hoe16:Linearization} towards answering the aforementioned questions. Specifically, we propose a measure of non-linearity for stochastic systems, called \emph{Statistical-distance-based Non-linearity Measure\xspace (SNM\xspace)}, to help identify the suitability of linearization in a given problem of motion planning under uncertainty. SNM\xspace is based on the total variation distance between the original dynamics and sensing models, and their corresponding linearized models. It is general enough to be applied to any type of motion and sensing errors, and any linearization technique, regardless of the type of approximation of the true beliefs (e.g., with and without Gaussian simplification). We show that the difference between the value of the optimal strategy generated if we plan using the original model and if we plan using the linearized model, can be upper bounded by a function linear in SNM\xspace. Furthermore, our experimental results indicate that compared to recent state-of-the-art methods of non-linearity measures for stochastic systems, SNM\xspace is more sensitive to the effect that obstacles have on the effectiveness of linearization, which is critical for motion planning. To further test the applicability of SNM\xspace in motion planning, we develop a simple on-line planner that uses a local estimate of SNM\xspace to automatically switch between a general planner\ccite{Kur13:An} that uses the original POMDP model and a linearization-based planner (adapted from\ccite{Sun15:High}) that uses the linearized model. Experimental results on a car-like robot with acceleration control, and a 4-DOFs and 6-DOFs manipulators with torque control indicate that this simple planner can appropriately decide if and when linearization should be used and therefore computes better strategies faster than each of the component planner. \section{Acknowledgements} This work is partially funded by ANU Futures Scheme QCE20102. The early part of this work is funded by UQ and CSIRO scholarship for Marcus Hoerger. \bibliographystyle{ieeetr} \section{SNM}\label{sec:SNM} Intuitively, our proposed measure SNM\xspace is based on the total variation distance between the effect of performing an action and perceiving an observation under the true dynamics and sensing model, and the effect under the linearized dynamic and sensing model. The total variation distance $D_{TV}$ between two probability measures $\mu$ and $\nu$ over a measurable space $\Omega$ is defined as $D_{TV}(\mu, \nu) = \sup_{E \in \Omega} \left |\mu(E) - \nu(E) \right |$. An alternative expression of $D_{TV}$ which we use throughout the paper is the functional form $D_{TV}(\mu, \nu) = \frac{1}{2}\sup_{\left |f \right | \leq 1}\left |\int f\ensuremath{d}\xspace\mu - \int f\ensuremath{d}\xspace\nu \right |$. Formally, SNM\xspace is defined as: \begin{definition} \label{def:mon} Let $\ensuremath{P}\xspace = \ensuremath{\langle S, A, O, T, Z, R, \ensuremath{b_0}\xspace, \gamma \rangle}\xspace$ be the POMDP model of the system and $\ensuremath{\widehat{P}}\xspace = \ensuremath{\langle S, A, O, \widehat{T}, \widehat{Z}, R, \ensuremath{b_0}\xspace, \gamma \rangle}\xspace$ be a linearization of \ensuremath{P}\xspace, where \ensuremath{\widehat{T}}\xspace is a linearization of the transition function \ensuremath{T}\xspace and \ensuremath{\widehat{Z}}\xspace is a linearization of the observation function \ensuremath{Z}\xspace of \ensuremath{P}\xspace, while all other components of \ensuremath{P}\xspace and \ensuremath{\widehat{P}}\xspace are the same. Then, the SNM\xspace (denoted as \ensuremath{\Psi}\xspace) between \ensuremath{P}\xspace and \ensuremath{\widehat{P}}\xspace is $\nm{\ensuremath{P}\xspace}{\ensuremath{\widehat{P}}\xspace} = \nmT{\ensuremath{P}\xspace}{\ensuremath{\widehat{P}}\xspace} + \nmZ{\ensuremath{P}\xspace}{\ensuremath{\widehat{P}}\xspace}$, where \begin{align} \nmT{\ensuremath{P}\xspace}{\ensuremath{\widehat{P}}\xspace} &= \sup_{s \in S, a \in A} D_{TV}(\ensuremath{T(s, a, s')}\xspace, \ensuremath{\widehat{T}(s, a, s')}\xspace) \\ \nmZ{\ensuremath{P}\xspace}{\ensuremath{\widehat{P}}\xspace} &= \sup_{s \in S, a \in A} D_{TV}(\ensuremath{Z(s, a, o)}\xspace, \ensuremath{\widehat{Z}(s, a, o)}\xspace) \end{align} \end{definition} Note that SNM\xspace can be applied as both a global and a local measure. In the latter case, the supremum over the state $s$ can be restricted to a subset of \ensuremath{S}\xspace, rather than the entire state space. Furthermore, SNM\xspace is general enough for any approximation to the true dynamics and sensing model, which means that it can be applied to any type of linearization and belief approximation techniques, including those that assume and those that do not assume Gaussian belief simplifications. We want to use the measure \nm{\ensuremath{P}\xspace}{\ensuremath{\widehat{P}}\xspace} to bound the difference between the expected total reward received if the system were to run the optimal policy of the true model \ensuremath{P}\xspace and if it were to run the optimal policy of the linearized model \ensuremath{\widehat{P}}\xspace. Note that since our interest is in the actual reward received, the values of these policies are evaluated with respect to the original model \ensuremath{P}\xspace (we assume \ensuremath{P}\xspace is a faithful model of the system). More precisely, we want to show that: \begin{theorem}\label{th:valUpperBound} If \ensuremath{\pi^*}\xspace denotes the optimal policy for \ensuremath{P}\xspace and \ensuremath{\widehat{\pi}^*}\xspace denotes the optimal policy for \ensuremath{\widehat{P}}\xspace, then for any $\ensuremath{b}\xspace\in\mathbb{B}$, \begin{align} &V_{\ensuremath{\pi^*}\xspace}(\ensuremath{b}\xspace) - V_{\ensuremath{\widehat{\pi}^*}\xspace}(\ensuremath{b}\xspace) \leq 4\gamma\frac{R_{max}}{(1-\gamma)^2} \nm{\ensuremath{P}\xspace}{\ensuremath{\widehat{P}}\xspace} \nonumber \end{align} where \newline $V_{\pi}(b) = R(b, \pi(b)) + \gamma \int_{o \in O}Z(b, a, o)V_{\pi}(\tau(b, a, o)) \ensuremath{d}\xspace\ensuremath{o}\xspace$ for any policy $\pi$ and $\tau(b, a, o)$ is the belief transition function as defined in \eref{e:belTrans} \end{theorem} To proof \thref{th:valUpperBound}, we first assume, without loss of generality, that a policy $\pi$ for a belief \ensuremath{b}\xspace is represented by a conditional plan $\sigma\in\Gamma$, where $\Gamma$ is the set of all conditional plans. $\sigma$ can be specified by a pair $\left \langle \ensuremath{a}\xspace, \nu \right \rangle$, where $\ensuremath{a}\xspace\in\ensuremath{A}\xspace$ is the action of $\sigma$ and $\nu: \ensuremath{O}\xspace \rightarrow \Gamma$ is an observation strategy which maps an observation to a conditional plan $\sigma'\in\Gamma$. Every $\sigma$ corresponds to an $\alpha$-function $\alpha_{\sigma}: \ensuremath{S}\xspace \rightarrow \mathbb{R}$ which specifies the expected total discounted reward the robot receives when executing $\sigma$ starting from $\ensuremath{s}\xspace\in\ensuremath{S}\xspace$, i.e. \begin{align}\label{eq:alpha_s} &\alpha_{\sigma}(s) = \rewFuncComp{\ensuremath{s}\xspace}{\ensuremath{a}\xspace}\nonumber\\ &+ \gamma \ensuremath{\int_{s' \in S}}\xspace \ensuremath{\int_{o \in O}}\xspace T(\ensuremath{s}\xspace, \ensuremath{a}\xspace, \ensuremath{s'}\xspace) Z(\ensuremath{s'}\xspace, \ensuremath{a}\xspace, \ensuremath{o}\xspace)\alpha_{\nu(\ensuremath{o}\xspace)}(\ensuremath{s'}\xspace) \ensuremath{d}\xspace\ensuremath{o}\xspace \ensuremath{d}\xspace\ensuremath{s'}\xspace \end{align} where $\ensuremath{a}\xspace\in\ensuremath{A}\xspace$ is the action of $\sigma$ and $\alpha_{\nu(\ensuremath{o}\xspace)}$ is the $\alpha$-function corresponding to conditional plan $\nu(\ensuremath{o}\xspace)$. For a given belief \ensuremath{b}\xspace, the value of the policy $\pi$ represented by the conditional plan $\sigma$ is then $V_{\pi}(\ensuremath{b}\xspace) = \int_{\ensuremath{s}\xspace\in\ensuremath{S}\xspace} \ensuremath{b}\xspace(\ensuremath{s}\xspace)\alpha_{\sigma}(\ensuremath{s}\xspace)\ensuremath{d}\xspace\ensuremath{s}\xspace$. Note that \eref{eq:alpha_s} is defined with respect to POMDP \ensuremath{P}\xspace. Analogously we define the linearized $\alpha$-function $\widehat{\alpha}_{\sigma}$ with respect to the linearized POMDP \ensuremath{\widehat{P}}\xspace by replacing the transition and observation functions in \eref{eq:alpha_s} with their linearized versions. Now, suppose that for a given belief \ensuremath{b}\xspace, $\sigma^* = \argsup_{\sigma\in\Gamma} \int_{\ensuremath{s}\xspace\in\ensuremath{S}\xspace}\ensuremath{b}\xspace(\ensuremath{s}\xspace)\alpha_{\sigma}(\ensuremath{s}\xspace)\ensuremath{d}\xspace\ensuremath{s}\xspace$ and $\widehat{\sigma}^* = \argsup_{\sigma\in\Gamma}\int_{\ensuremath{s}\xspace\in\ensuremath{S}\xspace}\ensuremath{b}\xspace(\ensuremath{s}\xspace)\widehat{\alpha}_{\sigma}(\ensuremath{s}\xspace)\ensuremath{d}\xspace\ensuremath{s}\xspace$. $\sigma^*$ and $\widehat{\sigma}^*$ represent the policies $\pi^*$ and $\widehat{\pi}^*$ that are optimal at \ensuremath{b}\xspace for POMDP \ensuremath{P}\xspace and \ensuremath{\widehat{P}}\xspace respectively. For any $\ensuremath{s}\xspace\in\ensuremath{S}\xspace$ we have that $\alphaFunctPolComp{\widehat{\sigma}^*}{\ensuremath{s}\xspace} \geq \linAlphaFunctPolComp{\widehat{\sigma}^*}{\ensuremath{s}\xspace} - \left |\alphaFunctPolComp{\widehat{\sigma}^*}{\ensuremath{s}\xspace} - \linAlphaFunctPolComp{\widehat{\sigma}^*}{\ensuremath{s}\xspace} \right |$ and $\linAlphaFunctPolComp{\sigma^*}{\ensuremath{s}\xspace} \geq \alphaFunctPolComp{\sigma^*}{\ensuremath{s}\xspace} - \left | \alphaFunctPolComp{\sigma^*}{\ensuremath{s}\xspace} - \linAlphaFunctPolComp{\sigma^*}{\ensuremath{s}\xspace}\right |$. Therefore \begin{align}\label{eq:geq_1} \int_{s \in S}\xspace \belS{\ensuremath{s}\xspace} \alphaFunctPolComp{\widehat{\sigma}^*}{\ensuremath{s}\xspace} \ensuremath{d}\xspace\ensuremath{s}\xspace \geq &\int_{s \in S}\xspace \belS{\ensuremath{s}\xspace} \linAlphaFunctPolComp{\widehat{\sigma}^*}{\ensuremath{s}\xspace} \ensuremath{d}\xspace\ensuremath{s}\xspace\nonumber \\ & - \int_{s \in S}\xspace \belS{\ensuremath{s}\xspace} \left | \alphaFunctPolComp{\widehat{\sigma}^*}{\ensuremath{s}\xspace} - \linAlphaFunctPolComp{\widehat{\sigma}^*}{\ensuremath{s}\xspace} \right | \ensuremath{d}\xspace\ensuremath{s}\xspace \end{align} and \begin{align}\label{eq:geq_2} \int_{s \in S}\xspace \belS{\ensuremath{s}\xspace} \linAlphaFunctPolComp{\sigma^*}{\ensuremath{s}\xspace} \ensuremath{d}\xspace\ensuremath{s}\xspace \geq &\int_{s \in S}\xspace \belS{\ensuremath{s}\xspace}\alphaFunctPolComp{\sigma^*}{\ensuremath{s}\xspace} \ensuremath{d}\xspace\ensuremath{s}\xspace\nonumber \\&- \int_{s \in S}\xspace \belS{\ensuremath{s}\xspace}\left |\alphaFunctPolComp{\sigma^*}{\ensuremath{s}\xspace} - \linAlphaFunctPolComp{\sigma^*}{\ensuremath{s}\xspace} \right |\ensuremath{d}\xspace\ensuremath{s}\xspace \end{align} Since $\widehat{\sigma}^*$ is the optimal conditional plan for POMDP \ensuremath{\widehat{P}}\xspace at \ensuremath{b}\xspace, we also know that \begin{equation}\label{eq:geq_3} \int_{s \in S}\xspace \belS{\ensuremath{s}\xspace} \linAlphaFunctPolComp{\widehat{\sigma}^*}{\ensuremath{s}\xspace} \ensuremath{d}\xspace\ensuremath{s}\xspace \geq \int_{s \in S}\xspace \belS{\ensuremath{s}\xspace} \linAlphaFunctPolComp{\sigma^*}{\ensuremath{s}\xspace} \ensuremath{d}\xspace\ensuremath{s}\xspace \end{equation} From \eref{eq:geq_1}, \eref{eq:geq_2} and \eref{eq:geq_3} it immediately follows that \begin{alignat}{2}\label{eq:geq_4} \int_{s \in S}\xspace \belS{\ensuremath{s}\xspace} \alphaFunctPolComp{\widehat{\sigma}^*}{\ensuremath{s}\xspace} \ensuremath{d}\xspace\ensuremath{s}\xspace \geq & &&\int_{s \in S}\xspace \belS{\ensuremath{s}\xspace} \alphaFunctPolComp{\sigma^*}{\ensuremath{s}\xspace} \ensuremath{d}\xspace\ensuremath{s}\xspace \nonumber \\ & && - 2 \int_{s \in S}\xspace \belS{\ensuremath{s}\xspace}\sup_{\sigma\in\Gamma}\left |\alphaFunctPolComp{\sigma}{\ensuremath{s}\xspace} - \linAlphaFunctPolComp{\sigma}{\ensuremath{s}\xspace} \right |\ensuremath{d}\xspace\ensuremath{s}\xspace \nonumber \\ V_{\widehat{\pi}^*}(b) \geq& && V_{\pi^*}(b) \nonumber \\ & &&- 2 \int_{s \in S}\xspace \belS{\ensuremath{s}\xspace}\sup_{\sigma\in\Gamma}\left |\alphaFunctPolComp{\sigma}{\ensuremath{s}\xspace} - \linAlphaFunctPolComp{\sigma}{\ensuremath{s}\xspace} \right | \ensuremath{d}\xspace\ensuremath{s}\xspace \end{alignat} Before we continue, we first have to show the following Lemma: \begin{lemma}\label{lem:lem0} Let $R_m = \max\{\left |R_{min} \right |, R_{max}\}$, where $R_{min} = \min_{s,a} R(s, a)$ and $R_{max} = \max_{s,a} R(s, a)$. For any conditional plan $\sigma\in\Gamma$ and any $\ensuremath{s}\xspace \in \ensuremath{S}\xspace$, the absolute difference between the original and linearized $\alpha$-functions is upper bounded by \begin{align} \left | \alphaFunctPolComp{\sigma}{\ensuremath{s}\xspace} - \linAlphaFunctPolComp{\sigma}{\ensuremath{s}\xspace} \right | \leq 2\gamma\frac{R_{m}}{(1-\gamma)^2} \nm{\ensuremath{P}\xspace}{\ensuremath{\widehat{P}}\xspace}\nonumber \end{align} \end{lemma} The proof of \lref{lem:lem0} is presented in the Appendix~\ref{ssec:lemma_0_proof}. Using the result of \lref{lem:lem0}, we can now conclude the proof for \thref{th:valUpperBound}. Substituting the upper bound derived in \lref{lem:lem0} into the right-hand side of \eref{eq:geq_4} and re-arranging the terms gives us \begin{equation} V_{\pi^*}(\ensuremath{b}\xspace) - V_{\widehat{\pi}^*}(\ensuremath{b}\xspace) \leq 4\gamma\frac{R_{m}}{(1-\gamma)^2} \nm{\ensuremath{P}\xspace}{\ensuremath{\widehat{P}}\xspace} \end{equation} which is what we are looking for. $\square$ \section{Approximating SNM\xspace}\label{ssec:monApprox} Now, the question is how can we compute SNM\xspace sufficiently fast, so that this measure can be used as a heuristic during on-line planning to decide when a linearization-based solver will likely yield a good policy and when a general solver should be used. Unfortunately, such a computation is often infeasible when the planning time per step is limited. Therefore, we approximate SNM\xspace off-line and re-use the results during run-time. Here we discuss how to approximate the transition component \ensuremath{\Psi_T}\xspace of SNM\xspace, however, the same method applies to the observation component \ensuremath{\Psi_Z}\xspace. Let us first rewrite the transition component of \ensuremath{\Psi_T}\xspace as \begin{align}\label{e:snmTransCompRe} \ensuremath{\Psi_T}\xspace &= \sup_{\ensuremath{s}\xspace \in \ensuremath{S}\xspace} \ensuremath{\Psi_T}\xspace(s)\nonumber \\&= \sup_{\ensuremath{s}\xspace\in\ensuremath{S}\xspace}\sup_{\ensuremath{a}\xspace\in\ensuremath{A}\xspace}D_{TV}(\ensuremath{T(s, a, s')}\xspace, \ensuremath{\widehat{T}(s, a, s')}\xspace) \end{align} where $\ensuremath{\Psi_T}\xspace(s)$ is the transition component of SNM\xspace, given a particular state. To approximate \ensuremath{\Psi_T}\xspace, we replace \ensuremath{S}\xspace in \eref{e:snmTransCompRe} by a sampled representation of \ensuremath{S}\xspace, which we denote as $\tilde{\ensuremath{S}\xspace}$. The value $\ensuremath{\Psi_T}\xspace(s)$ is then evaluated for each $\ensuremath{s}\xspace\in\tilde{\ensuremath{S}\xspace}$ off-line, and the results are saved in a lookup-table. This lookup-table can then be used during run-time to get a local approximation of \ensuremath{\Psi_T}\xspace around the current belief. The first question that arises is, how do we efficiently sample the state space? A naive approach would be to employ a simple uniform sampling strategy. However, for large state spaces this is often wasteful, because for motion planning problems, large portions of the state space are often irrelevant since they either can't be reached from the initial belief or are unlikely to be traversed by the robot during run-time. A better strategy is to consider only the subset of the state space that is reachable from the support set of the initial belief under any policy, denoted as $\ensuremath{S}\xspace_{\ensuremath{b_0}\xspace}$. To sample from $\ensuremath{S}\xspace_{\ensuremath{b_0}\xspace}$, we use a simple but effective method: Assuming deterministic dynamics, we solve the motion planning problem off-line using kinodynamic RRTs and use the nodes in the RRT-trees as a sampled representation of $\ensuremath{S}\xspace_{\ensuremath{b_0}\xspace}$. In principle any deterministic sampling-based motion planner can be used to generate samples from $\ensuremath{S}\xspace_{\ensuremath{b_0}\xspace}$, however, in our case RRT is a particularly suitable due to its space-filling property \ccite{kuffner2011space}. Note that RRT generates states according to a deterministic transition function only. If required, one could also generate additional samples according to the actual stochastic transition function of the robot. However, in our experiments the state samples generated by RRT were sufficient. The second difficulty in approximating $\ensuremath{\Psi_T}\xspace(s)$ is the computation of the supremum over the action space. Similar to restricting the approximation to a discrete set of states reachable from the initial belief, we can impose a discretization on the action space which leaves us with a maximization over discrete actions, denoted as $\tilde{\ensuremath{A}\xspace}$. Using the set $\tilde{A}$, we approximate \eref{e:snmTransCompRe} for each state in $\tilde{\ensuremath{S}\xspace}_{\ensuremath{b_0}\xspace}$ ---the sampled set of $\ensuremath{S}\xspace_{\ensuremath{b_0}\xspace}$--- as follows: Given a particular state $\ensuremath{s}\xspace \in \tilde{\ensuremath{S}\xspace}_{\ensuremath{b_0}\xspace}$ and action $\ensuremath{a}\xspace \in \tilde{\ensuremath{A}\xspace}$, we draw $n$ samples from the original and linearized transition function and construct a multidimensional histogram from both sample sets. In other words, we discretize the distributions that follow from the original and linearized transition function, given a particular state and action. Suppose the histogram consists of $k$ bins. The value $\ensuremath{\Psi_T}\xspace(\ensuremath{s}\xspace, \ensuremath{a}\xspace)$ is then approximated as \begin{equation}\label{eq:smmTransCompStAct} \ensuremath{\Psi_T}\xspace(\ensuremath{s}\xspace, \ensuremath{a}\xspace) \approx \frac{1}{2} \sum_{i = 1}^{k} \left |p_i - \widehat{p}_i \right | \end{equation} where $p_i = \frac{n_i}{\sum_{j=1}^k n_j}$ and $n_i$ is the number of states inside bin $i$ sampled from the original transition function, while $\widehat{p}_i = \frac{\widehat{n}_i}{\sum_{j=1}^k \widehat{n}_j}$ and $\widehat{n}_i$ is the number of states inside bin $i$ sampled from the linearized transition function. The right-hand side of \eref{eq:smmTransCompStAct} is simply the definition of the total variation distance between two discrete distributions. By repeating the above process for each action in $\tilde{A}$ and taking the maximum, we end up with an approximation of $\ensuremath{\Psi_T}\xspace(s)$. This procedure is repeated for every state in the set $\tilde{\ensuremath{S}\xspace}_{\ensuremath{b_0}\xspace}$. As a result we get a lookup-table, assigning each state in $\tilde{\ensuremath{S}\xspace}_{\ensuremath{b_0}\xspace}$ an approximated value of $\ensuremath{\Psi_T}\xspace(s)$. During planning, we can use the lookup-table and a sampled representation of a belief \ensuremath{b}\xspace to approximate SNM\xspace at \ensuremath{b}\xspace. Suppose $\tilde{\ensuremath{b}\xspace}$ is the sampled representation of \ensuremath{b}\xspace (e.g., a particle set), then for each state $s \in \tilde{\ensuremath{b}\xspace}$, we take the state $\ensuremath{s}\xspace_{near} \in \tilde{\ensuremath{S}\xspace}_{\ensuremath{b_0}\xspace}$ that is nearest to $s$, and assign $\ensuremath{\Psi_T}\xspace(s) = \ensuremath{\Psi_T}\xspace(\ensuremath{s}\xspace_{near})$. The maximum SNM value $\max_{s \in \tilde{\ensuremath{b}\xspace}} \ensuremath{\Psi_T}\xspace(s)$ gives us an approximation of the transition component of SNM\xspace with respect to the belief \ensuremath{b}\xspace. Clearly this approximation method assumes that states that are close together should yield similar values for SNM\xspace. At first glance this is a very strong assumption. In the vicinity of obstacles or constraints, states that are close together could potentially yield very different SNM\xspace values. However, we will now show that under mild assumptions, pairs of states that are elements within certain subsets of the state space indeed yield similar SNM\xspace values. Consider a partitioning of the state space into a finite number of local-Lipschitz subsets $S_i$ that are defined as follows: \begin{definition}\label{d:partition} Let \ensuremath{S}\xspace be a metric space with distance metric $D_{\ensuremath{S}\xspace}$. $\ensuremath{S}\xspace_i$ is called a local-Lipschitz subset of $\ensuremath{S}\xspace$ if for any $\ensuremath{s}\xspace_1, \ensuremath{s}\xspace_2 \in \ensuremath{S}\xspace_i$, any $\ensuremath{s'}\xspace \in \ensuremath{S}\xspace$ and any $\ensuremath{a}\xspace \in \ensuremath{A}\xspace: \left |\ensuremath{T}\xspace(\ensuremath{s}\xspace_1, \ensuremath{a}\xspace, \ensuremath{s'}\xspace) - \ensuremath{T}\xspace(\ensuremath{s}\xspace_2, \ensuremath{a}\xspace, \ensuremath{s'}\xspace) \right | \leq C_{\ensuremath{T}\xspace_i}D_{\ensuremath{S}\xspace}(\ensuremath{s}\xspace_1, \ensuremath{s}\xspace_2)$ and $\left |\ensuremath{\widehat{T}}\xspace(\ensuremath{s}\xspace_1, \ensuremath{a}\xspace, \ensuremath{s'}\xspace) - \ensuremath{\widehat{T}}\xspace(\ensuremath{s}\xspace_2, \ensuremath{a}\xspace, \ensuremath{s'}\xspace) \right | \leq C_{\ensuremath{\widehat{T}}\xspace_i}D_{\ensuremath{S}\xspace}(\ensuremath{s}\xspace_1, \ensuremath{s}\xspace_2)$, where $C_{\ensuremath{T}\xspace_i} \geq 0$ and $C_{\ensuremath{\widehat{T}}\xspace_i} \geq 0$ are finite local-Lipschitz constants \end{definition} In other words, $\ensuremath{S}\xspace_i$ are subsets of $\ensuremath{S}\xspace$ in which the original and linearized transition functions are Lipschitz continuous with Lipschitz constants $C_{\ensuremath{T}\xspace_i}$ and $C_{\ensuremath{\widehat{T}}\xspace_i}$. With this definition at hand, we can now show the following lemma: \begin{lemma}\label{lem:lemApprox} Let \ensuremath{S}\xspace be a $n-dimensional$ metric space with distance metric $D_{\ensuremath{S}\xspace}$ and assume \ensuremath{S}\xspace is normalized to $\left [0, 1 \right ]^n$. Furthermore let $\ensuremath{S}\xspace_i$ be a local-Lipschitz subset of \ensuremath{S}\xspace, then \begin{equation} \left | \ensuremath{\Psi_T}\xspace(\ensuremath{s}\xspace_1) - \ensuremath{\Psi_T}\xspace(\ensuremath{s}\xspace_2) \right | \leq \frac{1}{2} \sqrt{n} D_{\ensuremath{S}\xspace}(\ensuremath{s}\xspace_1, \ensuremath{s}\xspace_2) \left [C_{\ensuremath{T}\xspace_i} + C_{\ensuremath{\widehat{T}}\xspace_i} \right ] \nonumber \end{equation} for any $\ensuremath{s}\xspace_1, \ensuremath{s}\xspace_2 \in S_i$ \label{l:subsetLipschitz} \end{lemma} The proof for this Lemma is presented in \appref{ssec:proofLem4}. This Lemma indicates that the difference between the SNM\xspace values for two states from the same local-Lipschitz subset $\ensuremath{S}\xspace_i$ depends only on the distance $D_{\ensuremath{S}\xspace}$ between them, since $C_{\ensuremath{T}\xspace_i}$ and $C_{\ensuremath{\widehat{T}}\xspace_i}$ are constant for each subset $\ensuremath{S}\xspace_i$. Thus, as the distance between two states converges towards zero, the SNM\xspace value difference converges towards zero as well. This implies that we can approximate SNM for a sparse, sampled representation of $\ensuremath{S}\xspace_{\ensuremath{b_0}\xspace}$ and re-use these approximations on-line with a small error, without requiring an explicit representation of the $\ensuremath{S}\xspace_i$ subsets. \section{SNM-Planner: An Application of SNM\xspace for Planning} \label{sec:method} SNM-Planner\xspace is an on-line planner that uses SNM\xspace as a heuristic to decide whether a general, or a linearization-based POMDP solver should be used to compute the policy from the current belief. The general solver used is Adaptive Belief Tree (ABT)\ccite{Kur13:An}, while the linearization-based method called Modified High Frequency Replanning (MHFR), which is an adaptation of HFR\ccite{Sun15:High}. HFR is designed for chance-constraint POMDPs, i.e., it explicitly minimizes the collision probability, while MHFR is a POMDP solver where the objective is to maximize the expected total reward. An overview of SNM-Planner\xspace is shown in \aref{alg:smnd}. During run-time, at each planning step, SNM-Planner\xspace computes a local approximation of SNM\xspace around the current belief $\ensuremath{b}\xspace_i$ (line 5). If this value is smaller than a given threshold, SNM-Planner\xspace uses MHFR to compute a policy from the current belief, whereas ABT is used when the value exceeds the threshold (line 8-12). The robot then executes an action according the computed policy (line 13) and receives and observation (line 14). Based on the executed action and perceived observation, we update the belief (line 15). SNM-Planner\xspace represents beliefs as sets of particles and updates the belief using a SIR particle filter\ccite{arulampalam2002tutorial}. Note that MHFR assumes that beliefs are multivariate Gaussian distributions. Therefore, in case MHFR is used for the policy computation, we compute the first two moments (mean and covariance) of the particle set to obtain a multivariate Gaussian approximation of the current belief. The process then repeats from the updated belief until the robot has entered a terminal state (we assume that we know when the robot enters a terminal state) or until a maximum number of steps is reached. In the following two subsections we provide a brief an overview of the two component planners ABT and MHFR. \begin{algorithm} \caption{SNM-Planner\xspace (initial belief \ensuremath{b_0}\xspace, SNM\xspace threshold $\mu$, max. planning time per step $t$, max. number of steps $N$)}\label{alg:smnd} \begin{algorithmic}[1] \State InitializeABT(\ensuremath{P}\xspace) \State InitializeMHFR(\ensuremath{P}\xspace) \State $i=0$, $\ensuremath{b}\xspace_i = \ensuremath{b_0}\xspace$, terminal = False \While{terminal is False and $i < N$} \State $\widehat{\Psi} =\ $approximateSNM($\ensuremath{b}\xspace_i$) \State $t_p = t - t_a$ \Comment $t_{a}$ is the time the algorithm takes to approximate SNM\xspace \If{$\widehat{\Psi} < \mu$} \State $a =\ $MHFR($\ensuremath{b}\xspace_i$, $t_p$) \Else \State $a =\ $ABT($\ensuremath{b}\xspace_i$, $t_p$) \EndIf \State terminal = executeAction($a$) \State $o =\ $get observation \State $b_{i+1} = \tau(\ensuremath{b}\xspace_i, a, o)$ \State $i = i + 1$ \EndWhile \end{algorithmic} \end{algorithm} \subsection{Adaptive Belief Tree (ABT)}\label{ssec:ABT} ABT is a general and anytime on-line POMDP solver based on Monte-Carlo-Tree-Search (MCTS). ABT updates (rather than recomputes) its policy at each planning step. To update the policy for the current belief, ABT iteratively constructs and maintains a belief tree, a tree whose nodes are beliefs and whose edges are pairs of actions and observations. ABT evaluates sequences of actions by sampling episodes, that is, sequences of state-–action-–observation-–reward tuples, starting from the current belief. Details of ABT can be found in\ccite{Kur13:An}. \subsection{Modified High-Frequency Replanning (MHFR)}\label{ssec:MHFR} The main difference between HFR and MHFR is that HFR is designed for chance constraint POMDP, i.e., it explicitly minimizes the collision probability, while MHFR is a POMDP solver, whose objective is to maximize the expected total reward. Similar to HFR, MHFR approximates the current belief by a multivariate Gaussian distribution. To compute the policy from the current belief, MHFR samples a set of trajectories from the mean of the current belief to a goal state using multiple instances of RRTs\ccite{kuffner2011space} in parallel. It then computes the expected total discounted reward of each trajectory by tracking the beliefs around the trajectory using a Kalman Filter, assuming maximum-likelihood observations. The policy then becomes the first action of the trajectory with the highest expected total discounted reward. After executing the action and perceiving an observation, MHFR updates the belief using an Extended Kalman Filter. The process then repeats from the updated belief. To increase efficiency, MHFR additionally adjusts the previous trajectory with the highest expected total discounted reward to start from the mean of the updated belief and adds this trajectory to the set of sampled trajectories. More details on HFR and precise derivations of the method are available in\ccite{Sun15:High}. \section{Background and Related Work}\label{sec:relWork} \subsection{Background} In this paper, we consider motion planning problems, in which a robot must move from a given initial state to a state in the goal region while avoiding obstacles. The robot operates inside deterministic, bounded, and perfectly known 2D or 3D environments populated by static obstacles. The robot's transition and observation models are uncertain and defined as follows. Let $\ensuremath{S}\xspace \subset \mathbb{R}^n$ be the bounded n-dimensional state space, $A \subset \mathbb{R}^d$ the bounded $d$-dimensional control space and $\ensuremath{O}\xspace \subset \mathbb{R}^l$ the bounded $l$-dimensional observation space of the robot. The state of the robot evolves according to a discrete-time non-linear function, which we model in the general form $\ensuremath{s}\xspace_{t+1} = f(\ensuremath{s}\xspace_t, \ensuremath{a}\xspace_t, v_t)$ where $\ensuremath{s}\xspace_t \in \ensuremath{S}\xspace$ is the state of the robot at time $t$, $\ensuremath{a}\xspace_t \in \ensuremath{A}\xspace$ is the control input at time $t$, and $v_t \in \mathbb{R}^d$ is a random transition error. At each time step $t$, the robot perceives imperfect information regarding its current state according to a non-linear stochastic function of the form $\ensuremath{o}\xspace_t = h(\ensuremath{s}\xspace_t, w_t)$, where $\ensuremath{o}\xspace_t \in \ensuremath{O}\xspace$ is the observation at time $t$ and $w_t \in \mathbb{R}^d$ is a random observation error. This class of motion planning problems under uncertainty can naturally be formulated as a Partially Observable Markov Decision Process (POMDP). Formally, a POMDP is a tuple \ensuremath{\langle S, A, O, T, Z, R, \ensuremath{b_0}\xspace, \gamma \rangle}\xspace, where \ensuremath{S}\xspace, \ensuremath{A}\xspace and \ensuremath{O}\xspace are the state, action, and observation spaces of the robot. $T$ is a conditional probability function $T(\ensuremath{s}\xspace, \ensuremath{a}\xspace, \ensuremath{s'}\xspace) = p(\ensuremath{s'}\xspace \,|\, \ensuremath{s}\xspace, \ensuremath{a}\xspace)$ (where $\ensuremath{s}\xspace, \ensuremath{s'}\xspace \in \ensuremath{S}\xspace$ and $\ensuremath{a}\xspace \in \ensuremath{A}\xspace$) that models the uncertainty in the effect of performing actions, while $Z(\ensuremath{s}\xspace, \ensuremath{a}\xspace, \ensuremath{o}\xspace) = p(\ensuremath{o}\xspace | \ensuremath{s}\xspace, \ensuremath{a}\xspace)$ (where $\ensuremath{o}\xspace\in\ensuremath{O}\xspace$) is a conditional probability function that models the uncertainty in perceiving observations. $R(\ensuremath{s}\xspace, \ensuremath{a}\xspace)$ is a reward function, which encodes the planning objective. \ensuremath{b_0}\xspace is the initial belief, capturing the uncertainty in the robot's initial state and $\gamma \in (0, 1)$ is a discount factor. At each time-step, a POMDP agent is at a state $s \in \ensuremath{S}\xspace$, takes an action $a \in \ensuremath{A}\xspace$, perceives an observation $o \in \ensuremath{O}\xspace$, receives a reward based on the reward function $R(s, a)$, and moves to the next state. Now due to uncertainty in the results of action and sensing, the agent never knows its exact state and therefore, estimates its state as a probability distribution, called belief. The solution to the POMDP problem is an optimal policy (denoted as \ensuremath{\pi^*}\xspace), which is a mapping $\ensuremath{\pi^*}\xspace: \mathbb{B} \rightarrow \ensuremath{A}\xspace$ from beliefs ($\mathbb{B}$ denotes the set of all beliefs, which is called the belief space) to actions that maximizes the expected total reward the robot receives, i.e. \begin{align} &V^*(\ensuremath{b_0}\xspace) = \nonumber\\ &\max_{a \in \ensuremath{A}\xspace} \left(R(b, a) + \gamma \int_{o \in \ensuremath{O}\xspace} p(o | b, a) V^*(\tau(b, a, o)) \, \ensuremath{d}\xspace\ensuremath{o}\xspace\right) \end{align} where $\tau(b, a, o)$ computes the updated belief estimate after the robot performs action $a \in \ensuremath{A}\xspace$ and perceived $o \in \ensuremath{O}\xspace$ from belief $b$, and is defined as: \begin{align}\label{e:belTrans} b'(s') &= \tau(b, a, o)(s') \nonumber \\&= \eta \, Z(s', a, o) \int_{s \in \ensuremath{S}\xspace} T(s, a, s') b(s) ds \end{align} For the motion planning problems considered in this work, we define the spaces $S$, $A$, and $O$ to be the same as those of the robotic system (for simplicity, we use the same notation). The transition $T$ represents the dynamics model $f$, while $Z$ represents the sensing model $h$. The reward function represents the task' objective, for example, high reward for goal states and low negative reward for states that cause the robot to collide with the obstacles. The initial belief \ensuremath{b_0}\xspace represents uncertainty on the starting state of the robot. \subsection{Related Work on Non-Linearity Measures} Linearization is a common practice in solving non-linear control and estimation problems. It is known that linearization performs well only when the system's non-linearity is ``weak"\ccite{Li12:Measure}. To identify the effectiveness of linearization in solving non-linear problems, a number of non-linearity measure have been proposed in the control and information fusion community. Many of these measures (e.g.\ccite{Bat80:Relative,Bea60:Confidence,Ema93:A}) have been designed for deterministic systems. For instance,\ccite{Bat80:Relative} proposed a measure derived from the curvature of the non-linear function. The work in\ccite{Bea60:Confidence,Ema93:A} computes a measure based on the distance between the non-linear function and its nearest linearization. A brief survey of non-linearity measures for deterministic systems is available in\ccite{Li12:Measure}. Non-linearity measures for stochastic systems has been proposed. For instance,\ccite{Li12:Measure} extends the measures in\ccite{Bea60:Confidence,Ema93:A} to be based on the average distance between the non-linear function that models the motion and sensing of the system, and the set of all possible linearizations of the function. Another example is\ccite{Dun13:Nonlinearity} that proposes a measures which is based on the distance between distribution over states and its Gaussian approximation, called Measure of Non-Gaussianity\xspace (MoNG\xspace), rather than based on the non-linear function itself. Assuming a passive stochastic systems, this measures computes the negentropy between a transformed belief and its Gaussian approximation. The results indicate that this measure is more suitable to measure the non-linearity of stochastic systems, as it takes into account the effect that non-linear transformations have on the shape of the transformed beliefs. This advancement is encouraging and we will use MoNG\xspace as a comparator of SNM\xspace. However, for this purpose, MoNG\xspace must be modified since we consider non-passive problems in work. The exact modifications we made can be found in Section~\ref{ssec:MHFR}. Despite the various non-linearity measures that have been proposed, most are not designed to take the effect of obstacles to the non-linearity of the system into account. Except for MoNG\xspace, all of the aforementioned non-linearity measures will have difficulties in reflecting these effects, even when they are embedded in the motion and sensing models. For instance, curvature-based measures requires the non-linear function to be twice continuously differentiable, but the presence of obstacles is very likely to break the differentiability of the motion model. Furthermore, the effect of obstacles is likely to violate the additive Gaussian error, required for instance by\ccite{Li12:Measure}. Although MoNG\xspace can potentially take the effect of obstacles into account, it is not designed to. In the presence of obstacles, beliefs have support only in the valid region of the state space, and therefore computing the difference between beliefs and their Gaussian approximations is likely to underestimate the effect of obstacles. SNM\xspace is designed to address these issues. Instead of building upon existing non-linearity measures, SNM\xspace adopts approaches commonly used for sensitivity analysis\ccite{Mas12:Loss,Mul97:Does} of Markov Decision Processes (MDP) ---a special class of POMDP where the observation model is perfect, and therefore the system is fully observable. These approaches use statistical distance measures between the original transition dynamics and their perturbed versions. Linearized dynamics can be viewed as a special case of perturbed dynamics, and hence this statistical distance measure can be applied as a non-linearity measure, too. We do need to extend these analysis, as they are generally defined for discrete state space and are defined with respect to only the transition models (MDP assumes the state of the system is fully observable). Nevertheless, such extensions are feasible and the generality of this measure could help identifying the effectiveness of linearization in motion planning under uncertainty problems. \section{Experiments and Results} The purpose of our experiments is two-fold: To test the applicability of SNM\xspace to motion planning under uncertainty problems and to test SNM-Planner\xspace. For our first objective, we compare SNM\xspace with a modified version of the Measure of Non-Gaussianity (MoNG\xspace)\ccite{Dun13:Nonlinearity}. Details on this measure are in Section~\ref{ssec:mong}. We evaluate both measures using two robotic systems, a car-like robot with 2$^{nd}$-order dynamics and a torque-controlled 4DOFs manipulator, where both robots are subject to increasing uncertainties and increasing numbers of obstacles in the operating environment. Furthermore we test both measures when the robots are subject to highly non-linear collision dynamics and different observation models. Details on the robot models are presented in Section~\ref{ssec:robot_models}, whereas the evaluation experiments are presented in Section~\ref{ssec:testing_snm}. To test SNM-Planner\xspace we compare it with ABT and MHFR on three problem scenarios, including a torque-controlled 7DOFs manipulator operating inside a 3D office environment. Additionally we test how sensitive SNM-Planner\xspace is to the choice of the SNM\xspace-threshold. The results for these experiments are presented in Section~\ref{ssec:testing_snm-planner}. All problem environments are modelled within the OPPT framework\ccite{hoerger2018software}. The solvers are implemented in C++. For the parallel construction of the RRTs in MHFR, we utilize 8 CPU cores throughout the experiments. All parameters are set based on preliminary runs over the possible parameter space, the parameters that generate the best results are then chosen to generate the experimental results. \subsection{Measure of Non-Gaussianity\xspace}\label{ssec:mong} The Measure of Non-Gaussianity (MoNG\xspace) proposed in\ccite{Dun13:Nonlinearity} is based on the negentropy between the PDF of a random variable and its Gaussian approximation. Consider an $n$-dimensional random variable $X$ distributed according to PDF $p(x)$. Furthermore, let \lin{X} be a Gaussian approximation of $X$ with PDF $\widehat{p}(x)$, such that $\lin{X} \sim N(\mu , \Sigma_x)$, where $\mu$ and $\Sigma_x$ are the first two moments of $p(x)$. The negentropy between $p$ and \lin{p} (denoted as \J{p}{\lin{p}}) is then defined as \begin{equation} \J{p}{\lin{p}} = H(\lin{p}) - H(p) \end{equation} where \begin{equation}\label{e:entropies} \begin{split} \entr{\lin{p}} &= \frac{1}{2} ln \left [(2 \pi e)^n \left |det(\Sigma_x) \right | \right ] \\ \entr{p} &= - \int p(x) \ln p(x) dx \end{split} \end{equation} are the differential entropies of $p$ and $\lin{p}$ respectively. A (multivariate) Gaussian distribution has the largest differential entropy amongst all distributions with equal first two moments, therefore \J{p}{\lin{p}} is always non-negative. In practice, since the PDF $p(x)$ is not known exactly in all but the simplest cases, \entr{p} has to be approximated. In\ccite{Dun13:Nonlinearity} this measure has originally been used to assess the non-linearity of passive systems. Therefore, in order to achieve comparability with SNM\xspace, we need to extend the Non-Gaussian measure to general active stochastic systems of the form $s_{t+1} = f(s_t, a_t, v_t)$. We do this by evaluating the non-Gaussianity of distribution that follow from the transition function \ensuremath{T(s, a, s')}\xspace given state $s$ and action $a$. In particular for a given $s$ and $a$, we can find a Gaussian approximation of \ensuremath{T(s, a, s')}\xspace (denoted by \ensuremath{T_G(s, a, s')}\xspace) by calculating the first two moments of the distribution that follows from \ensuremath{T(s, a, s')}\xspace. Using this Gaussian approximation, we define the Measure of Non-Gaussianity\xspace as \begin{align} &MoNG\xspace(\ensuremath{T}\xspace, \ensuremath{T_G}\xspace) = \nonumber\\ &\sup_{\ensuremath{s}\xspace \in \ensuremath{S}\xspace, \ensuremath{a}\xspace \in \ensuremath{A}\xspace} \left [H(\ensuremath{T_G(s, a, s')}\xspace) - H(\ensuremath{T(s, a, s')}\xspace)\right ] \end{align} Similarly we can compute the Measure of Non-Gaussianity\xspace for the observation function: \begin{align} &MoNG\xspace(\ensuremath{Z}\xspace, \ensuremath{Z_G}\xspace) = \nonumber\\ &\sup_{\ensuremath{s}\xspace \in \ensuremath{S}\xspace, \ensuremath{a}\xspace \in \ensuremath{A}\xspace} \left [H(\ensuremath{Z_G(s, a, o)}\xspace) - H(\ensuremath{Z(s, a, o)}\xspace) \right ] \end{align} where \ensuremath{Z_G}\xspace is a Gaussian approximation of \ensuremath{Z}\xspace. In order to approximate the entropies $\entr{\ensuremath{T(s, a, s')}\xspace)}$ and \entr{\ensuremath{Z(s, a, o)}\xspace}, we are using a similar histogram-based approach as discussed in Section~\ref{ssec:monApprox}. The entropy terms for the Gaussian approximations can be computed in closed form, according to the first equation in \eref{e:entropies}\ccite{Ahmed89Entropy}. \subsection{Robot Models}\label{ssec:robot_models} \subsubsection{4DOFs-Manipulator. }\label{sssec:4DOFManipulator} The 4DOFs-manipulator consists of 4 links connected by 4 torque-controlled revolute joints. The first joint is connected to a static base. In all problem scenarios the manipulator must move from a known initial state to a state where the end-effector lies inside a goal region located in the workspace of the robot, while avoiding collisions with obstacles the environment is populated with. The state of the manipulator is defined as $\ensuremath{s}\xspace=(\theta, \dot{\theta}) \in \mathbb{R}^{8}$, where $\theta$ is the vector of joint angles, and $\dot{\theta}$ the vector of joint velocities. Both joint angles and joint velocities are subject to linear constraints: The joint angles are constrained by $(-3.14, 3.14)rad$, whereas the joint velocities are constrained by $(6,\allowbreak 2,\allowbreak 2,\allowbreak 2)rad/s$ in each direction. Each link of the robot has a mass of $1kg$. The control inputs of the manipulator are the joint torques, where the maximum joint torques are $(20,\allowbreak 20,\allowbreak 10,\allowbreak 5)Nm/s$ in each direction. Since ABT assumes a discrete action space, we discretize the joint torques for each joint using the maximum torque in each direction, which leads to 16 actions. The dynamics of the manipulator is defined using the well-known Newton-Euler formalism\ccite{spong06:RobotModelling}. For both manipulators we assume that the input torque for each joint is affected by zero-mean additive Gaussian noise. Note however, even though the error is Gaussian, due to the non-linearities of the motion dynamics the beliefs will not be Gaussian in general. Since the transition dynamics for this robot are quite complex, we assume that the joint torques are applied for 0.1s and we use the ODE physics engine\ccite{drumwright2010:extending} for the numerical integration of the dynamics, where the discretization (\textrm{i.e.}\ $\delta t$) of the integrator is set to $\delta t = 0.004s$. The robot is equipped with two sensors: The first sensor measures the position of the end-effector inside the robot's workspace, whereas the second sensor measures the joint velocities. Consider a function $g: \mathbb{R}^{8} \mapsto \mathbb{R}^3$ that maps the state of the robot to an end-effector position inside the workspace, then the observation model is defined as \begin{equation}\label{eq:obs4DOF} o = [g(s), \dot{\theta}]^T + w \end{equation} where $w_t$ is an error term drawn from a zero-mean multivariate Gaussian distribution with covariance matrix $\Sigma_w$. The initial state of the robot is a state where the joint angles and velocities are zero. When the robot performs an action where it collides with an obstacle it enters a terminal state and receives a penalty of -500. When it reaches the goal area it also enters a terminal state, but receives a reward of 1,000. To encourage the robot to reach the goal area quickly, it receives a small penalty of -1 for every other action. \subsubsection{7DOFs Kuka iiwa manipulator. }\label{sssec:7DOFManipulator} The 7DOFs Kuka iiwa manipulator is very similar to the 4DOFs-manipulator. However, the robot consists of 7 links connected via 7 revolute joints. We set the POMDP model to be similar to that of the 4DOFs-manipulator, but expand it to handle 7DOFs. For this robot, the joint velocities are constrained by $(3.92,\allowbreak 2.91,\allowbreak 2.53,\allowbreak 2.23,\allowbreak 2.23,\allowbreak 2.23,\allowbreak 1.0)rad/s$ in each direction and the link masses are $(4,\allowbreak 4,\allowbreak 3,\allowbreak 2.7,\allowbreak 1.7,\allowbreak 1.8,\allowbreak 0.3)kg$. Additionally, the torque limits of the joints are $(25,\allowbreak 20,\allowbreak 10,\allowbreak 10,\allowbreak 5,\allowbreak 5,\allowbreak 0.5)Nm/s$ in each direction. For ABT we use the same discretization of the joint torques as in the 4DOFs-manipulator case, \textrm{i.e.} we use the maximum torque per joint in each direction, resulting in 128 actions. Similarly to the 4DOFs-manipulator, we assume that the input torques are applied for 0.1s and we use the ODE physics engine with an integration step size of 0.004s to simulate the transition dynamics. The observation and reward models are the same as for the 4DOFs-manipulator. The initial joint velocities are all zero and almost all joint angles are zero too, except for the second joint, for which the initial joint angle is $-1.5rad$. \fref{f:scenarioCompStudy}(c) shows the Kuka manipulator operating inside an office scenario. \subsubsection{Car-like robot. }\label{sssec:SecOrderCar. } A nonholonomic car-like robot of size ($0.12\times0.07\times0.01$) drives on a flat xy-plane inside a 3D environment populated by obstacles The robot must drive from a known start state to a position inside a goal region without colliding with any of the obstacles. The state of the robot at time t is defined as a 4D vector $s_t = (x_t, y_t, \theta_t, \upsilon_t) \in \mathbb{R}^4$, where $x_t, y_t \in [-1, 1]$ is the position of the center of the robot on the $xy$-plane, $\theta_t \in [-3.14, 3.14]rad$ the orientation and $\upsilon_t \in [-0.2, 0.2]$ is the linear velocity of the robot. The initial state of the robot is $(−0.7,−0.7,1.57rad,0)$ while the goal region is centered at $(0.7,0.7)$ with radius $0.1$. The control input at time $t$, $a_t = (\alpha_t, \phi_t)$ is a 2D real vector consisting of the acceleration $\alpha \in [-1, 1]$ and the steering wheel angle $\phi_t \in [-1rad, 1rad]$. The robot’s dynamics is subject to control noise $v_t = (\tilde{\alpha}_t, \tilde{\phi}_t) \sim N(0, \Sigma_v)$. The robot’s transition model is \begin{equation}\label{eq:carDynamics} s_{t+1} = f(s_t, a_t, v_t) = \begin{bmatrix} x_t + \Delta t \upsilon_t \cos \theta_t\\ y_t + \Delta t \upsilon_t \sin \theta_t\\ \theta_t + \Delta t \tan(\phi_t + \tilde{\phi}_t) / 0.11\\ \upsilon_t + \Delta t (\alpha_t + \tilde{\alpha}_t) \end{bmatrix} \end{equation} where $\Delta t = 0.3s$ is the duration of a timestep and the value $0.11$ is the distance between the front and rear axles of the wheels. This robot is equipped with two types of sensors, a localization sensor that receives a signal from two beacons that are located at $(\hat{x}_1, \hat{y}_1)$ and $(\hat{x}_2, \hat{y}_2)$. The second sensor is a velocity sensor mounted on the car. With these two sensors the observation model is defined as \begin{equation}\label{e:obstFunctCarMazeAdditive} o_t = \begin{bmatrix} \frac{1}{((x_t - \hat{x}_1)^2 + (y_t - \hat{y}_1)^2 + 1)}\\ \frac{1}{((x_t - \hat{x}_2)^2 + (y_t - \hat{y}_2)^2 + 1)}\\ v_t \end{bmatrix} + w_t \end{equation} where $w_t$ is an error vector drawn from a zero-mean multivariate Gaussian distribution with covariance matrix $\Sigma_w$. Similar to the manipulators described above, the robot receives a penalty of -500 when it collides with an obstacle, a reward of 1,000 when reaching the goal area and a small penalty of -1 for any other action. \subsection{Testing SNM\xspace}\label{ssec:testing_snm} In this set of experiments we want to understand the performance of SNM\xspace compared to MoNG\xspace in various scenarios. In particular, we are interested in the effect of increasing uncertainties and the effect that obstacles have on the effectiveness of SNM\xspace, and if these results are consistent with the performance of a general solver relative to a linearization-based solver. Additionally, we want to see how highly-nonlinear collision dynamics and different observation models -- one with additive Gaussian noise and non-additive Gaussian noise -- affect our measure. For the experiments with increasing motion and sensing errors, recall from Section~\ref{ssec:robot_models} that the control errors are drawn from zero-mean multivariate Gaussian distributions with covariance matrices $\Sigma_v$. We define the control errors (denoted as \ensuremath{e_T}\xspace) to be the standard deviation of these Gaussian distributions, such that $\Sigma_v = \ensuremath{e_T}\xspace^2 \times \mathds{1}$. Similarly for the covariance matrices of the zero-mean multivariate Gaussian sensing errors, we define the observation error as \ensuremath{e_Z}\xspace, such that $\Sigma_w = \ensuremath{e_Z}\xspace^2 \times \mathds{1}$. Note that during all the experiments, we use normalized spaces, which means that the error vectors affect the normalized action and observation vectors. For SNM\xspace and MoNG\xspace we first generated 100,000 state samples for each scenario, and computed a lookup table for each error value off-line, as discussed in Section~\ref{ssec:monApprox}. Then, during run-time we calculated the average approximated SNM and MonG values. \subsubsection{Effects of increasing uncertainties in cluttered environments. }\label{ssec:increasingly_uncertain} \begin{figure*} \centering \begin{tabular}{c@{\hspace*{5pt}}c@{\hspace*{5pt}}c@{\hspace*{5pt}}} \includegraphics[height=4cm]{DubinMaze} & \includegraphics[height=4cm]{4DOFFactory1-cropped} & \includegraphics[height=4cm]{KukaOfficeEnvironment} \\ (a) Maze & (b) Factory & (c) KukaOffice \end{tabular} \caption{Test scenarios for the different robots. The objects colored black and gray are obstacles, while the green sphere is the goal region. (a) The Maze scenario for the car-like robot. The blue squares represents the beacons, while the orange square at the bottom left represents the initial state. (b) The 4DOFs-manipulator scenario. (c) The KukaOffice scenario} \label{f:scenarioCompStudy} \end{figure*} To investigate the effect of increasing control and observation errors to SNM\xspace, MoNG\xspace and the two solvers ABT and MHFR in cluttered environments, we ran a set of experiments where the 4DOFs-manipulator and the car-like robot operate in empty environments and environments with obstacles, with increasing values of \ensuremath{e_T}\xspace and \ensuremath{e_Z}\xspace, ranging between $0.001$ and $0.075$. The environments with obstacles are the Factory and Maze environments shown in \fref{f:scenarioCompStudy}(a) and (b). For each scenario and each control-sensing error value (we set $\ensuremath{e_T}\xspace = \ensuremath{e_Z}\xspace$), we ran 100 simulation runs using ABT and MHFR respectively with a planning time of 2s per step. The average values for SNM\xspace and MoNG\xspace and the relative value differences between ABT and MHFR in the empty environments are presented in \tref{t:measureCompareEmpty}. The results show that for both scenarios SNM\xspace and MoNG\xspace are sensitive to increasing transition and observation errors. This resonates well with the relative value difference between ABT and MHFR. The more interesting question is now, how sensitive are both measures to obstacles in the environment? \tref{t:measureCompareClutter}(a) and (b) shows the results for the Factory and the Maze scenario respectively. It is evident that SNM\xspace increases significantly compared to the empty environments, whereas MoNG\xspace is almost unaffected. Overall obstacles increase the relative value difference between ABT and MHFR, except for large uncertainties in the Maze scenario. This indicates that MHFR suffers more from the additional non-linearities that obstacles introduce. SNM\xspace is able to capture these effects well. An interesting remark regarding the results for the Maze scenario in \tref{t:measureCompareClutter}(b) is that the relative value difference actually decreases for large uncertainties. The reason for this can be seen in \fref{f:relValCarMaze}. As the uncertainties increase, the problem becomes so difficult, such that both solvers fail to compute a reasonable policy within the given planning time. However, clearly MHFR suffers earlier from these large uncertainties compared to ABT. \begin{table} \centering \resizebox{\columnwidth}{!}{% \begin{tabular}{|c|c|c|c|} \hline \multicolumn{4}{|c|}{\textbf{(a) Empty environment 4DOFs-manipulator}} \\ \hline \hline \textbf{$\ensuremath{e_T}\xspace = \ensuremath{e_Z}\xspace$} & \textbf{SNM\xspace} & \textbf{MoNG\xspace} & $\mathbf{\left |\frac{V_{ABT}(b_0) - V_{MHFR}(b_0)}{V_{ABT}(b_0)}\right |}$ \\ \hline 0.001 & 0.207 & 0.548 & 0.0110 \\ \hline 0.0195 & 0.213 & 0.557 & 0.0346 \\ \hline 0.038 & 0.243 & 0.603 & 0.0385 \\ \hline 0.057 & 0.254 & 0.617 & 0.0437 \\ \hline 0.075 & 0.313 & 0.686 & 0.0470 \\ \hline \hline \multicolumn{4}{|c|}{\textbf{(b) Empty environment Car-like robot}} \\ \hline \hline \textbf{$\ensuremath{e_T}\xspace = \ensuremath{e_Z}\xspace$} & \textbf{SNM\xspace} & \textbf{MoNG\xspace} & $\mathbf{\left |\frac{V_{ABT}(b_0) - V_{MHFR}(b_0)}{V_{ABT}(b_0)}\right |}$ \\ \hline 0.001 & 0.169 & 0.473 & 0.1426 \\ \hline 0.0195 & 0.213 & 0.479 & 0.1793 \\ \hline 0.038 & 0.295 & 0.458 & 0.1747 \\ \hline 0.057 & 0.350 & 0.476 & 0.1839 \\ \hline 0.075 & 0.395 & 0.446 & 0.2641 \\ \hline \end{tabular}} \caption{Average values of SNM, MonG and the relative value difference between ABT and MHFR for the 4DOFs-manipulator (a) and the car-like robot (b) operating inside empty environments.} \label{t:measureCompareEmpty} \end{table} \begin{table} \centering \resizebox{\columnwidth}{!}{% \begin{tabular}{|c|c|c|c|} \hline \multicolumn{4}{|c|}{\textbf{(a) Factory environment}} \\ \hline \hline \textbf{$\ensuremath{e_T}\xspace = \ensuremath{e_Z}\xspace$} & \textbf{SNM\xspace} & \textbf{MoNG\xspace} & $\mathbf{\left |\frac{V_{ABT}(b_0) - V_{MHFR}(b_0)}{V_{ABT}(b_0)}\right |}$ \\ \hline 0.001 & 0.293 & 0.539 & 0.0892 \\ \hline 0.0195 & 0.351 & 0.567 & 0.1801 \\ \hline 0.038 & 0.470 & 0.621 & 0.5818 \\ \hline 0.057 & 0.502 & 0.637 & 0.7161 \\ \hline 0.075 & 0.602 & 0.641 & 1.4286 \\ \hline \hline \multicolumn{4}{|c|}{\textbf{(b) Maze environment}} \\ \hline \hline \textbf{$\ensuremath{e_T}\xspace = \ensuremath{e_Z}\xspace$} & \textbf{SNM\xspace} & \textbf{MoNG\xspace} & $\mathbf{\left |\frac{V_{ABT}(b_0) - V_{MHFR}(b_0)}{V_{ABT}(b_0)}\right |}$ \\ \hline 0.001 & 0.215 & 0.482 & 0.2293 \\ \hline 0.0195 & 0.343 & 0.483 & 1.4473 \\ \hline 0.038 & 0.470 & 0.491 & 1.1686 \\ \hline 0.057 & 0.481 & 0.497 & 0.0985 \\ \hline 0.075 & 0.555 & 0.502 & 0.0040 \\ \hline \end{tabular}} \caption{Average values of SNM, MonG and the relative value difference between ABT and MHFR for the 4DOFs-manipulator operating inside the Factory environment (a) and the car-like robot operating inside the Maze environment (b).} \label{t:measureCompareClutter} \end{table} \begin{figure} \centering \includegraphics[width=0.485\textwidth]{resDubinMaze2} \caption{The average total discounted rewards achieved by ABT and MHFR in the Maze scenario, as the uncertainties increase. Vertical bars are the 95\% confidence intervals.} \label{f:relValCarMaze} \end{figure} \subsubsection{Effects of increasingly cluttered environments. } To investigate the effects of increasingly cluttered environments on both measures, we ran a set of experiments in which the Car-like robot and the 4DOFs-manipulator operate inside environments with an increasing number of randomly distributed obstacles. For this we generated test scenarios with 5, 10, 15, 20, 25 and 30 obstacles that are uniformly distributed across the environment. For each of these test scenarios, we randomly generated 100 environments. \fref{f:randObstacles}(a)-(b) shows two example environments with 30 obstacles for the Car-like robot and the 4DOFs-manipulator. For this set of experiments we don't take collision dynamics into account. The control and observation errors are fixed to $e_t = e_z = 0.038$ which corresponds to the median of the uncertainty values. \tref{t:increasingObstacles} presents the results for SNM\xspace, MoNG\xspace and the relative value difference between ABT ant MHFR for the 4DOFs-manipulator (a) and the car-like robot (b). From these results it is clear that, as the environments become increasingly cluttered, the advantage of ABT over MHFR increases, indicating that the obstacles have a significant effect on the Gaussian belief assumption of MHFR. Additionally SNM\xspace is clearly more sensitive to those effects compared to MoNG\xspace, whose values remain virtually unaffected by the clutterness of the environments. \begin{figure} \centering \begin{tabular}{cc} \includegraphics[width=0.20\textwidth]{DubinRandom30-cropped} & \includegraphics[width=0.20\textwidth]{4DOFRandom30-cropped} \\ (a) Car-like robot & (b) 4DOFs-manipulator \end{tabular} \caption{Two example scenarios for the Car-like robot (a) and the 4DOFs-manipulator (b) with 30 randomly distributed obstacles.} \label{f:randObstacles} \end{figure} \begin{table} \centering \resizebox{\columnwidth}{!}{% \begin{tabular}{|c|c|c|c|} \hline \multicolumn{4}{|c|}{\textbf{(a) 4DOFs-manipulator with increasing number of obstacles}} \\ \hline \hline Num obstacles & SNM & MonG & $\mathbf{\left |\frac{V_{ABT}(b_0) - V_{MHFR}(b_0)}{V_{ABT}(b_0)}\right |}$ \\ \hline 5 & 0.359 & 0.650 & 0.0276 \\ \hline 10 & 0.449 & 0.643 & 0.0683 \\ \hline 15 & 0.514 & 0.673 & 0.2163 \\ \hline 20 & 0.527 & 0.683 & 0.2272 \\ \hline 25 & 0.651 & 0.690 & 0.2675 \\ \hline 30 & 0.698 & 0.672 & 0.3108 \\ \hline \hline \multicolumn{4}{|c|}{\textbf{(b) Car-like robot with increasing number of obstacles}} \\ \hline \hline Num obstacles & SNM & MonG & $\mathbf{\left |\frac{V_{ABT}(b_0) - V_{MHFR}(b_0)}{V_{ABT}(b_0)}\right |}$ \\ \hline 5 & 0.327 & 0.459 & 0.0826 \\ \hline 10 & 0.387 & 0.473 & 0.1602 \\ \hline 15 & 0.446 & 0.482 & 0.1846 \\ \hline 20 & 0.468 & 0.494 & 0.4813 \\ \hline 25 & 0.529 & 0.489 & 0.5788 \\ \hline 30 & 0.685 & 0.508 & 0.7884 \\ \hline \end{tabular}} \caption{Average values of SNM, MonG and relative value difference between ABT and MHFR for the 4DOFs-manipulator (a) and the car-like robot (b) operating inside environments with increasing numbers of obstacles.} \label{t:increasingObstacles} \end{table} \subsubsection{Effects of collision dynamics. } Intuitively, collision dynamics are highly non-linear effects. Here we investigate SNM\xspace's capability in capturing these effects compared to MoNG\xspace. For this, the robots are allowed to collide with the obstacles. In other words, colliding states are not terminal and the dynamic effects of collisions are reflected in the transition model. For the 4DOFs-manipulator these collisions are modeled as additional constraints (contact points) that are resolved by applying "correcting velocities" to the colliding bodies in the opposite direction of the contact normals. For the Car-like robot, we modify the transition model \eref{eq:carDynamics} to consider collision dynamics such that \begin{equation}\label{eq:car_coll_transition} s_{t+1} = \begin{cases} f_{col}(s_t, a_t, v_t) & \text{ if } f(s_t, a_t, v_t)\ \text{collides} \\ f(s_t, a_t, v_t) & \text{ else } \end{cases} \end{equation} where \begin{equation}\label{eq:car_coll_funct} f_{coll}(s_t, a_t, v_t) = \left [x_t, y_t, \theta_t, -3v_t \right ]^T \end{equation} This transition function causes the robot to slightly "bounce" off obstacles upon collision. There are two interesting remarks regarding this transition function: The first one is that \eref{eq:car_coll_funct} is a deterministic. In other words, a collision causes an immediate reduction of the uncertainty regarding the state of the robot. Second, while the collision effects \eref{eq:car_coll_funct} are linear, \eref{eq:car_coll_transition} is not smooth since the collision dynamics induce discontinuities when the robot operates in the vicinity of obstacles. \begin{table} \centering \resizebox{\columnwidth}{!}{% \begin{tabular}{|c|c|c|c|} \hline \multicolumn{4}{|c|}{\textbf{(a) Maze environment with collision dynamics}} \\ \hline \hline \textbf{$\ensuremath{e_T}\xspace = \ensuremath{e_Z}\xspace$} & \textbf{SNM\xspace} & \textbf{MoNG\xspace} & $\mathbf{\left |\frac{V_{ABT}(b_0) - V_{MHFR}(b_0)}{V_{ABT}(b_0)}\right |}$ \\ \hline 0.001 & 0.425 & 0.490 & 0.3807 \\ \hline 0.0195 & 0.576 & 0.505 & 7.0765 \\ \hline 0.038 & 0.636 & 0.542 & 8.6847 \\ \hline 0.057 & 0.740 & 0.569 & 2.0194 \\ \hline 0.075 & 0.776 & 0.611 & 1.7971 \\ \hline \hline \multicolumn{4}{|c|}{\textbf{(b) Factory environment with collision dynamics}} \\ \hline \hline \textbf{$\ensuremath{e_T}\xspace = \ensuremath{e_Z}\xspace$} & \textbf{SNM\xspace} & \textbf{MoNG\xspace} & $\mathbf{\left |\frac{V_{ABT}(b_0) - V_{MHFR}(b_0)}{V_{ABT}(b_0)}\right |}$ \\ \hline 0.001 & 0.492 & 0.639 & 0.07141 \\ \hline 0.0195 & 0.621 & 0.621 & 0.4007 \\ \hline 0.038 & 0.725 & 0.738 & 0.6699 \\ \hline 0.057 & 0.829 & 0.742 & 1.0990 \\ \hline 0.075 & 0.889 & 0.798 & 1.7100 \\ \hline \end{tabular}} \caption{Average values of SNM, MonG and the relative value difference between ABT and MHFR for the 4DOFs-manipulator operating inside the Factory environment (a) and the car-like robot operating inside the Maze environment (b) while being subject to collision dynamics.} \label{t:measureCompareColl} \end{table} \tref{t:measureCompareColl} shows the comparison between SNM\xspace and MoNG\xspace and the relative value difference between ABT and MHFR for the 4DOFs-manipulator operating inside the Factory environment (a) and the car-like robot operating inside the Maze environment (b) while being subject to collision dynamics. It can be seen that the additional non-linear effects are captured well by SNM\xspace. Interestingly, compared to the results in \tref{t:measureCompareClutter}(a), where the 4DOFs-manipulator operates in the same environment without collision dynamics, MoNG\xspace captures the effects of collision dynamics as well, which indicates that collision dynamics have a large effect on the Gaussian assumption made by MHFR. Looking at the relative value difference between ABT and MHFR confirms this. MHFR suffers more from the increased non-linearity of the problems caused by collision dynamics compared to ABT. This effect aggravates as the uncertainty increases, which is a clear indication that the problem becomes increasingly non-linear with larger uncertainties. Looking at the results for the car-like robot operating in the Maze scenario presents a similar picture. Comparing the results in \tref{t:measureCompareColl}(b) where collision dynamics are taken into account to \tref{t:measureCompareClutter}(b), shows that collision dynamics have a significant effect both to SNM\xspace as well as Measure of Non-Gaussianity\xspace. \subsubsection{Effects of non-linear observation functions with non-additive errors. }\label{ss:observationComparison} In the previous experiments we assumed that the observation functions are non-linear functions with additive Gaussian noise, a special class of non-linear observation functions. This class of observation functions has some interesting implications: First of all, the resulting observation distribution remains Gaussian. This in turn means that MoNG\xspace for the observation function evaluates to zero. Second, linearizing the observation function results in a Gaussian distribution with the same mean but different covariance. We therefore expect that the observation component SNM\xspace remains small, even for large uncertainties. To investigate how SNM\xspace reacts to non-linear observation functions with non-additive noise, we ran a set of experiments for the 4DOFs-manipulator operating inside the Factory environment and the car-like robot operating inside the Maze environment where we replaced both observation functions with non-linear functions with non-additive noise. For the 4DOFs-manipulator we replaced the observation function defined in \eref{eq:obs4DOF} with \begin{equation}\label{e:4DOFObsNonAdditive} o_t = g(s_t + w_t) \end{equation} where $w_t \sim N(0, \Sigma_w)$. In other words, the manipulator has only access to a sensor that measure the position of the end-effector in the workspace. For the car-like robot we use the following observation function: \begin{equation}\label{e:obstFunctCarMazeNonAdditive} o_t = \begin{bmatrix} \frac{1}{((x_t + w_t^1 - \hat{x}_1)^2 + (y_t + w_t^2 - \hat{y}_1)^2 + 1)}\\ \frac{1}{((x_t + w_t^1 - \hat{x}_2)^2 + (y_t + w_t^2 - \hat{y}_2)^2 + 1)}\\ v_t + w_t^3 \end{bmatrix} \end{equation} where $\left (w_t^1, w_t^2, w_t^3 \right )^T \sim N(0, \Sigma_w)$. For both robots, we set $e_t = 0.038$. \begin{table} \centering \resizebox{\columnwidth}{!}{% \begin{tabular}{|c|c|c|c|c|c|} \hline \multicolumn{6}{|c|}{\textbf{(a) Factory environment with additive observation errors}} \\ \hline \hline $\mathbf{\ensuremath{e_Z}\xspace}$ & 0.001 & 0.0195 & 0.038 & 0.057 & 0.075 \\ \hline \textbf{SNM\xspace} & 0.001 & 0.004 & 0.013 & 0.036 & 0.047 \\ \hline \textbf{MonG} & 0.0 & 0.0 & 0.0 & 0.0 & 0.0 \\ \hline \hline \multicolumn{6}{|c|}{\textbf{(b) Factory environment with non-additive observation errors}} \\ \hline \hline $\mathbf{\ensuremath{e_Z}\xspace}$ & 0.001 & 0.0195 & 0.038 & 0.057 & 0.075 \\ \hline \textbf{SNM\xspace} & 0.012 & 0.087 & 0.173 & 0.234 & 0.317 \\ \hline \textbf{MonG} & 0.0 & 0.047 & 0.094 & 0.136 & 0.173 \\ \hline \end{tabular}} \caption{Comparison between the observation component of SNM\xspace and MoNG\xspace for the 4DOF-manipulator operating inside the Factory environment with observation function \eref{eq:obs4DOF} (a) and \eref{e:4DOFObsNonAdditive} (b) as the observation errors increase.} \label{t:compAdditive4DOF} \end{table} \begin{table} \centering \resizebox{\columnwidth}{!}{% \begin{tabular}{|c|c|c|c|c|c|} \hline \multicolumn{6}{|c|}{\textbf{(a) Maze environment with additive observation errors}} \\ \hline \hline $\mathbf{\ensuremath{e_Z}\xspace}$ & 0.001 & 0.0195 & 0.038 & 0.057 & 0.075 \\ \hline \textbf{SNM\xspace} & 0.002 & 0.012 & 0.037 & 0.048 & 0.060 \\ \hline \textbf{MonG} & 0.0 & 0.0 & 0.0 & 0.0 & 0.0 \\ \hline \hline \multicolumn{6}{|c|}{\textbf{(b) Maze environment with non-additive observation errors}} \\ \hline \hline $\mathbf{\ensuremath{e_Z}\xspace}$ & 0.001 & 0.0195 & 0.038 & 0.057 & 0.075 \\ \hline \textbf{SNM\xspace} & 0.083 & 0.086 & 0.101 & 0.198 & 0.207 \\ \hline \textbf{MonG} & 0.0 & 0.012 & 0.032 & 0.053 & 0.075 \\ \hline \end{tabular}} \caption{Comparison between the observation component of SNM\xspace and MoNG\xspace for the car-like robot operating inside the Maze environment with observation function \eref{e:obstFunctCarMazeAdditive}(a) and observation function \eref{e:obstFunctCarMazeNonAdditive}(b) as the observation errors increase.} \label{t:compAdditiveCar} \end{table} \tref{t:compAdditive4DOF} shows the values for the observation components of SNM\xspace and MoNG\xspace for the 4DOFs-manipulator operating inside the Factory environment as the observation errors increase. As expected, for additive Gaussian errors, MoNG\xspace is zero, whereas SNM\xspace is small but measurable. This shows that SNM\xspace is able to capture the difference of the variance between the original and linearized observation functions. For non-additive errors, the observation function is non-Gaussian, therefore we can see that both measures increase as the observation errors increase. Interestingly for both measures the observation components yield significantly smaller values compared to the transition components. This indicates that the non-linearity of the problem stems mostly from the transition function. For the car-like robot operating inside the Maze environment we see a similar picture. For the observation function with additive Gaussian errors, \tref{t:compAdditiveCar}(a) shows that MoNG\xspace remains zero for all values of \ensuremath{e_Z}\xspace, whereas SNM\xspace yields a small but measurable value. Again, both measures increase significantly in the non-additive error case in \tref{t:compAdditiveCar}(b). The question is now, how do ABT and MHFR perform in both scenarios when observation functions with non-additive Gaussian errors are used? \tref{t:measureCompareNonAdditive}(a) shows this relative value difference for the 4DOFs-manipulator operating inside the Factory environment. It can be seen that as the errors increase, the relative value difference between ABT and MHFR increase significantly, compared to the relative value difference shown in \tref{t:measureCompareClutter}(a), where an observation function with additive errors is used. Similarly, for the car-like robot operating inside the Maze scenario using the observation function with non-additive errors, the relative value difference shown in table \tref{t:measureCompareNonAdditive}(b) between the two solvers is much larger compared to \tref{t:measureCompareClutter}(b). This is in line with our intuition that non-Gaussian observation functions are more challenging for linearization-based solvers. \begin{table} \centering \resizebox{\columnwidth}{!}{% \begin{tabular}{|c|c|c|c|} \hline \multicolumn{4}{|c|}{\textbf{(a) Factory environment with non-additive observation errors}} \\ \hline \hline \textbf{$\ensuremath{e_T}\xspace = \ensuremath{e_Z}\xspace$} & \textbf{SNM\xspace} & \textbf{MoNG\xspace} & $\mathbf{\left |\frac{V_{ABT}(b_0) - V_{MHFR}(b_0)}{V_{ABT}(b_0)}\right |}$ \\ \hline 0.001 & 0.012 & 0.0 & 0.06992 \\ \hline 0.0195 & 0.0878 & 0.0476 & 0.43861 \\ \hline 0.038 & 0.1732 & 0.0941 & 0.89720 \\ \hline 0.057 & 0.2347 & 0.1363 & 1.46063 \\ \hline 0.075 & 0.3178 & 0.1740 & 8.34832 \\ \hline \hline \multicolumn{4}{|c|}{\textbf{(b) Maze environment with non-additive observation errors}} \\ \hline \hline \textbf{$\ensuremath{e_T}\xspace = \ensuremath{e_Z}\xspace$} & \textbf{SNM\xspace} & \textbf{MoNG\xspace} & $\mathbf{\left |\frac{V_{ABT}(b_0) - V_{MHFR}(b_0)}{V_{ABT}(b_0)}\right |}$ \\ \hline 0.001 & 0.0837 & 0.0 & -0.12451 \\ \hline 0.0195 & 0.0868 & 0.0121 & 0.33872 \\ \hline 0.038 & 0.1017 & 0.0321 & 1.41429 \\ \hline 0.057 & 0.1983 & 0.0531 & 8.70111 \\ \hline 0.075 & 0.2072 & 0.0758 & 0.95132 \\ \hline \end{tabular}} \caption{Average values of SNM, MonG and the relative value difference between ABT and MHFR for the 4DOFs-manipulator operating inside the Factory environment (a) and the car-like robot operating inside the Maze environment (b) with non-additive observation errors} \label{t:measureCompareNonAdditive} \end{table} \subsection{Testing SNM-Planner\xspace}\label{ssec:testing_snm-planner} In this set of experiments we want to test the performance of SNM-Planner\xspace in comparison with the two component planners ABT and MHFR. To this end we tested SNM-Planner\xspace on three problem scenarios: The Maze scenario for the car like robot shown in \fref{f:scenarioCompStudy}(a) and the Factory scenario for the 4DOFs-manipulator. Additionally we tested SNM-Planner\xspace on a scenario in which the Kuka iiwa robot operates inside an office environment, as shown in \fref{f:scenarioCompStudy}(b). Similarly to the Factory scenario, the robot has to reach a goal area while avoiding collisions with the obstacles. The planning time per step is 8s in this scenario. For the SNM\xspace-threshold we chose 0.5. Here we set $\ensuremath{e_T}\xspace=\ensuremath{e_Z}\xspace=0.038$. \begin{table} \centering \resizebox{\columnwidth}{!}{% \begin{tabular}{|c|c|c|c|} \hline \textbf{Planner} & \textbf{Car-like robot} & \textbf{4DOFs-manipulator} & \textbf{Kuka iiwa} \\ \hline \hline ABT & -150.54 $\pm$ 40.6 & 801.78 $\pm$ 25.7 & 498.33 $\pm$ 30.6 \\ \hline MHFR & -314.25 $\pm$ 31.4 & 345.82 $\pm$ 60.8 & -163.21 $\pm$ 29.6 \\ \hline SNM-Planner\xspace & \textbf{14.68 $\pm$ 46.3} & \textbf{833.17 $\pm$ 13.4} & \textbf{620.67 $\pm$ 35.7} \\ \hline \end{tabular}} \caption{Average total discounted reward and $\pm$ 95\% confidence interval over 1,000 simulation runs. The proportion of ABT being used in the Maze, Factory and Office scenarios is 37.85\%, 56.43\% and 42.33\% respectively.} \label{t:snmPlannerResults} \end{table} The results in \tref{t:snmPlannerResults} indicate that SNM-Planner\xspace is able to approximately identify when it is beneficial to use a linearization-based solver and when a general solver should be used. In all three scenarios, SNM-Planner\xspace outperforms the two component planners. In the Maze scenario, the difference between SNM-Planner\xspace and the component planners is significant. The reason is, MHFR is well suited to compute a long-term strategy, as it constructs nominal trajectories from the current state estimate all the way to the goal, whereas the planning horizon of ABT is limited by the depth of the search tree. However, in the proximity of obstacles, the Gaussian belief assumption of MHFR are no long valid, and careful planning is required to avoid collisions with the obstacles. In general ABT handles these situations better than MHFR. SNM-Planner\xspace combines the benefits of both planners and alleviates their shortcoming. \fref{f:DubinSNMSamples} shows state samples for which the SNM\xspace-values exceed the given threshold of 0.5. It is obvious that many of these samples are clustered around obstacles. In other words, when the support set of the current belief (i.e. the subset of the state space that is covered by the belief particles) lies in open areas, MHFR is used to drive the robot towards the goal, whereas in the proximity of obstacles, ABT is used to compute a strategy that avoids collisions with the obstacles. A similar behavior was observed in the KukaOffice environment. During the early planning steps, when the robot operates in the open area, MHFR is well suited to drive the end-effector towards the goal area, but near the narrow passage at the back of the table, ABT in general computes better motion strategies. Again, SNM-Planner\xspace combines both strategies to compute better motion strategies than each of the component planners alone. \begin{figure} \centering \includegraphics[width=0.5\columnwidth]{DubinSNMSamples} \caption{State samples in the Maze scenario for which the approximated SNM\xspace value exceeds the chosen threshold of 0.5} \label{f:DubinSNMSamples} \end{figure} \subsubsection{Sensitivity of SNM-Planner\xspace. } In this experiment we test how sensitive the performance of SNM-Planner\xspace is to the choice of the SNM\xspace-threshold. Recall that SNM-Planner\xspace uses this threshold to decide, based on a local approximation of SNM\xspace, which solver to use for the policy computation. For small thresholds SNM-Planner\xspace favors ABT, whereas for large thresholds MHFR is favored. For this experiment we test SNM-Planner\xspace on the Factory problem (\fref{f:scenarioCompStudy}(b)) with multiple values for the SNM\xspace-threshold, ranging from 0.1 to 0.9. For each threshold value we estimate the average total expected discounted reward achieved by SNM-Planner\xspace using 1,000 simulation runs. Here we set $\ensuremath{e_T}\xspace=\ensuremath{e_Z}\xspace=0.038$. \tref{t:SNMPlannerSensitivity} summarizes the results. It can be seen that the choice of the threshold can affect the performance of SNM-Planner\xspace, particularly for values that are on either side of the spectrum (very small values or very large values) where SNM-Planner\xspace favors only one of the component solvers. However, between the threshold values of 0.2 and 0.5 the results are fairly consistent, which indicates that there's a range of SNM\xspace-threshold values for which SNM-Planner\xspace performs well. \begin{table}[htb] \centering \resizebox{\columnwidth}{!}{% \begin{tabular}{|c|c|c|} \hline \textbf{SNM-Threshold} & \textbf{Avg. total discounted reward} & \textbf{\% ABT used}\\ \hline \hline 0.1 & 789.43 $\pm$ 18.4 & 100.0 \\ \hline 0.2 & 794.69 $\pm$ 15.3 & 95.3 \\ \hline 0.3 & 801.82 $\pm$ 14.2 & 89.8 \\ \hline 0.4 & 834.32 $\pm$ 13.3 & 65.2\\ \hline 0.5 & 833.17 $\pm$ 13.4 & 59.6\\ \hline 0.6 & 725.71 $\pm$ 19.6 & 42.7 \\ \hline 0.7 & 622.39 $\pm$ 18.5 & 30.6 \\ \hline 0.8 & 561.02 $\pm$ 29.4 & 21.5 \\ \hline 0.9 & 401.79 $\pm$ 39.6 & 7.8 \\ \hline \end{tabular}} \caption{Average total discounted reward and 95\% confidence intervals of SNM-Planner\xspace on the Factory problem for varying SNM\xspace-threshold values. The average is collected over 1,000 simulation runs. The last column shows the percentage of ABT being used as the component solver.\vspace{-9pt}} \label{t:SNMPlannerSensitivity} \end{table} \vspace{-9pt} \section{Summary and Future Work}\label{sec:discussion} This paper presents our preliminary work in identifying the suitability of linearization for motion planning under uncertainty. To this end, we present a general measure of non-linearity, called Statistical-distance-based Non-linearity Measure\xspace (SNM\xspace), which is based on the distance between the distributions that represent the system's motion--sensing model and its linearized version. Comparison studies with one of state-of-the-art methods for non-linearity measure indicate that SNM\xspace is more suitable in taking into account obstacles in measuring the effectiveness of linearization. We also propose a simple on-line planner that uses a local estimate of SNM\xspace to select whether to use a general POMDP solver or a linearization-based solver for robot motion planning under uncertainty. Experimental results indicate that our simple planner can appropriately decide where linearization should be used and generates motion strategies that are comparable or better than each of the component planner. Future work abounds. For instance, the question for a better measure remains. The total variation distance relies on computing a maximization, which is often difficult to estimate. Statistical distance functions that relies on expectations exists and can be computed faster. How suitable are these functions as a non-linearity measure? Furthermore, our upper bound result is relatively loose and can only be applied as a sufficient condition to identify if linearization will perform well. It would be useful to find a tighter bound that remains general enough for the various linearization and distribution approximation methods in robotics.
{'timestamp': '2020-06-01T02:07:19', 'yymm': '2005', 'arxiv_id': '2005.14406', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14406'}
arxiv
\section{Introduction}\label{sec:bsu-intro} Spatial structures and spatial algorithms are sometimes overshadowed by geostatistics and geochemical analysis in geology and stratigraphic modelling despite playing a no-less important role. In this paper, \textit{surface warping} is concerned with computational methods for mesh surface manipulation that automatically increase spatial fidelity \cite{guglielmino20133d}.\footnote{This should not be confused with alternative meanings in geomorphology for instance where \textit{surface warping} is attributed to cross-bending stresses resulting from torsional forces in the study of the mechanics of geologic structures \cite{mead1920notes}.} Specifically, it focuses on reshaping and correcting inaccuracies in an existing surface to maximize its agreement with observed data; in particular, geochemical assays sampled from drilled holes in an ore deposit. For decades, displacement field estimation (e.g. \cite{krishnamurthy1995optical}\cite{chang1997simultaneous}\cite{mark1997post}\cite{farneback2001very}\cite{secker2003lifting}) and surface editing techniques (e.g. \cite{nealen2006physically}\cite{sorkine2004laplacian}) have flourished in the computer vision and computer graphics community. The idea of directly manipulating mesh surface vertices can be traced back to Allan, Wyvill and Witten \cite{allan1989methodology} amongst others in a contemporary context, where the concepts of region of influence, movement constraints (in terms of decay function, bound and anchored vertices) are discussed. In specific disciplines such as video coding, dense motion field (optical flow) estimation and segmentation have, for instance, been attempted using deformable mesh motion models and MAP estimators. The a priori distribution of the estimates can be modelled by a coupled Markov random field to account for both spatial smoothness and temporal continuity along the estimated motion trajectories \cite{stiller1994object}. Despite these similarities, the \textit{surface and boundary alignment} problem considered in this paper differs in some significant ways. Although displacement estimation remains a central theme, the observations rely on \textit{geochemistry} rather than photogrammetry (or interferometry in the case of strain tensor estimation from geodetic and satellite deformation measurements \cite{guglielmino20133d}) and these observations are sparse, spatially irregular and noisy in comparison. For the surface and boundary alignment problem, mesh processing techniques \cite{botsch2010polygon} and domain knowledge \cite{dewaele-18} can play a crucial role. To the authors' knowledge, \textit{displacement field estimation} has not been utilized previously in 3D surface-based modelling of geological structures \cite{caumon2009surface} or exploited in practice to improve the efficacy of models in mining. This paper aims to bridge the gap that exists between a model and the latest data acquired from a mine. The Bayesian approach basically connects a model (or belief) with evidence from geochemical observations (the reality). Displacement estimation helps identify discrepancies, then surface warping corrects spatial inaccuracies in the surface-based representation of the relevant geological structures. In the literature, research has progressed largely in two separate streams: (1) advances in computational techniques that manipulate surfaces using dense uniformly sampled data, where warping is used to process visual information or register anatomical changes via MRI \cite{thompson2000warping} for instance; (2) generating 3D subsurface models using extensive field data and different modalities, a variety of techniques (including the use of contours and differential geometry) are summarized in \cite{leung-19subsurface} (Sect.\,1.1) and \cite{caumon2009surface}. In the first research stream, examples include (a) energy constrained mesh deformation using subspace gradient domain techniques \cite{huang2006subspace} where the targeted application is computer animation; and (b) post-rendering 3D warping which compensates for occlusion-related artifacts due to viewpoint variation by compositing interpolants from multiple reference frames \cite{mark1997post}. In computer graphics, methods for constructing extrinsically smooth and globally optimal directional fields have been considered by Jakob et al.\,\cite{jakob2015instant}, Huang and Ju \cite{huang2016extrinsically} and Kn{\"o}ppel et al.\,\cite{knoppel2013globally} where it is treated as a discrete optimization or sparse eigenvalue problem. An example from the second stream is the work of Olierook et al.\,\cite{olierook2021bayesian} which uses a Bayesian approach to fuse lithostratigraphic field observations with aeromagnetic and gravity measurements to build 3D geological models without structural data. Such model is fit for purpose for mineral exploration; however the grade control requirements encountered in a mine production setting are generally more stringent and demands far greater precision and vertical resolution. In \cite{calcagno2008geological}, Calcagno et al.\, use cokriging \cite{ver1998constructing} to create a continuous 3D potential field to describe the geometry of the geology. The model input consists of the location of geological interfaces and orientation data. Subsequently, structural information such as the location and orientation of boundaries are extracted from isosurfaces and the gradient of the interpolated potential function. The state of the art \cite{maccormack-19} generally considers modelling as an open-loop process where the input data is complete and a static model is to be produced. In practice, data is usually harvested bench-by-bench in a piecemeal manner in open-pit mining. Thus, there is a strong incentive in utilizing newly acquired data to improve both surface definitions and the existing model, to further understand the subterranean deposit below the current bench for mine planning and operational guidance. The missing link is a synergy between geochemical data, surface representation and the model --- and whether grade prediction performance can benefit from an incremental update strategy. These novel issues have not received much attention in earth and spatial science. In terms of where this paradigm fits, based on Nealen's survey article \cite{nealen2006physically}, a new category called geochemistry-based Bayesian deformable surface (GC-BDS) model is proposed to characterize the warping approach presented in this paper. \subsection{Motivation}\label{sec:motivation} To understand the importance of surface and boundary alignment, we first consider the implications of working with an inaccurate (or misleading) surface and its flow-on effects on subsequent modelling processes before formulating a Bayesian framework for surface warping with a view of improving surface integrity. As motivation, we illustrate how starting with a bad surface --- one that is not representative of the true geological boundary --- can impact on the block structure and inferencing ability of a grade estimation model. \begin{figure*}[!htb] \centering \includegraphics[width=140mm]{fig-warping-motivation1.pdf} \caption{Computational pipeline for the orebody grade estimation task. Block model spatial restructuring and inferencing both suffer from the negative effects of a surface that misrepresents the true geological boundary. The question marks serve as a reminder that the grade value of all the blocks need to be estimated.} \label{fig:warping-motivation1} \end{figure*} Figure~\ref{fig:warping-motivation1} illustrates the computational pipeline for a typical grade estimation problem where the main objectives are (i) obtain a compact block-based representation of the orebody with good boundary localization property; (ii) estimate the grade value for chemical components of interest, predicting these values especially at locations where no measurements are available using geostatistical or machine learning techniques. For the first objective, it requires changing the spatial structure of the model, partitioning the blocks as necessary (down to some predetermined, acceptable minimum block size) to closely follow the location and approximate the curvature of the geological boundary which the surface seeks to represent. In Fig.~\ref{fig:warping-motivation1}(top middle), we have a situation where the existing surface misrepresents the location of the actual boundary [which is not directly observable].\footnote{For illustrative purpose, Fig.~\ref{fig:warping-motivation1} shows a situation where the modelled boundary is grossly misplaced. In practice, the discrepancies that exist between the actual and initial modelled boundary are often explained by local differences due to inadequate sampling.} Consequently, the spatial restructuring algorithm \cite{leung2020mos} produces a block structure that is not faithful to the underlying boundary through no fault of its own. For the second objective, using a Gaussian Process (GP) learning and inferencing approach [described in Appendix~\ref{sect:inferencing-for-grade-estimation}], spatial variations (covariance functions) are learnt using samples drawn from an incorrect geological domain structure. A major consequence, depicted in Fig.~\ref{fig:warping-motivation1}(bottom right), is that the inferenced values for the blocks are biased near the actual boundary due to under-estimation or over-estimation of the chemistry values, and the blocks not properly decomposed to follow the shape of the boundary. These two factors lead to smearing in the predicted chemistry across the actual boundary which has practical implications for ore extraction and material blending in a production setting. \begin{figure*}[!htb] \centering \includegraphics[width=140mm]{fig-warping-motivation2.pdf} \caption{Rectification of the boundary through surface warping improves the spatial structure and inferencing ability of the grade block model.} \label{fig:warping-motivation2} \end{figure*} The main proposition of this paper is a Bayesian approach that corrects inaccuracies in a mesh surface through spatial warping which thus increases the positional integrity of the underlying boundary that it seeks to represent. Conceptually, the problem involves estimating the displacements to bring an existing surface into alignment with the true boundary based on the observed sample chemistry. The aim is to capture more precisely the shape and location of local features; this is depicted in Fig.~\ref{fig:warping-motivation2}(top left). The existing block structure is modified adaptively to align itself with the new warped surface. In Fig.~\ref{fig:warping-motivation2}(top center), the new block structure evidently follows the curvature of the new surface, however some of the preexisting (subdivided) blocks from the earlier misplaced boundary still remain. A block merging algorithm proposed in \cite{leung2020mos} is used to coalesce fragmented blocks to produce the consolidated block structure shown in Fig.~\ref{fig:warping-motivation2}(top right). The GP inferencing procedure is applied once again to the new block structure. The result shown in Fig.~\ref{fig:warping-motivation2}(bottom right) is free of blending or smearing artefacts. When the surface is accurate, the resultant model exhibits a clear contrast in the predicted grade values on either side of the actual boundary. Improving the reliability of these estimates ultimately enables better decision making, planning and ore extraction. To summarise, an ill-placed boundary can impact the block structure and grade estimation in significant ways. The boundary localization properties deteriorate when a block model is partitioned by an inaccurate surface. Incorrect geological domain classification resulting from a misleading surface can cause smearing to occur during inferencing where compositions are over-estimated or under-estimated near the actual boundary. \subsection{Contributions}\label{sect:contributions} In Section~\ref{sect:surface-warping}, the surface warping problem is formulated in a Bayesian framework and the MAP (maximum a posteriori) solution for node displacements estimation is presented; this serves to maximize the agreement between surfaces and geochemical observations from blast hole samples. In Section~\ref{sect:boundary-warping-fusion-workflow-validation}, local improvements are visually highlighted. An objective measure called \textit{r\textsubscript{2} cdf error score} is proposed and used for model validation to demonstrate an improvement in grade estimation performance resulting from spatial warping. \section{Surface warping}\label{sect:surface-warping} Surface warping may be framed as a Bayesian parametric inference problem where the objective is to estimate the required displacements (or spatial corrections) $\boldsymbol{\theta}\equiv \mathbf{d}\in\mathbb{R}^3$ to maximize the positional integrity of geological boundaries given a set of observations. In general terms, the observations consist of the location $\mathbf{x}\in\mathbb{R}^3$ and spatial extent $\boldsymbol {\delta}=[0,0,h]^T\subseteq\mathbb{R}^3$ of the measurements, as well as the composition $\mathbf{c}\in\mathbf{R}^K$ of the sample determined by chemical assays. The prior information available is a reference geological structure $\mathcal{G}$ that determines the geozone classification ($g\in\mathbb{Z}$) of a sample which indicates the geological domain where it belongs. This prior embeds knowledge about the stratigraphic structure of the modelled region which is considered a faithful (unbiased) representation of the ground truth at large scales, but inaccurate at smaller scales ($\sim 5-20$m) due to sparse sampling and local variation. Accordingly, applying Bayes rule, the problem may be formulated as \begin{align} \argmax_{\mathbf{d}} P(\mathbf{d}\!\mid\! \mathbf{c},\mathbf{s})\label{eq:surface-warping-problem} \end{align} where spatial information is contained in $\mathbf{s}=[\mathbf{x},\boldsymbol{\delta}]^T\in\mathbb{R}^6$ and \begin{align} P(\mathbf{d}\!\mid\! \mathbf{c},\mathbf{s})&\propto P(\mathbf{c}\!\mid\!\mathbf{d},\mathbf{s})\, P(\mathbf{d}\!\mid\!\mathbf{s}) \label{eq:surface-warping-bayes-formula1}\\ &= \left(\sum_{g} P(\mathbf{c},g\!\mid\! \mathbf{d},\mathbf{s})\right) P(\mathbf{d}\!\mid\!\mathbf{s}) \label{eq:surface-warping-bayes-formula2}\\ &= \left(\sum_{g} P(\mathbf{c}\!\mid\! g,\mathbf{d},\mathbf{s}) P(g\!\mid\! \mathbf{d},\mathbf{s})\right) P(\mathbf{d}\!\mid\!\mathbf{s}) \label{eq:surface-warping-bayes-formula3}\\ &= \sum_{g} P(\mathbf{c}\!\mid\! g,\mathbf{d},\mathbf{s}) P(g\!\mid\! \mathbf{d},\mathbf{s}) P(\mathbf{d}\!\mid\!\mathbf{s}) \label{eq:surface-warping-bayes-formula4}\\ &\approx \sum_{g} P(\mathbf{c}\!\mid\! g) P(g, \mathbf{d}\!\mid\! \mathbf{s})\label{eq:surface-warping-bayes-formula5} \end{align} Marginalization, conditional probabilities and conditional independence,\footnote{In our experience, using $p(\mathbf{c}\!\mid\! g,\mathbf{d},\mathbf{s})$ does not further increase performance since spatial attributes are already modelled by $P(g,\mathbf{d}\!\mid\!\mathbf{s})$.} ($\mathbf{c}\perp\!\!\!\perp \mathbf{d},\mathbf{s})\mid g$, are used in (\ref{eq:surface-warping-bayes-formula2}), (\ref{eq:surface-warping-bayes-formula3}) and (\ref{eq:surface-warping-bayes-formula5}), respectively. The final expression in (\ref{eq:surface-warping-bayes-formula5}) offers a clear interpretation for the posterior $P(\mathbf{d}\!\mid\! \mathbf{c},\mathbf{s})$. Specifically, $P(\mathbf{c}\!\mid\! g)$ denotes the likelihood of observing the chemical composition $\mathbf{c}$ in geozone $g$, whereas $P(g, \mathbf{d}\!\mid\! \mathbf{s})$ represents a spatial prior that considers the displacement and geozone likelihood given the sample location. This Bayesian network is described by the graphical model shown in Fig.~\ref{fig:graphical-model}. Even for this simple structure, there is tremendous scope for ingenuity. The following describes one possible implementation and reflects on some practical issues. \begin{figure*}[!htb] \centering \includegraphics[width=85mm]{fig-graphical-model.pdf} \caption{Graphical model for surface warping. The graph expresses the conditional dependence structure between the random variables: \textbf{c}=observed chemistry, \textbf{g}=geozone, \textbf{d}=displacement and \textbf{s}=spatial properties. The arrows represent conditional dependency of a target node from a source node.} \label{fig:graphical-model} \end{figure*} For readers new to geostatistics, a common pitfall is an attempt to model $P(\mathbf{c}\!\mid\! g)$ directly using raw chemical assay measurements and an affinity measure such as the Mahalanobis distance, $d^2(\mathbf{c}^\text{sample},\mathbf{c}^\text{class})$. As Filzmoser et al.\cite{filzmoser-hron-08} have pointed out, statistical analysis performed on compositional data\footnote{A key characteristic of compositional data is that they lie in the Aitchison Simplex \cite{filzmoser-hron-08}, which means the data is not Gaussian (or even symmetrically) distributed. An increase in a key component may cause another to decrease and the components sum to a constant.} without resorting to log-ratio transformation may lead to invalid or dubious interpretations \cite{garrett-17}. Even when the Mahalanobis distance metric can be legitimately applied following isometric log-ratio transformation \cite{greenacre-19}, it may still be inappropriate, as errors of the same magnitude may have different levels of significance depending on the grading thresholds. In grade estimation work, samples are routinely categorized based on composition. Thus, instead of $P(\mathbf{c}\!\mid\! g)$, a likelihood probability mass function $L(y(\mathbf{c})\!\mid\! g)$ is used by Lowe in \cite{rtgi-rtcma2018} where $y(\mathbf{c})$ represents a categorical label. These labels generally correspond to mineralogical groupings or `destination tags' since the excavated materials will be sorted eventually based on chemical and material properties.\footnote{For downstream ore processing, it is useful to know whether the material is hard or friable, lumpy or fine, viscous or powdery. Typically, 6 to 12 categorical labels, $y(\mathbf{c})$, are used. For our purpose, we focus more on sample chemistry. The criteria for HG (high grade) and LGA (low grade aluminous) iron ore, for instance, might be set at Fe $\ge$ 60\% and ($50\%\le \text{Fe} < 60\%$, Al\textsubscript{2}O\textsubscript{3} $\ge 3\%$), respectively. These parameters vary depending on the deposit and geozone.} In practice, there is a finite number of mineralogical groupings and geozones. Hence, $L(y(\mathbf{c})\!\mid\! g)$ is computed from a table with dimensions ($N_\text{class},N_\text{geozone}$) constructed using frequency counts applied to assay samples collected from exploration drillings. Here, $\mathbf{c}$ is observed, $y(\mathbf{c}): \mathbb{R}^K\rightarrow \mathbb{Z}$ is a deterministic mapping and $g$ is known. For the prior $P(g, \mathbf{d}\!\mid\! \mathbf{s}(\mathbf{x},\boldsymbol{\delta}))$, a proxy function $R(\mathbf{x}+\mathbf{d}, g, \boldsymbol{\delta})$ is used to compute the geozone and displacement likelihood in \cite{rtgi-rtcma2018}. This utilizes the a priori geological structure $\mathcal{G}$ to assess the feasibility of displacement $\mathbf{d}$. In particular, $R(\mathbf{x}+\mathbf{d}, g, \boldsymbol{\delta})$ determines the amount of overlap, $r\in[0,1]$, between geozone $g$ and an interval observation $\boldsymbol{\delta}$ of length $h$ at the proposed location $(\mathbf{x}+\mathbf{d})$. Alternatively, spatial correlation may be modelled using autocorrelation functions and random field simulation as demonstrated in \cite{gong2020stratigraphic} in regions where stratigraphic association can be reasonably inferred from dense drill hole samples. It is clear that a number of strategies can be used to find the optimal displacement in a hierarchical search space. For instance, a conditional random field may be used to impose connectivity and regularization constraints. For simplicity and speed, a set of candidate displacement points $\{\mathbf{d}_i\}$ may be chosen from a regular 3-D lattice in the vicinity of $\mathbf{x}$, viz., $\mathcal{L}_{\mathbf{x}}$. Assuming $\lvert \mathcal{L}_{\mathbf{x}}\rvert = N_\text{displacement}$ for all $\mathbf{x}$, the posterior would result in a table of size $(N_\text{sample},N_\text{displacement})$. The maximum a posteriori (MAP) estimate is given by (\ref{eq:surface-warping-max-posterior-estimate}), the solution with minimum $\lVert\mathbf{d}\rVert$ is chosen in the event of a tie. \begin{align} \mathbf{d}_\text{MAP}(\mathbf{x})&=\argmax_{\mathbf{d}} L(\mathbf{d}\!\mid\! y(\mathbf{c}),\mathbf{s}(\mathbf{x},\boldsymbol{\delta}))\notag\\ &= \argmax_{\mathbf{d}} \sum_g L(y(\mathbf{c})\!\mid\! g)R(\mathbf{x}+\mathbf{d}, g, \boldsymbol{\delta})\label{eq:surface-warping-max-posterior-estimate} \end{align} Diffusion flow techniques (based on using discrete Laplace-Beltrami \cite{botsch2010polygon}) may be applied to manifold surfaces to obtain a coherent displacement field where $\mathbf{d}_\text{MAP}(\mathbf{x})$ varies smoothly. However, dithering often presents as a simpler alternative. The solution is obtained as an aggregate average over a small neighbourhood, $\{\mathbf{x}+\boldmath{\epsilon}_i\}\in\mathcal{N}_\mathbf{x}$,\footnote{Another option is to treat $\mathcal{N}_\mathbf{x}$ as the barycentric cell or mixed Voronoi cell \cite{botsch2010polygon} in the 1-ring neighbourhood of $\mathbf{x}$.} with higher weights $w(\mathbf{x}_i)$ given to nearby estimates and displacements perpendicular to the surface normal $\mathbf{n}_\mathbf{x}$. \begin{align} \mathbf{d}'_\text{MAP}(\mathbf{x})=\sum_{\mathbf{x}_i\in\mathcal{N}_\mathbf{x}} w(\mathbf{x}_i)\cdot \mathbf{d}_\text{MAP}(\mathbf{x}_i)\label{eq:surface-warping-map-aggregate} \end{align} For instance, setting $w(\mathbf{x}_i)$ to $\text{proximity}(\mathbf{x},\mathbf{x}_i)\times\left|\left<\mathbf{n}_\mathbf{x},\mathbf{d}_\text{MAP}(\mathbf{x}_i)\right>\right|$ provides local smoothing and discourages movement parallel\footnote{Tangential movements do not effectively compensate for displacement errors which are perpendicular to the surface.} to the surface which is not productive.\footnote{In our implementation, IDW (inverse distance weights) are used for proximity($\mathbf{x},\mathbf{x}_i$). Another option is to use normalized exponential (softmax) function $\frac{e^{-\beta z_i}}{\sum_{i\in\mathcal{N}}e^{-\beta z_i}}$ where $z_i=\lVert\mathbf{x}-\mathbf{x}_i\rVert$. For the direction penalty term, $1 - (1 - {\cos}^2\theta)^2$ is used in place of $\left|\left<\mathbf{n}_\mathbf{x},\mathbf{d}_\text{MAP}(\mathbf{x}_i)\right>\right|$, where $\cos\theta = \left<\mathbf{n}_\mathbf{x},\mathbf{d}_\text{MAP}(\mathbf{x}_i)\right>$.} In instances where stratigraphic forward modelling (SFM) hints are available, $\mathbf{n}_\mathbf{x}$ may be guided instead by directional projections based on the deposition and evolution of sedimentary facies within a stratigraphic framework \cite{huang2015recent}. Given a set of mesh surface vertices $\mathbf{x}_q\in\mathcal{S}$, their corrected positions after surface warping are given by \vspace{-1mm}\begin{align} \mathbf{x}'_q=\mathbf{x}_q-\mathbf{d}'_\text{MAP}(\mathbf{x}_q).\label{eq:surface-warping-vertices-correction} \end{align} Equation (\ref{eq:surface-warping-vertices-correction}) simply applies the displacement-error corrections to surface vertices. Computing this expression usually requires spatial interpolation as $\mathbf{d}_\text{MAP}(\mathbf{x})$ is initially evaluated at sparse locations where assay information (geochemical evidence) is available. In areas where spatial resolution is low, mesh surface triangles may be subdivided to increase point density. The classification function, $y(\mathbf{c}): \mathbb{R}^K\rightarrow \mathbb{Z}$, and more generally $p(\mathbf{c}\!\mid\! g)$, may be learned \cite{leung2021warpml} using supervised or unsupervised techniques when the rules for destination tags (mineralogical grouping) are inadequate or unavailable. \subsection{Algorithm}\label{sect:spatial-warping-algorithm} The Bayesian surface warping algorithm may be summarised in a series of steps. The description here is immediately followed with explanation and illustration of the key steps in Sec.~\ref{sect:illustration}. \begin{enumerate} \item[]\hspace{-9mm}Given a chemical assay to material type categorical mapping $y(\mathbf{c}): \mathbb{R}^K\rightarrow \mathbb{Z}$, \item Compute $L(y(\mathbf{c})\!\mid\! g)\in\mathbb{R}^{N_\text{class}\times N_\text{geozone}}$ using training samples $\{(\mathbf{c}_j, g_j)\}_j$ from exploration holes\label{algo:step1} \item[]\hspace{-9mm}For each blast hole sample $i=1,\ldots, N_\text{sample}$: \item Assign categorical label $y(\mathbf{c}_i)\in\{1,\ldots,N_\text{class}\}$ to each sample\label{algo:step2} \item Compute $L(y(\mathbf{c}_i)\!\mid\! g)$ across all $N_\text{geozone}$ geozones\label{algo:step3} \item Compute geozone-displacement likelihood, $R(\mathbf{x}_i+\mathbf{d}_i, g,\boldsymbol{\delta}_i)$\label{algo:step4} \item[]\hspace{-9mm}For each surface vertex $\mathbf{x}_q$ and candidate displacement vector $\mathbf{d}_k$ from $\mathcal{L}_{\mathbf{x}_q}, k\in\{1,\ldots,N_\text{displacement}\}$: \item Interpolate the displacement field\label{algo:step5} \begin{enumerate} \item Find the $M$ nearest\footnote{Alternatively, use samples inside a local geodesic ball, e.g. within the 1-ring neighbourhood \cite{botsch2010polygon}.} samples to $\mathbf{x}_q$\label{algo:step5a} \item Compute $L_{m,k}\equiv L(\mathbf{d}_{m,k}\!\mid\! y(\mathbf{c}_m),\mathbf{s}_m(\mathbf{x}_m,\boldsymbol{\delta}_m)) = \sum_g L(y(\mathbf{c}_m)\!\mid\! g)R(\mathbf{x}_m+\mathbf{d}_{m,k}, g, \boldsymbol{\delta}_m)$\\to obtain a table where $m\in\{1,\ldots,M\}$ and $k\in\{1,\ldots, N_\text{displacement}\}$.\label{algo:step5b} \item Normalize each row s.t. $\max_k L(\mathbf{d}_{m,k}\!\mid\! y(\mathbf{c}_m),\mathbf{s}_m(\mathbf{x}_m,\boldsymbol{\delta}_m)) = 1$ for each $m$\label{algo:step5c} \item Compute weights incorporating proximity and directional preference:\\$w_{m,k}(\mathbf{x}_q) \propto \text{proximity}(\mathbf{x}_q,\mathbf{x}_m)\times\left|\left<\mathbf{n}_{\mathbf{x}_q},\mathbf{d}_{m,k}\right>\right|$ and $\sum w_{m,k} = 1$\label{algo:step5d} \item Compute $\overline{L}(\mathbf{d}_{k}\!\mid\! y(\mathbf{c}_m),\mathbf{s}_m) =\sum_m w_{m,k} L_{m,k}$\label{algo:step5e} \item Let $\mathbf{d}_\text{MAP}(\mathbf{x}_q)=\mathbf{d}_{m,k^*}$ where $k^*=\argmax_k \overline{L}(\mathbf{d}_{k}\!\mid\! y(\mathbf{c}_m),\mathbf{s}_m)$\label{algo:step5f} \end{enumerate} \item Apply smoothing to MAP displacement estimate. For example,\label{algo:step6} \begin{enumerate} \item Compute inverse distance weights $w_{p,q}$ for neighbour points $\mathbf{x}_p\in\mathcal{N}_{\mathbf{x}_q}$ s.t. $\sum w_{p,q}=1$ \item Compute $\mathbf{d}'_\text{MAP}(\mathbf{x}_q)=\sum_{p} w_{p,q}\cdot \mathbf{d}_\text{MAP}(\mathbf{x}_p)$ \end{enumerate} \item Apply correction to surface vertex to minimize discrepancy\label{algo:step7} \begin{enumerate} \item Update $\mathbf{x}'_q\leftarrow \mathbf{x}_q-\mathbf{d}'_\text{MAP}(\mathbf{x}_q)$\label{algo:step7a} \end{enumerate} \item Post-processing step: resolve conflicts, e.g. any surface patch intersection that may arise. \end{enumerate} \subsection{Illustration}\label{sect:illustration} The Algorithm presented in Sec.~\ref{sect:spatial-warping-algorithm} step \ref{algo:step1} produces a table for $L(y(\mathbf{c})\mid g)$. The example shown in Fig.~\ref{fig:dest-tags-observation-likelihood-given-geozone} has size $N_\text{geozone}\!=\!24$, $N_\text{class}\!=\!7$. The exact definitions and geochemical mapping, $y(\mathbf{c})$, used will vary depending on the site. The main point to convey is the probabilistic association between chemistry and geozone, thus an assay sample with destination tag $y(\mathbf{c})$ has a plausible connection with multiple geozones in general. For instance, the HG tag has strong affinity with mineralized geozones (\textit{M}) but its association with hydrated domains (\textit{H}) cannot be discounted based on chemical evidence alone. This multivalent proposition is emphasized in Fig.~\ref{fig:chemistry-likelihood-latex} where each dot corresponds to a single blasthole assay observation $y(\mathbf{c}_i)$ (computed in step \ref{algo:step2}) and often a given location lit up in multiple geozones across different panels. This represents a spatial description of the evaluation in step \ref{algo:step3}. The panels in Fig.~\ref{fig:chemistry-likelihood-latex} reveal spatial correlation with certain orebody structures and varying response (probability) associated with the dolerite dyke (\textit{D}) in row 2 and mineralized geozones (\textit{M}) in row 3. \begin{table}[!htb] \setlength\tabcolsep{0pt} \begin{center} \scriptsize \begin{tabular}{c} \includegraphics[width=95mm,trim={0mm 0mm 0mm 0mm},clip]{fig-dest-tags-observation-likelihood-given-geozone.pdf}\\ Destination definitions --- HG (high grade): $\text{Fe}\ge 60$ and $\text{Al}_2\text{O}_3 < 6$, BL (blended): $\text{Fe}\in [55,60)$, LG (low grade): $\text{Fe}< 55$;\\ +S (siliceous: $\text{Al}_2\text{O}_3 < 3$), +A (aluminous: $\text{Al}_2\text{O}_3 \in[3,6)$), W\textsubscript{1} (waste: $\text{Fe}< 50$ and $\text{Al}_2\text{O}_3 < 6$), W\textsubscript{2,3} (waste: $\text{Al}_2\text{O}_3 \ge 6$)\\ Geozone definitions: \textit{H}=hydrated, \textit{M}=mineralized, \textit{U}=unmineralized, \textit{C}=canga, \textit{B}=detrital, \textit{D}=dolerite. \end{tabular} \end{center} \captionof{figure}{Likelihood table of destination tag (geochemical mapping) given geozone, $L(y(\mathbf{c})\mid g)$} \label{fig:dest-tags-observation-likelihood-given-geozone} \end{table} \begin{figure*}[!htb] \centering \includegraphics[width=125mm]{fig-chemistry-likelihood-latex.pdf} \caption{Evaluation of $L(y(\mathbf{c}_i)\mid g)$ across geozones for many samples $\mathbf{c}_i$ within a spatial region of interest} \label{fig:chemistry-likelihood-latex} \end{figure*} Step~\ref{algo:step4} of the algorithm starts incorporating spatial information to disambiguate between geozone candidates whose chemistry are consistent with the observed assay sample. In concert, step~\ref{algo:step5} performs displacement estimation to minimize geochemical discrepancies with respect to the existing boundary represented by the surface. Fig.~\ref{fig:geochemistry-spatial-likelihood} provides a motivating example for both endeavors. First of all, if an assay sample is chemically consistent with the geozone it is currently situated in, there is no need for any spatial correction. It is only required when the observed chemistry is incongruent with the geochemical characteristics of the assumed domain at the measured location. \begin{figure*}[!htb] \centering \includegraphics[width=140mm]{fig-geochemistry-spatial-likelihood.pdf} \caption{Displacement estimation using $L(y(\textbf{c}_i)\mid g) R(\mathbf{x}_i+\mathbf{d}_i,g,\boldsymbol{\delta}_i)$} \label{fig:geochemistry-spatial-likelihood} \end{figure*} Figure~\ref{fig:geochemistry-spatial-likelihood}(a) shows an out-of-place (low grade Fe) observation within a mineralized domain. This is reflected numerically by $L(y(\mathbf{c}_i\mid G_1) \ll L(y(\mathbf{c}_i\mid G_2)$, where $G_1\in M$ and $G_2\in U$ belong to mineralized and unmineralized domains, respectively. Fig.~\ref{fig:geochemistry-spatial-likelihood}(b) elaborates on step~\ref{algo:step5b}: $L_{m,k}\equiv L(\mathbf{d}_{m,k}\!\mid\! y(\mathbf{c}_m),\mathbf{s}_m(\mathbf{x}_m,\boldsymbol{\delta}_m))$ for just one sample ($m=1$) and considers three displacement hypotheses $H_k$ with displacement vectors $\mathbf{d}_k\equiv\mathbf{d}_{m,k}, k\in\{1,...,K\}$ where $K=3$. The geozone-displacement likelihood $R(\mathbf{x}_m+\mathbf{d}_{m,k}, g, \boldsymbol{\delta}_m)$ is determined by the fraction of sample interval overlap with the a priori geozone structure. The example in Fig.~\ref{fig:geochemistry-spatial-likelihood}(b) shows the displacement hypothesis $H_2$ has the greatest support numerically. Intuitively, it represents the translation required to move the low grade sample completely into the unmineralized domain, $G_2$. Although hypothesis $H_3$ also provides a feasible solution, the displacement is greater and therefore it is not preferred. Based on these principles, Fig.~\ref{fig:geochemistry-spatial-likelihood}(c) shows the optimal displacement estimated for $M=2$ samples. Put simply, step~\ref{algo:step5e} roughly corresponds to Fig.~\ref{fig:geochemistry-spatial-likelihood}(d) where the displacement computed for a surface vertex $\mathbf{x}_q$ is essentially a weighted average of the estimated displacement from its $M$ nearest neighbors. Step~\ref{algo:step6} typically produces a locally smooth displacement error field. For an arbitrary vertex $\mathbf{x}_q$, the optimal solution, $\mathbf{d}'_\text{MAP}(\mathbf{x}_q)$, appears as a peak (see asterisk) in the parameter space in Fig.~\ref{fig:displacement-error-extrapolated}. Finally, the surface vertices are adjusted to complete step~\ref{algo:step7}, this may seen as additional smoothing or extrapolation on top of Fig.~\ref{fig:geochemistry-spatial-likelihood}(d).\footnote{In step~\ref{algo:step7a}, the update equation $\mathbf{x}'_q\leftarrow \mathbf{x}_q-\mathbf{d}'_\text{MAP}(\mathbf{x}_q)$ contains a minus sign because the displacement error estimation process considers moving samples around the initial boundary. In practice, we need to do the opposite, viz. move the boundary with respect to the samples which remain fixed at their measured locations.} \begin{figure*}[!htb] \centering \includegraphics[width=65mm]{fig-displacement-error-extrapolated.pdf} \caption{The likelihood associated with each displacement vector in the parameter space. The optimal solution (see asterisk) represents the consensus amongst sample estimates $\mathbf{d}_\text{MAP}(\mathbf{x}_p)$ in the neighborhood of $\mathbf{x}_q$, $\mathcal{N}_{\mathbf{x}_q}$} \label{fig:displacement-error-extrapolated} \end{figure*} \subsection{Complexity}\label{sect:complexity} The main computational complexity lies in step~\ref{algo:step5} of the algorithm. Looking at $L_{m,k} = \sum_g L(y(\mathbf{c}_m)\!\mid\! g)R(\mathbf{x}_m+\mathbf{d}_{m,k}, g, \boldsymbol{\delta}_m)$, since $L(y(\mathbf{c}_m)\!\mid\! g)$ amounts to an $O(1)$ lookup operation, the per-sample complexity comes from $R(\mathbf{x}_m+\mathbf{d}_{m,k}, g, \boldsymbol{\delta}_m)$ where sample $m$ is fixed and $k\in\{1,\ldots,N_\text{displacement}\}$ varies over the displacement search space. Assuming a rectilinear, uniformly quantized search space over a lattice $\mathcal{L}\subset\mathbb{R}^3$ and $n$ grid points in each linear dimension, an exhaustive brute-force search (see Fig.~\ref{fig:complexity}a) is $O(n^3)$. \begin{figure*}[!htb] \centering \includegraphics[width=140mm]{fig-complexity.pdf} \caption{Displacement search space exploration strategies: (a) brute-force, (b) subject to autoregressive or motion predictive modelling constraints, (c) hierarchical approach.} \label{fig:complexity} \end{figure*} Depending on the surface geometry and sampling density, if the displacement estimation process is amenable to autoregressive or motion predictive modelling \cite{elnagar1998motion,kim2014robust}, complexity drops to $O(n^2)$. As an example, if the optimal displacement at three points in the vicinity of $\mathbf{x}_m$ are represented by the vertices of the triangle in the solution space in Fig.~\ref{fig:complexity}(b) and the cost function is locally convex, then the search may be constrained to the triangular region $\Omega\subset\mathbb{R}^2$. Although this paper does not mandate a specific implementation, it is worth noting that a hierarchical search strategy (see k-step successive refinement in Fig.~\ref{fig:complexity}c or \cite{konrad2005}) has an approximate complexity of $O(n\log n)$ since an ($2^3+1$) point search is conducted $k$ times, where $k\in\mathbb{Z}\approx \log_2 n$. \section{Performance evaluation}\label{sect:boundary-warping-fusion-workflow-validation} The benefits of spatial warping is first demonstrated, this will be followed by results from a large scale validation experiment. \begin{figure*}[!htb] \centering \includegraphics[width=140mm]{fig-surface-warping.pdf} \caption{Surface warping performed on a mineralization base surface. (a) original mesh surface, (b) warped surface, (c) map shows where the surface has elevated and sunk after warping. (d)--(e) Assays rendered above the original (resp. warped) surface are predominantly high-grade; (f) displacement field obtained through surface warping (an equivalent high resolution display is shown in Fig.~\ref{fig:displacement-field})} \label{fig:surface-warping} \end{figure*} \subsection{Local corrections due to spatial warping}\label{sect:local-correction-spatial-warping} Figure~\ref{fig:surface-warping} provides an overview of the surface warping result for a mineralization base surface where high grade material ideally sits above the boundary. The bottom panels illustrate the displacement field and highlight changes in elevation by superimposing the surfaces before and after warping. The right hand side panels in the top and middle row show the mineral (Fe) grade of the assay samples situated above the original and warped surfaces. \begin{figure*}[!htb] \centering \includegraphics[width=125mm]{fig-displacement-field.pdf} \caption{Changes to the surface: (a) signed distance visualization obtained from (b) vertices displacement field; (c)--(d) magnified view of the displacement field in two sub-regions.} \label{fig:displacement-field} \end{figure*} Figure~\ref{fig:displacement-field}(a) describes the topological changes to the warped surface. It conveys the same information as Fig.~\ref{fig:surface-warping}(c) albeit at higher resolution. This signed distance visualization is generated using a multiscale cloud compare algorithm \cite{lague2013accurate} which takes the original and warped surface vertices as input and displays elevation differences as a color map. Figure~\ref{fig:displacement-field}(b) and insets show the raw displacement field obtained directly from the warping process as a quiver plot. \begin{figure*}[!htb] \centering \includegraphics[height=78mm,width=125mm]{fig-surface-warping-differences-magnified.pdf} \caption{Fe grade of assay samples situated above the (top) original and (bottom) warped `min\_base' surface.} \label{fig:surface-warping-differences-magnified} \end{figure*} Figure~\ref{fig:surface-warping-differences-magnified} examines the effects of surface warping in more detail. It provides a magnified view of the rectangular region shown in Fig.~\ref{fig:surface-warping}(d) and (e). As expected, areas pointed by an arrow have contracted after surface warping. This results in the correct behaviour whereby non-mineralized samples have vanished below the mineralization boundary which is implicitly represented by the warped surface. The white lines indicate inclusive behaviour (or areas of expansion) where mineralized samples have risen above the mineralization boundary following surface warping. Overall, local delineation between high-grade and low-grade material has improved. The surface has effectively been pushed down to include more mineralized (red) samples and lifted up to exclude more low-grade (yellow) samples. Although the assay samples are coloured by iron grade alone in this illustration, it is worth bearing in mind that ore grade is assessed in practice as a function of multiple chemical components and this often includes Al\textsubscript{2}O\textsubscript{3} and other trace elements. \begin{figure*}[!htb] \centering \includegraphics[width=125mm]{fig-surface-sections-with-assays.pdf} \caption{Surface cross-sections taken at (a) $400\pm 5$m and (b) $440\pm 5$m show better delineation between waste and high-grade samples after warping.} \label{fig:surface-sections-with-assays} \end{figure*} Figure~\ref{fig:surface-sections-with-assays} presents an alternative view. Surface cross-sections (the shell being visualized as black ribbons) are shown together with assay samples (coloured by grade) at two different elevations. Local changes are indicated by the arrows. The original surface is inaccurate at (a.1) as it excludes certain high-grade samples whereas in (a.2), (a.3) and (b.4) waste samples are included inside the boundary. Evidently, the warped surface provides better delineation between waste and high-grade samples as the boundary encircles the waste; this is especially noticeable at (b.4) in the warped surface. These observations can be verified quantitatively in Table~\ref{tab:samples-above-below-original-and-warped-surface} which demonstrates more effective separation of high grade and waste samples with warping.\footnote{Note that the dominant samples (HG/BL above the surface, and LG/W below the surface) do not quite reach 100\%. In part, this is due to some assay samples being taken from hole intervals that span across mineralized and non-mineralized geozones. Other surfaces that further delineate HG and W materials are not considered for the purpose of this evaluation.} \begin{table}[h] \begin{center} \small \setlength\tabcolsep{4pt} \caption{Assay samples above and below the original and warped surfaces, categorised by High grade (HG), Blended (BL) siliceous and aluminous, Low grade (LG) and Waste (W).}\label{tab:samples-above-below-original-and-warped-surface} \begin{tabular}{|l|p{12mm}|p{6mm}p{6mm}|p{6mm}p{6mm}|p{6mm}p{6mm}p{6mm}|c|c|}\hline \multicolumn{11}{|c|}{Samples located above surface}\\ \hline Surface & HG & BLS & BLA & LGS & LGA & W\textsubscript{1} & W\textsubscript{2} & W\textsubscript{3} & $\frac{\text{(HG+BL)}}{\text{(HG+BL+LG+W)}}$ & $\frac{\text{(HG+BL)}}{\text{(HG+BL+W)}}$ \\ \hline \textbf{original} & 12809 & 1609 & 3127 & 714 & 884 & 2588 & 1899 & 113 & 73.8\% & 79.2\% \\ \textbf{warped} & 13421 & 1730 & 3286 & 710 & 975 & 2194 & 1968 & 145 & 75.5\% & 81.0\% \\ \hline change & ++++++ & + & ++ & & + & -\,-\,-\,- & + & & +1.7\% & +1.8\% \\ \hline \multicolumn{11}{|c|}{Samples located below surface}\\ \hline Surface & HG & BLS & BLA & LGS & LGA & W\textsubscript{1} & W\textsubscript{2} & W\textsubscript{3} & $\frac{\text{(LG+W)}}{\text{(HG+BL+LG+W)}}$ & $\frac{\text{(W)}}{\text{(HG+W)}}$ \\ \hline \textbf{original} & 1396 & 723 & 553 & 513 & 558 & 3874 & 876 & 223 & 69.3\% & 78.0\% \\ \textbf{warped} & 783 & 602 & 394 & 518 & 468 & 4268 & 806 & 191 & 77.8\% & 87.1\% \\ \hline change & -\,-\,-\,-\,-\,- & - & -\,- & & - & ++++ & - & & +8.5\% & +9.1\% \\ \hline \end{tabular} \end{center} \end{table} \subsection{Validation experiment}\label{sect:validation-experiment} To provide an objective evaluation, an end-to-end validation procedure known as r\textsubscript{2} spatial reconciliation is applied to assess the potential benefits of the proposed scheme where surface warping, block model restructuring and interval GP grade inferencing are applied, relative to a baseline resource model where none of these are used. The comparison requires computing r\textsubscript{2} values or ratios of (grade-block average)/(model predicted value) for each respective model and a chemical of interest, where a ``grade-block'' is an industry term that refers to regions with fairly constant composition and a typical volume ranging from 625\,m\textsuperscript{3} to 145,000\,m\textsuperscript{3}. These grade-blocks are marked with a destination tag for mining excavation purpose based on material types and/or the estimated grades. The grade-block averages (for Fe, SiO\textsubscript{2} etc.) are computed by geologists using the blast hole assays contained within the grade-block boundaries. The corresponding model predictions are volume-weighted averages of the GP inferenced mean grade values calculated over all blocks (perhaps numbered in the tens, hundreds or thousands) that intersect with each grade-block.\footnote{Fair sampling --- whether the number of samples taken is adequate and representative of the geology --- is an important consideration from the viewpoints of reliability and performance evaluation. In reality, suboptimal sampling does occur particularly in low-grade regions where the cost of extra sampling outweighs the benefit of knowing more about a waste zone with zero profit potential. In any event, the grade-block averages are as close to the ground truth as one can possibly attain.} Table~\ref{tab:r2-reconciliation-raw-data} shows the raw data for 5 grade-blocks and r\textsubscript{2} values computed for the proposed and reference model. Each grade-block is identified by the pit, bench and destination-tag. What is shown is only a snippet of a large table. The dest-tags\footnote{HG = high grade, WH = waste/hydrated, BGA = blended aluminous, LGS = low grade siliceous.} represent a classification based on average grade-block composition. For validation, we will consider two pits (A and B) from a Pilbara iron ore mine and five benches each of height 10m with a base elevation from 70m to 110m in 10m increment. In Table~\ref{tab:r2-reconciliation-raw-data}, bench 90 extends from a height of 90m to 100m. Accordingly, the grade-blocks used for evaluation are restricted to this z-interval. Model performance will be evaluated in `intra-bench' and 'predictive' mode. The former, indicated by RL\textsubscript{90} for instance, allows data down to a minimum elevation of 90m to be used during modelling (incl. GP training). Evaluation of an RL\textsubscript{90} model on bench 90 indicates how well a model interpolates the assay data. The latter, indicated by RL\textsubscript{100}, permits only data down to 100m to be used during modelling. Evaluation of an RL\textsubscript{100} model on unseen data from bench 90 focuses on a model's look-ahead (generalization and prediction) capability, viz. how well it vertically extrapolates the assay data. These differences are illustrated in Fig.~\ref{fig-intra-vs-inter-prediction}. \begin{figure*}[!htb] \centering \includegraphics[width=140mm]{fig-intra-vs-inter-prediction.pdf} \caption{Model evaluation inferencing modes. (Left) bench-below\,/\,forward prediction, (right) intra-bench estimation mode.} \label{fig-intra-vs-inter-prediction} \end{figure*} \begin{table}[h] \begin{center} \small \setlength\tabcolsep{4pt} \caption{r\textsubscript{2} spatial reconciliation: excerpt of raw data showing the grade-block (gb) and model predicted averages and normalized tonnage associated with 5 grade blocks.}\label{tab:r2-reconciliation-raw-data} \begin{tabular}{|l|r|p{7mm}p{9mm}|p{8mm}|p{7mm}p{9mm}|p{8mm}|p{7mm}p{9mm}|p{8mm}|}\hline \begin{tabular}{@{}l@{}}Pit\,/\,bench\,/\\ blast\#\,/\,dest-tag\end{tabular} & tonne\% & \begin{tabular}{@{}c@{}}Fe\\ (gb)\end{tabular} & \begin{tabular}{@{}c@{}}Fe\\ (model)\end{tabular} & \begin{tabular}{@{}c@{}}\textbf{Fe}\\ \textbf{r\textsubscript{2}}\end{tabular} & \begin{tabular}{@{}c@{}}SiO\textsubscript{2}\\ (gb)\end{tabular} & \begin{tabular}{@{}c@{}}SiO\textsubscript{2}\\ (model)\end{tabular} & \begin{tabular}{@{}c@{}}\textbf{SiO\textsubscript{2}}\\ \textbf{r\textsubscript{2}}\end{tabular} & \begin{tabular}{@{}c@{}}Al\textsubscript{2}O\textsubscript{3}\\ (gb)\end{tabular} & \begin{tabular}{@{}c@{}}Al\textsubscript{2}O\textsubscript{3}\\ (model)\end{tabular} & \begin{tabular}{@{}c@{}}\textbf{Al\textsubscript{2}O\textsubscript{3}}\\ \textbf{r\textsubscript{2}}\end{tabular}\\ \hline \multicolumn{11}{|c|}{Proposed model}\\ \hline A\,/\,90\,/\,1\,/\,HG13 & 1.47028 & 63.558 & 63.679 & 0.998 & 2.281 &\ 2.219 & 1.027 & 1.977 & 1.892 & 1.045\\ A\,/\,90\,/\,1\,/\,WH10 & 0.90878 & 47.969 & 54.935 & 0.873 & 25.786 & 14.664 & 1.758 & 1.762 & 2.022 & 0.871\\ A\,/\,90\,/\,3\,/\,HG23 & 1.25085 & 62.237 & 59.237 & 1.050 & 3.834 &\ 7.195 & 0.532 & 2.011 & 1.758 & 1.143\\ A\,/\,90\,/\,399\,/\,BGA9 & 0.73250 & 56.618 & 55.832 & 1.014 & 8.807 &\ 9.748 & 0.903 & 3.034 & 3.228 & 0.940\\ A\,/\,90\,/\,5\,/\,LGS40 & 0.95260 & 54.531 & 52.953 & 1.029 & 9.440 & 10.383 & 0.909 & 6.853 & 7.581 & 0.904\\ \hline \multicolumn{11}{|c|}{Reference model}\\ \hline A\,/\,90\,/\,1\,/\,HG13 & 1.53145 & 63.558 & 62.942 & 1.009 & 2.281 &\ 2.640 & 0.863 & 1.977 & 2.098 & 0.942\\ A\,/\,90\,/\,1\,/\,WH10 & 0.89634 & 47.969 & 56.863 & 0.843 & 25.786 & 11.948 & 2.158 & 1.762 & 2.048 & 0.860\\ A\,/\,90\,/\,3\,/\,HG23 & 1.13243 & 62.237 & 63.299 & 0.983 & 3.834 &\ 2.434 & 1.575 & 2.011 & 2.061 & 0.975 \\ A\,/\,90\,/\,399\,/\,BGA9 & 0.63901 & 56.618 & 51.399 & 1.101 & 8.807 & 16.487 & 0.534 & 3.034 & 3.301 & 0.919 \\ A\,/\,90\,/\,5\,/\,LGS40 & 0.94149 & 54.531 & 56.785 & 0.960 & 9.440 &\ 8.183 & 1.153 & 6.853 & 5.719 & 1.198 \\ \hline \end{tabular} \end{center} \end{table} In order to convey useful information for large-scale performance evaluation, we propose using an r\textsubscript{2} error score. First, the r\textsubscript{2} values associated with bench $z$ and an RL\textsubscript{\textit{h}} model (where $h=z$ in intra-bench mode, or $h=z+10$ in predictive mode) are sorted in increasing order and cumulative tonnage percentages are computed. This produces an r\textsubscript{2} cumulative distribution function (cdf); an example of which is shown in Fig.~\ref{fig-obk-reconciliation-r2-cdf}(a). An $r_2$ value less than 1 indicates over-estimation by the model, conversely, a value greater than 1 indicates under-estimation w.r.t. the grade-blocks. In a perfect scenario where there is zero discrepancy between the grade-blocks and model predicted values, the cdf curve becomes a step function that transitions from 0\% to 100\% at an r\textsubscript{2} value of 1. Hence, adding the area below the curve for $r_2 < 1$ to the area above the curve for $r_2 \ge 1$ provides an aggregate error measure (a performance statistic) of a model for a given pit, bench and chemical. The graphs also give insight. For instance, the left-leaning red curve in Fig.~\ref{fig-obk-reconciliation-r2-cdf}(f) provides evidence of bias, viz. the reference model has a tendency of over-estimating the Al\textsubscript{2}O\textsubscript{3} grade in pit B for bench 90. \begin{figure*}[!t] \centering \includegraphics[width=140mm]{fig-obk-reconciliation.pdf} \caption{Evaluation of orebody grade estimation RL\textsubscript{90} model using grade blocks from two pits and bench 90. The r\textsubscript{2} cumultative distribution function associated with pit A (top) and pit B (bottom) are shown from left to right for Fe, SiO\textsubscript{2} and Al\textsubscript{2}O\textsubscript{3}.} \label{fig-obk-reconciliation-r2-cdf} \end{figure*} \begin{table}[h] \begin{center} \footnotesize \setlength\tabcolsep{4pt} \caption{r\textsubscript{2} spatial reconciliation $r_2$ statistics.}\label{tab:r2-reconciliation-stats} \begin{tabular}{|c|c|ccc|ccc|ccc|ccc|}\hline & & \multicolumn{6}{c|}{Pit A} & \multicolumn{6}{c|}{Pit B}\\ & &\multicolumn{3}{c}{Proposed model} & \multicolumn{3}{c|}{Reference}& \multicolumn{3}{c}{Proposed model} & \multicolumn{3}{c|}{Reference}\\ \hline Bench & Model & Fe & SiO\textsubscript{2} & Al\textsubscript{2}O\textsubscript{3} & Fe & SiO\textsubscript{2} & Al\textsubscript{2}O\textsubscript{3} & Fe & SiO\textsubscript{2} & Al\textsubscript{2}O\textsubscript{3} & Fe & SiO\textsubscript{2} & Al\textsubscript{2}O\textsubscript{3}\\ \hline \multicolumn{2}{c}{} &\multicolumn{12}{c}{Intra-bench estimation performance}\\ \hline 110 & RL\textsubscript{110} & \textbf{4.271} & \textbf{18.202} & \textbf{12.059} & 7.761 & 34.531 & 19.995 & \textbf{3.351} & \textbf{20.905} & \textbf{17.516} & 4.069 & 21.737 & 20.087\\ 100 & RL\textsubscript{100} & \textbf{5.411} & \textbf{28.101} & \textbf{24.784} & 8.548 & 46.368 & 29.377 & \textbf{2.093} & \textbf{15.670} & \textbf{11.505} & 3.282 & 22.298 & 19.057\\ 90 & RL\textsubscript{90} & \textbf{5.948} & \textbf{26.851} & \textbf{14.468} & 11.776 & 51.499 & 41.703 & \textbf{2.411} & \textbf{16.817} & \textbf{10.962} & 5.365 & 32.322 & 22.423\\ 80 & RL\textsubscript{80} & \textbf{4.693} & \textbf{16.172} & \textbf{21.967} & 12.182 & 60.436 & 27.069 & \textbf{6.777} & \textbf{22.986} & \textbf{18.957} & 10.461 & 39.828 & 29.820\\ 70 & RL\textsubscript{70} & \textbf{9.420} & \textbf{19.646} & \textbf{25.036} & 11.135 & 49.092 & 53.319 & \textbf{9.416} & \textbf{24.409} & \textbf{44.289} & 9.688 & 39.862 & 77.711 \\ \hline $\mu_\text{g}$ & & \textbf{5.711} & \textbf{21.280} & \textbf{18.828} & 10.117 & 47.611 & 31.816 & \textbf{4.042} & \textbf{19.862} & \textbf{17.933} & 5.919 & 30.140 & 28.823\\ \hline \multicolumn{2}{c}{} &\multicolumn{12}{c}{Bench-below prediction performance}\\ \hline 100 & RL\textsubscript{110} & \textbf{6.707} & \textbf{41.035} & 34.372 & 8.548 & 46.372 & 29.381 & 4.136 & 20.800 & 25.621 & 3.282 & 19.060 & 22.301 \\ 90 & RL\textsubscript{100} & \textbf{9.832} & \textbf{41.214} & \textbf{26.107} & 11.776 & 51.495 & 38.455 & \textbf{4.100} & \textbf{29.440} & \textbf{17.766} & 5.365 & 32.322 & 22.425 \\ 80 & RL\textsubscript{90} & \textbf{7.336} & \textbf{24.695} & \textbf{21.196} & 12.182 & 60.437 & 27.067 & \textbf{8.794} & \textbf{29.516} & \textbf{27.742} & 10.461 & 39.821 & 29.817 \\ 70 & RL\textsubscript{80} & \textbf{8.069} & \textbf{28.985} & \textbf{42.950} & 11.135 & 49.097 & 53.319 & \textbf{9.605} & \textbf{25.907} & \textbf{63.121} & 9.688 & 39.859 & 77.786 \\ \hline $\mu_\text{g}$ & & \textbf{7.904} & \textbf{33.170} & \textbf{30.064} & 10.810 & 51.594 & 35.734 & \textbf{6.152} & \textbf{27.558} & \textbf{28.362} & 6.500 & 32.705 & 31.554\\ \hline \multicolumn{14}{c}{$\mu_\text{g}$ denotes the geometric mean} \end{tabular} \end{center} \end{table} The two pits combined contain over 400 grade-blocks and a volume in excess of $3\times10^6$ m\textsuperscript{3}. The summary statistics for intra-bench estimation and bench-below prediction are shown in Table~\ref{tab:r2-reconciliation-stats}. The main observation is that the proposed model outperforms the reference model. With few exceptions, the r\textsubscript{2} error scores are consistently lower for both intra-bench and bench-below prediction for Fe, SiO\textsubscript{2} and Al\textsubscript{2}O\textsubscript{3}. Generally, the error scores are higher for bench-below prediction, the performance gap reflects the relative difficulty of the problem. These findings suggest the use of surface warping, block model spatial restructuring and interval GP inference can increase accuracy in grade estimation. In particular, improving the alignment of mesh surfaces with respect to the underlying boundaries (using the observed geochemistry from samples to enforce consistency) can make a real difference and improve orebody modelling outcomes. \subsection{Discussion}\label{sect:discussion} Although the results have been analyzed in the context of improving grade models, there is also intrinsic value in updating geological boundaries via surface warping using geochemical assay data. The ability to better characterize the lithological contacts (e.g. transition between mineralized and unmineralized domains) improves the mine geologist's ability to understand ore genesis events, particularly fluid flow within major structures in a banded iron formation (BIF) hosted iron ore sytem \cite{hagemann2016bif,perring2020new}. Shale boundaries\footnote{Shale is essentially a clay mineral with elevated SiO\textsubscript{2} and Al\textsubscript{2}O\textsubscript{3} content.}, along with folds and faults, play a significant role in controlling mineralization as fluid pathways are restricted by impermeable layers such as shale bands. From a modelling perspective, warped surfaces have been used successfully to modify the block model structure in \cite{leung2020mos} to improve the delineation between domains for grade estimation. Commercially available geo-modelling softwares often employ implicit modelling techniques \cite{cowan2003practical} to extract boundary as an iso-surface from a manifold. Recent work by Renaudeau et al.\,even handles discontinuities \cite{renaudeau2019implicit}. A recognized problem with this process is that it generally assumes the entire dataset is available and models everything at once. In contrast, our proposal honors the geologist's interpretations and uses the mesh surfaces prepared by experts as starting points. The warping procedure can be applied iteratively as more production data (for instance, blasthole assays from a single bench) become available to rectify surfaces incrementally. This flexible approach works well with sparse data and periodic updates which underscore the progressive nature of open-pit mining. More accurate knowledge about these geological boundaries can be exploited to improve decision making and process efficiency. It facilitates dynamic mine planning and presents options on whether to excavate, postpone or abandon operations in an area. Then, there is the fleet management and task scheduling aspect which coordinates the movement of mining equipment \cite{samavati2019improvements} such as diggers, excavators and haul trucks, directing them when and where to go to achieve flow targets \cite{seiler2020flow}. Knowing where an ore/waste transition might occur, drill-charge-and-blast operations may be optimized with respect to placement and depth. The directional information conveyed by the surfaces also provides guidance for adaptive sampling \cite{ahsan-15} which maximizes utility and minimizes cost. This allows specific areas to be targeted where the boundary transition is most uncertain. As Fig.~\ref{fig-changes-propagating-to-bench-below} shows, surface warping can project information to an adjacent bench or the bench below; this gives to some extent a forward stratigraphic modelling capability, allowing the drilling density and assay sampling rate to be adjusted if needed. Geological risks \cite{benndorf2013stochastic} can be mitigated with an improved grade model. These risks include identifying sticky or hazardous material, as well as grade control in general, such as finding waste instead of ore in a variable grade block. \begin{figure*}[!t] \centering \includegraphics[width=85mm]{fig-changes-propagating-to-bench-below.pdf} \caption{Surface warping can propagate directional information about a boundary to the bench below} \label{fig-changes-propagating-to-bench-below} \end{figure*} \section{Conclusion}\label{sect:conclusion} This paper described the importance of having an accurate surface for grade estimation in mining. As motivation, it was shown that an inaccurate surface --- one that fails to capture the location and shape of the underlying geological boundary --- can impact the block structure and inferencing ability of the resultant grade estimation model which in turn can lead to smearing and misleading interpretations. The main contribution was a Bayesian formulation of the surface warping problem which seeks to maximize the agreement between the surface and observed data. The objective was to reshape the surface where possible to provide a clear delineation between ore and waste material that is consistent with the observations. This involved estimating and applying the optimal displacement to the mesh vertices based on spatial and compositional analysis. The maximum a posteriori (MAP) solution considered the chemistry observation likelihood in a given geozone and incorporated an a priori spatial structure which allows the likelihood of a displacement estimate to be computed using geological domain knowledge. The results showed that locally, the mineralized and non-mineralized samples are better separated by the warped surface. For end-to-end performance evaluation which encompasses surface warping, block model spatial restructuring, and grade estimation based on GP inferencing, the \textit{r\textsubscript{2} reconciliation error score} was proposed. This provided a grade model validation metric that is useful irrespective of the actual algorithms\,/\,processes deployed in the system components. Our experiments showed the r\textsubscript{2} error scores were consistently and significantly lower with surface warping when the estimated grades for chemicals of interest (Fe, SiO\textsubscript{2} and Al\textsubscript{2}O\textsubscript{3}) were compared with over 400 grade-blocks for two large pits, having a total volume in excess of $3\times 10^6$ m\textsuperscript{3}. This demonstrated the value of implementing the displacement estimation framework for surface warping\,/\,boundary rectification, and spatial algorithms more generally, in a mining automation context. \section{Authorship statement} The first two authors contributed to the core contents in this paper. Alexander Lowe studied surface warping (mesh vertices displacement estimation) as a maximum likelihood problem. He investigated different strategies and provided a concrete software implementation. Raymond Leung reformulated the problem in a Bayesian framework, developed the block model spatial restructuring algorithms, and proposed using the R\textsubscript{2} CDF error score as a validation measure. He conceptualized this paper and wrote the manuscript in consultation with other authors. Anna Chlingaryan and Arman Melkumyan devised the covariance functions and mathematical framework for grade estimation and GP inference using interval data (see Appendix). John Zigman conducted the validation experiments. John and Raymond performed data analysis and interpreted the results. \begin{appendix} \section{Appendix: Gaussian Processes --- inferencing for grade estimation}\label{sect:inferencing-for-grade-estimation} Inferencing refers to the task of predicting the grade value for certain chemicals of interest at locations where direct assay measurements are unavailable. In this exposition, Gaussian Process (GP) is used to provide a probabilistic model of the grade functions given a set of data, this allows both the mean and uncertainty associated with the compositional percentage of various chemicals such as Fe, SiO\textsubscript{2} etc.\,to be estimated. Inferencing is generally preceded by a training phase which optimizes the hyper-parameters that describe the Gaussian Process. Mathematically, a GP is an infinite collection of random variables, any finite number of which has a joint Gaussian distribution. Machine learning using GPs consists of two steps: training and inference. For training, simulated annealing and gradient descent procedures are used to optimize the hyper-parameters to create a probabilistic model that best represents the training data. Specifically, the GP hyper-parameters include \textit{length scales} that describe the rate of change in composition with space, and \textit{noise variance} that describes the amount of noise present in the data. A training set $\mathcal{T}=(X,\mathbf{y})$ consists of a matrix of training samples $X=[x_1,x_2,\ldots,x_N]^T\in\mathbb{R}^{N\times D}$ and corresponding target vector $\mathbf{y}=[y_1,y_2,\ldots,y_N]\in\mathbb{R}^N$. Here, $N$ represents the number of training samples available for a geozone. Each $x_i\in\mathbb{R}^D$ denotes an observation (the spatial coordinates where an assay sample is taken) and the associated value $y_i\in\mathbb{R}$ denotes a chemical's compositional percentage. The objective is to compute the predictive distribution $f(x_*)$ at various test points $x_*$. Formally, a GP model places a multivariate Gaussian distribution over the space of function variables $f(x)$, mapping input to output spaces. GPs can also be considered as a stochastic process that can be fully specified by its mean function $m(x)$ and covariance function $k(x,x')$. To completely describe the standard regression model, we assume Gaussian noise $\varepsilon$ with variance $\sigma_\text{n}^2$, so that $y=f(x)+\varepsilon$. With a training set $(X, f, y)=(\{x_i\}, \{f_i\}, \{y_i\})_{i=1:N}$ and test set $(X, f, y)=(\{x_{*i}\}, \{f_{*i}\}, \{y_{*i}\})_{i=1:N}$ where $\{y_i\}$ are observed and $\{y_{*i}\}$ are unknown and $m(x)=0$, the joint distribution becomes \begin{align} \begin{bmatrix}y \\ f_*\end{bmatrix}\sim \mathcal{N}\left(0,\begin{bmatrix}K(X,X)+\sigma_\text{n}^2 I & K(X,X_*)\\K(X_*,X)& K(X_*,X_*)\end{bmatrix}\right) \label{eq:gp-joint-distribution} \end{align} In Equation~(\ref{eq:gp-joint-distribution}), $\mathcal{N}(\mu, cov(f_*))$ is a multivariate Gaussian distribution with mean $\mu$, posterior covariance at the estimated locations $cov(f_*)$, and $K$ is the covariance matrix computed between all the points in the set. Thus, the matrix element $K_{i,j*}\equiv K(X_i,X_{*j})$ for instance is obtained by applying the kernel to the locations of sample $x_i$ and $x_{*j}$ from the training and test sets, respectively. By conditioning on the observed training points, the predictive distribution for new points can be obtained as: \begin{align} p(f_*\!\mid\! X_*,X,y)=\mathcal{N}(\mu, cov(f_*))\label{eq:gp-predictive-dist} \end{align} where \begin{align} \mu&=K(X_*,X)\left[K(X,X)+\sigma_\text{n}^2I\right]^{-1} y\label{eq:gp-predictive-mean} \end{align} and the posterior covariance \begin{align} cov(f_*)&=K(X_*,X_*) - K(X_*,X)\left[K(X,X)+\sigma_\text{n}^2 I\right]^{-1} K(X,X_*)\label{eq:gp-predictive-covariance} \end{align} Learning a GP model is equivalent to learning the hyper-parameters of the covariance function from a data set. In a Bayesian framework, this can be performed by maximising the log of the marginal likelihood \cite{williams2006gaussian} with respect to $\theta$: \begin{align} \log p(y\mid X,\theta)=-\frac{1}{2}y^T\left[K(X,X)+\sigma_\text{n}^2 I\right]^{-1}y -\frac{1}{2}\log\left|K(X,X)+\sigma_\text{n}^2 I\right|-\frac{N}{2}\log 2\pi\label{eq:gp-nlml} \end{align} The marginal likelihood is a non-convex function, thus only local maxima can be obtained. It has three terms (from left to right) that represent the data fit, complexity penalty (to include the Occam's razor principle) and a normalization constant. In this standard framework, the main contribution is the design of new kernels \cite{rtgi-rtcma2014} that deal with not only point-based observations, but also \textit{interval} observations where $y_i$ represents an average assay value measured over some interval in drilled holes. This enables performing data fusion between exploration and blast hole assays taking into consideration their respective supports. The GP covariance functions for interval data are described mathematically in \cite{rtgi-rtcma2014}. Relevant works that underpin this theory can be found in \cite{jewbali2011apcom} and \cite{rasmussen2003bayesian}. \end{appendix} \vspace{3mm} \section*{Acknowledgment} This work was supported by the Australian Centre for Field Robotics and the Rio Tinto Centre for Mine Automation. \bibliographystyle{unsrt}
{'timestamp': '2021-04-01T02:08:04', 'yymm': '2005', 'arxiv_id': '2005.14427', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14427'}
arxiv
\section{Introduction} \blfootnote{* First authors contributed equally.} Automated analysis of microscopic images heavily relies on classification or segmentation of objects in the image. Starting from a robust and precise segmentation algorithm, downstream analysis subsequently will be more accurate and reliable. Deep learning (DL) approaches nowadays have state-of-the-art performance in nearly all computer vision tasks (\cite{russakovsky2015imagenet}). In medical images or more specifically in computational pathology (CP), DL plays an important role for tackling wide range of tasks. Despite their success, DL methods have a major problem-their data hungry nature. If they are not provided with sufficient data, they can easily over-fit on the training data, leading to poor performance on the new unseen data. In computational pathology, most models are trained on datasets that are acquired from just a small sample size of whole data distribution. These models would fail if they are applied on a new distribution (e.g new tissue types or different center that data is coming from). Hence, one needs to collect annotation from new distribution and then add it to training set to overcome false predictions. Obtaining annotation as a target for training deep supervised models is time consuming, labour-intensive and sometimes involves expert knowledge. Particularly, for segmentation task where dense annotation is required. It is worth mentioning that in terms of performance, semi-supervised and weakly supervised methods are still far behind fully supervised methods (\cite{taghanaki2019deep}). Therefore, if one needs to build a robust and applicable segmentation algorithm, supervised methods are priority. In CP, fully automatic approaches which do not require user interactions have been extensively applied on histology images for segmentation of different objects (e.g. cells, nuclei, glands, etc.) where DL models have shown state-of-the-art performance (\cite{sirinukunwattana2017gland, kumar2019multi, graham2019hover, koohbanani2019nuclear, pinckaers2019neural, graham2019mild, chen2016dcan, gamper2020pannuke, zhou2019cia}). Semi-automatic (interactive) segmentation approaches which require the user to provide an input to the system bring several advantages over fully automated approaches: 1) due to the supervisory signal as a prior to the model, interactive models lead to better performance; 2) possible mistakes can be recovered by user interactions; 3) interactive models are less sensitive to domain shift since the supervisory signal can compensate for variations in domains, in other words, interactive models are more generalizable; and 4) selective attribute of interactive models gives the flexibility to the user to choose the arbitrary instances of objects in the visual field (e.g selecting one nucleus for segmentation out of hundreds of nuclei in the ROI). Due to generalizability power, these models can also serve as annotation tool to facilitate and speed up the annotation collection. Then these annotations can be used to train a fully automatic method for extracting the relevant feature for the task in hand. For example delineating boundaries of all nuclei, glands or any object of interest is highly labour intensive and time consuming. To be more specific, considering that annotation of one nuclei takes 10s, a visual field containing 100 nuclei takes ~17 minutes to be annotated. To this end, among interactive models, approaches that require minimum user interaction are of high importance, as it not only minimizes the user effort but also speed up the process. In this paper, by concentrating on keeping user interactions as minimum as possible , we propose a unified CNN-based framework for interactive annotation of important microscopic object in three different levels (nuclei, cells, and glands). Our model accepts minimum user interaction which is suitable for collecting annotation in histology domain. \begin{figure}[h] \centering \includegraphics[width =0.9\columnwidth]{validation.pdf} \caption{\textbf{NuClick interactive segmentation} of objects in histopathological images with different levels of complexity: nuclei (first row), cells (second row), and glands (third row). Solid stroke line around each object outlines the ground truth boundary for that object, overlaid transparent mask is the predicted segmentation region by NuClick, and points or squiggles indicate the provided guiding signal for interactive segmentation.} \label{fig:validation} \end{figure} \section{Related Works} \subsection{Weakly Supervised Signals for Segmentation} Numerous methods have been proposed in the literature that utilise weak labels as supervisory signals. In these methods, supervisory signal serves as an incomplete (weak) ground truth segmentation in the model output. Therefore, a desirable weakly supervised model would be a model that generalize well on the partial supervisory signals and outputs a more complete segmentation of the desired object. These methods are not considered as interactive segmentation methods and are particularly useful when access to full image segmentation labels is limited. For instance, \cite{yoo2019pseudoedgenet} and \cite{qu2019weakly} introduced weakly supervised nucleus segmentation models which are trained based on nuclei centroid points instead of full segmentation masks. Several other works used image-level labels (\cite{pathak2014fully, kolesnikov2016seed, pathak2015constrained, wei2018revisiting}), boxes (\cite{khoreva2017simple}), noisy web labels (\cite{jin2017webly, ahmed2014semantic}), point-clicks (\cite{bearman2016s, bell2015material, chen2018tap, wang2014touchcut}), and squiggles (\cite{lin2016scribblesup, xu2015learning}) as weak labels to supervise their segmentation models. Our model is analogous to methods proposed by \cite{bearman2016s} and \cite{lin2016scribblesup} with the difference that we used points and squiggles as auxiliary guiding signals in the input of our model. Our model is fully supervised and we will show how this additional information can be used to further improve accuracy of segmentation networks on histology images. \subsection{Interactive segmentation} \label{Sec-inter} Interactive segmentation of objects has been studied for over a decade now. In many works (\cite{bai2009geodesic, batra2011interactively, boykov2001interactive, rother2004grabcut, cheng2015densecut, gulshan2010geodesic, shankar2015video, mortensen1998interactive, cagnoni1999genetic, de2004interactive, wang2018interactive, li2018interactive}) object segmentation is formulated as energy minimization on a graph defined over objects. In a recent unsupervised approach proposed by \cite{papadopoulos2017extreme}, the annotator clicks on four extreme points (left-most, right-most, top and bottom pixels), then an edge detection algorithm is applied to the whole image to extract boundaries, afterwards the shortest path between two neighboring extreme points is chosen as boundary of the object. Area within the boundaries is considered as foreground and the region outside the extreme points is considered as background for the appearance model. Grabcut (\cite{rother2004grabcut}) and Graphcut (\cite{kwatra2003graphcut}) are classic interactive segmentation models, which segment objects by gradually updating the appearance model. These models require the user to mark in both background and foreground regions. Although they use extensive guiding signals, they would fail if the object has blurred or complex boundaries. In recent years, CNN models have been extensively used for interactive segmentation (\cite{xu2017deep, xu2016deep, agustsson2019interactive, papadopoulos2017extreme, maninis2018deep, ling2019fast, castrejon2017annotating, acuna2018efficient, wang2019object}). A well-known example is DEXTRE (\cite{maninis2018deep}) which utilizes extreme points as an auxiliary input to the network. First, the annotator clicks four points on the extreme positions of objects then a heat map (Gaussian map for each point where points are at the centers of Gaussians) channel is created form these clicks which is attached to the input and serves as guiding signal. There are methods in the literature that require the user to draw a bounding box around the desired object. \cite{wang2018interactive} proposed a method for interactive medical images segmentation where an object of interest is selected by drawing a bounding box around it. Then a deep network is applied on a cropped image to obtain segmentation. They also have a refinement step based on Grabcut that takes squiggles from the user to highlight the foreground and background regions. This model is applicable for single object (an organ) segmentation in CT/MRI images where this organ has similar appearance and shape in all images. However, this approach is not practical for segmentation of multiple objects (like nuclei) or amorphous objects (like glands) in histology domain. Some methods combined bounding box annotations with Graph Convolutional Network (GCN) to achieve interactive segmentation (\cite{ling2019fast,castrejon2017annotating, acuna2018efficient}). In these methods the selected bounding box is cropped from the image and fed to a GCN to predict polygon/spline around object. The polygon surrounds the object then can be adjusted in an iterative manner by refining the deep model. Also, there are some hybrid methods which are based on the level sets (\cite{caselles1997geodesic}). \cite{acuna2019devil} and \cite{wang2019object} embedded the level set optimization strategy in deep network to achieve precise boundary prediction from coarse annotations. For some objects such as nuclei, manual selection of four extreme points or drawing a bounding box is still time-consuming, considering that an image of size 512$\times$512 can contain more that 200 nuclei. Moreover, extreme points for objects like glands are not providing sufficient guidance to delineate boundaries due to complex shape and unclear edges of such objects. In this paper, we propose to use a single click or a squiggle as the guiding signal to keep simplicity in user interactions while providing enough information. Similar to our approach is a work by \cite{sakinis2019interactive}, where the annotator needs to place two pairs of click points inside and outside of the object of interest. However, their method is limited to segmenting a single predefined object, like prostate organ in CT images unlike the multiple objects (nuclei, cell, and glands) in histology images, as is the case in this study, that mutate greatly in appearance for different cases, organs, sampling/staining methods, and diseases. \subsection{Interactive full image segmentation} Several methods have been proposed to interactively segment all objects within the visual field. \cite{andriluka2018fluid} introduced Fluid Annotation, an intuitive human-machine interface for annotating the class label and delineating every object and background region in an image. An interactive version of Mask-RCNN (\cite{he2017mask}) was proposed by \cite{agustsson2019interactive} which accepts bounding box annotations and incorporates a pixel-wise loss allowing regions to compete on the common image canvas. Other older works that also segment full image are proposed by \cite{nieuwenhuis2012spatially, nieuwenhuis2014co, santner2010interactive, vezhnevets2005growcut}. Our method is different from these approaches as these are designed to segment all objects in natural scenes, requiring the user to label the background region and missing instances may interfere with the segmentation of desired objects. Besides, these approaches require high degree of user interaction for each object instance (minimum of selecting 4 extreme points). However, in interactive segmentation of nuclei/cells from microscopy images, selecting four points for each object is very cumbersome. On the other hand, all above-mentioned methods are sensitive to the correct selection of extreme points which also can be very confusing for the user when he/she aims to mark a cancerous gland in histology image with complex shape and vague boundaries. Furthermore, another problem with a full image segmentation method like \cite{agustsson2019interactive} is that it uses Mask-RCNN backbone for RoI feature extraction which has difficulty in detecting objects with small sizes such as nuclei. In this paper we propose \textbf{NuClick} that uses only one point for delineating nuclei and cells and a squiggle for outlining glands. For nucleus and cell segmentation, proving a dot inside nucleus and cell is fast, easy, and does not require much effort from user compared to recent methods which rely on bounding boxes around objects. For glands, drawing a squiggle inside the glands is not only much easier and user friendly for annotator but also gives more precise annotations compared to other methods. Our method is suitable for single object to full image segmentation and is applicable to a wide range of object scales, i.e. small nuclei to large glands. To avoid interference of neighboring objects in segmentation of desired object, a hybrid weighted loss function is incorporated in NuClick training. This paper is complementary to our previous paper (\cite{jahanifar2019nuclick}), where we showed results of the preliminary version of NuClick and its application to nuclei, whereas here we extend its application to glands and cells. As a result of the current framework, we release two datasets of lymphocyte segmentation in Immunohistochemistry (IHC) images and segmentation mask of white blood cells (WBC) in blood sample images\footnote{https://github.com/navidstuv/NuClick}. A summary of our contributions is as follows: \begin{itemize} \item We propose the first interactive deep learning framework to facilitate and speed up collecting reproducible and reliable annotation in the field of computational pathology. \item We propose a deep network model using guiding signals and multi-scale blocks for precise segmentation of microscopic objects in a range of scales. \item We propose a method based on morphological skeleton for extracting guiding signals from gland masks, capable of identifying holes in objects. \item We Incorporate a weighted hybrid loss function in the training process which helps to avoid interference of neighboring objects when segmenting the desired object. \item Performing various experiments to show the effectiveness and generalizability of the NuClick. \item We release two datasets of lymphocyte dense annotations in IHC images and touching white blood cells (WBCs) in blood sample images. \end{itemize} \section{Methodology} \subsection{NuClick framework overview} Unlike previous methods that use a bounding box or at least four points \cite{maninis2018deep, boykov2001interactive, wu2014milcut, rother2012interactive, papadopoulos2017extreme} for interactive segmentation, in our proposed interactive segmentation framework only one click inside the desired object is sufficient. We will show that our framework is easily applicable for segmenting different objects in different levels of complexity. We present a framework that is applicable for collecting segmentation for nuclei which are smallest visible objects in histology images, then cells which consist of nucleus and cytoplasm, and glands which are a group of cells. Within the current framework the minimum human interaction is utilized to segments desired object with high accuracy. The user input for nucleus and cell segmentation is as small as one click and for glands a simple squiggle would suffice. NuClick is a supervised framework based on convolutional neural networks which uses an encoder-decoder network architecture design. In the training phase, image patches and guiding signals are fed into the network, therefore it can learn where to delineate objects when an specific guiding signal appears in the input. In the test phase, based on the user-input annotations (clicks or squiggles), image patches and guiding signal maps are generated to be fed into the network. Outputs of all patches are then gathered in a post-processing step to make the final instance segmentation map. We will explain in details all aspects of this framework in the following subsections. \subsection{Model architecture \& loss} Efficiency of using encoder-decoder design paradigm for segmentation models has been extensively investigated in the literature and it has been shown that UNet design paradigm works the best for various medical (natural) image segmentation tasks (\cite{hesamian2019deep, garcia2017review}). Therefore, similar to \cite{jahanifar2019nuclick}, an encoder-decoder architecture with multi-scale and residual blocks has been used for NuClick models, as depicted in \cref{fig:network architecture}. As our goal is to propose a unified network architecture that segments various objects (nuclei, cells and glands), it must be capable of recognizing objects with different scales. In order to segment both small and large objects, the network must be able to capture features on various scales. Therefore, we incorporate multi-scale convolutional blocks \cite{jahanifar2018segmentation} throughout the network (with specific design configurations related to the network level). Unlike other network designs (eg. DeepLab v3 \cite{chen2017rethinking}) that only uses multi-scale \textit{atrous} convolutions in the last low-resolution layer of the encoding path, we use them in three different levels both in encoding and decoding paths. By doing this, NuClick network is able to extract relatable semantic multi-scale features from the low-resolution feature maps and generate fine segmentation by extending the receptive fields of its convolution layers in high-resolution feature maps in the decoder part. Parameters configuration for residual and multi-scale blocks is shown on each item in the \cref{fig:network architecture} Furthermore, using residual blocks instead of plain convolutional layers enables us to design a deeper network without risk of gradient vanishing effect \cite{he2016deep}. In comparison to \cite{jahanifar2019nuclick}, the network depth has been further increased to better deal with more complex objects like glands. \begin{figure*} [ht!] \includegraphics[width =\textwidth]{architecture_nuclick+.pdf} \caption{Overview of the NuClick network architecture which consists of Convolutional, Residual, and Multi-Scale convolutional blocks.} \label{fig:network architecture} \end{figure*} The loss function used to train NuClick is a combination of soft dice loss and weighted cross entropy. The dice loss helps to control the class imbalance and the weighted cross entropy part penalizes the loss if in the prediction map other objects rather than the desired object were present. \begin{equation} \begin{array}{l} {\cal L} = 1 - {{\left( {\sum\limits_i {{p_i}{g_i} + \varepsilon } } \right)} \mathord{\left/ {\vphantom {{\left( {\sum\limits_i {{p_i}{g_i} + \varepsilon } } \right)} {\left( {\sum\limits_i {{p_i} + \sum\limits_i {{g_i} + \varepsilon } } } \right)}}} \right. \kern-\nulldelimiterspace} {\left( {\sum\limits_i {{p_i} + \sum\limits_i {{g_i} + \varepsilon } } } \right)}}\\ \quad \;\; - \frac{1}{n}\sum\limits_{i = 1}^n {{w_i}({g_i}\log {p_i} + (1 - {g_i})\log (1 - {p_i}))} \end{array} \label{eq:loss} \end{equation} where $n$ is the number of pixels in the image spatial domain, ${p_i}$, ${g_i}$, and ${w_i}$ are values of the prediction map, the ground-truths mask $\bf{G}$, and the weight map $\bf{W}$ at pixel $i$, respectively and $\varepsilon$ is a small number. Considering that $\bf{G}$ has value of 1 for the desired (included) objects and 0 otherwise, its complement ${\bf{\tilde G}}$ has value of 1 for the undesired (excluded) objects in the image and 0 otherwise. The adaptive weight map is then defined as: ${\bf{W}} = {\alpha}^2 {\bf{G}} + \alpha{\bf{\tilde G}}+1$ ,where $\alpha$ is the adaptive factor that is defined based on areas of the included and excluded objects as follows: $ \alpha = \max \left\{ {{{\sum {{\bf{\tilde G}}} } \mathord{\left/ {\vphantom {{\sum {{\bf{\tilde G}}} } {\sum {\bf{G}} }}} \right. \kern-\nulldelimiterspace} {\sum {\bf{G}} }},1} \right\}$. This weighting scheme puts more emphasis on the object to make sure it would be completely segmented by the network while avoiding false segmentation of touching undesired objects. \subsection{Guiding Signals} \subsubsection{Guiding signal for nuclei/cells} When annotator clicks inside a nucleus, a map to guide the segmentation is created, where the clicked position is set to one and the rest of pixels are set to zero which we call it \textit{inclusion map}. In most scenarios, when more than one nucleus are clicked by the annotator (if he/she wants to have all nuclei annotated), another map is also created where positions of all nuclei except the desired nucleus/cell are set to one and the rest of pixels are set to zero, which is called \textit{exclusion map}. When only one nucleus is clicked exclusion map is a zero map. Inclusion and exclusion maps are concatenated to RGB images to have 5 channels as the input to the network (as illustrated in \cref{fig:network architecture}). The same procedure is used for creating guiding signals of cells. However, we took some considerations into the training phase of the NuClick in order to make it robust against guiding signal variations. In the following paragraphs, we will describe these techniques for both training and testing phases. \paragraph{Training} To construct inclusion map for training, a point inside a nucleus/cell is randomly chosen. It has been taking into account that the sampled point has at least 2 pixels distance from the object boundaries. The exclusion map on the other hand is generated based on the centroid location of the rest of nuclei within the patch. Thereby, guiding signals for each patch are continuously changing during the training. Therefore the network sees variations of guiding signals in the input for each specific nuclei and will be more robust against human errors during the test. In other words the network learns to work with click points anywhere inside the desired nuclei so there is no need of clicking in the exact centroid position of the nuclei. \paragraph{Test} At inference time, guiding signals are simply generated based on the clicked positions by the user. For each desired click point on image patch, an inclusion map and an exclusion map are generated. The exclusion map have values if user clicks on more than one nuclei/cells, otherwise it is zero. Size of information maps for nuclei and cells segmentation tasks are set to $128\times128$ and $256\times256$, respectively. For test time augmentations we can disturb the position of clicked points by 2 pixels in random direction. The importance of exclusion map is in cluttered areas where nuclei are packed together. If the user clicks on all nuclei within these areas, instances will be separated clearly. In the experimental section we will show the effect of using exclusion maps. \subsubsection{Guiding signal for glands} Unlike nuclei or cells, since glands are larger and more complex objects, single point does not provide strong supervisory signal to the network. Therefore, we should chose another type of guiding signal which is informative enough to guide the network and simple enough for annotator during inference. Instead of points, we propose to use squiggles. More precisely, the user provides a squiggle inside the desired gland which determines the extent and connectivity of it. \paragraph{Training} Considering $\bf{M}$ as the desired ground truth (GT) mask in the output, an inclusion signal map is randomly generated as follows: First we apply a Euclidean distance transform function $D(x)$ on the mask to obtain distances of each pixel inside the mask to the closest point on the object boundaries: \begin{equation} {D_{i,j}}(\bf{M}) = \left\{ {\sqrt {{{(i - {i_b})}^2} + {{(j - {j_b})}^2}} |(i,j) \in \bf{M}} \right\} \end{equation} where ${i_b}$ and ${j_b}$ are the closest pixel position on the object boundary to the desired pixel position $(i,j)$. Afterwards, we select a random threshold ($\tau$) to apply on the distance map for generating a new mask of the object which indicates a region inside the original mask. $$ {{\overline \bf{M}}_{i,j}} = \left\{ \begin{array}{l} 1\,\,\,\,\,\,\,if\,\,{D_{i,j}} > \tau \\ 0\,\,\,\,\,\,otherwise\, \end{array} \right. $$ The threshold is chosen based on the mean ($\mu$) and standard deviation ($\sigma$) of outputs of distance function, where the interval for choosing $\tau$ is $[0 ,\mu + \sigma ]$. Finally, to obtain the proper guiding signal for glands, the morphological skeleton (\cite{serra1983image}) of the new mask ${\overline \bf{M}}$ is constructed. Note that we could have used the morphological skeleton of the original mask as the guiding signal (which does not change throughout the training phase) but that may cause the network to overfit towards learning specific shapes of skeleton and prevents it from adjusting well with annotator input. Therefore, by changing the shape of the mask, we change the guiding signal map during training. \begin{figure*}[ht] \centering \includegraphics[width =0.9\textwidth]{glandGuidingSignal.pdf} \caption{Generating supervisory signal (inclusion map) for NuClick while training on gland dataset. The left image is the GT mask of a sample gland and $D(\bf{M})$ is the distance transformation of that mask. By changing the threshold value ($\tau$), the guiding signal (skeleton of the new mask ${\overline \bf{M}}$ which is specified by green color) is also changing.} \label{fig:glandGuid} \end{figure*} An example of constructing map for a gland is depicted in the \cref{fig:glandGuid}. In this figure, the left hand side image represents the GT of the desired gland on which its corresponding skeleton is overlaid with green color. If we use this same mask for training the network, the guiding signal would remain the exact same for all training epochs. However, based on our proposed mask changing technique, we first calculate the distance transformation of the GT, $D(\bf{M})$, and then apply a threshold of $\tau$ on it to construct a new mask of ${\overline \bf{M}}$. As you can see in Fig. \ref{fig:glandGuid}, by changing the the threshold value, appearance of the new mask is changing which results in different morphological skeletons as well (note the change of overlaid green colored lines with different $\tau$ values). This will make the NuClick network robust against the huge variation of guiding signals provided by the user during the test phase. The exclusion map for gland is constructed similar to nuclei/cells i.e., except one pixel from each excluding object all other pixels are set to zero. \paragraph{Test} When running inference, the user can draw squiggles inside the glandular objects. Then patches of 512$\times$512 are extracted from image based on the bounding box of the squiggle. If the bounding box height or width is smaller than 512, it is relaxed until height and width are 512. And if the bounding box is larger than 512 then image and corresponding squiggle maps are down-scaled to 512$\times$512. \subsection{Post-processing} After marking the desired objects by the user, image patches, inclusion and exclusion maps are generated and fed into the network to predict an output segmentation for each patch. Location of each patch is stored in the first step, so it can be used later to build the final instance segmentation map. The first step in post-processing is converting the prediction map into an initial segmentation mask by applying a threshold of 0.5. Then small objects (objects with area less than 50 pixels) are removed. Moreover, for removing extra objects except desired nucleus/cell/gland inside the mask, morphological reconstruction operator is used. To do so, the inclusion map plays the role of marker and initial segmentation is considered as the mask in morphological reconstruction. \section{Setups and Validation Experiments} \subsection{Datasets} \paragraph{Gland datasets} Gland Segmentation dataset \cite{sirinukunwattana2017gland} (GlaS) and GRAG datasets \cite{awan2017glandular, graham2019mild} are used for gland segmentation. GlaS dataset consists of 165 tiles, 85 of which for training and 80 for test. Test images of GlaS dataset are also split into to TestA and TestB. TestA was released to the participants of the GlaS challenge one month before the submission deadline, whereas Test B was released on the final day of the challenge. Within GRAG dataset, there are a total of 213 images which is split into 173 training images and 40 test images with different cancer grades. Both of these datasets are extracted from Hematoxylin and Eosin (H\&E) WSIs. \paragraph{Nuclei dataset} MonuSeg (\cite{kumar2019multi}) and CPM (\cite{vu2019methods}) datasets which contain 30 and 32 H\&E images ,respectively, have been used for our experiments. 16 images of each of these datasets are used for training. \paragraph{Cell dataset} A dataset of 2689 images consisting of touching white blood cells (WBCs) were synthetically generated for cell segmentation experiments. To this end, we used a set of 11000 manually segmented non-touching WBCs (WBC library). Selected cells are from one of the main five category of WBCs: Neutrophils, Lymphocytes, Eosinophils, Monocytes, or Basophils. The original patches of WBCs were extracted from scans of peripheral blood samples captured by CELLNAMA LSO5 slide scanner equipped with oil immersion 100x objective lens. However, the synthesized images are designed to mimic the appearance of bone marrow samples. In other words, synthesized images should contain several (10 to 30) touching WBCs. Therefore, for generating each image a random number of cells are selected from different categories of WBC library and then they are added to a microscopic image canvas which contains only red blood cells. During the image generation each added cell is well blended into the image so its boundary looks seamless and natural. This would make the problem of touching object segmentation as hard as real images. It is worth mentioning that each WBC is augmented (deformed, resize, and rotate) before being added to the canvas. Having more than 11000 WBCs and performing cell augmentation during the image generation would guarantee that the network does not overfit on a specific WBC shape. For all datasets 20\% of training images are considered as validation set. \subsection{Implementation Details} For our experiments, we used a work station equipped with an Intel Core i9 CPU, 128GB of RAM and two GeForce GTX 1080 Ti GPUs. All experiments were done in Keras framework with Tensorflow backend. For all applications, NuClick is trained for 200 epochs. Adam optimizer with learning rate of $3 \times {10^{ - 3}}$ and weight decay of of $5 \times {10^{ - 5}}$ was used to train the models. Batch size for nuclei, cell and gland was set to 256, 64 and 16 respectively. We used multiple augmentations as follows: random horizontal and vertical flip, brightness adjustment, contrast adjustment, sharpness adjustment, hue/saturation adjustment, color channels shuffling and adding Gaussian noise (\cite{jahanifar2018segmentation}). \subsection{Metrics} For our validation study we use metrics that has been reported in the literature for cell and gland instance segmentation. For nuclei and cells we have used AJI (Aggregated Jaccard Index) proposed by \cite{kumar2017dataset}: an instance based metric which calculates Jaccard index for each instance and then aggregates them, Dice coefficient: A similar metric to IoU (Intersection over Union), Hausdorff distance (\cite{sirinukunwattana2017gland}): the distance between two polygons which is calculated per object, Detection Quality (DQ): is equivalent to ${F\textsubscript{1}}-Score$ divided by 2, SQ: is summing up IoUs for all true positive values over number of true positives and PQ: DQ$\times$SQ (\cite{kirillov2019panoptic}). For AJI, Dice, the true and false values are based on the pixel value but for DQ true and false values are based on the value of IoU. The prediction is considered true positive if IoU is higher 0.5.\\ \begin{table} \centering \caption{Comparison of the proposed network architecture with other approaches: MonuSeg dataset have been used for these experiments.} \label{tArch} \begin{tabular}{lllll} \hline\hline & AJI & Dice & PQ & Haus. \\ \hline Unet & 0.762 & 0.821 & 0.774 & 8.73 \\ FCN & 0.741 & 0.798 & 0.756 & 9.5 \\ Segnet & 0.785 & 0.846 & 0.794 & 8.33 \\ NuClick W/O MS block & 0.798 & 0.860 & 0.808 & 6.11 \\ NuClick + 1 MS block & 0.817 & 0.889 & 0.820 & 5.51 \\ NuClick + 2 MS blocks & 0.830 & 0.905 & 0.829 & 4.93 \\ NuClick + 3 MS blocks & 0.834 & 0.912 & \textbf{0.838} & \textbf{4.05} \\ NuClick + 4 MS blocks & \textbf{0.835} & \textbf{0.914} & 0.838 & 4.05 \\ \hline\hline \end{tabular} \end{table} For gland segmentation, we use F1-score, Dice\textsubscript{Obj}, and Hausdorff distance (\cite{sirinukunwattana2017gland}). The True positives in F1-score are based on the thresholded IoU. Dice\textsubscript{Obj} is average of dice values over all objects and Hausdorff distance here is the same as the one used for nuclei. \subsection{Network Selection} In this section, we investigate the effect of multi-scale blocks on NuClick network and compare its performance with other popular architectures. Ablating various choices of components in NuClick network architecture have been shown in \cref{tArch}. We tested our architecture with up to 4 multi-scale (MS) blocks and we observed that adding more that 3 MS blocks does not contribute significantly to the performance. It can be observed that our architecture outperforms three other popular methods (UNet by \cite{ronneberger2015u}, SegNet by \cite{badrinarayanan2017segnet}, and FCN by \cite{long2015fully}). When we use no MS block, our model is still better than all baseline models which shows the positive effect of using residual blocks. We opt to use 3 MS blocks in the final NuClick architecture because it is suggesting a competitive performance while having smaller network size. \subsection{Validation Experiments} Performance of NuClick framework for interactive segmentation of nuclei, cells, and glands are reported in \cref{tValNuc,tValCell,tValGland}, respectively. For nuclei and cells, centroid of the GT masks were used to create inclusion and exclusion maps, whereas for gland segmentation, morphological skeleton of the GT masks were utilized. For comparison purposes, performance of other supervised and unsupervised interactive segmentation methods are included as well. In \cref{tValNuc,tValCell}, reported methods are Region Growing (\cite{adams1994seeded}): iteratively determines if the neighbouring pixels of an initial seed point should belong to the initial region or not (in this experiment, the seed point is GT mask centroid and the process for each nuclei/cell is repeated 30 iterations), Active Contour (\cite{chan2001active}): which iteratively evolves the level set of an initial region based on internal and external forces (the initial contour in this experiment is a circle with radius 3 pixels positioned at the GT mask centroid), marker controlled watershed (\cite{parvati2008image}) that is based on watershed algorithm in which number and segmentation output depends on initial seed points (in this experiment, unlike \cite{parvati2008image} that generates seed points automatically, we used GT mask centroids as seed points), interactive Fully Convolutional Network--iFCN (\cite{xu2016deep}): a supervised DL based method that transfers user clicks into distance maps that are concatenated to RGB channels to be fed into a fully convolutional neural network (FCN), and Latent Diversity--LD (\cite{li2018interactive}): which uses two CNNs to generate final segmentation. The first model takes the image and distance transform of two dots (inside and outside of object) to generate several diverse initial segmentation maps and the second model selects the best segmentation among them. \begin{table} \centering \caption{Performance of different interactive segmentation methods for nuclear segmentation on validation set of MonuSeg dataset} \label{tValNuc} \begin{tabular}{lccccl} \hline\hline Method & AJI & Dice & SQ & PQ & Haus. \\ \hline Watershed & 0.189 & 0.402 & 0.694 & 0.280 & 125 \\ Region Growing & 0.162 & 0.373 & 0.659 & 0.241 & 95 \\ Active Contour & 0.284 & 0.581 & 0.742 & 0.394 & 67 \\ iFCN & 0.806 & 0.878 & 0.798 & 0.782 & 7.6 \\ LD & 0.821 & 0.898 & 0.815 & 0.807 & 5.8 \\ NuClick & \textbf{0.834 } & \textbf{0.912} & \textbf{0.839} & \textbf{0.838} & \textbf{4.05} \\ \hline\hline \end{tabular} \end{table} \begin{table} \centering \caption{Performance of different interactive segmentation methods for cell segmentation on test set of WBC dataset} \label{tValCell} \begin{tabular}{lccccl} \hline\hline & AJI & Dice & SQ & PQ & Haus. \\ \hline Watershed & 0.153 & 0.351 & 0.431 & 0.148 & 86 \\ Region Growing & 0.145 & 0.322 & 0.414 & 0.129 & 71 \\ Active Contour & 0.219 & 0.491 & 0.522 & 0.198 & 50 \\ iFCN & 0.938 & 0.971 & 0.944 & 0.944 & 9.51 \\ LD & 0.943 & 0.978 & 0.949 & 0.949 & 8.33 \\ NuClick & \textbf{0.954} & \textbf{0.983} & \textbf{0.958} & \textbf{0.958} & \textbf{7.45} \\ \hline\hline \end{tabular} \end{table} \begin{table} \centering \setlength{\tabcolsep}{2.5pt} \caption{Performance of different interactive segmentation methods for gland segmentation on test sets of GLaS dataset} \label{tValGland} \begin{tabular}{lccc|ccc} \hline\hline & \multicolumn{3}{c|}{TestA} & \multicolumn{3}{c}{TestB} \\ \hline & F1 & Dice\textsubscript{Obj} & Haus. & F1 & Dice\textsubscript{Obj} & Haus. \\ \hline Grabcut & 0.462 & 0.431 & 290 & 0.447 & 0.412 & 312 \\ Deep Gabcut & 0.886 & 0.827 & 51 & 0.853 & 0.810 & 57 \\ DEXTRE & 0.911 & 0.841 & 43 & 0.904 & 0.829 & 49 \\ Mask-RCNN & \multicolumn{1}{l}{0.944} & 0.875 & 35 & \multicolumn{1}{l}{0.919} & 0.856 & 41 \\ BIFseg & \multicolumn{1}{l}{0.958} & 0.889 & 28 & \multicolumn{1}{l}{0.921} & 0.864 & 38 \\ NuClick & \textbf{1.000} & \textbf{0.956} & \textbf{15} & \textbf{1.000} & \textbf{0.951} & \textbf{21} \\ \hline\hline \end{tabular} \end{table} In \cref{tValGland}, reported methods are Grabcut by \cite{rother2004grabcut}: which updates appearance model within the bounding box provided by the user, Deep GrabCut by \cite{xu2017deep}: which converts the bounding box provided by the user into a distance map that is concatenated to RGB image as the input of a deep learning model, DEXTRE (\cite{maninis2018deep}): a supervised deep learning based method which is mentioned in the \cref{Sec-inter} and accepts four extreme points of glands as input (extreme points are extracted based on each object GT mask), and a Mask-RCNN based approach proposed by \cite{agustsson2019interactive}: where the bounding box is also used as the input to the Mask-RCNN. \cite{agustsson2019interactive} also added a instance-aware loss measured at the pixel level to the Mask-RCNN loss. We also compared our method for gland segmentation with BIFseg (\cite{wang2018interactive}) that needs user to crop the object of interest by drawing bounding box around it. The cropped region is then resized and fed into a resolution-preserving CNN to predict the output segmentation. \cite{wang2018interactive} also used a refinement step which is not included in our implementation. For GrabCut, Deep GrabCut, BIFseg, and Mask-RCNN approaches the bounding box for each object is selected based on its GT mask. For iFCN and LD methods, positive point (point inside the object) is selected according to the centroid of each nucleus and negative click is a random point outside the desired object. \begin{figure*}[h!] \centering \includegraphics[width =0.95\textwidth]{generalizability.pdf} \caption{\textbf{Generalizability of NuClick:} The first row shows results of NuClick on CPM dataset for nuclei segmentation (where the network was trained on MoNuSeg dataset). The second row illustrates two samples of gland segmentation task from CRAG dataset where the model was trained on GLaS dataset. Solid stroke line around each object outlines the ground truth boundary for that object, overlaid transparent mask is the predicted segmentation region by NuClick, and points or squiggles indicate the provided guiding signal for interactive segmentation. (Best viewed in color)} \label{fig:generalize} \end{figure*} Based on \cref{tValNuc}, NuClick achieved AJI score of 0.834, Dice value of 0.912, and PQ value of 0.838 which outperformed all other methods for nuclear segmentation on MonuSeg dataset. Performance gap between NuClick and other unsupervised methods is very high (for example in comparison with Watershed method, NuClick achieves a 0.645 higher AJI). Extreme low evaluation values achieved by unsupervised metrics indicate that they are not suitable for intricate task of nuclear segmentation, even if they are fed with GT markers. There is also iFCN (\cite{xu2016deep}), a deep learning based method in \cref{tValNuc} that is trained based on the clicked dots inside and outside of objects. However, NuClick performs better than iFCN for all AJI, Dice, and PQ metrics by margin of 2.8\%, 3.4\%, and 5.6\%, respectively, which is a considerable boost. For the other CNN based method in \cref{tValNuc}, LD method, NuClick advantage over all metrics is also evident. The same performance trend can be seen for both cell and gland segmentation tasks in \cref{tValCell,tValGland}. For the cell segmentation task, NuClick was able to segment touching WBCs from synthesized dense blood smear images quite perfectly. Our proposed method achieves AJI, Dice, and PQ values of 0.954, 0.983, and 0.958, respectively, which indicates remarkable performance of the NuClick in cell segmentation. Validation results of our algorithm on two test sets from GlaS dataset (testA and testB) are reported in \cref{tValGland} alongside the results of 4 supervised deep learning based algorithms and an unsupervised method (Grabcut). Markers used for Grabcut are the same as ones that we used for NuClick. Based on \cref{tValGland} our proposed method is able to outperform all other methods for gland segmentation in both testA and testB datasets by a large margine. For testB, NuClick achieves F1-score of 1.0, Dice similarity coefficient of 0.951, and Hausdorff distance of 21, which compared to the best performing supervised method (BIFseg) shows 7.9\%, 8.7\%, and 17 pixels improvement, respectively. The F1-score value of 1.0 achieved for NuClick framework in gland segmentation experiment expresses that all of desired objects in all images are segmented well enough. As expected, unsupervised methods, like Grabcut, perform much worse in comparison to supervised method for gland segmentation. Quantitatively, our proposed framework shows 55.3\% and 53.9\% improvement compared to Grabcut in terms of F1-score and Dice similarity coefficients. The reason for the advantage of NuClick over other methods mainly lies in its squiggle-based guiding signal which is able to efficiently mark the extent of big, complex, and hollow objects. It is further discussed in \cref{Sec:discussion}. Methods like DEXTRE, BIFseg, and Mask-RCNN are not evaluated for interactive nucleus/cell segmentation, because they may be cumbersome to apply in this case. These methods need four click points on the boundaries of nucleus/cell (or drawing a bounding box for each of them) which is still labour-intensive as there may be a large number of nuclei/cells within an image. Segmentation quality for three samples are depicted in \cref{fig:validation}. In this figure, the first, second, and third rows belong to a sample drawn from MoNuSeg, WBC, and GLaS validation sets. The left column of \cref{fig:validation} shows original images and images on the right column contains GT boundaries, segmentation mask, and guiding signals (markers) overlaid on them. Guiding signals for nuclei and cell segmentation are simple clicks inside each object (indicated by diamond-shape points on the images) while for glands (the third row) guiding signals are squiggles. In all exemplars, extent of the prediction masks (indicated by overlaid transparent colored region) are very close to the GT boundaries (indicated by solid strokes around each object). \section{Discussions} \label{Sec:discussion} In order to gain better insights into the performance and capabilities of the NuClick, we designed several evaluation experiments. In this section we will discuss different evaluation experiments for NuClick. First we will assess the generalizability of the proposed framework, then we will discuss how it can adapt to new domains without further training, after that the reliability of NuClick output segmentation is studied. Moreover, sensitivity of output segmentation to variations in the guiding signals is also addressed in the following subsections. \begin{figure*}[ht!] \centering \includegraphics[width =0.95\textwidth]{adaptability.pdf} \caption{\textbf{Domain adaptability of NuClick:} nuclei from unseen domains (Pap Smear sample in the first row and IHC stained sample in the second tow) are successfully segmented using the NuClick which was trained on MoNuSeg dataset. In all images, solid stroke line around each object outlines the ground truth boundary for that object (except for IHC samples, for which ground truth masks are unavailable), overlaid transparent mask is the predicted segmentation region by NuClick, and points indicate the provided guiding signal for interactive segmentation. (best viewed in color)} \label{fig:adapt} \end{figure*} \subsection{Generalization study} To show the generalizability of the NuClick across an unseen datasets, we designed an experiment in which NuClick is trained on the training set of a specific dataset and then evaluated on the validation set of another dataset but within the same domain. Availability of different labeled nuclei and gland datasets allow us to better show the generalizability of our proposed framework across different dataset and different tasks. To assess the generalizability upon nuclei segmentation, two experiments were done. In one experiment, NuClick was trained on training set of MoNuSeg dataset and then evaluated on the validation set of CPM dataset. In another experiment this process was done contrariwise where CPM training set was used for training the NuClick and MoNuSeg testing set was used for the evaluation. Evaluation results of this study are reported in the first two rows of \cref{tGeneralize}. From this table we can conclude that NuClick can generalize well across datasets because it gains high values for evaluation metrics when predicting images from dataset that was not included in its training. For example, when NuClick is trained on the MoNuSeg training set, Dice and SQ evaluation metrics resulted for CPM validation set are 0.908 and 0.821, respectively, which are very close to the values reported for evaluating the MoNuSeg validation set using the same model i.e., Dice of 0.912 and SQ of 0.839 in \cref{tValNuc}. This closeness for two different datasets using the same model supports our claim about generalizability of the NuClick. Similarly, to test the generlizability of the NuClick when working on gland segmentation task, it has been trained on one gland dataset and tested on validation images from another gland dataset. As GlaS test set is divided into TestA and TestB, when NuClick is trained on CRAG, it has been test on testA and testB of GlaS (named as GlaSA and GlaSB in \cref{tGeneralize}). High values of Dice\textsubscript{Obj} metric and low values for Hasdroff distances also supports the generalizability of NuClick framework for gland segmentation task as well. To provide visual evidence for this claim, we illustrated two nuclear segmentation samples from CPM validation set (resulted using a model trained on MoNuSeg dataset) and two gland segmentation samples from CRAG validation set (resulted using a model trained on GLaS dataset) in \cref{fig:generalize}. In all cases NuClick was able to successfully segment the desired objects with high accuracy. In all images of \cref{fig:generalize} different overlaid colors corresponds to different object instances, solid stroke lines indicate GT boundaries, transparent color masks show the predicted segmentation region, and other point or squiggle markers representing guiding signals for interactive segmentation. \begin{table} \centering \setlength{\tabcolsep}{2pt} \caption{Results of generalization study across different datasets for interactive nuclei and gland segmentation} \begin{tabular}{lllcc|cc} \hline\hline & Train & Test & Dice & SQ & Dice\textsubscript{Obj} & Haus. \\ \hline \multirow{2}{*}{Nuclei} & MoNuSeg & CPM & 0.908 & 0.821 & - & - \\ & CPM & MoNuSeg & 0.892 & 0.811 & - & - \\ \hdashline \multirow{2}{*}{Gland} & GLaS & CRAG & \multicolumn{1}{l}{-} & \multicolumn{1}{l|}{-} & \multicolumn{1}{l}{0.932} & \multicolumn{1}{l}{31} \\ & CRAG & GLaSA & \multicolumn{1}{l}{-} & \multicolumn{1}{l|}{-} & \multicolumn{1}{l}{0.944} & \multicolumn{1}{l}{28} \\ & CRAG & GLaSB & \multicolumn{1}{l}{-} & \multicolumn{1}{l|}{-} & \multicolumn{1}{l}{0.938} & \multicolumn{1}{l}{30} \\ \hline\hline \end{tabular} \label{tGeneralize} \end{table} \subsection{Domain adaptation study} To assess the performance of the NuClick on unseen samples from different data domains, we trained it on MoNuSeg dataset which contains labeled nuclei from histopathological images and then used the trained model to segment nuclei in cytology and immunohistochemistry (IHC) samples. In the cytology case, a dataset of 42 FoVs were captured from 10 different Pap Smear samples using CELLNAMA LSO5 slide scanner and 20x objective lens. These samples contain overlapping cervical cells, inflammatory cells, mucus, blood cells and debris. Our desired objects from these images are nuclei of cervical cells. All nuclei from cervical cells in the available dataset of Pap Smear images were manually segmented with the help of a cytotechnologist. Having the GT segmentation for nuclei, we can use their centroid to apply the NuClick on them (perform pseudo-interactive segmentation) and also evaluate the results quantitatively, as reported in \cref{tAdapt}. High values of evaluation metrics reported in \cref{tAdapt} shows how well NuClick can perform on images from a new unseen domain like Pap Smear samples. Some visual examples are also provided in fig. \ref{fig:adapt} to support this claim. As illustrated in the first row of fig. \ref{fig:adapt}, NuClick was able to segment touching nuclei (in very dense cervical cell groups) from Pap Smear samples with high precision. It is able to handle nuclei with different sizes and various background appearances. \begin{table} \centering \caption{Performance NuClick framework on segmenting nuclei in images from an unseen domain (Pap Smear)} \begin{tabular}{lccccc} \hline\hline Method & AJI & Dice & SQ & DQ & PQ \\ \hline NuClick & 0.934 & 0.965 & 0.933 & 0.997 & 0.931 \\ \hline\hline \end{tabular} \label{tAdapt} \end{table} For the IHC images, we utilized NuClick to delineate lymphocytes. The dataset we have used for this section is a set of 441 patches with size of $256\times256$ extracted from LYON19 dataset. LYON19 is scientific challenge on lymphocyte detection from images of IHC samples. In this dataset samples are taken from breast, colon or prostate organs and are then stained with an antibody against CD3 or CD8 \cite{lyon19} (membrane of lymphocyte would appear brownish in the resulting staining). However, for LYON19 challenge organizers did not release any instance segmentation/detection GTs alongside the image ROIs. Therefore, we can not assess the performance of NuClick segmentation on this dataset quantitatively. However, the quality of segmentation is very desirable based on the depicted results for two random cases in the second row of \cref{fig:adapt}. Example augmentations in \cref{fig:adapt} are achieved by clicks of a non-expert user inside lymphocytes (based on his imperfect assumptions). As it is shown in \cref{fig:adapt}, NuClick is able to adequately segment touching nuclei even in extremely cluttered areas of images from an unseen domain. These resulting instance masks were actually used to train an automatic nuclei instance segmentation network, SpaNet \cite{koohbanani2019nuclear}, which helped us achieve the first rank in LYON19 challenge. In other words, we approached the problem lymphocyte detection as an instance segmentation problem by taking advantage of our own generated nuclei instance segmentation masks \cite{jahanifar2019nuclick}. It also approves the reliability of the NuClick generated prediction masks, which is discussed in more details in the following subsection. \subsection{Segmentation Reliability Study} The important part of an interactive method for collecting segmentation is to see how the generated segmentation maps are reliable. To check the reliability of generated masks, we use them for training segmentation models. Then we can compare the performance of models trained on generated mask with the performance of models trained on the GTs. This experiment has been done for nuclear segmentation task, where we trained three well-known segmentation networks (U-Net \cite{ronneberger2015u}, SegNet \cite{badrinarayanan2017segnet}, and FCN8 \cite{long2015fully}) with GT and NuClick generated masks separately and evaluated the trained models on the validation set. Results of these experiments are reported in \cref{tRelaiable}. Note that when we are evaluating the segmentation on MoNuSeg dataset, the NuClick model that generated the masks is trained on the CPM dataset. Therefore, in that case NuClick framework did not see any of MoNuSeg images during its training. As shown in \cref{tRelaiable} there is a negligible difference between the metrics achieved by models trained on GT masks and the ones that trained on NuClick generated masks. Even for one instance, when testing on MoNuSeg dataset, Dice and SQ values resulted from FCN8 model trained on annotations of NuClick\textsubscript{CPM} are 0.01 and 0.006 (insignificantly) higher than the model trained on GT annotations, respectively. This might be due to more uniformity of the NuClick generated annotations, which eliminate the negative effect of inter annotator variations present in GT annotations. Therefore, the dense annotations generated by NuClick are reliable enough for using in practice. If we consider the cost of manual annotation, it is more efficient to use annotations obtained from NuClick to train models. \begin{table} \centering \setlength{\tabcolsep}{1pt} \caption{Results of segmentation reliability experiments} \begin{tabular}{lcc|cc|cc|cc} \hline\hline \multirow{3}{*}{} & \multicolumn{4}{c|}{Result on MoNuSeg test set} & \multicolumn{4}{c}{Result on CPM test set} \\ \cline{2-9} & \multicolumn{2}{c|}{GT} & \multicolumn{2}{c|}{NuClick\textsubscript{CPM}} & \multicolumn{2}{c|}{GT} & \multicolumn{2}{c}{NuClick\textsubscript{MoNuSeg}} \\ \cline{2-9} & Dice & SQ & Dice & SQ & Dice & SQ & Dice & SQ \\ \hline Unet & 0.825 & 0.510 & 0.824 & 0.503 & 0.862 & 0.596 & 0.854 & 0.584 \\ SegNet & 0.849 & 0.531 & 0.842 & 0.527 & 0.889 & 0.644 & 0.881 & 0.632 \\ FCN8 & 0.808 & 0.453 & 0.818 & 0.459 & 0.848 & 0.609 & 0.836 & 0.603 \\ \hline\hline \end{tabular} \label{tRelaiable} \end{table} \begin{figure*}[h!] \centering \includegraphics[width =\textwidth]{sensitivityAnalysis2.pdf} \caption{Example results of NuClick, highlighting the variations in the user input. First and second rows show the prediction of Nuclick at different positions of clicks inside objects. The third and fourth rows demonstrates the predictions of nuclick in presense of variouse shape of squiggle. Solid stroke line around each object outlines the ground truth boundary for that object, overlaid transparent mask is the predicted segmentation region by NuClick, and points or squiggles indicate the provided guiding signal for interactive segmentation. (Best viewed in color, zoom in to clearly see boundaries)} \label{fig:sens} \end{figure*} \begin{figure*} [ht!] \includegraphics[width =\textwidth]{extremeCases.pdf} Extreme cases for nuclei and glands: clumped nuclei in H\&E and IHC images (a-d) and irregular glands/tumor regions in cancerous colon and prostate images (e-h) are shown. In all images, solid stroke line around each object outlines the ground truth boundary for that object (except for d and e where the ground truth masks are unavailable), overlaid transparent mask is the predicted segmentation region by NuClick, and points or squiggles indicate the provided guiding signal for interactive segmentation. (Best viewed in color, zoom in to clearly see boundaries) \label{fig:extreme} \end{figure*} \begin{table} \centering \caption{Effect of disturbing click positions by amount of $\sigma$ on NuClick outputs for nuclei and cells segmentation} \label{tValsigma} \begin{tabular}{lccc|ccc} \hline\hline & \multicolumn{3}{c|}{Nuclei} & \multicolumn{3}{c}{Cells (WBCs)} \\ \hline $\sigma$ & AJI & Dice & PQ. & AJI & Dice & PQ. \\ \hline 1 & 0.834 & 0.912 & 0.838 & 0.954 & 0.983 & 0.958 \\ 3 & 0.834 & 0.911 & 0.837 & 0.954 & 0.983 & 0.958 \\ 5 & 0.832 & 0.911 & 0.835 & 0.953 & 0.983 & 0.957 \\ 10 & 0.821 & 0.903 & 0.822 & 0.953 & 0.982 & 0.957 \\ 20 & - & - & - & 0.950 & 0.979 & 0.955 \\ 50 & - & - & - & 0.935 & 0.961 & 0.943 \\ \hline\hline \end{tabular} \label{tSensitivity} \end{table} \subsection{Sensitivity to Guiding Signals} Performance of an interactive segmentation algorithm highly depends on quality of the user input markers. In other words, an ideal interactive segmentation tool must be robust against errors in the input annotations as much as possible. For instance, in nucleus or cell segmentation, an ideal segmentation tools should perform well to delineate boundaries of nuclei as long as user clicks fall inside the nuclei region i.e., the clicked point does not need to be located exactly at the center of the desired nuclei. \begin{table} \centering \caption{Effect of disturbing click positions by amount of $\sigma$ on NuClick outputs for nuclei and cells segmentation} \label{tValsigma} \begin{tabular}{lccc|ccc} \hline\hline & \multicolumn{3}{c|}{Nuclei} & \multicolumn{3}{c}{Cells (WBCs)} \\ \hline $\sigma$ & AJI & Dice & PQ. & AJI & Dice & PQ. \\ \hline 1 & 0.834 & 0.912 & 0.838 & 0.954 & 0.983 & 0.958 \\ 3 & 0.834 & 0.911 & 0.837 & 0.954 & 0.983 & 0.958 \\ 5 & 0.832 & 0.911 & 0.835 & 0.953 & 0.983 & 0.957 \\ 10 & 0.821 & 0.903 & 0.822 & 0.953 & 0.982 & 0.957 \\ 20 & - & - & - & 0.950 & 0.979 & 0.955 \\ 50 & - & - & - & 0.935 & 0.961 & 0.943 \\ \hline\hline \end{tabular} \label{tSensitivity} \end{table} To assess the sensitivity of NuClick to the variations in the guiding signal, we design an experiment for nuclei and cell segmentation applications in which location of the guiding point in the inclusion map is perturbed by adding value of ${\sigma}$ to the location of centroids. We repeat this experiment for different values of $\sigma$ for both nuclei and cell segmentation applications and report the results in \cref{tSensitivity}. For nuclear segmentation, jittering the location up to 10 pixels is investigated. It has been shown that disturbing the click position from the centroid up to 5 pixels does not considerably degrade the segmentation results. However, when the jittering amount is equal to $\sigma=10$, all evaluation metrics drop by 1\% or more. This reduction in metrics does not necessarily imply that NuClick is sensitive to click positions, because this fall in performance may be due to the fact that radius of some nuclei is less than 10 pixels and jittering the click position by 10 pixels cause it to fall outside the nuclei region therefore confusing the NuClick in correctly segmenting the desired small nucleus. However, even reduced metrics are still reliable in comparison with the resulted metrics from other methods as reported in \cref{tValNuc}. The same trend can be seen for cell segmentaiton task in \cref{tSensitivity}. However, for cells in our dataset we were able to increase the jittering range (up to 50 pixels) because in the WBC dataset, white blood cells have a diameter of at least 80 pixels. As one can see, the segmentation results are very robust against the applied distortion to the click position. Changing the click location by 50 pixels makes considerable drop in performance which can be due to the same reason as we discussed the nuclei case i.e., amount of jittering is bigger than the average radius of some small cells. Unfortunately, we can not quantitatively analyze the sensitivity of the NuClick to the squiggle changes, because its related changes are not easily measurable/paramtereizable. However, for two examples of histology images we tried to show the effect of changing the guiding squiggles on the resulting segmentation in \cref{fig:sens}. In this figure, the effect of changing the click position for two examples of nuclei segmentation and two examples cell segmentation are also visualized. It is obvious from exemplars in \cref{fig:sens} that NuClick successfully works with different shapes of squiggles as the guiding signal. Squiggles can be short in the middle or adjacent regions of the desired gland, or they can be long enough to cover the main diameter of the gland. They can be continuous curves covering all section and indentation of the gland geometry, or separated discrete lines that indicate different sections of a big gland. They can even have arbitrary numerical or letters shape like the example in the last row of \cref{fig:sens}. In all cases, it is obvious that NuClick is quite robust against variations in the guiding signals which is due to the techniques that we have incorporated during training of the NuClick (randomizing the inclusion map). It is worth mentioning that we have conducted experiments with training NuClick for gland segmentation using extreme points and polygons as guiding signals. Even with a considerable number of points on gland boundary or polygons with large number of vertices (filled or hollow), the network failed to converge during the training phase. However, we observed that even simple or small squiggles are able to provide enough guiding information for the model to converge fast. We have also conducted another experiment to assess the sensitivity of NuClick on the exclusion maps. In other words, we want to see if eliminating the exclusion map has any effect on NuClick segmentation performance. To this end, we evaluate the performance of NuClick for nuclei segmentation on MoNuSeg dataset in the absence of exclusion map. Therefore in this situation the input to the network would have 4 channels (RGB plus inclusion map). The network is trained from scratch on the MoNuSeg training set with the new considerations and then evaluated on the MoNuSeg validation set. Results of this experiment are reported in \cref{tExclud}. Based on \cref{tExclud}, performance of the NuClick significantly drops when exclusion map is missing. That is because there are a lot of overlapping nuclei in this dataset and without having the exclusion map, the network has no clue of the neighboring nuclei when dealing with a nucleus that belongs to a nuclei clump. \subsection{Extreme Cases} To investigate the effectiveness of NuClick when dealing with extreme cases, output of NuClick for images with challenging objects (high grade cancer in different tissue types) are shown in \cref{fig:extreme}. For example in \cref{fig:extreme}a-c touching nuclei with unclear edges from patches of cancerous samples have been successfully segmented by NuClick. Additionally, \cref{fig:extreme}d shows promising segmentation of densely clustered blood cells in a blurred IHC image from another domain (extracted from LYON19 dataset (\cite{lyon19})). In \cref{fig:extreme}e-f, images of glands with irregular shapes and their overlaid predictions are shown. As long as the squiggle covers the extend of gland, we can achieve a good segmentation. A noteworthy property of NuClick framework is its capability to segment objects with holes in them. In \cref{fig:extreme}e-f, although margins of glands are very unclear and some glands have holes in their shape, NuClick can successfully recognizing boundaries of each gland. Further, if the squiggle encompass the hole, it will be excluded from final segmentation whereas if the squiggle covers part of holes in the middle of glands, they will be included in the segmentation. For instance, in \cref{fig:extreme}g, a complex and relatively large gland is well delineated by the NuClick. Note that this gland contains a hole region which belongs to the gland and it is correctly segmented as part of the gland because the guiding signal covers that part. This is a powerful and very useful property that methods based on extreme points or bounding box like \cite{maninis2018deep} and \cite{wang2018interactive} do not offer. We also show a cancerous prostate image (extracted from PANDA dataset (\cite{bulten2020automated})) in \cref{fig:extreme}h where the tumor regions are outlined by NuClick. Overall, these predictions shows the capability of NuClick in providing reasonable annotation in scenarios that are even challenging for humans to annotate. Note that for images in \cref{fig:extreme}d,h the ground truth segmentation masks are not available, therefore they are not shown. \begin{table} \centering \setlength{\tabcolsep}{2.5pt} \caption{Performance of NuClick on the MonuSeg dataset with and without exclusion map} \begin{tabular}{llllll} & AJI & Dice & SQ & DQ & PQ \\ \hline\hline NuClick with ex. map & 0.834 & 0.912 & 0.839 & 0.999 & 0.838 \\ NuClick without ex. map & 0.815 & 0.894 & 0.801 & 0.972 & 0.778 \end{tabular} \label{tExclud} \end{table} \subsection{User Correction} In some cases, the output of models might not be correct, therefore there should be a possibility that user can modify wrong predictions. This is a matter of implementation of the interface in most cases, Hence, when the output is not as good as expected, the user can modify the supervisory signal by extending squiggles, changing the shape of squiggles or move the position of clicks. After the modification has been applied, the new modified supervisory signal is fed to the network to obtain new segmentation. \section{Conclusions} In this paper, we have presented NuClick, a CNN-based framework for interactive segmentation of objects in histology images. We proposed a simple and robust way to provide input from the user which minimizes human effort for obtaining dense annotations of nuclei, cell and glands in histology. We showed that our method is generizable enough to be used across different datasets and it can be used even for annotating objects from completely different data distributions. Applicability of NuClick has been shown across 6 datasets, where NuClick obtained state-of-the art performance in all scenarios. NuClick can also be used for segmenting other objects like nerves and vessels which are less complex and less heterogeneous compared to glands. We believe that NuClick can be used as a useful plug-in for whole slide annotation programs like ASAP (\cite{litjens2017asap}) or Qupath (\cite{bankhead2017qupath}) to ease the labeling process of the large-scale datasets. \bibliographystyle{unsrt \section{Introduction} \IEEEPARstart{T}{his} demo file is intended to serve as a ``starter file'' for IEEE journal papers produced under \LaTeX\ using IEEEtran.cls version 1.8 and later. I wish you the best of success. \hfill mds \hfill December 27, 2012 \subsection{Subsection Heading Here} Subsection text here. \subsubsection{Subsubsection Heading Here} Subsubsection text here. \section{Conclusion} The conclusion goes here. \appendices \section{Proof of the First Zonklar Equation} Appendix one text goes here. \section{} Appendix two text goes here. \section*{Acknowledgment} The authors would like to thank... \ifCLASSOPTIONcaptionsoff \newpage \fi
{'timestamp': '2020-07-08T02:21:28', 'yymm': '2005', 'arxiv_id': '2005.14511', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14511'}
arxiv
\section{Introduction} Graph ($G(V,E)$, in which $V$ is vertex set for describing dataset and $E$ is edge set for representing the relationship set between data) can capture the relationship of data distribution based on metric method (For example, Euclidean distance,Cosine distance or Kullback-Leibler divergence etc). As a metric representation, graph plays a vital role in pattern recognition. Especially, the recent graph convolutional networks (GCN) have the promising results for many application, for example, human activities \cite{manessi2020dynamic} \cite{zhao2019semantic} \cite{zeng2019graph},facial action unit detection \cite{liu2020relation}, text classification \cite{yao2019graph},and node classification \cite{kipf2016semi} \cite{hu2019hierarchical} \cite{lee2018higher} \cite{qin2018spectral}\cite{lin2019structure}. However, the graph structure is fixed in GCN methods, and it limits GCN for the application of the graph structure loss. Furthermore, the fixed graph structure usually is measured by one metric method, which can not better fit to the distribution of data. Therefore, Graph learning (GL) based on GCN \cite{jiang2019semi} \cite{jiang2019glmnet} \cite{jiang2019unified} \cite{chen2019deep} \cite{hu2019feature} is presented for dynamically mining graph structure of data. Graph learning faces to a key question, which is the structure relationship learning of data distribution. Existing methods fucus on how to update the graph structure with the metric constraint to optimize the object function \cite{du2020low}\cite{Lin2017Dynamic} or neural networks \cite{jiang2019semi} \cite{jiang2019glmnet} \cite{jiang2019unified} \cite{chen2019deep} \cite{hu2019feature}. The metric constraint usually is defined by two ways. One way is similarity metric learning, which is a global graph structure learning from all data samples. This method often focuses on the difference representation in the inter-class. Another way specifies different weights to different data in it's neighborhood (for example graph attention networks (GAT) \cite{velivckovic2017graph}) for capturing the local graph structure, which tends to the difference description in the intra-class. The global and local graph complement each other for classification. However, existing methods ignores the joint effect of these graphs and the relationship between the global and local graph based on GL for semi-supervised classification. Therefore, DGL is proposed for jointly considering these graphs structure for semi-supervised classification. Our main contributions include two points. One is to construct deep graph learning networks for dynamically capturing the global graph by similarity metric learning and local graph by attention learning. Compared with existing methods, the difference of this point focus on the joint consideration the different graphs to further find the distribution structure of the different data. Another is to fuse the global and local graph by the hierarchical progressive learning for semi-supervised classification.In contrast to existing methods, the difference of this point is the dynamic mining the relationship of these graphs to better balance the tendentious contradiction of the different graphs between inter-class and intra-class. the Figure \ref{fig-1} shows the difference between the global and local graph, and the modules of DGL. \begin{figure*}[ht] \begin{center} \includegraphics[width=1\linewidth]{1.png} \end{center} \vspace{-0.2in} \caption{The illustration of deep graph learning for mining the global and local graph.} \label{fig-1} \end{figure*} \section{Related Works} \label{rws} Graph learning try to automatically construct graph structure from data. Compared with fixed similarity metrics, the difference of GL can dynamically assign the neighbor of each data point, and automatically compute the weight between data points. Therefore, GL can obtain the better accuracy than the fixed graph description by similarity metrics \cite{kang2019robust}. According to the different learning framework, the recent GL methods can be divided into two categories, which are non-neural networks and neural networks. One is the methods based on non-neural networks, which attempt to build the optimization function based on the graph generation hypothesis. For example, in terms of completeness hypothesis, self-expressiveness \cite{huang2019auto} \cite{liu2013robust} \cite{kang2018self} regards linear coefficient matrix between data as the graph matrix for the impressive performance in clustering and semi-supervised learning; in accordance with Laplacian graph spectrum, graph learning based on spectral constraints \cite{kumar2019unified} complements the relationship of data by incorporating prior structural knowledge;on the basis of sparse sampling theory, sparse graph learning \cite{hu2019multi} \cite{chen2019adaptive}\cite{pei2019graph} captures few graph connections by adjusting sparsity parameter for improving the classification performance. The superiority of these methods focuses on the relevance between graph generation and constrains, and parameterizes graph generation processing for dynamically controlling graph learning. Because model construction usually be fixed by the specific function, graph structure information from raw data is difficultly mined by iterative boosts. Another is the approaches based on neural networks, which often simulate the interaction relationship between graph edges and nodes for propagating graph structure information by GCN \cite{jiang2019semi}. In these different networks, these are two types of methods for dynamically computing graph structure. The first type of method is the aggregation of nodes and edges information for updating the weight between nodes layer by layer. For example, hierarchical graph convolutional network(H-GCN) \cite{hu2019hierarchical} repeatedly aggregates similar nodes to hypernodes, and combines one- or two-hop neighborhood information to enlarge the receptive field of each node for encoding graph structure information; edge-labeling graph neural network (EGNN) \cite{kim2019edge} \cite{gong2018exploiting} updates the weight of graph by iteratively aggregating the node representation and the edgelabels with direct exploitation of both intra-cluster similarity and the inter-cluster dissimilarity. The second type of method is the similarity metric of pairwise nodes in some layer. For instance, graph learning-convolutional network(GLCN)\cite{jiang2019semi} optimizes graph structure by learning the transformation relationship of feature difference; dimension-wise separable graph convolution (DSGC) \cite{li2019attributed} uses the relationship among node attributes to complement node relations for representation learning by the covariance metric; graph learning neural networks (GLNNs) \cite{gao2019exploring} iteratively explores the optimization of graphs from both data and tasks by graph Laplacian regularizer; deep iterative and adaptive learning for graph neural networks (DIAL-GNN) \cite{chen2019deep} deals with the graph structure learning problem as a dynamical cosine similarity metric learning problem. These methods mostly consider the global structure from all data sample in the second type of method or the local structure from neighbor data in the first type of method. However, the hierarchical progressive relationship between the global and local graph is ignored. From above mentions, the methods based on non-neural networks show the better causal relationship between graph structure and the specific optimization function, while the methods based on neural networks demonstrate the stronger learning ability between graph structure and the uncertain optimization networks. It makes the latter be more suitable for further mining the graph structure. Moreover, the similarity metric of pairwise nodes in graph usually directly connect with raw data to easily fit its distribution. Therefore, our proposed method focuses on graph learning based on GCN to find the hierarchical progressive relationship between the global and local graph. \section{Deep graph learning} Deep graph learning (DGL) includes three modules, which are similarity metric learning module (S-module), attention learning module(A-module) and fusion learning module(F-module) in figure \ref{fig-2}. Similarity metric learning module implements graph structure computation for dynamically updating global structure relationship based on the raw data or the transformed data. Attention learning module reassigns the weight of the neighbor of each data point for finding the significant local structure based on the global structure. Fusion learning module integrates node representation based on the different graph structure for semi-supervised classification. \begin{figure*}[htp] \begin{center} \includegraphics[width=1\linewidth]{2.png} \end{center} \vspace{-0.2in} \caption{The network frameworks of deep graph learning, which contains similarity metric learning module (S-module), attention learning module(A-module) and fusion learning module(F-module).$X_{N \times D}$,$X_{N \times D_{0}}^{0}$,$X_{N \times D_{1}}^{1}$,$X_{N \times D_{2}}^{2}$,$X_{N \times D_{3}}^{3}$ and $X_{N \times D_{4}}^{4}$ respectively are node representation of each layer(The superscript of the node representation is the serial number of layer, and the subscript of the node representation shows the dimension space of the node representation.); $A_{N\times N}^{0}$ and $A_{N\times N}^{1}$ respectively are the adjacent matrix of the different layer(The superscript of the adjacent matrix is the serial number of layer, and the subscript of the adjacent matrix shows the dimension space of the adjacent matrix.); $Loss_{G}$ is the loss of graph learning; $Loss_{C}$ is the loss of classification; $Loss$ is the total loss of the whole networks.} \label{fig-2} \end{figure*} \subsection{Similarity metric learning module} Given data matrix $X\in R^{N\times D}$ ($N$ is the sample number of data, and $D$ is the dimension of each data), Let $X$ be the node representation of graph $G$. We expect to learn $G$ from $X$ for semi-supervised classification. In this module, there are three types of layer for stacking network structure. \textbf{The first type of layer} is linear projection layer for reducing the dimension of raw data feature. Because the dimension of raw data often leads to the higher computation complexity, the linear transformation of the reduction dimension is expected to implement in this layer. \begin{align} \label{fun-1} \begin{aligned} &X^{0}_{N\times D_{0}}=XP, \end{aligned} \end{align} here, $P\in R^{D \times D_{0}}$ is the linear transformation matrix, and $X^{0}_{N\times D_{0}}$ stands for the output of the linear projection layer. \textbf{The second type of layer} is graph learning layer for computing the weight of the pairwise nodes. The adjacent relationship $A^{l}_{N\times D_{l}}(i,j)$($i$ and $j$ respectively are the subscript of the different node representation in Graph $G$; $l$ represents the serial number of the layer)can describe this relationship weight, and can be defined as follow. \begin{align} \label{fun-2} \begin{aligned} A^{l}_{N\times N}(i,j)= &\frac{A(i,j)\exp(ReLU((\alpha^{l})^{T}|x_{i}^{l}-x_{j}^{l}|))}{\sum^{N}_{j}A(i,j)\exp(ReLU((\alpha^{l})^{T}|x_{i}^{l}-x_{j}^{l}|))}, \end{aligned} \end{align} here, $A$ is the normalized adjacent matrix from the initial data source. If $A$ is not available, $A(i,j)=1$. $ReLU(f)=\max(0,f)$ ($f$ is any variable or matrix) can assure the nonnegativity of $A^{l}_{N\times N}(i,j)$. $x_{i}^{l}\in R^{D_{l} \times 1}$ and $x_{j}^{l}\in R^{D_{l} \times 1}$ respectively are the different row transpose of the input $X^{l}_{N\times D_{l}}$ in the current layer. Equation \ref{fun-2} makes $A^{l}_{N\times N}$ normalized corresponding to its row. $\alpha^{l}\in R^{D_{l} \times 1}$ is weight parameter vector for measuring the significance of the relationship between nodes. Graph learning mainly trains the network for learning $\alpha^{l}$($l$=\{0,1\}). \textbf{The third type of layer} is graph convolution layer for propagating information based on graph. According to GCN\cite{kipf2016semi}, we can define the graph convolution layer as follow. \begin{align} \label{fun-3} \begin{aligned} &X_{N \times D_{l+1}}^{l+1}=ReLU(\hat{D^{l}}^{-1/2}\hat{A^{l}}\hat{D^{l}}^{-1/2}X_{N \times D_{l}}^{l}W^{l}), \end{aligned} \end{align} here, $\hat{A^{l}}=I_{N\times N}+A^{l}_{N\times N}$($I_{N\times N}\in R^{N\times N}$ is the identity matrix); $\hat{D^{l}}(i,i)=\sum_{j}A^{l}_{N\times N}(i,j)$; $W^{l}\in R^{D^{l}\times D^{l+1}}$ is the trainable weight matrix of the current layer. Similarity metric learning module based on three types layer includes one linear projection layer, two graph learning layer and graph convolution layer from input to output. Especially, two times stack of graph learning layer and graph convolution layer can construct deep network for mining the global graph structure of the different scale node representation. \subsection{Attention learning module} In the whole network construction, the global structure generation by similarity metric learning module can initially build local structure information of the neighbor of node representation. However, this local structure information only come from the pair-wise relevance between the current node and all other nodes, but weaken the importance discrimination of the node in the neighborhood of the current node. Therefore, we expect to construct attention learning module by the aggregation of the neighbor information for further capturing the local structure based on the sparse constrains neighborhood of the global structure(we call this process as hierarchical progressive learning).The original GAT \cite{velivckovic2017graph} only can process the binary weight of pair-wise node representation. For example, attention mechanism is built based on node's neighborhood weighted by binary value. However, the weight of the learned graph is real-value, which help to confirm the node's neighborhood with the incorporating the sparse constrains of the global graph structure. Therefore, the operation of attention mechanism is defined as follow. \begin{align} \label{fun-4} \begin{aligned} &X_{N \times D_{l+1}}^{l+1}=ReLU(\beta^{l}X_{N \times D_{l}}^{l}W^{l}), \end{aligned} \end{align} here, $\beta^{l}\in R^{N \times N}$ is the attention coefficient matrix, which any entry $\beta^{1}(i,j)$ directly is relevant with $X_{N \times D_{l}}^{l}(i,:)$,$X_{N \times D_{l}}^{l}(j,:)$ and $A_{N\times N}^{l}(i,j)$. Therefore, we define $\beta^{1}(i,j)$ by information aggregation based on graph as follow. \begin{align} \label{fun-5} \begin{aligned} &\hat{\beta}^{l}(i,j)=\exp{(ReLU(\gamma^{T}[X_{N \times D_{l}}^{l}(i,:)W^{l}\|X_{N \times D_{l}}^{l}(j,:)W^{l}]))}A_{N\times N}^{l}(i,j), \end{aligned} \end{align} \begin{align} \label{fun-6} \begin{aligned} &\beta^{1}(i,j)=\hat{\beta}^{l}(i,j)/\sum^{N}_{k}\hat{\beta}^{l}(i,k), \end{aligned} \end{align} here, $\|$ is the concatenation operator for transforming into column vector;$\gamma\in R^{2D_{l+1}\times 1}$ is the aggregation weight, which is shared by the dimension of all pari-wise nodes aggregation. In attention learning module, we handle the different scale information from the global graph structure by two graph attention layer for further mining local graph structure, which is credible basis for the description of the intra-class. \subsection{Fusion learning module} Fusion learning module includes two parts, which respectively are fusion learning layer for the different node representation and loss function for network training propagation. \textbf{The first part} is fusion learning layer to process the different dimension question of the node representation or the weight balance issue from the different module (similarity metric learning module or attention learning module). From figure \ref{fig-2}, the inputs of this module have $X_{N \times D_{2}}^{2}$ of graph convolution layer output, $X_{N \times D_{3}}^{3}$ and $X_{N \times D_{4}}^{4}$ of the different graph attention layer output. Because this network need deal with classification, we uniform the output dimension of the different module ($D_{2}=D_{3}=D_{4}=C$, $C$ is class number). Therefore, we define fusion learning layer as follow. \begin{align} \label{fun-7} \begin{aligned} &Z=Softmax(\eta_{1}X_{N \times D_{2}}^{2}+\eta_{2}X_{N \times D_{3}}^{3}+\eta_{3}X_{N \times D_{4}}^{4}), \end{aligned} \end{align} here $\eta=[\eta_{1},\eta_{2},\eta_{3}]$ is fusion coefficient vector, which encodes the importance of the different node representation. \textbf{The second part} is loss function definition, which determine the tendency of the network learning. The total loss $Loss$ contains the classification loss $Loss_{C}$ and the graph loss $Loss_{G}$. In semi-supervised classification, we construct classification loss based on the labeled data by cross-entropy loss for evaluating the error between the predicted label $Z$ and the real label $Y$. Therefore, $Loss_{C}$ is defined as follow. \begin{align} \label{fun-8} \begin{aligned} &Loss_{C}=-\sum_{k\in S}\sum_{c=1}^{C}Y_{kc}lnZ_{kc}, \end{aligned} \end{align} here,$S$ is the labeled data set; $Y_{kc}$ stands for the $kth$ label data belonging to the $cth$ class; $Z_{kc}$ shows the $kth$ label data predicted as the $cth$ class. In graph learning, we compute the adjacent matrix $A_{N\times N}^{0}$ and $A_{N\times N}^{1}$ for describing the graph of the different scale. To constrain the properties (sparsity and consistence) of these adjacent matrix, we define the graph loss $Loss_{G}$ as follow. \begin{align} \label{fun-9} \begin{aligned} Loss_{G}=&\lambda_{1}(X^{T}_{N\times D}(I-A_{N\times N}^{0})X_{N\times D}+X^{T}_{N\times D}(I-A_{N\times N}^{1})X_{N\times D})\\ &+\lambda_{2}(\|A_{N\times N}^{0}\|_{F}^{2}+\|A_{N\times N}^{1}\|_{F}^{2})+\lambda_{3}\|A_{N\times N}^{0}-A_{N\times N}^{1}\|_{F}^{2}, \end{aligned} \end{align} here, the first term can enforce the $X_{N\times D}$ matching with the topology of the graph by graph Laplacian regularizer; the second term can guarantee the sparsity of these adjacent matrixes; the third term can assure the consistence between these adjacent matrixes. Therefore,the total loss $Loss$ is the sum of $Loss_{C}$ and $Loss_{G}$. \begin{align} \label{fun-10} \begin{aligned} Loss=Loss_{C}+Loss_{G}, \end{aligned} \end{align} \section{Experiment} \subsection{Datasets} For evaluating the proposed DGL method, we carry out experiments in one generated dataset, and six benchmark datasets, which include three the paper-citation networks datasets(Cora,Citeseer and Pubmed\cite{sen2008collective}) and two image datasets(MNIST\cite{lecun1998gradient} and Cifar10\cite{krizhevsky2009learning}). The synthesized dataset contains 4 classes, each of which has 1000 samples, and includes 4000 samples. These data are randomly synthesized. In experiment, each class samples are divided into four groups, which are 1/100/899, 2/100/898, 3/100/897 and 4/100/896 for training/validation/testing sets. Table \ref{tab-1} show its details. Cora dataset includes 7 classes that have 2708 grouped publications as nodes represented by one-hot vector in term of the present or absence state of a word in the learned directory and their link relationship graph. Citeseer dataset contains 6 classes that involve 3327 scientific paper described like the same way of Cora dataset and their undirected graph. Pubmed dataset has 3 classes that include 19717 diabetes-related publication indicated by a term frequency-inverse document frequency (TF-IDF)\cite{wu2019comprehensive} and their relevance graph. In these datasets, experiments follow the configuration of the previous work \cite{kipf2016semi}. We select 500 samples for validation and 1000 samples for testing. Table \ref{tab-1} shows the specific information of these datasets. Cifar10 dataset has 10 classes that consists 50000 natural images\cite{krizhevsky2009learning}. The size of each RGB image is $32\times 32$. We select 10000 images (1000 images for each class) for evaluating the proposed DGL. For representing each image, we use Resnet-20\cite{he2016deep} to extract feature. MNIST dataset contains 10 classes of hand-written digit. We also select 10000 images (1000 images for each class) for assessing the proposed DGL. Each image feature is 784 dimension vector generated by the gray image. Table \ref{tab-1} demonstrates the statistics of these datasets. \begin{table*}[!ht] \small \renewcommand{\arraystretch}{1.0} \caption{Datasets statistics and the extracted feature in experiments.} \label{tab-1} \begin{center} \newcommand{\tabincell}[2]{\begin{tabular}{@{}#1@{}}#2\end{tabular}} \begin{tabular}{lp{0.8cm}p{1.0cm}p{1.2cm}p{1.0cm}p{1.5cm}p{1.2cm}p{0.8cm}} \hline \bfseries Datasets & \bfseries \tabincell{l}{Classes \\number} & \bfseries \tabincell{l}{Training\\Number} &\bfseries \tabincell{l}{Validating\\Number}& \bfseries \tabincell{l}{Testing\\Number} & \bfseries \tabincell{l}{Total number \\of images} & \bfseries \tabincell{l}{Feature\\dimension}& \bfseries \tabincell{l}{Initial\\graph} \\ \hline \hline \tabincell{l}{Generated\\ data}&$4$ &$4\sim16$& $400$ &$3596\sim3584$& $4000$ &200&No\\ \hline Cora &$7$ &$140$& $500$ &$1000$& $2708$ &1433&Yes\\ \hline Citeseer&$6$ &$120$& $500$ &$1000$& $3327$ &3703&Yes\\ \hline Pubmed &$3$ &$59$& $500$ &$1000$& $19717$ &500&Yes\\ \hline Cifar10 &$10$ &$1000\sim8000$& $1000$ &$8000\sim1000$& $50000$ &128& No\\ \hline MNIST &$10$ &$1000\sim8000$& $1000$ &$8000\sim1000$& $60000$ &784& No\\ \hline \end{tabular} \end{center} \end{table*} \subsection{Experimental configuration} In experiments, we set $D_{0}=70$, $D_{1}=30$ and $D_{2}=D_{3}=D_{4}$, which is equal the classes number. The training maximum episodes of the proposed DGL is $200$. The parameter $\lambda_{1}$, $\lambda_{2}$ and $\lambda_{3}$ respectively are set $0.1$,$0.01$ and $0.001$. In Cifar10 and MNIST datasets, we select 8 group data for the different training-validating-testing sets(1000-1000-8000, 2000-1000-7000, 3000-1000-6000, 4000-1000-5000, 5000-1000-4000, 6000-1000-3000, 7000-1000-2000 and 8000-1000-1000). In the different datasets, validation set mainly is used for optimizing hyper-parameters, which include the dropout rate for all layer, the number of hidden units and the learning rate. \subsection{Generated data experiment} For observing the generated date, we reduce multi-dimension data to two dimension for visualizing data by t-SNE \cite{maaten2008visualizing}. Figure \ref{fig-21} shows the distribution of the generated data in two dimension, and experimental results of four methods, which are the proposed DGL,GLSGCN,GLGCN\cite{jiang2019semi} and GLGAT. GLSGCN and GLGAT is constructed for extending graph learning method in section \ref{extending}. Although the few data are labeled, DGL can still learn the structure distribution of data to obtain the promising results. Therefore, we conduct the following experiments for further evaluating the proposed DGL in the real datasets. \begin{figure*}[ht] \begin{center} \includegraphics[width=1\linewidth]{3.png} \end{center} \vspace{-0.2in} \caption{The structure distribution of the two-dimension generated data in (a) and the contrast experiment of the graph learning method in (b).} \label{fig-21} \end{figure*} \subsection{Comparison with baseline approaches} \label{baseline} In this section, we implement the proposed DGL and the baseline methods, which are GCN\cite{kipf2016semi}, GAT \cite{velivckovic2017graph}, simplifying graph convolutional networks(SGCN)\cite{wu2019simplifying} and GLGCN \cite{jiang2019semi}. GCN can construct the basic architecture of graph representation and classification model by the localized first-order approximation of spectral graph convolutions. GAT can learn the different weights to different nodes in a neighborhood for finding the attentions mechanism of local data. SGCN can eliminate the redundant complexity and computation of GCN by removing nonlinear unit and collapsing operation between the different layer. GLGCN can combine graph learning and graph convolution to optimize the global graph structure. Comparing with these methods, DGL can not only mine the global graph structure by the different scale graph learning layer, but also capture the local graph structure by the different scale graph attention layer. Furthermore, DGL can integrate the node representation from the different graph structure by fusion learning layer. Table \ref{tab-2} shows that DGL has the best performance in these methods. The experimental results between parentheses of GCN, GAT GLGCN come from the literature\cite{jiang2019semi}, while the results of SGCN stem from the literature \cite{wu2019simplifying}. \begin{table}[!ht] \small \renewcommand{\arraystretch}{1.0} \caption{Comparison of the proposed DGL method with baseline methods (GCN,GAT,SGCN and GLGCN) for semi-supervised classification, average per-class accuracy (\%) is reported based on the same data configurations in the different datasets. The results between parentheses come from the different literatures. All methods use the initial graph for computing model.} \label{tab-2} \begin{center} \newcommand{\tabincell}[2]{\begin{tabular}{@{}#1@{}}#2\end{tabular}} \begin{tabular}{lp{2.5cm}p{2.5cm}p{2.5cm}} \hline \bfseries Method &\bfseries Cora &\bfseries Citeseer &\bfseries Pubmed \\ \hline \hline GCN\cite{kipf2016semi} & $81.1\pm0.4 (82.9)$ &$71.0\pm0.2 (70.9)$ & $78.9\pm0.5 (77.9)$ \\ \hline GAT\cite{velivckovic2017graph} & $81.4\pm0.8 (83.2)$ &$71.8\pm0.3 (71.0)$ & $78.1\pm0.4 (78.0)$ \\ \hline SGCN\cite{wu2019simplifying} & $82.3\pm0.5 (81.0)$ &$71.4\pm0.3(71.9)$ & $78.3\pm0.2(78.9)$ \\ \hline GLGCN\cite{jiang2019semi} & $82.2\pm0.7(85.5)$ &$72.0\pm0.2(72.0)$ & $78.3\pm0.1(78.3)$ \\ \hline\hline DGL & $\textbf{84.8}\pm0.7$ &$\textbf{74.2}\pm0.5$ & $\textbf{80.2}\pm0.2$ \\ \hline \end{tabular} \end{center} \end{table} \subsection{Comparing with State-of-the-arts} \label{sota} Graph learning with neural network shows the promising results for semi-supervised classification. In section \ref{rws}, we summary the graph learning methods based on neural network, find the bias of the global graph structure or the local graph structure in existing methods. Therefore, we try to construct the new graph learning method based on neural network for further mining graph structure and balance the bias of these methods. We compare the proposed DGL with H-GCN \cite{hu2019hierarchical},GLNNs \cite{gao2019exploring},DIAL-GNN\cite{chen2019deep} and GLGCN\cite{jiang2019semi}. The difference of these methods is detailed in section \ref{rws}. Table \ref{tab-3} shows the best performance of the different methods, for example, GLGCN in Cora,and DGL in Citeseer and Pubmed. These methods can obtain the approximate performance in these datasets. For further contrasting the difference between GLGCN and the proposed DGL, we carry out the graph learning experiment in following section. \begin{table}[!ht] \small \renewcommand{\arraystretch}{1.0} \caption{Comparison of the proposed DGL method with state-of-the-art methods (H-GCN,GLNNs,DIAL-GNN and GLGCN) for semi-supervised classification, average per-class accuracy (\%) is reported based on the same data configurations in the different datasets. The results between parentheses come from the different literatures. All methods use the initial graph for computing model.} \label{tab-3} \begin{center} \newcommand{\tabincell}[2]{\begin{tabular}{@{}#1@{}}#2\end{tabular}} \begin{tabular}{lp{2.5cm}p{2.5cm}p{2.5cm}} \hline \bfseries Method &\bfseries Cora &\bfseries Citeseer &\bfseries Pubmed \\ \hline \hline H-GCN\cite{hu2019hierarchical} & $(84.5\pm0.5)$ &$(72.8\pm0.5)$ & $(79.8\pm0.4)$ \\ \hline GLNNs\cite{gao2019exploring} & $(83.4)$ &$(72.4)$ & $(76.7)$ \\ \hline DIAL-GNN\cite{chen2019deep} & $(84.5\pm 0.3)$ &$(74.1\pm0.2)$ & $Null$ \\ \hline GLGCN\cite{jiang2019semi} & $\textbf{(85.5)}$ &$(72.0)$ & $(78.3)$ \\ \hline\hline DGL & $84.8\pm0.7$ &$\textbf{74.2}\pm0.5$ & $\textbf{80.2}\pm0.2$ \\ \hline \end{tabular} \end{center} \end{table} \subsection{Comparing with the extended graph learning methods} \label{extending} In this section, we involve four methods, which are GLGCN\cite{jiang2019semi}, the proposed DGL and two extended methods (graph learning based on SGCN(GLSGCN) and graph learning based on GAT(GLGAT)). We use the basic idea of GLGCN to construct GLSGCN and GLGAT. \textbf{GLSGCN} includes a linear projection layer, which reduce the dimension of the original data to $70$,a graph learning layer and the following layers that are same with SGCN\cite{wu2019simplifying}. \textbf{GLGAT} also adds a linear projection layer for reducing the dimension of the data, a graph learning layer and the other layers that have the same configuration like GAT\cite{velivckovic2017graph}. In these experiments, all citation datasets do not use the initial graph, and graph structure can be learned from the original data by the different methods, for instance, GLSGCN and GLGCN tend to capture the global structure; GLGAT shallowly mine the global and local structure; the proposed DGL can deeply consider these structures for semi-supervised classification. Table \ref{tab-4} demonstrates the performance of the proposed DGL is better than that of other graph learning method. It indicates that deep mining and fusion of the different structure can significantly improve the performance of semi-supervised classification. GLSGCN shows the worse results than other methods in Cora and Citeseer datasets, while this method has the approximate result of other methods in Pubmed datasets. The main reason is that the simplifying structure of GLSGCN has the negative influence for graph structure learning in more categories. Table \ref{tab-5} shows the experimental results in MINIST image datasets. In the different training sets, DGL can outperform other graph learning methods. The same situation happens in Cifar10 of Table \ref{tab-6}. In all methods, the increasing training data is not a necessary and sufficient condition for the better performance because of the random data selection. \begin{table}[!ht] \small \renewcommand{\arraystretch}{1.0} \caption{Comparison of the proposed DGL method with the related graph learning methods (GLGCN, GLSGCN, GLGAT and DGL) for semi-supervised classification, average per-class accuracy (\%) is reported based on the same data configurations in the citation datasets (Cora,Citeseer and Pubmed). All methods do not use the initial graph for computing model.} \label{tab-4} \begin{center} \newcommand{\tabincell}[2]{\begin{tabular}{@{}#1@{}}#2\end{tabular}} \begin{tabular}{lp{2.5cm}p{2.5cm}p{2.5cm}} \hline \bfseries Method &\bfseries Cora &\bfseries Citeseer &\bfseries Pubmed \\ \hline \hline GLSGCN & $55.9\pm0.6$ &$49.6\pm0.3$ & $74.8\pm0.5$ \\ \hline GLGCN\cite{jiang2019semi} & $60.1\pm 0.3$ &$64.6\pm 0.2$ & $73.3\pm 0.5$ \\ \hline GLGAT & $63.1\pm 0.4$ &$65.5\pm0.2$ & $75.3\pm 0.2$ \\ \hline\hline DGL & $\textbf{65.3}\pm0.3$ &$\textbf{68.9}\pm0.4$ & $\textbf{76.9}\pm0.5$ \\ \hline \end{tabular} \end{center} \end{table} \begin{table}[!ht] \small \renewcommand{\arraystretch}{1.0} \caption{Comparison of the proposed DGL method with the related graph learning methods (GLGCN, GLSGCN, GLGAT and DGL) for semi-supervised classification, average per-class accuracy (\%) is reported based on the different data training/validation/testing in the MNIST image datasets.The initial graph for computing model is not available.} \label{tab-5} \begin{center} \newcommand{\tabincell}[2]{\begin{tabular}{@{}#1@{}}#2\end{tabular}} \begin{tabular}{lp{2.1cm}p{2.1cm}p{2.1cm}p{2.1cm}} \hline \bfseries Method &\bfseries \tabincell{l}{MNIST\\1000/1000/8000} &\bfseries \tabincell{l}{MNIST\\2000/1000/7000} &\bfseries \tabincell{l}{MNIST\\3000/1000/6000} &\bfseries\tabincell{l}{MNIST\\4000/1000/5000} \\ \hline \hline GLSGCN & $37.7\pm0.2$ &$38.7\pm0.4$ & $39.5\pm0.1$ & $39.6\pm0.2$\\ \hline GLGCN\cite{jiang2019semi} & $84.9\pm 0.4$ &$85.9\pm 0.2$ & $85.2\pm 0.3$& $88.0\pm 0.2$ \\ \hline GLGAT & $86.3\pm 0.5$ &$89.9\pm0.2$ & $89.7\pm 0.4$ & $89.2\pm 0.6$\\ \hline\hline DGL & $\textbf{89.1}\pm0.6$ &$\textbf{91.4}\pm0.2$ & $\textbf{91.1}\pm0.3$ & $\textbf{92.4}\pm0.5$\\ \hline \bfseries Method &\bfseries\tabincell{l}{MNIST\\5000/1000/4000} &\bfseries\tabincell{l}{MNIST\\6000/1000/3000} &\bfseries\tabincell{l}{MNIST\\7000/1000/2000} &\bfseries\tabincell{l}{MNIST\\8000/1000/1000} \\ \hline \hline GLSGCN & $39.4\pm0.3$ &$39.3\pm0.4$ & $38.9\pm0.3$ & $42.7\pm0.5$\\ \hline GLGCN\cite{jiang2019semi} & $87.9\pm 0.4$ &$86.4\pm 0.2$ & $88.0\pm 0.5$ & $88.9\pm 0.7$\\ \hline GLGAT & $89.7\pm 0.3$ &$89.1\pm0.7$ & $89.6\pm 0.4$ & $90.2\pm 0.5$\\ \hline\hline DGL & $\textbf{91.1}\pm0.5$ &$\textbf{91.3}\pm0.2$ & $\textbf{91.6}\pm0.6$ & $\textbf{92.4}\pm0.4$\\ \hline \end{tabular} \end{center} \end{table} \begin{table}[!ht] \small \renewcommand{\arraystretch}{1.0} \caption{Comparison of the proposed DGL method with the related graph learning methods (GLGCN, GLSGCN, GLGAT and DGL) for semi-supervised classification, average per-class accuracy (\%) is reported based on the different data training/validation/testing in the Cifar10 image datasets.The initial graph for computing model is not available.} \label{tab-6} \begin{center} \newcommand{\tabincell}[2]{\begin{tabular}{@{}#1@{}}#2\end{tabular}} \begin{tabular}{lp{2.1cm}p{2.1cm}p{2.1cm}p{2.1cm}} \hline \bfseries Method &\bfseries \tabincell{l}{Cifar10\\1000/1000/8000} &\bfseries \tabincell{l}{Cifar10\\2000/1000/7000} &\bfseries \tabincell{l}{Cifar10\\3000/1000/6000} &\bfseries\tabincell{l}{Cifar10\\4000/1000/5000} \\ \hline \hline GLSGCN & $63.5\pm0.4$ &$66.4\pm0.3$ & $71.5\pm0.5$ & $72.6\pm0.2$\\ \hline GLGCN\cite{jiang2019semi} & $84.2\pm 0.2$ &$79.7\pm 0.5$ & $81.1\pm 0.8$& $86.8\pm 0.4$ \\ \hline GLGAT & $86.5\pm 0.8$ &$87.4\pm0.5$ & $87.5\pm 0.6$ & $88.0\pm 0.3$\\ \hline\hline DGL & $\textbf{87.5}\pm0.5$ &$\textbf{88.8}\pm0.3$ & $\textbf{88.8}\pm0.6$ & $\textbf{88.8}\pm0.4$\\ \hline \bfseries Method &\bfseries\tabincell{l}{Cifar10\\5000/1000/4000} &\bfseries\tabincell{l}{Cifar10\\6000/1000/3000} &\bfseries\tabincell{l}{Cifar10\\7000/1000/2000} &\bfseries\tabincell{l}{Cifar10\\8000/1000/1000} \\ \hline \hline GLSGCN & $63.7\pm0.5$ &$73.3\pm0.3$ & $75.5\pm0.6$ & $71.0\pm0.3$\\ \hline GLGCN\cite{jiang2019semi} & $83.7\pm 0.9$ &$80.0\pm 0.5$ & $84.5\pm 0.7$ & $80.0\pm 0.7$\\ \hline GLGAT & $85.2\pm 0.5$ &$86.3\pm0.4$ & $87.5\pm 0.6$ & $87.0\pm 0.3$\\ \hline\hline DGL & $\textbf{87.0}\pm0.2$ &$\textbf{88.6}\pm0.5$ & $\textbf{89.0}\pm0.4$ & $\textbf{89.0}\pm0.3$\\ \hline \end{tabular} \end{center} \end{table} \subsection{Ablation experiments} \label{ablation} In this section, we expect to delete some parts form DGL for analyzing the function of the different components. In the proposed DGL, 'deep' has two kinds of meaning. One meaning is the information mining from global structure to local structure (from S-module of DGL to A-module of DGL in figure \ref{fig-2}). Therefore, we delete A-module for simulating the situation of non-local structure, which is called \textbf{DGL-non-local}. Another meaning is the metric learning of the different scale convolution information (two graph learning layers of DGL in \ref{fig-2}). Consequently, we delete the second graph learning layer for imitating the shallow metric learning, which is called \textbf{DGL-shallow-metric}. If DGL dose not consider the local graph structure and only care the metric learning of the single layer information, DGL will degrade to GLGCN. So, the intrinsic difference between DGL and GLGCN is the deep graph structure information mining and learning. Table \ref{tab-7} shows that the performance of DGL is superior to that of other methods. Specially, local graph structure mining by attention mechanism can complement global structure capturing by metric learning, so the performance of DGL-shallow-metric is better than that of GLGCN. Deep metric learning can obtain the more abundant structure information from the different scale node representation, hence the classification accuracy of DGL-non-local outperforms that of GLGCN. The performance of DGL-shallow-metric is obvious better than that of DGL-non-local, and it demonstrates that hierarchical progressive learning from the global structure to the local structure can get the more positive effect than metric learning from the different scale node representation. Furthermore, both factors can be considered for constructing DGL, and DGL can obtain the promising results for semi-supervised classification. \begin{table}[!ht] \small \renewcommand{\arraystretch}{1.0} \caption{Comparison of the proposed DGL method with GLGCN , and the ablated methods (DGL-non-local and DGL-shallow-metric) for semi-supervised classification, average per-class accuracy (\%) is reported based on the different datasets.The initial graph for computing model is not available.} \label{tab-7} \begin{center} \newcommand{\tabincell}[2]{\begin{tabular}{@{}#1@{}}#2\end{tabular}} \begin{tabular}{lp{2.5cm}p{2.5cm}p{2.5cm}} \hline \bfseries Method &\bfseries Cora &\bfseries Citeseer &\bfseries Pubmed \\ \hline \hline GLGCN\cite{jiang2019semi} & $60.1\pm 0.3$ &$64.6\pm 0.2$ & $73.3\pm 0.5$ \\ \hline DGL-non-local & $62.5\pm0.5$ &$65.9\pm0.2$ & $75.4\pm0.3$ \\ \hline DGL-shallow-metric & $63.7\pm 0.2$ &$66.2\pm0.5$ & $75.8\pm 0.4$ \\ \hline\hline DGL & $\textbf{65.3}\pm0.3$ &$\textbf{68.9}\pm0.4$ & $\textbf{76.9}\pm0.5$ \\ \hline \bfseries Method &\bfseries \tabincell{l}{MNIST\\1000/1000/8000} &\bfseries\tabincell{l}{Cifar10\\1000/1000/8000} \\ \hline \hline GLGCN\cite{jiang2019semi} & $84.9\pm 0.4$ &$84.2\pm 0.2$ \\ \hline DGL-non-local & $85.7\pm0.3$ &$85.2\pm0.5$ \\ \hline DGL-shallow-metric & $87.6\pm 0.6$ &$86.9\pm0.3$ \\ \hline\hline DGL & $\textbf{89.1}\pm0.6$ &$\textbf{87.5}\pm0.5$ \\ \hline \end{tabular} \end{center} \end{table} \subsection{Graph learning visualization} For directly observing graph learning process, we reduce multi-dimension node data to two dimension for visualizing data by t-SNE \cite{maaten2008visualizing}. we respectively show the node data distribution of the different episodes(1,50,100,150) in Cifar10 image datasets, in which training/validation/testing data number respectively is set $1000/1000/8000$. Figure \ref{fig-3} shows that the various structure distribution in the different leaning stage. In episode 1, the data distribution presents the hybrid state of the class; in episode 50, the less categories can be separated from all classes; in episode 100, the more categories subsequently can be parted from the whole classes; in episode 150, most of categories can be divided each other. We can observe that the globe and local structure distribution gradually show the aggregation state of the class. Figure \ref{fig-4} indicates that the loss change with episode increasing in DGL and GLGCN. The training or testing loss of DGL obviously is less than that of GLGCN, and it shows that DGL model can obtain the better performance than GLGCN model in training and testing for semi-supervised classification. \begin{figure*}[ht] \begin{center} \includegraphics[width=1\linewidth]{4.png} \end{center} \vspace{-0.2in} \caption{The various structure distribution of the different leaning stage of DGL in Cifar10 dataset. (a) is the structure distribution of episode $1$, (b) for that of episode $50$, (c) for that of episode $100$ and (d) for that of episode $150$. Horizontal and vertical axis respectively stand for the different dimension of data.} \label{fig-3} \end{figure*} \begin{figure*}[ht] \begin{center} \includegraphics[width=0.8\linewidth]{5.png} \end{center} \vspace{-0.2in} \caption{The loss of DGL and GLGCN in training and testing in Cifar10 dataset.} \label{fig-4} \end{figure*} \subsection{Experimental results analysis} \label{analysis} In experiments, eleven methods are utilized to evaluating the different aspects of the proposed DGL. These method can be divided into four group for the different purpose. The first group includes four baseline methods (GCN\cite{kipf2016semi}, GAT\cite{velivckovic2017graph}, SGCN\cite{wu2019simplifying} and GLGCN \cite{jiang2019semi} in section \ref{baseline}) for cognising the motivation of the proposed DGL. The second group contains four state-of-art methods(H-GCN \cite{hu2019hierarchical},GLNNs \cite{gao2019exploring}, DIAL-GNN\cite{chen2019deep} and GLGCN\cite{jiang2019semi} in section \ref{sota}) for analyzing the advantages and disadvantages between these graph learning methods and the proposed DGL. The third group explores two methods(GLSGCN and GLGAT in section \ref{extending}) based on the main idea of GLGCN \cite{jiang2019semi} for extending the graph learning method based on GCN \cite{kipf2016semi}. The forth group exploits two methods (DGL-non-local and DGL-shallow-metric in section \ref{ablation}) for finding the function of the different components in the proposed DGL. According to the above experiments, we can have the following observations. \begin{itemize} \item The performance of DGL outperforms the baseline approaches, which are GCN\cite{kipf2016semi}, GAT \cite{velivckovic2017graph}, SGCN \cite{wu2019simplifying} and GLGCN \cite{jiang2019semi} in section \ref{baseline}. GCN\cite{kipf2016semi} can reveal the node information propagation based on the statically global graph structure for capturing the data distribution relationship and node representation. GAT \cite{velivckovic2017graph} can assign the weight of the neighborhood in each data node to learn the local graph structure. SGCN \cite{wu2019simplifying} can simplify networks architecture based on the statically global graph structure for reaching the approximating results of GCN. GLGCN \cite{jiang2019semi} can extract the global graph structure from the original data in the networks learning for constructing the basic frameworks of graph learning based on GCN. DGL can not only dynamically mine the global and local graph structure for balancing their effect of the information propagation, but also simultaneously encode the node representation of the different scale outputs for improving the performance of semi-supervised classification. \item The graph learning methods based GCN (GLGCN\cite{jiang2019semi} and the proposed DGL) have the obvious performance improvement than the non-graph learning methods (GCN\cite{kipf2016semi}, GAT \cite{velivckovic2017graph} and SGCN \cite{wu2019simplifying}). The main reason is that the graph learning methods can dynamically generate graph structure by the parameterized interaction computation, while non-graph learning methods can only depend on the static graph structure in the whole networks learning regardless of the change of each layer. Therefore, the graph learning methods can better fit to the distribution of the transforming data in each layer for enhancing the performance of semi-supervised classification. \item In the state-of-the-art graph learning methods based on neural networks(H-GCN \cite{hu2019hierarchical},GLNNs \cite{gao2019exploring}, DIAL-GNN\cite{chen2019deep} and GLGCN\cite{jiang2019semi} in section \ref{sota}), the global or local graph structure can be described and mined by hierarchical aggregation or metric learning. The proposed DGL can comprehensively consider the global and local graph structure, and encode their propagation relationship for improving the performance of the networks model. Therefore, DGL can obtain the best performance of Citeseer and Pubmed datasets and the approximated best performance of Cora dataset in these state-of-the-art methods. \item The extended graph learning methods (GLSGCN and GLGAT in section \ref{extending}) conbine the main idea of GLGCN\cite{jiang2019semi} with GAT \cite{velivckovic2017graph} or SGCN \cite{wu2019simplifying} for finding the adaptation of the graph learning method. GLSGCN can get the worse performance than GLGCN \cite{jiang2019semi},while GLGAT can obtain the better performance than GLGCN \cite{jiang2019semi}. It shows that nonlinear unit layer have the stronger learning ability for dynamically generating graph structure. DGL outperforms GLSGCN and GLGAT, and it demonstrates that the different scale metric learning (from the global to the local graph structure and from the different layers) can contribute to the construction of the graph learning model. \item The proposed DGL method can delete the different components to formulate the different ablation methods (DGL-non-local and DGL-shallow-metric in section \ref{ablation}). DGL-non-local method emphasises on the global graph structure learning from the different scale node representation, while DGL-shallow-metric focuses on the balance learning between the global and the local graph structure in single layer. The performance of DGL-shallow-metric is superior to that of DGL-non-local, and it indicates that the depth mining from the global graph structure to the local graph structure has the more obvious effect than deep metric learning from the different scale outputs. However, two factors is simultaneously considered to build DGL that can obtain the promising results for semi-supervised classification. \item In the extended graph learning experiment, the different graph learning method shows the approximate results with training/validation/testing change. It reveals that graph learning process can complement the insufficient number of the training samples for improving the generalization of the model. Therefore, in Table \ref{tab-5} and \ref{tab-6}, this situation happens in the experimental results of the different graph learning methods. \end{itemize} \section{Conclusion} We have presented deep graph learning (DGL) method to address the global and local graph integration learning for improving semi-supervised classification. The proposed DGL can not only use graph learning layer and graph attention layer for hierarchical progressive graph structure mining, but also adopt two graph learning layers for deep capturing the global graph structure information from the different scale node representation. Furthermore, DGL can balance the difference between the global and local graph structure for finding the abundant data relationship, and fusion the node representation of the different layers for enhancing semi-supervised classification. Finally, DGL can automatically generate graph structure in networks learning, and dynamically encode the various information of the different layers. Experimental results and analysis shows that the proposed DGL method is promising for node classification on Citeseer,Cora, Pubmed,MNIST and Cifar10 datasets. \section{Acknowledgements} The authors would like to thank the anonymous reviewers for their insightful comments that help improve the quality of this paper. This work was supported by NSFC (Program No.61771386,Program No.61671376 and Program No.61671374).
{'timestamp': '2020-06-01T02:07:13', 'yymm': '2005', 'arxiv_id': '2005.14403', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14403'}
arxiv
\section*{Summary} \begin{enumerate} \item Ecologists use distance sampling to estimate the abundance of plants and animals while correcting for undetected individuals. By design, data collection is simplified by requiring only the distances from a transect to the detected individuals be recorded. Compared to traditional design-based methods that require restrictive assumption and limit the use of distance sampling data, model-based approaches enable broader applications such as spatial prediction, inferring species-habitat relationships, unbiased estimation from preferentially sampled transects, and integration into multi-type data models. Unfortunately, model-based approaches require the exact location of each detected individual in order to incorporate environmental and habitat characteristics as predictor variables. \item Using a hierarchical specification, we modified model-based methods for distance sampling data by including a probability distribution that accounts for location uncertainty generated when only the distances are recorded. We tested and demonstrated our method using a simulation experiment and by modeling the habitat use of Dickcissels (\textit{Spiza americana}) using distance sampling data collected from the Konza Prairie in Kansas, USA. \item Our results showed that ignoring location uncertainty can result in biased coefficient estimates and predictions. However, accounting for location uncertainty remedies the issue and results in reliable inference and prediction. \item Location uncertainty is difficult to eliminate when collecting some types of ecological data. Like other types of measurement error, hierarchical models can accommodate the data collection process thereby enabling reliable inference. Our approach is a significant advancement for the analysis of distance sampling data because it remedies the deleterious effects of location uncertainty and requires only distances be recorded. In turn, this enables historical distance sampling data sets to be compatible with modern data collection and modeling practices.\bigskip{} \end{enumerate} \begin{doublespace} \noindent \textbf{\textit{\emph{Key-words: }}}ecological fallacy, hierarchical model, integrated population model, point process, resource selection, species distribution model \vspace{-1cm} \end{doublespace} \section*{Introduction} Distance sampling has been widely used for nearly a half a century to estimate abundance of plants and animals. This method involves one or more observers recording the distances from point or line transects to detected individuals (\citealt{burnham1980estimation,buckland2001introduction}). Early statistical methods for the analysis of distance sampling data used design-based estimators that accounted for errors in detection. This resulted in a hybrid analysis, involving model-based methods used to account for errors in detection and design-based methods used to estimate abundance (\citealt{buckland2016model}). More recently, fully model-based approaches have been developed to enable spatial prediction, statistical inference regarding species-habitat relationships, and unbiased estimation of abundance from point and line transects that are placed non-randomly (\citealt{stoyan1982remark,hogmander1991random,hedley2004spatial,johnson2010model,miller2013spatial}). Current areas of research include data assimilation, fusion, integration or reconciliation requiring the development of joint models that combine multiple types of data. Such recent developments include integrated species distribution models that incorporate distance sampling data and presence-only data collected by citizen scientists (\citeauthor{Fletcher2019} \textit{in press}). Spatially-explicit models that link abundance to environmental and habitat characteristics are used in many areas of ecological research. For example, presence-absence, count, and presence-only data enable spatial prediction of species distributions (\citealt{elith2009species,hefleyHSDM}). Other examples include integrated species distributions models used to predict abundance and occupancy with higher accuracy by combining multiple types of data (e.g., \citealt{williams2017integrated}; \citeauthor{Fletcher2019} \textit{in press}). A common theme among these approaches is that the location of the individual is conceptualized as a point in geographic space where environmental conditions and habitat characteristics are measured (\citealt{hefleyHSDM,kery2015applied,milller2019}). Those location-specific conditions and characteristics (hereafter ``predictor variables'') are used to specify an intensity function which enables statistical inference regarding species-habitat relationships and provides estimates of abundance and occupancy that can be mapped at any spatial resolution. This framework relies on characterizing the distribution of abundance as a spatial point processes which is the same approach used to develop models for distance sampling data (\citealt{stoyan1982remark,hogmander1991random,hedley2004spatial,johnson2010model,miller2013spatial}). Often ecologists do not have the exact locations of individuals. For example, exact locations are unrecoverable from distance sampling data collected along line transects unless auxiliary information such as the location of the observer at the time of detection is recorded. Regardless of the mechanisms that obscure the exact locations, uncertainty limits the usefulness of the data because values of the predictor variables cannot be obtained. For example, if a distance sampling data set does not include the exact locations then analysis is restricted to models that include only the predictor variables that are constant for all individuals detected from a given transect (\citealt{johnson2010model,buckland2016model}). In practice, this lead to model-misspecification and lower predictive accuracy. Sometimes researchers attempt to mitigate this problem by using surrogate predictor variables such as the habitat characteristics at a convenient location (e.g., the center of the transect) or the average value of the predictor variable calculated from an area within an arbitrary distance of the transect line or point. Use of surrogate predictor variables can also bias parameter estimates and predictions. In some cases, the bias can invert the inferred relationship between predictor variables and abundance (\citealt{hefley2014correction,hefley2017bias,walker2018bias}; \citeauthor{walker2019bias} \textit{under revision}). To eliminate these issues, we present a model-based approach for distance sampling data that can be used when the location of individuals is uncertain. Our approach enables the same inference as model-based approaches requiring exact locations and can be incorporated into integrated data models that are based on an underlying point process (e.g., \citeauthor{Fletcher2019} \textit{in press}). Our approach relies on a hierarchical modeling framework, but results in relatively simple marginalized distributions that can be used for efficient Bayesian or likelihood-based estimation and inference. Using simulated data, we evaluate the ability of our method to account for location uncertainty and compare it to existing approaches commonly used in practice. Finally, we demonstrate our method using line transect data to estimate habitat use of a grassland bird species, the Dickcissel. \begin{spacing}{1.9} \section*{Materials and methods} \end{spacing} \begin{spacing}{1.9} \subsection*{MODEL-BASED DISTANCE SAMPLING} \end{spacing} \noindent A common practice when constructing statistical models is to choose a probability distribution that matches important characteristics of the data. For example, if the data are counts then a statistical model that assumes a Poisson distribution might be used. Counts must be non-negative integers and the Poisson distribution is capable of generating non-negative integers (i.e., the support of the data and probability distribution match). As a result, a statistical model that is constructed using a Poisson distribution has the potential to have generated the observed data. Adhering to this principal results in generative statistical models that capture important characteristics of the process (e.g., predicted counts that are always $\geq0$), which can be important for interpretation and model checking (\citealt{conn2018guide,gelfand2018bayesian}). When constructing a statistical model for distance sampling data probability distributions should match the following characteristics of the data: 1) the number and locations of individuals are random variables; and 2) the location of individuals exists in continuous geographic space. In what follows, we use the term \textquotedblleft continuous geographic space\textquotedblright{} to describe spatial areas that are defined as polygons and contain an infinite number of possible locations (points) within the boundary of each polygon. Researchers have developed model-based approaches for the spatial analysis of distance sampling data (e.g., \citealt{miller2013spatial,buckland2016model}), but existing approaches do not account for location uncertainty except in the case where the distribution of individuals is spatially uniform (e.g., \citealt{borchers2015unifying}). Our approach builds upon one of the most common model-based methods for the spatial analysis of distance sampling data that uses an inhomogeneous Poisson point process (IPPP) distribution, which allows for heterogeneity in the spatial distribution of individuals. In what follows, we review previously developed modeling approaches based on the IPPP distribution and then extend this model to account for location uncertainty. The IPPP distribution describes the random number and locations of individuals within a continuous geographic space. The IPPP is constructed by assuming the spatial distribution of individuals is explained by an intensity function, $\lambda(\mathbf{s})$, where $\mathbf{s}$ is a vector that contains the coordinates of a single location contained within the study area $\mathcal{S}$. The intensity function is commonly specified as \begin{equation} \text{log}(\lambda(\mathbf{s}))=\beta_{0}+\boldsymbol{\mathbf{x}}(\mathbf{s})^{'}\boldsymbol{\beta}\:, \end{equation} where $\beta_{0}$ is the intercept, $\boldsymbol{\mathbf{x}}(\mathbf{s})$ is a $p\times1$ vector that contains predictor variables at location $\mathbf{s}$, and $\boldsymbol{\beta}\equiv(\beta_{1},...,\beta_{p})^{'}$ is a vector of regression coefficients. Estimating the regression coefficients from distance sampling data enables inference regarding species-habitat relationships. An important property of the IPPP distribution is that estimates of abundance can be obtained for any geographic region that is contained within the study area. More precisely, for any sub-region $\mathcal{A}$ contained within the study area $\mathcal{S}$, an estimate of abundance is \begin{equation} \bar{\lambda}=\intop_{\mathcal{A}}\lambda(\mathbf{s})d\mathbf{s}\:, \end{equation} which is referred to as the integrated intensity function. Clearly, accurate estimates of abundance requires reliable estimation of the intensity function ($\lambda(\mathbf{s})$) which depends on the intercept ($\beta_{0}$), regression coefficients ($\boldsymbol{\beta}$) and predictor variables ($\boldsymbol{\mathbf{x}}(\mathbf{s})$). As with traditional distance sampling methods, the IPPP can incorporate a detection function, which we denote $q(\mathbf{s})$, where $q(\cdot)$ is the usual detection function (e.g., half-normal function) that depends on the location $\mathbf{s}$ by way of the distance between an individual and the point or line transect. Employing the notation from above, the probability distribution function for the IPPP is \begin{equation} [\mathbf{z}_{1},\mathbf{z}_{2},...,\mathbf{z}_{n},n|\lambda(\mathbf{s}),q(\mathbf{s})]=e^{\mathbf{-\intop_{\mathcal{S}}\lambda(\mathbf{s})}q(\mathbf{s)}d\mathbf{s}}\prod_{i=1}^{n}\lambda(\mathbf{z}_{i})q(\mathbf{z}_{i})\:, \end{equation} where $\mathbf{z}_{1},\mathbf{z}_{2},...,\mathbf{z}_{n}$ are the coordinate vectors (i.e., exact locations) of the $n$ detected individuals (\citealt{johnson2010model}). The product of $\lambda(\mathbf{s})$ and $q(\mathbf{s})$ is referred to as the thinned intensity function (\citealt{cressie1993statistics}, p. 689). The bracket notation $[\cdot]$, used on the left hand side of Eq. 3, represents a probability distribution. Using bracket notation, $[y,z]$ is a joint distribution where $y$ and $z$ are the random variables, $[y|z]$ is a conditional distribution where $y$ is the random variable given $z$. The marginal distribution of $y$ can be obtained by ``integrating out'' $z$ (i.e., $[y]=\int[y,z]dy$). When expressed as a likelihood function, Eq. 3 can be used to estimate parameters associated with the intensity and detection functions. For example, using Eq. 3 as a likelihood function facilitates estimation of the regression coefficients, $\boldsymbol{\beta}$, from Eq. 1 and enables inference regarding species-habitat relationships. Evaluation of the likelihood function, however, requires the exact locations of all $n$ detected individuals. \vspace{0.66cm} \begin{spacing}{1.9} \subsection*{ACCOUNTING FOR UNKNOWN LOCATION} \end{spacing} \noindent Parameter estimation and statistical inference using the IPPP distribution requires the exact location of each detected individual because the likelihood function from Eq. 3 assumes that $\mathbf{z}_{i}$ is recorded. When collecting distance sampling data, the exact location of each detected individual is usually not recorded which generates location uncertainty. Below, we extend the IPPP distribution so that the model can be implemented when the location of individuals is uncertain. Our extension could be viewed as a special case of the unified approach of \citet{borchers2015unifying}, however, the authors did not present how models that involve nonuniform distribution of plants and animals, such as the IPPP, might be implemented. In what follows, we show in detail how to implement such models. Using distance sampling data collected from a line transect, an individual's exact location is an unknown point that lies on one of two lines parallel to the transect at a perpendicular distance that is equal to the recorded distance. Similarly, for point transects, the location of an individual is an unknown point on the perimeter of a circle centered on the transect with a radius that is equal to the recorded distance. If the exact location is unknown but lies on a line or perimeter of a circle, a model that is based on the IPPP distribution and accounts for location uncertainty in \begin{equation} [\mathbf{y}_{1},\mathbf{y}_{2},...,\mathbf{y}_{n},n|\lambda(\mathbf{s}),q(\mathbf{s})]=e^{\mathbf{-\intop_{\mathcal{S}}\lambda(\mathbf{s})}q(\mathbf{s)}d\mathbf{s}}\prod_{i=1}^{n}{\displaystyle |\mathcal{L}_{i}|}^{-1}\intop_{\mathcal{L}_{i}}\lambda(\mathbf{z}_{i})q(\mathbf{z}_{i})d\mathbf{z}_{i}\: \end{equation} where the modification involves replacing the product of $\lambda(\mathbf{z}_{i})$ and $q(\mathbf{z}_{i})$ in Eq. 3 with an integral. In Eq. 4, the random variable is the coordinate vectors $\mathbf{y}_{1},\mathbf{y}_{2},...,\mathbf{y}_{n}$ and number of detected individuals $n$. As in Eq. 3, $\mathbf{z}_{i}$ is the exact coordinate of the $i^{\text{th}}$ individual, which is integrated out of the joint distribution to obtain Eq. 4. Knowing the distance and transect of detection determines the limits of integration in Eq. 4, where $\mathcal{L}_{i}$ is the parallel lines (circle perimeter) and $|\mathcal{L}_{i}|$ is the length of the lines (or circle perimeter). Conceptually $\mathbf{y}_{i}$ can be thought of as the coordinate where the $i^{\text{th}}$ individual was ``recorded'', which is different than the true location of the individual $\mathbf{z}_{i}$ because the ``recorded'' location is a uniformly distributed point on $\mathcal{L}_{i}$ (see Appendix S1 for more detail).\vspace{0.66cm} \subsection*{ACCOUNTING FOR MEASUREMENT ERROR IN DISTANCES} In many cases the distance between the transect and the detected individuals may be recorded with error, which introduces another source of location uncertainty. For example, in the data illustration that follows, the distances recorded for individual birds close to the transect line were almost certainly recorded with greater accuracy than those detected further from the line. To account for error in distances, we construct a hierarchical model where the observed random variable, $\mathbf{y}_{i}$, is the ``recorded'' location which depend on the exact locations $\mathbf{z}_{i}$ (see Appendix S1 for more detail). A hierarchical model that accounts for both types of location uncertainty is \begin{equation} [\mathbf{y}_{1},\mathbf{y}_{2},...,\mathbf{y}_{n},n|\boldsymbol{\theta},\lambda(\mathbf{s}),q(\mathbf{s})]=e^{\mathbf{-\intop_{\mathcal{S}}\lambda(\mathbf{s})}q(\mathbf{s)}d\mathbf{s}}\prod_{i=1}^{n}{\displaystyle |\mathcal{L}_{i}|}^{-1}\intop_{\mathcal{S}}[d(\mathbf{y}_{i},t_{i})|d(\mathbf{z}_{i},t_{i}),\boldsymbol{\theta}]\lambda(\mathbf{z}_{i})q(\mathbf{z}_{i})d\mathbf{z}_{i}\:. \end{equation} In equation above, $\boldsymbol{\theta}\equiv(\theta_{1},\theta_{2},...\theta_{m})^{'}$ is a vector of unknown parameters of $[d(\mathbf{y}_{i},t_{i})|d(\mathbf{z}_{i},t_{i}),\boldsymbol{\theta}]$, which is a probability distribution that describes the recorded distances $d(\mathbf{y}_{i},t_{i})$ given the true distances $d(\mathbf{z}_{i},t_{i})$. The function $d(\cdot,\cdot)$ returns the perpendicular distance between a coordinate vector and the transect, $t_{i}$, where the $i^{\text{th}}$ individual was detected. We refrain from specifying the functional form of $[d(\mathbf{y}_{i},t_{i})|d(\mathbf{z}_{i},t_{i}),\boldsymbol{\theta}]$ because this portion of our model is general and any appropriate distribution can be chosen as shown in the data illustration. \subsection*{MODEL IMPLEMENTATION} For all models, estimating the parameters associated with the intensity ($\mathbf{\lambda(\mathbf{s})}$) and detection ($q(\mathbf{s})$) functions requires evaluation of the the integrals in the likelihood. In nearly all situation, solving the integrals will require numerical integration using approximations such as Monte Carlo or numerical quadrature (\citealt{BB2L}). Using a numerical quadrature involves the approximation \begin{equation} \intop_{\mathcal{A}}f(\mathbf{s)}d\mathbf{s}\approx|\mathcal{A}|{\displaystyle \sum_{q=1}^{Q}}f(\mathbf{s}_{q})\:, \end{equation} where $f(\mathbf{s})$ is an unspecified function, $\mathcal{A}$ is an arbitrary region (or line) with area (or length) $|\mathcal{A}|$ and $Q$ is the number of (equally spaced) points partitioning the polygon (or line). The function $f(\mathbf{s})$ is specified based on the integral. For example, Eqs. 3\textendash 5 contains the integral $\mathbf{\intop_{\mathcal{S}}\lambda(\mathbf{s})}q(\mathbf{s)}d\mathbf{s}$, which could be approximated by defining $f(\mathbf{s})\equiv\lambda(\mathbf{s})q(\mathbf{s}).$ Accounting for location uncertainty requires a hierarchical model because the probability distribution in Eqs. 4 and 5 were constructed by conditioning on the exact locations which are random variables that follow an IPPP distribution (see Appendix S1). Regardless of the inferential paradigm, the models are challenging to fit to distance sampling data because each detected individual has a latent (unobserved) true coordinate vector, which results in $2n$ additional parameters. For example, the true coordinate vectors could be estimated by fully specifying a Bayesian model and obtaining samples from the marginal posterior using a Markov chain Monte Carlo (MCMC) algorithm. This approach, however, requires sampling from a high-dimensional posterior distribution. Such an approach is challenging because the MCMC algorithm can be difficult to tune and require multiple evaluations of the likelihood function, involving a quadrature approximation. Estimates of the true coordinate vectors are of little interest because most studies use distance sampling data to obtain predictions densities and infer species-habitat relationships. As a result, the true coordinate vectors can be treated as ``nuisance parameters'' and removed by integrating the joint likelihood as we did in Eqs. 4\textendash 5 (\citealt{borchers2015unifying}). The integrated likelihood has $2n$ fewer parameters and the remaining parameters can be estimated using maximum likelihood estimation or by sampling from the posterior distribution using techniques such as MCMC (see Appendix S1). In both the simulation experiment and data example that follow, we estimate all parameters by maximizing the appropriate likelihood using the Nelder-Mead algorithm in R (\citealt{nelder1965simplex,TeamR}; see Appendix S2 and S3). For all model parameters, we obtain approximate variances by inverting the Hessian matrix and construct Wald-type confidence intervals (CIs; \citealt{pawitan2001all}). To obtain CI for derived quantities, we use percentiles of the empirical distribution obtained from a bootstrapping approach outlined by \citet{lele2010estimability} based on the results of \citet{harris1989predictive}.\vspace{0.66cm} \begin{spacing}{1.9} \subsection*{SIMULATION EXPERIMENT} \end{spacing} \begin{doublespace} \noindent We conducted a simulation experiment to evaluate the influence of location uncertainty on model-based distance sampling methods and to test the efficacy of our new approach. We expect that standard approaches will result in biased parameter estimates which may obscure species-habitat relationships or, in the worst case, result in misleading conclusions. Conversely, we expect that our proposed method that accounts for location uncertainty will result in unbiased parameter estimates (in the asymptotic sense). We expect that accounting for location uncertainty will result in parameter estimates that are more variable and have estimates of uncertainty that are appropriately inflated (e.g., CIs will be wider) when compared to estimates obtained from exact locations. \end{doublespace} We simulated the exact location of individuals from an IPPP distribution on the unit square with a single predictor variable ($x(\mathbf{s})$) and specified the intensity function as $\text{log}(\lambda(\mathbf{s}))=\beta_{0}+\beta_{1}$$x(\mathbf{s})$ with $\beta_{0}=9$ and $\beta_{1}=1$ (Fig. 1). We evaluated two scenarios by varying the location of 16 point transects. In the first scenario, we placed point transects in poorer quality ``habitat'' (i.e., at lower values of $x(\mathbf{s})$; Fig. 1a) whereas in the second scenario we randomly placed the transects but restricted transect placement so that detection of the same individual from multiple transect was not possible (Fig 1b). We designed the first and second scenarios to evaluate how location uncertainty influences parameter estimates when transects are placed based on convenience and under a randomized design respectively. We simulated the detection of each individual using a Bernoulli distribution by calculating the probability of detection for each individual using a truncated half-normal detection function specified as $p_{i}=e^{-\left(\frac{d_{i}}{0.025}\right)^{2}}I(d_{i}<0.06),$ where $p_{i}$ is the probability of detection for the $i^{\text{th}}$ individual that occurs at a distance $d_{i}$ from the point transect (Fig. 1). We simulated 250 data sets for each scenario and fit four models to each data set. For the first model, we used the exact locations of the individuals and fit Eq. 3 to the simulated data. This is the ideal situation because the generating process used to simulate the data matches the generating process specified by the statistical model. Thus, we expected unbiased parameter estimates with the narrowest CIs under model 1. For the second and third models, the ``available'' data included only the distances from the point transects to the locations of the detected individuals. Because the exact locations of the individuals were unavailable, we fit Eq. 3 using two different surrogate predictors which included: 1) the value of $x(\mathbf{s})$ at the point transect where the individual was detected (model 2); and 2) the average of $x(\mathbf{s})$ within a distance of $0.06$ of the transect where the individual was detected (model 3). The distance of $0.06$ distance was chosen to correspond to the value used to truncate the half-normal detection function, which would be unknown in practice. Finally, our fourth model uses the same data as the second and third model, but instead accounts for location uncertainty using Eq. 4. For each of the two scenarios and four models, we assessed reliability of the inferred species-habitat relationship by comparing the true values of $\beta_{1}$ to the estimated value and the coverage probability of the 95\% CIs. We assessed efficiency by calculating the average length of the 95\% CI for $\hat{\beta}_{1}$ that was obtained from the model that accounts for location uncertainty (i.e., model 4) divided by the average length of the 95\% CI for $\hat{\beta}_{1}$ obtained from fitting the IPPP distribution using data with exact locations (i.e., model 1). In Appendix S2, we provide a tutorial with R code to implement the simulation and reproduce Fig. 1 and table 1 .\vspace{0.66cm} \begin{spacing}{1.9} \subsection*{FIELD-COLLECTED AVIAN DATA} \end{spacing} \noindent Distance sampling data from 137 bird species were collected over a 29 year period from 1981 to 2009 as part of the Long Term Ecological Research Program at the Konza Prairie Biological Station (KPBS; Fig. 2). The KPBS is a tallgrass prairie site located in northeastern Kansas, USA and is experimentally managed under varied grazing and fire regimes (\citealt{knapp1998grassland}). We used data from a single species, Dickcissels (\textit{Spiza americana}), which are the most common grassland-breeding species at KPBS. Both male and female Dickcissels perch conspicuously from the tops of vegetation and males vocalize frequently (\citealt{temple2002}). For our analysis, we used observations of Dickcissels collected by a single observer over the period of May 27, 1981 to June 26, 1981. This resulted in 106 individuals detected on 11 of the 14 transects at perpendicular distances ranging from $0\,\text{m}$ to $61\,\text{m}$. A full description of the data is provided in \citet{zimmerman1993birds} and \citet{KONZADATA}. We illustrate our method using elevation as a predictor variable (Fig. 2). Elevation within the KPBS is available from a digital elevation model that has cell resolution of $2\,\text{m}\times2\,\text{m}$ (\citealt{KONZAElev}). Based on previous research, we expect the abundance of Dickcissels should be greater at higher elevations when compared to lower elevations (\citealt{zimmerman1993birds}). Given our distance sampling data, it is not possible to reconstruct the exact location of each detected individual, therefore, we are unable to obtain the elevation at the location of each detected Dickcissel. We implement four models that included: a) the standard distance sampling model (Eq. 3) using a surrogate predictor which was the average elevation along the transect where the individual was detected (model a); b) a model that accounts for location uncertainty assuming that distances are recorded without error (i.e., Eq. 4; model b); c) a model that accounts for location uncertainty and distance mismeasurement that follows a truncated normal distribution (model c); and d) a model that accounts for location uncertainty distance mismeasurement that follows a Laplace distribution. For models c and d, which accounted for error in the recorded distances, we assumed that variance of the normal and Laplace distributions was zero on the transect line, but increased linearly at an unknown rate as the distance between the individual bird and transect increased (see Fig 3c. for an example). We truncated the normal and Laplace distributions at distances below $0\,\text{m}$ and above $150\,\text{m}$ to increase computational efficiency of the quadrature approximation. Because the maximum recorded distance in our data set was $61\,\text{m}$, this truncation has negligible influence on our results. Depending on the specifics of the study design, it is easy to incorporate different specifications such as a constant variance model or alternative probability distributions (e.g., a Poisson distribution for distances that are rounded to the nearest meter). In Appendix S3, we include additional details associated with the field-collected avian data analysis along with a tutorial and R code to implement the models and reproduce Table 2 and Figs. 2 and 3.\vspace{0.66cm} \section*{Results} \subsection*{SIMULATION EXPERIMENT} When the exact location of each detected individual was available, the standard IPPP model in Eq. 3 (model 1) performed as expected in that estimates of $\beta_{1}$ appeared to be unbiased and 95\% CI covered the true value with probabilities between 0.93\textendash 0.96 (Fig 1; Table 1). In contrast, when location uncertainty was not accounted for (models 2 and 3), the estimated regression coefficients were biased (Fig. 1) and coverage probabilities of the 95\% CIs were $\leq0.38$ (Table 1). When the transect locations were placed based on convenience and the surrogate predictor variable was obtained from the center of the transect (model 2), the bias was particularly large and resulted in negative estimates of regression coefficients for most data sets even though the true value was $\beta_{1}=1$ (Fig. 1a). Our method (model 4), which accounted for location uncertainty, yielded apparently unbiased estimates of $\text{\ensuremath{\beta_{1}}}$ for both scenarios and produced coverage probabilities between $0.95$\textendash $0.98$ (Fig. 1; Table 1). The 95\% CI were $1.49$\textendash $1.50$ times longer when the exact location was unknown (Table 1). These results demonstrate that our proposed method efficiently accounted for location uncertainty and resulted in parameter estimates that are about 50\% less precise than parameter estimates obtained when the exact location is known. This shows that the loss of information resulting from location uncertainty could be ameliorated by collecting more data.\vspace{0.66cm} \begin{spacing}{1.9} \subsection*{FIELD-COLLECTED AVIAN DATA} \end{spacing} All three models that accounted for location uncertainty (models b\textendash d) had similar Akaike information criterion scores that were $>811$ points lower than model a, which used Eq. 3 and the average elevation along the transect as the predictor (Table 1). This indicates that accounting for location uncertainty improved the fit of the model to the data. Predicted Dickcissels abundance at higher elevations was greater when location uncertainty was accounted for in models b\textendash d (Table 2; Figure 3a). This difference in predictions was caused by the regression coefficient estimates, which were 27\% larger for the three models that accounted for location uncertainty (models b\textendash d) when compared to the model that used the surrogate predictor (model a; Table 2).\textcolor{black}{{} The model comparison of the estimated relationship between elevation and abundance, distance and the probability of detection, and the true distance and recorded distance are visualized in Fig. 3.} \section*{Discussion} This study demonstrates that location uncertainty, when unaccounted for, can result in biased parameter estimates and unreliable inference regarding species-habitat relationships. Within a broader context, location uncertainty manifests as an ecological fallacy namely that the inferred relationship from aggregated data could differ when compared to individual-level data (\citealp{ecologicalfallacy,cressie2011statistics}, p. 197). Point process models using exact locations of individuals targets inference about the habitat and environmental preferences of individuals whereas ignoring location uncertainty and using transect-wide surrogate predictors results only in inference about how abundance varies among the transects. Individual-level inference is invariant to changes in the spatial scale of the analysis, whereas transect-level inference is scale specific. Our study demonstrates that spatial model-based approaches for traditional distance sampling data can provide reliable individual-level inference, even when the exact locations of individuals are unknown. This is a significant advancement because our approach enables individual-level inference, but does not require auxiliary data that may difficult or impossible to obtain for historical data sets (e.g., \citealt{borchers2015unifying}). Our approach also offers insight into best practices for future distance sampling study design when recording the exact location of individuals may be difficult or infeasible. Our simulation results suggest that, given a desired statistical power or level of precisions for parameter estimates, there is a tradeoff between sample size (i.e., the number of detected individuals) and location accuracy. The deleterious effects of collecting distance sampling data without recording the exact location can be remediated by simply collecting more data and selecting an appropriate model. For example, in both scenarios of our simulation experiment, the same precision of parameter estimates can be achieved by either detecting $n$ individuals and recording their exact locations, or by detecting $\approx1.5n$ individuals and recording only their distances. Although the sample size calculations from our simulation results are not generalizable to future data collection efforts, study-specific power analyses could be conducted to determine the tradeoff between the two data collection approaches. \vspace{0.66cm} \begin{spacing}{1.9} \subsection*{PRACTICAL GUIDANCE FOR DATA ANALYSIS} \end{spacing} \noindent Location uncertainty is ubiquitous in all sources of spatially referenced data because it is impossible to measure and record the location with infinite precision. Despite the presence of location uncertainty in all sources of data, accounting for it may be time consuming because the models are tailored to the specifics of the study and usually must be fit using ``custom built'' computer code (\citealt{BB2L}). For some data sets accounting for location uncertainty will be required and in other data sets it may not be possible or beneficial. Prior to fitting models to distance sampling data, we urge researchers consider the seven questions below to determine possible impact of location uncertainty on study outcomes. \begin{enumerate} \item \textit{Does the predictor variable exhibit fine-scale spatial variability?} If so, the predictor variable is likely to change when moving a short distance from one location to another location. In this case, the surrogate predictor variable (e.g., elevation at the transect centroid) will likely differ from the predictor variable at the location of the individuals. Whenever the surrogate predictor variable included in a model is different from the value of the predictor at the exact locations, there is the potential for bias. The larger the difference between the value of the surrogate variable and the value at the exact location, the more important it will be to account for location uncertainty. \item \textit{Are the placement of the transects related to the spatial structure of the predictor variable?} For example, the transects may be placed along roads within larger areas of homogeneous habitat. In this case, a surrogate predictor such as the percentage of grassland within $100\,\text{m}$, may be strongly influenced by the location of the transects and creates a potential for bias to occur. Accounting for location uncertainty may be needed. \item \textit{Are the spatial scales of the predictor variables known?} In many cases environmental characteristics within an area surrounding the location of the individuals is used to determine the influence of landscape-level processes (e.g., percentage of grassland within $100\,\text{m}$). These approaches use a buffer or kernel that is typically centered at the exact location of the individual. The predictor variable is calculated by integrating the kernel and point-level predictor variable over the study area (e.g., \citealt{heaton2011kernel,heaton2011spatial,heaton2012kernel,bradter2013identifying,chandler2016estimating,miguet2017quantify,stuber2017bayesian}). Because the buffer or kernel is centered at the exact location of the individuals, accounting for location uncertainty is likely to influence the inference. \item \textit{Is the spatial resolution of the predictor variables too course?} In some situation the spatial resolution of the predictor variable will only be available at a course grain. For example, WorldClim provides a set of climate variables that are predictions available on a $1\times1\,\text{km}$ grid (\citealt{hijmans2005very}). The transect from our data example are all $\leq1589\,\text{m}$ in length. For a given transect, most detected individuals would be assigned the same value of the predictor variables from WorldClim because most of the individual birds occur within a single $1\times1\,\text{km}$ grid cell. If the goal of the study is to relate abundance to climatic variables using WorldClim, then in such a case, the researcher would experience minimal or no gain from accounting for location uncertainty. \item \textit{Are spatial data for the predictor variables available over the entire study area?} In some situations the predictor variables will not be available at every location within the study area. For example, many studies that collect distance sampling data on animals also collect detailed information on vegetation at a feasible number of locations within the study area. It is tempting to use vegetation measurements as predictor variables that are collected at the location that is thought to be closest to the individual animal. This approach presents two challenges: 1) if the vegetation at the location of the individual is different than the location where the measurements were taken, the predictor variables may result in biased coefficient estimates; and 2) fitting point process models to data requires a continuous surface of the predictor variable over the entire study area. In this situation, we recommend first building a statistical model that can predict the vegetation measurements as a continuous surface over the study area. This is equivalent to building a custom high-resolution ``raster layer'' using the the vegetation data. Developing auxiliary models for predictor variables that are measured in the field is a common technique used in spatial statistics to ameliorate the problem of misaligned data (\citealt{gotway2002combining,gelfand2010misaligned}; \citeauthor{Pacifici2019} \textit{in press}). Once the predictor variable is available as a continuous surface or high resolution raster layer, then accounting for location uncertainty is likely to be beneficial. \item \textit{Is the location uncertain for only a portion of the observations?} There may be situations were only a portion of the observations have uncertain locations (e.g., \citealt{hefley2014correction,hefley2017bias}). If the number of observations with uncertain locations is small (e.g., $<5\%$ of the observation), these could be removed from the data set and perhaps cause only minor changes in inference. If the number of observations with uncertain locations is larger, then we recommend constructing models that integrate both sources of data (e.g., by combining portions of the likelihood in Eq. 3 and Eq. 4). Similar approaches could be applied to situations where different sources of data result in the magnitude of the location uncertainty being variable. For example, the mismeasurement of distances in our historic Dickcissel distance sample data are likely to be larger than more recent surveys in the same data set because researchers adopted the use of laser rangefinders. \item \textit{Do the predictor variables contain errors?} In some situations, the predictor variables contain errors. For example, researchers may include modeled climatic predictor variables, but the predicted climate at any given location is different than the true conditions. In this situation, the error in the predictors may mask or exacerbate the effect of location uncertainty. This problem is well-studied in the statistics literature where it is known as ``errors-in-variables'' (\citealt{carroll2006measurement}). In addition to location uncertainty, errors-in-variables can be accounted for by using a hierarchical modeling framework (e.g. \citealt{foster2012uncertainty,stoklosa2015climate,hefleyHSDM}).\vspace{0.66cm} \end{enumerate} \begin{spacing}{1.9} \subsection*{CONCLUSION} \end{spacing} \noindent Ecological data are messy in ways that result in many potential biases. For example, failing to account for detection may result in biased estimates of abundance. Ecologists have focused intensively on some sources of bias (e.g., detection) while paying little attention to other sources of bias such as location uncertainty. Thus, there is a shortage of tools available for less studied sources of bias, leading researchers to rely on ad hoc and untested procedures. We recommend avoiding untested procedures because location uncertainty can create complex biases that are difficult to anticipate and understand (e.g., \citealp{montgomery2011implications,hefley2014correction,brost2015animal,mitchell2016sensitivity,hefley2017bias,gerber2018accounting,walker2018bias}; \citeauthor{walker2019bias} \textit{under revision}). Model-based approaches have provided a wealth of tools to address biases in many types of ecological data. In situation where location uncertainty is a concern, model-based approaches like those proposed in our study will enable researchers to make reliable ecological inference and accurate predictions. \noindent \vspace{0.66cm} \section*{Acknowledgements} We thank all individuals, including Elmer Finck, John Zimmerman, and Brett Sandercock, who contributed to the the distance sampling data used in our study. The material in this study is based upon research supported by the National Science Foundation (DEB-1754491 and DEB-1440484 under the LTER program).\vspace{0.66cm} \section*{Data accessibility} The field-collected avian data is available from \citet{KONZADATA}. Additional files required to reproduce the results of this study (e.g. shapefiles of transects) are archived in the Dryad Digital Repository (\citealt{hefley2019dryaddata}). \renewcommand{\refname}{\vspace{0.1cm}\hspace{-0cm}\selectfont\large References}\setlength{\bibsep}{0pt} \bibliographystyle{apa}
{'timestamp': '2020-06-01T02:03:58', 'yymm': '2005', 'arxiv_id': '2005.14316', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14316'}
arxiv
\section{Introduction} \label{sec:intro} Several prior works for depth estimation from monocular images doesn't work with raw images straight out of the camera, which would be distorted and unrectified. Instead, these raw images are corrected with image processing techniques before being fed into the network to predict an undistorted rectified depth map. We propose a novel fully differentiable architecture which allows estimating the distorted unrectified depth directly from a raw image without the need for any pre-processing techniques to correct the image. This pipeline in turn saves time and computation power, and can be used directly in real-time scenarios without any prerequisites. The parameters which define distortion vary slightly with the environment in which the camera is present. Our model exploits the fact that more or less the amount of distortion in an image is fixed as long as we use the same camera. This allows us to pre-define a transformation flowfield for undistorting the image and using it in the training pipeline. Image rectification on-the-fly with prerecorded camera parameters has an overhead of around 75msec for a typical 30 FPS (frames per second) camera in one second. Our proposed model for unrectified distorted images doesn't have any overhead at inference when compared to models based on rectified images as it uses a neural network with the same number of trainable parameters. Image rectification also leads to information loss from the raw image. Higher the camera distortion, the higher the loss of pixel information from the raw data. In the KITTI dataset due to the distortion effect of the camera, the images have been rectified and cropped to 1242 $\times$ 375 such that the size of the rectified undistorted images is smaller than the raw unrectified distorted image size of 1392 $\times$ 512 pixels. Image rectification in KITTI resulted in the pixel loss of 10.77\% and 27.34\% along the width and height of the image, respectively. This pixel loss becomes more prominent at higher resolutions. We address the above issues by proposing the following contributions: \begin{figure} \centering \resizebox{0.5\textwidth}{!}{ \input{fig/att_map/att_map.tex}} \caption{Visualization of self-attention map. Left: Shows Query locations marked with a red dot on the unrectified input image. Right: Attention map for those query locations overlayed on the unrectified input image with arrows summarizing most-attended regions. Rather than attending to spatially adjacent pixels, the proposed network learns to attended pixels with similar color and texture. } \label{fig:att} \end{figure} \begin{enumerate} \itemsep -0.5em \item Introduced an end to end fully differentiable novel pipeline to tackle monocular depth estimation on distorted and unrectified images. \item Proposed a novel self-attention depth network to handle long range dependencies in the feature map leading to sharper depth maps. \item Incorporated instance normalisation throughout model architecture to handle style variation in the input data. \end{enumerate} Some of the prior self-supervised monocular depth estimation works are briefed here. Zhou \textit{et al}., \cite{zhou2017unsupervised} proposed an unsupervised depth estimation end-to-end framework from video sequence where view synthesis act as the supervisory signal. Mahjourian \textit{et al}., \cite{mahjourian2018unsupervised} introduced a 3D loss to enforce consistency of the estimated 3D point cloud. Yin \textit{et al}., \cite{yin2018geonet} jointly learned monocular depth, optical flow and ego motion from videos in unsupervised manner. Luo \textit{et al}., \cite{luo2018every} also jointly learned monocular depth, optical flow and ego motion from video but used these result to produce motion mask, occlusion mask, 3D motion map for rigid background and dynamic objects. Godard \textit{et al}., \cite{godard2019digging} achieved state of the art results in KITTI rectified dataset with minimum reprojection loss, full-resolution mutli-scale sampling and a mask that ignores training pixels that violate camera motion assumptions. \setlength{\belowcaptionskip}{-1pt} \begin{figure*}[ht] \centering \begin{subfigure}{.45\textwidth} \centering \includegraphics[width=1\linewidth]{fig/att/att_encoderv3.pdf} \caption{} \label{fig:input} \end{subfigure} \begin{subfigure}{.45\textwidth} \centering \includegraphics[width=1\linewidth]{fig/att/att_blockv2.pdf} \caption{} \label{fig:output} \end{subfigure} \caption{(a) Proposed self-attention depth estimation network. (b) Self-attention block. $\bigotimes$ denote matrix multiplication.} \label{fig:net} \end{figure*} \section{Synthesis of unrectified image} All the prior works on monocular depth estimation have used rectified images during training to estimate depth. But the raw images from camera are unrectified images; henceforth we enable an efficient way to train the depth estimation network on unrectified images. Rectification is required on images like stereo pairs to rectify the error in rotation and translation between cameras. Image distortion is prevalent in images caused by varying magnification in relation to the angular distance to the optical axis. Due to the imperfect alignment of the lens or sensor, distortion may get decentered, but that is rarely an issue in current cameras. Usually, these images are fixed beforehand, as it would affect the projection geometry from one view to another. Distortion of a typical $90^\circ$ FOV (field of view) camera can be modeled with few intrinsic parameters where $k_1,k_2,k_3,p_1,p_2$ are the known distortion parameters. We can obtain the undistorted image coordinate $\hat{c}_{t-1}^{undist}$ at time $t-1$ from distorted image coordinate $c^{dist}_{t}$ at time $t$ by Equ.~\ref{eq:1}. \begin{align} \label{eq:1} \hat{c}_{t-1}^{undist} \approx \mathbf{K} \mathbf{T}_{t \rightarrow t-1}D_{t}\mathbf{K}^{-1}\xi\{c^{dist}_{t}\} \end{align} where $\mathbf{K}$ is the camera intrinsic $3 \times 3$ matrix that transforms camera coordinates to image coordinates which comprises of focal length $f_x, f_y$, principal point offset $x_0, y_0$ along x and y directions and axis skew $s$ as shown in Equ.~\ref{eq:2}, $\mathbf{T}_{t \rightarrow t-1}$ camera transformation $3 \times 4$ matrix from target view frame at $t$ to source view frame at $t-1$ consisting of $3 \times 3$ rotation matrix $\mathbf{R}$ and $3 \times 1$ translation vector $\mathbf{t}$ as shown in Equ.~\ref{eq:3}, $D_t$ is the per-pixel depth predicted by the network and $\xi$ is the undistortion function with pre-computed distortion parameters. \begin{align} \label{eq:2} \mathbf{K} = \left[ \begin{array}{ccc} f_x & s & x_0\\ 0 & f_y & y_0\\ 0 & 0 & 1 \end{array} \right] \end{align} \begin{align} \label{eq:3} \mathbf{T} = [ \mathbf{R} \, |\, \mathbf{t}] = \left[ \begin{array}{ccc|c} r_{1,1} & r_{1,2} & r_{1,3} & t_1 \\ r_{2,1} & r_{2,2} & r_{2,3} & t_2 \\ r_{3,1} & r_{3,2} & r_{3,3} & t_3 \end{array} \right] \end{align} Per-pixel depth $D_t$ of frame at time $t$ and camera transformation $\mathbf{T}_{t \rightarrow t-1}$ from frame at time $t$ to $t-1$ are estimated by self-attention depth and pose network, respectively as shown in Fig.~\ref{fig:net}. Pose network \cite{zhou2017unsupervised} takes three adjacent distorted image frames at time $t-1$, $t$, $t+1$ and predicts camera transformation $\mathbf{T}_{t \rightarrow t-1}$ and $\mathbf{T}_{t \rightarrow t+1}$. While self-attention depth network takes single distorted image frame $I^{dist}_{t}$ at time $t$ to predict per-pixel depth $D_t$. During inference, only self-attention depth network is used to predict depthmap of an input image. \subsection{Image coordinates to World coordinates} \label{sec:2.1} With intrinsic matrix $\mathbf{K}$, estimated depth $D_t$ and undistortion function $\xi$, we can project distorted image coordinates to world coordinates as shown in Equ.~\ref{eq:4}. \begin{align} \label{eq:4} \left[\begin{array}{c} X \\ Y \\ Z \end{array}\right] \approx D_{t}\mathbf{K}^{-1}\xi \Bigg\{ \left[\begin{array}{c} x^{dist}_t \\ y^{dist}_t \\ 1 \end{array}\right]\Bigg\} \end{align} where $(x^{dist}_t, y^{dist}_t)$ is unrectified image coordinates and $(X, Y, Z)$ is world coordinates. Undistortion function $\xi$ is used to pre-compute undistortion map which is used in the training pipeline as shown in Equ.~\ref{eq:5}. \begin{align} \label{eq:5} \left[\begin{array}{c} x^{undist}_t \\ y^{undist}_t \\ \end{array}\right] \approx \xi \Bigg\{ \left[\begin{array}{c} x^{dist}_t \\ y^{dist}_t \\ \end{array}\right]\Bigg\} \end{align} The mathematical formulation of radial and tangential distortions used in the undistortion function $\xi$ are shown below in Equ.~\ref{eq:6} and Equ.~\ref{eq:7} \begin{align} \label{eq:6} \begin{gathered} \hat{x}^{dist}_t \approx x^{undist}_t(1+k_1r^2+k_2r^4+k_3r^6) \\ \hat{y}^{dist}_t \approx y^{undist}_t(1+k_1r^2+k_2r^4+k_3r^6) \end{gathered} \end{align} Here $x^{undist}_t$ and $y^{undist}_t$ denotes undistorted pixel coordinates, $\hat{x}^{dist}_t$, $\hat{y}^{dist}_t$ denotes radially distorted pixel coordinates and $r^2={x^{undist}_t}^2+{x^{undist}_t}^2$. Tangential distortion caused by lens misalignment can be formulated with distortion parameters $p_1$ and $p_2$ along with radial distortion as shown in Equ.~\ref{eq:7}. \begin{align} \label{eq:7} \begin{gathered} x^{dist}_t \approx \hat{x}^{dist}_t + 2p_1x^{undist}_ty^{undist}_t + p_2(r^2+2{x^{undist}_t}^2) \\ y^{dist}_t \approx \hat{y}^{dist}_t + p_1(r^2+{y^{undist}_t}^2) + 2p_2x^{undist}_ty^{undist}_t \end{gathered} \end{align} $x^{dist}_t$ and $y^{dist}_t$ are resultant image coordinate after radial and tangential distortion. Distortion mapping in Equ.\ref{eq:5} is used to inverse map distorted image coordinates to undistorted image coordinates. These undistorted image coordinates can be projected to world coordinates by dot operation with inverse camera intrinsic $\mathbf{K}^{-1}$ and estimated per-pixel depth $D_t$ as shown in Equ.~\ref{eq:8}. \begin{align} \label{eq:8} \left[\begin{array}{c} X \\ Y \\ Z \end{array}\right] \approx D_{t}\mathbf{K}^{-1} \left[\begin{array}{c} x^{undist}_t \\ y^{undist}_t \\ 1 \end{array}\right] \end{align} \subsection{World coordinates to Image coordinates} \label{sec:2.2} The estimated transformation matrix $\mathbf{T}_{t \rightarrow t-1}$ from image frame at time $t$ to $t-1$ along with intrinsic matrix $\mathbf{K}$ is used to transform world coordinates to image coordinates of frame at time $t-1$ as shown in Equ.~\ref{eq:9}. \begin{align} \label{eq:9} \left[\begin{array}{c} x^{undist}_{t-1} \\ y^{undist}_{t-1} \\ 1 \end{array}\right] = \left[\begin{array}{c} x/z \\ y/z \\ 1 \end{array}\right] \equiv \left[\begin{array}{c} x \\ y \\ z \end{array}\right] \approx \mathbf{K}T_{t \rightarrow t-1} \left[\begin{array}{c} X \\ Y \\ Z \\ 1 \end{array}\right] \end{align} \subsection{View Synthesis} The image coordinate projection from frame $t$ to $t-1$ as discussed in subsection \ref{sec:2.1} and \ref{sec:2.2} can only project distorted image coordinates at $t$ frame to $t-1$ unrectified image coordinates as shown in Equ.~\ref{eq:1}. For view synthesis, we propose a trick with image undistortion function $\varphi$ using the pre-computed distortion map to undistort the source image $I^{dist}_{t-1}$ at t-1 as shown in Equ.~\ref{eq:10}. It should be noted that this undistortion operation is performed only in the training phase. \begin{align} \label{eq:10} I^{undist}_{t-1} = \varphi \{ I^{dist}_{t-1} \} \end{align} This unrectified image $I^{undist}_{t-1}$ can be used to sample pixel values according to projected image unrectified coordinates $x^{undist}_{t-1}, y^{undist}_{t-1}$ to synthesize unrectified image $\hat{I}^{dist}_{t}$ at time $t$ as shown in Equ.~\ref{eq:11}. $\big \langle \big \rangle$ is the bilinear sampler. For simplicity, synthesis of distorted image $\hat{I}^{dist}_{t}$ at time $t$ from distorted image $I^{dist}_{t-1}$ at time $t-1$ is shown. But the proposed method synthesis $I^{dist}_{t}$ from images $I^{dist}_{t+1}$ at time $t+1$ too. \begin{align} \label{eq:11} \hat{I}^{dist}_{t} = I^{undist}_{t-1} \big \langle x^{undist}_{t-1}, y^{undist}_{t-1} \big \rangle \end{align} \section{Reconstruction loss} The depth network takes one distorted unrectified image $I^{dist}_{t}$ at time $t$ to reconstruct $\hat{I}^{dist}_{t}$ by inverse wrapping nearby distorted views $I^{dist}_{t-1}$ and $I^{dist}_{t+1}$ with estimated depth $D_{t}$. The reconstruction loss $L^s$ at scale $s$ of our network consist of two parts, photometric loss $L_{p}$ and smoothness loss $L_s$. We follow \cite{godard2017unsupervised} in using mixture of L1 and SSIM $S(.)$ with $\alpha_1=0.85$ and $\alpha_2=0.15$ for the reconstruction loss for supervising the networks as shown in Equ.~\ref{eq:12}. \begin{align} \label{eq:12} L_{p}^{t-1} = \eta_{t-1}\Bigg(\alpha_1 \frac{1-S(I_t^{dist},\hat{I}_{t}^{dist})}{2} + \alpha_2 |I_t^{dist}-\hat{I}_{t}^{dist}|\Bigg) \end{align} Here $\eta_{t-1}$ stands for auto mask \cite{godard2019digging} which is used to mask out the pixels which do not change across time steps. This mask allows to remove static objets like a car moving at same speed as the camera and far away objects like sky, since they don't contribute of the loss. We also use an edge-aware smoothness loss is as shown in Equ.~\ref{eq:13}. \begin{align} \label{eq:13} L_{s}^{t-1} = |\bigtriangledown_u D_{t}| e^{-|\bigtriangledown_u I_{t}^{dist}|} + |\bigtriangledown_v D_{t}| e^{-|\bigtriangledown_v I_{t}^{dist}|} \end{align} \begin{table*}[t] \vspace{2mm} \centering \resizebox{\textwidth}{!}{ \begin{tabular}{l|c|cccc|ccc} Approach & Input &\multicolumn{4}{c|}{Lower is better} & \multicolumn{3}{c}{Higher is better}\\ \cline{3-9} & & Abs Rel & Sq Rel & RMSE & RMSE log & $\delta < 1.25$ & $\delta < 1.25^2$ & $\delta < 1.25^3$ \\ \hline Zhou~\cite{zhou2018unsupervised} & rectified & 0.176 & 1.532 & 6.129 & 0.244 & 0.758 & 0.921 & 0.971 \\ Mahjourian~\cite{mahjourian2018unsupervised} & rectified & 0.134 & 0.983 & 5.501 & 0.203 & 0.827 & 0.921 & 0.981 \\ GeoNet~\cite{yin2018geonet} & rectified & 0.132 & 0.994 & 5.240 & 0.193 & 0.833 & 0.953 & 0.985 \\ EPC++~\cite{luo2018every} & rectified & 0.120 & 0.789 & 4.755 & 0.177 & 0.856 & 0.961 & 0.987 \\ Monodepth2~\cite{godard2019digging} & rectified & 0.090 & 0.545 & 3.942 & 0.137 & 0.914 & 0.983 & 0.995 \\ \hline Our (resnet18 w/o attention) & unrectified & 0.1481 & 1.2579 & 5.805 & 0.221 & 0.817 & 0.941 & 0.978 \\ Our (resnet50 w/o attention) & unrectified & 0.1254 & 1.0812 & 5.407 & 0.197 & 0.866 & 0.956 & 0.983 \\ \hline Our (resnet18 w/ attention BN) & unrectified & 0.1305 & 1.0462 & 5.501 & 0.195 & 0.838 & 0.95 & 0.983 \\ Our (resnet50 w/ attention BN) & unrectified & 0.1158 & 0.7714 & 4.865 & 0.175 & 0.861 & 0.961 & 0.988 \\ \hline Our (resnet18 w/ attention IN) & unrectified & 0.1253 & 0.9420 & 5.367 & 0.187 & 0.846 & 0.954 & 0.985 \\ Our (resnet50 w/ attention IN) & unrectified & 0.1067 & 0.6866 & 4.585 & 0.163 & 0.879 & 0.968 & 0.991 \\ \end{tabular} } \caption{Qualitative result comparison on KITTI improved ground truth eigen split. All state of the art methods predict depth from rectified distorted image unlike the proposed method that predict depth capped at 80m from unrectified distorted image. BN: Batch normalization and IN: Instance normalization.} \label{tab:qual} \end{table*} \begin{figure*}[!ht] \centering \resizebox{\textwidth}{!}{ \input{fig/quali/qual.tex}} \caption{Qualitative result comparison on KITTI unsynced+unrectified dataset. Figure best viewed in color.} \label{fig:qual} \end{figure*} \section{Self-Attention network} Most of the depth estimation networks like \cite{godard2019digging},\cite{garg2016unsupervised} use convolutions for capturing the local information. But it is well known fact that receptive field of convolutions is quite small. Inspired by \cite{zhang2018self}, we introduce self-attention at different stages within our Resnet encoder \cite{he2016deep} of the depth estimation network to handled long range relations. This enables us to incorporate the contextual information into the high dimensional feature maps. This particularly constrains the network to produce more robust feature maps which result in much improved depth estimation.To the best of knowledge our architecture is the first to incorporate contextual information at different layers of the network for the purpose of unsupervised depth estimation. As a proof of our contribution we visualize attention maps of few samples in Fig.~\ref{fig:att}. We can observe how the network learns to attend pixels belonging to the same attribute or texture for a particular query pixel. \section{Handling variation in style} We believe that major issue in training such models is the high variation in style of the input images which makes it difficult for the model from reaching its best potential. Therefore taking inspiration from \cite{huang2017arbitrary} we normalise feature maps after each convolutional layer. This trivial procedure particularly normalises style of every training image and thus facilitates better training as the model discards the style information and focuses only on the content information to infer depth. \section{Experiments and results} We use the KITTI raw (unsynced+unrectified) dataset \cite{geiger2013vision} for training. We extracted 652 of the 697 eigen test split to evaluate unrectified depth with improved KITTI groundtruth depth maps on which all our qualitative results are done, as shown in Table~\ref{tab:qual}. Our proposed depth estimation method is evaluated using metrics in \cite{eigen2014depth} for a fair comparison with other state of the art methods for rectified images. Note that as there is no previous benchmark for depth estimation on unrectified images, we compare our results with those of rectified images. For evaluating predicted unrectified depthmap, we undistort the unrectified depth map and compare it to the rectified ground truth. The main limitation of proposed method is the transferability to other dataset captured with a different camera. As distortion varies from one camera to another, direct transfer learning would be difficult, but fine-tuning is the best way until and unless the projection doesn't break. The projection used in the propose method will fail with extreme distortion like wide-angle lens. \section{Conclusion} We proposed a novel self-attention network for learning monocular depth from unrectified video frames. Our attention framework is able to capture long distance contextual information which results in much sharper depth maps. We also handle style variance in the training distribution by using instance normalisation. Finally, we evaluated the unrectified depth estimation against state of the art methods on rectified depth estimation and achieved comparable results.
{'timestamp': '2020-06-01T02:03:53', 'yymm': '2005', 'arxiv_id': '2005.14313', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14313'}
arxiv
\section{Introduction} Judging similarity between any pair of stimuli is an ambiguous problem: deciding what counts as similar is subjective and sensitive to context \cite{Medin1993}. Nevertheless, people are relatively consistent in making similarity judgments, which is perhaps explained in part by the biases they develop towards emphasizing some stimulus features over others (\textit{e.g.,} shape over size, color, or material; \citeNP{Diesendruck2003}). Understanding the features (and the weights upon them) that people employ when evaluating the similarity of complex stimuli like images remains an open problem. Deep neural networks have been demonstrated to be predictive of multiple aspects of human visual perception in visuoperceptual tasks \cite<\textit{e.g.,}>{Lake2015,Kubilius2016}. This utility has led to their increasing use as proxies of human cognition to understand mechanisms underlying cognitive processes or as proofs-of-concept to establish the possibility of a certain cognitive strategy \cite{Kriegeskorte2015, Cichy2019}. For example, \citeA{Sanders2020} show that CNNs can be trained using multidimensional scaling representations to derive psychological representations of images. In other work, \citeA{Peterson2017} show correspondences between similarities in convolutional neural net (CNN) representations and human similarity judgments for natural images. They find that, while out-of-the-box CNN representations are only partially reflective of human psychological representations, they can be adapted to support a more fine-grained correspondence. The success of CNNs in predicting human similarity judgments suggests that they might also be helpful in identifying the features which inform those judgments. However, CNN representations are high-dimensional, potentially redundant, and likely include psychologically irrelevant stimulus information. An important question, given their increasing use in cognitive modeling is how many relevant features/dimensions they really contribute and what the nature of those features might be. In this work, we propose a method inspired by previous work by \citeA{Rumelhart1993} which we call similarity-driven dimensionality reduction (SimDR), which obtains low-dimensional projections of CNN image representations that best capture human similarity judgments. Surprisingly, our method reveals that human similarity judgments continue to be well-preserved even up to two orders of magnitude fewer dimensions than previous work. This suggests that the dimensionality of psychological representations is considerably less than the full set of CNN features. We further probe the individual dimensions of these representations that capture concepts essential to judging similarity, and find that most of them are interpretable. In particular, we show that broad categories are given more importance by our model than finer ones captured in subsequent dimensions, in line with the hierarchical structure oft-found to characterize human cognition \cite{Cohen2000, Rogers2004SemanticCA}. \section{Method} \citeA{Peterson2017} show that the final representation layer of a CNN can be adapted to better predict human similarity judgments. The size of the final representation in CNNs is typically of the order of $10^3$, which makes interpretation difficult. To serve our purpose of leveraging CNN representations to understand human similarity judgments, we require representations that are interpretable and can give us insights into the actual cognitive task. \citeA{Rumelhart1993} constructed a connectionist model to mimic human similarity judgments. The model takes two stimuli as input and outputs a similarity judgment. The hidden layer is of lower dimensionality than the input, resulting in a compressed representation. Extending this idea to modern CNNs, our method (SimDR) reduces the CNN representations of images to a low-dimensional space which is optimal for predicting human similarity judgments. If the obtained representations have sufficiently low dimensionality, we can interpret individual dimensions to see what they capture and make inferences about similarity judgments in humans. This model and the data used are explained in the following sections. \subsection{Datasets} \citeA{Peterson2017} collected six human similarity datasets for natural images drawn from the following domains: animals, vehicles, vegetables, fruits, furniture and a dataset encompassing a variety of domains (``various''). Each of these sets comprises pairwise similarity ratings from ten people for 120 images, which we employ in all analyses that follow. \subsection{Similarity-driven Dimensionality Reduction} \citeA{Peterson2017} showed that the final, fully-connected representation layer of VGG-19 \cite{Simonyan15} is most predictive of human similarity judgments, hence we use the same 4096-dimensional VGG-19 representations for all our experiments. The task of obtaining low-dimensional representations of images which capture factors underlying human similarity judgments is split by SimDR into two objectives: (a) projecting VGG-19 representations to a low-dimensional space, and (b) predicting human similarity judgments using the low-dimensional representations. These two objectives are jointly optimized leading to low-dimensional representations that are predictive of human similarity judgments. VGG-19 representations of two input images are passed through a single linear layer of small width (\textit{i.e.,} a bottleneck layer) which projects them to a lower-dimensional space. This is followed by an inner product of the outputs of the bottleneck layer to obtain the predicted similarity rating for the input pair (Fig.~\ref{fig::model_diag}). The inner product is our representational similarity measure, which contrasts with \citeA{Rumelhart1993}, and more directly generalizes the method of \citeA{Peterson2017}. For both input images, the weights of the bottleneck layer are shared. The weights are learned by back-propagating the loss incurred during the prediction of human similarity judgments, hence optimizing the projected representations to predict human similarity judgments. This contrasts with the method of \citeA{Peterson2017}, which learns weights for each of the 4096 input dimensions, or principal component analysis (PCA), which preserves as much information as possible as opposed to just that which is relevant to human similarity judgments (and thus may inflate the estimated intrinsic dimensionality). We first trained a separate model for each dataset. CNN feature vectors were first normalized such that their norms were one. We used mean squared error loss with L2 regularization to train each model. The L2 coefficient was selected between $10^{-3}$ and $10^3$ by $6$-fold cross-validation over the $120$ images. Further, for every dataset, the number of nodes in the bottleneck layer is varied in the range of $1-64$. We also compare the above with a simple unsupervised baseline that alternatively obtains low-dimensional representations by running PCA over the input VGG-19 representations. These low-dimensional representations are then transformed by ridge regression using the method of \citeA{Peterson2017} to predict similarity ratings. As above, we vary the number of principal components in the range of $1-64$. \begin{figure}[!t] \begin{center} \includegraphics[width=0.9\linewidth, trim=3mm 3mm 3mm 4mm, clip=true]{figs/model} \end{center} \caption{Overview of SimDR. CNN representations for an image pair are down-projected using a shared low-dimensional bottleneck layer. An inner product of the outputs gives predicted similarity rating for the input pair.} \label{fig::model_diag} \end{figure} \begin{table}[!b] \begin{center} \setlength{\tabcolsep}{3.5pt} \begin{tabular}{lcccc} \hline Dataset & Raw & \citeA{Peterson2017} & SimDR & PCA \\ \hline Animals & 0.58 & 0.74 & 0.64 & 0.47\\ Vehicles & 0.51 & 0.58 & 0.57 &0.51 \\ Fruits & 0.27 & 0.36 & 0.30 & 0.27\\ Furniture & 0.19 & 0.35 & 0.33 & 0.28\\ Various & 0.37 & 0.54 & 0.50 & 0.31\\ Vegetables & 0.27 & 0.34 & 0.30 & 0.32\\ \hline \end{tabular} \caption{$R^2$ scores for all datasets (SimDR values are for bottleneck layer of size 64).} \label{table::r2score} \end{center} \end{table} \begin{figure*}[!t] \begin{center} \includegraphics[width=1.0\linewidth, trim=2mm 2mm 3mm 3mm, clip=true]{figs/dimvsr2} \end{center} \caption{Explained variance ($R^2$) of our models in predicting human similarity judgments on each dataset. The dashed lines correspond to the prediction performance in \citeA{Peterson2017} when all input dimensions are used.} \label{fig::dimvsr2} \end{figure*} \section{Few dimensions predict similarity judgments} We observe for all datasets that the SimDR $R^2$ score at 64 dimensions is higher than that of the raw (untransformed) CNN representations (Table~\ref{table::r2score}). The PCA-based model performed worse than SimDR for all datasets (except for the \textit{vegetables} dataset), suggesting that supervision is much more selective of the human-relevant dimensions. We also observe that the prediction performance of SimDR quickly saturates as the number of dimensions increases beyond $10-20$, approaching the prediction performance obtained using all VGG-19 features (Fig.~\ref{fig::dimvsr2}; dashed lines). Notably, the \textit{animals} dataset requires only 6 nodes to achieve an $R^2$ score of 0.6 while the \textit{various} dataset achieves an $R^2$ of 0.49 at 6 nodes. These results strongly suggest that human similarity judgments can be captured by considerably fewer dimensions (by at least two orders of magnitude) than those comprising VGG-19 representations, and more generally that psychological representations as measured by similarity experiments are much lower-dimensional than CNN representations. Additional evidence for this can be seen in the intrinsic dimensionality of the CNN representations themselves without respect to human judgements. Fig.~\ref{fig::pca_data} illustrates this using PCA: cumulative variance explained is shown as a function of the number of components, for each dataset. Notably, the dimensionality elbow is both longer and later than those in Fig.~\ref{fig::dimvsr2}. Interestingly, CNNs also appear to assign equal dimensionality to all datasets (except \textit{various}), apparently much unlike humans (Fig.~\ref{fig::dimvsr2}). \section{Interpretation of low-dimensional features} Now that we have demonstrated the sufficiency of low-dimensional representations to predict similarity judgments, we can attempt to interpret the reduced dimensions. For this experiment, we focus on the top 3 datasets based on $R^2$ score---\textit{animals}, \textit{vehicles}, \textit{various}. As mentioned above, SimDR achieves an $R^2$ score of 0.6 on the \textit{animals} dataset using only 6 dimensions. On the \textit{various} dataset, it achieves an $R^2$ score of 0.49 using 6 dimensions, and an $R^2$ score of 0.45 on \textit{vehicles} dataset using 16 dimensions. We fix these as the bottleneck layer sizes for each of these datasets. The aforementioned dimensions for each of the three datasets are chosen by visually identifying an elbow in performance (Fig.~\ref{fig::dimvsr2}) such that the rate of increase in $R^2$ score is small beyond this point. We want to understand these individual dimensions; however, they may not be orthogonal. To address this, we further orthogonalize our low-dimensional representations using PCA to ensure that each dimension encodes unique information. We then take the top few dimensions which explain most of the variance for each dataset. This contrasts with the use of PCA above to produce a baseline reduced feature set in that it is performed after supervised dimensionality reduction. \begin{figure}[!b] \begin{center} \includegraphics[width=1.0\linewidth, trim=7mm 2mm 13mm 10mm, clip=true]{pca_data} \end{center} \caption{Cumulative variance explained in the full VGG-19 representations as a function of principal component.} \label{fig::pca_data} \end{figure} \begin{figure*}[!t] \begin{center} \includegraphics[width=1.0\linewidth, trim=6mm 8mm 6mm 6mm, clip=true]{pca_1d} \end{center} \caption{Image embeddings along the top four principal components of low-dimensional SimDR representations.} \label{fig::pca_1d} \end{figure*} \begin{figure*}[!t] \begin{center} \includegraphics[width=1.0\linewidth, trim=7mm 7mm 14mm 6mm, clip=true]{pca_2d} \end{center} \caption{Examples of image embeddings for three datasets using the top principal components of the SimDR representations.} \label{fig::pca_2d} \end{figure*} \begin{figure*}[!t] \begin{center} \includegraphics[width=1.0\linewidth, trim=3mm 2mm 3mm 2mm, clip=true]{figs/dendogram} \end{center} \caption{Dendrograms of hierarchical clustering for 2-dimensional representations and 6-dimensional representations on \textit{animals} dataset. \textit{H: Herps, B: Birds, P: Primates, R: Rodents, WC: Wild cats, G: Grazers, E: Dogs, Bears and Large animals}.} \label{fig::dendrograms} \end{figure*} \subsection{Visualizing individual dimensions} The ability of the low-dimensional representations to predict similarity indicates that they are efficiently encoding information essential for making similarity judgments. Hence, they can further be leveraged to understand what factors allow them to predict similarity judgments. To this end, for each of the three datasets, we visualize image embeddings along the top four principal dimensions of the low-dimensional features learned via SimDR. We visualize validation images for a single fold (out of the 6 cross validation folds), though we observe that the dimensions were consistent across all folds in terms of capturing the same concepts (Fig.~\ref{fig::pca_1d}). We observe that the first dimension for each dataset appears to be largely continuous, and captures broad categories. In the animals dataset, this dimension goes from non-mammals to mammals. The first dimension of the \textit{various} dataset goes from inanimate objects to dogs and humans. The first dimension of the \textit{vehicles} dataset shows a gradation from vehicles with two or no wheels (\textit{e.g.,} sled, wheelchair) to those with four wheels (\textit{e.g.,} trucks, buses), though the interpretation in this case is not as evident, which may stem from the low variance (12\%) captured by the top component. Some of the other principal components are also apparently interpretable and interesting. For example, the second principal component of the \textit{vehicles} dataset distinguishes water transport from land transport, the third principal component of the \textit{various} dataset distinguishes natural things from artificial ones, while the fourth dimension in the \textit{animals} dataset distinguishes birds from non-birds. Each of these individual dimensions captures a different taxonomic relationship, suggesting that such relationships are important factors in determining similarity judgments of natural images. \subsection{Clusters formed by pairs of dimensions} \label{subsec::clusters} As an alternative visualization strategy, we explore 2D projections of the image representations along two of the top four principal components in Fig.~\ref{fig::pca_2d}. These plots are useful in observing clusters of images formed by a combination of principal components, where each cluster tells us what kind of images are considered similar by the model. Echoing \citeA{Peterson2017}, we observe clusters for herptiles, primates, birds, wild cats, rodents, and grazers in the \textit{animals} dataset. We see clusters for human faces and body parts, animals, vegetables, houses, and natural things in the \textit{various} dataset. The \textit{vehicles} dataset shows distinct clusters for trains, bikes, horses, airplanes, and tanks. \subsection{Hierarchical similarity and bottleneck effects} Next, we analyze the effect of changing the width of the bottleneck layer. We know that increasing the width improves prediction performance. Here, we are interested in interpreting the information captured by different bottleneck sizes. To visualize this, we explore dendrograms \cite{Shepard390} for the \textit{animals} dataset. Fig.~\ref{fig::dendrograms} shows that when the size of the bottleneck layer in SimDR is 2, two clusters---primates and non-primates---are formed. This suggests that belonging to the primate group is the most important trait influencing similarity judgments in the \textit{animals} dataset, which is encoded in as little as two dimensions. At a bottleneck size of 6, however, further hierarchical structure can be seen where many more categories are present. At intermediate sizes between 2 and 6, additional clusters continue to emerge (not shown). The hierarchical structure formed by the 6-dimensional representations is closely related to that formed using human similarity data in \citeA{Peterson2017}. We observe that increasing the bottleneck width introduces further categorical distinctions in other datasets too. For the \textit{various} dataset, at a bottleneck width of 4, we observe distinct clusters for animals and humans (and their body parts). In the case of the \textit{vehicles} dataset, 4-dimensional bottleneck layer representations preserve distinctions based on wheels. Hence, these are primary traits influencing similarity judgments which are captured at small bottleneck widths. These results motivate a hierarchical organization of factors underlying human similarity judgments in our model, providing empirical results consistent with mathematical theories of hierarchical semantic knowledge organisation in neural networks \cite{Saxe2019}. \section{Shared features across domains} We have seen that each of the six individual SimDR models can discover low-dimensional representations which are predictive of similarity judgments separately for each domain. A natural question that follows from this is whether the dimensions learned by these models trained on specific domains are also shared across domains. Translating this into the framework of human judgments, the question we pose is the following: do different domains share factors underlying human similarity judgments? \subsection{Canonical Correlation Analysis} \begin{figure}[h] \centering \includegraphics[width=1.0\linewidth, trim=0mm 5mm 22mm 15mm, clip=true]{figs/cca_heatmap} \caption{Inter-domain relatedness ($R^2$) as measured by regularized CCA between all domain pairs.} \label{fig:cca} \end{figure} We use L2-regularized canonical correlation analysis (CCA; \citeNP{Bilenko2016}) to evaluate the degree of shared information or factors between low-dimensional representations belonging to any two domains. From each of the six models trained on individual domains, we obtain 64-dimensional representations for all pairs of images (from all 6 datasets). We then perform regularized CCA on 64-dimensional representations from every pair of domains. We observe in Fig.~\ref{fig:cca} that the $R^2$ score is highest for \textit{fruits} and \textit{vegetables}, followed by \textit{animals} and \textit{vehicles}. This implies that the model trained on fruits and the model trained on vegetables have overlapping latent factors and hence, their similarity predictions are also based on some common factors. The same is true for \textit{animals} and \textit{vehicles} datasets. While it seems reasonable for \textit{fruits} and \textit{vegetables} to share common factors for similarity, the relationship between \textit{animals} and \textit{vehicles} is less clear, although we suspect it may have something to do with common backgrounds (which often contain scene information such as grass, sky, and water, unlike our other categories). \subsection{Domain-agnostic SimDR} To determine whether a more general set of dimensions could be learned that generalizes across domains, we trained a SimDR model on image pairs from all six datasets using 6-fold cross-validation. We compared this to models trained on individual domains and tested on all others to assess how they generalize on their own. The results, shown in Fig.~\ref{fig:pooled}, reveal that the pooled model nears saturation at a few hidden dimensions. Hence, even with a diverse dataset, few dimensions are enough to predict similarity judgments. Next, we see that the domain-specific models do not generalize well when tested on all datasets, lending credibility to our earlier claim that these models learn dimensions which are specific to individual domains. Lastly, Fig.~\ref{fig:pooledtest} shows the performance of the pooled model in predicting individual domains, and reveals that certain domains (\textit{animals}, \textit{vehicles}, \textit{various}) are well-explained by general features learned from the pool of all domains, while others require more domain-specific features (\textit{vegetables}, \textit{fruits}, \textit{furniture}). \begin{figure}[!b] \centering \includegraphics[width=1.0\linewidth, trim=6mm 2mm 16mm 14mm, clip=true]{figs/dimvsr2_pooled} \caption{Performance of models tested on all domains (with varying bottleneck layer size). The dashed line shows the performance of the model trained on all domains in \citeNP{Peterson2017}. Solid lines correspond to models trained on different datasets.} \label{fig:pooled} \end{figure} \begin{figure}[!b] \centering \includegraphics[width=1.0\linewidth, trim=6mm 2mm 16mm 14mm, clip=true]{figs/pooled1} \caption{Performance of pooled model tested on individual domains and on all domains (with varying bottleneck layer size). The dashed line shows the performance of the model trained on all domains in \citeNP{Peterson2017}. Solid lines correspond to the pooled model tested on different datasets.} \label{fig:pooledtest} \end{figure} \section{Conclusion} Our work shows that CNN representations can be transformed to lower dimensions---where interpretation is far less cumbersome---while still being predictive of similarity judgments. We also observe that only a few dimensions are required to predict psychological representations as opposed to a considerably larger, full set of CNN features. This finding is interesting because the deep feature sets increasingly being used in both cognitive modeling \cite<for a review, see>{ma2020neural} and neuroscience \cite{Kriegeskorte2015,kietzmann2018deep,Cichy2019} are much higher-dimensional. Indeed, some work may already suggest that our findings could generalize to modeling neural activity as well \cite{mur2013human}, though future work must bear this out. Moreover, in this low-dimensional space, we are able to visualize individual dimensions and show that they code for unique concepts. Hence, they provide insights into potential factors that influence human similarity judgments, and potentially various other visual tasks. We observe that increasing the size of the bottleneck layer introduces finer levels of distinction, mirroring hierarchical clustering in human cognition. These results together show the ability of CNN representations to both predict and explain human similarity judgments using a few dimensions. This work takes a step towards showing that psychological representations can be predicted by far fewer dimensions than used in CNNs; and that they are not only quantitatively predictive of human similarity judgments but provide insights about how people make similarity judgments. We think our approach can help bridge the interpretation gap between CNN representations and psychological representations by providing interpretable factors which influence human similarity judgment. \section{Acknowledgements} This work was supported by the National Science Foundation (grant number 1718550), and the School of Engineering and Applied Sciences at Princeton University. \bibliographystyle{apacite} \setlength{\bibleftmargin}{.125in} \setlength{\bibindent}{-\bibleftmargin}
{'timestamp': '2020-06-01T02:05:16', 'yymm': '2005', 'arxiv_id': '2005.14363', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14363'}
arxiv
\section{Introduction} In response to climate change concerns, the decarbonization and digitization of the electricity sector have been accelerated in recent years. The path to decarbonization is associated with the high penetration of Distributed Energy Resources (DERs), such as rooftop solar, home batteries and electric vehicles with the potential to support a reliable, affordable and lower-emissions electricity grid. Increase in the deployment of DERs raises several opportunities and challenges in the electricity systems \cite{openenergy}. Technical challenges include increase in bidirectional power flows, raise in the voltage levels, and lack of visibility \cite{coster2010integration}. On the other side, efficient DER integration can provide substantial benefits for energy customers \cite{aemo}. DER owners can benefit from Feed-In-Tariffs (FiTs) programs by selling energy back to the utility grid for a fixed price \cite{ye2017analysis}. Alternatively, they can be coordinated and aggregated for participation in different markets. Virtual Power Plants (VPPs) are an example of DER aggregation to exploit their inherent flexibility \cite{pudjianto2007virtual}. An emerging technique for integration of small-scale producers and consumers to energy markets is Peer-to-Peer (P2P) trading, which allows bilateral energy transactions between users \cite{tushar2020peer}. P2P trading provides significant benefits for both end users and grid operators such as increasing welfare by preference satisfaction \cite{morstyn2018using}, lowering operational costs, and improving system reliability \cite{mengelkamp2018designing}. P2P trading offers the flexibility required to coordinate agents with diverse preferences. Grid digitization provides a two-way communication network which allows the DER owners and energy customers to act as proactive agents in the energy markets and paves the path for P2P market implementation. Through direct interaction of agents in a decentralized platform, small-scale producers are allowed to compete with large traditional suppliers. In the P2P trading, it is expected that market participants can settle the bilateral transactions with less influence from a central authority \cite{giotitsas2015peer}. Hence, designing a decentralized platform for managing market participants with diverse preferences is a challenging task. Blockchain technology offers new opportunities for decentralized market designs and enables energy producers and consumers to directly negotiate and trade energy. It provides a platform to store and share data in a secure and verifiable manner, even when the identity and trustworthiness of market participants is unknown \cite{van2020integrated}. Given the properties of blockchain, several blockchain-based platforms for P2P energy trading have been developed recently \cite{mengelkamp2018designing,li2017consortium,wang2019energy}. The Brooklyn microgrid is a prototype of blockchain enabled P2P market, in which a blockchain framework is employed to implement a decentralized microgrid energy market \cite{mengelkamp2018designing}. A unified blockchain framework for various scenarios of energy trading in an industrial internet of things is proposed in \cite{li2017consortium}, in which a credit-based payment scheme is employed to overcome the transaction limitation caused by transaction confirmation delays. An operation framework for P2P energy trading at distribution level is presented in \cite{wang2019energy}, where the system operator clears the market using a crowdsourced energy system model. The blockchain framework should incorporates a proper market settlement approach to settle the bilateral transactions among the agents. There are several approaches that can be applied for P2P market clearing and peer matching, such as auction-based mechanism, game theory, and optimization-based methods. In the auction-based mechanism, agents express their interest in energy trading by submitting their offers, and the energy allocation and price would be determined based on the market clearing rules \cite{chen2019trading}. The game theory approaches aim to provide a stable solution that is beneficial for all parties \cite{tushar2018peer}. In the optimization-based method, the market settlement is formulated as an optimization problem, which can be decomposed to local subplroblems solvable by each agent \cite{khorasany2019decentralised}. The optimization-based methods can be implemented in a decentralized manner without any need to third party intervention and allows agent to optimize their welfare by participating in the P2P market, and hence, are well suited for blockchain-enabled P2P markets. The aim of this paper is to design a blockchain-enabled P2P market that provides a secure and transparent environment for energy trading of producer and consumer agents. In the proposed approach agents can \textit{advertise} their surplus/deficit energy. In order to reduce the computation and communication overheads, a \textit{Prioritization} step is considered in the market settlement process that enables agent to prioritize their trading partners based on their proximity and reputation factor. To incite agents to trade energy with their neighboring agents, a grid service charge is considered to apply a transaction fee to each trade based on the electrical distance between producer and consumer. In order to preserve the privacy of the agents, We propose an Anonymous Proof of Location (A-PoL) algorithm that enables them to prove their location without revealing their real-identity. A decentralized optimization algorithm is employed for the \textit{Negotiation} that allows agents iteratively optimize their welfare in the negotiation process. The privacy of agents in the negotiation process is also preserved, as they do not need to exchange their private information related to their energy and price preferences. The contributions of this paper are summarized as follows: \begin{itemize} \item [-] Designing a pure decentralized P2P trading framework that does not require access to private information of agents; \item[-] Implementing a \textit{prioritization} step to allow agents select their trading partners based on their location and reputation; \item[-] Proposing a A-PoL algorithm which uses a Certificate of Location (CoL) issued by smart meter to approve the location of agents. \end{itemize} The rest of this paper is organized as follows. Section \ref{sec: market structure} outlines the structure of the market, including agents modeling, market objective, and decentralized optimization of the market objective. Section \ref{sec:energy trading} explains the market settlement process and its different steps. Case studies and numerical results are reported in Section \ref{sec: case study}. A detailed analysis of the security and privacy of the proposed framework is presented in Section \ref{sec:security}. Finally, concluding remarks are given in Section \ref{sec:conclusion}. \section{Market Structure}\label{sec: market structure} In this section, we outline the details of the market structure. The proposed architecture consists of two layers that are: i) physical layer that is the underlying physical network to transfer electricity from producers to consumers. The minimum requirement for a successful transaction between a producer and a consumer is existence of a path to transfer power between them, and ii) overlay layer that is where the participating nodes, that includes energy producer, consumer, and the grid operator, connect through a public blockchain to share information. The overlay provides a secure platform for the participating nodes to advertise their energy, negotiate on their offers, and decide on their actions in the market. Market mechanism is implemented in this layer that enables the agents to trade energy and settle energy transactions.\par In the rest of this section, we discuss agent's modeling in Section \ref{sub:sec:agent-modeling}, market objective in Section \ref{sub:sec:market-settlement}, and decentralized optimization method for market settlement in Section \ref{sub:sec:coordination}. \par \subsection{Agents modeling}\label{sub:sec:agent-modeling} We consider an energy network with a set of agents consisting of a set of producer agents with index \(i \in \mathcal{P}=\{1, ..., P\}\) and a set of consumer agents with index \( j \in \mathcal{C}=\{1, ..., C\}\) connected to a physical layer manged by a grid operator. Producers have energy producing capability and can use their own generated energy for their demand. In case that there is more generation than demand, producers can sell it to consumers or the grid. Consumers on the other side can buy energy from producers or the grid. Producers and consumers can negotiate for energy trading in a forward market for any time interval \(t \in \mathcal{T} =\{1, ..., T\}\) with equal duration (e.g., one hour). Agents are equipped with smart meters, which determines the energy surplus/deficit for trade in each time slot. (more discussion on application of smart meter) After energy management, agents indicate their energy surplus and deficit. Each agent can trade with the grid or with other agents in the network. The total energy surplus and deficit of producers and consumers can be represented as \begin{equation}\label{tot energ pro} e_i=e_i^G +\sum_{j \in \mathcal{C}}{e_{ij}^P} \end{equation} \begin{equation}\label{tot energ cons} e_j= e_j^G+\sum_{i \in \mathcal{P}}{e_{ji}^P} \end{equation} where, \(e_i^G\) and \(e_j^G\) are the traded energy between producer $i$/consumer $j$ and the grid respectively, \(e_{ij}^P\) is sold energy by producer $i$ to consumer $j$, and \(e_{ji}^P\) is the bought energy by consumer $j$ from producer $i$. Each agent in the P2P market aims to maximize its welfare. The welfare incorporates the utility/cost of energy consumption/generation, cost/revenue of trade with other agents or the grid, and the cost of using grid for P2P trading. The welfare function of producers and consumers can be modeled by (\ref{pro welf}) and (\ref{con welf}) respectively \begin{equation}\label{pro welf} W_i(e_i, \lambda_{ij},\gamma_{ij})= \underline{\lambda}^G e_i^G +\sum_{j \in \mathcal{C}}{e_{ij}^P (\lambda_{ij}-\gamma_{ij})}-C_i(e_i) \end{equation} \begin{equation}\label{con welf} W_j(e_j, \lambda_{ij},\gamma_{ij})= U_j(e_j)- \overline{\lambda}^G e_j^G -\sum_{i \in \mathcal{P}}{e_{ij}^P (\lambda_{ij}+\gamma_{ij})} \end{equation} where \(\underline{\lambda}^G\) denotes FiT representing the price for selling energy to the grid; \(\lambda_{ij}\) is energy price in transaction between producer $i$ and consumer $j$; \(\gamma_{ij}\) is grid service charge for using grid infrastructure for this trade; \(\overline{\lambda}^G\) denotes the price for selling from the grid which is usually a fixed value over the time (e.g. time of use tariff). The grid selling and buying prices limit energy price in the P2P market, i.e. for any bilateral trade \begin{equation}\label{price lim} \underline{\lambda}^G \leq \lambda_{ij} \leq \overline{\lambda}^G. \end{equation} The cost function of the producer represents the cost of generating energy \(e_i\) and can be modeled as \cite{grainger2003power} \begin{equation}\label{cost-func-producer} C_i(e_i)=a_i e_i^2 +b_i e_i +c_i \end{equation} where \(a_i, b_i\) and $c_i$ are positive constants, which can be adjusted by the producer to reflect the generation cost. Since producers usually have renewable generation resources with zero marginal costs, the cost function can represent the cost associated with battery degradation cost, if producer needs to discharge its battery to sell the energy. On the other side, the utility function of a consumer represents its satisfaction level by consuming energy $e_j$ and can be modeled as \cite{samadi2010optimal} \begin{equation}\label{cost-function-consumer} U_j(e_j)= \begin{cases} -a_j e_j^2 +b_j e_j \;\;\;\; :0 \leq e_j \leq \frac{b_j}{2 a_j}\\ \frac{b_j^2}{4 a_j} \;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\ :e_j \geq \frac{b_j}{2 a_j} \end{cases} \end{equation} where \(a_j\), and \(b_j\) are unique positive constants for each consumer. These parameters reflect the valuation of the energy by the consumer and denotes the price that consumer is willing to pay for the energy. To incite agents to trade with their closest electrical partner, a grid service charge is considered for each transaction. This fee represents the price that agents need to pay for using the grid infrastructure for each trade and is expressed by \begin{equation}\label{service charge} \gamma_{ij}=\omega d_{ij} \end{equation} where \(\omega\) is grid service charge per unit of electrical distance for each unit of energy, and \(d_{ij}\) is the electrical distance between producer $i$ and consumer $j$. This distance can be calculated based on power transfer distance, which aggregates the absolute value of Power Transfer Distribution Factor (PTDF) induced by a trade as in \begin{equation} \label{eq:ptdf} d_{ij}=\sum_{l \in \mathcal{L}}{\phi^l_{ij}}. \end{equation} For any trade, \(\phi^l_{ij}\) indicates the fraction of transacted power from producer $i$ to consumer $j$ that flows over a line $l$, and can be calculated using the method presented in \cite{wood2013power}. \subsection{Market objective} \label{sub:sec:market-settlement} The market objective for P2P trading is formulated as social welfare maximization, which maximizes the total welfare of players in the market subject to the constraints, and mathematically can be modeled as: \begin{equation}\label{tot objective} \begin{aligned} & \underset{\textbf{\textit{$e_i$,$e_j$}}}{\text{max}} \sum_{i \in \mathcal{P}}{W_i} + \sum_{j \in \mathcal{C}}{W_j}\\ & \text{s.t. constraints} \end{aligned} \end{equation} As stated in (\ref{price lim}), the price in P2P market is always beneficial for both producers and consumers. Hence, it is rational to assume that all agents try to maximize their traded energy in the P2P market and minimize trading with the grid, by setting $e_i^G=e_j^G=0$. Therefore, Eq. (\ref{tot objective}) can be rewritten as: \begin{subequations}\label{social welfare} \begin{equation} \begin{aligned} & \underset{\text{\textbf{{$e_{ij}$,$e_{ji}$}}}}{\text{max}} \sum_{j \in \mathcal{C}}{U_j(e_{ji})} - \sum_{i \in \mathcal{P}}{C_i({e_{ij}})} - \sum_{j \in \mathcal{C}}{\sum_{i \in \mathcal{P}}}{(e_{ij}+e_{ji})\gamma_{ij}}\\ \end{aligned} \end{equation} \begin{equation}\label{producer flex} \text{s.t.} \;\;\; \underline{e_i} \leq \sum_{j \in \mathcal{C}}{e_{ij}^P} \leq \overline{e_i} \;\;\;\;\;\;\;\;\;\;\;\;\;\; :\underline{\mu_i}, \overline{\mu_i} \end{equation} \begin{equation}\label{consumer flex} \underline{e_j} \leq \sum_{i \in \mathcal{P}}{e_{ji}^P} \leq \overline{e_j} \;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\; :\underline{\mu_j}, \overline{\mu_j} \end{equation} \begin{equation}\label{demand supply} e_{ij}^P=e_{ji}^P \;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\; :\lambda_{ij} \end{equation} \end{subequations} where (\ref{producer flex}) and (\ref{consumer flex}) represents the flexibility constraints of producer, and consumer, respectively. The constraint (\ref{demand supply}) represents the power balance in transaction between producer $i$ and consumer $j$. \(\underline{\mu_i}, \overline{\mu_i}, \underline{\mu_j}, \overline{\mu_j}, \lambda_{ij}\) are dual variables associated with these constraints. \subsection{Decentralized optimization} \label{sub:sec:coordination} In this paper, our aim is to solve (\ref{social welfare}) with only P2P communications to ensure data privacy of the agents. To do so, a decentralized optimization approach is employed to formulate market settlement in P2P market \cite{khorasany2019decentralised}. In this approach, dual variables are used to decouple constraints, and then, the problem is decomposed to local subproblems solvable by producers and consumers. The local subproblem is solved by deploying the sub-gradient projection method \cite{boyd2011distributed}. Each agent, contributes to solving the global problem by updating its local decision variables. The set of decision variables for producers and consumers are \{\(\lambda_{ij}, e_{ij}^P, \underline{\mu_i}, \overline{\mu_i}\}\), and \{\( e_{ji}^P, \underline{\mu_j}, \overline{\mu_j}\)\}, respectively. The market settlement approach is an iterative process, in which agents update their decision variables iteratively and exchange information without revealing their private information. The updates of the decision variables of agents are based on the Karush–Kuhn–Tucker (KKT) optimality conditions of the local problems, and can be developed using first order deviate of the relaxed problem as follows:\\ \(\forall i \in \mathcal{P}\) \begin{subequations}\label{sell update dec} \begin{equation}\label{sell price update} \lambda_{ij}^{k+1}=\left[\lambda_{ij}^{k}-\rho_{\lambda}^k(e_{ij}^{P,k}-e_{ji}^{P,k})\right]^{+} \end{equation} \begin{equation}\label{sell mu low update} \underline{\mu_i}^{k+1}=\left[\underline{\mu_i}^{k}+\rho_{\mu}^k(\underline{e_i}-e_i^k)\right]^{+} \end{equation} \begin{equation}\label{sell mu up update} \overline{\mu_i}^{k+1}=\left[\overline{\mu_i}^{k}+\rho_{\mu}^k(e_i^k-\overline{e_i})\right]^{+} \end{equation} \begin{equation}\label{sell energy update} e_{ij}^{{P,k+1}}= \left[e_{ij}^{{P,k}}+\zeta_{ij}^k(\tilde{e}_{ij}^{P,k+1}-e_i^k)\right]^{+}\\ \end{equation} \begin{equation}\label{set point sell update} \tilde{e}_{ij}^{P,k+1}=\frac{\lambda_{ij}^{k+1}-\gamma_{ij}-\overline{\mu_i}^{k+1}+\underline{\mu_i}^{k+1}-b_i}{2 a_i} \end{equation} \end{subequations} \(\forall j \in \mathcal{C}\) \begin{subequations}\label{buyer update dec} \begin{equation}\label{buyer mu low update} \underline{\mu_j}^{k+1}=\left[\underline{\mu_j}^{k}+\rho_{\mu}^k(\underline{e_j}-e_j^k)\right]^{+} \end{equation} \begin{equation}\label{buyer mu up update} \overline{\mu_j}^{k+1}=\left[\overline{\mu_j}^{k}+\rho_{\mu}^k(e_j^k-\overline{e_j})\right]^{+} \end{equation} \begin{equation}\label{buyer power update} e_{ji}^{P,k+1}= \left[e_{ji}^{P,k}+\zeta_{ji}^k(\tilde{e}_{ji}^{P,k+1}-e_j^k)\right]^{+} \end{equation} \begin{equation}\label{buyer set point update} \tilde{e}_{ji}^{P,k+1}=\frac{b_j-\lambda_{ij}^{k+1}-\gamma_{ij}-\overline{\mu_j}^{k+1}+\underline{\mu_j}^{k+1}}{2 a_j} \end{equation} \end{subequations} where $k$ is the iteration index, \(\tilde{e}_{ij}^{P}, \tilde{e}_{ji}^{P}\) are optimal power set points of producer and consumer at the price \(\lambda_{ij}\). \(\zeta_{ij}, \zeta_{ji}\) are asymptotically proportional factors, \(\rho\) is a small tuning parameter, and \([.]^+\) denotes max \{.,0\}. The information exchange between producers and consumers during the decentralized optimization process is explained in section \ref{sec:neg}. \section{Market Settlement Process}\label{sec:energy trading} In this section, we outline the details of the market settlement process for P2P trading. The proposed framework consists of four main phases that are summarized in Fig. \ref{fig:full algorithm} and discussed in details in the rest of this section. \begin{figure} \input{marketsettlement} \caption{Market settlement algorithm}\label{fig:full algorithm} \end{figure} The proposed framework considers the location of the participants denoted by $\sigma$ in the grid service charge calculation as denoted in (\ref{service charge}). Thus, it is critical for the involved parties to prove their location. This potentially enables the malicious nodes to track the activities of a particular user which in turn compromises the user privacy. To address this challenge, we propose a A-PoL algorithm that enables the users to prove their location while protecting their real-identity which in turn enhances the level of anonymity offered to the users. The proposed PoL algorithm involves a CoL that is issued by a smart meter in the network as shown in Fig. \ref{fig:CoL}. The energy companies maintain a local record of the accurate location of the installed smart meters. During the installation process, the energy company deploys a key pair in each smart meter (step 1 in Fig. \ref{fig:CoL}) and records $<PK,location>$ tuple in its local storage. The company serves as a certificate authority (CA) for PKs deployed in smart meters. Although the CA is a trusted authority, relying on the PK provided by the CA may potentially compromise the privacy of the users as the company can build a virtual profile of the user and their energy trading (by observing the proof of location transactions). To address this challenge, we propose the CoL. \par \begin{figure} \centering \includegraphics[scale=0.5]{COL.jpeg} \caption{An overview of the proposed CoL.} \label{fig:CoL} \end{figure} CoL is a certificate received from a verifier that is an independent smart meter in the network. Assume smart meter \textit{A} is going to establish a CoL. Once deployed on site, \textit{A} explores the CA to find potential smart meters that can function as the verifier. Assume smart meter \textit{B} is selected by \textit{A} to function as the verifier. Recall that we assume the smart meters are tamper resistant and thus \textit{A} can send its request to any meter listed in CA. \textit{A} may request a group of nodes to function as verifiers. \textit{A} sends a CoL request transaction to \textit{B} that is structured as $<T\_ID, MTR, \sigma, PK, Sign>$, where \textit{T\_ID} is the unique identifier of the transaction which is the hash of the transaction content. \par \textit{A} populates the root hash of a Merkle tree constructed by recursively hashing a number of PKs in the \textit{MTR} field. The PKs in the leaves of the tree are later employed by \textit{A} to prove ownership on the CoL which is discussed in greater detail later in this section. The number of PKs may vary based on the application. $\sigma$ is the noisy location of the smart meter that can be the location at a lower resolution, e.g., the street in which the meter is installed. This potentially protects the privacy of the smart meter against deanonymization as studied later in Section \ref{sec:security}. \textit{PK} is the PK of \textit{A} allocated by the CA and \textit{Sign} is the corresponding signature which proves that \textit{A} owns the private key corresponding to the PK. \par When the verifier, i.e.,\textit{B} receives the CoL request, it verifies that the transaction is generated by a genuine smart meter that is done by requesting the CA (step 3). To protect the privacy of the user, the CA does not reveal the actual location of smart meter to \textit{B} instead only confirms if the PK is registered and genuine smart meter. Once verified, the verifier creates a CoL that is \textit{sign(hash(MTR, $\sigma$))} and replies back to \textit{A} by sending the reply transaction structured as $<CoL, PK, Sign> $, where CoL is as outlined above, \textit{PK } is the PK of the verifier, i.e., \textit{B} registered by the CA, and \textit{Sign} is the corresponding signature of the verifier. \par \textit{A} employs the received CoL to anonymously prove its location to the nodes in the overlay. To do so, \textit{A} appends $CoL_f\textsuperscript{A} = (CoL_A, PK\textsubscrtip{ver}, Sig\textsubscrtip{ver}, MTR_A, \sigma_A, PK_A, MTL_A, \\ Sign_A)$ where the first three fields are extracted from the response of the verifier \textit{B}. MTR and $\sigma_A$ are extracted from the CoL request sent to the verifier. \textit{$PK_A$} is a PK that was part of the leaves of the Merkle tree. $MTL_A$ is the leaves of the Merkle tree that are necessary to prove the existence of $PK_A$ in the MTR and $Sign_A$ is the signature corresponding to PK. The last three fields ensure that only the owner of the certificate, who knows the PKs in the Merkle tree and the corresponding private key, can use the certificate. \par To verify the location of \textit{A}, the participating nodes in the blockchain, say \textit{C}, must first verify that $PK_A$ belongs to $MTR_R$ using $MTL_A$. Next, \textit{C} verifies if $Sign_A$ matches $PK_A$. The third step in verifying is to verify if $hash(MTR_A, \sigma_A) = CoL_A$. The final step is for \textit{C} to verify PK\textsubscrtip{ver} using CA. This ensures that a genuine smart meter has signed the CoL. If all the above steps successfully passed, the location of \textit{A} is verified. \par Having discussed the details of the proposed PoL algorithm, we study the process of P2P energy trading in the rest of this section. The algorithms implementd by producer and consumer agents are represented in Algorithm \ref{producer lag} and \ref{consumer alg}, respectively and are discussed with greater details in the rest of this section. \subsection{Advertisement}\label{sub:sec:advertisement} The main aim of this phase is for the agents to advertise their energy to the potential consumers/producers. In each market interval, agents participate in the forward market by submitting their offers and asks in the form of \textit{advertisement transaction (AT)} that is structured as follow: \begin{equation} AT = (T\_ID, price/amount, \eta_i, CoL_f\textsuperscript{i}) \end{equation} where \textit{price/amount} can be either the price of the energy, i.e., $\lambda_i, \forall i\in \mathcal{P}$, if AT is generated by a producer or the amount of requested energy, i.e., $e_j, \forall j\in \mathcal{C}$, if AT is generated by a consumer, and \(\eta\) is the reputation factor of agent.\par In conventional blockchain-based frameworks, the negotiation transactions are stored in the blockchain that provides high auditability. However, this potentially increases the computational and storage resource consumption of the blockchain and limits throughput, i.e., the total number of transactions that can be stored per second. These potentially reduce the blockchain scalability while smart grid comprises of a broad range of devices that may produce transactions frequently. To address this challenge, in our framework the negotiation transactions are stored in a public database managed by the grid operator that is referred to as \textit{Advertisement Database} (AD). The write access of AD is restricted only to the grid operator and other nodes in the overlay have read-only permission. The parties involved in an AT transaction, i.e., energy producer and consumer, may store the transactions locally and employs in case of dispute between parties. The final price and amount of energy agreed by the participants is later defined during negotiation, thus the reference to AT transaction is limited. Consequently, we skipped storage of such transactions in the blockchain. \par \subsection{Prioritization} After \textit{advertisement} step, agents explore the available ATs in the AD for the negotiation. One-on-one negotiation may potentially increase the delay associated with finalizing the trade as either side of the trade may have higher welfare in trading with another party in the network. Also, negotiation with every agent in the market increases the computation and communication overheads which potentially leads to low scalability \cite{khorasany2019enhancing}. Thus, agents need to prioritize their trading partners based on their preferences and only negotiate with a given number of agents. As stated in section \ref{sub:sec:agent-modeling}, agents have to pay a grid service charge for each transaction as defined in (\ref{service charge}). This charge is directly associated with the distance between the producer \textit{i} and the consumer \textit{j}, and impacts the welfare of the agents. Accordingly, agents are incentivized to trade with trading partners located in close vicinity. This in turn reduces the load on the transformation lines and thus reduces the cost in managing the physical layer. On the other hand, agents may prefer to negotiate with the trading partners with higher reputation factors, indicating their past performance in fulfilling their commitments. Thus, agents need to prioritize their trading partners based on their preferences, which includes reputation factor and distance, and only negotiate with a given number of them. Agents may have varied preferences over reputation factor and distance of their trading partners. Hence, we define a priority index for each possible transaction between producers and consumers. This index for offer from consumer $j$ received by producer $i$, and offer from producer $i$ received by consumer $j$ are defined using (\ref{sell pri index}) and (\ref{buy pri index}) respectively. \begin{equation}\label{sell pri index} \Upsilon_{ij}=\alpha_i \rho_j +\beta_i (1-\cfrac{|\sigma_i -\sigma_j|}{D_{ij}})\\ \end{equation} \begin{equation}\label{buy pri index} \Upsilon_{ji}=\alpha_j \rho_i +\beta_j (1-\cfrac{|\sigma_i -\sigma_j|}{D_{ji}})\\ \end{equation} where \(\alpha\) and \(\beta\) are the weights that agent places on the reputation factor and proximity of other agents, respectively such that \(\alpha+\beta=1\), \(D_{ij}=\underset{\sigma_j}{\max} |\sigma_i-\sigma_j|\), \(D_{ji}=\underset{\sigma_i}{\max} |\sigma_i-\sigma_j|\). After calculating priority index, each agent divides its trading partners to a set of $\mathcal{N}$ groups and then, starts to negotiate with the agents from the group with the highest priority and proceed to the group with the lowest priority. Each group of potential consumers/producers for producer $i$/consumer $j$ can be formed as \begin{equation}\label{prioritization sell} \Omega_i^n=\{j \in \mathcal{C}| (N-n)/N \leq \Upsilon_{ij} \leq (N-n+1)/N \} , \forall n \in \mathcal{N} \end{equation} \begin{equation}\label{prioritization buy} \Omega_j^n=\{i \in \mathcal{P}| (N-n)/N \leq \Upsilon_{ji} \leq (N-n+1)/N \} , \forall n \in \mathcal{N} \end{equation} in which for consumer $j$, producers in group $\Omega_j^n$ have higher priority than producers in $\Omega_j^{n+1}$. Similarly, for producer $i$, consumers in group $\Omega_i^n$ have higher priority than consumers in $\Omega_i^{n+1}$. \subsection{Negotiation} After \textit{prioritization}, each consumer starts negotiating with producer agents in $\Omega_j^1$. The first step is for consumer \textit{A} to request the grid service charge from the grid operator. \textit{A} sends the list of agents in $\Omega_j^1$ to the grid operator who calculates grid service charge using (\ref{service charge}) and sends response back to \textit{A}. Once, \textit{A} received the grid service charge, it starts the negotiation with agents in $\Omega_j^1$ by sending an \textit{Energy Negotiation} (EN) transaction that is structured as $ <T\_ID, Amount, Price, PK\textsuperscript{D}, Sign\textsuperscript{D}, PK\textsuperscript{+}, Sign, PK\textsuperscript{+},\\ Agreement_P, Agreement_C>$ where \textit{Amount} identifies the total amount of energy demanded by \textit{A} and \textit{price} is the price in which the consumer is willing to pay. \textit{PK\textsuperscript{D}} and \textit{ Sign\textsuperscript{D}} represent PK of the destination agent and its corresponding signature. The destination can be either the producer, when \textit{A} generates the transaction, or \textit{A}, when a producer is the generator of the transaction. This potentially enables routing the transaction to the destination using routing algorithm proposed in \cite{dorri2019spb}. \textit{Sign } and \textit{PK} represent the PK and signature of the transaction generator. Finally, \textit{$Agreement_P$} and \textit{$Agreement_C $} are flags that indicate whether the energy producer or consumer, respectively, agree with all situations in the trade. The generator of EN signs the hash of the transaction content which potentially ensures the integrity of the transaction content. After populating EN, \textit{A} sends the transaction to the energy producers in $\Omega_j^1$. \par The energy producer may potentially receive several EN transactions from consumers. The producer only responds to those who are in the set of $\Omega_i^1$. For each received EN from consumers in this set, the producer updates the price using (\ref{sell price update}). When the response from the producer is received by the consumers, they update their energy using (\ref{buyer power update}) and again respond to the producer. This process continues till both side of the trade agree on the trade conditions and thus set $Agreement_P$ and $ Agreement_C$ as '1'. An EN transaction is considered as valid transaction to be stored in the blockchain only when both energy producer and consumer sign the transaction and $Agreement_P$ and $ Agreement_C$ are set as '1'. This ensures that only the last transaction that contains the trade conditions is stored in the blockchain which in turn increases the blockchain throughput and reduces delay of the negotiation. \begin{algorithm}[t] \caption{Producer's Algorithm}\label{producer lag} \footnotesize{ \begin{algorithmic}[1] \State Submit offer AT \Comment{\textit{Advertisement}}\\ \state Explore AD to find potential trading partners \State Divide consumers in groups $\Omega_i^1, ..., \Omega_i^N$ using (\ref{prioritization sell}) \Comment{\textit{Prioritization}} \State Set $n\gets 1$ \State Receive EN transactions from consumers \Comment{\textit{Negotiation}} \While{$|\lambda_{ij}^{P,k+1}-\lambda_{ij}^{P,k}| \geq \epsilon$} \For {$j \in \Omega_i$} \State Receive $\gamma_{ij}$ from grid operator \State Receive $e_{ji}^{k}$ from consumer \State Calculate $\lambda_{ij}^{k+1}$ using (\ref{sell price update}) \State Update $\overline{\mu}_i^{k+1}$ and $\underline{\mu}_i^{k+1}$ using (\ref{sell mu low update}) and (\ref{sell mu up update}) \State Calculate $e_{ij}^{P,k+1}$ using (\ref{sell energy update}) \State Broadcast $\lambda_{ij}^{P,k+1}$ to consumers \EndFor \EndWhile \State Check if more energy is available \State Set $n\gets n+1$ \State Repeat Negotiation with new consumers \State Receive LP from consumers \Comment{\textit{Energy trading}} \State Inject agreed energy \State Sign EI \end{algorithmic} } \end{algorithm} \begin{algorithm}[t] \caption{Consumer's Algorithm}\label{consumer alg} \footnotesize{ \begin{algorithmic}[1] \State Submit ask AT \Comment{\textit{Advertisement}}\\ \state Explore AD to find potential trading partners \State Divide producers in groups $\Omega_j^1, ..., \Omega_j^N$ using (\ref{prioritization buy}) \Comment{\textit{Prioritization}} \State Set $n\gets 1$ \State Send EN transactions to producers \Comment{\textit{Negotiation}} \While{$|e_j^{P,k+1}-e_j^{P,k}| \geq \epsilon$} \For {$i \in \Omega_j^n$} \State Receive $\gamma_{ij}$ from grid operator \State Receive $\lambda_{ij}^{k}$ from producer \State Update $\overline{\mu}_j^{k+1}$ and $\underline{\mu}_j^{k+1}$ using (\ref{buyer mu low update}) and (\ref{buyer mu up update}) \State Calculate $e_{ji}^{P,k+1}$ using (\ref{buyer power update}) \State Broadcast $e_{ji}^{P,k+1}$ to producers \EndFor \EndWhile \State Check if more energy is needed \State Set $n\gets n+1$ \State Repeat Negotiation with new producers \State Send LP to producers \Comment{\textit{Energy trading}} \State Sign EI \end{algorithmic} } \end{algorithm} \subsection{Energy trading} In this section, we discuss the process in trading energy. Once agents agree on the trade condition, during the negotiation step, the consumer generates a \textit{Late Payment (LP)} transaction that is structured as $<T\_ID, Price, Input, Output, EN\_Ref, Expiry\_Time, \\ Sign>$, where \textit{price} is price to be paid to the energy producer. \textit{Input} is the address of an unspent transaction that has enough balance to pay the transaction price, and \textit{output} is the address of the energy producer as in the last EN transaction. \textit{En\_Ref} is the address of the EN transaction that is stored in the public blockchain. Conventional energy trading frameworks rely on a TTP to oversee the trade and ensure that both side of the trade commit to their obligations which in turn reduces the privacy of the users. To address this challenge, our framework relies on atomic transactions. In the latter, two transactions are considered valid if and only if both are generated within a specified time frame. Any incompatible transaction is considered as invalid and thus is not stored in the blockchain \cite{dorri2019spb}. \textit{Expiry\_Time} represents the time period in which the second transaction corresponding to the current LP must be generated, otherwise, LP is discarded. \textit{Sign} is the signature of the transaction generator that must be corresponding to the PK used in EN transaction. The consumer then broadcasts LP transaction.\par The energy producer starts injecting energy to the grid when it receives the LP transaction. Once the total amount of agreed energy is injected to the grid, the smart meter of the producer generates an \textit{Energy Injection} (EI) transaction which is a multisig transaction and is structured as $ <Amount, LP\_ID, PK\_P, Sign\_P, PK\_C, Sign\_C>$, where \textit{Amount} is the amount of energy injected into the grid by the producer. \textit{LP\_ID} is \textit{T\_ID} of the corresponding LP that is used for verification of the trade as outlined in the next paragraph. EI requires two out of two signatures to be considered as a valid transaction that are the energy producer signature, populated in \textit{PK\_P} and \textit{Sign\_P}, and energy consumer signature, populated in \textit{PK\_C} and \textit{Sign\_C}.\par Once EI is broadcasted to the network, the participating nodes in the blockchain start verifying the energy trade. First, the participants must locate the associated LP and EN. Recall that EI contains the \textit{LP\_ID} and LP contains \textit{EN\_Ref} that is the identifier of the EN transaction. The verifiers first match the signatures and PKs in the transactions. The next step is for the verifiers to validate that the amount and price agreed in the transactions match. Once all the above steps are successfuly validated, EI and LP transactions are stored in the blockchain which triggers the payment of the energy price to the energy producer. If the price in these transactions differ, the verifiers discard those transactions. \par In case of detecting inconsistency in the amount of the injected energy in EI, the verifiers call a \textit{Dispute Resolution} (DR) smart contract. The DR smart contract contains rules to manage the situation where the energy producer failed to transfer the promised amount of energy to the consumer, for example, the energy produced by the solar panel of an energy producer may be less than the estimated production which potentially impacts the traded energy. Based on the amount of transferred energy identified in EI, DR calculates a new energy price and generates a \textit{Price Update (PU)} transaction requesting the energy consumer to generate a new LP with exactly the same condition as the previous one while updating the price. PU is structured as $<LP\_ID, Old\_Price, New\_Price>$. The new LP is broadcast to the network and is stored in the blockchain with the corresponding EI. \par Recall that in our framework, we defined reputation that impacts the decision making of the nodes. The reputation is given by the DR smart contract based on the commitments of an energy producer. In case of the above example, the DR will reduce the reputation of the node and inform all participants. In this study we consider the negative reputation only which is when a node misbehaved in the network. \section{Case Studies}\label{sec: case study} \begin{figure} \input{casestudy} \caption{33-Bus test system}\label{fig:test system} \end{figure} \begin{table}[] \centering \caption{Parameter Setup}\label{tab:parameters} \begin{tabular}{cccc} \hline \multicolumn{4}{c}{\textbf{Key parameters}} \\ \hline Parameter & \multicolumn{1}{c|}{Value} & Parameter & Value \\ \hline $P$ & \multicolumn{1}{c|}{14} & $C$ & 18 \\ $\rho_\lambda$ & \multicolumn{1}{c|}{0.01} & $\rho_\mu$ & 0.001 \\ $\overline{\lambda}^G$& \multicolumn{1}{c|}{5 \cent/kWh^2} &$\underline{\lambda}^G$ & 25 \cent/kWh^2 \\ $N$& \multicolumn{1}{c|}{2} & $\omega$ & 2 \cent/kWh/ km \\ \hline \multicolumn{2}{c|}{\textbf{Producers' parameters}} & \multicolumn{2}{c}{\textbf{Consumers' parameters}} \\ \hline $a_i$ & \multicolumn{1}{c|}{(0.5-1] \cent/kWh^2} & $a_j$ & (0.5-10] \cent/kWh^2 \\ $b_i$& \multicolumn{1}{c|}{[5-10] \cent/kWh} & $b_j$ & [10-20] \cent/kWh \\ $\underline{e}_i$& \multicolumn{1}{c|}{[0-5] kWh} & $\underline{e}_j$ & [1-4] kWh\\ $\overline{e}_i$& \multicolumn{1}{c|}{[5-10] kWh} & $\overline{e}_j$ & [6-10] kWh \\ $\eta_i,\alpha_i,\beta_i$& \multicolumn{1}{c|}{[0-1]} & $\eta_j,\alpha_j,\beta_j$ & [0-1] \\ \hline \end{tabular} \end{table} In this section, simulation case studies are provided to verify the operation of the proposed framework. As shown in Fig. \ref{fig:test system}, the considered test system is the IEEE 33-bus distribution system with 16 producers and 16 consumers. Table \ref{tab:parameters} summarizes key parameters, and range of values for producers and consumers parameters. Fig. \ref{fig: power and price res} illustrates the results of P2P trading in the test system. The traded energy and price in different transactions have various values based on the agents preferences. Agents tend to trade energy with their closest neighbor agents to pay less grid service charge. For example, consumer at bus 1 buys energy from producer at bus 18. However, if the offer/ask from the agent at nearest node is not available, or does not satisfy the requirement of the agents, they have to trade with other neighboring agents. For instance, while the nearest agents to agent 5 are agents at bus 4 and 6, this agent trades energy with producers at bus 26 and 27. Since agents 4 and 6 have preferred to trade with other neighboring nodes (agents at bus 3 and 7 respectively), their offers are not available to the agent 5. We can see that agents 16 and 17 do not buy any energy in the market. These agents have lower utility function parameter compared to their neighboring agents, which means that their willingness to pay for energy is less than agent 15, and hence, producer at bus 14 prefers to trade with agent at bus 15. \begin{figure} \centering \includegraphics[scale=0.51]{figures/powerandprice.pdf} \caption{Transactions between producers and consumers; a) traded energy, b) energy price.}\label{fig: power and price res} \end{figure} To investigate the impact of considering grid service charge on the number of transactions ($n_T$), we implemented the energy trading algorithm for different values of $\omega$. The results are reported in Fig. \ref{fig:line flow}, where each marker indicates a transaction between producer and consumer and total number of transactions in each case is given in parentheses. The case with \(\omega=0\) means that there is not limit on the distance of agents and they can trade with any number of agents. Therefore, the number transactions in this case is significantly higher. Increasing the value of ($\omega$) reduces the number of transactions, and correspondingly reduces the welfare of agents as they have to trade less energy and pay more cost for utilizing the grid. \begin{figure} \centering \includegraphics[scale=0.9]{figures/lineflow.pdf} \caption{Impact of considering grid service charge on the number of transactions.}\label{fig:line flow} \end{figure} The negotiation among agents is an iterative process and the time required for agents to reach agreement depends on several factors including, number of agents, number of iterations required for convergence in Algorithm \ref{producer lag} and \ref{consumer alg}, computation time required to solve (\ref{sell update dec}) and (\ref{buyer update dec}) by agents in each iteration, and communication time. The results of the implementing the market settlement algorithm with and without implementing \textit{prioritization} step are compared as reported in Table \ref{tab:prioritization}. The \textit{prioritization} step reduces the number on negotiating agents, and hence, reduces the number of communication in each iteration. On the other hand, agents need less time to solve (\ref{sell update dec}) and (\ref{buyer update dec}), as they have less decision variables after \textit{prioritization}. Therefore, applying \textit{prioritization} reduces the negotiation time among agents. \begin{table}[tb!] \centering \caption{Impact of Prioritization}\label{tab:prioritization} \setlength{\tabcolsep}{5pt} \begin{tabular}{lcc} \cline{2-3} \\[-0.7em] & \textbf{w prioritization} & \textbf{w/o prioritization} \\ \\[-0.7em] \hline No. of decision variables & \multirow{2}{*}{38, 16} & \multirow{2}{*}{20, 6} \\ \\[-1em] (producer, consumer) & & \\ \\[-1em] No. of communications & \multirow{2}{*}{63} & \multirow{2}{*}{252} \\ \\[-1em] (in each iteration) & & \\ \\[-1em] No. of iterations for convergence & 163 & 206 \\ \\[-1em] \hline Negotiation time (s) & 1.04 & 1.88 \\ \\[-1em] \hline \end{tabular} \end{table} \begin{table}[tb!] \centering \caption{Comparative results of P2P market} \label{tab:p2p results} \setlength{\tabcolsep}{5pt} \begin{tabular}{lcc} \cline{2-3} \\[-0.7em] & \textbf{P2P} & \textbf{No P2P} \\ \\[-0.7em] \hline Total imported energy from grid (kWh) [$\sum_j{e_j^G}$] & 22.31 & 119 \\ \\[-1em] Total exported energy to grid (kWh) [$\sum_i{e_i^G}$] & 8.46 & 105 \\ \\[-1em] Total welfare of consumers ($\cent$) [$\sum_j{W_j}$] & 62.73 & -4143.04 \\ \\[-1em] Total welfare of producers ($\cent$) [$\sum_i{W_i}$] & 242.64 & -302.03 \\ \\[-1em] Total paid grid service charge ($\cent$) [$\sum_j \sum_i {e_{ij}^p \gamma_{ij}}$] & 50.44 & 0 \\ \hline \end{tabular} \end{table} In order to demonstrate the efficacy of the P2P market, the results of this market are compared with the case that producers and consumers only trade with the grid. Comparative results are reported in Table \ref{tab:p2p results}. As it can be inferred from the results, P2P market reduces the imported and exported energy by agent to the grid. Also, since the P2P market price is more beneficial for agents (see (\ref{price lim})), they can reach higher value of welfare in the P2P market, though they have to pay a grid service charge to the grid operator. As stated in Section \ref{sub:sec:advertisement}, in the proposed framework the ATs are stored off the chain in AD. Here, we study the impact of using AD by evaluating the blockchain size and number of consensus rounds. Blockchain size shows the amount of saved storage space by employing AD while number of consensus rounds evaluates the amount of computational overhead saved by running less consensus rounds. We employed the structure and configuration of IEEE 33-bus distribution to implement a distributed network using Java programming language. We assumed that the size of each block is 10 transactions and we disregarded the consensus algorithm as it does not impact the functionality of the proposed method. We run the network for 10 epochs. During each epoch, each energy producer generates an AT. To benchmark the results, we assume a baseline method where all ATs are stored in the blockchain. To focus on the impact of AD, we disregard the rest of the functions and assume ATs are the only transactions generated during each epoch. Based on the implementation results, the size of each advertisement transaction is 1776 B. After 10 epochs the baseline blockchain includes 16 blocks with the cumulative size of 314KB. Thus, each node must allocate 314KB storage space to store blockchain. Our solution off-loads this overhead to a central trusted node who is managing the AD, thus there is no memory overhead on the participating nodes in the blockchain. Assume $\nu $ represents the mining overhead that can include computational, packet and memory overhead. Then, the proposed framework incurs no overhead during advertisement process in the miners while conventional methods 16$\nu$. We next evaluate the processing overhead associated with CoL. We proposed a CoL that enables the users to anonymously verify the location of the parties involved in energy trading. CoL enhances the anonymity level of users and thus protects the user privacy. On the flip side, it increases the processing overhead on the users to generate and verify CoL. To evaluate the incurred overhead, we implemented our framework using Java programming language on Raspberry Pi 2 which represents low-resource devices. We measured the processing time for generating the CoL request, which involves generating a set of keys and forming the Merkle tree, and verifying the CoL which involves verifying the existence of the PK in the Merkle tree and validating the corresponding signatures. The implementation results are shown in Table \ref{tab:COL-performance}. The verification of the CoL involves verifying two signatures which potentially takes longer time than generating CoL. In addition to the processing overhead, CoL increases the size of the transactions. Table \ref{tab:COL-packet} compares the size of transactions and represents the impact of CoL. \par \begin{table}[tb!] \centering \setlength{\tabcolsep}{5pt} \caption{Analyzes of CoL performance.}\label{tab:COL-performance} \begin{tabular}{ccc} \hline & CoL formation & CoL verification \\\hline Processing time (ms) & 663.2 & 1795 \\\hline \end{tabular} \end{table} \begin{table}[tb!] \centering \setlength{\tabcolsep}{5pt} \caption{Analyzes of CoL performance.}\label{tab:COL-packet} \begin{tabular}{ccccc} \hline & AT & EN & LP & EI \\\hline Including CoL (B) & 2193 & 1928 & 1056 & 1912 \\\hline Excluding CoL (B) & 1041 & 1928 & 1056 & 1912 \\\hline \end{tabular} \end{table} \section{Security and Privacy Analysis}\label{sec:security} In this section we analyze the security and privacy of the proposed framework. We first outline threat mode and then discuss possible attacks and how to protect against those.\par \textbf{\textit{Threat Model:}} We assume that the adversary (or cooperative adversaries) can sniff the communications, discard transactions, generate fake transactions, and pretend to be another node in the network. The adversary may attempt to deanonymize a user by classifying blockchain transactions and monitoring real-time communications in blockchain. We assume standard secure encryption algorithms are in place which cannot be compromised by the adversary. We assume smart meters are tamper resistance and thus the end users cannot modify the transactions generated by the meters. \par \subsection{Security} In the following we discuss possible attacks and how the proposed framework protects against those. \par \textit{CoL Reply Attack:} In this attack, the malicious node attempts to employ CoL of another node to generate transactions. The node that employs a CoL is required to sign the corresponding transaction with the private key corresponding to a PK that exists in MTR that is only known to the CoL generator. Thus, it is impossible for a malicious node to utilize the CoL of another node. \par \textit{Fake CoL:} In this attack, a malicious node pretends to be a genuine smart meter generates fake CoL that can later be used in its energy tradings. The CoL must be signed only by a genuine smart meter and the CA validates the PK of the verifier. In case of this attack, CA will not validate PK and thus the attack can be detected. \par \textit{Double spending:} In this attack, a malicious energy producer attempts to sell the same amount of energy to different consumers. Recall from Section \ref{sec:energy trading} that an energy trade involves three main transactions which are EN, LP, and EI. Once the agreed energy is injected to the grid, the smart meter of the energy producer generates a EI transaction that trigers the payment of the energy price to the producer. The smart meter generates only one EI that includes a reference to the corresponding LP and LP includes a reference to the corresponding EN. Thus, it is impossible for the energy producer to sell the same energy to multiple nodes. \par An energy producer may attempt to inject less energy than the agreed amount and claim the full price. The smart meter of the producer will only generate the EI if the full amount of agreed energy is injected to the grid. If the energy producer injects part of the energy and the expiry time approach, the smart meter will generate an EI reflecting the amount that is injected to the grid. In this case, DR smart contract is called that adjusts the price of the energy and ensues the producer is only paid for the amount of energy injected to the grid. \par \textit{Reputation Modification:} In this attack, the malicious node attempts to improve their reputation or reduce the reputation of another node in the network. Recall that blockchain is an immutable ledger that makes it impossible to modify or remove previously stored transactions, which makes it impossible for the attacker to modify their reputation. To reduce the reputation of another node, the malicious node shall modify the code of the smart contract which is impossible due to the immutability of the blockchain. DR smart contract is the only entity that can reduce the reputation of a node. All participants know the address of the valid DR contract. When participating nodes receive reputation reduction from a contract, they first verify if the contract address matches with the genuine DR smart contract. If so, they accept the new reputation. Otherwise, they discard the transaction. \subsection{Privacy} In the following we analyze the proposed framework from privacy perspective. Recall from Section \ref{sec:energy trading} that the grid operator charges a grid service charge per each transaction that depends on the distance between the energy consumer and producer. Thus, the consumer and producer require to prove their location, however, this may compromise their privacy as malicious nodes can classify the blockchain transactions to deanonymize the user. To address this challenge, we proposed A-PoL that enables the participants in the blockchain to verify the location of an anonymous smart meter using a CoL. Assume node \textit{A} is using A-PoL. The privacy of \textit{A} can be studied from the perspective of the following entities: i) CA: \textit{A} uses the PK populated by the CA only to prove its identity to the verifier. CoL employed by \textit{A} includes PK of the verifier and not \textit{A}. Given that the verifier is selected randomly by \textit{A} and there is no link between \textit{A} and the verifier, the CA is unable to identify the transactions generated by \textit{A}, ii) verifier: \textit{A} only sends MTR to the verifier that hides the actual PKs of \textit{A} from the verifier. \textit{A} reveals the PKs in the Merkle tree to prove ownership on CoL. A group of smart meters may choose to create a single MTR which further protects their privacy, and iii) network participants: the network participants only receive CoL that contains of the verifier and MTR. As outlined earlier, there is no link between the verifier and \textit{A}, thus knowledge of the identity of the verifier does not impact the privacy of \textit{A}. The Merkle tree includes a number of PKs that are employed by \textit{A} (or other involved smart meters) to generate transactions, thus, \textit{A} may generate multiple transactions with the same PK. This potentially reduces the anonymity level of the user as malicious nodes may attempt to deanonymize a user by classifying their transactions. The anonymity level of \textit{A} largely depends on the number of PKs employed in the Merkle tree. Large number of PKs incur overheads on \textit{A} to manage the keys. Thus, there is a trade-off between the number of keys in Merkle tree and the user anonymity. \par Recall from Section \ref{sub:sec:market-settlement} that the energy producer and consumer employ a cost/utility function, as shown in (\ref{cost-func-producer}) and (\ref{cost-function-consumer}), which represent their willingness to pay or accept energy price based on their preferences and concerns. These functions depends on $a_i$, $b_i$ and $c_i$ and thus it is critical for the producers and consumers to keep these values private. In the proposed framework, the market settlement does not need the nodes to reveal $a_i$, $b_i$ and $c_i$ which in turn enhances the privacy of the users. \section{Conclusion and Future Work}\label{sec:conclusion} In this paper a blockchain-enabled framework for P2P energy trading is proposed. -We can relax the assumption that the smart meters are seure - We assumed that the smart meter location is fixed and known by the CA. how the mobility of the meter may impact this? \bibliographystyle{IEEEtran} \section{Introduction} In response to climate change concerns, the decarbonization and digitization of the electricity sector have been accelerated in recent years. The path toward decarbonization is associated with the high penetration of Distributed Energy Resources (DERs), such as rooftop solar, home batteries, and Electric Vehicles (EVs) with the potential to support a reliable, affordable and lower-emissions electricity grid. Progressive deployment of DERs raises several opportunities and challenges in the electricity systems \citep{openenergy}. Technical challenges include the increase in bidirectional power flows, the raise in the voltage levels, and lack of visibility \citep{coster2010integration}. On the other side, efficient DER integration can provide substantial benefits for energy customers \citep{aemo}. DER owners can benefit from Feed-In-Tariffs (FiTs) programs by selling energy back to the utility grid for a fixed price \citep{ye2017analysis}. Alternatively, they can be coordinated and orchestrated for participation in different markets. \begin{figure}[t!] \centering \includegraphics[scale=0.5]{figures/no.png} \end{figure} Given this context, Transactive Energy (TE) is emerging as a new approach for orchestrating and coordinating operation of DERs. TE is a market-based approach for energy management, which uses price signals to coordinate demand and supply across the network and among all users and entities \citep{council2015gridwise}. TE approach facilitates integration of DERs in the grid, while maintaining the system reliability \citep{liu2017transactive}. It provides a transformative solution to technological and socioeconomic challenges of the power grid modernization \citep{li2019blockchain}. Built upon the context of TE, a novel technique for the integration of small-scale producers and consumers to energy markets is Peer-to-Peer (P2P) trading, which allows bilateral energy transactions between users \citep{tushar2020peer}. P2P trading provides significant benefits for both end users and grid operators such as increasing welfare by preference satisfaction \citep{morstyn2018using}, lowering operational costs, and improving system reliability \citep{mengelkamp2018designing}. P2P trading offers the flexibility required to coordinate agents with diverse preferences. Recent advances in the Internet of Things (IoT) and digital technologies have paved the path toward grid digitization. Grid digitization provides a two-way communication network that allows DER owners and energy consumers to act as proactive agents in the energy markets and facilitates P2P market implementation. Through direct interaction of agents in a decentralized platform, small-scale producers are allowed to compete with large traditional suppliers, and consumers have the freedom to select their energy suppliers based on their preferences. In the P2P trading, it is expected that market participants can settle the bilateral transactions with least influence from a central authority \citep{giotitsas2015peer}. Hence, designing a decentralized platform for managing market participants with diverse preferences is a challenging task. Blockchain technology offers new opportunities for decentralized market designs due to its salient features which includes decentralization, trust, anonymity, and auditability. Blokchain enables energy producers and consumers to directly negotiate and trade energy without reliance on Trusted Third Party (TTP). It provides a platform to store and share data in a secure and verifiable manner, even when the identity and trustworthiness of market participants are unknown \citep{van2020integrated}. The participating nodes in the blockchain, that includes energy consumers, producers, prosumers, or grid operators, jointly form an overlay network where they can exchange information \citep{wu2019comprehensive}. Given the properties of blockchain, and the need for a truly decentralized platform for P2P trading, designing blockchain-enabled frameworks for P2P trading is gaining momentum in recent years. The blockchain framework for P2P trading should incorporate an appropriate market settlement approach to match trading peers and to settle the bilateral transactions among them. Compared to traditional markets, P2P market offers more flexibility and trading options to the agents, and hence, it needs a pricing mechanism that incentivizes both producers and consumers to participate in the market. There are several approaches that can be applied to P2P market clearing and peer matching, such as auction-based mechanism, game theory, and optimization-based methods \citep{li2018location, paudel2018peer, khorasany2019decentralised}. In the auction-based mechanism, agents express their interest in energy trading by submitting their offers, and the energy allocation and price would be determined based on the market clearing rules \citep{li2018location}. The game theory approaches aim to provide a stable solution that is beneficial for all parties \citep{paudel2018peer}. In the optimization-based methods, the market settlement is formulated as an optimization problem, which can be decomposed to local subproblems solvable by each agent \citep{khorasany2019decentralised}. The optimization-based methods can be implemented in a decentralized manner without any need for third party interventions, which allows agents to optimize their welfare by participating in the P2P market. Hence, these methods are well-suited for blockchain-enabled P2P markets. However, the computation and communication overheads of these methods are of concern, as they require agents to iteratively negotiate to reach agreements on their actions. Therefore, reducing these overheads is a key requirement This paper designs a blockchain-enabled P2P market that provides a secure and transparent environment for the energy trading of producer and consumer agents. In the proposed approach, agents \textit{Advertise} their surplus/deficit energy during each market interval. We use an Advertisement Database (AD) that is centrally managed by the grid operator to skip storing advertisement in public blockchain, which in turn, reduces the blockchain memory footprint. A decentralized optimization algorithm is employed for the \textit{Negotiation} that allows agents to iteratively optimize their welfare in the negotiation process. In order to reduce the computation and communication overheads, a \textit{Prioritization} step is considered in the market settlement process that enables agents to prioritize their trading partners based on their proximity and reputation factor. Network constraints should be incorporated in the P2P trading to ensure that energy transactions respect electric grid constraints. Instead of enforcing network constraints directly to the proposed framework, we define a grid service charge for each transaction. To incentivize agents to trade energy with their neighboring agents and reducing network loading, this charge is calculated based on the electrical distance between producer and consumer. To this end, we propose an Anonymous Proof of Location (A-PoL) algorithm that enables agents to prove their location without revealing their real identity. Once the energy consumer and producer agree on the conditions of the trade, they start trading the energy. To reduce the reliance on TTP yet ensure the security of the trade, we adopt the concept of atomic meta-transactions~\citep{dorri2019spb} where two transactions are considered valid only if they are generated within a particular period of time. The contributions of this paper are summarized as follows: \begin{itemize} \item [-] a decentralized P2P trading framework that does not require access to private information of agents in any stage of the market settlement; \item[-] a novel \textit{prioritization} step to allow agents to select their trading partners based on their location and reputation in order to reduce the system overheads; \item[-] a new A-PoL algorithm, which uses a Certificate of Location (CoL) issued by smart meters to approve the location of agents without revealing their real identity. \end{itemize} The rest of this paper is organized as follows. Section \ref{sec:related} explains some related work. Section \ref{sec: market structure} outlines the structure of the market, including agents modeling, market objective, and decentralized optimization of the market objective. Section \ref{sec:energy trading} explains the market settlement process and its different steps. Case studies and numerical results are reported in Section \ref{sec: case study}. A detailed analysis of the security and privacy of the proposed framework is presented in Section \ref{sec:security}. Finally, concluding remarks are given in Section \ref{sec:conclusion}. \section{Prior Art}\label{sec:related} In recent years blockchain applications in energy systems, such as demand response, microgrid energy management, EV integration, and energy trading, has attracted tremendous attention due to its salient features including decentralization, transparency, trust, and immutability \citep{andoni2019blockchain,musleh2019blockchain}. In \citep{van2020cooperative}, a decentralized framework for cooperative demand response is presented, in which smart contracts are employed to allow participants to collaboratively decide on their planning profiles. Su \textit{et. al} \citep{su2018secure} employed blockchain to implement secure charging services for EVs with the execution of smart contracts. In \citep{noor2018energy}, blockchain technology is utilized to implement a demand side energy management method for the efficient operation of microgrids. Hassan \textit{et. al} \citep{hassan2019deal} developed a blockchain-based approach for microgrid energy auction, in which to reduce computational complexity, at every node consortium blockchain is used that authorizes only selected nodes to add a new block in the blockchain. The application of blockchain for P2P energy trading has been investigated in several studies. The Brooklyn microgrid is a prototype of a blockchain-enabled P2P market, in which a blockchain framework is employed to implement a decentralized microgrid energy market \citep{mengelkamp2018designing}. A unified blockchain framework for various scenarios of energy trading in an industrial IoT is proposed in \citep{li2017consortium}, in which a credit-based payment scheme is employed to overcome the transaction limitation caused by transaction confirmation delays. An operation framework for P2P energy trading at the distribution level is presented in \citep{wang2019energy}, where the system operator clears the market using a crowdsourced energy system model. Dang \textit{et. al} \citep{dang2019demand} proposed a blockchain-based P2P market for optimal load management of big industrial users, in which users can organize their own P2P market to save their electricity costs. In \citep{luo2018distributed}, a two-layer system for distributed electricity trading among prosumers is proposed, in which in the first layer prosumers can form coalitions and negotiate energy trading, and in the second layer blockchain is employed for settlement of transactions formed in the first layer. A methodology for the co-simulation of power distribution networks and local P2P energy trading platforms is presented in \citep{hayes2020co}, in which a blockchain-based distributed double auction trade mechanism is employed to model the trading platform. The existing blockchain-based frameworks for energy trading suffer from: \textit{(i) negotiation overheads:} the decentralized optimization methods rely on iterative negotiation between involved agents. In a market with large number of participants, this iterative process increases the communication and computation overheads, and consequently the negotiation time. \textit{(ii) Reliance on a TTP:} most of the existing studies rely on a TTP to oversee the trade and ensure that both sides of the trade commit to their obligations. However, this potentially may lead to centralization and privacy concerns as TTP can build virtual profile about the users. \textit{(iii) Blockchain overheads:} in conventional blockchain-based methods in smart grids, all communications are stored in the blockchain, which in turn increases the blockchain memory footprint and thus reduces scalability. In this regard, this paper proposes a blockchain-enabled P2P market that alleviates the above-mentioned limitations. \section{The Market Structure}\label{sec: market structure} \begin{figure}[tb!] \centering \includegraphics[scale=0.8]{figures/marketlayer.pdf} \caption{An overview of the proposed blockchain-enabled P2P energy trading.} \label{fig:layers} \end{figure} In this section, we outline the details of the market structure. As shown in Fig. \ref{fig:layers}, the proposed architecture consists of two layers: i) physical layer that is the underlying physical network to transfer electricity from producers to consumers. The minimum requirement for a successful transaction between a producer and a consumer is the existence of a path to transfer power between them, and ii) information layer where the participating nodes, that includes energy producer, consumer, and the grid operator, connect through a public blockchain to share information. The information layer provides a secure platform for the participating nodes to advertise their energy, negotiate on their offers, and decide on their actions in the market. The market mechanism is implemented in this layer that enables the agents to trade energy and settle energy transactions. \par \subsection{Agents modeling}\label{sub:sec:agent-modeling} We consider an energy network with a set of agents consisting of a set of producer agents with index \(i \in \mathcal{P}=\{1, ..., P\}\) and a set of consumer agents with index \( j \in \mathcal{C}=\{1, ..., C\}\) connected to a physical layer manged by a grid operator. Producers have energy producing capability and can use their own generated energy for their demand. In case there is more generation than demand, producers can sell surplus energy to consumers or to the grid. Consumers, on the other side, can buy energy from producers or the grid. Producers and consumers can negotiate for energy trading in a forward market for any time interval \(t \in \mathcal{T} =\{1, ..., T\}\) with equal duration (e.g., one hour). Agents are equipped with smart meters, which determines the energy surplus/deficit for trade in each time slot. The smart meters are connected to the information layer and thus, can exchange information in blockchain. It is assumed that the smart meters are tamper-resistant. We assume that each agent is equipped with an energy management system that can quantitatively estimate the energy surplus or deficit that needs to be traded in each market interval. Each agent can trade with the grid or with other agents in the network. The total energy surplus and deficit of producers and consumers is represented as \begin{equation}\label{tot energ pro} e_i=e_i^G +\sum_{j \in \mathcal{C}}{e_{ij}^P} \end{equation} \begin{equation}\label{tot energ cons} e_j= e_j^G+\sum_{i \in \mathcal{P}}{e_{ji}^P} \end{equation} where, \(e_i^G\) and \(e_j^G\) are the traded energy between producer $i$/consumer $j$ and the grid respectively, \(e_{ij}^P\) is the sold energy by producer $i$ to consumer $j$, and \(e_{ji}^P\) is the purchased energy by consumer $j$ from producer $i$. Each agent in the P2P market aims to maximize its welfare. The welfare incorporates the utility/cost of energy consumption/generation, cost/revenue of trade with other agents or the grid, and the cost of using grid for the P2P trading. The welfare function of producers and consumers can be modeled by (\ref{pro welf}) and (\ref{con welf}), respectively \begin{equation}\label{pro welf} W_i(e_i, \lambda_{ij},\gamma_{ij})= \underline{\lambda}^G e_i^G +\sum_{j \in \mathcal{C}}{e_{ij}^P (\lambda_{ij}-\gamma_{ij})}-C_i(e_i) \end{equation} \begin{equation}\label{con welf} W_j(e_j, \lambda_{ij},\gamma_{ij})= U_j(e_j)- \overline{\lambda}^G e_j^G -\sum_{i \in \mathcal{P}}{e_{ij}^P (\lambda_{ij}+\gamma_{ij})} \end{equation} where \(\underline{\lambda}^G\) denotes FiT representing the price for selling energy to the grid; \(\lambda_{ij}\) is energy price in transaction between producer $i$ and consumer $j$; \(\gamma_{ij}\) is grid service charge for using grid infrastructure for this trade; \(\overline{\lambda}^G\) denotes the price for selling from the grid which is usually a fixed value over the time (e.g. time of use tariff). The grid selling and buying prices limit energy price in the P2P market, i.e. for any bilateral trade \begin{equation}\label{price lim} \underline{\lambda}^G \leq \lambda_{ij} \leq \overline{\lambda}^G. \end{equation} The cost function of the producer represents the cost of generating energy \(e_i\) and can be modeled as \citep{grainger2003power} \begin{equation}\label{cost-func-producer} C_i(e_i)=a_i e_i^2 +b_i e_i +c_i \end{equation} where \(a_i, b_i\) and $c_i$ are positive constants, which can be adjusted by the producer to reflect the generation cost. Since producers usually have renewable generation resources with zero marginal costs, the cost function can represent the cost associated with battery degradation cost, if the producer needs to discharge its battery to sell the energy. On the other side, the utility function of a consumer represents its satisfaction level by consuming energy $e_j$ and can be modeled as \citep{samadi2010optimal} \begin{equation}\label{cost-function-consumer} U_j(e_j)= \begin{cases} -a_j e_j^2 +b_j e_j \;\;\;\; :0 \leq e_j \leq \frac{b_j}{2 a_j}\\ \frac{b_j^2}{4 a_j} \;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\ :e_j \geq \frac{b_j}{2 a_j} \end{cases} \end{equation} where \(a_j\), and \(b_j\) are unique positive constants for each consumer. These parameters reflect the valuation of the energy by the consumer and denotes the price that consumer is willing to pay for the energy. A fundamental challenge in implementing P2P markets is how to deal with network constraints, without having a central dispatch mechanism. In this work, instead of enforcing network constraints directly, we use a grid service charge for each trade \citep{baroche2019exogenous}. This fee represents the price that agents need to pay for using the grid infrastructure for each trade. To incite agents to trade with their closest electrical partner and to reduce network loading, this charge is calculated based on the electrical distance between producer and consumer as in \begin{equation}\label{service charge} \gamma_{ij}=\omega d_{ij} \end{equation} where \(\omega\) is the grid service charge per unit of electrical distance for each unit of energy, and \(d_{ij}\) is the electrical distance between producer $i$ and consumer $j$. This distance can be calculated based on power transfer distance, which aggregates the absolute value of Power Transfer Distribution Factor (PTDF) induced by a trade as in \begin{equation} \label{eq:ptdf} d_{ij}=\sum_{l \in \mathcal{L}}{\phi^l_{ij}}. \end{equation} For any trade, \(\phi^l_{ij}\) indicates the fraction of transacted power from producer $i$ to consumer $j$ that flows over a line $l$, and can be calculated using the method presented in \citep{wood2013power}. \subsection{Market objective} \label{sub:sec:market-settlement} The market objective for P2P trading is formulated as social welfare maximization, which maximizes the total welfare of players in the market subject to the constraints, and mathematically can be modeled as: \begin{equation}\label{tot objective} \begin{aligned} & \underset{\textbf{\textit{$e_i$,$e_j$}}}{\text{max}} \sum_{i \in \mathcal{P}}{W_i} + \sum_{j \in \mathcal{C}}{W_j}\\ & \text{s.t. constraints.} \end{aligned} \end{equation} As stated in (\ref{price lim}), the prices in the P2P market should always be beneficial for both producers and consumers. Hence, it is reasonable to assume that all agents try to maximize their traded energy in the P2P market and to minimize trading with the grid by setting $e_i^G=e_j^G=0$. Therefore, (\ref{tot objective}) can be rewritten as: \begin{subequations}\label{social welfare} \begin{equation} \begin{aligned} & \underset{\text{\textbf{{$e_{ij}$,$e_{ji}$}}}}{\text{max}} \sum_{j \in \mathcal{C}}{U_j(e_{ji})} - \sum_{i \in \mathcal{P}}{C_i({e_{ij}})} - \sum_{j \in \mathcal{C}}{\sum_{i \in \mathcal{P}}}{(e_{ij}+e_{ji})\gamma_{ij}}\\ \end{aligned} \end{equation} \begin{equation}\label{producer flex} \text{s.t.} \;\;\; \underline{e_i} \leq \sum_{j \in \mathcal{C}}{e_{ij}^P} \leq \overline{e_i} \;\;\;\;\;\;\;\;\;\; :\underline{\mu_i}, \overline{\mu_i} \end{equation} \begin{equation}\label{consumer flex} \underline{e_j} \leq \sum_{i \in \mathcal{P}}{e_{ji}^P} \leq \overline{e_j} \;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\; :\underline{\mu_j}, \overline{\mu_j} \end{equation} \begin{equation}\label{demand supply} e_{ij}^P=e_{ji}^P \;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\; :\lambda_{ij} \end{equation} \end{subequations} where (\ref{producer flex}) and (\ref{consumer flex}) represents the flexibility constraints of producer, and consumer, respectively. The constraint (\ref{demand supply}) represents the power balance in transaction between producer $i$ and consumer $j$. \(\underline{\mu_i}, \overline{\mu_i}, \underline{\mu_j}, \overline{\mu_j}, \lambda_{ij}\) are dual variables associated with these constraints. \subsection{Decentralized optimization} \label{sub:sec:coordination} In this paper, our aim is to solve (\ref{social welfare}) with only P2P communications to ensure data privacy of the agents. To do so, a decentralized optimization approach is employed to formulate the market settlement in P2P market \citep{khorasany2019decentralised}. In this approach, dual variables are used to decouple constraints, and then, the problem is decomposed to local subproblems solvable by producers and consumers. The local subproblem is solved by deploying the sub-gradient projection method \citep{boyd2011distributed}. Each agent contributes to solving the global problem by updating its local decision variables. The set of decision variables for producers and consumers are \{\(\lambda_{ij}, e_{ij}^P, \underline{\mu_i}, \overline{\mu_i}\}\), and \{\( e_{ji}^P, \underline{\mu_j}, \overline{\mu_j}\)\}, respectively. The market settlement approach is an iterative process, in which agents update their decision variables iteratively and exchange information without revealing their private information. The updates of the decision variables of agents are based on the Karush–Kuhn–Tucker (KKT) optimality conditions of the local problems, and can be developed using first order deviate of the relaxed problem as follows:\\ \(\forall i \in \mathcal{P}\) \begin{subequations}\label{sell update dec} \begin{equation}\label{sell price update} \lambda_{ij}^{k+1}=\left[\lambda_{ij}^{k}-\rho_{\lambda}^k(e_{ij}^{P,k}-e_{ji}^{P,k})\right]^{+} \end{equation} \begin{equation}\label{sell mu low update} \underline{\mu_i}^{k+1}=\left[\underline{\mu_i}^{k}+\rho_{\mu}^k(\underline{e_i}-e_i^k)\right]^{+} \end{equation} \begin{equation}\label{sell mu up update} \overline{\mu_i}^{k+1}=\left[\overline{\mu_i}^{k}+\rho_{\mu}^k(e_i^k-\overline{e_i})\right]^{+} \end{equation} \begin{equation}\label{sell energy update} e_{ij}^{{P,k+1}}= \left[e_{ij}^{{P,k}}+\zeta_{ij}^k(\tilde{e}_{ij}^{P,k+1}-e_i^k)\right]^{+}\\ \end{equation} \begin{equation}\label{set point sell update} \tilde{e}_{ij}^{P,k+1}=\frac{\lambda_{ij}^{k+1}-\gamma_{ij}-\overline{\mu_i}^{k+1}+\underline{\mu_i}^{k+1}-b_i}{2 a_i} \end{equation} \end{subequations} \(\forall j \in \mathcal{C}\) \begin{subequations}\label{buyer update dec} \begin{equation}\label{buyer mu low update} \underline{\mu_j}^{k+1}=\left[\underline{\mu_j}^{k}+\rho_{\mu}^k(\underline{e_j}-e_j^k)\right]^{+} \end{equation} \begin{equation}\label{buyer mu up update} \overline{\mu_j}^{k+1}=\left[\overline{\mu_j}^{k}+\rho_{\mu}^k(e_j^k-\overline{e_j})\right]^{+} \end{equation} \begin{equation}\label{buyer power update} e_{ji}^{P,k+1}= \left[e_{ji}^{P,k}+\zeta_{ji}^k(\tilde{e}_{ji}^{P,k+1}-e_j^k)\right]^{+} \end{equation} \begin{equation}\label{buyer set point update} \tilde{e}_{ji}^{P,k+1}=\frac{b_j-\lambda_{ij}^{k+1}-\gamma_{ij}-\overline{\mu_j}^{k+1}+\underline{\mu_j}^{k+1}}{2 a_j} \end{equation} \end{subequations} where $k$ is the iteration index, \(\tilde{e}_{ij}^{P}, \tilde{e}_{ji}^{P}\) are optimal power set points of producer and consumer at the price \(\lambda_{ij}\). \(\zeta_{ij}, \zeta_{ji}\) are asymptotically proportional factors, \(\rho\) is a small tuning parameter, and \([.]^+\) denotes max \{.,0\}. The information exchange between producers and consumers during the decentralized optimization process is explained in Section \ref{sec:neg}. \begin{figure}[tb!] \centering \input{marketsettlement} \caption{Market settlement algorithm.}\label{fig:full algorithm} \end{figure} \section{Market Settlement Process}\label{sec:energy trading} In this section, we outline the details of the market settlement process for P2P trading. The proposed framework consists of four main phases namely; \textit{(i) Advertisement:} to enable agents to advertise the energy that they want to trade, \textit{(ii) Prioritization:} to allow agent prioritize their trading partners based on their preferences, \textit{(iii) Negotiation:} in which agents negotiate on the energy quantity and price in each transaction, and \textit{(iv) Energy trading:} which is the step that energy transfer and payment would be taking place. These steps are summarized in Fig. \ref{fig:full algorithm} and discussed in detail in the rest of this section. \subsection{Anonymous proof of location} As shown in (\ref{service charge}) in the proposed framework the grid service charge is calculated based on the location of the participants denoted by $\sigma$ which requires the involved parties to reveal their location. However, this potentially enables the malicious nodes to track the activities of a particular user, which in turn compromises user privacy. Additionally, the distributed and anonymous nature of blockchain makes it challenging for the users to verify the location claimed by another node. To address these challenges, we propose an A-PoL algorithm that enables the users to prove their location while protecting their real identity, which in turn enhances the level of anonymity offered to the users. The proposed A-PoL algorithm involves a CoL that is issued by a smart meter in the network, as shown in Fig. \ref{fig:CoL}. The energy companies maintain a local record of the accurate location of the installed smart meters. During the installation process, the energy company deploys a key pair in each smart meter (step 1 in Fig. \ref{fig:CoL}) and records $<PK,location>$ tuple in its local storage. The company serves as a certificate authority (CA) for PKs deployed in smart meters. Although the CA is a trusted authority, relying on the PK provided by the CA may compromise the privacy of the users as the company can build a virtual profile of the user and their energy trading (by observing the proof of location transactions). To address this challenge, we propose CoL. \par CoL is a certificate received from a verifier that is an independent smart meter in the network. Assume smart meter \textit{A} is going to establish a CoL. Once deployed on site, \textit{A} explores the CA to find potential smart meters that can function as the verifier and selects one randomly. Assume smart meter \textit{B} is selected by \textit{A} to function as the verifier. Recall that we assume the smart meters are tamper resistant, and thus \textit{A} can send its request to any meter listed in CA. \textit{A} sends a CoL request transaction to \textit{B} that is structured as $<T\_ID, MTR, \sigma, PK, Sign>$, where \textit{T\_ID} is the unique identifier of the transaction which essentially is the hash of the transaction content. \par \textit{A} populates the root hash of a Merkle tree constructed by recursively hashing a number of PKs in the \textit{MTR} field. The PKs in the leaves of the tree are later employed by \textit{A} to prove ownership on the CoL, which is discussed in greater detail later in this section. The number of PKs may vary based on the application. $\sigma$ is the noisy location of the smart meter that can be the location at a lower resolution, e.g., the street in which the meter is installed. This protects the privacy of the smart meter against deanonymization, as studied later in Section \ref{sec:security}. \textit{PK} is the PK of \textit{A} allocated by the CA, and \textit{Sign} is the corresponding signature, which proves that \textit{A} owns the private key corresponding to the PK. \par \begin{figure}[tb!] \centering \input{col} \caption{An overview of the proposed CoL.} \label{fig:CoL} \end{figure} When the verifier, i.e. \textit{B} receives the CoL request, it verifies that the transaction is generated by a genuine smart meter that is done by requesting the CA (step 3). To protect the privacy of the user, the CA does not reveal the actual location of the smart meter to \textit{B} instead, only confirms if the PK is registered and genuine smart meter. Once verified, the verifier creates a CoL that is \textit{sign(hash(MTR, $\sigma$))} and replies back to \textit{A} by sending the reply transaction structured as $<CoL, PK, Sign>$, where CoL is as outlined above, \textit{PK} is the PK of the verifier, i.e., \textit{B} registered by the CA, and \textit{Sign} is the corresponding signature of the verifier. \par \textit{A} employs the received CoL to anonymously prove its location to the nodes in the overlay. To do so, \textit{A} appends $CoL_f^{A} = (CoL_A, PK_{ver}, Sig_{ver}, MTR_A, \sigma_A, PK_A, MTL_A, Sign_A)$ where the first three fields are extracted from the response of the verifier \textit{B}. MTR and $\sigma_A$ are extracted from the CoL request sent to the verifier. \textit{$PK_A$} is a PK that was part of the leaves of the Merkle tree. $MTL_A$ is the leaves of the Merkle tree that are necessary to prove the existence of $PK_A$ in the MTR, and $Sign_A$ is the signature corresponding to PK. The last three fields ensure that only the owner of the certificate, who knows the PKs in the Merkle tree and the corresponding private key, can use the certificate. \par To verify the location of \textit{A}, the participating nodes in the blockchain, say \textit{C}, must first verify that $PK_A$ belongs to $MTR_R$ using $MTL_A$. Next, \textit{C} verifies if $Sign_A$ matches $PK_A$. The third step in verifying is to verify if $hash(MTR_A, \sigma_A) = CoL_A$. The final step is for \textit{C} to verify $PK_{ver}$ using CA. This ensures that a genuine smart meter has signed the CoL. If all the above steps successfully passed, the location of \textit{A} is verified. \par Having discussed the details of the proposed A-PoL algorithm, we study the process of P2P energy trading in the rest of this section. The algorithms implemented by producer and consumer agents are represented in Algorithm \ref{producer lag} and \ref{consumer alg}, respectively, and are discussed with greater details in the rest of this section. \subsection{Advertisement}\label{sub:sec:advertisement} The main aim of this phase is for the agents to advertise their energy to the potential consumers/producers. In each market interval, agents participate in the forward market by submitting their offers and asks in the form of \textit{advertisement transaction (AT)} that is structured as follow $ AT = (T\_ID, price/amount, \eta_i, CoL_f^{i})$, where \textit{price/amount} can be either the price of the energy, i.e., $\lambda_i, \forall i\in \mathcal{P}$, if AT is generated by a producer or the amount of requested energy, i.e., $e_j, \forall j\in \mathcal{C}$, if AT is generated by a consumer, and \(\eta\) is the reputation factor of agent.\par In conventional blockchain-based frameworks, the negotiation transactions are stored in the blockchain that provides high auditability. However, this increases the computational and storage resource consumption of the blockchain and limits the throughput, i.e., the total number of transactions that can be stored per second \citep{zhang2020privacy}. These can limit the blockchain scalability while smart grid comprises of a broad range of devices that may produce transactions frequently. To address this challenge, in the proposed framework, the negotiation transactions are stored in a public database managed by the grid operator that is referred to as \textit{Advertisement Database} (AD). The write access of AD is restricted only to the grid operator and other nodes in the overlay have read-only permission. The parties involved in an AT transaction, i.e., energy producers and consumers, may store the transactions locally to be employed as a reference in case of a dispute between parties. The final price and the amount of energy agreed by the participants are later defined during a negotiation which limits future references to AT transaction. Thus, we store AT in AD which potentially reduces the packet overhead and blockchain memory footprint. \begin{algorithm}[tb!] \caption{Producer's Algorithm}\label{producer lag} \footnotesize{ \begin{algorithmic}[1] \State Submit offer AT \Comment{\textit{Advertisement}} \State Explore AD to find potential trading partners \State Divide consumers in groups $\Omega_i^1, ..., \Omega_i^N$ using (\ref{prioritization sell}) \Comment{\textit{Prioritization}} \State Set $n\gets 1$ \State Receive EN transactions from consumers \Comment{\textit{Negotiation}} \While{$|\lambda_{ij}^{P,k+1}-\lambda_{ij}^{P,k}| \geq \epsilon$} \For {$j \in \Omega_i$} \State Receive $\gamma_{ij}$ from grid operator \State Receive $e_{ji}^{k}$ from consumer \State Calculate $\lambda_{ij}^{k+1}$ using (\ref{sell price update}) \State Update $\overline{\mu}_i^{k+1}$ and $\underline{\mu}_i^{k+1}$ using (\ref{sell mu low update}) and (\ref{sell mu up update}) \State Calculate $e_{ij}^{P,k+1}$ using (\ref{sell energy update}) \State Broadcast $\lambda_{ij}^{P,k+1}$ to consumers \EndFor \EndWhile \State Check if more energy is available \State Set $n\gets n+1$ \State Repeat Negotiation with new consumers \State Receive LP from consumers \Comment{\textit{Energy trading}} \State Inject agreed energy \State Sign EI \end{algorithmic} } \end{algorithm} \subsection{Prioritization} After \textit{advertisement} step, agents explore the available ATs in the AD for the negotiation. One-on-one negotiation can increase the delay associated with finalizing the trade as either side of the trade may have higher welfare in trading with another party in the network. Also, negotiation with every agent in the market increases the computation and communication overheads, which potentially leads to low scalability \citep{khorasany2019enhancing}. Thus, agents need to prioritize their trading partners based on their preferences and only negotiate with a given number of agents. As stated in Section \ref{sub:sec:agent-modeling}, agents have to pay a grid service charge for each transaction as defined in (\ref{service charge}). This charge is directly associated with the distance between the producer \textit{i} and the consumer \textit{j}, and impacts the welfare of the agents. Accordingly, agents are incentivized to trade with trading partners located in close vicinity. This reduces the load on the transmission lines and thus reduces the cost in managing the physical layer. On the other hand, agents may prefer to negotiate with the trading partners with higher reputation factors, indicating their past performance in fulfilling their commitments. Thus, agents need to prioritize their trading partners based on their preferences to limit the partner search space. These preferences include reputation factor and distance. Agents may have varied preferences over reputation factor and distance of their trading partners. Hence, we define a priority index for each possible transaction between producers and consumers. This index for offer from consumer $j$ received by producer $i$, and offer from producer $i$ received by consumer $j$ are defined using (\ref{sell pri index}) and (\ref{buy pri index}), respectively. \begin{equation}\label{sell pri index} \Upsilon_{ij}=\alpha_i \rho_j +\beta_i (1-\cfrac{|\sigma_i -\sigma_j|}{D_{ij}})\\ \end{equation} \begin{equation}\label{buy pri index} \Upsilon_{ji}=\alpha_j \rho_i +\beta_j (1-\cfrac{|\sigma_i -\sigma_j|}{D_{ji}})\\ \end{equation} where \(\alpha\) and \(\beta\) are the weights that agent places on the reputation factor and proximity of other agents, respectively such that \(\alpha+\beta=1\), \(D_{ij}=\underset{\sigma_j}{\max} |\sigma_i-\sigma_j|\), \(D_{ji}=\underset{\sigma_i}{\max} |\sigma_i-\sigma_j|\). The second term in (\ref{sell pri index}) and (\ref{buy pri index}) denotes the proximity of each trading partner to the agent, such that for the furthest trading partner of each agent this value is zero. After calculating priority index, each agent divides its trading partners to a set of $\mathcal{N}$ groups and then, starts to negotiate with the agents from the group with the highest priority and proceed to the group with the lowest priority. Each group of potential consumers/producers for producer $i$/consumer $j$ can be formed as \begin{equation}\label{prioritization sell} \Omega_i^n=\{j \in \mathcal{C}| (N-n)/N \leq \Upsilon_{ij} \leq (N-n+1)/N \} , \forall n \in \mathcal{N} \end{equation} \begin{equation}\label{prioritization buy} \Omega_j^n=\{i \in \mathcal{P}| (N-n)/N \leq \Upsilon_{ji} \leq (N-n+1)/N \} , \forall n \in \mathcal{N} \end{equation} in which for consumer $j$, producers in group $\Omega_j^n$ have higher priority than producers in $\Omega_j^{n+1}$. Similarly, for producer $i$, consumers in group $\Omega_i^n$ have higher priority than consumers in $\Omega_i^{n+1}$. \begin{algorithm}[tb!] \caption{Consumer's Algorithm}\label{consumer alg} \footnotesize{ \begin{algorithmic}[1] \State Submit ask AT \Comment{\textit{Advertisement}} \State Explore AD to find potential trading partners \State Divide producers in groups $\Omega_j^1, ..., \Omega_j^N$ using (\ref{prioritization buy}) \Comment{\textit{Prioritization}} \State Set $n\gets 1$ \State Send EN transactions to producers \Comment{\textit{Negotiation}} \While{$|e_j^{P,k+1}-e_j^{P,k}| \geq \epsilon$} \For {$i \in \Omega_j^n$} \State Receive $\gamma_{ij}$ from grid operator \State Receive $\lambda_{ij}^{k}$ from producer \State Update $\overline{\mu}_j^{k+1}$ and $\underline{\mu}_j^{k+1}$ using (\ref{buyer mu low update}) and (\ref{buyer mu up update}) \State Calculate $e_{ji}^{P,k+1}$ using (\ref{buyer power update}) \State Broadcast $e_{ji}^{P,k+1}$ to producers \EndFor \EndWhile \State Check if more energy is needed \State Set $n\gets n+1$ \State Repeat Negotiation with new producers \State Send LP to producers \Comment{\textit{Energy trading}} \State Sign EI \end{algorithmic} } \end{algorithm} \subsection{Negotiation}\label{sec:neg} After \textit{prioritization}, each consumer starts negotiating with producer agents in $\Omega_j^1$. The first step is for consumer \textit{A} to request the grid service charge from the grid operator. \textit{A} sends the list of agents in $\Omega_j^1$ to the grid operator who calculates grid service charges using (\ref{service charge}) and sends the response back to \textit{A}. Once \textit{A} receives the grid service charge, it starts the negotiation with agents in $\Omega_j^1$ by sending an \textit{Energy Negotiation} (EN) transaction that is structured as $ <T\_ID, Amount, Price, PK^{D}, Sign^{D}, PK^{+}, Sign, PK^{+},\\ Agreement_P, Agreement_C>$ where \textit{Amount} identifies the total amount of energy demanded by \textit{A} and \textit{price} is the price in which the consumer is willing to pay. \textit{PK\textsuperscript{D}} and \textit{ Sign\textsuperscript{D}} represent PK of the destination agent and its corresponding signature. The destination can be either the producer, when \textit{A} generates the transaction, or \textit{A}, when a producer is the generator of the transaction. This potentially enables routing the transaction to the destination using the routing algorithm proposed in \citep{dorri2019spb}. \textit{Sign } and \textit{PK} represent the PK and signature of the transaction generator. Finally, \textit{$Agreement_P$} and \textit{$Agreement_C $} are flags that indicate whether the energy producer or consumer, respectively, agree with all situations in the trade. The generator of EN signs the hash of the transaction content which potentially ensures the integrity of the transaction content. After populating EN, \textit{A} sends the transaction to the energy producers in $\Omega_j^1$. \par The energy producer may receive several EN transactions from consumers. The producer only responds to those who are in the set of $\Omega_i^1$. For each received EN from consumers in this set, the producer updates the price using (\ref{sell price update}). When the response from the producer is received by the consumers, they update their energy using (\ref{buyer power update}) and again respond to the producer. This process continues till both sides of the trade agree on the trade conditions and thus set $Agreement_P$ and $ Agreement_C$ as '1'. An EN transaction is considered as a valid transaction to be stored in the blockchain only when both energy producer and consumer sign the transaction and $Agreement_P$ and $ Agreement_C$ are set as '1'. This ensures that only the last transaction that contains the trade conditions is stored in the blockchain, which in turn increases the blockchain throughput and reduces the delay of the negotiation. \subsection{Energy trading} In this section, we discuss the energy trading process. Once agents agree on the trade condition, during the negotiation step, the consumer generates a \textit{Late Payment} (LP) transaction that pays the energy price to the producer. Conventional energy trading frameworks rely on a TTP to oversee the trade and ensure that both sides of the trade commit to their obligations, which in turn reduces the privacy of the users. To address this challenge, our framework relies on atomic meta-transactions. In the latter, two transactions are considered valid if and only if both are generated within a specified time frame. Any incompatible transaction is considered as invalid and thus is not stored in the blockchain \citep{dorri2019spb}. LP is an atomic meta-transactions thus the energy price is not transferred to the producer accoutn unless LP is coupled with another transaction that is discussed in next paragraph. LP is structured as $<T\_ID, Price, Input, Output, EN\_Ref, Expiry\_Time, \\ Sign>$, where \textit{price} is price to be paid to the energy producer. \textit{Input} is the address of an unspent transaction that has enough balance to pay the transaction price, and \textit{output} is the address of the energy producer as in the last EN transaction. \textit{En\_Ref} is the address of the EN transaction that is stored in the public blockchain. \textit{Expiry\_Time} represents the time period in which the second transaction corresponding to the current LP must be generated, otherwise, LP is discarded. \textit{Sign} is the signature of the transaction generator that must be corresponding to the PK used in EN transaction. The consumer then broadcasts LP transaction.\par The energy producer starts injecting energy to the grid when it receives the LP transaction. Once the total amount of agreed energy is injected to the grid, the smart meter of the producer generates an \textit{Energy Injection} (EI) transaction which is a multisig transaction and is structured as $ <Amount, LP\_ID, PK\_P, Sign\_P,\\ PK\_C, Sign\_C>$, where \textit{Amount} is the amount of energy injected into the grid by the producer. \textit{LP\_ID} is \textit{T\_ID} of the corresponding LP that is used for verification of the trade as outlined in the next paragraph. EI requires two out of two signatures to be considered as a valid transaction that are the energy producer signature, populated in \textit{PK\_P} and \textit{Sign\_P}, and energy consumer signature, populated in \textit{PK\_C} and \textit{Sign\_C}.\par Once EI is broadcasted to the network, the participating nodes in the blockchain start verifying the energy trade. First, the participants must locate the associated LP and EN. Recall that EI contains the \textit{LP\_ID} and LP contains \textit{EN\_Ref} that is the identifier of the EN transaction. The verifiers first match the signatures and PKs in the transactions. The next step is for the verifiers to validate that the amount and price agreed in the transactions match. Once all the above steps are successfully validated, EI and LP transactions are stored in the blockchain, which triggers the payment of the energy price to the energy producer. If the price in these transactions differs, the verifiers discard those transactions. \par In case of detecting inconsistency in the amount of the injected energy in EI, the verifiers call a \textit{Dispute Resolution} (DR) smart contract. The DR smart contract contains rules to manage the situation where the energy producer failed to transfer the promised amount of energy to the consumer, for example, the energy produced by the solar panel of an energy producer may be less than the estimated production, which potentially impacts the traded energy. Based on the amount of transferred energy identified in EI, DR calculates a new energy price and generates a \textit{Price Update (PU)} transaction requesting the energy consumer to generate a new LP with exactly the same condition as the previous one while updating the price. PU is structured as $<LP\_ID, Old\_Price, New\_Price>$. The new LP is broadcast to the network and is stored in the blockchain with the corresponding EI. \par Recall that in the proposed framework, we defined the reputation factor that impacts the decision making of the nodes. The reputation is given by the DR smart contract based on the commitments of an energy producer. In the case of the above example, the DR will reduce the reputation of the node and inform all participants. In this study, we consider the negative reputation only, which is when a node misbehaved in the network. \section{Case Studies}\label{sec: case study} \begin{figure} \centering \input{casestudy} \caption{33-Bus test system.}\label{fig:test system} \end{figure} \begin{table}[] \centering \footnotesize{ \caption{Parameter Setup.}\label{tab:parameters} \begin{tabular}{cccc} \hline \multicolumn{4}{c}{\textbf{Key parameters}} \\ \hline Parameter & \multicolumn{1}{c|}{Value} & Parameter & Value \\ \hline $P$ & \multicolumn{1}{c|}{14} & $C$ & 18 \\ $\rho_\lambda$ & \multicolumn{1}{c|}{0.01} & $\rho_\mu$ & 0.001 \\ $\overline{\lambda}^G$& \multicolumn{1}{c|}{5 \cent/kWh^2} &$\underline{\lambda}^G$ & 25 \cent/kWh^2 \\ $N$& \multicolumn{1}{c|}{2} & $\omega$ & 2 \cent/kWh/ km \\ \hline \multicolumn{2}{c|}{\textbf{Producers' parameters}} & \multicolumn{2}{c}{\textbf{Consumers' parameters}} \\ \hline $a_i$ & \multicolumn{1}{c|}{(0.5-1] \cent/kWh^2} & $a_j$ & (0.5-10] \cent/kWh^2 \\ $b_i$& \multicolumn{1}{c|}{[5-10] \cent/kWh} & $b_j$ & [10-20] \cent/kWh \\ $\underline{e}_i$& \multicolumn{1}{c|}{[0-5] kWh} & $\underline{e}_j$ & [1-4] kWh\\ $\overline{e}_i$& \multicolumn{1}{c|}{[5-10] kWh} & $\overline{e}_j$ & [6-10] kWh \\ $\eta_i,\alpha_i,\beta_i$& \multicolumn{1}{c|}{[0-1]} & $\eta_j,\alpha_j,\beta_j$ & [0-1] \\ \hline \end{tabular} } \end{table} In this section, simulation case studies are provided to verify the operation of the proposed framework. As shown in Fig. \ref{fig:test system}, the considered test system is the IEEE 33-bus distribution system with 16 producers and 16 consumers. Table \ref{tab:parameters} summarizes key parameters and range of values for producers and consumers parameters. Fig. \ref{fig: power and price res} illustrates the results of P2P trading in the test system. The traded energy and price in different transactions have various values based on the agents' preferences. Agents tend to trade energy with their closest neighbor agents to pay less grid service charge. For example, consumer at bus 1 buys energy from producer at bus 18. However, if the offer/ask from the agent at the nearest node is not available, or does not satisfy the requirement of the agents, they have to trade with other neighboring agents. For instance, while the nearest agents to agent 5 are agents at bus 4 and 6, this agent trades energy with producers at bus 26 and 27. Since agents 4 and 6 have preferred to trade with other neighboring nodes (agents at bus 3 and 7 respectively), their offers are not available to the agent 5. It can be seen that agents 16 and 17 do not buy any energy in the market. These agents have lower utility function parameters compared to their neighboring agents, which means that their willingness to pay for energy is less than agent 15, and hence, producer at bus 14 prefers to trade with the agent at bus 15. \begin{figure}[tb!] \centering \includegraphics[scale=0.75]{figures/tradedpowernew.pdf} \caption{Transactions between producers and consumers; a) traded energy, b) energy price.}\label{fig: power and price res} \end{figure} To investigate the impact of considering the grid service charge on the number of transactions ($n_T$), we implemented the energy trading algorithm for different values of $\omega$. The results are reported in Fig. \ref{fig:line flow}, where each marker indicates a transaction between the producer and consumer, and the total number of transactions in each case is given in parentheses. The case with \(\omega=0\) means that there is no limit on the distance of agents, and they can trade with any number of agents. Therefore, the number of transactions in this case is significantly higher. Increasing the value of $\omega$ reduces the number of transactions. The welfare of agents depend on the grid service charge that they pay (see (\ref{pro welf}) and (\ref{con welf})), and hence, increase in $\omega$ reduces their welfare as they have to trade less energy and pay more cost for utilizing the grid. The negotiation among agents is an iterative process and the time required for agents to reach agreement depends on several factors including, number of agents, number of iterations required for convergence in Algorithm \ref{producer lag} and \ref{consumer alg}, the computation time required to solve (\ref{sell update dec}) and (\ref{buyer update dec}) by agents in each iteration, and communication time. The results of implementing the market settlement algorithm with and without implementing \textit{prioritization} step are compared, as reported in Table \ref{tab:prioritization}. The \textit{prioritization} step reduces the number of negotiating agents, and hence, reduces the number of communication in each iteration. On the other hand, agents need less time to solve (\ref{sell update dec}) and (\ref{buyer update dec}), as they have fewer decision variables after \textit{prioritization}. Therefore, applying \textit{prioritization} reduces negotiation time among agents by nearly 45\%. \begin{figure} \centering \includegraphics[scale=0.85]{figures/lineflow.pdf} \caption{Impact of considering grid service charge on the number of transactions.}\label{fig:line flow} \end{figure} \begin{table}[tb!] \centering \footnotesize{ \caption{Impact of Prioritization.}\label{tab:prioritization} \setlength{\tabcolsep}{5pt} \begin{tabular}{lcc} \cline{2-3} \\[-0.7em] & \textbf{w prioritization} & \textbf{w/o prioritization} \\ \\[-0.7em] \hline No. of decision variables & \multirow{2}{*}{38, 16} & \multirow{2}{*}{20, 6} \\ \\[-1em] (producer, consumer) & & \\ \\[-1em] No. of communications & \multirow{2}{*}{63} & \multirow{2}{*}{252} \\ \\[-1em] (in each iteration) & & \\ \\[-1em] No. of iterations for convergence & 163 & 206 \\ \\[-1em] \hline Negotiation time (s) & 1.04 & 1.88 \\ \\[-1em] \hline \end{tabular} } \end{table} \begin{table}[tb!] \centering \footnotesize{ \caption{Comparative results of P2P market.} \label{tab:p2p results} \setlength{\tabcolsep}{5pt} \begin{tabular}{lcc} \cline{2-3} \\[-0.7em] & \textbf{P2P} & \textbf{No P2P} \\ \\[-0.7em] \hline Total imported energy from grid (kWh) [$\sum_j{e_j^G}$] & 22.31 & 119 \\ \\[-1em] Total exported energy to grid (kWh) [$\sum_i{e_i^G}$] & 8.46 & 105 \\ \\[-1em] Total welfare of consumers ($\cent$) [$\sum_j{W_j}$] & 62.73 & -4143.04 \\ \\[-1em] Total welfare of producers ($\cent$) [$\sum_i{W_i}$] & 242.64 & -302.03 \\ \\[-1em] Total paid grid service charge ($\cent$) [$\sum_j \sum_i {e_{ij}^p \gamma_{ij}}$] & 50.44 & 0 \\ \hline \end{tabular} } \end{table} In order to demonstrate the efficacy of the P2P market, the results of this market are compared with the case that producers and consumers only trade with the grid. Comparative results are reported in Table \ref{tab:p2p results}. As it can be inferred from the results, P2P market reduces the imported and exported energy by agents to the grid, meaning they trade more with other P2P agents. Also, since the P2P market price is more beneficial for agents (see (\ref{price lim})), they can reach a higher value of welfare in the P2P market, though they have to pay a grid service charge to the grid operator. As stated in Section \ref{sub:sec:advertisement}, in the proposed framework, the ATs are stored off chain in AD. Here, we study the impact of using AD by evaluating the blockchain size and number of consensus rounds, i.e., evaluating how many times the validators shall run the consensus algorithm. Blockchain size shows the amount of saved storage space by employing AD while the number of consensus rounds evaluates the amount of computational overhead saved by running less consensus rounds. We employed the structure and configuration of the IEEE 33-bus distribution to implement a distributed network using Java programming language on Raspberry Pi 2. It is assumed that the size of each block is 10 transactions. The process involved in the consensus algorithm is abstracted out as it does not impact the functionality of the proposed method. Ten market intervals are implemented during which each energy producer generates an AT. To benchmark the results, a baseline method is considered where all ATs are stored in the blockchain. To focus on the impact of AD, we disregard the rest of the functions and assume ATs are the only transactions generated during each market interval. Based on the implementation results, the size of each AT is 1776 B. After 10 epochs, the baseline blockchain includes 16 blocks with the cumulative size of 314KB. Thus, each node must allocate 314KB storage space to store blockchain. Our solution off-loads this overhead to a central trusted node who is managing the AD, thus there is no memory overhead on the participating nodes in the blockchain. Assume $\nu $ represents the overhead associated with appending a new block that includes computational, packet and memory overhead. The proposed framework incurs no overhead during the \textit{advertisement} process on the validators while the overhead is 16$\nu$ in the conventional methods. We next evaluate the processing overhead associated with CoL. We proposed a CoL that enables the users to anonymously verify the location of the parties involved in energy trading. CoL enhances the anonymity level of users and thus protects user privacy. On the flip side, it increases the processing overhead on the users to generate and verify CoL. To evaluate the incurred overhead, we implemented our framework using Java programming language on Raspberry Pi 2, which represents low-resource devices. We measured the processing time for generating the CoL request, which involves generating a set of keys and forming the Merkle tree, and verifying the CoL, which involves verifying the existence of the PK in the Merkle tree and validating the corresponding signatures. The implementation results are shown in Table \ref{tab:COL-performance}. The verification of the CoL involves verifying two signatures, which potentially takes longer time than generating CoL. In addition to the processing overhead, CoL increases the size of the transactions. Table \ref{tab:COL-packet} compares the size of transactions and shows that CoL only affects the AT. It nearly doubles the size of AT, but this does not affect the size of the blockchain as AT's are stored off-chain only. All other transactions are unaffected by CoL. \par \section{Security and Privacy Analysis}\label{sec:security} In this section, we analyze the security and privacy of the proposed framework. We first outline threat mode and then discuss possible attacks and how to protect against those.\par \textbf{\textit{Threat Model:}} We assume that the adversary (or cooperative adversaries) can sniff the communications, discard transactions, generate fake transactions, and pretend to be another node in the network. The adversary may attempt to deanonymize a user by classifying blockchain transactions and monitoring real-time communications in blockchain. We assume standard secure encryption algorithms are in place, which cannot be compromised by the adversary. We assume smart meters are tamper resistance, and thus the end users cannot modify the transactions generated by the meters. \par \begin{table}[tb!] \centering \footnotesize{ \setlength{\tabcolsep}{5pt} \caption{CoL processing time.}\label{tab:COL-performance} \begin{tabular}{ccc} \hline & CoL formation & CoL verification \\\hline Processing time (ms) & 663.2 & 1795 \\\hline \end{tabular} } \end{table} \begin{table}[tb!] \centering \footnotesize{ \setlength{\tabcolsep}{5pt} \caption{Comparison of transaction sizes.}\label{tab:COL-packet} \begin{tabular}{ccccc} \hline & AT & EN & LP & EI \\\hline Including CoL (Bytes) & 2193 & 1928 & 1056 & 1912 \\\hline Excluding CoL (Bytes) & 1041 & 1928 & 1056 & 1912 \\\hline \end{tabular} } \end{table} \subsection{Security} In the following, we discuss possible attacks and how the proposed framework protects against those. \par \textit{CoL Reply Attack:} In this attack, the malicious node attempts to employ CoL of another node to generate transactions. The node that employs a CoL is required to sign the corresponding transaction with the private key corresponding to a PK that exists in MTR that is only known to the CoL generator. Thus, it is impossible for a malicious node to utilize the CoL of another node. \par \textit{Fake CoL:} In this attack, a malicious node pretends to be a genuine smart meter generates fake CoL that can later be used in its energy tradings. The CoL must be signed only by a genuine smart meter, and the CA validates the PK of the verifier. In the case of this attack, CA will not validate PK, and thus the attack can be detected. \par \textit{Double selling:} In this attack, a malicious energy producer attempts to sell the same amount of energy to different consumers. Recall from Section \ref{sec:energy trading} that an energy trade involves three main transactions, which are EN, LP, and EI. Once the agreed energy is injected to the grid, the smart meter of the energy producer generates a EI transaction that triggers the payment of the energy price to the producer. The smart meter generates only one EI that includes a reference to the corresponding LP, and LP includes a reference to the corresponding EN. Thus, it is impossible for the energy producer to sell the same energy to multiple nodes. \par An energy producer may attempt to inject less energy than the agreed amount and claim the full price. The smart meter of the producer will only generate the EI if the full amount of agreed energy is injected to the grid. If the energy producer injects part of the energy and the expiry time approaches, the smart meter will generate an EI reflecting the amount that is injected to the grid. In this case, DR smart contract is called that adjusts the price of the energy and ensues the producer is only paid for the amount of energy injected to the grid. \par \textit{Reputation Modification:} In this attack, the malicious node attempts to improve their reputation or reduce the reputation of another node in the network. Recall that blockchain is an immutable ledger that makes it impossible to modify or remove previously stored transactions, which makes it impossible for the attacker to modify their reputation. To reduce the reputation of another node, the malicious node shall modify the code of the smart contract, which is impossible due to the immutability of the blockchain. DR smart contract is the only entity that can reduce the reputation of a node. All participants know the address of the valid DR contract. When participating nodes receive reputation reduction from a contract, they first verify if the contract address matches with the genuine DR smart contract. If so, they accept the new reputation. Otherwise, they discard the transaction. \subsection{Privacy} In the following, we analyze the proposed framework from the privacy perspective. Recall from Section \ref{sec:energy trading} that the grid operator charges a grid service charge per each transaction that depends on the distance between the energy consumer and producer. Thus, the consumer and producer must prove their location, however, this may compromise their privacy as malicious nodes can classify the blockchain transactions to deanonymize the user. To address this challenge, we proposed A-PoL that enables the participants in the blockchain to verify the location of an anonymous smart meter using a CoL. Assume node \textit{A} is using A-PoL. The privacy of \textit{A} can be studied from the perspective of the following entities: i) CA: \textit{A} uses the PK populated by the CA only to prove its identity to the verifier. CoL employed by \textit{A} includes PK of the verifier and not \textit{A}. Given that the verifier is selected randomly by \textit{A} and there is no link between \textit{A} and the verifier, the CA is unable to identify the transactions generated by \textit{A}, ii) verifier: \textit{A} only sends MTR to the verifier that hides the actual PKs of \textit{A} from the verifier. \textit{A} reveals the PKs in the Merkle tree to prove ownership of CoL. A group of smart meters may choose to create a single MTR, which further protects their privacy, and iii) network participants: the network participants only receive CoL that contains of the verifier and MTR. As outlined earlier, there is no link between the verifier and \textit{A}, thus knowledge of the identity of the verifier does not impact the privacy of \textit{A}. The Merkle tree includes a number of PKs that are employed by \textit{A} (or other involved smart meters) to generate transactions, thus, \textit{A} may generate multiple transactions with the same PK. This potentially reduces the anonymity level of the user as malicious nodes may attempt to deanonymize a user by classifying their transactions. The anonymity level of \textit{A} largely depends on the number of PKs employed in the Merkle tree. The large number of PKs incur overheads on \textit{A} to manage the keys. Thus, there is a trade-off between the number of keys in the Merkle tree and user anonymity. \par Recall from Section \ref{sub:sec:market-settlement} that the energy producer and consumer employ a cost/utility function, as shown in (\ref{cost-func-producer}) and (\ref{cost-function-consumer}), which represent their willingness to pay or accept energy price based on their preferences and concerns. These functions depend on $a_i$, $b_i$, and $c_i$, and thus it is critical for the producers and consumers to keep these values private. In the proposed framework, the market settlement does not need the nodes to reveal $a_i$, $b_i$ and $c_i$, which in turn enhances the privacy of the users. \section{Conclusion and Future Works}\label{sec:conclusion} In this paper, we propose a blockchain-enabled P2P energy market, which provides a secure and privacy-preserving environment for energy trading between producers and consumers. A decentralized market settlement process is designed, which allows agents to trade energy without revealing their private information. The grid service charge, calculated based on the distance between producer and consumer, is used to incite agents trade energy locally and to reduce the possibility of overloading electricity grid lines.\par To reduce the blockchain memory footprint, we propose AD that stores the energy advertisements and is maintained by the grid operator. A \textit{prioritization} step is implemented to enable agents to select their trading partners based on their location and reputation factors. In order to allow agents to prove their location without revealing their real identity, an A-PoL algorithm is proposed using CoL issued by smart meters. Simulation results on IEEE 33-bus test system confirm that the proposed framework improves the welfare of agents through P2P trading, while their privacy is protected. Furthermore, employing AD to store ATs, and limiting the number of trading partners through \textit{prioritization} decrease the system overheads. For future work is needed to relax the tamper resistance assumption considered for smart meters. Relaxing this assumption complicates the trust issue as the smart meters may generate fake transactions. As another research direction, the impact of mobility of the smart meters on A-PoL can be studied. In such cases, the CA must ensure that the location of a meter is as claimed before granting a certificate. It is critical for the CA to be able to revoke granted certificates as smart meters may change its location. Another challenge for future work is to explore ways of decentralizing the AD without increasing the blockchain memory footprint to achieve an even more decentralized energy marketplace. \bibliographystyle{IEEEtran} \section{Introduction} \IEEEPARstart{I}{n response} to climate change concerns, the decarbonization and digitization of the electricity sector have been accelerated in recent years. The path toward decarbonization is associated with the high penetration of Distributed Energy Resources (DERs), such as rooftop solar, home batteries, and Electric Vehicles (EVs) with the potential to support a reliable, affordable and lower-emissions electricity grid. Progressive deployment of DERs raises several opportunities and challenges in the electricity systems \cite{openenergy}. Technical challenges include the increase in bidirectional power flows, the raise in the voltage levels, and lack of visibility \cite{coster2010integration}. On the other side, efficient DER integration can provide substantial benefits for energy customers \cite{aemo}. DER owners can benefit from Feed-In-Tariffs (FiTs) programs by selling energy back to the utility grid for a fixed price \cite{ye2017analysis}. Alternatively, they can be coordinated and aggregated for participation in different markets. Virtual Power Plants (VPPs) are an example of DERs aggregation to exploit their inherent flexibility \cite{pudjianto2007virtual}. An emerging technique for the integration of small-scale producers and consumers to energy markets is Peer-to-Peer (P2P) trading, which allows bilateral energy transactions between users \cite{tushar2020peer}. P2P trading provides significant benefits for both end users and grid operators such as increasing welfare by preference satisfaction \cite{morstyn2018using}, lowering operational costs, and improving system reliability \cite{mengelkamp2018designing}. P2P trading offers the flexibility required to coordinate agents with diverse preferences. Recent advances in the Internet of Things (IoT) and digital technologies have paved the path toward grid digitization. Grid digitization provides a two-way communication network that allows DER owners and energy consumers to act as proactive agents in the energy markets and facilitates P2P market implementation. Through direct interaction of agents in a decentralized platform, small-scale producers are allowed to compete with large traditional suppliers, and consumers have the freedom to select their energy suppliers based on their preferences. In the P2P trading, it is expected that market participants can settle the bilateral transactions with least influence from a central authority \cite{giotitsas2015peer}. Hence, designing a decentralized platform for managing market participants with diverse preferences is a challenging task. Blockchain technology offers new opportunities for decentralized market designs due to its salient features which includes decentralization, trust, anonymity, and auditability. Blokchain enables energy producers and consumers to directly negotiate and trade energy without reliance on Trusted Third Party (TTP). It provides a platform to store and share data in a secure and verifiable manner, even when the identity and trustworthiness of market participants are unknown \cite{van2020integrated}. The participating nodes in the blockchain, that includes energy consumers, producers, prosumers, or grid operators, jointly form an overlay network where they can exchange information \cite{wu2019comprehensive}. Given the properties of blockchain, and the need for a truly decentralized platform for P2P trading, designing blockchain-enabled frameworks for P2P trading is gaining momentum in recent years. The blockchain framework for P2P trading should incorporate an appropriate market settlement approach to match trading peers and to settle the bilateral transactions among them. Compared to traditional markets, P2P market offers more flexibility and trading options to the agents, and hence, it needs a pricing mechanism that incentivizes both producers and consumers to participate in the market. There are several approaches that can be applied to P2P market clearing and peer matching, such as auction-based mechanism, game theory, and optimization-based methods \cite{li2018location, paudel2018peer, khorasany2019decentralised}. In the auction-based mechanism, agents express their interest in energy trading by submitting their offers, and the energy allocation and price would be determined based on the market clearing rules \cite{li2018location}. The game theory approaches aim to provide a stable solution that is beneficial for all parties \cite{paudel2018peer}. In the optimization-based methods, the market settlement is formulated as an optimization problem, which can be decomposed to local subproblems solvable by each agent \cite{khorasany2019decentralised}. The optimization-based methods can be implemented in a decentralized manner without any need for third party interventions, which allows agents to optimize their welfare by participating in the P2P market. Hence, these methods are well-suited for blockchain-enabled P2P markets. However, the computation and communication overheads of these methods are of concern, as they require agents to iteratively negotiate to reach agreements on their actions. Therefore, reducing these overheads is a key requirement This paper designs a blockchain-enabled P2P market that provides a secure and transparent environment for the energy trading of producer and consumer agents. In the proposed approach agents \textit{Advertise} their surplus/deficit energy during each market interval. We use an Advertisement Database (AD) that is centrally managed by the grid operator to skip storing advertisement in public blockchain, which in turn, reduces the blockchain memory footprint. A decentralized optimization algorithm is employed for the \textit{Negotiation} that allows agents to iteratively optimize their welfare in the negotiation process. In order to reduce the computation and communication overheads, a \textit{Prioritization} step is considered in the market settlement process that enables agents to prioritize their trading partners based on their proximity and reputation factor. Network constraints should be incorporated in the P2P trading to ensure that energy transactions respect electric grid constraints. Instead of enforcing network constraints directly to the proposed framework, we define a grid service charge for each transaction. To incentivize agents to trade energy with their neighboring agents and reducing network loading, this charge is calculated based on the electrical distance between producer and consumer. To this end, we propose an Anonymous Proof of Location (A-PoL) algorithm that enables agents to prove their location without revealing their real identity. Once the energy consumer and producer agree on the conditions of the trade, they start trading the energy. To reduce the reliance on TTP yet ensure the security of the trade, we adopt the concept of atomic meta-transactions~\cite{dorri2019spb} where two transactions are considered valid only if they are generated within a particular period of time. The contributions of this paper are summarized as follows: \begin{itemize} \item [-] a decentralized P2P trading framework that does not require access to private information of agents in any stage of the market settlement; \item[-] a novel \textit{prioritization} step to allow agents to select their trading partners based on their location and reputation in order to reduce the system overheads; \item[-] a new A-PoL algorithm, which uses a Certificate of Location (CoL) issued by smart meters to approve the location of agents without revealing their real identity. \end{itemize} The rest of this paper is organized as follows. Section \ref{sec:related} explains some related work. Section \ref{sec: market structure} outlines the structure of the market, including agents modeling, market objective, and decentralized optimization of the market objective. Section \ref{sec:energy trading} explains the market settlement process and its different steps. Case studies and numerical results are reported in Section \ref{sec: case study}. A detailed analysis of the security and privacy of the proposed framework is presented in Section \ref{sec:security}. Finally, concluding remarks are given in Section \ref{sec:conclusion}. \section{Prior Art}\label{sec:related} In recent years blockchain applications in energy systems, such as microgrid energy management, EV integration, and energy trading, has attracted tremendous attention due to its salient features including decentralization, transparency, trust, and immutability \cite{andoni2019blockchain,musleh2019blockchain}. Su \textit{et. al} \cite{su2018secure} employed blockchain to implement secure charging services for EVs with the execution of smart contracts. In \cite{noor2018energy}, blockchain technology is utilized to implement a demand side energy management method for the efficient operation of microgrids. Hassan \textit{et. al} \cite{hassan2019deal} developed a blockchain-based approach for microgrid energy auction, in which to reduce computational complexity, at every node consortium blockchain is used that authorizes only selected nodes to add a new block in the blockchain. The application of blockchain for P2P energy trading has been investigated in several studies. The Brooklyn microgrid is a prototype of a blockchain-enabled P2P market, in which a blockchain framework is employed to implement a decentralized microgrid energy market \cite{mengelkamp2018designing}. A unified blockchain framework for various scenarios of energy trading in an industrial IoT is proposed in \cite{li2017consortium}, in which a credit-based payment scheme is employed to overcome the transaction limitation caused by transaction confirmation delays. An operation framework for P2P energy trading at the distribution level is presented in \cite{wang2019energy}, where the system operator clears the market using a crowdsourced energy system model. Dang \textit{et. al} \cite{dang2019demand} proposed a blockchain-based P2P market for optimal load management of big industrial users, in which users can organize their own P2P market to save their electricity costs. In \cite{luo2018distributed}, a two-layer system for distributed electricity trading among prosumers is proposed, in which in the first layer prosumers can form coalitions and negotiate energy trading, and in the second layer blockchain is employed for settlement of transactions formed in the first layer. The existing blockchain-based frameworks for energy trading suffer from: \textit{(i) negotiation overheads:} the decentralized optimization methods rely on iterative negotiation between involved agents. In a market with large number of participants, this iterative process increases the communication and computation overheads, and consequently the negotiation time. \textit{(ii) reliance on a TTP:} most of the existing studies rely on a TTP to oversee the trade and ensure that both sides of the trade commit to their obligations. However, this potentially may lead to centralization and privacy concerns as TTP can build virtual profile about the users. \textit{(iii) Blockchain overheads:} in conventional blockchain-based methods in smart grids, all communications are stored in the blockchain, which in turn increases the blockchain memory footprint and thus reduces scalability. In this regard, this paper proposes a blockchain-enabled P2P market that alleviates the above-mentioned limitations. \section{The Market Structure}\label{sec: market structure} \begin{figure}[tb!] \centering \includegraphics[scale=0.8]{figures/market layer.pdf} \caption{An overview of the proposed blockchain-enabled P2P energy trading.} \label{fig:layers} \end{figure} In this section, we outline the details of the market structure. As shown in Fig. \ref{fig:layers}, the proposed architecture consists of two layers: i) physical layer that is the underlying physical network to transfer electricity from producers to consumers. The minimum requirement for a successful transaction between a producer and a consumer is the existence of a path to transfer power between them, and ii) information layer where the participating nodes, that includes energy producer, consumer, and the grid operator, connect through a public blockchain to share information. The information layer provides a secure platform for the participating nodes to advertise their energy, negotiate on their offers, and decide on their actions in the market. The market mechanism is implemented in this layer that enables the agents to trade energy and settle energy transactions. \par \subsection{Agents modeling}\label{sub:sec:agent-modeling} We consider an energy network with a set of agents consisting of a set of producer agents with index \(i \in \mathcal{P}=\{1, ..., P\}\) and a set of consumer agents with index \( j \in \mathcal{C}=\{1, ..., C\}\) connected to a physical layer manged by a grid operator. Producers have energy producing capability and can use their own generated energy for their demand. In case there is more generation than demand, producers can sell surplus energy to consumers or to the grid. Consumers, on the other side, can buy energy from producers or the grid. Producers and consumers can negotiate for energy trading in a forward market for any time interval \(t \in \mathcal{T} =\{1, ..., T\}\) with equal duration (e.g., one hour). Agents are equipped with smart meters, which determines the energy surplus/deficit for trade in each time slot. The smart meters are connected to the information layer and thus, can exchange information in blockchain. It is assumed that the smart meters are tamper-resistant. We assume that each agent is equipped with an energy management system that can quantitatively estimate the energy surplus or deficit that needs to be traded in each market interval. Each agent can trade with the grid or with other agents in the network. The total energy surplus and deficit of producers and consumers is represented as \begin{equation}\label{tot energ pro} e_i=e_i^G +\sum_{j \in \mathcal{C}}{e_{ij}^P} \end{equation} \begin{equation}\label{tot energ cons} e_j= e_j^G+\sum_{i \in \mathcal{P}}{e_{ji}^P} \end{equation} where, \(e_i^G\) and \(e_j^G\) are the traded energy between producer $i$/consumer $j$ and the grid respectively, \(e_{ij}^P\) is the sold energy by producer $i$ to consumer $j$, and \(e_{ji}^P\) is the purchased energy by consumer $j$ from producer $i$. Each agent in the P2P market aims to maximize its welfare. The welfare incorporates the utility/cost of energy consumption/generation, cost/revenue of trade with other agents or the grid, and the cost of using grid for the P2P trading. The welfare function of producers and consumers can be modeled by (\ref{pro welf}) and (\ref{con welf}), respectively \begin{equation}\label{pro welf} W_i(e_i, \lambda_{ij},\gamma_{ij})= \underline{\lambda}^G e_i^G +\sum_{j \in \mathcal{C}}{e_{ij}^P (\lambda_{ij}-\gamma_{ij})}-C_i(e_i) \end{equation} \begin{equation}\label{con welf} W_j(e_j, \lambda_{ij},\gamma_{ij})= U_j(e_j)- \overline{\lambda}^G e_j^G -\sum_{i \in \mathcal{P}}{e_{ij}^P (\lambda_{ij}+\gamma_{ij})} \end{equation} where \(\underline{\lambda}^G\) denotes FiT representing the price for selling energy to the grid; \(\lambda_{ij}\) is energy price in transaction between producer $i$ and consumer $j$; \(\gamma_{ij}\) is grid service charge for using grid infrastructure for this trade; \(\overline{\lambda}^G\) denotes the price for selling from the grid which is usually a fixed value over the time (e.g. time of use tariff). The grid selling and buying prices limit energy price in the P2P market, i.e. for any bilateral trade \begin{equation}\label{price lim} \underline{\lambda}^G \leq \lambda_{ij} \leq \overline{\lambda}^G. \end{equation} The cost function of the producer represents the cost of generating energy \(e_i\) and can be modeled as \cite{grainger2003power} \begin{equation}\label{cost-func-producer} C_i(e_i)=a_i e_i^2 +b_i e_i +c_i \end{equation} where \(a_i, b_i\) and $c_i$ are positive constants, which can be adjusted by the producer to reflect the generation cost. Since producers usually have renewable generation resources with zero marginal costs, the cost function can represent the cost associated with battery degradation cost, if the producer needs to discharge its battery to sell the energy. On the other side, the utility function of a consumer represents its satisfaction level by consuming energy $e_j$ and can be modeled as \cite{samadi2010optimal} \begin{equation}\label{cost-function-consumer} U_j(e_j)= \begin{cases} -a_j e_j^2 +b_j e_j \;\;\;\; :0 \leq e_j \leq \frac{b_j}{2 a_j}\\ \frac{b_j^2}{4 a_j} \;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\ :e_j \geq \frac{b_j}{2 a_j} \end{cases} \end{equation} where \(a_j\), and \(b_j\) are unique positive constants for each consumer. These parameters reflect the valuation of the energy by the consumer and denotes the price that consumer is willing to pay for the energy. A fundamental challenge in implementing P2P markets is how to deal with network constraints, without having a central dispatch mechanism. In this work, instead of enforcing network constraints directly, we use a grid service charge for each trade \cite{baroche2019exogenous}. This fee represents the price that agents need to pay for using the grid infrastructure for each trade. To incite agents to trade with their closest electrical partner and to reduce network loading, this charge is calculated based on the electrical distance between producer and consumer as in \begin{equation}\label{service charge} \gamma_{ij}=\omega d_{ij} \end{equation} where \(\omega\) is the grid service charge per unit of electrical distance for each unit of energy, and \(d_{ij}\) is the electrical distance between producer $i$ and consumer $j$. This distance can be calculated based on power transfer distance, which aggregates the absolute value of Power Transfer Distribution Factor (PTDF) induced by a trade as in \begin{equation} \label{eq:ptdf} d_{ij}=\sum_{l \in \mathcal{L}}{\phi^l_{ij}}. \end{equation} For any trade, \(\phi^l_{ij}\) indicates the fraction of transacted power from producer $i$ to consumer $j$ that flows over a line $l$, and can be calculated using the method presented in \cite{wood2013power}. \subsection{Market objective} \label{sub:sec:market-settlement} The market objective for P2P trading is formulated as social welfare maximization, which maximizes the total welfare of players in the market subject to the constraints, and mathematically can be modeled as: \begin{equation}\label{tot objective} \begin{aligned} & \underset{\textbf{\textit{$e_i$,$e_j$}}}{\text{max}} \sum_{i \in \mathcal{P}}{W_i} + \sum_{j \in \mathcal{C}}{W_j}\\ & \text{s.t. constraints.} \end{aligned} \end{equation} As stated in (\ref{price lim}), the prices in the P2P market should always be beneficial for both producers and consumers. Hence, it is reasonable to assume that all agents try to maximize their traded energy in the P2P market and to minimize trading with the grid by setting $e_i^G=e_j^G=0$. Therefore, (\ref{tot objective}) can be rewritten as: \begin{subequations}\label{social welfare} \begin{equation} \begin{aligned} & \underset{\text{\textbf{{$e_{ij}$,$e_{ji}$}}}}{\text{max}} \sum_{j \in \mathcal{C}}{U_j(e_{ji})} - \sum_{i \in \mathcal{P}}{C_i({e_{ij}})} - \sum_{j \in \mathcal{C}}{\sum_{i \in \mathcal{P}}}{(e_{ij}+e_{ji})\gamma_{ij}}\\ \end{aligned} \end{equation} \begin{equation}\label{producer flex} \text{s.t.} \;\;\; \underline{e_i} \leq \sum_{j \in \mathcal{C}}{e_{ij}^P} \leq \overline{e_i} \;\;\;\;\;\;\;\;\;\;\;\;\;\; :\underline{\mu_i}, \overline{\mu_i} \end{equation} \begin{equation}\label{consumer flex} \underline{e_j} \leq \sum_{i \in \mathcal{P}}{e_{ji}^P} \leq \overline{e_j} \;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\; :\underline{\mu_j}, \overline{\mu_j} \end{equation} \begin{equation}\label{demand supply} e_{ij}^P=e_{ji}^P \;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\; :\lambda_{ij} \end{equation} \end{subequations} where (\ref{producer flex}) and (\ref{consumer flex}) represents the flexibility constraints of producer, and consumer, respectively. The constraint (\ref{demand supply}) represents the power balance in transaction between producer $i$ and consumer $j$. \(\underline{\mu_i}, \overline{\mu_i}, \underline{\mu_j}, \overline{\mu_j}, \lambda_{ij}\) are dual variables associated with these constraints. \begin{figure}[tb!] \input{marketsettlement} \caption{Market settlement algorithm.}\label{fig:full algorithm} \end{figure} \subsection{Decentralized optimization} \label{sub:sec:coordination} In this paper, our aim is to solve (\ref{social welfare}) with only P2P communications to ensure data privacy of the agents. To do so, a decentralized optimization approach is employed to formulate the market settlement in P2P market \cite{khorasany2019decentralised}. In this approach, dual variables are used to decouple constraints, and then, the problem is decomposed to local subproblems solvable by producers and consumers. The local subproblem is solved by deploying the sub-gradient projection method \cite{boyd2011distributed}. Each agent contributes to solving the global problem by updating its local decision variables. The set of decision variables for producers and consumers are \{\(\lambda_{ij}, e_{ij}^P, \underline{\mu_i}, \overline{\mu_i}\}\), and \{\( e_{ji}^P, \underline{\mu_j}, \overline{\mu_j}\)\}, respectively. The market settlement approach is an iterative process, in which agents update their decision variables iteratively and exchange information without revealing their private information. The updates of the decision variables of agents are based on the Karush–Kuhn–Tucker (KKT) optimality conditions of the local problems, and can be developed using first order deviate of the relaxed problem as follows:\\ \(\forall i \in \mathcal{P}\) \begin{subequations}\label{sell update dec} \begin{equation}\label{sell price update} \lambda_{ij}^{k+1}=\left[\lambda_{ij}^{k}-\rho_{\lambda}^k(e_{ij}^{P,k}-e_{ji}^{P,k})\right]^{+} \end{equation} \begin{equation}\label{sell mu low update} \underline{\mu_i}^{k+1}=\left[\underline{\mu_i}^{k}+\rho_{\mu}^k(\underline{e_i}-e_i^k)\right]^{+} \end{equation} \begin{equation}\label{sell mu up update} \overline{\mu_i}^{k+1}=\left[\overline{\mu_i}^{k}+\rho_{\mu}^k(e_i^k-\overline{e_i})\right]^{+} \end{equation} \begin{equation}\label{sell energy update} e_{ij}^{{P,k+1}}= \left[e_{ij}^{{P,k}}+\zeta_{ij}^k(\tilde{e}_{ij}^{P,k+1}-e_i^k)\right]^{+}\\ \end{equation} \begin{equation}\label{set point sell update} \tilde{e}_{ij}^{P,k+1}=\frac{\lambda_{ij}^{k+1}-\gamma_{ij}-\overline{\mu_i}^{k+1}+\underline{\mu_i}^{k+1}-b_i}{2 a_i} \end{equation} \end{subequations} \(\forall j \in \mathcal{C}\) \begin{subequations}\label{buyer update dec} \begin{equation}\label{buyer mu low update} \underline{\mu_j}^{k+1}=\left[\underline{\mu_j}^{k}+\rho_{\mu}^k(\underline{e_j}-e_j^k)\right]^{+} \end{equation} \begin{equation}\label{buyer mu up update} \overline{\mu_j}^{k+1}=\left[\overline{\mu_j}^{k}+\rho_{\mu}^k(e_j^k-\overline{e_j})\right]^{+} \end{equation} \begin{equation}\label{buyer power update} e_{ji}^{P,k+1}= \left[e_{ji}^{P,k}+\zeta_{ji}^k(\tilde{e}_{ji}^{P,k+1}-e_j^k)\right]^{+} \end{equation} \begin{equation}\label{buyer set point update} \tilde{e}_{ji}^{P,k+1}=\frac{b_j-\lambda_{ij}^{k+1}-\gamma_{ij}-\overline{\mu_j}^{k+1}+\underline{\mu_j}^{k+1}}{2 a_j} \end{equation} \end{subequations} where $k$ is the iteration index, \(\tilde{e}_{ij}^{P}, \tilde{e}_{ji}^{P}\) are optimal power set points of producer and consumer at the price \(\lambda_{ij}\). \(\zeta_{ij}, \zeta_{ji}\) are asymptotically proportional factors, \(\rho\) is a small tuning parameter, and \([.]^+\) denotes max \{.,0\}. The information exchange between producers and consumers during the decentralized optimization process is explained in Section \ref{sec:neg}. \section{Market Settlement Process}\label{sec:energy trading} In this section, we outline the details of the market settlement process for P2P trading. The proposed framework consists of four main phases namely; \textit{(i) Advertisement:} to enable agents to advertise the energy that they want to trade, \textit{(ii) Prioritization:} to allow agent prioritize their trading partners based on their preferences, \textit{(iii) Negotiation:} in which agents negotiate on the energy quantity and price in each transaction, and \textit{(iv) Energy trading:} which is the step that energy transfer and payment would be taking place. These steps are summarized in Fig. \ref{fig:full algorithm} and discussed in detail in the rest of this section. \subsection{Anonymous proof of location} As shown in (\ref{service charge}) in the proposed framework the grid service charge is calculated based on the location of the participants denoted by $\sigma$ which requires the involved parties to reveal their location. However, this potentially enables the malicious nodes to track the activities of a particular user, which in turn compromises user privacy. Additionally, the distributed and anonymous nature of blockchain makes it challenging for the users to verify the location claimed by another node. To address these challenges, we propose an A-PoL algorithm that enables the users to prove their location while protecting their real identity, which in turn enhances the level of anonymity offered to the users. The proposed A-PoL algorithm involves a CoL that is issued by a smart meter in the network, as shown in Fig. \ref{fig:CoL}. The energy companies maintain a local record of the accurate location of the installed smart meters. During the installation process, the energy company deploys a key pair in each smart meter (step 1 in Fig. \ref{fig:CoL}) and records $<PK,location>$ tuple in its local storage. The company serves as a certificate authority (CA) for PKs deployed in smart meters. Although the CA is a trusted authority, relying on the PK provided by the CA may compromise the privacy of the users as the company can build a virtual profile of the user and their energy trading (by observing the proof of location transactions). To address this challenge, we propose CoL. \par \begin{figure}[tb!] \centering \input{col} \caption{An overview of the proposed CoL.} \label{fig:CoL} \end{figure} CoL is a certificate received from a verifier that is an independent smart meter in the network. Assume smart meter \textit{A} is going to establish a CoL. Once deployed on site, \textit{A} explores the CA to find potential smart meters that can function as the verifier and selects one randomly. Assume smart meter \textit{B} is selected by \textit{A} to function as the verifier. Recall that we assume the smart meters are tamper resistant, and thus \textit{A} can send its request to any meter listed in CA. \textit{A} sends a CoL request transaction to \textit{B} that is structured as $<T\_ID, MTR, \sigma, PK, Sign>$, where \textit{T\_ID} is the unique identifier of the transaction which essentially is the hash of the transaction content. \par \textit{A} populates the root hash of a Merkle tree constructed by recursively hashing a number of PKs in the \textit{MTR} field. The PKs in the leaves of the tree are later employed by \textit{A} to prove ownership on the CoL, which is discussed in greater detail later in this section. The number of PKs may vary based on the application. $\sigma$ is the noisy location of the smart meter that can be the location at a lower resolution, e.g., the street in which the meter is installed. This protects the privacy of the smart meter against deanonymization, as studied later in Section \ref{sec:security}. \textit{PK} is the PK of \textit{A} allocated by the CA, and \textit{Sign} is the corresponding signature, which proves that \textit{A} owns the private key corresponding to the PK. \par When the verifier, i.e. \textit{B} receives the CoL request, it verifies that the transaction is generated by a genuine smart meter that is done by requesting the CA (step 3). To protect the privacy of the user, the CA does not reveal the actual location of the smart meter to \textit{B} instead, only confirms if the PK is registered and genuine smart meter. Once verified, the verifier creates a CoL that is \textit{sign(hash(MTR, $\sigma$))} and replies back to \textit{A} by sending the reply transaction structured as $<CoL, PK, Sign> $, where CoL is as outlined above, \textit{PK } is the PK of the verifier, i.e., \textit{B} registered by the CA, and \textit{Sign} is the corresponding signature of the verifier. \par \textit{A} employs the received CoL to anonymously prove its location to the nodes in the overlay. To do so, \textit{A} appends $CoL_f\textsuperscript{A} = (CoL_A, PK\textsubscrtip{ver}, Sig\textsubscrtip{ver}, MTR_A, \sigma_A, PK_A, MTL_A, \\ Sign_A)$ where the first three fields are extracted from the response of the verifier \textit{B}. MTR and $\sigma_A$ are extracted from the CoL request sent to the verifier. \textit{$PK_A$} is a PK that was part of the leaves of the Merkle tree. $MTL_A$ is the leaves of the Merkle tree that are necessary to prove the existence of $PK_A$ in the MTR, and $Sign_A$ is the signature corresponding to PK. The last three fields ensure that only the owner of the certificate, who knows the PKs in the Merkle tree and the corresponding private key, can use the certificate. \par To verify the location of \textit{A}, the participating nodes in the blockchain, say \textit{C}, must first verify that $PK_A$ belongs to $MTR_R$ using $MTL_A$. Next, \textit{C} verifies if $Sign_A$ matches $PK_A$. The third step in verifying is to verify if $hash(MTR_A, \sigma_A) = CoL_A$. The final step is for \textit{C} to verify PK\textsubscrtip{ver} using CA. This ensures that a genuine smart meter has signed the CoL. If all the above steps successfully passed, the location of \textit{A} is verified. \par Having discussed the details of the proposed A-PoL algorithm, we study the process of P2P energy trading in the rest of this section. The algorithms implemented by producer and consumer agents are represented in Algorithm \ref{producer lag} and \ref{consumer alg}, respectively, and are discussed with greater details in the rest of this section. \subsection{Advertisement}\label{sub:sec:advertisement} The main aim of this phase is for the agents to advertise their energy to the potential consumers/producers. In each market interval, agents participate in the forward market by submitting their offers and asks in the form of \textit{advertisement transaction (AT)} that is structured as follow: \begin{equation} AT = (T\_ID, price/amount, \eta_i, CoL_f\textsuperscript{i}) \end{equation} where \textit{price/amount} can be either the price of the energy, i.e., $\lambda_i, \forall i\in \mathcal{P}$, if AT is generated by a producer or the amount of requested energy, i.e., $e_j, \forall j\in \mathcal{C}$, if AT is generated by a consumer, and \(\eta\) is the reputation factor of agent.\par In conventional blockchain-based frameworks, the negotiation transactions are stored in the blockchain that provides high auditability. However, this increases the computational and storage resource consumption of the blockchain and limits the throughput, i.e., the total number of transactions that can be stored per second. These can limit the blockchain scalability while smart grid comprises of a broad range of devices that may produce transactions frequently. To address this challenge, in the proposed framework, the negotiation transactions are stored in a public database managed by the grid operator that is referred to as \textit{Advertisement Database} (AD). The write access of AD is restricted only to the grid operator and other nodes in the overlay have read-only permission. The parties involved in an AT transaction, i.e., energy producers and consumers, may store the transactions locally to be employed as a reference in case of a dispute between parties. The final price and the amount of energy agreed by the participants are later defined during a negotiation which limits future references to AT transaction. Thus, we store AT in AD which potentially reduces the packet overhead and blockchain memory footprint. \par \subsection{Prioritization} After \textit{advertisement} step, agents explore the available ATs in the AD for the negotiation. One-on-one negotiation can increase the delay associated with finalizing the trade as either side of the trade may have higher welfare in trading with another party in the network. Also, negotiation with every agent in the market increases the computation and communication overheads, which potentially leads to low scalability \cite{khorasany2019enhancing}. Thus, agents need to prioritize their trading partners based on their preferences and only negotiate with a given number of agents. As stated in Section \ref{sub:sec:agent-modeling}, agents have to pay a grid service charge for each transaction as defined in (\ref{service charge}). This charge is directly associated with the distance between the producer \textit{i} and the consumer \textit{j}, and impacts the welfare of the agents. Accordingly, agents are incentivized to trade with trading partners located in close vicinity. This reduces the load on the transmission lines and thus reduces the cost in managing the physical layer. On the other hand, agents may prefer to negotiate with the trading partners with higher reputation factors, indicating their past performance in fulfilling their commitments. Thus, agents need to prioritize their trading partners based on their preferences to limit the partner search space. These preferences include reputation factor and distance. Agents may have varied preferences over reputation factor and distance of their trading partners. Hence, we define a priority index for each possible transaction between producers and consumers. This index for offer from consumer $j$ received by producer $i$, and offer from producer $i$ received by consumer $j$ are defined using (\ref{sell pri index}) and (\ref{buy pri index}), respectively. \begin{equation}\label{sell pri index} \Upsilon_{ij}=\alpha_i \rho_j +\beta_i (1-\cfrac{|\sigma_i -\sigma_j|}{D_{ij}})\\ \end{equation} \begin{equation}\label{buy pri index} \Upsilon_{ji}=\alpha_j \rho_i +\beta_j (1-\cfrac{|\sigma_i -\sigma_j|}{D_{ji}})\\ \end{equation} where \(\alpha\) and \(\beta\) are the weights that agent places on the reputation factor and proximity of other agents, respectively such that \(\alpha+\beta=1\), \(D_{ij}=\underset{\sigma_j}{\max} |\sigma_i-\sigma_j|\), \(D_{ji}=\underset{\sigma_i}{\max} |\sigma_i-\sigma_j|\). The second term in (\ref{sell pri index}) and (\ref{buy pri index}) denotes the proximity of each trading partner to the agent, such that for the furthest trading partner of each agent this value is zero. After calculating priority index, each agent divides its trading partners to a set of $\mathcal{N}$ groups and then, starts to negotiate with the agents from the group with the highest priority and proceed to the group with the lowest priority. Each group of potential consumers/producers for producer $i$/consumer $j$ can be formed as \begin{equation}\label{prioritization sell} \Omega_i^n=\{j \in \mathcal{C}| (N-n)/N \leq \Upsilon_{ij} \leq (N-n+1)/N \} , \forall n \in \mathcal{N} \end{equation} \begin{equation}\label{prioritization buy} \Omega_j^n=\{i \in \mathcal{P}| (N-n)/N \leq \Upsilon_{ji} \leq (N-n+1)/N \} , \forall n \in \mathcal{N} \end{equation} in which for consumer $j$, producers in group $\Omega_j^n$ have higher priority than producers in $\Omega_j^{n+1}$. Similarly, for producer $i$, consumers in group $\Omega_i^n$ have higher priority than consumers in $\Omega_i^{n+1}$. \subsection{Negotiation}\label{sec:neg} After \textit{prioritization}, each consumer starts negotiating with producer agents in $\Omega_j^1$. The first step is for consumer \textit{A} to request the grid service charge from the grid operator. \textit{A} sends the list of agents in $\Omega_j^1$ to the grid operator who calculates grid service charges using (\ref{service charge}) and sends the response back to \textit{A}. Once \textit{A} receives the grid service charge, it starts the negotiation with agents in $\Omega_j^1$ by sending an \textit{Energy Negotiation} (EN) transaction that is structured as $ <T\_ID, Amount, Price, PK\textsuperscript{D}, Sign\textsuperscript{D}, PK\textsuperscript{+}, Sign, PK\textsuperscript{+},\\ Agreement_P, Agreement_C>$ where \textit{Amount} identifies the total amount of energy demanded by \textit{A} and \textit{price} is the price in which the consumer is willing to pay. \textit{PK\textsuperscript{D}} and \textit{ Sign\textsuperscript{D}} represent PK of the destination agent and its corresponding signature. The destination can be either the producer, when \textit{A} generates the transaction, or \textit{A}, when a producer is the generator of the transaction. This potentially enables routing the transaction to the destination using the routing algorithm proposed in \cite{dorri2019spb}. \textit{Sign } and \textit{PK} represent the PK and signature of the transaction generator. Finally, \textit{$Agreement_P$} and \textit{$Agreement_C $} are flags that indicate whether the energy producer or consumer, respectively, agree with all situations in the trade. The generator of EN signs the hash of the transaction content which potentially ensures the integrity of the transaction content. After populating EN, \textit{A} sends the transaction to the energy producers in $\Omega_j^1$. \par The energy producer may receive several EN transactions from consumers. The producer only responds to those who are in the set of $\Omega_i^1$. For each received EN from consumers in this set, the producer updates the price using (\ref{sell price update}). When the response from the producer is received by the consumers, they update their energy using (\ref{buyer power update}) and again respond to the producer. This process continues till both sides of the trade agree on the trade conditions and thus set $Agreement_P$ and $ Agreement_C$ as '1'. An EN transaction is considered as a valid transaction to be stored in the blockchain only when both energy producer and consumer sign the transaction and $Agreement_P$ and $ Agreement_C$ are set as '1'. This ensures that only the last transaction that contains the trade conditions is stored in the blockchain, which in turn increases the blockchain throughput and reduces the delay of the negotiation. \begin{algorithm}[tb!] \caption{Producer's Algorithm}\label{producer lag} \footnotesize{ \begin{algorithmic}[1] \State Submit offer AT \Comment{\textit{Advertisement}}\\ \state Explore AD to find potential trading partners \State Divide consumers in groups $\Omega_i^1, ..., \Omega_i^N$ using (\ref{prioritization sell}) \Comment{\textit{Prioritization}} \State Set $n\gets 1$ \State Receive EN transactions from consumers \Comment{\textit{Negotiation}} \While{$|\lambda_{ij}^{P,k+1}-\lambda_{ij}^{P,k}| \geq \epsilon$} \For {$j \in \Omega_i$} \State Receive $\gamma_{ij}$ from grid operator \State Receive $e_{ji}^{k}$ from consumer \State Calculate $\lambda_{ij}^{k+1}$ using (\ref{sell price update}) \State Update $\overline{\mu}_i^{k+1}$ and $\underline{\mu}_i^{k+1}$ using (\ref{sell mu low update}) and (\ref{sell mu up update}) \State Calculate $e_{ij}^{P,k+1}$ using (\ref{sell energy update}) \State Broadcast $\lambda_{ij}^{P,k+1}$ to consumers \EndFor \EndWhile \State Check if more energy is available \State Set $n\gets n+1$ \State Repeat Negotiation with new consumers \State Receive LP from consumers \Comment{\textit{Energy trading}} \State Inject agreed energy \State Sign EI \end{algorithmic} } \end{algorithm} \begin{algorithm}[tb!] \caption{Consumer's Algorithm}\label{consumer alg} \footnotesize{ \begin{algorithmic}[1] \State Submit ask AT \Comment{\textit{Advertisement}}\\ \state Explore AD to find potential trading partners \State Divide producers in groups $\Omega_j^1, ..., \Omega_j^N$ using (\ref{prioritization buy}) \Comment{\textit{Prioritization}} \State Set $n\gets 1$ \State Send EN transactions to producers \Comment{\textit{Negotiation}} \While{$|e_j^{P,k+1}-e_j^{P,k}| \geq \epsilon$} \For {$i \in \Omega_j^n$} \State Receive $\gamma_{ij}$ from grid operator \State Receive $\lambda_{ij}^{k}$ from producer \State Update $\overline{\mu}_j^{k+1}$ and $\underline{\mu}_j^{k+1}$ using (\ref{buyer mu low update}) and (\ref{buyer mu up update}) \State Calculate $e_{ji}^{P,k+1}$ using (\ref{buyer power update}) \State Broadcast $e_{ji}^{P,k+1}$ to producers \EndFor \EndWhile \State Check if more energy is needed \State Set $n\gets n+1$ \State Repeat Negotiation with new producers \State Send LP to producers \Comment{\textit{Energy trading}} \State Sign EI \end{algorithmic} } \end{algorithm} \subsection{Energy trading} In this section, we discuss the energy trading process. Once agents agree on the trade condition, during the negotiation step, the consumer generates a \textit{Late Payment} (LP) transaction that pays the energy price to the producer. Conventional energy trading frameworks rely on a TTP to oversee the trade and ensure that both sides of the trade commit to their obligations, which in turn reduces the privacy of the users. To address this challenge, our framework relies on atomic meta-transactions. In the latter, two transactions are considered valid if and only if both are generated within a specified time frame. Any incompatible transaction is considered as invalid and thus is not stored in the blockchain \cite{dorri2019spb}. LP is an atomic meta-transactions thus the energy price is not transferred to the producer accoutn unless LP is coupled with another transaction that is discussed in next paragraph. LP is structured as $<T\_ID, Price, Input, Output, EN\_Ref, Expiry\_Time, \\ Sign>$, where \textit{price} is price to be paid to the energy producer. \textit{Input} is the address of an unspent transaction that has enough balance to pay the transaction price, and \textit{output} is the address of the energy producer as in the last EN transaction. \textit{En\_Ref} is the address of the EN transaction that is stored in the public blockchain. \textit{Expiry\_Time} represents the time period in which the second transaction corresponding to the current LP must be generated, otherwise, LP is discarded. \textit{Sign} is the signature of the transaction generator that must be corresponding to the PK used in EN transaction. The consumer then broadcasts LP transaction.\par The energy producer starts injecting energy to the grid when it receives the LP transaction. Once the total amount of agreed energy is injected to the grid, the smart meter of the producer generates an \textit{Energy Injection} (EI) transaction which is a multisig transaction and is structured as $ <Amount, LP\_ID, PK\_P, Sign\_P, PK\_C, Sign\_C>$, where \textit{Amount} is the amount of energy injected into the grid by the producer. \textit{LP\_ID} is \textit{T\_ID} of the corresponding LP that is used for verification of the trade as outlined in the next paragraph. EI requires two out of two signatures to be considered as a valid transaction that are the energy producer signature, populated in \textit{PK\_P} and \textit{Sign\_P}, and energy consumer signature, populated in \textit{PK\_C} and \textit{Sign\_C}.\par Once EI is broadcasted to the network, the participating nodes in the blockchain start verifying the energy trade. First, the participants must locate the associated LP and EN. Recall that EI contains the \textit{LP\_ID} and LP contains \textit{EN\_Ref} that is the identifier of the EN transaction. The verifiers first match the signatures and PKs in the transactions. The next step is for the verifiers to validate that the amount and price agreed in the transactions match. Once all the above steps are successfully validated, EI and LP transactions are stored in the blockchain, which triggers the payment of the energy price to the energy producer. If the price in these transactions differs, the verifiers discard those transactions. \par In case of detecting inconsistency in the amount of the injected energy in EI, the verifiers call a \textit{Dispute Resolution} (DR) smart contract. The DR smart contract contains rules to manage the situation where the energy producer failed to transfer the promised amount of energy to the consumer, for example, the energy produced by the solar panel of an energy producer may be less than the estimated production, which potentially impacts the traded energy. Based on the amount of transferred energy identified in EI, DR calculates a new energy price and generates a \textit{Price Update (PU)} transaction requesting the energy consumer to generate a new LP with exactly the same condition as the previous one while updating the price. PU is structured as $<LP\_ID, Old\_Price, New\_Price>$. The new LP is broadcast to the network and is stored in the blockchain with the corresponding EI. \par Recall that in the proposed framework, we defined the reputation factor that impacts the decision making of the nodes. The reputation is given by the DR smart contract based on the commitments of an energy producer. In the case of the above example, the DR will reduce the reputation of the node and inform all participants. In this study, we consider the negative reputation only, which is when a node misbehaved in the network. \section{Case Studies}\label{sec: case study} \begin{figure} \input{casestudy} \caption{33-Bus test system.}\label{fig:test system} \end{figure} \begin{table}[] \centering \caption{Parameter Setup.}\label{tab:parameters} \begin{tabular}{cccc} \hline \multicolumn{4}{c}{\textbf{Key parameters}} \\ \hline Parameter & \multicolumn{1}{c|}{Value} & Parameter & Value \\ \hline $P$ & \multicolumn{1}{c|}{14} & $C$ & 18 \\ $\rho_\lambda$ & \multicolumn{1}{c|}{0.01} & $\rho_\mu$ & 0.001 \\ $\overline{\lambda}^G$& \multicolumn{1}{c|}{5 \cent/kWh^2} &$\underline{\lambda}^G$ & 25 \cent/kWh^2 \\ $N$& \multicolumn{1}{c|}{2} & $\omega$ & 2 \cent/kWh/ km \\ \hline \multicolumn{2}{c|}{\textbf{Producers' parameters}} & \multicolumn{2}{c}{\textbf{Consumers' parameters}} \\ \hline $a_i$ & \multicolumn{1}{c|}{(0.5-1] \cent/kWh^2} & $a_j$ & (0.5-10] \cent/kWh^2 \\ $b_i$& \multicolumn{1}{c|}{[5-10] \cent/kWh} & $b_j$ & [10-20] \cent/kWh \\ $\underline{e}_i$& \multicolumn{1}{c|}{[0-5] kWh} & $\underline{e}_j$ & [1-4] kWh\\ $\overline{e}_i$& \multicolumn{1}{c|}{[5-10] kWh} & $\overline{e}_j$ & [6-10] kWh \\ $\eta_i,\alpha_i,\beta_i$& \multicolumn{1}{c|}{[0-1]} & $\eta_j,\alpha_j,\beta_j$ & [0-1] \\ \hline \end{tabular} \end{table} In this section, simulation case studies are provided to verify the operation of the proposed framework. As shown in Fig. \ref{fig:test system}, the considered test system is the IEEE 33-bus distribution system with 16 producers and 16 consumers. Table \ref{tab:parameters} summarizes key parameters and range of values for producers and consumers parameters. Fig. \ref{fig: power and price res} illustrates the results of P2P trading in the test system. The traded energy and price in different transactions have various values based on the agents' preferences. Agents tend to trade energy with their closest neighbor agents to pay less grid service charge. For example, consumer at bus 1 buys energy from producer at bus 18. However, if the offer/ask from the agent at the nearest node is not available, or does not satisfy the requirement of the agents, they have to trade with other neighboring agents. For instance, while the nearest agents to agent 5 are agents at bus 4 and 6, this agent trades energy with producers at bus 26 and 27. Since agents 4 and 6 have preferred to trade with other neighboring nodes (agents at bus 3 and 7 respectively), their offers are not available to the agent 5. It can be seen that agents 16 and 17 do not buy any energy in the market. These agents have lower utility function parameters compared to their neighboring agents, which means that their willingness to pay for energy is less than agent 15, and hence, producer at bus 14 prefers to trade with the agent at bus 15. \begin{figure}[tb!] \centering \includegraphics[scale=0.75]{figures/tradedpowernew.pdf} \caption{Transactions between producers and consumers; a) traded energy, b) energy price.}\label{fig: power and price res} \end{figure} To investigate the impact of considering the grid service charge on the number of transactions ($n_T$), we implemented the energy trading algorithm for different values of $\omega$. The results are reported in Fig. \ref{fig:line flow}, where each marker indicates a transaction between the producer and consumer, and the total number of transactions in each case is given in parentheses. The case with \(\omega=0\) means that there is no limit on the distance of agents, and they can trade with any number of agents. Therefore, the number of transactions in this case is significantly higher. Increasing the value of $\omega$ reduces the number of transactions. The welfare of agents depend on the grid service charge that they pay (see (\ref{pro welf}) and (\ref{con welf})), and hence, increase in $\omega$ reduces their welfare as they have to trade less energy and pay more cost for utilizing the grid. The negotiation among agents is an iterative process and the time required for agents to reach agreement depends on several factors including, number of agents, number of iterations required for convergence in Algorithm \ref{producer lag} and \ref{consumer alg}, the computation time required to solve (\ref{sell update dec}) and (\ref{buyer update dec}) by agents in each iteration, and communication time. The results of implementing the market settlement algorithm with and without implementing \textit{prioritization} step are compared, as reported in Table \ref{tab:prioritization}. The \textit{prioritization} step reduces the number of negotiating agents, and hence, reduces the number of communication in each iteration. On the other hand, agents need less time to solve (\ref{sell update dec}) and (\ref{buyer update dec}), as they have fewer decision variables after \textit{prioritization}. Therefore, applying \textit{prioritization} reduces negotiation time among agents by nearly 45\%. \begin{figure} \centering \includegraphics[scale=0.85]{figures/lineflow.pdf} \caption{Impact of considering grid service charge on the number of transactions.}\label{fig:line flow} \end{figure} \begin{table}[tb!] \centering \caption{Impact of Prioritization.}\label{tab:prioritization} \setlength{\tabcolsep}{5pt} \begin{tabular}{lcc} \cline{2-3} \\[-0.7em] & \textbf{w prioritization} & \textbf{w/o prioritization} \\ \\[-0.7em] \hline No. of decision variables & \multirow{2}{*}{38, 16} & \multirow{2}{*}{20, 6} \\ \\[-1em] (producer, consumer) & & \\ \\[-1em] No. of communications & \multirow{2}{*}{63} & \multirow{2}{*}{252} \\ \\[-1em] (in each iteration) & & \\ \\[-1em] No. of iterations for convergence & 163 & 206 \\ \\[-1em] \hline Negotiation time (s) & 1.04 & 1.88 \\ \\[-1em] \hline \end{tabular} \end{table} \begin{table}[tb!] \centering \caption{Comparative results of P2P market.} \label{tab:p2p results} \setlength{\tabcolsep}{5pt} \begin{tabular}{lcc} \cline{2-3} \\[-0.7em] & \textbf{P2P} & \textbf{No P2P} \\ \\[-0.7em] \hline Total imported energy from grid (kWh) [$\sum_j{e_j^G}$] & 22.31 & 119 \\ \\[-1em] Total exported energy to grid (kWh) [$\sum_i{e_i^G}$] & 8.46 & 105 \\ \\[-1em] Total welfare of consumers ($\cent$) [$\sum_j{W_j}$] & 62.73 & -4143.04 \\ \\[-1em] Total welfare of producers ($\cent$) [$\sum_i{W_i}$] & 242.64 & -302.03 \\ \\[-1em] Total paid grid service charge ($\cent$) [$\sum_j \sum_i {e_{ij}^p \gamma_{ij}}$] & 50.44 & 0 \\ \hline \end{tabular} \end{table} In order to demonstrate the efficacy of the P2P market, the results of this market are compared with the case that producers and consumers only trade with the grid. Comparative results are reported in Table \ref{tab:p2p results}. As it can be inferred from the results, P2P market reduces the imported and exported energy by agents to the grid, meaning they trade more with other P2P agents. Also, since the P2P market price is more beneficial for agents (see (\ref{price lim})), they can reach a higher value of welfare in the P2P market, though they have to pay a grid service charge to the grid operator. As stated in Section \ref{sub:sec:advertisement}, in the proposed framework, the ATs are stored off chain in AD. Here, we study the impact of using AD by evaluating the blockchain size and number of consensus rounds, i.e., evaluating how many times the validators shall run the consensus algorithm. Blockchain size shows the amount of saved storage space by employing AD while the number of consensus rounds evaluates the amount of computational overhead saved by running less consensus rounds. We employed the structure and configuration of the IEEE 33-bus distribution to implement a distributed network using Java programming language on Raspberry Pi 2. It is assumed that the size of each block is 10 transactions. The process involved in the consensus algorithm is abstracted out as it does not impact the functionality of the proposed method. Ten market intervals are implemented during which each energy producer generates an AT. To benchmark the results, a baseline method is considered where all ATs are stored in the blockchain. To focus on the impact of AD, we disregard the rest of the functions and assume ATs are the only transactions generated during each market interval. Based on the implementation results, the size of each AT is 1776 B. After 10 epochs, the baseline blockchain includes 16 blocks with the cumulative size of 314KB. Thus, each node must allocate 314KB storage space to store blockchain. Our solution off-loads this overhead to a central trusted node who is managing the AD, thus there is no memory overhead on the participating nodes in the blockchain. Assume $\nu $ represents the overhead associated with appending a new block that includes computational, packet and memory overhead. The proposed framework incurs no overhead during the \textit{advertisement} process on the validators while the overhead is 16$\nu$ in the conventional methods. We next evaluate the processing overhead associated with CoL. We proposed a CoL that enables the users to anonymously verify the location of the parties involved in energy trading. CoL enhances the anonymity level of users and thus protects user privacy. On the flip side, it increases the processing overhead on the users to generate and verify CoL. To evaluate the incurred overhead, we implemented our framework using Java programming language on Raspberry Pi 2, which represents low-resource devices. We measured the processing time for generating the CoL request, which involves generating a set of keys and forming the Merkle tree, and verifying the CoL, which involves verifying the existence of the PK in the Merkle tree and validating the corresponding signatures. The implementation results are shown in Table \ref{tab:COL-performance}. The verification of the CoL involves verifying two signatures, which potentially takes longer time than generating CoL. In addition to the processing overhead, CoL increases the size of the transactions. Table \ref{tab:COL-packet} compares the size of transactions and shows that CoL only affects the AT. It nearly doubles the size of AT, but this does not affect the size of the blockchain as AT's are stored off-chain only. All other transactions are unaffected by CoL. \par \section{Security and Privacy Analysis}\label{sec:security} In this section, we analyze the security and privacy of the proposed framework. We first outline threat mode and then discuss possible attacks and how to protect against those.\par \textbf{\textit{Threat Model:}} We assume that the adversary (or cooperative adversaries) can sniff the communications, discard transactions, generate fake transactions, and pretend to be another node in the network. The adversary may attempt to deanonymize a user by classifying blockchain transactions and monitoring real-time communications in blockchain. We assume standard secure encryption algorithms are in place, which cannot be compromised by the adversary. We assume smart meters are tamper resistance, and thus the end users cannot modify the transactions generated by the meters. \par \begin{table}[tb!] \centering \setlength{\tabcolsep}{5pt} \caption{CoL processing time.}\label{tab:COL-performance} \begin{tabular}{ccc} \hline & CoL formation & CoL verification \\\hline Processing time (ms) & 663.2 & 1795 \\\hline \end{tabular} \end{table} \begin{table}[tb!] \centering \setlength{\tabcolsep}{5pt} \caption{Comparison of transaction sizes.}\label{tab:COL-packet} \begin{tabular}{ccccc} \hline & AT & EN & LP & EI \\\hline Including CoL (Bytes) & 2193 & 1928 & 1056 & 1912 \\\hline Excluding CoL (Bytes) & 1041 & 1928 & 1056 & 1912 \\\hline \end{tabular} \end{table} \subsection{Security} In the following, we discuss possible attacks and how the proposed framework protects against those. \par \textit{CoL Reply Attack:} In this attack, the malicious node attempts to employ CoL of another node to generate transactions. The node that employs a CoL is required to sign the corresponding transaction with the private key corresponding to a PK that exists in MTR that is only known to the CoL generator. Thus, it is impossible for a malicious node to utilize the CoL of another node. \par \textit{Fake CoL:} In this attack, a malicious node pretends to be a genuine smart meter generates fake CoL that can later be used in its energy tradings. The CoL must be signed only by a genuine smart meter, and the CA validates the PK of the verifier. In the case of this attack, CA will not validate PK, and thus the attack can be detected. \par \textit{Double selling:} In this attack, a malicious energy producer attempts to sell the same amount of energy to different consumers. Recall from Section \ref{sec:energy trading} that an energy trade involves three main transactions, which are EN, LP, and EI. Once the agreed energy is injected to the grid, the smart meter of the energy producer generates a EI transaction that triggers the payment of the energy price to the producer. The smart meter generates only one EI that includes a reference to the corresponding LP, and LP includes a reference to the corresponding EN. Thus, it is impossible for the energy producer to sell the same energy to multiple nodes. \par An energy producer may attempt to inject less energy than the agreed amount and claim the full price. The smart meter of the producer will only generate the EI if the full amount of agreed energy is injected to the grid. If the energy producer injects part of the energy and the expiry time approaches, the smart meter will generate an EI reflecting the amount that is injected to the grid. In this case, DR smart contract is called that adjusts the price of the energy and ensues the producer is only paid for the amount of energy injected to the grid. \par \textit{Reputation Modification:} In this attack, the malicious node attempts to improve their reputation or reduce the reputation of another node in the network. Recall that blockchain is an immutable ledger that makes it impossible to modify or remove previously stored transactions, which makes it impossible for the attacker to modify their reputation. To reduce the reputation of another node, the malicious node shall modify the code of the smart contract, which is impossible due to the immutability of the blockchain. DR smart contract is the only entity that can reduce the reputation of a node. All participants know the address of the valid DR contract. When participating nodes receive reputation reduction from a contract, they first verify if the contract address matches with the genuine DR smart contract. If so, they accept the new reputation. Otherwise, they discard the transaction. \subsection{Privacy} In the following, we analyze the proposed framework from the privacy perspective. Recall from Section \ref{sec:energy trading} that the grid operator charges a grid service charge per each transaction that depends on the distance between the energy consumer and producer. Thus, the consumer and producer must prove their location, however, this may compromise their privacy as malicious nodes can classify the blockchain transactions to deanonymize the user. To address this challenge, we proposed A-PoL that enables the participants in the blockchain to verify the location of an anonymous smart meter using a CoL. Assume node \textit{A} is using A-PoL. The privacy of \textit{A} can be studied from the perspective of the following entities: i) CA: \textit{A} uses the PK populated by the CA only to prove its identity to the verifier. CoL employed by \textit{A} includes PK of the verifier and not \textit{A}. Given that the verifier is selected randomly by \textit{A} and there is no link between \textit{A} and the verifier, the CA is unable to identify the transactions generated by \textit{A}, ii) verifier: \textit{A} only sends MTR to the verifier that hides the actual PKs of \textit{A} from the verifier. \textit{A} reveals the PKs in the Merkle tree to prove ownership of CoL. A group of smart meters may choose to create a single MTR, which further protects their privacy, and iii) network participants: the network participants only receive CoL that contains of the verifier and MTR. As outlined earlier, there is no link between the verifier and \textit{A}, thus knowledge of the identity of the verifier does not impact the privacy of \textit{A}. The Merkle tree includes a number of PKs that are employed by \textit{A} (or other involved smart meters) to generate transactions, thus, \textit{A} may generate multiple transactions with the same PK. This potentially reduces the anonymity level of the user as malicious nodes may attempt to deanonymize a user by classifying their transactions. The anonymity level of \textit{A} largely depends on the number of PKs employed in the Merkle tree. The large number of PKs incur overheads on \textit{A} to manage the keys. Thus, there is a trade-off between the number of keys in the Merkle tree and user anonymity. \par Recall from Section \ref{sub:sec:market-settlement} that the energy producer and consumer employ a cost/utility function, as shown in (\ref{cost-func-producer}) and (\ref{cost-function-consumer}), which represent their willingness to pay or accept energy price based on their preferences and concerns. These functions depend on $a_i$, $b_i$, and $c_i$, and thus it is critical for the producers and consumers to keep these values private. In the proposed framework, the market settlement does not need the nodes to reveal $a_i$, $b_i$ and $c_i$, which in turn enhances the privacy of the users. \section{Conclusion and Future Works}\label{sec:conclusion} In this paper, we propose a blockchain-enabled P2P energy market, which provides a secure and privacy-preserving environment for energy trading between producers and consumers. A decentralized market settlement process is designed, which allows agents to trade energy without revealing their private information. The grid service charge, calculated based on the distance between producer and consumer, is used to incite agents trade energy locally and to reduce the possibility of overloading electricity grid lines.\par To reduce the blockchain memory footprint, we propose AD that stores the energy advertisements and is maintained by the grid operator. A \textit{prioritization} step is implemented to enable agents to select their trading partners based on their location and reputation factors. In order to allow agents to prove their location without revealing their real identity, an A-PoL algorithm is proposed using CoL issued by smart meters. Simulation results on IEEE 33-bus test system confirm that the proposed framework improves the welfare of agents through P2P trading, while their privacy is protected. Furthermore, employing AD to store ATs, and limiting the number of trading partners through \textit{prioritization} decrease the system overheads. For future work is needed to relax the tamper resistance assumption conisdered for smart meters. Relaxing this assumption complicates the trust issue as the smart meters may generate fake transactions. As another research direction, the impact of mobility of the smart meters on A-PoL can be studied. In such cases, the CA must ensure that the location of a meter is as claimed before granting a certificate. It is critical for the CA to be able to revoke granted certificates as smart meters may change its location. Another challenge for future work is to explore ways of decentralizing the AD without increasing the blockchain memory footprint to achieve an even more decentralized energy marketplace. \bibliographystyle{IEEEtran}
{'timestamp': '2020-06-01T02:11:09', 'yymm': '2005', 'arxiv_id': '2005.14520', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14520'}
arxiv
\section{Introduction} The epidemic of SARS-CoV-2 infection triggered an unprecedented public health response. Given the lack of effective vaccine and treatment in 2020, this response included a variety of travel restrictions and social distancing measures \cite{Tian}. While these measures help to slow down the epidemic they come at significant economical and societal cost \cite{ECDCRRA}. As an alternative an approach focusing on rapid diagnosis is increasingly recommended \cite{WHO.S} and prior to lifting social distancing measures large-scale community testing should be in place \cite{EC}. Testing efforts are complemented by identifying and quarantining contacts of the diagnosed cases. Of note, by isolating the asymptomatic contacts from their social networks, this strategy takes into account the pre-symptomatic and asymptomatic spread of the infection \cite{Tong, Huang}, believed to be one of the key drivers of fast spread of COVID-19. As an example, wide spread testing in general population followed by isolation of the infected helped to reduce COVID-19 incidence by 90\% in an Italian village of Vo’Euganeo \cite{Day}. A modelling study in France offers similar conclusions arguing that relaxing social lock-down will be only feasible in case of extensive testing \cite{Di}. While there is already a number of studies estimating the effects of general social distancing measures \cite{Flaxman, Tian, Di, Giordano}, less is known about the impact of quarantine. Hellewell et al. \cite{Hellewell} investigated the potential of rapid isolation of cases and contact tracing to control the epidemic, finding that prohibitively high levels of timely contact tracing are necessary to achieve control. However, new technologies may offer sufficiently fast alternative to traditional contact tracing, in which case the epidemic could be still controlled by contact tracing \cite{Ferretti}. \smallskip Our aim is to develop a SEIR-type model which incorporates the effects of quarantine and validate it in a setting in which measures to reduce contacts are in place. We apply it to investigate the role of quarantine in Poland. The first case of COVID-19 in Poland was diagnosed on March 4th. Social distancing measures were rapidly introduced during the week of 9 - 13th March including closure of schools and universities, cancellation of mass events and closure of recreation facilities such as bars, restaurants, gyms etc. as well as shopping malls. Religious gatherings were limited. Finally, borders were closed for non-citizens \cite{Pinkas}. These measures were fully in place on March 16th. Further, beginning at March 25th restrictions on movement and travel were introduced (lock-down). Wearing face covers became obligatory on April 14th. The restrictions were gradually lifted beginning at April 20th. We focus on modelling the time period when the social distancing measures were in place and then consider different scenarios of relaxation of the restrictions with possible improvement of testing and contact tracing. We note that the procedures for quarantine were in place even before the social distancing measures. They initially focused on individuals arriving from COVID-19 affected areas in China. When the epidemic started spreading in European countries people who came back to Poland from these countries were advised to immediately seek medical attention if they experienced any symptoms consistent with COVID-19. However, adherence to these recommendations was not evaluated. As soon as the first case was diagnosed in Poland quarantine for close contacts was also implemented. \smallskip This paper aims to define a deterministic population model describing the epidemic in classical terms of susceptible, exposed, infectious, removed. In our model the quarantine becomes a separate state that removes individuals from susceptible and exposed states. We show that the reproductive number in our model is given by a simple formula referring to the parameters of transmission and transition, but also to parameters describing the quarantine. We demonstrate that in a real life scenario (case study of Poland) the quarantine effectively reduces the growth of infectious compartment. Increasing the efficiency of contact tracing and testing may may to some extent compensate lifting up the social distancing restrictions. \section{Methods} \subsection{The model} We introduce a modification of the classical SEIR model including effects of quarantine. To underline importance of that extension we call it SEIRQ. Formally the model is described by a system of ordinary differential equations with delay dedicated to the quarantine. \begin{figure}[h!] \label{model} \centering \includegraphics[width=0.75\textwidth]{obrazek_z_kwarantanna.pdf} \caption{{\bf Schematic representation of the states included in the model}. The solid lines represent the transition parameters and the dashed line indicate that the specific quantity is added.} \end{figure} \noindent The following states are included in the model: $S(t)$ -- susceptible $E(t)$ -- exposed (infected, not infectious) $I_d(t)$ -- infectious who will be diagnosed $I_u(t)$ -- infectious who will not be diagnosed $R_d(t)$ -- diagnosed and isolated $R_u(t)$ -- spontaneously recovered without being diagnosed $Q(t)$ -- quarantined \bigskip The figure \ref{model} presents the schematic representation of the model. A susceptible individual (state $S$), when becoming infected first moves to the state $E$, to model the initial period, when the infected individual is not yet infectious. Next the cases progress to one of the infectious states $I_d, I_u$ at the rates $\kappa\sigma$ and $(1-\kappa)\sigma$, respectively. In general, moving through the $I_d$ pathway concerns these individuals who (independently of quarantine) would meet the testing criteria, as relevant to the local testing policy, e.g. testing of people with noticeable symptoms. We shall emphasize that from the point of view of analysis of spread of infection, the quantity $I_u$ shall be regarded rather as not recognized infections, not necessarily asymptomatic or mild. With this interpretation the value of $\kappa$ can be influenced by intensity of testing. The creation of state $E$ is via $I_d$ and $I_u$ with transmission rates $\beta_d$ and $\beta_u$, respectively, normalized to the total population size $N=S+E+I_d+ I_u+R_d+R_u+Q$, which is assumed to be constant in time, births and deaths are neglected. The transition parameter $\sigma$ is assumed identical for both groups, relating to the time between infection and becoming infectious. The infectious individuals then move to the state $R_d$, which is the state of being diagnosed and isolated (and later recovered or deceased), with the rate $\gamma_d$ corresponding to the observed time between onset and diagnosis. On the other hand $R_u$ contains people who spontaneously recovered with rate $\gamma_u$. Our model includes an additional state of being quarantined ($Q$). To mimic the situation of contact tracing, individuals can be put in quarantine from the state $S$ (uninfected contacts) or the state $E$ (infected contacts). These individuals stay in the quarantine for a predefined time period $T$. We assume that the number of people who will be quarantined depend on the number of individuals who are diagnosed. An average number of individuals quarantined per each diagnosed person is denoted as $\alpha$. However, as the epidemic progresses some of the contacts could be identified among people who were already infected, but were not previously diagnosed, i.e. the state $R_u$. We note that moving individuals between the states $Q$ and $R_u$ has no effect on the epidemic dynamics, therefore we assume that only individuals from $S$ and $E$ are quarantined and we reduce the average number of people put on quarantine by the factor $\frac{S(t)}{S(t)+R_u(t)}$. Further, to acknowledge the capacity limits of the public health system to perform the contact tracing, we introduce a quantity $K_{max}$, describing the maximum number of people who can be put in quarantine during one time step. We also assume that among the quarantined a proportion $\theta$ is infected. After the quarantine, the infected part $\theta K(t-T)$ goes to $R_d$ and the rest $(1-\theta)K(t-T)$ returns to $S$. Taking all of the above into account, the model is described with the following SEIRQ system: \begin{equation}\label{seir} \begin{array}{l} \dot S(t)=- S(t) (\beta_d I_d(t)+\beta_uI_u(t)) - (1-\theta)K(t) + (1-\theta)K(t-T), \\[5pt] \dot E(t)= S(t) (\beta_d I_d(t) + \beta_u I_u(t)) - \sigma E(t) - \theta K(t)\\ [5pt] \dot I_d(t)=\kappa \sigma E(t) - \gamma_d I_d(t), \\[5pt] \dot I_u(t)=(1-\kappa) \sigma E(t) -\gamma_u I_u(t),\\[5pt] \dot R_d(t)= \gamma_d I_d(t) + \theta K(t-T),\\ [5pt] \dot R_u(t)=\gamma_u I_u(t),\\[5pt] \dot Q(t)= K(t)-K(t-T),\\[5pt] \mbox{where \ \ } K(t)={\rm min}\{\frac{S(t)}{S(t)+R_u(t)} \alpha \gamma_d I_d(t), K_{max} \}, \mbox{\ \ and \ \ } \alpha,\beta_d,\beta_u,\gamma_d,\gamma_u, \theta, T \geq 0. \end{array} \end{equation} We assume that the parameters $\alpha, \beta_d, \beta_u, \theta$, $\gamma_u$ and $\gamma_d$ depend on the country and time-specific public health interventions and may therefore change in time periods. Due to proper interpretation of the equation on $E$ we require that $\beta_d \geq \theta \alpha \gamma_d$ to ensure positiveness of $E$. \subsection{Basic reproductive number, critical transmission parameter $\beta^*$.} Based on the general theory of SEIR type models \cite{Dik}, we introduce the reproductive number \begin{equation} \label{def:R0} \mathcal{R}=\kappa \left( \frac{ \beta_d}{\gamma_d} - \theta \alpha \right) + (1-\kappa) \frac{\beta_u}{\gamma_u}. \end{equation} It determines the stability of the system as $\mathcal{R} <1$ and instability for $\mathcal{R}>1$ (the growth/decrease of pandemia). This quantity not only explains the importance is testing (in terms of $\kappa$) and quarantine (in terms of $\alpha$), but also gives an indication on levels of optimal testing and contact tracing. We underline that this formula works for the case when the capacity of the contact tracing has not been exceeded $(K(t)<K_{max})$. The details of derivation of \eqref{def:R0} are provided in the Appendix, section \ref{sec:R}. We shall emphasize the formal mathematical derivation holds for the case when $I$ and $E$ are small comparing to $S$. Therefore the complete dynamics of the nonlinear system (\ref{seir}) is not fully determined by \eqref{def:R0}. However in the regime of epidemic suppression, which is the case of COVID-19 epidemic in Poland, $I$ and $E$ are small compared to $S$ and so the formula (\ref{def:R0}) reasonably prescribes spreading of infection in the population. The critical value $\mathcal{R}=1$ defines the level of transmission which is admissible, taking into account the existing quarantine policy, in order to control epidemic. As the level of transmission depends on the level of contacts, this provides information on the necessary level of social distancing measures. The formula \eqref{def:R0} indicates that improving the contact tracing may compensate relaxation of contact restrictions. The key quantity is $\theta \alpha$. Indeed the system with the quarantine has the same stability properties as one without $K$, but with the new transmission rate $\beta_d^{new}=\beta_d - \theta \alpha \gamma_d$. In order to guarantee the positiveness of $E$, $\beta_d^{new}$ must be nonnegative. It generates the constraint \begin{equation} \label{3.1} \theta\alpha\gamma_d \leq \beta_d. \end{equation} The above condition also implies the theoretical maximal admissible level of quarantine. We define it by improving the targeting of the quarantine, i.e. by the highest possible level of $\theta$: \begin{equation}\label{def:thetamax} \theta_{max} = \frac{\beta_d}{\gamma_d\alpha}. \end{equation} As long as the $K_{max}$ threshold is not exceeded the effect of the increase in $\theta$ or in $\alpha$ play the same role at the level of linearization (small $I, E$). However, in general it is not the case and for the purpose of our analysis we fix $\alpha$. For our analysis we assume $\beta_d=\beta_u=\beta$. The reason is that, both $I_d$ and $I_u$ contain a mixture of asymptomatic and symptomatic cases and although there might be a difference we lack information to quantify this difference. Then using formula \eqref{def:R0} we compute critical values $\beta^*(\kappa,\theta,\alpha)$ defined as \begin{equation} \label{def:betacrit} {\mathcal R}(\beta^*)=1, \mbox{ \ namely \ } \beta^*(\kappa,\theta,\alpha,\gamma_d,\gamma_u)=\frac{(1+\theta\alpha\kappa)\gamma_d\gamma_u}{\gamma_u\kappa+\gamma_d(1-\kappa)}. \end{equation} It shows the upper bound on transmission rate $\beta$ which still guarantees the suppression of pandemic. We shall omit the dependence on $\gamma_d,\gamma_u$ as these are fixed in our case, and denote briefly $\beta^*(\kappa,\theta,\alpha)$. In the case of maximal admissible quarantine (\ref{def:thetamax}) we obtain \begin{equation} \label{betamax} \beta^*(\theta_{max},\kappa) = \frac{\gamma_u}{1-\kappa}, \end{equation} which can be regarded as theoretical upper bound for $\beta$ if we assume "optimal admissible" quarantine for fixed $\kappa$, for which the epidemic could be still controlled. It must be kept in mind though that the condition (\ref{3.1}) means that we are able to efficiently isolate all persons infected by every diagnosed, therefore is unrealistic. The resulting $\beta^*(\theta_{max},\kappa)$ should be therefore considered as a theoretical limit for transmission rate. \subsection{Fitting procedure} All simulations are performed using GNU Octave ({\em https://www.gnu.org/software/octave/}). The underlying tool for all computations is a direct finite difference solver with a 1 day time step. \smallskip {\bf Basic assumptions for data fitting.} We estimate the transmission rates $\beta$ by fitting the model predictions to the data on the cumulative number of confirmed cases. Since people with confirmed diagnosis are efficiently isolated, they are immediately included into $R_d$. Therefore, the quantity fitted to the data is $R_d(t)$. The crucial assumption behind our approach is that the parameter $\beta$ changes twice during the period of analysis. The reason is that we can distinguish two important time points in the development of epidemic in Poland. The first is initial restrictions including school closure effective March 12, which was accompanied with restrictions on other social activities. As we do not take migration into account in our model, we assume that the effect of border closing is reflected in $\beta$. The second turning point was a lockdown announced on March 25. For simplicity we comprise the effect of above measures in two jump changes in $\beta$ in $t \in \{t_1,t_2\}$ and choose $t_1=14, \quad t_2=28$. With $t=1$ corresponding to March 3 it means small delay with respect to the above dates which can be justified by the fact that new cases are reported with a delay of approximately 2 days. \smallskip {\bf Choice of fixed parameters (Tab. \ref{tab0}).} We assume that the parameters $\sigma, \gamma_u$ represent the natural course of infection and their values could be based on the existing literature. The parameter $\sigma$ describes the rate of transition from non-infectious incubation state $E$ into the infectious states $I_d$ or $I_u$. The value of $\sigma$ takes into account the incubation period and presymptomatic infectivity period. $\gamma_u$ relates to the period of infectivity, which we select based on the research regarding milder cases, assuming that serious cases are likely diagnosed. Further, $\kappa$ is a parameter related both to the proportion of asymptomatic infection and the local testing strategies. Since the literature findings provide different possible figures, for $\kappa$ we examine three different scenarios. Parameters $\gamma_d, \theta$ and $\alpha$ are fixed in our model for the purpose of data fitting, but informed by available data. One of the scenarios of future dynamics of the epidemic (section \ref{sec:future}) considers possible increase of $\theta$. Parameter $\gamma_d$ was estimated basing on time from onset to diagnosis for diagnosed cases, and $\theta$ as rate of diagnosed among quarantined. Furthermore we fix the parameter $\alpha$ by comparing the number of quarantined people obtained in simulations with actual data. The capacity level of public health services is set in terms of possible number of quarantined per day $K_{max}$, as double the level observed so far. Detailed justification of the values of fixed parameters collected in the following table, is given in the Appendix, section \ref{sec:par}. \begin{table}[h!] \centering \begin{tabular}{|c|c|c|} \hline & & \\[-8pt] Parameter & Value & Source \\[4pt] \hline& & \\[-8pt] $\sigma$ & $\frac{1}{3.5}$ & Literature: incubation time \cite{Guan, Li.Q, Lauer} \\ & & + presymptomatic spread \cite{Wei, Tong, Huang} \\[4pt] \hline & & \\[-8pt] $\gamma_d$ & $\frac{1}{5.5}$ & Observed data: appendix section \ref{sec:par} \\[4pt] \hline & & \\[-8pt] $\gamma_u$ & $\frac{1}{10}$ & Literature: \cite{Hu}, WHO mission report from China \\[4pt] \hline & & \\[-8pt] $\kappa$ & \{0.2; 0.5; 0.8\} & Literature: proportion asymptomatic\\ & & or undocumented \cite{Li.R, Nishiura, Day,John} \\[4pt] \hline & & \\[-8pt] $\theta$ & 0.006 & Observed data: appendix section \ref{sec:par} \\[4pt] \hline & & \\[-8pt] $\alpha$ & 75 & Observed data: appendix section \ref{sec:par} \\[4pt] \hline & & \\[-8pt] $K_{max}$ & 50 000 & $2 \,\times$ the maximum level observed so far (arbitrary decision) \\[4pt] \hline \end{tabular} \caption{Fixed parameters used in the model} \label{tab0} \end{table} {\bf Optimization algorithm.} In order to fit the values $\beta_1,\beta_2,\beta_3$ we use a standard gradient descent algorithm. The error function is defined as mean square difference between the cumulative number of diagnoses and the $R_d(t)$ predicted from the model. For the initial values the error function is optimized only for a limited number of possible conditions, as these mostly impact $\beta_1$, which is less relevant for future predictions. To estimate confidence intervals we use a method of parametric bootstrap. The optimisation procedures are described in the Appendix, section \ref{sec:opt}, where we also show precise errors of data fitting. \smallskip {\bf Dataset.} The data series contains cumulative number of confirmed cases of COVID-19 in Poland from March 3 (first confirmed case in Poland) till April 26, which amounts to 54 observations. The data are taken from official communications of the Ministry of Health. As explained in table \ref{tab0} and appendix (section \ref{sec:par} additional data sources were used for choosing $\theta$, $\alpha$ and $\gamma_d$. \section{Results} \label{s:sym} \subsection{Estimation of parameters and "no-change" scenario predictions} In Table \ref{tab2.1} we show estimated values of $\beta_i$, where $i=1,2,3$ correspond to the time intervals when different measures were in place, and the ${\mathcal R}$ for the third time interval. Given the social distancing measures in place early April 2020, as well as the quarantine levels, the reproductive number was below 1, independently of the value of $\kappa$, which relates to testing effectiveness. The figure \ref{fig2.0} shows the fit of the models assuming different levels of $\kappa$. Good fit is found for all three models although predictions start to differ in the middle-term prognosis. \begin{figure}[h!] \begin{center} \includegraphics[width=12cm]{dopasowanieRdRu.pdf} \end{center} \caption{Results of model fit to cumulative diagnosed cases ($R_d$) for $\kappa=0.2,0.5,0.8$ (panel A) and corresponding predictions for undiagnosed, recovered compartment, $R_u$ (panel B). Coloured shades correspond to 95\% confidence intervals for the respective colour line.} \label{fig2.0} \end{figure} \begin{table}[h!] \centering \begin{tabular}{|c|c|c|c|} \hline & & & \\[-8pt] & $\kappa=0.2$ & $\kappa=0.5$ & $\kappa=0.8$ \\[4pt] \hline & & & \\[-8pt] $\beta_1$ & 0.635 & 0.684 & 0.738 \\[4pt] & (0.569 , 0.701) & (0.611 , 0.744) & (0.672 , 0.812) \\[4pt] \hdashline & & & \\[-8pt] $\beta_2$ & 0.332 & 0.383 & 0.442 \\[4pt] & (0.288 , 0.397) & (0.336 , 0.443) & (0.4 , 0.514) \\[4pt] \hdashline & & & \\[-8pt] $\beta_3$ & 0.099 & 0.132 & 0.175 \\[4pt] & (0.081 , 0.118) & (0.11 , 0.149) & (0.147 , 0.214) \\[4pt] \hdashline & & & \\[-8pt] $\mathcal{R}(\beta_3, 0.006,75)$ & 0.817 & 0.802 & 0.772 \\[4pt] & (0.651 , 0.977) & (0.648 , 0.915) & (0.569 , 0.874) \\[4pt] \hline \end{tabular} \caption{Estimated values of $\beta_i$ and values of $\mathcal{R}$ corresponding to the latest estimation period with 95\% confidence intervals } \label{tab2.1} \end{table} We proceed with predictions assuming that the restrictions are continued, i.e.keeping $\beta=\beta_3$ (note that the estimated $\beta_3$ is different for each $\kappa$). We calculate the epidemic duration ($t_{max}$), the peak number of infected ($I_d^{max}, I_u^{max}$) and the final size of the epidemic ($R_d(t_{max}), R_u(t_{max})$). In order to show the influence of quarantine we compare the situation with quarantine, keeping the same $\theta,\alpha$, to the situation without quarantine, setting $\alpha\theta=0$. The results of the development of the epidemic during the first 120 days are shown on Figure \ref{fig2.2a}. For $\kappa=0.2$ the difference between the scenarios with and without quarantine is visible but not striking. However for $\kappa=0.5$ and $\kappa=0.8$ a bifurcation in the number of new cases occurs around $t=40$ leading to huge difference in the total time of epidemic and total number of cases. These values are summarized in the table \ref{tab2.2}. We note that given the epidemic state in the first half of April 2020 for all values of $\kappa$ the model predicts epidemic extinction both with quarantine and without quarantine. However, since the epidemic is very near to the endemic state, the predicted duration is very long, especially if no quarantine is applied. \begin{table}[h!] \centering \begin{tabular}{|c|c|c|c|c|c|c|} \hline & & & & & & \\[-8pt] $\kappa$ & quarantine factors & $R_d(t_{max})$ & $R_u(t_{max})$ & $I_d^{max}$ & $I_u^{max}$ & $t_{max}$ \\ [4pt] \hline & & & & & & \\[-8pt] 0.2 & $\theta=0.006, \alpha=75$ & 31 & 85 & 1.9 & 10.8 &450 \\ & $\theta,\alpha = 0$ & 44 & 175 & 2.1 & 12.5 & 830 \\[4pt] \hline & & & & & & \\[-8pt] 0.5 & $\theta=0.006, \alpha=75$ & 29 & 20 & 1.9 & 2.7 & 330 \\ & $\theta,\alpha = 0$ & 1078 & 1078 & 5.1 & 9.2 & 3200 \\[4pt] \hline & & & & & & \\[-8pt] 0.8 & $\theta=0.006, \alpha=75$ & 24 & 4 & 1.9 & 0.7 & 230 \\ & $\theta,\alpha = 0$ & 6317 & 1579 & 10.6 & 47.6 & 1280 \\[4pt] \hline \end{tabular} \caption{ Duration of epidemic ($t_{max}$) in days, the final values of $R_d$ and $R_u$, in thousands ($R_d(t_{max}), R_u(t_{max})$) and peak values of $I_d$ and $I_u$, in thousands ($I_d^{max}, I_u^{max}$) according to quarantine and testing scenarios.} \label{tab2.2} \end{table} \begin{figure}[h!] \centering \includegraphics[width=16cm]{PanelPorPredykcji.pdf} \caption{Predicted values of $R_d,R_u$ (panels A -- C) and $I_d, I_u$ (panels D -- E), as depending on the value of $\kappa$ and whether or not the quarantine is implemented. For $t>54$ $\beta=\beta_3$ estimated for each $\kappa$, with the same quarantine parameters or without quarantine at all.} \label{fig2.2a} \end{figure} \subsection{Critical $\beta^*$ for the current situation} Using the formula \eqref{def:betacrit} we can compute critical values $\beta^*$. In Table \ref{tab1} we show the values of $\beta^*(\kappa,0.006,75)$ and for convenience recall also estimated values of $\beta_3$ and ${\mathcal R}$, listed already in Table \ref{tab2.1}. Moreover we compute $\beta^*(\kappa,0,0)$, i.e. without quarantine and show values of ${\mathcal R}$ for our estimated values of $\beta_3$ and the same $\gamma_d, \gamma_u$ but without quarantine. Comparing the estimated values of $\beta_3$ (table \ref{tab1}) for all cases of $\kappa$ are only slightly below $\beta^*$. \begin{table}[h!] \centering \begin{tabular}{|c|c|c|c|c|c|c|} \hline $\kappa$ & $\beta_3$ & $\beta^*(\kappa,0.006,75)$ & ${\mathcal R}(\beta_3,\kappa,0.006,75)$ & $\beta^*(\kappa,0,0)$ & ${\mathcal R}(\beta_3,\kappa,0,0)$ & $\beta_3 - \theta \alpha \gamma_d$ \\ \hline 0.2 & 0.099 & 0.12 & 0.817 & 0.11 & 0.907 & 0.018 \\ 0.5 & 0.132 & 0.158 & 0.802 & 0.129 & 1.03 & 0.051 \\ 0.8 & 0.175 & 0.211 & 0.772 & 0.155 & 1.132 & 0.074 \\ \hline \end{tabular} \caption{Values of $\beta^*$ and $\mathcal R(\beta_3)$ with quarantine ($i=0.006, \; \alpha=75$) and without quarantine } \label{tab1} \end{table} Eliminating the quarantine, for the estimated values of $\beta_3$, we have different situations depending on the actual value of $\kappa$. In case $\kappa=0.2$, so assuming that currently only 20\% of infections are diagnosed, the low values of ${\mathcal R}$ are due to low $\beta_3$ rather than the effect of quarantine (controlling epidemic by social contact restrictions). In effect even if we remove the quarantine we have still ${\mathcal R}<1$, but very close to 1. On the other hand if $\kappa=0.5$ or $\kappa=0.8$ we estimate higher $\beta_3$, which corresponds to the situation of controlling the epidemic by extensive testing and quarantine. For these cases, if we remove the quarantine, we end up with ${\mathcal R}>1$. The quantity $\beta_3-\theta\alpha\gamma_d$ represents effective transmission rate due to diagnosed cases. In particular it shows by how much the transmission could be reduced by improved contact tracing ($\theta\alpha$) and faster diagnosis ($\gamma_d$). These results confirm that the higher is the ratio of undiagnosed infections, the weaker is influence of quarantine. In the next section we verify these results numerically. \subsection{Impact of quarantine at relaxation of social distancing} \label{sec:future} Our second goal is to simulate loosening of restrictions. In particular we want to verify numerically the critical thresholds $\beta^*$ listed in table \ref{tab1}. For this purpose we assume that at $t=60$ we change $\beta$. For each value of $\kappa$ we consider 3 scenarios:\\[2pt] {\bf (a)} Current level quarantine: i.e. quarantine parameters $\theta=0.006, \; \alpha=75$ are maintained;\\[2pt] {\bf (b)} No quarantine is applied starting from $t=60$; \\[5pt] {\bf (c)} The maximal admissible quarantine is applied, meaning that $\theta_{max}=\frac{\beta}{\alpha \gamma_d}$ (see (\ref{def:R0})). In this case $\alpha=75$. As long as the limit $K_{max}$ is not reached there is no difference whether we increase $\alpha$ or $\theta$, the decisive parameter is $\alpha \theta$. Increasing $\alpha$ would lead to reaching $K=K_{max}$ earlier and hence worse outcomes.\\[5pt] Figures \ref{fig3.1}-\ref{fig3.3} show the final values of $R=R_d+R_u$ and time till the end of epidemic depending on the value of $\beta$ for $t \geq 60$. for above 3 scenarios and different values of $\kappa$. The theoretical values of $\beta^*$ are shown by black lines. The results confirm that around $\beta^*$ a rapid increase in the total number of infected occurs, coinciding with the peak total epidemic duration. Thus the numerical computations confirm that the critical $\beta^*$ calculated for the linear approximation in the section 2.2 are adequate, with a small bias towards lower values. \begin{figure}[h!] \centering \includegraphics[width=14cm]{koniecBYbeta_02.pdf} \caption{Duration of epidemic and the final epidemic size as dependent on $\beta$, for $\kappa=0.2$.} \label{fig3.1} \end{figure} The case $\kappa=0.2$ shows that the influence of quarantine is not high, even for the maximal admissible case, when we are able to efficiently isolate all persons infected by every diagnosed. \begin{figure}[h!] \centering \includegraphics[width=14cm]{koniecBYbeta_05.pdf} \caption{Duration of epidemic and the final epidemic size as dependent on $\beta$, for $\kappa=0.5$.} \label{fig3.2} \end{figure} \begin{figure}[h!] \centering \includegraphics[width=14cm]{koniecBYbeta_08.pdf} \caption{Duration of epidemic and the final epidemic size as dependent on $\beta$, for $\kappa=0.8$.} \label{fig3.3} \end{figure} A striking feature in the behaviour of total number of infected are jumps for certain critical value of $\beta$ observed for $\kappa=0.5$ and $\kappa=0.8$, both in case $\theta=0.006$ and $\theta=\theta_{max}$. The values of $R_d$ and $R_u$ before and after these qualitative changes are summarized in Table \ref{tab3.1}. \begin{table}[h!] \centering \begin{tabular}{|c|c|c|c|c|} \hline & $\beta$ & $R_d(t_{max})$ & $R_u(t_{max})$ & $t_{max}$ \\ \hline & & & & \\[-8pt] $\kappa=0.5, \; \theta=0.006$, & 0.163 & 1171 & 811 & 4170 \\[3pt] & 0.164 & 6160 & 5875 & 1200 \\[4pt] \hline & & & & \\[-8pt] $\kappa=0.5, \; \theta=\theta_{max}(\beta)$, & 0.211 & 1423 & 666 & 4800 \\[3pt] & 0.212 & 11458 & 10971 & 840 \\[4pt] \hline & & & & \\[-8pt] $\kappa=0.8, \; \theta=0.006$ & 0.218 & 1137 & 236 & 4740 \\[3pt] & 0.219 & 13706 & 3365 & 1060 \\[4pt] \hline & & & & \\[-8pt] $\kappa=0.8, \; \theta=\theta_{max}(\beta)$ & 0.566 & 1762 & 108 & 2850 \\[3pt] & 0.567 & 27602 & 6729 & 570 \\[4pt] \hline \end{tabular} \caption{Critical values of $\beta$ obtained in simulations and corresponding final numbers of diagnosed/undiagnosed (in thousands) and total time of epidemic.} \label{tab3.1} \end{table} A closer investigation for these values of $\beta$ shows that in all 4 cases the jump occurs for the first value of $\beta$ for which the limit number of quarantined, $K_{max} = 50 000$, is achieved. Notice that immediately after passing the threshold the values become very close to those without quarantine. Therefore the effect of quarantine is immediately and almost completely cancelled after passing the critical value of $\beta$. The transition is milder in the case $\kappa=0.2$ which can be explained by the fact that the transition takes place for lower values of $\beta$. Results of our simulations confirm the theoretical prediction that the margin in relaxation of restrictions is very narrow if we want to avoid a blow up of the number infections. Strengthening of quarantine allows to remain in a stable regime while increasing $\beta$. \section{Discussion} We propose a simple SEIR-type model (SEIRQ), which includes the effects of testing and contact tracing. The model formulation allows to calculate an interpretable formula for the reproductive number $\mathcal{R}$ \eqref{def:R0}. As typical for this class of models, $\mathcal{R}$ depends on transmission parameters $\beta$. Increasing $\beta$ corresponding in e.g. to higher frequency of social contacts increases $\mathcal{R}$. Decreasing $\beta$, for example in consequence of widespread use of face masks, has the opposite effect. On the other hand $\gamma_d$ reflects the time to diagnosis and the formula indicates that more rapid diagnosis is associated with lower $\mathcal{R}$. In addition, our model offers a clear interpretation of the quarantine effect. The transmission rate due to diagnosed cases, $\beta_d$, is decreased by the factor $\theta\alpha\gamma_d$ indicating that both the number of quarantined per diagnosed individual ($\alpha$) and proper targeting of the quarantine (the infection rate among the quarantined $\theta$) equally contribute to this factor. Also the parameter related to testing: the delay in diagnosis, $\gamma_d^{-1}$, plays similar role. This quantifies the potential of a wide range of interventions to improve testing and contact tracing, as outlined in e.g. in ECDC recommendations \cite{ECDCCT}. In particular, as the number of people put in quarantine per each case and the infection rate among the quarantined impact $\mathcal{R}$ in similar fashion, our results support the recommendations to focus on the high risk contacts when the resources do not allow to follow all contacts. Our model takes into consideration only the effective contact tracing, i.e. the situation when the infected contacts are identified and put in quarantine before they become infectious. People who are identified later would be modelled as passing through one of the $I$ states to the $R$ states. This means that the number of quarantined in our model can be also increased by faster contact tracing. The timely identification of contacts may be a significant challenge in the quarantine approach given that the incubation time can be as short as 2 days in 25\% of cases \cite{Guan}. As mentioned by other Authors \cite{Ferretti}, the delays in manual contact tracing are usually at least 3 days and under such circumstances the contact tracing and quarantine alone may be insufficient to control the epidemic. This could be improved with digital contact tracing. Notably, mixed contact tracing strategies implemented in South Korea indeed helped to control the epidemic at the early stages \cite{Korea}. The use of "smart contact tracing" with mobile phone location data and administrative databases were also key to rapid identification and self-quarantine of contacts in Taiwan \cite{Chen} and implementation of such strategy helped Singapore to control the epidemic without major disruptions of social activities \cite{Ng}. We note that the quarantine effect relates only to transmission due to diagnosed cases. As expected, in order to control the epidemic the transmission due to undiagnosed cases has to be negligible. This can be controlled by general measures such as {\it lockdown}, which universally decrease the frequency of social contacts and are therefore likely to reduce $\beta_u$. In our model the part of $\mathcal{R}$ representing transmission due to undiagnosed cases is scaled by $(1-\kappa)$, the parameter relating to the efficiency of the testing system. Again, the examples of Singapore as well as the Italian village of Vo’Euganeo show that the widespread testing complementing the efficient contact tracing was essential to suppress epidemic. Testing unrelated to epidemiological links decreases $(1-\kappa)$ factor, thus making the factors impacting transmission due to diagnosed cases, such as quarantine, more powerful to decrease $\mathcal{R}$. Further, our model allows to study the effect of the situation, in which the contact tracing capacities are exceeded. In this situation the epidemic is likely to quickly develop to the levels observed without quarantine. It is therefore quite crucial to implement the aggressive contact tracing system, when the epidemic is still at low levels and it is possible to bring the epidemic to suppression phase. We demonstrate the high impact of contact tracing and quarantine on the observed numbers of cases in Poland. This effect was coupled with substantial reduction in the transmission parameter $\beta$ resulting from social contact restrictions. Depending on the scenario, $\beta$ decreased by 76\% to 84\%, bringing $\mathcal{R}$ below 1. The estimated effect of the quarantine in Poland would depend on which of the considered scenarios regarding testing efficiency was the most relevant to our situation. In our model the quarantine is estimated to be the most effective for the scenario in which most of the cases are diagnosed ($\kappa=0.8$). Testing strategies that comprise testing of all individuals with symptoms of respiratory illness could theoretically identify up to 82\% of infected, assuming they would all present to medical care. This could be coupled with random screening of high risk individuals, in e.g. health care workers, or - in case of high incidence - even random screening of entire community to achieve the $\kappa$ of the order of 0.8. The Polish clinical recommendations specifically mention only testing all individuals with severe infections \cite{AOTMIT}. In addition testing is provided to health care workers. The severe course corresponds to approximately 18\% of all infections \cite{Guan}. Therefore, the $\kappa=0.8$ scenario is unlikely to be realistic in Poland. We believe that the plausible current $\kappa$ in our country lies between 0.2 and 0.5. For these scenarios the model shows that the control of the epidemic is largely achieved through suppression of $\beta$. In case of relaxation of social contact restrictions, the efforts should be focused on increasing the level of testing in order to decrease the proportion of undiagnosed cases as well as maintaining or increasing the effectiveness of quarantine. For smaller $\kappa$, even substantially increasing the effectiveness of quarantine does not allow to go back to the level of social contacts from before the epidemic ($\beta_1$). Finally, the contact tracing effort was manageable in Poland due to relatively small number of cases. Should the case load increase substantially longer delays in contact tracing would occur, which can substantially decrease the effects of quarantine \cite{Hellewell, Ferretti}. \smallskip {\bf Limitations and future directions of research.} We do not consider the likely reduced transmission from undiagnosed cases who are more likely to be asymptomatic or paucisymtopmatic cases $(\beta_u<\beta_d)$. The reduction factor for infectiousness of asymptomatic is still under investigation. One study found a 60-fold lower viral loads in asymptomatic cases \cite{Liu}, but another estimated the transmissibility reduction by 50\% \cite{Li.R}. Moreover, we did not have sufficient data to include this additional parameter. We calibrated our model only to diagnosed cases, which were officially available. Calibration to mortality data is another approach successfully implemented in e.g. \cite{Flaxman} that potentially removes bias due to different testing policies. As there were relatively fewer fatalities in Poland and little data on clinical progression we decided on simplified model without explicit modelling of the outcomes. Furthermore, we did not consider the sub-optimal adherence to quarantine. It is likely that some individuals would not fully comply to strict quarantine rules. However, only anecdotal evidence for such phenomenon is available at this time. In our model it would decrease the effective $\alpha\theta$, which was chosen to fit to observed number of people put in quarantine. Finally, the analysis of $\mathcal{R}$ is suitable for small size of epidemic, when $S \approx N$. For other cases the results are still useful, but the approximation may be biased, as we have shown for $\beta^*$. Due to little available data and policy changes we did not have sufficient data to determine which $\kappa$ scenario is the most appropriate. \smallskip In conclusion we present a simple model, which allows to understand the effects of testing, contact tracing and quarantining of the contacts. We apply the model to the data in Poland and we show that despite a substantial impact of contact tracing and quarantine, it is unlikely that the control of the epidemic could be achieved without any reduction of social contacts. \smallskip {\bf Acknowledgments.} This work was partially supported by the Polish National Science Centre’s grant No2018/30/M/ST1/00340 (HARMONIA).
{'timestamp': '2020-06-01T02:11:17', 'yymm': '2005', 'arxiv_id': '2005.14532', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14532'}
arxiv
\section{Introduction} \label{sec:introduction} \input{introduction} \section{Notation} \input{notation} \section{DCTN's description} \subsection{Input preprocessing} \label{sec:input_preprocessing} \input{input_preprocessing} \subsection{Entangled plaquette states} \label{sec:entangled_plaquette_states} \input{entangled_plaquette_states} \subsection{Description of the whole model} \label{sec:description_of_the_whole_model} \input{description_of_the_whole_model} \subsection{Optimization} \input{optimization} \section{Experiments} \label{sec:experiments} \input{experiments} \section{Conclusion} \input{conclusion} \section*{Acknowledgements} The work of Anh-Huy Phan was supported by the Ministry of Education and Science of the Russian Federation under Grant 14.756.31.0001. \bibliographystyle{plainnat} \subsection{MNIST} We tested DCTN with one EPS, \(\nu=0.5\) in \cref{eq:phi_definition}, \(K_1=4, Q_1=4\), \(\text{lr} = 3 \cdot 10^{-3}\), \(\lambda = 0\) in \cref{eq:opt_problem_whole_tn_l2_reg}, batch size 128 on MNIST dataset with 50000/10000/10000 training/validation/test split. We got 98.75\% test accuracy. MNIST is considered relatively easy and doesn't represent modern computer vision tasks \citep{fashionmnist_readme}. \subsection{FashionMNIST} FashionMNIST \citep{xiao2017fashion} is a dataset fully compatible with MNIST: it contains 70000 grayscale \(28 \times 28\) images. Each image belongs to one of 10 classes of clothes. We split 70000 images into 50000/10000/10000 training/validation/test split and experimented with models with one, two, and three EPSes. The more EPSes we used, the more overfitting DCTN experienced and the worse validation accuracy got, so we didn't experiment with more than three EPSes. For one, two, and three EPSes, we chose hyperparameters by a combination of gridsearch and manual choosing and presented the best result (chosen by validation accuracy before being evaluated on the test dataset) in \Cref{table:fashionmnist_experiments}. In \Cref{sec:how_hyperparameters_affect_optimization_and_generalization}, we describe more experiments and discuss how various hyperparameters affect optimization and generalization of DCTN. \begin{table}[h] \caption{Comparison of our best models (top 3 rows) with 1, 2, and 3 EPSes, respectively, with the best (by a combination of accuracy and parameter count) existing models on FashionMNIST dataset. DCTN with one EPS wins against existing models with similar parameter count. Adding more EPSes makes test accuracy worse due to overfitting. All 3 of our models eventually reach nearly 100\% accuracy if not stopped early. We trained all DCTNs with batch size 128.} \label{table:fashionmnist_experiments} \resizebox{\textwidth}{!}{% \begin{tabular}{p{13cm}lr} Model & Accuracy & Parameter count \\ \hline One EPS \(K_1{=}4\), \(Q_1{=}4\), \(\nu{=}0.5\), \(E_1 {\sim} \mathcal{N}(\mu{=}0, \sigma{=}0.25)\), \(A,b {\sim} U[-(H_1 W_1 Q_1)^{-0.5}, -(H_1 W_1 Q_1)^{0.5}]\), \(\text{lr}{=}3\cdot10^{-3}\), \(\lambda{=}0\), \cref{eq:opt_problem_whole_tn_l2_reg} & 89.38\% & \(2.9 \cdot 10^5\) \\ \hline Two EPSes, \(K_1{=}4, Q_1{=}4, K_2{=}3, Q_2{=}6\), \(\nu {\approx} 1.46\), EPSes initialized from \(\mathcal{N}(\mu{=}0, \sigma{=}Q_\text{in}^{-0.5 K^2})\), \(A {\sim} \mathcal{N}(\mu{=}0, \sigma{=}0.25(H_2 W_2 Q_2)^{-0.5})\), \(b {\sim} U[-(H_2 W_2 Q_2)^{-0.5}, (H_2 W_2 Q_2)^{-0.5}]\), \(\text{lr}{=}1.11\cdot10^{-4}\), \(\lambda{=}10^{-2}\), \cref{eq:opt_problem_epswise_l2_reg} & 87.65\% & \(1.8 \cdot 10^6\) \\ \hline Three EPSes, \(K_1{=}4, Q_1{=}4, K_2{=}3, Q_2{=}12, K_2{=}2, Q_2{=}24\), \(\nu {\approx} 1.46\), EUSIR initialization of EPSes (see \Cref{sec:initialization_and_scaling_of_input}), \(A {\sim} \mathcal{N}(\mu{=}0, \sigma{=}0.25 (H_2 W_2 Q_2)^{-0.5})\), \(b {\sim} U[-(H_3 W_3 Q_3)^{-0.5}, (H_3 W_3 Q_3)^{-0.5}]\), \(\text{lr}{=}10^{-7}\), \(\lambda {=} 10^{-1}\), \cref{eq:opt_problem_whole_tn_l2_reg} & 75.94\% & \(4\cdot10^6\) \\ \hline GoogleNet + Linear SVC & 93.7\% & \(6.8\cdot 10^6\) \\ \hline VGG16 & 93.5\% & \(2.6 \cdot 10^7\) \\ \hline CNN: 5x5 conv -\textgreater 5x5 conv -\textgreater linear -\textgreater linear & 91.6\% & \(3.3 \cdot 10^6\) \\ \hline AlexNet + Linear SVC & 89.9\% & \(6.2 \cdot 10^7\) \\ \hline Matrix tensor train in snake pattern (Glasser 2019) & 89.2\% & ? \\ \hline Multilayer perceptron & 88.33\% & \(2.3 \cdot 10^5\) \end{tabular}} \end{table} \subsection{CIFAR10} CIFAR10~\citep{cifar10} is a colored dataset of 32 by 32 images in 10 classes. We used 45000/5000/10000 train/validation/test split. We evaluated DCTN on the colored version using YCbCr color scheme and on grayscale version which mimics MNIST and FashionMNIST. The results are in \Cref{table:cifar10_experiments}. DCTN overfits and performs poorly -- barely better than a linear classifier. Our hypotheses for why DCTN performs poorly on CIFAR10 in contrast to MNIST and FashionMNIST are: (a)~CIFAR10 images have much less zero values; (b)~classifying CIFAR10 is a much more difficult problem; (c)~making CIFAR10 grayscale loses too much useful information, while non-grayscale version has too many features, which leads to overfitting. In the future work, we are going to check these hypotheses with intensive numerical experiments. \begin{table}[h] \caption{DCTN results on CIFAR10. For each number of color channels, for each number of EPSes, we chose the kernel sizes \(K_n\), the quantum dimension sizes \(Q_n\), and the learning rate using grid search (excluding models the training of which didn't fit in 8 Gb of videocard's RAM) and showed the best model in the table. All of these models can reach almost 100\% training accuracy if not stopped early. Two bottom rows show the accuracy of a linear classifier and of one of the state of the art CNNs for comparison.} \label{table:cifar10_experiments} \centering \begin{tabular}{ccc} Channels & Model & Accuracy\\ \hline Grayscale & One EPS, \(K_1{=}4, Q_1{=}4\) & 49.5\%\\ \hline Grayscale & Two EPSes, \(K_1{=}4, Q_1{=}4, K_2{=}3, Q_2{=}6\) & 54.8\%\\ \hline YCbCr & One EPS, \(K_1{=}2, Q_1{=}24\) & 51\%\\ \hline YCbCr & Two EPSes, \(K_1{=}2, Q_1{=}23, K_2{=}2, Q_2{=}24\) & 38.6\%\\ \hline RGB & Linear classifier & 41.73\%\\ \hline RGB & EfficientNet-B7~\citep{efficientnet} & 98.9\%\\ \end{tabular} \end{table} \subsection{Properties of successful neural networks} \label{sec:properties} Nowadays, neural networks (\emph{NNs}) achieve outstanding results in many machine learning tasks~\citep{paperswithcode_sota}, including computer vision, language modeling, game playing (e.g. Checkers, Go), automated theorem proving~\citep{gpt_f}. There are three properties many (but not all) NNs enjoy, which are thought to be responsible for their success. For example, \citep{cohen2016expressive} discusses the importance of these properties for deep CNNs. \begin{itemize} \item \emph{Parameter sharing}, aka applying the same transformation multiple times in parallel or sequentially. A layer of a convolutional neural network (\emph{CNN}) applies the same function, defined by a convolution kernel, to all sliding windows of an input. A recurrent neural network (RNN) applies the same function to the input token and the hidden state at each time step. A self-attention layer in a transformer applies the same query-producing, the same key-producing, and the same value-producing function to each token.~\citep{illustrated_transformer} \item \emph{Locality}. Interactions between nearby parts of an input are modeled more accurately, while interactions between far away parts are modeled less accurately or not modeled at all. This property makes sense only for some types of input. For images, this is similar to receptive fields in a human's visual cortex. For natural language, nearby tokens are usually more related than tokens far away from each other. CNNs and RNNs enjoy this property. \item \emph{Depth}. Most successful NNs, including CNNs and transformers, are deep, which allows them to learn complicated transformations. \end{itemize} \subsection{The same properties in tensor networks} Tensor networks (\emph{TNs}) are linear algebraic representations of quantum many-body states based on their entanglement structure. They've found applications in signal processing. People are exploring their applications to machine learning, e.g. tensor regression -- a class of machine learning models based on contracting (connecting the edges) an input tensor with a parametrized TN. Since NNs with the three properties mentioned in \Cref{sec:properties} are so successful, it would make sense to try to devise a tensor regression model with the same properties. That is what we do in our paper. As far as we know, some existing tensor networks have one or two out of the three properties, but none have all three. \begin{itemize} \item MERA (see Ch. 7 of \citep{bridgeman2017handwaving_and_interpretive_dance}) is a tree-like tensor network used in quantum many-body physics. It's deep and has locality. \item Deep Boltzmann machine can be viewed as a tensor network. (See Sec. 4.2 of \citep{cichocki_part_2} or \citep{glasser2018probabilistic} for discussion of how restricted Boltzmann machine is actually a tensor network. It's not difficult to see a DBM is a tensor network as well). For supervised learning, it can be viewed as tensor regression with depth, but without locality or weight sharing. \item \citep{glasser2018probabilistic} introduced Entangled plaquette states (\emph{EPS}) with weight sharing for tensor regression. They combined one EPS with a linear classifier or a matrix tensor train. Such a model has locality and parameter sharing but isn't deep. \item \citep{cohen2016expressive} introduced a tensor regression model called Deep convolutional arithmetic circuit. However, they used it only theoretically to analyze the expressivity of deep CNNs and compare it with the expressivity of tensor regression with tensor in CP format (canonical polyadic / CANDECOMP PARAFAC). Their main result is a theorem about the typical canonical rank of a tensor network used in Deep convolutional arithmetic circuit. The tensor network is very similar to the model we propose, with a few small modifications. We conjecture that the proof of their result about the typical canonical rank being exponentially large can be modified to apply to our tensor network as well. \item \citep{miller_2020_umps_psm} did language modeling by contracting an input sequence with a matrix tensor train with all cores equal to each other. It has locality and parameter sharing. \item \citep{liu2019ml_by_unitary_tn_of_hierarchical_tree_structure} used a tree-like tensor regression model with all cores being unitary. Their model has locality and depth, but no weight sharing. \item \citep{stoudenmire1605supervised} and \citep{novikov2016exponential} performed tensor regression on MNIST images and tabular datasets, respectively. They encoded input data as rank-one tensors like we do in \Cref{sec:input_preprocessing} and contracted it with a matrix tensor train to get predictions. Such a model has locality if you order the matrix tensor train cores in the right way. \end{itemize} \subsection{Contributions} The main contributions of our article are: \begin{itemize} \item We devise a novel tensor regression model called Deep convolutional tensor network (\emph{DCTN}). It has all three properties listed in \Cref{sec:properties}. It is based on the (functional) composition of TNs called Entangled plaquette state (\emph{EPS}). DCTN is similar to a deep CNN. We apply it to image classification, because that's the most straightforward application of deep CNNs. (\Cref{sec:description_of_the_whole_model}) \item We show how EPS can be implemented as a backpropagatable function/layer which can be used in neural networks or other backpropagation based models (\Cref{sec:entangled_plaquette_states}). \item Using common techniques for training deep neural networks, we train and evaluate DCTN on MNIST, FashionMNIST, and CIFAR10 datasets. A shallow model based on one EPS works well on MNIST and FashionMNIST and has a small parameter count. Unfortunately, increasing depth of DCTN by adding more EPSes hurts its accuracy by increasing overfitting. Also, our model works very badly on CIFAR10 regardless of depth. We discuss hypotheses why this is the case. (\Cref{sec:experiments}). \item We show how various hyperparameters affect the model's optimization and generalization (\Cref{sec:how_hyperparameters_affect_optimization_and_generalization}). \end{itemize}
{'timestamp': '2020-11-17T02:15:07', 'yymm': '2005', 'arxiv_id': '2005.14506', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14506'}
arxiv
\section{Introduction} Blockchain technology is maturing at a fast pace. The development of real-world applications shows real interest from both industry and academia \cite{zohar2015,UlHassan2019}. For instance, applications have been developed in the areas of public administration \cite{Belchior2019, Belchior2019_Audits}, access control \cite{rouhani2019,ssibac}, and others \cite{casino2019}. Additionally, blockchain is progressing towards the performance of centralized systems: for example, the Hyperledger Fabric blockchain is predicted to achieve 50,000 \emph{transactions per second} \cite{Gorenflo2019,Gorenflo2020}. Figure \ref{fig:stats} depicts the number of search results per year for ``blockchain interoperability'' that Google Scholar returned. In 2015, only two documents were related to blockchain interoperability. In 2016, 2017, 2018, 2019, and 2020, the results were 8, 15, 64, 130, and 207, respectively, showing a steep increase regarding interest in this research area. \begin{wrapfigure}{r}{0.4\textwidth} \centering \includegraphics[width=\linewidth]{figures/gs_interest.pdf} \caption{Research trends on blockchain interoperability} \label{fig:stats} \end{wrapfigure} Serving multiple use cases and stakeholders requires various blockchain features and capabilities \cite{wef2020}. The need for adaptability is a motivating factor for creating different blockchains, leading to a heterogeneous ecosystem \cite{Xu2017,hardjono2021,pilai2020}. Choosing new blockchains allows researchers and developers to implement new use case scenarios and keep up with recent endeavors. However, each blockchain has its security risks, as the technology is still maturing, the user base is limited (e.g., in comparison to the web or databases), and there are uncovered bugs, and security flaws \cite{sok_attacks}. Therefore, developers and researchers have to choose between novelty and stability, leading to a vast diversity of choices \cite{Anceaume2018}. This diversity leads to \emph{fragmentation}: there are many \emph{immature} blockchain solutions (e.g., without extensive testing). Until recently, blockchains did not consider the need for interoperability, as each one focused on resolving specific challenges, leading to \emph{data and value silos} \cite{jin2018, Abebe2019,tasca2017}. Moreover, what if the blockchain in which a particular service is running becomes obsolete, vulnerable, or is shutdown? If the user requirements or circumstances change over time, a different blockchain might be more appropriate for a specific use case \cite{agileLikoebe}. What if the service to serve is so crucial that it requires seamless dependability? Furthermore, if we want to reproduce our use case to another blockchain, how can we increase \emph{portability}? In 1996, Wegner stated that ``interoperability is the ability of two or more software components to cooperate despite differences in language, interface, and execution platform'' \cite{wegner96}. In that context, Wegner established a bridge between the concept of interoperability and existing standards. As authors were influenced by the standards existing at that time, authors nowadays are influenced by the Internet architecture and concepts, in what concerns blockchain interoperability \cite{Hardjono2019,vo2018}. Thus, reflecting on the Internet's architecture seems like a good starting point to understand how blockchains can interoperate. Thus, it is important to solve the \emph{blockchain interoperability} challenge, i.e., to provide interoperability between blockchains in order to explore synergies between different solutions, scale the existing ones, and create new use cases (see Section \ref{subsec:bid}). For example, a user should be able to transfer their assets from a blockchain to another or build \emph{cross-blockchain decentralized applications}. While information systems evolve, so do the meaning and scope of interoperability. According to the National Interoperability Framework Observatory (NIFO), endorsed by the European Commission, there are several interoperability layers \cite{NIFO_inter}: \emph{technical interoperability}, \emph{semantic interoperability}, \emph{organizational interoperability}, \emph{legal interoperability}, \emph{integrated public service governance}, and \emph{interoperability governance}. For instance, technical interoperability regards the technical mechanisms that enable integration among blockchains, while semantic interoperability concerns whether the application-specific semantics can be conserved across blockchains. Despite interoperability having an extensive scope, we mainly focus on \emph{technical interoperability}, and \emph{semantic interoperability} as most blockchain interoperability work is concentrated. We leave the study of other interoperability layers for future work. Interoperability does not only conflate flexibility and application portability. It also has the potential to solve some of the biggest blockchain research challenges. In particular, interoperability promotes blockchain \emph{scalability}, as it provides a way to offload transactions to other blockchains, e.g., via sharding \cite{scotm,bcsharding}, it can promote privacy (by allowing the end-user to use different blockchain for data objects with different privacy requirements), and creates new business opportunities. Given the complexity of this research area, we attempt to answer three research questions: \textbf{RQ1}: What is the current landscape concerning blockchain interoperability, both in industry and academia? \textbf{RQ2}: Are technological requirements for blockchain interoperability currently satisfied? \textbf{RQ3}: Are there real use cases requiring blockchain interoperability? \subsection{Contributions} As a systematization of knowledge on blockchain interoperability, this paper yields four-fold contributions: \begin{itemize} \item Introduce the blockchain interoperability research area, presenting the necessary background and highlighting definitions tailored both for industry and academia. We define blockchain interoperability and discuss different blockchain interoperability architectures and standards. \item Propose the Blockchain Interoperability Framework (BIF), a framework defining criteria to assess blockchain interoperability solutions. \item Present a \emph{systematic literature review}, where we identify and discuss blockchain interoperability solutions, accordingly to BIF, in three categories: \emph{Public Connectors}, \emph{Blockchain of Blockchains}, and \emph{Hybrid Connectors}. In particular, our analysis is based on several sources (e.g., peer-reviewed papers, whitepapers, blog posts, technical reports), enabling an in-depth understanding of each solution's current state and its \emph{roadmap}, i.e., its creator's plans. To achieve this, \emph{we systematically contacted the authors of grey literature papers and industrial solutions}: this is our innovative attempt to provide the reader with high-quality information in this rapidly emerging research area. This method allows us to obtain up-to-date, reliable information that often is cumbersome to obtain. \item We identify and propose use cases that benefit from a multiple blockchain approach, pinpoint challenges and obstacles to the development of blockchain interoperability solutions and standards, and propose future research directions, paving the way for systematic research in this area. \end{itemize} \subsection{Organization} Section \ref{sec:back} provides background on blockchain consensus algorithms, previous results on blockchain interoperability, and blockchain interoperability definitions and architecture. Next, Section \ref{sec:related_literature_reviews} presents and discusses related literature reviews, while Section \ref{sec:bif} introduces the Blockchain Interoperability Framework. Next, a systematic review and analysis of blockchain interoperability categories is conducted, distributed across three categories, in Section \ref{sec:solutions}: Public Connectors (Section \ref{sec_crypto}), Blockchain of Blockchains (Section \ref{sec:be}), and Hybrid Connectors (Section \ref{subsec:blockchain_connectors}). For each category, we provide a detailed analysis and discussion. To provide a holistic view of the blockchain interoperability landscape, we promote a general discussion in Section \ref{sec:discussion_sec}. This discussion compares solutions across categories (Section \ref{sec:discussion}), presents standardization efforts (Section \ref{sec:technologies_standards}), informs readers regarding use case scenarios with multiple blockchains (Section \ref{sec:use_cases}), answers to the research questions (Section \ref{sec:res_q_a}), and indicates challenges related to interoperability (Section \ref{sec:issues}). We present research directions (Section \ref{sec:research_directions}), and, finally, we conclude the paper (Section \ref{sec:concl}). Six appendices complement this survey. Appendix \ref{a:method} presents the methodology employed. Appendix \ref{a:architecture} presents an architecture for blockchain interoperability, reviewing the various efforts on that topic. Appendix \ref{a:crypto}, \ref{a:be} and \ref{a:connectors} presents a description of the surveyed public connectors, blockchain of blockchains, and hybrid connector approaches, respectively. Finally, Appendix \ref{a:use_cases} complements the use case section, by presenting more cross-blockchain use cases. \section{Background} \label{sec:back} In this section, we provide the necessary background to the understanding of this survey. \subsection{A Primer on Blockchain Technology} \label{sec:primer} The term \emph{blockchain} has at least two different meanings: a type of system and a type of data structure. In this paper, we use the term blockchain to denominate a class of distributed systems. A blockchain maintains a shared state, specifically a replicated data structure that we denominate \emph{distributed ledger}. This ledger is maintained by a set of machines with computational and storage resources, called nodes (or peers or participants). Nodes are not trusted individually to maintain the distributed ledger; they are trusted as a group due to their number and diversity \cite{vukolic_bcpitw}. A blockchain can also be considered a \emph{deterministic state machine} that provides a certain service, given existing incentives that the network can reward. The first blockchain was part of the Bitcoin system and provided as service transactions of a cryptocurrency, a digital currency, also designated Bitcoin \cite{nakamoto2008}. The service provided by Bitcoin is the execution of transactions of bitcoins. Most blockchains are programmable, i.e., their state machine is extensible with user programs. These programs are often designated \emph{smart contracts} \cite{szabo1997paper,ethereum-white-paper} and their execution is caused by calls also designated \emph{transactions}. Smart contracts are executed in a virtual machine, e.g., in the Ethereum Virtual Machine (EVM) in Ethereum and other blockchains that adopted the EVM for compatibility (that we designate \emph{EVM-based blockchains}). Smart contracts are often used to implement \emph{tokens}, i.e., blockchain-based abstractions that can be owned and represent currency, resources, assets, access, equity, identity, collectibles, etc.~\cite{antonopoulos2018mastering}. There are several standard token formats, e.g., ERC-20 and ERC-721. These tokens are fungible and non-fungible assets, respectively. A fungible asset is interchangeable with another asset of the same type. Conversely, a non-fungible asset is an asset that is unique and has specific properties. In many blockchains, transactions are aggregated in \emph{blocks}, linked by the previous block's cryptographic hash. Hence those data structures are also called blockchains - often viewed as deterministic state machines. Blockchain systems ought to be resilient to faults (e.g., \emph{crash fault-tolerant} or \emph{Byzantine fault-tolerant}), as there may be crashes or malicious nodes on the network \cite{correia2019byzantine}. They run a consensus algorithm to create agreement on a global ledger state in the presence of Byzantine faults. Consensus algorithms are important because they define the behavior of blockchain nodes and their interaction \cite{correia2019byzantine,zheng2017}, and the security assumptions of each blockchain. They, therefore, affect how blockchain peers communicate and operate with each other: in Bitcoin's Proof-of-Work (PoW), peers have to compute a cryptographic challenge to validate transactions, competing with each other. Another blockchain, Tendermint, uses a Byzantine fault-tolerant state machine replication (BFT) algorithm \cite{Kwon2016}, supporting up to a third less one of faulty participants. In Hyperledger Fabric, a widely-used private blockchain platform, a consensus algorithm allows higher transaction throughput than PoW by allowing a subset of nodes to execute and endorse transactions (called endorser peers) and by typically using a weaker consensus (only crash fault-tolerant). The variety of blockchain infrastructures makes it challenging to categorize blockchains, and their interoperability solutions, as there are no \emph{de facto} blockchain interoperability or blockchain architecture standards. Apart from differences in the consensus, blockchains can be deemed \emph{public} (also called permissionless) or \emph{private} (also called permissioned). Permissionless blockchains do not require authentication for participants to access the ledger. \emph{Bitcoin} \cite{nakamoto2008} and \emph{Ethereum} \cite{ethereum-white-paper,ethereum_yellow_paper} are examples of such blockchains. Permissioned blockchains are blockchains in which users are authenticated and can be held accountable according to a governance model suitable for enterprise and governmental needs. Hyperledger Fabric \cite{fabric}, Corda \cite{r3}, Quorum \cite{quorum}, Tendermint \cite{Kwon2016}, and Multichain \cite{multichain} are examples of permissioned blockchains. \begin{wrapfigure}{r}{0.6\textwidth} \centering \includegraphics[scale=0.32]{figures/Fig1.pdf} \caption{Representation of two blockchains, Hyperledger Fabric \cite{fabric}, and Bitcoin \cite{nakamoto2008}.} \label{fig:blockchains} \end{wrapfigure} Figure \ref{fig:blockchains} depicts two blockchains: Hyperledger Fabric, a permissioned blockchain; and Bitcoin, a permissionless blockchain. The supporting layers (e.g., networking, storage, encryption) \cite{Kan2018} provide a basis for the consensus engine, which orders transactions and appends them to the chain of blocks. In Hyperledger Fabric, the consensus is modular, based on endorsement policies. In Fabric, a client (C) sends a transaction proposal to the peer nodes (P), and obtains a signed transaction, called an endorsement (steps 1 and 2). An orderer validates the endorsements and builds a block with valid transactions, appending it to the ledger (steps 3 and 4). In Bitcoin, the consensus is based on the notion of Proof-of-Work (PoW), a cryptographic puzzle that mining nodes need to solve in order to build a valid block. This corresponds roughly to Fabric's steps 1-3. After a node finds a solution to PoW, it then can propose a block of transactions to be appended to the ledger (step 4). Blockchain trust is based on the incentive models that guide the behavior of the nodes. For instance, in Bitcoin, nodes have the incentive to produce blocks of transactions and support the network because they are rewarded Bitcoins. Conversely, nodes do not have the incentive to disrespect the protocol, as attacks are expensive and nodes can get punished \cite{Conti2018}. In Hyperledger Fabric, where nodes are identified, they have the business incentive to follow the protocol because parties cooperate towards a common goal, and misbehavior can be punished according to the law or applicable governance model. Decentralization, different goals, and incentives support the trust on the blockchain -- parties can share the ledger without relying on a trusted, centralized party. The ability to distribute trust on a global state fostered the appearance of \emph{decentralized applications} (\emph{dApps}) \cite{antonopoulos2018mastering}. A dApp is a computer program running on a decentralized peer-to-peer network. For example, Steemit\footnote{https://steemit.com/} is a social blogging dApp that rewards content-creators with cryptocurrency. Thus, dApps are based on smart contracts running on a blockchain, but they also have other components that should equally be decentralized. \subsection{Cross-Blockchain Communication} \label{sec:ccc} Cross-blockchain communication involves two blockchains: a \emph{source blockchain}, and a \emph{target blockchain}. The source blockchain is the blockchain in which the transaction is initiated to be executed on a target blockchain. While general-purpose interoperability comes down to a blockchain exposing its internal state to other, cross-chain asset transfers rely on an atomic three-phase procedure: 1) locking (or extinguishing) of an asset on a source blockchain; 2) blockchain transfer commitment, and 3) creation of a representation of the asset on a target blockchain \cite{odap_draft_01,hermes-middleware-2021,scotm}. This procedure, later explained in detail, relies on a \emph{cross-chain communication protocol} (CCCP). A CCCP defines the process by which a pair of blockchains interact to synchronize cross-chain transactions correctly. Hence, a CCCP allows \emph{homogeneous} blockchains to communicate. For instance, sidechains typically use a CCCP (e.g., Zendoo allows communication between Bitcoin-like blockchains systems \cite{zendo}). Conversely, a \emph{cross-blockchain communication protocol} (CBCP) defines the process by which a pair of blockchains interact to synchronize cross-blockchain transactions correctly. CBCPs allow \emph{heterogeneous} blockchains to communicate (e.g., the Interledger Protocol allows any blockchains that implement the protocol to exchange ``money packets'' \cite{ILPv4}). The differentiation between CCCPs and CBCPs is important because CCCPs typically can leverage the interoperating blockchains' constructs and functionality (e.g., utilize smart contracts to implement a relay \cite{peacerelay}), whereas CBCPs normally require blockchains to be adapted. However, CBCPs may leverage specific functionalities of both blockchains \cite{btcrelay}. Cross-blockchain, or cross-chain communication, is a requirement for blockchain interoperability. This section provides a few theoretical results regarding cross-blockchain communication, and thus also blockchain interoperability. Zamyatin et al.~\cite{sok_cdl} prove that ``there exists no asynchronous CCC [cross-chain communication] protocol tolerant against misbehaving nodes''. The authors use a reduction to the fair exchange problem \cite{fair_exchange} to prove that correct cross-chain communication is as hard as the fair exchange problem. As a consequence of the presented theorem, the authors state that ``there exists no CCC protocol tolerant against misbehaving nodes without a trusted third party''. A trusted third party can be centralized or decentralized. Centralized trusted parties are, for example, trusted validators \cite{hyperledger_cactus}. A decentralized trusted party can be another blockchain, in which their participants agree on the global ledger state via a consensus algorithm. However, the trusted party has to ensure that most participants are honest, guaranteeing the correctness of the process is guaranteed. Cross-chain protocols, therefore ``use the consensus of the distributed ledgers as an abstraction for a trusted third party.'' \cite{sok_cdl}. Borkowski et al.~\cite{tast_paper7} derive the ``lemma of rooted blockchains'' that states that a source blockchain cannot verify the existence of data on a target blockchain with practical effort. In particular, the source blockchain would need to be able to mimic consensus from the target blockchain, and it would have to store a (potentially large) subset of the target blockchain's block history. On a recent endeavor, Lafourcade and Lombard-Platet \cite{pascal2020} formalize the blockchain interoperability problem, arguing that fully decentralized blockchain interoperability is not possible. More specifically, there is no protocol assuming a full-client that can realize its interoperability functions, such as asset transfer, without a third party's aid. However, a blockchain with two ledgers offers the possibility of interoperability (there is, in fact, the possibility of moving assets from one ledger to the other). This study applies mainly to public blockchains. The results above are relevant because they lead to an important consideration: \emph{cross-blockchain transactions are not feasible in practice without the participation of a trusted third party}. In other words, although trust assumptions vary greatly from permissionless to permissioned networks, cross-blockchain transactions, as well as cross-chain transactions, require a trusted third party to assure the correctness of the underlying protocol. Most solutions presented throughout this paper present at least one decentralized trust anchor. \subsection{Blockchain Interoperability Definitions} \label{subsec:bid} In this section, we define additional technical terms for an understanding of this study. Vernadat defines interoperability among enterprise systems as \cite{Vernadat2006}: ``a measure of the ability to perform interoperation between [...] entities (software, processes, systems, business units...). The challenge relies on facilitating communication, cooperation, and coordination among these processes and units''. Abebe et al.~propose a general communication protocol as an alternative approach to the ``point-to-point'' blockchain interoperability approach \cite{Abebe2019}. Interoperability is defined as ``the semantic dependence between distinct ledgers to transfer or exchange data or value, with assurances of validity''. Pillai and Biswas refer that ``cross-communication is not intended to make direct state changes to another blockchain system. Instead, cross-communication should trigger some set of functionalities on the other system that is expected to operate within its own network'' \cite{Pillai2019}. A technical report from the National Institute of Standards and Technology (NIST) defines blockchain interoperability as ``a composition of distinguishable blockchain systems, each representing a unique distributed data ledger, where atomic transaction execution may span multiple heterogeneous blockchain systems, and where data recorded in one blockchain are reachable, verifiable, and \emph{referable} by another possibly foreign transaction in a semantically compatible manner'' \cite{NISTIR}. Hardjono et al.~define blockchain survivability as ``the completion (confirmation) of an application-level transaction [composed of subtransactions] independent of blockchain systems involved in achieving the completion of the transaction.''\cite{Hardjono2019} The concept of transactions and subtransactions relates to ``\emph{best effort delivery}'', that applications must comply to, by ensuring that transactions and their \emph{subtransactions} are completed (i.e., committed) within a certain time frame. Regarding types of blockchain interoperability, Besançon et al. highlight three \cite{tbig}: interoperability between different blockchains, interoperability between dApps using the same blockchain, and interoperability blockchain and other technologies (such as integration with enterprise systems). While different definitions tackle different dimensions of interoperability, there is room for improvement. We define several terms that encompass the whole scope of technical interoperability to later provide a holistic definition of technical interoperability (see Figure \ref{fig:concept_map}). To recall the definition presented in Section \ref{sec:ccc}, a {source blockchain} is a blockchain that issues transactions against a {target blockchain}. A \emph{source node} is a node from the source blockchain, and a target node belongs to the target blockchain. When several participants elect a source node and a target node, we achieve decentralization in the context of interoperability \cite{jin2018}. A \ac{CC-Tx}, where ``CC'' stands for \emph{cross-chain}, and ``Tx'' for transaction, is a transaction between different chains, which belong to the same blockchain system (homogeneous blockchains), for example, between EVM-based blockchains. We use the \ac{CC-Tx}, \emph{inter-chain transaction}, and \emph{inter-blockchain transaction} terms interchangeably. A \ac{CB-Tx} is a transaction between different blockchains (heterogeneous blockchains), for example, between Hyperledger Fabric and Bitcoin. Note that the terms \ac{CC-Tx} and \ac{CB-Tx} are used as synonyms in the industry, as currently, most solutions connect homogeneous blockchains. A \ac{CC-dApp} is a dApp that leverages cross-blockchain transactions to implement its business logic. We use the terms \ac{CC-dApp} and \emph{cross-blockchain decentralized application} (CB-dApp) interchangeably. Other terms with the same meaning in the literature are inter-chain decentralized application and inter-blockchain decentralized application. A \ac{IoB} is a system ``where homogeneous and heterogeneous decentralized networks communicate to facilitate cross-chain transactions of value'' \cite{vo2018}. We use this definition of IoB throughout this paper. The term \ac{BoB} is not used consistently \cite{Verdian2018, hyperservice}. Verdian et al.~use it to describe the structure that aggregates blocks from different blockchains into ``meta blocks'', organized through a consensus mechanism using \emph{posets} (partially ordered sets) and total order theory \cite{Verdian2018}, thus producing a blockchain of blockchains. A poset consists of a set of elements and their binary relationships that are ordered according to a specific set of rules \cite{lattice}. Influenced by those authors, we define a \ac{BoB} \emph{as a system in which a consensus protocol organizes blocks that contain a set of transactions belonging to CC-dApps, spread across multiple blockchains. Such a system should provide accountability for the parties issuing transactions on the various blockchains and providing a holistic, updated view of each underlying blockchain}. Note that BoB solutions belong to the category with the same name. Therefore, the notion of \ac{IoB} directly refers to the connection relationships among blockchains, whereas the term \ac{BoB} refers to an architecture made possible by IoB. BoB approaches are concerned with the validation and management of cross-blockchain transactions. \begin{wrapfigure}{r}{0.5\textwidth} \centering \includegraphics[scale=0.22]{figures/concept_map_4.pdf} \caption{Concept map, illustrating the relationship between different concepts related to blockchain interoperability} \label{fig:concept_map} \end{wrapfigure} Figure \ref{fig:concept_map} shows the relationship between the different concepts concerning blockchain interoperability. A \ac{CC-dApp} realizes the blockchain of blockchains approach. This approach can provide the semantic level interoperability (i.e., concerned at transmitting the meaning of the data, which corresponds to the value level interoperability) required by organizations, mappable by the applicational layer. However, it relies on the existence of an IoB -- a network of blockchains. For an IoB to exist, technical interoperability (or mechanical interoperability) is required. In the context of a CC-dApp, cross-chain transactions are ordered by a \emph{cross-chain dApp protocol}. Such protocols should assure transaction atomicity and resolve possible conflicts in transactions spawning across homogeneous and heterogeneous blockchains. From the several definitions we encountered during our research, we envision \emph{blockchain interoperability} as: \emph{the ability of a source blockchain to change the state of a target blockchain (or vice-versa), enabled by cross-chain or cross-blockchain transactions, spanning across a composition of homogeneous and heterogeneous blockchain systems, the IoB.} IoB transactions are delivered via a cross-blockchain communication protocol, thereby granting technical interoperability, enabling \ac{CC-dApp}s. \ac{CC-dApp}s provide semantic interoperability via the BoB. The BoB approach is realized by a cross-blockchain dApp protocol, which provides consensus over a set of cross-chain transactions, thus enabling cross-chain dApps. \section{Related Literature Reviews} \label{sec:related_literature_reviews} Due to the novelty and large-breadth of this research area, few updated surveys cover aspects of blockchain interoperability. We compare existing surveys based on the \emph{criteria} and \emph{sub-criteria} shown in Table \ref{tab:related_survey_criteria}. For example, in the first row, the criteria ``public connector'' evaluates if a study addresses its sub-criteria: work on sidechains, hash-lock time contracts, and notary schemes. On the second row, the criteria Blockchain of Blockchains evaluates if a study describes BoB solutions (1) and if it performs a detailed comparison, including consensus, security, validators, and performance. \begin{table}[] \centering \resizebox{\linewidth}{!}{% \begin{tabular}{@{}lllll@{}} \toprule \textbf{Criteria} & \textbf{Description} & \textbf{Sub-criteria 1} & \textbf{Sub-criteria 2} & \textbf{Sub-criteria 3} \\ \midrule \textbf{Public Connectors (PC)} & Addresses public connectors & Sidechains & Hash lock contracts & Notary Schemes \\ \midrule \textbf{Blockchain of Blockchains (BoB)} & Addresses BoBs & Describes solutions & Detailed comparison & N/A \\ \midrule \textbf{Hybrid Connectors (HC)} & Addresses Hybrid Connectors & Trusted Relays & Blockchain agnostic protocols & Blockchain migrators \\ \midrule \textbf{Architecture (AR)} & Addresses architectures enabling CCCPs & Proposes architecture & Presents related work & N/A \\ \midrule \textbf{Cross-chain Standards (ST)} & Addresses standards for interoperability & Present standards & Relate standards to solutions & N/A \\ \midrule \textbf{Cross-analysis (CC)} & Compares across categories & Compare categories & Compare sub-categories & N/A \\ \midrule \textbf{Use Cases (UC)} & Presents use cases using an IoB or BoB & Existing use cases & Predicted use cases & N/A \\ \midrule \textbf{Open Issues (OI)} & Challenges on interoperability & Research directions & Relate interoperability to other issues & N/A \\ \bottomrule \end{tabular}% } \caption{Survey comparison criteria, description, and sub-criteria. } \label{tab:related_survey_criteria} \end{table} Buterin presents a survey on public connector solutions, including notary schemes, sidechains, and hash-time locking techniques \cite{vitalik2016}. Similarly, other surveys focus on public connectors \cite{sok_cdl,tast_paper8,koens2019,singh2020}, with a focus on sidechains and hash lock time contracts. Vo et al. present work mostly on architecture for interoperability, presenting some BoB and HC solutions \cite{vo2018}, while Qasse et al. organize solutions across sidechains, blockchain routers, smart contracts, and industrial solutions \cite{Qasse2019}. Johnson et al. focus on Ethereum as the infrastructure enabling interoperability across several categories of solutions \cite{Johnson2019}. Siris et al.~\cite{inter_approaches}, Kannengieber et al. \cite{niclas2020}, and Bishnoi et al. \cite{Bishnoi2020} tackle a wider range of solutions. \begin{wraptable}{r}{0.7\textwidth} \centering \footnotesize \begin{tabular}{@{}lcccccccc@{}} \toprule & \multicolumn{3}{c}{\textbf{Solution category}} & \multicolumn{5}{c}{\textbf{Detailed Analysis}} \\ \midrule \multicolumn{1}{c}{} & & & \multicolumn{1}{c|}{} & & & & & \\ \multicolumn{1}{c}{\multirow{-2}{*}{\textbf{Reference}}} & \multirow{-2}{*}{PC} & \multirow{-2}{*}{BoB} & \multicolumn{1}{c|}{\multirow{-2}{*}{HC}} & \multirow{-2}{*}{AR} & \multirow{-2}{*}{ST} & \multirow{-2}{*}{CC} & \multirow{-2}{*}{UC} & \multirow{-2}{*}{OI} \\ \midrule \multicolumn{1}{l|}{Buterin \cite{vitalik2016}, 2016} & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \multicolumn{1}{c|}{\cellcolor[HTML]{BF504D}-} & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ \\ \midrule \multicolumn{1}{l|}{Vo et al.\cite{vo2018}, 2018} & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{F79545}$\pm$ & \multicolumn{1}{c|}{\cellcolor[HTML]{F79545}$\pm$} & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{D8E3BB}+ \\ \midrule \multicolumn{1}{l|}{Borkowski et al. \cite{tast_paper5}, 2018} & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \multicolumn{1}{c|}{\cellcolor[HTML]{BF504D}-} & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ \\ \midrule \multicolumn{1}{l|}{Quasse et al. \cite{Qasse2019}, 2019} & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{F79545}$\pm$ & \multicolumn{1}{c|}{\cellcolor[HTML]{F79545}$\pm$} & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{F79545}$\pm$ \\ \midrule \multicolumn{1}{l|}{Johnson et al. \cite{Johnson2019}, 2019} & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{F79545}$\pm$ & \multicolumn{1}{c|}{\cellcolor[HTML]{F79545}$\pm$} & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- \\ \midrule \multicolumn{1}{l|}{Zamyatin et al. \cite{sok_cdl}, 2019} & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \multicolumn{1}{c|}{\cellcolor[HTML]{BF504D}-} & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ \\ \midrule \multicolumn{1}{l|}{Siris et al. \cite{inter_approaches}, 2019} & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{F79545}$\pm$ & \multicolumn{1}{c|}{\cellcolor[HTML]{F79545}$\pm$} & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- \\ \midrule \multicolumn{1}{l|}{Koens et al. \cite{koens2019}, 2019} & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ \\ \midrule \multicolumn{1}{l|}{Singh et al. \cite{singh2020}, 2020} & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ \\ \midrule \multicolumn{1}{l|}{Kannengießer et al., \cite{niclas2020}, 2020} & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{F79545}$\pm$ & \multicolumn{1}{c|}{\cellcolor[HTML]{F79545}$\pm$} & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- \\ \midrule \multicolumn{1}{l|}{Bishnoi et al. \cite{Bishnoi2020}, 2020} & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- \\ \midrule \multicolumn{1}{l|}{\emph{this survey}} & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \multicolumn{1}{c|}{\cellcolor[HTML]{D8E3BB}+} & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ \\ \midrule & \multicolumn{1}{l}{} & \multicolumn{1}{l}{} & \multicolumn{1}{l}{} & \multicolumn{1}{l}{} & \multicolumn{1}{l}{} & \multicolumn{1}{l}{} & \multicolumn{1}{l}{} & \multicolumn{1}{l}{} \\ \bottomrule \end{tabular} \caption{Comparison of related literature reviews: PC (Public Connectors), Blockchain of Blockchains (BoB), HC (Hybrid Connectors), AR (architectures for blockchain interoperability), ST (standards), CC (cross-comparison), UC (use cases), OI (open-issues). Each criterion can be ``fulfilled'' (``+'' in green background), ``partially fulfilled'' (``$\pm$'' in orange background) or ``not fulfilled'' (``-`'' in red background), if it addresses all, between one and all, or none of its sub-criteria, respectively. } \label{tab:related_slr} \end{wraptable} We aim at providing a solid, throughout and comprehensive foundation on which researchers can rely upon as a starting point in this field, including a description of the related surveys, which illuminated our research. In contrast to most of the works mentioned above, this paper provides a holistic view of blockchain interoperability by focusing not only on public connectors but also on BoBs and hybrid connectors. By including updated grey literature and focusing on private blockchain interoperability, a comprehensive discussion on standards, use cases, and architecture for interoperability was possible. \section{Blockchain Interoperability Framework} \label{sec:bif} This section presents the Blockchain Interoperability Framework (BIF), a framework classifying solutions collected through our methodology. To drive criteria for assessing the categories (and specific solutions) of blockchain interoperability, we analyzed the solution space using the six ``W'' questions: Who, What, Where, When, Why, and How. The ``Why'' was determined irrelevant to our analysis because its purpose is constant -- connecting different chains (CC-Txs), different blockchains (CB-Txs), or even to arbitrary systems (e.g., enterprise legacy systems). This is instead addressed by the ``where'' question. \subsection{Deriving Evaluation Criteria} The ``what'' refers to the \emph{assets} exchanged. An interoperability solution can handle different data objects or assets. Hence it is important to know which data representations a solution supports \cite{wegner96}. Assets can be treated as data (arbitrary payloads), as fungible assets, or non-fungible assets \cite{barnes2020,pilai2020,hyperledger_cactus}. Arbitrary data is often represented via a key-value pair, being the preferred representation of some blockchains \cite{sawtooth,fabric,vukolic_bcpitw}. The key-value is also useful to represent the contents of account-based blockchains \cite{eth2_wiki,algorand,quorum}. Payment tokens are fungible tokens \cite{Pillai2019}. Utility tokens include tokens used to access a service or application, such as non-fungible tokens (e.g., ERC20 tokens). Finally, asset tokens represent real-world physical or digital instruments, such as blockchain-based promissory notes, regulated by the {Swiss Financial Market Supervisory Authority} \cite{draft-sardon-blockchain-gateways-usecases-00} (see more details in Section \ref{sec:use_cases}), or bonds \cite{barnes2020}. An asset has different maturity levels. In particular, an asset may be standardized, (e.g., ERC tokens\cite{erc20}, standardized schema for utility tokens, ERC1400, a security token \cite{erc1400s,erc1400}) and/or {regulated} \cite{oecd2021,finma,usexchcomm}. Regulated digital assets are backed by legal frameworks. We consider all asset tokens to be regulated. We envision utility tokens as standardized and asset tokens as standardized and regulated (i.e., asset tokens are emitted by legal entities) The ``who'' question refers to whom controls the CC-Tx process and thus accounts for trust establishment \cite{sidechains_pos,sok_cdl}). It can be the end-user (e.g., \cite{hyperledger_cactus,Frauenthaler2019}), a consortium (e.g., \cite{peggedsidechains, Schulte2019}), or a trusted third party (e.g., cloud services, centralized notary schemes). Some solutions allow different levels of control. The ``where'' refers to what are the source and target ledgers, as well as what is the support of conducting the CC process. Solutions can support public blockchains (P) or non-public blockchains (NP). We use NP to designate private blockchains, other decentralized ledger technology (DLT) systems, and centralized systems (e.g., VISA payment network). The supported systems of each solution matter since communication may happen unidirectionally or bi-directionally \cite{hyperledger_cactus}. Blockchain oracles apart, it often is not feasible to have a solution based on a blockchain system connected to a centralized system (e.g., providing insurance data). A smart contract may be the one conducting an asset transfer (on-chain channel, with on-chain CC-Tx validation) versus an off-chain settlement, e.g., techniques using commitment schemes \cite{abebe2020,zendo}, or via (semi-)centralized system (off-chain channel). Typically, on-chain channels offer more resiliency, but off-chain channels are more scalable. Combinations between off-chain and on-chain channels also exist (e.g., payment networks \cite{LN}). Offline channels depend on different proof generation mechanisms \cite{abebe2020, sidechains_pos, zendo}. The ``when'' refers to the set of processes (e.g., executing CC-Txs) that are defined at \emph{design-time} or \emph{run-time}. \emph{Design-time customization} decisions affect the punctual behavior of a CC-dApp concerning when it is executed. At design-time, a user defines the behavior of the solution \emph{apriori}. If a change is needed, a new instance of the solution needs to be deployed. Conversely, \emph{run-time customization} decisions are flexible, allowing the end-user to adjust the conditions defined by business logic as needed. Solutions in which business logic is changed at run-time are called \emph{flexible approaches}, allowing to adjust business logic and conditions that trigger the execution of a CB-Tx or CC-Tx by a CC-dApp. Most literature reviews focus on design-time approaches and public blockchains, leaving a vast range of recent solutions out of scope. In this survey, we also consider private-private and public-private blockchain interoperability, focusing on flexible approaches. The ``how'' regards the realization of cross-chain transactions: how are CC-Txs realized on the underlying DLTs? Often, these transactions can be performed using \emph{cross claims}, i.e., by locking/burning an asset on the source blockchain and unlocking/creating its representation on the target blockchain. Cross-claims require two nodes from different blockchains, where one performs one operation in a source blockchain in exchange for its counterparty performing other operations on a target blockchain - each party logs the operation in case a dispute is needed. Typically, cross-claims operate in semi-trusted environments (e.g., private blockchain, regulated blockchain), and can be operated via a (semi) trusted third party \cite{hyperledger_cactus,odap_draft_01,crp_draft_00}. Escrowed cross-claims are the standard mechanism for asset transfers, operating similarly to cross-claims, but in an untrusted environment, leveraging dispute-resolution mechanisms (e.g., via smart contracts requiring inclusion proofs \cite{abebe2020}) or by parties holding custody of assets and collateral, \cite{xclaim,dextt, plasma_vitalik}. Inclusion proofs include applying Merkle tree proofs to block header transfer via a coordinating blockchain, block header transfer, or direct signing \cite{robinson2020}. Collateralization is the process in which a party performing the transfer of assets provides a certain amount of their assets as a guarantee of following the protocol (e.g., not to steal assets from the end-user). If a party misbehaves (e.g., steals assets), the deposit is given to the victim party. Finally, a mediated CC-Tx includes (an offline) trusted party \cite{hyperledger_cactus}. In case of a dispute about an asset transfer between a public blockchain and a private blockchain (P-NP) or a public blockchain and an enterprise system (also P-NP), there needs to be a dispute-resolution mechanism. This is due to NP systems' private nature, although several mechanisms exist to prove internal state belonging to private blockchains. Hence, CC-Txs have a trade-off risk-performance: the less centralization there is on the CC-Tx settlement, the worst the performance, but the lesser the risk. The ``how'' also relates to the extent to which the implementation of the solution is tested. Solutions might be implemented, tested, and validated (application to a real-world scenario). Testing regards \emph{correctness guarantees}: \emph{behavioral correctness} or \emph{formal correctness}. Behavioral correctness is the ability to guarantee that CC-Txs are issued as intended, without unintended consequences (e.g., asset lock, asset theft). While in practice, behavioral correctness depends on formal correctness, we say a solution has behavioral correctness if it has a suite of test cases \cite{testing}. Formal correctness assures that an algorithm is correct with respect to a specification. Formal verification checks the correctness of algorithms against a specification using, for instance, formal methods. Smart contract verification tools allow developers to reduce the probability of creating bugs, thus incurring penalties, as smart contracts are generally difficult to update once deployed \cite{smartbugs}. Another point of providing trust to the user is the solution to have an open-source implementation, where the code can be peer-reviewed and corrected if needed. \subsection{Evaluation Criteria} \label{subsec:criteria_bif} Having discussed the survey's scope, we next define the set of criteria we use to characterize the interoperability solutions. Similarly to Section \ref{sec:related_literature_reviews}, each criterion can be ``fulfilled'' ``partially fulfilled'' or ``not fulfilled''. If a criterion is a yes/no question (e.g., does the solution support asset type ``data''?), we do not explicitly refer to the fulfillment conditions as they are evident. Next, we detail the criteria type (first-level), criteria sub-type (second level), and criteria from BIF: \begin{itemize}\small \item Asset: this category refers to properties of an asset involved in a CC-Tx. \begin{itemize} \item Type: what type of assets does the solution support? \begin{enumerate} \item Data: can the solution manipulate arbitrary data? \item Payment tokens: can the solution manipulate cryptocurrencies? This criterion is partially fulfilled if the asset is only used as collateral or to reward a service's operational maintenance. \item Utility tokens: can the solution manipulate utility tokens? This criterion is partially fulfilled if the asset is used only as collateral or to reward a service's operational maintenance. \item Asset tokens: can the solution manipulate utility tokens? \end{enumerate} \item Infrastructure: what are the systems involved? \begin{enumerate} \item P: This criterion is fully fulfilled if more than two public blockchains are supported. It is partially fulfilled if one or two public blockchains are supported. \item NP: This criterion is fully fulfilled if more than two non-public blockchains are supported. It is partially fulfilled if one or two non-public blockchains are supported. \end{enumerate} \end{itemize} \item Trust Establishment: this category refers to how a solution provides trust to the users. \begin{itemize} \item Decentralization: who operates the solution instance? \begin{enumerate} \item End-user \item Consortium \item Trusted (third) party \end{enumerate} If multiple criteria are selected, it indicates a solution supports more than one mode of operation. \item Channel: where are CC-Tx validated? \begin{enumerate} \item On-chain: This criteria is partially fulfilled if proofs are created on-chain but validation occurs off-chain. \item Off-chain: This criteria is partially fulfilled if proofs are created off-chain but validation occurs on-chain. \end{enumerate} \end{itemize} \item CC-Tx Realization: this category refers to how and where a CC-Tx is settled. \begin{itemize} \item Mechanism: how are CC-Txs agreed-upon multiple parties? \begin{enumerate} \item Cross-claim \item Escrowed cross-claim \item Mediated \end{enumerate} \end{itemize} \item Extra-functional: this category refers to the design of the solution itself. \begin{enumerate} \item Tests: the approach provides a set of test cases. \item Implementation: the approach provides an open-source implementation and is validated in the industry. This criterion is partially fulfilled if the implementation is closed-source. \item Validation: the approach is validated in an actual use case scenario. \item Run-time: the business logic of the solution can be changed dynamically, as needed. This criterion is considered not fulfilled if logic is settled when the solution is instantiated, i.e., changing logic requires a new instance. \end{enumerate} \end{itemize} \section{Overview of Blockchain Interoperability Approaches} \label{sec:solutions} We conducted a systematic literature review following the protocol described in Appendix A, yielding 80 relevant documents out of the initial 330. By grouping the publications and grey literature, a pattern arises: these works are either about interoperability across public blockchains holding cryptocurrencies, application-specific blockchain generators with interoperability capabilities, or protocols connecting heterogeneous blockchains. We thus classify each study into one of the following categories: \emph{Public Connectors} (Section \ref{sec_crypto}), \emph{Blockchain of Blockchains} (Section \ref{sec:be}), and \emph{Hybrid Connectors} (Section \ref{subsec:blockchain_connectors}). Each category is further divided into sub-categories. Table \ref{tab:existing_sols} summarizes the work conducted. \begin{table}[] \centering \resizebox{\textwidth}{!}{% \begin{tabular}{@{}lcccccccccccccl@{}} \toprule & \multicolumn{5}{c}{\textbf{Asset}} & \multicolumn{8}{c}{\textbf{Trust Establishment}} & \\ \midrule \multicolumn{1}{l|}{} & \multicolumn{3}{c|}{\textbf{Type}} & \multicolumn{2}{c|}{\textbf{Infra.}} & \multicolumn{3}{c|}{\textbf{Decentral.}} & \multicolumn{2}{c|}{\textbf{Channel}} & \multicolumn{3}{c|}{\textbf{CC-Realization}} & \\ \midrule \multicolumn{1}{l|}{\textbf{Sub-Category}} & \multicolumn{1}{c|}{D} & \multicolumn{1}{c|}{P} & \multicolumn{1}{c|}{U} & \multicolumn{1}{c|}{P} & \multicolumn{1}{c|}{NP} & \multicolumn{1}{c|}{U} & \multicolumn{1}{c|}{C} & \multicolumn{1}{c|}{TTP} & \multicolumn{1}{c|}{OC} & \multicolumn{1}{c|}{OF} & \multicolumn{1}{c|}{CC} & \multicolumn{1}{c|}{ECC} & \multicolumn{1}{c|}{M} & \multicolumn{1}{c}{\textbf{References}} \\ \midrule {\color[HTML]{ADD73F} \begin{tabular}[c]{@{}l@{}}Sidechains\\ \& Relays\end{tabular}} & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cite{plasma,wang-cc_elec-2020} \\ {\color[HTML]{000000} } & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cite{btcrelay, peacerelay, testimonium,waterloo2019,Frauenthaler2020} \\ {\color[HTML]{000000} } & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cite{POA,blockCollider} \\ {\color[HTML]{000000} } & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cite{peggedsidechains,loom,liquid,blockstream,nocust} \\ {\color[HTML]{000000} } & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cite{blocknet,rsk,zendo,horizon2021} \\ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cite{Shlomovits2020,cctxnarges,belotti2020,Robinson2019,Deshpande2020,gugger-bmcc-2020} \\ {\color[HTML]{000000} } & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cite{ILPv4,quilt} \\ \midrule {\color[HTML]{ADD73F} } & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & See Section \ref{sec:crypto_notaries} \\ \multirow{-2}{*}{{\color[HTML]{ADD73F} \begin{tabular}[c]{@{}l@{}}Notary\\ Scheme\end{tabular}}} & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cite{0x,uniswaptokrex,Tian2020} \\ \midrule {\color[HTML]{ADD73F} HLTC} & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cite{dextt,xclaim,Lu2017,comit,fusion,Dai-cctm-2020,Rueegger-ccas-2020} \\ \midrule {\color[HTML]{F79545} \begin{tabular}[c]{@{}l@{}}Blockchain\\ of Blockchains\end{tabular}} & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cite{Kwon2016,Wood2017,komodo} \\ {\color[HTML]{000000} } & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cite{ark2019,aion2017,overledger03} \\ \midrule {\color[HTML]{BF504D} \begin{tabular}[c]{@{}l@{}}Trusted \\ Relays\end{tabular}} & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cite{nissl2020,falazi2020,Kan2018,crossfabric2020} \\ {\color[HTML]{BF504D} } & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cite{Hardjono2019,hermes-middleware-2021,odap_draft_01,crp_draft_00,zhao2020,wang2020,xiao2020} \\ \midrule {\color[HTML]{BF504D} B. Agnostic} & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cite{hyperledger_cactus,abebe2020,Abebe2019,acctp2020} \\ {\color[HTML]{BF504D} Protocols} & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cite{hyperservice,ion2018,pilai2020,robinson2020,cantonwhitepaper,pang2020} \\ \midrule {\color[HTML]{BF504D} } & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{9B9B9B}N/A & \cellcolor[HTML]{9B9B9B}N/A & \cellcolor[HTML]{9B9B9B}N/A & \cite{Frauenthaler2019,scheid2019,Westerkamp-scmob-2019} \\ \multirow{-2}{*}{{\color[HTML]{BF504D} \begin{tabular}[c]{@{}l@{}}Blockchain\\ Migrators\end{tabular}}} & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{F79545}$\pm$ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{BF504D}- & \cellcolor[HTML]{D8E3BB}+ & \cellcolor[HTML]{BF504D}- & \cite{scotm} \\ \bottomrule \end{tabular}% } \caption{ Evaluation of blockchain interoperability solutions by subcategory accordingly to the Blockchain Interoperability Framework. N/A stands for not applicable. Public connectors are represented in green, Blockchain of blockchains in orange, and Hybrid connectors in red. } \label{tab:existing_sols} \end{table} \subsection{Public Connectors} \label{sec_crypto} The first family of blockchain interoperability solutions aimed to provide interoperability between cryptocurrency systems, as stated by Vitalik \cite{vitalik2016}. This category identifies and defines different chain interoperability strategies across public blockchains supporting cryptocurrencies, including sidechain approaches, notary schemes, and hash time hash-locks. Some solutions share characteristics of more than one sub-category, and thus they can be considered hybrid. We introduce each sub-category, presenting only two illustrative examples of each one for the sake of space. Appendix \ref{a:crypto} depicts a complete list of Public Connectors approaches. After that, a summarized evaluation table is presented using the BIF. These tables are later discussed in Section \ref{sec:disc_crypto}. \subsubsection{\underline{Sidechains \& Relays}} \label{subsec:crypto_side} A \emph{sidechain} (or \emph{secondary chain}, or \emph{satellite chain}, or \emph{child chain}) is a mechanism for two existing blockchains to interoperate \cite{peggedsidechains, sidechains_pos}, scale (e.g., via blockchain sharding \cite{omniledger}), and be upgraded \cite{velvet} in which one blockchain (\emph{main chain} or mainchain) considers another blockchain as an extension of itself (the sidechain). The mainchain maintains a ledger of assets and is connected to the sidechain, a separate system attached to the main chain via a cross-chain communication protocol \cite{zendo}. An example is a \emph{two-way peg}, a mechanism for transferring assets between the main chain and the sidechain \cite{singh2020}. Main chains can be sidechains of each other \cite{vitalik2016}, creating each chain's possible to connect to others. Sidechains are considered layer one solutions (built on top of layer 0 solutions - blockchains) to implement layer-2 solutions, such as payment channels \cite{nocust}. The second layer allows off-chain transactions between users through the exchange of messages tethered to a sidechain \cite{sok_layers}. A sidechain is then a construct that allows for offloading transactions from the mainchain, processes it, and can redirect the outcome of such processing back to the main chain. For instance, state channels are off-chain sidechains used to implement, for example, payment channels, by offloading transactions of the blockchain \cite{LN}. In a payment channel, participants interact, collecting cryptographically signed messages. Those messages update the current state without publishing it to the mainchain. When the payment channel is closed, the final state is published onto the main chain, where an on-chain dispute/closure phase may occur \cite{nocust}. Payment channels are appropriated for use cases requiring several transactions that can be combined in a single one. Main chains communicate with sidechains via a CCP, often tightly coupled with the functionality of both chains. The basic components of sidechain design are the mainchain consensus protocol, the sidechain consensus protocol, and the cross-chain communication protocol \cite{zendo}. Sidechains allow different interactions between participating blockchains, being the most common the transfer of assets between the main chain and the sidechain (two-way peg) \cite{pow_side,singh2020}. A \emph{two-way peg} works in the following manner: a user, operating on the mainchain, sends X tokens to a custom address that locks assets. Those funds are locked on the mainchain, and a corresponding number of tokens are created on the sidechain. The user can now use the tokens on the sidechain. Eventually, the user can transfer back the tokens to the main chain, which causes assets on the sidechain to be locked or destroyed, depending on the implementation. There are three major types of two-way pegs: simplified payment verification, centralized two-way pegs, and federated two-way pegs. \emph{Simplified payment verification} (SPV) \cite{nakamoto2008,spvbwiki} is done by \emph{light clients}, which consist of blockchain clients that can verify transactions on the blockchain without having its entire state. The SPV client only needs the block headers; verifying that a transaction is in a block is to request a Merkle tree proof \cite{merkle} including that transaction. In particular, transactions are represented as Merkle tree leaves. Given a leaf node as a target and a path comprised of nodes and its siblings to the target, verifying a Merkle tree proof of including the target is to reconstruct a partial Merkle tree root. A relay solution is an SPV client for a source blockchain running on a target blockchain, enabling verification of transactions \cite{testimonium}. This verification enables conditional logic to occur on a target blockchain. Since relays are between blockchains and those blockchains are using behavior from others (bidirectionally or unidirectionally), relays include the presence of sidechains. This is saying, without a sidechain, there are no relay solutions. \emph{Centralized two-way pegs}, on the contrary, trust a central entity, benefiting in terms of efficiency. An example is an \emph{exchange}, an organization, typically a company, that trades cryptocurrencies on behalf of its clients. However, Exchanges are a Notary Scheme, so we defer their explanation to Section \ref{sec:crypto_notaries}. Disadvantages include a single point of failure and centralization. \emph{Federated two-way pegs} try to decentralize the previous solution. In this solution, a group is responsible for locking and unlocking funds instead of just one. Standard implementations rely on multi-signature schemes, in which a quorum of entities must sign transactions to be deemed valid by the network. Although a better option, it does not eliminate centralization. \begin{wrapfigure}{r}{0.55\textwidth} \centering \includegraphics[scale=0.40]{figures/Fig6.pdf} \caption{A general sidechain system \cite{btcrelay}} \label{fig:sidechains} \end{wrapfigure} Figure \ref{fig:sidechains} depicts a system based on the BTC Relay \cite{btcrelay}. In \emph{BTC Relay}, parties called \emph{relayers} keep track of the block headers of the main chain (the Bitcoin network in the figure), and input them to the BTC Relay smart contract, hosted on Ethereum. This procedure builds a pool of Bitcoin headers that can be used (via their stored Merkle trees) to verify on-chain information, including the presence of transactions. This way, any party can request a transaction to be verified by the smart contract that holds the headers' knowledge (via SPV). Transaction validation can be relayed to deployed Ethereum smart contracts, allowing several use cases, for example, the issuance of tokens. \emph{Zendoo} is a cross-chain transfer protocol that realizes a decentralized, verifiable blockchain system for payments \cite{zendo}. The authors consider a parent-child relationship, where nodes from the sidechain can observe the mainchain's state, but the main chain can only observe the sidechains via cryptographically authenticated certificates. Zk-SNARKSs enable the authentication, validation, and integrity of the information provided by the sidechains via verifiable proofs \cite{zksnarks}. Such proofs are used to generate certificate proofs for the mainchain, enabling a secure verification scheme. \subsubsection{\underline{Notary Schemes}} \label{sec:crypto_notaries} A notary scheme involves a \emph{notary} that is an entity that monitors multiple chains, triggering transactions in a chain upon an event (e.g., a smart contract is deployed) taking place on another chain \cite{vitalik2016}. Notary schemes are, in practice, instantiated as centralized exchanges (EXs) or decentralized exchanges (DEXs). The most popular centralized exchanges, by volume, as of the 8th of February 2021 are Binance\footnote{https://www.binance.com/en}, Coinbase\footnote{https://www.coinbase.com/}, and Huobi Global\footnote{https://www.huobi.com/}. Exchanges facilitate signaling between market participants by managing an order book and matching buyers and sellers. If the trust anchor is put on a centralized party, where it holds users' private keys or funds, the notary is a centralized exchange. Otherwise, if exchanges do not execute the trades on behalf of the users, only providing a matching service, they are considered decentralized exchanges. We present the protocols of two decentralized exchanges: 0x \cite{0x}, and Uniswap \cite{uniswap}. \emph{0x} implements a decentralized exchange as a set of smart contracts (called automated market makers), replacing an on-chain order book with a real-time price-adjustment model. 0x uses a hybrid implementation, ``off-chain order relay with on-chain settlement'', combining the idea of a state channel with settlement smart contracts. Two parties participate: \emph{makers} and \emph{takers}. Makers place orders on the exchange, providing liquidity for the network (a set of decentralized exchanges), while takers place orders matched with the makers' orders. 0x uses the ZRX token and the Ethereum blockchain to incentivize users to host and maintain order books (provide liquidity). In exchange, 0x makers choose the rewards they obtain for each trade - although they have to comply with the DEX policies under the possibility of the order not being disseminated. This approach relies on a smart contract set (smart contract) and several smart contracts representing the different tokens supported. First, a maker creates an order to exchange token A for B, at a given rate, right after it approves a DEX to access its balance of token A. A taker discovers this order and wishes to trade its tokens B for tokens A. The taker grants permission to the DEX to access its tokens, and the DEX performs the exchange after several validations (e.g., the order has not expired, and it has not been filled). \emph{Uniswap} is a set of smart contracts implementing an automated liquidity pool, serving as a decentralized exchange \cite{uniswap}. Each Uniswap pool provides liquidity for two assets based on the constant set as the reserves' product. Prices for each asset are provided by an on-chain price oracle smart contract. Uniswap can support ERC-20 to ERC-20 trades and even flash loans, a theme explored in the decentralized finance area. A flash loan is a type of loan that does not require collateral, as the debt is repaid within the transaction. Flash loans work because the borrowed asset to be paid within the transaction requesting it \cite{uniswap}. \subsubsection{\underline{Hashed Time-Lock Contracts}} \label{subsec:crypto_hashed} Hashed time-locks contracts (HTLCs) initially appeared as an alternative to centralized exchanges, as they enable cross-chain atomic operations \cite{htl}. HTLCs techniques use hashlocks \cite{hashlock} and timelocks \cite{timelock} to enforce atomicity of operations, normally between two parties. A trader commits to make the transaction by providing a cryptographic proof before a timeout to the other. This scheme allows for the creation of multiple outputs (such as multiple payments), depending on solely one hashlock. HTLCs are used in Bitcoin for conditional payments, or cross-chain payments (Bitcoin-Ethereum), i.e., \emph{atomic swaps} \cite{atomicswaps,Black2019,accs2015}. Atomic swaps can be thought as a form of distributed commitment resilient to Byzantine adversaries. Thus, an atomic cross-chain swap is a distributed atomic transaction \cite{Herlihy2018}, settled on-chain. Several projects implement HTLCs differently, providing different correctness guarantees. However, the general algorithm is quite similar in most of the solutions. Let us consider an HTLC-supported atomic swap between Alice (holding assets of type $a$ in blockchain $\mathcal{B}_a$) and Bob (holding assets of type $b$ in blockchain $\mathcal{B}_b$). An atomic swap can be realized as follows \cite{belotti2020,zapala2020}: 1) Alice generates and hashes a secret $s$, yielding $h$. The protection of a smart contract with hash $h$ is called a hashlock because it will lock a smart contract - only parties with knowledge of secret $s$ can know it since secure hash functions are pre-image resistant (i.e., a hash function cannot be inverted). Alice also creates a timelock $t_b$, corresponding to an upper bound in which the created hashlock can be unlocked, i.e., Bob can unlock the smart contract up to $t_b$, where $t_b$ corresponds to a specified future time or block height; 2) Alice publishes the smart contract in $\mathcal{B}_a$. Bob verifies the deployment, and records $h$ and $t_b$; 3) Bob publishes a smart contract in $\mathcal{B}_b$ locking $b$ with hashlock $h$, but with timelock $ta$ such that $t_a < t_b$, i.e., Alice can claim $b$ before $t_a$. 4) Alice checks that Bob's smart contract has been published and gives as input secret $s$, before $t_a$, acquiring asset $b$. In practice, this triggers a transfer; 5) Bob now sends $s$ to Alice's smart contract in the interval $[t_a,t_b]$, acquiring $a$. Note that if Bob issues the transaction after $t_b$, Bob will not obtain access to $b$. Some solutions utilize the notion of HLTC and enhance it, providing an additional on-chain trust anchor. In particular, two solutions are presented: XCLAIM \cite{xclaim} and the \ac{LN} \cite{LN}. \emph{XClaim} uses a combination of HLTCs, collateralization, and escrow parties, realizing non-interactive cross-chain atomic swaps \cite{xclaim}. This protocol includes several actors: the requester, the sender, the receiver, the redeemer, the backing vault, and the issuing smart contract. Requesters lock coins to issue tokens, while the redeemer burns tokens to receive coins. The sender sends tokens, while the receiver receives them. After that, the vault smart contract fulfills requests of asset backing and ensures correct redeeming. An issuing smart contract issues and exchanges representations of a token (cryptocurrency-backed assets) and enforces the vault's correct behavior. Considering a transaction between Bitcoin and Ethereum, firstly, the vault locks collateral in Ethereum smart contracts. This collateral defines the amount of CBA that the vault can issue. A user that wants to issue Bitcoin-backed tokens sends Bitcoin to the vault. User A then sends a proof of transaction submitted to the Bitcoin mainchain to a chain relay, e.g., BTC Relay. The chain relay verifies the submitted transaction and alerts the issuing smart contract. The smart contract releases the Bitcoin-backed assets to the user. On the other hand, a user issues a transaction against the smart contract, locking/burning its backed tokens. The vault releases the Bitcoin to the user, and it submits a proof of the involved operations to the chain relay. The chain relay verifies the proof and only then releases the collateral to the vault. XClaim currently supports exchanges between Bitcoin and Ethereum\footnote{https://github.com/crossclaim/xclaim-sol}. The protocol execution consumes substantially lower Ether than traditional HTLCs. {\ac{LN}} enables high-volume, low latency micro-payments on the Bitcoin network \cite{LN}. LN is a payment scheme (i.e., an off-chain sidechain). LN allows several parties to open a payment channel, transact amongst them, and when all the intermediary payments are completed, the final output is sent to the mainchain. LN works as follows: 1) funds are placed into a multi-signature Bitcoin address (two-party multi-signature if only two people are transacting). In order for funds to be changed, two signatures are required. After that, the funds will be managed off-chain via commitment transactions (i.e., a commitment to pay part of the available funds to the other party); 2) Parties can now transact offline under the regime they choose; 3) To settle the payments performed off-chain, both parties sign a new exit transaction. Note that parties can unilaterally close the payment channel in case of conflict. LN is considered a precursor of HLTCs because its bi-directional payment channels allow payments to be routed across multiple payment channels using HLTCs. \subsubsection{\underline{Discussion on Public Connectors}} \label{sec:disc_crypto} Public Connectors started emerging as early as 2015 \cite{ZyskindOz2015}, when researchers and practitioners alike saw the potential in cross-chain transactions to support, for instance, atomic swaps \cite{atomicswaps,Black2019,accs2015}, and payment channels \cite{LN}. Sidechains are the solutions increasing the main network's scalability by processing and batching large amounts of transactions before submission on the main blockchain \cite{singh2020, plasma, rsk}. Relays can fetch block headers from sidechains, enabling data verification \cite{btcrelay,peacerelay,waterloorelay}. While sidechains are mainly used on public blockchains, there are also permissioned blockchain sidechains \cite{sidechain_fabric}. We note that some sidechains may have a cross-chain mechanism realization HLTCs, being a solution belonging to multiple categories (e.g., \cite{LN}). Most sidechains use Ethereum and have a sidechain consensus mechanism, which is allusive to bidirectional transfers \cite{zendo}. Simple relay schemes, which verify transactions on other chains, such as BTC Relay, have a simple sidechain consensus, as the information flow is unidirectional \cite{btcrelay}. In particular, validators can sign events that happened on the source chain (if validation happens across EVM-based chains) or transfer block headers (via users or aggregation chains) \cite{robinson2020}. Liquid \cite{liquid}, and POA \cite{POA} rely on a consortium of validators running trusted hardware to execute smart contracts and validate transactions. Other solutions, such as Wanchain \cite{wanchainroadmap} rely on a trusted consortium, but without running trusted hardware. However, sidechains suffer from several limitations. Safe cross-chain interactions are rooted in the assumption that the main chain is secure, i.e., the network cannot be successfully attacked. Compromising the main chain would invalidate the sidechain logic. Conversely, centralization in sidechains tends to exist to a higher degree than on mainchains, because typically there is a trade-off between decentralization-performance (e.g., lesser validating nodes versus higher throughput). Consequently, if an attacker can obtain control on a (potentially small) set of validators, funds can be stolen from users. Therefore, it is important to have different stakeholders with different incentives, diminish the likelihood of collusion, and rely on a reasonable quorum of validators to sign each transaction (e.g., 8 out of 11 versus 3 out of 10). If a sidechain has a strong security model, it may lead to a slow transaction settlement, stalling assets, and lowering liquidity. For example, the RSK sidechain \cite{rsk} takes approximately the time to confirm 100 Bitcoin blocks (around 15 hours) to convert BTC to RBTC\footnote{https://developers.rsk.co/rsk/}. Finally, sidechains typically do not allow for arbitrary code to specify conditions on the pegging mechanism, thus not empowering them to develop more complex applications. Notaries on the Public Connectors category are cryptocurrency exchanges. EXs have the majority of the market share, comparatively to DEXs. While EXs provide services to the end-user, decentralized exchanges tend to provide better exchange fees and security. The trade-off is, therefore, comfort and speed - security. This subcategory provides great flexibility at run-time because EXs and smart contracts that DEXs support triggers (e.g., stop-loss orders). Notary schemes have to capture the logic of smart contracts in both chains. Although they can capture the full spectrum of interoperability -- both at the value and mechanical levels (see Section \ref{subsec:blockchain_connectors}), practical applications are limited. In summary, notary schemes are intermediaries between blockchains. EXs are notaries because they execute actions on behalf of the end-user (e.g., buy cryptocurrencies conditionally). DEXs are notaries because they provide matching for the end-users by pinning and advertising trade offers encoded in smart contracts. The HTLCs category was the first one to allow asset exchange in a trustless way. HTLCs allow atomic swaps between different blockchains, funding bidirectional payment channels. HTLCs are flexible because they can be chained after each other \cite{zapala2020}, and therefore enable trades even if there is no direct connection between the trading parties. As they serve as programmable escrows, they represent the most trustless and practical approach of the three. However, hashed timelocks might lead to capital retention and unfair trade, as the trader issuing a cross-blockchain asset transfer may only provide the secret on specific conditions (exploring the spread of the cryptocurrency exchange rate) \cite{xclaim}. Many solutions are hybrid, sharing characteristics of HTLCs and sidechains, either exploring collateralization-punishment schemes rooted on smart contracts (\cite{cctxnarges,sai2019,xclaim}, or locking-in and locking-out assets \cite{dextt,fusion,metronome_faq,metronome}. HLTCs are practical solutions across public blockchains. HLTCs could also provide asset transfers between private blockchains, but only under the participation of a third party blockchain and a semi-trust environment \cite{hardjono2021}, or if both parties belong to both private blockchains. Current efforts to address these limitations include Hyperledger Cactus \cite{hyperledger_cactus}. Concluding, Public Connectors are the best approach to perform cryptocurrency trades and moving fungible and non-fungible assets across public blockchains. We encourage the reader to refer to some related surveys focusing on sidechains to complement this survey (see Section \ref{sec:related_literature_reviews}). \subsection{Blockchain of Blockchains} \label{sec:be} \emph{Blockchain of Blockchains} are frameworks that \emph{provide reusable data, network, consensus, incentive, and contract layers for the creation of application-specific blockchains (customized blockchains) that interoperate between each other}. We briefly present Polkadot \cite{Wood2017,polkadot_2} and Cosmos \cite{Kwon2016}, the most widely adopted Blockchain of Blockchains in terms of market capitalization\footnote{USD 22.1B and USD 3.6B respectively, as of February 2021}. A detailed comparison between Polkadot, Cosmos, and Ethereum 2.0 (the baseline) is deferred to Appendix \ref{a:be}. Other Blockchain of Blockchains include Ark \cite{ark2019}, Komodo \cite{komodo}, and AION \cite{aion2017}. Wood proposes \emph{Polkadot}, a network that aims to connect blockchain networks \cite{Wood2017}. Polkadot provides the foundation for \emph{parachains}, i.e., ``globally-coherent dynamic data structures'' hosted side-by-side. Parachains are, thus, the parallelized chains that participate in the Polkadot network. Specialized parachains called bridges link independent chains \cite{Wood2017}. Polkadot is based on \emph{Substrate}, a framework for creating cryptocurrencies and other decentralized systems. It guarantees cross-language support with WebAssembly, a light client, and off-chain workers, allowing for integration with other technologies. Polkadot enables interoperability based on state transition validation, done by the chain-relay validators. Parachains communicate through the Cross-chain Message Passing Protocol (XCMP), a queuing communication mechanism based on a Merkle tree \cite{xcmp}. Communicating state transition proofs from parachain to relay chain is achieved via an erasure-coding scheme. Polkadot scales by connecting up to 100 parachains directly to the relay chain in the short-medium term. A long-term solution is being studied, where second and third-level parachains are added in parallel. \emph{Cosmos} is a decentralized network of independent parallel blockchains, called \emph{zones} \cite{Kwon2016}. The zones are essentially Tendermint blockchains \cite{tendermint}. Zones can transfer data to other zones directly or via \emph{hubs}. Hubs minimize the number of connections between zones and avoid double spendings. For example, zone A can connect to zone B via Hub C and receive tokens from zone B. Zone A would need to trust the tokens from zone B and Hub C. This scheme allows zones to maintain a reduced number of connections. Both ways utilize the inter blockchain communication protocol (IBC) \cite{ibc}. IBC resembles the Internet network layer as it routes arbitrary data packets to a target blockchain. A target blockchain can know that a certain ordered packet with arbitrary data came from another blockchain. By handling transportation and order, the protocol has several steps to achieve cross-zone transactions. First, each chain involved tracks the headers of the others, acting as a light client. When a transfer is initiated, the protocol locks the assets on the origin chain. After that, the proof is sent to the target blockchain, which then represents the locked assets. A similar mechanism is used to recover the original tokens. This scheme allows for interoperability among Tendermint blockchains. Other kinds of blockchains can interoperate with a Cosmos chain via peg zones. Peg zones resemble the pegged sidechain mechanism \cite{peggedsidechains}, in which a representation of the locked token of the source blockchain is created on the target blockchain. Cosmos abstracts the development of a blockchain into three layers: networking, consensus, and application. Tendermint BFT realizes the networking and consensus layers. The Tendermint BFT engine is connected to the application layer by a protocol called: the Application Blockchain Interface (ABCI). The Cosmos SDK realizes the applicational layer, allowing developers to develop smart contracts in languages that can be compiled to WASM\footnote{https://blog.cosmos.network/announcing-the-launch-of-cosmwasm-cc426ab88e12}. \subsubsection{\underline{Discussion on Blockchain of Blockchains}} \label{sec:block_engine_disc} Blockchain of Blockchains implementations are similar to relays and sidechains, as there is typically the main chain (often called relay chain) that connects the secondary chains, which can be application-specific blockchains. This scheme allows high throughput and flexibility to the end-users, providing interoperability capabilities between their platform instances. For example, Cosmos's Tendermint-based blockchains interoperate (instant finality assured), while Polkadot provides interoperability on Substrate-based blockchains (for instance, via Cumulus\footnote{https://wiki.polkadot.network/docs/en/build-cumulus}, a tool for connecting a blockchain to Polkadot). To connect to other chains, Cosmos, Polkadot, AION, and utilize a mechanism similar to pegged sidechains or hashlock time contracts (ARK \cite{ark2019}) to interact with other blockchains, commonly called bridges. \begin{table*}[] \caption{Comparison of Blockchain Engine interoperability solutions \cite{polkadot_comparison,Kwon2016}} \label{tab:be} \centering \normalsize \resizebox{\textwidth}{!}{% \begin{tabular}{@{}lllllllllll@{}} \toprule & \multicolumn{2}{c}{\textbf{Communication}} & \multicolumn{6}{c}{\textbf{Properties}} & \multicolumn{2}{c}{\textbf{Community}} \\ \midrule \multicolumn{1}{l|}{} & Cross-chain & \multicolumn{1}{l|}{Cross-blockchain} & Consensus & Security & Validator & Maximum & Number of & \multicolumn{1}{l|}{Smart} & \multicolumn{1}{c}{Launch} & \multicolumn{1}{c}{Roadmap} \\ \multicolumn{1}{l|}{} & Protocol & \multicolumn{1}{l|}{interoperability} & Mechanism & assumption & number & Throughput & instances & \multicolumn{1}{l|}{Contracts} & & \\ \midrule \multicolumn{1}{l|}{Polkadot \cite{Wood2017} \mbox{}\hfill \checkmark} & XCMP & \multicolumn{1}{l|}{$\CIRCLE$} & BABE and GRANDPA & SM & 197 & $10^{3}$ & 200 & \multicolumn{1}{l|}{WASM} & November 2019 & Main network launch \\ \multicolumn{1}{l|}{Cosmos \cite{Kwon2016} \mbox{}\hfill \checkmark} & IBC Protocol & \multicolumn{1}{l|}{$\LEFTcircle$} & Tendermint & SM & 125 & $10^{3}$ & $\textgreater$ 70 & \multicolumn{1}{l|}{WASM} & March 2019 & Governance updates \\ \multicolumn{1}{l|}{ARK \cite{ark2019} \mbox{}\hfill \checkmark} & SmartBridge & \multicolumn{1}{l|}{$\LEFTcircle$} & Delegated proof of stake & M & 51 & 18.5 & Unlimited & \multicolumn{1}{l|}{WASM$^{\ast}$} & May 2019 & ARK Swap Market \\ \multicolumn{1}{l|}{AION \cite{aion2017} \mbox{}\hfill \checkmark} & Interchain transactions & \multicolumn{1}{l|}{$\Circle$} & Proof of intelligence & M & $\times$ & $\times$ & $\times$ & \multicolumn{1}{l|}{Aion Language} & April 2018 & Market assimilation \\ \midrule & & & & & & & & & & \\ \multicolumn{11}{l}{\begin{tabular}[c]{@{}l@{}}\checkmark our description was endorsed by the authors/team \\ $\times$ not known \\ $\ast$ some languages compilable to WASM, such as Go and .NET, but not all of them\end{tabular}} \\ \multicolumn{11}{l}{\begin{tabular}[c]{@{}l@{}}$\CIRCLE$ can interoperate with instances of the same blockchain engine. Interoperate with more than two heterogeneous blockchains\\ $\LEFTcircle$ can interoperate with instances of the same blockchain engine. Interoperate with up to two heterogeneous blockchains \\ $\Circle$ can interoperate with instances of the same blockchain engine\end{tabular}} \end{tabular}% } \end{table*} Table \ref{tab:be} maps out the current blockchain engine landscape by extracting and evaluating their main characteristics. Some information was not possible to obtain due to the lack of details on the whitepapers. It is possible to observe that Blockchain of Blockchains is very recent: Polkadot's test network, Kusama \cite{kusama}, was released in November 2019; Cosmos' main network was launched in March 2019. ARK launched in May 2019. AION launched in April 2018. Blockchain of Blockchains has different cross-chain communication protocol, e.g., in Polkadot, {cross-chain message passing}\footnote{https://wiki.polkadot.network/docs/en/learn-crosschain}; in Cosmos, the inter-blockchain communication protocol \cite{Kwon2016}. Cosmos and Polkadot have some differences regarding their approach: in Cosmos, the idea is to provide blockchains tailored to specific applications. IBC is more generic than XCMP, letting users customize their zones with higher freedom: security and validation are decided per zone. Polkadot restricts this customization but offers a shared security layer, making a trade-off security-customization. The security assumptions criteria depict the number of nodes assumed to be honest. A supermajority (SM) assumes that at least two-thirds of the nodes are honest, a common condition required by Byzantine fault-tolerant consensus algorithms ($n \textgreater$ $\frac{2}{3}$), while the majority (M) assumes at least half of the nodes are honest ($\textgreater \frac{1}{2}$). The validator number on a network comes with a trade-off: while a higher number is generally better for decentralization and robustness, it comes with an increase of latency towards block production -- and consequently lower throughput. Polkadot currently has around 297 validators, and this number is gradually increasing in the short-term to support up to 100 first-level parachains. At the time of writing, Polkadot is developing bridges for Bitcoin \cite{xclaim}, Tendermint, Libra \cite{libra}, and Ethereum. Interoperability between parachains is provided by Substrate. Currently, Cosmos has 125 validators. The number of validators can rise to 300. Currently, there are around 70 zones, and ``the number is growing''. While Cosmos does hold a limit for zones (as each zone is self-sovereign), there is no limit for how many zones can be attached to a Hub. Cosmos can interoperate with Etheruem. The Cosmos SDK provides interoperability between zones. Cosmos supports multiple peg zone implementations for Bitcoin and one for Ethereum. ARK has 51 validators, which can validate the transactions of a number of blockchains bound to the company's physical resources (instances managed by ARK). ARK can send and receive ERC-20 tokens to the Ethereum blockchain. We found no information regarding AION's validator number, throughput, or maximum sub-chains \cite{aion2017}. The theoretical throughput of the presented solutions varies: Polkadot's relay chain supports around 1000 transactions per second, considering that a block can include around 7,000 transactions at a 6-second block time (considering current weights, March 2021). Cosmos theoretical throughput can achieve up to dozens of thousands of transactions per second (tps) with two validators. With 64 validators, it falls into several thousand transactions per second. ARK can achieve around 18.5 transactions per second, relying on a proof of work consensus. The number of validators is set to 51. ARK is not a completely decentralized solution, as it manages instances of ARK blockchains. There is no theoretical limit of bridge chains, except the service provider resources. Several optimizations are being done in Cosmos, Polkadot, and ARK, to increase the throughput. The AION The project looks deprecated and stalled. As stated, the ``white paper is both ambitious and experimental'' \cite{aion2017}. AION is now a part of a larger project called the \emph{Open Application Network} (OAN). Cosmos and Polkadot support smart contracts in languages compilable to WASM (Web Assembly), which means developers can write them in languages such as Go, C++, and JavaScript. AION would support domain-specific languages, Aion language. Blockchain of Blockchains instances achieve inter-chain interoperability by a common point of contact, the ``connector'', analogous with Hyperledger Fabric channels \cite{fabric}. The connectors are the relay chain, the Cosmos Hub, the AION-1 blockchain, and the ARK main net if the technology is Polkadot, Cosmos Network, AION, or ARK, respectively. In Polkadot, the connector provides shared security. The relay-chain (the chain that coordinates consensus and communication between parachains and external blockchains) connects parachains and parachains to bridges. In Cosmos, the connector is loosely coupled to blockchains, providing greater flexibility than Polkadot. We could not extract meaningful considerations about AION's connector. In ARK, it looks like the connector is centralized at the expense of developability and ease of use. Concerning cross-blockchain interoperability, all solutions rely on \emph{bridges} or \emph{adapters} that route transaction from a particular blockchain type to another. While the provided features can be desirable for end-users, blockchain-engines do not interoperate with each other. In light of this fact, end-users are obligated to choose between existing solutions, leading to sub-optimal leveraging of available resources. Therefore, participant networks have constraints on interoperability, ending at relying on a single blockchain engine solution. Some authors defend that blockchain engine approaches are not universally accepted and cannot eliminate fragmentation \cite{Abebe2019}. Some solutions are even centralized, in the sense that its code is not open-source, and the end-user needs to use an SDK to access core functionalities (e.g., \cite{ark2019,aion2017}). However, ongoing work on building a Tendermint light client for GRANDPA, which would allow Polkadot to interact with Cosmos may allow blockchain engine interoperability in the short-medium term. Thus, in theory, interoperability across Blockchain of Blockchains can also be achieved via the relay chain technique (i.e., a blockchain engine can be a sidechain of other blockchain engines; validation can happen via SPV). Moreover, Blockchain of Blockchains requires transaction fees to keep the network operating. Given enterprise blockchain systems, a question could be posed: at which point shall an organization pay fees to sustain its business model across several blockchains? While Cosmos can provide flexibility configuring a zone, on Polkadot, this can be harder. Therefore, Blockchain of Blockchains can provide an optimal leveraging for public infrastructures, but that is not necessarily the case for private blockchains. \subsection{Hybrid Connectors} \label{subsec:blockchain_connectors} The \emph{Hybrid Connector} category is composed of interoperability solutions that are not Public Connectors or Blockchain of Blockchains. Directed to both public and private blockchains, Hybrid Connectors attempt at delivering a ``blockchain abstraction layer'' \cite{wef2020}, capable of exposing a set of uniform operations allowing a dApp to interact with blockchains without the need of using different APIs \cite{falazi2020}. We derived a set of sub-categories from the studies available: \emph{Trusted Relays}, \emph{Blockchain Agnostic Protocols} (including \emph{Blockchain of Blockchains}), and \emph{Blockchain Migrators}. Trusted relays are directed to environments where a blockchain registry facilitates the discovery of the target blockchains. Typically, such a scheme appears in a permissioned blockchain environment, where trusted escrow parties route cross-blockchain transactions. As the name suggests, Blockchain-agnostic protocols provide technology-agnostic protocols for interoperation between distributed ledger systems but do not guarantee backward compatibility. In other words, to use such protocols, their source code has to be changed to existing blockchains to use such protocols. Solutions from the blockchain of blockchains category aim to provide mechanisms for developers to build cross-chain dApps. The blockchain migrators sub-category aggregates solutions that perform data migration across blockchains, which resemble the notary schemes discussed in Section \ref{sec:crypto_notaries} (as there is typically a centralized party mediating the migration process). We introduce each sub-category, presenting only one illustrative example of each for the sake of space. Appendix \ref{a:connectors} depicts a complete list of Hybrid Connectors. Evaluation tables for each sub-category are discussed in Section \ref{sec:disc_connect}. \subsubsection{\underline{Trusted Relays}} \label{sec:block_connector_trusted_relay} Trusted relays are trusted parties that redirect transactions from a source blockchain to a target blockchain, allowing end-users to define arbitrary business logic. These solutions imply managing different APIs, in which cross-chain consensus may be modular. \emph{Hyperledger Cactus} (Cactus), previously known as Blockchain Integration Framework, uses an interoperability validator network that validates cross-chain transactions, optionally using a trusted escrow party \cite{hyperledger_cactus}. However, decentralized validators are implemented as well -- making this project move towards a decentralized trusted relay. Cactus allows a party or a set of parties to issue transactions against several ledgers, similarly to some notary scheme solutions \cite{timothesis,timo2019}. The interoperability is enabled through a set of \emph{interoperability validators}, which are participants from the source and target blockchains. Such validators collect cross-chain transaction requests, sign and deliver them. A CB-Tx is deemed valid, given that a quorum of validators signs them. It is then assumed that the blockchains participating in the network know how to address each other. However, trusted escrows can be replaced by decentralized parties. Currently, Hyperledger Cactus\footnote{https://github.com/hyperledger/cactus} supports Hyperledger technologies (e.g., Fabric, Besu), Corda, and Quorum. The roadmap predicts integration with public blockchains and blockchain migration capabilities. \subsubsection{\underline{Blockchain-Agnostic Protocols}} \label{sec:block_connector_blockagnosticprotocol} Blockchain-agnostic protocols enable cross-blockchain or cross-chain communication between arbitrarily distributed ledger technologies by providing a blockchain abstraction layer. These solutions enable BoBs, ``a system in which a consensus protocol organizes blocks that contain a set of transactions belonging to CC-dApps, spread across multiple blockchains. Such system should provide accountability for the parties issuing transactions on the various blockchains and providing a holistic, updated view of each underlying blockchain'' (Section \ref{subsec:bid}). Typically, the cross-chain consensus is fixed, and business logic is more restricted. The \emph{\ac{ILP}} can be considered a decentralized, peer-to-peer payment network \cite{Thomas2015}. It firstly adopted a generalized hash locking scheme to enable asset transfers, and it was directed to cryptocurrency transfers. Nowadays, ILP is technology-agnostic, defining a ``lowest unit common denominator'' across distributed ledgers, blockchains, fiat payment networks, the ILP packet. ILP sends payment information in packets by leveraging a network of connectors, which route such packets. At the core of Interledger is the Interledger Protocol (ILPv4) \cite{ILPv4}, which defines how senders, routers (or node, or connector), and receivers interact. Typically, the connector is a money packet router. The root of trust is then the connector, which has to be trusted: companies can settle payments via the routers, given that clearance of such payments is done afterward while being protected by the law. A sender is an entity that initiates a value transfer. A router applies currency exchange and forwards packets of value. The receiver obtains the value transmitted. ILPv4 is a request/response protocol enabled by ILPv4 packets. Each packet contains transaction information, and can be divided into \emph{prepare}, \emph{fulfill}, and \emph{reject} packets. A sender node initiates an exchange of value by sending a \emph{prepare} ILPv4 packet to a receiver. When a receiver obtains the prepared packet, it sends the response back to the sender via routers. The response may be a \emph{fulfill} packet, whereby a transaction has been successfully executed, or a reject packet. Several specifications for Interledger and related protocols are available\footnote{https://github.com/interledger/rfcs}. The Interledger Protocol is discussed by a W3C community group\footnote{https://www.w3.org/community/interledger/} and has a proposal that ``describes data structures and formats, and a simple processing model, to facilitate payments on the Web''\footnote{https://w3c.github.io/webpayments/proposals/interledger/}. The interledger protocol cannot integrate with existing blockchains: each one must be adapted to use ILP. A disadvantage is that Interledger does not support the transfer of non-fungible tokens (such as ERC-721\footnote{http://erc721.org/} tokens). \subsubsection{\underline{Blockchain Migrators}} \label{sec:block_connector_bm} Blockchain migrators allow an end-user to migrate the state of a blockchain to another. Currently, it is only possible to migrate data across blockchains, although moving smart contracts is also predicted \cite{hyperledger_cactus}. \emph{Fynn et al.} present an abstraction for smart contracts to switch to another blockchain consistently, moving the state required by the transaction to the target blockchain and execute it \cite{scotm}. The authors call such abstraction the \emph{Move} operation. The operation works as follows: first, it locks a smart contract on the source blockchain; next, the Move protocol recreates the smart contract in the target blockchain. This method allows arbitrary states to be transferred between blockchains. For example, it allows transferring cryptocurrencies by creating tokens on the target blockchain backed-up by locked tokens on the source blockchain (similarly to pegged sidechains). This method was tested on Ethereum and Hyperledger Burrow (based on Ethereum). The solution assumes the same cross-blockchain smart contracts utilize the same virtual machine, which can be limiting. Furthermore, for such a solution to be deployed, it requires Solidity changes and possibly a soft fork on Ethereum. \subsubsection{\underline{Discussion on Hybrid Connectors}} \label{sec:disc_connect} This section defined the hybrid connector category and its sub-categories: trusted relays, blockchain-agnostic protocols, and blockchain migrators. Regarding centralization, almost all adopt a decentralized model. Permissioned blockchain solutions are less flexible, as all involved participants are identified. In particular, trusted relays endorse connections made in a peer-to-peer fashion, upon previous agreement \cite{Abebe2019,Ghaemi2021}. However, Abebe et al.'s work pose some limitations: interoperating networks require a priori knowledge of each other's identities and configurations, hence being static. A discovery service could be implemented using a blockchain registry or a pub-sub mechanism \cite{Ghaemi2021}, in which networks could be added and removed. In trusted relays, it is not completely clear the mechanisms to minimize malicious relay services, apart from replication (whereby the risk of a censorship attack is reduced but not erased). Hyperledger Cactus could be a true enabler of interoperability, given that a (decentralized) trusted blockchain registry would be deployed, and public escrow parties could replace the overlay of trusted parties. Cactus could, therefore, make the transition between a trusted relay to a semi-trusted relay or even a trustless relay. Blockchain-agnostic protocols will be better positioned to offer interoperability to existing and yet to-exist blockchains, but most do not grant backward compatibility and lack the flexibility to define business logic. This inflexibility is inherent to the provided homogeneous interfaces (containing roles, methods, data, message formats, for instance, \cite{falazi2020}); at least such solutions scale slowly, as adding methods compatible with all the supported blockchains incur in a polynomial effort. However, this category might resemble some of the trusted relay solutions. In particular, both Cactus \cite{hyperledger_cactus}, and SCIP \cite{falazi2020} rely on connectors and validators and gateways, to access the underlying blockchains. The gateway paradigm implies a (semi) trusted gateway having read/write access to the shared ledger of the blockchain, and often they are expected to participate in the consensus mechanism of the blockchain \cite{hardjono2021}. While there is a higher trust requirement, gateway approaches might be the most suitable to solve interoperability across private blockchains if gateways are framed in a legal and regulatory framework. Proper solutions for enterprises, gateways need infrastructure comprising, for example, public identifiers, a set of connectors, and validators (which Cactus could provide), among others. From the blockchain of the blockchains category, we highlight Hyperservice, a peer-reviewed paper, and Overledger. Hyperservice tries to achieve full dApp atomicity by introducing the concept of \emph{stateless smart contracts}. Using a stateless smart contract, a \ac{CC-dApp} can load a clean state for a contract, using a valid block. While it can partially solve forks in the underlying blockchains, a \ac{CC-dApp} utilizes, the application of this concept paves a direction to decouple smart contract execution from the consensus layer \cite{hyperservice}. Overledger is a sorted list of messages that are interpreted as the state of a cross-blockchain application. While this is an exciting approach to blockchain interoperability, the solution is proprietary, hindering community efforts for more complex solutions. Blockchain migrators respond to an enterprise need: migration in case of disaster or performance issues \cite{belchior2020_bpvi,bandara2019}. The two presented solutions can only provide data portability across a small set of public blockchains. It is currently impossible to reproduce the chain of events via smart contracts, as that requires a smart-contract translator functionality. A limitation that we identified in the context of Hybrid Connectors is that most solutions do not support hard forks (i.e., the separation of a blockchain into two different blockchains) nor propose a solution for eventual forks, unlike some public connectors (most HTLCs and notary schemes). Forks do not happen regularly, and some solutions offer a quick analysis of the problem and acknowledge their importance \cite{hyperledger_cactus, blockCollider, Verdian2018}. However, this is still a problem that can affect the dependability of cross-chain dApps; dealing with forks is still an open issue. For instance, the protocol used in Hyperservice is unable to revert any state update to smart contracts when a dApp terminates prematurely, i.e., it does not grant atomicity. If one does not have atomicity guarantees, it forces the cross-blockchain application into an inconsistent state when a fork occurs. This can put at risk the purpose of the project: functional cross-blockchain applications. The same problem applies to, for instance, Overleder \cite{overledger03}. While one might be tempted to conclude that standardization could improve cross-blockchain API design, some argue that APIs are unlikely to generalize well across radically different technologies. Blockchain-agnostic protocols are more likely to be standardized than APIs, as shown historically by successful standards efforts such as HTTP or the TCP/IP family. Finally, solutions that prove cross-smart contract capabilities are emerging, but still in development \cite{scheid2019,Verdian2018,hyperservice,blockCollider,Abebe2019}. \section{Discussion, Use Cases and Research Questions} \label{sec:discussion_sec} This section presents a comprehensive summary of each blockchain interoperability category we extracted and our considerations about blockchain interoperability. Then it presents use cases and finishes with answers to the research questions we proposed. \subsection{Discussion} \label{sec:discussion} Although blockchain interoperability is a complex technology, connecting blockchains ends up being a manageable approach, despite differences in, for example, data structures, digital signature schemes, transmission protocols, verification mechanisms, consensus mechanisms, token issue mechanisms, and smart contract language. However, ``there is a scant effort today to address the standardization of the various infrastructure building blocks – messages, data formats, and flows – to support the interoperability across blockchains'' \cite{hardjono2021}. Different categories of solutions approach the interoperability problem differently. Our paper firstly introduced Public Connectors in Section \ref{sec_crypto} and stressed their importance. Token exchange is arguably no longer the whole scope of blockchain interoperability \cite{hyperservice}. Instead, various interoperability approaches emerged in the last years, whereby many of them aimed at generalizing blockchain interoperability. In particular, emerging solutions can be categorized as Hybrid Connectors, which provide cross-blockchain communication, and Blockchain of Blockchains, which allow an end-user to create customized, interoperable blockchains at the expense of vendor lock-in. Public connectors are the most cited among industry and academia, as they provide practical solutions to real-world problems: asset transfers. As these were the first solutions to emerge, not surprisingly, some may not succeed. It seems that the merge of sidechain and protocols relying on an escrow party (enforced by smart contracts) are the most suitable solutions for interoperability among public blockchains. We argue that the flexibility, decentralization, and security of such proposals can be utilized for secure interoperability. However, creating and maintaining a decentralized application using several blockchains was difficult - and hence the Blockchain of Blockchains solutions appeared. Those can facilitate blockchain adoption while providing built-in interoperability among instances of the same platform, whereas variations of the solutions mentioned above can be used to bridge Blockchain of Blockchains to other blockchains. While Blockchain of Blockchains, such as Cosmos or Polkadot provide a consensus engine and a security infrastructure to build blockchains, blockchain of blockchains aims at developing solutions using different infrastructures. In particular, Cosmos and Polkadot might progress towards \emph{homogenity}, as they support only the creation of Tendermint-based blockchains and Substrate-based blockchains, respectively. While they provide interoperability capabilities, mainly on the chains relying on their technology and other desirable features (shared layer of security, decentralization, governance, better scalability), the end-users choice will be tied to specific implementations. Paradoxically, such solutions might contribute to data and value silos, as solutions built with them cannot connect with an arbitrary blockchain \cite{Abebe2019}. Despite this fact, one could argue that this problem can be alleviated by building bridges/adapters. These solutions are promising but are challenging to integrate with legacy systems and, generally, private blockchains - and hence the hybrid connectors started appearing. Hybrid Connectors, specifically blockchain migrators and blockchain of blockchains, progress towards a user-centric, blockchain-agnostic view, enabling enterprise-connected CC-dApps. Arguably, the most suitable solution for connecting private blockchains is the usage of blockchain-agnostic protocols; however, they do not grant backward compatibility (as all previous solutions have to be adapted to integrate the adopted communication protocol). To overcome this fact, the short-medium-term solution would be using trusted relays. An interesting way for trusted relays to venture is by decentralizing the escrow party: from a set of trusted validators to a network of public nodes. It then follows from this survey that one could perceive trusted relays and blockchain-agnostic protocols to be good solutions to link private blockchains; and sidechain, smart-contract-based protocols suitable to solve interoperability among public blockchains. A network of blockchain engine-powered blockchains can be leveraged using Hybrid Connectors. For instance, there is a possible synergy between Cosmos and the Interledger Protocol: when a user wants to make an in-app payment with fiat currency (e.g., dollars) within a Cosmos zone, he or she can rely on the interledger protocol as a payment rail. If using cryptocurrencies to pay (e.g., Bitcoin), the interledger router can route the transactions for a payment channel (e.g., Lightning Network), providing more trustful interaction. To connect this ecosystem to private blockchains, bridges have to be developed. To make such bridges trustable, a possible solution would be to elect a group of validator nodes, via an overlay network, that participates in the consensus of public blockchains and private blockchains. This way, cross-chain, and cross-blockchain transactions can be endorsed. It is worth mentioning that several cross-chain programming languages are appearing, such as the Hyperservice Language \cite{Liu2019} and DAML \cite{daml}. DAML provides a unified Blockchain programming model by abstracting the underlying blockchains and exposing a higher-level abstract ledger on top, similarly to HSL. DAML has different integration degrees: DAML as an application on the target platform; and integration where the DAML runtime engine validates transactions. Programs compiled on such languages can run on top of a BoB platform. To conclude this discussion, we recall to the reader that blockchain development has been done in silos since its inception. New solutions for blockchain interoperability started emerging as of 2017, and, perhaps not surprisingly, such solutions are also being adopted in silos. While Public Connectors methods are commonly used nowadays, we focus on Blockchain of Blockchains and Hybrid Connectors. Blockchain of Blockchains and Hybrid Connectors allows interoperability between blockchains and other distributed ledger technologies and enterprise systems in the medium term. This promotes the development of blockchain interoperability standards. While blockchain matures, industries will tend to incorporate this technology into their business processes. Then, we predict that mass adoption will follow. \subsection{Supporting Technologies and Standards} \label{sec:technologies_standards} Besides the presented solutions, there is work towards the support and standardization of blockchain interoperability. Blockchain interoperability standards attempt to create a ``standardized transaction format and syntax'', which is common to all blockchains, and secondly, a ``standardized minimal operations set,'' common to all blockchains \cite{Hardjono2019}. In particular, a standardized format is important because while fungible and non-fungible assets have a single, well-defined representation in each blockchain, arbitrary data can be manipulated freely. First, we introduce indirect contributions that promote blockchain interoperability and then the existing standards. Recent efforts are visible in enabling heterogeneous smart contract integration through service-orientation \cite{falazi_scip}, allowing external consumer applications to invoke smart contract functions uniformly. A cross-blockchain data storage solution becomes a feasible solution to achieve application interoperability, whereby applications rely on one blockchain. Some dApps\footnote{https://ethlance.com/} already leverage the InterPlanetary File System (IPFS) \cite{Benet2014} to create a common storage, adjacent to the blockchain. The InterPlanetary File System provides a peer-to-peer network for storing and delivering arbitrary data in a distributed file system, potentially facilitating the transfer of data across blockchains \cite{belchior2021-bungee}. Organizations are working on standardizing digital assets. The Token Taxonomy Initiative\footnote{https://tokentaxonomy.org/} is a consortium dedicated to digital token standardization. It proposes a standard to identify tokens' behavior, properties, and control interfaces according to a token classification hierarchy. This project allows application developers to utilize a standard code set for interacting with tokens regardless of the blockchain platform, thus incentivizing blockchain interoperability. In the context of general interoperability, the Ethereum ERCs are a \emph{de facto} standard\footnote{https://eips.ethereum.org/erc}. Oracles are mechanisms that software systems provide an external source of truth for blockchains \cite{oracles2020}, and they can be centralized or decentralized \cite{Fan2018}. Typically, centralized oracles are not as dependable as decentralized oracles, as they constitute a single point of failure. Hyperledger Avalon \cite{hyperledger_avalon} defers intensive processing from the main blockchain to an off-chain channel to support centralized yet trustable oracles (by using trusted execution environments). Since multiple blockchains can use the same data, it fosters interoperability. Open source projects like Hyperledger Indy\footnote{https://www.hyperledger.org/projects/hyperledger-indy} and Hyperledger Aries\footnote{https://www.hyperledger.org/projects/hyperledger-aries} operate in the field of digital identity and self-sovereign identity. Central concepts of self-sovereign identity are decentralized identifiers (DIDs) \cite{did} and verifiable credentials \cite{vc2017}. Decentralized Identifiers can be created, managed, and shared using Zero-Knowledge Proofs (ZKPs) mechanism, even allowing to create new access control models \cite{ssibac}. Such technologies allow for identity portability, enabling cross-blockchain identities \cite{Hyland-Wood2018}. So far, the presented standards are called DLT/Blockchain Enabling Technology Standards because they focus on standardizing elements that blockchains can use, as opposed to DLT/Blockchain Generic Framework Standards \cite{lima2018}. These refer to standardization of blockchain interoperability data and metadata formats, identity, and protocols, namely the IETF, ISO, Enterprise Ethereum Alliance, IEEE, The EU Blockchain Observatory \& Forum, and W3C. At the Internet Engineering Task Force (IETF), work is being done defining a set of drafts that guide the implementation of ODAP, a protocol using gateways \cite{odap_draft_01,crp_draft_00,draft-hardjono-blockchain-interop-arch-01}. The ISO Technical Committee 307 works towards the ``standardization of blockchain and distributed ledger technologies''\footnote{https://www.iso.org/committee/6266604.html}, but did not produce any standard yet. Subgroup 7 (ISO/TC/SG7) focuses specifically on interoperability. The Enterprise Ethereum Client Specification, currently on its seventh version, ``defines the implementation requirements for Enterprise Ethereum clients, including the interfaces to external-facing components of Enterprise Ethereum and how they are intended to be used'', including cross-chain interoperability \cite{eeav7}. The IEEE Blockchain Initiative\footnote{https://blockchain.ieee.org/standards} and the IEEE Standards Association\footnote{https://standards.ieee.org/}, through the IEEE Standards P3203, P3204, and P3205 \footnote{https://blockchain.ieee.org/standards} work at providing ``interfaces and protocols of data authentication and communication for homogeneous and heterogeneous blockchain interoperability''. The EU Blockchain Observatory \& Forum by the European Commission aims to 1) the monitoring of blockchain activities in Europe, 2) the management of the source of blockchain knowledge, 3) the creation of a forum for sharing information, and 4) the creation of recommendations on the role the EU could play in blockchain \cite{eublock}. The same entity points out the likelihood of an increasing number of standards and adoption within governments \cite{eu_forum}. The W3C, via the Interledger Payments Community Group \footnote{https://www.w3.org/community/interledger/}, is connecting payment networks, including decentralized ledgers. Other organizations working in the area include BIA, BiTA, BRIBA, BSI, CESI, DCSA, EBP, GS1, and MOBI \cite{wef2020}. Standardization efforts focused on a specific blockchain (DLT/Blockchain Platform-Specific Standards) are, for example, the 0302 Aries Interop Profile \footnote{https://github.com/hyperledger/aries-rfcs/tree/master/concepts/0302-aries-interop-profile} and the Hyperledger Fabric Interoperability working group \footnote{https://wiki.hyperledger.org/display/fabric/Fabric+Interop+Working+Group}. Multiple standards will likely arise and be used, for each vertical industry, as there is a lack of generalized interoperability standards. Standards are then reused across industries (e.g., IEEE P2418.5). Solving interoperability in a specific sector would then pave the way for standards in other industries because the main requirement is domain expertise (ontologies are good starting points for standardization) \cite{lima2018}. The heterogeneity created by standards will pose a regulation challenge, as blockchains may spread across different jurisdictions \cite{hermes-middleware-2021}. \subsection{Use Cases with Multiple Blockchains} \label{sec:use_cases} In this Section, we present use cases with multiple blockchains. More use cases can be found in Appendix \ref{a:use_cases}. The industry is still applying blockchain to use cases using only one blockchain. Consequently, it is expected that use cases with multiple blockchains are rare. Notwithstanding, according to the existing resources, it seems that there is considerable interest in use cases using multiple blockchains. As long as the technologies mature, novel, disruptive use cases may be found. For the sake of space, we present some general use cases involving an IoB \cite{draft-sardon-blockchain-gateways-usecases-00}. We refer readers to Appendix F for more use cases relative to Public Connectors, Hybrid Connectors, and Blockchain of Blockchains. The first big IoB use case is asset transfers, where users can transfer assets from one blockchain to another. While some approaches implement this use case in an ad-hoc way, the emergence of central bank digital currencies (CBDCs) \cite{mbcb,oecd2021}, requires further efforts and standardization \cite{visa2020}. A CBDC is a digital version of a sovereign currency of a nation. A CBDC is issued by central banks, where each unit represents a claim on the value held by such central bank. Many blockchains features are appealing to implement CBDCs, particularly the offered immutability, transparency, and trust distribution. Some central banks are already experimenting with blockchain, including the Monetary Authority of Singapore and the Bank of Canada \cite{draft-sardon-blockchain-gateways-usecases-00}. As each CBDC can be implemented with a blockchain, and each central bank might choose a different technology, interoperability between them is achieved using an IoB or even a BoB. Another major use case is interoperability across supply chains \cite{draft-sardon-blockchain-gateways-usecases-00, hyperledger_cactus}. A supply chain is a chain of value transfer between parties, from the raw product (physical or intellectual) to its finalized version. Managing a supply chain is a complex process because it includes many non-trusting stakeholders (e.g., enterprises, regulators). As many markets are open and fluid, enterprises do not take the time to build trust - and instead, rely on a paper trail that logs the state of an object in the supply chain. This paper trail is needed for auditability and typically can be tampered with, leading to blockchain's suitability to address these problems \cite{wef2020}. A key challenge of blockchain-based supply chains is to interoperate with other DLT systems. Interoperability granted each participant of the supply chain (e.g., supplier, manufacturer, retailer) can participate at several supply chains (and thus several blockchains) using a single endpoint, simplifying the interaction process while reducing costs. Other use cases comprise connecting Hyperledger Fabric and Ethereum with Singapore Exchange and Monetary Authority of Singapore via node integration and EVRYTHNG, a product connecting multiple chains via API to digitize products \cite{wef2020}. Finally, identity and data portability can be provided by an IoB approach. Identity paradigms like self-sovereign identity \cite{ssibac} can increase identity portability by providing users control of their identities. Typically, this is achieved by rooting user credentials in a blockchain. Hence, if blockchains can communicate with identity providers that are blockchains, one can use the same identity in different blockchains. Data portability complies with blockchains, allowing blockchain users to use their data outside of a blockchain without requiring significant effort. \subsection{Answers to the Research Questions} \label{sec:res_q_a} In this section, we provide answers to the presented research questions (further elaborated on Section \ref{sec:res_q}). \begin{enumerate} \item \textbf{What is the current landscape concerning blockchain interoperability solutions, both from the industry and the academia? i.e., what is the current state of blockchain interoperability solutions?} The first step towards blockchain interoperability has been creating mechanisms allowing the exchange of tokens (e.g., cryptocurrencies). We categorized such solutions as Public Connectors (Section \ref{sec_crypto}). Such category comprises Sidechains and Relays (Section \ref{subsec:crypto_side}), Notary Schemes (Section \ref{sec:crypto_notaries}), and Hash Time Lock Contracts (Section \ref{subsec:crypto_hashed}). This category provides an idea of the emergence of blockchain interoperability - but this area no longer applies solely to token exchanges between homogeneous blockchains. Novel blockchain interoperability approaches are Blockchain of Blockchains (see Section \ref{sec:be}) and Hybrid Connectors (Section \ref{subsec:blockchain_connectors}). Hybrid Connectors fall into four sub-categories: trusted relays (Section \ref{sec:block_connector_trusted_relay}), blockchain-agnostic protocols (Section \ref{sec:block_connector_blockagnosticprotocol}), and blockchain migrators (Section \ref{sec:block_connector_bm}. We also analyzed related literature reviews on blockchain interoperability, in Section \ref{sec:related_literature_reviews}. \item \textbf{Is the set of technological requirements for blockchain interoperability currently satisfied?} There are two requirements for realizing technical interoperability \cite{vitalik2016}: a pair of sufficiently mature blockchains to build artifacts that promote interoperability and ``some application or need that cannot be served by implementing it on a single blockchain.'' There are several blockchains that can be considered mature enough to support applications built on top of them \cite{fabric, Gorenflo2019,Wood2017,Kwon2016}. On the other hand, interoperability regarding blockchain needs to have the necessary infrastructure and facilitating technologies. In particular, the production of standards \cite{Hyland-Wood2018,token_taxonomy_initiative} technologies like decentralized identifiers \cite{did}, verifiable credentials \cite{vc2017}, cross-blockchain communication protocols \cite{dextt,xclaim,sok_cdl}, and the representation of blockchain smart contracts \cite{Hyland-Wood2018} can foster the likelihood for blockchain interoperability standards and solutions, as they remove considerable barriers to blockchain interoperability. On the other hand, there is a set of cross-blockchain use cases that validate the need for interoperability, which will inevitably foster it \cite{hermes-middleware-2021}. In conclusion, the set of critical requirements for blockchain interoperability is currently satisfied, but there is still work to be done at standardization and interoperability across public-private and private-private blockchains. \item \textbf{Are there real use cases enabling a value chain coming from blockchain interoperability?} Regarding the third research question, some authors defend that blockchain interoperability is important and crucial for the survivability of this technology \cite{Hardjono2019,Pillai2019 hermes-middleware-2021,hyperservice}. Standards are paving the way for blockchain adoption \cite{Hyland-Wood2018, Deshpande2017}. It is likely that ``forward-looking interoperability standards are most likely to result in successful standards creation and facilitate industry growth'' \cite{Hyland-Wood2018}. Conversely, standardization is a requirement for mass adoption that is being developed. Given the multiple blockchain interoperability solutions, both Hybrid Connectors, and Blockchain of Blockchains, some of them with considerable weight on the industry, we believe this is a very likely scenario. In Section \ref{sec:use_cases}, we expose multiple use-cases that may benefit from cross-blockchain technology, which can foster adoption by enthusiasts and enterprises. In conclusion, we envision reliable solutions and standards emerging in the following years and a steady increase in blockchain adoption by enterprises and individuals alike. \end{enumerate} As a value enhancer and maturing key factor, interoperability will ultimately decide the survival of this technology. Based on the evidence collected and analyzed, we foresee increased attention to this research area, with blockchain interoperability gaining traction among the academia and the industry. \subsection{Open Issues and Challenges} \label{sec:issues} In this section, we present open issues and challenges regarding blockchain interoperability and, in a more general sense, the adoption of blockchain. Nowadays, solutions available to build decentralized applications lack interoperability, thwarting scalability \cite{tbig}. As Liu et al.~note, ``it is very challenging to enforce correct executions in a full trust-free manner where no trusted authority is allowed to coordinate the executions on different blockchains'' \cite{hyperservice}. Although interesting and notorious recent advances in this area make interoperability a reality, there is still a gap between theory and practice, as much of the existing work is mostly conceptual. Given the vast amount of blockchain platforms, fragmentation regarding solutions and their approach to interoperability is strongly present, for example, in IoT scenarios \cite{Zhu2019}. A combination of multiple platforms tailored for specific purposes, which can be public, private, or consortium, adds an overhead to manage workflows. In particular, this concern is intensified when multiple blockchains are serving a specific application. Concerning blockchain scalability, the internet of blockchains can be realized upon improvements to current performance, both in public and private blockchains. Techniques such as implicit consensus and data sharding can improve transaction throughput and storage \cite{omniledger}. However, blockchain sharding requires solving cross-blockchain transaction routing and retrieval and asset referencing (also known as the discoverability problem). It is challenging to coordinate transactions from different blockchains to support a cross-chain dApp, as different blockchains have different properties (e.g., architecture, protocols \cite{Abebe2019}, service discovery, access control, between others). In particular, reverting a transaction that depended on another can be cumbersome, especially given different transaction finalities from different blockchains). Some solutions have proposed a mechanism to overcome such a challenge (blockchain of blockchains) \cite{Verdian2018,hyperservice}. Although a promising approach, it is still unclear the applicability of these solutions to arbitrarily complex cross-blockchain dApp. More research is required to confirm the feasibility of this approach. Some authors \cite{vo2018} highlight problems related to the GDPR, such as security, trust, confidentiality, and data privacy issues. In particular, security threats are exacerbated by the presence of multiple blockchains and possible multiple administrators. Regarding privacy, the authors underline problems with the right-to-forget, in which a user can ask his or her data to be deleted from the blockchain. Currently, most blockchains do not provide effective mechanisms that can respond to this request. Blockchain fine-grain access control is appointed as a key requirement to minimize information leakage and confidentiality risk. Blockchain interoperability reduces dependencies on a single blockchain, and consequently, risk (e.g., the blockchain is attacked) \cite{dextt}, it does not eliminate the inherent risks. It is worth underscoring that the multiple blockchain approach is more complicated than the sum of its parts, as there is extra complexity underlying the cross-chain communication. This adds challenges to governance: whereas a private consortia can use Hybrid Connectors at will to interoperate systems (decentralized and/or decentralized), the governance model is not straightforward within community projects, supported by public blockchains. In short, the most relevant open issues towards blockchain interoperability are: \begin{itemize} \item The gap between theory and practice, including the lack of standardization and implementations \cite{hardjono2021,Zhu2019}, \item Discoverability \cite{Verdian2018,hyperservice, Abebe2019}, \item Privacy and Security \cite{Thomas2015,vo2018,Wood2017,sok_cdl}, \item Governance \cite{Hardjono2019, Hardjono2019a,wef2020,Qasse2019}. \end{itemize} Notwithstanding, security \cite{surv_sec, sok_crpyto}, privacy \cite{casino2019}, and scalability (e.g., using sharding \cite{surv_shar} or novel blockchain systems \cite{appendableblock}) remain the most prominent areas to be improved in the blockchain space. \section{Research Directions} \label{sec:research_directions} New tools, frameworks, standard proposals, and even programming models are emerging and need further development. Programming models such as Polkadot and Cosmos offer developers a way to create their blockchains effectively and connect them to other blockchains. Protocols such as ILP and UIP allow cross-blockchain transactions. Programming languages such as HSL and DAML aim at embedding different blockchain models, providing an abstraction for cross-blockchain dApps. Although one can have good reasons to utilize blockchain interoperability solutions for public or private blockchains, few solutions are available for connecting them. The problem of obtaining state from permissioned blockchains effectively \cite{abebe2020} makes interoperating with private blockchains a challenge \cite{wef2020,iiconsortium2020}. Thus, connecting public and private blockchains bidirectionally remains an open problem. One of the problems that bidirectional communication across permissioned and permissionless ledgers poses is semantic compatibility. Technical interoperability does provide the technical foundation that realizes interoperability but does not grant semantic interoperability per se \cite{Hardjono2019}. There is, therefore, a gap: how can we effectively combine both blockchain types to enable new use cases? How to make sure a solution complies with the goals of all involved stakeholders? Disciplines as view integration can help to provide an answer \cite{belchior2020_bpvi}. View integration is the process that combines views of the same business process into a consolidated one by combining the different views of the stakeholders participating in different blockchains. Another considerable obstacle for blockchain adoption is its fast-paced development. The development of blockchain interoperability standards may provide a way for more flexibility regarding backward compatibility. In the light of the present study and the identified open issues and challenges, we propose research directions based on some sections of our survey: research on architecture for enabling blockchain interoperability, Public Connectors, Blockchain of Blockchains, Hybrid Connectors, and supporting technologies, standards, use cases, and others. \emph{Architecture for Blockchain Interoperability} (Section \ref{a:architecture}): \begin{itemize} \item Define a blockchain interoperability maturity model, modeling interoperability at its various layers (e.g., technological, semantic, organizational). \item Model the different views on the various types of interoperability, according to different stakeholders (e.g., the provider's technical view on a cross-blockchain dApp \emph{versus} the semantic view of the end-user on the same cross-blockchain dApp). \item Study blockchain interoperability semantics by exploring, for example, the research area of view integration \cite{view_int}. \end{itemize} Public Connectors (Section \ref{sec_crypto}): \begin{itemize} \item Research on how permissioned blockchains can benefit from sidechains to improve scalability and privacy. \item Develop protocols to allow fiat money exchange, higher liquidity on decentralized exchanges. Conversely, improve the level of privacy and security of centralized exchanges. \end{itemize} Blockchain of Blockchains (Section \ref{sec:be}): \begin{itemize} \item Integration of existing blockchain systems with Blockchain of Blockchains. \item Study how Blockchain of Blockchains can provide a reliable interoperability scheme bridging permissioned blockchains and permissionless blockchains. \item Connect Blockchain of Blockchains to both centralized systems and decentralized ledger systems (e.g., connect Polkadot to Visa). \end{itemize} Hybrid Connectors (Section \ref{subsec:blockchain_connectors}): \begin{itemize} \item Decentralize the trust of trusted relays by integrating them with public blockchains (e.g., by submitting the state periodically to a public blockchain); \item Study how blockchain-agnostic protocols can be easily adapted to existing ledgers. \item Explore the blockchain of blockchains approach as an advance in dependable blockchain-based applications. \item Improve atomicity and consistency guarantees on cross-blockchain decentralized applications. \item Explore blockchain migration across public and permissioned ledgers. Such migration schemes can be decentralized and adapt to functional and non-functional requirements imposed by stakeholders. \item Explore blockchain migration via non-trusted relays (e.g., using a set of public escrow nodes following a protocol). \item Develop frameworks for multiple blockchain management. Such frameworks should respond to multiple stakeholder needs, decentralizing trust. \item Model integration abstraction layers that enable the development of universally connected contracts. \item Research on the visualization of CC-Txs. \end{itemize} Supporting technologies and standards, use cases, and others (Section \ref{sec:discussion}): \begin{itemize} \item Work along with regulators and standardizing bodies to come with blockchain interoperability standards across industries \item Research on blockchain interoperability programming languages, supporting tools, and standards, including but not limited to cross-blockchain programming languages and frameworks, decentralized identifiers and verifiable credentials, and blockchain interoperability standards for enterprise blockchains; \item Explore new use cases using multiple blockchains, the ``value-level'' interoperability \cite{hyperledger_cactus}. \item Research synergies between cryptocurrency-based interoperability approaches, Blockchain of Blockchains, and Hybrid Connectors. \item Study security aspects of blockchain interoperability. \item Understand the implications of the different interoperability layers (value, semantic, organizational, among others). \end{itemize} \section{Conclusion} \label{sec:concl} In this paper, we performed a systematic literature review on blockchain interoperability. We systematically analyzed, compared, and discussed 80 documents, corresponding to 45 blockchain interoperability solutions. By including grey literature, we expect to thwart intrinsic limitations regarding the blockchain interoperability research area, such as a considerable presence of the industry. By exploring each solution methodologically, this study provides interesting insights, distributed across three categories: Public Connectors, Blockchain of Blockchains, and Hybrid Connectors. Despite sidechain and HLTC solutions are gaining traction in the industry, blockchain interoperability are not solely Public Connectors solutions. New approaches started emerging since 2017. Hybrid Connectors provide a varied landscape of solutions, adapted for the majority of the use cases. They are likely to be used to produce cross-blockchain dApps. Blockchain of Blockchains are likely to be adopted by the industry in the short-medium term, by leveraging easy-to-produce, customizable blockchains. Our findings allow us to conclude that conditions to research on blockchain interoperability are fulfilled, allowing a multitude of new use cases. Thus, we expect interest in this research area to raise considerably. This work is towards making the blockchain ecosystem more practical, by easing work for developers and researchers. We expect that this study provides a robust and dependable starting point whereby developers and researchers can work in the blockchain interoperability research area \begin{acks} The authors would like to thank to the anonymous reviewers that constructively provided suggestions that significantly improved this paper. Thanks to Peter Somogyvari, Paul DiMarzio, Jag Sidhu, Sergio Lerner, Andy Leung, Travis Walker, Bill Laboon, Josh Lee, Austin King, Oliver Birch, Thomas Hardjono, and Miguel Matos for fruitful discussions regarding blockchain interoperability. We thank Daniel Hardman and Ken Elbert for constructive discussions about DIDs and verifiable credentials. Special thanks go to Iulia Mihaiu, Cláudio Correia, Benedikt Putz, Francisco Braga, Gavin Wood, João Ferreira, Miguel Pardal, Jonas Gehrlein, and Dilum Bandara for constructive comments and suggestions that greatly contributed to improving the paper. The authors express their gratitude to the Linux Foundation for providing the Diversity \& Inclusion scholarship. This work was partially supported by the EC through project 822404 (QualiChain), and by national funds through Fundação para a Ciência e a Tecnologia (FCT) with reference UIDB/50021/2020 (INESC-ID). \end{acks} \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2021-03-23T01:34:37', 'yymm': '2005', 'arxiv_id': '2005.14282', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14282'}
arxiv
\section{Introduction} Tensors, as a generalization of vectors and matrices, arise in many data processing applications and have attracted great interests. For instance, video inpainting \cite{tensor_video}, magnetic resonance imaging (MRI) data recovery \cite{tensor_MRI, MRI_tensor}, 3D image reconstruction \cite{tensor_3dimage, tensor_3DReconstruction}, high-order web link analysis [16], hyperspectral image (HSI) or multispectral image recovery \cite{tensor_HSI, chen2018tensor}, personalized web search \cite{tensor_web}, and seismic data reconstruction \cite{tensor_seismic_data}. Tensor completion tries to recover a low-rank tensor from its partially observed entries. A large number of tensor completion methods have been proposed and successfully used in many applications. Among them, the tensor rank minimization based methods are considered as state-of-the-art methods with promising performance, and their robustness to noisy and missing data has also been proven \cite{lu2019TRPCA}. However, due to the nonunique definitions of the tensor rank, it is extremely hard to directly solve the tensor rank minimization problem. To overcome this issue, many researchers have been devoted to defining the tensor rank based on the different decomposition methods, such as the matrix factorization \cite{LMaFit}, CANDECOMP/PARAFAC (CP) decomposition \cite{CP}, Tucker decomposition \cite{tucker_1, ZENG_HSI_tensor}, tensor singular value decomposition (t-SVD) \cite{t_SVD}, tensor train \cite{tensor_train_TingzhuHuang} and tensor ring \cite{tensor_ring_YipengLiu}. The commonly used definitions of tensor rank are CP-rank, Tucker-rank, multi-rank and tubal-rank based on t-SVD. However, it is NP-hard to solve the minimization problem of CP-rank which has no relaxation and certain limitations in applications. Although the Tucker-rank, relying on matrix ranks, is relatively simple, it is also NP-hard to directly minimizing the Tucker-rank problem. To tackle this difficulty, the sum of nuclear norm (SNN) \cite{HaLRTC} is introduced as a convex relaxation of the Tucker-rank. Specifically, SNN is defined by the sum of nuclear norms of the unfolding matrices along all dimensions in tensors. Due to the similar approximation to matrix case and convenient calculation algorithm, SNN is widely used in the tensor completion task \cite{tensor_Qrank}. Besides, the tensor multi-rank and tubal-rank induced from t-SVD are computable. As a tightest convex surrogate for tensor multi-rank, the tensor nuclear norm (TNN) \cite{t_SVD} is defined as the sum of the matrix nuclear norms of each frontal slice in the Fourier transformed tensor. TNN has shown its effectiveness to keep the intrinsic structure of tensors and attracted extensive attention for tensor completion problems in recent years \cite{lu2019TRPCA}. Due to the convexity of matrix nuclear norms, SNN and TNN have limitation in the accuracy of approximation to the tensor rank function. Recently, a number of studies \cite{list_nonconvex,Original_BFMN}, both practically and theoretically, have shown that the nonconvex approximation of rank function can provide better estimation accuracy and variable selection consistency than the nuclear norm. For example, a partial sum of the tensor nuclear norm (PSTNN) is proposed as a nonconvex surrogate of the tensor rank by Jiang et al. \cite{PSTNN}; Xue et al. \cite{xue2019nonconvex} unfold the underlying tensor along its all modes and use a nonconvex logarithmic surrogate function to refine the rank approximation. Actually, except for the logarithmic function used by Xue et al., a series of nonconvex surrogate are proposed for approximating to the rank function better, such as the minimax concave function \cite{Folded_concave}, log-sum function \cite{logsum_penalty}, log-determinant function \cite{ji_nonlogDet}, $L_p$ norm for $p\in (0, 1)$ \cite{lysaker_noise_2004_10_27,burger_nonlinear_2006_10_28}, $L_{1/2}$ norm \cite{lou_L1L2} and $\gamma$ norm \cite{Non_LRMA}. In addition, TNN and PSTNN involve the singular value decompositions (SVDs) of many matrices, which are time-consuming. To cope with this issue, Xu et al. \cite{Tmac} propose a parallel matrix factorization low-rank tensor completion model (TMac), which obtain promising results with less running time than TNN and PSTNN. Further, combined with the total variation (TV) regularization, Ji et al. \cite{MFTV} propose TV regularized low-rank matrix factorization method (MF-TV) for low-rank tensor completion problems. \begin{figure*}[!t] \centering \subfloat[Original image]{\includegraphics[width=0.23\linewidth]{Image_video_b94.png} \hfil \subfloat[Our model]{\includegraphics[width=0.23\linewidth]{Image_video_b94_sr005LxLxNN}}% \hfil \subfloat[TMac]{\includegraphics[width=0.23\linewidth]{Image_video_b94_sr005Tmac}}% \hfil \subfloat[TNN]{\includegraphics[width=0.23\linewidth]{Image_video_b94_sr005TNN} \caption{The completed results of Suzie with 95\% missing entries by different methods. From (a) to (d), the original image, the result by our model, Tmac, and TNN, respectively.} \label{TNN_Tamc_our-model_figure_video_sr0.05} \end{figure*} Although the above-mentioned low-rank tensor completion methods show great success in dealing with various issues, three major open questions have yet to be addressed. Firstly, in the tensor rank approximations based on tensor decomposition or matrix decomposition, the low-rank priors of underlying tensor are only explored by the convex or nonconvex relaxations of original tensor rank function, while the low-rank priors of factors obtained by the decomposition are not investigated further. Secondly, TNN or PSTNN based methods \cite{TNN, PSTNN} need to compute lots of SVDs, which become very slow or even not applicable for large-scale problems \cite{Tmac}. Thirdly, the aforementioned methods adopt single surrogate of tensor rank function, which would cause suboptimal solution of the low-rank tensor completion problems \cite{T_Sp} and can not fully explore the low-rank priors in all modes, especially when the tensor data is heavily contaminated or the sampling rate is very low. One can see an example in Fig. \ref{TNN_Tamc_our-model_figure_video_sr0.05}. In this paper, motivated and convinced by the much better performance of models that utilize the low-ranknesses in all mode in tensors \cite{HaLRTC, Tmac}, instead of using the single surrogate of tensor rank function to represent the low-rank prior in underlying tensor directly, we first apply parallel matrix factorization to all modes of underlying tensor. Further, the novel double $L_{\gamma}$ norm, a kind of nonconvex penalty, is designed to represent the underlying joint-manifold drawn from the mode factorization factors. By exploiting this auxiliary information, our method leverages low-rank decomposition and low-rank approximation, which help to accurately estimate the mode factors and missing entries. An block successive upper-bound minimization method-based algorithm is designed to efficiently solve the proposed model, and it can be demonstrated that our numerical scheme converge to the coordinatewise minimizers. The proposed model has been evaluated on three types of public tensor datasets, which show that our algorithm can recover a variety of low-rank tensors with significantly fewer samples than the compared methods. The rest of this paper is organized as follows. Section \ref{notation} introduces some notations about tensors and the operations. Section \ref{related works} reviews the related works. In Section \ref{the proposed model}, the proposed model is presented and its optimization is deduced in detail. In Section \ref{Numerical experiments}, the proposed model is evaluated on several public tensor datasets. Section \ref{conclusion} gives the conclusions. \section{Preliminary} \label{notation} \subsection{Notations} In this paper, following \cite{Tmac}, vector, matrix and tensor are denoted as bold lower-case letter $\mathbf{x}$, bold upper-case letter $\mathbf{X}$ and caligraphic letter $\mathcal{X}$, respectively. Let $x_{i_{1} \ldots i_{N}}$ represent the $\left(i_{1}, \ldots, i_{N}\right)$-th component of an $N$-way tensor $\mathcal{X}$. Then, for $\mathcal{X}, \mathcal{Y} \in \mathbb{R}^{I_{1} \times \ldots \times I_{N}},$ their inner product is defined as \begin{equation} \label{equation:inner_product} \langle\mathcal{X}, \mathcal{Y}\rangle=\sum_{i_{1}=1}^{I_{1}} \cdots \sum_{i_{N}=1}^{I_{N}} x_{i_{1} \cdots i_{N}} y_{i_{1} \cdots i_{N}}. \end{equation} Based on (\ref{equation:inner_product}), the \textbf{Frobenius norm} of a tensor $\mathcal{X}$ is defined as $\|\mathcal{X}\|_{\text{F}}=\sqrt{\langle\mathcal{X}, \mathcal{X}\rangle}$. \textbf{Fibers} of tensor $\mathcal{X}$ are defined as a vector obtained by fixing all indices of $\mathcal{X}$ except one, and \textbf{slices} of $\mathcal{X}$ are defined as a matrix by fixing all indices of $\mathcal{X}$ except two. The \textbf{mode-$n$ matricization}/\textbf{unfolding} of $\mathcal{X} \in \mathbb{R}^{I_{1} \times \ldots \times I_{N}}$ is denoted as a matrix $\mathbf{X}_{(n)} \in \mathbb{R}^{I_{n} \times \Pi_{j \neq n} I_{j}}$ with columns being the mode-$n$ fibers of $\mathcal{X}$ in the lexicographical order. Furthermore, to clearly represent the matricization process, we define \textbf{unfold}$_{n}(\mathcal{X})=\mathbf{X}_{(n)}$, and \textbf{fold}$_{n}$ is the inverse of \textbf{unfold}$_{n}$, i.e., \textbf{fold} $_{n}\left(\text { \textbf{unfold} }_{n}(\mathcal{X})\right)=\mathcal{X}$. The $n$-rank of an $N$-way tensor $\mathcal{X},$ denoted as $\operatorname{rank}_{n}(\mathcal{X}),$ is the rank of $\mathbf{X}_{(n)},$ and the rank of $\mathcal{X}$ is defined as an array: \begin{equation} \operatorname{rank}(\mathcal{X})=\left(\operatorname{rank}\left(\mathbf{X}_{(1)}\right), \cdots, \operatorname{rank}\left(\mathbf{X}_{(N)}\right)\right). \end{equation} \subsection{Operators} \label{operators} The \textbf{Proximal Operator} of is defined as follows: \begin{equation} \label{equation:PPA_0} \operatorname{prox}_{f}(v):=\arg \min _{u} f(u)+\frac{\rho}{2}\|u-v\|^{2}, \end{equation} where $f(u)$ is convex; $\rho$ is the proximal parameter. Then, the minimization of $\{f(u)\}$ is equivalent to \begin{equation} \arg \min _{u} f(u)+\frac{\rho}{2}\|u-u^k\|^{2}, k=1,2,\cdots, \end{equation} where $u^k$ is the last update of $u$. We define the \textbf{Projection Operator} as follows: \begin{equation} \left(\mathcal{P}_{\Omega}(\mathcal{Y})\right)_{i_{1} \cdots i_{N}}=\left\{\begin{array}{ll} {y_{i_{1}, \cdots, i_N,}} & {\left(i_{1}, \cdots, i_{N}\right) \in \Omega} \\ {0,} & {\text { otherwise }} \end{array}\right. \end{equation} where $\Omega$ is the index set of observed entries. The function of $\mathcal{P}_{\Omega}$ is to keep the entries in $\Omega$ and zeros out others. \section{Related Works} \label{related works} We first introduce related tensor completing methods based on the tensor rank minimization. Given a partial observed tensor $\mathcal{F} = \mathcal{P}_{\Omega}(\mathcal{Y}) \in \mathbb{R}^{I_{1} \times I_{2} \times \cdots \times I_{N}}$, tensor completion task is to recover a low-rank tensor $\mathcal{Y}$ from $\mathcal{F}$, according to the priors of underlying tensor $\mathcal{Y}$. In the past decade, TNN induced by t-SVD \cite{t_SVD} has been widely used for 3-order low-rank tensor completion \cite{TNN}. The TNN based method aims to recover a low-rank tensor by penalizing the nuclear norm of each front slice in the Fourier transformed domain, \begin{equation} \label{TNN} \arg\min_{\mathcal{Y}} \frac{1}{I_{3}} \sum_{i=1}^{I_{3}}\left\|\bar{\mathbf{Y}}^{(i)}\right\|_{*} , s.t.~ \mathcal{P}_{\Omega}(\mathcal{Y})=\mathcal{F}, \end{equation} where $\bar{\mathbf{Y}}^{(i)} \in \mathbb{C}^{I_{1} \times I_{2}}$ denotes the $i$-th frontal slice of $\bar{\mathcal{Y}}$, $\bar{\mathcal{Y}}=\operatorname{fft}(\mathcal{Y},[],3)$ denotes the fast Fourier transform of $\mathcal{Y}$ along the third dimension. \begin{figure*} \centering \includegraphics[width=1\linewidth]{3-model-lowrank-Lx-norm} \caption{Flowchart of the proposed low-rank tensor approximation: nonconvex tensor $L_{\gamma}$ norm.} \label{fig:3-model-lowrank-lx-norm} \end{figure*} Then, to alleviate bias phenomenons of the TNN minimization in tensor completion tasks, Jiang et al. \cite{PSTNN} represent the low-rank prior of underlying tensor by using the PSTNN. The PSTNN regularized tensor completion model is formulated as follows: \begin{equation} \label{PSTNN} \arg\min_{\mathcal{Y}} \frac{1}{I_{3}} \sum_{i=1}^{I_{3}}\left\|\bar{\mathbf{Y}}^{(i)}\right\|_{p=M}, s.t.~ \mathcal{P}_{\Omega}(\mathcal{Y})=\mathcal{F}, \end{equation} where $$\|\bar{\mathbf{Y}}^{(i)}\|_{p=M} := \sum_{j=M+1}^{\min (I_1, I_2)} \sigma_{j}(\bar{\mathbf{Y}}^{(i)}),$$ and $\sigma_{j}(\bar{\mathbf{Y}}^{(i)})$ denotes the $j$-th largest singular value of $\bar{\mathbf{Y}}^{(i)}$. To reduce the burden of calculating SVDs in TNN and PSTNN, Liu et al. \cite{HaLRTC} unfold the $N$-order tensor into multiple modal matrices along the direction of each mode, and then use the sum of the nuclear norms of these modal matrices, i.e., SNN, to describe the low-rank structure of the underlying tensor. With that definition, the completion model is formulated as follows: \begin{equation} \label{} \arg\min_{\mathcal{Y}} \sum_{n=1}^{N} \alpha_i \left\|\mathbf{Y}_{(n)}\right\|_{*}, s.t., \mathcal{P}_{\Omega}(\mathcal{Y})=\mathcal{F}. \end{equation} Furthermore, Xu et al. \cite{Tmac} propose a Tmac model by using parallel matrix factorization, which obtain promising results with less computational complexity than TNN and PSTNN, \begin{equation} \label{Tmac} \begin{aligned} &\arg\min _{\mathcal{Y}, \mathbf{X}, \mathbf{A}} \sum_{n=1}^{N} \frac{\alpha_{n}}{2}\left\|\mathbf{Y}_{(n)}-\mathbf{A}_{n} \mathbf{X}_{n}\right\|_{F}^{2},\\ &\text { s.t. } \quad \mathcal{P}_{\Omega}(\mathcal{Y})=\mathcal{F}, \end{aligned} \end{equation} where $\alpha_n$ are weights and satisfy $\sum_{n=1}^{N}\alpha_n=1$. Although the above-mentioned low-rank tensor completion methods report success on dealing with a large variety of tasks, there are several open issues which have yet to be addressed. Firstly, the above approaches either explore the low-rank prior lying in only one mode of the underlying tensor or directly represent the low-rank prior of original tensor by using low-rank decomposition. They do not further explore the prior of the factors (e.g., $\mathbf{A}_n, \mathbf{X}_n$ in (\ref{Tmac})) obtained by low-rank decomposition. Secondly, TNN based methods \cite{TNN, PSTNN, lu2019TRPCA} need to compute lots of SVDs, which is time-consuming or even not applicable for large-scale problems \cite{Tmac}. Thirdly, these methods adopt single surrogate of tensor rank function, which would cause suboptimal solution of the low-rank tensor completion problems \cite{T_Sp} and can not fully explore the low-rank priors in all modes, especially when the tensor data is heavily contaminated or the sampling rate is very low. One can see an example in Fig. \ref{TNN_Tamc_our-model_figure_video_sr0.05}, in which the video "suzie" with 95\% missing entries, it can be seen that our model restores most of the structural information of the video, while the videos restored by the methods adopt single surrogate contain only the outline of the images. \section{Double nonconvex $L_{\gamma}$ norm based low-rank approximation for tensor completion } \label{the proposed model} In the following, a novel double nonconvex $L_{\gamma}$ norm based low-rank approximation of tensor multi-modes (LRATM) is introduced firstly. Then, the optimization of the proposed LRATM model is deduced in detail. \subsection{LRATM Model} For a tensor $\mathcal{Y}\in \mathbb{R}^{I_{1} \times I_{2} \times \cdots \times I_{N}}$, to enhance the flexibility for handling different correlations along different modes in the underlying tensor, while to effectively explore the underlying joint-manifold drawn from the mode factorization factors, we first formulate a nonconvex novel tensor $L_{\gamma}$ norm, \begin{equation} \begin{aligned} &\left\|\mathcal{Y}\right\|_{\gamma}= \sum_{n=1}^{N} (\tau_n \left\|\mathbf{X}_{n}\right\|_{\gamma}+\lambda_n \left\|\mathbf{A}_{n}\right\|_{\gamma}), \end{aligned} \end{equation} where $\mathbf{Y}_{(n)}=\mathbf{A}_{n} \mathbf{X}_{n}$, and $$\left\|\mathbf{X}\right\|_{\gamma}:=\sum_{t=1}^{\min \{p, q\}}\left(1-e^{-\sigma_{t}(\mathbf{X}) / \gamma}\right)$$ is a nonconvex approximation of $rank(\mathbf{X})$, and $\sigma_{t}(\mathbf{X})$ is the $t$-th biggest singular value of $\mathbf{X} \in \mathbb{R}^{p \times q}$. $\tau_n$ and $\lambda_n$ are non-negative constants that balance the two terms. Then, our tensor $L_{\gamma}$ norm based low-rank approximation model for low-rank tensor completion, i.e., the proposed LRATM model is written as \begin{equation} \label{BMF_LRTC} \begin{aligned} \arg\min{\left\|\mathcal{Y}\right\|_{\gamma}}=&\arg\min_{\mathcal{Y},\mathbf{X},\mathbf{A}} \sum_{n=1}^{N} (\tau_n \left\|\mathbf{X}_{n}\right\|_{\gamma}+\lambda_n \left\|\mathbf{A}_{n}\right\|_{\gamma}), \\ &s.t., ~ \mathbf{Y}_{(n)}=\mathbf{A}_{n} \mathbf{X}_{n}, \mathcal{P}_{\Omega}(\mathcal{Y})=\mathcal{F}. \end{aligned} \end{equation} To better understand the proposed LRATM model, we plot the flowchart of the proposed low-rank tensor approximation in Fig. \ref{fig:3-model-lowrank-lx-norm}. It can be seen that the video, MRI and HSI in the first column essentially can be viewed as 3-order tensors in the second column. When we unfold the 3-order tensor in three directions, the low-rank structure of all the $N$ modes can be explored by using parallel matrix decomposition, i.e., $\mathbf{Y}_{(n)}=\mathbf{A}_{n} \mathbf{X}_{n}, n=1,2,\cdots, N$, which is computationally much cheaper than SVD. The decomposed factors have practical physical meaning, $\mathbf{A}_n$ represents a library (each column contains a signature of the $n$-th mode direction), and $\mathbf{X}_n$ is called an encoding. For example, in the unmixing problem for HSI \cite{HSI_unmixing}, each column of $\mathbf{A}_3$ contains a spectral signature, and each row of $\mathbf{X}_3$ contains the fractional abundances of a given endmembers. This interpretation is also valid for the mode-3 unfolding of video and MRI. The above parallel matrix decomposition can effectively explore the low-rank structure of underlying tensor, but the prior information contained in the factor matrices ($\mathbf{A}_{n}, \mathbf{X}_{n}$) is not explored at all. Therefore, to further enhance the potential capacity of tensor completion models, it is necessary to design new and reasonable formulas to explore the priors in the factor matrices. Here, we propose the novel nonconvex double $L_{\gamma}$ norm to formulate the underlying joint-manifold drawn from the mode factorization factors $\mathbf{A}_n$ and $\mathbf{X}_n$. The superiority of $L_{\gamma}$ norm over nuclear norm and other nonconvex penalties is shown in the fifth column of Fig. \ref{fig:3-model-lowrank-lx-norm}. It is obvious that the red curve of $L_{\gamma}$ norm is closer to the green curve of $L_0$ norm (rank function) than other nonconvex penalties. \subsection{Optimization Procedure of LRATM} In this section, the proposed model is solved by using the block successive upper-bound minimization (BSUM) \cite{BSUM} method. The objective function of the proposed LRATM model(\ref{BMF_LRTC}) can be formulated as follows: \begin{equation} \begin{aligned} f(\mathbf{X}, \mathbf{A}, \mathcal{Y})=\sum_{n=1}^{N}& \left(\frac{\alpha_{n}}{2}\left\|\mathbf{Y}_{(n)}-\mathbf{A}_{n} \mathbf{X}_{n}\right\|_{\text{F}}^{2}+\tau_n \left\|\mathbf{X}_{n}\right\|_{\gamma}\right.\\ &\left.+\lambda_n \left\|\mathbf{A}_{n}\right\|_{\gamma}\right). \end{aligned} \end{equation} According to the proximal operator (\ref{equation:PPA_0}), the update can be written as: \begin{equation} \label{equation_original_PPA} p(\mathcal{S}, \mathcal{S}^k)=f\left(\mathcal{S}, \mathcal{S}^k\right)+\frac{\rho}{2}\left\|\mathcal{S}-\mathcal{S}^{k}\right\|_{\text{F}}^{2}, \end{equation} where $\rho>0$ is a positive constant; $\mathcal{S}=(\mathbf{X}, \mathbf{A}, \mathcal{Y})$ and $\mathcal{S}^{k}=\left(\mathbf{X}^{k}, \mathbf{A}^{k}, \mathcal{Y}^{k}\right)$. Let \begin{equation} \left\{\begin{array}{l} g_{1}\left(\mathbf{X}, \mathcal{S}_{1}^{k}\right)=f\left(\mathbf{X}, \mathbf{A}^{k}, \mathcal{Y}^{k}\right)+\frac{\rho}{2}\left\|\mathbf{X}-\mathbf{X}^{k}\right\|_{\text{F}}^{2}, \\ g_{2}\left(\mathbf{A}, \mathcal{S}_{2}^{k}\right)=f\left(\mathbf{X}^{k+1}, \mathbf{A}, \mathcal{Y}^{k}\right)+\frac{\rho}{2}\left\|\mathbf{A}-\mathbf{A}^{k}\right\|_{\text{F}}^{2,} \\ g_{3}\left(\mathcal{Y}, \mathcal{S}_{3}^{k}\right)=f\left(\mathbf{X}^{k+1}, \mathbf{A}^{k+1}, \mathcal{Y}\right)+\frac{\rho}{2}\left\|\mathcal{Y}-\mathcal{Y}^{k}\right\|_{\text{F}}^{2}, \end{array}\right. \end{equation} where \begin{equation} \left\{\begin{array}{l} S_{1}^{k}=\left(\mathbf{X}^{k}, \mathbf{A}^{k}, \mathcal{Y}^{k}\right),\\ S_{2}^{k}=\left(\mathbf{X}^{k+1}, \mathbf{A}^{k}, \mathcal{Y}^{k}\right),\\ S_{3}^{k}=\left(\mathbf{X}^{k+1}, \mathbf{A}^{k+1}, \mathcal{Y}^{k}\right). \end{array}\right. \end{equation} Then, problem (\ref{equation_original_PPA}) can be rewritten as follows: \begin{equation} \label{equation:XAY} \left\{\begin{array}{l} \displaystyle \mathbf{X}^{k+1}=\arg\min_{\mathbf{X}} g_{1}\left(\mathbf{X}, \mathcal{S}_{1}^{k}\right), \\ \displaystyle \mathbf{A}^{k+1}=\arg\min_{\mathbf{A}} g_{2}\left(\mathbf{A}, \mathcal{S}_{2}^{k}\right), \\ \displaystyle \mathcal{Y}^{k+1}=\arg\min_{\mathcal{P}_{\Omega}(\mathcal{Y})=\mathcal{F}} g_{3}\left(\mathcal{Y}, \mathcal{S}_{3}^{k}\right). \end{array}\right. \end{equation} \subsubsection{Update $\mathbf{X}_n$} With fixing other variables, the optimization subproblem with respect to $\mathbf{X}_n, n=1,2,\cdots,N$, in (\ref{equation:XAY}) can be written as follows: \begin{equation} \label{equation_X} \begin{aligned} \arg\min_{\{\mathbf{X}_n\}_{n=1}^{N}} \sum_{n=1}^{N}& \left(\frac{\alpha_{n}}{2}\left\|\mathbf{Y}_{(n)}-\mathbf{A}_{n} \mathbf{X}_{n}\right\|_{\text{F}}^{2}+\tau_n \left\|\mathbf{X}_{n}\right\|_{\gamma}\right.\\ &\left.+\frac{\rho_n}{2}\left\|\mathbf{X}_n-\mathbf{X}_n^{k}\right\|_{\text{F}}^{2}\right). \end{aligned} \end{equation} To efficiently solve the above optimization, we first introduce auxiliary variables $\mathbf{X}_{n}=\mathbf{Z}_{n}, n=1,2,\cdots,N$. Then, by the augmented Lagrangian multiplier (ALM) method, the optimization subproblem (\ref{equation_X}) can be rewritten as: \begin{equation} \label{equation:X_alm} \begin{aligned} &\arg\min_{\{\mathbf{X}_n, \{\mathbf{Z}_n\}_{n=1}^{N}} \sum_{n=1}^{N} \left(\frac{\alpha_{n}}{2}\left\|\mathbf{Y}_{(n)}-\mathbf{A}_{n} \mathbf{X}_{n}\right\|_{\text{F}}^{2}+\tau_n \left\|\mathbf{Z}_{n}\right\|_{\gamma}\right.\\ &\left.+\frac{\rho_n}{2}\left\|\mathbf{X}_n-\mathbf{X}_n^{k}\right\|_{\text{F}}^{2}+\left\langle\Gamma_{n}^\mathbf{X}, \mathbf{X}_n-\mathbf{Z}_n\right\rangle +\frac{\rho_{n}}{2}\left\|\mathbf{X}_{n}-\mathbf{Z}_{n}\right\|_{\text{F}}^{2}\right). \end{aligned} \end{equation} where $\Gamma_{n}^\mathbf{X}$ are Lagrangian multipliers. With other variables fixed, the minimization subproblem for $\mathbf{Z}_n$ can be deduced from (\ref{equation:X_alm}) as follows: \begin{equation} \label{equation:Zn} \mathbf{Z}_n^{k+1}= \arg \min_{\mathbf{Z}_n} \left\|\mathbf{Z}_{n}\right\|_{\gamma}+\frac{\hat{\rho}_{n}}{2}\left\|\mathbf{Z}_{n}-\mathbf{P}_n^k\right\|_{\text{F}}^{2}, \end{equation} where $\hat{\rho}_{n}=\rho_{n}/\tau_n$, $\mathbf{P}_n^k=\mathbf{X}_{n}^{k}+\Gamma_{n}^{\mathbf{X}}/\rho_n$. Let $\sigma_{1}^{k} \geq \sigma_{2}^{k} \geq \cdots \geq \sigma_{t_n}^{k}$ represent the singular values of $\mathbf{Z}_n^{k} \in \mathbb{R}^{r_n \times s_n}$ with $t_n=\min \left\{r_n, s_n\right\}$ and $\nabla \phi\left(\sigma_{n}^{k}\right)$ denote the gradient of $\phi(x) = 1-e^{-x/\gamma}$ at $\sigma_{n}^{k} .$ Let $$f(\mathbf{Z}_n)=\frac{1}{2}\left\|\mathbf{Z}_n-\mathbf{P}_n^k\right\|_{\text{F}}^{2}.$$ It is easy to prove that the gradient of $f(\mathbf{Z}_n)$ is Lipschitz continuous by setting the Lipschitz constant being $1.$ As stated in \cite{Non_LRMA}, considering the nonascending order of singular values and according to the antimonotone property of gradient of our nonconvex function, we have \begin{equation} \begin{aligned} & 0 \leq \nabla \phi\left(\sigma_{1}^{k}\right) \leq \nabla \phi\left(\sigma_{2}^{k}\right) \leq \cdots \leq \nabla \phi\left(\sigma_{t_n}^{k}\right), \\ & \phi\left(\sigma_{i}(\mathbf{Z}_n)\right) \leq \phi\left(\sigma_{i}^{k}\right)+\nabla \phi\left(\sigma_{i}^{k}\right)\left(\sigma_{i}(\mathbf{Z}_n)-\sigma_{i}^{k}\right), \end{aligned} \label{equ:gradient} \end{equation} where $i=1,2,\cdots,t_n$. Following (\ref{equ:gradient}), the subproblem with respect to $\mathbf{Z}_n$ (\ref{equation:Zn}) can be written as following relaxation: \begin{equation} \begin{split} &\arg \min _{\mathbf{Z}_n} \frac{1}{\hat{\rho}_{n}} \sum_{n=1}^{t_n} \phi\left(\sigma_{n}^{k}\right)+\nabla \phi\left(\sigma_{n}^{k}\right)\left(\sigma_{n}(\mathbf{Z}_n)-\sigma_{n}^{k}\right)+f(\mathbf{Z}_n) \\ &=\arg \min _{\mathbf{Z}_n} \frac{1}{\hat{\rho}_{n}} \sum_{n=1}^{t_n} \nabla \phi\left(\sigma_{n}^{k}\right) \sigma_{n}(\mathbf{Z}_n)+\frac{1}{2}\left\|\mathbf{Z}_n-\mathbf{P}_{n}^{k}\right\|_{\text{F}}^{2}. \end{split} \label{equ:relaxation} \end{equation} Then, based on \cite{lu_nonconvex, Non_LRMA}, the solution of (\ref{equ:relaxation}) can be efficiently obtained by generalized weight singular value thresholding (WSVT) \cite{WSVT} , as shown in Lemma 1. \noindent\textbf{Lemma 1}: For any $1 / \hat{\rho}_{n}>0$, the given data $\mathbf{P}_n^k=\mathbf{X}_{n}^{k}+\Gamma_{n}^{\mathbf{X}}/\rho_n$, and $0 \leq \nabla \phi\left(\sigma_{1}^{k}\right) \leq \nabla \phi\left(\sigma_{2}^{k}\right) \leq \cdots \leq \nabla \phi\left(\sigma_{t_n}^{k}\right)$, a globally optimal solution $\mathbf{Z}_n^{*}$ to (\ref{equ:relaxation}) is given as follows: \begin{equation} \label{equation_solution_Zn} \quad \mathbf{Z}_n^{k+1}= \operatorname{WSVT}\left(\mathbf{P}_n^{k}, \frac{\nabla \phi}{\hat{\rho}_{n}}\right) =\mathbf{U} \mathbf{S}_{\frac{\nabla \phi}{\hat{\rho}_{n}}}(\mathbf{\Sigma}) \mathbf{V}^{T}, \end{equation} where $\mathbf{P}_n^{k}=\mathbf{U} \mathbf{\Sigma} \mathbf{V}^{T}$ is the SVD of $\mathbf{P}_n^{k}$; $$\mathbf{S}_{\frac{\nabla \phi}{\hat{\rho}_{n}}}(\mathbf{\Sigma})=\operatorname{Diag}\left\{\max \left(\mathbf{\Sigma}_{ii}-\frac{\nabla \phi \left( \mathbf{\sigma}_{i}^{k}\right)}{\hat{\rho}_{n}}, 0\right)\right\},$$ and $i=1,2,\cdots,t_n$. With other variables fixed, the minimization subproblem for $\mathbf{X}_n$, $n=1,2,\cdots, N$, can be deduced from (\ref{equation:X_alm}) as follows: \begin{equation} \label{equationforX} \begin{aligned} \mathbf{X}_n^{k+1}&= \arg\min_{\mathbf{X}_n}\frac{\alpha_{n}}{2}\left\|\mathbf{Y}_{(n)}-\mathbf{A}_{n}^{k} \mathbf{X}_{n}\right\|_{\text{F}}^{2}\\ &+\frac{\rho_{n}}{2}\left\|\mathbf{X}_{n}-\frac{\mathbf{Z}_{n}^{k+1}-\Gamma_{n}^k/\mu_n+\mathbf{X}_n^{k}}{2}\right\|_{\text{F}}^{2}. \end{aligned} \end{equation} They are convex and have the following closed-form solutions \begin{equation} \label{equation:solution_Xn} \begin{aligned} \mathbf{X}_n^{k+1}=&\frac{1}{2}(\alpha_{n}\mathbf{A}_n^T\mathbf{A}_n+2\rho_n \mathbf{I}_n)^{-1}\left[2\alpha_{n}\mathbf{A}_n^T\mathbf{Y}_{(n)}\right.\\ &\left. +\mu_n \left(\mathbf{Z}_{n}^{k+1}-\Gamma_{n}^k/\mu_n+\mathbf{X}_n^{k}\right)\right]. \end{aligned} \end{equation} The Lagrangian multipliers $\Gamma_{n}^{\mathbf{X}}$ can be updated by the following equation \begin{equation} \label{equation:Lambda_2} \Gamma_{n}^{\mathbf{X}} = \Gamma_{n}^{\mathbf{X}} + \mathbf{X}_n-\mathbf{Z}_n. \end{equation} \subsubsection{Update $\mathbf{A}_n$} With fixing other variables, the optimization subproblem with respect to $\mathbf{A}_n$, $n=1,2,\cdots,N$, in (\ref{equation:XAY}) can be written as follows: \begin{equation} \label{equation_A_aux} \begin{aligned} \arg\min_{\{\mathbf{A}_n\}_{n=1}^{N}} \sum_{n=1}^{N} & \left(\frac{\alpha_{n}}{2}\left\|\mathbf{Y}_{(n)}-\mathbf{A}_{n} \mathbf{X}_{n}\right\|_{\text{F}}^{2}+\lambda_n \left\|\mathbf{A}_{n}\right\|_{\gamma}\right.\\ &\left.+\frac{\rho_n}{2}\left\|\mathbf{A}_n-\mathbf{A}_n^{k}\right\|_{\text{F}}^{2}\right). \end{aligned} \end{equation} To efficiently solve the above optimization, we first introduce auxiliary variables $\mathbf{A}_{n}=\mathbf{J}_{n}, n=1,2,\cdots,N$. Then, by the ALM method, the problem (\ref{equation_A_aux}) can also be reformulated as \begin{equation} \label{equation:A_alm} \begin{aligned} & \arg\min_{\{\mathbf{A}_n,\mathbf{J}_n\}_{n=1}^{N}} \sum_{n=1}^{N} \left(\frac{\alpha_{n}}{2}\left\|\mathbf{Y}_{(n)}-\mathbf{A}_{n} \mathbf{X}_{n}\right\|_{\text{F}}^{2}+\lambda_n \left\|\mathbf{J}_{n}\right\|_{\gamma}\right.\\ & \left. +\frac{\rho_n}{2}\left\|\mathbf{A}_n-\mathbf{A}_n^{k}\right\|_{\text{F}}^{2} +\left\langle\Gamma_{n}^\mathbf{A},\mathbf{A}_n-\mathbf{J}_n\right\rangle +\frac{\rho_{n}}{2}\left\|\mathbf{A}_{n}-\mathbf{J}_{n}\right\|_{\text{F}}^{2}\right), \end{aligned} \end{equation} where $\Gamma_{n}^\mathbf{A}$ are the Lagrangian multipliers. With other variables fixed, the minimization subproblem for $\mathbf{J}_n$ can be deduced from (\ref{equation:A_alm}) as follows: \begin{equation} \displaystyle \mathbf{J}_n^{k+1}= \arg \min_{\mathbf{J}_n} \lambda_n \left\|\mathbf{J}_{n}\right\|_{\gamma}+\frac{\rho_{n}}{2}\left\|\mathbf{J}_{n}-\mathbf{Q}_n^k\right\|_{\text{F}}^{2}. \end{equation} where $\tilde{\rho}_{n}=\rho_{n}/\lambda_n$; $\mathbf{Q}_n^k=\mathbf{A}_{n}^{k}+\Gamma_{n}^{\mathbf{A}}/\rho_n$. Its solution can also be obtained by \textbf{Lemma 1} as follows: \begin{equation} \label{equation_solution_Jn} \quad \mathbf{J}_n^{k+1}=\operatorname{WSVT}\left(\mathbf{Q}_n^{k}, \frac{\nabla \phi}{\tilde{\rho}_{n}}\right). \end{equation} With other variables fixed, the minimization subproblem for $\mathbf{A}_n$, $n=1,2,\cdots, N$, can be deduced from (\ref{equation:A_alm}) as follows: \begin{equation} \label{equationforA} \begin{aligned} \mathbf{A}_n^{k+1}= &\arg\min_{\mathbf{A}_n} \frac{\alpha_{n}}{2}\left\|\mathbf{Y}_{(n)}-\mathbf{A}_{n} \mathbf{X}_{n}\right\|_{\text{F}}^{2}\\ &+\rho_{n}\left\|\mathbf{A}_{n}-\frac{\mathbf{J}_{n}^{k+1}-\Gamma_{n}^\mathbf{A}/\rho_n+\mathbf{A}_n^{k}}{2}\right\|_{\text{F}}^{2}. \end{aligned} \end{equation} They are also convex and have the following closed-form solutions \begin{equation} \label{equation_solution_An} \begin{aligned} \mathbf{A}_{n}^{k+1}=&\left(\mathbf{Y}_{(n)}^{k}\left(\mathbf{X}_{n}^{k+1}\right)^{T}+\rho_n (\mathbf{J}_{n}^{k+1}-\Gamma_{n}^\mathbf{A}/\rho_n+\mathbf{A}_n^{k})\right)\\ &\left(\mathbf{X}_{n}^{k+1}\left(\mathbf{X}_{n}^{k+1}\right)^{T}+2\rho_{n} \mathbf{I}_{n}\right)^{\dagger}. \end{aligned} \end{equation} Finally, the Lagrangian multipliers $\Gamma_{n}^{\mathbf{A}}$ can be updated by the following equation \begin{equation} \label{equation:Lambda_1} \Gamma_{n}^{\mathbf{A}} = \Gamma_{n}^{\mathbf{A}} + \mathbf{A}_n-\mathbf{J}_n. \end{equation} \subsubsection{Update $\mathcal{Y}$} With other variables fixed, the minimization subproblem with respect to $\mathcal{Y}$ in (\ref{equation:XAY}) can be written as \begin{equation} \begin{aligned} & \arg\min_{\{\mathbf{Y}_{(n)}\}_{n=1}^{N}} \sum_{n=1}^{N} \frac{\alpha_{n}}{2}\left\|\mathbf{Y}_{(n)}-\mathbf{A}_{n} \mathbf{X}_{n}\right\|_{\text{F}}^{2}+\frac{\rho}{2}\left\|\mathcal{Y}-\mathcal{Y}^{k}\right\|_{\text{F}}^{2} \\ & s.t., \mathcal{P}_{\Omega}(\mathcal{Y})=\mathcal{F}. \end{aligned} \end{equation} Then, the update of $\mathcal{Y}^{k+1}$ can be written explicitly as \begin{equation} \label{equation_solution_Y} \begin{array}{l} \displaystyle \mathcal{Y}^{k+1}=\mathcal{P}_{{\Omega}^c}\left(\sum_{n=1}^{N} \alpha_{n} \text { fold }_{n}\left(\frac{\mathbf{A}_{n}^{k+1} \mathbf{X}_{n}^{k+1}+\rho_n \mathbf{Y}_{(n)}^{k}}{1+\rho_n}\right)\right)+\mathcal{F}, \end{array} \end{equation} where $\Omega^{C}$ is the complementary set of $\Omega$. \begin{algorithm}[!t] \caption{:Algorithm for the LRATM model.} \label{algorithm:A1} \begin{algorithmic}[1] \Require The observed tensor $\mathcal{F}$; The set of index of observed entries $\Omega$; Stopping criterion $\varepsilon$, the given $n$-rank, $r=\left(r_{1}, r_{2}, r_{3}\right)$. \Ensure The completed tensor. \State Initialize: $\mathbf{X}_n=\mathbf{Z}_n=0, \mathbf{A}_n=\mathbf{J}_n=0,\Gamma_{n}^\mathbf{X}=0, \Gamma_{n}^\mathbf{A}=0, n=1,2, \cdots, N$; $k=0$. \State Repeat until convergence: \State Update $\mathbf{X}, \mathbf{Z}, \mathbf{A}, \mathbf{J}, \mathcal{Y}, \Gamma^{\mathbf{X}}, \Gamma^{\mathbf{A}}$ via 1st step: Update $\mathbf{Z}_n$ via (\ref{equation_solution_Zn}) 2nd step: Update $\mathbf{X}_n$ via (\ref{equation:solution_Xn}) 3rd step: Update $\mathbf{A}_n$ via (\ref{equation_solution_An}) 4th step: Update $\mathbf{J}_n$ via (\ref{equation_solution_Jn}) 5th step: Update $\mathcal{Y}$ via (\ref{equation_solution_Y}) 6th step: Update the parameter via (\ref{equation:Lambda_2}), (\ref{equation:Lambda_1}) \State Check the convergence condition. \end{algorithmic} \end{algorithm} \subsection{ Complexity and Convergence Analysis} The proposed algorithm for our LRATM model is summarized in Algorithm \ref{algorithm:A1}. Further, we discuss the complexity and convergence of the proposed algorithm. \subsubsection{Complexity analysis} The cost of computing $\mathbf{X}_{n}$ is $O\left(I_{n} r_{n}^{2}+I_{n} r_{n} s_{n}+r_{n}^{2} s_{n}\right)$, calculating $\mathbf{Z_n}$ has a complexity of $O\left( \Pi_{j \neq n} I_{j} \times r_{n}^2 \right)$, the complexity of updating $\mathbf{J}_n$ is $O\left(I_{n} r_{n}^2\right)$, calculating $\mathbf{A}_{n}$ has a complexity of $O\left(I_{n} r_{n}^{2}+I_{n} r_{n} s_{n}+r_{n}^{2} s_{n}\right)$, calculating $\mathcal{Y}$ has a complexity of $O\left(r_{1} I_{1} s_{1}+\cdots+r_{N} I_{N} s_{N}\right)$. Therefore, the total complexity of the proposed algorithm can be obtained by counting the complexity of the above variables, i.e., \begin{equation} \label{equation:complexity_model1} O\left(\sum_{n}(3I_{n} r_{n}^2+\Pi_{j \neq n} I_{j} \times r_{n}^2+3 I_{n} r_{n} S_{n}+2 r_{n}^{2} s_{n})\right). \end{equation} \subsubsection{Convergence analysis} In this section, we theoretically analyze the convergence of the proposed algorithm by using the BSUM method \cite{BSUM}. \noindent \textbf{Lemma 2} \cite{BSUM}: Let us assume that the feasible set $\mathcal{X}$ is the cartesian product of $n$ closed convex sets: $\mathcal{X}=\mathcal{X}_1 \times \mathcal{X}_2 \times \cdots \times \mathcal{X}_{n}$. Given the problem \begin{equation} \min f(x), s.t. ~ x \in \mathcal{X}, \end{equation} assume $h\left(x, x^{k-1}\right)$ is an approximation of $f(x)$ at the $(k-1)$-th iteration, which satisfies the following conditions: \begin{equation} \begin{array}{l} 1) \quad h_{i}\left(y_{i}, y\right)=f(y), \forall y \in \mathcal{X}, \forall i; \\ 2) \quad h_{i}\left(x_{i}, y\right) \geq f\left(y_{1}, \ldots, y_{i-1}, x_{i}, y_{i+1}, \ldots, y_{n}\right), \\ \quad \quad \forall x_{i} \in \mathcal{X}_{i}, \forall y \in \mathcal{X}, \forall i;\\ 3) \quad \left.h_{i}^{\prime}\left(x_{i}, y ; d_{i}\right)\right|_{x_i=y_i}=f^{\prime}(y ; d), \forall d=\left(0, \cdots, d_{i} \cdots 0\right) \\ \quad \quad \text { s.t. } y_{i}+d_{i} \in \mathcal{X}_{i}, \forall i;\\ 4) \quad h_{i}\left(x_{i}, y\right) \text{is continuous in} \left(x_{i}, y\right), \forall i; \end{array} \end{equation} where $h_{i}\left(x_{i}, y\right)$ is the sub-problem with respect to the $i$-th block and $f^{\prime}(y ; d)$ is the direction derivative of fat the point $y$ in direction $d$. Suppose $h_{i}\left(x_{i}, y\right)$ is quasi-convex in $x_{i}$ for $i=1,2, \cdots, n$. Furthermore, assume that each sub-problem $\arg\min h_i\left(x_{i}, x^{k-1}\right), s.t. ~ x \in \mathcal{X}_{i}$ has a unique solution for any point $x^{k-1} \in \mathcal{X} .$ Then, the iterates generated by the BSUM algorithm converge to the set of coordinatewise minimum of $f$. \noindent \textbf{Theorem 1.} The iterates generated by (\ref{equation_original_PPA}) converge to the set of coordinatewise minimizers. \textbf{Proof.} It is easy to verify that $g\left(\mathcal{S}, \mathcal{S}^{k}\right)$ is an approximation and a global upper bound of $f(\mathcal{S})$ at the $k$-th iteration, which satisfies the following conditions: \begin{equation} \begin{array}{l} 1) \quad g_{i}\left(\mathcal{S}_{i}, \mathcal{S}\right)=f(\mathcal{S}), \forall \mathcal{S}, i=1,2,3; \\ 2) \quad g_{i}\left(\bar{\mathcal{S}}_{i}, \mathcal{S}\right) \geq f\left(\mathcal{S}_{1}, \cdots, \bar{\mathcal{S}_{i}}, \cdots, \mathcal{S}_{3}\right), \\ \quad\quad \forall \bar{\mathcal{S}}_{i}, \forall \mathcal{S}, i=1,2,3; \\ 3) \quad \left.g_{i}^{\prime}\left(\bar{\mathcal{S}}_{i}, \mathcal{S} ; \mathbf{M}_{i}\right)\right|_{\bar{\mathcal{S}}_{i}=\mathcal{S}_{i}}=f^{\prime}\left(\mathcal{S} ; \mathbf{M}^i\right), \\ \quad \quad \forall \mathbf{M}^{i}=\left(0, \ldots, \mathbf{M}_{i},\ldots, 0\right); \\ 4) \quad g_{i}\left(\bar{\mathcal{S}}_{i}, \mathcal{S}\right) \text{is continuous in} \left(\bar{\mathcal{S}}_{i}, \mathcal{S} \right), i=1,2,3; \end{array} \end{equation} where $\mathcal{S}=(\mathbf{X}, \mathbf{A}, \mathcal{Y}),$ and $\mathcal{S}_{i}$ equal $\mathbf{X}, \mathbf{A}, \mathcal{Y}$ for $i=1,2,3,$ respectively. In addition, the subproblem $g_{i}(i=1,2,3)$ is quasi-convex with respect to $\mathbf{X}, \mathbf{A}$ and $\mathcal{Y}$ respectively and each sub-problem of $g_{i}$ has a unique solution. Therefore, all assumptions in \textbf{Lemma 1} are satisfied. According to the conclusion of \textbf{Lemma 1}, the \textbf{Theorem 1} is valid, and the proposed algorithm is theoretically convergent. \section{Numerical experiments} \label{Numerical experiments} In this section, the proposed model is evaluated on three types of public tensor datasets, i.e., video datasets, MRI dataset and HSI dataset which have been frequently used to interpret the tensor completion performance of different models. To demonstrate its effectiveness, we compare the proposed model with TMac method \cite{Tmac}, MF-TV method \cite{MFTV}, single TNN based method \cite{lu2019TRPCA} and PSTNN based method \cite{PSTNN}. \begin{table}[t] \caption{The averaged PSNR, SSIM, FSIM, ERGA and SAM of the completed results on video "suzie" by Tmac, MF-TV, TNN, PSTNN and our model with different sampling rates. The best values are highlighted in bolder fonts.} \centering \label{table_video_suzie} \setlength{\tabcolsep}{1mm}{ \begin{tabular}{cccccccc} \hline \hline && &SR =0.05 &&&& \\ PQI & nosiy& our model& MF-TV& TMac& PSTNN& TNN\\ PSNR & 7.259 & \textbf{29.464} & 13.801 & 23.385 & 17.447 & 22.005 \\ SSIM & 0.009 & \textbf{0.807} & 0.094 & 0.622 & 0.192 & 0.563 \\ FSIM & 0.454 & \textbf{0.885} & 0.42 & 0.792 & 0.59 & 0.776 \\ ERGA & 1057.282 & \textbf{83.571} & 501.117 & 167.927 & 327.678 & 194.844 \\ MSAM & 77.324 & \textbf{3.622} & 24.095 & 6.927 & 13.775 & 7.797 \\ \hline &&&SR = 0.1&&&&\\ PQI & nosiy& our model& MF-TV& TMac& PSTNN& TNN\\ PSNR& 7.493& \textbf{32.056}& 22.356& 26.189& 26.647& 26.032\\ SSIM& 0.014& \textbf{0.878}& 0.605& 0.74& 0.68& 0.692\\ FSIM& 0.426& \textbf{0.924}& 0.758& 0.838& 0.843& 0.846\\ ERGA& 1029.096& \textbf{62.314}& 196.059& 124.369 &117.104& 124.923\\ MSAM& 71.725& \textbf{2.764}& 6.99& 5.423& 5.171& 5.405 \\ \hline &&&SR = 0.2&&&&\\ PQI & nosiy& our model& MF-TV& TMac& PSTNN& TNN\\ PSNR& 8.005& \textbf{34.378}& 32.064& 27.274& 30.566& 30.561\\ SSIM& 0.02& \textbf{0.918}& 0.872& 0.782& 0.829& 0.831\\ FSIM& 0.391& \textbf{0.948}& 0.916& 0.853& 0.91& 0.911\\ ERGA& 970.285& \textbf{47.877}& 66.692& 109.627& 75.472& 75.598\\ MSAM& 63.522& \textbf{2.183}& 2.81& 4.812& 3.399& 3.395\\ \hline \hline \end{tabular}} \end{table} To accurately evaluate the performance of the test models, two types of standards are employed to quantitatively evaluate the quality of the completed tensors. The first one is the visual evaluation of the completed data, which is a qualitative evaluation standard. The second one is the five quantitative picture quality indices (PQIs), including the peak signal-to-noise ratio (PSNR) \cite{PSNR}, structural similarity index (SSIM) \cite{SSIM}, feature similarity (FSIM) \cite{FSIM}, erreur relative globale adimensionnelle de synth\`ese (ERGAS) \cite{EGRAS}, the mean the spectral angle mapper (SAM) \cite{SAM}. Larger PSNR, SSIM, FSIM and smaller ERGAS, SAM are, the better the completion performance of the corresponding model is. Since the experimental datasets are all third-order tensors, the PQIs for each frontal slice in the completed tensor are first calculated, and then the mean of these PQIs are finally used to evaluate the performance of the models. All experiments are performed on MATLAB 2019b, the CPU of the computer is Inter core i7@2.2GHz and the memory is 64GB. The code will be posted on the following URL: https://github.com/NavyZeng/LRATM. \subsection{Video Data} \begin{figure*}[!t] \centering \subfloat[Original]{\includegraphics[width=0.13\linewidth]{Image_video_b94}}% \hfil \subfloat[95\% Masked]{\includegraphics[width=0.13\linewidth]{Image_video_b94_sr005Nosiy}}% \hfil \subfloat[our model]{\includegraphics[width=0.13\linewidth]{Image_video_b94_sr005LxLxNN}}% \hfil \subfloat[MF-TV]{\includegraphics[width=0.13\linewidth]{Image_video_b94_sr005MF_TV}}% \hfil \subfloat[Tmac]{\includegraphics[width=0.13\linewidth]{Image_video_b94_sr005Tmac}}% \hfil \subfloat[PSTNN]{\includegraphics[width=0.13\linewidth]{Image_video_b94_sr005PSTNN}}% \hfil \subfloat[TNN]{\includegraphics[width=0.13\linewidth]{Image_video_b94_sr005TNN} \caption{One slice of the recovered video for “suzie” by our model, MF-TV, Tmac, PSTNN and TNN. The sampling rate is 5\%.} \label{figure_video_sr0.05} \end{figure*} \begin{figure*}[!t] \centering \subfloat[Original]{\includegraphics[width=0.13\linewidth]{Image_video_b10_sr01suzie_b10}}% \hfil \subfloat[90\% Masked]{\includegraphics[width=0.13\linewidth]{Image_video_b10_sr01Nosiy}}% \hfil \subfloat[our model]{\includegraphics[width=0.13\linewidth]{Image_video_b10_sr01LxLxNN}}% \hfil \subfloat[MF-TV]{\includegraphics[width=0.13\linewidth]{Image_video_b10_sr01MF_TV}}% \hfil \subfloat[Tmac]{\includegraphics[width=0.13\linewidth]{Image_video_b10_sr01Tmac}}% \hfil \subfloat[PSTNN]{\includegraphics[width=0.13\linewidth]{Image_video_b10_sr01PSTNN}}% \hfil \subfloat[TNN]{\includegraphics[width=0.13\linewidth]{Image_video_b10_sr01TNN} \caption{One slice of the recovered video for “suzie” by our model, MF-TV, Tmac, PSTNN and TNN. The sampling rate is 10\%.} \label{figure_video_sr0.1} \end{figure*} \begin{figure*}[!t] \centering \subfloat[Original]{\includegraphics[width=0.13\linewidth]{Image_video_b10_sr02suzie_b10}}% \hfil \subfloat[80\% Masked]{\includegraphics[width=0.13\linewidth]{Image_video_b10_sr02Nosiy}}% \hfil \subfloat[our model]{\includegraphics[width=0.13\linewidth]{Image_video_b10_sr02LxLxNN}}% \hfil \subfloat[MF-TV]{\includegraphics[width=0.13\linewidth]{Image_video_b10_sr02MF_TV}}% \hfil \subfloat[Tmac]{\includegraphics[width=0.13\linewidth]{Image_video_b10_sr02Tmac}}% \hfil \subfloat[PSTNN]{\includegraphics[width=0.13\linewidth]{Image_video_b10_sr02PSTNN}}% \hfil \subfloat[TNN]{\includegraphics[width=0.13\linewidth]{Image_video_b10_sr02TNN} \caption{One slice of the recovered video for “suzie” by our model, MF-TV, Tmac, PSTNN and TNN. The sampling rate is 20\%.} \label{figure_video_sr0.2} \end{figure*} In this subsection, we compare our model with MF-TV, Tmac, TNN and PSTNN on two video datasets: "suzie" and “hall”\footnote{http://trace.eas.asu.edu/yuv/}, both of which are colored using YUV format, and two slices of them are shown in Fig. \ref{figure_video_sr0.05} and Fig. \ref{figure_hall_sr0.05}, respectively. Their sizes both are 144 $\times$ 176 $\times$ 150. We test all five methods on a series of sampling rates (SR): 5\%, 10\% and 20\%, and all the test models are evaluated in terms of quantitative comparison and visual evaluation. In addition, the $n$-rank is approximated by using the number of the largest 0.5\% singular values. For quantitative comparison, Table \ref{table_video_suzie} and Table \ref{table_video_hall} report the PQIs of the results completed by different methods. The best result for each PQI are marked in bold. From Table \ref{table_video_suzie} and Table \ref{table_video_hall}, it can be found that our model obtains the highest indices among the five tested models in all SR cases; Tmac obtains the second best PQIs, when the SR is set to 5\% or 10\%; While MF-TV obtains the second best PQIs, when SR is set to 20\%. The margins between the results by our model and the second best results are more than 5dB considering the PSNR. For visual evaluation, we illustrate one frontal slice of the completed results with different sampling rates in Fig. \ref{figure_video_sr0.05}, Fig. \ref{figure_video_sr0.1}, Fig. \ref{figure_video_sr0.2}, Fig. \ref{figure_hall_sr0.05} and Fig. \ref{figure_hall_sr0.1}. It is clear from the figures that the results of our model are closest to the ground truth than other tested models, especially at low sampling rates. Specifically, as shown in Fig. \ref{figure_hall_sr0.1}, Fig. \ref{figure_video_sr0.05} and Fig. \ref{figure_video_sr0.1}, when the sampling rates are 0.05 and 0.1, the advantages of our model are most obvious. Our model restores most of the structural information of the videos, while the videos restored by the competitive models contain only the outline of the images. At a higher sampling rate, as shown in Fig. \ref{figure_video_sr0.2} and Fig. \ref{figure_hall_sr0.1}, our model and competitive models both complete the main structural information of the images, but our model recovers more texture and detail information. \begin{table} [t] \centering \caption{The averaged PSNR, SSIM, FSIM, ERGA and SAM of the recovered results on video "hall" by Tmac, MF-TV, TNN, PSTNN and our model with different sampling rates. The best values are highlighted in bolder fonts.} \label{table_video_hall} \setlength{\tabcolsep}{1mm}{ \begin{tabular}{cccccccc} \hline \hline &&&SR =0.05 &&&& \\ PQI& nosiy& our model& MF-TV& TMac& PSTNN& TNN\\ PSNR & 4.82 & \textbf{28.347} & 13.539 & 22.101 & 16.075 & 20.78 \\ SSIM & 0.007 & \textbf{0.894} & 0.412 & 0.675 & 0.36 & 0.636 \\ FSIM & 0.387 & \textbf{0.920} & 0.612 & 0.789 & 0.672 & 0.792 \\ ERGA & 1225.779 & \textbf{83.146} & 452.351 & 168.866 & 335.52 & 195.315 \\ MSAM & 77.299 & \textbf{2.360} & 12.865 & 3.818 & 8.64 & 4.299 \\ \hline &&&SR = 0.1&&&&\\ PQI & nosiy & our model & MF-TV & TMac & PSTNN & TNN \\ PSNR & 5.055 & \textbf{31.804} & 24.855 & 26.936 & 29.014 & 28.433 \\ SSIM & 0.013 & \textbf{0.935} & 0.829 & 0.854 & 0.892 & 0.905 \\ FSIM & 0.393 & \textbf{0.950} & 0.873 & 0.888 & 0.934 & 0.936 \\ ERGA & 1193.075 & \textbf{56.998} & 131.422 & 97.185 & 77.395 & 82.259 \\ MSAM & 71.7 &\textbf{ 1.904} & 3.669 & 2.404 & 2.417 & 2.46 \\ \hline &&&SR = 0.2&&&&\\ PQI & nosiy & our model & MF-TV & TMac & PSTNN & TNN \\ PSNR & 5.567 & \textbf{33.941} & 33.006 & 27.648 & 33.629 & 33.691 \\ SSIM & 0.025 & \textbf{0.952} & 0.94 & 0.869 & 0.961 & 0.962 \\ FSIM & 0.403 & \textbf{0.964} & 0.954 & 0.897 & 0.973 & 0.974 \\ ERGA & 1124.737 & \textbf{44.581} & 50.971 & 89.271 & 46.123 & 45.851 \\ MSAM & 63.507 & \textbf{1.574} & 1.779 & 2.226 & 1.584 & 1.565 \\ \hline \hline \end{tabular}} \end{table} \subsection{Magnetic resonance imaging data} \begin{figure*}[!t] \centering \subfloat[Original]{\includegraphics[width=0.13\linewidth]{Image_hall_b21_sr005Original}}% \hfil \subfloat[95\% Masked]{\includegraphics[width=0.13\linewidth]{Image_hall_b21_sr005Nosiy}}% \hfil \subfloat[our model]{\includegraphics[width=0.13\linewidth]{Image_hall_b21_sr005LxLxNN}}% \hfil \subfloat[MF-TV]{\includegraphics[width=0.13\linewidth]{Image_hall_b21_sr005MF_TV}}% \hfil \subfloat[Tmac]{\includegraphics[width=0.13\linewidth]{Image_hall_b21_sr005Tmac}}% \hfil \subfloat[PSTNN]{\includegraphics[width=0.13\linewidth]{Image_hall_b21_sr005PSTNN}}% \hfil \subfloat[TNN]{\includegraphics[width=0.13\linewidth]{Image_hall_b21_sr005TNN} \caption{One slice of the recovered video “hall” by our model, MF-TV, Tmac, PSTNN and TNN. The sampling rate is 5\%.} \label{figure_hall_sr0.05} \end{figure*} \begin{figure*}[!t] \centering \subfloat[Original]{\includegraphics[width=0.13\linewidth]{Image_hall_b104_sr01Original}}% \hfil \subfloat[90\% Masked]{\includegraphics[width=0.13\linewidth]{Image_hall_b104_sr01Nosiy}}% \hfil \subfloat[our model]{\includegraphics[width=0.13\linewidth]{Image_hall_b104_sr01LxLxNN}}% \hfil \subfloat[MF-TV]{\includegraphics[width=0.13\linewidth]{Image_hall_b104_sr01MF_TV}}% \hfil \subfloat[Tmac]{\includegraphics[width=0.13\linewidth]{Image_hall_b104_sr01Tmac}}% \hfil \subfloat[PSTNN]{\includegraphics[width=0.13\linewidth]{Image_hall_b104_sr01PSTNN}}% \hfil \subfloat[TNN]{\includegraphics[width=0.13\linewidth]{Image_hall_b104_sr01TNN} \caption{One slice of the recovered video “hall” by our model, MF-TV, Tmac, PSTNN and TNN. The sampling rate is 10\%.} \label{figure_hall_sr0.1} \end{figure*} \begin{figure*}[!t] \centering \subfloat[]{\includegraphics[width=0.2\linewidth]{psnr_suzie_sr005}} \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{psnr_suzie_sr01}} \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{psnr_suzie_sr02}} \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{ssim_suzie_sr005}} \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{ssim_suzie_sr01}} \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{ssim_suzie_sr02}} \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{fsim_suzie_sr005}}% \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{fsim_suzie_sr01}}% \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{fsim_suzie_sr02}}% \caption{The PSNR, SSIM and FSIM of the recovered video "suzie" by MF-TV, Tmac, TNN, PSTNN and our model for all slices, respectively.} \label{PSNR and SSIM of video} \end{figure*} \begin{figure*}[!t] \centering \subfloat[Original]{\includegraphics[width=0.13\linewidth]{Image_MRI_b7_sr01MRI_b7}}% \hfil \subfloat[90\% Masked]{\includegraphics[width=0.13\linewidth]{Image_MRI_b7_sr01Nosiy}}% \hfil \subfloat[our model]{\includegraphics[width=0.13\linewidth]{Image_MRI_b7_sr01LxLxNN}}% \hfil \subfloat[MF-TV]{\includegraphics[width=0.13\linewidth]{Image_MRI_b7_sr01MF_TV}}% \hfil \subfloat[Tmac]{\includegraphics[width=0.13\linewidth]{Image_MRI_b7_sr01Tmac}}% \hfil \subfloat[PSTNN]{\includegraphics[width=0.13\linewidth]{Image_MRI_b7_sr01PSTNN}}% \hfil \subfloat[TNN]{\includegraphics[width=0.13\linewidth]{Image_MRI_b7_sr01TNN} \caption{One slice of the recovered MRI by our model, MF-TV, Tmac, PSTNN and TNN. The sampling rate is 10\%.} \label{figure_MR_sr0.1_1} \end{figure*} \begin{figure*}[!t] \centering \subfloat[Original]{\includegraphics[width=0.13\linewidth]{Image_MRI_b83_sr01MRI_b83}}% \hfil \subfloat[90\% Masked]{\includegraphics[width=0.13\linewidth]{Image_MRI_b83_sr01Nosiy}}% \hfil \subfloat[our model]{\includegraphics[width=0.13\linewidth]{Image_MRI_b83_sr01LxLxNN}}% \hfil \subfloat[MF-TV]{\includegraphics[width=0.13\linewidth]{Image_MRI_b83_sr01MF_TV}}% \hfil \subfloat[Tmac]{\includegraphics[width=0.13\linewidth]{Image_MRI_b83_sr01Tmac}}% \hfil \subfloat[PSTNN]{\includegraphics[width=0.13\linewidth]{Image_MRI_b83_sr01PSTNN}}% \hfil \subfloat[TNN]{\includegraphics[width=0.13\linewidth]{Image_MRI_b83_sr01TNN} \caption{One slice of the recovered MRI by our model, MF-TV, Tmac, PSTNN and TNN. The sampling rate is 10\%.} \label{figure_MR_sr0.1_2} \end{figure*} \begin{figure*}[!t] \centering \subfloat[Original]{\includegraphics[width=0.13\linewidth]{Image_MRI_b95_sr01MRI_b95}}% \hfil \subfloat[90\% Masked]{\includegraphics[width=0.13\linewidth]{Image_MRI_b95_sr01Nosiy}}% \hfil \subfloat[our model]{\includegraphics[width=0.13\linewidth]{Image_MRI_b95_sr01LxLxNN}}% \hfil \subfloat[MF-TV]{\includegraphics[width=0.13\linewidth]{Image_MRI_b95_sr01MF_TV}}% \hfil \subfloat[Tmac]{\includegraphics[width=0.13\linewidth]{Image_MRI_b95_sr01Tmac}}% \hfil \subfloat[PSTNN]{\includegraphics[width=0.13\linewidth]{Image_MRI_b95_sr01PSTNN}}% \hfil \subfloat[TNN]{\includegraphics[width=0.13\linewidth]{Image_MRI_b95_sr01TNN} \caption{One slice of the recovered MRI by our model, MF-TV, Tmac, PSTNN and TNN. The sampling rate is 10\%.} \label{figure_MR_sr0.1_3} \end{figure*} \begin{figure*}[!t] \centering \subfloat[Original]{\includegraphics[width=0.13\linewidth]{Image_MRI_b118_sr01MRI_b118}}% \hfil \subfloat[90\% Masked]{\includegraphics[width=0.13\linewidth]{Image_MRI_b118_sr01Nosiy}}% \hfil \subfloat[our model]{\includegraphics[width=0.13\linewidth]{Image_MRI_b118_sr01LxLxNN}}% \hfil \subfloat[MF-TV]{\includegraphics[width=0.13\linewidth]{Image_MRI_b118_sr01MF_TV}}% \hfil \subfloat[Tmac]{\includegraphics[width=0.13\linewidth]{Image_MRI_b118_sr01Tmac}}% \hfil \subfloat[PSTNN]{\includegraphics[width=0.13\linewidth]{Image_MRI_b118_sr01PSTNN}}% \hfil \subfloat[TNN]{\includegraphics[width=0.13\linewidth]{Image_MRI_b118_sr01TNN} \caption{One slice of the recovered MRI by our model, MF-TV, Tmac, PSTNN and TNN. The sampling rate is 10\%.} \label{figure_MR_sr0.1_4} \end{figure*} \begin{figure*}[!t] \centering \subfloat[]{\includegraphics[width=0.2\linewidth]{psnr_mri_sr005}} \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{psnr_mri_sr01}} \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{psnr_mri_sr02}} \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{ssim_mri_sr005}} \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{ssim_mri_sr01}} \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{ssim_mri_sr02}} \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{fsim_mri_sr005}}% \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{fsim_mri_sr01}}% \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{fsim_mri_sr02}}% \caption{The PSNR, SSIM and FSIM of the recovered MRI by MF-TV, Tmac, TNN, PSTNN and our model for all slices, respectively.} \label{PSNR and SSIM of MRI} \end{figure*} To further verify the versatility of our model for different datasets, in this subsection we compare our model with MF-TV, Tmac, TNN and PSTNN on MRI dataset, i.e., the cubical MRI data\footnote{http://brainweb.bic.mni.mcgill.ca/brainweb/selection$\_$normal.html}. Its one slice is shown in Fig. \ref{figure_MR_sr0.1_1}. The size of the dataset is 181 $\times$ 217 $\times$ 150. We test all five methods on a series of sampling rates: 5\%, 10\%, 20\% and 30\%. In addition, the $n$-rank is approximated by using the number of the largest 0.5\% singular values. For quantitative comparison, Table \ref{table_MRI} reports the PQIs of the results completed by different methods. The best result for each PQI are marked in bold. From Table \ref{table_MRI}, it can be found that our method obtains the highest indices among the five tested methods in all SR cases. Further, the same advantage of our model can also be seen in Fig. \ref{PSNR and SSIM of MRI} which reports the PSNR, SSIM and FSIM of each slice. For visual comparison, Fig. \ref{figure_MR_sr0.1_1}, Fig. \ref{figure_MR_sr0.1_2}, Fig. \ref{figure_MR_sr0.1_3} and Fig. \ref{figure_MR_sr0.1_4} show slices with 90\% missing values and the corresponding completed slices by all the tested methods. From the results, we see again that our model can better retain the local details and texture information of the images, and effectively restore the main structure of the images than other compared methods. Therefore, one can see that the recovered data obtained by our model has the best visual evaluation. \begin{table}[t] \centering \caption{The averaged PSNR, SSIM, FSIM, ERGA and SAM of the recovered results on MRI by Tmac, MF-TV, TNN, PSTNN and our model with different sampling rates. The best values are highlighted in bolder fonts.} \label{table_MRI} \setlength{\tabcolsep}{1mm}{ \begin{tabular}{ccccccccc} \hline \hline &&&SR =0.05 &&&& \\ PQI& nosiy& our model& MF-TV& TMac& PSTNN& TNN\\ PSNR & 10.258 & \textbf{26.414} & 12.332 & 20.51 & 15.859 & 18.218 \\ SSIM & 0.228 & \textbf{0.722} & 0.099 & 0.45 & 0.224 & 0.27 \\ FSIM & 0.473 & \textbf{0.834} & 0.52 & 0.711 & 0.642 & 0.646 \\ ERGA & 1030.203 & \textbf{184.279} & 814.747 & 339.385 & 545.77 & 434.774 \\ MSAM & 76.54 & \textbf{20.411} & 55.603 & 31.367 & 36.355 & 31.11 \\ \hline &&&SR = 0.1&&&&\\ PQI & nosiy & our model & MF-TV & TMac & PSTNN & TNN \\ PSNR & 10.492 & \textbf{32.652} & 15.406 & 21.411 & 22.061 & 22.535 \\ SSIM & 0.241 & \textbf{0.912} & 0.25 & 0.531 & 0.482 & 0.536 \\ FSIM & 0.511 & \textbf{0.926} & 0.587 & 0.732 & 0.764 & 0.78 \\ ERGA & 1002.8 & \textbf{89.116} & 584.827 & 308.655 & 275.473 & 266.753 \\ MSAM & 70.986 & \textbf{14.637} & 41.826 & 29.345 & 24.585 & 24.6 \\ \hline &&&SR = 0.2&&&&\\ PQI & nosiy & our model & MF-TV & TMac & PSTNN & TNN \\ PSNR & 11.003 & \textbf{36.529} & 27.062 & 22.33 & 29.152 & 28.571 \\ SSIM & 0.271 & \textbf{0.962} & 0.737 & 0.586 & 0.804 & 0.802 \\ FSIM & 0.564 & \textbf{0.963} & 0.84 & 0.754 & 0.895 & 0.891 \\ ERGA & 945.583 & \textbf{57.037} & 173.636 & 276.269 & 127.133 & 136.182 \\ MSAM & 62.887 & \textbf{11.559} & 21.792 & 27.267 & 17.513 & 17.855 \\ \hline \hline \end{tabular}} \end{table} \subsection{Hyperspectral Image Data} \begin{figure*}[!t] \centering \subfloat[Original]{\includegraphics[width=0.13\linewidth]{Image_HSI_b72.png}}% \hfil \subfloat[97.5\% Masked]{\includegraphics[width=0.13\linewidth]{Image_HSI_b72_sr0025Nosiy}}% \hfil \subfloat[our model]{\includegraphics[width=0.13\linewidth]{Image_HSI_b72_sr0025LxLxNN}}% \hfil \subfloat[MF-TV]{\includegraphics[width=0.13\linewidth]{Image_HSI_b72_sr0025MF_TV}}% \hfil \subfloat[Tmac]{\includegraphics[width=0.13\linewidth]{Image_HSI_b72_sr0025Tmac}}% \hfil \subfloat[PSTNN]{\includegraphics[width=0.13\linewidth]{Image_HSI_b72_sr0025PSTNN}}% \hfil \subfloat[TNN]{\includegraphics[width=0.13\linewidth]{Image_HSI_b72_sr0025TNN} \caption{One slice of the recovered HSI "Cuprite" by our model, MF-TV, Tmac, PSTNN and TNN. The sampling rate is 2.5\%.} \label{figure_HSI_sr0.025} \end{figure*} \begin{figure*}[!t] \centering \subfloat[Original]{\includegraphics[width=0.13\linewidth]{Image_HSI_b72.png}}% \hfil \subfloat[95\% Masked]{\includegraphics[width=0.13\linewidth]{Image_HSI_b72_sr005Nosiy}}% \hfil \subfloat[our model]{\includegraphics[width=0.13\linewidth]{Image_HSI_b72_sr005LxLxNN}}% \hfil \subfloat[MF-TV]{\includegraphics[width=0.13\linewidth]{Image_HSI_b72_sr005MF_TV}}% \hfil \subfloat[Tmac]{\includegraphics[width=0.13\linewidth]{Image_HSI_b72_sr005Tmac}}% \hfil \subfloat[PSTNN]{\includegraphics[width=0.13\linewidth]{Image_HSI_b72_sr005PSTNN}}% \hfil \subfloat[TNN]{\includegraphics[width=0.13\linewidth]{Image_HSI_b72_sr005TNN} \caption{One slice of the recovered HSI "Cuprite" by our model, MF-TV, Tmac, PSTNN and TNN. The sampling rate is 5\%.} \label{figure_HSI_sr0.05} \end{figure*} \begin{figure*}[!t] \centering \subfloat[PSNR]{\includegraphics[width=0.15\linewidth]{psnr_hsi_sr0025}}% \hfil \subfloat[SSIM]{\includegraphics[width=0.15\linewidth]{ssim_hsi_sr0025}}% \hfil \subfloat[FSIM]{\includegraphics[width=0.15\linewidth]{fsim_hsi_sr0025}}% \hfil \subfloat[PSNR]{\includegraphics[width=0.15\linewidth]{psnr_hsi_sr005}}% \hfil \subfloat[SSIM]{\includegraphics[width=0.15\linewidth]{ssim_hsi_sr005}}% \hfil \subfloat[FSIM]{\includegraphics[width=0.15\linewidth]{fsim_hsi_sr005}}% \caption{The PSNR, SSIM and FSIM of the recovered HSI "Cuprite" by MF-TV, Tmac, TNN, PSTNN and our model for all slices, respectively.(a)-(c): 97.5\% entries missing, (d)-(f): 95\% entries missing.} \label{PSNR and SSIM of HSI} \end{figure*} In this section, we compare our model with MF-TV, Tmac, TNN and PSTNN on one HSI dataset: Airborne Visible/Infrared Imaging Spectrometer (AVIRIS) Cuprite data\footnote{http://aviris.jpl.nasa.gov/html/aviris.freedata.html}. The size of AVIRIS Cuprite data is 150 $\times$ 150 $\times$ 188. Its one slice is shown in Fig. \ref{figure_HSI_sr0.05}. We test all five methods on a series of sampling rates: 2.5\%, 5\% and 10\%. In addition, the $n$-rank is approximated by using the number of the largest 0.3\% singular values. For quantitative comparison, Table \ref{table_HSI} reports the average PQIs of each tested method with three different sampling rates. At sampling rates 0.025 and 0.05, Fig. \ref{PSNR and SSIM of HSI} reports the PSNR, SSIM and FSIM of each frontal slice in the completed results. For visual comparison, Fig. \ref{figure_HSI_sr0.05} and Fig. \ref{figure_HSI_sr0.025} show slices of the sampled data with 97.5\% and 95\% missing values and the corresponding recovered slices by the tested methods. From the results, we see again that our model not only obtains the highest PQIs, but also recovers more structure information and spatial details of the images than compared methods, especially at low sampling rates. \begin{table} \caption{The averaged PSNR, SSIM, FSIM, ERGA and SAM of the recovered results on hyperspectral image "Cuprite" by Tmac, MF-TV, TNN, PSTNN and our model with different sampling rates. The best values are highlighted in bolder fonts.} \centering \label{table_HSI} \setlength{\tabcolsep}{1mm}{ \begin{tabular}{ccccccccc} \hline \hline &&&SR =0.025&&&& \\ PQI& nosiy& our model& MF-TV& TMac& PSTNN& TNN\\ PSNR & 7.666 & \textbf{34.595} & 26.115 & 21.25 & 13.387 & 22.783 \\ SSIM & 0.007 & \textbf{0.861} & 0.539 & 0.412 & 0.124 & 0.554 \\ FSIM & 0.48 & \textbf{0.916} & 0.765 & 0.755 & 0.613 & 0.775 \\ ERGA & 1043.633 & \textbf{50.383} & 237.074 & 235.594 & 539.574 & 245.333 \\ MSAM & 81.221 & \textbf{1.662} & 12.913 & 7.842 & 17.98 & 9.156 \\ \hline &&&SR = 0.05&&&&\\ PQI& nosiy& our model& MF-TV& TMac& PSTNN& TNN\\ PSNR & 7.779 & \textbf{38.202} & 34.684 & 28.945 & 20.621 & 26.579 \\ SSIM & 0.01 & \textbf{0.928} & 0.845 & 0.712 & 0.31 & 0.663 \\ FSIM & 0.471 & \textbf{0.960} & 0.915 & 0.846 & 0.735 & 0.836 \\ ERGA & 1030.139 & \textbf{41.898} & 89.372 & 93.352 & 234.445 & 154.292 \\ MSAM & 77.268 & \textbf{1.559} & 4.386 & 3.278 & 7.886 & 5.413 \\ \hline &&&SR = 0.1&&&&\\ PQI & nosiy & our model & MF-TV & TMac & PSTNN & TNN \\ PSNR & 8.013 &39.056 & \textbf{40.888} & 35.627 & 35.51 & 35.015 \\ SSIM & 0.014 &0.939 & \textbf{0.957} & 0.885 & 0.907 & 0.897 \\ FSIM & 0.451 &0.966 & \textbf{0.978} & 0.931 & 0.951 & 0.943 \\ ERGA & 1002.75 &34.544 & \textbf{34.263} & 44.518 & 54.421 & 57.537 \\ MSAM & 71.695 &\textbf{1.299} &1.46 & 1.445 & 2.072 & 2.192 \\ \hline \hline \end{tabular}} \end{table} \begin{figure*}[!t] \centering \subfloat[]{\includegraphics[width=0.15\linewidth]{video-Hall_SR=005_PSNR}}% \hfil \subfloat[]{\includegraphics[width=0.15\linewidth]{video-Hall_SR=01_PSNR}}% \hfil \subfloat[]{\includegraphics[width=0.15\linewidth]{video-Hall_SR=02_PSNR}}% \hfil \subfloat[]{\includegraphics[width=0.15\linewidth]{video-Hall_SR=005_SSIM}}% \hfil \subfloat[]{\includegraphics[width=0.15\linewidth]{video-Hall_SR=01_SSIM}}% \hfil \subfloat[]{\includegraphics[width=0.15\linewidth]{video-Hall_SR=02_SSIM}}% \caption{Sensitivity analysis of parameter $\gamma$ in video "hall" dataset. (a-c) Change in the MPSNR value: SR= 0.05, 0.1 and 0.2. (e-f) Change in the MSSIM value: 0.05, 0.1 and 0.2, respectively.} \label{parameter_analysis_hall} \end{figure*} \begin{figure*}[!t] \centering \subfloat[]{\includegraphics[width=0.15\linewidth]{MRI_SR=005_PSNR}}% \hfil \subfloat[]{\includegraphics[width=0.15\linewidth]{MRI_SR=01_PSNR}}% \hfil \subfloat[]{\includegraphics[width=0.15\linewidth]{MRI_SR=02_PSNR}}% \hfil \subfloat[]{\includegraphics[width=0.15\linewidth]{MRI_SR=005_SSIM}}% \hfil \subfloat[]{\includegraphics[width=0.15\linewidth]{MRI_SR=01_SSIM}}% \hfil \subfloat[]{\includegraphics[width=0.15\linewidth]{MRI_SR=02_SSIM}}% \caption{Sensitivity analysis of parameter $\gamma$ in MRI dataset. (a-c) Change in the MPSNR value: SR= 0.05, 0.1 and 0.2. (e-f) Change in the MSSIM value: 0.05, 0.1 and 0.2, respectively.} \label{parameter_analysis_MRI} \end{figure*} \begin{figure*}[!t] \centering \subfloat[SR=0.025]{\includegraphics[width=0.15\linewidth]{HSI_SR=0025_PSNR}}% \hfil \subfloat[SR=0.05]{\includegraphics[width=0.15\linewidth]{HSI_SR=005_PSNR}}% \hfil \subfloat[SR=0.1]{\includegraphics[width=0.15\linewidth]{HSI_SR=01_PSNR}}% \hfil \subfloat[SR=0.025]{\includegraphics[width=0.15\linewidth]{HSI_SR=0025_SSIM}}% \hfil \subfloat[SR=0.05]{\includegraphics[width=0.15\linewidth]{HSI_SR=005_SSIM}}% \hfil \subfloat[SR=0.1]{\includegraphics[width=0.15\linewidth]{HSI_SR=01_SSIM}}% \caption{Sensitivity analysis of parameter $\gamma$ in HSI dataset. (a-c) Change in the MPSNR value: SR= 0.025, 0.05 and 01. (e-f) Change in the MSSIM value: 0.025, 0.05 and 0.1, respectively.} \label{parameter_analysis_HSI} \end{figure*} \begin{table*} \centering \caption{Parameters setting in the proposed algorithm} \label{table:parameter_setting} \begin{tabular}{ccccc ccccc ccc} \hline & &Vdieo-suzie& & &Video-hall& & &MRI dataset& & &HSI dataset& \\ \hline SR& 0.05& 0.1&0.2 &0.05& 0.1&0.2 &0.05& 0.1&0.2 &0.025& 0.05&0.1\\ $\gamma$& 2.3&2.5&2.7&1.7&2.6&2.6&1.3&2.5&3.0&3.5&5.5&5.7\\ \hline \end{tabular} \end{table*} \subsection{Discussion} Considering the fact that the $\gamma$ in $\mathbf{X}_n$ and $\mathbf{A}_n$ have certain proportional relationship, we simply set the $\gamma$ in $\mathbf{X}_n$ as 0.1, and tune the $\gamma$ in $\mathbf{A}_n$ carefully. For experiments on video datasets , MRI and HSI dataset, Fig. \ref{parameter_analysis_hall}, Fig. \ref{parameter_analysis_MRI} and Fig. \ref{parameter_analysis_HSI} show the effect of parameter $\gamma$ on PSNR and SSIM at different sampling rates, respectively. To enhance the repeatability of our model, we list the optimal $\gamma$ of various datasets at different sampling rates in Table \ref{table:parameter_setting}. In addition, we manually set both $\tau_n$ and $\lambda_n$ as 0.01. \section{Conclusions} \label{conclusion} In this paper, we propose a novel double low-rank tensor model based on multi-mode matrix decomposition for tensor completion. Instead of using the traditional single nuclear norm or its relaxation to represent the low-rank prior of underlying tensor directly, we first apply parallel matrix factorization to all modes of underlying tensor, then, a novel double nonconvex $L_{\gamma}$ norm is designed to represent the underlying joint-manifold drawn from the mode factorization factors. An BSUM based algorithm is designed to efficiently solve the proposed model, and it can be demonstrated that our numerical scheme converges to the coordinatewise minimizers. The proposed model has been evaluated on three types of public tensor datasets, which show that our algorithm can complete a variety of low-rank tensors with significantly fewer samples than the compared methods. \section*{Acknowledgment} The authors would like to express their thanks to Dr. C. Lu, Dr. Y. Xu, Dr. T. Ji and Dr. T. Jiang for sharing their codes for the tested methods. In addition, this research is supported by the Fundamental Research Funds for the Central Universities under Grant No. 2452019073 and the National Natural Science Foundation of China under Grant No. 61876153. \ifCLASSOPTIONcaptionsoff \newpage \fi \bibliographystyle{IEEEtran \section{Introduction} Tensors, as a generalization of vectors and matrices, arise in many data processing applications and have attracted great interests. For instance, video inpainting \cite{tensor_video}, magnetic resonance imaging (MRI) data recovery \cite{tensor_MRI, MRI_tensor}, 3D image reconstruction \cite{tensor_3dimage, tensor_3DReconstruction}, high-order web link analysis [16], hyperspectral image (HSI) or multispectral image recovery \cite{tensor_HSI, chen2018tensor}, personalized web search \cite{tensor_web}, and seismic data reconstruction \cite{tensor_seismic_data}. Tensor completion tries to recover a low-rank tensor from its partially observed entries. A large number of tensor completion methods have been proposed and successfully used in many applications. Among them, the tensor rank minimization based methods are considered as state-of-the-art methods with promising performance, and their robustness to noisy and missing data has also been proven \cite{lu2019TRPCA}. However, due to the nonunique definitions of the tensor rank, it is extremely hard to directly solve the tensor rank minimization problem. To overcome this issue, many researchers have been devoted to defining the tensor rank based on the different decomposition methods, such as the matrix factorization \cite{LMaFit}, CANDECOMP/PARAFAC (CP) decomposition \cite{CP}, Tucker decomposition \cite{tucker_1, ZENG_HSI_tensor}, tensor singular value decomposition (t-SVD) \cite{t_SVD}, tensor train \cite{tensor_train_TingzhuHuang} and tensor ring \cite{tensor_ring_YipengLiu}. The commonly used definitions of tensor rank are CP-rank, Tucker-rank, multi-rank and tubal-rank based on t-SVD. However, it is NP-hard to solve the minimization problem of CP-rank which has no relaxation and certain limitations in applications. Although the Tucker-rank, relying on matrix ranks, is relatively simple, it is also NP-hard to directly minimizing the Tucker-rank problem. To tackle this difficulty, the sum of nuclear norm (SNN) \cite{HaLRTC} is introduced as a convex relaxation of the Tucker-rank. Specifically, SNN is defined by the sum of nuclear norms of the unfolding matrices along all dimensions in tensors. Due to the similar approximation to matrix case and convenient calculation algorithm, SNN is widely used in the tensor completion task \cite{tensor_Qrank}. Besides, the tensor multi-rank and tubal-rank induced from t-SVD are computable. As a tightest convex surrogate for tensor multi-rank, the tensor nuclear norm (TNN) \cite{t_SVD} is defined as the sum of the matrix nuclear norms of each frontal slice in the Fourier transformed tensor. TNN has shown its effectiveness to keep the intrinsic structure of tensors and attracted extensive attention for tensor completion problems in recent years \cite{lu2019TRPCA}. Due to the convexity of matrix nuclear norms, SNN and TNN have limitation in the accuracy of approximation to the tensor rank function. Recently, a number of studies \cite{list_nonconvex,Original_BFMN}, both practically and theoretically, have shown that the nonconvex approximation of rank function can provide better estimation accuracy and variable selection consistency than the nuclear norm. For example, a partial sum of the tensor nuclear norm (PSTNN) is proposed as a nonconvex surrogate of the tensor rank by Jiang et al. \cite{PSTNN}; Xue et al. \cite{xue2019nonconvex} unfold the underlying tensor along its all modes and use a nonconvex logarithmic surrogate function to refine the rank approximation. Actually, except for the logarithmic function used by Xue et al., a series of nonconvex surrogate are proposed for approximating to the rank function better, such as the minimax concave function \cite{Folded_concave}, log-sum function \cite{logsum_penalty}, log-determinant function \cite{ji_nonlogDet}, $L_p$ norm for $p\in (0, 1)$ \cite{lysaker_noise_2004_10_27,burger_nonlinear_2006_10_28}, $L_{1/2}$ norm \cite{lou_L1L2} and $\gamma$ norm \cite{Non_LRMA}. In addition, TNN and PSTNN involve the singular value decompositions (SVDs) of many matrices, which are time-consuming. To cope with this issue, Xu et al. \cite{Tmac} propose a parallel matrix factorization low-rank tensor completion model (TMac), which obtain promising results with less running time than TNN and PSTNN. Further, combined with the total variation (TV) regularization, Ji et al. \cite{MFTV} propose TV regularized low-rank matrix factorization method (MF-TV) for low-rank tensor completion problems. \begin{figure*}[!t] \centering \subfloat[Original image]{\includegraphics[width=0.23\linewidth]{Image_video_b94.png} \hfil \subfloat[Our model]{\includegraphics[width=0.23\linewidth]{Image_video_b94_sr005LxLxNN}}% \hfil \subfloat[TMac]{\includegraphics[width=0.23\linewidth]{Image_video_b94_sr005Tmac}}% \hfil \subfloat[TNN]{\includegraphics[width=0.23\linewidth]{Image_video_b94_sr005TNN} \caption{The completed results of Suzie with 95\% missing entries by different methods. From (a) to (d), the original image, the result by our model, Tmac, and TNN, respectively.} \label{TNN_Tamc_our-model_figure_video_sr0.05} \end{figure*} Although the above-mentioned low-rank tensor completion methods show great success in dealing with various issues, three major open questions have yet to be addressed. Firstly, in the tensor rank approximations based on tensor decomposition or matrix decomposition, the low-rank priors of underlying tensor are only explored by the convex or nonconvex relaxations of original tensor rank function, while the low-rank priors of factors obtained by the decomposition are not investigated further. Secondly, TNN or PSTNN based methods \cite{TNN, PSTNN} need to compute lots of SVDs, which become very slow or even not applicable for large-scale problems \cite{Tmac}. Thirdly, the aforementioned methods adopt single surrogate of tensor rank function, which would cause suboptimal solution of the low-rank tensor completion problems \cite{T_Sp} and can not fully explore the low-rank priors in all modes, especially when the tensor data is heavily contaminated or the sampling rate is very low. One can see an example in Fig. \ref{TNN_Tamc_our-model_figure_video_sr0.05}. In this paper, motivated and convinced by the much better performance of models that utilize the low-ranknesses in all mode in tensors \cite{HaLRTC, Tmac}, instead of using the single surrogate of tensor rank function to represent the low-rank prior in underlying tensor directly, we first apply parallel matrix factorization to all modes of underlying tensor. Further, the novel double $L_{\gamma}$ norm, a kind of nonconvex penalty, is designed to represent the underlying joint-manifold drawn from the mode factorization factors. By exploiting this auxiliary information, our method leverages low-rank decomposition and low-rank approximation, which help to accurately estimate the mode factors and missing entries. An block successive upper-bound minimization method-based algorithm is designed to efficiently solve the proposed model, and it can be demonstrated that our numerical scheme converge to the coordinatewise minimizers. The proposed model has been evaluated on three types of public tensor datasets, which show that our algorithm can recover a variety of low-rank tensors with significantly fewer samples than the compared methods. The rest of this paper is organized as follows. Section \ref{notation} introduces some notations about tensors and the operations. Section \ref{related works} reviews the related works. In Section \ref{the proposed model}, the proposed model is presented and its optimization is deduced in detail. In Section \ref{Numerical experiments}, the proposed model is evaluated on several public tensor datasets. Section \ref{conclusion} gives the conclusions. \section{Preliminary} \label{notation} \subsection{Notations} In this paper, following \cite{Tmac}, vector, matrix and tensor are denoted as bold lower-case letter $\mathbf{x}$, bold upper-case letter $\mathbf{X}$ and caligraphic letter $\mathcal{X}$, respectively. Let $x_{i_{1} \ldots i_{N}}$ represent the $\left(i_{1}, \ldots, i_{N}\right)$-th component of an $N$-way tensor $\mathcal{X}$. Then, for $\mathcal{X}, \mathcal{Y} \in \mathbb{R}^{I_{1} \times \ldots \times I_{N}},$ their inner product is defined as \begin{equation} \label{equation:inner_product} \langle\mathcal{X}, \mathcal{Y}\rangle=\sum_{i_{1}=1}^{I_{1}} \cdots \sum_{i_{N}=1}^{I_{N}} x_{i_{1} \cdots i_{N}} y_{i_{1} \cdots i_{N}}. \end{equation} Based on (\ref{equation:inner_product}), the \textbf{Frobenius norm} of a tensor $\mathcal{X}$ is defined as $\|\mathcal{X}\|_{\text{F}}=\sqrt{\langle\mathcal{X}, \mathcal{X}\rangle}$. \textbf{Fibers} of tensor $\mathcal{X}$ are defined as a vector obtained by fixing all indices of $\mathcal{X}$ except one, and \textbf{slices} of $\mathcal{X}$ are defined as a matrix by fixing all indices of $\mathcal{X}$ except two. The \textbf{mode-$n$ matricization}/\textbf{unfolding} of $\mathcal{X} \in \mathbb{R}^{I_{1} \times \ldots \times I_{N}}$ is denoted as a matrix $\mathbf{X}_{(n)} \in \mathbb{R}^{I_{n} \times \Pi_{j \neq n} I_{j}}$ with columns being the mode-$n$ fibers of $\mathcal{X}$ in the lexicographical order. Furthermore, to clearly represent the matricization process, we define \textbf{unfold}$_{n}(\mathcal{X})=\mathbf{X}_{(n)}$, and \textbf{fold}$_{n}$ is the inverse of \textbf{unfold}$_{n}$, i.e., \textbf{fold} $_{n}\left(\text { \textbf{unfold} }_{n}(\mathcal{X})\right)=\mathcal{X}$. The $n$-rank of an $N$-way tensor $\mathcal{X},$ denoted as $\operatorname{rank}_{n}(\mathcal{X}),$ is the rank of $\mathbf{X}_{(n)},$ and the rank of $\mathcal{X}$ is defined as an array: \begin{equation} \operatorname{rank}(\mathcal{X})=\left(\operatorname{rank}\left(\mathbf{X}_{(1)}\right), \cdots, \operatorname{rank}\left(\mathbf{X}_{(N)}\right)\right). \end{equation} \subsection{Operators} \label{operators} The \textbf{Proximal Operator} of is defined as follows: \begin{equation} \label{equation:PPA_0} \operatorname{prox}_{f}(v):=\arg \min _{u} f(u)+\frac{\rho}{2}\|u-v\|^{2}, \end{equation} where $f(u)$ is convex; $\rho$ is the proximal parameter. Then, the minimization of $\{f(u)\}$ is equivalent to \begin{equation} \arg \min _{u} f(u)+\frac{\rho}{2}\|u-u^k\|^{2}, k=1,2,\cdots, \end{equation} where $u^k$ is the last update of $u$. We define the \textbf{Projection Operator} as follows: \begin{equation} \left(\mathcal{P}_{\Omega}(\mathcal{Y})\right)_{i_{1} \cdots i_{N}}=\left\{\begin{array}{ll} {y_{i_{1}, \cdots, i_N,}} & {\left(i_{1}, \cdots, i_{N}\right) \in \Omega} \\ {0,} & {\text { otherwise }} \end{array}\right. \end{equation} where $\Omega$ is the index set of observed entries. The function of $\mathcal{P}_{\Omega}$ is to keep the entries in $\Omega$ and zeros out others. \section{Related Works} \label{related works} We first introduce related tensor completing methods based on the tensor rank minimization. Given a partial observed tensor $\mathcal{F} = \mathcal{P}_{\Omega}(\mathcal{Y}) \in \mathbb{R}^{I_{1} \times I_{2} \times \cdots \times I_{N}}$, tensor completion task is to recover a low-rank tensor $\mathcal{Y}$ from $\mathcal{F}$, according to the priors of underlying tensor $\mathcal{Y}$. In the past decade, TNN induced by t-SVD \cite{t_SVD} has been widely used for 3-order low-rank tensor completion \cite{TNN}. The TNN based method aims to recover a low-rank tensor by penalizing the nuclear norm of each front slice in the Fourier transformed domain, \begin{equation} \label{TNN} \arg\min_{\mathcal{Y}} \frac{1}{I_{3}} \sum_{i=1}^{I_{3}}\left\|\bar{\mathbf{Y}}^{(i)}\right\|_{*} , s.t.~ \mathcal{P}_{\Omega}(\mathcal{Y})=\mathcal{F}, \end{equation} where $\bar{\mathbf{Y}}^{(i)} \in \mathbb{C}^{I_{1} \times I_{2}}$ denotes the $i$-th frontal slice of $\bar{\mathcal{Y}}$, $\bar{\mathcal{Y}}=\operatorname{fft}(\mathcal{Y},[],3)$ denotes the fast Fourier transform of $\mathcal{Y}$ along the third dimension. \begin{figure*} \centering \includegraphics[width=1\linewidth]{3-model-lowrank-Lx-norm} \caption{Flowchart of the proposed low-rank tensor approximation: nonconvex tensor $L_{\gamma}$ norm.} \label{fig:3-model-lowrank-lx-norm} \end{figure*} Then, to alleviate bias phenomenons of the TNN minimization in tensor completion tasks, Jiang et al. \cite{PSTNN} represent the low-rank prior of underlying tensor by using the PSTNN. The PSTNN regularized tensor completion model is formulated as follows: \begin{equation} \label{PSTNN} \arg\min_{\mathcal{Y}} \frac{1}{I_{3}} \sum_{i=1}^{I_{3}}\left\|\bar{\mathbf{Y}}^{(i)}\right\|_{p=M}, s.t.~ \mathcal{P}_{\Omega}(\mathcal{Y})=\mathcal{F}, \end{equation} where $$\|\bar{\mathbf{Y}}^{(i)}\|_{p=M} := \sum_{j=M+1}^{\min (I_1, I_2)} \sigma_{j}(\bar{\mathbf{Y}}^{(i)}),$$ and $\sigma_{j}(\bar{\mathbf{Y}}^{(i)})$ denotes the $j$-th largest singular value of $\bar{\mathbf{Y}}^{(i)}$. To reduce the burden of calculating SVDs in TNN and PSTNN, Liu et al. \cite{HaLRTC} unfold the $N$-order tensor into multiple modal matrices along the direction of each mode, and then use the sum of the nuclear norms of these modal matrices, i.e., SNN, to describe the low-rank structure of the underlying tensor. With that definition, the completion model is formulated as follows: \begin{equation} \label{} \arg\min_{\mathcal{Y}} \sum_{n=1}^{N} \alpha_i \left\|\mathbf{Y}_{(n)}\right\|_{*}, s.t., \mathcal{P}_{\Omega}(\mathcal{Y})=\mathcal{F}. \end{equation} Furthermore, Xu et al. \cite{Tmac} propose a Tmac model by using parallel matrix factorization, which obtain promising results with less computational complexity than TNN and PSTNN, \begin{equation} \label{Tmac} \begin{aligned} &\arg\min _{\mathcal{Y}, \mathbf{X}, \mathbf{A}} \sum_{n=1}^{N} \frac{\alpha_{n}}{2}\left\|\mathbf{Y}_{(n)}-\mathbf{A}_{n} \mathbf{X}_{n}\right\|_{F}^{2},\\ &\text { s.t. } \quad \mathcal{P}_{\Omega}(\mathcal{Y})=\mathcal{F}, \end{aligned} \end{equation} where $\alpha_n$ are weights and satisfy $\sum_{n=1}^{N}\alpha_n=1$. Although the above-mentioned low-rank tensor completion methods report success on dealing with a large variety of tasks, there are several open issues which have yet to be addressed. Firstly, the above approaches either explore the low-rank prior lying in only one mode of the underlying tensor or directly represent the low-rank prior of original tensor by using low-rank decomposition. They do not further explore the prior of the factors (e.g., $\mathbf{A}_n, \mathbf{X}_n$ in (\ref{Tmac})) obtained by low-rank decomposition. Secondly, TNN based methods \cite{TNN, PSTNN, lu2019TRPCA} need to compute lots of SVDs, which is time-consuming or even not applicable for large-scale problems \cite{Tmac}. Thirdly, these methods adopt single surrogate of tensor rank function, which would cause suboptimal solution of the low-rank tensor completion problems \cite{T_Sp} and can not fully explore the low-rank priors in all modes, especially when the tensor data is heavily contaminated or the sampling rate is very low. One can see an example in Fig. \ref{TNN_Tamc_our-model_figure_video_sr0.05}, in which the video "suzie" with 95\% missing entries, it can be seen that our model restores most of the structural information of the video, while the videos restored by the methods adopt single surrogate contain only the outline of the images. \section{Double nonconvex $L_{\gamma}$ norm based low-rank approximation for tensor completion } \label{the proposed model} In the following, a novel double nonconvex $L_{\gamma}$ norm based low-rank approximation of tensor multi-modes (LRATM) is introduced firstly. Then, the optimization of the proposed LRATM model is deduced in detail. \subsection{LRATM Model} For a tensor $\mathcal{Y}\in \mathbb{R}^{I_{1} \times I_{2} \times \cdots \times I_{N}}$, to enhance the flexibility for handling different correlations along different modes in the underlying tensor, while to effectively explore the underlying joint-manifold drawn from the mode factorization factors, we first formulate a nonconvex novel tensor $L_{\gamma}$ norm, \begin{equation} \begin{aligned} &\left\|\mathcal{Y}\right\|_{\gamma}= \sum_{n=1}^{N} (\tau_n \left\|\mathbf{X}_{n}\right\|_{\gamma}+\lambda_n \left\|\mathbf{A}_{n}\right\|_{\gamma}), \end{aligned} \end{equation} where $\mathbf{Y}_{(n)}=\mathbf{A}_{n} \mathbf{X}_{n}$, and $$\left\|\mathbf{X}\right\|_{\gamma}:=\sum_{t=1}^{\min \{p, q\}}\left(1-e^{-\sigma_{t}(\mathbf{X}) / \gamma}\right)$$ is a nonconvex approximation of $rank(\mathbf{X})$, and $\sigma_{t}(\mathbf{X})$ is the $t$-th biggest singular value of $\mathbf{X} \in \mathbb{R}^{p \times q}$. $\tau_n$ and $\lambda_n$ are non-negative constants that balance the two terms. Then, our tensor $L_{\gamma}$ norm based low-rank approximation model for low-rank tensor completion, i.e., the proposed LRATM model is written as \begin{equation} \label{BMF_LRTC} \begin{aligned} \arg\min{\left\|\mathcal{Y}\right\|_{\gamma}}=&\arg\min_{\mathcal{Y},\mathbf{X},\mathbf{A}} \sum_{n=1}^{N} (\tau_n \left\|\mathbf{X}_{n}\right\|_{\gamma}+\lambda_n \left\|\mathbf{A}_{n}\right\|_{\gamma}), \\ &s.t., ~ \mathbf{Y}_{(n)}=\mathbf{A}_{n} \mathbf{X}_{n}, \mathcal{P}_{\Omega}(\mathcal{Y})=\mathcal{F}. \end{aligned} \end{equation} To better understand the proposed LRATM model, we plot the flowchart of the proposed low-rank tensor approximation in Fig. \ref{fig:3-model-lowrank-lx-norm}. It can be seen that the video, MRI and HSI in the first column essentially can be viewed as 3-order tensors in the second column. When we unfold the 3-order tensor in three directions, the low-rank structure of all the $N$ modes can be explored by using parallel matrix decomposition, i.e., $\mathbf{Y}_{(n)}=\mathbf{A}_{n} \mathbf{X}_{n}, n=1,2,\cdots, N$, which is computationally much cheaper than SVD. The decomposed factors have practical physical meaning, $\mathbf{A}_n$ represents a library (each column contains a signature of the $n$-th mode direction), and $\mathbf{X}_n$ is called an encoding. For example, in the unmixing problem for HSI \cite{HSI_unmixing}, each column of $\mathbf{A}_3$ contains a spectral signature, and each row of $\mathbf{X}_3$ contains the fractional abundances of a given endmembers. This interpretation is also valid for the mode-3 unfolding of video and MRI. The above parallel matrix decomposition can effectively explore the low-rank structure of underlying tensor, but the prior information contained in the factor matrices ($\mathbf{A}_{n}, \mathbf{X}_{n}$) is not explored at all. Therefore, to further enhance the potential capacity of tensor completion models, it is necessary to design new and reasonable formulas to explore the priors in the factor matrices. Here, we propose the novel nonconvex double $L_{\gamma}$ norm to formulate the underlying joint-manifold drawn from the mode factorization factors $\mathbf{A}_n$ and $\mathbf{X}_n$. The superiority of $L_{\gamma}$ norm over nuclear norm and other nonconvex penalties is shown in the fifth column of Fig. \ref{fig:3-model-lowrank-lx-norm}. It is obvious that the red curve of $L_{\gamma}$ norm is closer to the green curve of $L_0$ norm (rank function) than other nonconvex penalties. \subsection{Optimization Procedure of LRATM} In this section, the proposed model is solved by using the block successive upper-bound minimization (BSUM) \cite{BSUM} method. The objective function of the proposed LRATM model(\ref{BMF_LRTC}) can be formulated as follows: \begin{equation} \begin{aligned} f(\mathbf{X}, \mathbf{A}, \mathcal{Y})=\sum_{n=1}^{N}& \left(\frac{\alpha_{n}}{2}\left\|\mathbf{Y}_{(n)}-\mathbf{A}_{n} \mathbf{X}_{n}\right\|_{\text{F}}^{2}+\tau_n \left\|\mathbf{X}_{n}\right\|_{\gamma}\right.\\ &\left.+\lambda_n \left\|\mathbf{A}_{n}\right\|_{\gamma}\right). \end{aligned} \end{equation} According to the proximal operator (\ref{equation:PPA_0}), the update can be written as: \begin{equation} \label{equation_original_PPA} p(\mathcal{S}, \mathcal{S}^k)=f\left(\mathcal{S}, \mathcal{S}^k\right)+\frac{\rho}{2}\left\|\mathcal{S}-\mathcal{S}^{k}\right\|_{\text{F}}^{2}, \end{equation} where $\rho>0$ is a positive constant; $\mathcal{S}=(\mathbf{X}, \mathbf{A}, \mathcal{Y})$ and $\mathcal{S}^{k}=\left(\mathbf{X}^{k}, \mathbf{A}^{k}, \mathcal{Y}^{k}\right)$. Let \begin{equation} \left\{\begin{array}{l} g_{1}\left(\mathbf{X}, \mathcal{S}_{1}^{k}\right)=f\left(\mathbf{X}, \mathbf{A}^{k}, \mathcal{Y}^{k}\right)+\frac{\rho}{2}\left\|\mathbf{X}-\mathbf{X}^{k}\right\|_{\text{F}}^{2}, \\ g_{2}\left(\mathbf{A}, \mathcal{S}_{2}^{k}\right)=f\left(\mathbf{X}^{k+1}, \mathbf{A}, \mathcal{Y}^{k}\right)+\frac{\rho}{2}\left\|\mathbf{A}-\mathbf{A}^{k}\right\|_{\text{F}}^{2,} \\ g_{3}\left(\mathcal{Y}, \mathcal{S}_{3}^{k}\right)=f\left(\mathbf{X}^{k+1}, \mathbf{A}^{k+1}, \mathcal{Y}\right)+\frac{\rho}{2}\left\|\mathcal{Y}-\mathcal{Y}^{k}\right\|_{\text{F}}^{2}, \end{array}\right. \end{equation} where \begin{equation} \left\{\begin{array}{l} S_{1}^{k}=\left(\mathbf{X}^{k}, \mathbf{A}^{k}, \mathcal{Y}^{k}\right),\\ S_{2}^{k}=\left(\mathbf{X}^{k+1}, \mathbf{A}^{k}, \mathcal{Y}^{k}\right),\\ S_{3}^{k}=\left(\mathbf{X}^{k+1}, \mathbf{A}^{k+1}, \mathcal{Y}^{k}\right). \end{array}\right. \end{equation} Then, problem (\ref{equation_original_PPA}) can be rewritten as follows: \begin{equation} \label{equation:XAY} \left\{\begin{array}{l} \displaystyle \mathbf{X}^{k+1}=\arg\min_{\mathbf{X}} g_{1}\left(\mathbf{X}, \mathcal{S}_{1}^{k}\right), \\ \displaystyle \mathbf{A}^{k+1}=\arg\min_{\mathbf{A}} g_{2}\left(\mathbf{A}, \mathcal{S}_{2}^{k}\right), \\ \displaystyle \mathcal{Y}^{k+1}=\arg\min_{\mathcal{P}_{\Omega}(\mathcal{Y})=\mathcal{F}} g_{3}\left(\mathcal{Y}, \mathcal{S}_{3}^{k}\right). \end{array}\right. \end{equation} \subsubsection{Update $\mathbf{X}_n$} With fixing other variables, the optimization subproblem with respect to $\mathbf{X}_n, n=1,2,\cdots,N$, in (\ref{equation:XAY}) can be written as follows: \begin{equation} \label{equation_X} \begin{aligned} \arg\min_{\{\mathbf{X}_n\}_{n=1}^{N}} \sum_{n=1}^{N}& \left(\frac{\alpha_{n}}{2}\left\|\mathbf{Y}_{(n)}-\mathbf{A}_{n} \mathbf{X}_{n}\right\|_{\text{F}}^{2}+\tau_n \left\|\mathbf{X}_{n}\right\|_{\gamma}\right.\\ &\left.+\frac{\rho_n}{2}\left\|\mathbf{X}_n-\mathbf{X}_n^{k}\right\|_{\text{F}}^{2}\right). \end{aligned} \end{equation} To efficiently solve the above optimization, we first introduce auxiliary variables $\mathbf{X}_{n}=\mathbf{Z}_{n}, n=1,2,\cdots,N$. Then, by the augmented Lagrangian multiplier (ALM) method, the optimization subproblem (\ref{equation_X}) can be rewritten as: \begin{equation} \label{equation:X_alm} \begin{aligned} &\arg\min_{\{\mathbf{X}_n, \{\mathbf{Z}_n\}_{n=1}^{N}} \sum_{n=1}^{N} \left(\frac{\alpha_{n}}{2}\left\|\mathbf{Y}_{(n)}-\mathbf{A}_{n} \mathbf{X}_{n}\right\|_{\text{F}}^{2}+\tau_n \left\|\mathbf{Z}_{n}\right\|_{\gamma}\right.\\ &\left.+\frac{\rho_n}{2}\left\|\mathbf{X}_n-\mathbf{X}_n^{k}\right\|_{\text{F}}^{2}+\left\langle\Gamma_{n}^\mathbf{X}, \mathbf{X}_n-\mathbf{Z}_n\right\rangle +\frac{\rho_{n}}{2}\left\|\mathbf{X}_{n}-\mathbf{Z}_{n}\right\|_{\text{F}}^{2}\right). \end{aligned} \end{equation} where $\Gamma_{n}^\mathbf{X}$ are Lagrangian multipliers. With other variables fixed, the minimization subproblem for $\mathbf{Z}_n$ can be deduced from (\ref{equation:X_alm}) as follows: \begin{equation} \label{equation:Zn} \mathbf{Z}_n^{k+1}= \arg \min_{\mathbf{Z}_n} \left\|\mathbf{Z}_{n}\right\|_{\gamma}+\frac{\hat{\rho}_{n}}{2}\left\|\mathbf{Z}_{n}-\mathbf{P}_n^k\right\|_{\text{F}}^{2}, \end{equation} where $\hat{\rho}_{n}=\rho_{n}/\tau_n$, $\mathbf{P}_n^k=\mathbf{X}_{n}^{k}+\Gamma_{n}^{\mathbf{X}}/\rho_n$. Let $\sigma_{1}^{k} \geq \sigma_{2}^{k} \geq \cdots \geq \sigma_{t_n}^{k}$ represent the singular values of $\mathbf{Z}_n^{k} \in \mathbb{R}^{r_n \times s_n}$ with $t_n=\min \left\{r_n, s_n\right\}$ and $\nabla \phi\left(\sigma_{n}^{k}\right)$ denote the gradient of $\phi(x) = 1-e^{-x/\gamma}$ at $\sigma_{n}^{k} .$ Let $$f(\mathbf{Z}_n)=\frac{1}{2}\left\|\mathbf{Z}_n-\mathbf{P}_n^k\right\|_{\text{F}}^{2}.$$ It is easy to prove that the gradient of $f(\mathbf{Z}_n)$ is Lipschitz continuous by setting the Lipschitz constant being $1.$ As stated in \cite{Non_LRMA}, considering the nonascending order of singular values and according to the antimonotone property of gradient of our nonconvex function, we have \begin{equation} \begin{aligned} & 0 \leq \nabla \phi\left(\sigma_{1}^{k}\right) \leq \nabla \phi\left(\sigma_{2}^{k}\right) \leq \cdots \leq \nabla \phi\left(\sigma_{t_n}^{k}\right), \\ & \phi\left(\sigma_{i}(\mathbf{Z}_n)\right) \leq \phi\left(\sigma_{i}^{k}\right)+\nabla \phi\left(\sigma_{i}^{k}\right)\left(\sigma_{i}(\mathbf{Z}_n)-\sigma_{i}^{k}\right), \end{aligned} \label{equ:gradient} \end{equation} where $i=1,2,\cdots,t_n$. Following (\ref{equ:gradient}), the subproblem with respect to $\mathbf{Z}_n$ (\ref{equation:Zn}) can be written as following relaxation: \begin{equation} \begin{split} &\arg \min _{\mathbf{Z}_n} \frac{1}{\hat{\rho}_{n}} \sum_{n=1}^{t_n} \phi\left(\sigma_{n}^{k}\right)+\nabla \phi\left(\sigma_{n}^{k}\right)\left(\sigma_{n}(\mathbf{Z}_n)-\sigma_{n}^{k}\right)+f(\mathbf{Z}_n) \\ &=\arg \min _{\mathbf{Z}_n} \frac{1}{\hat{\rho}_{n}} \sum_{n=1}^{t_n} \nabla \phi\left(\sigma_{n}^{k}\right) \sigma_{n}(\mathbf{Z}_n)+\frac{1}{2}\left\|\mathbf{Z}_n-\mathbf{P}_{n}^{k}\right\|_{\text{F}}^{2}. \end{split} \label{equ:relaxation} \end{equation} Then, based on \cite{lu_nonconvex, Non_LRMA}, the solution of (\ref{equ:relaxation}) can be efficiently obtained by generalized weight singular value thresholding (WSVT) \cite{WSVT} , as shown in Lemma 1. \noindent\textbf{Lemma 1}: For any $1 / \hat{\rho}_{n}>0$, the given data $\mathbf{P}_n^k=\mathbf{X}_{n}^{k}+\Gamma_{n}^{\mathbf{X}}/\rho_n$, and $0 \leq \nabla \phi\left(\sigma_{1}^{k}\right) \leq \nabla \phi\left(\sigma_{2}^{k}\right) \leq \cdots \leq \nabla \phi\left(\sigma_{t_n}^{k}\right)$, a globally optimal solution $\mathbf{Z}_n^{*}$ to (\ref{equ:relaxation}) is given as follows: \begin{equation} \label{equation_solution_Zn} \quad \mathbf{Z}_n^{k+1}= \operatorname{WSVT}\left(\mathbf{P}_n^{k}, \frac{\nabla \phi}{\hat{\rho}_{n}}\right) =\mathbf{U} \mathbf{S}_{\frac{\nabla \phi}{\hat{\rho}_{n}}}(\mathbf{\Sigma}) \mathbf{V}^{T}, \end{equation} where $\mathbf{P}_n^{k}=\mathbf{U} \mathbf{\Sigma} \mathbf{V}^{T}$ is the SVD of $\mathbf{P}_n^{k}$; $$\mathbf{S}_{\frac{\nabla \phi}{\hat{\rho}_{n}}}(\mathbf{\Sigma})=\operatorname{Diag}\left\{\max \left(\mathbf{\Sigma}_{ii}-\frac{\nabla \phi \left( \mathbf{\sigma}_{i}^{k}\right)}{\hat{\rho}_{n}}, 0\right)\right\},$$ and $i=1,2,\cdots,t_n$. With other variables fixed, the minimization subproblem for $\mathbf{X}_n$, $n=1,2,\cdots, N$, can be deduced from (\ref{equation:X_alm}) as follows: \begin{equation} \label{equationforX} \begin{aligned} \mathbf{X}_n^{k+1}&= \arg\min_{\mathbf{X}_n}\frac{\alpha_{n}}{2}\left\|\mathbf{Y}_{(n)}-\mathbf{A}_{n}^{k} \mathbf{X}_{n}\right\|_{\text{F}}^{2}\\ &+\frac{\rho_{n}}{2}\left\|\mathbf{X}_{n}-\frac{\mathbf{Z}_{n}^{k+1}-\Gamma_{n}^k/\mu_n+\mathbf{X}_n^{k}}{2}\right\|_{\text{F}}^{2}. \end{aligned} \end{equation} They are convex and have the following closed-form solutions \begin{equation} \label{equation:solution_Xn} \begin{aligned} \mathbf{X}_n^{k+1}=&\frac{1}{2}(\alpha_{n}\mathbf{A}_n^T\mathbf{A}_n+2\rho_n \mathbf{I}_n)^{-1}\left[2\alpha_{n}\mathbf{A}_n^T\mathbf{Y}_{(n)}\right.\\ &\left. +\mu_n \left(\mathbf{Z}_{n}^{k+1}-\Gamma_{n}^k/\mu_n+\mathbf{X}_n^{k}\right)\right]. \end{aligned} \end{equation} The Lagrangian multipliers $\Gamma_{n}^{\mathbf{X}}$ can be updated by the following equation \begin{equation} \label{equation:Lambda_2} \Gamma_{n}^{\mathbf{X}} = \Gamma_{n}^{\mathbf{X}} + \mathbf{X}_n-\mathbf{Z}_n. \end{equation} \subsubsection{Update $\mathbf{A}_n$} With fixing other variables, the optimization subproblem with respect to $\mathbf{A}_n$, $n=1,2,\cdots,N$, in (\ref{equation:XAY}) can be written as follows: \begin{equation} \label{equation_A_aux} \begin{aligned} \arg\min_{\{\mathbf{A}_n\}_{n=1}^{N}} \sum_{n=1}^{N} & \left(\frac{\alpha_{n}}{2}\left\|\mathbf{Y}_{(n)}-\mathbf{A}_{n} \mathbf{X}_{n}\right\|_{\text{F}}^{2}+\lambda_n \left\|\mathbf{A}_{n}\right\|_{\gamma}\right.\\ &\left.+\frac{\rho_n}{2}\left\|\mathbf{A}_n-\mathbf{A}_n^{k}\right\|_{\text{F}}^{2}\right). \end{aligned} \end{equation} To efficiently solve the above optimization, we first introduce auxiliary variables $\mathbf{A}_{n}=\mathbf{J}_{n}, n=1,2,\cdots,N$. Then, by the ALM method, the problem (\ref{equation_A_aux}) can also be reformulated as \begin{equation} \label{equation:A_alm} \begin{aligned} & \arg\min_{\{\mathbf{A}_n,\mathbf{J}_n\}_{n=1}^{N}} \sum_{n=1}^{N} \left(\frac{\alpha_{n}}{2}\left\|\mathbf{Y}_{(n)}-\mathbf{A}_{n} \mathbf{X}_{n}\right\|_{\text{F}}^{2}+\lambda_n \left\|\mathbf{J}_{n}\right\|_{\gamma}\right.\\ & \left. +\frac{\rho_n}{2}\left\|\mathbf{A}_n-\mathbf{A}_n^{k}\right\|_{\text{F}}^{2} +\left\langle\Gamma_{n}^\mathbf{A},\mathbf{A}_n-\mathbf{J}_n\right\rangle +\frac{\rho_{n}}{2}\left\|\mathbf{A}_{n}-\mathbf{J}_{n}\right\|_{\text{F}}^{2}\right), \end{aligned} \end{equation} where $\Gamma_{n}^\mathbf{A}$ are the Lagrangian multipliers. With other variables fixed, the minimization subproblem for $\mathbf{J}_n$ can be deduced from (\ref{equation:A_alm}) as follows: \begin{equation} \displaystyle \mathbf{J}_n^{k+1}= \arg \min_{\mathbf{J}_n} \lambda_n \left\|\mathbf{J}_{n}\right\|_{\gamma}+\frac{\rho_{n}}{2}\left\|\mathbf{J}_{n}-\mathbf{Q}_n^k\right\|_{\text{F}}^{2}. \end{equation} where $\tilde{\rho}_{n}=\rho_{n}/\lambda_n$; $\mathbf{Q}_n^k=\mathbf{A}_{n}^{k}+\Gamma_{n}^{\mathbf{A}}/\rho_n$. Its solution can also be obtained by \textbf{Lemma 1} as follows: \begin{equation} \label{equation_solution_Jn} \quad \mathbf{J}_n^{k+1}=\operatorname{WSVT}\left(\mathbf{Q}_n^{k}, \frac{\nabla \phi}{\tilde{\rho}_{n}}\right). \end{equation} With other variables fixed, the minimization subproblem for $\mathbf{A}_n$, $n=1,2,\cdots, N$, can be deduced from (\ref{equation:A_alm}) as follows: \begin{equation} \label{equationforA} \begin{aligned} \mathbf{A}_n^{k+1}= &\arg\min_{\mathbf{A}_n} \frac{\alpha_{n}}{2}\left\|\mathbf{Y}_{(n)}-\mathbf{A}_{n} \mathbf{X}_{n}\right\|_{\text{F}}^{2}\\ &+\rho_{n}\left\|\mathbf{A}_{n}-\frac{\mathbf{J}_{n}^{k+1}-\Gamma_{n}^\mathbf{A}/\rho_n+\mathbf{A}_n^{k}}{2}\right\|_{\text{F}}^{2}. \end{aligned} \end{equation} They are also convex and have the following closed-form solutions \begin{equation} \label{equation_solution_An} \begin{aligned} \mathbf{A}_{n}^{k+1}=&\left(\mathbf{Y}_{(n)}^{k}\left(\mathbf{X}_{n}^{k+1}\right)^{T}+\rho_n (\mathbf{J}_{n}^{k+1}-\Gamma_{n}^\mathbf{A}/\rho_n+\mathbf{A}_n^{k})\right)\\ &\left(\mathbf{X}_{n}^{k+1}\left(\mathbf{X}_{n}^{k+1}\right)^{T}+2\rho_{n} \mathbf{I}_{n}\right)^{\dagger}. \end{aligned} \end{equation} Finally, the Lagrangian multipliers $\Gamma_{n}^{\mathbf{A}}$ can be updated by the following equation \begin{equation} \label{equation:Lambda_1} \Gamma_{n}^{\mathbf{A}} = \Gamma_{n}^{\mathbf{A}} + \mathbf{A}_n-\mathbf{J}_n. \end{equation} \subsubsection{Update $\mathcal{Y}$} With other variables fixed, the minimization subproblem with respect to $\mathcal{Y}$ in (\ref{equation:XAY}) can be written as \begin{equation} \begin{aligned} & \arg\min_{\{\mathbf{Y}_{(n)}\}_{n=1}^{N}} \sum_{n=1}^{N} \frac{\alpha_{n}}{2}\left\|\mathbf{Y}_{(n)}-\mathbf{A}_{n} \mathbf{X}_{n}\right\|_{\text{F}}^{2}+\frac{\rho}{2}\left\|\mathcal{Y}-\mathcal{Y}^{k}\right\|_{\text{F}}^{2} \\ & s.t., \mathcal{P}_{\Omega}(\mathcal{Y})=\mathcal{F}. \end{aligned} \end{equation} Then, the update of $\mathcal{Y}^{k+1}$ can be written explicitly as \begin{equation} \label{equation_solution_Y} \begin{array}{l} \displaystyle \mathcal{Y}^{k+1}=\mathcal{P}_{{\Omega}^c}\left(\sum_{n=1}^{N} \alpha_{n} \text { fold }_{n}\left(\frac{\mathbf{A}_{n}^{k+1} \mathbf{X}_{n}^{k+1}+\rho_n \mathbf{Y}_{(n)}^{k}}{1+\rho_n}\right)\right)+\mathcal{F}, \end{array} \end{equation} where $\Omega^{C}$ is the complementary set of $\Omega$. \begin{algorithm}[!t] \caption{:Algorithm for the LRATM model.} \label{algorithm:A1} \begin{algorithmic}[1] \Require The observed tensor $\mathcal{F}$; The set of index of observed entries $\Omega$; Stopping criterion $\varepsilon$, the given $n$-rank, $r=\left(r_{1}, r_{2}, r_{3}\right)$. \Ensure The completed tensor. \State Initialize: $\mathbf{X}_n=\mathbf{Z}_n=0, \mathbf{A}_n=\mathbf{J}_n=0,\Gamma_{n}^\mathbf{X}=0, \Gamma_{n}^\mathbf{A}=0, n=1,2, \cdots, N$; $k=0$. \State Repeat until convergence: \State Update $\mathbf{X}, \mathbf{Z}, \mathbf{A}, \mathbf{J}, \mathcal{Y}, \Gamma^{\mathbf{X}}, \Gamma^{\mathbf{A}}$ via 1st step: Update $\mathbf{Z}_n$ via (\ref{equation_solution_Zn}) 2nd step: Update $\mathbf{X}_n$ via (\ref{equation:solution_Xn}) 3rd step: Update $\mathbf{A}_n$ via (\ref{equation_solution_An}) 4th step: Update $\mathbf{J}_n$ via (\ref{equation_solution_Jn}) 5th step: Update $\mathcal{Y}$ via (\ref{equation_solution_Y}) 6th step: Update the parameter via (\ref{equation:Lambda_2}), (\ref{equation:Lambda_1}) \State Check the convergence condition. \end{algorithmic} \end{algorithm} \subsection{ Complexity and Convergence Analysis} The proposed algorithm for our LRATM model is summarized in Algorithm \ref{algorithm:A1}. Further, we discuss the complexity and convergence of the proposed algorithm. \subsubsection{Complexity analysis} The cost of computing $\mathbf{X}_{n}$ is $O\left(I_{n} r_{n}^{2}+I_{n} r_{n} s_{n}+r_{n}^{2} s_{n}\right)$, calculating $\mathbf{Z_n}$ has a complexity of $O\left( \Pi_{j \neq n} I_{j} \times r_{n}^2 \right)$, the complexity of updating $\mathbf{J}_n$ is $O\left(I_{n} r_{n}^2\right)$, calculating $\mathbf{A}_{n}$ has a complexity of $O\left(I_{n} r_{n}^{2}+I_{n} r_{n} s_{n}+r_{n}^{2} s_{n}\right)$, calculating $\mathcal{Y}$ has a complexity of $O\left(r_{1} I_{1} s_{1}+\cdots+r_{N} I_{N} s_{N}\right)$. Therefore, the total complexity of the proposed algorithm can be obtained by counting the complexity of the above variables, i.e., \begin{equation} \label{equation:complexity_model1} O\left(\sum_{n}(3I_{n} r_{n}^2+\Pi_{j \neq n} I_{j} \times r_{n}^2+3 I_{n} r_{n} S_{n}+2 r_{n}^{2} s_{n})\right). \end{equation} \subsubsection{Convergence analysis} In this section, we theoretically analyze the convergence of the proposed algorithm by using the BSUM method \cite{BSUM}. \noindent \textbf{Lemma 2} \cite{BSUM}: Let us assume that the feasible set $\mathcal{X}$ is the cartesian product of $n$ closed convex sets: $\mathcal{X}=\mathcal{X}_1 \times \mathcal{X}_2 \times \cdots \times \mathcal{X}_{n}$. Given the problem \begin{equation} \min f(x), s.t. ~ x \in \mathcal{X}, \end{equation} assume $h\left(x, x^{k-1}\right)$ is an approximation of $f(x)$ at the $(k-1)$-th iteration, which satisfies the following conditions: \begin{equation} \begin{array}{l} 1) \quad h_{i}\left(y_{i}, y\right)=f(y), \forall y \in \mathcal{X}, \forall i; \\ 2) \quad h_{i}\left(x_{i}, y\right) \geq f\left(y_{1}, \ldots, y_{i-1}, x_{i}, y_{i+1}, \ldots, y_{n}\right), \\ \quad \quad \forall x_{i} \in \mathcal{X}_{i}, \forall y \in \mathcal{X}, \forall i;\\ 3) \quad \left.h_{i}^{\prime}\left(x_{i}, y ; d_{i}\right)\right|_{x_i=y_i}=f^{\prime}(y ; d), \forall d=\left(0, \cdots, d_{i} \cdots 0\right) \\ \quad \quad \text { s.t. } y_{i}+d_{i} \in \mathcal{X}_{i}, \forall i;\\ 4) \quad h_{i}\left(x_{i}, y\right) \text{is continuous in} \left(x_{i}, y\right), \forall i; \end{array} \end{equation} where $h_{i}\left(x_{i}, y\right)$ is the sub-problem with respect to the $i$-th block and $f^{\prime}(y ; d)$ is the direction derivative of fat the point $y$ in direction $d$. Suppose $h_{i}\left(x_{i}, y\right)$ is quasi-convex in $x_{i}$ for $i=1,2, \cdots, n$. Furthermore, assume that each sub-problem $\arg\min h_i\left(x_{i}, x^{k-1}\right), s.t. ~ x \in \mathcal{X}_{i}$ has a unique solution for any point $x^{k-1} \in \mathcal{X} .$ Then, the iterates generated by the BSUM algorithm converge to the set of coordinatewise minimum of $f$. \noindent \textbf{Theorem 1.} The iterates generated by (\ref{equation_original_PPA}) converge to the set of coordinatewise minimizers. \textbf{Proof.} It is easy to verify that $g\left(\mathcal{S}, \mathcal{S}^{k}\right)$ is an approximation and a global upper bound of $f(\mathcal{S})$ at the $k$-th iteration, which satisfies the following conditions: \begin{equation} \begin{array}{l} 1) \quad g_{i}\left(\mathcal{S}_{i}, \mathcal{S}\right)=f(\mathcal{S}), \forall \mathcal{S}, i=1,2,3; \\ 2) \quad g_{i}\left(\bar{\mathcal{S}}_{i}, \mathcal{S}\right) \geq f\left(\mathcal{S}_{1}, \cdots, \bar{\mathcal{S}_{i}}, \cdots, \mathcal{S}_{3}\right), \\ \quad\quad \forall \bar{\mathcal{S}}_{i}, \forall \mathcal{S}, i=1,2,3; \\ 3) \quad \left.g_{i}^{\prime}\left(\bar{\mathcal{S}}_{i}, \mathcal{S} ; \mathbf{M}_{i}\right)\right|_{\bar{\mathcal{S}}_{i}=\mathcal{S}_{i}}=f^{\prime}\left(\mathcal{S} ; \mathbf{M}^i\right), \\ \quad \quad \forall \mathbf{M}^{i}=\left(0, \ldots, \mathbf{M}_{i},\ldots, 0\right); \\ 4) \quad g_{i}\left(\bar{\mathcal{S}}_{i}, \mathcal{S}\right) \text{is continuous in} \left(\bar{\mathcal{S}}_{i}, \mathcal{S} \right), i=1,2,3; \end{array} \end{equation} where $\mathcal{S}=(\mathbf{X}, \mathbf{A}, \mathcal{Y}),$ and $\mathcal{S}_{i}$ equal $\mathbf{X}, \mathbf{A}, \mathcal{Y}$ for $i=1,2,3,$ respectively. In addition, the subproblem $g_{i}(i=1,2,3)$ is quasi-convex with respect to $\mathbf{X}, \mathbf{A}$ and $\mathcal{Y}$ respectively and each sub-problem of $g_{i}$ has a unique solution. Therefore, all assumptions in \textbf{Lemma 1} are satisfied. According to the conclusion of \textbf{Lemma 1}, the \textbf{Theorem 1} is valid, and the proposed algorithm is theoretically convergent. \section{Numerical experiments} \label{Numerical experiments} In this section, the proposed model is evaluated on three types of public tensor datasets, i.e., video datasets, MRI dataset and HSI dataset which have been frequently used to interpret the tensor completion performance of different models. To demonstrate its effectiveness, we compare the proposed model with TMac method \cite{Tmac}, MF-TV method \cite{MFTV}, single TNN based method \cite{lu2019TRPCA} and PSTNN based method \cite{PSTNN}. \begin{table}[t] \caption{The averaged PSNR, SSIM, FSIM, ERGA and SAM of the completed results on video "suzie" by Tmac, MF-TV, TNN, PSTNN and our model with different sampling rates. The best values are highlighted in bolder fonts.} \centering \label{table_video_suzie} \setlength{\tabcolsep}{1mm}{ \begin{tabular}{cccccccc} \hline \hline && &SR =0.05 &&&& \\ PQI & nosiy& our model& MF-TV& TMac& PSTNN& TNN\\ PSNR & 7.259 & \textbf{29.464} & 13.801 & 23.385 & 17.447 & 22.005 \\ SSIM & 0.009 & \textbf{0.807} & 0.094 & 0.622 & 0.192 & 0.563 \\ FSIM & 0.454 & \textbf{0.885} & 0.42 & 0.792 & 0.59 & 0.776 \\ ERGA & 1057.282 & \textbf{83.571} & 501.117 & 167.927 & 327.678 & 194.844 \\ MSAM & 77.324 & \textbf{3.622} & 24.095 & 6.927 & 13.775 & 7.797 \\ \hline &&&SR = 0.1&&&&\\ PQI & nosiy& our model& MF-TV& TMac& PSTNN& TNN\\ PSNR& 7.493& \textbf{32.056}& 22.356& 26.189& 26.647& 26.032\\ SSIM& 0.014& \textbf{0.878}& 0.605& 0.74& 0.68& 0.692\\ FSIM& 0.426& \textbf{0.924}& 0.758& 0.838& 0.843& 0.846\\ ERGA& 1029.096& \textbf{62.314}& 196.059& 124.369 &117.104& 124.923\\ MSAM& 71.725& \textbf{2.764}& 6.99& 5.423& 5.171& 5.405 \\ \hline &&&SR = 0.2&&&&\\ PQI & nosiy& our model& MF-TV& TMac& PSTNN& TNN\\ PSNR& 8.005& \textbf{34.378}& 32.064& 27.274& 30.566& 30.561\\ SSIM& 0.02& \textbf{0.918}& 0.872& 0.782& 0.829& 0.831\\ FSIM& 0.391& \textbf{0.948}& 0.916& 0.853& 0.91& 0.911\\ ERGA& 970.285& \textbf{47.877}& 66.692& 109.627& 75.472& 75.598\\ MSAM& 63.522& \textbf{2.183}& 2.81& 4.812& 3.399& 3.395\\ \hline \hline \end{tabular}} \end{table} To accurately evaluate the performance of the test models, two types of standards are employed to quantitatively evaluate the quality of the completed tensors. The first one is the visual evaluation of the completed data, which is a qualitative evaluation standard. The second one is the five quantitative picture quality indices (PQIs), including the peak signal-to-noise ratio (PSNR) \cite{PSNR}, structural similarity index (SSIM) \cite{SSIM}, feature similarity (FSIM) \cite{FSIM}, erreur relative globale adimensionnelle de synth\`ese (ERGAS) \cite{EGRAS}, the mean the spectral angle mapper (SAM) \cite{SAM}. Larger PSNR, SSIM, FSIM and smaller ERGAS, SAM are, the better the completion performance of the corresponding model is. Since the experimental datasets are all third-order tensors, the PQIs for each frontal slice in the completed tensor are first calculated, and then the mean of these PQIs are finally used to evaluate the performance of the models. All experiments are performed on MATLAB 2019b, the CPU of the computer is Inter core i7@2.2GHz and the memory is 64GB. The code will be posted on the following URL: https://github.com/NavyZeng/LRATM. \subsection{Video Data} \begin{figure*}[!t] \centering \subfloat[Original]{\includegraphics[width=0.13\linewidth]{Image_video_b94}}% \hfil \subfloat[95\% Masked]{\includegraphics[width=0.13\linewidth]{Image_video_b94_sr005Nosiy}}% \hfil \subfloat[our model]{\includegraphics[width=0.13\linewidth]{Image_video_b94_sr005LxLxNN}}% \hfil \subfloat[MF-TV]{\includegraphics[width=0.13\linewidth]{Image_video_b94_sr005MF_TV}}% \hfil \subfloat[Tmac]{\includegraphics[width=0.13\linewidth]{Image_video_b94_sr005Tmac}}% \hfil \subfloat[PSTNN]{\includegraphics[width=0.13\linewidth]{Image_video_b94_sr005PSTNN}}% \hfil \subfloat[TNN]{\includegraphics[width=0.13\linewidth]{Image_video_b94_sr005TNN} \caption{One slice of the recovered video for “suzie” by our model, MF-TV, Tmac, PSTNN and TNN. The sampling rate is 5\%.} \label{figure_video_sr0.05} \end{figure*} \begin{figure*}[!t] \centering \subfloat[Original]{\includegraphics[width=0.13\linewidth]{Image_video_b10_sr01suzie_b10}}% \hfil \subfloat[90\% Masked]{\includegraphics[width=0.13\linewidth]{Image_video_b10_sr01Nosiy}}% \hfil \subfloat[our model]{\includegraphics[width=0.13\linewidth]{Image_video_b10_sr01LxLxNN}}% \hfil \subfloat[MF-TV]{\includegraphics[width=0.13\linewidth]{Image_video_b10_sr01MF_TV}}% \hfil \subfloat[Tmac]{\includegraphics[width=0.13\linewidth]{Image_video_b10_sr01Tmac}}% \hfil \subfloat[PSTNN]{\includegraphics[width=0.13\linewidth]{Image_video_b10_sr01PSTNN}}% \hfil \subfloat[TNN]{\includegraphics[width=0.13\linewidth]{Image_video_b10_sr01TNN} \caption{One slice of the recovered video for “suzie” by our model, MF-TV, Tmac, PSTNN and TNN. The sampling rate is 10\%.} \label{figure_video_sr0.1} \end{figure*} \begin{figure*}[!t] \centering \subfloat[Original]{\includegraphics[width=0.13\linewidth]{Image_video_b10_sr02suzie_b10}}% \hfil \subfloat[80\% Masked]{\includegraphics[width=0.13\linewidth]{Image_video_b10_sr02Nosiy}}% \hfil \subfloat[our model]{\includegraphics[width=0.13\linewidth]{Image_video_b10_sr02LxLxNN}}% \hfil \subfloat[MF-TV]{\includegraphics[width=0.13\linewidth]{Image_video_b10_sr02MF_TV}}% \hfil \subfloat[Tmac]{\includegraphics[width=0.13\linewidth]{Image_video_b10_sr02Tmac}}% \hfil \subfloat[PSTNN]{\includegraphics[width=0.13\linewidth]{Image_video_b10_sr02PSTNN}}% \hfil \subfloat[TNN]{\includegraphics[width=0.13\linewidth]{Image_video_b10_sr02TNN} \caption{One slice of the recovered video for “suzie” by our model, MF-TV, Tmac, PSTNN and TNN. The sampling rate is 20\%.} \label{figure_video_sr0.2} \end{figure*} In this subsection, we compare our model with MF-TV, Tmac, TNN and PSTNN on two video datasets: "suzie" and “hall”\footnote{http://trace.eas.asu.edu/yuv/}, both of which are colored using YUV format, and two slices of them are shown in Fig. \ref{figure_video_sr0.05} and Fig. \ref{figure_hall_sr0.05}, respectively. Their sizes both are 144 $\times$ 176 $\times$ 150. We test all five methods on a series of sampling rates (SR): 5\%, 10\% and 20\%, and all the test models are evaluated in terms of quantitative comparison and visual evaluation. In addition, the $n$-rank is approximated by using the number of the largest 0.5\% singular values. For quantitative comparison, Table \ref{table_video_suzie} and Table \ref{table_video_hall} report the PQIs of the results completed by different methods. The best result for each PQI are marked in bold. From Table \ref{table_video_suzie} and Table \ref{table_video_hall}, it can be found that our model obtains the highest indices among the five tested models in all SR cases; Tmac obtains the second best PQIs, when the SR is set to 5\% or 10\%; While MF-TV obtains the second best PQIs, when SR is set to 20\%. The margins between the results by our model and the second best results are more than 5dB considering the PSNR. For visual evaluation, we illustrate one frontal slice of the completed results with different sampling rates in Fig. \ref{figure_video_sr0.05}, Fig. \ref{figure_video_sr0.1}, Fig. \ref{figure_video_sr0.2}, Fig. \ref{figure_hall_sr0.05} and Fig. \ref{figure_hall_sr0.1}. It is clear from the figures that the results of our model are closest to the ground truth than other tested models, especially at low sampling rates. Specifically, as shown in Fig. \ref{figure_hall_sr0.1}, Fig. \ref{figure_video_sr0.05} and Fig. \ref{figure_video_sr0.1}, when the sampling rates are 0.05 and 0.1, the advantages of our model are most obvious. Our model restores most of the structural information of the videos, while the videos restored by the competitive models contain only the outline of the images. At a higher sampling rate, as shown in Fig. \ref{figure_video_sr0.2} and Fig. \ref{figure_hall_sr0.1}, our model and competitive models both complete the main structural information of the images, but our model recovers more texture and detail information. \begin{table} [t] \centering \caption{The averaged PSNR, SSIM, FSIM, ERGA and SAM of the recovered results on video "hall" by Tmac, MF-TV, TNN, PSTNN and our model with different sampling rates. The best values are highlighted in bolder fonts.} \label{table_video_hall} \setlength{\tabcolsep}{1mm}{ \begin{tabular}{cccccccc} \hline \hline &&&SR =0.05 &&&& \\ PQI& nosiy& our model& MF-TV& TMac& PSTNN& TNN\\ PSNR & 4.82 & \textbf{28.347} & 13.539 & 22.101 & 16.075 & 20.78 \\ SSIM & 0.007 & \textbf{0.894} & 0.412 & 0.675 & 0.36 & 0.636 \\ FSIM & 0.387 & \textbf{0.920} & 0.612 & 0.789 & 0.672 & 0.792 \\ ERGA & 1225.779 & \textbf{83.146} & 452.351 & 168.866 & 335.52 & 195.315 \\ MSAM & 77.299 & \textbf{2.360} & 12.865 & 3.818 & 8.64 & 4.299 \\ \hline &&&SR = 0.1&&&&\\ PQI & nosiy & our model & MF-TV & TMac & PSTNN & TNN \\ PSNR & 5.055 & \textbf{31.804} & 24.855 & 26.936 & 29.014 & 28.433 \\ SSIM & 0.013 & \textbf{0.935} & 0.829 & 0.854 & 0.892 & 0.905 \\ FSIM & 0.393 & \textbf{0.950} & 0.873 & 0.888 & 0.934 & 0.936 \\ ERGA & 1193.075 & \textbf{56.998} & 131.422 & 97.185 & 77.395 & 82.259 \\ MSAM & 71.7 &\textbf{ 1.904} & 3.669 & 2.404 & 2.417 & 2.46 \\ \hline &&&SR = 0.2&&&&\\ PQI & nosiy & our model & MF-TV & TMac & PSTNN & TNN \\ PSNR & 5.567 & \textbf{33.941} & 33.006 & 27.648 & 33.629 & 33.691 \\ SSIM & 0.025 & \textbf{0.952} & 0.94 & 0.869 & 0.961 & 0.962 \\ FSIM & 0.403 & \textbf{0.964} & 0.954 & 0.897 & 0.973 & 0.974 \\ ERGA & 1124.737 & \textbf{44.581} & 50.971 & 89.271 & 46.123 & 45.851 \\ MSAM & 63.507 & \textbf{1.574} & 1.779 & 2.226 & 1.584 & 1.565 \\ \hline \hline \end{tabular}} \end{table} \subsection{Magnetic resonance imaging data} \begin{figure*}[!t] \centering \subfloat[Original]{\includegraphics[width=0.13\linewidth]{Image_hall_b21_sr005Original}}% \hfil \subfloat[95\% Masked]{\includegraphics[width=0.13\linewidth]{Image_hall_b21_sr005Nosiy}}% \hfil \subfloat[our model]{\includegraphics[width=0.13\linewidth]{Image_hall_b21_sr005LxLxNN}}% \hfil \subfloat[MF-TV]{\includegraphics[width=0.13\linewidth]{Image_hall_b21_sr005MF_TV}}% \hfil \subfloat[Tmac]{\includegraphics[width=0.13\linewidth]{Image_hall_b21_sr005Tmac}}% \hfil \subfloat[PSTNN]{\includegraphics[width=0.13\linewidth]{Image_hall_b21_sr005PSTNN}}% \hfil \subfloat[TNN]{\includegraphics[width=0.13\linewidth]{Image_hall_b21_sr005TNN} \caption{One slice of the recovered video “hall” by our model, MF-TV, Tmac, PSTNN and TNN. The sampling rate is 5\%.} \label{figure_hall_sr0.05} \end{figure*} \begin{figure*}[!t] \centering \subfloat[Original]{\includegraphics[width=0.13\linewidth]{Image_hall_b104_sr01Original}}% \hfil \subfloat[90\% Masked]{\includegraphics[width=0.13\linewidth]{Image_hall_b104_sr01Nosiy}}% \hfil \subfloat[our model]{\includegraphics[width=0.13\linewidth]{Image_hall_b104_sr01LxLxNN}}% \hfil \subfloat[MF-TV]{\includegraphics[width=0.13\linewidth]{Image_hall_b104_sr01MF_TV}}% \hfil \subfloat[Tmac]{\includegraphics[width=0.13\linewidth]{Image_hall_b104_sr01Tmac}}% \hfil \subfloat[PSTNN]{\includegraphics[width=0.13\linewidth]{Image_hall_b104_sr01PSTNN}}% \hfil \subfloat[TNN]{\includegraphics[width=0.13\linewidth]{Image_hall_b104_sr01TNN} \caption{One slice of the recovered video “hall” by our model, MF-TV, Tmac, PSTNN and TNN. The sampling rate is 10\%.} \label{figure_hall_sr0.1} \end{figure*} \begin{figure*}[!t] \centering \subfloat[]{\includegraphics[width=0.2\linewidth]{psnr_suzie_sr005}} \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{psnr_suzie_sr01}} \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{psnr_suzie_sr02}} \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{ssim_suzie_sr005}} \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{ssim_suzie_sr01}} \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{ssim_suzie_sr02}} \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{fsim_suzie_sr005}}% \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{fsim_suzie_sr01}}% \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{fsim_suzie_sr02}}% \caption{The PSNR, SSIM and FSIM of the recovered video "suzie" by MF-TV, Tmac, TNN, PSTNN and our model for all slices, respectively.} \label{PSNR and SSIM of video} \end{figure*} \begin{figure*}[!t] \centering \subfloat[Original]{\includegraphics[width=0.13\linewidth]{Image_MRI_b7_sr01MRI_b7}}% \hfil \subfloat[90\% Masked]{\includegraphics[width=0.13\linewidth]{Image_MRI_b7_sr01Nosiy}}% \hfil \subfloat[our model]{\includegraphics[width=0.13\linewidth]{Image_MRI_b7_sr01LxLxNN}}% \hfil \subfloat[MF-TV]{\includegraphics[width=0.13\linewidth]{Image_MRI_b7_sr01MF_TV}}% \hfil \subfloat[Tmac]{\includegraphics[width=0.13\linewidth]{Image_MRI_b7_sr01Tmac}}% \hfil \subfloat[PSTNN]{\includegraphics[width=0.13\linewidth]{Image_MRI_b7_sr01PSTNN}}% \hfil \subfloat[TNN]{\includegraphics[width=0.13\linewidth]{Image_MRI_b7_sr01TNN} \caption{One slice of the recovered MRI by our model, MF-TV, Tmac, PSTNN and TNN. The sampling rate is 10\%.} \label{figure_MR_sr0.1_1} \end{figure*} \begin{figure*}[!t] \centering \subfloat[Original]{\includegraphics[width=0.13\linewidth]{Image_MRI_b83_sr01MRI_b83}}% \hfil \subfloat[90\% Masked]{\includegraphics[width=0.13\linewidth]{Image_MRI_b83_sr01Nosiy}}% \hfil \subfloat[our model]{\includegraphics[width=0.13\linewidth]{Image_MRI_b83_sr01LxLxNN}}% \hfil \subfloat[MF-TV]{\includegraphics[width=0.13\linewidth]{Image_MRI_b83_sr01MF_TV}}% \hfil \subfloat[Tmac]{\includegraphics[width=0.13\linewidth]{Image_MRI_b83_sr01Tmac}}% \hfil \subfloat[PSTNN]{\includegraphics[width=0.13\linewidth]{Image_MRI_b83_sr01PSTNN}}% \hfil \subfloat[TNN]{\includegraphics[width=0.13\linewidth]{Image_MRI_b83_sr01TNN} \caption{One slice of the recovered MRI by our model, MF-TV, Tmac, PSTNN and TNN. The sampling rate is 10\%.} \label{figure_MR_sr0.1_2} \end{figure*} \begin{figure*}[!t] \centering \subfloat[Original]{\includegraphics[width=0.13\linewidth]{Image_MRI_b95_sr01MRI_b95}}% \hfil \subfloat[90\% Masked]{\includegraphics[width=0.13\linewidth]{Image_MRI_b95_sr01Nosiy}}% \hfil \subfloat[our model]{\includegraphics[width=0.13\linewidth]{Image_MRI_b95_sr01LxLxNN}}% \hfil \subfloat[MF-TV]{\includegraphics[width=0.13\linewidth]{Image_MRI_b95_sr01MF_TV}}% \hfil \subfloat[Tmac]{\includegraphics[width=0.13\linewidth]{Image_MRI_b95_sr01Tmac}}% \hfil \subfloat[PSTNN]{\includegraphics[width=0.13\linewidth]{Image_MRI_b95_sr01PSTNN}}% \hfil \subfloat[TNN]{\includegraphics[width=0.13\linewidth]{Image_MRI_b95_sr01TNN} \caption{One slice of the recovered MRI by our model, MF-TV, Tmac, PSTNN and TNN. The sampling rate is 10\%.} \label{figure_MR_sr0.1_3} \end{figure*} \begin{figure*}[!t] \centering \subfloat[Original]{\includegraphics[width=0.13\linewidth]{Image_MRI_b118_sr01MRI_b118}}% \hfil \subfloat[90\% Masked]{\includegraphics[width=0.13\linewidth]{Image_MRI_b118_sr01Nosiy}}% \hfil \subfloat[our model]{\includegraphics[width=0.13\linewidth]{Image_MRI_b118_sr01LxLxNN}}% \hfil \subfloat[MF-TV]{\includegraphics[width=0.13\linewidth]{Image_MRI_b118_sr01MF_TV}}% \hfil \subfloat[Tmac]{\includegraphics[width=0.13\linewidth]{Image_MRI_b118_sr01Tmac}}% \hfil \subfloat[PSTNN]{\includegraphics[width=0.13\linewidth]{Image_MRI_b118_sr01PSTNN}}% \hfil \subfloat[TNN]{\includegraphics[width=0.13\linewidth]{Image_MRI_b118_sr01TNN} \caption{One slice of the recovered MRI by our model, MF-TV, Tmac, PSTNN and TNN. The sampling rate is 10\%.} \label{figure_MR_sr0.1_4} \end{figure*} \begin{figure*}[!t] \centering \subfloat[]{\includegraphics[width=0.2\linewidth]{psnr_mri_sr005}} \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{psnr_mri_sr01}} \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{psnr_mri_sr02}} \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{ssim_mri_sr005}} \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{ssim_mri_sr01}} \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{ssim_mri_sr02}} \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{fsim_mri_sr005}}% \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{fsim_mri_sr01}}% \hfil \subfloat[]{\includegraphics[width=0.2\linewidth]{fsim_mri_sr02}}% \caption{The PSNR, SSIM and FSIM of the recovered MRI by MF-TV, Tmac, TNN, PSTNN and our model for all slices, respectively.} \label{PSNR and SSIM of MRI} \end{figure*} To further verify the versatility of our model for different datasets, in this subsection we compare our model with MF-TV, Tmac, TNN and PSTNN on MRI dataset, i.e., the cubical MRI data\footnote{http://brainweb.bic.mni.mcgill.ca/brainweb/selection$\_$normal.html}. Its one slice is shown in Fig. \ref{figure_MR_sr0.1_1}. The size of the dataset is 181 $\times$ 217 $\times$ 150. We test all five methods on a series of sampling rates: 5\%, 10\%, 20\% and 30\%. In addition, the $n$-rank is approximated by using the number of the largest 0.5\% singular values. For quantitative comparison, Table \ref{table_MRI} reports the PQIs of the results completed by different methods. The best result for each PQI are marked in bold. From Table \ref{table_MRI}, it can be found that our method obtains the highest indices among the five tested methods in all SR cases. Further, the same advantage of our model can also be seen in Fig. \ref{PSNR and SSIM of MRI} which reports the PSNR, SSIM and FSIM of each slice. For visual comparison, Fig. \ref{figure_MR_sr0.1_1}, Fig. \ref{figure_MR_sr0.1_2}, Fig. \ref{figure_MR_sr0.1_3} and Fig. \ref{figure_MR_sr0.1_4} show slices with 90\% missing values and the corresponding completed slices by all the tested methods. From the results, we see again that our model can better retain the local details and texture information of the images, and effectively restore the main structure of the images than other compared methods. Therefore, one can see that the recovered data obtained by our model has the best visual evaluation. \begin{table}[t] \centering \caption{The averaged PSNR, SSIM, FSIM, ERGA and SAM of the recovered results on MRI by Tmac, MF-TV, TNN, PSTNN and our model with different sampling rates. The best values are highlighted in bolder fonts.} \label{table_MRI} \setlength{\tabcolsep}{1mm}{ \begin{tabular}{ccccccccc} \hline \hline &&&SR =0.05 &&&& \\ PQI& nosiy& our model& MF-TV& TMac& PSTNN& TNN\\ PSNR & 10.258 & \textbf{26.414} & 12.332 & 20.51 & 15.859 & 18.218 \\ SSIM & 0.228 & \textbf{0.722} & 0.099 & 0.45 & 0.224 & 0.27 \\ FSIM & 0.473 & \textbf{0.834} & 0.52 & 0.711 & 0.642 & 0.646 \\ ERGA & 1030.203 & \textbf{184.279} & 814.747 & 339.385 & 545.77 & 434.774 \\ MSAM & 76.54 & \textbf{20.411} & 55.603 & 31.367 & 36.355 & 31.11 \\ \hline &&&SR = 0.1&&&&\\ PQI & nosiy & our model & MF-TV & TMac & PSTNN & TNN \\ PSNR & 10.492 & \textbf{32.652} & 15.406 & 21.411 & 22.061 & 22.535 \\ SSIM & 0.241 & \textbf{0.912} & 0.25 & 0.531 & 0.482 & 0.536 \\ FSIM & 0.511 & \textbf{0.926} & 0.587 & 0.732 & 0.764 & 0.78 \\ ERGA & 1002.8 & \textbf{89.116} & 584.827 & 308.655 & 275.473 & 266.753 \\ MSAM & 70.986 & \textbf{14.637} & 41.826 & 29.345 & 24.585 & 24.6 \\ \hline &&&SR = 0.2&&&&\\ PQI & nosiy & our model & MF-TV & TMac & PSTNN & TNN \\ PSNR & 11.003 & \textbf{36.529} & 27.062 & 22.33 & 29.152 & 28.571 \\ SSIM & 0.271 & \textbf{0.962} & 0.737 & 0.586 & 0.804 & 0.802 \\ FSIM & 0.564 & \textbf{0.963} & 0.84 & 0.754 & 0.895 & 0.891 \\ ERGA & 945.583 & \textbf{57.037} & 173.636 & 276.269 & 127.133 & 136.182 \\ MSAM & 62.887 & \textbf{11.559} & 21.792 & 27.267 & 17.513 & 17.855 \\ \hline \hline \end{tabular}} \end{table} \subsection{Hyperspectral Image Data} \begin{figure*}[!t] \centering \subfloat[Original]{\includegraphics[width=0.13\linewidth]{Image_HSI_b72.png}}% \hfil \subfloat[97.5\% Masked]{\includegraphics[width=0.13\linewidth]{Image_HSI_b72_sr0025Nosiy}}% \hfil \subfloat[our model]{\includegraphics[width=0.13\linewidth]{Image_HSI_b72_sr0025LxLxNN}}% \hfil \subfloat[MF-TV]{\includegraphics[width=0.13\linewidth]{Image_HSI_b72_sr0025MF_TV}}% \hfil \subfloat[Tmac]{\includegraphics[width=0.13\linewidth]{Image_HSI_b72_sr0025Tmac}}% \hfil \subfloat[PSTNN]{\includegraphics[width=0.13\linewidth]{Image_HSI_b72_sr0025PSTNN}}% \hfil \subfloat[TNN]{\includegraphics[width=0.13\linewidth]{Image_HSI_b72_sr0025TNN} \caption{One slice of the recovered HSI "Cuprite" by our model, MF-TV, Tmac, PSTNN and TNN. The sampling rate is 2.5\%.} \label{figure_HSI_sr0.025} \end{figure*} \begin{figure*}[!t] \centering \subfloat[Original]{\includegraphics[width=0.13\linewidth]{Image_HSI_b72.png}}% \hfil \subfloat[95\% Masked]{\includegraphics[width=0.13\linewidth]{Image_HSI_b72_sr005Nosiy}}% \hfil \subfloat[our model]{\includegraphics[width=0.13\linewidth]{Image_HSI_b72_sr005LxLxNN}}% \hfil \subfloat[MF-TV]{\includegraphics[width=0.13\linewidth]{Image_HSI_b72_sr005MF_TV}}% \hfil \subfloat[Tmac]{\includegraphics[width=0.13\linewidth]{Image_HSI_b72_sr005Tmac}}% \hfil \subfloat[PSTNN]{\includegraphics[width=0.13\linewidth]{Image_HSI_b72_sr005PSTNN}}% \hfil \subfloat[TNN]{\includegraphics[width=0.13\linewidth]{Image_HSI_b72_sr005TNN} \caption{One slice of the recovered HSI "Cuprite" by our model, MF-TV, Tmac, PSTNN and TNN. The sampling rate is 5\%.} \label{figure_HSI_sr0.05} \end{figure*} \begin{figure*}[!t] \centering \subfloat[PSNR]{\includegraphics[width=0.15\linewidth]{psnr_hsi_sr0025}}% \hfil \subfloat[SSIM]{\includegraphics[width=0.15\linewidth]{ssim_hsi_sr0025}}% \hfil \subfloat[FSIM]{\includegraphics[width=0.15\linewidth]{fsim_hsi_sr0025}}% \hfil \subfloat[PSNR]{\includegraphics[width=0.15\linewidth]{psnr_hsi_sr005}}% \hfil \subfloat[SSIM]{\includegraphics[width=0.15\linewidth]{ssim_hsi_sr005}}% \hfil \subfloat[FSIM]{\includegraphics[width=0.15\linewidth]{fsim_hsi_sr005}}% \caption{The PSNR, SSIM and FSIM of the recovered HSI "Cuprite" by MF-TV, Tmac, TNN, PSTNN and our model for all slices, respectively.(a)-(c): 97.5\% entries missing, (d)-(f): 95\% entries missing.} \label{PSNR and SSIM of HSI} \end{figure*} In this section, we compare our model with MF-TV, Tmac, TNN and PSTNN on one HSI dataset: Airborne Visible/Infrared Imaging Spectrometer (AVIRIS) Cuprite data\footnote{http://aviris.jpl.nasa.gov/html/aviris.freedata.html}. The size of AVIRIS Cuprite data is 150 $\times$ 150 $\times$ 188. Its one slice is shown in Fig. \ref{figure_HSI_sr0.05}. We test all five methods on a series of sampling rates: 2.5\%, 5\% and 10\%. In addition, the $n$-rank is approximated by using the number of the largest 0.3\% singular values. For quantitative comparison, Table \ref{table_HSI} reports the average PQIs of each tested method with three different sampling rates. At sampling rates 0.025 and 0.05, Fig. \ref{PSNR and SSIM of HSI} reports the PSNR, SSIM and FSIM of each frontal slice in the completed results. For visual comparison, Fig. \ref{figure_HSI_sr0.05} and Fig. \ref{figure_HSI_sr0.025} show slices of the sampled data with 97.5\% and 95\% missing values and the corresponding recovered slices by the tested methods. From the results, we see again that our model not only obtains the highest PQIs, but also recovers more structure information and spatial details of the images than compared methods, especially at low sampling rates. \begin{table} \caption{The averaged PSNR, SSIM, FSIM, ERGA and SAM of the recovered results on hyperspectral image "Cuprite" by Tmac, MF-TV, TNN, PSTNN and our model with different sampling rates. The best values are highlighted in bolder fonts.} \centering \label{table_HSI} \setlength{\tabcolsep}{1mm}{ \begin{tabular}{ccccccccc} \hline \hline &&&SR =0.025&&&& \\ PQI& nosiy& our model& MF-TV& TMac& PSTNN& TNN\\ PSNR & 7.666 & \textbf{34.595} & 26.115 & 21.25 & 13.387 & 22.783 \\ SSIM & 0.007 & \textbf{0.861} & 0.539 & 0.412 & 0.124 & 0.554 \\ FSIM & 0.48 & \textbf{0.916} & 0.765 & 0.755 & 0.613 & 0.775 \\ ERGA & 1043.633 & \textbf{50.383} & 237.074 & 235.594 & 539.574 & 245.333 \\ MSAM & 81.221 & \textbf{1.662} & 12.913 & 7.842 & 17.98 & 9.156 \\ \hline &&&SR = 0.05&&&&\\ PQI& nosiy& our model& MF-TV& TMac& PSTNN& TNN\\ PSNR & 7.779 & \textbf{38.202} & 34.684 & 28.945 & 20.621 & 26.579 \\ SSIM & 0.01 & \textbf{0.928} & 0.845 & 0.712 & 0.31 & 0.663 \\ FSIM & 0.471 & \textbf{0.960} & 0.915 & 0.846 & 0.735 & 0.836 \\ ERGA & 1030.139 & \textbf{41.898} & 89.372 & 93.352 & 234.445 & 154.292 \\ MSAM & 77.268 & \textbf{1.559} & 4.386 & 3.278 & 7.886 & 5.413 \\ \hline &&&SR = 0.1&&&&\\ PQI & nosiy & our model & MF-TV & TMac & PSTNN & TNN \\ PSNR & 8.013 &39.056 & \textbf{40.888} & 35.627 & 35.51 & 35.015 \\ SSIM & 0.014 &0.939 & \textbf{0.957} & 0.885 & 0.907 & 0.897 \\ FSIM & 0.451 &0.966 & \textbf{0.978} & 0.931 & 0.951 & 0.943 \\ ERGA & 1002.75 &34.544 & \textbf{34.263} & 44.518 & 54.421 & 57.537 \\ MSAM & 71.695 &\textbf{1.299} &1.46 & 1.445 & 2.072 & 2.192 \\ \hline \hline \end{tabular}} \end{table} \begin{figure*}[!t] \centering \subfloat[]{\includegraphics[width=0.15\linewidth]{video-Hall_SR=005_PSNR}}% \hfil \subfloat[]{\includegraphics[width=0.15\linewidth]{video-Hall_SR=01_PSNR}}% \hfil \subfloat[]{\includegraphics[width=0.15\linewidth]{video-Hall_SR=02_PSNR}}% \hfil \subfloat[]{\includegraphics[width=0.15\linewidth]{video-Hall_SR=005_SSIM}}% \hfil \subfloat[]{\includegraphics[width=0.15\linewidth]{video-Hall_SR=01_SSIM}}% \hfil \subfloat[]{\includegraphics[width=0.15\linewidth]{video-Hall_SR=02_SSIM}}% \caption{Sensitivity analysis of parameter $\gamma$ in video "hall" dataset. (a-c) Change in the MPSNR value: SR= 0.05, 0.1 and 0.2. (e-f) Change in the MSSIM value: 0.05, 0.1 and 0.2, respectively.} \label{parameter_analysis_hall} \end{figure*} \begin{figure*}[!t] \centering \subfloat[]{\includegraphics[width=0.15\linewidth]{MRI_SR=005_PSNR}}% \hfil \subfloat[]{\includegraphics[width=0.15\linewidth]{MRI_SR=01_PSNR}}% \hfil \subfloat[]{\includegraphics[width=0.15\linewidth]{MRI_SR=02_PSNR}}% \hfil \subfloat[]{\includegraphics[width=0.15\linewidth]{MRI_SR=005_SSIM}}% \hfil \subfloat[]{\includegraphics[width=0.15\linewidth]{MRI_SR=01_SSIM}}% \hfil \subfloat[]{\includegraphics[width=0.15\linewidth]{MRI_SR=02_SSIM}}% \caption{Sensitivity analysis of parameter $\gamma$ in MRI dataset. (a-c) Change in the MPSNR value: SR= 0.05, 0.1 and 0.2. (e-f) Change in the MSSIM value: 0.05, 0.1 and 0.2, respectively.} \label{parameter_analysis_MRI} \end{figure*} \begin{figure*}[!t] \centering \subfloat[SR=0.025]{\includegraphics[width=0.15\linewidth]{HSI_SR=0025_PSNR}}% \hfil \subfloat[SR=0.05]{\includegraphics[width=0.15\linewidth]{HSI_SR=005_PSNR}}% \hfil \subfloat[SR=0.1]{\includegraphics[width=0.15\linewidth]{HSI_SR=01_PSNR}}% \hfil \subfloat[SR=0.025]{\includegraphics[width=0.15\linewidth]{HSI_SR=0025_SSIM}}% \hfil \subfloat[SR=0.05]{\includegraphics[width=0.15\linewidth]{HSI_SR=005_SSIM}}% \hfil \subfloat[SR=0.1]{\includegraphics[width=0.15\linewidth]{HSI_SR=01_SSIM}}% \caption{Sensitivity analysis of parameter $\gamma$ in HSI dataset. (a-c) Change in the MPSNR value: SR= 0.025, 0.05 and 01. (e-f) Change in the MSSIM value: 0.025, 0.05 and 0.1, respectively.} \label{parameter_analysis_HSI} \end{figure*} \begin{table*} \centering \caption{Parameters setting in the proposed algorithm} \label{table:parameter_setting} \begin{tabular}{ccccc ccccc ccc} \hline & &Vdieo-suzie& & &Video-hall& & &MRI dataset& & &HSI dataset& \\ \hline SR& 0.05& 0.1&0.2 &0.05& 0.1&0.2 &0.05& 0.1&0.2 &0.025& 0.05&0.1\\ $\gamma$& 2.3&2.5&2.7&1.7&2.6&2.6&1.3&2.5&3.0&3.5&5.5&5.7\\ \hline \end{tabular} \end{table*} \subsection{Discussion} Considering the fact that the $\gamma$ in $\mathbf{X}_n$ and $\mathbf{A}_n$ have certain proportional relationship, we simply set the $\gamma$ in $\mathbf{X}_n$ as 0.1, and tune the $\gamma$ in $\mathbf{A}_n$ carefully. For experiments on video datasets , MRI and HSI dataset, Fig. \ref{parameter_analysis_hall}, Fig. \ref{parameter_analysis_MRI} and Fig. \ref{parameter_analysis_HSI} show the effect of parameter $\gamma$ on PSNR and SSIM at different sampling rates, respectively. To enhance the repeatability of our model, we list the optimal $\gamma$ of various datasets at different sampling rates in Table \ref{table:parameter_setting}. In addition, we manually set both $\tau_n$ and $\lambda_n$ as 0.01. \section{Conclusions} \label{conclusion} In this paper, we propose a novel double low-rank tensor model based on multi-mode matrix decomposition for tensor completion. Instead of using the traditional single nuclear norm or its relaxation to represent the low-rank prior of underlying tensor directly, we first apply parallel matrix factorization to all modes of underlying tensor, then, a novel double nonconvex $L_{\gamma}$ norm is designed to represent the underlying joint-manifold drawn from the mode factorization factors. An BSUM based algorithm is designed to efficiently solve the proposed model, and it can be demonstrated that our numerical scheme converges to the coordinatewise minimizers. The proposed model has been evaluated on three types of public tensor datasets, which show that our algorithm can complete a variety of low-rank tensors with significantly fewer samples than the compared methods. \section*{Acknowledgment} The authors would like to express their thanks to Dr. C. Lu, Dr. Y. Xu, Dr. T. Ji and Dr. T. Jiang for sharing their codes for the tested methods. In addition, this research is supported by the Fundamental Research Funds for the Central Universities under Grant No. 2452019073 and the National Natural Science Foundation of China under Grant No. 61876153. \ifCLASSOPTIONcaptionsoff \newpage \fi \bibliographystyle{IEEEtran
{'timestamp': '2020-06-23T02:29:50', 'yymm': '2005', 'arxiv_id': '2005.14521', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14521'}
arxiv
\section{Introduction} Neural conversation systems which treat dialogue response generation as a sequence generation task \cite{neural_conversation_model} often produce generic and incoherent responses \cite{shao-etal-2017-generating}. The primary reason for this is that, unlike humans, such systems do not have any access to background knowledge about the topic of conversation. For example, while chatting about movies, we use our background knowledge about the movie in the form of plot details, reviews and comments that we might have read. To enrich such neural conversation systems, some recent works \cite{moghe-etal-2018-towards,wizard_of_wikipedia,zhou-etal-2018-dataset} incorporate external knowledge in the form of documents which are relevant to the current conversation. For example, \cite{moghe-etal-2018-towards}, released a dataset containing conversations about movies where every alternate utterance is extracted from a background document about the movie. This background document contains plot details, reviews and Reddit comments about the movie. The focus thus shifts from sequence generation to identifying relevant snippets from the background document and modifying them suitably to form an appropriate response given the current conversational context. Intuitively, any model for this task should exploit semantic, structural and sequential information from the conversation context and the background document. For illustration, consider the chat shown in Figure \ref{dataset_example} from the Holl-E movie conversations dataset \cite{moghe-etal-2018-towards}. In this example, Speaker 1 nudges Speaker 2 to talk about how James's wife was irritated because of his career. The right response to this conversation comes from the line beginning at \textit{``His wife Mae \dots''}. However, to generate this response, it is essential to understand that (i) \textit{His} refers to James from the previous sentence; (ii) \textit{quit boxing} is a contiguous phrase, and (iii) \textit{quit} and \textit{he would stop} mean the same. We need to exploit (i) \textbf{structural} information, such as, the co-reference edge between \textit{His-James} (ii) the \textbf{sequential} information in \textit{quit boxing} and (iii) the \textbf{semantic} similarity (or synonymy relation) between \textit{quit} and \textit{he would stop}. \begin{figure} \centering \begin{tikzpicture} \node[draw, text width=7.3cm] at (-6,0) {\textbf{Source Doc:} ... At this point James Braddock (Russel Crowe) was a light heavyweight boxer, who was forced to retired from the ring after breaking his hand in his last fight. \textbf{His wife Mae had prayed for years that he would quit boxing, before becoming permanently injured}. ... \textbf{Conversation:} \\ Speaker 1(N): Yes very true, this is a real rags to riches story. Russell Crowe was excellent as usual. \\ Speaker 2(R): Russell Crowe owns the character of James Bradock, the unlikely hero who makes the most of his second chance. He's a good fighter turned hack. \\ Speaker 1(N): Totally! Oh by the way do you remember his wife ... how she wished he would stop\\ Speaker 2(P): His wife Mae had prayed for years that he would quit boxing, before becoming permanently injured.\\ }; \node[draw] at (-6,-6.2){\includegraphics[scale=0.37]{dep.png}}; \end{tikzpicture} \caption{Sample conversation from the Holl-E Dataset. For simplicity, we show only a few of the edges. The edge in blue corresponds to co-reference edge, the edges in green are dependency edges and the edge in red is the entity edge. } \label{dataset_example} \end{figure} To capture such multi-faceted information from the document and the conversation context we propose a new architecture which combines BERT with explicit sequence and structure information. We start with the deep contextualized word representations learnt by BERT which capture distributional semantics. We then enrich these representations with sequential information by allowing the words to interact with each other by passing them through a bidirectional LSTM as is the standard practice in many NLP tasks. Lastly, we add explicit structural information in the form of dependency graphs, co-reference graphs, and entity co-occurrence graphs. To allow interactions between words related through such structures, we use GCNs which essentially aggregate information from the neighborhood of a word in the graph. Of course, combining BERT with LSTMs in itself is not new and has been tried in the original work \cite{devlin-etal-2019-bert} for the task of Named Entity Recognition. Similarly, the work in \cite{bastings-etal-2017-graph} combines LSTMs with GCNs for the task of machine translation. To the best of our knowledge this is the first work which combines BERT with explicit structural information. We investigate several interesting questions in the context of dialogue response generation. For example, (i) Are BERT-based models best suited for this task? (ii) Should BERT representations be enriched with sequential information first or structural information? (iii) Are dependency graph structures more important for this task or entity co-occurence graphs? (iv) Given the recent claims that BERT captures syntactic information, does it help to explicitly enrich it with syntactic information using GCNs? To systematically investigate such questions we propose a simple plug-and-play \textit{Semantics-Sequences-Structures} (\textit{SSS}) framework which allows us to combine different semantic representations (GloVe, BERT, ELMo) with different structural priors (dependency graphs, co-reference graphs, \textit{etc.}). It also allows us to use different ways of combining structural and sequential information, \textit{e.g.}, LSTM first followed by GCN or vice versa or both in parallel. Using this framework we perform a series of experiments on the \textit{Holl-E} dataset and make some interesting observations. First, we observe that the conventional adaptation of GCNs for NLP tasks, where contextualized embeddings obtained through LSTMs are fed as input to a GCN, exhibits poor performance. To overcome this, we propose some simple alternatives and show that they lead to better performance. Second, we observe that while BERT performs better than GloVe and ELMo, it still benefits from explicit structural information captured by GCNs. We find this interesting because some recent works \cite{tenney-etal-2019-bert,jawahar-etal-2019-bert,hewitt-manning-2019-structural} suggest that BERT captures syntactic information, but our results suggest that there is still more information to be captured by adding explicit structural priors. Third, we observe that certain graph structures are more useful for this task than others. Lastly, our best model which uses a specific combination of semantic, sequential and structural information improves over the baseline by 7.95\%. \section{Related work} There is active interest in using external knowledge to improve informativeness of responses for goal-oriented as well as chit-chat conversations \cite{lowe2015,KGNCM,moghe-etal-2018-towards,wizard_of_wikipedia}. Even the teams participating in the annual Alexa Prize competition \cite{alexa_prize} have benefited by using several knowledge resources. This external knowledge can be in the form of knowledge graphs or unstructured texts such as documents. Many NLP systems including conversation systems use RNNs as their basic building block which typically capture $n$-gram or sequential information. Adding structural information through tree-based structures \cite{tai-etal-2015-improved} or graph based structures \cite{marcheggiani-titov-2017-encoding} on top of this has shown improved results on several tasks. For example, GCNs have been used to improve neural machine translation \cite{marcheggiani-etal-2018-exploiting} by exploiting the semantic structure of the source sentence. Similarly, GCNs have been used with dependency graphs to incorporate structural information for semantic role labelling \cite{marcheggiani-titov-2017-encoding}, neural machine translation \cite{bastings-etal-2017-graph} and entity relation information in question answering \cite{de-cao-etal-2019-question} and temporal information for neural dating of documents \cite{vashishth-etal-2018-dating}. There have been advances in learning deep contextualized word representations \cite{peters-etal-2018-deep,devlin-etal-2019-bert} with a hope that such representations will implicitly learn structural and relational information with interaction between words at multiple layers \cite{jawahar-etal-2019-bert,peters-etal-2018-dissecting}. These recent developments have led to many interesting questions about the best way of exploiting rich information from sentences and documents. We try to answer some of these questions in the context of background aware dialogue response generation. \section{Background} \label{sec:background} In this section, we provide a background on how GCNs have been leveraged in NLP to incorporate different linguistic structures. \if 0 \subsection{Deep Contextualized Representations} \noindent \textbf{ELMo} \cite{elmo} computes deep, contextualized word representations by training a neural network on a 1 Billion Word dataset with a language modeling objective. The architecture consists of a context-independent CNN layer followed by two layers of Bi-LSTMs. The final ELMo embedding of a word is the linear combination of its embeddings learned at these 3 layers. The embeddings learned at each layer can be further fine-tuned for a particular task. \\ \noindent \textbf{BERT} \cite{bert} uses a multi-layer bidirectional Transformer \cite{transformer} as its base architecture and is trained using a corpus containing 3.3B tokens. It uses a masked language modelling objective and next sentence prediction to learn deep bidirectional representations. \\ Due to space constraints, we refer the reader to the respective papers for more details. \fi \label{sec:gcn-background} The Syntactic-GCN proposed in \cite{marcheggiani-titov-2017-encoding} is a GCN \cite{kipf2016semi} variant which can model multiple edge types and edge directions. It can also dynamically determine the importance of an edge. They only work with one graph structure at a time with the most popular structure being the dependency graph of a sentence. For convenience, we refer to Syntactic-GCNs as GCNs from here on. Let $G$ denote a graph defined on a text sequence (sentence, passage or document) with nodes as words and edges representing a directed relation between words. Let $\mathcal{N}$ denote a dictionary of list of neighbors with $\mathcal{N}(v)$ referring to the neighbors of a specific node $v$, including itself (self-loop). Let $dir(u,v) \in \{in, out, self\}$ denote the direction of the edge, $(u,v)$. Let $\mathcal{L}$ be the set of different edge types and let $L(u,v) \in \mathcal{L}$ denote the label of the edge, $(u,v)$. The $(k+1)$-hop representation of a node $v$ is computed as \begin{equation} h^{(k+1)}_v=\sigma(\sum_{u \in\mathcal{N}(v)}g^{(k)}_{(u,v)}(W_{dir(u,v)}^{(k)}{h}_u^{(k)}+ b_{L(u,v)}^{(k)}) \label{eqn:final-syntactic-gcn} \end{equation} where $\sigma$ is the activation function, $g_{(u,v)} \in \mathbb{R}$ is the predicted importance of the edge $(u,v)$ and $h_v \in \mathcal{R}^m$ is node, $v$'s embedding. $W_{dir(u,v)} \in \{W_{in},W_{out}, W_{self}\}$ depending on the direction $dir(u,v)$ and $W_{in}$, $W_{self}$ and $W_{out} \in \mathcal{R}^{m*m}$. The importance of an edge $g_{(u,v)}$ is determined by an edge gating mechanism w.r.t. the node of interest, $u$ as given below: \begin{equation} g_{(u,v)} = sigmoid \big( h_{u} \ . \ W_{dir(u,v)} + b_{L(u,v)} \big) \label{eqn:edge-gating} \end{equation} In summary, a GCN computes new representation of a node $u$ by aggregating information from it's neighborhood $\mathcal{N}(v)$. When $k$=0, the aggregation happens only from immediate neighbors, i.e., 1 hop neighbors. As the value of $k$ increases the aggregation implicitly happens from a larger neighborhood. \section{Proposed Model} \label{sec:proposed} Given a document $D$ and a conversational context $Q$ the task is to generate the response $\mathbf{y} = y_1, y_2, ...., y_m$. This can be modeled as the problem of finding a $\mathbf{y}^*$ that maximizes the probability $P(\mathbf{y}$\textbar $D,Q)$ which can be further decomposed as \begin{align*} \mathbf{y}^*= \arg\max_\mathbf{y} \prod_{t=1}^{m} P(y_t | y_1,...,y_{t-1},Q,D) \end{align*} As has become a standard practice in most NLG tasks, we model the above probability using a neural network comprising of an encoder, a decoder, an attention mechanism and a copy mechanism. The copy mechanism essentially helps to directly copy words from the document $D$ instead of predicting them from the vocabulary. Our main contribution is in improving the document encoder where we use a plug-and-play framework to combine semantic, structural and sequential information from different sources. This enriched document encoder could be coupled with any existing model. In this work, we couple it with the popular GTTP model \cite{see-etal-2017-get} as used by the authors of the \textit{Holl-E} dataset. In other words, we use the same attention mechanism, decoder and copy mechanism as GTTP but augment it with an enriched document encoder. Below, we first describe the document encoder and then very briefly describe the other components of the model. We also refer the reader to the supplementary material for more details. \subsection{Encoder} Our encoder contains a semantics layer, a sequential layer and a structural layer to compute a representation for the document words which is a sequence of words $w_1$, $w_2$, ..., , $w_m$. We refer to this as a plug-and-play document encoder simply because it allows us to plug in different semantic representations, different graph structures and different simple but effective mechanisms for combining structural and semantic information. \noindent\textbf{Semantics Layer:} Similar to almost all NLP models, we capture semantic information using word embeddings. In particular, we utilize the ability of BERT to capture deep contextualised representations and later combine it with explicit structural information. This allows us to evaluate (i) whether BERT is better suited for this task as compared to other embeddings such as ELMo and GloVe and (ii) whether BERT already captures syntactic information completely (as claimed by recent works) or can it benefit form additional syntactic information as described below. \noindent\textbf{Structure Layer:} To capture structural information we propose multi-graph GCN, \textit{M-GCN}, a simple extension of GCN to extract relevant multi-hop multi-relational dependencies from multiple structures/graphs efficiently. In particular, we generalize $G$ to denote a labelled multi-graph, \textit{i.e.}, a graph which can contain multiple (parallel) labelled edges between the same pair of nodes. Let $\mathcal{R}$ denote the set of different graphs (structures) considered and let $G=\{\mathcal{N}_1, \mathcal{N}_2\dots \mathcal{N}_{|\mathcal{R}|}\}$ be a set of dictionary of neighbors from the $|\mathcal{R}|$ graphs. We extend the Syntactic GCN defined in Eqn: \ref{eqn:final-syntactic-gcn} to multiple graphs by having $|\mathcal{R}|$ graph convolutions at each layer as given in Eqn: \ref{eqn:m-gcn}. Here, $g\_conv(\mathcal{N})$ is the graph convolution defined in Eqn: \ref{eqn:final-syntactic-gcn} with $\sigma$ as the identity function. Further, we remove the individual node (or word) $i$ from the neighbourhood list $\mathcal{N}(i)$ and model the node information separately using the parameter $W_{self}$. \begin{equation} h^{(k+1)}_i = ReLU \big( (h^{(k)}_iW^{(k)}_{self} + \sum_{\mathcal{N} \in G } g\_conv(\mathcal{N}) \big) \label{eqn:m-gcn} \end{equation} This formulation is advantageous over having $|\mathcal{R}|$ different GCNs as it can extract information from multi-hop pathways and can use information across different graphs with every GCN layer (hop). Note that $h^{0}_i$ is the embedding obtained for word $v$ from the semantic layer. For ease of notation, we use the following functional form to represent the final representation computed by by M-GCN after $k$-hops starting from the initial representation $h^{0}_i$, given $G$. \begin{equation*} h_i = M\textnormal{-}GCN(h_i^0, G, k) \end{equation*} \noindent\textbf{Sequence Layer:} The purpose of this layer is to capture sequential information. Once again, following standard practice, we pass the word representations computed by the previous layer through a bidirectional LSTM to compute a sequence contextualized representation for each word. As described in the next subsection, depending upon the manner in which we combine these layers, the previous layer could either be the structure layer or the semantics layer. \begin{figure*} \centering \resizebox{\textwidth}{7.7 cm}{\includegraphics{SSSFramework.png}} \caption{The \textit{SSS} framework} \label{img:sss-design} \end{figure*} \subsection{Combining structural and sequential information} \label{sec:SSS Framework} As mentioned earlier, for a given document $D$ containing words $w_1, w_2, w_3, \dots, w_m$, we first obtain word representations $x_1, x_2, x_3, \dots, x_m$ using BERT (or ELMo or GloVe). At this point we have three different choices for enriching the representations using structural and sequential information: (i) structure first followed by sequence (ii) sequence first followed by structure or (iii) structure and sequence in parallel. We depict these three choices pictorially in Figure \ref{img:sss-design} and describe them below with appropriate names for future reference. \subsubsection{Sequence contextualized GCN (\textit{Seq-GCN})} \textit{Seq-GCN} is similar to the model proposed in \cite{bastings-etal-2017-graph,marcheggiani-titov-2017-encoding} where the word representations $x_1, x_2, x_3, \dots, x_m$ are first fed through a BiLSTM to obtain sequence contextualized representations as shown below. \begin{equation*} h_{i}^{seq} = BiLSTM(h_{i-1}^{seq}, x_i) \label{eqn:c-gcns-a} \end{equation*} These representations $h_1, h_2, h_3, \dots, h_m$ are then fed to the M-GCN along with the graph $G$ to compute a $k$-hop aggregated representation as shown below: \begin{equation*} h_i^{str} = M\textnormal{-}GCN(h_{i}^{seq}, G, k) \label{eqn:c-gcns-b} \end{equation*} This final representation $h_i^{final} = h_i^{str}$ for the $i$-th word thus combines semantics, sequential and structural information in that order. This is a popular way of combining GCNs with LSTMs but our experiments suggest that this does not work well for our task. We thus explore two other variants as explained below. \subsubsection{Structure contextualized LSTM (\textit{Str-LSTM})} Here, we first feed the word representations $x_1, x_2, x_3, \dots, x_m$ to M-GCN to obtain structure aware representations as shown below. \begin{equation*} h_i^{str} = M\textnormal{-}GCN(x_{i}, G, k) \label{eqn:g-lstms-a} \end{equation*} These structure aware representations are then passed through a BiLSTM to capture sequence information as shown below: \begin{align*} h_{i}^{seq} = BiLSTM(h_{i-1}^{seq}, h_i^{str}) \label{eqn:g-lstms-b} \end{align*} This final representation $h_i^{final} = h_i^{seq}$ for the $i$-th word thus combines semantics, structural and sequential information in that order. \subsubsection{Parallel GCN-LSTM (\textit{Par-GCN-LSTM})} Here, both M-GCN and BiLSTMs are fed with word embeddings $x_i$ as input to aggregate structural and sequential information independently as shown below: \begin{align*} h_i^{str} &= M\textnormal{-}GCN(x_{i}, G, k) \\ h_{i}^{seq} &= BiLSTM(h_{i-1}^{seq}, x_i) \end{align*} The final representation, $h_i^{final}$, for each word is computed as $h_i^{final} = h_{i}^{str} + h_{i}^{seq}$ and combines structural and sequential information in parallel as opposed to a serial combination in the previous two variants. \subsection{Decoder, Attention and Copy Mechanism} Once the final representation for each word is computed, an attention weighted aggregation, $c_t$, of these representations is fed to the decoder at each time step $t$. The decoder itself is a LSTM which computes a new state vector $s_t$ at every timestep $t$ as \begin{align*} s_t = LSTM (s_{t-1}, c_t) \end{align*} The decoder then uses this $s_t$ to compute a distribution over the vocabulary where the probability of the $i$-th word in the vocabulary is given by $p_i = softmax(Vs_t + Wc_t + b)_i$. In addition, the decoder also has a copy mechanism wherein, at every timestep $t$, it could either choose the word with the highest probability $p_i$ or copy that word from the input which was assigned the highest attention weight at timestep $t$. Such copying mechanism is useful in tasks such as ours where many words in the output are copied from the document $D$. We refer the reader to the GTTP paper for more details of the standard copy mechanism. \if 0 \noindent \textbf{Parallel v/s Sequential combination}: In sequential combination (\textit{Str-C-LSTM}, \textit{Seq-C-GCN}) , the last layer takes in a particular contextual word representation and modifies it by incorporating additional information. Whereas with the parallel model (\textit{Par-GCN-LSTM}), both the sequence and structure contextual representation are directly used. In sequential combination, a latter layer might modify the information from the preceding layer beyond recovery through direct means. It is a concerning issue when a layer adds additional information rather than merely performing a (non) linear projection as it is susceptible to significantly modifying the original input. This is termed as the node information morphing in the GCN literature \cite{vijayan2018hopf, li2018deeper}, where the information of the node gets morphed by neighborhood information with every new layer. This is not an issue with the parallel model but a weighted combination is not powerful enough to learn complex correlations between outputs. \fi \section{Experimental setup} \label{sec:experiments} In this section, we briefly describe the dataset and task setup followed by the pre-processing steps we carried to obtain different linguistic graph structures on this dataset. We then describe the different baseline models. \subsection{Dataset description} We evaluate our models using Holl-E, an English language movie conversation dataset \cite{moghe-etal-2018-towards} which contains $\sim$ 9k movie chats and $\sim$ 90k utterances. Every chat in this dataset is associated with a specific background knowledge resource from among the plot of the movie, the review of the movie, comments about the movie, and occasionally a fact table. Every even utterance in the chat is generated by copying and or modifying sentences from this unstructured background knowledge. The task here is to generate/retrieve a response using conversation history and appropriate background resource. Here, we focus only on the \textit{oracle} setup where the correct resource from which the response was created is provided explicitly. We use the same train, test, and validation splits as provided by the authors of the paper. \subsection{Construction of linguistic graphs} We consider leveraging three different graph-based structures for this task. Specifically, we evaluate the popular syntactic word dependency graph (\textit{Dep-G}), entity co-reference graph (\textit{Coref-G}) and entity co-occurrence graph (\textit{Ent-G}). Unlike the word dependency graph, the two entity level graphs can capture dependencies that may span across sentences in a document. We use the dependency parser provided by SpaCy\footnote{https://spacy.io/} to obtain the dependency graph (\textit{Dep-G}) for every sentence. For the construction of the co-reference graph (\textit{Coref-G}), we use the NeuralCoref model \footnote{https://github.com/huggingface/neuralcoref. Code at https://github.com/nikitacs16/horovod\_gcn\_pointer\_generator } integrated with SpaCy. For the construction of the entity graph (\textit{Ent-G}), we first perform named-entity recognition using SpaCy and connect all the entities that lie in a window of $k=20$. \subsection{Baselines} We categorize our baseline methods as follows: \\ \textbf{Without Background knowledge}: We consider the simple Sequence-to-Sequence (S2S) \cite{neural_conversation_model} architecture that conditions the response generation only on the \textit{previous} utterance and completely ignores the other utterances as well as the background document. We also consider HRED \cite{HRED}, a hierarchical variant of the S2S architecture which conditions the response generation on the entire conversation history in addition to the last utterance. Of course, we do not expect these models to perform well as they completely ignore the background knowledge but we include them for the sake of completeness.\\ \textbf{With Background Knowledge}: To the S2S architecture we add an LSTM encoder to encode the document. The output is now conditioned on this representation in addition to the previous utterance. We refer to this architecture as S2S-D. Next, we use GTTP \cite{see-etal-2017-get} which is a variant of the S2S-D architecture with a copy-or-generate decoder; at every time-step, the decoder decides to copy from the background knowledge or generate from the fixed vocabulary. We also report the performance of the BiRNN + GCN architecture that uses dependency graph only as discussed in \cite{marcheggiani-titov-2017-encoding}. Finally, we note that in our task many words in the output need to be copied sequentially from the input background document which makes it very similar to the task of span prediction as used in Question Answering. We thus also evaluate BiDAF \cite{BIDAF}, a popular question-answering architecture, that extracts a span from the background knowledge as a response using complex attention mechanisms. For a fair comparison, we evaluate the spans retrieved by the model against the ground truth responses. We use BLEU-4 and ROUGE (1/2/L) as the evaluation metrics as suggested in the dataset paper. Using automatic metrics is more reliable in this setting than the open domain conversational setting as the variability in responses is limited to the information in the background document. We provide implementation details in the Appendix A. \section{Results and Discussion} \label{sec:analysis} In Table \ref{table:baselines_and_best_model}, we compare our architecture against the baselines as discussed above. \textit{SSS}(BERT) is our proposed architecture in terms of the \textit{SSS} framework. We report best results within \textit{SSS} chosen across 108 configurations comprising of four different graph combinations, three different contextual and structural infusion methods, three M-GCN layers, and, three embeddings. \begin{table} \begin{center} \resizebox{\linewidth}{!}{% \begin{tabular}{|c|c|c|c|c|} \hline Model & BLEU & \multicolumn{3}{c|}{ROUGE} \\ \hline & & 1 & 2 & L \\ \hline S2S & 4.63 & 26.91 & 9.34 & 21.58 \\ HRED & 5.23 & 24.55 & 7.61 & 18.87 \\ \hline S2S-D & 11.71 & 26.36 & 13.36 & 21.96 \\ GTTP & 13.97 & 36.17 & 24.84 & 31.07 \\ BiRNN+GCN & 14.70 & 36.24 & 24.60 & 31.29 \\ BiDAF & 16.79 & 26.73 & 18.82 & 23.58 \\ \hline \textit{SSS}(GloVe) & 18.96 & 38.61 & 26.92 & 33.77 \\ \textit{SSS}(ELMo) & 19.32 & 39.65 & 27.37 & 34.86 \\ \textit{SSS}(BERT) & \textbf{22.78} & \textbf{40.09} & \textbf{27.83} & \textbf{35.20} \\ \hline \end{tabular} } \caption{Results of automatic evaluation. Our proposed architecture \textit{SSS}(BERT) outperforms the baseline methods.} \label{table:baselines_and_best_model} \end{center} \end{table} The best model was chosen based on performance of the validation set. From Table \ref{table:baselines_and_best_model}, it is clear that our improvements in incorporating structural and sequential information with BERT in the \textit{SSS} encoder framework significantly outperforms all other models. \subsection{Qualitative Evaluation} We conducted human evaluation for the \textit{SSS} models from Table \ref{table:baselines_and_best_model} against the generated responses of GTTP. We presented 100 randomly sampled outputs to three different annotators. The annotators were asked to pick from four options: A, B, both, and none. The annotators were told these were conversations between friends. Tallying the majority vote, we obtain win/loss/both/none for \textit{SSS}(BERT) as 29/25/29/17, \textit{SSS}(GloVe) as 24/17/47/12 and \textit{SSS}(ELMo) as 22/23/41/14. This suggests qualitative improvement using \textit{SSS} framework. We also provide some generated examples in the Appendix B1. We found that the \texttt{SSS} framework had less confusion in generating the opening responses than the GTTP baseline. These ``conversation starters'' have a unique template for every opening scenario and thus have different syntactic structures respectively. We hypothesize that the presence of dependency graphs over these respective sentences helps to alleviate the confusion as seen in Example 1. The second example illustrates why incorporating structural information is important for this task. We also observed that \textit{SSS} encoder framework does not improve on the aspects of human creativity such as diversity, initiating a context-switch, and common sense reasoning as seen in Example 3. \begin{table} \begin{center} \resizebox{\linewidth}{!}{% \begin{tabular}{|c|c|c|c|c|c|} \hline Emb & Paradigm & BLEU & \multicolumn{3}{c|}{ROUGE} \\ \hline & & & 1 & 2 & L \\ \hline \multirow{3}{*}{GloVe} & Sem & 4.4 & 29.72 & 11.72 & 22.99 \\ & Sem+Seq & 14.83 & 36.17 & 24.84 & 31.07 \\ & \textit{SSS}& 18.96 & 38.61 & 26.92 & 33.77 \\ \hline \multirow{3}{*}{ELMo} & Sem & 14.36 & 32.04 & 18.75 & 26.71 \\ & Sem+Seq & 14.61 & 35.54 & 24.58 & 30.71 \\ & \textit{SSS}& 19.32 & 39.65 & 27.37 & 34.86 \\ \hline \multirow{3}{*}{BERT} & Sem & 11.26 & 33.86 & 16.73 & 26.44 \\ & Sem+Seq & 18.49 & 37.85 & 25.32 & 32.58 \\ & \textit{SSS}& 22.78 & 40.09 & 27.83 & 35.2 \\ \hline \end{tabular} } \end{center} \caption{Performance of components within the \textit{SSS} framework.} \label{table:SSS-Framework} \end{table} \subsection{Ablation studies on the \textit{SSS} framework} We report the component-wise results for the \textit{SSS} framework in Table \ref{table:SSS-Framework}. The \textit{Sem} models condition the response generation directly on the word embeddings. We observe that ELMo and BERT perform much better than GloVe embeddings. The \textit{Sem+Seq} models condition the decoder on the representation obtained after passing the word embeddings through the LSTM layer. These models outperform their respective \textit{Sem} models. The gain with ELMo is not significant because the underlying architecture already has two BiLSTM layers whcih are anyways being fine-tuned for the task. Hence the addition of one more LSTM layer may not contribute to learning any new sequential word information. It is clear from Table \ref{table:SSS-Framework} that the \textit{SSS} models, that use structure information as well, obtain a significant boost in performance, validating the need for incorporating all three types of information in the architecture. \begin{table*} \begin{center} \resizebox{\linewidth}{!}{% \begin{tabular}{|c|cccc|cccc|cccc|} \hline Emb & \multicolumn{4}{c|}{Seq-GCN} & \multicolumn{4}{c|}{Str-LSTM} & \multicolumn{4}{c|}{Par-GCN-LSTM} \\ \hline & \multicolumn{1}{c|}{BLEU} & \multicolumn{3}{c|}{ROUGE} & \multicolumn{1}{|c|}{BLEU} & \multicolumn{3}{c|}{ROUGE} & \multicolumn{1}{c|}{BLEU} & \multicolumn{3}{c|}{ROUGE} \\ \hline & \multicolumn{1}{c|}{} & \multicolumn{1}{c|}{1} & \multicolumn{1}{c|}{2} & \multicolumn{1}{c|}{L} & \multicolumn{1}{c|}{} & \multicolumn{1}{c|}{1} & \multicolumn{1}{c|}{2} & \multicolumn{1}{c|}{L} & \multicolumn{1}{c|}{} & \multicolumn{1}{c|}{1} & \multicolumn{1}{c|}{2} & \multicolumn{1}{c|}{L} \\ \hline GloVe & 15.61 & 36.6 & 24.54 & 31.68 & 18.96 & 38.61 & 26.92 & 33.77 & 17.1 & 37.04 & 25.70 & 32.2 \\ \hline ELMo & 18.44 & 37.92 & 26.62 & 33.05 & 19.32 & 39.65 & 27.37 & 34.86 & 16.35 & 37.28 & 25.67 & 32.12 \\ \hline BERT & 20.43 & 40.04 & 26.94 & 34.85 & 22.78 & 40.09 & 27.83 & 35.20 & 21.32 & 39.9 & 27.60 & 34.87 \\ \hline \end{tabular}} \end{center} \caption{Performance of different hybrid architectures to combine structural information with sequence information} \label{table:SSS-Models} \end{table*} \subsection{Combining structural and sequential information} The response generation task of our dataset is a span based generation task where phrases of text are expected to be copied or generated as they are. The sequential information is thus crucial to reproduce these long phrases from background knowledge. This is strongly reflected in Table \ref{table:SSS-Models} where \textit{Str-LSTM} which has the LSTM layer on top of GCN layers performs the best across the hybrid architectures discussed in Figure \ref{img:sss-design}. The \textit{Str-LSTM} model can better capture sequential information with structurally and syntactically rich representations obtained through the initial GCN layer. The \textit{Par-GCN-LSTM} model performs second best. However, in the parallel model, the LSTM cannot leverage the structural information directly and relies only on the word embeddings. \textit{Seq-GCN} model performs the worst among all the three as the GCN layer at the top is likely to modify the sequence information from the LSTMs. \subsection{Understanding the effect of structural priors} While a combination of intra-sentence and inter-sentence graphs is helpful across all the models, the best performing model with BERT embeddings relies only on the dependency graph. In case of GloVe based experiments, the entity and co-reference relations were not independently useful with the \textit{Str-LSTM} and \textit{Par-GCN-LSTM} models, but when used together gave a significant performance boost, especially for \textit{Str-LSTM}. However, most of the BERT based and ELMo based models achieved competitive performance with individual entity and co-reference graphs. There is no clear trend across the models. Hence, probing these embedding models is essential to identify which structural information is captured implicitly by the embeddings and which structural information needs to be added explicitly. For the quantitative results, please refer to the Appendix B2. \subsection{Structural information in deep contextualised representations} Earlier work has suggested that deep contextualized representations capture syntax and co-reference relations \cite{peters-etal-2018-dissecting,jawahar-etal-2019-bert,tenney-etal-2019-bert, hewitt-manning-2019-structural}. We revisit Table \ref{table:SSS-Framework} and consider the \textit{Sem+Seq} models with ELMo and BERT embeddings as two architectures that \textit{implicitly} capture structural information. We observe that the \textit{SSS} model using the simpler GloVe embedding outperforms the ELMo \textit{Sem+Seq} model and performs slightly better than the BERT \textit{Sem+Seq} model. Given that the \textit{SSS} models outperform the corresponding \textit{Sem+Seq} model, the extent to which the deep contextualized word representations learn the syntax and other linguistic properties implicitly is questionable. Also, this calls for better loss functions for learning deep contextualised representations that can incorporate structural information explicitly. More importantly, all the configurations of \textit{SSS} (GloVe) have lesser memory footprint in comparison to both ELMo and BERT based models. Validation and training of GloVe models require one-half, sometimes even one-fourth of computing resources. Thus, the simple addition of structural information through the GCN layer to the established Sequence-to-Sequence framework that can perform comparably to stand-alone expensive models is an important step towards Green AI\cite{green_ai}. \section{Conclusion} We demonstrated the usefulness of incorporating structural information for the task of background aware dialogue response generation. We infused the structural information explicitly in the standard semantic+sequential model and observed performance boost. We studied different structural linguistic priors and different ways to combine sequential and structural information. We also observe that explicit incorporation of structural information helps the richer deep contextualized representation based architectures. We believe that the analysis presented in this work would serve as a blueprint for analysing future work on GCNs ensuring that the gains reported are robust and evaluated across different configurations.
{'timestamp': '2020-06-01T02:03:57', 'yymm': '2005', 'arxiv_id': '2005.14315', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14315'}
arxiv
\section{Introduction} Multiple unmanned aerial vehicles (UAVs) have attracted considerable interest these years, of which prospective applications include disaster area or maritime surveillance, border patrol, environmental sensing, delivery service, etc (\cite{jenie2016taxonomy}). This determines that the UAVs would fly in an integrated airspace with a variety of possible conflict objects therein (See in Fig. \ref{fig:environment}). However, one key issue that limits the extensive application and the integration into such complex dynamic integrated airspace system of the UAVs is the collision avoidance problem (\cite{dalamagkidis2008unmanned, dalamagkidis2011integrating, shively2018unmanned}), which is also called as conflict detection and resolution in the literature . Various approaches for collision avoidance of UAVs have been developed these years. \cite{898217} presented cohesive discussion and comparative evaluation of 68 modeling methods for conflict detection and resolution. \cite{lalish2012distributed} discussed the related approaches based on the degree of centralization, the type of the vehicle model, the number of vehicles, and the heterogeneity or homogeneity of the vehicles, respectively. \cite{hoy2015algorithms} mainly reviewed the development of model predictive control (MPC), sensor-based boundary following, sensor-based path planning, and some reactive methods on collision avoidance. Moving obstacles and multi-vehicle situations were also discussed. \cite{mahjri2015review} summarized the functions of a collision avoidance system into three steps: the sensing, the detection, and the resolution, and reviewed the related approaches from these three aspects. Besides, \cite{zhang2018survey} presented an overview of collision avoidance approaches in large, middle and small scales, respectively. The above mentioned survey papers summarized the related research from many different aspects. But one common fact indicated by these papers is that most of these approaches are designed for some specific conflict scenarios (\cite{garcia2016biologically},\cite{dentler2019collision} ). This means any single approach cannot be used to completely solve the problem. To study out a solution for general conflict resolution in the complex dynamic integrated airspace, \cite{jenie2016taxonomy} firstly proposed a taxonomy of conflict detection and resolution approaches for UAVs based on their types of surveillance, coordination, maneuver, and autonomy, then discussed possible combinations of available approaches for a complete solution. However, specific implementations of such approach combinations were not given. Therefore, this paper aims to design a hierarchical collision avoidance system, which is capable of detecting and resolving general conflicts, for autonomous multiple fixed-wing UAVs in the complex dynamic integrated airspace. The main contribution of this paper is the proposal and implementation of the hierarchical collision avoidance architecture. \begin{itemize} \item[-] Firstly, a three-layered collision avoidance architecture dependent on local communication and onboard sensing is proposed for multiple fixed-wing UAVs, by analyzing characteristics of existing methods and hierarchical modeling of the local airspace. \item[-] Then a specific algorithm implementation is studied for each layer of the collision avoidance architecture. \item[-]Finally, the effectiveness of the proposed methodology is evaluated and validated by comparative simulations carried out under both deterministic and probabilistic sensing conditions. \end{itemize} \section{Problem Formulation} \subsection{Preliminary concept definition} Before further discussion, two concepts should be clarified: \begin{definition}[\textbf{Collision}]\label{def_1} For the $i$-th UAV in a $n$-UAV system ($i\in\{1,\cdots,n\}$) and any possible conflict object $o$ in the airspace, a collision happens if \begin{equation}\label{eq:collision_condition} d_{i,o}\leq R_s \end{equation} where $d_{i,o}$ represents the distance between the $i$-th UAV and the conflict object $o$, $R_s$ denotes the restricted safe radius of the UAVs. \end{definition} \begin{definition} [\textbf{Conflict}] For a UAV, a conflict is detected if a collision is predicted to happen on it within a specific time period $\tau_w$ in the future, where $\tau_w$ is the early warning time for collision conflicts. \end{definition} Then two main functions of collision avoidance control are to firstly detect potential conflicts and then take actions to avoid collisions if any conflicts are detected. \subsection{Conflict scenarios analysis} A collision avoidance system aims to enable the UAVs to handle all possible collision conflicts to ensure safe and orderly operations. To this end, various possible conflict objects in the complex integrated airspace are first discussed. See Table \ref{tb:obstacle_categorization}. \begin{table}[htb] \caption{Classifications of various conflict objects in the integrated airspace}\label{tb:obstacle_categorization} \begin{center} \renewcommand{\arraystretch}{1.2} \begin{threeparttable} \begin{tabular}{c|c|c|c} \hline \multicolumn{2}{c|}{ Classification Principles} & Static &Dynamic \\\hline \multirow{6}{*}{Non-cooperative} & \multirow{3}{*}{Unknown} & \multirow{3}{*}{new buildings} & birds \\ ~ & ~ & ~ & air masses \\ ~ & ~ & ~ & enemy UAVs \\ \cline{2-4} ~ & \multirow{3}{*}{Known} & mountains & ~ \\ ~ & ~ & old buildings & ~\\ ~ & ~ & lighthouses & ~ \\\hline \multirow{3}{*}{Cooperative} &\multirow{2}{*}{Unknown} & ~ &civil aircrafts\\ ~ & ~ & ~ & other UAVs \\ \cline{2-4} ~ & Known & ~ & neighbor UAVs \\ \hline \end{tabular} \end{threeparttable} \end{center} \end{table} Firstly, in the consideration of motion states, conflict objects are classified as static and dynamic. % Then according to whether there is active avoidance intention in the process of conflict resolution, they are classified into cooperative and non-cooperative ones. For example, objects like flying birds, balloons, and air masses, which are very much likely to disturb the flight but cannot implement active avoidance if conflicts exist, are classified as non-cooperative. % Civil aircraft are treated as cooperative because generally they can take active collision avoidance maneuvers based on some common rules, although the unknown nature of UAVs to the civil aircraft and vice versa make the cooperation rather challenging. % Thirdly, based on the ways of information acquisition, those obtained by prior knowledge or active communications are included in the known category. Other objects like some new buildings or other aircraft, requiring real-time perception, are included in the unknown category. \begin{figure}[t] \begin{center} \includegraphics[width=8.4cm]{environment} \caption{Prospective mission airspace and possible conflict objects therein} \label{fig:environment} \end{center} \end{figure} \subsection{Collision avoidance objective} This paper mainly studies real-time online collision avoidance. Therefore, those known environmental objects, that can generally be handled before the flight through trajectory pre-planning, are not the focus of this paper. For the rest of the conflict objects, taking the $i$-th UAV in a $n$-UAV system as a reference, denote the set of its neighbor UAVs as $\mathcal{N}_i$, the set of other potential unknown conflict objects as $\mathcal{O}_i$. Then all possible conflict objects of the $i$-th UAV can be represented as the augmented obstacle set: $$\mathcal{O}_i^{aug}\coloneqq \mathcal{N}_i\cup\mathcal{O}_i$$ Then according to Definition \ref{def_1}, the primary objective of collision avoidance control would be to keep a separate distance larger than $R_s$ for the $i$-th UAV from all obstacles in $\mathcal{O}_i^{aug}$, e.g., to ensure \begin{equation}\label{eq:CA_requirement} d_{i,o} > R_s, \forall o\in\mathcal{O}_i^{aug} \end{equation} Moreover, except for the collision avoidance requirement in \eqref{eq:CA_requirement}, dynamic constraints of the minimum cruising speed and limited heading rate, and optimization for the maneuver energy consumption and the required task performance index should also be considered in the collision avoidance strategy. \subsection{Kinematics} This paper studies the collision avoidance problem for UAVs implementing planar flights. Thus the fixed-wing UAVs are modeled as unicycle kinematics: \begin{equation}\label{eq:kinematics} \begin{cases} \dot x =v\cos\phi \\ \dot y=v\sin\phi \\ \dot\phi = u \end{cases} \end{equation} where, $(x,y,\phi)^T$ represents the state vector of the UAV, $(x,y)^T$ denotes the position and $\phi$ describes the heading angle, $v$ is the cruising speed, which is set to be constant during the flight, and the control input $u = \omega$ denotes the heading rate of the UAV. Meanwhile, the control input is subject to the following constraint: \begin{equation} u \in \mathcal{U}, \mathcal{U}\coloneqq\{\omega|-\omega_{max}\leq \omega \leq \omega_{max}\} \end{equation} where $\omega_{max}$ represents the upper bound of the heading rate. Considering the discrete control process during the flight, we use the second-order Runge-Kutta method to obtain the discrete kinematics model. \section{Hierarchical collision avoidance architecture} \newcommand{\tabincell}[2]{\begin{tabular}{@{}#1@{}}#2\end{tabular}} \begin{table*}[htb] \caption{Algorithm review}\label{tb:Algorithm_comparation} \begin{center} \renewcommand{\arraystretch}{1.2} \begin{threeparttable} \begin{tabular}{c|c|cc|ccc|c} \hline\hline ~ & ~& \tabincell{c}{Computation \\ complexity}& Optimality & MV & MO & IRM & References \\\hline \multirow{4}{*}{\tabincell{c}{Path \\ planning}} & Graph search approaches & high & $\blacktriangle$ &\cmark&$ \blacktriangle$&$\blacktriangle$&[1],[2]\\ ~ & Mathematical programming & high& \cmark& \cmark & $\blacktriangle$& \cmark&[1],[5] \\ ~ & Artificial heuristic approaches & high & \cmark & \cmark&$\blacktriangle$& \cmark& [3],[5] \\ ~ & Potential field based planning& low & $\blacktriangle$ &\cmark&$\blacktriangle$&$\blacktriangle$& [1]\\ \hline \multirow{2}{*}{\tabincell{c}{Optimized \\ control}} & Game theory based approaches & high & $\blacktriangle$& \cmark& \xmark& \cmark & [6],[7]\\ ~ & Distributed model predictive control & $\bigstar$ & \cmark & \cmark &\cmark&\cmark& [4] \\ \hline \multirow{3}{*}{\tabincell{c}{Reactive \\ approaches}} & Geometric approaches & low & \xmark &$\blacktriangle$&\cmark& $\blacktriangle$ & [4]\\ ~ & Rule-based approaches & low & \xmark&\cmark&\xmark&$\blacktriangle$&[1]\\ ~ & Potential field based reactive approaches & low & \xmark &\cmark&\cmark&$\blacktriangle$& [1],[4]\\ \hline \hline \end{tabular} \begin{tablenotes} \footnotesize \item[*] Reference: [1] \cite{zhang2018survey}, [2] \cite{dadkhah2012survey}, [3] \cite{yu2015sense}, [4] \cite{hoy2015algorithms}, [5] \cite{mahmoudzadeh2018online}, [6] \cite{mylvaganam2018autonomous}, [7] \cite{mylvaganam2017differential} \item[*] Key: MV (\textbf{M}ultiple \textbf{V}ehicles), MO (\textbf{M}oving \textbf{O}bstacles), IRM (\textbf{I}nput \textbf{R}estricted \textbf{M}odel) \item[*] Symbols: $\bigstar$ (Not necessarily high), $\blacktriangle$ (With some disadvantages). \end{tablenotes} \end{threeparttable} \end{center} \end{table*} \subsection{Three-layered collision avoidance framework } \begin{figure} \begin{center} \includegraphics[width=6.0cm]{local_airspace_partition} \caption{The three-layered conflict detection region} \label{fig:local_airspace_partition} \end{center} \end{figure} The two main functions of collision avoidance control can be briefly described as conflict detection and resolution. Conflict detection using one single approach once for all can easily fail or delay because of sensing inaccuracy and uncertainty, or communication delay and interrupts. Besides, approaches for conflict resolution in the literature have different advantages and disadvantages in different conflict situations. Therefore, a three-layered collision avoidance architecture including a three-layered airspace partition for hierarchical conflict detection and a three-layered complementary conflict resolution strategy is proposed in this subsection. \subsubsection{\textbf{Three-layered airspace for hierarchical conflict detection}} Dynamic properties at different ranges from the UAV can vary greatly. Thus, a conflict detection region $\Omega_c$ is introduced and partitioned into three layers to implement hierarchical conflict detection: \begin{equation} \begin{split} &\qquad\Omega_c=\Omega_o \cup \Omega_m \cup \Omega_i \\ &\begin{cases} \Omega_o& = \{\bm{P}| R_m < d_{\bm{P}} \leq R_o\leq R_d\}\\ \Omega_m &=\{\bm{P} | R_i < d_{\bm{P}} \leq R_m\}\\ \Omega_i &= \{\bm{P} | R_s < d_{\bm{P}} \leq R_i \} \end{cases} \end{split} \label{eq:conflict_region_partition} \end{equation} where $R_o$, $R_m$ and $R_i$ are the radius of the three-layered conflict detection airspace, $d_{\bm{P}}$ denotes the distance of point $\bm{P}$ in the nearby airspace from the UAV. See Fig. \ref{fig:local_airspace_partition}. Note that $\Omega_d\supseteq\Omega_c$ is the perceptible area of the UAV. The outer-layer airspace has quite long distance from the UAV, which indicates that conflict situations in this area are essentially determined to the reference flight trajectories. Situations in middle-layer airspace is the most dynamic and complex. Motion state variations of neighbor UAVs, other aircraft, balloons, and the UAV itself, increase the uncertainty of conflict situations in this area. The inner-layer airspace has very short distance from the UAV, which determines the UAV should be able to detect potential conflicts very quickly so as to leave enough time for collision avoidance actions. Therefore, a hierarchical conflict detection and resolution scheme is developed in the consideration of these properties. \subsubsection{\textbf{Three-layered conflict detection and resolution}} Approaches for conflict resolution in the literature can be roughly classified into three categories: path planning, optimized control, and reactive approaches. See Table \ref{tb:Algorithm_comparation}. To maximize the advantages of different algorithms, a hierarchical collision avoidance framework integrating these three types of algorithms is proposed for general conflict scenarios. See Fig. \ref{fig:CA_scheme_framewrk}. Considering the range from the UAV and the level of dynamic complexity, a hierarchical collision avoidance framework integrating path planning schemes for the outer layer, optimized control for the middle layer and reactive methods for the inner layer is developed. Notably, the inner-layer reactive control law has the highest priority when it is activated. The middle-layer optimized control scheme has the second priority, which can provides better optimization and flexibility for highly dynamic middle-layer airspace. When there is no conflict detected, the UAVs fly according to the scheduled trajectories. \begin{figure}[h] \centering \includegraphics[width=8.4cm]{framework} \caption{The three-layered collision avoidance framework (CR: the abbreviation of "conflict resolution")} \label{fig:CA_scheme_framewrk} \end{figure} \subsection{Methodology} This subsection studies to present an implementation for the proposed hierarchical collision avoidance framework. \subsubsection{\textbf{Outer-layer path planning using sub-targets and Cubic B-spline}} Path planning approaches have been widely studied for collision avoidance problems. \cite{shuai2014real} proposed a real-time obstacle avoidance method using a sub-targets algorithm and Cubic B-spline for mobile robots that move to a specified target point. Inspired by his work, a conflict detection scheme based on the closest point of environment obstacles from the reference flight path is developed, with consideration of flight tracking error. This approach relies on the onboard sensing system for spacial status information updating. In this way, the sub-targets generation procedure in \cite{shuai2014real} is extended to curved-path following scenarios. Then a collision-free smooth path is generated using the sub-targets and Cubic B-spline algorithms as in \cite{shuai2014real}. \subsubsection{\textbf{Middle-layer DMPC-based collision avoidance}} Distributed model predictive control (DMPC) can explicitly deal with inter-agent constraints and find approximate optimal solutions for subsystems. Besides, the state prediction of MPC provides prior advantage in conflict detection. Thus a DMPC collision avoidance strategy, which executed by all the subsystems synchronously, is developed. The distributed controllers will rely on the local communication system and onboard sensing system for environmental information collection. Firstly, the conflict detection procedure based on state prediction is implemented. Since the reference trajectory is already known, the reference state of each UAV in the future could be computed and transmitted to its neighbor UAVs with the newest state information. Then for the $i$-th UAV in a $n$-UAV system, the assumed motion states of all neighbor UAVs in $\mathcal{N}_i$ could be computed. Also, the sensing system obtains the real-time information of environmental objects in $\mathcal{O}_i$. Thus the distance variations of the UAV from its neighbor UAVs and other environmental objects, e.g., all obstacles in $\mathcal{O}_i^{aug}$, could be predicted for conflict detection. Then if any conflict is detected at time interval $k$, the optimal local collision avoidance input sequence $\bm{u}_{i,(k)}^{\ast} = \{u_{i,(k+0|k)}^{\ast},\cdots,u_{i,(k+N-1|k)}^{\ast}\}$ would be generated by solving the following optimization problem: \begin{equation} \label{eq:DMPC_scheme} \begin{split} &J_{i,(k)}^{\ast}=\min_{\bm{u}_{i,(k)}}J_{i,(k)}\left(\bm{X}_{i,(k)},\bm{u}_{i,(k)}, \tilde{\bm{X}}_{(k-1)}^{\mathcal{O}_{i}^{aug}}\right) \\ &s.t. \\ &\quad u_{i,(k+l|k)}\in\mathcal{U}, \forall l = 0,1,\cdots,N-1 \end{split} \end{equation} where $\bm{X}_{i,(k)}$ is the newest state, $\tilde{\bm{X}}_{(k-1)}^{\mathcal{O}_{i}^{aug}}$ represents the predicted motion states of $\mathcal{O}_i^{aug}$. Once the local collision avoidance command sequence $\bm{u}_{i,(k)}^{\ast}$ has been generated, the first item $u_{i,(k+0|k)}^{\ast}$ would be applied to the UAV, and the complete sequence would be transmitted to its neighbor UAVs for next conflict detection. The whole process is summarized in Algorithm \ref{alg:DMPC_based_CDR}. Due to the limitations of the length of the paper, this algorithm is not rigorous detailed and a complete description and analysis will be given in our another paper later. \begin{algorithm}[htbp] \caption{Middle-layer DMPC-based collision avoidance} \label{alg:DMPC_based_CDR} \begin{algorithmic}[1] \State Parameter initialization: $T$, $N$, $R_m$, $R_s$, etc. \State Spacial status information updating: $\mathcal{O}_i^{aug}$ \State $k \gets k+1$ \State Conflict detection based on motion prediction \Procedure{Conflict Resolution}{} \State Calculate $\bm{u}_{i,(k)}^{\ast}$ by solving \eqref{eq:DMPC_scheme} \State Apply $u_{i,(k+0|k)}^{\ast}$ to the UAV \State Transmit the newest state and the control sequence $\bm{u}_{i,(k)}^{\ast}$ to neighbor UAVs \EndProcedure \State Returen to step 2 \end{algorithmic} \end{algorithm} \subsubsection{\textbf{Inner-layer reactive collision avoidance}} Inner-layer conflict detection and resolution provides the last guarantee for the flight safety of UAVs. Thus for quick response to conflicts, sufficient conditions for non-conflicting flights of any two UAVs in a short distance were derived in previous work (\cite{8996560}), which is utilized for conflict detection. Then a reactive collision avoidance control law is firstly proposed for two-UAV conflict based on the collision-free conditions: \begin{equation}\label{eq:inner_layer_CA} u_i=\rho k_{\psi}\left(\frac{1}{2}\arccos{\frac{\bm{v}_{ij}\cdot\bm{P}_{ij}}{|\bm{v}_{ij}||\bm{P}_{ij}|}}-\pi/4\right) \end{equation} where, parameter $\rho$ is the sign of turning direction, $k_{\psi}$ in (1/s) is a constant coefficient, which transforms the desired heading change into the desired heading rate, $\bm{v}_{ij}$ and $\bm{P}_{ij}$ are the relative velocity and position vectors of the $i$-th and the $j$-th UAVs, respectively. Moreover, the collision avoidance control law in \eqref{eq:inner_layer_CA} was further developed by integrating some additional rules on direction choosing, for more complicated conflict scenarios which involves more than two UAVs (\cite{8996560}). \subsection{Overall hierarchical algorithm} Finally, the overall hierarchical implementation of the hierarchical collision avoidance system is developed by integrating the three approaches described above, which is presented in Algorithm \ref{alg:overall_SMS_algorithm}. \begin{algorithm}[htbp] \caption{The distributed hierarchical collision avoidance for multiple UAVs} \label{alg:overall_SMS_algorithm} \begin{algorithmic}[1] \Procedure{Parameter Initialization}{} \State Initializa $\omega_{max}$, $T$, $R_o$, $R_m$, $R_i$, $R_s$, and $N$; \State $inner\_conflict\_flag \gets 0$ \State $middle\_conflict\_flag \gets 0$ \State $outer\_conflict\_flag \gets 0$ \EndProcedure \State Update data for $\mathcal{O}_{i,(k)}^{aug} = \mathcal{N}_{i,(k)} \cup \mathcal{O}_{i,(k)}$ \State $k \gets k+1$ \Procedure{Conflict Detection}{} \State \textbf{return} $inner\_conflict\_flag$, \State $middle\_conflict\_flag$, and $outer\_conflict\_flag$ \EndProcedure \Procedure{Conflict Resolution}{} \If{$inner\_conflict\_flag==1$} \State \textbf{Do} reactive cillision avoidance control \ElsIf{$middle\_conflict\_flag==1$} \State \textbf{Do} DMPC based collision avoidance \ElsIf{$outer\_conflict\_flag==1$} \State \textbf{Do} path-planning based collision avoidance \Else \State \textbf{Do} normal trajectory tracking. \EndIf \EndProcedure \State Return to step 7 \end{algorithmic} \end{algorithm} \section{Simulations} Comparative simulation tests for the proposed hierarchical collision avoidance system are carried out in comparison with the DMPC-only collision avoidance approach. The DMPC approach is chosen for comparison because it is a typical algorithm which can deal with various dynamic conflict scenarios in the literature. \subsection{Simulation settings} Simulations are performed on Matlab 2018. Each UAV is functioned as a separate running Matlab and uses the UDP protocol for local communication, which is set to be fully connected. The impact of communication delay and failures are ignored. The UAVs utilize the kinematics in \eqref{eq:kinematics} and are required to follow several pre-planned closed triangle-like curved paths at a constant cruising speed using the pure pursuit with line-of-sight approach (\cite{sujit2014unmanned}). To increase the frequency of conflicts for simulation verification, each reference path is designed to be intersected with the others. Each circle of the paths is about $1500m$. Besides, several environmental obstacles are distributed on or near the reference paths. Then during simulation flights, the UAVs perform the collision avoidance method, e.g., the hierarchical collision avoidance system or the DMPC-only approach, when certain conflict is detected. Main parameter settings are presented in Table \ref{tab:list_of_parameters}. \begin{table}[htbp] \caption{Parameter settings in simulation tests} \begin{center} \renewcommand{\arraystretch}{1.2} \begin{tabular}{p{0.6cm}|p{1.3cm}|p{5.5cm}} \hline \hline ~& \textbf{Value}& \textbf{Meaning} \\ \hline $V$& $19 (m/s)$& The cruising speed \\ \hline $\omega_{max}$& $0.6 (rad/s)$& The maximum heading rate \\ \hline $R_o$& $80 (m)$ & The outer-layer detection region radius \\ \hline $R_m$& $70 (m)$& The middle-layer detection region radius\\ \hline $R_i$ & $55 (m)$& The inner-layer detection region radius\\ \hline $T$& $0.1 (s)$& The control and sampling period \\ \hline $R_s$& $30 (m) $& The restricted safe radius of the UAV \\ \hline \hline \end{tabular} \label{tab:list_of_parameters} \end{center} \end{table} \subsection{Simulations with deterministic sensing} The simulations are firstly carried out for 5 UAVs with deterministic sensing, e.g., the information of obstacles are obtained as far as they enter the perceptible area $\Omega_d$. Then, the UAVs keep doing conflict detection during the flight, and activate the corresponding conflict resolution methods when certain conflicts are detected. In each comparative simulation, the initial positions of the UAVs are the same and randomly chosen from the non-conflict points on the reference paths. The operation time is set to be 5000 control cycles. Thus the flight distance of each UAV in a simulation test is about $9500m$. Once the distance of the UAV from obstacles is less than $R_s$, it is marked as a failure of conflict resolution. Then total number of failures is calculated for comparison. \begin{table}[htb] \caption{Simulations with deterministic sensing}\label{tb:determinisitic_sensing_5_UAVs} \begin{center} \renewcommand{\arraystretch}{1.2} \begin{tabular}{c|c|c|c|c} \hline\hline ~& \multicolumn{2}{c|}{ \textbf{Failure times}} & \multicolumn{2}{c}{ \tabincell{c}{\textbf{Average } \\ \textbf{collision-free } \\ \textbf{distance (m)}}} \\ \cline{2-5} ~& \tabincell{c}{DMPC \\ only} & \tabincell{c}{Hierarchical \\ CAS} & \tabincell{c}{DMPC \\ only} & \tabincell{c}{Hierarchical \\ CAS} \\ \hline Test 1 & 74 & 43 & 128.38 & 220.93 \\ Test 2& 69 & 24 & 137.68 & 395.83 \\ Test 3& 66 & 17 & 143.94 & 558.82 \\ Test 4& 77 & 28 & 123.38 & 339.28 \\ Test 5& 56 & 15 & 169.64 & 633.33 \\ \hline Summation & 342 & 127 & \\\hline Mean & ~ & ~ & 140.60 & 429.64 \\\hline\hline \end{tabular} \begin{tablenotes} \footnotesize \item{*} CAS: the abbreviation of "collision avoidance system" \end{tablenotes} \end{center} \end{table} Table \ref{tb:determinisitic_sensing_5_UAVs} presents the results of 5 comparative simulations. From the content we can see that the total number of conflict resolution failures in flights of about $47500m$ is $127$ using the proposed hierarchical collision avoidance system, which is much less than the result of the DMPC-only method ($342$). Besides, the mean of average collision-free distance using the hierarchical collision avoidance system is $429.64m$, which is much longer than that of the DMPC-only method ($140.60m$). \subsection{Simulations with probabilistic sensing} In the consideration of perception uncertainties in reality, simulations are then performed for 5 UAVs with probabilistic sensing, e.g., obstacles are successfully sensed at a increasing probability as the distance from the UAV decreases. In simulation tests, the probability of successful perception in the outer-layer conflict detection region is $0.70$, the probability of the middle-layer region is $0.85$, and that of the inner-layer region is set to be $1$. Results of 5 comparative simulations are presented in Table \ref{tb:probabilistic_sensing_5_UAVs}. \begin{table}[htb] \caption{Simulations with probabilistic sensing}\label{tb:probabilistic_sensing_5_UAVs} \begin{center} \renewcommand{\arraystretch}{1.2} \begin{tabular}{c|c|c|c|c} \hline\hline ~& \multicolumn{2}{c|}{ \textbf{Failure times}} & \multicolumn{2}{c}{ \tabincell{c}{\textbf{Average } \\ \textbf{collision-free } \\ \textbf{distance (m)}}} \\ \cline{2-5} ~& \tabincell{c}{DMPC \\ only} & \tabincell{c}{Hierarchical \\ CAS} & \tabincell{c}{DMPC \\ only} & \tabincell{c}{Hierarchical \\ CAS} \\ \hline Test 1 & 56 & 31 & 169.64 & 306.45 \\ Test 2& 63 & 10 & 150.79 & 950.00 \\ Test 3& 61 & 17 & 155.74 & 558.82 \\ Test 4& 70 & 18 & 135.71 &527.78\\ Test 5& 63 & 24 & 150.79 & 395.83 \\ \hline Summation & 313 & 100 & \\\hline Mean & ~ & ~ & 152.53 & 547.78 \\\hline\hline \end{tabular} \begin{tablenotes} \footnotesize \item{*} CAS: the abbreviation of "collision avoidance system" \end{tablenotes} \end{center} \end{table} Table \ref{tb:probabilistic_sensing_5_UAVs} shows that, the average collision-free distance using the hierarchical collision avoidance system ($547.78m$) is more than three times that of the DMPC-only scheme ($152.53m$). This indicates that the proposed hierarchical strategy is more capable in the uncertain real world. \section{Conclusion} In conclusion, this paper studied a three-layered collision avoidance architecture for autonomous multiple fixed-wing UAVs. The effectiveness of the hierarchical collision avoidance system is tested via numerical simulations, in which the result verified the advantage of the proposed methodology in comparison with the DMPC-only collision avoidance scheme. This work is the first attempt of combing several different approaches together to handle complex conflict scenarios of multiple UAVs. Future work will continue to study the safety management for multiple fixed-wing UAVs. Firstly, the parameters and algorithms involved in the integrated methodology could to be further optimized to maximize the effect of each layer of the integrated scheme. Secondly, the study on this issue in three-dimensional space is in progress. Besides, physical experiment is also a concern of the authors in future work.
{'timestamp': '2020-06-01T02:08:55', 'yymm': '2005', 'arxiv_id': '2005.14455', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14455'}
arxiv
\section{Introduction} In future motorways, the development of vehicular ad hoc networks (VANETs) which deliver exceptional road safety and driving efficiency has sparked interdisciplinary research in both computer vision and wireless communications. In the near future, vehicles will be equipped with a variety of sensing technologies, including radars, $360^\circ$ cameras, ultrasonic sensors, and lidars. Computer vision algorithms will then fuse this information to classify road users (cars, cyclists, pedestrians, etc.), predict their behaviour, adjust the speed of the car, and improve the response of vehicles to critical events i.e. automatic braking, adjusting road position, etc. Information exchange among vehicles therefore becomes indispensable. Local perception, for example, can be limited under certain conditions. Consider also blind spots appearing in the presence of dense traffic, shadowing due to buildings and vegetation, sensor impairments, weather conditions, and/or the road layout, all limiting the success of the on-board sensors. There are therefore ongoing standardization activities for collective perception (or cooperative sensing) mechanisms, where the vehicles exchange not only their state (position, speed, acceleration)~\cite{ETSIcam}, but also their perception of the environment~\cite{ETSIcpm}. As a result, the requirement for wireless communication technologies to sustain reliable connectivity between the vehicles becomes essential. A key element of the road infrastructure will be the Road Side Unit (RSU) with mounted stationary sensors and wireless connectivity. It is expected that the roadside unit will receive a variety of messages from multiple vehicles not necessarily connected to each other, obtain object information from its own sensors, fuse the combined information and finally broadcast it to the vehicles~\cite[Section 4.1.2]{ETSIcpm}. In this scenario, it is important that the broadcast reaches as many vehicles as possible, especially in case of emergency. A practical solution to achieve this objective is to combine both Vehicle-to-Vehicle (V2V) and Vehicle-to-Infrastructure (V2I) communications, establishing connections between the vehicles and the roadside unit in a multihop fashion, seen ubiquitously in ad hoc networks. Motivated by this emerging scenario, the objective of this article is to develop our understanding of the roadside unit's multi-hop communication range i.e. who is within $k$-hops of the roadside unit, in V2V and V2I communication, as a function of the traffic density $\rho$ cars per unit length of road. In this case, we adopt a \textit{protocol-and-interference-free} approach, where the vehicles are modeled as the vertices of a one-dimensional (1D) soft random geometric graph \cite{penrose2016}. The reason is that we aim to identify the fundamental limits of multi-hop communication in VANETs, in particular, the simplest case, two-hop connectivity, between the vehicles and the roadside unit. Incorporating the impact of interference and multiple access into multihop connectivity will only degrade the performance, and hence, our results can be regarded as an upper performance bound. Multihop connectivity occurs when the network's diameter is bounded \cite{grimmettbook}, i.e the longest shortest path in the network is below a certain threshold. We instead study the number of cars in a random geometric vehicular network built on a quasi-1D line (i.e. a single lane highway) within $k$ hops to a single, fixed roadside unit, for $k=2$, denoted as $N_2$. \noindent The main technical contributions of our work are summarized as follows. \begin{itemize} \item We derive the following infinite series expression for $N_2$ in terms of $\rho$ for $\mathbb{E} [N_2]$, i.e. $$ \mathbb{E} [N_2] = \sqrt{2 \pi}\rho\sum_{k=1}^\infty (-1)^{k-1}\frac{\big(\rho \sqrt{\pi/2} \big)^k}{k!\sqrt{k}}. $$ \item We study the asymptotics of the $\mathbb{E} [N_{2}]$ as the car density approaches infinity and zero. Namely, in Theorem~\ref{t:expectation}, we show that the expected number of cars within two hops to a single, fixed roadside unit asymptotically grows as $$ \mathbb{E} [N_2] \simeq 2 \rho \sqrt{\log \big(\rho \sqrt{\pi/2} \big)} \nonumber $$ as $\rho \to \infty$. \item We compare these analytic predictions to snapshots of real traffic, showing how variation in the underlying stationary Poisson Point Process (PPP) model of the cars does not affect the results, and observe a normal approximation property for $N_2$. \end{itemize} This paper is structured as follows. In Section \ref{sec:review}, we present a literature review of the related works. In Section \ref{sec:model}, we set up and discuss our VANET system model using the random connection model. In Section \ref{sec:analysis}, we state Theorem \ref{t:expectation}, and provide its proof. In Section \ref{sec:traces}, we corroborate our scaling laws with experimental evidence provided from actual traffic data, in relation with normal approximation. Finally, we conclude our work in Section~\ref{sec:conclusion}. \section{Related Work} \label{sec:review} The performance evaluation of VANETs using point processes, line processes and stochastic geometry has gained increasing attention in the literature. These tools offer a framework for studying the impact of various parameters onto the network performance, with relatively low computational complexity. For example, the study in~\cite{Chetlur2018-2} models the locations of vehicles by a Cox point process, and highlights the conflicting impact of the intensities of streets and vehicles on the probability of outage at the typical receiver. In urban settings, the Manhattan Poisson line process has been used to model grid-like road networks~\cite{Baccelli2012, Jeyaraj2017}, while the Poisson line process is pertinent to streets with random orientations~\cite{Chetlur2018-2, Choi2018b}. In most studies, the distribution of vehicles along each street is assumed to follow a 1D PPP (Poisson point process), giving rise to the Cox point process for the distribution of vehicles in the plane~\cite{choi2018,choi2020}. The above studies have highlighted that near road intersections, the receiver performance degrades, because over there, there is dominant interference from multiple streets. The performance evaluation studies of motorway VANETs have utilized much simpler spatial models than the Cox process, mainly due to tractability. Super-imposing straight lines, parallel to each other, is sufficient to model multi-lane motorways with unidirectional traffic flows. This simplification has allowed researchers to incorporate the effect of IEEE 802.11p instead of ALOHA into the performance assessment of VANETs~\cite{Farooq2015, Tong2016}. Furthermore, realistic point processes which introduce correlations in the locations of vehicles along a lane not captured by the PPP, but present in realistic road traffic, have been investigated~\cite{Koufos2018b, Koufos2019, Koufos2020}. The studies in~\cite{Farooq2015, Tong2016} have suggested the use of modified Mat{\'e}rn processes to model the impact of IEEE 802.11p on the locations of concurrent interferers. The study in~\cite{Farooq2015} has also compared a variety of packet forwarding schemes in the performance evaluation of multi-hop VANETs. The study in~\cite{Tong2016} has incorporated queueing theory into the spatial model in an attempt to understand the impact of non-saturated data traffic on the outage probability. Finally, the studies in~\cite{Koufos2018b, Koufos2019, Koufos2020}, have suggested a hardcore distance amendment to the PPP, for the distribution of vehicles along a lane. It is shown, that the hardcore distance can significantly improve the predictions for the distribution of outage probability along the motorway (meta-distribution of the signal-to-interference ratio), and this remark has also been justified using real-world vehicular traces from~\cite{Gramaglia2014,Gramaglia2016}. All the studies discussed above have considered the effect of both interference and fading on the performance assessment. In this paper, we focus on a topic in communication theory known as the \textit{random connection model}. This incorporates any point process, modeling the positions of cars, moving or otherwise, as well as any probabilistic law which governs the connectivity. In spatial networks, there is a current theme of studying the relation between graph distance (hop distance), and Euclidean distance~\cite{diaz2016} i.e. how the geometric embedding of the nodes relates to the hop-statistics between the cars. This is particularly important in the mobile ad hoc network (MANET) and VANET settings. For a comprehensive review of all work in this area, see Mao's recent monograph~\cite{mao2017}, as well as the early work of Chandler et al.~\cite{chandler1989}, and later Ta et al.~\cite{ta2007}, and Mao et al.~\cite{maoanderson2011}. Two recent major works deal with the random connection model in the V2V and V2I setting~\cite{ng2011,zhang2012}. Ng et al. in~\cite{ng2011} present analysis and analytic formulas for the two-hop connectivity probability, which gives the probability that all vehicles in a VANET are within two hops, given vehicles connect pairwise with probability $p$. This is developed to the general case of an arbitrary number of hops of the roadside by Zhang et al.~\cite{zhang2012}. The study in \cite{Mao2010} calculates the probability that a node in a 1D PPP has a two-hop path to the origin. However, the distribution of the number of nodes with a two-hop path is not treated therein, neither asymptotic equivalents for ultra-dense and sparse networks are derived, as we will do in this paper. Finally, in \cite{kartungiles2018b,privault2019} the moments of the number of $k$-hop paths to the origin in a 2D random connection model are computed, which is a different metric as compared to that studied in the present paper, where the moments of the number of nodes in the graph with a $k$-hop path to the origin are calculated. Note that a node may have more than one $k$-hop path, e.g., more than one relay node to the origin in the case of two-hop paths. \begin{figure*}[!th] \centering \centering \includegraphics[width=0.9 \textwidth]{system} \centering \caption{Illustration of the infrastructure-based VANET model with multi-hop connectivity. } \label{fig:system} \end{figure*} \section{System Model} \label{sec:model} In summary, we consider \begin{itemize} \item A connection function $H( x-y) = \mathbb{P} ( x \leftrightarrow y ) \in [0,1]$ which gives the probability that two nodes $x,y\in \mathbb{R}$ at distance $r=|x-y|$ in the graph have a link, resembling the long-term proportion of the time that a Rayleigh fading channel is in coverage~\cite{sklar1997-1}. \item A \textit{random connection model}, which is a random geometric graph $G_H (\mathcal{X})$ built on a stationary, homogeneous PPP $\mathcal{X}$ with flat intensity $\rho>0$ on an interval $V \subset \mathbb{R}$ centered at the origin. The graph $G_H (\mathcal{X})$ is built on long-range links (known in physics as \textit{soft connectivity} \cite{giles2016}) with a ``Rayleigh fading'' connection function $H(r)=\exp(-r^2)$, and contains a point added at the location $u\in \mathbb{R}$, representing the roadside unit. \end{itemize} This resembles 1D \textit{continuum percolation}, or a fluid of particles in the so-called ``Potts fluid''~\cite{drory1997,krioukov2016}, but with soft inter-particle potential, see Fig.~\ref{fig:system}. Let $P$ denote the transmit power level, common for all vehicles. Given a link formed over a distance $r$ and letting $h$ denote the amplitude of the Rayleigh fading channel, $g\!\left(r\right)$ the distance-based path loss, $\Upsilon$ the threshold information-theoretic decoding rate at the receiver, and $N_0$ the noise power level, the connection probability $P_c$ of the link can be expressed as the following probability \begin{equation} \label{e:coverage} P_c = \mathbb{P} \left[\log_{2}\left(1+\frac{P\, g\left(r\right)}{N_{0}}\hspace{0.5mm}|h|^2\right) > \Upsilon\right]. \end{equation} The distance-based path-loss function $g\left(r\right) = C r^{-\eta}$ depends on some positive path loss attenuation constant $C\!<\!1$ and the path loss exponent $\eta\!>\! 0$. Rearranging Eq.~\eqref{e:coverage}, we have, with the following constant $\beta := N_{0} \left(2^{\Upsilon}-1\right)/\left(P\, C\right) $, a function of the rate $\Upsilon$ which when increased will decrease the typical length of links, that $\mathbb{P} ( |h|^2 > \beta r^\eta ) $, and since $|h|^2$ is exponentially distributed with a unit mean, we have \begin{equation} \nonumber P_c=\exp(-\beta r^\eta ). \end{equation} Therefore, the success probability of any V2V or V2I communication link can be modelled by a stretched exponential function of the link distance $r$, \begin{align} \nonumber H(r) = \exp(-\beta r^\eta ) \end{align} for some $\beta\!>\!0$. In the next section, we take $\beta = 1$ and focus on the case with $\eta\!=\!2$ which captures free space path loss \cite{giles2016,cef2012,sklar1997-1}. Additionally, the main notations used in the paper are listed in Table~\ref{Tab:Notations}. \begin{table}[H] \centering \caption{ Table of Notations} \label{Tab:Notations} \begin{tabular}{l||p{8cm}} \hline Notations & Definition \\ \hline \hline $\simeq$ & Asymptotically equivalent to, i.e. $f(\rho)/g(\rho) \to 1$ as $\rho \to \infty$. \\ \hline $\sim$ & Distributed as \\ \hline $\to$ & Limit \\ \hline $\twoheadleftrightarrow$ & Has a two-hop path to\\ \hline $\leftrightarrow $ & Connects to \\ \hline $N_1(x,u)$ & Count of two-hop paths between nodes at $x$ and $u$ \\ \hline $\mathbb{E} [\cdot]$ & Expectation under a Poisson point process with density $\rho>0$ \\ \hline $\mathbb{P} (\cdot )$ & Probability that an event occurs \\ \hline $\mathbf{1}(\cdot)$ & Indicator function \\ \hline $|\cdot|$ & Absolute value \\ \hline $e$ & Euler's number \\ \hline $N_{2}$ & The number of vehicles within two hops of the roadside unit \\ \hline $P$ & Transmit power of the vehicles \\ \hline $\Upsilon$ & Communication rate threshold \\ \hline $\eta$ & Path-loss exponent \\ \hline $\rho$ & Density of vehicles \\ \hline $V$ & Interval of $\mathbb{R}$ containing the vehicles \\ \hline $\mathcal{X}$ & A PPP representing the distribution of the vehicles on $V$ \\ \hline \end{tabular} \end{table} Finally, it is noted that to have a two-hop path, the signal-to-noise ratio (SNR) for both hops must be higher than or equal to the threshold $\Upsilon$. From this perspective, a {\it{decode-and-forward}} relay is essentially assumed here. \subsubsection*{Slivnyak-Mecke formula} We close this section with the statement of the Slivnyak-Mecke formula, which will be used throughout the paper. It is an extension of Campbell's formula to sum over tuples of a point process. Often, and throughout this paper, we sum indicator functions over tuples of nodes of a point process, and evaluate the typical value of the sum over all graphs. We might, for example, sum an indicator function over singletons (i.e. $1$-tuples of nodes) of the point process, which gives isolation. Then, this sum would give the number of isolated nodes, and the expected value of the sum the expected number of isolated nodes. We refer the reader to e.g. \cite[Lemma 2.3]{penrose2016} for the following lemma. \begin{lemma}[Slivnyak-Mecke Formula]\label{l:mecke} Let $n\geq 1$. For any measurable real-valued function $g$ defined on the product of $V^n \times \mathcal{G}$, where $\mathcal{G}$ is the space of all graphs in $V$, the following relation holds: \begin{multline}\label{e:meckeformula} \mathbb{E} \! \left[ \sum_{X_1 ,\dots,X_n \in \mathcal{X}}^{\neq} g(X_1 ,\ldots,X_n , G_H (\mathcal{X}\setminus \{X_1,\ldots,X_n\})) \right] \\ = \rho^n \mathbb{E} \! \left[ \int_{V} \cdots\int_{V} g\left(x_1,\dots,x_n , G_H (\mathcal{X} ) \right) \mathrm{d}x_1 \cdots \mathrm{d}x_n \right]\!, \end{multline} where $\mathcal{X}$ is a Poisson point process with intensity $\rho>0$ on $V$, and $\sum^{\not=}$ means the sum over all \textit{ordered} $t$-tuples of distinct points in $\mathcal{X}$. \end{lemma} \section{Results} \label{sec:analysis} This section presents the main technical results of our work. We start by introducing the preliminaries and then address the problem of determining the statistics of the number of vehicles on the road within two-hop range of a roadside unit in the system described in Section~\ref{sec:model}. \subsection{Two-hop connectivity} In the sequel, we let \begin{equation} \nonumber N_1(x,u) : = \sum_{z \in \mathcal{X}}\mathbf{1}\left(x \leftrightarrow z \leftrightarrow u\right) \end{equation} denote the number of distinct two-hop paths between vertices at $x$ and $u$ in $V$. The following lemma will be used throughout the remainder of the article. \begin{lemma} \label{l1} The number $N_1(x,u)$ of two hop paths between two given vertices $x, u \in V$ has a Poisson distribution. \end{lemma} \begin{proof} A proof of this result can be found in \cite[Section 2]{privault2019} by computing the moments of $N_1(x,u)$ using the Slivnyak-Mecke formula and non-flat partitions. Other proofs can be provided, e.g. by constructing $G_H (\mathcal{X} )$ as another Poisson point process obtained by thinning $\mathcal{X}$ with probability $H(x,y)H(y,u)$ at every vertex $y\in V$. Here, we will use a combinatorial argument to better understand why the moments of $N_1(x,u)$ match those of a Poisson distribution. Consider for instance the second moment. \begin{align} \mathbb{E}_\rho \left[ ( N_1(x,u) )^2\right] &= \mathbb{E}_\rho \left[\left(\sum_{z \in \mathcal{X}}\mathbf{1}\left(x \leftrightarrow z \leftrightarrow u\right) \right)^2 \right] \\ &= \mathbb{E}_\rho \left[\sum_{z_1,z_2 \in \mathcal{X}}\mathbf{1}\left(x \leftrightarrow z_1 \leftrightarrow u\right)\mathbf{1}\left(x \leftrightarrow z_2 \leftrightarrow u\right)\right]. \end{align} The pairs of paths in the above sum are either two different paths, or a path paired with itself. The pair which is of different paths, via a graph union of those paths, forms a diamond topology, i.e. a pair of two-hop paths united at their extremes, and they can be averaged by the Slivnyak-Mecke formula Eq.~\eqref{e:meckeformula} as \begin{multline}\label{e:m1} \mathbb{E} \left[\sum_{z_1,z_2 \in \mathcal{X} \atop z_1\not= z_2}\mathbf{1}\left(x \leftrightarrow z_1 \leftrightarrow u\right)\mathbf{1}\left(x \leftrightarrow z_2 \leftrightarrow u\right)\right] \\ = \vspace{5px} \rho^2\!\! \int_{V^2} \!\! \mathbb{E} \left[\mathbf{1}\left(x \leftrightarrow z_1 \leftrightarrow u\right)\mathbf{1}\left(x \leftrightarrow z_2 \leftrightarrow u\right)\right] \mathrm{d}z_1 \mathrm{d}z_2. \end{multline} Adding the self-pairs yields the second moment \begin{multline}\label{e:m2} \mathbb{E} \big[N_1(x,u)^2\big] \\ =\underbrace{\rho^2\int_{V^2}\mathbb{E} \left[\mathbf{1}\left(x \leftrightarrow z_1 \leftrightarrow u\right)\mathbf{1}\left(x \leftrightarrow z_2 \leftrightarrow u\right)\right] \mathrm{d}z_1 \mathrm{d}z_2}_{\text{Two-hop paths which do not intersect}} + \underbrace{\rho\int_{V}\mathbb{E} \left[\mathbf{1}\left(x \leftrightarrow z \leftrightarrow u\right)\right] \mathrm{d}z}_{\text{Self-pairs}} \\ = \big( \mathbb{E} [ N_1(x,u) ] \big)^2 + \mathbb{E} [ N_1(x,u) ]. \end{multline} and, similarly, the third moment \begin{multline}\label{e:m3} \mathbb{E} \big[\big( N_1(x,u)\big)^3\big] = \underbrace{\rho^3\int_{V^{3}}\mathbb{E} \left[\mathbf{1}\left(x \leftrightarrow z_1 \leftrightarrow u\right)\mathbf{1}\left(x \leftrightarrow z_2 \leftrightarrow u\right) \mathbf{1}\left(x \leftrightarrow z_3 \leftrightarrow u\right)\right] \mathrm{d}z_1 \mathrm{d}z_2\mathrm{d}z_3}_{\text{Triples of two-hop paths which do not intersect}} \\ + 3\underbrace{\rho^2\int_{V^2}\mathbb{E} \left[\mathbf{1}\left(x \leftrightarrow z_1 \leftrightarrow u\right)\mathbf{1}\left(x \leftrightarrow z_2 \leftrightarrow u\right) \right] \mathrm{d}z_1 \mathrm{d}z_2}_{\text{Triples of two-hop paths of which a pair intersect}} + \underbrace{\rho\int_{V}\mathbb{E} \left[\mathbf{1}\left(x \leftrightarrow z \leftrightarrow u\right)\right] \mathrm{d}z}_{\text{Self-triples}} \\= \big(\mathbb{E} [ N_1(x,u) ]\big)^3 + 3 \big( \mathbb{E} [ N_1(x,u) ]\big)^2 +\mathbb{E} [ N_1(x,u) ]. \end{multline} In other words, the expected number of ordered $k$-tuples of two-hop paths is given by the mean number of two-hop paths to the $k^{\text{th}}$ power, which corresponds to a Poisson factorial moment. The reason is that the every integral of order $k$ has an integrand which can be factorized, resulting into a product of integrals, each of which is the mean, as one can see in Eqs.~\eqref{e:m1}, \eqref{e:m2} and \eqref{e:m3} above. More generally, the moments of $N_1(x,u)$ are given by \begin{equation} \nonumber \mathbb{E} \big[ \big( N_1(x,u) \big)^n \big] = \sum_{k=1}^n S(n,k) \big( \mathbb{E} [ N_1(x,u) ] \big)^k , \qquad n \geq 1, \end{equation} where $S(n,k)$ is the Stirling number of the second kind, i.e. the number of ways to partition a set of $n$ objects into $k$ non-empty and disjoint subsets, see \cite[Section 4]{privault2019}. As such, the moments of the two-hop path count $N_1(x,u)$ are those of the Poisson distribution with mean $\mathbb{E} [ N_1(x,u) ]$ \end{proof} Next, we compute the mean number of two hop paths which join two vertices of the graph, starting with the case of a finite interval of width $|V|<\infty$, which will later become the real line $\mathbb{R}$. \begin{proposition} \label{p1} [Two-hop connectivity in finite length]. When $|V|<\infty$, the probability of existence of at least one two-hop path between $x,u \in V$ is given by \begin{equation} \label{e:ccl} \mathbb{P} ( x \twoheadleftrightarrow u ) = 1 -\exp\left(- \frac{\rho}{2} \sqrt{\frac{\pi}{2}} e^{-(x-u)^2/2} \left(\mathrm{erf}\left( \frac{|V|-(x-u)}{\sqrt{2}}\right) + \mathrm{erf}\left( \frac{|V|+x-u}{\sqrt{2}}\right)\right) \right) \end{equation} where ${\mathrm{erf}}\left(x\right)\!=\! ( 2 /\sqrt{\pi} ) \int_0^x e^{-t^2}{\rm d}t$ is the error function. \end{proposition} \begin{proof} The mean of $N_1(x,u)$ is given by by Campbell's theorem for point processes as \begin{align} \nonumber \mathbb{E} [ N_1(x,u) ] &= \rho\int_{V} \mathbb{E} \left[\mathbf{1}\left(x \leftrightarrow z \leftrightarrow u\right) \right]\mathrm{d}z \\ \nonumber &= \rho\int_{V} H(x,z)H(z,u)\mathrm{d}z \\ \nonumber &= \rho\int_{-|V|/2}^{|V|/2} e^{- \left(x-z\right)^2 -(z-u)^2 }\mathrm{d}z \\ \nonumber &= \frac{\rho }{2} \sqrt{\frac{\pi}{2}} e^{-(x-u)^2/2} \left(\mathrm{erf}\left( \frac{|V|-(x-u)}{\sqrt{2}}\right) + \mathrm{erf}\left( \frac{|V|+x-u}{\sqrt{2}}\right)\right). \end{align} We conclude from Lemma~\ref{l1}, by noting that the probability that at least one two-hop path exists between $x$ and $u$ in $V$ is given by the complement of the void probability of a Poisson variate, as \begin{equation}\label{e:indicator2} \mathbb{P} ( x \twoheadleftrightarrow u ) = 1- \mathbb{P} ( N_1(x,u) = 0 ) = 1-\exp\left(- \mathbb{E} [ N_1(x,u) ]\right). \end{equation} \end{proof} Corollary~\ref{c1} below, which treats the infinite length case $V = \mathbb{R}$, can be obtained from Proposition~\ref{p1} by letting $|V|$ tend to infinity in \eqref{e:ccl}, or from Lemma~\ref{l1}. \begin{corollary} \label{c1} [Two-hop connectivity in infinite length]. When $V=\mathbb{R}$, the probability of existence of at least one two-hop path between $x$ and $u$ in $\mathbb{R}$ is given by $$ \mathbb{P} ( x \twoheadleftrightarrow u ) = 1-\exp\left(-\rho \sqrt{\frac{\pi}{2}}e^{-(x-u)^2/2 }\right). $$ \end{corollary} \begin{proof} Here, we have \begin{align} \nonumber \mathbb{E} [ N_1(x,u) ] &= \rho\int_{-\infty}^\infty \mathbb{E} \left[\mathbf{1}\left(x \leftrightarrow z \leftrightarrow u\right) \right]\mathrm{d}z \\ \nonumber &= \rho\int_{-\infty}^\infty H(x,z)H(z,u)\mathrm{d}z \\ \nonumber &= \rho\int_{-\infty}^\infty e^{- \left(x-z\right)^2 -(z-u)^2 }\mathrm{d}z \\ \nonumber &= \rho\sqrt{\frac{\pi}{2}} e^{-(x-u)^2/2}, \end{align} and we can conclude by \eqref{e:indicator2} and Lemma~\ref{l1} as in the proof of Proposition~\ref{p1}. \end{proof} \subsection{Main result} In this section, we apply Corollary~\ref{c1} to analyze the mean number of vertices with two-hop connectivity to the roadside unit. \begin{theorem} \label{t:expectation} [Mean number of vehicles with two-hop connectivity to the roadside unit under Rayleigh fading]. Let $N_2$ be the number of vertices with two-hop connectivity to the roadside unit in a specific realisation of $G_H (\mathcal{X})$, defined in Section \ref{sec:model}. \begin{enumerate}[i)] \item The mean number $\mathbb{E} [N_2]$ of $N_2$ of vertices with at least one two-hop path to the roadside unit is given by \begin{align}\label{e:a0} \mathbb{E} [N_2 ] &= \rho \int_{-\infty}^\infty \big( 1-\exp\big(-\rho \sqrt{\pi / 2}e^{-(x-u)^2/2 }\big)\big) \mathrm{d}x \nonumber \\ &= \rho\sqrt{2\pi}\sum_{k=1}^{\infty}(-1)^{k-1}\frac{\big(\rho \sqrt{\pi/2} \big)^k}{k!\sqrt{k}}. \end{align} \item In addition, we have the exact equivalents \begin{equation}\label{e:a1} \mathbb{E} [N_2 ] \simeq 2 \rho \sqrt{ 2\ln\rho + 2\ln\sqrt{\pi/ 2} }, \qquad [\rho \to \infty], \end{equation} as $\rho$ tends to infinity, and \begin{equation}\label{e:a2} \mathbb{E} [N_2 ] \simeq \pi \rho^2, \qquad [\rho \to 0], \end{equation} as $\rho$ tends to zero. \end{enumerate} \end{theorem} \begin{proof} \noindent $(i)$ We represent the number $N_2$ of vertices in $G_H (\mathcal{X})$ which have graph distance to the point at $u \in \mathbb{R}$ of two hops or less as the sum $$ N_2= \sum_{x \in \mathcal{X}}\mathbf{1}\left(x \twoheadleftrightarrow u\right). $$ With an expected density of $\rho$ points per unit of length we find, via the Slivnyak-Mecke formula of Lemma~\ref{l:mecke} and Corollary~\ref{c1}, that the expected value of this number is given by \begin{eqnarray} \nonumber \mathbb{E} [N_2] & = & \mathbb{E} \left[\sum_{x \in \mathcal{X}}\mathbf{1}\left(x \twoheadleftrightarrow u\right)\right] \\ \nonumber & = & \rho\int_{-\infty}^\infty \mathbb{E} \left[\mathbf{1}\left(x \twoheadleftrightarrow u\right)\right] \mathrm{d}x \\ \nonumber & = & \rho\int_{-\infty}^\infty \mathbb{P} ( x \twoheadleftrightarrow u ) \mathrm{d}x \\ \nonumber & = & \rho \int_{-\infty}^\infty \big( 1-\exp\big(-\rho \sqrt{\pi / 2}e^{-x^2/2 }\big)\big) \mathrm{d}x \\ \nonumber & = & \rho f ( \rho \sqrt{\pi / 2} ), \end{eqnarray} where $$ f (\alpha ) := \int_{-\infty}^\infty \big( 1 - \exp \big( - \alpha e^{-x^2/2} \big) \big)\mathrm{d}x, \qquad \alpha >0. $$ The above integral can be expanded in a Taylor series about $\rho=0$ and integrated term by term to obtain the infinite oscillating sum $$ f(\alpha ) = - \int_{-\infty}^\infty \sum_{k=1}^{\infty}\frac{(-\alpha )^k}{k!} e^{-kx^2 /2}\mathrm{d}x = - \sqrt{2\pi}\sum_{k=1}^{\infty} \frac{(-\alpha )^k}{k!\sqrt{k}}, $$ which proves Eq.~\eqref{e:a0}. \noindent $(ii)$ Next, we derive the asymptotics \eqref{e:a1} as $\rho \to \infty$. By change of variable, we have \begin{align} \nonumber f\left(\alpha\right) & = 2 \sqrt{2 \log \alpha }\int_0^\infty \big( 1 - \exp\big({-\alpha^{1-x^2}} \big)\big) \mathrm{d}x \\ & = 2 \sqrt{2 \log \alpha }\int_0^1 \big( 1 - \exp\big({-\alpha^{1-x^2}} \big)\big) \mathrm{d}x \, + \nonumber \\ & \, 2 \sqrt{2 \log \alpha }\int_1^\infty \big(1 - \exp\big({-\alpha^{1-x^2}} \big)\big) \mathrm{d}x, \, \alpha \geq 1. \label{e:f(a)0} \end{align} Using the bound $0 \leq 1- e^{-\alpha^{1-x^2}} \leq e \alpha^{1-x^2}$, which is valid as $0 \leq \alpha^{1-x^2} \leq 1$ when $x \geq 1$ and $\alpha \geq 1$, we have \[ \begin{array}{ccl} 0 \!\!\!&\leq&\!\!\! \displaystyle \int_1^\infty \big( 1 - e^{-\alpha^{1-x^2}} \big) \mathrm{d}x \leq \alpha e \int_1^\infty \alpha^{-x^2} \mathrm{d}x \nonumber \\ \!\!\!&\leq &\!\!\! \displaystyle \alpha e \int_1^\infty x e^{-x^2 \log \alpha } \mathrm{d}x \nonumber = \frac{e}{2 \log \alpha }, \quad \alpha \geq 1. \end{array} \] Furthermore, by the limit $\lim_{\alpha \to \infty} \alpha^{1-x^2}= +\infty$, $x\in [0,1)$, and dominated convergence, the first integral in Eq.~\eqref{e:f(a)0} satisfies \[ \lim_{\alpha \to \infty} \int_0^1 \big(1 - e^{-\alpha^{1-x^2}} \big) \mathrm{d}x = 1. \] From the inequalities \[ \begin{array}{ccl} \displaystyle \int_0^1 \!\!\! \big(1 - \exp\big({-\alpha^{1-x^2}} \big)\big) \mathrm{d}x \!\!\!&\leq&\!\!\! \displaystyle \int_0^\infty \!\!\! \big(1 - \exp\big({-\alpha^{1-x^2}} \big)\big) \mathrm{d}x \\ \!\!\!&\leq&\!\!\! \displaystyle \int_0^1 \!\!\! \big(1 - \exp\big({-\alpha^{1-x^2}} \big)\big) \mathrm{d}x \, + \\ & & \displaystyle \frac{e}{2 \log \alpha}, \end{array} \] we conclude to \[ f(\alpha ) \simeq 2 \sqrt{2\log \alpha }, \qquad [\alpha \to \infty]. \] The equivalent \eqref{e:a2} as $\alpha$ tends to zero follows by truncation of Eq.~\eqref{e:a0}. \end{proof} Theorem 1 is validated against simulations in Fig.~\ref{fig:realization2} with $10\,000$ independent graph realizations of the 1D random connection model, where the mean degree $\mu_d$ of $G_H (\mathcal{X})$, given by \begin{equation} \label{e:p0} \begin{array}{ccl} \mu_d &=& \displaystyle \rho\int_{-\infty}^\infty \mathbb{P} ( x \leftrightarrow 0 ) \mathrm{d}x \\ &=& \displaystyle \rho\int_{-\infty}^\infty H(r){\rm d}r \\ &=& \displaystyle \rho\int_{-\infty}^\infty e^{- r^2}{\rm d}r \\ &=& \displaystyle \rho \sqrt{\pi}, \end{array} \end{equation} goes to infinity as $\rho \to \infty$. \begin{figure}[!t] \centering \includegraphics[width=3.5in]{MeanMonteCarlo.png} \caption{The mean number of vehicles with a two-hop path to the origin, Eq.~\eqref{e:a0}, compared against Monte Carlo. $20\,000$ simulation runs. We simulate over a line segment $\mathcal{X} \subset [-L,L]$, where $L\!=\!\sqrt{2\log\! (- \rho \sqrt{\pi/2} / \log\! (1-\epsilon ) )}$, and the constant $\epsilon\!\ll\! 1$ is positive, $\epsilon\!=\! 10^{-8}$ in our simulations. Note that the vehicles at distances larger than $L$ from the origin have a two-hop connection with probability less than $\epsilon$, see Eq.~\eqref{e:indicator2}, and thus they do not contribute essentially to the value of $N_2$. For large values of $\rho$ many terms in Eq.~\eqref{e:a0} contribute to the sum, and the oscillating series may start to diverge due to precision errors. For $\rho\!>\!20$ we have truncated the series in Eq.~\eqref{e:a0} at the $250$-th term, and we have used high precision arithmetics in Mathematica at the $50$-th digit. The asymptotic approximation for $\rho\rightarrow\infty$ in Eq.~\eqref{e:a1} behaves well over the full range of intensities, while the approximation for $\rho\rightarrow 0$ is accurate only for very sparse networks. The simulated variance of the number of two-hop paths is depicted too.} \label{fig:realization2} \end{figure} In addition, we see in Fig.~\ref{fig:realization2} that the asymptotic expression in Eq.~\eqref{e:a1} remains very accurate also for realistic values of $\rho$. \begin{figure}[!t] \centering \includegraphics[scale=0.4]{o2} \includegraphics[scale=0.4]{o1} \caption{The existence of a path to the RSU: 1-hop i.e. a direct link with probability $H\!\left(r\right)\!=\! e^{-r^2}$ (left panel) in terms of the path loss exponent $\eta$, and 2-hop (right subfigure), as a function of the distance between the node and the RSU, taking $\eta=2$, see Eq.~\eqref{e:indicator2}.} \label{fig:realization} \end{figure} In Fig.~\ref{fig:realization} (right subfigure), we illustrate that the probability of a two-hop path, see Eq.~\eqref{e:indicator2}, for $\rho\to\infty$ will remain close to unity for small distances $x$ from the roadside unit, and it will sharply jump from unity to zero. In Fig.~\ref{fig:grid0} we observe that as the expected vertex degree $\mu_d$ in Eq.~\eqref{e:p0} tends to infinity, the Cumulative Distribution Function (CDF) of $N_2$ converges to that of the normal distribution, after rescaling, i.e. \begin{equation}\label{e:p} \mathbb{P} \left(\frac{N_2 - \mathbb{E} [N_2]}{\sqrt{\mathrm{Var}[N_2]}} \leq x \right) \simeq \Phi(x), \qquad x\in \mathbb{R}, \end{equation} as $\rho$ tends to infinity, with $\Phi$ the CDF of the standard normal distribution. Observing normal approximation is common in the case of independent trials. Here, the events ``a node $v$ has a two-hop path to the roadside unit'', for each $v \in \mathcal{X}$, are dependent, nevertheless, the dependency is sufficiently short range to lead to a Gaussian distribution in the dense limit of Eq.~\eqref{e:p0}. \begin{figure}[!t] \centering \centering \includegraphics[width=0.45 \textwidth]{r1001} \caption{\small{Counts of nodes with two-hop connectivity to the point at $0$, for various PPP densities $\rho$ cars per typical connection range. Even for relatively low densities, a Gaussian distribution is present. We take $\mathcal{X} \subset [-10,10]$, using $\rho$ points per unit length, and the connection function $H(r)=\exp(-r^2)$. The mean node degree is $\rho\sqrt{\pi}$.}} \label{fig:grid0} \end{figure} \section{Validation with synthetic traces}\label{sec:traces} Next, we assess the validity of the Poissonian assumption for the distribution of vehicles along a motorway. Using synthetic traces generated based on traffic data collected on the motorway M40 outside Madrid, Spain~\cite{Gramaglia2014,Gramaglia2016}, we simulate the distribution, $f_{\hat{N_2}}$, of the number of vehicles with at least one two-hop link to the origin, and compare this distribution (also referred to as the empirical distribution) to a Gaussian with mean equal to the parameter calculated in Eq.~\eqref{e:a0}. Overall, the spatial distribution of vehicles, at a snapshot of time, along a motorway, is not exactly Poisson. Therefore we quantify the sensitivity of the mean $\mathbb{E} [N_2]$, in Eq.~\eqref{e:a0}, to small perturbations to the deployment model. According to~\cite{Gramaglia2014,Gramaglia2016}, magnetic induction loops under the concrete layer of the motorway are used to measure the average intensity and speed of vehicles separately, for each of the three lanes (uni-directional traffic flow). The measurements took place on different days and times in May 2010, covering heterogeneous traffic conditions during weekdays, weekends, the busy hour, and off-peak. The collected parameters are used to calibrate a micro-mobility simulator, whose output is $1800$ consecutive snapshots of a $10$-km segment on a three-lane motorway. Thanks to~\cite{Gramaglia2014,Gramaglia2016}, these snapshots are publicly available. The associated data files contain the horizontal location and occupied lane for all the vehicles over the $1800$ snapshots. The time granularity is set to one second, so the total simulation time was half an hour, i.e., 8:30 a.m. - 9:00 a.m. for the busy hour, see~\cite[Section III-A]{Gramaglia2014}. We first generate the empirical distribution, $f_{\hat{N_2}}$, for a snapshot of vehicles taken during the busy hour. Firstly, we project all vehicles in the snapshot onto a single line. It is noted that this, apparently, does not introduce any error, perhaps because the communication range is expected to be much larger than the inter-lane distance separation, which has been taken as equal to $3$m in~\cite{Gramaglia2014,Gramaglia2016}. We then construct the empirical CDF of headway distances using linear interpolation between the points of the CDF. In each simulation run, we generate uniform random numbers in the interval $\left[0,1\right]$, and we map them to the numerically inverted CDF. This is known as inversion sampling. We do so until we cover a line segment of $10$ km with vehicles. The set of vehicles is denoted by $\mathcal{X}$, and the origin is located in the middle of the segment at $5$ km. Next, for each vehicle $x\!\in\!\mathcal{X}$, we generate a random number uniformly in $\left[0,1\right]$. After comparing it with the value of the connection function $e^{-\beta r^2}$, where $r$ is the distance between the vehicle and the origin, we can identify the set of vehicles $\mathcal{X}_1$, which have a single-hop link to the origin. Then, we search over the vehicles $x\!\in\!\mathcal{X}\backslash \mathcal{X}_1$ and separate those with a single-hop link to, at least, one of the vehicles in $\mathcal{X}_1$. They become the elements of the set $\mathcal{X}_2$, which consists of the vehicles with a two-hop path to the origin. To complete the set $\mathcal{X}_2$ we need to add to it the elements of the set $\mathcal{X}_1$ which also have a two-hop connection to the roadside unit. Finally, the cardinality of the set $\mathcal{X}_2$ is computed and stored for each simulation run. The simulated probability mass function (PMF), $f_{\hat{N_2}}$, along with the Gaussian approximation are depicted in Fig.~\ref{fig:N2Busy}. Although the empirical CDF of inter-vehicle distances is not exactly exponential, see the inset in Fig.~\ref{fig:N2Busy}, Eq.~\eqref{e:a0} can approximate very well the mean number of vehicles with a two-hop link to the origin. In addition, the Gaussian approximation appears to fit very well the PMFs, validating Eq.~\eqref{e:p}. \begin{figure}[!t] \centering \includegraphics[width=3.5in]{N2Busy.png} \caption{The empirical PMF, $f_{\hat{N_2}}$, (blue bars), of the number of vehicles with a two-hop connection to the origin for the $1000-$th snapshot of the vehicles during the busy-hour. $20\,000$ simulation runs per PMF. The two PMFs correspond to mean degrees, $\hat{\rho}\sqrt{\pi / \beta}$, equal to $10$ and $25$. The intensity, $\hat{\rho}\!\approx\!0.0604 {\text{m}}^{-1}$, has been estimated as being equal to the inverse of the mean headway distance calculated from the snapshot, which is also the maximum likelihood estimate for the intensity of a PPP. Note that given the snapshot, the mean degree can be varied by changing the parameter $\beta$ of the connection function $e^{-\beta r^2}$ yielding $\beta\!\approx\!1.146\times 10^{-4}$ and $\beta\!\approx\!1.834\times 10^{-5}$ for mean degrees $10$ and $25$ respectively. The simulated mean values of the number of two-hop paths, $\mathbb{E} [\hat{N}_2]$, are $24.82$ vehicles for mean degree equal to $10$ and $73.63$ vehicles for mean degree equal to $25$. Eq.~\eqref{e:a0} yields $24.60$ and $72.90$ for the expected number of vehicles $\mathbb{E} [N_2]$ respectively. The Gaussian approximation with mean equal to $\mathbb{E} [N_2]$ and variance obtained by the simulations is depicted in the red dashed lines. In the inset, we illustrate the empirical CDF of headway distances (black solid line) along with its exponential approximation (red dashed line).} \label{fig:N2Busy} \end{figure} Thus far, we have utilized just a single snapshot of vehicles in simulating the statistics of the number of two-hop paths to the origin. This may not be representative of the traffic conditions during the busy hour. Therefore, we also simulate the distribution $f_{\hat{N}_2}$ over multiple snapshots. During network planning, it is expected that we monitor the motorway traffic for some time while estimating the average intensity of vehicles, and we finally apply Eq.~\eqref{e:a0} to predict the mean number of vehicles with a two-hop connection to the roadside unit. In our simulations, we will actually use the last $1200$ out of the total $1800$ snapshots, in order to allow the first vehicles entering the roadway to reach the exit. This is to ensure that for all considered snapshots there are enough vehicles along the highway, hence, we can accurately simulate the statistics of connectivity. Since the considered snapshots cover a time interval of $20$ mins, there are slight variations in the intensity of vehicles during this time, see the solid line in the inset of Fig.~\ref{fig:N2BusyAllsnap}. On the other hand, the model in Eq.~\eqref{e:a0} requires a single value for the intensity $\rho$. We will utilize the average estimated intensity over all considered snapshots, see the dashed line in the inset. The results are depicted in Fig.~\ref{fig:N2BusyAllsnap}. Eq.~\eqref{e:a0} is still a very good estimate of the simulated mean number of vehicles with a two-hop path to the origin. Also, the quality of the Gaussian fit remains good, even though the actual deployment of vehicles does not follow a PPP, and in addition to that, the intensity of vehicles varies with respect to time. In Fig.~\ref{fig:N2OffpeakAllsnap}, the same study is repeated during off-peak, i.e., 11:40 a.m. - 12:00 p.m., see~\cite[Section III-A]{Gramaglia2014}. The average intensity of vehicles becomes lower than that during the busy hour, but the approximation accuracy of our model is still very satisfactory. \begin{figure}[!t] \centering \includegraphics[width=3.5in]{N2BusyAllsnap.png} \caption{The empirical PMF, $f_{\hat{N_2}}$, (blue bars), of the number of vehicles with a two-hop connection to the origin averaged over $1200$ snapshots during the busy hour. For each snapshot we have generated $100$ independent spatial configurations of vehicles by sampling its empirical CDF of inter-vehicle distances. Two values for the parameter $\beta$ are considered: $\beta\!=\! 5\times 10^{-5}$ and $\beta\!=\! 10^{-5}$. The simulated mean values for the number of vehicles with a two-hop path to the RSU is $39.51$ and $100.60$ respectively. The estimated intensity $\hat{\rho}$ for each snapshot is depicted in the inset. In Eq.~\eqref{e:a0}, we have used the mean intensity averaged over all the considered snapshots yielding $\hat{\rho}\!=\!0.0585\, {\text{m}}^{-1}$, see the dashed line in the inset. After substituting $\hat{\rho}$ into Eq.~\eqref{e:a0}, we obtain $39.12$ and $99.60$ for the expected number of vehicles $\mathbb{E} [N_2]$ respectively with a two-hop connection to the RSU. The red dashed line corresponds to the Gaussian approximation for the distribution of $N_2$ using mean equal to $\mathbb{E} [N_2]$ and variance obtained by the simulations.} \label{fig:N2BusyAllsnap} \end{figure} \begin{figure}[!t] \centering \includegraphics[width=3.5in]{N2OffpeakAllsnap.png} \caption{The empirical PMF, $f_{\hat{N_2}}$, (blue bars), and the Gaussian approximation (red dashed lines) for the distribution of the number of vehicles with a two-hop connection to the origin averaged over $1200$ snapshots during off-peak. See also the caption of Fig.~\ref{fig:N2BusyAllsnap} for the related explanation.} \label{fig:N2OffpeakAllsnap} \end{figure} \section{Conclusion} \label{sec:conclusion} Motivated by V2I communications in a VANET topology, we investigate the notion of $k$-hop connectivity to a fixed roadside unit, specifically, in the random connection model on a 1D PPP with connection function $H(r) = \exp(-r^2)$, and with $k=2$. We know the paths are Poisson in number between a car and the roadside, so using the void probability, calculate the existence probability, which is integrated over the road domain to give the typical number of cars $N_2$ with at least one two-hop path to the origin. This is then expanded in a power series to provide an infinite oscillating series expression for $N_2$, which, truncated to the first term, shows that the two hop connectivity grows quadratically with traffic density, when the traffic is low. We then perform integral asymptotics to derive that $N_2$ is asymptotically equivalent to \begin{equation} N_2 \simeq \sqrt{2}\rho \sqrt{ \ln\rho + \ln\sqrt{\pi / 2} }. \end{equation} Finally, we present comparison with both Monte Carlo simulations, corroborating these formulas, and with a random model based on traffic data in Madrid. The Madrid data confirms that the typical number of vehicles in two-hop range of a roadside unit is an accurate representation of an interference-free network of moving cars, at a random instance of time, and further, that a Gaussian central limit theorem is also present. \section{Acknowledgements} This research is supported by the Ministry of Education, Singapore, under its AcRF Tier 1 grant MOE2018-T1-001-201 RG25/18. \footnotesize \def$'${$'$} \def\polhk#1{\setbox0=\hbox{#1}{\ooalign{\hidewidth \lower1.5ex\hbox{`}\hidewidth\crcr\unhbox0}}} \def\polhk#1{\setbox0=\hbox{#1}{\ooalign{\hidewidth \lower1.5ex\hbox{`}\hidewidth\crcr\unhbox0}}} \def$'${$'$}
{'timestamp': '2020-06-01T02:07:20', 'yymm': '2005', 'arxiv_id': '2005.14407', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14407'}
arxiv
\section{Additional Experiments} \myparagraph{Blocking Effectiveness} Figure~\ref{fig:bbafro} compares the Pair Recall of \afro{} and a traditional blocking pipeline $\mathcal{B}$, both with block-weights initialized with \texttt{TF-IDF} weighting mechanism. Figure~\ref{fig:bbafroappendix} performs the same comparison with the pipelines initialized using \texttt{Unif} weights. Since, all blocks are assigned equal weight, we consider the block cleaning threshold of 100 along with default value of M. \afro{} performs substantially better than $\mathcal{B}$ for different settings of block building techniques across various datasets. With comparison to \texttt{TF-IDF} weighting scheme, \texttt{Unif} performs slightly worse but the difference is not substantial. The no-feedback pipeline $\mathcal{B}$ has varied performance across different data sets with the best performance on \texttt{products} and poorest performance on \texttt{citations} and \texttt{songs}. \subsection{Setup} \label{sec:setup} \noindent Before showing results we describe our experimental setup and the methods considered in our experiments. \myparagraph{Experimental set-up} We implemented the algorithms in Java and machine learning tools in Python. The code runs on a server with 500GB RAM (all codes used $\leq$ 50GB RAM) and 64 cores. We consider six real-world data sets (see Table \ref{tab:dataset}) of various sizes and diverse cluster distributions. \dfnew{All the datasets are publicly available and come with their own manually curated ground truth.} We use publicly available pre-trained deep learning models\footnote{\url{https://cloud.google.com/vision}, \url{ https://www.ibm.com/watson/services/visual-recognition/}} to generate text descriptions of the image data (\texttt{cars}). For implementing the hierarchy we observed that we can trim at a depth of $10$ without any significant drop in the performance. \myparagraph{Blocking methods} We consider \dfnew{8} strategies for the blocking sub-tasks described in Section~\ref{sec:prel} and \dfnew{combine such strategies into 16 different pipelines. We study such pipelines with and without our \afro{} approach on top. \begin{compactitem} \item[$\mathcal{BB}$)] We consider 4 methods for Block Building ($\mathcal{BB}$) and follow the suggestions of \cite{papadakis2018return} for their configuration. Standard blocking~\cite{papadakis2015schema} (\texttt{StBl}) generates a new block for each text token in the dataset. Q-grams blocking~\cite{gravano2001approximate} (\texttt{QGBL}) generates a new block for each 3-gram of characters. Sorted neighborhood~\cite{hernandez1995merge} (\texttt{SoNE}) sorts the tokens for each attribute and generates a new block for every sliding window of size 3 over these sort orders. Canopy clustering~\cite{mccallum2000efficient} (\texttt{CaCl}) generates a new block for each cluster of high similarity records (calculated as unweighted Jaccard similarity). We construct multiple instances of canopies (blocks), one for each attribute (i.e., based on the similarity of record pairs with respect to that attribute) and one based on all attributes together. \item[$\mathcal{BC}$)] We consider 2 traditional block scoring methods for Block Cleaning ($\mathcal{BC}$), dubbed \texttt{TF-IDF}~\cite{schutze2008introduction} and uniform scoring (\texttt{Unif}). For comparison purposes, we process blocks in non-increasing score order until the number of intra-block pairs equals to a parameter $M$ and then prune the remaining blocks. We set default $M$ to $10$ million.\footnote{\review{We note that setting a score threshold rather than a limit on the number of pairs would not take into account different scores distributions fairly.}} \item[$\mathcal{CC}$)] We consider 2 popular methods for Comparison Cleaning ($\mathcal{CC}$), dubbed meta-blocking~\cite{metablocking} (\texttt{MB}) and \texttt{BLOSS}{}~\cite{dal2018bloss}, and follow the suggestions of \cite{metablocking} for their configuration. Weights of record pairs are set to their Jaccard similarity weighted with the block scores from the $\mathcal{BC}$ sub-task. We consider the top $100$ high-weight pairs for each record and prune the remaining record pairs. \end{compactitem}} \noindent We recall that variants of our approach are denoted as \afro(,,) while traditional blocking pipelines without feedback are denoted as $\mathcal{B}$(,,) where the parameters correspond to techniques for $\mathcal{BB},\ \mathcal{BC}$ and $\mathcal{CC}$ sub-tasks, respectively. Default methods are \texttt{StBl} for $\mathcal{BB}$, \texttt{TF-IDF} for $\mathcal{BC}$ and \texttt{MB} for $\mathcal{CC}$. Default $\phi$ \dfnew{for \afro{}} is $0.01$. \begin{figure*}[ht!] \centering \includegraphics[width= \textwidth]{plots/pcstbl}\\ \includegraphics[width= \textwidth]{plots/pcbloss}\\ \caption{Pair recall of $\mathcal{B}$(,\texttt{TF-IDF},) and \afro{}(,\texttt{TF-IDF},) with varying $\mathcal{BB}$ and $\mathcal{CC}$. (a-d) use \texttt{MB} and (e-h) use \texttt{BLOSS}. \texttt{CaCl} did not finish within 24 hrs on \texttt{songs} and \texttt{citations} data set. \label{fig:bbafro}} \end{figure*} \myparagraph{Pair matching and Clustering methods} We consider the following 3 strategies that leverage the notion of an \emph{oracle} to answer pairwise queries of the form ``does $u$ match with $v$?'' (a) $\texttt{Edge}$ ~\cite{wang2013leveraging} with default parameter setting. (b) \texttt{Eager}{}~\cite{galhotraSigmod}, the state-of-the-art technique to solve ER in the presence of erroneous oracle answers. (c) \texttt{Node} is the ER mechanism derived from~\cite{vesdapunt2014crowdsourcing} and was proposed as an improvement over \texttt{Edge}. The \texttt{Eager}{} algorithm handles noise for data sets with matching pairs much larger than $n$ and performs similar to \texttt{Edge} for data sets that have fewer matching pairs \cite{firmani2016online}, so we use it as default. We implement the abstract oracle tool with a classifier using scikit learn\footnote{\url{https://scikit-learn.org/stable/}} in Python. We consider two variants, Random forests (default) and a Neural Network. \review{The random forest classifier is trained with default settings of scikit learn. The neural network is implemented with a 3-layer convolutional neural network followed by two fully connected layers. We used word2vec word-embeddings for each token in the records. } In structured data sets, we extract similarity features for each attribute as in~\cite{das2017falcon}. For \texttt{cars} we use the text descriptions to calculate text-based features along with image-based features. Given the unstructured nature of text descriptions for some data sets we extracted POS tags using Spacy\footnote{\url{https://spacy.io/}}. All the considered classifiers are trained off-line with less than $1,000$ labelled pairs, \dfnew{containing a similar amount of matching and non-matching pairs. These labelled record pairs are the ones provided by the respective source for \texttt{citations}, \texttt{songs}, \texttt{products} and \texttt{camera} (the papers mentioned in Table~\ref{tab:dataset}, column ``ref.''). For \texttt{cars} and \texttt{cora} we perform active learning (following the guidelines of \cite{das2017falcon}) to identify a small set of labelled examples for training, which are excluded from the evaluation of blocking quality.} \subsection{Benefits of Progressive Blocking} \label{sec:exptwo} In this experiment we evaluate the empirical benefit of \afro{} compared to previous blocking strategies. \myparagraph{Blocking effectiveness} Figure \ref{fig:bbafro} compares the Pair Recall (PR) of \afro{} and of a traditional blocking pipeline $\mathcal{B}$ for different choices of the block building and comparison cleaning techniques. We use default block cleaning \texttt{TF-IDF} and default $M$ value. \afro{} achieves more than $0.90$ recall for all the data sets and with all the block building strategies, \review{ demonstrating its robustness to different cluster distributions and properties of the data.} Conversely, most of the considered block building strategies (\texttt{StBl}, \texttt{QGBL} and \texttt{SoNE}) have significantly lower recall even when used together with \texttt{BLOSS}{} for selecting the pairs wisely. \texttt{QGBL} and \texttt{SoNE} help to improve recall in data sets with spelling errors but due to very few spelling mistakes in our data sets \texttt{StBl} has slightly higher recall. In terms of the data sets, the no-feedback blocking approach $\mathcal{B}$ has varied behavior. \texttt{products} and \texttt{camera} yield the best performance due to the presence of relatively cleaner blocks that help to easily identify matching pairs even without feedback. \texttt{songs} has higher noise and \texttt{cars} has a skewed distribution of clusters thereby making it harder for previous techniques to handle. For this analysis, we do not consider \texttt{cora} (the smallest data set) as it has less than $2$M pairs and hence, all techniques achieve perfect recall. We observed similar trends with \texttt{Unif} method for block cleaning in place of \texttt{TF-IDF} (discussed in Appendix). \begingroup \setlength{\tabcolsep}{1pt} \begin{table} \caption{\review{Running time comparison of $\mathcal{B}$(\texttt{StBl},\texttt{TF-IDF},\texttt{MB}) and \afro{}(\texttt{StBl},\texttt{TF-IDF},\texttt{MB}). \label{tab:timeafro}}} \centering \scriptsize { \begin{tabular}{ |l | | c | c |c|c|} \hline Dataset&\multicolumn{2}{c|}{0.95 Pair recall} & \multicolumn{2}{c|}{Time budget: 1 hr} \\\hline &\afro{} & $\mathcal{B}$ & \afro{}& $\mathcal{B}$ \\ \hline \hline \texttt{songs} & 29min & 3hrs & 0.96 & 0.78 \\ \texttt{citations} & 55min & Did not finish in 24 hrs& 0.97 & 0.64 \\ \texttt{cars} & 4hr 10min & 12hr & 0.78& 0.54\\ \hline \texttt{products} & 6min 25sec & 6min 13sec & 0.99&0.98 \\ \texttt{camera} & 12min & 13min & 0.97 &0.96 \\ \texttt{cora} & 5min 20 sec & 5min 15 sec & 1 & 1 \\ \hline \end{tabular} } \end{table} \endgroup \myparagraph{Blocking efficiency} \review{In this experiment, we consider two different settings to compare (i) the time required to achieve more than $0.95$ pair recall (ii) the pair recall when the pipeline is allowed to run for a fixed amount of time ($1$ hour). We run each technique for various values of $M$ and choose the best value that satisfies the required constraints. In the case of fixed budget of running time = $1$hour, we run \afro{}'s feedback loop for the most iterations that allow the pipeline to process all records in the required time limit. } \review{Table~\ref{tab:timeafro} compares the total time required to achieve $0.95$ pair recall for each dataset\footnote{\review{This includes the time required by each approach to perform pair matching on the generated candidates.}}. \afro{} provides more than $3$ times reduction in running time for most large scale datasets in this setting. In terms of total number of pairs enumerated, \afro{} considers around M=10 million to achieve $0.95$ recall for \texttt{citations} as opposed to more than 200 million for $\mathcal{B}$. We observed similar results for other block building (\texttt{SoNE}, \texttt{QGBL} and \texttt{CaCl}) and cleaning strategies. } \review{The last two columns of Table~\ref{tab:timeafro} compare the pair recall of the generated candidates when the technique is allowed to run for $1$ hour. \afro{} achieves better pair recall as compared to $\mathcal{B}$ across all datasets. The gain in recall is higher for larger datasets. The performance of \afro{} for \texttt{cars} is lower than that of \afro{} in Figure~2d because the feedback loop does not converge completely in 1hr. The pipeline runs for 8 rounds of feedback in this duration. This is consistent with the performance of \afro{} in Figure~4a, where the feedback is turned off after $10$ iterations. }\review{The difference in performance of \afro{} and $\mathcal{B}$ is not high for small datasets of low noise like \texttt{products}, \texttt{cora} and \texttt{camera} as opposed to \texttt{songs}, \texttt{citations} and \texttt{cars}. } \subsection{Robustness of Progressive Blocking} \label{sec:expone} In this section, we evaluate the performance of \afro{} with varying strategies for pair matching and clustering in Algorithm~\ref{algo:afro} (referred to as $W$ in the pseudo-code). \dfnew{For this analysis, we use the default setting for $M$ as in Figure~\ref{fig:bbafro}.} \myparagraph{Varying ER methods} \df{We recall that \afro{} can be used in conjunction with a variety of techniques for pair matching and clustering. } Table \ref{tab:FL} compares the Pair Recall of the blocking graph, when using the different progressive ER methods mentioned in Section~\ref{sec:setup}. The final Pair Recall of \afro{} is more than $0.90$ in all data sets \review{and matching algorithms} except \texttt{citations} for node ER and more than $0.85$ in all cases. This observation confirms our theoretical analysis in Section~\ref{sec:theory}, demonstrating that the feedback loop can improve the blocking, irrespective of the ER algorithm under consideration (which is a desirable property for a blocking algorithm). The above comparison of ER performance considers the algorithms with a default choice of Random Forest classifier as the oracle. We observed that the feedback from the ER phase when using a Neural Network classifier contains slightly more errors but the blocking phase with \afro{} shows similar recall. We provide more discussion on ER errors in Section~\ref{sec:expthree}. \myparagraph{Benefit on the final ER result} Table~\ref{tab:eager} compares the F-score of the final ER results when blocking is \review{performed} with and without \afro{}. In this experiment we use the state-of-the-art algorithm, \texttt{Eager}{} as the pair matching algorithm with default parameter values. Final F-score achieved with feedback is more than 0.9 for all data sets except \texttt{products}. For \texttt{songs}, \texttt{citations} and \texttt{cars} the F-score of \afro{} is 1.5 times more than that of traditional blocking pipeline without feedback, thus demonstrating the effects of better effectiveness and efficiency of blocking. \begingroup \setlength{\tabcolsep}{2pt} \begin{table} \centering \scriptsize \caption{\dfnew{(a) Pair recall of \afro{} on varying ER strategies. (b) Comparison of the final F-score of the \texttt{Eager} method. The blocking graph is computed with \afro{}(StBl, TF-IDF, MB) and $\mathcal{B}$(StBl, TF-IDF, MB) (both with default settings).}} \vspace{-2mm} {\subfloat[\label{tab:FL}]{\begin{tabular}{ |l | | c | c |c|c|} \hline \multirow{2}{*}{Dataset} & \multirow{2}{*}{$\mathcal{B}$}\multirow{2}{*} & \multicolumn{3}{c|}{\afro{}} \\ \cline{3-5} & & \texttt{Edge} & \texttt{Node} & \texttt{Eager} \\ \hline\hline \texttt{songs} & 0.53 & {0.9} & {0.9} & {0.9} \\ \texttt{citations} & 0.42 & {0.90} &0.87 & 0.95 \\ \texttt{cars} & 0.54 & {0.98} & 0.99 & 0.98 \\ \hline \texttt{products} & 0.95 & {0.98} & 0.98 & 0.98 \\ \texttt{camera} & 0.92 & 0.97 & 0.97 & 0.97 \\ \texttt{cora} & 1 & 1 & 1 & 1 \\ \hline \end{tabular}}} { \subfloat[\label{tab:eager}]{ \begin{tabular}{ |p{1.2 cm} | | c | c|} \hline \multirow{2}{*}{Dataset} & \multirow{2}{*}{$\mathcal{B}$} & \multirow{2}{*}{\afro{}} \\ & & \\\hline\hline \texttt{songs} & 0.65 & \textbf{0.92} \\ \texttt{citations} & {0.56} & \textbf{0.92} \\ \texttt{cars} & 0.64 & \textbf{0.94} \\ \hline \texttt{products} & 0.71 &\textbf{0.72} \\ \texttt{camera} & 0.92 & \textbf{0.95} \\ \texttt{cora} & 0.99 & 0.99 \\ \hline \end{tabular}}} \end{table} \endgroup \subsection{Progressive Behavior} \label{sec:expthree} This section studies the performance of \afro{} dynamically, in terms of (i) effect of feedback frequency $\phi$, (ii) effect of error on convergence, and (iii) convergence of the blocking result in the maximum number of rounds. \begin{figure} \centering \subfloat[{Feedback Frequency }\label{fig:feedback}]{\includegraphics[width=0.24\textwidth]{plots/feedback.pdf}} \subfloat[Oracle error \label{fig:error}]{\includegraphics[width=0.24\textwidth]{plots/error}} \caption{Progressive behavior of \afro{} with varying feedback frequency and errors in the feedback (\texttt{cars}). \label{fig:freq}} \end{figure} \myparagraph{Feedback frequency} The $\phi$ parameter represents the fraction of newly processed record pairs after which feedback is sent from the partial ER results back to the blocking phase. Therefore, the parameter $\phi$ can control the maximum number of rounds of \afro{} and how often the blocking graph is updated. In order to describe the effect of varying $\phi$, Figure~\ref{fig:feedback} shows the F-score of the ER results as a function of the percentage of rounds completed, that we refer to as the \emph{blocking progress}.\footnote{Not to be confused with the ``ER progress'' in Algorithm~\ref{algo:afro}}. In the figure, different curves correspond to different feedback frequencies, including the default one (in blue). This plot shows that by updating the blocking graph more frequently (and thus increasing the number of rounds), the F-score \review{increases faster when $\phi$ is reduced from 0.08 to 0.01. The plot also shows that the F-score corresponding to smaller values of $\phi$ (up to 0.01) is consistently higher or equal as compared to the F-score corresponding to larger values of $\phi$.} Given that the running time of the pipeline increases with more frequent updates (\review{smaller values of $\phi$}), there appears to be limited value in decreasing $\phi$ below $0.01$, thus justifying our choice for its default setting } \myparagraph{Effect of ER errors} \review{As in} the previous experiment, Figure~\ref{fig:error} shows the effect of synthetic error in the ER results by varying the fraction of \dfnew{erroneous oracle answers. To this end, we corrupted the oracle answers randomly so as to get the desired amount of noise.} We note that even when 1 out of 5 answers are wrong, the final F-score is almost $0.8$, growing monotonically from the beginning to the end at the cost of a few extra pairs compared. \afro{} converges slower with higher error but the error does not accumulate and it performs much better than any other baseline. Additionally, we observed that even with 20\% error, the pair recall of \afro{} is as high as $0.98$ even though the F-score is close to 0.8 due to mistakes made by pair matching and clustering phase. This confirms that \afro{} is robust to errors in ER results and maintains high effectiveness to produce ER results with high F-score. \begin{figure} \centering \includegraphics[width=0.48\textwidth]{plots/fig4} \caption{Effect of feedback loop in \texttt{cars} dataset.\label{fig:cars}} \end{figure} \myparagraph{Score Convergence} Figure 4a compares the Pair Recall (PR) of the blocking phase of \afro{}(\texttt{StBl},\texttt{TF-IDF},\texttt{MB}) after every round of feedback with the recall of $\mathcal{B}$(\texttt{StBl},\texttt{TF-IDF},\texttt{MB}). Both $\mathcal{B}$ and \afro{} start with PR value close to 0.52 and \afro{} consistently improves with more feedback achieving PR close to $0.9$ in less than 18 rounds. This shows the convergence of \afro{}'s score assignment strategy to achieve high PR values even with minimal feedback. Figure 4b compares the final F-score achieved by our method if the feedback loop is stopped after a few rounds. It shows that \afro{} achieves more than 0.8 F-score even when stopped after 10 rounds of feedback. This experiment validates that the convergence of block scoring leads to the convergence of the entire ER workflow. \subsection{Key takeaways} The empirical analysis in the previous sections has demonstrated \afro{}'s benefit on final F-score and its ability to boost effectiveness of blocking techniques across all data sets without compromising on efficiency. The key takeaways from our analysis are summarized below. \begin{compactitem} \item \afro{} improves Pair Recall irrespective of the technique used for block building, block cleaning or comparison cleaning (Figure \ref{fig:bbafro}), \df{thus demonstrating its flexibility}. \item Feedback based scoring helps in particular to boost blocking efficiency and effectiveness for noisy datasets with many matching pairs (i.e. containing large clusters) such as \texttt{cars}, by enabling accurate selection of cleanest blocks. \item The block intersection algorithm helps in particular with data sets with fewer matching pairs (i.e. with mainly small clusters) such as \texttt{citations} and \texttt{songs}, by providing a way to build small focused blocks with high fraction of matching pairs. Block intersection can also help in data sets like \texttt{products} and \texttt{camera} but the benefit is not as high as that in \texttt{songs}, because many records in such data sets have unique identifiers (e.g. product model IDs) and thus initial blocks are reasonably clean. \end{compactitem} \section{Introduction} \label{sec:intro} \sloppy Entity Resolution (ER) is the problem of identifying which records in a data \review{set} refer to the same real-world entity~\cite{elmagarmid2007duplicate}. ER technologies are key for solving complex tasks (e.g., building a knowledge graph) but comparing all the record pairs to decide which pairs match is often infeasible. For this reason, the first step of ER selects sub-quadratic number of record pairs to compare in the subsequent steps. To this end, a commonly used approach is \emph{blocking}~\cite{papadakis2016comparative}. Blocking groups similar records into \emph{blocks} and then selects pairs from the ``cleanest'' blocks -- i.e., those with fewer non-matching pairs -- for further comparisons. The literature is rich with methods for building and processing blocks~\cite{papadakis2016comparative}, but depending on the data \review{set} at hand, different techniques can either leave too many matching pairs outside, leading to incomplete ER results and low effectiveness, or include too many non-matching pairs, leading to low efficiency. \begingroup \setlength{\tabcolsep}{2pt} \begin{table} \scriptsize \centering \caption{Sample records (we omit schema information) referring to 4 distinct entities. $r_i^{e}$ represents the i-th record referring to entity $e$. Records in the first \review{two} rows refer to a Chevrolet Corvette C6 ($c6$) and a Z6 ($z6$). Records in the \review{last two rows} to a Chevrolet Malibu ($ma$) and a Citr{\"o}en C6 ($ci$) (same model name as Corvette C6 but different car). \label{tab:example}} \begin{tabular}{|l|l|} \hline $r_1^{c6}$: chevy corvette c6 & $r_2^{c6}$: chevy corvette c6 navigation \\ \hline $r_3^{c6}$: chevrolet corvette c6 & $r_1^{z6}$: corvette z6 navigation \\ \hline $r_1^{ma}$: chevy malibu navigation & $r_2^{ma}$: chevrolet chevy malibu \\ \hline $r_3^{ma}$: chevrolet malibu & $r_1^{ci}$: citroen c6 navigation \\ \hline \end{tabular} \end{table} \endgroup \begin{figure*}[t] \centering {\subfloat[\label{fig:mypipel}]{\includegraphics[height=2.3cm]{fig/feedback.pdf}}} {\subfloat[\label{fig:distr}]{\includegraphics[height=2.3cm]{fig/distribution.pdf}}} \caption{\dfnew{(a) Illustration of a standard blocking pipeline. Block building, block cleaning and comparison cleaning sub-tasks are highlighted in white. The downstream ER algorithm is shown in gray. Description of each record is reported in Table~\ref{tab:example}. (b) Block size distribution (standard blocking) for the real \texttt{cars} dataset used in our experiments.}} \end{figure*} \myparagraph{\dfnew{\afro{}}} We propose a new \emph{progressive} blocking technique that overcomes the above limitations by short-circuiting the two operations -- blocking and pair comparisons -- that are traditionally solved sequentially. Our method starts with an aggressive blocking step, which is efficient but not very effective. Then, it computes a limited amount of ER results on \review{a subset of pairs selected by the aggressive blocking, and sends these partial (matching and non-matching) results from the ER phase back to the blocking phase, creating a ``loop'', to improve blocking effectiveness.} In this way, \dfnew{blocking can progressively self-regulate and} adapt to the properties of each dataset, with no configuration effort. We illustrate our blocking method, that we call \afro{}, in the following example. \begin{example} Consider the records in Table~\ref{tab:example} from the \texttt{cars} dataset used in our experiments, \dfnew{and a standard schema-agnostic blocking strategy $\mathcal{S}$ such as~\cite{papadakis2015schema}. As shown in Figure~\ref{fig:mypipel}, we consider three blocking sub-tasks~\cite{papadakis2016comparative}. First, during \emph{block building}, $\mathcal{S}$ creates a separate block for each text token (we only show the blocks `corvette', `navigation', `malibu', 'c6' and `chevy'). Then, during \emph{block cleaning}, {$\mathcal{S}$ uses a threshold to prune out all the blocks of large size}. Depending on the threshold value (using the block sizes in the entire {\tt cars} dataset, shown in Figure 1b), we can have any of the following extreme behaviors. (Note that no intermediate setting of the threshold can yield a sparse set of candidates that is at the same time complete.)} \begin{compactitem} \item \emph{Aggressive} blocking: \dfnew{$\mathcal{S}$ prunes every block except the smallest one (`chevy') and returns} $(r_1^{c6},r_2^{c6})$, $(r_1^{c6},r_1^{ma})$, $(r_2^{c6},r_1^{ma})$ and $(r_1^{ma},r_2^{ma})$, missing $r_3^{c6}$ and $r_3^{ma}$. \item \emph{Permissive} blocking: \dfnew{$\mathcal{S}$ prunes only the largest block (`chevrolet') and returns many non-matching pairs} \end{compactitem} \dfnew{Finally, during \emph{comparison cleaning}, $\mathcal{S}$ can use another threshold to further prune out pairs sharing few blocks, e.g. by using \emph{meta-blocking}~\cite{metablocking}. As in block cleaning, different threshold values can yield aggressive or permissive behaviours. Note that matching pairs such as $(r_2^{c6},r_3^{c6})$ share the same number of blocks (`corvette' and `c6') as non-matching pairs such as $(r_2^{c6},r_1^{z6})$ (`corvette' and `navigation'). (Even worse, `c6' is larger than `navigation'.)} \label{ex:motivcars} \end{example} \afro{} can solve these problems in a few rounds: the first round does aggressive blocking, the second round does more effective blocking \dfnew{by making targeted updates} accordingly to partial ER results, and so on. \dfnew{Examples of such updates to the blocking result are discussed below. \begin{compactenum} \item \review{Creation of new blocks that help \emph{inclusion} of} $(r_1^{c6},r_3^{c6}), (r_2^{c6},r_3^{c6})$: \review{\afro{}} creates a \emph{new} block `corvette $\land$ c6' \dfnew{with records present in both blocks `corvette' and `c6'.} \review{This block is much smaller than its two constituents and has only Corvette C6 cars.} \item \dfnew{Adaptive cleaning to help \emph{inclusion} of} $(r_1^{ma},r_3^{ma}), (r_2^{ma},r_3^{ma})$: \dfnew{\afro{} can discourage pruning of block `malibu' that contains Chevrolet Malibu cars, even if it is a large block;} \item \dfnew{Adaptive cleaning to help \emph{exclusion} of non-matching pairs}: \dfnew{\afro{} can encourage pruning of block `navigation' that contains no matching pairs, even if it is a small block.} \end{compactenum} After a few rounds of updates like the above, \review{\afro{} returns all the matching pairs with very few non-matching pairs}. Note that after the last round, the ER output can be computed on the resulting pairs as in the traditional setting. Updates of type (1) are performed via a new \emph{block intersection} algorithm, while (2) and (3) are performed by a new \emph{block scoring} method. By construction, when the blocking scores converge, the entire blocking result also converges. \myparagraph{Our contributions} The main contribution of this paper is a new blocking methodology with both high efficiency and effectiveness in a variety of application scenarios. Since \afro{} can in principle start off using any blocking strategy, it represents not only a new approach but also a way to ``boost'' traditional ones. \afro{} works seamlessly across different entity cluster size distributions such as: \begin{compactitem} \item \emph{small entity clusters}, where, using block intersection, \afro{} can recover entities such as Corvette C6 consisting of few records sharing large and dirty blocks. \item \emph{large entity clusters}, where, using block scoring, \afro{} can recover entities such as Chevrolet Malibu consisting of many records sharing large and clean blocks \end{compactitem} \noindent We prove theoretically and show empirically that, with a few rounds and a limited amount of \review{partial ER} results, our progressive blocking method can provide a significant boost in blocking effectiveness without penalizing efficiency. Specifically, we (i) demonstrate fast convergence and low space and time complexity ($O(n \log^2 n)$, where $n$ is the number of records) of \afro{}; (ii) report experiments achieving up to 60\% increase in recall when compared to state-of-the-art blocking~\cite{dal2018bloss}, and up to 5x boost in efficiency. Finally, we observe that \afro{} can yield up to 70\% increase on the F-score of the final ER result, thus confirming the substantial benefits of our approach. \myparagraph{Outline} The rest of this paper is organized as follows. Sections~\ref{sec:prel} and~\ref{sec:arch} provide preliminary discussions and a high-level description of the \afro{} approach. Sections~\ref{sec:refinement} and~\ref{sec:feedback} explain our block intersection and block scoring methods, respectively. Section~\ref{sec:perf} provides theoretical analysis of \afro{}'s effectiveness and Section~\ref{sec:exp} provides extensive experimental results and key takeaways. Section~\ref{sec:related} discusses the related work and we conclude in Section~\ref{sec:concl}. \section{Blocking Preliminaries} \label{sec:prel} \begin{table} \centering \scriptsize \caption{Notation Table} \begin{tabular}{||c | c||} \hline $V$ & Collection of records \\ \hline $\mathcal{C}$ & Collection of clusters \\ \hline $B$ & Block: A subset of records, $B \subseteq V$\\\hline $p_m(u,v)$ & Similarity between $u$ and $v$\\\hline \bgraph{}~$=(V,A')$ & Blocking graph, $A' \subset V \times V$ \\\hline $\phi$ & Feedback frequency\\\hline $p(B)$ & Probability score of a block $B$ \\\hline $u(B)$ & Uniformity score of block $B$\\ \hline $H(B)$ & Entropy of block $B$\\ \hline $\mathcal{H}$ & Block Hierarchy \\ \hline $G_t$ & Random Geometric graph \\ \hline $\gamma$ & Fraction of nodes used for scoring blocks\\ \hline $\mu_g$& Expected similarity of a matching edge\\\hline $\mu_r$& Expected similarity of a non-matching edge\\\hline \end{tabular} \label{table:notation} \end{table} \df{ {Table~\ref{table:notation} summarizes the main symbols used throughout this paper.}} \dfnew{Let $V$ be the input set of records, with $|V|=n$. Consider an (unknown) graph $\mathcal{C}=(V, E^{+})$, where $(u,v) \in E^{+}$ means that $u$ and $v$ represent the same entity. $\mathcal{C}$ is transitively closed, that is, each of its connected components $C \subseteq V$ is a clique representing a distinct entity. We call each clique a \textit{cluster} of $V$, and refer to the partition induced by $\mathcal{C}$ as the ER \emph{ground truth}.} \dfnew{\begin{definition}[Pair Recall] Given a set of matching record pairs $A' \subseteq V \times V$, Pair Recall is the fraction of pairs $(u,v) \in E^+$ that can be either (i) matched directly, because $(u,v)\in A'$, or (ii) indirectly inferred from other pairs $(u,w_0), (w_0,w_1), \dots, (w_c,v) \in A'$ by connectivity. \end{definition} } \dfnew{A formal definition of the blocking task follows.} \dfnew{\begin{problem}[Blocking Task] Given a set of records $V$, group records into possibly overlapping blocks $\mathcal{B}\equiv \{B_1, B_2, \dots\}$, $B_i\subseteq V$ and compute a graph \bgraph{}~$=(V,A')$, where $A' \subseteq A$, $A \equiv \{(u,v) : \exists B_i \in \mathcal{B}\textnormal{ s.t. }u \in B_i \land v \in B_i\}$, such that $A'$ is sparse ($|A'| << {n \choose 2}$) and $A'$ has high Pair Recall. We refer to \bgraph{} as the \emph{blocking graph}. \label{prob:blocking} \end{problem}} \dfnew{The blocking graph \bgraph{} is the final product of blocking and contains all the pairs that can be considered for pair matching. The efficiency and effectiveness of the blocking method is measured as Pair Recall (PR) of (the set of edges in) \bgraph{} and the number of edges in it for a certain PR, respectively.} Blocking methods consist of three sub-tasks as defined by~\cite{papadakis2016comparative}: block building, block cleaning and comparison cleaning. In the following, we describe each of these steps and the corresponding methods in the literature. \emph{Block building} ($\mathcal{BB}$) takes as input $V$ and returns a block collection $\mathcal{B}$, by assigning each record in $V$ to possibly multiple blocks. The popular \emph{standard blocking}~\cite{papadakis2015schema} strategy creates a separate block $B_t$ for each token $t$ in the records and assigns to $B_t$ all the records that contain the token $t$. In order to tolerate spelling errors, \emph{q-grams blocking}~\cite{gravano2001approximate} considers \review{character-level} q-grams instead of entire tokens. Other strategies include \emph{canopy clustering}~\cite{mccallum2000efficient} \review{and} \emph{sorted neighborhood}~\cite{hernandez1995merge}. \review{Canopy clustering iteratively selects a random seed record $r$, and creates a new block $B_r$ (or a canopy) with all the records that have a high similarity with $r$ with respect to a given similarity function (e.g., using a subset of features~\cite{mccallum2000efficient}). We can use different similarity functions to build different sets of canopies.} Sorted neighborhood sorts all the records \review{according to multiple sort orders (e.g., each according to a different attribute~\cite{hernandez1995merge}) and then it slides a window $w$ of tokens over each ordering, every time creating a new block $B_w$. Blocks have the same number of distinct tokens but the number of records in a block can vary significantly. \df{Each {of} these techniques creates $O(n)$ blocks.}} \emph{Block cleaning} ($\mathcal{BC}$) takes as input \dfnew{the} block collection $\mathcal{B}$ and returns a subset $\mathcal{B}' \subseteq \mathcal{B}$ by \dfnew{pruning} blocks that may contain too many non-matching record pairs. Block cleaning is typically performed by assigning each block a $score: \mathcal{B} \rightarrow {\rm I\!R}$ with a block scoring procedure and then \dfnew{pruning} blocks with low score. Traditional scoring strategies include functions of block sizes such as TF-IDF~\cite{elmagarmid2007duplicate,papadakis2012blocking}. \emph{Comparison cleaning} ($\mathcal{CC}$) takes as input the set $A$ of all the intra-block record pairs in \dfnew{the} block collection $\mathcal{B}'$ \dfnew{(which is a subset of the intra-block record pairs in $\mathcal{B}$)} and returns a graph \bgraph{}~$=(V,A')$, with $A' \subseteq A$, by \dfnew{pruning} pairs that \review{are likely to} be non-matching. Comparison cleaning is typically performed by assigning each pair a $weight: A \rightarrow {\rm I\!R}$ and then pruning pairs with low weight. Weighting strategies include \emph{meta-blocking}~\cite{metablocking} possibly with active learning~\cite{simonini2016blast,dal2018bloss}. In classic meta-blocking, $weight(u,v)$ corresponds to the number of blocks in which $u$ and $v$ co-occur, \review{based on the assumption that that more blocks a record pair shares, the more likely it is to be matching.\footnote{\review{This assumption holds for block building methods such as standard blocking, q-grams blocking and sorted neighborhood with multiple orderings~\cite{hernandez1995merge}, and extends naturally to canopy clustering by using multiple similarity functions.}}} The recent \texttt{BLOSS}{} strategy~\cite{dal2018bloss} employs active learning on top of the pairs generated by meta-blocking, and learns a classifier using features extracted from the blocking graph for further pruning. \df{We denote with $\mathcal{B}$($X,Y,Z$) a blocking strategy that uses the methods $X$, $Y$, and $Z$, respectively for block building, block cleaning and comparison cleaning. The strategy used in our $\texttt{cars}$ example (Example~\ref{ex:motivcars}) can be thus denoted as $\mathcal{B}$(\emph{standard blocking, TF-IDF, meta-blocking}).} \myparagraph{After blocking} \dfnew{Typical ER algorithms include \emph{pair matching} and entity~\emph{clustering} operations. Such operations label as ``matching'' the pairs referring to the same entity and ``non-matching'' otherwise, and typically require the use of a classifier~\cite{mudgal2018deep} or a crowd~\cite{wang2013leveraging}. Clustering consists of building a possibly noisy clustering $\mathcal{C}'$ according to labels, and can be done with a variety of techniques, including robust variants of connected components~\cite{VerroiosErrors} and random graphs~\cite{galhotraSigmod}. This noisy clustering is the final product of ER. } \section{Overview of \MakeLowercase{p}Blocking} \label{sec:arch} Analogous to traditional blocking methods, \afro{} takes as input a collection $V$ of records and returns a blocking graph \bgraph{}. A high-level view of the methods introduced in \afro{}, for each of the main blocking sub-tasks of Section~\ref{sec:prel}, is provided below. Such methods, unlike previous ones, can leverage a feedback of partial ER results. \emph{Block building} \review{in \afro{}} constructs new blocks \sg{arranged in the form of} a \emph{hierarchy}. First level blocks are initialized with blocks generated by a traditional method (e.g., standard blocking, sorted neighborhood, canopy clustering or q-gram blocking). Subsequent levels contain intersections of the blocks in the previous levels. \afro{} can use feedback from the \review{partial} ER output to build intersections such as `corvette $\land$ c6' that can lead to new, cleaner blocks, and avoid bad intersections such as `corvette $\land$ chevrolet' that would not improve the fraction of matching pairs in \bgraph{} (Chevrolet Corvette C6 and Z6 are different entities). We discuss block intersection in Section~\ref{sec:refinement}. \emph{Block cleaning} \review{in \afro{}} prunes dirty blocks based on feedback-based scores. First round scores \review{are} initialized with a traditional method \review{(e.g. TF-IDF)}. Then, scores are \review{refined} based on feedback by combining two quantities: the fraction $p(B)$ of matching pairs in a block $B$, and the block uniformity $u(B)$, which captures the distribution of entities within the block ($u(B)$ is the inverse of \emph{perplexity}~\cite{manning1999foundations}). \sg{Since the goal of blocking phase is to identify blocks \review{that} have a higher fraction of matching pairs and fewer entity clusters, we combine the above values as $score(B) = p(B) \cdot u(B)$.} \afro{} can use feedback from the \review{partial} ER output to estimate $p(B)$ and $u(B)$, yielding high scores for clean blocks such as `malibu' (high $p(B)$ and high $u(B)$) and low scores for dirtier blocks such as `navigation' (low $p(B)$ and low $u(B)$), and `c6' (low $u(B)$). We discuss block scoring in Section~\ref{sec:feedback}. Finally, \emph{comparison cleaning} \review{in \afro{}} is implemented with a traditional method such as meta-blocking. \begin{algorithm}[t] \caption{Our blocking method \afro{}} \label{algo:afro} \begin{algorithmic}[1] {\scriptsize \REQUIRE Records $V$, methods $X$, $Y$, $Z$ for each blocking step. Default: \emph{X=standard blocking, Y= TF-IDF} and \emph{Z=meta-blocking}. \ENSURE Blocking graph \bgraph{} \STATE $\mathcal{C}' \leftarrow \emptyset$ \STATE $B\leftarrow$ build the first level of block hierarchy with method $X$ \STATE $scores \leftarrow$ initialize block scores using method $Y$ \STATE \bgraph{} $ \leftarrow$ block cleaning and comparison cleaning with method $Z$ \STATE \bgraph{}$_{new} \leftarrow \emptyset$ \FOR{round=2; round $\leq 1 / \phi$ $\land$ \bgraph{} $\neq$ \bgraph{}$_{new}$; round++} \WHILE{ER progress is less than $\phi$} \STATE $\mathcal{C}' \leftarrow$ \df{Execute an incremental step of method $W$ for pair matching and clustering on \bgraph{}} \ENDWHILE \STATE $score \leftarrow$ update the block scores according to $\mathcal{C}'$ \texttt{ //Feedback} \STATE $B\leftarrow$ update the block hierarchy based on $score$ \STATE \bgraph{} $ \leftarrow $ \bgraph{}$_{new}$ \STATE \bgraph{}$_{new} \leftarrow$ block cleaning and comparison cleaning with $Z$ \ENDFOR \RETURN H } \end{algorithmic} \end{algorithm} \myparagraph{Workflow} \sg{Algorithm~\ref{algo:afro} describes the \afro{} workflow and how the introduced blocking methods can be used. We denote with \afro{}($X,Y,Z$) \dfnew{a progressive blocking strategy} that uses the methods $X$, $Y$ and $Z$, respectively for building the first level of the block hierarchy, initializing the block scores, and performing comparison cleaning \dfnew{as described in Algorithm~\ref{algo:afro}}. In our \texttt{cars} examples, we have \afro{}(\emph{standard blocking, TF-IDF, meta-blocking}). We first initialize the set of clusters $\mathcal{C}'$, the block hierarchy and the block scores (\textbf{lines 1--3}). The next step (\textbf{line 4}) consists of computing the first version of the blocking graph \bgraph{} according to the selected method for comparison cleaning (e.g., meta-blocking). The graph \bgraph{} is then progressively updated, round after round (\textbf{lines 6--12}). In order to activate the feedback mechanism, \afro{} needs to interact with an ER algorithm $W$ for pair matching and clustering operations (\textbf{line 7--8}).} \df{ Algorithm \review{$W$} is executed over \bgraph{} until it makes a \emph{progress} of $\phi$ with $\phi \in [0,1]$, that is, until {$\phi \cdot n \log^2{n}$} record pairs have been processed since the previous round.\footnote{For algorithms such as~\cite{vesdapunt2014crowdsourcing}, progress can be defined as a fraction $\phi \cdot n$ of processed \emph{records} since the previous round.} At that point, the algorithm $W$ is interrupted, $\mathcal{C}'$ is updated (\textbf{line 8}) and sent as feedback to all of \afro{}'s components.} Based on such feedback, we update the function $score(B)=p(B) \cdot u(B)$ (\textbf{line 9}) and construct new blocks in the form of a hierarchy (\textbf{line 10}). Higher score blocks are used to enumerate the most promising record pairs and generate the updated blocking graph \bgraph{}$_{new}$ (\textbf{lines 11-12}). When either the maximum number of rounds $\frac{1}{\phi}$ has been reached (setting $\phi=1$ is the same as switching off the feedback) or the blocking result converges (\bgraph{} $=$ \bgraph{}$_{new}$), \afro{} terminates by returning \bgraph{}. \review{We present a formal analysis of the effectiveness of \afro{} in Section~\ref{sec:perf}.} We refer to Section~\ref{sec:exp} for experiments. Due to its robustness to different choices of the pair matching algorithm $W$, we do not include $W$ in \afro{}'s parameters (differently from $X$, $Y$, $Z$). Natural choices for $W$ include \emph{progressive} ER strategies that can process \bgraph{} in an online fashion and compute $\mathcal{C}'$ incrementally~\cite{verroioswaldo,vesdapunt2014crowdsourcing,mudgal2018deep}. However, traditional algorithms, such as~\cite{elmagarmid2007duplicate} can be used as well by adding \emph{incremental ER} techniques~\cite{gruenheid2014incremental,incrementwang} on top. \subsection{Computational complexity} \label{sec:compl} For efficiency, it is crucial to ensure that the total time and space taken to compute \bgraph{} is close to linear in $n$. Since every round of \afro{} comes with its own time and space overhead, we first describe how to bound the complexity of every round and then discuss how to set the parameter $\phi$ in Algorithm~\ref{algo:afro} (and thus the maximum number of rounds) so as to bound the complexity of the entire workflow. \myparagraph{Round Complexity} \afro{} implements the following strategies to decrease overhead of each round. \emph{Efficient block cleaning.} We compute the block scores by sampling $\Theta(\log n)$ \sg{records from each of the top $O(n)$} high-score blocks computed in the previous round. \emph{Efficient comparison cleaning.} For simplicity, we build \bgraph{} by enumerating at most $\Theta(n\log^2 n)$ intra-block pairs by processing blocks in non-increasing block score. Based on the above discussion, we have Lemma~\ref{lem:compl} \begin{Lemma} A single round of \afro{}($X,Y,Z$), such as \afro{}(\emph{standard blocking, TF-IDF, meta-blocking}) has $O(n\log^2 n)$ \sg{space and time complexity}. \label{lem:compl} \end{Lemma} \begin{proof} We first show that the total feedback is limited to $O(n\log^2 n)$ \sg{space complexity}, even though it considers all transitively inferred matching and non-matching edges, which can be $\Omega(n\log^2 n)$. For the matching pairs, we store all the records with an entity id such that any pair of records that have been resolved share the same id. This requires $O(n)$ space in the worst case and captures all the matching edges that have been identified in the ER output. For the non-matching pairs, we store a non-matching edge between their entity ids. Since the maximum number of pairs returned by \afro{} is limited to $O(n\log^2 n)$, the total number of pairs compared in each round and thus the number of non-matching edges stored is also $O(n\log^2 n)$. Then, we analyze the complexity of using feedback for the $\mathcal{BB}$ and $\mathcal{BC}$ tasks. Since the maximum number of blocks considered in any round for the scoring component is $O(n)$ and the scoring mechanism samples $O(\log^2 n)$ pairs from each block, the total number of edges enumerated for block scoring and building is $O(n\log^2 n)$. Since the maximum number of pairs for inclusion in the graph $H$ is also $O(n\log^2 n)$, a single round of \afro{} outputs $H$ in $O(n\log^2 n)$ total work. \end{proof} \myparagraph{Workflow Complexity} \review{As discussed in Section~\ref{sec:perf}, $\phi$ can be set to a small constant fraction.} Thus, along with Lemma~\ref{lem:compl}, this guarantees an $O(n\log^2 n)$ complexity for the entire workflow. Experimentally a smaller $\phi$ value yields higher final recall, thus as a default we set $\phi=0.01$, yielding a maximum of $100$ rounds. Although such a $\phi$ value gets the best trade-off between effectiveness and efficiency in our experiments, we also observe that slight variations of its setting do not affect the performance much (Section~\ref{sec:exp}), demonstrating the robustness of \afro{}. \section{Block Building} \label{sec:refinement} \input{refinement.tex} \section{Block Cleaning} \label{sec:feedback} Let $A' \subset V \times V$ be the pairs selected by blocking phase at a given point (we recall that $A'$ is the edge set of the blocking graph \bgraph{}~$=(V,A')$) and each considered pair $(u,v)\in A'$ has a similarity value denoted by $p_m(u,v)$. A block $B\subseteq V$ refers to a subset of records. Using this notation, we discuss the different methods for scoring blocks and how the scores converge with feedback for effective ER performance. \input{scoring.tex} Finally, for the presented analysis, we assumed that oracle answers are correct. Nonetheless, (i) for small amount of oracle errors ($\sim 5\%$), we can leverage methods such as~\cite{galhotraSigmod,VerroiosErrors} to correct them, and (ii) in more challenging applications with up to $20\%$ erroneous answers, we show experimentally (see Section~\ref{sec:exp}) that \afro{} keeps converging, only at a slightly slower rate and demonstrates robustness. \section{Experiments} \label{sec:exp} \input{experiments.tex} \section{Related work} \label{sec:related} Blocking has been used to scale Entity Resolution (ER) for a very long time. However, all the techniques in the literature have considered blocking as a preprocessing step and suffered from the trade-off between effectiveness and efficiency/scalability. We divide the related work into two parts: advanced blocking methods which we improve upon, and progressive ER methods which can be used to generate a limited amount of matching/non-matching pairs to send as a feedback to our blocking computation. \myparagraph{Advanced blocking methods} There are many blocking methods in the literature with different internal functionalities and solving different blocking sub-tasks. In this paper, we considered four representative block building strategies, namely standard blocking~\protect\cite{papadakis2015schema}, canopy clustering~\protect\cite{mccallum2000efficient}, sorted neighborhood~\protect\cite{hernandez1995merge} and q-grams blocking~\protect\cite{gravano2001approximate}. It is well-known that such techniques can yield a fairly dense blocking graph when used alone. We refer the reader to~\cite{papadakis2016comparative} for an extensive survey of various blocking techniques and their shortcomings. \dfnew{Such block building strategies can be used as the method $X$ in our Algorithm~\ref{algo:afro}.} Recent works have proposed advanced methods that can be used in combination with the mentioned block building techniques by focusing on the comparison cleaning sub-task (thus improving on efficiency). The first technique in this space is \emph{meta-blocking}~\cite{metablocking}. Meta-blocking \dfnew{aims to extract the most similar pairs of records by leveraging block-to-record relationships and} can be very efficient in reducing the number of unnecessary pairs produced by traditional blocking techniques, but \review{it is} not always easy to configure. To this end, follow-up works \dfnew{such Blast~\cite{simonini2016blast} use ``loose'' schema information to distinguish promising pairs, while~\cite{bilenko2006adaptive} and SNB~\cite{papadakis2014supervised} rely on a sample of labeled pairs for learning accurate blocking functions and classification models respectively. Finally,} the most recent strategy \texttt{BLOSS}{}~\cite{dal2018bloss} uses \emph{active learning} to select such a sample \dfnew{and configure the meta-blocking}. The goal of traditional meta-blocking~\cite{metablocking} and its follow-up techniques like \texttt{BLOSS}{}~\cite{dal2018bloss} prune out low similarity candidates from the blocking graph generated using various block building strategies discussed above. Their performance is highly dependent on the effectiveness of block building techniques and the quality of blocking graph. On the other hand, \afro{} constructs meaningful blocks that effectively capture majority of the matching pairs and scores each block based on their quality to generate fewer non-matching pairs in the blocking graph. Meta-blocking techniques compute the blocking graph statically, prior to ER, and thus can be used as the $Z$ method in our Algorithm~\ref{algo:afro}. In Figure~\ref{fig:bbafro} we compare with classic meta-blocking and \texttt{BLOSS}{}, as the latter shows its superiority over Blast and SNB \myparagraph{Progressive ER} Many applications need to resolve data sets efficiently but do not require the ER result to be complete. Recent literature described methods to compute the best possible partial solution. Such techniques include \emph{pay-as-you-go} ER~\cite{whang2013pay} that use ``hints'' on records that are likely to refer to the same entity and more generally \emph{progressive} ER such as the schema-agnostic method in~\cite{simonini2018schema} and the strategies in~\cite{altowim2014progressive}\cite{papenbrock2015progressive} that consider a limit on the execution time. In our discussion, we considered oracle-based techniques, namely \texttt{Node}~\cite{vesdapunt2014crowdsourcing}, \texttt{Edge}~\cite{wang2013leveraging}, and \texttt{Eager}~\cite{galhotraSigmod}. Differently from other progressive techniques, oracle-based methods consider a limit on the number of pairs that are examined by the oracle for matching/non-matching response. Such techniques were originally designed for dealing with the crowd but they can also be used with a variety of classifiers due to their flexibility. All these techniques naturally work in combination with \afro{} by sending as feedback their partial results. \myparagraph{Other ER methods} In addition to the above methods, we mention works on ER architectures that can help users to debug and tune parameters for the different components of ER~\cite{gokhale2014corleone,das2017falcon,konda2016magellan,papadakis2018return}. Specifically, the approaches in~\cite{gokhale2014corleone,das2017falcon} show how to leverage the crowd in this setting. All of these techniques are orthogonal to the scope of our work and we do not consider them in our analysis. \df{The previous work in~\cite{whang2009entity} proposes to greedily merge records as they are matched by ER, while processing the blocks one at a time. Each merged record (containing tokens from the component records) is added to the unprocessed blocks, permitting its participation in the subsequent matching and merging by their iterative algorithm. Limitations of processing blocks one at a time has been shown in more recent blocking works~\cite{metablocking}. } \section{Conclusions} \label{sec:concl} We have proposed a new blocking algorithm, \afro{} that progressively updates the relative scores of blocks and constructs new blocks by leveraging a novel feedback mechanism from partial ER results. Most of the techniques in the literature perform blocking as a preprocessing step to prune out redundant non-matching record pairs. However, these techniques are sensitive to the distribution of cluster sizes and the amount of noise in the data set and thus are either highly efficient with poor recall or have high recall with poor efficiency. \afro{} can boost the effectiveness and efficiency of blocking across all data sets by jump-starting blocking with any of the standard techniques and then using new robust feedback-based methods for solving blocking sub-tasks in a data-driven way. To the best of our knowledge, \afro{} is the first framework where blocking and pair matching components of ER can help each other and produce high quality results in synergy. \bibliographystyle{abbrv} \subsection{Conjunction of non-consecutive } \noindent Suppose the maximum depth of the hierarchy is $d$ which is a constant. The construction of \dfnew{refined} blocks can take $O(n^d)$ time if the number of blocks considered in the first layer is $O(n)$. For efficiency, we iterate over the records (linear scan) and for each record $r$, we consider all pairs of blocks that contain $r$ as candidates to generate blocks in the different levels of the hierarchy. The following lemma bounds the total number of refined blocks across the hierarchy. \begin{Lemma} The number of blocks present in $\mathcal{H}$ is $O(n)$ if each record $r$ is present in a constant number of blocks. \end{Lemma} \begin{proof} Our algorithm considers each record $u\in V$ and generates intersection blocks by performing conjunction of blocks that contain the record $u$. Suppose the record $u$ is present in $\gamma_u$ blocks in the first layer. Then the maximum number of blocks present in $\mathcal{H}$ that contain $u$ is $\sum_{i=1}^{d} {\gamma_u \choose i} $. Assuming $\gamma_u$ is a constant, the maximum number of blocks in the hierarchy is $n\sum_{i=1}^{d} {\gamma_u \choose i}=O(n)$. \end{proof} \myparagraph{Refinement algorithm} We are now ready to describe \afro{}'s intersection method for building the block hierarchy. Our method has two steps: \begin{compactitem} \item (Alg. \ref{algo:creation}) The first step creates all possible blocks considering the intersection search space. \item (Alg. \ref{algo:cleaning}) The cleaning phase removes the blocks that do not satisfy the correlation criterion described above. \end{compactitem} Algorithm~\ref{algo:creation} describes the creation step, which iterates over all the records in the corpus and creates all possible blocks per record. \review{The list of all blocks to which a record belongs is constructed (denoted by blockLst) and the new blocks are added in different layers. The layer of the new block depends on the number of intersecting blocks that constitute the new block}. Then, the cleaning step in Algorithm~\ref{algo:cleaning} iterates over the different layers and keeps only the blocks that satisfy the score or size requirements. For a block in layer $q$, \texttt{getParents}() identifies the two blocks which are in layer $(q-1)$ whose conjunction generates the block being considered. If these parents have been removed during the cleaning phase, then their parents are considered and the process is continued recursively until we end up at the ancestors present in the list of blocks. \review Block Layers Creation (Alg.~\ref{algo:creation}) constructs all the blocks in the form of a hierarchy and Layer Cleaning (Alg.~\ref{algo:cleaning}) deactivates the blocks that do not satisfy the correlation requirements. \dfnew{Since the result of block layers creation does not change in different \afro{} iterations, decoupling the creation component from the cleaning component (which changes dynamically) allows for more efficient computation.}} \myparagraph{Time complexity} Assuming the depth of the hierarchy is a constant, Algorithms~\ref{algo:creation} and~\ref{algo:cleaning} operate in time linear in the number of records $n$. Block refinement takes $3$ minutes for a data set with $1M$ records in our experiments. \section{ Analysis of \MakeLowercase{p}Blocking} \label{sec:perf} In this section we present a theoretical analysis of the effectiveness of \afro{}. We first analyze the pair recall of blocking in the absence of feedback by considering a natural generative model for block creation. Next we analyze the effect of feedback on block scoring and the final recall. \subsection{Pair Recall without Feedback} \dfnew{We start by giving the following basic lemma below. \begin{Lemma} The blocking graph \bgraph{}~$=(V,A')$ contains a spanning tree for each clique $C$ of $\mathcal{C} = (V, E^+)$ iff the Pair Recall is 1.\label{lem:rec} \end{Lemma} \begin{proof} If $A'$ contains a spanning tree for each clique $C$, then any pair $(u,v)\in A'\cap E^+$ contributes directly to the recall. \sg{All pairs of records $(u,v)$ that refer to the same entity, $(u,v) \in E^+$ and are not present in $A'$, $(u,v)\notin A'$ can be inferred from the edges in the spanning tree using transitivity, ensuring Pair Recall = 1. For the converse, let us assume that $\exists~C\in \mathcal{C}$ such that $A'$ does not contain any spanning tree over the matching edges. This implies that $C$ is split into multiple components (say $C_1$, $C_2$) when restricted to $ A'\cap E^+$ edges. In this case, the collection of matching edges joining these components, $\{(x,y), \forall x\in C_1, y\in C_2\}$ cannot be inferred as none of these edges are processed by the mentioned ER operations, yielding pair recall of \bgraph{} less than 1.} \end{proof}} Our probabilistic model for block creation is motivated by the standard blocking~\cite{papadakis2015schema}, sorted neighborhood~\cite{hernandez1995merge} and canopy clustering~\cite{mccallum2000efficient} algorithms which aim to generate blocks that capture high similarity candidate pairs. This model of block generation is closely related to Random Geometric Graphs \cite{penrose2003random} which were proposed by Gilbert in 1961 and have been used widely to analyze spatial graphs. \begin{definition}[Random Geometric Graphs] Let $S^t$ refer to the surface of a t-dimensional unit sphere, $S^t\equiv \{x\in \mathbb{R}^{t+1}\mid ||x||_2=1 \}$. A random geometric graph $G_t(V,E)$ of $n$ vertices $V$, has parameters $t\in \mathbb{Z}^+ $ and a real number $r\in [0,2]$. It assigns each vertex $i\in V$ to a point chosen independently and uniformly at random within $S^t$ and any pair of vertices $i,j\in V$ are connected if the distance between their respective points is less than $r$. \end{definition} Now, we define the probabilistic block generation model. \begin{definition}[Probabilistic Block Generation] The block generation model places the records $u\in V$ independently and uniformly at random within $S^t$. Every record $u$ constructs a ball of volume $(\alpha\log n/n)$ with $u$ as the center, where $\alpha$ is a given parameter and all points within the ball are referred to as block $B_u$. \end{definition} The set of points present within a ball $B_u$ can be seen as high similarity points that would have been chosen as blocking candidates in the absence of feedback. Our probabilistic block generation model constructs $n$ blocks, one for each node and every pair of records that co-occur in a block $B_u, u\in V$, has an edge in the blocking graph \bgraph{}$_g(V,E)$ (subscript $g$ to emphasize generative model). Next we analyze pair recall of \bgraph{}$_g(V,E)$. \myparagraph{Notation} Let $d(u,v)$ refer to the distance between records $u$ and $v$ and $r_\epsilon$ refer to the radius of an $\epsilon$-volume ball\footnote{ $\epsilon = O(r_\epsilon^t)$.} in $t$ dimensions. Under these assumptions we first show that the expected number of edges in the blocking graph \bgraph{}$_g$ is at least $\frac{\alpha (n-1)\log n}{2}$ and then that \bgraph{}$_g(V,E)$ has recall $< <1$. \begin{Lemma} The blocking graph \bgraph{}$_g(V,E)$ contains at least $\alpha\frac{(n-1)\log n}{2}$ candidate pairs on expectation. \end{Lemma} \begin{proof} Each record $u\in V$, constructs a spherical ball of volume $\alpha \log n/n$, with $u$ as the center and all points within the ball are added as neighbors of $u$ in the blocking graph. Hence, the number of expected neighbors of $u$ within the ball is $\alpha (n-1)\log n/n $. There are a total of $n$ such blocks (one ball per record) and each of the candidate pairs $(u,v)$ is counted twice (once for the block $B_u$ and once for the block $B_v$). Hence there are a total of $\frac{\alpha(n-1)\log n}{2}$ such candidate pairs. Notice that this analysis ignores the candidate pairs $(u,v)$ which are more than $r_{\alpha\log n/n}$ from each other but are connected in the blocking graph. This would happen if they are present together in another block centered at $w\in V\setminus\{u,v\}$, that is $\exists w \mid d(u,w)\leq r_{\alpha\log n/n}$ and $d(v,w)\leq r_{\alpha\log n/n}$. This shows that the total number of candidate pairs in the blocking graph is atleast $\frac{\alpha(n-1)\log n}{2}$. \end{proof} Additionally, \bgraph{}$_g(V,E)$ has the following property: \begin{Lemma} A blocking graph \bgraph{}$_g$ is a subgraph of a random geometric graph $G_t$ with $r=2r_{\alpha\log n/n}$ \end{Lemma} \begin{proof} Following the construction of blocking graph, if the distance between any pair of vertices $u,v\in V$ is less than or equal to $r_{c\log n/n}$, then $(u,v)\in E$. Similarly, any pair of nodes $u,v\in V$ such that $d(u,v)> 2r_{c\log n/n}$, then $(u,v)\notin E$. However, if $r_{c\log n/n}<d(u,v)\leq 2r_{c\log n/n}$, the pair $(u,v)\in H_g$ only if $\exists w\in V$ such that $d(u,w)\leq r_{c\log n/n}$ and $d(v,w)\leq r_{c\log n/n}$. This shows that the blocking graph $H_g$ is a subgraph of a random geometric graph where a pair of vertices (u,v) is connected only if the distance $d(u,v)\leq 2r_{c\log n/n}$ is connected. \end{proof} This means that if $G_t$ has suboptimal recall then \bgraph{}$_g$ also has poor recall and hence, we analyze the recall of $G_t$ with $r=2r_{\alpha\log n/n}$. Lemma \ref{lem:rec} shows that the blocking graph will achieve recall $=1$ only if it contains a spanning tree of each cluster. Hence, we analyze the formation of spanning trees in $G_t'=G_t(V,E\cap E^+)$ that refers to $G_t$ restricted to matching edges. We show the following result, \sg{ \begin{Lemma}\label{lem:disconn} The graph $G_t$ restricted to matching edges in the ground truth, $E^+$ splits a cluster $C$, where $|C|=o(n/\alpha)$ into multiple components. \end{Lemma} \begin{proof} Using the connectivity result from \cite{penrose2003random}, a random geometric graph $G_t$ of $n$ nodes is disconnected if the expected degree of the nodes is $< \log n$. Additionally, it splits the graph $G_t$ into many smaller clusters. Therefore, a cluster $C\in V$ is disconnected in $G_t'=G_t(V,E\cap E^+)$ if the degree of each vertex is $< \log |C|$. The expected degree of a record $u\in C$, restricted to $G_t'$ is $O(|C|(\frac{\alpha \log n}{n} )) =o (\log n) $ if $|C| =o(n/\alpha)$. Hence, the expected degree of each node within a cluster $C$ is $o(\log |C|)$, leading to formation of disconnected components within $C$. \end{proof} \begin{theorem} A blocking graph \bgraph{}$_g(V,E)$, generated according to the probabilistic block model has recall $<1$ unless all clusters have size $\Theta(n)$ assuming $\alpha$ is a constant. \end{theorem} \begin{proof} Lemma~\ref{lem:disconn} shows that the cluster $C$ of size $< n/\alpha$ is split into various disconnected components when restricted to matching edges. Hence, the blocking graph \bgraph{}$_g$ does not form a spanning tree of $C$ and will have recall less than $1$ \review{(Lemma~\ref{lem:rec})}. Since the cluster $C$ is broken into many small clusters, the drop in recall is also significant. \end{proof} \myparagraph{Remark} The analysis extends when considering less noisy data such as when only a constant fraction of records are placed randomly on the unit sphere, and the remaining records are grouped together according to the cluster identity they belong to. Our analysis exposes the lack of robustness of performing blocking without feedback. } \subsection{Pair Recall with Feedback} \label{sec:theory} \sloppy In this section we analyze the pair recall of blocking when employed with \afro{}. For this analysis we consider the noisy edge similarity model $p_m(u,v)$ that builds on the edge noise model studied in prior work on ER \cite{firmani2016online}. \begin{definition}[Noisy edge model] Noisy edge model defines the similarity of a pair of records with parameters $\theta\in (0,1)$, $\beta = \Theta(\log n)$ and $\beta' = \Theta(\log n)$. A matching edge $(u,v)\in E^+$ has a similarity distributed uniformly at random within $[\theta,1]$ with probability $1-\frac{\beta}{n}$ and remaining edges are distributed uniformly within $[0,\theta)$. A non-matching edge has similar distribution on similarity values with $\beta'$ instead of $\beta$. \end{definition} When $\beta << \beta'$, the matching probability score of a block with higher fraction of matching edges is much higher than the one with fewer matching edges and \afro{} algorithm will consider blocks in the correct ordering even in the absence of feedback. However, it is most challenging when non-matching edges are generated with a distribution similar to matching edges, that is $\beta$ and $\beta'$ are close. We define a random variable $X(u,v)$ to refer to the edge similarity distributed according to the noisy edge model. Following this notion, let $\mu_g$ and $\mu_r$ denote the expected similarity of a matching and non-matching edge respectively. $$\mu_g = \left(1-\beta/n\right)\frac{1+\theta}{2} + \frac{\beta}{n}\frac{\theta}{2}$$ and $\mu_r$ has the same value with $\beta'$ instead of $\beta$. We show that the feedback based block score initialized with TF-IDF weights is able to achieve perfect recall with a feedback of $\Theta(n\log^2 n)$ pairs assuming that the ER phase { makes no mistakes on the pairs that it processes, helping to ensure the correctness of partially inferred entities. } Additionally, the feedback from the ER phase is distributed randomly across edges within a block. We also discuss the extension when feedback is biased towards pairs from large entity clusters and high similarity pairs. In those scenarios, \afro{}'s scoring mechanism converges quicker leveraging the larger feedback due to transitivity. \myparagraph{Effect of Sampling} First, we show that sampling $\Theta(\log n)$ records from a block gives approximation within a factor of $(1+\epsilon)$ of the matching probability score computed using all the records. \review{\begin{Lemma} For a block $B$ with $|B| > c\log n$, the matching probability score of $B$ estimated by sampling $\Theta(\log n/\epsilon^2) $ records randomly is within $[(1-\epsilon),(1+\epsilon)]$ factor of $p(B)$ with a probability of $1-o(1)$, where $p(B)$ is the score using all $|B|$ records. \label{lem:sampling} \end{Lemma}} \begin{proof} \review{Consider a block $B$ with more than $c\log n$ records. Let $X(u,v)$ denote the edge similarity of a pair $(u,v)$ according to the noisy edge model. The matching probability score of $B$ on considering the complete block is $\frac{1}{{|B|\choose 2}}\sum_{u,v\in B} X(u,v)$. The expected score of the block ($\mu_B$) is} \begin{eqnarray*} \frac{1}{{|B|\choose 2}}E\left[\sum_{u,v\in B} X(u,v)\right] &&=\frac{1}{{|B|\choose 2}} \sum_{\substack {u,v\in B,\\(u,v)\in E^+}} E[X(u,v)]\\ && + \frac{1}{{|B|\choose 2}} \sum_{\substack{ u,v\in B,\\(u,v)\in E^-}} E[X(u,v)]\\ &=& (1-\alpha)\mu_g + \alpha \mu_r \end{eqnarray*} where $\alpha$ is the fraction of non-matching pairs in the block $B$. \review{For a sample of $S=c\log n/\epsilon'^2$ records, the expected probability score ($\mu_S$) is $ (1-\alpha)\mu_g + \alpha \mu_r$, where $\epsilon'=\epsilon/(2+\epsilon)$} \begin{eqnarray*} \frac{1}{{c\log n \choose 2}}E[\sum_{u,v\in S} X(u,v)] &=& \frac{1}{{c\log n\choose 2}}\sum_{\substack{u,v\in S, \\(u,v)\in E^+}} E[X(u,v)]\\ && + \frac{1}{{c\log n\choose 2}}\sum_{\substack{u,v\in S,\\ (u,v)\in E^-}} E[X(u,v)]\\ &=& (1-\alpha)\mu_g + \alpha \mu_r \end{eqnarray*} \review{Using Hoeffding's inequality~\cite{hoeffding}, \begin{eqnarray*} Pr\left[\frac{1}{{c\log n \choose 2}}\sum_{u,v\in S} X(u,v) \leq (1-\epsilon')\mu_S \right]\\ \leq e^{-2\epsilon'^2\mu_S^2{c\log n \choose 2}}\\ \leq e^{-2\log n}=\frac{1}{n^2}\\ \end{eqnarray*} Using the same argument, we can show that $Pr\left[{(1-\epsilon')}\mu_S \leq \frac{1}{{c\log n \choose 2}}\sum\limits_{u,v\in S} X(u,v) \leq (1+\epsilon')\mu_S \right] \geq 1- \frac{2}{n^2}$ This shows that the calculated probability score on the samples $S$ is within a factor of $(1-\epsilon')$ and $(1+\epsilon')$ of the expected score with a probability of $1-o(1)$. The probability score of $B$ on considering all records, is also within a factor of $(1-\epsilon')$ and $(1+\epsilon')$ of the expected value $\mu_S$. Therefore, the estimated score on sampling guarantees approximation within a factor of $\frac{1+\epsilon'}{1-\epsilon'} = 1+2\epsilon'/(1-\epsilon') = 1+\epsilon$ with a high probability. } \end{proof} \noindent \dfnew{The above lemma can extend to block uniformity because $p_m$ values are used analogously for expected cluster sizes. In Lemma~\ref{lem:atleast} we show how to set the constant within the $\Theta$ notation based on level of noise in the $p_m$ values.} To prove the convergence of \afro{}, we first estimate the lower and upper bound of matching probability scores of a block $B$ in the presence of feedback and show that a feedback of $\Theta(\log^2 n)$ is enough to rank blocks with larger fraction of matching pairs higher than the blocks with fewer matching pairs. Our analysis first considers the blocks containing more than $\gamma \log n$ records (where $\gamma$ is a large constant say $12$) and we analyze the smaller blocks separately. \myparagraph{Convergence for large blocks} First, we evaluate the converged block scores with a feedback $F$ and evaluate the condition that the block scores are in the correct order. For this analysis, we consider the fraction of matching edges for block score computation but similar lemmas extend for the uniformity score calculation. \begin{Lemma} For all blocks $B$, with more than $\gamma \log n$ records, the matching probability score of $B$, $p(B)$ after a feedback of $F=O(\log^2 n)$ randomly chosen pairs is at most $(1-\alpha){|F|}/{{\gamma \log n \choose 2 }} + 1.5p'(1-|F|/{\gamma \log n \choose 2})$ with a probability of $1-1/n^3$, where $\alpha$ is the fraction of non-matching pairs in $B$, $\gamma$ is a constant and $p'=\mu_g(1-\alpha) + \mu_r\alpha$.\label{lem:atleast} \end{Lemma} \begin{proof} For block scoring, \afro{} considers a sample of $S= \gamma \log n$ records (where $\gamma$ is a large constant) and considers the sample ensuring that feedback $F\subseteq S\times S$ belongs to this sample. The total number of matching edges which have been identified with feedback over randomly chosen pairs is $(1-\alpha)|F|$. Let $X(u,v)$ be a random variable that refers to the similarity of the pair $(u,v)$ and $\mu(u,v)$ to its expected value. For $S=\gamma\log n$, the expected similarity of non-feedback edges within $C$ is \begin{eqnarray*} \sum_{\substack{u,v\in S,\\ (u,v)\notin F}}\mu(u,v) &=& \sum_{(u,v)\in E^+} E[X(u,v)] + \sum_{(u,v)\notin E^+}E[X(u,v)]\\ &=& \sum_{(u,v)\in E^+} \mu_g + \sum_{(u,v)\notin E^+}\mu_r\\ &=& \left({\gamma \log n \choose 2 }-|F|\right) (\mu_g(1-\alpha)+\mu_r\alpha) \end{eqnarray*} We use the Hoeffding inequality to bound the total similarity, $\sum X(u,v)$ of $T=\left({\gamma \log n \choose 2 }-|F|\right) = \gamma' {\log n \choose 2 }$, for some constant $\gamma'$, edges which do not have feedback. \begin{eqnarray*} \sum_{u,v\in B_c, (u,v)\notin F} X(u,v) \le (1+\delta)\sum_{u,v\in B_c, (u,v)\notin F}\mu(u,v) \end{eqnarray*} with a probability of $1-e^{-2\delta^2\mu_T^2/ |T|}$ which can be simplified as $1-e^{-\delta^2\mu_T}$, since $\mu_r,\mu_g>1/2$ Hence, the probability of success simplifies to $> 1- 1/n^3$ after substituting $\delta = 0.5$. Hence, the similarity score of the block $B$ is atmost $\left(\frac{|F|}{{\gamma\log n\choose 2}}(1-\alpha) + 1.5p'(1-|F|/{\gamma \log n \choose 2})\right)$ with a high probability. \end{proof} Similarly, we prove a lower bound on block score. \begin{Lemma} For all blocks $B$ with $|B|\ge \gamma \log n$, the matching probability score after a feedback $F=O(\log^2 n)$ record pairs in $B$ is at least $(1-\alpha){|F|}/{{\gamma \log n \choose 2}} + 0.5 p'(1-|F|/{\gamma \log n \choose 2})$ with a probability of $1-1/n^3$, where $p'=\mu_g(1-\alpha) + \mu_r\alpha$ and $\gamma$ is a constant. \label{lem:atmost} \end{Lemma} Now, we analyze different scenarios of edge noise to understand the trade-off between required feedback and noise. \begin{Lemma} For every pair of blocks, $B_c,B_d$ with more than $\gamma \log n$ records, the matching probability score estimate of $B_c$ with $1-\alpha$ fraction of matching edges is greater than the score of $B_d$ with $1-\beta$ (with $\alpha<\beta$) fraction of matching edges with a probability of $1-\frac{2}{n} $ if $ \left((1-\alpha)\mu_g + \alpha \mu_r\right) >3 \left((1-\beta)\mu_g + \beta \mu_r\right)$ even in the absence of feedback.\label{lem:converge0feed} \end{Lemma} \begin{proof} Using Lemma \ref{lem:atleast} and \ref{lem:atmost}, we can evaluate the condition that $score(B_c)>score(B_d)$ with a probability of $1-\frac{2}{n^3}$, in the absence of feedback. In order to guarantee this for all blocks, we perform a union bound over $\Theta(n^2)$ pairs of blocks, guaranteeing the success rate to $1-o(1)$. \end{proof} The previous lemma shows a scenario where the noise is not high and the prior based estimation of matching probability scores give a correct ordering of blocks. Now, we consider the more challenging noisy scenario and show that $\Theta(\log^2 n)$ feedback per block is enough for correct ordering. \begin{Lemma} For every pairs of blocks, $B_c,B_d$ with more than $\gamma \log n$ records, the matching probability score estimate of $B_c$ with $1-\alpha$ fraction of matching edges is greater than the score of $B_d$ with $1-\beta$ (where $\alpha<\beta$) fraction of matching edges with a probability of $1-\frac{2}{n} $ whenever the ER phase provides overall feedback of $\Theta(n\log^2 n)$ randomly chosen edges.\label{lem:converge} \end{Lemma} \begin{proof} Using Lemma \ref{lem:atmost}, $score(B_c)\ge {|F|}/{{\gamma \log n\choose 2}}(1-\alpha) + 0.5(\mu_g(1-\alpha)+\alpha\mu_r)(1-|F|/{\gamma \log n \choose 2}) $ and using Lemma \ref{lem:atleast}, $score(B_d) \le {|F|}/{{\gamma \log n \choose 2}}(1-\beta) + 1.5(\mu_g(1-\beta)+\beta\mu_r)(1-|F|/{\gamma \log n \choose 2})$ with a probability of $1-\frac{2}{n^3}$. Hence, $score (B_c) > score (B_d)$ holds if $F=c\log^2 n$, where $c$ is a large constant. With a union bound over ${n\choose 2}$ pairs of blocks, the score of any block $B_c$ (with higher fraction of matches) is higher than that of any block $B_d$ (with lower fraction of matches) with a probability of $1-\frac{2}{n}$. The total feedback to ensure $\Theta(\log^2 n)$ feedback on each block is $\Theta(n\log^2 n)$ as we consider $\Theta(n)$ blocks for scoring. \end{proof} \myparagraph{Convergence for small blocks} The above analysis does not extend to blocks of size less than $\gamma \log n$. However, all these blocks are ranked higher than the large blocks by TF-IDF. Hence, when \afro{} is initialized, the initial set of candidates generated will consider all these blocks before any of the larger blocks. In the worst case, there can be $\delta n$ such blocks, for some constant $\delta$ because our approach constructs a constant number of blocks per record (say $\delta$). Thus, the maximum number of candidates considered from small blocks is $\delta n{\gamma\log n\choose 2}$ and all these candidates are considered in the first iteration of \afro{}. Following the discussion on small and large blocks, we prove the main result of the convergence of \afro{}. \begin{theorem} \afro{} pipeline achieves perfect recall with a feedback of $O (n\log^2 n)$ spread randomly across blocks. \label{thm:main} \end{theorem} \begin{proof} For blocks with more than $\gamma \log n$ records, Lemmas \ref{lem:converge0feed} and \ref{lem:converge} show that a block with higher fraction of matching pairs is ranked higher than a block with fewer matching pairs, if provided with a feedback of $\Theta (n\log^2 n)$. Blocks with less than $\gamma \log n$ records have not been considered above but in the worst case, these blocks generate $O(n\log^2 n)$ candidates as the maximum number of blocks considered is $\Theta(n)$. This ensures that a feedback of $\Theta (n\log^2 n)$ is sufficient to ensure the stated result. \end{proof} \begin{table*}[ht!] \centering \scriptsize \caption{Number of nodes $n$ (i.e., records), number of clusters $k$ (i.e., entities), size of the largest cluster $\left|C_1\right|$, the total number of matches in the data set $|E^+|$ and the reference to the paper where they appeared first. } \label{tab:dataset} \begin{tabular}{ |l | | c |c| c | c | c | c | l |} \hline dataset & \multicolumn{2}{c|}{$n$} & $k$ & $\left|C_1\right|$ & $\left|E^+\right|$ & ref. & description \\ \hline\hline \texttt{songs} & 1M & 1M & ~0.99M & 2 & 146K & \protect\cite{das2017falcon} & Self-join of songs with very few matches. \\\hline \texttt{citations} & 1.8M & 2.5M & \review{3.8M} & 2 & 558K & \protect\cite{das2017falcon} & Bibliographic records from DBLP and CiteSeer. \\\hline \texttt{products} & 2554 & 22K & \review{23.5K} & $2$ & 1154 & \protect\cite{gokhale2014corleone} & A collection of products from retail companies website. \\\hline \texttt{cora} & \multicolumn{2}{c|}{1.9K} & 191 & 236 & 62.9K & \protect\cite{cora2004} & Title, author, venue, and date of scientific papers. \\\hline \texttt{cars} & \multicolumn{2}{c|}{16.5K} & 48 & 1799 & 5.9M & \protect\cite{carsVision} & Descriptions of cars with make and model. \\\hline \texttt{camera} & \multicolumn{2}{c|}{29.7K} & 26K & 91 & 102K & \protect\cite{di2kg} & A collection of cameras from over 25 retail companies. \\\hline \end{tabular} \end{table*} \myparagraph{Discussion} Lemma \ref{lem:converge} considers the convergence of block scores when the feedback is provided randomly over $\Theta(\log^2 n)$ edges within a block. If the feedback is biased towards $\Theta(\log^2 n)$ non-matching edges, the scores of noisier blocks will drop quicker and \afro{} will converge faster. Similarly, if the ER algorithm queries pairs with higher similarity (e.g. edge ordering \cite{wang2013leveraging}) or grows clusters by processing nodes (e.g. node ordering \cite{vesdapunt2014crowdsourcing}), providing larger feedback due to transitivity, this will only facilitate the growth (reduction) in score of blocks with higher (lower) fraction of matching pairs leading to faster convergence.
{'timestamp': '2021-03-17T01:15:16', 'yymm': '2005', 'arxiv_id': '2005.14326', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14326'}
arxiv
\section{Introduction} Per-pixel depth estimation from more than one two-dimensional images is a well-explored research field in computer vision. Recently the surge in estimating per-pixel depth from a single two-dimensional image has increased in the research community. Monocular depth estimation poses a variety of real-world applications like autonomous driving, robot navigation, and surgical devices. Monocular depth estimation has been studied in numerous settings like supervised, semi-supervised, and self-supervised. The introduction of convolution neural network (CNN) for depth estimation has helped to gain significant improvement over other traditional methods. The supervised method considered monocular depth estimation as a regression problem with ground truth depth which are collected using devices like LiDAR and RGBD camera. However ground truth depth collection from these devices is a tedious task. The devices used for this purpose has its own downfalls. LiDAR produces a sparse depth map, and RGBD cameras have limitations on the maximum depth it can capture. The self-supervised method studies monocular depth estimation as a view synthesis problem using stereo images and/or video sequences. This view synthesis acts as the supervision of the system. The semi-supervised setting takes the best of both worlds by using sparse depth maps and multi view images for depth estimation. Even though deep learning-based methods have shown astonishing results in most computer vision task, it has been shown that they are vulnerable to attacks. The vulnerability of deep learning models for tasks like image classification, detection, and segmentation is extensively studied in the literature. However, attacks on safety-critical models like depth estimation are not investigated broadly. In this paper, we investigate the robustness of monocular depth estimators against adversarial attacks. We mainly examine pixel perturbation and patch attack against a diverse set of depth estimators. There are few works on adversarial attacks on monocular depth estimation. But these attacks only focus on classical perturbation attacks like FGSM (Fast Gradient Sign Attack) and IFGSM (Iterative FGSM). FGSM is one of the most straightforward white-box adversarial attacks introduced in \cite{goodfellow2014explaining} which uses the gradient of the loss with respect to the input data, then adjusts the input data to maximize the loss. FGSM is a one-shot method, whereas IFGSM takes more than one gradient steps to find the perturbation. Some of the drawbacks of these attacks are: \begin{enumerate} \item Perturbation attacks like FGSM are image dependent and are not ideal for real-world attacks as it needs access to the image captured by the system to attack the model. \item Defense against FGSM is more natural than adaptive perturbations generated by a network. \end{enumerate} Existing adversarial attacks on classification, object detection, and segmentation aim to maximize non-essential softmax and minimize other softmax predictions of the network, thereby flipping the final prediction of the deep neural network. However, these attacks don't have a significant effect on the scene understanding models like depth estimation. Despite its success in basic vision tasks like classification ,regression models can be attacked by these attacks to a very limited extent. In this work, we introduce a deep feature annihilation loss for both perturbation and patch attacks as shown in Figure~\ref{fig:teaser}. Deep feature annihilation (DFA) loss corrupts the internal representation of a deep neural network, rather than just the final layers. Attacks with DFA have demonstrated a more substantial effect on resultants. The main contributions of this paper are: \begin{enumerate} \item Show the vulnerability of monocular depth estimators against precisely calculated perturbation added to the input image. \item Study the effect of patch attack on monocular depth estimators even when less than one percent of the image pixels are corrupted. \item Introdunce a novel Deep Feature Annihilation loss for stronger attacks. \item Conducted extensive white and black-box testing for both perturbation and patch attack for monocular depth estimation. \item Study the transferability of adversarial samples, mainly cross-model transferability and cross data transferability. \end{enumerate} \section{Related Works} \subsection{Monocular Depth Estimation} Zhou \textit{et al}., \cite{zhou2017unsupervised} proposed an unsupervised depth estimation end-to-end framework from video sequence where view synthesis act as the supervisory signal. Godard \textit{et al}., \cite{godard2017unsupervised} estimate disparity from stereo images with a novel LR consistency loss. Mahjourian \textit{et al}., \cite{mahjourian2018unsupervised} introduced a 3D loss to enforce consistency of the estimated 3D point cloud. Yin \textit{et al}., \cite{yin2018geonet} jointly learned monocular depth, optical flow and ego motion from videos in unsupervised manner. Luo \textit{et al}., \cite{luo2018every} also jointly learned monocular depth, optical flow and ego motion from video but used these result to produce motion mask, occlusion mask, 3D motion map for rigid background and dynamic objects. Wang \textit{et al}., \cite{wang2018learning} proposed novel depth normalization strategy that substantially improves performance of the estimator. Godard \textit{et al}., \cite{godard2019digging} achieved state of the art results in KITTI rectified dataset with minimum reprojection loss, full-resolution mutli-scale sampling and a mask that ignores training pixels that violate camera motion assumptions. Bian \textit{et al}., \cite{bian2019unsupervised} proposes a scale consistent loss and a mask to handle moving and occluded objects. Lee \textit{et al}., \cite{lee2019big} introduce a network architecture that utilizes novel local planer guidance layers to guide densely encoded features to estimate depth. \subsection{Adversarial Attack} In \cite{szegedy2013intriguing} Szegedy \textit{et al}. shows that numerous state of the art neural networks are vulnerable to adversarial samples. Attacking a neural network with adversarial samples is called an adversarial attack. Adversarial attacks strive to make small perturbation in the network input so that it causes erroneous results. Attacks are mainly two types: perturbation attack and patch attack. The perturbation attack adds minute changes to pixels values so that its indistinguishable from the clean image but affects the prediction accuracy of the model. Patch attack adds a small patch that usually occupies less than one percent of the image and makes the result inaccurate. The drawback of the perturbation attack is that the attack needs to have access to the system to modify the image with the adversarial sample. Patch attacks succeed in this issue and can be placed at an apparent location in the scene to attack the model. Goodfellow \textit{et al.} \cite{goodfellow2014explaining} introduced a fast and straightforward perturbation attack called Fast Gradient Sign Attack (FGSM) that uses gradient with respect to input and adjust the input data to maximize the loss. Nguyen \textit{et al.} \cite{nguyen2015deep} shows how easy it is to generate adversarial samples that are undetectable to the human eye. They have also shown completely unrecognizable attacked images classified with a high degree of confidence. Su \textit{et al.} \cite{su2019one} reveals that even attacking a single pixel can change the classification prediction. \cite{kurakin2016adversarial} demonstrates a real physical adversarial attack in which a printed adversarial example can also affect the prediction correctness. \cite{athalye2017synthesizing} reflects the existence of 3D adversarial samples, which can fool classification models in different viewpoints, transformations, and cameras. \cite{sharif2016accessorize} fooled facial recognition system with adversarial glasses and \cite{evtimov2017robust} ticked stop sign classifier by placing adversarial stickers over it. \subsection{Adversarial Attack on Scene Understanding} Adversarial attacks in tasks like detection, semantic segmentation, and reinforcement learning are studied in \cite{hendrik2017universal, xie2017adversarial, behzadan2017vulnerability}. We mainly focus on attacks toward scene understanding tasks like depth estimation. Ranjan \textit{et al.} \cite{ranjan2019attacking}, shows the effect of adversarial patch attack on optical flow estimation. They have demonstrated that corrupting less than one percent of the pixels with a patch can deteriorate the prediction quality. The effect of adversarial patch extends beyond the region of the attack in some of the optical flow estimation models. In essence, the encoder-decoder architecture based models found to be more sensitive than spatial pyramid architecture. They also visualized feature maps of successful and failed attacks to understand the essence under the hood. Hu \textit{et al.} \cite{hu2019analysis} studies basic perturbation attacks like IFGSM (Iterative FGSM) on monocular depth estimation and also proposes a defense mechanism based on \cite{hu2019visualization}. The perturbations non-salient parts are marked out to defend against the attack. Zhang \textit{et al.} \cite{zhang2020adversarial} explores basic perturbation attacks with FGSM, IFGSM, and MI-FGSM (Momentum IFGSM) for non-targetted, targeted, and universal attack in monocular depth estimation. In contrast, we investigate global and image dependent perturbation with a novel DFA loss that attacks deep feature maps rather than final activation like \cite{hu2019analysis} and \cite{zhang2020adversarial}. We also conducted an extensive study adversarial patch attacks on monocular depth estimators, which are more significant in a real-world attack. The transferability of both global perturbation and patch are studied in this work. \section{Approach} The robustness of a model that predicts depth from one or more images is considered to be a safety-critical task. We aim to optimize pixel intensity change in an image so that it affects the final prediction of the depth estimation models. These pixel intensity changes can occur in mainly two ways: \begin{enumerate} \item Adding a small perturbation to the clean image in a way that it's indistinguishable from the clean image as briefed in Section~\ref{pertattack}. \item Corrupting few pixels, usually less than 1\% in the image as briefed in Section~\ref{patchattack}. \end{enumerate} Say $D \in \mathbb{R}^{h \times w}$ where $D(x,y)$ is the ground truth depth value at pixel location $(x,y)$ where $x \in \mathbb{Z}_+^{h}, y \in \mathbb{Z}_+^{w}$ of a clean image $I \in \mathbb{R}^{h \times w \times 3}$, the attacked adversarial image $\tilde{I} \in \mathbb{R}^{h \times w \times 3}$ will force the model to predict a wrong estimate $\tilde{D} \in \mathbb{R}^{h \times w}$ with a constraint that $I(x,y) \approx \tilde{I}(x,y)$ and $h, w$ is the height and width of the image. Though an adversarial sample can be created against the objective by maximizing the loss between predicted and ground-truth value, but ground truth depth maps are scarce. Widely popular autonomous dataset like KITTI \cite{geiger2013vision} provides sparse LiDAR ground truth but are very limited in number. The indoor NYU dataset \cite{silberman2012indoor} consists of dense depth ground truth, but the depth range are limited to the RGBD camera. Ground truth data collected from devices like Sonar, Radar, and Lidar can be used to train a supervised depth estimation model. But supervised depth learning requires a vast amount of ground truth depth data, and these depth sensors have their error and noise characteristics, which will affect the learning process of the deep neural network. 3D lasers depth sensors measurements are typically much sparser than the image and thus lack detailed depth inference. These sensors also require accurate calibration and synchronization with the cameras. Rather than relying on ground truth depth information, an alternative approach to train a model to estimate depth is by self-supervised fashion using stereo image pairs and/or video streams from a single camera. The self-supervision signal comes from the loss between the synthesized view and the target view. View synthesis is another extensively explored problem in computer vision, where the objective is to reconstruct a specific view from one or more given views. As all state of the art approaches are self-supervised, in this investigation we study five self-supervised monocular depth estimators, namely, SFM (Structure from motion)~\cite{zhou2017unsupervised}, SCSFM (Scale-Consistent SFM)~\cite{bian2019unsupervised}, Monodepth1~\cite{godard2017unsupervised}, DDVO (Direct Depth Visual Odometry)~\cite{wang2018learning}, Monodepth1~\cite{godard2017unsupervised}, Monodepth2~\cite{godard2019digging}, and B2F~\cite{janai2018unsupervised}. SFM, SCSFM, DDVO, B2F and Monodepth2 learns depth from monocular video but Monodepth1 uses stereo images. Monodepth2 also extends there work to stereo and stereo + videos training. Due to the limited availability of ground truth data, the depth network prediction of the clean image is taken as pseudo ground truth. Using these pseudo ground truths for attack makes it easy to attack a model in the absence of actual ground truth. \input{figs/pert/adv/pert_adv.tex} \subsection{Perturbation Attack} \label{pertattack} A depth network $M$ that estimates depth $D$ from a single image $I \in \mathbb{R}^{h \times w \times 3}$ as shown in Equ.~\ref{eq1}, is attacked by adding a perturbation $\alpha \in \mathbb{R}^{h \times w}$ to $I$ as shown in Equ.~\ref{eq2}. The perturbation $\alpha$ is constrained with $\eta$ when added to an image to make the added perturbation unapparent to the naked eye as shown in Equ.~\ref{eq3}. The perturbation is designed to be undetected in the attacked image $\tilde{I}$, and the attacked image looks as close as possible to the clean image $I$. The response of the network $M$ at attacked image $\tilde{I}$ is $\tilde{D}$. \begin{gather} D = M(I) \label{eq1} \\ \tilde{I} = Adv(I, \alpha, \eta) = I + \eta * \alpha \label{eq3} \\ \tilde{D} = M(Adv(I, \alpha, \eta)) \label{eq2} \end{gather} We basically experiment with two forms of pertubation namely global $\alpha_G$ and image-specific $\alpha_I$ pertubation. A perturbation network $P$ is used to generate image-specific or global perturbation. $P$ is a trivial encoder-decoder architecture based deep neural network. The image-specific perturbation network is trained with an unattacked image as input like $\alpha_I = P(I)$. This perturbation needs access to the input image to generate a perturbation noise which makes it less suitable for real-world attack (qualitative analysis in Supplementary material). However the global perturbation network is trained with random noise as input like $\alpha_G = P(\mathcal{N})$ where $\mathcal{N} \sim \mathcal{U}(0,1) \in \mathbb{R}^{h \times w}$. This perturbation has a higher chance of attacking a system in real world as compared to image-specific perturbation, thus in this investigation we focus on global pertubation. Both image-specific and global perturbation are optimized by minimizing DFA loss (see Section \ref{loss}). The optimized global pertubations for monocular depth estimators with different $\eta$ is shown in Figure~\ref{fig:pert_adv}. \subsection{Patch Attack} \label{patchattack} A depth network $M$ which estimates depth $D$ from a single image $I \in \mathbb{R}^{h \times w \times 3}$ is attacked by placing an adversarial patch $\beta \in \mathbb{R}^{H \times W}$ on the image $I$ at location $\xi$ as shown in Equ.~\ref{eq4} where $H,W$ is less than 1\% of image size $h,w$. Transformations $\omega$ includes rotation and scaling are applied on the patch $\beta$ randomly to make the patch invariant to these transformations. The response of the network $M$ at attacked image $Adv(I, \beta, \omega, \xi)$ is $\tilde{D}$. \begin{gather} \tilde{D} = M(Adv(I, \beta, \omega, \xi)) \label{eq4} \end{gather} Adversarial patches are generated by optimizing random noise initialized with $\mathcal{N} \sim \mathcal{U}(0,1) \in \mathbb{R}^{H \times W}$ by a neural network. The optimization minimizes DFA (see Section~\ref{loss}) to create global patches that are apt for real-world attacks. The square patches we optimized for monocular depth estimators are of different sizes i.e., $50 \times 50$, $60 \times 60$, $72 \times 72$ and $100 \times 100$ which are approximately 0.5\%, 0.75\%, 1\% and 2\% of the original KITTI image size $1242 \times 375$ as shown in Figure~\ref{fig:patch_adv}. \input{figs/patch/adv/patch_adv} \subsection{Deep Feature Annihilation loss} \label{loss} As compared to networks for tasks like classification and detection, regression networks are much more difficult to attack, especially depth estimation networks. To deal with this issue, we introduce a novel DFA loss $L_{dfa}$, which attacks the internal feature representation of the input image. Note that we are optimizing the following objective after every convolution layer sparing few initial encoder layers. \begin{gather} F_l = F_l^{att} \times F_l^{org} \\ L_{dfa} = \sum_{l}^{} \log [1+ \mathbb{E}(F_l^2) - \mathbb{E}(F_l)^2) ] W_l \end{gather} The aim is to minimize the variance of correlation between the features maps $F_l^{org}$ and $F_l^{att}$ where $F_l^{org}, F_l^{att}$ are the activations obtained from layer $l$ in the depth network $M$ after passing the unattacked image and attacked image through the network, respectively weighted with an empirically found $W_l$ . This objective forces non-dominant activation values to increase while forcing the dominant activation values to decrease, resulting in the reduction of variance as shown in Figure~\ref{fig:feat_lvis_sfm}. Variance reduction ends up costing network much semantic information, which makes the decoder incompetent to propagate useful information to output proper depth map. We have experimented by limiting the loss to just a variance reduction of $F_l^{att}$; however, our objective of minimizing the variance of correlations works much better in practice. \input{figs/patch/qual/patch_whitebox_50} \input{tables/whitebox_patch_rmse} \input{figs/pert/qual/pert_whitebox_5} \input{tables/whitebox_gpert_rmse} \input{figs/pert_blackbox/pert_blackbox_5} \input{tables/trans_pert_rmse} \input{figs/patch_blackbox/patch_blackbox_72} \input{tables/trans_patch_rmse} \input{figs/city_transfer/city_trans} \section{Experiments} Adversarial attacks can be categorized mainly in two ways: the desired perturbation type and assumption of the attacker's knowledge. Two perturbation types used in this investigation are briefed in Section~\ref{pertattack} and Section~\ref{patchattack}. In this section, the kinds of assumptions of the attacker's knowledge will be discussed, particularly, white-box and black-box attack. \subsection{White-box Attack} In a white-box attack, the attacker has full knowledge and access to the target model, including network architecture, input, output, and weights. We optimized adversarial samples in both perturbation and patch type. Generated perturbation is the same size as the input image of the target model. The perturbation was optimized in such a way that it is imperceivable to our naked eye. The perturbation added to the input image is constrained in our experiments in the range of $[0.01, 0.1]$ as shown in Figure~\ref{fig:white_pert_adv5} and Table~\ref{tab:whitebox_gpert_rmse}. For patch type attack we generate square adversarial patches on each network independently. All patches estimated for these networks are global, i.e., doesn't depend on the image where it is pasted. Each patch is augmented to make it invariant to rotation and location. Rotation is sampled randomly from $n \times \frac{\pi}{2}$ where $n \in \mathbb{Z}_+: 0 \leq n \leq 4$ and location from $\xi(x, y)$ where $(x,y) \in \mathbb{Z}_+: 0 \leq x \leq w, 0 \leq y \leq h$. The patch and perturbation are optimized with 45000+ image frames from the KITTI dataset. The output from the respective pretrained model in response to the clean image is treated as pseudo ground truth to optimize the adversarial sample. Then the DFA loss between network's responses from a clean image and an attacked image is minimized. Stochastic Gradient Descent (SDG) \cite{sutskever2013importance} with learning rate $0.01$ and Adam \cite{kingma2014adam} with learning rate $0.001$, $\beta_1 = 0.9$, $\beta_2 = 0.999$ are used to optimize perturbation and patch, respectively, in PyTorch \cite{paszke2019pytorch}. \input{figs/feature/feature_layer_sfm} \subsection{Black-box Attack} In a black-box attack, the attacker has access to input and output but not to target network architecture and weights. The black-box attack is the most realistic attack, especially in safety-critical applications. These applications are designed in such a way that the attacker doesn't have direct access to the system. A global perturbation and patch learned from different models in the investigation are used for this attack. The global adversarial sample is optimized like a white-box attack. Even though adversarial samples are successful in attacking deep learning models with small perturbation or by corrupting few pixels, the transferability property of the adversarial samples makes it a severe threat. It has been shown that adversarial samples are cross-model transferable i.e., adversarial pertubation optimized to attack Model A can be used to attack Model B which deals with the same task. Let Model A be an open-sourced model trained to estimate per-pixel depth from an image, with the transferability property; an attacker can attack a closed Model B effectively using Model A's adversarial samples. In this study, we analyzed the transferability of the adversarial sample across all models under investigation. We also study cross-data transferability of the learned patch as shown in Figure~\ref{fig:cross_data}. Cross-data transferability examines how well an adversarial sampled can be optimized with a publicly available dataset A to attack a model on proprietary data. The adverisal patch learned from KITTI dataset was used to attack images from Cityscape~\cite{cordts2016cityscapes}, considering KITTI as open source data and cityscape as proprietary data. This transferability assures that publicly available data can be used to attack almost any related models. \subsection{Evaluation} The qualitative evalution of the attacks are conducted using metrics in \cite{eigen2014depth} with KITTI 2015 dataset \cite{geiger2013vision}. Root mean square error (RMSE) along with relative degradation (Rel) of RMSE are used to measure the vulnerability of the depth networks (Absolute relative error metric in supplementary material). As shown in Table~\ref{tab:whitebox_patch_rmse} and Table~\ref{tab:whitebox_gpert_rmse}, its evident that all state-of-the-art models are vulnerable to adversarial samples in whitebox attacks. Our adversarial perturbation could attack all models very well and in few networks like DDVO and Mono2 just 5\% of corruption could cause more than 100\% damage to the depth maps. We can also see that corrupting less than even 1\% of the image using the adversarial patch can cause more than 20\% damage in the estimated depth map and also the damage extends significantly beyond the region of the patch thus making it a very dangerous real world attack. The qualitative result in Table~\ref{tab:trans_pert_rmse} and Table~\ref{tab:trans_patch_rmse} assure successful black-box attack on all state-of-the-art monocular depth estimation networks. \subsection{Analyze Deep Features} Unlike most adversarial attacks, in this investigation, we corrupt the network's internal representation of an input image with our perturbation. In our experiment, striking the final layer alone didn't affect the prediction drastically for monocular depth estimation. The adversarial samples generated from existing methods still preserve a high level of input information in its deep hidden layers. These extracted features obstruct the desired attack in the model. To counter this issue, we targeted deep features representation of the input image to generate adversarial noise. We visualized deep features of attacked and clean image in Figure~\ref{fig:feat_lvis_sfm}. For better visualization, feature outputs of zero image are taken as a clean image, and perturbation added to zero image is considered as an attacked image. It shows how each network layer reacts to the clean image and how the decoder layers react to an attacked image and exhibit an activation inversion property. From the visualization we can see that suppressed and non-dominant activations are exaggerated while dominant activations are weakened thus justifying our earlier claim. DFA makes the internal feature representation hollow and thereby creating a more robust attack on the final prediction of the network. \section{Conclusion} In this paper, we proposed an effective adversarial attack on monocular depth estimators. We explored both perturbation and patch type attacks in this study. The adversarial samples are designed with DFA loss to destroy the internal representation of the network, thereby resulting in a more vigorous attack. The attacks are evaluated extensively with white-box and black-box testing on KITTI dataset. The deep features of the network are visualized for a better understanding of the proposed attack. Also, cross-data transferability of the attack is examined.
{'timestamp': '2020-06-01T02:03:39', 'yymm': '2005', 'arxiv_id': '2005.14302', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14302'}
arxiv
\section{Introduction} Bayesian uncertainty quantification is useful for calibrating physical models to observed data. As well as inferring the parameters that produce the best fit between a model and observed data, Bayesian methods can also identify the range of parameters that are consistent with observations and allow for prior beliefs to be incorporated into inferences. This means that not only can predictions be made but also their uncertainty can be quantified. In demography, Bayesian analysis is used to forecast the global population \citep{gerland2014world}. In defence systems, Bayesian analysis is used to track objects from radar signals \citep{arulampalam2002tutorial}. And in computational neuroscience Bayesian analysis is used to compare different models of brain connectivity and to estimate physiological parameters in mechanistic models \citep{kiebel2008dynamic}. Many more examples can be found in the references of \citep{bishop2006pattern,gelman2013bayesian,lunn2012bugs}. We focus here on problems which require the use of Markov Chain Monte Carlo (MCMC), a widely applicable methodology for generating samples approximately drawn from the posterior distribution of model parameters given observed data. MCMC is useful for problems where a parametric closed form solution for the posterior distribution cannot be found. MCMC became popular in the statistical community with the re-discovery of Gibbs sampling \citep{smith1993bayesian}, and the development of the BUGS software \citep{lunn2012bugs}. More recently it has been found that methods which use derivatives of the posterior distribution with respect to model parameters, such as the Metropolis Adjusted Langevin Algorithm (MALA) and Hamiltonian Monte Carlo (HMC) tend to generate samples more efficiently than methods which do not require derivatives \citep{hoffman2014no}. HMC is used in the popular Stan software \citep{carpenter2017stan}. From the perspective of a C++ programmer, the limitations of Stan are as follows: it may take a significant investment of effort to get started. Either the C++ code has to be translated into the Stan modelling language. Or, alternatively, C++ code can be called from Stan, but it may be challenging to (efficiently) obtain the derivatives that Stan needs in order to sample efficiently. The software that we present includes (i) our own implementation of a derivative-based MCMC sampler called simplified manifold MALA (smMALA). This sampler can be easily be used in conjunction with C++ codes for Bayesian data analysis, (ii) Stan's MCMC sampler with derivatives computed using \dcocpp{}, an industrial standard tool for efficient derivative computation. An alternative approach to the one presented in this paper would be simply to use Stan as a stand-alone tool without the smMALA sampler and without \dcocpp{}. Determining the most efficient MCMC sampler for a given problem is still an active area of research, but at least within computational neuroscience, it has been found the smMALA performs better than HMC methods on certain problems \citep{sengupta2016gradient}. Determining the most appropriate method for computing derivatives will depend on both the user and the problem at hand. In many applications Algorithmic Differentiation (AD) is needed for the reasons given in Section \ref{sec:deriv}. The Stan Math Library includes an open-source AD tool. Commercial AD tools such as \dcocpp{} offer a richer set of features than open-source tools, and these features may be needed in order to optimize derivative computations. For example, the computations done using the Eigen linear algebra library \citep{eigenweb} can be differentiated either using the Stan Math Library or using \dcocpp{} but there are cases where \dcocpp{} computes derivatives more efficiently than the Stan Math Library \citep{peltzer2019eigen}. The aim of the software we present is to offer a range of options that both make it easy to get started and to tune performance. \section{Methods for spectral time-series analysis} \pagestyle{main} \subsection{Whittle likelihood} The software presented in this paper is targeted at differential equation models with a stable equilibrium point and stochastic input. We refer to such models as stable SDEs. The methods that are implemented assume that the system is operating in a regime where we can approximate the dynamics through linearization around the stable fixed point. If the time-series data is stationary this is a reasonable assumption. Note that the underlying model may be capable of operating in nonlinear regimes such as limit cycles or chaos in addition to approximately linear dynamics. However, parameter estimation using data in nonlinear regimes quickly becomes intractable - see Chapter 2 of \citep{maybank2019bayesian}. The stability and linearity assumptions are commonly made in the computational neuroscience literature, see for example \citep{moran2009dynamic}. In order to simplify the presentation we illustrate the software using a linear state-space model, which is of the form, \begin{equation} \label{eq:de} d\mathbf{X}(t) = A\, \mathbf{X}(t)dt + \mathbf{P}(t), \end{equation} \noindent where the term $A\, \mathbf{X}(t)$ represents the deterministic evolution of the system and $\mathbf{P}(t)$ represents the noisy input. The example we analyze in this paper is the noise-driven harmonic oscillator, which is a linear state-space model with \begin{equation} A = \begin{pmatrix} 0 & 1 \\ -\omega_0^2 & -2 \zeta \omega_0 \end{pmatrix}, \quad \mathbf{P}(t) = \begin{pmatrix} 0 \\ dW(t) \end{pmatrix}, \end{equation} \noindent and where $dW(t)$ represents a white noise process with variance $\sigma_{in}^2$. The observations are modelled as $Y_k = X_0(k\cdot \Delta t) + \epsilon_k$ with $\epsilon_k \sim N(0, \sigma_{obs}^2)$. Our aim is to infer model parameters ($\omega_0, \zeta, \sigma_{in}$) from time-series data. This could be done in the time-domain using a Kalman filter, but it is often more computationally efficient to do inference in the frequency domain \citep{bojak2005modeling,maybank2017fast}. In the case where we only have a single output (indexed by $i$) and a single input (indexed by $j$), we can compute a likelihood of the parameters $\theta$ in the frequency domain through the following steps. \begin{enumerate} \item Compute the (left and right) eigendecomposition of $A$, such that, \begin{equation} A \mathcal{R} = \Lambda \mathcal{R}, \quad \mathcal{L} A = \mathcal{L} \Lambda, \quad \mathcal{L} \mathcal{R} = \mathrm{diag}(c) \\ \end{equation} where $\mathrm{diag}(c)$ is a diagonal matrix, such that $c_i$ is the dot product of the $i$th left eigenvector with the $i$th right eigenvector. \item Compute $ij$th element of the transfer matrix for frequencies $\omega_1,\ldots,\omega_K$, \begin{equation} \label{eq:transfer} \mathcal{T}(\omega) = \mathcal{R}\ \mathrm{diag}\bigg[ \frac{1}{c_k (i\omega - \lambda_k)} \bigg]\ \mathcal{L}. \end{equation} \item Evaluate the spectral density for component $i$ of $\mathbf{X}(t)$, $f_{X_i}(\omega)$, and the spectral density for the observed time-series, $f_{Y}(\omega)$, \begin{align} \label{eq:spec_eq} f_{X_i}(\omega) &= |\mathcal{T}_{ij}(\omega)|^2\ f_{P_j}(\omega), \\ f_{Y}(\omega) &= f_{X_i}(\omega) + \sigma_{obs}^2 \Delta t, \end{align} \noindent where $f_{P_j}(\omega)$ is the spectral density for component $j$ of $\mathbf{P}(t)$. \item Evaluate the Whittle likelihood, \begin{equation} \label{eq:whittle} p(y_0,\ldots,y_{n-1}|\theta) = p(S_0,\ldots,S_{n-1}|\theta) \approx \prod_{k=1}^{n/2-1} \frac{1}{f_Y(\omega_k)} \exp\left[-\frac{S_k}{f_Y(\omega_k)}\right], \end{equation} where $\{S_k\}$ is the Discrete Fourier Transform of $\{y_k\}$. Note that $\theta$ represents a parameter set (e.g. specific values of $\omega_0, \zeta, \sigma_{in}$) that determines the spectral density. \end{enumerate} The matrix $A$ that parameterizes a linear state-space model is typically non-symmetric, which means that eigenvectors and eigenvalues will be complex-valued. We use Eigen-AD \citep{peltzer2019eigen}, a fork of the \cpp{} linear algebra library Eigen \citep{eigenweb}. Eigen is templated which facilitates the application of AD by overloading tools and Eigen-AD provides further optimizations for such tools. The operations above require an AD tool that supports differentiation of complex variables. AD of complex variables is considered in \citep{pusch1995ad}. It is available from release 3.2.0 of the Stan Math Library and in \dcocpp{} from release 3.4.3. \subsection{Markov Chain Monte Carlo} \label{sec:mcmc} In the context of Bayesian uncertainty quantification, we are interested in generating samples from the following probability distribution, \begin{equation} \label{eq:bayes} p(\theta|y) \propto p(y|\theta) p(\theta), \end{equation} \noindent where $p(y|\theta)$ is the likelihood of the parameter set $\theta$ given observed data $y_0,\ldots,\allowbreak y_{n-1}$, and $p(\theta)$ is the prior distribution of the parameters. In many applications the likelihood $p(y|\theta)$ is based on some physical model where we cannot derive a closed form expression for the posterior density $p(\theta|y)$. Markov Chain Monte Carlo (MCMC) has emerged over the last 30 years as one of the most generally applicable and widely used framework for generating samples from the posterior distribution \citep{gelman2013bayesian,green2015bayesian}. The software used in this paper makes use of two MCMC algorithms: the No U-Turn Sampler (NUTS) \citep{hoffman2014no} and the simplified manifold Metropolis Adjusted Langevin Algorithm (smMALA) \citep{girolami2011riemann}. NUTS is called via the Stan environment \citep{carpenter2017stan}. It is a variant of Hamiltonian Monte Carlo (HMC), which uses the gradient (first derivative) of the posterior density, whereas smMALA uses the gradient and Hessian (first and second derivatives) of the posterior density, smMALA is described in Algorithm \ref{alg:smmala}. The error in estimates obtained from MCMC is approximately $C / \sqrt{N}$, where $N$ is the number of MCMC iterations and $C$ is some problem-dependent constant. In general it is not possible to demonstrate that MCMC has converged, but there are several diagnostics that can indicate non-convergence, see Section 11.4 of \citep{gelman2013bayesian} for more detail. Briefly, there are two phases of MCMC sampling: burn-in and the stationary phase. Burn-in is finished when we are in the region of the parameter space containing the true parameters. In this paper we restrict ourselves to synthetic data examples. In this case it is straight-forward to assess whether the sampler is burnt in by checking whether the true parameters used to simulate the data are contained in the credible intervals obtained from the generated samples. In real data applications, it is good practice to test MCMC sampling on a synthetic data problem that is analogous to the real data problem. During the stationary phase we assess convergence rate using the effective sample size, \textit{N Eff}. If we were able to generate independent samples from the posterior then the constant $C$ is $\mathcal{O}(1)$. MCMC methods generate correlated samples, in which case $C$ may be $\gg 1$. A small \textit{N Eff} (relative to $N$) is an indicator of slow convergence. If we are sampling from a multivariate target distribution, \textit{N Eff} for the $i$th component is equal to, \begin{equation} \frac{S}{1 + 2 \sum_k \hat{\rho}_i(k)}, \end{equation} \noindent where $S$ is the number of samples obtained during the stationary period, and $\hat{\rho}_i(k)$, is an estimate of the autocorrelation at lag $k$ for the $i$th component of the samples. This expression can be derived from writing down the variance of the average of a correlated sequence (Chapter 11 of \citep{gelman2013bayesian}). The key point to note is that if the autocorrelation decays slowly \textit{N Eff} will be relatively small. \begin{algorithm}[ht] \KwIn{Data, $y$; Initial value for $\theta = (\theta_1,\ldots,\theta_N)$; \newline Likelihood $l(y|\theta)$; Prior distribution $p(\theta)$.} \Parameter{Step size, $h$; Number of iterations, $I$} \For{$i = 2,\ldots,I$ }{ Evaluate gradient and Hessian of the unnormalized log posterior,\newline \Indp $g_{\theta} = \nabla \bigg[\log[ \ l(y|\theta)\ p(\theta) \ ] \bigg]$ and $\mathbf{H}_{\theta}$\; Set $C = h^2 \mathbf{H}_{\theta}^{-1}$, and $m = \theta + \frac{1}{2} C\, g_{\theta}$\; Propose $\theta^* \sim q(\theta^*|\theta)=N(m, C)$\; Evaluate acceptance ratio, $\alpha(\theta, \theta^*) = \mathrm{min}\left[1, \dfrac{l(y|\theta^*) p(\theta^*) q(\theta|\theta^*) }{l(y|\theta) p(\theta) q(\theta^*|\theta)} \right]$\; Draw $u \sim \mathrm{Uniform}(0,1)$\; \lIf{$u < \alpha(\theta, \theta^*)$}{Set $\theta = \theta^*$ } } \caption{smMALA}\label{alg:smmala} \end{algorithm} \subsection{Derivative computation} \label{sec:deriv} A central finite difference approximation to the first and second derivatives of the function $F(\theta): \mathbb{R}^N \rightarrow \mathbb{R}^M$ can be computed as, \begin{equation} \label{eq:d1} \frac{\partial F}{\partial \theta_i} \approx \frac{F(\theta+h e_i) - F(\theta-h e_i)}{2 h}, \qquad \frac{\partial^2 F}{\partial \theta_i \partial \theta_j} \approx \frac{\dfrac{\partial F}{\partial \theta_i}\big(\theta + h e_j\big) - \dfrac{\partial F}{\partial \theta_i}\big(\theta-h e_i\big)}{2 h}, \nonumber \end{equation} \noindent where $e_i$ is the $i$th Cartesian basis vector, and $h$ is a user-defined step-size. For first-order derivatives the default value we use is $\sqrt{\epsilon}|\theta_i|$, where $\epsilon$ is machine epsilon for double types, i.e., if $\theta_i$is $\mathcal{O}(1)$, $h\approx10^{-8}$. For second derivatives the default value is $\epsilon^{1/3}|\theta_i|$, so that $h\approx 5\cdot 10^{-6}$. More details on the optimal step size in finite difference approximations can be found in \citep{nagblog-fd}. First derivatives computed using finite differences require $\mathcal{O}(N)$ function evaluations, where $N$ is the number of input variables, and the optimal relative accuracy is around $10^{-6}-10^{-8}$ for double precision variables. Second derivatives require $\mathcal{O}(N^2)$ function evaluations, and the optimal accuracy is around $10^{-2}-10^{-4}$. Derivatives that are accurate to machine precision ($10^{-14}-10^{-16}$ for double precision variables) can be computed using AD tools. AD tools generally use one of two modes: tangent (forward) or adjoint (reverse). For a function with $N$ inputs and $M$ outputs, tangent mode requires $\mathcal{O}(N)$ function evaluations and adjoint mode requires $\mathcal{O}(M)$ function evaluations. In statistical applications our output is often a scalar probability density, so adjoint AD will scale better with $N$ than either tangent mode or finite differences in terms of total computation time. Adjoint AD is implemented as follows using the Stan Math Library, \citep{carpenter2015stan}. \begin{verbatim} // Define and init matrix with Stan's adjoint type Matrix<stan::math::var,Dynamic,1> theta = input_values; // Compute primal and gradient stan::math::var lp = computation(theta); lp.grad(); // Extract gradient Matrix<double,Dynamic,1> grad_vec(theta.size()); for(int j=0; j<theta.size(); j++) grad_vec(j) = theta(j).adj(); \end{verbatim} In the code above the function is evaluated using the \texttt{stan::math:var} scalar type rather than \texttt{double}. During function evaluation, derivative information is recorded. When the \texttt{grad()} function is called this derivative information is interpreted and derivative information is then accessed by calling \texttt{adj()} on the input variables. Similarly to the Stan Math Library, derivatives with machine-precision accuracy can be computed using the NAG \dcocpp{} tool developed in collaborations with RWTH Aachen University's STCE group, \citep{AIB-2016-08}. \begin{verbatim} // Define and init matrix with dco's adjoint type typedef dco::ga1s<double> DCO_MODE; typedef DCO_MODE::type Scalar; Matrix<Scalar,Dynamic,1> theta = input_values; // Enable dynamic activity analysis for(int j=0; j<theta.size(); j++) DCO_MODE::global_tape->register_variable(theta(j)); // Compute primal and gradient Scalar lp = computation(theta); dco::derivative(lp) = 1.0; DCO_MODE::global_tape->interpret_adjoint(); // Extract gradient Matrix<double,Dynamic,1> grad_vec(theta.size()); for(int j=0; j<theta.size(); j++) grad_vec(j) = dco::derivative(theta(j)); \end{verbatim} \dcocpp{} provides its adjoint type using the \texttt{dco::ga1s<T>::type} typedef, where \texttt{T} is the corresponding primal type (e.g.\ \texttt{double}). Higher order adjoints can be achieved by recursively nesting the adjoint type. Using this type, the program is first executed in the augmented forward run, where derivative information is stored in the \texttt{global\_tape} data structure. The \texttt{register\_variable} function initialises recording of the tape and facilitates dynamic varied analysis~\citep{hascoet2005tbr}. Derivative information recorded during the augmented primal run is then interpreted using the \texttt{interpret\_adjoint()} function and \texttt{dco::derivative} is used to access the propagated adjoints. \section{Results for noise driven harmonic oscillator} We now present the results of MCMC sampling using smMALA to estimate parameters of the noise driven harmonic oscillator. Then we demonstrate that, for this particular model, MCMC sampling can be accelerated by using NUTS. We also compare run times and sampling efficiency when AD is used to evaluate derivatives. Here we estimate parameters using synthetic data (i.e. data generated from the model). This is a useful check that the MCMC sampler is working correctly: we should be able to recover the parameters that were used to simulate the data. We generate a pair of datasets representing different conditions (which we label $c_1$ and $c_2$). We assume that the $\omega_0$ and $\sigma_{in}$ parameters vary across conditions, but that $\zeta$ is fixed across conditions, and that $\sigma_{obs}=0.05$ (i.e. it is known and does not need to be sampled). In Table \ref{fig:ho_mcmc_spec} we show that the $95\%$ credible intervals for each parameter include the actual parameter values for all 5 parameters. These results came from one MCMC run of $10,000$ iterations using the Whittle likelihood and a uniform prior. The step size parameter, $h$, was set to $1.0$. There were no burn-in iterations as the sampler was initialized at the true parameter values. Figure \ref{fig:ho_mcmc_spec} shows $95\%$ confidence intervals for the spectral density obtained using the Welch method alongside $95\%$ credible intervals for the spectral density estimated from $10,000$ MCMC iterations. This is another useful check: the spectral density predictions generated by sampled parameter sets are consistent with non-parametric estimates of the spectral density. \begin{figure} \centering \hspace{-2.2cm} \begin{minipage}[b]{0.60\linewidth} \centering \includegraphics[width=1.05\linewidth]{harmonic_oscillator_spec_dens_est} \end{minipage \begin{minipage}[b]{0.30\linewidth} \centering \begin{tabular}[b]{|c||c|c|c|c|} \hline \multirow{2}{*} & \multirow{2}{*}{Actual} & \multicolumn{3}{c|}{Quantile} \\ \hhline{|~||~|-|-|-|} & & 0.025 & 0.50 & 0.975 \\ \hhline{|=||=|=|=|=|} $\omega_0(c_1)$ & 80 & 78.3 & 80.0 & 82.1 \\ \hline $\omega_0(c_2)$ & 40 & 37.4 & 38.9 & 40.4 \\ \hline $\sigma_{in}(c_1)$ & 100 & 94.0 & 101 & 109 \\ \hline $\sigma_{in}(c_2)$ & 10 & 9.53 & 10.6 & 11.7 \\ \hline $\zeta$ & 0.2 & 0.17 & 0.19 & 0.22 \\ \hline \end{tabular} \vspace{1.5cm} \end{minipage} \caption{Spectral density and posterior parameter estimates for noise driven harmonic oscillator. Synthetic data was generated by simulating from the model: duration = 20.0, time-step = 0.01. Two datasets ($c_1$ and $c_2$) were generated with different parameter values for $\omega_0$ and $\sigma_{in}$ in each dataset (values are given in `actual' column). The quantiles are estimated from a sequence of $10,000$ MCMC samples from the joint (posterior) distribution of all the parameters given all of the data. For example, 2.5\% of the MCMC samples had $\omega_0(c_1)$ values less than 78.3.} \label{fig:ho_mcmc_spec} \end{figure} Table \ref{tab:bench} uses the same model and the same datasets as above to compare smMALA with NUTS, and finite differences with AD. The AD implementation used in smMALA was dco's tangent over adjoint mode (i.e. \texttt{dco::gt1s} combined with \texttt{dco::ga1s}). In NUTS we used the dco's tangent mode for computing the derivatives of the spectral density and Stan's adjoint mode (\texttt{stan::math::var}) for the rest of the computation. Given the most recent developments in the Stan Math Library (see release notes for v3.2.0) it would likely be possible to use Stan's adjoint mode for the whole computation. However this was not the case when we started writing the code. In general users may find that they need the more advanced functionality of \dcocpp{} for part of their computation in order to obtain good performance. The MCMC samplers were each run for 1,000 iterations. The results were analyzed using Stan's \texttt{stansummary} command-line tool. To account for correlation between MCMC samples we use the \textit{N Eff} diagnostic defined in Section \ref{sec:mcmc} to measure sampling efficiency, min \textit{N Eff} is the minimum over the 5 model parameters. Table \ref{tab:bench} shows that, for the noise driven harmonic oscillator, we can accelerate MCMC sampling by a factor of around 3-4 through the combined effect of more efficient MCMC sampling (NUTS rather than smMALA) and more accurate derivative evaluations (AD rather than finite differences). In some cases the \textit{N Eff / s} is higher for finite differences than for AD, because of the small number of input variables. However, even for this simple model the NUTS min \textit{N Eff} is higher with AD than with central finite differences suggesting that the extra accuracy in the derivatives results in more efficient sampling per MCMC iteration. In the context of Bayesian uncertainty quantification what we are interested in is whether the MCMC samples are an accurate representation of the true posterior distribution. A necessary condition for posterior accuracy is that the true parameters are (on average) contained in the credible intervals derived from the MCMC samples. This is the case for all the different variants of MCMC that we tested. The main differences we found between the different variants was the sampling efficiency. As discussed in Section \ref{sec:mcmc}, a sampling efficiency that is $3-4$ time greater means a reduction in the value of $C$ in the Monte Carlo error ($C / \sqrt{N}$) by that factor. Another way of interpreting this is that we could reduce the number of MCMC iterations by a factor of $3-4$ and expect to obtain the same level of accuracy in the estimated posterior distribution. \begin{table}[!htb] \caption{Noise-driven harmonic oscillator benchmarking results on Intel 2.50GHz CPU, Ubuntu (18.04) Linux.} \begin{tabular}{|l|l|l|l|l|} \hline MCMC sampler & Derivative implementation & CPU time (s) & min \textit{N Eff} & min \textit{N Eff} / s \\ \hline smMALA & Finite differences & 6.2 & 150 & 24 \\ smMALA & \dcocpp & 8.2 & 150 & 18 \\ NUTS & Finite differences & 8.5 & 384 & 46 \\ NUTS & Stan and \dcocpp & 6.0 & 503 & 84 \\ \hline \end{tabular} \label{tab:bench} \end{table} \section{Discussion} The Whittle likelihood function is written to be polymorphic over classes derived from the a base class called \texttt{Stable\_sde}. The function signature includes a reference to the base class. \begin{verbatim} template<typename SCALAR_T> SCALAR_T log_whittle_like(Stable_sde<SCALAR_T> & m, ...); \end{verbatim} Classes that are derived from the \texttt{Stable\_sde} base class must define the following pure virtual function. \begin{verbatim} virtual Matrix<SCALAR_T, Dynamic, Dynamic> sde_jacobian(...) = 0; \end{verbatim} The spectral density evaluation (Equation \eqref{eq:spec_eq}) is implemented in the base class, reducing the effort required to do spectral data analysis for other stable SDEs. The smMALA sampler is written to be polymorphic over classes derived from a base class called \texttt{Computation}. Classes that are derived from the \texttt{Computation} base class must define the following pure virtual function. \begin{verbatim} virtual SCALAR_T eval(Matrix<SCALAR_T,Dynamic,1>& theta,...) = 0; \end{verbatim} This function should evaluate the posterior density in the user's model. The gradient and Hessian of the posterior density are implemented in the \texttt{Compu\-tation} class. This reduces the effort required to use NUTS or smMALA for other computational models. Classes derived from \texttt{Stable\_sde} or from \texttt{Computation} can be instantiated with several different scalar types including \texttt{double}, \texttt{stan\allowbreak::math\allowbreak::var}, and a number of \dcocpp{} types. This enables automatic evaluation of first and second derivatives. The gradient and Hessian functions need a template specialization to be defined in the base class for each different scalar type that is instantiated. We conclude with some comments regarding the choice of MCMC sampler and the method for evaluating derivatives. Our software only implements derivative-based MCMC as this tends to be more computationally efficient than other MCMC methods \citep{hoffman2014no,penny2016annealed}. Derivative-based MCMC samplers can be further subdivided into methods that use higher-order derivatives, such as smMALA (sometimes referred to as Riemannian) and methods that only require first-order derivatives (such as NUTS). Riemannian methods tend to be more robust to complexity in the posterior distribution, but first-order methods tend to be more computationally efficient for problems where the posterior geometry is relatively simple. We recommend using smMALA in the first instance, then NUTS as a method that may provide acceleration in MCMC sampling, in terms of effective samples per second, \textit{N Eff /s}. Regarding the derivative method, finite difference methods often result in adequate performance for problems with moderate input dimension (e.g. 10-20), at least with smMALA. But for higher-dimensional problems (e.g. Partial Differential Equations or Monte Carlo simulation) we recommend accelerating derivative computation using adjoint AD \citep{nagsite-ad,naumann2018adjoint}. The software presented enables users to implement and benchmark all these alternatives so that the most appropriate methods for a given problem can be chosen. \bibliographystyle{apalike}
{'timestamp': '2020-08-04T02:33:06', 'yymm': '2005', 'arxiv_id': '2005.14281', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14281'}
arxiv
\section{Introduction} \vspace{-0.15in} \begin{figure} \centering \includegraphics[height=5.5cm,width=0.9\linewidth]{FIG/new_intro32.pdf} \caption{Starting from 32M GitHub\xspace repositories, we find 7.5K malware source code repositories using 137 malware keywords (Q137).} \label{fig:intro} \end{figure} Security research could greatly benefit by an extensive database of malware source code, which is currently unavailable. This is the assertion that motivates this work. First, security researchers can use malware source code to: (a) understand malware behavior and techniques, and (b) evaluate security methods and tools~\cite{darki2019idapro,jerkins2017motivating}. In the latter, having the source code can provide the groundtruth for assessing the effectiveness of different techniques, such as reverse engineering methods\cite{healey2019source, schulte2018evolving,chen11novel} and anti-virus methods. Second, currently, a malware {\bf source code} database is not readily available. By contrast, there are several databases with malware {\bf binary code}, as collected via honeypots, but even those are often limited in number and not widely available. We discuss existing malware archives in Section~\ref{sec:related}. {\bf A missed opportunity:} Surprisingly, software archives, like GitHub\xspace, host many publicly-accessible malware repositories, but this has not yet been explored to provide security researchers with malware source code for their studies. In this work, we focus on GitHub\xspace which is arguably the largest software storing and sharing platform. As of October 2019, GitHub\xspace reports more than 34 million users \cite{git:user} and more than 32 million public repositories~\cite{git:pub-repo}. As we will see later, there are thousands of repositories that have malware source code, which seem to have escaped the radar of the research community so far. Why do authors create public malware repositories? This question mystified us: these repositories expose both the creators and the intelligence behind the malware. Intrigued, we conducted a small investigation on malware authors, as we discuss below. {\bf Problem:} How can we find malware source code repositories in a large archive, like GitHub\xspace? The input to the problem is an online archive and the desired output is a database of malware repositories. The challenges include: (a) collecting an appropriate set of repositories from the potentially vast archive, (b) identifying the repositories that contain malware. Optionally, we also want to further help researchers that will potentially use these repositories, by determining additional properties, such as the most likely target platform, the malware type or family etc. Another practical challenge is the need to create the ground truth for validation purposes. {\bf Related work:} To the best of our knowledge, there does not seem to be any studies focusing on the problem above. We group related works in the following categories. First, several studies analyze software repositories to find usage and limitations without any focus on malware~\cite{cosentino2016findings}. Second, several efforts maintain databases of malware binaries but without source code~\cite{allix2016androzoo,arp2014drebin}. Third, many efforts attempt to extract higher-level information from binaries, such as lifting to Intermediate Representation(IR)~\cite{vdurfina2011design}, but it is really difficult to re-create the source code~\cite{chen2013refined}. In fact, such studies would benefit from our malware source-code archive to evaluate and improve their methods. Taking a software engineering angle, an interesting work~\cite{calleja2016look} compares the evolution of 150 malware source code repositories with that of benign software. We discuss related works in Section~\ref{sec:related}. {\bf Contributions:} Our work is arguably the first to systematically identify malware source code repositories from a massive public archive. The contribution of this work is three-fold: (a) we propose SourceFinder\xspace, a systematic approach to identify malware source-code repositories with high precision, (b) we create, arguably, the largest non-commercial malware source code archive with \sourceNum repositories, and (c) we study patterns and trends of the repository ecosystem including temporal and author-centric properties and behaviors. We apply and evaluate our method on the GitHub\xspace archive, though it could also be used on other archives, as we discuss in Section~\ref{sec:discussion}. Our key results can be summarized in the following points, and some key numbers are shown in Figure~\ref{fig:intro}. a. We collect {\bf \totalrepo malware-related repositories} from GitHub\xspace. In the collection, we overcome various practical limitations, and we also generate an extensive groundtruth with 2013 repositories, as we explain in Section~\ref{sub-sec:data-collection}. b. {\bf SourceFinder\xspace achieves \precision precision.} We systematically consider different Machine Learning approaches, and carefully-created representations for the different fields of the repository, such as title, description etc. We then systematically evaluate the effect of the different features, as we discuss in Section~\ref{sec:result}. We show that we classify malware repositories with a \precision precision, \recall recall and \fOne F1-score using five fields from the repository. c. {\bf We identify \sourceNum malware source-code repositories}, which is arguably the largest malware source-code database in the research community. We have already downloaded the contents in these repositories, in case GitHub\xspace decides to deactivate them. We also created a curated database of 250 malware repositories manually verified and spanning a wide range of malware types. Naturally, we intend to make our datasets available for research purposes. d. {\bf The number of new malware repositories in our data more than triples every four years}. The increasing trend is interesting and alarming at the same time. e. {\bf We identify popular and influential repositories.} We identify the malware repositories using three metrics of popularity: the number of watchers, forks and stars. We find 8 repositories that dominate the top-5 lists of all three metrics. f. {\bf We identify prolific and influential authors.} We find that 3\% of the authors have more than 300 followers. We also find that 0.2\% of the authors have more than 7 malware repositories, with the most prolific author {\em cyberthreats} having created 336 repositories. g. {\bf We identify and profile 18\xspace professional hackers.} We find 18\xspace authors of malware repositories, who seem to have created a brand around their activities, as they use the same user names in security forums. For example, user {\em 3vilp4wn} (pronounced evil-pawn) is the author of a keylogger malware in GitHub\xspace, which the author is promoting in the {\em Hack This Site} forum using the same username. We present our study of malware authors in Section~\ref{sec:authors}. {\bf Open-sourcing for maximal impact: creating an engaged community.} We intend to make our datasets and our tools available for research purposes. Our vision is to create community-driven reference center, which will provide: (a) malware source code repositories, (b) community-vetted labels and feedback, and (c) open-source tools for collecting and analyzing malware repositories. Our goal is to expand our database with more software archives. Although authors could start hiding their repositories (see Section~\ref{sec:discussion}), we argue that our already-retrieved database could have significant impact in enabling certain types of research studies. \section{Background} \label{backround-data} \label{sub-sec:background} \vspace{-0.15in} We provide background information on GitHub\xspace and the type of information that repositories have. GitHub\xspace is a massive world-wide software archive, which enables users to share code through its public repositories thus creating a global social network of interaction. For instance, first, users can collaborate on a repository. Second, users often "fork" projects: they copy and evolve projects. Third, users can follow projects, and "up-vote" projects using "stars" (think Facebook likes). Although GitHub\xspace has many private repositories, there are 32 million public software repositories. We describe the key elements of a GitHub\xspace repository. A repository is equivalent to a project folder, and typically, each repository corresponds to a single software project. A repository in GitHub\xspace has the following data fields: a) title, b) description, c) topics, d) README file, e) file and folders, f) date of creation and last modified, g) forks, h) watchers, i) stars, and j) followers and followings, which we explain below. {\bf 1. Repository title: } The title is a mandatory field and it usually consists of less than 3 words. {\bf 2. Repository description: } This is an optional field that describes the objective of the project and it is usually 1-2 sentences long. {\bf 3. Repository topics: } An author can optionally provide topics for her repository, in the form of tags, for example, \textit{``linux, malware, malware-analysis, anti-virus"}. Note that 97\% of the repositories in our dataset have less than 8 topics. {\bf 4. README file: } As expected, the README file is a documentation and/or light manual for the repository. This field is optional and its size varies from one or two sentences to many paragraphs. For example, we found that 17.48\% of the README files in our repositories are empty. {\bf 5. File and folders: } In a well-constructed software, the file and folder names of the source code can provide useful information. For example, some malware repositories contain files or folders with indicative names, such as ``malware", ''source code" or even specific malware types or names of specific malware, like {\em mirai}. {\bf 6. Date of creation and last modification: } GitHub\xspace maintains the date of creation and last modification of a repository. We find malware repository created in 2008 are actively being modified by authors till present. 7. {\bf Number of forks:} Users can fork a public repository: they can create a clone of the project~\cite{jiang2017and}. An user can fork any public repository to change locally and contribute to the original project if the owner accepts the modification. The number of forks is an indication of the popularity and impact of a repository. Note that the number of forks indicates the number of distinct users that have forked a repository. {\bf 8. Number of watchers:} Watching a repository is equivalent to ``following" in the social media language. A ``watcher" will get notifications, if there is any new activity in that project. The numbers of watchers is an indication of the popularity of a repository~\cite{dabbish2012social}. {\bf 9. Number of stars: } A user can ``star" a repository, which is equivalent to the ``like" function in social media~\cite{begel2013social}, and places the repository in the users favorite group, but does not provide constant updates as with the ``watching" function. {\bf 10. Followers: } Users can also follow other users' work. If A follows B, A will be added to B's followers and B will be added to A's following list. The number of followers is an indication of the popularity of a user~\cite{lee2013github}. \section{Data Collection} \label{sub-sec:data-collection} \vspace{-0.15in} \begin{table \centering \small \begin{tabular} {|p{0.1\linewidth}|p{0.65\linewidth}|r|} \hline {\bf Set} & {\bf Descriptions} & {\bf Size} \\ \hline Q1 & Query set = \{"malware"\} & 1 \\ \hline Q50 & Query with 50 keywords with Q1$\subset$Q50 & 50 \\ \hline Q137 & Query with 137 keywords with Q50$\subset$Q137 & 137\\ \hline \hline \hline RD1 & Retrieved repositories from query Q1 & 2775 \\ \hline RD50 & Retrieved repositories from query Q50 & 14332 \\ \hline RD137 & Retrieved repositories from query Q137 & 97375 \\ \hline \hline \hline LD1 & Labeled subset of RD1 dataset & 379 \\ \hline LD50 & Labeled subset of RD50 dataset & 755 \\ \hline LD137 & Labeled subset of RD137 dataset & 879 \\ \hline \hline \hline M1 & Malware source code repositories in RD1 & 680 \\ \hline M50 & Malware source code repositories in RD50 & 3096 \\ \hline M137 & Malware source code repositories in RD137 & 7504 \\ \hline \hline \hline \curDataSet & Manually verified malware source code dataset & 250 \\ \hline \end{tabular} \caption{Datasets, their relationships, and their size.} \label{tab:my_label} \end{table} The first step in our work is to collect repositories from GitHub\xspace that have a higher chance of being related to malware. Extracting repositories at scale from GitHub\xspace hides several subtleties and challenges, which we discuss below. Using the GitHub\xspace Search API, a user can query with a set of keywords and obtain the most relevant repositories. We describe briefly how we select appropriate keywords, retrieve related repositories from GitHub\xspace and how we establish our ground truth. {\bf A. Selecting keywords for querying: } In this step, we want to retrieve repositories from GitHub\xspace in a way that: (a) provides as many as possible malware repositories, and (b) provides a wide coverage over different types of malware. For this reason, we select keywords from three categories: (a) malware and security related keywords, such as malware and virus, (b) malware type names, such as ransomware and keylogger, and (c) popular malware names, such as mirai. Due to space limitations, we will provide the full list of keywords in our website at publication time for repeatability purposes. We define three sets of keywords that we use to query GitHub\xspace. The reason is that we want to assess the sensitivity of the number of keywords on the outcome. Specifically, we use the following query sets: (a) the {\bf Q1 set}, which only contains the keyword ``malware"; (b) the {\bf Q50 set}, which contains 50 keywords, and (c) the {\bf Q137 set} which contains 137 keywords. The Q137 keyword set is a super-set of Q50, and Q50 is a superset of Q1. As we will see below, using the query set Q137 provides wider coverage, and we recommend in practice. We use the other two to assess the sensitivity of the results in the initial set of keywords. We list our datasets in Table~\ref{tab:my_label}. {\bf B. Retrieving related repositories:} Using the Search API, we query GitHub\xspace with our set of keywords. Specifically, we query GitHub\xspace with every keyword in our set separately. In an ideal world, this would have been enough to collect all related repositories: a query with ``malware" (Q1) should return the many thousands related repositories, but this is not the case. The search capability hides several subtleties and limitations. First, there is a limit of 1000 repositories that a single search can return: we get the top 1000 repositories ordered by relevancy to the query. Second, the GitHub API allows 30 requests per minute for an authenticated user and 10 requests per minute for an unauthenticated user. {\bf Bypassing the API limitations.} We were able to find a work around for the first limitation by using ranking option. Namely, a user can specify her preferred ranking order for the results based on: (a) best match, (b) most stars, (c) fewest stars, (d) most forks, (e) fewest forks, (f) most recently updated, and (g) the least recently updated order. By repeating a query with all these seven ranking options, we can maximize the number of distinct repositories that we get. This way, for each keyword in our set, we search with these seven different ranking preferences to obtain a list of GitHub\xspace repositories. {\bf C. Collecting the repositories:} We download all the repositories identified in our queries using PyGithub~\cite{PyGithub}, and we obtain three sets of repositories RD1, RD50 and RD137. These retrieved datasets have the same "subset" relationship that they query sets have: RD1 $\subset$ RD50 $\subset$ RD137. Note that we remove pathological repositories, mainly repositories with no actual content, or repositories "deleted" by GitHub\xspace. For each repository, we collect and store: (a) repository-specific information, (b) author-specific information, and (c) all the code within the repository. As we see from Table~\ref{tab:my_label}, using more and specialized malware keywords returns significantly more repositories. Namely, searching with the keyword ``malware" does return 2775 repositories, but searching with the Q50 and Q137 returns 14332 and 97375 repositories respectively. \begin{table} \centering \footnotesize \begin{tabular} {|p{0.28\linewidth}|p{0.28\linewidth}|p{0.28\linewidth}|} \hline {\bf Labeled Dataset} & {\bf Malware Repo.} & {\bf Benign Repo.} \\ \hline LD137 & 313 & 566 \\ \hline LD50 & 326 & 429 \\ \hline LD1 & 186 & 193 \\ \hline \end{tabular} \caption{Our groundtruth: labeled datasets for each of the three queries, for a total of 2013 repositories.} \label{tab:dat_def} \end{table} {\bf D. Establishing the groundtruth}: As there was no available groundtruth, we needed to establish our own. As this is a fairly technical task, we opted for domain experts instead of Mechanical Turk users, as recommended by recent studies~\cite{gharibshah2020rest}. We use three computer scientists to manually label 1000 repositories, which we selected in a uniformly random fashion, from each of our dataset RD137 and RD50 and 600 repositories from RD1. The judges were instructed to independently investigate every repository thoroughly. {\bf Ensuring the quality of the groundtruth.} To increase the reliability of our groundtruth, we took the following measures. First, we asked judges to label a repository {\em only}, if they were certain that it is malicious or benign and distinct, and leave it unlabeled otherwise. We only kept the repositories for which the judges agreed unanimously. Second, duplicate repositories were removed via manual inspection, and were excluded from the final labeled dataset to avoid overfitting. It is worth noting that we only found very few duplicates in the order of 3-5 in each dataset with hundreds of repositories. With this process, we establish three separate labeled datasets named LD137, LD50, and LD1 starting from the respective malware repositories from each of our queries, as shown in Table~\ref{tab:dat_def}. Although the labeled datasets are not 50-50, they are representing both classes reasonably well, so that a naive solution that will label everything as one class, would perform poorly. By contrast, our approach performs sufficiently well, as we will see in Section~\ref{sec:result}. As there is no available dataset, we argue that we make a sufficient size dataset by manual effort. \section{Overview of our Identification Approach} \label{mal-identification} \vspace{-0.15in} Here, we describe our supervised learning algorithm to identify the repositories that contain malware. {\bf Step 1. Data preprocessing:} As in any Natural Language Processing (NLP) method, we start with some initial processing of the text to improve the effectiveness of the solution. We briefly outline three levels of processing functionality. \textbf{a. Character level preprocessing:} We handle the character level ``noise" by removing special characters, such as punctuation and currency symbols, and fix Unicode and other encoding issues. \textbf{b. Word level preprocessing:} We eliminate or aggregate words following the best practices of Natural Language Processing~\cite{jivani2011comparative}. First, we remove article words and other words that don't carry significant meaning on their own. Second, we use a stemming technique to handle inflected words. Namely, we want to decrease the dimensionality of the data by grouping words with the same "root". For example, we group the words ``organizing'', ``organized'', ``organize'' and ``organizes'' to one word ``organize''. Third, we filter out common file and folder names that we do not expect to help in our classification, such as ``LEGAL'', ``LICENSE'', ``gitattributes'' etc. \textbf{c. Entity level filtering:} We filter entities that are likely not helpful in describing the scope of a repository. Specifically, we remove numbers, URLs, and emails, which are often found in the text. We found that this filtering improved the classification performance. In the future, we could consider mining URLs and other information, such as names of people, companies or youtube channels, to identify authors, verify intention, and find more malware activities. {\bf Step 2. The repository fields:} We consider fields from the repositories that can be numbers or text. Text-based fields require processing in order to turn them into classification features and we explain this below. We use and evaluate the following text fields: title, description, topics, file and folder names and README file fields. \textbf{Text field representation: } We consider two techniques to represent each text field by a feature in the classification. {\bf i. Bag of Words (BoW):} The bag-of-words (BoW) model is among the most widely used representations of a document. The document is represented as the number of occurrences of its words, disregarding grammar and word order~\cite{zhang2010understanding}. This model is commonly used in document classification where the frequency of each word is used as feature value for training a classifier~\cite{mctear2016conversational}. We use the model with the count vectorizer and TF-IDF vectorizer to create the feature vector. In more detail, we represent each text field in the repository with a vector $V[K]$, where $V[i]$ corresponds to the significance of work $i$ for the text. There are several ways to assign values $V[i]$: (a) zero-one to account for presence, (b) number of occurrences, and (c) the TF-IDF value of the word. We evaluated all the above methods. {\em Fixing the number of words per field.} To improve the effectiveness of our approach using BoW, we conduct a feature selection process, ${\chi}^2$ statistic following best practices~\cite{rogati2002high}. The ${\chi}^2$ statistic measures the lack of independence between a word (feature) and a class. A feature with lower chi-square score is less informative for that class, and thus not useful in the classification. We discuss this further in Section~\ref{sec:result}. For each text-based field $f$, we select the top $K_f$ words for that field, which exhibit the highest discerning power in identifying malware repositories. Note that we set a value for $K_f$ during the training stage For each field, we select the value $K_f$, as we explain in Section~\ref{sec:result}. {\bf ii. Word embedding:} The word embedding model is a vector representations of each word in a document: each word is mapped to an M-dimensional vector of real numbers~\cite{mikolov2013distributed}, or equivalently are projected in an M-dimensional space. A good embedding ensures that words that are close in meaning have nearby representations in the embedded space. In order to create the document vector, word embedding follows two approaches (i) frequency-based vectorizer(unsupervised)~\cite{schnabel2015evaluation} and (ii) content-based vectorizer(supervised)~\cite{kusner2015word}. Note that in this type of representation, we do not use the {\em word level processing}, which we described in the previous step, since this method can leverage contextual information. We use frequency-based word embedding with word average and TF-IDF vectorizer. We also use pre-trained model of Google word2vec~\cite{mikolov2013efficient} and Stanford (Glov)~\cite{pennington2014glove} to create the feature vector. Finally, we create the vector of the repository by concatenating the vectors of each field of that repository. {\bf Step 3. Selecting the fields:} Another key question is which fields from the repository to use in our classification. We experiment with all of the fields listed in Section~\ref{sub-sec:background} and we explain our findings in the next Section. {\bf Step 4. Selecting a ML engine:} We design classifiers to classify the repositories into two classes: (i) malware repository and (ii) benign repository. We systematically evaluate many machine learning algorithms \cite{murphy2012machine,bishop2006pattern}: Naive Bayes (NB), Logistic Regression (LR), Decision Tree (CART), Random Forest(RF), K-Nearest Neighbor (KNN), Linear Discriminant Analysis (LDA), and Support Vector Machine (SVM). {\bf Step 5. Detecting source code repositories:} We also want to identify the existence of source code in the repositories, as the final step in providing malware source code to the community. We propose a heuristic approach, which seems to work fairly well in practice. First, we want to identify files in the repository that contain source code. To do this, we start by examining their file extension. If the file extension is one of the known programming languages: {\em Assembly, C/C++, Batch File, Bash Shell Script, Power Shell script, Java, Python, C\#, Objective-C, Pascal, Visual Basic, Matlab, PHP, Javascript, and Go}, we label it as a source file. Second, if the number of source files in a repository exceeds the {\bf \sourceThresh threshold (\sourceThreshS)}, we consider that the repository contains source code. {\em How effective is this heuristic?} It turns out that in practice it works pretty well, as we will see in Section \ref{sec:result}. Given that authors go out of their way to share their malware openly, and even provide appropriate titles and keywords, it seems less likely that they will attempt to obfuscate the existence of source code in the repository. \section{Evaluation: Choices and Results} \label{sec:result} \vspace{-0.15in} In this section, we evaluate the effectiveness of the classification based on the proposed methodology defined in Section~\ref{mal-identification}. More specifically, our goal here is to answer the following questions: \begin{enumerate} \itemsep-0.3em \item {\bf Repository Field Selection:} Which repository fields should we consider in our analysis? \item {\bf Field Representation:} Which feature representation is better between bag of words (BoW) and word embeddings and considering several versions of each? \item {\bf Feature Selection}: What are the most informative features in identifying malware repositories? \item {\bf ML Algorithm Selection:} Which ML algorithm exhibits the best performance? \item {\bf Classification Effectiveness:} What is the precision, recall and F1-score of the classification? \item {\bf Identifying Malware Repositories:} How many malware repositories do we find? \item {\bf Identifying Malware Source Code Repository: } How many of the malware repositories have source code? \end{enumerate} Note that we have a fairly complex task: we want to identify the best fields, representation method and Machine Learning engine, while considering different values for parameters. What complicates matters is that all these selections are interdependent. We present our analysis in sequence, but we followed many trial and error and non-linear paths in reality. {\bf 1. Selecting repository fields:} We evaluated all the repository fields mentioned earlier. In fact, we used a significant number of experiments with different subsets of the features, not shown here due to space limitations. We find that the title, description, topics, README file, and file and folder names have the most discerning power. We also considered number of forks, watchers, and stars of the repository and the number of followers and followings of the author of the repository. We found that not only it did not help, but it usually decreased the classification accuracy by 2-3\%. One possible explanation is that the numbers of forks, stars and followers reflect the popularity rather than the content of a repository. \begin{table \centering \footnotesize \begin{tabular} {|p{0.65\linewidth}|p{0.22\linewidth}|} \hline {\bf Representation} & \textbf{Classification Accuracy Range} \\ \hline Bag of Words with Count Vectorizer & 86\%-51\% \\ \hline Bag of Words with Count Vectorizer + Feature Selection & 91\%-56\% \\ \hline Bag of Words with TF-IDF vectorizer & 82\%-63\% \\ \hline \hline Word Embedding with Word Average & 85\%-72\% \\ \hline Word Embedding with TF-IDF & 85\%-74\% \\ \hline \hline Pretrained Google word2vec Model & 76\%-64\% \\ \hline Pretrained Stanford (Glov) Model & 73\%-62\% \\ \hline \end{tabular} \caption{Selecting the feature representation model: We evaluate all the representations across seven machine learning approaches and report the range of the overall classification accuracy. } \label{tab:feature-representation} \end{table} {\bf 2. Selecting a field representation:} The goal is to find, which representation approach works better. In Table \ref{tab:feature-representation}, we show the comparison of the range of classification accuracy across the 7 different ML algorithms that we will also consider below. We find that Bag of Words with the count vectorizer representation reaches 86\% classification accuracy, with the word embedding approach nearly matches that with 85\% accuracy. Note that we finetune the selection of words to represent each field in the next step. Why does not the embedding approach outperform the bag of words? One would have expected that the most complex embedding approach would have been the winner and with a significant margin. We attribute this to the relatively small text size in most text fields, which also do not provide well-structured sentences (think two-three words for the title, and isolated words for the topics). Furthermore, the word co-occurrences does not exist in topics and file names field, which partly what makes embedding approaches work well in large and well structured documents \cite{li2015word, globerson2007euclidean}. In the rest of this paper, we choose the Bag of Words with count vectorizer to represent our text fields, since it exhibits good performance and is computationally less intensive than the embedding method. \begin{figure} \centering \includegraphics[height=5cm, width=0.99\linewidth]{FIG/model_comparison3.pdf} \caption{Naive Bayes tops by performance (Accuracy, Precision, Recall and F1-score) comparison among NB, LR, CART, RF, KNN, LDA and SVM on dataset LD137.} \label{fig:model_comparison} \end{figure} \textbf{3. Fixing the number of words per field.} We want to identify the most discerning words from each text field, which is a standard process in NLP for improving the scalability, efficiency and accuracy of a text classifier \cite{chen2009feature}. Using the ${\chi}^2$ statistic, we select the top $K_f$ best words from each field. To select the appropriate number of words per field, we followed the process below. We vary $K_f$ = 5,10,20,30,40 and 50 for title, topic and README file, and we find that the top 30 words in title, 10 words in topic and 10 words in README file exhibit the highest accuracy. Similarly, we try $K_f$ = 80, 90, 100, 110 and 120 for file names and $K_f$ = 300, 325, 350, 375, 400, 425, 450 and 475 for the description field. We find that the top 100 words for file and folder names and top 400 words for description field give the highest accuracy. Note that we do this during training and refining the algorithm, and then we continue to use these words as features in testing. Thus, we select the top: (a) 30 words from the title, (b) 10 words from the topics, (c) 400 words from the description, (d) 100 words from the file names, and 10 words from the README file. This leads to a total of 550 words across all fields. For reference, we find 9253 unique words in the repository fields of our training dataset. Reducing the focus on the top 550 most discerning words per field increases the classification accuracy by as much as 20\% in some cases. {\bf 4. Evaluating and selecting ML algorithms:} We asses the classification performance of Multinomial Naive Bayes (NB), Logistic Regression (LR), Support Vector Machine (SVM), Decision Tree (CART), Random Forest(RF), Linear Discriminant Analysis (LDA), and K-Nearest-Neighbors (KNN), and show their precision, recall and F1-score in Figure~\ref{fig:model_comparison}. Multinomial Naive Bayes exhibits the best F1-score with \fOne, striking a good balance between \precision precision, \recall recall for the malware class. Detecting the benign class we do even better with 92\% precision, 94\% recall and 93\% F1-score. By contrast, the F1-score of the other algorithms is below 79\%. Note that KNN, LR and LDA provide higher precision, but with significantly lower recall. Clearly, one could use these algorithms to get higher precision at the cost of lower total number of repositories. We use Multinomial Naive Bayes as our classification engine for the rest of this study. We attempt to explain the superior F1-Score of the Naive Bayes in our context. The main advantage of Naive Bayes over other algorithms is that it considers the features independently of each other and can handle large number of features better. As a result, it is more robust to noisy or unreliable features. It also performs well in domains with many equally important features, where other approaches suffer, especially with a small training data, and it is not prone to overfitting~\cite{ting2011naive}. As a result, the Naive Bayes is considered a dependable algorithm for text classification and it is often used as the benchmark to beat~\cite{xu2018bayesian}. \begin{figure \includegraphics[width=0.99\linewidth, height=5cm]{FIG/precision-recall-malware2.pdf} \caption{Assessing the effect of the number of keywords in the query: Precision, Recall and F1-score of our approach on the LD137, LD50 and LD1 labeled datasets.} \label{fig:precision-recall} \end{figure} {\bf 5. Assessing the effect of the query set:} We have made the following choices in the previous steps: (a) 5 text-based fields, (b) bag of words with count vectorization, (c) 550 total words across all the fields, and (d) the Multinomial Naive Bayes. We perform 10-fold cross validation and report the precision, recall and F1-score in Figure~\ref{fig:precision-recall} for our three different labeled data sets. We see that the precision stays above 89\% for all three datasets, with a recall above 77\%. It is worth noting the relative stability of our approach with respect to the keyword set for the initial query especially between LD50 and LD137 datasets. The LD1 dataset we observe higher accuracy, but significantly less recall compared to LD137. We attribute this fact to the single keyword used in selecting the repositories in LD1, which may have lead to a more homogeneous group of repositories. Interestingly, LD50 seem to have the lower recall and F1-score even though the differences are not that large. \textbf{6. Identifying \malrepo malware repositories:} We use LD137 to train our Multinomial Naive Bayes model and apply it on RD137 dataset. We find \malrepo malware repositories. We also apply the same trained model on RD1 and RD50 and find 809 and 3615 malware repositories respectively, but this repositories are included in the \malrepo. (Recall that RD1 and RD50 are subsets of RD137). \begin{table \centering \footnotesize \begin{tabular} {|p{0.14\linewidth}|p{0.13\linewidth}||p{0.18\linewidth}|p{0.32\linewidth}|} \hline \textbf{Dataset} & \textbf{Initial} & \textbf{Malware} & \textbf{Mal. + Source} \\ \hline RD1 & 2775 & 809 & 680 \\ \hline RD50 & 14332 & 3615 & 3096 \\ \hline RD137 & 97375 & 8644 & 7504 \\ \hline \end{tabular} \caption{The identified repositories per dataset with: (a) malware, and (b) malware and source code.} \label{tab:mal-identifcation} \end{table} \textbf{7. Identifying \sourceNum malware source code repositories:} We use our heuristic approach to identify source code repositories. We set our \sourceThresh threshold to 75\%, meaning that: if more than 75\% of files in a repository are source code files, we label it as a source code repository. Applying this heuristic, we find that \sourceNum repositories are most likely source code repositories in RD137. We use the name \textbf{M137} to refer to this group of malware source code repositories. We find 680 and 3096 malware source code repositories in RD1 and RD50 as shown in Table \ref{tab:mal-identifcation}. However, these are subset of M137, given that RD1 and RD50 are subsets of RD137. To evaluate the effectiveness of our heuristic, we manually check 30 randomly-selected repositories from M137. We find that all 30 repositories contain source code\footnote{Apart from a manual verification, these 30 repositories were further stress-tested: (a) 20 where used in a separate static analysis study, and (b) 15 were compiled and run successfully within an emulator. }, which corresponds to 100\% precision. We will further evaluate the effectiveness of this heuristic in the future. \textbf{8. A curated malware source code dataset: \curDataSet} As a tangible contribution, we provide, \curDataSet, a dataset of 250 repositories from the M137 dataset, which we manually verify for containing malware source code and relating to a particular malware type. Opting for diversity and coverage, the dataset spans all the identified types: virus, backdoor, botnet, keylogger, worm, ransomware, rootkit, trojan, spyware, spoof, ddos, sniff, spam, and cryptominer. While constantly updating, we will make this dataset available to researchers. \section{A large scale study of malware} \label{sec:longitudinal} \vspace{-0.15in} Encouraged by the substantial number of malware repositories, we study the distributions and longitudinal properties of the identified malware repositories in M137. {\bf Caveat:} We provide some key observations in this section, but they should be viewed as indicative and approximate trends and only within the context of the collected repositories and with the general assumption that repository titles and descriptions are reasonably accurate. In Section~\ref{sec:discussion}, we discuss issues around the biases and limitations that our dataset may introduce. \begin{figure}[h] \centering \includegraphics[height=5cm,width=0.40\textwidth]{FIG/loglog_forks_stars_watch.pdf} \caption{CCDF distributions of forks, stars and watchers per repository.} \label{fig:ccdf-repos} \end{figure} \textbf{A. Identifying influential repositories.} The prominence of a repository can be measured by the number of \textit{forks}, \textit{stars}, and \textit{watchers}. In Figure~\ref{fig:ccdf-repos}, we plot the complementary cumulative distribution function (CCDF) of these three metrics for our malware repositories. {\bf Fork distribution:} We find that 2\% of the repositories seem quite influential with at least 100 forks as shown in Figure~\ref{fig:ccdf-repos}. Recall that the fork counter indicates the number of distinct users that have forked a repository. For reference, 78\% of the repositories have less than 2 forks. {\bf Star distribution}: We find that 2\% of the repositories receive more than 250 stars as shown in Figure~\ref{fig:ccdf-repos}. For reference, 75\% of the repositories have less than 3 stars. {\bf Watcher distribution}: In Figure~\ref{fig:ccdf-repos}, we find that 1\% of the repositories have more than 50 watchers. For reference, we observe that 84\% of the repositories have less than 3 watchers. Note that these distributions are skewed, and follow patterns that can be approximated by a log-normal distribution. {\em Which are the most influential repositories?} We find that 8 repositories dominate the top 5 spots across all three metrics: stars, forks, and watchers. We present a short profile of these dominant repositories in Table \ref{tab:top8repo}. Most of the repositories contain a single malware project, which is an established practice among the authors in GitHub\xspace~\cite{projectperrepo1,projectperrepo2}. We find that the repository ``theZoo''~\cite{thezoo}, created by \textit{ytisf} in 2014 is the most forked, watched, and starred repository with 1393 forks, 730 watchers and 4851 stars as of October, 2019. However, this repository is quite unique and was created with the intention of being a malware database with 140 binaries and 80 source code repositories. \begin{table}[t] \centering \footnotesize \begin{tabular} {|p{0.02\linewidth}|p{0.16\linewidth}|p{0.05\linewidth}|p{0.05\linewidth}|p{0.1\linewidth}|p{0.32\linewidth}|} \hline \textbf{R ID} & \textbf{Author} & \textbf{\# Star} & \textbf{\# Fork}& \textbf{\# Watcher}& \textbf{ Content of the Repository}\\ \hline 1 & ytisf & 4851 & 1393 & 730 & 80 malware source code and 140 Binaries\\ \hline 2 & n1nj4sec & 4811 & 1307 & 440 & Pupy RAT\\ \hline 3 & Screetsec & 3010 & 1135 & 380 & TheFatRat Backdoor\\ \hline 4 & malwaredllc & 2515 & 513 & 268 & Byob botnet\\ \hline 5 & RoganDawes & 2515 & 513 & 268 & USB attack platform\\ \hline 6 & Visgean & 626 & 599 & 127 & Zeus trojan horse\\ \hline 7 & Ramadhan & 535 & 283 & 22 & 30 malware samples\\ \hline 8 & dana-at-cp & 1320 & 513 & 125 & backdoor-apk backdoor\\ \hline \end{tabular} \caption{The profile of the top 5 most influential malware repositories across all three metrics with 8 unique repositories.} \label{tab:top8repo} \end{table} {\bf Influence metrics are correlated}: As one would expect, the influence and popularity metrics are correlated. We use a common correlation metric, the Pearson Correlation Coefficient ($r$)~\cite{benesty2009pearson}, measured in a scale of $[-1,1]$. We calculate the metric for all pairs of our three popularity metrics. We find that all of them exhibit higher positive correlation: stars vs. forks ($r=0.92$, $p<0.01$), forks vs. watchers ($r=0.91$, $p<0.01$) and watchers vs. stars ($r=0.91$, $p<0.01$). \textbf{B. Malware Type and Target Platform.} We wanted to get a feel for what type of malware we have identified. As a first approximation, we use the keywords found in the text fields to relate repositories in M137 with the type of malware and the intended target platform. Our goal is to create the two-dimensional distribution per malware type and the target platform as shown in Table~\ref{tab:type_os_distribution}. To create this table, we associate a repository with keywords in its title, topics, descriptions, file names and README file fields of: (a) the 6 target platforms, and (b) the 13 malware type keywords. \textit{How well does this heuristic approach work?} We provide two different indications of its relative effectiveness. First, the vast majority of the repositories relate to one platform or type of malware: (a) less than 8\% relate to more than one platform, and (b) less than 11\% relate to more than one type of malware. Second, we manually verify the 250 repositories in our curated data~\curDataSet and find a 98\% accuracy. Below, we provide some observations from Table~\ref{tab:type_os_distribution}. {\bf a. Keyloggers reign supreme.} We see that one of the largest categories is the keylogger malware with 679 repositories, which are mostly affiliated with Windows and Linux platforms. We discuss the emergence of keyloggers below in our temporal analysis. {\bf b. Windows and Linux are the most popular targets.} Not surprisingly, we find that the majority of the malware repositories are affiliated with these two platforms: 1592 repositories for Windows, and 1365 for Linux. {\bf c. MacOS-focused repositories: fewer, but they exist.} Although MacOS platform are less common among PC users, we see that malware repositories targeting such platforms indeed exist. As shown in Figure~\ref{fig:platform-trend}, MacOS malware repositories are an order of magnitude less compared to those for Windows and Linux. \begin{table}[t] \footnotesize \begin{tabular} {|p{0.10\linewidth}|r|r|r|r|r|r|r|} \hline \multirow{2}{*}{\textbf{Types}} & \multicolumn{7}{|c|}{\textbf{Target Platform}} \\ \cline{2-8} & Wind. & Linux & Mac & IoT & Andr. & iOS & {\bf Total} \\ \hline \hline {\bf Total} & {\bf 1592} & {\bf 1365} & {\bf 380} & {\bf 108} & {\bf 442} & {\bf 131} & {\bf 4018} \\ \hline \hline key- logger & 396 & 209 & 42 & 2 & 27 & 3 & {\bf 679} \\ \hline back- door & 181 & 227 & 37 & 11 & 51 & 4 & {\bf 511} \\ \hline virus & 235 & 131 & 34 & 2 & 51 & 16 & {\bf 469} \\ \hline botnet & 153 & 154 & 43 & 36 & 64 & 17 & {\bf 467} \\ \hline trojan & 133 & 70 & 24 & 16 & 67 & 19 & {\bf 329} \\ \hline spoof & 76 & 115 & 88 & 2 & 20 & 9 & {\bf 310} \\ \hline rootkit & 55 & 163 & 13 & 2 & 19 & 3 & {\bf 255} \\ \hline ransom- ware & 117 & 67 & 14 & 1 & 33 & 13 & {\bf 245} \\ \hline ddos & 71 & 95 & 20 & 10 & 9 & 3 & {\bf 208} \\ \hline worm & 61 & 45 & 18 & 5 & 25 & 18 & {\bf 172} \\ \hline spyware & 45 & 22 & 6 & 6 & 38 & 16 & {\bf 133} \\ \hline spam & 40 & 29 & 18 & 14 & 23 & 5 & {\bf 129} \\ \hline sniff & 29 & 38 & 23 & 1 & 15 & 5 & {\bf 111} \\ \hline \end{tabular} \caption{Distribution of the malware repositories from M137 dataset based on the malware type and malware target platform. This table demonstrates the repositories that fit with the criteria defined in Section~\ref{sec:longitudinal}.} \label{tab:type_os_distribution} \end{table} \begin{figure*}[h] \begin{subfigure}{0.26\textwidth} \includegraphics[height=5cm,width=5cm]{FIG/overall-trend.pdf} \caption{New malware repositories created per year.} \label{fig:overall-trend} \end{subfigure} ~ \begin{subfigure}{0.42\textwidth} \includegraphics[height=5cm,width=7.7cm]{FIG/type-trend.pdf} \caption{New repositories per type of malware per year.} \label{fig:type-trend} \end{subfigure} ~ \begin{subfigure}{0.30\textwidth} \includegraphics[height=5cm,width=5.5cm]{FIG/platform-trend.pdf} \caption{New malware repositories per target platform per year.} \label{fig:platform-trend} \end{subfigure} \caption{New malware repositories per year: a) all malware, b) per type of malware, and c) per target platform. } \label{fig:trend} \end{figure*} \textbf{C. Temporal analysis.} We want to study the evolution and the trends of malware repositories. We plot the number of new malware repositories per year: a) total malware, b) per type of malware, and c) per target platform in Figure~\ref{fig:trend}. We discuss a few interesting temporal behaviors below. {\bf a. The number of new malware repositories more than triples every four years.} We see an alarming increase from 117 malware repositories in 2010 to 620 repositories in 2014 and to 2166 repositories in 2018. We also observe a sharp increase of 70\% between 2015 to 2016 shown in Figure~\ref{fig:overall-trend}. {\bf b. Keyloggers started a super-linear growth since 2010} and are by far affiliated with the most new repositories per year since 2013, but their rate of growth reduced in 2018. {\bf c. Ransomware repositories emerge in 2014 and gain momentum in 2017}. Ransomware experienced their highest growth rate in 2017 with 155 new repositories, while that number dropped to 103 in 2018. {\bf d. Malware activity slowed down in 2018 across the board.} It seems that 2018 is a slower year for all malware even when seen by type ( Figure~\ref{fig:type-trend}) and target platform (Figure~\ref{fig:platform-trend}). We find that the number of new malware repositories has dropped significantly in 2018 for most types of malware except virus, keylogger and trojan. {\bf e. IoT and iPhone malware repositories become more visible after 2014}. We find that IoT malware emerges in 2015 and iPhone malware sees an increase after 2014 in Figure~\ref{fig:platform-trend}. We conjecture that this is possibly encouraged by the emergence and increasing popularity of specific malware: (a) WireLurker, Masque, AppBuyer malware~\cite{iosmalware2014} for iPhones, and (b) BASHLITE \cite{iotbashlite}, a Linux based botnet for IoT devices. We find the names of the aferemntioned malware in many repositories starting in 2014. Interestingly, the source code of the original BASHLITE botnet is available in a repository created by {\em anthonygtellez} in 2015. {\bf f. Windows and Linux: dominant but slowing down.} In Figure \ref{fig:platform-trend}, we see that windows and linux malware are flattened between 2017 and 2018. By contrast, IoT and android repositories have increased. \section{Understanding malware authors} \label{sec:authors} \vspace{-0.15in} Intrigued by the fact that authors create public malware repositories, we attempt to understand and profile their behavior. As a first step towards understanding the malware authors\xspace, we want to assess their popularity and influence. We use the following metrics: (a) number of malware repositories which they created, (b) number of followers, (c) total number of watchers on their repositories, and (d) total number of stars. We focus on the first two metrics here. We use the notation \textit{top k authors} for any of the metrics above, where \textit{k} can be any positive integer to referring to "heavy-hitters". \textbf{A. Finding influential malware authors\xspace. } We study the distribution of the number of malware repositories created and the number followers per author in following. First, we find that 15 authors are contributing roughly 5\% of all malware repositories by examining the CCDF of the created repositories in Figure~\ref{fig:cddf-author}. From the figure, we find an outlier author, {\em cyberthreats}, who doesn't follow power law distribution~\cite{faloutsos1999power}, has created 336 malware repositories. We also find that 99\% authors have less than 5 repositories. Second, we study the distribution of the number of followers per author but omit the plot due to space limitations. The distributions is skewed with 3\% (221) of the authors having more than 300 followers each, while 70\% of the authors have less than 16 followers. \begin{figure}[] \centering \includegraphics[height=4cm, width=0.40\textwidth]{FIG/loglog_repos_per_author_ccdf2.pdf} \caption{CCDF of malware repositories per author.} \label{fig:cddf-author} \end{figure} \textbf{B. Malware authors\xspace strive for an online ``brand":} In an effort to understand the motive of sharing malware repositories, we make the following investigation. {\bf a. Usernames seem persistent across online platforms.} We find that many malware authors\xspace use the same username consistently across many online platforms, such as security forums. We conjecture that they are developing a reputation and they use their username as a ``unique" identifier. We identify 18\xspace malware authors\xspace\footnote { Note that this does not mean that the other authors are not doing the same, but they could be active in other security forums or online platforms. }, who are active in at least one of the three security forums: Offensive Community, Ethical Hacker and Hack This Site, for which we happen to have access to their data. We conjecture that at least some of these usernames correspond to the same users based on the following two indications. First, we find direct connections between the usernames across different platforms. For example, user {\em 3vilp4wn} at the ``Hack This Site'' forum is promoting a keylogger malware by referring to a GitHub\xspace repository~\cite{hacktool3vilp4wn} whose author has the same username. Second, these usernames are fairly uncommon, which increases the likelihood of belonging to the same person. For example, there is a GitHub\xspace user with the name {\em fahimmagsi}, and someone with the same username is boasting about their hacking successes in the ``Ethical Hacker'' forum. As we will see below, {\em fahimmagsi} seems to have a well-established online reputation. {\bf b. ``Googling" usernames reveals significant hacking activities.} Given that these GitHub\xspace usernames are fairly unique, it was natural to look them up on the web at large. Even a simple Internet search with the usernames reveals significant hacking activities, including hacking websites or social networks, and offering hacking tutorials in YouTube. We investigate the \textit{top 40} most prolific malware authors\xspace using a web search with a {\em single} simple query: ``hacked by $<$username$>$''. We then examine only the first page of search results. Despite all these self-imposed restrictions, we identify three users with substantial hacking related activities across Internet. For example, we find a number of news articles for hacking a series of websites by GitHub\xspace users {\em fahimmagsi} and {\em CR4SH} \cite{hacknewsfahimmagsi}~\cite{hacktoolcr4sh}. Moreover, we find user {\em n1nj4sec} sharing a multi-functional Remote Access Trojan (RAT) named ``Pupy", developed by her, which received significant news coverage in security articles back in March of 2019~\cite{pupyGithub}\cite{pupyarticle}. We are confident that well-crafted and targeted searches can connect more malware authors with hacking activities and usernames in other online forums. \section{Discussion} \label{sec:discussion} \vspace{-0.15in} We discuss the effectiveness and limitations of SourceFinder\xspace. \textbf{a. Why is malware publicly available in the first place?} Our investigation in Section~\ref{sec:authors} provides strong indications that malware authors want to actively establish their hacking reputation. It seems that they want to boost their online credibility, which often translates to money. Recent works~\cite{Portnoff2017, Deb2018_USC3,Sapienza2018_USC2} study the underground markets of malware services and tools: it stands to reason that notorious hackers will attract more clients. At the same time, GitHub\xspace acts as a collaboration platform, which can help hackers improve their tools. \textbf{b. Do we identify every malware repository in GitHub\xspace?} Our tool can not guarantee that it will identify every malware repository in GitHub\xspace. First, we can only identify repositories that ``want to be found": (a) they must be public, and (b) they must be described with the appropriate text and keywords. Clearly, if the author wants to hide her repository, we won't be able to find it. However, we argue that this defeats the purpose of having a public archive: if secrecy was desired, the code would have been shared through private links and services. Second, our approach is constrained by GitHub\xspace querying limitations, which we discussed in Section \ref{sub-sec:data-collection}, and the set of 137 keywords that we use. However, we are encouraged by the number and the reasonable diversity of the retrieved repositories we see in Table~\ref{tab:type_os_distribution}. \textbf{c. Are our datasets representative?} This is the typical hard question for any measurement or data collection study. First of all, we want to clarify that our goal is to create a large database of malware source code. So, in that regard, we claim that we accomplished our mission. At the same time, we seem to have a fair number of malware samples in each category of interest, as we see in Table~\ref{tab:type_os_distribution}. Studying the trends of malware is a distant second goal, which we present with the appropriate caveat. On the one hand, we are limited by GitHub\xspace's API operation, as we discussed earlier. On the other hand, we attempt to reduce the biases that are under our control. To ensure some diversity among our malware, we added as many words as we could in our 137 malware, which is likely to capture a wide range of malware types. We argue that the fairly wide breadth of malware types in Table \ref{tab:type_os_distribution} is a good indication. Note that our curated dataset \curDataSet with 250 malware is reasonably representative in terms of coverage. {\bf d. What is the overlap among the identified repositories?} Note that our repository does not include forked repositories, since {\bf GitHub\xspace does not return forked repositories as answers to a query}. Similarly, the breadth of the types of the malware as shown in Table~\ref{tab:type_os_distribution} hints at a reasonable diversity. However, our tool cannot claim that the identified repositories are distinct nor is it attempting do so. GitHub\xspace does not restrict authors from copying (downloading), and uploading it as a new repository. In the future, we intend to study the similarity and evolution among these repositories. {\bf e. Are the authors of repositories the original creator of the source code?} This is an interesting and complex question that goes beyond the scope of this work. Identifying the original creator will require studying the source code of all related repositories, and analyzing the dynamics of the hacker authors, which we intend to do in the future. {\bf f. Are all the malware authors malicious?} Not necessarily. This is an interesting question, but it is not central to the main point of our work. On the one hand, we find some white hackers or researchers, such as Yuval Nativ~\cite{yuval}, or Nicolas Verdier~\cite{Nicolas}. On the other hand, several authors seem to be malicious, as we saw in Section~\ref{sec:authors}. {\bf g. Are our malware repositories in "working order"?} It is hard to know for sure, but we attempt to answer indirectly. First, we pick 30 malware source codes and all of them compiled and a subset of 15 of them actually run successfully in an emulated environment as we already mentioned. Second, these public repositories are a showcase for the skills of the author, who will be reluctant to have repositories of low quality. Third, public repositories, especially popular ones, are inevitably scrutinized by their followers. \textbf{h. Can we handle evasion efforts?} Our goal is to create the largest malware source-code database possible and having collected \sourceNum malware repositories seems like a great start. In the future, malware authors\xspace could obfuscate their repositories by using misleading titles, and description, and even filenames. We argue that authors seem to want their repositories to be found, which is why they are public. We also have to be clear: it is easy for the authors to hide their repositories, and they could would start by making them private or avoid GitHub\xspace altogether. However, both these moves will diminish the visibility of the authors. \textbf{i. Will our approach generalize to other archives? } We believe that SourceFinder\xspace can generalize to other archives, which provide public repositories, like GitLab and BitBucket. We find that these sites allow public repositories and let the users retrieve repositories. We have also seen equivalent data fields (title, description, etc). Therefore, we are confident that our approach can work with other archives. \section{Related Work} \label{sec:related} \vspace{-0.15in} There are several works that attempt to determine if a piece of software is malware, usually focusing on a binary, using static or dynamic analysis~\cite{aycock2006computer,kolbitsch2009effective,shankarapani2011malware,damodaran2017comparison}. However, to the best of our knowledge, no previous study has focused on identifying malware source code in public software archives, such as GitHub\xspace, in a systematic manner as we do in this work. We highlight the related works in the following categories: {\bf a. Studies that needed source code.} Several studies~\cite{lepik2018art,zhong2015stealthy,shen2018javascript} use malware source code that are manually retrieved from GitHub\xspace repositories. Some studies~\cite{calleja2016look}~\cite{calleja2018malsource} compare the evolution and the code reuse of 150 malware source codes (with only some from GitHub\xspace) with that of benign software from a software engineering perspective and study the code reuse. Overall, various studies \cite{darki2019idapro,jerkins2017motivating} can benefit from malware source code to fine-tune their approach. \textbf{b. Mining and analyzing GitHub\xspace:} Many studies have analyzed different aspects of GitHub\xspace, but not with the intention of retrieving malware repositories. First, there are efforts that study the user interactions and collaborations on GitHub\xspace and their relationship to other social media in \cite{kollanyi2016automation,horawalavithana2019mentions,pletea2014security}. Second, some efforts discuss the challenges in extracting and analyzing data from GitHub\xspace with respect to sampling biases~\cite{cosentino2016findings,gousios2017mining}. Other works~\cite{kalliamvakou2014promises,kalliamvakou2016depth} study how users utilize the various features and functions of GitHub\xspace. Several studies \cite{howison2004perils,rainer2005evaluating,treude2018unusual} discuss the challenges of mining software archives, like \textit{SourceForge} and GitHub\xspace, arguing that more information is required to make assertions about users and software projects. \textbf{c. Databases of malware source code:} At the time of writing this paper, there are few malware source code databases and are rarely updated such as project \textit{theZoo}~\cite{thezoo}. To the best of our knowledge, there does not exist an active archive of malware source code, where malware research community can get an enough number of source code to analyze. \textbf{d. Database of malware binaries:} There are well established malware binary collection initiatives, such as Virustotal~\cite{total2019virustotal} which provides analysis result for a malware binary. There are also community based projects such as VirusBay~\cite{virusbay} that serve as malware binary sharing platform. \textbf{e. Converting binaries to source code:} A complementary approach is to try to generate the source code from the binary, but this is a very hard task. Some works~\cite{vdurfina2011design,vdurfina2013psybot} focus on reverse engineering of the malware binary to a high-level language representation, but not source code. Some other efforts \cite{healey2019source, schulte2018evolving,chen11novel} introduce binary decompilation into readable source code. However, malware authors use sophisticated obfuscation techniques \cite{saidi2010experiences}\cite{yakdan2016helping,chen2013refined} to make it difficult to reverse engineer a binary into source code. {\bf f. Measuring and modeling hacking activity.} Some other studies analyze the underground black market of hacking activities but their starting point is security forums~\cite{Portnoff2017, Deb2018_USC3,Sapienza2018_USC2}, and as such they study the dynamics of that community but without retrieving any malware code. \section{Conclusion} \vspace{-0.1in} Our work capitalizes on a great missed opportunity: there are thousands of malware source code repositories on GitHub\xspace. At the same time, there is a scarcity of malware source code, which is necessary for certain research studies. Our work is arguably the first to develop a systematic approach to extract malware source-code repositories at scale from GitHub\xspace. Our work provides two main tangible outcomes: (a) we develop SourceFinder\xspace, which identifies malware repositories with \precision precision, and (b) we create, possibly, the largest non-commercial malware source code archive with \sourceNum repositories. Our large scale study provide some interesting trends for both the malware repositories and the dynamics of the malware authors. We intend to open-source both SourceFinder\xspace and the database of malware source code to maximize the impact of our work. Our ambitious vision is to become the authoritative source for malware source code for the research community by providing tools, databases, and benchmarks.
{'timestamp': '2020-06-01T02:03:51', 'yymm': '2005', 'arxiv_id': '2005.14311', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14311'}
arxiv
\section{Introduction} \label{sec:intro} \input{02_introduction.tex} \section{Privacy-Protection Drone Patrol System} \label{sec:main} \input{03_system_main.tex} \section{Approach, Modifications, and Algorithm} \label{sec:approach_modifications} \input{03_1_Approach_and_Modification.tex} \section{Evaluation} \label{sec:Experiments} \input{04_experiments.tex} \section{Conclusion} \label{sec:Conclusion} \input{05_conclusion.tex} \bibliographystyle{ieeetr} \subsection{Related Work} \subsubsection{Removal of Privacy Sensitive Information} In robot cameras, the privacy infringement has attracted attention to develop a method removing the privacy-sensitive information in images \cite{PlaceAvoider, Jason, MU_Low_Anonymizer}. In \cite{PlaceAvoider}, the authors introduced scene recognition from a image. The scheme determines if a person is in a privacy-sensitive location. If a image is taken in a privacy-sensitive place, the proposal allows a camera device to be automatically turned off. However, faces are still exposed in privacy-insensitive places, and thus this scheme is not suitable for patrol drone visions. Jason et al. \cite{Jason} developed the privacy preserving action detection via a face modifier by using Generative Adversarial Networks (GANs). They proposed pixel-level modifications to change each person's face with minimal effect on action recognition performance. The proposed generator modifies each pixel in a original face to remove features of the face. To train the generator, the authors design their discriminator based on a face identification network that recognizes who s/he is. The generator learns the way to make the discriminator believe that a generated face is different from the original image. However, the generator tends to replace a input face to another face in the training dataset. In other words, the problem is that the generator doesn't learn how to change a face not in the training dataset. Moreover, the generator observes pixels of a face for modification, which means that a modified face is generated based on the original face. This approach could still leave some information of a original face in a modified face. The work \cite{MU_Low_Anonymizer} proposed a dynamic resolution face detection architecture to blur faces. The framework detects faces from extreme low resolution images via the proposed deep learning-based algorithm. Except for the detected faces, other privacy-insensitive pixels are enhanced to high resolution. Hence, in result images, only faces are blurred, which protects privacy-sensitive parts while preserving the performance of robot perception. However, in the case that a face are big in a frame, an intimate person can recognize who the person is in the frame even if the face is blurred. In addition, it would be possible not to detect a face in a low-resolution image, and then this scheme couldn't protect a person's privacy. \subsubsection{Generative Adversarial Networks} Generative Adversarial Networks (GANs) have had impressive success in generating realistic images \cite{GAN_Goodfellow}. The goal of this learning framework is to train a neural network to model a image distribution in an unsupervised manner. The trained network can generate a fake image indistinguishable from a real image. This training approach have been adopted to image-to-image translation \cite{Huang_18, Isola_17, Karacan_16, Karacan_18, Liu_17, Zhao_19, Zhu_17, Zhu_17_2, Park_19}. Those works learn a mapping from input to output images, meaning that a input image is translated to a image in a different image distribution. To construct our training architecture for obtaining deep-learning networks for our purpose, we have adopted the latest two works \cite{Park_19, Zhu_17}. By using the training framework in \cite{Zhu_17}, we make a generator to translate a photorealistic image to a segmentation mask, and the work \cite{Park_19} is used to train another generator that converts the resultant segmentation mask to a photorelistic image. \subsubsection{SLAM} To verify that our anonymization method has no effect on vision-based robot perception, we utilize simultaneous localization and mapping (SLAM) techniques. By using SLAM, in an unknown environment, a robot constructs a map around itself and localizes itself in the resultant map. Hence, in a video frame, manipulation of some pixels could affect the performance of SLAM since a map is drawn by extracting feature points of lines, edges, and corners of objects in images. In this work, ORB-SLAM2 \cite{ORB-SLAM2} is implemented on our system, which is one of the most popular algorithms of the vision-based SLAM. \subsection{Face Anonymizing Approach} \begin{figure*}[t] \centering \includegraphics[width=0.7\paperwidth]{Face_Anonymization_Procedure.eps} \caption{Our Approach to Anonymize Faces in a Video Frame} \label{Fig:Anonymization_Approach} \end{figure*} Fig.~\ref{Fig:Anonymization_Approach} illustrates our anonymization approach for our system. To anonymize faces, a companion computer has three different networks: Face detection network, Segmentation network, and Synthesis network. The face detection network operates to detect faces whenever a video frame is fetched to the companion computer. Detected faces are cropped and resized to meet the required input size of the segmentation network. Via the segmentation network, face's images are translated to semantic images. Note that the semantic images have no privacy information but the outline of detected faces is still maintained in the resultant images. The synthesis network generates photorelistic images based on the semantic images. Finally, the phtorelistic images replace the original faces. Since semantic images still have the outline of each facial component, phtorelistic images could retain facial expressions. \subsection{Training Architecture for Segmentation and Synthesis Networks} \if\mycmd1 \begin{figure*}[t] \centering \includegraphics[width=0.8\paperwidth]{Training_Architecture_3.eps} \caption{Training Architecture for Segmentation and Synthesis Networks} \label{Fig:Training_Architecture} \end{figure*} \else \begin{figure}[t] \centering \includegraphics[width=0.99\columnwidth]{Training_Architecture_4.eps} \caption{Training Architecture for Segmentation and Synthesis Networks} \label{Fig:Training_Architecture} \end{figure} \fi Fig.~\ref{Fig:Training_Architecture} presents our training architecture for segmentation and synthesis networks. To train those networks, we combine CycleGAN and GauGAN each of which is one of the spotlight image-to-image translation frameworks using GAN. The segmentation network is trained by CycleGAN's framework, where Generator $G$ called segmentation generator is to generate a semantic images from a photorealistic image. The synthesis network is obtained from GauGAN's framework. Generator $G^\text{s}$ will make a photorealistic image from the output of segmentation generator $G$. To obtain well-trained networks suitable for anonymization, we make modifications to generators' and discriminators' losses of both translation frameworks. \subsubsection{Training Architecture Model} To explain our modifications, we formulate our training architecture as follows. For training samples, $X$ and $Y$ denote a photorelistic domain and a semantic domain, respectively. For each domain, training samples are represented by $\{x_i\}_{i=1}^{N}$ and $\{y_j\}_{j=1}^{N}$.\footnote{In this work, $x_i$ is paired with a corresponding $y_j$, and thus both domains have the same number of samples.} Samples of each domain are followed by a data distribution, which represents $x \sim p_\text{data}(x)$ and $y \sim p_\text{data}(y)$, respectively. In this architecture, we have three generators, $G$, $F$, and $G^\text{s}$. Each generator is a mapping function: $G: X \rightarrow Y$, $F: Y \rightarrow X$, and $G^\text{s}: Y \rightarrow X$. For adversarial networks of those generators, there are discriminators $D_X$, $D_Y$, and $D_X^\text{s}$ each of which distinguishes if a input is from a data distribution or is generated by a generator. $D_Y$, $D_X$, and $D_X^\text{s}$ examine output of $G$, $F$, and $G^\text{s}$, respectively. \subsubsection{Well-Known Basic Definitions} In this subsection, we introduce well-known definitions of losses \cite{Zhu_17, Park_19}. Based on the losses, we will describe our modifications. \textbf{Adversarial Loss}: for each generator and discriminator pair, the \textit{adversarial loss} is defined as follows. \if\mycmd1 \begin{equation} \label{eq:adversarial_loss} \mathcal{L}_\text{adv}(G, D_Y, X, Y) = \mathbb{E}_{x \sim p_\text{data}(x)}[\text{log}(1-D_Y(G(x)))] + \mathbb{E}_{y \sim p_\text{data}(y)}[\text{log}(D_Y(y))], \end{equation} \else \begin{align} \label{eq:adversarial_loss} \mathcal{L}_\text{adv}(G, D_Y, X, Y) &= \mathbb{E}_{x \sim p_\text{data}(x)}[\text{log}(1-D_Y(G(x)))] \nonumber \\ &+ \mathbb{E}_{y \sim p_\text{data}(y)}[\text{log}(D_Y(y))], \end{align} \fi where $G(x)$ is a generated image by a generator $G$. $G$ tries to make $D_Y$ as difficult as possible to distinguish generated samples $G(x)$ from real samples $y$ whereas $D_Y$ should not be deceived by $G$. The relationship can be formulated as $\min_G \max_{D_Y} \mathcal{L}_{\text{adv}}(G, D_Y, X, Y)$. Hence, the generator actually should minimize the following loss. \if\mycmd1 \begin{align} \label{eq:loss_adv_G} \mathcal{L}_{\text{adv}, G}(G, D_Y, X, Y) &= \mathbb{E}_{x \sim p_\text{data}(x)}[\text{log}(1-D_Y(G(x)))]. \end{align} \else \begin{align} \label{eq:loss_adv_G} \!\!\!\!\mathcal{L}_{\text{adv}, G}(G, D_Y, X, Y) = \mathbb{E}_{x \sim p_\text{data}(x)}[\text{log}(1\!-\!D_Y(G(x)))]. \end{align} \fi For other pairs, ($F$, $D_X$) and ($G^\text{s}$, $D_X^\text{s}$), the adversarial loss can be obtained by replacing ($G$, $D_Y$) in (\ref{eq:adversarial_loss}) with ($F$, $D_X$) and ($G^\text{s}$, $D_X^\text{s}$). In addition, in (\ref{eq:adversarial_loss}), $X$ and $Y$ are replaced with $Y$ and $X$. \textbf{Cycle-Consistency Loss}: the \textit{cycle-consistency loss} \cite{Zhu_17} is defined as \begin{equation} \mathcal{L}_\text{cyc}(G, F) = \mathcal{L}_{ \text{cyc}, G}(F) + \mathcal{L}_{\text{cyc}, F}(G), \end{equation} where $\mathcal{L}_{G, \text{cyc}}(F)$ and $\mathcal{L}_{F, \text{cyc}}(G)$ is a cycle-consistency loss for each generator, which is defined as \begin{align} \mathcal{L}_{\text{cyc}, G}(F) &= \mathbb{E}_{x \sim p_\text{data}(x)}[\lVert F(G(x)) - x \rVert_1], \\ \mathcal{L}_{\text{cyc}, F}(G) &= \mathbb{E}_{y \sim p_\text{data}(y)}[\lVert G(F(y)) - y \rVert_1]. \end{align} This cycle-consistency loss is used to induce a sample $x_i$ to be mapped to a desired sample $y_j$. Note that the adversarial loss guarantees that via a learned mapping function samples in a domain $X$ are mapped to samples in a domain $Y$, but the learned mapping function cannot translate a sample $x_i$ to a intended $y_j$. In other words, the adversarial loss can guarantee translation between data distributions. Hence, to obtain a mapping function between individual samples, the cycle-consistency loss should be used in the training procedure for generators. \textbf{Multi-Scale Discriminators' Feature Loss}: multiple discriminators are utilized to distinguish between a sample $y_j$ and a synthesized output $G(x_i)$ \cite{Park_19}. $M$ Discriminators are trained to distinguish $y_j$ and $G(x_i)$ at $M$ different scales, which allows each discriminator to examine $y_j$ and $G(x_i)$ at a different view. As the size of $y_j$ and $G(x_i)$ becomes smaller, a discriminator has a wider view of $y_j$ and $G(x_i)$ since receptive field sizes of all the discriminators are the same. By using multiple discriminators, for a generator $G^\text{s}$, a GAN feature matching loss is defined as follows. \if\mycmd1 \begin{equation} \label{eq:loss_FM_G} \mathcal{L}_{\text{FM}, G^\text{s}}(D_{X,1}^\text{s}, \ldots, D_{X,M}^\text{s}) = \sum_{k=1}^{M} \frac{1}{M} \mathbb{E}_{(y,x)} \Bigl [ \sum_{i=1}^{T} \frac{1}{N_i} \lVert D_{X,k}^{\text{s}, i}(x) - D_{X,k}^{\text{s}, i}(G^\text{s}(y)) \rVert_{1} \Bigr ], \end{equation} \else \begin{align} \label{eq:loss_FM_G} \!\!\!\!&\mathcal{L}_{\text{FM}, G^\text{s}}(D_{X,1}^\text{s}, \ldots, D_{X,M}^\text{s}) \nonumber \\ \!\!\!\!&= \!\! \sum_{k=1}^{M} \!\frac{1}{M} \mathbb{E}_{(y,x)} \!\Bigl [ \sum_{i=1}^{T} \frac{1}{N_i} \lVert D_{X,k}^{\text{s}, i}(x) \!-\! D_{X,k}^{\text{s}, i}(G^\text{s}(y)) \rVert_{1} \! \Bigr ], \end{align} \fi where $\mathbb{E}_{(y, x) \sim p_\text{data}(y, x)} \triangleq \mathbb{E}_{(y,x)}$ for simplicity. $M$ is the number of discriminators, $D_{X, k}^\text{s}(\cdot)$ is the $M$-th discriminator, and $D_{X, k}^{\text{s}, i}$ is denoted as the $i$-th layer feature extractor of $D_{X, k}^\text{s}(\cdot)$. $N_i$ means the number of elements in each layer, and $T$ is the number of feature layers. Note that $G^\text{s}$ can learn how to translate a semantic image to a photorealistic image at both coarse and fine views since discriminators distinguish $x$ and $G^\text{s}(y)$ at $M$ different views. \textbf{VGG Perceptual Loss}: the work \cite{Park_19} utilizes the perceptual loss in \cite{Johnson_16}. The VGG perceptual loss is obtained by the 19-layer VGG network \cite{vgg}. The VGG perceptual loss is defined as \if\mycmd1 \begin{equation} \label{eq:loss_VGG_G} \mathcal{L}_\text{VGG}(\psi, x, G^\text{s}(y))=\sum_{i \in S_\text{I}} \frac{1}{C_i H_i W_i}\lVert \psi_i(G^\text{s}(y)) - \psi_i(x) \rVert_{1}, \end{equation} \else \begin{equation} \label{eq:loss_VGG_G} \mathcal{L}_\text{VGG}(\psi, x, G^\text{s}(y))=\sum_{i \in S_\text{I}} \frac{\lVert \psi_i(G^\text{s}(y)) - \psi_i(x) \rVert_{1}}{C_i H_i W_i}, \end{equation} \fi where $S_\text{I}$ is the set including VGG's layer indexes, $\psi$ is the 19-layer VGG network and $\psi_i$ is denoted as the $i$-th layer of $\psi$. For $\psi_i$, $C_i$, $H_i$, and $W_i$ are the number of channels, the height, and the width, respectively. By minimizing $\mathcal{L}_\text{VGG}(\cdot)$, $G^\text{s}$ can generate a photorealistic image $G^\text{s}(y)$, visually indistinguishable from $x$ in the feature-level perspective. \subsection{Our Modifications for Anonymization System} \subsubsection{Modification on Segmentation Generator's Loss} The goal of a segmentation generator $G$ is to generate semantic images with which a synthesis generator $G^\text{s}$ makes well-synthesized images. \textbf{Modification}: to consider the performance of $G^\text{s}$ in the loss of $G$, we define the loss of $G$ as follows. \begin{align} \label{eq:loss_G_segmentation} &\mathcal{L}_{G}(G, F, D_Y, G^\text{s}) \nonumber\\ &= \underbrace{\mathcal{L}_\text{\text{adv}, G}(G, D_Y, X, Y) + \lambda_\text{cyc} \mathcal{L}_{\text{cyc}, G}(F)}_{\text{the original loss of $G$}} \nonumber \\ & + \underbrace{\lambda_\text{s} \mathcal{L}_{G^\text{s}}(G^\text{s}, D_{X, 1}^\text{s}, \ldots ,D_{X, M}^\text{s}, G) + \lambda_\text{dist} \mathcal{L}_\text{dist}(G)}_{\text{the newly added term}}, \end{align} where $\mathcal{L}_\text{dist}(G) = \mathbb{E}_{x \sim p_\text{data}(x)}[\lVert G(x)-y \rVert_{1}]$, and $\mathcal{L}_\text{dist}(G)$ could further reduce the space of possible mapping functions with $\mathcal{L}_{\text{cyc}, G}(F)$. $\mathcal{L}_{G^\text{s}}$ is the loss of a synthesis generator $G^\text{s}$, and will be explained in Section~\ref{sec:Modifications_on_Synthesis} in detail. In addition, $\lambda_\text{cyc}, \lambda_\text{s}$, and $\lambda_\text{dist}$ control the relative importance of each loss. By adding $\mathcal{L}_{G^\text{s}}(G^\text{s}, D_{X, 1}^\text{s}, \ldots ,D_{X, M}^\text{s}, G)$, the generator $G$ will be trained to generate a semantic image minimizing the loss of $G^\text{s}$. \textbf{Objective of Segmentation Learning Part}: Hence, the full objective of segmentation-learning part is defined as: \if\mycmd1 \begin{align} \label{eq:objective_segmentation} \mathcal{L}_\text{seg}(G, F, D_X, D_Y, G^\text{s}) &= \mathcal{L}_{G}(G, F, D_Y, G^\text{s}) + \mathbb{E}_{y\sim p_\text{data}(y)}[D_Y(y)] \nonumber \\ &+ \mathcal{L}_{F}(G, F, D_X) +\mathbb{E}_{x\sim p_\text{data}(x)}[D_X(x)], \end{align} \else \begin{align} \label{eq:objective_segmentation} &\mathcal{L}_\text{seg}(G, F, D_X, D_Y, G^\text{s}) \nonumber \\ &= \mathcal{L}_{G}(G, F, D_Y, G^\text{s}) + \mathbb{E}_{y\sim p_\text{data}(y)}[D_Y(y)] \nonumber \\ &+ \mathcal{L}_{F}(G, F, D_X) +\mathbb{E}_{x\sim p_\text{data}(x)}[D_X(x)], \end{align} \fi where $\mathcal{L}_{F}(G,\! F,\! D_X) \!\!=\!\! \mathcal{L}_{\text{adv}, F}(F, \!D_X, \!Y, \!X) + \lambda_\text{cyc} \mathcal{L}_{\text{cyc}, F}(G)$. The segmentation learning part will solve (\ref{eq:objective_segmentation}) as follows: \begin{equation} \label{eq:solve_segmentation_objective} G^{*}, F^{*} = \operatornamewithlimits{argmin}\limits_{G, F} \max_{D_X, D_Y} \mathcal{L}_\text{seg}(G, F, D_X, D_Y, G^\text{s}). \end{equation} \subsubsection{Modifications on Synthesis Generator's Loss} \label{sec:Modifications_on_Synthesis} There are two main challenges to hinder the learning of synthesis generator to anonymize faces. We introduce loss of a synthesis generator $G^\text{s}$, and then explain each challenge. To obtain a synthesis generator to achieve our system purpose, we have a modification on the loss of $G^\text{s}$ and the loss of $D_{X,k}^\text{s}, \forall k$. In addition, we modify the way to train the discriminator $D_{X,k}^\text{s}$. In \cite{Park_19}, by using (\ref{eq:loss_adv_G}), (\ref{eq:loss_FM_G}), and (\ref{eq:loss_VGG_G}), the loss of a synthesis generator can be written as \if\mycmd1 \begin{align} \label{eq:loss_G_synthesis} \mathcal{L}_{G^\text{s}}(G^\text{s}, D_{X,1}^\text{s}, \ldots D_{X,M}^\text{s}, G) &= \sum_{k=1}^{M} \frac{1}{M} \Bigl \{ \mathcal{L}_{\text{adv}, G^\text{s}}(G^\text{s}, D_{X, k}^\text{s}, Y, X, G(x)) + \mathcal{L}_{\text{FM}, G^\text{s}}(D_{X,k}^\text{s}) \Bigr \} \nonumber \\ &+ \mathcal{L}_\text{VGG}(\psi, x, G^\text{s}(G(x))), \end{align} \else \begin{align} \label{eq:loss_G_synthesis} &\mathcal{L}_{G^\text{s}}(G^\text{s}, D_{X,1}^\text{s}, \ldots D_{X,M}^\text{s}, G) \nonumber \\ &=\!\! \sum_{k=1}^{M} \! \frac{1}{M} \Bigl \{ \! \mathcal{L}_{\text{adv}, G^\text{s}}(G^\text{s}, D_{X, k}^\text{s}, Y, X, G(x)) + \mathcal{L}_{\text{FM}, G^\text{s}}(D_{X,k}^\text{s}) \! \Bigr \} \nonumber \\ &+ \mathcal{L}_\text{VGG}(\psi, x, G^\text{s}(G(x))), \end{align} \fi where we introduce for simplicity $\mathcal{L}_{\text{FM}, G^\text{s}}(D_{X,k}^\text{s})=\mathbb{E}_{(y,x)} \Bigl [ \sum_{i=1}^{T} \frac{1}{N_i} \lVert D_{X,k}^{\text{s}, i}(x) - D_{X,k}^{\text{s}, i}(G^\text{s}(y)) \rVert_{1} \Bigr ]$ in (\ref{eq:loss_FM_G}). In addition, $\mathcal{L}_{\text{adv}, G^\text{s}}(G^\text{s}, D_{X, k}^\text{s}, Y, X, G(x))$ is redefined as \if\mycmd1 \begin{equation} \label{eq:loss_synthesis_G_redefined} \mathcal{L}_{\text{adv}, G^\text{s}}(G^\text{s}, D_{X, k}^\text{s}, Y, X, G(x)) = \mathbb{E}_{y\sim p_\text{data}(y)} \Bigl [\text{log}(1-D_{X,k}^\text{s}(G^\text{s}(G(x)))) \Bigr ]. \end{equation} \else \begin{align} \label{eq:loss_synthesis_G_redefined} &\mathcal{L}_{\text{adv}, G^\text{s}}(G^\text{s}, D_{X, k}^\text{s}, Y, X, G(x)) \nonumber \\ &= \mathbb{E}_{\hat{y}\sim p_\text{data}(y)} \Bigl [\text{log}(1-D_{X,k}^\text{s}(G^\text{s}(\hat{y}))) \Bigr ], \end{align} \fi where $\hat{y}=G(x)$. \textbf{Challenge in VGG Perceptual Loss}: in the synthesis-learning part, the loss (\ref{eq:loss_G_synthesis}) should be minimized to train the generator $G^\text{s}$. The minimization leads to reduce $\mathcal{L}_{\text{VGG}}(\psi, x, G^\text{s}(G(x)))$, and thus the distance between features of $x$ and $G^\text{s}(G(x))$ is also reduced during the training of $G^\text{s}$. As a result, the generator $G^\text{s}$ is trained to generate a photorealistic image $G^\text{s}(G(x))$ that can be almost the same as the original photorealistic image $x$. This trained generator cannot be utilized for our face-anonymizing system. \textbf{Modification on VGG Perceptual Loss}: to prevent the distance between $G^\text{s}(G(x))$ and $x$ from being reduced to a very small value, we introduce margins to the VGG perceptual loss (\ref{eq:loss_VGG_G}) as follows. \if\mycmd1 \begin{equation} \label{eq:loss_VGG_G_with_margin} \mathcal{L}_\text{VGG}(\psi, x, G^\text{s}(y), S_\text{I})=\sum_{i \in S_\text{I}} \max \Bigl (0, \frac{1}{C_i H_i W_i} \lVert \psi_i(G^\text{s}(y)) - \psi_i(x) \rVert_{1} - \epsilon_{m(i)} \Bigr), \end{equation} \else \begin{align} \label{eq:loss_VGG_G_with_margin} &\mathcal{L}_\text{VGG}(\psi, x, G^\text{s}(y), S_\text{I})\nonumber \\ &=\sum_{i \in S_\text{I}} \max \Bigl (0, \frac{\lVert \psi_i(G^\text{s}(y)) - \psi_i(x) \rVert_{1}}{C_i H_i W_i} - \epsilon_{m(i)} \Bigr), \end{align} \fi where $\Upsilon = \{ \epsilon_1, \ldots, \epsilon_{|S_\text{I}|} \}$ and $|S_\text{I}|$ is the number of elements in $S_\text{I}$. $m(i)$ is a mapping function to find for $S_\text{I}$ a VGG's layer index corresponding to $i$. Note that a margin value allows the distance between the $i$-th VGG layers for $x$ and $G^\text{s}(G(x))$ to be at least $\epsilon_i$ value. Hence, a photorealistic image $G^\text{s}(G(x))$ can have different features from features of the original image $x$, which could make $G^\text{s}(G(x))$ look different from $x$. \textbf{Challenge in Adversarial Loss and Multi-Scale Discriminators' Feature Loss}: to explain our additional modifications, we need to comprehend about how a discriminator $D_{X, k}^\text{s}$ works. Based on the understanding, we describe a hindrance to the learning of our synthesis generator $G^\text{s}$. In addition, we modify the adversarial losses of $G^\text{s}$ and $D_{X, k}^\text{s}$, and the multi-scale discriminators' feature loss of $G^\text{s}$. To minimize (\ref{eq:loss_synthesis_G_redefined}), $G^\text{s}$ should make a synthesized face $G^\text{s}(G(x))$ look like a face in the training dataset, and thus tends to translate $G(x)$ to $x$ that is what our system should anonymize. Specifically, in (\ref{eq:loss_synthesis_G_redefined}), a discriminator $D_{X,k}^\text{s}$ examines $G^\text{s}(G(x))$ to determine if $G^\text{s}(G(x))$ is from the training dataset $X$ or is arbitrarily generated. The generated image $G^\text{s}(G(x))$ contains an entire face, and thus $D_{X,k}^\text{s}$ is trained to determine whether the entire face in $G^\text{s}(G(x))$ is from the training dataset. As a result, to deceive $D_{X,k}^\text{s}$, $G^\text{s}$ is trained to generate $x$ from $G(x)$. \textbf{Modifications on Adversarial Loss and Multi-Scale Discriminators' Feature Loss}: to prevent that $G^\text{s}$ regenerates the almost same face as $x$, we have modification on the adversarial losses of $G^\text{s}$ and $D_{X,k}^\text{s}$. The reason that $G^\text{s}$ reproduces $x$ is because a discriminator $D_{X,k}^\text{s}$ examines if the entire face in $G^\text{s}(G(x))$ is from a training dataset including $x$. In other words, to deceive $D_{X,k}^\text{s}$ checking an entire face, $G^\text{s}$ necessarily makes a face from the domain $X$, which greatly reduces the space of possible mapping. In addition, $G^\text{s}$ should produce a photorealistic face by maintaining the shape and location of each facial part in a semantic-face image, which also further reduces the space of possible mapping. For expanding the space of possible mapping, we limit a discriminator $D_{X,k}^\text{s}$ to investigate each facial component, not entire face. By applying the idea, the adversarial loss is rewritten as follows. \if\mycmd1 \begin{align} \label{eq:loss_adv_synthesis_modified} \mathcal{L}_\text{adv}^{s}(G^\text{s}, D_{X,1}^\text{s}, \ldots, D_{X,M}^\text{s}, Y, X, S_\xi) &= \sum_{k=1}^{M} \frac{1}{M} \Bigl \{ \mathbb{E}_{y\sim p_\text{data}(y)} \Bigl [ \sum_{i\in S_{\xi}} \frac{1}{|S_{\xi}|} \text{log}(1-D_{X,k}^\text{s}(\xi_{i}(G^\text{s}(\hat{y})))) \Bigr ] \Bigr \} \nonumber \\ &+ \sum_{k=1}^{M} \frac{1}{M} \Bigl \{ \mathbb{E}_{x\sim p_\text{data}(x)} \Bigl [ \sum_{i\in S_{\xi}} \frac{1}{|S_{\xi}|} \text{log}(D_{X,k}^\text{s}(\xi_i(x))) \Bigr ] \Bigr \}, \end{align} \else \begin{align} \label{eq:loss_adv_synthesis_modified} &\mathcal{L}_\text{adv}^{s}(G^\text{s}, D_{X,1}^\text{s}, \ldots, D_{X,M}^\text{s}, Y, X, S_\xi) \nonumber \\ &= \sum_{k=1}^{M}\! \frac{1}{M} \! \Bigl \{ \mathbb{E}_{y\sim p_\text{data}(y)} \Bigl [ \sum_{i\in S_{\xi}} \!\!\frac{1}{|S_{\xi}|} \text{log}(1\!-\!D_{X,k}^\text{s}(\xi_{i}(G^\text{s}(\hat{y})))) \Bigr ] \! \Bigr \} \nonumber \\ &+ \sum_{k=1}^{M} \frac{1}{M} \Bigl \{ \mathbb{E}_{x\sim p_\text{data}(x)} \Bigl [ \sum_{i\in S_{\xi}} \frac{1}{|S_{\xi}|} \text{log}(D_{X,k}^\text{s}(\xi_i(x))) \Bigr ] \Bigr \}, \end{align} \fi where we denote the output of our segmentation generator as $\hat{y}=G(x)$, $\xi_i$ is the extractor to extract pixels corresponding to the label index $i$, $S_{\xi}$ is the set including extracted labels' index, and $|S_{\xi}|$ is the number of elements in $S_\xi$. For example, if $i=2$ and the label index 2 indicates a nose in a face, all pixels in $\xi_2(G^\text{s}(\hat{y}))$ become zero except for the pixels corresponding to the nose. According to (\ref{eq:loss_adv_synthesis_modified}), our modification allows a discriminator $D_{X,k}^\text{s}$ to examine a part of a face instead of observing all facial parts at a time. This approach allows discriminators to learn the distribution of each facial component instead of learning the distribution of an entire face. Hence, a discriminator tries to distinguish each part of a face in $G^\text{s}(\hat{y})$ from that of a face in $x$, which could widen the space of possible mapping in the entire face's point of view. In addition, by setting $|S_\xi|<N_\text{f}$ where $N_\text{f}$ denotes the number of labels in a face, we make discriminators observe some parts of an entire face, and thus the generator $G^\text{s}$ could have wider space of possible mapping for the other parts not examined by discriminators. \if\mycmd1 In the same vein, the multi-scale discriminators' feature loss can be also redefined as \begin{equation} \label{eq:loss_multi_scale_disc_feature_modified} \mathcal{L}_{\text{FM}, G^\text{s}}(D_{X,1}^\text{s}, \ldots, D_{X,M}^\text{s}, S_\xi) = \sum_{k=1}^{M} \frac{1}{M} \underbrace{\mathbb{E}_{(y,x)} \Bigl [ \sum_{i=1}^{T} \frac{1}{N_i} \sum_{j\in S_\xi} \frac{1}{|S_\xi|} \lVert D_{X,k}^{\text{s}, i}(\xi_j(x)) - D_{X,k}^{\text{s}, i}(\xi_j(G^\text{s}(\hat{y}))) \rVert_{1} \Bigr ]}_{\mathcal{L}_{\text{FM},G^\text{s}}(D_{X,k}^\text{s}, S_\xi)}. \end{equation} \else In the same vein, the multi-scale discriminators' feature loss can be also redefined as (\ref{eq:loss_multi_scale_disc_feature_modified}). \begin{figure*} \begin{align} \label{eq:loss_multi_scale_disc_feature_modified} &\mathcal{L}_{\text{FM}, G^\text{s}}(D_{X,1}^\text{s}, \ldots, D_{X,M}^\text{s}, S_\xi) = \sum_{k=1}^{M} \frac{1}{M} \underbrace{\mathbb{E}_{(y,x)} \Bigl [ \sum_{i=1}^{T} \frac{1}{N_i} \sum_{j\in S_\xi} \frac{1}{|S_\xi|} \lVert D_{X,k}^{\text{s}, i}(\xi_j(x)) D_{X,k}^{\text{s}, i}(\xi_j(G^\text{s}(\hat{y}))) \rVert_{1} \Bigr ]}_{\mathcal{L}_{\text{FM},G^\text{s}}(D_{X,k}^\text{s}, S_\xi)}. \end{align} \end{figure*} \fi In spite of our modifications on $\mathcal{L}_\text{adv}^\text{s}(\cdot)$ and $\mathcal{L}_{\text{FM}, G^\text{s}}(\cdot)$, there is still room for $G^\text{s}$ to learn to regenerate $x$ since $\mathcal{L}_{\text{FM},G^\text{s}}(D_{X,k}^\text{s}, S_\xi)$ still compares features of $G^\text{s}(G(x))$ and $x$, which are extracted by $D_{X,k}^\text{s}$. \if\mycmd1 Hence, we slightly modify (\ref{eq:loss_multi_scale_disc_feature_modified}) as follows. \begin{align} \label{eq:loss_multi_scale_disc_feature_modified_2} \mathcal{L}_{\text{FM}, G^\text{s}}(D_{X,1}^\text{s}, \ldots, D_{X,M}^\text{s}, S_\xi) = \sum_{k=1}^{M} \frac{1}{M} \underbrace{\mathbb{E}_{(y,x,\tilde{x})} \Bigl [ \sum_{i=1}^{T} \frac{1}{N_i} \sum_{j\in S_\xi} \frac{1}{|S_\xi|} \lVert D_{X,k}^{\text{s}, i}(\xi_j(\tilde{x})) - D_{X,k}^{\text{s}, i}(\xi_j(G^\text{s}(\hat{y}))) \rVert_{1} \Bigr ]}_{\mathcal{L}_{\text{FM},G^\text{s}}(D_{X,k}^\text{s}, S_\xi)}, \end{align} where $\tilde{x} \neq x$ but $\tilde{x}$ is in the same training dataset of $x$. By the modification, $\mathcal{L}_{\text{FM},G^\text{s}}(D_{X,k}^\text{s}, S_\xi)$ compares features of $G^\text{s}(G(x))$ to features of $\tilde{x}$, which can help $G\text{s}$ learning to generate a different face from $x$. \else Hence, we slightly modify (\ref{eq:loss_multi_scale_disc_feature_modified}) to (\ref{eq:loss_multi_scale_disc_feature_modified_2}). \begin{figure*} \begin{align} \label{eq:loss_multi_scale_disc_feature_modified_2} \mathcal{L}_{\text{FM}, G^\text{s}}(D_{X,1}^\text{s}, \ldots, D_{X,M}^\text{s}, S_\xi) = \sum_{k=1}^{M} \frac{1}{M} \underbrace{\mathbb{E}_{(y,x,\tilde{x})} \Bigl [ \sum_{i=1}^{T} \frac{1}{N_i} \sum_{j\in S_\xi} \frac{1}{|S_\xi|} \lVert D_{X,k}^{\text{s}, i}(\xi_j(\textcolor{blue}{\tilde{x}})) - D_{X,k}^{\text{s}, i}(\xi_j(G^\text{s}(\hat{y}))) \rVert_{1} \Bigr ]}_{\mathcal{L}_{\text{FM},G^\text{s}}(D_{X,k}^\text{s}, S_\xi)}, \end{align} \noindent\makebox[\linewidth]{\rule{17cm}{0.4pt}} \end{figure*} In (\ref{eq:loss_multi_scale_disc_feature_modified_2}), $\mathbb{E}_{(x,y,\tilde{x})\sim p_\text{data}(x, y, x)} \triangleq \mathbb{E}_{x,y,\tilde{x}}$, and $\tilde{x} \neq x$ but $\tilde{x}$ is from the same training dataset of $x$. By the modification, $\mathcal{L}_{\text{FM},G^\text{s}}(D_{X,k}^\text{s}, S_\xi)$ compares features of $G^\text{s}(G(x))$ to features of $\tilde{x}$, which can help $G^\text{s}$ learning to generate a different face from $x$. \fi \textbf{Objective of Synthesis Learning Part}: Based on (\ref{eq:loss_VGG_G_with_margin}), (\ref{eq:loss_adv_synthesis_modified}), and (\ref{eq:loss_multi_scale_disc_feature_modified_2}), our full objective of synthesis-learning part is defined as: \if\mycmd1 \begin{align} \label{eq:objective_synthesis_learning} \mathcal{L}_\text{syn}(G^\text{s}, D_{X,1}^\text{s}, \ldots, D_{X,M}^\text{s}, S_\xi, G) &= \mathcal{L}_\text{adv}^\text{s}(G^\text{s}, D_{X,1}^\text{s}, \ldots, D_{X,M}^\text{s}, Y, X, S_\xi) + \mathcal{L}_{\text{FM}, G^\text{s}}(D_{X,1}^\text{s}, \ldots, D_{X,M}^\text{s}, S_\xi) \nonumber \\ &+ \mathcal{L}_\text{VGG}(\psi, x, G^\text{s}(y), S_\text{I}) + \mathcal{L}_{\text{cyc}, G^\text{s}}(G), \end{align} \else \begin{align} \label{eq:objective_synthesis_learning} &\mathcal{L}_\text{syn}(G^\text{s}, D_{X,1}^\text{s}, \ldots, D_{X,M}^\text{s}, S_\xi, G) \nonumber \\ &= \mathcal{L}_\text{adv}^\text{s}(G^\text{s}, D_{X,1}^\text{s}, \ldots, D_{X,M}^\text{s}, Y, X, S_\xi) \nonumber \\ &+ \mathcal{L}_{\text{FM}, G^\text{s}}(D_{X,1}^\text{s}, \ldots, D_{X,M}^\text{s}, S_\xi) \nonumber \\ &+ \mathcal{L}_\text{VGG}(\psi, x, G^\text{s}(y), S_\text{I}) + \mathcal{L}_{\text{cyc}, G^\text{s}}(G), \end{align} \fi where $\mathcal{L}_{\text{cyc}, G^\text{s}}(G) = \mathbf{E}_{x \sim p_\text{data}(x)}[\lVert G(G^\text{s}(G(x))) - G(x) \rVert_{1}]$ that allows a synthesized image $G^\text{s}(G(x))$ to maintain the shape and location of each facial part in $x$. Since (\ref{eq:loss_multi_scale_disc_feature_modified_2}) compares features of $G^\text{s}(G(x))$ to those of $\tilde{x}$, the generator $G^\text{s}$ can make a synthesized image to remain the shape and location of each facial part in $\tilde{x}$ not in $x$. Hence, $\mathcal{L}_{\text{cyc}, G^\text{s}}(G)$ helps $G^\text{s}$ to generate synthesized images to remain the shape and location of facial parts in $x$. Hence, by $\mathcal{L}_{\text{cyc}, G^\text{s}}(G)$ and (\ref{eq:loss_multi_scale_disc_feature_modified_2}), $G^\text{s}$ can generate a synthesized face $G^\text{s}(G(x))$ including facial features of $\tilde{x}$ while maintaining the shape and location of facial components in $x$. Finally, the synthesis learning part will solve (\ref{eq:objective_synthesis_learning}) as follows: \begin{equation} (G^\text{s})^* = \operatornamewithlimits{argmin}\limits_{G^\text{s}} \max\limits_{D_{X,k}^\text{s},\forall k} \mathcal{L}_\text{syn}(G^\text{s}, D_{X,1}^\text{s}, \ldots, D_{X,M}^\text{s}, S_\xi, G). \end{equation} \subsection{Training Procedure and Details} \input{Algorithm_Training_Procedure} \textbf{Procedure}: The overall training procedure is summarized in Algorithm~\ref{alg:training_procedure}, where $N_\text{data}$ is the number of data in the dataset $X$ and $Y$. By repeating the training procedure, we obtain the optimized $G^*$ and $(G^\text{s})^*$. \textbf{Details}: In segmentation learning part, for the segmentation generator $G$, we adopt the network architecture in \cite{Johnson_16} that is known for powerful neural-type transfer and use 9 resnet blocks for $256 \times 256$ images, which is applied equally to the generator $F$. For the discriminators $D_X$ and $D_Y$, we use $70 \times 70$ PatchGANs \cite{Isola_17, Li_16, Ledig_17, Zhu_17}. In synthesis learning part, we construct our network architecture by applying the Spectrum Norm \cite{Spectrum_Norm} to all the layers in both generator and discriminator. For our synthesis generator, we use the SPADE generator in \cite{Park_19}. Finally, we set $M=3$ for our discriminators. For our training, we set $\lambda_\text{cyc}, \lambda_\text{s}, \lambda_\text{dist}$ to $10$ in (\ref{eq:loss_G_segmentation}). A solver is set to the ADAM solver \cite{ADAM} with a batch size of 1. For the solver, $\beta_1=0.5$ and $\beta_2=0.999$ in segmentation learning part and $\beta_1=0$ and $\beta_2=0.999$ in synthesis learning part. \textbf{Training Dataset}: We conduct our training procedure with CelebA-HQ dataset \cite{CelebAMask-HQ}. This dataset contains 30,000 high-resolution face images with 19 semantic classes. In this work, we modify the semantic dataset by extracting 10 main facial components. In our modified semantic dataset, semantic classes include skin, nose, eyes, eyebrows, ears, mouth, lip, hair, neck, and eyeglass. In addition, we utilize a face detector to crop a face in high-resolution face images. The reason that cropped face images are needed is that in our system faces in a video frame will be detected by using a face detector. By conducting this preprocessing, we can train segmentation and synthesis generators, optimized for our system. Moreover, we create and use various resolution images for a image. Our segmentation generator requires a specific sized image as input, and thus detected face images should be resized to the specific size. If the size of a detected face is smaller than the required size, a resized face image is low resolution. In reality, our system can detect a face in various sizes, various resolutions. To make our segmentation and synthesis generators work well with various resolutions, we utilize various resolution images for a face image during our training procedure. \subsection{Face-Anonymizing Algorithm} \input{Algorithm_Face_Anonymizing} With the optimized segmentation and synthesis generators, our face-anonymizing procedure is conducted as in Algorithm~\ref{alg:face_anonymizing_algorithm}. A companion computer conducts Algorithm~\ref{alg:face_anonymizing_algorithm} whenever it receives a video frame. $f_\text{D}$ denotes detected faces, $N_\text{face}$ is the number of detected faces, $f_\text{A}$ includes all anonymized faces, and $R_\text{thr}$ is a threshold for the ratio of the face size to the image size. Note that $f_\text{D}$ and $f_\text{A}$ also include the background as well as faces. \textbf{Maintenance of Background}: In Algorithm~\ref{alg:face_anonymizing_algorithm}, $B(\cdot)$ is a function that makes all nonzero elements in a input semantic image 1. In a semantic image, zero indicates the background. $B^{-1}(\cdot)$ is the opposite function of $B(\cdot)$. Hence, in Algorithm~\ref{alg:face_anonymizing_algorithm}, \textcircled{1} creates a image that mixes the anonymized face in $f_\text{A}$ and the background in $f_\text{D}$, which could preserve the background in the original image. \textbf{Repetitive Face Detection}: In Algorithm \ref{alg:face_anonymizing_algorithm}, we repeat to conduct the face detector with detected faces until the size of a face in $f_\text{D}$ occupies $R_\text{thr}\times100$ of the size of $f_\text{D}$. The reason for this repetitive detection is that our generators well anonymize a input image that is full of one face. \begin{figure}[!t] \centering \includegraphics[width=1\columnwidth]{Repetitive_Detection.eps} \caption{Bounding box regression and NMS} \label{Fig:Repetitive_Detection} \end{figure} The face detector finds a face with the bounding box regression and non-maximum suppression (NMS). The bounding box regression provides several bounding boxes (red boxes) on a face in Fig.~\ref{Fig:Repetitive_Detection}(a). Then, NMS trims the bounding boxes to obtain a bounding box (the yellow box) in Fig.~\ref{Fig:Repetitive_Detection}(b). In Fig.~\ref{Fig:Repetitive_Detection}(c), however, the resultant image is not suitable as input for our generators. Hence, to increase the ratio of the face size to the image size, we repeatedly conduct the face detector on a face until we obtain a image in Fig.~\ref{Fig:Repetitive_Detection}(d). \subsection{Drone Patrol System} The drone system consists of the following components: (1) Drone control computer operating motors so that the drone can move physically, (2) Companion computer conducting face-anonymizing neural networks and performing SLAM, (3) Wireless chipset receiving commands from the ground station and transmitting anonymized video frames to it, (4) High-resolution camera recording a video; In our drone, the companion computer is connected with the drone control computer, the wireless chipset, and the high-resolution camera. We utilize ROS to allow all the components to communicate with each other. Via wireless communication, the companion computer communicates with the ground station. The ground station can transmit a command message to the companion computer. The companion computer sends the received message to drone control computer controls. The moving drone continuously records images via the camera, which is passed to our face-anonymzing networks implemented in the companion computer. The anonymized images are sent back to the ground station via the wireless chipset, and thus we can immediately check the results on the screen of the ground station. At the same time, the anonymized images are processed by the ORB-SLAM2 algorithm. \subsection{Face-Anonymizing Generators Evaluation} \textbf{Face Detection}: Our system utilizes a lightweight but accurate face detector, called FaceBoxes \cite{zhang2017faceboxes}. The computing speed is invariant no matter how many faces are in a image, and the accuracy was verified with various face datasets. \textbf{Test Dataset}: We test our face-anonymizing generators on several datasets. \begin{itemize} \item \textit{CelebA-HQ}: This dataset contains 30,000 high-resolution face images. We randomly select 1,500 images for our test. Note that the remaining 28,500 images are used for the training. \item \textit{Helen}: This dataset has 2,330 face images \cite{Helen}. In addition, this provides 2,330 annotation images to locate 8 facial components, which are skin, eyebrow, eye, nose, lip, inner mouth, and hair. \item \textit{Facescrub}: This dataset is large face datset, which contains 106,863 face images of male and female 530 celebrities \cite{Facescrub}. \item \textit{FaceForensic}: This dataset provides 1000 video sequences, which has been sourced from 977 youtube videos \cite{roessler2019faceforensicspp}. All videos contain a mostly frontal face without occlusions. \end{itemize} \textbf{Qualitative Evaluation of Face Anonymization}: \begin{figure}[t] \centering \includegraphics[width=0.95\columnwidth]{Test_CelebA_0.eps} \vspace{-0.15in} \caption{Test Results on CelebA-HQ Dataset} \label{Fig:Result_CelebA-HQ_part} \vspace{-0.1in} \end{figure} \begin{figure}[t] \centering \includegraphics[width=0.95\columnwidth]{Test_Helen_0.eps} \vspace{-0.15in} \caption{Test Results on Helen Dataset} \label{Fig:Result_Helen_part} \vspace{-0.1in} \end{figure} \begin{figure}[t] \centering \includegraphics[width=0.95\columnwidth]{Test_FaceScrub_0.eps} \vspace{-0.15in} \caption{Test Results on FaceScrub Dataset} \label{Fig:Result_FaceScrub_part} \end{figure} Figs.~\ref{Fig:Result_CelebA-HQ_part}, \ref{Fig:Result_Helen_part}, and \ref{Fig:Result_FaceScrub_part} provide the quality of our face-anonymizing generators. We can confirm that our method produces well anonymized faces for diverse faces in CelebA-HQ, Helen, and FaceScrub dataset. For each dataset, the additional results are shown in Figs.~\ref{Fig:Result_CelebA-HQ}, \ref{Fig:Result_Helen}, and \ref{Fig:Result_FaceScrub}. \textbf{Quantitative Evaluation of Face Anonymization}: To evaluate our anonymization system quantitatively, we utilize siamese network \cite{siamese_net}. The siamese network is widely utilized to measure the dissimilarity between two images. Via the siamese network, we measure how dissimilar an anonymized face and an original face are. For our evaluation, we train a siamese network to calculate Euclidean distance between two faces. The larger the euclidean distance is, the more dissimilar two faces are. The inception resnet \cite{InceptionResnet} is adopted for the backbone network of the siamese network. We perform 50 epochs of training on the CASIA-WebFace dataset \cite{CASIA}, which includes about 500,000 images, and the image sizes are $256 \times 256$. \begin{table}[t] \centering \caption{Average Euclidean distance for each test dataset} \label{table:siamese_result} \begin{tabular}{|c||c|c||c|l|c|c|} \hline & \multicolumn{2}{c||}{Criterion} & \multicolumn{4}{c|}{Test Dataset} \\ \hline \multirow{3}{*}{\begin{tabular}[c]{@{}c@{}}Average\\ Euclidean\\ Distance\end{tabular}} & Same & Different & \multicolumn{2}{c|}{\multirow{2}{*}{\begin{tabular}[c]{@{}c@{}}CelebA\\ HQ\end{tabular}}} & \multirow{2}{*}{Helen} & \multirow{2}{*}{FaceScrub} \\ & person & people & \multicolumn{2}{c|}{} & & \\ \cline{2-7} & 1.15 & 2.13 & \multicolumn{2}{c|}{1.57} & 2.59 & 1.94 \\ \hline \end{tabular} \end{table} Table~\ref{table:siamese_result} presents the average Euclidean distance for each test dataset. In the criterion, the value for 'Same person' is average Euclidean distance between faces of the same person, and another value for 'Different people' is obtained between faces of different people. Those values are measured during training the siamese network. For each test dataset, the value is the average Euclidean distance between an original face and an anonymized face by our system. Note that the larger the value is, the more dissimilar two faces are. According to Table~\ref{table:siamese_result}, our anonymization system indeed can make a face that looks different from an original face. For all test dataset, the average Euclidean distance is larger than that of criterion. \begin{figure}[t] \centering \includegraphics[width=1\columnwidth]{Test_FaceForensic_3.eps} \caption{Test Results on FaceForensic Dataset via Algorithm~\ref{alg:face_anonymizing_algorithm}} \label{Fig:Result_FaceForensic_3} \end{figure} \begin{figure*}[t] \centering \includegraphics[width=1.8\columnwidth]{Demo_Desk_1.eps} \caption{SLAM Results on a original video and an anonymized video} \label{Fig:SLAM_Results_Desk} \vspace{-0.1in} \end{figure*} \begin{figure*}[t] \centering \includegraphics[width=2\columnwidth]{Demo_Drone.eps} \caption{Our face-anonymizing system results on drone} \label{Fig:Evaluation_on_drone} \vspace{-0.1in} \end{figure*} \begin{figure*}[t] \centering \includegraphics[width=2\columnwidth]{Demo_Drone_SLAM.eps} \caption{SLAM results on drone} \label{Fig:Evaluation_SLAM_on_drone} \vspace{-0.1in} \end{figure*} \subsection{Evaluation of Algorithm~\ref{alg:face_anonymizing_algorithm}} To test Algorithm~\ref{alg:face_anonymizing_algorithm}, we conduct our algorithm on FaceForensic video dataset. Fig.~\ref{Fig:Result_FaceForensic_3} presents results for various videos. In each result for 'original' and 'Anonymized', a enlarged face image is attached for readability. Those results confirm that our algorithm finds a face in a video frame, and then anonymizes the detected face well. The additional results are shown in Figs.~\ref{Fig:Result_FaceForensic_1} and \ref{Fig:Result_FaceForensic_2}. As a result, for various dataset, our privacy-protection drone vision system can remove privacy information of a person by anonymizing his/her face. \subsection{SLAM Results} In this section, we investigate the impact of our proposal on vision-based robot perception, ORB-SLAM2. Fig.~\ref{Fig:SLAM_Results_Desk} shows two types of results: \begin{itemize} \item \textit{Frames with SLAM's features} are obtained via ORB-SLAM2, in the upper figures of Fig.~\ref{Fig:SLAM_Results_Desk}. The resultant images include green boxes that are feature points extracted by ORB-SLAM2. The feature points indicate edges, lines, and corners of objects in a image. \item \textit{PointCloud2's results} are drawn via RVIZ \cite{pointcloud2, rviz} based on the extracted feature points. In the lower figures of Fig.~\ref{Fig:SLAM_Results_Desk}, the white points are stamped by the calculated distance between a ZED camera and extracted feature points. \end{itemize} In Fig.~\ref{Fig:SLAM_Results_Desk}, the upper figures present the comparison of feature extraction results on a original video frame and an anonymized video frame. In both frames, the feature points are well extracted. The extracted feature points of our anonymization scheme are almost the same as that of the original video. In addition, we can notice that the face is also anonymized well by our scheme. The lower figures present the distance between a camera and a face, measured by ORB-SLAM2. In the red circle, the white points are extracted from the face. Hence, the distance between those points and a ZED camera means the distance between the face and the camera. Under our scheme, the distance is almost the same as that under the original video. In summary, our anonymization scheme has no impact on the performance of ORB-SLAM2, which confirms that our system can preserve vision-based drone perception well. In the drone perception, inaccuracy can indeed incur an accident where a drone hits a person's face. Since our approach effectively protects the person's privacy with good perception, our anonymization scheme is certainly proper to privacy-protection drone patrol system. \subsection{Drone Hardware Setup} \textbf{Drone Hardware Specification}: We build a customized drone each component of which is as follows. We selected DJI F550 for our drone frame. 1137 T-motor V2 carbon fiber propeller and T-motor MN3110 KV 780 are selected as propellers and motors. T-motor Air 40A is chosen as electronic speed controllers. We utilize Holybro Pixhawk4 for our drone control computer. Finally, we selected ZED stereo camera for our high-resolution camera. \textbf{Experiments of Face-Anonymizing Networks with Nvidia Xavier}: NVIDIA Jetson Xavier is an machine-learning computer for autonomous machines with the high-computing power. Especially, this companion computer has a 512-core GPU, and thus it is indeed suitable for large-scale matrix operations which are needed for efficient neural networks computation. A 8800mah 4S1P LiPo battery was installed for power supply, which provides a voltage of 14.8V. \subsection{Our Face-Anonymizing System Result on Drone} Fig.~\ref{Fig:Evaluation_on_drone} shows our face-anonymizing system results on a video recorded in a drone. The drone is hovering in our laboratory, and a person is walking in front of the drone. From this result, we can confirm that our system can well anonymize a face with varying its size. Fig.~\ref{Fig:Evaluation_SLAM_on_drone} presents the comparison of feature extraction results on an original video and an anonymized video. Both videos confirm that the feature points are well extracted. In our anonymization scheme, the extracted feature points are almost the same as that of the original video. \begin{figure*}[t] \centering \includegraphics[width=0.7\paperwidth]{Test_FaceForensic_1.eps} \caption{Additional Test Results on FaceForensic Dataset via Algorithm~\ref{alg:face_anonymizing_algorithm}} \label{Fig:Result_FaceForensic_1} \end{figure*} \begin{figure*}[t] \centering \includegraphics[width=0.7\paperwidth]{Test_FaceForensic_2.eps} \caption{Additional Test Results on FaceForensic Dataset via Algorithm~\ref{alg:face_anonymizing_algorithm}} \label{Fig:Result_FaceForensic_2} \end{figure*} \begin{figure*}[t] \centering \includegraphics[width=0.7\paperwidth]{Test_CelebA.eps} \caption{Additional Test Results on CelebA-HQ Dataset} \label{Fig:Result_CelebA-HQ} \end{figure*} \begin{figure*}[t] \centering \includegraphics[width=0.7\paperwidth]{Test_Helen.eps} \caption{Additional Test Results on Helen Dataset} \label{Fig:Result_Helen} \end{figure*} \begin{figure*}[t] \centering \includegraphics[width=0.7\paperwidth]{Test_FaceScrub.eps} \caption{Additional Test Results on FaceScrub Dataset} \label{Fig:Result_FaceScrub} \end{figure*}
{'timestamp': '2020-06-01T02:06:43', 'yymm': '2005', 'arxiv_id': '2005.14390', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14390'}
arxiv
\section{Introduction} Simultaneous machine translation is the task of generating partial translations before observing the entire source sentence. The task fits scenarios such as live captioning and speech-to-speech translation, where the user expects a translation before the speaker finishes the sentence. Simultaneous MT has to balance between latency and translation quality. If more input is consumed before translation, quality is likely to improve due to increased context, but latency also increases. On the other hand, consuming limited input decreases latency, but degrades quality. There have been several approaches to solve simultaneous machine translation. In \citep{dalvi2018incremental,ma2019stacl}, a fixed policy is introduced to delay translation by a fixed number of words. Alternatively, \citet{satija2016simultaneous,gu2017learning,alinejad2018prediction} use reinforcement learning to learn a dynamic policy to determine whether to read or output words. \citet{cho2016sinmt} adapt the decoding algorithm without relying on additional components. However, these methods do not modify the training of the underlying NMT model. Instead, it is trained on full sentences. \citet{arivazhagan2019monotonic} introduce a holistic framework that relaxes the hard notion of read/write decisions at training time, allowing it to be trained jointly with the rest of the NMT model. In this paper, we integrate a source chunk boundary detection component into a bidirectional recurrent NMT model. This component corresponds to segmentation or read/write decisions in the literature. It is however trained jointly with the rest of the NMT model. We propose an algorithm to chunk the training data based on automatically learned word alignment. The chunk boundaries are used as a training signal along with the parallel corpus. The main contributions of this work are as follows: \begin{itemize} \item We introduce a source chunk boundary detection component and train it jointly with the NMT model. Unlike in \citep{arivazhagan2019monotonic}, our component is trained using hard decisions, which is consistent with inference. \item We propose a method based on word alignment to generate the source and target chunk boundaries, which are needed for training. \item We study the use of bidirectional vs unidirectional encoder layers for simultaneous machine translation. Previous work focuses mostly on the use of unidirectional encoders. \item We provide results using text and speech input. This is in contrast to previous work that only simulates simultaneous NMT on text input. \end{itemize} \section{Related Work} \citet{oda2014optimizing} formulate segmentation as an optimization problem solved using dynamic programming to optimize translation quality. The approach is applied to phrase-based machine translation. Our chunking approach is conceptually simpler, and we explore its use with neural machine translation. \citet{cho2016sinmt} devise a greedy decoding algorithm for simultaneous neural machine translation. They use a model that is trained on full sentences. In contrast, we train our models on chunked sentences to be consistent with the decoding condition. \citet{satija2016simultaneous}, \citet{alinejad2018prediction}, and \citet{gu2017learning} follow a reinforcement learning approach to make decisions as to when to read source words or to write target words. \citet{Zheng2019SimplerAF} propose the simpler approach to use the position of the reference target word in the beam of an existing MT system to generate training examples of read/write decisions. We extract such decisions from statistical word alignment instead. In \citet{ma2019stacl,dalvi2018incremental}, a wait-$k$ policy is proposed to delay the first target word until $k$ source words are read. The model alternates between generating $s$ target words and reading $s$ source words, until the source words are exhausted. Afterwards, the rest of the target words are generated. In addition, \citet{dalvi2018incremental} convert the training data into chunks of predetermined fixed size. In contrast, we train models that learn to produce dynamic context-dependent chunk lengths. The idea of exploiting word alignments to decide for necessary translation context can be found in several recent papers. \citet{arthur2020learning} train an agent to imitate read/write decisions derived from word alignments. In our architecture such a separate agent model is replaced by a simple additional output of the encoder. \citet{Xiong2019DuTongChuanCT} use word alignments to tune a pretrained language representation model to perform word sequence chunking. In contrast, our approach integrates alignment-based chunking into the translation model itself, avoiding the overhead of having a separate component and the need for a pretrained model. Moreover, in this work we improve on pure alignment-based chunks using language models (Section \ref{subsec:improved_chunking}) to avoid leaving relevant future source words out of the chunk. \citet{press2018noatt} insert $\epsilon$-tokens into the target using word alignments to develop an NMT model without an attention mechanism. Those tokens fulfill a similar purpose to \textit{wait} decisions in simultaneous MT policies. \newcite{arivazhagan2019monotonic} propose an attention-based model that integrates an additional monotonic attention component. While the motivation is to use hard attention to select the encoder state at the end of the source chunk, they avoid using discrete attention to keep the model differentiable, and use soft probabilities instead. The hard mode is only used during decoding. We do not have to work around discrete decisions in this work, since the chunk boundaries are computed offline before training, resulting in a simpler model architecture. \section{Simultaneous Machine Translation} The problem of offline machine translation is focused on finding the target sequence $e_1^I=e_1...e_I$ of length $I$ given the source sequence $f_1^J$ of length $J$. In contrast, simultaneous MT does not necessarily require the full source input to generate the target output. In this work, we formulate the problem by assuming latent monotonic chunking underlying the source and target sequences. Formally, let $s_1^K=s_1...s_k...s_K$ denote the chunking sequence of $K$ chunks, such that $s_k=(i_k,j_k)$, where $i_k$ denotes the target position of last target word in the $k$-th chunk, and $j_k$ denotes the source position of the last source word in the chunk. Since the source and target chunks are monotonic, the beginnings of the source and target chunks do not have to be defined explicitly. The chunk positions are subject to the following constraints: \begin{align} i_0 = j_0 = 0, & \ \ \ i_K = I, \ \ \ j_K = J, \nonumber \\ i_{k-1} < i_{k}, & \ \ \ j_{k-1} < j_{k}. \label{eq:constraints} \end{align} We use $\tilde{e}_k=e_{i_{k-1}+1}...e_{i_k}$ to denote the $k$-th target chunk, and $\tilde{f}_k=f_{j_{k-1}+1}...f_{j_k}$ to denote its corresponding source chunk. The target sequence $e_1^I$ can be rewritten as $\tilde{e}_1^K$, similarly, the source sequence can be rewritten as $f_1^J=\tilde{f}_1^K$. We introduce the chunk sequence $s_1^K$ as a latent variable as follows: \begingroup \allowdisplaybreaks \begin{align} &\;p(e_1^I|f_1^J) = \sum_{K,s_1^K} p(e_1^I,s_1^K|f_1^J) \label{eq:latent}\\ &= \sum_{K,s_1^K} p(\tilde{e}_1^K,s_1^K|\tilde{f}_1^K) \label{eq:rewrite}\\ &= \sum_{K,s_1^K} \prod_{k=1}^K p(\tilde{e}_k,s_k|\tilde{e}_1^{k-1}, s_1^{k-1}, \tilde{f}_1^K) \label{eq:chain} \\ &= \sum_{K,s_1^K} \prod_{k=1}^K p(i_k|\tilde{e}_1^{k}, s_1^{k-1}, j_k, \tilde{f}_1^K) \nonumber \\ & \hspace{16.5mm}\cdot p(\tilde{e}_k|\tilde{e}_1^{k-1}, s_1^{k-1}, j_k, \tilde{f}_1^K) \nonumber \\ & \hspace{16.5mm}\cdot p(j_k|\tilde{e}_1^{k-1}, s_1^{k-1}, \tilde{f}_1^K), \label{eq:word_chunk_decomp} \end{align} \endgroup where Equation~\ref{eq:latent} introduces the latent sequence $s_1^K$ with a marginalization sum over all possible chunk sequences and all possible number of chunks $K$. In Equation~\ref{eq:rewrite} we rewrite the source and target sequences using the chunk notation, and we apply the chain rule of probability in Equation~\ref{eq:chain}. We use the chain rule again in Equation~\ref{eq:word_chunk_decomp} to decompose the probability further into a \textit{target chunk boundary probability} $p(i_k|\tilde{e}_1^{k}, s_1^{k-1}, j_k, \tilde{f}_1^K)$, a \textit{target chunk translation probability} $p(\tilde{e}_k|\tilde{e}_1^{k-1}, s_1^{k-1}, j_k, \tilde{f}_1^K)$, and a \textit{source chunk boundary probability} $p(j_k|\tilde{e}_1^{k-1}, s_1^{k-1}, \tilde{f}_1^K)$. This creates a generative story, where the source chunk boundary is determined first, followed by the translation of the chunk, and finally by the target chunk boundary. The translation probability can be further decomposed to reach the word level: \begin{align} &p(\tilde{e}_k,|\tilde{e}_1^{k-1}, s_1^{k-1}, j_k, \tilde{f}_1^K) \nonumber \\ &= \prod_{i=i_{k-1}+1}^{i_k} p(e_i|\underbrace{e_{i_{k-1}+1}^{i-1}, \tilde{e}_1^{k-1}}_{=e_1^{i-1}}, s_1^{k-1}, j_k, \tilde{f}_1^K) \nonumber \\ &\approx \prod_{i=i_{k-1}+1}^{i_k} p(e_i|e_1^{i-1}, f_1^{j_k}, k). \end{align} In this work, we drop the marginalization sum over chunk sequences and use fixed chunks during training. The chunk sequences are generated as described in Section \ref{sec:chunking}. \section{Model} \subsection{Source Chunk Boundary Detection} \label{sec:boundary_detection} We simplify the chunk boundary probability, dropping the dependence on the target sequence and previous target boundary decisions \begin{align} p(j_k|\tilde{e}_1^{k-1}, s_1^{k-1}, \tilde{f}_1^K) \approx p(j_k|f_1^{j_k}, j_1^{k-1}), \end{align} where the distribution is conditioned on the source sequence up to the last word of the $k$-th chunk. It is also conditioned on the previous source boundary decisions $j_1...j_{k-1}$. Instead of computing a distribution over the source positions, we introduce a binary random variable $b_j$ such that for each source position we estimate the probability of a chunk boundary: \begin{equation} b_{j,k} = \begin{cases} 1 & \text{if\,} j \in \lbrace j_1, j_2 ... j_k \rbrace \\ 0 & \mathrm{otherwise.} \end{cases} \end{equation} For this, we use a forward stacked RNN encoder. The $l$-th forward encoder layer is given by \begin{equation} \hspace{-0.05cm} \label{eq:forward} \overrightarrow{h}_{j,k}^{(l)} = \begin{cases} \scalebox{.8}[1.0]{$LSTM$}\big( [\hat{f}_j; \hat{b}_{{j-1},k}], \overrightarrow{h}_{j-1,k}^{(l)}\big) & \hspace*{4mm} l = 1 \vspace{2mm} \\ \scalebox{.8}[1.0]{$LSTM$}\big( \overrightarrow{h}_{j,k}^{(l-1)}, \overrightarrow{h}_{j-1,k}^{(l)}\big) & \hspace*{-7mm} 1 < l < L_{enc}, \end{cases} \end{equation} where $\hat{f}_j$ is the word embedding of the word $f_j$, which is concatenated to the embedding of the boundary decision at the previous source position $\hat{b}_{j-1,k}$. $L_{enc}$ is the number of encoder layers. On top of the last layer a softmax estimates $p(b_{j,k})$: \begin{equation} \label{eq:source_chunk_detection} \hspace{-0cm}p(b_{j,k}) = \text{softmax}\big(g([\overrightarrow{h}_{j,k}^{(L_{enc})}; \hat{f}_j; \hat{b}_{j-1,k}]) \big),\hspace{-0.2cm} \end{equation} where $g(\cdot)$ denotes a non-linear function. \subsection{Translation Model} We use an RNN attention model based on~\cite{Bahdanau14:softalign} for $p(e_i|e_1^{i-1}, f_1^{j_k})$. The model shares the forward encoder with the chunk boundary detection model. In addition, we extend the encoder with a stacked backward RNN encoder. The $l$-th backward layer is given by \begin{equation} \hspace{-0.07cm} \label{eq:backward} \overleftarrow{h}_{j,k}^{(l)} = \begin{cases} \textbf{0} & j>j_k, \forall l \vspace{1.5mm} \\ \scalebox{.8}[1.0]{$LSTM$}\big( [\hat{f}_j; b_{j,k}], \overleftarrow{h}_{j+1,k}^{(l)}\big) & l = 1 \vspace{2mm} \\ \scalebox{.8}[1.0]{$LSTM$}\big( \overleftarrow{h}_{j,k}^{(l-1)}, \overleftarrow{h}_{j+1,k}^{(l)}\big) & \hspace*{-3mm} 1 < l < L_{enc}, \end{cases} \end{equation} where the backward layer is computed within a chunk starting at the last position of the chunk $j=j_k$. $\textbf{0}$ indicates a vector of zeros for positions beyond the current chunk. The source representation is given by the concatenation of the last forward and backward layer \begin{equation} \label{eq:concat} h_{j,k} = [\overrightarrow{h}_{j,k}^{(L_{enc})}; \overleftarrow{h}_{j,k}^{(L_{enc})}]. \end{equation} We also stack $L_{dec}$ LSTM layers in the decoder \begin{equation} u_{i,k}^{(l)} = \begin{cases} \scalebox{.8}[1.0]{$LSTM$}\big( u_{i,k}^{(l-1)}, u_{i-1,\hat{k}}^{(l)}\big) & \hspace*{-2mm} 1 < l < L_{dec} \\ \scalebox{.8}[1.0]{$LSTM$}\big( [\hat{e}_{i}; d_{i,k}], u_{i-1,\hat{k}}^{(l)}\big) & \hspace*{5mm} l = 1, \end{cases} \end{equation} where $\hat{e}_{i}$ is the target word embedding of the word $e_{i}$, $\hat{k}=k$ unless the previous decoder state belongs to the previous chunk, then $\hat{k}=k-1$. The vector $d_{i,k}$ is the context vector computed over source positions up to the last source position $j_k$ in the $k$-th chunk \begin{align} d_{i,k} =& \sum_{j=1}^{j_k} \alpha_{i,j,k} h_{j,k} \\ \alpha_{i,j,k} =& \text{softmax}(r_{i,1,k}...r_{i,j_k ,k})|_j \\ r_{i,j,k} =& f(h_{j,k}, u_{i-1,\hat{k}}^{(L_{dec})}), \end{align} where $\alpha_{i,j,k}$ is the attention weight normalized over the source positions $1\leq j \leq j_k$, and $r_{i,j,k}$ is the energy computed via the function $f$ which uses $\tanh$ of the previous top-most decoder layer and the source representation at position $j$. Note the difference to the attention component used in offline MT, where the attention weights are computed considering the complete source sentence $f_1^J$. The output distribution is computed using a softmax function of energies from the top-most decoder layer $u_{i-1,k}^{(L_{dec})}$, the target embedding of the previous word $\hat{e}_{i-1}$, and the context vector $d_{i-1,k}$ \begin{align} p(e_i |& e_1^{i-1}, f_1^{j_k},k) = \nonumber \\ &\text{softmax}\big(g([u_{i-1,k}^{(L_{dec})}; \hat{e}_{i-1}; d_{i-1,k}])\big). \end{align} \subsection{Target Chunk Boundary Factor} Traditionally, the translation model is trained to produce a sentence end token to know when to stop the decoding process. In our approach, this decision has to be made for each chunk (see next section). Hence, we have to train the model to predict the end positions of the chunks on the target side. For this, we use a target factor \citep{garcia2016factored, wilken2019novel}, i.e. a second output of the decoder in each step: \begin{align} \label{eq:target_chunk_detection} p(b_i |& e_1^{i}, f_1^{j_k},k) = \nonumber \\ &\text{softmax}(g( u_{i-1,k}^{(L_{dec})}, \hat{e}_{i}, \hat{e}_{i-1}, d_{i-1,k})) \end{align} where $b_i$ is a binary random variable representing target chunk boundaries analogous to $b_j$ on the source side. This probability corresponds to the first term in Equation \ref{eq:word_chunk_decomp}, making the same model assumptions as for the translation probability. Note however, that we make the boundary decision dependent on the embedding $\hat{e}_{i}$ of the target word produced in the current decoding step. \section{Search} Decoding in simultaneous MT can be seen as an asynchronous process that takes a stream of source words as input and produces a stream of target words as output. In our approach, we segment the incoming source stream into chunks and output a translation for each chunk individually, however always keeping the full source and target context. \begin{algorithm} \DontPrintSemicolon \SetKwInOut{Input}{input}\SetKwInOut{Output}{output} \Input{ source word stream $f_1^J$} \Output{ target word stream $e_1^I$} \BlankLine $\hat{\bm{f}_k}$ = [], $\overrightarrow{\bm{h}}$ = [], $\overleftarrow{\bm{h}}$ = [] \; \For{$f_j$ \textbf{\upshape in} $f_1^J$}{ $\hat{f}_j$ = Embedding($f_j$) \; $\overrightarrow{h}_j$, $p(b_j)$ = runForwardEncoder($\hat{f}_j$) \; $\hat{\bm{f}_k}$ += $\hat{f_j}$ \; $\overrightarrow{\bm{h}}$ += $\overrightarrow{h}_j$ \; \If{$p(b_i) > t_b$ \textbf{\upshape or} j = J}{ $\overleftarrow{\bm{h}}_k$ = runBackwardEncoder($\hat{\bm{f}_k}$) \; $\overleftarrow{\bm{h}}$ += $\overleftarrow{\bm{h}}_k$ \; $\tilde{\bm{e}}_k$ = runDecoder($\overrightarrow{\bm{h}}$, $\overleftarrow{\bm{h}}$) \; $e_1^I$ += $\tilde{\bm{e}}_k$ \; $\hat{\bm{f}_k}$ = [] \; } } \caption{Simultaneous Decoding \\ \footnotesize{lists in bold, [] is the empty list, += appends to a list}} \label{algo:decoding} \end{algorithm} Algorithm \ref{algo:decoding} explains the simultaneous decoding process. One source word $f_j$ (i.e. its embedding $\hat{f}_j$) is read at a time. We calculate the next step of the shared forward encoder (Equation \ref{eq:forward}), including source boundary detection (Equation \ref{eq:source_chunk_detection}). If the boundary probability $p(b_j)$ is below a certain threshold $t_b$, we continue reading the next source word $f_{j+1}$. If, however, a chunk boundary is detected, we first feed all word embeddings $\hat{\bm{f}}_k$ of the current chunk into the backward encoder (Equation \ref{eq:backward}), resulting in representations $\overleftarrow{\bm{h}}_k$ for each of the words in the current chunk. After that, the decoder is run according to Equations \ref{eq:concat}--\ref{eq:target_chunk_detection}. Note, that it attends to representations $\overrightarrow{\bm{h}}$ and $\overleftarrow{\bm{h}}$ of all source words read so far, not only the current chunk. Here, we perform beam search such that in each decoding step those combinations of target words and target chunk boundary decisions are kept that have the highest joint probability. A hypothesis is considered final as soon as it reaches a position $i$ where a chunk boundary $b_i = 1$ is predicted. Note that the length of a chunk translation is not restricted and hypotheses of different lengths compete. When all hypotheses in the beam are final, the first-best hypothesis is declared as the translation $\tilde{e}_k$ of the current chunk and all its words are flushed into the output stream at once. During search, the internal states of the forward encoder and the decoder are saved between consecutive different calls while the backward decoder is initialized with a zero state for each chunk. \section{Alignment-Based Chunking} \label{sec:chunking} \subsection{Baseline Approach} \label{subsec:baseline_chunking} We aimed at a meaningful segmentation of sentence pairs into bilingual chunks which could then be translated in monotonic sequence and each chunk is -- in terms of aligned words -- translatable without consuming source words from succeeding chunks. We extract such a segmentation from unsupervised word alignments in source-to-target and target-to-source directions that we trained using the Eflomal toolkit~\citep{Ostling2016efmaral} and combined using the \textit{grow-diag-final-and} heuristic~\citep{koehn03:spb}. Then, for each training sentence pair, we extract a sequence of ``minimal-length'' monotonic phrase pairs, i.e. a sequence of the smallest possible bilingual chunks which do not violate the alignment constraints\footnote{This means that all source words within a bilingual chunk are aligned only to the target words within this chunk and vice versa.} and at the same time are conform with the segmentation constraints in Equation~\ref{eq:constraints}. By this we allow word reordering between the two languages to happen only within the chunk boundaries. The method roughly follows the approach of~\cite{marino05:tuples}, who extracted similar chunks as units for n-gram based statistical MT. For fully monotonic word alignments, only chunks of length 1 either on the source or the target side are extracted (corresponding to 1-to-1, 1-to-M, M-to-1 alignments). For non-monotonic alignments larger chunks are obtained, in the extreme case the whole sentence pair is one chunk. Any unaligned source or target words are attached to the chunk directly preceding them, also any non-aligned words that may start the source/target sentence are attached to the first chunk. We perform the word alignment and chunk boundary extraction on the word level, and then convert words to subword units for the subsequent use in NMT. \begin{figure*}[t] \centering \footnotesize{ \begin{verbatim} EN: And | along came | a | brilliant | inventor, | a | scientist, | who | came up with a partial cure for that disease DE: Dann | kam | ein | brillanter | Erfinder des Wegs, | ein | Wissenschaftler, | der | eine teilweise Heilung für diese Krankheit fand EN: And | along came | a brilliant inventor, | a scientist, | who | came up with a partial cure for that disease DE: Dann | kam | ein brillanter Erfinder des Wegs, | ein Wissenschaftler, | der | eine teilweise Heilung für diese Krankheit fand \end{verbatim} } \caption{Examples of the baseline and the improved approach of extracting chunk boundaries. Note how in the improved approach noun phrases were merged into single bigger chunks. Also note the long last chunk that corresponds to the non-monotonic alignment of the English and German subordinate clause.}\label{fig:chunk-example} \end{figure*} \subsection{Delayed Source Chunk Boundaries}\label{subsec:delay} We observed that the accuracy of source boundary detection can be improved significantly by including the words immediately following the source chunk boundary into the context. Take e.\,g. the source word sequence \texttt{I have seen it}. It can be translated into German as soon as the word \texttt{it} was read: \texttt{Ich habe es gesehen}. Therefore the model is likely to predict a chunk boundary after \texttt{it}. However, if the next read source word is \textcolor{red}{\texttt{coming}}, it becomes clear that we should have waited because the correct German translation is now \texttt{Ich habe es \textcolor{red}{kommen} gesehen}. There is a reordering which invalidates the previous partial translation. To be able to resolve such cases, we shift the source chunks by a constant delay $D$ such that $j_1, ..., j_k, ..., j_K$ becomes $j_1 + D, ..., j_k + D, ..., j_K + D$.\footnote{If $j_K + D > J$, we shift the boundary to $J$, allowing empty source chunks at sentence end.} Note that the target chunks remain unchanged, thus the extra source words also provide an expanded context for translation. In preliminary experiments we saw large improvements in translation quality when using a delay of 2 or more words, therefore we use it in all further experiments. \subsection{Improved Chunks for More Context} \label{subsec:improved_chunking} The baseline chunking method (Section \ref{subsec:baseline_chunking}) considers word reordering to determine necessary context for translation. However, future context is often necessary for correct translation. Consider the translation \texttt{The beautiful woman} $\rightarrow$ \texttt{Die schöne Frau}. Here, despite of the monotonic alignment, we need the context of the third English word \texttt{woman} to translate the first two words as we have to decide on the gender and number of the German article \texttt{Die} and adjective \texttt{schöne}. In part, this problem is already addressed by adding future source words into the context as described in Section~\ref{subsec:delay}. However, this method causes a general increase in latency by $D$ source positions and yet covers only short-range dependencies. A better approach is to remove any chunk boundary for which the words following it are important for a correct translation of the words preceding it. To this end, we introduce a heuristic that uses two bigram target language models (LMs). The first language model yields the probability $p(e_{i_k} | e_{i_k - 1})$ for the last word $e_{i_k}$ of chunk $s_k$, whereas the second one computes the probability $p(e_{i_k}|e_{i_k+1})$ for the last word in the chunk given the first word $e_{i_k+1}$ of the next chunk $s_{k+1}$ that follows the word $e_{i_k}$. The chunk boundary after $e_{i_k}$ is removed if the probability of the latter reverse bigram LM is higher than the probability of the first one by a factor $l = \sqrt{i_k - i_{k-1}}$, i.e. dependent on the length of the current chunk. The motivation for this factor is that shorter chunks should be merged with the context to the right more often than chunks which are already long, provided that the right context word has been frequently observed in training to follow the last word of such a chunk candidate. The two bigram LMs are estimated on the target side of the bilingual data, with the second one trained on sentences printed in reverse order. Examples of the chunks extracted with the baseline and the improved approach for a given training sentence pair are shown in Figure~\ref{fig:chunk-example}. \section{Streaming Speech Recognition} \label{sec:asr} To translate directly from speech signal, we use a cascaded approach. The proposed simultaneous NMT system consumes words from a streaming automatic speech recognition (ASR) system. This system is based on a hybrid LSTM/HMM acoustic model~\citep{bourlard89,Hochreiter:1997:LSTM}, trained on a total of approx.~2300 hours of transcribed English speech from the corpora allowed by IWSLT 2020 evaluation, including MUST-C, TED-LIUM, and LibriSpeech. The acoustic model takes 80-dim.~MFCC features as input and estimates state posterior probabilities for 5000 tied triphone states. It consists of 4 bidirectional layers with 512 LSTM units for each direction. Frame-level alignment and state tying were bootstrapped with a Gaussian mixtures acoustic model. The LM of the streaming recognizer is a 4-gram count model trained with Kneser-Ney smoothing on English text data (approx.~2.8B running words) allowed by the IWSLT 2020 evaluation. The vocabulary consists of 152K words and the out-of-vocabulary rate is below~1\%. Acoustic training and the HMM decoding were performed with the RWTH ASR toolkit~\cite{wiesler2014:rasr}. The streaming recognizer implements a version of chunked processing~\citep{chen2016training,zeyer16} which allows for the same BLSTM-based acoustic model to be used in both offline and online applications. By default, the recognizer updates the current first-best hypothesis by Viterbi decoding starting from the most recent frame and returns the resulting word sequence to the client. This makes the first-best hypothesis ``unstable'', i.e.~past words can change depending on the newly received evidence due to the global optimization of the Viterbi decoding. To make the output more stable, we made the decoder delay the recognition results until all active word sequences share a common prefix. This prefix is then guaranteed to remain unchanged independent of the rest of the utterance and thus can be sent out to the MT model. \section{Experiments} We conduct experiments on the IWSLT simultaneous translation task for speech translation of TED talks from English to German. \subsection{Setup} For training the baseline NMT system, we utilize the parallel data allowed for the IWSLT 2020 evaluation. We divide it into 3 parts: in-domain, clean, and out-of-domain. We consider data from the TED and MUST-C corpora~\citep{mustc19} as in-domain and use it for subsequent fine-tuning experiments, as well as the ``ground truth'' for filtering the out-of-domain data based on sentence embedding similarity with the in-domain data; details are given in \citep{pbahar2020iwsltsystem}. As ``clean'' we consider the News-Commentary, Europarl, and WikiTitles corpora and use their full versions in training. As out-of-domain data, we consider OpenSubtitles, ParaCrawl, CommonCrawl, and \textit{rapid} corpora, which we reduce to 40\% of their total size, or to 23.2M parallel lines, with similarity-based filtering. Thus, in total, we use almost 26M lines of parallel data to train our systems, which amounts to ca.~327M running words on the English side. Furthermore, we added 7.9M sentence pairs or ca.~145M running words of similarity-filtered back-translated\footnote{ The German-to-English system that we used to translate these data into English is an off-line system trained using the Transformer Base architecture~\citep{transformer} on the in-domain and clean parallel data.} German monolingual data allowed by the IWSLT 2020 evaluation. In training, the in-domain and clean parallel data had a weight of 5. All models were implemented and trained with the RETURNN toolkit \cite{returnn_acl2018}. We used an embedding size of 620 and LSTM state sizes of 1000. \begin{table*}[!h] \centering \begin{tabular}{llllllll} \hline \multirow{2}{*}{\textbf{System}} & \textbf{\hspace*{-2mm} Delay} &\multicolumn{2}{c}{\textbf{tst2015}} & \multicolumn{2}{c}{\textbf{must-c-HE}} & \multicolumn{2}{c}{ \textbf{must-c-COMMON}} \\ && \textbf{\BLEU} & \textbf{\TER} & \textbf{\BLEU} & \textbf{\TER} & \textbf{\BLEU} & \textbf{\TER} \\ \hline \textbf{Offline baseline, Transformer} \\ \hspace{2mm} using reference transcript & n/a & 32.7 & 50.9 & 30.1 & 54.3 & 32.6 & 48.9 \\ \hspace{2mm} using streaming ASR & n/a & 28.6 & 56.3 & 26.0 & 59.2 & 26.4 & 57.3 \\ \hline \textbf{Proposed simultaneous NMT} & 2 & 24.8 & 60.2 & 21.7 & 63.0 & 21.9 & 60.2 \\ \hspace{2mm} unidirectional, & 3 & 24.6 & 60.2 & 22.6 & 62.7 & 21.8 & 60.8 \\ \hspace{2mm} (6 enc. 2 dec.) & 4 & 24.6 & 61.1 & 22.8 & 62.8 & 21.7 & 61.5 \\ \hline \textbf{Proposed simultaneous NMT} & 2 & 24.6 & 60.0 & 21.4 & 62.8 & 21.9 & 60.6 \\ \hspace{2mm} bidirectional, & 3 & 24.4 & 60.5 & 22.0 & 62.7 & 21.7 & 61.1 \\ \hspace{2mm} (2x4 enc.\,1 dec.) & 4 & 24.6 & 61.0 & 21.8 & 63.1 & 21.9 & 61.4 \\ \hline \end{tabular} \caption{\label{tbl:speech_mt} Experimental results (in \%) for simultaneous NMT of speech, IWSLT 2020 English$\to$German.} \end{table*} As heldout tuning set, we use a combination of IWSLT dev2010, tst2014, and MUST-C-dev corpora. To obtain bilingual chunks as described in Section~\ref{sec:chunking}, we word-align all of the filtered parallel/back-translated and tuning data in portions of up to 1M sentence pairs, each of them combined with all of the in-domain and clean parallel data. As heldout evaluation sets, we use IWSLT tst2015, as well as MUST-C HE and COMMON test data. For the text input condition, we applied almost no preprocessing, tokenization was handled as part of the subword segmentation with the sentencepiece toolkit~\citep{kudo2018sentencepiece}. The vocabularies for both the source and the target subword models had a size of 30K. For the speech input condition, the additional preprocessing applied to the English side of the parallel data had the goal to make it look like speech transcripts. We lowercased the text, removed all punctuation marks, expanded common abbreviations, especially for measurement units, and converted numbers, dates, and other entities expressed with digits into their spoken form. For the cases of multiple readings of a given number (e.g. \texttt{one oh one}, \texttt{one hundred and one}), we selected one randomly, so that the system could learn to convert alternative readings in English to the same number expressed with digits in German. Because of this preprocessing, our system for the speech condition learned to insert punctuation marks, restore word case, and convert spoken number and entity forms to digits as part of the translation process. The proposed chunking method (Section \ref{sec:chunking}) is applied to the training corpus as a data preparation step. We measured average chunk lengths of 2.9 source words and 2.7 target words. 40\% of both the source and target chunks consist of a single word, about 20\% are longer than 3 words. We compute case-sensitive BLEU~\citep{papineni02:bleu} and TER~\citep{snover06:ter} scores as well as the average lagging (AL) metric \citep{ma2019stacl}. \subsection{Results} Table \ref{tbl:speech_mt} shows results for the proposed simultaneous MT system. For reference, we first provide the translation quality of an offline system that is trained on full sentences. It is a transformer ``base'' model \cite{transformer} that we trained on the same data as the online systems. Row 1 shows BLEU and TER scores for translation of the human reference transcription of the speech input (converted to lower-case, punctuation removed), whereas row 2 uses the automatic transcription generated by our streaming ASR system (Section \ref{sec:asr}). The ASR system has a word error rate (WER) of 8.7 to 11.2\% on the three test sets, causing a drop of 4-6\% BLEU absolute. All following systems are cascaded streaming ASR + MT online systems that produce translations from audio input in real-time. Those systems have an overall AL of 4.1 to 4.5 seconds, depending on $D$. We compare between two categories of models: unidirectional and bidirectional. For the unidirectional models the backwards decoder (Equation \ref{eq:backward}) was removed from the architecture. We show results for different values of source boundary delay $D$ (see Section \ref{subsec:delay}). For the number of layers we choose $L_\text{enc}=6$ and $L_{\text{dec}}=2$ for the unidirectional models, and $L_{\text{enc}}=4$ (both directions) and $L_\text{dec}=1$ for the bidirectional models, such that the number of parameters is comparable. Contradicting our initial assumption, bidirectional models do not outperform unidirectional models. This might indicate be due to the fact that the majority of chunks are too short to benefit from a backwards encoding. Also, the model is not sensitive to the delay $D$. This \textit{confirms} our assumption that the additional context of future source words is primarily useful for making the source boundary decision, and for this a context of 2 following (sub-)words is sufficient. For translation, the model does not depend on this ``extra'' context but instead is able to make sufficiently good chunking decisions. Table \ref{tbl:text_mt} shows results for the case of streamed text input (cased and with punctuation marks). We compare our results to a 4-layer unidirectional system that was trained using the wait-$k$ policy \citep{ma2019stacl}. For this, we chunk the training data into single words, except for a first chunk of size $k=9$ on the source side, and set the delay to $D=0$. All of our systems outperform this wait-$k$ system by large margins. We conclude that the alignment-based chunking proposed in Section \ref{sec:chunking} is able to provide better source context than a fixed policy and that the source boundary detection component described in Section \ref{sec:boundary_detection} successfully learns to reproduce this chunking at inference time. Also for the text condition, we do not observe large differences between uni- and bidirectional models and between different delays. \begin{table*}[!h] \centering \begin{tabular}{lclllllll} \hline \multirow{2}{*}{\textbf{System}} & \multirow{2}{*}{\hspace*{-4mm}\textbf{Delay}}& \multirow{1}{*}{\textbf{Avg.}} & \multicolumn{2}{c}{\textbf{tst2015}} & \multicolumn{2}{c}{\textbf{must-c-HE}} & \multicolumn{2}{c}{\textbf{must-c-COMMON}} \\ & & \textbf{AL} & \textbf{\BLEU} & \textbf{\TER} & \textbf{\BLEU} & \textbf{\TER} & \textbf{\BLEU} & \textbf{\TER} \\ \hline \textbf{Baseline} wait-k (k=9) & - & & 27.4 & 55.8 & 25.1 & 59.5 & 27.4 & 54.2 \\ \hline \textbf{Proposed simultaneous MT} & 2 & 4.72 & 30.2 & 52.6 & 28.8 & 55.0 & 30.0 & 50.8 \\ \hspace{2mm} unidirectional & 3 & 5.26 & 30.3 & 53.2 & 28.8 & 55.2 & 29.7 & 50.8 \\ \hspace{2mm} (6 enc.\,2 dec.) & 4 & 6.17 & 29.9 & 53.1 & 28.6 & 55.1 & 29.6 & 50.8 \\ \hline \textbf{Proposed simultaneous MT} & 2 & 4.65 & 29.3 & 53.4 & 28.1 & 55.4 & 29.7 & 50.9 \\ \hspace{2mm} bidirectional & 3 & 5.46 & 29.6 & 53.7 & 29.0 & 54.8 & 29.7 & 51.6 \\ \hspace{2mm} (2x4 enc.\,1 dec.) & 4 & 6.15 & 29.2 & 54.0 & 28.3 & 55.3 & 29.7 & 51.5\\ \hline \end{tabular} \caption{\label{tbl:text_mt} Experimental results (in \%) for simultaneous NMT of text input, IWSLT 2020 English$\to$German.} \end{table*} \begin{figure} \vspace*{-1.5mm} \centering \include{BLEU_vs_AL} \vspace*{-6mm} \caption{BLEU vs. AL for bidirectional systems from Table \ref{tbl:text_mt}, generated using a delay $D$ of $2$, $3$, and $4$. } \label{fig:bleu_al} \end{figure} For all systems, we report AL scores averaged over all test sets. Figure \ref{fig:bleu_al} breaks down the scores to the individual test sets for the bidirectional models. For a source boundary delay $D=2$ we observe an AL of $4.6$ to $4.7$ words. When increasing $D$, we increase the average lagging score by roughly the same amount, which is expected, since the additional source context for the boundary decision is not translated in the same step where it is added. As discussed before, translation quality does not consistently improve from increasing $D$. \begin{figure} \centering \include{len_norm_tuning} \vspace*{-6mm} \caption{BLEU vs. the length normalization factor ($\alpha$) on the tuning set (dev2010 + tst2014 + MUST-C-dev).} \label{fig:len_norm_tuning} \vspace*{-5mm} \end{figure} We found tuning of length normalization to be important, as the average decoding length for chunks is much shorter than in offline translation. For optimal results, we divided the model scores by $I^\alpha$, $I$ being the target length, and tuned the parameter $\alpha$. Figure \ref{fig:len_norm_tuning} shows that $\alpha=0.9$ works best in our experiments, independent of the source boundary delay $D$. This value is used in all experiments. Furthermore, we found the model to be very sensitive to a source boundary probability threshold $t_b$ different than $0.5$ regarding translation quality. This means the ``translating'' part of the network strongly adapts to the chunking component. \section{Conclusion} We proposed a novel neural model architecture for simultaneous MT that incorporates a component for splitting the incoming source stream into translatable chunks. We presented how we generate training examples for such chunks from statistical word alignment and how those can be improved via language models. Experiments on the IWSLT 2020 English-to-German task proved that the proposed learned source chunking outperforms a fixed wait-$k$ strategy by a large margin. We also investigated the value of backwards source encoding in the context of simultaneous MT by comparing uni- and bidirectional versions of our architecture. \section*{Acknowledgements} We would like to thank our colleague Albert Zeyer for fruitful discussions and RETURNN implementation support.
{'timestamp': '2020-06-01T02:09:57', 'yymm': '2005', 'arxiv_id': '2005.14489', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14489'}
arxiv
\section{Methods} \begin{figure*}[t] \centering \includegraphics[width=1.0\linewidth]{figures/networks.pdf} \caption{An overview of CoDiNet. \textbf{Similar Image Generation}: Each sample is augmented randomly and get several similar augmentations. \textbf{Dynamic Routing Network}: Through a dynamic routing network, we get routing paths and prediction for each sample. \textbf{Path Distribution Optimization}: We optimize the path distribution with the consistency loss $\mathcal{L}_{con}$ and the diversity loss $\mathcal{L}_{div}$. Note that the augmentation methods are commonly used in classification, which are cropping and horizontally flipping. Best viewed in color. } \label{fig.min_max} \end{figure*} In this section, we illustrate our method CoDiNet in detail. First, we formulate dynamic routing as a space mapping and introduce the basics of dynamic routing accordingly. Second, we show how to model the relationship between the two spaces with the regularization of consistency and diversity. Third, we design a training strategy to make our dynamic routing network adaptive to different computational budgets. Finally, we illustrate our process of training and inference. For convenience, \cref{tab:notation} summarizes the notations. \begin{table}[tb] \centering \caption{Notations} \label{tab:notation} \vspace{-1em} \begin{tabu} to 0.49\textwidth {X[c]X[4]} \toprule $\mathcal{S}$ & a sample space\\ $s_i$ & a sample \\ $\mathcal{R}$ & a routing space\\ $r_i$ & the routing path for $s_i$\\ $\mathcal{\phi}$& an $n$-block network\\ $F_k$ & the $k$-th block of $\mathcal{\phi}$\\ $a_k$ & the input of the $(k+1)$-th block of $\mathcal{\phi}$\\ $U_k$ & the router for the $k$-th block \\ $u_k$ & the execution decision of the $k$-th block \\ $v_k$ & the relaxation of $u_k$ \\ \midrule $m_c$ & the margin for consistency \\ $m_d$ & the margin for diversity \\ $\mathcal{L}_{con}$ & the loss function for consistency \\ $\mathcal{L}_{div}$ & the loss function for diversity \\ $\mathcal{L}_{cost}$ & the loss function for customizable dynamic routing\\ $\alpha$ & the hyper-parameter for $\mathcal{L}_{con}$ \\ $\beta$ & the hyper-parameter for $\mathcal{L}_{div}$ \\ $\gamma$ & the hyper-parameter for $\mathcal{L}_{cost}$ \\ \bottomrule \end{tabu} \end{table} \subsection{Dynamic Routing as a Space Mapping} \subsubsection{Routing Space} We see dynamic routing as a mapping from a sample space to a routing space. A sample space $\mathcal{S}$ is a set of samples, and a routing space $\mathcal{R}$ is the set of all the possible routing paths of a dynamic routing network $\mathcal{\phi}$. In this way, dynamic routing can be considered as a mapping $\mathcal{\phi}:\mathcal{S} \rightarrow \mathcal{R}$. That is, for each sample $s_i\in\mathcal{S}$, its routing path $r_i \in \mathcal{R}$ in a dynamic routing network $\mathcal{\phi}$ is \begin{equation} r_i = \mathcal{\phi}(s_i). \end{equation} A routing path consists of a sequence of to-be-skipped and to-be-run blocks. In this paper, we use the same block as in ResNet~\cite{he2016deep}. Let $\mathcal{\phi}$ be an $n$-block network and $u_k \in \{0,1\}$ be the execution decision for the $k$-th block, where $0$ stands for to-be-skipped and $1$ stands for to-be-run. Then, a routing path for the sample $s_i$ is a concatenation of decisions for all the blocks, i.e., $r_i = (u_1, u_2, \cdots, u_n)$. Hence, the routing space of $\mathcal{\phi}$ is $\mathcal{R}={\{0, 1\}^{n}}$, which contains $2^n$ routing paths in total \subsubsection{Routers} For each block in the network $\mathcal{\phi}$, there is a router used to decide whether the block should be executed for a specific sample. Let $F_{k}$ be the $k$-th block of $\mathcal{\phi}$, $a_{k-1}$ be the input of $F_{k}$, and $U_k$ be the router for the $k$-th block. Then, the dynamic routing result $a_k$ of the $k$-th block is defined as \begin{equation} a_{k} = u_{k} \cdot F_{k}(a_{k-1}) + (1-u_{k}) \cdot a_{k-1}, \end{equation} where the value of $u_k$ stands for the decision of $U_k$. Routers are supposed to find the correct path while incurring a low computational cost. To minimize the cost, we use a lightweight structure for each router, which only contains two fully connected layers, as shown in \cref{sfig:routing_module}. First, the router $U_k$ gathers information from the block input $a_{k-1} \in \mathbb{R}^{W_k \times H_k \times C_k}$ across channels by global average pooling, which is written as \begin{equation} z_k = \mathrm{gap}(a_{k-1}). \end{equation} Then, the fused features $z_k$ are processed by two fully connected layers sequentially. Let $\mathrm{W}_1 \in \mathbb{R}^{d \times C_k}$ and $\mathrm{W}_2 \in \mathbb{R}^{2 \times d}$ be the weights of $U_k$'s first layer and second layer respectively, where $d$ denotes the output dimension of the first layer. The router $U_k$ is defined as \begin{equation} U_k = \mathrm{W}_2 \circ \sigma(\mathrm{W}_1 \circ z_k), \end{equation} where $\sigma(\cdot)$ is an activation function, and $\circ$ denotes matrix multiplication. It is worth noting that $U_k$ is a two-element vector as a result. $U_k[0]$ is the first element of $U_k$, and $U_k[1]$ is the second element. In this way, the execution decision $u_k$ of the $k$-th block is calculated by \begin{equation} u_k = \mathop{\arg\max}_j(U_k[j]), \end{equation} where $u_k=0$ means to-be-skipped, and $u_k=1$ means to-be-run as a result. The simple yet effective structure incurs less than one percent of the computational cost of a convolution block. \begin{figure*}[t] \centering \subfigure[Routing Space]{ \centering \includegraphics[height=1.6in, width=0.23\linewidth]{figures/insight1.png} \label{sfg.insight_a} } \subfigure[Augmentation]{ \centering \includegraphics[height=1.6in, width=0.23\linewidth]{figures/insight2.png} \label{sfg.insight_b} } \subfigure[Consistency]{ \centering \includegraphics[height=1.6in, width=0.23\linewidth]{figures/insight3.png} \label{sfg.insight_c} } \subfigure[Diversity]{ \centering \includegraphics[height=1.6in, width=0.23\linewidth]{figures/insight4.png} \label{sfg.insight_d} } \caption{Illustration of the optimization of path distribution. A solid point means a routing path of an image. A hollow circle means a routing path center of similar images. (a) Suppose we have four different input images whose paths distribute in the routing space. (b) With augmentations, we can get four similar instances of each image. (c) The consistency regularization makes routing paths of similar instances cluster around their center. (d) The diversity regularization disperses the center of dissimilar instances. Best viewed in color. } \label{fig.insight} \end{figure*} \subsubsection{Route Relaxation} \label{sec.relaxation} To make the binary routing decisions $u_1, u_2, \cdots, u_n$ optimizable in an end-to-end fashion, we utilize a continuous, differentiable relaxation function, Gumbel-Softmax \cite{gumbel1948statistical}, at the end of each router as shown in \cref{sfig:routing_module}. Gumbel-Softmax turns discrete values into continuous ones, enabling backpropagation. Let $g$ be the noise samples from a Gumbel distribution, and let $\mathcal{T}$ be the temperature which is fixed to $1$ in our experiments. The relaxation for $u_k$, called $v_k$, is calculated by \begin{equation} v_k = \mathrm{softmax}(\frac{\log(U_k)+g}{\mathcal{T}})[1], \end{equation} where $\mathrm{softmax}(\cdot)[1]$ is the second element. In this way, the dynamic routing result of the $i$-th block is relaxed by \begin{equation} a_{k} = v_k \cdot F_{k}(a_{k-1}) + (1-v_k) \cdot a_{k-1}. \label{eq1} \end{equation} The routing path $r_i$ for an $n$-block network is also relaxed by $r_i = (v_1, v_2, \cdots, v_n)$, where each element is in $[0,1]$. It is worth noting that a block in $\mathcal{\phi}$ is either run or skipped at inference time. We will describe it in \cref{sssec:inference}. Next, we propose to regularize routing paths in the routing space. \subsection{Consistency and Diversity Regularization} \label{loss} We expect that the routing paths of similar samples should be consistent in the routing space. Otherwise, the routing paths should be diverse. In real scenarios, the similarity of different images is difficult to measure. Therefore, we propose to regularize the routing paths of samples according to their self-supervised similarity, i.e., considering the augmentations of an image as its similar samples. To this end, we first generate similar images in \cref{sssec:generation}. To realize consistency for similar samples and diversity for dissimilar samples, we directly regularize path distributions in \cref{sssec:consistency} and \cref{sssec:diversity}. An overview of the proposed optimization method is shown in \cref{fig.min_max}. \subsubsection{Similar Images Generation} \label{sssec:generation} To obtain similar samples, we randomly augment each original sample several times by random cropping and horizontal flipping. We treat the set of augmentations as similar inputs as shown in \cref{sfg.insight_a} and \cref{sfg.insight_b}. Suppose a training batch containing $L$ samples, and $M$ augmentations for each sample. Then, we have an augmented set $\{s_{i,1}, s_{i, 2}, \cdots, s_{i,M}\}$ for a sample $s_i$, where $s_{i,j}$ stands for the $j$-th augmentation for $s_i$. Therefore, there are $L \times M$ inputs in an iteration, i.e., $\{s_{1,1}, s_{1, 2}, \cdots, s_{1,M}\}, \cdots, \{s_{L,1}, s_{L,2}, \cdots, s_{L,M}\}$. \subsubsection{Consistency Regularization} \label{sssec:consistency} As shown in \cref{sfg.insight_c}, consistency regularization is an attractive force in each group of similar samples to make them closer. Let $r_{i,j}$ be the routing path of sample $s_{i,j}$, $\overline{r_{i,:}}$ be the mean of $\{r_{i,1}, r_{i,2}, \cdots, r_{i,M}\}$, which represents the routing path center of sample $s_{i}$'s augmentations. In this way, the optimization of consistency is written as \begin{equation} \begin{aligned} \label{eq.consistent} \mathcal{L}_{con}= & \dfrac{1}{L}\dfrac{1}{M}\sum_{i=1}^{L} \sum_{j=1}^{M}[\left \|\, r_{i,j}-\overline{r_{i,:}}\, \right \| - m_c]_+^2, \end{aligned} \end{equation} where $L$ is the batch size, $M$ is the number of augmentations, $\| \cdot \|$ is the $L^2$ norm, $m_c$ is the margin for consistency, and $[x]_+ = max(0, x)$ denotes the hinge. The minimization of $\mathcal{L}_{con}$ is to narrow down the differences between all the routing paths and the mean routing path. To further illustrate the consistency, we visualize the path distribution of five classes from the CIFAR-10 test set in \cref{fig.consistency}. In the first row of \cref{fig.consistency}, the paths of the vanilla dynamic routing method scatter in the routing space randomly. With consistency regularization, paths cluster around the center in the routing space, becoming consistent as shown in the second row of \cref{fig.consistency}. \begin{figure*}[t] \centering \includegraphics[width=\linewidth]{figures/consistency_new.pdf} \caption{Visualization of the routing path distribution under different constraints through t-SNE on the CIFAR-10 test set. Figures in the first row show the path distribution of the vanilla dynamic routing method without $\mathcal{L}_{con}$ and $\mathcal{L}_{div}$. Figures in the second row show the path distribution of the experiments with $\mathcal{L}_{con}$ only. Figures in the third row show the path distribution of our method. All figures are in the same coordinate scales. } \label{fig.consistency} \end{figure*} \subsubsection{Diversity Regularization} \label{sssec:diversity} Conversely, as shown in \cref{sfg.insight_d}, diversity regularization is a repulsive force between each group of similar samples to push them away. The optimization of diversity is defined as \begin{equation} \label{eq.diverse} \begin{aligned} \mathcal{L}_{div}= & \dfrac{1}{L}\dfrac{1}{L-1} \sum_{i=1}^{L} \sum_{j \neq i} [m_d-\left \|\overline{r_{i,:}} -\overline{r_{j,:}}\,\right \|]_+^2, \end{aligned} \end{equation} where $m_d$ is the margin for diversity, and $\sum_{j\neq i}$ means all samples in the batch except $s_i$. Within a batch, the mean routing path is optimized to maximize the differences for different groups. In this way, the routing paths of different groups are dispersed and the diversity of routing paths can be guaranteed. Another advantage of diversity regularization is that it helps the network explore more paths. Path distribution in the real scenario under diversity regularization is also shown in \cref{fig.consistency}. Compared with the first two rows, samples in the third row cluster around several centers and different clusters keep distant from each other, which is in line with our expectations. In our method, consistency and diversity are two facets of the problem. Although $\mathcal{L}_{con}$ makes the routing space compact, it also runs a risk of making the whole routing space collapse into a small space, impairing the diversity of routing paths. Thus, introducing $\mathcal{L}_{div}$ can compensate for the disadvantage of stand-alone $\mathcal{L}_{con}$ and make the routing paths diverse at the same time. Similarly, $\mathcal{L}_{div}$ can enhance the routing space exploration; however, making routing paths scattered without constraint can be harmful to the parameter sharing among routing paths. As a result, we propose to make use of $\mathcal{L}_{con}$ and $\mathcal{L}_{div}$ together. \subsection{Customizable Dynamic Routing} \label{sec.cost} Dynamic routing is aimed at saving the cost of a network at inference time. How much cost dynamic routing should save for a network depends on the application scenario. Since the computational budget is different from device to device, it is better to make a dynamic routing network adaptive to devices. We design a learning strategy to make a dynamic routing network adaptive to different computational budgets. Let $c_k$ be the computational cost of the $k$-th block. The total cost for an $n$-block network is defined as \begin{equation} {cost}_{all} = \sum_{k=1}^{n} c_k \cdot u_k. \end{equation} To make it learnable, we use the relaxed continuous routing variable, $v_k$, similar to \cref{eq1}. After relaxation, the loss function for cost optimization $\mathcal{L}_{cost}$ becomes \begin{equation} \mathcal{L}_{cost} = \sum_{k=1}^{n} c_k \cdot v_k. \end{equation} It is worth noting that we build a computational cost lookup table which records the floating-point operations (FLOPs) of each block. During optimization, each block $F_k$ will be assigned a cost $c_k$ given by the lookup table. By putting all the losses together, the overall objective of our method is \begin{equation} \mathcal{L}_{total} = \mathcal{L}_{cls} + \alpha \cdot \mathcal{L}_{con} + \beta \cdot \mathcal{L}_{div}+ \gamma \cdot \mathcal{L}_{cost}, \label{eq.total} \end{equation} in which $\mathcal{L}_{cls}$ is the cross entropy loss used for classification, $\mathcal{L}_{con}$ is the loss defined in \cref{eq.consistent}, and $\mathcal{L}_{div}$ is the loss defined in \cref{eq.diverse}. $\alpha$, $\beta$, and $\gamma$ are the hyper-parameters for respective losses. To make a dynamic routing network adaptive to different computational budgets, we tune the hyper-parameter $\gamma$ of $\mathcal{L}_{cost}$. Therefore, we can customize the learned network with different computational costs and performances. That is, a smaller $\gamma$ encourages an expensive model, and a larger $\gamma$ encourages an inexpensive model. \begin{table*}[t] \caption{The Efficiency and Accuracy Trade-off based on ResNet-110 on CIFAR-10} \label{tab.Detailed_Data} \vspace{-1em} \renewcommand\arraystretch{1.35} \setlength{\tabcolsep}{4.85mm}{ \begin{tabular}{lccccccc} \toprule \multicolumn{1}{l}{Settings} & \multicolumn{1}{c}{GMACCs} & \begin{tabular}[c]{@{}c@{}}Speedup\\ (in GMACCs)\end{tabular} & \begin{tabular}[c]{@{}c@{}}Inference Time\\ GTX-1080 (ms)\end{tabular} & \begin{tabular}[c]{@{}c@{}}Inference Time\\ GTX-1080ti (ms)\end{tabular} & \begin{tabular}[c]{@{}c@{}}Inference Time\\ RTX-2080ti (ms)\end{tabular} & Acc. (\%)\\ \midrule ResNet-110 & 0.51 & 1.0$\times$ & 17.2 & 16.4 & 15.3 & 93.60 \\ \hline $\gamma=0.01$ & 0.29 & 1.8$\times$ & 9.43 & 8.69 & 8.56 & 94.47 \\ $\gamma=0.02$ & 0.27 & 1.9$\times$ & 8.53 & 8.41 & 8.16 & 94.30 \\ $\gamma=0.04$ & 0.22 & 2.3$\times$ & 7.69 & 7.62 & 7.37 & 93.94 \\ $\gamma=0.08$ & 0.20 & 2.6$\times$ & 7.66 & 7.18 & 6.98 & 93.71 \\ $\gamma=0.10$ & 0.10 & 5.1$\times$ & 3.85 & 3.74 & 3.29 & 92.45 \\ \bottomrule \end{tabular}} \medskip \emph{\footnotesize GMACCs refers to billions of multiply-accumulates. $\gamma$ is the weight for $\mathcal{L}_{cost}$ defined in Eq.(12). The unit of inference time is millisecond.} \vspace{-1.0em} \end{table*} \begin{table}[t] \caption{Ablation Study of Routers, $\mathcal{L}_{con}$ and $\mathcal{L}_{div}$ on CIFAR-10} \renewcommand\arraystretch{1.3} \label{tab:ablation_study} \vspace{-1em} \setlength{\tabcolsep}{2.4mm}{ \begin{tabular}{l|ccccc} \toprule \multicolumn{1}{l|}{Methods} & Routers & $\mathcal{L}_{con}$ & \multicolumn{1}{c|}{$\mathcal{L}_{div}$} &\#Path & Acc. (\%)\\ \midrule ResNet-110 & --- &--- & \multicolumn{1}{c|}{---} & 1 & 93.60 \\ Vanilla & $\checkmark$ &--- & \multicolumn{1}{c|}{---} & 113 & 93.66 \\ \midrule Vanilla + $\mathcal{L}_{con}$& $\checkmark$ &$\checkmark$ & \multicolumn{1}{c|}{---} &20 & 92.88 \\ Vanilla + $\mathcal{L}_{div}$& $\checkmark$ & --- & \multicolumn{1}{c|}{$\checkmark$} & 1079 & 91.34 \\ CoDiNet &$\checkmark$ & $\checkmark$ & \multicolumn{1}{c|}{$\checkmark$} &276 & \textbf{94.47} \\ \bottomrule \end{tabular}} \medskip \emph{\footnotesize Vanilla is the vanilla dynamic routing network. The number of activated routing paths and the accuracy under different constraints based on ResNet-110.} \end{table} \subsection{Training and Inference} \label{sssec:inference} At training time, we optimize our network in two stages. First, we train the parameters of all the blocks and all the routers together by \cref{eq.total}. Second, we finetune our network to narrow down the decisions' difference between training and inference. We use continuous decisions $(v_1, v_2, \cdots, v_n)$ as a relaxation of binary decisions $(u_1, u_2, \cdots, u_n)$ to make the first training stage end-to-end, but training with the continuous relaxation $v_k$ of the binary decision $u_k$ will inevitably cause a gap between training and inference. Therefore, we finetune the network with the parameters in each router fixed. In terms of inference, a block in the network is either run or skipped exclusively. That is, \begin{equation} a_{k} = \begin{dcases} F_{k}(a_{k-1}), & \text{if } v_k\geq 0.5;\\ a_{k-1}, & \text{otherwise.} \end{dcases} \end{equation} \section{Conclusion} In this paper, we see routing mechanisms from a novel perspective that regards a dynamic routing network as a mapping from a sample space to a routing space. From this view, path distribution in routing space is a fundamental problem in a dynamic routing network. We propose a novel framework CoDiNet to regularize path distribution with diversity and consistency. Moreover, we design a customizable dynamic routing module enabling the network to adapt to different computational budgets. We compare CoDiNet with state-of-the-art methods on four benchmark datasets, demonstrating that it can effectively reduce the computational cost without compromising performance. \section*{Acknowledgement} This work is supported in part by National Key Research and Development Program of China under Grant 2020AAA0107400, National Natural Science Foundation of China under Grant U20A20222, Zhejiang Provincial Natural Science Foundation of China under Grant LR19F020004, and key scientific technological innovation research project by Ministry of Education. \section{Introduction}\label{sec:introduction}} \else \section{Introduction} \label{sec:introduction} \fi \IEEEPARstart{D}{ynamic} routing is a sample-adaptive inference mechanism for neural networks. At inference time, only part of a dynamic routing network would be activated for each sample, which is aimed at reducing computational cost with little performance compromised~\cite{veit2018convolutional, wang2018skipnet, wu2018blockdrop, almahairi2016dynamic}. In essence, dynamic routing can be considered as a mapping from a sample space to a routing space. As shown in \cref{fig.mapping}, when samples are presented to a dynamic routing model, they are mapped into a routing space. Each sample's routing path in the routing space can be represented as a binary vector, consisting of a sequence of to-be-run and to-be-skipped blocks. The model walks through the to-be-run blocks. From the perspective of space mapping, how inference paths should be distributed in the routing space remains relatively unexplored. Since dynamic routing is related to two spaces, i.e., a sample space and a routing space, we focus on this question: \textit{how do we model the relationship between the two spaces?} We expect that the distance between similar samples should be close in the routing space. Otherwise, the distance should be far. Moreover, \textit{what kind of samples are similar?} We utilize the self-supervised similarity and encourage the self-supervised augmentations walking through close routing paths. Since the images obtained by self-supervised augmentations remain semantically and visually unchanged, their routing paths should be close in the routing space. In comparison, images belong to the same semantic class might be significantly different due to different background, object layout, and color. The feature extraction patterns of these samples are different so that it is infeasible to utilize close routing paths for such visually different images. As shown in \cref{fig_idea}, images $a$ and $a'$, images $b$ and $b'$ are similar to each other, while $c$ and $c'$, $d$ and $d'$ are dissimilar. Therefore, the routing paths of images $a$ and $a'$, images $b$ and $b'$ should be the same or similar, while routing paths of images $c$ and $c'$, $d$ and $d'$ should be different. \begin{figure}[t] \centering \includegraphics[width=1.0\linewidth]{figures/mapping.pdf} \caption{Illustration of dynamic routing. A dynamic routing network is a mapping from a sample space to a routing space. Each routing path consists of a sequence of to-be-run and to-be-skipped blocks. The dynamic routing model walks through the to-be-run blocks. Best viewed in color. } \label{fig.mapping} \end{figure} \begin{figure*}[t] \centering \includegraphics[width=\linewidth]{figures/introduction.pdf} \caption{Illustration of our motivation. \textbf{Left:} Schematic diagram of a dynamic routing network, in which each layer can be either executed or skipped. \textbf{Middle:} A demonstration of the routing space. All potential routing paths compose a binary routing space. \textbf{Right:} Routing paths for similar images should be the same or similar, e.g., $a$ and $a'$, $b$ and $b'$, while routing paths for dissimilar images should be different, e.g., $c$ and $c'$, $d$ and $d'$. Best viewed in color.} \label{fig_idea} \end{figure*} To this end, we explicitly model the relationship between the sample space and the routing space, therein establishing the connection between samples and routing paths. We propose a novel dynamic routing method, termed CoDiNet, to regularize the path distribution in a routing space with the properties of consistency and diversity, based on the aforementioned space mapping. Firstly, the consistency regularization makes augmentations of the same sample have similar feature activations, thus forming a specific routing paths for specific samples. Parameters on the specific routing path are consistently stimulated by similar samples, which is favorable to parameter sharing among similar samples and robustness of the network. At the same time, the diversity regularization makes the routing paths generated by dynamic routing more diverse, which strengthens the exploration of the network. It is evident that the more routing paths are used, the more capacity of the network is utilized. Computational cost is another important issue because the computational ability of different platforms varies considerably. For instance, the inference speed of ResNet-50~\cite{he2016deep} on GTX 1080ti \textit{(30fps)} is much faster than that on Maxwell TitanX \textit{(18fps)} at a resolution of $224\times224$. The average cost of dynamic routing networks should be customizable, when the networks are applied to platforms with different computational budgets. To this end, we propose a differentiable computational cost loss to optimize the average computational cost of the model and make the computational budgets customizable. The main contributions of CoDiNet can be summarized into three parts: \begin{itemize} [leftmargin=*] \item We explicitly model the relationship between the sample space and the routing space, therein establishing the connection between samples and routing paths. \item We propose a novel consistency-and-diversity regularized optimizing method modeling the relationships between the two spaces, which makes routing paths optimizable. \item We design a customizable dynamic routing module and achieve state-of-the-art results in terms of computational cost reduction and performance. \end{itemize} \begin{figure*}[h] \subfigure[Dynamic routing]{ \label{sfig:dynamic_routing} \centering \includegraphics[width=.45\linewidth, height=1.5in]{figures/router_a.pdf} } \subfigure[Our router]{ \label{sfig:routing_module} \centering \includegraphics[width=.53\linewidth, height=1.5in]{figures/router.pdf} } \caption{Illustration of dynamic routing and our router. (a) Comparison between static inference and dynamic routing. In the dynamic routing network, whether the current convolution block would be executed depends on the output of the previous block. (b) Illustration of the structure of our router. The cost of our router is negligible compared with a convolution block.} \label{fig.route_structure} \end{figure*} \section{Experiments} In this section, we conduct a series of experiments to evaluate the performance of CoDiNet. First, we introduce the experimental setup. Second, we perform the ablation studies for the proposed regularization. Third, we compare our results with the state-of-the-art works and other related methods. Next, we show qualitative analysis on the proposed modules in our method. In the end, we compare different routing strategies and structures. \subsection{Experimental Setup} \label{detail} \subsubsection{Datasets and Metrics} We evaluate our method on four widely used datasets, which are CIFAR-10~\cite{krizhevsky2009learning}, CIFAR-100~\cite{krizhevsky2009learning}, SVHN~\cite{netzer2011reading}, and ImageNet~\cite{deng2009imagenet} (ILSVRC2012). CIFAR-10/100 consists of 60,000 colored images, which are resized to 32$\times$32. Out of the 60,000 images, 50,000 images are used for training, and the other 10,000 images are used for testing. SVHN includes 73,257 training images and 26,032 testing images. ImageNet contains 1,281,167 training images and 50,000 validation images that are annotated with 1,000 classes and resized to 224$\times$224. We use classification accuracy (top-1) as an evaluation metric. \begin{table}[t] \caption{Results on SVHN} \label{tab:SVHN_result} \vspace{-1em} \setlength{\tabcolsep}{2.6mm}{ \renewcommand\arraystretch{1.3} \begin{tabular}{lccc} \toprule Networks & ResNet-110 & Vanilla dynamic routing & CoDiNet \\ \midrule Acc. (\%) & 94.19 & 93.15 & 94.28 \\ GMACCs & 0.51 & 0.38 & 0.39 \\ \bottomrule \end{tabular}} \medskip \emph{\footnotesize Results are based on ResNet-110. Vanilla dynamic routing is the method without $\mathcal{L}_{con}$ and $\mathcal{L}_{div}$.} \end{table} \subsubsection{Implementation Details} For data augmentation, we follow the settings as in~\cite{veit2018convolutional, wang2018skipnet}. Images from CIFAR-10/100 are padded with 4 pixels on each side. Images from all datasets except SVHN are randomly cropped and horizontally flipped with a probability of 0.5. Those from SVHN are randomly cropped only. On CIFAR-10/100 and SVHN, the lightweight ResNets~\cite{he2016deep} are adopted as the backbones, including ResNet-32, ResNet-74 and ResNet-110. On ImageNet, ResNet-50 and ResNet-101 are adopted as the backbones. Finally, the computational is measured in GMACCs, i.e., billions of multiply-accumulate operations as used in~\cite{veit2018convolutional, wang2018skipnet, wu2018blockdrop, almahairi2016dynamic}. During training, we use SGD as an optimizer with a momentum of 0.9 and a weight decay of 1e-4. The initial learning rate is set to 0.1 and a multi-step scheduler is adopted. On CIFAR10/100, the step-wise learning rate decays by 0.1 at 150 and 200 epochs. As for ImageNet, it decays by 0.1 every 30 epochs. As for the loss hyper-parameters, $\alpha$ and $\beta$ are set to 0.2 respectively. To control the computational cost precisely, the hyper-parameter $\gamma$ for $\mathcal{L}_{cost}$ is tuned adaptive. Besides, the margin for consistency $m_c$ and the margin for diversity $m_d$ are set to 0.2 and 0.5 respectively. \begin{table*}[t] \caption{Results on CIFAR-10/100} \label{tab:result_10_100} \vspace{-1em} \setlength{\tabcolsep}{1.7mm}{ \renewcommand\arraystretch{1.4} \begin{tabular}{clccccccccc} \toprule & & \multicolumn{3}{c}{ResNet-32} & \multicolumn{3}{c}{ResNet-74} & \multicolumn{3}{c}{ResNet-110} \\ \cmidrule{3-11} & & Acc. (\%) & \#Param (M) & \multicolumn{1}{c|}{GMACCs} & Acc. (\%) & \#Param (M) & \multicolumn{1}{c|}{GMACCs} & Acc. (\%) & \#Param (M) & GMACCs \\ \midrule \multirow{3}{*}{\rotatebox{90}{CIFAR-10}} & \multicolumn{1}{l|}{ResNets} & 92.40 & 0.46 & \multicolumn{1}{c|}{0.14} & 93.30 & 1.13 & \multicolumn{1}{c|}{0.34} & 93.60 & 1.71 & 0.51 \\ &\multicolumn{1}{l|}{Vanilla dynamic routing} & 91.55 & 0.49 & \multicolumn{1}{c|}{0.09} & 93.17 & 1.21 & \multicolumn{1}{c|}{0.18} & 93.66 & 1.83 & 0.30 \\ &\multicolumn{1}{l|}{CoDiNet} & \bf{92.48} & 0.49 & \multicolumn{1}{c|}{0.09} & \bf{93.61} & 1.21 & \multicolumn{1}{c|}{0.19} & \bf{94.47} & 1.83 & 0.29 \\ \midrule \multirow{3}{*}{\rotatebox{90}{CIFAR-100}} & \multicolumn{1}{l|}{ResNets} & 68.7 & 0.46 & \multicolumn{1}{c|}{0.14} & 70.5 & 1.13 & \multicolumn{1}{c|}{0.34} & 71.2 & 1.71 & 0.51 \\ &\multicolumn{1}{l|}{Vanilla dynamic routing} & 66.4 & 0.49 & \multicolumn{1}{c|}{0.09} & 69.7 & 1.21 & \multicolumn{1}{c|}{0.20} & 70.3 & 1.83 & 0.24 \\ &\multicolumn{1}{l|}{CoDiNet} & \bf{69.2} &0.49 & \multicolumn{1}{c|}{0.11} & \bf{70.9} & 1.21 & \multicolumn{1}{c|}{0.21} & \bf{72.9} & 1.83 & 0.24 \\ \bottomrule \end{tabular}} \medskip \emph{\footnotesize Vanilla dynamic routing only uses our routers without $\mathcal{L}_{con}$ or $\mathcal{L}_{div}$. GMACCs refers to billions of multiply-accumulates. \#Param is the number of parameters.} \end{table*} \begin{table}[t] \caption{Comparison with State-of-the-Arts on CIFAR-10} \label{tab.sota_result} \vspace{-1em} \setlength{\tabcolsep}{4.0mm}{ \renewcommand\arraystretch{1.3} \begin{tabular}{llcccc} \toprule Methods & Backbones & GMACCs & Acc. (\%) \\ \midrule \emph{baseline} \\ ResNet-32 & --- & 0.14 & 92.40 \\ ResNet-110& --- & 0.50 & 93.60 \\ \midrule \emph{dynamic routing} \\ SkipNet~\cite{wang2018skipnet} & ResNet-74&0.09 & 92.38 \\ BlockDrop~\cite{wu2018blockdrop} & ResNet-110&0.17 & 93.60 \\ Conv-AIG~\cite{veit2018convolutional} & ResNet-110&0.41 & 94.24 \\ IamNN~\cite{leroux2018iamnn} & ResNet-101 & 1.10 & 94.60 \\ CGap~\cite{du2019efficient} & ResNet-110 & 0.19 & 93.43\\ \midrule \emph{early prediction}\\ ACT~\cite{graves2016adaptive} & ResNet-110& 0.38 & 93.50 \\ SACT~\cite{figurnov2017spatially} & ResNet-110&0.31 & 93.40 \\ DDI~\cite{wang2020dual} & ResNet-74 &0.14 &93.88 \\ DG-Net~\cite{shafiee2019dynamic} & ResNet-101& 3.20 & 93.99 \\ DG-Net (light) & ResNet-101& 2.22 & 91.99 \\ \midrule \emph{ours}\\ CoDiNet-32 &ResNet-32& 0.09 & 92.48 \\ CoDiNet-110 & ResNet-110& 0.29 & \textbf{94.47} \\ \bottomrule \end{tabular}} \medskip \emph{\footnotesize The results of the others are the best results reported in their papers. GMACCs refer to billions of multiply-accumulates.} \end{table} \subsection{Ablation Study} \label{sec_ablation} In this part, we discuss the effectiveness of each module in CoDiNet. First, we perform the ablation studies on consistency and diversity. Then, we discuss the customizable dynamic routing module, which is proposed to strike the balance between computational cost reduction and accuracy. \begin{table}[t] \caption{Comparison with State-of-the-Arts on ImageNet} \label{tab.sota_imagenet} \vspace{-1em} \renewcommand\arraystretch{1.3} \setlength{\tabcolsep}{3.4mm}{ \begin{tabular}{llcc} \toprule Methods & Backbones & GMACCs & Acc. (\%) \\ \midrule \emph{baseline} & & &\\ ResNet-50 & --- & 3.86 & 75.36 \\ ResNet-101 & --- & 7.63 & 76.45 \\ \midrule \emph{dynamic routing} & & &\\ Conv-AIG 50~\cite{veit2018convolutional} & ResNet-50 & 3.06 & 76.18 \\ Conv-AIG 101 & ResNet-101 & 5.11 & 77.37\\ SkipNet~\cite{wang2018skipnet} & ResNet-101 & 6.70 & 77.40 \\ SkipNet (light) & ResNet-101 & 3.60 & 75.22 \\ LC-Net~\cite{xia2020fully} & ResNet-50 & 2.89 & 74.10 \\ BlockDrop~\cite{wu2018blockdrop} & ResNet-101 & 7.32 & 76.80 \\ DG-Net~\cite{shafiee2019dynamic} & ResNet-101 & 7.05 & 76.80\\ DDI~\cite{wang2020dual} & DenseNet-201 & 3.50 & 76.50 \\ \midrule \emph{early prediction} & & &\\ MSDN~\cite{Huang2017MultiScaleDN} & DenseNets & 2.30 & 74.24 \\ RA-Net~\cite{yang2020resolution} & DenseNets & 2.40 & 75.10 \\ IamNN~\cite{leroux2018iamnn} & ResNet-101 & 4.00 & 69.50 \\ ACT~\cite{graves2016adaptive} & ResNets & 6.70 & 75.30 \\ SACT~\cite{figurnov2017spatially} & ResNets & 7.20 & 75.80 \\ \midrule \emph{ours} & & &\\ CoDiNet-50 & ResNet-50& 3.10 & 76.63 \\ CoDiNet-101 & ResNet-101& 5.02 & \textbf{77.85}\\ \bottomrule \end{tabular}} \medskip \emph{\footnotesize The results of the others are the best results reported in their papers. GMACCs refer to billions of multiply-accumulates.} \end{table} \subsubsection{Effectiveness of Regularization} First, we conduct experiments on CIFAR-10 to show the ablation studies on each component based on ResNet-110. As shown in \cref{tab:ablation_study}, the accuracy of the vanilla dynamic routing method is 93.66\% with 113 paths. With consistency regularization, limited paths are utilized, and the performance decreases to 92.88\%. When utilizing the consistency and diversity regularization at the same time, it achieves an accuracy of 94.47\% with 276 paths. We also provide the numerical improvement on other datasets to verify the proposed consistency and diversity-based optimization as a whole. As shown in \cref{tab.sota_imagenet}, our method achieves a comparable result with 18.4\% computational cost reduction on ImageNet with 1.2\% accuracy improvements. The results on SVHN are shown in \cref{tab:SVHN_result}. Compared with the result of the vanilla dynamic routing method on SVHN, our method gains 1.13\% improvement with about 5\% extra computational cost, which is about 22\% computation reduction against original ResNet-110. \begin{figure*}[t] \centering \includegraphics[width=\linewidth]{figures/diversity_path.pdf} \caption{Visualization of the routing paths distribution under different $m_d$ through t-SNE. $m_d$ is the margin of diversity, which is defined in \cref{eq.diverse}. Figures in row 1, 2 and 3 show routing path distributions for $m_d=0.25, 0.5$, and $0.75$ respectively. Images are of 5 classes (airplane, automobile, bird, cat, and deer) from the CIFAR-10 test set.} \label{fig.diversity} \end{figure*} \begin{figure}[t] \centering \subfigure[CIFAR-10]{ \centering \includegraphics[width=.485\linewidth]{minor/cifar10_sota.pdf} \label{sfg.flop_compare_a} } \hspace{-1.4em} \subfigure[ImageNet]{ \centering \includegraphics[width=.485\linewidth]{minor/imagenet_sota.pdf} \label{sfg.flop_compare_b} } \caption{The accuracy against computational cost (GMACCs) of CoDiNet comparing to related methods on CIFAR-10 and ImageNet.} \label{fig.results_comparison} \end{figure} \subsubsection{Effect of Customizable Dynamic Routing} Another benefit of our method is that we can optimize the computational cost explicitly. As we discussed in \cref{sec.cost}, the proposed $\mathcal{L}_{cost}$ can balance the trade-off between accuracy and cost. And we only need to tune the weight of $\mathcal{L}_{cost}$, i.e., $\gamma$ in \cref{eq.total}, to obtain a desired model. \cref{tab.Detailed_Data} shows the trade-off between classification accuracy, GMACCs, and the average inference time on the CIFAR-10 dataset. With the increasing of the computational cost, the accuracy tends to be upward. In the extreme case, our method achieves even only 0.10 GMACCs with a comparable accuracy, which can meet the requirements on low power platforms. \subsection{Performance Comparison} In this part, we compare the results of CoDiNet with related methods. First, we compare CoDiNet with the results of ResNets on CIFAR-10/100. Next, we compare CoDiNet with the state-of-the-art dynamic routing networks, early prediction models\footnote{The results of ACT and SACT are quoted from~\cite{wu2018blockdrop} because ACT and SACT did not report corresponding results.}, and related compression methods on CIFAR-10 and ImageNet. \subsubsection{Comparison with ResNets} We make a comparison between CoDiNet and ResNets, w.r.t., accuracy and GMACCs. As shown in \mbox{\cref{tab:result_10_100}}, our method achieves higher accuracy with less cost in all experimental settings. In particular, compared with ResNet-110 on the CIFAR-10 dataset, our method needs 60\% cost (0.29 GMACCs) compared to the original network (0.51 GMACCs), and achieves 0.87\% improvement on accuracy. Similarly, on CIFAR-100, our method achieves significant improvement compared with ResNets and vanilla dynamic routing networks (without $\mathcal{L}_{con}$ and $\mathcal{L}_{div}$). It achieves an accuracy of 72.9\% with 0.24 GMACCs. Besides, the cost reduction on deep networks is much larger than cost reduction on shallow networks. It shows that deep networks are more redundant than shallow networks. \subsubsection{Comparison on CIFAR-10} \label{sssec:sotas} We compare CoDiNet with other state-of-the-art dynamic routing methods, early prediction networks, and related compression methods. As shown in \cref{tab.sota_result}, we compare with the following methods: BlockDrop~\cite{wu2018blockdrop}, SkipNet~\cite{wang2018skipnet}, Conv-AIG~\cite{veit2018convolutional}, ACT~\cite{graves2016adaptive}, SACT~\cite{figurnov2017spatially}, CGAP~\cite{du2019efficient}, DDI~\cite{wang2020dual}, Iamm~\cite{leroux2018iamnn}, DG-Net~\cite{shafiee2019dynamic}. Following \cite{wu2018blockdrop}, PFEC \cite{li2016pruning} and LCCL \cite{dong2017more} are used for comparison. BlockDrop and SkipNet are prevalent methods, applying reinforcement learning and LSTM respectively to implement the dynamic routing. BlockDrop achieves an accuracy of $93.6\%$ with 0.17 GMACCs on CIFAR-10 with ResNet-110. Conversely, SkipNet focuses more on computational cost reduction, obtaining an accuracy of $92.38\%$ with 0.09 GMACCs. Conv-AIG achieves an accuracy of 94.24\% with about 0.41 GMACCs. As shown in \cref{sfg.flop_compare_a}, the CoDiNet outperforms other methods in most cases with a comparable computational cost. Our method achieves an accuracy of 94.47\% with only 0.29 GMACCs. More importantly, our method does not conflict with compression methods, and it can be used along with compression methods for better performance. \subsubsection{Comparison on ImageNet} We compare CoDiNet with state-of-the-art methods on ImageNet as shown in \cref{tab.sota_imagenet}, and the efficiency-accuracy trade-off in \cref{sfg.flop_compare_b}. Among these methods, Conv-AIG~\cite{veit2018convolutional} reports results based on ResNet-50 and ResNet-101, which are 76.18\% and 77.37\% with 3.06 and 5.11 GMACCs respectively. SkipNet~\cite{wang2018skipnet} achieves an accuracy of 75.22\% with 3.6 GMACCs. Besides, RA-Net~\cite{yang2020resolution} is an early prediction method that processes different samples in different resolutions, which achieves an accuracy of 75.10\% with 2.40 GMACCs. In comparison, CoDiNet outperforms these methods, which achieves an accuracy of 76.63\% with 3.10 GMACCs based on ResNet-50 and an accuracy of 77.85\% with 5.02 GMACCs based on ResNet-101. \begin{figure}[t] \centering \includegraphics[width=\linewidth]{minor/path_KL1.pdf} \caption{KL divergence of the predictions between original and its augmentation on the CIFAR-10 test set. Green bars stands for the vanilla dynamic routing ResNet-110. Blue bars stands for the dynamic ResNet-110 with $\mathcal{L}_{con}$. Best viewed in color.} \label{fig.KD} \end{figure} \begin{figure}[t] \centering \includegraphics[width=\linewidth]{minor/Focus1_2.png} \caption{The visualization of the routing paths of multi-augmentations for samples. We randomly visualize 150 groups of augmentations from the CIFAR-10 test set. Dots in the same color stand for a group of augmentations from the same sample. Best viewed in color.} \label{fig.std_vis} \end{figure} \subsection{Qualitative Analysis} In this part, we conduct experiments to qualitatively analyze our proposals. First, we analyze the effect of the consistency regularization and the diversity regularization. Next, we visualize the distribution of relaxed routing paths. Finally, we show the images sharing the same routing paths. \begin{table}[t] \caption{Analysis of the Margin of Diversity} \renewcommand\arraystretch{1.3} \label{tab:path_number} \vspace{-1.0em} \setlength{\tabcolsep}{6.8mm}{ \begin{tabular}{c|ccc} \toprule $m_d$ &\#Path & GMACCs & Acc. (\%) \\ \midrule 0.25 &196 & 0.22 & 93.12 \\ 0.50 &276 & 0.29 & \textbf{94.47} \\ 0.75 &396 & 0.24 & 92.75 \\ 1.00 &800 & 0.32 & 92.46 \\ \bottomrule \end{tabular}} \medskip \emph{\footnotesize The number of activated routing paths and accuracy under different margins of diversity with ResNet-110 on CIFAR-10. $m_d$ is the margin of diversity defined in \cref{eq.diverse}, \#Path is the number of utilized routing paths and GMACCs refer to billions of multiply-accumulates.} \end{table} \subsubsection{Analysis of Consistency} \label{sssec:ana_consistency} To illustrate the effectiveness of the consistency regularization, we adopt KL divergence as an indicator to measure the difference of paths between original test set and augmented test set. That is, a smaller KL divergence indicates a better consistency. Compared with the vanilla dynamic routing on the CIFAR-10 test set, we found that the consistency regularization can significantly enhance the consistency between routing paths of original and augmented images. It also improves the performance of the augmented test set. As shown in \cref{fig.KD}, the KL divergence between original and augmented images decreases considerably with $\mathcal{L}_{con}$. Additionally, we design a qualitative experiment to show the effect of the consistency regularization. We adopt various augmentation methods including random cropping, horizontal flipping, vertical flipping, and rotation on the 10,000 images of the CIFAR-10 test set. For each original image, we compare its routing path with that of its augmentation under two models: CoDiNet and vanilla dynamic routing. As a result, 5,342 out of 10,000 image pairs have consistent routing paths with CoDiNet, i.e., the original image and its augmented image have the same routing path. With vanilla dynamic routing, only 2,265 images have consistent paths with their augmentation. \subsubsection{Analysis of Diversity} \label{sssec:ana_diversity} The number of distinct routing paths at inference time under different settings of $m_d$ is shown in \cref{tab:path_number}. With a larger margin, more routing paths will be obtained. When $m_d$ is 0.5, our method achieves the best performance on CIFAR-10 based on ResNet-110. When $m_d$ is larger than 0.5, the performance drops. The reason for that might lie in too dispersed routing paths resulting in under-fitting. Next, we visualize the routing path distribution on the CIFAR-10 test set to demonstrate the tendency of different margins of diversity $m_d$. In \cref{fig.diversity}, paths are dispersed significantly with an increase of $m_d$. When $m_d$ is 0.25, paths cluster into two groups. When $m_d$ is 0.75, the scale of coordinate is similar as $m_d = 0.5$, but the distribution is more disperse. \begin{figure*}[t] \centering \subfigure[Path distribution without $\mathcal{L}_{con}$ or $\mathcal{L}_{div}$]{ \centering \includegraphics[width=0.48\linewidth, height=2.3in]{minor/disconsist.pdf} \label{sfg.disconsist} } \subfigure[Path distribution with $\mathcal{L}_{con}$ and $\mathcal{L}_{div}$]{ \centering \includegraphics[width=0.48\linewidth, height=2.3in]{minor/consist.pdf} \label{sfg.consist} } \caption{Visualization of continuous routing paths by t-SNE on the CIFAR-10 test set. The color of each dot is the mathematical expectation numbers of to-be-run blocks. Red refers to more to-be-run blocks, while blue to fewer. Images in the green rectangle are augmentations from the same image. Images in the red rectangle are from the same category. Images in the blue rectangle are from different categories. Best viewed in color.} \label{fig.similar} \end{figure*} \subsubsection{Illustration of Routing Paths for Similar Samples} In this section, we obtain groups of similar images by applying self-supervised augmentation methods (random cropping, horizontal flipping, vertical flipping, and rotation) on the CIFAR-10 test set ten times and then visualize the distribution of routing paths for self-supervised similar images to show the routing paths of ``similar samples'' clustering together by directly visualizing the distribution of routing paths for self-supervised similar images. We mark the augmented images from the same raw images with the same color. As shown in \cref{fig.std_vis}, points with the same color, i.e., augmentations of the same sample, tend to cluster together. As a result, the routing paths of self-supervised similar samples tend to cluster together in our method. \subsubsection{Correlation between Samples Similarity and Routing Paths Similarity} In this section, we calculate the PCC (Pearson correlation coefficient) between sample feature similarity and sample routing path similarity. A higher correlation coefficient value indicates the sample feature similarity is more positively correlated to the path similarity, therefore, the routing paths of similar images are closer in the routing space. Specifically, we use the Cosine Similarity on every pair of routing paths and sample features as the routing paths similarity and sample similarity. To better represent samples, the sample features are extracted by a third-party unsupervised model (an ImageNet pre-trained MoCo~\cite{moco}). As shown in \cref{tab.similarity_method}, the Pearson correlation coefficient for our CoDiNet is 0.581, while the one for the vanilla dynamic routing is 0.024. Thus, our method is about 24 times larger than the vanilla one. Besides, we plot the correlation diagrams for different sample pairs in \cref{fig.similar_core}. Clearly, our method is more likely to encourage the consistency between routing path similarity and sample similarity. \subsubsection{Visualization of Relaxed Routing Paths} As shown in \cref{fig.similar}, we visualize the relaxed routing paths of the vanilla dynamic routing network and CoDiNet by t-SNE. Different colors correspond to different mathematical expectations of the numbers of to-be-run blocks. Red refers to more to-be-run blocks, while blue refers to less to-be-run block. The path distribution of the method without $\mathcal{L}_{con}$ or $\mathcal{L}_{div}$, is shown in \cref{sfg.disconsist}, where the paths gather in a small space around the center. In comparison, the path distribution of CoDiNet are regularly distributed and scattered throughout a much larger space as shown in \cref{sfg.consist}. \begin{table}[t] \caption{Illustration of the PCC (Pearon correlation coefficient) between sample similarity and the routing path similarity.} \vspace{-1.0em} \label{tab.similarity_method} \setlength{\tabcolsep}{4.4mm}{ \begin{tabular}{lcc} \toprule Methods & Vanilla Dynamic Routing & Our CoDiNet \\ \midrule PCC & 0.024 & 0.581 \\ \bottomrule \end{tabular}} \medskip \emph{\footnotesize PCC refers to the Pearon correlation coefficient. The PCC value ranges from -1 to 1. A PCC value of 0 implies that there is no linear correlation between the similarities. Experiments is on CIFAR-10.} \end{table} \begin{figure}[t] \centering \subfigure[Vanilla dynamic routing]{ \includegraphics[width=0.485\linewidth]{minor/van_alpha.pdf} \label{sfg.NMI} } \hspace{-1.4em} \subfigure[Our CoDiNet]{ \includegraphics[width=0.485\linewidth]{minor/our_alpha.pdf} \label{sfg.EUR} } \caption{The correlation between the similarity of sample features and the similarity of sample routing paths with our CoDiNet and the vanilla dynamic routing. We use Cosine Similarity to measure the similarity. It is worth noting that the closer the point to the dotted line, the more positively correlated the similarity of samples and the similarity of paths.} \label{fig.similar_core} \end{figure} Moreover, we provide three groups of samples to present the routing paths of the self-supervised similar images cluster together no matter they belong to the same category or not. As shown in~\cref{fig.similar}, we provide three groups of images and mark out their routing paths. Firstly, images in the green rectangle are augmentations from the same image. Then, images in the red rectangle are from the same category. Next, images in the blue rectangle are from different categories. As shown in~\cref{sfg.disconsist}, the routing paths of images in each rectangle are scattered among the whole distribution without $\mathcal{L}_{con}$ or $\mathcal{L}_{div}$. In comparison, with $\mathcal{L}_{con}$ and $\mathcal{L}_{div}$, the routing paths of images in each group are respectively cluster together as shown in~\cref{sfg.consist}. Therefore, the proposed consistency regularization term can effectively make the routing paths of similar images clustering together. \section{Related Works}\label{sec:related} In this section, we revisit relevant methods and divide them into three categories: dynamic routing networks, early prediction networks, and model compression methods. Dynamic routing and early prediction are two typical approaches to dynamic inference. The former focus on skipping unnecessary units at inference time, while the latter is characterized by multiple exits. Model compression methods are also popular for cost reduction with static inference. \subsection{Dynamic Routing Networks} Layer dropping has long been used as a regularization technique in neural networks, e.g., DropConnection~\cite{wan2013regularization} and Dropout~\cite{JMLR:v15:srivastava14a}. Veit {et al}.~\cite{EnsemblesShallow} found that only short paths of deep residual networks are needed. Motivated by this, dynamic routing networks have emerged as a promising technique to skip blocks or layers at inference time for acceleration~\cite{veit2018convolutional, wang2018skipnet, wu2018blockdrop, almahairi2016dynamic, su2020dynamic}. Specifically, ConvNet-AIG~\cite{veit2018convolutional} proposed a convolutional network that adaptively defines its inference graph conditioned on the input images. it proposes a router to make the execution decision for each convolutional block. SkipNet~\cite{wang2018skipnet} introduced a method with LSTM gate-ways to determine whether the current block would be skipped or not. Besides, BlockDrop~\cite{wu2018blockdrop} adopted an extra policy network to sample routing paths from the whole routing space to speed up ResNets' inference. Slimmable Nets~\cite{yu2018slimmable} intended to train a model to support multiple widths to fit different computational constraints. Recursive network~\cite{guo2019dynamic} proposes to execute a convolutional layer multiple times. RNR~\cite{rao2018runtime} models the dynamic process as a Markov decision process and uses reinforcement learning for training. Spatial dynamic convolutions for fast inference were proposed in~\cite{verelst2020dynamic, yu2019universally, sun2020computation, xie2020spatially}. Multi-scale networks were introduced in~\cite{huang2018multi, yang2020resolution}. They learn easy samples at low resolutions, while hard samples at high resolutions. Channel-based dynamic routing methods~\cite{su2020dynamic, jordao2020discriminative} were introduced as well. Recently, various dynamic methods with different kinds of selection have been proposed. Multi-kernel methods~\cite{Chen_2020_CVPR, chen2020dynamic} select different CNN kernels for better performance. Recursive network~\cite{guo2019dynamic} are introduced to reuse the networks. At training time, dynamic routing models are prone to early convergence to suboptimal states. To deal with the issue, SkipNet~\mbox{\cite{wang2018skipnet}} uses multiple training stages, Blockdrop~\mbox{\cite{wu2018blockdrop}} uses curriculum learning, dynamic conv~\mbox{\cite{verelst2020dynamic}} uses annealing, sparsity network~\mbox{\cite{sun2020computation}} uses a non-conditional pre-training. In comparison, we focus on how to learn proper paths. To this end, we model the relation between samples and their routing paths explicitly and optimize the routing paths directly, achieving a more stable dynamic routing model. \subsection{Early Prediction Networks} While a dynamic routing network has only one exit, an early prediction network is characterized by multiple exits. In an early prediction network, the network exits once the criterion for a certain sample is satisfied. Traditional methods~\cite{reyzin2011boosting, hu2014efficient} applied heuristic and greedy algorithms to reduce the executed layers. BranchyNet~\cite{teerapittayanon2016branchynet} proposed a multiple-branch framework by attaching fully connected layers to intermediate layers of the backbone. ACT~\cite{graves2016adaptive} proposed a halting unit for a recurrent neural network (RNN) to realize early prediction. Following ACT, SACT~\cite{figurnov2017spatially} proposed a CNN-based early prediction network, adopting a stopping unit for each point on feature maps. Since then, early prediction frameworks have been widely used in classification for efficient inference. Considering multi-scale inputs, MSDN~\cite{Huang2017MultiScaleDN} introduced early-exit branches based on DenseNet~\cite{huang2017densely}. According to the allowed time budget, McIntosh et al.~\cite{mcintosh2018recurrent} proposed an RNN architecture to dynamically determine the exit. Li {et al}.~\cite{li2019improved} proposed a self-distillation mechanism to supervise inter-layer outputs with deeper layers. Instead of bypassing residual units, DCP~\cite{gao2018dynamic} generated decisions to save the computational cost for channels. Hydranets~\cite{Hydranets} proposed to replace the last residual block with a Mixture-of-Experts layer. Recently, methods have been adopted to other applications, such as action recognition~\cite{hussein2020timegate, meng2020ar} and object detection~\cite{zhang2019slimyolov3}. Our method belongs to dynamic routing networks. Thus, our method does not have multiple exits as early prediction networks do. We also compare our method with early prediction networks in \cref{sssec:sotas}. \subsection{Model Compression Methods} Compression methods are proposed for high-performance models on platforms with limited computational resources. Knowledge distillation~\cite{hinton2015distilling, chen2017learning, chen2018distilling, yu2018nisp}, low-rank factorization~\cite{ioannou2015training, tai2015convolutional, jaderberg2014speeding}, and quantization~\cite{han2015deep, wu2016quantized, polino2018model} have been widely used to compress the structures and to prune the parameters of neural networks. Besides, recent researches tend to prune unimportant filters or features~\cite{li2016pruning, he2017channel, luo2017thinet, wen2016learning, huang2018condensenet} to compress or speed-up the model. They identify ineffective channels or layers by examining the magnitude of the weight or activation. The relatively ineffective channels and layers are pruned from the model. Then the pruned model is finetuned to mitigate the accuracy loss. With the iteration of pruning unnecessary parts and then finetuning the model, computational cost and model size can reduce effectively. Perforated CNN~\cite{Perforated} speeds up the inference by skipping the computations at fixed spatial locations. In addition, Neural Architecture Search provides other technique plans achieving low-cost models including MnasNet \cite{tan2019mnasnet}, ProxylessNAS \cite{cai2018proxylessnas}, EfficientNet \cite{tan2019efficientnet}, and FbNet \cite{wu2019fbnet}. In contrast to this line of work where the same amount of computation is applied to all samples, we focus on efficient inference by dynamically choosing a series of blocks to be executed conditioned on the input. \section{Discussion on Routers} In this section, we compare CoDiNet with two implementations of Gumbel-Softmax, and different router structures to analyze the design of our router. The discussion focuses on the following questions. First, which variant of Gumbel-Softmax is suitable to utilize in our method? Next, what are the advantages of the router used in our method compared to other kinds of routers? \begin{figure}[h] \centering \subfigure[CIFAR-10]{ \centering \includegraphics[width=.487\linewidth]{minor/gumbel_cifar10.pdf} \label{sfg.gumbel_a} } \hspace{-1.6em} \subfigure[CIFAR-100]{ \centering \includegraphics[width=.487\linewidth]{minor/gumbel_cifar100.pdf} \label{sfg.gumbel_b} } \caption{The accuracy against computational cost of the re-parameterized and the straight-through Gumbel-Softmax variants on CIFAR-10/100. Results are based on ResNet-110. Best viewed in color.} \label{fig.Gumbel_Softmax} \end{figure} \subsection{Effectiveness of Gumbel-Softmax}\label{gumbel_softmax} To train the dynamic routing network end-to-end, relaxation methods are employed because the binary routing paths are not differentiable. As discussed in \cref{sec.relaxation}, we adopt Gumbel-Softmax for in our method. In this section, we compare the two variants of Gumbel-Softmax, i.e., the re-parameterized variant and the straight-through variant. As shown in \cref{fig.Gumbel_Softmax}, the re-parameterized variant performs better than the straight-through variant in most cases on CIFAR-10 and CIFAR-100. Weighing the pros and cons, we take the re-parameterized variant Gumbel-Softmax in our method. \begin{figure}[h] \centering \subfigure[CIFAR-10]{ \centering \includegraphics[width=.487\linewidth]{minor/CIFAR10_router.pdf} \label{sfg.router_a} } \hspace{-1.6em} \subfigure[CIFAR-100]{ \centering \includegraphics[width=.487\linewidth]{minor/CIFAR100_router.pdf} \label{sfg.router_b} } \caption{The accuracy against computational cost of the CNN router, the RNN router, and the FC router on CIFAR-10/100. Results are based on ResNet-110. Best viewed in color.} \label{fig.routers_compare} \end{figure} \subsection{Advantages of Our Router}\label{model_compare} Routers are key components in a dynamic routing network, which make execution decision for blocks. How to design a lightweight yet effective router has always been the focus in dynamic routing. In this section, we discuss different types of routers: the CNN router, the RNN router, and the FC router. As shown in~\cref{fig.routers_compare}, we show the accuracy against computational cost, when a network equipped with different routers. Specifically, a CNN router is composed of a $3\times 3$ convolutional layer followed by a global average pooling layer and a linear layer to output $1\times2$ vector. A RNN router is composed of a global average pooling, a shared linear layer, and a shared LSTM layer with a hidden unit size of 10. For the FC router, it uses two linear layers, after a global average pooling. Please refer to~\cite{veit2018convolutional, wang2018skipnet} for more details. As a result, the FC router achieves the highest accuracy under multiple computational settings, comparing with the RNN router and the CNN router.
{'timestamp': '2021-05-27T02:15:26', 'yymm': '2005', 'arxiv_id': '2005.14439', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14439'}
arxiv
\subsection{GEMM vs SpDM}\label{subsection:gemm_vs_spdm} A naive method to solve SpDM is directly using high-performance GEMM libraries, such as cuBLAS, if the sparsity of matrix A is not very high. High-performance GEMM libraries focus on improving the computational throughput of GPUs. For example, cuBLAS can achieve over 90\% of theoretical peak computational throughput of Nvidia Titan X Pascal. Here we briefly analyze the performance of cuBLAS using the roofline model. Note that we only discuss the square matrix multiplication for simplicity. Generally, for calculation of $\ma{C}=\ma{A} \times \ma{B}$, we need $O(n^3)$ multiplications and additions. Meanwhile, accessing the elements of $\ma{A}$ and $\ma{B}$ is also time consuming in modern GPU architectures. Ideally we need $2 \times n^2$ memory access for $\ma{A}$ and $\ma{B}$ at least. However, due to the limited cache size and registers, practical GEMM implementations have much more main memory access. The previous high-performance GEMM works struggle to reduce the overhead brought by slow memory access and promote the compute core utilization. The optimization principles include [citation]. However, consider SpDM, in which $\ma{A}$ is of high sparsity. Simply using those high-performance GEMM libraries may bring many useless calculations. Only $1-s$ of $n^3$ calculations have contributions to $\ma{C}$. That is, even high-performance GEMM libraries can achieve nearly peak computational performance of the devices, the effective percentage of those flops is as low as $1-s$. \begin{equation} T = (\alpha n^3+\beta)\times (1-s) \label{eq:time_sparse} \end{equation} \section{Introduction} Sparse-dense matrix-matrix multiplication (SpDM) has many application areas. It is not only exploited in traditional research fields (e.g., graph analytics \cite{tiskin2001all}, biology \cite{vazquez2010matrix}), but becoming a potential faster implementation for sparse deep learning \cite{liu2015sparse}\cite{shi2017speeding}\cite{wen2017learning}\cite{sun2017meprop}\cite{shi2019distributed}. However, it requires very high sparsity of the model to achieve accelerated speed compared to the original dense implementations \cite{narang2017exploring}. Dense matrix multiplication, i.e., $C=A\times B$ or general purpose matrix multiplication (GEMM) has been well studied on GPUs to achieve high efficiency \cite{volkov2008benchmarking}\cite{chu2009practical}\cite{nath2010improved}\cite{matsumoto2011multi}\cite{kurzak2012autotuning}\cite{lai2013performance}\cite{abdelfattah2016performance}\cite{zhang2017understanding}\cite{yan2020demystifying}\cite{liu2018g}. However, multiplication of a sparse matrix to a dense matrix (SpDM), in which the sparse matrix is stored with memory-saving formats like compressed row storage (CRS) \cite{dongarra2000compressed}, is understudied, and it easily loses efficiency on modern GPUs. For example, the time cost of calculating the multiplication of a $8000\times 8000$ sparse matrix with sparsity of $0.9$ (i.e., $90\%$ of elements are zeros) to a dense matrix with single precision requires $780ms$ by using cuSPARSE on an Nvidia Tesla P100 GPU, while the corresponding dense algorithm by cuBLAS only requires $121ms$.\footnote{Both cuSPARSE and cuBLAS are from the library of CUDA-8.0.} In other words, though the sparse matrix can reduce the number of multiplication and accumulation operations (MACs) by $90\%$ (since a zero element times any numbers produces zeros that has no contribution to the final results, so such operations can be avoided.), the highly optimized cuBLAS is about $7\times$ faster than cuSPARSE in the above example. For a much higher sparsity of $0.995$, cuSPARSE can be about $50\%$ faster than cuBLAS at the dimension of $8000\times 8000$ matrices on the P100 GPU. High sparsity requirement on SpDM makes it difficult to be deployed as the efficient implementation of matrix multiplication because of the inefficient algorithm design of the SpDM algorithm in cuSPARSE. In practical problems, on one hand, if the sparsity is not high enough, doing SpDM could result in very low efficiency, while using the dense form could get results faster if there is enough memory; on the other hand, if the sparsity is very high, using the dense form not only leads to low efficiency, but it also wastes memory. From our empirical studies of cuSPARSE and cuBLAS, the sparse algorithm of cuSPARSE requires the matrix sparsity to be larger than $0.99$ to outperform the dense counterpart of cuBLAS. One of our key observations of cuSPARSE is that it has many slow memory access that easily leaves the computational resources (i.e., cores) stale in its SpDM APIs. To this end, we would like to design an efficient SpDM algorithm to better utilize the GPU computational resources. Only a small number of research works focus on high-performance SpDM algorithms for modern GPUs. The most relevant work is \cite{ortega2013fastspmm}, \cite{yang2018design} and \cite{parger2020speck}\cite{jiang2020novel}. On one hand, Ortega et al. \cite{ortega2013fastspmm} try to better optimize the GPU memory access pattern (i.e., coalesced memory access) to achieve higher efficiency. On the other hand, besides the optimization of coalesced memory access, Yang et al. \cite{yang2018design} use the principles of row split \cite{bell2009implementing} and merge path \cite{merrill2016merge} in sparse matrix-dense vector multiplication (SpMV) to design more efficient algorithms for SpDM on GPUs. Jiang et al. \cite{jiang2020novel} mainly re-order the row data and Parger et al. \cite{parger2020speck} propose the parameter tuning technique to optimize the performance of SpDM. However, in \cite{yang2018design}, the authors design their algorithms mainly for the cases that the dense matrices are tall-skinny, and it requires a heuristic to choose whether to use merge-based or row split for better performance. In this paper, we not only exploit the GPU algorithm optimization principles (e.g., coalesced memory access), but also revisit the popular roofline performance model \cite{williams2009roofline} on GPUs to analyze how to increase operational intensity, and then we propose an efficient SpDM algorithm. Our contributions are summarized as follows: \begin{itemize} \item We design an efficient SpDM algorithm called GCOOSpDM on GPUs with several optimization techniques including coalescing memory access, bank conflict avoidance of the shared memory and high computation-to-memory ratios. \item We evaluate the proposed algorithm on a large number of sparse matrices including the public dataset and randomly generated matrices, and the experimental results show that GCOOSpDM outperforms cuSPARSE 1.5-8$\times$ faster in a large proportion of matrices on Nvidia GPUs. \item We conduct instruction-level analysis for the kernels of GCOOSpDM and cuSPARSE, and the profiled results confirm that our proposed algorithm uses much less slow memory access (DRAM and L2 cache) than cuSPARSE. \item As compared to cuSPARSE, GCOOSpDM decreases the sparsity requirement from $0.99$ to $0.98$ in order to outperform dense implementation of cuBLAS. \end{itemize} The rest of the paper is organized as follows. Section \ref{section:preliminaries} gives introductions to the preliminaries related to SpDM and GEMM. We present our proposed algorithm for efficient SpDM in Section \ref{section:algorithm}. The experimental evaluation and analysis are illustrated in Section \ref{section:evaluation}. Section \ref{section:relatedwork} introduces the related work, and finally we conclude this paper in Section \ref{section:conclusion}. \section{Preliminaries}\label{section:preliminaries} A multiplication of two matrices $\ma{A}\in \mathbb{R}^{m\times k}$ and $\ma{B}\in \mathbb{R}^{k\times n}$ produces an result matrix $\ma{C}\in \mathbb{R}^{m\times n}$, i.e., \begin{equation} \ma{C}(i,j)=\sum_{l=0}^{l=k-1}\ma{A}(i,l)\times \ma{B}(l, j). \end{equation} To simplify the analysis of the algorithms, we assume that the dimensions of $\ma{A}$ and $\ma{B}$ are both $n\times n$. The sparsity $s$ of matrix $\ma{A}$ is defined as the ratio of the number of zero elements over the total number of elements. \subsection{The roofline model} The roofline model \cite{williams2009roofline} is commonly used in performance modeling of multi-core/many-core architectures like GPUs \cite{kim2011performance}\cite{zhang2017understanding}\cite{konstantinidis2017quantitative}. The term operational intensity $r$ (operations per byte of DRAM traffic) is defined to predict the performance of kernels. In the model, there is an upper bound of the GPU throughput when $r$ reaches some threshold, which indicates the program is computation-bound. If $r$ is smaller than the threshold, the GPU throughput is a linear function with respect to $r$, which indicates the program is memory-bound. Using cuBLAS GEMM as an example, in Fig. \ref{fig:gpucublas}, we compare the experimental throughput of dense matrix multiplication with the theoretical throughput from roofline model on two different Nvidia GPUs, GTX980 and Titan X. Though GEMM in cuBLAS has achieved nearly optimal throughput on matrix multiplication, directly applying GEMM for sparse matrices could result in many useless calculations due to the large amount of zeros. The irregular non-zero elements in sparse matrices make the data access from global memory to registers become the bottleneck of matrix multiplication. In other words, each time of data reading from the sparse matrix, only a limited number of computational operations. Therefore, algorithms for SpDM are generally memory-bound, and for such problems, one should design the algorithm to increase $r$ to achieve higher efficiency. \begin{figure}[!h] \centering \includegraphics[width=0.8\linewidth]{cublas_model.pdf} \caption{The roofline models for theoretical peak throughput and cuBLAS throughput with single-precision on GPUs.} \label{fig:gpucublas} \end{figure} \subsection{GPU memory hierarchy} From the roofline model, one should improve the memory access efficiency to fully utilize the computational power of GPUs. There are several types of memories in the GPU memory hierarchy. From fast to slow of access speed, it contains registers, the shared memory (or L1 cache), L2 cache and the global memory \cite{volkov2008benchmarking}\cite{mei2017dissecting}\cite{mei2014benchmarking}. The shared memory and global memory are two kinds of memories that can be flexibly manipulated by programming. In general, data that is repeatedly used could be put into the shared memory or registers for better utilization of GPU cores. \subsection{COO: The coordinate storage format} Assume that the matrix is a row-major matrix. The coordinate storage format (COO) \cite{bell2009implementing} is a simple storage scheme for sparse matrices. COO uses an array $values$ to store the values of all non zero elements. The coordinate information of each non zero element is sequentially stored in array $rows$ and array $cols$ respectively. Take a real-valued example of a $4\times 4$ sparse matrix as follows: \[ \ma{A}= \begin{bmatrix} 7 & 0 & 0 & 8 \\ 0 & 10 &0 & 0 \\ 9 & 0 & 0 & 0 \\ 0 & 0 & 6 & 3 \end{bmatrix}, \] the COO format of $\ma{A}$ is represented by \begin{align*} values&=[7,8,10,9,6,3],\\ rows &=[0,0,1,2,3,3],\\ cols &=[0,3,1,0,2,3]. \end{align*} \section{Efficient Algorithm Design}\label{section:algorithm} In this section, we describe the design of our proposed efficient SpDM algorithm on GPUs including the customized storage format for sparse matrices and its conversion from the dense ones. According to the above analysis in operations of SpDM on GPUs, we first design a new sparse format called grouped COO (GCOO), which is convenient for coalesced memory access and is useful to increase the operational intensity $r$. Then we propose an efficient SpDM algorithm by using GCOO. \subsection{GCOO: Grouped COO storage format} A similar format of GCOO is the sliced COO (SCOO) format proposed in \cite{dang2012sliced}, with which the authors achieved higher throughput on sparse matrix-vector multiplication (SpMV) on both CPUs and GPUs. In this paper, we bring the idea of SCOO to propose GCOO for matrix multiplication. The sparse matrix is partitioned to $g$ groups according to the number of columns $n$, and each group is stored in the COO format, so we call it GCOO. For an $n\times n$ matrix stored in the GCOO format, there are $g=\lfloor \frac{n+p-1}{p} \rfloor$ groups, and each group contains $p$ columns except the last one who has $n-(g-1)\times p$ columns. If $n$ is divisible by $p$, then the last group also has $p$ columns. In GCOO, each group is stored in the COO format, and COOs from all groups are concatenated into one array. Let group $i$ be stored in the COO format with $rows_i$, $cols_i$ and $values_i$, where $i=0,1,...,g-1$. We have the stored values of GCOO with $rows$, $cols$ and $values$ that are generated from the concatenation of $rows_i$, $cols_i$ and $values_i$ respectively. \begin{figure}[!h] \centering \includegraphics[width=0.4\linewidth]{gcooformat.pdf} \caption{An example of GCOO. It has 2 groups, and each group contains 2 columns (i.e., $p=2$).} \label{fig:gcoo} \end{figure} An example of grouping in matrix $\ma{A}$ is shown in Fig. \ref{fig:gcoo}. Matrix $\ma{A}$ is divided into to 2 groups. Group $0$ is represented by $rows_0=[0,1,2]$, $cols_0=[0,1,0]$ and $values_0=[7,10,9]$; and group $1$ is represented by $rows_1=[0,3,3]$, $cols_1=[3,2,3]$ and $values_1=[8,6,3]$. Finally, two groups are concatenated into one array with an extra index array $gIdxes$ to indicate which positions are corresponding to related groups. Therefore, the final stored format of GCOO is as follows: \begin{align*} values&=[7,10,9,8,6,3],\\ rows &=[0,1,2,0,3,3],\\ cols &=[0,1,0,3,2,3],\\ gIdxes &=[0,3], \end{align*} where $gIdxes$ is an auxiliary array to store the group indexes. It is noted that $rows$, $cols$ and $values$ in GCOO are not the same as those of COO since a single group in GCOO is in a COO format. In order to easily access each group's elements, we use an extra auxiliary array, $nnzPerGroup$, to store the number of non-zero elements in each group. In the above example, the values of $nnzPerGroup$ should be: \begin{align*} nnzPerGroup &=[3,3]. \end{align*} In practice, GCOO spends slightly more memory space than COO and CSR, but it provides more convenient access of data with a higher probability. The comparison of memory consumption to store an $n\times n$ matrix with a sparsity of $s$ (note that $nnz=s\times n^2$) is shown in Table \ref{table:memcon}. \begin{table}[!ht] \centering \caption{Memory consumption of different formats.} \label{table:memcon} \begin{tabular}{|l|l|} \hline Format& Memory complexity \\\hline \hline CSR & $2\times nnz+n$ \\\hline COO & $3\times nnz$ \\\hline GCOO & $3\times nnz + 2\times \lfloor \frac{n+p-1}{p} \rfloor$\\\hline \end{tabular} \end{table} The main advantage of GCOO is to help reuse the data from slow memories (e.g., global memory and L2 cache). Specifically, if there exist two or more continuous non-zero elements in one group that are in the same row, then the fetched element from the dense matrix $\ma{B}$ can be reused in the register instead of being read from the slow memory again. \subsection{Matrix conversion to GCOO} For the cases that the input matrices $\ma{A}$ and $\ma{B}$ are stored in the dense form, there would be an extra overhead in the format conversion to apply the SpDM algorithm. For example, cuSPARSE provides an API ``cusparseSdense2csr'' to convert the dense matrix to the CSR format so that one can apply the SpDM APIs. For our proposed GCOO, we also need to provide an efficient conversion scheme to convert the dense matrix to GCOO. We use two steps to convert the dense matrix to the GCOO storage. Step 1: Count the number of non-zero elements. To convert a dense form of a matrix to the sparse form, one should first count the number of non-zero elements ($nnz$) of that matrix in order to allocate the memory according to the value of $nnz$. As for GCOO, we have pre-grouped the matrix by pre-defined $p$, so it is straightforward to calculate the non-zero elements in parallel for different groups such that the array $nnzPerGroup$ can also be calculated. Therefore, in this step, $nnz$, $gIdxes$ and $nnzPerGroup$ can be calculated by scanning the original dense matrix. Step 2: Store the non-zero elements to $rows$, $cols$ and $values$. First, the memories of $rows$, $cols$ and $values$ are allocated according to $nnz$, and then we can read the non-zero elements with their coordinate information and write them to $rows$, $cols$, and $values$ according to the indexes by $nnzPerGroup$ in parallel. The pseudocode of the matrix conversion on the GPU from the dense form to GCOO is shown in Algorithm \ref{algo:gcooconv}. \begin{algorithm}[!ht] \caption{convertToGCOOFormat}\label{algo:gcooconv} \textbf{Input: } $A, wA, hA, p$\\ \textbf{Output: $values, cols, rows, gIdxes, nnzPerGroup$} \begin{algorithmic}[1] \small \State $nGroup = (hA + p - 1) / p$; \State Allocate memory for $gIdxes$ and $nnzPerGroup$ according to $nGroup$; \State Calculate $gIdxes$ and $nnzPerGroup$ and $nnz$ by scanning $\ma{A}$; \State Allocate memory for $values$, $cols$, and $rows$ according to $nnz$; \State Set values of $values$, $cols$ and $rows$ by scanning $\ma{A}$; \end{algorithmic} \end{algorithm} \subsection{GCOOSpDM: an efficient SpDM algorithm} In the proposed algorithm GCOOSpDM, we focus on three factors that have major impact on the performance. 1) Data partition for the CUDA execution context \cite{nvidia2010programming}. 2) The coalesced memory access of global memory on the sparse matrix $\ma{A}$ and the two dense matrices $\ma{B}$ and $\ma{C}$. 3) When exploiting the faster memory on Nvidia GPUs with the shared memory, we guarantee that the access of the shared memory has no bank conflict. 4) After accessing a single element of the sparse matrix $\ma{B}$, we strive to calculate more results for $\ma{C}$, i.e., achieving higher operational intensity, so that we can achieve higher GFLOPS. \textbf{Data partition of matrices}. In the context of CUDA, a \textit{thread} is the smallest execution unit of instructions. A group of threads forms a \textit{thread block}, which is executed in a stream multiprocessor (SM) of GPU. Multiple \textit{thread blocks} form a \textit{grid}, and some \textit{thread blocks} are executed in parallel on different SMs at one time. Let $b$ denote the size of a thread block. In our algorithm, each thread block calculates $b\times p$ elements of $\ma{C}$ separately, so a resulting $n\times n$ matrix requires $\lceil \frac{n}{b} \rceil\times \lceil \frac{n}{p} \rceil$ thread blocks. All threads in a thread block share a group of sparse data of $\ma{A}$, but each thread reads continuous columns $\ma{B}$ to do the operations of multiplication and addition to the continuous columns of $\ma{C}$. An example of data partition for $b=4, p=2$ and $n=6$ is shown in Fig. \ref{fig:multiplication}. In the grid, it has 6 thread blocks. Each thread block contains $b=4$ threads, and it calculates 8 elements of $\ma{C}$. Each thread calculates $p=2$ elements of $\ma{C}$. \textbf{Coalesced memory access}. Three matrices including one sparse matrix $\ma{A}$ with the GCOO format and two dense arrays ($\ma{B}$ and $\ma{C}$) are needed to interactive with the global memory. Irregular global memory access would result in performance degradation on modern GPUs, so we should read the input matrices ($\ma{A}$ and $\ma{B}$) and write the output matrix $\ma{C}$ in a coalesced way. First, we consider the sparse matrix $\ma{A}$ stored with the GCOO format. Since each group in GCOO of $\ma{A}$ is assigned to one thread block, we just need to consider the block level access of one group of GCOO, i.e., a COO format that has $p$ columns. The number of floating point operations is determined by the number of nonzero elements of $\ma{A}$, so we scan COO to find the corresponding columns of $\ma{B}$. Due to the sparse property, COO could not have many elements, which means we can load COO to the shared memory such that all the threads can read the data fast. Therefore, the $b$ threads in one thread block read $b$ elements of COO from the global memory to the shared memory in a coalesced way. After $\ma{A}$ has been put into the shared memory, it is no need to re-read the elements of $\ma{A}$ from the global memory. Second, the dense matrix of $\ma{B}$ should be read-aware. The matrix $\ma{B}$ only needs to be accessed when a $(col, row, a)$ of COO has been read from the shared memory, so every thread reads the same $(col, row, a)$, the corresponding column of $\ma{B}$ should be same while the rows should be different to keep all the threads busy and work balance. So threads $t_0, t_1, ..., t_{b-1}$ need to read $\ma{B}(row_0, col), \ma{B}(row_1, col), ..., \ma{B}(row_{b-1}, col)$ in the current block respectively. In order to support the coalesced memory read of $\ma{B}$, the row elements should be in the continuous memory. It is easy to do this because we can just transpose $\ma{B}$ or store $\ma{B}$ in a column-major matrix such that the above elements are in the continuous memory. Finally, for the result matrix $\ma{C}$, we should only write the matrix once with the final result for each thread to achieve higher throughput. As discussed above, thread $t_i$ reads $(col, row, a)$ of $\ma{A}$, and multiplies with the elements indexed by $(row_i, col)$ in $\ma{B}$, so the write position of $\ma{C}$ should be $(row, row_i)$. As a result, $\ma{C}$ should also be column-major or transposed for the coalesced memory writing. \textbf{None bank conflict access of the shared memory}. The shared memory used in our algorithm is only proper to the sparse matrix of $\ma{A}$ with the COO format (in one thread block). The kernel allocates a fixed size $b$ of shared memory, and the threads in one thread block read $b$ non-zero elements from $\ma{A}$ each time. Since all the threads in one thread block need to read all elements of $\ma{A}$ to calculate the corresponding columns of $\ma{C}$, all threads read the same element of $\ma{A}$. Therefore, the data in the shared memory can be accessed by all threads in a broadcast way \cite{nvidia2010programming}, which would not result in any bank conflict, and the broadcast access of the shared memory requires only a very small number of clock cycles to fetch the data. \textbf{High computation-to-memory ratio}. Achieving a high operational intensity $r$ is very important to a high throughput. Regarding the multiplication and accumulation of each thread, each thread reads the shared memory of $\ma{A}$ to get $(col, row, a)$ (donated by $a_r$), and then multiplies $\ma{B}(row_i, col)$ (donated by $b_r$) of $\ma{B}$. In such scenario, we have two opportunities to have more calculations with $a_r$ and $b_r$ since they have been loaded into the registers. The first chance is to find other element of $\ma{B}$ to be multiplied with $a_r$, but the other element that can be multiplied with $a_r$ has been assigned to the other block, so this chance cannot be fulfilled. The second one is to find a next element of $\ma{A}$ who has the same column with the previous one while its row is different, i.e., $(col, row_1, a)$. Therefore, we can search the next $a_{r1}$ (since $\ma{A}$ has been loaded in the shared memory, the time cost of searching is low.) to reuse $b_r$. If such an $a_{r1}$ exists, then we can have $b$ times of multiplication and accumulation without an extra global memory (or L2 cache) access, which results in a higher $r$. For a uniform distributed sparse matrix with sparsity of $s$, there could be $(1-s)\times n$ non-zero elements in the same column. According to the above four criteria, we conclude the GCOOSpDM algorithm with the following three steps. Step 1. Each thread block iteratively reads the COO values into the shared memory such that all threads in this thread block can read the COO values for their rows. We exactly know the columns that we need to calculate in the current thread block. Step 2. The $t^{th}$ thread scans the COO items from the shared memory, and the item contains $row$, $col$ and $value$. According to $col$, the thread reads the element $B(t,col)$ of $\ma{B}$, and then performs the multiplication of $value \times B(t, col)$, whose result is added to the local variable $c_{t,col}$. I.e., $c_{t,col}+=value \times B(t, col)$. Step 3. Since the current group of data is stored as the COO format, for the current element $(row, col, value)$, its next element should have the same $col$ index if that column has more than one element. So we continue scanning the shared memory to check if there are elements that have the same $col$ such that we can reuse the element of $B(t, col)$. \begin{figure}[!h] \centering \includegraphics[width=\linewidth]{multiplication.pdf} \caption{Partition of matrices. $\ma{A}$ is the sparse matrix, $\ma{B}$ is the dense matrix, and $\ma{C}$ is the result matrix.} \label{fig:multiplication} \end{figure} The visualization of the algorithm executed with the CUDA programming model is shown in Fig. \ref{fig:multiplication}. On the grid level, there are 6 thread blocks, and each thread block calculates the results of sub-matrix with size of $b\times p$ from $b$ rows of $\ma{B}$, and $p$ columns (i.e., one group in GCOO) of $\ma{A}$. On the thread block level, the GCOO data of sparse matrix are loaded into faster memory once (the shared memory) which is shared among all the threads in the thread block. On the thread level, each thread independently takes charge of computing $p$ elements of $\ma{C}$, say the thread scans the shared memory to read $row$, $col$ and $value$, and then reads the values in column $row$ of $\ma{B}$, which are multiplied by $value$ separately, and each result is accumulated to column $col$ of $\ma{C}$. The algorithm of GCOOSpDM is shown in Algorithm \ref{algo:gcoospdm}. In Algorithm \ref{algo:gcoospdm}, we first (line 1-10) initialize some local variables including the thread level indexes of output and COO for the current thread block. Then we iteratively scan a block of COO in the for-loop of line 11, and at each iteration, a thread block of COO values are loaded into the shared memory (line 12-15). After that each value of COO in the shared memory is read by all the threads in one thread block, and the corresponding value $b$ in $\ma{B}$ is also read to calculate the result (line 21-26). Instead of continuing the above step, we keep the value of $b$ in the register, and scan the shared COO to check whether we can reuse $b$ so that less memory operations are required (line 28-36). By this way, we can achieve higher operational intensity, i.e., $b$ is reused to do more floating point calculations. At the end, the local results of each thread are written back to $\ma{C}$ that is stored in the global memory with corresponding indexes (line 38-39). Note that both reading of matrix $\ma{A}$ and matrix $\ma{B}$ from the global memory is in a coalescent way, the result writing to matrix $\ma{C}$ is also coalescent. In term of access of the shared memory, it broadcast the data to all the threads in a warp with a small number of cycles. \begin{algorithm}[!ht] \caption{GCOOSpDM}\label{algo:gcoospdm} \textbf{Input: } $values, cols, rows, gIdxes, nnzPerGroup, wA, hA, \\B, wB, hB, C$\\ \textbf{Output: $C$} \begin{algorithmic}[1] \small \State $Cj = blockIdx.y*b+threadIdx.x$; \State $Ci0 = blockIdx.x*p$; \State Initial local temporary results $c[0...p]$; \State Set number of non-zero elements of current group: $nnz$; \State // Set the current group of COO \State $vals=values+gIdxes[blockIdx.x]$; \State $cols=cols+gIdxes[blockIdx.x]$; \State $rows=rows+gIdxes[blockIdx.x]$; \State $iter=(b+nnz-1)/b$; \State $extra = nnz \& (b - 1)$; \For{$i=0 \rightarrow iter$} \State $cooOffset=i*b$; \State $sVals[threadIdx.x]=vals[cooOffset]$; \State $sCols[threadIdx.x]=cols[cooOffset]$; \State $sRows[threadIdx.x]=rows[cooOffset]$; \State $cnnz=\text{max}(extra, b)$; \State $\_\_$syncthreads(); \If{$Cj<wB$} // Not exceed the boundary \State $k=1$; \For{$j=0\rightarrow cnnz, step=k$} \State $col = sCols[j]$; \State $row = sRows[j]$; \State $av=sVals[j]$; \State $bv=B[col*wB+Cj]$; // Registered. \State $outIdx=row\&(p-1)$; \State $c[outIdx]+=av*bv$; \State $k=1$; \While{$j+k<cnnz$} // Search $A$ to reuse $bv$ \State $newCol=sCols[j+k]$; \If{$newCol \neq col$} \State break; \EndIf \State $av=sVals[k+j]$; \State $row = sRows[k+j]$; \State $outIdx=row\&(CPG-1)$; \State $c[outIdx]+=av*bv$; \State $k+=1$; \EndWhile \EndFor \EndIf \State $\_\_$syncthreads(); \EndFor \For{$i=0 \rightarrow p$} // Write results to the global memory \State $C[Cj+(Ci0+i)*wB]=c[i]$; \EndFor \end{algorithmic} \end{algorithm} \section{Evaluation and Analysis}\label{section:evaluation} To show the effectiveness of our proposed algorithm, we do varies of experiments across three Nvidia GPU cards (i.e., GTX 980, GTX Titan X Pascal and Tesla P100) using two kinds of data. The first one is the public sparse matrix dataset \cite{davis2011university} which has different patterns of matrices, and the second one is randomly generated matrices whose zero-valued elements have a uniform distribution.\footnote{Codes of GCOOSpDM and scripts of performance evaluation can be found in \url{https://github.com/hclhkbu/gcoospdm}. And the raw data of our experimental results can be found in: \url{https://github.com/hclhkbu/gcoospdm/tree/master/results}.} The characteristics of tested GPUs are shown in Table \ref{table:gpus}. And the software installed is CUDA-8.0. \begin{table}[!ht] \centering \caption{Characteristics of tested GPUs.} \label{table:gpus} \begin{tabular}{|l|l|l|l|} \hline Model& GTX980 &TitanX & P100 \\\hline \hline SMs $\times$ cores per SM & 16$\times$128 & 28$\times$128 & 56$\times$64 \\\hline Peak TFLOPS &4.981 & 10.97 & 9.5 \\\hline Memory Bandwidth (GB/s) &224 & 433 & 732 \\\hline \end{tabular} \end{table} \subsection{Results on public sparse matrices} We use the public sparse matrices in \cite{davis2011university}. Since we only consider the schemes of square matrices, we pick up all the square matrices in the dataset to evaluate the performances of GCOOSpDM and cuSPARSE. The chosen dataset contains 2694 matrices, whose sparsity is in the range of $[0.98, 0.999999]$, and their dimensions are in the range of $[64, 36720]$. The performance comparison between GCOOSpDM and cuSPARSE is shown in Fig. \ref{fig:realdata}, where $T_{algorithm}$ is used to denote the execution time of $algorithm$. We first compare the overall performance of our algorithm with cuSPARSE on the 2694 matrices, and we then choose 14 types of matrices from varies of applications to compare the performance of the algorithms. \textbf{Overall performance}. In the 2694 tested matrices, there are about $78\%$ matrices that GCOOSpDM outperforms cuSPARSE on the P100 GPU, and there are more than $90\%$ matrices that GCOOSpDM achieves better performance than cuSPARSE on both GTX980 and TitanX. The average speedups are $1.66\times$, $1.7\times$ and $1.68\times$ on GTX980, TitanX and P100 respectively. Moreover, the maximum speedups of GCOOSpDM are $4.5\times$, $6.3\times$ and $4.2\times$ on GTX980, TitanX and P100 GPUs respectively. By contrast, on the $22\%$ matrices that cuSPARSE is better than GCOOSpDM on the P100 GPU, cuSPARSE only outperforms GCOOSpDM about $1.2\times$ on average. On GTX 980 and Titan X GPUs, there are about $10\%$ cuSPARSE outperforming GCOOSpDM about $1.14\times$. cuSPARSE performs better on the P100 GPU than GTX 980 and TitanX GPUs mainly because the P100 GPU has a much higher memory bandwidth than the other two GPUs as shown in Table \ref{table:gpus}. \begin{figure}[!h] \centering \subfigure[GTX 980] { \includegraphics[width=0.32\linewidth]{real980_frequency.pdf} }\hspace{-3.5mm} \subfigure[Titan X Pascal] { \includegraphics[width=0.32\linewidth]{realtitanx_frequency.pdf} }\hspace{-3.5mm} \subfigure[Tesla P100] { \includegraphics[width=0.32\linewidth]{realp100_frequency.pdf} } \caption{The performance comparison with the frequency of the time ratio between cuSPARSE and GCOOSpDM with the public dataset on three GPUs. The last value (i.e., 2.0+) of x-axis means that $T_{cuSPARSE}/T_{GCOOSpDM} \ge 2.0$.} \label{fig:realdata} \end{figure} \begin{table}[!ht] \centering \caption{Details of selected sparse matrices.} \label{table:selectedmatrx} \begin{tabular}{|l|l|l|l|} \hline Matrix & $n$ & Sparsity & Related Problem\\\hline \hline nemeth11&9506&2.31e-03&Quantum Chemistry \\\hline human\_gene1&22283&2.49e-02&Undirected Weighted Graph\\\hline Lederberg&8843&5.32e-04&Directed Multigraph\\\hline m3plates&11107&5.38e-05&Acoustics \\\hline aug3dcqp&35543&6.16e-05&2D/3D \\\hline Trefethen\_20000b&19999&7.18e-04&Combinatorial \\\hline ex37&3565&5.32e-03&Computational Fluid\\\hline g7jac020sc&5850&1.33e-03&Economic \\\hline LF10000&19998&1.50e-04&Model Reduction \\\hline epb2&25228&2.75e-04&Thermal \\\hline plbuckle&1282&9.71e-03&Structural \\\hline wang3&26064&2.61e-04&Semiconductor Device \\\hline fpga\_dcop\_01&1220&3.96e-03&Circuit Simulation \\\hline viscoplastic2\_C\_1&32769&3.55e-04&Materials \\\hline \end{tabular} \end{table} \textbf{14 types of matrices}. It can be seen that GCOOSpDM does not always outperform cuSPARSE. To further understand the main reasons, we select 14 types of matrices that have different structures and non-zero patterns from a range of areas to analyze their performance differences. The details of the selected matrices are shown in Table \ref{table:selectedmatrx}. To normalize the algorithm performances, we use effective GFLOPS to measure the algorithms as the following Equation \begin{equation}\label{equ:perf} P_{algorithm}=\frac{2\times n^3\times (1-s)}{T_{algorithm}}. \end{equation} The performance comparison is shown in Fig. \ref{fig:realbar}. On three matrices (``nemeth11'', ``plbuckle'' and ``fpga\_dcop\_01''), GCOOSpDM is worse than cuSPARSE due to the non-zero distribution of the matrices. On these three matrices, the non-zero elements are mainly located on the diagonal of the matrices, such that there is little opportunity to reuse the pre-fetched value of $bv$ (i.e., line 30 will intermediately hold and no further calculations for current $bv$), but it still spends extra overheads to search $\ma{A}$. \begin{figure}[!ht] \centering \includegraphics[width=0.9\linewidth]{realbarp100.pdf} \caption{The performance comparison of selected matrices on a Tesla P100 GPU. (The higher the better.)} \label{fig:realbar} \end{figure} \subsection{Random sparse matrices} We randomly generate square matrices whose dimension are in the range of $[400, 14500]$ with a step size of $100$. For each size of a matrix, we generate the elements with the sparsity in two ranges (i.e, $[0.8,0.995]$ at a $0.005$ step and $[0.995, 0.9995]$ at a $0.0005$ step). In total, there are $6968$ matrices with uniformly distributed non-zero elements for evaluation. \textbf{Overall performance}. The performance comparison between GCOOSpDM and cuSPARSE using the randomly generated matrices is shown in Fig. \ref{fig:sythperf}. Our GCOOSpDM algorithm outperforms cuSPARSE in $99.51\%$, $99.23\%$ and $97.37\%$ matrices on GTX980, TitanX and P100 GPUs respectively, and the average speedups are $2.13\times$, $2\times$ and $1.57\times$ respectively. Particularly, the maximum speedups on the three GPUs are $4.7\times$, $6.5\times$ and $8.1\times$ respectively. On the cases that cuSPARSE is better GCOOSpDM, they only occupy a very small proportion (less than $3\%$), and the average performance ratio is only around $1.17$, which indicates very close performance on less than $3\%$ cases. \begin{figure}[!h] \centering \subfigure[GTX 980] { \includegraphics[width=0.32\linewidth]{syth980_frequency.pdf} }\hspace{-3.5mm} \subfigure[Titan X Pascal] { \includegraphics[width=0.32\linewidth]{sythtitanx_frequency.pdf} }\hspace{-3.5mm} \subfigure[Tesla P100] { \includegraphics[width=0.32\linewidth]{sythp100_frequency.pdf} } \caption{The performance comparison with the frequency of the time ratio between cuSPARSE and GCOOSpDM with the random generated sparse matrices on three GPUs. The last value (i.e., 2.0+) of x-axis means that $T_{cuSPARSE}/T_{GCOOSpDM} \ge 2.0$.} \label{fig:sythperf} \end{figure} \begin{figure}[!h] \centering \subfigure[$n=4000$] { \includegraphics[width=0.48\linewidth]{perfvssparsity980_4000.pdf} }\hspace{-3mm} \subfigure[$n=14000$] { \includegraphics[width=0.48\linewidth]{perfvssparsity980_14000.pdf} } \caption{Performance vs. sparsity on the GTX980 GPU. The lower the better.} \label{fig:perfvssparsity980} \end{figure} \begin{figure}[!h] \centering \subfigure[$n=4000$] { \includegraphics[width=0.48\linewidth]{perfvssparsitytitanx_4000.pdf} }\hspace{-3mm} \subfigure[$n=14000$] { \includegraphics[width=0.48\linewidth]{perfvssparsitytitanx_14000.pdf} } \caption{Performance vs. sparsity on the TitanX GPU. The lower the better.} \label{fig:perfvssparsitytitanx} \end{figure} \begin{figure}[!h] \centering \subfigure[$n=4000$] { \includegraphics[width=0.48\linewidth]{perfvssparsityp100_4000.pdf} }\hspace{-3mm} \subfigure[$n=14000$] { \includegraphics[width=0.48\linewidth]{perfvssparsityp100_14000.pdf} } \caption{Performance vs. sparsity on the P100 GPU. The lower the better.} \label{fig:perfvssparsityp100} \end{figure} \textbf{Time vs. sparsity}. As we have shown the efficiency of GCOOSpDM in large range of matrices and sparsity, we want to study further about the performance related to the sparsity $s$. We take two matrices with medium ($n=4000$) and large ($n=14000$) dimensions to show the relationship between performance and sparsity. The range of sparsity is kept at $[0.95, 0.9995]$. Here we also put the time cost of the dense algorithm from cuBLAS into comparison so that we can understand under what sparsity GCOOSpDM can outperform cuBLAS. The results for these two sizes of matrices on GTX980, TitanX and P100 GPUs are shown in Fig. \ref{fig:perfwithspar980}, \ref{fig:perfwithspartitanx} and Fig. \ref{fig:perfwithsparp100}, respectively. On one hand, it can be seen that cuBLAS has a constant time cost when the sparsity of matrix increases since the dense algorithm does not consider zero values. On the other hand, the sparse algorithms of cuSPARSE and GCOOSpDM tend to have a linear speedup when the sparsity increases. Given the two specific dimensions of matrices, GCOOSpDM outperforms cuSPARSE with all sparsity. When the sparsity becomes larger than some thresholds, the sparse algorithm would have advantages than the dense one. However, cuSPARSE needs the sparsity be up to $0.995$ to outperform cuBLAS, while our proposed algorithm GCOOSpDM can outperform cuBLAS with sparsity larger than $0.98$. In summary, the GCOOSpDM algorithm is more applicable for matrix multiplication on GPUs than cuSPARSE and cuBLAS under sparsity larger than $0.98$ to achieve higher performance on current GPUs. \begin{figure}[!h] \centering \subfigure[$s=0.98$] { \includegraphics[width=0.48\linewidth]{effective_flops980098.pdf} }\hspace{-3mm} \subfigure[$s=0.995$] { \includegraphics[width=0.48\linewidth]{effective_flops9800995.pdf} } \caption{Performance vs. dimension on GTX980. The higher the better.} \label{fig:perfwithspar980} \end{figure} \begin{figure}[!h] \centering \subfigure[$s=0.98$] { \includegraphics[width=0.48\linewidth]{effective_flopstitanx098.pdf} }\hspace{-3mm} \subfigure[$s=0.995$] { \includegraphics[width=0.48\linewidth]{effective_flopstitanx0995.pdf} } \caption{Performance vs. dimension on TitanX. The higher the better.} \label{fig:perfwithspartitanx} \end{figure} \begin{figure}[!h] \centering \subfigure[$s=0.98$] { \includegraphics[width=0.48\linewidth]{effective_flopsp100098.pdf} }\hspace{-3mm} \subfigure[$s=0.995$] { \includegraphics[width=0.48\linewidth]{effective_flopsp1000995.pdf} } \caption{Performance vs. dimension on P100. The higher the better.} \label{fig:perfwithsparp100} \end{figure} \textbf{Performance vs. matrix size}. To further show the sensitivity of the algorithm to the matrix size, we demonstrate the throughput (GFLOPS) in a range of matrix dimensions (i.e., $n\in [400, 14000]$) at two sparsity $0.98$ and $0.995$. The experimental results with sparsity of $0.98$ and $0.995$ are in Fig. \ref{fig:perfwithspar980}, \ref{fig:perfwithspartitanx} and \ref{fig:perfwithsparp100} on three different GPUs. On the three tested GPUs, GCOOSpDM outperforms cuSPARSE with different values of $n$ and two sparsity. For small matrices (e.g., $n<1500$), cuBLAS still outperforms GCOOSpDM since it takes only a small number of cycles in calculating small matrices while GCOOSpDM needs extra overheads on memory allocation and matrix conversion. Given the sparsity of $0.98$ and $n>2000$, GCOOSpDM achieves similar performance as (or slightly better than) cuBLAS. With the sparsity of $0.995$, cuSPARSE achieves close performance with cuBLAS, while GCOOSpDM outperforms cuBLAS up to $2$ times. \subsection{Breakdown of time costs} In this subsection, assume that given $\ma{A}$ and $\ma{B}$ are both in the dense form, while $\ma{A}$ is of high sparsity, we would like to present the time costs of matrix conversion and the kernel calculation to finish the matrix multiplication using the sparse algorithm. The different overheads are summarized into three categories: memory allocation for sparse matrix storage, matrix conversion from the dense form to the sparse form, and SpDM kernel calculation. We summarize the first two categories as an extra overhead (EO), and the third one as the real time cost of kernel calculation (KC). The metrics of EO and KC are used to compare GCOOSpDM and cuSPARSE. Instead of using three GPUs, we only choose a TitanX GPU as our analysis platform, since three GPUs should have similar time distribution. Similar to the previous subsection, we use two sizes of matrices (i.e., $n=4000$ and $n=14000$) with sparsity of $[0.95, 0.96, 0.97, 0.98, 0.99]$ for comparison. The results are shown in Fig. \ref{fig:breakdown}. It can be seen that EO has only a small proportion of the total time, and both GCOOSpDM and cuSPARSE have a very close overhead of EO. The dominated part is the execution time of the kernel that calculates the matrix multiplication. \begin{figure}[!h] \centering \subfigure[$n=4000$] { \includegraphics[width=0.48\linewidth]{breakdown_4000.pdf} }\hspace{-3mm} \subfigure[$n=14000$] { \includegraphics[width=0.48\linewidth]{breakdown_14000.pdf} }\hspace{-3mm} \caption{Time breakdown for two sizes of matrices. ``GCOO.'' represents the GCOOSpDM algorithm, and ``cuSPA.'' represents the algorithm in cuSPARSE.} \label{fig:breakdown} \end{figure} \subsection{Instruction analysis} \input{performance_analysis} \section{Related work}\label{section:relatedwork} Multiplication of sparse matrices to dense vectors (SpMV) on GPUs have been well studied (e.g., \cite{greathouse2014efficient}\cite{hou2017auto}\cite{bell2009implementing}\cite{merrill2016merge}). Even SpDM can be implemented by multiple SpMVs, the performance could be bad due to a large number of kernel invokes if the matrix is with a large dimension. However, some optimization principles can be applied for SpDM. For example, Yang et al. \cite{yang2018design} use split row \cite{bell2009implementing} and merged path \cite{merrill2016merge} to design SpDM algorithms particularly for tall-skinny matrices. Regarding the SpDM algorithm analysis, Greiner et al. \cite{greiner2010complexity} propose an I/O model to interpret the lower bound of efficient serial algorithms. Cache oblivious dense and sparse matrix algorithms are presented by Bader et al. for multi-core CPUs \cite{bader2008cache}. Performance benchmarks \cite{ezouaoui2013performance} are conducted to evaluate the efficiency of different sparse matrix formats for SpDM. Koanantakool et al., \cite{koanantakool2016communication} introduce the communication-avoiding SpDM algorithms that are applied in distributed memory systems. Recent work in designing the row reordering technique to achieve better data temporal locality \cite{jiang2020novel} and the dynamic parameter tuning \cite{parger2020speck} to improve the SpDM performance on GPUs. \section{Conclusion and Future Work}\label{section:conclusion} Sparse-dense matrix-matrix multiplication is commonly used in many scientific computing areas, while designing such algorithms on modern GPUs is non-trivial due to the irregular structure of the sparse matrix. In this paper, we propose an efficient sparse matrix-dense matrix multiplication algorithm on GPUs, called GCOOSpDM. The main optimization techniques used in our algorithm are the coalesced global memory access, proper usage of the shared memory, and reuse the data from the slow global memory. The experimental results show that our proposed algorithm outperforms the vendor-based library: cuSPARSE several times on both the public sparse dataset and randomly generated matrices on three recent Nvidia GPUs (i.e., GTX 980, Titan X Pascal, and Tesla P100). We also analyze in depth the performance improvement on instruction-level to understand why GCOOSpDM performs better than cuSPARSE. The key observation of the instruction-level analysis is that the reduced number of global memory access contributes a lot to the performance gain. It is difficult for a single algorithm to fit all structures of matrices, sparsity and different types of GPUs. Auto-tune algorithms play an important role for algorithms to find efficient configuration or implementations in different cases. We would like to consider the auto-tune scheme to set proper $p$ and $b$ for our GCOOSpDM algorithm in the future work, and try to extend the GCOO storage format to the multiplication of two sparse matrices. \bibliographystyle{IEEEtran} \Urlmuskip=0mu plus 1mu
{'timestamp': '2020-06-01T02:09:28', 'yymm': '2005', 'arxiv_id': '2005.14469', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14469'}
arxiv
\section{Introduction} The field of network medicine has gained tremendous traction in recent years. With the growth of public disease datasets and development in computational methods, several recent works have attempted to use data-driven methods to study disease progression \cite{OXT18,KHO19}. Network medicine \cite{6,8,9,10,SON19} offers innovative data-driven solutions to disease modeling through analyzing complex interactions within data. For instance, \cite{10} identifies disease-related genetic variants through network-based studies of the human disease network (i.e. the ‘diseaseome’), in which diseases are linked if they share one or more associated genes. Functional brain networks for neurobiologically relevant graphical properties of Alzheimers disease are analyzed in \cite{JAL17}. However, network-based patient subtyping based not only on disease variable values but also on their trajectories, i.e., evolution of variable patterns, is relatively unexplored. Parkinson’s Disease, a degenerative neurological disorder, is the second most common neurodegenerative disorder following Alzheimer’s disease, affecting an estimated 7-10 million people worldwide \cite{1}. It is both chronic, meaning it persists over a long duration, and progressive, meaning symptoms, such as tremor, loss of memory, impaired balance etc. worsen with time \cite{SCH06,LEW05}. In addition, it is a highly variable disease, with rate and type of progression differing significantly across the population \cite{2}. It is increasingly evident that Parkinson's disease is not a single entity but rather a heterogeneous disorder with multiple subtypes. Several studies have attempted to classify patients into subtypes \cite{KRI20, SAU16, VAN11, SEL09}.Two recent studies have developed models of PD progression based on clinical, demographic and genetic data at baseline, using hierarchical cluster analysis \cite{5} and a Bayesian multivariate predictive inference platform \cite{16}, to identify PD subtypes. However, there is no overall consensus on Parkinson's subtypes \cite{5}, and little is known about the effect of the interplay between different types of variables on Parkinson's progression. Early recognition of patient subtype allows medical workers to employ subtype-specific treatment, potentially improving and prolonging life \cite{MAR13,THE14}. However, current approaches in Parkinson's subtyping have largely not explored data-driven analyses to unravel multiple complex influences of a large number of longitudinal variables on disease progression \cite{24}. Sophisticated data-driven methods are required to extract meaningful information effectively from medical datasets. In recent years, several deep learning approaches to disease-subtyping have emerged \cite{ZHA19,MIO18}. However, such approaches are limited in extracting interpretable information about the micro-structure of the subtypes, i.e., the variable relationships that underlie the subtype. In contrast, network science approaches offer an intuitive visualization for modeling relationships between different types of variables. Additionally, evolving interactions between variables are easily represented through a multi-layer structure. Significant research has been done in clustering in a multi-layer network \cite{DONG12,KIM15}. However, subtyping through trajectory clustering is relatively unexplored in network medicine\cite{14,15}. This work presents a novel multi-layer-network-based Trajectory Clustering (TC) algorithm to identify disease subtypes based on similarities in trajectories through variable clusters. First, it identifies variable-communities (clusters of variables that co-express) through modeling patient-variable interactions as a bipartite network. It then tracks patient-memberships through multiple layers of variable-communities to define their trajectories. Lastly, disease subtypes are identified by clustering similar trajectories. To the best of the author's knowledge, the only other work with a trajectory-based approach to Parkinson's subtyping is the author's previous work \cite{KRI20}. While their research questions and data are the same as those in this paper, \cite{KRI20} defines trajectories as matrices (and implements a trajectory \textit{profile} clustering) which is fundamentally different than the method proposed in this paper, and yields different, although complementary, results. Additionally, it is a first-order method. In contrast, this paper defines trajectories through a multi-layer network and identifies subtypes using a graph-based second-order trajectory clustering. The novel contributions of this approach are multifold: (1) a unique subtyping approach on graphs with intuitive visualization of trajectories, (2) identification of co-expressing variable clusters in the stacked-multi-layer network offering a variable-centric perspective to disease progression (3) studying disease progression as a function of \textit{any} outcome variable (with results presented for outcome variable MDS-UPDRS3). The contributions of this work are distinct from and complementary to those in \cite{KRI20}. The contributions of this work are (a) extracting clusters of co-expressing variables at different stages of disease, and (b) identifying subtypes based on similarities in disease trajectories. The set of variable clusters identified by our network are in agreement with Parkinson's disease domains recognized in medical literature \cite{MAR18}. Disease subtypes identified are shown to be statistically distinct and are supported by the results in \cite{KRI20}. This easily generalizable approach for multi-layer trajectory clustering presents a unique way for extracting patterns of disease progression in complex longitudinal medical data, and helps bridge the gap between data-based computational approaches and applied medicine. \section{Data} Data used in the preparation of this article was obtained from the Parkinson’s Progression Markers Initiative (PPMI) database (www.ppmi-info.org/data). It consists of patient variable values across 5 timepoints: baseline year (denoted as year0) and years-1,2,3, and 4. Upon excluding patients with incomplete data, 194 patients remained in the analysis.The dataset categorizes the clinical variables into domains (Cognitive, Behavioral, Sleep, PD Severity, Autonomic, Disability) based upon functionality as shown in \ref{data}. Variable data is obtained from commonly used standard medical tests, a few of which are outlined below. JOLO is a standardized test of visuospatial skills. SDM is a test measuring neurological information processing speed and efficiency using a symbol/digit substitution tasks. HVLT is a word-learning test that measures episodic verbal memory and recall ability. SEADL assesses the difficulties patients have completing daily activities or chores. EPS test scores give a subjective measure of a patient's daytime sleepiness. STAI is used in clinical settings to diagnose anxiety and to distinguish it from depressive syndromes. The MDS - UPDRS scale includes series of ratings for typical Parkinson’s symptoms that cover all of the movement hindrances of Parkinson’s disease and consist of Mentation, Behavior and Mood, Activities of Daily Living, Motor sections etc. According to PPMI, motor assessment for variables in this dataset was performed in a `practically defined off' state, i.e., subjects are asked to withhold medication prior to the assessment for 12 hours, practically eliminating medication effects on motor symptoms. \begin{figure}[htbp!] \begin{center} \includegraphics[width=0.95\linewidth]{Images/all_figs/all_figs1} \end{center} \caption{Description of the six medical domains and their variables in the PPMI clinical dataset.} \label{data} \end{figure} \section{Network Architecture: Stacked Multi-layer Network} \label{bip} Variable-communities within each layer are identified and stacked to create a multi-layer framework across which patient trajectories are defined. This proceeds as follows: \begin{enumerate} \item Within each layer, individual-variable relationships for $I$ patients and $V$ relationships, are modeled as a bipartite network. Bipartite networks are graphs consisting of two sets of disjoint and independent nodes, such that there exist no edges between nodes belonging to the same set. They are a natural choice for modeling relationships between two different classes (in this case patients variables). The adjacency matrix $Z$ of the bipartite network is created as follows: \begin{itemize} \item The `direction' of each variable is determined. If disease progression (how severely a patient is affected) is positively correlated with values of the disease variable $v$) then the direction of the variable $d_v$ is set as +1, and if disease-affection is negatively correlated with disease variable values, then $d_v = -1$. These directions are standard and well known for variables in the PPMI clinical data. Variables ESS, RBDQ, GDS, STAI, MDS-UPDRS-1,2,3,T and Age have $d_v =1$ and HVLT, JOLO, SFT, LNS, SDM, MoCA, SEADL have $d_v =-1 $. \item The value ($F_{iv}$) of variable $v$ in individual $i$ is then converted to a z value, $z_{iv}$ that normalizes it between $0$ and $1$, \begin{equation} z_{iv} =\frac{F_{iv} - \min_{j \in I}F_{jv}}{\max_{j \in I}F_{jv}-\min_{j \in I}F_{jv}}. \end{equation} These z values are continuous and non-thresholded. \item The adjacency matrix $Z$ of size $I \times V$ for the patient-variable bipartite network is populated as \begin{equation} Z_{ij} = \cases{ z_{iv} \quad &if $d_v=1$ \\ 1-z_{iv} \quad &if $d_v=-1$.} \end{equation} \end{itemize} \item An independent patient-variable bipartite network is generated for each layer (an illustrative bipartite network is shown in figure \ref{mult_bip} (left)), where a layer could represent a time-point or a range of outcome variable values. An outcome variable is simply any variable as a function of which one may desire to measure disease progression as indicated by non-outcome variables. This paper presents results for outcome variable chosen to be MDS-UPDR3. Then Louvain community detection \cite{18} is implemented on the bipartite network for each layer $l$. Louvain community detection yields the number of communities through optimization of the Newman-Girvan modularity function \cite{19} and has no hyperparameters. It identifies variable-communities $C_k^l$, where $k \in [0, \ldots, K_l-1]$, comprising of patients and variables (shown through shaded ovals in figure \ref{mult_bip} (left)), and $K_l$ is the total number of variable-communities in layer $l$. \begin{figure}[htbp!] \begin{center} \includegraphics[width=0.95\linewidth]{Images/all_figs/all_figs2} \end{center} \caption{(left) shows a representative bipartite patient-variable network for one layer. The highlighted ovals represent variable-communitites consisting of patients and disease variables. (right) represents a stacked multi-layer graph over three layers, where the variable-communities from (left) form the first layer. Three sample trajectories are shown, and the corresponding closeness between nodes $X$ and $Y$ is calculated.} \label{mult_bip} \end{figure} The TC algorithm to cluster patient trajectories (and hence patients) is presented in sec. \ref{tc_bip}. \item These variable-communities in each layer, variable-community represented as a node, are stacked across all layers as shown in figure~\ref{mult_bip}(right). This is the stacked multi-layer graph ($G$). Each individual belongs to a variable-community $C_k^l$ at each time-point. One can then track individual $i$ membership over time to define a patient trajectory $T_i$. \end{enumerate} \section{Trajectory Clustering Algorithm} \label{tc_bip} Each node in $G$ is a variable-community. Trajectory Clustering (TC) is a second-order algorithm identifies patient subtypes based by clustering patients with similar trajectories of disease progression on the stacked multi-layer network $G$ as follows: \begin{enumerate} \item `Node closeness' $cl(X,Y)$ between two nodes $X$ and $Y$ in graph $G$ is defined as the fraction of whole or partial trajectories passing through $X$ and $Y$ that overlap. Suppose $A$ and $B$ are sets of all edges (both inter-layer and intra-layer), with repetition, that belong to trajectories passing through node $X$ and node $Y$ respectively, then node closeness between is defined as \begin{equation} cl(X,Y)=\frac{\#(A \cap B )}{\#( A \cup B)}. \end{equation} where $\#$ denotes the size of a set. Note that $cl(X,X)=1.$ Figure~\ref{mult_bip} (b) presents a simple example of node closeness calculated between nodes $X$ and $Y$. There is one overlapping edge-pair {$A_2, B_2$} on trajectories passing through nodes $X,Y$, and the total size of the set of edges on these trajectories is $3$. Hence, $cl(X,Y)=1/3$. \item Trajectory Similarity ($\eta(T_i,T_j)$) between two individual (patient) trajectories $T_i$ and $T_j$ is then given by $\Sigma_{t}cl(X(t)_{T_i},Y(t)_{T_j})$, where $X(t)_{T_i}$ is the node $X(t)$ that trajectory $T_i$ passes through at timepoint $t$. $\eta(T_i,T_j)$ measures not just first-order similarities between two trajectories, but also second-order similarities i.e., interactions between two non-overlapping trajectories that result from their mutual overlap with a third set of trajectories. Important properties of the second-order TC algorithm are outlined in \ref{timex}. \item A patient-patient network $P$ is created whose adjacency matrix is given by \begin{equation} P_{i,j}= \eta(T_i,T_j). \end{equation} . The network P contains information of how similar patients are in terms of their disease trajectories. $P_{i,j}$ gives the trajectory similarity $\eta(T_i,T_j)$ between patients $i$ and $j$. Thus a higher value of $P_{i,j}$ indicates that patients $i$ and $j$ are connected with a higher weight in the network $P$ and are correspondingly more likely to have similar disease progression patterns. $P$ is a symmetric matrix with $P_{i,i}=1$. \item Louvain community detection is implemented on the network P (for 100 runs), and the maximally occuring communtiy configuration over all runs was chosen to obtain $M$ trajectory-communities $S_k$ (where $k \in [0, \ldots M-1]$) with similar disease progression trajectories. In a modularity maximizing algorithm such as Louvain \cite{18}, the optimal number of trajectory-communities are unconstrained and automatically identified to correspond to the configuration with maximal modularity (a commonly used metric for community detection in networks). \end{enumerate} \section{Results} \subsection{Bipartite variable-communities} \begin{figure*}[ht!] \begin{center} \includegraphics[width=0.95\linewidth]{Images/all_figs/all_figs4} \end{center} \caption{Community profiles of the variable-communities in each layer. Here, the layers represent time-points. Each panel represents one variable-community comprising of individuals and variables. These communities are characterized by the variables in them, listed above each panel. The panels show the average $z$ value of all people in that variable-community, and error bars are given by their standard deviation.} \label{multi} \end{figure*} Upon creating an individual-variable network for each layer (where each layer is a timepoint) as in figure \ref{bip} (left), Louvain community detection is performed on each layer. Figure ~\ref{multi} shows the communities $C_l$ identified in each layer $l$ comprising of individuals as well as dominant variable. These variable-communities are characterized by the dominant disease variables that belong to them (listed above each variable-community in figure~\ref{multi}). The variable-communities are indicative of sets of variables that patients co-express with high severity in different stages of the disease. For instance, the last panel (bottom row) in the baseline year indicates that in early stages of disease, patients displaying severity in variable GDS for instance, are also likely to display severity in STAI. While variables are treated independently in this analysis, the emergent variable-community structure is largely consistent with domain structure in medical literature \cite{MAR18}. The composition of variable-communities remains similar across the layers. Age and JOLO (a cognitive variable) cluster together in all layers. Another variable-community comprises of all the other cognitive variables. Disability (SEADL) and General PD Severity Variables (PD-1,2,3,T) commonly co-express with high severity together in all layers except in the baseline year where PD-1 is found to co-express with Autonomic (SCOPA-AUT) and Sleep (RBDQ) variables. As General PD Severity variables represent motor functioning, their co-occurence with disability is expected. Sleep and Autonomic variables often clustered together in several layers. Mental Health variables (GDS, STAI) initially form an independent variable-community, however, as time progresses, they co-express with high severity with PD Severity and Disability domains. Deterioration of mental health is expected with worsening motor skills and increased disability, particularly in later stages of disease progression. The clustering of variables in the same domain is further validation of our method yielding medically relevant results. The individuals within each variable-community have relatively high average severity of corresponding variables that characterize the community. \subsubsection{Statistical analysis} The Kruskal-Wallis statistical test \cite{KRU52} is an estimate of whether two variables are sampled from the same distribution. Kruskal-Wallis test for multiple groups was conducted to validate this approach and demonstrate some of the differences between variable-communities. This test is chosen because it is applicable in cases such as this where values for several of the variables violate the normality assumption. \begin{table*}[htbp!] \caption{\label{stat1} Comparing the variable-communities (described in figure~\ref{multi}) in each layers (representative of timepoints) through the Kruskal-Wallis p-values. } \begin{indented} \item[] \lineup \begin{tabular}{ ccccccc } \br Variable & Median & Year0 & Year1 & Year2 & Year3 & Year4 \\ \mr Age & 71.00&1.759E-08 & 2.439E-07 & \textbf{2.263E-09} & 2.966E-06 & 5.115E-08 \\ \textbf{Cognitive} &&&&&&\\ JOLO* & 14.00& 3.687E-06 & 6.807E-06 & 8.491E-05 & 2.769E-03 & 1.526E-09 \\ SDM* & 42.00&3.951E-07 & 3.764E-09 & 7.653E-07 & 5.050E-08 & 7.435E-12 \\ SFT* & 47.50&5.151E-07 & 1.920E-06 & 1.381E-04 & 3.276E-09 & 2.753E-07 \\ HVLT* & 0.90& \textbf{3.222E-03} & 6.110E-07 & \textbf{5.731E-03} & \textbf{2.959E-01} & 7.282E-05 \\ LNS* & 11.00&1.207E-05 & 1.457E-08 & 1.347E-07 & 1.234E-11 & 5.982E-11 \\ MOCA* & 27.00& 1.767E-05 & 3.470E-05 & 1.163E-06 & 2.379E-04 & 2.928E-08 \\ \textbf{Other} &&&&&&\\ SEADL* &95.00& 4.317E-10 & 5.634E-10 & 1.039E-07 & 6.277E-07 & 3.821E-08 \\ RBDQ & 4.00&2.931E-08 & 1.247E-06 & 1.212E-09 & 2.699E-10 & 1.172E-11 \\ ESS & 6.00& \textbf{1.265E-01} & 6.166E-08 & 6.262E-08 & 4.623E-10 & 1.191E-08 \\ SCOPA-AUT & 9.00& 6.022E-09 & 4.087E-07 & 5.470E-10 & 8.695E-09 & 2.638E-10 \\ GDS & 2.00&6.678E-06 & 1.323E-08 & 7.281E-05 & 2.941E-08 & 9.002E-09 \\ STAI & 65.00&1.805E-07 & 4.617E-09 & 1.374E-03 & 6.388E-07 & 2.223E-08 \\ \textbf{General PD} &&&&&&\\ PD-1 & 5.50&3.609E-10 & 8.432E-09 & 1.789E-09 & 3.372E-12 & 4.205E-12 \\ PD-2 &5.00& 1.471E-08 & 1.969E-09 & 1.231E-08 & 1.599E-12 & 2.570E-15 \\ PD-3 & 20.00&2.587E-08 & 1.088E-08 & 1.026E-10 & 2.275E-09 & 4.794E-12 \\ PD-T &32.00& 1.674E-14 & 5.236E-14 & 1.280E-14 & 9.158E-16 & 5.981E-17\\ \br \end{tabular} \end{indented} \end{table*} Table~\ref{stat1} tabulates the medians and the p-values of the Kruskal-Wallis statistical test applied to each layer. Medians are calculated from the whole population raw data. Variables with negative directions are denoted by an asterisk (*). The p-values are a measure of statistical differences amongst the variable values of the individuals belonging to the different variable-communities. To account for Type I errors due to multiple comparisons the Benjamini-Hochberg False Discovery Rate method \cite{BEN95} is used. This gives us an adjusted significance level for each of the p-values $\alpha_{adjusted} = \frac{\alpha \times i}{n_c}$, where $n_c$ is the total number of comparisons, and $i$ is the rank of the p-value (for example, the smallest has a rank of 1, the second smallest has a rank of 2 etc.). Significance value $\alpha = 0.05$. Total number of comparisons $n_c = T \times V = 5 \times 17 = 85$, where $T$ is the number of timepoints, and $V$ is the number of variables. For instance, in Table~\ref{stat1}, HVLT in year 3 has the largest p-value (rank one), hence it has the strictest acceptance threshold given by $\alpha_{adjusted} = \frac{0.05 \times 1}{85} = 5.882 \times 10^{-3}$. Comparisons not meeting the criteria for statistical significance are shown in bold text. A majority of the p-values are below their adjusted significance level, suggesting that there is an underlying statistical difference between the variable distributions in the variable-communitites in a layer. \subsection{Trajectory Clustering on Temporally Stacked Multi-layer Network} \label{timex-cluster} \subsubsection{Trajectory communities} Each individual is a member of one of the variable-communities at each time-point (or in each layer in this case). Tracing their membership yields their trajectory. The TC algorithm (sec. \ref{bip}) identifies patient subtypes based on similarities in their trajectories through the multi-layer network. The run time of the trajectory clustering algorithm on the temporally stacked multi-layer network is $4.9346s$. All code was run on a laptop with 2.8 GHz Intel Core i5 processor and 8 GB RAM. \begin{figure*}[htbp!] \begin{center} \includegraphics[width=0.95\linewidth]{Images/all_figs/all_figs5} \end{center} \caption{Each node represents a variable-community consisting of variables and patients. The size of the node denotes the number of people in the variable-community. The variables are color-coded by domain. Patient trajectories from the baseline layer to the year4 layer are clustered using the TC algorithm. The trajectory-communities (subtypes) are color-coded and directed (from left to right). The thickness of a colored edge denotes the number of patients flowing along that edge in the corresponding trajectory-community. Number of people in each subtype are as follows: green - 56, orange - 55, red - 53, blue - 33. Edges with fewer than 3 people are not plotted.} \label{TS_bip} \end{figure*} As shown in figure~\ref{TS_bip}, the TC algorithm identifies four distinct trajectory-communities (subtypes) for disease progression across temporal layers. The edges are directed from left to right (baseline year to year4), shown without arrows for ease of viewing. The thickness of the edges is a measure of the flow of people between the corresponding variable-community nodes. Thus, edge thickness is an estimate of the probability of transition of patients expressing high severity from one variable set to another as time progresses. The green subtype $S_0$ with 56 patients is characterized by an older population and higher severity of JOLO, as well as increase in general Cognitive impairment as time progresses. The orange subtype $S_1$ with 55 patients displays high values of Cognitive variables. In addition, it progresses to high severity in General PD Severity and Sleep variables. The red subtype $S_2$ with 53 patients is characterized by high Disability and severe General PD (motor), and develops severity in Mental Health variables through progression of time. Lastly, the blue subtype $S_3$, the smallest trajectory-community with 33 patients, is characterized by severe Autonomic and Sleep variables. It shows limited Cognitive and General PD severity in earlier years, and the severity of expression of these variables reduces over time. \subsubsection{Trajectory-community profiles} \begin{figure*}[ht!] \begin{center} \includegraphics[width=0.95\linewidth]{Images/all_figs/all_figs6} \end{center} \caption{Trajectory profiles of the 4 trajectory-communities. The $i^{th}$ vertical set of panels corresponds to a trajectory-community denoted by $S_i$). Within each column, the five panels arranged from top to bottom show the average profile in years 0(baseline),1,2,3,4 respectively. Each individual panel shows the average $z$ values across all variables of $\kappa_i^l$ patients in a trajectory-community.} \label{v_prof} \end{figure*} Figure ~\ref{v_prof} shows the trajectory profile (weighted average profile of all individuals belonging to a trajectory-community) across all layers (which is equivalent to timepoints in this case). The trajectory profiles ($S_i^t$) of trajectory-community $i$ at timepoint $t$ is obtained by taking the weighted average of the variable-communities that members of the trajectory-community belong to as follows: \begin{equation} S_i^t=\frac{\Sigma_{i} X(t)_{T_i}}{\kappa_i^t}. \label{tc_pr} \end{equation} where $i \in \kappa_i^t$ and $\kappa_i^t$ is the total number of individuals in trajectory-community $S_i$ and layer $t$. $X(t)_{T_i}$ is the variable-community that individual $i$ belongs to at time $t$. As seen in figure~\ref{v_prof}, each trajectory-community has a distinct trajectory profile with different evolution patterns and high values of their corresponding dominant variables. The green trajectory-community $S_0$ with 56 members has a relatively mild disease stage, despite having a relatively older population. Disability, Autonomic, and General PD severity start very low, and continue to stay low over time. Amongst the cognitive variables, JOLO is slightly higher than in other trajectory-communities through the layers, ESS starts high and reduces over time, whereas HVLT gets more severe. The orange trajectory-community $S_1$ with 55 members show consistently high severity in all Cognitive variables except JOLO and MoCA. Other variables are low; Disability reduces across the layers, whereas Sleep variables show a slight increase as disease progresses across time. The red trajectory-community $S_2$ with 53 members has relatively severe General PD Severity motor variables. As time progresses, Autonomic, Mental Health and Disability demonstrate growth in severity. Lastly, the blue trajectory-community $S_3$, the smallest with 33 members show heterogeneity in the variable structure. General PD Severity variables remain consistently low through time, whereas Sleep variables RBDQ and ESS show growth in severity across the layers. \subsubsection{Statistical analysis} To validate the algorithm and demonstrate the differences in the \textit{progression} of the different trajectory-communities, the Kruskal-Wallis statistical test for multiple groups was conducted on the \textit{difference} between the consecutive year variable values. This test is chosen because it is applicable in cases such as this where values for several of the variables violate the normality assumption. We do not include the variable `age' in the statistical analysis since the difference in age between consecutive years is exactly 1 regardless of the subtype. \begin{table} \caption{ \label{stat2} Comparing evolution of trajectory-communities by calculating the Kruskal-Wallis p-values for variable differences between consecutive years.} \begin{indented} \item[] \lineup \begin{tabular}{ cccc } \br Variable & Year1-Year0 & Year2-Year1 & Year3-Year2 \\ \mr \textbf{Cognitive} &&&\\ JOLO* & 1.451E-06 & 7.295E-04 & 3.335E-11 \\ SDM* & 2.579E-05 & \textbf{2.556E-02} & 6.247E-05 \\ SFT* & 2.089E-05 & 9.683E-07 & 1.005E-05 \\ HVLT* & 4.225E-04 & 1.892E-05 & 1.548E-18 \\ LNS* & 3.724E-06 & \textbf{8.711E-02} & 3.486E-04 \\ MOCA* & 2.562E-04 & 5.158E-07 & 3.142E-13 \\ \textbf{Other} &&&\\ SEADL* & \textbf{1.092E-02} & 1.809E-07 & 5.618E-08 \\ RBDQ & 9.470E-04 & 3.796E-09 & \textbf{2.015E-02} \\ ESS & 6.881E-15 & 1.059E-07 & 1.708E-04 \\ SCOPA-AUT & 3.035E-03 & 1.202E-05 & 3.529E-11 \\ GDS& 4.778E-08 & 6.070E-03 & 4.111E-05 \\ STAI & 3.209E-07 & \textbf{4.996E-02} & 2.330E-05 \\ \textbf{General PD} &&&\\ MDS-UPDRS-1& 3.648E-03 & 2.545E-05 & \textbf{2.418E-02} \\ MDS-UPDRS-2 & 6.627E-03 & 3.092E-04 & 2.503E-03 \\ MDS-UPDRS-3 & 2.502E-03 & 1.405E-07 & 2.590E-06 \\ T-MDS-UPDRS& \textbf{9.561E-03} & 2.809E-04 & 3.607E-03 \\ \br \end{tabular} \end{indented} \end{table} Table~\ref{stat2} tabulates the medians and the p-values of the Kruskall-Wallis statistical test to study statistical differences in the growth of variables across layers between individuals belonging to the different variable-communities. Variables with negative directions are denoted by an asterisk (*). To account for Type I errors due to multiple comparisons the Benjamini-Hochberg False Discovery Rate method \cite{BEN95} is used. This gives us an adjusted significance level for each of the p-values $\alpha_{adjusted} = \frac{\alpha \times i}{n_c}$, where $n_c$ is the total number of comparisons, and $i$ is the rank of the p-value. Significance value $\alpha$ is chosen to be $0.05$. Total number of comparisons $n_c = N_t \times N_v = 3 \times 16 = 46$, where $N_t$ is the number of year-differences, and $N_v$ is the number of variables. Comparisons that do not meet the significance criteria are highlighted in bold in the table. A majority of the values are below their adjusted significance level, suggesting that there exist significant differences in variable progression of the different trajectory-communities. \subsection{Trajectory Clustering Across an Independent Outcome Variable} \label{pdx} Often, medical practitioners may be interested in studying the evolution of disease variables as a function of an outcome variable (a clinical test or variable known to be indicative of specific aspects of disease progression that are of interest). This may, in particular, be useful when complete temporal data about a patient is unavailable, however comprehensive data of evolution of a specific variable is available instead. Defining layers through values of an outcome variable, allows us to identify subtypes based on trajectories through progression of an outcome variable. \begin{figure*}[htbp!] \begin{center} \includegraphics[width=0.95\linewidth]{Images/all_figs/all_figs7} \end{center} \caption{Trajectory clustering across the outcome variable - baseline MDS-UPDRS3 / PD3 values. The layers represent quartiles of the outcome variable raw values. The boundary values that determine the layers are denoted in red. Each node represents a variable-community consisting of variables and patients. The size of the node denotes the number of patient-years associated with the community. Each patient can contribute upto 5 times (one for each year) to a variable-community. The variables are color-coded by domain in the legend. Patient trajectories directed from the baseline year to the year4 are clustered using the TC algorithm. These trajectories progress in time and hence, are not required to pass through all the outcome variable layers. The trajectory-communities (subtypes) are color-coded. The thickness of a colored edge denotes the number of patients along that edge in the corresponding trajectory-community. Number of people in each trajectory-community are as follows: green - 47, orange - 44, red - 58, blue - 48. } \label{PD_1} \end{figure*} \begin{figure*}[htbp!] \begin{center} \includegraphics[width=0.95\linewidth]{Images/all_figs/all_figs8} \end{center} \caption{(a) Variable-community profiles in each layer. Here, the layers represent values of the outcome variable MDS-UPDRS-3. Each panel represents a variable-community comprising of patient-years and variables. The variables in each variable-community are listed above each panel, and are used to identify the variable-communities. The panels show the average $z$ value of all patient-years in that variable-community. (b)Trajectory profiles of the 4 trajectory-communities. The $i^{th}$ vertical set of panels corresponds to a trajectory community $S_i$. Within each column, the four panels arranged from top to bottom show the average profile in layers low, low-mid, mid-high, and high. Each individual panel shows the average $z$ values across all variables of $\kappa$ patient-years in a trajectory-community in a layer. All error bars are given by the standard deviation. } \label{PD_2} \end{figure*} MDS-UPDRS-3 (divided into quartiles on the x axis) is known to be indicative of PD progression and was chosen as the outcome variable. In figure~\ref{PD_1}, four disease progression trajectory-subtypes across outcome variable layers are identified. The layers are defined by raw baseline MDS-UPDRS-3 values as follows: layer low contains values below $22.0$, layer low-mid contains values between $22.0$ and $31.0$, layer mid-high contains values between $31.0$ and $38.0$, and layer high contains values above $38.0$. Dependent variables are chosen to be the same as in section \ref{timex}, with the exception of General PD severity variables. This method is generalizable to selection of any outcome variable. Figure~\ref{PD_1} shows the subtypes identified by the trajectory clustering algorithm. The run time of the TC algorithm on the multi-layer network stacked across outcome variables is $1.7213s$. The size of the nodes in figure~\ref{PD_1} indicate the number of patient-years in that variable-community, i.e., one patient may contribute up to $5$ times to a certain community, one for each timepoint. This implies that a patient may, in consecutive years, remain in the same variable-community, or transition to a different variable-community in the same layer, or transition to a different variable-community in a different layer. Figure~\ref{PD_2}(a) shows the variable-community profile, i.e., average $z$ values of all the patients in each community in each layer with errors given by their standard deviation. The position of variable-community profiles corresponds to the node in figure~\ref{PD_1}. In figure~\ref{PD_2}(a), one can see that the variables denoting a variable-community have a correspondingly higher relative $z$ value. In figure~\ref{PD_2}(b) shows the average trajectory profile as calculated in \ref{tc_pr} amongst for each trajectory-community across each layer. As seen in figure~\ref{PD_1} and figure~\ref{PD_2}(b),The green trajectory-community $S_0$ with $47$ patients largely remains in low to low-medium PD-3 layers, with $101$ patient-years in layer low, and $72$ patient-years in layer low-medium. Individuals in this trajectory-community start with low disease state (as measured by PD-3), and show slow disease progression over the years, staying in the low-medium range of disease progression. The orange trajectory-community $S_1$ with $44$ patient-years is the least affected. Patients are most severely affected in the Cognitive domain, however they remain largely in the low disease layer. The red trajectory-community $S_2$ with $58$ starts in a relatively high disease state, and consistently gets worse, whereas the blue trajectory-community $S_3$ with $48$ starts relatively healthy but with severe disease progression into mid-high and high layers of disease severity measured through PD-3. \section{Conclusion} This work introduces a novel algorithm for the identification of subtypes based on relationships between trajectories through a multi-layer network. Multidimensional clinical datasets are often not used to their full potential due to the complexities of a cohesive analysis. This work extracts disease variables that co-express with high severity at different stages of disease progression. Then it extracts trajectories of progression through these variable-communities, i.e., through sets of high severity variables. Lastly, it identifies disease subtypes through clustering patient trajectories. Additionally, it promotes second-order comparisons in the calculation of $\eta$ i.e., correlations across time between two trajectories that do not have overlapping edges but interact with common neighboring trajectories. The agreement of variable-clusters with the domain-structure e.g. Cognitive, Autonomic etc., as well as the statistical analysis, both validate the success of this approach. Parkinson's Disease has a multitude of clinical variables that interact in complex manners that vary through stages of the disease. A number of studies have identified Parkinson's subtypes based on baseline characteristics \cite{5,20,22}. In contrast, our novel algorithm uses longitudinal data (or patient trajectory over time) to identify disease subtypes through TC. In other words, our method accounts for both disease variable values as well as their progression patterns as a patient progresses through the different layers of the multi-layer stacked-bipartite network. While Parkinson's Disease, being both multivariate and progressive, served to demonstrate the effectiveness of the TC algorithm, the algorithm can, in principle, be easily extended to include non-clinical features, such as genetic or fluid biomarkers, as well as to other datasets. The TC algorithm identifies subtypes through clustering patient trajectories across layers. This work presents two methods of analysis and visualization of disease progression: Parkinson's disease trajectory through time, and Parkinson's disease trajectory through an outcome variable (representative of disease progression). Our second-order TC algorithm emphasizes the dynamical aspect of disease progression in addition to the static properties of the associated variables at every stage, contrary to several earlier data-driven methods in medicine that emphasize one or the other. Results are presented in an interpretable visualization that is easily accessible to and comprehensible by medical practitioners in contrast with black box methods in machine learning. The TC algorithm is a data-driven network-based method for detection of patient subtype. Like other data-driven methods, this analysis is limited by the availability and quality of the database. The number of variables provided in the database is not exhaustive in the context of Parkinson’s disease. As larger datasets are made available, such results are likely to be more informative and robust. Additionally, in applying a data-driven approach to medical data, important medical decisions must always be made in conjunction with medical expertise. An advantage as well as caveat of this approach is that trajectories are tracked through variable sets, and not through individual variables. Future directions of such work would naturally include extension to other types of medical data (genetic \cite{17}, biomarker etc.), as well as extension to other types of time-evolving and heterogenous datasets. Additional directions of potential interest include studying disease evolution through other outcome variables, as well as treatment-based modifications to the algorithm where effects of treatment are expected during gathering of data. By the nature of such a data-driven method, this approach may not be appropriate for datasets with high variability, low quantity, or data with inconsistent temporal sampling. Parkinson's disease is a highly variable disease with a long onset time. Knowledge of which cluster a new patient belongs to in the baseline year, would allow medical practitioners to predict their subtype and corresponding trajectory, including the type and rate of disease progression. This could open up new and exciting avenues in the field of personalized medicine. Moreover, prediction of disease progression will improve prognostic counseling, a problem commonly encountered by clinicians, by highlighting predicted disease features. It will also support them in seeking more aggressive treatment for patients predicted to display rapid disease progression. Thus, this multi-layer network-based TC approach harnesses data to provide interpretable solutions in the field of early, predictive medicine. \section*{Data and Code Availability} Data was obtained from PPMI, a public-private partnership funded by the Michael J. Fox Foundation for Parkinson’s Research and funding partners, including abbvie, Allergan, Avid Radiopharmaceuticals, Biogen, Biolegend, Bristol-Myers Squibb, Celgene, Denali, GE Healthcare, Genentech, gsk, Lilly, Pfizer, Merck, MSD, Lundbeck, Piramal, Prevail Therapeutics, Roche, Sanofi Genzyme, Servier, Takeda, Teva, Ucb, Verily, Voyager Therapeutics and Golub Capital. There are no patents, products in development or marketed products to declare. Python code is available at \textit{www.github.com/chimeraki/Multilayer-Trajectory-Clustering} \ack{ The author wishes to sincerely thank Prof. Michelle Girvan, Dr. Lisa M. Shulman, MD and Dr. Rainer von Coelln, MD for helpful discussions and suggestions.} \section*{References} \bibliographystyle{unsrt}
{'timestamp': '2020-08-04T02:38:04', 'yymm': '2005', 'arxiv_id': '2005.14472', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14472'}
arxiv
\section{Introduction} Technology-based intimate partner surveillance (IPS) causes immense harms. A discrete form of intimate partner violence (IPV), IPS is the deliberate surveillance of an intimate partner with or without their knowledge, levied through technical and non-technical methods. Survivors have reported their abusers use spyware apps, account compromise, GPS trackers, shared cellular plans, and more to monitor their digital lives and physical locations~\cite{freed2017digital,freed2018stalker,matthews2017stories,woodlock2017abuse,southworth2007intimate}. Prior work has also indicated that a wealth of IPS apps are available online~\cite{chatterjee2018spyware} and in active use against victims~\cite{roundy2020many,havron2019clinical,freed2019clinical}. To better protect targets of abuse, we need to both improve technologies' robustness to abuse and better inform \mbox{interventional} approaches that directly aid victims~\cite{havron2019clinical,freed2019clinical}. To achieve these aspirations, however, we need to better understand how those interested in perpetrating IPS learn to conduct these attacks. To date, there have been few investigations into how attackers locate the resources that help them enact abuse. Chatterjee et al.~\cite{chatterjee2018spyware} highlight that blogs, videos, and question-and-answer sites exist online that help facilitate IPS, but stop short of investigating the communities who make use of them. There is a methodological hurdle in discovering this information: we need a way to hear from potential attackers directly. In this work, we provide the first study exploring how potential attackers use the Internet to learn how to enact IPS against their victims. We identify a set of five public, online forums where people discuss infidelity in intimate relationships and tools for monitoring cellphones. We build a crawler to retrieve the conversations on these forums and use it to compile a dataset containing over 200\,K posts spread across almost 20\,K threads. This dataset contains an unprecedented amount of information about the strategies of IPS attackers, contextualized in user-generated natural language. While prior work has described the attacks experienced by victims, we present a detailed view of how these attacks are created and developed---the capabilities attackers seek, the vulnerabilities they exploit, and the community dynamics that enable them. We analyze this data using mixed-methods. We begin with quantitative measurements of the forums, their users, and their posting behaviors. These analyses reveal that most forums contain ``superusers'' involved with a disproportionately large fraction of threads. For two of the five forums, we discover that their content consists almost entirely of spam advertising particular spyware tools, in a manner that may be consistent with search engine optimization (SEO) techniques deployed by the creators of those tools. We also determine that many of their most highly viewed threads are about technology-based IPS, suggesting these forums have generated a significant audience for IPS-related content. We then perform qualitative coding of a large sample of 750 threads (250 from each of the three forums that are not \mbox{inundated} by spyware ads). Via thematic analysis \cite{braun2006using}, we \mbox{surface} novel insights about the online behaviors of IPS attackers. We show that potential attackers seek online support for suspicions of infidelity, and that community members respond by outlining exactly how to track, monitor, and otherwise compromise the privacy of an intimate partner. We show that discussion of IPS is prevalent in these forums, with one forum having 78\% of sampled threads related to IPS. We develop a taxonomy of IPS attacks surfaced from the suggestions made in these forums (Table~\ref{tab:taxonomy}). \textit{Tool-based attacks} directly weaponize technology such as audiovisual recorders, keyloggers, backup recovery tools, and more, and can be understood in two subcategories: those requiring physical access to a partner, and those that do not. \textit{Coercion and subterfuge} attacks manipulate a partner into unlocking their devices or accounts. Finally, we see many suggestions to \textit{outsource attacks} by hiring private investigators. Although some of these strategies have been reported by victims \cite{freed2018stalker, matthews2017stories}, our analysis provides the complementary view of potential perpetrators. We highlight tools, tactics, and services that have not been reported previously, and which we believe were previously unknown to those helping victims. We also report on the conversational patterns within these forums that enable would-be attackers (what we describe as \textit{escalation}), and, conversely, patterns in which they are discouraged away from IPS (\textit{de-escalation}). These findings suggest that public forums can serve as a source of threat intelligence informing interventions to dissuade abuse. In fact, our work is already having impact for IPS interventions. We shared our results with the team running a clinic providing direct assistance to IPV survivors facing IPS \cite{havron2019clinical, freed2019clinical},\footnote{https://www.ipvtechresearch.org} who are working towards using our findings in their procedures. More broadly, our analyses yield insights for technologists, platforms, and advocates on how we might defend against and mitigate the spread of IPS. We close by discussing implications for platforms, future work in automated threat intelligence, and how policymakers might address the for-profit operations that financially benefit from abuse. \section{Background and Related Work} \paragraph{IPV and technology abuse.} Prior work has examined the behaviors, justifications, and tactics of intimate partner abusers \cite{hearn_violences_1998, kelly_naming_2016, stark_coercive_2009}, including work identifying suspicions of infidelity as a leading trigger for IPV in heterosexual couples \cite{arnocky2015anticipated, nemeth2012sexual}. Of this literature, a growing body of work explores the role of technology in IPV, including how abusers exploit technology to monitor, harass, control or otherwise harm their targets~\cite{freed2017digital,freed2018stalker,chatterjee2018spyware,matthews2017stories,dimond2011domestic,woodlock2017abuse,southworth2007intimate}. Chatterjee et al.~\cite{chatterjee2018spyware} observed that abusers are likely exploiting easy-to-find online resources, including tutorials, question-and-answer sites, and videos explaining how to use spyware for IPS. Roundy et al.~\cite{roundy2020many} used datasets from a major antivirus vendor to explore a broader class of creepware that includes spyware, but also SMS bombers, hacking tutorials, and more. These works have provided valuable intelligence for corresponding anti-IPS interventions with victims and survivors \cite{freed2019clinical, havron2019clinical}. To date, however, less research has examined the role of online communities in IPV. Some have examined how targets experience IPV in digital media and seek support through online forums \cite{dragiewicz2018technology, leitao2019technology}, but to the best of our knowledge, ours is the first study to measure and analyze how forums lead attackers to such tools. Our work confirms that attackers are discussing and recommending IPS strategies on public forums available to any Internet user. We also identify new tactics, such as custom scripts to monitor websites visited and launch man-in-the-middle attacks. \paragraph{Online measurement studies.} Prior work has used measurement and analysis of online forums to shed light on communities discussing criminal or otherwise malicious behaviors. For some of these communities, this research has led to the development of threat intelligence. Commercially motivated criminals, such as spammers and black-hat hackers, use online forums as marketplaces and for learning adversarial techniques from each other~\cite{thomas2006underground,motoyama2011analysis,franklin2007inquiry}. Research on this phenomenon has identified structure, trust, and superusers in these communities~\cite{afroz2013honor, afroz2014doppelganger, garg2015fc}. Relatedly, online forums used by pedophiles and others involved in the creation and distribution of child sexual abuse materials have been studied to gain insights into the way participants justify or normalize abuse, and share technical and non-technical strategies that facilitate abuse~\cite{durkin1999propagandizing}. Similar methods have also been used to analyze forums associated with hate groups~\cite{chatzakou2017hate,ribeiro2018characterizing}, cyberbullying~\cite{kowalski2012cyberbullying,chatzakou2017measuring}, doxxing~\cite{snyder2017fifteen}, mis- and disinformation campaigns~\cite{starbird2019disinformation}, harassment~\cite{mariconti2018you, hua20twitter, hua20towardstwitter}, and sex trafficking~\cite{portnoff2017backpage}. These measurement studies include ones that directly document abuse (e.g., hate and harassment on social media), as well as those investigating perpetrators' discussions of tactics (e.g., perpetrators sharing ways to maximize the emotional impact of harassing messages). Our work falls in the latter category. While methodologically similar, we differ in our focus on people who use online forums to discuss strategies for IPS. Similar to the work on cybercrime and child abuse forums, analysis of online resources such as craigslist and backpage has led to threat intelligence that helped combat human trafficking~\cite{portnoff2017backpage}. We aim to have a similar impact on IPS and IPV more broadly. In summary, our research questions are: \begin{newitemize} \item What role do online forums play in surfacing IPS resources to potential attackers? \item What role do commercially motivated entities play in these online communities? \item What tools and tactics are being suggested to potential attackers, and at what levels of technical sophistication? \end{newitemize} \section{Forums and Datasets} \label{sec:methods} To answer these research questions, we perform a mixed-methods analysis of a large sample of posts and threads from public online forums with a high density of IPS-relevant conversation. In this section, we review our analysis targets and data collection approach, as well as the resulting datasets. \paragraph{Infidelity and IPS forums.} We identified several forums whose content includes a large number of posts touching on IPS. These were discovered through a combination of pointers from prior work~\cite{chatterjee2018spyware} and online web searches using a combination of terms such as ``spyware track wife''. While we endeavored to be exhaustive, we restricted attention only to publicly available forums, excluding forums accessible only to registered users or users who had crossed some threshold number of active posts. We may also have missed forums that are not easily found via search engines. Finally, many forums have a small number of posts touching on IPS, but with the overwhelming majority of content being irrelevant to our study. We excluded those from our analysis and selected forums that seemed to have a higher concentration of IPS-related posts. Future work might explore techniques to discover IPS-related forums that are harder to access and find. Our analyses focus primarily on three forums that aim to help people navigate infidelity. To prevent the publication of this work from advertising spyware, or from unintentionally impacting these public forums by convincing them to go private, we anonymize them.\footnote{Our data, including forum names, is available for research upon request.} The forums we study include: \begin{newitemize} \item \textbf{Forum~A\xspace}, a community dedicated to discussing ``\textit{investigative equipment}.'' Forum~A\xspace is a subforum of a website providing resources on resolving marital conflicts with Alexa rank approximately 500,000. \item \textbf{Forum~B\xspace}, a community dedicated to advice on ``\textit{detecting infidelity and deception.}'' Forum~B\xspace is a subforum of a website providing resources on cheating in romantic relationships, with Alexa rank approximately 900,000. \item \textbf{Forum~C\xspace}, a moderated Reddit subforum that bills itself as ``\textit{a safe place to ask for advice and guidance}'' for those facing infidelity in a relationship. As of February 2020, Forum~C\xspace\ had approximately 80,000 subscribers, and Reddit was the 18th most popular website in the world.\footnote{\url{https://www.alexa.com/siteinfo/reddit.com}. Alexa rankings are based on global traffic and engagement over the last 90 days.} \end{newitemize} We additionally investigated two subforums that focus on spyware tools: \textbf{Forums D\xspace} and \textbf{E\xspace}, both subforums of a community for cellphone advice. Forum~D\xspace\ focuses on spyware for mobile phones, while Forum~E\xspace\ focuses on spyware generally. These subforums surfaced in Internet searches for the same sets of IPS-related keywords as those used to discover the three infidelity forums above. As we discuss further in Section~\ref{sec:data-desc}, our analysis concludes most content on these forums are spam advertisements for particular spyware tools. For simplicity, we will use the term ``\textit{forum}'' to refer to the communities we studied in-depth (e.g., Forum~C\xspace), and ``\textit{parent forum}'' to refer to their parents where needed (e.g., Reddit). \paragraph{Data collection.} We collected data from Forums A\xspace, B\xspace, D\xspace and E\xspace via custom crawlers built using Scrapy, an open-source, Python-based framework for web scraping.\footnote{\url{https://docs.scrapy.org/en/latest/}} Our crawlers preserved the threaded structure of each forum's content, as well as metadata like views and post and update timestamps where available. We did not download any media beyond text---specifically avoiding images---and stored all data in a local database on a secured server. Our analysis covers a set of scrapes collected using this pipeline in October of 2019. For Forum~C\xspace, we used the scrape available via the Reddit corpus within ConvoKit \cite{chang2019convokit}, which was collected in October 2018. Table ~\ref{tab:dataset} summarizes the complete dataset. \paragraph{Limitations.} Our study combines quantitative and qualitative methodologies to characterize a sampling of publicly available forums where discussion of IPS tactics manifests. We emphasize our work may not generalize to discussion on private forums, such as those that require the creation of an account and a threshold of posts or months active for access, or those occurring within private social groups on larger social media platforms such as Facebook and Twitter. We also focus on English-language forums, and thus our findings cannot be taken to represent the scope of IPS discussion worldwide. We believe there is compelling future research in investigating larger public-facing communities, like other subreddits or closed communities on and off of influential social networks. \paragraph{Ethics.} Throughout this work, we were sensitive to the ethics of using online discussions of highly personal topics for research. Our data is from publicly available fora accessible on the Internet without authentication. Our IRB office reviewed the study and deemed it to not be human-subjects research, since all data was already in the public domain. Still, we took precautions to ensure our research remained safe and privacy-preserving. The only identifiers we used were the public usernames associated with each post. We did not pursue identification of people from their posts or usernames, or collect or store images. In reporting our work, we have scrubbed information that might trace back to the people behind the pseudonyms, e.g., locations or specific narrative details. \section{Forum Activity and Users} \label{sec:data-desc} \begin{table*}[ht] \centering \footnotesize \begin{tabular}{@{}lrrrrr@{}} \hline & \multicolumn{1}{c}{\textbf{Forum~A\xspace}} & \multicolumn{1}{c}{\textbf{Forum~B\xspace}} & \multicolumn{1}{c}{\textbf{Forum~C\xspace}} & \multicolumn{1}{c}{\textbf{Forum~D\xspace}} & \multicolumn{1}{c}{\textbf{Forum~E\xspace}} \\ \hline Date of first thread & Jan 2006 & Aug 2005 & May 2013 & Oct 2008 & Feb 2013 \\ Size of forum (threads) & 268 & 1,175 & 11,291 & 3,388 & 2,788 \\ Size of forum (posts) & 1,608 & 8,932 & 183,381 & 7,540 & 4,952 \\ Unique active users in forum & 462 & 2,102 & 12,740 & 264 & 543 \\ \hline Avg. thread views (stdev) & 3,438 (13,249) & 4,822 (12,194) & -- & 1,685 (7,634) & 6,315 (44,813) \\ Avg. thread length in posts (stdev) & 7 (17) & 4 (8) & 16 (17) & 2 (1) & 2 (2) \\ Avg. time to new thread (stdev) & 140 days (198 days) & 7 days (13 days) & 3 days (13 days) & 1 day (11 days) & 21 hrs (11 days) \\ Avg. time to new post (stdev) & 3 days (13 days) & 14 hrs (2 days) & 15 minutes (2 hrs) & 12 hrs (5 days) & 12 hrs (2 days) \\ \hline IPS-relevant \% of threads$^\alpha$ & 78 & 51 & 18 & -- & --\\ Size of IPS-relevant sample (posts)$^\alpha$ & 1,411 & 2,011 & 1,032 & -- & -- \\ Unique users active in IPS-relevant threads$^\alpha$ & 296 & 465 & 346 & -- & -- \\ \% of IPS-relevant threads that escalate$^\alpha$ & 32 & 38 & 35 & -- & --\\ \hline \end{tabular} \caption{Comparison of the five forums in our dataset. Forum~C\xspace does not provide viewership information (marked by dashes). $^\alpha$\,Calculated via qualitative analysis of random samples of 250 threads per non-spam forum, see Section~\ref{sec:qual-methods}.} \label{tab:dataset} \end{table*} We begin by measuring the nature of activity on these forums. Later on (Sections~\ref{sec:seeker-experience},~\ref{sec:taxonomy}), we use qualitative methods to more deeply characterize their content. \paragraph{Forum activity and viewership.} The forums in our dataset varied in their rates of activity and reported viewership. In total, the forums contain 18,937 threads, with Forum~C\xspace\ containing the most threads and posts (Table~\ref{tab:dataset}). Activity data in terms of thread and post times was available for all forums. We note that activity on Forums A\xspace and B\xspace peaked between 2010 and 2015, and has significantly dropped off in the last five years, while activity on Forum~C\xspace has exploded in that time (Figure~\ref{fig:forums-over-time}). We hypothesize this may represent a shift away from niche forums focused on infidelity and towards niche subcommunities of larger social media platforms like Reddit. Despite the recent drop-offs, these forums remain publicly available resources for would-be abusers, and contain IPS tools and tactics that are still relevant today; thus we included them in our qualitative analysis (Section \ref{sec:qual-methods}). While these three forums exhibit similar seasonal and diurnal patterns, temporal patterns for Forums E\xspace\ and D\xspace\ exhibit greater variability, as well as strong peaks in year-over-year posting activity in 2013 and 2014, respectively. As we will discuss subsequently, this reflects concentrated activity by advertisers posting spam marketing spyware products. Across all forums, the total number of views was approximately 30\,M. This is likely a significant underestimate of total viewership given that it does not include Reddit's Forum~C\xspace, for which we do not have viewership data. Within each forum, the distribution of views per thread was dominated by one or two highly viewed threads (usually `sticky' threads compiling forum rules or shared resources) and then a long tail of less-viewed threads. The distributions of thread lengths for each forum followed similar long-tail patterns, with an average thread length of six posts. \paragraph{Forum users and ``superusers''.} Table~\ref{tab:dataset} shows the number of users in each forum, identified by comparing the usernames attached to each post via case-insensitive string equality. Forums differed in the number of unique users, from 264 in Forum~D\xspace\ to 12,740 in Forum~C\xspace, but all forums have ``superusers'' that account for a disproportionate number of posts. Figure~\ref{fig:superusers} gives (left chart) a CDF of the fraction of each forum's posts made by users and (right chart) a histogram of the fractions of all threads to which a user posted. For clarity, we only show the 50 and 25 most prolific users, respectively. \begin{figure*}[t] \centering \includegraphics{figures/posts_yearly.pdf} \caption{Histograms (normalized to maximum bin value in forum) for \textbf{(left)} postings per year, with shading indicating the years for which we have post data for the forum, \textbf{(middle)} postings per month of year, and \textbf{(right)} postings per hour of day. } \label{fig:forums-over-time} \end{figure*} \begin{figure*}[t] \centering \hpagess{.70}{.25}{ \input{figures/posts_cdf} }{ \footnotesize \begin{tabular}[c]{clr} \hline \textbf{User} & \textbf{Forums} \\ \hline 1 & A\xspace, B\xspace & \\ 2 & A\xspace, B\xspace &\\ 3 & A\xspace, D\xspace, E\xspace&\\ 4 & B\xspace, D\xspace&\\ 5 & B\xspace, E\xspace&\\ 6 & B\xspace, D\xspace, E\xspace&\\ 7 & B\xspace, C\xspace&\\ 8 & C\xspace, D\xspace&\\ \hline \end{tabular} } \caption{\textbf{(Left)} Cumulative fraction of posts per user for the top 50 users. \textbf{(Middle)} Fraction of threads with posts from the top 25 users. Forum~E\xspace\ (resp.~Forum~D\xspace) are dominated by 1 (resp.~2) superusers, while the other three forums show a more even spread of posts and threads among users. \textbf{(Right)} Multiple-forum users and the forums in which they posted. Excludes the 17 users found posting in Forums D\xspace\ and E\xspace, which share a parent forum.} \label{fig:superusers} \label{tab:mult-forum-users} \end{figure*} Forums E\xspace and D\xspace are clear outliers compared to the other forums; this is due to spammers, as we discuss below. While the other three forums also have superusers, they do not dominate their forums to the same degree. Additionally, cursory examination shows they are not spammers. Some are human and robot moderators, including an automatic moderator on Forum~C\xspace that posts the subreddit's rules as the first response to each thread-starting post. But most superusers appear to be humans particularly engaged in the forum, driving the culture and activity of the community with their posts. We additionally checked whether posters were active in multiple forums in our data. Comparing usernames via case-insensitive string equality, we found just eight users recurring across forums that had no structural reason to be connected. Of these, only one user made contributions that exceeded 1\% of posts or threads in any forum. While this finding seems to indicate superusers are not cross-posting across multiple forums, we note it is simple to register accounts with different usernames in these forums. We consider the identification of users across forums to be an area of future work. \paragraph{Spyware spam and SEO inflation in Forums D\xspace\ and E\xspace.} As mentioned above, Forums D\xspace and E\xspace stood out along many dimensions. Most content in these two forums can be attributed to a handful of users: notably, the top user in Forum~D\xspace\ contributed to 95\% of threads and authored 45\% of posts, and the second-most-active user contributed to 95\% of threads and authored 44\% of posts. Forum~E\xspace exhibits a similar pattern of dominance by a handful of users. Inspection shows many of the threads in Forum~D\xspace constitute conversations between its top two users: one posts a spam advertisement for a spyware tool, and another follows up with a short response. We conclude this demonstrates a strategy of search engine optimization (SEO) employed by the company behind the spyware tool to boost the forum's visibility on Internet searches and attract attention to their spyware product. Specifically, 94\% of the posts made by the top user were the same message: an advertisement for the spyware tool. This user also authored nearly half (45\%) of the posts on this forum. Forum~D\xspace's second-most-prolific user bears a username closely associated with that spyware tool, and posts either ads for the tool or short, meaningless messages (\textit{``Hi,''} \textit{``Hello''}) in response to the first user's ads. We found similar patterns within Forum~E\xspace. Having concluded that most activity on these two forums was spam intended to inflate SEO for specific spyware products, we excluded them from our qualitative analysis of forum content (Sections~\ref{sec:seeker-experience},~\ref{sec:taxonomy}). \paragraph{Prevalence of IPS-related keywords.} To efficiently understand the organic content in the three infidelity forums, we sought automated ways to identify only those threads that were relevant to IPS. As a first-cut assessment, we performed keyword-based searches of the threads in our dataset using a small set of keywords identified from prior work \cite{chatterjee2018spyware}: ``\textit{spy}'', ``\textit{monitor}'', ``\textit{track}'', ``\textit{hack}'' and ``\textit{record}'' (Table~\ref{tab:keyword-relevance}). This first-cut assessment showed keyword searches are, unsurprisingly, insufficient for accurate discovery of relevant threads: for example, the keyword `\textit{record}' may be used in the context of recording someone without their consent, but also in the context of music recordings. To quantify this, we assembled a human-labeled dataset of 750 threads sampled across each of the three non-spam forums and manually coded for relevance to IPS (see Section~\ref{sec:qual-methods} for detailed methods). We then applied a regex-based labeling method that flagged threads as relevant if any post within the thread contained any one of keywords in our seed set. Using our 750 human-labeled threads as ground truth, this simple approach achieves an AUC of 0.62, indicating it misses a large number of relevant threads (false negatives) and contains a large number of irrelevant threads (false positives). As a result, we do not rely on the regex-based approach for any of our subsequent analyses, but instead study the posts human-labeled as ground truth. The development of automated learning techniques that can efficiently flag IPS-relevant threads remains a tantalizing area of future work. \begin{table}[t] \centering \footnotesize \begin{tabular}{lrrrrr} \hline \textbf{Keywords} & \textbf{A\xspace} & \textbf{B\xspace} & \textbf{C\xspace} & \textbf{D\xspace} & \textbf{E\xspace} \\ \hline spy & 26.9 & 7.1 & 1.6 & 98.4 & 42.1 \\ monitor & 8.6 & 2.2 & 3.0 & 97.8 & 27.8 \\ track & 13.4 & 5.4 & 8.8 & 25.7 & 30.0 \\ hack & 3.7 & 1.1 & 2.3 & 1.1 & 4.1 \\ record & 14.9 & 7.8 & 7.3 & 3.8 & 1.4 \\ spy, monitor, track, hack, record & 43.7 & 17.3 & 17.6 & 99.4 & 62.3 \\ \hline \end{tabular} \caption{Percentage of threads within each forum containing one or more of the indicated keywords.} \label{tab:keyword-relevance} \end{table} \section{Understanding Forum Content} \label{sec:qual-methods} Our data contain rich information on attackers' strategies, interactions, and stated goals embedded in the natural language of users' posts. Here, we describe our qualitative methods for analyzing the content within Forums A\xspace, B\xspace\ \& C\xspace. \paragraph{Establishing human ratings for IPS relevance.} Our initial measurements showed not all content on these forums is relevant to the discussion of IPS tactics: for example, while 8 of the top 10 threads by viewership on Forum~B\xspace\ contained some mention of ways to monitor an intimate partner, the other two threads discussed contraception and women's underwear. Thus, to focus our analysis, we first established human ratings for whether or not a given thread was relevant to IPS. We began by randomly choosing 30 threads, 10 from each forum. Three coders independently rated whether each thread was IPS-relevant. We stipulated that a relevant thread should both (1) discuss an intent to track, monitor, surveil, or otherwise compromise an intimate partner's privacy; and (2) describe doing so via technology. Inter-rater reliability showed agreement in 28/30 threads (Fleiss' kappa of 0.91 \cite{mchugh2012interrater}). We then expanded our analysis to arrive at a set of IPS-relevant threads for further study. We randomly sampled 750 threads (250 from each forum) that we split evenly among the three coders. As reported in Table~\ref{tab:dataset}, we ultimately found 78\% of the sampled data within Forum~A\xspace\ was relevant to IPS; 51\% within Forum~B\xspace; and 18\% within Forum~C\xspace. These figures are in line with expectations: Forum~A\xspace, which is explicitly dedicated to ``\textit{investigative equipment}'', has the highest prevalence of IPS-related content, while Forum~C\xspace, which has a more general focus on discussion of infidelity, has the lowest. In total, 370 of the 750 randomly sampled threads were coded as IPS-relevant. We found no statistically significant correlations between thread viewership and IPS relevance in any forum, or any noteworthy patterns in seasonal, diurnal, or year-over-year posting activity within IPS-relevant data. \paragraph{Understanding IPS-relevant content.} We used open thematic coding \cite{braun2006using} to make sense of the 370 IPS-relevant threads. Three researchers independently read through several threads and generated initial codes. We then met over multiple sessions to jointly develop a codebook. Through multiple rounds of iteration, we refined the codebook by applying it to additional data until we reached saturation and codebook stability. Our final codebook contained 29 codes clustered into two high-level categories: \textit{forum culture} and \textit{tools and tactics} (see Appendix~\ref{sec:codebook}). Once the codebook was finalized, three researchers divided up the remaining threads and coded them. Our research team stayed in close correspondence throughout the analysis, repeatedly meeting to discuss threads that were unclear at first pass. We also took steps to minimize the impact of repeated readings of detailed stories of IPS and violence on our team. Researchers were encouraged to take breaks where needed, to reach out to each other regularly to process what we were reading, and to practice self-care. We report the themes that emerged from our analysis in Sections~\ref{sec:seeker-experience} and~\ref{sec:taxonomy}. We emphasize that our analyses are qualitative: thus, we do not report raw or percentage prevalence numbers for any of our themes, except where noted and appropriately tested via inter-rater reliability measurements. \section{Forum Interactions} \label{sec:seeker-experience} In this section, we give a general overview of how users interact within these forums. We begin by discussing how users self-report finding these communities, and what they seek within them. We then describe how communities respond to their requests. We identify threads in which communities encourage users to conduct IPS, either by encouraging them to carry out existing attacks, or by providing them with ideas for attacks of increased severity---what we call \textit{escalation}. We also identify threads in which communities discourage users from IPS at all, a pattern we call \textit{de-escalation}. \paragraph{How users find these forums.} In several threads in each forum, users describe how and why they sought out these forums in the first place. Many described locating the forum via basic Google queries on topics related to infidelity and cheating. In other posts, users reported discovering the site through a trusted recommendation from a professional enlisted to help them with their relationships, such as a therapist. Our data also show that for Forums A\xspace\ and B\xspace, users are often directed to these specific forums by moderators or users of other communities within their parent forum. For example, a moderator in Forum~A\xspace posted in response to a thread starter: \begin{quoting}[leftmargin = .1 in, vskip= .1 in, indentfirst = false] \textit{``I asked you to come here to click on the many threads and read information for yourself. There are pages and pages all about spying \dots This forum is a kind of archive where the information will be available for anyone to peruse at leisure. There is no need to wait. Look around!''} \end{quoting} Here, we see a forum moderator reinforce that these discussions are a resource for anyone to browse. We discovered that Forum~A\xspace\ in particular hosts several `resource threads' pinned at the top of the forum that provide primers for beginners. \paragraph{Forum-goers' stated goals.} Once in the forum, most users make an initial post outlining a complex social situation, \mbox{usually} suspected or actualized infidelity, and ask the community for advice on what to do, e.g. ``\textit{How can I forgive him?}'' or ``\textit{How do I move on?}'' Most of these posts sought suggestions from others for `next steps', such as confronting their intimate partner or seeking legal advice. The bulk of posts within Forum~C\xspace\ followed this pattern, mimicking the advice-seeking observed broadly in forums for social support \cite{yang2019seekers, Fu-Advice:19, chen2019reddit}. We also identified a different kind of request focused on {\it technical} support for intended or ongoing IPS, e.g. ``\textit{How can I read my wife's Facebook messages?}'' or ``\textit{How do I use this spyware tool?}'' Many of these users contextualized their asks in a detailed narrative of their situation that included an admission of past IPS, most commonly by reading a partner's text messages or emails. For example, consider this initial post, paraphrased from Forum~B\xspace: \begin{quoting}[leftmargin = .1 in, vskip= .1 in, indentfirst = false] \textit{``I caught my wife by reading her journal and emails. She does not know that I know, and I continue to monitor her email account. I don't think she knows. I haven't told a soul about this, so this is my release. I can elaborate...''} \end{quoting} Not all users framed their interactions as requests, however; a subset of thread starters within Forums A\xspace\ and B\xspace\ posted to share unsolicited advice on working with certain IPS tools. This advice was often couched in a personal narrative (e.g. ``\textit{Here's how I tracked his Internet history after he deleted it}'') and usually promoted the use of the tools. We consider these to be organic advertisements for these tools, the implications of which are discussed in Section~\ref{sec:discussion}. Overall, we identified three high-level goals for users who sought IPS-related advice across these forums. Many users fixated on reading their partner's emails or text messages, or what we call \textit{(1) investigation of a partner's prior activities}. Many were also interested in real-time access to their partner's devices, to gain information such as live updates on their partner's location and browsing history: in our view, these attackers sought \textit{(2) continuous monitoring of a partner's current and future device use}. Finally, we saw that many posters expanded the target of their IPS to include a suspected affair partner, with the goal of identifying their personal information (e.g., name, address or vehicle registration). We use the term \textit{affair partner} here to mean the person involved in an affair outside of the intimate relationship, occasionally referred to as the `other' man or woman, and we name this goal as a \textit{(3) compromise of a suspected affair partner's privacy}. \label{sec:responses} \paragraph{Community escalations.} Communities' responses to users' requests varied. As expected for online support forums, many responded with emotional support and advice on managing infidelity, including recommendations for looking after users' mental and physical health. In a significant body of threads, however, communities responded by encouraging thread starters to pursue their current enactment of IPS, or even to increase the severity of their attacks. We call this a pattern of \textit{escalation}: a situation in which a user begins with a relatively benign request for information, and through interactions with one or more IPS promoters is presented with ideas for enacting or increasing the severity of an IPS attack. Consider this example from Forum~B\xspace. A user begins a thread by asking for emotional support: ``\textit{I can't believe my relationship has come to this, but I need some advice. Recently I discovered a situation that I'm not sure how to perceive...}'' An hour later, a responder offers several actionable ways for the user to invade their partner's privacy: \begin{quoting}[leftmargin = .1 in, vskip= .1 in, indentfirst = false] \textit{``There are several things you can do. Start by going into full snoop mode. Purchase a voice activated recorder and put it in his car. Snoop his phone records. Place spyware on his computer. Snoop his emails and FB account.''} \end{quoting} From there, a concerning dialogue unfolds. As the thread starter shares more details of their story over follow-up posts, the same responder repeatedly suggests ways to enact IPS, for example by offering: \begin{quoting}[leftmargin = .1 in, vskip= .1 in, indentfirst = false] \textit{``A voice-activated recorder is cheap, \$40 at Walmart. Stop bringing this up, and make him think everything is back to normal. Then, monitor him. Good luck.''} \end{quoting} To get a sense of the prevalence of this thread pattern in our corpus, we conducted an additional qualitative coding effort over our human-labeled sampling of IPS-relevant posts. Three coders first coded a random set of 30 relevant threads (10 from each forum) for whether or not they showed a pattern of escalation. Inter-rater reliability showed substantial agreement between raters: out of the 30 posts, all 3 raters agreed on 25 posts, and the remaining 5 showed 2 out of 3 raters in agreement (Fleiss's kappa of 0.77). We then split the remaining relevant threads among the three coders, finding that approximately one-third of relevant threads showed patterns of escalation (Table~\ref{tab:dataset}). This proportion remained the same in both forums explicitly focused on investigating suspected deception (A\xspace, B\xspace), and in more general support forums for those `recovering' from infidelity (C\xspace). \paragraph{Community de-escalations.} While escalations appeared with alarming prevalence in our dataset, we also found a handful of instances of the opposite: \textit{de-escalations}, in which the community deterred a user from conducting IPS. In many of these cases, responders reminded posters of the physical and mental impact of continuously performing IPS on a partner. These responders saw that IPS directly undermined the trust required for recovery of a healthy intimate relationship. As this example from Forum~A\xspace shows: \begin{quoting}[leftmargin = .1 in, vskip= .1 in, indentfirst = false] \textit{``You've got to ask though, when do you stop snooping? That can't be healthy for your relationship if you're being insecure about everything.''} \end{quoting} De-escalating responders also often pointed out that IPS may not help people achieve their goals, and instead sabotage a relationship. For cases where IPS had already been \mbox{committed}, a small number of users pointed out how the intimate partner may be experiencing this level of privacy intrusion. We demonstrate this `pushback' against IPS through this responder on Forum~B\xspace, after a thread starter admits to monitoring his partner through a home security system: \begin{quoting}[leftmargin = .1 in, vskip= .1 in, indentfirst = false] \textit{``You sound crazy to watch her like that! The fact that you've analyzed every little detail on the system tells everyone a lot about your own insecurities ... come on dude, you're trying to make something out of nothing here.''} \end{quoting} Some de-escalating responders also reminded thread starters of the potential legal consequences of engaging in IPS. This included warnings that the use of some attacks could result in a criminal record, failed divorce proceedings due to misbehavior, or expulsion from social groups. \section{Taxonomy of IPS Attacks} \label{sec:taxonomy} We now describe the IPS tools and tactics discussed within these forums. We present a taxonomy (Table~\ref{tab:taxonomy}) of four types of attacks: (1) \textit{tool-based attacks requiring physical access}, including installing spyware on a partner's phone and attaching GPS trackers to their person; (2) \textit{tool-based attacks not requiring physical access}, including leveraging shared cloud accounts; (3) strategies involving \textit{coercion and subterfuge}, for example convincing a partner to provide access, or tricking them into connecting with falsified social media profiles; and (4) \textit{outsourced attacks}, namely hiring private investigators. \subsection{Tools that require physical access} \label{sec:taxonomy-tools-physical} \begin{table}[t] \centering \footnotesize \begin{tabular}{|l|} \hline {\bf Tool-based attacks that require physical access} \\ Using a cellphone backup recovery tool on a partner's device \\ Installing a keylogger on a partner's device \\ Installing screen recording spyware on a partner's device \\ Installing GPS trackers on a partner's body or in their car \\ Installing audiovisual recorders in the car or the home \\ \hline {\bf Tool-based attacks that do not require physical access} \\ Leveraging features of a shared phone plan \\ Using shared cloud tools to access a partner's personal data \\ Using router monitoring tools to track and manipulate Internet activity \\ Using reverse lookup directories to find personal information \\ \hline {\bf Coercion and subterfuge} \\ Leveraging physical proximity to gain access \\ Convincing a partner to give total access \\ Catfishing a partner \\ \hline {\bf Outsourced attacks} \\ Hiring a private investigator \\ \hline \end{tabular} \caption{Taxonomy of IPS attacks promoted on these forums.} \label{tab:taxonomy} \end{table} Our analysis surfaced many attacks requiring access to a target's devices. These attacks are particularly possible in IPS, due to the proximity between intimate partners \cite{freed2018stalker}. \paragraph{Backup recovery tools.} Recall that a common goal for attackers was the discovery of what a partner said in their texts or emails. To this end, responders promoting IPS often recommended the use of \textit{cellphone backup recovery tools}: both specific software dedicated to reading data from phones or SIM cards, and creative workarounds leveraging built-in iOS or Android features to access that same information. Some of the spyware previously reported \cite{chatterjee2018spyware} works by accessing similar data stores; our data show for the first time how attackers share these products with each other, and how they homebrew their own tools for accessing this information. In particular, a substantial number of threads were dedicated to tools that recovered deleted texts from iPhones. Similar tools were available for Android phones, and in older threads we even surfaced evidence of responders helping attackers retrieve texts from Blackberries. While some responders in these threads advocated for the use of specific products, others presented instructions for homebrewed tools they had developed to read messages from a partner's backup files synced to shared iTunes or iCloud storage. Some responders posted code anyone could use to convert such backup files into text files for easy reading, and many also offered one-on-one technical support. \paragraph{Keyloggers and screen recorders.} Many attackers were interested in continuous capture of their partners' digital activities, such as websites they visited or passwords they used. For these attackers, responders often recommended installing \textit{keyloggers} and \textit{screen recorders} on a partner's devices. These tools had been surfaced as potential spyware in prior work \cite{chatterjee2018spyware}, but our data highlight they are actively shared as solutions for attackers on these forums. One responder on Forum~C\xspace\ claimed he had installed keyloggers on all PCs and laptops in his home, describing the benefits of these tools: \begin{quoting}[leftmargin = .1 in, vskip= .1 in, indentfirst = false] ``\textit{Great for capturing passwords \& her true thoughts when messaging (things she backspaced over and didn't send).}'' \end{quoting} Many responders also recommended screen recorders, such as those built for companies to install on workers' devices---in fact, this use case was often invoked to prove a product's legitimacy. Responders also discussed the benefits and drawbacks of specific products, including whether the paid tiers of some tools were worth purchasing. \paragraph{Location tracking and audiovisual recording.} We saw many instances of responders recommending tools for environmental surveillance of a partner's activities, conversations and whereabouts, e.g., \textit{voice-activated recorders} and \textit{GPS tracking devices} placed in key locations like a partner's car. Responders were quick to make recommendations about where to obtain these devices, how much one should expect to pay for them, and best practices for hiding them from targets: \begin{quoting}[leftmargin = .1 in, vskip= .1 in, indentfirst = false] ``\textit{A GPS tracker can fit into a purse without them knowing. I'm positive you can figure out a place to stash one in a car. People track autistic kids and animals with them.}'' \end{quoting} Surveillance of partners in cars was a recurring theme throughout our data. In addition to providing recommendations on the best places in a car to place a GPS tracker, several threads promoted the use of more sophisticated tools that plug into a car's on-board diagnostics (OBD) system and continuously report the car's location to a remote database, to which an attacker can then subscribe. These tools would be useful, one responder said, because ``\textit{unless a person knows to check the OBD they would never think to look for it.}'' \subsection{Tools that do not require physical access} \label{sec:taxonomy-tools-no-physical} For would-be attackers who were unable to access a partner's phone to install spyware or car to plant a GPS tracker, the responders in our data readily provided tools that did not require physical access to partner or device. \paragraph{Leveraging shared phone plans.} Many would-be attackers sought ways to leverage the fact that they shared a phone plan with their intended target. Most seemed to know that a partner's call and SMS histories were accessible on a phone bill; in fact, viewing these was often the first thing an attacker tried, and the use of these records as vectors for abuse has been documented \cite{freed2018stalker}. But the contents of messages are often left off of phone bills; in response, our data show these attackers come to the forums to find other ways to obtain more information from their service providers. Responders regularly provided tips on how to contact service providers and obtain more detailed records: for example, in one thread on Forum~B\xspace, a responder described how to contact Verizon and set up a monthly spreadsheet dump of all call activity. Phone companies were required to provide these records to account owners, the responder claimed, as a form of consumer protection. Attackers were also savvy to the many other ways a provider's plan management tools could be used to surveil a partner. Verizon, AT\&T, and T-Mobile were purported to have capabilities ranging from email monitoring to mobile keylogging. Consider the following exchange on Forum~A\xspace: \begin{quoting}[leftmargin = .1 in, vskip= .1 in, indentfirst = false] {\bf Attacker:} ``\textit{We are in the process of choosing new cellphones and a new company. Which is the best company to keep tabs, records, etc? We currently have iPhones on AT\&T, and their Family Map did help me prove his affair.}'' \\ \noindent {\bf Responder:} ``\textit{If you're getting everything you need with AT\&T, I would stay with them. They have immediate online access [to phone records] and their GPS is good.}'' \end{quoting} In this example, we see responders outline the features of shared plans that make them useful to an attacker: immediate online access to call and text histories, quality GPS for location tracking, and family sharing products that provide easy-to-use interfaces for surveillant capabilities. This last type of tool was especially common in our data, confirming prior work \cite{chatterjee2018spyware, freed2018stalker}. This example also highlights the \mbox{collaborative} nature of how attacks surface in these forums, with a responder echoing and encouraging an attacker towards IPS. Of note, the responder in this example is the third-most-prolific superuser of Forum~A\xspace, and many of their posts are similarly IPS-related. \paragraph{Features of shared cloud services.} Many tools that did not require physical device access took advantage of the built-in features of cloud-based sharing tools. The use of cloud tools for abuse has been reported in prior work \cite{freed2018stalker}; however, our data show for the first time how attackers share these tools with each other as ways to overcome targets' defenses. In many threads, attackers seemed aware of the ways iCloud tools in particular could be used to surveil partners who had not provided device access. One thread began: \begin{quoting}[leftmargin = .1 in, vskip= .1 in, indentfirst = false] ``\textit{What is the best spyware if I can't get their phone, but have their Apple ID and password?}'' \end{quoting} In this example and many others, our data show attackers are encouraged by the forum to use their partner's Apple ID to view their personal messages and photos from a web browser---no device access necessary. This was commonly invoked as a solution for attackers who sought more detailed information on their partner's texts than records from a service provider contained. Many of these attackers reported they arrived at this method of attack because they had seen a drop-off in their partner's texting activity as reported by their phone bills, and had inferred the partner had moved to iMessage or another messaging service that used data rather than SMS. (Messaging that uses data is not typically itemized on a phone bill.) Some of these attacks, however, did not even require an attacker to use a partner's login, because their personal data was already syncing to a shared Apple device. For example, an attacker on Forum~C\xspace described discovering she could view a partner's messages on a family iPad, which was synced to her partner's iCloud account. Our data show attacks of this nature also levied against third-parties, namely the affair partners: in one thread on Forum~B\xspace, an attacker describes realizing her partner's affair partner was using an iPad synced to an iCloud account shared by all three-parties, making her purchasing and Internet history accessible for the attacker to browse. Attackers were particularly eager to share how iCloud tools could be used for location tracking. One attacker on Forum~A\xspace described how to use the Significant Locations feature within iOS to examine a partner's recent location history. In another thread on Forum~A\xspace, a user shared an article on Find My Friends and called out its abusive potential: \begin{quoting}[leftmargin = .1 in, vskip= .1 in, indentfirst = false] \textit{``Interesting article about an iPhone app called `Find My Friends', which you may be able to load on your spouse's phone to track their whereabouts.''} \end{quoting} Cloud-based tools outside of the Apple ecosystem were also called out for similar purposes. One responder on Forum~C\xspace shared how Android users could view a ``\textit{timeline}'' of a partner's visited locations via their Google Maps account. Another shared how WhatsApp's phone-to-Web syncing features could be used in concert with one-time physical access to maintain continuous access to a partner's messages. This responder described the initial connection as a ``\textit{one-minute job}'' best done while a partner sleeps, and claimed they were ``\textit{actually shocked at what a privacy flaw this seems to be.}'' Lastly, our forums contained many suggestions for mobile spyware products that leveraged cloud-based access to a target's device, such as tools marketed for use in parental control contexts. Much of the discussion of these products also offered advice on free versus paid tiers, setup and configuration, and even best practices for contacting customer service teams. \paragraph{Web traffic trackers on shared networks.} In several forums, we discovered threads in which responders offered advice on how to install \textit{web traffic monitoring tools} on a shared WiFi network. The scope of this attack and the level of detail in which it was described was noticeably more sophisticated than others in our data, or what has to our knowledge been previously reported. In one thread on Forum~C\xspace, a person who described themselves as a ``\textit{heartbroken techie}'' with a background in software development started a thread detailing how they used a DNS resolution service to monitor the traffic on their home router. With their tool, the attacker said, they could record every website their partner visited, regardless of whether they deleted their Internet history, in the form of reports issued within 24 hours. The attacker shared the command line scripts and configurations they had used, and even offered to share a GitHub repository where others could retrieve their code. In addition to describing how they used the service to monitor router traffic, they went on to discuss how they used its domain blocking alerts to manipulate their partner: \begin{quoting}[leftmargin = .1 in, vskip= .1 in, indentfirst = false] \textit{``You can set up a customized message (as I call it, the `oh shit' alert) that will pop up if they try accessing a site that is blocked. It's amazing how much someone will confess if they know you're tech-savvy and you tell them you have a detailed history of their actions (even if you don't.)''} \end{quoting} In another case, a responder on Forum~A\xspace who claimed to be a computer security professional introduced the forum to the concept of a man-in-the-middle attack and recommended an entry-level tool for mounting one. As they described, the tool was able to obtain not just a history of websites visited, but also copies of data sent over the network, e.g. the contents of emails and chats. Most notably, they described the tool as a way to actively manipulate a partner's activity: \begin{quoting}[leftmargin = .1 in, vskip= .1 in, indentfirst = false] \textit{``[You can also] modify the data traffic in real time. This can be used for tactics like replacing phone numbers, names and addresses as they travel over the network. Think about creative ways to change the contents of the websites/emails/chats that they're looking at.'' \end{quoting} This last example was sourced from one of the `resource threads' in Forum~A\xspace. The responder goes on to offer his services to community members who want help mounting such attacks. We discuss the implications of these types of attacks and the role of technologists providing such support in Section \ref{sec:discussion}. \paragraph{Reverse lookup directories.} Lastly, our data show would-be attackers seeking and receiving tips for investigating their partners' prior actions via reverse lookup tools, used most commonly to identify people from their phone numbers. Most cases presented as a thread starter finding an unknown number in a partner's texts or call records via other attacks, and then asking the forum for advice on how to discover whether it belonged to an affair partner or an escort service: \begin{quoting}[leftmargin = .1 in, vskip= .1 in, indentfirst = false] \textit{``If anyone knows a really good reverse cell lookup, please let me know. Just found a few unknown numbers on my husband's phone.''} \end{quoting} Many solutions offered were simple websites containing databases of people's personal information---one thread even offered tips on how to search Facebook by phone number. But responders in our data also recommended a wide array of commercial products that market themselves as collators of public information on individuals (e.g., WhitePages). Many of these tools offer a free tier enabling lookup of names, addresses, and phone numbers in addition to a paid service for more thorough background checks. Although these tools are relatively unsophisticated from a technical perspective, they featured in several stories that resulted in an attacker confronting their partner or suspected affair partner at an address or phone number located through these services. \subsection{Coercion and subterfuge} \label{sec:taxonomy-coercion} In addition to recommending specific tools, many responders had advice for coercing or subverting a target into providing access to their data and accounts, most often passwords. \paragraph{Leveraging physical proximity to gain access.} Attackers frequently shared how they used their close physical proximity to their targets to overcome common defenses without specific tooling. While many of these tactics had been previously reported from victims' perspectives \cite{freed2018stalker}, we report for the first time attackers jointly developing such coercive strategies in public forums. In many cases, attackers advised each other to manipulate a partner into `accidentally' revealing a password, as seen in the following example from Forum~A\xspace: \begin{quoting}[leftmargin = .1 in, vskip= .1 in, indentfirst = false] ``\textit{Get her to send texts \dots while you are sitting next to her. Then try to make out the password as she types it in.}'' \end{quoting} These strategies often did not require active manipulation. In some cases, gaining access was as simple as waiting for a partner to fall asleep: \begin{quoting}[leftmargin = .1 in, vskip= .1 in, indentfirst = false] \textit{``My wife would get drunk and pass out. It was simple to just hold the iPhone up to her thumb to unlock it. Took pictures of a lot of conversations so I have a record.''} \end{quoting} Some would-be attackers sought help creating opportunities like these. In one thread on Forum~A\xspace, an attacker asks: \begin{quoting}[leftmargin = .1 in, vskip= .1 in, indentfirst = false] ``\textit{I have wondered if there is a relaxing drug that will knock her out long enough for me to scan her texts and photos. Any suggestions on how I get that phone?}'' \end{quoting} Once a partner slept or was otherwise unconscious, attackers and responders offered a range of strategies for exploiting their lowered defenses. These included ways to overcome two-factor authentication schemes---namely, resetting passwords on locked accounts and taking the opportunity to capture codes---as well as ways to plant monitoring tools that could track activity long-term, such as swapping their SIM card into a partner's device to capture their call and text activity. \paragraph{Creating fake profiles to access their social media.} Coercive attacks did not necessarily need to be physical or direct: we also found evidence of manipulations via social media. Several threads showed attacks using fake social media profiles to overcome the privacy controls a target may have set. While the use of fake social media profiles to directly harass targets has been reported \cite{freed2018stalker}, we found evidence of attackers leveraging fake profiles in a new way: using second- and third-degree connections to access a target's profile. In one thread on Forum~A\xspace, a responder details step-by-step how to fabricate a believable Facebook account, and use it to befriend accounts that are friends with the target. The attacker can thus access parts of the target's social media profiles that have been locked away from the attacker, but have remained unlocked to what they believe are friends-of-friends. The responder describes the access afforded thus: \begin{quoting}[leftmargin = .1 in, vskip= .1 in, indentfirst = false] ``\textit{After your friend request has been accepted, revisit the pages where you couldn't see anything before. You'll be shocked at how much information will suddenly be available, as many MANY people set up security so it's not public, but can be viewed by friends-of-friends. In my neck of the woods there are a lot of local bars that have 1000+ friends and guess what? Every one of those 1000+ friends has now given access to those 1000+ people that allow friends-of-friends to see their info, and I'd guess over half do.}'' \end{quoting} That responder then cautions attackers to ensure the privacy settings on their real and fake Facebook profiles are set to only show information to the account owner, because, the responder says, ``\textit{I don't believe FB is secure.}'' \paragraph{Convincing a partner to provide total access.} Our data also showed attackers and responders championing a strategy of simply convincing a partner that unfettered access to all devices and accounts should be expected in an \mbox{intimate} \mbox{partnership}. In our context, infidelity forums, this was often raised as a way to facilitate reconciliation after an affair: \begin{quoting}[leftmargin = .1 in, vskip= .1 in, indentfirst = false] ``\textit{Tell her you need her iCloud password to review something. If she refuses, that's a giant red flag. Then I suggest you say `wife, I love you dearly, but if I don't see what's on that phone, then you are telling me that you're cheating. If you have nothing to hide, then let me see it.'} '' \end{quoting} Freed et al. \cite{freed2018stalker} previously reported that abusers often convinced IPV survivors to share their passwords during ``good'' phases of a relationship as a way to establish trust, and subsequently threatened them to continue sharing or face consequences when the relationship turned ``bad''. Our work extends this to show that attackers promote to each other the idea of privacy compromise as currency in abusive relationships, often describing this as key to overcoming the emotional toll of suspicions of infidelity. In fact, many of these threads shared stories in which a partner who was suspected of cheating in the past still shared total access months or years later. \subsection{Outsourced attacks} \label{sec:taxonomy-outsourcing} The final category of IPS attacks surfaced in our data are those in which a responder recommends external resources for investigation or monitoring of an intimate partner. \paragraph{Private investigators (PIs).} As expected for an infidelity forum context, many attackers and responders within our data referenced hiring PIs to track their partners, with the goal of finding evidence of an affair. Notably, hiring a PI was framed as a legal and ethical way to obtain information, as in this example from a responder on Forum~B\xspace: \begin{quoting}[leftmargin = .1 in, vskip= .1 in, indentfirst = false] ``\textit{You should hire a PI, who acts within the law to obtain the confirmation you require. But that's all that it will be in the vast majority of cases...merely confirmation.}'' \end{quoting} Many of the PIs recommended in our data offered services within their specific localities, e.g., ``\textit{He does not do surveillance unless the target originates in [specific U.S. state].}'' These recommendations typically included a phone number to call and a person to ask for---or even, in some cases, a person from the forum to claim as a referral. In addition to general recommendations to seek out PIs and referrals to specific PIs, we also found one thread in which a responder posted a link to the website of a specific national agency, as well as another thread with a directory of `\textit{vetted}' PIs. These recommendations were often framed as more costly than other attacks, to be used as a last resort. One responder on Forum~A\xspace\ remarked PIs were expensive, but at least ``\textit{cheaper than a divorce lawyer}''. \section{Discussion} \label{sec:discussion} We now synthesize takeaways from our findings for anti-IPS efforts. First, our work extends the IPS threat model outlined in this and prior works \cite{freed2018stalker, chatterjee2018spyware}. Security experts seeking to prevent their work from misuse in IPS might consider accounting for this threat model in their technology development practices---in particular, Freed et al. \cite{freed2018stalker} supplies the concept of a \textit{UI-bound adversary} as a consideration for design teams. We additionally outline broader considerations for security experts, including the use of these online communities as a source of IPS threat intelligence and the development of countermeasures that target the commercial entities behind the spyware industry. Finally, we describe how our work is already impacting interventions, and close by posing a set of open ethical questions for the security community. \paragraph{Online forums are a rich source of IPS threat intelligence.} Our work highlights how analysis of online communities can provide anti-IPS advocates with valuable intelligence on the motivations and tactics of intimate partner abusers. By observing how attackers interact in these forums and the specific tools they promote for use, we were able to surface new knowledge on IPS strategies that can directly inform interventional efforts. Our results confirm findings from prior work that showed the abundance of dual-use and overt spyware apps available for attackers \cite{chatterjee2018spyware}, and highlighting victims' experiences of tech-enabled abuse \cite{freed2018stalker}. But the details of how, precisely, abusers learn to mount these attacks had not previously been reported, and attackers' levels of sophistication had not been well-understood. Our analysis highlights how attackers are collaborating on new tactics in these forums, and surfaces how these attacks are conducted at an unprecedented level of granularity. For example, we find that attackers are not just inspecting targets' call histories on shared family plans, as has been reported previously \cite{freed2018stalker}---they are also sharing strategies on how best to contact service providers and obtain more detailed records. We also surface novel attacks more sophisticated than those previously reported in the IPS context, for example the use of WiFi router tools to monitor and manipulate a partner. Mining these forums for threat intelligence might help anti-IPS efforts stay ahead of attackers' ever-evolving techniques. We see substantial future work in creating semi-automated tools that enable analyses like ours to scale. As our initial keyword searches (Section~\ref{sec:data-desc}) showed, the way IPS manifests in user-generated natural language may be too nuanced for current automated techniques alone to reliably detect. However, human ratings are laborious and inefficient and, importantly, repeated exposure to stories of abuse can inflict harm on people analyzing large bodies of such texts \cite{figley_compassion_1995}. These problems are exacerbated on large social media platforms, where the volume and speed of conversations generated by millions of users creates urgent problems of scale. We see a role for advanced language processing techniques in overcoming these challenges. For example, a system might quickly and reliably extract the specific strategies recommended within a post without relying on forum-specific features (as applied in cybercrime marketplaces in \cite{durrett2017identifying}). Such a system might provide a valuable pipeline for security and privacy researchers and anti-IPV advocates building frontline defenses against emergent attack strategies, for example the Coalition Against Stalkerware.\footnote{https://stopstalkerware.org} In fact, our work has already had impact in this regard. We shared our results with the team of practitioners that runs a technology clinic providing direct interventions to IPV survivors facing IPS \cite{havron2019clinical, freed2019clinical}.\footnote{https://www.ipvtechresearch.org/} At time of writing, they are working to integrate our threat intelligence into their training materials for advocates, as well as their clinic's procedures for discovering and mitigating how abusers are enacting surveillance against their clients. \paragraph{The for-profit industry behind IPS products uses online forums to market their tools.} Our work also shows that the online ecosystems promoting spyware feature a significant presence from companies creating and marketing their own surveillance products. At one extreme, we found entire forums bloated with spam advertisements for a single spyware tool, suggesting these forums were leveraged to manipulate that tool's SEO. We also found that recommendations for IPS tools are not just manifesting as spam advertisements and SEO for specific spyware apps, but are also shared organically among users in the forum communities. Within these organic posts, responders engage meaningfully with forum-goers' relationship problems, but also evangelize specific IPS tools or approaches and even serve as technical support for users' spyware installations. Their posts reveal the concerns of consumers in this market: we find posts on the merits and drawbacks of a range of spyware products, both free and paid, and the market rates for voice-activated recorders, GPS trackers, and PIs. All told, our analysis suggests these forums are likely one corner of a broad industry offering `solutions' for would-be attackers to turn suspicions of infidelity into actualized IPS. These findings suggest a role for mitigation strategies that directly target these commercial entities. Prior work has demonstrated ways to undermine commercially motivated spam and SEO attacks by working directly with banks and payment processors to make e-crime difficult to monetize \cite{kanich2011show, mccoy2012priceless}. Similar approaches may be effective in the context of IPS. Future work should investigate further the mechanics of how forums like these are leveraged as marketing tactics by spyware companies, with the goal of informing such `follow-the-money' countermeasures. Similar countermeasures might be also useful for security experts concerned about keeping their tools from being misused for IPS: it is possible, for example, that dual-use apps \cite{chatterjee2018spyware} are being advertised as spyware. Where possible, security experts should prevent their tools from being marketed in this way. \paragraph{Platform-level defenses might mitigate the spread of IPS.} In addition, our work raises concerns for large social media platforms, where conversations escalating into IPS ``how-tos'' may be happening in spaces that are not specifically dedicated to infidelity, surveillance, or intimate relationships. We have highlighted features of IPS-relevant conversations, and outlined an agenda for creating semi-automated techniques to extract attackers' strategies from such forums. Platforms concerned about their role in enabling the spread of IPS could use this work to develop community norms or content moderation strategies attuned to these forums' dynamics---for example, the moderators of Forum~C\xspace might consider banning posts that escalate threads into IPS, and instead seek to encourage de-escalation. Future work might investigate further the scale of the problem within popular social media networks as a first step to developing such mitigation strategies. Social media platforms might also consider the fake profile attacks discussed in Section~\ref{sec:taxonomy-coercion}, and use the patterns we uncovered to more effectively surface falsified accounts. They might also consider de-emphasizing second- and third-degree network connections in users' experiences of their platforms, or offer privacy controls that limit users' audiences to first-degree connections by default. \paragraph{Online communities are collaboratively creating new IPS attacks.} Our work also shows that people with significant training in computer security and privacy, while potentially well-meaning, are actually helping to further develop IPS attacks on these forums. We were surprised to see the level of technical sophistication in some threads, particularly in contrast to the relatively unsophisticated techniques reported in prior studies with victims \cite{matthews2017stories,freed2018stalker}. Some attacks did fall into the bucket of previously known techniques, for example physical privacy violations like shoulder surfing that are addressable through existing defense strategies \cite{khan2018evaluating, davin2017baseline}. However, several involved the use of custom shell scripts and other more sophisticated techniques, including methods for extracting information from artifacts like iPhone backups and leveraging DNS resolution tools to manipulate a partner's Internet traffic. In a sense, the IPS promoters who championed their homegrown surveillance tools in these forums were engaged in a process of collaborative innovation, working with other tech-savvy community members to create and refine new abuse tactics. This is similar to behaviors seen previously in cybercrime forums~\cite{cybercrime:weis15}, in which a handful of sophisticated users create tools and then provide or sell them to the community. These collaborative processes are not just creating more efficient attacks, they are also making attacks more accessible to more would-be attackers: much of the discussion on these forums serves as how-to guides for less tech-savvy members, and in many cases communities even provide one-on-one troubleshooting. Future research might further analyze the cooperative dynamics of how these forums develop new attacks, and compare these against known tactics used to perpetrate harm in offline settings (c.f., \cite{hearn_violences_1998}). \paragraph{Infidelity is used as a justification for IPS.} The forums we studied were rife with emotionally vulnerable people seeking and receiving assistance with difficult interpersonal problems. But they were also rife with attackers freely admitting to and promoting the use of surveillance tools against an intimate partner, often by arguing that infidelity justifies surveillance. In this, we see that the context of infidelity both attracted people to the forums as a site for emotional support and masked them from the social exclusion they might have faced if admitting to IPS in a non-infidelity context \cite{hearn_violences_1998}. This is particularly concerning for anti-IPS efforts, as it can set a precedent of using infidelity as an excuse for abusive actions---a practice mirrored in offline discussions with abusers in IPV \cite{nemeth2012sexual}. We see compelling areas for future work in using these forums to identify the cultural norms and justifications that encourage abusive behaviors. In concert with ongoing behavior change work with abusers \cite{kelly_naming_2016}, such work could draw on the patterns of de-escalation we uncovered to develop alternative strategies for resolving suspicions of infidelity without resorting to IPS. These alternatives could be promoted before IPS on these forums, thereby retaining the supportive community structure they provide to some forum-goers while discouraging abusive practices. The infidelity forum setting also creates gray areas for the computer security community at large. Some of the responders providing (ab)users with strategies for IPS were self-described computer security experts who reported using the same tools they promoted for surveillance in their professional work. In the context of helping people who reported they were in toxic relationships, these experts may have felt their material support facilitating IPS was justified. What's more, in the context of publicly available forums like the ones in our study, these experts' bespoke surveillance solutions constitute a persistent record accessible to anyone on the Internet with little effort. It is possible that well-meaning computer security experts may have facilitated IPS not just for the user who posted in the forum, but also for the numerous people who would browse these threads in the future. We raise these tensions as a set of open ethical questions for the security community. Much as medical doctors operate by a professional code of conduct to `do no harm,' should computer security experts abide by a corresponding professional ethos to wield their expertise only for good? How should judgment calls between justifiable and unjustifiable surveillance be made, and who should make them? And how can computer security experts balance publicizing attacks to support anti-IPS efforts (for example, in this work) against the possibility that doing so might inadvertently help more attackers? \section{Conclusion} We have provided the first measurement study of the online communities in which people enacting IPS discuss their tactics. Through a mixed-methods study of five public forums, including a Reddit subforum dedicated to infidelity, we developed a taxonomy of the IPS strategies attackers discuss online. We showed that these forums are sites for both spam advertising specific spyware products and organic discussion of surveillance tools between users. We highlighted threads in which (ab)users learn new IPS tactics from more tech-savvy forum-goers, as well as cases where forums deter them from conducting IPS. Our work is already impacting anti-IPS interventions by informing programs that directly assist victims. \section*{Acknowledgments} We thank Sandra Ebirim for vital contributions to the data analysis phase of our study. We are also grateful to our reviewers, whose comments greatly helped to improve our paper. This work was funded in part by NSF Awards \#1916096 and \#1916126, as well as gifts from Facebook and Google. \bibliographystyle{plain}
{'timestamp': '2020-06-01T02:04:37', 'yymm': '2005', 'arxiv_id': '2005.14341', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14341'}
arxiv
\section{Introduction} \label{sec:introduction} The combination of ubiquitous multimedia and high performance computing resources has inspired numerous efforts to \emph{manipulate} audio-visual content for both benign and sinister purposes. Recently, there has been a lot of interest in the creation and detection of high-quality videos containing facial and auditory manipulations, popularly known as \emph{deepfakes}~\cite{dolhansky2019deepfake,DBLP:DF-TIMIT}. Since fake videos are often indistinguishable from genuine counterparts, detection of deepfakes is challenging but topical given their potential for denigration and defamation, especially against women and in propagating misinformation~\cite{dystopia,AI2018}. Part of the challenge in detecting deepfakes via artifical intelligence (AI) approaches is that deepfakes are themselves created via AI techniques. Neural network-based architectures like Generative Adversarial Networks (GANs)~\cite{NIPS2014_5423} and Autoencoders~\cite{Vincent2008} are used for generating fake media content, and due to their `learnable' nature, output deepfakes become more naturalistic and adept at cheating fake detection methods over time. Improved deepfakes necessitate novel fake detection (FD) solutions; FD methods have primarily looked at frame-level visual features~\cite{Capsule_Forensics} for statistical inconsistencies, but temporal characteristics~\cite{using_RNNs} have also been examined of late. Recently, researchers have induced audio-based manipulations to generate fake content, and therefore, corruptions can occur in both the visual and audio channels. Deepfakes tend to be characterized by visual inconsistencies such as a lack of lip-sync, unnatural facial and lip appearance/movements or assymmetry between facial regions such as the left and right eyes (see~Fig.~\ref{fig:localisation} for an example). Such artifacts tend to capture user attention. Authors of~\cite{Grimes1991MildAD} performed a psycho-physical experiment to study the effect of \emph{dissonance}, \textit{i.e.}, lack of sync between the audio and visual channels on user attention and memory. Three different versions of four TV news stories were shown to users, one having perfect audio-visual sync, a second with some asynchrony, and a third with no sync. The study concluded that out-of-sync or \emph{dissonant} audio-visual channels induced a high user cognitive load, while in-sync audio and video (no dissonance condition) were perceived as a \emph{single stimulus} as they `belonged together'. We adopt the \emph{dissonance} rationale for deepfake detection, and since a fake video would contain either an altered audio or visual channel, one can expect higher audio-visual dissonance for fake videos than for real ones. We measure the audio-visual dissonance in a video via the \emph{\textbf{Modality Dissonance Score}} (MDS), and use this metric to label it as \emph{real}/\emph{fake}. Specifically, audio-visual dissimilarity is computed over 1-second video chunks to perform a fine-grained analysis, and then aggregated over all chunks for deriving MDS, employed as figure-of-merit for video labeling. MDS is modeled based on the \emph{contrastive} loss, which has traditionally been employed for discovering lip-sync issues in video~\cite{outoftime}. Contrastive loss enforces the video and audio features to be \emph{closer} for real videos, and \emph{farther} for fake ones. Our method also works with videos involving only the audio/visual channel as our neural network architecture includes the video and audio-specific sub-networks, which seek to independently learn discriminative real/fake features via the imposition of a \textit{cross-entropy} loss. Experimental results confirm that these unimodal loss functions facilitate better real-fake discriminability over modeling only the contrastive loss. Experiments on the DFDC~\cite{dolhansky2019deepfake} and DF-TIMIT~\cite{VID-TIMIT} datasets show that our technique outperforms the state-of-the-art by upto 7\%, which we attribute to the following factors: (1) Modeling unimodal losses in addition to the contrastive loss which measures modality dissonance, and (2) Learning discriminative features by comparing 1-second audio-visual \emph{chunks}~to compute MDS, as against directly learning video-level features. Chunk-wise learning also enables \textit{localization} of transient video forgeries (\textit{i.e.}, where only some frames in a sequence are corrupted), while past works have only focused on the \emph{real}-\emph{fake} labeling problem. The {key contributions} of our work are: (a) We propose a novel multimodal framework for deepfake video detection based on modality dissonance computed over small temporal segments; (b) To our knowledge, our method is the first to achieve temporal forgery localization, and (c) Our method achieves state-of-art results on the DFDC dataset, improving AUC score by up to 7\%. \section{Literature Review} Recently, considerable research efforts have been devoted to detecting fake multimedia content automatically and efficiently. Most video faking methods focus on manipulating the video modality; audio-based manipulation is relatively rare. Techniques typically employed for generating fake visual content include 3D face modeling, computer graphics-based image rendering, GAN-based face image synthesis, image warping, \textit{etc}. Artifacts are synthesized either via face swapping while keeping the expressions intact (\textit{e.g.}, DeepFakes\footnote{https://github.com/deepfakes/faceswap}, FaceSwap\footnote{https://github.com/MarekKowalski/FaceSwap/}) or via facial expression transfer, \textit{i.e.}, facial reenactment (\textit{e.g.}, Face2Face \cite{thies2016face}). Approaches for fake video detection can be broadly divided into three categories as follows: \subsection{Image-based} These methods employ image/frame-based statistical inconsistencies for \emph{real}/\emph{fake} classification. For example,~\cite{visual_artifacts} uses visual artifacts such as missing reflections and incomplete details in the eye and teeth regions, inconsistent illumination and heterogeneous eye colours as cues for fake detection. Similarly,~\cite{inconsistent_headposes} relies on the hypothesis that the 3-D head pose generated using the entire face's landmark points will be very different from the one computed using only the central facial landmarks, in case the face is synthetically generated. Authors of \cite{Li2018ExposingDVFWA}~hypothesize that fake videos contain artifacts due to resolution inconsistency between the warped face region (which is usually blurred) and surrounding context, and models the same via the VGG and ResNet deep network architectures. A capsule network architecture is proposed in~\cite{Capsule_Forensics} for detecting various kinds of spoofs, such as video replays with embedded images and computer-generated videos. \begin{sloppypar} A multi-task learning framework for fake detection-cum-segmentation of manipulated image (or video frame) regions is presented in~\cite{multi-task}. It is based on a convolutional neural network, comprising an encoder and a Y-shaped decoder, where information gained by one of the detection/segmentation tasks is shared with the other so as to benefit both tasks. A two-stream network is proposed in~\cite{Two-stream}, which leverages information from local noise residuals and camera characteristics. It employs a GoogLeNet-based architecture for one stream, and a patch based triplet network as second stream. Authors of~\cite{afchar2018mesonet} train a CNN, named MesoNet, to classify real and fake faces generated by the DeepFake and Face2face techniques. Given the similar nature of falsifications achieved by these methods, identical network structures are trained for both problems by focusing on mesoscopic properties (intermediate-level analysis) of images. \end{sloppypar} \subsection{Video-based} Video-based fake detection methods also use temporal features for classification, since many a time, deepfake videos contain realistic frames but the warping used for manipulation is temporally inconsistent. For instance, variations in eye-blinking patterns are utilized in~\cite{in_ictu_oculi} to determine real and fake videos. Correlations between different pairs of facial action units across frames are employed for forgery detection in~\cite{protecting_leaders}. Authors of~\cite{using_RNNs} extract frame-level CNN features, and use them to train a recurrent neural network for manipulation detection. \subsection{Audio-visual features based} Aforementioned approaches exploit only the visual modality for identifying deepfake videos. However, examining other modalities such as audio signal in addition to the video can also be helpful. As an example, authors of~\cite{mittal2020emotions} propose a Siamese network-based approach, which compares the multimedia as well as emotion-based differences in facial movements and speech patterns to learn differences between real and fake videos. Lip-sync detection in unconstrained settings is achieved by learning the \emph{closeness} between the audio and visual channels for in-sync vs out-of-sync videos via contrastive loss modeling in~\cite{outoftime}. While this technique is not meant to address deep-fake detection \emph{per se}, lip-sync issues can also be noted from a careful examination of deepfake videos, and the contrastive loss is useful for \emph{tying up} genuine audio-visual pairs. \subsection{Bimodal Approaches} While it may be natural to see audio and video as the two main information modes that indicate the genuineness/fakeness of a video, one can also employ multiple cues from the visual modality for identifying fake videos. Multimodal cues are especially useful while tackling sophisticated visual manipulations. In~\cite{using_RNNs}, both intra-frame and inter-frame visual consistencies are modeled by feeding in frame-level CNN features to train a recurrent neural network. Statistical differences between the warped face area and the surrounding regions are learned via the VGG and ResNet architectures in~\cite{Li2018ExposingDVFWA}. Hierarchical relations in image (video frame) content are learned via a Capsule Network architecture in~\cite{Capsule_Forensics}. \subsection{Analysis of Related Work} Upon examining related literature, we make the following remarks to situate our work with respect to existing works. \begin{figure*}[!tbph] \centering \includegraphics[width=\textwidth]{BTP-pipeline.pdf} \caption{MDS-based fake video detection: Features extracted from 1-second audio-visual segments are input to the MDS network. The MDS network comprises the audio and visual sub-networks, whose description is provided in Table~\ref{tab:stream_arch}. Descriptors learned by the video and audio sub-networks are tuned via the cross-entropy loss, while the contrastive loss is employed to enforce higher dissimilarity between audio-visual chunks arising from \emph{fake} videos. MDS is computed as the aggregate audio-visual dissonance over the video length, and employed as a figure of merit for labeling a video as \emph{real}/\emph{fake}.} \label{fig:pipeline} \end{figure*} \begin{itemize} \item[1.] While frame-based methods that learn spatial inconsistencies have been proposed to detect deepfakes, temporal-based approaches are conceivably more powerful to this end, as even if the manipulation looks natural in a static image, achieving temporally consistent warping even over a few seconds of video is difficult. Our approach models temporal characteristics, as we consider 1-second long audio-visual segments to distinguish between real and fake videos. Learning over tiny video chunks allows for a fine-grained examination of temporal differences, and also enables our method to temporally \emph{localize} manipulation in cases where the forgery targets only a small portion of the video. To our knowledge, prior works have only focused on assigning a \emph{real}/\emph{fake} video label. \item[2.] Very few approaches have addressed deepfake detection where the audio/video stream may be corrupted. In this regard, two works very related to ours are~\cite{outoftime} and~\cite{mittal2020emotions}. In~\cite{outoftime}, the contrastive loss function is utilized to enforce a smaller distance between lip-synced audio-visual counterparts; our work represents a novel application of the contrastive loss, employed for lip-sync detection in~\cite{outoftime}, to deepfake detection. Additionally, we show that learning audio-visual dissonance over small chunks and aggregating these measures over the video duration is more beneficial than directly learning video-level features. \item[3.] Both multimedia and emotional audio-visual features are learned for FD in~\cite{mittal2020emotions}. We differ from~\cite{mittal2020emotions} in three respects: (a) While we do not explicitly learn emotional audio-visual coherence, forged videos need not be emotional in nature; audio-visual consistency is enforced via the contrastive loss in our approach. (b) The training framework in~\cite{mittal2020emotions} requires a \emph{real}--\emph{fake} video pair. Our approach does not constrain the training process to involve video-pairs, and adopts the traditional training protocol. (c) Whilst~\cite{mittal2020emotions} perform a video-level comparison of audio-visual features to model dissonance, we compare smaller chunks and aggregate chunk-wise measures to obtain the MDS. This enables our approach to localize transient forgeries. \item[4.] Given that existing datasets primarily involve visual manipulations (number of datasets do not have an audio component), our architecture also includes audio and visual sub-networks which are designed to learn discriminative unimodal features via the cross-entropy loss. Our experiments show that additionally including the cross-entropy loss is more beneficial than employing only the contrastive loss. Enforcing the two losses in conjunction enables our approach to achieve state-of-the-art performance on the DFDC dataset. \end{itemize} \section{MDS-based fake video detection} As discussed in Section \ref{sec:introduction}, our FD technique is based on the hypothesis that deepfake videos have \emph{higher dissonance} between the audio and visual streams as compared to real videos. The dissimilarity between the audio and visual channels for a \emph{real}/\emph{fake} video is obtained via the Modality Dissonance Score (MDS), which is obtained as the aggregate dissimilarity computed over 1-second visual-audio chunks. In addition, our network enforces learning of discriminative visual and auditory features even if the contrastive loss is not part of the learning objective; this enables FD even if the input video is missing the audio/visual modality, in which case the contrastive loss is not computable. A description of our network architecture for MDS-based deepfake detection follows. \subsection{Overview} Given an input video, our aim is to classify it as \emph{real} or \emph{fake}. We begin with a training dataset $D = \{(v^1,y^1), (v^2,y^2), ... , (v^N,y^N)\}$ consisting of $N$ videos. Here, $v^i$ denotes the input video and the label $y^i \ \epsilon \ \{0,1\}$ indicates whether the video is \emph{real} ($y^i=0$) or \emph{fake} ($y^i=1$). The training procedure is depicted in Fig. \ref{fig:pipeline}. We extract the audio signal from input video $v^i$ using the \emph{ffmpeg} library, and split it into $D$-second segments. Likewise for the visual modality, we divide the input video into $D$-second long segments, and perform face tracking on these video segments using the S3FD face detector~\cite{zhang2017s3fd} to extract the face crops. This pre-processing gives us segments of visual frames $\{s^i_1, s^i_2, ... , s^i_n\}$ along with corresponding audio segments $\{a^i_1, a^i_2, ... , a^i_n\}$, where $n$ denotes segment count for an input video $v^i$. We employ a bi-stream network, comprising the audio and video streams, for deepfake detection. Each video segment $s^i_t, t= 1 \ldots n$ is passed through a visual stream $S_v$, and the corresponding audio segment $a^i_t$ is passed through the audio stream $S_a$. These streams are described in Sections \ref{sec:visual} and \ref{sec:audio}. The network is trained using a combination of the \emph{contrastive loss} and the \emph{cross-entropy loss}. The contrastive loss is meant to \emph{tie up} the audio and visual streams; it ensures that the video and audio streams are \emph{closer} for real videos, and \emph{farther} for fake videos. Consequently, one can expect a low MDS for real, and high MDS for fake videos. If either the audio or visual stream is missing in the input video, in which case the contrastive loss is not computable, the video and audio streams will still learn discriminative features as constrained by the unimodal cross-entropy losses. These loss functions are described in Sec.~\ref{sec:loss}. \subsection{Visual Stream} \label{sec:visual} The input to the visual stream is $s^i_t$, a video sequence of size ($3 \times h \times w \times D*f$), where 3 refers to the RGB color channels of each frame, $h, w$ are the frame height and width, $D$ is the segment length in seconds, and $f$ is the video frame rate. Table \ref{tab:stream_arch} depicts the architecture of the video and audio sub-networks. The visual stream ($S_v$) architecture is inspired by the 3D-ResNet similar to \cite{DBLP:journals/corr/abs-1711-09577}. 3D-CNNs have been widely used for action recognition in videos, and ResNet is one of the most popular architectures for image classification. The feature representation learnt by the visual stream, in particular the fc8 output, denoted by $f_v$ is used to compute the contrastive loss. We also add a 2-neuron classification layer at the end of this stream, which outputs the visual-based prediction label. So the output of this stream, labeled as $\hat{y}_v^i$, constitutes the unimodal cross-entropy loss. \definecolor{cadetblue}{rgb}{0.37, 0.62, 0.63} \definecolor{pistachio}{rgb}{0.58, 0.77, 0.45} \definecolor{orange}{rgb}{1.0, 0.5, 0.0} \definecolor{palecopper}{rgb}{0.85, 0.54, 0.4} \definecolor{mountainmeadow}{rgb}{0.19, 0.73, 0.56} \definecolor{pastelorange}{rgb}{1.0, 0.7, 0.28} \definecolor{yellow}{rgb}{1.0, 1.0, 0.0} \definecolor{violet}{rgb}{0.56, 0.0, 1.0} \begin{table}[t] \caption{Structure of the audio and visual streams (initial layers of the visual stream are the same as in the 3D ResNet architecture \cite{DBLP:journals/corr/abs-1711-09577}).} \label{tab:stream_arch} \scalebox{0.9}{ \begin{tabular}{c c} \toprule \textbf{Visual Stream} & \textbf{Audio Stream}\\ \midrule \multirow{3}{*}{\colorbox{red!30}{conv1}} & \colorbox{red!30}{conv\_1, 3$\times$3, 1, 64}\\ & \colorbox{white}{batch\_norm\_1, 64}\\ & \colorbox{blue!30}{pool\_1, 1$\times$1, MaxPool}\\ \multirow{3}{*}{\colorbox{red!30}{conv2\_x}} & \colorbox{red!30}{conv\_2, 3$\times$3, 64, 192}\\ & \colorbox{white}{batch\_norm\_2, 192}\\ & \colorbox{blue!30}{pool\_2, 3$\times$3, MaxPool}\\ \multirow{2}{*}{\colorbox{red!30}{conv3\_x}} & \colorbox{red!30}{conv\_3, 3$\times$3, 192, 384}\\ & \colorbox{white}{batch\_norm\_3, 384}\\ \multirow{2}{*}{\colorbox{red!30}{conv4\_x}} & \colorbox{red!30}{conv\_4, 3$\times$3, 384, 256}\\ & \colorbox{white}{batch\_norm\_4, 256}\\ \multirow{3}{*}{\colorbox{red!30}{conv5\_x}} & \colorbox{red!30}{conv\_5, 3$\times$3, 256, 256}\\ & \colorbox{white}{batch\_norm\_5, 256}\\ & \colorbox{blue!30}{pool\_5, 3$\times$3, MaxPool}\\ \multirow{2}{*}{\colorbox{orange!80}{average pool}} & \colorbox{red!30}{conv\_6, 5$\times$4, 256, 512}\\ & \colorbox{white}{batch\_norm\_6, 512}\\ \colorbox{mountainmeadow!80}{fc7, 256$\times$7$\times$7, 4096} & \colorbox{mountainmeadow!80}{fc7, 512$\times$21, 4096} \\ \colorbox{white}{batch\_norm\_7, 4096} & \colorbox{white}{batch\_norm\_7, 4096} \\ \colorbox{mountainmeadow!80}{fc8, 4096, 1024} & \colorbox{mountainmeadow!80}{fc8, 4096, 1024} \\ \colorbox{white}{batch\_norm\_8, 1024} & \colorbox{white}{batch\_norm\_8, 1024} \\ \colorbox{cadetblue!80}{dropout, $p=0.5$} & \colorbox{cadetblue!80}{dropout, $p=0.5$} \\ \colorbox{mountainmeadow!80}{fc10, 1024, 2} & \colorbox{mountainmeadow!80}{fc10, 1024, 2} \\ \bottomrule \end{tabular}} \end{table} \subsection{Audio Stream} \label{sec:audio} Mel-frequency cepstral coefficients (MFCC) features are input to the audio stream. MFCC features~\cite{Mogran2004} are widely used for speaker and speech recognition \cite{martinez2012speaker}, and have been the state-of-the-art for over three decades. For each audio segment of $D$ second duration $a^i_t$, MFCC values are computed and passed through the audio stream $S_a$. 13 mel frequency bands are used at each time step. Overall, audio is encoded as a heat-map image representing MFCC values for each time step and each mel frequency band. We base the audio stream architecture on convolutional neural networks designed for image recognition. Contrastive loss $L_1$ uses the output of fc8, denoted by $f_a$. Similar to the visual stream, we add a classification layer at the end of the audio stream, and the output $\hat{y}_a^i$ is incorporated in the cross-entropy loss for the audio modality. \begin{figure}[!b] \centering \vspace{-4mm} \subfloat{\includegraphics[width = 70mm]{Contrastive_Alone_Test_1109}} \newline \subfloat{\includegraphics[width = 70mm]{Combined_Loss_Test_1109}} \vspace{-1mm} \caption{Effect of loss functions: The graphs show the effect of audio and visual cross-entropy loss functions (Section \ref{sec:AblationStudies}). The top and bottom graphs show the MDS distribution for test samples, when the contrastive loss $ L_1$ alone and combined losses $L$ are used in the training of the MDS network, respectively.}\vspace{-1mm} \label{fig:Graphs} \end{figure} \subsection{Loss functions} \label{sec:loss} Inspired by~\cite{outoftime}, we use \emph{contrastive loss} as the key component of the objective function. Contrastive loss enables maximization of the dissimilarity score for manipulated video sequences, while minimizing the MDS for real videos. This consequently ensures separability of the real and fake videos based on MDS (see Fig.~\ref{fig:Graphs}). The loss function is represented by Equation \ref{eq:1}. Here, $y^i$ is the label for video $v^i$ and \emph{margin} is a hyper-parameter. Dissimilarity score $d_t^i$, is the Euclidean distance between the (segment-based) feature representations $f_v$ and $f_a$ of the visual and audio streams respectively. In addition, we employ the cross-entropy loss for the visual and audio streams to learn feature representations in a robust manner. These loss functions are defined in Equations \ref{eq:3} (visual) and \ref{eq:4} (audio). The overall loss $L$ is a weighted sum of these three losses, $L_1, L_2$ and $L_3$ as in Eq.~\ref{eq:9}. \begin{equation} L_1 = \frac{1}{N} \sum_{i=1}^{N} (y^i) \ (d_t^i)^2 + (1-y^i) \ max(margin-d_t^i,0)^2 \label{eq:1} \\ \end{equation} \begin{equation} d_t^i = \|f_v - f_a\|_2 \label{eq:2} \end{equation} \begin{equation} L_2 = - \ \frac{1}{N} \sum_{i=1}^{N} y^i \ \log{\hat{y}_v^i} \ + (1-y^i) \ \log{(1-\hat{y}_v^i)} \label{eq:3} \\ \end{equation} \begin{equation} L_3 = - \ \frac{1}{N} \sum_{i=1}^{N} y^i \ \log{\hat{y}_a^i} \ + (1-y^i) \ \log{(1-\hat{y}_a^i)} \label{eq:4} \end{equation} \begin{align} L = \ \lambda_1L_1 + \lambda_2L_2 + \lambda_3L_3 \label{eq:9} \end{align} \noindent where $\lambda_1,\lambda_2, \lambda_3 =1$ in our design. \subsection{Test Inference} \label{sec:test} During test inference, the visual segments $\{s^i_1, s^i_2, ... , s^i_n\}$ and corresponding audio segments $\{a^i_1, a^i_2, ... , a^i_n\}$ of a video are passed through $S_v$ and $S_a$, respectively. For each such segment, dissimilarity score $d_t^i$ (Equation \ref{eq:2}) is accumulated to compute the MDS as below: \begin{equation} MDS_i = \frac{1}{n} \sum_{t=1}^{n} d^i_t \label{eq:5} \end{equation} \noindent To label the test video, we compare $MDS_i$ with a threshold $\tau$ using $1\{MDS_i < \tau\}$ where $1\{.\}$ denotes the logical indicator function. $\tau$ is determined on the training set. We compute MDS for both real and fake videos of the train set, and the midpoint between the average values for the real and fake videos is used as a representative value for $\tau$. \section{Experiments} \subsection{Dataset Description} As our method is multimodal, we use two public audio-visual deepfake datasets in our experiments. Their description is as follows:\\ \\ \textbf{Deepfake-TIMIT \cite{DBLP:DF-TIMIT}:} This dataset contains videos of 16 similar looking pairs of people, which are manually selected from the publicly available VIDTIMIT \cite{VID-TIMIT} database and manipulated using an open-source GAN-based\footnote{https://github.com/shaoanlu/faceswap-GAN} approach. There are two different models for generating fake videos, one Low Quality (LQ), with $64\times64$ input/output size, and the other High Quality (HQ), with $128\times128$ input/output size. Each of the 32 subjects has 10 videos, resulting in a total of 640 face swapped videos in the dataset; each video is of $512\times384$ resolution with 25 fps frame rate, and of $\approx 4s$ duration. However, the audio channel is not manipulated in any of the videos.\\ \noindent \textbf{DFDC dataset \cite{dolhansky2019deepfake}:} The preview dataset, comprising of 5214 videos was released in Oct 2019 and the complete one with 119,146 videos in Dec 2019. Details of the manipulations have not been disclosed, in order to represent the real adversarial space of facial manipulation. The manipulations can be present in either audio or visual or both of the channels. In order to bring out a fair comparison, we used 18,000 videos\footnote{Same as the videos used in \cite{mittal2020emotions}.} in our experiments. The videos are of $\approx10s$ duration each with an fps of 30, so there are $\approx300$ frames per video. \subsection{Training Parameters} For both the datasets, we used $D=1$ second segment duration and the margin hyper-parameter described in Equation \ref{eq:1} was set to 0.99. This resulted in (3 x 30 x 224 x 224) dimensional input for the visual stream in case of DFDC dataset and for the other dataset, Deepfake-TIMIT, the input dimension to the visual stream was (3 x 25 x 224 x 224). On DFDC we trained our model for 100 epochs with a batch size of 8 whereas for Deepfake-TIMIT the model only required 50 epochs with 16 batch size for convergence as the dataset size was small. We used Adam optimizer with a learning rate of 0.001 and all the results were generated on Nvidia Titan RTX GPU with 32 GB system RAM. For the evaluation, we use video-wise Area Under the Curve (AUC) metric. \begin{table*}[!tbph] \caption{Comparison of our method with other techniques on DFDC and DFTIMIT datasets using the AUC metric. For our method frame-wise results are reported inside the brackets. (*We found a discrepancy in the train-test split of the 18k samples subset of \cite{mittal2020emotions}. Hence, the results have been updated after removing the discrepancy from the test set (20$^{th}$ March, 2021).)} \label{tab:scores} \centering \scalebox{0.96}{ \begin{tabular}{|c|c|c|c|c|c|c|c|c|c|} \cline{1-10} \multirow{2}{*}{}& \multicolumn{2}{ |c| }{\multirow{2}{*}{} } & \multicolumn{7}{ |c| }{\textbf{Methods}} \\ \cline{4-10} & \multicolumn{1}{c}{}& & Capsule & Multi-task & HeadPose & Two-stream & VA-MLP & VA-LogReg & Meso4 \\ & \multicolumn{1}{c}{}& & \cite{Capsule_Forensics} & \cite{multi-task} & \cite{inconsistent_headposes} & \cite{Two-stream} & \cite{visual_artifacts} & & \cite{afchar2018mesonet} \\ \cline{1-10} \multirow{3}{*}{\textbf{Datasets}} & \multicolumn{2}{|c|}{\textbf{DFDC}} & 53.3 & 53.6 & 55.9 & 61.4 & 61.9 & 66.2 & 75.3 \\ \cline{2-10} & \multirow{2}{*}{\textbf{DFTIMIT}} & \textbf{LQ} & 78.4 & 62.2 & 55.1 & 83.5 & 61.4 & 77.0 & 87.8 \\ \cline{3-10} & & \textbf{HQ} & 74.4 & 55.3 & 53.2 & 73.5 & 62.1 & 77.3 & 68.4 \\ \cline{1-10} \textbf{Modality} & \multicolumn{2}{|c|}{} & V & V & V & V & V & V & V \\ \cline{1-10} \thickhline \multirow{2}{*}{}& \multicolumn{2}{ |c| }{\multirow{2}{*}{} } & \multicolumn{7}{ |c| }{\textbf{Methods}} \\ \cline{4-10} & \multicolumn{1}{c}{}& & Xception-raw & Xception-c40 & Xception-c23 & FWA & DSP-FWA & Siamese-based & \textbf{Our Method} \\ & \multicolumn{1}{c}{}& & \cite{rossler2019faceforensics++} & & & \cite{Li2018ExposingDVFWA} & & \cite{mittal2020emotions} & \\ \cline{1-10} \multirow{3}{*}{\textbf{Datasets}} & \multicolumn{2}{|c|}{\textbf{DFDC}} & 49.9 & 69.7 & 72.2 & 72.7 & 75.5 & \colorbox{red!30}{84.4} & \colorbox{blue!30}{\textbf{90.55 (90.66)*}} \\ \cline{2-10} & \multirow{2}{*}{\textbf{DFTIMIT}} & \textbf{LQ} & 56.7 & 75.8 & 95.9 & \colorbox{blue!30}{99.9} & \colorbox{blue!30}{99.9} & 96.3 & \colorbox{red!30}{97.9 (98.3)} \\ \cline{3-10} & & \textbf{HQ} & 54.0 & 70.5 & 94.4 & 93.2 & \colorbox{blue!30}{99.7} & 94.9 & \colorbox{red!30}{96.8 (94.7)} \\ \cline{1-10} \textbf{Modality} & \multicolumn{2}{|c|}{} & V & V & V & V & V & AV & AV \\ \cline{1-10} \end{tabular}} \end{table*} \begin{table}[b] \caption{The AUC based comparison of audio stream, visual stream, contrastive loss only and combined loss (Details in Section \ref{sec:AblationStudies}).} \label{tab:lambdas} \scalebox{0.86}{ \begin{tabular}{|c|c|c|c|} \hline \begin{tabular}[c]{@{}c@{}}$\lambda_1$=0,$\lambda_2$=0,$\lambda_3$=1\\ Audio Stream\end{tabular} & \begin{tabular}[c]{@{}c@{}}$\lambda_1$=1,$\lambda_2$=0,$\lambda_3$=0\\ Contrastive Only\end{tabular} & \begin{tabular}[c]{@{}c@{}}$\lambda_1$=0,$\lambda_2$=1,$\lambda_3$=0\\ Visual Stream\end{tabular} & \begin{tabular}[c]{@{}c@{}}$\lambda_1$=1,$\lambda_2$=1,$\lambda_3$=1\\ Combined Loss\end{tabular} \\ \hline 50.0 & 86.1 & 89.7 & 91.7 \\ \hline \end{tabular}} \end{table} \subsection{Ablation Studies} \label{sec:AblationStudies} To decide the structure of the network and effect of different components, we chose 5800 videos (4000 real and 1800 fake) from the DFDC dataset, divided them into an 85:15 train-test split, following video-wise AUC and conducted the following experiments:\\ \textbf{Effect of Loss Functions:} We evaluated the contribution of the audio and visual streams based cross-entropy loss functions ($L_2$ and $L_3$, respectively). The hypothesis behind adding these two loss functions to the network is that the feature representations learnt across the audio and visual streams, respectively will be more discriminative towards the task of deep fake detection. This should further assist in the task of computing a segment dissimilarity score $d_t^i$, which disambiguates between fake and real videos. This hypothesis was tested by training the network on the DFDC dataset in two different settings. The first setting is based on training the MDS network with contrastive loss only. The second setting is combination of the three loss functions for training of the MDS network. Figure \ref{fig:Graphs} shows two graphs generated using the MDS scores as predicted by the networks from the two settings above. It is observed that the distributions of real and fake videos have lesser intersection in the case of the network trained with all three losses. Overall, combined loss function and contrastive loss only based networks achieved 92.7\% and 86.1\% AUC scores. The difference attributes to the observation that the gap between average MDS for real and fake videos widens when cross-entropy loss functions are also used. Hence, there is more clear distinction between the dissonance scores for real and fake. \textbf{Audio and Visual Stream Performance:} We analysed the individual discriminative ability to identify fake and real videos for the audio and the visual streams. In this case the cross-entropy loss alone was used for training of the streams. It was observed that the audio stream only and visual stream only based deepfake classifiers achieved 50.0 and 89.7\%, respectively. Note that audio stream achieves less performance as in the DFDC dataset, minimal manipulation is performed on the audio signal of the videos. \begin{figure}[t] \centering \includegraphics[width=4cm,height=3.5cm]{exp_aud_loss.png}\hspace{2mm \includegraphics[width=4.1cm,height=3.5cm]{exp_vid_loss.png}\vspace{-1mm} \caption{Discriminative-ability of individual streams: The graphs show the distribution of the mean L2 distance, when a fake segment and corresponding real segment are passed through only the audio and visual streams.} \label{fig:vid_aud_plot} \end{figure} \begin{figure}[b] \centering \vspace{-2mm} \includegraphics[width=8.6cm]{Activation.png \caption{Grad-CAM results: Three frames are overlayed with the important attention regions highlighted using Grad-CAM. Note that forehead, face region and neck regions are highlighted in the 1st, 2nd and 3rd frames respectively.} \vspace{-4mm} \label{fig:GRADCAM} \end{figure} In Equation \ref{eq:5}, for the four configurations: audio stream only, contrastive loss only, visual stream only and combined loss, we set the parameters as follows: ($\lambda_1=0,\lambda_2=0,\lambda_3=1$), ($\lambda_1=1,\lambda_2=0,\lambda_3=0$), ($\lambda_1=0,\lambda_2=1,\lambda_3=0$) and ($\lambda_1=1,\lambda_2=1,\lambda_3=1$). In the case of audio stream and visual stream based classification, the cross-entropy generated real and fake probabilities are generated segment-wise. We compute a maximum over the probabilities to compute the final fake and real for these two streams, individually. For further assessing the audio and visual stream's individual performances, we generated the plots shown in Figure \ref{fig:vid_aud_plot}. The process is as follows: a fake video segment and corresponding real video segment is passed through the streams and L2 distance is computed between the output of fc8 layer of the visual/audio sub-network. Then the average of these L2 distances for a video pair is plotted. It is observed in the audio stream plot, that most of the videos are centered close to 0 inter-pair L2 distance. This is due to the fact that audio has been modified in few cases in DFDC dataset. On the contrary, in the plot for the visual stream, we observed that the inter-pair L2 scores is spread across the dataset. This supports the argument that the visual stream is more discrimiantive due to the added cross entropy loss. In Table \ref{tab:lambdas}, we show the AUC of the four configurations mentioned above. Note that these numbers are on a smaller set of DFDC, which is used for ablation studies only. The contrastive loss only based configuration, which uses both the streams, achieves 86.1\%. The fusion of the cross-entropy loss into the final MDS network ($\lambda_1=1,\lambda_2=1,\lambda_3=1$ for Equation \ref{eq:5}), achieves 92.7\%. This backs up the argument that comparing (using contrastive loss) features learned through supervised channels enhances the performance of the MDS network. \textbf{Segment Duration:} For deciding the optimal length of the temporal segment $D$, we conducted empirical analysis with temporal sizes of $D = [1,2,4]$ seconds. From the evaluation on the DFDC dataset, we observed that the temporal duration $D=1$ second is most optimum. This can attributed to the larger number of segments representing each video, thereby allowing fine-grained comparison of the audio and the visual data of a video. \subsection{Evaluation on DFDC Dataset} We compare the performance of our method on the DFDC dataset with other state-of-the-art works \cite{mittal2020emotions,Capsule_Forensics,afchar2018mesonet,rossler2019faceforensics++,visual_artifacts,in_ictu_oculi,inconsistent_headposes,Two-stream}. A total of 18,000 videos are used in this experiment\footnote{Please note that some earlier methods in Table \ref{tab:scores} are trained on DFDC preview (5000 videos), which is no longer available. }. In Table \ref{tab:scores}, it is observed that the MDS network approach outperforms the other visual-only and audio-visual based approaches by achieving 91.54\%. The performance is \textasciitilde8\% more relatively than the other audio-visual based approach \cite{mittal2020emotions}. Please note that the result 91.54\% is achieved with the test set containing 3281 videos out of which 281 videos have two subjects each. We chose the larger face and passed it through the visual stream. The performance of the network without these multiple subject videos is 93.50\%. We also report the frame-wise AUC (91.60\%) as mentioned in brackets in Table \ref{tab:scores}. This is computed by assigning each frame of a video the same label as predicted for the video by our method. We argue that the gain in performance here is due to: (a) The temporal segmentation of the video into segment helps in fine-grained audio-visual feature comparison; (b) We extract task-tuned features from the audio and visual segments. Here task-tuned means that the features are learnt to discriminate between real and fake with the $L_2$ and $L_3$ loss functions, and (c) The visual stream's input is the face and an extra margin (see Figure \ref{fig:pipeline}) around it, which accounts for some rigid (head) movement along with the non-rigid (facial) movements. We visualise the important regions using the Gradient-weighted Class Activation Mapping (Grad-CAM) method \cite{selvaraju2017grad}. Figure \ref{fig:GRADCAM} shows the important regions localised by Grad-CAM on few frames of a video. Note that the region around the face is highlighted in the middle frame. Also, the forehead and the neck regions are highlighted in the first and third frames, respectively. This supports our argument that the disharmony between the non-rigid and rigid movement is also discriminative for the visual stream to classify between real and fake videos. \subsection{Evaluation on DFTIMIT Dataset} The DeepFake-TIMIT (DFTIMIT) dataset is smaller as compared to the DFDC dataset. We trained the MDS network in two resolution settings: LQ and HQ. Table \ref{tab:scores} shows the comparison of our method with the other state-of-the-art methods. It is observed that our method achieves comparable results (LQ: 97.92\% and HQ: 96.87\%) with the top achieving method \cite{Li2018ExposingDVFWA}. In the DFTIMIT test set there are 96 videos in total. This applies that the penalty for mis-classification towards the overall AUC is high in DFTIMIT's case. It is interesting to note that our method mis-classified just 3 video samples in the HQ experiments and 2 videos in the LQ experiments. \cite{Li2018ExposingDVFWA} achieve state-of-the-art results (LQ: 99.9\% and HQ: 99.7\%) on DFTIMIT, however, achieve relatively lower AUC results (72.7\%) on the larger dataset DFDC. In comparison our method achieved 18\% more than \cite{Li2018ExposingDVFWA} on DFDC dataset. This could also mean that the DFTIMIT dataset is now saturated due to smaller size similar to the popular ImageNet dataset \cite{deng2009imagenet}. We also report the frame-wise AUC (LQ: 98.3\% and HQ: 94.7\%) for DFTIMIT as mentioned in brackets in Table \ref{tab:scores}. \begin{figure}[t] \centering \includegraphics[width=8.6cm]{localisation.png} \vspace{6mm} \includegraphics[width=8.6cm]{localisation_1.png}\vspace{-2mm} \caption{Forgery Localization results: In the two examples above, the red part of the curve is detected as fake and blue as real by our method. The segment of the video with segment wise dissimilarity above the threshold is labelled as fake and below the threshold is labelled as real. On the x-axis, we have the original segment labels and on the y-axis the segment-level dissimilarity score (Section \ref{sec:localisation}).} \label{fig:localisation} \end{figure} \subsection{Temporal Forgery Localization} \label{sec:localisation} With the advent of sophisticated forgery techniques, it is possible that an entire video or smaller portions of the video are manipulated to deceive the audience. If in case parts of the original video are corrupted, it would be useful from the FD perspective to be able to locate the timestamps corresponding to the corrupted segments. In an interesting work, Wu \textit{et al.}~\cite{wu2018busternet} proposed a CNN which detects forgery along with the forged locations in images. However, their method is only applicable to copy-paste image forgery. As we process the vidseo by dividing it into temporal segments, a fine-grained analysis of the input video is possible, thereby enabling \textit{forgery localization}. In contrast to the MDS network, earlier techniques \cite{mittal2020emotions,Li2018ExposingDVFWA} computed features over the entire video. We argue that if a forgery has been performed on a small segment of a video, the forgery signatures in that segment may get diluted due to pooling across the whole video. A similar phenomenon is also observed in prior work relating to pain detection and localization \cite{sikka2014classification}. As the pain event could be short and its location is not labeled, the authors divide the video into temporal segments for better pain detection. Most of the datasets, including the ones used in this paper have data manipulation performed on practically the entire video. To demonstrate the effectiveness of our method for forgery localization in fake videos, we joined segments from real and corresponding fake videos of the same subject at random locations. In Figure \ref{fig:localisation}, we show the outputs on two videos created by mixing video segments of the same subject from the DFDC dataset. Here, the segment-wise score is shown on the $y$-axis. The segments for which the score is above a threshold are assigned as being fake (red on the curve) and below the threshold (blue color on the curve) are assigned are real. In addition to Figs.~\ref{fig:GRADCAM} and~\ref{fig:Graphs}, forgery localization makes the working of the MDS-based fake detection framework more \emph{explainable} and \emph{interpretable}. \section{Conclusion and Future Work} We propose a novel bimodal deepfake detection approach based on the modality dissonance score (MDS), which captures the similarity between audio and visual streams for real and fake videos thereby facilitating separability. The MDS is modeled via the contrastive loss computed over segment-level audiovisual features, which constrains genuine audio-visual streams to be \textit{closer} than fake counterparts. Furthermore, cross-entropy loss is enforced on the unimodal streams to ensure that they independently learn discriminative features. Experiments show that (a) the MDS-based FD framework can achieve state-of-the-art performance on the DFDC dataset, and (b) the unimodal cross-entropy losses provide extra benefit on top of the contrastive loss to enhance FD performance. Explainability and interpretability of the proposed approach are demonstrated via audio-visual distance distributions obtained for \emph{real} and \emph{fake} videos, Grad-CAM outputs denoting attention regions of the MDS network, and forgery localization results. Future work would focus on (a) incorporating human assessments (acquired via EEG and eye-gaze sensing) in addition to content analysis adopted in this work; (b) exploring algorithms such as multiple instance learning for transient forgery detection, and (c) achieving real-time forgery detection (accomplished by online intrusions) given the promise of processing audio-visual information over 1-second segments. \section{Acknowledgement} We are grateful to all the brave frontline workers who are working hard during this difficult COVID19 situation. \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2021-03-23T01:11:59', 'yymm': '2005', 'arxiv_id': '2005.14405', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14405'}
arxiv
\subsection{Deriving repair rules from short-cut rules} Having defined short-cut rules, they can be operationalized to get edit rules for source graphs and forward rules that repair these edits. As such edits may delete source elements, correspondence elements may be left without corresponding source elements. Hence, the resulting triple graphs show a form of partiality. They are called \emph{partial triple graphs}. Given a model, formally considered as triple graph $G_S \xleftarrow{\sigma_G} G_C \xrightarrow{\tau_G} G_T$, a user edit on $G_S$ may consist of the deletion and/or creation of graph elements, resulting in a graph $G_S^{\prime}$. In general, the \enquote{old} correspondence morphism $\sigma_G: G_C \to G_S$ does not extend to a correspondence morphism from $G_C$ to $G_S^{\prime}$: The user might have deleted elements in the image of $\sigma_G$. However, there is a \emph{partial morphism} $\sigma_G^{\prime}: G_C \dashrightarrow G_S^{\prime}$ that is defined for all elements whose image under $\sigma_G$ still exists. \begin{definition}[Partial triple graph] A \emph{partial graph morphism} $f: A \dashrightarrow B$ is a graph morphism $f: A^{\prime} \to B$ where $A^{\prime}$ is a subgraph of $A$; $A^{\prime}$ is called the \emph{domain} of $f$. A \emph{partial triple graph} $G^{\prime} = G_S^{\prime} \xdashleftarrow{\sigma_G^{\prime}} G_C^{\prime} \xdashrightarrow{\tau_G^{\prime}} G_T^{\prime}$ consists of three graphs $G_S^{\prime},G_C^{\prime},G_T^{\prime}$ and two partial graph morphisms $\sigma_G^{\prime}: G_C^{\prime} \dasharrow G_S^{\prime}$ and $\tau_G^{\prime}: G_C^{\prime} \dasharrow G_T^{\prime}$. Given a triple graph $G = (G_S \xleftarrow{\sigma_G} G_C \xrightarrow{\tau_G} G_T)$ and a user edit of $G_S$ that results in a graph $G_S^{\prime}$, the \emph{partial triple graph induced by the edit} is $G_S^{\prime} \xdashleftarrow{\sigma_G^{\prime}} G_C \xrightarrow{\tau_G} G_T$ where $\sigma_G^{\prime}$ is obtained by restricting $\sigma_G$ to those elements $x$ of $G_C$ (node or edge) for which $\sigma_G(x) \in G_S$ is still an element of $G_S^{\prime}$. \end{definition} According to the above definition, triple graphs are special partial triple graphs, namely those, where the domain of both partial correspondence morphisms is the whole correspondence graph $G_C$. When operationalizing short-cut rules, i.e., splitting them into a \emph{source} and a \emph{forward rule}, we also have to deal with this kind of partiality: In contrast to the rules of a given TGG, a short-cut rule might delete an element. Hence, its forward rule might need to contain a correspondence element for which the corresponding source element is missing; it is referenced in the short-cut rule. This element is deleted by the corresponding source rule. \begin{definition}[Source and forward rule of short-cut rule. Repair rule] Given a pair $(r_1,r_2)$ of plain, monotonic triple rules with short-cut rule $r_{\mathit{sc}} = (L_{\mathit{sc}} \xleftarrow{l_{\mathit{sc}}} K_{\mathit{sc}} \xrightarrow{r_{\mathit{sc}}} R_{\mathit{sc}})$, the \emph{source} and \emph{forward rule} of $r_{\mathit{sc}}$ are defined as \begin{equation*} r_{\mathit{sc}}^S \coloneqq (L_{\mathit{sc}}^S \xleftarrow{(l_{\mathit{sc},S}, \mathit{id}_{\emptyset}, \mathit{id}_{\emptyset})} K_{\mathit{sc}}^S \xrightarrow{(r_{\mathit{sc},S}, \mathit{id}_{\emptyset}, \mathit{id}_{\emptyset})} R_{\mathit{sc}}^S) \end{equation*} and \begin{equation*} r_{\mathit{sc}}^F \coloneqq (L_{\mathit{sc}}^F \xleftarrow{(id_{R_{\mathit{sc},S}}, l_{\mathit{sc},C}, l_{\mathit{sc},T})} K_{\mathit{sc}}^F \xrightarrow{(id_{R_{\mathit{sc},S}}, r_{\mathit{sc},C}, r_{\mathit{sc},T})} R_{\mathit{sc}}^F) \end{equation*} where \begin{align*} L_{\mathit{sc}}^S & \coloneqq (L_{\mathit{sc},S} \leftarrow \emptyset \rightarrow \emptyset), \\ K_{\mathit{sc}}^S & \coloneqq (K_{\mathit{sc},S} \leftarrow \emptyset \rightarrow \emptyset), \\ R_{\mathit{sc}}^S & \coloneqq (R_{\mathit{sc},S} \leftarrow \emptyset \rightarrow \emptyset), \\ L_{\mathit{sc}}^F & \coloneqq (R_{\mathit{sc},S} \dashleftarrow L_{\mathit{sc},C} \rightarrow L_{\mathit{sc},T}), \\ K_{\mathit{sc}}^F & \coloneqq (R_{\mathit{sc},S} \leftarrow K_{\mathit{sc},C} \rightarrow K_{\mathit{sc},T}), \text{ and } \\ R_{\mathit{sc}}^F & \coloneqq (R_{\mathit{sc},S} \leftarrow R_{\mathit{sc},C} \rightarrow R_{\mathit{sc},T}) \enspace . \end{align*} Given a TGG $\mathit{GG}$, a \emph{repair rule for $\mathit{GG}$} is the forward rule $r_{\mathit{sc}}^F$ of a short-cut rule $r_{\mathit{sc}}$ where $r_{\mathit{sc}}$ has been constructed from a pair of rules of $\mathit{GG}$. \end{definition} For more details (in particular, the definition of morphisms between partial triple graphs), we refer the interested reader to the literature~\cite{FKST19,KFST19}. In this paper, we are more interested in conveying the intuition behind these rules by presenting examples. We next recall the most important property of this operationalization, namely that, as in the monotonic case, an application of a short-cut rule corresponds to the application of its source rule, followed by an application of the forward rule if consistently matched. \begin{theorem}[{\cite[Theorem~7]{FKST19} and \cite[Theorem~23]{KFST19}}]\label{thm:equivalence} Given a short-cut rule $r_{\mathit{sc}}$, there is a transformation \begin{equation*} (G_S \leftarrow G_C \rightarrow G_T) \Rightarrow_{r_{\mathit{sc}},m_{\mathit{sc}}} (H_S \leftarrow H_C \rightarrow H_T) \end{equation*} via this short-cut rule if and only if there is a transformation \begin{align*} (G_S \leftarrow G_C \rightarrow G_T) & \Rightarrow_{r_{\mathit{sc}}^S,m_{\mathit{sc}}^S} (H_S \dashleftarrow G_C \rightarrow G_T) \\ & \Rightarrow_{r_{\mathit{sc}}^F,m_{\mathit{sc}}^F} (H_S \leftarrow H_C \rightarrow H_T) \end{align*} applying source rule $r_{\mathit{sc}}^S$ with match $m_{\mathit{sc}}^S = (m_{\mathit{sc},S},\emptyset,\emptyset)$ and forward rule $r_{\mathit{sc}}^F$ at match $m_{\mathit{sc}}^F = (n_{\mathit{sc},S},m_{\mathit{sc},C},m_{\mathit{sc},T})$. \end{theorem} For practical applications, repair rules should also be equipped with filter NACs. Let the repair rule $r_{\mathit{sc}}^F$ be obtained from a short-cut rule $r_{\mathit{sc}}$ that has been computed from rule pair $(r_1, r_2)$, both coming from a given TGG. As the application of $r_{\mathit{sc}}^F$ replaces an application of $r_1^F$ by one of $r_2^F$, $r_{\mathit{sc}}^F$ should be equipped with the filter NAC of $r_2^F$. However, just copying that filter NAC would not preserve its semantics; a more refined procedure is needed. The LHS of $r_2^F$ is a subgraph of the one of $r_{\mathit{sc}}^F$ by construction. There is a known procedure, called \emph{shift along a morphism}, that \enquote{moves} an application condition from a subgraph to the supergraph preserving its semantics~\cite[Lemma~3.11 and Construction~3.12]{EGHLO14}. We use this construction to compute the filter NACs of repair rules. By using this known construction, the filter NACs we construct for our repair rules have the following property: \begin{lemma}[{\cite[Lemma~3.11 and Construction~3.12]{EGHLO14}.}]\label{lem:property-filter-NACs} Let $r_{\mathit{sc}}$ be a plain short-cut rule obtained from the pair of monotonic rules $(r_1,r_2)$ where the forward rule $r_2^F$ is equipped with a set $\mathit{NAC}_2^F$ of filter NACs. Let $\mathit{NAC}_{\mathit{sc}}^F$ be the set of NACs computed by applying the shift construction to $\mathit{NAC}_2^F$ along the inclusion morphism $\iota: L_2^F \hookrightarrow L_{\mathit{sc}}^F$ of the LHS of $r_2^F$ into the LHS of $r_{\mathit{sc}}$ (which exists by construction). Then, an injective match $m_{\mathit{sc}}^F$ for $r_{\mathit{sc}}^F$ (into any partial triple graph $G$) satisfies the set of NACs $\mathit{NAC}_{\mathit{sc}}^F$ if and only if the induced injective match $m_{\mathit{sc}}^F \circ \iota$ for $r_2^F$ satisfies $\mathit{NAC}_2^F$. \end{lemma} \begin{example} The forward rules of the short-cut rules in Fig.~\ref{fig:scRules} are depicted in Fig.~\ref{fig:fwdSCRules}. \secondRRule{} is derived to replace an application of \secondTGGForwardRule{} by one of \firstTGGForwardRule{}. This forward rule is equipped with a filter NAC which ensures that the rule is used only to translate \packages{} at the top of a hierarchy. Just copying this NAC to the \package{} \p{} in \secondRRule{} would not preserve this behaviour: The rule would be applicable in situations where the \package{} to which \ssp{} is matched contains a \package{} to which \p{} is matched. Shifting the NAC from \firstTGGForwardRule{} to \secondRRule{} instead, the forbidden edge between the two \packages{} is introduced in addition. It ensures that \p{} can be matched to \packages{} at the top of a hierarchy, only. \fourthRRule{} (see Figure~\ref{fig:fourth-repair-rule}) assumes two connected \packages{} and deletes a \folder{} between their corresponding \folders{} as well as the \doc{} contained in the deleted \folder{} and the correspondence node referencing it. The LHS of this rule is a proper partial triple graph as there is a correspondence node which is not mapped to any element of the source part. \begin{figure}% \includegraphics[width=\columnwidth]{Diagram/OSCRules_4.pdf}% \caption{Repair rule derived from \fourthSCRule{}}% \label{fig:fourth-repair-rule}% \end{figure} \end{example} \subsection{Conditions for valid repair rule applications} Now, we transfer the results obtained so far to the case of repair rules. To do so, we first define \emph{valid matches} for repair rules (in a restricted kind of transformation sequences). \begin{definition}[Valid match for repair rule]\label{def:valid-repair-match} Let a TGG $\mathit{GG}$ and a consistently-marking transformation sequence \begin{equation}\label{eq:orig-trafo} G_0 \Rightarrow_{r_1^{\mathit{FN}},m_1^F} G_1 \Rightarrow_{r_2^{\mathit{FN}},m_2^F} \dots \Rightarrow_{r_t^{\mathit{FN}},m_t^F} G_t \end{equation} via forward rules $r_i^{\mathit{FN}},\ 1 \leq i \leq t$, (possibly with filter NACs) of $\mathit{GG}$ be given. Let \begin{equation*} G_i = (G_{0,S} \leftarrow G_{i,C} \rightarrow G_{i,T}) \enspace . \end{equation*} Let there be some source edit step \begin{equation*} G_t \Rightarrow_{r_{\mathit{sc}}^S,m_{\mathit{sc}}^S} G^\prime \end{equation*} where $G^\prime = (H_S \dashleftarrow G_{t,C} \rightarrow G_{t,T})$, $r_{\mathit{sc}}$ is a source rule of a short-cut rule derived from a rule pair $(r_j,r)$ where $1 \leq j \leq t$ and $r$ stems from $\mathit{GG}$, and $m_{\mathit{sc}}^S|_{R_{j,S}} = n_{j,S}$, i.e., when restricted to the source part of the RHS $R_j$ of $r_j$ match $m_{\mathit{sc}}^S$ coincides with the source part of the comatch $n_j$. Moreover, the application of this source edit shall not introduce a violation of any of the filter NACs of $r_1^{\mathit{FN}}, \dots, r_{j-1}^{\mathit{FN}}$. Then, a match $m_{\mathit{sc}}^F$ for the corresponding forward rule $r_{\mathit{sc}}^F$ in $G^\prime$ is \emph{valid} if the following properties hold. \begin{enumerate} \item \emph{Reversing match:} Given comatch $(n_{\mathit{sc},S}^S,\emptyset,\emptyset)$ of the application of the source rule $r_{\mathit{sc}}^S$, its match is \begin{equation*} m_{\mathit{sc}}^F = (n_{\mathit{sc},S}^S,m_{\mathit{sc,C}}^F,m_{\mathit{sc,T}}^F) \end{equation*} and also $m_{\mathit{sc,C}}^F$ and $m_{\mathit{sc,T}}^F$ coincide with $n_{j,C}$ and $n_{j,T}$ when restricted to $R_{j,C}$ and $R_{j,T}$, respectively. \item \emph{Sequential independence:} \begin{enumerate} \item \emph{Non-disabling match:} The application of $r_{\mathit{sc}}^F$ does not delete elements used in the applications of $r_{j+1}^{\mathit{FN}}, \dots, r_{t}^{\mathit{FN}}$ nor does it create elements forbidden by one of the filter NACs of those forward rules. \item \emph{Context-preserving match:} The presumed elements of the repair rule $r_{\mathit{sc}}^F$ (which accord to the presumed elements of the short-cut rule $r_{\mathit{sc}}$) are matched to elements of $H_S$ which are marked as translated in $G_{j-1,S}$ and in $G_{t,C}$ and $G_{t,T}$ to elements which are already created in $G_{j-1,C}$ and $G_{j-1,T}$. This means, elements stemming from the LHS $L$ of $r$ which have not been identified with elements from $L_j$ in the short-cut rule $r_{\mathit{sc}}$, are matched to elements already translated/existing in $G_{j-1}$. \end{enumerate} \item \emph{Creation-preserving match:} All source elements that are newly created by short-cut rule $r_{\mathit{sc}}$, i.e., the source elements of $R_S \setminus L_S$ that have not been merged with an element of $R_{j,S} \setminus L_{j,S}$ during the short-cut rule construction, are matched to elements which are yet untranslated in $G_{t,S}$. \end{enumerate} \end{definition} Note that together, conditions 2. (a) and (b) above constitute sequential independence between the applications of $r_{j+1}^{\mathit{FN}}, \dots, r_{t}^{\mathit{FN}}$ and the one of $r_{\mathit{sc}}^{\mathit{F}}$. Moreover, the additional requirement on the match to be creation preserving (compared to Theorem~\ref{thm:valid-applications} for short-cut rules) originates from the fact that forward rules do not create but mark source elements. The following corollary uses Theorem~\ref{thm:equivalence} to transfer the statement of Theorem~\ref{thm:valid-applications} to repair rules. \begin{corollary}\label{cor:valid-repair-rule-applications} Let a TGG $\mathit{GG}$ and a consistently marking transformation sequence as in~(\ref{eq:orig-trafo}), followed by an edit step exactly as in Definition~\ref{def:valid-repair-match} above be given. Then, applying $r_{\mathit{sc}}^F$ at a \emph{valid match} $m_{\mathit{sc}}^F$ in $G^{\prime}$ induces a \emph{consistently marking transformation sequence} \begin{equation}\label{eq:induced-trafo} \begin{split} G_0^{\prime} \Rightarrow_{r_1^{\mathit{FN}},m_1^F} G_1^{\prime} \Rightarrow_{r_2^{\mathit{FN}},m_2^F} \dots & \Rightarrow_{r_{j-1}^{\mathit{FN}},m_{j-1}^F} G_{j-1}^{\prime} \\ & \Rightarrow_{r^{\mathit{FN}},m^F} X \end{split} \end{equation} with $G_i^{\prime} = (H_S \dashleftarrow G_{i,C} \rightarrow G_{i,T})$ for $0 \leq i \leq j-1$. \end{corollary} \begin{proof} For a valid match $m_{\mathit{sc}}^F$ of $r_{\mathit{sc}}^F$, by its \emph{reversing property}, the conditions of Theorem~\ref{thm:equivalence} are met. Hence, we obtain a sequence \begin{equation*} G_0 \Rightarrow_{r_1^{\mathit{FN}},m_1^F} \dots \Rightarrow_{r_t^{\mathit{FN}},m_t^F} G_t \Rightarrow_{r_{\mathit{sc}},m_{\mathit{sc}}} X^\prime \enspace . \end{equation*} As a consistently marking sequence of forward rules corresponds to a sequence of TGG rule applications, and the preconditions of Theorem~\ref{thm:valid-applications} are met (\enquote{exists} is exchanged by \enquote{marked} on the source component), this sequence induces a sequence \begin{equation*} G_0 \Rightarrow_{r_1^{\mathit{FN}},m_1^F} \dots \Rightarrow_{r_{j-1}^{\mathit{FN}},m_{j-1}^F} G_{j-1} \Rightarrow_{r,m} X \end{equation*} (where we do not care for the further applications of forward rules). Now, we can split $r$ into its source and forward rule. Its source rule is sequentially independent from the other forward rule applications: $r_{\mathit{sc}}^S$ does not delete anything, the rules $r_1^{\mathit{FN}}, \dots, r_{j-1}^{\mathit{FN}}$ match, and does not create a filter NAC violation by assumption and, as a consequence, $r^S$ does not. Hence, by the local Church-Rosser Theorem, we might equivalently switch the application of $r^S$ to the beginning of the sequence and obtain sequence~(\ref{eq:induced-trafo}), as desired. Moreover, by Lemma~\ref{lem:property-filter-NACs}, the filter NAC of $r^F$ holds whenever $m_{\mathit{sc}}^F$ satisfies the filter NAC of $r_{\mathit{sc}}^F$. Finally, as the start of the transformation sequence (up to index $j-1$) is context preserving, and by assumption 2. (b), the match $m_{\mathit{sc}}^F$ matches presumed elements of $r_{\mathit{sc}}^F$ to already translated ones (in $H_S$) or already created ones (in $G_{j-1,C}$ and $G_{j-1,T}$), this sequence is context preserving. Analogously, assumption 3. ensures that it is creation-preserving: No element which is already marked as translated in $G_{t,S}$ is marked a second time. Hence, the whole sequence is consistently marking. \qed \end{proof} \subsection{Performance Evaluation} To get realistic models, we extracted five models from Java projects hosted on Github using the reverse engineering tool MoDisco~\cite{HB14} and translated them into our own documentation structure. In addition, we generated five synthetic models consisting of $n$-level \package{} hierarchies with each non-leaf \package{} containing five sub-\packages{} and each leaf \package{} containing five \classes{}. While the realistic models shall show that our approach scales to real world cases, the synthetic models are chosen to show scalability in a more controlled way by increasing hierarchies gradually. To evaluate our synchronization process, we performed several model changes. We refactored each of the models in four different scenarios; two example refactorings are the moving of a \class{} from one \package{} to another or the complete relocation of a \package{}. Then we used eMoflon to synchronize these changes in order to restore consistency to the documentation model using two synchronization processes, namely with and without \repairRules{}. The legacy synchronization process of eMoflon is presented in~\cite{LAFVS17,Leblebici18}; the new synchronization process applying additional repair rules takes place according to the algorithm presented in Sect.~\ref{sec:syncProcess} with the extensions mentioned in Sect.~\ref{sec:prospect}. These synchronization steps are subject to our evaluation and we pose the following research questions: \textbf{(RQ1)} {\em For different kinds of model changes, how many elements can be preserved that would be deleted and recreated otherwise?} \textbf{(RQ2)} {\em How does our new synchronization process affect the runtime performance?} \textbf{(RQ3)} {\em Are there specific scenarios in which our new synchronization process performs especially good or bad?} In the following, we evaluate our new {\em synchronization process by repair rules} against the {\em legacy synchronization process} in eMoflon. While the legacy one revokes forward rule applications and re-propagates the source model using forward rules, our new one prefers to apply short-cut repair rules as far as possible and falls back to revoking and re-propagation if there is no possible repair rule application. To evaluate the performance of the legacy and the new model synchronization processes, we consider the following synchronization scenarios: Altering a root \package{} by creating a new \package{} as root would imply that many rule applications have to be reverted to synchronize the changes correctly with the legacy synchronization process (Scenario 1). In contrast, our new approach might perform poorly when a model change does not inflict a large cascade of invalid rule applications. Hence, we move \classes{} between \packages{} (Scenario 3) and \methods{} between \classes{} (Scenario 4) to measure if the effort of applying \repairRules{} does infer a performance loss when both, the new and old algorithm, do not have to repair many broken rule applications. Note that Scenario 4 extends our evaluation presented in \cite{FKST19} as it provides a more fine-granular scenario. Finally, we simulate a scenario which is somewhat between the first three by relocating leaf \packages{} (Scenario 2) which, using the legacy model synchronization, would lead to a re-translation of all underlying elements. \begin{table*} \centering \caption{Legacy synchronizer -- Time in sec. and number of created elements} \label{tbl:measurements_legacy} \begin{tabular}{@{}l@{\hskip 7.5pt}*{15}{l}@{}} \toprule & \multicolumn{2}{c}{Both} & \phantom{a} & \multicolumn{11}{c}{Legacy Synchronization} \\ \cmidrule{2-3} \cmidrule{5-15} & \multicolumn{2}{c}{Trans.} & \phantom{i} & \multicolumn{2}{c}{Scen. 1} & \phantom{i} & \multicolumn{2}{c}{Scen. 2} & \phantom{i} & \multicolumn{2}{c}{Scen. 3} & \phantom{i} & \multicolumn{2}{c}{Scen. 4}\\ \cmidrule{2-3} \cmidrule{5-6} \cmidrule{8-9} \cmidrule{11-12} \cmidrule{14-15} Models & Sec & Elts & & Sec & Elts & & Sec & Elts & & Sec & Elts & & Sec & Elts \\ \midrule lang.List & 0.3 & 25 & & 0.2 & 20 & & -- & -- & & 0.06 & 5 & & 0.04 & 3 \\ tgg.core & 6.4 & 1.6k & & 39 & 1.6k & & 3.8 & 99 & & 0.64 & 17 & & 0.2 & 3 \\ modisco.java & 9.9 & 3.2k & & 228 & 3.3k & & 18.6 & 192 & & 3.6 & 33 & & 0.4 & 4 \\ eclipse.compare & 10.74 & 3.8k & & 83 & 3.7k & & 3.1 & 76 & & 2.36 & 47 & & 0.1 & 1 \\ eclipse.graphiti & 20.7 & 6.5k & & 704 & 6.5k & & 63.9 & 490 & & 5.65 & 25 & & 0.9 & 3 \\ \midrule synthetic $n=1$ & 0.6 & 89 & & 0.5 & 84 & & 0.2 & 21 & & 0.07 & 5 & & 0.03 & 1 \\ synthetic $n=2$ & 1.4 & 345 & & 1.7 & 340 & & 0.2 & 21 & & 0.11 & 5 & & 0.04 & 1 \\ synthetic $n=3$ & 3.5 & 1369 & & 13.2 & 1364 & & 0.3 & 21 & & 0.11 & 5 & & 0.07 & 1 \\ synthetic $n=4$ & 14.5 & 5.5k & & 141.5 & 5.5k & & 1 & 21 & & 0.32 & 5 & & 0.09 & 1 \\ synthetic $n=5$ & 58.5 & 22k & & 2863 & 22k & & 10.7 & 21 & & 1.07 & 5 & & 0.23 & 1 \\ \bottomrule \end{tabular} \end{table*} \begin{table*} \centering \caption{New synchronizer -- Time in sec. and number of created elements} \label{tbl:measurements_sc} \begin{tabular}{@{}lllllllllllll@{}} \toprule & \multicolumn{11}{c}{Synchronization by Repair Rules} \\ \cmidrule{2-12} & \multicolumn{2}{c}{Scen. 1} & \phantom{i} & \multicolumn{2}{c}{Scen. 2} & \phantom{i} & \multicolumn{2}{c}{Scen. 3} & \phantom{i} & \multicolumn{2}{c}{Scen. 4}\\ \cmidrule{2-3} \cmidrule{5-6} \cmidrule{8-9} \cmidrule{11-12} Models & Sec & Elts & & Sec & Elts & & Sec & Elts & & Sec & Elts \\ \midrule lang.List & 0.2 & 0 & & -- & -- & & 0.03 & 0 & & 0.02 & 0 \\ tgg.core & 0.8 & 0 & & 0.11 & 0 & & 0.05 & 0 & & 0.04 & 0 \\ modisco.java & 2.5 & 0 & & 0.2 & 0 & & 0.09 & 0 & & 0.1 & 0 \\ eclipse.compare & 0.7 & 0 & & 0.08 & 0 & & 0.04 & 0 & & 0.03 & 0 \\ eclipse.graphiti & 6.1 & 0 & & 0.21 & 0 & & 0.09 & 0 & & 0.1 & 0 \\ \midrule synthetic $n=1$ & 0.1 & 0 & & 0.05 & 0 & & 0.03 & 0 & & 0.05 & 0 \\ synthetic $n=2$ & 0.1 & 0 & & 0.05 & 0 & & 0.02 & 0 & & 0.04 & 0 \\ synthetic $n=3$ & 0.1 & 0 & & 0.07 & 0 & & 0.02 & 0 & & 0.04 & 0 \\ synthetic $n=4$ & 0.4 & 0 & & 0.14 & 0 & & 0.04 & 0 & & 0.04 & 0 \\ synthetic $n=5$ & 1.5 & 0 & & 0.37 & 0 & & 0.09 & 0 & & 0.06 & 0 \\ \bottomrule \end{tabular} \end{table*} Tables~\ref{tbl:measurements_legacy} and \ref{tbl:measurements_sc} depict the measured time in seconds (Sec) and the number of re-/created elements (Elts) in each scenario (1)--(4). The first table additionally shows measurements for the initial translation (Trans.) of the Java AST model into the documentation structure. For each scenario, Table~\ref{tbl:measurements_legacy} shows the numbers of synchronization steps using the legacy synchronizer without \repairRules{} while Table~\ref{tbl:measurements_sc} reflects the numbers of our new synchronizer with \repairRules{}. W.r.t. our research questions stated above, we interpret these tables as follows: The Elts columns of Table~\ref{tbl:measurements_sc} show clearly that using repair rules preserves all those elements in our scenarios that are deleted and recreated by the legacy algorithm otherwise as shown in Table~\ref{tbl:measurements_legacy} \textbf{(RQ1)}. The runtime shows a significant performance gain for Scenario~1 including a worst-case model change in which the legacy algorithm has to re-translate all elements \textbf{(RQ2)}. {\em Repair rules} do not introduce an overhead compared to the legacy algorithm as can be seen for the synthetic time measurements in Scenario 4 where only one rule application has to be repaired or reapplied \textbf{(RQ2)}. Our new approach excels when the cascade of invalidated rule applications is long. Even if this is not the case, it does not introduce any measurable overhead compared to the legacy algorithm as shown in Scenarios 2, 3, and 4 (\textbf{RQ3}). \paragraph{Threats to validity.} Our evaluation is based on five real world and five synthetic models. Of course, there exists a wide range of Java projects that differ significantly from each other w.r.t. their size, purpose, and developer style. Thus, the results may not be transferable to other projects. Nonetheless, we argue that the four larger models extracted from Github projects are representative since they are deduced from established tools of the Eclipse ecosystem. The synthetic models are also representative as they show the scalability of our approach in a more controlled environment with an increasing scaling factor. Together, realistic and synthetic models show that our approach does not only increase the performance of eMoflons synchronization process but also reduce the amount of re-created elements. Since each re-created element may contain information that would be lost during the process, we preserve this information and increase the overall quality of eMoflons synchronization results. In this evaluation, we selected four edit operations that are representative w.r.t. their dependency on other edit operations. They may not be representative w.r.t. other aspects such as size or kind of change. We consider those aspects to be of minor importance in this context as dependency is the cause for deleting and recreating elements in the legacy synchronization process. Finally, we limited our evaluation to one TGG rule set only as we experienced similar results for a broader range of TGGs from the eMoflon test zoo\footnote{Accessible via \url{https://github.com/eMoflon/emoflon-ibex-tests}}. \subsection{Refactorings} \label{sec:refactorings} As explained in Sect.~\ref{sec:implementation}, we currently employ two different strategies to overlap two rules and to create a short-cut rule. We pose the following research question: \textbf{(RQ4)} {\em Are the generated \shortcutRules{} applicable to realistic scenarios? Are further \shortcutRules{} necessary?} Since our example addresses code changes that are incorporated by the Java AST model primarily, we relate our approach to available code refactorings. In the following, we refer to the book on code refactorings written by Martin Fowler~\cite{Fowler2018} which presents 66 refactorings. Our example TGG, depicted in Fig.~\ref{fig:eval_rule_set_full}, defines consistency on a structural level solely, without incorporating behaviour, i.e., the bodies of methods and constructors. Hence, we selected those refactorings that describe changes on \packages{}, \classes{} and \interfaces{}, {\em MethodDeclarations} and \parameters{}, and \fields{}. The result is a set of 16 refactorings for which we evaluated if \shortcutRules{} help to directly propagate the corresponding change of the AST model or deletion and recreation has to take place. \begin{figure*} \centering \includegraphics[width=.9\textwidth]{Diagram/Refactorings.pdf} \caption{Refactorings} \label{fig:refactoring} \end{figure*} Fig.~\ref{fig:refactoring} lists these refactorings together with information on the TGG rules and/or \shortcutRules{} that are applicable in these scenarios. For some of the refactorings as e.g., {\em Extract Class} and \emph{Push-Down Field}, we identified situations where not only \shortcutRules{} are necessary to propagate the changes. In these cases, new elements may be created which can be propagated using operationalized TGG rules. The deletion of elements can be propagated by revoking the corresponding prior propagation step. However, many refactorings benefit from using \shortcutRules{}, for example, those that move methods and fields. If recreation of documentation on the target part is necessary, it can lead to information loss as there may not be all the necessary information in the Java AST model. \textit{Example:} \emph{Push-Up Field} moves and merges a similar field from various subclasses into a common superclass. If one of the subclass fields is moved to the superclass, we can propagate this change using \emph{Move-Field-Repair-Rule}, which is depicted in Fig.~\ref{fig:move_field_rule}. \begin{figure} \includegraphics[width=\columnwidth]{Diagram/Move-Field.pdf} \caption{Move-Field-Repair-Rule} \label{fig:move_field_rule} \end{figure} In summary, we are able to solve all 16 refactorings using a combination of (inverse) TGG rules and our generated \shortcutRules{} \textbf{(RQ4)}. \paragraph{Threats to validity.} Note that \shortcutRules{} are especially useful when elements are moved instead of deleting and recreating them in some other location. Those changes are hard to detect and are not covered here. Refactorings such as {\em Push-Up Method}, which moves a method that occurs in several subclasses to their common superclass, can be done in two different ways. First, one of the methods is moved to the superclass while the methods in the other subclasses are deleted. This employs the use of \shortcutRules{} for the moved method followed by revocation steps for the deleted methods to delete the corresponding documentation elements. Second, all methods may be deleted and a new similar method is created in the superclass. In that case, there is no \shortcutRule{} that helps to preserve information and all propagated documentation elements for the method will be blank. Hence, our approach depends on the kind of change. In particular, it helps when user edits also try to preserve information instead of recreating them. In addition, we have not incorporated behaviour in our example; such an extension of our TGG may be considered in future work. However, we can argue that most of those refactorings can be reduced to the movement of elements, the deletion of superfluous elements and the creation of new elements. These changes are manageable in general using a sequence of \shortcutRule{} and (inverse) operationalized TGG rule applications. Finally, we evaluated these cases by hand based on the generated \shortcutRules{} from our implementation. Test cases implementing the identified refactorings and combinations of them will be accessible via eMoflons test zoo. \subsection{Tool architecture} Figure~\ref{fig:architecture} depicts a UML component diagram to show the main components of eMoflon's bidirectional transformation engine. The architecture has two main components: \textit{TGG Core} contains the core components of eMoflon and \textit{Repair Framework} adds (short-cut) repair rules to eMoflon\rq{}s functionality. The \emph{TGG engine} manages the synchronization process and alters source, target, and correspondence model in order to restore consistency. For this purpose, it applies for\-ward/ back\-ward \textit{operationalized TGG rules} to translate elements or revokes broken rule applications. Finding matches in an incremental way is an important requirement for efficient model synchronization since minor model changes should be detectable without re-evaluating the whole model. For this reason, eMoflon relies on \textit{incremental pattern matching} to detect the appearance of new matches as well as the disappearance of formerly detected ones. It uses different incremental pattern matchers such as Democles~\cite{VD13} and HiPE~\cite{hipe} and allows to switch freely between them for optimizing the performance for each transformation scenario. Furthermore, eMoflon employs the use of various \textit{integer linear programming} (ILP) solvers such as Gurobi~\cite{Gurobi16} and CPLEX~\cite{CPLEX}, e.g., in order to find correspondence links (mappings) between source and target models, which is referred to as consistency check~\cite{leblebici2017inter}. We have extended this basic setup by introducing the \emph{Repair Framework}, which consists of the \emph{Repair Strategy} and the \emph{Shortcut Rule Creator}. The \emph{Repair Strategy} is attached to the \textit{TGG Engine} from which it is called with a set of broken rule matches. It attempts to repair the corresponding rule applications by using repair rules created by the \emph{Shortcut Rule Creator}, which uses the ILP interface provided by the \emph{TGG Core} in order to find overlaps between TGG rules and finally, to create short-cut repair rules. For invoking the repair rules, however, we have to find matches of repair rules. This is done by a \textit{Batch (local-search) Pattern Matcher} which, in contrast to the incremental pattern matcher, does not perform any book-keeping. As a repair of a rule application is always done locally, the checking of matches throughout the whole model is considered to be too expensive and thus, a \emph{Batch Pattern Matcher} can perform this task more efficiently. \subsection{ILP-based short-cut rule creation} \label{sec:sc-rule-creation} In order to create an overlap between two rules, a morphism between the graphs of both rules has to be found: Each element may only be mapped once; a context element may only be mapped to another context element. Created elements are mapped to each other, respectively. Furthermore, a node can only be mapped to a node of the same type as we do not incorporate inheritance between types yet. Edges are allowed to be mapped to each other only if their corresponding source and target elements are also mapped to each other, respectively. We use integer linear programming (ILP) to encode the search space of all possible mappings and search for a maximal mapping. Each possible mapping $m$ is considered to be a variable of our ILP problem such that calculating \begin{equation*} max (\sum_{m \in M} m) \end{equation*} yields the maximal overlap, with $ M $ being the set of all mappings and $ m \in \{0, 1\} $. To ensure that each element $e$ is mapped only once, we define a constraint to exclude non-used mappings: $ (\sum_{m \in A_e} m) \leqslant 1 $ with $ A_e $ being the set of all alternative mappings for element $e$. To ensure that edges are mapped only if their adjacent nodes are mapped as well, we define the following constraint: $ m_e \implies m_v $ which translates to $ m_e \leq m_v $ with $ m_e $ being the edge mapping and $ m_v $ being one of the mappings of node $src(e)$ or $trg(e)$. Maximizing the number of activated variables yields the common kernel of both input rules, i.e., a maximal overlap between them. If the overlap between the created elements of both rules is empty, we drop this overlap as the resulting short-cut rule would not preserve any elements. Given a common kernel of two rules, we glue them along this kernel and yield a short-cut rule. For all elements of the resulting short-cut rule, which are not in the common kernel, we do the following: (1) Preserved elements remain preserved in the short-cut rule. (2) Created elements of the first rule become deleted ones as the first rule is inverted. (3) Created elements of the second rule remain created ones. We calculate two kinds of overlap for each pair of rules and hence, two short-cut rules: a maximal and a minimal overlap. The maximal overlap is calculated by allowing mappings between all created and context elements, respectively. On the other hand, the minimal overlap is created by allowing mappings between created elements only. Considering the corresponding ILP problem, this means that all other mapping candidates are dropped. Finally, the derived short-cut rules are operationalized to obtain the repair rules employed in our synchronization algorithm. \subsection{Attribute Constraints} Although attribute constraints have not been incorporated formally in our approach, eMoflon is able to define and solve those within the former legacy translation and synchronization process. As can be seen in Fig.~\ref{fig:eval_rule_set_full}, many rules have an equality constraint defined between the name attributes of created elements on both, source and target parts. For TGG rules, this means that the attribute values may be chosen arbitrarily since both nodes would be created from scratch. In forward rules, source elements are already present which means that an attribute constraint can be interpreted as to propagate or copy the already present value to a newly created element. We reuse this functionality for our new synchronization process in the following a way: After applying a repair rule, we ensure that the constraints of the replacing rule are fulfilled. The definition of attribute constraints and their treatment is due to Anjorin et al.~\cite{AVS12}.\footnote{This approach allows to specify constraints on attributes that involve also operations which are not only equality checks such as the concatenation of values of type \emph{String}.} \section{Introduction} \label{sec:intro} \input{introduction-long} \section{Informal Introduction to TGG-Based Model Synchronization} \label{sec:example} \input{example} \section{Preliminaries: Triple Graphs, Triple Graph Grammars and their Operationalizations} \label{sec:preliminaries} \input{preliminaries} \section{Short-cut Rules} \label{sec:sc-rules} \input{sc-rules} \section{Constructing Language-Preserving Repair Rules} \label{sec:constructing-repair-rules} \input{constructing-repair-rules} \section{Synchronization Algorithm} \label{sec:syncProcess} \input{syncProcess} \section{Implementation} \label{sec:implementation} \input{implementation} \section{Evaluation} \label{sec:implAndEvaluation} \input{evaluation-long} \section{Related Work} \label{sec:related-work} \input{related-work} \section{Conclusion} \label{sec:conclusion} \input{conclusion} \subsubsection*{Acknowledgments} This work was partially funded by the German Research Foundation (DFG) project \enquote{Triple Graph Grammars (TGG)~2.0}. \\ We would also like to thank the anonymous reviewers for their thoughtful comments and efforts. \bibliographystyle{spmpsci} \subsection{Graphs, triple graphs, and their transformations} \emph{Graphs} and their (rule-based) \emph{transformations} are suitable to formalize various kinds of models and their evolution, in particular of EMF models~\cite{BET12}.\footnote{Therefore in this paper, we use the terms \emph{graph} and \emph{model} interchangeably. In the formal parts, we will consequently speak of graphs following the formal literature.} In the context of this work, a \emph{graph} consists of a set of nodes and a set of directed edges which connect nodes. Graphs may be related by \emph{graph morphisms}, and a \emph{triple graph} consists of three graphs connected by two graph morphisms. \begin{definition}[Graph, graph morphism, triple graph, and triple graph morphism]\label{def:graphs} A \emph{graph} $G = (V,E,s,t)$ consists of a set $V$ of vertices, a set $E$ of edges, and source and target functions $s,t: E \rightarrow V$. An {\em element} $x$ of $G$ is a node or an edge, i.e., $x \in V$ or $x \in E$. A \emph{graph morphism} $f:G \rightarrow H$ between graphs $G = (V_G, E_G, s_G, t_G)$ and $H = (V_H, E_H, s_H, t_H)$ consists of two functions $f_V: V_G \rightarrow V_H$ and $f_E: E_G \rightarrow E_H$ that are compatible with the assignment of source and target to edges, i.e., $f_V \circ s_G = s_H \circ f_E$ and $f_V \circ t_G = t_H \circ f_E$. Given a fixed graph $\mathit{TG}$, a \emph{graph typed over $\mathit{TG}$} is a graph $G$ together with a graph morphism $\mathit{type}_G: G \to \mathit{TG}$. A \emph{typed graph morphism} $f: (G, \mathit{type}_G) \to (H, \mathit{type}_H)$ between typed graphs is a graph morphism $f: G \to H$ that respects the typing, i.e., $\mathit{type}_G = \mathit{type}_H \circ f$ (componentwise). A (typed) graph morphism $f = (f_V,f_E)$ is \emph{injective} if both $f_V$ and $f_E$ are. A \emph{triple graph} $G = (G_S \xleftarrow{\sigma_G} G_C \xrightarrow{\tau_G} G_T)$ consists of three graphs $G_S, G_C, G_T$, called \emph{source, correspondence}, and \emph{target graph}, and two graph morphisms $\sigma_G: G_C \rightarrow G_S$ and $\tau_G: G_C \rightarrow G_T$, called \emph{source} and \emph{target correspondence morphism}. A \emph{triple graph morphism} $f: G \rightarrow H$ between two triple graphs $G$ and $H$ consists of three graph morphisms $f_S: G_S \rightarrow H_S, f_C: G_C \rightarrow H_C$ and $f_T: G_T \rightarrow H_T$ such that $\sigma_H \circ f_C = f_S \circ \sigma_G$ and $\tau_H \circ f_C = f_T \circ \tau_G$. Given a fixed triple graph $\mathit{TG}$, a \emph{triple graph typed over $\mathit{TG}$} is a triple graph $G$ together with a triple graph morphism $\mathit{type}_G: G \to \mathit{TG}$. Again, \emph{typed triple graph morphisms} are triple graph morphisms that respect the typing. A (typed) triple graph morphism $f = (f_S,f_C,f_T)$ is \emph{injective} if $f_S, f_C$, and $f_T$ all are. \end{definition} \begin{example} Figure~\ref{fig:translationExample} depicts three triple graphs; their common type graph is depicted in Fig.~\ref{fig:typegraph}. The typing morphism is indicated by annotating the elements of the triple graphs with the types to which they are mapped in the type graph. The nodes in the triple graphs are of types \package{}, \folder{}, \class{}, and \doc{}. In each case, the source graph is depicted to the left and the target graph to the right. The hexagons in the middle constitute the correspondence graphs. Formally, the edges from the correspondence graphs to source and target graphs are morphisms: The edges encode how an individual correspondence node is mapped by the correspondence morphisms. For example, the nodes \rootP{} and \rootF{} of types \package{} and \folder{} correspond to each other as they share the same correspondence node as preimage under the correspondence morphisms. \end{example} Rules offer a declarative means to specify transformations of (triple) graphs. While classically rewriting of triple graphs has been performed using non-deleting rules only, we define a less restricted notion of rules\footnote{As used in double pushout rewriting of graphs or objects of other adhesive categories more generally~\cite{EEPT06,LS05}.} right away since short-cut rules and repair rules derived from them are both potentially deleting. A rule $p$ consists of three triple graphs, namely a \emph{left-hand side} (LHS) $L$ and a \emph{right-hand side} (RHS) $R$ and an \emph{interface} $K$ between them. Applying such a rule to a triple graph $G$ means to choose an injective morphism $m$ from $L$ to $G$. The elements from $m(L\setminus l(K))$ are to be deleted; if this results in a triple graph again, the morphism $m$ is called a match and $p$ is applicable at that match. After this deletion, the elements from $R \setminus r(K)$ are added; the whole process of applying a rule is also called a \emph{transformation (step)}. \begin{definition}[Rule, transformation (step)] A \emph{rule} $p = (L \xleftarrow{l} K \xrightarrow{r} R)$ consists of three triple graphs, $L$, $R$, and $K$, called the \emph{left-hand side}, \emph{right-hand side}, and \emph{interface}, respectively, and two injective triple graph morphisms $l: K \to L$ and $r: K \to R$. A rule is called \emph{monotonic}, or \emph{non-deleting}, if $l$ is an isomorphism. In this case we denote the rule as $r: L \to R$. The \emph{inverse rule} of a rule $p$ is the rule $p^{-1} = (R \xleftarrow{r} K \xrightarrow{l} L)$. Given a triple graph $G$, a rule $p = (L \xleftarrow{l} K \xrightarrow{r} R)$, and an injective triple graph morphism $m: L \to G$, the rule $p$ is \emph{applicable at $m$} if \begin{equation*} D \coloneqq G \setminus (m(L \setminus l(K))) \enspace , \end{equation*} is a triple graph again. Operator $\setminus$ is understood as node- and edge-wise set-theoretic difference. The source and target functions of $D$ are restricted accordingly. If $D$ is a triple graph, \begin{equation*} H \coloneqq D \cup n(R \setminus r(K)) \enspace , \end{equation*} is computed. Operator $\cup$ is understood as node- and edge-wise set-theoretic union. $n(R \setminus r(K))$ is a new copy of newly created elements. $n$ can be extended to $R$ by $n(r(K)) = m(l(K))$. The values of the source and target functions for edges from $n(R \setminus r(K))$ with source or target node in $K$ are determined by $m \circ l$, i.e., \begin{align*} s_H(e) & \coloneqq m(l(r^{-1}(s_R(e)))) \\ t_H(e) & \coloneqq m(l(r^{-1}(t_R(e)))) \end{align*} for such edges $e \in n(E_R)$ with $s_R(e) \in r_V(V_K)$ or $t_R(e) \in r_V(V_K)$. The whole computation is called a \emph{transformation (step)}, denoted as $G \Rightarrow_{p,m} H$ or just $G \Rightarrow H$, $m$ is called a \emph{match}, $n$ is called a \emph{comatch} and $D$ is the \emph{context triple graph} of the transformation. \end{definition} An equivalent definition based on computing two \emph{pushouts}, a notion from category theory generalizing the union of sets along a common subset, serves as basis when developing a formal theory~\cite{EEPT06}. In the following and in our examples, we always assume $K$ to be a common subgraph of $L$ and $R$ and the injective morphisms $l$ and $r$ to be the corresponding inclusions; this significantly eases the used notation. When we talk about the union of two graphs $G_1$ and $G_2$ along a common subgraph $S$, we assume that $G_1 \cap G_2 = S$. To enhance expressiveness, a rule may contain \emph{negative application conditions} (NACs)~\cite{EEPT06}. A NAC extends the LHS of a rule with a forbidden pattern: A rule is allowed to be applied only at matches which cannot be extended to any pattern forbidden by one of its NACs. If we want to stress that a rule is not equipped with NACs, we call it a \emph{plain rule}. \begin{definition}[Negative application conditions] Given a rule $p = (L \leftarrow K \rightarrow R)$, a set of \emph{negative application conditions} (NACs) for $p$ is a finite set of graphs $\mathit{NAC} = \{N_1, \dots, N_k\}$ such that $L$ is a subgraph of every one of them, i.e., $L \subset N_i$ for $1 \leq i \leq k$. A rule $(p = (L \leftarrow K \rightarrow R),\mathit{NAC})$ with NACs is applicable at a match $m: L \rightarrow G$ if the plain rule $p$ is and, moreover, for none of the NACs $N_i$ there exists an injective morphism $x_i: N_i \to G$ such that $x_i \circ \iota_i = m$ where $\iota_i: L \hookrightarrow N_i$ is the inclusion of $L$ into $N_i$. \end{definition} \begin{example} Different sets of triple rules are depicted in Figs.~\ref{fig:tggRules}, \ref{fig:tggFwdRules}, \ref{fig:scRules}, and \ref{fig:fwdSCRules}. All rules in these figures are presented in an \emph{integrated} form: Instead of displaying LHS, RHS, and the interface as three separate graphs, just one graph is presented where the different roles of the elements are displayed using markings (and color). The unmarked (black) elements constitute the interface of the rule, i.e., the context that has to be present to apply a rule. Unmarked elements and elements marked with $(--)$ (black and red elements) form the LHS while unmarked elements and elements marked with $(++)$ (black and green elements) constitute the RHS. Elements marked with (nac) (blue elements) extend the LHS to a NAC; different NACs for the same rule are distinguished using names. As triple rules are depicted, their LHSs and RHSs are triple graphs themselves. For example, the LHS $L$ of \secondTGGRule{} (Fig.~\ref{fig:tggRules}) consists of the nodes \ssp{} and \ssf{} of types \package{} and \folder{} and the correspondence node in between. While, e.g., all rules in Fig.~\ref{fig:tggRules} are monotonic, \secondSCRule{} is not as it deletes edges and a \doc{}. Applying \secondSCRule{} to the triple graph (a) in Fig.~\ref{fig:translationExample} leads to the triple graph (c), when \package{}-nodes \ssp{} and \p{} (of the rule) are matched to \rootP{} and \subP{} (in the graph), respectively. (The \folders{} on the target part are mapped accordingly.) The rules \firstSCRule{} and \secondSCRule{} are inverse to each other. Finally, \firstTGGForwardRule{} (Fig.~\ref{fig:tggFwdRules}) depicts a rule that is equipped with a NAC: It is applicable only at \packages{} that are not referenced by other \packages{}. This means that it is applicable at node \subP{} in the triple graph (b) depicted in Fig.~\ref{fig:translationExample}, but not at node \leafP{}. \end{example} \subsection{Triple graph grammars and their operationalization} Sets of triple graph rules can be used to define languages. \begin{definition}[Triple graph grammar] A \emph{triple graph grammar} (TGG) $\mathit{GG} = (\mathcal{R},S)$ consists of a set of plain, monotonic triple rules $\mathcal{R}$ and a start triple graph $S$. In case of typing, all rules of $\mathcal{R}$ and $S$ are typed over the same triple graph. The language of a TGG $\mathit{GG}$, denoted as $\mathcal{L}(\mathit{GG})$, is the reflexive and transitive closure of the relation induced by transformation steps via rules from $\mathcal{R}$, i.e., \begin{equation*} \mathcal{L}(\mathit{GG}) \coloneqq \{H \, | \, S \Rightarrow_{\mathcal{R}}^* H\} \end{equation*} where $\Rightarrow_{\mathcal{R}}^*$ denotes a finite sequence of transformation steps where each rule stems from $\mathcal{R}$. The \emph{projection of the language of a TGG to its source part} is the set \begin{equation*} \mathcal{L}_S(\mathit{GG}) \coloneqq \{ G_S \, | \, G = (G_S \leftarrow G_C \rightarrow G_T) \in \mathcal{L}(\mathit{GG})\} \enspace , \end{equation*} i.e., it consists of the source graphs of the triple graphs of $\mathcal{L}(\mathit{GG})$. \end{definition} In applications, quite frequently, the start triple graph of a TGG is just the empty triple graph. We use $\emptyset$ to denote the empty graph, the empty triple graph, and morphisms starting from the empty (triple) graph; it will always be clear from the context what is meant. To enhance expressiveness of TGGs, their rules can be extended with NACs or with some attribution concept for the elements of generated triple graphs. A recent overview of such concepts and their expressiveness can be found in~\cite{WOR19}. In the following, we first restrict ourselves to TGGs that contain plain rules only and discuss extensions of our approach subsequently. \begin{example} The rule set depicted in Fig.~\ref{fig:tggRules}, together with the empty triple graph as start graph, constitutes a TGG. The triple graphs (a) and (c) in Fig.~\ref{fig:translationExample} are elements of the language defined by that grammar while the triple graph (b) is not. \end{example} The operationalization of triple graph rules into \emph{source} and \emph{forward} (or, analogously, into \emph{target} and \emph{backward}) \emph{rules} is central to working with TGGs. Given a rule, its source rule performs the rule\rq{}s actions on the source graph only while its forward rule propagates these to correspondence and target graph. This means that, for example, source rules can be used to generate the source graph of a triple graph while forward rules are then used to translate the source graph to correspondence and target side such that the result is a triple graph in the language of the TGG. Classically, this operationalization is defined for monotonic rules only~\cite{Schuerr95}. We will later explain how to extend it to arbitrary triple rules. We also recall the notion of marking~\cite{Leblebici18} and \emph{consistency patterns} which can be used to check if a triple graph belongs to a given TGG. \begin{definition}[Source and forward rule. Consistency pattern] Given a plain, monotonic triple rule $r = L \rightarrow R$ with $r = (r_S, r_C, r_T)$, $L = (L_S \xleftarrow{\sigma_L} L_C \xrightarrow{\tau_L} L_T)$ and $R = (R_S \xleftarrow{\sigma_R} R_C \xrightarrow{\tau_R} R_T)$, its \emph{source rule} is defined as \begin{equation*} r^S \coloneqq (L_S \leftarrow \emptyset \rightarrow \emptyset) \xrightarrow{(r_S, \mathit{id}_{\emptyset}, \mathit{id}_{\emptyset})} (R_S \leftarrow \emptyset \rightarrow \emptyset) \enspace . \end{equation*} Its \emph{forward rule} is defined as \begin{equation*} r^F \coloneqq (R_S \xleftarrow{\sigma_R \circ r_C} L_C \xrightarrow{\tau_L} L_T) \xrightarrow{(\mathit{id}_{R_S}, r_C, r_T)} (R_S \xleftarrow{\sigma_R} R_C \xrightarrow{\tau_R} R_T) \enspace . \end{equation*} We denote the left- and right-hand sides of source and forward rules of a rule $r$ by $L^S,L^F,R^S$, and $R^F$, respectively. The \emph{consistency pattern} derived from $r$ is the rule \begin{equation*} r^C \coloneqq (R_S \xleftarrow{\sigma_R} R_C \xrightarrow{\tau_R} R_T) \xrightarrow{(\mathit{id}_{R_S}, \mathit{id}_{R_C}, \mathit{id}_{R_T})} (R_S \xleftarrow{\sigma_R} R_C \xrightarrow{\tau_R} R_T) \end{equation*} that, upon application, just checks for the existence of the RHS of the rule without changing the instance it is applied to. Given a rule $r$, each element $x \in R_S \setminus L_S$ is called a \emph{source marking element} of the forward rule $r^F$; each element of $L_S$ is called \emph{required}. Given an application $G \Rightarrow_{r^F,\mathit{m^F}} H$ of a forward rule $r^F$, the elements of $G_S$ that have been matched by source marking elements of $r^F$, i.e., the elements of the set $\mathit{m}^F(R_S \setminus L_S)$ are called \emph{marked elements}. A transformation sequence \begin{equation}\label{eq:forward-sequence} G_0 \Rightarrow_{m_1^F,r_1^F} G_1 \Rightarrow_{m_2^F,r_2^F} \dots \Rightarrow_{m_t^F,r_t^F} G_t \end{equation} is called \emph{creation preserving} if no two rule applications in sequence (\ref{eq:forward-sequence}) mark the same element. It is called \emph{context preserving} if, for each rule application in sequence (\ref{eq:forward-sequence}), the required elements have been marked by a previous rule application in sequence (\ref{eq:forward-sequence}). If these two properties hold for sequence~(\ref{eq:forward-sequence}), it is called {\em consistently marking}. It is called \emph{entirely marking} if every element of the common source graph $G_S$ of the triple graphs of this sequence is marked by a rule application in sequence (\ref{eq:forward-sequence}). \end{definition} The most important formal property of this operationalization is that applying a (sequence of) source rule(s) followed by applying the (sequence of) corresponding forward rule(s) yields the same result as applying the (sequence of) original TGG rule(s) assuming consistent matches~\cite{Schuerr95,EEEHT07}. Moreover, there is a correspondence between triple graphs belonging to the language of a given TGG and consistently and entirely marking transformation sequences via its forward rules. We formally state this correspondence as it is an ingredient for the proof of correctness of our synchronization algorithm. \begin{lemma}[{see \cite[Fact~1]{LAFVS17} or ~\cite[Lemma~4]{Leblebici18}}]\label{lem:emccp-series} Let a TGG $\mathit{GG}$ be given. There exists a triple graph $G = (G_S \leftarrow G_C \rightarrow G_T) \in \mathcal{L}(\mathit{GG})$ if and only if there exists a transformation sequence like the one depicted in~(\ref{eq:forward-sequence}) via forward rules from $\mathit{GG}$ such that $G_0 = (G_S \leftarrow \emptyset \rightarrow \emptyset),\ G_t = (G_S \leftarrow G_C \rightarrow G_T)$, and the transformation sequence is consistently and entirely marking. \end{lemma} For practical purposes, forward rules and consistency patterns may be equipped with so-called \emph{filter NACs} which can be automatically derived from the set of rules of the given TGG. The simplest examples of such filter NACs arise through the following analysis: For each rule that translate a node without translating adjacent edges it is first checked if other rules translate the same type of node but also translate an adjacent edge of some type. If this is the case, it is checked if there are further rules which only translate the detected kind of adjacent edge. If none is found, the original rule is equipped with a NAC forbidding the respective kind of edges. This avoids a dead-end in translation processes: In the presence of such a node with its adjacent edge, using the original rule to only translate the node leaves an untranslatable edge behind. The filter NAC of \firstTGGForwardRule{} is derived in exactly this way. For the exact and more sophisticated derivation processes of filter NACs, we refer to the literature~\cite{Hermann2010,KLKS10}. For our purposes it suffices to recall their distinguishing property: Filter NACs do not prevent \enquote{valid} transformation sequences of forward rules. We state this property in the terminology of our paper. \begin{fact}[{\cite[Fact~4]{Hermann2010}}] Given a TGG $\mathit{GG} = (\mathcal{R},S)$, for each $r \in \mathcal{R}$, let $r^{\mathit{FN}}$ denote the corresponding forward rule that is additionally equipped with a set of derived filter NACs. (This set might be empty). For $G_0 = (G_S \leftarrow \emptyset \rightarrow \emptyset)$, there exists a consistently and entirely marking transformation sequence \begin{equation*} G_0 \Rightarrow_{r_1^F,m_1^F} G_1 \Rightarrow_{r_2^F,m_2^F} \dots \Rightarrow_{r_t^F,m_t^F} G_t \end{equation*} via the forward rules (without filter NACs) derived from $\mathcal{R}$ if and only if the sequence \begin{equation*} G_0 \Rightarrow_{r_1^{\mathit{FN}},m_1^F} G_1 \Rightarrow_{r_2^{\mathit{FN}},m_2^F} \dots \Rightarrow_{r_t^{\mathit{FN}},m_t^F} G_t \end{equation*} exists, i.e, if none of the filter NACs blocks one of the above rule applications. \end{fact} \begin{example} The source rules of the triple rules depicted in Fig.~\ref{fig:tggRules} are depicted in Fig.~\ref{fig:tggSourceRules}. They allow to create \packages{} and \classes{} on the source side without changing correspondence and target graphs. The formally existing empty graphs at correspondence and target sides are not depicted. The corresponding forward rules are given in Fig.~\ref{fig:tggFwdRules}. Their required elements are annotated with \marked{} and their source marking elements with \marking{}. The rule \firstTGGForwardRule{} is equipped with a filter NAC: The given grammar does not allow to create a \package{} that is contained in another one with its original rule \firstTGGRule{}. Hence, the derived forward rule should not be used to translate a \package{}, which is contained in another one, to a \folder{}. As evident in the examples, the application of a source rule followed by the application of the corresponding forward rule amounts to the application of the original triple rule if matched consistently. The consistency patterns that are derived from the TGG rules of our example are depicted in Fig.~\ref{fig:consistency}. They just check for existence of the pattern that occurs after applying the original TGG rule. A consistency pattern is equipped with the filter NACs of both its corresponding forward and backward rule. In our example, only \emph{Root-Consistency-Pattern} receives such NACs; one from \firstTGGForwardRule{} and the second one from the analogous backward rule. An occurrence of a consistency pattern in our example model indicates that a specific location corresponds to a concrete TGG rule application. Hence, a disappearance of such a match indicates that a former intact rule application has been broken and needs some fixing. We call this a \emph{broken match for a consistency pattern} or, short, a \emph{broken consistency match}. Practically, we will exploit an incremental pattern matcher to notify us about such disappearances. \begin{figure}[ht] \centering \includegraphics[width=1.0\columnwidth]{Diagram/Consistency_attr.pdf} \caption{Example: Consistency Patterns} \label{fig:consistency} \end{figure} \end{example} \subsection{Sequential independence} The proof of correctness of our synchronization approach relies on the notion of \emph{sequential independence}. Transformations that are sequentially independent can be performed in arbitrary order. \begin{definition}[Sequential independence] Given two transformation steps $G \Rightarrow_{r_1,m_1} H_1 \Rightarrow_{r_2,m_2} X$, via plain rules $r_1,r_2$ these are \emph{sequentially independent} if \begin{equation}\label{eq:seq-independence} n_1(R_1) \cap m_2(L_2) \subseteq n_1(K_1) \cap m_2(K_2) \end{equation} where $n_1$ is the comatch of the first transformation. \end{definition} By the Local Church-Rosser Theorem the order of sequentially independent transformation can be switched. This means that, given a sequentially independent transformation sequence $G \Rightarrow_{r_1,m_1} H_1 \Rightarrow_{r_2,m_2} X$, there exists a sequentially independent transformation sequence $G \Rightarrow_{r_2,m_2^\prime} H_2 \Rightarrow_{r_1,m_1^\prime} X$~\cite[Theorem~3.20]{EEPT06}. If $r_1$ and $r_2$ are equipped with NACs $\mathit{NAC}_1$ and $\mathit{NAC}_2$, respectively, transformation steps as above are \emph{sequentially independent} if condition~(\ref{eq:seq-independence}) holds and moreover, the thereby induced matches $m_2^\prime: L_2 \to G$ and $m_1^\prime: L_1 \to H_2$ both satisfy the respective sets of NACs. In particular, the Local Church-Rosser Theorem still holds. In our setting of graph transformation, it is easy to check the sequential independence of transformations~\cite{EEPT06,EGHLO14}. A sequence $t_1;t_2$ of two transformation steps is sequentially independent if and only if the following holds. \begin{itemize} \item $t_2$ does not match an element that $t_1$ created. \item$t_2$ does not delete an element that $t_1$ matches. \item $t_2$ does not create an element that $t_1$ forbids. \item $t_1$ does not delete an element that $t_2$ forbids. \end{itemize} \subsection{Construction of short-cut rules} We recall the construction of short-cut rules in a semiformal way and reuse an example of~\cite{FKST18} for illustration; a formal treatment (in a category-theoretical setting) can be found in that paper. Given an inverse monotonic rule (i.e., a rule that purely deletes) and a monotonic rule, a \shortcutRule{} combines their respective actions into a single rule. Its construction allows to identify elements that are deleted by the first rule as recreated by the second one. To motivate the construction, assume two monotonic rules $r_1: L_1 \rightarrow R_1$ and $r_2: L_2 \rightarrow R_2$ be given. Applying the inverse rule of $r_1$ to a triple graph $G$, provides an image of $L_1$ in the resulting triple graph $H$. When applying $r_2$ thereafter, the chosen match for $L_2$ in $H$ may intersect with the image of $L_1$ yielding a triple graph $L_{\cap}$. This intersection can also be understood as saying that $L_{\cap}$ provides a partial match for $L_2$. The inverse application of the first rule deletes elements which may be recreated again. In this case, it is possible to extend the sub-triple graph $L_{\cap}$ of $H$ to a sub-triple graph $R_{\cap}$ of $H$ with these elements. In particular, $R_{\cap}$ is a sub-triple graph of $R_1$ and $R_2$ as it includes elements only that have been deleted by the first rule and created by the second. Based on this observation, the construction of short-cut rules is defined as follows (slightly simplified and directly merged with an example): \begin{construction}[Short-cut rule] Let two plain, monotonic rules $r_1 = L_1 \to R_1$ and $r_2= L_2 \to R_2$ be given. A short-cut rule $r_{\mathit{sc}}$ for the rule pair $(r_1,r_2)$, where $r_1$ is considered to be applied inversely, is constructed in the following way: \begin{figure*} \centering \includegraphics[width=.8\textwidth,trim={1.5mm 1.5mm 1.5mm 1.5mm},clip]{Diagram/example-common-kernel.pdf} \caption{A common kernel rule pair (\firstTGGRule{},\secondTGGRule{}). The names of the nodes indicate their mappings and the rules are depicted top-down.} \label{fig:example-common-kernel} \end{figure*} \begin{enumerate} \item \emph{Choice of common kernel:} A (potentially empty) sub-triple graph $L_{\cap}$ of $L_1$ and $L_2$ and a sub-triple graph $R_{\cap}$ of $R_1$ and $R_2$ with $L_{\cap} \subseteq R_{\cap}$ are chosen. We call $\Lcap \subseteq \Rcap$ a \emph{common kernel} of both rules. In Fig.~\ref{fig:example-common-kernel}, an example of such a common kernel is given. It is a common kernel for rule pair (\firstTGGRule{}, \secondTGGRule{}). The common kernel is depicted in the center of Fig.~\ref{fig:example-common-kernel}. This choice of a common kernel will lead to \firstSCRule{} as resulting short-cut rule. In this example, $L_{\cap}$ is empty and $R_{\cap}$ extends $L_{\cap}$ by identifying the \packages{} \p, \folders{} \f, and the correspondence node in between. The elements of $R_{\cap} \setminus L_{\cap}$, called \emph{recovered elements}, are to become the elements that are preserved by an application of the short-cut rule compared to reversely applying the first rule followed by applying the second one (provided that these applications overlap in $L_{\cap}$). In the example case, the whole graph $R_{\cap}$ is recovered as $L_{\cap}$ is empty. \item \emph{Construction of LHS and RHS:} One first computes the union $L_{\cup}$ of $L_1$ and $L_2$ along $L_{\cap}$. The result is then united with $R_1$ along $L_1$ and $R_2$ along $L_2$, respectively, to compute the LHS and the RHS of the short-cut rule. Figure~\ref{fig:example-construction-LHS-RHS} displays this. \item \emph{Interface construction:} The interface $K$ of the short-cut rule is computed by taking the union of $L_{\cup}$ and $R_{\cap}$ along $L_{\cap}$. For our example, this construction is depicted in Figure~\ref{fig:example-construction-interface}. The elements of $L_2 \setminus L_{\cap}$ are called \emph{presumed elements} since, given a match for the inverse first rule, i.e., for $R_1$, these are exactly the elements needed to extend this match to a match of the short-cut rule. In our example, these are the \package{} \ssp{}, the \folder{} \ssf{}, and the correspondence node in between. \end{enumerate} \begin{figure*} \centering \includegraphics[width=\textwidth,trim={1.5mm 1.5mm 1.5mm 1.5mm},clip]{Diagram/example-construction-LHS-RHS.pdf} \caption{Constructing the LHS and the RHS of the short-cut rule \firstSCRule{}} \label{fig:example-construction-LHS-RHS} \end{figure*} \end{construction} \begin{figure} \centering \includegraphics[width=\columnwidth,trim={1.5mm 1.5mm 1.5mm 1.5mm},clip]{Diagram/example-construction-interface.pdf} \caption{Constructing the interface of the short-cut \firstSCRule{}; the interface is the resulting graph in the bottom right corner.} \label{fig:example-construction-interface} \end{figure} \begin{example} More examples of short-cut rules are depicted in Fig.~\ref{fig:scRules}. Both, \firstSCRule{} and \secondSCRule{}, are constructed for the rules \firstTGGRule{} and \secondTGGRule{}. Switching the role of of the inverse rule, two short-cut rules can be constructed having equal common kernels. In both cases, the \package{} \p{}, the \folder{} \f{} and the correspondence node between them are recovered elements, as these elements would have been deleted and re-created otherwise. While in \firstSCRule{}, the presumed elements are the \package{} \ssp{} and the \folder{} \ssf{} with a correspondence node in between, the set of presumed elements of \secondSCRule{} is empty. Another possible common kernel for \firstTGGRule{} and \secondTGGRule{} is one where $R_{\cap}$ is an empty triple graph as well. As the resulting short-cut rule just copies both rules (one of them inversely) next to each other, this rule is not interesting for our desired application. \end{example} \subsection{Expressivity of short-cut rules} Given a set of rules, there are {\em two degrees of freedom} when deciding which short-cut rules to derive from them: First, one has to choose for which \emph{pairs of rules} short-cut rules shall be derived. Secondly, given a pair of rules, there is typically not only one way to construct a short-cut rule for them: In general, there are different choices for a \emph{common kernel}. However, when fixing a common kernel, i.e., $\Lcap$ and $\Rcap$, the result of the construction is uniquely determined. If, moreover, the LHSs and RHSs of the rules are finite, the set of possible common kernels is finite as well. As short-cut rules correspond to possible (complex) edits of a triple graph, the more short-cut rules are derived, the more user edits are available which can directly be propagated by the corresponding repair rules. But the number of rules that has to be computed (and maintained throughout the synchronization process) in this way, would quickly grow. And maybe several of the constructed rules would capture edits that are possible in principle but unlikely to ever be performed in a realistic scenario. Hence, some trade-off between expressivity and maintainability has to be found. We shortly discuss these effects of choices: The construction of short-cut rules is defined for \emph{any two} monotonic rules~\cite{FKST18} -- we do not need to restrict to the rules of a given TGG but may also use monotonic rules that have been constructed as so-called \emph{concurrent rules}~\cite{EEPT06} of given TGG rules as input for the short-cut rule construction. A concurrent rule combines the actions of two (or more) subsequent rule applications into a single rule. Hence, deriving short-cut rules from concurrent rules that have been built of given TGG rules leads to short-cut rules that capture even more complex edits into a single rule. The next example presents such a derived short-cut rule. While our conceptual approach is easily extended to support such rules, we currently stick with short-cut rules directly derived from a pair of rules of the given TGG in our implementation. \begin{example} The short-cut rule \fourthSCRule{} depicted in Fig.~\ref{fig:sc-rule-4} is not directly derived of the TGG rules depicted in Fig.~\ref{fig:tggRules}. Instead, the concurrent rule of two given applications of \secondTGGRule{} is constructed first. This concurrent rule directly creates a chain of two \packages{} and \folders{} into an existing pair of \package{} and \folder{}. The rule in Fig.~\ref{fig:sc-rule-4} is a short-cut rule of this concurrent rule and \secondTGGRule{}. It takes back the creation of a chain such that the bottom package is directly included in the top package in Fig.~\ref{fig:sc-rule-4}. \begin{figure} \includegraphics[width=\columnwidth]{Diagram/SC_Rule_4.pdf} \caption{Example for a short-cut rule not directly derived from the rules of our example TGG} \label{fig:sc-rule-4} \end{figure} \end{example} Concerning the choice of a common kernel, we follow two strategies. In both strategies, we overlap as many of the newly created elements of the two input rules as possible since these are the elements that we try to preserve. A \emph{minimal overlap} overlaps created elements only, i.e. no context elements. An example is \secondTGGRule{}, which overlapped with itself, results in \thirdSCRule{} and which corresponds to a move refactoring step. A \emph{maximal overlap} overlaps not only created elements of both rules but also context elements. Creating such an overlap for \secondTGGRule{} with itself would result in the \emph{Sub-Consistency-Pattern}, which has no effect when applied. However, when overlapping different rules with each other, it is often useful to re-use context elements. This is the case, for example, for \emph{VariableDec-2-Parameter-Rule} and \emph{TypeAccess-2-ReturnType-Rule} of our evaluation rule set in Fig.~\ref{fig:eval_rule_set_full} below. A full overlap between both rules would allow to transform a signature parameter to a return parameter of the same method and of the same type and, vice versa. Both strategies aim to create different kinds of short-cut rules with specific purposes. Since generating all possible overlaps and thus short-cut rules is expensive, we chose a heuristic approach to generate a useful subset of them. As we are dealing with triple graphs being composed of source, target and correspondence graphs, the overlap of source graphs should correspond to that of target graphs. This restricts the kind of \enquote{reuse} of elements the derived short-cut rules enable. The allowance of any kind of overlap may include unintended ones. We argue for the usefulness of these strategies in our evaluation in Sect.~\ref{sec:implAndEvaluation}. \subsection{Language preserving short-cut rule applications} The central intuition behind the construction of short-cut rules is to replace the application of a monotonic triple rule by another one. In this sense, a short-cut rule captures a complex edit operation on triple graphs that (in general) cannot be performed directly using the rules of a TGG. We illustrate this behaviour in the following. Subsequently, we discuss the circumstances under which applications of short-cut rules are \enquote{legal} in the sense that the result still belongs to the language of the respective TGG. \medskip Let a TGG $\mathit{GG}$ and a sequence of transformations \begin{equation}\label{eq:original-sequence} G_0 \Rightarrow_{r_1,m_1} G_1 \Rightarrow_{r_2,m_2} G_2 \Rightarrow \dots \Rightarrow_{r_t,m_t} G_t \end{equation} be given where all the $r_i$, $1 \leq i \leq t$, are rules of $\mathit{GG}$, all the $m_i$ denote the respective matches, and $G_0 \in \mathcal{L}(\mathit{GG})$; in particular $G_t \in \mathcal{L}(\mathit{GG})$ as well. Fixing some $j \in \{1, \dots, t\}$ and some rule $r$ of $\mathit{GG}$, we construct a short-cut rule $r_{sc}$ for $(r_j, r)$ with some common kernel $\Lcap \subseteq \Rcap$. Next, we can consider the transformation sequence \begin{equation*} G_0 \Rightarrow_{r_1,m_1} G_1 \Rightarrow_{r_2,m_2} G_2 \Rightarrow \dots \Rightarrow_{r_t,m_t} G_t \Rightarrow_{r_{sc},m_{sc}} G_t' \end{equation*} that arises by appending an application of $r_{sc}$ to transformation sequence~(\ref{eq:original-sequence}). Under certain technical cir\-cumstances (which we will state below) this transformation sequence is equivalent\footnote{The formal notion of equivalence used here is called \emph{switch equivalence} and captures the idea that, in case of sequential independence, the order of rule applications might be switched while using basically the same match for each rule application and receiving the same result; compare, e.g.,~\cite{Kreowski86,BCHKS14}.} to the sequence \begin{equation}\label{eq:final-sequence} \begin{split} G_0 \Rightarrow_{r_1,m_1} G_1 \Rightarrow \dots \Rightarrow_{r_{j-1},m_{j-1}} G_{j-1} \Rightarrow_{r,m_{sc}^{\prime}} G_j^{\prime} \\ \Rightarrow_{r_{j+1},m_{j+1}^{\prime}} \dots \Rightarrow_{r_t,m_t^{\prime}} G_t^{\prime\prime} \end{split} \end{equation} where the application of $r_j$ at match $m_j$ is replaced by an application of $r$ at a match $m_{sc}\rq{}$ that is derived from the match $m_{sc}$ of the \shortcutRule{}. The following matches $m_{j+1},\allowbreak \dots,\allowbreak m_{t}$ have been adapted accordingly. They still match the same elements but formally they do so in other triple graphs. In particular, $G_t^{\prime\prime}$, the result of the transformation sequence (\ref{eq:final-sequence}), \emph{is isomorphic} to $G_t^{\prime}$ and hence, $G_t^{\prime}$ can be understood as arising by replacing the $j$-th rule application in the transformation sequence (\ref{eq:original-sequence}) by an application of the rule $r$; thus, $G_t^{\prime}$ also belongs to the language of the TGG: The sequence~(\ref{eq:final-sequence}) starts at a triple graph $G_0 \in \mathcal{L}(\mathit{GG})$ and solely consists of applications of rules from $\mathit{GG}$. \begin{figure*} \centering \includegraphics[width=.75\textwidth]{Diagram/RuleApplications_Solved}% \caption{Example: Transforming sequences of rule applications by applying short-cut rules}% \label{fig:ruleApplications_Solved}% \end{figure*} \begin{example} Consider the triple graph depicted in Fig.~\ref{fig:translationExample} (a). It arises by applying \firstTGGRule{}, followed by two applications of \secondTGGRule{}, and finally an application of \thirdTGGRule{}. When matched as already described in the introductory example, an additional application of \secondSCRule{} to this triple graph results in the one depicted in Fig.~\ref{fig:translationExample} (c). Alternatively, this can be derived by two applications of \firstTGGRule{}, followed by an application of \secondTGGRule{} and \thirdTGGRule{} each. As schematically depicted in Fig.~\ref{fig:ruleApplications_Solved}, the application of the \shortcutRule{} \secondSCRule{} transforms an transformation sequence deriving the first triple graph into a transformation sequence deriving the second one by replacing an application of \secondTGGRule{} by one of \firstTGGRule{}. \end{example} In the following, we state when the above described behaviour is the case (in a somewhat less technical language than originally used). \begin{theorem}[{\cite[Theorem~8]{FKST19}}]\label{thm:valid-applications} Let the transformation sequence~(\ref{eq:original-sequence}) be given and let $r_{sc}$ be a \shortcutRule{} that is derived from $(r_j, r)$. If the following three conditions are met, this sequence is equivalent to sequence~(\ref{eq:final-sequence}) where original TGG rules are applied only. \begin{enumerate} \item \emph{Reversing match:} The application of $r_{sc}$ at $m_{sc}$ reverses the application of $r_j$, i.e., $n_j(R_j) = m_{\mathit{sc}}|_{R_j}(R_j)$. \item \emph{Sequential independence:} \begin{enumerate} \item \emph{Non-disabling match:} The application of $r_{sc}$ at $m_{sc}\rq{}$ does not delete elements used in the applications of $r_{j+1}, \dots, r_t$. \item \emph{Context-preserving match:} The match $m_{sc}$ for $r_{sc}$ already exists in $G_{j-1}$. Since the assumption on the match to be reversing already ensures this for elements of $L_{\mathit{sc}}$ that stem from $R_j$, context-preservation ensures in particular that the \emph{presumed elements} of $r_{sc}$ are matched to elements already existing in $G_{j-1}$. \end{enumerate} \end{enumerate} \end{theorem} \begin{example} We illustrate each of the above mentioned conditions: \begin{enumerate} \item \emph{Reversing match:} In our example of matching \firstSCRule{} to the triple graph (c) in Fig.~\ref{fig:translationExample} this means that its nodes \p{} and \f{} (and the correspondence node in between) are allowed to be matched to elements only that have been created using \firstTGGRule{}. In this way, it is avoided to mis\-use the rule to introduce \packages{} (and \folders{}) that are contained by more than one \package{} (or \folder{}). \item \emph{Non-disabling match:} For example, \fourthSCRule{} from Fig.~\ref{fig:sc-rule-4} is not allowed to delete \packages{} and \folders{} that already contain \classes{} or \docs{}, respectively. \item \emph{Context preserving match:} Returning to our example of matching \firstSCRule{} to the triple graph (c) in Fig.~\ref{fig:translationExample} this means that as soon as nodes \subP{} and \subF{} in that triple graph have been chosen as matches for the nodes \p{} and \f{} of \firstSCRule{}, the nodes \leafP{} and \leafF{} are not allowed to be chosen as matches for nodes \ssp{} and \ssf{} of \firstSCRule{}. The creation of \leafP{} and \leafF{} depends on \subP{} and \subF{} being created first. In this way, the introduction of cyclic dependencies between elements is avoided. \end{enumerate} \end{example} \subsection{The Basic Setup}\label{sec:basic-setup-algorithm} We assume a TGG $\mathit{GG}$ with \emph{plain, monotonic rules} to be given. Its language defines consistency. This means that a triple graph $G = (G_S \leftarrow G_C \rightarrow G_T)$ is consistent if and only if $G \in \mathcal{L}(\mathit{GG})$. \paragraph{The problem.} A consistent triple graph $G = (G_S \leftarrow G_C \rightarrow G_T) \in \mathcal{L}(\mathit{GG})$ is given; by Lemma~1 there exists a corresponding consistently and entirely marking sequence $t$ of forward rule applications. After editing source graph $G_S$ we get $G\rq{} = (H_S \dashleftarrow G_C \rightarrow G_T)$. Generally, the result $G\rq{}$ is a partial triple graph and does not belong to $\mathcal{L}(\mathit{GG})$. We assume that all the edits are performed by applying source rules. They may be derived from the original TGG rules or from short-cut rules. Our goal is to provide a \emph{model synchronization algorithm} that, given $G = (G_S \leftarrow G_C \rightarrow G_T) \in \mathcal{L}(\mathit{GG})$ and $G\rq{} = (H_S \dashleftarrow G_C \rightarrow G_T)$ as input, computes a triple graph $H = (H_S \leftarrow H_C \rightarrow H_T) \in \mathcal{L}(\mathit{GG})$. As a side condition, we want to minimize the amount of elements of $G_C$ and $G_T$ that are deleted and recreated during that synchronization. \paragraph{Ingredients of our algorithm.} We provide a rule-based model synchronization algorithm leveraging an incremental pattern matcher. During that algorithm, rules are applied to compute a triple graph $(H_S \leftarrow H_C \rightarrow H_T) \in \mathcal{L}(\mathit{GG})$ from the (partial) triple graph $(H_S \dashleftarrow G_C \rightarrow G_T)$. We apply two different kinds of rules, namely \begin{enumerate} \item forward rules derived from the rules of the TGG $\mathit{GG}$ and \item repair rules, i.e., operationalized short-cut rules. \end{enumerate} Forward rules serve to propagate the addition of elements. The use of these rules for model synchronization is standard. However, the use of additional repair rules and the way in which they are employed are conceptually novel.\footnote{Note that consistency is still defined by the (plain, monotonic) rules of the given TGG; the general repair rules are derived only to improve the synchronization process.} The repair rules allow to directly propagate more complex user edits. During the synchronization process, the rules are applied reacting to notifications by an incremental pattern matcher. We require this pattern matcher to provide the following information: \begin{enumerate} \item The original triple graph $G = (G_S \leftarrow G_C \rightarrow G_T)$ is \emph{covered with consistency patterns}. When considering the induced matches for forward rules, every element of $G_S$ is marked exactly once. The dependency relation between elements required by these matches is acyclic. This means that the induced transformation sequence of forward rules is consistently and entirely marking. Such a sequence always exists since $G \in \mathcal{L}(\mathit{GG})$; see Lemma~\ref{lem:emccp-series}. \item \emph{Broken consistency matches} are reported. A match for a consistency pattern in $G$ is broken in $G\rq{}$ if one of the elements it matches or creates has been deleted or if an element has been created that violates one of the filter NACs of that consistency pattern. \item The incremental pattern matcher notifies about newly occurring matches for forward rules. It does so in a \emph{correct} way, i.e., it only notifies about matches that lead to consistently marking transformations. \item In addition, the incremental pattern matcher informs a \emph{precedence graph}. This precedence graph contains information about the mutual dependencies of the elements in the partial triple graph. Here, an element is dependent on another one if the forward rule application marking the former matches the latter element as required. We consider the transitive closure of this relation. \end{enumerate} \subsection{Synchronization Process} \label{subsec:sync-process} Our synchronization process is depicted in Algorithm~\ref{alg:sync}. It applies rules to translate elements and repair rule applications. In that, it applies a different strategy than suggested in~\cite{LAFVS17,Leblebici18}. There, invalid rule applications are revoked as long as there exist any. Subsequently, forward rules are applied as long as possible. By trying to apply a suitable repair rule instead of revoking an invalid rule application, we are able to avoid deletion and recreation of elements. Our synchronization algorithm is defined as follows. Note that we present an algorithm for synchronizing in forward direction (from source to target) while synchronizing backwards is performed analogously. The function \textit{synchronize} is called on the current partial triple graph that is to be synchronized. In line~\ref{alg:sync:update}, \textit{updateMatches} is called on this partial triple graph. It returns the set of consistency matches currently broken, a set of consistency matches being still intact, and a set of forward TGG rule matches. By calling the function \emph{isFinished} (line~\ref{alg:sync:isFinished-call}), termination criteria for the synchronization algorithm are checked. If the set of broken consistency matches and the set of forward TGG rule matches are both empty and all elements of the source graph are marked as translated, the synchronization algorithm terminates (line~\ref{alg:sync:terminate}). Yet, if both sets are empty but there are still untranslated elements in the source graph, an exception is thrown in line~\ref{alg:sync:exception}, signaling that the (partial) triple graph is in an inconsistent state. Subsequently, function \emph{translate} is used (line~\ref{alg:sync:translate-call}) to propagate the creation of elements: If the set of forward TGG rule matches is non-empty (line~\ref{alg:sync:apply}), we choose one of these matches, apply the corresponding rule, and continue the synchronization process (line~\ref{alg:sync:sync1}). This step is done prior to any repair. The purpose is to create the context which may be needed to make repair rules applicable. An example for such a context creation is the insertion of a new root \package{} which has to be translated into a root \folder{} before applying \firstRRule{} thereafter (see Fig.~\ref{fig:tggFwdRules}). \begin{algorithm*} \begin{algorithmic}[1] \Function{synchronize}{tripleGraph} \State $\mathrm{(brokenCMatches, intactCMatches,fwdMatches) \leftarrow updateMatches(tripleGraph)}$ \label{alg:sync:update} \\ \If{isFinished(tripleGraph, fwdMatches, brokenCMatches))} \label{alg:sync:isFinished-call} \State \Return \EndIf \\ \If{translate(tripleGraph, fwdMatches)} \label{alg:sync:translate-call} \State \Return \EndIf \\ \State $\mathrm{(cMatch, success) \leftarrow repair(tripleGraph, brokenCMatches)}$ \label{alg:sync:repair-call} \If{!success} \State \textbf{throw} InconsistentStateException \label{alg:sync:exception2} \EndIf \State \Return \EndFunction \\ \Function{isFinished}{tripleGraph, fwdMatches, brokenCMatches} \label{alg:sync:isFinished} \If{isEmpty(brokenCMatches) \&\& isEmpty(fwdMatches)} \label{alg:sync:termination} \If{allElementsTranslated(tripleGraph.source)} \State \Return true \label{alg:sync:terminate} \Else{} \State \textbf{throw} InconsistentStateException \label{alg:sync:exception} \EndIf \EndIf \State \Return false \EndFunction \\ \Function{translate}{tripleGraph, fwdMatches} \label{alg:sync:translate} \If{!isEmpty(fwdMatches)} \label{alg:sync:apply} \State fwdMatch = chooseMatch(fwdMatches) \State $\mathrm{tripleGraph \leftarrow applyRule(tripleGraph, fwdMatch, getFWDRule(fwdMatch))}$ \State synchronize(tripleGraph) \label{alg:sync:sync1} \State \Return true \EndIf \State \Return false \EndFunction \\ \Function{repair}{tripleGraph, brokenCMatches} \State $\mathrm{cMatch \leftarrow chooseMatch(brokenCMatches)}$ \label{alg:sync:chooseMatch} \State $\mathrm{scRules \leftarrow getSuitableSCRules(cMatch)}$ \State $\mathrm{scMatches \leftarrow findSCMatches(scRules, cMatch)}$ \\ \While{!isEmpty(scMatches)} \label{alg:sync:while} \State $\mathrm{scMatch \leftarrow chooseMatch(scMatches)}$ \If{isValidMatch(scMatch)} \label{alg:sync:isValid} \State $\mathrm{tripleGraph \leftarrow applyRule(tripleGraph, cMatch, getSCRule(scMatch))}$ \label{alg:sync:sync4} \State synchronize(tripleGraph) \label{alg:sync:sync2} \State \Return (cMatch, true) \EndIf \EndWhile \State \Return (cMatch, false) \EndFunction \end{algorithmic} \caption{eMoflon -- Synchronization Process} \label{alg:sync} \end{algorithm*} If the above cases do not apply, there must be at least one broken consistency match and the corresponding rule application has to be repaired (line~\ref{alg:sync:repair-call}): Hence, we choose one broken consistency match (line~\ref{alg:sync:chooseMatch}) for which a set of suitable repair rules is determined. A broken consistency match includes information about the rule it corresponds to (e.g., the name of the rule). Furthermore, it includes which elements are missing or which filter NACs are violated such that the corresponding application does not exist any more. We calculate the set of matches of \repairRules{} (i.e., forward \shortcutRules{}) that stem from \shortcutRules{} revoking exactly the rule that corresponds to the broken consistency match. In particular, by knowing which elements of a broken rule application still exist in the current source graph, we can stick to those repair rules that preserve exactly the still existing elements. While the calculated set of unprocessed \repairRule{} matches is not empty (line~\ref{alg:sync:while}), we choose one of these matches and check whether it is \emph{valid}. By constructing the partial match of a \repairRule{}, we only need to ensure that none of its \emph{presumed elements} is matched in such a way that a cyclic dependency is introduced. This means that they must not be matched to elements that are dependent of elements to which the \emph{recovered elements} are matched. If a match is valid, we apply the corresponding repair rule and continue the synchronization process (line~\ref{alg:sync:sync2}). If no such rule or valid match is available, an exception is thrown (line~\ref{alg:sync:exception2}). \subsection{Formal properties of the synchronization process.} We discuss the termination, correctness, and completeness of our synchronization algorithm. Our algorithm terminates as long as every forward rule translates at least one element (which is a quite common condition; compare~\cite[Lemma~6.7]{HEOCDXGE15} or \cite[Theorem~3]{Leblebici18}). \begin{theorem} Let a TGG $\mathit{GG}$ with plain, monotonic rules be given. If every derived forward rule of $\mathit{GG}$ has at least one source marking element, our algorithm terminates for any finite input $G\rq{} = (H_S\rq{} \dashleftarrow G_C \rightarrow G_T)$. \end{theorem} \begin{proof} The algorithm terminates -- by either throwing an exception or returning a result -- if at one point both, the set of broken consistency matches and the set of matches for forward rules are empty; compare the function \emph{isFinished} starting in line~\ref{alg:sync:isFinished}. The algorithm is called recursively, always applying a forward rule if a match is available. As every forward rule marks at least one element as translated and forward rules are only matched in such a way that source marking elements are matched to yet untranslated ones, the application of forward rules (lines~\ref{alg:sync:apply} et seq.), i.e., the recursive call of function \emph{translate}, halts after finitely many steps. Moreover, an application of a forward rule never introduces a new broken consistency match: As it neither creates nor deletes elements in the source graph, it cannot delete elements matched by a consistency pattern nor create elements forbidden by one. This means that, as soon as the set of broken consistency matches is empty, the whole synchronization algorithm will terminate. We show that at some point this set of broken consistency matches will be empty or an exception is thrown. Whenever the algorithm is called with an empty set of matches for forward rules, broken consistency matches are considered by applying a repair rule, i.e., by calling the function \emph{repair}. New matches for forward rules can result from this; as discussed above, newly appearing matches for forward rules are unproblematic. However, an application of a repair rule does not introduce a new violation of any consistency match: As it does not create source elements, it cannot introduce violations of filter NACs. And by the condition on valid matches to be non-disabling (condition 2. (a) in Definition~\ref{def:valid-repair-match}), no elements needed by other consistency matches are deleted. Hence, by application of a repair rule, the number of invalid consistency matches is reduced by one and the algorithm terminates as soon as all broken consistency matches are repaired. If there is a broken consistency match that cannot be repaired -- either because no suitable repair rule or no valid match is available -- an exception is thrown and the algorithm stops. \qed \end{proof} \paragraph{Correctness.} Upon termination without exception, our algorithm is correct. \begin{theorem}[Correctness of algorithm]\label{thm:correctness-algorithm} Let a TGG $\mathit{GG}$ with plain, monotonic rules, a triple graph $G = (G_S \leftarrow G_C \rightarrow G_T) \in \mathcal{L}(\mathit{GG})$, and a partial triple graph $G\rq{} = (G_S\rq{} \dashleftarrow G_C \rightarrow G_T)$ that arises by a user edit step on the source graph be given. If our synchronization algorithm terminates without exception and yields $H = (H_S \leftarrow H_C \rightarrow H_T)$ as output, then $H_S = G_S\rq{}$ and $H \in \mathcal{L}(\mathit{GG})$. \end{theorem} \begin{proof} We see immediately that $H_S = G_S\rq{}$ since none of the applied rules modifies the source graph. If the synchronization process terminates without exception, all elements are translated, no matches for forward rules are found, and no consistency match is broken any more. This means that the collected matches of the forward rules form an entirely marking transformation sequence. By Lemma~\ref{lem:emccp-series}, we have to show that this sequence is also consistently marking. Then, the matches of the forward rules that correspond to the matches of the consistency patterns that the incremental pattern matcher has collected encode a transformation sequence that allows to translate the triple graph $(H_S \leftarrow \emptyset \rightarrow \emptyset)$ to a triple graph $(H_S \leftarrow H_C \rightarrow H_T) \in \mathcal{L}(\mathit{GG})$. We assume that the incremental pattern matcher recognizes all broken consistency matches and reports correct matches for forward rules only. This means, throughout the application of forward rules, the set of all valid consistency matches remains consistently marking. We have to show that this is also the case for repair rule applications. If it is, upon termination without exception, there is an entirely and consistently marking sequence of forward rules which corresponds to a triple graph from $\mathit{GG}$ by Lemma~\ref{lem:emccp-series}. Whenever we apply a repair rule we are (at least locally) in the situation of Corollary~\ref{cor:valid-repair-rule-applications}: There is a (maybe empty) sequence of consistently marking forward rule applications and a suitable broken consistency pattern indicates, that a user edit step applying the source rule $r_{\mathit{sc}}^S$ of a short-cut rule $r_{\mathit{sc}}$ has taken place. Applying the repair rule $r_{\mathit{sc}}^F$ at a valid match amounts to replacing the application of rule $r_j^F$, whose consistency pattern was broken, by rule $r^F$ in a consistently marking way. \qed \end{proof} We only informally discuss \emph{completeness}. We understand completeness as follows: for every input $G\rq{} = (H_S \dashleftarrow G_C \rightarrow G_T)$ with $H_S \in \mathcal{L}_S(\mathit{GG})$, we obtain a result $H = (H_S \leftarrow H_C \rightarrow H_T) \in \mathcal{L}(\mathit{GG})$. In general, the above proposed algorithm is not complete. We randomly apply forward rules at available matches (without using backtracking) but the choice and order of such applications can affect the result if the final sequence of forward rule applications leads to a dead-end or translates the given source graph. However, the algorithm is complete whenever the set of forward rules is of such a form that the order of their application does not make a difference (somewhat more formally: they meet some kind of confluence) and the user edit is of the form discussed in Sect.~\ref{sec:basic-setup-algorithm}. Analogous restrictions on forward rules hold for other synchronization processes that have been formally examined for completeness~\cite{HEOCDXGE15,Leblebici18}. Adding filter NACs to the forward rules of a TGG is a technique that can result in such a set of confluent forward rules even if the original set of forward rules is not. Moreover, there are static methods to test TGGs for such a behaviour~\cite{ALST14,HEOCDXGE15}; they check for sufficient but not for necessary criteria. If it is known that the set of forward rules of a given TGG guarantees completeness and the edit is of a suitable kind, a thrown exception during our synchronization process implies that $H_S \notin \mathcal{L}_S(\mathit{GG})$. \subsection{A synchronization example} \begin{figure*}% \includegraphics[width=\textwidth]{Diagram/Example-Sync-Alg-adapted.pdf}% \caption{Example of our proposed synchronization algorithm. Grey background indicates broken consistency matches.}% \label{fig:algorithm-example}% \end{figure*} We illustrate our synchronization algorithm with an example illustrated in Fig.~\ref{fig:algorithm-example}. For simplicity, we neglect the \textsf{content} attribute and concentrate on the structural behaviour. As a starting point, we assume that a user edits the source graph of the triple graph depicted in Fig.~\ref{fig:algorithm-example}~(a) (in the following, we will refer to the triple graphs occurring throughout the algorithm just by their numbers). She adds a new root package above \rootP{}, removes the link between \packages{} \rootP{} and \subP{}, and creates a further class \texttt{c2}. All these changes are specified by either a source rule of the TGG or the source rule of a derived short-cut rule. The resulting triple graph is depicted in~(b). The elements in front of the grey background are considered to be inconsistent, due to a broken consistency match. Furthermore, \texttt{c2} and \texttt{nRootP} are not translated, yet. In the first two passes of the algorithm, the two available matches for forward rules are applied (in random order): \thirdTGGForwardRule{} translates the newly added \class{} \texttt{c2} and \firstTGGForwardRule{} translates the \package{} \texttt{nRootP}; this results in the triple graph (c). Note that the last rule application creates a match for the repair rule \firstRRule{}. This is the reason why we start our synchronization process with applications of forward rules. The incremental pattern matcher notifies about two broken consistency matches, which are dealt with in random order. \rootP{} is no longer a root package (which is detected by a violation of the according filter NAC in the consistency pattern) and \subP{} is now a root package (which is detected by the missing incoming edge). Both violations are captured by repair rules, namely \firstRRule{} and \secondRRule{}, whose applications lead to~(d) and (e). The algorithm terminates with a triple graph that belongs to the TGG. \subsection{Prospect: Support of further kinds of editing and advanced TGG features} \label{sec:prospect} We shortly describe the support of further kinds of editing and more advanced features of TGGs by our approach to synchronization, namely attributed TGGs, rules with NACs, and support for additional attribute constraints. \paragraph{Further kinds of editing.} In our implementation (see Sect.~\ref{sec:implementation}), we do not only support the addition of elements and propagation of edits that correspond to source rules of derived edit rules. Actually, we do not make any assumptions about the kind of editing. This is achieved by incorporating the application of repair rules into the algorithm suggested by Leblebici et al.~\cite{LAFVS17,Leblebici18}, which has also been proved to be correct and to terminate. The implemented algorithm first tries to apply a forward or repair rule. If there is none available with a valid match, the algorithm falls back to revoking of an invalid rule application. This means that all elements that have been created by this rule application are deleted (and adjacent edges of deleted nodes are implicitly deleted as well). In line with that revoking of invalid rule applications, it also allows for implicit deletion of adjacent edges in the application of repair rules. In that way, the application of a repair rule might trigger new appearances of broken consistency matches. We are convinced that \emph{correctness} is not affected by that more general approach: Inspecting the proofs of Corollary~\ref{cor:valid-repair-rule-applications} and Theorem~\ref{thm:correctness-algorithm}, the key to correctness is that the sequences of currently valid consistency matches remain consistently marking. That is achieved via the conditions on matches for repair rules to be \emph{reversing}, \emph{context-preserving}, and \emph{creation-preserving}. Dropping the condition to be \emph{non-disabling} (by implicitly deleting adjacent edges) does not effect correctness, therefore. However, proving termination in that more general context is future work. \paragraph{Advanced features.} The {\em attribution of graphs} can be formalized by representing data values as special nodes and the attribution of nodes and edges as special edges connecting graph elements with these data nodes~\cite{EEPT06}. As the rules of a TGG are monotonic, they only set attribute values but never delete or change them. (The deletion or change of an attribute value would include the deletion of the attribution edge pointing to it.) The formal construction of short-cut rules is based purely on category-theoretic concepts, which can be directly applied to rules on attributed triple graphs as well. The properties proven for short-cut rules in~\cite{FKST18} are valid also in that case.\footnote{To be precise, in~\cite{FKST18}, all proofs are elaborated for the case of monotonic rules in an \emph{adhesive} category. Attributed triple graphs are \emph{adhesive HLR} which is a weaker notion. However, inspecting the proofs, this does not make any difference as long as the category has so-called \emph{effective pushouts}. This is known to be the case for attributed (triple) graphs; compare, e.g.,~\cite[Remark~5.57]{EEGH15}.} Hence, we can freely apply the construction of short-cut rules and derivation of repair rules to attributed TGGs. In fact, our implementation already supports attribution. For the propagation of attribute changes (made by a user), however, we rely on the inherent support eMoflon offers, which is discussed in Sect.~\ref{sec:implementation}. Deriving repair rules to propagate such changes is possible in principle but remains future work. In practical applications, TGGs are often not only attributed but also equipped with \emph{attribute constraints}. These enable the user to, for example, link the values of attributes of correlated nodes. eMoflon comes with facilities to detect violations of such constraints and offers support to repair such violations. In our implementation, we rely on these features of eMoflon to support attribute constraints but do not contribute additional support in our newly proposed synchronization algorithm. To summarize, while fully formalized for the case of plain TGG rules without attribution, our implementation already supports the synchronization of attributed TGGs with additional attribute constraints. As these additional features do not affect our construction of short-cut and repair rules, we do not consider them (yet) to improve the propagation of attribute changes (that may lead to violations of attribute constraints). Instead, we rely on the existing theory and facilities of eMoflon as introduced by Anjorin et al.~\cite{AVS12}. In contrast, while computing short-cut and repair rules of rules with NACs is straightforward, adapting our synchronization algorithm to that case is future work and no tool support is available yet.
{'timestamp': '2020-06-01T02:10:47', 'yymm': '2005', 'arxiv_id': '2005.14510', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14510'}
arxiv
\section{Introduction} \subfile{sections/introduction} \section{Background} \subfile{sections/background} \section{Related Work} \subfile{sections/relatedwork} \section{Experimental Setup} \subfile{sections/experimentalsetup} \section{Baseline Experiment} \subfile{sections/baselineexperiment} \section{Reinforcement Learning Experiment} \subfile{sections/qlearningexperiment} \section{Conclusion} \subfile{sections/conclusion} \bibliographystyle{./bibliography/IEEEtran} \subsection{Knative Serverless Platform} \label{subsec:Knative} As an open-source serverless platform, Knative provides a set of Kubernetes-based middleware components to support deploying and serving of serverless applications, including the capability to automatically scale resources on demand \cite{knativedocsautoscaling}. The auto-scaling function is implemented by different serving components, described by the request flow in \Cref{fig:knative-autoscaling} based on Knative v0.12. If a service revision is scaled to zero, i.e. the service deployment is reduced to a replica of null operating pods, the ingress gateway forwards incoming requests first to the activator \cite{knativedocsautoscaling}. The activator then reports the information to the autoscaler, which instructs the revision's deployment to scale-up appropriately. Further, it buffers the requests until the user pods of the revision become available, which can cause cold-start costs in terms of latency, as the requests are blocked for the corresponding time. In comparison, if a minimum of one replica is maintained active, the activator is bypassed and the traffic can flow directly to the user pod. \begin{figure}[t] \centering \includegraphics[width=8.5cm]{images/knative_autoscaling3.pdf} \caption{Simplified request flow in Knative} \label{fig:knative-autoscaling} \end{figure} When the requests reach the pod, they are channeled by the \emph{queue-proxy} container and, subsequently, processed in the \emph{user-container}. The queue-proxy only allows a certain number of requests to enter the user-container simultaneously, and queues the requests if necessary. The amount of parallel processed requests is specified by the \textit{concurrency} parameter configured for a particular revision. By default, the value is set to a concurrency target of 100, defining how many parallel requests are preferred per user-container at a given time. However, the user can explicitly restrict the number of concurrent requests by specifying a value between 0 and 1000 for the \textit{concurrency limit}.\footnote{A value of 0 allows unlimited concurrent requests and therefore results in no scaling \cite{openshiftknative}.} Further, each queue-proxy measures the incoming load and reports the average concurrency and requests per second on a separate port. The metrics of all queue-proxy containers are scraped by the autoscaler component, which then decides how many new pods need to be added or removed to keep the desired concurrency level. \subsection{Q-learning} RL refers to a collection of trial-and-error methods in which an agent is trained to make good decisions by interacting with his environment and receiving positive or negative feedback in form of rewards for a respective action. A popular RL algorithm is the model-free Q-learning. Q-learning stepwise trains an approximator $Q_{\theta}(s,a)$ of the optimal action-value function $Q^*$. $Q_{\theta}(s,a)$ specifies the cumulated reward the agent can expect when starting in a state $s$, taking an action $a$, and then acting according to the optimal policy forever after. By observing the actual reward in each iteration, the optimization of the Q-function is performed incrementally per step $t$: \[Q(s_t,a_t)\xleftarrow{}(1-\alpha)Q(s_t,a_t) + \alpha[r_t + \gamma \max_{a} Q(s_{t+1},a)]\] $\alpha$ describes the learning rate, i.e. to what extent newly observed information overrides old information and $\gamma$ a discount factor that serves to balance between the current and future reward. As RL is a trial-and-error method, during training, the agent has to choose between the exploration of a new action and the exploitation of the current best option \cite{sutton2018rl}. In research, this is often implemented with an $\epsilon$-greedy strategy, where $\epsilon$ defines the probability of exploration that usually decreases as the learning process advances \cite{rossi2019horizontal, mnih2013playing}. With a probability of $1-\epsilon$, the agent selects based on the optimal policy and chooses the action that maximizes the expected return from starting in $s$, i.e. the action with the highest Q-value: \[a^*(s) = \arg \max_{a} Q^*(s,a)\] In the basic algorithm, the Q-values for each state-action combination are stored in a lookup table, the so-called \textit{Q-table}, indexed by states and actions. The tabular representation of the agent's knowledge serves as a basis for decision-making during the entire learning episode. \end{document} \subsection{Design} As outlined in the previous section, we use the application parameters \emph{bloat}, \emph{prime} and \emph{sleep} to simulate varying workload characteristics. Starting with a no-operation workload where no parameters are passed, the memory allocation and CPU load were gradually increased for each new experiment. The step size of the memory allocating parameter was aligned with the memory buckets commonly used for the standard pricing model of serverless platforms. To simulate compute-intensive and longer-lasting requests, different prime and sleep parameters were chosen correspondingly. The detailed values are specified in \Cref{tab:concurrencyperformance}. Per profile, we run performance tests for different concurrency levels according to the process flow described in \Cref{{fig:processflow}}. Theoretically, the concurrency limit can take all values between 0 and 1000. To keep the experiments computationally feasible, we proceed in steps of 20, starting at a concurrency limit of 10 and ending at 310. As stated in related literature, we focus on latency and throughput as key performance measures of serverless applications \cite{li2019understanding}. Average throughput is defined by requests per second (RPS), mean latency refers to the average time in seconds taken to return a response to a request. To cover tail latency, we include the 95th percentile of latencies of all requests as an additional metric. Furthermore, each test is repeated ten times to compensate for outliers or other fluctuations, before the concurrency is updated to the next limit. \subsection{Results} We structure the analysis of the baseline experiment results in three parts. First, we examine the behavior of the individual workload profiles under different concurrency configurations. Second, we focus on the relation of the target variables throughput and latency during the tests. Finally, further metrics about resource utilization on container and pod level are analyzed. As described above, we conducted the experiment for different combinations of the three parameters to simulate possible use cases. Table \ref{tab:concurrencyperformance} gives an overview of the outcomes with the concurrency limit that lead to the optimal test result in terms of one of the performance measures. Due to the numerous uncontrollable factors that influence the performance of the cluster, each result forms a snapshot in time. The respective workload configuration is described by the three columns on the left. Taking all tests into account, the smallest possible concurrency of 10 is the most common configuration that resulted in the best performance across all three indicators. Interestingly, this does not correspond to the default setting of the KPA where a target concurrency value of 100 is preferred \cite{knativekpaconfig}. In particular, workloads that consume memory exclusively perform better with fewer parallel requests per pod instance, e.g tests \#\rom{2}, \#\rom{9}, \#\rom{16} and \#\rom{17}. Similar observations are made for workloads with additional low CPU usage, i.e. lower \emph{prime} parameter, as in tests \#\rom{3} and \#\rom{10}. Deviations can be observed when the requests pause for a certain time. These workloads result in higher throughput and lower mean and tail latency when a higher concurrency is chosen, e.g tests \#\rom{7}, \#\rom{8} and \#\rom{14}. \begin{table}[t] \begin{threeparttable} \caption{Concurrency Performance Tests } \label{tab:concurrencyperformance} \begin{centering} \begin{tabular}{|c|c|c|c|c|c|c|} \hline \textbf{Test}&\multicolumn{3}{|c|}{\textbf{Workload Profile}}&\multicolumn{3}{|c|}{\textbf{Conc. Limit Yielding Best Perf.}} \\ \cline{2-7} \textbf{\#} & \textbf{\textit{bloat}}$^*$ & \textbf{\textit{prime}} & \textbf{\textit{sleep}}$^*$ & \textbf{\textit{thrghpt}} & \textbf{\textit{mean lat.}} & \textbf{\textit{95th lat.}}\\ \hline \rom{1} & - & - & - & 50 & 50 & 70 \\ \hline \rom{2} & 128 & - & - & 30 & 30 & 30 \\ \hline \rom{3} & 128 & 1000 & - & 10 & 10 & 10\\ \hline \rom{4} & 128 & 10.000 & - & 30 & 30 & 10\\ \hline \rom{5} & 128 & 100.000 & - & 10 & 10 & 10\\ \hline \rom{6} &128 & 1000 & 1000 & 110 & 110 & 150 \\ \hline \rom{7} & 128 & 10.000 & 1000 & 70 & 70 & 70 \\ \hline \rom{8} & 128 & 100.000 & 1000 & 110 & 110 & 110 \\ \hline \rom{9} & 256 & - & - & 10 & 10 & 10 \\ \hline \rom{10} & 256 & 1000 & - & 10 & 10 & 10 \\ \hline \rom{11} & 256 & 10.000 & - & 10 & 10 & 10 \\ \hline \rom{12} & 256 & 100.000 & - & 10 & 10 & 10 \\ \hline \rom{13} & 256 & 1000 & 1000 & 50 & 50 & 50 \\ \hline \rom{14} & 256 & 10.000 & 1000 & 110 & 110 & 110 \\ \hline \rom{15} & 256 & 100.000 & 1000 & 10 & 10 & 30 \\ \hline \rom{16} &512 & - & - & 10 & 10 & 10\\ \hline \rom{17} & 1024 & - & - & 30 & 30 & 30\\ \hline \end{tabular} \begin{tablenotes} \small \item $^*$ \textit{bloat} is defined in MB and \textit{sleep} in milliseconds. \end{tablenotes} \label{tab1} \end{centering} \end{threeparttable} \end{table} Depending on the workload, the distance between the optimal configuration and the second best concurrency can be very small, which becomes more evident when analyzing a single test in detail. Fig. \ref{fig:thrpt_lat} shows the result of test \#\rom{7}, which is examined representatively. Although the individual measurement points fluctuate, clear trends are identified in the average values. A significant increase in throughput can be observed when the concurrency limit is raised to 70. This setting also yields the lowest value for mean latency, differing from the second-best value at concurrency 50 by only 80 milliseconds. The distance becomes more critical when considering the tail latency of the $95^{th}$ percentile, where a request takes more than 740 milliseconds on average longer to receive a response when compared to the most effective configuration. At a concurrency of 10, the difference amounts to almost 3 seconds, further underlining the performance variations caused by the different settings. The greatest slowdown in tail latency in this test occurs at a concurrency of 310 with more than 3.7 seconds. Besides, the overall performance decreases strongly when the concurrency limit exceeds a level of 210. This tendency can be found across the majority of tests, indicating that due to the high simultaneous processing of many requests, only a limited amount of resources are available for a single request. Further observations show that with increasing memory utilization, i.e. the bloat parameter, performance tends to drop at lower concurrency limits. In some cases, additionally, the success ratio strongly declines. For example in test \#\rom{16}, from a concurrency of 170 onwards, more than 10\% of the requests received non-successful responses. In test \#\rom{17} accordingly, this output can be observed from a concurrency of 90 onwards. \begin{figure}[t] \centering \includegraphics[width=7.5cm]{images/test_7_thrpt_lat.pdf} \caption{Performance of workload test \#\rom{7}} \label{fig:thrpt_lat} \end{figure} Focusing on the target metrics, the tests show that adjusting the concurrency limit to an appropriate setting can yield significant improvements in throughput and latency. Furthermore, an inverse behavior of the measures can be observed within the tests. For the previously considered test \#\rom{7}, the results indicate a significant negative correlation of throughput and mean latency of $-0.989$, and a similar correlation for throughput and $95^{th}$-percentile latency of $-0.916$.\footnote{For all statistical tests, Pearson correlation coefficient is used with a two-sided p-value for testing non-correlation and an alpha level of $.001$.} This strong negative relationship between the metrics is found across all tests, with significant correlation coefficients ranging from $-0.995$ to $-0.748$.\footnote{Except for test \#\rom{1} and \#\rom{13} with significant correlations of throughput and tail latency of $-0.629$, and throughput and mean latency of $-0.677$.} Subsequently, an improvement in throughput usually results in a lower and more favorable latency. This finding implies that there is no need to make trade-offs between different target metrics when adjusting the concurrency. Instead, the problem can be reduced to one objective metric, representing the others. \begin{comment} To explore the impact on resource consumption in more detail, CPU and memory usage was measured for different infrastructure components. Fig. \ref{fig:metrics_cpu_avg_sum} shows the average CPU usage of a user pod, and, broken down to a more detailed level, the usage of the two containers queue-proxy and user-container, which are deployed in each user pod. The user-container, which runs the application and processes the requests, has a linear increase in CPU consumption relative to the number of concurrent requests. The queue-proxy, which manages the forwarding of requests to the application and limiting of the concurrency, also shows an increase, however with a lower positive slope. Considering only the containers, this implies that the higher the concurrency, the higher the utilization of a single queue-proxy, but the lower the total usage on the cluster, due to the relatively fewer number of containers, as shown by the green dashed line in Fig. \ref{fig:metrics_cpu_avg_sum}. Since the consumption of a user-container is relatively higher, this has no significant effect on the overall usage at pod level, see mauve colored line. \begin{figure}[t] \centering \includegraphics[width=8cm]{images/test7_metrics_cpu_avg_sum.pdf} \caption{CPU util. of user-container, queue-proxy and user pod on average per container/ pod instance (avg) and the sum over all container/ pod instances (sum) based on workload test \#\rom{7}} \label{fig:metrics_cpu_avg_sum} \end{figure} Similar patterns occur when analyzing memory consumption. However, in the user-container as in the queue-proxy a lower growth rate in the average consumption with increasing concurrency can be seen, resulting in the highest total consumption of all user pods at a concurrency of 10. To summarize, a variation of the concurrency limit can influence the performance and in particular the average resource consumption of a container. Although performance may be affected by numerous latent factors that are difficult to control, this baseline experiment reveals the potential for performance-enhancing measures through a more precise auto-scaling mechanism. \end{comment} \end{document} \subsection{Cloud Architecture} The overall architecture of our experiment is illustrated in Fig. \ref{fig:expsetup}. To test the auto-scaling capabilities in an isolated environment, we set up two separate Kubernetes clusters, using IBM Cloud Kubernetes Service (IKS). On the \textit{service cluster}, the sample service used for the experiments is deployed. The cluster contains 9 nodes with 16 vCPU and 64 GB memory each, designed to provide sufficient capacity to host all Knative components and avoid performance limitations. The \textit{client cluster} consists of one node with 16 vCPU and 64 GB memory responsible for sending requests to the service cluster to generate load. The agent manages the activities on both clusters, including the configuration updates of the sample service based on collected metrics, and coordinates the process flow of the experiment, taking the role of an IKS user. \begin{figure}[t] \centering \includegraphics[width=8cm]{images/cluster_architecture_3.pdf} \caption{Architectural setup including the information flow} \label{fig:expsetup} \end{figure} The Knative resources are installed on the service cluster (version v0.12), including the serving components explained in Section \ref{subsec:Knative}, which control the state of the deployed sample service and enable auto-scaling of additional pods on demand. Using the trial-and-error method of RL in the second experiment, we update the concurrency configuration of the service in each iteration. To comprehensively test the auto-scaling capability, we activated the scale-to-zero functionality in the autoscaler's configmap, which requires a cold start in each iteration. We further increased the replica number of ingress gateways, which handle load balancing, to bypass performance issues and to focus our studies exclusively on the auto-scaling functionalities. \subsection{Workload} Serverless computing is used for a variety of applications, accompanied by different resource requirements. For example, the processing of video and image material or highly-parallel analytical workloads, such as MapReduce jobs, demand considerable memory and computing power. Other applications, such as chained API compositions or chatbots, tend to be less compute-intensive but may require longer execution or response time. To investigate the concurrency impact of many different workloads, we generate a synthetic, stable workload profile simulating serverless applications. We use Knative's example \emph{Autoscale-go} application for this purpose, which allows different parameters to be passed with the request to test incremental variations of the workload characteristics and thus emulate varying CPU- and memory- intensive workloads \cite{knativeautoscale-go}. The three application parameters are \emph{bloat}, \emph{prime} and \emph{sleep}, wherein the first is used to specify the number of megabytes to be allocated and the second to calculate the prime numbers up to the given number, to create either memory- or compute-intensive loads. The sleep parameter pauses the request for the corresponding number of milliseconds, as in applications with certain waiting times. \subsection{Process Flow} \label{subsec:processflow} The basic process flow of one iteration is illustrated in Fig. \ref{fig:processflow}. In each iteration the agent sends a concurrency update to the service cluster, which accordingly creates a new revision with the respective concurrency limit. When the service update is complete, the agent sends the start signal to the client cluster, which begins issuing parallel requests against the service cluster. To simulate a large number of user requests at the same time, we use the HTTP load testing tool \emph{Vegeta}, which features sending HTTP requests at a constant rate. In the experiment, 500 requests are sent simultaneously over a period of 30s to ensure sufficient demand for scaling and sufficient time to provide additional instances. After the last response is received, Vegeta outputs a report of the test results, including information on latency distribution of requests, average throughput and success ratio of responses. The performance measures are then stored by the agent. Additionally, the agent crawls metrics from the Knative monitoring components, exposed via a Prometheus-based HTTP API within the cluster, to get further information about resource usage at cluster, node, pod and container level. Using this data, the concurrency update is chosen to proceed to the next iteration. \begin{figure}[t] \centering \includegraphics[width=8.5cm]{images/Process_flow2.pdf} \caption{Process flow} \label{fig:processflow} \end{figure} \end{document} \subsection{Design} The process flow is based on the procedure from section \ref{subsec:processflow}, extended with a more sophisticated logic of the agent. Instead of incrementally increasing the concurrency, the agent uses knowledge of the system environment (states) to test different concurrency updates (actions) and evaluates them by receiving scores (reward). In each iteration, the environment is defined by the current state, which, should provide a complete description of the system dynamics including all relevant information for optimal decision making. Due to the large number of factors influencing performance, e.g. hidden cluster activities or network utilization, this is neither traceable nor computationally feasible in the used Q-learning algorithm. Therefore, we break down our state space $S$ into three key features. We define $S$ at time step $i$ as the combination of the state variables $s_i$ = $(conc_i, cpu_i, mem_i)$, where $conc_i$ depicts the concurrency limit, $cpu_i$ is the average CPU utilization per user-container and $mem_i$ is the average memory utilization per user-container. The selection of the features is aligned with related research, with $conc_i$ as the equivalent of the number of VMs in VM auto-scaling approaches \cite{barrett2013applying, bitsakos2018derp}. $cpu_i$ and $mem_i$ serve as a direct source of information about the resource utilization of a respective workload. Since both CPU and memory utilization are continuous numbers, we discretize them into bins of equal size. In each state $s_i \in S$, we define $A(s_i)$ as the set of valid actions, where $A$ is the set of all actions. The agent can choose between decreasing, maintaining or increasing the concurrency limit by 20, i.e. $A$ = $\{-20,0,20\}$. If the agent reaches the endpoints on the concurrency scale, i.e. the minimum or maximum concurrency, the action space in this state is reduced accordingly by the non-executable action. After each iteration, the agent receives an immediate reward according to the performance achieved through the action. In related literature, the reward is often based on the distance or ratio between the performance measure and a certain \textit{Service Level Agreement}, such as a throughput or response time target value \cite{horovitz2018efficient, dutreilh2011using}. Since there is no target level to be achieved nor prior information about the performance given in our problem definition, we define an artificial reference value $ref\_value$ as the best value obtained to date. Due to the permanent, albeit minor fluctuations in the measures, we propose a tolerance band around the reference value to avoid weighting minor non-relevant deviations. Furthermore, the results from the preliminary study have shown a highly negative correlation between throughput and latency, i.e. higher throughput usually leads to lower and therefore better latency. This relation in turn allows to focus exclusively on throughput ($thrghpt$) as one single objective. The calculation of the reward $r$ in time step $i$ is as follows. \[ r_i = \begin{cases} \frac{thrghpt_i}{ref\_{value}} & \begin{array}{r@{}} \text{if $thrghpt_i$} \leq \text{ref\_value} \cdot {0.95} \\ \text{or $thrghpt_i$} \geq \text{ref\_value} \cdot {1.05} \end{array}\\ 1 & \begin{array}{r@{}} \text{else} \end{array}\\ \end{cases} \] Q-learning is initiated with the following parameters. A learning rate $\alpha$ = 0.5 is chosen to balance newly acquired and existing information, a discount factor $\gamma$ = 0.9 to ensure that the agent strives for a long-term high return. To encourage the exploration of actions at the beginning of training, we implement a decaying $\epsilon$-greedy policy starting at iteration 50 with $\epsilon$ = 1 and then slowly decrease over time by a decay factor of 0.995 per iteration. The minimum exploration probability is set to $\epsilon_{min}$ = 0.1, to allow for the detection of possible changes in the system. The knowledge the agent acquires is stored in a Q-table and updated each iteration. To examine whether the model can effectively learn the concurrency values identified in section \ref{sec:baseline} as high throughput configurations, the results are analyzed representatively based on workload test \#\rom{7} and \#\rom{10}. The former test showed high performance at a concurrency limit of 70, while the second reached the best test results at an edge concurrency of 10. \subsection{Results} \begin{figure}[t] \centering \includegraphics[width=8cm]{images/qlearning_10_thrpt_conc_epsilon.pdf} \caption{Performance of Q-learning model, workload \#\rom{10}} \label{fig:qlearning1} \end{figure} \begin{figure}[t] \centering \includegraphics[width=8cm]{images/qlearning_7_thrpt_conc_epsilon.pdf} \caption{Performance of Q-learning model, workload \#\rom{7}} \label{fig:qlearning2} \end{figure} First, we analyze the results to examine the suitability of the proposed Q-learning-based model to fine-tune the auto-scaling. Second, we evaluate the performance of the approach in terms of throughput improvements compared to Knative's default auto-scaling configuration. Based on workload profile \#\rom{10}, Fig. \ref{fig:qlearning1} shows in detail how the agent applies RL logic to incrementally change the concurrency and to adjust it as the training progressed. Beginning at concurrency 170, random exploration leads to a moderate decline of the concurrency limit in the first 30 iterations. This results in an improvement in throughput in this test, captured by the rewards and corresponding Q-values for each state-action combination. The most effective scaling policy of 10 parallel requests per container is first reached in iteration 121. Nevertheless, due to the $\epsilon$-greedy strategy, exploratory actions are chosen, which might differ from the down-scaling decision and cause the agent to deviate from a good strategy. As training progresses, a trend towards performance-enhancing concurrency configurations can be observed, indicating the agent is more likely to exploit the optimal decision rather than exploring. After 330 iterations, the concurrency stabilizes at a limit of 10 parallel requests per container, implying the agent has learned the correct scaling policy, according to the results from section \ref{sec:baseline}. Due to the minimum $\epsilon$ = 0.1, exploration still rarely occurs to ensure the agent can respond to changes in the environment. A different learning process of the proposed Q-learning approach can be observed for workload \#\rom{7}, depicted in Fig. \ref{fig:qlearning2}. The varying concurrency curve shows the initial strategy of the agent exploring first the higher state space before proceeding with lower concurrency limits. After 250 iterations the exploitation phase outweighs and the concurrency gradually levels off. In comparison to workload \#\rom{10}, where the algorithm's scaling policy converges to a single concurrency limit, the configuration here fluctuates, mainly between 50 and 70, and retains this pattern. Further differences between the test results arise from the throughput metric, which shows strong fluctuations between 230 and 415 RPS across all iterations. The deviations, which also appear within one concurrency setting, considerably impair the agent's ability to evaluate suitable state-action-pairs via the reward function. Nevertheless, the agent is able to narrow down the scaling range to a limited number of values at which it identified the best outcomes in terms of throughput, and which agrees with the result of the baseline experiment in Section \ref{sec:baseline}. \begin{comment} \begin{figure}[t] \centering \includegraphics[width=8cm]{images/qlearning_10_reward_thrpt.pdf} \caption{Throughput and reward of workload \#\rom{10}} \label{fig:qlearning10reward} \end{figure} \begin{figure}[t] \centering \includegraphics[width=8cm]{images/qlearning_7_reward_thrpt.pdf} \caption{Throughput and reward of workload \#\rom{7}} \label{fig:qlearning7reward} \end{figure} \end{comment} To evaluate the proposed scaling policies, we benchmark the average performance of the Q-learning-based approach with the static default setting. For this purpose, the same experimental setup is used as in the Q-learning test, except for the auto-scaling configuration, where the original setting of a concurrency target of 100 is applied \cite{knativedocsautoscaling}.\footnote{Additionally, the container target percentage is set to 0.7 as in the default configmap.} Fig. \ref{fig:qlearning_avgthrpt} depicts the average throughput up to the respective iteration of the Q-learning model and the default configuration for the two considered workloads. Both result in the Q-learning model outperforming the test based on Knative's standard settings. Considering workload \#\rom{7} first, the model requires approximately 150 iterations until the average performance reaches default-level. Subsequently, the throughput increases to an average of 400 RPS providing a minor advantage of 20 RPS compared to the standard system. A more significant enhancement shows workload \#\rom{10}. While in the first 10 iteration the default settings alternate between 350 and 440 RPS, converging to an average of about 393 RPS, the performance of our model is initially lower. However, with ongoing learning the average throughput improves and excels already from iteration 10 onwards. After 600 iterations, the presented Q-learning based model reaches an average throughput of 740 RPS, hence achieving more than 80\% of the performance of the default setting, which stabilizes at 390 RPS on average. To summarize the results, the proposed model learned within finite time a scaling policy that outperforms the default Knative configuration in terms of throughput, proving the Q-learning-based approach is well-feasible to refine the auto-scaling mechanism. \begin{figure}[t] \centering \includegraphics[width=8cm]{images/qlearning_avgthroughput.pdf} \caption{Comparison of average throughput of the Q-learning model and the Knative default auto-scaling setting} \label{fig:qlearning_avgthrpt} \end{figure} \end{document} \subsection{Serverless computing} With the growing number of serverless computing offerings, there has been an increasing interest of the academic community in comparing different solutions, with scalability being one of the key elements of evaluation \cite{li2019understanding}. In multiple works, different propriety serverless platforms were benchmarked, including their ability to scale, focusing on Amazon Lambda, Microsoft Azure Functions \cite{lloyd2018serverless}, along with Google Cloud Functions \cite{wang2018peeking} and additionally IBM Cloud Functions \cite{lee2018evaluation}. Similar studies have been carried out in the area of open-source serverless frameworks, with greater attention paid to the auto-scaling capabilities. Mohanty et al. \cite{mohanty2018evaluation} evaluated Fission, Kubeless, and OpenFaaS and concluded that Kubeless provides the most consistent performance in terms of response time. Another comparison of both qualitative and quantitative features of Kubeless, OpenFaas, Apache Openwhisk, and Knative, comes to the same conclusion, albeit generally indicating the limited user control over custom Quality of Service (QoS) requirements \cite{palade2019evaluation}. These studies solely consider the default auto-scaler Kubernetes HPA. Possible adjustments to the auto-scaling mechanism itself are not further examined. Li et al. \cite{li2019understanding} propose a more concrete distinction between resource-based and workload-based scaling policies. The authors compare the performance of different workload scenarios using the tuning capability of concurrency levels in Knative and clearly suggest further investigation of the applicability of this auto-scaling capability, which also motivates this research. \subsection{Auto-scaling} As elasticity is one of the main characteristics of the increasing adaption of cloud computing, the automatic, on-demand provisioning and de-provisioning of cloud resources have been the subject of intensive research in recent years \cite{singh2019research}. We discuss related work under two aspects: first, the underlying theories on which auto-scaling is built with a focus on RL, and second, the entities being scaled. To classify numerous techniques at the algorithmic level, different taxonomies were proposed, where the predominant categories are threshold-based rules, queuing theory and RL \cite{lorido2014review,singh2019research}. In the former, scaling decisions are made on predefined thresholds and are most popular among public cloud providers, e.g. Amazon ECS \cite{AWSservicescaling}. Despite the simplistic implementation, identifying suitable thresholds requires expert knowledge \cite{singh2019research}, or explicit application understanding \cite{dutreilh2010data}. Queuing theory has been used to mathematically model applications \cite{lorido2014review}. As they usually impose a stationary system, the models are less reactive towards changes \cite{lorido2014review}. In contrast, RL offers an interesting approach through online learning of the most suitable scaling action and without the need for any a-priori knowledge \cite{lorido2014review}. Many authors have therefore investigated the applicability of model-free RL algorithms, such as Q-learning, in recent years \cite{rossi2019horizontal}. Dutreihl et al. \cite{dutreilh2010data} show that although Q-learning based VM controlling requires an extensive learning phase and adequate system integration, it can lead to significant performance improvements compared to threshold-based auto-scaling, since thresholds are often set too tightly while seeking for the optimal resource allocation. To combine the advantages of both, Q-learning itself can be used to automatically adapt thresholds to a specific application \cite{horovitz2018efficient}. In terms of the entity being scaled, RL has been mostly applied to policies for VM allocation and provisioning, e.g. in \cite{bitsakos2018derp}. With the emergence of container-based applications, this field has become a greater focus of research \cite{rossi2019horizontal}. In both areas, the scope of action is concentrated mainly on horizontal (scale-out/-in) \cite{horovitz2018efficient}, vertical scaling (scale-up/-down) \cite{rao2011distributed}, or the combination of both \cite{rossi2019horizontal}. However, little research has been done in areas that extend the classic auto-scaling problem of VM or container configuration. As a novel approach we investigate the applicability of Q-learning to request-based auto-scaling in a serverless environment. Differently from the existing work on direct vertical or horizontal scaling with RL, we propose a model that learns an effective scaling policy by adapting the level of concurrent requests per container instance to a specific workload. \end{document}
{'timestamp': '2020-06-01T02:07:22', 'yymm': '2005', 'arxiv_id': '2005.14410', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14410'}
arxiv
\section{Introduction} Machine learning (ML) \cite{bishop_pattern_2011,cover_elements_1991,hastie2009elements,hundred} refers to a broad field of study, with multifaceted applications of cross-disciplinary breadth. ML {is a subset of Artificial Intelligence (AI) which} ultimately aims at developing computer algorithms that improve automatically through experience. The core idea is that systems can learn from data, so as to identify distinctive patterns and make consequently decisions, with minimal human intervention. The range of applications of ML methodologies is extremely vast \cite{sutton2018reinforcement,graves2013speech,sebe2005machine,grigorescu2020survey}, and still growing at a steady pace due to the pressing need to cope with the efficiently handling of big data \cite{chen2014big}. Biomimetic approaches to sub-symbolic AI \cite{rosenblatt1961principles} inspired the design of powerful algorithms. These latter sought to reproduce the unconscious process underlying fast perception, the neurological paths for rapid decision making, as e.g. employed for faces \cite{meyers2008using} or spoken words \cite{caponetti2011biologically} recognition. An early example of a sub-symbolic brain inspired AI was the perceptron \cite{rosenblatt1958perceptron}, the influential ancestor of deep neural networks (NN) \cite{bengio2007greedy,Goodfellow-et-al-2016}. The perceptron is indeed an algorithm for supervised learning of binary classifiers. It is a linear classifier, meaning that its forecasts are based on a linear prediction function which combines a set of weights with the feature vector. Analogous to neurons, the perceptron adds up its input: if the resulting sum is above a given threshold the perceptron fires (returns the output the value 1) otherwise it does not (and the output equals zero). Modern multilayer perceptrons, account for multiple hidden layers with non-linear activation functions. The learning is achieved via {minimizing the classification error.} {Single or multilayered perceptrons should be trained by examples \cite{bengio2007greedy,hinton2006fast,rumelhart1988learning}. Supervised learning requires indeed a large set of positive and negative examples, the training set, labelled with their reference category.} The perceptrons' acquired ability to perform classification is eventually stored in a finite collection of numbers, the weights and thresholds that were learned during the successive epochs of the supervised training. To date, it is not clear how such a huge collection of numbers (hundred-millions of weights in state of the art ML applications) are synergistically interlaced for the deep networks to execute the assigned tasks, with an exceptional degree of robustness and accuracy \cite{xie2020explainable,hinton2015distilling,erhan2010understanding}. Starting from these premises, the aims of this paper are multifold. On the one side, we will develop a novel learning scheme which is anchored on reciprocal space. Instead of {iteratively} adjusting the weights of the edges that define the connection among nodes, we will modify {the spectra of a collection of suitably engineered matrices that bridge adjacent layers. To eventually recover a multilayered feedforward architecture in direct space, we postulate a nested indentation of the associated eigenvectors. These latter act as the effective gears of a processing device operated in reciprocal space. The directed indentation between stacks of adjacent eigenvectors yield a compression of the activation pattern, which is eventually delivered to the detection nodes.} {As a starting point, assume eigenvectors are frozen to a reference setting which fulfills the prescribed conditions. The learning is hence solely restricted to the eigenvalues, a choice which amounts to performing a {\it global} training, targeted to identifying key collective modes, the selected eigen-directions, for carrying out the assigned classification task. The idea of conducting a global training on a subset of parameters has been also proposed in other works \cite{frankle2020training, Gabri__2019}. This is at odd with the usual approach to machine learning where {\it local} adjustments of pairwise weights are implemented in direct space. As we shall prove, by tuning the eigenvalues, while freezing the eigenvectors, yields performances superior to those reached with usual (local) techniques bound to operate with an identical number of free parameters, within an equivalent network architecture. Eigenvalues are therefore identified as key target of the learning process, proving more fundamental than any other set of identical cardinality, allocated in direct space. Remarkably, the distribution of weights obtained when applying the spectral learning technique restricted to the eigenvalues is close to that recovered when training the neural network in direct space, with no restrictions on the parameters to be adjusted. In this respect, spectral learning bound to the eigenvalues could provide a viable strategy for pre-training of deep neural networks. Further, the set of trainable eigenvalues can be expanded at will by inserting linear processing units between the adjacent layers of a non-linear multilayered perceptron. Added linear layers act as veritable booms of a {\it telescopic neural network}, which can be extracted during the learning phase and retracted in operational mode, yielding compact networks with improved classification skills. The effect of the linear expansion is instead negligible, if applied to neural learning of standard conception. The entries of the indented eigenvectors can be also trained resulting in enhanced performance, as compared to the setting where eigenvalues are exclusively modulated by the learning algorithm. To demonstrate the principles which underly spectral training, we employ the MNIST database, a collection of handwritten digits to be classified. The examined problem is relatively simple: a modest number of tunable parameters is indeed necessary for achieving remarkable success rates. When allowing for the simultaneous training of the eigenvalues and (a limited fraction of ) eigenvectors, the neural networks quickly saturates to accuracy scores which are indistinguishable from those obtained via conventional approaches to supervised learning. More challenging tasks should be probably faced to fully appreciate the role played by a progressive optimization of the eigenmodes, the collective directions in reciprocal space where information flows. As remarked above, the eigenvectors have been here constructed so as to yield a feedforward multi-layered architecture in direct space. By relaxing this assumption, comes to altering the network topology and thus exporting the spectral learning strategy to other frameworks, as e.g. reservoir computing. In general terms, working in the spectral domain corresponds to optimizing a set of {\it non orthogonal} directions (in the high dimensional space of the nodes) and associated weights (the eigenvalues), a global outlook which could contribute to shed novel light on the theoretical foundations of supervised learning.} {\section{Linear and non-linear spectral learning}} To introduce and test the proposed method we will consider a special task, i.e. recognition of handwritten digits. To this end, we will make use of the MNIST database \cite{lecun1998mnist} which has a training set of 60,000 examples, and a test set of 10,000 examples. Each image is made of $N_1=28 \times 28$ pixels and each pixel bears an 8-bit numerical intensity value, see Fig. \ref{fig1}. A deep neural network can be trained using standard backpropagation \cite{bengio2007greedy} algorithms to assign the weights that link the nodes (or perceptrons) belonging to consecutive layers. The first layer has $N_1$ nodes and the input is set to the corresponding pixel's intensity. The highest error rate reported on the original website of the database \cite{lecun1998mnist} is 12 \%, which is achieved using a simple linear classifier, with no preprocessing. In early 2020, researchers announced 0.16 \% error \cite{byerly2020branching} with a deep neural network made of branching and merging convolutional networks. Our goal here is to contribute to the analysis with a radically different approach to the learning, {rather than joining the efforts to break current limit in terms of performance and classification accuracy. More specifically, and referring to the MNIST database as a benchmark application, we will assemble a network made of $N$ nodes, organized in successive $\ell$ layers, tying the training to reciprocal space.} {Directed connections between nodes belonging to consecutive layers are encoded in a set of $\ell-1$, $N \times N$ adjacency matrices. The eigenvectors of these latter matrices are engineered so as to favour the information transfer from the reading frame to the output layer, upon proper encoding. The associated eigenvalues represent the primary target of the novel learning scheme. In the following we will set up the method, both with reference to its linear and non-linear versions. Tests performed on the MNIST database are discussed in the next Section.} {\subsection{Linear spectral learning: Single-layer perceptron trained in reciprocal space}} Assume $N_i$ to label the nodes assigned to layer $i$, {and define} $N=\sum_{i=1}^{\ell} N_i$. {For the specific case here inspected the} output layer is composed by ten nodes ($N_{\ell}=10$), where recognition takes eventually place. Select one image from the training set and be $n_1$ $(=0,1,2..,9)$ the generic number therein displayed. We then construct a column vector $\vec{n}_1$, of size $N$, whose first $N_1$ entries are the intensities displayed on the pixels of the selected image (from the top-left to the bottom-right, moving horizontally), as illustrated in Fig. \ref{fig1}. {All other entries are initially set to zero. As we shall explain in the following, our goal is to transform the input $\vec{n}_1$ into an output vector with same dimensions. The last $N_{\ell}$ elements of this latter vector represent the output nodes where reading is eventually performed.} \begin{figure} \centering \includegraphics[scale=0.3]{Fig1.png} \caption{\it Each image of the training set is mapped into a column vector $\vec{n}_1$, of size $N$, whose first $N_1 = 28 \times$ 28 entries are the intensities displayed on the pixels of the image.} \label{fig1} \end{figure} To set the stage, we begin by reporting on a simplified scenario that, as we shall prove in the following, yields a single layer perceptron. The extension to multi-layered architectures will be discussed {right after}. {Consider the entry layer made of $N_1$ nodes and the outer one composed of $N_2$ elements. In this case $N=N_1+N_2$. The input vector $\vec{n}_1$ undergoes a linear transformation to yield $\vec{n}_2=\mathbf{A}_1 \vec{n}_1$ where $\mathbf{A}_1$ is a $N\times N$ matrix that we shall characterize in the following. Introduce matrix $\Phi_1$: this is the identity matrix $\mathbb{1}_{N \times N}$ modified by the inclusion of a sub-diagonal block $N_{2} \times N_{1}$, e.g. filled with uniformly distributed random numbers, defined in a bounded interval, see Fig. \ref{fig2}. The columns of $\Phi_1$, hereafter $\left(\vec{\phi}_1\right)_k$ with $k=1,...,N$, define a basis of the $N$ dimensional space to which $\vec{n}_1$ and $\vec{n}_2$ belong. Then, we introduce the diagonal matrix $\Lambda_1$. The entries of $\Lambda_1$ are set to random (uniform) numbers spanning a suitable interval. A straightforward calculation returns $\left(\Phi_1\right)^{-1}=2 \mathbb{1}_{N \times N}-\Phi_1$. We hence define $\mathbf{A}_1= \Phi_1 \Lambda_1 \left(2 \mathbb{1}_{N \times N}-\Phi_1\right)$ as the matrix that transforms $\vec{n}_1$ into $\vec{n}_2$. Because of the specific structure of the input vector, and owing the nature of $\mathbf{A}_1$, the information stored in the first $N_1$ elements of $\vec{n}_1$ is passed to the $N_2$ successive entries of $\vec{n}_2$, in a compactified form which reflects both the imposed eigenvectors' indentation and the chosen non trivial eigenvalues. } {To see this more clearly, expand the $N$-dimensional input vector $\vec{n}_1$ on the basis made of $\left( \vec{\phi}_1 \right)_k$ to yield $\vec{n}_1=\sum_{k=1}^N c_k \left( \vec{\phi}_1 \right)_k$ where $c_k$ stands for the coefficients of the expansion. The first $N_1$ vectors are necessarily engaged to explain the non zero content of $\vec{n}_1$ and, because of the imposed indentation, rebound on the successive $N_2$ elements of the basis. These latter need to adjust their associated weights $c_k$ to compensate for the echoed perturbation. The action of matrix $\mathbf{A}_1$ on the input vector $\vec{n}_1$ can be exemplified as follows:} \begin{equation} \vec{n}_2 = \mathbf{A}_1 \vec{n}_1 = \mathbf{A}_1 \sum_{k=1}^N c_k \left( \vec{\phi}_1 \right)_k = \sum_{k=1}^{N_1+N_2} c_k \left( \Lambda_1 \right)_k \left( \vec{\phi}_1 \right)_k \end{equation} {where $\left( \Lambda_1 \right)_k$ are the element of matrix $\Lambda_1$. In short, the entries of $\vec{n}_2$ from position $N_1+1$ to position $N_1+N_2$ represent a compressed (if $N_2<N_1$) rendering of the supplied input signal, the key to decipher the folding of the message being stored in the $N_{2} \times N_{1}$ sub-diagonal block of $\Phi_1$, (i.e. the eigenvector indentation) and in the first set of $N=N_1+N_2$ eigenvalues $\left( \Lambda_1 \right)_k$. The key idea is to propagate this message passing scheme, from the input to the output in a multi-layer setting, and adjust (a subset of) the spectral parameters involved so as to optimize the encoding of the information.} \begin{figure} \centering \includegraphics[scale=0.5]{LineareAdiacenza.pdf} \caption{\it {Panel (a): the structure of matrix $\Phi_k$ is schematically depicted. The diagonal entries of $\Phi_k$ are unities. The sub-diagonal block of size $N_{k+1} \times N_{k}$ for $k=1,\ell-1$ is filled with uniform random numbers in $[a,b]$, with $a,b \in \mathbb{R}$. These blocks yields an effective indentation between successive stacks of linearly independent eigenvectors. The diagonal matrix of the eigenvalues $\Lambda_k$ is also represented. The sub-portions of $\Phi_k$ and $\Lambda_k$ that get modified by the training performed in spectral domain are highlighted (see legend). In the experiments reported in this paper the initial eigenvectors entries are uniform random variables distributed in $[-0.5,0.5]$. The eigenvalues are uniform random numbers distributed in the interval $[-0.01,0.01]$. Optimizing the range to which the initial guesses belong (for both eigenvalues and eigenvectors) is an open problem that we have not tackled. Panel (b): a $(N_1 + N_\ell) \times (N_1 + N_\ell)$ matrix $\mathcal{A}_c$ can be obtained from $\mathcal{A}=\left( \Pi_{k=1}^{\ell-1} \mathbf{A}_{k} \right) $, which provides the weights for a single layer perceptron, that maps the input into the output, in direct space.}} \label{fig2} \end{figure} { To this end, we introduce the $N \times N$ matrix operator $\Phi_k$, for $k=2,...,\ell-1$. In analogy with the above, $\Phi_k$ is the identity matrix $\mathbb{1}_{N \times N}$ modified with a sub-diagonal block $N_{k+1} \times N_{k}$, which extends from rows $N_k$ to $N_k+N_{k+1}$, and touches tangentially the diagonal, as schematically illustrated in Fig. \ref{fig2} (a). Similarly, we introduce $\Lambda_k$, for $k=2,...,\ell-1$, which is obtained from the identity matrix $\mathbb{1}_{N \times N}$ upon mutating to uniformly distributed random entries the diagonal elements that range from $\sum_{i=1}^k N_i$ (not included) to $\sum_{i=1}^{k+1} N_i$ (included). Finally, we define $\mathbf{A}_k= \Phi_k \Lambda_k \left(2 \mathbb{1}_{N \times N}-\Phi_k\right)$, as the matrix that transforms $\vec{n}_k$ into $\vec{n}_{k+1}$, with $k=2,...,\ell-1$. In principle, both non trivial eigenvalues' and eigenvectors' input can be self-consistently adjusted by the envisaged learning strategy. The input signal $\vec{n}_1$ is hence transformed into an output vector $\vec{n}_{\ell}$ following a cascade of linear transformations implemented via matrices $\mathbf{A}_k$. In formulae:} \begin{equation} \vec{n}_{\ell} = \mathbf{A}_{\ell-1} ...\mathbf{A}_{1} \vec{n}_1 = \left( \Pi_{k=1}^{\ell-1} \Phi_k \Lambda_k \left(2 \mathbb{1}_{N \times N}-\Phi_k\right)\right) \vec{n}_1 \end{equation} {where in the last step we made use of the representation of $\mathbf{A}_k$ in dual space. The generic vector $\vec{n}_{k+1}$, for $k=1,..., \ell-1$ is obtained by applying matrix $\mathbf{A}_k$ to $\vec{n}_k$. The first $N_1+N_2+...+N_k$ components of $\vec{n}_{k+1}$ coincide with the corresponding entries of $\vec{n}_k$, namely $\left[ \vec{n}_{k+1} \right]_m \equiv \left[ \vec{n}_{k} \right]_m$ for $m<N_1+N_2+...+N_k$. Here, $\left[ \left(\vec{\cdot}\right) \right]_m$ identifies the $m$-th component of the vector $\left(\vec{\cdot}\right)$. Recall that, by construction, $\left[ \vec{n}_{k} \right]_m=0$ for $m> N_1+N_2+...+N_k$. On the contrary, the components $\left[ \vec{n}_{k+1} \right]_m$ with $N_1+N_2+...+N_k+1<m<N_1+N_2+...+N_k+N_{k+1}$ are populated by non trivial values which reflect the eigenvectors indentation, as well as the associated eigenvalues. This observation can be mathematically proven as follows. Write $\vec{n}_k$ on the basis formed by the eigenvectors $\left( \vec{\phi}_k \right)_l$ to eventually get:} \begin{equation} \vec{n}_k = \sum_{l=1}^{N_1+N_2+...+N_{k+1}} c_l \left( \vec{\phi}_k \right)_l \equiv \sum_{l=1}^{N_1+N_2+...+N_k} c_l \vec{e}_l \end{equation} {where $\left(\vec{e}_1, \vec{e}_2...\right)$ stand for the canonical basis and the last inequality follows the specific structure of the eigenvectors (remark that the leftmost sum in the above equation includes $N_{k+1}$ more elements than the second). By definition:} \begin{equation} \vec{n}_{k+1} = \mathbf{A}_k \vec{n}_k = \sum_{l=1}^{N_1+N_2..+N_{k+1}} c_l \left( \Lambda_k \right)_l \left( \vec{\phi}_k \right)_l \end{equation} {From the above relation, one gets for $m \le N_1+N_2+...+N_k$} \begin{equation} \left[ \vec{n}_{k+1} \right]_m = \sum_{l=1}^{N_1+N_2..+N_{k}} c_l \left[ \vec{e}_l \right]_m \equiv \left[ \vec{n}_{k} \right]_m \end{equation} {where the first equality sign follows from the observation that $\left( \vec{\phi}_k \right)_l$ coincides with $\vec{e}_l$ and $\left( \Lambda_k \right)_l=1$, over the explored range of $m$. For $N_1+N_2+...+N_k+1 \le m \le N_1+N_2+...+N_k+N_{k+1}$, we obtain instead:} \begin{equation} \left[\vec{n}_{k+1}\right]_m = \sum_{l=N_1+N_2..+N_{k-1}}^{N_1+N_2..+N_{k+1}} c_l \left( \Lambda_k \right)_l \left[ \left( \vec{\phi}_k \right)_l \right]_m \end{equation} {Finally, it is immediate to show that $\left[\vec{n}_{k+1}\right]_m=0$ for $m> N_1+N_2+...+N_k+N_{k+1}$, because of the specific form of the employed eigenvectors. In short, the information contained in the last non trivial $N_k$ entries of $\vec{n}_k$ rebound on the successive $N_{k+1}$ elements of $\vec{n}_{k+1}$, funnelling the information downstream from the input to the output. The successive information processing relies on the indented (non orthogonal) eigenvectors and the associated eigenvalues, which hence define the target of the training in reciprocal space. } { To carry out the learning procedure one needs to introduce a loss function $L(\vec{n}_1)$. For illustrative purposes this latter can be written as:} \begin{equation} \label{LF} L(\vec{n}_1) = \left\lVert l(\vec{n}_1) - \sigma\left[ \left( \Pi_{k=1}^{\ell} \Phi_k \Lambda_k \left(2 \mathbb{1}_{N \times N}-\Phi_k\right) \right) \vec{n} _1\right ] \right\lVert^2 \end{equation} { where $\sigma(\cdot)$ is the softmax operation applied to the last entries of the $\ell$-th image of the input vector $\vec{n}_1$. In the above expression, $l(\vec{n}_1)$ stands for the label attached to $\vec{n}_1$ depending on its category. More into details, the $k$-th entry of $l(\vec{n}_1)$ is equal unit (and the rest identically equal to zero) if the number supplied as an input is identical to $k$, with $k=0,1,...,9$. The loss function can be minimized by acting on the free parameters of the learning scheme. Specifically, the learning can be restricted to the set of $N$ non trivial eigenvalues, split in $\ell$ distinct groups, each referred to one of the $\mathbf{A}_{k}$ matrices (i.e. $N_1+N_2$ eigenvalues of $\mathbf{A}_{1}$, $N_3$ eigenvalues of $\mathbf{A}_{2}$,...., $N_{\ell}$ eigenvalues of $\mathbf{A}_{\ell-1}$). In addition, the sub-diagonal block entries of $\Phi_k$, the elements of the basis which dictate the successive indentation between adjacent layers, can be adjusted as follows the training scheme. In the following section we will report about the performance of the method, implemented in its different modalities, against those obtained with a classical approach to the learning anchored in direct space. In the actual implementation we have chosen to deal with a categorical cross-entropy loss function.} {Before ending this section a few remarks are mandatory. Introduce $\mathcal{A} = \Pi_{k=1}^{\ell} \mathbf{A}_{k}$. The linear transformation that links the input vector $\vec{n}_1$ to the generated output $\vec{n}_{\ell}$, can be compactly expressed as $\vec{n}_{\ell} = \mathcal{A} \vec{n}_1$. Then, recall that the classification relies on examining the last $N_\ell$ entries of $\vec{n}_{\ell}$. Hence, for the specific setting here examined, where the mapping is obtained as a cascade of linear transformations, one can imagine to recast the whole procedure in a space of reduced dimensionality. Be $\vec{z}$ a column vector made of $N_1 + N_\ell$ elements. The first $N_1$ entries of $\vec{z}$ are the intensities on the pixels of the selected image, as for the homologous $\vec{{n}}_1$ quantity. The other elements are set to zero. Then, consider the $(N_1 + N_\ell) \times (N_1 + N_\ell)$ matrix $\mathcal{A}_c$ (the label $c$ stands for {\it compact}), constructed from $\mathcal{A}$ by trimming out all the information that pertain to the intermediate layers, as introduced in the reciprocal space (see Fig. \ref{fig2}(b)). Stated differently, matrix $\mathcal{A}_c$ provides the weighted links that feed from the input to the output layer in direct space, via the linear transformation $\mathcal{A}_c \vec{z}$: this is a single layer perceptron, shown in Fig. \ref{fig2}(b), which was trained by endowing reciprocal space with an arbitrary number of additional dimensions, the intermediate stacks responsible for the sequential embedding of the information. Intermediate layers can be literally extracted, during the training phase, and subsequently retracted in operational mode. The importance to allowing for additional layers, and so provide the neural network of a telescopic attribute, will be assessed in the forthcoming sections.} {From the algorithmic point of view the process outlined above can be rephrased in simpler, although equivalent terms. For all practical purposes, one could take the (column) input vector $\vec{{n}}_1$ to have $N_1+N_2$ elements. Following the scheme depicted above, the first $N_1$ entries are the intensities on the pixels of the selected image, while the remaining $N_2$ elements are set to zero. We now introduce a $(N_1+N_2) \times (N_1+N_2)$ matrix $\mathbf{A}_{1}$. This is the identity matrix $\mathbb{1}_{(N_1+N_2) \times (N_1+N_2)}$ with the inclusion of a sub-diagonal block $N_{2} \times N_{1}$, which handles the information processing that will populate the second $N_2$ elements of the output vector $\vec{{n}}_2= \mathbf{A}_{1} \vec{{n}_1}$. Then, we formally replace the $(N_1+N_2)$ column vector $\vec{{n}}_2$ with a column vector made of $(N_2+N_3)$ elements, termed $\vec{{n}}_{2t}$, whose first $N_2$ elements are the final entries of $\vec{{n}}_2$. The remaining $N_3$ elements of $\vec{{n}}_{2t}$ are set to zero. Now, rename $\vec{{n}}_{2t}$ as $\vec{{n}}_2$ and presents it as the input of a $(N_2+N_3) \times (N_2+N_3)$ matrix $\mathbf{A}_{2}$, with a non trivial sub-diagonal $N_{3} \times N_{2}$ block. This latter maps the first $N_2$ elements of the input vector, into the successive $N_3$ of the output one, by completing the second step of an algorithmic scheme which can be iteratively repeated. In analogy with the above, each $(N_k+N_{k+1}) \times (N_k+N_{k+1})$ matrix $\mathbf{A}_{k}$ can be written as $\mathbf{A}_k= \Phi_k \Lambda_k \left(2 \mathbb{1}_{(N_k+N_{k+1}) \times (N_k+N_{k+1})}-\Phi_k\right)$, where now the column vectors of $\Phi_k$ are the eigevenctors of $\mathbf{A}_k$ and form a non-orthogonal basis of the $(N_k+N_{k+1})$ space where input and output vectors belong. $\Lambda_k$ is a diagonal matrix of the eigenvalues: the first $N_k$ are set to one, while the other $N_{k+1}$ are non trivial entries to be adjusted self-consistently via the learning scheme. Framing the process in the augmented space of $N$ dimensions, as done earlier, allows us to avoid adapting the dimensions of the involved vectors at each iteration. On the contrary, this is a convenient procedure to be followed when aiming at a numerical implementation of the envisaged scheme. Notice that to discuss the algorithmic variant of the method, we made use of the same symbols employed earlier. The notation clash is however solely confined to this paragraph.} {In the following, we will discuss how these ideas extend to the more general setting of non-linear multi-layered neural networks.} {\subsection{Training non-linear multi-layered neural networks in the spectral domain}} { In analogy with the above, the image to be processes is again organized in a $N\times1$ column vector $\vec{n}_1$. This latter is transformed into $\vec{n}_2=\mathbf{A}_1 \vec{n}_1$, where matrix ${N \times N}$ matrix $\mathbf{A}_1$ is recovered from its spectral properties, respectively encoded in $\Phi_1$ and $\Lambda_1$. The output vector $\vec{n}_2$ is now filtered via a suitable {\it non-linear} function $f(\cdot)$. This step marks a distinction between, respectively, the linear and non-linear versions of the learning schemes. For the applications here reported we have chosen to work with a rectified linear unit (ReLU) $f(\cdot)= max(0, \cdot)$. Another possibility is to set $f(\cdot, \beta_1)=\tanh[\beta_1(\cdot)]$, where $\beta_1$ is a control parameter which could be in principle self-consistently adjusted all along the learning procedure. We are now in a position to iterate the same reasoning carried out in the preceding section, adapted to the case at hand. More specifically, we introduce the generic $N\times N$ matrix $\mathbf{A}_k= \Phi_k \Lambda_k \left(2 \mathbb{1}_{N \times N}-\Phi_k\right)$ which transforms $\vec{n}_k$ into $\vec{n}_{k+1}$, with $k=2,...,\ell-1$. The outcome of this linear transformation goes through the non-linear filter. The loss function $L(\vec{n})$ generalizes to:} \begin{equation} \label{LF} L(\vec{n}) = \left\lVert l(\vec{n}_1) - \sigma\left( f\left(\mathbf{A}_{\ell-1}.... f\left (\mathbf{A}_2 f \left (\mathbf{A}_1 \vec{n_1},\beta_1 \right), \beta_2 \right),\beta_{\ell-1} \right) \right) \right\rVert^2 \end{equation} {with an obvious meaning of the involved symbols. In the set of experiments reported below we assume, in analogy with the above, a categorical cross-entropy loss function. The loss function is minimized upon adjusting the free parameters of the learning scheme: the $\ell-1$ blocks of tunable eigenvalues, the elements that define the successive indentation of the nested basis which commands the transfer of the information (and e.g. the quantities $\beta_k$, if the sigmoidal hyperbolic function is chosen as a non-linear filter). This eventually yields a fully trained network, in direct space, which can be unfolded into a layered architecture to perform pattern recognition (see Fig. \ref{fig3}). Remarkably, self-loop links are also present. The limit of a linear single layer perceptron is recovered when silencing the non-linearities: a $(N_1 + N_\ell) \times (N_1 + N_\ell)$ matrix $\mathcal{A}_c$ can be generated from the $N \times N$ matrices $\mathbf{A}_{k}$, following the same strategy outlined above. A sequence of linear layers can be also interposed between two consecutive non-linear stacks. The interposed layers allow to enlarge the space of parameters employed in the learning scheme, and can be retracted when operating the deep neural network after completion of the learning stage. Their role is {\it de facto} encapsulated in the entries of the linear operator that bridges the gap between the adjacent non-linear stacks, as explained above when referring to the telescopic operational modality.} \begin{figure} \centering \includegraphics[scale=0.5]{EmbeddingProgressivo.pdf} \\ \caption{\it {The non-linear version of the training scheme returns a multi-layered architecture with self-loops links in direct space. Linear and non-linear transformation can be combined at will, matrices $\mathbf{A}_k$ providing the connection between successive layers. Linear layers can be retracted in operational mode, following a straightforward variant of the compactification procedure described in the main body of the paper. }} \label{fig3} \end{figure} {\section{Results}} To build and train the aforementioned models we used TensorFlow and created a custom spectral layer matrix that could be integrated in virtually every TensorFlow or Keras model. That allowed us to leverage on the automatic differentiation capabilities and the built-in optimizers of TensorFlow. Recall that we aim at training {just a a portion of the diagonal of $\Lambda_k$ and a block of $\Phi_k$}. To reach this goal we generated two fully trainable matrices, for each layer in the spectral domain, and applied a suitably designed mask to filter out the sub-parts of the matrices to be excluded from the training. This is easy to implement and, although improvable from the point of view of computational efficiency, it works perfectly, given the size of the problem to be handled. We then trained all our models with the AdaMax optimizer \cite{kingma2014adam} by using a learning rate of $0.03$ for the linear case and $0.01$ for the non-linear one. The training proceeded for {about $20$ epochs} and during each epoch the network was fed with batches of images of {different size, ranging from $300$ to $800$.}. These hyperparameters have been chosen so as to improve on GPU efficiency, accuracy and stability. However, we did not perform a systematic study to look for the optimal setting. All our models have been trained on a virtual machine hosted by Google Colaboratory. Standard neural networks have been trained on the same machine using identical software and hyperparameters, for a fair comparison. Further details about the implementation, as well as a notebook to reproduce our results, can be found in the public repository of this project \cite{gitrepo}. {We shall start by reporting on the performance of the linear scheme. The simplest setting is that of a perceptron made of two layers: the input layer with $N_1=28 \times 28 = 784$ nodes and the output one made of $N_2=10$ elements. The perceptron can be trained in the spectral domain by e.g. tuning the $N=N_1+N_2=794$ eigenvalues of $\mathbf{A}_{1}$, the matrix that links the input ($\vec{n}_1$) and output ($\vec{n}_2$) vectors. The learning restricted to the eigenvalues returns a perceptron which performs the sought classification task with an accuracy (the fraction of correctly recognized images in the test-set) of $(82 \pm 2) \%$ (averaging over $5$ independent runs). This figure is to be confronted with the accuracy of a perceptron trained with standard techniques in direct space. For a fair comparison, the number of adjustable weights should be limited to $N$. To this aim, we randomly select a subset of weights to be trained and carry out the optimization on these latter. The process is repeated a few ($5$ in this case) times and, for each realization, the associated accuracy computed. Combining the results yields an average performance of $(79 \pm 3) \%$ , i.e. a slightly smaller score (although compatible within error precision) than that achieved when the learning takes place in the spectral domain. When the training extends to all the $N_1 \times N_2$ weights (plus $N_1+N_2$ bias), conventional learning yields a final accuracy of $(92.7 \pm 0.1) \%$. This is practically identical to the score obtained in the spectral domain, specifically $(92.5 \pm 0.2) \%$, when the sub-diagonal entries of the eigenvectors matrix are also optimized (for a total of $N_1+N_2+N_1 \times N_2$ free parameters). The remarkable observation is however that the distribution of the weights as obtained when the learning is restricted on the eigenvalues (i.e using about the 10 \% of the parameters employed for a full training in direct space) matches quite closely that retrieved by means of conventional learning schemes, see Fig. \ref{fig4} . This is not the case when the learning in direct space acts on a subset of $N$, randomly selected, weights (data not shown). Based on the above, it can be therefore surmised that optimizing the eigenvalues constitutes a rather effective pre-training strategy, which engages a modest computational load.} \begin{figure} \centering \includegraphics[scale=0.7]{Percettrone.pdf} \\ \caption{\it {Distribution of the weights of a perceptron. The red line follows the spectral training limited the $N_1+N_2$ eigenvalues. The black line follows the training in direct space. Here, $N_1 \times N_2$ parameters are adjusted in the space of the nodes. The distribution are very similar, but the spectral learning employs about $10 \%$ of the parameters used in direct space. The distributions obtained when forcing the training in direct space to operate on a subset of $N_1+N_2$ weights are very different from the one displayed (for every choice of the randomly selected family of weights to be trained).}} \label{fig4} \end{figure} {To further elaborate on the potentiality of the proposed technique, we modify the simple two-layers perceptron, with the inclusion of supplementary computing layers. As explained above the newly added layers plays an active role during the learning stage, but can be retracted in operating mode so as to return a two-layers perceptron. The weights of this latter bear however an imprint of the training carried out for the linear network in the expanded configuration. Two alternative strategies will be in particular contemplated. On the one side, we will consider a sole additional layer, endowed with $N_2$ nodes, interposed between the input and output layers made of, respectively, $N_1=784$ and $N_{\ell} \equiv N_3=10$ nodes. We will refer to this as to the {\it wide linear} configuration. The performance of the method can be tested by letting $N_2$ to progressively grow. On the other side, the {\it deep linear} configuration is obtained when interposing a sequence of successive (linear) stacks between the input ($N_1=784$) and the output ($N_{\ell} =10$) layers.} { In Fig. \ref{fig5}, we report on the performance of the wide learning scheme as a function of $N_2+N_3$. As we shall clarify, this latter stands for the number of trained parameters for (i) the spectral learning acted on a subset of the tunable eigenvalues and for (ii) the conventional learning in direct space restricted to operate on a limited portion of the weights. The red line in the main panel of Fig. \ref{fig5} refers to the simplified scheme where a subset of the eigenvalues are solely tuned (while leaving the eigenvectors fixed at the random realization set by the initial condition). We have in particular chosen to train the second bunch of $N_2$ eigenvalues of the transfer matrix $\mathbf{A}_{1}$ and the $N_3=10$ non trivial eigenvalues of matrix $\mathbf{A}_{2}$, in line with the prescriptions reported in the preceding Section. The blue line reports on the accuracy of the neural network trained in direct space: the target of the optimization is a subset of cardinality $N_2+N_3$ of the $N_1 N_2+N_2 N_3$ weights which could be in principle adjusted in the space of the nodes. The performance of the spectral method proves clearly superior, as it can be readily appreciated by visual inspection of Fig. \ref{fig5}. The black line displays the accuracy of the linear neural network when the optimization acts on the full set of $N_1 N_2+N_2 N_3$ trainable parameters. No improvement is detectable when increasing the size of the intermediate layer: the displayed accuracy is substantially identical to that obtained for the basic perceptron trained with $N_1 N_2=7840$ parameters. The spectral learning allows to reach comparable performance already at $N_2=1000$ ($13 \%$ of the parameters used for the standard two layers perceptron with $N_1 \times N_2$ parameters, as discussed above). In the inset of Fig. \ref{fig5}, the distribution of the entries of matrix $\mathcal{A}_c$, the equivalent perceptron, is depicted in red for the setting highlighted in the zoom. The black line refers to the two-layers equivalent of the neural network trained in direct space, employing the full set of trainable parameters (black dot enclosed in the top-left dashed rectangle drawn in the main panel of Fig. \ref{fig5}). The two distributions look remarkably close, despite the considerable reduction in terms of training parameters, as implemented in the spectral domain (for the case highlighted, $0.13 \%$ of the parameters employed under the standard training). Similarly to the above, the distribution obtained when forcing the training in direct space to act on a subset of $N_1+N_2$ weights are just a modest modulation of the initially assigned profile, owing to the {\it local} nature of the learning in the space of the nodes.} {In Fig. \ref{fig6}, we report the results of the tests performed when operating under the deep linear configuration. Symbols are analogous to those employed in Fig. \ref{fig5}. In all inspected cases, the entry layer is made of $N_1=784$ elements and the output one has $N_{\ell}=10$ nodes. The first five points, from left to right, refer to a three layers (linear) neural network. Hence, $\ell=3$ and the size of the intermediate layer is progressively increased, $N_2=20,80,100,500,800$. The total number of trained eigenvalues is $N_2+N_3$, and gets therefore larger as the size of the intermediate layer grows. The successive four points of the collections are obtained by setting $\ell=4$. Here, $N_2=800$ while $N_3$ is varied ($=100,200,400,600$). The training impacts on $N_2+N_3+N_4$ parameters. Finally the last point in each displayed curve is obtained by working with a five layers deep neural network, $\ell=5$. In particular $N_2=800$, $N_3=600$ and $N_4=500$, for a total of $N_2+N_3+N_4+N_5$ tunable parameters. Also in this case, the spectral algorithm performs better than conventional learning schemes constrained to operate with an identical number of free parameters. Similarly, the distribution of the weights of an equivalent perceptron trained in reciprocal space matches that obtained when operating in the space of the nodes and resting on a considerably larger number of training parameters. To sum up, eigenvalues are parameters of key importance for neural networks training, way more strategic than any other set of equivalent cardinality in the space of the nodes. As such, they allow for a global approach to the learning, with significant reflexes of fundamental and applied interest. In all cases here considered, the learning can extend to the eigenvectors: an optimized indentation of the eigen-directions contribute to enhance the overall performance of the trained device.} \begin{figure} \centering \includegraphics[scale=0.5]{WideLinearBox.pdf} \\ \caption{\it {A three layers neural network is considered. The accuracy of the neural network is plotted as a function of the number of parameters that we chose to train with the spectral algorithm, $N_2+N_3$. The red line reports on the performance of the spectral training. The blue line refers to the neural network trained in direct space: the optimization runs on $N_2+N_3$ parameters, a subset of the total number of adjustable weights $N_1 N_2+N_2 N_3$. The black line stands for the accuracy of the linear neural network when training the full set of $N_1 N_2+N_2 N_3$ parameters. Notice that the reported accuracy is comparable to that obtained for a standard two layers perceptron. Inset: the distribution of the entries of the equivalent perceptrons are plotted. The red curve refer to the spectral learning restricted to operate on the eigenvalues; the black profile to the neural network trained in direct space, employing the full set of adjustable parameters. In both cases, the weights refer to the two layers configuration obtained by retracting the intermediate linear layer employed during the learning stage. }} \label{fig5} \end{figure} \begin{figure} \centering \includegraphics[scale=0.5]{DeepLinearBox.pdf} \\ \caption{\it { The performance of the spectral algorithm are tested for a multi-layered linear configuration. Symbols are chosen in analogy to Fig. \ref{fig5}. In all cases, the input layer is made of $N_1=784$ elements and the output layer has $N_{\ell}=10$ nodes. The first five points, from left to right in each of the curves depicted in the main panel, refer to a three layers (linear) neural network. The size of the intermediate layer is progressively increased, as $N_2=20,80,100,500,800$. The total number of trained eigenvalues is $N_2+N_3$. The subsequent four points are obtained by considering a four layers architecture. In particular, $N_2=800$ while $N_3$ takes values in the interval ($100,200,400,600$). The training acts on $N_2+N_3+N_4$ eigenvalues. The final point in each curve is obtained with a four layers deep neural network. Here, $N_2=800$, $N_3=600$ and $N_3=500$, for a total of $N_2+N_3+N_4+N_5$ tunable parameters in the spectral setting. Inset: the distribution of the entries of the equivalent perceptrons are displayed, with the same color code adopted in Fig. \ref{fig5}. Also in this case, the weights refer to the two layers configuration obtained by retracting the intermediate linear layers employed in the learning stage. }} \label{fig6} \end{figure} {We now turn to considering a non-linear architecture. More specifically, we will assume a four layers network with, respectively, $N_1=784, N_2,N_3=120, N_4=10$. The non-linear ReLU filter acts on the third layer of the collection, while the second is a linear processing unit. As in the spirit of the wide network configuration evoked above, we set at testing the performance of the neural network for increasing $N_2$. For every choice of $N_2$, the linear layer can be retracted yielding a three-layered effective non-linear configurations. We recall however that training the network in the enlarged space where the linear unit is present leaves a non trivial imprint in the weights that set the strength of the links in direct space.} {In Fig \ref{fig7}, we plot the computed accuracy as a function of $N_2$, the size of the linear layer. In analogy with the above analysis, the red curve refers to the training restricted to $N_2+N_3+N_4$ eigenvalues; the blue profile is obtained when the deep neural network is trained in direct space by adjusting an identical number of inter-nodes weights. As for the case of a fully linear architecture, by adjusting the eigenvalues yields better classification performances. The black line shows the accuracy of the neural network when the full set of $N_1 N_2+N_2 N_3+N_3 N_4$ is optimized in direct space. The green line refer instead to the spectral learning when the eigenvalues and eigenvectors are trained simultaneously. The accuracies estimated for these two latter settings agree within statistical error, even if the spectral scheme seems more robust to overfitting (the black circles declines slightly when increasing $N_2$, while the collection of green points appears rather stable).} \begin{figure} \centering \includegraphics[scale=0.5]{NonLinearAccuracy.pdf} \\ \caption{\it {The accuracy of the non-linear deep neural network is tested. We assume a four layers network with, respectively, $N_1=784, N_2,N_3=120, N_4=10$; $N_2$ is changed so as to enlarge the set of parameters to be trained. The red line refers to the spectral training, with $N_2+N_3+N_4$ adjusted eigenvalues. The blue line stands for a neural network trained in direct space, the target of the optimization being a subset made of $N_2+N_3+N_4$ weights, randomly selected from the available pool of $N_1 N_2+N_2 N_3+N_3 N_4$ tunable parameters. The black line reports the accuracy of the linear neural network when training the full set of $N_1 N_2+N_2 N_3+N_3 N_4$ weights. The green line refer to the spectral learning when eigenvalues and eigenvectors are simultaneously trained.}} \label{fig7} \end{figure} \section{Conclusions} Summing up, we have here proposed a novel approach to the training of deep neural networks which is bound to the spectral, hence reciprocal, domain. The {eigenvalues and eigenvectors} of the adjacency matrices that connects consecutive layers via directed feed-forward links are trained, instead of adjusting the weights that bridge each pair of nodes of the collection, as it is customarily done in the framework of conventional ML approaches. {The first conclusion of our analysis is that optimizing the eigenvalues, when freezing the eigenvectors, yields performances which are superior to those attained with conventional methods {\it restricted} to a operate with an identical number of free parameters. It is therefore surmised that eigenvalues are key target parameters for neural networks training, in that they allow for a {\it global} handling of the learning. This is at variance with conventional approaches which seek at modulating the weights of the links among mutually connected nodes. Secondly, the spectral learning restricted to the eigenvalues yields a distribution of the weights which resembles quite closely that obtained with conventional algorithms bound to operate in direct space. For this reason, the proposed method could be used in combination with existing ML algorithms for an effective (and computationally advantageous) pre-training of deep neural networks. We have also shown that linear processing units inserted in between consecutive, non-linearly activated layers produce an enlargement of the learning parameters space, with beneficial effects in terms of performance of the trained device. Extending the learning so as to optimize the eigenvectors enhances the ability of the network to operate the sought classification. In the proposed implementation, and to recover a feed-forward architecture in direct space, we have assumed a nested indentation of the eigenvectors. Entangling the eigenvectors referred to successive stacks is the key for a recursive processing of the data, from the input to the output layer. Employing other non-orthogonal basis could eventually allow to challenge different topologies in direct space and shed novel light on the surprising ability of deep networks to cope with the assigned tasks.} {In future perspective, it would interesting to characterize the solutions attained with the spectral method, following the strategy outlined in \cite{feizi2017porcupine}. Further, it could be interesting to combine the spectral approach to other existing schemes which have been devised to improve the computational performance of deep neural networks, without significant loss in final recognition accuracy \cite{6638949, frankle2020training}.} \bibliographystyle{unsrt}
{'timestamp': '2020-10-23T02:26:55', 'yymm': '2005', 'arxiv_id': '2005.14436', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14436'}
arxiv
\section{Introduction} \IEEEPARstart{V}{ideo} dominates the Internet. In North America, Netflix and YouTube alone account for more than fifty percent of downstream traffic, and there are many other significant video service providers. Improving the efficiency of video encoding, storage, and streaming over communication networks is a principle goal of video sharing and streaming platforms. One relevant and essential research direction is the perceptual optimization of rate-distortion tradeoffs in video encoding and streaming, where distortion (or quality) is usually modeled using video quality assessment (VQA) algorithms that can predict human judgements of video quality. This has motivated years of research on the topics of perceptual video and image quality assessment (VQA/IQA). VQA research can be divided into two closely related categories: subjective video quality studies and objective video quality modeling. Subjective video quality research usually requires substantial resources devoted to time- and labor-consuming human studies to obtain valuable and reliable subjective data. The datasets obtained from subjective studies are invaluable for the development, calibration, and benchmarking of objective video quality models that are consistent with subjective mean opinion scores (MOS). \begin{table*}[!t] \setlength{\tabcolsep}{2.5pt} \renewcommand{\arraystretch}{1.1} \centering \begin{threeparttable} \caption{Evolution of popular public video quality assessment databases: from legacy lab studies of synthetically distorted video sets to large-scale crowdsourced user-generated content (UGC) video datasets with authentic distortions} \label{table:db_comp} \begin{tabular}{llllllllp{3.5cm}lllll} \toprule \textsc{Database} & \textsc{Year} & \textsc{\#Cont} & \textsc{\#Total} & \textsc{Resolution} & \textsc{FR} & \textsc{Len} & \textsc{Format} & \textsc{Distortion Type} & \textsc{\#Subj} & \textsc{\#Rates} & \textsc{Data} & \textsc{Env} \\ \hline\\[-1.em] LIVE-VQA & 2008 & 10 & 160 & 768$\times$432 & 25/50 & 10 & YUV+264 & Compression, transmission & 38 & 29 & DMOS+$\sigma$ & In-lab \\ EPFL-PoliMI & 2009 & 12 & 156 & CIF/4CIF & 25/30 & 10 & YUV+264 & Compression, transmission & 40 & 34 & MOS & In-lab \\ VQEG-HDTV & 2010 & 49 & 740 & 1080i/p & 25/30 & 10 & AVI & Compression, transmission & 120 & 24 & RAW & In-lab \\ IVP & 2011 & 10 & 138 & 1080p & 25 & 10 & YUV & Compression, transmission & 42 & 35 & DMOS+$\sigma$ & In-lab \\ TUM 1080p50 & 2012 & 5 & 25 & 1080p & 50 & 10 & YUV & Compression & 21 & 21 & MOS & In-lab \\ CSIQ & 2014 & 12 & 228 & 832$\times$480 & 24-60 & 10 & YUV & Compression, transmission & 35 & N/A & DMOS+$\sigma$ & In-lab \\ CVD2014 & 2014 & 5 & 234 & 720p, 480p & 9-30 & 10-25 & AVI & Camera capture (authentic) & 210 & 30 & MOS & In-lab \\ MCL-V & 2015 & 12 & 108 & 1080p & 24-30 & 6 & YUV & Compression, scaling & 45 & 32 & MOS & In-lab \\ MCL-JCV & 2016 & 30 & 1560 & 1080p & 24-30 & 5 & MP4 & Compression & 150 & 50 & RAW-JND & In-lab \\ KoNViD-1k & 2017 & 1200 & 1200 & 540p & 24-30 & 8 & MP4 & Diverse distortions (authentic) & 642 & 114 & MOS+$\sigma$ & Crowd \\ LIVE-Qualcomm & 2018 & 54 & 208 & 1080p & 30 & 15 & YUV & Camera capture (authentic) & 39 & 39 & MOS & In-lab \\ LIVE-VQC & 2018 & 585 & 585 & 1080p-240p & 19-30 & 10 & MP4 & Diverse distortions (authentic) & 4776 & 240 & MOS & Crowd \\ YouTube-UGC & 2019 & 1380 & 1380 & 4k-360p & 15-60 & 20 & MKV & Diverse distortions (authentic) & $>$8k & 123 & MOS+$\sigma$ & Crowd \\ \bottomrule \end{tabular} \begin{tablenotes}[para,flushleft] \footnotesize \item \textsc{\#Cont}: Total number of unique contents. \item \textsc{\#Total}: Total number of test sequences, including reference and distorted videos. \item \textsc{Resolution}: Video resolution (p: progressive). \item \textsc{FR}: Framerate. \item \textsc{Len}: Video duration/length (in seconds). \item \textsc{Format}: Video container. \item \textsc{\#Subj}: Total number of subjects in the study. \item \textsc{\#Rates}: Average number of subjective ratings per video. \item \textsc{Env}: Subjective testing environment. In-lab: study was conducted in a laboratory. Crowd: study was conducted by crowdsourcing. \end{tablenotes} \end{threeparttable} \end{table*} Hence, researchers have devoted considerable efforts on the development of high-quality VQA datasets that benefit the video quality community. Table \ref{table:db_comp} summarizes the ten-year evolution of popular public VQA databases. The first successful VQA database was the LIVE Video Quality Database \cite{seshadrinathan2010study}, which was first made publicly available in 2008. It contains $10$ pristine high-quality videos subjected to compression and transmission distortions. Other similar databases targeting simulated compression and transmission distortions have been released subsequently, including EPFL-PoliMI \cite{de2010h}, VQEG-HDTV \cite{vqeg_hdtv}, IVP \cite{ivp}, TUM 1080p50 \cite{keimel2012tum}, CSIQ \cite{vu2014vis3}, MCL-V \cite{lin2015mcl}, and MCL-JCV \cite{wang2016mcl}. All of the above mentioned datasets are based on a small set of high-quality videos, dubbed ``pristine'' or ``reference,'' then synthetically distorting them in a controlled manner. We will refer to these kinds of synthetically-distorted video sets as \textit{legacy} VQA databases. Legacy databases are generally characterized by only a small number of unique contents, each simultaneously degraded by only one or at most two synthetic distortions. For most practical scenarios, these are too simple to represent the great variety of real-world videos, and hence, VQA models derived on these databases may be insufficiently generalizable to large-scale realistic commercial VQA applications. Recently, there has been tremendous growth in social media, where huge volumes of user-generated content (UGC) is shared over the media platforms such as YouTube, Facebook, and TikTok. Advances in powerful and affordable mobile devices and cloud computing techniques, combined with significant advances in video streaming have made it easy for most consumers to create, share, and view UGC pictures/videos instantaneously across the globe. Indeed, the prevalence of UGC has started to shift the focus of video quality research from \textit{legacy} synthetically-distorted databases to newer, larger-scale authentic UGC datasets, which are being used to create solutions to what we call the \textbf{\textsf{UGC-VQA problem}}. UGC-VQA studies typically follow a new design paradigm whereby: 1) All the source content is consumer-generated instead of professional-grade, thus suffers from unknown and highly diverse impairments; 2) they are only suitable for testing and comparing no-reference models, since reference videos are unavailable; 3) the types of distortions are authentic and commonly intermixed, and include but are not limited to capture impairments, editing and processing artifacts, compression, transcoding, and transmission distortions. Moreover, compression artifacts are not necessarily the dominant factors affecting video quality, unlike legacy VQA datasets and algorithms. These unpredictable perceptual degradations make perceptual quality prediction of UGC consumer videos very challenging. Here we seek to address and gain insights into this new challenge (UGC-VQA) by first, conducting a comprehensive benchmarking study of leading video quality models on several recently released large-scale UGC-VQA databases. We also propose a new fusion-based blind VQA (BVQA) algorithm, which we call the VIDeo quality EVALuator (VIDEVAL), which is created by the processes of feature selection from existing top-performing VQA models. The empirical results show that a simple aggregation of these known models can achieve state-of-the-art (SOTA) performance. We believe that our expansive study will inspire and drive future research on BVQA modeling for the challenging UGC-VQA problem, and also pave the way towards deep learning-based solutions. The outline of this paper is as follows: Section \ref{sec:ugc_db} reviews and analyzes the three most recent large-scale UGC-VQA databases, while Section \ref{sec:nr_vqa} briefly surveys the development of BVQA models. We introduce the proposed VIDEVAL model in Section \ref{sec:fs}, and provide experimental results in Section \ref{sec:exp}. Finally, concluding remarks are given in Section \ref{sec:conclud}. \begin{figure*}[!t] \def0.6{0.197} \centering \subfloat[LIVE-VQC][{LIVE-VQC}]{\includegraphics[height=0.6\textwidth]{figs/LIVE-VQC-thumbs.pdf} \label{fig:snapshota}} \hspace{-0.284em} \subfloat[KoNViD-1k][{KoNViD-1k}]{\includegraphics[height=0.6\textwidth]{figs/KONVID-1K-thumbs.pdf} \label{fig:snapshotb}} \hspace{-0.284em} \subfloat[YouTube-UGC][{YouTube-UGC}]{\includegraphics[height=0.6\textwidth]{figs/YOUTUBE-UGC-thumbs.pdf} \label{fig:snapshotc}} \caption{Sample frames of the video contents contained in the three large scale UGC-VQA databases: (a) LIVE-VQC \cite{sinno2018large}, (b) KoNViD-1k \cite{hosu2017konstanz}, and (c) YouTube-UGC \cite{wang2019youtube}. LIVE-VQC includes only natural contents captured by mobile devices, while KoNViD-1k and YouTube-UGC comprise of both natural videos, animations, and gaming sources. Note that YouTube-UGC video set is categorized whereas the others are not.} \label{fig:snapshot} \end{figure*} \begin{table*}[!t] \setlength{\tabcolsep}{4pt} \renewcommand{\arraystretch}{1.1} \centering \caption{Public large-scale user-generated content video quality assessment (UGC-VQA) databases compared: KoNViD-1k \cite{hosu2017konstanz}, LIVE-VQC \cite{sinno2018large}, and YouTube-UGC \cite{wang2019youtube}} \label{table:ugc_db_comp} \begin{tabular}{lccc} \toprule \textsc{Database Attribute} & KoNViD-1k & LIVE-VQC & YouTube-UGC \\ \hline\\[-1.em] Number of contents & 1200 & 585 & 1380 \\ Video sources & YFCC100m (Flickr) & Captured (mobile devices) & YouTube \\ Video resolutions & 540p & 1080p,720p,480p,etc. & 4k,1080p,720p,480p,360p \\ Video layouts & Landscape & Landscape,portrait & Landscape,portrait \\ Video framerates & 24,25,30 fr/sec & 20,24,25,30 fr/sec & 15,20,24,25,30,50,60 fr/sec \\ Video lengths & 8 seconds & 10 seconds & 20 seconds \\ Audio track included & Yes (97\%) & Yes & No \\ Testing methodology & Crowdsourcing (CrowdFlower) & Crowdsourcing (AMT) & Crowdsourcing (AMT) \\ Number of subjects & 642 & 4,776 & $>$8,000 \\ Number of ratings & 136,800 (114 votes/video) & 205,000 (240 votes/video) & 170,159 (123 votes/video) \\ Rating scale & Absolute Category Rating 1-5 & Continuous Rating 0-100 & Continuous Rating 1-5 \\ \multirow[t]{6}{*}{Content remarks} & \multirow[t]{6}{4.6cm}{Videos sampled from YFCC100m via a feature space of blur, colorfulness, contrast, SI, TI, and NIQE; Some contents irrelevant to quality research; Content was clipped from the original and resized to 540p.} & \multirow[t]{6}{4.6cm}{Videos manually captured by certain people; Content including many camera motions; Content including some night scenes that are prone to be outliers; Resolutions not uniformly distributed.} & \multirow[t]{6}{4.6cm}{Videos sampled from YouTube via a feature space of spatial, color, temporal, and chunk variation; Contents categorized into $15$ classes, including HDR, screen content, animations, and gaming videos.} \\ \\ \\ \\ \\ \\ \multirow[t]{5}{*}{Study remarks} & \multirow[t]{5}{4.6cm}{Study did not account for or remove videos on which stalling events occurred when viewed; test methodology prone to unreliable individual scores.} & \multirow[t]{5}{4.6cm}{Distribution of MOS values slightly skewed towards higher scores; standard deviation statistics of MOS were not provided.} & \multirow[t]{5}{4.6cm}{Distribution of MOS values slightly skewed towards higher values; three additional chunk MOS scores with standard deviation were provided.} \\ \\ \\ \\ \\ \bottomrule \end{tabular} \end{table*} \section{UGC-VQA Databases} \label{sec:ugc_db} The first UGC-relevant VQA dataset containing authentic distortions was introduced as the Camera Video Database (CVD2014) \cite{nuutinen2016cvd2014}, which consists of videos with in-the-wild distortions from 78 different video capture devices, followed by the similar LIVE-Qualcomm Mobile In-Capture Database \cite{ghadiyaram2017capture}. These two databases, however, only modeled (camera) capture distortions on small numbers of not very diverse unique contents. Inspired by the first successful massive online crowdsourcing study of UGC picture quality \cite{ghadiyaram2015massive}, the authors of \cite{hosu2017konstanz} created the KoNViD-1k video quality database, the first such resource for UGC videos. It consists of 1,200 public-domain videos sampled from the YFCC100M dataset \cite{thomee2015yfcc100m}, and was annotated by 642 crowd-workers. LIVE-VQC \cite{sinno2018large} was another large-scale UGC-VQA database with 585 videos, crowdsourced on Amazon Mechanical Turk to collect human opinions from 4,776 unique participants. The most recently published UGC-VQA database is the YouTube-UGC Dataset \cite{wang2019youtube} comprising 1,380 20-second video clips sampled from millions of YouTube videos, which were rated by more than 8,000 human subjects. Table \ref{table:ugc_db_comp} summarizes the main characteristics of the three large-scale UGC-VQA datasets studied, while Figure \ref{fig:snapshot} shows some representative snapshots of the source sequences for each database, respectively. \subsection{Content Diversity and MOS Distribution} As a way of characterizing the content diversity of the videos in each database, Winkler \cite{winkler2012analysis} suggested three quantitative attributes related to spatial activity, temporal activity, and colorfulness. Here we expand the set of attributes to include six low-level features including brightness, contrast, colorfulness \cite{hasler2003measuring}, sharpness, spatial information (SI), and temporal information (TI), thereby providing a larger visual space in which to plot and analyze content diversities of the three UGC-VQA databases. To reasonably limit the computational cost, each of these features was calculated on every 10th frame, then was averaged over frames to obtain an overall feature representation of each content. For simplicity, we denote the features as $\{\mathrm{C}_i\},i=1,2,...,6$. Figure \ref{fig:ind_feat_dis} shows the fitted kernel distribution of each selected feature. We also plotted the convex hulls of paired features, to show the feature coverage of each database, in Figure \ref{fig:feat_cvx_hull}. To quantify the coverage and uniformity of these databases over each defined feature space, we computed the relative range and uniformity of coverage \cite{winkler2012analysis}, where the relative range is given by: \begin{equation} \label{eq:relative_range} \mathrm{R}_i^k=\frac{\max(\mathrm{C}_i^k)-\min(\mathrm{C}_i^k)}{\max_{k} (\mathrm{C}_i^k)}, \end{equation} where $\mathrm{C}_i^k$ denotes the feature distribution of database $k$ for a given feature dimension $i$, and $\max_{k}(\mathrm{C}_i^k)$ specifies the maximum value for that given dimension across all databases. Uniformity of coverage measures how uniformly distributed the videos are in each feature dimension. We computed this as the entropy of the $\mathrm{B}$-bin histogram of $\mathrm{C}_i^k$ over all sources for each database indexed $k$: \begin{equation} \label{eq:uniformity} \mathrm{U}^k_i=-\sum_{b=1}^\mathrm{B} p_b \log_\mathrm{B} p_b, \end{equation} where $p_b$ is the normalized number of sources in bin $b$ at feature $i$ for database $k$. The higher the uniformity the more uniform the database is. Relative range and uniformity of coverage are plotted in Figure \ref{fig:relative_range} and Figure \ref{fig:uniformity}, respectively, quantifying the intra- and inter-database differences in source content characteristics. We also extracted 4,096-dimensional VGG-19 \cite{simonyan2014very} deep features and embedded these features into 2D subspace using t-SNE \cite{maaten2008visualizing} to further compare content diversity, as shown in Figure \ref{fig:tsne}. Apart from content diversity expressed in terms of visual features, the statistics of the subjective ratings are another important attribute of each video quality database. The main aspect considered in the analysis here is the distributions of mean opinion scores (MOS), as these are indicative of the quality range of the subjective judgements. The analysis of standard deviation of MOS is not presented here since it is not provided in LIVE-VQC. Figure \ref{fig:mos_dist} displays the histogram of MOS distributions for the three UGC-VQA databases. \begin{figure*}[!t] \captionsetup[subfigure]{justification=centering} \centering \def0.32{0.133} \def0ex{-0.4em} \subfloat[Brightness][{Brightness}]{\includegraphics[height=0.32\textwidth]{figs/brightness_mu_dist.pdf} \label{fig:ind_feat_disa}} \hspace{0ex} \subfloat[Contrast][{Contrast}]{\includegraphics[height=0.32\textwidth]{figs/contrast_mu_dist.pdf} \label{fig:ind_feat_disb}} \hspace{0ex} \subfloat[Colorfulness][{Colorfulness}]{\includegraphics[height=0.32\textwidth]{figs/colorfulness_mu_dist.pdf} \label{fig:ind_feat_disc}} \hspace{0ex} \subfloat[Sharpness][{Sharpness}]{\includegraphics[height=0.32\textwidth]{figs/sharpness_mu_dist.pdf} \label{fig:ind_feat_disd}} \hspace{0ex} \subfloat[SI][{SI}]{\includegraphics[height=0.32\textwidth]{figs/si_mu_dist.pdf} \label{fig:ind_feat_dise}} \hspace{0ex} \subfloat[TI][{TI}]{\includegraphics[height=0.32\textwidth]{figs/ti_std_mu_dist.pdf} \label{fig:ind_feat_disf}} \caption{Feature distribution comparisons among the three considered UGC-VQA databases: KoNViD-1k, LIVE-VQC, and YouTube-UGC.} \label{fig:ind_feat_dis} \end{figure*} \begin{figure}[!t] \centering \def0.32{0.12} \def0ex{-0.em} \def0.255{0.255} \def1pt{1pt} \def3pt{3pt} \footnotesize \setlength{\tabcolsep}{1.5pt} \renewcommand{\arraystretch}{1.0} \begin{tabular}{ccc} \includegraphics[ height=0.255\linewidth, keepaspectratio]{figs/KONVID_1K_BRxCT.pdf} & \includegraphics[ height=0.255\linewidth, keepaspectratio]{figs/KONVID_1K_CFxSR.pdf} & \includegraphics[ height=0.255\linewidth, keepaspectratio]{figs/KONVID_1K_SIxTI.pdf} \\[1pt] \multicolumn{3}{c}{(a) {KoNViD-1k} } \\[3pt] \includegraphics[ height=0.255\linewidth, keepaspectratio]{figs/LIVE_VQC_BRxCT.pdf} & \includegraphics[ height=0.255\linewidth, keepaspectratio]{figs/LIVE_VQC_CFxSR.pdf} & \includegraphics[ height=0.255\linewidth, keepaspectratio]{figs/LIVE_VQC_SIxTI.pdf} \\[1pt] \multicolumn{3}{c}{(b) LIVE-VQC} \\[3pt] \includegraphics[ height=0.255\linewidth, keepaspectratio]{figs/YOUTUBE_UGC_BRxCT.pdf} & \includegraphics[ height=0.255\linewidth, keepaspectratio]{figs/YOUTUBE_UGC_CFxSR.pdf} & \includegraphics[ height=0.255\linewidth, keepaspectratio]{figs/YOUTUBE_UGC_SIxTI.pdf} \\[1pt] \multicolumn{3}{c}{(c) YouTube-UGC} \\ \end{tabular} \caption{Source content (blue `x') distribution in paired feature space with corresponding convex hulls (orange boundaries). Left column: BR$\times$CT, middle column: CF$\times$SR, right column: SI$\times$TI.} \label{fig:feat_cvx_hull} \end{figure} \subsection{Observations} \label{ssec:observation} We make some observations from the above plots. As may be seen in Figures \ref{fig:ind_feat_disa} and \ref{fig:ind_feat_disb}, and the corresponding convex hulls in Figure \ref{fig:feat_cvx_hull}, KoNViD-1k and YouTube-UGC exhibit similar coverage in terms of brightness and contrast, while LIVE-VQC adheres closer to middle values. Regarding colorfulness, KoNViD-1k shows a skew towards higher scores than the other two datasets, which is consistent with the observations that Flickr users self-characterize as either professional video/photographers or as dedicated amateurs. On the sharpness and SI histograms, YouTube-UGC is spread most widely, while KoNViD-1k is concentrated on lower values. Another interesting finding from the TI statistics: LIVE-VQC is distributed more towards higher values than YouTube-UGC and KoNViD-1k, consistent with our observation that videos in LIVE-VQC were captured in the presence of larger and more frequent camera motions. We will revisit this interesting aspect of TI when evaluating the BVQA models in Section \ref{sec:exp}. The visual comparison in Figure \ref{fig:tsne} shows that YouTube-UGC and KoNViD-1k span a wider range of VGG-19 feature space than does LIVE-VQC, indicating significant content diversity differences. Figure \ref{fig:mos_dist} shows the MOS distributions: all three databases have right-skewed MOS distributions, with KoNViD-1k less so, and LIVE-VQC and YouTube-UGC more so. The overall ranges and uniformity comparisons in Figures \ref{fig:relative_range}, \ref{fig:uniformity}, and \ref{fig:tsne} suggest that constructing a database by crawling and sampling from a large content repository is likely to yield a more content-diverse, uniformly-distributed dataset than one created from pictures or videos captured directly from a set of user cameras. Both cases may be argued to be realistic in some scenario. \begin{figure}[!t] \def0.6{0.823} \centering \includegraphics[width=0.6\linewidth]{figs/relative_range.pdf} \caption{Relative range $\mathrm{R}^k_i$ comparisons of the selected six features calculated on the three UGC-VQA databases: KoNViD-1k, LIVE-VQC, and YouTube-UGC.} \label{fig:relative_range} \end{figure} \begin{figure}[!t] \def0.6{0.823} \centering \includegraphics[width=0.6\linewidth]{figs/coverage_uniformity.pdf} \caption{Comparison of coverage uniformity $\mathrm{U}^k_i$ of the selected six features computed on the three UGC-VQA databases: KoNViD-1k, LIVE-VQC, and YouTube-UGC.} \label{fig:uniformity} \end{figure} \begin{figure*}[!t] \centering \def0.32{0.16} \def0ex{10pt} \subfloat[KoNViD-1k][{KoNViD-1k}]{\includegraphics[height=0.32\textwidth]{figs/KONVID_1K_MOS_hist.pdf} \label{fig:mos_dist-a}} \hspace{0ex} \subfloat[LIVE-VQC][{LIVE-VQC}]{\includegraphics[height=0.32\textwidth]{figs/LIVE_VQC_MOS_hist.pdf} \label{fig:mos_dist-b}} \hspace{0ex} \subfloat[YouTube-UGC][{{YouTube-UGC}}]{\includegraphics[height=0.32\textwidth]{figs/YOUTUBE_UGC_MOS_hist.pdf} \label{fig:mos_dist-c}} \caption{MOS histograms and the fitted kernel distributions of the three UGC-VQA databases: KoNViD-1k, LIVE-VQC, and YouTube-UGC.} \label{fig:mos_dist} \end{figure*} \begin{figure}[!t] \def0.6{0.6} \centering \includegraphics[width=0.6\linewidth]{figs/tSNE_vgg19.pdf} \caption{VGG-19 deep feature embedding via t-SNE \cite{maaten2008visualizing} on KoNViD-1k, LIVE-VQC, and YouTube-UGC, respectively.} \label{fig:tsne} \end{figure} \section{UGC-VQA Models} \label{sec:nr_vqa} The goal of subjective video quality studies is to motivate the development of automatic objective video quality models. Conventionally, objective video quality assessment can be classified into three main categories: full-reference (FR), reduced-reference (RR), and no-reference (NR) models. FR-VQA models require the availability of an entire pristine source video to measure visual differences between a target signal and a corresponding reference \cite{wang2004video, vmaf,sheikh2005information, chen2020perceptual}, while RR-VQA models only make use of a limited amount of reference information \cite{wang2005reduced,soundararajan2012video}. Some popular FR-VQA models, including PSNR, SSIM \cite{wang2004image}, and VMAF \cite{vmaf} have already been successfully and massively deployed to optimize streaming and shared/uploaded video encoding protocols by leading video service providers. NR-VQA or BVQA models, however, rely solely on analyzing the test stimuli without the benefit of any corresponding ``ground truth'' pristine signal. It is obvious that only BVQA models are appropriate for the UGC-VQA problem. Here we briefly review the evolution of BVQA models, from conventional handcrafted feature-based approaches, on to convolutional neural network-based models. \subsection{Conventional Feature-Based BVQA Models} Almost all of the earliest BVQA models have been `distortion specific,' meaning they were designed to quantify a specific type of distortion such as blockiness \cite{wang2000blind}, blur \cite{marziliano2002no}, ringing \cite{ feng2006measurement}, banding \cite{ wang2016perceptual, tu2020bband, tu2020adaptive}, or noise \cite{amer2005fast, norkin2018film} in distorted videos, or to assess multiple specific coincident distortion types caused by compression or transmission impairments \cite{caviedes2017no, keimel2009no}. More recent top-performing BVQA models are almost exclusively learning-based, leveraging a set of generic quality-aware features, combined to conduct quality prediction by machine learning regression \cite{ moorthy2011blind, mittal2012no, saad2014blind, kundu2017no, ghadiyaram2017perceptual, korhonen2019two, ye2012unsupervised, pei2015image, tu2021rapique}. Learning-based BVQA models are more versatile and generalizable than `distortion specific' models, in that the selected features are broadly perceptually relevant, while powerful regression models can adaptively map the features onto quality scores learned from the data in the context of a specific application. The most popular BVQA algorithms deploy perceptually relevant, low-level features based on simple, yet highly regular parametric bandpass models of good-quality scene statistics \cite{ruderman1994statistics}. These natural scene statistics (NSS) models predictably deviate in the presence of distortions, thereby characterizing perceived quality degradations \cite{sheikh2006image}. Successful blind picture quality assessment (BIQA) models of this type have been developed in the wavelet (BIQI \cite{moorthy2010two}, DIIVINE \cite{moorthy2011blind}, C-DIIVINE \cite{zhang2014c}), discrete cosine transform (BLIINDS \cite{saad2010dct}, BLIINDS-II \cite{saad2012blind}), curvelet \cite{liu2014no}, and spatial intensity domains (NIQE \cite{mittal2012making}, BRISQUE \cite{mittal2012no}), and have further been extended to video signals using natural bandpass space-time video statistics models \cite{li2016spatiotemporal,mittal2015completely,saad2014blind, sinno2019spatio}, among which the most well-known model is the Video-BLIINDS \cite{saad2014blind}. Other extensions to empirical NSS include the joint statistics of the gradient magnitude and Laplacian of Gaussian responses in the spatial domain (GM-LOG \cite{xue2014blind}), in log-derivative and log-Gabor spaces (DESIQUE \cite{zhang2013no}), as well as in the gradient domain of LAB color transforms (HIGRADE \cite{kundu2017no}). The FRIQUEE model \cite{ghadiyaram2017perceptual} has been observed to achieve SOTA performance both on UGC/consumer video/picture databases like LIVE-Challenge \cite{ghadiyaram2015massive}, CVD2014 \cite{nuutinen2016cvd2014}, and KoNViD-1k \cite{hosu2017konstanz} by leveraging a bag of NSS features drawn from diverse color spaces and perceptually motivated transform domains. Instead of using NSS-inspired feature descriptors, methods like CORNIA \cite{ye2012unsupervised} employ unsupervised learning techniques to learn a dictionary (or codebook) of distortions from raw image patches, and was further extended to Video CORNIA \cite{xu2014no} by applying an additional temporal hysteresis pooling \cite{seshadrinathan2011temporal} of learned frame-level quality scores. Similar to CORNIA, the authors of \cite{xu2016blind} proposed another codebook-based general-purpose BVQA method based on High Order Statistics Aggregation (HOSA), requiring only a small codebook, yet yielding promising performance. A very recent handcrafted feature-based BVQA model is the ``two level'' video quality model (TLVQM) \cite{korhonen2019two}, wherein a two-level feature extraction mechanism is adopted to achieve efficient computation of a set of carefully-defined impairment/distortion-relevant features. Unlike NSS features, TLVQM selects a comprehensive feature set comprising of empirical motion statistics, specific artifacts, and aesthetics. TLVQM does require that a large set of parameters (around 30) be specified, which may affect performance on datasets or application scenarios it has not been exposed to. The model currently achieves SOTA performance on three UGC video quality databases, CVD2014 \cite{nuutinen2016cvd2014}, KoNViD-1k \cite{hosu2017konstanz}, and LIVE-Qualcomm \cite{ghadiyaram2017capture}, at a reasonably low complexity, as reported by the authors. \subsection{Deep Convolutional Neural Network-Based BVQA Models} Deep convolutional neural networks (CNNs or ConvNets) have been shown to deliver standout performance on a wide variety of low-level computer vision applications. Recently, the release of several ``large-scale'' (in the context of IQA/VQA research) subjective quality databases \cite{ghadiyaram2015massive, hosu2017konstanz} have sped the application of deep CNNs to perceptual quality modeling. For example, several deep learning picture-quality prediction methods were proposed in \cite{kang2014convolutional, kim2017deep, ying2019patches, chen2020proxiqa}. To conquer the limits of data scale, they either propose to conduct patch-wise training \cite{kang2014convolutional, bosse2016deep, kim2017deep} using global scores, or by pretraining deep nets on ImageNet \cite{deng2009imagenet}, then fine tuning. Several authors report SOTA performance on legacy synthetic distortion databases \cite{sheikh2006statistical,ponomarenko2013color} or on naturally distorted databases \cite{ghadiyaram2015massive, hosu2020koniq}. Among the applications of deep CNNs to blind video quality prediction, Kim \cite{kim2018deep} proposed a deep video quality assessor (DeepVQA) to learn the spatio-temporal visual sensitivity maps via a deep ConvNet and a convolutional aggregation network. The V-MEON model \cite{liu2018end} used a multi-task CNN framework which jointly optimizes a 3D-CNN for feature extraction and a codec classifier using fully-connected layers to predict video quality. Zhang \cite{zhang2018blind} leveraged transfer learning to develop a general-purpose BVQA framework based on weakly supervised learning and a resampling strategy. In the VSFA model \cite{li2019quality}, the authors applied a pre-trained image classification CNN as a deep feature extractor and integrated the frame-wise deep features using a gated recurrent unit and a subjectively-inspired temporal pooling layer, and reported leading performance on several natural video databases \cite{nuutinen2016cvd2014, hosu2017konstanz, ghadiyaram2017capture}. These SOTA deep CNN-based BVQA models \cite{kim2018deep, liu2018end, zhang2018blind, li2019quality} produce accurate quality predictions on legacy (single synthetic distortion) video datasets \cite{seshadrinathan2010study, vu2014vis3}, but struggle on recent in-the-wild UGC databases \cite{nuutinen2016cvd2014, ghadiyaram2017capture,hosu2017konstanz}. \begin{table}[!t] \setlength{\tabcolsep}{4pt} \renewcommand{\arraystretch}{1.1} \centering \caption{Summary of the initial feature set and the finalized VIDEVAL subset after feature selection.} \label{table:feat_sum} \begin{threeparttable} \begin{tabular}{llcc} \toprule \textsc{Feature Name} & \textsc{Feature Index} & \textsc{\#($\mathcal{F}_\mathrm{INIT}$)} & \textsc{\#($\mathrm{VIDEVAL}$)} \\ \hline\\[-1.em] BRISQUE\textsubscript{avg} & $f_1-f_{36}$ & 36 & 3 \\ BRISQUE\textsubscript{std} & $f_{37}-f_{72}$ & 36 & 1 \\ GM-LOG\textsubscript{avg} & $f_{73}-f_{112}$ & 40 & 4 \\ GM-LOG\textsubscript{std} & $f_{113}-f_{152}$ & 40 & 5 \\ HIGRADE-GRAD\textsubscript{avg} & $f_{153}-f_{188}$ & 36 & 8 \\ HIGRADE-GRAD\textsubscript{std} & $f_{189}-f_{224}$ & 36 & 1 \\ FRIQUEE-LUMA\textsubscript{avg} & $f_{225}-f_{298}$ & 74 & 4 \\ FRIQUEE-LUMA\textsubscript{std} & $f_{299}-f_{372}$ & 74 & 8 \\ FRIQUEE-CHROMA\textsubscript{avg} & $f_{373}-f_{452}$ & 80 & 10 \\ FRIQUEE-CHROMA\textsubscript{std} & $f_{453}-f_{532}$ & 80 & 1 \\ FRIQUEE-LMS\textsubscript{avg} & $f_{533}-f_{606}$ & 74 & 1 \\ FRIQUEE-LMS\textsubscript{std} & $f_{607}-f_{680}$ & 74 & 0 \\ FRIQUEE-HS\textsubscript{avg} & $f_{681}-f_{684}$ & 4 & 0 \\ FRIQUEE-HS\textsubscript{std} & $f_{685}-f_{688}$ & 4 & 0 \\ TLVQM-LCF\textsubscript{avg} & $f_{689}-f_{710}$ & 22 & 5 \\ TLVQM-LCF\textsubscript{std} & $f_{711}-f_{733}$ & 23 & 3 \\ TLVQM-HCF & $f_{734}-f_{763}$ & 30 & 6 \\ \hline\\[-1.em] $\mathcal{F}_\mathrm{ALL}$ & $f_1-f_{763}$ & 763 & 60 \\ \bottomrule \end{tabular} \begin{tablenotes}[para,flushleft] \footnotesize \item $^\star$All the spatial features are calculated every two frames and aggregated into a single feature vector within 1-sec chunks. The overall feature vector for the whole video is then obtained by averaging all the chunk-wise feature vectors. Subscript \textit{avg} means within-chunk average pooling, whereas subscript \textit{std} means within-chunk standard deviation pooling. \end{tablenotes} \end{threeparttable} \end{table} \section{Feature Fused VIDeo Quality EVALuator (VIDEVAL)} \label{sec:fs} We have just presented a diverse set of BVQA models designed from a variety of perspectives, each either based on scene statistics, or motivated by visual impairment heuristics. As might be expected, and as we shall show later, the performances of these models differ, and also vary on different datasets. We assume that the features extracted from different models may represent statistics of the signal in different perceptual domains, and henceforce, a selected fusion of BVQA models may be expected to deliver better consistency against subjective assessment, and also to achieve more reliable performance across different databases and use cases. This inspired our new feature fused VIDeo quality EVALuator (VIDEVAL), as described next. \begin{figure}[!t] \def0.32{0.8} \def1{1} \centering \includegraphics[width=0.32\linewidth]{figs/ALL_COMBINED_feat_sel_results_plot.pdf} \caption{{Feature selection performance (PLCC) of three selected algorithms as a function of $k$ on the All-Combined\textsubscript{c} dataset. The shaded error bar denotes the standard deviation of PLCC over 10 iterations.}} \label{fig:feat_sel} \end{figure} \begin{figure}[!t] \def0.32{0.8} \def1{1} \centering \includegraphics[width=0.32\linewidth]{figs/ALL_COMBINED_model_based_svr_feat_importance.pdf} \caption{Visualization of the second step in feature selection: frequency of each feature being selected over 100 iterations of train-test splits using SVR importance selection method with fixed $k=60$.} \label{fig:feat_import} \end{figure} We begin by constructing an initial feature set on top of existing high-performing, compute-efficient BVQA models and features, distilled through a feature selection program. The goal of feature selection is to choose an optimcal or sub-optimal feature subset $\mathcal{F}_{k}\in \mathbb{R}^k$ from the initial feature set $\mathcal{F}_{\mathrm{INIT}}\in \mathbb{R}^\mathrm{N}$ (where $k<{N}$) that achieves nearly top performance but with many fewer features. \subsection{Feature Extraction} \label{ssec:feat_extract} We construct an initial feature set by selecting features from existing top-performing BVQA models. For practical reasons, we ignore features with high computational cost, e.g., certain features from DIIVINE, BLIINDS, C-DIIVINE, and V-BLIINDS. We also avoid using duplicate features in different models, such as the BRISQUE-like features in HIGRADE, and the C-DIIVINE features in V-BLIINDS. This filtering process yields the initial feature candidates, which we denote as BRISQUE, GM-LOG, HIGRADE-GRAD, FRIQUEE-LUMA, FRIQUEE-CHROMA, FRIQUEE-LMS, FRIQUEE-HS, TLVQM-LCF, and TLVQM-HCF. Inspired by the efficacy of standard deviation pooling as first introduced in GMSD \cite{xue2013gradient} and later also used in TLVQM \cite{korhonen2019two}, we calculate these spatial features every second frame within each sequentially cut non-overlapping one-second chunk, then we enrich the feature set by applying average and standard deviation pooling of frame-level features within each chunk, based on the hypothesis that the variation of spatial NSS features also correlates with the temporal properties of the video. Finally, all the chunk-wise feature vectors are average pooled \cite{tu2020comparative} across all the chunks to derive the final set of features for the entire video. Table \ref{table:feat_sum} indexes and summarizes the selected features in the initial feature set, yielding an overall 763-dimensional feature vector, $\mathcal{F}_\mathrm{INIT}\in\mathbb{R}^{763}$. \begin{figure}[!t] \centering \def0.32{0.4} \def0ex{0ex} \subfloat[][{}]{\includegraphics[height=0.32\linewidth]{figs/inlsa_before.pdf} \label{fig:inlsa-a}} \hspace{0ex} \subfloat[][{}]{\includegraphics[height=0.32\linewidth]{figs/inlsa_after.pdf} \label{fig:inlsa-b}} \caption{Scatter plots of MOS versus NIQE scores (a) before, and (b) after INLSA calibration \cite{pinson2003objective} using YouTube-UGC as the reference set.} \label{fig:inlsa} \end{figure} \subsection{Feature Selection} \label{ssec:feat_select} We deploy two types of feature selection algorithms to distill the initial feature set. The first method is a model-based feature selector that utilizes a machine learning model to suggest features that are important. We employed the popular random forest (RF) to fit a regression model and eliminate the least significant features sorted by permutation importance. We also trained a support vector machine (SVM) with the linear kernel to rank the features, as a second model selector. Another sub-optimal solution is to apply a greedy search approach to find a good feature subset. Here we employed Sequential Forward Floating Selection (SFFS), and used SVM as the target regressor with its corresponding mean squared error between the predictions and MOS as the cost function. The mean squared error is calculated by cross-validation measures of predictive accuracy to avoid overfitting. One problem with feature selection is that we do not know \textit{a priori} what $k$ to select, i.e., how many features are needed. Therefore, we conducted a two-step feature selection procedure. First, we evaluated the feature selection methods as a function of $k$ via 10 train-test iterations, to select the best algorithm with corresponding optimal $k$. Figure \ref{fig:feat_sel} shows the median PLCC (defined in Section \ref{ssec:eval_proto}) performance with respect to $k$ for different feature selection models, based on which we finally chose the SVM importance method with $k=60$ in our next experiments. In the second step, we applied the best feature selection algorithm with the fixed best $k$ over 100 random train-test splits. On each iteration, a subset is selected from the feature selector, based on which the frequency of each feature over the iterations is counted, and the $j$ most frequently occurring features are included into the final feature set. Figure \ref{fig:feat_import} shows the frequency of each feature being selected over 100 random splits in the second step. This selection process is implemented on a combined dataset constructed from three independent databases, as described in Section \ref{ssec:eval_proto}. Table \ref{table:feat_sum} summarizes the results of the feature selection procedure (SVR importance with $k=60$), yielding the final proposed VIDEVAL model. \begin{figure}[!t] \centering \def0.32{0.98} \includegraphics[width=0.32\linewidth]{figs/ALL_COMBINED_boxplot_new.pdf} \caption{Box plots of PLCC, SRCC, and KRCC of evaluated learning-based BVQA algorithms on the All-Combined\textsubscript{c} dataset over 100 random splits. For each box, median is the central box, and the edges of the box represent 25th and 75th percentiles, while red circles denote outliers.} \label{fig:all_boxplot} \end{figure} \begin{table}[!t] \setlength{\tabcolsep}{4pt} \renewcommand{\arraystretch}{1.1} \centering \caption{Performance comparison of evaluated opinion-unaware ``completely blind'' BVQA models.} \label{table:compete-blind} \begin{tabular}{llcccc} \toprule \textsc{Dataset} & \textsc{Model} \textbackslash\ \textsc{Metric} & SRCC$\uparrow$ & KRCC$\uparrow$ & PLCC$\uparrow$ & RMSE$\downarrow$ \\ \hline\\[-1.em] \multirow{3}{*}{KoNViD} & NIQE (1 fr/sec) & 0.5417 & 0.3790 & 0.5530 & 0.5336 \\ & ILNIQE (1 fr/sec) & 0.5264 & 0.3692 & 0.5400 & 0.5406 \\ & VIIDEO & 0.2988 & 0.2036 & 0.3002 & 0.6101 \\ \hline\\[-1.em] \multirow{3}{*}{LIVE-C} & NIQE (1 fr/sec) & 0.5957 & 0.4252 & 0.6286 & 13.110 \\ & ILNIQE (1 fr/sec) & 0.5037 & 0.3555 & 0.5437 & 14.148 \\ & VIIDEO & 0.0332 & 0.0231 & 0.2146 & 16.654 \\ \hline\\[-1.em] \multirow{3}{*}{YT-UGC} & NIQE (1 fr/sec) & 0.2379 & 0.1600 & 0.2776 & 0.6174 \\ & ILNIQE (1 fr/sec) & 0.2918 & 0.1980 & 0.3302 & 0.6052 \\ & VIIDEO & 0.0580 & 0.0389 & 0.1534 & 0.6339 \\ \hline\\[-1.em] \multirow{3}{*}{All-Comb} & NIQE (1 fr/sec) & 0.4622 & 0.3222 & 0.4773 & 0.6112 \\ & ILNIQE (1 fr/sec) & 0.4592 & 0.3213 & 0.4741 & 0.6119 \\ & VIIDEO & 0.1039 & 0.0688 & 0.1621 & 0.6804 \\ \bottomrule \end{tabular} \end{table} \begin{table*}[!t] \setlength{\tabcolsep}{2.7pt} \renewcommand{\arraystretch}{1.1} \centering \begin{threeparttable} \caption{Performance comparison of evaluated BVQA models on the four benchmark datasets. The \underline{\textbf{underlined}} and \textbf{boldfaced} entries indicate the best and top three performers on each database for each performance metric, respectively.} \label{table:eval_svr} \begin{tabular}{lcccccccccc} \toprule \textsc{Dataset} & \multicolumn{4}{c}{KoNViD-1k} & & \multicolumn{4}{c}{LIVE-VQC} \\ \cline{2-5}\cline{7-10}\\[-1.em] \textsc{Model} \textbackslash\ \textsc{Metric} & \textsc{SRCC$\uparrow$ (std)} & \textsc{KRCC$\uparrow$ (std)} & \textsc{PLCC$\uparrow$ (std)} & \textsc{RMSE$\downarrow$ (std)} & & \textsc{SRCC$\uparrow$ (std)} & \textsc{KRCC$\uparrow$ (std)} & \textsc{PLCC$\uparrow$ (std)} & \textsc{RMSE$\downarrow$ (std)} \\ \hline\\[-1.em] BRISQUE (1 fr/sec) & 0.6567 (.035) & 0.4761 (.029) & 0.6576 (.034) & 0.4813 (.022) & & 0.5925 (.068) & 0.4162 (.052) & 0.6380 (.063) & 13.100 (.796) \\ GM-LOG (1 fr/sec) & 0.6578 (.032) & 0.4770 (.026) & 0.6636 (.031) & 0.4818 (.022) & & 0.5881 (.068) & 0.4180 (.052) & 0.6212 (.063) & 13.223 (.822) \\ HIGRADE (1 fr/sec) & 0.7206 (.030) & 0.5319 (.026) & 0.7269 (.028) & 0.4391 (.018) & & 0.6103 (.068) & 0.4391 (.054) & 0.6332 (.065) & 13.027 (.904) \\ FRIQUEE (1 fr/sec) & 0.7472 (.026) & 0.5509 (.024) & 0.7482 (.025) & 0.4252 (.017) & & 0.6579 (.053) & 0.4770 (.043) & 0.7000 (.058) & 12.198 (.914) \\ CORNIA (1 fr/sec) & 0.7169 (.024) & 0.5231 (.021) & 0.7135 (.023) & 0.4486 (.018) & & 0.6719 (.047) & 0.4849 (.039) & 0.7183 (.042) & 11.832 (.700) \\ HOSA (1 fr/sec) & 0.7654 (.022) & 0.5690 (.021) & 0.7664 (.020) & 0.4142 (.016) & & 0.6873 (.046) & 0.5033 (.039) & {\textbf{0.7414 (.041)}} & {\textbf{11.353 (.747)}} \\ VGG-19 (1 fr/sec) & {\textbf{0.7741 (.028)}} & {\textbf{0.5841 (.027)}} & {\textbf{0.7845 (.024)}} & {\textbf{0.3958 (.017)}} & & 0.6568 (.053) & 0.4722 (.044) & 0.7160 (.048) & 11.783 (.696) \\ ResNet-50 (1 fr/sec) & \textbf{\underline{0.8018} (.025)} & {\textbf{\underline{0.6100} (.024)}} & {\textbf{\underline{0.8104} (.022)}} & {\textbf{\underline{0.3749} (.017)}} & & 0.6636 (.051) & 0.4786 (.042) & 0.7205 (.043) & 11.591 (.733) \\ KonCept512 (1 fr/sec) & 0.7349 (.025) & 0.5425 (.023) & 0.7489 (.024) & 0.4260 (.016) & & 0.6645 (.052) & 0.4793 (.045) & 0.7278 (.046) & 11.626 (.767) \\ PaQ-2-PiQ (1 fr/sec) & 0.6130 (.032) & 0.4334 (.026) & 0.6014 (.033) & 0.5148 (.019) & & 0.6436 (.045) & 0.4568 (.035) & 0.6683 (.044) & 12.619 (.848) \\ V-BLIINDS & 0.7101 (.031) & 0.5188 (.026) & 0.7037 (.030) & 0.4595 (.023) & & {\textbf{0.6939 (.050)}} & {\textbf{0.5078 (.042)}} & 0.7178 (.050) & 11.765 (.828) \\ TLVQM & 0.7729 (.024) & 0.5770 (.022) & 0.7688 (.023) & 0.4102 (.017) & & {\textbf{\underline{0.7988} (.036)}} & {\textbf{\underline{0.6080} (.037)}} & {\textbf{\underline{0.8025} (.036)}} & {\textbf{\underline{10.145} (.818)}} \\ VIDEVAL & \textbf{0.7832 (.021)} & \textbf{0.5845 (.021)} & \textbf{0.7803 (.022)} & \textbf{0.4026 (.017)} & & \textbf{0.7522 (.039)} & \textbf{0.5639 (.036)} & \textbf{0.7514 (.042)} & \textbf{11.100 (.810)} \\ \midrule \textsc{Dataset} & \multicolumn{4}{c}{YouTube-UGC} & & \multicolumn{4}{c}{All-Combined\textsubscript{c}\hyperlink{all_exp}{$^\dagger$}} \\ \cline{2-5}\cline{7-10}\\[-1.em] \textsc{Model} \textbackslash\ \textsc{Metric} & \textsc{SRCC$\uparrow$ (std)} & \textsc{KRCC$\uparrow$ (std)} & \textsc{PLCC$\uparrow$ (std)} & \textsc{RMSE$\downarrow$ (std)} & & \textsc{SRCC$\uparrow$ (std)} & \textsc{KRCC$\uparrow$ (std)} & \textsc{PLCC$\uparrow$ (std)} & \textsc{RMSE$\downarrow$ (std)} \\ \hline\\[-1.em] BRISQUE (1 fr/sec) & 0.3820 (.051) & 0.2635 (.036) & 0.3952 (.048) & 0.5919 (.021) & & 0.5695 (.028) & 0.4030 (.022) & 0.5861 (.027) & 0.5617 (.016) \\ GM-LOG (1 fr/sec) & 0.3678 (.058) & 0.2517 (.041) & 0.3920 (.054) & 0.5896 (.022) & & 0.5650 (.029) & 0.3995 (.022) & 0.5942 (.030) & 0.5588 (.014) \\ HIGRADE (1 fr/sec) & {\textbf{0.7376 (.033)}} & {\textbf{0.5478 (.028)}} & {\textbf{0.7216 (.033)}} & {\textbf{0.4471 (.024)}} & & 0.7398 (.018) & 0.5471 (.016) & {0.7368 (.019)} & {0.4674 (.015)} \\ FRIQUEE\hyperlink{fri_exp}{$^{\star}$} (1 fr/sec) & {\textbf{{0.7652} (.030)}} & {\textbf{{0.5688} (.026)}} & {\textbf{{0.7571} (.032)}} & {\textbf{{0.4169} (.023)}} & & {\textbf{{0.7568} (.023)}} & {\textbf{{0.5651} (.021)}} & {\textbf{0.7550 (.022)}} & {\textbf{0.4549 (.018)}} \\ CORNIA (1 fr/sec) & 0.5972 (.041) & 0.4211 (.032) & 0.6057 (.039) & 0.5136 (.024) & & 0.6764 (.021) & 0.4846 (.017) & 0.6974 (.020) & 0.4946 (.013) \\ HOSA (1 fr/sec) & 0.6025 (.034) & 0.4257 (.026) & 0.6047 (.034) & 0.5132 (.021) & & 0.6957 (.018) & 0.5038 (.015) & 0.7082 (.016) & 0.4893 (.013) \\ VGG-19 (1 fr/sec) & 0.7025 (.028) & 0.5091 (.023) & 0.6997 (.028) & 0.4562 (.020) & & 0.7321 (.018) & 0.5399 (.016) & 0.7482 (.017) & {0.4610 (.013)} \\ ResNet-50 (1 fr/sec) & 0.7183 (.028) & 0.5229 (.024) & 0.7097 (.027) & 0.4538 (.021) & & {\textbf{0.7557 (.017)}} & {\textbf{0.5613 (.016)}} & {\textbf{{0.7747} (.016)}} & {\textbf{{0.4385} (.013)}} \\ KonCept512 (1 fr/sec) & 0.5872 (.039) & 0.4101 (.030) & 0.5940 (.041) & 0.5135 (.022) & & 0.6608 (.022) & 0.4759 (.018) & 0.6763 (.022) & 0.5091 (.014) \\ PaQ-2-PiQ (1 fr/sec) & 0.2658 (.047) & 0.1778 (.032) & 0.2935 (.049) & 0.6153 (.019) & & 0.4727 (.029) & 0.3242 (.021) & 0.4828 (.029) & 0.6081 (.015) \\ V-BLIINDS & 0.5590 (.049) & 0.3899 (.036) & 0.5551 (.046) & 0.5356 (.022) & & 0.6545 (.023) & 0.4739 (.019) & 0.6599 (.023) & 0.5200 (.016) \\ TLVQM & 0.6693 (.030) & 0.4816 (.025) & {0.6590} ({.030}) & {0.4849} ({.022}) & & {0.7271 (.018)} & {0.5347 (.016)} & {0.7342 (.018)} & {0.4705 (.013)} \\ VIDEVAL\hyperlink{fri_exp}{$^{\star}$} & \textbf{\underline{0.7787} (.025)} & \textbf{\underline{0.5830} (.023)} & \textbf{\underline{0.7733} (.025)} & \textbf{\underline{0.4049} (.021)} & & {\textbf{\underline{0.7960} (.015)}} & {\textbf{\underline{0.6032} (.014)}} & {\textbf{\underline{0.7939} (.015)}} & {\textbf{\underline{0.4268} (.015)}} \\ \bottomrule \end{tabular} \begin{tablenotes}[para,flushleft] \footnotesize \item \hypertarget{fri_exp}{$^\star$}FRIQUEE and VIDEVAL were evaluated on a subset of 1,323 color videos in YouTube-UGC, denoted YouTube-UGC\textsubscript{c}, since it yields numerical errors when calculating on the remaining $57$ grayscale videos. For the other BVQA models evaluated, no significant difference was observed when evaluated on YouTube-UGC\textsubscript{c} versus YouTube-UGC, and hence we still report the results on YouTube-UGC. \\ \item \hypertarget{all_exp}{$^\dagger$}For a fair comparison, we only combined and calibrated (via INLSA \cite{pinson2003objective}) all the color videos from these three databases to obtain the combined dataset, i.e., All-Combined\textsubscript{c} (3,108)\! $=$\! KoNViD-1k (1,200)\! $+$\! LIVE-VQC (585)\! $+$\! YouTube-UGC\textsubscript{c} (1,323). \end{tablenotes} \end{threeparttable} \end{table*} \begin{figure*}[!t] \captionsetup[subfigure]{justification=centering} \centering \def0ex{0em} \def0.32{0.188} \subfloat[BRISQUE]{\includegraphics[width=0.32\textwidth]{figs/ALL_COMBINED_BRISQUE_kfCV_corr.pdf} \label{fig1a}} \hspace{0ex} \subfloat[GM-LOG]{\includegraphics[width=0.32\textwidth]{figs/ALL_COMBINED_GMLOG_kfCV_corr.pdf} \label{fig1b}} \hspace{0ex} \subfloat[HIGRADE]{\includegraphics[width=0.32\textwidth]{figs/ALL_COMBINED_HIGRADE1_kfCV_corr.pdf} \label{fig1c}} \hspace{0ex} \subfloat[FRIQUEE]{\includegraphics[width=0.32\textwidth]{figs/ALL_COMBINED_FRIQUEEALL_kfCV_corr.pdf} \label{fig1d}} \subfloat[CORNIA]{\includegraphics[width=0.32\textwidth]{figs/ALL_COMBINED_CORNIA10K_kfCV_corr.pdf} \label{fig1e}} \\[-2ex] \subfloat[HOSA]{\includegraphics[width=0.32\textwidth]{figs/ALL_COMBINED_HOSA_kfCV_corr.pdf} \label{fig1f}} \hspace{0ex} \subfloat[VGG-19]{\includegraphics[width=0.32\textwidth]{figs/ALL_COMBINED_vgg19_kfCV_corr.pdf} \label{fig1g}} \hspace{0ex} \subfloat[ResNet-50]{\includegraphics[width=0.32\textwidth]{figs/ALL_COMBINED_resnet50_kfCV_corr.pdf} \label{fig1h}} \hspace{0ex} \subfloat[KonCept512]{\includegraphics[width=0.32\textwidth]{figs/ALL_COMBINED_KONCEPT512_kfCV_corr.pdf} \label{fig1i}} \hspace{0ex} \subfloat[PaQ-2-PiQ]{\includegraphics[width=0.32\textwidth]{figs/ALL_COMBINED_PAQ2PIQ_kfCV_corr.pdf} \label{fig1j}} \\ [-2ex] \subfloat[V-BLIINDS]{\includegraphics[width=0.32\textwidth]{figs/ALL_COMBINED_VBLIINDS_org_kfCV_corr.pdf} \label{fig1k}} \hspace{0ex} \subfloat[TLVQM]{\includegraphics[width=0.32\textwidth]{figs/ALL_COMBINED_TLVQM_kfCV_corr.pdf} \label{fig1l}} \hspace{0ex} \subfloat[{VIDEVAL}]{\includegraphics[width=0.32\textwidth]{figs/ALL_COMBINED_FFVIQE_release_kfCV_corr.pdf} \label{fig1m}} \caption{Scatter plots and nonlinear logistic fitted curves of VQA models versus MOS trained with a grid-search SVR using $k$-fold cross-validation on the All-Combined\textsubscript{c} set. (a) BRISQUE (1 fr/sec), (b) GM-LOG (1 fr/sec), (c) HIGRADE (1 fr/sec), (d) FRIQUEE (1 fr/sec), (e) CORNIA (1 fr/sec), (f) HOSA (1 fr/sec), (g) VGG-19 (1 fr/sec), (h) ResNet-50 (1 fr/sec), (i) KonCept512 (1 fr/sec), (j) PaQ-2-PiQ (1 fr/sec), (k) V-BLIINDS, (l) TLVQM, and (m) VIDEVAL.} \label{fig:kvcv_draw} \end{figure*} \section{Experimental Results} \label{sec:exp} \subsection{Evaluation Protocol} \label{ssec:eval_proto} \textbf{UGC Dataset Benchmarks.} To conduct BVQA performance evaluation, we used the three UGC-VQA databases: KoNViD-1K \cite{hosu2017konstanz}, LIVE-VQC \cite{sinno2018large}, and YouTube-UGC \cite{wang2019youtube}. We found that the YouTube-UGC dataset contains 57 grayscale videos, which yield numerical errors when computing the color model FRIQUEE. Therefore, we extracted a subset of 1,323 color videos from YouTube-UGC, which we denote here as the YouTube-UGC\textsubscript{c} set, for the evaluation of color models. In order to study overall model performances on all the databases, we created a large composite benchmark, which is referred to here as All-Combined\textsubscript{c}, using the iterative nested least squares algorithm (INLSA) suggested in \cite{pinson2003objective}, wherein YouTube-UGC is selected as the anchor set, and the objective MOS from the other two sets, KoNViD-1k and LIVE-VQC, are linearly mapped onto a common scale ($[1,5]$). Figure \ref{fig:inlsa} shows scatter plots of MOS versus NIQE scores before (Figure \ref{fig:inlsa-a}) and after (Figure \ref{fig:inlsa-b}) INLSA linear mapping, calibrated by NIQE \cite{mittal2012making} scores. The All-Combined\textsubscript{c} (3,108) dataset is simply the union of KoNViD-1k (1,200), LIVE-VQC (575), and YouTube-UGC\textsubscript{c} (1,323) after MOS calibration: \begin{equation} \label{eq:mos_cal_kon} y_\mathrm{adj}=5-4\times\left[(5-y_\mathrm{org})/4\times1.1241-0.0993\right] \end{equation} \begin{equation} \label{eq:mos_cal_live} y_\mathrm{adj}=5-4\times\left[(100-y_\mathrm{org})/100\times0.7132+0.0253\right] \end{equation} where (\ref{eq:mos_cal_kon}) and (\ref{eq:mos_cal_live}) are for calibrating KoNViD-1k and LIVE-VQC, respectively. $y_\mathrm{adj}$ denotes the adjusted scores, while $y_\mathrm{org}$ is the original MOS. \textbf{BVQA Model Benchmarks.} We include a number of representative BVQA/BIQA algorithms in our benchmarking evaluation as references to be compared against. These baseline models include NIQE \cite{mittal2012making}, ILNIQE \cite{zhang2015feature}, VIIDEO \cite{mittal2015completely}, BRISQUE \cite{mittal2012no}, GM-LOG \cite{xue2014blind}, HIGRADE \cite{kundu2017no}, FRIQUEE \cite{ghadiyaram2017perceptual}, CORNIA \cite{ye2012unsupervised}, HOSA \cite{xu2016blind}, KonCept512 \cite{hosu2020koniq}, PaQ-2-PiQ \cite{ying2019patches}, V-BLIINDS \cite{saad2014blind}, and TLVQM \cite{korhonen2019two}. Among these, NIQE, ILNIQE, and VIIDEO are ``completely blind'' (opinion-unaware (OU)), since no training is required to build them. The rest of the models are all training-based (opinion-aware (OA)) and we re-train the models/features when evaluating on a given dataset. We also utilized the well-known deep CNN models VGG-19 \cite{simonyan2014very} and ResNet-50 \cite{he2016deep} as additional CNN-based baseline models, where each was pretrained on the ImageNet classification task. The fully-connected layer (4,096-dim) from VGG-19 and average-pooled layer (2,048-dim) from ResNet-50 served as deep feature descriptors, by operating on 25 227$\times$227 random crops of each input frame, then average-pooled into a single feature vector representing the entire frame \cite{kim2017deep}. Two SOTA deep BIQA models, KonCept512 \cite{hosu2020koniq} and PaQ-2-PiQ \cite{ying2019patches}, were also included in our evaluations. We implemented the feature extraction process for each evaluated BVQA model using its initial released implementation in MATLAB R2018b, except that VGG-19 and ResNet-50 were implemented in TensorFlow, while KonCept512\footnote{\url{https://github.com/ZhengyuZhao/koniq-PyTorch}} and PaQ-2-PiQ\footnote{\url{https://github.com/baidut/paq2piq}} were implemented in PyTorch. All the feature-based BIQA models extract features at a uniform sampling rate of one frame per second, then temporally average-pooled to obtain the overall video-level feature. \textbf{Regression Models.} We used a support vector regressor (SVR) as the back-end regression model to learn the feature-to-score mappings, since it achieves excellent performance in most cases \cite{korhonen2019two, saad2014blind, kim2017deep, ghadiyaram2017perceptual, mittal2012no, xu2014no}. The effectiveness of SVR, however, largely depends on the selection of its hyperparameters. As recommended in \cite{chang2011libsvm}, we optimized the SVR parameter values $(C,\gamma)$ by a grid-search of $10\times 10$ exponentially growing sequences (in our experiments, we used a grid of $C=2^1,2^2,...,2^{10},\gamma=2^{-8},2^{-7},...,2^{1}$) using cross-validation on the training set. The pair $(C,\gamma)$ yielding the best cross-validation performance, as measured by the root mean squared error (RMSE) between the predicted scores and the MOS, is picked. Afterward, the selected model parameters are applied to re-train the model on the entire training set, and we report the evaluation results on the test set. This kind of cross-validation procedure can prevent over-fitting, thus providing fair evaluation of the compared BVQA models. We chose the linear kernel for CORNIA, HOSA, VGG-19, and ResNet-50, considering their large feature dimension, and the radial basis function (RBF) kernel for all the other algorithms. We used Python 3.6.7 with the scikit-learn toolbox to train and test all the evaluated learning-based BVQA models. \textbf{Performance Metrics.} Following convention, we randomly split the dataset into non-overlapping training and test sets ($80\%/20\%$), where the regression model was trained on the training set, and the performance was reported on the test set. This process of random split was iterated 100 times and the overall median performance was recorded. For each iteration, we adopted four commonly used performance criteria to evaluate the models: The Spearman Rank-Order Correlation Coefficient (SRCC) and the Kendall Rank-Order Correlation Coefficient (KRCC) are non-parametric measures of prediction monotonicity, while the Pearson Linear Correlation Coefficient (PLCC) with corresponding Root Mean Square Error (RMSE) are computed to assess prediction accuracy. Note that PLCC and RMSE are computed after performing a nonlinear four-parametric logistic regression to linearize the objective predictions to be on the same scale of MOS \cite{seshadrinathan2010study}. \subsection{Performance on Individual and Combined Datasets} \label{ssec:performance_diff_datasets} Table \ref{table:compete-blind} shows the performance evaluation of the three ``completely blind'' BVQA models, NIQE, ILNIQE, and VIIDEO on the four UGC-VQA benchmarks. None of these methods performed very well, meaning that we still have much room for developing OU ``completely blind'' UGC video quality models. Table \ref{table:eval_svr} shows the performance evaluation of all the learning-based BVQA models trained with SVR on the four datasets in our evaluation framework. For better visualization, we also show box plots of performances as well as scatter plots of predictions versus MOS on the All-Combined\textsubscript{c} set, in Figures \ref{fig:all_boxplot} and \ref{fig:kvcv_draw}, respectively. Overall, VIDEVAL achieves SOTA or near-SOTA performance on all the test sets. On LIVE-VQC, however, TLVQM outperformed other BVQA models by a notable margin, while it significantly underperformed on the more recent YouTube-UGC database. We observed in Section \ref{ssec:observation} that LIVE-VQC videos generally contain more (camera) motions than KoNViD-1k and YouTube-UGC, and TLVQM computes multiple motion relevant features. Moreover, the only three BVQA models containing temporal features (V-BLIINDS, TLVQM, and VIDEVAL) excelled on LIVE-VQC, which suggests that it is potentially valuable to integrate at least a few, if not many, motion-related features into quality prediction models, when assessing on videos with large (camera) motions. \begin{table}[!t] \setlength{\tabcolsep}{4pt} \renewcommand{\arraystretch}{1.1} \centering \caption{Performances on different resolution subsets: 1080p (427), 720p (566), and $\le$480p (448).} \label{table:resolution_breakdown} \begin{tabular}{lccccccccccccccccccccccccc} \toprule \textsc{Subset} & \multicolumn{2}{c}{1080p} & & \multicolumn{2}{c}{720p} & & \multicolumn{2}{c}{$\le$480p} \\ \cline{2-3}\cline{5-6}\cline{8-9}\\[-1.em] \textsc{Model} & SRCC & PLCC & & SRCC & PLCC & & SRCC & PLCC \\ \hline\\[-1.em] BRISQUE & 0.4597 & 0.4637 & & 0.5407 & 0.5585 & & 0.3812 & 0.4065 \\ GM-LOG & 0.4796 & 0.4970 & & 0.5098 & 0.5172 & & 0.3685 & 0.4200 \\ HIGRADE & 0.5142 & 0.5543 & & 0.5095 & 0.5324 & & 0.4650 & 0.4642 \\ FRIQUEE & 0.5787 & 0.5797 & & 0.5369 & 0.5652 & & 0.5042 & 0.5363 \\ CORNIA & 0.5951 & \textbf{0.6358} & & 0.6212 & 0.6551 & & 0.5631 & 0.6118 \\ HOSA & 0.5924 & 0.6093 & & \textbf{\underline{0.6651}} & \textbf{0.6739} & & \textbf{0.6514} & \textbf{0.6652} \\ VGG-19 & \textbf{0.6440} & 0.6090 & & 0.6158 & \textbf{0.6568} & & \textbf{0.5845} & \textbf{0.6267} \\ ResNet-50 & \textbf{\underline{0.6615}} & \textbf{\underline{0.6644}} & & \textbf{0.6645} & \textbf{\underline{0.7076}} & & \textbf{\underline{0.6570}} & \textbf{\underline{0.6997}} \\ {KonCept512} & \textbf{0.6332} & \textbf{0.6336} & & 0.6055 & 0.6514 & & 0.4271 & 0.4612 \\ {PaQ-2-PiQ} & 0.5304 & 0.5176 & & 0.5768 & 0.5802 & & 0.3646 & 0.4748 \\ V-BLIINDS & 0.4449 & 0.4491 & & 0.5546 & 0.5719 & & 0.4484 & 0.4752 \\ TLVQM & 0.5638 & 0.6031 & & \textbf{0.6300} & 0.6526 & & 0.4318 & 0.4784 \\ VIDEVAL & 0.5805 & 0.6111 & & {0.6296} & {0.6393} & & 0.5014 & 0.5508 \\ \bottomrule \end{tabular} \end{table} \begin{table}[!t] \setlength{\tabcolsep}{4pt} \renewcommand{\arraystretch}{1.1} \centering \caption{Performances on different content subsets: screen content (163), animation (81), and gaming (209).} \label{table:content_breakdown} \begin{tabular}{lccccccccccccccccccccccccc} \toprule \textsc{Subset} & \multicolumn{2}{c}{Screen Content} & & \multicolumn{2}{c}{Animation} & & \multicolumn{2}{c}{Gaming} \\ \cline{2-3}\cline{5-6}\cline{8-9}\\[-1.em] \textsc{Model} & SRCC & PLCC & & SRCC & PLCC & & SRCC & PLCC \\ \hline\\[-1.em] BRISQUE & 0.2573 & 0.3954 & & 0.0747 & 0.3857 & & 0.2717 & 0.3307 \\ GM-LOG & 0.3004 & 0.4244 & & 0.2009 & 0.4129 & & 0.3371 & 0.4185 \\ HIGRADE & 0.4971 & 0.5652 & & 0.1985 & 0.4140 & & 0.6228 & 0.6832 \\ FRIQUEE & \textbf{0.5522} & \textbf{0.6160} & & 0.2377 & 0.4574 & & \textbf{0.6919} & \textbf{0.7193} \\ CORNIA & 0.5105 & 0.5667 & & 0.1936 & 0.4627 & & 0.5741 & 0.6502 \\ HOSA & 0.4667 & 0.5255 & & 0.1048 & 0.4489 & & 0.6019 & \textbf{0.6998} \\ VGG-19 & 0.5472 & 0.6229 & & 0.1973 & 0.4700 & & 0.5765 & 0.6370 \\ ResNet-50 & \textbf{\underline{0.6199}} & \textbf{\underline{0.6676}} & & \textbf{0.2781} & \textbf{0.4871} & & \textbf{0.6378} & 0.6779 \\ {KonCept512} & 0.4714 & 0.5119 & & \textbf{0.2757} & \textbf{0.5229} & & 0.4780 & 0.6240 \\ {PaQ-2-PiQ} & 0.3231 & 0.4312 & & 0.0208 & 0.4630 & & 0.2169 & 0.3874 \\ V-BLIINDS & 0.3064 & 0.4155 & & 0.0379 & 0.3917 & & 0.5473 & 0.6101 \\ TLVQM & 0.3843 & 0.4524 & & 0.2708 & 0.4598 & & 0.5749 & 0.6195 \\ VIDEVAL & \textbf{{0.6033}} & \textbf{{0.6610}} & & \textbf{\underline{0.3492}} & \textbf{\underline{0.5274}} & & \textbf{\underline{0.6954}} & \textbf{\underline{0.7323}} \\ \bottomrule \end{tabular} \end{table} It is also worth mentioning that the deep CNN baseline methods (VGG-19 and ResNet-50), despite being trained as picture-only models, performed quite well on KoNViD-1k and All-Combined\textsubscript{c}. This suggests that transfer learning is a promising technique for the blind UGC-VQA problem, consistent with conclusions drawn for picture-quality prediction \cite{kim2017deep}. Deep models will perform even better, no doubt, if trained on temporal content and distortions. {The two most recent deep learning picture quality models, PaQ-2-PiQ, and KonCept512, however, did not perform very well on the three evaluated video datasets. The most probable reason would be that these models were trained on picture quality datasets \cite{ying2019patches, hosu2020koniq}, which contain different types of (strictly spatial) distortions than UGC-VQA databases. Models trained on picture quality sets do not necessarily transfer very well to UGC video quality problems. In other words, whatever model should be either trained or fine-tuned on UGC-VQA datasets in order to obtain reasonable performance. Indeed, if temporal distortions (like judder) are present, they may severely underperform if the frame quality is high \cite{madhusudana2020subjective}.} \begin{table}[!t] \setlength{\tabcolsep}{4pt} \renewcommand{\arraystretch}{1.1} \centering \caption{Performances on different quality subsets: low quality (1558) and high quality (1550).} \label{table:quality_breakdown} \begin{tabular}{lccccccccccccccccccccccccc} \toprule \textsc{Subset} & \multicolumn{2}{c}{Low Quality} & & \multicolumn{2}{c}{High Quality} \\ \cline{2-3}\cline{5-6}\\[-1.em] \textsc{Model} & SRCC & PLCC & & SRCC & PLCC \\ \hline\\[-1.em] BRISQUE & 0.4312 & 0.4593 & & 0.2813 & 0.2979 \\ GM-LOG & 0.4221 & 0.4715 & & 0.2367 & 0.2621 \\ HIGRADE & 0.5057 & 0.5466 & & 0.4714 & 0.4799 \\ FRIQUEE & \textbf{0.5460} & \textbf{0.5886} & & \textbf{0.5061} & \textbf{0.5152} \\ CORNIA & 0.4931 & 0.5435 & & 0.3610 & 0.3748 \\ HOSA & \textbf{0.5348} & \textbf{0.5789} & & 0.4208 & 0.4323 \\ VGG-19 & 0.3710 & 0.4181 & & 0.3522 & 0.3614 \\ ResNet-50 & 0.3881 & 0.4250 & & 0.2791 & 0.3030 \\ {KonCept512} & 0.3428 & 0.4497 & & 0.2245 & 0.2597 & \\ {PaQ-2-PiQ} & 0.2438 & 0.2713 & & 0.2013 & 0.2252 \\ V-BLIINDS & 0.4703 & 0.5060 & & 0.3207 & 0.3444 \\ TLVQM & 0.4845 & 0.5386 & & \textbf{0.4783} & \textbf{0.4860} \\ VIDEVAL & \textbf{\underline{0.5680}} & \textbf{\underline{0.6056}} & & \textbf{\underline{0.5546}} & \textbf{\underline{0.5657}} \\ \bottomrule \end{tabular} \end{table} \begin{table}[!t] \setlength{\tabcolsep}{3.5pt} \renewcommand{\arraystretch}{1.1} \centering \caption{Best model in terms of SRCC for cross dataset generalization evaluation.} \label{table:cross_dataset_srcc} \begin{tabular}{lcccccccc} \toprule \textsc{Train}\textbackslash\textsc{Test} & LIVE-VQC & KoNViD-1k & YouTube-UGC\textsubscript{c} \\ \hline\\[-1.em] LIVE-VQC & - & ResNet-50 (0.69) & ResNet-50 (0.33) \\ KoNViD-1k & ResNet-50 (0.70) & - & VIDEVAL (0.37) \\ YouTube-UGC\textsubscript{c} & HOSA (0.49) & VIDEVAL (0.61) & - \\ \bottomrule \end{tabular} \end{table} \begin{table}[!t] \setlength{\tabcolsep}{3.5pt} \renewcommand{\arraystretch}{1.} \centering \caption{Best model in terms of PLCC for cross dataset generalization evaluation.} \label{table:cross_dataset_plcc} \begin{tabular}{lcccccccc} \toprule \textsc{Train}\textbackslash\textsc{Test} & LIVE-VQC & KoNViD-1k & YouTube-UGC\textsubscript{c} \\ \hline\\[-1.em] LIVE-VQC & - & ResNet-50 (0.70) & VIDEVAL (0.35) \\ KoNViD-1k & ResNet-50 (0.75) & - & VIDEVAL (0.39) \\ YouTube-UGC\textsubscript{c} & HOSA (0.50) & VIDEVAL (0.62) & - \\ \bottomrule \end{tabular} \end{table} \subsection{Performance Evaluation on Categorical Subsets} We propose three new categorical evaluation methodologies - resolution, quality, and content-based category breakdown. These will allow us to study the compared BVQA models from additional and practical aspects in the context of real-world UGC scenarios, which have not been, nor can it be accounted in previous legacy VQA databases or studies. \begin{table*}[!t] \setlength{\tabcolsep}{4pt} \renewcommand{\arraystretch}{1.1} \centering \caption{{Performance comparison of a total of eleven temporal pooling methods using TLVQM and VIDEVAL as testbeds on KoNViD-1k, LIVE-VQC, and YouTube-UGC. The three best results along each column are \textbf{boldfaced}.}} \label{table:pooling} \begin{tabular}{lccccccccccccccccccccccc} \toprule \textsc{Database} & \multicolumn{5}{c}{KoNViD-1k} & & \multicolumn{5}{c}{LIVE-VQC} & & \multicolumn{5}{c}{YouTube-UGC} \\ \cline{2-6}\cline{8-12}\cline{14-18}\\[-1.em] \textsc{Model} & \multicolumn{2}{c}{TLVQM} & & \multicolumn{2}{c}{VIDEVAL} & & \multicolumn{2}{c}{TLVQM} & & \multicolumn{2}{c}{VIDEVAL} & & \multicolumn{2}{c}{TLVQM} & & \multicolumn{2}{c}{VIDEVAL} \\ \cline{2-3}\cline{5-6}\cline{8-9}\cline{11-12}\cline{14-15}\cline{17-18}\\[-1.em] \textsc{Pooling} & SRCC & PLCC & & SRCC & PLCC & & SRCC & PLCC & & SRCC & PLCC & & SRCC & PLCC & & SRCC & PLCC \\ \hline\\[-1.em] Mean & \textbf{0.7511} & \textbf{0.7475} & & 0.7749 & \textbf{0.7727} & & \textbf{0.7917} & \textbf{0.7984} & & \textbf{0.7396} & 0.7432 & & \textbf{0.6369} & \textbf{0.6310} & & 0.7447 & 0.7332\\ Median & 0.7483 & 0.7437 & & 0.7650 & 0.7698 & & 0.7708 & 0.7887 & & 0.7236 & 0.7308 & & 0.6127 & 0.6090 & & 0.7452 & \textbf{0.7448} \\ Harmonic & 0.7458 & 0.7392 & & \textbf{0.7772} & 0.7681 & & 0.7845 & 0.7890 & & 0.7312 & 0.7250 & & 0.6119 & 0.6038 & & 0.7449 & 0.7318 \\ Geometric & 0.7449 & 0.7461 & & 0.7566 & 0.7592 & & \textbf{0.7878} & \textbf{0.7964} & & \textbf{0.7412} & 0.7487 & & 0.6347 & 0.6236 & & \textbf{0.7508} & \textbf{0.7437} \\ Minkowski & 0.7498 & \textbf{0.7481} & & \textbf{0.7775} & \textbf{0.7727} & & 0.7863 & 0.7908 & & 0.7371 & \textbf{0.7558} & & \textbf{0.6368} & \textbf{0.6311} & & \textbf{0.7542} & \textbf{0.7508} \\ Percentile & 0.7078 & 0.7000 & & 0.7161 & 0.7049 & & 0.7378 & 0.7313 & & 0.6596 & 0.6576 & & 0.4871 & 0.4996 & & 0.6443 & 0.6465 \\ VQPooling & 0.7240 & 0.7196 & & 0.7366 & 0.7296 & & 0.7696 & 0.7895 & & 0.7240 & 0.7311 & & 0.5654 & 0.5618 & & 0.6942 & 0.6862 \\ Primacy & 0.7456 & 0.7451 & & 0.7711 & 0.7700 & & 0.7751 & 0.7851 & & 0.7349 & \textbf{0.7523} & & 0.5734 & 0.5692 & & 0.7221 & 0.7156 \\ Recency & \textbf{0.7528} & 0.7470 & & 0.7683 & 0.7677 & & 0.7715 & 0.7857 & & \textbf{0.7405} & \textbf{0.7584} & & 0.5821 & 0.5695 & & 0.7176 & 0.7116 \\ Hysteresis & 0.7434 & 0.7430 & & 0.7612 & 0.7554 & & 0.7856 & 0.7901 & & 0.7226 & 0.7433 & & 0.6092 & 0.6109 & & 0.7370 & 0.7306 \\ EPooling & \textbf{0.7641} & \textbf{0.7573} & & \textbf{0.7831} & \textbf{0.7867} & & \textbf{0.7925} & \textbf{0.7917} & & 0.7371 & 0.7372 & & \textbf{0.6452} & \textbf{0.6592} & & \textbf{0.7517} & 0.7379 \\ \toprule \end{tabular} \end{table*} For resolution-dependent evaluation, we divided the All-Combined\textsubscript{c} set into three subsets, based on video resolution: (1) 427 1080p-videos (110 from LIVE-VQC, 317 from YouTube-UGC), (2) 566 720p-videos (316 from LIVE-VQC, 250 from YouTube-UGC), and (3) 448 videos with resolution $\le$480p (29 from LIVE-VQC, 419 from YouTube-UGC), since we are also interested in performance on videos of different resolutions. We did not include 540p-videos, since those videos are almost exclusively from KoNViD-1k. Table \ref{table:resolution_breakdown} shows the resolution-breakdown evaluation results. Generally speaking, learned features (CORNIA, HOSA, VGG-19, KonCept512, and ResNet-50) outperformed hand-designed features, among which ResNet-50 ranked first. \begin{figure}[!t] \centering \footnotesize \def0.32{0.32} \def0ex{0ex} \def0.3264\linewidth{0.3264\linewidth} \begin{tabular}{cc} \multirow{1}{*}[0.3264\linewidth]{\includegraphics[height=0.32\linewidth]{figs/Vlog_2160P-408f_plot.jpg}} & {\includegraphics[height=0.3668\linewidth]{figs/resolution_nss.pdf}} \\ (a) Vlog\_2160P-408f.mkv & (b) MSCN distributions \\ \end{tabular} \caption{{(a) An examplary 2160p video from YouTube-UGC and (b) the mean-subtracted contrast-normalized (MSCN) distributions of its downscaled versions: 2160p, 1440p, 1080p, 720p, 480p, and 360p.}} \label{fig:nss} \end{figure} {Here we make two arguments to try to explain the observations above: (1) video quality is intrinsically correlated with resolution; (2) NSS features are implicitly \textit{resolution-aware}, while CNN features are not. The first point is almost self-explanatory, no matter to what degree one agrees. To further justify this, we trained an SVR only using resolution (height, width) as features to predict MOS on YouTube-UGC, which contains balanced samples across five different resolutions. This yielded surprisingly high values $0.576 / 0.571$ for SRCC$/$PLCC, indicating the inherent correlation between video quality and resolution. Secondly, we selected one 2160p video from YouTube-UGC, namely `Vlog2160P-408f.mkv,' and plotted, in Figure \ref{fig:nss}, the mean-subtracted contrast-normalized (MSCN) distributions of its downscaled versions: 2160p, 1440p, 1080p, 720p, 480p, and 360p. It may be observed that resolution can be well separated by MSCN statistics, based on which most feature-based methods are built. We may infer, from these two standpoints, that including various resolutions of videos is favorable to the training of NSS-based models, since NSS features are resolution-aware, and resolution is further well correlated with quality. In other words, the resolution-breakdown evaluation shown in Table \ref{table:resolution_breakdown}, which removes this important implicit feature (resolution), would possibly reduce the performance of NSS-based models, such as FRIQUEE and VIDEVAL.} \begin{table*}[!t] \setlength{\tabcolsep}{4pt} \renewcommand{\arraystretch}{1.1} \centering \begin{threeparttable} \caption{Feature description, dimensionality, computational complexity, and average runtime comparison (in seconds evaluated on twenty $1080p$ videos from LIVE-VQC) among MATLAB-implemented BVQA models.} \label{table:complexity} \begin{tabular}{llp{5.5cm}cp{5.5cm}c} \toprule \textsc{Class} & \textsc{Model} & \textsc{Feature Description} & \textsc{Dim} & \textsc{Computational Complexity} & \textsc{Time (sec)} \\ \hline\\[-1.em] \multirow{15}{*}{\shortstack{IQA}} & NIQE (1 fr/sec) & Spatial NSS & 1 & $\mathcal{O}(d^2 NT)$ $d$: window size & 6.3 \\ & ILNIQE (1 fr/sec) & {Spatial NSS, gradient, log-Gabor, and color statistics} & 1 & {$\mathcal{O}((d^2+h+gh)NT)$ $d$: window size; $h$: filter size; $g$: log-Gabor filter size} & 23.3 \\ & BRISQUE (1 fr/sec) & Spatial NSS & 36 & $\mathcal{O}(d^2 NT)$ $d$: window size & 1.7 \\ & GM-LOG (1 fr/sec) & Joint statistics of gradient magnitude and laplacian of gaussian coefficients & 40 & {$\mathcal{O}(((h+k)NT)$ $d$: window size; $k$: probability matrix size} & 2.1 \\ & HIGRADE (1 fr/sec) & Spatial NSS, and gradient magnitude statistics in LAB color space & 216 & {$\mathcal{O}(3(2d^2+k)NT)$ $d$: window size; $k$: gradient kernel size} & 11.6 \\ & FRIQUEE (1 fr/sec) & Complex streerable pyramid wavelet, luminance, chroma, LMS, HSI, yellow channel, and their transformed domain statistics & 560 & $\mathcal{O}((fd^2 N+4N(\log(N)+m^2))T)$ $d$: window size; $f$: number of color spaces; $m$: neighborhood size in DNT & 701.2 \\ & CORNIA (1 fr/sec) & Spatially normalized image patches and max min pooling & 10k & $\mathcal{O}(d^2 KNT)$ $d$: window size $K$: codebook size & 14.3 \\ & HOSA (1 fr/sec) & Local normalized image patches based on high order statistics aggregation & 14.7k & $\mathcal{O}(d^2 KNT)$ $d$: window size $K$: codebook size & 1.2 \\ \\[-1.1em] \hline\\[-1.em] \multirow{10}{*}{\shortstack{VQA}} & VIIDEO & Frame difference spatial statistics, inter sub-band statistics & 1 & $\mathcal{O}(N\log(N)T)$ & 674.8 \\ & V-BLIINDS & Spatial NSS, frame difference DCT coefficient statistics, motion coherency, and egomotion & 47 & $\mathcal{O}((d^2 N+\log(k)N+k^2 w^3)T)$ $d$: window size; $k$: block size; $w$: motion vector tensor size & 1989.9 \\ & TLVQM & Captures impairments computed at two computation levels: low complexity and high complexity features & 75 & $\mathcal{O}((h_1^2 N+k^2 K)T_1+(\log(N)+h_2^2) NT_2))$ $h_1,h_2$: filter size; $k$: motion estimation block size; $K$: number of key points & 183.8 \\ & VIDEVAL & Selected combination of NSS features in multiple perceptual spaces and using visual impairment features from TLVQM & 60 & $\mathcal{O}((fh_1^2N+k^2K)T_1+h_2^2NT_2)$ $h_1,h_2$: filter size; $f$: number of color spaces; $k$: motion estimation block size; $K$: number of key points & 305.8 \\ \bottomrule \end{tabular} \begin{tablenotes}[para,flushleft] \item $N$: number of pixels per frame; $T$: number of frames computed for feature extraction. Note that for VIIDEO and V-BLIINDS, $T$ is the total number of frames, whereas for IQA models, $T$ equals the total number of frames sampled at 1 fr/sec. For TLVQM and VIDEVAL, $T_1$ is total number of frames divided by 2, while $T_2$ is the number of frames sampled at 1 fr/sec. \end{tablenotes} \end{threeparttable} \end{table*} We also divided the All-Combined\textsubscript{c} into subsets based on content category: Screen Content (163), Animation (81), Gaming (209), and Natural (2,667) videos. We only reported the evaluation results on the first three subsets in Table \ref{table:content_breakdown}, since we observed similar results on the Natural subset with the entire combined set. The proposed VIDEVAL model outperformed over all categories, followed by ResNet-50 and FRIQUEE, suggesting that VIDEVAL features are robust quality indicatives across different content categories. The third categorical division is based on quality scores: we partitioned the combined set into Low Quality (1,558) and High Quality (1,550) halves, using the median quality value 3.5536 as the threshold, to see the model performance only on high/low quality videos. Performance results are shown in Table \ref{table:quality_breakdown}, wherein VIDEVAL still outperformed the other BVQA models on both low and high quality partitions. \subsection{Cross Dataset Generalizability} We also performed a cross dataset evaluation to verify the generalizability of BVQA models, wherein LIVE-VQC, KoNViD-1k, and YouTube-UGC\textsubscript{c} were included. That is, we trained the regression model on one full database and report the performance on another. To retain label consistency, we linearly scaled the MOS values in LIVE-VQC from raw $[0,100]$ to $[1,5]$, which is the scale for the other two datasets. We used SVR for regression and adopted $k$-fold cross validation using the same grid-search as in Section \ref{ssec:eval_proto} for hyperparameter selection. The selected parameter pair were then applied to re-train the SVR model on the full training set, and the performance results on the test set were recorded. Table \ref{table:cross_dataset_srcc} and \ref{table:cross_dataset_plcc} show the best performing methods with cross domain performances in terms of SRCC and PLCC, respectively. We may see that the cross domain BVQA algorithm generalization between LIVE-VQC and KoNViD-1k was surprisingly good, and was well characterized by pre-trained ResNet-50 features. We also observed better algorithm generalization between KoNViD-1k and YouTube-UGC than LIVE-VQC, as indicated by the performances of the best model, VIDEVAL. This might be expected, since as Figure \ref{fig:tsne} shows, YouTube-UGC and KoNViD-1k share overlapped coverage of content space, much larger than that of LIVE-VQC. Therefore, we may conclude that VIDEVAL and ResNet-50 were the most robust BVQA models among those compared in terms of cross domain generalization capacities. \subsection{Effects of Temporal Pooling} Temporal pooling is one of the most important, unresolved problems for video quality prediction \cite{park2012video, tu2020comparative,seshadrinathan2011temporal, korhonen2019two, bampis2018recurrent}. In our previous work \cite{tu2020comparative}, we have studied the efficacy of various pooling methods using scores predicted by BIQA models. Here we extend this to evaluate on SOTA BVQA models. For practical considerations, the high-performing TLVQM and VIDEVAL were selected as exemplar models. Since these two models independently extract features on each one-second block, we applied temporal pooling of chunk-wise quality predictions. A total of eleven pooling methods were tested: three Pythagorean means (arithmetic, geometric, and harmonic mean), median, Minkowski ($p=2$) mean, percentile pooling ($20\%$) \cite{moorthy2009visual}, VQPooling \cite{park2012video}, primacy and recency pooling \cite{murdock1962serial}, hysteresis pooling \cite{seshadrinathan2011temporal}, and our previously proposed ensemble method, EPooling \cite{tu2020comparative}, which aggregates multiply pooled scores by training a second regressor on top of mean, Minkowski, percentile, VQPooling, variation, and hysteresis pooling. We refer the reader to \cite{tu2020comparative} for detailed algorithmic formulations and parameter settings thereof. It is worth noting that the results in Table \ref{table:pooling} are only \textit{self-consistent}, meaning that they are not comparable to any prior experiments - since we employed chunk-wise instead of previously adopted video-wise quality prediction to be able to apply temporal quality pooling, which may affect the base performance. Here we observed yet slightly different results using BVQA testbeds as compared to what we observed on BIQA \cite{tu2020comparative}. Generally, we found the mean families and ensemble pooling to be the most reliable pooling methods. Traditional sample mean prediction may be adequate in many cases, due to its simplicity. Pooling strategies that more heavily weight low-quality parts, however, were not observed to perform very well on the tested BVQA, which might be attributed to the fact that not enough samples ($8\sim 20$) can be extracted from each video to attain statistically meaningful results. \subsection{Complexity Analysis and Runtime Comparison} The efficiency of a video quality model is of vital importance in practical commercial deployments. Therefore, we also tabulated the computational complexity and runtime cost of the compared BVQA models, as shown in Tables \ref{table:complexity}, \ref{table:time_dl}. The experiments were performed in MATLAB R2018b and Python 3.6.7 under Ubuntu 18.04.3 LTS system on a Dell OptiPlex 7080 Desktop with Intel Core i7-8700 CPU@3.2GHz, 32G RAM, and GeForce GTX 1050 Graphics Cards. The average feature computation time of MATLAB-implemented BVQA models on 1080p videos are reported in Table \ref{table:complexity}. The proposed VIDEVAL method achieves a reasonable complexity among the top-performing algorithms, TLVQM, and FRIQUEE. We also present theoretical time complexity in Table \ref{table:complexity} for potential analytical purposes. {We also provide in Table \ref{table:time_dl} an additional runtime comparison between MATLAB models on CPU and deep learning models on CPU and GPU, respectively. It may be observed that top-performing BVQA models such as TLVQM and VIDEVAL are essentially slower than deep CNN models, but we expect orders-of-magnitude speedup if re-implemented in pure $\text{C}/\text{C}\texttt{++}$. Simpler NSS-based models such as BRISQUE and HIGRADE (which only involve several convolution operations) still show competitive efficiency relative to CNN models even when implemented in MATLAB. We have also seen a $5\sim 10$ times speedup switching from CPU to GPU for the CNN models, among which KonCept512 with PyTorch-GPU was the fastest since it requires just a single pass to the CNN backbone, while the other three entail multiple passes for each input frame.} Note that the training/test time of the machine learning regressor is approximately proportional to the number of features. Thus, it is not negligible compared to feature computation given a large number of features, regardless of the regression model employed. The feature dimension of each model is listed in Table \ref{table:complexity}. As may be seen, codebook-based algorithms (CORNIA (10$k$) and HOSA (14.7$k$)) require significantly larger numbers of features than other hand-crafted feature based models. Deep ConvNet features ranked second in dimension (VGG-19 (4,080) and ResNet-50 (2,048)). Our proposed VIDEVAL only uses 60 features, which is fairly compact, as compared to other top-performing BVQA models like FRIQUEE (560) and TLVQM (75). \begin{table}[!t] \setlength{\tabcolsep}{4pt} \renewcommand{\arraystretch}{1.1} \centering \caption{{Run time comparison of feature-based and deep learning BVQA models (in seconds evaluated on twenty $1080p$ videos from LIVE-VQC). Model loading time for deep models are excluded}.} \label{table:time_dl} \begin{tabular}{lrrccccccccccccccccccccccc} \toprule \textsc{Model} & & \textsc{Time (Sec)} \\ \hline\\[-1.em] BRISQUE (1 fr/sec) & MATLAB-CPU & 1.7 \\ HOSA (1 fr/sec) & MATLAB-CPU & 1.2 \\ TLVQM & MATLAB-CPU & 183.8 \\ VIDEVAL & MATLAB-CPU & 305.8 \\ \hline\\[-1.em] VGG-19 (1 fr/sec) & TensorFlow-CPU & 27.8 \\ & TensorFlow-\textit{GPU} & 5.7 \\ ResNet-50 (1 fr/sec) & TensorFlow-CPU & 9.6 \\ & TensorFlow-\textit{GPU} & 1.9 \\ \hline\\[-1.em] KonCept512 (1 fr/sec) & PyTorch-CPU & 2.8 \\ & PyTorch-\textit{GPU} & 0.3 \\ PaQ-2-PiQ (1 fr/sec) & PyTorch-CPU & 6.9 \\ & PyTorch-\textit{GPU} & 0.8 \\ \bottomrule \end{tabular} \end{table} \subsection{{Ensembling VIDEVAL with Deep Features}} \label{ssec:ensemble} We also attempted a more sophisticated ensemble fusion of VIDEVAL and deep learning features to determine whether this could further boost its performance, which could give insights on the future direction of this field. Since PaQ-2-PiQ aimed for local quality prediction, we included the predicted $3\times 5$ local quality scores as well as a single global score, as additional features. For KonCept512, the feature vector (256-dim) immediately before the last linear layer in the fully-connected head was appended. Our own baseline CNN models, VGG-19 and ResNet-50, were also considered, because these are commonly used standards for downstream vision tasks. The overall results are summarized in Table \ref{table:fusion}. We may observe that ensembling VIDEVAL with certain deep learning models improved the performance by up to $\sim 4\%$ compared to the vanilla VIDEVAL, which is very promising. Fusion with either ResNet-50 or KonCept512 yielded top performance. It should be noted that the number of fused features is also an essential aspect. For example, blending VIDEVAL (60-dim) with VGG-19 (4,096-dim) may not be recommended, since the enormous number of VGG-19 features could possibly dominate the VIDEVAL features, as suggested by some performance drops in Table \ref{table:fusion}. \begin{table}[!t] \setlength{\tabcolsep}{3.5pt} \renewcommand{\arraystretch}{1.1} \centering \caption{Performance of the ensemble VIDEVAL models fused with additional deep learning features.} \label{table:fusion} \begin{tabular}{llcccc} \toprule \textsc{Dataset} & \textsc{Model} \textbackslash\ \textsc{Metric} & SRCC & KRCC & PLCC & RMSE \\ \hline\\[-1.em] \multirow{5}{*}{KoNViD} & VIDEVAL & 0.7832 & 0.5845 & 0.7803 & 0.4024 \\ & VIDEVAL$+$VGG-19 & 0.7827 & 0.5928 & 0.7913 & 0.3897 \\ & VIDEVAL$+$ResNet-50 & 0.8129 & 0.6212 & \textbf{0.8200} & \textbf{0.3659} \\ & VIDEVAL$+$KonCept512 & \textbf{0.8149} & \textbf{0.6251} & 0.8169 & 0.3670 \\ & VIDEVAL$+$PaQ-2-PiQ & 0.7844 & 0.5891 & 0.7793 & 0.4018 \\ \hline\\[-1.em] \multirow{5}{*}{LIVE-VQC} & VIDEVAL & 0.7522 & 0.5639 & 0.7514 & 11.100 \\ & VIDEVAL$+$VGG-19 & 0.7274 & 0.5375 & 0.7717 & 10.749 \\ & VIDEVAL$+$ResNet-50 & 0.7456 & 0.5555 & 0.7810 & 10.385 \\ & VIDEVAL$+$KonCept512 & \textbf{0.7849} & \textbf{0.5953} & \textbf{0.8010} & \textbf{10.145} \\ & VIDEVAL$+$PaQ-2-PiQ & 0.7677 & 0.5736 & 0.7686 & 10.787 \\ \hline\\[-1.em] \multirow{5}{*}{YT-UGC} & VIDEVAL & 0.7787 & 0.5830 & 0.7733 & 0.4049 \\ & VIDEVAL$+$VGG-19 & 0.7868 & 0.5930 & 0.7847 & 0.3993 \\ & VIDEVAL$+$ResNet-50 & \textbf{0.8085} & 0.6128 & \textbf{0.8033} & \textbf{0.3837} \\ & VIDEVAL$+$KonCept512 & 0.8083 & \textbf{0.6139} & 0.8028 & 0.3859 \\ & VIDEVAL$+$PaQ-2-PiQ & 0.7981 & 0.6015 & 0.7941 & 0.3959 \\ \hline\\[-1.em] \multirow{5}{*}{All-Comb} & VIDEVAL & 0.7960 & 0.6032 & 0.7939 & 0.4268 \\ & VIDEVAL$+$VGG-19 & 0.7859 & 0.5912 & 0.7962 & 0.4202 \\ & VIDEVAL$+$ResNet-50 & 0.8115 & \textbf{0.6207} & \textbf{0.8286} & \textbf{0.3871} \\ & VIDEVAL$+$KonCept512 & \textbf{0.8123} & 0.6193 & 0.8168 & 0.4017 \\ & VIDEVAL$+$PaQ-2-PiQ & 0.7962 & 0.5991 & 0.7934 & 0.4229 \\ \toprule \end{tabular} \end{table} \subsection{Summarization and Takeaways} Finally, we briefly summarize the experimental results and make additional observations: \begin{enumerate} \item Generally, spatial distortions dominated quality prediction on Internet UGC videos like those from YouTube and Flickr, as revealed by the remarkable performances of picture-only models (e.g., HIGRADE, FRIQUEE, HOSA, ResNet-50) on them. Some motion-related features (as in TLVQM) may not apply as well in this scenario. \item On videos captured with mobile devices (e.g., those in LIVE-VQC), which often present larger and more frequent camera motions, including temporal- or motion-related features can be advantageous (e.g., V-BLIINDS, TLVQM, VIDEVAL). \item Deep CNN feature descriptors (VGG-19, ResNet-50, etc.) pre-trained for other classical vision tasks (e.g. image classification) are transferable to UGC video quality predictions, achieving very good performance, suggesting that using transfer learning to address the general UGC-VQA problem is very promising. \item It is still a very hard problem to predict UGC video quality on non-natural or computer-generated video contents: screen contents, animations, gaming, etc. Moreover, there are no sufficiently large UGC-VQA datasets designed for those kinds of contents. \item A simple feature engineering and selection implementation built on top of current effective feature-based BVQA models is able to obtain excellent performance, as exemplified by the compact new model (VIDEVAL). \item Simple temporal mean pooling of chunk-wise quality predictions by BVQA models yields decent and robust results. Furthermore, an ensemble pooling approach can noticeably improve the quality prediction performance, albeit with higher complexity. \item Ensembling scene statistics-based BVQA models with additional deep learning features (e.g., VIDEVAL plus KonCept512) could further raise the performance upper bound, which may be a promising way of developing future BVQA models. \end{enumerate} \section{Conclusion} \label{sec:conclud} We have presented a comprehensive analysis and empirical study of blind video quality assessment for user-generated content (the \textbf{\textsf{UGC-VQA problem}}). We also proposed a new fusion-based BVQA model, called the VIDeo quality EVALuator (VIDEVAL), which uses a feature ensemble and selection procedure on top of existing efficient BVQA models. A systematic evaluation of prior leading video quality models was conducted within a unified and reproducible evaluation framework and accordingly, we concluded that a selected fusion of simple distortion-aware statistical video features, along with well-defined visual impairment features, is able to deliver state-of-the-art, robust performance at a very reasonable computational cost. The promising performances of baseline CNN models suggest the great potential of leveraging transfer learning techniques for the UGC-VQA problem. We believe that this benchmarking study will help facilitate UGC-VQA research by clarifying the current status of BVQA research and the relative efficacies of modern BVQA models. To promote reproducible research and public usage, an implementation of VIDEVAL has been made available online: \textbf{\url{https://github.com/vztu/VIDEVAL}}. In addition to the software, we are also maintaining an ongoing performance leaderboard on Github: \textbf{\url{https://github.com/vztu/BVQA_Benchmark}}. \ifCLASSOPTIONcaptionsoff \newpage \fi \bibliographystyle{IEEEtran}
{'timestamp': '2021-04-20T02:07:39', 'yymm': '2005', 'arxiv_id': '2005.14354', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14354'}
arxiv
\section{Introduction} The emergence of COVID-19 in early 2020 and its subsequent outbreak have affected and changed the world dramatically. According to the World Health Organization (WHO), by mid-May 2020, the number of confirmed COVID-19 cases has reached 5 millions with death toll over 300,000 world wid . Several mandatory rules have been introduced by the government to prevent the spread of the coronavirus, such as social distancing, bans on social gatherings, store closures and school closures. Despite their positive effects on slowing the spread of the pandemaic, they neverthless caused severe impacts on the society, the economy and people's everyday life. There have been anti-lockdown and anti-social-distancing protests in many places around the world. Given these difficult situations, it is crucial for policy-makers to understand people's opinions toward the pandemic so that they can (1) balance the concerns of stoping the pandemic on the one hand and keeping people in good spirits on the other hand and (2) anticipate people's reactions to certain events and policy so that the policy-makers can prepare in advance. More generally, a close look at the public affect during the time of COVID-19 could help us understand people's reaction and thoughts in the face of extreme crisis, which sheds light on humanity in moments of darkness. People constantly post about the pandemic on social media such as Twitter, Weibo and Facebook. They express their attitudes and feelings regarding various aspects of the pandemic, such as the medical treatments, public policy, their worry, etc. Therefore, user-generated content on social media provides an important source for understanding public emotions and concerns. In this paper, we provide a comprehensive analysis on the affective trajectories of American people and Chinese people based on Twitter and Weibo posts between January 20th, 2020 and May 11th 2020. We identify fine-grained emotions (including anger, disgust, fear, happiness, sadness, surprise) expressed on social media based on the user-generated content. Additionally, we build NLP taggers to extract the triggers of different emotions, e.g., why people are angry or surprised, what they are worried, etc. We also contrast public emotions between China and the Unites States, revealing sharp differences in public reactions towards COVID-19 related issues in different countries. By tracking the change of public sentiment and emotion over time, our work sheds light on the evolution of public attitude towards this global crisis. This work contributes to the growing body of research on social media content in the time of COVID-19. Our study provides a way to extracting public emotion towards the pandemic in real-time, and could potentially lead to better decision-making and the development of wiser interventions to fight this global crisis. The rest of this paper is organized as follows: we briefly go through some related work in Section 2. We then present the analyses on topic trends in Weibo and Twitter (section 3), the extracted emotion trajectories (section 4) and triggers of those emotions (section 5). We finally conclude this paper in Section 6. \section{Related Work} \subsection{Analyses on Social Media Content about COVID-19 } \begin{comment} There has been a decade history of using NLP tools to analyze user-generated content on social media regarding variety of aspects, such as epidemic detection \cite{achrekar2011predicting,paul2011you,ji2012epidemic,li2013early}, natural disaster detection \cite{sakaki2010earthquake,sakaki2012tweet}, topic trend detection \cite{hong2010empirical,o2010tweetmotif,zhao2011comparing}, sentiment and emotion analysis \cite{go2009twitter,o2010tweets,kouloumpis2011twitter,bollen2011modeling,balabantaray2012multi,severyn2015twitter,kumar2015emotion}, entity and event extraction \cite{ritter2011named,ritter2012open,li2014major,zhou2014simple,deng2015overview}. \end{comment} At the time of writing, analyses on people's discussions and behaviors on social media in the context of COVID-19 has attracted increasing attention. \cite{alshaabi2020world} analyzed tweets concerning COVID-19 on Twitter by selecting important 1-grams based on rank-turbulence divergence and compare languages used in early 2020 with the ones used a year ago. The authors observed the first peak of public attention to COVID-19 around January 2020 with the first wave of infections in China, and the second peak later when the outbreak hit many western countries. \cite{chen2020covid} released the first COVID-19 Twitter dataset. \cite{kleinberg2020measuring} provided a ground truth corpus by annotating 5,000 texts (2,500 short + 2,500 long texts) in UK and showed people's worries about their families and economic situations. \cite{gao2020mental} viewed emotions and sentiments on social media as indicators of mental health issues, which result from self-quarantining and social isolation. \cite{schild2020go} revealed increasing amount of hateful speech and conspiracy theories towards specific ethnic groups such as Chinese on Twitter and 4chan’s. Other researchers started looking at the spread of misinformation on social media \cite{gallotti2020assessing,ferrara2020covid}. \cite{cinelli2020covid} provide an in-depth analysis on the diffusion of misinformation concerning COVID-19 on five different social platforms. \subsection{Analyses of Emotions and Sentiments on Social Media} {\it Discrete Emotion Theory } \cite{plutchik1980general,frijda1988laws,parrott2001emotions} think that all humans have an innate set of distinct basic emotions. Paul Ekman and his colleagues \cite{ekman1992argument} proposed that the six basic emotions of humans are anger, disgust, fear, happiness, sadness, and surprise. Ekman explains that different emotions have particular characteristics expressed in varying degrees. Researchers have debated over the exact categories of discreate emotions. For instance, \cite{raghavan1975number} proposed eight classes for emotions including love, mirth, sorrow, anger, energy, terror, disgust and astonishment. Automatically detecting sentiments and emotions in text is a crucial problem in NLP and there has been a large body of work on annotating texts based on sentiments and building machine tools to automatically identify emotions and sentiments \cite{yang2007emotion,pang2008opinion,mohammad2016sentiment,tang2015document}. \cite{mohammad2017wassa} created the first annotated dataset for four classes of emotions, anger, fear, joy, and sadness, in which each text is annotated with not only a label of emotion category, but also the intensity of the emotion expressed based on the Best–Worst Scaling (BWS) technique \cite{louviere1991best}. A follow-up work by \cite{mohammad2018semeval} created a more comprehensively annotated dataset from tweets in English, Arabic, and Spanish. The dataset covers five different sub-tasks including emotion classification, emotion intensity regression, emotion intensity ordinal classification, valence regression and valence ordinal classification. There has been a number of studies on extracting aggregated public mood and emotions from social media \cite{mishne2006capturing,liu2007arsa,dodds2010measuring,gilbert2010widespread}. Facebook introduced Gross National Happiness (GNH) to estimate the aggregated mood of the public using the LIWC dictionary. Results show a clear weekly cycle of public mood. \cite{mitchell2013geography} and \cite{li2014nasty} specially investigate the influence of geographic places and weather on public mood from Twitter data. The mood indicators extracted from tweets are very predictive and robust \cite{dodds2010measuring,dodds2011temporal}. Therefore, they have been used to predict real-world outcomes such as economic trends \cite{gilbert2010widespread,rao2012tweetsmart,rao2012using,zhang2011predicting}, stock market \cite{bollen2011twitter,chung2011predicting}, influenza outbreak \cite{li2013early}, and political events \cite{hopkins2010method,o2010tweets,tumasjan2010predicting,larsson2012studying}. \section{General Trends for COVID-19 Related Posts} \input{figs/general.tex} In this section, we present the general trends for COVID19-related posts on Twitter and Weibo. We first present the semi-supervised models we used to detect COVID-19 related tweets. Next we present the analysis on the topic trends on the two social media platforms. \subsection{Retrieving COVID-19 Related Posts} For Twitter, we first obtained 1\% of all tweets that are written in English and published within the time period between January 20th, 2020 and May 11th 2020. The next step is to select tweets related to COVID-19. The simplest way, as in \cite{chen2020covid,ferrara2020covid}, is to use a handcrafted keyword list to obtain tweets containing words found in the list. However, this method leads to lower values in both precision and recall: for precision, user-generated content that contains the mention of a keyword is not necessarily related to COVID-19. For example, the keyword list used in \cite{chen2020covid} include the word {\it China}, and it is not suprising that a big proportion of the posts containing ``China" is not related to COVID-19; for recall, keywords for COVID-19 can change over time and might be missing in the keyword list. To tackle this issue, we adopt a bootstrapping approach. The bootstrapping approach is related to previous work on semi-supervised data harvesting methods \cite{li2014weakly,davidov2007fully,kozareva2010learning}, in which we build a model that recursively uses seed examples to extract patterns, which are then used to harvest new examples. Those new examples are further used as new seeds to get new patterns. To be specific, we first obtained a starting seed keyword list by (1) ranking words based on tf-idf scores from eight COVID-19 related wikipedia articles; (2) manually examining the ranked word list, removing those words that are apparently not COVID-19 related, and use the top 100 words in the remaining items. Then we retrieved tweets with the mention of those keywords. Next, we randomly sampled 1,000 tweets from the collection and manually labeled them as either COVID-19 related or not. The labeled dataset is split into the training, development and test sets with ratio 8:1:1. A binary classification model is trained on the labeled dataset to classify whether a post with the mention of COVID-related keywords is actually COVID-related. The model is trained using BERT \cite{devlin2018bert} and optimized using Adam \cite{kingma2014adam}. Hyperparameters such as the batch size, learning rate are tuned on the development set. Next, we obtain a new seed list by picking the most salient words that contribute to the positive category in the binary classification model based on the first-order derivative saliency scores \cite{erhan2009visualizing,simonyan2013deep,li2015visualizing}. This marks the end of the first round of the bootstrapping. Next we used the new keyword list to re-harvest a new dataset with the mention of the keyword, 1,000 of which is selected and labeled to retrain the binary classification model. We repeat this process for three times. F1 scores for the three rounds of binary classification are 0.74, 0.82, 0.86 respectively. After the final round of bootstrapping, we collected a total number of 78 million English tweets concerning the topic of COVID-19. We used this strategy to retrieve COVID-related posts on Weibo and collected a total number of 16 million posts. \subsection{Analyses} We report the intensity scores for Weibo and Twitter in Figure \ref{general}. We split all tweets by date, where $X_t$ denotes all tweets published on day $t$. The value of intensity is the number of posts classified as COVID-related divided by the total number of retrieved posts, i.e., $|X_t|$. On Weibo, we observe a peak in late January and February, then a drop, followed by another rise in March, and a gradual decline afterwards. The trend on Chinese social media largely reflects the progress of the pandemic in China: the outbreak of COVID-19 and the spread from Wuhan to the rest of the country corresponds to the first peak. The subsequent drop reflects the promise in containing the virus, followed by a minor relapse in March. For Twitter, we observe a small peak that is aligned with the news from China about the virus. The subsequent drop reflects the decline of the attention to the outbreak in China. The curve progressively went up since March, corresponding to the outbreak in the US. Upon the writing of this paper, we have not observed a sign of drop in the intensity score of COVID19-related posts. \section{The Evolution of Public Emotion} In this section, we present the analyses on the evolution of public emotion in the time of COVID-19. We first present the algorithms we used to identify the emotions expressed in a given post. Next we present the results of the analyses. \subsection{Emotion Classification} We adopted the well-established emotion theory by Paul Ekman \cite{ekman1992argument}, which groups human emotions into 6 major categories, i.e., anger, disgust, worry, happiness, sadness, and surprise. Given a post from a social network user, we assign one or multiple emotion labels to it \cite{buechel2016emotion,demszky2020goemotions}. This setup is quite common in text classification \cite{ikonomakis2005text,aggarwal2012survey,zhang2015character,zhou2015c,joulin2016bag}. For emotion classification of English tweets, we take the advantage of labeled datasets from the SemEval-2018 Task 1e \cite{mohammad2018semeval}, in which a tweet was associated with either the ``neutral'' label or with one or multiple emotion labels by human evaluators. The SemEval-2018 Task 1e contains eleven emotion categories in total, i.e., anger, anticipation, disgust, fear, joy, love, optimism, pessimism, sadness, surprise and trust, and we only use the datasets for a six-way classification, i.e., anger, disgust, fear, happiness, sadness, and surprise. Given that the domain of the dataset used in \cite{mohammad2018semeval} covers all kinds of tweets, and our domain of research covers only COVID-related tweets, there is a gap between the two domains. Therefore, we additionally labeled 15k COVID-related tweets following the guidelines in \cite{mohammad2018semeval}, where each tweet can take either the neural label or one/multiple emotion labels. Since one tweet can take on multiple emotion labels, the task is formalized as a a multi-label classification task, in which six binary (one vs. the rest) classifiers are trained. We used the description-based BERT model \cite{chai2020description} as the backbone, which achieves current SOTA performances on a wide variety of text classification tasks. More formally, let us consider a to-be-classified tweet $x=\{x_1,\cdots,x_L\}$, where $L$ denotes the length of the text $\bm{x}$. Each $x$ will be tagged with one or more class labels $y \in \mathcal{Y} = [1,N]$, where $N=6$ denotes the number of the predefined emotion classes (the six emotion categories). To compute the probability $p(y|\bm{x})$, each input text $\bm{x}$ is concatenated with the description $\bm{q}_y$ to generate $\{\text{[CLS]};\bm{q}_y;\text{[SEP]};\bm{x}\}$, where $\text{[CLS]}$ and $\text{[SEP]}$ are special tokens. The description $q_y$ is the Wikipedia description for each of the emotions. For example, $q_y$ for the category {\it anger} is {\it ``Anger, also known as wrath or rage, is an intense emotional state involving a strong uncomfortable and hostile response to a perceived provocation, hurt or threat."} Next, the concatenated sequence is fed to the BERT model, from which we obtain the contextual representations $h_\text{[CLS]}$. $h_\text{[CLS]}$ is then transformed to a real value between 0 and 1 using the sigmoid function, representing the probability of assigning the emotion label $y$ to the input tweet $\bm{x}$: \begin{equation} p(y|\bm{x})=\text{sigmoid}(W_2\text{ReLU}(W_1h_\text{[CLS]}+b_1)+b_2) \end{equation} where $W_1,W_2,b_1,b_2$ are some parameters to optimize. Classification performances for different models are presented in Table \ref{en-emotion}. \begin{table} \center \begin{tabular}{cccc}\hline Model & Acc & micro F1 & macro F1 \\\hline SVM biagram & 51.4 & 63.0 & 52.7 \\ BERT \cite{devlin2018bert} & 65.0 & 75.2 & 66.1 \\ BERT-description \cite{chai2020description} & 66.8 & 77.0 & 68.3 \\\hline \end{tabular} \caption{ Results for the multi-label emotion classification for English tweets. } \label{en-emotion} \end{table} \subsection{Analyses} For emotion $y$, its intensity score $S(t,y)$ for day $t$ is the average probability (denoted by $P(y|x)$) of assigning label $y$ to all the texts in that day $X_t$. For non COVID-related texts, $P(y|x)$ is automatically set to 0. We thus have: \begin{equation} S(t,y) = \frac{1}{|X_t|} \sum_{x\in X_t} p (y|x) \end{equation} For Chinese emotion classification, we used the labeled dataset in \cite{lai2019fine}, which contains 15k labeled microblogs from weibo\footnote{The original dataset contains 7 categories of emotions, and we used only six of them.}. In addition to the dataset provided by \cite{lai2019fine}, we labeled COVID-related 20k microblogs. The combined dataset is then used to train a multi-label classification model based on the description-BERT model \cite{chai2020description}. Everyday emotion scores for Weibo are computed in the same way as for Twitter. The time series of intensity scores of six different emotions, i.e., sadness, anger, disgust, worry, happiness, surprise, for Weibo and Twitter are shown in Figures \ref{ch-emotion} and \ref{en-emotion}, respectively. For Weibo, as can be seen, the trend of {\it worry} is largely in line with the trend of the general intensity of the COVID-related posts. It reached a peak in late January, and then gradually went down, followed by a small relapse in mid-March. For {\it anger}, the intensity first went up steeply at the initial stage of the outbreak, staying high for two weeks, and then had another sharp increase around February 8th. The peak on February 8th was due to the death of Wenliang Li, a Chinese ophthalmologist who issued the warnings about the virus. The intensity for anger then gradually decreased, with no relapse afterwards. The intensity for {\it disgust} remained relatively low across time. For {\it sadness}, the intensity reached the peak at the early stage of the outbreak, then gradually died out with no relapse. For {\it surprise}, it went up first, mostly because of the fact that the public was surprised by the new virus and the unexpected outbreak, but then gradually went down. The intensity for {\it happiness} remained relatively low across time, with a small peak in late April, mostly because the countrywide lockdown was over. For Twitter, the intensity for {\it worry} went up shortly in late January, followed by a drop. The intensity then went up steeply in mid-March in response to the pandemic breakout in the States, reaching a peak around March 20th, then decreased a little bit and remained steady afterwards. The intensity for {\it anger} kept going up after the outbreak in mid-March, with no drop observed. The trend for {\it sadness} is mostly similar to that of the overall intensity. For {\it surprise}, the curve went up first after the breakout in early March, reaching a peak around Mar 20th, then dropped, and remained steady afterwards. For {\it happiness}, the intensity remained low over time. \begin{table*} \small \center \begin{tabular}{|c|c|c|c|c|c|}\hline sadness & anger & disgust &worry &happiness & surprise \\\hline passed away &realdonaldtrump & covid / covid-19 &covid / covid-19 & healthy &covid / covid-19 \\ \multirow{2}{*}{died} & \multirow{2}{*}{lockdown} & \multirow{2}{*}{realdonaldtrump}& \multirow{2}{*}{job} & \multirow{2}{*}{help} &human-to-human \\ & & & &&transmission \\ deaths & government & chinese &kids &recover &outbreak \\ fever &quarantine& trump&bill& check & lockdown\\ unemployed & wuhan& masks & unemployed& return to work& test\\ parents& lies & virus & food &reopening& deaths \\ test positive & close & pence & crisis & vaccine &pandemic\\ family & stayhome & chinks & parents & money &confirmed cases\\ patients & WHO & china & economy & treatment &total numbers\\ isolation & trump & hospitals & families & friends & conspiracy \\\hline \end{tabular} \caption{Top 10 extracted trigger spans regarding different emotions on Twitter.} \label{top-entity} \end{table*} \begin{table*} \small \center \begin{tabular}{|c|c|c|c|c|}\hline China& lockdown &Trump & Hospitals &Increasing Cases and Deaths \\\hline China& quarantine& realdonaldtrump & hospital& case \\ Chinese& stay & donald & patients & deaths\\ Wuhan& close&lies & test & report\\ bat-eating&home &republicans &doctor & confirmed\\ chink& stayhome & hydroxychloroquin & case & report\\ chinesevirus & boarder & american & healthcare& york \\ sinophobia&shutdown&media & drug &us \\ chingchong & distancing &governor & vaccine & total \\ hubei& coronalockdown&pence & ventilator & government\\ \hline \end{tabular} \caption{Top mentions of different subcategories for {\it anger} on Twitter.} \label{anger} \end{table*} \begin{table*} \small \center \begin{tabular}{|c|c|c|c|c|}\hline syndrome and being infected& families &finance and economy & jobs and food &Increasing Cases and Deaths \\\hline fever& parents& money & jobs & deaths \\ hospital & mother & stock & unemployed& spread\\ cough& children&financial &food &poll number \\ test positive&mom &price & money & death toll \\ icu& families & loan &work & confirmed \\ doctor &father &business& starve & rise\\ bed&kids& debt & unemployment & official \\ confimed & daughter &market & check & number \\ sick& father-in-law& crash& layoff & safe\\ \hline \end{tabular} \caption{Top mentions of different subcategories for {\it worry} anger on Twitter.} \label{worry} \end{table*} \input{figs/ch_emotion.tex} \input{figs/en_emotion.tex} \section{ Emotional Triggers} For a given emotion, we would like to dive deeper into its different subcategories. For example, for {\it worry}, we wish to know what the public is worried about, and how these triggers of worry change over time. In this section, we first present our methods for extracting triggers/subcategories for different emotions, followed by some analyses and visualization on the Twitter data. \subsection{Extracting the Triggers for Different Emotions} In order to extract the emotional triggers from Twitter’s noisy text, we first annotate a corpus of tweets. For the ease of annotation, each emotion is associated with only a single trigger: the person/entity/event that a user has a specific emotion towards/with/about. A few examples are shown as follows with target triggers surrounded by brackets. \begin{itemize} \item {\it Angry protesters are traveling 100's of miles to join organized rallies over COVID-19 [lockdown]$_{attr\_anger}$. } \item {\it Feeling awfully tired after a 5.30am start for work today. Worried too about [the early return to school]$_{attr\_worry}$, my grandchildren are so very dear to me . I could not bear to lose them to covid. } \item {\it All Americans are very angry with [@realDonaldTrump]$_{attr\_anger}$ 81,647 dead Americans would be very angry as well. If they weren’t dead.} \item {\it Fucking [bat-eating chinks]$_{{attr\_anger}}$, go die in a hole, far away from us. } \item {\it Well, I am ANGRY as hell at Trump$_{attr\_anger }$}. \item {\it With great sadness we report the sad [loss of two dear Friends]$_{{attr\_sadness}}$ } \item {\it The lockdown$_{{attr\_anger}}$ was implemented when there were hardly any cases and now it is above lakhs and people are acting so carelessly. Making me so angry. } \end{itemize} In order to build an emotional trigger tagger, we annotated 2,000 tweets in total, and split them into training, development and test sets with ratio 8:1:1. We treat the problem as a sequence labeling task, using Conditional Random Fields for learning and inference with BERT-MRC features \cite{li2019unified}. Comparing with vanilla BERT tagger \cite{devlin2018bert}, the BERT-MRC tagger has the strength of encoding the description of the to-be-extracted entities, e.g., {\it what they are worried about}. As this description provides the prior knowledge about the entities, it has been shown to outperform vanilla BERT even when less training data is used. In addition to the representation features from BERT-MRC, we also considered the Twitter-tuned POS features \cite{ritter2011named}, the dependency features from a Twitter-tuned dependency parsing model \cite{kong2014dependency} and the Twitter event features \cite{ritter2012open}. The precision and recall for segmenting emotional triggers on English tweets are reported in Table \ref{trigger}. \begin{table*}[!ht] \center \begin{tabular}{lccc}\hline Model & Pre & Rec & F1 \\\hline BERT & 0.41 & 0.60 & 0.48\\ BERT-MRC & 0.54 & 0.66 &0.59 \\ CRF with BERT-MRC features & 0.53 &0.68&0.60\\ CRF with BERT-MRC features, POS, event and parse tree features & 0.58 & 0.78 & 0.66 \\\hline \end{tabular} \caption{Performances of different models on emotional trigger extraction from Tweets.} \label{trigger} \end{table*} The precision and recall for segmenting triggering event phrases are reported in Table 3. We observe a significant performance boost with linguistic features such as POS and dependency features. This is mainly due to the small size of the labeled dataset. The best model achieves an F1 score of 0.66. \input{figs/angry.tex} \input{figs/worry.tex} \subsection{Clustering Trigger Mentions} Since different extracted tokens may refer to the same concept or topic, we would like to cluster the extracted trigger mentions. The method of supervised classification is unsuitable for this purpose since (1) it is hard to predefine a list of potential triggers to people's anger or worry; (2) it is extremely labor-intensive to annotate tweets with worry types or anger types and (3) these types may change over time. For these reasons, we decided to use semi-supervised approaches that will automatically induce worry/anger types that match the data. We adopt an approach based on LDA \cite{blei2003latent}. It was inspired by work on unsupervised information extraction \cite{chambers2011template,ritter2012open,li2014major}. We use the emotion {\it anger} to illustrate how trigger mentions are clustered. Each extracted trigger mentions for {\it anger} is modeled as a mixture of {\it anger} types. Here we use subcategory, type, and topic interchangeablely, all referring to the cluster of similar mentions. Each topic is characterized by a distribution over triggers, in addition to a distribution over dates on which a user talks about the topic. Taking dates into account encourages triggers that are mentioned on the same date to be assigned to the same topic. We used collapsed Gibbs Sampling \cite{griffiths2004finding} for inference. For each emotion, we ran Gibbs Sampling with 20 topics for 1,000 iterations, obtaining the hidden variable assignments in the last iteration. Then we manually inspected the top mentions for different topics and abandoned the incoherent ones. The daily intensity score for a given subcategory $k$ belonging to emotion $y$ is given as follows: \begin{equation} S(t,y, k) = \frac{1}{|X_t|} \sum_{x\in X_t} p (k|x) {\bf I}(y_x = y) \end{equation} where $p(k|x)$ is computed based on the parameters of the latent variable model. \subsection{Analyses} We report the top triggers for different emotions in Table \ref{top-entity}. We adopt a simple strategy of reporting the most frequent triggers for different emotions. For {\it sadness}, the most frequent triggering events and topics are being test positive, and the death of families and friends. For {\it anger}, the top triggers are shutdown, quarantine and other mandatory rules. People also express their anger towards public figures such as President Donald Trump, Mike Pence, along with China and Chinese. For {\it worry}, the top triggers include jobs, getting the virus, payments and families. For {\it happiness}, the top triggers are recovering from the disease, city reopening and returning to work. For {\it surprise}, the public are mostly surprised by the virus itself, its spread and the mass deaths it caused. Next we report the results of the mention clustering for {\it anger} and {\it worry} in Tables \ref{anger} and \ref{worry}, respectively. The unsupervised clustering reveals clearer patterns in the triggering events: top subcategories for {\it anger} include China with racist words such as {\it chink} and {\it chingchong}; lockdown and social distancing; public figures like President Donal Trump and Mike Pence; treatments in hospitals, and the increasing cases and deaths; Table \ref{anger} displays the change of intensity scores for the subcategories of {\it anger}. We observe a sharp increase in public anger toward China and Chinese around March 20th, in coincidence with President Donald Trump calling coronavirus 'Chinese virus' in his tweets. Public anger towards the lockdown sharply escalated in mid-March, but decreased a bit after late April when some places started to reopen. Top subcategories for {\it worry} include syndromes for COVID-19, finance and economy, families, jobs and food, and increasing cases and deaths. Table \ref{worry} displays the change of intensity scores for subcategories of {\it worry}. People increasingly worried about families over time. It is interesting to see that the worry about finance and economy started going up in mid-February, earlier than other subcategories. \section{Conclusion} In this paper, we perform analyses on topic trends, sentiments and emotions of the public in the time of COVID-19 on social media. By tracking the change of public emotions over time, our work reveals how the general public reacts to different events and government policy. Our study provides a computational approach to understanding public affect towards the pandemic in real-time, and could help create better solutions and interventions for fighting this global crisis.
{'timestamp': '2020-06-08T02:06:53', 'yymm': '2005', 'arxiv_id': '2005.14464', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14464'}
arxiv
\section{Introduction} \IEEEPARstart{S}{everal} applications use information that is encoded as vectors of integers, either directly or indirectly. Furthermore, these vectors are affected by noise that may increase or decrease entries of the vectors by a limited amount. We mention a few of these examples: In high-density magnetic recording channels, information is stored in the lengths of runs of $0$'s. Various phenomena may cause the reading process to shift the positions of $1$'s (peak-shift error), thereby changing the length of adjacent runs of $0$'s by a limited amount (e.g., see \cite{KuzVin93,LevVin93}). In flash memories, information is stored in the charge levels of cells in an array. However, retention (slow charge leakage), and inter-cell interference, may cause charge levels to move, usually, by a limited amount (e.g., see~\cite{CasSchBohBru10}). More recently, in some DNA-storage applications, information is stored in the lengths of homopolymer runs. These however, may end up shorter or longer than planned, usually by a limited amount, due to variability in the molecule-synthesis process (see~\cite{JaiFarSchBru20}). In all of the applications mentioned above, an integer vector $\mathbf{v}\in\mathbb{Z}^n$ encodes information. If at most $t$ of its entries suffer an increase by as much as $k_+$, or a decrease by as much as $k_-$, we can write the corrupted vector as $\mathbf{v}+\mathbf{e}$, where $\mathbf{e}$ resides within a shape we call the \emph{$(n,t,k_+,k_-)$-error-ball}, and is defined as \begin{equation} \label{eq:ball} {\mathcal B}(n,t,\kp,\km)\triangleq \set*{\mathbf{x}=(x_1,x_2,\ldots,x_n)\in \mathbb{Z}^n ; -k_- \leq x_i \leq k_+ \text{ and } \wt(\mathbf{x}) \leq t }, \end{equation} where $\wt(\mathbf{x})$ denotes the Hamming weight of $\mathbf{x}$. It now follows that an error-correcting code in this setting is equivalent to a packing of $\mathbb{Z}^n$ by ${\mathcal B}(n,t,\kp,\km)$, a covering code is equivalent to a covering of $\mathbb{Z}^n$ by ${\mathcal B}(n,t,\kp,\km)$, and a perfect code is equivalent to a tiling of $\mathbb{Z}^n$ by ${\mathcal B}(n,t,\kp,\km)$. An example of $\mathcal{B}(3,2,2,1)$ is shown in Fig.~\ref{fig:qc}. \begin{figure} \begin{center} \includegraphics{qc.eps} \end{center} \caption{A depiction of $\mathcal{B}(3,2,2,1)$ where each point in $\mathcal{B}(3,2,2,1)$ is shown as a unit cube.} \label{fig:qc} \end{figure} A significant amount of works has been devoted to tiling/packing/covering of $\mathbb{Z}^n$ by these shapes, albeit, almost exclusively for the case of $t=1$. When packing and tiling are concerned, the \emph{cross}, $\mathcal{B}(n,1,k,k)$, and semi-cross, $\mathcal{B}(n,1,k,0)$ have been extensively researched, e.g., see \cite{Ste84,HamSte84,HicSte86,SteSza94,KloLuoNayYar11} and the many references therein. This was extended to \emph{quasi-crosses}, $\mathcal{B}(n,1,k_+,k_-)$, in \cite{Sch12}, creating a flurry of activity on the subject \cite{YarKloBos13,Sch14,ZhaGe16,ZhaZhaGe17,ZhaGe18,YeZhaZhaGe20}. To the best of our knowledge, \cite{Ste90,KloLuoNayYar11,BuzEtz12,WeiSchwartz} are the only works to consider $t\geq 2$. \cite{Ste90,BuzEtz12} considered tiling a notched cube (or a ``chair''), which for certain parameters becomes $\mathcal{B}(n,n-1,k,0)$, while \cite{KloLuoNayYar11} considered packing the same ball $\mathcal{B}(n,n-1,k,0)$. Among others, \cite{WeiSchwartz} recently studied the tiling problem in the most general case, i.e., tiling ${\mathcal B}(n,t,\kp,\km)$ for $t \geq 2$. Covering problems have also been studied, though only when $t=1$,~\cite{CSW2014,Klove2016,KloveSchwartz2014}. The main goal of this paper is to study packing and covering of $\mathbb{Z}^n$ by ${\mathcal B}(n,t,\kp,\km)$ when $t\geq 2$. We provide explicit constructions for both packings and coverings, as well some non-constructive existence results. In particular, we demonstrate the existence of packings with asymptotic packing density $\Omega(1)$ (as $n$ tends to infinity) for some sets of $(t,k_+,k_-)$, and the existence of coverings with density $O(1)$ for any given $(t,k_+,k_-)$. Additionally, we generalize the concept of packing to $\lambda$-packing, which works in conjunction with the list-decoding framework and list size $\lambda$. We show the existence of $\lambda$-packings with density $O(n^{-\epsilon})$ for any $(t,k_+,k_-)$ and arbitrarily small $\epsilon>0$, while maintaining a list size $\lambda=O(\epsilon^{-t})$, which does not depend on $n$. Our results are summarized at the end of this paper, in Table~\ref{tab:summary}. The paper is organized as follows. We begin, in Section~\ref{sec:prelim}, by providing notation and basic known results used throughout the paper. Section~\ref{sec:packing} is devoted to the study of packings. This is generalized in Section~\ref{sec:genpack} to $\lambda$-packings. In Section~\ref{sec:covering} we construct coverings. Finally, we conclude in Section~\ref{sec:conclusion} by giving a summary of the results as well as some open problems. \section{Preliminaries} \label{sec:prelim} For integers $a\leq b$ we define $[a,b]\triangleq\set*{a,a+1,\dots,b}$ and $[a,b]^*\triangleq [a,b]\setminus\set*{0}$. We use $\mathbb{Z}_m$ to denote the cyclic group of integers with addition modulo $m$, and $\mathbb{F}_q$ to denote the finite field of size $q$. A \emph{lattice} $\Lambda\subseteq\mathbb{Z}^n$ is an additive subgroup of $\mathbb{Z}^n$ (sometimes called an \emph{integer lattice}). A lattice $\Lambda$ may be represented by a matrix $\mathcal{G}(\Lambda)\in\mathbb{Z}^{n\times n}$, the span of whose rows (with integer coefficients) is $\Lambda$. From a geometric point of view, when viewing $\Lambda$ inside $\mathbb{R}^n$, a \emph{fundamental region} of $\Lambda$ is defined as \[ \Pi(\Lambda)\triangleq \set*{ \sum_{i=1}^n c_i\mathbf{v}_i ; c_i\in\mathbb{R}, 0\leq c_i < 1 },\] where $\mathbf{v}_i$ is the $i$-th row of $\mathcal{G}(\Lambda)$. It is well known that the volume of $\Pi(\Lambda)$ is $\abs{\det(\mathcal{G}(\Lambda))}$, and is independent of the choice of $\mathcal{G}(\Lambda)$. We therefore denote \[ \vol(\Lambda)\triangleq \vol(\Pi(\Lambda)) = \abs*{\det(\mathcal{G}(\Lambda))}.\] In addition, if $\vol(\Lambda)\neq 0$ then \[ \vol(\Lambda)=\abs*{\mathbb{Z}^n / \Lambda}.\] We say $\mathcal{B}\subseteq\mathbb{Z}^n$ \emph{packs} $\mathbb{Z}^n$ by $T\subseteq\mathbb{Z}^n$, if the translates of $\mathcal{B}$ by elements from $T$ do not intersect, namely, for all $\mathbf{v},\mathbf{v}'\in T$, $\mathbf{v}\neq\mathbf{v}'$, \[ (\mathbf{v}+\mathcal{B})\cap(\mathbf{v}'+\mathcal{B})=\varnothing.\] We say $\mathcal{B}$ \emph{covers} $\mathbb{Z}^n$ by $T$ if \[ \bigcup_{\mathbf{v}\in T} (\mathbf{v}+\mathcal{B}) = \mathbb{Z}^n.\] If $\mathcal{B}$ both packs and covers $\mathbb{Z}^n$ by $T$, then we say $\mathcal{B}$ \emph{tiles} $\mathbb{Z}^n$ by $T$. The \emph{packing density} (or \emph{covering density}, respectively) of $\mathcal{B}$ by $T$ is defined as \[ \delta\triangleq \lim_{\ell\to\infty} \frac{\abs*{[-\ell,\ell]^n\cap T}\cdot\abs{\mathcal{B}}}{\abs*{[-\ell,\ell]^n}}.\] When $T=\Lambda$ is some lattice, we call these lattice packings and lattice coverings, respectively. The density then takes on a simpler form \[\delta = \frac{\abs{\mathcal{B}} }{\vol(\Lambda)}.\] Throughout the paper, the object we pack and cover $\mathbb{Z}^n$ with, is the error ball, ${\mathcal B}(n,t,\kp,\km)$, defined in \eqref{eq:ball}. We conveniently observe that for all integers $n\geq 1$, $0\leq t\leq n$, $0\leq k_-\leq k_+$, we have \[ \abs*{{\mathcal B}(n,t,\kp,\km)}=\sum_{i=0}^t \binom{n}{i}(k_++k_-)^i.\] \subsection{Lattice Packing/Covering/Tiling and Group Splitting} Lattice packing, covering, and tiling of $\mathbb{Z}^n$ with $\mathcal{B}(n,t,k_+,k_-)$, in connection with group splitting, has a long history when $t=1$ (e.g., see \cite{Ste67}), called lattice tiling by crosses if $k_+=k_-$ (e.g., \cite{Ste84}), semi-crosses when $k_-=0$ (e.g., \cite{Ste84,HamSte84,HicSte86}), and quasi-crosses when $k_+\geqk_-\geq 0$ (e.g., \cite{Sch12,Sch14}). For an excellent treatment and history, the reader is referred to~\cite{SteSza94} and the many references therein. Other variations, keeping $t=1$ include~\cite{Tam98,Tam05}. More recent results may be found in~\cite{YeZhaZhaGe20} and the references therein. For $t\geq 2$, an extended definition of group splitting in connection with lattice tiling is provided in \cite{WeiSchwartz}. In the following, we modify this definition to distinguish between lattice packings, coverings, and tilings. \begin{definition} \label{def:split} Let $G$ be a finite Abelian group, where $+$ denotes the group operation. For $m\in\mathbb{Z}$ and $g\in G$, let $mg$ denote $g+g+\dots+g$ (with $m$ copies of $g$) when $m>0$, which is extended in the natural way to $m\leq 0$. Let $M\subseteq\mathbb{Z}\setminus\set*{0}$ be a finite set, and $S=\set*{s_1,s_2,\dots,s_n}\subseteq G$. \begin{enumerate} \item If the elements $\mathbf{e}\cdot (s_1,\dots,s_n)$, where $\mathbf{e}\in (M\cup\set{0})^n$ and $1\leq \wt(\mathbf{e})\leq t$, are all distinct and non-zero in $G$, we say the set $M$ partially $t$-splits $G$ with splitter set $S$, denoted \[G \geq M\diamond_t S.\] \item If for every $g\in G$ there exists a vector $\mathbf{e}\in (M\cup\set{0})^n$, $\wt(\mathbf{e})\leq t$, such that $g=\mathbf{e}\cdot (s_1,\dots,s_n)$, we say the set $M$ completely $t$-splits $G$ with splitter set $S$, denoted \[G \leq M\diamond_t S.\] \item If $G \geq M\diamond_t S$ and $G \leq M\diamond_t S$ we say $M$ $t$-splits $G$ with splitter set $S$, and write \[ G = M\diamond_t S.\] \end{enumerate} \end{definition} In our context, since we are interested in packing and covering with ${\mathcal B}(n,t,\kp,\km)$, then in the previous definition, we need to take $M\triangleq [-k_-,k_+]^*$. Thus, the following two theorems show the equivalence of partial $t$-splittings with $M$ and lattice packings of ${\mathcal B}(n,t,\kp,\km)$, summarizing Lemma 3 and Lemma 4 in\cite{BuzEtz12}, and similarly for complete $t$-splittings and lattice coverings. \begin{theorem} \label{th:lattotile} Let $G$ be a finite Abelian group, $M\triangleq [-k_-,k_+]^*$, and $S=\set*{s_1,\dots,s_n}\subseteq G$. Define $\phi:\mathbb{Z}^n\to G$ as $\phi(\mathbf{x})\triangleq\mathbf{x}\cdot(s_1,\dots,s_n)$ and let $\Lambda\triangleq\ker\phi$ be a lattice. \begin{enumerate} \item If $G \geq M\diamond_t S$, then $\mathcal{B}(n,t,k_+,k_-)$ packs $\mathbb{Z}^n$ by $\Lambda$. \item If $G \leq M\diamond_t S$, then $\mathcal{B}(n,t,k_+,k_-)$ covers $\mathbb{Z}^n$ by $\Lambda$. \end{enumerate} \end{theorem} \begin{IEEEproof} For packing, see Lemma 4 in \cite{BuzEtz12}. For covering, denote $\mathcal{B}\triangleq\mathcal{B}(n,t,k_+,k_-)$. Assume $\mathbf{x}\in\mathbb{Z}^n$. Since $G \leq M\diamond_t S$, there exists a vector $\mathbf{e}\in\mathcal{B}$ such that $\phi(\mathbf{x})=\phi(\mathbf{e})$. Then $\mathbf{v}\triangleq \mathbf{x}-\mathbf{e}\in\Lambda$, and $\mathbf{x}\in\mathbf{v}+\mathcal{B}$. \end{IEEEproof} In the theorem above, for $G \geq M\diamond_t S$, since the quotient group $\mathbb{Z}^n / \Lambda$ is isomorphic to the image of $\phi$, which is a subgroup of $G$, we have $\vol(\Lambda)\leq \abs{G}$. Then the packing density of $\Lambda$ is \[\delta = \frac{\abs{{\mathcal B}(n,t,\kp,\km)} }{\vol(\Lambda)}\geq\frac{\abs{{\mathcal B}(n,t,\kp,\km)} }{\abs{G}} .\] For $G \leq M\diamond_t S$, $\vol(\Lambda)= \abs{G}$, and the covering density of $\Lambda$ is \[\delta = \frac{\abs{{\mathcal B}(n,t,\kp,\km)} }{\vol(\Lambda)}=\frac{\abs{{\mathcal B}(n,t,\kp,\km)} }{\abs{G}} .\] It is known that a lattice packing implies a partial splitting. While not of immediate use to us in this paper, we do mention that an analogous claim is also true for lattice coverings, as the following theorem shows. \begin{theorem} Let $\Lambda\subseteq\mathbb{Z}^n$ be a lattice. Define $G\triangleq \mathbb{Z}^n / \Lambda$. Let $\phi:\mathbb{Z}^n\to G$ be the natural homomorphism, namely the one that maps any $\mathbf{x}\in\mathbb{Z}^n$ to the coset of $\Lambda$ in which it resides, and then $\Lambda=\ker\phi$. Finally, let $\mathbf{e}_i$ be the $i$-th unit vector in $\mathbb{Z}^n$ and set $s_i\triangleq\phi(\mathbf{e}_i)$ for all $1\leq i\leq n$ and $S\triangleq\set*{s_1,s_2,\dots,s_n}$. \begin{enumerate} \item If $\mathcal{B}(n,t,k_+,k_-)$ packs $\mathbb{Z}^n$ by $\Lambda$, then $G\geq M\diamond_t S$; \item if $\mathcal{B}(n,t,k_+,k_-)$ covers $\mathbb{Z}^n$ by $\Lambda$, then $G\leq M\diamond_t S$, \end{enumerate} where $M\triangleq [-k_-,k_+]^*$. \end{theorem} \begin{IEEEproof} The packing see Lemma 3 in \cite{BuzEtz12}. Now we prove the claim for covering. Let $\Lambda+\mathbf{x} \in G$ be any element of $G$. Since ${\mathcal B}(n,t,\kp,\km)$ covers $\mathbb{Z}^n$ by $\Lambda$, there exist $\mathbf{v}\in\Lambda$ and $\mathbf{e}\in{\mathcal B}(n,t,\kp,\km)$ such that $\mathbf{x}=\mathbf{v}+\mathbf{e}$. This means \[\Lambda+\mathbf{x}=\phi(\mathbf{x})=\phi(\mathbf{v})+\phi(\mathbf{e})=\phi(\mathbf{e})=\mathbf{e}\cdot(s_1,\dots,s_n),\] which completes the proof. \end{IEEEproof} Finally, a connection between perfect codes in the Hamming metric, and lattice tilings with ${\mathcal B}(n,t,\kp,\km)$ was observed in~\cite{WeiSchwartz}. We repeat a theorem we shall later generalize. \begin{theorem}[Theorem~3 in \cite{WeiSchwartz}] \label{th:perfectcode} In the Hamming metric space, let $C$ be a perfect linear $[n,k,2t+1]$ code over $\mathbb{F}_p$, with $p$ a prime. If $k_++k_-+1=p$, then \[ \Lambda\triangleq \set*{ \mathbf{x}\in\mathbb{Z}^n ; (\mathbf{x}\bmod p)\in C}\] is a lattice, and $\mathcal{B}(n,t,k_+,k_-)$ tiles $\mathbb{Z}^n$ by $\Lambda$. \end{theorem} \section{Constructions of Lattice Packings} \label{sec:packing} In this section we describe several constructions for packings of ${\mathcal B}(n,t,\kp,\km)$. We begin by showing how to translate codes in the Hamming metric into lattices that pack ${\mathcal B}(n,t,\kp,\km)$. Apart from a single case, these have vanishing density. The motivation for showing these ``off-the-shelf'' constructions is to create a baseline against which we measure our tailor-made constructions that appear later. These use $B_t[N;1]$ sequences, or take inspiration from constructions of sets with no arithmetic progression, to construct codes that improve upon the baseline. \subsection{Constructions Based on Error-Correcting Codes} Theorem~\ref{th:perfectcode} can be easily modified to yield the following construction, the proof of which is the same as that of \cite[Theorem 3]{WeiSchwartz} and we omit here to avoid unnecessary repetition. \begin{theorem} \label{th:linearcode} In the Hamming metric space, let $C$ be a linear $[n,k,2t+1]$ code over $\mathbb{F}_p$, with $p$ a prime. If $0\leq k_++k_- < p$ are integers, then \[ \Lambda\triangleq \set*{ \mathbf{x}\in\mathbb{Z}^n ; (\mathbf{x}\bmod p)\in C}\] is a lattice, and $\mathcal{B}(n,t,k_+,k_-)$ packs $\mathbb{Z}^n$ by $\Lambda$. \end{theorem} Since $\mathcal{B}(n,t,k_+,k_-)$ packs $\mathbb{Z}^n$ by $\Lambda$, the lattice $\Lambda$ is an error-correcting code over $\mathbb{Z}$ for asymmetric limited-magnitude errors. We note that a similar construction of error-correcting codes over a finite alphabet for asymmetric limited-magnitude errors was presented in \cite{CasSchBohBru10} and the decoding scheme therein can be adapted here as follows. Let $\mathbf{x}\in\Lambda$ be a codeword, and $\mathbf{y} \in\mathbf{x}+{\mathcal B}(n,t,\kp,\km)$ be the channel output. Denote $\boldsymbol{\psi}= \mathbf{y} \pmod{p}$. Run the decoding algorithm of the linear $[n,k,2t+1]$ code on $\boldsymbol{\psi}$ and denote the output as $\boldsymbol{\phi}$. Then $\boldsymbol{\phi}$ is a codeword of the linear code over $\mathbb{F}_p$ and it is easy to see that $\boldsymbol{\phi}=\mathbf{x} \pmod{p}$. Thus $\mathbf{y}-\mathbf{x}\equiv\boldsymbol{\psi} - \boldsymbol{\phi} \pmod{p}$. Denote $\boldsymbol{\epsilon}=\boldsymbol{\psi} - \boldsymbol{\phi} \pmod{p}$ and let $\mathbf{e}=(e_1,e_2,\ldots,e_n)$ where \[ e_i \triangleq \begin{cases} \epsilon_i, \textup{\ \ if $0\leq \epsilon_i \leq k_+$;} \\ \epsilon_i-p, \textup{\ \ otherwise.}\\ \end{cases} \] Then $\mathbf{x}$ can be decoded as $\mathbf{x}=\mathbf{y}-\mathbf{e}$. Now let us look at the packing density. \begin{corollary} \label{cor:linearcode} Let $\Lambda$ be the lattice constructed in Theorem~\ref{th:linearcode}. Then $\vol(\Lambda)=p^{n-k}$ and the packing density is \[\delta=\frac{\sum_{i=0}^t \binom{n}{i}(k_++k_-)^i}{ p^{n-k} }.\] \end{corollary} \begin{IEEEproof} In Theorem~\ref{th:linearcode}, the quotient group $\mathbb{Z}^n/ \Lambda$ is isomorphic to the group $\mathbb{Z}_p^{n-k}$ (see Example 3 and Example 4 in \cite{WeiSchwartz}). The claim is then immediate. \end{IEEEproof} When $t$ is small, we may use BCH codes as the input to construct the lattice packing. \begin{theorem}[Primitive narrow-sense BCH codes {\cite[Theorem 10]{aly2007quantum}}]\label{primitiveBCH} Let $p$ be a prime. Fix $m\ge 1$ and $2\le d\le p^{\ceil{m/2}}-1$. Set $n=p^m-1$. Then there exists an $[n,k,d]$-code over $\mathbb{F}_p$ with \[k=n-\ceil{(d-1)(1-1/p)}m.\] \end{theorem} \begin{corollary}\label{cor:lc} Let $\psi(x)$ be the smallest prime not smaller than $x$ \footnote{It is known that $\psi(x)\leq x+x^{21/40}$ \cite{BakHarPin01}, and conjectured that $\psi(x)=x+O(\log x)$.} and denote $p\triangleq\psi(k_++k_-+1)$. Let $m,t$ be positive integers such that $2t\le p^{\ceil{m/2}}-2$, and set $n=p^m-1$. Then $\mathbb{Z}^n$ can be lattice packed by ${\mathcal B}(n,t,\kp,\km)$ with density \[\delta = \frac{\sum_{i=0}^t \binom{n}{i}(k_++k_-)^i}{(n+1)^{\ceil{2t(1-{1}/p)}} }.\] \end{corollary} \begin{IEEEproof} Simply combine Theorem~\ref{primitiveBCH} with Corollary~\ref{cor:linearcode}. \end{IEEEproof} Note that if $k_+=1$ and $k_-=0$, then the packing density in Corollary~\ref{cor:lc} is $\delta=\frac{\sum_{i=0}^t \binom{n}{i}}{(n+1)^{t}}=\frac{1}{t!}+o(1)$ (when $t$ is fixed and $n$ tends to infinity). However, for all the other values of $k_+$ and $k_-$, namely $p\geq 3$, the density always vanishes when $n$ tends to infinity, i.e., $\delta=\Theta(n^{t-\ceil{2t(1-{1}/p)}})$. In the remainder of this section, we will present some constructions to provide lattice packings of higher density. Perfect codes were used in \cite{WeiSchwartz} obtain lattice tilings, i.e., lattice packings with density $1$. Similarly, it is possible to use quasi-perfect linear codes to obtain lattice packings with high densities. \begin{corollary}\label{cor:quasiperfectlc} Assume that $1\leq k_++k_-\leq 2$ are non-negative integers. \begin{enumerate} \item Let $m$ be a positive integer and $n=(3^m+1)/2$. Then $\mathbb{Z}^n$ can be lattice-packed by $\mathcal{B}(n,2,k_+,k_-)$ with density \[\delta = \frac{ {n\choose 2}(k_++k_-)^2 +n(k_++k_-) +1 }{(2n-1)^2}.\] \item Let $m\geq 3$ be an odd integer and $n=(3^m-1)/2$. Then $\mathbb{Z}^n$ can be lattice packed by $\mathcal{B}(n,2,k_+,k_-)$ with density \[\delta = \frac{ {n\choose 2}(k_++k_-)^2 +n(k_++k_-) +1 }{(2n+1)^2}.\] \end{enumerate} \end{corollary} \begin{IEEEproof} For the first case, we take a $[(3^m+1)/2, (3^m+1)/2-2m,5]_3$ code from \cite{GashkovSidelnikov1986} as the input of Theorem~\ref{th:linearcode} to obtain the lattice packing, while for the second, we take a $[(3^m-1)/2, (3^m-1)/2-2m,5]_3$ code from \cite{DanevDodunekov2008} as the input. \end{IEEEproof} We note that \cite{LiHelleseth2016} presented some binary quasi-perfect linear codes with minimum distance $5$, which can give rise to packings of $\mathcal{B}(n,2,1,0)$. It has been checked out that the corresponding densities are asymptotically the same as that in Corollary~\ref{cor:lc}, i.e., $\frac{1}{2}+o(1)$. \cite{LiHelleseth2016} also studied $p$-ary quasi-perfect linear codes with $p\geq 3$. However, the minimum distances of those codes are no more that $4$. So they cannot be used to obtain packings of ${\mathcal B}(n,t,\kp,\km)$ with $t \geq 2$. The following theorem uses non-linear codes to construct non-lattice packing, the proof of which is the same as that of \cite[Theorem 5]{CasSchBohBru10} and we omit here to avoid unnecessary repetition. \begin{theorem} \label{th:nonlinearcode} In the Hamming metric space, let $C$ be a $q$-ary $(n,M,2t+1)$ code. Denote \[ V\triangleq \set*{ \mathbf{v}\in\mathbb{Z}^n ; (\mathbf{v}\bmod q)\in C}.\] If $k_++k_- < q$, then for any distinct $\mathbf{v},\mathbf{v}'\in V$, we have $(\mathbf{v}+{\mathcal B}(n,t,\kp,\km)) \cap (\mathbf{v}'+{\mathcal B}(n,t,\kp,\km))=\varnothing$, namely, ${\mathcal B}(n,t,\kp,\km)$ can pack $\mathbb{Z}^n$ by $V$. \end{theorem} \begin{corollary} \label{cor:nonlinearcode} The density of the packing of $\mathbb{Z}^n$ constructed in Theorem~\ref{th:nonlinearcode} is \[\delta=\frac{M\cdot\sum_{i=0}^t \binom{n}{i}(k_++k_-)^i}{ q^{n} }.\] \end{corollary} \begin{IEEEproof} Note that the set $V$ constructed in Theorem~\ref{th:nonlinearcode} has period $q$ in each coordinate. Thus, the packing density of $\mathbb{Z}^n$ is equal to the packing density of $\mathbb{Z}_q^n$, which is $\frac{M}{q^n}\sum_{i=0}^t \binom{n}{i}(k_++k_-)^i.$ \end{IEEEproof} \begin{corollary}\label{cor:perparata} Let $m \geq 4$ be even integer and let $n=2^m-1$. Then $\mathbb{Z}^n$ can be packed by $\mathcal{B}(n,2,1,0)$ with density \[\delta = \frac{ {n\choose 2} +n +1 }{(n+1)^2/2}=1-\frac{n-1}{(n+1)^2}.\] \end{corollary} \begin{proof} We take a binary $(2^m-1, 2^{2^m-2m},5)$ Preparata code \cite{Preparata1968} as the input of Theorem~\ref{th:nonlinearcode} to obtain the packing. \end{proof} \subsection{Construction Based on $B_t[N;1]$ Sets for $(k_+,k_-)=(1,0)$ or $(1,1)$} A subset $A\subseteq\mathbb{Z}$ is called a \emph{$B_t[g]$ set} if every integer can be written in at most $g$ different ways as a sum of $t$ (not necessary distinct) elements of $A$ (e.g., see \cite[Section~4.5]{TaoVu06} and the many references therein). In this section, however, we require $B_t[1]$ sets with a somewhat stronger property. Specifically, a subset $A$ of $\mathbb{Z}_N$ is called a \emph{$B_t[N;1]$ set} if the sums of any $t$ (not necessary distinct) elements of $A$ are all different modulo $N$. Bose and Chowla \cite{BoseChowla} presented two classes of $B_t[N;1]$ sets. \begin{theorem}\cite[Theorem 1 and Theorem 2]{BoseChowla}\label{thm:Btset} Let $q$ be a prime power and $t$ be a positive integer. Let $\alpha_0=0,\alpha_1,\alpha_2,\ldots,\alpha_{q-1}$ be all the different elements of $\mathbb{F}_q$. \begin{enumerate} \item Let $\xi$ be a primitive element of the extended field $\mathbb{F}_{q^t}$. For each $0\leq i \leq q-1$, let $d_i \in \mathbb{Z}_{q^{t}-1}$ be such that \[\xi^{d_i}=\xi+\alpha_i.\] Then the set $S_1\triangleq \set*{d_i;0\leq i \leq q-1}$ is a $B_t[q^t-1;1]$ set of size $q$. \item Let $\eta$ be a primitive element of the extended field $\mathbb{F}_{q^{t+1}}$. For each $0\leq i \leq q-1$, let $\beta_i \in \mathbb{F}_q$ and $s_i \in \mathbb{Z}_{(q^{t+1}-1)/(q-1)}$ such that \[ \beta_i\eta^{s_i}=\eta+\alpha_i.\] Then the set $S_2\triangleq \set*{s_i;0\leq i \leq q-1} \cup \set{0}$ is a $B_t[(q^{t+1}-1)/(q-1);1]$ set of size $q+1$. \end{enumerate} \end{theorem} \begin{theorem}\label{thm:con-Btset-1} Let $A$ be a $B_t[N;1]$ set which contains $0$. Denote $S\triangleq A\setminus\set{0}$. Then $\mathbb{Z}_N \ge \set{1} \diamond_t S$. \end{theorem} \begin{IEEEproof} Suppose to the contrary that $\set*{s_{i_1},s_{i_2},\ldots,s_{i_{\ell}}}$ and $\set*{s_{j_1},s_{j_2},\ldots,s_{j_{r}}}$ are two distinct subsets of $S$ such that \[s_{i_1}+s_{i_2}+\ldots+s_{i_{\ell}}\equiv s_{j_1}+s_{j_2}+\ldots+s_{j_{r}} \pmod{N},\] where $\ell,r\leq t$. Then we have \[ \underbrace{0+0+\cdots +0}_{t-\ell}+ s_{i_1}+s_{i_2}+\ldots+s_{i_{\ell}}\equiv \underbrace{0+0+\cdots +0}_{t-r}+s_{j_1}+s_{j_2}+\ldots+s_{j_{r}} \pmod{N},\] which contradicts that $S\cup \set{0}$ is a $B_t[N;1]$ set. \end{IEEEproof} The following result slightly improves upon the density obtained in Corollary~\ref{cor:lc} for lattice packings of $\mathcal{B}(n,t,1,0)$. \begin{corollary} \label{cor:btsets} \begin{enumerate} \item If $n+1$ is a prime power, then for any $2\leq t \leq n$, there is a lattice packing of $\mathbb{Z}^n$ by $\mathcal{B}(n,t,1,0)$ with density \[\delta=\frac{\sum_{i=0}^t\binom{n}{i} }{(n+1)^t-1}=\frac{1}{t!}+o(1).\] \item If $n$ is a prime power, then for any $2\leq t \leq n$, there is a lattice packing of $\mathbb{Z}^n$ by $\mathcal{B}(n,t,1,0)$ with density \[\delta=\frac{\sum_{i=0}^t\binom{n}{i}}{(n^{t+1}-1)/(n-1)}=\frac{1}{t!}+o(1).\] \end{enumerate} \end{corollary} \begin{IEEEproof} Note that if $\set*{s_1,s_2,\ldots,s_n}$ is a $B_t[N;1]$ set, then $\set*{0,s_2-s_1,s_3-s_1,\ldots,s_n-s_1}$ is also a $B_t[N;1]$ set, which contains $0$. Hence, combining Theorem~\ref{thm:Btset} and Theorem~\ref{thm:con-Btset-1}, together with Theorem~\ref{th:lattotile}, we prove the claim. \end{IEEEproof} In general, we do not have an efficient decoding scheme for the lattice code obtained from Theorem~\ref{thm:con-Btset-1}. However, for the lattice code $\Lambda_{S_2\setminus\set{0}}$ obtained from the $B_t[(q^{t+1}-1)/(q-1);1]$ set $S_2$ in Theorem~\ref{thm:Btset}, we have the following decoding algorithm (summarized in Algorithm~\ref{alg:decoding}). Let $n=q$ and let $S_2\setminus\set{0}=\set{s_0,\dots,s_{n-1}}$ be defined as in Theorem~\ref{thm:Btset}. Let $\mathbf{x}\in\Lambda_{S_2\setminus\set{0}}$ be a codeword and $\mathbf{y} \in \mathbf{x}+\mathcal{B}(n,t,1,0)$ be the channel output. Then $\mathbf{x}\cdot (s_0,s_1,\ldots,s_{n-1})=0$, and $\mathbf{y}-\mathbf{x}$ is a binary vector over $\set{0,1}$ of weight at most $t$. Let $i_1,i_2,\ldots,i_r$ be the indices of the nonzero bits of $\mathbf{y}-\mathbf{x}$, and denote $s=\mathbf{y}\cdot (s_0,s_1,\ldots,s_{n-1})$. We aim to recover $i_1,i_2,\ldots,i_r$ from $s$. Since \begin{align*} s&=\mathbf{y}\cdot (s_0,s_1,\ldots,s_{n-1}) = \mathbf{y}\cdot (s_0,s_1,\ldots,s_{n-1}) -0 =\mathbf{y}\cdot (s_0,s_1,\ldots,s_{n-1})-\mathbf{x}\cdot (s_0,s_1,\ldots,s_{n-1}) \\ &= (\mathbf{y}-\mathbf{x})\cdot (s_0,s_1,\ldots,s_{n-1}) =\sum_{\ell=1}^r s_{i_\ell}, \end{align*} we have that \begin{equation}\label{eq:decode} \parenv*{\prod_{\ell=1}^r \beta_{i_\ell}} \eta^s= \prod_{\ell=1}^r\parenv*{\beta_{i_\ell} \eta^{s_{i_\ell}}} =\prod_{\ell=1}^r(\eta+\alpha_{i_\ell}). \end{equation} Let $p(x)$ be the primitive polynomial of $\eta$ and $r(x) = x^s \bmod p(x)$. Then $r(\eta)=\eta^s$, and we substitute this in \eqref{eq:decode} to obtain \[\parenv*{\prod_{\ell=1}^r \beta_\ell} r(\eta)=\prod_{\ell=1}^r(\eta+\alpha_{i_\ell}).\] Since both the polynomials $(\prod_{\ell=1}^r \beta_{i_\ell}) r(x)$ and $\prod_{\ell=1}^r(x+\alpha_{i_\ell})$ are over $\mathbb{F}_q$ and have degrees at most $t$, they should be the same; otherwise, $\eta$ is a root of a nonzero polynomial of degree at most $t$, which contradicts the fact that $\eta$ is a primitive element of $\mathbb{F}_{q^{t+1}}$. Thus, we may solve $(\prod_{\ell=1}^r \beta_\ell) r(x)$ to find out $\alpha_{i_1}, \alpha_{i_1},\ldots, \alpha_{i_r}$. Finally, we can subtract $\sum_{\ell=1}^r \mathbf{e}_{i_\ell}$ from $\mathbf{y}$ to obtain $\mathbf{x}$. \begin{algorithm}[ht] \caption{Decoding algorithm for $\Lambda_{S_2\setminus\set{0}}$ from Theorem~\ref{thm:Btset}} \label{alg:decoding} \begin{algorithmic}[1] \Statex \textbf{Input:} received vector $\mathbf{y}\in\mathbb{Z}^n$ suffering at most $t$ errors \Statex \quad\quad\quad $S_2\setminus\set{0}=\set{s_0,\dots,s_{n-1}}$ from Theorem~\ref{thm:Btset} \Statex \quad\quad\quad where $\eta$ is a root of a primitive polynomial $p(x)$ of degree $t+1$ \Statex \quad\quad\quad and where $\mathbb{F}_q\setminus\set{0}=\set{\alpha_1,\dots,\alpha_{q-1}}$. \Statex \textbf{Output:} codeword $\mathbf{x}\in\Lambda_{S_2\setminus\set{0}}$ such that $\mathbf{y}\in\mathbf{x}+\mathcal{B}(n,t,1,0)$ \State $s \gets \mathbf{y} \cdot (s_0,s_1,\ldots,s_{n-1})$ \label{step:s} \State $r(x)\gets x^s \bmod p(x)$ \label{step:r} \For{$1\leq i\leq q-1$} \label{step:loop} \If{$r(\alpha_i)=0$} \State $\mathbf{y} \gets \mathbf{y} - \mathbf{e}_i$ \EndIf \EndFor \State \Return{$\mathbf{y}$} \end{algorithmic} \end{algorithm} Let us analyze the time complexity of Algorithm~\ref{alg:decoding}, where we count the number of field operations in $\mathbb{F}_q$. The inner product in Step~\ref{step:s} takes $O(n)$ operations. Step~\ref{step:r} is possible to compute in $O(t^2 \log s)$ field operations (by using successive squaring and multiplication by $x$ as necessary, taking a modulo $p(x)$ after each iteration). Since $s \in \mathbb{Z}_{(q^{t+1}-1)/(q-1)}$ and $n=q$, it is $O(t^3 \log n)$. Finally, the root search loop starting in Step~\ref{step:loop} takes $O(tn)$ operations. Thus, in total, the time complexity $O(tn+t^3\log n)$ field operations. If $t$ is constant, then this is linear in the code length. As a final comment, we point out that $q=O(n)$, and thus the basic field operations of addition and multiplication may be realized in $O(\mathrm{polylog}(n))$ time. We now move from packing $\mathcal{B}(n,t,1,0)$ to packing $\mathcal{B}(n,t,1,1)$. In general, we note that one can use a $B_{h}[N;1]$ set with $h=t(k_++k_-)$ to obtain a lattice packing of ${\mathcal B}(n,t,\kp,\km)$ in $\mathbb{Z}_n$ for $k_++k_- \geq 2$. However, in this case, the density is $O(n^{t(1-{k_++k_-})})$, which vanishes when $n$ tends to infinity. Similarly, the lattice packing from Corollary~\ref{cor:lc} also has vanishing density $O(n^{t-\ceil{2t(1-{1}/p)}})$. In the following, we give a modified construction which uses a $B_{t}[N;1]$ set to obtain a lattice packing of $\mathcal{B}(n,t,1,1)$ with density $\Omega(1)$. \begin{theorem}\label{thm:con-Btset-pm1} Let $A=\set{a_1,a_2,\dots,a_n}$ be a $B_t[N;1]$ set. In the group $\mathbb{Z}_N \times \mathbb{Z}_{2t+1}$, construct a set \[S\triangleq \set*{ (a_i,1) ; a_i \in A}.\] Then $\mathbb{Z}_N \times \mathbb{Z}_{2t+1} \ge \set{-1,1} \diamond_t S$. \end{theorem} \begin{IEEEproof} Suppose to the contrary that there are $(a_{i_1},1),(a_{i_1},1),\dots,(a_{i_{\ell}},1)$ and $(a_{j_1},1),(a_{j_2},1),\dots,(a_{j_{r}},1)$ in $S$ such that \begin{equation}\label{eq:con-Bset} \sum_{m=1}^{\ell'} (a_{i_m},1)-\sum_{m=\ell'+1}^{\ell}(a_{i_m},1) = \sum_{m=1}^{r'} (a_{j_m},1)-\sum_{m=r'+1}^{r}(a_{j_m},1), \end{equation} where $0\leq \ell'\leq \ell \leq t$ and $0\leq r'\leq r \leq t$, and the addition is over the group $\mathbb{Z}_N \times \mathbb{Z}_{2t+1}$. The second coordinate of the equation above implies that \[\ell-2\ell'\equiv r-2r' \pmod{2t+1}.\] Since $0\leq \ell'\leq \ell \leq t$ and $0\leq r'\leq r \leq t$, we have $\ell-2\ell', r-2r'\in [-t,t]$. It follows that $\ell-2\ell'= r-2r',$ and so, $\ell'+r-r'=r'+\ell-\ell'$. Let $\tau\triangleq\ell'+r-r'$. Then \[\tau = \frac{\ell'+r-r'+r'+\ell-\ell'}{2} =\frac{\ell+r}{2} \leq t.\] Rearranging the terms in the first coordinate of the equation \eqref{eq:con-Bset}, we have \begin{equation}\label{eq:con-Bset-2} a_{i_1}+ a_{i_2}+\cdots+ a_{i_{\ell'}} + a_{j_{r'+1}} + \cdots + a_{j_{r}} \equiv a_{j_1}+ a_{j_2}+\cdots+ a_{j_{r'}} + a_{i_{\ell'+1}} + \cdots + a_{i_{\ell}} \pmod{N}. \end{equation} On both side of \eqref{eq:con-Bset-2}, there are $\tau$ terms. This contradicts the fact that $A$ is a $B_{t}[N;1]$ (and hence a $B_{\tau}[N;1]$ set for any $\tau \leq t$). \end{IEEEproof} Combining Theorem~\ref{thm:Btset} and Theorem~\ref{thm:con-Btset-pm1}, together with Theorem~\ref{th:lattotile}, we have the following result. \begin{corollary} \label{cor:kpm1} If $n$ is a prime power, then for any $2\leq t \leq n$, there is a lattice packing of $\mathbb{Z}^n$ by $\mathcal{B}(n,t,1,1)$ with density \[\delta=\frac{\sum_{i=0}^t\binom{n}{i}2^i }{(2t+1)(n^t-1)}=\frac{2^t}{t!(2t+1)}+o(1).\] If $n-1$ is a prime power, then for any $2\leq t \leq n$, there is a lattice packing of $\mathbb{Z}^n$ by $\mathcal{B}(n,t,1,1)$ with density \[\delta=\frac{\sum_{i=0}^t\binom{n}{i} 2^i}{(2t+1)((n-1)^{t+1}-1)/(n-2)}=\frac{2^t}{t!(2t+1)}+o(1).\] \end{corollary} \subsection{Constructions for $t=2$} Whereas in the previous section we considered unconstrained $t$ but only small values of $k_+,k_-$, in this section we focus on the case of $t=2$ but unconstrained $k_+,k_-$. We first present a construction based on $k$-fold Sidon sets. Such sets were first defined in~\cite{Lazebnik2003} as a generalization of Sidon sets. We repeat the definition here. Let $k$ be a positive integer and let $N$ be relatively prime to all elements of $[1,k]$, i.e., $\gcd(N,k!)=1$. Fix integers $c_1,c_2,c_3,c_4\in [-k,k]$ such that $c_1+c_2+c_3+c_4=0$, and let $\mathcal{S}$ be the collection of sets $S \subseteq \set{1,2,3,4}$ such that $\sum_{i \in S} c_i=0$ and $c_i\neq 0$ for $i \in S$. We note that $\mathcal{S}$ always contains the empty set. Consider the following equation over $x_1,x_2,x_3,x_4\in \mathbb{Z}_N$: \begin{equation}\label{eq:kfoldSidonset} c_1x_1+c_2x_2+c_3x_3+c_4x_4\equiv 0 \pmod{N}. \end{equation} A solution of \eqref{eq:kfoldSidonset} is \emph{trivial} if there exists a partition of the set $\set{i ; c_i\neq 0}$ into sets $S,T\in \mathcal{S}$ such that $x_i=x_j$ for all $i,j\in S$ and all $i,j\in T$. We now define a \emph{$k$-fold Sidon set} to be a set $A\subseteq\mathbb{Z}_N$ such that for any $c_1,c_2,c_3,c_4\in [-k,k]$ with $c_1+c_2+c_3+c_4=0$, equation \eqref{eq:kfoldSidonset} has only trivial solutions in $A$. In the special case of $k=1$, a $1$-fold Sidon set coincides with the usual definition of a \emph{Sidon set}, which is also a $B_2[N;1]$ set. \begin{theorem}\label{thm:con-kfoldSidonset} Let $A=\set{a_1,a_2,\dots,a_n}\subseteq\mathbb{Z}_n$ be a $k$-fold Sidon set. Assume that $0\leq k_-\leq k_+\leq k$ and $k_++k_-\geq 1$. In the group $G \triangleq \mathbb{Z}_{2(k_++k_-)+1} \times \mathbb{Z}_N$, construct a set \[S\triangleq \set*{ (1,x) ; x \in A}.\] Then $G \ge [-k_-,k_+]^* \diamond_2 S$. \end{theorem} \begin{IEEEproof} Suppose to the contrary that $G$ is not partially $2$-split by $S$. Then there are $x_1,x_2,x_3,x_4 \in A$ and $c_1,c_2,c_3,c_4 \in [-k_-,k_+]$ such that \[ c_1+c_2\equiv c_3+c_4 \pmod{2(k_++k_-)+1},\] and \begin{equation}\label{eq:con-kfoldSidonset} c_1 x_1+c_2 x_2\equiv c_3 x_3 + c_4 x_4 \pmod{N}, \end{equation} where all the following hold: \begin{enumerate} \item $x_1\neq x_2$ \item $x_3\neq x_4$ \item $x_1\neq x_3$ if $c_1=c_3$ and $c_2=c_4=0$ \item $x_2\neq x_4$ if $c_2=c_4$ and $c_1=c_3=0$ \item $(x_1,x_2)\neq (x_3,x_4)$ if $(c_1,c_2)=(c_3,c_4)$. \item $(x_1,x_2)\neq (x_4,x_3)$ if $(c_1,c_2)=(c_4,c_3)$. \end{enumerate} Since $-(k_++k_-) \leq a+b,c+d \leq k_++k_-$, it follows that $c_1+c_2=c_3+c_4$, or equivalently, $c_1+c_2-c_3-c_4=0$. To avoid contradicting the assumption that $A$ is a $k$-fold Sidon set, $(x_1,x_2,x_3,x_4)$ should be a trivial solution of \eqref{eq:con-kfoldSidonset}. We consider the following cases: \textbf{Case 1.} If none of $c_1,c_2,c_3,c_4$ are $0$, we consider the possible partitions of $\set{1,2,3,4}$. Since $x_1\neq x_2$ and $x_3\neq x_4$, $1$ and $2$, respectively $3$ and $4$, cannot be placed in the same set in the partition. Then the possible partitions are $\set{\set{1,3}, \set{2,4}}$, and $\set{\set{1,4}, \set{2,3}}$. If the partition is $\set{\set{1,3}, \set{2,4}}$, then $c_1-c_3=0$ and $c_2-c_4=0$. It follows that $x_1=x_3$ and $x_2=x_4$, which contradicts that $(x_1,x_2)\neq (x_3,x_4)$ when $(c_1,c_2)=(c_3,c_4)$. The case of $\set{\set{1,4},\set{2,3}}$ is proved symmetrically. \textbf{Case 2.} If there is exactly one element of $c_1,c_2,c_3,c_4$ that is equal to $0$, say w.l.o.g., $c_1=0$, then the only possible partition of $\set{2,3,4}$ is $\set{ \emptyset, \set{2,3,4}}$, which contradicts $x_3\neq x_4$. \textbf{Case 3.} If there are exactly two elements of $c_1,c_2,c_3,c_4$ that are equal to $0$, w.l.o.g., we may consider the two cases where $c_1=c_2=0$, and $c_1=c_3=0$. If $c_1=c_2=0$, the only possible partition of $\set{3,4}$ is $\set{ \emptyset, \set{3,4} }$, which contradicts $x_3\neq x_4$. If $c_1=c_3=0$, the only possible partition of $\set{2,4}$ is $\set{ \emptyset, \set{2,4} }$. Then we have $x_2=x_4$. Note that $c_1=c_3=0$ and $c_2=c_4$, and we get a contradiction. \textbf{Case 4.} If there are exactly three elements of $c_1,c_2,c_3,c_4$ that are equal to $0$, assume w.l.o.g., that $c_2=c_3=c_4=0$ and $c_1\neq 0$. Then we need to partition $\set{1}$. However, such a partition does not exist as $c_1\neq 0$. Thus, there is no solution to (\refeq{eq:con-kfoldSidonset}). \end{IEEEproof} When $k=2$, a family of $2$-fold Sidon sets is constructed in \cite{Lazebnik2003} by removing some elements from Singer difference sets with multiplier $2$. \begin{theorem}[Theorem~2.5 in \cite{Lazebnik2003}]\label{thm:2foldSidonset} Let $m$ be a positive integer and $N=2^{2^{m+1}}+2^{2^m}+1$. Then there exists a $2$-fold Sidon set $A\subseteq \mathbb{Z}_N$ such that \[\abs{A} \geq \frac{1}{2} N^{1/2}-3. \] \end{theorem} We immediately get the following corollary. \begin{corollary} \label{cor:t2sidon} Let $0\leq k_-\leq k_+\leq 2$ be integers with $k_++k_-\geq 1$. There is an infinite family of integers $n$ such that $\mathbb{Z}^n$ can be lattice packed by $\mathcal{B}(n,2,k_+,k_-)$ with density \[\delta=\frac{\binom{n}{2}(k_++k_-)^2 + n(k_++k_-)+1 }{(2(k_++k_-)+1)(2n+6)^2}=\frac{1}{8(2(k_++k_-)+1)}+o(1).\] \end{corollary} \begin{IEEEproof} Simply combine Theorem~\ref{thm:con-kfoldSidonset} and Theorem~\ref{thm:2foldSidonset}. \end{IEEEproof} Now, we present a construction for $t=2$ and $0\leq k_-\leq k_+\leq 3$, which combines Behrend's method \cite{Behrend46} and Ruzsa's method \cite{Ruzsa93} to forbid some specified linear equations. \begin{theorem}\label{thm:con-t=2} Let $0\leq k_-\leq k_+\leq 3$ be integers such that $k_++k_-\geq 1$. Set $\alpha \triangleq \max\set{2k_+^2,3}$. Let $D \geq 2$ and $K\geq 1$ be integers, and $p\equiv\pm 5\pmod{12}$ be a prime such that $(\alpha K+1)^D \leq p$. For each $0\leq m < DK^2$, define \[C_m\triangleq \set*{ x= \sum_{i=0}^{D-1} x_i (\alpha K+1)^i ; 0\leq x_i\leq K, \sum_{i=0}^{D-1}x_i^2=m }. \] Let $G \triangleq \mathbb{Z}_{3k_++2k_-+1} \times \mathbb{Z}_p\times \mathbb{Z}_p$, and construct a subset \[ S_m\triangleq \set*{ s_x ; x \in C_m }, \textup{ where } s_x \triangleq (1,x,x^2) \in G.\] If $k_+\leq 3$, then $G\geq M\diamond_2 S_m$ for every $0\leq m < DK^2$, and where $M\triangleq [-k_-,k_+]^*$. \end{theorem} \begin{IEEEproof} Suppose to the contrary that $G$ is not partially $2$-split by $S_m$. We consider the following cases. \textbf{Case 1.} $a s_x ={\mathbf{0}}$ for some $a \in M$ and $x\in C_m$. The first coordinate of this equation is $a\equiv 0 \pmod{3k_++2k_-+1}$. Since $-k_-\leq a \leq k_+$, necessarily $a=0$, a contradiction. \textbf{Case 2.} $a s_x =b s_y$ for some $a,b \in M$, $x,y \in C_m$ and $(a,x)\neq (b,y)$. Similarly to Case 1, the first coordinate implies that $a=b$. From the second coordinate, we have $a x \equiv b y \pmod{p}$, and so, $x\equiv y \pmod{p}$. It follows that $x =y$ as $0\leq x,y <p$, which contradicts $(a,x)\neq (b,y)$. \textbf{Case 3.} $a s_x + b s_y = {\mathbf{0}}$ for some $a,b \in M$, $x,y \in C_m$ and $x\neq y$. The first coordinate implies $a+b=0$ as $-2k_- \leq a+b\leq 2k_+$. W.l.o.g., we assume $a>0$. Then $a s_x= (-b) s_y$, where $0< a, -b \leq k_-$, which was ruled out in Case 2. \textbf{Case 4.} $a s_x + b s_y = c s_u$ for some $a,b,c \in M$ and $x,y,u\in C_m$ with $x\not =y$. From the first coordinate, we have $a+b=c$ as $-2k_- \leq a+b\leq 2k_+$ and $-k_-\leq c \leq k_+$. If $x=u$ or $y=u$, then $b s_y=bs_u$ or $a s_x=as_u$, respectively, both of which were ruled out in Case 2. Thus, in the following, we assume $x,y,u$ are pairwise distinct. Furthermore, using the condition $a+b=c$ and rearranging the terms, we may assume that $a,b,c>0$. From the second coordinate, we have that $a x + by \equiv c u \pmod{p}$, or equivalently, \[ \sum_{i=0}^{D-1} (ax_i+b y_i) (\alpha K+1)^i \equiv \sum_{i=0}^{D-1} c u_i (\alpha K+1)^i \pmod{p}.\] Note that $0\leq ax_i+b y_i, cu_i\leq 2k_+ K <\alpha K+1$ and $p \geq (\alpha K+1)^D$. It follows that $ax_i+b y_i=cu_i$ for all $0\leq i\leq D-1$. Thus, the three distinct points $(x_0,x_1,\ldots, x_{D-1})$, $(y_0,y_1,\ldots, y_{D-1})$, and $(u_0,u_1,\ldots, u_{D-1})$, are collinear in $\mathbb{Z}^D$ where $D\geq 2$, which contradicts the fact that they are on the same sphere, i.e., $\sum_i x_i^2=\sum_i y_i^2=\sum_i u_i^2=m$. \textbf{Case 5.} $a s_x + b s_y = c s_u +d s_v$ for some $a,b,c,d \in M$, $x,y,u,v\in C_m$, $x\neq y$ and $u\neq v$, where $abcd$ is negative. By rearranging the terms, we may assume w.l.o.g. that \[a s_x + b s_y + c s_z = d s_u\] for some $0<a,b,c,d \leq k_+$ and $x,y,z,u\in C_m$ where $x,y,z,u$ are not all the same. Note that $0<a+b+c\leq 3k_+$ and $0< d \leq k_+$. From the first coordinate of the equation above we have $a+b+c=d$. The second coordinate of the equation implies that \[ \sum_{i=0}^{D-1} (ax_i+b y_i+cz_i) (\alpha K+1)^i \equiv \sum_{i=0}^{D-1} d u_i (\alpha K+1)^i \pmod{p}.\] Since $0\leq ax_i+b y_i+ cz_i\leq 3 k_+ K < \alpha K+1$ and $0\leq du_i\leq k_+ K <\alpha K+1$, necessarily $ax_i+by_i+cz_i=d u_i$ for all $0\leq i \leq D-1$. Then \begin{align*} ax_i^2+by_i^2+cz_i^2 & = a (x_i-u_i+u_i)^2 + b (y_i-u_i+u_i)^2 +c (z_i-u_i+u_i)^2 \\ &=a (x_i-u_i)^2 +2a(x_i-u_i)u_i+au_i^2 +b (y_i-u_i)^2 +2b(y_i-u_i)u_i+bu_i^2 \\ &\ \ \ +c (z_i-u_i)^2 +2c(z_i-u_i)u_i+cu_i^2 \\ & = a (x_i-u_i)^2 +b (y_i-u_i)^2 +c (z_i-u_i)^2+2(ax_i+by_i+cz_i)u_i \\ & \ \ \ -(a+b+c) u_i^2 \\ & = a (x_i-u_i)^2 +b (y_i-u_i)^2 +c (z_i-u_i)^2 +(a+b+c) u_i^2. \end{align*} Note that $x,y,z,u\in C_m$, i.e., $\sum_{i=0}^{D-1}x_i^2=\sum_{i=0}^{D-1}y_i^2=\sum_{i=0}^{D-1}z_i^2=\sum_{i=0}^{D-1}u_i^2$. It follows that \begin{align*} (a+b+c) \sum_{i=0}^{D-1}u_i^2 &= a \sum_{i=0}^{D-1}x_i^2+b \sum_{i=0}^{D-1}y_i^2+c \sum_{i=0}^{D-1}z_i^2 \\ & = a \sum_{i=0}^{D-1}(x_i-u_i)^2 +b \sum_{i=0}^{D-1} (y_i-u_i)^2 +c \sum_{i=0}^{D-1}(z_i-u_i)^2 +(a+b+c) \sum_{i=0}^{D-1}u_i^2, \end{align*} which in turn implies that $x_i=y_i=z_i=u_i$ for all $0\leq i\leq D-1$, and so, $x=y=z=u$, a contradiction. \textbf{Case 6.} $a s_x + b s_y = c s_u +d s_v$ for some $a,b,c,d \in M$, $x,y,u,v\in C_m$, $x\neq y$ and $u \neq v$, where $abcd$ is positive. Note that from the first coordinate, we have $a+b=c+d$. By rearranging the terms, we may assume that \[a s_x + b s_y = c s_u + d s_v\] for some $0<a,b,c,d \leq k_+$, $a+b=c+d$, $x,y,u,v\in C_m$ and $x,y,u,v$ are not all the same. The second coordinate and the third coordinate of the equation above imply that \begin{equation}\label{eq:1order} ax+by\equiv cu+dv \pmod{p} \end{equation} and \begin{equation}\label{eq:2order} ax^2+by^2\equiv cu^2+dv^2 \pmod{p}. \end{equation} We multiply \eqref{eq:2order} by $a+b$, and then subtract the square of \eqref{eq:1order}. Noting that $a+b=c+d$, the result is \begin{equation}\label{eq:dif} ab(x-y)^2\equiv cd (u-v)^2 \pmod{p}. \end{equation} If $x= y$, using \eqref{eq:1order} and \eqref{eq:dif}, it is easy to see that $x,y,u,v$ are all the same, a contradiction; if $x=u$, then \eqref{eq:1order} was ruled out in Case 4. Thus, we may assume that $x,y,u,v$ are pairwise distinct, and so, \begin{equation}\label{eq:square} abcd\equiv c^2d^2(u-v)^2/ (x-y)^2\pmod{p}, \end{equation} i.e., $abcd$ should be a quadratic residue modulo $p$. Check all the possible $abcd$, where $0<a,b,c,d\leq k_+\leq 3$ and $a+b=c+d$. We have $abcd\in\set{1,2^2,3^2,4^2,6^2,9^2,3\cdot 2^2}$. Since $p\equiv \pm 5\pmod{12}$, $3$ is not a quadratic residue modulo $p$, and so, $abcd\in\set{1,2^2,3^2,4^2,6^2,9^2}$. In all of these cases, $abcd$ is a square in $\mathbb{Z}$. Denote $t=\sqrt{abcd}$. Since $0<a,b,c,d\leq k_+$, we have $0<t\leq k_+^2$. Substituting $abcd=t^2$ in \eqref{eq:square} yields \begin{equation}\label{eq:sqrt} \pm t(x-y)\equiv cd(u-v) \pmod{p}. \end{equation} Solving the system of equations \eqref{eq:1order} and \eqref{eq:sqrt}, we get \begin{equation*} (c^2+cd)u\equiv (\pm t +ac)x+(bc\mp t)y \pmod{p}. \end{equation*} Note that $a+b=c+d$. Hence, \begin{equation}\label{eq:sol} \sum_{i=0}^{D-1} (ac+bc)u_i (\alpha K+1)^i \equiv \sum_{i=0}^{D-1}( (\pm t +ac)x_i+(bc\mp t)y_i )(\alpha K+1)^i \pmod{p}. \end{equation} Since $(\pm t +ac)+(bc\mp t)=ac+bc>0$, at least one of $\pm t +ac$ and $bc\mp t$ is positive. We proceed in the following subcases. \begin{enumerate} \item If $\pm t +ac=0$, we have $t=ac$, and so, \[\sum_{i=0}^{D-1} (ac+bc)u_i (\alpha K+1)^i \equiv \sum_{i=0}^{D-1} (bc+ac)y_i (\alpha K+1)^i \pmod{p},\] which in turn implies $u=y$, a contradiction. Similarly, if $bc\mp t=0$, we can get $u=x$, again, a contradiction. \item If both $\pm t +ac$ and $bc\mp t$ are positive, then $0\leq (\pm t +ac)x_i+(bc\mp t)y_i \leq (ac+bc) K \leq 2k_+^2 K\leq \alpha K$. On the other hand, $0\leq (ac+bc)u_i \leq 2k_+^2 K \leq \alpha K$. Thus it follows from \eqref{eq:sol} that \[(ac+bc)u_i= (\pm t +ac)x_i+(bc\mp t)y_i \textup{ for all } 0\leq i \leq D-1.\] That is, the three distinct points $(x_0,x_1,\ldots, x_{D-1}), (y_0,y_1,\ldots, y_{D-1})$ and $(u_0,u_1,\ldots, u_{D-1})$ of $\mathbb{F}_p^D$ are collinear, which contradicts the fact that they are on the same sphere. \item If $\pm t +ac$ is negative, then $bc\mp t$ is positive. Rearranging the terms in \eqref{eq:sol}, we have that \[\sum_{i=0}^{D-1} ((ac+bc)u_i-(\pm t +ac)x_i) (\alpha K+1)^i \equiv \sum_{i=0}^{D-1}(bc\mp t)y_i (\alpha K+1)^i \pmod{p}.\] Since \begin{align*} 0 & \leq (ac+bc)u_i-(\pm t +ac)x_i = (ac+bc)u_i+(\mp t -ac)x_i \\ & \leq (ac+bc)K+(\mp t -ac)K = (bc \mp t) K \leq 2k_+^2 K \leq \alpha K, \end{align*} then \[(ac+bc)u_i- (\pm t +ac)x_i =(bc\mp t)y_i \textup{ for all } 0\leq i \leq D-1.\] Again we get three distinct points on the same sphere which are collinear, a contradiction. \item If $bc\mp t$ is negative, then $\pm t +ac$ is positive. Using the same argument as above, we can get the contradiction. \end{enumerate} Thus we complete our proof. \end{IEEEproof} \begin{remark} In the proof above, the product $abcd$ is required to be either a square of $\mathbb{Z}$ or a non quadratic residue modulo $p$. This requirement comes from Ruzsa's method, in the proof of Theorem of 7.3 of \cite{Ruzsa93}. However, for $k_+\geq 4$, this requirement cannot be satisfied: we may choose $(a,b,c,d)$ to be $(1,4,2,3), (1,3,2,2)$ or $(2,4,3,3)$, the products $24,12$ and $72$ are not squares and they cannot simultaneously be non quadratic residues modulo $p$ for any prime $p$ as, using the Legendre symbol, \[ \parenv*{\frac{6}{p}}=\parenv*{\frac{2}{p}}\parenv*{\frac{3}{p}}.\] \end{remark} \begin{corollary} \label{cor:behruz} Let $t=2$ and $0\leq k_- \leq k_+ \leq 3$, $k_++k_-\geq 1$. There is an infinite family of $n$ such that $\mathbb{Z}^n$ can be lattice packed by ${\mathcal B}(n,t,\kp,\km)$ with density $\delta=\Omega(c^{-\sqrt{\ln n}})$ for some real number $c>0$. \end{corollary} \begin{IEEEproof} Let $p\equiv\pm 5\pmod{12}$ be a sufficiently large prime. Set $D\triangleq \floor{\sqrt{\ln p}}$ and $K\triangleq \floor{(e^D-1)/\alpha}$. Then we have $(\alpha K+1)^D \leq p$. Consider the group $G$ and the splitting sets $S_m$, $m\in [0,DK^2-1]$, in Theorem~\ref{thm:con-t=2}. According to the pigeonhole principle, there exists one set $S_m$ of size $\geq \frac{(K+1)^D}{DK^2}$. Then \begin{align*} n & \geq \frac{(K+1)^D}{DK^2} = \frac{\parenv*{\floor*{\frac{e^D-1}{\alpha}}+1}^D }{D\floor*{\frac{e^D-1}{\alpha}}^2} \geq \frac{\parenv*{\frac{e^D-\alpha}{\alpha}+1}^D }{D\parenv*{\frac{e^D-1}{\alpha}}^2} \geq \frac{\alpha^2 e^{D^2}}{\alpha^{D}D e^{2D} } \\ & \geq \frac{\alpha^2 e^{ \floor*{\sqrt{\ln p}}^2}}{\alpha^{\sqrt{\ln p}} \sqrt{\ln p} e^{2\sqrt{\ln p}} } \geq \frac{\alpha^2 e^{ \parenv*{\sqrt{\ln p}-1}^2}}{\alpha^{\sqrt{\ln p}} \sqrt{\ln p} e^{2\sqrt{\ln p}} } = \frac{e\alpha^2 p}{\alpha^{\sqrt{\ln p}} \sqrt{\ln p} e^{4\sqrt{\ln p}} }\\ & \geq \frac{p}{c_1 ^{ \sqrt{\ln p}} }, \end{align*} for some real number $c_1>0$. Taking logarithm of both side, we have $\ln n \geq \ln p -\sqrt{\ln p} \ln c_1$, or equivalently, \[\ln p - \ln c_1 \sqrt{\ln p} - \ln n \leq 0.\] Solving for $\sqrt{\ln p}$, we get \[\sqrt{\ln p} \leq \frac{\ln c_1 +\sqrt{ (\ln c_1)^2+4\ln n } }{2},\] and so \[ \ln p \leq \frac{4\ln n +2(\ln c_1)^2 +2 \ln c_1 \sqrt{ (\ln c_1)^2+4\ln n } }{4}\leq \ln n +c_2 \sqrt{\ln n},\] for some real number $c_2>0$. It follows that \[ n\geq \frac{p}{e^{c_2\sqrt{\ln n}}},\] and \[\delta \geq \frac{ \binom{n}{2} (k_++k_-)^2+n(k_++k_-)+1 }{\abs{G}} = \Omega(c^{-\sqrt{\ln n}}),\] for some real number $c>0$. \end{IEEEproof} \section{Generalized Packings} \label{sec:genpack} It is a common practice in coding theory to also consider list decoding instead of unique decoding. In such scenarios, the channel output is decoded to produce a list of up to $\lambda$ possible distinct codewords, where the channel output is within the error balls centered at each of these codewords. In this section, we therefore generalize the concept of packing to work in conjunction with list decoding. The trade-off we present here is that at the price of a constant-sized list, $\lambda$, we can find lattice packings of ${\mathcal B}(n,t,\kp,\km)$ with density almost constant, $\Omega(n^{-\epsilon})$, for any $\epsilon>0$. The proof method, however, is non-constructive, and relies on the probabilistic method. Given a shape $\mathcal{B} \subseteq \mathbb{Z}^n$ and a lattice $\Lambda \subseteq \mathbb{Z}^n$, we say $\mathcal{B}$ \emph{$\lambda$-packs $\mathbb{Z}^n$ by $\Lambda$} if for every element $\mathbf{z}\in\mathbb{Z}^n$, there are at most $\lambda$ distinct elements $\mathbf{v}_i\in\Lambda$ such that $\mathbf{z}\in\mathbf{v}_i+\mathcal{B}$. Obviously, if $\lambda=1$, this definition coincides with the packing defined in Section~\ref{sec:prelim}. Let $G$ be a finite Abelian group, $M\triangleq [-k_-,k_+]^*$, and $S\subseteq G$. If each element of $G$ can be written in at most $\lambda$ ways as a linear combination of $t$ elements of $S$ with coefficients from $M \cup \set{0}$, then we say $G \overset{\lambda}{\geq} M \diamond_t S$. The following result is an analogue of Theorem~\ref{th:lattotile}, which relates lattice packings to Abelian groups. The proof is exactly analogous, and we omit it. \begin{theorem} Let $G$ be a finite Abelian group and $M\triangleq [-k_-,k_+]^*$. Suppose that there is a subset $S=\set*{s_1,s_2,\ldots,s_n}\subseteq G$ such that $G \overset{\lambda}{\geq} M \diamond_t S$. Define $\phi:\mathbb{Z}^n\to G$ as $\phi(\mathbf{x})\triangleq\mathbf{x}\cdot(s_1,\dots,s_n)$ and let $\Lambda\triangleq\ker\phi$ be a lattice. Then $\mathcal{B}(n,t,k_+,k_-)$ $\lambda$-lattice-packs $\mathbb{Z}^n$ by $\Lambda$. \end{theorem} We use the probabilistic approach detailed in~\cite{vu:2002}, and follow some of the notation there. Let $x_1,x_2,\ldots, x_N$ be independent $\set{0,1}$ random variables. Let $Y=Y(x_1,x_2,\ldots,x_N)$ be a polynomial of $x_1,x_2,\ldots, x_N$. $Y$ is \emph{normal} if its coefficients are between $0$ and $1$. A polynomial $Y$ is \emph{simplified} if every monomial is a product of different variables. Since we are dealing with $\set{0,1}$ random variables, every $Y$ has a unique simplification. Given a set $A$, let $\partial_A(Y)$ denote the partial derivative of $Y$ with respect to $A$, and let $\partial_A^*$ be the polynomial obtained from the partial derivative $\partial_A (Y)$ by subtracting its constant coefficient. Define $\mathbb{E}_j^*(Y)\triangleq \max_{\abs{A}\geq j} \mathbb{E}(\partial_A^* Y)$. \begin{theorem}\cite[Corollary~4.9]{vu:2002}\label{thm:vucon} For any positive constants $\alpha$ and $\beta$ and a positive integer $d$, there is a positive constant $C=C(d,\alpha,\beta)$ such that if $Y$ is a simplified normal polynomial of degree at most $d$ and $\mathbb{E}_0^*(Y)\leq N^{-\alpha}$, then $\Pr(Y\geq C) \leq N^{-\beta}$. \end{theorem} We now use Theorem~\ref{thm:vucon} to show the existence of generalized lattice packings with the desired parameters. \begin{theorem} \label{th:prob} Let $0\leq k_-\leqk_+$ with $k_++k_-\geq 1$, and $t>0$, be integers. Let $N$ be a sufficiently large integer such that $\gcd(N,k_+!)=1$, and fix $G\triangleq\mathbb{Z}_N$. Then for any $0<\epsilon<1/t$, there is a number $\lambda$ which only depends on $t$ and $\epsilon$, and a subset $S=\set{s_1,s_2,\dots, s_n}\subseteq G$ with $\frac{1}{2}N^{1/t-\epsilon}\leq n \leq \frac{3}{2}N^{1/t-\epsilon}$, such that $G \overset{\lambda}{\geq} M \diamond_t S$, where $M\triangleq[-k_-,k_+]^*$. \end{theorem} \begin{IEEEproof} Set $\alpha=\epsilon t$, $\beta=2$, and $d=t$. Denote \[p\triangleq N^{\frac{1}{t}-1-\epsilon}.\] We construct $S$ randomly. For each $0\leq i < N$, let the event $i\in S$ be independent with probability $p$. Let $x_i$ be the indicator variable of the event $i \in S$. Then $\abs{S}=\sum_{i=0}^{N-1}x_i$, and \[\mathbb{E}(\abs{S})=Np=N^{\frac{1}{t}-\epsilon}.\] Using Chernoff's inequality, one can show that \begin{equation}\label{eq:sizeexpc} \Pr\parenv*{\frac{1}{2}\mathbb{E}(\abs{S})\leq \abs{S}\leq \frac{3}{2}\mathbb{E}(\abs{S})}\geq 1- 2e^{-\mathbb{E}(\abs{S})/16}. \end{equation} For every $g\in G$ and $0 \leq i_1 < i_1 <\cdots <i_\ell < N$, denote \[c(g;i_1,i_2,\ldots, i_\ell)\triangleq\abs{ \set*{(a_1,a_2,\ldots,a_\ell)\in M^\ell; g=a_1i_1+a_2i_2+\cdots a_\ell i_\ell} },\] where addition and multiplication are in $G=\mathbb{Z}_N$. Consider the following random variables (which are polynomials in the indicator random variables $x_0,\dots,x_{N-1}$), \[Y_g \triangleq \parenv*{ \sum_{0 \leq i_1 <\cdots <i_t < N } {c(g;i_1,i_2,\ldots,i_t)} x_{i_1}x_{i_2}\cdots x_{i_t}}/(k_++k_-)^t,\] and \[Z_g \triangleq \parenv*{\sum_{\substack{1\leq \ell \leq t-1 \\ 0 \leq i_1 <\cdots <i_\ell < N }} {c(g;i_1,i_2,\ldots,i_{\ell})} x_{i_1}x_{i_2}\cdots x_{i_\ell}}/(k_++k_-)^{t-1}.\] Both of them are positive, and as polynomials, they are simplified, and normal. To show that $G \overset{\lambda}{\geq} M \diamond_t S$, it suffices to show that $(k_++k_-)^tY_g+(k_++k_-)^{t-1}Z_g \leq \lambda-1$ for every $g\in G$. We first look at $Y_g$. Since $\gcd(N,k_+!)=1$, if we fix $a_1,a_2,\ldots,a_t\in M^t$ and $i_1,i_2,\ldots, i_{t-1}$, then there is a unique $i_t \in [0,N-1]$ such that $a_1i_1+a_2i_2+\cdots+a_ti_t=g$. Hence, \[\mathbb{E}(Y_g) \leq ((k_++k_-)^t N^{t-1} p^{t})/(k_++k_-)^t= N^{-\epsilon t} =N^{-\alpha}.\] For the partial derivative $\partial_A (Y_g)$ with $A=\set{j_1,j_2,\ldots, j_k} \subseteq [0,N-1]$ and $k\leq t-1$, \[ \partial_A (Y_g)= \sum_{c_1,c_2,\ldots, c_k \in M}\parenv*{ \sum_{0\leq i_1<i_2 <\cdots i_{t-k}<N} {c(g-c_1j_1-\cdots-c_kj_k;i_1,i_2,\ldots,i_{t-k})} x_{i_1}x_{i_2}\cdots x_{i_{t-k}}}/(k_++k_-)^t, \] hence, \begin{align*} \mathbb{E}(\partial_A (Y_g)) & \leq (k_++k_-)^k((k_++k_-)^{t-k}N^{t-k-1}p^{t-k}/(k_++k_-)^t) \\ & = N^{-\epsilon t +k\epsilon -k/t} < N^{-\alpha}. \end{align*} Applying Theorem~\ref{thm:vucon}, there is a number $C$, depending on $t$ and $\epsilon$, such that \begin{equation}\label{eq:Yupbound} \Pr(Y_g \geq C) \leq N^{-2}. \end{equation} As for $Z_g$, a similar computation to the above shows that \[\mathbb{E}(\partial_A^*(Z_g))= O(N^{t-1-k-1} p^{t-1-k}).\] Since \begin{align*} N^{t-1-k-1} p^{t-1-k}= N^{-\epsilon t-(\frac{1}{t}-\epsilon)(k+1)} < N^{-\alpha}, \end{align*} we have $\mathbb{E}(\partial_A^*(Z_g)) < N^{-\alpha}$ when $N$ is sufficiently large. Applying Theorem~\ref{thm:vucon} again, there is a $C'$ such that \begin{equation}\label{eq:Zupbound} \Pr(Z_g\geq C') \leq N^{-2}. \end{equation} Denote $\lambda = C(k_++k_-)^t +C'(k_++k_-)^{t-1}+1$. Then \eqref{eq:Yupbound} and \eqref{eq:Zupbound} imply, via a union bound, that \[\Pr(\textup{there exists } g \in G \textup{ such that } (k_++k_-)^tY_g+(k_++k_-)^{t-1}Z_g > \lambda-1) \leq 2N^{-1}. \] From this, together with \eqref{eq:sizeexpc}, we can see that the random set $S$ satisfies the conditions with probability at least $1-2N^{-1}-2e^{-\mathbb{E}(\abs{S})/16}$, which is positive for large enough $N$. Thus, such a set exists. \end{IEEEproof} \begin{corollary} \label{cor:genpack} Let $0\leq k_-\leqk_+$ with $k_++k_-\geq 1$, and $t>0$, be integers. Then for any real number $\epsilon>0$, there is an integer $\lambda$ and infinitely many values of $n$ such that $\mathbb{Z}^n$ can be $\lambda$-lattice-packed by ${\mathcal B}(n,t,\kp,\km)$ with density $\delta=\Omega(n^{-\epsilon})$. \end{corollary} \begin{IEEEproof} Fix $\epsilon'\triangleq\frac{\epsilon}{\epsilon t+ t^2}$, and observe that $\epsilon'<1/t$. Use Theorem~\ref{th:prob} with $\epsilon'$, noting that $N=\Theta(n^{\epsilon+t})$, to obtain a lattice $\lambda$-packing of ${\mathcal B}(n,t,\kp,\km)$ with density \[ \delta \geq \frac{\abs{{\mathcal B}(n,t,\kp,\km)}}{\abs{G}}=\frac{\sum_{i=0}^t \binom{n}{i}(k_++k_-)^i}{N}=\Omega(n^{-\epsilon}).\] \end{IEEEproof} As a final comment on the matter, we observe that a tedious calculation shows that in the above corollary $\lambda=O(\epsilon^{-t})$ -- a calculation which we omit. \section{Constructions of Lattice Coverings} \label{sec:covering} We switch gears in this section, and focus on covering instead of packing. We first argue that using known techniques from the theory of covering codes in the Hamming metric, we can show the existence of non-lattice coverings of $\mathbb{Z}^n$ by ${\mathcal B}(n,t,\kp,\km)$. However, these have a high density of $\Omega(n)$. We then provide a product construction to obtain a lattice covering by ${\mathcal B}(n,t,\kp,\km)$ with density $O(1)$. Fixing an integer $\ell\in\mathbb{N}$, we use the same argument as the one given in \cite[Section~12.1]{CohHonLitLob97} to construct a covering code $C\subseteq\mathbb{Z}_\ell^n$, of size \[ \abs*{C}=\ceil*{\frac{n\ell^n \ln \ell}{\abs*{{\mathcal B}(n,t,\kp,\km)}}}.\] We can then translate this covering of $\mathbb{Z}_\ell^n$ by ${\mathcal B}(n,t,\kp,\km)$ to a covering of $\mathbb{Z}^n$ by using the same idea as Theorem~\ref{th:linearcode}, and defining $C'\triangleq\set*{ \mathbf{x}\in\mathbb{Z}^n ; (\mathbf{x}\bmod \ell)\in C}$. However, the density of the resulting covering is \[ \delta= \frac{\abs*{C}\cdot\abs*{{\mathcal B}(n,t,\kp,\km)}}{\ell^n} = \Omega(n).\] We therefore proceed to consider more efficient coverings using the product construction whose details follow. \begin{theorem} \label{con-reccovering} Suppose that there exist a finite Abelian group $G$ and a subset $S \subseteq G$ such that $G \leq M \diamond_1 S$. Let $t>0$ be an integer, and denote \[S^{(t)}\triangleq\set*{(s,0,0,\dots, 0) ; s \in S} \cup \set*{(0,s,0,\dots,0) ; s\in S} \cup \cdots \cup\set*{(0,0,0,\dots,s) ; s \in S}.\] Then $G^{t}\leq M \diamond_t S^{(t)}$. \end{theorem} \begin{IEEEproof} For any element $g=(g_1,g_2,\ldots,g_t)\in G^{t}$, since $G\leq M \diamond_1 S$, for each $1\leq i \leq t$, there are $s_i\in S$ and $c_i \in M\cup \set{0}$ such that $g_i=c_i\cdot s_i$. Hence, \[g=c_1(s_1,0,0,\ldots,0)+c_2(0,s_2,0,\ldots,0)+\cdots+c_t(0,0,0,\ldots,s_t).\] That is, $g$ can be written as a linear combination of $t$ elements of $S$ with coefficients from $M \cup \set{0}$, and so, $G^{t}\leq M \diamond_t S^{(t)}$. \end{IEEEproof} We can now construct a lattice covering, using the previous theorem. \begin{corollary} \label{cor:cover} Let $\overline{\psi}(x)$ be the largest prime not larger than $x$, and denote $p\triangleq\overline{\psi}(k_++k_-+1)$. Let $0\leq k_-\leq k_+$, with $k_++k_-\geq 1$, and $t>0$, be integers. Define $M\triangleq [-k_-,k_+]^*$. Then for any integer $m>0$, there exists $S\subseteq (\mathbb{Z}_{p^m})^t$, $\abs{S}=t\cdot\frac{p^m-1}{p-1}$, such that $(\mathbb{Z}_{p^m})^t\leq M \diamond_t S$, and thereby, a lattice covering of $\mathbb{Z}^n$, $n=\abs{S}$, with density \[\delta = \frac{ \sum_{i=0}^{t} \binom{n}{i} (k_++k_-)^i }{ ( n(p-1)/t+1 )^t }=\frac{(t(k_++k_-))^t}{t!(p-1)^t}+o(1).\] \end{corollary} \begin{IEEEproof} According to \cite[Construction 1]{Sch12}, there is a subset $A\subseteq \mathbb{Z}_{p^m}$ of size $\frac{p^m-1}{p-1}$ such that $\mathbb{Z}_{p^m}=[-k_-,p-1-k_-]^*\diamond_1 A$. We may apply Theorem~\ref{con-reccovering} to obtain a subset $S=A^{(t)}\subseteq (\mathbb{Z}_{p^m})^t$ of size $t\cdot\frac{p^m-1}{p-1}$ such that $(\mathbb{Z}_{p^m})^t\leq M\diamond_t S$. The calculation of the density of the resulting lattice covering is straightforward. \end{IEEEproof} \section{Conclusion} \label{sec:conclusion} Motivated by coding for integer vectors with limited-magnitude errors, we provided several constructions of packings of $\mathbb{Z}^n$ by ${\mathcal B}(n,t,\kp,\km)$ for various parameters. These are summarized in Table~\ref{tab:summary}. While the parameter ranges of the constructions sometimes overlap, and perhaps result in equal or inferior asymptotic density, having more constructions allows for more choices for fixed values of the parameters. One main goal was to construct lattice packings, analogous to linear codes, as these are generally easier to analyze, encode, and decode. Thus, except for one case, all constructions we provide lattices. The main tool in constructing these is the connection between lattice packings of ${\mathcal B}(n,t,\kp,\km)$ and $t$-splittings of Abelian groups. The other important goal was to have asymptotic packing density that is non-vanishing. This is achieved in many of the cases. We also discussed $\lambda$-packing, which allows for a small overlap between the translates of ${\mathcal B}(n,t,\kp,\km)$ centered at the lattice points. This is useful for list-decoding setting with a list size of $\lambda$. The result we obtain is non-constructive, and it provides a trade-off between the list size and the packing density. Finally, we also addressed the problem of lattice-covering of $\mathbb{Z}^n$ by ${\mathcal B}(n,t,\kp,\km)$, showing using the product construction, that there exist such coverings with asymptotic constant density. The results still leave numerous open questions, of which we mention but a few: \begin{enumerate} \item Constructions for packings of ${\mathcal B}(n,t,\kp,\km)$ with $t\geq 3$, $k_+\geq 2$, and non-vanishing asymptotic density are still unknown. \item Whether asymptotic density of $1$ is attainable for all parameters is still an open questions. Such lattice packings would be analogous to asymptotically perfect codes. \item In the asymptotic regime of $t=\Theta(n)$, all of the constructions in this paper produce packings with vanishing asymptotic rates. Such families of packings are analogous to good codes in the Hamming metric, and their existence and constructions would be most welcome. \item Efficient decoding algorithms are missing for most of the cases. In the asymptotic regime of constant $t$, $\abs{{\mathcal B}(n,t,\kp,\km)}=\Theta(n^t)$. Thus, we are looking for non-trivial decoding algorithms, whose run-time is $o(n^t)$. \item We would also like to find constructive versions of the non-constructive proofs for $\lambda$-packings, and covering lattices. \end{enumerate} \begin{table*} \caption{A summary of the results} \label{tab:summary} {\renewcommand{\arraystretch}{1.2} \begin{tabular}{cccccll} \hline\hline Type & $t$ & $k_+$ & $k_-$ & density & Location & Comment \\ \hline Packing & any & 1 & 0 & $\frac{1}{t!}+o(1)$ & Corollary~\ref{cor:lc} & via BCH codes \\ Packing & any & any & any & $\Theta(n^{t-\ceil{2t(1-{1}/p)}})$ & Corollary~\ref{cor:lc} & via BCH codes, $p\geq k_++k_-+1$ prime\\ Packing & any & 1 & 0 & $\frac{1}{t!}+o(1)$ & Corollary~\ref{cor:btsets} & via $B_t[N;1]$ sets \\ Packing & any & 1 & 1 & $\frac{2^t}{t!(2t+1)}+o(1)$ & Corollary~\ref{cor:kpm1} & via $B_t[N;1]$ sets \\ Packing & 2 & 1 & 0 & $1-o(1)$ & Corollary~\ref{cor:perparata} & via Preparata codes, non-lattice packing \\ Packing & 2 & 1 & 1 & $\frac{1}{2}+o(1)$ & Corollary~\ref{cor:quasiperfectlc} & via quasi-perfect linear codes\\ Packing & 2 & 2 & 0 & $\frac{1}{2}+o(1)$ & Corollary~\ref{cor:quasiperfectlc} & via quasi-perfect linear codes\\ Packing & 2 & $\leq 2$ & $\leq 2$ & $\frac{1}{8(2(k_++k_-)+1)}+o(1)$ & Corollary~\ref{cor:t2sidon} & via $2$-fold Sidon sets \\ Packing & 2 & $\leq 3$ & $\leq 3$ & $\Omega(c^{-\sqrt{\ln n}})$ & Corollary~\ref{cor:behruz} & via Behrend's and Ruzsa's methods \\ $\lambda$-Packing & any & any & any & $\Omega(n^{-\epsilon})$ & Corollary~\ref{cor:genpack} & $\lambda=O(\epsilon^{-t})$ \\ Covering & any & any & any & $\frac{(t(k_++k_-))^t}{t!(p-1)^t}+o(1)$ & Corollary~\ref{cor:cover} & $p\leq k_++k_-+1$ prime \\ \hline\hline \end{tabular} } \end{table*}
{'timestamp': '2020-06-01T02:11:08', 'yymm': '2005', 'arxiv_id': '2005.14519', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14519'}
arxiv
\section{Introduction} Today, algorithmic systems driven by large amounts of data are increasingly being used in all aspects of life. Often, such systems are being used to assist, or, even replace human decision-making. This increased dependence on algorithms has given rise to the field of algorithmic fairness, where the goal is to ensure that algorithms do not exhibit biases towards specific individuals, or groups of users (see e.g., \cite{fairness-study} for a survey). We also live in a connected world where networks, be it, social, communication, interaction, or cooperation networks, play a central role. However, surprisingly, fairness in networks has received less attention. Link analysis algorithms, such as Pagerank~\cite{pagerank}, take a graph as input and use the structure of the graph to determine the relative importance of its nodes. The output of the algorithms is a numerical weight for each node that reflects its importance. The weights are used to produce a ranking of the nodes, but also as input features in a variety of machine learning algorithms including classification~\cite{spam-classifier}, and search result ranking~\cite{pagerank}. Pagerank performs a random walk on the input graph, and weights the nodes according to the stationary probability distribution of this walk. At each step, the random walk restarts with probability $\gamma$, where the restart node is selected according to a``jump'' distribution vector $\mathbf{v}$. Since its introduction in the Google search engine, Pagerank has been the cornerstone algorithm in several applications (see, e.g., \cite{pagerank-survey}). Previous research on the fairness of centrality measures has considered only degrees and found biases that arise as a network evolves \cite{glass-ceiling,glass-ceiling-recommend}, or has studied general notions of fairness in graphs based on the premise that similar nodes should get similar outputs \cite{inform}. In this work, we focus on the fairness of the Pagerank algorithm. As in previous research, we view fairness as lack of discrimination against a protected group defined by the value of a sensitive attribute, such as, gender, or race \cite{fairness-study}. We operationalize this view by saying that a link analysis algorithm is \textit{$\phi$-fair}, if the fraction of the total weight allocated to the members of the protected group is $\phi$. The value of $\phi$ is a parameter that can be used to implement different fairness policies. For example, by setting $\phi$ equal to the ratio of the protected nodes in the graph, we ask that the protected nodes have a share in the weights proportional to their share in the population, a property also known as demographic parity \cite{fairness-awarness}. We also consider \emph{targeted} fairness, where we focus on a specific subset of nodes to which we want to allocate weights in a fair manner. We revisit Pagerank through the lens of our fairness definitions, and we consider the problem of defining families of Pagerank algorithms that are fair. We also define the \emph{utility loss} of a fair algorithm as the difference between its output and the output of the original Pagerank algorithm, and we pose the problem of achieving fairness while minimizing utility. We consider two approaches for achieving fairness. The first family of algorithms we consider is the \emph{fairness-sensitive} Pagerank family which exploits the jump vector $\mathbf{v}$. There has been a lot of work on modifying the jump vector to obtain variants of Pagerank biased towards a specific set of nodes. The topic-sensitive Pagerank algorithm \cite{topic-sensitive} is such an example, where the probability is assigned to nodes of a specific topic. In this paper, we take the novel approach of using the jump vector to achieve $\phi$-fairness. We determine the conditions under which this is feasible and formulate the problem of finding the jump vector that achieves $\phi$-fairness while minimizing utility loss as a convex optimization problem. Our second family of algorithms takes a microscopic view of fairness by looking at the behavior of each individual node in the graph. Implicitly, a link analysis algorithm assumes that links in the graph correspond to endorsements between the nodes. Therefore, we can view each node, as an agent that \emph{endorses} (or \emph{votes for}) the nodes that it links to. Pagerank defines a process that takes these individual actions of the nodes and transforms them into a global weighting of the nodes. We thus introduce, the \textit{locally fair PageRank algorithms}, where each individual node acts fairly by distributing its own pagerank to the protected and non-protected groups according to the fairness ratio $\phi$. Local fairness defines a dynamic process that can be viewed as a \textit{fair random walk}, where \emph{at each step} of the random walk (not only at convergence), the probability of being at a node of the protected group is $\phi$. In our first locally fair PageRank algorithm, termed the \textit{neighborhood locally fair} Pagerank algorithm, each node distributes its pagerank fairly among its immediate neighbors, allocating a fraction $\phi$ to the neighbors in the protected group, and $1-\phi$ to the neighbors in the non-protected group. The \textit{residual-based locally fair} Pagerank algorithms generalizes this idea. Consider a node $i$ that has less neighbors in the protected group than $\phi$. The node distributes an equal portion of its pagerank to each of its neighbors and a residual portion $\delta(i)$ to members in the protected group but not necessarily in its own neighborhood. The residual is allocated based on \textit{a residual redistribution policy}, which allows us to control the fairness policy. In this paper, we exploit a residual redistribution policy that minimizes the utility loss. We then define a stronger fairness requirement, termed universal personalized fairness, that asks that the derived personalized pageranks of all nodes are fair. We prove that the locally fair algorithms achieve also universal personalized fairness. Surprisingly, the locally fair algorithms are the \emph{only} family of algorithms with this property. Thus, we show that an algorithm is locally fair, if and only if, it is universally personalized fair. We use real and synthetic datasets to study the conditions under which {{Pagerank}} and personalized {{Pagerank}} are fair. We also evaluate both quantitatively and qualitatively the output of our fairness-aware algorithms. In summary, in this paper, we make the following contributions: \begin{itemize} \item We initiate a study of fairness for the {{Pagerank}} algorithm. \item We propose the fairness-sensitive Pagerank family that modifies the jump vector so as to achieve fairness, and the locally fair Pagerank family that guarantees that individually each node behaves in a fair manner. \item We prove that local fairness implies universal personalized fairness and also that this is the only family of algorithms with this property, establishing an equivalence between local fairness and universal personalized fairness. \item We perform experiments on several datasets to study the conditions under which Pagerank unfairness emerges and evaluate the utility loss for enforcing fairness. \end{itemize} The remainder of this paper is structured as follows. In Section \ref{sec:definitions}, we provide definitions of fairness and we formulate our problems. In Sections \ref{sec:fairness-sensitive} and \ref{sec:local-fair}, we introduce the fairness sensitive and the locally fair families of {{Pagerank}} algorithms. In Section \ref{sec:universal}, we discuss personalized fairness and we show an equivalence between local and universal personalized fairness. The results of our experimental evaluation are presented in Section \ref{sec:experiments}. Finally, we present related research in Section \ref{sec:related-work} and our conclusions in Section \ref{sec:conclusions}. \section{Definitions} \label{sec:definitions} In this section, we first present background material and then we define Pagerank fairness. \subsection{Preliminaries} The {{Pagerank}} algorithm~\cite{pagerank} pioneered link analysis for weighting and ranking the nodes of a graph. It was popularized by its application in the Google search engine, but it has found a wide range of applications in different settings~\cite{pagerank-survey}. The algorithm takes as input a graph $G = (V,E)$, and produces a scoring vector, that assigns a weight to each node $v \in V$ in the graph. The scoring vector is the stationary distribution of a random walk on the graph $G$. The {{Pagerank}} random walk is a random walk with restarts. It is parameterized by the value $\gamma$, which is the probability that the random walk will restart at any step. The node from which the random walk restarts is selected according to the jump vector $\mathbf{v}$, which defines a distribution over the nodes in the graph. Typically, the jump probability is set to $\gamma = 0.15$, and the jump vector is set to the uniform vector. The ``organic'' part of the random walk is governed by the transition matrix $\mathbf{P}$, which defines the transition probability $P[i,j]$ between any two nodes $i$ and $j$. The transition matrix is typically defined as the normalized adjacency matrix of graph $G$. Special care is required for the sink nodes in the graph, that is, nodes with no outgoing edges. In our work, we adopt the convention that, when at a sink node, the random walk performs a jump to a node chosen uniformly at random~\cite{pagerank-survey}. That is, the corresponding zero-rows in the matrix $\mathbf{P}$ are replaced by the uniform vector. The Pagerank vector $\mathbf{p}$ satisfies the equation: \begin{equation} \mathbf{p}^T= (1-\gamma) \mathbf{p}^T \mathbf{P} + \gamma \, \mathbf{v}^T \label{eqn:PR} \end{equation} It can be computed either by solving the above equation, or by iteratively applying it to any initial probability vector. The Pagerank algorithm is fully defined by the three parameters we described above: the transition matrix $\mathbf{P}$, the restart probability $\gamma$, and the restart (or jump) vector $\mathbf{v}$. Different settings for these parameters result in different algorithms. Given a graph $G = (V,E)$, let $\mathcal{PR}(G)$ denote the family of all possible Pagerank algorithms on graph $G$. Each algorithm in $\mathcal{PR}(G)$ corresponds to a triplet $(\mathbf{P}(G), \gamma, \mathbf{v}(G))$ for the parameters of the random walk. This is a very general family that essentially includes all possible random walks defined over the nodes of graph $G$. We will refer to the algorithm that uses the typical settings as the \emph{original} Pagerank algorithm, $\textsc{OPR}$, and use $\mathbf{p}_O$ to denote its pagerank vector. Several variations of the original Pagerank algorithm have been proposed, that modify the above parameters to achieve different goals~\cite{pagerank-survey}. We are interested in defining \emph{fair} Pagerank algorithms. \subsection{Fair Pagerank} We focus on graphs where a set of nodes defines a protected group based on the value of some protected attribute. For example, in the case of social, collaboration, or citation networks where each node is a person, protected attributes may correspond to gender, age, race, or religion. In the following for simplicity, we assume binary such attributes, but our algorithms can be extended for the general case. We consider two types of nodes, red and blue nodes, and the corresponding groups denoted $R$ and $B$ respectively. Group $R$ is the protected group. We denote with $r = \frac{|R|}{n}$, and $b = \frac{|B|}{n}$, the fraction of nodes that belong to the red and blue group respectively. Let $\textsc{PR}\in\mathcal{PR}(G)$ be a Pagerank algorithm on graph $G$. We will use $\textsc{PR}(u)$ to denote the pagerank mass that $\textsc{PR}$ assigns to node $u$, and, abusing the notation, $\textsc{PR}(R)$ to denote the total pagerank mass that $\textsc{PR}$ assigns to the nodes in the red group (for the blue group, $\textsc{PR}(B) = 1-\textsc{PR}(R))$. We will say that $\textsc{PR}$ is \emph{fair}, if it assigns weights to each group according to a specified ratio $\phi$. \begin{definition} [Pagerank Fairness] Given a graph $G = (V,E)$ containing the protected group $R\subseteq V$, and a value $\phi \in (0,1)$, a Pagerank algorithm $\mathrm{PR} \in \mathcal{PR}(G)$ is $\phi$-fair on graph $G$, if $\mathrm{PR}(R) = \phi$. \end{definition} The ratio $\phi$ may be specified so as to implement specific affirmative action policies, or other fairness enhancing interventions. For example, $\phi$ may be set in accordance to the 80-percent rule advocated by the US Equal Employment Opportunity Commission (EEOC), or some other formulation of disparate impact \cite{disparate-impact}. Setting $\phi$ = $r$, we ask for a fair Pagerank algorithm that assigns weights proportionally to the sizes of the two groups. In this case, fairness is analogous to demographic parity, i.e., the requirement that the demographics of those receiving a positive outcome are identical to the demographics of the population as a whole \cite{fairness-awarness}. Our goal is to define fair Pagerank algorithms. We say that a \emph{family} of Pagerank algorithms $\textsl{FPR} \subseteq \mathcal{PR}(G)$ is $\phi$-fair if all the Pagerank algorithms in the family are $\phi$-fair. The first problem we consider is to find such families of algorithms. \begin{problem} Given a graph $G = (V,E)$ containing a protected group of nodes $R \subseteq V$, and a value $\phi \in (0,1)$, define a family of algorithms $\textsl{FPR} \subseteq \mathcal{PR}(G)$ that is $\phi$-fair. \end{problem} We can achieve fairness by modifying the parameters of the Pagerank algorithm. For the following, we assume the jump probability $\gamma$ to be fixed, and we only consider modifications to the transition matrix $\mathbf{P}$ and the jump vector $\mathbf{v}$. A $\phi$-fair family of algorithms is defined by a specific process, parameterized by $\phi$, for defining $\mathbf{P}$ and $\mathbf{v}$. A fair Pagerank algorithm will clearly output a different weight vector than the original Pagerank algorithm. We assume that the weights of the original Pagerank algorithm carry some \emph{utility}, and use these weights to measure the \emph{utility loss} for achieving fairness. Concretely, if $\mathbf{f}$ is the output of a fair Pagerank algorithm $\textsc{FPR}$ and $\mathbf{p}_O$ is the output of the original Pagerank algorithm $\textsc{OPR}$, we define the utility loss of $\textsc{FPR}$ as: $L(\textsc{FPR}) = L(\mathbf{f},\mathbf{p}_O) = \|\mathbf{f}-\mathbf{p}_O\|^2$. The second problem we consider is finding a fair algorithm that minimizes the utility loss. \begin{problem} Given a $\phi$-fair family of algorithms $\textsl{FPR} \subset \mathcal{PR}(G)$, find an algorithm $\mathrm{PR}$ $\in \textsl{FPR}$ that minimizes the utility loss $L(\mathrm{PR})$. \end{problem} Finally, we introduce an extension of the fairness definition, termed \emph{targeted fairness}, that asks for a fair distribution of weights among a specific set of nodes $S$ that is given as input. The subset $S$ contains a protected group of nodes $S_R$. Targeted fairness asks that a fraction $\phi$ of the pagerank mass that $\textsc{PR}$ assigns to $S$ goes to the protected group $S_R$. For example, assume a co-authorship graph $G$, where $S$ is the set of authors of a particular male-dominated field. We want to allocate to the female authors $S_R$ in this field a fraction $\phi$ of the total pagerank allocated to $S$. \begin{definition} [Targeted Fairness] Given a graph $G = (V,E)$, a subset of nodes $S\subseteq V$ containing a protected group $S_R\subseteq S$, and a value $\phi \in (0,1)$, a Pagerank algorithm $\mathrm{PR}\in \mathcal{PR}(G)$, is targeted $\phi$-fair on the subset $S$ of $G$, if $\mathrm{PR}(S_R) = \phi \mathrm{PR}(S)$. \end{definition} The two problems we defined above can also be defined for targeted fairness. \section{Fairness Sensitive PageRank} \label{sec:fairness-sensitive} Our first family of algorithms achieves fairness by keeping the transition matrix $\mathbf{P}$ fixed and changing the jump vector $\mathbf{v}$ so as to meet the fairness criterion. We denote this family of algorithms as the \emph{Fairness-Sensitive Pagerank} (\textsl{FSPR}) algorithms. \subsection{The \textsl{FSPR} Algorithm} First, we note that that pagerank vector $\mathbf{p}$ can be written as a linear function of the jump vector $\mathbf{v}$. Solving Equation (\ref{eqn:PR}) for $\mathbf{p}$, we have that $\mathbf{p}^T = \mathbf{v}^T\mathbf{Q}$, where \[ \mathbf{Q} = \gamma \left[\mathbf{I} - (1-\gamma)\mathbf{P} \right]^{-1} \] Note that if we set $\mathbf{v} = \mathbf{e}_j$, the vector with $\mathbf{e}_j[j] = 1$ and zero elsewhere, then $\mathbf{p}^T = \mathbf{Q}_{j}^T$, the $j$-th row of matrix $\mathbf{Q}$. Therefore, the row vector $\mathbf{Q}_{j}^T$ corresponds to the personalized pagerank vector of node $j$. The pagerank vector $\mathbf{p}$ is a linear combination of the personalized pagerank vectors of all nodes, as defined by the jump vector. Let $\mathbf{p}[R]$ denote the pagerank mass that is allocated to the nodes of the protected category. We have that $$ \mathbf{p}[R] = \sum_{i\in R} \left(\mathbf{v}^T \mathbf{Q} \right) [i] = \mathbf{v}^T \left( \sum_{i\in R} \mathbf{Q}_{i} \right) = \mathbf{v}^T \mathbf{Q}_R $$ where $\mathbf{Q}_{i}$ is the $i$-th column of matrix $\mathbf{Q}$, and $\mathbf{Q}_R$ is the vector that is the sum of the columns of $\mathbf{Q}$ in the set $R$. $\mathbf{Q}_R[j]$ is the total personalized pagerank that node $j$ allocates to the red group. For the algorithm to be fair, we need $\mathbf{p}[R] = \phi$. Thus, our goal is to find a jump vector $\mathbf{v}$ such that $\mathbf{v}^T \mathbf{Q}_R = \phi$. Does such a vector always exist? We prove the following: \begin{lemma} \label{lemma:solution-feasibiliy} Given the vector $\mathbf{Q}_R$, there exists a vector $\mathbf{v}$ such that $\mathbf{v}^T \mathbf{Q}_R = \phi$, if and only if, there exist nodes $i,j$ such that $\mathbf{Q}_R[i] \leq \phi$ and $\mathbf{Q}_R[j] \geq \phi$ \end{lemma} \begin{proof} We have $ \mathbf{p}[R]= \mathbf{v}^T \mathbf{Q}_R = \sum_{j = 1}^N \mathbf{v}[j]\mathbf{Q}_R[j] $, with $0 \leq \mathbf{v}[j] \leq 1$. If $\mathbf{v}^T \mathbf{Q}_R = \phi$, there must exist $i,j$ with $\mathbf{Q}_R[i] \leq \phi$, and $\mathbf{Q}_R[j] \geq \phi$. Conversely, if there exists two such entries $i,j$, then we can find values $\pi_i$ and $\pi_j$, such that $\pi_i \mathbf{Q}_R[i] + \pi_j \mathbf{Q}_R[j] = \phi$ and $\pi_i + \pi_j = 1$. \end{proof} \noindent {\bf Complexity.} Note that there is a very efficient way to compute the personalized pagerank, $\mathbf{Q}_R[j]$, that node $j$ allocates to the red group. We can add a red and a blue absorbing node in the random walk and estimate the probability for each node $j$ to be absorbed by the corresponding absorbing node. This can be done in the time required for running Pagerank. Thus, it is possible to compute the $\mathbf{Q}_R$ vector without doing matrix inversion to compute $\mathbf{Q}$. \subsection{Minimizing Utility Loss} \label{sec:optimization-fair-sensitive} An implication of Lemma~\ref{lemma:solution-feasibiliy} is that, in most cases, there are multiple jump vectors that give a fair pagerank vector. We are interested in the solution that minimizes the utility loss. To solve this problem we exploit the fact that the utility loss function $L(\mathbf{p}_\mathbf{v},\mathbf{p}_O) = \|\mathbf{p}_\mathbf{v} - \mathbf{p}_O\|^2$, where $\mathbf{p}_\mathbf{v}$ is the fair pagerank vector and $\mathbf{p}_O$ the original vector, is convex. We also can express the fairness requirement as a linear constraint. Thus, we define the following convex optimization problem. \begin{equation*} \begin{aligned} & \underset{\mathbf{x}}{\text{minimize}} & & \|\mathbf{x}^T \mathbf{Q} - \mathbf{p}_O\|^2 \\ & \text{subject to} & & \mathbf{x}^T \mathbf{Q}_R = \phi\\ & & & \sum_{i = 1}^{n} \mathbf{x}[i] = 1 \\ & & & 0 \leq \mathbf{x}[i] \leq 1, \; i = 1, \ldots, n \\ \end{aligned} \end{equation*} This problem can be solved using standard convex optimization solvers. In our work, we used the CVXOPT software package\footnote{https://cvxopt.org/}. The complexity of the algorithm is dominated by the computation of matrix $\mathbf{Q}$ which requires a matrix inversion. We can speed up this process by exploiting the fact that the rows of $\mathbf{Q}$ are personalized pagerank vectors, which can be computed (in parallel) by performing multiple random walks. We can improve performance further using approximate computation, e.g., \cite{approximatepr}. \subsection{Targeted Fairness \textsl{FSPR} Algorithm} We can formulate a similar convex optimization problem for the targeted fairness problem. Let $\mathbf{Q}_S = \sum_{i\in S} \mathbf{Q}_i$ be the sum of columns of $\mathbf{Q}$ for the nodes in $S$, and $\mathbf{Q}_{S_R} = \sum_{i\in S_R} \mathbf{Q}_i$be the sum of columns of $\mathbf{Q}$ for the nodes in $S_R$. We define a convex optimization problem that is exactly the same as in Section~\ref{sec:optimization-fair-sensitive}, except for the fact that we replace the constraint $\mathbf{x}^T \mathbf{Q}_R = \phi$ with the constraint $\mathbf{x}^T \mathbf{Q}_{S_R} = \phi \mathbf{x}^T \mathbf{Q}_S $. \section{Locally Fair PageRank} \label{sec:local-fair} Our second family of fair Pagerank algorithms, termed \emph{Locally Fair Pagerank} (\textsl{LFPR}), takes a microscopic view of fairness, by asking that \textit{each individual node} acts fairly, i.e., each node distributes its own pagerank to red and blue nodes fairly. In random walk terms, local fairness defines a dynamic process that can be viewed as a random walk that is fair at each step, and not just at convergence. The \textsl{LFPR} contains all Pagerank algorithms, where all rows of the transition matrix $\mathbf{P}$ are $\phi$-fair vectors. That is, for every node $i \in V$, $\sum_{j \in R} P[i,j] = \phi$. Also, the jump vector $\mathbf{v}$ is $\phi$-fair: $\sum_{j \in R} \mathbf{v}[j] = \phi$. We now consider specific algorithms from the family of locally fair algorithms. \subsection{The Neighborhood \textsl{LFPR} Algorithm} We first consider a node that treats its neighbors fairly by allocating a fraction $\phi$ of its pagerank to its red neighbors and the remaining $1 - \phi$ fraction to its blue neighbors. In random walk terms, at each node the probability of transitioning to a red neighbor is $\phi$ and the probability of transitioning to a blue neighbor $1-\phi$. Formally, we define the \textit{neighborhood locally fair pagerank} ({{\sc LFPR$_N$}}) as follows. Let $out_R(i)$ and $out_B(i)$ be the number of outgoing edges from node $i$ to red nodes and blue nodes respectively. We define $\mathbf{P}_R$ as the stochastic transition matrix that handles transitions to red nodes, or random jumps to red nodes if such links do not exist: \[ \mathbf{P}_R[i,j] = \left \{ \begin{tabular}{cl} $\frac{1}{out_R(i)}$, & if $(i, j)$ $\in$ E and $j$ $\in$ $R$ \\ $\frac{1}{|R|}$, & if $out_R(i) = 0$ and $j$ $\in$ $R$ \\ 0, & otherwise \\ \end{tabular} \right. \] The transition matrix $\mathbf{P}_B$ for the blue nodes is defined similarly. The transition matrix $\mathbf{P}_N$ of the {{\sc LFPR$_N$}} algorithm is defined as: \begin{center} $\mathbf{P}_N = \phi \, \mathbf{P}_R + (1 - \phi) \, \mathbf{P}_B $ \end{center} We also define a $\phi$-fair jump vector $\mathbf{v}_N$ with $\mathbf{v}_N[i]$ = $\frac{\phi}{|R|}$, if $i \in R$, and $\mathbf{v}_N[i]$ = $\frac{1-\phi}{|B|}$, if $i \in B$. The neighborhood locally-fair pagerank vector $\mathbf{p}_N$ is defined as: \[ \mathbf{p}_N^T = (1 - \gamma) \mathbf{p}_N^T \mathbf{P}_N + \gamma \, \mathbf{v}_N^T \] \subsection{The Residual-based \textsl{LFPR} Algorithms} We consider an alternative fair behavior for individual nodes. Similarly to the {{\sc LFPR$_N$}} algorithm, each node $i$ acts fairly by respecting the $\phi$ ratio when distributing its own pagerank to red and blue nodes. However, now node $i$ treats its neighbors the same, independently of their color and assigns to each of them the same portion of its pagerank. When a node is in a ``biased'' neighborhood, i.e., the ratio of its red neighbors is different than $\phi$, to be fair, node $i$ distributes only a fraction of its pagerank to its neigbors, and the remaining portion of its pagerank to nodes in the underrepresented group. We call the remaining portion \emph{residual} and denote it by $\delta(i)$. How $\delta(i)$ is distributed to the underrepresented group is determined by a \textit{residual policy}. Intuitively, this corresponds to a fair random walker that upon arriving at a node $i$, with probability 1-$\delta(i)$ follows one of $i$'s outlinks and with probability $\delta(i)$ jumps to one or more node belonging to the group that is locally underrepresented. We now describe the algorithm formally. We divide the (non sink) nodes in $V$ into two sets, $L_R$ and $L_B$, based on the fraction of their red and blue neighbors. Set $L_R$ includes all nodes $i$ such that $out_R(i)/out(i) < \phi$, where $out(i)$ the out-degree of node $i$, that is, the nodes for which the ratio of red nodes in their neighborhoods is smaller than the required $\phi$ ratio. These nodes have a residual that needs to be distributed to red nodes. Analogously, $L_B$ includes all nodes $i$ such that $out_R(i)/out(i) \geq \phi$, that have a residual to be distributed to blue nodes. Consider a node $i$ in $L_R$. To compute $\delta_R(i)$ note that each neighbor of $i$ gets a fraction $\rho_R(i) = \frac{1-\delta_R(i)}{out(i)}$ of $i$'s pagerank. The residual $\delta_R(i)$ of $i$'s pagerank goes to red nodes. In order for node $i$ to be $\phi$-fair, we have: \begin{equation} \frac{1-\delta_R(i)}{out(i)}out_R(i) + \delta_R(i)= \phi \label{eq:excess1} \end{equation} Solving for $\delta_R(i)$ and using the fact that $out(i) = out_R(i)+out_B(i)$ we get $\delta_R(i) = \phi - \frac{(1-\phi)\,out_R(i)}{out_B(i)}$, and $\rho_R(i) = \frac{1-\phi}{out_B(i)}$. \iffalse Consider a node $i$ in $L_R$. Each neighbor of $i$ gets the same portion of $i$'s pagerank, let $\rho_R(i)$ be this portion. To attain the $\phi$ ratio, the residual $\delta_R(i)$ of $i$'s pagerank goes to the red nodes. Portions $\rho_R(i)$ and $\delta_R(i)$ must be such that: \begin{equation} (1- \phi) \,\, (out_R(i) \, \rho_R(i) + \delta_R(i)) = \phi \,\, (out_B(i) \, \rho_R(i)) \label{eq:excess1} \end{equation} \begin{equation} out_R(i) \,\rho_R(i) + out_B(i) \, \rho_R(i) + \delta_R(i) = 1 \label{eq:excess2} \end{equation} From Equations (\ref{eq:excess1}) and (\ref{eq:excess2}), we get $\rho_R(i)$ = $\frac{1-\phi}{out_B(i)}$ and the residual is $\delta_R(i) = \phi - \frac{(1-\phi)\,out_R(i)}{out_B(i)}$. \fi Analogously, for a node $i$ in $L_B$, we get a residual $\delta_B(i) = (1 -\phi) - \frac{\phi\,out_B(i)}{out_R(i)}$ that goes to the blue nodes, and $\rho_B(i)$ = $\frac{\phi}{out_R(i)}$. For a sink node $i$, we assume that $i$ belongs to both $L_R$ and $L_B$ with residual $\delta_R(i)$ = $\phi$ and $\delta_B(i)$ = $1- \phi$. \vspace*{0.1in} \noindent \textit{Example.} Consider a node $i$ with 5 out-neighbors, 1 red and 4 blue, and let $\phi$ be $0.5$. This is a ``blue-biased''node, that is, $i$ $\in$ $L_R$. With the residual algorithm, each of $i$'s neighbors gets $\rho_R(i)$ = $0.5/4 = 1/8$ portion of $i$'s pagerank, resulting in red neighbors getting $1/8$ and blue neighbors $4/8$ of i's pagerank. The residual $\delta_B(i)$ = $3/8$ goes to nodes in the red group so as to attain the $\phi$ ratio and make $i$ fair. In terms of the random walker interpretation, a random walker that arrives at $i$, with probability $5/8$ chooses one of $i$'s outlinks uniformly at random and with probability $3/8$ jumps to nodes in the red group. \hfill$\qed$. Formally, we define $\mathbf{P}_L$ as follows: \[ \mathbf{P}_L[i, j] = \left \{ \begin{tabular}{cl} $\frac{1-\phi}{out_B(i)}$, & if $(i, j)$ $\in$ $E$ and $i \in L_R$\\ $\frac{\phi}{out_R(i)}$, & if $(i, j)$ $\in$ $E$ and $i \in L_B$ \\ $0$ & otherwise \end{tabular} \right. \] \iffals Let $\mathbf{\delta}_R$ be the vector carrying the red residual, that is, $\mathbf{\delta}_R[i] = \phi - \frac{(1-\phi)\,out_R(i)}{out_B(i)}$, if $i \in L_R$ and 0 otherwise. Similarly, let $\mathbf{\delta}_B$ be the vector carrying the blue residual, that is, $\delta_B(i) = (1 -\phi) - \frac{\phi\,out_B(i)}{out_R(i)}$, if $i \notin L_B$ and 0 otherwise. We have a total red residual $\Delta_R = \mathbf{p}_L^T \, \mathbf{\delta}_R $ and a total blue residual $\Delta_B = \mathbf{p}_L^T \, \mathbf{\delta}_B$, where $\mathbf{p}_L$ is the locally fair pagerank vector. \f $\mathbf{P}_L$ handles the transitions of nodes to their neighborhood. To express the residual distribution policy, we introduce matrices $\mathbf{X}$ and $\mathbf{Y}$, that capture the policy for distributing the residual to red and blue nodes respectively. Specifically, $\mathbf{X}[i, j]$ denotes the portion of the $\delta_R(i)$ of node $i$ $\in$ $L_R$ that goes to node $j$ $\in$ $R$, and $\mathbf{Y}[i, j]$ the portion of the $\delta_B(i)$ of node $i$ $\in$ $L_B$ that goes to node $j$ $\in$ $B$. The locally-fair pagerank vector $\mathbf{p}_L$ is defined as: \[ \mathbf{p}_L^T = (1 - \gamma) \mathbf{p}_L^T \, (\mathbf{P}_L + \mathbf{X} + \mathbf{Y}) + \gamma \, \mathbf{v}_N^T \] \noindent \textbf{Residual Distribution Policies.} The $\mathbf{X}$ and $\mathbf{Y}$ allocation matrices allow us the flexibility to specify appropriate policies for distributing the residual. For example, the {{\sc LFPR$_N$}} algorithm is a special case of the residual-based algorithm, with \vspace*{-0.05in} \[ \mathbf{X}_N[i, j] = \left \{ \begin{tabular}{cl} $\frac{\delta_R(i)}{out_R(i)}$, & if $i \in L_R$, $(i,j) \in E$, and $j \in R$ \\ $\frac{\delta_R(i)}{|R|}$, & if $i \in L_R$, $out_R(i) = 0$, and $j \in R$ \\ 0 & otherwise \\ \end{tabular} \right. \] and $\mathbf{Y}_N[i, j]$ defined analogously. We also consider residual policies where all nodes follow the same policy in distributing their residual, that is, each red node gets the same portion of the red residuals and each blue node the same portion and the blue residuals. In this case, the residual policy is expressed through two (column) vectors $\mathbf{x}$ and $\mathbf{y}$, with $\mathbf{x}[j]$ = 0 if $j \in B$ and $\mathbf{y}[j]$ = 0, $j \in R$. Each node $i \in L_R$ sends a fraction $\delta_R(i)\mathbf{x}[j]$ of its pagerank to red node $j$, while each node $i \in L_B$ sends a fraction $\delta_B(i)\mathbf{y}[j]$ of its pagerank to blue node $j$. Let $\mathbf{\delta}_R$ be the vector carrying the red residual, and $\mathbf{\delta}_B$ the vector carrying the blue residual. We have: \begin{equation*} \mathbf{p}_L^T = (1 - \gamma)\mathbf{p}_L^T\, (\mathbf{P}_L + \mathbf{\delta}_R \, \mathbf{x}^T + \mathbf{\delta}_B \, \mathbf{y}^T) + \gamma \, \mathbf{v}_N^T. \end{equation*} We define two locally fair {{Pagerank}} algorithms based on two intuitive policies of distributing the residual: \vspace{0.05in} \noindent The \textit{Uniform Locally Fair {{Pagerank}}} ({{\sc LFPR$_U$}}) algorithm distributes the residual uniformly. Specifically, we define the vector $\mathbf{x}$, as $\mathbf{x}[i]$ = $\frac{1}{|R|}$ for $i \in R$, and the vector $\mathbf{y}$, as $\mathbf{y}[i]$ = $\frac{1}{|B|}$, for $i \in B$. \vspace{0.05in} \noindent The \textit{Proportional Locally Fair {{Pagerank}}} ({{\sc LFPR$_P$}}) algorithm distributes the residual proportionally to the original pagerank weights $\mathbf{p}_O$ Specifically, we define the vector $\mathbf{x}$, as $\mathbf{x}[i]$ = $\frac{ \mathbf{p}_O[i] }{\sum_{i \in R}\mathbf{p}_O[i]}$, for $i \in R$, and the vector $\mathbf{y}$, as $\mathbf{y}[i]$ = $\frac{ \mathbf{p}_O[i] }{\sum_{i \in B}\mathbf{p}_O[i]}$, for $i \in B$. \subsection{Fairness of the \textsl{LFPR} Algorithms} Although each node acts independently of the other nodes in the network, this microscopic view of fairness results in a macroscopic view of fairness. Specifically, we prove the following theorem. \begin{theorem} The locally fair {{Pagerank}} algorithms are $\phi$-fair. \label{theorem:local} \end{theorem} \iffals \begin{proof} We must show that $\sum_{v \in R} \mathbf{p}_N(u) = \phi$. Since each node in the graph gives a portion $\phi$ of its pagerank to red nodes, we have \[\sum_{v \in R} \mathbf{p}_N(u) = \sum_{v \in V} \phi \, \mathbf{p}_N(u) \] which proves the theorem. \end{proof} \fi \begin{proof} Let $\mathbf{e}_R$ denote the vector with 1's at the red nodes and zero at the blue nodes. The amount of pagerank that vector $\mathbf{p}_L$ gives to the red nodes can be expressed as $\mathbf{p}_L^T\mathbf{e}_R$. Let $\mathbf{P}_D$ = $\mathbf{P}_L + \mathbf{X} + \mathbf{Y}$, we have: \[ \mathbf{p}_L^T\mathbf{e}_R= (1-\gamma)\mathbf{p}_L^T \mathbf{P}_D\mathbf{e}_R + \gamma \mathbf{v}_N^T\mathbf{e}_R \] By design we have that $\mathbf{v}_N^T\mathbf{e}_R = \phi$. For transition matrix $\mathbf{P}_D$, due to the local fairness property, we know that each row has probability $\phi$ of transitioning to a red node. Therefore, $\mathbf{P}_D\mathbf{e}_R = \phi\mathbf{e}$, where $\mathbf{e}$ is the vector of all ones. Note that since $\mathbf{p}_L$ is a distribution we have that $\mathbf{p}_L^T\mathbf{e} = 1$. We thus have: $\mathbf{p}_L^T\mathbf{e}_R= (1-\gamma)\phi + \gamma\phi = \phi$. \end{proof} \subsection{Minimizing Utility Loss} We now consider how to distribute the residual so as to minimize the utility loss of the locally fair Pagerank. We denote this algorithm as {{\sc LFPR$_O$}}. To this end, we compute the $\mathbf{x}$ and $\mathbf{y}$ residual distribution vectors by formulating an optimization problem. We can write the vector $\mathbf{p}_L$ as a function of the vectors $\mathbf{x}$ and $\mathbf{y}$ as follows: \[ \mathbf{p}_L^T(\mathbf{x},\mathbf{y}) = \gamma \, \mathbf{v}_N^T \left[\mathbf{I} - (1-\gamma)(\mathbf{P}_L + \delta_R\, \mathbf{x}^T + \delta_B\, \mathbf{y}^T) \right]^{-1} \] We can now define the optimization problem of finding the vectors $\mathbf{x}$ and $\mathbf{y}$ that minimize the loss function $L(\mathbf{p}_L, \mathbf{p}_O) = \|\mathbf{p}_L(\mathbf{x},\mathbf{y}) - \mathbf{p}_O\|^2$ subject to the constraint that the vectors $\mathbf{x}$ and $\mathbf{y}$ define a distribution over the nodes in $R$ and $B$ respectively. Since our problem is not convex, we implement a Stochastic Random Search algorithm for solving it, that looks at randomly selected directions for the gradient, and selects the one that causes the largest decrease. We enforce the distribution constraints by adding a penalty term $\lambda$ $\left ( (\sum_{i = 1}^{n} \mathbf{x}_i - 1)^2 + (\sum_{i = 1}^{n} \mathbf{y}_i - 1)^2\right )$. We enforce the positivity constraints through proper bracketing at the line-search step. The complexity of the algorithm is $O\left ( I\cdot K\cdot T_{PR}\right )$, where $I$ is the number of iterations, $K$ the number of random directions that are examined, and $T_{PR}$ the cost of running Pagerank. In our experiments, $I$ and $K$ are in the order of a few hundreds. \subsection{Targeted Fairness \textsl{LFPR} Algorithms} We can apply the locally fair algorithms to the targeted fairness problem. Let $S_R$ and $S_B$ be the red and blue nodes in the set $S$ respectively, and let $I_S$ be the set of in-neighbors of $S$. The idea is that the nodes in $I_S$ should distribute their pagerank to $S_R$ and $S_B$ fairly, such that the portion that goes to nodes in $S_R$ is a $\phi$ fraction of the total pagerank that goes to the set $S$. We can implement the same redistribution policies as in the case of the neighborhood local and the residual-based local fair algorithms. We also need the (global) jump vector $\mathbf{v}$ to obey the $\phi$ ratio for the nodes in $S$. We can achieve this by redistributing the probability $|S|/n$ of the jump vector according to the $\phi$ ratio. \section{Personalized Fairness} \label{sec:universal} A special case of the {{Pagerank}} algorithm is when the restart vector is defined to be the unit vector $\mathbf{e}_i$ that puts all the mass at a single node $i$. For any {{Pagerank}} algorithm $\textsc{PR} \in \mathcal{PR}$, we can define the corresponding personalized algorithm $\textsc{PR}_i$ by setting $\mathbf{v} = \mathbf{e}_i$. The output of the algorithm $\textsc{PR}_i$ is a probability vector, where $\textsc{PR}_i(u)$ is the probability that a random walk that always restarts at node $i$ is at $u$ after infinite number of steps. We say that node $i$ allocates this probability to node $u$. Personalized random walks have found several applications in network analysis~\cite{pagerank-survey}. For example, the probability $\textsc{PR}_i(u)$ can be seen as a measure of proximity between node $i$ and node $u$, and it has been used for recommendations. For a personalized Pagerank algorithm $\textsc{PR}_i$, we define $\textsc{PR}_i(R)$ and $\textsc{PR}_i(B)$ to be the probability that node $i$ allocates to the red and blue groups respectively. Recall that if $\mathbf{v}$ is the jump vector, then $\textsc{PR}(R) = \sum_{i\in V} \mathbf{v}[i] \textsc{PR}_i(R)$. We can think of the probability $\textsc{PR}_i(R)$, as a measure of how a specific node $i$ ``views'' the red group, while $\textsc{PR}(R)$ captures the value that the network places on the red nodes on aggregate. We could define fairness for the $\textsc{PR}_i$ algorithm using the standard fairness definition. However, note that since the random walk jumps with probability $\gamma$ to node $i$ at every step, this immediately adds probability $\gamma$ to the category of node $i$. This probability is due to the random jump and not due to the ''organic'' random walk, and the structure of the graph. We thus subtract this probability, and we define the vector $\overline{\textsc{PR}_i}$, where $\overline{\textsc{PR}_i}(i) = \textsc{PR}_i(i)-\gamma$, and $\overline{\textsc{PR}_i}(u) = \textsc{PR}_i(u)$, for $u \neq i$. Another way to think of this is that an amount $\gamma$ of probability is reserved for restarting, and the remaining $1-\gamma$ is allocated through the random walk. This is the probability mass that we want to allocate fairly. We say that the \emph{personalized} Pagerank algorithm $\textsc{PR}_i$ is $\phi$-fair if $\overline{\textsc{PR}_i}(R) = \phi(1-\gamma)$. Intuitively, fairness of $\textsc{PR}_i$ implies that node $i$ treats the red and blue groups fairly. For example, if we think of $\overline{\PR_i}(R)$ as a proximity measure, and $\phi = 0.5$, $\phi$-fairness implies that node $i$ is equally close to the red and blue groups. Given that this probability is often used for recommendations, this has also implications to the fairness of the recommendations. \begin{figure}[] \includegraphics[width = \columnwidth]{books_hist_sep2.pdf} \caption{Histogram of personalized red ratio values.} \label{books-histogram} \end{figure} Note that a Pagerank algorithm $\textsc{PR}$ may be fair, while the corresponding personalized Pagerank algorithms are not. In Figure~\ref{books-histogram}, we consider the original Pagerank algorithm $\textsc{OPR}$, and we show the histogram of the $\overline{\textsc{OPR}_i}(R)$ values for the \textsc{books} dataset (described in Section~\ref{sec:experiments}), for the red and blue nodes, in red and blue respectively. For this dataset, we have that $r = 0.47$ and $\textsc{OPR}(R)$ is 0.46. That is, the original Pagerank algorithm is almost fair for $\phi = r$. However, we observe that the distribution of the $\overline{\textsc{OPR}_i}(R)$ values is highly polarized. The values for the red nodes (shown in red) are concentrated in the interval $[0.8,1]$, while the values for the blue nodes (in blue) are concentrated in the interval $[0,0.2]$. Thus, although the network as a whole has a fair view of the two groups, the individual nodes are highly biased in favor of their own group. Motivated by this observation, we consider a stronger definition of fairness, where given an algorithm $\textsc{PR}$ we require that \emph{all} derivative Personalized Pagerank versions of this algorithm are fair. That is, it is not sufficient that the algorithm treats the red group fairly on aggregate, but we require that each individual node is also fair. \begin{definition}[Universal Personalized Fairness] Given a graph $G = (V,E)$ containing the protected group $R\subseteq V$, and a value $\phi \in (0,1)$, a Pagerank algorithm $\textsc{PR} \in \mathcal{PR}(G)$ is universally personalized $\phi$-fair on graph $G$, if for every node $i \in V$, the personalized Pagerank algorithm $\textsc{PR}_i$ is personalized $\phi$-fair. \end{definition} Since we want all personalized algorithms to be fair, universal personalized fairness (universal fairness for short) is a property of the transition matrix $\mathbf{P}$ of the Pagerank algorithm. Since the \textsl{FSPR} family does not change the matrix $\mathbf{P}$, it is not universally fair. We will show that the locally fair algorithms are universally fair. Furthermore, we can prove that universally fair algorithms are locally fair. Therefore, universal fairness is equivalent to local fairness. \begin{theorem} A Pagerank algorithm $\textsc{PR}$ is universally personalized $\phi$-fair if and only if it is locally fair. \end{theorem} \begin{proof} We first prove that if an algorithm $\textsc{PR}$ is locally fair then it is personalized fair. The proof is similar to that of Theorem~\ref{theorem:local}. Let $\mathbf{p}_i$ denote the personalized pagerank vector of algorithm $\textsc{PR}_i$. We know that $ \mathbf{p}_i^T = (1-\gamma)\mathbf{p}_i^T\mathbf{P} + \gamma \mathbf{e}_i^T $ where $\mathbf{e}_i$ is the vector with 1 at the position $i$, and 0 everywhere else. The amount of probability that $\textsc{PR}_i$ allocates to the red category can be computed as $\textsc{PR}_i(R) = \mathbf{p}_i^T \mathbf{e}_R$, where $\mathbf{e}_R$ is the vector with 1 at the positions of all red nodes and 0 everywhere else. Multiplying the equation for $\mathbf{p}_i^T$ with $\mathbf{e}_R$ we have: \[ \textsc{PR}_i(R) = (1-\gamma)\mathbf{p}_i^T\mathbf{P}\mathbf{e}_R + \gamma \mathbf{e}_i^T\mathbf{e}_R \] Since $\textsc{PR}$ is fair, for every row of the transition matrix $\mathbf{P}$, the probability of transitioning to a red node is $\phi$. Therefore we have that $\mathbf{P} \mathbf{e}_R = \phi\mathbf{e}$, where $\mathbf{e}$ is the vector of all 1's. Also, since $\mathbf{p}_i$ defines a distribution $\mathbf{p}_i^T\mathbf{e} = 1$. Therefore $(1-\gamma)\mathbf{p}_i^T\mathbf{P}\mathbf{e}_R = \phi(1-\gamma)$. We have: \[ \textsc{PR}_i(R) = \phi(1-\gamma) + \gamma\mathbf{e}_i^T \mathbf{e}_R \] The value of the second term $\gamma\mathbf{e}_i^T \mathbf{e}_R$ depends on whether the node $i$ is red or blue. If $i$ is blue, $\gamma\mathbf{e}_i^T \mathbf{e}_R = 0$, and we have $\textsc{PR}_i(R) = \phi(1-\gamma)$. If $i$ is red, $\gamma\mathbf{e}_i^T \mathbf{e}_R = \gamma$, and thus $\textsc{PR}_i(R) = \phi(1-\gamma) + \gamma$, which proves our claim. For the opposite direction we make use of the fact that the pagerank vector can be written as $\mathbf{p}^T = \mathbf{v}^T\mathbf{Q}$, where $\mathbf{v}$ is the jump vector and $\mathbf{Q} = \gamma\left[\mathbf{I} - (1-\gamma)\mathbf{P}\right]^{-1}$. % % From Section~\ref{sec:fairness-sensitive} we know that the $i$-th row of matrix $\mathbf{Q}$ is equal to the personalized pagerank vector $\mathbf{p}_i$. The product $\mathbf{r} = \mathbf{Q}\mathbf{e}_R$ is a vector where $\mathbf{r}[i] = \textsc{PR}_i(R)$. We have assumed that the $\textsc{PR}$ algorithm is universally personalized $\phi$-fair. Therefore $\mathbf{r}[i] = \phi(1-\gamma) + \gamma$ if $i$ is red, and $\mathbf{r}[i] = \phi(1-\gamma)$ if $i$ is blue. That is, $\mathbf{r} = \phi(1-\gamma)\mathbf{e} + \gamma\mathbf{e}_R$. Using the fact that $\mathbf{r} = \mathbf{Q}\mathbf{e}_R$, and that $\mathbf{Q}\mathbf{e} = \mathbf{e}$, since $\mathbf{Q}$ is stochastic, we have the following derivations: \begin{align} \mathbf{Q}\mathbf{e}_R & = \phi(1-\gamma)\mathbf{Q}\mathbf{e} + \gamma\mathbf{e}_R \nonumber\\ \mathbf{Q}^{-1}\mathbf{Q}\mathbf{e}_R & = \phi(1-\gamma)\mathbf{Q}^{-1}\mathbf{Q}\mathbf{e} + \gamma\mathbf{Q}^{-1}\mathbf{e}_R \nonumber\\ \mathbf{e}_R & = \phi(1-\gamma)\mathbf{e} + \gamma\frac1\gamma \left(\mathbf{I} - (1-\gamma)\mathbf{P} \right)\mathbf{e}_R \nonumber\\ \mathbf{e}_R & = \phi(1-\gamma)\mathbf{e} + \mathbf{e}_R - (1-\gamma) \mathbf{P} \mathbf{e}_R \nonumber\\ \mathbf{P} \mathbf{e}_R & = \phi \mathbf{e} \nonumber \end{align} The last equation means that the probability of transitioning from any node in the graph to a red node is $\phi$, which proves our claim. \end{proof} The theorem holds also when we consider targeted fairness. We can prove that an algorithm is universally personalized targeted fair, if and only if it is locally fair. We omit the details of the proof due to lack of space. \section{Experimental Evaluation} \label{sec:experiments} Our goal is to evaluate Pagerank fairness in different kinds of networks, identify the conditions under which Pagerank unfairness emerges and evaluate the effect of the proposed fair Pagerank algorithms. Previous research has shown that homophily and size imbalance may lead to degree unfairness \cite{glass-ceiling,glass-ceiling-recommend,xyz}. Is this the case for Pagerank unfairness? Specifically, we address the following three research questions: \vspace*{0.03in} \noindent \textbf{RQ1:} Under which conditions are the original Pagerank and personalized Pagerank algorithms fair? \noindent \textbf{RQ2:} What is the utility loss incurred by the proposed fair Pagerank algorithms in different networks? \noindent \textbf{RQ3:} What are the qualitative characteristics of the proposed fair Pagerank algorithms? \begin{figure}[] \centering {\includegraphics[width = 0.4\textwidth]{real_violinplots.pdf}} \caption{Distribution of the red personalized pagerank of the red and blue nodes for the real datasets, $\phi$-fairness when the red pagerank is $r$ (\sc{books} $r$ = 0.47, \sc{blogs} $r$ = 0.48, \sc{dblp} $r$ = 0.17, and \sc{twitter} $r$ = 0.61).} \label{fig:real-violin-plots} \end{figure} \vspace*{0.03in} \noindent \textbf{Datasets.} We use both real and synthetic datasets. Our real datasets are the following: \begin{itemize} \item {\sc{books}}: A network of books about US politics where edges between books represented co-purchasing\footnote{\url{http://www-personal.umich.edu/~mejn/netdata/}}. \item {\sc{blogs}}: A directed network of hyperlinks between weblogs on US politic \cite{blogs-dataset}. \item {\sc{dblp}}: An author collaboration network constructed from DBLP including a subset of data mining and database conferences. \item {\sc{twitter}}: A political retweet graph from \cite{nr}. \end{itemize} The characteristics of the real datasets are summarized in Table \ref{table:real}. To infer the gender in {\sc{dblp}}, we used the python \textit{gender guesser} package\footnote{\url{https://pypi.org/project/gender-guesser/}}. Regarding $homophily$, we measure for each group, the percentage of the edges that are \textit{cross-edges} that is they point to nodes of the other group divided by the expected number of such edges. We denote these quantities as $\textit{cross}_R$ and $\textit{cross}_B$. Values significantly smaller than 1 indicate that the corresponding group exhibits homophily \cite{network-book}. Synthetic networks are generated using the biased preferential attachment model introduced in \cite{glass-ceiling}. The graph evolves over time as follows. Let $G_t = (V_t, E_t)$ and $d_t(v)$ denote the graph and the degree of node $v$ at time $t$, respectively. The process starts with an arbitrary connected graph $G_0$, with $n_0 \, r$ red and $n_0 \,(1 - r)$ blue nodes. At time step $t + 1$, $t > 0$, a new node $v$ enters the graph. The color of $v$ is red with probability $r$ and blue with probability $1-r$. Node $v$ chooses to connect with an existing node $u$ with probability $\frac{d_t(u)}{\sum_{w \in G_{t} d_t(w)}}$. If the color of the chosen node $u$ is the same with the color of the new node $v$, then an edge between them is inserted with probability $\alpha$; otherwise an edge is inserted with probability $1-\alpha$. If no edge is inserted, the process of selecting a neighbor for node $v$ is repeated until an edge is created. \begin{figure*}[] \centering \subfigure[{symmetric, $r$ = 0.3}]{ {\includegraphics[width = 0.22\textwidth]{sym_varyHom_size_03_utility_plot.pdf}} } \subfigure[{asymmetric, $r$ = 0.3}]{ {\includegraphics[width=0.22\textwidth]{asym_varyHom_size_03_utility_plot4.pdf}} } \subfigure[{symmetric, $r$ = 0.5}]{ {\includegraphics[width = 0.22\textwidth]{sym_varyHom_size_05_utility_plot.pdf}} } \subfigure[{asymmetric, $r$ = 0.5}]{ {\includegraphics[width=0.22\textwidth]{asym_varyHom_size_05_utility_plot1.pdf}} } \caption{Utility loss for synthetic networks, $\phi$ = 0.5.} \label{fig:synth-utility-homo} \end{figure*} \begin{figure}[] \centering \subfigure[{$r$ = 0.3}]{ {\includegraphics[width = 0.22\textwidth]{sym_varyPhi_size_03_utility_plot.pdf}} } \subfigure[{$r$ = 0.5}]{ {\includegraphics[width = 0.22\textwidth]{sym_varyPhi_size_05_utility_plot4.pdf}} } \caption{Utility loss for the synthetic datasets, $\alpha$ = 0.5.} \label{fig:synth-utility-phi} \end{figure} \begin{figure*}[] \centering \subfigure[{\sc{books}}]{ {\includegraphics[width = 0.22\textwidth]{books_utility_plot.pdf}} } \subfigure[{\sc{blogs}}]{ {\includegraphics[width = 0.22\textwidth]{blogs_utility_plot.pdf}} } \subfigure[{\sc{dblp}}]{ {\includegraphics[width = 0.22\textwidth]{dblp_course_utility_plot.pdf}} } \subfigure[{\sc{twitter}}]{ {\includegraphics[width = 0.22\textwidth]{twitter_utility_plot2.pdf}} } \caption{Utility loss for the real networks, (original red pagerank, \sc{books}: 0.48, \sc{blogs}: 0.33, \sc{dblp}: 0.16, and \sc{twitter}: 0.57).} \label{fig:real-utility} \end{figure*} Parameter $r$ controls the group size imbalance. Parameter $\alpha$ controls the level of homophily: $\alpha < 0.5$ corresponds to heterophily, $\alpha = 0.5$ to neutrality and $\alpha > 0.5$ to homophily. We consider: (a) a symmetric case, where $\alpha$ is the same for both groups and (b) an asymmetric case, where we set $\alpha$ = 0.5 for the blue group, making it neutral, and vary $\alpha$ for the red group. The datasets and code are available in GitHub\footnote{\url{https://github.com/SotirisTsioutsiouliklis/FairLaR}}. \subsection{When is Pagerank Fair?} We study the conditions under which the original Pagerank and personalized Pagerank algorithms are fair. We assume that the algorithms are fair, if they respect demographic parity, that is, if each group gets pagerank equal to its ratio in the overall population ($\phi$ = $r$). For brevity, we shall call the (personalized) pagerank allocated to red nodes \textit{red (personalized) pagerank} and the (personalized) pagerank allocated to blue nodes \textit{blue (personalized) pagerank} . First, we study homophily and size imbalance using synthetic datasets. In Figure \ref{fig:local-synthetic-all}(a), we report the red pagerank for the symmetric and in Figure \ref{fig:local-synthetic-all}(b) for the asymmetric case. Fairness corresponds to the identity line (red pagerank = $r$). Values above the line indicate unfairness towards the blue group, while values below the line unfairness towards the red group. We also plot the distribution of the red personalized pagerank in Figures \ref{fig:sym-violin-plots} and \ref{fig:asym-violin-plots} for the symmetric and asymmetric case respectively. To test whether the red personalized pagerank of a node depends on its color, we plot two distributions, one for the red personalized pagerank of the red nodes and one for the red personalized pagerank of the blue nodes. Distributions are plotted in the form of violin plots. Personalized pagerank fairness corresponds to the case in which the two distributions overlap, with their mean on value $r$. Note that when a group is homophilic, it is expected that a large part of its personalized pagerannk goes to nodes of its own color, e.g., red homophilic nodes have large red personalized pageranks. \noindent \textbf {Symmetric case} (Figures \ref{fig:local-synthetic-all}(a) and \ref{fig:sym-violin-plots}): When both groups are homophilic ($\alpha$ = 0.7, 0.9), the nodes tend to form two clusters, one with red nodes and one with blue nodes sparsely connected to each other. This leads to an almost fair pagerank (with a very slight unfairness towards the minority group), but highly unfair personalized pageranks. On the contrary, when there is heterophily ($\alpha = 0.1, 0.3$), there are no clusters, nodes tend to connect with nodes of the opposite color, and the larger group favors the smaller one. In this case, the pagerank and personalized pageranks of both the blue and the red nodes are all unfair towards the majority group. This is especially evident when the imbalance in size is large (small $r$). \noindent \textbf {Asymmetric case} (Figures \ref{fig:local-synthetic-all}(b) and \ref{fig:asym-violin-plots}): When the red nodes are homophilic ($\alpha$ = 0.7, 0.9), the red group keeps the pagerank to itself. As a result both pagerank and personalized pageranks are unfair towards the blue nodes, especially for larger $r$. When the red nodes are heterophilic ($\alpha$ = 0.1, 0.3), the red group favors the blue group, and as a result, both the pagerank and the personalized pagerank are unfair towards the red nodes, especially for larger $r$. Thus, independently of the size $r$, pagerank is unfair to the blue (the neutral) group in case of homophily, and unfair to the red group in the case of heterophily. \noindent \textbf {Universal fairness:} The only case when both pagerank and personalized pageranks are all fair is in a neutral network ($\alpha = 0.5$) with same-size groups ($r$ = 0.5) (middle violin plots in Figures \ref{fig:sym-violin-plots}(c) and \ref{fig:asym-violin-plots}(c)). \noindent \textbf {Real datasets:} For the real datasets, we report the red pagerank in Table \ref{table:real} ($p_R$ value) and plot the distributions of the red personalized pagerank of the blue and red nodes in Figure \ref{fig:real-violin-plots}. For {\sc books}, there is no size imbalance and there is strong symmetric homophily leading to fair pagerank and highly unfair personalized pageranks. For {\sc blogs}, there is no size imbalance, but the blue group is slightly more homophilic, which leads both to unfairness in pagerank for the red group, and unfairness of the personalized pagerank of the blue nodes towards the red ones. For {\sc dblp}, we have large size imbalance with the red group being the minority but almost neutral behavior in terms of homophily, leading to an almost fair pagepank, and the majority of personalized pageranks being fair. Finally, for {\sc twitter}, the red group is larger than the blue group but less homophilic which leads to a slight unfairness towards the red group for both pagerank and personalized pageranks. \subsection{What is the Utility Loss for Fairness?} We now look into the utility loss for achieving fairness. We can view utility loss for each network as a measure of the cost we have to pay to achieve $\phi$-fairness for this network. First, to assess the utility loss of our algorithms in absolute terms we compute a lower bound for the utility loss. \noindent \textbf{Lower Bound.} We compute a lower bound on the utility loss, by constructing the probability vector $\mathbf{w}$ that is $\phi$-fair, and it has the minimum utility loss compared to the original pagerank vector $\mathbf{p}_O$. Note that vector $\mathbf{w}$ is not necessarily attainable by any Pagerank algorithm in $\mathcal{PR}$. To compute $\mathbf{w}$, we start with $\mathbf{p}_O$ and we redistribute the probability between the two groups to make it fair. Let $\mathbf{p}_O(R)$ be the probability assigned to the red group by $\mathbf{p}$. Without loss of generality, assume that $\mathbf{p}_O(R)< \phi$, and let $\Delta = \phi-\mathbf{p}_O(R)$. To make the vector fair, we need to remove $\Delta$ probability mass from the nodes in $B$, and redistribute it to the nodes in $R$. It is easy to show that to minimize the loss, the optimal redistribution will remove uniformly $\Delta/|B|$ probability from all nodes in $B$, and add uniformly $\Delta/|R|$ to all nodes in $R$. This follows from the fact that among all distribution vectors the one with the smallest length is the uniform one. However, this process does not guarantee that the resulting vector will not have negative entries, since some blue nodes may have probability less than $\Delta/|B|$. Let $\beta$ be the smallest non-zero such probability of any blue node. Our algorithm transfers $\beta$ probability from all the non-zero blue nodes to the red nodes, and then recursively applies the same procedure for the residual amount of probability that has not been transferred. It is not hard to show that this process will produce a fair vector with the minimum utility loss with respect to $\mathbf{p}_O$. Figures \ref{fig:synth-utility-homo} and \ref{fig:synth-utility-phi} report the utility loss for selected synthetic networks and Figure \ref{fig:real-utility} for different values of $\phi$ for the real datasets. $LB$ is the lower bound on utility loss. \noindent \textbf{Effect of $\phi$:} In all cases, loss increases as the requested $\phi$ deviates from the red pagerank originally assigned to the red group (Figures \ref{fig:synth-utility-phi} and \ref{fig:real-utility}). \noindent \textbf{\textsl{FSPR}:} \, In some cases {{\sc FSPR}} incurs high utility loss and, occasionally, it is even unable to find an appropriate solution. {{\sc FSPR}} achieves fairness by changing the jump vector of the Pagerank algorithm. The overall pagerank vector is a linear combination of the personalized pagerank vectors, with the jump vector providing the coefficients of this linear combination. {{\sc FSPR}} increases the jump probability for the vectors that favor the group it wants to promote and takes away probability from the vectors that favor the other group. However, when there are few, or no appropriate such vectors, {{\sc FSPR}} is forced to make extreme choices (assign a lot of probability to a few vectors) thus incurring high utility loss, or it is unable to find any solution. There are several such examples in our datasets. For the {\sc dblp} dataset (Figure \ref{fig:real-utility}(c)), for small values of $\phi$ ($\phi \leq 0.3$), the utility loss of {{\sc FSPR}} is close to the optimal, but for $\phi \geq 0.4$, it skyrockets. Looking at Figure \ref{fig:real-violin-plots}, we see that there are very few personalized pagerank vectors with red pagerank larger than 0.4. As a result, for $\phi \geq 0.4$, {{\sc FSPR}} is forced to allocate all the probability of the jump vector to these nodes, leading to high utility loss. It is also interesting to observe the effect of homophily, or lack of, on the utility loss of {{\sc FSPR}}. In Figure \ref{fig:synth-utility-homo}(a) and (b), utility loss peaks when the network is neutral ($\alpha = 0.5$). In this case, there is no personalized pagerank vector that strongly favors one group over the other. \noindent \textbf{\textsl{LFPR}:} \, Overall, for the locally fair family of algorithms, the utility loss function is smoother, avoiding high peaks. The locally fair algorithms are directly affected by homophily, since this determines the composition of the neighborhoods of the nodes. As we deviate from neutrality, the loss increases (Figure \ref{fig:synth-utility-homo}). This holds especially for the {{\sc LFPR$_N$}} algorithm. This can be seen very clearly in {\sc books} (Figure \ref{fig:real-utility}(a)), where {{\sc FSPR}} almost achieves the lower bound, while {{\sc LFPR$_N$}} incurs high utility loss because of {\sc books} being very homophilic. The utility loss of {{\sc LFPR$_U$}} and {{\sc LFPR$_P$}} follows in general the same trend as {{\sc LFPR$_N$}}. Finally, {{\sc LFPR$_O$}} redistributes any residual Pagerank so that the utility loss is optimized and in many cases its utility loss is close to the lower bound ($LB$). \noindent \textbf{Summary:} {{\sc FSPR}} works well when there are enough unfair nodes (i.e., nodes with unfair personalized pageranks), as it can distribute the jump probability to them to achieve fairness. On the contrary, locally fair algorithms have high utility loss when there are many unfair nodes. {{\sc LFPR$_N$}} is the most sensitive to homophily. The utility loss of {{\sc LFPR$_N$}} can be seen as a measure of local unfairness. Overall, the locally fair algorithms are more stable than {{\sc FSPR}}. {{\sc LFPR$_O$}} works very well in terms of utility loss and in many cases it achieves utility close to the lower bound. \subsection{Qualitative Evaluation} In this section, we provide some qualitative experiments, to better understand the properties of the fair algorithms. \begin{figure}[t] \centering \subfigure[Original {{Pagerank}}]{ {\includegraphics[width = 0.175\textwidth]{books_05_pagerank.png}} } \subfigure[{{\sc LFPR$_N$}}]{ {\includegraphics[width = 0.175\textwidth]{books_05_lfprNei.png}} } \subfigure[{{\sc FSPR}}]{ {\includegraphics[width = 0.175\textwidth]{books_05_sensitive.png}} } \subfigure[Jump vector for {{\sc FSPR}}]{ {\includegraphics[width = 0.175\textwidth]{books_05_jumpV.png}} } \caption{Visualization of the {\sc book} dataset.} \label{fig:vis-books} \end{figure} \begin{figure}[t] \centering \subfigure[Original {{Pagerank}}]{ {\includegraphics[width = 0.22\textwidth]{dblp-course-05-pagerank.pdf}} } \subfigure[{{\sc LFPR$_N$}}]{ {\includegraphics[width = 0.22\textwidth]{dblp-course-05-lfprNei.pdf}} } \subfigure[{{\sc FSPR}}]{ {\includegraphics[width = 0.22\textwidth]{dblp-course-05-sensitive.pdf}} } \subfigure[Jump vector for {{\sc FSPR}}]{ {\includegraphics[width = 0.22\textwidth]{dblp-course-05-jumpV.pdf}} } \caption{Visualization of the {\sc dblp} dataset.} \label{fig:vis-dblp} \end{figure} \noindent \textbf{Visualization.} In Figures \ref{fig:vis-books} and \ref{fig:vis-dblp}, we visualize the results of the algorithms for the {\sc books} and the {\sc dblp} dataset respectively, for $\phi$ = 0.5. Red nodes are colored red, and blue nodes are colored blue. Their size depends on the value of the quantity we visualize. We visualize the pagerank values for the original Pagerank, {{\sc FSPR}} and {{\sc LFPR$_N$}} algorithms, and the jump vector probabilities for {{\sc FSPR}}. For {\sc books}, where the original red pagerank is close to $\phi$, {{\sc FSPR}} is very similar to the original Pagerank algorithm. {\sc books} is homophilic and the jump vector assigns rather uniform weights to almost all nodes. On the other hand, {{\sc LFPR$_N$}} promotes heavily nodes connecting the two opposite groups, i.e., nodes that are minorities in their neighborhoods. We observe a different result in {\sc dblp}, where $\phi$ is much larger than the original red pagerank. {{\sc LFPR$_N$}} distributes weights broadly in the red community, while {{\sc FSPR}} is much more aggressive. This is especially evident in the jump vector which promotes a few nodes in the periphery. \begin{table}[ht] \centering \caption{Top-10 authors with $\phi$ = 0.3; the number in parenthesis is the position of the author in the original {{Pagerank}} ($\textsc{OPR}$) (female authors in bold). } \footnotesize{ \begin{tabular}{l l l} \toprule $\textsc{OPR}$ & {\sc FSPR} & {\sc LFPR$_N$} \\ \midrule C. Faloutsos & C. Faloutsos (1) & C. Faloutsos (1) \\ G. Weikum & G. Weikum (2) & G. Weikum (2) \\ P. S. Yu & P. S. Yu (3) & \textbf{J. Widom} (38) \\ M. Stonebraker & M. Stonebraker (4) & M. Stonebraker (4) \\ M. J. Franklin & M. J. Franklin (5) & P. S. Yu (3)\\ H. Garcia-Molina & H. Garcia-Molina (6) & \textbf{S. T. Dumais} (28) \\ D. Kossmann & D. Kossmann (7) & \textbf{M. Lalmas} (27) \\ W. Lehner & \textbf{E. A. Rundensteiner} (22) & P. Serdyukov (17) \\ M. J. Carey & R. Agrawal (11) & \textbf{E. Bertino} (25) \\ M. de Rijke & W. Lehner (8) & \textbf{E. A. Rundensteiner} (22) \\ \bottomrule \end{tabular} \label{table:case-study} } \end{table} \noindent \textbf{Anecdotal Examples.} We will use the {\sc dblp} dataset for a qualitative evaluation of the results of the algorithms. Recall that for this dataset, women are the minority with $r$ = 0.17, and the original red pagerank is equal to 0.16. To achieve a fairer representation of women, we apply the {{\sc LFPR$_N$}} and {{\sc FSPR}} algorithms with $\phi$ = 0.3. In Table \ref{table:case-study}, we present the first 10 authors for each algorithm. In the original Pagerank algorithm $\textsc{OPR}$, there is no female author in the top-10 (the first one appears in position 22). {{\sc FSPR}} achieves fairness but also minimizes utility loss, so the result is fair but also close to that of $\textsc{OPR}$. {{\sc LFPR$_N$}} asks that all authors have $\phi$-fair inter-gender collaborations resulting in a large number of female authors appearing in the top-10 positions. \begin{table}[ht] \centering \caption{Top-3 female authors by conference, $\phi$ = 0.3.} \footnotesize { \begin{tabular}{lll} \toprule &SIGIR&SIGMOD\\ \midrule \multirow{3}{*}{{\sc FSPR}}& Mounia Lalmas & Elke A. Rundensteiner \\ &Susan T. Dumais & Elisa Bertino \\ &Juliana Freire & Tova Milo \\ \midrule \multirow{3}{*}{{\sc LFPR$_N$}}& Susan T. Dumais & Jennifer Widom \\ & Mounia Lalmas & Elke A. Rundensteiner \\ & Emine Yilmaz & Fatma Ozcan \\ \bottomrule \end{tabular} } \label{table:case-study-conf} \end{table} We also use {\sc dblp} to study the targeted fair Pagerank algorithms. In this case, we want to enforce fair behavior towards authors in specific conferences. We consider two such conferences, SIGIR and SIGMOD, and select $S$ to include authors of each one of them. In Table \ref{table:case-study-conf}, we show the top-3 women authors for each conference according to our algorithms. We observe that the algorithms produce different results depending on the conference, each time promoting women that are authorities in their respective fields, such as, Suzan Dumais when $S$ is SIGIR, and Jennifer Widom when $S$ is SIGMOD. \section{Related Work} \label{sec:related-work} \noindent \textbf{Algorithmic fairness.} Recently, there has been increasing interest in algorithmic fairness, especially in the context of machine learning. Fairness is regarded as the lack of discrimination on the basis of some protective attribute. Various definition of fairness having proposed especially for classification \cite{fairness-awarness,fairness-study,fairness-measures,bias-fairness-survey}. We use a group-fairness definition, based on parity. Approaches to handing fairness can be classified as \textit{pre-processing}, that modify the input data, \textit{in-processing}, that modify the algorithm and \textit{post-processing} ones, that modify the output. We are mostly interested in in-processing techniques. There is also prior work on fairness in ranking~\cite{fai*r,Julia17,Biega18,pair-wise}. All of these works consider ranking as an ordered list of items, and use different rules for defining and enforcing fairness that consider different prefixes of the ranking~\cite{fai*r,Julia17}, pair-wise orderings~\cite{pair-wise}, or exposure and presentation bias~\cite{exposure-ranking,Biega18}. Our goal in this paper is not to propose a new definition of ranking fairness, but rather to initiate a study of fairness in link analysis. A distinguishing aspect of our approach is that we take into account the actual Pagerank weights of the nodes, not just their ranking. Furthermore, our focus in this paper, is to design in-processing algorithms that incorporate fairness in the inner working of the Pagerank algorithm. We present a post-processing approach as a means to estimate a lower bound on the utility loss. None of the previous approaches considers ranking in networks, so the proposed approaches are novel. \noindent \textbf{Fairness in networks.} There has been some recent work on network fairness in the context of graph embeddings \cite{fair-embedding,filter-bubbles,fair-walk}. The work in \cite{fair-embedding} follows an in-processing approach that extends the learning function with regulatory fairness enforcing terms, while the work in \cite{filter-bubbles} follows a post-processing approach so as to promote link recommendations to nodes belonging to specific groups. Both works are not related to our approach. The work in \cite{fair-walk} extends the node2vec graph embedding method by modifying the random walks used in node2vec with fair walks, where nodes are partitioned into groups and each group is given the same probability of being selected when a node makes a transition. The random walk introduced in \cite{fair-walk} has some similarity with the random walk interpretation of {{\sc LFPR$_N$}}. It would be interesting to see, whether our extended residual-based algorithms could be utilized also in the context of graph embeddings, besides its use in link analysis. There are also previous studies on the effect of homophily, preferential attachment and imbalances in group sizes. It was shown that the combination of these three factors leads to uneven degree distributions between groups \cite{glass-ceiling}. Recent work shows that this phenomenon is exaggerated by many link recommendation algorithms \cite{glass-ceiling-recommend}. Evidence of inequality between degree distribution of minorities and majorities was also found in many real networks \cite{homophily-ranking}. Our work extends this line of research by looking at Pagerank values instead of degrees. Along this lines, recent work studies in depth how homophily and size imbalance can affect the visibility that different groups get in link recommendations, i.e, how often nodes in each group get recommended \cite{xyz}. Very recent work also looks at graph mining algorithms in general from the perspective of individual fairness, where the goal is to produce a similar output for similar nodes \cite{inform}. Finally, there is previous work on diversity in network ranking. The goal is to find important nodes that also maximally cover the nodes in the network~\cite{grasshoper,divrank}. Our problem is fundamentally different, since we look for scoring functions that follow a parity constraint. \section{Conclusions} \label{sec:conclusions} In this paper, we initiate a study of fairness for Pagerank. We provide definitions of fairness, and we propose two approaches for achieving fairness: one that modifies the jump vector, and one that imposes a fair behavior per node. We prove that the latter is equivalent to a stronger notion of fairness that also guarantees personalized Pagerank fairness. We also consider the problem of attaining fairness while minimizing the utility loss of Pagerank. Our experiments demonstrate the behavior of our different algorithms. There are many direction for future work. First, we would like to study the role of $\gamma$, i.e., the jump probability. Then, it would be interesting to explore other notions of Pagerank fairness, besides $\phi$-fairness, for instance ones based on rank-aware fairness \cite{edbt-tut}. Furthermore, we plan to explore further applications of the theory behind our fair Pagerank algorithms to derive novel notions of fair random walks.
{'timestamp': '2021-03-25T01:03:43', 'yymm': '2005', 'arxiv_id': '2005.14431', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14431'}
arxiv
\section{Introduction} \blfootnote{\IEEEauthorrefmark{1}Saeid Haghighatshoar is currently with the Swiss Center for Electronics and Microtechnology (CSEM), however his contribution to this work was made while he was with the CommIT group (saeid.haghighatshoar@csem.ch).} Massive multiple-input multiple-output (MIMO) communication systems have recently received considerable attention by promising unprecedented data rates, network coverage and link reliability \cite{larsson2014massive,bjornson2016massive}. This technology makes use of a large number ($M\gg 1$) of antennas at the base station (BS), enabling the spatial multiplexing of several data streams to a number of users $K$ that share the same time-frequency transmission resource \cite{yang2013performance}. Massive MIMO can be implemented for both narrow-band and wide-band signaling and is compatible with new trends such as millimeter wave (mmWave) communications \cite{heath2016overview}. In order to precode effectively the Downlink (DL) data streams to the users, massive MIMO requires some level of channel state information at the transmitter side (CSIT). This can be easily obtained in TDD systems owing to channel reciprocity and calibrated RF front-ends \cite{marzetta2010noncooperative,shepard2012argos}. However, in the case where the computation of the precoder is too complex for real-time operations, or in the FDD case, where obtaining accurate and timely CSIT is very difficult, several schemes have been proposed in order to exploit the statistical structure of the massive MIMO channels, and in particular to decompose them into ``virtual beam directions", such that the precoding and channel estimation can be performed in a virtual beam domain of reduced dimension \cite{adhikary2013joint,haghighatshoar2016massive,haghighatshoar2018low,khalilsarai2018fdd}. In particular, in many typical propagation environments the number of scatterers is much less than the number of array elements, the BS is connected to a user through a narrow angular aperture. Therefore, by a careful choice of the beam-space, the BS can use a variety of sparse signal processing tools to efficiently perform its tasks \cite{haghighatshoar2017massive,khalilsarai2018achieve,nguyen2013compressive,wunder2018hierarchical}. Defining the array response vector as ${{\mathbb f} a} (\hbox{\boldmath$\xi$}) = [ e^{j\tfrac{2\pi}{\lambda}\langle {{\mathbb f} r}_1 , \hbox{\boldmath$\xi$} \rangle},\ldots,e^{j\tfrac{2\pi}{\lambda}\langle {{\mathbb f} r}_M , \hbox{\boldmath$\xi$} \rangle}, ]^{\sf T}$, the MIMO channel covariance can be written as \cite{khalilsarai2018fdd} \begin{equation}\label{eq:ch_cov_0} \widetilde{\hbox{\boldmath$\Sigma$}} = {\mathbb E} \left[ {{\mathbb f} h} {{\mathbb f} h}^{{\sf H}} \right] = \int_{\hbox{\boldmath$\Xi$}} \gamma (\hbox{\boldmath$\xi$}) {{\mathbb f} a} (\hbox{\boldmath$\xi$}) {{\mathbb f} a} (\hbox{\boldmath$\xi$})^{{\sf H}} d\hbox{\boldmath$\xi$}, \end{equation} where $\lambda$ is the wavelength, $\{{{\mathbb f} r}_m \}_{m=1}^M$ denotes antenna locations, $\hbox{\boldmath$\xi$} \in \hbox{\boldmath$\Xi$}$ is the angle of arrival (AoA) and $\gamma (\hbox{\boldmath$\xi$})$ is the angular power spread function. The beam-space for a user is characterized by a set of vectors, called \textit{virtual beams} that span the column space of $\widetilde{\hbox{\boldmath$\Sigma$}}$. The ``best" choice for such vectors is given by the eigenvectors of $\widetilde{\hbox{\boldmath$\Sigma$}}$ denoted as columns of the matrix ${{\mathbb f} U} = [{{\mathbb f} u}_1,\ldots,{{\mathbb f} u}_M]$, which also comprise the basis for the Karhunen-L{\`o}eve (KL) expansion of ${{\mathbb f} h}$ as $ {{\mathbb f} h} = \sum_{m=1}^{M} w_m {{\mathbb f} u}_m, $ where $w_m \in {\mathbb C}, \, m=1,\ldots,M$ are uncorrelated random variables. The KL expansion provides the best $k$-term approximation for ${{\mathbb f} h}$ and has, exclusive to itself, the property of decorrelating ${{\mathbb f} h}$ into orthonormal vectors $\{ {{\mathbb f} u}_m \}_{m=1}^M$ with uncorrelated coefficients $\{w_m \}_{m=1}^M$ \cite{unser2014introduction}. For Gaussian channels, widely assumed in wireless multipath channel models, this property is even more pronounced as the coefficients become statistically independent. The variance of a coefficient $\sigma_m^2 ={\mathbb E} [ |w_m|^2 ] $ represents the channel ``power" along virtual beam ${{\mathbb f} u}_m$ and reveals the channel angular sparsity, such that if the power along a beam is less than a threshold ($\sigma_m^2 < \epsilon$), one can assume that the BS receives almost no energy from that beam. While obtaining the set of virtual beams is easy for a single user, it is not straightforward when one deals with multiple users, since in general the users do not share the same set of eigenvectors. On the other hand, having a suitable set of common virtual beams (CVB) is highly desirable for DL channel training and multi-user precoding \cite{sayeed2013beamspace,khalilsarai2018fdd}. Most of the works in the literature \textit{assume} the existence of a common basis of orthogonal beam directions that (approximately) diagonalizes all user covariances and represents a sort of common eigenvectors set (CES) \cite{heath2016overview}. For the simplest case of a \textit{uniform linear array} (ULA), it is typically taken for granted that the CVB is given by a uniform sampling of the array response vector, which in turn is equivalent to the DFT basis. The implicit (and seldom mentioned) reason for this assumption comes from an asymptotic ($M\to \infty$) equivalence between Toeplitz and circulant matrices according to the Szeg{\"o} theorem (see \cite{adhikary2013joint} and references therein). Since the covariance of the channel associated with a ULA is Toeplitz, and since circulant matrices are diagonalized by the DFT matrix, it holds that DFT columns form an approximate set of eigenvectors for any ULA covariance. As this theoretic result holds for large ULAs, the choice of a suitable set of virtual beams for small or moderate-sized arrays is unclear. Besides, for array geometries other than the ULA, such as circular, planar and cylindrical arrays, no universal virtual beam design is known. This paper provides a solution for the problem above. Given random channel realizations ${{\mathbb f} h}_k^{(1)},\, {{\mathbb f} h}_k^{(2)},\, \ldots, \, {{\mathbb f} h}_k^{(N)}$ of a set of users $k=1,\ldots,K$ and without knowing the array geometry we propose a rigorous method for obtaining an orthogonal CVB set. Note that this problem is more general compared to the case in which we have user covariances $\widetilde{\hbox{\boldmath$\Sigma$}}_k,\, k=1,\ldots, K$. Our method is based on the maximum-likelihood (ML) estimation of the \textit{postulated} CES given random channel realizations. We formulate the ML problem as an optimization over the unitary manifold and proposed a \textit{projected gradient descent} (PGD) method to solve it. We prove the convergence of this algorithm to a stationary point of the likelihood function with arbitrary initialization. We also show that, with jointly diagonalizable covariances, the CES coincides with the global maximizer of the likelihood function. Finally, we compare our method to the classic joint approximate diagonalization of eigenmatrices (JADE) algorithm \cite{cardoso1993blind} to show its superior performance. \section{System Setup} Consider the following scenario: we observe $N$ random realizations for each of the $K$ independent, stationary, zero-mean vector Gaussian processes as \begin{equation}\label{eq:vector_observations} {{\mathbb f} H}_k = \left[ {{\mathbb f} h}_k^{(1)},\ldots,{{\mathbb f} h}_k^{(N)} \right] \in {\mathbb C}^{M\times N},\, k=1,\ldots,K. \end{equation} The covariance matrix of process $k$ is denoted by $\widetilde{\hbox{\boldmath$\Sigma$}}_k = {\mathbb E} [{{\mathbb f} h}_k {{\mathbb f} h}_k^{{\sf H}} ]$. The random vector ${{\mathbb f} h}_k$ can represent, for instance, the channel vector of a user $k$ communicating with a base station (BS) equipped with $M$ antennas. The eigendecomposition of $\widetilde{\hbox{\boldmath$\Sigma$}}_k$ is given as \begin{equation}\label{eq:eigdecomp_true} \widetilde{\hbox{\boldmath$\Sigma$}}_k = {{\mathbb f} U}_k \widetilde{\hbox{\boldmath$\Lambda$}}_k {{\mathbb f} U}_k^{{\sf H}}, \end{equation} where ${{\mathbb f} U}_k$ is the unitary matrix of eigenvectors (${{\mathbb f} U}_k^{{\sf H}} {{\mathbb f} U}_k=\mathbf{I}_M$) and $\widetilde{\hbox{\boldmath$\Lambda$}}_k$ is the diagonal matrix of eigenvalues. We are interested in obtaining a (approximate) common eigenstructure\footnote{We use the terms ``common eigenstructure", ``common eigenvectors set", and ``common virtual beams set" interchangeably.} among all covariances $\{ \widetilde{\hbox{\boldmath$\Sigma$}}_k \}_{k=1}^K$ given random samples $\{{{\mathbb f} H}_k\}_{k=1}^K$. If the covariance matrices are jointly diagonalizable, i.e. if there exists a unitary matrix ${{\mathbb f} U}^c$ such that ${{\mathbb f} U}_1={{\mathbb f} U}_2=\ldots={{\mathbb f} U}_K={{\mathbb f} U}^c$, then it is desirable to obtain ${{\mathbb f} U}^c$ as the common eigenstructure. If the covariances are \textit{not} jointly diagonalizable, then we want to obtain a unitary matrix ${{\mathbb f} U}^\star$ as the common eigenstructure that best diagonalizes the covariances. To have a systematic way of estimating the common eigenstructure, we first impose the joint diagonalizability criterion on the estimation model, in which each covariance is decomposed as \begin{equation}\label{eq:decomp} \hbox{\boldmath$\Sigma$}_k = {{\mathbb f} U} \hbox{\boldmath$\Lambda$}_k {{\mathbb f} U}^{{\sf H}}, \end{equation} where ${{\mathbb f} U}=[{{\mathbb f} u}_1,\ldots,{{\mathbb f} u}_M]\in {\mathbb C}^{M\times M}$ is a unitary matrix (${{\mathbb f} U}^{{\sf H}} {{\mathbb f} U}=\mathbf{I}_M$) representing the to-be-estimated common eigenstructure (or CVB set) and, assuming non-singular covariances for simplicity, $\hbox{\boldmath$\Lambda$}_k = \text{diag}(\hbox{\boldmath$\lambda$}_k)$ is a diagonal matrix with positive diagonal elements given in the vector $\hbox{\boldmath$\lambda$}_k$ for $k=1,\ldots,K$. Note the difference between the true covariance $\widetilde{\hbox{\boldmath$\Sigma$}}_k$ in \eqref{eq:eigdecomp_true} and the hypothetical covariance $\hbox{\boldmath$\Sigma$}_k$ in \eqref{eq:decomp}. Then, given random samples as in \eqref{eq:vector_observations}, we solve a maximum-likelihood optimization to estimate ${{\mathbb f} U}$. This approach can be seen as a \textit{deliberately mismatched} ML estimation method: the covariances do \textit{not} generally share the same set of eigenvectors, but we impose this property by adopting the model in \eqref{eq:decomp}. Notice that by imposing such model mismatch, we look for the common unitary matrix ${{\mathbb f} U}$ that best fits the sample data ${{\mathbb f} H}_1,\ldots, {{\mathbb f} H}_K$, where ``best fit" is to be interpreted in the Maximum Likelihood sense. Observing the random samples $\{ {{\mathbb f} H}_k \}_{k=1}^K$, one can write the likelihood function as a function of the hypothetical covariance matrices according to \begin{equation}\label{eq:ML_func} \begin{aligned} & p\left(\{{{\mathbb f} H}_k \}_{k=1}^K |\{ \hbox{\boldmath$\Sigma$}_k\}_{k=1}^K \right) =\\ &\prod_{k=1}^{K} \frac{1}{(2\pi)^{\frac{M}{2}} {\mathop{\rm det}} (\hbox{\boldmath$\Sigma$}_k)^{\frac{N}{2}}}\exp \left( -\frac{1}{2N}\text{trace}({{\mathbb f} H}_k^{{\sf H}} \hbox{\boldmath$\Sigma$}_k^{-1} {{\mathbb f} H}_k)\right)=\\ & \prod_{k=1}^{K} \frac{1}{(2\pi)^{\frac{M}{2}} {\mathop{\rm det}} (\hbox{\boldmath$\Sigma$}_k)^{\frac{N}{2}}}\exp \left( -\frac{1}{2}\text{trace}( \hbox{\boldmath$\Sigma$}_k^{-1} \widehat{\hbox{\boldmath$\Sigma$}}_k )\right), \end{aligned} \end{equation} where we have defined $\widehat{\hbox{\boldmath$\Sigma$}}_k:= \frac{1}{N} {{\mathbb f} H}_k {{\mathbb f} H}_k^{{\sf H}}$, as the sample covariance of the $k$-th process. Taking the $-\log(\cdot)$ of the likelihood function, scaling it, omitting constant terms, and replacing $\hbox{\boldmath$\Sigma$}_k$ with ${{\mathbb f} U} \hbox{\boldmath$\Lambda$}_k {{\mathbb f} U}^{{\sf H}}$ from \eqref{eq:decomp}, one can show that maximizing the likelihood function is equivalent to minimizing the following ML cost as a function of the parameters ${{\mathbb f} U}$ and $ \{ \hbox{\boldmath$\lambda$}_k \}_{k=1}^K$: \begin{equation}\label{eq:cost_func} \begin{aligned} & {\cal C} \left({{\mathbb f} U} , \{ \hbox{\boldmath$\lambda$}_k \}_{k=1}^K \right) =\\ &\scalebox{0.92}{$\sum_{k=1}^{K} \log{\mathop{\rm det}}\, ({{\mathbb f} U} \text{diag}(\hbox{\boldmath$\lambda$}_k) {{\mathbb f} U}^{{\sf H}}) + \text{trace} \left( ({{\mathbb f} U} \text{diag}(\hbox{\boldmath$\lambda$}_k) {{\mathbb f} U}^{{\sf H}})^{-1} \widehat{\hbox{\boldmath$\Sigma$}}_k \right).$} \end{aligned} \end{equation} Since ${\mathop{\rm det}}\, ({{\mathbb f} U} \text{diag}(\hbox{\boldmath$\lambda$}_k) {{\mathbb f} U}^{{\sf H}}) =\nolinebreak {\mathop{\rm det}}\, (\text{diag}(\hbox{\boldmath$\lambda$}_k) ),$ and \scalebox{0.95}{$\text{trace} \left( ({{\mathbb f} U} \text{diag}(\hbox{\boldmath$\lambda$}_k) {{\mathbb f} U}^{{\sf H}})^{-1} \widehat{\hbox{\boldmath$\Sigma$}}_k \right) = \nolinebreak \text{trace} \left( \text{diag}(\hbox{\boldmath$\lambda$}_k)^{-1} {{\mathbb f} U}^{{\sf H}} \widehat{\hbox{\boldmath$\Sigma$}}_k{{\mathbb f} U} \right),$} we have \begin{equation} {\cal C} \left({{\mathbb f} U} , \{ \hbox{\boldmath$\lambda$}_k \}_{k=1}^K \right) = \sum_{m,k} \log \hbox{\boldmath$\lambda$}_{k,m} + \frac{{{\mathbb f} u}_m^{{\sf H}} \widehat{\hbox{\boldmath$\Sigma$}}_k {{\mathbb f} u}_m}{\hbox{\boldmath$\lambda$}_{k,m}}, \end{equation} where $\hbox{\boldmath$\lambda$}_{k,m}> 0$ is the $m$-th element of $\hbox{\boldmath$\lambda$}_k$. The ML optimization problem then can be formulated as \begin{equation}\label{eq:ML_formula_1} \begin{aligned} &\underset{\{ {{\mathbb f} u}_m \}_{m=1}^M ,\{\hbox{\boldmath$\lambda$}_k \}_{k=1}^K}{\text{minimize}} && \sum_{m,k} \log \hbox{\boldmath$\lambda$}_{k,m} + \frac{{{\mathbb f} u}_m^{{\sf H}} \widehat{\hbox{\boldmath$\Sigma$}}_k {{\mathbb f} u}_m}{\hbox{\boldmath$\lambda$}_{k,m}}\\ &\hspace{6mm} \text{subject to} && {{\mathbb f} u}_m^{{\sf H}} {{\mathbb f} u}_n = \delta_{m,n} \end{aligned} \end{equation} For simplicity we assume that all sample covariance matrices are non-singular, such that ${{\mathbb f} u}_m^{{\sf H}} \widehat{\hbox{\boldmath$\Sigma$}}_k {{\mathbb f} u}_m>0$ for any ${{\mathbb f} u}_m$. As a result, it is easy to show that, for given $\{ {{\mathbb f} u}_m\}_{m=1}^M$, the function $g(x)=\log x + \frac{{{\mathbb f} u}_m^{{\sf H}} \widehat{\hbox{\boldmath$\Sigma$}}_k {{\mathbb f} u}_m}{x},\, x>0$ achieves its minimum at $x={{\mathbb f} u}_m^{{\sf H}}\widehat{ \hbox{\boldmath$\Sigma$}}_k {{\mathbb f} u}_m$. Therefore, we take the minimization in \eqref{eq:ML_formula_1} first with respect to $\hbox{\boldmath$\lambda$}_{k,m}, \, k\in [K],\, m\in [M]$ (for an integer $n$, we define $[n]:=\{1,\ldots,n \}$) and transform \eqref{eq:ML_formula_1} to \begin{equation}\label{eq:ML_formula_2} \begin{aligned} &\underset{\{ {{\mathbb f} u}_m \}_{m=1}^M }{\text{minimize}} && f({{\mathbb f} U})=\sum_{m,k} \log \left( {{\mathbb f} u}_m^{{\sf H}} \widehat{\hbox{\boldmath$\Sigma$}}_k {{\mathbb f} u}_m\right) \\ & \text{subject to} && {{\mathbb f} u}_m^{{\sf H}} {{\mathbb f} u}_n = \delta_{m,n} \end{aligned}\tag{$P_{ ML}$} \end{equation} This presents an optimization problem over the manifold of unitary matrices ${\cal U} = \{ {{\mathbb f} U} \in {\mathbb C}^{M\times M}:\, {{\mathbb f} U}^{{\sf H}} {{\mathbb f} U} =\mathbf{I}_M \}$. To solve \ref{eq:ML_formula_2}, we propose a gradient projection method and show that it converges to a stationary point of the cost function $f({{\mathbb f} U})$. \subsection{Intermezzo: Jointly Diagonalizable Covariances and Global Optimality of the CES} In the discussion above, we said that for jointly diagonalizable covariances, we with to obtain the CES ${{\mathbb f} U}^c$ as a result of our estimation method. In order to show that the ML problem \eqref{eq:ML_formula_2} gives a reasonable framework to satisfy this property, here we prove that for jointly diagonalizable covariances and by assuming sample covariances to have converged ($\widehat{ \hbox{\boldmath$\Sigma$}}_k = \hbox{\boldmath$\Sigma$}_k$), the CES ${{\mathbb f} U}^c$ is in fact a global minimizer of $P_{ML}$. Let the set of covariances $\hbox{\boldmath$\Sigma$}_k,~k\in [K]$ to be decomposed as \begin{equation}\label{eq:commut_cov} \hbox{\boldmath$\Sigma$}_k = {{\mathbb f} U}^c \hbox{\boldmath$\Lambda$}_k {{\mathbb f} U}^{c\, {{\sf H}}}, \end{equation} where ${{\mathbb f} U}^c \in {\mathbb C}^{M\times M}$ denotes the CES. Assume $\widehat{ \hbox{\boldmath$\Sigma$}}_k = \hbox{\boldmath$\Sigma$}_k$, and consider the following definition. \begin{definition}[Majorization] For ${{\mathbb f} x} \in {\mathbb R}^{M}$, define ${{\mathbb f} x}^{\downarrow}$ as the vector containing the elements of ${{\mathbb f} x}$ in descending order. Let ${{\mathbb f} y} \in {\mathbb R}^M$ be another vector such that $\sum_{i=1}^{M}{{\mathbb f} x}_i =\sum_{i=1}^{M}{{\mathbb f} y}_i $. We say ${{\mathbb f} x}$ \textit{majorizes} ${{\mathbb f} y}$ (${{\mathbb f} x} \succ {{\mathbb f} y}$) iff \[ \sum_{i=1}^{m}{{\mathbb f} x}^{\downarrow}_i \ge \sum_{i=1}^{m}{{\mathbb f} y}^{\downarrow}_i, \] for all $m\in [M]$. \end{definition} We have the following theorem on global optimality of ${{\mathbb f} U}^c$. \begin{theorem}\label{thm_global_opt} Let $\hbox{\boldmath$\Sigma$}_k,\, k=1,\ldots, K$ be a set of jointly diagonalizable covariance matrices as in \eqref{eq:commut_cov} and consider the optimization problem \begin{equation}\label{eq:opt_new} \underset{{{\mathbb f} U}}{\text{minimize}}\, f({{\mathbb f} U})=\sum_{m,k} \log \left( {{\mathbb f} u}_m^{{\sf H}} \hbox{\boldmath$\Sigma$}_k {{\mathbb f} u}_m \right) ~\text{s.t.}~ {{\mathbb f} u}_m^{{\sf H}} {{\mathbb f} u}_n = \delta_{m,n}. \end{equation} Then ${{\mathbb f} U}^\star = {{\mathbb f} U}^c$ is a global solution of \eqref{eq:opt_new}. \end{theorem} \begin{proof} For any unitary ${{\mathbb f} U}$, define the vector $\hbox{\boldmath$\sigma$}_k ({{\mathbb f} U}) \in {\mathbb R}^M$ where $[\hbox{\boldmath$\sigma$}_k ({{\mathbb f} U})]_{m} = {{\mathbb f} u}_m^{{\sf H}} \hbox{\boldmath$\Sigma$}_k {{\mathbb f} u}_m$. In particular $\hbox{\boldmath$\sigma$}_k ({{\mathbb f} U}^c)$ is the vector of eigenvalues of $\hbox{\boldmath$\Sigma$}_k$. Using the properties of eigenvalue decomposition one can show $\hbox{\boldmath$\sigma$}_k ({{\mathbb f} U}^c) \succ \hbox{\boldmath$\sigma$}_k ({{\mathbb f} U})$ for all ${{\mathbb f} U} \in {\cal U}$ and all $k\in [K]$. In addition, the function $h({{\mathbb f} x}) = \sum_i \log ({{\mathbb f} x}_i)$ is Schur-concave \cite{peajcariaac1992convex} and therefore $\sum_m \log ([\hbox{\boldmath$\sigma$}_k ({{\mathbb f} U}^c)]_m) \le \sum_m \log ([\hbox{\boldmath$\sigma$}_k ({{\mathbb f} U})]_m)$. Hence, $f ({{\mathbb f} U}^c)\le f ({{\mathbb f} U})$ for all ${{\mathbb f} U} \in {\cal U}$, proving ${{\mathbb f} U}^c$ to be the global minimizer of $f({{\mathbb f} U})$ over ${\cal U}$. \end{proof} \section{ML via Projected Gradient Descent} The projected gradient descent method (PGD) is a well-known iterative optimization algorithm \cite{bertsekas2015convex}. Starting from an initial point ${{\mathbb f} U}^{(0)}$, this method consists of the two following steps per iteration: \begin{equation}\label{eq:PGD_step1} \widetilde{{{\mathbb f} U}}^{(t)} = {{\mathbb f} U}^{(t)} - \alpha_t \nabla f({{\mathbb f} U}^{(t)})\tag{Gradient Step} \end{equation} \begin{equation}\label{eq:PGD_step2} {{\mathbb f} U}^{(t+1)} = {\cal P}_{{\cal U}} (\widetilde{{{\mathbb f} U}}^{(t)}) \tag{Projection Step} \end{equation} where $\alpha_t>0$ is a step size, $\nabla f({{\mathbb f} U}^{(t)})\in {\mathbb C}^{M\times M}$ is the gradient of $f$ at ${{\mathbb f} U}^{(t)}$ and ${\cal P}_{{\cal U}}:{\mathbb C}^{M\times M}\to {\cal U} $ denotes the orthogonal projection operator onto the set of unitary matrices. The explicit expression of this operator is given in \cite{manton2002optimization}; Nevertheless, we derive it here through the following lemma for the sake of completeness. \begin{lemma} Let ${{\mathbb f} V} \in {\mathbb C}^{M\times M}$ be a matrix with singular value decomposition ${{\mathbb f} V} = {{\mathbb f} S} {{\mathbb f} D} {{\mathbb f} T}^{{\sf H}}$ where ${{\mathbb f} S}$ and ${{\mathbb f} T}$ are unitary matrices of left and right eigenvectors and ${{\mathbb f} D}=\text{diag}({{\mathbb f} d})$ is non-negative diagonal. Then, the orthogonal projection of ${{\mathbb f} V}$ onto the set of unitary matrices is given by ${\cal P}_{{\cal U}}({{\mathbb f} V}) ={{\mathbb f} S} {{\mathbb f} T}^{{\sf H}}$. \end{lemma} \begin{proof} The orthogonal projection of ${{\mathbb f} V}$ is given by the minimizer of $g({{\mathbb f} U})= \Vert {{\mathbb f} V} -{{\mathbb f} U}\Vert_F^2$ over the set of unitary matrices, where $\Vert\cdot \Vert_F^2$ denotes Frobenius norm and ${{\mathbb f} U}^{{\sf H}}{{\mathbb f} U}=\mathbf{I}_M$. We can write \begin{equation}\label{eq:fro} \begin{aligned} g({{\mathbb f} U})= \Vert {{\mathbb f} V} -{{\mathbb f} U}\Vert_F^2 & = \Vert {{\mathbb f} U}\Vert_{\sf F}^2 + \Vert {{\mathbb f} V} \Vert_{\sf F}^2 - 2\field{R}\{ \langle{{\mathbb f} V} , {{\mathbb f} U} \rangle \}\\ & =M + \Vert {{\mathbb f} V} \Vert_{\sf F}^2 - 2\field{R}\{ \langle{{\mathbb f} V} , {{\mathbb f} U} \rangle \}, \end{aligned} \end{equation} where the inner product is defined as $\langle{{\mathbb f} V} , {{\mathbb f} U} \rangle = \text{trace} ({{\mathbb f} U}^{{\sf H}} {{\mathbb f} V}) $ and we used the fact that $ \text{trace} ({{\mathbb f} U} {{\mathbb f} U}^{{\sf H}})=\text{trace}(\mathbf{I}_M)=M$. According to Von Neumann's trace inequality we have $| \langle{{\mathbb f} V} , {{\mathbb f} U} \rangle |=|\text{trace}\left( {{\mathbb f} U}^{{\sf H}}{{\mathbb f} V} \right)|\le \langle {{\mathbb f} s}_{{{\mathbb f} U}},{{\mathbb f} d} \rangle, $\cite{mirsky1975trace}, where ${{\mathbb f} s}$ denotes the singular values vector of ${{\mathbb f} U}$. In the special case where ${{\mathbb f} U}$ is unitary, we have ${{\mathbb f} s}_{{{\mathbb f} U}} = [1,\ldots,1]^{\sf T}$ and $|\langle{{\mathbb f} V} , {{\mathbb f} U} \rangle |\le \langle {{\mathbb f} s}_{{{\mathbb f} U}},{{\mathbb f} d} \rangle = \sum_i {{\mathbb f} d}_i.$ Now, using \eqref{eq:fro} we have $ g({{\mathbb f} U})\ge M +\Vert {{\mathbb f} V}\Vert_{\sf F}^2 -2\sum_i {{\mathbb f} d}_i,$ where the right hand side of the inequality is independent of ${{\mathbb f} U}$. We show that the lower bound on $g({{\mathbb f} U})$ is achieved by ${{\mathbb f} U}^\star = {{\mathbb f} S} {{\mathbb f} T}^{{\sf H}}$. This is seen by the fact that \begin{equation} \begin{aligned} g({{\mathbb f} S} {{\mathbb f} T}^{{\sf H}} )&= M + \Vert {{\mathbb f} S} {{\mathbb f} D} {{\mathbb f} T}^{{\sf H}}\Vert_{\sf F}^2 - 2\field{R}\{ \langle{{\mathbb f} S} {{\mathbb f} D} {{\mathbb f} T}^{{\sf H}} , {{\mathbb f} S} {{\mathbb f} T}^{{\sf H}} \rangle \}\\ & = M + \Vert {{\mathbb f} S} {{\mathbb f} D} {{\mathbb f} T}^{{\sf H}}\Vert_{\sf F}^2 - 2\text{trace}({{\mathbb f} D})\\ &= M + \Vert{{\mathbb f} V} \Vert_{\sf F}^2 - 2\sum_i {{\mathbb f} d}_i,. \end{aligned} \end{equation} This completes the proof. \end{proof} This lemma provides an explicit formula for the orthogonal projection of a matrix into the unitary set as \begin{equation}\label{eq:orthogonal_proj} {\cal P}_{{\cal U}}:{\mathbb C}^{M\times M}\to {\cal U},\, {{\mathbb f} V} = {{\mathbb f} S} {{\mathbb f} D} {{\mathbb f} T}^{{\sf H}}\to {{\mathbb f} S} {{\mathbb f} T}^{{\sf H}}. \end{equation} The following theorem presents the main result of this work. \begin{theorem}\label{th:convergance} Let ${{\mathbb f} U}^{(0)}\in {\cal U}$ be an initial point and consider the gradient projection update rule \begin{equation}\label{eq:grad_proj} {{\mathbb f} U}^{(t+1)} = {\cal P}_{{\cal U}} \left( {{\mathbb f} U}^{(t)} - \alpha_t \nabla f ({{\mathbb f} U}^{(t)}) \right),\,\, t=0,1,\ldots, \end{equation} with $\alpha_t \in (0,\frac{1}{L})$ for all $t$, where $L$ is the Lipschitz constant of $\nabla f({{\mathbb f} U})$. Then the sequence $\{ {{\mathbb f} U}^{(t)},\, t=0,1,\ldots \}$ converges to a stationary point of $f({{\mathbb f} U})$. \end{theorem} In order to prove Theorem \ref{th:convergance}, we need to first prove some useful properties of the ML optimization problem. \subsection{Lipschitz Continuity of the Cost Gradient} As a first step, we prove that the cost gradient $\nabla f({{\mathbb f} U})$ is Lipschitz continuous over ${\cal U}$. Note that the manifold ${\cal U}$ is a subset of the closed convex ball ${\cal B}$ (${\cal U} \subset {\cal B}$) where ${\cal B} = \{ {{\mathbb f} U}\, :\, \Vert {{\mathbb f} U} \Vert_{\sf F}\le \sqrt{M} \}.$ One can show that $f({{\mathbb f} U})$ has Lipschitz continuous gradient over ${\cal B}$, i.e. there exists a constant $L$, such that $\Vert \nabla f({{\mathbb f} U} )- \nabla f({{\mathbb f} U}') \Vert_{\sf F} \le L \Vert {{\mathbb f} U} - {{\mathbb f} U}' \Vert_{\sf F},$ for all ${{\mathbb f} U},{{\mathbb f} U}' \in {\cal B}$. One way to prove this is by showing that the Hessian of $f({{\mathbb f} U})$ has bounded operator norm over ${\cal B}$. Define the complex Hessian as the $M^2\times M^2$ square matrix $\nabla^2 f({{\mathbb f} U})$ whose elements are given as \cite{gunning2009analytic} $ [\nabla^2 f({{\mathbb f} U})]_{m,n} = \frac{\partial^2\, f({{\mathbb f} U})}{\partial [\vec ({{\mathbb f} U})]_m \partial [\vec ({{\mathbb f} U})]_n^\ast },$ for $m,n\in [M^2]$, where $\vec ({{\mathbb f} U}) = [{{\mathbb f} u}_1^{\sf T},\ldots,{{\mathbb f} u}_M^{\sf T}]^{\sf T}$ is the vectorized version of ${{\mathbb f} U}$. Simple calculations show that the Hessian is a block-diagonal matrix with its $m$-th diagonal block given as \begin{align}\label{eq:Hess_f_0} {{\mathbb f} D}_f^{(m)} = \sum_{k=1}^K \frac{\widehat{\hbox{\boldmath$\Sigma$}}_k^{\sf T}}{{{\mathbb f} u}_m^{{\sf H}} \widehat{\hbox{\boldmath$\Sigma$}}_k {{\mathbb f} u}_m} - \sum_{k=1}^K \frac{\left( \widehat{\hbox{\boldmath$\Sigma$}}_k {{\mathbb f} u}_m {{\mathbb f} u}_m^{{\sf H}} \widehat{\hbox{\boldmath$\Sigma$}}_k \right)^{\sf T}}{\left({{\mathbb f} u}_m^{{\sf H}} \widehat{\hbox{\boldmath$\Sigma$}}_k {{\mathbb f} u}_m\right)^2}, \end{align} \noindent so that we have $\nabla^2 f({{\mathbb f} U}) = \text{blkdiag}\left( {{\mathbb f} D}_f^{(1)},\ldots,{{\mathbb f} D}_f^{(M)} \right)$. Note that both terms on the right-hand-side of \eqref{eq:Hess_f_0} are PSD and therefore ${{\mathbb f} D}_f^{(m)}$ is the difference of two PSD matrices. \begin{lemma} The Hessian matrix $\nabla^2 f({{\mathbb f} U})$ is bounded in operator norm. \end{lemma} \begin{proof} Define the operator norm of a matrix ${{\mathbb f} A}\in {\mathbb C}^{M^2\times M^2}$ as $\Vert {{\mathbb f} A} \Vert_{op} = \underset{\Vert{{\mathbb f} x} \Vert=1}{\sup} \frac{\Vert {{\mathbb f} A} {{\mathbb f} x} \Vert}{\Vert{{\mathbb f} x} \Vert}$, where $\Vert \cdot \Vert$ is the $\ell_2$ norm. For a block-diagonal matrix such as $\nabla^2 f ({{\mathbb f} U}) $, the operator norm is equal to the maximum of the operator norms of each individual block, i.e. $ \Vert \nabla^2 f ({{\mathbb f} U}) \Vert_{op} = \underset{m}{\max}~ \Vert {{\mathbb f} D}_f^{(m)} \Vert_{op}$. Using \eqref{eq:Hess_f_0}, the operator norm of block $m$ is bounded as \scalebox{0.97}{$\Vert {{\mathbb f} D}_f^{(m)} \Vert_{op} \le \max \left\{ \sum_k \frac{\Vert \widehat{\hbox{\boldmath$\Sigma$}}_k \Vert_{op}}{{{\mathbb f} u}_m^{{\sf H}} \widehat{\hbox{\boldmath$\Sigma$}}_k {{\mathbb f} u}_m}\,,\, \sum_k\frac{\Vert \widehat{\hbox{\boldmath$\Sigma$}}_k{{\mathbb f} u}_m \Vert^2}{({{\mathbb f} u}_m^{{\sf H}} \widehat{\hbox{\boldmath$\Sigma$}}_k {{\mathbb f} u}_m)^2} \right\}$} where we used the fact that ${{\mathbb f} D}_f^{(m)}$ is the difference of two PSD matrices and therefore its operator norm is bounded by the maximum of the operator norms of the two. Also, since the matrix $\widehat{\hbox{\boldmath$\Sigma$}}_k {{\mathbb f} u}_m {{\mathbb f} u}_m^{{\sf H}} \widehat{\hbox{\boldmath$\Sigma$}}_k$ is of rank one, its operator norm is equal to $\Vert \widehat{\hbox{\boldmath$\Sigma$}}_k{{\mathbb f} u}_m \Vert^2$. Finally, since sample covariances are assumed to be non-singular, both arguments in $\max\{\cdot\}$ are finite. Taking the maximum over all $M$ bounds also results in a finite value and the proof is complete. \end{proof} Next we show that the Lipschitz constant of $\nabla f ({{\mathbb f} U})$ is related to the operator norm of $\nabla^2 f({{\mathbb f} U})$. \begin{lemma} For a twice differentiable function $f({{\mathbb f} U})$ with Hessian bounded in operator norm as $\Vert \nabla^2 f({{\mathbb f} U}) \Vert_{op} \le L$ for all ${{\mathbb f} U}$, the gradient $\nabla f ({{\mathbb f} U})$ is Lipschitz continuous with Lipschitz constant $L$. \end{lemma} \begin{proof} We show that the Lipschitz continuity condition $\Vert \nabla f({{\mathbb f} U})-\nabla f({{\mathbb f} U}') \Vert_{\sf F}\le L \Vert {{\mathbb f} U} -{{\mathbb f} U}' \Vert_{\sf F} $ holds for any ${{\mathbb f} U},\, {{\mathbb f} U}'$ via the following sequence of inequalities: \begin{equation}\label{eq:Ineq_5} \begin{aligned} \Vert \nabla f({{\mathbb f} U})-\nabla f({{\mathbb f} U}') \Vert_{\sf F} &\overset{(a)}{\le} \underset{\Vert {{\mathbb f} B} \Vert_{\sf F}=1}{\sup} \left| \left\langle {{\mathbb f} B} , \nabla f({{\mathbb f} U})-\nabla f({{\mathbb f} U}') \right\rangle \right|\\ & \hspace{-32mm}\scalebox{0.89}{$=\underset{\Vert {{\mathbb f} B} \Vert_{\sf F}=1}{\sup} \left| \left\langle \vec({{\mathbb f} B}) ,\int_{0}^1 \nabla^2 f \left({{\mathbb f} U}'+t({{\mathbb f} U} - {{\mathbb f} U}')\right)\text{vec}({{\mathbb f} U} - {{\mathbb f} U}')\, dt \right\rangle \right|$} \\ & \hspace{-32mm}\scalebox{0.9}{$\le \underset{\Vert {{\mathbb f} B} \Vert_{\sf F}=1}{\sup}\int_{0}^1 \left| \left\langle \vec({{\mathbb f} B}) , \nabla^2 f \left({{\mathbb f} U}'+t({{\mathbb f} U} - {{\mathbb f} U}')\right)\text{vec}({{\mathbb f} U} - {{\mathbb f} U}')\, \right\rangle \right|dt$}\\ & \hspace{-32mm}\scalebox{0.85}{$\overset{(b)}{\le}\underset{\Vert {{\mathbb f} B} \Vert_{\sf F}=1}{\sup}\underset{t\in [0,1]}{\sup} \Vert \nabla^2 f \left({{\mathbb f} U}'+t({{\mathbb f} U} - {{\mathbb f} U}')\right) \Vert_{op} \Vert \text{vec}({{\mathbb f} U} - {{\mathbb f} U}') \Vert \Vert \vec({{\mathbb f} B}) \Vert$}\\ & \hspace{-32mm}\scalebox{0.81}{$=\underset{t\in [0,1]}{\sup} \Vert \nabla^2 f \left({{\mathbb f} U}'+t({{\mathbb f} U} - {{\mathbb f} U}')\right) \Vert_{op} \Vert \text{vec}({{\mathbb f} U} - {{\mathbb f} U}') \Vert $}\overset{(c)}{\le } L \Vert {{\mathbb f} U} - {{\mathbb f} U}' \Vert_{\sf F}. \\ \end{aligned} \end{equation} Inequality $(a)$ holds by taking into account the fact that for the particular value of ${{\mathbb f} B}$ as ${{\mathbb f} B}_0 = \frac{\nabla f({{\mathbb f} U})-\nabla f({{\mathbb f} U}') }{\Vert \nabla f({{\mathbb f} U})-\nabla f({{\mathbb f} U}') \Vert_{\sf F} }$ we have $ \langle {{\mathbb f} B}_0 , \nabla f({{\mathbb f} U})-\nabla f({{\mathbb f} U}') \rangle = \Vert \nabla f({{\mathbb f} U})-\nabla f({{\mathbb f} U}') \Vert_{\sf F}.$ Inequality $(b)$ comes from an application of the Cauchy-Schwarz inequality and the definition of the operator norm. Finally, inequality $(c)$ holds due to the assumption on the boundedness of the Hessian operator norm, i.e. $\Vert\nabla^2 f({{\mathbb f} U})\Vert_{op}\le L$ for all ${{\mathbb f} U}$, and the proof is complete. \end{proof} The next lemma emerges as a consequence of the discussion above. \begin{lemma} For any pair of matrices ${{\mathbb f} U},{{\mathbb f} U}'\in {\cal B}$ we have \begin{equation}\label{eq:descent} f({{\mathbb f} U})\le f({{\mathbb f} U}') + \langle \nabla f({{\mathbb f} U}'),{{\mathbb f} U} - {{\mathbb f} U}'\rangle + \frac{L}{2}\Vert{{\mathbb f} U}-{{\mathbb f} U}' \Vert_{\sf F}^2, \end{equation} where $L$ is the gradient Lipschitz constant. \end{lemma} \begin{proof} See \cite{bertsekas2015convex}, proposition 6.1.2. \end{proof} This lemma is used as a tool to prove the convergence of PGD to a stationary point, as outlined by Theorem \ref{th:convergance}. \subsection{\textbf{Proof of Theorem \ref{th:convergance}}} We start by replacing ${{\mathbb f} U}'$ with ${{\mathbb f} U}^{(t)}$ in \eqref{eq:descent} and defining the RHS of \eqref{eq:descent} as the proxy function \begin{equation}\label{eq:proxy} \scalebox{0.92}{$f_{\sf proxy}^{(t)} ({{\mathbb f} U})= f({{\mathbb f} U}^{(t)}) + \langle \nabla f({{\mathbb f} U}^{(t)}),{{\mathbb f} U} - {{\mathbb f} U}^{(t)}\rangle + \frac{L}{2}\Vert{{\mathbb f} U}-{{\mathbb f} U}^{(t)} \Vert_{\sf F}^2,$} \end{equation} at point ${{\mathbb f} U}^{(t)}$, such that we have \begin{equation}\label{eq:proxy_bound} f({{\mathbb f} U})\le f_{\sf proxy}^{(t)} ({{\mathbb f} U}) \end{equation} for all ${{\mathbb f} U}\in {\cal U}$ and $ f({{\mathbb f} U}^{(t)})= f_{\sf proxy}^{(t)} ({{\mathbb f} U}^{(t)}). $ Now let us show that the point ${{\mathbb f} U}^{(t+1)}={\cal P}_{{\cal U}} \left( {{\mathbb f} U}^{(t)} - \alpha_t \nabla f ({{\mathbb f} U}^{(t)}) \right)$ is indeed a minimizer of $f_{\sf proxy}^{(t)}({{\mathbb f} U})$ over ${\cal U}$ with $\alpha_t=\frac{1}{L}$. To see this, note that we can expand $f_{\sf proxy}^{(t)}({{\mathbb f} U})$ as $ f_{\sf proxy}^{(t)}({{\mathbb f} U}) = \langle \nabla f({{\mathbb f} U}^{(t)}),{{\mathbb f} U}\rangle-L \langle {{\mathbb f} U}^{(t)},{{\mathbb f} U} \rangle + {\sf const.}, $ for all unitary ${{\mathbb f} U}$. Then, minimizing $f_{\sf proxy}^{(t)}({{\mathbb f} U}) $ is equivalent to the maximization problem: $\underset{{{\mathbb f} U}^{{\sf H}} {{\mathbb f} U} = \mathbf{I}_{M}}{\text{maximize}}\,\, \langle {{\mathbb f} U}^{(t)} -\frac{1}{L}\nabla f({{\mathbb f} U}^{(t)}),{{\mathbb f} U} \rangle$. But the maximum of this objective is achieved at the point ${{\mathbb f} U}^\star = {{\mathbb f} S}_t {{\mathbb f} T}_t^{{\sf H}}$, where ${{\mathbb f} S}_t$ and ${{\mathbb f} T}_t$ are matrices of left and right eigenvectors in the SVD form $ {{\mathbb f} U}^{(t)} -\frac{1}{L}\nabla f({{\mathbb f} U}^{(t)}) = {{\mathbb f} S}_t{{\mathbb f} D}_t {{\mathbb f} T}_t^{{\sf H}}$. But this implies that ${{\mathbb f} U}^\star = {{\mathbb f} S}_t {{\mathbb f} T}_t^{{\sf H}} = {\cal P}_{{\cal U}} \left( {{\mathbb f} U}^{(t)} - \frac{1}{L}\nabla f ({{\mathbb f} U}^{(t)}) \right)={{\mathbb f} U}^{(t+1)}$ and ${{\mathbb f} U}^{(t+1)}$ is a minimizer of $f_{\sf proxy}^{(t)}({{\mathbb f} U})$. The chain of inequalities below immediately follows: \begin{equation}\label{eq:ineqs} \scalebox{0.92}{$f({{\mathbb f} U}^{(t+1)})\overset{(a)}{\le } f_{\sf proxy}^{(t)}({{\mathbb f} U}^{(t+1)})\overset{(b)}{\le } f_{\sf proxy}^{(t)}({{\mathbb f} U}^{(t)})\overset{(c)}{= } f({{\mathbb f} U}^{(t)}),$} \end{equation} where $(a)$ follows from \eqref{eq:proxy_bound}, $(b)$ follows from the fact that ${{\mathbb f} U}^{(t+1)}$ is aminimizer of $f_{\sf proxy}^{(t)}({{\mathbb f} U})$, and $(c)$ is a result of $f({{\mathbb f} U}^{(t)})= f_{\sf proxy}^{(t)} ({{\mathbb f} U}^{(t)})$. Therefore we have $f({{\mathbb f} U}^{(t+1)}) \le f({{\mathbb f} U}^{(t)}), $ for $t=0,1,\ldots$ and since $f({{\mathbb f} U})$ is bounded from below, the gradient projection sequence $\{ {{\mathbb f} U}^{(t)},\, t=0,1,\ldots \}$ converges to a stationary point of $f({{\mathbb f} U})$. $\hfill \QED$ \begin{figure}[t] \centering \includegraphics[ width=0.37\textwidth]{Cost_Global.pdf} \caption{The average cost $f({{\mathbb f} U})$ as a function of the number of samples, for the solution of PGD ${{\mathbb f} U}^\star (N)$ and the global optimum ${{\mathbb f} U}^c$. We have set $M=16$ and $K=8$. } \label{fig:cost_global} \end{figure} \section{Simulation Results} To study the performance of our proposed method, in this section we provide some empirical results. \subsection{Jointly Diagonalizable Covariances} The case of jointly diagonalizable covariances is especially interesting, as we know by Theorem \ref{thm_global_opt} that the global optimum of the ML problem is given by the shared CES ${{\mathbb f} U}^c$ (see \eqref{eq:commut_cov}). In order to assess the performance of our method, we compare the ML cost as a function of the number of random samples per process $N$, to the cost at the global minimum. Consider a signal dimension (number of antennas) $M=16$ and a number of processes (number of users) $K=8$. We generate a random unitary matrix as the CES ${{\mathbb f} U}^c$ by calculating the eigenvectors of a random matrix of size $M\times M$ with i.i.d complex Gaussian elements. Also, for each process $k\in [K]$, we generate a random vector of eigenvalues $\hbox{\boldmath$\lambda$}_k$ with i.i.d, positive elements given as $\hbox{\boldmath$\lambda$}_{k,m}=|\rho_m|$ where $\rho_m \sim {\cal N} (0,1)$. Then we form the covariance matrix of user $k$ as $\widetilde{\hbox{\boldmath$\Sigma$}}={{\mathbb f} U}^c \text{diag}(\hbox{\boldmath$\lambda$}_k){{\mathbb f} U}^{c\, {{\sf H}}}$. We also normalize the covariances to have trace equal to one. This way we have randomly generated covariances with a shared CES. Now, having the covariances, we can generate random realizations for each process for different sample sizes $N$. We run a Monte Carlo simulation with $1000$ iterations, at each iteration generating covariances as stated above, then for each sample size $N$ we run our proposed PGD method which converges to a point ${{\mathbb f} U}^\star (N)$ (explicitly noting the dependence on $N$). Then, we average the cost function ${{\mathbb f} U}^\star (N)$ in \eqref{eq:ML_formula_2} over the Monte Carlo iterations for each value of $N$ and compare it to the average cost at the global optimum $f({{\mathbb f} U}^c )$. Note that the latter of course is not a function of $N$. The PGD method is initialized with a random unitary matrix. Theorem \ref{th:convergance} guarantees convergence to a stationary point when the step size is chosen as $\alpha_t\in (0,1/L)$. However, practically we can be more ambitious by choosing larger step sizes as $\alpha_t = \frac{\alpha_0}{t},~t=1,2,\ldots$ with $\alpha_0 =2$ and our simulation results show that even with this choice, PGD converges. Fig. \ref{fig:cost_global} illustrates the result. We denote the solution of our method with ${{\mathbb f} U}^\star (N)$, to explicitly highlight its dependence on the number of samples $N$. The interesting fact about this result is that, as the number of samples gets larger, the PGD with random initialization always converges to the global optimum, as its cost value is the same as that in the optimal point ${{\mathbb f} U}^c$. This is an empirical evidence for the convergence of our proposed method to the global solution for jointly diagonalizable covariances. \begin{figure}[t] \centering \includegraphics[ width=0.386\textwidth]{eta_func.pdf} \caption{The average diagonalization metric as function of the sampling ratio $N/M$, for the solution of our proposed PGD method vs the JADE method. We set $M=16$ and $K=8$. } \label{fig:eta_func} \end{figure} \subsection{Non-Jointly Diagonalizable Covariances} As a different scenario, we consider covariances that are not jointly diagonalizable. This is done by generating a different random unitary eigenvector matrix for each process separately as $\widetilde{\hbox{\boldmath$\Sigma$}}={{\mathbb f} U}_k \text{diag}(\hbox{\boldmath$\lambda$}_k){{\mathbb f} U}_k^{ {{\sf H}}}$. The eigenvalue vectors $\hbox{\boldmath$\lambda$}_k$ are generated as before and we normalize the covariances to have unit trace. So, in this case we do not have a CES and the PGD method yields a unitary matrix that approximately jointly diagonalizes the covariances. Since we do not have the global optimum in this case, we compare our method to the JADE algorithm, which is a classic Jacobian-based method for joint covariance diagonalization (we do not explain the details of this method here due to space limitations and refer the reader to \cite{cardoso1993blind} for a full account). One way to measure the performance of joint diagonalization methods is by defining the metric $\eta : {\mathbb C}^{M\times M}\to [0,1]$: \begin{equation}\label{eq:eta} \eta ({{\mathbb f} U}) = 1-\frac{1}{K}\sum_{k=1}^K\frac{\Vert \text{diag}({{\mathbb f} U}^{{\sf H}} \hbox{\boldmath$\Sigma$}_k{{\mathbb f} U}) \Vert}{\Vert \hbox{\boldmath$\Sigma$}_k \Vert_{\sf F}}, \end{equation} where $\text{diag}(\cdot)$ with a matrix argument as in \eqref{eq:eta} denotes the $M$-dim vector of the diagonal elements of its argument. The smaller the value of $\eta ({{\mathbb f} U})$ is, the better ${{\mathbb f} U}$ jointly diagonalizes the covariances. In the extreme case, If ${{\mathbb f} U}$ diagonalizes all covariance matrices, we have $\eta ({{\mathbb f} U})=0$. The joint diagonalization metric is empirically averaged over $1000$ Monte Carlo simulations and for different sample sizes for the solutions of our proposed PGD method and the JADE method. Fig. \ref{fig:eta_func} illustrates the results. It clearly shows that for the ranges of sample sizes considered here, the proposed PGD method outperforms the classic JADE method, yielding smaller values of the diagonalization metric on average, and hence achieving a better joint diagonalization of the covariances. \subsection{CES for ULA: PGD vs the Fourier Basis} For a ULA it is usually taken for granted that the CES is given by the Fourier basis vectors. While this is true in an asymptotic sense thanks to the Szeg{\"o} theorem, it does not hold for small to moderate array sizes. We conclude our simulations by showing that, in fact the unitary basis produced by our proposed method better diagonalizes ULA covariances, compared to the DFT basis. \begin{figure}[t] \centering \includegraphics[ width=0.4\textwidth]{eta_U_vs_Fourier.pdf} \caption{The average diagonalization metric as function of the number of antennas $M$, for the solution of our proposed PGD method vs the Fourier basis. Here we have set $K=5$. } \label{fig:U_vs_F} \end{figure} We consider $K=5$ $M$-dimensional ULA covariances, generated randomly according to \eqref{eq:ch_cov_0} (see \cite{khalilsarai2018fdd} on randomly generating ULA covariances). Since each covariance is associated with a user that occupies a limited angular range as seen from the BS, we generate the covariances such that each of them has an ``effective" rank of $r_k=\text{effrank}(\widetilde{\hbox{\boldmath$\Sigma$}}_k)=\lceil\frac{M}{2} \rceil$. The effective rank is equivalent to the number of significant covariance eigenvalues as well as channel angular sparsity. We plot the expected joint diagonalization metric ${\mathbb E} [ \eta (\cdot) ]$ as a function of the number of antennas for the unitary matrix yielded by our method as well as for the Fourier basis ${{\mathbb f} F}$ where $[{{\mathbb f} F}]_{m,n}=\frac{1}{\sqrt{M}}e^{j2\pi \frac{(m-1)(n-1)}{M}},\, m,n\in [M]$. We assume that the sample covariance has converged, i.e. $\widehat{ \hbox{\boldmath$\Sigma$}}_k = \widehat{ \hbox{\boldmath$\Sigma$}}_k $ for all $k$. The expectation ${\mathbb E} [ \eta (\cdot) ]$ is taken over random covariance realizations and is calculated empirically over 100 Monte-Carlo loops. Fig. \ref{fig:U_vs_F} illustrates the result. As we can see, the basis given by the PGD method achieves better diagonalization (smaller $\eta$ values) than the Fourier basis, which shows that using our method is in fact preferable even for the diagonalization of ULA covariances. Also, as $M$ increases, the two bases have closer diagonalization metrics since we are approaching the asymptotic regime in which the Fourier basis approximately diagonalizes the Toeplitz ULA covariances. \section{Conclusion} We presented a framework for estimating the common eigenstructure for a set of covariance matrices. Our approach was based on maximizing the likelihood function of the postulated common eigenvectors set, given random vector realizations. We proposed the PGD method and proved its convergence to a stationary point of the likelihood function. Our empirical results illustrated that the proposed method converges to the global optimum when the covariances indeed share a common eigenvectors set. It outperforms the classic JADE method in all ranges of sample sizes. It also performs better than the Fourier basis in diagonalizing covariances generated by a ULA geometry in a multi-user MIMO setup. {\small \bibliographystyle{IEEEtran} \subsection*{}% \hbox{\hspace{.05\hsize}\defbox{\medskip#1\bigskip}}% \subsection*{}} \def{} \def{\hbox{\it\tiny T}}{{\hbox{\it\tiny T}}} \def{\text{diag}}{{\text{diag}}} \def\phantom{-}{\phantom{-}} \def\buildrel{\rm w}\over\longrightarrow{\buildrel{\rm w}\over\longrightarrow} \def\buildrel{\rm v}\over\longrightarrow{\buildrel{\rm v}\over\longrightarrow} \def\tvlimit#1{\buildrel{\scriptscriptstyle #1}\over\Longrightarrow} \def\buildrel{\rm d}\over\longrightarrow{\buildrel{\rm d}\over\longrightarrow} \def\goes#1{\buildrel{#1}\over\longrightarrow} \def\wiggles#1{\buildrel{#1}\over\leadsto} \def\mathsf{tr}{\mathsf{tr}} \def{\rm rank\,}{{\rm rank\,}} \def\hbox{\rm deg\thinspace}{\hbox{\rm deg\thinspace}} \def{\rm sign}{{\rm sign}} \def{\rm supp\,}{{\rm supp\,}} \newsavebox{\junk} \savebox{\junk}[1.6mm]{\hbox{$|\!|\!|$}} \def{\usebox{\junk}}{{\usebox{\junk}}} \def{\mathop{\rm det}}{{\mathop{\rm det}}} \def\mathop{\rm lim\ sup}{\mathop{\rm lim\ sup}} \def\mathop{\rm lim\ inf}{\mathop{\rm lim\ inf}} \def\mathop{\rm arg\, min}{\mathop{\rm arg\, min}} \def\mathop{\rm arg\, max}{\mathop{\rm arg\, max}} \def\field{A}{{\sf A}} \def{\sf K}{{\sf K}} \def{\sf U}{{\sf U}} \def{\sf V}{{\sf V}} \def{\sf W}{{\sf W}} \def{\mathchoice{\sf X}\sfX{\hbox{\scriptsize\sf X}}\smallsfX}{{\sf X}} \def{\mathchoice{\sf Y}\sfY{\hbox{\scriptsize\sf Y}}\smallsfY}{{\sf Y}} \def{\sf Z}{{\sf Z}} \def{\mathbb y}{{\cal B}({\mathchoice{\sf Y}\sfY{\hbox{\scriptsize\sf Y}}\smallsfY})} \def\tinyplus{\vbox{\hrule width 3pt depth -1.5pt height 1.9pt \vskip -1.5pt \hbox{\hskip 1.3pt\vrule height 3pt depth 0pt width .4pt}}} \def{\sf X^{\rm z}}{{\sf X^{\rm z}}} \def{\cal B}(\state^\hbox{\rm\tiny z}){{\cal B}({\mathchoice{\sf X}\sfX{\hbox{\scriptsize\sf X}}\smallsfX}^\hbox{\rm\tiny z})} \def{\sf X^{{\rm z}_{ \tinyplus}}}{{\sf X^{{\rm z}_{ \tinyplus}}}} \def({\sf X},{\cal B}({{\mathbb f} X}),{{\mathbb f} m}){({\sf X},{\cal B}({{\mathbb f} X}),{{\mathbb f} m})} \def{\mathbb x}{{{\cal B}({\mathchoice{\sf X}\sfX{\hbox{\scriptsize\sf X}}\smallsfX})}} \def{\cal B}(\state^{{\rm z}_{\tinyplus}} )} \def\bxplus{{{\cal B}^+(\state)}{{\cal B}({\mathchoice{\sf X}\sfX{\hbox{\scriptsize\sf X}}\smallsfX}^{{\rm z}_{\tinyplus}} )} \def\bxplus{{{\cal B}^+({\mathchoice{\sf X}\sfX{\hbox{\scriptsize\sf X}}\smallsfX})}} \newcommand{\field}[1]{\mathbb{#1}} \def\field{R}_+{\field{R}_+} \def\field{R}{\field{R}} \def\field{A}{\field{A}} \def\mbox{\rm{\large{1}}}{\mbox{\rm{\large{1}}}} \def\mbox{\rm{\large{0}}}{\mbox{\rm{\large{0}}}} \def\field{I}{\field{I}} \def\field{T}{\field{T}} \def\field{Z}{\field{Z}} \def\field{Z}{\field{Z}} \def\field{Z}_+{\field{Z}_+} \def\field{Q}{\field{Q}} \def\field{C}{\field{C}} \def{\check{{\cal F}}}{{\check{{\cal F}}}} \def{\check{{\mathchoice{\bfatom}{\bfatom}{\alpha}{\alpha}}}}{{\check{{\mathchoice{\bfatom}{\bfatom}{\alpha}{\alpha}}}}} \def\check{{\sf E}}{\check{{\sf E}}} \def\check{\Phi}{\check{\Phi}} \def\check{\bfmath{\Phi}}{\check{\bfmath{\Phi}}} \def\check{{\sf P}}{\check{{\sf P}}} \def\cProb\!{\check{{\sf P}}\!} \def\check{\Phi}{\check{\Phi}} \def\check{\pi}{\check{\pi}} \def\check{A}{\check{A}} \def{\check{G}}{{\check{G}}} \def{\check{P}}{{\check{P}}} \def{\cal B}^+({\check{\state}}){{\cal B}^+({\check{\state}})} \def{\check{\state}}{{\check{{\mathchoice{\sf X}\sfX{\hbox{\scriptsize\sf X}}\smallsfX}}}} \def{\cal B}(\cstate){{\cal B}({\check{\state}})} \def\bfmath{\Phi}^{\Lambda}{\bfmath{\Phi}^{\Lambda}} \def{\mathbb A}{{\mathbb A}} \def{\mathbb B}{{\mathbb B}} \def{\mathbb C}{{\mathbb C}} \def{\mathbb D}{{\mathbb D}} \def{\mathbb E}{{\mathbb E}} \def{\mathbb F}{{\mathbb F}} \def{\mathbb G}{{\mathbb G}} \def{\mathbb H}{{\mathbb H}} \def{\mathbb I}{{\mathbb I}} \def{\mathbb J}{{\mathbb J}} \def{\mathbb K}{{\mathbb K}} \def{\mathbb L}{{\mathbb L}} \def{\mathbb M}{{\mathbb M}} \def{\mathbb N}{{\mathbb N}} \def{\mathbb O}{{\mathbb O}} \def{\mathbb P}{{\mathbb P}} \def{\mathbb Q}{{\mathbb Q}} \def{\mathbb R}{{\mathbb R}} \def{\mathbb S}{{\mathbb S}} \def{\mathbb T}{{\mathbb T}} \def{\mathbb U}{{\mathbb U}} \def{\mathbb V}{{\mathbb V}} \def{\mathbb W}{{\mathbb W}} \def{\mathbb X}{{\mathbb X}} \def{\mathbb Y}{{\mathbb Y}} \def{\mathbb Z}{{\mathbb Z}} \def{\mathbb a}{{\mathbb a}} \def{\mathbb b}{{\mathbb b}} \def{\mathbb c}{{\mathbb c}} \def{\mathbb d}{{\mathbb d}} \def{\mathbb e}{{\mathbb e}} \def{\mathbb f}{{\mathbb f}} \def{\mathbb g}{{\mathbb g}} \def{\mathbb h}{{\mathbb h}} \def{\mathbb i}{{\mathbb i}} \def{\mathbb j}{{\mathbb j}} \def{\mathbb k}{{\mathbb k}} \def{\mathbb l}{{\mathbb l}} \def{\mathbb m}{{\mathbb m}} \def{\mathbb n}{{\mathbb n}} \def{\mathbb o}{{\mathbb o}} \def{\mathbb p}{{\mathbb p}} \def{\mathbb q}{{\mathbb q}} \def{\mathbb r}{{\mathbb r}} \def{\mathbb s}{{\mathbb s}} \def{\mathbb t}{{\mathbb t}} \def{\mathbb u}{{\mathbb u}} \def{\mathbb v}{{\mathbb v}} \def{\mathbb w}{{\mathbb w}} \def{\mathbb x}{{\mathbb x}} \def{\mathbb y}{{\mathbb y}} \def{\mathbb z}{{\mathbb z}} \def{\bf A}{{{\mathbb f} A}} \def{\bf B}{{{\mathbb f} B}} \def{\bf C}{{{\mathbb f} C}} \def{\bf D}{{{\mathbb f} D}} \def{\bf E}{{{\mathbb f} E}} \def{\bf F}{{{\mathbb f} F}} \def{\bf G}{{{\mathbb f} G}} \def{\bf H}{{{\mathbb f} H}} \def{\bf I}{{{\mathbb f} I}} \def{\bf J}{{{\mathbb f} J}} \def{\bf K}{{{\mathbb f} K}} \def{\bf L}{{{\mathbb f} L}} \def{\bf M}{{{\mathbb f} M}} \def{\bf N}{{{\mathbb f} N}} \def{\bf O}{{{\mathbb f} O}} \def{\bf P}{{{\mathbb f} P}} \def{\bf Q}{{{\mathbb f} Q}} \def{\bf R}{{{\mathbb f} R}} \def{\bf S}{{{\mathbb f} S}} \def{\bf T}{{{\mathbb f} T}} \def{\bf U}{{{\mathbb f} U}} \def{\bf V}{{{\mathbb f} V}} \def{\bf W}{{{\mathbb f} W}} \def{\bf X}{{{\mathbb f} X}} \def{\bf Y}{{{\mathbb f} Y}} \def{\bf Z}{{{\mathbb f} Z}} \def{\bf a}{{{\mathbb f} a}} \def{\bf b}{{{\mathbb f} b}} \def{\bf c}{{{\mathbb f} c}} \def{\bf d}{{{\mathbb f} d}} \def{\bf e}{{{\mathbb f} e}} \def{\bf f}{{{\mathbb f} f}} \def{\bf g}{{{\mathbb f} g}} \def{\bf h}{{{\mathbb f} h}} \def{\bf i}{{{\mathbb f} i}} \def{\bf j}{{{\mathbb f} j}} \def{\bf k}{{{\mathbb f} k}} \def{\bf l}{{{\mathbb f} l}} \def{\bf m}{{{\mathbb f} m}} \def{\bf n}{{{\mathbb f} n}} \def{\bf o}{{{\mathbb f} o}} \def{\bf p}{{{\mathbb f} p}} \def{\bf q}{{{\mathbb f} q}} \def{\bf r}{{{\mathbb f} r}} \def{\bf s}{{{\mathbb f} s}} \def{\bf t}{{{\mathbb f} t}} \def{\bf u}{{{\mathbb f} u}} \def{\bf v}{{{\mathbb f} v}} \def{\bf w}{{{\mathbb f} w}} \def{\bf x}{{{\mathbb f} x}} \def{\bf y}{{{\mathbb f} y}} \def{\bf z}{{{\mathbb f} z}} \def{\mathfrak{A}}{{\mathfrak{A}}} \def{\mathfrak{B}}{{\mathfrak{B}}} \def{\mathfrak{C}}{{\mathfrak{C}}} \def{\mathfrak{D}}{{\mathfrak{D}}} \def{\mathfrak{E}}{{\mathfrak{E}}} \def{\mathfrak{F}}{{\mathfrak{F}}} \def{\mathfrak{G}}{{\mathfrak{G}}} \def{\mathfrak{H}}{{\mathfrak{H}}} \def{\mathfrak{I}}{{\mathfrak{I}}} \def{\mathfrak{J}}{{\mathfrak{J}}} \def{\mathfrak{K}}{{\mathfrak{K}}} \def{\mathfrak{L}}{{\mathfrak{L}}} \def{\mathfrak{M}}{{\mathfrak{M}}} \def{\mathfrak{N}}{{\mathfrak{N}}} \def{\mathfrak{O}}{{\mathfrak{O}}} \def{\mathfrak{P}}{{\mathfrak{P}}} \def{\mathfrak{Q}}{{\mathfrak{Q}}} \def{\mathfrak{R}}{{\mathfrak{R}}} \def{\mathfrak{S}}{{\mathfrak{S}}} \def{\mathfrak{T}}{{\mathfrak{T}}} \def{\mathfrak{U}}{{\mathfrak{U}}} \def{\mathfrak{V}}{{\mathfrak{V}}} \def{\mathfrak{W}}{{\mathfrak{W}}} \def{\mathfrak{X}}{{\mathfrak{X}}} \def{\mathfrak{Y}}{{\mathfrak{Y}}} \def{\mathfrak{Z}}{{\mathfrak{Z}}} \def{\mathfrak a}{{\mathfrak a}} \def{\mathfrak b}{{\mathfrak b}} \def{\mathfrak c}{{\mathfrak c}} \def{\mathfrak d}{{\mathfrak d}} \def{\mathfrak e}{{\mathfrak e}} \def{\mathfrak f}{{\mathfrak f}} \def{\mathfrak g}{{\mathfrak g}} \def{\mathfrak h}{{\mathfrak h}} \def{\mathfrak i}{{\mathfrak i}} \def{\mathfrak j}{{\mathfrak j}} \def{\mathfrak k}{{\mathfrak k}} \def{\mathfrak l}{{\mathfrak l}} \def{\mathfrak m}{{\mathfrak m}} \def{\mathfrak n}{{\mathfrak n}} \def{\mathfrak o}{{\mathfrak o}} \def{\mathfrak p}{{\mathfrak p}} \def{\mathfrak q}{{\mathfrak q}} \def{\mathfrak r}{{\mathfrak r}} \def{\mathfrak s}{{\mathfrak s}} \def{\mathfrak t}{{\mathfrak t}} \def{\mathfrak u}{{\mathfrak u}} \def{\mathfrak v}{{\mathfrak v}} \def{\mathfrak w}{{\mathfrak w}} \def{\mathfrak x}{{\mathfrak x}} \def{\mathfrak y}{{\mathfrak y}} \def{\mathfrak z}{{\mathfrak z}} \def{\mathscr{A}}{{\mathscr{A}}} \def{\mathscr{B}}{{\mathscr{B}}} \def{\mathscr{C}}{{\mathscr{C}}} \def{\mathscr{D}}{{\mathscr{D}}} \def{\mathscr{E}}{{\mathscr{E}}} \def{\mathscr{F}}{{\mathscr{F}}} \def{\mathscr{G}}{{\mathscr{G}}} \def{\mathscr{H}}{{\mathscr{H}}} \def{\mathscr{I}}{{\mathscr{I}}} \def{\mathscr{J}}{{\mathscr{J}}} \def{\mathscr{K}}{{\mathscr{K}}} \def{\mathscr{L}}{{\mathscr{L}}} \def{\mathscr{M}}{{\mathscr{M}}} \def{\mathscr{N}}{{\mathscr{N}}} \def{\mathscr{O}}{{\mathscr{O}}} \def{\mathscr{P}}{{\mathscr{P}}} \def{\mathscr{Q}}{{\mathscr{Q}}} \def{\mathscr{R}}{{\mathscr{R}}} \def{\mathscr{S}}{{\mathscr{S}}} \def{\mathscr{T}}{{\mathscr{T}}} \def{\mathscr{U}}{{\mathscr{U}}} \def{\mathscr{V}}{{\mathscr{V}}} \def{\mathscr{W}}{{\mathscr{W}}} \def{\mathscr{X}}{{\mathscr{X}}} \def{\mathscr{Y}}{{\mathscr{Y}}} \def{\mathscr{Z}}{{\mathscr{Z}}} \def{\mathscr a}{{\mathscr a}} \def{\mathscr b}{{\mathscr b}} \def{\mathscr c}{{\mathscr c}} \def{\mathscr d}{{\mathscr d}} \def{\mathscr e}{{\mathscr e}} \def{\mathscr f}{{\mathscr f}} \def{\mathscr g}{{\mathscr g}} \def{\mathscr h}{{\mathscr h}} \def{\mathscr i}{{\mathscr i}} \def{\mathscr j}{{\mathscr j}} \def{\mathscr k}{{\mathscr k}} \def{\mathscr l}{{\mathscr l}} \def{\mathscr m}{{\mathscr m}} \def{\mathscr n}{{\mathscr n}} \def{\mathscr o}{{\mathscr o}} \def{\mathscr p}{{\mathscr p}} \def{\mathscr q}{{\mathscr q}} \def{\mathscr r}{{\mathscr r}} \def{\mathscr s}{{\mathscr s}} \def{\mathscr t}{{\mathscr t}} \def{\mathscr u}{{\mathscr u}} \def{\mathscr v}{{\mathscr v}} \def{\mathscr w}{{\mathscr w}} \def{\mathscr x}{{\mathscr x}} \def{\mathscr y}{{\mathscr y}} \def{\mathscr z}{{\mathscr z}} \def{\mathtt{A}}{{\mathtt{A}}} \def{\mathtt{B}}{{\mathtt{B}}} \def{\mathtt{C}}{{\mathtt{C}}} \def{\mathtt{D}}{{\mathtt{D}}} \def{\mathtt{E}}{{\mathtt{E}}} \def{\mathtt{F}}{{\mathtt{F}}} \def{\mathtt{G}}{{\mathtt{G}}} \def{\mathtt{H}}{{\mathtt{H}}} \def{\mathtt{I}}{{\mathtt{I}}} \def{\mathtt{J}}{{\mathtt{J}}} \def{\mathtt{K}}{{\mathtt{K}}} \def{\mathtt{L}}{{\mathtt{L}}} \def{\mathtt{M}}{{\mathtt{M}}} \def{\mathtt{N}}{{\mathtt{N}}} \def{\mathtt{O}}{{\mathtt{O}}} \def{\mathtt{P}}{{\mathtt{P}}} \def{\mathtt{Q}}{{\mathtt{Q}}} \def{\mathtt{R}}{{\mathtt{R}}} \def{\mathtt{S}}{{\mathtt{S}}} \def{\mathtt{T}}{{\mathtt{T}}} \def{\mathtt{U}}{{\mathtt{U}}} \def{\mathtt{V}}{{\mathtt{V}}} \def{\mathtt{W}}{{\mathtt{W}}} \def{\mathtt{X}}{{\mathtt{X}}} \def{\mathtt{Y}}{{\mathtt{Y}}} \def{\mathtt{Z}}{{\mathtt{Z}}} \def{\mathtt a}{{\mathtt a}} \def{\mathtt b}{{\mathtt b}} \def{\mathtt c}{{\mathtt c}} \def{\mathtt d}{{\mathtt d}} \def{\mathtt e}{{\mathtt e}} \def{\mathtt f}{{\mathtt f}} \def{\mathtt g}{{\mathtt g}} \def{\mathtt h}{{\mathtt h}} \def{\mathtt i}{{\mathtt i}} \def{\mathtt j}{{\mathtt j}} \def{\mathtt k}{{\mathtt k}} \def{\mathtt l}{{\mathtt l}} \def{\mathtt m}{{\mathtt m}} \def{\mathtt n}{{\mathtt n}} \def{\mathtt o}{{\mathtt o}} \def{\mathtt p}{{\mathtt p}} \def{\mathtt q}{{\mathtt q}} \def{\mathtt r}{{\mathtt r}} \def{\mathtt s}{{\mathtt s}} \def{\mathtt t}{{\mathtt t}} \def{\mathtt u}{{\mathtt u}} \def{\mathtt v}{{\mathtt v}} \def{\mathtt w}{{\mathtt w}} \def{\mathtt x}{{\mathtt x}} \def{\mathtt y}{{\mathtt y}} \def{\mathtt z}{{\mathtt z}} \def{\sf A}{{\sf A}} \def{\sf B}{{\sf B}} \def{\sf C}{{\sf C}} \def{\sf D}{{\sf D}} \def{\sf E}{{\sf E}} \def{\sf F}{{\sf F}} \def{\sf G}{{\sf G}} \def{\sf H}{{\sf H}} \def{\sf I}{{\sf I}} \def{\sf J}{{\sf J}} \def{\sf K}{{\sf K}} \def{\sf L}{{\sf L}} \def{\sf M}{{\sf M}} \def{\sf N}{{\sf N}} \def{\sf O}{{\sf O}} \def{\sf P}{{\sf P}} \def{\sf Q}{{\sf Q}} \def{\sf R}{{\sf R}} \def{\sf S}{{\sf S}} \def{\sf T}{{\sf T}} \def{\sf U}{{\sf U}} \def{\sf V}{{\sf V}} \def{\sf W}{{\sf W}} \def{\sf X}{{\sf X}} \def{\sf Y}{{\sf Y}} \def{\sf Z}{{\sf Z}} \def{\sf a}{{\sf a}} \def{\sf b}{{\sf b}} \def{\sf c}{{\sf c}} \def{\sf d}{{\sf d}} \def{\sf e}{{\sf e}} \def{\sf f}{{\sf f}} \def{\sf g}{{\sf g}} \def{\sf h}{{\sf h}} \def{\sf i}{{\sf i}} \def{\sf j}{{\sf j}} \def{\sf k}{{\sf k}} \def{\sf l}{{\sf l}} \def{\sf m}{{\sf m}} \def{\sf n}{{\sf n}} \def{\sf o}{{\sf o}} \def{\sf p}{{\sf p}} \def{\sf q}{{\sf q}} \def{\sf r}{{\sf r}} \def{\sf s}{{\sf s}} \def{\sf t}{{\sf t}} \def{\sf u}{{\sf u}} \def{\sf v}{{\sf v}} \def{\sf w}{{\sf w}} \def{\sf x}{{\sf x}} \def{\sf y}{{\sf y}} \def{\sf z}{{\sf z}} \def\bfmath#1{{\mathchoice{\mbox{\boldmath$#1$}}% {\mbox{\boldmath$#1$}}% {\mbox{\boldmath$\scriptstyle#1$}}% {\mbox{\boldmath$\scriptscriptstyle#1$}}}} \def\bfmath{a}{\bfmath{a}} \def\bfmath{b}{\bfmath{b}} \def\bfmath{d}{\bfmath{d}} \def\bfmath{e}{\bfmath{e}} \def\bfmath{m}{\bfmath{m}} \def\bfmath{q}{\bfmath{q}} \def\bfmath{r}{\bfmath{r}} \def\bfmath{v}{\bfmath{v}} \def\bfmath{x}{\bfmath{x}} \def\bfmath{y}{\bfmath{y}} \def\bfmath{u}{\bfmath{u}} \def\bfmath{w}{\bfmath{w}} \def\bfmath{\widehat w}{\bfmath{{\hat w}}} \def\bfmath{z}{\bfmath{z}} \def\bfmath{A}{\bfmath{A}} \def\bfmath{B}{\bfmath{B}} \def\bfmath{C}{\bfmath{C}} \def\bfmath{D}{\bfmath{D}} \def\bfmath{E}{\bfmath{E}} \def\bfmath{F}{\bfmath{F}} \def\bfmath{G}{\bfmath{G}} \def\bfmath{H}{\bfmath{H}} \def\bfmath{I}{\bfmath{I}} \def\bfmath{{\hat I}}{\bfmath{{\hat I}}} \def\bfmath{\haL}{\bfmath{\haL}} \def\bfmath{L}{\bfmath{L}} \def\bfmath{M}{\bfmath{M}} \def\bfmath{N}{\bfmath{N}} \def\bfmath{Q}{\bfmath{Q}} \def\bfmath{R}{\bfmath{R}} \def\bfmath{\bar{R}}{\bfmath{\bar{R}}} \def\bfmath{S}{\bfmath{S}} \def\bfmath{T}{\bfmath{T}} \def\bfmath{U}{\bfmath{U}} \def\bfmath{\widehat N}{\bfmath{\widehat N}} \def{\bfmath{$\widehat Q$}}{\bfmath{\widehat Q}} \def\bfmath{X}{\bfmath{X}} \def\tilde \bfmX{\bfmath{\widetilde{X}}} \def\bfmath{\widetilde{Q}}{\bfmath{\widetilde{Q}}} \def\tilde{\bfmath{q}}{\tilde{\bfmath{q}}} \def\bfmath{Y}{\bfmath{Y}} \def\bfmath{\widehat Y}{\bfmath{\widehat Y}} \def\hbox to 0pt{$\widehat{\bfmY}$\hss}\widehat{\phantom{\raise 1.25pt\hbox{$\bfmY$}}}{\bfmath{\hhaY}} \def\hbox to 0pt{$\widehat{\bfmY}$\hss}\widehat{\phantom{\raise 1.25pt\hbox{$\bfmY$}}}{\hbox to 0pt{$\widehat{\bfmath{Y}}$\hss}\widehat{\phantom{\raise 1.25pt\hbox{$\bfmath{Y}$}}}} \def\bfmath{V}{\bfmath{V}} \def\bfmath{W}{\bfmath{W}} \def\bfmath{\widehat W}{\bfmath{{\widehat W}}} \def\bfmath{Z}{\bfmath{Z}} \def{\bfmath{\widehat Z}}{{\bfmath{\widehat Z}}} \def\bfmath{\widehat w}{\bfmath{\widehat w}} \def\bfmath{\widehat y}{\bfmath{\widehat y}} \def\bfmath{\widehat z}{\bfmath{\widehat z}} \def{\bfmath{$\widehat Q$}}{\bfmath{\widehat Q}} \def\bfmath{\widehat S}{\bfmath{\widehat S}} \def\bfmath{\widehat U}{\bfmath{\widehat U}} \def\bfmath{\widehat W}{\bfmath{\widehat W}} \def{\mbox{\boldmath$\alpha$}}{\bfmath{\theta}} \def\bfmath{\Phi}{\bfmath{\Phi}} \def\bfmath{\eta}{\bfmath{\eta}} \def\bfmath{\pi}{\bfmath{\pi}} \def\bfmath{\phi}{\bfmath{\phi}} \def\bfmath{\psi}{\bfmath{\psi}} \def\bfmath{\rho}{\bfmath{\rho}} \def\bfmath{\zeta}{\bfmath{\zeta}} \def\bfmath{\Upsilon}{\bfmath{\Upsilon}} \def{\widehat{\Psi}}{{\widehat{\Psi}}} \def{\widehat{\Gamma}}{{\widehat{\Gamma}}} \def{\widehat{\Sigma}}{{\widehat{\Sigma}}} \def{\widehat{\bfPhi}}{{\widehat{\bfmath{\Phi}}}} \def{\widehat P}{{\widehat P}} \def{\hat c}{{\hat c}} \def\hat{z}{\hat{z}} \def{\hat {\i}}{{\hat {\i}}} \def{\hat f}{{\hat f}} \def{\hat g}{{\hat g}} \def{\hat m}{{\hat m}} \def{\hat h}{{\hat h}} \def{\hat p}{{\hat p}} \def{\hat q}{{\hat q}} \def{\bfmath{$\widehat Q$}}{{\bfmath{$\widehat Q$}}} \def\hat v{\hat v} \def{\hat w}{{\hat w}} \def{\hat y}{{\hat y}} \def{\widehat F}{{\widehat F}} \def{\hat I}{{\hat I}} \def{\hat J}{{\hat J}} \def\hat{N}{\hat{N}} \def{\widehat Q}{{\widehat Q}} \def{\widehat T}{{\widehat T}} \def{\widehat W}{{\widehat W}} \def{\hat\eta}{{\hat\eta}} \def{\hat\theta}{{\hat\theta}} \def{\hat\psi}{{\hat\psi}} \def{\hat\pi}{{\hat\pi}} \def{\hat\nu}{{\hat\nu}} \def{\hat\mu}{{\hat\mu}} \def{\hat\alpha}{{\hat\alpha}} \def{\hat\beta}{{\hat\beta}} \def{\hat\gamma}{{\hat\gamma}} \def{\hat\lambda}{{\hat\lambda}} \def{\hat\Lambda}{{\hat\Lambda}} \def{\rm A}{{\rm A}} \def{\rm B}{{\rm B}} \def{\rm C}{{\rm C}} \def{\rm C}{{\rm C}} \def{\rm E}{{\rm E}} \def{\rm H}{{\rm H}} \def{\rm I}{{\rm I}} \def{\rm M}{{\rm M}} \def{\rm P}{{\rm P}} \def{\rm Q}{{\rm Q}} \def{\rm d}{{\rm d}} \def{\rm g}{{\rm g}} \def{\rm k}{{\rm k}} \def{\rm u}{{\rm u}} \def{\rm x}{{\rm x}} \def{\rm P}{{\rm P}} \def{\rm E}{{\rm E}} \def\til={{\widetilde =}} \def{\widetilde \Phi}{{\widetilde \Phi}} \def{\widetilde N}{{\widetilde N}} \def{\widetilde P}{{\widetilde P}} \def{\widetilde Q}{{\widetilde Q}} \def\widetilde T{\widetilde T} \def\widetilde W{\widetilde W} \def{\tilde \mu}{{\tilde \mu}} \def{\tilde \pi}{{\tilde \pi}} \def{\bf\tilde X}{{{\mathbb f}\tilde X}} \def{\bf \tilde m}{{{\mathbb f} \tilde m}} \def{\tilde \theta}{{\tilde \theta}} \def\tilde e{\tilde e} \def\tilde \sigma{\tilde \sigma} \def\tilde \tau{\tilde \tau} \def{\cal A}{{\cal A}} \def{\cal B}{{\cal B}} \def{\cal C}{{\cal C}} \def{\cal D}{{\cal D}} \def{\cal E}{{\cal E}} \def{\cal F}{{\cal F}} \def{\cal G}{{\cal G}} \def{\cal H}{{\cal H}} \def{\cal J}{{\cal J}} \def{\cal I}{{\cal I}} \def{\cal K}{{\cal K}} \def{\cal L}{{\cal L}} \def{\cal M}{{\cal M}} \def{\cal N}{{\cal N}} \def{\cal O}{{\cal O}} \def{\cal P}{{\cal P}} \def{\cal Q}{{\cal Q}} \def{\cal R}{{\cal R}} \def{\cal S}{{\cal S}} \def{\cal T}{{\cal T}} \def{\cal U}{{\cal U}} \def{\cal V}{{\cal V}} \def{\cal W}{{\cal W}} \def{\cal X}{{\cal X}} \def{\cal Y}{{\cal Y}} \def{\cal Z}{{\cal Z}} \def{\mbox{\boldmath$\alpha$}}{{\mbox{\boldmath$\alpha$}}} \def{\mathchoice{\bfatom}{\bfatom}{\alpha}{\alpha}}{{\mathchoice{{\mbox{\boldmath$\alpha$}}}{{\mbox{\boldmath$\alpha$}}}{\alpha}{\alpha}}} \def\clG^+(\gamma){{\cal G}^+(\gamma)} \def\clG^+(s){{\cal G}^+(s)} \def{\mathbb{V}\sfa \sfr}{{\mathbb{V}{\sf a} {\sf r}}} \defA_+{A_+} \def\barAt#1{\overline{A_+(#1)}} \def\head#1{\subsubsection*{#1}} \def\atopss#1#2{\genfrac{}{}{0cm}{2}{#1}{#2}} \def\atop#1#2{\genfrac{}{}{0pt}{}{#1}{#2}} \def\FRAC#1#2#3{\genfrac{}{}{}{#1}{#2}{#3}} \def\fraction#1#2{{\mathchoice{\FRAC{0}{#1}{#2}}% {\FRAC{1}{#1}{#2}}% {\FRAC{3}{#1}{#2}}% {\FRAC{3}{#1}{#2}}}} \def\ddt{{\mathchoice{\FRAC{1}{d}{dt}}% {\FRAC{1}{d}{dt}}% {\FRAC{3}{d}{dt}}% {\FRAC{3}{d}{dt}}}} \def\ddr{{\mathchoice{\FRAC{1}{d}{dr}}% {\FRAC{1}{d}{dr}}% {\FRAC{3}{d}{dr}}% {\FRAC{3}{d}{dr}}}} \def\ddr{{\mathchoice{\FRAC{1}{d}{dy}}% {\FRAC{1}{d}{dy}}% {\FRAC{3}{d}{dy}}% {\FRAC{3}{d}{dy}}}} \def\ddtp{{\mathchoice{\FRAC{1}{d^{\hbox to 2pt{\rm\tiny +\hss}}}{dt}}% {\FRAC{1}{d^{\hbox to 2pt{\rm\tiny +\hss}}}{dt}}% {\FRAC{3}{d^{\hbox to 2pt{\rm\tiny +\hss}}}{dt}}% {\FRAC{3}{d^{\hbox to 2pt{\rm\tiny +\hss}}}{dt}}}} \def\ddalpha{{\mathchoice{\FRAC{1}{d}{d\alpha}}% {\FRAC{1}{d}{d\alpha}}% {\FRAC{3}{d}{d\alpha}}% {\FRAC{3}{d}{d\alpha}}}} \def\half{{\mathchoice{\FRAC{1}{1}{2}}% {\FRAC{1}{1}{2}}% {\FRAC{3}{1}{2}}% {\FRAC{3}{1}{2}}}} \def\third{{\mathchoice{\FRAC{1}{1}{3}}% {\FRAC{1}{1}{3}}% {\FRAC{3}{1}{3}}% {\FRAC{3}{1}{3}}}} \def\fourth{{\mathchoice{\FRAC{1}{1}{4}}% {\FRAC{1}{1}{4}}% {\FRAC{3}{1}{4}}% {\FRAC{3}{1}{4}}}} \def\threefourth{{\mathchoice{\FRAC{1}{3}{4}}% {\FRAC{1}{3}{4}}% {\FRAC{3}{3}{4}}% {\FRAC{3}{3}{4}}}} \def\sixth{{\mathchoice{\FRAC{1}{1}{6}}% {\FRAC{1}{1}{6}}% {\FRAC{3}{1}{6}}% {\FRAC{3}{1}{6}}}} \def\eighth{{\mathchoice{\FRAC{1}{1}{8}}% {\FRAC{1}{1}{8}}% {\FRAC{3}{1}{8}}% {\FRAC{3}{1}{8}}}} \def\buildrel{\rm dist}\over ={\buildrel{\rm dist}\over =} \def\mathbin{:=}{\mathbin{:=}} \def\mu^{\hbox{\rm \tiny Leb}}{\mu^{\hbox{\rm \tiny Leb}}} \def{\cal M}{{\cal M}} \def{\sf P}{{\sf P}} \def{\sf P\! }{{\sf P\! }} \def{\sf E}{{\sf E}} \def\taboo#1{{{}_{#1}P}} \def{\rm i.o.}{{\rm i.o.}} \def{\rm a.s.}{{\rm a.s.}} \def{\rm vec\, }{{\rm vec\, }} \def{\displaystyle\frac{1}{ N}}{{\displaystyle\frac{1}{ N}}} \def\average#1,#2,{{1\over #2} \sum_{#1}^{#2}} \def\hbox{ \rm \ enters\ }{\hbox{ \rm \ enters\ }} \def\eye(#1){{{\mathbb f}(#1)}\quad} \def\varepsilon{\varepsilon} \def\,\cdot\,{\,\cdot\,} \def{{\mathbb V}{\sf a}{\sf r}}{{{\mathbb V}{\sf a}{\sf r}}} \newtheorem{theorem}{{{\mathbb f} Theorem}} \newtheorem{proposition}{{{\mathbb f} Proposition}} \newtheorem{corollary}{Corollary} \newtheorem{definition}{{{\mathbb f} Definition}} \newtheorem{remark}{{{\mathbb f} Remark}} \newtheorem{lemma}{{{\mathbb f} Lemma}} \def\Lemma#1{Lemma~\ref{t:#1}} \def\Proposition#1{Proposition~\ref{t:#1}} \def\Theorem#1{Theorem~\ref{t:#1}} \def\Corollary#1{Corollary~\ref{t:#1}} \def\Remark#1{Remark~\ref{t:#1}} \def\Section#1{Section~\ref{#1}} \def\Figure#1{Figure~\ref{f:#1}} \def\Chapter#1{Chapter~\ref{c:#1}} \def\Appendix#1{Appendix~\ref{c:#1}} \def\eq#1/{(\ref{e:#1})} \newcommand{\inp}[2]{{\langle #1, #2 \rangle}} \newcommand{\inpr}[2]{{\langle #1, #2 \rangle}_{\mathbb R}} \newcommand{\beqn}[1]{\notes{#1}% \begin{eqnarray} \elabel{#1}} \newcommand{\end{eqnarray} }{\end{eqnarray} } \newcommand{\beq}[1]{\notes{#1}% \begin{equation}\elabel{#1}} \newcommand{\end{equation}}{\end{equation}} \def\begin{description}{\begin{description}} \def\end{description}{\end{description}} \def{\overline {a}}{{\overline {a}}} \def{\overline {c}}{{\overline {c}}} \def{\overline {f}}{{\overline {f}}} \def{\overline {g}}{{\overline {g}}} \def{\overline {h}}{{\overline {h}}} \def{\overline {l}}{{\overline {l}}} \def{\overline {m}}{{\overline {m}}} \def{\overline {n}}{{\overline {n}}} \def{\overline {p}}{{\overline {p}}} \newcommand{{\bar{x}}}{{\bar{x}}} \def{\overline {y}}{{\overline {y}}} \def{\overline {A}}{{\overline {A}}} \def{\overline {B}}{{\overline {B}}} \def{\overline {C}}{{\overline {C}}} \def{\overline {E}}{{\overline {E}}} \def{\overline {M}}{{\overline {M}}} \def{\overline {P}}{{\overline {P}}} \def{\overline {Q}}{{\overline {Q}}} \def{\overline {T}}{{\overline {T}}} \def{\underline{n}}{{\underline{n}}} \def{\underline{\rho}}{{\underline{\rho}}} \def{\overline{\atom}}{{\overline{{\mathchoice{\bfatom}{\bfatom}{\alpha}{\alpha}}}}} \def{\overline{\rho}}{{\overline{\rho}}} \def{\overline{\mu}}{{\overline{\mu}}} \def{\overline{\nu}}{{\overline{\nu}}} \def{\overline{\alpha}}{{\overline{\alpha}}} \def{\overline{\beta}}{{\overline{\beta}}} \def{\overline{\alpha}}{{\overline{\alpha}}} \def{\overline{\eta}}{{\overline{\eta}}} \def\overline{\bfPhi}{\overline{\bfmath{\Phi}}} \def\overline{\Phi}{\overline{\Phi}} \def\overline{\clF}{\overline{{\cal F}}} \def\overline{\sigma}{\overline{\sigma}} \def\overline{\Sigma}{\overline{\Sigma}} \def\overline{\tau}{\overline{\tau}} \def\hat{\sigma}{\hat{\sigma}} \def\hat{\tau}{\hat{\tau}} \def\hat{P}{\hat{P}} \def\hat{\Phi}{\hat{\Phi}} \def\hat{\bfPhi}{\hat{\bfmath{\Phi}}} \def\hat{\cal F}{\hat{\cal F}} \newcounter{rmnum} \newenvironment{romannum}{\begin{list}{{\upshape (\roman{rmnum})}}{\usecounter{rmnum} \setlength{\leftmargin}{14pt} \setlength{\rightmargin}{8pt} \setlength{\itemindent}{-1pt} }}{\end{list}} \newcounter{anum} \newenvironment{alphanum}{\begin{list}{{\upshape (\alph{anum})}}{\usecounter{anum} \setlength{\leftmargin}{14pt} \setlength{\rightmargin}{8pt} \setlength{\itemindent}{-1pt} }}{\end{list}} \newenvironment{assumptions}[1]{% \setcounter{keep_counter}{\value{#1}} \def#1{#1} \begin{list}{\sf\, (#1\arabic{#1})\mindex{Assumption (#1\arabic{#1})}\, }{\usecounter{#1}% \setlength{\rightmargin}{\leftmargin}} \setcounter{#1}{\value{keep_counter}}}% {\end{list}} \def\ass(#1:#2){(#1\ref{#1:#2})} \def\ritem#1{ \item[{\sf \ass(\current_model:#1)}] } \newenvironment{recall-ass}[1]{% \begin{description} \def\current_model{#1}}{ \end{description} } \def\Ebox#1#2{% \begin{center} \parbox{#1\hsize}{\epsfxsize=\hsize \epsfbox{#2}} \end{center}} \def\cite{meytwe92d}{\cite{meytwe92d}}
{'timestamp': '2020-06-01T02:08:57', 'yymm': '2005', 'arxiv_id': '2005.14457', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14457'}
arxiv
\section{Introduction}\label{introduction} A citation network refers to a (un)weighted, directed graph with the directed edges representing the citations, the edge weights (if exist) representing the number of citations between two nodes (e.g., papers, journals, authors). The impact made by the work done by an entity/node is measured using the impact factor. The impact factor of a journal for a particular year is measured by the total number of citations received by the articles published in the journal during the preceding two years, divided by the total number of articles published in that journal during the preceding two years \cite{impactfactor}. It is widely known and we shall also explain below that anomalous citations can purposefully manipulate impact factors. Since the Journal Impact Factor (JIF) is used to determine the importance of the contributions made by the journal in its own domain, it becomes essential to spot the anomalies in citation networks in order to understand if there is any misuse of citations to manipulate JIF and what are the reasons behind such misuse. Anomalous citations can be divided into two major categories: \begin{enumerate} \item \textbf{Self-citations}: They refer to the citations made by entities, i.e., journals or authors, to themselves, which can, in certain cases, lead to a disproportionate increase in JIF of the entity \cite{chakraborty2018good}. \item \textbf{Citation Stack}: It refers to the citation made by an entity, i.e., a journal or an author, to another entity, which can, in certain cases, be anomalously high and deviate from the usual behaviour of the entity \cite{chakraborty2018good}. \end{enumerate} \citet{fowler2007does} showed that the more one cites oneself (self-citation), the more others cite them. \citet{ioannidis2015generalized} classified the phenomenon of self-citation to different types -- direct, co-author, collaborative and coercive-induced self-citation. They further raised concerns over how inappropriate self-citations can affect impact factor, and suggested the usage of citation indices which are more foolproof to collusion using inappropriate self-citations. \citet{Bartneck2010DetectingHM} discussed how h-index can be inflated by authors by manipulating self-citation. \citet{SelfCitation}, in their study on analyzing the effect of excessive self-citation, argued for a new metric based on more transparency to help curb excessive self-citations, which may have a negative effect on our ability to truly analyze the impact and contributions of a scientific research in its research domain. However, limited work has been done in the field of analyzing citation stack. In 2011, Thomson Reuters \cite{ThomsonReuter} (currently known as Clarivate Analytics) suspended 33 journals from its Journal Citation Report due to a very high rate of self-citations, which contributed to as much as 90\% of the JIF of those journals. Therefore, anomalous citation detection is an important task in bibliometrics. \textbf{Our Contributions}: In this paper, we study a citation network at the journal level, define the notion of anomalies for scientific citation networks, and detect the anomalous journal pairs with focus on the anomalies from one entity to another (citation stack), along with a confidence score indicating the correctness of our prediction. We also categorize them into different types, and figure out possible reasons for such anomalies. The major contributions of this paper are mentioned below: \begin{itemize} \item We present a novel approach to detect the anomalies in a journal-level scientific citation network, and compare the results with the existing graph anomaly detection algorithms. \item Due to the lack of ground-truth for citation anomalies, we introduce JoCAD, a novel dataset which consists of synthetically injected citation anomalies (Section \ref{Datasets_JoCAD}), and use it to evaluate our methodology and compare the performance of our method with the state-of-the-art graph anomaly detection methods. \item Our model is able to predict the anomalous citation pairs with 100\% precision and 86\% F1-score (Section \ref{experimental-results}). \item We further categorize the anomalies detected into various types and dig out possible reasons to develop a deeper understanding of the root causes. \item We also analyze our model on the Microsoft Academic Search dataset, a real-world citation dataset (Section \ref{Experiment_MAS}), labeled by human annotators (Section \ref{human-annotator}). \item We interpret our results using a case study, wherein our results resemble the citations and Scimago Journal \& Country Rank (SJR) rating-change charts (Section \ref{case-study}). \item We further design an interactive web portal - `Journal Citations Analysis Tool' which can process any citation network and show journal-level anomalous citations. It helps the users analyze the temporal citation pattern of a given journal (Section \ref{portal}). \end{itemize} \noindent\fbox{% \parbox{0.78\columnwidth}{% \textbf{Reproducibility:} The codes and the datasets are available at: \url{http://bit.ly/anomalydata}.}} \section{Related Work}\label{relatedwork} The methodology used in this paper is closely related to the techniques used in anomaly detection in complex networks, and journal-level study of citation networks. Both these topics are well-studied; however, to the best of our knowledge, anomaly detection in journal-level citation network has not been studied yet. \subsection{Anomaly Detection in Complex Networks} Anomaly detection in networks is a widely explored area. \citet{Noble} proposed a subdue based method for anomaly detection in graphs. \citet{Hodge2004} wrote a survey of machine learning and statistical techniques for outlier detection, and categorized the outlier detection algorithms into three major types, namely, unsupervised clustering, supervised classification and semi-supervised recognition. The anomalies themselves have been categorized into two broad types \cite{chen} -- \textit{white crow} anomalies, which can be easily identified as outliers, and \textit{in-disguise} anomalies, which try to hide themselves and are thus difficult to detect. \citet{moon} presented OutRank, an algorithm to detect white-crow anomalies by assigning a similarity score to objects. \citet{Eberle2007MiningFS} detected in-disguise anomalies, which they called ``structural anomalies". We present two methods that cover both kinds of anomalies mentioned above. The box plot method in Section \ref{sec:method} detects white-crow anomalies as it identifies high number of citations between journals (which is an easily noticeable feature) after bucketing them according to their sizes. The time-series method in Section \ref{sec:method} detects in-disguise anomalies as it analyzes citations over the years and detects outliers from the usual behaviour (which can not be noticed from an overall study of the data). Anomalous groups in a citation network can be seen as communities with high citation activity with each other. \citet{Sun2005NeighborhoodFA} presented algorithms for community detection in bipartite graphs. They introduced two kinds of functions for the purpose of community detection and outlier detection. Oddball algorithm was proposed for unsupervised anomaly detection in weighted graphs, wherein each node is treated as an ego, and the neighbourhood network around it is studied as the egonet \cite{oddball}. \citet{Noble} detected anomalies in graph-based data by categorizing them in two ways - anomalous sub-structures and anomalous sub-graphs. They claimed that these anomalous sub-structures and sub-graphs are extremely rare as compared to ``usual" sub-structures and sub-graphs. \citet{Chandola:2009:ADS:1541880.1541882} presented a survey which provided classified anomalies into three types: \begin{itemize} \item \textbf{Point Anomalies:} It refers to the individual data points which are anomalous with respect to the entire data. For example, consider the real life scenario of the price of a stationary item. The cost of the item suddenly rises and becomes twice the previous cost. The new cost is thus, an example of a point anomaly. \item \textbf{Contextual Anomalies:} If a data instance is anomalous only in a particular context, then it is a contextual anomaly. It is also known as a conditional anomaly. \citet{Huber} designed a method to process event streams from technical systems for timely detecting anomalies and thus helping prevent huge industrial losses. \item \textbf{Collective Anomalies:} If the existence of certain data points individually is not anomalous but their collective existence collectively is, then they are called collective anomalies. \end{itemize} In our study, we focus on the collective anomalies. The standard anomaly detection algorithms for graphs could not be used for detecting pairwise anomalies in a citation network because the subtle signal strengths of the anomalies at the journal level in the citation network could not be detected by the pre-existing graph algorithms. An alternate way of modelling this problem can be using supervised machine learning techniques, which can be used to learn the suitable feature representation that can help in detecting anomalous behaviour among journals, authors, paper, etc. However, due to the lack of a ground-truth dataset of considerable size which has sufficient examples of anomalous behaviours of the above entities, machine learning algorithms could not be applied. We empirically show that existing graph anomaly detection methods could not work on the problem under consideration (Section \ref{experimental-results}). This motivated us to study detection of pair-wise anomalies. \subsection{Journal-level Study of Citation Networks} \citet{Hummon1989ConnectivityIA} modelled the connectivity in citation networks as an exhaustive search problem and applied a depth-first-search variant to quantify the similarity in the network. They focused on the similarity of edges. \citet{Zhang} presented a clustering algorithm which calculated the similarity between adjacent nodes and formed clusters based on that score. Study of citation network is a sufficiently explored topic. It dates back to 1965, when \citet{solla} studied the citation network and made inferences about the nature of references of a scientific paper with respect to its field and length. Various facets of citation networks have been studied, most widely explored being the network of papers and its outgoing citations. \citet{Osareh} studied citation network and its applications. \citet{Zhao:2008:CPC:1458082.1458125} studied the evolution of heterogeneous citation networks. Researches have also focused on the citation interactions among authors using citation analysis. \citet{Prabha} carried out a pilot study on the reasons behind the citations in scientific papers. He found that many of the citations made by papers are not essential for the results produced by it. \citet{Cronin2002} studied paper reference patterns with respect to the authors of the paper. They defined an author's \textit{citation identity} as the authors they cite in their work, and \textit{citation image} as the authors who cite them. They argued that the reference styles of authors are a form of watermark for their work. One important application of anomaly detection in citation network is to find the possibility of collusion among entities. \citet{cartel} came up with an algorithm to detect citation cartels \cite{journal}. It was a community detection algorithm focusing on anomalous pair of citations. The authors also discussed the possibility of some anomalous pairs being cases of citation cartels. Claiming whether a citation is a result of possible collusion or not is a non-trivial task, and requires an in-depth examination of every citation. In this paper, we focus only on the anomalies in the citation graph, and we do not try to claim any intentions behind those anomalous citations. \section{Datasets}\label{datasets} For the purpose of this study, we consider two different datasets. One of the major challenges while devising the experiments was the lack of ground-truth for anomalous citations in the real-world dataset. We thus introduce a journal citation anomaly dataset (called JoCAD), a dataset which consists of synthetically injected anomalies (see Section \ref{Datasets_JoCAD}). We use this for the purpose of testing our model and reporting the final accuracy in terms of the F1-score (Section \ref{experimental-results}). We also use the Microsoft Academic Search Dataset, a real-world citation dataset, for carrying out a case-study on the anomalous pair of journals detected by our model (Section \ref{case-study}). \subsection{Microsoft Academic Search Dataset}\label{Datasets_MAS} The Microsoft Academic Search (MAS) Dataset \cite{chakraborty2018good,MAS} consists of 1.6 million publications and 1 million authors related to the Computer Science domain. It has various metadata information about a paper, including the year of publication, keywords of the paper, the references of the paper, the specific field (AI, algorithms, etc.) the paper is targeted towards, and the abstract of the paper. The dataset spans from 1970 to 2014. This dataset has been extensively used in the past for bibliographic analysis \cite{chakraborty2015categorization,chakraborty2018universal}. We preprocessed the dataset according to the needs of our model. We removed the metadata which were not useful for the study. These included keywords, abstract, and the related fields of the paper. Table \ref{tab:MAS} shows statistics of the dataset. \begin{table}[!h] \begin{center} \caption{ Microsoft Academic Search Dataset \cite{chakraborty2018good,MAS}}\label{tab:MAS} \begin{tabular}{ c | c } \hline Entity & Number \\ \hline No. of papers & 1.6 million \\ No. of citations & 6 million \\ No. of journals & 1,800 \\ No. of journal pairs & 8,500\\ \hline \end{tabular} \end{center} \vspace{-5mm} \end{table} \subsection{JoCAD - Our Synthetically Injected Anomaly Dataset}\label{Datasets_JoCAD} For anomaly detection in citation graphs, the ground-truth is not well-defined. Hence, we created a synthetic dataset, wherein we synthetically injected anomalies to serve as the ground truth in our further experiments. The synthetic data generation process is motivated by \citet{Hayat2017}. Our synthetic dataset contains 100 journals, each having a journal index between 0 and 99, and containing citation information for the journals ranging over 20 years (2000-2020). We assign the number of papers in the journal as a random number in a pre-decided range. Similarly, we assign the citation count between each pair of journals as a random number in a pre-decided range which we consider as the normal citation behaviour of the journal pairs. For injecting anomalies, we intuitively list properties of an anomalous pair of journals. The properties consist of a sudden spike in the number of citations from one journal to another or from both journals to each other in some random year; or a gradual increase from one journal to another or from both journals to each other, which result in an anomalously high number of citations over all the years. Using these methods with reasonable randomness, we create a total of 110 anomalies. The final dataset consists of 110 anomalous pairs out of total 10,000 pairs of journals. The types of anomalies we inject into the dataset can be broadly classified into five types: \begin{enumerate} \item If the number of citations from journal $J_i$ to journal $J_j$ in a particular year is significantly more than the normal citation behaviour of the journal pairs, i.e., there is a sudden spike in the number of citations from $J_i$ to $J_j$ in that year, then the citation from $J_i$ to $J_j$ is an instance of {\bf Type 1 anomaly}. \item If the number of citations from $J_i$ to $J_j$ increases significantly over successive years, with the difference in the number of citations between any two years $Y_i$ and $Y_j$ being greater than the expected difference in the number of citations between any journal pair, then the citation from $J_i$ to $J_j$ is an instance of {\bf Type 2 anomaly}. \item If the number of citations from $J_i$ to $J_j$ in the year $Y_k$ is significantly higher than the average number of citations between any journal pairs, and the number of citations from $J_j$ to $J_i$ in the year $Y_{k+1}$ is significantly higher than the average number of citations between any journal pairs, then both the citations from $J_i$ to $J_j$ and vice-versa are instances of {\bf Type 3 anomaly}. \item If the number of citations from $J_i$ to $J_j$ in the year $Y_i$ is greater than or equal to double the number of citations received by $J_i$ from $J_j$ in the previous year $Y(i-1)$, then the citation from $J_i$ to $J_j$ is an instance of {\bf Type 4 anomaly}. \item If the number of citations from $J_i$ to $J_j$ in the year $Y_i$ is greater than or equal to double the number of citations from $J_i$ to $J_j$ in the previous year $Y_{i-1}$, then the citation from $J_i$ to $J_j$ is an instance of {\bf Type 5 anomaly}. \end{enumerate} \section{Methodology}\label{methodology} In this section, we first introduce the problem definition, followed by the proposed methodology. \begin{figure*}[!] \centering \includegraphics[width=15 cm]{dia1.jpeg} \caption{Flow diagram of our methodology.} \label{fig:methodology} \end{figure*} \subsection{Problem Definition} Given a set of papers $P$, where each paper has 4 attributes -- journal name, authors, citations, and the year of publication, as the input to the system, the task is to predict the journal-to-journal anomalies with a confidence score of the prediction made, classify the anomaly into its type and suggest possible reasons for the existence of the same. \subsection{Proposed Methodology}\label{sec:method} We use a two-fold approach (as shown in Figure \ref{fig:methodology}) to classify the citation anomalies --- box plot and time-series analysis. \subsubsection{Box Plot Bucket Analysis:} We start by clustering the journals into buckets based on similar behaviour in terms of the total number of papers published in the journal. For each journal in our database, we define the usual behaviour of the given journal by analyzing the behaviour of all the journals lying in the same bucket as the given journal, i.e., all the journals having similar number of papers as that of the given journal, and then use the box plot method to predict the anomalies. For each possible bucket, we pair each of the papers in the current bucket with each of the papers in the bucket of the given journal. We refer to the set of all these paper-paper pairs as a grid. We now detect the anomalies using box plot. To calculate the outlier behaviour, using a box plot, we calculate the first quartile and the third quartile\footnote{ The first quartile is the 25$th$ percentile of the data and the third quartile is the 75$th$ percentile of the data. The second quartile refers to the median of the distribution.} of the data points corresponding to the journal-journal citation counts in the selected grid. We define anomalous journal-journal pairs as the data points which lie outside the area: [(first-quartile - ($1.5\times IQR$)) , (third-quartile + ($1.5\times IQR$))], where interquartile range $IQR$ = (third-quartile - first-quartile). The anomalies detected by the box plot method are static anomalies as these anomalies are based on the total number of citations between two journals over all the years. \subsubsection{Time-series Analysis:} Once we have the pairs declared anomalous by the box plot, we analyze each of them with time-series analysis to confirm if there exists some year during which there was a sudden change in their usual citation behaviour. The anomalies detected by the time-series analysis method are dynamic anomalies as these anomalies are susceptible to change every year. To define the ``usual behaviour", we use the empirical rule. The empirical rule, also called the ``68-95-99.7 rule'' \cite{pukelsheim1994three}, is a statistical rule that states the percentage of values of a Gaussian distribution that \textcolor{black}{lies} within 2, 4, and 6 standard deviations around the mean. According to the rule, 2 standard deviations around the mean cover 68.27\% of the values, 4 standard deviations around the mean cover 95.45\% of the values, and 6 standard deviations around the mean cover 99.73\% of the values. To check the usual behaviour for a pair of journals for a given year (say $Y$), we list the number of citations from one journal to another till $Y$, and calculate mean and standard deviation from the distribution. Then, as stated by the empirical formula, 99.73\% of the data is expected to lie within 6 standard deviations around the mean. Hence, if the number of citations from one journal to another exceeds this range, it is suggested to be anomalous by the time-series analysis. To understand the different types of unusual behaviour, we extend the existing notions of synchronous and dianchronous citations \cite{macro} and use synchronous citations to refer to the citations from a journal to another journal, and dianchronous citations to refer to the citations received by a journal. For a given pair of journals, we check four types of behaviours for each year: \begin{enumerate} \item \textbf{One sided synchronous citations}: This consists of detecting the unusual behaviour of outgoing citations from one journal to the other for each side, i.e., if the two journals are $J_1$ and $J_2$, the above test is performed separately for the outgoing citations from $J_1$ to $J_2$ and for the outgoing citations from $J_2$ to $J_1$, for each year as stated above. \item \textbf{One sided dianchronous citations}: This consists of detecting the unusual behaviour of incoming citations from one journal to the other for each side i.e., if two journals are $J_1$ and $J_2$, the above test is performed separately for the incoming citations from $J_1$ to $J_2$ and the incoming citations from $J_2$ to $J_1$, for each year as stated above. \item \textbf{Double sided synchronous citations}: This consists of detecting the unusual behaviour of outgoing citations from one journal to the other for both the journals simultaneously, and if both of the sides lie in the outlier range, this pair is said to have double sided synchronous behaviour. \item \textbf{Double sided dianchronous citations}: This consists of detecting the unusual behaviour of incoming citations from one journal to the other for both the journals simultaneously, and if both of the sides lie in the outlier range, this pair is said to have double sided synchronous behaviour. \end{enumerate} Checking both synchronous and dianchronous citation behaviours is essential because a particular number of citations from one journal to another can be in the normal range for the citing journal but not in the normal range for the cited journal, or vice-versa. This kind of case can happen in many instances. For example, one unpopular journal suddenly increases citations to a very popular journal and to an unusually high level; or one very popular journal suddenly increases citations to an unpopular journal. In both cases, only one side of the single side anomalies will be evident from the distribution based check described above. \subsubsection{Reasons for Possible Anomalies:} We categorize the detected anomalies hinting at five possible reasons for their occurrence, namely, many-many anomaly, many-one anomaly, one-many anomaly, one-one anomaly, and previous-author collaboration. For the first four, we supplement a metric that captures the essence of the citation graph being highly crowded at both the ends (journals $J_1$ and $J_2$) for many-many anomaly, and so on. To do this, we define the ``normal behaviour" of the citations {\em given by a paper to a journal} by first creating a Gaussian distribution with the citation count from a paper to a journal as the data points and then, using the empirical formula, we use $\mu \pm \sigma$ to define the normal behaviour of nearly 70\% of the data points. Now consider all the papers in the citing (sender) journal, i.e., the journal $J_1$, and count the number of papers in the journal which contribute to $J_2$ (cited/receiver journal) that is at least the normal behaviour: $paper-to-journal\ count > \mu \pm \sigma$. Dividing this by the total number of papers in published in $J_1$, we get the percentage of papers (vertices in the citation network) in the $J_1$'s side which is crowded in terms of the citation count they produce for $J_2$, denoted as `sender-percentage'. Now, we define the ``normal behaviour" of the citations received by a paper from a journal, by creating a Gaussian distribution with the citation count from a journal to a paper as the data points, and then, we use the empirical formula to define the normal behaviour of the data points. Similar to the previous case, based on the above definition of the normal behaviour, we now consider all the papers in the receiver journal $J_2$, and count the number of papers in $J_2$ which are cited by $J_1$ (the sender journal) more than or equal to the normal behaviour: $journal-to-paper\ count > \mu \pm \sigma$. Dividing this by the total number of papers in $J_2$, we get the percentage of papers (vertices) in the receiver's side which is crowded in terms of the citation count they receive from $J_1$, denoted as `receiver-percentage'. Now we are ready to categorize an anomaly as many-many, many-one, one-many, or one-one based on the following criteria: \begin{enumerate} \item \textbf{Many-many Anomaly:} If the sender-percentage is $>75\%$ and the receiver-percentage is $>75\%$, then it is the case of a many-many anomaly since both the receiver's and the sender's sides are extremely crowded. \item \textbf{Many-one Anomaly:} If the sender-percentage is $>75\%$ and the receiver-percentage is $<25\%$, then it is the case of a many-one anomaly since the receiver's side is not crowded while the sender's side is extremely crowded. \item \textbf{One-many Anomaly:} If the sender-percentage is $<25\%$ and the receiver-percentage is $>75\%$, then it is the case of a one-many anomaly since the sender's side is not crowded while the receiver's side is extremely crowded. \item \textbf{One-one Anomaly:} If the sender-percentage is $<25\%$ and the receiver-percentage is $<25\%$, then it is the case of a one-one anomaly since both the sender's and receiver's side are not crowded. \end{enumerate} \begin{figure*}[!t] \centering \includegraphics[width=1.1\columnwidth]{reasons.png} \caption{Pictorial representation of four of the five possible reasons of anomalies. The fifth reason (effect of collaboration) is not shown here.} \label{fig:reasons} \end{figure*} Figure \ref{fig:reasons} diagrammatically shows the four reasons listed above. To explain the reasons for the anomalies, we also look into the previous collaboration of the authors of a publication and count the number of such occurrences between the journal-journal pairs. In particular, we detect if at the time of publishing a paper in year $Y$ any of the authors of the paper has previously collaborated with any of the authors of the paper it is citing. We then increment a counter by $1$. We do so for paper-pairs consisting of every paper in the sender-journal $J_1$ and all the papers it cites in the receiver-journal $J_2$, and thus calculate the total number of \textbf{previous-author-collaborations}. \subsection{Confidence Score}\label{confidence} Our model finally assigns a confidence score to every anomaly detected, which states how confident the model is on the pair of journals being anomalous in a year \cite{ConfScore}. A confidence score is first assigned by box plot method to each anomaly, then by the time-series method, and at last both the scores are combined, giving the final confidence score. We use the $tanh$ function\footnote{$tanh$ is a hyperbolic function which gives a value ranging from -1 to 1, and in case of only positive inputs, 0 to 1.} for calculating the individual confidence scores from the two methods -- box plot and time-series. One intuition is that if our method states a pair to be anomalous, we are at least $50\%$ sure of it being anomalous. Following this intuition, we scale the confidence scores given by individual methods to be from $0.5-1$ instead of $0-1$. Another intuition is that in the time-series method, both-sided anomaly is a more unusual event than a single-sided anomaly. This is because a both-sided anomaly in a particular year means both the journals went beyond the normal behaviour and cited the other. We state the confidence of a both-sided anomaly to be at least $75\%$. Therefore, a both-sided anomaly is scaled between $0.75-1$ instead of $0-1$. \begin{figure*} \centering \includegraphics[width=15 cm]{labelled_chart.png} \caption{Histogram of confidence scores of anomalies in the MAS dataset.} \label{fig:histogram} \end{figure*} For combining the scores, we choose to take the average of the two scores. This is done because both the methods have equal importance in the detection of the anomaly. Figure \ref{fig:histogram} shows the histogram of the confidence scores of anomalies detected from the MAS dataset. We analyze the most anomalous pair with confidence score 0.93 and find that it is logical for the pair to be anomalous (see case studies in Section \ref{case-study}). \section{Experiments}\label{experiments} \subsection{Comparison of Time-series Analysis with SJR ratings}\label{experimentA} To evaluate the performance of the time-series method for anomalous behaviour detection, we use the SJR ratings to check changes in ratings of journals stated anomalous in some particular years. Scimago Journal \& Country Rank, better known as SJR, is a journal rating system \cite{SJR}. It uses data similar to what is used by H-index, and gives year-wise ranks to journals. It is a well-recognised rating system for journals and conferences. We scraped the SJR ratings over the years for all the journals present in the MAS dataset from the portal made for SJR ratings. The comparison of sudden increase in citations to each other for pairs of journals mostly resonates with the respective SJR rating changes of the citation-receiving journal in the next two years. The case-study of the most anomalous pair of journals also supports the same result (see Section \ref{case-study}). \subsection{Experimental Results}\label{experimental-results} For anomaly detection in citation graphs, there is no well-defined ground-truth or a proper evaluation metric. Hence, for the purpose of evaluating the performance of our method, we created a synthetic dataset wherein we synthetically injected anomalies~\ref{datasets}. They were treated as the ground-truth in our experiments, and we report our results based on them. We use precision, recall and F1 score for the final evaluation. \textbf{Baseline Methods:} Due to the lack of any existing baseline for the given task, we decided to use the existing graph anomaly detection algorithms and each of the methods used by us, namely, the box plot method and the time-series method, to act as baselines for evaluating our proposed model. We used K-means clustering, one of the popular graph anomaly detection algorithms, but it could only detect 38 anomalous pairs out of the total of 110. The detected pairs are the pairs with a large number of citations on both sides i.e., to and from one journal to another over the years. These are clearly visible by taking the summation of the citations on both sides, similar to the box plot method. However, K-means clustering algorithm is unable to detect other types of anomalous pairs, and thus has a lower recall and F1 score as compared to our method. \begin{table}[h!] \label{F1_scores} \begin{center} \caption{Results of anomaly detection methods and our models.} \label{tab:result} \begin{tabular}{ c c c c } \hline Method & Precision (\%) & Recall (\%) & F1 Score (\%) \\ \hline K-means & 100 & 34.5 & 67.2 \\ Box plot & 59.19 & 93.63 & 72.53 \\ Time-series & 86.73 & 77.27 & 81.73 \\ Our model & 100 & 75.45 & 86.01 \\ \hline \end{tabular} \end{center} \end{table} Table \ref{tab:result} shows the comparative results of the baselines and our model. The F1 score of our model comes out to be $86.01\%$ which is higher than that of the baselines. Also, the precision of our model comes out to be $100\%$, which means that all the pairs stated anomalous with the agreement of both the methods are actually anomalous. \subsection{Results on the MAS Dataset}\label{Experiment_MAS} We ran the model on the real-world MAS dataset. The histogram of confidence scores of the anomalies found in the dataset is shown in Figure \ref{fig:histogram} (explained in Section \ref{confidence}). Out of total 8.5 thousand journal-pairs, total of 328 anomalies are found. The number of unique pairs of anomalous journals (irrespective of the year of anomaly) is 230, and the total number of journals found in any anomaly is 103. We observe that the occurrence of anomalies is rare (only $3\%$), and the occurrence of both-sided anomalies is extremely rare (only $4$ cases out of $8.5$ thousand pairs), as shown in Table \ref{tab:distribution} \begin{table}[h!] \begin{center} \caption{Distribution of types of journal-pair anomalies found in the MAS dataset.}\label{tab:distribution} \begin{tabular}{ c c c } \hline Type & Number & Percentage of total pairs \\ \hline Single (One sided) & 324 & 3.85\% \\ Double (Both sided) & 4 & 0.04\%\\ Total & 328 & 3.90\% \\ \hline \end{tabular} \end{center} \end{table} We plot the average number of publications per year that are anomalous, i.e., the ratio of the number of anomalous publications in a year to the total number of publications in that year. The temporal frequency mapping of anomalies is shown in Figure \ref{fig:year}. We can infer that the frequency of the relative year-wise anomalous journals decreases over the years. This decrease might be due to a huge boost given to the academic research in the field of Computer Science, which led to an increase in the total number of journals. This might have decreased the ratio over time. Another reason could be more stringent rules and regulations imposed in the scientific community, which could have led to a decrease in anomalous activity amongst journals. \begin{figure} \centering \includegraphics[width=\columnwidth]{size.png} \caption{Average anomalous publications throughout the years.} \label{fig:year} \end{figure} Next, we plot the trends with respect to the size of the anomalous journals, defined in terms of the number of papers published in it. Figure \ref{fig:size} shows the decline of anomalous activities as the size of a journal increases. This might be due to a bigger journal having a wider variety of papers, research domains, and authors. Another reason might be the journals which have gained recognition and prestige over time are likely to receive high number of novel and high-quality papers which should be published. Thus, prestigious and renowned journals may have a bigger journal size, which are less likely to be anomalous. \begin{figure} \centering \includegraphics[width=\columnwidth]{time.png} \caption{Fraction of anomalous papers published in a journal with the size of the journal. } \label{fig:size} \end{figure} \begin{figure*}[t!] \centering \includegraphics[width=15 cm]{lab_case.png} \caption{The number of citations from Symposium on Information theory to Transactions of Information Theory over years.} \label{fig:case} \end{figure*} \subsection{Human Annotators}\label{human-annotator} Two human annotators\footnote{The annotators were experts in data mining domain and their age ranges between 25-35 years.} were asked to independently label the anomalies detected by our method on the MAS dataset as anomalous or non-anomalous. The annotation was done on the basis of the number of citations between the journals over years, and relevant metrics such as the average number of citations over all the years between the journals and the popularity of both journals. They checked the popularity of journals based on factors like impact factor and cite score. Each annotator annotated all 328 anomalous pairs. They placed 38 pairs and 25 pairs respectively in the non-anomalous category. The inter-annotator agreement was $0.78$, based on \textit{Cohen's kappa coefficient}. \subsection{Case Study}\label{case-study} We conduct a case study for the anomalous pair with the highest confidence in the MAS dataset. The pair is the journal \textit{IEEE Transactions on Information Theory} and the conference \textit{IEEE International Symposium on Information Theory}, and the confidence score of being an anomaly is $93\%$. IEEE has a professional society, namely \textit{The Information Theory Society} \cite{itsoc}, under whose umbrella lies its main journal - \textit{IEEE Transactions on Information Theory} (IEEE TIT) and its flagship conference, \textit{IEEE International Symposium on Information Theory}. The symposium is a conference for researchers to meet and discuss work done in the field of information theory. The work can be previously published or unpublished. As the work can be previously published, and the conference is a part of the same society as the journal, many authors of the published papers in the journal could attend the conference to display their work. Hence, it is natural for the two to have numerous citations to each other over the years. Because of this, there can be two reasons for a citation: \begin{enumerate} \item A paper has already been published in the journal and the authors were invited to the conference to present and discuss their work. \item A paper was not accepted by the journal and the authors presented their work \textcolor{black}{at} the conference. Later, some other researcher used their work and cited them. The paper then got published in the journal. \end{enumerate} Some citations may not exist because of the journal and the conference being a part of the same society. There would be many instances where a paper not published in the journal but presented at the conference had cited a paper previously published in the journal. \begin{figure*}[!t] \centering \includegraphics[width=15 cm]{Portal_final_27_04.png} \caption{A snapshot of our portal. It shows the result of detecting multiple anomalous relationships for the journal IET software/IEEE Proceedings in the year 1989.} \label{fig:Portal_2} \end{figure*} Charts in Figure \ref{fig:case} show the number of citations from Symposium on Information Theory to IEEE TIT, the change in SJR rating of IEEE TIT over the years, the number of citations from IEEE TIT to Symposium on Information Theory, and the change in SJR ratings of Symposium on Information Theory over the years. A clear resemblance in citations and SJR rating-change charts \cite{scimagojr.com} for both the journal and the conference shows that the findings of time-series analyzes correspond to the changes in the SJR rating of IEEE TIT. As stated in the introduction, JIF depends upon the number of citations the journal had received in the two previous years. A sudden spike can be seen in the citations from the conference to the journal \textcolor{black}{in the year} 2003. At the same time, a spike can be seen in the SJR rating of the journal \textcolor{black}{in the year} 2004, which shows that the increased citation count has contributed towards \textcolor{black}{an} increase in the rating of the journal. \section{A Web Portal}\label{portal} We use the journal level citation network created using the MAS dataset to develop a portal which allows the user to find the anomalies corresponding to a journal for all the possible years. It provides an interactive graphical interface, which visually depicts the anomalies in a citation network. The user can enter the details of the journal, based on which the portal provide the user with a year-wise analysis of the anomalies. A screenshot of the portal is presented in Figure \ref{fig:Portal_2}. For all pairs of journals in our dataset which form an anomalous pair with the journal queried by the user, we display the year-wise anomalies in an anomaly graph. This graph depicts each of the journals as nodes, while the citations between them is represented by the edges. The size of a node is proportional to the number of papers in the journal, i.e., a larger size of the node indicates that the journal has published a higher number of papers. The size of an edge depicts the number of citations between the two journals, i.e., a thicker edge between two journals indicates a higher number of citations between them. The number on top of each node represents its journal index, which is mapped to the respective journal name in our dataset.\smallskip{} \noindent\fbox{% \parbox{0.98\columnwidth}{% A beta version of the portal is live and can be accessed here: \url{https://journalcitationsanalysistool.herokuapp.com/}.}} \section{Conclusion}\label{conclusions} In this paper, we presented a novel model to detect the journal-level anomalous pairs. The model also gives the confidence score by analyzing both static and dynamic anomalies using box plot bucketing method and time-series analysis. We also curated JoCAD, a novel dataset, which consists of synthetically injected citation anomalies. We further ran our model on two datasets, namely, JoCAD and the Microsoft Academic Dataset, and used it to evaluate our methodology. We achieved 86\% F1 score on JoCAD in the comparison of our method with the standard graph anomaly detection methods. We interpreted our results in a case study using the Microsoft Academic Dataset, wherein our results resemble the citations and Scimago Journal \& Country Rank (SJR) rating-change charts. We experimentally showed a high similarity between the time-series trends predicted by our method and the time-series trends as reflected by the SJR. We further designed an interactive web portal - `Journal Citations Analysis Tool` which given the citation network as an input, shows the journal-level anomalous citations, and helps users analyze the temporal citation pattern of a given journal. Future work in this direction can include an in-depth study about the reasons for the anomaly detected as well as extend the work in developing methods for the detection of citation cartels. We acknowledge that while curating the dataset, JoCAD, we could have possibly introduced a human bias in it, which can be reduced in the future. We would like to explore the anomalous citation behavior in other domains as well. Other relevant future work can take into account the textual context of a citation made, and calculate its similarity with the content of the paper being cited. This will help us understand the relevance of the citation made and thus help predict anomalous citations better. \section*{Acknowldgement} T. Chakraborty would like to acknowledge the support of Ramanujan Fellowship, DST (ECR/2017/00l691), and the Infosys Centre of AI, IIIT-Delhi, India. \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2020-06-01T02:04:38', 'yymm': '2005', 'arxiv_id': '2005.14343', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14343'}
arxiv
\section{Introduction} \label{sec:intro} Constructing a latent space for human motion is an important problem as it has a wide range of applications such as motion recognition, prediction, interpolation, and synthesis. Ideal motion spaces should be compact in the sense that random sampling in the space leads to plausible motions and comprehensive so as to generate a wide range of human motions. In addition, locally linear arrangement of the semantically related hidden vectors would benefit motion synthesis, e.g., by simple algebraic operations. However, constructing a compact and versatile motion space and extracting valid motions from it remains a challenging problem because the body parts of human body are highly correlated in general actions and the joints are constrained to satisfy the bone lengths and the range of movement. The high dimensionality of the joint space adds additional difficulty to this problem. \begin{figure}[h] \centering \includegraphics[width=0.9\linewidth]{figures/interpolation.jpeg} \caption{Examples of motion interpolation on the latent motion manifold generated by our method. The first and last columns are snapshots of two input motions, and the intermediate columns show the snapshots of four individual motions obtained by the linear interpolation on the motion manifold.} \label{fig:interpolation} \end{figure} In this paper, we present a novel framework to construct a latent motion manifold and to produce various human motions from the motion manifold. In order to embrace the temporal characteristic of human motion, our model is based on the sequence-to-sequence model. The unsupervised sequence-to-sequence models have been shown to be effective by previous studies on motion prediction \cite{martinez2017human, pavllo2018quaternet}. % Based on these studies, we develop several novel technical contributions to achieve a compact yet versatile latent motion manifold and a motion generation method as follows. First, our model is characterized by the combination of one encoder and two decoders. Given a motion manifold vector, one decoder learns to generate the joint rotation while the other learns to output joint rotation velocities. As will be discussed later, the joint rotation decoder has the advantage of reconstructing long term motions better. In comparison, the joint velocity decoder has the advantage of improving the continuity of the motion. By complementing each other, our two decoder model shows a higher reconstruction accuracy than that of the single decoder model. Second, unlike previous studies that deal with only either joint angles or joint positions, by adding a forward kinematics (FK) layer \cite{villegas2018neural}, our joint angle-based human representation achieves the advantage of satisfying bone-length constraints and simplifying joint limit representation. By additionally considering joint position computed by the FK layer while training, our method reduces the joint position error, which is visually more perceptible than the joint angle error. Lastly, we introduce several loss functions, each of which contributes to enhancing the quality of the motion manifold in different aspects. A reconstruction loss reduces the difference between the reconstructed motion and the input motion and thus allows the manifold to synthesize motion content and details observed in the training motion dataset. A regularizer loss improves the distribution quality of the motion manifold and thus enables random sampling and interpolation on the manifold. In addition, an adversarial loss increases the naturalness of the motions generated from the motion manifold. In this paper we show that, based on these technical contributions, our method allows for various practical applications such as random generation of motions, motion interpolation, motion denoising and motion analogy as will be shown in Sec.~\ref{sec:result}. The capability of our method is demonstrated by the comparison with other approaches, such as the seq2seq model~\cite{martinez2017human} and the convolution model~\cite{holden2015learning, holden2016deep}. The remaining part of this paper proceeds as follows: After reviewing previous studies related to our work in Sec.~\ref{sec:related}, we present our method and loss function in detail in Sec.~\ref{sec:method}. Sections~\ref{sec:data} detail the data pre-processing and Sec.~\ref{sec:result} reports a number of experiments performed to verify the effectiveness of our method. Section~\ref{sec:conclusion} discusses the limitations of our work, future research directions, and concludes the paper. Our code and networks are available at {\small \url{https://github.com/DK-Jang/human_motion_manifold}}. \section{Related work} \label{sec:related} Researcher have developed several methods to construct motion manifold to generate natural human motions, but compared with studies on manifold learning for other data such as image, research on motion data is scarce. Linear methods such as PCA can model human motion in only a local region. Chai \textit{et al}. \cite{chai2005performance} apply local PCA to produce a motion manifold that includes a certain range of human motion, and apply it for synthesizing movements from low dimensional inputs such as the position of end effectors. Lawrence \cite{lawrence2004gaussian} use Gaussian Process Latent Variable Model (GPLVM) to find a low dimensional latent space for high dimensional motion data. Taylor \textit{et al}. \cite{taylor2007modeling} propose a modified Restricted Boltzmann Machine that is able to deal with the temporal coherency of the motion data. Lee \textit{et al}. \cite{lee2010motion} propose motion fields method, a novel representation of motion data, which allows for creating human motion responsive to arbitrary external disturbances. Recently, with the development of deep learning technology, a method of constructing a motion manifold by using Convolutional Neural Network (CNN)-based encoder was introduced by Holden \textit{et al}. \cite{holden2015learning, holden2016deep}. Butepage \textit{et al}. \cite{butepage2017deep} compare a number of deep learning frameworks for modeling human motion data. Our method for constructing motion manifold is based on previous studies on sequence learning for motion to predict the joint position sequences of a 3D human body given past motions. Martinez \textit{et al}. \cite{martinez2017human} develop a novel sequence-to-sequence encoder-decoder model that predicts human motion given a short duration of past motion. The presented result is impressive but has a few limitations that sometimes implausible motions such as foot sliding are generated and the initial pose of the predicted motion is somewhat discontinuous from the input motion. Pavllo \textit{et al}. \cite{pavllo2018quaternet} selectively use a joint rotation-based loss for short term prediction and a joint position-based loss for long term prediction. The latter includes forward kinematics to compute the joint positions. However, the basic sequence-to-sequence model can only predict short term motions and has limitations in predicting non-trivial, long term motions. In addition, a loss function that minimizes only the prediction error does not guarantee to construct compact and versatile motion manifold. Our method solves these problems by jointly considering joint rotation and position errors in the loss function and by adding regularization to the motion manifold. In a broader perspective, our work is related with the studies on recognizing and generating human motion, which remains a challenging research topic due to the high dimensionality and dynamic nature of the human motion. Wu and Shao \cite{wu2014leveraging} propose a hierarchical dynamic framework that extracts top-level skeletal joint features and uses the learned representation to infer the probability of emissions to infer motion sequences. Du \textit{et al}. ~\cite{du2015hierarchical} and Wang \textit{et al}. ~\cite{wang2017modeling} use recurrent neural network (RNN) to model temporal motion sequences and propose hierarchical structure for action recognition. With regard to motion synthesis, Mittelman \textit{et al}. \cite{mittelman2014structured} propose a new class of Recurrent Temporal Restricted Boltzmann Machine (RTRBM). The structured RTRBM explicitly graphs to model the dependency structure to improve the quality of motion synthesis. Fragkiadaki \textit{et al}. \cite{fragkiadaki2015recurrent} propose the Encoder-Recurrent-Decoder (ERD) that combines representation learning with learning temporal dynamics for recognition and prediction of human body pose in videos and motion capture. Jain \textit{et al}. \cite{jain2016structural} propose structural RNN for combining the power of high-level spatio-temporal graphs. \section{Method} \label{sec:method} This section details our framework. After defining notations used in this paper, we explain the structure of the network and the design of the loss function for training. \subsection{Representation and notations} \label{subsec:rep} We denote the human motion set by $\mathcal{Q}$ and corresponding random variable by $\mQ$. A motion with a time range of $[t,t+\Delta t -1]$ is written as $\mQ_{t:(t+\Delta t -1)} = [\vq_t, \ldots, \vq_{t+\Delta t -1}]$, where $\vq_t$ denotes the pose at time $t$. A pose is represented with a set of joint angles written in the exponential coordinates, i.e., $\vq_t = [q_{i,x}^t, q_{i,y}^t, q_{i,z}^t]_{i=1}^{n_{joint}}$ where $(q_{i,x}^t, q_{i,y}^t, q_{i,z}^t)$ are the three components of the exponential coordinates and $n_{joint}$ is the number of joints. Therefore, the dimension of a human motion is $\mathcal{Q} \in \real^{\Delta t \times n_{joint} \times 3}$. Lastly, $\vp_t$ is the pose represented with the joint positions at time $t$ corresponding to $\vq_t$, and $\mP_{t:(t+\Delta t -1)}=[\vp_t, \ldots, \vp_{t+\Delta t -1}]$. $\mP$ is also a random variable of motion set $\mathcal{Q}$. \subsection{Motion manifold with sequential networks} \label{subsec:motionmanifold} \begin{figure*}[th] \centering \includegraphics[width=0.99\textwidth]{figures/overview.jpeg} \caption{Structure of our sequential networks for constructing the motion manifold.} \label{fig:overview} \end{figure*} We construct a motion manifold in an end-to-end unsupervised way using a network of sequential networks, with an objective to minimize the difference between the ground truth motion space distribution and the reconstructed motion space distribution extracted from the latent motion manifold. To this end, we develop a sequential model that consists of the RNN with Gated Recurrent Unit (GRU). Our model has a sequence-to-sequence structure \cite{martinez2017human}, which is often used in machine translation. This RNN structure is effective for maintaining the temporal coherency in motion, and {\color{green} it is trained to generate a fixed length of motion (150 frames) in our study.} As shown in Fig. \ref{fig:overview}, our model includes the combination of one encoder and two decoders with a regularizer. The encoder takes the source motion as an input and maps it to the latent motion space. The regularizer encourages the encoded motion distribution to approximate some prior distribution. The two decoders are designed to map the latent motion space to joint angles and joint velocities, respectively. Details of our model are given next. \subsubsection{Encoder} \label{subsubsec:enc} The encoder consists of a GRU and one linear layer, and Fig. \ref{fig:overview} shows the unrolled schematic diagram of the encoder. The $\Delta t$ poses $[\vq_t, \ldots, \vq_{t+\Delta t -1}]$ of a motion are input to the GRU sequentially. The GRU encodes the current frame while being conditioned by the previous frames with their hidden representation. Specifically, the pose $\vq_i$ in the $i$-th frame is encoded as follows: \begin{equation} \label{eq:en} \begin{aligned} h_i^{Enc} = \text{GRU}_{W_{Enc}}(h_{i-1}^{Enc}, \, \vq_i), \end{aligned} \end{equation} where $h_{i}$ is the hidden state at frame $i$, and $W_{Enc} \in \mathbb{R}^{\text{3}n_{\text{joint}} \times d_h}$ are the training parameters with $d_h$ being the hidden dimension of the GRU. After the final pose of the input motion is read, one linear layer of parameter $W_{\text{c}} \in \mathbb{R}^{d_h \times d_m}$ receives $h_{t+\Delta t -1}$ and compresses it to produce the $d_m$-dimensional code $Z \in \mathcal{Z}$ where $\mathcal{Z}$ denotes the motion manifold. It is worth mentioning that this compression brings the benefit of denoising input data. Now the encoder mapping $Enc: \, \mathcal{Q} \rightarrow \mathcal{Z}$ is completed. \subsubsection{Latent motion manifold with the Wasserstein regularizer} \label{subsubsec:reg} We adopt the Wasserstein regularizer for matching the distribution $E_Z:=\mathbb{E}_{P_{\mQ}}[E(Z \mid \mQ)]$ of the motion manifold to the desired prior distribution $P_Z$. Unlike the variational auto-encoder \cite{rezende2014stochastic}, the sequential networks trained with the Wasserstein regularizer allows non-random encoders to deterministically map inputs to the latent codes, and thus it helps randomly sampled or interpolated points in the motion manifold correspond to plausible motions Refer to \cite{tolstikhin2017wasserstein} for more details about the Wasserstein regularizer. \subsubsection{Decoder with joint rotation and joint velocity} \label{subsubsec:dec} Our decoder model consists of two kinds: One decoder learns the joint rotation and the other learns joint rotational velocity as shown in Fig. \ref{fig:overview}. Both decoders are based on the GRU while the connection structures of the two are different. Unlike the rotation decoder, the velocity decoder adds a residual connection between the input and the output to construct joint rotation. Each decoder then generates the reconstructed joint angle sequence in reverse temporal order as suggested by \cite{srivastava2015unsupervised}. The decoders are trained simultaneously with backpropagation. This dual decoder model is based on the idea of \cite{srivastava2015unsupervised}. By combining the two decoders, we can alleviate the limitations of individual decoder models. The rotation decoder shows strength when reconstructing long term motions because it learns joint angle itself. Conversely, it may cause pose discontinuity between frames. The velocity decoder has the advantage of reconstructing continuous human motion as it outputs difference between consecutive rotations, which is usually small and easier to learn. However, training velocities tends to be unstable in a long-term sequence because the longer the motion is, the more error is accumulated. As our two decoders have contrasting strengths and weaknesses, when combined, they complement each other in synergy. Unlike previous studies about motion prediction, recognition and manifold ~\cite{butepage2017deep,martinez2017human,holden2015learning,fragkiadaki2015recurrent,pavllo2018quaternet} in which either only the joint rotations or the joint positions are used, our model considers both the joint rotations and positions in the motion reconstruction loss term, $L_R$ (See Eq.~\ref{eq:motion_recon_loss}). Loss with joint angles has the advantage of preventing errors such as inconsistent bone length or deviation from human motion range, and thus learning with joint angle loss can generate plausible motions. However, rotation prediction is often paired with a loss that averages errors over joints by giving each joint the same weight. The ignorance of varying influence of different joints on the reconstructed motion can yield large errors in the important joints and degrade the quality of the generated poses. The joint position loss minimizes the averaged position errors over 3D points, which better reflects perceptual differences between poses. To combine both joint rotations and positions in the motion reconstruction loss $L_R$, we add a forward kinematics (FK) layer that computes the joint positions from the joint rotations. This allows for calculating the loss between the joint positions of the target motion and the reconstruction motion. The FK module is valid for network training because its output is differentiable with respect to joint rotation. Finally, our method reconstructs the motion in the reverse order of the input sequence. Reversing the target sequence has an advantage in learning in that the first output frame of the decoder needs only to match the last frame input of the encoder, which allows for a continuous transition of hidden space vectors from the encoder to the decoders. {\color{green} Refer to \cite{srivastava2015unsupervised} for a theoretical background on this approach.} Details of our decoder are explained next. \paragraph*{Joint Rotation Decoder} \label{par:dec_rot} The unfolded schematic diagram of the joint rotation decoder is shown in the upper row in Fig. \ref{fig:overview}. It first transforms an element of the motion manifold $z \in Z$ to a $d_h$-dimensional hidden space vector with a linear layer of parameter $W_e^r \in \mathbb{R}^{d_m \times d_h}$. Then, conditioned by the hidden space vector representing the future frames, the GRU and a linear layer outputs the reconstructed pose $\widehat{\vq}_i^r$ at the $i$-th frame given its next pose $\widehat{\vq}_{i+1}^r$: \begin{align} h_i^{{Dec}^r} &= \text{GRU}_{W_{{Dec}^r}}(h_{i+1}^{{Dec}^r}, {\color{green} \widehat{\vq}_{i+1}^r} ), \label{eq:de_rot} \\ \widehat{\vq}_{i}^r &= W_o^{r \, T} h_i^{{Dec}^r}, \label{eq:out_rot} \end{align} where $W_{{Dec}^r} \in \mathbb{R}^{\text{3}n_{\text{joint}} \times d_h }$ is learning parameter of the GRU and $W_o^r \in \mathbb{R}^{d_h \times \text{3}n_{joint}}$ is the parameter of the linear layer. Note that, as mentioned earlier, the decoder uses the reversed input motion as the target motion, so the reconstruction is performed in the order of $\widehat{\mQ}_{(t+\Delta t -1):t} = [\widehatt{\vq}_{t+\Delta t -1}, \ldots, \widehat{\vq}_t]$. Unlike the encoder, the decoder uses the reconstructed result of the previous frame as the input \cite{martinez2017human, li2017auto}. This is equivalent to the noise scheduling \cite{bengio2015scheduled} without parameter tuning for long term reconstruction, and it also helps prevent the overfitting. The initial input $\widehat{\vq}_{t+\Delta t}^r$ to the GRU is set zero because there is no reconstruction result of the previous frame. The reconstructed joint rotations are used to calculate the angle loss with respect to the target motion, and are also used to calculate the position $\widehat{\vp}_{i}^r$ through the FK layer. \begin{equation} \label{eq:out_rot_fk} \begin{aligned} \widehat{\vp}_{i}^r = \, \text{Forward Kinematics} \, (\widehat{\vq}_{i}^r) \end{aligned} \end{equation} After the last pose $\widehat{\vq}_t$ is generated, the joint decoder mapping $Dec^r: \, \mathcal{Z} \rightarrow \mathcal{Q}$ is completed. \paragraph*{Joint Velocity Decoder} \label{par:dec_vel} The joint velocity decoder has the similar structure to the joint rotation decoder. The main difference is that it has a residual connection to generate $\widehat{\vq}_{i}^v$. \begin{align} h_i^{\text{dec}^v} &= \text{GRU}_{W_{\text{Dec}^v}}(h_{i+1}^{\text{Dec}^v}, \, {\color{green} \widehat{\vq}_{i+1}^v} ), \label{eq:de_vel} \\ \widehat{\vq}_{i}^v &= W_o^{v \, T} h_i^{\text{Dec}^v} + \, \widehat{\vq}_{i+1}^v, \label{eq:de_vel_output}\\ \widehat{\vp}_{i}^v &= \, \text{Forward Kinematics} \, (\widehat{\vq}_{i}^v), \label{eq:out_vel_fk} \end{align} where $W_{\text{Dec}^v} \in \mathbb{R}^{\text{3}n_{\text{joint}} \times d_h}$ and $W_o^{v}$ are the learning parameters. This residual network learns the difference between the current frame pose $\widehat{\vq}_{i}^v$ and the previous frame pose $\widehat{\vq}_{i+1}^v$. Therefore, the model predicts the angle difference or velocity and integrates it over time. After the last pose is generated, the joint velocity decoder mapping $Dec^v: \, \mathcal{Z} \rightarrow \mathcal{Q}$ is completed. \subsection{Training the motion manifold} \label{subsec:train} \begin{figure*}[th] \centering \includegraphics[width=0.85\textwidth]{figures/loss_overview.jpeg} \caption{Each loss term is evaluated from the data processed in the network pipeline shown with black arrows. Red arrows indicate the data used for the individual loss terms.} \label{fig:loss_overview} \end{figure*} We model a number of loss functions, each of which contributes to enhancing the quality of the motion generated from the motion manifold from different perspectives. To reduce the reconstruction loss, we employ two kinds of loss functions: Motion reconstruction loss $L_R$ that encourages a motion to be reconstructed after going through the encoder and decoder, and manifold reconstruction loss $L_M$ that helps a latent vector be reconstructed after going through the decoder and encoder. In addition, we include Wasserstein loss $L_W$ that penalizes the discrepancy between $P_Z$ and the distribution $E_Z$ induced by the encoder, and an adversarial loss $L_G$ to achieve more natural motions from the motion manifold. Figure~\ref{fig:loss_overview} shows overview of our loss functions. \paragraph*{Motion reconstruction loss} \label{par:motion_recon_loss} The motion reconstruction loss penalizes the difference between the motion and the reconstructed motion, which is obtained by encoding the motion followed by decoding it. Specifically, we measure the discrepancy of both the joint rotation angle $\vq$ and the joint position $\vp$ as follows: \begin{align} L_R &= L_{ang} + w_p L_{pos} \label{eq:motion_recon_loss} \\ L_{ang} &= \sum_i^{n_{joint}} \parallel \widehat{\vq}_{i}^r - \vq_i \parallel + \parallel \widehat{\vq}_{i}^v - \vq_i \parallel \\ L_{pos} &= \sum_i^{n_{joint}} \parallel \widehat{\vp}_{i}^r - \vp_i \parallel + \parallel \widehat{\vp}_{i}^v - \vp_i \parallel, \end{align} where $\parallel \cdot \parallel$ is the Euclidean norm and $w_p$ (= 5 in our experiment) is the weight of the position error. \paragraph*{Manifold reconstruction loss} \label{par:manifold_recon_loss} A latent code sampled from the latent distribution should be reconstructed after decoding and encoding. Manifold reconstruction loss encourages this reciprocal mapping between the motions and the manifold space. To this end, we apply $L_{1}$ loss similar to \cite{lee2018diverse}. We draw a motion manifold vector $Z$ from the encoded motion sequences and reconstruct it with $\widehat{Z}^r = Enc(Dec^r(Z))$ and $\widehat{Z}^v = Enc(Dec^v(Z))$, where $Z = Enc(\mQ_{t:(t+\Delta t -1)})$. \begin{equation} \label{eq:manifold_recon_loss} L_M = \, \parallel \widehat{Z}^r - Z \parallel_1 \, + \parallel \widehat{Z}^v - Z \parallel_1 \end{equation} \paragraph*{Wasserstein regularizer loss} \label{par:wa_loss} In order to make the manifold space have a particular desired prior distribution so that we can efficiently sample from the distribution, we use the Wasserstein regularizer that penalizes deviation of the distribution $E_Z$ of the latent manifold from the desired prior distribution $P_Z$. \begin{equation} \label{eq:MMD} L_W = \text{MMD}_k(P_Z,E_Z), \end{equation} where $P_Z(Z) = \mathcal{N}(Z; \, \mathbf{0}, \, \sigma_z^2 \cdot \mathbf{I_d})$ is modeled as the multivariate normal distribution with $\sigma_z^2$ being decided through validation. We use the maximum mean discrepancy $\text{MMD}_k$ to measure the divergence between two distributions with the inverse multi-quadratics kernel $k(x,y)=C/(C+\parallel x-y \parallel_2^2)$ with $C=2Z_{\text{dim}}\sigma_z^2$. We set $\sigma_z^2=1$ and the dimension of motion manifold space $Z_{\text{dim}}=64$. \paragraph*{Adversarial loss} \label{par:ad_loss} Finally, we employ the least squares generative adversarial network (LSGAN) to match the distribution of generated motion to the real motion data distribution, i.e., to promote motions generated by our model to be indistinguishable from real motions. \begin{equation} \label{eq:dis_loss} \begin{aligned} L_D =&\frac{1}{2} \sum_{\widehat{\mQ}_{t:(t+\Delta t -1)}} \left[D(\widehat{\mQ}_{t:(t+\Delta t -1)})-0 \right]^2 \,\, + \\ &\frac{1}{2} \sum_{\mQ_{t:(t+\Delta t -1)}} \left[D(\mQ_{t:(t+\Delta t -1)})-1 \right]^2 \end{aligned} \end{equation} \begin{equation} \label{eq:GAN_loss} L_G =\frac{1}{2} \sum_{\widehat{\mQ}_{t:(t+\Delta t -1)}} \left[D(\widehat{\mQ}_{t:(t+\Delta t -1)})-1 \right]^2 \,\,\,\,\,\, \end{equation} where the discriminator $D$ tries to distinguish between the reconstructed motions and the real motions. The discriminator is then used to help our decoder generate realistic motions. \paragraph*{Total loss} \label{par:total_loss} We jointly train the encoder, joint rotation decoder, joint velocity decoder and discriminator to optimize the total objective function, which is a weighted sum of the reconstruction loss, Wasserstein regularizer loss and adversarial loss. The total objective function of manifold network is: \begin{equation} \label{eq:GAN_loss} \begin{aligned} \min_{Enc,\, Dec^r,\, Dec^v} & \,\, L(Enc, Dec^r, Dec^v) \\ & = L_R + \lambda_M \,\, L_M +\lambda_W \,\, L_W + \lambda_G \,\, L_G \end{aligned} \end{equation} and the discriminator loss is: \begin{equation} \label{eq:GAN_loss} \min_{D} \,\, L(D) = \lambda_G \,\, L_D, \end{equation} where weighting parameters $\lambda_M$, $\lambda_W$ and $\lambda_G$ are $0.001$, $0.1$, and $0.001$ determined through validation. \section{Data pre-processing} \label{sec:data} We tested our method with H3.6M dataset. Every motion in the dataset has the same skeletal structure. All the poses are represented with the position and orientation of the root and the joint rotations expressed with the exponential coordinates. For the training, motion clips of 150 frames are randomly selected from the input motion sequence and used to learn a motion manifold. The root position in the transverse plane is removed and other data are normalized for better performance. We will explain how motion dataset is processed. \paragraph*{H3.6M dataset} H3.6M dataset \cite{h36m_pami} consists of 15 activities such as walking, smoking, discussion, taking pictures, and phoning performed by 7 subjects. We reduce 32 joints in the original data to 17 joints by removing redundant joints as done by \cite{martinez2017human}, and configured all data to have a frame rate of 25 Hz. Therefore, 150 frames motion applied to our model cover 6 seconds. The activities of subject S5 were used as the test data and those of the remaining subjects S1, S6, S7, S8, S9 and S11 were used as the training data. {\color{green} Some motion data contain noises such as joint popping, but was used without noise removal.} \section{Experimental Results} \label{sec:result} We perform several experiments to evaluate the performance of our method. First, we compare the reconstruction accuracy of the proposed model with its own variations with some components ablated as well as the sequence-to-sequence model proposed by \cite{martinez2017human}. Next, we test random sampling, motion interpolation via motion manifold, and motion denoising, followed by an experiment for motion analogies. {\color{green} For these tests, we use the joint rotation decoder to generate motions.} We qualitatively compare the result of motion interpolation and motion analogies with that of \cite{holden2015learning} \footnote{\cite{holden2015learning} is not compared with ours with respect to the reconstruction quality as it deals only with joint positions and not joint angles.}. All experiments were conducted with test sets not included in the training set. The supplemental video shows the resulting motions from the experiments. \subsection{Motion and manifold reconstruction} \label{subsec:result_recon} \begin{table*}[t] \centering \resizebox{0.9\textwidth}{!}{% \begin{tabular}{@{}ccccccccccccc@{}} \toprule \multicolumn{2}{c}{} & \multicolumn{2}{c}{1.2s} & \multicolumn{2}{c}{2.4s} & \multicolumn{2}{c}{3.6s} & \multicolumn{2}{c}{4.8s} & \multicolumn{2}{c}{6.0s} & \\ \cmidrule(lr){3-12} \multicolumn{2}{c}{\multirow{-2}{*}{Model}} & $E_r$ & $E_p$ & $E_r$ & $E_p$ & $E_r$ & $E_p$ & $E_r$ & $E_p$ & $E_r$ & $E_p$ & \multirow{-2}{*}{$E_z$} \\ \midrule & rot & 0.889 & 0.957 & 0.971 & 0.978 & 0.990 & 1.040 & 1.097 & 1.078 & 1.195 & \multicolumn{1}{c|}{1.181} & 0.317 \\ \multirow{-2}{*}{{$\mathbf{S}$}} & vel & - & - & - & - & - & - & - & - & - & \multicolumn{1}{c|}{-} & - \\ & rot & \textbf{0.823} & 0.855 & {\ul 0.868} & 0.923 & 0.925 & 0.999 & 1.039 & 1.032 & 1.164 & \multicolumn{1}{c|}{1.167} & 0.264 \\ \multirow{-2}{*}{{$\mathbf{D}$}} & vel & {\ul 0.856} & 0.889 & \textbf{0.843} & 0.889 & {\ul 0.877} & 0.961 & 1.008 & 1.081 & 1.127 & \multicolumn{1}{c|}{1.212} & 0.259 \\ & rot & 1.020 & 0.561 & 1.099 & 0.682 & 1.110 & 0.706 & 1.195 & 0.761 & 1.261 & \multicolumn{1}{c|}{0.822} & 0.196 \\ \multirow{-2}{*}{{{$\mathbf{DK}$}}} & vel & 1.347 & 0.600 & 1.353 & 0.698 & 1.323 & 0.723 & 1.382 & 0.756 & 1.391 & \multicolumn{1}{c|}{{\color[HTML]{000000} 0.809}} & 0.288 \\ & rot & 0.986 & {\ul 0.549} & 1.077 & \textbf{0.657} & 1.094 & {\ul 0.679} & 1.180 & 0.726 & 1.251 & \multicolumn{1}{c|}{0.810} & 0.188 \\ \multirow{-2}{*}{{{$\mathbf{DKG}$}}} & vel & 1.343 & 0.589 & 1.345 & 0.682 & 1.332 & 0.702 & 1.405 & 0.765 & 1.415 & \multicolumn{1}{c|}{ 0.834} & 0.307 \\ & rot & 0.997 & \textbf{0.541} & 1.066 & {\ul 0.659} & 1.084 & \textbf{0.668} & 1.162 & \textbf{0.696} & 1.258 & \multicolumn{1}{c|}{\textbf{0.780}} & 0.182 \\ \multirow{-2}{*}{{{$\mathbf{DKGM}$}} (ours)} & vel & 1.356 & 0.590 & 1.381 & 0.673 & 1.338 & 0.694 & 1.400 & 0.735 & 1.406 & \multicolumn{1}{c|}{0.792} & 0.293 \\ & rot & 0.906 & 0.629 & 0.909 & 0.730 & 0.886 & 0.724 & {\ul 0.954} & 0.754 & {\ul 1.053} & \multicolumn{1}{c|}{{\ul 0.788}} & {\ul 0.164} \\ \multirow{-2}{*}{{{$\mathbf{DKGMZ}$}}} & vel & 0.877 & 0.635 & 0.883 & 0.703 & \textbf{0.848} & 0.689 & \textbf{0.916} & {\ul 0.706} & \textbf{1.030} & \multicolumn{1}{c|}{0.815} & \textbf{0.157} \\ & rot & - & - & - & - & - & - & - & - & - & \multicolumn{1}{c|}{-} & - \\ \multirow{-2}{*}{Seq2seq} & vel & 0.875 & 0.863 & 0.870 & 0.954 & 0.891 & 1.059 & 1.039 & 1.177 & 1.154 & \multicolumn{1}{c|}{1.258} & 0.216 \\ \bottomrule \end{tabular} } \caption{{\color{green} Reconstruction errors of joint angles ($E_r$) and joint positions ($E_p$) at sample time frames, and the reconstruction error of the manifold vector ($E_z$). The error is measured with respect to the general actions (all the actions in the DB) in H3.6M dataset.}} \label{table:H3.6M_general} \end{table*} We assess the {accuracy} of the reconstructed motion $\widehat{\mQ}$ with respect to the input motion $\mQ$, as well as the {accuracy} of the reconstructed motion manifold vector $\widehat{\vz}$ with respect to the motion manifold vector $\vz$ obtained by encoding a motion. The results are provided in Table~\ref{table:H3.6M_general}. Generally, the reconstruction {accuracy} and the data generation quality of a manifold conflict with each other to some degree. As our purpose is to achieve a motion manifold that supports not only the motion reconstruction but also motion generation, it is important to strike a balance among various performance measures, and our method should not be evaluated only by the reconstruction {accuracy}. This trade off will be discussed in Sec. \ref{subsec:tradeoff}. The sequence-to-sequence model (Seq2seq) compared with ours is based on \cite{martinez2017human}. The only difference is that a fully connected layer of 64 dimension is implemented between the encoder and the decoder to construct a motion manifold. {\color{green} For ablation study, we prepare a set of variations of our model. The most basic model, denoted {$\mathbf{S}$}, has only joint rotation decoder with reconstruction and Wasserstein regularizer losses, without the FK layer in the network. Next model {$\mathbf{D}$} is the dual decoder model by adding the velocity decoder. From the dual model, we make variations by incrementally accumulating FK layer ({{$\mathbf{DK}$}}), adversarial loss ({{$\mathbf{DKG}$}}), manifold reconstruction loss ({{$\mathbf{DKGM}$}}, our method). The last variation {{$\mathbf{DKGMZ}$}} is made by concatenating the manifold vector to the decoder input, i.e., $\left[ \widehat{\vq}_{i+1}, \, Z \right]$ is used instead of $\widehat{\vq}_{i+1}$ in Eqs. \ref{eq:out_rot} and \ref{eq:de_vel}. The idea of this last variation is to prevent the decoder from forgetting the motion manifold vector. } All variations have the same network weight dimensions and hyper-parameters as our model. Supplemental material includes details of implementing the compared models. All models are trained with datasets that include all action categories. The {accuracy} of the motion reconstruction is evaluated for both the joint rotation decoder ($Dec^r$) and the joint velocity decoder ($Dec^v$). Both the Euclidean distances of joint angle errors ($L_{ang}$, also denoted as $E_r$) and joint position errors ($L_{pos}$ or $E_p$) are {\color{green} used for each decoder for the reconstruction loss}. As for the reconstruction quality of the motion manifold vector, we measure the $L_1$-norm ($E_z$) of the difference between the motion manifold vector $\vz$ obtained by encoding a motion sequence and the reconstructed vector $\widehat{\vz}^r$ obtained by sequentially decoding $\vz$ and encoding it. \begin{figure}[h] \centering \includegraphics[width=0.99\linewidth]{figures/reconstruction.jpeg} \caption{Ground truth motions (green) and reconstruction results (coral) of our method from H3.6M dataset.} \label{fig:recon} \end{figure} Table~\ref{table:H3.6M_general} shows the reconstruction errors of our method and others for the datasets containing all action categories (15 actions in H3.6M dataset). The reported errors are the average of 30 motions randomly selected from a test dataset. A total of 150 frames are divided into 5 intervals, and errors ($E_r$, $E_p$) are measured for each interval to investigate the temporal characteristic. The lowest and the next lowest errors are marked in bold and with underline, respectively. {\color{green} We first compare with respect to $E_r$ and $E_p$ errors. Comparing {$\mathbf{S}$} and {$\mathbf{D}$}, the latter has lower $E_r$ and $E_p$ errors, which suggests that the joint rotation and velocity decoders complement with each other to reduce the errors. Comparing {$\mathbf{D}$} and {{$\mathbf{DK}$}}, the latter reduces $E_p$ error significantly while only mildly sacrificing $E_r$ error. {{$\mathbf{DKG}$}} has lower $E_r$ and $E_p$ errors than {{$\mathbf{DK}$}}, but higher errors than {$\mathbf{D}$} and {$\mathbf{S}$}. This shows that adversarial loss slightly reduces reconstruction error. However, it turns out that the adversarial loss helps reconstruct the original behaviors, as will be discussed in Sec.~\ref{subsec:ZAd}. Examining the error of {{$\mathbf{DKGM}$}} and {{$\mathbf{DKGMZ}$}}, we can see that adding manifold reconstruction loss does not significantly affect the reconstruction errors while explicitly feeding the manifold vector to the decoder helps reduce the errors. Next, we examine manifold reconstruction error, $E_z$ ({\color{green} = $L_M$}). Comparing {$\mathbf{D}$} and {$\mathbf{S}$}, it is remarkable that {$\mathbf{D}$} reduces $E_z$ error even without any manifold-related loss term. However, adding FK layer to reduce joint position error slightly increases $E_z$ for the velocity decoder while it is decreased for the rotation decoder. Comparing {{$\mathbf{DK}$}} and {{$\mathbf{DKG}$}}, we can see that adversarial loss has negligible effect to the manifold reconstruction error. Subsequently, {{$\mathbf{DKGM}$}} reduces $E_z$ slightly by adding the manifold reconstruction error, and {{$\mathbf{DKGMZ}$}} achieves the lowest $E_z$ error by explicitly feeding the manifold vector to the decoder. {\color{green} Seq2seq~\cite{martinez2017human} shows less $E_r$ than our model, but $E_p$ is higher. In addition, our model shows better $E_z$ errors with respect to rotation decoder.} Figure~\ref{fig:recon} visualizes the reconstruction results with our model over time in comparison with the ground truth input motion. } \subsubsection{Trade off between joint angle, joint position and motion manifold} \label{subsec:tradeoff} \begin{figure*}[th] \centering \subfigure[$L_{ang}$ with respect to $\lambda_W$] {\includegraphics[width=0.33\linewidth]{figures/MMD_joint_anlge.png}} \hfill \subfigure[$L_{pos}$ with respect to $\lambda_W$] {\includegraphics[width=0.33\linewidth]{figures/MMD_joint_pos.png}} \hfill \subfigure[$L_{M}$ with respect to $\lambda_W$] {\includegraphics[width=0.33\linewidth]{figures/MMD_manifold.png}} \hfill \caption{Reconstruction errors of joint angle, joint position and manifold according to training step while adjusting $\lambda_W$ for H3.6M dataset.} \label{fig:tradeoff} \end{figure*} This experiment examines the effect of different settings of the weight $\lambda_W$ for the regularization on the reconstruction errors ($L_{ang}$ and $L_{pos}$) and on motion manifold ($L_M$) on the test set. We employed {$\mathbf{D}$} model for this experiment to exclude the effect of other loss terms. Figure~\ref{fig:tradeoff} (a) and (b) show that the joint reconstruction errors decrease as $\lambda_W$ becomes smaller, which makes {$\mathbf{D}$} model closer to a pure autoencoder, sacrificing the ability to enforce a prior over the motion manifold space while obtaining better reconstruction loss. For the same reason, Fig.~\ref{fig:tradeoff} (c) shows that the motion manifold reconstruction error $L_M$ decreases as $\lambda_W$ becomes larger. As our goal is to obtain an effective motion manifold that is able to generate realistic motions, it is important to find a suitable set of weight parameters that compromise among different qualities. {\color{green} \subsubsection{Adversarial loss and explicit feeding manifold vector} \label{subsec:ZAd} \begin{figure}[h] \centering \includegraphics[width=0.9\columnwidth]{figures/ablation_study.jpeg} \caption{{\color{green} Reconstruction results of different loss combinations for a posing while walking motion. Supplementary video includes full motions.} } \label{fig:ablation} \end{figure} Here we discuss the effects of adversarial loss (Sec.~\ref{par:ad_loss}) and explicitly feeding motion manifold vector to the decoders on motion quality. First, Table~\ref{table:H3.6M_general} shows that {{$\mathbf{DKG}$}} decreases $E_r$ from {{$\mathbf{DK}$}} only slightly. However, Fig.~\ref{fig:ablation} shows that {{$\mathbf{DK}$}} cannot properly reconstruct the original motion, reconstructing only posing motion from the original motion of posing with walking. In contrast, {{$\mathbf{DKG}$}} improves the overall motion quality by better reconstructing the behaviors in the original motion. Comparing our method ({{$\mathbf{DKGM}$}}) and {{$\mathbf{DKGMZ}$}}, the latter results in lower $E_r$ and $E_p$ than our method as shown in Table.~\ref{table:H3.6M_general}. However, Fig.~\ref{fig:ablation} reveals that {{$\mathbf{DKGMZ}$}} fails to capture walking motion. We conjecture that directly feeding manifold vector to decoder reduces reconstruction loss by explicitly retaining the motion manifold vector, but tends to converge to mean pose. In contrast, our method successfully reconstructs the original posing with walking behavior. This observation suggests that, while the joint reconstruction error is an important indicator of motion quality, it may not appropriately assess the motion quality in terms of reconstructing the original behaviors. } \subsection{Random motion samples} \label{subsec:sampling} To verify whether the latent motion manifold can create meaningful motions, we randomly sampled $P_Z$ and decoded to obtain motions. We extracted 30 random samples from the motion manifold learned with H3.6M dataset. \begin{figure}[h] \centering \includegraphics[width=0.99\linewidth]{figures/random_sampling_compare.jpeg} \caption{Results of randomly sampling motions from the motion manifold $P_Z$.} \label{fig:randomsampling} \end{figure} Figure \ref{fig:randomsampling} is the results of random sampling from $P_Z$, and one can see that our method can create various actions including sitting, crossing the legs, and resting on the wall. This result suggests that our motion manifold and decoder can create a wide range of plausible behaviors. {\color{green} To examine the importance of WAE, we experimented random sampling by replacing the WAE regularizer with a simple $L_2$-norm ${\lVert z \rVert}^2$ loss. Sampled motions from this method, as shown in Fig. \ref{fig:randomsampling} (right), often show unnatural poses and extreme joint rotations. This experiment shows that the WAE regularizer not only helps achieve the desired motion manifold distribution but also improves quality of motion sampling. } \subsection{Motion interpolation with latent motion manifold} \label{subsec:interpolation} We can interpolate two different motions by encoding them into the latent motion manifold and then performing linear interpolation between the encoded motion manifold vectors. The resulting interpolated motion created by our method is not just frame-by-frame interpolation, but may contain meaningful transition between the input motions. For example, interpolating sitting down motion and photo taking motion creates hand raising motion to prepare to take a picture from sitting posture. When waiting and smoking motions are interpolated, an interesting motion that a character seems tired of waiting and starts to smoke is created. The capability of creating such meaningful motions is due to the Wasserstein regularizer that shortens the distance between the encoded vectors by matching the motion manifold to the multivariate normal prior. Figure \ref{fig:interpolation} and the supplemental video show the interpolated motions. Figure~\ref{fig:inter_compare} compares our model with \cite{holden2015learning} with respect to interpolation. See supplementary material for the implementation of \cite{holden2015learning}. For the interpolation from sitting to walking (top) and from sitting down to taking photo (bottom), our model shows a natural transition between two motions while \cite{holden2015learning} creates somewhat averaged motion between the two motions. \begin{figure}[h] \centering \includegraphics[width=0.99\linewidth]{figures/interpolation_compare.jpeg} \caption{Interpolation from sitting to walking (top) and from sitting down to taking photo (bottom) made by our model (left) and \cite{holden2015learning} (right).} \label{fig:inter_compare} \end{figure} \subsection{Denoising motion data} \label{subsec:denoising} Our motion model can denoise motion data by projecting it to the latent motion manifold and decoding the motion manifold vector to obtain a reconstructed motion. {\color{green} Since the motion manifold is constructed only from human motion capture data, any element in the manifold is likely to be decoded to natural motion. Therefore, denoising effect occurs when noisy motion data is projected to the motion manifold.} We experiment on the denoising capability of our method in the similar manner as in \cite{holden2015learning}. We generate noise corrupted motion by randomly setting joint angles to zero with a probability of 0.5, which makes half of the joint angle information meaningless. Figure \ref{fig:noise} shows the denoised results which are quite similar to the ground truth motions. \begin{figure}[h] \centering \includegraphics[width=0.99\linewidth]{figures/noise.jpeg} \caption{Denoising experiment. Three poses are shown from the noise corrupted motion (orange), denoised motion by our method (coral), and the ground truth motion (green). Two motions (top and bottom) are shown.} \label{fig:noise} \end{figure} \subsection{Motion analogy} \label{subsec:analogy} \begin{figure}[h] \centering \subfigure[{Motion analogy among ``Walking with posing'', ``Walking'' and ``Sitting'' actions.}] {\includegraphics[width=0.99\linewidth]{figures/analogy.jpeg}} \hfill \subfigure[{Motion analogy among ``Smoking with sitting'', ``Sitting'' and ``Walking'' actions.}] {\includegraphics[width=0.99\linewidth]{figures/analogy2.jpeg}} \hfill \caption{{\color{green} Motion analogy experiments performing arithmetic operations in the motion manifold.}} \label{fig:analogies} \end{figure} Through motion analogy, we can understand how our model organizes motion manifold to represent the feature of actions. Details about analogy can be found in \cite{white2016sampling}. We perform vector algebraic operations with the latent vectors encoded from different motions and explore how the model organizes the latent space to represent motions. {\color{green} Figure \ref{fig:analogies} (a) shows that subtracting a motion manifold vector for ``sitting down'' motion from ``taking photo with sitting down'' motion creates a vector representing ``taking photo'' motion. The character is standing because a zero vector in our motion manifold corresponds to an idle standing motion. Subsequently, when an encoded ``walking'' motion manifold vector is added, the motion vector becomes a vector for ``taking photo with walking'' motion. Figure \ref{fig:analogies} (b) shows a similar analogy among ``walking'', ``smoking with walking'', and ``sitting'' motions.} \begin{figure}[h] \centering \includegraphics[width=0.99\linewidth]{figures/analogy_Holden.jpeg} \caption{{\color{green} Motion analogy experiment with \cite{holden2015learning}.}} \label{fig:anal_Holden} \end{figure} Figure \ref{fig:anal_Holden} shows the experiments of performing analogy with \cite{holden2015learning}. {\color{green} Figure \ref{fig:anal_Holden} (top) is the result of taking photo (left) and taking photo with walking (right) that correspond to Fig. \ref{fig:analogies} (a), and Fig. \ref{fig:anal_Holden} (bottom) shows smoking and smoking with sitting to compare with Fig. \ref{fig:analogies} (b).} One can see that the motion manifold obtained with \cite{holden2015learning} does not support analogy on the motion manifold. \section{Conclusion and future work} \label{sec:conclusion} In this paper, we presented a novel sequential network for constructing a latent motion manifold for modeling human motion. The main contributions of our method are the combined decoder for the joint rotation and joint velocity, and considering both the joint rotations and positions by adding the FK layer in both decoders, which improve the reconstruction accuracy. In addition, we composed a set of loss functions, each of which contribute to enhancing the quality of motions generated from the motion manifold space from different aspects. The capabilities of our model have been examined through various experiments such as random sampling, motion interpolation, denoising, and motion analogy. Our method has several limitations. First, as a sequence-to-sequence framework, the performance of our model degrades if trained to produce motions longer than 10 seconds. {\color{green} The supplementary video shows randomly generated motions with our network being trained to learn 300 frames (approx. 13 seconds). Resulting motions tend to lose details. } This limitation may be alleviated by employing an attention mechanism ~\cite{luong2015effective, bahdanau2014neural}. Second, the encoded motions tend to be smoothed in the process of matching the latent motion manifold to the prior distribution through the regularizer. For example, motions that contain frequent hand shaking, such as ``walking with dog'' or ``discussion'' motions in H3.6M dataset, lose fine details when reconstructed. Overcoming these limitations will be important future work. {\color{green} We only considered joint rotations in the encoder, but incorporating additional information, such as joint positions and velocities, may be beneficial to achieve better motion qualities. In addition, in the process of learning a motion manifold, loss terms to check validity of motions, such as joint limit, velocity limit and foot sliding, are not needed as all input motion data are considered valid. However, when an actual motion is sampled from the manifold and applied to an environment, such criteria may need to be checked. } Most studies on motion space learning have focused on representing a wide range of motion categories with a compact representation. In fact, the range of motion categories is only one aspect of the variedness of human motions. Even a single motion category such as walking exhibits widely different styles depending on gender, body scale, emotion, and personality. Developing a motion manifold that can generate stylistic variations of motion is another important future research direction. \section*{Acknowledgement} This work was supported by Giga Korea Project (GK17P0200) and Basic Science Research Program (NRF-2020R1A2C2011541) funded by Ministry of Science and ICT, Korea. \bibliographystyle{eg-alpha-doi}
{'timestamp': '2020-06-01T02:05:49', 'yymm': '2005', 'arxiv_id': '2005.14370', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14370'}
arxiv
\section{Introduction} Boolean automata networks (BANs) are studied for their capacity to succintly expose the complexity that comes with the composition of simple entities into a network. They belong to a wide family of systems which include cellular automata and neural networks, and can be described as cellular automata with arbitrary functions and on arbitrary graph structures. Understanding and predicting the dynamics of computing with BANs has been a focus of the scientific community which studies them, in particular since their applications include the modelling of gene regulatory networks~\cite{J-Kauffman1969,J-Thomas1973,J-Mendoza1998,J-Davidich2008,J-Demongeot2010}. In those applications, fixed points of a BAN are often viewed as cellular types and limit cycles as biological rhythms~\cite{J-Kauffman1969,J-Thomas1973}. It follows that most biological studies relying on BANs require the complete computation of their dynamics to propose conclusions. The complete computation of the dynamics of BANs is an exponentially costly process. Indeed, for $n$ the size of a BAN, the size of its dynamics is precisely $2^n$. The dynamics of a BAN is usually partitionned in two sorts of configurations: the recurring ones that are parts of attractors and either belong to a limit cycle or are fixed points; the others that evolve towards these attractors and belong to their attraction basins. The questions of characterising, computing or counting those attractors from a simple description of the network have been explored~\cite{C-Orponen1989,J-Aracena2008,J-Goles2008,J-Demongeot2012,C-Noual2012,J-Aracena2017}, and have been shown to be difficult problems~\cite{C-Orponen1989,C-Orponen1992,C-Bridoux2019,U-Bridoux2020,C-Nous2020}. In this paper, we propose a new method for computing the attractors of a BAN under the parallel update schedule. For any input network, this method generates another network which is possibly smaller and which is guaranteed to possess attractors isomorphic to those of the input network. Computing the dynamics of this smaller network therefore takes as much time as needed to compute the dynamics of the input networks, divided by some power of two. This method uses tools and results developed in previous works by the authors~\cite{C-Perrot2018,C-Perrot2020}. These works involve adding inputs to BANs, in a generalisation called modules that proposes in some cases the study of the computationnal capabilities of the network as the computation in terms of the inputs. In particular, a result states that two networks that have equivalent such computations share isomorphic attractors. Section~\ref{s:Definitions} starts by exposing all the definitions needed to read this paper. Section~\ref{s:PartA} explores the question of obtaining an acyclic module (AM) from a BAN. Section~\ref{s:PartB} explains how to extract so called output functions from a module. Section~\ref{s:PartC} details how to generate a minimal module from a set of output functions. Finally Section~\ref{s:PartD} shows the final step of the method, which implies constructing a BAN out of an AM and computing its dynamics. Each section explores complexity results of the different parts of the process, and details examples along the way. An illustrative outline of the paper can be found in Figure~\ref{f:Plan}. \input{figures/plan} \section{Definitions} \label{s:Definitions} \subsection{Boolean functions} In this paper, we consider a Boolean function as any function $f : \mathbb{B}^A \to \mathbb{B}$, for $A$ a finite set. An affectation $x$ of $f$ is a vector in $\mathbb{B}^A$. When considered as the input or output of a complexity problem, we encode Boolean functions as Boolean circuits. A \emph{Boolean circuit} of $f$ is an acyclic digraph in which nodes without incoming edges are labelled by an element in $A$, and every other node by a Boolean gate in $\{\wedge, \vee, \neg\}$, with a special node marked as the output of the circuit. The evaluation $f(x)$ is computed by mapping $x$ to the input nodes of the circuit, and propagating the evaluation along the circuit using the gates until the output node is reached. \subsection{Boolean automata networks and acyclic modules} \subsubsection{Boolean automata networks} BANs are composed of a set $S$ of automata. Each automaton in $S$, or node, is at any time in a state in $\mathbb{B}$. Gathering those isolated states into a vector of dimension $|S|$ provides us with a configuration of the network. More formally, a \emph{configuration} of $S$ over $\mathbb{B}$ is a vector in $\mathbb{B}^S$. The state of every automaton is bound to evolve as a function of the configuration of the entire network. Each node has a unique function, called a local function, that is predefined and does not change over time. A \emph{local function} is thus a function $f$ defined as $f: \mathbb{B}^S \to \mathbb{B}$. Formally, a BAN $F$ is a set that assigns a local function $f_s$ over $S$ for every $s \in S$. \begin{example} \label{ex1-BAN-def} Let $S_A = \{a, b, c, d\}$. Let $F_A$ be the BAN defined by $f_a(x) = x_d$, $f_b(x) = f_c(x) = x_a$, and $f_d(x) = \neg x_b \vee \neg x_c$. The interaction digraph of this BAN is depicted in Figure~\ref{f:ex:BAN} (left panel). \end{example} \begin{example} \label{ex2-BAN-def} Let $S_B = \{St, Sl, Sk, Pp, Ru, S9, C, C25, M, C^*\}$. Let $F_B$ be the BAN defined by $f_{St}(x) = \neg x_{St}$, $f_{Sl}(x) = \neg x_{Sl} \vee x_{C^*}$, $f_{Sk}(x) = x_{St} \vee \neg x_{Sk}$, $f_{Pp}(x) = x_{Sl} \vee \neg x_{Pp}$, $f_{Ru}(x) = f_{S9}(x) = \neg x_{Sk} \vee x_{Pp} \vee \neg x_C \vee \neg x_{C^*}$, $f_C(x) = \neg x_{Ru} \vee \neg x_{S9} \vee \neg x_{Sl}$, $f_{C25}(x) = \neg x_{Pp} \vee x_C$, $f_{M}(x) = x_{Pp} \vee \neg x_C$, and $f_{C^*}(x) = \neg x_{Ru} \vee \neg x_{S9} \vee x_{C25} \vee \neg x_M$. The interaction digraph of this BAN is depicted in Figure~\ref{f:ex:BAN} (right panel). \end{example} \input{figures/exampleBAN} In the scope of this paper, BANs (and modules) are udpated according to the parallel update schedule. Formally, for $F$ a BAN and $x$ a configuration of $F$, the update of $x$ under $F$ is denoted by configuration $F(x)$, and defined as for all $s$ in $S$, $F(x)_s = f_s(x)$. \begin{example} \label{ex1-BAN-update} Consider $F_A$ of Example~\ref{ex1-BAN-def}, and $x \in \mathbb{B}^{S_A}$ such that $x = 1001$. We observe that $F_A(x) = 1111$. Configurations $1000$ and $0111$ are recurring and form a limit cycle of size $2$, as well as configurations $0000$, $0001$, $1001$, $1111$, $1110$ and $0110$ that form a limit cycle of size $6$. \end{example} \subsubsection{Interaction digraph} BANs are usually represented by the influence that automata hold on each other. As such the visual representation of a BAN is a digraph, called an interaction digraph, whose nodes are the automata of the network, and arcs are the influences that link the different automata. Formally, $s$ \emph{influences} $s'$ if and only if there exist two configurations $x,x'$ such that $f_{s'}(x) \neq f_{s'}(x')$ and for all $r$ in $S$, $r \neq s$ if and only if $x_r = x'_r$. \subsubsection{Dynamics} Finally, we define the \emph{dynamics} of a BAN $F$ as the digraph with $\mathbb{B}^S$ as its set of vertices. There exists an edge from $x$ to $y$ if and only if $F(x) = y$. Computing the dynamics of a BAN from the description of its local function is an exponential process. See~\cite{B-Robert1986} for a more throughout introduction to BANs and related subjects. \subsubsection{Modules} Modules were first introduced in~\cite{C-Perrot2018}. A module $M$ is a BAN with added inputs. It is defined on two sets: $S$ a set of automata, and $I$ a set of inputs, with $S \cap I = \emptyset$. Similarly to standard BANs, we can define configurations as vectors in $\mathbb{B}^S$, and we define input configurations as vectors in $\mathbb{B}^I$. A local function of a module updates itself based on a configuration $x$ and an input configuration $i$, concatenated into one configuration. Formally, a local function is defined from $\mathbb{B}^{S \cup I}$ to $\mathbb{B}$. The module $M$ defines a local function for every node $s$ in $S$. \begin{example} Let $M_e$ be the module defined on $S_e = \{p, q, r\}$ and $I = \{\alpha, \beta\}$, such that $f_p(x) = x_\alpha$, $f_q(x) = \neg x_p$, and $f_r(x) = x_q \vee \neg x_\beta$. \end{example} We represent modules with an interaction digraph, in the same way as for BANs. The interaction digraph of a module has added arrows that represent the influence of the inputs over the nodes; for every node $s$ and every input $\alpha$, the node $s$ of the interaction digraph has an ingoing arrow labelled $\alpha$ if and only if $\alpha$ influences $s$, that is, there exists two input configurations $i,i'$ such that for all $\beta$ in $I$, $\beta \neq \alpha$ if and only if $i_\beta = {i'}_\beta$, and $x$ a configuration such that $f_s(x\cdot i) \neq f_s(x\cdot i')$, where $\cdot$ denotes the concatenation operator. A module is \emph{acyclic} if and only if its interaction digraph is cycle-free. \subsubsection{Recursive wirings} A recursive wiring over a module $M$ is defined by a partial function $\omega : I \not\to S$. The result of such a wiring is denoted $\circlearrowright_\omega M$, a module defined over sets $S$ and $I \setminus \mathrm{dom}(\omega)$, in which the local function of node $s$ is denoted $f'_s$ and defined as \begin{equation*} \forall x \in \mathbb{B}^{S \cup I},\ f'_s(x) = f_s( x \circ \hat \omega ), \text{ with } \hat\omega(i) = \begin{array}\{{ll}. \omega(i) & \text{if } i \in \mathrm{dom}(\omega)\\ i & \text{if } i \in I \setminus \mathrm{dom}(\omega) \end{array}\text{.} \end{equation*} \subsubsection{Output functions} Output functions were first introduced in~\cite{C-Perrot2020} and present another way of computing the evolution of an acyclic module. In the Boolean case, those functions are defined on $\mathbb{B}^{I \times \{1, \ldots, D\}} \to \mathbb{B}$, for I the input set of the module, and D some integer. We interpret an input in $\mathbb{B}^{I \times \{1, \ldots, D\}}$ as an evaluation over $\mathbb{B}$ of a set of variables ${I \times \{1, \ldots, D\}}$, and for $\alpha \in I$ and $d \leq D$, we denote this variable by $\alpha_d$. In the context of an acyclic module $M$, $\alpha_d$ is refering to the evaluation of the input $\alpha$ on the $d$th update of the module. A vector $j \in \mathbb{B}^{I \times \{1, \ldots, D\}}$ simply describes an evaluation of all the inputs of the network over $D$ iterations. With such a vector, and $x \in \mathbb{B}^S$, it is easy to see that the acyclic module $M$ can be updated $k$ times in a row, for any $k \leq D$. The result of this update is denoted by $M(x, j_{[1, \ldots, k]})$. The \emph{delay} of an output function $O$ is the maximal value in the set of all the $d \in \mathbb{N}$ for which there exists $\alpha \in I$ such that variable $\alpha_d$ has an influence on the computation of $O$. Finally, for $M$ an acyclic module defined on the sets $S$ and $I$, for $D$ a large enough integer, for $x \in \mathbb{B}^S$ and $j \in \mathbb{B}^{I \times \{1, \ldots, D\}}$ some vectors, and for $s$ a node in $S$, we define the output function of $s$, denoted $O_s$, as the output function with minimal delay $d$ such that $O_s(j) = M(x, j_{[1, \ldots, k]})_s$. Such a function always exists and is always unique. \subsection{Promise problems} In this paper, we make the hypothesis that every module passed as an input of a complexity problem follows the property that each of its local functions has only \emph{essential} variables. That is, a variable is included in the circuit encoding that function if and only if the automaton or input represented by that variable has an influence on said function. This hypothesis will be implemented throughout this paper by the use of promise problems~\cite{O-Goldreich2006}, which include a decision method which can dismiss instances of the problem without that method's complexity cost being included in the complexity of the problem. This approach is motivated by the fact that obfuscating the relation between automatons by building redundant variables in a circuit increases the complexity of most considered problems. We justify our decision in two points: first, the approach of this paper is one of providing and studying an applicable method in a context where misleading inputs in local functions are unlikely. Second, despite the inclusion of these promises we find high complexity issues in our pipeline, and as such we consider that it helps understanding the precise issues that prevent our method from being efficient. \section{From BANs to AMs} \label{s:PartA} The first step of our process is to unfold a BAN into an AM. This simply requires the removal of any cycle in the interaction digraph of the BAN, and their replacement by inputs. In the scope of this paper, the number of inputs generated is required to be minimal. This is justified by the fact that the complexity of most of the problems addressed in the pipeline highly depends on the number of inputs of the considered AM. \begin{fpproblem} \fpproblemtitle{Acyclic Unfolding Functional Problem} \fpprobleminput{A Boolean automata network $F$, an integer $k$.} \fpproblempromise{The encoding of the local functions of $F$ only has essential variables.} \fpproblemoutput{An acyclic module $M$ with at most $k$ inputs and a recursive wiring $\omega$ such that $\circlearrowright_\omega M = F$.} \end{fpproblem} \begin{theorem} \label{th-unfold-up} The Acyclic Unfolding Functional Problem is in $\text{FNP}$. \end{theorem} \begin{proof} The promise of this problem allows us to compute the interaction digraph of $F$ in polynomial time. Consider the following simple non-deterministic algorithm: first guess a module $M$ and a wiring $\omega$; then check that the number of inputs in $M$ is no more than $k$ and that $\circlearrowright_\omega M$ syntactically equals $F$. This algorithm operates in polynomial non-deterministic time since the recursive wiring is a simple substitution of variables, and thanks to the fact that one only needs to compare $\circlearrowright_\omega M$ and $F$ at a syntactical level. Indeed, if any solution exists, then a solution exists with the same number of nodes, the same inputs, the same wirings, and such that the substitution operated by $\omega$ on $M$ leads to the local functions of $F$ written identically: because all local functions are equal on a semantic level, this is always possible, by starting from the local functions of $F$ and operating variable substitutions that are then reversed by the recursive wiring $\omega$ (remark that this last ``reversed'' construction is not required to be computable in polynomial time). \end{proof} \begin{theorem} \label{th-unfold-down} The Acyclic Unfolding Functional Problem is $\text{NP}$-hard. \end{theorem} \begin{proof} Let us provide a reduction from the Feedback Vertex Set problem. We provide $f$ a function that for any instance $(G, k)$ of the Feedback Vertex Set problem, provides an instance $(F, k)$ of the Optimal Acyclic Unfolding Problem where $S = V(G)$ and $f_s$ is a OR function of exactly every node $s'$ such that $(s', s) \in A(G)$. This construction is explicitly designed so that the interaction digraph of $F$ is isomorphic to $G$. Clearly $f$ is computable in polynomial time. We also provide $g$ a function that for $(G, k)$ an instance of the Feedback Vertex Set problem, and $M$ a solution to the Optimal Acyclic Unfolding Problem, checks if $S = V(G)$, and then deduces the solution for $(G, k)$ the following way: $s$ is part of the feedback vertex set if and only if its influence has been replaced by an input in $M$. This means that the variable $x_s$ has been replaced in every local function in $M$ by the same input variable. Finally $g$ checks that the size of the obtained set is not greater than $k$. It is clear that $g$ is polynomial. From the definition of $f$ and $g$, it follows that the Feedback Arc Set problem reduces in polynomial time to the Optimal Acyclic Unfolding Problem, which implies the result. \end{proof} \begin{example} \label{ex1-AM} Consider $S_A$ and $F_A$ of Example~\ref{ex1-BAN-def}. Let us define $I_A = \{\alpha\}$. Let $M_A$ be the acyclic module that defines $f'_a(x) = x_{\alpha}$, $f'_b(x) = f'_c(x) = x_a$, and $f'_d(x) = \neg x_b \vee \neg x_c$. The module $M_A$ is a valid answer to the instance $F_A, k = 1$ of the Acyclic Unfolding Functional Problem. The interaction digraph of this module is represented in Figure~\ref{f:ex:MOD} (left panel). \end{example} \begin{example} \label{ex2-AM} Consider $S_B$ and $F_B$ of Example~\ref{ex2-BAN-def}. Let us define $I_B = \{\alpha_{St}, \alpha_{Sl}, \alpha_{Sk},$ $\alpha_{Pp}, \alpha_{C}, $ $\alpha_{C^*}\}$. Let $M_B$ be the acyclic module that defines $f'_{St}(x) = \neg x_{\alpha_{St}}$, $f'_{Sl}(x) = \neg x_{\alpha_{Sl}} \vee x_{\alpha_{C^*}}$, $f'_{Sk}(x) = x_{\alpha_{St}} \vee \neg x_{\alpha_{Sk}}$, $f'_{Pp}(x) = x_{\alpha_{Sl}} \vee \neg x_{\alpha_{Pp}}$, $f'_{Ru}(x) = f_{S9}(x) = \neg x_{\alpha_{Sk}} \vee x_{\alpha_{Pp}} \vee \neg x_{\alpha_C} \vee \neg x_{\alpha_{C^*}}$, $f'_C(x) = \neg x_{Ru} \vee \neg x_{S9} \vee \neg x_{\alpha_{Sl}}$, $f'_{C25}(x) = \neg x_{\alpha_{Pp}} \vee x_{\alpha_C}$, $f'_{M}(x) = x_{\alpha_{Pp}} \vee \neg x_{\alpha_C}$, and $f'_{C^*}(x) = \neg x_{Ru} \vee \neg x_{S9} \vee x_{C25} \vee \neg x_M$. The module $M_B$ is a valid answer to the instance $F_B, k = 6$ of the Acyclic Unfolding Functional Problem. The interaction digraph of this module is represented in Figure~\ref{f:ex:MOD} (right panel). \end{example} \input{figures/exampleMOD} \section{Output functions} \label{s:PartB} Output functions were first introduced in~\cite{C-Perrot2020}. They are a way to characterise the asymptotic behaviour of an AM as a set of Boolean functions that are computed from the local functions of the AM. Computing the output functions of an AM is a crucial step in the pipeline proposed in this work. \begin{fpproblem} \fpproblemtitle{Output Circuit Computation Problem} \fpprobleminput{An acyclic module $M$, and $X \subseteq S$ a set of output nodes.} \fpproblempromise{The encoding of the local functions of $M$ only has essential variables.} \fpproblemoutput {An output function for each node in $X$, encoded as a Boolean circuit.} \end{fpproblem} \begin{theorem} The Output Circuit Computation Problem is in FP. \end{theorem} \begin{proof} The promise of this problem allows us to deduce the interaction digraph of $M$ in polynomial time. To compute $X$, we provide an algorithm to compute the output function circuit of any node $s \in S$ in polynomial time. The algorithm first constructs a list of requirements. This list is initialy $R_0 = \{(s, 0)\}$, which can be interpreted to say that we require the construction of the output function of $s$ with added delay $0$. We construct the next list the following way: $(t', d') \in R_{k+1}$ if and only if there exists some $(t, d) \in R_{k}$ such that $t'$ influences $t$ in $M$. The total list $R$ is simply defined as $R = \bigcup_{i \in \mathbb{N}} R_i$. \begin{claim} $R$ is computable in polynomial time in the size of $M$. \end{claim} To see that this is true, consider that for $D$ the maximal depth of $M$, the maximal $d$ such that $(t, d) \in R_k$ for any $k$ is $D$. Indeed since the interaction digraph of $M$ is acyclic, the maximal delay value can only be obtained by following the longest path in $M$. As such we can conclude that the size of any $R_k$ is bounded by $D \times n$, for $n$ the size of the network $M$. Finally, by a similar argument, consider that the list $R$ converges after a maximum of $D$ steps. This implies that the list $R$ is computed after $D$ steps of a $D \times n$ costly process, and $R$ can therefore be computed in polynomial time. We can construct the Boolean circuit from $R$ in the following way: for every pair $(t, d) \in R$, take an instance of the Boolean circuit which encodes the local function of $t$. Combine all of these instances the following way: any input variable in $I$ is replaced by its delayed counterpart with delay $1 + d$. For example, if a variable $\alpha$ appeared in the local function of node $t$, substitute it by the variable $\alpha_{d + 1}$. Then, for any gate displaying an input variable $t' \in S$, replace it with the same gate, which rather than taking the value of variable $t'$, takes the value of the output of the circuit that computes the local function of the node $t'$ with added delay $d + 1$. By definition of $R$ this circuit will always be in $R$. The obtained circuit computes the output function of the node $s$. Repeat this process for every $s \in X$. \end{proof} \begin{example} \label{ex1-OUT} Consider $M_A$ of Example~\ref{ex1-AM}. Let $X_A = \{d\}$ be an instance of the Output Circuit Computation Problem. The circuit $O_d = \neg \alpha_3$ is a valid answer to that instance. \end{example} \begin{example} \label{ex2-OUT} Consider $M_B$ of Example~\ref{ex2-AM}. Let $X_B = \{St, Sk, Sl, Pp, C, C^*\}$ be an instance of the Output Circuit Computation Problem. The circuits $O_{St} = \neg \alpha_{St, 1}$, $O_{Sl} = \neg \alpha_{Sl, 1} \vee \alpha_{C^*, 1}$, $O_{Sk} = \alpha_{St, 1} \vee \neg \alpha_{Sk, 1}$, $O_{Pp} = \alpha_{Sl, 1} \vee \neg \alpha_{Pp, 1}$, $O_C = ( \alpha_{Sk, 2} \wedge \neg \alpha_{Pp, 2} \wedge \alpha_{C, 2} \wedge \alpha_{C^*, 2} ) \vee \neg \alpha_{Sl, 1}$ and $O_{C^*} = \alpha_{C, 2} \vee \neg \alpha_{Pp, 2}$ taken altogether are a valid answer to that instance. \end{example} \section{Optimal acyclic module synthesis} \label{s:PartC} \subsection{Module Synthesis} This part of the process takes in a set of output functions and generates a module that realizes these functions with an hopefully minimal number of nodes. In this part the actual optimisation of the pipeline, if any, can be directly observed. It is also the part of the pipeline which is the most computationnaly costly. \begin{fproblem} \fproblemtitle{Module Synthesis Problem} \fprobleminput{A set $I$ of input labels, a finite set of output functions $O$, encoded as Boolean circuits, defined on those labels, and $k$ an integer.} \fproblemoutput{An acyclic module $M$ with at most $k$ nodes such that every function in $O$ is the output function of at least one node in $M$.} \end{fproblem} \subsection{Complexity results} \begin{theorem} \label{th-syn-down} The Module Synthesis Problem is coNP-hard. \end{theorem} \begin{proof} Consider $f$ an instance of the Tautology problem, with $I$ the set of propositional variables contained in $f$. We define $f'$ as the output function defined on the labels $I$ such that $f'$ is obtained from $f$ by substituting all variables $\alpha \in I$ by their equivalent of delay 1, $\alpha_1$. Let us also define $f_1$ as the constant output function of delay $0$ which value is always $1$. We compose an instance of the Module Synthesis Problem with $I$ the set of input labels, $O = \{f', f_1\}$ and $k = 0$. This instance has a solution if and only there exists an acyclic module with only one node such that the output function of this node is equivalent to all the output functions in $O$. This implies that, if the problem has a solution, $f'$ is equivalent to $f_1$, which proves that $f'$ and $f$ are tautologies. Therefore computing the output of the Module Synthesis Problem requires solving a coNP-hard decision problem. \end{proof} \begin{theorem} The Module Synthesis Problem is in $\text{FNP}^\text{coNP}$. \end{theorem} \begin{proof} Consider the following algorithm. First, guess an acyclic module $M$, with size $k$. Compute every output function of the network, which is in FP. Then simply check that every function in $O$ is equivalent to at least one output function in $M$, which requires at most $|M| \times |O|$ calls to a $\text{coNP}$\ oracle. \end{proof} \subsection{Refining the complexity bounds} It is unclear whether the synthesis problem can be proven to be in $\text{FcoNP}$\ or to be $\text{NP}^\text{coNP}$-hard. An attempt has been made to prove the former by using a greedy algorithm which would fuse nodes in an acyclic module, starting from a trivially large enough module. This method requires solving the following problem: \begin{dproblem} \problemtitle{Module Local Fusion Problem} \probleminput{An acyclic module $M$ defined on sets $S$ and $I$, and $a, b$ two different nodes.} \problemquestion{Is there a local function $f_c$ such that there exists some acyclic module $M'$ defined on the node set $S \cup \{c\} \setminus \{a, b\}$ and input set $I$, such that $f_c \equiv f'_c$ and $O_s \equiv O'_s$ for $s \in S \setminus \{a, b\}$?} \end{dproblem} This problem formalises the idea of replacing two nodes by one in an acyclic module, such that every other output function in the module is conserved. Assuming the removed nodes are not considered outputs of the network is an important step of any greedy algorithm that would try to optimise the size of an acyclic module. It is rather simple to prove that this problem is coNP-hard, since its computation requires checking the equivalence of multiple pairs of Boolean circuits. It is also rather easy to see that it is in $\text{NP}^\text{coNP}$, as one can guess $f_c$ and $M'$ in polynomial time and verify the solution using a polynomial amount of calls to a $\text{coNP}$\ oracle, one for every equivalence check. The function $f_c$ could be composed as a binary function of the results of $f_a$ and $f_b$, as it is intuitive to suppose that assuming such a fusion is possible, then every node influenced by $a$ or $b$ should be computable from such a composition of $a$ and $b$. The issue however is that this process requires modifying every node influenced by $a$ or $b$ such that their output functions match the output functions in $M$. It is unclear that there should exist a method in $\text{coNP}$\ to ensure this modification such that the output functions are conserved. This leads us to believe that a greedy algorithm wouldn't prove the Optimal Module Synthesis Problem to be in $\text{FcoNP}$. Similarly, it is interesting to consider the open question of whether or not the Module Synthesis Problem can be proven $\text{NP}^\text{coNP}$-hard. This implies to prove, between other things, that the problem is $\text{NP}$-hard. This is, to us, another open problem as the Module Synthesis Problem does not seem equiped to compute the satisfaction of a Boolean formula or circuit. \subsection{Similarities to other optimisation problems} This open question bears strong ressemblance to another open problem that concerns Boolean circuits. The Circuit Minimisation Problem is a problem that asks to provide a Boolean circuit below a given size such that it computes a Boolean function given as a truth table as the input of the problem~\cite{C-Kabanets2000}. The problem is trivially in $\text{NP}$\ but it is not known whether the problem is in $\text{P}$ or $\text{NP}$-hard, as both possibilities imply proving other results which seem beyond the currently known techniques. The same problem has been found to be $\text{NP}$-complete in both restricted (DNFs) and generalised (unrestricted Boolean circuits) variations of the Boolean circuit model~\cite{C-Ilango2020}. There are strong similarities between acyclic modules and Boolean circuits. Both are defined on acyclic digraphs, have inputs and outputs, and compute Boolean functions. It is important to note that this analogy is misleading when talking about the optimisation of their size. Optimising a Boolean circuit requires the optimisation of a Boolean function in terms of the number of gates that computes it. Optimising an acyclic module, however, requires the optimisation of a network of functions with respect to a notion of delay of the inputs, whereas in this case one node may contain an arbitrary Boolean function. As such these problems seem too independent to provide any reduction between them. \subsection{Examples} \begin{example} \label{ex1-SYN} Consider the output function $O_d$ defined in Example~\ref{ex1-OUT}. Let us define $M'_A$ as the module defined on $S'_A = \{a, b, d\}$ and $I_A = \{\alpha\}$, such that $f''_a = x_{\alpha}$, $f''_b = x_a$ and $f_d = \neg x_b$. The module $M'_A$ is a valid answer to the instance $I_A, \{O_d\}, k = 3$ of the Module Synthesis Problem. The interaction digraph of this module is depicted in Figure~\ref{f:ex:MODSYN} (left panel). \end{example} \begin{example} \label{ex2-SYN} Consider the output functions $O_B = \{O_{St}, O_{Sl}, O_{Sk}, O_{Pp}, O_C, O_{C^*}\}$ defined in Example~\ref{ex2-OUT}. Let us define $M'_B$ as the module defined on $S'_B = \{St, Sl, Sk,$ $ Pp, Ru, C25, C^*\}$ and $I_B = \{\alpha_{St}, \alpha_{Sl}, \alpha_{Sk}, \alpha_{Pp}, \alpha_C, \alpha_{C^*}\}$, such that $f''_{St}(x) = \neg x_{\alpha_{St}}$, $f''_{Sl}(x) = \neg x_{\alpha_{Sl}} \vee x_{\alpha_{C^*}}$, $f''_{Sk}(x) = x_{\alpha_{St}} \vee \neg x_{\alpha_{Sk}}$, $f''_{Pp}(x) = x_{\alpha_{Sl}} \vee \neg x_{\alpha_{Pp}}$, $f''_{Ru}(x) = \neg x_{\alpha_{Sk}} \vee x_{\alpha_{Pp}} \vee \neg x_{\alpha_C} \vee \neg x_{\alpha_{C^*}}$, $f''_C(x) = \neg x_{Ru} \vee \neg x_{\alpha_{Sl}}$, $f''_{C25}(x) = \neg x_{\alpha_{Pp}} \vee x_{\alpha_C}$, and $f'_{C^*}(x) = x_{C25}$. The module $M'_B$ is a valid answer to the instance $I_B, O_B, k = 8$ of the Module Synthesis Problem. The interaction digraph of this module is depicted in Figure~\ref{f:ex:MODSYN} (right panel). \end{example} \input{figures/exampleMODSYN} \section{Final wiring and analysis} \label{s:PartD} The final step in the pipeline is simply to wire the module obtained in Section~\ref{s:PartC} so that the obtained networks hold isomorphic attractors to the input network. This is ensured by application of the following result.. \begin{theorem}[\cite{C-Perrot2020}] \label{th-limit-from-output} Let $M$ and $M'$ be two acyclic modules, with $T$ and $T'$ subsets of their nodes such that $|T| = |T'|$. If there exists $g$ a bijection from $I$ to $I'$ and $h$ a bijection from $T$ to $T'$ such that for every $s \in T$, $O_s$ and $O'_{h(s)}$ have same delay, and for every input sequence $j$ with length the delay of $O_s$, \[O_s(j) = O'_{h(s)}(j \circ g^{-1})\] then for any function $\omega : I \to T$, the networks $\circlearrowright_{\omega} M$ and $\circlearrowright_{h \circ \omega \circ g^{-1}} M'$ have isomorphic attractors (up to the renaming of automata given by $h$). \end{theorem} Applying this theorem to the current problem is simple: the module $M$ is the module obtained in Section~\ref{s:PartA}, and the module $M'$ is the module obtained in Section~\ref{s:PartC}. The set $T$ is the set of nodes which are substituted by new inputs in the process described in Section~\ref{s:PartA}. The set $T'$ is the set of nodes in $M'$ which are considered as the output of the module, for example when the module $M'$ is obtained as the result of the application of the functional problem defined in Section~\ref{s:PartC}. As modules $M$ and $M'$ are defined over the same set of inputs, the bijection $g$ is the identity. The bijection $h$ is directly constructed so that for all $s \in T$, $h(s)$ in $M'$ has an equivalent output function as $s$ in $M$, which is always possible thanks to the careful structure of our pipeline. It follows quite clearly that for any $s \in T$, and for any input sequence $j$, $O_s(j) = O'_{h(s)}(j \circ g^{-1})$ holds, and the theorem applies. \begin{example} \label{ex1-FIN} Consider $M'_A$ of Example~\ref{ex1-SYN}. Let $\omega_A(\alpha) = d$. The AN $\circlearrowright_{\omega_A} M'_A$ is defined over $S'_A = \{a, b, d\}$ such that $f'''_a(x) = x_d$, $f'''_b(x) = x_a$, $f'''_d(x) = \neg x_b$. The interaction digraph of this module is depicted in Figure~\ref{f:ex:FIN} (left panel). \end{example} \begin{example} \label{ex2-FIN} Consider $M'_B$ of Example~\ref{ex2-SYN}. Let $\omega_B(\alpha_s) = s$, for all $s \in X_B$. The AN $\circlearrowright_{\omega_B} M'_B$ is defined over $S'_B = \{St, Sl, Sk, Pp, Ru, C25, C^*\}$ such that $f'''_{St}(x) = \neg x_{St}$, $f'''_{Sl}(x) = \neg x_{Sl} \vee x_{C^*}$, $f'''_{Sk}(x) = x_{St} \vee \neg x_{Sk}$, $f'''_{Pp}(x) = x_{Sl} \vee \neg x_{Pp}$, $f'''_{Ru}(x) = \neg x_{Sk} \vee x_{Pp} \vee \neg x_C \vee \neg x_{C^*}$, $f'''_C(x) = \neg x_{Ru} \vee \neg x_{Sl}$, $f'''_{C25}(x) = \neg x_{Pp} \vee x_C$, and $f'_{C^*}(x) = x_{C25}$. The interaction digraph of this module is depicted in Figure~\ref{f:ex:FIN} (right panel). \end{example} This allows us to compute the attractors of any BAN by computing the dynamics of another BAN with possibly less nodes, thus dividing the number of computed configurations by some power of two. Examples throughout this paper showcase the application of the pipeline over two initial examples. Examples~\ref{ex1-BAN-def}, \ref{ex1-AM}, \ref{ex1-OUT}, \ref{ex1-SYN} and \ref{ex1-FIN} show the optimisation of a simple four nodes network into a three nodes equivalent network. The optimisation proceeds here by \lq compacting\rq\ two trivially equivalent nodes, $b$ and $c$, into one. The resulting BAN has dynamics $2^1$ times smaller than the initial network, with isomorphic attractors. Examples~\ref{ex2-BAN-def}, \ref{ex2-AM}, \ref{ex2-OUT}, \ref{ex2-SYN} and \ref{ex1-FIN} show the optimisation of a larger, more intricate network which is drawn from a model predicting the cell cycle sequence of fission yeast~\cite{J-Davidich2008}. This practical example, processed through our pipeline, reduces from $10$ nodes to $8$. This implies a reduction in dynamics size of $2^2$, while keeping isomorphic attractors. Both sets of examples are illustrated throughout the paper in Figures~\ref{f:ex:BAN}, \ref{f:ex:MOD}, \ref{f:ex:MODSYN} and \ref{f:ex:FIN}. \input{figures/exampleFIN} \section{Conclusion} The present paper showcases an innovative way of reducing the cost of computing the attractors of Boolean automata networks. The method provides better optimisation on networks showing structural redundancies, which are removed by the pipeline. The limitations of this method are still significant; it requires solving a problem that is at least $\text{coNP}$-hard, and believed to be $\text{FNP}^\text{coNP}$-complete. As it presently stands, this method is not as much a convincing practical tool as it is a good argument in favor of the powerfulness of acyclic modules, their output functions, and the approaches they allow together towards the computation of BAN dynamics. Future perspectives include finding better complexity bounds to the Module Synthesis Problem, and generalising the formalism of output functions and the optimisation pipeline to different update schedules distinct from parallel. \bibliographystyle{plain} {\small{
{'timestamp': '2020-07-21T02:34:29', 'yymm': '2005', 'arxiv_id': '2005.14531', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14531'}
arxiv
\section{Introduction}\label{sec:intro} Visual Simultaneous Localisation and Mapping (VSLAM) and the closely related Visual Odometry (VO) are established topics in the robotics community \citep{2012_Kaess_IJRR,2015_Leutenegger_ijrr,2016_Faessler_JFR,2017_ForsterScaramuzza_tro,2017_ForsterDelaert_tro}. They are key components of almost all aerial robotic systems \citep{2018_Delmerico_icra} and are used in a host of other robotic applications \citep{2008_Bonin-Font_JIRS} including autonomous driving and underwater robotics. VSLAM is used to refer to the case of the general SLAM problem where the available measurements are the bearings of landmarks such as provided by image features obtained using a monocular camera. Visual Odometry is a variant of the VSLAM problem where the solution is optimised for local consistency of the localisation of the system and updates landmark states only for currently visible landmarks. While the VO community has focused on embedded systems applications, and places a premium on algorithms with low computational and memory requirements \citep{2018_Delmerico_icra}, the VSLAM community has placed a premium on large scale map building, loop closure and accuracy \citep{2016_Stachniss_Handbook,2016_Cadena_TRO}. As a consequence, many state-of-the-art VO systems use filter based formulations \citep{2007_Mourikis_icra,2015_Bloesch_iros,2017_ForsterScaramuzza_tro,2014_Lynen_iros} in contrast to the full trajectory smoothing and graph based optimization formulation accepted as the community standard for SLAM problems \citep{2016_Cadena_TRO}. Well engineered trajectory smoothing algorithms using short sliding-windows are still highly competitive algorithms for VO \citep{2012_Kaess_IJRR,2015_Leutenegger_ijrr,2017_Qin_arxive,2017_ForsterDelaert_tro}. The non-linear observer community has become interested in the visual SLAM and VO problem in the last few years. Work by Guerrerio \textit{et al.}~ \citep{2013_Guerreiro_TRO} and Louren{\c{c}}o \textit{et al.}~ \citep{2016_LouGueBatOliSil} propose a non-linear observer for the ``robo-centric'' SLAM problem. Recent work by Barrau \textit{et al.}~ \citep{2016_Barrau_arxive,2017_Barrau_tac} introduce a symmetry group $\mathbf{SE}_{n+1}(3)$ for the SLAM problem and use this to derive an Invariant Kalman Filter algorithm that overcomes consistency issues that have plagued the EKF algorithms from the classical SLAM era \citep{2011_Dissanayake_ICIIS,2017_Zhang_ral}. Parallel work by Mahony \textit{et al.}~ \citep{2017_Mahony_cdc} show that this symmetry acts transitively on a principle fibre bundle $\mathcal{M}_n(3)$ which forms a natural geometric state-space for the SLAM problem, overcoming the gauge uncertainty present in the usual pose-map state representation. However, the symmetry induced by the group $\mathbf{SE}_{n+1}(3)$ applies only to the SLAM configuration state and is not compatible with bearing measurements. As a consequence, applying the $\mathbf{SE}_{n+1}(3)$ symmetry to the visual SLAM problem still requires linearisation of the output map. A new symmetry for the VSLAM problem was proposed in \citep{2019_vangoor_cdc_vslam} along with a non-linear observer. However, in this prior work the observer is closely based on \citep{2016_Hamel_cdc} and is derived in local coordinates and then lifted onto the symmetry group. It is of interest to consider the case where the observer is designed explicitly using the symmetry structure. In this paper, we present a highly robust, simple, and computationally cheap non-linear observer for the visual SLAM problem based on the new symmetry of the SLAM configuration space, first presented in \citep{2019_vangoor_cdc_vslam}. The symmetry is associated with the novel $\mathbf{VSLAM}_n(3)$ Lie-group, which acts on the raw pose-map configuration coordinates and is compatible with the SLAM configuration manifold $\mathcal{M}_n(3)$ \citep{2017_Mahony_cdc}. The symmetry group structure introduced allows direct application of previous work by Mahony \textit{et al.}~ \citep{RM_2013_Mahony_nolcos} in development of non-linear observers to yield a novel observer for continuous-time VSLAM. In the design of this observer, it is assumed measurements of the inverse depths of landmarks are available in addition to the bearing measurements. In practice, the inverse depth may be measured by using optical flow, triangulation, or depth cameras. The resulting algorithm is fully non-linear; no linearisation is required of the system or output maps. The approach has the advantage that constant gains can be used in the filter (no Riccati gains need be computed on-line) leading to lower computation and memory requirements. This additionally leads to a reduction in the number of parameters that need to be tuned in comparison with a standard EKF, making the proposed filter simpler to use in practice. The inherent symmetry of the approach ensures high levels of robustness and Theorem \ref{th:observer} proves almost global asymptotic and local exponential stability of the error coordinates. The convergence properties of the filter are demonstrated through a simulation experiment. Additional simulation experiments compare an EKF with our observer. These show that our observer achieves comparable mean RMSE to the EKF and has fewer outliers, and operates with a computational complexity that is only linear in the number of landmarks compared to quadratic complexity for the EKF. \section{Notation}\label{sec:notation} The special orthogonal group is the set of rotation matrices and is denoted $\mathbf{SO}(3)$ with Lie algebra $\mathfrak{so}(3)$. The special Euclidean group is the set of rigid body transformations and is denoted $\mathbf{SE}(3)$ with Lie algebra $\mathfrak{se}(3)$. The group of positive real numbers equipped with multiplication is denoted $\mathbf{MR}$ with Lie algebra $\mathfrak{mr}$. We use the notation $R_P \in \mathbf{SO}(3)$ and $x_P \in \mathbb{R}^3$ to denote the rotation and translation components of a rigid-body transformation $P \in \mathbf{SE}(3)$ and write \begin{equation} P = \begin{pmatrix} R_P & x_P \\ 0 & 1 \end{pmatrix}. \label{eq:matrix_pose_SE3} \end{equation} The pose of a vehicle moving in Euclidean space is written $P \in \mathbf{SE}(3)$. The kinematics of such a pose frame are written as \begin{gather} \dot{P} = PU, \quad \dot{R}_P = R_P \Omega_U^\times, \quad \dot{x}_P = R_P V_U \label{eq:rigid_kinematics_coords} \end{gather} where $\Omega_U=(\Omega_1,\Omega_2,\Omega_3)^\top$ and $V_U$ are the body-fixed rotational and translational velocity vectors, respectively, and \begin{equation} U = (\Omega_U^\times,V_u)^{\wedge} := \begin{pmatrix} \Omega_U^\times & V_U \\ 0 & 0 \end{pmatrix}, \quad \Omega^\times_U= \begin{pmatrix} 0 & -\Omega_3 & \Omega_2 \\ \Omega_3 & 0 & -\Omega_1 \\ -\Omega_2 & \Omega_1 & 0 \end{pmatrix}. \label{eq:wedge} \end{equation} One has that $\Omega^\times_U w = \Omega_U \times w$ for any $w \in \mathbb{R}^3$ where $\times$ refers to the vector (cross) product. For a unit vector $y \in \mathrm{S}^2 \subset \mathbb{R}^3$, the projector is given by \begin{align} \label{eq:projector} \Pi_y := I_3 - yy^\top, \end{align} and has the property $\Pi_y = - y^\times y^\times$. \section{Problem formulation}\label{sec:problem_formulation} The \emph{total space} coordinates for the SLAM problem are defined with respect to an unknown fixed but arbitrary reference $\mbox{$\{0\}$}$. Let $P \in \mathbf{SE}(3)$ represent the body-fixed frame coordinates of the robot with respect to this reference frame. Let \[ p_i \in \mathbb{R}^3, \quad\quad i = 1, \ldots, n, \] be sparse points in the environment expressed with respect to the reference frame $\mbox{$\{0\}$}$. The \emph{total space} of the SLAM problem is the product space \begin{align} \mathcal{T}_n(3) = \mathbf{SE}(3) \times \mathbb{R}^3 \times \cdots \times \mathbb{R}^3 \label{eq:tot_T} \end{align} made up of these raw coordinates $\Xi := (P, p_1, \ldots, p_n)$. The bearing of a point $p_i$ co-located with the robot pose centre $x_P$ is undefined, so the VSLAM problem can only be considered on the \emph{reduced total space} \begin{align} \mr{\mathcal{T}}_n(3) = \left\{ (P, p_i) \in \mathcal{T}_n(3) \; \vline \; (\forall i) \; p_i \neq x_P \right\}. \label{eq:reduced_total_space} \end{align} Moreover, since all the measurements of the VSLAM problem considered are made in the body-fixed frame the solution is only well defined up to an $\mathbf{SE}(3)$ gauge transformation \citep{2001_Kanatani_TIT}. This property can be expressed as an invariance of the problem formulation and leads to the quotient structure of the SLAM manifold proposed in \citep{2017_Mahony_cdc}. To keep the derivation simple and more accessible, in the present paper we will define the group actions and derive the observer on the reduced total space. The measurements considered are spherical coordinates $y_i$ of body-fixed frame observations of points in the environment, which in practice may be obtained from a calibrated monocular camera. Additionally, in this analysis, we assume inverse depth estimates $z_i$ are also available. That is, for a given robot pose $P$ and environment point $p_i$, \begin{subequations}\label{eq:h_output} \begin{align} y_i & := \frac{R_P^\top(p_i-x_P)}{|p_i-x_P|}, \label{eq:h_output_y} \\ z_i & := |p_i - x_P|^{-1}. \label{eq:h_output_z} \end{align} \end{subequations} The combined output space is $\mathcal{N}_n(3) = (S^2 \times \mathbb{R}^+) \times \cdots \times (S^2 \times \mathbb{R}^+)$ and we write $(y, z) = h(\Xi) = (h_1(\Xi),\dots,h_n(\Xi)) = ((y_1, z_1), \dots, (y_n, z_n))$, where appropriate. Let $U \in \mathfrak{se}(3)$ denote the velocity of the robot. Assume that the environment points $p_i$ being observed are static, and thus do not have a velocity. The tangent space of $\mathcal{T}_n(3)$ at a point $\Xi = (P, p_1, \ldots, p_n)$ can be identified with the matrix subspace \[ (PU, u_1,...,u_n), \quad U \in \mathfrak{se}(3), \quad u_1,...,u_n \in \mathbb{R}^3. \] The system kinematics can then be written as \begin{equation} \frac{\td}{\td t} ( P , p_1, \ldots, p_n ) = ( P U, 0, \ldots, 0 ). \label{eq:tot_kinematics} \end{equation} We assume that the robot velocity $U \in \mathfrak{se}(3)$ is measured. We will also measure the optical flow of each landmark \[ \phi_i \in T_{y_i} \mathrm{S}^2 \subset \mathbb{R}^3 \] by numerically differentiating the coordinates of $y_i$ between consecutive measurements. Here, we express $\phi_i \in T_{y_i} \mathrm{S}^2$ using the coordinates obtained by embedding $\mathrm{S}^2 \subset \mathbb{R}^3$. Define a measurement velocity space \begin{align} \mathbb{V} = \mathfrak{se}(3) \times \mathbb{R}^3 \times \cdots \times \mathbb{R}^3 \label{eq:vecV} \end{align} with elements $(U, \phi_1, \ldots, \phi_n)$. \section{Symmetry of the VSLAM problem}\label{sec:symmetry} The symmetry group of the VSLAM for $n$ landmarks in Euclidean 3-space with separate bearing and range measurements problem is the \emph{visual SLAM group} $\mathbf{VSLAM}_n(3)$ first described in \citep{2019_vangoor_cdc_vslam}. However, in this paper the VSLAM group and its actions are presented in a different form to \citep{2019_vangoor_cdc_vslam}. In the following, we will write $(Q_A,a)_1$ instead of the more formal $({\left(Q_A\right)}_1,a_1)$ and sometimes write $(Q_A,a)_i$ to represent the tuple $(Q_A,a)_1,\dots,(Q_A,a)_n$. Similarly, we will sometimes write $(P,p_i)$ instead of $(P,p_1,\dots,p_n)$. The VSLAM group \citep{2019_vangoor_cdc_vslam} may be written \begin{multline*} \mathbf{VSLAM}_n(3) = \{ (A,(Q_A,a)_1, \ldots,(Q_A,a)_n) \;|\; \\ A \in \mathbf{SE}(3),\; {\left(Q_A\right)}_i \in \mathbf{SO}(3),\; a_i\in \mathbf{MR}, \; i = 1, \ldots, n\}. \end{multline*} \begin{lemma} The set $\mathbf{VSLAM}_n(3)$ is a Lie group, defined as $$ \mathbf{VSLAM}_n(3) := \mathbf{SE}(3) \times (\mathbf{SO}(3)\times \mathbf{MR})^n.$$ \end{lemma} The visual SLAM group acts as a symmetry group on the reduced total space $\mr{\mathcal{T}}_n(3)$. \begin{lemma}\label{lem:Upsilon_action} The mapping $\Upsilon : \mathbf{VSLAM}_n(3) \times \mr{\mathcal{T}}_n(3) \rightarrow \mr{\mathcal{T}}_n(3)$ defined by \begin{align} \Upsilon((A,&(Q_A,a)_i),(P,p_i)) \notag \\ &= (PA,(a^{-1}R_{PA}Q_A^\top R_P^\top(p-x_P) +x_{PA})_i), \label{eq:Upsilon} \end{align} is a right group action of $\mathbf{VSLAM}_n(3)$ on $\mr{\mathcal{T}}_n(3)$. \end{lemma} The group action for the robot pose is rigid-body transformation. The group action for environment points is considerably more subtle and can be understood conceptually as a sequence of operations: firstly, the reference frame coordinates of an environment point are written in the body-fixed frame, this point is then rotated by $Q_A^\top$ and then scaled by $a^{-1}$, before these body-fixed frame coordinates are rewritten in the inertial frame using the \emph{new body-fixed frame} reference. \begin{figure}[ht] \begin{centering} \includegraphics[width = 0.8\linewidth]{figures/group_action_updated.eps} \caption{Group action $\Upsilon((A,(Q_A,a)_i),(P,p_1, \ldots, p_n))$. The pose $P \mapsto P A$, that is the tip point of the pose is updated by the correction $A \in \mathbf{SE}(3)$. The body fixed-frame environment points $R_A^\top (p_i - x_P)$ are rotated by $Q_A^\top$ and scaled by $a^{-1}$ in the body-fixed frame before \emph{transforming with the robot pose} to a new point $p_i'$ which is rewritten in the inertial frame. } \label{fig:symmetry_action} \end{centering} \end{figure} A key property of the proposed structure is that there is a compatible group operation on the output $\mathcal{N}_n(3)$ of the system. \begin{lemma}\label{lem:rho} The action $\rho : \mathbf{VSLAM}_n(3) \times \mathcal{N}_n(3) \rightarrow \mathcal{N}_n(3)$ defined by \begin{align}\label{eq:rho} \rho((A,(Q_A,a)_i),(y, z)_i)& := ((Q_A^\top y, az)_i) \end{align} is a transitive right action on $\mathcal{N}_n(3)$. Furthermore, one has \begin{align*} \rho((A,(Q_A,a)_i), h(\Xi)) & = h(\Upsilon((A, (Q_A,a)_i),\Xi)) \end{align*} where $h$ is given by \eqref{eq:h_output}. That is, $h$ is equivariant with respect to the actions $\Upsilon$ and $\rho$. \end{lemma} \subsection{Lift of the SLAM kinematics} A key aspect of the proposed approach is that the symmetry group $\mathbf{VSLAM}_n(3)$ and the reduced total space $\mr{\mathcal{T}}_n(3)$ are quite different spaces. The difference is particularly clear in studying the structure of the lifted kinematics on the $\mathbf{VSLAM}_n(3)$ group. The Lie-algebra of $\mathbf{VSLAM}_n(3)$ is \begin{equation*} \mathfrak{vslam}_n(3) = \mathfrak{se}(3) \times (\mathfrak{so}(3) \times \mathfrak{mr}) \times \dots \times (\mathfrak{so}(3) \times \mathfrak{mr}). \end{equation*} We write $(U,(W,w)_i) \in \mathfrak{vslam}_n(3)$ with $U \in \mathfrak{se}(3)$, $W_i \in \mathfrak{so}(3)$ and $w_i \in \mathfrak{r}$, where \begin{align*} U=\begin{pmatrix} \Omega_U^\times & V_U \\ 0 & 0 \end{pmatrix}. \end{align*} In order to implement an observer on the VSLAM group, it is necessary to lift the velocity measurements $(U,\phi_i) \in \mathbb{V}$ \eqref{eq:vecV} to elements $(U,(W,u)_i) \in \mathfrak{vslam}_n(3)$ such that the resulting group velocity is compatible with the system kinematics. That is, an algebraic map $\lambda : \mr{\mathcal{T}}_n(3) \times \mathbb{V} \rightarrow \mathfrak{vslam}_n(3)$ is required such that \begin{align} \label{eq:lift-condition} \mathrm{d} \Upsilon_{(P,p_i)} \lambda ((P,p_i),(U,\phi_i)) = (PU, 0, \ldots, 0). \end{align} \begin{proposition} The map $\lambda :\mr{\mathcal{T}}_n(3) \times \mathbb{V} \rightarrow \mathfrak{vslam}_n(3)$ defined by \begin{align} \label{eq:lambda} \lambda((P,p_i),(U,\dot{y}_i)) := \left(U ,\left((\phi \times y)^\times, z y^\top V_U\right)_i \right), \end{align} where $(y,z)_i = h((P,p_i))$ satisfies the lift condition \eqref{eq:lift-condition}. \end{proposition} \begin{proof} Under the static landmark assumption $p_i = 0$, the optic flow $\phi_i = \dot{y_i}$ is given by \begin{align} \label{eq:optical-flow} \phi_i &= -\Omega_U^\times y_i - z_i (I-y_i y_i^\top) V_U. \end{align} Let $(\lambda_A, (\lambda_Q^\times, \lambda_a)_i) := \lambda((P,p_i),(U,\phi_i))$. Evaluating the left-hand side of \eqref{eq:lift-condition}, one has \begin{align*} \mathrm{d} &\Upsilon_{(P,p_i)} \lambda ((P,p_i),(U,\phi_i)) \\ &= \mathrm{D} \Upsilon_{(P,p_i)}(\id) [ (\lambda_A, (\lambda_Q^\times, \lambda_a)_i) ], \\ &= (P\lambda_A, (- \lambda_a (p-x_P) + R_P \Omega_{\lambda_A}^\times R_P^\top (p - x_P) \\ &\hspace{2cm} - R_P \lambda_Q^\times R_P^\top (p - x_P) + R_P V_U )_i). \end{align*} This expression may be written in terms of $(y,z)_i$ as follows. \begin{align*} \mathrm{d} &\Upsilon_{(P,p_i)} \lambda ((P,p_i),(U,\phi_i)) \\ &= (P\lambda_P, (- \lambda_a R_P z^{-1} y + R_P (\Omega_{\lambda_A}^\times - \lambda_Q^\times) z^{-1} y + R_P V_U )_i). \end{align*} Multiply the landmark velocity terms by $R_P^\top$ and substitute in the values for $\lambda$ to obtain \begin{align*} - \lambda_a & z^{-1} y + (\Omega_{\lambda_A}^\times - \lambda_Q^\times) z^{-1} y + V_U \\ &= -yy^\top V + z^{-1} (\Omega_U - (\phi \times y)^\times) y + V_U, \\ &= z^{-1} \Omega_U^\times y - z^{-1} y^\times y^\times \phi + (I-yy^\top) V , \\ &= z^{-1} \Omega_U^\times y - z^{-1} (\Omega_U^\times y_i + z_i (I-y_i y_i^\top) V_U) + (I-yy^\top) V , \\ &= 0. \end{align*} Hence $\mathrm{d} \Upsilon_{(P,p_i)} \lambda ((P,p_i),(U,\phi_i)) = (P\lambda_A, R_P 0) = (PU, 0)$ as required. \end{proof} The lifted velocity $(U,(W,u)_i) = \lambda((P,p_i), (U, \phi_i))$ induces kinematics on the symmetry group that project down to the state space trajectory. Since the group action is not free, the stabiliser of $\Upsilon$ is non-trivial, and there are directions in $\mathfrak{vslam}_n(3)$, in particular $y_i^\times \in \mathfrak{so}(3)$, that are not constrained by the lift requirement \eqref{eq:lift-condition}. The lift in direction $y_i^\times \in \mathfrak{so}(3)$ is chosen to be zero without loss of generality. The lift $\lambda$ will enable us to go on and apply the observer design methodology developed in \citep{RM_2013_Mahony_nolcos}. \section{Observer design}\label{sec:observer} We approach the observer design by considering the lifted kinematics of the system on the symmetry group and designing the observer on $\mathbf{VSLAM}_n(3)$. Let $\Xi(t) = (P(t),p_i(t)) \in \mathcal{T}_n(3) $ be the `true' configuration of the SLAM problem, noting that $\Xi(t)$ is defined relative to some arbitrary reference $\mbox{$\{0\}$}$. Let $X(t) = (A(t),(Q(t) ,a(t))_i) \in \mathbf{VSLAM}_n(3)$ and define the \emph{lifted kinematics} \citep{RM_2013_Mahony_nolcos} \begin{align} \frac{\td}{\td t} X(t)&= X \lambda(\Upsilon(X, \Xi(0)), (U, \phi_i)) \notag \\ \quad X(0) &= \id. \label{eq:ddtX} \end{align} Equation \eqref{eq:ddtX} evolves on the VSLAM group where $(U, \phi_i) \in \mathbb{V}$ are the measured velocities and $\lambda$ is the lift function \eqref{eq:lambda}. Choose an arbitrary origin configuration \[ \mr{\Xi}= (\mr{P}, \mr{p}_i) \in \mathcal{T}_n(3). \] If the initial condition $X(0) \in \mathbf{VSLAM}_n(3)$ of the lifted kinematics satisfies $\Upsilon(X(0),\mr{\Xi}) = \Xi(0)$ then \eqref{eq:ddtX} induces a trajectory that satisfies \[ \Xi(t) = \Upsilon( X(t) , \mr{\Xi}) \in \mathcal{T}_n(3) \] for all time \citep{RM_2013_Mahony_nolcos}. Let the observer be defined as \[ \hat{X} = (\hat{A},(\hat{Q},\hat{a})_i) \in \mathbf{VSLAM}_n(3). \] The lifted kinematics \eqref{eq:ddtX} provide the internal model for the observer design. That is, the kinematics of the observer are given by \begin{align} \frac{\td}{\td t} \hat{X}(t)&= \hat{X} \lambda(\Upsilon(X, \mr{\Xi}), (U, \phi_i)) - \Delta \hat{X} \notag, \\ \hat{X}(0) &= \id, \label{eq:ObserXi} \end{align} where $\Delta \in \mathfrak{vslam}_n(3)$ is an innovation term to be assigned. Note that $\lambda(\Upsilon(X, \mr{\Xi}), (U, \phi_i))$ is shown in \eqref{eq:lambda} to depend only on the measured quantities $y_i, z_i, U, \phi_i$, and therefore can be implemented in the observer kinematics \eqref{eq:ObserXi}. The configuration estimate generated by the observer is given by \[ \hat{\Xi} = (\hat{P}, \hat{p}_i) = \Upsilon( \hat{X}, \mr{\Xi}) \in \mr{\mathcal{T}}_n(3) \] given the reference $\mr{\Xi} \in \mathcal{T}_n(3)$. \begin{theorem}\label{th:observer} Consider the kinematics \eqref{eq:ddtX} evolving on $\mathbf{VSLAM}_n(3)$ along with bounded outputs ${\bf y}=\{(y,z)_i\}=h(\Xi(t)) \in \mathcal{N}_n(3)$ given by \eqref{eq:h_output}. Fix an arbitrary origin configuration $\mr{\Xi}= (\mr{P}, \mr{p}_i)$ and define the output error ${\bf e}=\{(e_y,e_z)_i\}$ as \begin{align} {\bf e}=\rho(\hat{X}^{-1},\{(y,z)_i\})=\rho(E^{-1}, \{(\mr{y},\mr{z})_i\}) \in \mathcal{N}_n(3). \label{e} \end{align} where $\{(\mr{y},\mr{z})_i\} = h(\mr{\Xi})$ and $E=\hat{X} X^{-1}$. Consider the observer defined in \eqref{eq:ObserXi} and choose the innovation term $\Delta := (\Delta_A, (\Delta_Q, \Delta_a)^i)$ as follows: \begin{align} \Delta_Q^i & := -k_{Q_i}( e_{y_i} \times \mr{y}_i)^\times \label{eq:Delta_Q}\\ \Delta_a^i & := -k_{a_i} \frac{e_{z_i} - \mr{z}_i }{e_{z_i}} \label{eq:Delta_a} \\ \Delta_A &:= -k_{A} \Ad_{\hat{A}} \left( \begin{matrix} \Omega_\Delta^\times & V_\Delta \\ 0 & 0 \end{matrix} \right), \label{eq:Delta_A} \\ \begin{pmatrix} \Omega_{\Delta} \\ V_\Delta \end{pmatrix} &:= \left( \sum_{i=1}^n \begin{pmatrix} \Pi_{\hat{y}_i} & \hat{z}_i \hat{y}_i^\times \\ -\hat{z}_i \hat{y}_i^\times & \hat{z}_i^2 \Pi_{\hat{y}_i} \end{pmatrix} \right)^{-1} \left( \sum_{i=1}^n \begin{pmatrix} -\hat{y}_i^\times \phi_i \\ -\hat{z}_i \phi_i \end{pmatrix} \right) - \begin{pmatrix} \Omega_U \\ V_U \end{pmatrix}, \notag \end{align} where the gains $k_{a_i}, k_{Q_i}$ and $k_{A}$ are positive scalars (for $i = 1, \ldots, n$), and the matrix inverse in the definition of $\Delta_{A}$ is assumed to be well-defined Then the configuration estimate $\hat{\Xi}(t) = \Upsilon(\hat{X}(t),\mr{\Xi})$ converges almost globally asymptotically and locally exponentially to the true state $\Xi(t)=\Upsilon(X(t),\mr{\Xi})$ up to a possibly time-varying element in $\mathbf{SE}(3)$. \end{theorem} \begin{proof} Let $X(t) \in \mathbf{VSLAM}_n(3)$ satisfy the lifted kinematics \eqref{eq:ddtX} with $\Upsilon(X(0),\mr{\Xi}) = \Xi(0)$. It follows that $\Xi(t)=\Upsilon(X(t),\mr{\Xi})$ \citep{RM_2013_Mahony_nolcos}. Define \begin{equation} E=\hat{X} X^{-1} =: (\tilde{A}, (\tilde{Q},\tilde{a})_i) \in \mathbf{VSLAM}_n(3), \label{eq:E} \end{equation} with $\tilde{A}:=\hat{A}A^{-1}$, $(\tilde{Q},\tilde{a})_i=\left( \hat{Q} Q^\top , \hat{a} a^{-1} \right)_i$. Using \eqref{eq:ddtX} and \eqref{eq:ObserXi}, it is straightforward to verify that \begin{equation} \dot E = (-\Delta_A \tilde{A}, (-\Delta_Q \tilde{Q}, -\Delta_a \tilde{a})_i). \label{dotE} \end{equation} Using the fact that $E^{-1} = (\tilde{A}^{-1},(\tilde{Q}^\top, \tilde{a}^{-1})_i)$ then each element of equation \eqref{e} becomes \begin{align} (e_{y_i}, e_{z_i})&=\left (\tilde{Q} \mr{y}_i,\tilde{a}^{-1} \mr{z}_i \right)\label{eq:e}. \end{align} Based on \eqref{dotE}, the error kinematics satisfy \begin{align} \label{eq:error_kinematics} (\dot{e}_{y_i}, \dot{e}_{z_i})&= \left (-\Delta_Q^i e_{y_i}, \Delta_a^i e_{z_i}\right ). \end{align} We first prove almost-global asymptotic and local exponential stability of the equilibrium $(e_{y_i}, e_{z_i})=(\mr{y}_i, \mr{z}_i)$ for the error kinematics \eqref{eq:error_kinematics}. Consider the following candidate (positive definite) Lyapunov function $\Lyap: \mathcal{N}_n(3) \to \mathbb{R}^+$, \begin{equation} {\cal L}=\frac{1}{2}\sum_{i=1}^{n} \left (\left|e_{y_i}-\mr{y}_i \right|^2+\left (e_{z_i}-\mr{z}_i\right)^2 \right). \label{eq:lyap} \end{equation} Differentiating ${\cal L}$ and using \eqref{eq:Delta_Q} and \eqref{eq:Delta_a}, one gets: \begin{align*} \dot{\cal L} &=\sum_{i=1}^{n} \left (\left (e_{y_i}-\mr{y}_i \right )^\top \dot{e}_{y_i}+\left (e_{z_i}-\mr{z}_i\right)\dot{e}_{z_i} \right ) , \\ &= \sum_{i=1}^{n} \left( - \left( e_{y_i}-\mr{y}_i \right)^\top \Delta_Q^i e_{y_i} + \left( e_{z_i}-\mr{z}_i \right) \Delta_a^i e_{z_i} \right ) , \\ &=-\sum_{i=1}^{n} \left ( k_{y_i} \left | e_{y_i} \times \mr{y}_i \right |^2 + k_{z_i} \left (e_{z_i}-\mr{z}_i\right)^2 \right ). \end{align*} The time derivative of the Lyapunov function is negative definite and equal to zero when $e_{y_i}=\pm\mr{y}_i$ and $e_{z_i}=\mr{z}_i$. Direct application of Lyapunov's theorem ensures that the equilibrium $(e_{y_i},e_{z_i})=(\mr{y}_i, \mr{z}_i)$ is almost-globally \emph{asymptotically} stable\footnote{It is straightforward to verify that the equilibrium point $e_{y_i}=-\mr{y}_i$ is unstable.}. To prove local exponential stability of the observer it suffices to split the Lyapunov function into two parts \[ {\cal L}= {\cal L}_y +{\cal L}_z \] ${\cal L}_z =\frac{1}{2}\sum_{i=1}^{n} \left (e_{z_i}-\mr{z}_i\right)^2$ and verify that $\dot{\cal L}_z \leq -2 \min(k_{z_i}) {\cal L}_z$, with ${\cal L}_z$ converging exponentially to zero. Consider ${\cal L}_y=\sum_{i=1}^{n} {\cal L}_{y_i}$ with ${\cal L}_{y_i}=\frac{1}{2} \left|e_{y_i}-\mr{y}_i \right|^2$. If there exists a positive number $\epsilon$ such that ${\cal L}_{y_i} \leq 2 - \epsilon$, that is $e_{y_i}(0)$ is not in the opposite direction of $\mr{y}(0)$, for all $i=\{1,\ldots,n\}$, then \[ \dot{\cal L}_{y_i} \leq -2 \min(k_{y_i}) \epsilon {\cal L}_{y_i} \] This demonstrates local exponential stability (in a large domain) of the equilibrium $(e_{y_i},e_{z_i})=(\mr{y}_i, \mr{z}_i)$ In the limit, at the stable equilibrium point $(e_{y_i},e_{z_i})=(\mr{y}_i, \mr{z}_i)$), \eqref{eq:e} implies that \begin{align*} (\hat{y},\hat{z})_i = \left(Q_{\hat{A}}^\top \mr{y},\hat{a} \mr{z} \right)_i = \left(Q_{\hat{A}}^\top e_{y},\hat{a} e_{z} \right)_i = (y, z)_i, \end{align*} for all $i=1,\ldots,n$. This in turn implies \begin{align*} \rho(\hat{X}, (\mr{y},\mr{z})_i) & = h(\Upsilon(\hat{X}, \mr{\Xi})) = h ( \Upsilon(X, \mr{\Xi})) \\ & = \rho(X, (\mr{y}, \mr{z})_i) \end{align*} Regarding just the central equality, and noting that $h$ only preserves the relative pose on $\mr{\mathcal{T}}_n(3)$, it follows that \[ \Xi = \Upsilon(X, \mr{\Xi}) = \Upsilon(\hat{X}, \mr{\Xi}) \cong \hat{\Xi} \] The symbol $\cong$ indicates that $\Xi = \hat{\Xi}$ up to the possibly time-varying gauge transformation $\tilde{A}$. That is $$(\hat{P},\hat{p}_i) = (\tilde{A}^{-1} P, \tilde{A}^{-1} (p_i)) = (\tilde{A}^{-1} P, R_{\tilde{A}}^\top(p_i - x_{\tilde{A}})).$$ This concludes the proof of the almost-global asymptotic and local exponential stability. \end{proof} \begin{remark} Observe that the output error ${\bf e}$ is independent of the $\mathbf{SE}(3)$ innovation $\Delta_A$ and the primary stability analysis in Theorem \ref{th:observer} is undertaken on the output space, not the state-space. This is a key property of the $\mathbf{VSLAM}_n(3)$ symmetry and is intrinsic to the invariance of the underlying SLAM problem discussed in Section \S \ref{sec:problem_formulation}. The particular choice of innovation $\Delta_A$ in \eqref{eq:Delta_A} minimizes the least squares drift in the visual odometry error as observed from direct measurements of landmark coordinates and optical flow. This is only one of a family of possible choices (for example, \cite{2017_Mahony_cdc}), however, further analysis of this question is beyond the scope of the present paper. \end{remark} \section{Simulation Results} The first simulation experiment was conducted to verify the observer design in Theorem \ref{th:observer}. A robot is simulated to move in a circle with velocity $V_U = (0.1,0,0)$ m/s, $\Omega_U = (0,0,0.02\pi)$ rad/s on the ground, with 10 landmarks uniformly distributed in a 0.5-1 m band around the robot's path. The reference configuration $\mr{\xi}$ of the observer is randomly set, and the observer $\hat{X}$ is initialised to the identity group element. All landmarks are assumed to be measured at all times, and no noise is added to the system. The gains of the observer are set to $k_{Q_i} = 0.05$, $k_{a_i} = 0.02$, $k_{A} = 0.03$ for all $i=1,...,10$. The observer equations are implemented with Euler integration using a time step of 0.5 s. Figure \ref{fig:simple_sim} shows the evolution of the Lyapunov function \eqref{eq:lyap} components for each landmark over 100 s. The bearing storage refers to the component $l_y^i := \frac{1}{2}\vert e_{y_i} - \mr{y}_i \vert^2$ and the inverse depth storage refers to the component $l_z^i := \frac{1}{2}\vert e_{z_i} - \mr{z}_i \vert^2$ for each landmark index $i$. The top two plots show the value of these functions for each landmark, and the bottom two plots show the log value for each landmark. The plots clearly show the almost-global asymptotic and local exponential convergence of the observer's error system. \begin{figure}[!htb] \centering \includegraphics[width=0.85\linewidth]{figures/simple_sim_results.eps} \caption{The evolution of the individual components of the Lyapunov function \eqref{eq:lyap} for 10 landmarks over time.} \label{fig:simple_sim} \end{figure} Additional simulations were carried out to compare the non-linear observer proposed in Theorem \ref{th:observer} with an Extended Kalman Filter (EKF). A robot is simulated to move in a circle with velocity $V_U = (0.1,0,0)$ m/s, $\Omega_U = (0,0,0.02\pi)$ rad/s on the ground, with $n$ landmarks uniformly distributed in a 0.5-1 m band around the robot's path. The robot is modelled to have a sensor range of 1 m. The reference configuration $\mr{\xi}$ is initialised without any landmarks, and the observer group element is initialised to identity. When landmarks are first seen, their inertial frame position is computed using the observer's current position estimate, and the reference configuration is augmented with this value. When landmarks are not within the sensing range, the observer equations cannot be used, and the current observer estimate of the landmark position is fixed until the landmark is next seen. All noise added to the input velocities and output measurements is drawn from zero-mean Gaussian distributions. The linear velocity noise has variance $0.2$, the angular velocity noise has variance $0.1$, the optical flow noise has variance $0.02$, the bearing measurement noise has variance $0.01$, and the inverse depth measurement noise has variance $0.4$. The EKF is implemented with the system equation $\eqref{eq:tot_kinematics}$, and the measurement equations $\eqref{eq:h_output}$. The gains of the observer are set to $k_{Q_i} = 0.25$, $k_{a_i} = 0.1$, $k_{A} = 0.1$ for all $i=1,...,n$, and the observer equations were implemented using Euler integration with a time step of $0.5$ s. \begin{figure}[!htb] \centering \begin{subfigure}[t]{0.45\linewidth} \centering \includegraphics[width=\textwidth]{figures/sim_rmse_comparison.eps} \caption{Boxplot of the RMSE of EKF and our observer on 50 landmarks over 500 trials.} \label{fig:sim_rmse_comparison} \end{subfigure} \hspace{0.05\linewidth} \begin{subfigure}[t]{0.45\linewidth} \centering \includegraphics[width=\textwidth]{figures/sim_time_comparison.eps} \caption{Mean computation time of EKF and our observer on 10-400 landmarks over 500 trials.} \label{fig:sim_time_comparison} \end{subfigure} \caption{Results of the simulation experiments comparing an EKF with the proposed observer.} \end{figure} Figure \ref{fig:sim_rmse_comparison} compares the statistics of the RMSE of the EKF and our observer for $n=50$ landmarks after 100 s over 500 trials. While the EKF has a slightly lower mean RMSE, there are also more outliers due to linearisations errors. Figure \ref{fig:sim_time_comparison} shows the mean computation time of the EKF and our observer for an increasing value of $n$ between 10 and 400 landmarks over 500 trials per number of landmarks. While the processing time depends on the implementation of the EKF and of our observer, the figure clearly illustrates the quadratic complexity of the EKF and the linear complexity of our observer. \section{Conclusion} \label{sec:conclusion} This paper proposes a new symmetry for visual SLAM and VIO problems. This geometry is exploited to develop a visual SLAM observer and provide an almost global asymptotic and local exponential stability proof. The authors believe that the inherent simplicity and robustness of the proposed approach makes it useful as a tool for embedded robotics applications. \section*{Acknowledgement} This research was supported by the Australian Research Council through the ``Australian Centre of Excellence for Robotic Vision'' CE140100016. \bibliographystyle{plainnat}
{'timestamp': '2020-06-01T02:04:49', 'yymm': '2005', 'arxiv_id': '2005.14347', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14347'}
arxiv
\section{Introduction} \IEEEPARstart{O}{ver} the last decade, we have witnessed the evolution of vehicular networking from 'Vehicular Ad-Hoc Networks' (VANETs), enabling spontaneous direct communications between vehicles, to 'Connected Vehicles' generalizing information exchange among vehicles and infrastructure. Vehicular networking has been developed as an enabler of innovative applications intended to improve traffic safety, reduce congestion and even provide infotainment on-board. Early applications were designed to only provide information to drivers, delegating any decision making to them. However, in recent ambitious applications, such as automated driving or platooning, simple information treatment and forwarding mechanisms are not sufficient anymore. Instead, decision-making is based on models of the environment built and improved from increasingly large and diverse sets of input information. Models are designed to learn from experience rather than react to static input signals. In this context, the current standards of vehicular networking, designed for the exchange of static information alone, are no longer optimal. As the individual piece of information becomes meaningless compared with the model that was extracted from it, the scope of vehicular networks is gradually shifting to the creation and exchange of \emph{knowledge} models, as opposed to the sum of their training input. \begin{figure} \centering \includegraphics[width=\columnwidth]{img/data_info_knowledge.pdf} \caption{The Relationship between Data, Information and Knowledge} \label{fig:data_info_knowledge} \end{figure} The existing literature in the information science domain covers conceptual definition of data, information and knowledge \cite{zins2007}. In this paper, for the sake of clarity, we make similar distinctions among these categories. As shown in Figure~\ref{fig:data_info_knowledge}, the most fundamental element is data, that we define as an atomic value with a unit e.g. (5km). Next, information is built by aggregating pieces of data that describe a situation, e.g. (15:00, 30kph) a vehicle's speed at a given time. On top of information lies knowledge, which describes general patterns and relationships obtained through the analysis of sets of information. For example, clustering or classification algorithms can be used to extract hidden relationships within a set. Considering vehicles' pollutant emissions and speed through a day, a piece of extracted knowledge could be an estimate of the extra emissions linked to peak time. Various techniques, such as Artificial Intelligence (AI), Machine Learning (ML) or Formal Language (FL) have been used to extract knowledge in vehicular contexts through the analysis of various sources of information~\cite{yeLiang2018}. For example, Ruta~{\em et al.}~\cite{ruta2018} composed {\em knowledge} to recognize a high level context of driving by using sensor information from multiple cars in a common geographical area. Qi, Wang~{\em et al.}~\cite{qi2019} applied both learning algorithms and edge computing units offloading to provide optimal caching of high level connected driving services to vehicles, including image auto annotation or locally relevant recommendations yielding. Khan~{\em et al.}~\cite{khan2019} applied deep learning to learn the transmission patterns of neighboring vehicles and paved the way for fewer packet collisions. Regardless of the technique, extracting {\em knowledge} from information is a complex and expensive process, and the generated {\em knowledge} may be beneficial to other vehicles. So far each vehicle remains autonomous for its {\em knowledge} building, which requires highly specialized algorithms and a large amount of input information, potentially sourced from multiple different vehicles. This can be seen as a significant overhead considering that {\em knowledge} can be shared and not individually recreated. As a reaction, research has recently been focused on defining a knowledge-centric approach to networking, where information would not be the main focus anymore. Instead, knowledge would be created by nodes in the network, and directly stored and shared among them. Wu~{\em et al.}~\cite{wu2019} described the concept of a knowledge-centric networking framework, separated into the three building blocks of knowledge creation, composition and distribution. A literature survey on means of creating and distributing knowledge is performed. However, the concept of knowledge remains abstract and its implementation or format is left for future work. The structure and understanding of {\em knowledge} needs to be harmonized. Knowledge must move, follow and adapt in symbiosis with information as well as other pieces of knowledge. Finally, existing information networking mechanisms such as Information-Centric Networking (ICN) lack semantic annotations describing such context, which prevails them to uniquely locate and acquire the required knowledge~\cite{yao2019}. The naming, storage and dissemination of {\em knowledge} thus must integrate semantic annotations, which in turn need to be harmonized. In this paper we aim to present Vehicular Knowledge Networking (VKN), a knowledge-centric networking framework applied to vehicular networks. We suggest a common architecture for knowledge description, needed for subsequent storage, composition and exchange with other connected vehicles. VKN is a framework that makes performance improvements in other applications possible. In a conceptual passenger comfort-based rerouting application, we show a potential load and delay reduction in vehicular networks through cooperative knowledge building and sharing. The rest of this article is organized as follows: Section~\ref{sec:infovsknowledge} introduces information treatment standards and defines the scope of \emph{knowledge} in vehicular networks. Based on this understanding, Section~\ref{sec:vkn} describes a structure for knowledge description, storage and distribution. In Section~\ref{sec:application}, an application of the concept shows potential load and delay improvement for the network. Section~\ref{sec:opportunities} finally points out the potential research applicability behind VKN, while Section~\ref{sec:conclusion} summarizes the article. \section{Vehicular Information and Vehicular Knowledge} \label{sec:infovsknowledge} In this section, we first describe the current forms of information in vehicular networks, as well as various standards for information storing and sharing. Then, we build on this understanding to define a format for vehicular knowledge representation. \subsection{Information in Vehicular Networks} Nodes of the vehicular network may exchange diverse types of information, including but not limited to: \begin{itemize} \item Safety notifications, e.g. accidents or road condition. \item Vehicle state information and sensor measurements. \item Navigation information, e.g. maps, road or parking data. \item Information on topics such as weather or traffic flow. \item Road-related information, e.g. gas station opening times. \item Multimedia contents for user infotainment. \end{itemize} Various standards to represent and store information on-board vehicles have been developed in the past years. In ETSI standards, the storage of content in connected vehicles is performed inside the \emph{Local Dynamic Map (LDM)} information base~\cite{ETSIstandard_LDM}, itself divided into four layers: \begin{enumerate} \item Permanent static data, i.e. map data. \item Temporary static data, i.e. roadside infrastructure. \item Temporary dynamic data, e.g. roadblock, signal phase. \item Highly Dynamic data, e.g. vehicles, pedestrians. \end{enumerate} Although the LDM provides a standard approach for storing information, it does not provide any standard for information naming. Generally, any information may be stored in the LDM as long as it is labeled with a space-time area of relevance. This can lead to a lack of interoperability between the contents generated by different providers. To tackle this issue, semantic standards have been developed in order to provide nodes with a "common language" and avoid redundancy. For example, Syzdykbayev {\em et al.}~\cite{syzdykbayev2019} defined an ontology for interactions between the different actors of vehicular networks and the infrastructure. Moreover, the Vehicle Signal Specification (VSS), later extended to the VSSo ontology~\cite{vsso2018}, provides a standard way to address the state of the inner components of vehicles, e.g. steering wheels or windows opening. Finally, after it has been created and stored, information is spread within the vehicular network. In most vehicular applications, nodes care more about the information itself than about the host it originated from. Routing algorithms have thus been developed that focus on the information being shared rather than on its actual host and location in the network. Information-Centric Networking (ICN) is a networking paradigm that may be suitable for some vehicular applications. Rather than sending a request to a specific host, using ICN, a vehicle disseminates a request to fetch a specific information identified by a unique content name. \subsection{Vehicular Knowledge Representation} In next generation vehicular networks, we envision a shift away from the information-based architecture to the benefit of knowledge. As with information, mechanisms must be developed to create, compose, store and distribute knowledge, as introduced in the survey by Wu {\em et al.}~\cite{wu2019}. In order to go further and based on definitions of knowledge, we propose a formal structure for knowledge representation. In turn, it paves the way for the development of knowledge storage and distribution mechanisms. We understand knowledge as a piece of abstract content obtained from the analysis of a larger set of information~\cite{zins2007}. Knowledge can be extracted from information using machine learning algorithms, divided into three classes. Supervised learning is a technique applied to classification or regression. A model is trained based on a number of samples of the form: (information, class) for classification -- or (information, value) for regression. This step, called model training, allows it to grasp knowledge as the relationship between the information and its associated class i.e. the function that takes information as an input and returns its estimated class. Unsupervised learning works with a set of information in which it is able to find clusters of similar items. It creates knowledge from a set of information by exposing relationships among information items and sorting them into different clusters. Reinforcement learning, finally, can be used by an agent to learn the optimal behavior to adopt in a context of interaction with an environment to maximize a user-defined reward. Once trained, a machine learning model acts as a piece of knowledge, able to return synthetic knowledge from input information. The knowledge that is extracted through learning techniques can be further leveraged through knowledge composition methods where existing knowledge is further analyzed/collated to produce new knowledge. For instance, if a user wants to avoid traffic congestion, the system needs to first detect the congested zones and decompose the necessary factors including current location, destination, the estimated route/arrival time based on the current traffic. In this case, in addition to knowledge creation, the knowledge composition also collates some information and/or other knowledge, such as closed roads and/or construction zones, so as not to exacerbate the congestion. Thus, the word \emph{knowledge} can be used to refer to both: (i) the trained model or algorithm able to synthesize sets of information into a piece of knowledge, and (ii) the generated piece of knowledge, that further abstracts the available input information. As a consequence, we believe it is necessary to take both aspects into account as we suggest a formalization of knowledge definition, storage and distribution in vehicular networks. \begin{figure}[H] \centering \includegraphics[width=\columnwidth]{img/arch_format_knowledge.pdf} \caption{The Vehicular Knowledge Ecosystem} \label{fig:archi_vehic_knowledge} \end{figure} Figure~\ref{fig:archi_vehic_knowledge} shows a general picture of when and how knowledge is handled in vehicular networks for safety and driving-related applications. To the left of the figure, information is meant to be stored in the LDM, and has a time and area of validity. For the sake of interoperability with other vehicles, we consider it to be named and structured following well-known constraints, e.g. following the VSS specification. A \emph{knowledge model}, typically implemented as a trained machine learning algorithm, takes as input several pieces of information and produces a certain piece of knowledge as an output. In Figure~\ref{fig:archi_vehic_knowledge}, we distinguish two aspects of a knowledge model: a semantic description and a bytecode. The semantic description is used to describe the necessary input, the produced output and the potential preconditions necessary to the application of the model. We define the \emph{bytecode} of a model as the executable file that produces an output from a well-formed set of input information. By executing the bytecode of a model, one can produce a \emph{knowledge sample} that, just like the information used to produce it, has a time and area of validity. Another pertinent possible output for vehicles is an actuation signal, that may be triggered in reaction to the analysed input information. In practice, the generated \emph{knowledge sample} is structured similarly to information, the difference being that it is abstract and obtained through analysis. As a consequence, it can be fed as input to another knowledge model, generating new composed knowledge. \begin{figure*}[t!] \centering \includegraphics[width=0.75\textwidth]{img/arch_applied_comfort.pdf} \caption{Knowledge Models for Passenger Comfort Estimation.} \label{fig:archi_applied_comfort} \end{figure*} Figure~\ref{fig:archi_applied_comfort} shows an application of this definition of knowledge. It is related to the estimation of passenger comfort on-board a connected vehicle. We will come back to the \texttt{model.env\_comfort} model in Section~\ref{sec:application}, as we describe an application of VKN. \section{Aspects of Vehicular Knowledge Networking} \label{sec:vkn} \subsection{Knowledge Description \& Storage} The creation of knowledge in vehicular networks takes place at two levels: \begin{itemize} \item Using machine learning algorithms, automakers and organizations train and provide models capable of generating a piece of abstract knowledge from a set of input (information or \emph{knowledge samples}). \item The models are applied to real input, generating new \emph{knowledge samples}. \end{itemize} Knowledge models themselves are made of two separable components: (i) A description of the input and output parameters of the model, and (ii) the actual bytecode of the model, a program that will generate output \emph{knowledge samples} given well-formed input. Traditionally in vehicular networks, the two components are not separated. All aspects of the creation of a knowledge model, including training information gathering, model definition and training, are typically planned and organized by a single entity. The obtained model is then downloaded exclusively to the vehicle fleet of the training entity so that \emph{knowledge samples} can be locally generated. In some cases, keeping models proprietary can be an intentional choice by automakers in order to protect their competitiveness in the market. However, in other cases, a lack of cooperation in knowledge model building may lead to an inefficient use of resources. On the one hand, similar knowledge models are likely to be independently trained by competing entities, leading to redundant computations. On the other hand, no common format to describe the input, output, and preconditions of a model are provided by training entities. This prevents the cooperative use of knowledge models by a larger number of nodes. To tackle these issues, the semantic description of a model may be physically separated from its actual execution place, as shown in Figure~\ref{fig:knowledge_separation}. The knowledge model description formally states the input, output and preconditions to the application of a given model. It is a lightweight content to be shared with multiple nodes. The knowledge model's bytecode is the implemented program whose input and output match those of the semantic description. It performs the knowledge samples creation. Even if a vehicle is not in possession of a model's bytecode, it may request knowledge creation from another node using the constraints detailed in the model description. \begin{figure} \centering \includegraphics[width=0.8\columnwidth]{img/kdesc_vs_bytecode.pdf} \caption{Separation of Model Description and Bytecode} \label{fig:knowledge_separation} \end{figure} As a requirement for model description, the inputs and outputs of a model should be named according to standard semantics specifications such as VSS~\cite{vsso2018}. By consulting the specification for the name associated with each input or output, nodes are able to deduce the format of information and \emph{knowledge samples} required to apply the model. Moreover, preconditions to the model application may be set, e.g. conditions on the input information's age. A possible candidate model description language matching these requirements is OWL-S, as described by Martin~\emph{et al.}~\cite{owls}. It was originally developed for automatic Web Services discovery, composition and invocation. The \emph{process model} standard of OWL-S provides a means of description for the set of input, output and preconditions of a model. Figure~\ref{fig:owls_example} provides an example of a OWL-S description of the \texttt{model.env\_comfort} model introduced in the bottom left corner of Figure~\ref{fig:archi_applied_comfort}. \begin{figure} \centering \hspace*{0.05in} \begin{tabular}{c} \begin{lstlisting}[language=Xml] <AtomicProcess ID="model.env_comfort"> <hasInput resource="#traffic" /> <hasInput resource="#visibility" /> <hasInput resource="#twoWheelers" /> </AtomicProcess> <Input ID="traffic"> <parameterType resource="#Road.Traffic" /> </Input> <Input ID="visibility"> <parameterType resource="#Road.Visibility" /> </Input> <Input ID="twoWheelers"> <parameterType resource="#TwoWheelers.Concentration" /> </Input> <Output ID="comfort"> <parameterType resource="#Road.ComfortLevel" /> </Output> \end{lstlisting} \end{tabular} \caption{Comfort Model Description Structure in OWL-S} \label{fig:owls_example} \end{figure} As part of VKN, we suggest separating the storage of models' descriptions and bytecodes. On-board each connected vehicle, as shown in Figure~\ref{fig:knowledge_storage}, we suggest adding a \emph{knowledge} layer on top of the ITS facilities layer containing the LDM: \begin{itemize} \item In a Knowledge Base (KB), a list of known knowledge model descriptions are stored. \item A local storage in the knowledge layer may store knowledge model bytecodes. It is responsible for the actual execution of the knowledge creation process. The stored bytecodes are independent from the model descriptions stored in the KB. \item The generated \emph{knowledge samples} are stored in the LDM along with traditional information. \end{itemize} The KB is responsible for knowledge creation, and knowledge retrieval when the knowledge is remotely created. When creating knowledge, the KB looks up in the LDM for the necessary input items. Then, if the required model bytecode is stored locally, it is executed immediately. The KB also communicates with other nodes' KBs to reach for non locally-stored bytecodes. This allows for a flexible framework, allowing to expand or limit the creation and distribution of knowledge within a certain group of vehicles as needed. The modalities for such remote knowledge creation will be further developed in the knowledge distribution section. \begin{figure} \centering \includegraphics[width=\columnwidth]{img/knowledge_storage.pdf} \caption{On-Board Storage of Knowledge and Information} \label{fig:knowledge_storage} \end{figure} \subsection{Knowledge Distribution} As we separate knowledge models' bytecodes and their description, a structural need appears for the distribution of knowledge. As shown in Figure~\ref{fig:knowledge_layer_networking}, nodes of the vehicular network are inter-connected and knowledge creation may be the product of a cooperation between multiple nodes. \begin{figure} \centering \includegraphics[width=0.9\columnwidth]{img/knowledge_networking_toyota.pdf} \caption{Architecture of Vehicular Knowledge Networking} \label{fig:knowledge_layer_networking} \end{figure} The input information or \emph{knowledge samples} required for knowledge creation through a knowledge model are spread across the vehicular network. As a consequence, centralizing all the input content required for knowledge creation in a single node can be inefficient. VKN makes knowledge models mutually understandable. It brings the opportunity not only to share models themselves, but also to outsource knowledge creation to remote nodes fitted with pertinent input. By cooperatively creating knowledge among well-chosen nodes, the amount of potentially heavyweight model inputs transmitted within the vehicular network can be reduced, saving time and load. In order to achieve knowledge distribution, a \emph{Vehicular Knowledge Querying Language} (VKQL) must be defined to: \begin{enumerate} \item Lookup and retrieve the available knowledge models descriptions, their required input, output and preconditions. \item Spread knowledge model bytecodes efficiently. \item Delegate knowledge creation to remote nodes. \end{enumerate} An example of the delegation of knowledge creation to remote nodes and its potential benefits is developed in Section~\ref{sec:application}, through the example of passenger comfort-based rerouting. Finally, a balance must be found between widespread and too scarce distribution of bytecodes. The former would increase load in the network and negate the point of separating descriptions and bytecodes, while the latter would make access to bytecodes too difficult, increasing delay. Mechanisms to cache knowledge close to the vehicles could make use of technologies such as edge computing units~\cite{mach2017} or vehicular micro-clouds~\cite{VC5}. \section{Application: Passenger Comfort-based rerouting} \label{sec:application} As an application of VKN and to show potential benefits for vehicular networks, we investigate on the use case of \emph{passenger comfort-based rerouting}. The scenario is the following: a Highly-Automated Vehicle (HAV) $V_{ego}$ seeks to provide the most \emph{comfortable} driving itinerary to its passengers. \subsection{Comfort Knowledge Model} Under certain driving situations, as surveyed by Xin~\emph{et al.}~\cite{xin2019}, a HAV's autonomous driving ability can be challenged. In somes cases, it can lead to a take over by a human driver, which can be regarded as a factor of discomfort for passengers. Based on those factors and as an example, we defined a simplified knowledge model \texttt{model.env\_comfort} to determine the level of \emph{passenger comfort} in a given area, as introduced in the bottom left corner of Figure~\ref{fig:archi_applied_comfort}. The model reads a set of area-related input with semantically-defined names: \begin{enumerate} \item The current traffic conditions,\\$tr \in $ \texttt{Road.Traffic} $\equiv$ [\texttt{FLUID}, \texttt{CONGESTED}]. \item The visibility in the area, $v \in $ \texttt{Road.Visibility} $\equiv$ [\texttt{CLEAR}, \texttt{OBSTRUCTED}]. \item The concentration of two-wheelers in the surroundings, $c_{tw} \in $ \texttt{TwoWheelers.Concentration} $\equiv$ [\texttt{HIGH}, \texttt{MEDIUM}, \texttt{LOW}]. \end{enumerate} Based on this input, the model returns a discrete qualification of the level of comfort associated with driving in the area, as $cft \in $ \texttt{Road.ComfortLevel} $\equiv$ [\texttt{GOOD}, \texttt{FAIR}, \texttt{POOR}]. To demonstrate what a simplified version of a knowledge bytecode would be, we provide a simple pseudocode implementation of the model in Algorithm~\ref{algo:the_algo}. \begin{algorithm}[H] \small \caption{Simplified algorithm to compute comfort from environmental parameters} \label{algo:the_algo} \hspace*{\algorithmicindent} \textbf{Input} \\ \hspace*{\algorithmicindent} $c_{tw} \in $ [\texttt{HIGH}, \texttt{MEDIUM}, \texttt{LOW}] \\ \hspace*{\algorithmicindent} $v \in $ [\texttt{CLEAR}, \texttt{OBSTRUCTED}] \\ \hspace*{\algorithmicindent} $tr \in $ [\texttt{FLUID}, \texttt{CONGESTED}] \\ \hspace*{\algorithmicindent} \textbf{Output} \\ \hspace*{\algorithmicindent} $cft \in $ [\texttt{GOOD}, \texttt{FAIR}, \texttt{POOR}] \begin{algorithmic}[1] \IF{$c_{tw}$ = \texttt{LOW} \AND $v =$ \texttt{CLEAR} \AND $tr$ = \texttt{FLUID}} \STATE $cft \leftarrow$ \texttt{GOOD} \ELSIF{$c_{tw}$ = \texttt{HIGH}} \STATE $cft \leftarrow$ \texttt{POOR} \ELSE \STATE $cft \leftarrow$ \texttt{FAIR} \ENDIF \end{algorithmic} \end{algorithm} \subsection{Comfort Retrieval Scenario} The vehicle $V_{ego}$ has three itinerary options to reach its destination: crossing remote area $A$, $B$, or $C$. In order to compute the most comfortable itinerary for its passengers and take a decision on which route to take, $V_{ego}$ wishes to obtain a \texttt{Road.ComfortLevel} knowledge sample for each of these areas. Figure~\ref{fig:glob_scenario} illustrates the problem of the scenario. \begin{figure} \centering \includegraphics[width=\columnwidth]{img/reroutescenario.pdf} \caption{Illustration of the Comfort-based Rerouting Problem.} \label{fig:glob_scenario} \end{figure} Once $V_{ego}$ has obtained the comfort level on each of the areas $A$, $B$, and $C$, it is able to take an educated decision on what itinerary to follow. As an illustration, we describe the process of retrieving the driving comfort level from Area $A$. The problem is as follows: $V_{ego}$ is currently driving $N \geq 5km$ away from Area $A$, and wishes to obtain the driving comfort level in $A$ prior to crossing it, in order to potentially reroute beforehand. In a traditional, information-centric approach lacking standards for knowledge exchange, a typical solution to this problem would be as follows: \begin{enumerate} \setcounter{enumi}{-1} \item The comfort knowledge model is downloaded to $V_{ego}$. \item $V_{ego}$ transmits an information request via ICN to the target area. \item The information acquisition is sensed by a node in the target area and retrieved to $V_{ego}$. \item The remote comfort level is computed on-board $V_{ego}$. \end{enumerate} The input information is typically heavier than the produced knowledge. As a consequence, this approach increases load and delay in vehicular networks compared with a direct transfer of the knowledge. In a novel solution, making use of VKN, we suggest to outsource the production of knowledge to a node in the target area. As shown in Figure~\ref{fig:scenario}, instead of transmitting a request for input information to nodes in the target area, $V_{ego}$ directly transmits a request for the comfort level knowledge in the area. The knowledge creation request is then forwarded to a node in the target area in possession of the required \texttt{model.env\_comfort} model's bytecode. In turn, the remote node locally computes the comfort knowledge using input information stored in its LDM and obtained through sensors. After the knowledge has been produced, it is directly returned to $V_{ego}$. Knowledge is typically much lighter than the input it was extracted from. In turn, this allows to save load and delay in vehicular networks. \begin{figure} \centering \includegraphics[width=\columnwidth]{img/summary_scenario.pdf} \caption{Summary of the Comfort Level Retrieval in a Remote Area using VKN} \label{fig:scenario} \end{figure} \section{Research Applicability} \label{sec:opportunities} We described an application of cooperative \emph{knowledge samples} creation. By remotely running a knowledge model's bytecode in the area where its input information is sourced, unnecessary transfers of information are avoided to the benefit of knowledge. Similarly, mechanisms have been defined in the literature to train \emph{knowledge models} themselves while avoiding the transmission of training information for privacy and efficiency concerns. Federated Machine Learning (FML) is an open research topic in which multiple nodes cooperatively train and update a shared model without exchanging actual training information~\cite{fml2019}. A centralized service provider selects a set of client nodes to cooperatively train a model. A current state of the model to be trained is downloaded to each client. Then, each client locally performs a few training steps of the model with local information before sending the updated model state back to the server. The server then aggregates the updated client model states to compute a global update of the model, taking advantage of the local training of each client. An issue of this approach is that it is not trivial to ensure that all local nodes are interested in training and using the same model. Before being able to start the training, local nodes should be able to determine who among their neighbors is in possession of what type of model and has access to what kind of information. We believe this to be a pertinent use case for VKN, as a protocol of discovery of the knowledge already possessed by one's neighbor is needed to initialize a session of FML. \section{Conclusion} \label{sec:conclusion} Vehicular networks have been extensively studied in the past years. Several standards have been developed to store and share information. However, challenges remain to transition from an information-centric networking model to a model where common standards for knowledge characterization, description, storage and sharing allow nodes in vehicular networks to take full advantage of data-driven AI techniques. In this paper, using a common definition of knowledge, we determined under what forms it exists in vehicular networks, allowing us to concretely propose a structure for knowledge description, storage and sharing. Through a passenger comfort-based rerouting application, we exemplified the concept and showed potential performance improvements. Finally, we note the potential benefits of Vehicular Knowledge Networking for the open topic of Federated Machine Learning. Future work will focus on implementing, simulating and measuring the benefits of using VKN, with regards to traditional information-centric models. \balance \printbibliography \end{document}
{'timestamp': '2020-06-01T02:10:36', 'yymm': '2005', 'arxiv_id': '2005.14505', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14505'}
arxiv
\section{Introduction} In practice, one often encounters heterogeneous data, whose distribution is not constant, but depends on certain covariates. For example, data can be collected from several different sources, its distribution might differ across certain subpopulations or it could even change with time, etc. Inferring valid conclusions about a certain target of interest from such data can be very challenging as many different aspects of the distribution could potentially change. As an example, in medical studies, the effectiveness of a certain treatment might not be constant throughout the population but depend on certain patient characteristics such as age, race, gender, or medical history. Another issue could be that different patient groups were not equally likely to receive the same treatment in the observed data. Obviously, pooling all available data together can result in invalid conclusions. On the other hand, if for a given test point of interest one only considers similar training data points, i.e.\ a small homogeneous subpopulation, one may end up with too few samples for accurate statistical estimation. In this paper, we propose a method based on the Random Forest algorithm \citep{breiman2001random} which in a data-adaptive way determines for any given test point which training data points are relevant for it. This in turn can be used for drawing valid conclusions or for accurately estimating any quantity of interest. Let $\bold{Y}=(Y_1, Y_2, \ldots, Y_d) \in \mathbb{R}^{d}$ be a multivariate random variable representing the data of interest, but whose joint distribution is heterogeneous and depends on some subset of a potentially large number of covariates $\bold{X}=(X_1, X_2, \ldots, X_p) \in \mathbb{R}^{p}$. Throughout the paper, vector quantities are denoted in bold. We aim to estimate a certain target object $\tau(\bold{x})$ that depends on the conditional distribution $\P(\bold{Y} \mid \bold{X} \myeq \bold{x}) = \P(\bold{Y} \mid X_1 \myeq x_1, \ldots, X_p \myeq x_p)$, where $\bold{x} = (x_1, \ldots, x_p)$ is an arbitrary point in $\mathbb{R}^{p}$. The estimation target $\tau(\bold{x})$ can range from simple quantities, such as the conditional expectations $\E[f(\bold{Y}) \mid \bold{X}]$ \citep{breiman2001random} or quantiles $Q_\alpha[f(\bold{Y}) \mid \bold{X}]$ \citep{meinshausen2006quantile} for some function $f:\R^d \to \R$, to some more complicated aspects of the conditional distribution $\P(\bold{Y} \mid \bold{X} \myeq \bold{x})$, such as conditional copulas or conditional independence measures. Given the observed data $\{(\bold{x}_i,\bold{y}_i)\}_{i=1}^n$, the most straightforward way of estimating $\tau(\bold{x})$ nonparametrically would be to consider only the data points in some neighborhood $\mathcal{N}_{\bold{x}}$ around $\bold{x}$, e.g.\ by considering the $k$ nearest neighbors according to some metric. However, such methods typically suffer from the curse of dimensionality even when $p$ is only moderately large: for a reasonably small neighborhood, such that the distribution $\P(\bold{Y}\mid\bold{X}\in \mathcal{N}_\bold{x})$ is close to the distribution $\P(\bold{Y}\mid\bold{X}\myeq\bold{x})$, the number of training data points contained in $\mathcal{N}_{\bold{x}}$ will be very small, thus making the accurate estimation of the target $\tau(\bold{x})$ difficult. The same phenomenon occurs with other methods which locally weight the training observations such as kernel methods \citep{silverman1986density}, local MLE \citep{fan1998local} or weighted regression \citep{cleveland1979robust} even for the relatively simple problem of estimating the conditional mean $\E[\bold{Y}\mid\bold{X}\myeq\bold{x}]$ for fairly small $p$. For that reason, more importance should be given to the training data points $(\bold{x}_i, \bold{y}_i)$ for which the response distribution $\P(\bold{Y}\mid\bold{X}\myeq\bold{x}_i)$ at point $\bold{x}_i$ is similar to the target distribution $\P(\bold{Y}\mid\bold{X}\myeq\bold{x})$, even if $\bold{x}_i$ is not necessarily close to $\bold{x}$ in every component. In this paper, we propose the Distributional Random Forest (DRF) algorithm which estimates the multivariate conditional distribution $\P(\bold{Y}\mid\bold{X}\myeq\bold{x})$ in a locally adaptive fashion. This is done by repeatedly dividing the data points in the spirit of the Random Forest algorithm \citep{breiman2001random}: at each step, we split the data points into two groups based on some feature $X_j$ in such a way that the distribution of $\bold{Y}$ for which $X_j \leq l$, for some level $l$, differs the most compared to the distribution of $\bold{Y}$ when $X_j > l$, according to some distributional metric. One can use any multivariate two-sample test statistic, provided it can detect a wide variety of distributional changes. As the default choice, we propose a criterion based on the Maximal Mean Discrepancy (MMD) statistic \citep{gretton2007kernel} with many interesting properties. This splitting procedure partitions the data such that the distribution of the multivariate response $\bold{Y}$ in the resulting leaf nodes is as homogeneous as possible, thus defining neighborhoods of relevant training data points for every $\bold{x}$. Repeating this many times with randomization induces a weighting function $w_{\bold{x}}(\bold{x}_i)$ as in \citet{lin2002random, lin2006random}, described in detail in Section \ref{method_description}, which quantifies the relevance of each training data point $\bold{x}_i$ for a given test point $\bold{x}$. The conditional distribution is then estimated by an empirical distribution determined by these weights \citep{meinshausen2006quantile}. This construction is data-adaptive as it assigns more weight to the training points $\bold{x}_i$ that are closer to the test point $\bold{x}$ in the components which are more relevant for the distribution of $\bold{Y}$. Our forest construction does not depend on the estimation target $\tau(\bold{x})$, but it rather estimates the conditional distribution $\P(\bold{Y} \mid \bold{\mathbf{X}=\mathbf{x}})$ directly and the induced forest weights can be used to estimate $\tau(\bold{x})$ in a second step. This approach has several advantages. First, only one DRF fit is required to obtain estimates of many different targets, which has a big computational advantage. Furthermore, since those estimates are obtained from the same forest fit, they are mutually compatible. For example, if the conditional correlation matrix $\{\Cor(Y_i,\, Y_j \mid \bold{X}\myeq\bold{x})\}_{i,j=1}^d$ were estimated componentwise, the resulting matrix might not be positive semidefinite, and as another example, the CDF estimates $\hat{\P}(\bold{Y} \leq \bold{y} \mid \bold{X}\myeq\bold{x})$ might not be monotone in $\bold{y}$, see Figure \ref{comparison}. Finally, it can be extremely difficult to tailor forest construction to more complex targets $\tau(\bold{x})$. The induced weighting function can thus be used not only for obtaining simple distributional aspects such as, for example, the conditional quantiles, conditional correlations, or joint conditional probability statements, but also to obtain more complex objectives, such as conditional independence tests \citep{zhang2012kernel}, heterogeneous regression (see also Section \ref{sec: causality} for more details) \citep{kunzel2019metalearners, wager2018estimation} or semiparametric estimation by fitting a parametric model for $\bold{Y}$, having nonparametrically adjusted for $\bold{X}$ \citep{bickel1993efficient}. Representation of the conditional distribution via the weighting function has a great potential for applications in causality such as causal effect estimation or as a way of implementing do-calculus \citep{pearl2009causality} for finite samples, as we discuss in Section \ref{sec: causality}. Therefore, DRF is used in two steps: in the first step, we obtain the weighting function $w_\bold{x}(\cdot)$ describing the conditional distribution $\P(\bold{Y}\mid\bold{X}\myeq\bold{x})$ in a target- and model-free way, which is then used as an input for the second step. Even if the method used in the second step does not directly support weighting of the training data points, one can easily resample the data set with sampling probabilities equal to $\{w_\bold{x}(\bold{x}_i)\}_{i=1}^n$. The two-step approach is visualized in the following diagram: \begin{center} \hspace{2cm} \begin{tikzpicture} \matrix (m) [matrix of math nodes,row sep=2em, column sep=12em,minimum width=2em] { \P(\bold{Y}\mid\bold{X}\myeq\bold{x}) & \hat{\P}(\bold{Y}\mid\bold{X}\myeq\bold{x}) \\ \tau(\P) & \tau(\hat{\P}) \\}; \path[-stealth] (m-1-1) edge node [above] {1) get $w_\bold{x}(\cdot)$ with DRF} (m-1-2) (m-1-1) edge [dashed] node [left] {objective} (m-2-1) (m-1-2) edge node [right]{2) compute from $w_\bold{x}(\cdot)$} (m-2-2) (m-2-2) edge [dashed] node [above] {induced estimator} (m-2-1); \end{tikzpicture} \end{center} \subsection{Related work and our contribution} Several adaptations of the Random Forest algorithm have been proposed for targets beyond the original one of the univariate conditional mean $\E[Y \mid \bold{\mathbf{X}\myeq\mathbf{x}}]$: for survival analysis \citep{hothorn2006survival}, conditional quantiles \citep{meinshausen2006quantile}, density estimation \citep{pospisil2018rfcde}, CDF estimation \citep{hothorn2017transformation} or heterogeneous treatment effects \citep{wager2018estimation}. Almost all such methods use the weights induced by the forest, as described in Section \ref{method_description}, rather than averaging the estimates obtained per tree. This view of Random Forests as a powerful adaptive nearest neighbor method is well known and dates back to \citet{lin2002random, lin2006random}. It was first used for targets beyond the conditional mean in \citet{meinshausen2006quantile}, where the original forest construction with univariate $Y$ was used \citep{breiman2001random}. However, the univariate response setting considered there severely restricts the number of interesting targets $\tau(\bold{x})$ and our DRF can thus be viewed as an important generalization of this approach to the multivariate setting. In order to be able to perform certain tasks or to achieve a better accuracy, many forest-based methods adapt the forest construction by using a custom splitting criterion tailored to their specific target, instead of relying on the standard CART criterion. In \citet{zeileis2008model} and \citet{hothorn2017transformation}, a parametric model for the response $\bold{Y} \mid \bold{\mathbf{X}\myeq\mathbf{x}} \sim f(\theta(\bold{x}), \cdot)$ is assumed and recursive splitting is performed based on a permutation test which uses the user-provided score functions. Similarly, \citet{athey2019generalized} estimate certain univariate targets for which there exist corresponding score functions defining the local estimating equations. The data is split so that the estimates of the target in resulting child nodes differ the most. This is different, though, to the target-free splitting criterion of DRF, which splits so that the distribution of $\bold{Y}$ in child nodes is as different as possible. Since the splitting step is extensively used in the algorithm, its complexity is crucial for the overall computational efficiency of the method, and one often needs to resort to approximating the splitting criterion \citep{pospisil2018rfcde, athey2019generalized} to obtain good computational run time. We propose a splitting criterion based on a fast random approximation of the MMD statistic \citep{gretton2012kernel, zhao2015fastmmd}, which is commonly used in practice for two-sample testing as it is able to detect any change in the multivariate distribution of $\bold{Y}$ with good power \citep{gretton2007kernel}. DRF with the MMD splitting criterion also has interesting theoretical properties as shown in Section \ref{sec: theory} below. The multivariate response case has not received much attention in the Random Forest literature. Most of the existing forest-based methods focus on either a univariate response $Y$ or on a certain univariate target $\tau(\bold{x})$. One interesting line of work considers density estimation \citep{pospisil2018rfcde} and uses aggregation of the CART criteria for different response transformations. Another approach \citep{kocev2007ensembles, segal2011multivariate} is based on aggregating standard univariate CART splitting criteria for $Y_1, \ldots, Y_d$ and targets only the conditional mean of the responses, a task which could also be solved by separate regression fits for each $Y_i$. In order to capture any change in the distribution of the multivariate response $\bold{Y}$, one needs to not only consider the marginal distributions for each component $Y_i$, but also to determine whether their dependence structure changes, see e.g.\ Figure \ref{fig: conditional-independence}. There are not many methods that nonparametrically estimate the joint multivariate conditional distribution $\P(\bold{Y} \mid \bold{X}\myeq\bold{x})$ in the statistics or machine learning literature. Other than a few simple classical methods such as $k$-nearest neighbors and kernel regression, there are methods based on normalizing flows such as Inverse Autoregressive Flow \citep{kingma2016improving} or Masked Autoregressive Flow \citep{papamakarios2017masked} and also conditional variants of several popular generative models such as Conditional Generative Adversarial Networks \citep{mirza2014conditional} or Conditional Variational Autoencoder \citep{sohn2015learning}. The focus of these methods is more on the settings with large $d$ and small $p$, such as image or text generation. The comparison of DRF with the competing methods for distributional estimation can be found in Section \ref{sec: benchmarks}. Our contribution, resulting in the proposal of the Distributional Random Forest (DRF), can be summarized as follows: First, we introduce the idea of forest construction based on sequential multivariate two-sample test statistics. It does not depend on a particular estimation target and is completely nonparametric, which makes its implementation and usage very simple and universal. Not only does it not require additional user input such as the log-likelihoods or score functions, but it can be used even for complicated targets for which there is no obvious forest construction. Furthermore, it has a computational advantage as only a single forest fit is needed for producing estimates of many different targets that are additionally compatible with each other. Second, we propose an MMD-based splitting criterion with good statistical and computational properties, for which we also derive interesting theoretical results in Section \ref{sec: theory}. It underpins our implementation, which we provide as \texttt{R} and \texttt{Python} packages \texttt{drf}. Finally, we show on a broad range of examples in Section \ref{sec: applications} how many different statistical estimation problems, some of which not being easily tractable by existing forest-based methods, can be cast to our framework, thus illustrating the usefulness and versatility of DRF. \section{Method} \label{method_description} In this section we describe the details of the Distributional Random Forest (DRF) algorithm. We closely follow the implementations of the \texttt{grf} \citep{athey2019generalized} and \texttt{ranger} \citep{wright2015ranger} \texttt{R}-packages. A detailed description of the method and its implementation and the corresponding pseudocode can be found in the Appendix \ref{appendix: impdetails}. \subsection{Forest Building} The trees are grown recursively in a model-free and target-free way as follows: For every parent node $P$, we determine how to best split it into two child nodes of the form $C_L = \{X_j \leq l\}$ and $C_R = \{X_j > l\}$, where the variable $X_j$ is one of the randomly chosen splitting candidates and $l$ denotes its level based on which we perform the splitting. The split is chosen such that we maximize a certain (multivariate) two-sample test statistic \begin{equation} \label{eq: splitcrit} \mathcal{D}\left(\{\bold{y}_i\mid \bold{x}_i \in C_L\} \,,\, \{\bold{y}_i \mid \bold{x}_i \in C_R\}\right), \end{equation} which measures the difference of the empirical distributions of the data $\bold{Y}$ in the two resulting child nodes $C_L$ and $C_R$. Therefore, in each step we select the candidate predictor $X_j$ which seems to affect the distribution of $\bold{Y}$ the most, as measured by the metric $\mathcal{D}(\cdot,\cdot)$. Intuitively, in this way we ensure that the distribution of the data points in every leaf of the resulting tree is as homogeneous as possible, which helps mitigate the bias caused by pooling the heterogeneous data together. A related idea can be found in GRF \citep{athey2019generalized}, where one attempts to split the data so that the resulting estimates $\hat{\tau}_L$ and $\hat{\tau}_R$, obtained respectively from data points in $C_L$ and $C_R$, differ the most: \begin{equation}\label{eq: GRF split} \frac{n_Ln_R}{n_P^2} \left(\hat{\tau}_L - \hat{\tau}_R\right)^2, \end{equation} where we write $n_P = |\{i \mid \bold{x}_i \in P\}|$ and $n_L, n_R$ are defined analogously. One could construct the forest using any metric $\mathcal{D}(\cdot,\cdot)$ for empirical distributions. However, in order to have a good accuracy of the overall method, the corresponding two-sample test using $\mathcal{D}(\cdot,\cdot)$ needs to have a good power for detecting any kind of change in distribution, which is a difficult task in general, especially for multivariate data \citep{bai1996effect, szekely2004testing}. Another very important aspect of the choice of distributional metric $\mathcal{D}(\cdot, \cdot)$ is the computational efficiency; one needs to be able to sequentially compute the values of $\mathcal{D}\left(\{\bold{y}_i\mid \bold{x}_i \in C_L\} \,,\, \{\bold{y}_i \mid \bold{x}_i \in C_R\}\right)$ for every possible split very fast for the overall algorithm to be computationally feasible, even for moderately large datasets. Below, we propose a splitting criterion based on the MMD two-sample test statistic \citep{gretton2007kernel} which has both good statistical and computational properties. In contrast to other forest-based methods, we do not use any information about our estimation target $\tau$ in order to find the best split of the data, which comes with a certain trade-off. On one hand, it is sensible that tailoring the splitting criterion to the target should improve the estimation accuracy; for example, some predictors might affect the conditional distribution of $\bold{Y}$, but not necessarily the estimation target $\tau$ and splitting on such predictors unnecessarily reduces the number of training points used for estimating $\tau$. On the other hand, our approach has multiple benefits: it is easier to use as it does not require any user input such as the likelihood or score functions and it can also be used for very complicated targets for which one could not easily adapt the splitting criterion. Furthermore, only one DRF fit is necessary for producing estimates of many different targets, which has both computational advantage and the practical advantage that the resulting estimates are mutually compatible (see e.g.\ Figure \ref{fig: functionals}). Interestingly, sometimes it could even be beneficial to split based on a predictor which does not affect the target of estimation, but which affects the conditional distribution. This is illustrated by the following toy example. Suppose that for a bivariate response $(Y_1, Y_2)$ we are interested in estimating the slope of the linear regression of $Y_2$ on $Y_1$ conditionally on $p=30$ predictors $\bold{X}$, i.e. our target is $\tau(\bold{x}) = \Cov(Y_1, Y_2 \mid \bold{X}\myeq\bold{x})/\Var(Y_1 \mid \bold{X}\myeq\bold{x})$. This is one of the main use cases for GRF and its variant which estimates this target is called Causal Forest \citep{wager2018estimation, athey2019generalized}. Let us assume that the data has the following distribution: \begin{equation} \label{eq: toy_example} \P\left(\begin{bmatrix}Y_1 \\ Y_2\end{bmatrix} \,\,\middle|\,\, \bold{X}\myeq\bold{x}\right) \sim N\left(\begin{bmatrix} x_1 \\ x_1 \end{bmatrix}, \begin{bmatrix}\sigma^2 &0\\ 0 &\sigma^2\end{bmatrix}\right) \qquad \bold{X} \sim N(\bold{0}, I_p), \end{equation} i.e. $X_1$ affects only the mean of the responses, while the other $p-1$ predictors have no effect. In Figure \ref{fig: toy_example} we illustrate the distribution of the data when $n=300, p=30, \sigma=0.2$, together with the DRF and GRF splitting criteria. The true value of the target is $\tau(\bold{x})=0$, but when $\sigma$ is not too big, the slope estimates $\hat{\tau}$ on pooled data will be closer to $1$. Therefore, the difference of $\hat{\tau}_L$ and $\hat{\tau}_R$ between the induced slope estimates for a candidate split, which is used for splitting criterion \eqref{eq: GRF split} of GRF, might not be large enough for us to decide to split on $X_1$, or the resulting split might be too unbalanced. This results in worse forest estimates for this toy example, see Figure \ref{fig: toy_example}. \begin{figure}[h] \hspace*{-0.5cm} \includegraphics[width=1.04\textwidth]{toy_example2.png} \caption{Top left: Illustration of data distribution for the toy example \eqref{eq: toy_example} when $n=300,\, p=30$. Bottom: The corresponding MMD \eqref{eq: MMD splitcrit} (left) and GRF \eqref{eq: GRF split} splitting criteria (right) at the root node. The curves of different colors correspond to different predictors, with $X_1$ denoted in black. Top right: Comparison of the estimates of DRF and Causal Forest \citep{athey2019generalized} which respectively use those splitting criteria. Test points were randomly generated from the same distribution as the training data. Black dashed line indicates the correct value of the target quantity.} \label{fig: toy_example} \end{figure} \subsection{Weighting Function} \label{sec: weighting function} Having constructed our forest, just as the standard Random Forest \citep{breiman2001random} can be viewed as the weighted nearest neighbor method \citep{lin2002random}, we can use the induced weighting function to estimate the conditional distribution at any given test point $\bold{x}$ and thus any other quantity of interest $\tau(\bold{x})$. This approach is commonly used in various forest-based methods for obtaining predictions \citet{hothorn2017transformation, pospisil2018rfcde, athey2019generalized}. Suppose that we have built $N$ trees $\mathcal{T}_1, \ldots, \mathcal{T}_N$. Let $\mathcal{L}_k(\bold{x})$ be the set of the training data points which end up in the same leaf as $\bold{x}$ in the tree $\mathcal{T}_k$. The weighting function $w_{\bold{x}}(\bold{x}_i)$ is defined as the average of the corresponding weighting functions per tree \citep{lin2006random}: \begin{equation} \label{eq: weighting function} w_{\bold{x}}(\bold{x}_i) = \frac{1}{N} \sum_{k=1}^N \frac{\1\left(\bold{x}_i \in \mathcal{L}_k(\bold{x})\right)}{|\mathcal{L}_k(\bold{x})|}. \end{equation} The weights are positive add up to $1$: $\sum_{i=1}^n w_{\bold{x}}(\bold{x}_i) = 1$. In the case of equally sized leaf nodes, the assigned weight to a training point $\bold{x}_i$ is proportional to the number of trees where the test point $\bold{x}$ and $\bold{x}_i$ end up in the same leaf node. This shows that forest-based methods can in general be viewed as adaptive nearest neighbor methods. The sets $\mathcal{L}_k(\bold{x})$ of DRF will contain data points $(\bold{x}_i, \bold{y}_i)$ such that $\P(\bold{Y}\mid \bold{X}=\bold{x}_i)$ is close to $\P(\bold{Y}\mid \bold{\mathbf{X}=\mathbf{x}})$, thus removing bias due to heterogeneity of $\bold{Y}$ caused by $\bold{X}$. On the other hand, since the trees are constructed randomly and are thus fairly independent \citep{breiman2001random}, the leaf sets $\mathcal{L}_k(\bold{x})$ will be different enough so that the induced weights $w_{\bold{x}}(\bold{x}_i)$ are not concentrated on a small set of data points, which would lead to high estimation variance. Such good bias-variance tradeoff properties of forest-based methods are also implied by their asymptotic properties \citep{biau2012analysis, wager2014asymptotic}, even though this is a still active area of research and not much can be shown rigorously. One can estimate the conditional distribution $\P(\bold{Y}\mid\bold{X}=\bold{x})$ from the weighting function by using the corresponding empirical distribution: \begin{equation} \label{eq: distributional estimate} \hat{\P}(\bold{Y} \mid \bold{X}=\bold{x}) = \sum_{i=1}^n w_{\bold{x}}(\bold{x}_i)\cdot\delta_{\bold{y}_i}, \end{equation} where $\delta_{\bold{y}_i}$ is the point mass at $\bold{y}_i$. The weighting function $w_{\bold{x}}(\bold{x}_i)$ can directly be used for any target $\tau(\bold{x})$ in a second step and not just for estimating the conditional distribution. For example, the estimated conditional joint CDF is given by \begin{equation}\label{eq: CDF estimate} \hat{F}_{\bold{Y}\mid\bold{X}\myeq\bold{x}}(\bold{t}) = \hat{\P}(Y_1 \leq t_1, \ldots, Y_d \leq t_d \mid \bold{X}\myeq\bold{x}) = \sum_{i=1}^n w_\bold{x}(\bold{x}_i) \1(\cap_{j=1}^d \{(\bold{y}_i)_j \leq t_j\}). \end{equation} It is important to point out that using the induced weighting function for locally weighted estimation is different than the approach of averaging the noisy estimates obtained per tree \citep{wager2018estimation}, originally used in standard Random Forests \citep{breiman2001random}. Even though the two approaches are equivalent for conditional mean estimation, the former approach is often much more efficient for more complex targets \citep{athey2019generalized}, since the number of data points in a single leaf is very small, leading to large variance of the estimates. For the univariate response, the idea of using the induced weights for estimating targets different than the original target of conditional mean considered in \citet{breiman2001random} dates back to Quantile Regression Forests (QRF) \citep{meinshausen2006quantile}, where a lot of emphasis is put on the quantile estimation, as the number of interesting targets is quite limited in the univariate setting. In the multivariate case, on the other hand, many interesting quantities such as, for example, conditional quantiles, conditional correlations or various conditional probability statements can easily be directly estimated from the weights. By using the weights as an input for some other method, we can accomplish some more complicated objectives, such as conditional independence testing, causal effect estimation, semiparametric learning, time series prediction or tail-index estimation in extreme value analysis. As an example, suppose that our data $\bold{Y}$ come from a certain parametric model, where the parameter $\theta$ is not constant, but depends on $\bold{X}$ instead, i.e. $\bold{Y}\mid\bold{\mathbf{X}=\mathbf{x}} \sim f(\theta(\bold{x}), \cdot)$, see also \citet{zeileis2008model}. One can then estimate the parameter $\theta(\bold{x})$ by using weighted maximum likelihood estimation: $$\hat{\theta}(\bold{x}) = \argmax_{\theta \in \Theta} \sum_{i=1}^n w_\bold{x}(\bold{x}_i) \log f(\theta, \bold{y}_i).$$ Another example is heterogeneous regression, where we are interested in the regression fit of an outcome $Y \in \R$ on certain predicting variables $\bold{W}\in \R^s$ conditionally on some event $\{\bold{X} = \bold{x}\}$. This can be achieved by weighted regression of $Y$ on $\bold{W}$, where the weight $w_\bold{x}(\bold{x}_i)$ assigned to each data point $(\bold{w}_i, y_i)$ is obtained from DRF with the multivariate response $(Y, \bold{W}) \in \R^{s+1}$ and predictors $\bold{X} \in \R^p$, for an illustration see Section \ref{sec: causality}. \begin{figure}[h] \hspace*{-0.4cm} \includegraphics[width=1.03\textwidth]{visualization.png} \caption{Top: the characteristics of the important training sites, for a fixed test site whose position is indicated by a black star and whose characteristics are indicated in the title. The total weight assigned corresponds to the symbol size. Bottom: estimated joint conditional distribution of two pollutants NO$_2$ and PM$2.5$, where the weights correspond to the transparency of the data points. Green area corresponds to 'Good' air quality category ($\text{AQI} \leq 50$).} \label{air_data} \end{figure} The weighting function of DRF is illustrated on the air quality data in Figure \ref{air_data}. Five years ($2015-2019$) of air pollution measurements were obtained from the US Environmental Protection Agency (EPA) website. Six main air pollutants (nitrogen dioxide (NO$_2$), carbon monoxide (CO), sulphur dioxide (SO$_2$), ozone (O$_3$) and coarse and fine particulate matter (PM$10$ and PM$2.5$)) that form the air quality index (AQI) were measured at many different measuring sites in the US for which we know the longitude, latitude, elevation, location setting (rural, urban, suburban) and how the land is used within a $1/4$ mile radius. Suppose we would want to know the distribution of the pollutant measurements at some new, unobserved, measurement site. The top row illustrates for a given test site, whose characteristics are indicated in the plot title, how much weight in total is assigned to the measurements from a specific training site. We see that the important sites share many characteristics with the test site and that DRF determines the relevance of each characteristic in a data-adaptive way. The bottom row shows the corresponding estimates of the joint conditional distribution of the pollutants (we choose $2$ of them for visualization purposes) and one can clearly see how the estimated pollution levels are larger for the suburban site than for the rural site. The induced weights can be used, for example, for estimating the joint density (whose contours can be seen in the plot) or for estimating the probability that the AQI is below a certain value by summing the weights in the corresponding region of space. \subsection{Distributional Metric} In order to determine the best split of a parent node $P$, i.e. such that the distributions of the responses $\bold{Y}$ in the resulting child nodes $C_L$ and $C_R$ differ the most, one needs a good distributional metric $\mathcal{D}(\cdot,\cdot)$ (see Equation \eqref{eq: splitcrit}) which can detect change in distribution of the response $\bold{Y}$ when additionally conditioning on an event $\{X_j > l\}$. Testing equality of distributions from the corresponding samples is an old problem in statistics, called two-sample testing problem. For univariate data, many good tests exist such as Wilcoxon rank test \citep{wilcoxon1946individual}, Welch's t-test \citep{welch1947generalization}, Wasserstein two-sample testing \citep{ramdas2017wasserstein}, Kolmogorov-Smirnov test \citep{massey1951kolmogorov} and many others, but obtaining an efficient test for multivariate distributions has proven to be quite challenging due to the curse of dimensionality \citep{friedman1979multivariate, baringhaus2004new}. Additional requirement for the choice of distributional metric $\mathcal{D}(\cdot,\cdot)$ used for data splitting is that it needs to be computationally very efficient as splitting is used extensively in the algorithm. If we construct $N$ trees from $n$ data points and in each node we consider $\text{mtry}$ candidate variables for splitting, the complexity of the standard Random Forest algorithm \citep{breiman2001random} in the univariate case is $\O(N \times \text{mtry} \times n \log n)$ provided our splits are balanced. It uses the CART splitting criterion, given by: \begin{equation} \label{eq: CART} \frac{1}{n_P}\left(\sum_{\bold{x}_i \in C_L} (y_i - \overline{y}_L)^2 + \sum_{\bold{x}_i \in C_R} (y_i - \overline{y}_R)^2 \right), \end{equation} where $\overline{y}_L = \tfrac{1}{n_L}\sum_{\bold{x}_i \in C_L} y_i$ and $\overline{y}_R$ is defined analogously. This criterion has an advantage that not only it can be computed in $\O(n_P)$ complexity, but this can be done for all possible splits $\{X_j \leq l\}$ as cutoff level $l$ varies, since updating the splitting criterion when moving a single training data point from one child node to the other requires only $\O(1)$ computational steps (most easily seen by rewriting the CART criterion as in \eqref{eq: CART equivalent}). If the time complexity of evaluating the DRF splitting criterion \eqref{eq: splitcrit} for a single splitting candidate $X_j$ and all cutoffs $l$ of interest (usually taken to range over all possible values) is at least $n^c$ for some $c>1$, say $\O(f(n_P))$ for some function $f:\R \to \R$, then by solving the recursive relation we obtain that the overall complexity of the method is given by $\O(N \times \text{mtry} \times f(n))$ \citep{akra1998solution}, which can be unfeasible even for moderately large $n$ if $f$ grows too fast. The problem of sequential two-sample testing is also central to the field of change-point detection \citep{wolfe1984nonparametric, brodsky2013nonparametric}, with the slight difference that in the change-point problems the distribution is assumed to change abruptly at certain points in time, whereas for our forest construction we only are interested in finding the best split of the form $\{X_j \leq l\}$ and the conditional distribution $\P(\bold{Y}\mid \{\bold{X}\in P\} \cap\{X_j \leq l\})$ usually changes gradually with $l$. The testing power and the computational feasibility of the method play a big role in change-point detection as well. However, the state-of-the-art change-point detection algorithms \citep{li2015scan, matteson2014nonparametric} are often too slow for our purpose as sequential testing is done $\O(N \times \text{mtry} \times n)$ times for forest construction, much more frequently than in change-point problems. \subsubsection{MMD splitting criterion} \label{sec: MMD splitcrit} Even though DRF could in theory be constructed with any distributional metric $\mathcal{D}(\cdot, \cdot)$, as a default choice we propose splitting criterion based on the Maximum Mean Discrepancy (MMD) statistic \citep{gretton2007kernel}. Let $(\mathcal{H}, \langle\cdot,\cdot\rangle_\mathcal{H})$ be the RKHS of real-valued functions on $\R^d$ induced by some positive-definite kernel $k$, and let $\varphi:\R^d \to \mathcal{H}$ be the corresponding feature map satisfying that $k(\bold{u}, \bold{v}) = \langle\varphi(\bold{u}), \varphi(\bold{v})\rangle_\mathcal{H}$. The MMD statistic $\mathcal{D}_{\text{MMD}(k)}\left(U, V\right)$ for kernel $k$ and two samples $U = \{\bold{u}_1, \ldots, \bold{u}_{|U|}\}$ and $V = \{\bold{v}_1, \ldots, \bold{v}_{|V|}\}$ is given by: \begin{equation} \label{eq: MMD} \mathcal{D}_{\text{MMD}(k)}\left(U, V\right) = \frac{1}{|U|^2}\sum_{i,j=1}^{|U|} k(\bold{u}_i, \bold{u}_j) + \frac{1}{|V|^2}\sum_{i,j=1}^{|V|} k(\bold{v}_i, \bold{v}_j) - \frac{2}{|U||V|}\sum_{i=1}^{|U|}\sum_{j=1}^{|V|} k(\bold{u}_i, \bold{v}_j). \end{equation} MMD compares the similarities, described by the kernel $k$, within each sample with the similarities across samples and is commonly used in practice for two-sample testing. It is based on the idea that one can assign to each distribution $\mathcal{P}$ its embedding $\mu(\mathcal{P})$ into the RKHS $\mathcal{H}$, which is the unique element of $\mathcal{H}$ given by \begin{equation} \label{eq: RKHS embedding} \mu(\mathcal{P}) = \E_{\bold{Y} \sim \mathcal{P}}[\varphi(\bold{Y})]. \end{equation} The MMD two-sample statistic \eqref{eq: MMD} can then can then equivalently be written as the squared distance between the embeddings of the empirical distributions with respect to the RKHS norm $\norm{\cdot}_\mathcal{H}$: \begin{equation} \label{eq: MMD embedding} \mathcal{D}_{\text{MMD}(k)}\left(U, V\right) = \norm*{\mu\left(\frac{1}{|U|}\sum_{i=1}^{|U|} \delta_{\bold{u}_i}\right) - \mu\left(\frac{1}{|V|}\sum_{i=1}^{|V|} \delta_{\bold{v}_i}\right)}_\mathcal{H}^2, \end{equation} recalling that $\delta_{\bold{y}}$ is the point mass at $\bold{y}$. As the sample sizes $|U|$ and $|V|$ grow, the MMD statistic \eqref{eq: MMD embedding} converges to its population version, which is the squared RKHS distance between the corresponding embeddings of the data-generating distributions of $U$ and $V$. Since the embedding map $\mu$ is injective for characteristic kernel $k$, we see that MMD is able to detect any difference in the distribution. Even though the power of the MMD two sample test also deteriorates as the data dimensionality grows, since the testing problem becomes intrinsically harder \citep{reddi2014decreasing}, it still has good empirical power compared to other multivariate two-sample tests for a wide range of $k$ \citep{gretton2012kernel}. However, the $\O((|U|+|V|)^2)$ complexity for computing $\mathcal{D}_{\text{MMD}(k)}(U, V)$ from \eqref{eq: MMD} is too large for many applications. For that reason, several fast approximations of MMD have been suggested in the literature \citep{gretton2012kernel, zaremba2013b}. As already mentioned, the complexity of the distributional metric $\mathcal{D}(\cdot,\cdot)$ used for DRF is crucial for the overall method to be computationally efficient, since the splitting step is used extensively in the forest construction. We therefore propose splitting based on an MMD statistic computed with an approximate kernel $\tilde{k}$, which is also a fast random approximation of the original MMD \citep{zhao2015fastmmd}. Bochner's theorem (see e.g.\ \citet[Theorem 6.6]{wendland_2004}) gives us that any bounded shift-invariant kernel can be written as \begin{equation} \label{eq: bochner} k(\bold{u}, \bold{v}) = \int_{\R^d} e^{i\boldsymbol{\omega}^T(\bold{u}-\bold{v})}d\nu(\boldsymbol{\omega}), \end{equation} i.e.\ as a Fourier transform of some measure $\nu$. Therefore, by randomly sampling the frequency vectors $\boldsymbol{\omega}_1, \ldots, \boldsymbol{\omega}_B$ from normalized $\nu$, we can approximate our kernel $k$ by another kernel $\tilde{k}$ (up to a scaling factor) as follows: $$k(\bold{u}, \bold{v}) = \int_{\R^d} e^{i\boldsymbol{\omega}^T(\bold{u}-\bold{v})}d\nu(\boldsymbol{\omega}) \approx \frac{1}{B} \sum_{b=1}^B e^{i\boldsymbol{\omega}_b^T(\bold{u}-\bold{v})} = \tilde{k}(\bold{u}, \bold{v}),$$ where we define $\tilde{k}(\bold{u}, \bold{v}) = \langle \bold{\widetilde{\varphi}}(\bold{u}), \bold{\widetilde{\varphi}}(\bold{v})\rangle_{\mathbb{C}^B}$ as the kernel function with the feature map given by $$\bold{\widetilde{\varphi}}(\bold{u}) = \frac{1}{\sqrt{B}}\left(\tilde{\varphi}_{\boldsymbol{\omega}_1}(\bold{u}), \ldots, \tilde{\varphi}_{\boldsymbol{\omega}_B}(\bold{u})\right)^T = \frac{1}{\sqrt{B}}\left(e^{i\boldsymbol{\omega}_1^T\bold{u}}, \ldots, e^{i\boldsymbol{\omega}_B^T\bold{u}}\right)^T,$$ which is a random vector consisting of the Fourier features $\widetilde{\varphi}_{\boldsymbol{\omega}}(\bold{u}) = e^{i\boldsymbol{\omega}^T\bold{u}} \in \mathbb{C}$ \citep{rahimi2008random}. Such kernel approximations are frequently used in practice for computational efficiency \citep{rahimi2009weighted, le2013fastfood}. As a default choice of $k$ we take the Gaussian kernel with bandwidth $\sigma$, since in this case we have a convenient expression for the measure $\nu$ and we sample $\boldsymbol{\omega}_1, \ldots, \boldsymbol{\omega}_B \sim N_{d}(\bold{0}, \sigma^{-2}I_{d})$. The bandwidth $\sigma$ is chosen as the median pairwise distance between all training responses $\{\bold{y}_i\}_{i=1}^n$, commonly referred to as the 'median heuristic' \citep{gretton2012optimal}. From the representation of MMD via the distribution embeddings \eqref{eq: MMD embedding} we can obtain that MMD two-sample test statistic $\mathcal{D}_{\text{MMD}(\tilde{k})}$ using the approximate kernel $\tilde{k}$ is given by \begin{equation*} \mathcal{D}_{\text{MMD}(\tilde{k})}\left(\{\bold{u}_i\}_{i=1}^{|U|}, \{\bold{v}_i\}_{i=1}^{|V|}\right) = \frac{1}{B}\sum_{b=1}^B\left\lvert \frac{1}{|U|}\sum_{i=1}^{|U|} \tilde{\varphi}_{\boldsymbol{\omega}_b}(\bold{u}_i) - \frac{1}{|V|}\sum_{i=1}^{|V|} \tilde{\varphi}_{\boldsymbol{\omega}_b}(\bold{v}_i) \right\rvert^2. \end{equation*} Interestingly, $\mathcal{D}_{\text{MMD}(\tilde{k})}$ is not only an MMD statistic on its own, but can also be viewed as a random approximation of the original MMD statistic $\mathcal{D}_{\text{MMD}(k)}$ \eqref{eq: MMD} using kernel $k$; by using the kernel representation \eqref{eq: bochner}, it can be written (the derivation can be found in the Appendix \ref{appendix: proofs}) as \begin{equation*} \mathcal{D}_{\text{MMD}(k)}\left(\{\bold{u}_i\}_{i=1}^{|U|}, \{\bold{v}_i\}_{i=1}^{|V|}\right) = \int_{\R^d}\left\lvert \frac{1}{|U|}\sum_{i=1}^{|U|} \tilde{\varphi}_{\boldsymbol{\omega}}(\bold{u}_i) - \frac{1}{|V|}\sum_{i=1}^{|V|} \tilde{\varphi}_{\boldsymbol{\omega}}(\bold{v}_i) \right\rvert^2 d\nu(\boldsymbol{\omega}). \end{equation*} Finally, our DRF splitting criterion $\mathcal{D}(\cdot, \cdot)$ \eqref{eq: splitcrit} is then taken to be the (scaled) MMD statistic $\tfrac{n_Ln_R}{n_P^2}\mathcal{D}_{\text{MMD}(\tilde{k})}\left(\{\bold{y}_i\mid \bold{x}_i \in C_L\} \,,\, \{\bold{y}_i \mid \bold{x}_i \in C_R\}\right)$ with the approximate random kernel $\tilde{k}$ used instead of $k$, which can thus be conveniently written as: \begin{align} \label{eq: MMD splitcrit} \frac{1}{B}\sum_{b=1}^B \frac{n_Ln_R}{n_P^2} \left\lvert \frac{1}{n_L}\sum_{\bold{x}_i \in C_L} \tilde{\varphi}_{\boldsymbol{\omega}_b}(\bold{y}_i) - \frac{1}{n_R}\sum_{\bold{x}_i \in C_R} \tilde{\varphi}_{\boldsymbol{\omega}_b}(\bold{y}_i) \right\rvert^2, \end{align} where we recall that $n_P = |\{i \mid \bold{x}_i \in P\}|$ and $n_L, n_R$ are defined analogously. The additional scaling factor $\tfrac{n_Ln_R}{n_P^2}$ in \eqref{eq: MMD splitcrit} occurs naturally and compensates the increased variance of the test statistic for unbalanced splits; it also appears in the GRF \eqref{eq: GRF split} and CART (see representation \eqref{eq: CART equivalent}) splitting criteria. The main advantage of the splitting criterion based on $\mathcal{D}_{\text{MMD}(\tilde{k})}$ is that by using the representation \eqref{eq: splitcrit} it can be easily computed for every possible splitting level $l$ in $\O(Bn_P)$ complexity, whereas the MMD statistic $\mathcal{D}_{\text{MMD}(k)}$ using kernel $k$ would require $\O(n_P^2)$ computational steps, which makes the overall complexity of the algorithm $\O\left(B \times N \times \text{mtry} \times n \log n\right)$ instead of much slower $\O\left(N \times \text{mtry} \times n^2\right)$. We do not use the same approximate random kernel $\tilde{k}$ for different splits; for every parent node $P$ we resample the frequency vectors $\{\omega_b\}_{b=1}^B$ defining the corresponding feature map $\tilde{\varphi}$. Using different $\tilde{k}$ at each node might help to better detect different distributional changes. Furthermore, having different random kernels for each node agrees well with the randomness of the Random Forests and helps making the trees more independent. Since the MMD statistic $\mathcal{D}_{\text{MMD}(\tilde{k})}$ used for our splitting criterion is not only an approximation of $\mathcal{D}_{\text{MMD}(k)}$, but is itself an MMD statistic, it inherits good power for detecting any difference in distribution of $\bold{Y}$ in the child nodes for moderately large data dimensionality $d$, even when $B$ is reasonably small. One could even consider changing the number of random Fourier features $B$ at different levels of the tree, as $n_P$ varies, but for simplicity we take it to be fixed. There is some similarity of our MMD-based splitting criterion \eqref{eq: MMD splitcrit} with the standard variance reduction CART splitting criterion \eqref{eq: CART} when $d=1$, which can be rewritten as: \begin{equation} \label{eq: CART equivalent} \frac{n_Ln_R}{n_P^2}\left(\frac{1}{n_L}\sum_{\bold{x}_i \in C_L} y_i - \frac{1}{n_R}\sum_{\bold{x}_i \in C_R} y_i \right)^2. \end{equation} The derivation can be found in Appendix \ref{appendix: proofs}. From this representation, we see that the CART splitting criterion \eqref{eq: CART} is also equivalent to the GRF splitting criterion \eqref{eq: GRF split} when our target is the univariate conditional mean $\tau(\bold{x}) = \E[Y \mid \bold{X}\myeq\bold{x}]$ which is estimated for $C_L$ and $C_R$ by the sample means $\hat{\tau}_L = \overline{y}_L$ and $\hat{\tau}_R = \overline{y}_R$. Therefore, as it compares the means of the univariate response $Y$ in the child nodes, the CART criterion can only detect changes in the response mean well, which is sufficient for prediction of $Y$ from $\bold{X}$, but might not be suitable for more complex targets. Similarly, for multivariate applications, aggregating the marginal CART criteria \citep{kocev2007ensembles, segal2011multivariate} across different components $Y_i$ of the response can only detect changes in the means of their marginal distributions. However, it is possible in the multivariate case that the pairwise correlations or the variances of the responses change, while the marginal means stay (almost) constant. For an illustration on simulated data, see Figure \ref{fig: gaussian_copula}. Additionally, aggregating the splitting criteria over $d$ components of the response $\bold{Y}$ can reduce the signal size if only the distribution of a few components change. Our MMD-based splitting criterion \eqref{eq: MMD splitcrit} is able to avoid such difficulties as it implicitly inspects all aspects of the multivariate response distribution. If we take a trivial kernel $k_{\text{id}}(y_i, y_j) = y_i y_j$ with the identity feature map $\varphi_{\text{id}}(y) = y$, the corresponding distributional embedding \eqref{eq: RKHS embedding} is given by $\mu(\mathcal{P}) = \E_{Y\sim\mathcal{P}} Y$ and thus the corresponding splitting criterion based on $\mathcal{D}_{\text{MMD}(k_{\text{id}})}$ \eqref{eq: MMD embedding} corresponds exactly to the CART splitting criterion \eqref{eq: CART}, which can be seen from its equivalent representation \eqref{eq: CART equivalent}. Interestingly, Theorem \ref{thm: MMD_CART_equivalence} in Section \ref{sec: theory} below shows that the MMD splitting criterion with kernel $k$ can also be viewed as the abstract CART criterion in the RKHS $\mathcal{H}$ corresponding to $k$ \citep{fan2010cw}. Moreover, it is also shown that DRF with the MMD splitting criterion can thus be viewed asymptotically as a greedy minimization of the squared RKHS distance between the corresponding embeddings of our estimate $\hat{\P}(\bold{Y}\mid\bold{X}\myeq\bold{x})$ and the truth $\P(\bold{Y}\mid\bold{X}\myeq\bold{x})$ averaged over $\bold{x}$, thus justifying the proposed method. In Section \ref{sec: theory}, we exploit this relationship to derive interesting theoretical properties of DRF with the MMD splitting criterion. \section{Theoretical Results} \label{sec: theory} In this section we exploit the properties of kernel mean embedding in order to relate DRF with the MMD splitting criterion to an abstract version of the standard Random Forest with the CART splitting criterion \citep{breiman2001random} when the response is taking values in the corresponding RKHS. We further exploit this relationship to adapt the existing theoretical results from the Random Forest literature to show that our estimate \eqref{eq: distributional estimate} of the conditional distribution of the response is consistent with respect to the MMD metric for probability measures and with a good rate. Finally, we show that this implies consistency of the induced DRF estimates for a range interesting targets $\tau(\bold{x})$, such as conditional CDFs or quantiles. The proofs of all results can be found in the Appendix \ref{appendix: proofs}. Recalling the notation from above, let $\left(\mathcal{H}, \langle\cdot,\cdot\rangle_{\mathcal{H}}\right)$ be the Reproducing kernel Hilbert space induced by the positive definite kernel $k:\R^d\times\R^d \to \R$ and let $\varphi:\R^d \to \mathcal{H}$ be its corresponding feature map. The kernel embedding function $\mu:\mathcal{M}_{b}(\R^d) \to \mathcal{H}$ maps any bounded signed Borel measure $\mathcal{P}$ on $\R^d$ to an element $\mu(\mathcal{P}) \in \mathcal{H}$ defined by $$\mu(\mathcal{P}) = \int_{\R^d}\varphi(\bold{y})d\mathcal{P}(\bold{y}),$$ see \eqref{eq: RKHS embedding}. Boundedness of $k$ ensures that $\mu$ is indeed defined on all of $\mathcal{M}_{b}(\R^d)$, while continuity of $k$ ensures that $\mathcal{H}$ is separable \citet{hilbertspacebook}. By considering the kernel embedding $\mu(\cdot)$ and using its linearity, we can write the embedding of the distributional estimate $\mu(\hat{\P}(\bold{Y}\mid\bold{X}\myeq\bold{x}))$ of DRF \eqref{eq: distributional estimate} as the average of the embeddings of the empirical distributions of $\bold{Y}$ in the leaves containing $\bold{x}$ over all trees: \begin{equation} \label{eq: embedding estimate} \mu(\hat{\P}(\bold{Y}\mid\bold{X}\myeq\bold{x})) = \frac{1}{N}\sum_{k=1}^N \mu\left( \frac{1}{|\mathcal{L}_k(\bold{x})|}\sum_{\bold{x}_i \in \mathcal{L}_k(\bold{x})} \delta_{\bold{y}_i}\right) = \frac{1}{N}\sum_{k=1}^N \frac{1}{|\mathcal{L}_k(\bold{x})|}\sum_{\bold{x}_i \in \mathcal{L}_k(\bold{x})} \mu(\delta_{\bold{y}_i}). \end{equation} This is analogous to the prediction of the response for the standard Random Forest, but where we average the embeddings $\mu(\delta_{\bold{y}_i}) = \varphi(\bold{y}_i)$ instead of the response values themselves. Therefore, by using the kernel embedding, we can shift the perspective to the RKHS $\mathcal{H}$ and view DRF as the analogue of the original Random Forest for estimation of $\mu(\P(\bold{Y}\mid\bold{X}=\bold{x})) = \E[\varphi(\bold{Y})\mid\bold{X}\myeq\bold{x}]$ in some abstract Hilbert space. With this viewpoint, we can relate the MMD splitting criterion to the original CART criterion \eqref{eq: CART}, which measures the mean squared prediction error for splitting a certain parent node $P$ into children $C_L$ and $C_R$. On one hand, from Equation \eqref{eq: CART equivalent} we see that the CART criterion measures the squared distance between the response averages $\tfrac{1}{n_L}\sum_{\bold{x}_i \in C_L} y_i$ and $\tfrac{1}{n_R}\sum_{\bold{x}_i \in C_R} y_i$ in the child nodes, but on the other hand, Equation \eqref{eq: MMD embedding} shows that the MMD splitting criterion measures the RKHS distance between the embeddings of the empirical response distributions in $C_L$ and $C_R$. This is summarized in the following theorem, which not only shows that the MMD splitting criterion can be viewed as the abstract CART criterion in the RKHS $\mathcal{H}$ \citep{fan2010cw}, but also that DRF with the MMD splitting criterion can be viewed as greedy minimization of the average squared distance between the estimated and true conditional distributions, as measured by the RKHS norm between the corresponding embeddings to $\mathcal{H}$: \begin{restatable}{theorem}{MMDCART}\label{thm: MMD_CART_equivalence} For any split of a parent node $P$ into child nodes $C_L$ and $C_R$, let $\hat{\P}_\text{split}(\bold{x}) = \sum_{j\in\{L, R\}}\1(\bold{x}\in C_j) \tfrac{1}{n_j} \sum_{\bold{x}_i \in C_j} \delta_{\boldsymbol{y}_i}$ denote the resulting estimate of the distribution $\P(\bold{Y} \mid \bold{X}\myeq\bold{x})$ when $\bold{x} \in P$. Then the MMD splitting criterion is equivalent to the abstract version of the CART criterion \eqref{eq: CART} on $\mathcal{H}$: \small \begin{equation*} \argmax_{\text{split}} \frac{n_Ln_R}{n_P^2}\mathcal{D}_{\text{MMD}(k)}\left(\{\bold{y}_i \mid \bold{x}_i \in C_L\} , \{\bold{y}_i\mid \bold{x}_i\in C_R\}\right) = \argmin_{\text{split}} \frac{1}{n_P}\sum_{\bold{x}_i \in P} \norm*{\mu(\delta_{\bold{y}_i}) - \mu(\hat{\P}_{\text{split}}(\bold{x}_i))}_\mathcal{H}^2. \end{equation*} \normalsize Moreover, for any node $P$ and any fixed distributional estimator $\hat{\P}(\bold{Y}\mid\bold{X}\myeq\bold{x})$, we have: \small \begin{equation*} \frac{1}{n_P}\sum_{\bold{x}_i \in P} \norm*{\mu(\delta_{\bold{y}_i}) - \mu(\hat{\P}(\bold{Y}\mid\bold{X}\myeq\bold{x}_i))}_\mathcal{H}^2 = V_P + \E\left[\norm{\mu(\hat{\P}(\bold{Y}\mid\bold{X})) - \mu(\P(\bold{Y} \mid \bold{X}))}_\mathcal{H}^2 \mid \bold{X} \in P\right] + \O_{p}(n^{-1/2}), \end{equation*} \normalsize where $V_P = \E\left[\norm{\mu(\delta_\bold{Y}) - \mu(\P(\bold{Y} \mid \bold{X}))}_\mathcal{H}^2\mid \bold{X} \in P\right]$ is a deterministic term not depending on the estimates $\hat{\P}(\bold{Y}\mid\bold{X}\myeq\bold{x})$. \end{restatable} In conclusion, DRF with the MMD splitting criterion can be viewed as the standard Random Forest with the CART splitting criterion, but with the response $\mu(\delta_{\bold{Y}})$ taking values in an abstract RKHS $\mathcal{H}$ instead of $\R$. Therefore, one could in principle derive properties of DRF by adapting any theoretical result for standard Random Forests from the literature. However, a lot of care is needed for making the results rigorous in this abstract setup, as many useful properties of $\R$ need not hold for infinite-dimensional $\mathcal{H}$. The remaining part of this section is inspired by the results from \citet{wager2018estimation}. We suppose that the forest construction satisfies the following properties, which significantly facilitate the theoretical considerations of the method and ensure that our forest estimator is well behaved, as stated in \citet{wager2018estimation}: \begin{itemize} \item[\textbf{(P1)}] (\textit{Data sampling}) The bootstrap sampling with replacement, usually used in forest-based methods, is replaced by a subsampling step, where for each tree we choose a random subset of size $s_n$ out of $n$ training data points. We consider $s_n$ going to infinity with $n$, with the rate specified below. \item[\textbf{(P2)}] (\textit{Honesty}) The data used for constructing each tree is split into two parts; the first is used for determining the splits and the second for populating the leaves and thus for estimating the response. \item[\textbf{(P3)}] (\textit{$\alpha$-regularity}) Each split leaves at least a fraction $\alpha \leq 0.2$ of the available training sample on each side. Moreover, the trees are grown until every leaf contains between $\kappa$ and $2\kappa - 1$ observations, for some fixed tuning parameter $\kappa \in \N$. \item[\textbf{(P4)}] (\textit{Symmetry}) The (randomized) output of a tree does not depend on the ordering of the training samples. \item[\textbf{(P5)}] (\textit{Random-split}) At every split point, the probability that the split occurs along the feature $X_j$ is bounded below by $\pi/p$, for some $\pi > 0$ and for all $j=1,\ldots,p$. \end{itemize} The validity of the above properties are easily ensured by the forest construction. For more details, see Appendix \ref{appendix: impdetails}. From Equation \eqref{eq: embedding estimate}, the prediction of DRF for a given test point $\mathbf{x}$ can be viewed as an element of $\mathcal{H}$. If we denote the $i$-th training observation by $\mathbf{Z}_i=(\mathbf{x}_i, \mu(\delta_{\mathbf{y}_i})) \in \R^p \times \mathcal{H}$, then by \eqref{eq: embedding estimate} we estimate the embedding of the true conditional distribution $\mu(\P(\bold{Y}\mid\bold{X}\myeq\bold{x}))$ by the average of the corresponding estimates per tree: \begin{equation*}\label{rewriting} \mu(\hat{\P}(\mathbf{Y} \mid \mathbf{X} \myeq \mathbf{x})) = \frac{1}{N} \sum_{j=1}^N T(\bold{x}; \varepsilon_j, \mathcal{Z}_j), \end{equation*} where $\mathcal{Z}_k$ is a random subset of $\{\mathbf{Z}_i\}_{i=1}^n$ of size $s_n$ chosen for constructing the $j$-th tree $\mathcal{T}_j$ and $\varepsilon_j$ is a random variable capturing all randomness in growing $\mathcal{T}_j$, such as the choice of the splitting candidates. $T(\bold{x}; \varepsilon, \mathcal{Z})$ denotes the output of a single tree: i.e. the average of the terms $\mu(\delta_{\bold{Y}_i})$ over all data points $\bold{Z}_i$ contained in the leaf $\mathcal{L}(\bold{x})$ of the tree constructed from $\varepsilon$ and $\mathcal{Z}$. Since one can take the number of trees $N$ to be arbitrarily large, we consider an ``idealized'' version of our estimator, as done in \citet{wager2017estimation}, which we denote as $\hat{\mu}_n(\mathbf{x})$: \begin{equation}\label{finalestimator} \hat{\mu}_n(\mathbf{x}) = \binom{n}{s_n}^{-1} \sum_{i_1 < i_2 < \ldots < i_{s_n}} \E_{\varepsilon} \,\,T(\mathbf{x}; \varepsilon; \{\bold{Z}_{i_1}, \ldots, \bold{Z}_{i_{s_n}}\}), \end{equation} where the sum is taken over all $\binom{n}{s_n}$ possible subsets of $\{\mathbf{Z}_{i}\}_{i=1}^n$. We have that $\mu(\hat{\P}(\bold{Y}\mid\bold{X}\myeq\bold{x})) \to \hat{\mu}_n(\mathbf{x})$ as $N\to \infty$, while keeping the other variables constant, and thus we assume for simplicity that those two quantities are the same. Our main result shows that, under similar assumptions as in \citet{wager2017estimation}, the embedding of our conditional distribution estimator $\mu_n(\bold{x}) = \mu(\hat{\P}(\mathbf{Y} \mid \mathbf{X} \myeq \mathbf{x}))$ consistently estimates $\mu(\bold{x}) \coloneqq \mu(\P(\mathbf{Y} \mid \mathbf{X} \myeq \mathbf{x}))$ with respect to the RKHS norm with a certain rate: \begin{restatable}{theorem}{consistency}\label{thm: consistency} Suppose that our forest construction satisfies properties \textbf{(P1)}--\textbf{(P5)}. Assume additionally that $k$ is a bounded and continuous kernel and that we have a random design with $\bold{X}_1,\ldots, \bold{X}_n$ independent and identically distributed on $[0,1]^p$ with a density bounded away from $0$ and infinity. If the subsample size $s_n$ is of order $n^\beta$ for some $0 < \beta < 1$, the mapping $$\mathbf{x} \mapsto \mu(\mathbf{x})=\E[ \mu(\delta_\bold{Y}) \mid \mathbf{X} \myeq \mathbf{x}] \in \mathcal{H},$$ is Lipschitz and $ \sup_{\mathbf{x} \in [0,1]^p} \E[ \|\mu(\delta_\bold{Y})\|_\mathcal{H}^2\mid \mathbf{X} \myeq \mathbf{x}] < \infty$, we obtain the consistency w.r.t. the RKHS norm: \begin{equation}\label{eq: rate} \norm{\hat{\mu}_n(\mathbf{x})- \mu(\mathbf{x})}_\mathcal{H} = o_{p}\left(n^{-\gamma} \right), \end{equation} for any $\gamma < \frac{1}{2} \min\left( 1- \beta, \frac{\log(1-\alpha)}{\log(\alpha)} \frac{\pi}{p} \cdot \beta \right)$. \end{restatable} \begin{remark} The rate in \eqref{eq: rate} is analogous to the one from \citet{wager2018estimation}, who used it further to derive the asymptotic normality of the random forest estimator in $\R$. Indeed, one can show in our case that there exists a sequence of real numbers $\sigma_n \to 0$, such that $(\hat{\mu}_n(\mathbf{x})- \mu(\mathbf{x}))/\sigma_n$ as a random element of $\mathcal{\mathcal{H}}$ is ``asymptotically linear'', in the sense that it is indistinguishable asymptotically from an average of independent random elements in $\mathcal{H}$. Unfortunately, this alone is not enough to establish asymptotic normality of $(\hat{\mu}_n(\mathbf{x})- \mu(\mathbf{x}))/\sigma_n$ as an element of $\mathcal{H}$, a task left for future research. \end{remark} The above result shows that DRF estimate $\hat{\P}(\bold{Y}\mid\bold{X}\myeq\bold{x})$ converges fast to the truth $\P(\bold{Y}\mid\bold{X}\myeq\bold{x})$ in the MMD distance, i.e.\ the RKHS distance between the corresponding embeddings. Even though this is interesting on its own, ultimately we want to relate this result to estimation of certain distributional targets $\tau(\bold{x}) = \tau(\P(\bold{Y}\mid\bold{X}\myeq\bold{x})).$ For any $f \in \mathcal{H}$, we have that the DRF estimate of the target $\tau(\bold{x}) = \E[f(\bold{Y})\mid\bold{X}\myeq\bold{x}]$ equals the dot product $\langle f, \hat{\mu}_n(\mathbf{x}) \rangle_\mathcal{H}$ in the RKHS: \begin{equation*} \langle f , \hat{\mu}_n(\mathbf{x}) \rangle_\mathcal{H} = \left\langle f,\, \int_{\R^d} \varphi(\mathbf{y}) d \hat{\P}(\mathbf{y} \mid \mathbf{X} \myeq \mathbf{x})\right\rangle_\mathcal{H} = \int_{\R^d} f(\mathbf{y}) \, d\hat{\P}(\mathbf{y} \mid \mathbf{X} \myeq \mathbf{x}) = \sum_{i=1}^n w_{\mathbf{x}}(\mathbf{x}_i) f(\mathbf{y}_i), \end{equation*} where we recall the weighting function $w_{\mathbf{x}}(\cdot)$ induced by the forest \eqref{eq: weighting function}. Therefore, the consistency result \eqref{eq: rate} in Theorem \ref{thm: consistency} directly implies that \begin{equation} \label{eq: target consistency} \sum_{i=1}^n w_{\mathbf{x}}(\mathbf{x}_i) f(\mathbf{y}_i) = \langle f, \hat{\mu}_n(\mathbf{x}) \rangle_\mathcal{H} \stackrel{p}{\to} \langle f, \mu(\mathbf{x}) \rangle_\mathcal{H} = \E[f(\bold{Y})\mid\bold{X}\myeq\bold{x}] \quad \text{ for any $f \in \mathcal{H}$}, \end{equation} i.e. that the DRF consistently estimates the targets of the form $\tau(\bold{x}) = \E[f(\bold{Y})\mid\bold{X}\myeq\bold{x}]$, for $f \in \mathcal{H}$. From \eqref{eq: rate} we also obtain the rate of convergence when $s_n \asymp n^\beta$: \begin{equation*} \left|\sum_{i=1}^n w_{\mathbf{x}}(\mathbf{x}_i) f(\mathbf{y}_i) - \E[f(\bold{Y})\mid\bold{X}\myeq\bold{x}]\right| = o_{p}\left( n^{-\gamma} \norm{f}_\mathcal{H}\right), \end{equation*} for $\gamma$ as in Theorem \ref{thm: consistency}. When $k$ is continuous, it is well known that all elements of $\mathcal{H}$ are continuous, see e.g.\ \citet{hilbertspacebook}. Under certain assumptions on the kernel and its input space, holding for several popular kernels, (e.g.\ the Gaussian kernel) \citep{optimalestimationofprobabilitymeasures}, we can generalize the convergence result \eqref{eq: target consistency} to any bounded and continuous function $f:\R^d \to \R$, as the convergence of measures $\hat{\P}(\bold{Y}\mid\bold{X}\myeq\bold{x}) \to \P(\bold{Y}\mid\bold{X}\myeq\bold{x})$ in the MMD metric will also imply their weak convergence, i.e. $k$ metrizes weak convergence \citep{optimalestimationofprobabilitymeasures, simon2018kernel, simon2020metrizing}: \begin{corollary} \label{cor: metrizing weak convergence} Assume that one of the following two sets of conditions holds: \begin{itemize} \item[(a)] The kernel $k$ is bounded, (jointly) continuous and has \begin{align}\label{characteristiccondapp} \int \int k(\mathbf{x},\mathbf{y}) d\mathcal{P}(\mathbf{x}) d\mathcal{P}(\mathbf{y}) > 0 \ \ \forall \mathcal{P} \in \mathcal{M}_b(\R^d)\setminus \{0\}. \end{align} Moreover, $\mathbf{y} \mapsto k(\mathbf{y}_0, \mathbf{y})$ is vanishing at infinity, for all $\mathbf{y}_0 \in \R^d$. \item[(b)] The kernel $k$ is bounded, shift-invariant, (jointly) continuous and $\nu$ in the Bochner representation in \eqref{eq: bochner} is supported on all of $\R^d$. Moreover, $\mathbf{Y}$ takes its values almost surely in a closed and bounded subset of $\R^d$. \end{itemize} Then, under the conditions of Theorem \ref{thm: consistency}, we have for any bounded and continuous function $f:\R^d \to \R$ that DRF consistently estimates the target $\tau(\bold{x})=\E[f(\bold{Y})\mid\bold{X}\myeq\bold{x}]$ for any $\bold{x} \in [0,1]^p$: $$\sum_{i=1}^n w_{\mathbf{x}}(\mathbf{x}_i) f(\mathbf{y}_i) \,\stackrel{p}{\to}\, \E[f(\bold{Y})\mid\bold{X}\myeq\bold{x}].$$ \end{corollary} Recalling the Portmanteau Lemma on separable metric spaces, see e.g.\ \citet[Chapter 11]{dudley}, this has several other interesting consequences, such as the consistency of CDF and quantile estimates; Let $F_{\mathbf{Y}\mid\bold{X}\myeq\bold{x}}(\cdot)$ be the conditional CDF of $\mathbf{Y}$ and for any index $1\leq i\leq d$, let $F_{Y_i\mid\bold{X}\myeq\bold{x}}(\cdot)$ be the conditional CDF of $Y_i$ and $F_{Y_i\mid\bold{X}\myeq\bold{x}}^{-1}(\cdot)$ its generalized inverse, i.e. the quantile function. Let $\hat{F}_{Y_i\mid\bold{X}\myeq\bold{x}}(\cdot)$ and $\hat{F}_{Y_i\mid\bold{X}\myeq\bold{x}}^{-1}(\cdot)$ be the corresponding DRF estimates via weighting function \eqref{eq: CDF estimate}. Then we have the following result: \begin{corollary}\label{cor: cdfresult} Under the conditions of Corollary \ref{cor: metrizing weak convergence}, we have \begin{align*} \hat{F}_{\mathbf{Y} \mid\bold{X}\myeq\bold{x}}(\mathbf{t}) \, &\stackrel{p}{\to}\, F_{\mathbf{Y}\mid\bold{X}\myeq\bold{x}}(\mathbf{t}) \\ \hat{F}_{Y_i\mid\bold{X}\myeq\bold{x}}^{-1}(t) \, &\stackrel{p}{\to}\, F_{Y_i\mid\bold{X}\myeq\bold{x}}^{-1}(t) \end{align*} for all points of continuity $\mathbf{t} \in \R^d$ and $t \in \R$ of $F_{\mathbf{Y}\mid\bold{X}\myeq\bold{x}}(\cdot)$ and $F_{Y_i\mid\bold{X}\myeq\bold{x}}^{-1}(\cdot)$ respectively. \end{corollary} \section{Applications and Numerical Experiments} \label{sec: applications} The goal of this section is to demonstrate the versatility and applicability of DRF for many practical problems. We show that DRF can be used not only as an estimator of the multivariate conditional distribution, but also as a two-step method to easily obtain out-of-the box estimators for various, and potentially complex, targets $\tau(\bold{x})$. Our main focus lies on the more complicated targets which cannot be that straightforwardly approached by conventional methods. However, we also illustrate the usage of DRF for certain applications for which there already exist several well-established methods. Whenever possible in such cases, we compare the performance of DRF with the specialized, task-specific methods to show that, despite its generality, there is at most a very small loss of precision. However, we should point out that for many targets such as, that can not be written in a form of a conditional mean or a conditional quantile, for example, conditional correlation, direct comparison of the accuracy is not possible for real data, since no suitable loss function exists and the ground truth is unknown. Finally, we show that, in addition to directly estimating certain targets, DRF can also be a very useful tool for many different applications, such as causality and fairness. Detailed descriptions of all data sets and the corresponding analyses, together with additional simulations can be found in the appendix. \subsection{Estimation of Conditional Multivariate Distributions} \label{sec: benchmarks} In order to provide good estimates for any target $\tau(\bold{x}) = \tau(\P(\bold{Y}\mid\bold{X}\myeq\bold{x}))$, our method needs to estimate the conditional multivariate distribution $\P(\bold{Y}\mid \bold{X}\myeq\bold{x})$ well. Therefore, we first investigate here the accuracy of the DRF estimate \eqref{eq: distributional estimate} of the full conditional distribution and compare its performance with the performance of several existing methods. There are not many algorithms in the literature that nonparametrically estimate the multivariate conditional distribution $\P(\bold{Y}\mid \bold{\mathbf{X}=\mathbf{x}})$. In addition to a few simple methods such as the $k$-nearest neighbors or the kernel regression, which locally weight the training points, we also consider advanced machine learning methods such as the Conditional Generative Adversarial Network (CGAN) \citep{mirza2014conditional, aggarwal2019benchmarking}, Conditional Variational Autoencoder (CVAE) \citep{sohn2015learning} and Masked Autoregressive Flow \citep{papamakarios2017masked}. It is worth mentioning that the focus in the machine learning literature has been more on applications where $d$ is very large (e.g.\ pixels of an image) and $p$ is very small (such as image labels). Even though some methods do not provide the estimated conditional distribution in a form as simple as DRF, one is still able to sample from the estimated distribution and thus perform any subsequent analysis and make fair comparisons between the methods. \begin{figure}[h] \hspace{-0.8cm} \includegraphics[width=1.06\linewidth]{vignette.png} \caption{The illustration of the estimated joint conditional distribution obtained by different methods for the toy example \eqref{eq: vignette example}. For $1000$ randomly generated test points $\bold{X}_{\text{test}} \sim U(0, 1)^p$ the top row shows the estimated distribution of the response component $Y_1$, whereas the bottom row shows the estimated distribution of $Y_2$. The $0.1$ and $0.9$ quantiles of the true conditional distribution are indicated by a dashed black line, whereas the conditional mean is shown as a black solid line.} \label{fig: distribution illustration} \end{figure} We first illustrate the estimated distributions of the above method on a toy example where $n=1000, p=10, d=2$ and \begin{equation} \label{eq: vignette example} Y_1 \indep Y_2\mid \bold{X}\myeq\bold{x}, \quad Y_1 \mid \bold{X}\myeq\bold{x} \sim U(x_1, x_1 + 1), \quad Y_2 \mid \bold{X}\myeq\bold{x} \sim U(0, x_2), \quad \bold{X} \sim U(0,1)^p. \end{equation} That is, in the above example $X_1$ affects the mean of $Y_1$, whereas $X_2$ affects the both mean and variance of $Y_2$, and $X_3,\ldots, X_p$ have no impact. The results can be seen in Figure \ref{fig: distribution illustration} for the above methods. We see that, unlike some other methods, DRF is able to balance the importance of the predictors $X_1$ and $X_2$ and thus to estimate the distributions of $Y_1$ and $Y_2$ well. One can do a more extensive comparison on real data sets. We use the benchmark data sets from the multi-target regression literature \citep{mtr} together with some additional ones created from the real data sets described throughout this paper. The performance of DRF is compared with the performance of other existing methods for nonparametric estimation of multivariate distributions by using the Negative Log Predictive Density (NLPD) loss, which evaluates the logarithm of the induced multivariate density estimate \citep{quinonero2005evaluating}. As the number of test points grows to infinity, NLPD loss becomes equivalent to the average KL divergence between the estimated and the true conditional distribution and is thus able to capture how well one estimates the whole distribution instead of only its mean. In addition to the methods mentioned above, we also include the methods that are intended only for mean prediction, by assuming that the distribution of the response around its mean is homogeneous, i.e. that the conditional distribution $\P\left(\bold{Y} - \E[\bold{Y} \mid \bold{X}] \mid \bold{X}\myeq\bold{x}\right)$ does not depend on $\bold{x}$. This is fitted by regressing each component of $\bold{Y}$ separately on $\bold{X}$ and using the pooled residuals. We consider the standard nonparametric regression methods such as Random Forest \citep{breiman2001random}, XGBoost \citep{Chen:XGB}, and Deep Neural Networks \citep{goodfellow2016deep}. \begin{table}[h] \centering \begin{tabularx}{\textwidth}{lcccccccccccccc} \rot[0][3.5em]{} & \rot[45][1.8em]{jura} & \rot[45][1.8em]{slump} & \rot[45][1.8em]{wq} & \rot[45][1.8em]{enb} & \rot[45][1.8em]{atp1d} & \rot[45][1.8em]{atp7d} & \rot[45][1.8em]{scpf} & \rot[45][1.8em]{sf1} & \rot[45][1.8em]{sf2} & \rot[45][1.8em]{copula} & \rot[45][1.8em]{wage} & \rot[45][1.8em]{births1} & \rot[45][1.8em]{births2} & \rot[45][1.8em]{air} \\ \bottomrule \multicolumn{1}{c|}{$n$} & 359 & 103 & 1K & 768 & 337 & 296 & 143 & 323 & 1K & 5K & 10K & 10K & 10K & 10K\\ \multicolumn{1}{c|}{$p$} & 15 & 7 & 16 & 8 & 370 & 370 & 8 & 21 &22 & 10 & 73 & 23 & 24 & 15 \\ \multicolumn{1}{c|}{$d$} & 3 & 3& 14 &2 & 6 & 6 & 3 & 3 & 6 & 2 & 2 & 2 &4 & 6\\ \hline \multicolumn{1}{c|}{$\text{DRF}$} & \textbf{3.9} & \textbf{4.0} & \textbf{22.5} & 2.1 & 7.3 & \textbf{7.0} & \textbf{2.0} & \textbf{-24.2} & \textbf{-24.3} & \textbf{2.8} & \textbf{2.8} & 2.5 & \textbf{4.2} & \textbf{8.5} \\ \multicolumn{1}{c|}{$\text{CGAN}$} & 10.8 & 5.3 & 27.3 & 3.5 & 10.4 & 363 & 4.8 & 9.8 & 21.1 & 5.8 & 360 & \textbf{2.4} & {\small $>$1K} & 11.8 \\ \multicolumn{1}{c|}{$\text{CVAE}$} & 4.8& 37.8 & 36.8 & 2.6 & {\small $>$1K} & {\small $>$1K} & 108.8 & 8.6 & {\small $>$1K} & 2.9 & {\small $>$1K} & {\small $>$1K} & 49.7 & 9.6 \\ \multicolumn{1}{c|}{$\text{MAF}$} & 4.6 & 4.5 & 23.9& 3.0 & 8.0 & 8.1 & 2.6 & 4.7 & 3.8 & 2.9 & 3.0 & 2.5 & {\small $>$1K} & 8.5 \\ \multicolumn{1}{c|}{$\text{k-NN}$} & 4.5 & 5.0 & 23.4 & 2.4 & 8.8 & 8.6 & 4.1 & -22.4 & -19.7 & 2.9 & \textbf{2.8} & 2.7 & 4.4 & 8.8 \\ \multicolumn{1}{c|}{$\text{kernel}$} & 4.1 & 4.2 & 23.0 & \textbf{2.0} & \textbf{6.6} & 7.1 & 2.9 & -23.0 & -20.6 & 2.8 & 2.9 & 2.6 & 4.3 & 8.4 \\ \multicolumn{1}{c|}{$\text{RF}$} & 7.1 & 12.1 & 35.2 & 5.7 & 12.7 & 13.3 & 16.7 & 3.9 & 2.2 & 5.8 & 6.1 & 5.0 & 8.3 & 13.9 \\ \multicolumn{1}{c|}{$\text{XGBoost}$} & 11.4 & 38.3 & 25.9 & 3.0 & {\small $>$1K} & {\small {\small $>$1K}} & {\small $>$1K} & 0.3 & 1.6 & 3.5 & 2.9 & {\small $>$1K} & {\small $>$1K} & 12.8 \\ \multicolumn{1}{c|}{$\text{DNN}$} & 4.0 & 4.2 & 23.3 & 2.6 & 8.6 & 8.7 & 2.6 & 2.3 & 2.2 & 2.9 & 3.0 & 2.6 & 5.4 & 8.6 \\ \hline \end{tabularx} \caption{ NLPD loss computed on out-of-sample observations for the estimated conditional distributions obtained by several different methods (corresponding to rows) for many real data sets (corresponding to columns). The best method is indicated in bold. Detailed description of both the data sets and the competing methods can be found in Appendix \ref{appendix: simulation details}.} \label{benchtable} \end{table} The results are shown in Table \ref{benchtable}. We see that DRF performs well for a wide range of sample size and problem dimensionality, especially in problems where $p$ is large and $d$ is moderately big. It does so without the need for any tuning or involved numerical optimization. More detailed analysis and descriptions of each competing method and the loss function can be found in the Appendix \ref{appendix: simulation details}. \subsection{Estimation of Statistical Functionals} Because DRF represents the estimated conditional distribution $\hat{\P}(\bold{Y} \mid \bold{X}=\bold{x}) = \sum_{i} w_{\bold{x}}(\bold{x}_i)\cdot \delta_{\bold{y}_i}$ in a convenient form by using weights $w_{\bold{x}}(\bold{x}_i)$, a plug-in estimator $\tau(\hat{\P}(\bold{Y} \mid \bold{X}=\bold{x}))$ of many common real valued statistical functionals $\tau(\P(\bold{Y} \mid \bold{X}=\bold{x})) \in \R$ can be easily constructed from $w_{\bold{x}}(\cdot)$. \begin{figure}[h] \hspace{-0.7cm} \includegraphics[width=1.05\linewidth]{univariate.png} \caption{Scatter plot of predictions of the $0.1, 0.5$ and $0.9$ quantiles against $X_1$ for randomly generated $500$ test data points $\bold{X}_{\text{test}} \sim U(-1, 1)^p$. The true values of the quantiles are displayed by black dashed lines. The columns corresponds to different methods DRF (red), GRF (green), QRF (blue), TRF (purple). The rows correspond to different simulation scenarios. The first two are taken from \citet{athey2019generalized}.} \label{fig: univariate} \end{figure} We first investigate the performance for the classical problem of univariate quantile estimation on simulated data. We consider the following three data generating mechanisms with $p=40, n=2000$ and $\bold{X}_i \iid U(-1,1)^p$: \begin{itemize} \item Scenario 1: $Y \sim N(0.8\cdot \1(X_1 > 0), 1)$ (mean shift based on $X_1$) \item Scenario 2: $Y \sim N(0, (1+\1(X_1>0))^2)$ (variance shift based on $X_1$) \item Scenario 3: $Y \sim \1(X_1\leq 0) \cdot N(1, 1) + \1(X_1 > 0) \cdot \text{Exp}(1)$ (distribution shift based on $X_1$, constant mean and variance) \end{itemize} The first two scenarios correspond exactly to the examples given in \citet{athey2019generalized}. In Figure \ref{fig: univariate} we can see the corresponding estimates of the conditional quantiles for DRF, Quantile Regression Forest (QRF) \citep{meinshausen2006quantile}, which uses the same forest construction with CART splitting criterion as the original Random Forest \citep{breiman2001random} but estimates the quantiles from the induced weighting function, Generalized Random Forests (GRF) \citep{athey2019generalized} with a splitting criterion specifically designed for quantile estimation and Transformation Forests (TRF) \citep{hothorn2017transformation}. We see that DRF is performing very well even compared to methods that are specifically tailored to quantile estimation. For more detailed analysis and some additional examples, such as the univariate mean regression, we refer the reader to Appendix \ref{appendix: additional examples}. The multivariate setting is however more interesting, as one can use DRF to compute much more interesting statistical functionals $\tau(\bold{x})$. We illustrate this in Figure \ref{fig: functionals} for the the air quality data set, described in Section \ref{sec: weighting function}. The left plot shows one value of the estimated multivariate CDF, specifically the estimated probability of the event that the air quality index (AQI) is at most $50$ at a given test site. This corresponds to the "Good" category and means that the amount of every air pollutant is below a certain threshold determined by the EPA. Such probability estimates can be easily obtained by summing the weights of the training points belonging to the event of interest. \begin{figure}[h] \hspace*{-0.3cm} \includegraphics[width=1.04\textwidth]{functionals.png} \caption{Estimates of the probability $\P(\text{AQI} \leq 50 \mid \text{test site})$ (left) and the conditional correlation (right) derived from the DRF estimate of the multivariate conditional distribution.} \label{fig: functionals} \end{figure} In order to investigate the accuracy of the conditional CDF obtained by DRF, we compare the estimated probabilities with estimates of the standard univariate classification forest \citep{breiman2001random} with the response $\1(\text{AQI} \leq 50)$. In the left plot of Figure \ref{comparison}, we can see that the DRF estimates of the $\P(\text{AQI} \leq 50 \mid {\mathbf{X}=\mathbf{x}})$ (also visualized in Figure \ref{fig: functionals}) are quite similar to the estimates of the classification forest predicting the outcome $\1(\text{AQI} \leq 50)$. Furthermore, the cross-entropy loss evaluated on the held-out measurements equals $0.4671$ and $0.4663$ respectively, showing almost no loss of precision. In general, estimating the simple functionals from the weights provided by DRF comes usually at a small to no loss compared to the classical methods specifically designed for this task. In addition to the classical functionals $\tau(\bold{x})$ in the form of an expectation $\mathbb{E}(f(\bold{Y})\mid \bold{X}=\bold{x})$ or a quantile $Q_{\alpha}(f(\bold{Y})\mid \bold{X}=\bold{x})$ for some function $f: \mathbb{R}^{d} \rightarrow \mathbb{R}$, which can also be computed by solving the corresponding one-dimensional problems, additional interesting statistical functionals with intrinsically multivariate nature that are not that simple to estimate directly are accessible by DRF, such as, for example, the conditional correlations $\Cor(Y_i,\, Y_j \mid \bold{X}\myeq\bold{x})$. As an illustration, the estimated correlation of the sulfur dioxide ($\text{SO}_2$) and fine particulate matter (PM2.5) is shown in the right plot of Figure \ref{fig: functionals}. The plot reveals also that the local correlation in many big cities is slightly larger than in its surroundings, which can be explained by the fact that the industrial production directly affects the levels of both pollutants. \begin{figure}[h] \hspace*{-0.4cm} \includegraphics[width=1.02\textwidth, height=3.5cm]{classification_comparison.png} \caption{Left: Comparison of the CDF estimates obtained by DRF (displayed also in the left plot of Figure \ref{fig: functionals}) and by the classification forest. Right: Example how the CDF estimated by using the classification forest (blue) need not be monotone, whereas the DRF estimates (red) are well-behaved.} \label{comparison} \end{figure} A big advantage of the target-free forest construction of DRF is that all subsequent targets are computed from same the weighting function $w_\bold{x}$ obtained from a single forest fit. First, this is computationally more efficient, since we do not need for every target of interest to fit the method specifically tailored to it. For example, estimating the CDF with classification forests requires fitting one forest for each function value. Secondly and even more importantly, since all statistical functionals are plug-in estimates computed from the same weighting function, the obtained estimates are mathematically well-behaved and mutually compatible. For example, if we estimate $\Cor(Y_i, Y_j \mid \bold{X}\myeq\bold{x})$ by separately estimating the terms $\Cov(Y_i, Y_j \mid \bold{X}\myeq\bold{x})$, $\Var(Y_i \mid \bold{X}\myeq\bold{x})$, and $\Var(Y_j \mid \bold{X}\myeq\bold{x})$, one can not in general guarantee the estimate to be in the range $[-1, 1]$, but this is possible with DRF. Alternatively, the correlation or covariance matrices that are estimated entrywise are guaranteed to be positive semi-definite if one uses DRF. As an additional illustration, Figure \ref{comparison} shows that the estimated (univariate) CDF using the classification forest need not be monotone due to random errors in each predicted value, which can not happen with the DRF estimates. \subsection{Conditional Copulas and Conditional Independence Testing} \label{sec: copulas} One can use the weighting function not only to estimate certain functionals, but also to obtain more complex objects, such as, for example, the conditional copulas. The well-known Sklar's theorem \citep{sklar1959fonctions} implies that at a point $\textbf{x} \in \mathbb{R}^{p}$, the conditional CDF $\P(\bold{Y} \leq \bold{y} \mid \bold{X}=\bold{x}) = \P(Y_1 \leq y_1, \ldots, Y_d \leq y_d \mid \bold{X}=\bold{x})$ can be represented by a CDF $C_{\bold{x}}$ on $[0,1]^{d}$, the conditional copula at $\bold{x}$, and $d$ conditional marginal CDFs $F_{Y_i\mid\bold{X}\myeq\bold{x}}(y) = \P(Y_{i} \leq y \mid \bold{X}=\bold{x})$ for $1 \leq i \leq d$, as follows: \begin{equation} \label{eq: copula decomposition} \P(\bold{Y} \leq \bold{y}\mid \bold{X}=\bold{x}) = C_{\bold{x}}\left( F_{Y_1\mid\bold{X}\myeq\bold{x}}(y_1), \ldots, F_{Y_d\mid\bold{X}\myeq\bold{x}}(y_d) \right). \end{equation} Copulas capture the dependence of the components $Y_i$ by the joint distribution of the corresponding quantile levels of the marginal distributions: $F_{Y_i\mid\bold{X}\myeq\bold{x}}(Y_i) \in [0,1]$. Decomposing the full multivariate distribution to marginal distributions and the copula is a very useful technique used in many fields such as risk analysis or finance \citep{cherubini2004copula}. Using DRF enables us to estimate copulas conditionally, either by fitting certain parametric model or nonparametrically, directly from the weights. \begin{figure}[h] \centering \hspace*{-0.6cm} \includegraphics[width=1.04\textwidth]{copula+dist.png} \caption{Estimated conditional joint distribution of $(Y_1, Y_2)$ and conditional copulas obtained by DRF at different test points $\bold{x}$, where $x_1$ equals $0.25$ and $0.75$ respectively. The red lines are the contours of the true multivariate density function.} \label{fig: gaussian_copula} \end{figure} To illustrate this, consider an example where the $5$-dimensional $\bold{Y}$ is generated from the equicorrelated Gaussian copula $\bold{Y}= (Y_{1},\ldots,Y_{5}) \mid \bold{X}=\bold{x} \sim C^{\text{Gauss}}_{\rho(\bold{x})}$ conditionally on the covariates $\bold{X}$ with distribution $\mathbf{X}_i \iid U(0,1)^{p}$, where $p=30$ and $n\myeq 5000$. All $Y_i$ have a $N(0,1)$ distribution marginally, but their conditional correlation for $i \neq j$ is given by $\text{Cor}(Y_i, Y_j) = \rho(\bold{x}) = x_1$. Figure \ref{fig: gaussian_copula} shows that DRF estimates the full conditional distribution at different test points $\bold{x}$ quite accurately and thus we can obtain a good nonparametric estimate of the conditional copula as follows. First, for each component $Y_i$, we compute the corresponding marginal CDF estimate $\hat{F}_{Y_i\mid\bold{X}\myeq\bold{x}}(\cdot)$ from the weights. Second, we map each response $\bold{y}_i \to \bold{u}_i \coloneqq \left(\hat{F}_{Y_1\mid\bold{X}\myeq\bold{x}}\left((\bold{y}_i)_1\right), \ldots, \hat{F}_{Y_d\mid\bold{X}\myeq\bold{x}}\left((\bold{y}_i)_d\right)\right)$. The copula estimate is finally obtained from the weighted distribution $\sum_{i=1}^n w_{\bold{x}}(\bold{x}_i) \delta_{\bold{u}_i}$, from which we sample the points in Figure \ref{fig: gaussian_copula} in order to visualize the copula. If we want to instead estimate the copula parametrically, we need to find the choice of parameters for a given model family which best matches the estimated conditional distribution, e.g.\ by weighted maximum likelihood estimation (MLE). For the above example, the correlation parameter of the Gaussian copula can be estimated by computing the weighted correlation with weights $\{w_\bold{x}(\bold{x}_i)\}_{i=1}^n$. The left plot in Figure \ref{fig: conditional-independence} shows the resulting estimates of the conditional correlation $\text{Cor}\left(Y_1, Y_2 \mid \bold{X}=\bold{x}\right)$ obtained from $\text{DRF}_{\text{MMD}}$, which uses the MMD splitting criterion \eqref{eq: MMD splitcrit} described in Section \ref{sec: MMD splitcrit}, and $\text{DRF}_{\text{CART}}$, which aggregates the marginal CART criteria \citep{kocev2007ensembles, segal2011multivariate}. We see that $\text{DRF}_{\text{MMD}}$ is able to detect the distributional heterogeneity and provide good estimates of the conditional correlation. On the other hand, $\text{DRF}_{\text{CART}}$ cannot detect the change in distribution of $\bold{Y}$ caused by $X_1$ that well. The distributional heterogeneity can not only occur in marginal distribution of the responses (a case extensively studied in the literature), but also in their interdependence structure described by the conditional copula $C_{\bold{x}}$, as one can see from decomposition \eqref{eq: copula decomposition}. Since $\text{DRF}_\text{MMD}$ relies on a distributional metric for its splitting criterion, it is capable of detecting any change in distribution \citep{gretton2007kernel}, whereas aggregating marginal CART criteria for $Y_1, \ldots, Y_d$ in $\text{DRF}_\text{CART}$ only captures the changes in the marginal means. \begin{figure}[h] \centering \hspace*{-0.6cm} \includegraphics[width=0.9\textwidth]{conditional-independence.png} \caption{Estimated conditional correlation of $Y_1$ and $Y_2$ (left) and estimated conditional dependence quantified by HSIC statistic (right), obtained by $\text{DRF}_{\text{MMD}}$ (blue) and $\text{DRF}_{\text{CART}}$ (red) respectively. For every test point, we set $X_j=0.5, j \neq 1$. Black dashed curve indicates the population values.} \label{fig: conditional-independence} \end{figure} This is further illustrated for a related application of conditional independence testing, where we compute some dependence measure from the obtained weights. For example, we can test the independence $Y_1 \indep Y_2$ conditionally on the event $\bold{X}=\bold{x}$ by using the Hilbert Schmidt Independence Criterion (HSIC) \citep{HSIC}, which measures the difference between the joint distribution and the product of the marginal distributions. The right plot of Figure \ref{fig: conditional-independence} shows that the $\text{DRF}_{\text{MMD}}$ estimates are quite close to the population value of the HSIC, unlike the ones obtained by $\text{DRF}_\text{CART}$. \subsection{Heterogeneous Regression and Causal Effect Estimation} \label{sec: causality} In this and the following section, we illustrate that, in addition to direct estimation of certain targets, DRF can also be a useful tool for complex statistical problems and applications, such as causality. Suppose we would like to investigate the relationship between some (univariate) quantity of interest $Y$ and certain predictors $\bold{W}$ from heterogeneous data, where the change in distribution of $(\bold{W}, Y)$ can be explained by some other covariates $\bold{X}$. Very often in causality applications, $\bold{W}$ is a (multivariate) treatment variable, $Y$ is the outcome, which is commonly, but not necessarily, discrete, and $\bold{X}$ is a set of observed confounding variables for which we need to adjust if we are interested in the causal effect of $\bold{W}$ on $Y$. This is illustrated by the following causal graph: \begin{center} \begin{tikzpicture}[ > = stealth, shorten > = 1pt, auto, node distance = 3cm, semithick ] \tikzstyle{every state}=[ draw = black, thick, fill = white, minimum size = 4mm ] \node[circle, draw=black] (W) at (0,0) {$\bold{W}$}; \node[circle, draw=black] (X) at (2,1.3) {$\boldsymbol{X}$}; \node[circle, draw=black] (Y) at (4, 0) {$Y$}; \path[->,line width=1.4pt] (W) edge node {} (Y); \path[->] (X) edge node {} (W); \path[->] (X) edge node {} (Y); \end{tikzpicture} \end{center} The problem of nonparametric confounding adjustment is hard; not only can the marginal distributions of $Y$ and $\bold{W}$ be affected by $\bold{X}$, thus inducing spurious associations due to confounding, but the way how $\bold{W}$ affects $Y$ can itself depend on $\bold{X}$, i.e.\ the treatment effect might be heterogeneous. The total causal effect can be computed by using the adjustment formula \citep{pearl2009causality}: \begin{align} \E[Y\mid do(\bold{W}\myeq\bold{w})] &= \int \E[Y\mid do(\bold{W}\myeq\bold{w}), \bold{X}\myeq\bold{x}]\,\P(\bold{X}\myeq\bold{x}\mid do(\bold{W}\myeq\bold{w}))d\bold{x} \nonumber\\ &=\int \E[Y\mid \bold{W}\myeq\bold{w}, \bold{X}\myeq\bold{x}]\,\P(\bold{X}\myeq\bold{x})d\bold{x}. \label{eq: causal effect} \end{align} However, implementing do-calculus for finite samples and potentially non-discrete data might not be straightforward and comes with certain difficulties. The standard approach would be to estimate the conditional mean $\E[Y\mid \bold{W}\myeq\bold{w}, \bold{X}\myeq\bold{x}]$ nonparametrically by regressing $Y$ on $(\bold{X}, \bold{W})$ with some method of choice and to average out the estimates over different $\bold{x}$ sampled from the observed distribution of $\bold{X}$. Using DRF for this is not necessary, but has an advantage that one can easily estimate the full interventional distribution $\P(Y\mid do(\bold{W}\myeq\bold{w}))$ and not only the interventional mean. Another way to compute the causal effect is explained in the following, which allows to add more structure to the problem. We use DRF to first fit the forest with the multivariate response $(\bold{W}, Y)$ and the predictors $\bold{X}$. In this way, one can for any point of interest $\bold{x}$ obtain the joint distribution of $(\bold{W}, Y)$ conditionally on the event $\bold{X}\myeq\bold{x}$ and then the weights $\{w_\bold{x}(\bold{x}_i)\}_{i=1}^n$ can be used as an input for some regression method for regressing $Y$ on $\bold{W}$ in the second step. This conditional regression fit might be of separate interest and it can also be used for estimating the causal effect $\E[Y \mid do(\bold{W}\myeq\bold{w})]$ from \eqref{eq: causal effect}, by averaging the estimates $\E[Y \mid \bold{W}\myeq\bold{w}, \bold{X}\myeq\bold{x}]$ over $\bold{x}$, where $\bold{x}$ is sampled from the empirical observation of $\bold{X}$. In this way one can efficiently exploit and incorporate any prior knowledge of the relationship between $\bold{W}$ and $Y$, such as, for example, monotonicity, smoothness or that it satisfies a certain parametric regression model, without imposing any assumptions on the effect of $\bold{X}$ on $(\bold{W}, Y)$. Furthermore, one might be able to better extrapolate to the regions of space where $\P(\bold{W}\myeq\bold{w}, \bold{X}\myeq\bold{x})$ is small, compared to the standard approach which computes $\E[Y \mid \bold{W}\myeq\bold{w}, \bold{X}\myeq\bold{x}]$ directly, by regressing $Y$ on $(\bold{W}, \bold{X})$. Extrapolation is crucial for causal applications, since for computing $\E[Y\mid do(\bold{W}\myeq\bold{w})]$ we are interested in what would happen with $Y$ when our treatment variable $\bold{W}$ is set to be $\bold{w}$, regardless of the value achieved by $\bold{X}$. However, it can easily happen that for this specific combination of $\bold{X}$ and $\bold{W}$ there are very few observed data points, thus making the estimation of the causal effect hard \citep{pearl2009causality}. \begin{figure}[h] \hspace{-0.6cm} \includegraphics[width=1.05\linewidth]{causal_effect_example.png} \caption{Left: Visualization of heterogeneous synthetic example \eqref{eq: causal example}. Middle: Gray points depict joint distribution of $(W, Y)$ conditionally on $\bold{X}\myeq\bold{x}$, for some choices of $\bold{x}$ indicated in the top left corner. Black curve indicates the true conditional mean $\E[Y\mid W\myeq w, \bold{X}\myeq\bold{x}]$, the blue curve represents the estimate obtained by DRF with response $(W, Y)$ and predictors $\bold{X}$ in combination with smoothing splines regression, whereas the red curve represents the estimate obtained by standard Random Forest. Right: The corresponding estimates for both methods of the causal effect $\E[Y\mid do(W\myeq w)]$ computed from \eqref{eq: causal effect}. The true causal effect is denoted by a black dashed curve.} \label{fig: causal_effect} \end{figure} As an illustration, we consider the following synthetic data example, with continuous outcome $Y$, continuous univariate treatment $W$, $n=5000$ and $p=20$: \begin{equation} \label{eq: causal example} \bold{X} \sim U(0,5)^p,\quad W \mid \bold{X} \sim N(X_2, 1),\quad Y \mid \bold{X}, W \sim N(X_2 + X_1 \sin(W), 1). \end{equation} A visualization of the data can be seen on the left side of Figure \ref{fig: causal_effect}; treatment $W$ affects $Y$ non-linearly, $X_2$ is a confounding variable that affects the marginal distributions of $Y$ and $W$ and $X_1$ makes the treatment effect heterogeneous. The middle part of Figure \ref{fig: causal_effect} shows the conditional regression fits, i.e.\ the estimates of $\E[Y\mid W\myeq w, \bold{X}\myeq\bold{x}]$ as $w$ varies and $\bold{x}$ is fixed. We see that combination of DRF with response $(Y, W)$ and predictors $\bold{X}$ with the smoothing splines regression of $Y$ on $W$ (blue curve) is more accurate than the estimates obtained by standard Random Forest \citep{breiman2001random} with response $Y$ and predictors $(W, \bold{X})$ (red curve). Furthermore, we see that the former approach can extrapolate better to regions with small number of data points, which enables us to better estimate the causal effect $\E[Y \mid do(W \myeq w)]$ from \eqref{eq: causal effect}, by averaging the corresponding estimates of $\E[Y\mid W\myeq w, \bold{X}\myeq\bold{x}]$ over observed $\bold{x}$, as shown in the right plot of Figure \ref{fig: causal_effect}. The conditional regression fit $\E[Y\mid\bold{W}\myeq\bold{w}, \bold{X}\myeq\bold{x}]$ is related to the concept of the conditional average treatment effect (CATE) as it quantifies the effect of $\bold{W}$ on $Y$ for the subpopulation for which $\bold{X}=\bold{x}$. There exist many successful methods in the literature for estimating the causal effects and the (conditional) average treatment effects for a wide range of settings \citep{abadie2006large, chernozhukov2018double, wager2018estimation, kunzel2019metalearners}. Due to its versatility, DRF can easily be used when the underlying assumptions of existing methods are violated, when some additional structure is given in the problem or for the general, nonparametric, settings \citep{imbens2004nonparametric, ernest2015marginal, kennedy2017nonparametric}. Appendix \ref{appendix: additional examples} contains additional comparisons with some existing methods for causal effect estimation. \subsubsection{Births data} We further illustrate the applicability of DRF for causality-related problems on the natality data obtained from the Centers for Disease Control and Prevention (CDC) website, where we have information about all recorded births in the USA in 2018. We investigate the relationship between the pregnancy length and the birthweight, an important indicator of baby's health. Not only is this relationship complex, but it also depends on many different factors, such as parents' race, baby's gender, birth multiplicity (single, twins, triplets...) etc. In the left two plots of Figure \ref{birthweight} one can see the estimated joint distribution of birthweight and pregnancy length conditionally on many different covariates, as indicated in the plot. The black curves denote the subsequent regression fit, based on smoothing splines and described in detail in Appendix \ref{appendix: simulation details}. In addition to the estimate of the mean, indicated by the solid curve, we also include the estimates of the conditional $0.1$ and $0.9$ quantiles, indicated by dashed curves, which is very useful in practice for determining whether a baby is large or small for its gestational age. Notice how DRF assigns less importance to the mother's race when the point of interest is a twin (middle plot), as in this case more weight is given to twin births, regardless of the race of the parents. \begin{figure*}[h] \hspace*{-0.7cm} \includegraphics[width=1.06\textwidth]{births.png} \caption{Left and middle: estimated relationship of pregnancy length and birthweight, conditionally on the criteria indicated in the upper left corner. Right: estimated interventional effect of twin birth on the birthweight for a fixed pregnancy length. In all plots the solid curves denote the estimated conditional mean and the dashed denote the estimated $0.1$ and $0.9$ quantiles.} \label{birthweight} \end{figure*} Suppose now we would like to understand how a twin birth $T$ causally affects the birthweight $B$, but ignoring the obvious indirect effect due to shorter pregnancy length $L$. For example, sharing of resources between the babies might have some effect on their birthweight. We additionally need to be careful to adjust for other confounding variables $\bold{X}$, such as, for example, the parents' race, which can affect $B, T$ and $L$. We assume that this is represented by the following causal graph: \begin{center} \begin{tikzpicture}[ > = stealth, shorten > = 1pt, auto, node distance = 3cm, semithick ] \tikzstyle{every state}=[ draw = black, thick, fill = white, minimum size = 4mm ] \node[circle, draw=black] (T) at (0,0) {$T$}; \node[circle, draw=black] (X) at (2,1) {$\boldsymbol{X}$}; \node[circle, draw=black] (L) at (2,-1) {$L$}; \node[circle, draw=black] (B) at (4, 0) {$B$}; \path[->] (T) edge node {} (L); \path[->,line width=1.4pt] (T) edge node {} (B); \path[dashed,->] (X) edge node {} (T); \path[dashed,->] (X) edge node {} (L); \path[dashed,->] (X) edge node {} (B); \path[->] (L) edge node {} (B); \end{tikzpicture} \end{center} In order to answer the above question, we investigate the causal quantity $\P(B \mid do(T\myeq t, L\myeq l))$. Even though one cannot make such do-intervention in practice, this quantity describes the total causal effect if the birth multiplicity and the length of the pregnancy could be manipulated and thus for a fixed pregnancy length $l$, we can see the difference in birthweight due to $T$. We compute this quantity as already stated above, by using DRF with subsequent regression fits (described in detail in Appendix \ref{appendix: simulation details}), which has the advantage of better extrapolating to regions with small probability, such as long twin pregnancies (see middle plot of Figure \ref{birthweight}). In the right plot of Figure \ref{birthweight} we show the mean and quantiles of the estimated interventional distribution and we see that, as one might expect, a twin birth causes smaller birthweight on average, with the difference increasing with the length of the pregnancy. \subsection{Fairness} Being able to compute different causal quantities with DRF could prove useful in a range of applications, including fairness \citep{kusner2017counterfactual}. We investigate the data on approximately $1$ million full-time employees from the 2018 American Community Survey by the US Census Bureau from which we have extracted the salary information and all covariates that might be relevant for salaries. In the bottom left plot of Figure \ref{fig: wage} one can see the distribution of hourly salary of men and women (on the logarithmic scale). The overall salary was scaled with working hours to account for working part-time and for the fact that certain jobs have different working hours. We can see that men are paid more in general, especially for the very high salaries. The difference between the median hourly salaries, a commonly used statistic in practice, amounts $17\%$ for this data set. We would like to answer whether the observed gender pay gap in the data is indeed unfair, i.e.\ only due to the gender, or whether it can at least in part be explained by some other factors, such as age, job type, number of children, geography, race, attained education level and many others. Hypothetically, it could be, for example, that women have a preference for jobs that are paid less, thus causing the gender pay gap. In order to answer this question, we assume that the data is obtained from the following causal graph, where $G$ denotes the gender, $W$ the hourly wage and all other factors are denoted by $\bold{X}$: \begin{center} \begin{tikzpicture}[ > = stealth, shorten > = 1pt, auto, node distance = 3cm, semithick ] \tikzstyle{every state}=[ draw = black, thick, fill = white, minimum size = 4mm ] \node[circle, draw=black] (G) at (0,0) {$G$}; \node[circle, draw=black] (X) at (2,1) {$\boldsymbol{X}$}; \node[circle, draw=black] (W) at (4, 0) {$W$}; \path[->,line width=1.4pt] (G) edge node {} (W); \path[->] (G) edge node {} (X); \path[->] (X) edge node {} (W); \end{tikzpicture} \end{center} i.e.\ $G$ is a source node and $W$ is a sink node in the graph. In order to determine the direct effect of the gender on wage that is not mediated by other factors, we would like to compute the distribution of the nested counterfactual $W(\text{male},\, \bold{X}(\text{female}))$, which is interpreted in the data-generating process as the women's wage had they been treated in same way as men by their employers for determining the salary, but without changing their propensities for other characteristics, such as the choice of occupation. Therefore, it can be obtained from the observed distribution as follows: \begin{align} \P\left(W(\text{male},\, \bold{X}(\text{female}))\right) &= \int \P\left(W( G\myeq\text{male},\, \bold{X}\myeq\bold{x})\right)\P(\bold{X}\myeq\bold{x}\mid G\myeq\text{female})d\bold{x} \nonumber\\ &= \int \P\left(W\mid G\myeq\text{male},\, \bold{X}\myeq\bold{x}\right)\P(\bold{X}\myeq\bold{x}\mid G\myeq\text{female})d\bold{x}, \label{eq: nested_counterfactual} \end{align} Put in the language of the fairness literature, it quantifies the unfairness when all variables $\bold{X}$ are assumed to be resolving \citep{kilbertus2017avoiding}, meaning that any difference in salaries directly due to factors $\bold{X}$ is not viewed as gender discrimination. For example, one does not consider unfair if people with low education level get lower salaries, even if the gender distribution in this group is not balanced. \begin{figure}[h] \hspace*{-0.6cm} \includegraphics[width=1.05\textwidth]{wage_data2.png} \caption{Top row: Estimated joint distribution of wage and gender for some fixed values of other covariates $\bold{X}$ indicated in the top left part of each plot. Bottom row: observed overall distribution of salaries (left), estimated counterfactual distribution $\P\left(W(\text{male},\, \bold{X}(\text{female}))\right)$ of women's salaries (middle) and the quantile comparison of the counterfactual distribution of women's salaries and the observed distribution of men's salaries (right).} \label{fig: wage} \end{figure} There are several ways how one can compute the distribution of $W(\text{male},\, \bold{X}(\text{female}))$ from \eqref{eq: nested_counterfactual} with DRF. The most straightforward option is to take $W$ as the response and $(G, \bold{X})$ as predictors in order to compute the conditional distribution $\P\left(W\mid G\myeq\text{male},\, \bold{X}\myeq\bold{x}\right)$. However, with this approach it could happen that for predicting $\P\left(W\mid G\myeq\text{male},\, \bold{X}\myeq\bold{x}\right)$ we also assign weight to training data points for which $G\myeq\text{female}$. This happens if in some trees we did not split on variable $G$, which is likely, for example, if $\P(G=\text{male} \mid \bold{X}\myeq\bold{x})$ is low. Using salaries of both genders to estimate the distribution of men's salaries might be an issue if our goal is to objectively compare how women and men are paid. Another approach is to take $(W, G)$ as a multivariate response and $\bold{X}$ as the predictors for DRF and thus obtain joint distribution of $(W, G)$ conditionally on the event $\bold{X}\myeq\bold{x}$. In this way we can also quantify the gender discrimination of a single individual with characteristics $\bold{x}$ by comparing his/her salary to the corresponding quantile of the salary distribution of people of the opposite gender with the same characteristics $\bold{x}$ \citep{plevcko2019fair}. This is interesting because the distribution of salaries, and thus also the gender discrimination, can be quite different depending on other factors such as the industry sector or job type, as illustrated for a few choices of $\bold{x}$ in the top row of Figure \ref{fig: wage}. Finally, by averaging the DRF estimates of $\P\left(W\mid\bold{X}\myeq\bold{x},\, G\myeq\text{male}\right)$, conveniently represented via the weights, over different $\bold{x}$ sampled from the distribution $\P(\bold{X}\mid G\myeq\text{female})$, we can compute the distribution of the nested counterfactual $W(\text{male},\, \bold{X}(\text{female}))$. In the middle panel in the bottom row of Figure \ref{fig: wage} a noticeable difference in the means, also called natural direct effect in the causality literature \citep{pearl2009causality}, is still visible between the observed distribution of women's salaries and the hypothetical distribution of their salaries had they been treated as men, despite adjusting for indirect effects of the gender via covariates $\bold{X}$. By further matching the quantiles of the counterfactual distribution $\P\left(W(\text{male},\, \bold{X}(\text{female}))\right)$ with the corresponding quantiles of the observed distribution of men's salaries in the bottom right panel of Figure \ref{fig: wage}, we can also see that the adjusted gender pay gap even increases for larger salaries. Median hourly wage for women is still $11\%$ lower than the median wage for the hypothetical population of men with exactly the same characteristics $\bold{X}$ as women, indicating that only a minor proportion of the actually observed hourly wage difference of $17\%$ can be explained by other demographic factors. \section{Conclusion} We have shown that DRF is a flexible, general and powerful tool, which exploits the well-known properties of the Random Forest as an adaptive nearest neighbor method via the induced weighting function. Not only does it estimate multivariate conditional distributions well, but it constructs the forest in a model- and target-free way and is thus an easy to use out-of-the-box algorithm for many, potentially complex, learning problems in a wide range of applications, including also causality and fairness, with competitive performance even for problems with existing tailored methods. \newpag
{'timestamp': '2021-06-01T02:03:03', 'yymm': '2005', 'arxiv_id': '2005.14458', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14458'}
arxiv
\section{Introduction} A successful peg-hole insertion includes a series of sub-tasks like aligning the peg w.r.t hole and inserting in the hole. The task involves concurrent understanding of vision, depth and haptic modalities. This has been shown to pose significant difficulties for the robots. \cite{b1} claims that having a single modality, like vision, does not solve the peg-hole insertion problem accurately and precisely. This is the motivation behind our multi-modal perception system. In this work focus on using vision and optionally proprioception for robotic control, as well as trying to understand precision limits of a trainable vision-based controller. Reinforcement Learning (RL) allows learning control policies that are difficult to model explicitly. These policies can generalise with respect to the geometry of the peg and the hole, as stated in \cite{b1}. A UR5e robot used in our work is trained in the CoppeliaSim \cite{coppeliaSim} to learn a peg-hole insertion policy. We are using different model-free RL algorithms embedded in the Catalyst \cite{Catalyst} framework. In our experiments TD3\cite{TD3} converged to higher returns than DDPG\cite{DDPG} or SAC\cite{SAC} as shown in Fig. \ref{model_free} in section \ref{experiments}. Our deterministic control policy is learned from a multi-modal representation consisting of RGB-D images and proprioception. The policy generalises to different colours, as well as the 3D position of the peg and the block. \section{Related Work and Background} \label{related_work} \cite{RL_and_imitation} uses a hybrid approach of model-free deep RL and imitation learning to achieve zero-shot Sim2Real transfer on six different tasks with a single agent. The method shows that pre-training on expert demonstrations leads to faster training than learning the policy from scratch. \cite{GraspGAN} learns to refine synthetic images (domain adaptation) to achieve good grasping success rate using less real-world data. \cite{13} trains a network that maps input image to the robot's motor torque. \cite{b1} uses self-supervision to learn a compact and multimodal representation of the sensory inputs for the peg-hole insertion task. While all aforementioned works incorporate vision, none of them is using eye-in-hand approach which we consider much more suitable specifically for RL, where a policy can learn to optimize observations along the way, making the vision "active". \section{Problem Statement and Method Overview}\label{problem_statement} The main objective of our work is to make the robot learn a peg-hole insertion policy, which is invariant to the pose and color of the mating part or peg. This is done by training a robot in the simulation and then directly transferring the model to the real robot. For a better Sim2Real transferability, we experiment with image augmentation and include different modalities. We benchmark our approach against a proposed baseline model, introduced in section \ref{models}. \section{Baseline and RL Models}\label{models} \subsection{Baseline Model} Our baseline for the peg-in-hole insertion uses visual feedback together with classical computer vision tools to control the insertion of the peg. Firstly, the robot uses color information to segment out the mating part from the image. This allows to filter all the irrelevant visual noise. Secondly, the centre of the hole is being estimated. Finally, the end effector is guided to minimize the distance between the pose of the peg and the estimated pose of the hole. \subsection{Reinforcement Learning} We employ the actor-critic method, where both the actor and the critic are parameterized using neural networks. \begin{equation} R_{total} = R_{distance} + R_{success} + R_{collision} + R_{time} \label{reward_design} \end{equation} The total reward stated in Eq. \ref{reward_design} for each step consists of following components. \begin{itemize} \item \textbf{Distance Reward:} Based on the distance between the the peg and the target (the hole of the mating part). The smaller the distance, the higher the reward. \item \textbf{Success Reward:} A sparse reward based on the distance between the peg and the desired position in the hole. The agent is being rewarded once the peg gets very close to the target (specified by a threshold). \item \textbf{Collision Reward:} To discourage the robot from colliding with the block, a negative reward is obtained every time the agent collides with the mating part. \item \textbf{Time Reward:} To coerce the agent to complete the task as fast as possible, it obtains a small penalty per every step. \end{itemize} The scene in the CoppeliaSim and the real robot in starting position are shown in Fig. \ref{vrep}. On the real robot we use RealSense D435 RGB-D active stereo sensor. The mating part is being randomly placed on the table (always fully or partially visible for the robot in the starting position), imitating a flexible assembly process. \begin{figure}[ht] \centering \includegraphics[width=0.4\textwidth]{figures/scene.png} \caption{\textit{Left:} Rendered simulator scene from CoppeliaSim showing the UR5e robot with Robotiq gripper, a peg and a block. \textit{Right:} Real UR5e robot in our lab.} \label{vrep} \end{figure} \section{Experiments: Results} \label{experiments} First, we train the agent in the simulation. The learned policy is directly transferred to our real UR5e robot. Evaluation of the models is shown in Table \ref{tab:metrics}. We did a total of $30$ rollouts for each model, in which the mating part pose is changed for every 5 rollouts. These 6 mating poses are predefined, with a maximum distance of $39$ cm and $21$ cm between the poses in x- and y-axis respectively (in the plane of the table). The robot starts at a predefined home position for every rollout in both simulation and real world. The comparison of different model-free RL algorithms can be found in Fig. \ref{model_free}. Fig. \ref{ablation} shows which modalities are most important for the performance in the simulation. \begin{figure}[ht] \centering \includegraphics[width=0.45\textwidth]{figures/model-comp.png} \caption{ TD3 yielding higher return than SAC and DDPG.} \label{model_free} \end{figure} \begin{figure}[ht] \centering \includegraphics[width=0.45\textwidth]{figures/ablation.png} \caption{Ablation study showing different configurations of training in learning a peg-hole insertion policy in simulation. It can be seen that all the configurations converged to successful insertion in simulation. The performance of these configurations on real robot can be seen in Table \ref{tab:metrics}. } \label{ablation} \end{figure} \begin{table}[H] \centering \begin{tabular}{|c|c|c|c|} \hline \multirow{2}{*}{\textbf{Model Type}} & \multicolumn{2}{c|}{\textbf{Mean Error {[}mm{]}}} & \multirow{2}{*}{\textbf{Insertion {[}\%{]}}} \\ \cline{2-3} & x & y & \\ \hline Baseline & \hspace{1mm} $2.4\pm1.7$ & \hspace{0.1mm} $0.3\pm3.0$ & $100$ \\ \hline RGB w/ augs & $-2.0\pm3.8$ &$-9.8\pm11.2$ & $55$ \\ \hline RGB-D w/ augs & \hspace{1mm} $17.7\pm12.3$ & \hspace{0.1mm} $2.7\pm1.8$ & $0$ \\ \hline RGB-D w/o augs & $-124.1\pm166.9$ & \hspace{0.1mm} $65.6\pm94.4$ & $0$ \\ \hline \end{tabular} \caption{\textbf{Mean insertion error and insertion rate on the real robot.} The mean error between the ground truth position of the inserted peg versus the actual position at the end of an episode. Insertion rate is the percentage of the rollouts which end with successful insertion. The mean is taken over $30$ runs for different positions of the mating part on the table.} \label{tab:metrics} \end{table} \section{Discussion and Conclusion}\label{conclusion} Our initial hypothesis was that image augmentation is crucial for successful transfer from simulation to the real-world. Table \ref{tab:metrics} shows that augmentations improve the precision significantly. However, the RGB-D model still does not achieve steady, successful insertions. That could be because the depth image has a very specific structural noise (depth values are computed from stereo cameras) that can hardly be modelled with standard augmentation algorithms. Thus, RGB-only model shows much better performance. Additionally, the ablation study in Fig. \ref{ablation} shows that proprioceptive features are not critical for model performance for this task, neither in simulation, nor in real-life. Finally, we show that a purely eye-in-hand, image-based controller can be trained in simulation to perform peg-hole insertion with sub-centimetre accuracy. However, we still experience instabilities caused by changing light conditions and other environmental factors, that can be possibly improved by enhancing rendering in simulation and richer augmentation. For the future work we consider enhancing the vision-based controller with force-based one (trained end-to-end, as a single model), that can perform precise insertions with large initial uncertainty.
{'timestamp': '2020-06-01T02:07:12', 'yymm': '2005', 'arxiv_id': '2005.14401', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14401'}
arxiv
\section{Introduction} There has been an increasing trend in recent years to leverage machine learning methods to automate decision-making processes. However, for many applications, the adoption of such methods cannot rely solely on their prediction performance. For example, the European Union's General Data Protection Regulation, which became enforceable on 25 May 2018, introduces a right to explanation for all individuals so that they can obtain ``meaningful explanations of the logic involved'' when automated decision-making has ``legal effects'' on individuals or similarly ``significantly affecting'' them\footnote{\url{https://ec.europa.eu/info/law/law-topic/data-protection_en}}. Therefore, in addition to their prediction performance, machine learning methods have to be assessed on how they can supply their decisions with explanations. The performance of a machine learning method can be assessed by the extent to which it correctly predicts unseen instances. A metric like the accuracy score commonly measures the performance of a classification model. However, there is no standard approach to assess explainability. First, there is no mathematical definition of explainability. A definition proposed by~\cite{Miller19} states that the higher the explainability of a machine learning algorithm, the easier it is for someone to comprehend why certain decisions or predictions have been made. Second, there are several methods belonging to different categories (explainability-by-design, post-hoc model-specific explainability and post-hoc model-agnostic explainability)~\cite{Du20}, which provide their own form of explanations. The requirements for explainable machine learning methods are dependent upon the application and to whom the explanations are intended for~\cite{Tomsett18,Bohlender19}. In order to match these requirements and conduct experiments to validate the usefulness of the explanations by the end-users, there is a need to have a comprehensive assessment of the explainability of the existing methods.~\citeauthor{Doshi17} [2017] claim that creating a shared language is essential for the evaluation and comparison of machine learning methods, which is currently challenging without a set of explanation characteristics. As far as we have seen, there is no existing framework which defines a set of explanation characteristics that systematize the assessment of the explainability of existing machine learning methods. Hence, in this paper, we propose a new framework to assess and benchmark the performance-explainability characteristics of machine learning methods. The framework hypothesizes a set of explanation characteristics, and as emphasized in~\cite{Wolf19}, focuses on what people might need to understand about machine learning methods in order to act in concert with the model outputs. The framework does not claim to be exhaustive and excludes application-specific implementation constraints like time, memory usage and privacy. It could be a basis for the development of a comprehensive assessment of the machine learning methods with regards to their performance and explainability and for the design of new machine learning methods. Due to space constraint, we limit the illustration of the use of the framework to one category of machine learning methods and we choose the Multivariate Time Series (MTS) classifiers. Multivariate data which integrates temporal evolution has received significant interests over the past decade, driven by automatic and high-resolution monitoring applications (e.g. healthcare~\cite{Li18}, mobility~\cite{Jiang19}, natural disasters~\cite{Fauvel20}). Moreover, the available explainability solutions to support the current state-of-the-art MTS classifiers remain limited, so this category of methods appears meaningful to assess for us. The contributions of this paper are the following: \begin{itemize} \vspace{-0.4em} \item We present a new performance-explainability analytical framework to assess and benchmark machine learning methods; \vspace{-0.3em} \item We detail a set of characteristics that systematize the performance-explainability assessment of existing machine learning methods; \vspace{-0.3em} \item We illustrate the use of the framework by benchmarking the current state-of-the-art MTS classifiers. \vspace{-0.3em} \end{itemize} \section{Related Work} In this section, we first position this paper in the related work and introduce the different categories of explainability methods as a background to the notions that will be discussed in the framework. Then, we present the state-of-the-art machine learning methods that will be used to illustrate the framework, i.e. MTS classifiers. \vspace{-0.3em} \subsection{Explainability} Multiple taxonomies of explainability methods have been derived from different frameworks~\cite{Guidotti2018,Ventocilla18,Du20}. However, none of them defines a set of explanation characteristics that systematize the assessment of the explainability of existing machine learning methods. ~\cite{Guidotti2018} provides a classification of the main problems addressed in the literature with respect to the notion of explanation and the type of machine learning systems. ~\cite{Ventocilla18} proposes a high-level taxonomy of interpretable and interactive machine learning composed of six elements (Dataset, Optimizer, Model, Predictions, Evaluator and Goodness). And,~\cite{Du20} categorizes existing explainability methods of machine learning models into either by design or post-hoc explainability. As our framework aims to cover all types of methods, we do not present the frameworks focusing on a particular type of explainability methods (e.g.~\cite{Lundberg17,Ancona18,Henin19}). A five-step method to understand the requirements for explainable AI systems has been published in~\cite{Hall19}. The five steps are: explainee role definition, explanation characteristics identification, requirements collection, existing methods assessment and requirements/existing methods mapping. Our framework can be positioned as a further development of the fourth step of the method by detailing a set of explanations characteristics that systematize the assessment of existing methods. Our framework does not include application-specific implementation constraints like time, memory usage and privacy. As a background to the notions that will be discussed in the framework, we introduce the three commonly recognized categories (explainability-by-design, post-hoc model-specific explainability and post-hoc model-agnostic explainability)~\cite{Du20} to which all of the explainability methods are belonging to. First, some machine learning models provide explainability-by-design. These self-explanatory models incorporate explainability directly to their structures. This category includes, for example, decision trees, rule-based models and linear models. Next, post-hoc model-specific explainability methods are specifically designed to extract explanations for a particular model. These methods usually derive explanations by examining internal model structures and parameters. For example, a method has been designed to measure the contribution of each feature in random forests~\cite{Palczewska13}; and another one has been designed to identify the regions of input data that are important for predictions in convolutional neural networks using the class-specific gradient information~\cite{Selvaraju19}. Finally, post-hoc model-agnostic explainability methods provide explanations from any machine learning model. These methods treat the model as a black-box and does not inspect internal model parameters. For example, the permutation feature importance method~\cite{Altmann10} and the methods using an explainable surrogate model~\cite{Lakkaraju17,Lundberg17,Ribeiro18,Guidotti19} belong to this category. The explainability methods presented reflect the diversity of explanations generated to support model predictions, therefore the need for a framework in order to benchmark the machine learning methods explainability. The next section present the MTS classifiers that will be used to illustrate the framework. \vspace{-0.3em} \subsection{Multivariate Time Series Classifiers} \label{rw_MTS} The state-of-the-art MTS classifiers consist of a diverse range of methods which can be categorized into three families: similarity-based, feature-based and deep learning methods. Similarity-based methods make use of similarity measures to compare two MTS. Dynamic Time Warping (DTW) has been shown to be the best similarity measure to use along the k-Nearest Neighbors (k-NN)~\cite{Seto15}. There are two versions of kNN-DTW for MTS: dependent (DTW$_{D}$) and independent (DTW$_{I}$). Neither dominates over the other~\cite{Shokoohi17} from an accuracy perspective but DTW$_{I}$ allows the analysis of distance differences at feature level. Next, feature-based methods include shapelets (gRSF~\cite{Karlsson16}, UFS~\cite{Wistuba15}) and bag-of-words (LPS~\cite{Baydogan16}, mv-ARF~\cite{Tuncel18}, SMTS~\cite{Baydogan14}, WEASEL+MUSE~\cite{Schafer17}) models. WEASEL+MUSE shows better results compared to gRSF, LPS, mv-ARF, SMTS and UFS on average (20 MTS datasets). WEASEL+MUSE generates a bag-of-words representation by applying various sliding windows with different sizes on each discretized dimension (Symbolic Fourier Approximation) to capture features (unigrams, bigrams, dimension identification). Following a feature selection with chi-square test, it classifies the MTS based on a logistic regression classifier. Then, deep learning methods use Long-Short Term Memory (LSTM) and/or Convolutional Neural Networks (CNN). According to the results published, the current state-of-the-art model (MLSTM-FCN) is proposed in~\cite{Karim19} and consists of a LSTM layer and a stacked CNN layer along with Squeeze-and-Excitation blocks to generate latent features. Therefore, we choose to benchmark the performance-explainability of the best-in-class for each similarity-based, feature-based and deep learning category (DTW$_{I}$, WEASEL+MUSE and MLSTM-FCN classifiers). The next section introduces the performance-explainability framework, which is illustrated with the benchmark of the best-in-class MTS classifiers in section~\ref{sec:results}. \vspace{-0.5em} \section{Performance-Explainability Framework} The framework aims to respond to the different questions an end-user may ask to take an informed decision based on the predictions made by a machine learning model: \textit{What is the level of performance of the model? Is the model comprehensible? Is it possible to get an explanation for a particular instance? Which kind of information does the explanation provide? Can we trust the explanations? What is the target user category of the explanations?} The performance-explainability framework that we propose is composed of the following components, which will also be translated into terms specific to our application (MTS classifiers) whenever relevant: \vspace{-0.3em} \paragraph{Performance} \textit{What is the level of performance of the model?} The first component of the framework characterizes the performance of a machine learning model. Different methods (e.g. holdout, k-fold cross-validation) and metrics (e.g. accuracy, F-measure, Area Under the ROC Curve) exist to evaluate the performance of a machine learning model~\cite{Witten16}. However, there is no consensus on an evaluation procedure to assess the performance of a machine learning model. Recent work suggests that the definition of such an evaluation procedure necessitates the development of a measurement theory for machine learning~\cite{Flach19}. Many of the problems stem from a limited appreciation of the importance of the \textit{scale} on which the evaluation measures are expressed. Then, in current practices, the choice of a metric to evaluate the performance of a machine learning model depends on the application. According to the application, a metric aligned with the goal of the experiments is selected, which prevents the performance comparison of machine learning models across applications. Therefore, the performance component in the framework is defined as a first step towards a standard procedure to assess the performance of machine learning models. It corresponds to the relative performance of a model on a particular application. More specifically, it indicates the relative performance of the models as compared to the state-of-the-art model on a particular application and an evaluation setting. This definition allows the categorization of the models' performance on an application and an evaluation setting. In the case of different applications with a similar machine learning task, the performance component can give the list of models which outperformed current state-of-the-art models on their respective application. Thus, it points to certain models that could be interesting to evaluate on a new application, without providing guarantee that these models would perform the same on this new application. We propose an assessment of the performance in three categories: \begin{enumerate} \vspace{-0.4em} \item[$\bullet$] \textit{Best}: best performance. It corresponds to the performance of the first ranked model on the application following an evaluation setting (models, evaluation method, datasets); \vspace{-0.3em} \item[$\bullet$] \textit{Similar}: performance similar to that of the state-of-the-art models. Based on the same evaluation setting, it corresponds to all the models which do not show a statistically significant performance difference with the second ranked model. For example, the statistical comparison of multiple classifiers on multiple datasets is usually presented on a critical difference diagram~\cite{Demsar06}; \vspace{-1em} \item[$\bullet$] \textit{Below}: performance below that of the state-of-the-art models. It corresponds to the performance of the remaining models with the same evaluation setting. \end{enumerate} \paragraph{Model Comprehensibility} \textit{Is the model comprehensible?} The model comprehensibility corresponds to the ability for the user to understand how the model works and produces certain predictions. Comprehensibility is tightly linked to the model complexity; yet, there is no consensus on model complexity assessment~\cite{Guidotti2018}. Currently, two categories of models are commonly recognized: ``white-box'' models, i.e. easy-to-understand models, and ``black-box'' models, i.e. complicated-to-understand models~\cite{Lipton16}. For example, many rule-based models and decision trees are regarded as ``white-box'' models while ensemble methods and deep learning models are ``black-box'' models. Not all rule-based models or decision trees are ``white-box'' models. Cognitive limitations of humans place restrictions on the complexity of the approximations that are understandable to humans. For example, a decision tree with a hundred levels cannot be considered as an easy-to-understand model~\cite{Lakkaraju17}. Nevertheless, the distinction between ``white-box'' models and ``black-box'' models is clear among the machine learning methods of this paper. The state-of-the-art MTS classifiers are all ``black-box'' except one which is an easy-to-understand similarity-based approach. Therefore, due to space limitation, we propose a first assessment of the comprehensibility in two categories and we plan to further elaborate this component in future work: \begin{enumerate} \item[$\bullet$] \textit{Black-Box}: ``black-box'' model, i.e. complicated-to-understand models; \vspace{-0.3em} \item[$\bullet$] \textit{White-Box}: ``white-box'' model, i.e. easy-to-understand models. \end{enumerate} \paragraph{Granularity of the Explanations} \textit{Is it possible to get an explanation for a particular instance?} The granularity indicates the level of possible explanations. Two levels are generally distinguished: global and local~\cite{Du20}. Global explainability means that explanations concern the overall behavior of the model across the full dataset, while local explainability informs the user about a particular prediction. Some methods can provide either global or local-only explainability while other methods can provide both (e.g. decision trees). Therefore, we propose an assessment of the granularity in three categories: \begin{enumerate} \item[$\bullet$] \textit{Global}: global explainability; \vspace{-0.3em} \item[$\bullet$] \textit{Local}: local explainability; \vspace{-0.3em} \item[$\bullet$] \textit{Global \& Local}: both global and local explainability. \end{enumerate} \paragraph{Information Type} \textit{Which kind of information does the explanation provide?} The information type informs the user about the kind of information communicated. The most valuable information is close to the language of human reasoning, with causal and counterfactual rules~\cite{Pearl18}. Causal rules can tell the user that certain observed variables are the causes of specific model predictions. However, machine learning usually leverages statistical associations in the data and do not convey information about the causal relationships among the observed variables and the unobserved confounding variables. The usual statistical associations discovered by machine learning methods highly depend on the machine learning task. Therefore, we first give a generic high-level definition of the information type and then we detail and illustrate it for the application case of this paper (MTS classification). We propose a generic assessment of the information type in 3 categories from the least to the most informative: \begin{enumerate} \item[$\bullet$] \textit{Importance}: the explanations reveal the relative importance of each dataset variable on predictions. The importance indicates the statistical contribution of each variable to the underlying model when making decisions; \vspace{-0.3em} \item[$\bullet$] \textit{Patterns}: the explanations provide the small conjunctions of symbols with a predefined semantic (patterns) associated with the predictions; \vspace{-0.3em} \item[$\bullet$] \textit{Causal}: the most informative category corresponds to explanations under the form of causal rules; \end{enumerate} In this paper, the issue of Multivariate Time Series (MTS) classification is addressed. A MTS $M=\{x_1,...,x_d\} \in \mathcal{R}^{d*l}$ is an ordered sequence of $d \in \mathcal{N}$ streams with $x_i=(x_{i,1},...,x_{i,l})$, where $l$ is the length of the time series and $d$ is the number of multivariate dimensions. Thus, considering the MTS data type, the information can be structured around the features, i.e. the observed variables, and the time. We propose to decompose the 3 categories presented into 8 categories. In addition, we will illustrate each of these categories with an application in the medical field. Figure~\ref{fig:framework_MTS_example} shows the first MTS of the UEA Atrial Fibrilation~\cite{Bagnall18} test set that belongs to the class \textit{Non-Terminating Atrial Fibrilation}. This MTS is composed of two dimensions (two channels ECG) with a length of 640 (5 second period with 128 samples per second). It is worth noting that the explanations provided to illustrate each category are assumptive rather than validated, they are given as illustrative in nature. \begin{figure}[!htpb] \centering \includegraphics[width=.95\linewidth]{./Images/MTS_AtrialFibrilation.png} \caption{The first MTS sample of the UEA Atrial Fibrilation test set. It belongs to the class \textit{Non-Terminating Atrial Fibrilation} and is composed of two channels ECG on a 5 second period (128 samples per second).} \label{fig:framework_MTS_example} \vspace{-1.5em} \end{figure} \begin{table*}[!htpb] \centering \scriptsize \begin{threeparttable} \caption{Summary of framework results of the state-of-the-art MTS classifiers.} \label{tab:MTS} \vspace{-1em} \begin{tabularx}{.71\linewidth}{l>{\centering}m{3cm}>{\centering}m{3cm}>{\centering\arraybackslash}m{3cm}} \toprule \textbf{} & \textbf{Similarity-Based} & \textbf{Feature-Based} & \textbf{Deep Learning}\\ \textbf{} & DTW$_{I}$ & WEASEL+MUSE with SHAP & MLSTM-FCN with SHAP\\ \midrule\midrule[.1em] Performance & Below\tnote{1} & Similar\tnote{1} & Best\tnote{1}\\ Comprehensibility & White-Box & Black-Box & Black-Box\\ Granularity & Local & Both Global \& Local & Both Global \& Local\\ Information & Features+Time & Features+Time & Features+Time\\ Faithfulness & Perfect & Imperfect & Imperfect\\ User & Domain Expert & Domain Expert & Domain Expert\\ \bottomrule \end{tabularx} \begin{tablenotes} \item[1] Predefined train/test splits and an arithmetic mean of the accuracies on 35 public datasets [Karim et al., 2019]. As presented in section~\ref{rw_MTS}, the models evaluated in the benchmark are: DTW$_{D}$, DTW$_{I}$, gRSF, LPS, MLSTM-FCN, mv-ARF, SMTS, UFS and WEASEL+MUSE. \end{tablenotes} \vspace{-1.6em} \end{threeparttable} \end{table*} \begin{enumerate} \item[$\bullet$] \textit{Features} (\textit{Importance}): the explanations reveal the relative importance of the features on predictions. For example, in order to support a model output from the MTS of the Figure~\ref{fig:framework_MTS_example}, the explanations could tell the user that the channel 2 has a greater importance on the prediction than the channel 1; \vspace{-0.3em} \item[$\bullet$] \textit{Features + Time} (\textit{Importance}): the explanations provide the relative importance of the features and timestamps on predictions. For example, in order to support a model output from the MTS of the Figure~\ref{fig:framework_MTS_example}, the explanations could tell the user that the channel 2 has a greater importance on the prediction than the channel 1 and that the timestamps are in increasing order of importance on the prediction; \vspace{-0.3em} \item[$\bullet$] \textit{Features + Time + Values} (\textit{Importance}): in addition to the relative importance of the features and timestamps on predictions, the explanations indicate the discriminative values of a feature for each class. For example in Figure~\ref{fig:framework_MTS_example}, the explanations could give the same explanations as the previous category, plus, it could tell the user that the timestamps with the highest importance are associated with high values (values above 0.15) on the channel 2; \vspace{-0.3em} \item[$\bullet$] \textit{Uni Itemsets} (\textit{Patterns}): the explanations provide patterns under the form of groups of values, also called itemsets, which occur per feature and are associated with the prediction. For example, in order to support a model output from the MTS of the Figure~\ref{fig:framework_MTS_example}, the explanations could tell the user that the following itemsets are associated with the prediction: \{channel 1: extremely high value (above 1); channel 1: low value (below -0.05)\} and \{channel 2: high value (above 0.15); channel 2: extremely low value (below -0.1)\}. The first itemset can be read as: the prediction is associated with the occurence on the channel 1 of an extremely high value being above 1 and a low value being below -0.05 at another moment, without information on which one appears first; \vspace{-0.3em} \item[$\bullet$]\textit{Multi Itemsets} (\textit{Patterns}): the explanations provide patterns under the form of multidimensional itemsets, i.e. groups of values composed of different features, which are associated with the prediction. For example, in order to support a model output from the MTS of the Figure~\ref{fig:framework_MTS_example}, the explanations could tell the user that the following itemset is associated with the prediction: \{channel 1: extremely high value (above 1); channel 2: high value (above 0.15)\}; \vspace{-0.3em} \item[$\bullet$] \textit{Uni Sequences} (\textit{Patterns}): the explanations provide patterns under the form of ordered groups of values, also called sequences, which occur per feature and are associated with the prediction. For example, in order to support a model output from the MTS of the Figure~\ref{fig:framework_MTS_example}, the explanations could tell the user that the following sequences are associated with the prediction: $<$channel 1: extremely high value (above 1); channel 1: low value (below -0.05)$>$ and $<$channel 2: high values (above 0.15) with an increase during 1 second$>$. The first sequence can be read as: the prediction is associated with the occurrence on the channel 1 of an extremely high value being above 1 followed by a low value being below -0.05; \vspace{-0.3em} \item[$\bullet$] \textit{Multi Sequences} (\textit{Patterns}): the explanations provide patterns under the form of multidimensional sequences, i.e. ordered groups of values composed of different features, which are associated with the prediction. For example, in order to support a model output from the MTS of the Figure~\ref{fig:framework_MTS_example}, the explanations could tell the user that the following sequence is associated with the prediction: $<$channel 1: extremely high value (above 1); channel 2: high values (above 0.15) with an increase during 1 second$>$; \vspace{-0.3em} \item[$\bullet$] \textit{Causal}: the last category corresponds to explanations under the form of causal rules. For example, in order to support a model output from the MTS of the Figure~\ref{fig:framework_MTS_example}, the explanations could tell the user that the following rule applies: if (channel 1: extremely high value (above 1)) \& (channel 2: high values (above 0.15) with an increase during 1 second), then the MTS belongs to the class \textit{Non-Terminating Atrial Fibrilation}. \end{enumerate} \paragraph{Faithfulness} \textit{Can we trust the explanations?} The faithfulness corresponds to the level of trust an end-user can have in the explanations of model predictions, i.e. the level of relatedness of the explanations to what the model actually computes. An explanation extracted directly from the original model is faithful by definition. Some post-hoc explanation methods propose to approximate the behavior of the original ``black-box'' model with an explainable surrogate model. The explanations from the surrogate models cannot be perfectly faithful with respect to the original model~\cite{Rudin19}. The fidelity criteria is used to quantify the faithfulness by the extent to which the surrogate model imitates the prediction score of the original model~\cite{Guidotti2018}. In this paper, two MTS classifiers use an explainable surrogate model among the three state-of-the-art methods presented in section~\ref{sec:results}. However, there is no need to distinguish between the degree of fidelity of the surrogate models for the purpose of the comparison in this paper. Therefore, due to space limitation, we propose a first assessment of the faithfulness in two categories and we plan to further elaborate this component in future work: \begin{enumerate} \item[$\bullet$] \textit{Imperfect}: imperfect faithfulness (use of an explainable surrogate model); \vspace{-0.3em} \item[$\bullet$] \textit{Perfect}: perfect faithfulness. \end{enumerate} \paragraph{User category} \textit{What is the target user category of the explanations?} The user category indicates the audience to whom the explanations are accessible. The user's experience will affect what kind of \textit{cognitive chunks} they have, that is, how they organize individual elements of information into collections~\cite{Neat03}. Thus, it could be interesting to categorize the user types and associate with the model to whom the explanations will be accessible to. The broader the audience, the better are the explanations. Therefore, we propose an assessment in three categories: \begin{enumerate} \item[$\bullet$] \textit{Machine Learning Expert}; \vspace{-0.3em} \item[$\bullet$] \textit{Domain Expert}: domain experts (e.g. professionals, researchers); \vspace{-0.3em} \item[$\bullet$] \textit{Broad Audience}: non-domain experts (e.g. policy makers). \vspace{-0.3em} \end{enumerate} \begin{figure*}[!htpb] \centering \includegraphics[width=0.65\linewidth]{./Images/Parallel_Coordinates_MTS} \vspace{-0.5em} \caption{Parallel coordinates plot of the state-of-the-art MTS classifiers. Performance evaluation method: predefined train/test splits and an arithmetic mean of the accuracies on 35 public datasets [Karim et al., 2019]. As presented in section~\ref{rw_MTS}, the models evaluated in the benchmark are: DTW$_{D}$, DTW$_{I}$, gRSF, LPS, MLSTM-FCN, mv-ARF, SMTS, UFS and WEASEL+MUSE.} \label{fig:coordinates_example} \vspace{-1.3em} \end{figure*} In order to compare the methods visually using the proposed framework, the different aspects can be represented on a parallel coordinates plot. A parallel coordinate plot allows a 2-dimensional visualization of a high dimensional dataset and is suited for the categorical data of this framework. The next section presents an example of parallel coordinates plots comparing the state-of-the-art MTS classifiers. \vspace{-0.7em} \section{Application to Multivariate Time Series Classifiers} \label{sec:results} This section shows how the framework presented in the previous section can be used to assess and benchmark the state-of-the-art MTS classifiers. As introduced in section~\ref{rw_MTS}, the state-of-the-art MTS classifiers are: DTW$_{I}$, MLSTM-FCN and WEASEL+MUSE. The results of the assessment are summarized in Table~\ref{tab:MTS}, illustrated in Figure~\ref{fig:coordinates_example} and detailed in the following paragraphs. The first MTS classifier belongs to the similarity-based category and is the one-nearest neighbor MTS classifier with DTW distance (DTW$_{I}$). DTW$_{I}$ classifies MTS based on the label of the nearest sample and a similarity calculated as the cumulative distances of all dimensions independently measured under DTW. For each MTS, the explanation supporting the classification is the ranking of features and timestamps in decreasing order of their DTW distance with the nearest MTS. Based on predefined train/test splits and an arithmetic mean of the accuracies, DTW$_{I}$ underperforms the current state-of-the-art MTS classifiers on the 35 public datasets (Performance: \textit{Below}). The results from~\cite{Karim19} shows that DTW$_{I}$ has a statistically significant lower performance than MLSTM-FCN and WEASEL+MUSE. Furthermore, DTW$_{I}$ supports its predictions with limited information (Information: \textit{Features+Time}) that needs to be analyzed by a domain expert to ensure that it is relevant for the application (User: \textit{Domain Expert}). However, DTW$_{I}$ is an easy-to-understand model (Comprehensibility: \textit{White-Box}) which provides faithful explanations (Faithfulness: \textit{Perfect}) for each MTS (Granularity: \textit{Local}). Then, we can analyze MLSTM-FCN and WEASEL+ MUSE together. First, based on predefined train/test splits and an arithmetic mean of the accuracies, MLSTM-FCN exhibits the best performance on the 35 public datasets (Performance: \textit{Best})~\cite{Karim19}, followed by WEASEL+MUSE (Performance: \textit{Similar}). Second, both MLSTM-FCN and WEASEL+MUSE are ``black-box'' classifiers without being explainable-by-design or having a post-hoc model-specific explainability method. Thus, the explainability characteristics of these models depend on the choice of the post-hoc model-agnostic explainability method. We have selected SHapley Additive exPlanations (SHAP)~\cite{Lundberg17}, a state-of-the-art post-hoc model-agnostic explainability method offering explanations at all granularity levels. SHAP method measures how much each variable (Features+Time) impacts predictions and comes up with a ranking of the variables which could be exploited by domain experts. The combination of MLSTM-FCN and WEASEL+MUSE with SHAP enables them to outperform DTW$_{I}$ while reaching explanations with a similar level of information (Information: \textit{Features+Time}, DTW$_{I}$: \textit{Features+Time}), in the meantime remaining accessible to the same user category (User: \textit{Domain Expert}, DTW$_{I}$: \textit{Domain Expert}). However, as opposed to DTW$_{I}$, SHAP relies on a surrogate model which cannot provide perfectly faithful explanations (Faithfulness: \textit{Imperfect}, DTW$_{I}$: \textit{Perfect}). Therefore, based on the performance-explainability framework introduced, if a ``white-box'' model and perfect faithfulness are not required, it would be preferable to choose MLSTM-FCN with SHAP instead of the other state-of-the-art MTS classifiers on average on the 35 public datasets. In addition to its better level of performance, MLSTM-FCN with SHAP provides the same level of information and at all granularity levels. However, the imperfect faithfulness of the explanations could prevent the use of MLSTM-FCN with a surrogate explainable model on numerous applications. In addition, the level of information provided to support the predictions remains limited (Information: \textit{Features+Time}). Therefore, based on the assessment of the current state-of-the-art MTS classifiers with the framework proposed, it would be valuable for instance to design some new high-performing MTS classifiers which provide faithful and more informative explanations. For example, it could be interesting to work in the direction proposed in~\cite{Fauvel20LCE}. It presents a new MTS classifier (XEM) which reconciles performance (Performance: \textit{Best}) and faithfulness while providing the time window used to classify the whole MTS (Information: \textit{Uni Sequences}). XEM is based on a new hybrid ensemble method that combines an explicit approach to handle the bias-variance trade-off and an implicit approach to individualize classifier errors on different parts of the training data~\cite{Fauvel19}. Nevertheless, the explanations provided by XEM are only available per MTS (Granularity: \textit{Local}) and the level of information could be further improved. As suggested by the authors, it could be interesting to analyze the time windows identified for each class to determine if they contain some common multidimensional sequences (Information: \textit{Multi Sequences}, Granularity: \textit{Both Global \& Local}). These patterns could also broaden the audience as they would summarize the key information in the discriminative time windows. \vspace{-0.7em} \section{Conclusion} We have presented a new performance-explainability analytical framework to assess and benchmark the machine learning methods. The framework details a set of characteristics that systematize the performance-explainability assessment of machine learning methods. In addition, it can be employed to identify ways to improve current machine learning methods and to design new ones. Finally, we have illustrated the use of the framework by benchmarking the current state-of-the-art MTS classifiers. With regards to future work, we plan to further elaborate the definition of the different components of the framework (especially the \textit{Model Comprehensibility}, the \textit{Information Type} and the \textit{Faithfulness}) and evaluate the relevance of integrating new components. Then, we plan to apply the framework extensively to assess the different types of existing machine learning methods. \section*{Acknowledgments} This work was supported by the French National Research Agency under the Investments for the Future Program (ANR-16-CONV-0004) and the Inria Project Lab ``Hybrid Approaches for Interpretable AI'' (HyAIAI). \bibliographystyle{named}
{'timestamp': '2021-11-22T02:18:19', 'yymm': '2005', 'arxiv_id': '2005.14501', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14501'}
arxiv
\section{Introduction} Deep neural networks are now central to many real-world applications including image classification~\cite{ResNet,VGGnet,xu2019positive}, object detection~\cite{ren2016object,SSD}, low-level vision~\cite{SRCNN}, and natural language processing (NLP)~\cite{hochreiter1997long,mikolov2010recurrent,vaswani2017attention}. Their performance usually depends on the availability of large amounts of finely labeled training data. For example, the ImageNet dataset~\cite{deng2009imagenet}, which is used for image classification, includes over 1.2M images in 1000 different categories; the MegaFace face recognition dataset~\cite{kemelmacher2016megaface} has over 1M photos from 690k unique users; and the CoQA dataset~\cite{reddy2019coqa} used for NLP contains over 127k questions with answers collected from over 8k conversations. \begin{figure}[t] \centering \includegraphics[width=0.45\textwidth]{./figs/Intro} \caption{Diagram of the proposed DC-NAS. The given search space will be converted to a series of feature representations of different architectures. Then, a k-means algorithm is utilized to divide the searching problem, and the best architecture will be obtained by merging selected model candidates.} \label{Fig:pipeline} \end{figure} \begin{figure*}[t] \centering \begin{tabular}{ccc} \includegraphics[width=0.29\textwidth]{./figs/eval_5.pdf}& \includegraphics[width=0.29\textwidth]{./figs/eval_10.pdf}& \includegraphics[width=0.29\textwidth]{./figs/eval_15.pdf} \\ \small{(a)} & \small{(b)} & \small{(c)}\\ \includegraphics[width=0.29\textwidth]{./figs/eval_20.pdf}& \includegraphics[width=0.29\textwidth]{./figs/eval_200.pdf}& \includegraphics[width=0.29\textwidth]{./figs/final.pdf} \\ \small{(d)} & \small{(e)} & \small{(f)}\\ \end{tabular} \caption{Illustrative results of searching different neural architectures using conventional early stopping. Five architectures with different widths (\emph{i.e. }, $4$, $2$, $1$, $\frac{1}{2}$, and $\frac{1}{4}$) are established in each panel. Their performance is tested on the CIFAR-100 validation set using different strategies. (a)-(e) are the results learned using different epochs on the $10\%$ training set, and (f) shows the exact performance of these networks.} \label{Fig:Intro} \end{figure*} In addition to large amount of data, well-designed architectures are critical for effective deep neural networks, especially convolutional neural networks (CNNs) for computer vision tasks. There are many network architectures. Simonyan and Zisserman presented VGGNet~\cite{VGGnet}, which contains over $10^9$ learnable parameters. He~\emph{et.al.}~\cite{ResNet} presented a shortcut operation for training deep neural networks with over $50$ layers. ResNeXt~\cite{ResNeXt} combines the shortcut operation with the 'split-transform-merge' operation by first splitting the channel of each layer, then applying transformation separately, before finally merging the outputs with an addition operation. Huang~\emph{et.al.}~presented DenseNet~\cite{huang2017densely}, which strengths information flow by adding a shortcut to each pair of blocks. In addition, some modern neural architectures have significantly lower computational costs, allowing their use on mobile devices. MobileNet~\cite{Mobilenet} reduces the computational complexity by replacing the traditional convolution operation with a combination of depth-wise convolution and point-wise convolution. ShuffleNet~\cite{Shufflenet} enables information flow between groups by adding a channel shuffle operation after group convolution. Mobilenet-v2~\cite{sandler2018mobilenetv2} further uses a linear bottleneck and an inverted residual block to reuse the features and to overcome the manifold collapse problem produced by the ReLU operation. Han~\emph{et.al.}~developed GhostNet~\cite{han2019ghostnet} and built efficient neural networks by generating more features from some inexpensive operations. Despite the success of these networks and their variations, their design and implementation still require considerable human and computational resources. To address this, a number of neural architecture search (NAS) algorithms have been proposed to automatically search for optimal neural architectures in the given search space and dataset. Zoph \emph{et.al.}~\cite{zoph2016neural} generated the model descriptions of neural networks using a recurrent network and produced higher-accuracy architectures by training the recurrent neural network (RNN) with reinforcement learning. Real \emph{et.al.}~\cite{real2019regularized} used a modified evolutionary algorithm to search for better neural architectures in a given search space by introducing an age property to favor younger genotypes. Liu \emph{et.al.}~\cite{liu2018darts} represented the network architecture based on continuous relaxation, which allowed efficient architecture searching using gradient descent. Wang~\emph{et.al.}~\cite{wang2018towards} proposed an evolutionary method to automatically identify redundant filters in pre-trained deep neural networks. Pham \emph{et.al.}~\cite{pham2018efficient} reduced the search cost by searching for an optimal subgraph within a large computational graph with a controller. While these NAS methods have significantly contribute to searching for better neural architectures, they have a significant limitation: in order to achieve an acceptable search cost, each searched architecture is not precisely optimized. To this end, early stopping is widely used in NAS for fast comparison. However, considering all sub-networks together in early stopping is highly unstable since they each have variable computational power. Figure~\ref{Fig:Intro} illustrates a toy experiment comparing five simple networks on the CIFAR-100 dataset with different early stopping settings. Since the convergence of models with fewer parameters and lower computational complexity is usually faster, the early stopping results in the entire search space are biased. In addition, a consensus was recently reached~\cite{sciuto2019evaluating,li2019random,yang2019evaluation} that random searching sometimes performs better than objective function-oriented NAS methods, also suggesting that the NAS evaluation procedure requires further refinement. In this paper, we present a divide-and-conquer NAS (DC-NAS) scheme to better evaluate and handle the huge search space of neural architectures. In doing so, we highlight that the unified early stopping strategy for evaluating all networks sampled from the entire search space is unreliable, since the networks all have different numbers of parameters and computational power. We first observe the gradient change of each network's layers and operations and cluster them into several categories using the conventional k-means algorithm. Then, network comparisons are conducted in the same cluster by exploiting the usual early stopping strategy. Optimal networks in each cluster are finally merged and carefully trained to derive the best neural architecture in the given search space. The DC-NAS pipeline is shown in Figure~\ref{Fig:pipeline}. Since the gradient change can be directly calculated from the super-network with only limited cost and the k-means approach is also very efficient, DC-NAS does not obviously increase searching costs. Our extensive experimental results show that the proposed method can effectively solve the inaccurate evaluation problem and more efficiently perform NAS. Compared to state-of-the-art approaches, DC-NAS finds better performing networks in the same search space. \section{Related Works} To solve the problem of inaccurate evaluation of different networks, this work aims to divide the complex NAS problem into several sub-problems and obtain the optimal architecture by merging their results. Current NAS algorithms can be divided into two evaluation approaches: the early stopping strategy for evaluation and predictor based architecture searching. \subsection{Early Stopping in NAS} In order to automatically design high-performance deep neural networks, a series of algorithms have been proposed to search neural architectures in a given search space. Zoph~\emph{et.al.}~\cite{zoph2016neural} first proposed the concept of large-scale image classifier searching, which encoded different operations (\emph{e.g. }, convolution and pooling) and RNN connections to search for effective architectures using reinforcement learning (RL) by treating the accuracy of the current architecture as a reward and selecting policies to obtain the new architecture. Real~\emph{et.al.}~\cite{real2019regularized} proposed an evolutionary-based algorithm (EA) to search the architectures. Specifically, each individual neural network was regarded as an architectural component. Searching was performed across generations by using mutations and re-combinations of architectural components, with components showing better performance on the validation set picked and inherited by the next generation during evolution. Pham~\emph{et.al.}~\cite{pham2018efficient} developed efficient-NAS (ENAS), which significantly reduced the search cost by training a large computational graph and searching for an optimal subgraph that maximized the expected reward on a validation set using the weight-sharing method. Note that the reward used in RL and component performance in EA require training a large number of neural networks to convergence, which makes the search cost expensive. Thus, the early stopping strategy is commonly used to reduce the search cost, which trains the neural network over only a few epochs and uses the intermediate accuracy as the surrogate reward or performance of the component. Early stopping is a very effective method for quickly evaluating or predicting the intermediate neural architectures during searches. However, effectiveness is compromised, since for different architectures, the relationship between the intermediate accuracy and the final accuracy is unclear. Specifically, taking different networks sampled from the entire search space and applying the same early stopping strategy is ineffective, since networks with more learnable parameters are usually harder to optimize. In addition to the EA-based~\cite{yang2019cars} and RL-based NAS methods with early stopping, differentiable neural architecture searching (\emph{e.g. }, DARTS~\cite{liu2018darts}, Hit-Detector~\cite{guo2020hit}) also provides an efficient way to search deep neural networks. DARTS regarded the given super network as a continuous space and simultaneously maintained two sets of parameters with respect to the weights of the desired network and the weights for selecting different operations between nodes. SNAS~\cite{xie2018snas} replaced the feedback mechanism triggered by constant rewards with gradient feedback from a generic loss. FBNet~\cite{wu2019fbnet} proposed a hardware-aware efficient conv-net designing method by integrating the network architecture latency into the loss function. Differentiable NAS algorithms significantly increase the search speed by sharing weights across all sub-networks. However, determining the importance of each layer during the search is difficult. In other words, the parameter optimization results for the searched architectures are unreliable. \subsection{Network Performance Predictor} To avoid expensive search costs, a series of predictor-based methods have been proposed that better predict the latter part of the learning curve given the former part. For example, Domhan~\emph{et.al.}~\cite{domhan2015speeding} extrapolated network architecture performance from the first part of a learning curve by mimicking the early termination of bad runs using a probabilistic model. Klein~\emph{et.al.}~\cite{klein2016learning} studied the use of Bayesian neural networks to improve performance with a specialized learning curve layer. Swersky~\emph{et.al.}~\cite{swersky2014freeze} assumed that the training loss during the fitting procedure roughly followed an exponential decay towards an unknown final value and proposed a regression model based on Bayesian optimization. Baker~\emph{et.al.}~\cite{baker2017accelerating} proposed a sequential regression model to predict the validation accuracy using features based on network architectures, hyper-parameters, and time-series validation performance data. However, good performance relies on the assumption that the learning curve should be smooth, which is often not the case in reality, since the learning curve may abruptly change when the learning rate changes. Some other predictors try to directly predict architecture performance before training~\cite{tang2020semi}. Deng~\emph{et.al.}~\cite{deng2017peephole} proposed using long short-term memory (LSTM) to predict the performance of a given architecture. Specifically, each layer of the architecture was embedded into a feature vector according to some predefined rules, and the vectors were then concatenated to produce the LSTM input. Sun~\emph{et.al.}~\cite{sun2019surrogate} encoded the network architecture by assuming that it is consisted of ResNet block and DenseNet block, extracted features based on it, and then predicted the accuracy with random forests. Xu~\emph{et.al.}~\cite{xu2019renasrelativistic} argued that the rankings between different models were much more important than absolute performance, and proposed a predictor based on a pairwise ranking-based loss function. Although a well-trained neural architecture predictor can replace the early stopping approach and avoid the mixed evaluation problem, collecting the ground-truth labels (\emph{i.e. }, the exact network performance) to train the predictor is very expensive. Moreover, the predictor is sensitive to the number of training networks and the sampling strategy. Thus, NAS urgently requires an effective and accurate approach for comparing different searched architectures. \section{Divide-and-conquer Searching} We first revisit the evaluation of different sampled neural architectures in NAS, which is the main reason that some excellent architectures cannot be maintained during the search. Then, we develop divide-and-conquer NAS method. The original search space will be split to several clusters according to sub-network similarity. \subsection{Evaluation Problem in NAS} NAS represents a series of well-design approaches for obtaining the optimal neural architecture for the target task and related dataset from a huge search space. For a given search space $\mathcal S$ containing $p$ different neural architectures, \emph{i.e. }, $\mathcal{S} = \{\mathcal{N}_1,...,\mathcal{N}_p\}$, where $\mathcal N_i$ is the $i$-th sampled architecture from $\mathcal S$, each architecture is composed of a number of neural operations proven to be useful for deep learning (\emph{e.g. }, convolution, pooling, short-cuts, \emph{etc}.). Denoting the target dataset $\mathbf{D}$, the performance of each neural architecture can be calculated as \begin{equation} y_i = T(\mathcal{N}_i,\mathbf{D}), \end{equation} where $y_i$ is the accuracy of $\mathcal{N}_i$ on the test set and $T(\cdot)$ is the training function, which is tuned for the sampled network from $S$. In general, the training of a modern deep neural architecture is an intensive process (\emph{e.g. }, over eight GPU*days on ImageNet to train only one sub-network), and a large number of sub-networks exist in the search space. Evaluating all of these architectures individually is almost impossible. Thus, most NAS algorithms adopt an early stopping approach on a reduced dataset to evaluate each sub-network, \emph{i.e. }, \begin{equation} E(\mathcal{N}_i) = \tilde T(\mathcal{N}_i,\tilde{\mathbf{D}}), \label{Fcn:early} \end{equation} where $\tilde T(\cdot)$ is the training function with the early stopping strategy and $\tilde{\mathbf{D}}$ is the smaller dataset containing $\sigma$ (\emph{e.g. }, $5\%$) of the original training dataset to promote efficiency. Although Eq.~\ref{Fcn:early} can significantly reduce the time taken to evaluate the searched networks, it is very hard to construct a smaller dataset and training method to satisfy the following objective function: \begin{equation} \min_E\frac{1}{p}\sum_{i=1}^p||E(\mathcal{N}_i)-y_i||_2^2, \end{equation} where $||\cdot||_2$ is the conventional $\ell_2$-norm. This is because deep neural networks are highly complex and hard to train on large-scale datasets, and there is no ranking-preserving relationship between early stopping performance and the final ground-truth accuracy of an arbitrary neural network. It is in fact unnecessary to predict the exact accuracy (or ground-truth accuracy) of the searched networks. If the order of all sub-networks can be preserved, the evaluation function $E(\cdot)$ can also accurately help us to identify networks with better performance, significantly improving NAS efficiency. Therefore, the objective function for optimizing the evaluating function can be written as \begin{equation} \min_E\sum_{i=1}^p\sum_{j=i+1}^p \text{sgn}(y_j-y_i)\times\text{sgn}(E(\mathcal{N}_i)-E(\mathcal{N}_j)), \label{Fcn:obj} \end{equation} where $\text{sgn}(\cdot)$ is the sign function. Then, our goal is to find an efficient evaluator $E(\cdot)$ and embed it into mainstream NAS algorithms. Figure~\ref{Fig:Intro} shows that applying the same early stopping strategy to all networks cannot achieve the desired functionality, because the optimization routes of the various networks are different. For instance, some light-weight neural networks will first achieve a relatively high accuracy but their subsequent improvements are not obvious. However, if some neural networks have very close representations, their convergence statuses are similar. Therefore, the global early stopping strategy is unsuitable for constructing $E(\cdot)$. \subsection{Architecture Clustering} As discussed in Eq.~\ref{Fcn:obj}, an ideal evaluation function is defined to compare different network architectures during the search. In fact, Eq.~\ref{Fcn:obj} can also be regarded as a predictive problem, with some existing works addressing this~\cite{deng2017peephole,sun2019surrogate,xu2019renasrelativistic}. However, these methods require a certain number of fully-trained networks sampled from the given search space to construct the performance predictor, which is also very resource intensive. Handling the performance comparison task using a universal early stopping strategy is unreliable; nevertheless, early stopping is still the cheapest way to compare a set of architectures without too many differences. Therefore, we propose to conduct NAS in a divide-and-conquer manner to reduce the difficulty in comparing various architectures during the search. In practice, we divide all the sub-networks in the given search space $\mathcal{S}$ into $K$ categories using $K$ cluster centers to form $K$ different groups, \emph{i.e. }, $\mathbf{G}=\{\mathbf{G}_1,...,\mathbf{G}_K\}$. The corresponding objective function can be written as \begin{equation} \arg\min_{\mathbf{G}} \sum_{k=1}^K\sum_{\mathcal{N}\in\mathcal{G}_k} ||F(\mathcal{N})-F(\tilde{\mathcal{N}}_k)||_2^2, \label{Fcn:arc_cl} \end{equation} where $\tilde{\mathcal{N}}_k$ denotes the $k$-th clustering center of group $\mathbf{G}_k$, and $F(\cdot)$ is the feature representation of each input deep neural architecture. Establishing the relationship between deep neural architectures and their performance is difficult, and how to represent deep networks is also extremely complicated due to the various structures and billions of trainable parameters. Fortunately, the current mainstream search space is often regularized to a super-network~\cite{liu2018darts,xie2018snas,wu2019fbnet}, \emph{i.e. }, the depths and types of connections are usually fixed, and all the operations needing to be searched are merged in it. Thus, we suggest representing each sampled network from the given search space $\mathcal{S}$ using a code with fixed length $L$, \emph{i.e. }, the number of layers. One straightforward way to represent neural architectures is to regard the operations in each layer (\emph{e.g. }, ``conv'' and ``ReLU''~\cite{deng2017peephole,sun2019surrogate}) or computational complexity (\emph{i.e. }, FLOPS and memory~\cite{xu2019renasrelativistic,istrate2019tapas}) as neural architecture features. However, directly using these features does not capture the relationship between any two layers and operations, and the computational complexity cannot be computed for some parameter-free layers, \emph{e.g. }, pooling and short-cut layers. In addition, the phenomenon shown in Figure~\ref{Fig:Intro} motivates us to encode the optimization difficulty of different neural architectures. Therefore, given $L$ as the number of layers in the neural architectures and $\eta$ as the maximum epochs trained on the training set, we propose using the following representation function to encode an arbitrary network $\mathcal{N}_i$ into an $(L\times\eta)$-dimensional matrix, \emph{i.e. }, \begin{equation} \hat F_{l,e}(\mathcal{N}_{i})=\frac{<{\theta_{i}^{l,1}}, {\theta}_{i}^{l,e}>}{||\theta_{i}^{l,1}||\cdot||{\theta}_{i}^{l,e}||}, \label{Fcn:pfeat} \end{equation} where $\theta_{i}^{l,e}$ are the parameters in the $l$-th layer in network $N_i$ trained on the reduced training set $\tilde{\mathbf{D}}$ after $e$ epochs. The above function calculates the changes in parameters of a given network between the first and the $e$-th epochs, which can reflect the sensitivity of each layer in the sampled network. For instance, a layer with fewer parameters will converge faster than another layer with more parameters due to the different optimization difficulty, as shown in Figure~\ref{Fig:Intro}. Thus, we can use these features to distinguish neural architectures with different properties and divide the huge search space $\mathcal{S}$ accordingly. However, Eq.~\ref{Fcn:pfeat} also faces the same problem of not being able to represent some layers (such as pooling and short-cut) without trainable parameters. Thus, we further extend it to the output of each layer as the feature representation of a given neural network, \emph{i.e. }, \begin{equation} F_{l,e}(\mathcal{N}_{i})=\frac{<{o_{i}^{l,1}}, {o}_{i}^{l,e}>}{||o_{i}^{l,1}||\cdot||{o}_{i}^{l,e}||}, \label{Fcn:feat} \end{equation} where $o_{i}^{l,e}$ is the averaged output feature of the $l$-th layer in network $\mathcal{N}_{i}$ for a certain amount of data trained on $\tilde{\mathbf{D}}$ with $e$ epochs. To save the calculation of Eq.~\ref{Fcn:feat} and balance the information of each dimensionality, we further apply a global average pooling on the feature representation ${o}$ of each layer before calculating $F$. Then, we can utilize conventional k-means clustering or hierarchical clustering ~\cite{yaari1997segmentation,alsabti1997efficient} to divide the original search space into $K$ clusters according to the feature similarity between any two sampled neural architectures. \begin{algorithm}[t] \renewcommand\baselinestretch{1.1}\selectfont \caption{DC-NAS for Searching Neural Architectures.} \label{Alg:main} \begin{algorithmic}[1] \Require An arbitrary search space $\mathcal{S}$ containing $p$ sub-networks $\{\mathcal{N}_1,...,\mathcal{N}_p\}$ with $L$ layers. The target dataset $\mathbf{D}$ and it's shrunk version $\tilde{\mathbf{D}}$, the clustering number $K$, the number of epochs $\eta$ for extracting feature representations, and the number of sampled networks $s\leq p$. \State \textbf{Search Space Clustering:} \State Randomly generate $s$ neural architectures from $\mathcal{S}$; \For{$i = 1$ to $s$} \State Initialized the parameters in $\mathcal{N}_i$; \State Train the network $\mathcal{N}_i$ on $\tilde{\mathbf{D}}$ with $\eta$ epochs; \For{$l = 1$ to $L$} \For{$e = 1$ to $\eta$} \State Obtain features $o_{i}^{l,e}$ of the $l$-th layer after training $e$ epochs; \State Calculate $F_{l,e}(\mathcal{N}_{i})$ using Eq.~\ref{Fcn:feat}; \EndFor \EndFor \EndFor \State Cluster $s$ networks into $K$ groups $\{\mathcal{G}_1,...,\mathcal{G}_K\}$ using Eq.~\ref{Fcn:arc_cl}; \State \textbf{Merging Architectures:} \For{$i = 1$ to $K$} \State Find the best architecture $\hat{\mathcal{N}}_i$ in $\mathcal{G}_i$ using the conventional early stopping (Eq.~\ref{Fcn:res1} for architectures trained separately, Eq.~\ref{Fcn:res3} for architectures sampled from a super network); \EndFor \Ensure The optimal network $\mathcal{N}^*$ among the $K$ groups. \end{algorithmic} \end{algorithm} \subsection{Divide-and-conquer Network Comparison} After obtaining $K$ deep neural architecture clusters, the evaluation difficulty is naturally reduced, since each cluster represents deep models with similar optimization paths and performance. Therefore, we propose to first distinguish the best architecture in each group and then merge them to produce the final result. For architectures in the same cluster, we can reuse the conventional early stopping strategy to distinguish searched architectures in the same cluster with similar gradient changes. Therefore, for $K$ clusters, the $K$ optimal architecture can easily be solved by using \begin{equation} \hat{\mathcal{N}}_k = \mathop{\arg\max}_{\mathcal{N}\in\mathcal{G}_k}E(\mathcal{N}) = \mathop{\arg\max}_{\mathcal{N}\in\mathcal{G}_k}\tilde T(\mathcal{N},\tilde{\mathbf{D}}), \label{Fcn:res1} \end{equation} where $\hat{\mathcal{N}}_k$ is the best network architecture in the $k$-th group selected by the reduced dataset $\tilde{\mathbf{D}}$. Eq.\ref{Fcn:res1} is suitable when evaluating different neural networks that have been trained separately. However, for the sub-networks extracted from the pre-trained super network, the performance of each sub-network without further training is usually poor and might not represent its true fitting ability. Note that in a given pre-trained super-network, the operation parameters in each layer give the probabilities of choosing different operations in that layer. Thus, we use the sub-network with the largest probability of being chosen in a cluster as the representation of this cluster. Given ${ a(\mathcal N)}=\{a(\mathcal N^1),a(\mathcal N^2),\cdot\cdot\cdot,a(\mathcal N^L)\}$ as the operation probability parameters of each layer in a sub-network $\mathcal N$, we have: \begin{equation} \hat{\mathcal{N}}_k = \mathop{\arg\max}_{\mathcal{N}\in\mathcal{G}_k}\sum_{l=1}^L{a(\mathcal N^l)}, \label{Fcn:res3} \end{equation} Then, the optimal neural architecture in the given search space $\mathcal{S}$ can be easily derived using the following function: \begin{equation} \mathcal{N}^* = \mathop{\arg\max}_{\hat{\mathcal{N}}_i}T(\hat{\mathcal{N}}_i,\mathbf{D}), \quad \forall\;\; i = 1,...K, \label{Fcn:res2} \end{equation} where, the performance of each network selected in the specific cluster will be derived by fully training them on entire dataset $\mathbf{D}$ for an accurate comparison. Note that although the training procedure on $\mathbf{D}$ is somewhat expensive, the number of clusters $K$ is relatively small and Eq.~\ref{Fcn:res2} does not dominate our scheme. The detailed searching procedure of DC-NAS for accurately searching neural architectures is summarized in Algorithm~\ref{Alg:main}. \section{Experiments} We have therefore developed a novel NAS framework using the divide-and-conquer approach, splitting the huge search space into several groups to reduce the difficulty in evaluating the searched neural architectures. Here we verify the effectiveness of the proposed method on several NAS search spaces. \subsection{Validations on Toy Search Space} \paragraph{\textbf{Search Space Definition.}} We first validate the proposed method using a very simple search space, as shown in Figure~\ref{Fig:Intro}. The baseline network includes six convolutional layers and a fully-connected layer. We extend this baseline network by adjusting the channel ratio in different layers, \emph{i.e. }, $\frac{1}{4}$, $\frac{1}{2}$, $1$, $2$, $4$. Thus, the entire search space contains $5^6 = 15625$ neural architectures with different parameters and computational complexity. CIFAR-100~\cite{krizhevsky2009learning} is selected as the target dataset. Since the search space is relatively small, we first train all of these networks on $10\%$ of CIFAR-100, \emph{i.e. }, $\tilde{\mathbf{D}}$ in Eq.~\ref{Fcn:early}. The number of epochs used in the original baseline network is 200. For efficiency, these architectures are trained separately for 20 epochs. Then, all the images in the smaller training dataset $\bf\tilde D$ are used to extract the feature representations of each layer of these architectures after training different epochs. \paragraph{\textbf{Architecture Clustering and Searching.}} After obtaining the features of these neural architectures, we obtain a feature tensor $\mathcal T\in \mathbb R^{s\times L\times\eta}$ in which $L=6$. Specifically, we set $s=15625$ and $\eta\in\{5,10,20,30\}$. Then, we apply the k-means algorithm on this matrix to generate a series of architecture groups. After that, we evaluate each network cluster using Eq.\ref{Fcn:res1}, and $K$ selected networks will be fully trained on the entire training dataset $\bf D$ to obtain the final result, \emph{i.e. }, the optimal architecture in the given search space. \renewcommand{\multirowsetup}{\centering} \begin{table*}[t] \begin{center} \renewcommand\arraystretch{1.0} \caption{Searched results of DC-NAS with different clustering number $K$ and evaluating epochs $\eta$ on the toy search space.} \begin{tabular}{l|c|c|c|c|c|c} \hline DC-NAS & $K = 1$ & $K = 3$ & $K = 5$ & $K = 10$ & $K = 20$ &$K = 50$ \\ \hline\hline Top-1 acc(\%) (RS) & 75.01 & 75.36 & 75.49 & 75.58 & 75.71 & 75.83\\ \hline Top-1 acc(\%) ($\eta = 5$) & 71.74 & 73.96 & 73.96& 73.96& 75.38& 75.47 \\ \hline Top-1 acc(\%) ($\eta = 10$) & 71.13 & 75.42 & 75.42& 75.42& 75.83& 75.83\\ \hline Top-1 acc(\%) ($\eta = 20$) & 73.32 & 75.91 & 75.91 &75.91 & 75.91&76.07\\ \hline Top-1 acc(\%) ($\eta = 30$) & 74.07 & 75.91 & 75.91 &75.91 & 75.91&76.07\\ \hline \end{tabular} \label{Tab:kmeans} \end{center} \end{table*} In Table~\ref{Tab:kmeans}, we test the impact of parameter $K\in\{1,3,5,10,20,50\}$ in dividing the search space according to the feature representations of the architectures. We also examine the impact of parameter $\eta$ ranging from $\{5,10,20,30\}$. When $K=1$, DC-NAS is equivalent to the conventional early stopping strategy for evaluating searched neural architectures, which is used in almost all NAS algorithms. An increasing $K$ is more likely to obtain the global optimum of the search space, while increasing the evaluation time. When $K=15625$, the proposed method degrades to a traversal search in which the global optimum is guaranteed, but the evaluation time is unaffordable. We further compare the effectiveness of the proposed method with random search (RS). Note that we have trained $s=15625$ different architectures on $10\%$ of the original dataset with $10\%$ of the original epochs. Thus, for a given parameter $K$, the RS method randomly selects $156+K$ different neural architectures from the search space, and the architectures are fully trained to obtain the validation result. The architecture with the best validation result is selected, and this experiment is repeated $20$ times to overcome randomness. As shown in Table~\ref{Tab:kmeans}, the best search results are achieved when $\eta=30$, which is slightly higher than that of $\eta=20$ only when $K=1$. On the one hand, a larger $\eta$ indicates a higher dimension of the feature representation which increases the amount of information to help generate better clusters. On the other, a larger $\eta$ alleviates the randomness of the feature representation, and the feature can more precisely represent the degree of convergence of the layer. However, a larger $\eta$ will also increase the search cost of the proposed DC-NAS algorithm, and the architecture search problem is exactly a method of exhaustion when $\eta \rightarrow \inf$. Thus, we suggest to set $\eta = 20$ (\emph{i.e. }, $10\%$ of the epochs for fully training) for a trade-off between the performance of neural architecture and search cost. \begin{figure*}[t] \centering \subfloat[K=1]{ \begin{minipage}[t]{0.28\linewidth} \centering \includegraphics[width=0.63\linewidth]{figs/cluster_1.png} \end{minipage} } \centering \subfloat[K=3]{ \begin{minipage}[t]{0.56\linewidth} \centering \includegraphics[width=0.99\linewidth]{figs/cluster_3.png} \end{minipage} } \centering \subfloat[K=5]{ \begin{minipage}[t]{0.84\linewidth} \centering \includegraphics[width=1\linewidth]{figs/cluster_5.png} \end{minipage} } \caption{Visualization of the best deep neural architectures in each cluster with $K=1$, $K=3$ and $K=5$, respectively.} \label{figure_4} \end{figure*} Moreover, $K$ is also a very important parameter in our method. When $K=1$, the random search method achieves the best result, which means that the conventional early stopping method is not comparable to RS. However, the proposed method delivers significant gains even with a small cluster number ($K=3$), improving the search result from $73.32\%$ to $75.91\%$ and outperforming the RS method. This shows that DC-NAS can achieve a promising local optimum with only a slightly increase in the evaluation cost. We found that all the selected networks $\{\hat{\mathcal N}_k\}_{k=1}^K$ with a smaller $K$ also appear when $K$ increases as shown in Figure~\ref{figure_4}. The best network searched using $K=5$ includes the results using $K=3$, which demonstrates that the performance of the searched architecture will not decrease when $K$ becomes larger. In addition, we also find that a larger $K$ will not obviously enhance the accuracy of the searched network, since the number good candidates with sufficient discrimination \emph{w.r.t. } the number of intrinsic clusters is limited, and we keep $K=5$ in the following experiments. In order to explicitly understand the architecture clustering procedure, we detail the selected networks in each cluster using intra-cluster early stopping with $K = 5$ and $\eta=20$ (Table~\ref{Tab:resp}). Meanwhile, the searched architectures using different $K$ are also drawn in Figure~\ref{Fig:Intro}, selected networks in different clusters present variant architectures. Revising Figure~\ref{Fig:Intro}, for the given search space, the conventional early stopping method will search for the architecture with a small channel ratio, \emph{i.e. }, network architectures with few parameters and FLOPs, since a smaller network will converge faster on reduced dataset $\bf\tilde D$ at the beginning of training, thus outperforming larger networks with better ground-truth performance when applying the early stopping strategy. However, in Table~\ref{Tab:resp}, we show that there is an approximately $6$-times difference in the parameters and FLOPs between the largest and smallest models selected by DC-NAS, demonstrating that the proposed method can effectively solve the problem shown in Figure~\ref{Fig:Intro}. Furthermore, it can be found in Table~\ref{Tab:resp}, $\tilde{N}_3$ is about $1.87\times$ larger than $\tilde{N}_2$ with a slightly lower performance. This result illustrates that a larger model does not necessarily have higher accuracy. Overall, the proposed DC-NAS can distinguish models with different optimization difficulties and accurately evaluate them to obtain better architectures. \begin{table}[t] \begin{center} \renewcommand\arraystretch{1.2} \caption{Optimal architectures in each cluster when $K = 5$.} \begin{tabular}{c|c|c|c|c} \hline Network & Channel Ratio & Param & FLOPs & acc(\%) \\ \hline\hline $\tilde{N}_2$ & $4,2,1,2,0.25,2$ & 4.30M & 0.46G & 73.64\\ \hline $\tilde{N}_1$ & $2,2,1,4,0.5,0.5$ & 4.76M & 0.61G & 73.50\\ \hline $\tilde{N}_4$ & $2,4,4,2,0.25,1$ & 5.69M & 1.14G & 73.60\\ \hline $\tilde{N}_3$ & $2,4,1,0.5,4,0.5$ & 8.08M & 0.72G & 73.32\\ \hline $\tilde{N}_5$ & $2,4,4,2,4,1$ & 23.38M & 2.27G & 75.91 \\ \hline \end{tabular} \label{Tab:resp} \vspace{-1.5em} \end{center} \end{table} In addition, we sometimes need to sample some examples from the smaller dataset $\bf \tilde D$ in order to reduce the time taken to compute the averaged output feature of a specific layer in a given network (Eq.~\ref{Fcn:feat}). In order to verify the sensitivity of the proposed method in choosing different examples for extracting features, we repeat the search $10$ times with $K = 5$ and $\eta = 20$, each time randomly sampling 1000 images from the reduced training dataset $\bf \tilde D$ accordingly. The largest gap between the accuracy of the best and worst searched network is only about $0.2\%$, showing that the feature representation generation method utilized in Eq.~\ref{Fcn:feat} is very robust for distinguishing sub-networks in the given search space. \begin{table*}[t] \begin{center} \small \renewcommand\arraystretch{1.0} \caption{Searched results of DC-NAS and state-of-the-art methods on ImageNet.} \vspace{-0.5em} \begin{tabular}{c|cc|ccc|cc} \hline \multirow{2}{*}{Method} & Search & Search & Latency & FLOPs & Params&Top-1 & Top-5 \\ & methods & space & (ms) & (M) & (M) & acc(\%) & acc(\%)\\ \hline\hline Random Search &-&-&-&276&4.3&72.0&90.6\\ MobileNetV1~\cite{howard2017mobilenets} &handcraft & - & -&- & 4.2 & 70.6 & 89.5 \\ MobileNetV2 1.0$\times$~\cite{sandler2018mobilenetv2} & handcraft &- &-& 300 & 3.4 & 72.0 & 91.0\\ ShuffleNetV1 1.5$\times$ (g=3)~\cite{zhang2018shufflenet} & handcraft & &-& 292 & - & 71.5 & -\\ ShuffleNetV2 1.5$\times$~\cite{ma2018shufflenet} & handcraft & -&-& 299 & 3.5 & 72.6 & - \\ MobileNetV2 1.4$\times$~\cite{sandler2018mobilenetv2} & handcraft &-& -& 585 & 6.9 & 74.7 & - \\ ShuffleNetV2 2.0$\times$~\cite{ma2018shufflenet} & handcraft & -&- & 591 & 7.4 & 74.9 & - \\ \hline ChamNet-B~\cite{dai2019chamnet} & predictor & layer-wise &-& 323 & - & 73.8 & -\\ NASNet-A~\cite{zoph2018learning} & RL & cell &-& 564 & 5.3 & 74.0 & - \\ MnasNet~\cite{tan2019mnasnet} & RL & stage-wise & -&317 & 4.5 & 74.0 & -\\ FBNet-B~\cite{wu2019fbnet} & gradient & layer-wise & 87.07&295 & 4.5 & 74.1 & - \\ FBNet-B (our impl.) & gradient & layer-wise & 104.25& 326 & 4.7 & 73.7 & 91.5 \\ ProxylessNAS-R~\cite{cai2018proxylessnas} & gradient & layer-wise &-& -& 5.8 & 74.6 & 92.2\\ MnasNet-92~\cite{tan2019mnasnet} & RL & stage-wise& -&388 & 4.4 & 74.8 & -\\ FBNet-C~\cite{wu2019fbnet} & gradient & layer-wise &102.83& 375 & 5.5 & 74.9 & - \\ FBNet-C (our impl.) & gradient & layer-wise &116.55& 406 & 5.5 & 74.8 & 92.1 \\ \hline DC-NAS-A & & \multirow{5}{*}{layer-wise} & 117.89 &319 & 4.7 & 73.4& 91.5\\ DC-NAS-B & gradient & & 84.19 &328 & 4.9 & 73.7& 91.5\\ DC-NAS-C & + & & 104.10&341 & 5.0 & 74.2& 91.6\\ DC-NAS-D & cluster & & 103.39&369 & 4.9 & 74.7& 92.1\\ DC-NAS-E & & & 118.12&428 & 5.5 & \textbf{75.1}& \textbf{92.2}\\ \hline \end{tabular} \label{Tab:imgnet} \end{center} \end{table*} \subsection{Validations on ImageNet} After conducting experiments on CIFAR-100 data and analyzing the impact of each parameters in the proposed DC-NAS, we further employ the new method on the challenging large-scale ImageNet dataset~\cite{ImageNet}. This dataset contains over 1.2M images from 1000 categories. FBNet~\cite{wu2019fbnet} is selected as the baseline method because of the excellent performance on both model accuracy and latency. \paragraph{\textbf{Search Space Definition.}} We use the same search space proposed in FBNet~\cite{wu2019fbnet}, which is a layer-wise search space with a fixed super-network. The super-network architecture is composed of a $3\times3$ convolution layer, followed by seven SB blocks, a $1\times1$ convolution layer, a $7\times7$ average pooling layer and a fully-connected layer. Here SB block is the block that needs to be searched. Specifically, the block structure is fixed as a $1\times1$ convolution followed by a $k\times k$ depthwise convolution and another $1\times1$ convolution. ReLU activation is used after each layer, except for the last $1\times1$ convolution. When the stride of the block $s=2$, the stride of the first $1\times1$ convolution is 2. When $s=1$, a skip connection is added between the input and the output of the block. When searching for the SB block, the expansion ratio $e$, which determines the channel size expansion from input to output of the first $1\times1$ convolution, can be searched from $e\in\{1,3,6\}$, and the kernel size $k$ of the depthwise convolution is $k\in\{3,5\}$. Furthermore, the group convolution followed by a channel shuffle operation can be used in the first and last $1\times1$ convolutions. Finally, a skip operation can be applied to the SB block, which actually cancels the block and reduces the architecture depth. There are $9$ different candidate operations forming a search space of size $9^{22}$. \paragraph{\textbf{Results on ImageNet.}} Following~\cite{wu2019fbnet}, we first train the super-network on ImageNet-100 with 90 epochs. The first 10 epochs are trained with fixed operation parameters and the next 80 epochs are trained normally. In each epoch, the operator weight $w$ is first trained on $80\%$ of ImageNet-100 using SGD, and the probability parameters $a$ are trained on the remaining $20\%$ of the training set using Adam with an initial learning rate of 0.01 and weight decay of 0.0005. We then sample $10^7$ different architectures from the search space according to the operation probability of the pre-trained super-network. Specifically, we normalize the probabilities of the operations in the same layer, and then select operation of that layer based on the normalized probability. After that, we extract features using Eq.~\ref{Fcn:feat} with $10000$ images sampled from the ImageNet-100 training set. Finally, the feature representations of $10^7$ different samples are clustered into $K$ different groups using the k-means algorithm, and the representative sub-network from each group is selected using Eq.~\ref{Fcn:res3}. Considering the evaluation cost, we manually set a small cluster number $K=5$ in our experiment. When increasing $K$ to a larger number (\emph{e.g. }, $K=10$), we do not discover a significant increase of the search result. The five representative sub-networks are fully trained on ImageNet, and the search results are shown in Table~\ref{Tab:imgnet}, \emph{i.e. }, DC-NAS-A to DC-NAS-E. \paragraph{\textbf{Compare to state-of-the-art methods.}} The results of the proposed DC-NAS are compared to state-of-the-art models designed manually and automatically. The evaluation metrics are top-1/top-5 accuracies on the ImageNet validation set, and FLOPs and parameters of the searched models. During the experiment, we found that the results of FBNet~\cite{wu2019fbnet} reported in the original paper is different from the results that is implemented by ourselves, which was also pointed out in ~\cite{stamoulis2019single}. Thus, we report both the evaluation metrics of the searched results mentioned in the original paper and the results implemented by us (denote as `our impl.'). Table~\ref{Tab:imgnet} shows that our DC-NAS achieves a top-1 accuracy of \textbf{$75.1\%$}, which is a new stat-of-the-art ImageNet accuracy among hardware-efficient NAS models. Meanwhile, we also compare the proposed DC-NAS with a number of state-of-the-art methods including NASNet~\cite{zoph2018learning}, MnasNet~\cite{tan2019mnasnet}, ProxylessNAS~\cite{cai2018proxylessnas}, \emph{etc}. The comparison results shown in Table~\ref{Tab:imgnet} also demonstrate that the proposed DC-NAS outperforms other methods under the same range of FLOPs. \paragraph{\textbf{Search cost.}} The training process of super-net is exactly the same as in FBNet~\cite{wu2019fbnet}, which is 216 GPU hours. In this experiment, we do not need to adjust the hyper-parameter $\eta$. Extract features of $10^7$ different architectures using Eq.~\ref{Fcn:res3} takes about 15 GPU hours. Finally, clustering architectures into different groups by applying k-means on the extracted features can be done in a few minutes. Thus, the total search cost of DC-NAS is 231 GPU hours, which is $1.07\times$ compared to that of the baseline FBNet~\cite{wu2019fbnet}. In addition, it is easy to embed the proposed divide-and-conquer strategy into other frameworks to obtain better performance. \paragraph{\textbf{Latency.}} Besides the FLOPS and model sizes, we also report the latency of different model on an ARM based mobile device for a fair comparison. The latency of the DC-NAS-E with the highest performance for predicting a $224\times 224$ image is $118.12ms$, which is very close to that ($116.55ms$) of the FBNet-C. At the same time, we can find from Table~\ref{Tab:imgnet}, the latency of a neural network is not linearly related to FLOPS and model size. Thus, the hardware-aware strategy is essential for neural architecture search. Overall, the proposed DC-NAS can provide networks with the state-of-the-art performance on the given search space. \section{Conclusions} In this paper we present a divide-and-conquer neural architecture search (DC-NAS) approach for effectively searching deep neural architectures. The proposed method overcomes the evaluation problem inherent in traditional NAS methods, namely they choose architectures that perform well on smaller datasets using the early stopping strategy while rejecting architectures that are actually acceptable after full training. Specifically, DC-NAS first extracts features that represent the speed of convergence of sub-networks according to the change in output features of each layer after each training epoch. It then calculates the similarity between two different architectures according to the feature representations. After that, traditional k-means clustering is used to divide the huge search space into several groups, and the best architectures in each group are further compared to obtain the best searched architecture. Our experimental results show that the proposed DC-NAS can significantly improve the performance of the searched architecture with only a slightly increase in the evaluation cost compared to traditional NAS methods.
{'timestamp': '2020-06-01T02:08:57', 'yymm': '2005', 'arxiv_id': '2005.14456', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14456'}
arxiv
\section{} \documentclass[10pt]{article} \usepackage{hyperref} \hypersetup{colorlinks=true,linkcolor=black,citecolor=black,urlcolor=black,breaklinks=true} \usepackage{float} \usepackage[symbol]{footmisc} \usepackage[superscript,sort]{cite} \usepackage{array} \usepackage{bm} \usepackage{longtable} \newcolumntype{x}[1]{% >{\centering\hspace{0pt}}p{#1}}% \usepackage[normalem]{ulem} \usepackage{amsmath,amssymb} \newcommand{\textup{\AA}}{\textup{\AA}} \usepackage{amsthm,amscd,amsxtra,amsfonts,amsmath,amssymb,multirow} \usepackage{wrapfig} \usepackage[tiny,compact]{titlesec} \usepackage{threeparttable} \usepackage{helvet} \renewcommand{\familydefault}{\sfdefault} \usepackage{booktabs} \usepackage[table]{xcolor} \usepackage{xcolor,colortbl} \usepackage{placeins} \usepackage{tikz} \usetikzlibrary{shapes,arrows} \usepackage[T1]{fontenc} \usepackage[linesnumbered,ruled]{algorithm2e} \setlength{\oddsidemargin}{-0.2in} \setlength{\textwidth}{6.8in} \setlength{\topmargin}{0.0in} \setlength{\headheight}{0in} \setlength{\headsep}{0in} \setlength{\textheight}{9.0in} \setlength{\footskip}{0.3in} \providecommand{\e}[1]{\ensuremath{\times 10^{#1}}} \setlength{\parindent}{0.15in} \renewcommand\floatpagefraction{.9} \renewcommand\topfraction{.9} \renewcommand\bottomfraction{.9} \renewcommand\textfraction{.1} \setcounter{totalnumber}{50} \setcounter{topnumber}{50} \setcounter{bottomnumber}{50} \setlength{\floatsep}{0.05in} \setlength{\textfloatsep}{0.05in} \setlength{\intextsep}{0.05in} \setlength{\abovecaptionskip}{0.05in} \setlength{\belowcaptionskip}{0.05in} \titlespacing*{\section}{0pt}{*0}{*0} \titlespacing*{\subsection}{0pt}{*0}{*0} \titlespacing*{\subsubsection}{0pt}{*0}{*0} \titlespacing{\paragraph}{0pt}{*0}{*1} \renewcommand{\thefootnote}{\roman{footnote}} \newcommand{\warning}[1]{\footnote{\textcolor{red}{{\textbf{#1}}}}} \newcommand{\inlinewarning}[1]{{\textcolor{red}{{\textbf{#1}}}}} \newcommand{\ntodo}[1]{\footnote{\textcolor{blue}{{\textbf{Nathan to do: #1}}}}} \newcommand{\inlinentodo}[1]{{\textcolor{blue}{{\textbf{Nathan to do: #1}}}}} \definecolor{MyPurple}{rgb}{1,0,1} \newcommand{\gtodo}[1]{\footnote{\textcolor{MyPurple}{{\textbf{Guowei to do: #1}}}}} \newcommand{\inlinegtodo}[1]{{\textcolor{MyPurple}{{\textbf{Guowei to do: #1}}}}} \newcommand{\inlineanswer}[1]{{\textcolor{blue}{{\textbf{Answer: #1}}}}} \newcommand{\answer}[1]{\footnote{\textcolor{blue}{{\textbf{Answer: #1}}}}} \newcommand{\myrevision}[1]{{\marginpar{\Large $\Leftarrow$}}{\textbf{{#1}}}} \newcommand{\myrevisionfig}[1]{{\textbf{{#1}}}} \newcommand{\myparagraph}[1]{{\vskip 5pt \noindent{\bf [{#1}]}}} \renewcommand{\vec}[1]{{\mathbf{{#1}}}} \renewcommand{\thesection}{\Roman{section}} \renewcommand{\thesubsection}{{\thesection}.\Alph{subsection}} \renewcommand{\thesubsubsection}{{\thesubsection}.\arabic{subsubsection}} \newcommand{\norm}[1]{{\left| {#1} \right\|}} \newcommand{\beq}[1]{\begin{equation} \label{#1}} \newcommand{\end{equation}}{\end{equation}} \newcommand{\begin{array}{ll}}{\begin{array}{ll}} \newcommand{\end{array}}{\end{array}} \newcommand{\displaystyle}{\displaystyle} \newcommand{&\!\!\!\disp}{&\!\!\!\displaystyle} \def\S {\S} \usepackage{longtable} \usepackage{threeparttable} \usepackage{array} \newcolumntype{P}[1]{>{\centering\arraybackslash}p{#1}} \usepackage{multirow} \usepackage{color, colortbl} \definecolor{Lightblue}{rgb}{0.867,0.914,0.961} \definecolor{Lightgreen}{rgb}{0.883,0.934,0.848} \DeclareGraphicsExtensions{.pdf,.jpeg,.png} \title{Generative network complex for the automated generation of druglike molecules } \author{Kaifu Gao$^{1}$, Duc Duy Nguyen$^{1}$, Meihua Tu$^{2}$, and Guo-Wei Wei$^{1,3,4,}$\footnote{ Corresponding to Guo-Wei Wei. Email: wei@math.msu.edu}\\ $^1$ Department of Mathematics, Michigan State University, MI 48824, USA.\\ $^2$ Pfizer Medicine Design, 610 Main St, Cambridge, MA 02139, USA.\\ $^3$ Department of Electrical and Computer Engineering, Michigan State University, MI 48824, USA. \\ $^4$ Department of Biochemistry and Molecular Biology, Michigan State University, MI 48824, USA. \\ } \date{\today} \begin{document} \maketitle \begin{abstract} Current drug discovery is expensive and time-consuming. It remains a challenging task to create a wide variety of novel compounds with desirable pharmacological properties and cheaply available to low-income people. In this work, we develop a generative network complex (GNC) to generate new drug-like molecules based on the multi-property optimization via the gradient descent in the latent space of an autoencoder. In our GNC, both multiple chemical properties and similarity scores are optimized to generate and predict drug-like molecules with desired chemical properties. To further validate the reliability of the predictions, these molecules are reevaluated and screened by independent 2D fingerprint-based predictors to come up with a few hundreds of new drug candidates. As a demonstration, we apply our GNC to generate a large number of new BACE1 inhibitors, as well as thousands of novel alternative drug candidates for eight existing market drugs, including Ceritinib, Ribociclib, Acalabrutinib, Idelalisib, Dabrafenib, Macimorelin, Enzalutamide, and Panobinostat. \end{abstract} \section{Introduction} Drug discovery ultimately tests our understanding of molecular biology, medicinal chemistry, genetics, physiology, and pharmacology, the status of biotechnology, the utility of computational sciences, and the maturity of mathematical biology. Technically, drug discovery involves target discovery, lead discovery, lead optimization, preclinical development, three phases of clinical trials, and finally, launching to the market only if a drug can be demonstrated to be safe and effective in every stage. Among them, lead discovery, lead optimization, and preclinical development disqualify tens of thousands of compounds based on their binding affinities, solubility, partition coefficients, clearances, permeability, toxicities, pharmacokinetics, etc., leaving only about tens of them to clinical trials. Therefore, drug discovery is expensive and time-consuming currently: it takes about \$2.6 billion dollars and more than ten years, on average, to bring a new drug to the market \cite{dimasi2016innovation}. Reducing the expense and speeding up the process is one of the top priorities of the pharmaceutical industry. One of the key challenges in small molecule drug discovery is to find novel chemical compounds with desirable properties. Much effort has been taken to optimize this critical step in the drug discovery pipeline. For example, the development of high-throughput screening (HTS) has led to an unprecedented increase in the number of potential targets and leads \cite{hughes2011principles}. HTS can quickly conduct millions of tests to identify active compounds of interest using compound libraries rapidly \cite{macarron2011impact}. While there has been an increase in the number of potential targets and leads, the number of newly generated molecular entities has remained stable because of a high attrition rate by the elimination of leads with inappropriate physicochemical or pharmacological properties during preclinical development and clinical phases \cite{graul2009overcoming,tareq2010predictions}. Rational drug design (RDD) approaches are proposed to better identify candidates with the highest probability of success \cite{waring2015analysis}. These methods aim at finding new medications based on the knowledge of biologically druggable targets \cite{dimasi2016innovation,stromgaard2017textbook}. More recently, computer-aided drug design (CADD) has emerged as a useful approach in reducing the expense and period of drug discovery \cite{alqahtani2017silico}. Computational techniques have been developed for both virtual screening (VS) and optimizing the ADME properties of lead compounds. Primarily, these methods are designed as {\it in silico} filters to eliminate compounds with undesirable properties. These filters are widely applied for the assembly of compound libraries using combinatorial chemistry \cite{balakin2009compound}. The integration of early ADME profiling of lead chemicals has contributed to speeding up lead selection for phase-I trials without large amounts of revenue loss \cite{kapetanovic2008computer}. Currently, compounds are added in libraries based on target-focused design or diversity considerations \cite{huang2016protein}. VS and HTS can screen compound libraries to a subset of compounds whose properties are in agreement with various criteria \cite{szymanski2012adaptation}. Despite these efforts, current databases of chemical compounds remain small when compared with the chemical space spanned by all possible energetically stable stoichiometric combinations of atoms and topologies in molecules. It is estimated that there are about 10$^{60}$ distinct molecules; among them, roughly 10$^{30}$ are drug-like \cite{macarron2011impact}. As a result, computational techniques are also being developed for {\it de novo} design of drug-like molecules \cite{schneider2005computer} and generating large virtual chemical libraries, which can be screened more efficiently for {\it in silico} drug discovery. Among the available computational techniques, deep neural networks (DNN) have gathered much interest for their ability to extract features and learn physical principles from training data. Currently, DNN-based architectures have been successfully applied in a wide variety of fields in the biological and biomedical sciences \cite{min2017deep,mamoshina2016applications}. More interestingly, many deep generative models based on sequence-to-sequence autoencoders (Seq2seq AEs) \cite{sutskever2014sequence}, variational autoencoders (VAEs) \cite{kingma2013auto}, adversarial autoencoders (AAEs) \cite{makhzani2015adversarial}, generative adversarial networks (GANs) \cite{goodfellow2014generative} or reinforcement learning \cite{kaelbling1996reinforcement}, etc. have been proposed for exploring the vast drug-like chemical space and generating new drug-like molecules. Winter {\it et al.} \cite{winter2019efficient,winter2019learning} performed the optimization based on particle swarm optimization on the continuous latent space of a Seq2seq AE to generate new molecules with desired properties. Gomez-Bombarelli {\it et al.} \cite{gomez2018automatic} used a VAE to encode a molecule in the continuous latent space for exploring associated properties. Skalic {\it et al.} \cite{skalic2019shape} combined a conditional VAE and a captioning network to generate previously unseen compounds from input voxelized molecular representations. Kadurin {\it et al.} \cite{kadurin2017drugan} built an AAE to create new compounds. Sattarov {\it et al.} \cite{sattarov2019novo} combined deep autoencoder RNNs with generative topographic mapping to carry out {\it de novo} molecule design. A policy-based reinforcement learning approach was proposed to tune RNNs for episodic tasks \cite{olivecrona2017molecular,popova2018deep}, and extended to design desired molecules \cite{kang2018conditional}. Zhou {\it et al.} \cite{zhou2019optimization} also proposed a strategy to optimize molecules by combining domain knowledge of chemistry and state-of-the-art reinforcement learning techniques. However, the generative strategies mentioned above are not drug-specified. What is vital to drug discovery is to design potential drug candidates for specific drug targets. In a regular drug discovery procedure, the starting point is target identification, followed by lead generation. Then, lead optimization is performed to make lead compounds more drug-like \cite{hughes2011principles}. It is useful to find new lead compounds to replace existing market drugs for several reasons. First, existing market drugs might not be optimal. For example, they might not be potent enough, be too toxic and harmful to human health, or be too hard to synthesize. Additionally, they might have side effects, insufficient aqueous solubility (log S) that reduces the absorption of drugs \cite{kerns2008vitro}, or higher partition coefficients (log P) that lead to improper drug distributions within the body \cite{leo1971partition}. Moreover, for very expensive drugs, it is desirable to find cheap alternatives. With the generation of new alternative lead compounds in mind, one can make use of existing drug datasets to develop drug-specified generative models. In this process, it is critical to apply a similarity restraint to generate hundreds or even thousands of new drug-like molecules inside the chemical space close to the reference molecule. This similarity restraint enables us to generate new molecules that remain effective to the target. Moreover, from the viewpoint of machine learning, higher similarities to existing data always lead to more reliable predictions in generating molecules. The generative model can also realize lead optimization: by incorporating optimizers, generated molecules are designated to have one or more chemical properties better than the reference molecule. As a result, a large number of alternative drug candidates are created by drug-specified generative models. These candidates could be an effective and specified library to further screen for better or cheaper drug alternatives. Therefore, in this work, we develop a generative network complex (GNC) based on the multiple-property optimization via gradient descent in the latent space to automatically generate new drug-like molecules. One workflow of our GNC consists of three following stages \begin{enumerate} \item The SMILES string of a seed molecule are encoded into a vector in the latent space by a pre-trained encoder. \item Starting with the latent vector of the seed molecule, a DNN-based drug-like molecule generator modifies the vector via gradient descent, so that new latent vectors that satisfy multiple property restraints including chemical properties and similarity scores to the desired objectives are created. \item A pre-trained decoder decodes these new latent vectors into the SMILES strings of newly generated molecules. \end{enumerate} The rest of the paper is organized as follows. Section \ref{sec:methods} introduces our new GNC framework formed by the seq2seq AE and drug-like molecule generator. Section \ref{sec:experiments} discusses its reliability test on the BACE1 target, and more importantly, presents the performance of our GNC on a variety of existing drug targets. The insight into the roles of the multiple property restraints is offered in Section \ref{sec:discussions}. The conclusion is given in Section \ref{sec:conclusion}. \section{Methods}\label{sec:methods} \subsection{The sequence to sequence antoencoder (seq2seq AE)} The seq2seq model is an autoencoder architecture originated from natural language processing \cite{sutskever2014sequence}. It has been demonstrated as a breakthrough in language translation. The basic strategy of the seq2seq AE is to map an input sequence to a fixed-sized vector in the latent space using a gated recurrent unit (GRU) \cite{cho2014learning} or a long short-term memory (LSTM) network \cite{hochreiter1997long}, and then map the vector to a target sequence with another GRU or LSTM network. Thus the latent vector is an intermediate representation containing the ``meaning" of the input sequence. In our case, input and output sequences are both SMILES strings -- a one-dimensional "language" of chemical structures \cite{weininger1988smiles}. The seq2seq AE is trained to have a high reconstruction ratio between inputs and outputs so that the latent vectors contain faithful information of the chemical structures (see the upper part of Figure \ref{fig:gen-seq2seq}). Here we utilize a pre-trained seq2seq model from a recent work \cite{winter2019learning}. \subsection{The drug-like molecule generator based on the multi-property optimization} \begin{figure}[h] \centering \includegraphics[width=0.7\textwidth]{gen-seq2seq.png} \caption{A schematic illustration of our generative network complex 2.} \label{fig:gen-seq2seq} \end{figure} In our new GNC, we design a drug-like molecule generator elaborately, so that generated molecules not only satisfy desired properties but also share common pharmacophores with reference compounds. From a seed molecule, one generative workflow of the GNC is depicted in Figure \ref{fig:gen-seq2seq} and described as below. \begin{enumerate} \item Randomly pick a low-binding-affinity molecule from a target-specified training set as the seed, then the SMILES string of the seed molecule is encoded by a pre-trained encoder (in our case a GRU encoder) into a latent vector. \item The latent vector of the seed is fed into our DNN molecule generator. In every epoch, the generator comes up with a new vector $X \in \mathbb{R}^n$, and the deep learning network is instructed to evaluate $X$ via the following loss function \begin{equation}\label{eq:dnn_loss} {\cal L}(X)=\frac{1}{n}\sum_{i=1}^n k_i| \hat{y}_i(X) - y_{i0}|, \end{equation} where, $k_i$ is the $i$th predefined weight serving the purpose of emphasizing or deemphasizing different property restraints, $\hat{y}_i(X)$ is the predicted $i$th property value by a pre-trained predictor ${\cal M}_i$. Additionally, $y_{i0}$ is the objective value of the $i$th property. The restrained properties can be binding affinity (BA), the similarity score (Sim) to a reference molecule or others such as partition coefficient (Log P), Lipinski's rule of five \cite{lipinski1997experimental}, etc. Some guideline for $y_{i0}$ includes, in the BA restraint, one often sets $y_{\Delta G}$ < -9.6 kcal/mol, in the Log P condition, it is common to set $y_{\rm LogP}$ < 5, etc. \item Gradient descent is used to minimize the loss function in Eq. (\ref{eq:dnn_loss}) until the maximum number of epochs is reached \item The generated latent vectors satisfying the desired restraints are decoded into SMILES strings through a pre-trained decoder, as shown in Figure \ref{fig:gen-seq2seq}. \end{enumerate} To create a variety of novel drug-like molecules originated from leads or existing drugs (reference molecules), one can adopt different seed molecules as well as different objective values to achieve desired properties and similarity scores. The ultimate purpose of our molecule generator is to keep modifying the latent vector to satisfy the multiple druggable property restraints. Figure \ref{fig:gen-mechanism} illustrates the general mechanism of our generator. Notably, the pre-trained predictor weights inside our model stay intact throughout the backpropagation of the training process to the generator. The loss function converges when all conditions are met, and then, resulting latent vectors are decoded into SMILES strings. \begin{figure}[h] \centering \includegraphics[width=0.7\textwidth]{mechanism-gen2.png} \caption{The illustration of the latent-space molecule generator.} \label{fig:gen-mechanism} \end{figure} \subsection{The parameters of the molecule generator} \label{sec:param-gen} In our model, the dimension of the latent space is 512, so the input and output dimensions of the DNN molecule generator are also 512. The DNN generator has two hidden layers, with 1024 neurons in each layer. The activation function is tanh, the learning rate is 0.1, and the momentum is also 0.1. In this work, we are interested in binding affinity and similarity score restraints. The regularization coefficients of these two restraints ($k_{\rm \Delta G}$ and $k_{\rm Sim}$) are set to 1 and 10, respectively. The similarity score restraints is determined via the Tanimoto coefficient between a generated latent vector and the latent vector of a reference molecule. The binding affinity restraints rely on pre-trained binding affinity predictors. A pre-trained binding affinity predictor (LV-BP) takes latent vectors as its inputs and return predicted binding affinities. Therefore, typically, the input dimension of the predictor is 512, the output dimension is 1. The DNN predictor has three hidden layers with 1024, 1536, and 1024 neurons, respectively. The ReLU activation function is applied. The learning rate is 0.001, the number of training epochs is 4000, the batch size is 4. The predictor network is trained on target-specified datasets carefully selected from public databases such as ChEMBL \cite{gaulton2011chembl}. The generator and predictor are both programmed in the framework of PyTorch (Version 1.0.0) \cite{paszke2017pytorch}. In the current work, for each generation task, we randomly pick 50 low-binding-affinity molecules from the preselected dataset as seeds. For each seed, the generative network is run in a total of 2000 epochs, which takes less than 10 minutes under the supercomputer equipped with one Nvidia K80 GPU card. In practice, to quickly fill up the potential chemical search space, one can use more seeds and run more epochs for each seed. \subsection{Binding affinity reevaluation by the 2D-fingerprint predictor} \label{sec:2DFP-BP} Besides generating new molecules, the LV-BP in our GNC also predicts their binding affinities. However, no experimental values are available to validate these predicted affinities. Therefore, we cross-validate them using alternative binding affinity predictors. In the present work, we construct machine learning predictors based on 2D fingerprints (2DFP-BPs) to reevaluate the affinities of generated compounds. The 2D fingerprints computed from their SMILES strings are inputs to these 2DFP-BPs. If the predictions from the LV-BP and 2DFP-BPs are consistent, we regard the predictions as reliable. According to our previous tests \cite{gao20202d}, the consensus of ECFP4 \cite{rogers2010extended}, Estate1\cite{hall1995electrotopological} and Estate2 \cite{hall1995electrotopological} fingerprints performs best on binding-affinity prediction tasks. Therefore, this work also makes use of this consensus. We employ the RDKit software (version 2018.09.3) \cite{landrum2006rdkit} to generate 2D fingerprints from SMILES strings. Since the training sets in our current cases are not so large, we apply gradient boosting decision tree (GBDT) \cite{schapire2003boosting} model due to its accuracy and speed when handling small datasets. This GBDT predictor is constructed using the gradient boosting regressor module in scikit-learn (version 0.20.1) \cite{pedregosa2011scikit} and the following parameters: n\_estimators=10000, max\_depth=7, min\_samples\_split=3, learning\_rate=0.01, subsample=0.3, and max\_features=sqrt. The criteria used in our reevaluation are the root mean square error (RMSE), Pearson correlation coefficient ($R_p$), and active ratio. Here, the active ratio means the ratio of the number of the active molecules indicated both by the 2DFP-BP and LV-BP to the number of the active ones indicated by the LV-BP. \subsection{Multitask DNN predictors} \label{sec:param-multi} Multitask DNN predictors \cite{caruana1997multitask} for both latent vectors and 2D fingerprints are built for the drug Ribociclib with two different targets. The latent-vector based model has three hidden layers with 1024, 1536, and 1024 neurons. For the 2D-fingerprint based models, because the three different 2D fingerprints ECFP4, Estate1, Estate2 have 2048, 79, and 79 features, respectively, two different network architectures are used. For ECFP4, the numbers of neurons in the three hidden layers are 2500, 1500, and 500, respectively. For Estate1 and Estate2, their numbers of neurons are 500, 1000, and 500. Other parameters are the same as those of our single task predictors. These multitask models are also programmed in the framework of PyTorch (Version 1.0.0). \subsection{Drug-target interaction and common pharmacophore analysis} The interactions between drugs and their targets, as well as the pharmacophores of the drugs, are investigated. The purpose is to explore whether our generated molecules can still bind to the drug targets. Drug-target interactions are analyzed via the protein-ligand interaction profiles \cite{salentin2015plip}. It can identify drug-target interactions as well as their types such as hydrogen bonds, hydrophobic interactions, etc. However, the interaction analysis itself could not determine whether interactions are critical or not to the drug-target binding. By using the Phase module in Schr\"{o}dinger (version 2018-4) \cite{dixon2006phase}, we build pharmacophore models via searching common pharmacophores in all the active compounds to the target. Since these pharmacophores are widespread to all the active compounds, they are critical to the binding. Thus, if generated molecules still contain such pharmacophores, we can believe they are potential binders. It could be time-consuming to recognize common pharmacophores of hundreds of compounds. To avoid this obstacle, we group compounds into 50 clusters via the k-means algorithm implemented by scikit-learn \cite{pedregosa2011scikit}. We, then, collect the centroids of these 50 clusters for the common pharmacophore search. \subsection{Datasets} In this work, first, we explore the effect of different objective values in our generator on the binding-affinity prediction reliability to generated molecules. We carry out this reliability test on the Beta-Secretase 1 (BACE1) dataset. BACE1 is a transmembrane aspartic-acid protease human protein encoded by the BACE1 gene. It is essential for the generation of beta-amyloid peptide in neural tissue \cite{vassar2009beta}, a component of amyloid plaques widely believed to be critical in the development of Alzheimer's, rendering BACE1 an attractive therapeutic target for this devastating disease \cite{prati2017bace}. We download 3916 BACE1 compounds from the ChEMBL database. In the seq2seq autoencoder we utilized, there is a molecule filter that only selects organic molecules with more than 3 heavy atoms, their weights between 12 and 600, and their Log P values between -5 and 7 \cite{winter2019learning}. As a result, a total of 3151 molecules in the BACE1 dataset pass this filter and are used as the training set. \begin{table}[h] \centering \begin{tabular}{|P{2.0cm}|P{1.5cm}|P{3.2cm}|P{1.4cm}|P{1.4cm}|P{2.0cm}|P{2.6cm}|} \hline \rowcolor{Lightgreen} \textbf{Drug name} & \textbf{ChEMBL ID} & \textbf{Treatment} & \textbf{FDA approval year} & \textbf{$\Delta G$ (kcal/mol)} & \textbf{Filtered training set size} & \textbf{$\Delta G$ range of training set (kcal/mol)} \\ \hline Ceritinib & 2403108 & Non-small cell lung cancer & 2014 & -10.77 & 1203 & -5.26 to -13.93 \\ \hline Ribociclib & 3545110 & Breast cancer & 2017 & -10.98 \& -10.16 & 918 \& 289 & -6.31 to -12.98 \& -4.11 to -14.13 \\ \hline Acalabrutinib & 3707348 & Mantle cell lymphoma & 2017 & -11.67 & 1451 & -4.21 to -14.05 \\ \hline Idelalisib & 2216870 & Blood cancers & 2014 & -10.43 & 1959 & -1.92 to -14.16 \\ \hline Macimorelin & 278623 & Adult growth hormone deficiency & 2017 & -10.48 & 608 & -4.18 to -14.68 \\ \hline Dabrafenib & 2028663 & Cancers with a mutated gene BRAF & 2013 & -12.35 & 2254 & -5.49 to -14.68 \\ \hline Enzalutamide & 1082407 & Prostate cancer & 2012 & -10.53 & 1386 & -3.83 to -13.72 \\ \hline Panobinostat & 483254 & Cancers & 2015 & -12.46 & 1645 & -2.91 to -12.46 \\ \hline \end{tabular} \caption{The information about the eight market drugs used in the present study.} \label{table:eight-drug-inf} \end{table} More importantly, we employ our GNC to design alternative promising drug candidates for the eight drugs on the market. For each drug, we construct a dataset of the compounds that bind to the same drug target from the ChEMBL database. The collected compounds are also filtered by the filter in the seq2seq autoencoder. Table \ref{table:eight-drug-inf} lists information regarding these eight drugs, namely drug name, ChEMBL ID, FDA approval year, experimental drug affinity ($\Delta G$), filtered training set size, and affinity range of the training set. The SciFinder is one of the most comprehensive databases for chemical literature and substances (\url{ https://scifinder-n.cas.org}). It contains more than 143 million organic and inorganic substances. Here we search our generated molecules in this database to confirm they are new and never existed before. \section{Experiments} \label{sec:experiments} \subsection{Designing BACE1 inhibitors} \subsubsection{The accuracy of the seq2seq AE and predictors} We first test the accuracy of the seq2seq autoencoder and the LV-BP and 2DFP-BP predictors. When performing the seq2seq model on the filtered BACE1 dataset with 3151 molecules, the reconstruction ratio is 96.2\%. This high ratio guarantees the essential information of these input molecules is encoded into the corresponding latent vectors. Subsequently, these latent vectors are used as the features to train our latent-vector DNN binding affinity predictor (LV-BP), the labels are their corresponding experimental binding affinities. In a 5-fold cross-validation test on the BACE1 dataset, the LV-BP achieves an average Pearson correlation coefficient ($R_p$) of 0.871 and an average RMSE of 0.704 kcal/mol. The 2D-fingerprint GBDT binding affinity predictor (2DFP-BP) is used to reevaluate the predictions from the LV-BP. We also test this 2DFP-BP by the 5-fold cross-validation. The average $R_p$ and RMSE are 0.874 and 0.692 kcal/mol, respectively, quite comparable to the LV-BP. \subsubsection{Convergence analysis} \begin{figure}[!htp] \centering \includegraphics[width=0.6\textwidth]{pathway-loss.png} \caption{The convergence of the loss function, the LV-BP predicted $\Delta G$s, and the similarity score to the reference molecule during a molecule generation course. In this example, the $\Delta G$s of the seed molecule and the reference molecule are -6.81 kcal/mol and -12.02 kcal/mol, respectively. To force generated molecules evolving towards the reference molecule, we set the similarity score objective and the $\Delta G$ objective to be 1.00 and -12.02 kcal/mol, respectively.} \label{fig:pathway-loss} \end{figure} \begin{figure}[!htp] \centering \includegraphics[width=0.8\textwidth]{gen-pathway_reduced.png} \caption{A series of generated molecules over the evolution from the seed to the reference molecule.} \label{fig:gen-pathway} \end{figure} Here we conduct our GNC to generate new molecules and analyze how these new molecules evolve over a generation course. We start this experiment with a seed molecule picked from the BACE1 dataset; this molecule is far from active with the binding free energy ($\Delta G$) = -6.81 kcal/mol. The reference molecule is also from the BACE1 dataset, it is highly active with $\Delta G$ = -12.02 kcal/mol. The binding affinity objective $y_{\Delta G}$ is set to be -12.02 kcal/mol, and the similarity score to the reference molecule is targeted to $y_{\rm sim}=1.0$. Figure \ref{fig:pathway-loss}a depicts the loss function values computed at every epoch; Figure \ref{fig:pathway-loss}b and c illustrate the LV-BP predicted binding affinities and similarity scores, respectively. From these figures, one can observe that our GNC produces new potential BACE1 inhibitors with desirable binding affinities in less than 3000 epochs. Figure \ref{fig:gen-pathway} shows a series of generated molecules over the evolution from the seed to the reference molecule. The starting point is the seed molecule, its binding affinity and similarity score to the reference molecule are as low as -6.81 kcal/mol and 0.01, respectively. By receiving the feedback from the gradient descent in the generator, the similarity score gradually rises to 1.0. The improvement to the binding affinity is even faster: while a created molecule has a similarity score of 0.28, its LV-BP predicted $\Delta G$ already reaches -11.30 kcal/mol; while the similarity score is 0.90, the LV-BP predicted $\Delta G$ is -12.00 kcal/mol, which is essentially the same as the reference molecule's $\Delta G$ of -12.02 kcal/mol. \subsubsection{Reliability test on the designed BACE1 inhibitors}\label{sec:BACE1-reliablity-test} Using our GNC, we also generate millions of compounds targeting a wide range of binding affinities and similarity scores. Then the prediction reliability with these different ranges of binding affinities and similarity scores is tested. Individually, the similarity score objectives, $y_{\rm sim}$, vary from 0.50 to 0.95 with an increment of 0.025; the binding affinity objectives, $y_{\Delta G}$, receive values from -9.6 kcal/mol to -13.1 kcal/mol with an increment of -0.25 kcal/mol. Here we select -9.6 kcal/mol as the starting point since this value is a widely accepted threshold to identify active compounds; the endpoint of $\Delta G$ = -13.1 kcal/mol is the highest binding affinity value in the BACE1 dataset (see Figure \ref{fig:bace_dist}). \begin{figure}[!htb] \centering \includegraphics[width=0.4\textwidth]{filtered-bace_set-dist.png} \caption{The experimental $\Delta G$ distribution of the filtered BACE1 dataset.} \label{fig:bace_dist} \end{figure} \begin{figure}[!htb] \centering \includegraphics[width=1.0\textwidth]{bace-reeval.png} \caption{The reliability test to our GNC generator on the BACE1 dataset. The prediction reliability with different binding affinity objectives ($y_{\Delta G}$) and similarity score objectives ($y_{\rm sim}$) is tested. The discrepancies between the LV-BP and the 2DFP-BP predictions are evaluated by different criteria: (a) The RMSE; (b) The activate ratio; (c) The Pearson correlation; (d) The loss function values.} \label{fig:bace-reeval} \end{figure} The reliability test is based on reevaluating the LV-BP predicted binding affinities by the 2DFP-BP. The reliability criteria are the RMSE, active ratio, and $R_p$ between the LV-BP and 2DFP-BP prediction. The heatmaps in Figure \ref{fig:bace-reeval} shows these evaluation metric values corresponding to different similarity score and binding affinity restraints. Few blank points are present in each heatmap due to no available generation meeting these specific restraints. Figure \ref{fig:bace-reeval}a plots the RMSE metrics. It reveals the most reliable region, i.e., having low RMSE, is $y_{\rm sim}$ above 0.925, and the $y_{\Delta G}$ between -10.1 kcal/mol and -12.1 kcal/mol. This is expectable since machine learning models can render accurate predictions if generated structures are highly similar to the training data (see Figure \ref{fig:bace_dist}). Besides, a large population of training samples have $\Delta G$s between -10.1 kcal/mol and -12.1 kcal/mol, leading more reliable predictions to molecules generated inside this range. Outside this range, as both $y_{\Delta G}$ and $y_{\rm sim}$ decreasing, the RMSEs between the LV-BP and 2DFP-BP predictions increase. Specifically, if $y_{\Delta G} < -12.1$ kcal/mol and $y_{\rm sim} < 0.675$, the RMSEs are always over 3.2 kcal/mol. Figure \ref{fig:bace-reeval}c depicts the $R_p$s between the LV-BP and 2DFP-BP predictions with respect to $y_{\Delta G}$ and $y_{\rm sim}$. Similar to the manner of the RMSE distribution, $-$12.1 kcal/mol $ \leq y_{\Delta G} \leq 10.1$ kcal/mol and $0.9\leq y_{\rm sim} \leq 0.95$ lead to the $R_p$ values consistently higher than 0.8. The last component of our reliable analysis regards the loss function magnitudes of our GNC generator plotted in Figure \ref{fig:bace-reeval}d. In most cases, the loss function values are less than 0.05. However, in some special situations, our network cannot maintain the loss values lower than 0.15. At these points, we cannot find any generated molecules subject to the multi-property restraints simultaneously, which renders the blank spots in the criteria plots in Figures \ref{fig:bace-reeval}a, b, and c. In summary, to generate molecules with reliable predictions, one should set the binding affinity objective $y_{\Delta G}$ in a region filled with a large population of training data. Besides, the similarity score restraint $y_{\rm sim}$ should be high. However, in some circumstances, the generated molecules that have high predicted affinities should also be included in further consideration. \subsection{Designing alternative drug candidates} In this section, we utilize our GNC to produce alternative drug-like molecules with high binding affinities to the existing drugs' targets, which provides effective libraries for further improvement or searching cheaper drug alternatives. This work discusses eight drugs and their targets with the information regarding the names, ChEMBL IDs, energies, etc. summarized in Table \ref{table:eight-drug-inf}. All of these drugs were approved by the FDA in the recent decade to treat critical diseases, especially a variety of cancers. Notably, the drug Ribociclib has two different targets (Cyclin-dependent kinase 4 and Cyclin-dependent kinase 6), so Ribociclib has two sets of $\Delta G$s and two sets of training compounds. \subsubsection{The single-target drug: Ceritinib} \paragraph{The statistics of the drug Ceritinib.} The brand name of Ceritinib (ChEMBL ID: CHEMBL2403108) is Zykadia. It was developed by Novartis and approved by the FDA in April 2014 to treat different types of non-small cell lung cancers. Ceritinib is extremely expensive, with the monthly cost of Ceritinib-based treatment in the US being approximately \$11,428. Ceritinib inhibits the ALK tyrosine kinase receptor (ALK, CHEMBL ID: CHEMBL4247). The ChEMBL database provides 1407 molecules with experimental binding affinity labels to this target available. After going through the filter in our model, 1203 molecules are left to train our generator and predictor. Figure \ref{fig:chembl2403108-training-dis}a depicts the $\Delta G$ distribution of this training set; it unveils that, hundreds of training samples have their binding affinities close to or even higher than Ceritinib. The similarity score distribution in Figure \ref{fig:chembl2403108-training-dis}b indicates, the training set includes 355 samples with their similarity scores to Ceritinib over 0.3, 56 samples with such scores over 0.6. These promising analytical assessments enable our GNC to design potential inhibitors to the target ALK. \begin{figure}[!htb] \centering \includegraphics[width=0.7\textwidth]{chembl2403108-training-dis.png} \caption{(a) The $\Delta G$ distribution of the filtered training set to the target ALK. The red bar indicates the interval containing the $\Delta G$ of Ceritinib. (b) The similarity scores of the other molecules in this set to Ceritinib.} \label{fig:chembl2403108-training-dis} \end{figure} \paragraph{Designing new druglike molecules.} Here we use Ceritinib as the reference molecule to design alternative Ceritinib drugs. Section \ref{sec:BACE1-reliablity-test} suggests, to generate new molecules with desirable properties, the binding affinity objectives should be inside a region with plenty of training data, and the similarity scores to the reference molecule $y_{\rm sim}$ should be restrained to be high. However, high similarity scores could lead to quite limited chemical space. Our solution to this drawback is, first, extend similarity score restraint to a broader range, then reevaluate generated compounds using the 2DFP-BP, and only pick the ones with low discrepancies between the LV-BP and 2DFP-BP predicted affinities. Following this strategy, we set the similarity score restraints varying from 0.3 to 0.9 with an increment of 0.025; this is because more than 300 training samples have their similarity scores over 0.3, which is supportive to generate compounds in this similarity range. The binding affinities are aimed at the interval from -10.5 kcal/mol to -12.25 kcal/mol with an increment of -0.25 kcal/mol; this binding affinity region covers hundreds of training samples as well as the drug Ceritinib itself. After reevaluating by the 2DFP-BP, any generated molecules with the relative errors between the LV-BP and 2DFP-BP predicted affinities over 5 \% are thrown away. \paragraph{The 2DFP-BP reevaluation.} The details of the 2DFP-BP are offered in Section \ref{sec:2DFP-BP}. With Ceritinib as the reference, our GNC model creates 1095 novel active drug-like molecules, upon eliminating the ones with high discrepancies in their LV-BP and 2DFP-BP predictions, 629 molecules are left. Figure \ref{fig:corr-2d-dl-2403108} indicates, for these 629 molecules, the correlation between the two predictions is quite promising, with the RMSE = 0.28 kcal/mol, $R_p$ = 0.80, and active ratio = 0.95, respectively. This statistical information endorses the drug-likeness potential of our AI-generated molecules. \begin{figure}[h] \centering \includegraphics[width=0.55\textwidth]{corr-2d-dl-2403108.png} \caption{The correlation plot between the LV-BP and 2DFP-BP predicted $\Delta G$s of the generated molecules to the target ALK, the ones having high relative errors between the two predictions (>5 \%) are already eliminated.} \label{fig:corr-2d-dl-2403108} \end{figure} The LV-BP and 2DFP-BP predicted binding affinities of these 629 molecules are also averaged, and their distribution is shown in \ref{fig:chembl2403108-gen-dis}a. This figure reveals the preferred affinities of the generated compounds is from -9.8 kcal/mol to -10.8 kcal/mol, which is also the most popular affinity region of the training samples. Figure \ref{fig:chembl2403108-gen-dis}b illustrates their similarity score distribution to the reference drug Ceritinib. \begin{figure}[!htb] \centering \includegraphics[width=0.8\textwidth]{chembl2403108-gen-dis.png} \caption{The average predicted binding affinities to the target ALK of the generated molecules and their similarity scores to the reference drug Ceritinib. (a) The distribution of the averages of the LV-BP and 2DFP-BP predicted $\Delta G$s to the target ALK. (b) The similarity score distribution to the reference drug Ceritinib.} \label{fig:chembl2403108-gen-dis} \end{figure} \paragraph{Top 6 drug candidates.} Ranked by the average predicted binding affinities of these 629 molecules, we select the top 6 drug candidates. Their 2D draws are plotted in Figure \ref{fig:chembl2403108-top6}. The relative errors between their LV-BP and 2DFP-BP predictions are 1.3 \%, 3.1 \%, 0.1 \%, 4.0 \%, 3.5 \%, 3.9 \%, respectively. It is delighted to see that their average predicted affinities are much higher than that of the reference drug Ceritinib. Moreover, these candidates have similarity scores to the reference drug from 0.54 to 0.69. They are brand new and do not exist in the SciFinder database. We also calculate their log P values and synthetic accessibility scores (SAS) using RDKit, log S values by Alog PS 2.1 \cite{tetko2005virtual}, and report them in Figure \ref{fig:chembl2403108-top6}; these values are comparable to that of the reference drug and in reasonable ranges. \begin{figure}[!htb] \centering \includegraphics[width=0.85\textwidth]{chembl2403108-top6.png} \caption{The drug Ceritinib and its top 6 generated molecules. The predicted $\Delta G$s to the target ALK, similarity scores (Sim) to the drug, calculated log P, log S values, and synthetic accessibility scores (SASs) are also present.} \label{fig:chembl2403108-top6} \end{figure} \paragraph{The interaction and pharmacophore analysis.} One can observe from Figure \ref{fig:chembl2403108-top6}, even though the similarity scores are only between 0.56 and 0.69, these generated compounds share some moieties with the reference drug Ceritinib. This designates these common moieties to possibly involve critical interactions with the binding site of the target. \begin{figure}[ht!] \centering \includegraphics[width=0.8\textwidth]{interaction-pharm-chem2403108.png} \caption{The pharmacophore analysis to the ALK tyrosine kinase's binding site. (a) The interaction plot between the drug Ceritinib and ALK tyrosine kinase from the 3D experimental structure with the PDB ID 4MKC. (b) The 3D alignments of the common pharmacophores obtained from all the active compounds to the target ALK with the 3D experimental structure of the drug Ceritinib, the top 6 generated molecules are also aligned to it.} \label{fig:interaction-pharm-chem2403108} \end{figure} To verify our generated compounds still contain critical moieties to the binding, from experimental structures, we investigate the drug-target interactions, as well as the common pharmacophores among all the active compounds to the target. Figure \ref{fig:interaction-pharm-chem2403108}a shows the interaction details between the drug Ceritinib and its target in the 3D crystal structure of their complex (PDB ID 4MKC \cite{friboulet2014alk}). It reveals their interactions include, one hydrogen bond with one N atom in the pyrimidine of the drug (marked by 1 in the Figure \ref{fig:interaction-pharm-chem2403108}a) as the acceptor, one hydrogen bond with one N atom in the chain of the drug (marked by 2 in the Figure \ref{fig:interaction-pharm-chem2403108}a) as the donor, and another hydrogen bond with one O atom in the drug as the acceptor, one hydrophobic interaction between one benzene ring (marked by 3 in the Figure \ref{fig:interaction-pharm-chem2403108}a) and the target, as well as other hydrophobic interactions. The common pharmacophore analysis in Figure \ref{fig:interaction-pharm-chem2403108}b is consistent with the interaction analysis. The N atom in the pyrimidine of the drug (marked by 1 in the Figure \ref{fig:interaction-pharm-chem2403108}a and \ref{fig:interaction-pharm-chem2403108}b) and the N atom in the chain of the drug (marked by 2 in the Figure \ref{fig:interaction-pharm-chem2403108}a and \ref{fig:interaction-pharm-chem2403108}b)) are critical pharmacophores, they plays the roles of an acceptor and a donor of hydrogen bonds, respectively. Another pharmacophore is the benzene ring forming a hydrophobic interaction with the target. The pharmacophore analysis also reveals more potential interaction modes, such as the hydrophobic interaction between the Cl atom and target, and the hydrogen bond with the other N atom in the chain of the drug as its donor. As illustrated in Figure \ref{fig:interaction-pharm-chem2403108}b, all these critical pharmacophores are retained in our top 6 generated compounds, which strongly supports that these compounds are potential inhibitors to the target. \subsubsection{The double-target drug: Ribociclib} \paragraph{The statistics of the drug Ribociclib.} Here, we test the generative power of our GNC on multi-target drugs. In this case study, the multi-property restraints consist of multiple binding affinity criteria and the similarity score to a reference molecule. The drug we test here is Ribociclib (ChEMBL ID: CHEMBL3545110, brand name: Kisqali). It was developed by Novartis and Astex Pharmaceuticals and approved by the FDA in 2017 to treat certain kinds of breast cancers. The monthly cost of Ribociclib treatment is \$10,950 in the US. Ribociclib inhibits two different targets, namely the Cyclin-dependent kinase 4 (CDK4, CHEMBL ID: CHEMBL331) and Cyclin-dependent kinase 6 (CDK6, CHEMBL ID: CHEMBL2508). In the ChEMBL database, 919 molecules have CDK4 binding data, 289 molecules have CDK6 binding data. After filtered out, 918 and 289 molecules are retained, respectively, providing a small training set to the CDK6. Figure \ref{fig:chembl3545110-training-dis}a and b plot the $\Delta G$ distributions of these two training sets. It reveals, in both the CDK4 and CDK6 sets, hundreds of samples have binding affinities close to or even higher than Ribociclib. Figure \ref{fig:chembl3545110-training-dis}c and d show the similarity score distributions to Ribociclib of the two training sets. Both these sets include more than 200 samples with the similarity scores to the drug over 0.3, more than 60 samples with such scores over 0.6. \begin{figure}[!htb] \centering \includegraphics[width=0.8\textwidth]{chembl3545110-training-dis.png} \caption{(a) The experimental $\Delta G$ distribution of the training set to the target CDK4 with the interval containing the $\Delta G$ of the drug Ribociclib to CDK4 marked in red. (b) The experimental $\Delta G$ distribution of the CDK6 training set with the interval containing the $\Delta G$ of Ribociclib to CDK4 in red. (c) The similarity score distribution of the other samples in the CDK4 training set to Ribociclib. (d) The similarity score distribution of the other samples in the CDK6 set to Ribociclib.} \label{fig:chembl3545110-training-dis} \end{figure} \paragraph{The multitask predictor.} Since the CDK6 training set is small, it is challenging to train an accurate predictor for this target. However, the two targets, CDK4 and CDK6, are similar due to the calculation via SWISS-MODEL \cite{schwede2003swiss} with the sequence identity being 71.1\%. Therefore, multitask deep learning can enhance reliability. In our multitask architecture, the binding affinity predictor in our generator offers two outputs, each for one of the two targets, so the predictor is trained by the two training sets simultaneously. As a result, in a 5-fold crossing-validation test, the multitask model significantly improves the performance on the small dataset. \begin{table}[!htb] \centering \begin{tabular}{|l|l|l|l|l|} \hline \rowcolor{Lightgreen} \multirow{2}{*}{} & \multicolumn{2}{l|}{Target CDK4} & \multicolumn{2}{l|}{Target CDK6} \\ \cline{2-5} \rowcolor{Lightgreen} & Single task & Multitask & Single task & Multitask \\ \hline LV-BP & 0.791 & 0.804 & 0.524 & 0.811 \\ \hline 2FP-BP & 0.824 & 0.836 & 0.485 & 0.779 \\ \hline \end{tabular} \caption{The $R_p$s of $\Delta G$ predictions from the 5-fold cross-validation tests on the two targets of the drug Ribociclib by the single task and multitask predictors.} \label{table:5-fold_ST_MT} \end{table} As illustrated in Table \ref{table:5-fold_ST_MT}, the target CDK4 with a 918-molecule training set does not benefit so much from the multitask. However, to the target CDK6 only with a 289-molecule training set, the improvement is dramatic: the $R_p$s rise from 0.524 to 0.811 by the LV-BP and from 0.485 to 0.779 by the 2FP-BP. These results demonstrate the efficiency of the multitask architecture. \paragraph{The generation of new druglike molecules.} To design alternative Ribociclib drugs in broader chemical space, we set the similarity score restraints to Ribociclib from 0.30 to 0.90, with an increment of 0.025. The binding affinities to the target CDK4 are aimed at the interval between -10.80 kcal/mol and -12.00 kcal/mol with an increment of -0.2 kcal/mol; this interval covers the $\Delta G$s of Ribociclib as well as lots of other training samples. For the same reason, the objectives of the binding affinities to the target CDK6 are set from -10.2 kcal/mol to -11.0 kcal/mol with an increment of -0.2 kcal/mol. Totally, following this scheme, we create 1080 novel molecules. \paragraph{The reevaluation by 2DFP-BP.} \begin{figure}[!htb] \centering \includegraphics[width=0.9\textwidth]{corr-2d-dl-two-targets.png} \caption{The correlations between the LV-BP and 2DFP-BP predicted $\Delta G$s of the generated molecules to the targets CDK4 and CDK6, the ones having high relative errors between the two predictions (>5 \%) are already eliminated.} \label{fig:corr-2d-dl-two-targets} \end{figure} The predicted bind affinities of these 1080 generated compounds are reevaluated by the 2DFP-BP model incorporated with the multitask DNN. The parameters of this architecture are introduced in Section \ref{sec:param-multi}. After excluding the ones with high discrepancies between the LV-BP and 2DFP-BP predictions, 271 molecules are left. Figure \ref{fig:corr-2d-dl-two-targets} depicts the correlation plots between their LV-BP and 2DFP-BP predicted $\Delta G$s to the two targets. The correlations of the $\Delta G$s to both the two targets are promising. Specifically, the $\Delta G$s to the target CDK4 can achieve an RMSE of 0.29 kcal/mol, a $R_p$ of 0.69, and an active ratio as high as 0.98; the $\Delta G$s to the target CDK6 also have an RMSE of 0.27 kcal/mol, a $R_p$ of 0.65 and an active ratio of 0.78. \begin{figure}[!htb] \centering \includegraphics[width=0.8\textwidth]{chembl3545110-gen-dis.png} \caption{The average predicted $\Delta G$ to the targets CDK4 and CDK6 of the generated molecules and their similarity scores to the reference drug Ribociclib: (a, b) The distributions of the averages of the LV-BP and 2DFP-BP predicted $\Delta G$s to the two targets, respectively. (c) The similarity score distribution to the reference drug Ribociclib.} \label{fig:chembl3545110-gen-dis} \end{figure} Their LV-BP and 2DFP-BP predicted binding affinities to the two targets are also averaged, and the distributions are shown in Figure \ref{fig:chembl3545110-gen-dis}a,b. Figure \ref{fig:chembl3545110-gen-dis}c illustrates their similarity score distribution to the reference drug Ribociclib. \begin{figure}[!htb] \centering \includegraphics[width=0.7\textwidth]{chembl3545110-top6.png} \caption{The drug Ribociclib and its top 6 generated molecules. The predicted $\Delta G$s to the targets CDK4 and CDK6, similarity scores (Sim) to the drug, calculated log P, log S values, and synthetic accessibility scores (SASs) are also reported.} \label{fig:chembl3545110-top6} \end{figure} \paragraph{Top 6 drug candidates.} According to the average predicted binding affinities of these 271 molecules, we select the top 6 drug candidates. Figure \ref{fig:chembl3545110-top6} represents their 2D plots. To the target CDK4, the relative errors between their LV-BP and 2DFP-BP predictions are 4.6 \%, 3.0 \%, 3.2 \%, 0.2 \%, 1.6 \% and 0.7 \%, respectively; to CDK6, the relative errors between the two predictions are 1.7 \%, 1.2 \%, 3.7 \%, 3.4 \%, 4.8 \% and 1.7 \%, respectively. Most of them have better binding affinities than the reference drug Ribociclib. Such as, to CDK4, the affinities of the first and fourth compounds are predicted to be higher than that of Ribociclib, the other three have similar ones with Ribociclib; to CDK6, all the top 6 candidates have better binding affinities. Moreover, their similarity scores to the reference drug are between 0.65 and 0.75. They are not in the SciFinder database, which means these six candidates are novel. The log P, log S values and synthetic accessibility scores (SASs) calculated by RdKit and Alog PS are also showed in the figure; their log P, log S values and SASs are comparable to that of the reference drug. \begin{figure}[!htb] \centering \includegraphics[width=1.0\textwidth]{interaction-pharm-3545110-target2_reduced.png} \caption{(a) The illustration of the interactions between the drug Ribociclib and the target CDK6 extracted from the experimental structure (PDB ID 5L2T). (b) The 3D alignment of the common pharmacophores obtained from all the active compounds to the target CDK6 with the 3D experimental structure of the drug Ribociclib, the top 6 generated molecules are also aligned to it.} \label{fig:interaction-pharm-3545110-target2} \end{figure} \paragraph{The interaction and pharmacophore analysis.} Figure \ref{fig:interaction-pharm-3545110-target2}(a) shows the interaction details between the drug Ribociclib and the target CDK6 in the 3D crystal structure of their complex (PDB ID 5L2T \cite{chen2016spectrum}). It indicates the main interactions are hydrogen bonds and hydrophobic interactions. The pharmacophore analysis in Figure \ref{fig:interaction-pharm-3545110-target2}(b) reveals that the critical pharmacophores are the pyrrolopyrimidine, pyridine, and cyclohexane, which can form hydrogen bonds and hydrophobic interactions with the binding site. Among the top 6 candidates, except the first one, the others contain all these critical pharmacophores; the first one has most of them. This suggests all the six compounds are potential inhibitors to the targets. \begin{figure}[!htb] \centering \includegraphics[width=0.8\textwidth]{corr-other-drugs_reduced.png} \caption{The correlation plots between the LV-BP and 2DFP-BP predicted $\Delta G$s of the generated molecules to the six drug targets, the ones with high relative errors between the two predictions are already eliminated.} \label{fig:corr-other-drugs} \end{figure} \subsubsection{The tests on the other single-target drugs} We also apply our GNC to the rest six drugs listed in Table \ref{table:eight-drug-inf} and design novel drug candidates. The similarity score restraints are from 0.30 to 0.90, with an increment of 0.025. The $\Delta G$ objective ranges are chosen to contain the $\Delta G$s of the drugs as well as lots of other training samples. We also only collect the generated molecules with the relative errors between the LV-BP and 2DFP-BP predicted $\Delta G$s below 5 \%. \begin{figure}[!htb] \centering \includegraphics[width=0.9\textwidth]{detg-dis-others.png} \caption{The sizes and experimental $\Delta G$ distributions of the training sets to the six drug targets. The red bars indicate the intervals containing the $\Delta G$s of the six reference drugs.} \label{fig:detg-dis-others} \end{figure} \begin{figure}[!htb] \centering \includegraphics[width=0.9\textwidth]{sim-dis-others.png} \caption{ The similarity score distributions of other molecules in the six training sets to the reference drugs.} \label{fig:sim-dis-others} \end{figure} Figure \ref{fig:corr-other-drugs} indicates, since the ones with high discrepancies between the two predictions are eliminated, our generated compounds to all these six drug targets have promising correlations. Now, we focus on whether highly active drug candidates are created or not. This relies on the binding affinity and similarity score distributions of the training sets. Figure \ref{fig:detg-dis-others} provides the sizes and the $\Delta G$ distributions of these six target-specified training sets; the red bars indicate the intervals containing the $\Delta G$s of the reference drugs. Figure \ref{fig:sim-dis-others} plots their similarity score distributions. Figures \ref{fig:detg-dis-others}a shows that the training set of the drug Acalabrutinib contains 1459 compounds. Among them, more than 400 compounds have higher binding affinities than that of the drug, which is beneficial to generate compounds more potent than the drug. Also, Figure \ref{fig:sim-dis-others}a reveals that in the training set, over 500 molecules have the similarity scores to the drug over 0.3, which is quite helpful to generate novel compounds with similarity scores also in this range. These promising statistical information helps to explain why our GNC can create as many as 879 new compounds for this drug target with high confidence, and 17 of them have higher or similar binding affinities with that of Acalabrutinib; the best $\Delta G$ is -11.90 kcal/mol (see Figures S1 and S3). As revealed by \ref{fig:detg-dis-others}b, the training set of the drug Idelalisib is larger than that of Acalabrutinib; and over 500 molecules in this set have higher binding affinities than that of Idelalisib. As a result, 73 of the 794 generated compounds are more potent than Idelalisib, with the best $\Delta G$ being -11.27 kcal/mol (see Figures S1 and S4). Figure \ref{fig:detg-dis-others}c exhibits that the dataset of Macimorelin is quite small. However, the correlation of the generated molecules is still satisfactory, and 13 generated molecules have similar $\Delta G$s with that of the drug (see Figure S1). The reason is, its training set contains 205 compounds with higher binding affinities than that of the drug, and also 182 compounds with the similarity scores to the drug over 0.3. Figures \ref{fig:detg-dis-others}d and e depict the datasets of the drugs Dabrafenib and Enzalutamide. The affinity values of these two drugs are close to the upper boundaries of their training sets' affinity domains. In other words, few molecules in their training sets are more active than the drugs. Since the interpolation nature of machine learning models tends to provide reliable predictions inside the populated range, it is tough to generate compounds more potent than these drugs. Although their training set sizes and similarity scores are favorable, the numbers of generated compounds with better binding affinities than that of the drugs are only 2 and 4, respectively (see Figures S1, S6 and S7). We perform our last experiment on the drug Panobinostat. Panobinostat is an extreme example: as illustrated in Figure \ref{fig:detg-dis-others}f, its binding affinity is the highest in its training set. Therefore, although our GNC model generates 319 molecules, the top active one among them only reaches a $\Delta G$ of -11.56 kcal/mol, which is far less potent than the drug itself ($\Delta G$=-12.46 kcal/mol). In the supporting information, Figures S3 to S8 provide the top six generated alternative compounds for the drugs Acalabrutinib, Idelalisib, Macimorelin, Dabrafenib, Enzalutamide, and Panobinostat, as well as their predicted $\Delta G$s. \section{Discussions}\label{sec:discussions} With the availability of deep learning technologies, more and more {\it in silico} molecule generation models have been proposed. These models can be classified into three categories: randomized output, controlled output, and optimized output \cite{grow2019generative}. One of the challenges is how to generate new molecules with desired chemical properties, especially drug-like molecules. Another challenge is how to improve the utility of {\it in silico} molecule generation without direct experimental validations. To address these challenges, we propose a new GNC to generate drug-like molecules based on multi-property optimizations via gradient descent. \subsection{The essential circumstances for reliable and desired molecule generation} Based on our experiments, there are two essential circumstances to generate molecules with reliable and desired predicted chemical properties: \begin{enumerate} \item An objective property value should always be in a region with lots of training samples. Based on the nature of machine learning methods, the predictor can be built with high accuracy at an objective value if lots of training samples around it. It can be seen from Section \ref{sec:BACE1-reliablity-test} that when a binding affinity objective is in the middle of the training set's distribution, the latent space generator can always generate novel molecules with reliable predictions confirmed by the 2DFP-BP. However, when an objective is close to or even at the edge of the training-set distribution, one may still generate many novel compounds, but the predictions to them are quite risky, such as high discrepancies between the LV-BP and 2DFP-BP predictions. \item Generated compounds should have some high similarity scores to some existing molecules in the training set. If some molecules (not necessarily reference molecules) in the training set are similar to generated compounds, then the predictions are reliable and can be verified by the 2DFP-BP. \end{enumerate} \subsection{The necessity of both similarity and property value restraints} The two points above also explain why both similarity score and property value restraints should be included in our generator. The goal of property restraint is two-fold. First, it restricts property values to desired ones. Additionally, it can be used to achieve high reliability. As discussed above, if the property value is limited to a populated region of the training-set distribution, the resulting generated molecules will most likely have reliable predictions. Similarity restraint is also to ensure prediction accuracy. High similarity scores to existing molecules make predictions more accurate and reliable. Moreover, in a regular drug discovery procedure for a given target, one typically starts from some lead compounds or even current drugs and then carries out lead optimizations to make candidates more "drug-like", e.g., higher activity and lower side effects \cite{hughes2011principles}. Therefore, similarly, in a drug-specified generative model, the similarity to a reference compound or drug must be controlled to guarantee that new drug-like compounds still bind to the target. For example, with similarity restraint, generated molecules share pharmacophores with the reference drug. \subsection{Multiple property restraints} Drug design is sophisticated. To develop a drug, plenty of properties must be carefully studied, such as binding affinity, toxicity, partition coefficient (log P), aqueous solubility (log S), off-target effect. The failure in any one of these properties can prevent drug candidates from the market. In other words, drug design is a multi-property optimization process. Technically, our generator can handle this multi-property optimization. In our framework, the restraint to each property is realized by one term in the loss function. Therefore, multi-property optimization can be satisfied simultaneously in our GNC. In this work, multiple property restraints are tested on one drug with two targets (Ribociclib). It turns out, the generated new candidates have ideal binding affinities to the two targets simultaneously; this means, our model can work on the multiple property restraints. Multiple properties can also be specified as toxicity, log P, log S, etc. To avoid side effects, one can also control drug candidates to have a high binding affinity to one target but low binding affinities to other targets. \section{Conclusion} \label{sec:conclusion} Searching alternative drugs is important for improving the quality of existing drugs and making new drugs cheaply available to low-income people. In this work, we develop a new generative network complex (GNC) for automated generation of drug-like molecules based on the multi-property optimization via gradient descent in the latent space. In this new GNC, multiple chemical properties, particularly binding affinity and similarity score, are optimized to generate new molecules with desired chemical and drug properties. To ensure the prediction reliability of these new compounds, we reevaluate them by independent 2D-fingerprint based predictors. Molecules without consistent predictions from the latent-vector model and the 2D-fingerprint model are not accepted. After the consistent check, hundreds of potential potent drug candidates are reported. Performed on a supercomputer, the generation process from one seed to a large number of new molecules takes less than 10 minutes. Therefore, our GNC is an efficient new paradigm for discovering new drug candidates. To demonstrate the utility of the present GNC, we first test its reliability on the BACE1 target and then, further apply this model to generate thousands of new alternative drug candidates for a few market existing drugs, namely, Ceritinib, Ribociclib, Acalabrutinib, Idelalisib, Dabrafenib, Macimorelin, Enzalutamide, and Panobinostat. We also discuss the keys to generate drug-like candidates with reliable predictions. First, an objective property value should be in a populated region of the training-set distribution. Second, generated molecules need to have good similarity scores to some existing compounds in the training set. \vspace{1cm} \section*{Supplementary materials} Figures S1 to S8 are the $\Delta G$ and similarity score distributions of the generated drug-like molecules for the drugs Acalabrutinib, Idelalisib, Dabrafenib, Macimorelin, Enzalutamide, and Panobinostat, as well as the 2D plots and predicted $\Delta G$s of the top 6 among them. \vspace{1cm} \section*{Acknowledgments} This work was supported in part by NSF Grants DMS-1721024, DMS-1761320, and IIS1900473, NIH grant GM126189, and Michigan Economic Development Corporation. DDN and GWW are also funded by Bristol-Myers Squibb and Pfizer. \clearpage \vspace{1cm}
{'timestamp': '2020-06-01T02:03:11', 'yymm': '2005', 'arxiv_id': '2005.14286', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14286'}
arxiv
\section{Introduction} In the last two decades, random matrix theory (RMT) has produced numerous results that offer a better understanding of large random matrices. These advances have enabled interesting applications in communication theory and even though it can potentially contribute to many other data-rich domains such as brain imaging or genetic research, it has rarely been applied. The main barrier to the adoption of RMT may be the lack of concrete statistical results from the probability side. The straightforward adaptation of classical multivariate theory to high dimensions can sometimes be achieved, but such procedures are only valid under strict assumptions about the data such as normality or independence. Even minor differences between the model assumptions and the actual data lead to catastrophic results and such procedures also often do not have enough power. This paper proposes a statistical procedure for testing the equality of two covariance matrices when the number of potentially dependent data vectors $n$ and the number of variables $m$ are large. RMT denotes the investigation of estimates of covariance matrices $\hat{\Sigma}$ or more precisely their eigenvalues and eigenvectors when both $n$ and $m$ tend to infinity with $\lim \frac{m}{n}=c>0$. When $m$ is finite and $n$ tends to infinity the behaviour of the random matrix is well known and presented in the books of \cite{multi3}, \cite{multi} and \cite{multi2} (or its original version \cite{multi22}). In the RMT case, the behaviour is more complex, but many results of interest are known. \cite{Alice}, \cite{Tao} and more recently \cite{bookrecent} contain comprehensive introductions to RMT and \cite{Appliedbook} covers the case of empirical (estimated) covariance matrices. Although the existing theory builds a good intuition of the behaviour of these matrices, it does not provide enough of a basis to construct a test with good power, which is robust with respect to the assumptions. Inspired by the spike models, we extend the residual spikes introduced in \cite{mainarticle} and provide a description of the behaviour of this statistic under a null hypothesis when the perturbation is of order $k$. These results enable the user to test the equality of two populations as well as other null hypotheses such as the independence of two sets of variables. This paper can be seen as a complex particular case of \cite{mainarticle2}. However simulations show that equality between eigenvalues of the perturbation are not necessary for this complex statistic and moreover they show good robustness against perturbations of distributions.\\ The remainder of the paper is organized as follows. In the next section, we develop the test statistic and discuss the problems associated with high dimensions. Then we present the main theorem \ref{TH=Main}. The proof itself is technical and presented in Appendix \ref{appendixproof}. The last section contains an example of an application. \section{Test statistic}\label{section:teststat} We compare the spectral properties of two covariance estimators $\hat{\Sigma}_X$ and $\hat{\Sigma}_Y$ of dimension $m\times m$ which can be represented as \begin{eqnarray*} \hat{\Sigma}_X=P_X^{1/2} W_X P_X^{1/2} \text{ and } \hat{\Sigma}_Y=P_Y^{1/2} W_Y P_Y^{1/2}. \end{eqnarray*} In this equation, $W_X$ and $W_Y$ are of the form \begin{eqnarray*} W_X=O_X \Lambda_X O_X \text{ and } W_Y=O_Y \Lambda_Y O_Y, \end{eqnarray*} with $O_X$ and $O_Y$ being independent unit orthonormal random matrices whose distributions are invariant under rotations, while $\Lambda_X$ and $\Lambda_Y$ are independent positive random diagonal matrices, independent of $O_X, O_Y$ with trace equal to m and a bound on the diagonal elements. Note that the usual RMT assumption, $\frac{m}{n}=c$ is replaced by this bound! The (multiplicative) spike model of order $k$ determines the form of $P_X= {\rm I}_m + \sum_{s=1}^k (\theta_{X,s}-1) u_{X,s} u_{X,s}^t$ and $P_Y= {\rm I}_m+ \sum_{s=1}^k(\theta_{Y,s}-1) u_{Y,s} u_{Y,s}^t$ where $\left\langle u_{X,s} ,u_{X,r} \right\rangle=\left\langle u_{Y,s} ,u_{Y,r} \right\rangle=\delta_{s,r}$. Our results will apply to any two centered data matrices ${\mathbf{X}} \in \mathbb{R}^{m\times n_X}$ and ${\mathbf{Y}} \in \mathbb{R}^{m\times n_Y}$ which are such that \begin{eqnarray*} \hat{\Sigma}_X= \frac{1}{n_X}{\mathbf{X}} {\mathbf{X}}^t \text{ and } \hat{\Sigma}_Y= \frac{1}{n_Y}{\mathbf{Y}} {\mathbf{Y}}^t \end{eqnarray*} and can be decomposed in the manner indicated. This is the basic assumption concerning the covariance matrices. We will assume throughout that $n_X\geq n_Y$. Because $O_X$ and $O_Y$ are independent and invariant by rotation we can assume without loss of generality that for $s=1,2,...,k$, $u_{X,s}=e_s$ as in \cite{deformedRMT}. Under the null hypothesis we have $P_X=P_Y$ and we use the simplified notation $P_k$ for both matrices where for $s=1,2,...,k$, $\theta_{X,s}=\theta_{Y,s}=\theta_s$ and $u_{X,s}=u_{Y,s}(=e_s)$. To test $H_0:P_k=P_X=P_Y$ against $H_1:P_X\neq P_Y$ it is natural to consider the extreme eigenvalues of \begin{eqnarray} \hat{\Sigma}_X^{-1/2} \hat{\Sigma}_Y \hat{\Sigma}_X^{-1/2}\,.\label{eq:base1} \end{eqnarray} We could also swap the subscripts, but it turns our to be preferable to use the inversion on the matrix with larger sample size. The distributional approximations we will refer to are based on RMT, that is, they are derived by embedding a given data problem into a sequence of random matrices for which both $n$ and $m$ tend to infinity such that $m/n$ tends to a positive constant $c$. The most celebrated results of RMT describe the almost sure weak convergence of the empirical distribution of the eigenvalues (spectral distribution) to a non-random compactly supported limit law. An extension of this theory to the "Spike Model" suggests that we should modify $\hat{\Sigma}$ because estimates of isolated eigenvalues derived from the usual estimates are asymptotically biased. The following corrections will be used. \begin{Def} \label{Def=unbiased} Suppose $\hat{\Sigma}$ is of the form described at the start of the section. The \textbf{unbiased estimator of }$\theta_s$ for $s=1,...,k$ is defined as \begin{equation} \hat{\hat{\theta}}_s=1+\frac{1}{\frac{1}{m-k} \sum_{i=k+1}^{m} \frac{\hat{\lambda}_{\hat{\Sigma},i}}{\hat{\theta}_s-\hat{\lambda}_{\hat{\Sigma},i}}}\,,\label{eq:corrlambda} \end{equation} where $\hat{\lambda}_{\hat{\Sigma},i}$ is the $i^{\text{th}}$ largest eigenvalue of $\hat{\Sigma}$. When $\hat{\Sigma}=P_k^{1/2}WP_k^{1/2}$ as above, it is asymptotically equivalent to replace $\frac{1}{m-k}\sum_{i=k+1}^{m} \frac{\hat{\lambda}_{\hat{\Sigma},i}}{\hat{\theta}-\hat{\lambda}_{\hat{\Sigma},i}}$ in the denominator by $\frac{1}{m}\sum_{i=1}^{m} \frac{\hat{\lambda}_{W,i}}{\hat{\theta}-\hat{\lambda}_W,i}$.\\ Suppose that $\hat{u}_s$ is the eigenvector corresponding to $\hat{\theta}_s$, then the \textbf{filtered estimated covariance matrix } is defined as \begin{equation} \hat{\hat{\Sigma}}= {\rm I}_m+\sum_{s=1}^k (\hat{\hat{\theta}}_s-1) \hat{u}_s \hat{u}_s^t\,.\label{eq:corrSigma} \end{equation} \end{Def} The matrix (\ref{eq:base1}) which serves as the basis for the test then becomes either \begin{equation} \hat{\hat{\Sigma}}_X^{-1/2} \hat{\hat{\Sigma}}_Y \hat{\hat{\Sigma}}_X^{-1/2} \text{ or }\hat{\hat{\Sigma}}_X^{-1/2} \hat{\Sigma}_Y \hat{\hat{\Sigma}}_X^{-1/2} \,.\label{eq:base2} \end{equation} In the particular case where ${\mathbf{X}}$ and ${\mathbf{Y}}$ have independent jointly normal columns vector with constant variance $P_k=P_X=P_Y$, the distribution of the spectrum of the second of the above matrices is approximately Marcenko-Pastur distributed (see \cite{deformed}). This follows because $\hat{\hat{\Sigma}}_X$ is a finite perturbation. However, because of the non-consistency of the eigenvectors presented in \cite{deformedRMT}, we may observe \textbf{residual spikes} in the spectra, as shown in Figure \ref{fig=spike}. Thus, even if the two random matrices are based on the same perturbation, we see some spikes outside the bulk. This observation is worse in the last plot because four spikes fall outside the bulk even if there is actually no difference! This poses a fundamental problem for our test, because we must be able to distinguish the spikes indicative of a true difference from the residual spikes. These remarks lead to the following definition. \begin{Def} The \textbf{residual spikes} are the isolated eigenvalues of $$\hat{\hat{\Sigma}}_X^{-1/2} \hat{\hat{\Sigma}}_Y \hat{\hat{\Sigma}}_X^{-1/2}\text{ or of } \hat{\hat{\Sigma}}_X^{-1/2} \hat{\Sigma}_Y \hat{\hat{\Sigma}}_X^{-1/2}$$ when $P_X=P_Y$ (under the null hypothesis). The \textbf{residual zone} is the interval where a residual spike can fall asymptotically. \end{Def} \begin{figure}[htbp] \centering \begin{tabular}{cc} \includegraphics[width=0.26\paperwidth]{residualtheta10.pdf} & \includegraphics[width=0.26\paperwidth]{residualtheta10c=1.pdf} \\ \includegraphics[width=0.26\paperwidth]{residualtheta10c=02.pdf}& \includegraphics[width=0.26\paperwidth]{residualthetak.pdf} \end{tabular} \caption{Example of residual spikes of $\hat{\hat{\Sigma}}_X^{-1/2} \hat{\Sigma}_Y \hat{\hat{\Sigma}}_X^{-1/2}$ when $\theta=10$ for the first three figures and $\theta_{1,2,3,4}=10,15,20,25$ for the last figure.}\label{fig=spike} \end{figure} This paper studies these residual spikes by deriving the distribution of the extreme residual spikes under the null hypothesis. The philosophy is explained in Figure \ref{fig=residualzone0} with illustrations inspired by the i.i.d. normal case. All the eigenvalues inside the residual zone are potentially not indicative of real differences. However, when an eigenvalue is larger, we declare that this spike expresses a true difference. Most of our plots feature the seemingly more natural matrix \begin{eqnarray*} \hat{\hat{\Sigma}}_X^{-1/2} \hat{\Sigma}_Y \hat{\hat{\Sigma}}_X^{-1/2}\,. \end{eqnarray*} But, although this choice simplifies the study in terms of convergence in probability when the perturbation is of order $1$, this is no longer the case in more complex situations. In addition, the eigenvectors associated with the residual spikes are more accessible for the matrix in which all estimates are filtered. \begin{figure}[htbp] \centering \scalebox{0.7}{ \begin{tabular}{c} \input{residualzone} \\ \ \input{residualzone2} \end{tabular} } \caption{Residual zone of $\hat{\hat{\Sigma}}_X^{-1/2} \hat{\Sigma}_Y \hat{\hat{\Sigma}}_X^{-1/2}$ and $\hat{\hat{\Sigma}}_X^{-1/2} \hat{\hat{\Sigma}}_Y \hat{\hat{\Sigma}}_X^{-1/2}$.}\label{fig=residualzone0} \end{figure} Let $\hat\theta_{X,s}$ and $\hat\theta_{Y,s}$ be isolated eigenvalues and construct the asymptotic unbiased estimators as in Equation (\ref{eq:corrlambda}) \begin{eqnarray*} \hat{\hat{\theta}}_{X,s}=1+\frac{1}{\frac{1}{m-k} \sum_{i=k+1}^{m} \frac{\hat{\lambda}_{\hat{\Sigma}_{X},i}}{\hat{\theta}_{X,s}-\hat{\lambda}_{\hat{\Sigma}_{X},i}}} \text{ and } \hat{\hat{\theta}}_{Y,s}=1+\frac{1}{\frac{1}{m-k} \sum_{i=k+}^m \frac{\hat{\lambda}_{\hat{\Sigma}_{Y},i}}{\hat{\theta}_{Y,s}-\hat{\lambda}_{\hat{\Sigma}_{Y},i}}}, \end{eqnarray*} where $\hat{\lambda}_{\hat{\Sigma}_{X},i}$ and $\hat{\lambda}_{\hat{\Sigma}_{Y},i}$ are the i$^{th}$ ordered eigenvalue of $\hat{\Sigma}_{X}$ and $\hat{\Sigma}_{Y}$, respectively. The test statistic is then \begin{eqnarray*} \lambda_{\min}\left(\hat{\hat{\Sigma}}_X^{-1/2} \hat{\hat{\Sigma}}_Y \hat{\hat{\Sigma}}_X^{-1/2} \right) \text{ and } \lambda_{\max}\left(\hat{\hat{\Sigma}}_X^{-1/2} \hat{\hat{\Sigma}}_Y \hat{\hat{\Sigma}}_X^{-1/2} \right)\,, \end{eqnarray*} where the filtered matrices are constructed as in (\ref{eq:corrSigma}). These two statistics provide a basis for a powerful and robust test for the equality of (detectable) perturbations $P_X$ and $P_Y$. \subsection{Null distribution} \label{sec=test} Under $H_0$, $\lambda_{\max}\left(\hat{\hat{\Sigma}}_X^{-1/2} \hat{\hat{\Sigma}}_Y \hat{\hat{\Sigma}}_X^{-1/2} \right) $ is obviously a function of $\theta_s=\theta_{X,s}=\theta_{Y,s}$ for $s=1,2,...,k$. The suspected \textbf{worst case} occurs in the limit as $\theta_s\to\infty$ for all $s$ and it is this limit which will determine the critical values of the test. A criterion proposed in \cite{mainarticle} allows to check if this scenario is really the worst case. Let \begin{eqnarray*} &&\lambda_{\max}\left(\hat{\hat{\Sigma}}_X^{-1/2} \hat{\hat{\Sigma}}_Y \hat{\hat{\Sigma}}_X^{-1/2} \right) \leqslant \lim_{\theta \rightarrow \infty} \lambda_{\max}\left(\hat{\hat{\Sigma}}_X^{-1/2} \hat{\hat{\Sigma}}_Y \hat{\hat{\Sigma}}_X^{-1/2} \right) =V_{\max} ,\\ &&\lambda_{\min}\left(\hat{\hat{\Sigma}}_X^{-1/2} \hat{\hat{\Sigma}}_Y \hat{\hat{\Sigma}}_X^{-1/2} \right) \geqslant \lim_{\theta \rightarrow \infty} \lambda_{\min}\left(\hat{\hat{\Sigma}}_X^{-1/2} \hat{\hat{\Sigma}}_Y \hat{\hat{\Sigma}}_X^{-1/2} \right) =V_{\min}. \end{eqnarray*} Because of our focus on the worst case scenario under $H_0$, we will investigate the asymptotic as $\theta_i=\theta p_i$ for fixed $p_i>0$ and $\frac{\theta}{\sqrt{m}} \rightarrow \infty$. We recall that \cite{mainarticle2} also allows some finite $\theta_s$ but it seems intuitive that this scenario will not create a worst case in most situations. This intuition is highlighted by \cite{mainarticle} showing by simulation that the residual spike increase as a function of $\theta$ assuming $W_X=\frac{1}{n_X}{\mathbf{X}}\X^t$. Our test rejects the null hypothesis of equal populations if either $\P\left( V_{\max} > \hat{\lambda}_{\max} \right)$ or $\P\left( V_{\min} < \hat{\lambda}_{\min} \right)$ is small, where $\hat{\lambda}_{\max}$ and $\hat{\lambda}_{\min}$ are the observed extreme residual spikes. The following result describes the asymptotic behavior of the extreme eigenvalues and thus of $V_{\max}$ and $V_{\min}$. \begin{Th} \label{TH=Main} Suppose $W_X,W_Y \in \mathbb{R}^{m\times m}$ are as described at the start of Section 2 and \begin{enumerate} \item \cite{mainarticle} have already investigated the case $P_1= {\rm I}_m+(\theta-1)e_1 e_1^t \in \mathbb{R}^{m\times m}$ with $\frac{\sqrt{m}}{\theta}=o(1)$ with regard to large $m$. Let \begin{eqnarray*} \hat{\Sigma}_{X,P_1}=P_1^{1/2} W_X P_1^{1/2} \text{ and } \hat{\Sigma}_{Y,P_1}=P_1^{1/2} W_Y P_1^{1/2}. \end{eqnarray*} and $\hat{\hat{\Sigma}}_{X,P_1}$, $\hat{\hat{\Sigma}}_{Y,P_1}$ as described above (see, \ref{Def=unbiased}). Then, conditional on the spectra $S_{W_X}=\left\lbrace \hat{\lambda}_{W_X,1},\hat{\lambda}_{W_X,2},...,\hat{\lambda}_{W_X,m} \right\rbrace$ and $S_{W_Y}=\left\lbrace \hat{\lambda}_{W_Y,1},\hat{\lambda}_{W_Y,2},...,\hat{\lambda}_{W_Y,m} \right\rbrace$ of $W_X$ and $W_Y$, \begin{eqnarray*} \left. \sqrt{m} \frac{\left(\lambda_{\max}\left(\hat{\hat{\Sigma}}_{X,P_1}^{-1/2} \hat{\hat{\Sigma}}_{Y,P_1} \hat{\hat{\Sigma}}_{X,P_1}^{-1/2} \right) -\lambda^+ \right)}{\sigma^+} \right| S_{W_X}, S_{W_Y} \sim \mathbf{N}(0,1)+o_{p}(1), \end{eqnarray*} where \begin{eqnarray*} &&\lambda^+= \sqrt{M_2^2-1}+M_2, \hspace{30cm} \end{eqnarray*} \scalebox{0.77}{ \begin{minipage}{1\textwidth} \begin{eqnarray*} &&{\sigma^+}^2=\frac{1}{\left(M_{2,X}+M_{2,Y}-2\right) \left(M_{2,X}+M_{2,Y}+2\right)} \hspace{30cm} \\ &&\hspace{2cm} \Bigg( 9 M_{2,X}^4 M_{2,Y}+4 M_{2,X}^3 M_{2,Y}^2+4 M_{2,X}^3 M_{2,Y}+2 M_{2,X}^3 M_{3,Y}-2 M_{2,X}^2 M_{2,Y}^3\\ && \hspace{2cm}+4 M_{2,X}^2 M_{2,Y}^2-11 M_{2,X}^2 M_{2,Y}-8 M_{3,X} M_{2,X}^2 M_{2,Y}+2 M_{2,X}^2 M_{2,Y} M_{3,Y}\\ && \hspace{2cm}-2 M_{2,X}^2 M_{3,Y}+M_{2,X}^2 M_{4,Y}+4 M_{2,X} M_{2,Y}^3+M_{2,X} M_{2,Y}^2+4 M_{2,X} M_{2,Y}\\ && \hspace{2cm}-4 M_{3,X} M_{2,X} M_{2,Y}^2-4 M_{3,X} M_{2,X} M_{2,Y}-2 M_{2,X} M_{2,Y}^2 M_{3,Y}-4 M_{2,X} M_{2,Y} M_{3,Y}\\ && \hspace{2cm}-6 M_{2,X} M_{3,Y}+2 M_{4,X} M_{2,X} M_{2,Y}+2 M_{2,X} M_{2,Y} M_{4,Y}-2 M_{3,X} M_{2,Y}^2\\ && \hspace{2cm}+2 M_{3,X} M_{2,Y}+M_{4,X} M_{2,Y}^2+4 M_{2,X}^5+2 M_{2,X}^4-4 M_{3,X} M_{2,X}^3-13 M_{2,X}^3\\ && \hspace{2cm}-2 M_{3,X} M_{2,X}^2+M_{4,X} M_{2,X}^2-2 M_{2,X}^2+10 M_{3,X} M_{2,X}+4 M_{2,X}+4 M_{3,X}\\ && \hspace{2cm}-2 M_{4,X}+M_{2,Y}^5+2 M_{2,Y}^4-M_{2,Y}^3-2 M_{2,Y}^2+4 M_{2,Y}-2 M_{2,Y}^3 M_{3,Y}\\ && \hspace{2cm}-2 M_{2,Y}^2 M_{3,Y}+2 M_{2,Y} M_{3,Y}+4 M_{3,Y}+M_{2,Y}^2 M_{4,Y}-2 M_{4,Y}-4 \Bigg)\\ &&\hspace{1.25cm} + \frac{1}{\sqrt{\left(M_{2,X}+M_{2,Y}-2\right) \left(M_{2,X}+M_{2,Y}+2\right)}}\\ && \hspace{2cm} \Bigg( 5 M_{2,X}^3 M_{2,Y}-M_{2,X}^2 M_{2,Y}^2+2 M_{2,X}^2 M_{2,Y}+2 M_{2,X}^2 M_{3,Y}-M_{2,X} M_{2,Y}^3\\ && \hspace{2cm}+2 M_{2,X} M_{2,Y}^2-4 M_{2,X} M_{2,Y}-4 M_{3,X} M_{2,X} M_{2,Y}-2 M_{2,X} M_{3,Y}+M_{2,X} M_{4,Y}\\ && \hspace{2cm}-2 M_{3,X} M_{2,Y}+M_{4,X} M_{2,Y}+4 M_{2,X}^4+2 M_{2,X}^3-4 M_{3,X} M_{2,X}^2-5 M_{2,X}^2\\ && \hspace{2cm}-2 M_{3,X} M_{2,X}+M_{4,X} M_{2,X}+2 M_{2,X}+2 M_{3,X}+M_{2,Y}^4+2 M_{2,Y}^3+M_{2,Y}^2\\ && \hspace{2cm}+2 M_{2,Y}-2 M_{2,Y}^2 M_{3,Y}-2 M_{2,Y} M_{3,Y}-2 M_{3,Y}+M_{2,Y} M_{4,Y} \Bigg), \end{eqnarray*} \end{minipage}} \begin{eqnarray*} &&M_{s,X}= \frac{1}{m} \sum_{i=1}^m \hat{\lambda}_{W_X,i}^s,\hspace{30cm}\\ &&M_{s,Y}= \frac{1}{m} \sum_{i=1}^m \hat{\lambda}_{W_Y,i}^s,\\ &&M_s=\frac{M_{s,X}+M_{s,Y}}{2}. \end{eqnarray*} Moreover, \begin{eqnarray*} \left.\sqrt{m} \frac{\left(\lambda_{\min}\left(\hat{\hat{\Sigma}}_{X,P_1}^{-1/2} \hat{\hat{\Sigma}}_{Y,P_1} \hat{\hat{\Sigma}}_{X,P_1}^{-1/2} \right) -\lambda^- \right)}{\sigma^-}\right| S_{W_X}, S_{W_Y} \sim \mathbf{N}(0,1)+o_{m}(1), \end{eqnarray*} where \begin{eqnarray*} &&\lambda^-= -\sqrt{M_2^2-1}+M_2, \hspace{30cm}\\ &&{\sigma^-}^2=\left(\lambda^-\right)^4 {\sigma^+}^2. \end{eqnarray*} The error $o_p(1)$ in the approximation is with regard to large values of $m$. \item Suppose that $P_k= {\rm I}_m+\sum_{s=1}^k(\theta_s-1)e_s e_s^t \in \mathbb{R}^{m\times m}$ with $\theta_s=p_s \theta$, $p_s>0$ and $\frac{\sqrt{m}}{\theta}=o(1)$ with regard to large $m$. \begin{eqnarray*} \hat{\Sigma}_{X,P_k}=P_k^{1/2} W_X P_k^{1/2} \text{ and } \hat{\Sigma}_{Y,P_k}=P_k^{1/2} W_Y P_k^{1/2}, \end{eqnarray*} and $\hat{\hat{\Sigma}}_{X,P_k}$, $\hat{\hat{\Sigma}}_{Y,P_k}$ as described above (see, \ref{Def=unbiased}). \noindent Then, conditioning on the spectra $S_{W_X}$ and $S_{W_Y}$,\\ \scalebox{0.82}{ \begin{minipage}{1\textwidth} \begin{eqnarray*} \left. \lambda_{\max}\left(\hat{\hat{\Sigma}}_{X,P_k}^{-1/2} \hat{\hat{\Sigma}}_{Y,P_k} \hat{\hat{\Sigma}}_{X,P_k}^{-1/2}\right) \right| S_{W_X},S_{W_Y}=\lambda_{\max}\left( H^+ \right)+1+O_p\left(\frac{1}{m}\right),\\ \left.\lambda_{\min}\left(\hat{\hat{\Sigma}}_{X,P_k}^{-1/2} \hat{\hat{\Sigma}}_{Y,P_k} \hat{\hat{\Sigma}}_{X,P_k}^{-1/2}\right)\right| S_{W_X},S_{W_Y}=\lambda_{\max}\left( H^- \right)+1+O_p\left(\frac{1}{m}\right), \end{eqnarray*} \end{minipage}} where \begin{eqnarray*} H^\pm= \zeta_{\infty}^\pm \begin{pmatrix} \hat{\zeta}_1^\pm / \zeta_{\infty}^\pm & w_{1,2}^\pm & w_{1,3}^\pm & \cdots & w_{1,k}^\pm \\ w_{2,1}^\pm & \hat{\zeta}_2^\pm / \zeta_{\infty}^\pm & w_{2,3}^\pm & \cdots & w_{2,k}^\pm \\ w_{3,1}^\pm & w_{3,2}^\pm & \hat{\zeta}_3^\pm /\zeta_{\infty}^\pm & \cdots & w_{3,k}^\pm \\ \vdots & \vdots & \ddots & \ddots & \vdots \\ w_{k,1}^\pm & w_{k,2}^\pm & w_{k,3}^\pm & \cdots & \hat{\zeta}_k^\pm /\zeta_{\infty}^\pm \\ \end{pmatrix} , \end{eqnarray*} and \\ \scalebox{0.73}{ \begin{minipage}{1\textwidth} \begin{eqnarray*} &&\hat{\zeta}_i^+= \left.\lambda_{\max}\left(\hat{\hat{\Sigma}}_{X,\tilde{P}_i}^{1/2} \hat{\hat{\Sigma}}_{Y,\tilde{P}_i} \hat{\hat{\Sigma}}_{X,\tilde{P}_i}^{1/2} \right)-1 \right| S_{W_X},S_{W_Y},\hspace{30cm}\\ &&\hat{\zeta}_i^-= \left.\lambda_{\min}\left(\hat{\hat{\Sigma}}_{X,\tilde{P}_i}^{1/2} \hat{\hat{\Sigma}}_{Y,\tilde{P}_i} \hat{\hat{\Sigma}}_{X,\tilde{P}_i}^{1/2} \right)-1 \right| S_{W_X},S_{W_Y},\\ &&\zeta_{\infty}^\pm =\underset{m \rightarrow \infty}{\lim} \hat{\zeta}_i^\pm = \lambda^\pm -1,\\ &&w_{i,j}^\pm \sim { \color{red} \mathbf{N}}\left(0, \frac{1}{m}\frac{2 (M_{2,X}-1) (M_{2,Y}-1)+B_{X}^\pm +B_{Y}^\pm}{\left((\zeta_{\infty}^\pm-2 M_2+1)^2+2 (M_2-1)\right)^2} \right)+o_p\left( \frac{1}{\sqrt{m}} \right), \end{eqnarray*} \end{minipage}}\\ \scalebox{0.73}{ \begin{minipage}{1\textwidth} \begin{eqnarray*} &&B_{X}^+=\left(1-M_2+2 M_{2,X}+\sqrt{M_2^2-1}\right)^2 (M_{2,X}-1)\hspace{20cm}\\ &&\hspace{2cm} +2\left(-1+M_2-2M_{2,x}-\sqrt{M_2^2-1}\right)(M_{3,X}-M_{2,X})+(M_{4,X}-M_{2,X}^2),\\ &&B_{Y}^+=\left(1+M_2+M_{2,Y}-M_{2,X}-\sqrt{M_2^2-1}\right)^2 (M_{2,Y}-1)\\ &&\hspace{2cm} +2\left(-1-M_2-M_{2,Y}-M_{2,X}-\sqrt{M_2^2-1}\right)(M_{3,Y}-M_{2,Y})+(M_{4,Y}-M_{2,Y}^2),\\ &&B_{X}^-=\left(1-M_2+2 M_{2,X}-\sqrt{M_2^2-1}\right)^2 (M_{2,X}-1)\hspace{20cm}\\ &&\hspace{2cm} +2\left(-1+M_2-2M_{2,x}+\sqrt{M_2^2-1}\right)(M_{3,X}-M_{2,X})+(M_{4,X}-M_{2,X}^2),\\ &&B_{Y}^-=\left(1+M_2+M_{2,Y}-M_{2,X}+\sqrt{M_2^2-1}\right)^2 (M_{2,Y}-1)\\ &&\hspace{2cm} +2\left(-1-M_2-M_{2,Y}+M_{2,X}-\sqrt{M_2^2-1}\right)(M_{3,Y}-M_{2,Y})+(M_{4,Y}-M_{2,Y}^2). \end{eqnarray*} \end{minipage}}\\ \noindent The matrices $H^+$ and $H^-$ are strongly correlated. However, within a matrix, all the entries are uncorrelated. \end{enumerate} \end{Th} \begin{Rem} \label{Rem=thMain} \ The entries of the matrices $H^+$ and $H^-$ are asymptotically uncorrelated Normal or a sum of two Normals. \end{Rem} \paragraph*{Special case} If the spectra are Marcenko-Pastur distributed, we define $c_X=m/n_X$ and $c_Y=m/n_Y$. Then, \scalebox{0.79}{ \begin{minipage}{1\textwidth} \begin{eqnarray*} &&c=\frac{c_X+c_Y}{2},\hspace{30cm}\\ &&\lambda^+= c+\sqrt{c (c+2)}+1,\\ &&{\sigma^+}^2= c_X^3+c_X^2 c_Y+3 c_X^2+4 c_X c_Y-c_X+c_Y^2+c_Y\\ && \hspace{2cm}+\frac{ (8 c_X+2 c_X^2+\left(c_X^3+5 c_X^2+c_X^2 c_Y+4 c_X c_Y+5 c_X +3 c_Y+c_Y^2\right)\sqrt{c(c+2)}}{c+2},\\ &&w_{i,j}^+ \sim {\color{red} \mathbf{N}}\left(0, \frac{\sigma_w^2}{m} \right),\\ && \sigma_w^2=\frac{2c_X \left(\sqrt{c(c+2)}+2\right)+2 \c_Y \left(-\sqrt{c(c+2)}+2\right)+c_X^2+c_Y^2} {4c \left(-\sqrt{c \left(c+2\right)}+c+2\right)^2}. \end{eqnarray*} \end{minipage}}\\ (Proof Appendix \ref{appendixproof}. The {\color{red} red} character is not proven and is a sum of two asymptotic uncorrelated marginally normal random variables that are certainly independent.) \subsection{Discussion and simulation}\label{sec:smallsimulationmainth} The above theorem gives the limiting distribution of $V_{\max}$ and $V_{\min}$. In this subsection, we first check the quality of the approximations in Theorem \ref{TH=Main}. Then we investigate the worst case with regard to $\theta$. Finally we relax some assumption on $\theta_s$ and on the distribution. \subsubsection{Some simulations} Assume $\mathbf{X} \in \mathbb{R}^{m\times n_X}$ and $\mathbf{Y} \in \mathbb{R}^{m\times n_Y}$ with $\mathbf{X}=\left(X_1,X_2,...,X_{n_X}\right)$ and $\mathbf{Y}=\left(Y_1,Y_2,...,Y_{n_Y}\right)$. \scalebox{0.65}{ \begin{minipage}{1\textwidth} \begin{eqnarray*} &&X_i \sim \mathbf{N}_m\left(\vec{0},\sigma^2 {\rm I}_m \right) \text{ with } X_1 = \epsilon_{X,1}\text{ and } X_{i+1}=\rho X_i+\sqrt{1-\rho^2} \ \epsilon_{X,i+1}, \text{ where } \epsilon_{X,i} \overset{i.i.d}{\sim} \mathbf{N}_m\left(\vec{0},\sigma^2 {\rm I}_m\right),\\ &&Y_i \sim \mathbf{N}_m\left(\vec{0},\sigma^2 {\rm I}_m \right) \text{ with } Y_1 = \epsilon_{Y,1}\text{ and } Y_{i+1}=\rho Y_i+\sqrt{1-\rho^2} \ \epsilon_{Y,i+1}, \text{ where } \epsilon_{Y,i} \overset{i.i.d}{\sim} \mathbf{N}_m\left(\vec{0},\sigma^2 {\rm I}_m\right) \end{eqnarray*} \end{minipage}} Let $P_X= {\rm I}_m + (\theta_{X}-1) u_{X} u_{X}^t$ and $P_Y= {\rm I}_m+ (\theta_{Y}-1) u_{Y} u_{Y}^t$ be two perturbations in $\mathbb{R}^{m\times m}$. Then, \begin{eqnarray*} \mathbf{X}_P=P_X^{1/2} \mathbf{X} \text{ and } \mathbf{Y}_P=P_Y^{1/2} \mathbf{Y},\\ \hat{\Sigma}_X=\frac{\mathbf{X}_P^t \mathbf{X}_P}{n_X} \text{ and } \hat{\Sigma}_Y=\frac{\mathbf{Y}_P^t \mathbf{Y}_P}{n_Y}. \end{eqnarray*} We assume a common and large value for $\theta$ and $P_X=P_Y$. \begin{table} \begin{tabular}{ c c } \begin{minipage}{.45\textwidth} \centering \includegraphics[width=1\textwidth]{image1thetasame.pdf} \end{minipage} & \begin{minipage}{.45\textwidth} \centering \includegraphics[width=1\textwidth]{image2thetasame.pdf} \end{minipage}\\ \begin{minipage}{.45\textwidth} \centering \scalebox{0.8}{ \begin{tabular}{c} Scenario 1 \\ \begin{tabular}{c|c|c} $\rho=0.5$ & $c_X=0.5$ & $c_Y=2$ \\ \hline $m=1000$ & $n_X=2000$ & $n_Y=500$ \\ \end{tabular} \\ k=4, $\vec{\theta}=\left(15'000,5000,2000,500\right)$. \end{tabular}} \end{minipage} & \begin{minipage}{.45\textwidth} \centering \scalebox{0.8}{ \begin{tabular}{c} Scenario 2 \\ \begin{tabular}{c|c|c} $\rho=0.5$ & $c_X=0.5$ & $c_Y=2$ \\ \hline $m=1000$ & $n_X=2000$ & $n_Y=500$ \\ \end{tabular} \\ k=4, $\vec{\theta}=\left(5'000,5000,5000,5000\right)$. \end{tabular}} \end{minipage} \\ \begin{minipage}{.45\textwidth} \centering \includegraphics[width=1\textwidth]{image51differentk.pdf} \end{minipage} & \begin{minipage}{.45\textwidth} \centering \includegraphics[width=1\textwidth]{image52differentk.pdf} \end{minipage}\\ \begin{minipage}{.45\textwidth} \centering \scalebox{0.8}{ \begin{tabular}{c} Scenario 3 \\ \begin{tabular}{c|c|c} $\rho=0.5$ & $c_X=0.5$ & $c_Y=2$ \\ \hline $m=1000$ & $n_X=2000$ & $n_Y=500$ \\ \end{tabular} \\ k=1, $\vec{\theta}=5'000$. \end{tabular}} \end{minipage} & \begin{minipage}{.45\textwidth} \centering \scalebox{0.8}{ \begin{tabular}{c} Scenario 4 \\ \begin{tabular}{c|c|c} $\rho=0.5$ & $c_X=0.5$ & $c_Y=2$ \\ \hline $m=1000$ & $n_X=2000$ & $n_Y=500$ \\ \end{tabular} \\ k=8, $\vec{\theta}=\left(5'000,5'000,...,5'000\right)$. \end{tabular}} \end{minipage}\\ \begin{minipage}{.45\textwidth} \centering \includegraphics[width=1\textwidth]{image53differentk.pdf} \end{minipage} & \begin{minipage}{.45\textwidth} \centering \includegraphics[width=1\textwidth]{image1image31kest.pdf} \end{minipage}\\ \begin{minipage}{.45\textwidth} \centering \scalebox{0.8}{ \begin{tabular}{c} Scenario 5 \\ \begin{tabular}{c|c|c} $\rho=0.5$ & $c_X=0.5$ & $c_Y=2$ \\ \hline $m=1000$ & $n_X=2000$ & $n_Y=500$ \\ \end{tabular} \\ k=15, $\vec{\theta}=\left(5'000,5'000,...,5'000\right)$. \end{tabular}} \end{minipage} & \begin{minipage}{.45\textwidth} \centering \scalebox{0.8}{ \begin{tabular}{c} Scenario 6 \\ \begin{tabular}{c|c|c} $\rho=0.5$ & $c_X=0.5$ & $c_Y=2$ \\ \hline $m=1000$ & $n_X=2000$ & $n_Y=500$ \\ \end{tabular} \\ k=4, $\vec{\theta}=\left(15'000,5'000,2'000,500\right)$\\ $k_{est}=7$. \end{tabular}} \end{minipage}\\ \begin{minipage}{.45\textwidth} \centering \includegraphics[width=1\textwidth]{image1image32kest.pdf} \end{minipage} & \begin{minipage}{.45\textwidth} \centering \includegraphics[width=1\textwidth]{image1image33kest.pdf} \end{minipage}\\ \begin{minipage}{.45\textwidth} \centering \scalebox{0.8}{ \begin{tabular}{c} Scenario 7 \\ \begin{tabular}{c|c|c} $\rho=0.5$ & $c_X=0.5$ & $c_Y=2$ \\ \hline $m=1000$ & $n_X=2000$ & $n_Y=500$ \\ \end{tabular} \\ k=4, $\vec{\theta}=\left(15'000,5'000,2'000,500\right)$\\ $k_{est}=3$. \end{tabular}} \end{minipage} & \begin{minipage}{.45\textwidth} \centering \scalebox{0.8}{ \begin{tabular}{c} Scenario 8 \\ \begin{tabular}{c|c|c} $\rho=0.5$ & $c_X=0.5$ & $c_Y=2$ \\ \hline $m=1000$ & $n_X=2000$ & $n_Y=500$ \\ \end{tabular} \\ k=4, $\vec{\theta}=\left(15'000,3'000,8,6\right)$\\ $k_{est}=2$. \end{tabular}} \end{minipage} \end{tabular} \caption{Empirical distributions of the residual spikes together with the Gaussian densities from the theorem \ref{TH=Main} (in blue). } \label{tab:residual} \end{table} \paragraph*{Multiple eigenvalues} \ \\ Despite the lack of a proof, the maximum residual distribution when the eigenvalues of the perturbations are multiple is well approximated by our Theorem. This can be seen in Table \ref{tab:residual} but also in Appendix \ref{appendix:Tablecomplete}. \paragraph*{Different values of $k$} \ \\ Scenario 3, 4 and 5 of Table \ref{tab:residual} shows that the result holds for different values of $k$. The less accurate result of scenario 5 is due to the relatively large $k$, whereas the theorem is based on an approximation which considers $k$ to be small compared to $m$. The precision of the asymptotic approximation would be better for $k=15$ when $m=10'000$ with the same $c_X$ and $c_Y$, for example. \paragraph*{Wrong estimation of $k$} \ \\ Scenario 6, 7 and 8 of Table \ref{tab:residual} shows the impact of using wrong values of $k$. We see in Scenario 6 that a small overestimation of $k$ leads to a small overestimation of the maximum and small underestimation the minimum. This will lead to conservative tests. Scenario 7 shows that underestimation of $k$ can lead to a bad approximation but in this scenario we neglect perturbations of size $500$! Scenario 8 shows that neglecting two small perturbations of size $6$ and $8$, as we could easily do by mistake, still leads to very accurate approximations.\\ The simulation of Table \ref{tab:residual} are done to convince the reader of the usefulness of Theorem \ref{TH=Main}. In practice, we must estimate the parameters needed in the approximation. An arguments based on the Cauchy-interlacing theorem can convinced the reader that we can estimate \begin{eqnarray*} M_{X,s}=\frac{1}{m}\sum_{i=1}^m \lambda_{W_X}^s \end{eqnarray*} by \begin{eqnarray*} \hat{M}_{X,s}=\frac{1}{m-k}\sum_{i=k+1}^m \lambda_{\hat{\Sigma}_X}^s. \end{eqnarray*} The impact of using a wrong value for $k_{est}$ is investigate in Table \ref{tab=simulationkestimation} in Appendix \ref{appendix:Simulationkest}. \paragraph*{Other simulations} In appendix \ref{appendix:Simulationkest} we also investigate the approximation with estimated spectra for data with distributions that are not invariant by rotation. In some scenarios the approximation succeeds to estimate the location but failed to correctly estimate the variance. In others, the location of the maximum residual spike is overestimated and the minimum residual spike is underestimated. This would again lead to conservative tests, but suggests a lack of power. \section{An application} In this section, we apply our procedure developed from Theorem \ref{TH=Main} to data ${\color{red}{{\mathbf{X}}}}$ and ${\color{red}{{\mathbf{Y}}}}$. First, each step is briefly explained. Then, an analysis is presented on simulated data together with the mathematical work and the important plots.\\ This procedure is not unique and other solutions better adapted to the problem could be implemented. For example, the choice of $k$ and the number of perturbations, could certainly be improved. The goal of this section is to provide a procedure as conservative as possible with reasonably good asymptotic power. \begin{enumerate} \item First, we center the data with regard to the rows and columns. \item Then, we need to estimate $k$ and rescale the variance. These two tasks are interconnected. One intuitive way to choose $k$ for each matrix ($k_X$ and $k_Y$) consists in looking at the spectra for spikes and keeping in mind that overestimation is preferable to underestimation of the actual value.\\ Using $k=\max(k_X,k_Y)$, we can then rescale the matrices ${\color{red}{{\mathbf{X}}}}$ and ${\color{red}{{\mathbf{Y}}}}$ to create ${\color{blue}{{\mathbf{X}}}}$ and ${\color{blue}{{\mathbf{Y}}}}$. \item Next, we apply the procedure to ${\color{blue}{{\mathbf{X}}}}$ and ${\color{blue}{{\mathbf{Y}}}}$, using the above $k$. In our case, this leads to two observed extreme residual spikes. \item We compute the distribution of the residual spike by assuming $k$ perturbation and estimating $M_{s,X}$. \item Finally, we can compare the extreme values with their distribution under $\text{H}_0$ for testing purposes. \end{enumerate} \begin{Rem} \ Our simulations in Appendix \ref{appendix:Simulationkest}, show that the choice of $k$ does not affect the conservative nature of the test. A strong underestimation of $k$, however, greatly reduces the power. This explains the advice to overestimate $k$. \end{Rem} \subsection{Analysis} \label{sec:simulAnalysis} We observe data ${\color{red}{{\mathbf{X}}}}\in \mathbf{R}^{m \times n_X}$ and ${\color{red}{{\mathbf{Y}}}}\in \mathbf{R}^{m \times n_Y}$ that we suppose is already centred by rows and columns. We choose $k$ by looking at the histogram of the matrices in Figure \ref{Figexample1} where $m=1000$, $n_X=2000$ et $n_Y=500$. \begin{figure}[hbtp] \includegraphics[width=0.5\paperwidth]{ExampleSpectrum.pdf} \caption{Spectra of ${\color{red}{{\mathbf{X}}}}$ and ${\color{red}{{\mathbf{Y}}}}$ with largest isolated eigenvalues indicated by arrows.}\label{Figexample1} \end{figure} We try to overestimate a lower bound on $k$ based on Figure \ref{Figexample1}. The spectrum of ${\color{red}{{\mathbf{X}}}}$ seems to have $6$ isolated eigenvalues, but we could argue that two other eigenvalues are perturbations. The spectrum ${\color{red}{{\mathbf{Y}}}}$ clearly shows $5$ isolated eigenvalues and at most $2$ additional ones. We thus set $k=8$ knowing that we probably overestimate the true value. Next, we estimate the variances, \begin{eqnarray*} \hat{\sigma}_X^2= \frac{1}{m-k}\sum_{i=k+1}^m \lambda_i\left( \frac{1}{n_X}{\color{red}{{\mathbf{X}}}}\rX^t \right),\\ \hat{\sigma}_Y^2= \frac{1}{m-k} \sum_{i=k+1}^m \lambda_i\left( \frac{1}{n_Y}{\color{red}{{\mathbf{Y}}}}\rY^t \right). \end{eqnarray*} We can then rescale the matrices ${\color{red}{{\mathbf{X}}}}$ and ${\color{red}{{\mathbf{Y}}}}$ by $\hat{\sigma}_X$ and $\hat{\sigma}_Y$, respectively, to create the covariance matrices \begin{eqnarray*} \hat{\Sigma}_X=\frac{1}{n_X \hat{\sigma}_X^2} {\color{red}{{\mathbf{X}}}} {\color{red}{{\mathbf{X}}}}^t \text{ and } \hat{\Sigma}_Y=\frac{1}{n_Y \hat{\sigma}_Y^2} {\color{red}{{\mathbf{Y}}}} {\color{red}{{\mathbf{Y}}}}^t. \end{eqnarray*} Finally, we filter the matrices as in definition \ref{Def=unbiased}. \begin{eqnarray*} &&\hat{\hat{\Sigma}}_X = {\rm I}_m + \sum_{i=1}^k \left(\hat{\hat{\theta}}_{X,i}-1 \right) \hat{u}_{\hat{\Sigma}_X,i}\hat{u}_{\hat{\Sigma}_X,i}^t,\\ &&\hat{\hat{\theta}}_{X,i}= 1+\frac{1}{\frac{1}{m-k} \sum_{j=k+1}^m \frac{\hat{\lambda}_{ \hat{\Sigma}_X,j}}{\hat{\lambda}_{ \hat{\Sigma}_X,i}-\hat{\lambda}_{ \hat{\Sigma}_X,j}}}. \end{eqnarray*} The computed residual spikes of $\hat{\hat{\Sigma}}_X^{-1} \hat{\hat{\Sigma}}_Y$ are shown in Table \ref{Tabexample1}. \begin{table}[hbtp] \begin{tabular}{l|cccccccc} $\lambda_{\max}$ & 56.03 & 10.25 & 9.88 & 8.96 & 8.29 & 7.27 & 5.71 & 5.10 \\ $\lambda_{\min}$ & 0.04 & 0.10 & 0.13 & 0.13 & 0.18 & 0.21 & 0.34 & 0.36 \end{tabular} \caption{Observed residual spikes.}\label{Tabexample1} \end{table} Using Figure \ref{Figexample2} a, these values are compared to the theoretical distributions of the extreme residual spikes assuming equality of the perturbations of order $k$. The distribution in blue uses the usual estimator of the spectra and the distribution in orange uses the conservative estimator introduced in Appendix \ref{appendix:Spectrumestimation}. The moments of the spectra are summarize in Figure \ref{Figexample2} b. \begin{figure}[hbtp] \begin{center} \begin{tabular}{cc} \begin{minipage}{0.3\paperwidth} \includegraphics[width=0.3\paperwidth]{ExampleSpectrum2.pdf} \end{minipage} & \begin{minipage}{0.3\paperwidth} \scalebox{0.7}{ \begin{tabular}{l|cc} &$\lambda_{\min}$ & $\lambda_{\max}$\\ \color{blue} Usual & (0.085, 0.006) & (10.75, 0.45)\\ \color{orange} Robust & (0.067, 0.006) & (12.67, 0.47) \end{tabular}} \end{minipage}\\ a & b \end{tabular} \end{center} \caption{a: Distribution of the extreme residual spike assuming equality of the covariance, $k=8$ and $\theta_i$ large. (Robust estimation of the spectra in orange.) b: Estimated residual spikes moments, $(\mu,\sigma)$ using usual or robust estimators of the spectral moments. }\label{Figexample2} \end{figure} We finally clearly detect two residual spikes. Figure \ref{Figexample3} presents the residual eigenvectors of the residual eigenvalues. \begin{figure}[hbtp] \begin{center} \begin{tabular}{cc} $\lambda=56.03$ & $\lambda=0.04 $\\ \includegraphics[width=0.25\paperwidth]{residualvectormax1.pdf} & \includegraphics[width=0.25\paperwidth]{residualvectormin1.pdf} \\ $\lambda=10.25$ & $\lambda=0.10$ \\ \includegraphics[width=0.25\paperwidth]{residualvectormax2.pdf} & \includegraphics[width=0.25\paperwidth]{residualvectormin2.pdf} \end{tabular} \end{center} \caption{Representation of the entiere residual eigenvectors and only the 20 first entries. }\label{Figexample3} \end{figure} We conclude that the differences are in direction $e_3$ and $e_4$. As we see in the figure, two other eigenvectors also exhibit a structure. Without our test, we could have concluded that they also represent significant differences, but this residual structure is merely due to the biased estimation of the eigenvectors. \begin{center} \textbf{A structure in a residual eigenvector does not imply a real difference!} \end{center} \subsection{Conclusion} By studying perturbation of order $1$ in \cite{mainarticle} and perturbation of order $k$ in \cite{mainarticle2}, we highlighted the lack of power of the usual procedure to detect differences between two groups. This paper extended the residual spike to perturbations of order $k$ by using tools introduced in previous papers. While this test has weaker power than in \cite{mainarticle2}, it has the important advantage do be able to deal with multiple equal eigenvalues. Additional simulations investigating the robustness of this new procedure are contained in the thesis \cite{mathese} and seems promising. \pagebreak
{'timestamp': '2020-07-13T02:08:11', 'yymm': '2005', 'arxiv_id': '2005.14524', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14524'}
arxiv
\section{Introduction}\label{sec:intro} In~\cite{DBLP:journals/Prawitz15} Dag Prawitz proposed a natural deduction system for what was later called {\em Ecumenical logic} (EL), where classical and intuitionistic logic could coexist in peace. In this system, the classical logician and the intuitionistic logician would share the universal quantifier, conjunction, negation, and the constant for the absurd ({\em the neutral connectives}), but they would each have their own existential quantifier, disjunction, and implication, with different meanings. Prawitz' main idea is that these different meanings are given by a semantical framework that can be accepted by both parties. While proof-theoretical aspects were also considered, his work was more focused on investigating the philosophical significance of the fact that classical logic can be translated into intuitionistic logic. Pursuing the idea of having a better understanding of Ecumenical systems under the proof-theoretical point of view, in~\cite{Syn20} an Ecumenical sequent calculus ($\LEci$) was proposed. This enabled not only the proof of some important proof theoretical properties (such as cut-elimination and invertibility of rules), but it also provided a better understanding of the Ecumenical nature of consequence: it is intrinsically intuitionistic, being classical only in the presence of classical succedents. Also in~\cite{Syn20} a Kripke style semantics for EL was provided, and it was shown how worlds in the semantics could be adequately interpreted as nestings in nested sequents. This also enabled the proposal of an Ecumenical multi-succedent sequent system. In this work, we propose an extension of EL with the alethic modalities of {\em necessity} and {\em possibility}. There are many choices to be made and many relevant questions to be asked, \eg: what is the ecumenical interpretation of Ecumenical modalities? Should we add classical, intuitionistic, or neutral versions for modal connectives? What is really behind the difference between the classical and intuitionistic notions of truth? We propose an answer for these questions in the light of Simpson's meta-logical interpretation of modalities~\cite{Sim94} by embedding the expected semantical behavior of the modal operator into the Ecumenical first order logic. We start by highlighting the main proof theoretical aspects of $\LEci$ (Section~\ref{sec:LEci}). This is vital for understanding how the embedding mentioned above will mold the behavior of Ecumenical modalities, since modal connectives are interpreted in first order logics using quantifiers. In Sections~\ref{sec:modal} and~\ref{sec:emodal}, we justify our choices by following closely Simpson's script, with the difference that we prove meta-logical soundness and completeness using proof theoretical methods only. We then provide an axiomatic and semantical interpretation of Ecumenical modalities in Sections~\ref{sec:ax} and~\ref{sec:bi}. This makes it possible to extend the discussion, in Section~\ref{sec:extensions}, to relational systems with the usual restrictions on the relation in the Kripke model. That Section also brings two very interesting observations about intuitionistic $\K\T$. We end the paper with a discussion about logical Ecumenism in general. \section{The system $\LEci$}\label{sec:LEci} The language $\Lscr$ used for Ecumenical systems is described as follows. We will use a subscript $c$ for the classical meaning and $i$ for the intuitionistic, dropping such subscripts when formulae/connectives can have either meaning. Classical and intuitionistic n-ary predicate symbols ($P_{c}, P_{i},\ldots$) co-exist in $\Lscr$ but have different meanings. The neutral logical connectives $\{\bot,\neg,\wedge,\forall\}$ are common for classical and intuitionistic fragments, while $\{\iimp,\ivee,\iexists\}$ and $\{\cimp,\cvee,\cexists\}$ are restricted to intuitionistic and classical interpretations, respectively. The sequent system $\LEci$ was presented in~\cite{Syn20} as the sequent counterpart of Prawitz natural deduction system. The rules of $\LEci$ are depicted in Fig.~\ref{Fig:LEci}. Observe that the rules $R_c$ and $L_c$ describe the intended meaning of a classical predicate $P_{c}$ from an intuitionistic predicate $P_i$, $\LEci$ has very interesting proof theoretical properties, together with a Kripke semantical interpretation, that allowed the proposal of a variety of ecumenical proof systems, such as a multi-conclusion and a nested sequent systems, as well as several fragments of such systems~\cite{Syn20}. \begin{figure}[t] {\sc Initial and structural rules} \[ \infer[\init]{A,\Gamma \seq A}{} \qquad \infer[{\W}]{\Gamma \seq A}{\Gamma \seq \bot} \] {\sc Propositional rules} \[ \infer[{\wedge L}]{A \wedge B,\Gamma \seq C}{ A, B,\Gamma \seq C} \quad \infer[{\wedge R}]{\Gamma \seq A \wedge B}{\Gamma \seq A \quad \Gamma \seq B} \quad \infer[{\vee_i L}]{A \vee_i B,\Gamma \seq C}{A,\Gamma \seq C \quad B,\Gamma \seq C} \quad \infer[{\vee_i R_j}]{\Gamma \seq A_1\vee_i A_2}{\Gamma \seq A_j} \] \[ \infer[\vee_cL]{ A \vee_c B,\Gamma \seq\bot }{A,\Gamma \seq \bot & B, \Gamma \seq \bot} \quad \infer[\vee_cR]{\Gamma \seq \ A \vee_c B}{\Gamma, \neg A , \neg B \seq \bot} \quad \infer[{\iimp L}]{\Gamma, A\iimp B \seq C} {A\iimp B,\Gamma \seq A \quad B, \Gamma \seq C} \] \[ \infer[{\iimp R}]{\Gamma \seq A\iimp B}{\Gamma, A \seq B} \quad \infer[\cimp L]{ A \rightarrow_c B,\Gamma \seq\bot }{ A \rightarrow_c B,\Gamma \seq A & B,\Gamma \ \seq \bot} \quad \infer[\cimp R]{\Gamma \seq A \rightarrow_c B}{\Gamma, A , \neg B \seq \bot} \] \[ \infer[{\neg L}]{\neg A,\Gamma \seq \bot }{ \neg A,\Gamma \seq A} \quad \infer[{\neg R}]{\Gamma \seq \neg A}{\Gamma, A \seq \bot} \quad \infer[{\bot L}]{\bot,\Gamma \seq A}{} \quad \infer[L_c]{ P_c,\Gamma\seq\bot}{P_i,\Gamma\seq \bot } \quad \infer[R_c]{\Gamma \seq P_c}{\Gamma,\neg P_i \seq\bot} \] {\sc Quantifiers} \[ \infer[\forall L]{\forall x.A,\Gamma \seq C }{A[y/x],\forall x.A,\Gamma \seq C} \quad \infer[\forall R]{\Gamma \seq \forall x.A }{\Gamma \seq A[y/x]} \] \[ \infer[\exists_i L]{ \exists_ix.A,\Gamma \seq C}{A[y/x],\Gamma \seq C} \quad \infer[\exists_i R]{\Gamma \seq \exists_ix.A }{\Gamma \seq A[y/x]} \quad \infer[\exists_c L]{\exists_cx.A,\Gamma \seq \bot}{A[y/x],\Gamma \seq \bot} \quad \infer[\exists_c R]{\Gamma \seq \exists_cx.A}{\Gamma, \forall x.\neg A \seq \bot} \] \caption{Ecumenical sequent system $\LEci$. In rules $\forall R,\iexists L,\cexists L$, the eigenvariable $y$ is fresh.}\label{Fig:LEci} \end{figure} Denoting by $\vdash_{\mathsf{S}} A$ the fact that the formula $A$ is a theorem in the proof system $\mathsf{S}$, the following theorems are easily provable in $\LEci$: \begin{enumerate} \item\label{neg} $\vdash_{\LEci} (A \to_c \bot) \leftrightarrow_i (A \to_i \bot) \leftrightarrow_i (\neg A)$; \item\label{and} $\vdash_{\LEci} (A \vee_c B) \leftrightarrow_i \neg (\neg A \wedge \neg B)$; \item\label{or} $\vdash_{\LEci} (A \to_c B) \leftrightarrow_i \neg (A \wedge \neg B)$; \item\label{foe1} $\vdash_{\LEci} (\exists_cx.A) \leftrightarrow_i \neg (\forall x.\neg A)$. \end{enumerate} Note that~(\ref{neg}) means that the Ecumenical system defined in Fig.~\ref{Fig:LEci} does not distinguish between intuitionistic or classical negations, thus they can be called simply $\neg A$. We prefer to keep the negation operator in the language since the calculi presented in this work make heavy use of it. Theorems (\ref{and}) to (\ref{foe1}) are of interest since they relate the classical and the neutral operators: the classical connectives can be defined using negation, conjunction, and the universal quantifier. On the other hand, \begin{enumerate} \setcounter{enumi}{4} \item $\vdash_{\LEci} (A \to_i B) \to_i (A \to_c B)$ but $\not\vdash_{\LEci} (A \to_c B) \to_i (A \to_i B)$ in general; \item $\vdash_{\LEci} A\vee_c\neg A$ but $\not\vdash_{\LEci} A\vee_i\neg A $ in general; \item $\vdash_{\LEci} (\neg\neg A) \to_c A $ but $\not\vdash_{\LEci} (\neg\neg A) \to_i A $ in general; \item\label{mp} $\vdash_{\LEci} (A\wedge(A \to_i B)) \to_i B$ but $\not\vdash_{\LEci} (A\wedge(A \to_c B)) \to_i B $ in general; \item\label{foe2} $\vdash_{\LEci} \forall x.A \iimp \neg \exists_cx.\neg A $ but $\not\vdash_{\LEci} \neg\exists_cx.\neg A \to_i \forall x.A$ in general. \end{enumerate} Observe that~(\ref{foe1}) and~(\ref{foe2}) reveal the asymmetry between definability of quantifiers: while the classical existential can be defined from the universal quantification, the other way around is not true, in general. This is closely related with the fact that, proving $\forall x.A$ from $\neg\exists_cx.\neg A$ depends on $A$ being a classical formula. We will come back to this in Section~\ref{sec:modal}. On its turn, the following result states that logical consequence in $\LEci$ is intrinsically intuitionistic. \begin{proposition}[\cite{Syn20}]\label{prop:ev} $\Gamma\vdash B$ is provable in $\LEci$ iff $\vdash_{\LEci}\bigwedge\Gamma\iimp B$. \end{proposition} To preserve the ``classical behaviour'', \ie, to satisfy all the principles of classical logic \eg\ {\em modus ponens} and the {\em classical reductio}, it is sufficient that the main operator of the formula be classical (see~\cite{luiz17}). Thus, ``hybrid" formulas, \ie, formulas that contain classical and intuitionistic operators may have a classical behaviour. Formally, \begin{definition} A formula $B$ is called \textit{externally classical} (denoted by $B^{c}$) if and only if $B$ is $\bot$, a classical predicate letter, or its root operator is classical (that is: $\cimp,\vee_c,\exists_c$). A formula $C$ is {\em classical} if it is built from classical atomic predicates using only the connectives: $\cimp,\vee_c,\exists_c,\neg, \wedge,\forall$, and the unit $\bot$. \end{definition} For externally classical formulas we can now prove the following theorems \begin{enumerate} \setcounter{enumi}{9} \item $\vdash_{\LEci} (A \to_c B^{c}) \to_i (A \to_i B^{c})$. \item $\vdash_{\LEci} (A\wedge(A \to_c B^{c})) \iimp B^{c} $. \item $\vdash_{\LEci} \neg\neg B^c\iimp B^c$. \item $\vdash_{\LEci} \neg\exists_cx.\neg B^c \to_i \forall x.B^c$. \end{enumerate} Moreover, notice that all classical right rules as well as the right rules for the neutral connectives in $\LEci$ are invertible. Since invertible rules can be applied eagerly when proving a sequent, this entails that classical formulas can be eagerly decomposed. As a consequence, the Ecumenical entailment, when restricted to classical succedents (antecedents having an unrestricted form), is classical. \begin{theorem}[\cite{Syn20}]\label{thm:classical-right} Let $C$ be a classical formula and $\Gamma$ be a multiset of Ecumenical formulas. Then $$\vdash_{\LEci}\bigwedge\Gamma\cimp C \mbox{ iff } \vdash_{\LEci}\bigwedge\Gamma\iimp C.$$ \end{theorem} This sums up well, proof theoretically, the {\em ecumenism} of Prawitz' original proposal. \section{Ecumenical modalities}\label{sec:modal} In this section we will propose an ecumenical view for alethic modalities. Since there are a number of choices to be made, we will construct our proposal step-by-step. \subsection{Normal modal logics}\label{sec:nml} The language of \emph{(propositional, normal) modal formulas} consists of a denumerable set $\Prop$ of propositional symbols and a set of propositional connectives enhanced with the unary \emph{modal operators} $\square$ and $\lozenge$ concerning necessity and possibility, respectively~\cite{blackburn_rijke_venema_2001}. The semantics of modal logics is often determined by means of \emph{Kripke models}. Here, we will follow the approach in~\cite{Sim94}, where a modal logic is characterized by the respective interpretation of the modal model in the meta-theory (called {\em meta-logical characterization}). Formally, given a variable $x$, we recall the standard translation $\tradm{\cdot}{x}$ from modal formulas into first-order formulas with at most one free variable, $x$, as follows: if $P$ is atomic, then $\tradm{P}{x}=P(x)$; $\tradm{\bot}{x}=\bot$; for any binary connective $\star$, $\tradm{A\star B}{x}=\tradm{A}{x}\star \tradm{B}{x}$; for the modal connectives \begin{center} \begin{tabular}{lclc@{\quad}lcl} $\tradm{\square A}{x}$ & = & $\forall y ( \relfo(x,y) \rightarrow \tradm{A}{y})$ & & $\tradm{\lozenge A}{x}$ & = & $\exists y (\relfo(x,y) \wedge \tradm{A}{y})$ \\ \end{tabular} \end{center} where $\rel(x,y)$ is a binary predicate. Opening a parenthesis: such a translation has, as underlying justification, the interpretation of alethic modalities in a Kripke model $\m=(W,R,V)$: \begin{equation}\label{eq:kripke} \begin{array}{l@{\qquad}c@{\qquad}l} \m, w \models \square A & \mbox{ iff } & \text{for all } v \text{ such that }w \rel v, \m, v \models A.\\ \m, w \models \lozenge A & \mbox{ iff } & \text{there exists } v \text{ such that } w \rel v \text{ and } \m, v\models A. \end{array} \end{equation} $\rel(x,y)$ then represents the \emph{accessibility relation} $R$ in a Kripke frame. This intuition can be made formal based on the one-to-one correspondence between classical/intuitionistic translations and Kripke modal models~\cite{Sim94}. We close this parenthesis by noting that this justification is only motivational, aiming at introducing modalities. Models will be discussed formally in Section~\ref{sec:bi}. The object-modal logic OL is then characterized in the first-order meta-logic ML as $$ \vdash_{OL} A \quad\mbox{ iff } \quad \vdash_{ML} \forall x. \tradm{A}{x} $$ Hence, if ML is classical logic (CL), the former definition characterizes the classical modal logic $\logick$~\cite{blackburn_rijke_venema_2001}, while if it is intuitionistic logic (IL), then it characterizes the intuitionistic modal logic $\logicik$~\cite{Sim94}. In this work, we will adopt EL as the meta-theory (given by the system $\LEci$), hence characterizing what we will defined as the {ecumenical modal logic} $\EK$. \subsection{An Ecumenical view of modalities}\label{sec:view} The language of \emph{Ecumenical modal formulas} consists of a denumerable set $\Prop$ of (Ecumenical) propositional symbols and the set of Ecumenical connectives enhanced with unary \emph{Ecumenical modal operators}. Unlike for the classical case, there is not a canonical definition of constructive or intuitionistic modal logics. Here we will mostly follow the approach in~\cite{Sim94} for justifying our choices for the Ecumenical interpretation for {\em possibility} and {\em necessity}. The ecumenical translation $\tradme{\cdot}{x}$ from propositional ecumenical formulas into $\LEci$ is defined in the same way as the modal translation $\tradm{\cdot}{x}$ in the last section. For the case of modal connectives, observe that, due to Proposition~\ref{prop:ev}, the interpretation of ecumenical consequence should be essentially {\em intuitionistic}. With this in mind, the semantical description of $ \square A$ given by~\eqref{eq:kripke} should be understood, for an arbitrary $v$, as: {\em assuming that $wRv$, then $A$ is satisfied in $v$}. Or: \begin{center} {\em $A$ is satisfied in $v$ is a consequence of the fact that $wRv$.} \end{center} This implies that the box modality is a {\em neutral connective}. The diamond, on the other hand, has two possible interpretations: classical and intuitionistic, since its leading connective is an existential quantifier. Hence we should have the ecumenical modalities: $\square, \ilozenge, \clozenge$, determined by the translations \begin{center} \begin{tabular}{lclc@{\qquad}lcl} $\tradme{\square A}{x}$ & = & $\forall y ( \relfo(x,y) \iimp \tradme{A}{y})$\\ $\tradme{\ilozenge A}{x}$ & = & $\iexists y (\relfo(x,y) \wedge \tradme{A}{y})$ & & $\tradme{\clozenge A}{x}$ & = & $\cexists y (\relfo(x,y) \wedge \tradme{A}{y})$ \\ \end{tabular} \end{center} Observe that, due to the equivalence~(\ref{foe1}), we have \begin{enumerate} \setcounter{enumi}{13} \item $\clozenge A\iequiv \neg\square\neg A$ \end{enumerate} On the other hand, $\square$ and $\ilozenge$ are not inter-definable due to (\ref{foe2}). Finally, if $A^c$ is externally classical, then \begin{enumerate} \setcounter{enumi}{14} \item $\square A^c\iequiv \neg\clozenge\neg A^c$ \end{enumerate} This means that, when restricted to the classical fragment, $\square$ and $\clozenge$ are duals. This reflects well the ecumenical nature of the defined modalities. We will denote by $\EK$ the Ecumenical modal logic meta-logically characterized by $\LEci$ via $\tradme{\cdot}{x}$. \section{A labeled system for $\EK$}\label{sec:emodal} \begin{figure}[t] {\sc Initial and structural rules} \[ \infer[\init]{ x:A,\Gamma \vdash x:A}{} \quad \infer[{\W}]{\Gamma \vdash x:A}{\Gamma \vdash y:\bot} \] {\sc Propositional rules} \[ \infer[\wedge L]{ x:A\wedge B,\Gamma \vdash z:C}{ x:A, x:B,\Gamma \vdash z:C} \quad \infer[\wedge R]{\Gamma \vdash x:A \wedge B} {\Gamma \vdash x:A & \Gamma \vdash x:B} \] \[ \infer[\ivee L]{x: A \ivee B,\Gamma \vdash z:C} {x:A,\Gamma \vdash z:C & x:B,\Gamma \vdash z:C} \quad \infer[\ivee R_j]{\Gamma \vdash x:A_1 \ivee A_2}{\Gamma \vdash x:A_j} \] \[ \infer[\cvee L]{x: A \cvee B,\Gamma \vdash x:\bot} {x:A,\Gamma \vdash x:\bot & x:B,\Gamma \vdash x:\bot} \quad \infer[\cvee R]{\Gamma \vdash x:A \cvee B}{\Gamma,x:\neg A,x:\neg B \vdash x:\bot} \] \[ \infer[\iimp L]{x:A \iimp B,\Gamma \vdash z:C} {x:A \iimp B,\Gamma \vdash x:A & x:B,\Gamma \vdash z:C} \quad \infer[\iimp R]{\Gamma \vdash x:A \iimp B}{x:A,\Gamma \vdash x:B} \] \[ \infer[\cimp L]{x:A \cimp B,\Gamma \vdash x:\bot} {x:A \cimp B,\Gamma \vdash x:A & x:B,\Gamma \vdash y: \bot} \quad \infer[\cimp R]{\Gamma \vdash x:A \cimp B}{x:A,x:\neg B,\Gamma \vdash x: \bot} \] \[ \infer[{\neg L}]{x:\neg A,\Gamma \vdash x:\bot }{x:\neg A,\Gamma \vdash x:A} \quad \infer[{\neg R}]{\Gamma \vdash x:\neg A}{x:A,\Gamma \vdash x:\bot} \quad \infer[\bot]{x:\bot, \Gamma \vdash z:C}{} \] \[ \infer[L_c]{\Gamma, x:P_c\vdash x:\bot}{\Gamma, x:P_i\vdash x:\bot } \quad \infer[R_c]{\Gamma \vdash x:P_c}{\Gamma,x:\neg P_i \vdash x:\bot} \] {\sc Modal rules} \[ \infer[\square L]{xRy, x:\Box A,\Gamma \vdash z:C}{ xRy,y:A,x:\Box A,\Gamma \vdash z:C} \quad \infer[\square R]{\Gamma \vdash x:\Box A}{xRy, \Gamma \vdash y:A} \quad \infer[\ilozenge L]{x:\ilozenge A,\Gamma \vdash z:C}{xRy, y: A,\Gamma \vdash z:C} \] \[ \infer[\ilozenge R]{xRy, \Gamma \vdash x:\ilozenge A}{xRy,\Gamma \vdash y:A} \quad \infer[\clozenge L]{x:\clozenge A,\Gamma \vdash x:\bot}{xRy, y: A,\Gamma \vdash x:\bot} \quad \infer[\clozenge R]{\Gamma \vdash x:\clozenge A}{x:\Box\neg A,\Gamma \vdash x:\bot} \] \caption{Ecumenical modal system $\labEK$. In rules $\square R,\ilozenge L, \clozenge L$, the eigenvariable $y$ does not occur free in any formula of the conclusion.} \label{fig:EK} \end{figure} One of the advantages of having an Ecumenical framework is that some well known classical/intuitionistic systems arise as fragments~\cite{Syn20}. In the following, we will seek for such systems by proposing a labeled sequent system for ecumenical modalities. The basic idea behind labeled proof systems for modal logic is to internalize elements of the associated Kripke semantics (namely, the worlds of a Kripke structure and the accessibility relation between them) into the syntax. \emph{Labeled modal formulas} are either \emph{labeled formulas} of the form $x:A$ or \emph{relational atoms} of the form $x \rel y$, where $x, y$ range over a set of variables and $A$ is a modal formula. \emph{Labeled sequents} have the form $\Gamma \vdash x:A$, where $\Gamma$ is a multiset containing labeled modal formulas. Following~\cite{Sim94}, we will prove the following meta-logical soundness and completeness theorem. \begin{theorem}\label{thm:meta} Let $\Gamma$ be a multiset of labeled modal formulas and denote $[\Gamma]=\{\rel(x,y)\mid xRy\in\Gamma\}\cup \{\tradme{B}{x}\mid x:B\in\Gamma\}$. The following are equivalent: \begin{enumerate} \item[1.] $\Gamma\vdash x:A$ is provable in $\labEK$. \item[2.] $[\Gamma]\seq \tradme{A}{x}$ is provable in $\LEci$. \end{enumerate} \end{theorem} \begin{proof} We will consider the following translation between $\labEK$ rule applications and $\LEci$ derivations, where the translation for the propositional rules is the trivial one: \begin{align*} \vcenter{ \infer[\square L]{xRy,x:\square A,\Gamma\vdash z:C}{xRy,y: A,x:\square A,\Gamma\vdash z:C} } &\quad\leadsto\quad \\ \multispan2{$\hspace*{-2cm} \vcenter{ \infer=[(\forall L, \iimp L)]{ \rel(x,y),\forall y.(\rel(x,y)\iimp\tradme{A}{y}),[\Gamma]\seq\tradme{C}{z} }{ \infer{\rel(x,y),\forall y.(\rel(x,y)\iimp\tradme{A}{y}), \rel(x,y)\iimp\tradme{A}{y}, [\Gamma]\seq \rel(x,y)}{} & \deduce{\rel(x,y),\tradme{A}{y},\forall y.(\rel(x,y)\iimp\tradme{A}{y}),[\Gamma]\seq\tradme{C}{z}}{}& } } $} \end{align*} \begin{align*} & \vcenter{ \infer[\square R]{\Gamma\vdash x:\square A}{xRy,\Gamma\vdash y: A} } & \quad\leadsto\quad & \vcenter{ \infer=[(\forall R, \iimp R)]{[\Gamma]\seq \forall y.(\rel(x,y)\iimp\tradme{A}{y})} {\rel(x,y),[\Gamma]\seq \tradme{A}{y}} } \\& \vcenter{ \infer[\lozenge_i L]{x:\ilozenge A,\Gamma\vdash z:C}{xRy,y:A,\Gamma\vdash z:C} } & \quad\leadsto\quad & \vcenter{ \infer=[(\iexists L, \wedge L)]{\iexists y.(\rel(x,y)\wedge\tradme{A}{y}),[\Gamma]\seq \tradme{C}{z}}{\rel(x,y),\tradme{A}{y},[\Gamma]\seq \tradme{C}{z}} } \\& \vcenter{ \infer[\lozenge_c L]{x:\clozenge A,\Gamma\vdash x:\bot}{xRy,y:A,\Gamma\vdash x:\bot} } & \quad\leadsto\quad & \vcenter{ \infer=[(\cexists L, \wedge L)]{\cexists y.(\rel(x,y)\wedge\tradme{A}{y}),[\Gamma]\seq \bot} {\rel(x,y),\tradme{A}{y},[\Gamma]\seq \bot} } \\& \vcenter{ \infer[\lozenge_i R]{ xRy,\Gamma\vdash x:\ilozenge A }{ xRy,\Gamma\vdash y: A} } & \quad\leadsto\quad & \vcenter{ \infer=[(\iexists R, \wedge R)]{ \rel(x,y),[\Gamma]\seq \iexists y.(\rel(x,y)\wedge\tradme{A}{y}) }{ \infer{\rel(x,y),[\Gamma]\seq \rel(x,y)}{} & \deduce{\rel(x,y),[\Gamma]\seq \tradme{A}{y}}{} } } \\& \vcenter{ \infer[\lozenge_c R]{\Gamma\vdash x:\clozenge A}{x:\Box\neg A,\Gamma\vdash x:\bot} } & \quad\leadsto\quad & \vcenter{ \infer[(\cexists R)]{[\Gamma]\seq \cexists y.(\rel(x,y)\wedge\tradme{A}{y})} {\forall y.\neg(\rel(x,y)\wedge\tradme{A}{y}),[\Gamma]\seq\bot} } \end{align*} $(1)\Rightarrow(2)$ is then easily proved by induction on a proof of $\Gamma\vdash x:A$ in $\labEK$. For proving $(2)\Rightarrow(1)$ observe that \begin{itemize} \item the rules $\iimp R,\wedge L, \wedge R$ are invertible in $\LEci$ and $\iimp L$ is semi-invertible on the right (\ie~if its conclusion is valid, so is its right premise); \item $\vdash_{\LEci}\forall y.\neg (\rel(x,y)\wedge \tradme{A}{y})\leftrightarrow_i \forall y.\rel(x,y)\iimp\tradme{\neg A}{y}$. \end{itemize} Hence, in the translated derivations in $\LEci$ {\em provability} is maintained from the end-sequent to the open leaves. This means that choosing a formula $\tradme{B}{x}$ to work on is equivalent to performing all the steps of the translation given above. Therefore, any derivation of $[\Gamma]\vdash\tradme{A}{x}$ in $\LEci$ can be transformed into a derivation of the same sequent where all the steps of the translation are actually performed. This is, in fact, one of the pillars of the {\em focusing} method ~\cite{andreoli01apal,DBLP:journals/apal/LiangM11}. In order to illustrate this, consider the derivation \begin{center} $ \infer[(\forall L)]{\rel(x,y),\tradme{\Box A}{x},[\Gamma]\seq\tradme{C}{z}} {\deduce{\rel(x,y),\rel(x,y)\iimp\tradme{A}{y},\tradme{\Box A}{x},[\Gamma]\seq\tradme{C}{z}}{\pi}} $ \end{center} where one decides to work on the formula $\forall y.(\rel(x,y)\iimp\tradme{A}{y})=\tradme{\Box A}{x}$ obtaining a premise containing the formula $\rel(x,y)\iimp\tradme{A}{y}$, with proof $\pi$. Since $\iimp L$ is semi-invertible on the right and the left premise is straightforwardly provable, then $\pi$ can be substituted by the proof: \begin{center} $ \infer[\iimp L]{ \rel(x,y),\rel(x,y)\iimp\tradme{A}{y},\tradme{\Box A}{x},[\Gamma]\seq\tradme{C}{z} }{ \infer{\rel(x,y),\rel(x,y)\iimp\tradme{A}{y},\tradme{\Box A}{x},[\Gamma]\seq\rel(x,y)}{} & \deduce{\rel(x,y),\tradme{A}{y},\tradme{\Box A}{x},[\Gamma]\seq\tradme{C}{z}}{\pi'} } $ \end{center} Thus, by inductive hypothesis, $[xRy,y:A,x:\Box A,\Gamma\vdash z:C]$ is provable in $\labEK$. \end{proof} Finally, observe that, when restricted to the intuitionistic and neutral operators, $\labEK$ matches {\em exactly} Simpson's sequent system $\mathcal L_{\Box\Diamond}$~\cite{Sim94}. The analyticity of $\labEK$ is presented in Appendix~\ref{sec:cut}. \section{Axiomatization}\label{sec:ax} So far, we have motivated our discussion on Ecumenical modalities based on Simpson's approach of meta-logical characterization. But what about the axiomatic characterization of $\EK$? Classical modal logic $\K$ is characterized as propositional classical logic, extended with the \emph{necessitation rule} (presented in Hilbert style) $ A/\square A $ and the \emph{distributivity axiom} $ \ka:\;\square(A\ra B)\ra (\square A\ra\square B) $. Intuitionistic modal logic should then consist of propositional intuitionistic logic plus necessitation and distributivity. The problem is that there are many variants of axiom $\ka$ that induces classically, but not intuitionistically, equivalent systems. In fact, the following axioms classically follow from $\ka$ and the De Morgan laws, but not in an intuitionistic setting \begin{center} $ \begin{array}{lc@{\qquad}l} \ka_1:\;\square(A\ra B)\ra (\lozenge A\ra\lozenge B) & & \ka_2:\;\lozenge(A\vee B)\ra (\lozenge A\vee\lozenge B)\\ \ka_3:\;(\lozenge A\ra \square B)\ra \square(A\ra B) & & \ka_4:\;\lozenge \bot\ra\bot \end{array} $ \end{center} The combination of axiom $\ka$ with axioms $\ka_1$ to $\ka_4$ then exactly characterizes intuitionistic modal logic $\IK$~\cite{plotkin:stirling:86,Sim94}. In the ecumenical setting, there are many more variants from $\ka$, depending on the classical or intuitionistic interpretation of the implication and diamond. It is easy to see that the intuitionistic versions of the above axioms are provable in $\EK$ (see Appendix~\ref{app}). Hence, by combining this result with cut-elimination (Appendix~\ref{sec:cut}), $\EK$ is {\em complete} w.r.t.~this set of axioms. Observe that, since the intuitionistic operators imply the classical ones, if we substitute $i$ by $c$, the resulting clause is either not provable in $\EK$ or it is a consequence of the intuitionistic versions. Next we will show that $\EK$ is also sound w.r.t.~this set of axioms. For that, we propose an Ecumenical birrelational semantics for $\EK$. The proof passes through a translation from $\labEK$ to $\mathcal L_{\Box\Diamond}$, so we remember that this last labeled system is sound and complete w.r.t. the birelational semantics of $\IK$~\cite{Sim94}. \section{Ecumenical birelational models}\label{sec:bi} In~\cite{DBLP:journals/jlp/Avigad01}, the negative translation was used to relate cut-elimination theorems for classical and intuitionistic logics. Since part of the argumentation was given semantically, a notion of Kripke semantics for classical logic was stated, via the respective semantics for intuitionistic logic and the double negation interpretation (see also~\cite{DBLP:journals/apal/IlikLH10}). In~\cite{luiz17} a similar definition was given, but under the Ecumenical approach, and it was extended to the first-order case in~\cite{Syn20}. We will propose a birelational Kripke semantics for Ecumenical modal logic, which is an extension of the proposal in~\cite{luiz17} to modalities. \begin{definition}\label{def:ekripke} A {\em birelational Kripke model} is a quadruple $\m=(W,\leq,R,V)$ where $(W,R,V)$ is a Kripke model such that $\wld$ is partially ordered with order $\leq$, the satisfaction function $V:\langle W,\leq\rangle\rightarrow \langle2^\Prop,\subseteq\rangle$ is monotone and: \noindent F1. For all worlds $w,v,v'$, if $wRv$ and $v \leq v'$, there is a $w'$ such that $w \leq w'$ and $w'Rv'$; \noindent F2. For all worlds $w', w, v$, if $w \leq w'$ and $wRv$, there is a $v'$ such that $w'Rv'$ and $v \leq v'$. An {\em Ecumenical modal Kripke model} is a birelational Kripke model such that truth of an ecumenical formula at a point $w$ is the smallest relation $\modelse$ satisfying \noindent $ \begin{array}{l@{\qquad}c@{\qquad}l} \m,w\modelse P_{i} & \mbox{ iff } & P_{i}\in \val(w);\\ \m,w\modelse A\wedge B & \mbox{ iff } & \m,w\modelse A \mbox{ and } \m,w\modelse B;\\ \m,w\modelse A\vee_i B & \mbox{ iff } & \m,w\modelse A \mbox{ or } \m,w\modelse B;\\ \m,w\modelse A\iimp B & \mbox{ iff } & \text{for all } v \text{ such that }w \leq v, \m,v\modelse A \mbox{ implies } \m,v\modelse B;\\ \m,w\modelse \neg A & \mbox{ iff } & \text{for all } v \text{ such that }w \leq v, \m,v\not\modelse A;\\ \m,w \modelse \bot & & \mbox{never holds};\\ \m, w \modelse \square A & \mbox{ iff } & \text{for all } v,w' \text{ such that }w\leq w'\text{ and } w'\rel v, \m, v \modelse A.\\ \m, w \modelse \ilozenge A & \mbox{ iff } & \text{there exists } v \text{ such that } w \rel v \text{ and } \m, v\modelse A. \\ \m,w\modelse P_c & \mbox{ iff } & \m,w\modelse \neg(\neg P_i);\\ \m,w\modelse A\vee_c B & \mbox{ iff } & \m,w\modelse \neg(\neg A\wedge \neg B);\\ \m,w\modelse A\cimp B & \mbox{ iff } & \m,w\modelse \neg(A\wedge \neg B).\\ \m, w \modelse \clozenge A & \mbox{ iff } & \m,w\modelse \neg\square\neg A. \end{array} $ \end{definition} Since, restricted to intuitionistic and neutral connectives, $\modelse$ is the usual birelational interpretation $\models$ for $\IK$ (and, consequently, $\mathcal L_{\Box\Diamond}$ \cite{Sim94}), and since the classical connectives are interpreted via the neutral ones using the double-negation translation, an Ecumenical modal Kripke model is nothing else than the standard birelational Kripke model for intuitionistic modal logic $\IK$. Hence, it is not hard to prove soundness and completeness of the semantical interpretation above w.r.t. the sequent system $\labEK$. We start by defining a translation from $\labEK$ to $\mathcal L_{\Box\Diamond}$. We will abuse the notation and represent the connectives of $\IK/\mathcal L_{\Box\Diamond}$ using the neutral/intuitionistic correspondents in $\EK/\labEK$. \begin{definition}\label{def:transS} Let $\tradmk{\cdot}$ be the translation between formulas in $\EK$ and $\IK$ recursively defined as \noindent $ \begin{array}{lclc@{\qquad}lcl} \tradmk{P_i} & = & P_i & & \tradmk{P_c} & = & \neg(\neg(P_i))\\ \tradmk{\bot} & = & \bot & & \tradmk{\neg A} & = & \neg \tradmk{A}\\ \tradmk{A\wedge B} & = & \tradmk{A}\wedge\tradmk{B} & & \tradmk{A\ivee B} & = & \tradmk{A}\ivee\tradmk{B}\\ \tradmk{A\iimp B} & = & \tradmk{A}\iimp\tradmk{B} & & \tradmk{A\cvee B} & = & \neg(\neg\tradmk{A}\wedge\neg\tradmk{B})\\ \tradmk{A\cimp B} & = & \neg(\tradmk{A}\wedge\neg\tradmk{B})& & \tradmk{\Box A} & = & \Box \tradmk{A}\\ \tradmk{\ilozenge A} & = & \ilozenge \tradmk{A} & & \tradmk{\clozenge A} & = & \neg\Box\neg \tradmk{A}\\ \end{array} $\\ \noindent The translation $\tradms{\cdot}:\labEK\to \mathcal L_{\Box\Diamond}$ is defined as $\tradms{x:A}=x:\tradmk{A}$ and assumed identical on relational atoms. \end{definition} Since the translations above preserve the double-negation interpretation of classical connectives into intuitionistic (modal) logic, it is possible to prove: \begin{lemma}\label{lem:trad1} $\vdash_{\labEK} \Gamma\vdash x:A$ iff $\vdash_{\labEK}\tradms{\Gamma\vdash x:A}$ iff $\vdash_{\mathcal L_{\Box\Diamond}}\tradms{\Gamma\vdash x:A}$. \end{lemma} \begin{lemma}\label{lem:trad3} Let $A$ be a formula in $\EK$. Then $\modelse A$ iff $\models \tradmk{A}$. \end{lemma} \begin{proof} First of all, note that an Ecumenical modal Kripke model is totally determined by the valuation of the (intuitionistic) propositional variables. The proof follows then by easy structural induction on the formula $A$. For example, if $A=\clozenge B$ then $\modelse A$ iff $\modelse \neg\Box\neg B$. By inductive hypothesis, $\modelse B$ iff $\models \tradmk{B}$. Since $\neg$ and $\Box$ are neutral operators, then $\modelse\neg\Box\neg B$ and iff $\models \neg\Box\neg \tradmk{B}$. \end{proof} Now, observe that every formula in $\IK$ is a formula in $\EK$, hence the following theorem holds. \begin{theorem}\label{thm:scLEci} $\EK$ is sound and complete w.r.t.~the Ecumenical modal Kripke semantics, that is, $\vdash_{\EK} A$ iff $\modelse A$. \end{theorem} Moreover, $\EK$ is sound and complete w.r.t. the axioms $\ka-\ka_4$ presented in Section~\ref{sec:ax}. \section{Extensions}\label{sec:extensions} Depending on the application, several further modal logics can be defined as extensions of $\K$ by simply restricting the class of frames we consider. Many of the restrictions one can be interested in are definable as formulas of first-order logic, where the binary predicate $\rel(x,y)$ refers to the corresponding accessibility relation. Table \ref{tab:axioms-FOconditions} summarizes some of the most common logics, the corresponding frame property, together with the modal axiom capturing it~\cite{Sah75}. In the Ecumenical setting, we adopt the motto that ``relational predicates are second order citizens'' suggested in Section~\ref{sec:view} and interpret the implications in the axioms intuitionisticaly. We will refer to the ecumenical logic satisfying the axioms $F_1,\ldots, F_n$ as $\EK F_1\ldots F_n$. We conjecture that the semantics of a given logic $\EK F_1 \ldots F_n$ can be inferred from the one for $\EK$ of Definition $\ref{def:ekripke}$: We just consider Ecumenical models whose accessibility relation satisfies the set of properties $\{F_1, \ldots, F_n\}$ in place of generic Ecumenical models. \begin{table}[t] \begin{center} \begin{tabular}{|c|c|c|} \hline \textbf{Axiom} & \textbf{Condition} & \textbf{First-Order Formula} \\ \hline $\T:\,\square A \rightarrow A \wedge A \rightarrow \lozenge A$ & Reflexivity & $\forall x. \rel(x,x)$ \\ \hline $\4:\,\square A \rightarrow \square \square A \wedge \lozenge\lozenge A \rightarrow \lozenge A$ & Transitivity & $\forall x,y,z. (\rel(x,y) \wedge \rel(y,z)) \rightarrow \rel(x,z)$ \\ \hline $\5:\,\square A \rightarrow \square \lozenge A \wedge \lozenge\square A \rightarrow \lozenge A$ & Euclideaness & $\forall x,y,z. (\rel(x,y) \wedge \rel(x,z)) \rightarrow \rel(y,z)$ \\ \hline $\B:\,A \rightarrow \square \lozenge A \wedge\lozenge \square A \rightarrow A$ & Symmetry & $\forall x,y. \rel(x,y) \rightarrow \rel(y,x)$ \\ \hline \end{tabular} \end{center} \caption{Axioms and corresponding first-order conditions on $\rel$.} \label{tab:axioms-FOconditions} \end{table} Furthermore, following the approaches in~\cite{Sim94,Vig00,Neg05}, we can transform the axioms in Table~\ref{tab:axioms-FOconditions} into rules. In future work, we would like to investigate how these rules behave w.r.t~the ecumenical setting. \begin{figure}[t] \[ \infer[\T]{\Gamma\vdash w:C}{xRx,\Gamma\vdash w:C} \quad \infer[\4]{xRy,yRz,\Gamma\vdash w:C}{xRz,xRy,yRz,\Gamma\vdash w:C} \]\[ \infer[\5]{xRy,xRz,\Gamma\vdash w:C}{yRz,xRy,xRz,\Gamma\vdash w:C} \quad \infer[\B]{xRy,\Gamma\vdash w:C}{yRx,xRy,\Gamma\vdash w:C} \] \caption{Labeled sequent rules corresponding to axioms in Table~\ref{tab:axioms-FOconditions}. } \label{fig:extK} \end{figure} As a first step in this research direction, we finish this section with two very interesting observations about the case of axiom $\T$, illustrating the complexity of the interaction of modal axioms and ecumenical connective. First of all, recall~\cite{Sim94,DBLP:conf/fossacs/Strassburger13} that by itself, $\square A \iimp A$ does not enforce reflexivity of an intuitionistic model. In fact, in frames having the reflexivity property, both $\square A \iimp A$ and $A \iimp \ilozenge A$ are provable. \[ \infer[\wedge R]{xRx \vdash x: (\square A\iimp A) \wedge (A\iimp \ilozenge A)} {\infer[\iimp R]{xRx \vdash x:\square A\iimp A}{\infer[\square L]{xRx, x:\square A \vdash x: A}{\infer[\init]{xRx, x: A \vdash x: A}{}}}&\infer[\iimp R]{xRx \vdash x: A \iimp \ilozenge A}{\infer[\ilozenge R]{xRx, x: A \vdash x: \ilozenge A}{\infer[\init]{xRx, x: A \vdash x: A}{}}}} \] For the converse, since $\square$ and $\ilozenge$ are not inter-definable, we need to add $A \iimp \ilozenge A$ in order to still be complete w.r.t. reflexive models. Finally, it is well known that the set intuitionistic propositional operators is ``independent'', \ie, that each operator cannot be defined in terms of the others (Prawitz proposed a syntactical proof of this result in~\cite{prawitz1965}). It is also known that in the case of (many) constructive modal logics the modal operators $\Box$ and $\lozenge$ are independent of each other, as it is the case in $\EK$. But what would be the consequence of adding $\neg\ilozenge\neg A\iimp \Box A$ as an extra axiom to $\EK$? The following derivation shows that the addition of this new axiom has a disastrous propositional consequence. $$\small \infer[\cut]{\vdash x:(A\ivee\neg A)} {\infer[eq]{\vdash x:\Box (A\ivee\neg A)} {\infer[\neg R]{\vdash x:\neg\ilozenge\neg (A\ivee\neg A)} {\infer[\ilozenge L]{x:\ilozenge\neg (A\ivee\neg A)\vdash x:\bot} {\infer=[\neg L,\ivee R2,\neg R]{xRy,y:\neg (A\ivee\neg A)\vdash x:\bot} {\infer[\neg L,\ivee R1]{xRy,y:A, y:\neg (A\ivee\neg A)\vdash y:\bot} {\infer[\init]{xRy,y:A, y:\neg (A\ivee\neg A)\vdash y:A}{}}}}}}& \infer[\T]{x:\Box (A\ivee\neg A)\vdash x:(A\ivee\neg A)} {\infer[\Box L]{xRx,x:\Box (A\ivee\neg A)\vdash x:(A\ivee\neg A)} {\infer[\init]{xRx,x: (A\ivee\neg A)\vdash x:(A\ivee\neg A)}{}}}} $$ where $eq$ represents the proof steps of the substitution of a boxed formula for its diamond version.\footnote{We have presented a proof with $\cut$ for clarity, remember that $\labEK$ has the cut-elimination property (see Appendix~\ref{sec:cut}).} That is, if $\Box$ and $\lozenge_i$ are inter-definable, then $A\vee_i\neg A$ is a theorem and intuitionistic $\K\T$ collapses to a classical system! \section{Discussion and conclusion}\label{sec:conc} Some questions naturally arise with respect to Ecumenical systems: what (really) are Ecumenical systems? What are they good for? Why should anyone be interested in Ecumenical systems? What is the real motivation behind the definition and development of Ecumenical systems? Based on the specific case of the Ecumenical system that puts classical logic and intuitionist logic coexisting in peace in the same codification, we would like to propose three possible motivations for the definition, study and development of Ecumenical systems. \paragraph{Philosophical motivation} This was the motivation of Prawitz. Inferentialism, and in particular, logical inferentialism, is the semantical approach according to which the meaning of the logical constants can be specified by the rules that determine their correct use. According to Prawitz~\cite{DBLP:journals/Prawitz15}, \begin{quote} {\em ``Gentzen's introduction rules, taken as meaning constitutive of the logical constants of the language of predicate logic, agree, as is well known, with how intuitionistic mathematicians use the constants. On the one hand, the elimination rules stated by Gentzen become all justified when the constants are so understood because of there being reductions, originally introduced in the process of normalizing natural deductions, which applied to proofs terminating with an application of elimination rules give canonical proofs of the conclusion in question. On the other hand, no canonical proof of an arbitrarily chosen instance of the law of the excluded middle is known, nor any reduction that applied to a proof terminating with an application of the classical form of reductio ad absurdum gives a canonical proof of the conclusion.''} \end{quote} But what about the use classical mathematicians make of the logical constants? Again, according to Prawitz, \begin{quote} {\em ``What is then to be said about the negative thesis that no coherent meaning can be attached on the classical use of the logical constants? Gentzen's introduction rules are of course accepted also in classical reasoning, but some of them cannot be seen as introduction rules, that is they cannot serve as explanations of meaning. The classical understanding of disjunction is not such that $A\vee B$ may be rightly asserted only if it is possible to prove either A or B, and hence Gentzen's introduction rule for disjunction does not determine the meaning of classical disjunction.''} \end{quote} As an alternative, in a recent paper~\cite{Murzi2018} Murzi presents a different approach to the extension of inferentialism to classical logic. There are some natural (proof-theoretical) inferentialist requirements on admissible logical rules, such as harmony and separability (although harmonic, Prawitz' rules for the classical operators do not satisfy separability). According to Murzi, our usual logical practice does not seem to allow for an inferentialist account of classical logic (unlike what happens with respect to intuitionistic logic). Murzi proposes a new set of rules for classical logical operators based on: absurdity as a punctuation mark, and Higher-level rules~\cite{DBLP:journals/sLogica/Schroeder-Heister14}. This allows for a ``pure'' logical system, where negation is not used in premises. \paragraph{Mathematical/computational motivation} (This was actually the original motivation for proposing Ecumenical systems.) The first Ecumenical system (as far as we know) was defined by Krauss in a technical report of the University of Kassel~\cite{Krauss} (the text was never published in a journal). The paper is divided in two parts: in the first part, Krauss' Ecumenical system is defined and some properties proved. In the second part, some theorems of basic algebraic number theory are revised in the light of this (Ecumenical) system, where constructive proofs of some ``familiar classical proofs'' are given (like the proof of Dirichlet's Unit Theorem). The same motivation can be found in the final passages of the paper~\cite{DBLP:journals/Dowek16a}, where Dowek examines what would happen in the case of axiomatizations of mathematics. Dowek gives a simple example from Set Theory, and ends the paper with this very interesting remark: \begin{quote} {\em ``Which mathematical results have a classical formulation that can be proved from the axioms of constructive set theory or constructive type theory and which require a classical formulation of these axioms and a classical notion of entailment remains to be investigated.''} \end{quote} \paragraph{Logical motivation} In a certain sense, the logical motivation naturally combines certain aspects of the philosophical motivation with certain aspects of the mathematical motivation. According to Prawitz, one can consider the so-called classical first order logic as {\em ``an attempted codification of a fragment of inferences occurring in [our] actual deductive practice''}. Given that there exist different and even divergent attempts to codify our (informal) deductive practice, it is more than natural to ask about what relations are entertained between these codifications. Ecumenical systems may help us to have a better understanding of the relation between classical logic and intuitionistic logic. But one could say that, from a logical point of view, there's nothing new in the ecumenical proposal: Based on translations, the new classical operators could be easily introduced by ``explicit definitions''. Let us consider the following dialogue between a classical logician (CL) and an intuitionistic logician (IL), a dialogue that may arise as a consequence of the translations mentioned above: \begin{itemize} \item IL: if what you mean by $(A \vee B)$ is $\neg (\neg A \wedge \neg B)$, then I can accept the validity of $(A \vee \neg A)$! \item CL: but I do not mean $\neg (\neg A \wedge \neg \neg A)$ by $(A \vee \neg A)$. One must distinguish the excluded-middle from the the principle of non-contradiction. When I say that Goldbach's conjecture is either true or false, I am not saying that it would be contradictory to assert that it is not true and that it is not the case that it is not true! \item IL: but you must realize that, at the end of the day, you just have one logical operator, the Sheffer stroke (or the Quine's dagger). \item CL: But this is not at all true! The fact that we can define one operator in terms of other operators does not imply that we don't have different operators! We do have 16 binary propositional operators (functions). It is also true that we can prove $\vdash (A \vee_{c} B) \leftrightarrow \neg(\neg A \wedge \neg B)$ in the ecumenical system, but this doest not mean that we don't have three different operators, $\neg $, $\vee_{c}$ and $\wedge $. \end{itemize} Maybe we can resume the logical motivation in the following (very simple) sentence: \begin{quote} Ecumenical systems constitute a new and promising instrument to study the nature of different (maybe divergent!) logics. \end{quote} Now, what can we say about {\em modal} Ecumenical systems? Regarding the {\bf philosophical view}, in~\cite{Syn20} we have used invertibility results in order to obtain a sequent system for Prawitz' Ecumenical logic with a minimal occurrences of negations, moving then towards a ``purer'' Ecumenical system. Nevertheless, negation still plays an important r\^{o}le on interpreting classical connectives. This is transferred to our definition of Ecumenical modalities, where the classical possibility is interpreted using negation. We plan to investigate what would be the meaning of classical possibility without impure rules. For the {\bf mathematical view}, our use of intuitionistic/classical/neutral connectives allows for a more chirurgical detection of the parts of a mathematical proof that are intrinsically intuitionistic, classical or independent. We now bring this discussion to modalities. Finally, concerning the {\bf logical view}, it would be interesting to explore some relations between general results on translations and Ecumenical systems, expanding this discussion to modalities. To finish, we would like to say a word about our choices. It seems to be a common view, in the proof theory community, that Simpson's view is the more reasonable approach for modalities and intuitionism. From that, the choice of a labeled proof system for $\EK$ seems only natural. But labeled systems have a very unfortunate feature: it is really tricky to define an interpretation of sequents into the logical language. This problem often disappears when moving to nested-like systems~\cite{Brunnler:2009kx,Poggiolesi:2009vn,DBLP:conf/fossacs/Strassburger13,Lellmann:2015lns}, since the nestings keep the tree-structure information, matching exactly the history of a backwards proof search in an ordinary sequent calculus. Also, having an Ecumenical nested system would most probably allow for a comparison, in one system, between the nested sequent for $\IK$~\cite{DBLP:conf/fossacs/Strassburger13} and for $\CK$~\cite{DBLP:journals/corr/ArisakaDS15,DBLP:journals/aml/KuznetsS19}. Hence this is a path worth pursuing, together with the comparison of $\labEK$ with other labelled sequent systems for intuitionistic modal logics, specially the recent ones proposed in~\cite{marin:hal-02390454} and~\cite{DBLP:journals/corr/abs-1901-09812}.
{'timestamp': '2020-06-01T02:04:11', 'yymm': '2005', 'arxiv_id': '2005.14325', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14325'}
arxiv
\section{Introduction: Hospital Readmissions and the Pitfalls of Risk-Based Targeting} Unplanned hospital readmissions represent an undesirable outcome following a hospitalization, but are common, costly, and associated with substantial morbidity and mortality, occurring within 30 days following nearly 20\% of hospitalizations by Medicare beneficiaries \cite{Jencks2009RehospitalizationsProgram}. In 2011, 3.3 million patients in the United States were readmitted to the hospital within 30 days, incurring costs of \$41 billion \cite{Hines2011Conditions2011}. In 2012, responding the growing awareness of the toll of readmissions, the Centers for Medicare and Medicaid Services introduced the Hospital Readmissions Reduction Program (HRRP), which penalizes hospitals with risk-adjusted 30-day readmission rates higher than the average. As a consequence of the HRRP and other value-based care initiatives, many hospitals and health care systems in the United States have since implemented quality improvement (QI) initiatives and population health management programs that rely on risk assessment tools to identify hospitalized patients at high risk of readmission. Tailored interventions can be then targeted to these patients immediately following discharge, with the goal of preventing their readmission. The effectiveness of these interventions in preventing readmissions has been mixed, and the precise mechanisms through which they do so remain unclear. \cite{Leppin2014PreventingTrials,Hansen2011InterventionsReview,Wadhera2018AssociationPneumonia,Kansagara2016SoLiterature,Finkelstein2020HealthTrial,Bates2014BigPatients,Berkowitz2018AssociationJ-CHiP} Many risk assessment tools used in these efforts apply statistical modeling or supervised machine learning to estimate readmission risk among hospitalized patients based on data prior to discharge. \cite{Kansagara2011RiskReview.,Bayati2014Data-drivenStudy.,Escobar2015NonelectiveMortality,Billings2006CasePatients,Berkowitz2018AssociationJ-CHiP,Bates2014BigPatients} Stakeholders select a risk threshold with respect to resource constraints, which underpins objective criteria (often referred to in the machine learning literature as a \textit{treatment policy}) that determine which patients are selected to receive the intervention. Common threshold-based criteria specify that an intervention is to be delivered to all patients above a prespecified risk threshold, while those below it receive usual care. Underlying many population health management and QI efforts aimed at reducing readmissions is the implicit assumption that the patients most at risk are also those most likely to benefit from the intervention. \cite{Fihn2014InsightsAdministration,Bates2014BigPatients,HealthITAnalytics2016UsingHealthitanalytics.com/features/using-risk-scores-stratification-for-population-health-management,HealthITAnalytics2018TopHttps://healthitanalytics.com/news/top-4-big-data-analytics-strategies-to-reduce-hospital-readmissions} Ostensibly, this assumption has intuitive appeal, given that higher-risk patients appear to have "more room to move the needle", but it is not guaranteed to hold in practice \cite{Ascarza2018RetentionIneffective, Athey2017BeyondProblems}, especially in the context of readmissions \cite{Finkelstein2020HealthTrial,Lindquist2011UnderstandingFactors} and other settings where treatment effect heterogeneity may be present \cite{Athey2017BeyondProblems}. The need for analytical approaches that estimate patient-level benefit---referred to in some contexts as \textit{impactibility} \cite{Lewis2010ImpactibilityPrograms,Freund2011IdentificationPrograms,Steventon2017PreventingRisk,Flaks-Manov2020PreventingPrediction}---is beginning to be recognized, particularly for readmission reduction programs \cite{Steventon2017PreventingRisk}. However, the distinction between benefit and risk does not yet appear to be widely appreciated by both those developing and applying risk assessment tools. Individual benefit is often expressed in terms of treatment effects, which cannot be estimated by modelling outcome risk. Predicting, for example, a readmission risk of 60\% for a patient provides no information on their counterfactual risk if they were to receive a readmissions reduction intervention. The actual counterfactual risk for this hypothetical patient could be unchanged, on average, corresponding to no effect for the intervention. On the other hand, the effect of this intervention may be heterogeneous across levels of predicted risk, so that, for example, this patient experiences an absolute risk reduction (ARR) of 10\% as a result of the intervention, while another patient at a predicted risk of 30\% experiences an ARR of 20\%. Given limited resources, a decision-maker may wish to give the intervention to the latter patient. Indeed, when it comes to preventing readmissions, there is growing evidence that higher-risk patients---referred to in some contexts as "super-utilizers" \cite{Finkelstein2020HealthTrial}---may be less sensitive to a class of care coordination interventions relative to those at lower risk \cite{Steventon2017PreventingRisk,Lindquist2011UnderstandingFactors,Rich1993PreventionStudy.}. Moreover, efforts targeting preventative interventions based on predicted risk also fail to take into account that low-risk patients comprise the majority of readmissions \cite{Roland2012ReducingTrack}. That the majority of poor outcomes are experienced by patients at low risk, but who would not have been selected to receive an intervention, is an observation which has also surfaced in a range of predictive modeling problems in population health management \cite{Bates2014BigPatients}. Thus, targeting preventative interventions so as to include lower-risk patients among whom they may be effective, rather than targeting them only to high-risk patients, may potentially prevent more readmissions than the latter strategy \cite{Rose1985SickPopulations,Chiolero2015TheStrategy, McWilliams2017FocusingCosts}. However, even given a hypothetical ideal intervention---one guaranteed to be effective for \textit{all} patients in a population---staffing and other resource constraints may preclude scaling up such an intervention to an entire population. Hence, in order to maximize the net benefit of an intervention, "decoupling" the prediction problem into causal and predictive components---modeling not just heterogeneity in treatment effects, but also the (possibly heterogeneous) "payoffs" associated with successful prevention---may be necessary \cite{Kleinberg2015PredictionProblems}. Few, if any, analytical approaches to identify "care-sensitive" patients, or those whose outcomes may be most "impactible", currently exist, despite the clear need for such approaches. \cite{Lewis2010ImpactibilityPrograms,Flaks-Manov2020PreventingPrediction} Existing approaches based on off-the-shelf supervised machine learning methods, despite their flexibility and potential predictive power, cannot meet this need. \cite{Athey2017BeyondProblems} In this paper, we propose and demonstrate the feasibility of a causal machine learning framework to identify preventable hospital readmissions with respect to a readmission prevention intervention. In our context, the "preventability" of a readmission is not based on predefined, qualitative criteria, as in prior work (e.g., \cite{Goldfield2008IdentifyingReadmissions,Auerbach2016PreventabilityPatients}). Rather, it is expressed in quantitative terms: the greater the treatment effect on readmission estimated for a patient, the more preventable their potential readmission may be. To do so, we leverage a rich set of data drawn from before and after the roll-out of a comprehensive readmissions prevention intervention in an integrated health system, seeking to: (1) estimate the heterogeneity in the treatment effect of this intervention; (2) characterize the potential extent of mismatch between treatment effects and predicted risk; and (3) quantify the potential gains afforded by targeting based on treatment effects or benefit instead of risk. Finally, based on our findings, we also outline some possible directions for how population health management programs could be redesigned so as to maximize the aggregate benefit, or overall impact, of these preventative interventions. \section{Methods} \subsection{Data and Context} The data consist of 1,584,902 hospitalizations taking place at the 21 hospitals in Kaiser Permanente's Northern California region (hereafter KPNC) between June 2010 and December 2018. They include patient demographics, diagnosis codes, laboratory-based severity of illness scores at admission and at discharge, and a comorbidity burden score that is updated monthly. The data also record whether a patient experienced a non-elective re-admission and/or death within 30 days. These data are described in greater detail in \cite{Escobar2019MultiyearSystem}. These data encompass a period where a comprehensive readmissions prevention intervention, known as the \textit{Transitions Program}, began and completed implementation at all 21 KPNC hospitals from January 2016 to May 2017. The Transitions Program had two goals: (1) to standardize post-discharge care by consolidating a range of preexisting care coordination programs for patients with complex care needs; and (2) to improve the efficiency of this standardized intervention by targeting it to the patients at highest risk of the composite outcome of post-discharge re-admission and/or death. As currently implemented, the Transitions Program relies on a validated predictive model for the risk of this composite outcome \cite{Escobar2015NonelectiveMortality}, which was developed using historical data from between June 2010 and December 2013, before the implementation of the Transitions Program. Following development and validation of this model by teams at KPNC's Division of Research, it was subsequently integrated into KP HealthConnect, KPNC's electronic health record (EHR) system to produce continuous risk scores, ranging from 0 to 100\%, at 6:00 AM on the planned discharge day. These risk scores are used to automatically assign inpatients awaiting discharge to be followed by the Transitions Program over the 30-day period post-discharge. Inpatients with a predicted risk of $\geq\!\!25$ are assigned to be followed by the Transitions Program, and are considered to have received the Transitions Program intervention. On the other hand, inpatients with a predicted risk below 25\% receive usual post-discharge care at the discretion of the discharging physician. The Transitions Program intervention consists of a bundle of discrete interventions aimed at improving the transition from inpatient care to home or a to a skilled nursing facility. Together, they comprise an interlocking care pathway over the 30 days following discharge, beginning on the morning of the planned discharge day, and which we summarize step-by-step here and in Table \ref{tab:transitions}. \begin{table}[] \centering \resizebox{\textwidth}{!}{% \begin{tabular}{@{}cccccc@{}} \toprule Risk Level & Initial Assessment & Week 1 & Week 2 & Week 3 & Week 4 \\ \midrule \begin{tabular}[c]{@{}c@{}}High\\ ($\geq 45$\%)\end{tabular} & \begin{tabular}[c]{@{}c@{}}Phone follow-up \\ within 24 to 48 hours \\ \\ \textit{and}\end{tabular} & \begin{tabular}[c]{@{}c@{}}Phone follow-up\\ every other day\end{tabular} & \begin{tabular}[c]{@{}c@{}}2 phone follow-ups; \\ more as needed\end{tabular} & \begin{tabular}[c]{@{}c@{}}Phone follow-up \\ once weekly; \\ more as needed\end{tabular} & \begin{tabular}[c]{@{}c@{}}Phone follow-up \\ once weekly; \\ more as needed\end{tabular} \\ \cmidrule(r){1-1} \cmidrule(l){3-6} \begin{tabular}[c]{@{}c@{}}Medium\\ ($25-45$\%)\end{tabular} & \begin{tabular}[c]{@{}c@{}}Primary care physician follow-up visit\\ within 2 to 5 days\end{tabular} & \multicolumn{4}{c}{\begin{tabular}[c]{@{}c@{}}Once weekly phone follow-up \\ (with more as needed)\end{tabular}} \\ \midrule \begin{tabular}[c]{@{}c@{}}Low \\ ($\leq 25$\%)\end{tabular} & \multicolumn{5}{c}{Usual care at discretion of discharging physician} \\ \bottomrule \end{tabular}% } \caption{\footnotesize The Transitions Program intervention pathway. The initial assessment applies to both the medium and high risk groups. Following it, the pathway diverges in terms of the frequency of phone contact.} \label{tab:transitions} \end{table} For inpatients awaiting discharge and who have been assigned to be followed by the Transitions Program, on their planned discharge day, a case manager meets with them at the bedside to provide information on the Transitions Program. Next, once the patient has arrived home, a Transitions case manager calls them within 24 to 48 hours to walk them through their discharge instructions, and to identify any gaps in their understanding of them. If necessary, the case manager can also refer the patient to a pharmacist or social worker for focused follow-up. At the same time, the nurse also works to make an appointment with the patient's primary care physician to take place within 3 to 5 days post-discharge. Following this initial outreach, the Transitions case manager continues to contact the patient weekly by phone, and remains available throughout if the patient requires further assistance. At 30 days post-discharge, the patient is considered to have "graduated" and is no longer followed by the Transitions Program. All steps of this process are initiated through and documented in the EHR, enabling consistent followup for the patients enrolled. A special category of patients are considered at very high risk if their predicted risk is $\geq \!\! 45$\% or if they lack social support, and receive a more intensified version of the intervention. This version entails follow-up every other day via telephone for the first week post-discharge, followed by $\geq \!\! 2$ times a week the second week, and once a week afterward until "graduation" at 30 days. Initial analyses of the impacts of the Transitions Program \cite{Marafino2020ASystem}, using a hybrid difference-in-differences analysis/regression discontinuity approach \cite{Walkey2020NovelInitiative}, indicated that it was effective, being associated with approximately 1,200 and 300 fewer annual readmissions and deaths, respectively, within 30 days following their index discharge. Notably, these analyses also suggested some extent of risk-based treatment effect heterogeneity, in that the intervention appeared to be somewhat less effective for patients at higher risk compared to those at relatively lower risk. As a consequence of the conclusions of these analyses, two questions presented themselves. The first was whether the Transitions Program intervention could be re-targeted more efficiently, leading to greater aggregate benefit, possibly by including patients at lower risk who would not otherwise have received the intervention. The second arose out of the risk-based treatment effect heterogeneity suggested by these analyses---may the intervention in fact be less effective for patients at higher risk? If so, what is the extent of the mismatch between risk and treatment effects? To answer these questions requires modeling individual heterogeneous treatment effects, and not risk, as is commonly done. In this paper, we use the same data on 1,584,902 patients as that used for the analysis of the effectiveness of the Transitions Program. As in that analysis, we use a subset of 1,539,285 "index stays" which meet a set of eligibility criteria. These criteria include: the patient was discharged alive from the hospital; age $\geq \!\! 18$ years at admission; and their admission was not for childbirth (although post-delivery complications were included) nor for same-day surgery. Moreover, we consider a readmission non-elective if it began in the emergency department; if the principal diagnosis was an ambulatory care-sensitive condition \cite{AgencyforHealthcareResearchandQuality2001AHRQConditions.}; or if the episode of care began in an outpatient clinic, and the patient had elevated severity of illness, based on a mortality risk of $\geq\!\!7.2$\% as predicted by their laboratory-based acuity score (\texttt{LAPS2}) alone. The covariates used in this study (as input to the causal forest below) are summarized in Table \ref{tab:table1}. This project was approved by the KPNC Institutional Review Board for the Protection of Human Subjects, which has jurisdiction over all the study hospitals and waived the requirement for individual informed consent. \begin{table} \centering \resizebox{\textwidth}{!}{% \begin{tabular}{ll} \toprule \texttt{AGE} & Patient age in years, recorded at admission \\ \texttt{MALE} & Male gender indicator \\ \texttt{DCO\_4} & Code status at discharge (4 categories) \\ \texttt{HOSP\_PRIOR7\_CT} & Count of hospitalizations in the last 7 days prior to the current admission \\ \texttt{HOSP\_PRIOR8\_30\_CT} & Count of hospitalizations in the last 8 to 30 days prior to the current admission \\ \texttt{LOS\_30} & Length of stay, in days (with stays above 30 days truncated at 30 days) \\ \texttt{MEDICARE} & Indicator for Medicare Advantage status \\ \texttt{DISCHDISP} & Discharge disposition (home, skilled nursing, home health; one-hot encoded) \\ \texttt{LAPS2} & Laboratory-based acuity of illness score, recorded at admission \\ \texttt{LAPS2DC} & Laboratory-based acuity of illness score, recorded at discharge\\ \texttt{COPS2} & Comorbidity and chronic condition score, updated monthly\\ \texttt{HCUPSGDC} & Diagnosis super-group classification (30 groups; one-hot encoded) \\ \midrule \texttt{W} (or $W_i$) & Treatment: Transitions Program intervention \\ \texttt{Y} (or $Y_i$) & Outcome: Non-elective readmission within 30 days post-discharge \\ \bottomrule \end{tabular}} \vspace{0.2em} \caption{\footnotesize A list of the covariates used in this study.} \label{tab:table1} \end{table} \subsection{From (observational) data to predicted treatment effects: Causal forests} To identify potentially preventable readmissions, we undertake a causal machine learning approach using data taken from before and after the implementation of the Transitions Program at KPNC. Our causal machine learning approach is distinct from supervised machine learning as it is commonly applied in that it seeks to estimate individual \textit{treatment effects}, and not outcome risk. This objective cannot be readily accomplished with off-the-shelf supervised machine learning methods. \cite{Athey2017BeyondProblems} Compared to other methods for studying treatment effect heterogeneity (e.g. subgroup analyses), causal machine learning methods afford two advantages: one, they avoid strong modeling assumptions, allowing a data-driven approach; and two, they guard against overfitting through applying a form of regularization. We express these individual treatment effects of the Transitions Program intervention in terms of the estimated conditional average treatment effects (CATE), $\hat{\tau}_i$, which can be interpreted as absolute risk reductions (ARRs). It is through the sign and magnitude of these estimated CATEs that we consider a readmission potentially preventable: a $\hat{\tau}_i < 0$ denotes that the intervention would be expected to lower 30-day readmission risk for that patient, while a $\hat{\tau}_i > 0$ suggests that the intervention would be more likely to result in readmission within 30 days. A larger (more negative) CATE suggests a greater extent of preventability: i.e., $\hat{\tau}_j < \hat{\tau}_i < 0$ implies that patient $j$'s readmission is more "preventable"---their risk is more modifiable by the intervention---compared to patient $i$'s. To estimate these CATEs, we apply causal forests to the KPNC data described in the previous subsection. Causal forests \cite{AtheyGRF, Wager2018EstimationForests} represent a special case of generalized random forests \cite{Athey2019GeneralizedForests}. They have been used in a variety of applications, including to estimate conditional average partial effects; our overall approach resembles that undertaken in \cite{Athey}, which used them to study treatment effect heterogeneity in an observational setting. Causal forests can be viewed as a form of adaptive, data-driven subgroup analysis, and can be applied in either observational or randomized settings, relying on much of the machinery of random forests \cite{Breiman2001RandomForests}. These machinery retained from random forests include recursive partitioning, subsampling, and random selection of the splits. However, causal forests differ from random forests in several significant ways. For one, the splitting criterion seeks to place splits so as to maximize heterogeneity, instead of minimizing prediction error as with random forests. Moreover, when placing splits, the causal forest algorithm (depending on implementation details) has access to the data $X_i$ and treatment assignments $W_i$, but not to the outcomes $Y_i$, and a separate sample is used to estimate effects once these splits have been placed---a property often referred to as 'honesty' \cite{Wager2018EstimationForests}. We describe some necessary assumptions that are required in order to identify the CATEs, as the data are considered observational, and not randomized. The causal forest already fits a treatment assignment model, which deconfounds the subgroups in our study (described below) to some extent, but we also make further assumptions regarding the data, which we describe below, to facilitate deconfounding. We begin with some notation: for each of a set of units $i = 1, \ldots, n$, we observe the triple $(X_i, Y_i, W_i)$, where $X_i \in \mathbb{R}^p$ is a covariate vector, $Y_i \in \{0,1\}$ denotes the observed outcome, and $W_i \in \{0,1\}$ treatment assignment. Following Rubin's potential outcomes framework \cite{Rubin1974EstimatingStudies}, we assume the existence of potential outcomes, $Y_i(1)$ and $Y_i(0)$, for each unit, and define the conditional average treatment effect (CATE) for an unit $i$ with the covariate vector $X_i = x$ as \begin{equation} \tau_i(x) = \mathbb{E}[Y_i(1) - Y_i(0) \mid X_i = x]. \end{equation} Within a leaf $L$, a causal forest estimates this quantity as \begin{equation} \hat{\tau}(x) = \frac{1}{\mid\!\! \{j : W_j = 1 \wedge X_j \in L \}\!\! \mid} \sum_{\{j : W_j = 1 \wedge X_j \in L\}} Y_j \quad - \quad \frac{1}{\mid\!\! \{ j : W_j = 0 \wedge X_j \in L \}\!\! \mid} \sum_{\{j : W_j = 0 \wedge X_j \in L\}} Y_j \end{equation} for a $x \in L$. Heuristically, the process of fitting a causal forest aims to make these leaves $L$ as small as possible so that the data in each resemble a randomized experiment, while simultaneously maximizing effect heterogeneity. \cite{Wager2018EstimationForests} However, as we observe only one of the two potential outcomes for each unit, $Y_i = Y_i(W_i)$, we cannot estimate $Y_i(1) - Y_i(0)$ directly from these data. Under some assumptions, however, we can reprovision the units in the data that did experience the counterfactual outcome to estimate $\tau_i$, by having those units serve as 'virtual twins' for an unit $i$. These assumptions entail (1) the existence of these twins; and (2) that, in some sense, these twins look similar in terms of their covariates. These are the \textit{overlap} and \textit{uncounfoundedness} assumptions, respectively. Heuristically, the overlap assumption presumes that these twins could exist, and unconfoundedness posits that these twins are in fact similar in terms of their observed covariates. Together, these assumptions allow us to have some confidence that the $\tau_i(x)$ in fact do identify causal effects. We address identification with respect to the predicted risk threshold of 25\%, as well as the time period. By time period, recall that the Transitions Program intervention was rolled out to each of the 21 KPNC hospitals in a way that formed two completely disjoint subsets of patients, corresponding to the pre- and post-implementation periods. Also recall that patients were assigned to the intervention if they were discharged during the post-implementation period and their risk score was $>\!\!25$\%, while those below that value received usual care. An useful feature of these data is that all patients in the pre-implementation period were assigned 'shadow' risk scores using the same instantiation of the predictive model, even though none of these patients received treatment. Hence, the data are split into four disjoint subgroups, indexed by risk category and time period: \[ (\text{pre}, \geq\!\!25), \quad (\text{post}, \geq\!\!25), \quad (\text{pre}, <\!\!25), \quad (\text{post}, <\!\!25), \] i.e., the tuple $(\text{pre}, \geq\!\!25)$ denotes the subgroup consisting of patients discharged during the pre-implementation period with a risk score of $\geq\!\!25$\%, and $(.\,, \geq\!\!25)$ denotes all patients with risk $\geq\!\!25$\% in the data. Each hospital discharge belongs to one and only one of these subgroups. Heuristically, these 'shadow' risk scores allow us to mix data from across periods so that the $(\text{pre}, \geq\!\!25)$ subgroup can be used as a source of counterfactuals for patients in the $(\text{post}, \geq\!\!25)$ subgroup, assuming no unmeasured confounding as a consequence of the shift from "pre" to "post". Stratifying on the risk score allows us to deconfound the potential outcomes of the patients in these two subgroups. Moreover, these two subgroups together can be used to provide plausible counterfactuals for the patients in the $(.\,, <\!\!25)$ risk subgroup, despite none of those patients having been assigned to the intervention. We describe the identification strategy---which relies on standard ignorability assumptions---in more detail below, beginning with the $(.\,, \geq\!\!25)$ subgroup. First, for each of the four subgroups, we assume overlap: given some $\epsilon > 0$ and all possible $x \in \mathbb{R}^p$, \begin{equation} \epsilon < P(W_i = 1 \mid X_i = x) < 1 - \epsilon. \end{equation} This assumption means that no patient is guaranteed to receive the intervention, nor are they guaranteed to receive the control, based on their covariates $x$. For the patients in the $(.\,, \geq\!\!25)$ group, our identification strategy makes use of the balancing properties of risk scores (or prognostic scores) \cite{Hansen2008TheScore} to establish unconfoundedness. Assuming no hidden bias, conditioning on a prognostic score $\Psi(x) = P(Y \mid W = 0, x)$ is sufficient to deconfound the potential outcomes. The risk score used to assign the Transitions intervention is a prognostic score; hence, it is sufficient to deconfound these potential outcomes. For patients in the $(.\,, <\!\!25)$ subgroup, the picture is slightly more complicated. Among these patients, we cannot assume exchangeability conditional on the risk score $\hat{Y}_i$, \begin{equation} \{ Y_i(1), Y_i(0) \} \mathrel{\text{\scalebox{1.07}{$\perp\mkern-10mu\perp$}}} W_i \mid \hat{Y}_i, \end{equation} because, again, treatment assignment is contingent on a predicted risk $\hat{Y}_i \geq 0.25$, i.e., $W_i = \mathbf{1}\{\hat{Y}_i \geq 0.25\}$. However, recall that the causal forests are performing estimation in $X_i$-space, and not in $\hat{Y}_i$-space, and note that we can instead impose the slightly weaker assumption of ignorability conditional on some subset $X'_i \subseteq X_i$, which comprise inputs to the score $\hat{Y}_i$; namely, that \begin{equation} \{ Y_i(1), Y_i(0) \} \mathrel{\text{\scalebox{1.07}{$\perp\mkern-10mu\perp$}}} W_i \mid X'_i, \end{equation} which we can justify \textit{a priori} with the knowledge that no one component predictor predominates in the risk model (see the appendix to \cite{Escobar2015NonelectiveMortality}); that is, no one covariate strongly determines treatment assignment. We provide empirical evidence to establish the plausibility of this assumption, at least in low dimensions, in Figure \ref{fig:overlap}. Together with assuming the existence of potential outcomes, this \textit{unconfoundedness} assumption is sufficient to obtain consistent estimates of $\tau(x)$ \cite{Wager2018EstimationForests}. Moreover, since causal forests perform a form of local estimation, our assumptions are independent for the $(.\,, \geq\!\!25)$ and $(.\,, <\!\!25)$ subgroups in the sense that if the unconfoundedness assumption fails for either subgroup, but not the other, the estimates for the subgroup in which it does hold should not be affected. Finally, as a formal assessment of treatment effect heterogeneity, we also perform the omnibus test for heterogeneity \cite{Chernozhukov2017}, which seeks to estimate the best linear predictor of the CATE by using the "out-of-bag" predictions from the causal forest, $\hat{\tau}^{-i}$, to fit the following linear model: \begin{equation} Y_i - \hat{m}^{-i}(X_i) = \alpha\bar{\tau}(W_i - \hat{e}^{-i}(X_i)) + \beta(\hat{\tau}^{-i}(X_i) - \bar{\tau})(W_i - \hat{e}^{-i}(X_i)) + \epsilon, \end{equation} where \begin{equation} \bar{\tau} = \frac{1}{n} \sum^n_{i=1} \hat{\tau}^{-i}(X_i), \end{equation} and $\hat m(.)$ and $\hat e(.)$ denote the marginal outcome and assignment models estimated by the causal forest, respectively. (The superscript $-i$ denotes that the quantity was computed "out-of-bag", i.e., that the forest was not trained on example $i$). Fitting this linear model yields two coefficient estimates, $\alpha$ and $\beta$; an interpretation of these coefficients is that $\alpha$ captures the average treatment effect, and if $\alpha \approx 1$, then the predictions the forest makes are correct, on average. Likewise, $\beta$ measures how the estimated CATEs covary with the true CATEs; if $\beta \approx 1$, then these CATE estimates are well-calibrated. Moreover, we can use the $p$-value for $\beta$ as an omnibus test for heterogeneity; if the coefficient is statistically significantly greater than zero, then we can reject the null hypothesis of no treatment effect heterogeneity. \cite{AtheyEstimatingApplication} All analyses were performed in R (version 3.6.2); causal forests and the omnibus test for heterogeneity were implemented using the \texttt{grf} package (version 0.10.4). Causal forests were fit using default settings with $n = 8,000$ trees and per-hospital clusters (for a total of 21 clusters). \subsection{Translating predictions into treatment policies: Decoupling effects and payoffs} A relevant question, once predictions have been made---be they of risk or of treatment effects---is how to translate them into treatment decisions. With predicted risk, these decisions are made with respect to some risk threshold, or to a decision-theoretic threshold that takes utilities into account (e.g. as in the approach in \cite{Bayati2014Data-drivenStudy.}). However, both approaches are potentially suboptimal in the presence of treatment effect heterogeneity, requiring strong assumptions to be made regarding the nature of the treatment effect. (Indeed, \cite{Bayati2014Data-drivenStudy.} assumes a constant treatment effect for all patients.) Here, however, we deal with treatment effects instead of risk; an obvious approach starts by treating all patients $i$ with $\hat{\tau}(X_i) < 0$---that is, by treating all patients who are expected to benefit. However, resources may be constrained so that it is infeasible to treat all these patients, and making it necessary to prioritize from among those with $\hat{\tau}_i < 0$. One way to do so is to incorporate the costs associated with the potential outcome of a readmission, or the "payoffs" $\pi$ associated with successfully preventing a readmission \cite{Kleinberg2015PredictionProblems}, which we denote by $\pi_i = \pi(X_i)$. There are several ways to characterize these payoffs, which ideally can be done mainly in terms of the direct costs required to provide care for a readmitted patient, as well as financial penalties associated with high readmission rates. However, these data are not available to us, so we instead use length of stay (LOS) from the readmission as a proxy for cost, and assume that higher LOS is associated with higher resource utilization and thus higher costs. A range of payoffs could be specified, such as the risk of in-hospital mortality during the readmission, or an acuity-scaled LOS measure, as well as weighted combinations of these quantities. It is important to emphasize that these payoffs are associated with the characteristics of the readmission following the index stay, if one does occur---not those of the index stay itself. One approach to estimating these payoffs is to predict them using historical data, i.e., $\hat{\pi}(X_i) = \mathbb{E}[\pi_i \mid X_i = x]$ in a manner similar to that used to derive the risk scores. However, this is beyond the scope of this paper, and so we make some simplifying assumptions regarding the payoffs. Namely, we assume that (1) the individual payoffs $\pi_{i}$ can be approximated by the mean payoff across all patients, $\pi_{i} \approx \mathbb{E}[\pi_{i}]$, and (2) that the payoffs are mean independent of the predicted treatment effects, $\mathbb{E}[\pi_i \mid \tau_i] = \mathbb{E}[\pi_i]$. These two assumptions make it so that the $\hat{\tau}_i$ become the sole decision criterion for the treatment policies we evaluate in this paper, but we briefly outline how to incorporate these payoffs in decision-making. Given both the predicted treatment effects, $\hat{\tau}_i$, and payoffs, $\hat{\pi}_i$, we can compute the individual expected utilities, $\mathbb{E}[u_i] = \hat{\tau}_i \hat{\pi}_i$ for each patient. We assume that decision-makers are risk-neutral and that the cost to intervene is fixed. Then, given two patients, $i$ and $j$, and their respective expected utilities, we would prefer to treat $i$ over $j$ if $\mathbb{E}[u_i] > \mathbb{E}[u_j]$. Another interpretation (in a population sense) is that ordering the discharges in terms of their $\hat{\tau}_i$ induces one rank ordering, while ordering them in terms of their $\mathbb{E}[u_i]$ induces another. We can treat the top $k$\% of either ordering, subject to resource constraints, but doing so with the latter will result in greater net benefit and thus would be preferred. Under the assumptions we make above, $\mathbb{E}[u_i] \propto \hat{\tau}_i$ for each patient $i$. This particular decision-theoretic approach requires absolute, and not relative outcome measures, such as the relative risk reduction. \cite{Sprenger2017ThreeMeasures} \subsection{Measuring the impacts of different targeting strategies} To estimate the impact (in terms of the number of readmissions prevented) of several notional targeting strategies that focus on treating those with the largest expected benefit, and not those at highest predicted risk, we undertake the following approach. We stratify the patients in the dataset into ventiles $V_1, \ldots, V_{20}$ of predicted risk, where $V_1$ denotes the lowest (0 to 5\%) risk ventile, and $V_{20}$ the highest (95 to 100\%). Then, the causal forest is trained on data through the end of 2017, and used to predict CATEs for all patients discharged in 2018. First, for all patients above a predicted risk of 25\%, we compute the impact of the current risk-based targeting strategy based on the predicted CATEs from 2018, and compare it to that from prior work which estimated based on the average treatment effect of this intervention. \cite{Marafino2020ASystem} This comparison serves as one check of the calibration of the predicted CATEs; the number of readmissions prevented should substantially agree in both cases. Second, we then use these same predicted CATEs for 2018 to assess the impact of three CATE-based targeting strategies, which treat the top 10\%, 20\%, and 50\% of patients in each risk ventile based on their predicted CATE. These strategies spread the intervention across ventiles as a form of a hedge ("not putting all one's eggs in one basket"), rather than treating the top $k$\% patients in the dataset. The impacts of all targeting strategies are characterized both in terms of the annual number of readmissions prevented as well as the number needed to treat (NNT) to prevent one readmission. We estimate the annual number of readmissions prevented by training the causal forest on data through the end of 2017, and then summing the predicted CATEs for discharges taking place in 2018. The annual number of readmissions prevented can be expressed as \begin{equation} \sum^{20}_{j = 1} \sum_{i \in V^T_j} \hat{\tau}_i, \end{equation} where $V^T_j$ denotes the set of patients notionally selected for treatment in ventile $j$, and $\hat{\tau}_i$ the predicted CATE (treatment effect) for the patient $i$. Finally, the NNT in this setting has a slightly different interpretation than the one commonly encountered in many studies. Often, the NNT is cited as a summary measure based on the overall results of a trial, e.g., the average treatment effect (ATE). In this case, an ATE estimate $\hat{\tau}$, expressed in terms of the ARR, corresponds to a NNT of $1/\overline{\hat{\tau}_i} = 1/\hat{\tau}$. However, here, we instead estimate CATEs at the individual patient level and are interested in the NNTs specific to the subgroups that receive the intervention. Hence, the NNT is a property of these subgroups and can vary across subgroups as the average predicted CATE $\overline{\hat{\tau}_i}$ varies. \section{Results} \subsection{Overall characteristics of the cohort} From June 2010 to December 2018, 1,584,902 hospitalizations took place at the 21 KPNC hospitals represented in this sample. These included both inpatient hospitalizations as well as stays for observation. Further details regarding the overall cohort are presented in Table \ref{tab:a1}. Of these hospitalizations, 1,539,285 met the inclusion criteria, of which 1,127,778 (73.3\%) occurred during the pre-implementation period for the Transitions Program, and 411,507 (26.7\%) during the post-implementation period. Among these 411,507 hospitalizations taking place post-implementation, 80,424 (19.5\%) were predicted to be at high risk of 30-day post-discharge mortality or readmission; these patients were considered to have received the Transitions Program intervention following hospital discharge. Of the patients whose index stays were included, their mean age was 65.0 years, and 52.5\% were women. The overall 30-day non-elective rehospitalization rate among these index stays was 12.4\%, and 30-day post-discharge mortality was 4.0\%. Other patient-level characteristics are presented in Table \ref{tab:a1} in the Appendix. Notably, based on the distributions of \texttt{COPS2} and \texttt{LAPS2}, a key modeling assumption---that of overlap---appears to have been satisfied (Figure \ref{fig:overlap}). Patients at low risk (risk score $<\!\!25$\%) represented 63.3\% of all readmissions throughout the study period, while making up 82.9\% of index stays, compared to 36.7\% of all readmissions among those at high risk ($\geq \!\! 25$\%), which represented 17.1\% of index stays. Moreover, the mean length of stay of the readmission following an index stay was approximately constant across ventiles of predicted risk, satisfying another assumption; patients with predicted risk of 5 to 50\% at their index discharge had a mean length of stay during their readmission that ranged from 4.6 to 5.7 days, and these patients represented 90.5\% of all readmissions. (Figure \ref{fig:los-v-risk}) \begin{figure} \centering \includegraphics[scale=0.67]{img/overlap.pdf} \caption{\footnotesize Assessing the "unconfoundedness" assumption: each point denotes an admission, which are colored according to whether they received the Transitions Program intervention post-discharge ($W_i$). The $x$-axis records the value of a laboratory-based acuity score (\texttt{LAPS2DC}) and the $y$-axis the value of a chronic condition score (\texttt{COPS2)}, both at discharge. The extent of overlap displayed here is relatively good, and implies that overlap may be implausible only among patients at very high or very low risk. This plot is based on a random sample of $n = 20,000$ index admissions taken from the post-implementation period.} \label{fig:overlap} \end{figure} \begin{figure} \centering \includegraphics[scale=0.60]{img/los-v-risk.pdf} \caption{\footnotesize Average length of stay (LOS) by risk score ventile. The values in parentheses below the name of each ventile denote the proportion of all 30-day readmissions incurred by patients in that ventile; patients with a predicted risk below 25\% based on their index stay accounted for 63\% of all readmissions. Notably, the average LOS is roughly similar (at 5 days) for patients with predicted risk of 5\% to 80\%. The vertical dotted line represents the 25\% risk threshold used to assign the Transitions Program intervention.} \label{fig:los-v-risk} \end{figure} \subsection{Characterizing the treatment effect heterogeneity of the Transitions Program intervention} The estimated out-of-bag conditional average treatment effects (CATEs) yielded by the causal forest are presented in Figure \ref{fig:cate-overall}. The distributions of the CATEs are those of the discharges in their respective risk ventiles, but are not drawn on a common scale and so do not reflect the variation in sample size across ventiles. Qualitatively, these distributions exhibit wide spread, and suggest some extent of heterogeneity in the treatment effect of the Transitions Program intervention. In particular, treatment effects appear to be largest for patients discharged with a predicted risk of around 15 to 35\%. These effects also appeared to be somewhat attenuated as risk increased, with the center of mass tending towards zero for patients at higher risk. Notably, particularly among patients at higher risk, some estimated effects were greater than zero, indicating that the intervention was more likely to lead to readmission within 30 days. Finally, we also note that the CATE estimates themselves were well-calibrated in the sense that we identified no cases where an individual's CATE estimate was greater than their predicted risk. Figure \ref{fig:cate-hcupsg} is similar to the previous, but stratifies the display by Clinical Classification Software (CCS) supergroups. Definitions of these supergroups can be found in Table \ref{tab:b1} in the Appendix. The overall pattern is similar to that in the unstratified plot, in that treatment effects appear to be greatest for patients at low to moderate risk, but the shapes of these distributions vary from supergroup to supergroup. All supergroups appear to exhibit heterogeneity in treatment effect within ventiles, as well, which is more pronounced for some conditions, including hip fracture, trauma, and highly malignant cancers. Qualitatively, some supergroups exhibit bimodal or even trimodal distributions in the treatment effect of the Transitions Program intervention, suggesting identification of distinct subgroups based on these effects. Some ventiles are blank for some supergroups, because there were no patients belonging to those supergroups with predicted risks falling within those ranges. Quantitatively, fitting the best linear predictor yields estimates of $\hat \alpha = 1.16$ and $\hat \beta = 1.06$, with $p = 5.3 \times 10^{-8}$ and $2.23 \times 10^{-7}$, respectively. Interpreting the estimate of $\beta$ as an omnibus test for the presence of heterogeneity, we can reject the null hypothesis of no treatment effect heterogeneity. These effects can also be evaluated on a grid of two covariates to assess how the estimated CATE function varies with interaction of these covariates. This yields insight into the qualitative aspects of the surface of the CATE function and may identify subgroups among which the Transitions Program intervention may have been more or less effective. Here, we choose the Comorbidity Point Score (\texttt{COPS2}) and the Laboratory-based Acuity Score at discharge (\texttt{LAPS2DC}), while holding all other continuous covariates at their median values, except for age, which we set to 50 and 80. Categorical covariates were held at their mode, except for the supergroup, which we set to chronic heart failure (CHF). We plot the CATE function from the 10th to 90th percentiles of \texttt{LAPS2DC} and from the 0th to 95th percentiles of \texttt{COPS2}. This is akin to evaluating the CATE function for a set of pseudo-patients with CHF having these values of \texttt{COPS2} and \texttt{LAPS2DC}. Figure \ref{fig:cate-hcupsg} shows the resulting CATE functions for two choices of patient age: 50 and 80 years. In this region, the estimated CATE ranged from -0.060 to 0.025 (-6.0 to 2.5\%), meaning that the estimated absolute risk reduction of the Transitions Program intervention was as large as -6\% for some patients, while for others, their readmission risk was increased by as much as 2.5\%. The estimated CATE generally was increased in magnitude---suggesting that the Transitions Program intervention became more effective as age increased---at age 80 compared to 50. Moreover, and notably, the estimated CATE tended to increase with increasing \texttt{LAPS2DC}, which measures how acutely ill a patient was upon discharge based on their laboratory test data. This finding suggests that, for patients who were more ill at discharge (indeed, the average \texttt{LAPS2DC} in 2018 was 45.5), enrolling them in the Transitions Program may actually have encouraged them to return to the hospital. While this finding of such an effect may appear surprising, it is unclear if it actually represents "harm" in the sense it is usually interpreted; we discuss this finding in more depth in the Discussion section. \begin{figure} \centering \includegraphics[scale=0.67]{img/overall-cate-estimate.pdf} \caption{\footnotesize Treatment effect heterogeneity across risk score ventiles. The densities represent the distribution of estimated conditional average treatment effects within each ventile. They are drawn on a common scale, and hence do not reflect the variation in sample size across ventiles.} \label{fig:cate-overall} \end{figure} \begin{figure} \centering \includegraphics[scale=0.67]{img/cate-by-hcupsg.pdf} \caption{\footnotesize Treatment effect heterogeneity across risk score ventiles, stratified by Clinical Classification Software (CCS) supergroups based on the principal diagnosis code at discharge. A full listing of the definitions of these supergroups is given in Table \ref{tab:b1} in the Appendix. Abbreviations: CVD, cerebrovascular disease; AMI, acute myocardial infarction; CAP, community-acquired pneumonia; CHF, congestive heart failure; GI, gastrointestinal; UTI, urinary tract infection.} \label{fig:cate-hcupsg} \end{figure} \begin{figure} \centering \includegraphics[scale=0.67]{img/5080_chf.pdf} \caption{\footnotesize The estimated CATE function as it varies in the dimensions of \texttt{LAPS2DC} and \texttt{COPS2}, for a patient with chronic heart failure at ages 50 and 80. All other continuous variables were fixed at their median, and other categorical variables were fixed at their mode. (The transitions from one cell to another in this figure should not appear smooth; if this is the case, try a different PDF viewer.)} \label{fig:cate-chf} \end{figure} \subsection{Notional estimates of overall impact under different targeting strategies} Based on these individual CATE estimates, we compute the potential impacts of several notional targeting strategies using these estimated effects, and not predicted risk, to target the Transitions Program intervention. These impacts are expressed in terms of the number of annual readmissions prevented, and are presented in Table \ref{tab:policies}. These quantities are computed by training a model on all data through December 2017, which is then used to predict effects for patients discharged in 2018. These predicted effects are used to compute the numbers of readmissions prevented and number needed to treat (NNT). We also present the estimated number of interventions required under each strategy. We first confirm the calibration of the individual effect estimates by taking the same group of patients who were intervened upon under the current risk-based strategy, and use this group to estimate the number of readmissions prevented, with the aim of comparing this number to a previous estimate of the impact of this policy using the average treatment effect \cite{Marafino2020ASystem}. This results in an estimate of 1,246 (95\% confidence interval [CI] 1,110-1,381) readmissions prevented annually, which compares favorably to the previous estimate of 1,210 (95\% CI 990-1,430), representing further evidence that these estimates are well-calibrated. The NNT under both of these these strategies is 33, and the number of individual interventions needed is 39,985. (Table \ref{tab:policies}) Next, computing the impacts of the CATE-based strategies, which target the Transitions Program intervention to the top 10\%, 20\%, and 50\% of each risk ventile, we find that all of these policies are estimated to result in greater potential reductions in the absolute number of readmissions prevented. \ref{tab:policies} The top-10\% strategy may prevent 1,461 (95\% CI 1,294-1,628) readmissions annually, and does so more efficiently, as implied by the NNT of 13. Moreover, the top-20\% strategy requires the same total number of interventions as the existing risk-based strategy (39,648 vs. 39,985), yet is estimated to lead to double the number of annual readmissions prevented, at 2,478 (95\% CI 2,262-2,694). This strategy appears to be much more efficient, as evidenced by its estimated NNT of 16. Even under the most expansive strategy, which treats the top 50\% of each risk ventile and requires 250\% the number of total interventions compared to the risk-based strategy, also represents an improvement in the NNT (23 vs. 33). This strategy is estimated to lead to 4,458 (95\% CI 3,925-4,990) readmissions prevented annually, or nearly four times as many as the existing strategy. Finally, we also note that while there appears to exist a tradeoff in terms of absolute impact and efficiency, all CATE-based strategies substantially improved upon the risk-based targeting strategy in terms of the NNT. \begin{table}[] \centering \begin{tabular}{@{}lccc@{}} \toprule Treatment strategy & \begin{tabular}[c]{@{}c@{}}Annual readmissions \\ prevented, $n$\end{tabular} & \begin{tabular}[c]{@{}c@{}}Total interventions,\\ $n$\end{tabular} & NNT \\ \midrule \textbf{Risk-based targeting} & & & \\ \quad Target to $ \geq\!\! 25$\% (DiD estimate) & 1,210 (990-1,430) & 39,985 & 33 \\ \quad Target to $ \geq\!\! 25$\% (CF estimate) & 1,246 (1,110-1,381) & 39,985 & 33 \\ \midrule \textbf{CATE-based targeting} & & & \\ \quad Targeting top 10\% & 1,461 (1,294-1,628) & 18,993 & 13 \\ \quad Targeting top 20\% & 2,478 (2,262-2,694) & 39,648 & 16 \\ \quad Targeting top 50\% & 4,458 (3,925-4,990) & 102,534 & 23 \\ \bottomrule \end{tabular} \vspace{0.2em} \caption{\footnotesize Estimates of overall impacts of risk-based and notional CATE-based targeting strategies in terms of the annual numbers of readmissions prevented as well as the numbers needed to treat (NNTs) under each targeting strategy, based on the estimates for index admissions in 2018. The first quantity---the difference-in-differences (DiD) estimate---is based on the results of \cite{Marafino2020ASystem}. All quantities are rounded to the nearest integer. Parentheses represent 95\% confidence intervals. Abbreviations: CATE, conditional average treatment effect; DiD, difference-in-differences; CF, causal forest.} \label{tab:policies} \end{table} \section{Discussion} In this paper, we have shown the feasibility of estimating individual treatment effects for a comprehensive readmissions prevention intervention using data on over 1.5 million hospitalizations, representing an example of an "impactibility" model \cite{Lewis2010ImpactibilityPrograms}. Even though our analysis used observational data, we found that these individual estimates were well-calibrated, in that none of the individual estimates were greater than the predicted risk. Moreover, these estimates, in aggregate, when used to compute the impact of the risk-based targeting policy, substantially agreed with a separate estimate computed via a difference-in-differences analysis. Notably, our results suggest that strategies targeting similar population health management and quality improvement (QI) interventions based on these individual effects may lead to far greater aggregate benefit compared to targeting based on risk. In our setting, the difference translated to nearly as many as four times the number of readmissions prevented annually over the current risk-based approach. Our analysis also found both qualitative and quantitative evidence for treatment effect heterogeneity, particularly across levels of predicted risk: the Transitions Program intervention seemed less effective as predicted risk increased. The extent of this mismatch between treatment effect and predicted risk appeared substantial, and may have implications for the design of readmission reduction programs and related population health management programs. Furthermore, our analysis, when stratified by diagnostic supergroup, also appeared to identify distinct subgroups consisting of patients with larger, more negative treatment effects, indicating that the intervention may have been more effective in those subgroups. Patients expected to benefit could be prioritized to receive the intervention, while patients unlikely to benefit could instead receive more targeted care that better meets their needs, including specific subspecialty care, and in some cases, palliative care. More work remains to be done to investigate if these findings hold for other types of preventative interventions, to characterize these subgroups, and to evaluate how to best translate our preliminary findings into practice. Notably, our finding of a risk-treatment effect mismatch is in line with suggestions in the readmissions prevention literature \cite{Finkelstein2020HealthTrial,Steventon2017PreventingRisk,Lindquist2011UnderstandingFactors}. To the best of our knowledge, this work is the first to apply causal machine learning together with decision analysis to estimate the treatment effect heterogeneity of a population health management intervention, and as such, represents the first example of an end-to-end "impactibility" model \cite{Lewis2010ImpactibilityPrograms}. Our approach is also notable in that we show how to decouple the causal and predictive aspects of this prediction problem \cite{Kleinberg2015PredictionProblems, Ascarza2018RetentionIneffective}. In particular, our approach was principally inspired by a study of the effectiveness of targeting marketing interventions based on risk by Ascarza \cite{Ascarza2018RetentionIneffective}, as well as previous work on the causal aspects of prediction problems by Kleinberg and co-authors \cite{Kleinberg2015PredictionProblems, Kleinberg2018HumanPredictions}, and others taking causal approaches to prediction problems. \cite{Rubin2006EstimatingMethodology, Blake2015ConsumerExperiment} From a modeling perspective, treating such a problem as purely predictive, as is commonly done in studies developing readmission risk tools \cite{Kansagara2011RiskReview.}, relies on an assumption that may be implausible---specifically that treatment effects correlate with risk. On the other hand, a purely causal approach---one that focuses on modeling treatment effects---fails when confronted with prediction problems that involve resource allocation. Even those patients whose readmissions may be the most "impactible" may not also have the most resource-intensive readmissions. Indeed, this potential oversight exemplifies a form of bias referred to as "omitted payoff bias". \cite{Kleinberg2018HumanPredictions} Previous studies have investigated the extent to which preexisting risk assessment tools may already capture a patient's degree of impactibility, by integrating qualitative assessments from nurses and physicians into these models \cite{Flaks-Manov2020PreventingPrediction}. While there seems to be some overlap between predicted risk and impactibility as expressed by these providers, it appears incomplete, and it is not clear how clinician assessments could be integrated into existing models. \cite{Flaks-Manov2020PreventingPrediction} Further afield, performance metrics for predictive models such as the recently proposed "C statistic for benefit" \cite{vanKlaveren2018TheEffects} can assess the ability of such a model to discriminate between patients expected to benefit from a treatment and those who will not. While useful, these metrics do not facilitate assessment of treatment effect heterogeneity. Attempts have been made to model treatment effect heterogeneity among patients undergoing antihypertensive therapy using a similar causal machine learning approach (the X-learner \cite{Kunzel2019MetalearnersLearning}), and also found some extent of mismatch between treatment effects and risk. \cite{Duan2019ClinicalTherapy} \subsection{The necessity of estimating heterogeneous treatment effects, and not just outcome risk} Our results highlight the necessity of estimating the treatment effect heterogeneity associated with preventative interventions, particularly at the population scale. A full appraisal of such heterogeneity can aid in targeting these interventions to patients among whom they might be most effective, while targeting intensified versions, or different versions, to patients who may not be expected to benefit from the intervention as originally implemented. As a result, our analyses suggest that up to nearly as four times as many readmissions could be prevented compared to the current state of affairs, while incurring nominal marginal costs in terms of the total number of interventions delivered. Thus, the current risk-centric modeling methodology employed by many hospitals and health systems, as well as by payers, may limit the full potential of these interventions. We focus on what could be considered a special case of treatment effect heterogeneity---of that on the absolute risk scale. \cite{Kent2016RiskTrials., Kent2018PersonalizedEffects} Unlike other studies performing similar analyses (e.g. \cite{Kent2008AInfarction} and others cited in \cite{Kent2016RiskTrials.}) finding that a small group of high-risk patients accounted for most of the aggregate benefits, we instead found that the effect of the Transitions Program intervention were largest in the most numerous subgroup of patients, namely those at relatively low to moderate risk. For high-risk patients, the intervention appeared to be less effective, which is in line with the growing body of evidence showing similar findings \cite{Finkelstein2020HealthTrial,Steventon2017PreventingRisk,Lindquist2011UnderstandingFactors,Rich1993PreventionStudy.}. An open question is the extent to which these high-risk/ineffective patients are qualitatively distinct, to the point that they should be considered "futile", as some have proposed \cite{Lewis2010ImpactibilityPrograms}, or if they may be amenable to a more intensified version of the intervention or an entirely different approach altogether. A notable finding is that some patients had a predicted CATE greater than zero, indicating that the Transitions Program intervention may have encouraged them to return to the hospital. In other settings, a positive treatment effect would often be interpreted as harm, and suggest that the treatment be withheld from these patients. However, we argue that our finding does not readily admit such an interpretation. To see why, we note that this subgroup of patients with a positive CATE appeared to be those who were more acutely ill at discharge, as evidenced by their higher \texttt{LAPS2DC} scores (Figure \ref{fig:cate-chf}). In light of this finding, an alternative interpretation of these weakly positive effects is that they represent readmissions which may have been necessary, and which perhaps may have been facilitated by aspects of the Transitions Program intervention, including instructions to patients outlining the circumstances (e.g. new or worsening symptoms) under which they should return to the hospital. This finding holds particular relevance given increasing concern that readmission prevention programs, in responding to the incentives of the HRRP, may be reducing 30-day hospitalization rates at the expense of increased short- and long-run mortality. \cite{Wadhera2018AssociationPneumonia, Fonarow2017TheReconsider, Gupta2018ThePolicy} Moreover, this finding also suggests that the CATE estimates may be insufficient to capture the full impact of the Transitions Program intervention on patient outcomes, meaning that the estimated effect of the intervention on readmission alone may not represent a sufficient basis for future targeting strategies. It is plausible that intervening in a patient with a positive estimated effect may be warranted if the readmission would have a positive effect on other outcomes, despite the current emphasis of value-based purchasing programs on penalizing excess 30-day readmissions. For example, in fiscal year 2016, the maximum penalty for excess 30-day mortality was 0.2\% of a hospital's diagnosis-related group (DRG) payments under the Hospital Value-Based Purchasing program, while the maximum penalty for excess 30-day readmission was 3.0\% of DRG payments under the HRRP. \cite{Abdul-Aziz2017AssociationMortality} A more holistic targeting strategy would incorporate estimates of the intervention's effect on short- and long-run mortality and other outcomes, and explicitly include these quantities when computing expected utility. Selecting patients for treatment can then be formulated as an optimization problem that attempts to balance regulatory incentives, organizational priorities, patient welfare, and resource constraints. \subsection{Causal aspects of prediction problems} Our approach, in contrast to many studies which have developed readmission risk prediction models \cite{Kansagara2011RiskReview.,Bayati2014Data-drivenStudy.,Bates2014BigPatients}, instead focuses on the causal aspects of the readmissions prediction problem. Our analyses emphasize modeling treatment effect heterogeneity of the Transitions Program intervention and on closing the loop from prediction to decision. However, more work remains to formalize criteria that more clearly delineate the roles of causal inference and prediction in these prediction problems, and the extent to which either is necessary or sufficient for a given problem. As explored by \cite{Bayati2014Data-drivenStudy.} and \cite{Kleinberg2018HumanPredictions}, fully operationalizing a prediction model entails the following steps: \begin{equation*} \text{data} \Rightarrow \text{prediction} \Rightarrow \text{decision}. \end{equation*} Historically, many machine learning studies, including those in medicine, have emphasized the $\textit{data} \Rightarrow \textit{prediction}$ link, while neglecting the $\textit{prediction} \Rightarrow \textit{decision}$ link. These studies often evaluate model quality on the basis of performance metrics, including the area under the reciever operating characteristic curve (AUROC or AUC) or C-statistic, the area under the precision-recall curve (AUPRC), and other measures of accuracy. A final model is chosen from among candidate models because it maximizes the value of the metric of interest, with the implicit hope that it also maximizes its utility in a real-world setting were it to be so applied. However, this approach conflates prediction with classification---the risks of doing so which are clear, though perhaps underappreciated \cite{Harrell2019ClassificationThinking}---and hence also conflates prediction quality with decision quality. Indeed, it is conceivable (though not likely) that even an intervention based on a perfectly accurate prediction model---for example, one that correctly identified all readmissions---could result in no net benefit, if the intervention proved ineffective for all the "high-risk" patients whose readmissions were identified. This contrasts with the setting of many classification problems (which we emphasize again are distinct from prediction problems), including, for example, image classification. In these cases, the utility function of classification is expressible in terms of the performance metric of interest alone, such as the accuracy or $F_1$ score. For a given choice of metric, the utility of an image classifier is strictly increasing in that metric, whereas in our hypothetical readmission prediction model, even perfect "classification" is not sufficient. This mismatch between predictive performance and utility is less pronounced with a less severe extent of treatment effect heterogeneity, but our hypothetical example highlights the importance of making the distinction. To be sure, not all prediction problems decompose neatly into causal and predictive components. Some such problems are purely causal, while others can be solved with prediction alone. Models developed for risk adjustment, for example, represent an example of the latter types of problems, as in those contexts there is no link between an individual prediction and a decision. Rather, the predictions of risk adjustment are used in aggregate; for example, to obtain observed-to-expected ratios of outcomes for quality measures, or to adjust capitation payments according to case mix. \cite{MedPAC2016MedicareSystem} Another class of prediction models that can be viewed as solving purely predictive problems are those used for clinical decision support \cite{Chen2017MachineExpectations}, including the APACHE ICU mortality model \cite{Knaus1985APACHESystem}. These decision support systems can be used in the context of an individual patient at the point of care to inform decision-making. For example, the APACHE model can be used to track the response of a patient in the intensive care unit (ICU) to treatment, or an objective measure to help decide when palliative care may be necessary. \cite{Knaus2002APACHEReflections} But it is not used in isolation to decide when to start and stop an intervention, unlike the prediction model used to enroll patients in the Transitions Program which we studied in this paper. Instead, the physician is meant to integrate APACHE model output with other information to arrive at a decision, which may incorporate other clinical data not captured in the model, resource constraints, or even family preferences. This is an significant distinction: the view of the APACHE model as solving a purely predictive problem implicitly off-loads the burden of decision-making, and thus of conceptualizing an utility function, to the physician. Without a human (or physician) in the loop, the utility function must be made more explicit in order to maximize aggregate utility, as in the framework we describe in this paper. On the other hand, a setting where the link between prediction and decision is more explicit is that of resource allocation problems. A well-known example involves the MELD score \cite{Kamath2001ADisease}, which predicts 3-month mortality in liver failure and is used to prioritize patients for liver transplant. The prediction problem can again be classed as purely predictive, because patients with higher MELD scores (and hence higher 3-month mortality) benefit most: allocating donor livers to the patients with the highest MELD scores yields more years of life saved, in aggregate. A similar insight was employed by Kleinberg and co-authors \cite{Kleinberg2015PredictionProblems}, who investigated a different resource allocation problem---that of allocating joint replacement surgeries. A patient who receives a joint replacement will not see the full benefit until at least a year post-surgery, due to the time required for recovery and physical therapy in the interim. Hence, patients who receive a joint replacement, but die within a year post-surgery, do not benefit from surgery. With this in mind, the problem of allocating joint replacements can be cast as a purely predictive one by developing a prediction model for mortality at 1 year post-surgery. Surgeries can then be allocated to patients in need below a certain risk threshold. Unlike with the MELD score, the authors found that risk did not appear to correlate with benefit as measured by claims for physical therapy, joint injections, and physician visits pre-surgery. If the riskiest patients would otherwise have derived the most benefit from surgery, this would constitute an example of "omitted payoff bias", requiring a different utility function that took the payoff of decreased medical need (presumably corresponding to less severe symptoms) into account in order to assign patients to surgery. \cite{Kleinberg2015PredictionProblems} We close this subsection with an example of a prediction problem that appears purely predictive, but is in fact largely, and perhaps purely, causal. Consider the problem of identifying hospitalized patients who would benefit from a palliative care consultation, which has attracted considerable attention over the last two decades as the need for palliative care has grown. \cite{Weissman2011IdentifyingCare.} Holistic criteria have been proposed to identify these patients, spanning domains including mortality risk in the next 12 months, the presence of refractory symptoms, the patient's level of social support, and inability to carry out activities of daily living---which constitute a selection of the 13 indicators outlined in \cite{Weissman2011IdentifyingCare.}. Recently, attempts have also been made to reduce the problem of identifying patients who might benefit from palliative care to one of modeling 12-month mortality from hospital admission, e.g., \cite{Avati2018ImprovingLearning}. Notwithstanding the causal issues involved in defining this outcome of interest retrospectively and applying it prospectively (e.g., see \cite{Einav2018PredictiveLife} for a related discussion), this approach is also problematic in that it is unlikely to reliably identify patients who will actually benefit from palliative care, because it all omits other indicators of palliative care need beyond 12-month mortality. A palliative care consultation is a complex intervention which will likely have highly heterogeneous treatment effects on quality of life---which is the real outcome of interest---and it is unclear if these effects do in fact correlate with 12-month mortality risk. In fact, solving this proxy problem will likely identify many patients who will die in the short run, but who may not be amenable to palliative care. This includes patients in the ICU, for whom providing the full spectrum of palliative care can be challenging, due to sedation, the use of mechanical ventilation and other invasive interventions, environmental light and noise, and limits on family visitation. \cite{Cook2014DyingUnit} Conversely, this approach would also miss many patients who are at low mortality risk, but who may otherwise benefit from palliative care early in their disease course. Indeed, guidelines recommend initiating palliative care early in patients with cancer, for example---with some trials finding that initiation at as early as the time of diagnosis may be most effective. \cite{Howie2013EarlyImplications} \subsection{New processes for predictive algorithm-driven intervention deployments within learning health systems} Our findings could be used to retarget the Transitions Program intervention prospectively to patients who are most expected to benefit, rather than those at highest risk, resulting in larger aggregate benefit in terms of the number of readmissions prevented. Similarly, our approach could be used to retarget other population health management and QI interventions which are often deployed wholesale or using risk assessment tools. However, as we mention, these individual estimates were derived from observational data, and not from data generated via a randomized experiment---the latter type of data which represent the ideal substrate for estimating treatment effects insofar as randomization is able to mitigate the effects of confounding. \cite{Kent2018PersonalizedEffects} Furthermore, our approach requires interventional data, unlike those used to develop more traditional risk assessment tools, which are often based on retrospective data. Hence, to implement our approach, as an alternative to risk tool-driven approaches, may require rethinking how these predictive algorithm-driven interventions (or "prediction-action dyads", cf. \cite{Liu2019TheHealthcare}) are deployed within health systems, particularly in relation to existing digital infrastructure and institutional oversight processes. We outline several starting points for doing so below. One option is to first deploy a new predictive algorithm-driven intervention as part of a simple two-arm randomized trial which compares that intervention to usual care. This represents a pilot phase, generating data that are used to derive an impactibility model, along with a payoff model if necessary for the prediction problem. Following this pilot phase, two paths are possible: 1) based on this impactibility model, the intervention could be re-targeted to the patients most expected to benefit; or 2) alternatively, carrying out another two-arm randomized trial comparing risk-based to impactibility-based targeting. In the latter choice, patients would be randomized to either of the risk or impactibility arms, and based on their covariates would either receive or not receive the intervention according to their risk or benefit estimate. Based on the results of this second trial, whichever targeting approach proved more effective could then be put into use. Another option, if a predictive algorithm-driven intervention based on risk scores is already in use, does away with the pilot randomized trial. Instead, the first step is to derive a impactibility model from observational data, as we did in this study. Then, if the goal is to retarget this intervention to include more patients at lower risk---for example, patients between 10 and 25\% predicted risk---risk-based and impactibility-based targeting could be compared to each other in a three-arm randomized trial. The first arm consists of risk-based targeting using the current risk threshold; the second arm, impactibility-based targeting; and the third arm, risk-based targeting to patients in the 10-25\% risk subgroup. Finally, cluster-randomized trial designs based on the regression discontinuity design would allow treatment effect heterogeneity across levels of risk to be characterized, enabling the intervention to be retargeted to the groups among which it is most effective; we hope to investigate these designs in future work. These proposed options represent major shifts from how deployments of predictive algorithm-driven interventions are usually carried out in health systems. New institutional overnight processes \cite{Faden2013AnEthics}, digital infrastructure, and statistical methodology would be required in order to realize the full potential of these approaches. Many such interventions, if deemed to create only minimal risk, fall under the umbrella of routine quality improvement (QI) studies, which exempts them from ongoing independent oversight \cite{Finkelstein2015OversightResearch}. However, incorporating randomization, as we do in the options we describe above, shifts these interventions from the category of routine QI to non-routine QI or research. These two categories of studies often require independent oversight by, for example, an institutional review board (IRB), and may need to incorporate additional ethical considerations, e.g., requiring informed consent. It is possible that a categorization of a deployment process like the ones we describe above as non-routine QI or research could impede their being carried out, as has occurred in previous QI work. \cite{Baily2006SpecialSafety} However, similar attempts at deploying QI interventions as a part of rapid-cycle randomized experiments have escaped such categorization \cite{Horwitz2019CreatingTesting}, although standards will likely vary from institution to institution. Moreover, these new deployment processes we envision will also require new digital infrastructure to implement these models and provision their linked interventions as a part of randomized trials and to monitor their impacts in real-time (while accounting for early stopping and other biases), akin to how A/B testing is usually carried out by many Web-facing companies today \cite{Kohavi2013OnlineScale}. Another sticking point is the lack of established analogues of power analyses for causal forests and other methods. Without these analogues, it is not clear how to set the necessary sample size for a pilot randomized trial like the one we describe above, although it could possibly be determined via simulation. The investments required to establish these platforms may be considerable, and it remains unclear whether the costs in fact do outweigh the rewards, particularly when one also accounts for the opportunity costs associated with experimentation. However, the potential impact, both on patient outcomes and in terms of the knowledge generated, could be substantial, and merit further investigation. \subsection{Limitations} This study has several limitations. First, as this study is observational in nature, our analysis necessarily relies on certain assumptions, which, while plausible, are unverifiable. The unconfoundedness assumption that we make presumes no unmeasured confounding, and cannot be verified through inspection of the data nor via statistical tests. It is possible that our results, particularly the notional estimates of overall impact in terms of the numbers of readmissions prevented annually under the CATE-based targeting strategies, are biased. However, it appears that the magnitude of unobserved bias would have to be large to negate our results, particularly our estimates of the potential impacts of the CATE-based strategies. Furthermore, because the causal forest performs local linear estimation, the assumptions that we make with respect to the risk threshold can be considered modular in the sense that if they fail for the subgroup of patients with a predicted risk of below 25\% across both the pre- and post-implementation periods (which we anticipate would be most likely), they would still hold for the $\geq \!\!25$\% risk subgroup. Moreover, we again note that the CATEs appeared well-calibrated in at least two aspects: the number of readmissions prevented under the risk-based targeting strategy, as estimated using the predicted CATEs, agreed with that estimated via a separate analysis; and the predicted CATEs were never larger than the predicted risk for any individual. Furthermore, this limitation becomes moot if the data are generated by a randomized experiment. We outline several approaches for how existing processes of deploying predictive algorithm-driven interventions could be redesigned to incorporate randomization in order to iteratively refine these interventions through improved targeting. Second, these estimates of benefit must be computed with respect to an intervention, which cannot be made with historical data alone, as is often done when developing risk assessment tools. As such, the necessary data must be generated, whether through wholesale deployments of an intervention (as in many QI studies) or via randomized experiments. The latter provide a better basis for these analyses, but are costly and require additional infrastructure, and may be subject to more institutional oversight. Third, our simplifying assumption with respect to the nature of the payoffs may not have resulted in a targeting strategy that was in fact optimal, but we hope to explore in future work the feasibility of predicting payoffs using supervised machine learning in parallel with treatment effects within this framework, and observing how the resulting targeting strategies change. Third, although we incorporated it into our analysis, the \texttt{HCUPSGDC} variable is not uniformly always available at discharge. From the point of a view of a retrospective analysis that principally seeks to characterize treatment effect heterogeneity, this does not constitute a limitation. However, this consideration may preclude the application of this impactibility model prospectively in its current form, but it is possible that the patient's problem list at discharge could be used to infer the value of this variable, as there are only 25 categories used in our analysis. Finally, our results may not be applicable to all settings, particularly hospitals and health systems without a high degree of integration. However, the framework we outline here is agnostic as to application as well as the type of causal machine learning model used, and could be applied to resource allocation and other prediction problems more generally. \section{Conclusion} Causal machine learning can be used to identify preventable hospital readmissions, if the requisite interventional data are available. Moreover, our results point to a mismatch between readmission risk and treatment effect, which is consistent with suggestions in prior work. In our setting, the extent of this mismatch was considerable, suggesting that many preventable readmissions may be being "left on the table" with current risk modeling methodology. Our proposed framework is also generalizable to the study of a variety of population health management and quality improvement interventions driven by predictive models, as well as of algorithm-driven interventions in a range of settings outside of healthcare. \newpage \section*{Acknowledgements} The authors are immensely grateful to Colleen Plimier of the Division of Research, Kaiser Permanente Northern California, for assistance with data preparation, as well as to Dr. Tracy Lieu, also of the Division of Research, for reviewing the manuscript. In addition, the authors wish to thank Minh Nguyen, Stephen Pfohl, Scotty Fleming, and Rachael Aikens for helpful feedback on earlier versions of this work. Mr. Marafino was supported by a predoctoral fellowship from the National Library of Medicine of the National Institutes of Health under Award Number T15LM007033, as well as by funding from a Stanford School of Medicine Dean's Fellowship. Dr. Baiocchi was also supported by grant KHS022192A from the Agency for Healthcare Research and Quality. Dr. Vincent Liu was also supported by NIH grant R35GM128672 from the National Institute of General Medical Sciences. Portions of this work were also funded by The Permanente Medical Group, Inc., and Kaiser Foundation Hospitals, Inc. The content is solely the responsibility of the authors and does not necessarily represent the official views of the National Institutes of Health. The authors have no conflicts of interest to disclose. The funders played no role in the study design, data collection, analysis, reporting of the data, writing of the report, nor the decision to submit the article for publication. \section*{Appendix A} \setcounter{table}{0} \renewcommand{\thetable}{A\arabic{table}} \begin{table}[H] \centering \resizebox{\textwidth}{!}{% \begin{tabular}{@{}lccccc@{}} \toprule & Total & Pre-implementation & Post-implementation & \multicolumn{1}{l}{$p$-value} & \multicolumn{1}{l}{SMD} \\ \midrule Hospitalizations, $n$ & 1,584,902 & 1,161,452 & 423,450 & --- & --- \\ Patients, $n$ & 753,587 & 594,053 & 266,478 & --- & --- \\ Inpatient (\%) & 82.8 (69.7-90.6) & 84.4 (73.1-90.7) & 78.5 (57.7-90.3) & $<0.0001$ & -0.151 \\ Observation (\%) & 17.2 (9.4-30.3) & 15.6 (9.3-26.9) & 21.5 (9.7-42.3) & $<0.0001$ & 0.151 \\ Inpatient stay $<24$ hours & 5.2 (3.3-6.7) & 5.1 (3.8-6.5) & 5.6 (1.8-9.1) & $<0.0001$ & 0.041 \\ Transport-in & 4.5 (1.4-8.7) & 4.5 (1.7-8.8) & 4.5 (0.4-8.4) & 0.56 & -0.001 \\ Age, mean (years) & 65.3 (62.2-69.8) & 65.1 (61.9-69.6) & 65.8 (62.8-70.4) & $<0.0001$ & 0.038 \\ Male gender (\%) & 47.5 (43.4-53.8) & 47.0 (42.4-53.5) & 48.9 (45.3-54.9 & $<0.0001$ & 0.037 \\ KFHP membership (\%) & 93.5 (75.3-97.9) & 93.9 (80.0-98.0) & 92.5 (61.7-97.6) & $<0.0001$ & -0.052 \\ Met strict membership definition (\%) & 80.0 (63.4-84.9) & 80.6 (67.6-85.5) & 78.5 (51.3-83.8) & $<0.0001$ & -0.053 \\ Met regulatory definition (\%) & 61.9 (47.2-69.7) & 63.9 (50.2-72.2) & 56.5 (38.7-66.6) & $<0.0001$ & -0.152 \\ Admission via ED (\%) & 70.4 (56.7-82.0) & 68.9 (56.0-80.3) & 74.4 (58.4-86.6) & $<0.0001$ & 0.121 \\ Charlson score, median (points) & 2.0 (2.0-3.0) & 2.0 (2.0-3.0) & 2.0 (2.0-3.0) & $<0.0001$ & 0.208 \\ Charlson score $\geq 4$ (\%) & 35.2 (29.2-40.7) & 33.2 (28.2-39.8) & 40.9 (33.0-46.2) & $<0.0001$ & 0.161 \\ COPS2, mean (points) & 45.6 (39.1-52.4) & 43.5 (38.4-51.5) & 51.2 (39.7-55.8) & $<0.0001$ & 0.159 \\ COPS2 $\geq 65$ (\%) & 26.9 (21.5-32.0) & 25.3 (21.0-31.6) & 31.1 (22.5-35.4) & $<0.0001$ & 0.129 \\ Admission LAPS2, mean (points) & 58.6 (48.0-67.6) & 57.6 (47.4-65.8) & 61.3 (50.2-72.8) & $<0.0001$ & 0.092 \\ Discharge LAPS2, mean (points) & 46.7 (42.5-50.8) & 46.3 (42.5-50.8) & 47.6 (42.3-52.9) & $<0.0001$ & 0.039 \\ LAPS2 $\geq 110$ (\%) & 12.0 (7.8-16.0) & 11.6 (7.5-15.2) & 12.9 (8.3-18.4) & $<0.0001$ & 0.039 \\ Full code at discharge (\%) & 84.4 (77.3-90.5) & 84.5 (77.7-90.5) & 83.9 (75.9-90.5) & $<0.0001$ & -0.016 \\ Length of stay, days (mean) & 4.8 (3.9-5.4) & 4.9 (3.9-5.4) & 4.7 (3.9-5.6) & $<0.0001$ & -0.034 \\ Discharge disposition (\%) & & & & & 0.082 \\ \quad To home & 72.7 (61.0-86.2) & 73.3 (63.9-85.9) & 71.0 (52.1-86.9) & $<0.0001$ & \\ \quad Home Health & 16.1 (6.9-23.3) & 15.2 (6.9-22.6) & 18.5 (7.0-34.5) & $<0.0001$ & \\ \quad Regular SNF & 9.9 (5.9-14.3) & 10.0 (6.0-15.2) & 9.5 (5.6-12.4) & $<0.0001$ & \\ \quad Custodial SNF & 1.3 (0.7-2.5) & 1.5 (0.8-2.7) & 0.9 (0.4-1.8) & $<0.0001$ & \\ Hospice referral (\%) & 2.6 (1.7-4.4) & 2.6 (1.7-4.6) & 2.7 (1.5-4.0) & $<0.0001$ & 0.007 \\ \midrule \textbf{Outcomes}& & & & & \\ \quad Inpatient mortality (\%) & 2.8 (2.1-3.3) & 2.8 (2.1-3.3) & 2.8 (1.8-3.3) & 0.17 & -0.003 \\ \quad 30-day mortality (\%) & 6.0 (4.0-7.3) & 6.1 (4.1-7.6) & 5.9 (3.9-6.8) & $<0.0001$ & -0.006 \\ \quad Any readmission (\%) & 14.5 (12.7-17.2) & 14.3 (12.3-17.3) & 15.1 (13.3-17.0) & $<0.0001$ & 0.021 \\ \quad Any non-elective readmission (\%) & 12.4 (10.4-15.4) & 12.2 (10.2-15.5) & 13.1 (10.8-15.4) & $<0.0001$ & 0.029 \\ \quad Non-elective inpatient readmission (\%) & 10.5 (8.2-12.6) & 10.4 (8.1-12.8) & 10.8 (8.6-12.9) & $<0.0001$ & 0.012 \\ \quad Non-elective observation readmission (\%) & 2.4 (1.4-3.7) & 2.2 (1.2-3.4) & 3.0 (1.9-5.6) & $<0.0001$ & 0.049 \\ \quad 30-day post-discharge mortality (\%) & 4.0 (2.6-5.2) & 4.1 (2.7-5.4) & 3.9 (2.3-4.9) & $<0.0001$ & -0.007 \\ \quad Composite outcome (\%) & 15.2 (12.9-18.8) & 15.0 (12.9-19.1) & 15.8 (13.3-18.0) & $<0.0001$ & 0.023 \\ \bottomrule \end{tabular}} \caption{Characteristics of the cohort, including both index and non-index stays. Notably, comparing pre- to post-implementation, hospitalized patients were older, and tended to have higher comorbidity burden (higher COPS2) as well as a higher acuity of illness at admission (higher LAPS2). The use of observation stays also increased. These differences reflect a broader trend towards the pool of potential inpatient admissions becoming more and more ill over the decade from 2010, in large part due to the effectiveness of outpatient preventative care processes at KPNC, as well as of programs providing care outside of the hospital setting as an alternative to admission. Otherwise, care patterns did not substantially change, as evidenced by, e.g., transports-in, Kaiser Foundation Health Plan (KFHP) membership status, and discharge disposition mix, all of which had standardized mean differences (SMDs) $<0.1$. In large cohorts such as this one, SMDs can be a better guide to detecting covariate imbalances or differences between groups, owing to the effects of large sample sizes. Finally, as a consequence of increased comorbidity burden and admission acuity, and despite the implementation of the Transitions Program, rates of readmission and of the composite outcome increased from pre- to post-implementation. Abbreviations: SMD, standardized mean difference; KFHP, Kaiser Foundation Health Plan; LAPS2, Laboratory-based Acute Physiology Score, version 2; COPS2, COmorbidity Point Score, version 2; SNF, skilled nursing facility.} \label{tab:a1} \end{table} \section*{Appendix B} \setcounter{table}{0} \renewcommand{\thetable}{B\arabic{table}} \begin{table}[H] \centering \resizebox{\textwidth}{!}{% \begin{tabular}{@{}lc@{}} \toprule Supergroup name (\texttt{HCUPSGDC}) & \begin{tabular}[c]{@{}c@{}}Clinical Classification Software (CCS) \\ category code(s)\end{tabular} \\ \midrule Acute CVD & 109 \\ AMI & 100 \\ CAP & 122 \\ Cardiac arrest & 107 \\ CHF & 108 \\ Coma; stupor; and brain damage & 85 \\ Endocrine \& related conditions & 48-51, 53, 54, 56, 58, 200, 202, 210, 211 \\ Fluid and electrolyte disorders & 55 \\ GI bleed & 153 \\ Hematologic conditions & 59-64 \\ Highly malignant cancer & 17, 19, 27, 33, 35, 38-43 \\ Hip fracture & 226 \\ Ill-defined signs and symptoms & 250-253 \\ Less severe cancer & 11-16, 18, 20-26, 28-32, 34, 36, 37, 44-47, 207 \\ Liver and pancreatic disorders & 151, 152 \\ Miscellaneous GI conditions & 137-140, 155, 214 \\ Miscellaneous neurological conditions & 79-84, 93-95, 110-113, 216, 245, 653 \\ Miscellaneous surgical conditions & 86-89, 91, 118-121, 136, 142, 143, 167, 203, 204, 206, 208, 209, 212, 237, 238, 254, 257 \\ Other cardiac conditions & 96-99, 103-105, 114, 116, 117, 213, 217 \\ Other infectious conditions & 1, 3-9, 76-78, 90, 92, 123-126, 134, 135, 148, 197-199, 201, 246-248 \\ Renal failure (all) & 156, 157, 158 \\ Residual codes & 259 \\ Sepsis & 2 \\ Trauma & 205, 225, 227-236, 239, 240, 244 \\ UTI & 159 \\ \bottomrule \end{tabular}} \caption{List of Clinical Classification Software (CCS)-defined supergroups and their CCS codes used in this study. These supegroups represent levels of the covariate \texttt{HCUPSGDC}. More details on the CCS codes themselves, as well as mappings to their component ICD codes, can be found at \url{www.ahrq.gov/data/hcup}.} \label{tab:b1} \end{table} \newpage \printbibliography \end{spacing} \end{document}
{'timestamp': '2020-07-21T02:14:51', 'yymm': '2005', 'arxiv_id': '2005.14409', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14409'}
arxiv
\section{Introduction} Diabetic patients are at constant risk of developing Diabetic Retinopathy (DR) that may eventually lead to permanent vision loss if left unnoticed or untreated. In such patients, increased blood sugar, blood pressure, and cholesterol can cause small blood vessels in retina to protrude and, in due course, haemorrhage blood into retinal layers and/or vitreous humour \cite{amin2017method}. In severe conditions, scar tissues and newly proliferated fragile blood vessels blanket the retina and obstruct incoming light from falling on it. As a result, retina is unable to translate light into neural signals which results in blindness. Diabetic retinopathy advances slowly and gradually and may take years to reach proliferative stage, however, almost every diabetic patient is potentially susceptible to this complication. Timely diagnosis is the key to appropriate prognosis. Ophthalmologists usually detect DR by examining retinal fundus and looking for any signs of microaneurysms (bulging of blood vessels), blood leakage, and/or neovascularization \cite{akram2014detection}. While the indications of advanced stages of DR are rather prominent, these symptoms remain largely discrete in early stages. Figure \ref{fig:drStages} shows progress of DR from healthy to proliferative stage in Retinal Fundus Images (RFIs) taken from EyePACS dataset\footnote{https://www.kaggle.com/c/diabetic-retinopathy-detection/data}. It can be observed from the figure that the difference between healthy and early stages of DR are very subtle and not readily discernible. Manual analysis of these images requires highly qualified and specialized ophthalmologists who may not be easily accessible in developing countries or remote areas of developed countries. Even when medical experts are available, large scale analysis of RFIs is highly time-consuming, labour-intensive and prone to human error and bias. Furthermore, manual diagnosis by clinicians is largely subjective and rarely reproducible and, therefore, inter-expert agreement for a certain diagnosis is generally very poor. Computer-Aided Diagnosis (CAD) based on deep learning can provide easily accessible, efficient and economical solution for large-scale initial screening of many diseases including diabetic retinopathy. CAD can perform objective analysis of the given image and predict standardized and reproducible diagnosis, which is free from any bias or tiredness. It can not only help physicians by reducing their workload but can also outreach to underprivileged population and afford them the opportunity of swift and cost-effective initial screening, which may effectively prevent advancement of disease into severer stage. \begin{figure}[h] \centering \addtocounter{figure}{-1} \begin{subfigure}{0.19\textwidth} \includegraphics[width=\textwidth]{EyePACS0r.jpeg} \caption{(a) Healthy} \label{fig:healthy} \end{subfigure} \begin{subfigure}{0.19\textwidth} \includegraphics[width=\textwidth]{EyePACS1r.jpeg} \caption{(b) Mild} \label{fig:mild} \end{subfigure} \begin{subfigure}{0.19\textwidth} \includegraphics[width=\textwidth]{EyePACS2r.jpeg} \caption{(c) Moderate} \label{fig:moderate} \end{subfigure} \begin{subfigure}{0.19\textwidth} \includegraphics[width=\textwidth]{EyePACS3r.jpeg} \caption{(d) Severe} \label{fig:severe} \end{subfigure} \begin{subfigure}{0.19\textwidth} \includegraphics[width=\textwidth]{EyePACS4r.jpeg} \caption{(e) Proliferative} \label{fig:prolif} \end{subfigure} \caption{Progression of diabetic retinopathy from healthy to proliferative stage is subtle and gradual. Images are taken from EyePACS train set.} \label{fig:drStages} \end{figure} Convolutional Neural Networks (CNNs) are computer algorithms inspired by biological visual cortex. They work especially well in visual recognition tasks. CNNs have been used to perform at par with or even outperform humans in various challenging image recognition problems \cite{DBLP:journals/corr/abs-1712-00559,lee2016generalizing}. Today automated image recognition can be divided into coarse-grained classification and fine-grained classification. In former case, images are classified into high-level categories like humans, animals, vehicles and other objects in a natural scene, for example. In later case, classification is focused on low-level categories like species of dogs or models of cars etc. Fine-grained classification is particularly challenging owning to high intra-class variations and low inter-class variations. Although DR is also a fine-grained classification task, it has normally been addressed using simple coarse-grained classification algorithms. In this work we used a combination of general and fine-grained deep CNNs to analyze RFIs and predict automated diagnosis for DR. We used two of the most popular conventional image classification architectures i.e Residual Networks \cite{he2016resnet} and Densely Connected Networks \cite{huang2017densenet}, a network search framework called NASNet \cite{zoph2018nasnet} and two recently proposed methods for fine-grained classification namely NTS-Net \cite{yang2018ntsNet} and SBS Layer \cite{recasens2018saliency}. We tried to harvest the combined potential of these two approaches by training them separately and taking their ensemble during inference. We used EyePACS and Messidor datasets for evaluation. Since previous researches have used vastly disparate experimental setups, we cannot directly compare our results with most of them. However, we performed a broad range of experiments, following the most common problem settings in the literature like normal vs abnormal, referable vs non-referable, ternary and quaternary classification in order to define benchmarks which will afford future works with an opportunity of fair comparison. \subsection{Related Work}\label{sec:relatedWork} Over the past decade, machine learning and deep learning have been used to detect various pathologies, segment vessels and classify DR grades using RFIs. Welikala et al. \cite{welikala2014automated}~ detected proliferative DR by identifying neovascularization. They used an ensemble of two networks trained separately on 100 different patches for each network. The patches are taken from a selected set of 60 images collected from Messidor \cite{messidor2014feedback} and a private dataset. Since the dataset had only 60 images they performed leave-one-out cross validation and achieved 0.9505 Area Under the Curve (AUC) and sensitivity of 1 with specificity of 0.95 at the optimal operating point. Wang et al. \cite{wang2017zoom} identified suspicious regions in RFIs and classified DR into normal (nDR) vs abnormal (aDR) and referable (rDR) vs non-referable (nrDR). They developed a CNN based model called Zoom-in-Network to identify important regions. To classify an image the network uses the overview of the whole images and pays particular attention to important regions. They took 182 images from EyePACS dataset and let a trained ophthalmologist draw bounding boxes around 306 lesions. On Messidor dataset they achieved 0.921 AUC, 0.905 accuracy and 0.960 sensitivity at 0.50 specificity for nDR vs aDR. Gulshan et al. \cite{gulshan2016development} conducted a comprehensive study to distinguish rDR from nrDR grades. They trained a deep CNN on 128175 fundus images from a private dataset and tested on 9963 images from EyePACS-I and 1748 images of Messidor-2. They achieved AUC of 0.991 on EyePACS-I and 0.990 on Messidor-2. Guan et al. \cite{guan2018said} proposed that modeling each classifier after individual human grader instead of training a single classifier using average grading of all human experts improves classification performance. They trained 31 classifiers using a dataset of total 126522 images collected from EyePACS and three other clinics. The method is tested on 3547 images from EyePACS-I and Messidor-2, and achieved 0.9728 AUC, 0.9025 accuracy, and 0.8181 specificity at 0.97 sensitivity. However, it would have been more interesting if they had provided comparison of their suggested approach with ensemble of 31 networks modeled after average grading. Costa et al. \cite{costa2018end} used adversarial learning to synthesize color retinal images. However, the performance of their classifier trained on synthetic images was less than the classifier trained on real images. Aujih et al. \cite{aujih2018analysis} found that blood vessels play important role in disease classification and fundus images without blood vessels resulted in poor performance by the classifier. The role of multiple filter sizes in learning fine-grained features was studied by Vo et al. \cite{vo2016new}. To this end they used VGG network with extra kernels and combined kernels with multiple loss networks. They achieved 0.891 AUC for rDR vs nrDR and 0.870 AUC for normal vs abnormal on Messidor dataset using 10-fold cross validation. Somkuwar et al. \cite{somkuwar2015intensity} performed classification of hard exudates by exploiting intensity features using 90 images from Messidor dataset and achieved 100\% accuracy on normal and 90\% accuracy on abnormal images. Seoud et al. \cite{seoud2016red} focused on red lesions in RFIs, like haemorrhages and microaneurysms, and detected these biomarkers using dynamic shape features in order to classify DR. They achieved 0.899 AUC and 0.916 AUC for nDR vs aDR and rDR vs nrDR, respectively on Messidor. Rakhlin et al. \cite{rakhlin2018diabetic} used around 82000 images taken from EyePACS for training and around 7000 EyePACS images and 1748 images from Messidor-2 for testing their deep learning based classifier. They achieved 0.967 AUC on Messidor and 0.923 AUC on EyePACS for binary classification. Ramachandran et al. \cite{ramachandran2018diabetic} used 485 private images and 1200 Messidor images to test a third party deep learning based classification platform, which was trained on more than 100000 images. Their validation gave them 0.980 AUC on Messidor dataset for rDR vs nrDR classification. Quellec et al. \cite{quellec2017deep} capitalized a huge private dataset of around 110000 images and around 89000 EyePACS images to train and test a classifier for rDR vs nrDR grades and achieved 0.995 AUC on EyePACS. \vspace{-0.4 cm} \section{Materials and Methods} \vspace{-0.3 cm} This section provides details on the datasets used in this work and the ensemble methodology employed to perform classification. \subsection{Datasets} We used EyePACS dataset published publicly by Kaggle for a competition on Diabetic Retinopathy Detection. Table \ref{tab:EyePACS} gives overview of EyePACS dataset. Although this dataset is very large in size, only about 75\% of its images are of reasonable quality that they can be graded by human experts \cite{rakhlin2018diabetic}. EyePACS is graded on a scale of 0 to 4 in accordance with International Clinical Diabetic Retinopathy (ICDR) guidelines \cite{ICDR2002}. However, low gradability of this dataset raises suspicions on the fidelity of labels provided with each image. We pruned the train set to get rid of 657 completely uninterpretable images. For testing on EyePACS we used 33423 images randomly taken from test set. \begin{table}[h] \caption{Overview of EyePACS Dataset. IRMA stands for IntraRetinal Microvascular Abnormalities}\label{tab:EyePACS} \centering \resizebox{\textwidth}{!}{% \begin{tabular}{@{}cp{6cm}cccc@{}} \toprule \multirow{2}{*}{Severity Grade} & \multicolumn{1}{c}{\multirow{2}{*}{Criterion}} & \multicolumn{2}{c}{Train Set} & \multicolumn{2}{c}{Test Set} \\ \cmidrule(l){3-6} & \multicolumn{1}{c}{} & Images & Percentage & Images & Percentage \\ \midrule 0 & No Abnormalities & 25810 & 73.48 & 39533 & 73.79 \\ \hline 1 & Microaneurysms Only & 2443 & 6.95 & 3762 & 7.02 \\ \hline 2 & More than just microaneurysms but less than Grade 3 & 5292 & 15.07 & 7861 & 14.67 \\ \hline 3 & \begin{tabular}[c]{@{}p{6cm}@{}}More than 20 intraretinal hemorrhages in each of 4 quadrants\\ OR Definite venous beading in 2+ quadrants\\ OR Prominent IRMA in 1+ quadrant\\ AND no signs of proliferative retinopathy\end{tabular} & 873 & 2.48 & 1214 & 2.27 \\ \hline 4 & \begin{tabular}[c]{@{}p{6cm}@{}}Neovascularization\\ OR Vitreous/preretinal hemorrhage\end{tabular} & 708 & 2.02 & 1206 & 2.25 \\ \hline \multicolumn{2}{c}{Total} & 35126 & 100 & 53576 & 100 \\ \bottomrule \end{tabular} } \end{table} Messidor dataset consists of 1200 images collected at three different clinics in France. Each clinic contributed 400 images. This dataset is graded for DR on a scale of 0 to 3 following the criteria given in Table \ref{tab:Messidor}. Messidor dataset is validated by experts and is, therefore, of higher quality than EyePACS in terms of both image quality and labels. \begin{table}[h] \caption{Overview of Messidor Dataset}\label{tab:Messidor} \centering \begin{tabular}{clcc} \hline Severity Grade & \multicolumn{1}{c}{Criterion} & Images & Percentage \\ \hline 0 & \begin{tabular}[c]{@{}l@{}}No microaneurysms\\ AND No haemorrhages\end{tabular} & 546 & 45.50 \\ \hline 1 & \begin{tabular}[c]{@{}l@{}}Microaneurysms \textless{}= 5\\ AND No haemorrhages\end{tabular} & 153 & 12.75 \\ \hline 2 & \begin{tabular}[c]{@{}l@{}}5 \textless Microaneurysms \textless 15\\ AND 0 \textless Haemorrhages \textless 5\\ AND No Neovascularization\end{tabular} & 247 & 20.58 \\ \hline 3 & \begin{tabular}[c]{@{}l@{}}Microaneurysms \textgreater{}= 15\\ OR Haemorrhages \textgreater{}= 5\\ OR Neovascularization\end{tabular} & 254 & 21.17 \\ \hline \multicolumn{2}{c}{Total} & 1200 & 100 \\ \hline \end{tabular}% \end{table} \subsection{Methodology} \begin{figure}[b!] \centering \includegraphics[width=\textwidth]{ensembleDR.png} \caption{System Overview: Combining Coarse-Grained and Fine-Grained Classifiers} \label{fig:systemOverview} \end{figure} Figure \ref{fig:systemOverview} illustrates complete pipeline of the system combining coarse-grained and find-grained classifiers. Before feeding an image to the network, we first applied Otsu Thresholding to extract and crop retinal rim from RFI and get rid of irrelevant black background. Since the images in both datasets are taken with different cameras and under different clinical settings, they suffer from large brightness and color variations. We used adaptive histogram equalization to normalize brightness and enhance the contrast of visual artefacts which are critical for DR detection. Since the images are in RGB colour space, we first translate them into YCbCr colour space to distribute all luminosity information in Y channel and colour information in Cb and Cr channels. Adaptive histogram equalization is then applied on Y channel only and the resultant image is converted back to RGB colour space. We further normalized the images by subtracting local average colour from each pixel to highlight the foreground and help our network detect small features. Figure \ref{fig:PreProcess} shows the effects of preprocessing steps on RFIs. These pre-processed images are then used to train all five networks individually. During inference, each network gives diagnosis which are ensembled to calculate the final prediction. \begin{figure}[t] \centering \addtocounter{figure}{-1} \begin{subfigure}{0.32\textwidth} \includegraphics[width=\textwidth]{original} \caption{(a) Original Image before Preprocessing} \label{fig:original} \end{subfigure} \begin{subfigure}{0.32\textwidth} \includegraphics[width=\textwidth]{CLAHE.jpeg} \caption{(b) After Contrast Enhancement} \label{fig:histEq} \end{subfigure} \begin{subfigure}{0.32\textwidth} \includegraphics[width=\textwidth]{subtract-local-average.jpeg} \caption{(c) After Local Average Colour Subtraction} \label{fig:lvcSubtr} \end{subfigure} \caption{Effects of preprocessing steps on retinal fundus images} \label{fig:PreProcess} \end{figure} \subsubsection{Experimental Setup} From EyePACS train set, we randomly selected 30000 images for training and rest of the 4469 images were used for validation. Test set of EyePACS was used for reporting results on this dataset. From Messidor, we used 800 images for training and 400 images from Lariboisi\`ere Hospital for testing (as done by Lam et al. \cite{carson2018automated}). We employed a broad range of hyper parameters during training. All networks are initialized with pre-trained weights and fine-tuned on ophthalmology datasets. To evaluate these models on EyePACS and Messidor datasets under similar problem settings, we first parallelized DR grades of both datasets using criteria given in Figure \ref{fig:grades}. \begin{figure}[b] \centering \includegraphics[width=0.70\textwidth]{grades.png} \caption{Conversion of EyePACS grades to Quaternary, Ternary and Binary Classification} \label{fig:grades} \end{figure} \section{Results and Analysis} From section \ref{sec:relatedWork} we observe that previous works on EyePACS and Messidor have used disparate train and test splits and different classification tasks for example Quaternary, Ternary and Binary (rDR vs nrDR and nDR vs aDR). Furthermore, different researchers use different performance metrics to evaluate their method. Therefore, in such scenario comparison of any two works in not directly possible \cite{abramoff2016improved}. However, we conducted extensive experiments to perform all four classification tasks mentioned above and report comprehensive results to allow a rough comparison with some of the published state-of-the-art results on these datasets. \subsection{Results of Binary Classification} As discussed above, many previous works focus primarily on binary classification as nDR vs aDR or rDR vs nrDR grading. The criteria to convert 4 or 5 grades into binary grades is given in Figure \ref{fig:grades}. For our binary classification, the number of images used for training, validation and testing from EyePACS and Messidor are given in Table \ref{tab:distNAB} and \ref{tab:distRNR}. It can be seen from the tables that there is extensive class imbalance between both classes. Table \ref{tab:allResults} provides detailed performance metrics for all classification tasks including nDR vs aDR classification. Our results are competitive to that of Wang et al. in terms of accuracy and for all other metrics we outperform them. It should be noted here that Wang et al. performed 10-fold cross validation and although their sensitivity of 96 is higher than our 89.75, it is calculated at 50\% specificity while ours is at 90\% specificity. \begin{table} \resizebox{\textwidth}{!}{% \parbox[t]{.49\linewidth}{ \centering \caption{Class Distribution for Normal vs Abnormal Classification}\label{tab:distNAB} \resizebox{0.50\textwidth}{!}{ \begin{tabular}{lcccccc} \hline \multicolumn{1}{c}{\multirow{2}{*}{Grade}} & \multicolumn{3}{c}{EyePACS} & \multicolumn{3}{c}{Messidor} \\ \cline{2-7} \multicolumn{1}{c}{} & Train & Validate & Test & Train & Validate & Test \\ \hline Normal & 22668 & 2744 & 24741 & 346 & 49 & 151 \\ Abnormal & 7332 & 1725 & 8682 & 354 & 51 & 249 \\ Total & 30000 & 4469 & 33423 & 700 & 100 & 400 \\ \hline \end{tabular} } } \hfill \parbox[t]{.49\linewidth}{ \centering \caption{Class Distribution for Referable vs Non-Referable Classification}\label{tab:distRNR} \resizebox{0.50\textwidth}{!}{ \begin{tabular}{lcccccc} \hline \multicolumn{1}{c}{\multirow{2}{*}{Grade}} & \multicolumn{3}{c}{EyePACS} & \multicolumn{3}{c}{Messidor} \\ \cline{2-7} \multicolumn{1}{c}{} & Train & Validate & Test & Train & Validate & Test \\ \hline Non-Referable & 28825 & 4177 & 31937 & 453 & 65 & 181 \\ Referable & 1175 & 292 & 1486 & 247 & 35 & 219 \\ Total & 30000 & 4469 & 33423 & 700 & 100 & 400 \\ \hline \end{tabular} } } } \end{table} \begin{table}[] \centering \caption{Detailed Performance Metrics for Various Classification Settings}\label{tab:allResults} \resizebox{\textwidth}{!}{% \begin{tabular}{@{}lcccccccc@{}} \toprule \multicolumn{9}{c}{\textbf{Results of Binary (Normal vs Abnormal) Classification}} \\ \midrule \multicolumn{1}{c}{\multirow{2}{*}{\textbf{Model}}} & \multicolumn{2}{c}{\textbf{Accuracy (\%)}} & \multicolumn{2}{c}{\textbf{AUC (\%)}} & \multicolumn{2}{c}{\textbf{Sensitivity (\%)}} & \multicolumn{2}{c}{\textbf{Specificity (\%)}} \\ \cmidrule(l){2-9} \multicolumn{1}{c}{} & EyePACS & Messidor & EyePACS & Messidor & EyePACS & Messidor & EyePACS & Messidor \\ \midrule NTS-Net & \textbf{88.19} & 88.00 & 92.72 & 95.20 & 88 & 88.00 & 72 & 87.51 \\ SBS Layer & 80.11 & 89.50 & 86.20 & 95.17 & 80 & 89.50 & 54 & \textbf{92.07} \\ ResNet-50 & 82.86 & 87.75 & 89.46 & 95.06 & 83 & 87.75 & 75 & 90.49 \\ DenseNet-201 & 82.66 & 87.75 & 89.69 & 95.89 & 83 & 87.75 & \textbf{77} & 88.14 \\ NASNet & 82.19 & 87.25 & 88.49 & 95.04 & 82 & 87.25 & 73 & 89.14 \\ \textbf{Ensemble} & 87.74 & \textbf{89.75} & \textbf{93.44} & \textbf{96.50} & \textbf{88} & \textbf{89.75} & 75 & 91.44 \\ Vo et. al & N/A & 87.10 & N/A & 87.00 & N/A & 88.2 & N/A & 85.7 \\ Wang et. al & N/A & 90.50 & N/A & 92.10 & N/A & 96 & N/A & 50 \\ Soud et. al & N/A & N/A & N/A & 89.90 & N/A & N/A & N/A & N/A \\ \midrule \multicolumn{9}{c}{\textbf{Results of Binary (Referable vs Non-Referable) Classification}} \\ \midrule NTS-Net & 94.93 & \textbf{93.25} & 99.10 & \textbf{96.56} & 95 & \textbf{93} & 75 & \textbf{94} \\ SBS Layer & \textbf{95.89} & 88.75 & \textbf{99.44} & 94.90 & \textbf{96} & 89 & 67 & 90 \\ ResNet-50 & 95.08 & 86.75 & 98.97 & 94.95 & 95 & 87 & 81 & 89 \\ DenseNet-201 & 94.70 & 89.25 & 99.05 & 95.33 & 95 & 89 & 82 & 91 \\ NASNet & 91.98 & 87.50 & 97.45 & 95.16 & 92 & 88 & \textbf{85} & 89 \\ \textbf{Ensemble} & 95.34 & 89.25 & 99.23 & 96.45 & 95 & 89 & 81 & 91 \\ Lam et. al & N/A & 74.5 & N/A & N/A & N/A & N/A & N/A & N/A \\ Vo et. al & N/A & 89.70 & N/A & 89.10 & N/A & 89.3 & N/A & 90 \\ Wang et. al & N/A & 91.10 & N/A & 95.70 & N/A & 97.8 & N/A & 50 \\ Seoud et. al & N/A & 74.5 & N/A & 91.60 & N/A & N/A & N/A & N/A \\ \midrule \multicolumn{9}{c}{\textbf{Results of Ternary Classification}} \\ \midrule NTS-Net & 84.43 & 84.50 & 94.89 & 94.61 & 84 & 85 & 72 & \textbf{94} \\ SBS Layer & 76.93 & 84.50 & 90.95 & 94.12 & 77 & 85 & 50 & 91 \\ ResNet-50 & 81.23 & 80.50 & 93.51 & 93.79 & 81 & 81 & 74 & 92 \\ DenseNet-201 & 79.20 & 80.25 & 92.87 & 94.25 & 79 & 80 & \textbf{77} & 93 \\ NASNet & 78.95 & 81.75 & 91.93 & 94.00 & 79 & 82 & 71 & 89 \\ \textbf{Ensemble} & \textbf{84.94} & \textbf{85.25} & \textbf{95.28} & \textbf{95.40} & \textbf{85} & \textbf{85} & 73 & 92 \\ Lam et. al & N/A & 68.8 & N/A & N/A & N/A & N/A & N/A & N/A \\ \midrule \multicolumn{9}{c}{\textbf{Results of Quaternary Classification}} \\ \midrule NTS-Net & 82.53 & 74.50 & 95.72 & 91.84 & 83 & 75 & \textbf{76} & \textbf{92} \\ SBS Layer & 82.00 & 65.00 & 95.69 & 88.43 & 82 & 65 & 67 & 88 \\ ResNet-50 & 81.82 & 70.25 & 95.53 & 91.31 & 82 & 70 & 71 & 89 \\ DenseNet-201 & 79.38 & 74.00 & 95.04 & 92.26 & 79 & 74 & 75 & 91 \\ NASNet & 73.73 & 71.75 & 92.06 & 90.84 & 74 & 72 & 74 & 86 \\ \textbf{Emsemble} & \textbf{83.42} & \textbf{76.25} & \textbf{96.31} & \textbf{92.99} & \textbf{83} & \textbf{76} & 73 & 91 \\ Lam et. al & N/A & 57.2 & N/A & N/A & N/A & N/A & N/A & N/A \\ \bottomrule \end{tabular}% } \end{table} Results of rDR vs nrDR classification can also be found in Table \ref{tab:allResults}. All networks performed significantly better for this task than for normal vs abnormal classification on EyePACS dataset reaching maximum accuracy around 96\% with 99.44\% AUC using SBS layer architecture. For Messidor dataset, both NTS-Net and SBS Layer stand out from traditional classifiers. NTS-Net outperforms all other methods in all metrics, whereas ensemble of all methods gives sub-optimal performance than individual fine-grained methods. This can happen when majority of classifiers used for ensembling have a skewed performance towards downside and only a few give standout results. \subsection{Results of Multi-Class Classification} The complexity of classification task was gradually increased from binary to ternary and quaternary classification. Table \ref{tab:dist4c} and \ref{tab:dist3c} show the class distribution in train, validation and test splits for this multi-class setting. For ternary classification we used the criterion used by \cite{carson2018automated}, as shown in Figure \ref{fig:grades}. \begin{table} \parbox[t]{.49\linewidth}{ \centering \caption{Class Distribution for 4-Class Classification}\label{tab:dist4c} \resizebox{0.50\textwidth}{!}{ \begin{tabular}{ccccccc} \hline \multicolumn{1}{l}{\multirow{2}{*}{Grade}} & \multicolumn{3}{c}{EyePACS} & \multicolumn{3}{c}{Messidor} \\ \cline{2-7} \multicolumn{1}{l}{} & Train & Validate & Test & Train & \multicolumn{1}{l}{Validate} & \multicolumn{1}{l}{Test} \\ \hline 0 & 22668 & 2744 & 24741 & 346 & 49 & 151 \\ 1 & 6157 & 1433 & 7196 & 107 & 16 & 30 \\ 2 & 685 & 166 & 753 & 155 & 22 & 70 \\ 3 & 490 & 126 & 733 & 92 & 13 & 149 \\ Total & 30000 & 4469 & 33423 & 700 & 100 & 400 \\ \hline \end{tabular} } } \hfill \parbox[t]{.49\linewidth}{ \centering \caption{Class Distribution for 3-Class Classification}\label{tab:dist3c} \resizebox{0.50\textwidth}{!}{ \begin{tabular}{ccccccc} \hline \multicolumn{1}{l}{\multirow{2}{*}{Grade}} & \multicolumn{3}{c}{EyePACS} & \multicolumn{3}{c}{Messidor} \\ \cline{2-7} \multicolumn{1}{l}{} & Train & Validate & Test & Train & \multicolumn{1}{l}{Validate} & \multicolumn{1}{l}{Test} \\ \hline 0 & 22668 & 2744 & 24741 & 346 & 49 & 151 \\ 1 & 6157 & 1433 & 7196 & 107 & 16 & 30 \\ 2 & 1175 & 292 & 1486 & 247 & 35 & 219 \\ Total & 30000 & 4469 & 33423 & 700 & 100 & 400 \\ \hline \end{tabular} } } \end{table} Performance of individual networks and their ensemble for ternary and quaternary classification is given in Table \ref{tab:allResults}. Ensemble of all models gave better performance in this case. We also observe that the performance of NTS-Net is higher than all other individual networks. Our accuracies for both ternary and quaternary classification are superior than accuracies reported by Lam et al. \cite{carson2018automated}. Figure \ref{fig:confMats} provides a detailed overview of classification performance of ensemble. \begin{comment} \begin{figure}[t] \centering \begin{subfigure}{0.49\textwidth} \includegraphics[width=\textwidth]{rocNAB.png} \caption{Normal/Abnormal} \label{fig:referable_roc} \end{subfigure} \begin{subfigure}{0.49\textwidth} \includegraphics[width=\textwidth]{rocRNR4to2.png} \caption{Referable/Non-Referable} \label{fig:rocRNR} \end{subfigure} \begin{subfigure}{0.49\textwidth} \includegraphics[width=\textwidth]{roc3c.png} \caption{3-ary Classification} \label{fig:roc3c} \end{subfigure} \begin{subfigure}{0.49\textwidth} \includegraphics[width=\textwidth]{roc4cEP.png} \caption{4-ary Classification} \label{fig:roc4c} \end{subfigure} \caption{ROC Curves for all Classification Tasks} \label{fig:ROCs} \end{figure} \end{comment} \begin{figure}[b!] \centering \addtocounter{figure}{-1} \begin{subfigure}{0.24\textwidth} \includegraphics[width=\textwidth]{ConfMatNABEP.png} \caption{N/AB EyePACS} \label{fig:confMat-NAB-EP} \end{subfigure} \begin{subfigure}{0.24\textwidth} \includegraphics[width=\textwidth]{ConfMatRNR4to2EP.png} \caption{R/NR EyePACS} \label{fig:confMat-RNR-EP} \end{subfigure} \begin{subfigure}{0.24\textwidth} \includegraphics[width=\textwidth]{ConfMat3cEP.png} \caption{3-Class EyePACS} \label{fig:confMat-3c-EP} \end{subfigure} \begin{subfigure}{0.24\textwidth} \includegraphics[width=\textwidth]{confMat4cEP.png} \caption{4-Class EyePACS} \label{fig:confMat-4c-EP} \end{subfigure} \begin{subfigure}{0.24\textwidth} \includegraphics[width=\textwidth]{ConfMatNABM.png} \caption{N/AB Messidor} \label{fig:confMat-NAB-M} \end{subfigure} \begin{subfigure}{0.24\textwidth} \includegraphics[width=\textwidth]{ConfMatRNR4to2M.png} \caption{R/NR Messidor} \label{fig:confMat-RNR-M} \end{subfigure} \begin{subfigure}{0.24\textwidth} \includegraphics[width=\textwidth]{ConfMat3cM.png} \caption{3-Class Messidor} \label{fig:confMat-3c-M} \end{subfigure} \begin{subfigure}{0.24\textwidth} \includegraphics[width=\textwidth]{ConfMat4cM.png} \caption{4-Class Messidor} \label{fig:confMat-4c-M} \end{subfigure} \caption{Confusion Matrices for EyePACS and Messidor for all Classification Tasks. N/AB refers to Normal vs Abnormal; R/NR refers to Referable vs Non-Referable} \label{fig:confMats} \end{figure} \section{Conclusion} Diabetic Retinopathy detection using retinal fundus images is a fine-grained classification task. The biomarkers of this disease on retinal images are usually very small in size, especially for early stages, and are scattered all across the image. The ratio of pathologically important region to the whole input volume is therefore minuscule. Due to this reason traditional deep CNNs usually struggle to identify regions of interest and do not learn discriminatory features well. This problem of small and distributed visual artefacts coupled with unavailability of large publicly available high quality dataset with reasonable class imbalance makes DR detection particularly challenging for deep CNN models. However, fine-grained classification networks have high potential to provide standardized and large scale initial screening of diabetic retinopathy and help in prevention and better management of this disease. These networks are equipped with specialized algorithms to discover the important region from the image and pay particular heed to learn characterizing features from those regions. We achieved superior performance for diabetic retinopathy detection on binary, ternary and quaternary classification tasks than many previously reported results. However, due to hugely different experimental setups and choice of performance metrics, it is unfair to draw a direct comparison with any of the cited research. Nevertheless, we have provided a wide spectrum of performance metrics and detailed experimental setup for comparison by any future work. \bibliographystyle{splncs04}
{'timestamp': '2020-06-01T02:03:46', 'yymm': '2005', 'arxiv_id': '2005.14308', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14308'}
arxiv
\section*{Abstract} Researchers and managers model ecological communities to infer the biotic and abiotic variables that shape species' ranges, habitat use, and co-occurrence which, in turn, are used to support management decisions and test ecological theories. Recently, species distribution models were developed for and applied to data from ecological communities. Model development and selection for ecological community data is difficult because a high level of complexity is desired and achieved by including numerous parameters, which can degrade predictive accuracy and be challenging to interpret and communicate. Like other statistical models, multi-species distribution models can be overparameterized. Regularization is a model selection technique that optimizes predictive accuracy by shrinking or eliminating model parameters. For Bayesian models, the prior distribution automatically regularizes parameters. We propose a tree shrinkage prior for Bayesian multi-species distributions models that performs regularization and reduces the number of regression coefficients associated with predictor variables. Using this prior, the number of regression coefficients in multi-species distributions models is reduced by estimation of unique regression coefficients for a smaller number of guilds rather than a larger number of species. We demonstrated our tree shrinkage prior using examples of presence-absence data for six species of aquatic vegetation and relative abundance data for 15 species of fish. Our results show that the tree shrinkage prior can increase the predictive accuracy of multi-species distribution models and enable researchers to infer the number and species composition of guilds from ecological community data. The desire to incorporate more detail and parameters into models must be tempered by the limitations of the data and objectives of a study, which may include developing models that have good predictive accuracy and output that is easier to share with policymakers. Our tree shrinkage prior reduces model complexity while incorporating ecological theory, expanding inference, and can increase the predictive accuracy and interpretability of Bayesian multi-species distribution models. \bigskip{} \begin{doublespace} \noindent \textbf{\textit{\emph{Key-words: }}}Bayesian statistics, community ecology, ecological guild, joint species distribution model, model averaging, model selection, multi-species distribution model, prior distribution, regularization\vspace{-1cm} \end{doublespace} \section*{Introduction} Over the past 20 years species distribution models (SDMs) have become one of the most widely used quantitative methods in ecology (\citealt{elith2009species,franklin2010mapping,guisan2017habitat}). Species distribution models are routinely fit to presence-only, presence-absence, and abundance data to understand the biotic and abiotic variables that influence the habitat use and geographic distribution of a species (\citealt{aarts2012comparative,mcdonald2013location,hefleyHSDM}). The output of SDMs are used in scientific studies to test ecological theories and in application to delineate areas of high conservation value which informs management decisions (e.g., Wisz et al. \citeyear{wisz2013role}; \citealt{guisan2013predicting,hefley2015use}). Regardless of the type of data or method, the ultimate goal when using SDMs includes making reliable inference and accurate predictions. In many applications, a SDM is fit to data from a single species. If the study objectives require the analysis of data from multiple species, then a SDM is fit to data from each species and the models are combined using stacking (Norberg et al. \textit{in press} \nocite{ecomonograph2019}; \citeauthor{zurelltesting} \textit{in press}). Although this species-by-species approach is common it presents several challenges that limit the ability of researchers and managers to make reliable inference and accurate predictions (\citealt{hui2013mix,madon2013community,taylor2017joint}). For example, if the goal of a study is to produce accurate range maps then spatial predictions for a species that is rare will lack precision. Imprecise spatial predictions result from parameter estimates that have a high variance, which occurs because parameters are estimated using limited data from only a single rare species (e.g., \citealt{hefley2015existence}). As another example, consider the case where the goal is to infer the influence of a predictor variable such as temperature. Fitting a SDM for each species requires estimating a unique temperature coefficients for each species. Even if there are only a few predictor variables it will be difficult to summarize the regression coefficients for a moderate number of species, which will hinder communication with policymakers. Recently, SDMs for multiple species have been developed. So-called joint- or multi-species distribution models (MSDMs) enable a single model to be fit simultaneously to data from multiple species; the benefits include: 1) community-level inference and resulting prediction; 2) incorporation of biotic interactions; 3) more accurate predictions of single-species' distributions due to ``borrowing of strength'' across data from co-occurring species; and 4) the potential for model simplification. Many types of MSDMs have been developed using statistical or machine learning approaches (see synthesis in Norberg et al. \textit{in press} \nocite{ecomonograph2019} and \citealt{wilkinson2019comparison}). Hierarchical Bayesian modeling is a statistical approach that is easily customizable and widely used to model the distribution of multiple species (e.g., \citealt{taylor2017joint,johnson2017modeling,lany2018asymmetric,schliep2018joint,ovaskainen2017make,wilkinson2019comparison}). Briefly, hierarchical Bayesian models are specified using conditional probability distributions that represent the data collection process (i.e., the ``data model''), the latent ecological process (i.e., the ``process model''), and prior knowledge about parameters (i.e., the ``parameter model''; \citealt{wikle2019spatio}, pgs. 11\textendash 13; \citealt{hobbs2015bayesian}, ch. 6). For presence-absence data, \citet{wilkinson2019comparison} describes the quintessential hierarchical Bayesian MSDM. This includes the data model \begin{equation} y_{i,j}|z_{i,j}\sim\text{Bern(}g^{-1}(z_{i,j}))\,, \end{equation} where $y_{i,j}=1$ if the $i^{\text{th}}$ site ($i=1,2,...,n$) is occupied by the $j^{\text{th}}$ species ($j=1,2,...,J$) and $y_{i,j}=0$ if absent, ``Bern'' is a Bernoulli distribution, $g^{-1}(\cdot)$ is an inverse link function (e.g., logistic, probit), and $z_{i,j}$ is the latent process on the link scale. For MSDMs, a widely used process model is \begin{equation} \mathbf{z}|\boldsymbol{\mu},\ensuremath{\boldsymbol{\Sigma}}\sim\text{N(\ensuremath{\boldsymbol{\mu}}\ensuremath{,}\ensuremath{\boldsymbol{\Sigma}})\,,} \end{equation} where $\mathbf{z}$ is a random vector with elements $z_{i,j}$, $\boldsymbol{\mu}$ is expected value (mean), and $\ensuremath{\boldsymbol{\Sigma}}$ is the variance-covariance matrix of a multivariate normal distribution. The vector, $\boldsymbol{\mu}$, has elements $\mu_{i,j}$ and is typically specified using \begin{equation} \mu_{i,j}=\alpha_{j}+\mathbf{x}_{i}^{'}\boldsymbol{\beta}_{j}\,, \end{equation} where, for the $j^{\text{th}}$ species, $\alpha_{j}$ is the intercept and $\boldsymbol{\beta}_{j}$ are the $K$ regression coefficients (i.e., $\boldsymbol{\beta}_{j}\equiv(\beta_{j,1},\beta_{j,2},...,\beta_{j,K})^{'}$). The vector $\mathbf{x}_{i}$ contains $K$ measured predictor variables at the $i^{\text{th}}$ site, which are the same for all $J$ species (i.e., $\mathbf{x}_{i}\equiv(x_{i,1},x_{i,2},...,x_{i,K})^{'}$). In Eq. 2, the process model is specified jointly (i.e., using a multivariate distribution) to enable sharing of information across species. In previous studies, the variance-covariance matrix, $\boldsymbol{\Sigma}$ in Eq. 2, accounted for residual autocorrelation due to space, time, and/or biotic interactions. For example, within the literature on MSDMs, a main focus of methodological developments has been on parametrizing $\boldsymbol{\Sigma}$ to account for biotic factors, such as species co-occurrence, that can not be explained by the measured predictor variables $\mathbf{x}_{i}$ (e.g., \citealt{warton2008penalized,warton2015so,ovaskainen2017make,niku2017generalized,wilkinson2019comparison}). By comparison, however, there are only a few studies that have focused on the parameterization of $\boldsymbol{\mu}$ in Eq. 2 (e.g., \citealt{johnson2017modeling}). Regardless of the type of data, most MSDMs use a linear equation to model the influence of predictor variables. For example, all seven methods compared by \citet{wilkinson2019comparison} use Eq. 3 which, if there are $J$ species and $K$ predictor variables, will result in $J\times K$ regression coefficients. For even a small number of predictor variables and species, the overabundance of regression coefficients will be challenging to summarize and interpret and may result in a MSDM that is overparameterized. For many Bayesian MSDMs, the parameter model or prior is specified using simple distributions. For example, in six of the seven methods presented by \citet{wilkinson2019comparison} priors for the regression coefficients were specified using uniform distributions or independent normal distributions with known hyperparameters (e.g., $\beta_{j,k}\sim\text{N}(0,10)$). Although using simple parameter models is common practice, more sophisticated parameter models are useful. For example, the seventh method in \citet{wilkinson2019comparison} uses a multivariate normal distribution with unknown hyperparameters as a parameter model which enables estimation and inference regarding the correlation among regression coefficients. For MSDMs, the notion of a model for the parameters is important because it can enable novel inference and perform regularization. Regularization is a model selection technique used to optimize predictive accuracy by controlling model complexity (\citealt{bickel2006regularization,hooten2015guide}). \citet{johnson2017modeling} develop a hierarchical Bayesian MSDMs, which includes a parameter model that leverages the concept of ecological guilds (\citealt{simberloff1991guild}). For MSDMs, the ecological guild concept is useful because it provides a framework to incorporate ecological theory and reduce the number of regression coefficients associated with predictor variables. For example, the ecological guild concept suggests that some species may respond to predictor variables in a similar direction and magnitude as a result of similar resource use or ecological role. In other words, species within the same guild may be associated with similar values of the regression coefficients in Eq. 3. If the regression coefficients for two or more species are effectively the same, then the complexity of the MSDM can be reduced by estimating unique regression coefficients for a smaller number of guilds rather than a larger number of species. If the guild membership is known, then incorporating the guild concept into MSDMs is trivial and involves using Eq. 3 with a guild by predictor variable interaction effect rather than a species by predictor variable (\citealt{johnson2017modeling}). In nearly all applications, the number and species compositions of the guilds is unknown and must be estimated from data which can be accomplished using model-based techniques. For example, as a heuristic imagine that the species-specific regression coefficients for a single predictor variable in Eq. 3 were known. In this example, the number and species composition of guilds could be determined by classifying or clustering the regression coefficients into homogeneous groups. The classification model would be easier to interpret when compared to the larger number of species-specific regression coefficients because it provides a data-driven approach to determine which species can be modeled with a single guild-level regression coefficient. This ad-hoc approach is a useful heuristic because it gives insight into how a large number of regression coefficients can be summarized using a model for the parameters. Within a hierarchical Bayesian framework, formalizing this concept is straightforward by specifying an appropriate parameter model. Simple independent parameter models that are commonly used for MSDMs, such as $\beta_{j,k}\sim\text{N}(0,10)$, do not leverage the information in the data shared among species. The independence assumption eliminates the possibility that information about parameters will be shared across species. Shared information among the species, however, can be accessed by incorporating the guild concept into the parameter model. For example, \citet{johnson2017modeling} developed a hierarchical Bayesian MSDM using a Dirichlet process mixture for the parameter model, which enables regression coefficients to be estimated using data from all species within the same guild. Briefly, the Dirichlet process mixture is a distribution that can be used as a parameter model to cluster the species into guilds while simultaneously fitting a MSDM to community data. Classification and regression trees (CART; \citealt{CART1984}) are a machine learning approach with widespread use in ecology (\citealt{de2000classification,de2002multivariate,elith2008working}). For ecological data, CART offer a semi-automated approach to build predictive models that are easy to interpret. Although Bayesian variants of CART have been available for some time (e.g., \citealt{chipman1998bayesian,denison1998bayesian}), they are rarely used by ecologists. This is perhaps because accessible versions of Bayesian CART software are not easily modified to accommodate ecological data. For example, current implementations of Bayesian CART do not include a ``data model,'' which is needed to account for imperfect measurements of ecological processes. Conceptually, CART can be embedded within hierarchical Bayesian models (at any level), which would enable ecologists to exploit the benefit of both approaches (\citealt{shaby2012embedding}). In our work, we show how a specific type of CART can be used as a parameter model for Bayesian MSDMs. Similar to \citet{johnson2017modeling}, our approach leverages the concept of ecological guilds but reduces model complexity via a novel tree shrinkage prior (TSP). We illustrate the TSP by fitting MSDMs to presence-absence and relative abundance data collected to inform management of freshwater aquatic vegetation and fish populations. These data are collected as part of a long-term environmental monitoring program intended to inform management of the Upper Mississippi River System. Managers are required to use these data to make and justify management recommendations. This requires understanding the predictor variables that influence the distribution of a large number of species using models that can be easily shared with policymakers but that are capable of making accurate predictions. \begin{spacing}{1.9} \section*{Materials and methods} \end{spacing} \begin{spacing}{1.9} \subsection*{INCORPORATING GUILDS INTO MULTI-SPECIES DISTRIBUTION MODELS} \end{spacing} \noindent The mechanics of incorporating guilds into hierarchical Bayesian MSDMs was presented by \citet{johnson2017modeling}. For MSDMs, this involves a simple modification of Eq. 3 \begin{equation} \mathbf{\boldsymbol{\mu}}_{i}=\mathbf{\boldsymbol{\alpha}}+(\mathbf{x}_{i}^{'}\otimes\mathbf{Z})\boldsymbol{\gamma}\,, \end{equation} where, $\mathbf{\boldsymbol{\mu}}_{i}\equiv(\mu_{i,1},\text{\ensuremath{\mu_{i,2}},...,\ensuremath{\mu_{i,J}}})^{'}$ is a vector that specifies the expected value for the process model at the $i^{\text{th}}$ site for $J$ species, $\boldsymbol{\alpha}\equiv(\alpha_{1},\alpha_{2},...,\alpha_{J})^{'}$ contains intercept parameters for each species, and $\mathbf{x}_{i}\equiv(x_{i,1},x_{i,2},...,x_{i,K})^{'}$ contains $K$ predictor variables measured at the $i^{\text{th}}$ site. The matrix $\mathbf{Z}$ has dimensions $J\times G$ where the $j^{\text{th}}$ row contains an indicator variable that links the predictor variables to the guild-specific regression coefficients contained within the vector $\boldsymbol{\gamma}$. The mathematical symbol $\otimes$ denotes a Kronecker product. For example, let there be $J=4$ species, $G=2$ guilds, and $K=2$ predictor variables, then for the $i^{\text{th}}$ site, one configuration of Eq. 4 is \begin{equation} \begin{bmatrix}\mu_{i1}\\ \mu_{i2}\\ \mu_{i3}\\ \mu_{i4} \end{bmatrix}=\begin{bmatrix}\alpha_{1}\\ \alpha_{2}\\ \alpha_{3}\\ \alpha_{4} \end{bmatrix}+\left(\begin{bmatrix}x_{i1} & x_{i2}\end{bmatrix}\otimes\begin{bmatrix}1 & 0\\ 1 & 0\\ 0 & 1\\ 0 & 1 \end{bmatrix}\right)\begin{bmatrix}\gamma_{1,1}\\ \gamma_{2,1}\\ \gamma_{1,2}\\ \gamma_{2,2} \end{bmatrix}\,, \end{equation} where the first and second species are members of the first guild and the third and fourth species are members of the second guild. The guild-specific regression coefficients are $\boldsymbol{\gamma}\equiv(\gamma_{1,1},\gamma{}_{2,1},\gamma_{1,2},\gamma_{2,2})^{'}$ where the subscripts, $\gamma_{g,k}$, indicate the $g^{\text{th}}$ guild and the $k^{\text{th}}$ predictor variable. Modifications to the example given in Eq. 5, illustrates that incorporating the guild concept into MSDM results in a model that is flexible and includes two special cases. For example, if $\mathbf{Z}$ is a $4\times1$ matrix with all elements equal to one (i.e., $\mathbf{Z}\equiv(1,1,1,1)^{'}$), then all species would be in a single guild. Similarly if $\mathbf{Z}$ is a $4\times4$ identity matrix (i.e., a matrix with diagonal elements equal to one and zero on the off diagonal elements), then each species would be assigned to a unique guild; this results in the commonly used MSDM with unique species-specific regression coefficients (i.e., Eq. 3) and demonstrates that incorporating the guild concept into MSDMs can only improve the predictive accuracy. If the number and species composition of the guilds was known, then the matrix $\mathbf{Z}$ would also be known. In practice, however, the number and species composition of the guilds are unknown, which requires estimation of $\mathbf{Z}$. In turn, $\mathbf{Z}$ regularizes the MSDM because $\mathbf{Z}$ shrinks and reduces the number of regression coefficients from $J\times K$ to $G\times K$. \begin{spacing}{1.9} \subsection*{\vspace{0.66cm} TREE SHRINKAGE PRIOR} \end{spacing} \noindent A general introduction to tree-based methods is given in \citeauthor{james2013introduction} (2013; ch. 8) while \citet{linero2017review} provides a technical review of Bayesian tree approaches. We use vocabulary found in both \citeauthor{james2013introduction} (2013; ch. 8) and \citet{linero2017review}. The idea of a TSP is not new but, to our knowledge, has been used in only one unrelated setting (\citeauthor{guhaniyogi2018large} \textit{in press}). For MSDMs, the idea is simple; the species within terminal nodes of the tree represent the guilds and determines the matrix $\mathbf{Z}$ in Eq. 4. Each terminal node is associated with guild-level regression coefficients for the predictor variables. For example, in what follows, we use presence-absence data for six species of aquatic vegetation and a single predictor variable (water depth). An example of a binary tree is given in Fig. 1 and shows which species share the same numerical value of the regression coefficients for the predictor variable water depth. In this example, the standard MSDM results in six regression coefficients (i.e., one for each species). For the predictor variable water depth, a MSDM specified using the tree shown in Fig. 1 results in only three regression coefficients. Recall that there are intercept parameters for each species, as a result the binary tree in Fig. 1 reduces the number of parameters in the MSDM from 12 to 9. There are a variety of techniques to construct tree priors discussed within the statistics and machine learning literature (\citealt{linero2017review}). Most techniques rely on a tree generating stochastic process (\citealt{linero2017review}). Binary trees, like the example in Fig. 1, are a type of stochastic branching process (\citealt{dobrow2016introduction}, ch. 4). Specification of a tree generating stochastic process involves specifying probability distributions that generate a tree structure as a random variable. For example, a simple stochastic binary tree generating process for the six species of aquatic vegetation in Fig. 1 involves specifying a distribution that determines the splitting of parent nodes and a second distribution that determines the allocation of species to the child nodes (e.g., in Fig. 1 super guild 1 is a parent node with guilds 1 and 2 as child nodes). For the aquatic vegetation example, one way to specify a binary tree generating stochastic process would involve using a ``splitting distribution'' that determines if a parent node should be split into two child nodes. If a draw from the splitting distribution results in a value of one, the parent node is split and draws from a ``assignment distribution'' allocates the species within the parent node to one of the two child nodes. In practice, the assignment distribution is $\text{Bern}(0.5)$ whereas the splitting distribution is $\text{Bern}(p_{split})$, where the hyperparameter $p_{split}$ controls the model complexity by inducing a prior on the guilds. For example, if $p_{split}=1$ then a binary tree is generated with six terminal nodes (guilds) that contain only a single species; when $p_{split}=0$ a tree with no splits is generated and all six species are in the same guild. Finally, the terminal nodes of the MSDM with a TSP has guild-level regression coefficients, $\gamma_{g,k}$, which require the specification of priors. For tree-based methods, simple models like $\gamma_{g,k}\sim\text{N(0,10)}$ are commonly used, (\citealt{linero2017review}), however, more complex models have been developed (e.g., \citealt{gramacy2008bayesian}). In sum, specifying a stochastic tree generating process results in an implied prior on the tree structure. For example, a so-called non-informative prior could be constructed by specifying a tree generating stochastic process that generates all possible combinations of guilds with equal probability (e.g., \citealt{atkinson1992generating}). For the aquatic vegetation example such a prior would result in 63 unique guilds. For this example, the MSDM with the TSP could be implemented using Bayesian model averaging (\citealt{oliver1995pruning}). Model averaging is a well-known technique among ecologists (e.g., \citealt{hobbs2015bayesian}; Dormann et al. 2018\nocite{dormann2018model}), however, this would require fitting 63 models (i.e., a model for each unique guild). Although we could fit a MSDM with the TSP to the aquatic vegetation data using Bayesian model averaging, this approach would not work for a larger number of species. For example, the fisheries data used to illustrate the TSP contains 15 species which results in 32,767 unique guilds. Despite advances in computational statistics, implementation of tree-based methods using Bayesian model averaging is challenging because of the potential for a large number trees (\citealt{chipman2001practical,hooten2015guide,BB2L}, ch. 15). In the next section, we describe alternative strategies for model fitting that may be less familiar among ecologists. \subsection*{\vspace{0.66cm} MODEL FITTING} Hierarchical Bayesian MSDMs can be fit to presence-absence, abundance, and presence-only data using a variety of algorithms. Markov chain Monte Carlo (MCMC) algorithms are a type of stochastic sampling approach routinely used by ecologists and implemented in standard software such as WinBugs, JAGS, and Stan (\citealt{BB2L}). As such, we demonstrate the TSP using MCMC. Compared with other commonly used ecological models, MCMC based implementation of Bayesian trees usually requires highly specialized algorithms. As a result, an inability to easily construct efficient algorithms has likely slowed the adoption of Bayesian regression trees (\citealt{linero2017review}). For example, Bayesian model averaging, used to fit Bayesian trees to data, requires specialized algorithms (e.g., \citealt{oliver1995pruning,hernandez2018bayesian}). As mentioned, however, this may be computationally challenging or infeasible for the TSP when there is a large number of guilds. To increase computational efficiency, search algorithms have been used to identify higher probability tree structures, however, as noted by \citet{chipman1998bayesian}, the ``procedure is a sophisticated heuristic for finding good models rather than a fully Bayesian analysis, which presently seems to be computationally infeasible.'' Significant progress continues in the development of computationally efficient implementations of Bayesian trees (\citealt{linero2017review}), however, fitting tree-based models to data requires matching the model to computational algorithms which can be challenging for non-experts. An appealing implementation for ecologists is presenting by \citet{shaby2012embedding}. The \citet{shaby2012embedding} approach enables off-the-shelf software for tree-based methods, such as those available in R, to be embedded within hierarchical Bayesian models. This is appealing to ecologists because it makes the TSP accessible by eliminating the need to develop custom software to implement the TSP. Briefly, the technique of \citet{shaby2012embedding} is an approximate Gibbs sampler that enables machine learning algorithms to be embedded within hierarchical Bayesian models. In what follows we use a model-based recursive partitioning approach that is available in the R package ``partykit'' and implemented within the \texttt{lmtree(...)} function (\citealt{hothorn2006unbiased,zeileis2008model}; \citeauthor{zeileisparties} 2019). Model-based recursive partitioning estimates a binary tree and consequently $\mathbf{Z}$ and $\boldsymbol{\gamma}$ in Eq. 4. The approximate Gibbs sampler of \citet{shaby2012embedding} is similar to an empirical Bayesian step within a Gibbs sampler because priors for a portion of the unknown model parameters are replaced with estimates (\citealt{casella2001empirical}). As a result, when using the \citet{shaby2012embedding} approach, there are no distributions or hyperparameters associated with the TSP that must be specified. In what follows, we use standard MCMC algorithms for MSDMs, but employ the \citet{shaby2012embedding} approach. Constructing the approximate Gibbs sampler using the \citet{shaby2012embedding} approach for the aquatic vegetation data example is incredibly simple and requires only six lines of R code and the ability to sample univariate normal and truncated normal distributions (e.g., using the R functions \texttt{rnorm(...)} and \texttt{rtruncnorm(...)}; see section 2.3 in Appendix S1). To assist readers implementing similar MSDMs with the TSP, we provide tutorials with the computational details, annotated computer code, and the necessary code to reproduce all results and figures related to the analysis for the aquatic vegetation data and fisheries data examples (see Appendix S1 and S2). \vspace{0.66cm} \subsection*{STATISTICAL INFERENCE} A benefit of Bayesian inference is that uncertainty regarding the structure of the binary tree, and therefore the number and species composition of the guilds, is automatically accounted for. Under the Bayesian paradigm, samples from the posterior distribution of the trees are obtained during the model fitting process. The posterior distribution of the trees can be summarized to infer characteristics of the guilds. For example, the species composition of the guilds with the highest probability (given the data) can be obtained from the posterior distribution of the trees. In addition, posterior distributions of the species-level and guild-level regression coefficients can be sampled and summarized. The species-level regression coefficients, akin to $\boldsymbol{\beta}$ in Eq. 3, are a derived quantity calculated using \begin{equation} \boldsymbol{\beta}_{j}^{(m)}=\mathbf{W}_{j}^{(m)}\boldsymbol{\gamma}^{(m)}\,, \end{equation} where the superscript $m$ is the current MCMC sample, $\boldsymbol{\beta}_{j}$ is vector of regression coefficients for the $j^{\text{th }}$ species, $\mathbf{W}_{j}$ is a matrix that contains indicator variables linking the guild-level coefficients to the species. In the presence of guild membership uncertainty, the species-level regression coefficients result in a posterior distribution that is a mixture of the guild-level regression coefficients. When using the TSP, the posterior distribution of the regression coefficients for a species are akin to the model averaged posterior distribution obtained from fitting and averaging multiple MSDMs with differing species composition and numbers of guilds to the data. Similarly the guild-level regression coefficients are akin to the regression coefficients obtained from a single MSDM using a fixed guild structure. We recommend using the species-level regression coefficients to make inference because, with a finite amount of data, the species composition of the guilds will always be uncertain. Inference using the guild-level regression coefficients is conditional (i.e., valid for a fixed number and species composition of the guilds) and does not fully account for uncertainty. \subsection*{\vspace{0.66cm} LONG-TERM RESOURCE MONITORING DATA} \noindent The Mississippi River is the second longest river in North America and flows a distance of 3,734 km. The Upper Mississippi River System includes approximately 2,100 km of the Mississippi River channel and drains a basin covering 490,000 $\text{km}^{2}$ that contains 30 million people. The Upper Mississippi River Restoration Program was authorized under the Water Resources Development Act of 1986 (\citet{waterlaw}). The U.S. Army Corps of Engineers provides guidance, has overall Program responsibility, and established a long term resource monitoring (LTRM) element that includes collecting biological and geophysical data. The LTRM element is implemented by the U.S. Geological Survey, Upper Midwest Environment Sciences Center, in cooperation with the five Upper Mississippi River System states of Illinois, Iowa, Minnesota, Missouri, and Wisconsin (\citealt{UMRR}). The expressed goal of the LTRM element is to ``support decision makers with the information and understanding needed to maintain the Upper Mississippi River System as a viable multiple-use large river ecosystem.'' The biological data collected by LTRM contains a large number of species and exemplifies the need for interpretable MSDMs with results that are easy to communicate to policymakers. For example, data from 154 species, some of which are rare or endangered, have been collected by the LTRM element since 1993; inferences from these data provide context for management recommendations for these or collections of these species. As part of LTRM element, data on aquatic vegetation and fish are collected at multiple sites within six study reaches of the Upper Mississippi River. To illustrate our method, we use aquatic vegetation and fisheries data from navigation pool 8 collected in 2015. Complete details of data collection procedures for the aquatic vegetation data and fisheries data are given by \citet{vegsampling} and \citet{fishsampling} respectively. \begin{spacing}{1.9} \subsection*{\vspace{0.66cm} EXAMPLE 1: PRESENCE-ABSENCE OF AQUATIC VEGETATION} \end{spacing} \noindent Our objective for the first example is to illustrate the TSP using a simple MSDM. As such, this example was designed to demonstrate the proposed methods rather than to provide scientifically valid inference. As such, we use only a single predictor variable (water depth) and presence-absence absence data of six species of aquatic vegetation. At 450 unique sites, the presence or absence of a species was recorded. For our example, we use data for broadleaf arrowhead (\textit{Sagittaria latifolia}), Canadian waterweed (\textit{Elodea canadensis}), coontail (\textit{Ceratophyllum demersum}), stiff arrowhead (\textit{Sagittaria rigida}), white water lily (\textit{Nymphaea odorata}), and wild celery (\textit{Vallisneria americana}). This resulted in a total of 2,700 observations. For our analysis, we randomly selected 225 sites and used data from these for model fitting. We used data from the remaining 225 sites to test the predictive accuracy of the models. For the aquatic vegetation data, we use the data model \begin{equation} \mathbf{y}_{i}|\ensuremath{\mathbf{\boldsymbol{\mu}}_{i}}\sim\text{Bern(\ensuremath{\Phi}(\ensuremath{\mathbf{\boldsymbol{\mu}}_{i}})})\,, \end{equation} where $\mathbf{y}_{i}\equiv(y_{i,1},y_{i,2}...,y_{i,6})^{'}$ is the presence or absence of the six species at the $i^{\text{th}}$ site ($i=1,2,...,225)$. The parameter vector $\ensuremath{\mathbf{\boldsymbol{\mu}}_{i}}\equiv(\mu_{i,1},\mu_{i,2},...,\mu_{i,6})^{'}$ is mapped to a probability by applying the inverse probit link function, $\Phi(\cdot)$, to each element. The parameter vector $\ensuremath{\mathbf{\boldsymbol{\mu}}_{i}}$ is specified using Eq. 4, but is simplified due to the single predictor variable in this example \begin{equation} \mathbf{\boldsymbol{\mu}}_{i}=\mathbf{\boldsymbol{\alpha}}+x_{i}\mathbf{Z}\boldsymbol{\gamma}\,, \end{equation} where $\boldsymbol{\alpha}\equiv(\alpha_{1},\alpha_{2},...,\alpha_{6})^{'}$ is a vector that contains intercept parameters for each species and $x_{i}$ is the recorded water depth at the $i^{\text{th}}$ site. As in Eq. 4, the matrix $\mathbf{Z}$ has dimensions $J\times G$ where the $j^{\text{th}}$ row contains an indicator variable that links the predictor variables to the guild-specific regression coefficients contained within the vector $\boldsymbol{\gamma}\equiv(\gamma_{1,1},\gamma_{2,1},...,\gamma_{g,1})^{'}$. For the intercept, we use the prior $\alpha_{j}\sim\text{N(0,1})$ because this results in a uniform distribution when $\alpha_{j}$ is transformed using the function $\Phi(\ensuremath{\alpha_{j}})$. That is, using the prior $\alpha_{j}\sim\text{N(0,1})$ results in $\Phi(\ensuremath{\alpha_{j}})\sim\text{unif(0,1})$. We used a computationally efficient MCMC algorithm to fit the MSDM to the aquatic vegetation data. This MCMC algorithm relies on an auxiliary variable formulation of the binary regression model and has been used to fit MSDMs to presence-absence data (\citealt{albert1993bayesian}; \citealt{wilkinson2019comparison}; \citealt{BB2L}, pgs. 246\textendash 253). For each model fit, we use one chain and obtain 100,000 draws from the posterior distribution, but retain every $10^{\text{th}}$ sample to decrease storage requirements. Each model fit takes approximately 30 minutes using a desktop computer (see Appendix S1). We inspect the trace plot for each parameter to ensure that the Markov chain is sampling from the stationary distribution (i.e., the posterior distribution). We discard the first 500 samples and use the remaining 9,500 samples for inference. The model-based recursive partitioning approach available in the R function \texttt{lmtree(...)} and used to implement the TSP requires the specification of a tuning parameter (hereafter \texttt{alpha}; see Appendix S1). This tuning parameter, \texttt{alpha}, must be between zero and one and controls the splitting of parent nodes. Similar to the tree generating stochastic process (see Section TREE SHRINKAGE PRIOR), when \texttt{alpha$\,=1$} the tree has terminal nodes (guilds) that contain only a single species. When \texttt{alpha$\,=0$} the tree does not split and all six species are in the same guild. One way to estimate the tree tuning parameter, \texttt{alpha}, is to find the value that results in the most accurate predictions (\citealt{hobbs2015bayesian}). For this example, we illustrate two approaches by estimating the predictive accuracy of our models with scores that use either in-sample or out-of-sample data. For the out-of-sample score, we use data from the 225 sites that were not used to fit the model to calculate the log posterior predictive density (LPPD). For the in-sample score, we calculate the Watanabe-Akaike information criteria (WAIC). For comparison between scoring approaches, we report $-2\times\text{LPPD}$ as we would expect this and WAIC to result in similar numerical values (\citealt{gelman2014understanding}). For Bayesian models, computing in-sample scores like WAIC require a measurement of a model's complexity. In non-hierarchical non-Bayesian contexts, a model's complexity is the number of parameters in the model. For example, using the MSDM applied to the aquatic vegetation data, the number of parameters ranges from 7 (i.e., six intercept parameters and one regression coefficient) to 12 (i.e., six intercept parameters and six regression coefficients). Measuring the complexity of our Bayesian MSDM with the TSP is more complicated than simply counting the number of parameters because of the shrinkage effect and because it is not obvious how many parameters are required to estimate the number and species composition of the guilds. Fortunately, when calculating Bayesian information criterion like WAIC, measure of model complexity such as the ``effective number of parameters'' are available without any additional effort. To understanding how the TSP controls the complexity of the MSDM, we report the effective number of parameters using Eq. 12 from \citet{gelman2014understanding} as \texttt{alpha} varies from zero to one.\vspace{0.66cm} \begin{spacing}{1.9} \subsection*{EXAMPLE 2: FISH ABUNDANCE} \end{spacing} Our objective for the second example is to demonstrate a different and complex data type that necessitates a more sophisticated use of the TSP and deeper ecological interpretation, similar to what ecologists may encounter in practice. Here we use relative abundance data from 15 species of fish that were sampled at 83 sites, which included several species that were present at only a small number of sites and are considered rare or species of concern (Table 1). For example, at 79 of the 83 sites (95\%), a count of zero was recorded for river redhorse (\textit{Moxostoma carinatum}; Table 1). At each site, numerous predictor variables were measured, but for our analysis we use water temperature, speed, and depth as these were most relevant to management of the Upper Mississippi River System. The fisheries data were collected over three time periods which included period 1 (June 15 \textendash{} July 31), period 2 (August 1 \textendash{} September 14), and period 3 (September 15 \textendash{} October 31). The time periods are hypothesized to correspond to changes in habitat use. For example, one hypothesis is that species composition of the guilds and the regression coefficient estimates associated with water temperature, speed, and depth may be different during each period. In what follows, we demonstrate how to incorporate such dynamics into MSDMs using the fisheries data. For relative abundance data, \citet{johnson2017modeling} discuss several commonly used MSDMs including a data model that has a marginal distribution of \begin{equation} \mathbf{y}_{i}|\mathbf{z}_{i},\phi\sim\text{ZIP}(e^{\mathbf{z}_{i}},\phi)\,, \end{equation} where ``ZIP'' stands for zero-inflated Poisson, $e^{\mathbf{z}_{i}}$ is the expected value of the Poisson mixture component, and $\phi$ is the mixture probability (\citealt{BB2L}; pg. 320). We specify the process model using Eq. 2 with $\boldsymbol{\Sigma\equiv}\sigma_{\varepsilon}^{2}\mathbf{I}$ and \begin{equation} \mathbf{\boldsymbol{\mu}}_{i}=\mathbf{\boldsymbol{\alpha}}+\left(\mathbf{x}_{i}^{'}\otimes\mathbf{Z}_{t}\right)\boldsymbol{\gamma}_{t}, \end{equation} where the guild composition and regression coefficients vary over the three sample periods as indicated by subscript $t$ such that $\mathbf{Z}_{t}$ and $\boldsymbol{\gamma}_{t}$ corresponds to period 1 ($t=1$), period 2 ($t=2$), or period 3 ($t=3$). The vector $\mathbf{x}_{i}\equiv(x_{i,1},x_{i,2},x_{i,3})^{'}$ are the three predictor variables (water temperature, speed and depth) measured at the $i^{\text{th}}$ site. In total, there are $135$ unique regression coefficients if the guilds contained only a single species for all three periods, which would also be the case if the standard MSDM (i.e., Eq. 3) with simple priors for the regression coefficients was used. For the mixture probability, process model variance, and intercepts we used the priors $\phi\sim\text{unif}(0,1)$, $\sigma_{\varepsilon}^{2}\sim\text{IG}(2.01,1)$, and $\alpha_{j}\sim\text{N(0,10}^{3})$ respectively. For each model fit, we use one chain and obtain 30,000 draws from the posterior distribution, but retain every $10^{\text{th}}$ sample to decrease storage requirements. We inspect the trace plot for each parameter to ensure the Markov chain is sampling from the stationary distribution. We discard the first 500 samples and use the remaining 2,500 samples for inference. The computational cost to implement the TSP will increase as the number of species increase. In addition, allowing the number and species composition of the guilds to vary over the three periods increases the computational burden because the MSDM requires three TSPs instead of one. As a results, we do not select the value of the tree tuning parameter parameters that produces the best predictive model because fitting the MSDM once to the fisheries data takes about 23 hours using a desktop computer (see Appendix S2). Instead we choose a value of the tree tuning parameters that favors a small number of guilds, which we anticipate will make our results easier to share with policymakers. Similar to the aquatic vegetation example, the tree tuning parameters could be chosen to optimize the predictive ability of the model but this would make the annotated computer code provided in Appendix S2 difficult for many readers to use without access to high-performance computing resources.\vspace{0.66cm} \section*{Results} \begin{spacing}{1.9} \subsection*{EXAMPLE 1: PRESENCE-ABSENCE OF AQUATIC VEGETATION} \end{spacing} The value of the tree tuning parameter that produces the most accurate predictions was 0.6 when scored using LPPD and 0.025 when scored using WAIC. In what follows, we present results obtained from the MSDM with the TSP that used a value of the tree tuning parameter of 0.025 because this value was optimal based on WAIC, results in only a slight reduction in predictive accuracy when scored using LPPD, and yields a relatively large reduction in the number of parameters which simplifies statistical inference (Fig. 2). For the six species of aquatic vegetation, the posterior distributions for the species-level regression coefficient, obtained from Eq. 6, shows that the presence of wild celery has no statistical relationship with water depth while the remaining five species of vegetation exhibit a strong negative response to increases in water depth (Fig. 3a,b). In addition to the posterior distribution for the regression coefficients, derived quantities from the posterior distribution of the tree can provide insightful inference. For example, Fig 3c shows the posterior distribution of the number of terminal nodes (i.e., guilds) and Fig 3d shows the expected value of the posterior distribution of species co-occurrence within the same guild, both of which were derived from the posterior distribution of the trees. As another example, summaries of the posterior distribution of the tree may be of interest. For example, Fig. 3e shows the most likely tree, which is obtained from the mode of the posterior distribution of the trees and can be used to infer which guild structure is most likely. For the most likely tree, figure 3f shows the posterior distribution of the two guild-level regression coefficients. Again, caution must be taken when making inference from the guild-level regression coefficients because these are conditional on a single tree and do not account for guild uncertainty. For the aquatic vegetation data, however, the inference does not differ among the species-level and guild-level regression coefficients because the uncertainty in the number and species composition of the guilds is relatively low.\vspace{0.66cm} \begin{spacing}{1.9} \subsection*{EXAMPLE 2: FISH ABUNDANCE} \end{spacing} \noindent Similar to the aquatic vegetation example, we show the posterior distribution of the number of guilds (Fig. 4a,b,c), the expected value of species co-occurrence within the same guild (Fig. 4d,e,f), and the posterior distribution of the regression coefficients for each species (Figs. 5 and S1). During period 1, our results indicate that there are most likely two guilds (Fig 4a). The posterior distributions of the regression coefficients show that eight species (bluegill, bullhead minnow, emerald shiner, largemouth bass, mud darter, pugnose minnow, tadpole madtom, and weed shiner; hereafter ``guild 1 during/in period 1'') have large decreases in relative abundance when water temperature and depth increases (Figs. 5 and S1). These results suggest guild 1 during period 1 is more abundant in shallower side channels and off-channel habitats compared to the main channel, where depth is maintained at a minimum of 2.75 m for navigation. Of the species in guild 1 during period 1 many are nest spawners (e.g., bluegill, bullhead minnow, largemouth bass, pugnose minnow, tadpole madtom) and our results correspond with habitat requirements for successful reproduction. During period 1, the remaining seven species (golden redhorse, longnose gar, river redhorse, river shiner, shorthead redhorse, smallmouth bass, spotfin shiner; hereafter ``guild 2 during/in period 1'') have posterior distributions of the regression coefficients that indicate slight decrease in relative abundance when water temperature or depth increases, however, here is a non-negligible probability that these responses could be close to zero or even positive (Figs. 5 and S1). This suggest that during period 1 species in guild 2 are found over a broader range of conditions when compared to species in guild 1. Many of these species are classified as fluvial dependent or fluvial specialists, which are either generally found in lotic environments or require flowing water for some part of their life history (\citealt{galat2001conserving,lifehistory}). During period 2, our results indicate that there is most likely a single guild that contains all 15 species of fish (Fig 4b). The posterior distributions of regression coefficients for all species generally have an expected value near zero, suggesting random associations with water depth, speed, and temperature (Fig. 5 and S1). The lack of a response to water depth, speed, and temperature during period 2 may be a result of active foraging in which species are moving in search of food. During period 3, our results indicate that there are most likely two guilds (Fig 4c). The posterior distributions of the regression coefficients associated with depth indicate a negative response for five species (bluegill, largemouth bass, pugnose minnow, tadpole madtom, weed shiner; hereafter ``guild 1 during/in period 3''), which suggests an avoidance of the main channel (Figs. 5 and S1). In addition, our results show a negative response to water speed for the species in guild 1 during period 3 which suggest associations with lentic habitats such as backwater lakes. As temperatures decrease during period 3 (September 15 \textendash{} October 31), many of the species in guild 1 are known to move into slow-moving backwaters to minimize energy expenditures during winter conditions. During period 3, six species (bullhead minnow, emerald shiner, river redhorse, shorthead redhorse, smallmouth bass, spotfin shiner; ``guild 2 during/in period 3'') had a slightly positive association with water speed and negative association with water temperature (Figs. 5 and S1). These results suggest that species in guild 2 during period 3 are more likely to inhabit the main channel and side channels during this period than off-channel habitats. During period 3, there are four species (golden redhorse, longnose gar, mud darter, and river shiner) whose posterior distributions of regression coefficients do not clearly delineate guild association. These results suggest either a high level of guild uncertainty, insufficient data, or weaker associations with the variables examined. In summary, the number and composition of guilds changed over the three periods, suggesting shifts in habitat associations and species interactions through time. Whether these shifts were related to specific requirements for spawning, foraging, or overwintering would require additional field research designed to answer such questions, but our results are consistent with our understanding of fluvial dependence and general habitat guilds. \section*{Discussion} A benefit of hierarchical Bayesian modeling is that statistical models can be easily customized to match the goals of a study. In what follows, we discuss modifications to the data and/or process models that have been commonly used to accommodate different types and quality of data. The modifications we discuss can be incorporated without making major changes to the basic framework we presented. We begin by discussing modifications to the data model. For our aquatic vegetation and fisheries data examples we used data models that were appropriate for presence-absence and relative abundance data, respectively. Other types of ecological data may require the specification of different distributions for the data. For example, a beta distribution is often used for plant cover data, which are usually reported as percentages (\citealt{wright2017statistical}; \citeauthor{damgaard2019using} \textit{in press}). Our approach, using the process model in Eq. 3 and TSP, could be used to develop a MSDM for plant cover data by specifying a beta distribution as the data model. Similarly, selecting a data model that matches key characteristics of the observed data (e.g., the support) is a common model building practice and applications using the TSP are straightforward (\citealt{hobbs2015bayesian,BB2L}). Many types of ecological data are measured with error. For example, presence-absence data may contain false-negatives (\citealt{tyre2003improving,martin2005zero,gray2013influences}). For MSDMs, accounting for measurement error in the data is an important component of the model building process (\citealt{beissinger2016incorporating,warton2016extending,tobler2019joint}). For example, multi-species occupancy models have been developed to account for false-negatives in presence-absence community data (\citealt{dorazio2005estimating}). Model selection is challenging for multi-species occupancy models (\citealt{broms2016model}), however, using the approaches demonstrated in this paper, it is straightforward to implement the TSP for the multi-species occupancy model. This would involve adding a fourth level to the hierarchical MSDM in Eqs. 2\textendash 3 that accounts for the possibility of false-negatives in the presence-absence data (\citealt{BB2L}, ch. 23). Using the information provided in Appendix S1 in concert with \citet{dorazio2012gibbs} or \citeauthor{BB2L} (2019; ch. 23) would yield an efficient implementation that requires a minimal amount of additional programming. As noted in the introduction, a main focus of methodological development within the literature on MSDMs has been on parametrizing the variance-covariance matrix, $\boldsymbol{\Sigma}$, for the process model in Eq. 2. In previous studies the variance-covariance matrix was specified to account for residual autocorrelation due to space, time, or biotic interactions. These modifications to the variance-covariance matrix can be incorporated into a MSDM that uses the TSP. For example, latent variables parameterizations have been used to induce dependence among species and estimate $\boldsymbol{\Sigma}$ (\citealt{walker2011random,warton2015so,hui2016boral}). As another example, \citet{johnson2017modeling} note that spatial or temporal autocorrelation can be accounted for by including basis functions to estimate $\boldsymbol{\Sigma}$ (\citealt{hefley2017basis}). In both the latent variables parameterization and basis function approach, the matrix $\boldsymbol{\Sigma}$ is implicitly specified using a ``random effects'' or ``first-order representation'' (\citealt{hefley2017basis}; \citealt{wikle2019spatio}, pgs. 156\textendash 157). The TSP is easy to program using the approximate Gibbs sampling approach from \citet{shaby2012embedding} and requires only a few additional lines of code when compared to Bayesian MSDMs that use simple priors. The computational burden to implement the TSP, however, is considerably larger which may increase the run-time required to fit MSDMs to data. For example, fitting independent models for single-species or MSDM with simple priors to data is faster because the number and species composition of the guilds does not have to be estimate and it may be easy to parallelize the computational procedure (\citealt{BB2L}, ch. 19; \citeauthor{hooten2018making} \textit{in press}). In general, the TSP will become more computationally challenging to implement as the number of species increases. For example, our implementation which uses a model-based recursive partitioning approach available in the R function \texttt{lmtree(...)} has a computational complexity that increase nonlinearly with the number of species. As a result fitting a MSDM to data for a small number of species is relatively fast as demonstrated by our example with six species of aquatic vegetation, however, model fitting requires much more time for a larger number of species as demonstrated by our example with 15 species of fish. The increase in computational time is caused by the increase in the number of possible guilds. Based on our experience and using the computational approaches presented in this paper, the TSP becomes infeasible to fit to data that contains more than roughly twenty species, however, feasibility will vary by data set and computer resources. Although this is a current limitation of the TSP, other Bayesian MSDMs that incorporate the guild concept face similar challenges (e.g., \citealt{johnson2017modeling}) which demonstrates the need for more efficient algorithms for ``big'' ecological communities. Currently we suggest two approaches to alleviate the computational burden when applying our approach to a large number of species. The first suggestion is to choose off-the-shelf tree methods that use multiple processors (or cores). For example, we used the R function \texttt{lmtree(...)}which allows users to choose the number of processor cores for tree related computations. In practice, implementation that exploits multiple processors should reduce the time required to fit a MSDM with the TSP to data, however, gains will vary by application. The second approach to reduce the computational burden involves using values of the tree hyperparameters that favor a small number of guilds. In studies with a large number of species, choosing a value of the tree hyperparameters that results in a small number of guilds may reduce the predictive accuracy of the model, however, model fitting will likely be quicker. In addition a small number of guilds may be desirable for studies that contain a large number of species because interpretation of the results for a larger number of guilds may be challenging. Both techniques, using multiple cores and reducing the number of guilds, were illustrated in our fisheries data example (see Appendix S2). As with most computationally demanding statistical methods, advances may soon obviate the current challenges. Model development, implementation, and selection for data from ecological communities is difficult because a high level of complexity is desired which can be achieved by including numerous parameters. For example, commonly used MSDMs are specified so that each species has a unique regression coefficient for each predictor variable (e.g., \citealt{wilkinson2019comparison}). As a result it is common practice to overparameterize MSDMs, which can degrade predictive accuracy and produce results that are difficult to interpret and communicate. We illustrated how to reduce the number of parameters in commonly used Bayesian MSDMs by replacing simple prior distributions for regression coefficients with a TSP. The TSP reduces model complexity while incorporating ecological theory, expanding inference, and can increase the predictive accuracy and interpretability of Bayesian MSDMs. \vspace{0.66cm} \section*{Acknowledgements} The U.S. Army Corps of Engineers' Upper Mississippi River Restoration Program LTRM element is implemented by the U.S. Geological Survey, Upper Midwest Environment Sciences Center, in cooperation with the five Upper Mississippi River System states of Illinois, Iowa, Minnesota, Missouri, and Wisconsin. The U.S. Army Corps of Engineers provides guidance and has overall Program responsibility. The authors acknowledge support for this research from USGS G17AC00289. Use of trade, product, or firm names does not imply endorsement by the U.S. Government.\vspace{0.66cm} \section*{Data accessibility} The aquatic vegetation and fisheries data are publicly available from \citet{UMRR}, but the specific subsets used in this study will be archived in the Dryad Digital Repository. For the purpose of peer review, the data have been submitted as supporting material as a compressed file labeled Data.zip. \renewcommand{\refname}{\vspace{0.1cm}\hspace{-0cm}\selectfont\large References}\setlength{\bibsep}{0pt} \bibliographystyle{apa}
{'timestamp': '2020-06-01T02:03:40', 'yymm': '2005', 'arxiv_id': '2005.14303', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14303'}
arxiv
\section*{Acknowledgements} We would like to thank Alex Acero, Anmol Walia, Arjun Rangarajan, Barry-John Theobald, Bhagyashree Shekawat, Christopher Klein, Dhivya Piraviperumal, Hong Yu, Jianpeng Cheng, Jiarui Lu, John Giannandrea, John Keesling, Katy Linsky, Lanqing Wang, Ryan Templin, Robert Daland, Shruti Bhargava, Xi Chen and Yvonne Xiao for discussions and for their help and feedback. We also want to thank all the anonymous reviewers for the helpful feedback and suggestions on this work. \bibliographystyle{acl_natbib} \section{Architecture Design} \label{sec:method} For a given utterance, we first detect and label entities using the NER model and generate the top-$l$ candidate hypotheses using beam search. The EL model consists of two stages: (i) candidate retrieval and (ii) joint linking and re-ranking. In the retrieval stage, for each NER hypothesis, we construct a structured search query and retrieve the top-$c$ candidates from the retrieval engine. In the ranking stage, we use a neural network to rank these candidate entity links within each NER hypothesis while simultaneously using rich signals (entity popularity, similarity between entity embeddings, the relation across multiple entities in one utterance, etc.) from these entity links as additional features to re-rank the NER hypotheses from the previous step, thus jointly addressing both the NER and EL tasks. \input{sections/s3.1-ner.tex} \input{sections/s3.2-el.tex} \input{sections/s3.3-application.tex} \subsection{Improvement on Other Language Understanding Tasks} \label{subsec:method_application} We also explore the impact of our NEU feature encoding on two tasks: a domain classifier and a domain-specific shallow semantic parser. \subsubsection{Domain Classification} \label{subsubsec:method_intent} Domain classification identifies which domain a user's request falls into: sports, weather, music, etc., and is usually done by posing the task as sequence classification: our baseline uses word embeddings and gazetteer features as inputs to an RNN, in a manner similar to \newcite{chen2019active}. Consider a specific token $t$. Let $a$ be the number of alternatives used from the NER model in the domain classifier (which we treat as a hyperparameter), $p_{i}$ represent the (scalar) sequence level confidence score $p_{seq} ( \mathbf{\tilde{y_{i}}}, \mathbf{x}; \mathbf \theta )$ of the $i$\textsuperscript{th} NER alternative defined in Section~\ref{sec:ner}, $c_i$ represent an integer for the entity type that NER hypothesis $i$ assigns to the token $t$, and $\mathbf{o}(.)$ represent a function converting an integer into its corresponding one-hot vector. Then the additional NER feature vector $\mathbf{f_{r}}$ concatenated to the input vector fed into token $t$ as part of the domain classifier can be written as: \begin{equation} \label{eq:dc_ner} \mathbf{f_{r}} = \bigoplus_{i=1}^{i=a} p_i\mathbf{o}(c_i). \end{equation} Likewise, for the featurization that uses both NER and EL, let $a$ be the number of alternatives used from the NER+EL system in the domain classifier (also a hyperparameter); these $a$ alternatives are now sorted by the scores from the EL hypotheses, as opposed to the sequence level confidence scores from NER. Let $s_i$ be the $i$\textsuperscript{th} re-ranked alternative's cosine similarity score between the mention and knowledge base entity name as output by the EL model. $p_i$ and $c_i$ are consistent with our earlier notation, except that they now correspond to the $i$\textsuperscript{th} NER alternative after re-ranking. Then the additional NER+EL feature vector $\mathbf{f_{u}}$ concatenated to the input fed into token $t$ as part of the domain classifier can be written as: \begin{equation} \label{eq:dc_rer} \mathbf{f_{u}} = \bigoplus_{i=1}^{i=a} p_i\mathbf{o}(c_i) \oplus s_i\mathbf{o}(c_i). \end{equation} \subsubsection{Semantic Parsing} \label{subsubsec:method_parse} Our virtual assistant also uses domain-specific shallow semantic parsers, running after domain classification, responsible both for identifying the correct intent that the user expects (such as the ``play'' intent associated with a song) and for assigning semantic labels to each of the tokens in a user's utterance (such as the word ``score" and ``game'' respectively being tagged as tokens related to a sports statistic and sports event respectively in the utterance ``What's the score of yesterday's Warriors game?''). Each semantic parser is structured as a multi-task sequence classification (for the intent) and sequence tagging (for the token-level semantic labelling) task, with our production baseline using word embeddings and gazetteer features as inputs into an RNN similar to our domain classifier. Here, $\mathbf{f_{r}}$ and $\mathbf{f_{u}}$ are featurized as described above. Note that in contrast to the NEU system, the semantic parser uses a domain-specific ontology, to enable each domain to work independently and to not be encumbered by the need to align ontologies. \subsection{NER} \label{sec:ner} For the NER task, following \newcite{lample-etal-2016-neural} we use a combination of character and word level features. They are extracted by a bi-directional LSTM (biLSTM) \cite{hochreiter1997long}, and then concatenated with pre-trained GloVe word embeddings \footnote{We also tried more recent contextual embeddings such as BERT \cite{devlin2019bert}, and empirically observed very little difference in performance when compared to GloVe. So we adopt GloVE, which is substantially more efficient in terms of inference time required.} \cite{pennington-etal-2014-glove} to pass through another biLSTM and fed into a CRF model to produce the final label prediction based on a score $s( \mathbf{\tilde{y_{i}}}, \mathbf{x}; \mathbf{\theta} )$ that jointly optimizes the probability of labels for the tokens and the transition score for the entire sequence $\mathbf{\tilde{y_{i}}}=(y_1,\dots,y_T)$ given the input $\mathbf{x}$: \begin{equation*} s( \mathbf{\tilde{y_{i}}}, \mathbf{x}; \mathbf{\theta} ) = \sum_{t=0}^{T} \left( \psi_{t, \mathbf \theta}(y_t) + \phi_{t,t+1} (y_t, y_{t+1}) \right), \end{equation*} \noindent where $\psi_{t,\theta}$ is the biLSTM prediction score from the label $y_t$ of the $t$\textsuperscript{th} token, and $\phi(j, k)$ is the transition score from label $j$ to label $k$. During training, we maximize the probability of the correct label sequence $p_{seq}$, which is defined as \begin{equation*} p_{seq} ( \mathbf{\tilde{y_{i}}}, \mathbf{x}; \mathbf \theta ) = \frac{\exp({s( \mathbf{\tilde{y_{i}}}, \mathbf{x}; \mathbf \theta )) }}{\sum_{\mathbf{\tilde{y_{j}}} \in S} \exp{(s( \mathbf{\tilde{y_{j}}}, \mathbf{x}; \mathbf \theta ))}}, \end{equation*} \noindent where $\mathbf{\tilde{y_{i}}}$ is the label sequence for hypothesis $i$, and $S$ is the set of all possible label sequences. During inference, we generate up to 5 NER alternatives for each utterance using beam search. We also calculate a mention level confidence $p_{men}$ for each entity mention $ \mathbf{m_k}$. $p_{men}$ is computed by aggregating the sequence level confidence for all the prediction sequences that share the same mention sub-path $\mathbf{m_k}$: \begin{equation*} p_{men} (\mathbf{m_k}, \mathbf x ; \mathbf \theta) = \frac{ \sum_{ \mathbf{\tilde{y_{i}}} \in S_{\mathbf{m_i}}} \exp({s (\mathbf{\tilde{y_{i}}}, \mathbf{x}; \mathbf \theta )}) }{\sum_{ \mathbf{\tilde{y_j}} \in S} \exp(s (\mathbf{\tilde{y_{j}}}, \mathbf{x}; \mathbf \theta ))}, \end{equation*} \noindent where ${S_{m_i}}$ is the set of prediction sequences that all have $ \mathbf{m_k}$ as the prediction for the corresponding tokens. Both $p_{seq}$ and $p_{men}$ are computed by dynamic programming, and serve as informative features in the EL model. \subsection{Qualitative Analysis} \label{sec:qualitative} We provide a few examples to showcase the effectiveness of our NEU system. Firstly, the EL model is able to link noisy entity mentions to the corresponding entity canonical name in the knowledge base. For instance, when the transcribed utterance is ``play Carla Cabello'', the EL model is able to resolve the mention ``Carla Carbello'' to the correct artist name ``Camila Cabello''. Secondly, the EL model is able to recover from errors made by the NER system by leveraging the knowledge base to disambiguate entity mentions. The reranking is especially powerful when the utterance contains little context of the entity for the NER model to leverage. For example, for ``Doctor Strange'', the top NER hypothesis labels the full utterance as a generic ``Person'' type, and after reranking, EL model is able to leverage the popularity information (``Doctor Strange'' is a movie that was recently released and has a high popularity in our knowledge base) and correctly label the utterance as ``movieTitle''. Reranking is also effective when the entity mentions are noisy, which will cause mismatches for the gazetteer features that NER uses. For ``play Avengers Age of Ultra'', the top NER hypothesis only predicts ``Avengers'' as ``movieTitle'', while after reranking, the EL model is able to recover the full span ``Avengers Age of Ultra'' as a ``movieTitle'', and resolve it to ``Avengers: Age of Ultron'', the correct canonical title. The entity relations from the knowledge base are helpful for entity disambiguation. When the user refers to a sports team with the name ``Giants'', they could be asking for either ``New York Giants'', a National Football League (NFL) team, or ``San Francisco Giants'', a Major League Baseball team. When there are multiple sports team mentions in an utterance, the EL model leverages a relation feature from the knowledge base indicating whether the teams are from the same sports league (as the user is more likely to mention two teams from the same league and the same sport). Knowing entity relations, the EL model is able to link the mention ``Giants'' in ``Cowboys versus Giants'' to the NFL team, knowing that ``Cowboys'' is referring to ``Dallas Cowboys''. \section{Conclusion} \label{sec:concl} In this work, we have proposed a Named Entity Understanding framework that jointly identifies and resolves entities present in an utterance when a user interacts with a voice assistant. Our proposed architecture consists of two modules: NER and EL, with the EL serving the additional task of possibly correcting the recognized entities from NER by leveraging rich signals from entity links in the knowledge base while simultaneously linking these entities to the knowledge base. With several design strategies in our system targeted towards noisy natural language utterances, we have shown that our framework is robust to speech transcription and user errors that occur frequently in spoken dialog systems. We have also shown that featurizing the output of NEU and feeding these features into other language understanding tasks substantially improves the accuracy of these models. \section{System Evaluation} \label{sec:expt_res} \input{sections/s5.1-ner_el.tex} \input{sections/s5.2-case_study.tex} \input{sections/s5.3-application.tex} \section{Introduction} \label{sec:intro} Understanding named entities correctly when interacting with virtual assistants (e.g. ``Call Jon'', ``Play Adele hello'', ``Score for Warrior Kings game'') is crucial for a satisfying user experience. However, NER and EL methods that work well on written text often perform poorly in such applications: utterances are relatively short (with just $5$ tokens, on average), so there is not much context to help disambiguate; speech recognizers make errors (``Play Bohemian raspberry'' for ``Play Bohemian Rhapsody"); users also make mistakes (``Cristiano Nando'' for ``Cristiano Ronaldo''); non-canonical forms of names are frequent (``Shaq'' for ``Shaquille O'Neal''); and users often mention new entities unknown to the system. In order to address these issues we propose a novel Named Entity Understanding (NEU) system that combines and optimizes NER and EL for noisy spoken natural language utterances. We pass multiple NER hypotheses to EL for reranking, enabling NER to benefit from EL by including information from the knowledge base (KB). We also design a retrieval engine tuned for spoken utterances for retrieving candidates from the KB. The retrieval engine, along with other techniques devised to address fuzzy entity mentions, lets the EL model be more robust to partial mentions, variation in named entities, use of aliases, as well as human and speech transcription errors. Finally, we demonstrate that our framework can also empower other natural language understanding tasks, such as domain classification (a sentence classification task) and semantic parsing. \section{Datasets and Training Methodology} \label{sec:expt_setup} To create our datasets, we randomly sampled around $600k$ unique anonymous English transcripts (machine transcribed utterances), and annotated them with NER and EL labels. Utterances are subject to Apple’s baseline privacy practices with respect to Siri requests, including that such requests are not associated with a user’s Apple ID, email address, or other data Apple may have from a user’s use of other Apple services, and have been filtered as described in Section \ref{sec:ethics}. We then split the annotated data into 80/10/10 for train, development and test sets. For both the NER and EL tasks, we report our results on test sets sampled from the ``music'', ``sports'' and ``movie \& TV'' domains. These are popular domains in the usage and have a high percentage of named entities: with an average of 0.6, 1.1 and 0.7 entities for each utterance in the 3 domains respectively. To evaluate model performance specifically on noisy user inputs, we select queries from the test sets that are marked as containing speech transcription or user errors by the annotators and report results on this ``noisy" subset, which constitutes 13.5\%, 12.7\% data for movie\&TV and music domain respectively when an entity exists. \footnote{Sports domain does not have the annotation for noisy data available when this experiment was conducted.} To evaluate the relation feature, we also look at the ``related" subset where a valid relation exists in the utterance. This subset consists 13.4\% and 5.3\% of data for the music and sports domain with at least one entity. \footnote{Our KB does not have relation information for movie\&TV domain.} We first train the NER model described in Section \ref{sec:ner}. Next, for every example in our training dataset, we run inference on the trained NER model and generate the top-5 NER hypotheses using beam search. Following this, we retrieve the top 25 candidates for each of these hypotheses using our search engine combined with the ground truth NER and EL labels and fed to the EL model for training. To measure the NER model performance, we use the standard NER F1 metric used for the CoNLL-2003 shared task \cite{tjong-kim-sang-de-meulder-2003-introduction}. To measure the quality of the top-5 NER hypotheses, we compute the oracle top-5 F1 score by comparing and choosing the best alternative hypothesis among the $5$ and calculate its F1 score, for each test utterance. In this manner, we also know the upper bound that EL can reach from reranking NER hypotheses. As described in section \ref{subsec:el}, the EL model is optimized to perform two tasks simultaneously: entity linking and reranking of NER hypotheses. Hence to evaluate the performance of the EL model, we use two metrics: reranked NER-F1 score and the EL-F1 score. The reranked NER F1 score is measured on the NER predictions according to the top EL hypothesis, and is defined in the same way as the previous NER task. To evaluate entity linking quality, we adopt a strict F1 metric similar to the one used for NER. Besides entity boundary and entity type, the resolved entity also needs to be correct for the entity prediction to be counted as a true positive. \label{sec:hyperparams} For NER model training, we use standard mini-batch gradient descent using the Adam optimizer with an initial learning rate of 0.001, a scheduled learning rate decay of 0.99, LSTM with a hidden layer of size 350 and a batch size of 256. We apply a dropout of 0.5 to the embedding and biLSTM layers, and include token level gazetteer features \cite{ratinov-roth-2009-design} to boost performance in recognizing common entities. We linearly project these gazetteer features and concatenate the projection with the 200 dimensional word embeddings and 100 dimensional character embeddings which are then fed into the biLSTM followed by the CRF. For EL, the character CNN model we use has two layers, each with 100 convolution kernels of size 3, 4, and 5. Character embedding are 25 dimensional and trained end to end with the entity linking task. The MLP for embedding similarity takes the concatenation of two name embeddings, as well as their element-wise sum, difference, minimum, maximum, and multiplication. It has two hidden layers of size 1024 and 256, with output dimension 64. Similarity features of mentions in the prediction are averaged, while the other features like NER confidence and entity popularity are concatenated to the representation. The final MLP for scoring has two hidden layers, with size 256 and 64. We train the model on 4 GPUs with synchronous SGD, and for each gradient step we send a batch of 100 examples to each GPU. \section{Related Work} \label{sec:rel_work} There have been a few attempts to explore NER on the output of a speech pipeline \cite{ghannay2018end,abujabal2018neural,coucke2018snips}. Among these, our NER model is closest to \newcite{abujabal2018neural} and \newcite{coucke2018snips}; however, unlike the former, we use a richer set of features rather than phonemes as input, and unlike the latter, we are able to use a deep model because of the large volume of data available. EL has been well explored in the context of clean \cite{martins-etal-2019-joint,kolitsas-etal-2018-end,luo2015joint} and noisy text inputs \cite{eshel-etal-2017-named,guo-etal-2013-link,liu-etal-2013-entity}, but as with NER, there have been only a few efforts to explore EL in the context of transcribed speech \cite{benton-dredze-2015-entity,gao-2017-support}, although crucially, both these works assume gold standard NER and focus purely on the EL component. Traditionally, a pipelined architecture of NER followed by EL has been used to address the entity linking task \cite{lin-etal-2012-entity,derczynski2015analysis,bontcheva2017crowdsourcing,bowden-etal-2018-slugnerds}. Since these approaches rely only on the best NER hypothesis, errors from NER propagate to the EL step. To alleviate this, joint models have been proposed: \newcite{sil-yates} proposed an NER+EL model which re-ranks candidate mentions and entity links produced by their base model. Our work differs in that we use a high precision NER system, while they use a large number of heuristically obtained Noun Phrase (NP) chunks and word n-grams as input to the EL stage. \newcite{luo2015joint} jointly train an NER and EL system using a probabilistic graphical model. However, these systems are trained and tested on clean text and do not address the noise problems we are concerned with. \section{Ethical Considerations} \label{sec:ethics} We randomly sampled transcripts from Siri production datasets over a period of months, and we believe it to be a representative sample of usage in the domains described. In accordance with Apple’s privacy practices with respect to Siri requests, Siri utterances are not associated with a user’s Apple ID, email address, or other data Apple may have from a user’s use of other Apple services. In addition to Siri’s baseline privacy guarantees, we filtered the sampled utterances to remove transcripts that were too long, contained rare words, or contained references to contacts before providing the dataset to our annotators. \subsection{Joint Linking and Re-ranking} \label{subsec:el} \begin{table*}[b] \begin{equation} s(\mathbf{y}) = \textbf{MLP} ( \mathbf{f}_{\text{utter}} \oplus \mathbf{f}_{\text{NER}} \oplus \mathbf{f}_{\text{CR}} \bigoplus_{j=1}^{k} [\textbf{MLP}(\textbf{CNN}(\mathbf{m}_j), \textbf{CNN}(\mathbf{e}_j)) \oplus \\ \textbf{CNN}(\mathbf{m}_j) \oplus \textbf{CNN}(\mathbf{e}_j)] ) \label{eq-nen-score} \end{equation} \end{table*} The entity linking system follows the NER model and consists of two steps: candidate retrieval, and joint linking and re-ranking. To build the candidate retrieval engine, we first index the list of entities in our knowledge base, which can be updated daily to capture new entities and change of their popularity. To construct the index, we iterate through the flattened list of entities and construct token-level unigram, bigram and trigram terms from the surface form of each entity. Apart from using the original entity names, we also use common aliases, harvested from usage logs, for popular entities (e.g. LOTR as an alias for ``Lord of the Rings'') to make the retrieval engine more robust to commonly occurring variations. Next, we create an inverted index which maps the unique list of n-gram terms to the list of entities that these n-grams are part of, also known as posting lists. Further, to capture cross-entity relationships in the knowledge base (such as relationships between an artist and a song or two sports teams belonging to the same league), we assign a pointer\footnote{Each entity in our knowledge base consists of metadata (for example, a song entry in our knowledge base would contain metadata such as the music artist, album, year the song was released in etc.) that we leverage to automatically construct these relationship pointers.} for each entity in the knowledge base to its related entities and this relational information is leveraged by the EL model for entity disambiguation (described in \ref{sec:qualitative}). We then compute the tf-idf score for all the n-gram terms present in the entities and store them in the inverted index. For each hypothesis predicted by the NER model we query the retrieval engine with the corresponding text. We first send the query through a high-precision seq-to-seq correction model \cite{schmaltz-etal-2017-adapting,ge-etal-2019-automatic} trained using common errors observed in usage. Next, we construct n-gram features from the corrected query in a similar way to the indexing phase and retrieve all entities matching these n-gram features in our inverted index. Additionally, we use synonyms derived from usage for each term in the query to expand our search criteria: for example, our synonym list for ``Friend" contains ``Friends", which matches the TV show name which would have been missed if only the original term was used. For each entity retrieved, we get the tf-idf score for the terms present in the query chunk from the inverted index. We then aggregate the tf-idf scores of all the terms present in the query for this entity and linearly combine this aggregate score with other attributes such as popularity (i.e. prior usage probability) of the entity to generate a final score for all retrieved entity candidates for this query. Finally, we perform an efficient sort across all the entity candidates based on this score and return a top-$c$ (in our case $c$ = 25) list filtered by the entity type detected by the NER model for that hypothesis. These entity candidates coupled with the original NER hypothesis are sent to the ranker model described below for joint linking and re-ranking. Following the candidate retrieval step, we introduce a neural model to rerank the candidate entities, aggregating features from both the NER model and the candidate retrieval engine. The EL model scores each entity linking hypothesis separately. An entity linking hypothesis consists of a prediction from the NER model (which consists of named entity chunks in the input utterance and their types), and the candidate retrieval results for each chunk. Formally, we define an entity linking hypothesis $\mathbf{y}$ with $k$ entity predictions as: \begin{equation*} \mathbf{y} = \{ \mathbf{f}_{\text{utter}}, \mathbf{f}_{\text{NER}}, \mathbf{f}_{\text{CR}}, \{j \in \{1 \dots k\}: ( \mathbf{m}_j, \mathbf{e}_j ) \} \} \end{equation*} \noindent where $\mathbf{m}_j$ is the $j$-th mention in the utterance, and $\mathbf{e}_j$ is the entity name associated with this mention from the knowledge base. $\mathbf{f}_{\text{utter}}$, $\mathbf{f}_{\text{NER}}$, $\mathbf{f}_{\text{CR}}$ are features derived from the original utterance text, the NER model and the candidate retrieval system respectively. In our system, $\mathbf{f}_{\text{utter}}$ is a representation of the utterance from averaging the pre-trained word embeddings for the tokens in the utterance. Intuitively, having a dense representation of the full utterance can help the EL model better leverage signals from the utterance context. $\mathbf{f}_{\text{NER}}$ includes the type of each mention, as well as the sequence and mention confidence computed by the NER model. $\mathbf{f}_{\text{CR}}$ includes popularity, and whether a relation exists between the retrieved entities in $\mathbf{y}$. To be robust to noise, the EL model adopts a pair of CNNs to compare each entity mention $\mathbf{m}_j$ and its corresponding knowledge base entity name $\mathbf{e}_j$. The CNN learns a name embedding with one-dimensional convolution on the character sequence, and the kernel parameters are shared between the CNN used for user mention and the one used for the canonical name. A character-based text representation model is better at handling mis-transcriptions or mis-pronounced entity names. While a noisy entity name may be far from the canonical name in the word embedding space when they are semantically different, they are usually close to each other in the character embedding space due to similar spellings. To model the similarity between CNN name embeddings of $\mathbf{m}_j$ and $\mathbf{e}_j$, we use the standard cosine similarity as a baseline, we experiment with an MLP that takes the concatenated name embeddings as input. We are able to model more expressive interactions between the two name embeddings with the MLP, and in turn better handle errors. Finally, we concatenate the similarity features with other features as input to another MLP that computes the final score for $\mathbf{y}$. Formally, the scoring function is defined in Equation \ref{eq-nen-score}, where $\oplus$ means concatenation. In our data, the number of entity mentions in an utterance averages less than 3. We pad the entity feature sequence to length 5, which provides a good coverage. In the scoring model above, we use a simple concatenation to aggregate the embedding similarities of multiple entity mentions which empirically performs as well as sequence models like LSTM, while being much cheaper in computation. To train the EL model, we use the standard max-margin loss for ranking tasks. If for the $i$-th example, we denote the ground truth as $\mathbf{y^*}_i$ and an incorrect prediction as $\mathbf{\hat{y}}_i$, and the scoring function $s(\cdot)$ is as defined in Equation \ref{eq-nen-score}, the loss function is \begin{equation} \mathcal{L} = \frac{1}{N}\sum_{i = 1}^{N} [\gamma(\mathbf{\hat{y}}_i, \mathbf{y^*}_i) + s(\mathbf{\hat{y}}_i) - s(\mathbf{y^*}_i)]_+. \label{eq-nen-loss} \end{equation} The max-margin loss encourages the ground truth score to be at least a margin $\gamma$ higher than the score of an incorrect prediction. The margin is defined as a function of the ground truth and the incorrect prediction, thus adaptive to the quality of prediction. A larger margin is needed when the incorrect prediction is further away from the ground truth. For our reranking task, we set a smaller margin when only the resolved entities are incorrect but the NER result is correct, and a larger margin when the NER result is wrong. This adaptive margin helps rerank NER hypotheses even when the model cannot rank the linking results correctly. During training, we uniformly sample the negative predictions from the candidates retrieved by the retrieval engine. \section{Architecture Diagram} \label{app:arch_diag} \begin{figure}[h] \centering \includegraphics[width=\linewidth]{figure/NEU_arch_diagram.pdf} \caption{NEU system architecture.} \label{fig:neu_architecture} \end{figure} \subsection{Results} \label{subsec:el-results} We present F1 scores in different domains of the NER and EL model in Table \ref{tb:nen-best}. Since the EL model takes 5 NER hypotheses as input, it also acts as a re-ranker of the NER model, and we show substantial improvements on top-1 NER F1 score consistently over all test sets. \begin{table}[h] \begin{center} \begin{tabular}{|@{\hskip3pt}l@{\hskip3pt}|r|c|l@{\hskip2pt}|} \hline & \multicolumn{1}{c|}{\textbf{\begin{tabular}[c|]{@{}c@{}}NER F1\\ top-1/top-5\end{tabular}}} & \multicolumn{1}{c|}{\textbf{\begin{tabular}[c|]{@{}c@{}}reranked\\ NER F1\end{tabular}}} & \multicolumn{1}{@{\hskip4pt}l@{\hskip2pt}|}{\textbf{EL F1}} \\ \hline \textbf{movie\&TV} & 78.76 / 96.83 & 81.62 & 79.67 \\ \textbf{music} & 84.27 / 97.26 & 87.40 & 84.95 \\ \textbf{sports} & 92.97 / 99.15 & 93.48 & 91.13 \\ \hline \end{tabular} \caption{Results for the best model setting. NER F1 are reported on the top-1 and top-5 NER prediction from the NER model that provides features for EL. Reranked NER F1 and EL F1 are reported on top-1 prediction from the best EL model selected by development sets.} \label{tb:nen-best} \end{center} \end{table} \begin{table*}[!htb] \begin{minipage}{.265\linewidth} \centering \begin{tabular}{|l|r|} \hline \hline \multicolumn{1}{|c|}{\textbf{}} & \multicolumn{1}{c|}{\textbf{\begin{tabular}[c]{@{}c@{}}{\bf (a)}\\+ MLP \end{tabular}}} \\ \hline \textbf{movie\&TV} & +3.58 \\ \textbf{(noisy)} & +9.67 \\ \hline \textbf{music} & +2.05 \\ \textbf{(noisy)} & +10.03 \\ \hline \end{tabular} \end{minipage}% \begin{minipage}{.27\linewidth} \centering \begin{tabular}{|l|r|} \hline & \textbf{ (b)\, \, \, \,} \\ & \textbf{+ Relation} \\ \hline \textbf{music} & +0.86 \\ \textbf{(related)} & +1.97 \\ \hline \textbf{sports} & +0.07 \\ \textbf{(related)} & +0.81 \\ \hline \end{tabular} \end{minipage} % \begin{minipage}{.4\linewidth} \centering \begin{tabular}{|l|r|r|} \hline \multicolumn{1}{|c|}{\textbf{}} & \multicolumn{1}{c|}{\textbf{\begin{tabular}[c]{@{}c@{}}{\bf (c)}\\+ Utterance \\ Embedding\end{tabular}}} & \multicolumn{1}{c|}{\textbf{\begin{tabular}[c]{@{}c@{}}{\bf (d)}\\+ Log-scale \\ Popularity\end{tabular}}} \\ \hline \textbf{movie\&TV} & +0.25 & +0.27 \\ \textbf{music} & +0.39 & +0.02 \\ \textbf{sports} & -0.07 & +0.08 \\ \hline \end{tabular} \end{minipage} % \caption{EL mean F1 relative \% improvements, reported on 10 runs average.} \label{tb:nen-improve} \end{table*} In Table \ref{tb:nen-improve}, we show improvements achieved by several specific model design choices and features on entity linking performance. Table~\ref{tb:nen-improve}(a) shows the MLP similarity substantially improves entity linking accuracy with its capacity to model text variations, especially on utterances with noisy entity mentions. The relation feature is powerful for disambiguating entities with similar names, and we show a considerable improvement in EL F1 on the subset of utterances that have related entities in Table~\ref{tb:nen-improve}(b). Table~\ref{tb:nen-improve}(c) shows utterance embeddings brought improvements in the music, and media \& TV domains. The improvement brought by log-scale popularity feature is the largest for the movie \& TV domain as shown in Table~\ref{tb:nen-improve}(d), where the popularity distribution has extremely long tails compared to other domains.
{'timestamp': '2021-08-11T02:24:57', 'yymm': '2005', 'arxiv_id': '2005.14408', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14408'}
arxiv
\section{Introduction}\label{sec:intro} Functional registration or time-warping, refers to the process of aligning two or more functions or curves in time and is often a pre-processing step necessary for appropriately analyzing such functions. By registering functions before performing statistical analysis on such functions, we can account for arbitrary reparameterizations of functions. This can lead to incorrect analyses of many functional data applications, such as the well-known growth rate curve analysis. Function registration is heavily relied upon in image and shape registration where analysis results can vastly differ depending on whether the data has been properly registered or not. More details on the importance of functional data registration can be found in \cite{FSDA, marron2015}, and \cite{ramsay2005}. Functional data registration is also referred to as phase-amplitude separation, because the underlying goal of the procedure is to effectively distinguish phase ($x$-axis) from amplitude ($y$-axis) variation. For example, in tracking the migration paths of birds or hurricanes, functional data registration would allow one to isolate the statistical variation in the paths, from the statistical variation in the speed of traversing the paths. The registration of a pair of functions results in an optimal warping function, which enables one function to be aligned to the other. The resulting aligned functions characterize the amplitude variability, while the warping function captures the phase variability between the two functions. Early approaches to functional data alignment fall short in four major ways. (1) They lack the ability to characterize the uncertainty of the optimal warping function. (2) They assume the observed functions are naturally smooth and lack measurement error. (3) They do not consider more than one optimal alignment between a pair of functions. Finally, (4) Most methods do not use a proper distance as the objective function for registration. Traditional approaches to functional data alignment, which are demonstrated in \cite{srivastava-etal-JASA:2011,ramsay2005, sangalli-etal2:2010}, and \cite{kneip-ramsay:2008}, are not flexible enough to characterize the uncertainty of the resulting optimal alignment solution. These approaches make the common assumption that the functions to be aligned are smooth, and thus they break down when a function exhibits too much noise. These methods usually rely on a derivative which is extremely noisy when the original functions are noisy, presenting additional computational challenges. Recently, Bayesian frameworks have been proposed that can characterize the uncertainty of the warping function solution \citep{telesca2008,kurtek2017,lu2017, cheng2016}. The clear difference between these approaches is in how they specify a prior on the space of the warping function; as it lives on a nonlinear infinite dimensional manifold. The more recent Bayesian approaches by \cite{cheng2016, lu2017}, and \cite{kurtek2017} rely on the square root velocity function (SRVF) representation of the warping function space, introduced by \cite{srivastava2011} and \cite{srivastava-etal-JASA:2011}, to simplify the complicated geometry. We will also take advantage of this transformation and provide more details in Section \ref{sec:review}. Although these approaches demonstrate how a Bayesian framework can naturally handle uncertainty quantification of the warping function through posterior inference, few have account for measurement error in the observed data and none allow for a multimodal posterior, i.e. multiple optimal warpings. Only the most recently proposed approach \cite{matuk2019}, has addressed the need to account for observed measurement error. There approach is for sparsely sampled functions where they propose a data-driven prior for inference and solely look at sparsely sampled functions and do not treat the dense problem. Previous approaches, Bayesian or otherwise, have assumed the observed functions to be aligned are naturally smooth. Although smoothness is a convenient assumption, it can be an invalid one in many practical applications. Recent work \cite{panaretos:2016}, utilized a fPCA construction to avoid overfitting when the data has additive amplitude variation. Wrobel \cite{wrobel:2019}, recently extended the alignment to non-Gaussian data. Both of these methods do not address the estimation of the additive noise process that we will address in this paper. Lastly, no current approaches consider the challenging case of multiple optimal alignments between a pair of functions; or briefly mention a possible solution without application. In this paper, we propose a hierarchical Bayesian approach to the registration of a pair of noisy functions on $\mathbb{R}^1$ and demonstrate its advantages over previously proposed registration algorithms. We propose a new framework for functional alignment which relies on a proper distance metric, is robust to noise, capable of characterizing the uncertainty of the warping function, and can account for multiple optimal alignments. The novelty of our new framework is the following: Most notably, we employ parallel MCMC chains to capture multi-modal posterior distributions of our warping functions; to reflect the case when there are multiple optimal alignments. Additionally, we favor the geometric Hamiltonian Monte Carlo algorithm of \cite{beskos2017} ($\infty$-HMC), which is nontrivial to apply to problem of functional data alignment. The implementation of $\infty$-HMC within our MCMC sampler can appropriately account for the complex geometry of the target space and more efficiently sample the warping function. Lastly, our approach accounts for appropriate propagates measurement error, a challenge which has only recently been addressed by \cite{matuk2019}. This paper is organized in the following way. Section \ref{sec:review} reviews pairwise functional registration in $\mathbb{R}^1$, the general challenges associated with it, and introduces the square-root velocity function representation and proper distance metric relied upon throughout this paper. Section \ref{sec:pairwise} specifies our hierarchical Bayesian model for registering a pair of noisy functions on $\mathbb{R}^1$, including our MCMC algorithm and multi-chain approach to the challenge of multiple alignments. In Section \ref{sec:examples}, we evaluate the approach on simulated functional data as well as two real data sets: a SONAR dataset that is naturally noisy and iPhone-collected accelerometer data with multiple possible alignments. Code for the method is found in the \verb+fdasrvf+ Matlab package on GitHub\footnote{\url{https://github.com/jdtuck/fdasrvf_MATLAB}}. Finally, we discuss the impact of this approach, extensions to multiple pairwise alignments, nontrivial extensions to functions on more complex geometries, and future work in Section \ref{sec:disc}. \section{A review of function registration in $\mathbb{R}^1$}\label{sec:review} Following the notation of \cite{tucker2013} and without loss of generality, let $f$ be a real-valued and absolutely continuous function on domain $[0, 1]$. Note that in practice, $f$ is observed as discrete and interpolation can be used to more easily perform the requisite calculations. Let $\mathbb{F}$ denote the set of all such functions and $\Gamma$ denote the set of boundary-preserving diffeomorphisms: $\Gamma = \{\gamma : [0,1]\mapsto [0,1] \mid \gamma(0)=0,\gamma(1)=1\}$ such that the mapping $ [0,1]\mapsto [0,1]$ is bijective (invertible) and differentiable. From this point on, we will refer to $\Gamma$ as the set of warping functions. Then, for any $f\in \mathbb{F}$ and any $\gamma \in \Gamma,$ $f \circ \gamma$ denotes the time-warping of $f$ by $\Gamma$. For simplicity, consider the pairwise alignment problem where we wish to align functions $f_1,f_2 \in \mathbb{F}.$ A simplified registration problem can be formulated by finding a warping, $\gamma^*,$ that minimizes the cost of translating $f_2$ to $f_1$, for chosen cost function $$\gamma^* = \text{argmin}_{\gamma} \| f_1 - f_2 \circ \gamma\|^*, $$ where $\| \|^*$ is our distance metric yet to be chosen.\footnote{Although we are proposing a more robust approach, we are introducing a simplified registration problem to motivate the use of a proper distance metric.} There are a few main challenges that all alignment approaches face and handle differently. One challenge of function alignment, as pointed out by \cite{srivastava-etal-JASA:2011} and \cite{tucker2013}, is finding a cost function to do the alignment that is both symmetric, that is, aligning $f_1$ to $f_2$ is the same as aligning $f_2$ to $f_1$, and positive-definite, so that the metric is always non-negative and zero if and only if $f_1$ and $f_2$ are the same function after alignment. A natural choice is the usual $\mathbb{L}^2$ norm, denoted by $\|\cdot\|^2$, but it does not satisfy the symmetry requirement. More precisely, $$\text{argmin}_{\gamma}\|f_1 \circ \gamma - f_2 \|^2 \neq \text{argmin}_{\gamma}\|f_1 - f_2 \circ \gamma \|^2. $$ Second, there can be the issue of degeneracy in which case $\gamma^*$ is so distorted it can align functions which should not be aligned; giving a false impression that these functions are \textit{close} in the $\mathbb{L}^2$ sense when indeed they are not. Lastly, the $\mathbb{L}^2$ norm is not invariant under warping. That is, $$\| f_1 - f_2 \|^2 \neq \| f_1 \circ \gamma - f_2 \circ \gamma\|^2.$$ This means that two functions which are similar in an $\mathbb{L}^2$ sense, could be vastly different under the same warping, and vice versa. To overcome these three challenges, we follow \cite{tucker2013}, \cite{cheng2016} and \cite{lu2017} and take advantage of the square-root velocity function (SRVF) representation introduced by \cite{srivastava2011}. A function $f\in \mathbb{F}$ can be represented as a SRVF via the mapping: $$q:[0,1]\mapsto \mathbb{R},\ \ q(f(t))=\hbox{sign}(\dot{f}(t))\sqrt{|\dot{f}(t)|} \hbox{ for any } f\in \mathbb{F}.$$ There is an equivalency, up to a constant, between the SRVF of $f$ and $f$ itself and it is given by $f(t) = f(0) + \int_0^t q(f(t))|q(f(t))| ds$, where $|\cdot|$ is the absolute value. Moreover, the SRVF of $f \circ \gamma$ is $(q \circ \gamma)\sqrt{\dot{\gamma}}$. The SRVF transformation lends itself naturally to the Fisher-Rao (FR) metric. It can be shown that the FR distance between two functions is equivalent to the $\mathbb{L}^2$ distance between their respective SRVF transformations, i.e., $\| f_1 - f_2 \|_{FR} = \|q(f_1) - q(f_2) \|^2$ (see \cite{srivastava-etal-JASA:2011}). More importantly, the FR metric is phase invariant under warping, i.e., $\| f_1 \circ \gamma - f_2 \circ \gamma \|_{FR} = \|f_1 - f_2 \|_{FR}$ and \cite{srivastava2011} shows that the FR metric is symmetric under warping as well, i.e., $\| f_1 \circ \gamma - f_2 \|_{FR} = \| f_1 - f_2 \circ \gamma \|_{FR}$. Following this framework and without loss of generality, we will align the SRVF of $f_2$ to the SRVF of $f_1$, and then map the aligned functions back to the original space $\mathbb{F}$. In other words, we seek to estimate the warping function that minimizes $||q_1- (q_2,\gamma)||^2$, where $(q_2,\gamma)=(q_2\circ\gamma)\sqrt{\dot{\gamma}}$ and $q_j \doteq q(f_j(t))$ for $j=1,2$. Additional challenges in function alignment come when placing the problem in a Bayesian framework, namely selecting a prior distribution for $\gamma \in \Gamma$. Recall that $\Gamma$ is the space of diffeomorphic function mappings from $[0,1] \mapsto [0,1]$. Both optimization and Bayesian inference over this space is difficult, in particular, because this space is nonlinear and infinite dimensional. For example, the sum or scalar product of functions in $\Gamma$ is not necessarily still contained in $\Gamma$. To overcome this difficulty, we follow the approach of \cite{lu2017,tucker2013} which transforms $\gamma$ to its corresponding SRVF representation, and exploits the Riemannian-geometric structure of this transformation. Which ultimately allows us to utilize more traditional inference or optimization algorithms that rely on the linearity of the underlying search space. To understand how this transformation works, it is helpful to think of the set of warping functions $\Gamma$ as the space of univariate cumulative distribution functions for random variables on $[0,1]$. Then, for each $\gamma \in \Gamma$ there is an associated density function. Now, let $\psi=\sqrt{\dot{\gamma}}$ be the corresponding SRVF of $\gamma$ and $\Psi^+=\{\psi: [0,1]\mapsto \mathbb{R}^+\mid||\psi||^2=1\}$ \citep{bhattachayya1943} be the space of square-root densities (SRD). The SRD space is the positive orthant of the unit sphere in the Hilbert space $\mathbb{L}^2([0,1])$ denoted by $\Psi\{\psi: [0,1]\mapsto \mathbb{R}\mid||\psi||^2=1\}$. While this space is still infinite and nonlinear, it is much more simply defined. Since the SRVF is a bijective mapping and $\gamma(0)=0,$ we can reconstruct $\gamma$ by the inverse mapping $q^{-1}(\psi)(t)=\int_0^t\psi^2(s)ds.$ We can further simplify, and even linearize $\Psi^+$ by mapping from the top half of the unit sphere onto a tangent space at $\psi$ defined as $$T_{\psi}(\Psi)=\{g\in \mathbb{L}^2\mid\int_0^1g(s)\psi(s) ds=0\}.$$ For simplicity, we typically take $\psi = 1$, i.e., the identity function. Geometric details on $T_1(\Psi)$ can be found in \cite{srivastava2007} and \cite{kurtek2012,tucker2013}. The exponential map and its inverse can be used to map between $\Psi$ and $T_1(\Psi):$ $$\begin{aligned} &\exp_1: & T_1(\Psi)\mapsto \Psi &\hspace{4mm} \exp_1(g)=\cos(||g||)+\sin(||g||)\frac{g}{||g||},~~ g\in T_1(\Psi)\\ &\exp^{-1}_1: & \Psi\mapsto T_1(\Psi) &\hspace{4mm} \exp^{-1}_1(\psi)=\frac{\theta}{\sin(\theta)}(\psi-\cos(\theta)) ,~\theta=d(1,\psi) \hbox{ and } \psi\in\Psi, \end{aligned}$$ where $d(1,\psi) = \cos^{-1}\left(\int_0^1 \psi(t) dt \right)$. Mapping $\gamma$ onto the tangent space $T_1(\Psi)$ (summarized in Figure \ref{fig:mappings}) gives a convenient representation of $\gamma$ in the parametric vector space, and thus allows for a straight-forward prior specification to be placed on $T_1(\Psi)$ (discussed further in \ref{sec:modelspec}). Intuitively, this linearization is akin to mapping the points on the top half of the sphere to the tangent plane at the the north pole. Moreover, because $T_1(\Psi)$ is the space of square integrable functions with mean zero, one can parameterize this space of functions with a basis representation. \begin{figure} \centering \includegraphics[scale=0.3]{mappings.pdf} \caption{A summary of the mapping from $\Gamma$ to $T_1(\Psi)$ where the space $\Gamma$ is a nonlinear manifold and $\Psi$ is the unit sphere in the Hilbert space $\mathbb{L}^2([0,1])$.}\label{fig:mappings} \end{figure} Finally, through all of these transformations, the SRVF of $f_2 \circ \gamma$, denoted as $\mathcal{G}(g)$ can be written as $$\begin{aligned} \mathcal{G}(g(t))&:=(q_2,\gamma)(t)= q_2(\gamma(t))\sqrt{|\dot{\gamma(t)}|}&\\ &=q_2\bigg(\int_0^t\psi^2(s)ds\bigg)\psi(t)=q_2\bigg(\int_0^t\exp^2(g)(s)ds\bigg)\exp(g)(t),&&\\ \end{aligned}$$ where $g$ lives on the tangent space of $\Psi^+$, which is again linear. \section{Pairwise registration in $\mathbb{R}^1$}\label{sec:pairwise} First, we will detail our proposed approach in the simple case of pairwise alignment of functions $y_1$ and $y_2$ on $\mathbb{R}^1$. The functions are observed at a set of discretized time points $[t] = \{t_1,\dots,t_N\}$. In this section, we will fully specify our proposed Bayesian hierarchical framework for this pairwise alignment setting. Our Bayesian approach looks for optimal warping functions that warp one function to another using the $\mathbb{L}^2$ distance of the SRVF representations of the two functions, as defined in the previous section. Furthermore, by mapping the space of warping functions to the linear tangent space $T_1(\Psi)$ on the infinite dimensional half sphere we can perform the Bayesian inference over a parametrized, linear space. \subsection{Model specification}\label{sec:modelspec} Let $y_1$ and $y_2$ be noisy observations of $f_1, f_2 \in \mathbb{F}$, respectively. Then, at the first level of our hierarchical model we have, \textit{Level 1.} $$y_1([t])=f_1([t])+\epsilon_1([t]),\ \epsilon_1([t]) \sim MVN(0_N,\sigma_1^2 I_N)$$ and $$y_2([t])=f_2([t])+\epsilon_2([t]),\ \epsilon_2([t]) \sim MVN(0_N,\sigma_2^2 I_N),$$ where the observed noise processes $\epsilon_1, \epsilon_2$ are are assumed to follow a Gaussian white noise distribution with variances $\sigma_1^2$ and $\sigma_2^2$, respectfully, for each point in time. Here we assume no temporal correlation between noise parameters. Using the SRVF representation described in Section \ref{sec:review}, we aim to align $q_2(\gamma([t]))=q(f_2(\gamma([t]))$ to $q_1([t])=q(f_1([t]))$. Using the transformations from the previous section, we can equate $q_2(\gamma([t]))$ to $\mathcal{G}(g([t]))$ where $g$ is the projection of the square root density of $\gamma$ onto the tangent space of the infinite half sphere and so we model $q_1([t])-\mathcal{G}(g([t]))$ using a zero-mean multivariate Gaussian distribution following \cite{lu2017}. It should be noted that $q_2(\gamma([t])) = q_2(\int_0^{[t]}\psi(s)\,ds)\psi([t])$, where $\int_0^{[t]}\psi(s)\,ds$ denotes the $N$-dimensional vector \\ $\{\int_0^{t_1}\psi(s)\,ds,\dots,\int_0^{t_N}\psi(s)\,ds\}$. Thus, at the second level we have, \textit{Level 2.} $$q_1([t])-\mathcal{G}(g([t])) \sim MVN(0_N,\sigma^2 I_{N}),$$ with negative log-likelihood \begin{equation}\label{eq:phi} \Phi(g) := -\log p(q_1,q_2; g)\propto\bigg(\frac{1}{\sigma^2}\bigg)^{N}\exp\bigg\{-\frac{1}{2\sigma^2}\sum_{i=1}^{N}\big(q_1(t_i)-(q_2,\gamma)(t_i)\big)\bigg\}. \end{equation} Following the approach of \cite{lu2017}, we will assign a zero-mean Gaussian process prior to the sampled tangent space $T_1(\Psi),$ $$g \sim GP(0,\mathcal{C}),$$ with $\mathcal{C}$ being a positive, self-adjoint and trace-class operator on $\mathbb{R}^1.$ Zero-mean multivariate normal priors are assigned to mean functions $f_1([t])$ and $f_2([t])$ with structured kernel functions $K_1$ and $K_2$, i.e. $$f_1([t])\sim MVN(0_N,K_1) \hbox{ and } f_2([t]) \sim MVN(0_N,K_2).$$ In this work, we specify the squared exponential kernel function $K([t])=s^2\exp(-(d/2l)^2)$ for both $K_1$ and $K_2$ where $d$ is the computed distance matrix of $[t].$ Conditionally-conjugate inverse-gamma priors are specified for all covariance parameters $\sigma^2,\ \sigma_1^2,\ \sigma_2^2$ with the prior for $\sigma^2$ less informative than prior for $\sigma_1^2$ and $\sigma_2^2$ to help with potential identifiability issues. Hyperparameters $s_1^2, s_2^2$ and $l_1,l_2$ are assigned inverse-gamma and uniform priors respectively. The full hierarchical posterior can now be written as $$p(g,\theta | y_1,y_2) = \left[ \prod_{j=1}^2p(y_j|f_j,\sigma_j^2) \right] \exp \left[ -\Phi(g) \right]\pi(g,\theta), $$ where $\theta \doteq \{f_1,f_2,\sigma^2,\sigma_1^2,\sigma_2^2,\ s_1^2,\ s_2^2,\ l_1,\ l_2\}$, $\pi(g,\theta)$ is the prior distribution over parameters $g$ and $\theta$, and $p(y_j|f_j,\sigma_j^2)=\prod_{i=1}^Np(y_j(t_i)|f_j(t_i),\sigma_j^2)$ for $j=1,2$ is a product of univariate Gaussian distributions. \subsection{MCMC sampling} A Metropolis within Gibbs sampler is used to sample from the complete posterior distribution $p(g,\theta|y_1,y_2).$ For practical implementation, functions $f_1, f_2$ are discretized and we specify a basis representation for $g$, i.e., $g=B\mathbf{v}$ where $\bf{v}$ and $B$ are the set of $n_v$ basis coefficients and matrix of basis functions, respectively. The reason for this specification is as follows. Recall that $g$ lives on $T_1(\Psi)$, the tangent space to the top half of the infinite-dimensional unit sphere at the point $\psi \in \Psi$. For simplicity, we take $\psi$ to be the identity element so that $T_1$ becomes the space of all $\mathbb{L}^2$ integrable functions on $[0,1]$ that have zero mean with respect to unit weight, i.e., the uniform density on the unit interval. Even though $g$ is still infinite-dimensional we can sample it using the Karhunen-Lo\`{e}ve expansion where we specify the covariance operator $C$ via its eigenpairs $(b_k,\lambda_k^2)$, where the set $\{b_k(\cdot)\}$ forms an orthonormal basis for the functions space $T_1(\Psi)$. We therefore sample independent variates $v_k\sim\mathcal{N}(0,\lambda_k^2)$ and set $$ g = \sum_{k=1}^M v_k b_k, $$ where $M$ is the number of basis functions. This is similar to the method proposed in \cite{lu2017}. We can then use a Fourier series type representation to parameterize $C$ in terms of a finite collection of basis coefficients, $\mathbf{v}$, and discretized orthogonal basis vectors represented by columns of $B$. The eigenvalues, $\lambda_k$, are set to $\sigma_g^2/k_2$, where $\sigma_g$ is assumed to be known or provided. The choice of orthogonal basis functions are plentiful, but this paper uses the Fourier series and Legendre polynomial expansions. Both sets form a complete basis over the space of $\mathbb{L}^2$ integrable functions on a compact interval. Moreover, for the application at hand, both basis functions (other than the constant) are orthogonal to the unit weight; thus making it easy to satisfy the tangent space property. The Fourier basis is typically used for periodic functions and so convergence can be hindered if the function values are different at the domain end points. Legendre polynomials do not have this limitation, but they are not as widely known. The smoother the function to be approximated is, the faster the decay of the basis coefficients. This means we need fewer basis coefficients to represent the underlying function. In fact if the function is infinitely differentiable, the decay of the basis coefficients can be spectral, i.e., exponentially decaying. This applies to both Fourier and polynomial based expansions (see \cite{hesthaven2007}). The basis specification for $C$ thus allows us to more efficiently explore the posterior space $g|y_1,y_2,\theta$. To update $g,$ we wish to sample from the conditional posterior $p(g|y_1,y_2,\theta, B)$ $\propto \exp\big(-\Phi(g)\big)$. To account for the complex geometry of the target space which ${g|\cdot}$ lies on and to allow for our sampler, we will exploit Hamiltonian dynamics. Specifically we use the $\infty$-HMC algorithm described in \cite{beskos2017} to sample ${g|\cdot}$ within our MCMC sampling procedure. $\infty$-HMC is a modification of the standard Hamiltonian Monte Carlo (HMC algorithm developed to be well-defined on the infinite-dimensional Hilbert Space and thus is ideal for sampling from $T_1(\Psi)$. HMC is a natural choice for more complex geometries, as it allows for efficient sampling along posterior contours. As \cite{beskos2017} describes, HMC is an improvement over the preconditioned Crank-Nicholson method. Moreover, as we will show, in cases where the target density is multi-modal and separated by low probability regions, a parallel chain implementation with random starting points is needed to fully explore the state space of ${g|\cdot}$ (details given in Section \ref{sec:multalign}). The algorithm, detailed in Algorithm \ref{alg:infhmc} utilizes an auxiliary variable. As suggested in \cite{beskos2011} and implemented in \cite{beskos2017}, we choose to specify the auxiliary variable $v,$ interpreted as the \textit{velocity} of $g$. To implement Algorithm \ref{alg:infhmc}, and to update $g$, it is necessary to define the location-specific preconditioner matrix $\mathcal{K}(g)$ as the covariance of a local Gaussian approximation $N(m(g),\mathcal{K}(g))$ to the posterior. We define this pre-conditioner through its inverse: $$\mathcal{K}(g)^{-1} = \mathcal{C}^{-1} + \beta \mathcal{H}(g),$$ where $\mathcal{H}(g)$ is chosen as the Gauss-Newton Hessian (GNH), i.e. $$\mathcal{H}(g) = \langle \bigtriangledown \mathcal{G} (g),\ \mathcal{C}^{-1}\bigtriangledown \mathcal{G} (g)\rangle.$$ We can then calculate the natural gradient $\eta$: $$\eta (g)= -\mathcal{K}(g) \big[ \bigtriangledown \Phi (g)-\beta \mathcal{H} (g) g\big], $$ to calculate the Hamiltonian flow, $\Xi^t.$ As the exact analytic expression of $\Xi^t$ is often not available, $\infty$-HMC defines the flows $\Xi_1^t,\ \Xi_2^t$ of a split Hamiltonian system to numerically approximate $\Xi^t:$ $$\Xi_1^t(g,v)=\big(g,v+\frac{t}{2}\eta(g)\big)\ \hbox{ and }\ \Xi_2^t(g,v) = \big(g\cos t+v\sin t,-g\sin t+v\cos t\big).$$ The leapfrog map $\Psi_h(g,v): (u_0, v_0) \mapsto (g_h,v_h)$ is the composition of three sub-steps: $$\Psi_h(g,v)=\Xi_1^{h/2} \circ \Xi_2^h \circ \Xi_1^{h/2},$$ and the exact Hamiltonian flow $\Xi^T$ is then approximated by $$\Psi_h^{I}(g,v)=\Psi_h^{\lfloor T/h \rfloor},$$ a concatenation of $I=\lfloor T/h \rfloor$ Verlet steps. $\infty$-HMC requires user chosen time-step $h$ and leap-frog step $T.$ $\bigtriangledown\Phi(g)$ is the directional derivative of $\Phi$, defined in \eqref{eq:phi}, with respect to $g$ which is provided in the \ref{sec:deriv}. Compared to the \textit{Z-mixture pCN algorithm} \citep{cotter2013} used in \cite{lu2017} to update $\bf{v}$, we find that using $\infty$-HMC algorithm to update $g$ is significantly more efficient. We favor $\infty$-HMC over Z-mixture pCN because we are sampling from an infinite dimensional space. \cite{beskos2017} demonstrates that random walk-like algorithms, like the Z-mixture pCN, are not efficient and can break down on these high dimensional spaces. Additionally, the gradient information $\infty$-HMC relies upon helps inform the sampler and has been shown to increase overall MCMC sampling performance for hierarchical models, especially when sampling on infinite dimensional spaces \citep{beskos2017, BDA}. For broader application and sampling efficiency of the prior on the space of diffeomorphisms we chose to implement $\infty$-HMC for these reasons. We found that the Z-mixture pCN algorithm, even when implemented via parallel chains with random starts, was not able to capture the expected bimodal posterior in our simulated data example. The posterior was biased towards one mode only as shown in the posterior samples and achieved higher SSE. Figures demonstrating these comparisons are given in \ref{sec:mcmcdiag}. The additional tuning parameters, specifically the leap frog and time step sizes ($T$ and $h$ in Algorithm~\ref{alg:infhmc} respectively), available using $\infty$-HMC allowed for the posterior samples to more easily jump between the multiple possible target modes. \begin{algorithm} \caption{Sampling Algorithm for $g$ via $\infty$-HMC (\cite{beskos2011})}\label{alg:infhmc} \begin{enumerate} \item Given current $g$, propose $g'= P_g\{\Psi_h^{I}(g,v))\}$ where $P_g\{\cdot\}$ is the projection of $(g',v')=\Psi_h^{I}(g,v)$ onto the $g$ argument and $v$ (velocity) is an auxiliary variable sampled from $N(0,\mathcal{C}).$\\ \item Accept $g'$ with probability $1 \wedge \exp\{-\Delta H(g,v)\},$ $$\Delta H(g,v)\equiv H(g',v')-H(g,v),\ \ H(g,v)=\Phi(g)+\frac{1}{2}\langle g,\mathcal{C}^{-1}g\rangle+\frac{1}{2}\langle v,\mathcal{C}v\rangle.$$ \end{enumerate} \end{algorithm} Mean functions $f_1, f_2 \in \mathbb{R}^1$ are sampled from their respective conditional posteriors $$p(f_k|y_k,\theta)\propto p(y_k|f_k,\sigma_k^2)p(q_k([t])-\mathcal{G}(g([t]))|y_1,y_2,\theta)\pi(f_k),\ k=1,2~,$$ via Metropolis-Hastings with specified proposals $$f_k'([t]) \sim MVN(f_k([t]),\Sigma_k^*),\ k=1,2,$$ and squared exponential correlation structures specified for $\Sigma_1^*$ and $\Sigma_2^*.$ Variance parameters $\sigma^2,\ \sigma_1^2,\ \sigma_2^2$ and hyperparameters $s_1^2$ and $s_2^2$ can be Gibbs sampled from their respective inverse-gamma posteriors. Hyperparameters $l_1$ and $l_2$ can be sampled via Metropolis-Hastings with Gaussian proposal distributions and acceptance ratios: $$\alpha_{l_k}=\frac{p(f_k|y_k,l'_k)\pi(l_k)}{p(f_k|y_k,l_k)\pi(l'_k)},\ k=1,2.$$ \subsection{MCMC for multiple optimal alignments}\label{sec:multalign} Due to the high efficiency of the $\infty$-HMC algorithm, a single posterior chain generated using $\infty$-HMC would not be able to jump between modes and thus would be unable to capture multi-modal distributions. As highlighted by \cite{nishimura2017}, if the target distribution is multi-modal with modes separated by regions of low probability density; it is nearly impossible for any HMC algorithm to transition between modes due to the conservation of energy property of Hamiltonian dynamics. To obtain a multi-modal posterior distribution for $g|y_1,y_2,\theta,$ we run $K$ parallel chains with initial values for the basis coefficients of $g$ chosen randomly from a standard Normal distribution. The idea is to run separate chains at enough randomly generated starting points to land in the vicinity of the multiple modes; so that we don't have to rely on the HMC algorithm to cross the low-probability regions. Of course, we have no idea where those modes are in general, so it is important to explore the initial starting space. In this case the starting space is the space of coefficients, $\mathbf{v}$, of the linear expansion of $g$. Furthermore, under the assumption that each chain reaches their target sampling density after a thorough burn-in period, we can treat each chain as providing independent samples; and thus simply pool them together. For example, if each of the ten chains produce 10k samples, we can pool them together to obtain 100k samples. Alternatively, we can think of this approach as a type of parallel MCMC with a constant temperature parameter and no mixing. It is important to highlight that there could be more than one best possible solution. Having a posterior that can capture the total variability of the warping function sample all possible solutions, rather than simple pick one as a local optima, is an advantage of our method. However in practice, it may be necessary to choose between multiple possible solutions. This determination is application dependent; a good metric is to choose the best warping function that produces the smallest amplitude distance $||q_1 - (q_2,\gamma))||^2$ between the two SRVFs $q_1$ and $q_2$. Another suggestion is one sees see more of the posterior favoring one alignment over the other and this solution could be chosen. \section{Examples}\label{sec:examples} To demonstrate our proposed method, we will compare our flexible Bayesian approach with the state-of-the-art Dynamic Programming (DP) method of \cite{FSDA}. In short, the DP algorithm solves the optimal warping function by proposing successively better piecewise linear pathways on a unit square grid; where better is defined in terms of the Fisher-Rao metric. First, we will assess our method's performance on simulated noisy data for which multiple optimal alignments exist. Next, we will apply our method to two real datasets: a SONAR dataset and an iPhone movement dataset. The SONAR data is notably noisy and thus difficult to register. The iPhone data is less noisy but has multiple optimal alignments that previous methods discussed in Section \ref{sec:intro} do not account for. Before we move on to the examples, we need to address the issue of computing means or averages in non-Euclidean geometries, e.g., the positive orthant of infinite-dimensional unit sphere. For problems of this type, we typically use the Karcher or Fr\'{e}chet mean. This is obtained by minimizing the average squared distance between all pairs of sample points, $x_1,\dots,x_N \in \Psi$ i.e. $$m = \text{arg} \min_{p \in \Psi} \sum_{i=1}^N d^2(p,x_i), $$ where $d$ is the metric or geodesic distance measure on $\Psi$, the infinite-dimensional positive orthant of the unit sphere, given by $$d(\psi_1,\psi_2) = \cos^{-1}\left(\int_0^1 \psi_1(s)\psi_2(s) ds \right).$$ Note that in the case of Euclidean geometry, the Karcher mean is simply the average. The computation of the Karcher median is analogous. We use the method presented in \cite{XieKurtek:2016}, which is an extension of Algorithm 2 in \cite{tucker2013}. Now, in the multiple alignment case, our posterior will be multi-modal. In order to find the centroid of these individual modes, we do the following. We begin by computing all the pairwise distances under the metric $d$, between all posterior samples. We then use a clustering algorithm to separate the samples into their respective clusters. Then, for each cluster the Karcher mean or median can be computed as in the unimodal case. \subsection{Simulated data} \label{sec:simex} Consider the misaligned and noisy observations $y_1$ and $y_2$ shown in Figure \ref{fig:simf1f2} simulated by adding Gaussian white noise with $\sigma_1^2=\sigma_2^2=0.001$ to the true mean functions $f_1$ and $f_2$. Without loss of generality, we wish to align $y_2$ to $y_1.$ \begin{figure}[H] \centering \includegraphics[width=0.48\textwidth]{bimodal_simex.png} \includegraphics[width=0.48\textwidth]{bimodal_f1f2posteriors.png} \caption{Simulations $y_1$ and $y_2$ (left) and their respective posteriors $f_1|y_1$ and $f_2|y_2$ (right) plotted against the true functions.} \label{fig:simf1f2} \end{figure} The right panel in Figure \ref{fig:simf1f2} shows the estimated posteriors for $f_1$ and $f_2$ given our Bayesian approach. Figure \ref{fig:simwarping} compares the dynamic programming (DP) solution with our Bayesian approach. On the left, we see the optimal warping function for $y_2$ in blue, found by DP ($\gamma_{DP}$), which reflects some of the noise in the data and only identifies one possible warping function. The corresponding warped solution $y_2 \circ \gamma_{DP}$ is also shown in blue on the right. Also the warped solution of $\hat{f}_2 \circ \gamma_{DP}$ is shown in green, where $\hat{f}_2$ smoothed version of $y_2$ and DP is performed on a smoothed versions of $y_1$ and $y_2$. The smoothing in this case was performed using Gaussian process regression. In our Bayesian approach, we ran 8 MCMC chains each with 20,000 iterations, a burn-in of 5,000 iterations without thinning, for a total of 4,000 effective samples. The proposal parameters were chosen such that acceptance rates for each chain were between 0.2 and 0.4 (see Figure \ref{fig:simex_chains} for MCMC chains). Furthermore, we used $n_v=10$ Fourier basis functions to approximate the function $g$ on the tangent space $T_1(\Psi)$ resulting in a dimensionality of 20 (two for each basis function). The left figure of Figure \ref{fig:simwarping} compares the posterior samples of $\gamma|y_1,y_2$, with credible intervals and posterior mode to the DP solution. The right figure of Figure \ref{fig:simwarping} compares the posterior median warped solution to the DP warped solutions. From this we can see that the Bayesian approach gives us three possible solutions: (1) $f_2$ is aligned to the leftmost peak of $f_1$, (2) $f_2$ is aligned to the rightmost peak of $f_1$, and (3) $f_2$ is aligned to both peaks of $f_1$. Note that the DP method only gives us one out of the possible three solutions. \begin{figure}[H] \centering \includegraphics[width=0.48\textwidth]{bimodal_gammaall.png} \includegraphics[width=0.48\textwidth]{bimodal_f2warped_med.png} \caption{Comparison of the posterior distribution $\gamma|y_1,y_2$ to the DP solution $\gamma_{DP}$ applied to the simulated data, plotting the two identified modes and respective 95\% credible regions of the posterior $\gamma|y_1,y_2$ (left). Comparison of the DP warping of $y_2$ and smoothed $y_2$ to the median of the warping $f_2 \circ \gamma|y_1,y_2$ (right).} \label{fig:simwarping} \end{figure} \begin{figure}[H] \centering \includegraphics[width=0.48\textwidth]{bimodal_gamma_colored.png} \includegraphics[width=0.49\textwidth]{bimodal_f2warped_colored.png} \caption{$\gamma|y_1,y_2$ (left) and $f_2 \circ \gamma|y_1,y_2$ (right) from the 8 different MCMC chains, colored by the 3 posterior modes found.} \label{fig:simcolored} \end{figure} Further exploration of the Bayesian approach is shown in Figure \ref{fig:simcolored}. Here, we break down the posteriors $\gamma|y_1,y_2$ and $f_2 \circ \gamma|y_1,y_2$ from the 8 different MCMC chains, colored by the 3 posterior modes found. It is clear that 3 unique alignments were captured in the posteriors of $\gamma|y_1,y_2$ and $(f_2\circ \gamma)|y_1,y_2$ among the 8 different MCMC chains; identified by three distinct colors. The left shows the three posterior modes and respective 95\% credible regions, characterizing the uncertainty of each possible warping and the uncertainty of $(f_2\circ \gamma)|y_1,y_2$. This is exhibited by the width of the color-coded samples on the right. To give a statement on computational cost our implementation of the MCMC algorithm is done in MATLAB; and one chain for $3.2e4$ iterations takes 24 seconds on a 8 Core Mac Pro with 32GB of RAM. The dynamic programming algorithm is computationally $O(N^2)$, where $N$ is the dimension of the grid in the search space for the minimal energy, and for this simulated example $N=101$. The code provided the \verb+fdasrvf+ MATLAB package for DP is written in C and runs in 0.2 seconds. We executed this simulation for 25 replicates and computed the point-wise sum-of-squared error (SSE) for the median warping from our method and the warping function from DP performed using the raw data, $y_j,~j=1,2$; also from performing DP on the smoothed version of $y_j$. Figure~\ref{fig:multsim_SSE} presents a box plot for the SSE for all three methods. The SSE of the Bayesian method is similar to performing DP on the smoothed data. It should be noted that there is a larger spread in the inter-quartile region of the Bayesian method, and this is due to the fact that it is capturing multiple possible solutions that have different SSE values. Both of the DP solutions only find one solution, and this uncertainty (e.g., more than one registration) is not characterized in these methods. \begin{figure}[H] \centering \includegraphics[width=\textwidth]{multsim_SSE.png} \caption{Boxplot of the sum-of-squared errors for the Bayesian method compared to DP on the noisy data $y_j,~j=1,2$ (DP(y)) and DP on the smoothed noisy data (DP(f)).} \label{fig:multsim_SSE} \end{figure} Figure~\ref{fig:multsim_ex} presents four replicates from the simulated data with the median from the Bayesian posterior along with the posterior samples. The median of the posterior of $y_1$ and $y_2$ is shown respectively as $f_1$ and $f_2$. Additionally, the DP solutions for the noisy data (green) and the smoothed noisy data (blue). As expected the median of the Bayesian solution and the DP on the smoothed noisy data match nicely. However, the benefit of the Bayesian solution is shown in the posterior, where the multiple possible registrations are captured (with associated uncertainties) as the example as $f_1$ has two peaks and $f_2$ has one peak. \begin{figure}[H] \centering \begin{minipage}{\textwidth} \centering \includegraphics[width=.48\textwidth]{multsim_1.png}\quad \includegraphics[width=.48\textwidth]{multsim_3.png}\\ \includegraphics[width=.48\textwidth]{multsim_4.png}\quad \includegraphics[width=.48\textwidth]{multsim_7.png} \end{minipage} \caption{Four replicates from the simulated data showing the Bayesian alignment with the posterior in gray, also shown is the DP solution on both the noisy and smoothed noisy data.} \label{fig:multsim_ex} \end{figure} \subsection{SONAR data} \label{sec:sonar} Next, we apply our alignment approach to naturally noisy SONAR data collected at the Naval Surface Warfare Center Panama City Division's (NSWC PCD) test pond. For a description of the pond and measurement setup, the reader is referred to \cite{art:kargl}. In summary, the idea is to use the acoustic signals, generated from SONAR data, to discriminate and classify underwater ``targets'', e.g., unexploded ordnance. More precisely, acoustic signals were generated from the raw SONAR data to construct ``target strength" as a function of frequency and aspect angle. Due to the relatively small separation distances between the targets in the measurement setup and orientation, and uncertainty in the placement, the scattered fields from the targets overlap leading to misaligned signatures. This could lead to erroneous identification and classification of the target. For this example, we took two one-dimensional misaligned signatures, each with 1102 data samples, from a target that was a small notched aluminum cylinder. In our Bayesian approach, we ran 8 MCMC chains with 4,000 iterations each and a burn-in period of 2,000 steps without thinning; for a total of 16,000 samples. The proposal, prior, and hyperprior parameters were chosen such that acceptance rates were between 0.2 and 0.4 (see Figure \ref{fig:sonar_chains} for MCMC chains). We additionally specified $n_v=4$ Fourier basis functions to approximate $g$, as opposed to 8 in the previous example. We observed that reducing the number of basis functions $n_v$, allowed our HMC algorithm to more easily explore the posterior space of $g$; likely by allowing the inference to focus entirely on the lower frequency basis elements. Lastly, due to the noisiness of this data we only sampled $20\%$ of the data, instead of the full set of 1102 data points, in order to obtain smooth estimates of $f_1$ and $f_2$ and avoid overfitting. The posteriors $f_1|y_1$ and $f_2|y_2$ of the acoustic signatures from the SONAR data are shown in Figure \ref{fig:sonar_f1f2post} on the left (gray) and right (in orange and yellow). On the right, we compare the DP aligned solution (in blue) and the Bayesian aligned solution (in gray). Note that our Bayesian approach offers multiple possible alignments, one of which is similar to the DP approach, but another which more accurately matches the maximum peaks of $f_1$ and $f_2$. \begin{figure}[H] \centering \includegraphics[width=0.48\textwidth]{sonar_f1f2.png} \includegraphics[width=0.48\textwidth]{sonar_f2warped.png} \caption{Posteriors $f_1|y_1$ and $f_2|y_2$ shown in gray compared to the raw data $y_1$ and $y_2$ (left). The posterior of the warped function $(f_2 \circ \gamma)|y_1,y_2$ captures more possible alignments than the single DP warped solution in blue (right).}\label{fig:sonar_f1f2post} \end{figure} Figure \ref{fig:sonar_gampost} on the right panel compares the MAP estimates to the DP solution. Figure \ref{fig:sonar_gampost} on the left compares the DP solution to the posterior distribution of $\gamma|y_1,y_2$ and shows the posterior median and $95\%$ credible region of $\gamma|y_1, y_2$. The credible region quantifies the uncertainty around the estimated warping function $\gamma$ and thus the warped function $(f_2 \circ \gamma)$. Note that the credible region obtained from the Bayesian approach encapsulates the DP solution, which itself is not able to adequately account for the noise in the data. Subsequently, the uncertainty can be pushed through any later analyses for any quantity of interest that may depend on the aligned or warped functions. For example, any statistical moment calculations performed on the aligned functions, e.g., principal component analysis, can be modified to account for the uncertainty in the warping functions.\footnote{The most straightforward way to do this would be in Monte Carlo type fashion - compute the statistics for your quantity of interest (QoI) for each posterior sample $\gamma|y_1,y_2$, resulting in a histogram for the desired QoI.} \begin{figure}[H] \centering \includegraphics[width=0.48\textwidth]{sonar_gammaall.png} \includegraphics[width=0.49\textwidth]{sonar_f2warped_med.png} \caption{Comparison of the posterior distribution $\gamma|y_1,y_2$ to the DP solution $\gamma_{DP}$ applied to the SONAR data, plotting the two identified modes and respective 95\% credible regions of the posterior $\gamma|y_1,y_2$ (left). Comparison of the DP warping of $y_2$ and smoothed $y_2$ to the median of the warping $f_2 \circ \gamma|y_1,y_2$ (right).} \label{fig:sonar_gampost} \end{figure} \subsection{iPhone data} \label{sec:iphone} This data set consists of aerobic actions of subjects, such as biking, running, walking, etc., recorded using the Inertial Measurement Unit (IMU) on an Apple iPhone 4 smartphone; which these days is like using a cassette tape to listen to music. The IMU included a 3D accelerometer, gyroscope, and magnetometer. Each sample was taken at 60Hz, and manually trimmed to 500 samples (every 8.33s) to eliminate starting and stopping movements. For more information on the data set the reader is referred to \cite{mccall-reddy-shah}. We chose to demonstrate our method on two of forty-five functional samples from the walking accelerometer data in the $x$-direction. In this context, we are specifically interested in the information contained in the separated phase and amplitude components, rather than the resulting alignment. For example we are only interested in the amplitude variability of the acceleration in the $x$-direction. Comparing the functions after warping would allow us to consider this variability. The two examples we are aligning, shown in the right figure of Figure \ref{fig:iphone_f1f2post}, clearly have multiple possible alignments of $y_2$ to $y_1$ that we would like to also capture in the posterior $\gamma|y_1,y_2.$ To perform the Bayesian inference, we again ran 8 MCMC chains with 5,000 iterations each, a burn-in period of 1,000 steps, and thinning every other sample, for a total of 16,000 effective samples. The proposal, prior and hyperprior parameters were chosen such that acceptance rates were between 0.2 and 0.4 (see Figure \ref{fig:iphone_chains} for MCMC chains). We additionally specified $n_v=8$ Legendre basis functions to approximate $g.$ We specify Legendre polynomials here since the data is non-periodic in nature. The posteriors $f_1|y_1$ and $f_2|y_2$ can be seen in the left panel of Figure \ref{fig:iphone_f1f2post} along with $y_1$ and $y_2$ and the medians are shown in the right panel of Figure \ref{fig:iphone_gampost}. This image also compares the DP aligned solution $(y_2 \circ \gamma_{DP})$ to the posterior alignment of $f_2|y_2$, $(f_2 \circ \gamma) |y_1,y_2,$ from our Bayesian approach. It is clear that our Bayesian approach can capture multiple possible alignments, including alignments similar to the DP solution. For example, in addition to the alignment captured by the DP algorithm, the Bayesian approach also accounted for an alignment of $f_2$ to the leftmost peak of $f_1$. It is interesting to note here that the method didn't match $f_2$ to the rightmost peak of $f_1$. This would be caused by an extremely distorted warping function and the Fisher Rao metric natively guards against that by penalizing too high of a gradient. \begin{figure}[H] \centering \includegraphics[width=0.48\textwidth]{iphone_f1f2_legendre.png} \includegraphics[width=0.48\textwidth]{iphone_f2warped_legendre.png} \caption{Posteriors $f_1|y_1$ and $f_2|y_2$ shown in gray compared to the raw data $y_1$ and $y_2$ (left). The posterior of the warped function $(f_2 \circ \gamma)|y_1,y_2$ captures a more accurate alignment than the single DP warped solution in blue (right).} \label{fig:iphone_f1f2post} \end{figure} Figure \ref{fig:iphone_gampost} on the left compares the DP solution to the posterior distribution of $\gamma|y_1,y_2$ and shows the posterior median and $95\%$ credible region of $\gamma|y_1, y_2$. The credible region quantifies the uncertainty around the estimated warping function $\gamma$ and warped function $(f_2 \circ \gamma)$. The DP solution, obtained by trying to align the noisy data without prior data smoothing, is not built to account for the multiple possible alignments. \begin{figure}[H] \centering \includegraphics[width=0.48\textwidth]{iphone_gammaall_legendre.png} \includegraphics[width=0.48\textwidth]{iphone_f2warped_med.png} \caption{Comparison of the posterior distribution $\gamma|y_1,y_2$ to the DP solution $\gamma_{DP}$ applied to the iPhone data, plotting the two identified modes and respective 95\% credible regions of the posterior $\gamma|y_1,y_2$ (left). Comparison of the DP warping of $y_2$ to the median of the warping $f_2 \circ \gamma|y_1,y_2$ (right).} \label{fig:iphone_gampost} \end{figure} \section{Discussion}\label{sec:disc} We have proposed a new flexible Bayesian approach to functional alignment that handles measurement error and accounts for multiple optimal alignments in the posterior of the warping function $\gamma.$ We have demonstrated its advantages over the state-of-the-art Dynamic Programming method that has been used in recent alignment literature \cite{FSDA,srivastava2011,tucker2013} using both simulated and real datasets. Unlike DP, a Bayesian approach can characterize the uncertainty in the warping function solution $\gamma$, with Bayesian credible intervals. The hierarchical structure of our Bayesian method allows us to estimate measurement error observed in $y_1$ and $y_2$ and extract the mean functions $f_1$ and $f_2$ to be aligned, respectively. Accounting for measurement error directly in the method itself avoids any need for smoothing of the data typically done prior to applying DP in practice. Additionally, by running parallel MCMC chains, the posterior of the warping function $\gamma$ is able to capture all possible alignments and visualize the posterior modes and respective credible regions for one or more distinct alignments. Although existing Bayesian methods can account for uncertainty in the warping function, they are not able to find more than one possible alignment. This is because they focus on converging efficiently to one solution, and do not account for measurement uncertainty. Without accounting for all possible alignments, we are missing information; and not accounting for all uncertainty in $\gamma$. For future work, we look to extend the method to the multiple alignment problem. This will not be trivial in the case of multi-modal posteriors and multi-function alignment, as the solution will not be as simple as running multiple chains. The extension in our case would be the following: given $I$ functions you would construct $I$ pairwise alignments in Level 1 and Level 2 and then model the mean or template function using a Gaussian process prior and update. This processes would be somewhat similar to what was proposed in \cite{lu2017}. However, there lies the additional difficulty in sampling a model which can give multiple solutions. For some cases, each pairwise alignment to the template would produce multiple possible gamma functions. One would either need to determine which mode (e.g., \textit{optimal}) warping function to use or the uncertainty would need to be propagated to the sampling of the mean function. As noted in Cheng et al., \cite{cheng2016}, this template is only identifiable up to an equivalence class of warpings. The issue is more pronounced in the case of multiple alignments. The use of wormhole MCMC (\cite{lan2014}) or something similar would need to be explored and possibly used in this situation. Additionally, we can extend this from curves to trajectories that lie on Riemannian manifolds $\mathcal{M}$. In this case, one has to account for the non-zero curvature of the space and in particular, the calculation of the gradient in the Fisher Rao metric. \section*{Acknowledgment} This paper describes objective technical results and analysis. Any subjective views or opinions that might be expressed in the paper do not necessarily represent the views of the U.S. Department of Energy or the United States Government. This work was supported by the Laboratory Directed Research and Development program at Sandia National Laboratories; a multi-mission laboratory managed and operated by National Technology and Engineering Solutions of Sandia, LLC, a wholly owned subsidiary of Honeywell International, Inc., for the U.S. Department of Energy's National Nuclear Security Administration under contract DE-NA0003525.
{'timestamp': '2021-03-05T02:15:32', 'yymm': '2005', 'arxiv_id': '2005.14372', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14372'}
arxiv
\section{Introduction} In the past decade, progress in deep neural networks has resulted in the advancements in various computer vision tasks, such as image classification~\cite{alexnet, vgg, multicolumndnn, stochasticdepth}, object detection~\cite{frcnn, ssd}, and segmentation~\cite{maskrcnn}. The big success of deep neural networks is mainly contributed to the well-designed cells and sophisticated architectures. For example, VGGNet~\cite{vgg} suggested the use of smaller convolutional filters and stacked a series of convolution layers for achieving higher performance, ResNet~\cite{resnet} introduced the residual blocks to benefit the training of deeper neural networks, and DenseNet~\cite{densenet} designed the densely connected blocks to stack features from different depths. Besides the efforts on the initial architecture design, extensive experiments are often required to determine the weights and hyperparameters of the deep neural network. To automatically and efficiently search for neural networks of desireable properties (\emph{e.g.}, model size and FLOPs) from a predefined search space, a number of Neural Architecture Search (NAS) algorithms~\cite{darts, yang2019evaluation, li2020random, yu2019evaluating, nasbench101, nasbench201} have been recently proposed. Wherein, Evolutionary Algorithm (EA) based methods~\cite{amoebanet} maintain a set of architectures and generate new architectures using genetic operations like mutation and crossover. Reinforcement Learning (RL) based methods~\cite{zoph_rl_iclr, nasnet} sample architectures from the search space and train the controllers accordingly. The differentiable based methods~\cite{darts, fbnet, snas, metaarchitecturesearch} optimize the shared weights and architecture parameters, which significantly reduces the demand for computation resources and makes the search process efficient. \begin{figure*}[t] \centering \iffalse \subfigure[]{\label{fig_resnet}\includegraphics[height=5cm]{figs/fig_demo_multipathnetwork.png}} \subfigure[]{\label{fig_resnet_hourglass}\includegraphics[height=5cm]{figs/fig_hourglass.png}} \hspace{20pt} \subfigure[]{\label{fig_critical}\includegraphics[height=5cm]{figs/fig_critical.png}} \subfigure[]{\label{fig_minimal_supernet}\includegraphics[height=5cm]{figs/fig_demo_criticallayersearch.png}} \subfigure[]{\label{fig_non_critical_supernet}\includegraphics[height=5cm]{figs/fig_demo_noncriticallayersearch.png}} \subfigure[]{\label{fig_searched}\includegraphics[height=5cm]{figs/fig_demo_searched.png}} \subfigure{\label{fig_search_space}\includegraphics[width=0.7\linewidth]{figs/fig_demo_notations.png}} \fi \subfigure{\label{fig_search_space}\includegraphics[width=0.9\linewidth]{overall.png}} \caption{Blocks in the residual network are either ``vital'' or ``non-vital'', and they form the neck or bulb parts in the hourglass network. Two-stage search scheme speed up architecture search by 9$\times$ and the resource constrained search further accelerates architecture search by 72$\times$.} \label{fig_HourNAS} \vspace{-10pt} \end{figure*} These methods have made tremendous efforts to greatly accelerate the search process of NAS. Nevertheless, given the huge computation cost on the large-scale dataset~\cite{fbnet,sposnas,resourceconstrainednas,amc,onceforall}, \emph{e.g.}, 9 GPU days for NAS on the ImageNet benchmark, most methods execute NAS in a compromised way. The architecture is first searched on a smaller dataset (\emph{e.g.}, CIFAR-10 ~\cite{cifar}), and then the network weight of the derived architecture is trained on the large dataset. An obvious disadvantage of this concession is that the performance of the selected architecture on the CIFAR-10 may not be well extended to the ImageNet benchmark~\cite{undersandingrobustfyingnas}. We tend to use the minimal number of parameters without discrimination to construct an architecture that would achieve the maximal accuracy. But just as the popular 80-20 rule\footnote{{\color{black} The 80/20 rule (a.k.a Pareto principle, the law of vital few) is an aphorism that states, for many events, roughly 80\% of the effects come from 20\% of the causes.}} goes, only a few parts could be critical to the architecture's success, and we need to give them the most focus while balancing the parameter volume for other parts. In this paper, we propose HourNAS for an accurate and efficient architecture search on the large-scale ImageNet dataset. Blocks in an architecture are not created equally. Given all the possible paths for the information flow from the input to the output of the network, blocks shared by these paths are \emph{vital}, just as the neck of an hourglass to regulate the flow. We identify these vital blocks and make them the priority in the architecture search. The other non-vital blocks may not be critical to the accuracy of the architecture, but they often occupy the major volume of the architecture (like the bulb of an hourglass) and will carve up the resource budget left by the vital blocks. Instead of directly working in a large search space flooding with architectures that obviously do not comply with the constraints during deployment, we develop a space proposal method to screen out and optimize the most promising architecture candidates under the constraints. By treating the architecture search through an hourglass lens, the limited computation resource can be well allocated across vital and non-vital blocks. We design toy experiments on residual networks to illustrate the varied influence of vital and non-vital blocks on the network accuracy. The resulting HourNAS costs only about 3 hours~(0.1 GPU days) on the entire ImageNet dataset to achieve a 77.0\% Top-1 accuracy, which outperforms the state-of-the-art methods. \section{Related Works}\label{sec:relatedworks} This section reviews the methods for neural architecture search algorithms. Then, we discuss layer equality, \emph{i.e.}, the importance of different blocks in deep neural networks. \iffalse {\noindent \bf Efficient Network Design} In early age of deep learning, most widely used neural architectures are manually designed by human experts, \emph{e.g.}, VGG~\cite{vgg}, ResNet~\cite{resnet}, ~\cite{densenet}, and \emph{etc}. With the increasing demand for real-time applications on mobile or embedded devices, designing efficient neural networks has attracted more research interest. MobileNet serials~\cite{mobilenet, mobilenetv2} utilize the depthwise separable convolution and inverted residual block to construct efficient networks. ShuffleNet serials~\cite{shufflenet,shufflenetv2} employ pointwise group convolution and channel shuffle module to design computation-efficient models for mobile devices. Despite their strong performance, manually designed networks require a huge effort of human experts. \fi {\noindent \bf Neural Architecture Search.} To automate the design of neural models, neural architecture search (NAS) was introduced to discover efficient architectures with competitive performance. Reinforcement learning (RL) and evolution algorithm~(EA) were widely adopted in NAS~\cite{nasnet,zoph_rl_iclr,nsganet,amoebanet,mnasnet,sposnas,autogan}. However, these methods were highly computationally demanding. Many works have been devoted to improving the efficiency of NAS from different perspectives, \emph{e.g.}, by adopting the strategy of weight sharing~\cite{enas} or progressive search~\cite{pnas}. Differentiable based NAS attracted great interest as it drastically reduces the searching cost to several days or even hours~\cite{fbnet,darts,setnas,snas,autoreid,autodeeplab}. For example, DARTS~\cite{darts} adopted the continuous architecture representation to allow efficient architecture search via gradient descent. {\color{black} Meanwhile, as discusses in TuNAS~\cite{tunas}, gradient-based NAS methods consistently performed better than random search, showing the power of searching for excellent architectures. However, the most efficient gradient-based NAS methods still took dozens of days for directly searching on target large-scale dataset (\eg, ImageNet).} Thus, an efficient method for directly searching deep neural architectures on large-scale datasets and search spaces is urgently required. {\noindent \bf Layer Equality.} Most of existing NAS methods treated all layers with the same importance during the search. However, convolution neural networks are always over-parameterized and the impact on the final accuracy of each layer is totally different. Zhang \emph{et al.}~\cite{arealllayerscreatedequal} re-initialized and re-randomized the pre-trained networks, and found that some layers are robust to the disturbance. For some intermediate layers, the re-initialization and re-randomization steps did not have negative consequences on the accuracy. Veit \emph{et al.}~\cite{resnetensembles} decomposed residual networks and found that skipping some layers does not decrease the accuracy significantly. Ding \emph{et al.}~\cite{globalsparsemomentumsgd} pruned different layers separately and found some layers are more important to the final accuracy. It is obvious that the layers are not created equal, and some layers are more important than others. In this paper, we analyze the causes of the inequality phenomenon in the residual network and exploit this property in neural architecture search to improve its efficiency. \section{Hourglass Neural Architecture Search} In this section, we revisit the neural architecture search from an hourglass way. The vital few blocks should be searched with a higher priority to guarantee the potential accuracy of the architecture. The non-vital blocks that occupy the major volume are then searched in an extremely fast way by focusing on the discovered space proposals. \subsection{Vital Blocks: the Neck of Hourglass}\label{sec_notequal} In this paper, we focus on the serial-structure NAS SuperNet~\cite{mnasnet, efficientnet, fbnet, proxylessnas}, as it is hardware-friendly and capable of achieving superior performance. Before we illustrate vital blocks in a general NAS, we first take ResNet~\cite{resnet} as an example for the analysis. ResNet is one of the most popular manually designed architectures. It is established by stacking a series of residual blocks, and the residual block is defined as, \begin{equation} \mathbf{y} = \mathcal{F}(\mathbf{x}, \mathbf{w}) + \mathbf{x}, \label{eq_resnet} \end{equation} where $\mathbf{x}$ is the input feature map, $\mathcal{F}$ denotes the transformation (\emph{e.g.}, convolution and batch normalization for vision tasks) and $\mathbf{w}$ stands for the trainable parameters.\footnote{As for the downsample blocks (reduce the feature map size) and the channel expansion blocks (increase the channel number), we follow~\cite{resnetensembles} and use $\mathbf{y} = \mathcal{F}(\mathbf{x}, \mathbf{w})$ to express.} From the information flow perspective, there are two paths to transmit the information from the node $\mathbf{x}$ to the node $\mathbf{y}$, \emph{i.e.}, the shortcut connection and the transformation $\mathcal{F}$. If there are $m$ residual blocks in a network, there will be $2^m$ different paths for the information propagation in total. A general neural network $\mathcal{N}$ based on the residual blocks~\cite{resnet, mnasnet, fbnet} can therefore be approximated as the ensemble of a number of paths~\cite{resnetensembles} $\{\mathcal{P}_1, \dots, \mathcal{P}_n\}$, \emph{i.e.}, $\mathcal{N}(X) \approx \sum_{i=1}^{n} \mathcal{P}_i (X)$, where each path $\mathcal{P}_i$ is set up by a series of blocks, $X$ is the input data, and $n$ is the number of all the paths. It is worth noticing that there are a few blocks existing in all the possible paths, \emph{e.g.}, the gray blocks in Fig.~\ref{fig_HourNAS}. These self-contained blocks do not participate in forming any residual blocks, but they are \emph{vital}, because of their appearance in every path from the input to the output of the network. On the other hand, the green and blue blocks in Fig.~\ref{fig_HourNAS} are a part of the residual blocks $\mathbf{y} = \mathcal{F}(\mathbf{x}, \mathbf{w}) + \mathbf{x}$, where the information can be transmitted through the plain transformation $\mathcal{F}(\mathbf{x}, \mathbf{w})$ or the shortcut connection $\mathbf{x}$ to the next block, {\color{black} so they are not that vital}. {\color{black} \noindent \textbf{Identify and Examine Vital Blocks.}} Given the paths $\{\mathcal{P}_1, \dots, \mathcal{P}_n\}$ in a general residual network $\mathcal{N}$, the vital blocks shared by all the paths can be identified through $\hat{\mathcal{P}} = \mathcal{P}_1 \cap \dots \cap \mathcal{P}_n$, where $\mathcal{P}_i \cap \mathcal{P}_j$ denotes the intersection set of those blocks in paths $\mathcal{P}_i$ and $\mathcal{P}_j$. In the popular residual networks, such as ResNet~\cite{resnet} and FBNet~\cite{fbnet}, the vital blocks are exactly the first convolution layer, the last fully connected layer, the downsampling blocks, and the channel expansion blocks. These vital blocks are critical to the accuracy of the whole architecture, as they exist in all paths and act as the neck of the hourglass to control the information flow. In contrast, the other blocks would always find substitutes for themselves to keep the information flow, and they thus play a secondary role in the whole architecture. We further take mobile architectures as an example to illustrate the different influence of vital and non-vital blocks on the network accuracy. A random mask function $\mathcal{M}(\mathbf{y}, p)$ is introduced to destroy the output of blocks in the pretrained MnasNet~\cite{mnasnet} and MobileNetV2~\cite{mobilenetv2}, where $\mathbf{y}$ is the output feature map, and $0\le p\le 1$ is the probability. In particular, every channel is reset to 0 with a probability $p$. \begin{figure} \centering \subfigure[MnasNet]{\includegraphics[width=0.48\linewidth]{mnasnet_importance.pdf}} \subfigure[MobileNetV2]{\includegraphics[width=0.48\linewidth]{mobilenet_importance.pdf}} \caption{The diagram of block importance by using the MnasNet and MobileNetV2 pretrained models.} \label{fig_block_importance} \vspace{-15pt} \end{figure} Fig.~\ref{fig_block_importance} shows the accuracy change of MnasNet~\cite{mnasnet} and MobileNetV2~\cite{mobilenetv2} resulting from the feature distortion on different blocks. {\color{black} The $blocki\_j$ denotes the $j$-th block in the $i$-th stage. As discussed above, the first block in every stage is the vital block}. We set $p = \{0.3, 0.6, 1.0\}$ to gradually increase the degree of feature distortion. Each time we only manipulate one block while keeping others unchanged in the network. For the non-vital blocks (\emph{e.g.}, {\color{black}block3\_2 and block3\_3 in both MnasNet and MobileNetV2}), even if all the channels are reset to zero (\emph{i.e.}, p=1.0), the network does not undergo a significant accuracy degradation. However, a small portion (p=0.3) of channels that are masked out for those vital blocks ({\color{black}\emph{e.g.}, block1\_1 and block2\_1}) will lead to an obvious accuracy drop. \iffalse {\color{black} \noindent \textbf {Theoretical Analysis of Vital blocks.} In this part, we try to analyze why some layers play a more vital role by analyzing the rank. The rank in the feature represents the richness of information, and also represents the distinctiveness~\cite{yang2017breaking}. We start by considering two transformations, \begin{equation} \begin{aligned} y_1 &= \mathcal{F}(w \otimes x),\\ y_2 &= \mathcal{F}(w \otimes x) + x, \end{aligned} \end{equation} where $\mathcal{F}$ is the non-linear transformation, $\otimes$ is the matrix multiplication and $x$, $y$ are the input and output, respectively. The ranks of the outputs are: \begin{equation} \begin{aligned} rank(y_1) &\le \min\{rank(w), rank(x)\}, \\ rank(y_2) &\le \min\{rank(w), rank(x)\} + rank(x). \end{aligned} \end{equation} Adding the identity mapping makes $y_2$ capable of containing much more information, and the high rank feature maps are critical to the final performance~\cite{hrank}. The non-vital blocks and the vital blocks act like $y_2$ and $y_1$, respectively. For example, removing the learned transformation $\mathcal{F}$ of these transformations does not affect much to the whole network as Fig.~\ref{fig_block_importance} shows because the information could be preserved from the shortcut. For the transformation $y_1 = \mathcal{F}(w \otimes x)$, this is how downsampling blocks transform features, the quality of the transformation $\mathcal{F}$ itself determines the information preservation. } \fi {\color{black} \noindent \textbf{Revisit Neural Architecture Search.}} The goal of NAS is to search for the architecture of a higher accuracy under the constraints of available computational resources. In other words, NAS can be regarded as a problem of resource allocation. Vital blocks are potentially the most important and need to be put as the priority. As a result, more resources are better to be first allocated to the vital blocks, and the remaining resources are used for the non-vital blocks design. This therefore naturally motivates us to develop a two-stage search algorithm. During the first stage, we construct the minimal SuperNet $\mathcal{S}_{vital}$ {\color{black} by stacking all the vital layers and} search the vital blocks. {\color{black} The weights and architecture parameters are optimized alternatively in a differentiable way~\cite{fbnet}.} In the second stage, we fix the derived architecture of those vital blocks, and allocate the computational resources to search for the non-vital blocks. \subsection{Non-Vital Blocks: the Bulb of Hourglass} Non-vital blocks are often composed of a large number of parameters. They look like the bulb of the hourglass to determine the whole volume size. If the computational resources are unlimited to deploy the neural network, then we can make the network wider and deeper for achieving a higher performance~\cite{resnet, efficientnet}. However, the searched architectures are to be deployed on mobile devices which have demanding constraints of the resources, \emph{e.g.}, model size, and FLOPs. Without investigating these constraints, it would be ineffective to directly sample the architecture from a large search space. For example, if the sampled architectures cannot fully use the available computation resource, the resulting models might perform poorer than expected, which has been analyzed by a number of multi-objective NAS works~\cite{nsganet, cars, lemonade, mnasnet} (the Pareto front). Otherwise, if the sampled architectures overwhelm the use of computation resources, they would be difficult to be deployed. To tackle the dilemma, we introduce an efficient sampling operation to {\color{black} avoid wasting too much time on search unimportant operations}, and a space proposal strategy to put more attention on {\color{black} architectures that meet the target computational resources}. \subsection{Space Proposal for Efficient Resource Constrained Search} \label{sec_space_proposal} A general differentiable neural architecture search algorithm can be formulated as a bilevel optimization problem~\cite{darts}: \begin{equation} \begin{aligned} \theta^* &= \mathop{\mathrm{\arg\min}}_{\theta} \mathcal{H}_{val}(w^*(\theta), \theta),\\ \textnormal{s.t.} &~~ w^*(\theta) = \mathop{\mathrm{\arg\min}}_{w} \mathcal{H}_{train}(w, \theta), \end{aligned} \end{equation} where $\mathcal{H}$ is the cross-entropy loss function, and $\theta$ denotes the architecture parameters. If the accuracy is the only objective to be considered for searching, a complex architecture would be preferred for achieving a highest accuracy (see Sec.~\ref{sec_ablation}). However, if the obtained architectures are to be deployed on mobile devices, we may always have the computational resource constraints from the environment . Thus, neural architecture search that considers the multiple objectives can be formulated as, \begin{equation} \begin{aligned} \theta^* &= \mathop{\mathrm{\arg\min}}_{\theta} \mathcal{H}_{val}(w^*(\theta), \theta) + \alpha \times \mathcal{T}(\theta),\\ \textnormal{s.t.} &~~ w^*(\theta) = \mathop{\mathrm{\arg\min}}_{w} \mathcal{H}_{train}(w, \theta), \end{aligned} \end{equation} where $\mathcal{T}(\theta)$ is the regularization term that encourages the produced architecture to satisfy the target computational resource constraints. Assuming the constraints~(targets) on computational resources (\eg, model size, FLOPs) are $T_{i \in \{1, \dots, n\}}$, where $n$ is the number of objectives, an efficient and controllable way is to initialize architectures that satisfy $T$. Thus, we introduce the concept of space proposal. The space proposal is a subspace of the large search space, and all the sampled architectures from the space proposal satisfy the target resources. As a result, the search phase would not waste resources on optimizing useless architectures. In addition, the space proposal ensures ``what you set is what you get''. Similar to gradient-based NAS, the space proposal is represented by the architecture parameters. We take the FLOPs as an example to describe how to optimize a space proposal. Suppose $\theta$ represents the trainable architecture parameters of the NAS SuperNet and the size is $L\times O$, where $L$ is the maximum depth and $O$ is the number of candidate operations {\color{black} in each layer}. A number of methods $\mathcal{G}$ are capable of sampling architectures $A_{\theta}$ from architecture parameters $\theta$, \begin{equation} A_{\theta} = \mathcal{G}(\theta),~~\sum_{o} A_{l,o} = 1, \label{eq_sample} \end{equation} where $\mathcal{G}$ is usually specified as softmax~\cite{darts}, Gumbel-softmax~\cite{fbnet}, Gumbel-Max~\cite{gdas,data}, \emph{etc}. The $A_{l,o}$ is the $o$-th operation in the $l$-th layer. The FLOPs table $F$ of the SuperNet $\mathcal{S}$ is of size $L \times O$, where $F_{l, o}$ denotes the FLOPs of the $o$-th operation in the $l$-th SuperBlock. The FLOPs for sampled architecture $A_\theta$ is calculated as $\mathcal{R}_{F}(A_\theta) = \textnormal{sum} (A_\theta \odot F)$, where $\odot$ is the element-wise product. Assuming the target FLOPs is $T_{F}$, the optimization is formulated as, \begin{equation} \theta^F = \mathop{\mathrm{\arg\min}}_{\theta} | \mathcal{R}_{F}(\mathcal{G}(\theta)) - T_{F} | / M_{F}, \label{eq_clock_loss_flops} \end{equation} where $M_{F}$ is a constant scalar denotes the maximum FLOPs of the sampled architectures, and this term is used for normalizing the objective to $[0, 1]$. We extend Eqn~\ref{eq_clock_loss_flops} to $n$ different objectives. The targets for $n$ objectives are $T_{i \in \{1, \dots, n\}}$, and the optimization is defined as, \begin{equation} \theta^T = \mathop{\mathrm{\arg\min}}_{\theta} \frac{1}{n}\sum_{i=1}^n | \mathcal{R}_i (\mathcal{G}(\theta)) - T_i | / M_i, \label{eq_clock_loss} \end{equation} which $\mathcal{R}_i (\mathcal{G}(\theta))$ is the resource demand of the architecture sampled by $\mathcal{G}(\theta)$ on the $i$-th objective. This optimization problem is easily to be solved in a few seconds. The solution $\theta^T$ can be regarded as a space proposal under the constraints $T$, and the structure $A_{\theta^T}$ sampled from $\theta^{T}$ by Eqn~\ref{eq_sample} would be more easily to satisfiy target resources $T$. Instead of relying on a single optimal solution $\theta^T$, we turn to an ensemble way to start from different random initializations and derive a series of space proposals $\Theta^{T} = \{ \theta^{T}_1, \cdots, \theta^{T}_m \}$, where $m$ is the number of space proposals. The orthogonal constraint is also introduced to further increase the diversity of different space proposals, which is formulated as, \ \begin{equation} \begin{aligned} \theta_1, \dots, \theta_m = \mathop{\arg\min}_{\theta_1, \dots, \theta_m} (\frac{1}{nm}&\sum_{j=1}^m \sum_{i=1}^n |\mathcal{R}_i(\mathcal{G}(\theta_j)) - T_i| / M_i + \\ &\beta \times \sum (|O - I|)), \end{aligned} \label{eq_regularization_loss} \end{equation} where $O = \Theta\Theta^T$ is an $m\times m$ matrix and element $O_{i, j}$ denotes the inner product of $\theta_i$ and $\theta_j$. The term $\sum(|O-I|)$ regularizes $m$ space proposals to be orthogonal, which indicates that the architectures sampled from different space proposals are different. A uniformly initialized auxiliary parameter $\Pi$ of size $m$ is then introduced to sample space proposals, \ \begin{equation} \pi = \mathcal{P}(\Pi),~~\sum_i \pi_i = 1, \label{eq_pi} \end{equation} where $\mathcal{P}$ could be softmax, Gumbel-softmax or Gumbel-Max, $\pi$ is the sampled vector from $\Pi$ that used for combine the architectures sampled from $m$ space proposals, and the ensembled architecture $A_{\Theta}$ that used for updating the SuperNet is defined as, \ \begin{equation} A_{\Theta} = \sum_{i} \pi_i \cdot A_{\theta_i} = \sum_{i} \pi_{i} \cdot \mathcal{G}(\theta_i), \end{equation} where $A_{\Theta}$ is utilized for updating network parameter $w$ on train set $\mathcal{D}_{train}$ and architecture parameter $\Pi, \Theta$ on validation set $\mathcal{D}_{val}$, respectively. Every space proposal $\theta_i$ optimizes towards the good architectures in the space proposal and $\Pi$ optimizes towards better proposals. The NAS framework by using the space proposal strategy is summarized as, \ \begin{equation} \begin{aligned} \Pi^*, \Theta^* &= \mathop{\mathrm{\arg\min}}_{\Pi, \Theta} \mathcal{H}_{val}(w^*(\Pi, \Theta), \Pi, \Theta) + \alpha \times \mathcal{T}(\Pi, \Theta), \\ \textnormal{s.t.} &~~ w^*(\Pi, \Theta) = \mathop{\mathrm{\arg\min}}_{w} \mathcal{H}_{train}(w, \Pi, \Theta), \end{aligned} \end{equation} where $\mathcal{T}$ (Eqn~\ref{eq_clock_loss}) is the regularization on space proposal parameters (Eqn~\ref{eq_regularization_loss}), and $\alpha$ is the slope of the multi-objective loss term. \subsection{Overall Search Algorithm} {\color{black} Based on the proposed method, we summarize the overall search algorithm in Alg.~\ref{alg_fnas}.} \begin{algorithm}[h] \caption{The searching algorithm of HourNAS.} \begin{algorithmic}[1] \REQUIRE The NAS supernet $\mathcal{S}$, the computational targets $T_{i \in \{1, \dots, n\}}$, the train set $D_{train}$ and validation set $D_{val}$, the searching epochs for vital blocks $E_{vital}$ and non-vital blocks $E_{n-vital}$, the number of space proposals $m$, iterations $I_{sp}$ for training space proposals. \STATE \textbf{// Search Vital Blocks} \STATE Constructing the minimal SuperNet $\mathcal{S}_{vital}$ {\color{black} by stacking all the vital layers} and the architecture parameter $\theta_{vital}$. \FOR{e = 1 to $E_{vital}$} \FOR{data and target pair $(X_{tr}, Y_{tr})$ in $D_{train}$} \STATE Sample network $A$ from $\theta_{vital}$, calculate loss and update network parameters. \ENDFOR \FOR{data and target pair $(X_{val}, Y_{val})$ in $D_{val}$} \STATE Sample network $A$ from $\theta_{vital}$, calculate loss and update $\theta_{vital}$. \ENDFOR \ENDFOR \STATE The operations with the highest importance are selected to form the vital layers. \STATE \textbf{// Optimize $m$ space proposals} \STATE According to the computational targets $T$, HourNAS optimizes $m$ proposals $\Theta^{T} = \{ \theta^{T}_1, \cdots, \theta^{T}_m \}$ for $I_{sp}$ iterations (Eqn~\ref{eq_regularization_loss}), and construct the proposal sampler $\pi$~(Eqn~\ref{eq_pi}). \STATE \textbf{// Search Non-Vital Blocks} \FOR{e = 1 to $E_{n-vital}$} \FOR{data and target pair $(X_{tr}, Y_{tr})$ in $D_{train}$} \STATE Sample network $A$ from $\pi$ and $\Theta$, calculate loss and update network parameters. \ENDFOR \FOR{data and target pair $(X_{val}, Y_{val})$ in $D_{val}$} \STATE Sample network $A$ from $\pi$ and $\Theta$, calculate loss and update $\pi$ and $\Theta$. \ENDFOR \ENDFOR \STATE Fix operations by selecting the space proposal and operations with the highest probability. \ENSURE The architecture $A$ which satisfies the computational targets $T_{i \in \{1, \dots, n\}}$. \end{algorithmic} \label{alg_fnas} \end{algorithm} \section{Experiments}\label{sec:exp} In this section, we first describe the experimental settings and then extensively evaluate the proposed HourNAS on several popular NAS search spaces~\cite{fbnet, mnasnet, efficientnet} on ImageNet. \subsection{Experimental Settings} We use the HourNAS to search on the complete ImageNet train set. The subset $\mathcal{D}_{tr}$ takes $80\%$ of the train set to train network parameters and the rest $\mathcal{D}_{val}$ is used to update architecture parameters. We search on three popular search spaces, \ie, FBNet~\cite{fbnet}, MnasNet~\cite{mnasnet}, and EfficientNet~\cite{efficientnet}. For any of our searched architecture, the training strategy is the same as the corresponding baseline. {\color{black} We use the NVIDIA V100 GPU to measure the search time and compare with previous works fairly. The V100 GPU is also adopted by a number of literatures, for example, PDARTS~\cite{pdarts}, FBNet~\cite{fbnet}.} The HourNAS first searches the vital blocks for one epoch~(about 1 hour). Then, HourNAS optimizes multiple space proposals according to the computational targets and searches the non-vital blocks for one epoch~(about 2 hours). The whole searching process requires only one V100 GPU within 3 hours. Extending the search time will not further improve the accuracy, because the distribution of architecture parameters is stable. For competing methods like MnasNet~\cite{mnasnet}, 3 GPU hours could only train one sampled architecture and the RL controller has no difference with random search. We utilize the Gumbel-Max~\cite{astarsampling, data, gdas} to sample operations according to the learned importance, which avoids wasting searching time on undesired operations. Gumbel-Max samples an operation according to the learned probability distribution (\emph{i.e.}, importance). The sampling frequencies of those poor operations tend to be relatively low, so that we can effectively reduce the time spent on them. The Gumbel-Max sampling accelerates every iteration by around $O$ times, where $O$ is the number of candidate operations in every layer. During searching, we follow FBNet~\cite{fbnet} and add the temperature $\tau$ (Eqn~\ref{eq_sample}) for sharpening the distribution progressively. The temperature $\tau$ starts from 5.0 and multiply 0.9999 at every iteration. Slope parameter $\alpha$, $\beta$ are emperically set to 5.0 and 1e-2, respectively. Learning rates for optimizing weights and architecture parameters are 0.1 and 0.01, respectively. Adam~\cite{adam} optimizer is used to update architecture parameters. \begin{table*} \caption{Overall comparison on the ILSVRC2012 dataset.} \small \centering \begin{tabular}{c|c|c|c|c|c|c|c} \toprule \multirow{2}{*}{{Model}} & \multirow{2}{*}{{Type}} & Search & Search Cost & Params & FLOPS & Top-1 & Top-5 \\ & & Dataset & (GPU days) & (M) & (M) & (\%) & (\%) \\ \midrule ResNet50~\cite{resnet} & manual & - & - & 25.6 & 4100 & 75.3 & 92.2 \\ MobileNetV1~\cite{mobilenet} & manual & - & - & 4.2 & 575 & 70.6 & 89.5 \\ MobileNetV2~\cite{mobilenetv2} & manual & - & - & 3.4 & 300 & 72.0 & 91.0 \\ MobileNetV2~(1.4$\times$) & manual & - & - & 6.9 & 585 & 74.7 & 92.5 \\ ShuffleNetV2~\cite{shufflenetv2} & manual & - & - & - & 299 & 72.6 & - \\ ShuffleNetV2~(1.5$\times$) & manual & - & - & 3.5 & 299 & 72.6 & - \\ \midrule FPNASNet~\cite{fpnas} & auto & CIFAR-10 & 0.8 & 3.4 & 300 & 73.3 & - \\ SNAS~(mild)~\cite{snas} & auto & CIFAR-10 & 1.5 & 4.3 & 522 & 72.7 & 90.8\\ AmoebaNet-A~\cite{amoebanet} & auto & CIFAR-10 & 3150 & 5.1 & 555 & 74.5 & 92.0 \\ PDARTS~\cite{pdarts} & auto & CIFAR-10 & 0.3 & 4.9 & 557 & 75.6 & 92.6 \\ NASNet-A~\cite{nasnet} & auto & CIFAR-10 & 1800 & 5.3 & 564 & 74.0 & 91.3 \\ GDAS~\cite{gdas} & auto & CIFAR-10 & 0.2 & 5.3 & 581 & 74.0 & 91.5 \\ PNAS~\cite{pnas} & auto & CIFAR-10 & 225 & 5.1 & 588 & 74.2 & 91.9 \\ CARS-I~\cite{cars} & auto & CIFAR-10 & 0.4 & 5.1 & 591 & 75.2 & 92.5 \\ DARTS~\cite{darts} & auto & CIFAR-10 & 4 & 4.9 & 595 & 73.1 & 91.0 \\ MdeNAS~\cite{mdenas} & auto & CIFAR-10 & 0.2 & 6.1 & - & 74.5 & 92.1 \\ RCNet~\cite{resourceconstrainednas} & auto & ImageNet & 8 & 3.4 & 294 & 72.2 & 91.0 \\ SPOSNAS~\cite{sposnas} & auto & ImageNet & 13 & 5.3 & 465 & 74.8 & - \\ ProxylessNAS~\cite{proxylessnas} & auto & ImageNet & 8.3 & 7.1 & 465 & 75.1 & 92.5 \\ \midrule FBNet-B~\cite{fbnet} & auto & ImageNet & 9 & 4.8 & 295 & 74.1 & - \\ FBNet-C~\cite{fbnet} & auto & ImageNet & 9 & 5.5 & 375 & 74.9 & - \\ \textbf{HourNAS-FBNetSS-A} & auto & ImageNet & \textbf{0.1} & 4.8 & 298 & \textbf{74.1} & \textbf{91.8} \\ \textbf{HourNAS-FBNetSS-B} & auto & ImageNet & \textbf{0.1} & 5.5 & 406 & \textbf{75.0} & \textbf{92.2} \\ \midrule \textbf{HourNAS-EFBNetSS-C} & auto & ImageNet & \textbf{0.1} & 4.8 & 296 & \textbf{74.1} & \textbf{91.6} \\ \textbf{HourNAS-EFBNetSS-D} & auto & ImageNet & \textbf{0.1} & 5.5 & 394 & \textbf{75.3} & \textbf{92.3} \\ \midrule MnasNet-A1~\cite{mnasnet} & auto & ImageNet & 3800 & 3.9 & 312 & 75.2 & 92.5 \\ \textbf{HourNAS-MnasNetSS-E} & auto & ImageNet & \textbf{0.1} & 3.8 & 313 & \textbf{75.7} & \textbf{92.8} \\ \midrule EfficientNet-B0~\cite{efficientnet} & auto & ImageNet & - & 5.3 & 390 & 76.8 & - \\ \textbf{HourNAS-EfficientNetSS-F} & auto & ImageNet & \textbf{0.1} & 5.3 & 383 & \textbf{77.0} & \textbf{93.5} \\ \bottomrule \end{tabular} \label{tab_imagenet} \end{table*} \subsection{Comparison with State-of-the-arts} \textbf{FBNet Search Space (FBNetSS).} We first evaluate our HourNAS on the popular FBNet search space (FBNetSS), {\color{black} which contains $9^{22} \approx 1\times 10^{21}$ architectures}. HourNAS first searches the vital blocks and the results show that operations with the expansion ratio of six have significantly higher probabilities than other operations. We choose the operations with the highest probabilities to form the vital blocks. This result is in line with our intuition that the complex operations have the greatest feature extraction ability on the large dataset, \emph{i.e.}, ImageNet. After fixing the operations of the vital blocks, we are interested in finding the appropriate proposal number $m$. We set the computational resources the same as FBNet-B and search architectures using $m$ different space proposals. We first visualize the distribution of sampled architectures from the space proposal by gradually decreasing the temperature $\tau$. Each space proposal is optimized for 1000 iterations in total (Eqn~\ref{eq_clock_loss}). The computational targets are set to 4.8M parameters (x-axis) and 300M FLOPs (y-axis), which are consistent with FBNet-B~\cite{fbnet}. As shown in Fig.~\ref{fig_vis_space_proposal}, with the decrease of temperature of $\tau$, the sampled architectures satisfy the computational targets more precisely. \iffalse \begin{figure}[H] \centering \subfigure[$\tau=5.0$]{\includegraphics[width=0.2\linewidth]{figs/proposals/5.png}} \hspace{10pt} \subfigure[$\tau=1.0$]{\includegraphics[width=0.2\linewidth]{figs/proposals/1.png}} \hspace{10pt} \subfigure[$\tau=0.5$]{\includegraphics[width=0.2\linewidth]{figs/proposals/05.png}} \hspace{10pt} \subfigure[$\tau=0.1$]{\includegraphics[width=0.2\linewidth]{figs/proposals/01.png}} \caption{The distribution of 10,000 architectures sampled from optimized space proposal under different temperatures $\tau$.} \label{fig_vis_space_proposal} \end{figure} \fi \begin{figure} \centering \subfigure[$\tau=5.0$]{\includegraphics[width=0.24\linewidth]{5.png}} \subfigure[$\tau=1.0$]{\includegraphics[width=0.24\linewidth]{1.png}} \subfigure[$\tau=0.5$]{\includegraphics[width=0.24\linewidth]{05.png}} \subfigure[$\tau=0.1$]{\includegraphics[width=0.24\linewidth]{01.png}} \caption{The distribution of 10,000 architectures sampled from optimized space proposal under different temperatures $\tau$.} \label{fig_vis_space_proposal} \vspace{-10pt} \end{figure} The optimization step for constructing several space proposals takes only a few seconds, which is an efficient solution for controllable multi-objective neural architecture search. We enumerate $m= \{1, 2, 4, 8, 16\}$ and the operations with the highest probability according to $\Pi$ and $\Theta$ are selected after searching. The architectures are evaluated on the CIFAR-10 dataset to determine the appropriate space proposal number $m$ for finding superior architectures. {\color{black} In retraining, we integrate CutOut~\cite{cutout} to make networks generalize better.} As shown in Tab.~\ref{tab_appropriate_m}, $m=8$ could result in a well-performed architecture and we use $m=8$ in the following experiments to achieve a better trade-off between searching costs and performance. \begin{table}[H] \caption{Comparison of image classifiers on CIFAR-10 dataset.} \small \centering \begin{tabular}{l|c|c|c} \toprule \multirow{2}{*}{{Model}} & Test Error & {Params} & Search Cost \\ & (\%) & (M) & (GPU days) \\ \midrule HourNAS~(m=1) & 3.86 & 2.8 & 0.1 \\ HourNAS~(m=2) & 3.54 & 2.8 & 0.1 \\ HourNAS~(m=4) & 3.41 & 2.7 & 0.1 \\ HourNAS~(m=8) & 3.39 & 2.8 & 0.1 \\ HourNAS~(m=16) & 3.37 & 2.8 & 0.1 \\ \bottomrule \end{tabular} \label{tab_appropriate_m} \vspace{-15pt} \end{table} We search for models on the ImageNet dataset, \ie, HourNAS-FBNetSS-A and HourNAS-FBNetSS-B. To fairly compare with FBNet, HourNAS-FBNetSS-A has the same model size and FLOPs as FBNet-B, and HourNAS-FBNetSS-B has the same computational requirements as FBNet-C. {\color{black} We train the networks for 350 epochs in total with a batch size of 512. Learning rate starts from 0.25 and the weight decay is 1e-5. Label smoothing and learning rate warmup strategies are also used. The activation after convolution is the ReLU function.} The training strategy is the same as FBNet~\cite{fbnet} without using bells and whistles. As shown in Tab.~\ref{tab_imagenet}, the HourNAS-FBNetSS-A and HourNAS-FBNetSS-B achieve competitive accuracies with FBNet-B and FBNet-C, and the search time is drastically reduced by two orders of magnitude. We search HourNAS-FBNetSS-A for three times using different random seeds, and the standard deviation of Top-1 accuracy is 0.1\%. \textbf{Enlarged FBNet Search Space (EFBNetSS).} MixConv~\cite{mixconv} indicates that a larger kernel size leads to better performance. To understand the impact of search space and to further verify the effectiveness of HourNAS, we slightly enlarge the search space of FBNet. We add the blocks with kernel size $k=7$ and remove the blocks with group $g=2$. {\color{black} This modification results in a search space containing $1\times 10^{22}$ architectures, which is 10 times larger than the original one.} The multi-objectives are the same as HourNAS-FBNetSS-A and HourNAS-FBNetSS-B. We list the searched architectures in Tab.~\ref{tab_imagenet}. The HourNAS-EFBNetSS-C achieves the same Top-1 accuracy with HourNAS-FBNetSS-A and HourNAS-EFBNetSS-D surpasses HourNAS-FBNetSS-B by 0.3\% Top-1 accuracy. The larger kernel size $k=7$ ensures that the architectures are capable of perceiving the characteristics of a larger area. \begin{table*} \caption{The results of FBNet-Max and EfficientNet-Max on ILSVRC2012 dataset.} \centering \small \begin{tabular}{c|c|c|c|c} \toprule {Model} & Params (M) & FLOPS (M) & Top-1 (\%) & Top-5 (\%) \\ \midrule FBNet-Max & 5.7 & 583 & 75.7 & 92.8 \\ \midrule EfficientNet-Max & 5.8 & 738 & {78.3} & {94.0} \\ \bottomrule \end{tabular} \label{tab_full} \vspace{10pt} \caption{Comparisons of searching with and without vital block priori on ILSVRC2012 dataset. The search spaces are original (upper) and enlarged (lower) FBNet search space, respectively.} \centering \small \begin{tabular}{c|c|c|c|c|c|c|c} \toprule \multirow{2}{*}{{Model}} & \multirow{2}{*}{{Type}} & Search & Search Cost & Params & FLOPS & Top-1 & Top-5 \\ & & Dataset & (GPU days) & (M) & (M) & (\%) & (\%) \\ \midrule \textbf{HourNAS-FBNetSS-A} & auto & ImageNet & \textbf{0.1} & 4.8 & 298 & \textbf{74.1} & \textbf{91.8} \\ {HourNAS-FBNetSS-G}~(w/o vital block priori) & auto & ImageNet & {0.2} & 4.7 & 297 & 73.2 & 91.4 \\ \midrule \textbf{HourNAS-EFBNetSS-D} & auto & ImageNet & \textbf{0.1} & 4.8 & 296 & \textbf{74.1} & \textbf{91.6} \\ {HourNAS-EFBNetSS-H}~(w/o vital block priori) & auto & ImageNet & {0.2} & 4.8 & 299 & {73.5} & {91.3} \\ \bottomrule \end{tabular} \label{tab_vital_priori} \vspace{10pt} \caption{The results comparison on ILSVRC2012 dataset. } \centering \small \begin{tabular}{c|c|c|c|c|c|c|c} \toprule \multirow{2}{*}{{Model}} & \multirow{2}{*}{{Type}} & Search & Search Cost & Params & FLOPS & Top-1 & Top-5 \\ & & Dataset & (GPU days) & (M) & (M) & (\%) & (\%) \\ \midrule {HourNAS-FBNetSS-A} & auto & ImageNet & {0.1} & 4.8 & 298 & {74.1} & {91.8} \\ {HourNAS-FBNetSS-I} & auto & ImageNet & 1.0 & 4.8 & 318 & 74.2 & 91.8 \\ \bottomrule \end{tabular} \label{tab_gumbel} \vspace{-15pt} \end{table*} \textbf{MnasNet Search Space (MnasNetSS).} We further apply our proposed HourNAS to the search space of MnasNet~\cite{mnasnet}. {\color{black} The search space contains $2.5 \times 10^{23}$ architectures in total and is larger than FBNet search space.} We select MnasNet-A1 as the baseline and use its number of the parameters and FLOPs as two objectives to optimize 8 space proposals. The discovered HourNAS-MnasNetSS-E achieves a Top-1 accuracy of 75.7\% on the ILSVRC2012 dataset, which surpasses MnasNet-A1 by 0.5\%. \textbf{EfficientNet Search Space (EfficientNetSS).} To compare with the state-of-the-art architecture EfficientNet-B0~\cite{efficientnet}, we also use HourNAS to search on the same search space as EfficientNet, which {\color{black} contains $4 \times 10^{18}$ architectures.} Targeting at EfficientNet-B0, we use its model size and FLOPs as two objectives to regularize space proposals and name the searched architecture as HourNAS-EfficientNetSS-F. {\color{black} Same as EfficientNet\footnote{https://github.com/tensorflow/tpu/tree/master/models/official/efficientnet}, we use the Swish~\cite{searchactivation} activation and Exponential Moving Average~(EMA) in fully training.} Note that the AutoAugment~\cite{autoaugment} is not used. The result in Tab.~\ref{tab_imagenet} shows HourNAS-EfficientNetSS-F surpasses EfficientNet-B0 by 0.2\% Top-1 accuracy with similar number of parameters and FLOPs. \subsection{Ablation Study}\label{sec_ablation} If we do not restrict the computational resources of the sampled architectures in searching, the most complex block achieves the highest probability after searching for enough time. As shown in Tab.~\ref{tab_full}, we train the most complex architectures in both FBNet and EfficientNet search spaces, namely FBNet-Max and EfficientNet-Max. These two models obtain 75.7\%, and 78.3\% Top-1 accuracies, respectively. However, the computational resource requirements of these structures are relatively high. Therefore, the neural architecture search~(NAS) could be regarded as the problem of computational resource allocation given the resource constraints. \textbf{The Impact of Vital Block Priori.} In order to investigate the impact of the vital block priori, we directly search architectures without using the vital block information. All the blocks in the SuperNet $S$ are treated equally in searching. We use the Gumbel-Max sampling and space proposal strategy to search architectures under the same predefined computational resources. We use the previously described original and enlarged FBNet search spaces. We optimize 8 space proposals and it takes 6 hours for searching, which is twice of the counterpart that utilize the vital block priori. As shown in Tab.~\ref{tab_vital_priori}, the Top-1 accuracies of the discovered models (HourNAS-FBNetSS-G, HourNAS-EFBNetSS-H) drop by 0.9\% and 0.6\% on the ImageNet validation set, respectively. The searched vital blocks of HourNAS-FBNetSS-A uses 0.9M parameters and 130M FLOPs, and the HourNAS-FBNetSS-G uses 0.5M parameters and 55M FLOPs. The vital blocks in HourNAS-FBNetSS-G are not as expressive as HourNAS-FBNetSS-A, which results in worse performance. The results show the necessity of the vital block priori. Searching the vital blocks with higher priority is helpful in finding high-quality architectures. Therefore, we use a two-stage search method to allocate resources to vital blocks first, which can allocate resources more effectively, so as to complete the architecture search in a short time. The architectures are provided in the supplementary file, under same computational resources constraints, inclining more resources on the vital blocks gains more performance profit. \textbf{The Impact of Gumbel-Max Sampling.} As discussed in Sec.~\ref{sec_space_proposal}, there are several design choices for the sampling methods. To find out the impact of the Gumbel-Max sampling method, here we instead use the Gumbel softmax~\cite{fbnet} to optimize architecture parameters and network parameters. The search space and target resource constraints are the same as HourNAS-FBNetSS-A. The search process takes around 1 GPU day and the finalized architecture is denoted as HourNAS-FBNetSS-I. As shown in Tab.~\ref{tab_gumbel}, HourNAS-FBNetSS-I outperforms HourNAS-FBNetSS-A by 0.1\% Top-1 accuracy with much less searching cost, which demonstrate that Gumbel-Max is an efficient strategy for optimizing the SuperNet with almost no less of accuracy. \section{Conclusions}\label{sec:con} This paper investigates an efficient algorithm to search deep neural architectures on the large-scale dataset (\emph{i.e.}, ImageNet) directly. To reduce the complexity of the huge search space, we present an Hourglass-based search framework, namely HourNAS. The entire search space is divided into ``vital'' and ``non-vital'' parts accordingly. By gradually search the components in each part, the search cost can be reduced significantly. Since the ``vital'' parts are more important for the performance of the obtained neural network, the optimization on this part can ensure accuracy. By exploiting the proposed approach, we can directly search architectures on the ImageNet dataset that achieves a 77.0\% Top-1 accuracy using only 3 hours (\emph{i.e.}, about 0.1 GPU days), which outperforms the state-of-the-art methods in both terms of search speed and accuracy. \clearpage \newpage { \bibliographystyle{ieee_fullname}
{'timestamp': '2020-12-09T02:08:06', 'yymm': '2005', 'arxiv_id': '2005.14446', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14446'}
arxiv
\section{Introduction} The numerous applications of 3D vision, such as augmented reality, autonomous driving and robotic locomotion, aided by the ever increasing computational power of modern machines have caused a steep increase of interest in 3D vision and its applications. The research in the field has also been predominantly motivated by the wide scale access to good quality and low cost 3D scanners, which has opened many new avenues. However, despite of all the recent advancements of algorithms for 3D meshes and point clouds, there is still room for enhancements to match the performance of the systems designed for 2D images on similar tasks. Nearly all the state-of-the-art methods in the various fields of computer vision are designed for 2D images and there are also immense differences in the sizes of training datasets for 2D images compared to any of their 3D counterparts. This points to a need for the development of bridging techniques, which can make efficient uses of both 2D images and 3D point clouds or meshes. A technique that can fuse information from both 2D and 3D domains can benefit from the matured 2D vision as well as the contemporary advances in 3D vision. The complementary nature of 2D and 3D data can lead to an improved performance and efficiency in many potential applications, e.g., face recognition and verification, identification of objects or different regions of interest from coloured images in 3D maps, use of the 3D model of an object to locate it in an image in the presence of severe perspective distortion \citep{laga20183d}, as well as localization of a 2D images in a 3D point cloud. To move towards the goal of multi-domain information fusion from 2D and 3D domains, this paper proposes a novel approach to learn a framework to directly match feature descriptors extracted from 3D point clouds with those extracted from 2D images. This concept is used to localize images in point clouds directly generated from 3D scanners. To localize images, the developed framework is used to match 3D points of the point clouds to their corresponding pixels in 2D images with the help of multi-domain descriptor matching. The matched points between the images and the point clouds are then used to estimate the six degrees-of-freedom (DOF) position and orientation (pose) of images in the 3D world. 6-DOF pose estimation is an important research topic due to its numerous applications such as augmented reality, place recognition, robotic grasping, navigation, robotic pose estimation as well as simultaneous localization and mapping (SLAM). Current techniques for camera pose estimation can be classified into two major categories: \textbf{(i)} Regression networks based methods and \textbf{(ii)} Features based methods. The regression networks based methods (e.g. \cite{posenet,kendall2017geometric,walch2017image}), use deep neural networks to estimate the pose of the camera and consequently have high requirements for computational resources such as powerful GPUs and require a lot of training data \citep{xin2019review} from different viewpoints to ensure that the poses of query cameras are sufficiently close to the training ones \citep{sattler2019understanding}. Moreover they scale poorly with the increase in the size of 3D models and usually run into the problems of non-convergence for end-to-end training \citep{brachmann2018learning}. Features based method use hand-crafted approaches or deep learning methods to extract local or global features from images. An essential step in the state-of-the-art techniques in this category is the use of the Structure from Motion (SfM) pipeline \citep{colmapsfm,han2019image} to create sparse 3D models from images (e.g. \citep{li2010location,sattler2015hyperpoints,sattler2017efficient}). Structure from Motion pipelines provide a one-to-one correspondence between the points in the generated sparse point cloud and the pixels of the 2D images that were used to create the model. Several works use this information to localize images with respect to the 3D point cloud generated by SfM. However, model creation with SfM is a computationally expensive process which may be very time consuming depending on the number of images used and the quality of the point cloud to be generated. Models generated with SfM have especially poor quality for or miss out entirely on texture-less regions. Moreover, dependency on SfM generated point clouds renders such techniques futile for scenarios where point clouds have been obtained from 3D scanners. Now-a-days, high quality and user friendly 3D scanners (e.g. LIDAR, Microsoft Kinect, Matterport scanners and Faro 3D scanners) are available which can effectively render dense point clouds of large areas without the use of SfM. These point clouds are of better quality, not only because of their higher point density but also due to the reason that they can effectively capture bland surfaces that SfM based techniques tend to miss. To be able to directly localize 2D images in the point clouds generated from any 3D scanners, we propose a novel concept to directly match feature descriptors extracted from 3D point clouds with descriptors extracted from 2D images. The matched descriptors can then be used for 6-DOF camera localization of the image in the 3D point cloud. Figure \ref{fig:result} shows a section of the dense point cloud of the Shop Facade dataset \citep{posenet} along with a query image and the localization results of the proposed technique. To match the feature descriptors from 2D and 3D domain, we generate a dataset of corresponding 3D and 2D descriptors to train a two-stage classifier called `Descriptor-Matcher'. For localization of a 2D image in a point cloud, we first use image feature extraction techniques such as Scale Invariant Feature Transform (SIFT) \citep{lowesift} to extract keypoints and their descriptors from the 2D image. Similarly, we use techniques designed for point clouds \citep{guo20143d} such as 3D-SIFT key-points \citep{lowesift,pcl}, 3D-Harris key-points \citep{harris,laga20183d} and Rotation Invariant Features Transform (RIFT) descriptors \citep{rift} to extract 3D keypoints and descriptors from the point cloud. The Descriptor-Matcher is then used to find the matching pairs of 3D and 2D descriptors and their corresponding keypoints. This results in a list of coordinates in the point cloud and their corresponding pixels in the query image. The resulting one-to-one matches are then used in a robust algorithm for 6-DOF pose estimation to find the location and orientation of the query camera in the 3D point cloud. Figure \ref{fig:test_chart} shows the steps involved in our technique to estimate the camera pose for a query image. A preliminary version of this work appeared in \cite{my2d3d}. To the best of our knowledge, \cite{my2d3d} was the first work: \textbf{(i)} to match directly 3D descriptors extracted from dense point clouds with the 2D descriptors from RGB images, and \textbf{(ii)} to use direct matching of 2D and 3D descriptors to localize camera pose with 6-DOF in dense 3D point clouds. This work extends \cite{my2d3d} by improving all the elements of the proposed technique, including dataset generation, Descriptor-Matcher and pose estimation. Additionally, we propose a reliable method to create a large collection of 2D and 3D points with matching locations in images and point cloud, respectively. We also present more details of the proposed method and also evaluate the proposed technique on more challenging datasets compared to \cite{my2d3d}. The rest of this paper is organized as follows. Section \ref{related_work} discusses the various categories of the techniques in the literature for camera localization or geo-registration of images. The details of the proposed technique are presented in Section \ref{technique}. Section \ref{experiments} reports the experimental setup and a detailed evaluation of our results. Finally, the paper is concluded in Section \ref{conclusion}. \begin{figure*}[t] \begin{center} \includegraphics[width=1\linewidth]{Figures2.pdf} \end{center} \caption{A block diagram of the test pipeline of the proposed technique. We extract 3D key-points and descriptors from the dense 3D Point Cloud. 2D key-points and their corresponding descriptors are extracted from the 2D RGB Query Image. Then our proposed `Descriptor-Matcher' algorithm directly matches the 2D descriptors with the 3D descriptors to generate correspondence between points in 2D image and 3D point cloud. This is then used with a robust pose estimation algorithm to estimate the 6-DOF pose of the query image in the 3D point cloud.} \label{fig:test_chart} \end{figure*} \section{Related Work}\label{related_work} The numerous applications of camera pose estimation and image localization render it as an interesting and active field of research. Traditionally, there are two distinct approaches to estimate the position and orientation of a camera \citep{xin2019review}: \textbf{(i)} Features based methods and \textbf{(ii)} Network based pose regression methods. The proposed method forms a new category of possible approaches: \textbf{(iii)} Direct 2D-3D descriptor matching based methods. \subsection{Features based methods} Features based methods extract convolutional or hand-crafted features from 2D images and use them in different manners to localize the images. However, many of these methods only estimate approximate locations and use number of inliers found with RANSAC \citep{ransac} as a criterion for image registration e.g., a query image is considered as registered if the RANSAC stage of the method can find 12 inliers among the features for the query image. This is partly due to the fact that some datasets for image localization do not provide the ground truth position and orientation information for the query cameras. However, inlier count is not a reliable criterion and it does not represent the actual performance of any given method. Feature based methods can further be classified into two types of methods: Image retrieval based methods and SfM based methods. \subsubsection{Image retrieval based methods } Image retrieval based methods involve the use of a large geo-tagged database of images. To localize a 2D query image, these methods use different types of features to retrieve images similar to the query image. The average of the retrieved database images can be used as the predicted location of the query image. Alternatively, the poses of the retrieved images can be used to triangulate the pose of the query camera \citep{chen2011city,zamir2010accurate}. These methods cannot be used for the localization of 2D images in point clouds. Also, many times the images in the dataset are not sufficiently close to the query image which results in significant errors in pose estimation. \subsubsection{SfM-based methods} SfM-based methods produce better pose estimates than image retrieval based methods \citep{sattler2017efficient}. These methods use the SfM pipeline \citep{colmapsfm}. SfM first extracts and matches features such as SIFT, SURF or ORB, from the set of training images. Then the matched features between the different 2D images are used to create a 3D model on an arbitrary scale. Each point in the 3D model is created by triangulation of points from multiple images. \cite{irschara2009structure} used image retrieval to extract 2D images that were similar to the query 2D image from the training database. The extracted images were used with the SfM model to improve the accuracy of the estimated camera poses. \cite{li2010location} compared the features extracted from the query 2D images with the 2D features corresponding to the points in the SfM model to localize the images. \cite{sattler2015hyperpoints} improved the localization process with a visual vocabulary of 16 million words created from the features of the database images and their locations in the SfM point cloud. Later, \cite{sattler2017efficient} further extended their work with the help of a prioritized matching system to improve the estimated poses for the query images. However, these methods can only work with point clouds generated with SfM based pipelines \citep{piasco2018survey}. This is mainly due to the reason that the sparse point clouds generated with SfM save the corresponding information of the points and features from 2D images that were used to create the sparse SfM point cloud. SfM based methods rely on this information for pose estimation. Also some works use element-wise mean (or any other suitable function) of the feature descriptors of the points that were used to create a 3D point in the SfM point cloud as a 3D descriptor of that 3D point. Such an approximation of 3D features is dependent on the inherent information in the point cloud generated with SfM, which is not available if the point cloud had to be generated from a 3D scanner. Structure from Motion is a computationally expensive and time consuming process. The point clouds generated with SfM are sparse and very noisy \citep{feng20192d3d}. SfM models have especially poor quality at bland or texture-less regions and may miss out such areas altogether. Moreover, it requires multiple images of the same area from many different angles for good results, which is practically a difficult requirement, especially for large areas or buildings. Also the generated models are created on an arbitrary scale and it is not possible to determine the exact size of the model without extra information from other sources \citep{feng20192d3d}. The availability of high quality 3D scanners has made it possible to capture large scale point clouds in an efficient manner without the need to capture thousands of images to be used for the SfM pipeline. Moreover, LIDAR and other 3D scanners are now becoming an essential part of robots, particularly for locomotion and grasping. Therefore, it is essential to develop methods that can estimate 6-DOF poses for cameras in point clouds captured from any scanner. \subsection{Network-based pose regression methods} These methods use deep neural networks to estimate the position and orientation of query images through pose regression. However, \cite{sattler2019understanding} showed that these methods can only produce good results when the poses of the query images are sufficiently close to the training images. \cite{posenet} proposed a convolutional neural network, called PoseNet, which was trained to regress the 6-DOF camera pose of the query image. \cite{kendall2017geometric} later improved the loss function in Posenet while \cite{walch2017image} improved the network architecture to reduce the errors in pose estimations. \cite{brachmann2017dsac} introduced the concept of differentiable RANSAC. Instead of direct pose regression through a neural network, they created a differential version of RANSAC \citep{ransac} to estimate the location and orientation of the query cameras. Specifically, model of \cite{brachmann2017dsac} was composed of two CNNs, one to predict scene coordinates and the other CNN to select a camera pose from a pool of hypotheses generated from the output of the first CNN. However, their method was prone to over-fitting and did not always converge during end-to-end-optimization especially for outdoor scenes \citep{brachmann2018learning}. \cite{radwan2018vlocnet++} used a deep learning based architecture to simultaneously carry out camera pose estimation, semantic segmentation and odometry estimation by exploiting the inter-dependencies of these tasks for assisting each other. \cite{brachmann2018learning} modified \citep{brachmann2017dsac} with a fully convolutional network for scene coordinate regression as the only learnable component in their system. Soft inlier count was used to test the pose hypotheses. Although it improved the localization accuracy, the system still failed to produce results for datasets with large scale. \subsection{Direct 2D-3D descriptor matching based methods} Our preliminary work \citep{my2d3d} was the first technique to estimate the 6-DOF pose for query cameras by directly matching features extracted from 2D images and 3D point clouds. \cite{feng20192d3d} trained a deep convolutional network with triplet loss to estimate descriptors for patches extracted from images and point clouds. The estimated patches were used in an exhaustive feature matching algorithm for pose estimation. However, their system achieved a limited localization capability. This paper improves the concept of \citep{my2d3d} with an unconstrained method to extract pairs of corresponding 2D and 3D points for training, and improves the structure of Descriptor-Matcher. It also introduces a better pose estimation strategy. Our technique directly extracts 3D key-points and feature descriptors from point clouds which, in contrast to SfM based approaches, enables us to estimate poses in point clouds generated from any 3D scanner. Moreover, the capability of our method to work with dense point clouds allows it to use better quality feature descriptors, which additionally helps in the pose estimation of the query images. \section{Proposed Technique}\label{technique} The direct matching of 2D and 3D descriptors in our technique provides a way to localize the position and orientation of 2D query images in point clouds which is not constrained by the method of point cloud generation, the type of 3D scanners used or the indoor and outdoor nature of the environment. At the core of our technique is a classifier, called `Descriptor-Matcher', which is used to match the feature descriptors from 2D and 3D domain. Descriptor-Matcher is composed of two stages: coarse and fine. To train the Descriptor-Matcher, we need a dataset of 3D points and their corresponding pixel locations in the training images. It is impractical to manually create a dataset of matching 2D and 3D points, especially for large scales. To overcome this issue, we propose a method to automatically collect a large number of matching 3D and 2D points and their corresponding descriptors from a point cloud and a given set of 2D training images. The trained Descriptor-Matcher can then be used to localize a 2D query image in the point cloud. \subsection{Extraction of Key-points and Feature Descriptors} \label{technique:keypoint_extraction} Let us assume a dataset with $N$ number of training images with known ground truth poses. Let $PC_d$ be the point cloud in which the query images need to be localized: \begin{equation} \label{e1} PC_{d}= \bigcup_{i=1}^{Np}(x_i,y_i,z_i) \end{equation} where $\bigcup$ is the union operator, $Np$ is the number of points in the point cloud and $(x_i,y_i,z_i)$ are the Cartesian coordinates of the $i^{th}$ point of the point cloud. Nowadays, most of the 3D sensors can produce RGB images with ground truth camera positions relative to the generated point clouds. In case such information is not available, Multi View Stereo \citep{colmapmvs} can be used to generate ground truth camera poses for the training images as explained in \citep{my2d3d}. To create the dataset for training, we first use methods designed for point clouds to extract 3D keypoints and feature descriptors from the point cloud $PC_d$ \citep{pcl,guo20143d}. This results in a set of 3D keypoints: \begin{equation} \label{e2} keys3D= \bigcup_{j=1}^{N3}(x_j,y_j,z_j) \end{equation} and their corresponding 3D descriptors: \begin{equation} \label{e3} desc3D= \bigcup_{j=1}^{N3}(u_j^1,u_j^2,u_j^3,...u_j^{p}) \end{equation} where $(u_j^1,u_j^2,u_j^3,...u_j^{p})$ is the $p$ dimensional 3D descriptor of the $j^{th}$ 3D keypoint with Cartesian coordinates $(x_j,y_j,z_j)$, and $N3$ is the number of the detected keypoints in the dense point cloud. Similarly, we use keypoint and descriptor extraction methods specific for images to get a set of 2D keypoints $keys2d$ and feature descriptors $desc2d$ for each training image: \begin{equation} \label{e4} keys2D_n= \bigcup_{k=1}^{N2_n}(\widetilde{x}_{k,n},\widetilde{y}_{k,n}) \end{equation} \begin{equation} \label{e5} desc2D_n= \bigcup_{k=1}^{N2_n}(v_{k,n}^1,v_{k,n}^2,v_{k,n}^3,...v_{k,n}^{q}) \end{equation} where $N2_n$ is the number of the detected keypoints in $n^{th}$ image. $\widetilde{x}_{k,n}$ and $\widetilde{y}_{k,n}$ are the horizontal and vertical pixel coordinates, respectively, of the $k^{th}$ keypoint in the $n^{th}$ training image and $(v_{k,n}^1,v_{k,n}^2,v_{k,n}^3,...v_{k,n}^{q})$ is the $q$ dimensional 2D descriptor of that keypoint. \subsection{Dataset Generation} \label{technique:dataset} \subsubsection{Back ray Tracing} To calculate the distance between 2D and 3D keypoints, we need to either project the 3D keypoints onto the 2D image or the 2D keypoints onto the 3D point cloud. Projecting the 2D keypoints will involve the voxelization of the point cloud which is a computationally expensive process compared to its alternative (i.e., back ray tracing) for the task at hand. Therefore, for each image in the training set, we use the intrinsic and extrinsic matrix of the camera to trace back rays from the 3D key points $keys_{3d}$ on the image. Mathematically, back ray tracing can be represented through the following equation: \begin{equation} \label{e6} \begin{aligned} \begin{bmatrix} \hat{s}_{j,n}\, \hat{x}_{j,n},\,\hat{s}_{j,n}\, \hat{y}_{j,n},\,\hat{s}_{j,n} \end{bmatrix}^{tr} = \\ \begin{bmatrix}K_n\end{bmatrix} \! \begin{bmatrix}R_n|T_n\end{bmatrix} \! \begin{bmatrix}x_j,y_j,z_j,1\end{bmatrix}^{tr} \\ \forall j=1,2,3,...,N3 \end{aligned} \end{equation} Where $K_n$ is the intrinsic matrix of the camera, $R_n$ is the rotation matrix and $T_n$ is the translation vector for the conversion of points from world coordinates to camera coordinates for the $n^{th}$ image. The $tr$ superscript denotes the transpose of a matrix. The $\hat{x}_{j,n}$ and $\hat{y}_{j,n}$ are the horizontal and vertical pixel coordinates, respectively, of the projected 3D keypoint on the $n^{th}$ image and $\hat{s}_{j,n}$ is the depth of the 3D keypoint from the camera. We keep only those projected keypoints that are within the boundaries of the image and have a positive depth value so that they are in front of the camera: \begin{equation}\label{e7} \begin{aligned} \Theta_n= \bigcup(\hat{x}_{j,n}, & \hat{y}_{j,n},\hat{s}_{j,n}) \ s.t. \ (0<\hat{x}_{j,n}<img\_w_n)\ \\ and & \ (0<\hat{y}_{j,n}<img\_h_n)\ and\ (\hat{s}_{j,n}>0) \\ & \quad \qquad \qquad \qquad \forall \ j=1,2,3,...,N3 \end{aligned} \end{equation} Where $img\_w_n$ and $img\_h_n$ are the width and height of the $n^{th}$ image, respectively. However, as keypoints are extremely sparse, it is possible that points from the areas of the point cloud that are not visible in the image, get projected on the image. For example, if the camera is looking at a wall at a right angle and there is another wall behind the first one, then it is possible that the keypoints detected on the back wall get projected on the image. Theses false projections can create problems during the training of the Descriptor-Matcher as they result in the matching of locations between images and point clouds which are not the same and increase the number of false positives. Figure \ref{fig:depth_block_filter} shows examples of false projections of 3D keypoints from locations in point cloud which are not visible in the 2D image. \subsubsection{Depth Block Filtering} \label{technique:dataset:DBF} To overcome this problem, we devised a strategy based on the 3D points of the point cloud $PC_d$, called Depth Block Filtering. Similar to the 3D keypoints, we back trace the points in $PC_d$ to the image with the help of the intrinsic matrix of the camera, $K_n$, and the augmented matrix created by appending the rotation matrix $R_n$ with the translation vector $T_n$ to get the pixel coordinates of the 3D points: \begin{equation} \label{e8} \begin{aligned} \begin{bmatrix} \hat{s}_{i,n}\,\hat{x}_{i,n},\,\hat{s}_{i,n}\,\hat{y}_{i,n},\,\hat{s}_{i,n} \end{bmatrix} ^{tr}\!=\\ \begin{bmatrix}K_n\end{bmatrix} \! \begin{bmatrix}R_n|T_n\end{bmatrix} \! \begin{bmatrix}x_i,y_i,z_i,1\end{bmatrix}^{tr} \\ \forall i=1,2,3,...,Np \end{aligned} \end{equation} where $\hat{x}_{i,n}$ and $\hat{y}_{i,n}$ are the horizontal and vertical pixel coordinates, respectively, of the projected points of the 3D point cloud on the $n^{th}$ image and $\hat{s}_{i,n}$ is the depth of the projected point from the camera. We filter out all those points that are outside the boundaries of the image and behind the camera i.e., those with a negative depth value $\hat{s}_{i,n}$. \begin{equation}\label{e9} \begin{aligned} \Gamma_n= \bigcup(\hat{x}_{i,n}, & \hat{y}_{i,n},\hat{s}_{i,n}) \ s.t. \ (0<\hat{x}_{i,n}<img\_w_n)\ \\ and & \ (0<\hat{y}_{i,n}<img\_h_n)\ and\ (\hat{s}_{i,n}>0) \\ & \quad \qquad \qquad\qquad \forall \ i=1,2,3,...,Np \end{aligned} \end{equation} We convert the projected pixel values $\hat{x_i}$ and $\hat{y_i}$ in $\Gamma_n$ to whole numbers. Any duplicates in the resulting set that have the same values for both $\hat{x_i}$ and $\hat{y_i}$ are removed by keeping only those elements of $\Gamma_n$ which are closest to the position of the camera i.e., among the duplicate pixel locations, we keep the triple with the minimum value of $\hat{s_i}$. The depth values $\hat{s_i}$ in $\Gamma_n$ are then used to create a depth map for the training image. Next, we use the generated depth map to create blocks of size $\tau \times \tau$ pixels around the locations of the triples in the set of projected 3D keypoints $\Theta_n$. Finally, we filter out all the triples in $\Theta_n$ whose depth values $\hat{s_j}$ are greater than a threshold $\varphi$ in their respective depth block, where $\varphi$ and $\tau$ are constants. This strategy helps to cater not only for wrong projections but also for any holes in the point cloud as well. Figure \ref{fig:depth_block_filter} shows examples of the results from depth block filtering. \begin{figure*}[htbp] \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=1\linewidth]{DBF1.png} \captionsetup{justification=centering} \caption{} \label{fig:3a} \end{subfigure} \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=1\linewidth]{DBF2.png} \captionsetup{justification=centering} \caption{} \label{fig:3b} \end{subfigure} \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=1\linewidth]{DBF3.png} \captionsetup{justification=centering} \caption{} \label{fig:3c} \end{subfigure} \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=1\linewidth]{DBF4.png} \captionsetup{justification=centering} \caption{} \label{fig:3d} \end{subfigure} \caption{Examples of results from Depth Block Filtering (DBF). Due to the sparse nature of 3D keypoints, even the points occluded from the camera get projected by back ray tracing e.g., keypoints occluded by the fridge in (a) and (b) and points from around the shop in (c) and (d). Depth Block Filtering effectively removes the occluded keypoints and only retains the keypoints in the direct line of sight of the camera. \textbf{Left column:} Snapshot of sections from point clouds with 3D keypoints (red + green) that get projected on a training image. \textbf{Right column:} Image with the projected locations of 3D keypoints. \textbf{Red points:} Keypoints removed by DBF as occluded points. \textbf{Green points:} Keypoints retained by DBF. See Section \ref{technique:dataset:DBF} for details of DBF.} \label{fig:depth_block_filter} \end{figure*} \subsubsection{Creating 2D-3D Correspondences} We then calculate the Euclidean distances between the remaining projected points $(\hat{x}_{j,n},\hat{y}_{j,n})$ in the set of projections of 3D keypoints $\Theta_n$ and the 2D keypoints $keys2D_n$ on the image. The pairs of 2D and 3D keypoints whose projections are within a specified distance $\alpha$, measured in the units of pixels, are considered as the matching pairs. In the case that there are more than one 2D keypoints within the specified distance of the projection of a 3D keypoint or multiple 3D keypoints' projections are close to a 2D keypoint, only the pair with the smallest distance is considered for the dataset, i.e., we treat the matching of keypoints as a one-to-one correspondence for each image. Let $\zeta_n$ be the set of the pair of indices, corresponding to the points of $N3$ and $N2_n$, that are within an error threshold $\alpha$: \begin{equation}\label{e10} \begin{aligned} \zeta_n= \bigcup(j,k) \quad \forall \left || (\hat{x_j}-\widetilde{x}_{k,n}),(\hat{y_j}-\widetilde{y}_{k,n}) \right || < \alpha \\ \quad where \quad j=1,2,3,...,N3, \\ k=1,2,3,...,N2 \end{aligned} \end{equation} We use $\zeta_n$ to create a matching set of 3D and 2D points by retrieving the keypoints from $keys3D$ and $keys2D_n$ according to the indexes. This process is repeated for each training image and then the resulting sets of matching keypoints are concatenated to create a dataset of matching 3D and 2D points for the whole training set. To obtain a dataset of corresponding 3D and 2D descriptors for the matching points, we retrieve the corresponding descriptors for the 3D key-points from $desc3D$ and the 2D descriptors from $desc2D$. It is to be noted that in the resulting dataset, one 3D descriptor can correspond to multiple 2D descriptors as one 3D keypoint can appear in multiple images of the same place taken from different poses. \subsection{Training} \label{technique:train} The generated dataset of corresponding 2D and 3D features is used to train the Descriptor-Matcher. The Descriptor-Matcher is composed of two stages: a coarse matcher and a fine matcher, connected in series (see Figure \ref{fig:test_chart}). The two stages allow the Descriptor-Matcher to maintain both a high precision and computational efficiency at the same time, as explained in Section \ref{technique:test}. We evaluated several different classifiers for the coarse and fine stages including multi-layer fully connected Neural Networks \cite{khan2018guide}, Support Vector Machines with different kernels, Nearest Neighbour Classifiers with dictionary learning and Discriminant Analysis. However, we empirically found that Classification Tree \citep{treeref} performs best for the coarse stage of the matcher, while for the fine stage only Random Forest classifier \citep{randomforest} produces suitable results. Moreover, these classifiers have better robustness, speed, generalization capability and ability to handle over-fitting for the task at hand. We treat the problem of matching the descriptors from images and point cloud as a binary classification problem. At the input of the Descriptor-Matcher, we provide 2D and 3D descriptors, concatenated in the form of a $(p\! +\! q)\! \times \! 1$ vector. A positive result at the output indicates that the concatenated descriptors are from the same location in the image and the point cloud, while a negative result shows a mismatch. To split nodes in the classification tree of coarse matcher, as well as in the trees in Random Forest, we used Gini's Diversity Index to measure the impurity of nodes. The impurity criterion for our case is defined as: \begin{equation}\label{eq:gdi_binary} Gini's\ index=\frac{2\times r^+ \times r^-}{(r^++r^-)^2} \end{equation} where $r^+$ and $r^-$ are the number of positive and negative samples, respectively, at any given node of a tree. Consequently, an impure node will have a positive value for the splitting criterion, while a node with only positive or only negative samples will have Gini's diversity index equal to zero. To train the classifiers, the corresponding descriptors of the matching 3D and 2D keypoints in the generated dataset (Section \ref{technique:dataset}) were concatenated to create positive training samples. For the negative samples, we concatenated the 2D and 3D descriptors of the non-matching points in the dataset. We define non-matching points as those pairs whose corresponding locations in the point cloud are at least a distance $\beta$ apart. However, with the increase in the scale of the point cloud, it is possible that there are regions with similar appearance at different locations in the point cloud. This is particularly a concern for indoor scenarios, where there are comparatively more bald regions and repeated structures. To overcome this problem we also ensured that the Euclidean distance between the descriptors of non-matching points is greater than a threshold $\gamma$. We only used a randomly selected subset of the generated negative samples for training due to the large number of possible one-to-one correspondences between non-matching pairs. We optimized the fine-matcher for maximum precision to minimize the number of false positives in the final matches. \subsection{Testing} \label{technique:test} At test time, we first extract key-points and descriptors from the 2D query image that needs to be localized in the point cloud. Similarly, 3D keypoints and descriptors are extracted from the point cloud, if not already available. Then we concatenate the 2D descriptors of the query image and the 3D descriptors of the point cloud in a one-to-one fashion and use the two stage Descriptor-Matcher to find the matching and non-matching pairs. The pairs of descriptors are first tested by the coarse matcher and only the pairs with positive results for matches are passed to the fine-matcher. As the coarse matcher is composed of a single classification tree, it greatly reduces the number of pairs which need to be tested by the fine matcher, at only a small computational cost, thus greatly decreasing the prediction time of the algorithm. Then, we retrieve the corresponding keypoints for the descriptor pairs positively matched by the fine-matcher and use them as matching locations from the image and the point cloud for pose estimation. However, just like any classifier, the output of the Descriptor-Matcher contains some false positives and the matched 3D and 2D points are not completely free of wrong matches. We use two conditions to improve the descriptor matching. \textbf{First}, we use the probability scores for a positive match (which are in the range $ 0-1$) as the confidence value that a 2D descriptor and a 3D descriptor represent the same locations in the quey image and the point cloud, respectively. For a positive match, the predicted confidence value must be greater than $0.5$. \textbf{Second}, we also use two-way matching to improve the reliability of the matches. Specifically, based on the highest prediction confidence, we find the closest matching 3D descriptor for each 2D descriptor, and the closest matching 2D descriptor for each 3D descriptor. For a 2D descriptor to be treated as a corresponding pair for a 3D descriptor, the confidence value of the predicted match must be greater than the confidence value of that specific 2D descriptor matching with any other 3D descriptor and vice versa. To further filter out the false positives we use the MLESAC \citep{mlesacmatlab} algorithm along with the P3P \citep{p3pmatlab} algorithm to find the best set of points for the estimation of the position and orientation of the camera for the query image. MLESAC is an improved and more generalized algorithm compared to the traditional RANSAC \citep{ransac}. MLESAC generates the tentative solutions in the same manner as RANSAC. However, it produces a better final solution as, in addition to maximizing the number of inliers in the solution, it uses maximum likelihood estimation based on a Gaussian distribution of noise to minimize the re-projection error between the 2D image and 3D points \citep{mlesacmatlab}. Figure \ref{fig:test_chart} shows a block diagram of the steps involved to localize a 2D query image in a 3D point cloud. The predicted pose of the camera can further be refined with the application of the R1PPnP pose estimation algorithm \citep{zhou2018re} on the points identified as inliers by the MLESAC algorithm to estimate the final position and viewing direction of the query camera in the point cloud. The predicted pose information can be used to extract the section of the point cloud that corresponds to the query image for visualization purposes (Figure \ref{fig:result}). \section{Experiments and Analysis}\label{experiments} To evaluate the performance of our technique, we carried out extensive experiments on a number of publicly available datasets. These include Shop Facade \citep{posenet}, Old Hospital \citep{posenet}, Trinity Great Court \citep{kendall2017geometric}, King's College \citep{posenet} and St. Mary Church \citep{posenet} datasets from the Cambridge Landmarks Database for \textbf{outdoor scenarios}. To test the localization capability of the proposed technique for \textbf{indoor cases}, we used the Kitchen \citep{valentin2016learning} and Living Room \citep{valentin2016learning} Datasets from the Stanford RGB Localization Database and Baidu Indoor Localization Dataset \citep{idl}. In our experiments, SIFT key-points and descriptors \citep{lowesift} were extracted from the 2D query images. For the point clouds, we used 3D SIFT key-points \citep{pcl} and 3D RIFT descriptors \citep{rift} to extract keypoints and feature descriptors, respectively. 3D SIFT is a key-point extraction method designed for point clouds, which is inspired from the 2D SIFT key-point extraction algorithm \citep{lowesift} for 2D images. The original 2D SIFT algorithm was adapted for 3D point clouds by substituting the function of intensity of pixels in an image with the principal curvature of points in a point cloud \citep{pcl}. We set the maximum distance between the image keypoints and the projected 3D keypoints $\alpha=5\ pixels$ for the generation of positive samples. For the formation of one-to-one pairs for negative samples, we set the minimum distance between the 3D keypoints, $\beta$, to 0.5 and the minimum Euclidean distance between the 3D descriptors, $\gamma$ to $0.3$. To optimize the parameters for coarse and fine matchers, we divided the generated dataset of corresponding 2D and 3D descriptors (see Section \ref{technique:dataset}) into training and validation sets in the ratio of $8\! :\! 2$. Based on the performance on the validation set, we used grid search \citep{gridsearch} to fine tune the classification cost and the maximum number of splits in a tree for both coarse and fine matchers, as well as the number of trees in the Random Forest. Finally, the complete dataset of matching 2D and 3D features was used to train the Descriptor-Matcher with the optimized parameters. \subsection{Evaluation Metrics} We use the positional and the rotational errors in the predicted poses of the query images to evaluate the performance of our technique. As such, the positional error is calculated as the Euclidean distance between the ground truth and the predicted positions of the query camera in the 3D point cloud: \begin{equation} \label{pos_err} position\_error\! =\! \left || (x_g-x_e),(y_g-y_e),(z_g-z_e) \right |\! | \end{equation} where $(x_g,y_g,z_g)$ and $(x_e,y_e,z_e)$ are the ground truth and estimated positions of the query image's camera in the 3D point cloud, respectively. For the estimation of the rotational error, we calculated the minimum angle between the viewing directions of the predicted and the ground truth cameras for the 2D query image. If the predicted rotation matrix is represented by $R_e$ and the ground truth rotation matrix is $R_{g}$, then the rotational error $\phi$ in degrees can be calculated as follows: \begin{equation} \label{eq:R_err} \phi = \frac{\pi}{180} \times cos^{-1}(\frac{trace(R_g \times R_e^{tr})-1}{2}) \end{equation} \begin{sidewaystable*}[htbp]% \caption{Median and percentile localization errors for the outdoor datasets: Shop Facade, Old Hospital, St. Mary Church, King's College and Great Court Datasets. P stands for percentile, e.g., P 25\% means the maximum error for 25\% of the data when errors are sorted in the ascending order. m stands for metres} \centering \begin{tabular}{|l|l|c|c|c|c|c|} \specialrule{.15em}{.0em}{.0em} \textbf{Outdoor Datasets $\downarrow$} & \textbf{Errors $\downarrow$ \textbackslash{} Metrics $\rightarrow$} & \textbf{Median} & \textbf{P 25\%} & \textbf{P 50\%} & \textbf{P 75\%} & \textbf{P 90\%} \\\specialrule{.15em}{.0em}{.0em} \multirow{2}[0]{*}{\textbf{Shop Facade}} & \textbf{Position Error (m)} & 0.0860 m & 0.0307 m & 0.0860 m & 0.4258 m & 3.3890 m \\\cline{2-7} & \textbf{Angle Error (degrees)} & 0.7792\degree & 0.2776\degree & 0.7792\degree & 4.2890\degree & 33.6595\degree \\\specialrule{.15em}{.0em}{.0em} \multirow{2}[0]{*}{\textbf{Old Hospital}} & \textbf{Position Error (m)} & 0.1295 m & 0.0649 m & 0.1295 m & 0.2561 m & 3.2744 m\\\cline{2-7} & \textbf{Angle Error (degrees)} & 0.2210\degree & 0.1312\degree & 0.2210\degree & 0.6153\degree & 5.6263\degree \\\specialrule{.15em}{.0em}{.0em} \multirow{2}[0]{*}{\textbf{St. Mary Church}} & \textbf{Position Error (m)} & 0.1479 m & 0.0689 m & 0.1479 m & 0.9518 m & 13.3455 m \\\cline{2-7} & \textbf{Angle Error (degrees)} &0.4671\degree & 0.1814\degree & 0.4671\degree & 3.5267\degree & 35.3109\degree\\\specialrule{.15em}{.0em}{.0em} \multirow{2}[0]{*}{\textbf{King's College}} & \textbf{Position Error (m)} & 0.0877 m & 0.0533 m & 0.0877 m & 0.1332 m & 0.2108 m\\\cline{2-7} & \textbf{Angle Error (degrees)} & 0.1476\degree & 0.0880\degree & 0.1476\degree & 0.2613\degree & 0.4694\degree \\\specialrule{.15em}{.0em}{.0em} \multirow{2}[0]{*}{\textbf{Great Court}} & \textbf{Position Error (m)} & 0.5098 m & 0.2520 m & 0.5098 m & 1.5401 m & 14.7130 m\\\cline{2-7} & \textbf{Angle Error (degrees)} & 0.3526\degree & 0.1489\degree & 0.3526\degree & 1.3117\degree & 12.8685\degree \\\specialrule{.15em}{.0em}{.0em} \end{tabular} \label{tab:shop} \label{tab:hospital} \label{tab:church} \label{tab:king} \label{tab:court} \label{tab:street} \end{sidewaystable*} \subsection{Outdoor Datasets} We used the datasets from the Cambridge Landmarks Database \citep{posenet,kendall2017geometric} to test the localization performance of the proposed method in the outdoor scenarios. The images in these datasets were captured at different times under different lighting and weather conditions and contain a lot of urban clutter which increases the challenges for precise localization of camera poses. As the Cambridge Landmarks Database does not contain dense point clouds, we used the COLMAP's Multi View Stereo Pipeline \citep{colmapmvs} to generate dense point clouds for these datasets. Table \ref{tab:shop} reports the median errors for the estimated positions and orientations of the cameras for the query images for the outdoor datasets. We also report the percentile errors for the 25\%, 50\%, 75\% and 90\% of the query images in these datasets for the estimated camera poses. \subsubsection{Shop Facade Dataset} The Shop Facade Dataset \citep{posenet} from the Cambridge Landmarks Database is composed of the images of the intersection of two streets in Cambridge. The images mainly focus on the shops at the intersection. It covers an area of more than $900\ m^2$. It contains a total of 334 images with 103 images in the query set. We used the standard train-test split as defined by the authors of the dataset. Our proposed technique was able to localize all the images in the query set. \subsubsection{Old Hospital Dataset} The Old Hospital dataset \citep{posenet} contains 1077 images. There are 182 query images in the train-test split defined by the dataset's authors. The dataset covers an area of $2000\ m^2$. This dataset suffers particularly from the challenges of repetitive patterns, as well as high symmetry due to similar constructions on both sides of the centre of the building. The localization results are shown in Table \ref{tab:hospital}. \subsubsection{St. Mary Church Dataset} The St. Mary Church Dataset \citep{posenet} is composed of 2017 images of the Great St. Mary Church in Cambridge. It encompasses an area of $4800\ m^2$. Many of the images contain occlusions caused by pedestrians and other urban clutter due to which it becomes challenging to localize images in the 3D point cloud. We used the query set defined by the authors of the dataset which contains $530$ images for the evaluation of our technique, while the remaining 2D images were used to train the Descriptor-Matcher. Our technique successfully localized all the images in the query set. \subsubsection{King's College Dataset} This dataset covers the location and building of the King's College, which is one of the constituent colleges of the University of Cambridge \citep{posenet}. It consists of 1563 images captured with the camera of a smart phone. King's College covers an area of more than $5600\ m^2$. We used the train-query split of images defined by the authors of the dataset. There are 343 images in the query set. Table \ref{tab:king} shows the results of our technique on the dataset. \subsubsection{Trinity Great Court Dataset} Trinity Great Court is the main court (courtyard) of Trinity College, Cambridge. It is one of the largest enclosed courtyards in Europe with an area of $8000\ m^2$. The train and test sets consist of $1532$ and $760$ number of images, respectively \citep{kendall2017geometric}. The proposed technique successfully localized all the images in the dataset. \subsection{Indoor Datasets} Most of the pose estimation techniques in the literature have either been evaluated only for outdoor scenarios or for very small indoor scenes (e.g. tested for a maximum volume of $6m^3$ on Seven Scenes Database \citep{sevenscenes} ). Indoor localization of images is a more challenging problem compared to the outdoor settings \citep{idl}. Due to similar items (e.g., furniture) and the same construction patterns (e.g., cubicle shape of rooms, similar patterns on floor or ceiling, stairs), it is possible that different regions of the building look very similar, which greatly increases the possibility of wrong matches and incorrect camera pose estimation. On the other hand, indoor localization is a more useful application of image localization as many of the traditional localization methods, such as GPS based localization, do not work properly in indoor settings. To evaluate the performance of our technique on practical indoor localization scenarios, we used the Kitchen and Living Room Datasets from the Stanford RGB Localization Database \citep{valentin2016learning} and Baidu Indoor Localization dataset \citep{idl}. Table \ref{tab:idl} shows the median positional and rotational errors along with the percentile errors for the intervals of 25\%, 50\%, 75\%, and 90\% data on the indoor datasets. \subsubsection{Kitchen Dataset} This dataset contains RGB images and a 3D model of a Kitchen in an apartment. It is part of the Stanford RGB Localization Database \citep{valentin2016learning}. It covers a total volume of $33m^3$. The 2D images and the 3D point cloud were created with a Structure.io\footnote{https://structure.io/structure-sensor} 3D sensor coupled with an iPad. Both sensors were calibrated and temporally synced. We randomly selected $20\%$ of the images for the query set while used the remaining images for training the Descriptor-Matcher. Our technique successfully localized all the query images in the 3D model with high accuracy. We were able to estimate the 6-DOF poses of more than 90\% of the images with errors less than 4 cm and withing a degree, as shown in Table \ref{tab:idl}. \begin{sidewaystable*}[htbp] \caption{Median and percentile localization errors for the Kitchen, Living Room and Baidu Indoor Localization Datasets. P stands for percentile, e.g., P 25\% means the maximum error for 25\% of the data when errors are sorted in the ascending order. m stands for metres} \centering \begin{tabular}{|l|l|c|c|c|c|c|} \specialrule{.15em}{.0em}{.0em} \textbf{Indoor Datasets $\downarrow$} & \textbf{Errors $\downarrow$ \textbackslash{} Metrics $\rightarrow$} & \textbf{Median} & \textbf{P 25\%} & \textbf{P 50\%} & \textbf{P 75\%} & \textbf{P 90\%} \\\specialrule{.15em}{.0em}{.0em} \multirow{2}[0]{*}{\textbf{Kitchen}} & \textbf{Position Error (m)} & 0.0117 m & 0.0066 m & 0.0117 m & 0.0223 m & 0.0395 m\\\cline{2-7} & \textbf{Angle Error (degrees)} & 0.2128\degree & 0.1448\degree & 0.2128\degree & 0.3845\degree & 0.6399\degree \\\specialrule{.15em}{.0em}{.0em} \multirow{2}[0]{*}{\textbf{Living Room}} & \textbf{Position Error (m)} & 0.0101 m & 0.0059 m & 0.0101 m & 0.0180 m & 0.0470 m\\\cline{2-7} & \textbf{Angle Error (degrees)} & 0.3254\degree & 0.2011\degree & 0.3254\degree & 0.4877\degree & 1.6218\degree \\\specialrule{.15em}{.0em}{.0em} \multirow{2}[0]{*}{\textbf{Baidu Indoor Localization}} & \textbf{Position Error (m)} & 0.6930 m & 0.2020 m & 0.6930 m & 10.44 m & 24.55 m\\\cline{2-7} & \textbf{Angle Error (degrees)} & 2.30\degree & 0.6105\degree & 2.30\degree & 13.72\degree & 22.05\degree \\\specialrule{.15em}{.0em}{.0em} \end{tabular} \label{tab:idl} \end{sidewaystable*} \subsubsection{Living Room Dataset} The Living Room Dataset is part of the Stanford RGB Localization Database \citep{valentin2016learning} and comprises the 3D model and 2D images of a living area in an apartment with a total volume of $30m^3$. This dataset was also captured with a combination of Structure.io sensor and iPad cameras. For the quantitative evaluation on this dataset, $20\%$ of the images were randomly held out for query set, while the remaining images were used for the training set. We were able to localize all the images in the query set with more than 90\% localizations within a 5 cm error (Table \ref{tab:idl}). \begin{figure*}[htbp] \centering \begin{subfigure}[htbp]{1\textwidth} \centering \includegraphics[width=\textwidth]{PICIDLCropped.png} \caption{Top view} \label{fig:idl1} \end{subfigure} \hfill \begin{subfigure}[htbp]{1\textwidth} \centering \includegraphics[width=\textwidth]{PICIDL2Cropped.png} \caption{Side view} \label{fig:idl2} \end{subfigure} \caption{Different views of the point cloud of the shopping mall from Baidu Indoor Localization Dataset \citep{idl}. The large scale and repetitive structures in the dataset make it extremely challenging to localize 2D images in the point cloud compared to other indoor datasets. } \label{fig:idl} \end{figure*} \subsubsection{Baidu Indoor Localization Dataset} The Baidu Indoor Localization Dataset \citep{idl} is composed of a 3D point cloud of a multi-storey shopping mall created with the scans from a LIDAR scanner and a database of images with ground truth information for camera positions and orientations. The 3D point cloud contains more than 67 million points. Figure \ref{fig:idl} shows different views of the point cloud of the mall. The images in the dataset are captured with different cameras and smart phones and at different times which increases the complexity of the dataset. Moreover, many of the images contain occlusions due to the persons shopping in the mall. We randomly selected $10\%$ of the images for the query set, while the remaining images were used for the training set. Our technique successfully localized 78.2\% of the images in the query set. Despite the challenges of the dataset, we achieved a median pose estimation error of 0.69 m and 2.3 degrees as shown in Table \ref{tab:idl}. \begin{sidewaystable*}[htbp] \caption{Median errors for position and orientation estimation of our technique compared to other approaches on Cambridge Landmarks outdoor datasets. Pos stands for median positional error in meters and Ang stands for rotational error in degrees. NA: Results not available. Best results are shown in \textbf{bold} and second best results are \underline{underlined}.} \centering \begin{tabular}{|A|R|R|R|R|R|R|R|R|R|R|R|R|R|R|} \hline \textbf{Methods$\rightarrow$} & \multicolumn{2}{V|}{\textbf{PoseNet \citep{posenet} ICCV'15}} & \multicolumn{2}{V|}{\textbf{Geom. Loss Net \citep{kendall2017geometric} CVPR'17}} & \multicolumn{2}{V|}{\textbf{VLocNet \citep{valada2018deep} ICRA'18}} & \multicolumn{2}{V|}{\textbf{DSAC \citep{brachmann2017dsac} CVPR'17}} & \multicolumn{2}{V|}{\textbf{Active Search \citep{sattler2017efficient} TPAMI'17}} & \multicolumn{2}{V|}{\textbf{DSAC++ \citep{brachmann2018learning} CVPR'18}} &\multicolumn{2}{V|}{\textbf{Ours}} \\ \hline \textbf{Methods' Type$\rightarrow$} & \multicolumn{2}{V|}{\textbf{Network-based}} & \multicolumn{2}{V|}{\textbf{Network-based}} & \multicolumn{2}{V|}{\textbf{Network-based}} & \multicolumn{2}{V|}{\textbf{Network + RANSAC}} & \multicolumn{2}{V|}{\textbf{SfM-based}} & \multicolumn{2}{V|}{\textbf{Network + RANSAC}} &\multicolumn{2}{V|}{\textbf{2D to 3D Descriptors Matching}} \\ \hline \textbf{Datasets$\downarrow$} & \textbf{Pos (m)} & \textbf{Ang} & \textbf{Pos (m)} & \textbf{Ang} & \textbf{Pos (m)} & \textbf{Ang} & \textbf{Pos (m)} & \textbf{Ang} & \textbf{Pos (m)} & \textbf{Ang} & \textbf{Pos (m)} & \textbf{Ang} & \textbf{Pos (m)} & \textbf{Ang}\\ \hline \textbf{Shop Facade} & 1.46 & 4.04\degree & 0.88 & 3.78\degree & 0.593 & 3.529\degree & \underline{0.09} & \textbf{0.4\degree} & 0.12 & \textbf{0.4\degree} & \underline{0.09} & \textbf{0.4\degree} & \textbf{0.086} & \underline{0.779\degree} \\ \hline \textbf{Old Hospital} & 2.31 & 2.69\degree & 3.2 & 3.29\degree & 1.075 & 2.411\degree & 0.33 & 0.6\degree & 0.44 & 1\degree & \underline{0.24} & \underline{0.5\degree} & \textbf{0.129} & \textbf{0.221\degree} \\ \hline \textbf{King's College} & 1.92 & 2.70\degree & 0.88 & 1.04\degree & 0.836 & 1.419\degree & 0.30 & 0.5\degree & 0.42 & 0.6\degree & \underline{0.23} & \underline{0.4\degree} & \textbf{0.087} & \textbf{0.147\degree} \\ \hline \textbf{Great Court } & NA & NA & 6.83 & 3.47\degree & NA & NA & 2.80 & 1.5\degree & NA & NA & \underline{0.66} & \underline{0.4\degree} & \textbf{0.509} & \textbf{0.352\degree} \\ \hline \textbf{St. Mary Church} & 2.65 & 4.24\degree & 1.57 & 3.32\degree & 0.631 & 3.906\degree & 0.55 & 1.6\degree & \underline{0.19} & \underline{0.5\degree} & 0.20 & 0.7\degree & \textbf{0.147} & \textbf{0.467\degree} \\ \hline \end{tabular} \label{tab:comparison} \end{sidewaystable*} \subsection{Comparison with Other Approaches} The proposed technique for image localization in point clouds is based on a novel concept of directly matching the descriptors extracted from images and point clouds. The SfM based techniques are based on the matching of 2D features and require the point cloud to be generated from SfM pipeline. On the other hand, our technique can work with point clouds created with any 3D scanner or generated with any method and has no dependency on any information from SfM. The network based regression methods train directly to regress the poses of the images. However, this causes the networks to over-fit on the ground truth poses. Therefore at test time, they only produce good results for the images with poses close to the training ones \citep{sattler2019understanding}. In our technique, training of the Descriptor-Matcher is carried out on the feature descriptors with no information of the poses or the location of the points. This ensures that the Descriptor-Matcher does not over-fit on the training poses, rather it learns to find a mapping between the 2D and 3D descriptors. The final pose estimation is based on the principles of geometry which produce better pose estimates compared to end-to-end trained methods \citep{sattler2019understanding}. Therefore, the proposed method benefits from the non-reliance on SfM pipeline like the network based methods, as well as the ability to use geometry based pose estimation similar to the SfM based methods. For quantitative analysis, we provide a comparison of our results with the state-of-the-art methods for camera pose localization on the common datasets between the various approaches. We compare the median values of errors in the estimation of camera position and rotation on the outdoor datasets of Cambridge Landmarks Database \citep{posenet}, as mostly only the median errors are reported by other methods. The results of the compared methods are not available for Baidu Indoor Localization Dataset or Stanford RGB Localization Database. Our proposed method achieved competitive or superior localization accuracy to the state-of-the-art methods for 6-DOF pose estimation on all the datasets. Table \ref{tab:comparison} shows the median values for position and rotational errors of our technique compared to other prominent methods. \section{Conclusion}\label{conclusion} This paper proposed a novel method to directly match descriptors from 2D images with those from 3D point clouds, where the descriptors are extracted using 2D and 3D feature extraction techniques, respectively. We have shown that direct matching of 2D and 3D feature descriptors is an unconstrained and reliable method for 6-DOF pose estimation in point clouds. Our approach results in a pipeline which is much simpler compared to SfM or network based methods. Extensive quantitative evaluation has demonstrated that the proposed method achieved competitive performance with the state-of-the-art methods in the field. Moreover, unlike SfM based techniques, the proposed method can be used with point clouds generated with any type of 3D scanners and can work in both indoor and outdoor scenarios. \section*{Acknowledgements} This work was supported by the SIRF scholarship from the University of Western Australia (UWA) and by the Australian Research Council under Grant DP150100294. \balance
{'timestamp': '2020-06-01T02:10:30', 'yymm': '2005', 'arxiv_id': '2005.14502', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14502'}
arxiv
\section{Introduction} Molecular communication (MC) uses molecules as carriers of information. Molecular communication is envisioned to be applicable in a wide range of engineering and medical applications, especially as a means to realize communications among engineered biological nanomachines (see \cite{pierobon2010physical, nakano2012molecular, guo2015molecular, survey:medicine}). In diffusion-based MC, molecules are released into the medium by molecular transmitters. Information is coded by the transmitter in the type, number, or release time of the molecules. The released molecules randomly diffuse in the medium, with some reaching the molecular receivers. The receiver decodes the message sent by the transmitter based on the number of sensed molecules (see \cite{kuran2011modulation, arjmandi2013diffusion, srinivas2012molecular} for some examples of modulation schemes). Broadly speaking, two main types of diffusion-based MC exists: microscale MC and macroscale MC. In microscale MC, a small number of molecules are released into the medium by transmitters. The movement of each molecule is random and follows Brownian motion. On the other hand, in macroscale MC, a large number of molecules are released into the medium (the number of released molecules is in the order of moles). Macroscale MC is of interest as an alternative to electromagnetic wave-based systems in certain media \cite{guo2015molecular, farsad2016comprehensive}. In macroscale MC, instead of focusing on the location of individual molecules, by the law of large numbers, the \emph{average concentration} of molecules is described by Fick's law of diffusion, which is a \emph{deterministic} differential equation. Everything is described by deterministic equations until this point. However, various sources of noise or imperfection could be considered for molecular transmitters and receivers \cite{farsad2016comprehensive, gohari2016information}. In particular, the literature on MC usually associates a measurement noise to the receivers. The variance of this measurement noise depends on the concentration level of molecules at the receiver \cite{einolghozati2012collective}. In particular, a commonly used measurement noise is the ``Poisson particle counting noise" where the measurement follows a Poisson distribution whose mean is proportional to the concentration of molecules at the time of measurement. \textbf{Motivation:} One of the unique features of MC with no parallel in classical wireless communication is \emph{chemical reactions}: different types of molecules can react with each other and form new types of molecules in the medium. This feature of MC poses a challenge in macroscale MC since equations describing chemical reaction with diffusing particles are \emph{nonlinear} partial differential equations with no closed-form solutions\cite{noclosedform:1,noclosedform:2,noclosedform:3}. In other words, there is no analytical closed-form formula that describes the variations in the concentration of molecules over time and space for given boundary conditions, inputs to the medium, and system parameters such as the diffusion and reaction rate constants. These equations are commonly solved by numerical methods. While numerical techniques (such as the finite difference method and the finite element method) can provide accurate solutions, they require extensive computational resources. More importantly, these solutions are not generalizable: assume that we have solved the reaction-diffusion equations for one particular release pattern of molecules by the transmitters into the medium. Next, if we make some changes to the release pattern of molecules, we should start all over again and solve the reaction-diffusion equations again for the new release pattern. Numerical methods provide little insight into how the solution would change if the input or parameters of the medium change. This has a major drawback for the design of coding and modulation schemes, where we wish to optimize and find the best possible release pattern. A tractable (even if approximate) model for the solution of the reaction-diffusion systems is required to design codes or modulation schemes. Only with such a model can one formally the optimality of certain waveforms for a given communication problem. \textbf{Our contribution:} We apply the perturbation theory to design modulation schemes among manufactured devices in macroscale MC systems involving chemical reactions. Perturbation theory is a set of mathematical methods for finding approximate solutions. It was originally proposed to calculate the motions of planets in the solar system, which is an intractable problem (as the so-called three-body problem shows). The theory has been broadly applied in different scientific areas such as physics and mechanics for solving algebraic equations with no analytical solutions. While the perturbation theory has been used in the study of differential equations in general and in the context of fiber optics communication systems \cite{pert-opt-cite}, to the best of our knowledge it has not been hitherto utilized in molecular communication.\footnote{ Note that \cite{singularpert} uses the idea of \emph{ singular perturbation} which should not be confused with the \emph{perturbation theory}.} Just as non-linear functions can be locally approximated by the first terms of their Taylor series, perturbation theory shows that non-linear reaction-diffusion equations can be also approximated by their lower order terms. Our main contribution is a proposal to design coding and modulation schemes based on the lower order terms, which admit closed-form solutions. In other words, we provide an analytically tractable (approximate) model for studying chemical reactions in molecular communication. The accuracy of the model can be increasingly improved by including more terms from the Taylor series. We concretely illustrate the perturbation method by considering the following reaction-diffusion system in which molecules of type $\mathtt{A}$ and $\mathtt{B}$ react with each other in the medium and produce molecules of type $\mathtt{C}$: \begin{align}\label{ex1:reactionN1} \mathtt{A} + \mathtt{B} \underset{\lambda_2}{\stackrel{\lambda_1}{\rightleftharpoons}} \mathtt{C}. \end{align} Forward and backward reaction rates $\lambda_1$ and $\lambda_2$ represent the speed at which the chemical reaction takes place in the forward and backward directions. This reaction-diffusion system is chosen because it is one of the simplest chemical reactions with no closed-form solution. This basic reaction appears in many contexts, e.g. $\text{base}+\text{acid}\rightarrow \text{salt}$, or $NH_3+{H_2O}\rightarrow {NH_4OH}$, $\text{ADP}+\text{P}\rightarrow \text{ATP}$, or $ \text{lipoprotein} + \text{PRAP1} \underset{\lambda_2}{\stackrel{\lambda_1}{\rightleftharpoons}}\text{PRAP1-lipoprotein}$ in biology. It is used in \cite{farahnak2018medium:j:16} to design a communication strategy between engineered devices. It may be also used in chemical computing, \emph{e.g.} to implement a binary AND gate (as the product molecules are produced only when both reactants are present). The application considered in this paper is a communication system involving three engineered devices, two transmitters, and one receiver: the two transmitters release molecules of type $\mathtt A$ and $\mathtt B$ respectively, and the receiver senses the product molecules of type $\mathtt C$. The goal is to compute the best transmission waveform for each transmitter so that the receiver has minimum error probability to decode the messages of both transmitters (a multiple access channel setting). In this setting, we find the optimal waveforms that minimize the error probability in the low rate reaction regime (or in the small transmission time interval regime). In particular, we show that instead of using a continuous release waveform, it is optimal for the transmitters to release molecules at two time instances. To illustrate the broad applicability of our technique, we also discuss other reaction-diffusion systems (different from \eqref{ex1:reactionN1}) in the Appendix \ref{ex2,3}. These examples cover scenarios where the chemical reaction is either facilitating or impeding effective communication. \textbf{Related works:} The math literature on nonlinear partial differential equations (PDEs) studies different aspects of these equations, such as the existence and uniqueness of the solution, semianalytical solutions, numerical solutions, etc. Since most PDEs do not have closed-form solutions, showing the existence and in some cases, uniqueness of solution are important topics in the theory of PDEs. Unlike ordinary differential equations (ODE) which have a straightforward theorem for the existence and uniqueness of a solution, there is no general method for PDEs to show the existence and uniqueness of the solution. For instance, the existence and smoothness of solutions for the Navier-Stokes equations that describe the motion of a fluid in space are fundamental open problems in physics. Semianalytical techniques are series expansion methods in which the solution is expressed as an infinite series of explicit functions. Semianalytical techniques include the Adomian decomposition method, Lyapunov artificial small parameter method, homotopy perturbation method, and perturbation methods \cite{liao2003beyond,liao2012homotopy}. There are many numerical methods for solving PDEs which are classified in terms of complexity and stability of the solution. The finite element method, finite difference method, spectral finite element method, meshfree finite element method, discontinuous Galerkin finite element method are some examples of numerical techniques for solving PDEs \cite{numericalmethode:1,noclosedform:2}. For example, in the finite difference method, we partition the domain using a mesh and approximate derivatives with finite differences computed over the mesh. One of the challenges of using this method is determining the appropriate mesh size to guarantee the stability of the solution.\footnote{ Our own experiment with this method indicates that choosing the appropriate mesh size is particularly challenging when we have a reaction-diffusion system involving molecules that have very different diffusion constants (especially when one diffusion constant is more than ten times another diffusion constant).} There are some prior works in the literature on chemical physics that utilize the perturbation theory. For instance, the average survival time of diffusion-influenced chemical reactions is studied in \cite{pagitsas1992perturbation:e:1:1}. In \cite{kryvohuz2014nonlinear:e:1:2} some classes of chemical kinetics (describe by ODEs) have been solved by the perturbation theory. However, the setup and approach in these problems differ from the one encountered in MC. Due to their evident importance to MC, chemical reactions have been the subject of various studies. A molecular communication system involves transmitters, receivers, and the molecular media; chemical reactions may occur in each of these individual building blocks. Transmitters could use chemical reactions to produce signaling molecules \cite{bi2019chemical:j:9}. This is a chemical reaction inside the transmitter unit. On the receiver side, one might have ligand (or other types of) receptors on the surface of the receiver which react with incoming molecules. These receptors have been the subject of various studies, e.g., see \cite{chou2015impact:e:2:2:3,Ligand0, Ligand1, Ligand2, Ligand3,kuscu2018modeling:e:2:3:2, ahmadzadeh2016comprehensive:e:2:3:1,chou2014molecular:e:2:2:4}. Finally, chemical reactions have also been considered in the communication medium. This aspect of chemical reactions is of interest in this work. It is pointed out that chemical reactions could be used to suppress signaling molecules and thereby reduce intersymbol interference (ISI) and the signal-dependent measurement noise \cite{noclosedform:1,cho2017effective:j:12}, or to amplify the signal \cite{nakano2011repeater:F:22}. Complicated propagation patterns can be obtained by using chemical reactions\cite{nakano2015molecular:F:19}, and negative molecular signals could be implemented using chemical reactions \cite{farsad2016molecular:F:16,wang2014transmit:F:20,mosayebi2017type:F:21}. Notably, chemical reactions are shown to be beneficial for coding and modulation design \cite{farsad2016molecular:F:16,farahnak2018medium:j:16,noclosedform:2,nakano2015molecular:F:19,wang2014transmit:F:20,mosayebi2017type:F:21}. Since solving the reaction-diffusion equations is intractable, these works either use numerical simulations to back up the presented ideas or else simplify the reaction-diffusion process via idealized assumptions about chemical reactions. Authors in \cite{cao2019chemical:j:ro} provide an iterative numerical algorithm for solving reaction-diffusion equations. In \cite{farsad2017novel:e:2:2:2}, a neural network is used as the decoder in a medium with chemical reactions. This paper is organized as follows: in Section \ref{sec::generalperturbation}, we illustrate the perturbation method for solving reaction-diffusion equations through an example. In Section \ref{Sec:Mod} we design modulation schemes for our example in Section \ref{sec::generalperturbation}. In Section \ref{sec:Val}, we validate our model through numerical simulation. Finally concluding remarks and future work are given in Section \ref{Conclusion and Future Work}. \textbf{Notations and Remarks:} For functions $u_i(x,t)$ and $v_i(x,t)$, we define index convolution as follows: \begin{align}\label{dicreteconv} (u_{0:i-1}*^d v_{0:i-1})(x,t)=\sum_{j=0}^{i-1} u_{j}(x,t)v_{i-1-j}(x,t). \end{align} For two functions $u(x,t)$ and $v(x,t)$, convolution in both time and space is denoted by $**$ and defined as follows: \begin{align}(u**v)(x,t)=\int_{x'}\int_{t'}u(x,t)v(x-x',t-t')dx'dt'.\label{eqnconvts} \end{align} The concentration of molecules of type $\mathtt{A}$ at location $x$ and time $t$ is denoted by $[\mathtt{A}](x,t)$. Similarly, we use $[\mathtt{B}](x,t)$ and $[\mathtt{C}](x,t)$ to denote the concentration of molecules of types $\mathtt{B}$ and $\mathtt{C}$ respectively. We write $[\mathtt{A}](x,t)$ as a series in the perturbation method and use $[\mathtt{A}]_{i}(x,t)$ as the coefficient for the $i$th term in the expansion. For simplicity, we sometimes show a function without its arguments, e.g. we write $[\mathtt{A}]_{i}$ or $[\mathtt{A}]$ instead of $[\mathtt{A}]_{i}(x,t)$ or $[\mathtt{A}](x,t)$. Finally, all chemical reactions are considered in the time interval $[0,T]$ for some $T>0$. \section{Solving Reaction-Diffusion Equations via the Perturbation Method}\label{sec::generalperturbation} The perturbation method provides an explicit analytical solution in the form of an infinite series of functions. One can approximate the solution by taking a finite number of terms from this series. In this paper, we use the perturbation method to obtain an analytical model for the reaction-diffusion equations, which can be used for molecular communication. Our working example in the paper is as follows: consider two molecular transmitters $\mathsf \mathsf T_{\mathtt {A}}$ and $\mathsf \mathsf T_{\mathtt {B}}$, which release molecules $\mathtt{A}$ and $\mathtt{B}$, respectively. Molecules of type $\mathtt{A}$ and $\mathtt{B}$ react with each other in the medium and produce molecules of type $\mathtt{C}$ as follows: \begin{align}\label{ex1:reaction} \mathtt{A} + \mathtt{B} \underset{\lambda_2}{\stackrel{\lambda_1}{\rightleftharpoons}} \mathtt{C} \end{align} We assume a molecular receiver $\mathsf \mathsf R_{\mathtt {C}}$, which measures the concentration of molecules of type $\mathtt{C}$ at its location in order to detect the messages of the two transmitters. For simplicity, assume that the transmitters and receiver are placed on a one-dimensional line, with $\mathsf T_{\mathtt {A}}$, $\mathsf T_{\mathtt {B}}$, and $\mathsf R_{\mathtt {C}}$ being located at $x=0$, $x=d_\mathtt{B}$, and $x=d_R$ respectively. This assumption is just for the simplicity of exposition; the problem could be solved in two or three dimensions and we also provide simulation results in dimensions two and three in Section \ref{sec:Val}. We assume that the transmitters and receivers are small in size and view them as points on the real line; the transmitter and receiver are considered to be transparent, not impeding the diffusion of the released molecules (assumption of point sources is adopted for simplicity and is common in the MC literature, e.g., \cite{farahnak2018medium:j:16,noclosedform:2,farsad2016molecular:F:16}). This is depicted in Fig. \ref{fig:ex1}. Further details of the communication model are described in Section \ref{Sec:Mod} where we design a modulation scheme. In the rest of this section, we are merely interested in solving the reaction-diffusion equation describing reaction \eqref{ex1:reaction}. \begin{figure} \centering \includegraphics[trim={1cm 0cm 0cm 0cm}, scale=0.25]{Slide11.png} \caption{The system model} \label{fig:ex1} \vspace{-2.5em} \end{figure} Let $\gamma=\lambda_2/\lambda_1$ be the ratio of the backward and forward reaction rates, and set $\lambda=\lambda_1,\lambda_2=\gamma\lambda$ for some $\lambda\geq 0$. The following equation describes the system dynamic: \begin{align} &\frac{\partial[\mathtt{A}]}{\partial t}=D_\mathtt{A}~\frac{\partial^{2}[\mathtt{A}]}{{\partial x}^{2}}-\lambda~[\mathtt{A}][\mathtt{B}]+\gamma \lambda [\mathtt{C}]+f_\mathtt{A}(x,t),\label{A:ex1eq}\\ & \frac{\partial[\mathtt{B}]}{\partial t}=D_\mathtt{B}~\frac{\partial^{2}[\mathtt{B}]}{{\partial x}^{2}}-\lambda~[\mathtt{A}][\mathtt{B}]+\gamma \lambda [\mathtt{C}]+f_\mathtt{B}(x,t),\label{B:ex1eq}\\ & \frac{\partial[\mathtt{C}]}{\partial t}=D_\mathtt{C}~\frac{\partial^{2}[\mathtt{C}]}{{\partial x}^{2}}+\lambda~[\mathtt{A}][\mathtt{B}]-\gamma \lambda [\mathtt{C}]\label{C:ex1eq}, \end{align} where $f_\mathtt{A}(x,t),f_\mathtt{B}(x,t)$ are the released concentration of molecules (called the transmission waveforms), and $D_\mathtt{A}, D_\mathtt{B}, D_\mathtt{C}$ are the diffusion constants. The initial and boundary conditions are set to zero. We are interested in the solution for time $t\in[0,T]$. For the special case of $\lambda=0$, \emph{i.e.,} when there is no reaction, the above system of equations is linear and tractable. Consider a solution of these equations in the form, $[\mathtt{A}](x,t)=\sum_{i=0}^{\infty}\lambda^{i} [\mathtt{A}]_{i}(x,t)$, $[\mathtt{B}](x,t)=\sum_{i=0}^{\infty}\lambda^{i} [\mathtt{B}]_{i}(x,t)$ and $[\mathtt{C}](x,t)=\sum_{i=0}^{\infty}\lambda^{i} [\mathtt{C}]_{i}(x,t)$ for some Taylor series coefficients $[\mathtt{A}]_{i}(x,t)$, $[\mathtt{B}]_{i}(x,t)$ and $[\mathtt{C}]_{i}(x,t)$. By substituting these expressions in \eqref{A:ex1eq}, \eqref{B:ex1eq} and \eqref{C:ex1eq}, we obtain \begin{align}\label{New1h} &\frac{\partial}{\partial t}(\sum_{i=0}^{\infty}\lambda^{i} [\mathtt{A}]_{i}) =D_\mathtt{A}~\frac{\partial^{2}}{{\partial x}^{2}}(\sum_{i=0}^{\infty}\lambda^{i}[\mathtt{A}]_{i})-\lambda (\sum_{i=0}^{\infty}\lambda^{i} [\mathtt{A}]_{i})(\sum_{i=0}^{\infty}\lambda^{i}[\mathtt{B}]_{i})+\gamma\lambda \sum_{i=0}^{\infty}\lambda^{i}[\mathtt{C}]_{i} +f_\mathtt{A}(x,t), \end{align} \begin{align}\label{New2h:b} &\frac{\partial}{\partial t}(\sum_{i=0}^{\infty}\lambda^{i} [\mathtt{B}]_{i}) =D_\mathtt{B}~\frac{\partial^{2}}{{\partial x}^{2}}(\sum_{i=0}^{\infty}\lambda^{i}[\mathtt{B}]_{i})-\lambda (\sum_{i=0}^{\infty}\lambda^{i} [\mathtt{A}]_{i})(\sum_{i=0}^{\infty}\lambda^{i} [\mathtt{B}]_{i})+\gamma\lambda \sum_{i=0}^{\infty}\lambda^{i}[\mathtt{C}]_{i}+ f_\mathtt{B}(x,t), \end{align} \begin{align}\label{New3h} &\frac{\partial}{\partial t}(\sum_{i=0}^{\infty}\lambda^{i} [\mathtt{C}]_{i}) =D_\mathtt{C}~\frac{\partial^{2}}{{\partial x}^{2}}(\sum_{i=0}^{\infty}\lambda^{i}[\mathtt{C}]_{i})+\lambda (\sum_{i=0}^{\infty}\lambda^{i} [\mathtt{A}]_{i})(\sum_{i=0}^{\infty}\lambda^{i} [\mathtt{B}]_{i})-\gamma\lambda \sum_{i=0}^{\infty}\lambda^{i}[\mathtt{C}]_{i} . \end{align} Equations \eqref{New1h}, \eqref{New2h:b}, and \eqref{New3h} could be viewed as power series in $\lambda$ for fixed values of $x$ and $t$. Matching the coefficients of $\lambda^i$ on both sides of the equation, we obtain the following: \begin{align}\label{zerosol} \frac{\partial [\mathtt{A}]_{0}}{\partial t}=D_\mathtt{A}~\frac{\partial^{2}[\mathtt{A}]_{0}}{{\partial x}^{2}}+f_\mathtt{A}(x,t),~~ \frac{\partial [\mathtt{B}]_{0}}{\partial t}=D_\mathtt{B}~\frac{\partial^{2} [\mathtt{B}]_{0}}{{\partial x}^{2}}+f_\mathtt{B}(x,t),~~ \frac{\partial [\mathtt{C}]_{0}}{\partial t}=D_\mathtt{C}~\frac{\partial^{2} [\mathtt{C}]_{0}}{{\partial x}^{2}}. \end{align} For $i\geq 1$ we obtain \label{othersolA} \begin{align} &\frac{\partial[\mathtt{A}]_{i}}{\partial t}=D_\mathtt{A}~\frac{\partial^{2}[\mathtt{A}]_{i}}{{\partial x}^{2}}-[\mathtt{A}]_{0:i-1}*^d [\mathtt{B}]_{0:i-1}+\gamma[\mathtt{C}]_{i-1},\label{othersolA} \\ &\frac{\partial[\mathtt{B}]_{i}}{\partial t}=D_\mathtt{B}~\frac{\partial^{2}[\mathtt{B}]_{i}}{{\partial x}^{2}}-[\mathtt{A}]_{0:i-1}*^d [\mathtt{B}]_{0:i-1}+\gamma[\mathtt{C}]_{i-1},\label{othersolB} \\ &\frac{\partial[\mathtt{C}]_{i}}{\partial t}=D_\mathtt{C}~\frac{\partial^{2}[\mathtt{B}]_{i}}{{\partial x}^{2}}-[\mathtt{A}]_{0:i-1}*^d [\mathtt{B}]_{0:i-1}-\gamma[\mathtt{C}]_{i-1},\label{othersolC} \end{align} where we used the index convolution defined in \eqref{dicreteconv}. The functions $[\mathtt{A}]_{i}(x,t)$, $[\mathtt{B}]_{i}(x,t)$ and $[\mathtt{C}]_{i}(x,t)$ could be find recursively by first computing $[\mathtt{A}]_{0}(x,t)$, $[\mathtt{B}]_{0}(x,t)$ and $[\mathtt{C}]_{0}(x,t)$ from \eqref{zerosol}, and then using \eqref{othersolA}-\eqref{othersolC} to compute $[\mathtt{A}]_{i}(x,t)$, $[\mathtt{B}]_{i}(x,t)$ and $[\mathtt{C}]_{i}(x,t)$ from $[\mathtt{A}]_{j}(x,t)$, $[\mathtt{B}]_{j}(x,t)$ and $[\mathtt{C}]_{j}(x,t)$ for $j\leq i-1$. \subsection{Limitation on the simulation time interval and a remedy} The perturbation method provides recursive equations to find the functions $[\mathtt{A}]_{i}(x,t)$ and $[\mathtt{B}]_{i}(x,t)$. However, one still needs to show that the power series $\sum_{i=0}^{\infty}\lambda^{i} [\mathtt{A}]_{i}(x,t)$ and $\sum_{i=0}^{\infty}\lambda^{i} [\mathtt{B}]_{i}(x,t)$ are convergent to functions that satisfy the original reaction-diffusion differential equation. Perturbation theory does not provide a general recipe for showing this convergence, and it should be done on a case-by-case basis. We show in Appendix \ref{AppA0 } that the series is convergent as long as $\lambda\leq \mathcal{O}(1/T)$, \emph{i.e.,} the radius of convergence of the series is proportional with the inverse of the total time period. In other words, we need $\lambda$ to be sufficiently small (or for $T$ to be sufficiently small). Provided that $T$ is sufficiently small, Appendix \ref{AppA0 } shows that the solution given by the perturbation method is equal to the true solution (satisfies the reaction-diffusion equations). Next, we propose an approach to tackle the above shortcoming if we wish to compute the solution for larger values of $T$: we can divide the time interval $T$ into $k$ subintervals of size $T/k$. Since the radius of convergence is of order $\mathcal{O}(\frac 1T)$, reducing the size of the interval by a factor of $k$ increases the radius of convergence by a multiplicative factor of $k$. Thus, we can first compute the solution in the interval $[0,T/k]$ and use the value at $T/k$ to compute the solution in the interval $[T/k,2T/k]$, etc. \subsection{Solving equations \eqref{zerosol}-\eqref{othersolC}} In order to solve \eqref{zerosol}, let $\phi_\mathtt{A}(x,t)$ be the solution of the following equation with diffusion coefficient $D_\mathtt{A}$: \begin{align}\label{greenA} \frac{\partial \phi_\mathtt{A}}{\partial t}=D_\mathtt{A}~\frac{\partial^{2}\phi_\mathtt{A}}{{\partial x}^{2}}+\delta(x)\delta(t). \end{align} We have \begin{align} \phi_\mathtt{A}(x,t)=\frac{1}{\sqrt{4\pi D_\mathtt{A} t}}\exp(-\frac{x^2}{4 D_\mathtt{A} t}),~ x\in \mathbb{R},~t\geq 0. \end{align} Similarly, we define $\phi_\mathtt{B}(x,t)$ and $\phi_\mathtt{C}(x,t)$ as the solutions of \begin{align}\label{greenBC} \frac{\partial \phi_\mathtt{B}}{\partial t}=D_\mathtt{B}~\frac{\partial^{2}\phi_\mathtt{B}}{{\partial x}^{2}}+\delta(x)\delta(t), \qquad \frac{\partial \phi_\mathtt{C}}{\partial t}=D_\mathtt{C}~\frac{\partial^{2}\phi_\mathtt{C}}{{\partial x}^{2}}+\delta(x)\delta(t). \end{align} Then, the solutions of \eqref{zerosol}, \eqref{othersolA}-\eqref{othersolC} are as follows: \begin{align}\label{ex1:A0,B0} &[\mathtt{A}]_{0}=\phi_\mathtt{A}**f_{\mathtt{A}},~~ [\mathtt{B}]_{0}=\phi_\mathtt{B}**f_{\mathtt{B}},~~[\mathtt{C}]_{0}=0, \end{align} and for $i\geq 1$, \begin{align} &[\mathtt{A}]_{i}=-\phi_\mathtt{A}**([\mathtt{A}]_{0:i-1}*^d[\mathtt{B}]_{0:i-1}+\gamma[\mathtt{C}]_{i-1}),\label{recu-eq1}\\ &[\mathtt{B}]_{i}=-\phi_\mathtt{B}**([\mathtt{A}]_{0:i-1}*^d [\mathtt{B}]_{0:i-1}+\gamma[\mathtt{C}]_{i-1}),\label{recu-eq2}\\ &[\mathtt{C}]_{i}=+\phi_\mathtt{C}**([\mathtt{A}]_{0:i-1}*^d [\mathtt{B}]_{0:i-1}-\gamma[\mathtt{C}]_{i-1}),\label{recu-eq3} \end{align} where $**$ stands for the two-dimensional convolution (see \eqref{eqnconvts}). In general, the perturbation method does not yield a closed-form analytical solution for the reaction-diffusion equation because it is not possible (in general) to find a closed-form solution for the recursive equations \eqref{recu-eq1}-\eqref{recu-eq3}. However, the following example indicates a special instance where a closed-form solution can be found. \begin{example}\label{exampleA1} Consider the special choice of $f_{\mathtt{A}}(x,t)=f_{\mathtt{B}}(x,t)=1 ,x\in \mathbb{R}^{d}, t\geq 0 $, $D_{{\mathtt{A}}}=D_{{\mathtt{B}}}$, and $\gamma=0$. While these input signals are not interesting, the convolutions in \eqref{recu-eq1}-\eqref{recu-eq3} can be explicitly worked out for this choice of input signals. Using symmetry, we have $[\mathtt{A}]_i(x,t)=[\mathtt{B}]_i(x,t)$ for $i\geq 0$. The zero and first terms of perturbation can be computed as follows: \begin{align} &[\mathtt{A}]_{0}(x,t)=\phi**f_{ \mathtt{A}}=\int_{0}^{t}\int_{x\in \mathbb{R}^{d}}\phi(x-x',t-t')f_{ \mathtt{A}}(x',t')dx'dt'=t. \end{align} We prove, by induction, that $[\mathtt{A}]_{i}(x,t)=(-1)^{i}\alpha_{i}t^{2i+1}$ where $\alpha_{i}=\sum_{j=0}^{i-1} \alpha_{j}\alpha_{i-1-j}/(2i+1), i\geq 1, $ and $\alpha_0=1$. We have: \begin{align} [\mathtt{A}]_{i}&=-\phi**\sum_{j=0}^{i-1}[\mathtt{A}]_{j}[\mathtt{A}]_{i-1-j}\nonumber\\ &=-\int_{0}^{t}\int_{x\in \mathbb{R}^{d}}\phi(x-x',t-t')\sum_{j=0}^{i-1}(-1)^{j}\alpha_{j}t'^{2j+1}(-1)^{i-1-j}\alpha_{i-1-j}t'^{2i-2j-1} dx'dt'\nonumber\\&=(-1)^{i}\frac{\sum_{j=0}^{i-1} \alpha_{j}\alpha_{i-1-j}}{2i+1}t^{2i+1}. \end{align} By induction, one can prove that $(1/3)^{i}\leq \alpha_{i}\leq (1/2)^i$. The solution of reaction-diffusion for this particular example is as follows: $[\mathtt{A}](x,t)=\sum_{i=0}^{\infty}\lambda^{i}[\mathtt{A}]_i=\sum_{i=0}^{\infty}\lambda^{i}(-1)^{i}\alpha_{i}t^{2i+1}$. \end{example} \subsection{Interpretation in terms of Picard's iterative process} An alternative way to understand the recursive equations \eqref{ex1:A0,B0}-\eqref{recu-eq3} is through Picard's iterative process. In this process, one converts the differential equation to an integral form and uses it to identify the Picard iteration operator. Consider the reaction-diffusion equations in \eqref{A:ex1eq}-\eqref{C:ex1eq}. To convert this system of differential equations to an integral form, we utilize the fact that the solution of the differential equation $ \frac{\partial[\mathtt{u}]}{\partial t}=D_\mathtt{u}~\frac{\partial^{2}[\mathtt{u}]}{{\partial x}^{2}}+g_{u}$ with zero initial and boundary condition is $u=\phi_{u}**g_{u}$ where $\phi_{u}$ is the solution of the differential equation for an impulse input (impulse response). Thus, from \eqref{A:ex1eq}-\eqref{C:ex1eq} we obtain \begin{align} &[\mathtt{A}](x,t)=\phi_{\mathtt A}**(-\lambda[\mathtt{A}][\mathtt{B}]+\gamma\lambda[\mathtt{C}]+f_{\mathtt{A}}(x,t)),\\ &[\mathtt{B}](x,t)=\phi_{\mathtt B}**(-\lambda[\mathtt{A}][\mathtt{B}]+\gamma\lambda[\mathtt{C}]+f_{\mathtt{B}}(x,t)),\\ &[\mathtt{C}](x,t)=\phi_{\mathtt C}**(\lambda[\mathtt{A}][\mathtt{B}]-\gamma\lambda[\mathtt{C}]). \end{align} Therefore, the Picard iteration operator is obtained as follows: \begin{align} &\mathcal{\tau}:\mathcal{C}\times \mathcal{C}\times \mathcal{C} \mapsto \mathcal{C}\times \mathcal{C}\times \mathcal{C}\nonumber\\ &\mathcal{\tau}(\mathtt{a},\mathtt{b},\mathtt{c})=(\phi_\mathtt{A}**(-\lambda\mathtt{a}\mathtt{b}+\lambda\gamma\mathtt{c}+f_\mathtt{A}),\phi_\mathtt{B}**(-\lambda\mathtt{a}\mathtt{b}+\lambda\gamma\mathtt{c}+f_\mathtt{B}),\phi_\mathtt{C}**(\lambda\mathtt{a}\mathtt{b}-\gamma\lambda\mathtt{c})), \end{align} where $\mathcal{C}$ is the space of continuous functions. The solution of the reaction-diffusion system is a fixed point of the Picard iteration operator. Picard's iterative process suggests the following recursive algorithm to find a fixed point of the operator $\mathcal{\tau}$: \begin{align} (\mathtt{a}^{(n+1)},\mathtt{b}^{(n+1)},\mathtt{c}^{(n+1)})=\mathcal{\tau}(\mathtt{a}^{(n)},\mathtt{b}^{(n)},\mathtt{c}^{(n)}),~~~(\mathtt{a}^{(-1)},\mathtt{b}^{(-1)},\mathtt{c}^{(-1)})=(0,0,0),~~n\geq-1\label{banchiter}, \end{align} where $(\mathtt{a}^{(n)},\mathtt{b}^{(n)},\mathtt{c}^{(n)})$ is the triple of functions that we obtain at the $n$th iteration. Picard's iterative process relates to the perturbation method as follows: using induction and comparing \eqref{recu-eq1}-\eqref{recu-eq3} with the recursive equations given in \eqref{banchiter}, one obtains \begin{align} \mathtt{a}^{(n)}&=\sum_{i=0}^{n}\lambda^{i} [\mathtt{A}]_{i}(x,t)&n=0,1\\ \mathtt{a}^{(n)}&=\sum_{i=0}^{n}\lambda^{i} [\mathtt{A}]_{i}(x,t)+\mathcal{O}(\lambda^{n+1})&n\geq 2. \end{align} A similar statement holds for $\mathtt{b}^{(n)}$ and $\mathtt{c}^{(n)}$, showing that their first $n$ lower terms match the first $n$ lower terms of the Taylor series expansion in the perturbation method. \subsection{Approximate Solutions} In practice, we can approximate the true concentrations of molecules by computing the first $n$ terms in the Taylor series expansion: \begin{align} [\mathtt{A}](x,t)\approx \sum_{i=0}^{n}\lambda^{i} [\mathtt{A}]_{i}(x,t) \end{align} for some fixed $n$. One can stop at the $n$-term of the Taylor expansion when the contribution of the $(n+1)$th term is negligible compared to the first $n$ terms. While $n$th term can be explicitly found in Example \ref{exampleA1}, for general reaction-diffusion equations, there is no (non-recursive) explicit expression for the terms in the Taylor series expansion. In Section \ref{sec:Val}, we illustrate the sufficiency of choosing $n=1$ or $n=2$ when the length of the time interval $T$ is in the order of seconds. In the following, we provide a theoretical justification for choosing $n=1$ when the time interval $T$ is small: consider the reaction-diffusion equations \begin{align} &\frac{\partial[\mathtt{A}]}{\partial t}=D_\mathtt{A}~\frac{\partial^{2}[\mathtt{A}]}{{\partial x}^{2}}-\lambda~[\mathtt{A}][\mathtt{B}]+\gamma \lambda [\mathtt{C}]+f_\mathtt{A}(x,t),\\ & \frac{\partial[\mathtt{B}]}{\partial t}=D_\mathtt{B}~\frac{\partial^{2}[\mathtt{B}]}{{\partial x}^{2}}-\lambda~[\mathtt{A}][\mathtt{B}]+\gamma \lambda [\mathtt{C}]+f_\mathtt{B}(x,t),\\ & \frac{\partial[\mathtt{C}]}{\partial t}=D_\mathtt{C}~\frac{\partial^{2}[\mathtt{C}]}{{\partial x}^{2}}+\lambda~[\mathtt{A}][\mathtt{B}]-\gamma \lambda [\mathtt{C}], \end{align} along with the initial conditions $ [\mathtt{A}](x,0)=g_{\mathtt{A}}(x), [\mathtt{B}](x,0)=g_{\mathtt{B}}(x)$ and $ [\mathtt{C}](x,0)=g_{\mathtt{C}}(x)$. The one-step finite difference iteration (in the finite difference method) for a small value of $t$ is as follows: \begin{align} [\mathtt{A}]_{FDM}(x,t)&=[\mathtt{A}](x,0)+t\frac{\partial[\mathtt{A}]}{\partial t}(x,0) \nonumber\\&=g_{\mathtt{A}}(x)+t\left[ D_{\mathtt{A}}g_{\mathtt{A}}''(x)- \lambda g_{\mathtt{A}}(x)g_{\mathtt{B}}(x)+ \gamma\lambda g_{\mathtt{C}}(x)+ f_{\mathtt{A}}(x,0)\right] \nonumber\\&=g_{\mathtt{A}}(x)+\mathcal{O}(t).\end{align} Let $[\mathtt{A}]^{(1)}(x,t)=[\mathtt{A}]_{0}(x,t)+\lambda [\mathtt{A}]_{1}(x,t)$ be the approximate solution of the perturbation method up to the order one terms. In Appendix \ref{AppA:3} we show the following equivalence with the finite difference solution: \begin{theorem}\label{thmN1} The first-order approximation $[\mathtt{A}]^{(1)}(x,t)=[\mathtt{A}]_{0}(x,t)+\lambda [\mathtt{A}]_{1}(x,t)$ and the finite difference method are equivalent for small values of $t$, \emph{i.e.,} $ [\mathtt{A}]^{(1)}(x,t)= [\mathtt{A}]_{FDM}(x,t)+\mathcal{O}(t^2)$. A similar statement holds for molecules of type $\mathtt{B}$ and $\mathtt{C}$. \end{theorem} As illustrated in Section \ref{sec:Val}, the time steps do not necessarily need to be very small for the perturbation solution to closely track the true solution (and can be in the order of seconds). Therefore, the perturbation method can be understood as a generalization of the finite difference method that allows for longer time steps. \section{Modulation Design}\label{Sec:Mod} In Section \ref{sec::generalperturbation}, a closed-form solution for the reaction-diffusion equation \eqref{ex1:reaction} was obtained. In this section, we use this solution to find the optimal release pattern of molecules by the transmitters in order to minimize the error probability of the communication system. Suppose transmitter $ \mathsf T_{\mathtt {A}}$ intends to send a message bit $M_\mathtt{A}\in\{0,1\}$ to the receiver. The transmitter $ \mathsf T_{\mathtt {A}}$ releases molecules of type $[\mathtt {A}]$ into the medium according to $f_\mathtt{A}^{0}(x,t)=a_0(t)\delta(x), 0\leq t\leq T$ if $M_\mathtt{A}=0$, and according to $f_\mathtt{A}^{1}(x,t)=a_1(t)\delta(x), 0\leq t\leq T$ if $M_\mathtt{A}=1$. In other words, the waveform $a_{0}(t)$ is the released concentration of molecules of type $\mathtt A$ when $M_\mathtt{A}=0$, and $a_{1}(t)$ is the released density when $M_\mathtt{A}=1$. Similarly, suppose that transmitter $ \mathsf T_{\mathtt {B}}$ encodes message $M_\mathtt{B}\in\{0,1\}$ by $f_{\mathtt{B}}^{j}(x,t)=b_{j}(t) \delta(x-d_{\mathtt{B}}), 0\leq t\leq T, j=0,1$, where the waveforms $b_{0}(t)$ and $b_{1}(t)$ are defined similarly for transmitter $\mathsf T_{\mathtt {B}}$. The total amount of released molecules of types $\mathtt A$ and $\mathtt B$ during the transmission period $T$ is assumed to be at most $s_{\mathtt A}$ and $s_{\mathtt B}$ respectively, \emph{i.e.,} \begin{align}\int_{0}^T a_i(t)dt\leq s_{\mathtt A},~\int_{0}^T b_i(t)dt\leq s_{\mathtt B}, \quad i=0,1.\label{eqn:New6} \end{align} The input messages ${M}_\mathtt{A}, {M}_\mathtt{B}$ are assumed to be uniform Bernoulli random variables. Receiver $\mathsf R_{\mathtt {C}}$ samples the density of molecules of type $\mathtt{C}$ at its location at the end of the time slot at time $t=T$. The receiver is assumed to be transparent and suffers from the particle counting noise. More specifically, the receiver is assumed to get a sample from $\mathsf{Poisson}\big(V\cdot [\mathtt{C}](d_{R},T)\big)$ where $[\mathtt{C}](d_{R},T)$ is the density of molecules of type $\mathtt C$ at time $T$ and location $d_{R}$, and $V$ is a constant. Using this observation, $\mathsf R_{\mathtt {C}}$ outputs its estimate of the transmitted message pair $(\hat{M}_\mathtt{A},\hat{M}_\mathtt{B})\in \{00,01,10,11\}$. The probability of error is \begin{equation} Pr(e)=Pr\{ (M_{\mathtt{A}}, M_{\mathtt{B}})\neq (\hat{M}_\mathtt{A},\hat{M}_\mathtt{B})\}.\label{eqnErrorProb1} \end{equation} Having transmitted messages $a_{m_{\mathtt{A}}}(t), b_{m_{\mathtt{B}}}(t)$ for a message pair $(m_{\mathtt{A}}, m_{\mathtt{B}})$, let $\rho_{m_{\mathtt{A}}, m_{\mathtt{B}}}$ denote the density of molecules of type $\mathtt{C}$ at the time of sampling. The receiver aims to recover $\hat m_{\mathtt{A}}, \hat m_{\mathtt{B}}$ using a sample $\mathsf{Poisson}(V\cdot \rho_{m_{\mathtt{A}}, m_{\mathtt{B}}})$. Our goal is to design nonnegative signals $a_{i}(t), b_{j}(t)$ satisfying \eqref{eqn:New6} to minimize the error probability. The key utility of the technique given in Section \ref{sec::generalperturbation} is that it provides a closed-form expression for $\rho_{m_{\mathtt{A}}, m_{\mathtt{B}}}$ in terms of $a_i(t)$ and $b_j(t)$. An order $n$ approximation to the reaction-diffusion is when we consider the reaction-diffusion equations up to the terms of order $\lambda^n$ in the Taylor expansion. We say that waveforms $a_i(t)$ and $b_j(t)$ are order $n$ optimal waveforms if they minimize the error probability for the approximate reaction-diffusion equations up to order $n$. For low reaction rates, we are mainly interested in order one optimal waveforms. In the following theorem, we show that for low reaction rates, one possible optimal strategy is for $ \mathsf T_{\mathtt {A}},\mathsf T_{\mathtt {B}}$ to release molecules in at most two time instances in a bursty fashion. The location of these instantaneous releases is determined by the message it wants to transmit. In other words, waveform $a_{i}(t)$ is the sum of two Dirac's delta functions. \begin{theorem}\label{th::1} Consider approximating the solution of the reaction-diffusion equations with the perturbation solution up to the first-order term. Consider the problem of choosing waveforms $a_i(t), b_i(t)$ to minimize the error probability. Then, restricting minimization to waveforms $a_i(t), b_i(t)$ with the following structure does not change the minimum value of error probability: \begin{align} &a_0(t)=\hat{a}_{01}\delta(t-t_1^{[a_0]})+\hat{a}_{02}\delta(t-t_2^{[a_0]}),~ a_1(t)=\hat{a}_{11}\delta(t-t_1^{[ a_1]})+\hat{a}_{12}\delta(t-t_2^{[a_1]}),\\ & b_0(t)=\hat{b}_{01}\delta(t-t_1^ {[b_0]})+\hat{b}_{02}\delta(t-t_2^ {[b_0]}),~~ b_1(t)=\hat{b}_{11}\delta(t-t_1^{[b_1]})+\hat{b}_{12}\delta(t-t_2^{[b_1]}), \end{align} for some non-negative constants $\hat{a}_{ij},\hat{b}_{ij}$ satisfying $\sum_{j}\hat{a}_{ij}\leq s_{\mathtt A}$ and $\sum_{j}\hat{b}_{ij}\leq s_{\mathtt B}$ for $i=0,1$, and for some $t_j^{[a_i]},t_j^{[b_i]}\in[0,T]$. \end{theorem} \begin{proof} By substituting $f_\mathtt{A}^{i}(x,t),f_\mathtt{B}^{i}(x,t), i=0,1$ in \eqref{ex1:A0,B0} and \eqref{recu-eq1}-\eqref{recu-eq3}, one obtains an explicit formula for (the first-order approximation of) the concentration of molecules $\mathtt{C}$ in terms of $f_\mathtt{A}^{i}(x,t),f_\mathtt{B}^{i}(x,t), i=0,1$. In particular, the concentration $[\mathtt{C}](d_{R},T)$ at receiver's location at the sampling time $T$ is as follows: \begin{align} [\mathtt{C}](d_ {R},T)=\lambda\int_{0}^{T} \int_{-\infty}^{+\infty}\int_{0}^{t'} \int_{0}^{t'}& \phi_{\mathtt{C}}(d_R-x',T-t') \phi_{\mathtt{A}}(x',t'-t_1) \phi_{\mathtt{B}}(x'-d_{\mathtt{B}},t'-t_2)\nonumber\\& a_{M_{\mathtt{A}}}(t_1) b_{M_{\mathtt{B}}}(t_2) dt_{1}dt_{2}dx'dt'. \end{align} Observe that $[\mathtt{C}](d_ {R},T)$ has a \emph{bilinear} form with respect to $a_{M_{\mathtt{A}}}(t)$ and $b_{M_{\mathtt{B}}}(t)$ . In the other words, if $a_{M_{\mathtt{A}}}(t)$ is kept fixed then $[\mathtt{C}](d_ {R},T)$ is linear with respect to $b_{M_{\mathtt{B}}}(t)$ and vice versa. Let \begin{equation}\label{densities::ex1:final} \rho=\left\{ {\begin{array}{*{20}{llll}} \rho_{00}=[\mathtt{C}](d_{R},T)& & \text{if}&(M_{\mathtt{A}},M_{\mathtt{B}})=(0,0)\\ \rho_{01}=[\mathtt{C}](d_{R},T)& & \text{if}&(M_{\mathtt{A}},M_{\mathtt{B}})=(0,1)\\ \rho_{10}=[\mathtt{C}](d_{R},T)& & \text{if}&(M_{\mathtt{A}},M_{\mathtt{B}})=(1,0)\\ \rho_{11}=[\mathtt{C}](d_{R},T)& & \text{if}&(M_{\mathtt{A}},M_{\mathtt{B}})=(1,1) \\ \end{array}}\right. \end{equation} Using \eqref{densities::ex1:final} we can compute $ (\rho_{00},\rho_{01},\rho_{10},\rho_{11})$ for any given $a_{0}(t), a_{1}(t), b_0(t)$ and $b_1(t)$. The receiver aims to recover $\hat m_{\mathtt{A}}, \hat m_{\mathtt{B}}$ using a sample $\mathsf{Poisson}(V\rho_{m_{\mathtt{A}}, m_{\mathtt{B}}})$. Minimizing the error probability (given in \eqref{eqnErrorProb1}) is equivalent to solving a Poisson hypothesis testing problem (see Appendix \ref{AppB} for a review). Our goal is to design nonnegative signals $a_{i}(t), b_{j}(t)$ satisfying \eqref{eqn:New6} to minimize the error probability of this Poisson hypothesis testing problem. Note that the tuple $ (\rho_{00},\rho_{01},\rho_{10},\rho_{11})$ forms a \emph{sufficient statistic} for computing the error probability. In other words, if we change the signals $a_{i}(t), b_{j}(t)$ in such a way that the four numbers $ (\rho_{00},\rho_{01},\rho_{10},\rho_{11})$ are unchanged, the error probability remains unchanged. Take signals $a_i(t)$ and $b_j(t)$ for $i,j\in\{0,1\}$ that minimize the error probability. We claim that we can find $\hat a_0(t)$ of the form $\hat a_0(t)=\hat{a}_{01}\delta(t-t_1^{[a_0]})+\hat{a}_{02}\delta(t-t_2^{[a_0]})$ for some $\hat{a}_{01}$ and $\hat{a}_{02}$ such that if we replace the $(a_0(t), a_1(t), b_0(t), b_1(t))$ by $(\hat a_0(t), a_1(t), b_0(t), b_1(t)),$ the corresponding values of $ (\rho_{00},\rho_{01},\rho_{10},\rho_{11})$ remain unchanged. Moreover, $\hat a_0(t)$ satisfies the power constraint \eqref{eqn:New6}. Since the error probability depends on the waveforms only through the values of $ (\rho_{00},\rho_{01},\rho_{10},\rho_{11})$, we deduce that replacing $a_0(t)$ with $\hat a_0(t)$ does not change the error probability. Since signals $a_i(t)$ and $b_j(t)$ for $i,j\in\{0,1\}$ minimized the error probability, we deduce that using $\hat a_0(t)$ would also achieve the minimum possible probability of error. By a similar argument we can reduce the support of waveforms $a_1(t)$, $b_0(t)$, and $b_1(t)$ one by one while fixing the other waveforms. This completes the proof. It remains to show that changing $a_0(t)$ by $\hat{a}_0(t)$ while preserving the values of $ (\rho_{00},\rho_{01},\rho_{10},\rho_{11})$ is possible. Replacing $a_0(t)$ by $\hat{a}_0(t)$ while fixing $a_1(t)$, $b_0(t)$, and $b_1(t)$ may only change $\rho_{00}$ and $\rho_{01}$. The values of $\rho_{10}$ and $\rho_{11}$ are only functions of $a_1(t)$, $b_0(t)$, and $b_1(t)$ which we are fixing. Moreover, $\rho_{00}$ and $\rho_{01}$ are linear functions of $a_0(t)$ when we fix $b_0(t)$ and $b_1(t)$. In other words, one can find functions $f_1(t)$ and $f_2(t)$ such that \begin{equation} \rho_{00}=\int_{t\in[0,T]}a_0(t)f_1(t)dt,\qquad \rho_{01}=\int_{t\in[0,T]}a_0(t)f_2(t)dt.\label{eqnDeff1} \end{equation} The power constraint \eqref{eqn:New6} is also a linear constraint on $a_0(t)$. We would like to change $a_0(t)$ to $\hat a_0(t)$ in such a way that two linear constraints corresponding to $\rho_{00}$ and $\rho_{01}$ are preserved, and the power of $\hat a_0(t)$ is less than or equal to the power of $a_0(t)$. Existence of $\hat{a}_0(t)$ with these properties follows from Lemma \ref{SupportLemma} given in Appendix \ref{AppC} (with the choice of $f(t)=1$, $n=2$, and $f_1(t)$ and $f_2(t)$ given in \eqref{eqnDeff1}), once we view $a_0(t)$ as an unnormalized probability distribution. \end{proof} In order to determine parameters in the statement of Theorem \ref{th::1} we need to optimize over constants $\hat{a}_{ij}$, $\hat{b}_{ij}$, $t_j^{[a_i]},t_j^{[b_i]}$. From the first-order equation, $\rho_{ij}$ (the concentration when the first transmitter sends bit $i\in\{0,1\}$ and the second transmitter sends the bit $j\in\{0,1\}$) equals \begin{equation} \begin{array}{*{20}{l}} \rho_{00}=\sum_{i,j=1}^{2}\hat{a}_{0i}\hat{b}_{0j}G(t_{i}^{[a_0]},t_{j}^{[b_0]}) \\ \rho_{01}=\sum_{i,j=1}^{2}\hat{a}_{0i}\hat{b}_{1j}G(t_{i}^{[a_0]},t_{j}^{[b_1]})\\ \rho_{10}=\sum_{i,j=1}^{2}\hat{a}_{1i}\hat{b}_{0j}G(t_{i}^{[a_1]},t_{j}^{[b_0]})\\ \rho_{11}=\sum_{i,j=1}^{2}\hat{a}_{1i}\hat{b}_{1j}G(t_{i}^{[a_1]},t_{j}^{[b_1]}), \end{array} \end{equation} where \begin{equation} G(t_i,t_j)=\lambda\phi_{\mathtt{C}}(x,t)**\big(\phi_{\mathtt{A}}(x,t-t_i) \phi_{\mathtt{B}}(x-d_{\mathtt{B}},t-t_j)\big) |_{t=t_s,x=d_R}. \end{equation} To recover the messages of the transmitters, the receiver needs to solve a Poisson hypothesis testing problem (see Appendix \ref{AppB}) with four hypotheses: $\rho=V\rho_{00}$ or $\rho=V\rho_{01}$ or $\rho=V\rho_{10}$ or $\rho=V\rho_{11}$ for a constant $V$. The error probability of this hypothesis testing problem should be minimized with respect to $\hat{a}_{ij}$, $\hat{b}_{ij}$, $t_j^{[a_i]},t_j^{[b_i]}$. As an example, consider the following parameters in Table\ref{tabj}: \begin{table}[H] \centering \caption{Parameters} \label{tabj} \begin{tabular}{ |c|c|c| } \hline \multirow{2}{*}{$(D_{\mathtt{A}},D_{\mathtt{B}},D_{\mathtt{C}})[m^{2}s^{-1}]$} &\multirow{2}{*} {$10^{-9}\times(1,1,1)$}\\ &\\ \hline \multirow{2}{*} {$\lambda[molecules^{-1}.m^{3}.s^{-1}]$} & \multirow{2}{*}{$ 10^{-23}$}\\ &\\ \hline \multirow{2}{*}{$V[m^{3}]$} &\multirow{2}{*} {$10^{-11}$}\\ &\\ \hline \multirow{2}{*}{$T[s]$ }& \multirow{2}{*}{$3$} \\ &\\ \hline \multirow{2}{*}{$d_{\mathtt{B}} [m]$} & \multirow{2}{*}{$5\times 10^{-5}\times(2,0,0) $ } \\ &\\ \hline \multirow{2}{*}{$d_{R}[m]$} & \multirow{2}{*}{$5\times 10^{-5}\times(1,0,0)$} \\ &\\ \hline \multirow{2}{*}{$s_{\mathtt{A}}[molecules.m^{-3}],s_{\mathtt{B}}[molecules.m^{-3}])$} & \multirow{2}{*}{$10^7\times(1,1)$} \\ &\\ \hline \end{tabular} \end{table} Simulation results yield the optimal values for $\hat{a}_{ij}$, $\hat{b}_{ij}$, $t_j^{[a_i]},t_j^{[b_i]}$ as in Table\ref{tab78} \begin{table}[H] \centering \caption{Values of unknown parameters.} \label{tab78} \begin{tabular}{ |c|c|c| } \hline \multirow{2}{*}{$(\hat{a}_{01},\hat{a}_{02})$} &\multirow{2}{*} {$(1.13\times 10^6,8.82\times 10^6)$}\\ &\\ \hline \multirow{2}{*} {$(\hat{a}_{11},\hat{a}_{12})$} & \multirow{2}{*}{$ (2.17\times 10^6,1.07\times 10^6)$}\\ &\\ \hline \multirow{2}{*}{$(\hat{b}_{01},\hat{b}_{02})$} &\multirow{2}{*} {$(0.97\times 10^6,3.2\times 10^6)$}\\ &\\ \hline \multirow{2}{*}{$(\hat{b}_{11},\hat{b}_{12})$ }& \multirow{2}{*}{$(3.52\times 10^6,6.46\times 10^6)$} \\ &\\ \hline \multirow{2}{*}{$(t_{1}^{[a_0]},t_{2}^{[a_0]})$} & \multirow{2}{*}{$(0,2) $ } \\ &\\ \hline \multirow{2}{*}{$(t_{1}^{[a_1]},t_{2}^{[a_1]})$} & \multirow{2}{*}{$(0,1) $ } \\ &\\ \hline \multirow{2}{*}{$(t_{1}^{[b_0]},t_{2}^{[b_0]})$} & \multirow{2}{*}{$(1,2)$} \\ &\\ \hline \multirow{2}{*}{$t_{1}^{[b_1]},t_{2}^{[b_1]}$} & \multirow{2}{*}{$(1,2)$} \\ &\\ \hline \multirow{2}{*}{$p_{e}$} & \multirow{2}{*}{$2.6\times 10^{-5}$} \\ &\\ \hline \end{tabular} \end{table} Figs. \ref{probabilty1} and \ref{probabilty2} show the optimal error probability (as defined in \eqref{eqnErrorProb1}) as a function of $s=s_{\mathtt{A}}=s_{\mathtt{B}}$ for the above parameters. Fig. \ref{pulsevsdelta} compares the error probabilities of optimal waveforms (sum of two delta functions) with a pulse release pattern, \emph{i.e.,} when we consider four waveforms $(f_{\mathtt{A}}^{0}(t)=a_{0}\mathbbm{1}_{0\leq t\leq T},f_{\mathtt{A}}^{1}(t)=a_{1}\mathbbm{1}_{0\leq t\leq T},f_{\mathtt{B}}^{0}(t)=b_{0}\mathbbm{1}_{0\leq t\leq T},f_{\mathtt{B}}^{1}(t)=b_{1}\mathbbm{1}_{0\leq t\leq T})$ as input signals to reaction diffusion equations. The error probability of the pulse waveforms is obtained by minimizing the error probability over pulse amplitudes $a_0, a_1\leq s_{\mathtt{A}}/T$ and $b_0, b_1\leq s_{\mathtt{B}}/T$. \begin{figure}[H] \centering \includegraphics[scale=.75]{errorvsS5.png} \caption{Error probability of the optimal waveforms for $10^5\leq s \leq 4\times 10^6$ [molecules.$m^{-3}$].} \label{probabilty1} \vspace{-3em} \end{figure} \begin{figure}[H] \centering \includegraphics[scale=.75]{errorvsS3.png} \caption{Error Probability of the optimal waveforms for $4\times 10^6\leq s \leq 1.4\times 10^7$ [molecules.$m^{-3}$].} \label{probabilty2} \end{figure} \begin{figure}[H] \centering \includegraphics[trim={1cm 0cm 0cm 0cm}, scale=.75]{logpulsevsdelta.png} \caption{Comparison between optimal wave-form and pulse family.} \label{pulsevsdelta} \vspace{-3em} \end{figure} \begin{figure}[H] \centering \includegraphics[trim={1cm 0cm 0cm 0cm}, scale=.75]{accurace1.png} \caption{First-order approximation for the first set parameters } \label{fig:1e-22,unequal,Nx=64,first} \end{figure} \section{Simulation} \label{sec:Val} In this section, we validate our method through numerical simulation. We need to specify the diffusion coefficients, reaction rate $\lambda$, input signals $f_{\mathtt A}$ and $f_{\mathtt B}$ as well as the locations of the transmitters. Previous works in the literature commonly take the number of released molecules to be either in the order of $10^{-14}$ moles (which is $10^9$ molecules) \cite{arjmandi2019diffusive,farahnak2018medium:j:16,cao2019chemical:j:ro}, or in the order of $10^{-3}$ moles \cite{farsad2016molecular:F:16}. The reaction rates in these works are generally in the order of $1$ to $10^8$ $\text{mole}^{-1}.m^{3}.s^{-1}$ or equivalently $10^{-23}$ to $10^{-15}$ $\text{molecules}^{-1}.m^{3}.s^{-1}$ \cite{cao2019chemical:j:ro,farsad2016molecular:F:16,bi2019chemical:j:9,chang2005physical}. We run three simulations for three choices of parameters for the reaction given in \eqref{ex1:reaction}. The exact solutions are obtained by the finite difference method (FDM). The first simulation borrows its system parameters from \cite{cao2019chemical:j:ro} as in Table \ref{tab1}: \begin{table} \centering \caption{First set of parameters.} \label{tab1} \begin{tabular}{ |c|c|c| } \hline \multirow{2}{*}{$(D_{\mathtt{A}},D_{\mathtt{B}},D_{\mathtt{C}})[m^{2}s^{-1}]$} &\multirow{2}{*} {$10^{-10}\times(10,7,1)$}\\ &\\ \hline \multirow{2}{*} {$\lambda[molecules^{-1}.m.s^{-1}]$} & \multirow{2}{*}{$ 10^{-22}$}\\ &\\ \hline \multirow{2}{*} {$\gamma[s^{-1}]$} & \multirow{2}{*}{$0$}\\ &\\ \hline \multirow{2}{*}{$f_{\mathtt{A}}(x,t)$} &\multirow{2}{*} {$5\times 10^{8}\delta(x)\delta(t)$}\\ &\\ \hline \multirow{2}{*}{$f_{\mathtt{B}}(x,t)$ }& \multirow{2}{*}{$2.4\times 10^{9}\delta(x-d_{\mathtt{B}})\delta(t)$} \\ &\\ \hline \multirow{2}{*}{$d_{\mathtt{A}} [m]$} & \multirow{2}{*}{$0 $ } \\ &\\ \hline \multirow{2}{*}{$d_{\mathtt{B}} [m]$} & \multirow{2}{*}{$ 10^{-4} $ } \\ &\\ \hline \multirow{2}{*}{$d_{R}[m]$} & \multirow{2}{*}{$5\times 10^{-5}$} \\ &\\ \hline \end{tabular} \end{table} In the second simulation we use the same parameters as in the first simulation, but make the three diffusion constants be the same $(D_{\mathtt{A}}=D_{\mathtt{B}}=D_{\mathtt{C}}=10^{-9}[m^2/s])$. Figs. \ref{fig:1e-22,unequal,Nx=64,first} and \ref{fig:1e-22,equal,Nx=120,first} are plotted based on the first and second set of system parameters respectively. They depict the concentration of the molecule of type $\mathtt{C}$ at the receiver's location calculated by the first-order term of perturbation method along with the true solution (computed via FDM). It can be seen that for these system parameters, the first-order term of the perturbation series is closely following the true solution. \begin{figure}[H] \centering \includegraphics[trim={1cm 0cm 0cm 0cm}, scale=.75]{jomong5.png} \caption{First-order approximation for the second set parameters} \label{fig:1e-22,equal,Nx=120,first} \vspace{-3em} \end{figure} \begin{figure}[H] \centering \includegraphics[trim={1cm 0cm 0cm 0cm}, scale=.75]{jomong67new.png} \caption{First-order and second-order approximate solutions for $\lambda=10^{-15}$.} \label{fig:1e-15,equal,Nx=120,first,T=15} \end{figure} Using the same parameters as in the second simulation, one can observe that the first-order term of perturbation series is still accurate as long as $\lambda\leq 10^{-16} [\text{molecules}^{-1}.m.s^{-1}]$. Fig. \ref{fig:1e-15,equal,Nx=120,first,T=15} plots the curves for $\lambda=10^{-15}$. As one can observe while the first-order term of the perturbation series does not track the exact solution for $t>5s$, while the second-order term tracks the true solution in $t<15s$. For $t>15s$, the perturbation solution up to the second-order term does not track the exact solution well, hence to obtain an accurate solution we have to consider third or higher-order terms in the perturbation solution. This observation is consistent with the theoretical analysis given in Appendix \ref{AppA0 }, where the convergence rate of perturbation solution depends on the length of the time interval $T$. We also remark that in many prior works on chemical reactions in MC, the observation time $T$ is rather small: \cite{arjmandi2019diffusive} uses $T\leq 0.1 s$, \cite{bi2019chemical:j:9} uses $T\leq 4 s$; \cite{cao2019chemical:j:ro} uses $T\leq 10 s$, while in other cases $T$ is in taken of order $\mu s$ \cite{farahnak2018medium:j:16,mosayebi2017type:F:21}. Fig. \ref{relative1} fixes $T=10[s]$ and plots the relative error of the first-order approximation solution of $[\mathtt{C}]$ for the second set of parameters in terms of $\lambda$. Fig. \ref{relative21} draws a similar curve for the second-order approximation of the perturbation solution. These figures confirm (the theoretical result) that for sufficiently small reaction rates, the relative error is negligible. For instance, to have a relative error of at most $0.01$, the first-order solution can be used for $\lambda<3\times10^{-16}$ (Fig. \ref{relative1}) while the second-order solution is valid until $\lambda<3\times10^{-15}$ (Fig. \ref{relative21}). Next, let us fix the relative error to be $0.05$ and define the permissible time interval as \begin{align} T_{\max}=\max\left\{T:\left|\frac{[\mathtt{C}]_{FDM}(t)-[\mathtt{C}]_{PER-Order-1}(t)}{[\mathtt{C}]_{FDM}(t)}\right|\leq .05, \qquad \forall t\in [0,T]\right\}.\label{TmaxDef}\end{align} In other words, $T_{\max}$ is the maximum simulation time interval for which the relative error is less than 5 percent. Fig. \ref{maxt2} shows the $T_{\max}$ for the first-order approximation of $[\mathtt{C}]$ in terms of $\lambda$. \begin{figure}[H] \centering \includegraphics[trim={1cm 0cm 0cm 0cm}, scale=0.75]{relativeerror1.png} \caption{Relative error for the first-order approximation.} \label{relative1} \vspace{-3em} \end{figure} \begin{figure}[H] \centering \includegraphics[trim={1cm 0cm 0cm 0cm}, scale=0.75]{relativeeerror21.png} \caption{Relative error for up to second-order approximation.} \label{relative21} \end{figure} \begin{figure}[H] \centering \includegraphics[trim={1cm 0cm 0cm 0cm}, scale=0.75]{maxt2.png} \caption{Permissible simulation time interval in terms of $\lambda$.} \label{maxt2} \vspace{-3em} \end{figure} \begin{figure}[H] \centering \includegraphics[trim={1cm 0cm 0cm 0cm}, scale=0.75]{jomong9.png} \caption{First-order approximation curve for the third set parameters.} \label{fig:.1,equal,Na=1micromole,first} \end{figure} In some applications, a significantly larger number of molecules (in the order of moles) are released into the medium. In the third simulation, we consider this case and take the following parameters in Table \ref{tab2}: \begin{table} \centering \caption{Third set of parameters} \label{tab2} \begin{tabular}{ |c|c|c| } \hline \multirow{2}{*}{$(D_{\mathtt{A}},D_{\mathtt{B}},D_{\mathtt{C}})[m^{2}.s^{-1}]$} &\multirow{2}{*} {$10^{-9}\times(1,1,1)$}\\ &\\ \hline \multirow{2}{*} {$\lambda[molecules^{-1}.m.s^{-1}]$} & \multirow{2}{*}{$ 10^{-24}/6.02214$}\\ &\\ \hline \multirow{2}{*} {$\gamma[s^{-1}]$} & \multirow{2}{*}{$0$}\\ &\\ \hline \multirow{2}{*}{$f_{\mathtt{A}}(x,t)$} &\multirow{2}{*} {$6.02214\times 10^{17}\delta(x)\delta(t)$}\\ &\\ \hline \multirow{2}{*}{$f_{\mathtt{B}}(x,t)$ }& \multirow{2}{*}{$6.02214\times 10^{17}\delta(x-d_{\mathtt{B}})\delta(t)$} \\ &\\ \hline \multirow{2}{*}{$d_{\mathtt{A}} [m]$} & \multirow{2}{*}{$0 $ } \\ &\\ \hline \multirow{2}{*}{$d_{\mathtt{B}} [m]$} & \multirow{2}{*}{$ 10^{-4} $ } \\ &\\ \hline \multirow{2}{*}{$d_{R}[m]$} & \multirow{2}{*}{$5\times 10^{-5}$} \\ &\\ \hline \end{tabular} \end{table} Fig. \ref{fig:.1,equal,Na=1micromole,first} shows that the first term of the perturbation series is close to the exact solution. \textbf{The effect of dimension:} While we assumed the transmitter and receivers to lie on a one-dimensional line, the problem can be solved in higher dimensions in a similar manner. In Figs. \ref{dim2} and \ref{dim3}, we compare the perturbation method (up to the first-order approximation) and the true solution in two and three dimensions. The parameters are the same as the second set of parameters with $\lambda[{molecules}^{-1}.m^{3}.s^{-1}]=10^{-23}$. As we see our solution is still accurate. We observe that as the dimension of the medium increases, concentrations decay faster. This is due to the extra degrees of freedom in the dispersion of molecules. \begin{figure}[H] \centering \includegraphics[trim={1cm 0cm 0cm 0cm}, scale=.75]{dim2.png} \caption{2d medium, first-order approximation} \label{dim2} \vspace{-3em} \end{figure} \begin{figure}[H] \centering \includegraphics[trim={1cm 0cm 0cm 0cm}, scale=0.75]{dim3.png} \caption{3d medium, first-order approximation} \label{dim3} \end{figure} \textbf{The effect of diffusion coefficients:} In Fig. \ref{DconC} we plot $[\mathtt{C}]$ for different values of $D_\mathtt{C}$, for the second set of parameters. Observe that $[\mathtt{C}]$ is a decreasing function of $D_\mathtt{C}$. Fig. \ref{maxt} plots $T_{\max}$ (as defined in \eqref{TmaxDef}) versus $D_\mathtt{C}$ for the same parameters, showing that increasing $D_\mathtt{C}$ decreases $T_{\max}$. \begin{figure}[H] \centering \includegraphics[trim={1cm 0cm 0cm 0cm}, scale=0.75]{effectonctwobox.png} \caption{Effect of $D_\mathtt{C}$ on $[\mathtt{C}]$ } \label{DconC} \vspace{-3em} \end{figure} \begin{figure}[H] \centering \includegraphics[trim={1cm 0cm 0cm 0cm}, scale=0.75]{maxt.png} \caption{Impact of diffusion coefficient on the permissible simulation time interval} \label{maxt} \end{figure} \section{Conclusion and Future Work}\label{Conclusion and Future Work} We addressed the difficulty of designing modulation due to the lack of existence of closed-form solutions for the reaction-diffusion equation by providing an approximate solution to the reaction-diffusion equations. We observed that for many choices of system parameters our solution is accurate. Also, we observed that the accuracy of our solution depends on time observation $T$. Using the proposed model, we designed optimal waveforms for a multiple-access setting. In the Appendix\ref{ex2,3} of this paper two more examples are considered (Example II and Example III). In Example II, we consider a communication system with one transmitter and one receiver. The transmitter can send molecules of type $\mathtt{A}$ or $\mathtt{B}$, while the receiver can only measure molecules of type $\mathtt{A}$. The medium has molecules of a different type $\mathtt{C}$ that can react with both $\mathtt{A}$ and $\mathtt{B}$. The transmitter releases molecules of type $\mathtt{B}$ in order to ``clean up" the medium of molecules of type $\mathtt{C}$ so that molecules of type $\mathtt{A}$ can reach the receiver without being dissolved through reaction with $\mathtt{C}$ as they travel from the transmitter to the receiver. In Example III, we consider a two-way communication system with two transceiver nodes. In other words, each node aims to both send and receiver information from the other node. Transmitters use different molecule types and these molecules can react with each other. The chemical reaction in this scenario is destructive because it reduces the concentration of molecules at the two transceivers. Many other settings could be studied and left for future work. Firstly, we only considered transparent receivers in this work. The literature on MC also considers absorbing or ligand/reactive receivers. Since the perturbation method is broadly applicable to non-linear differential equations, the proposed framework can be also applied to absorbing or reactive receivers with more work. An absorbing receiver adds a boundary condition to the reaction-diffusion equations (the concentration of absorbed molecules being zero at the receiver's location). On the other hand, the reactive receiver adds an ordinary differential equation to the system's equations, for receptors on the surface of the receiver. Further, one could study the design of optimal waveforms when taking multiple samples in the transmission time slot (instead of just one sample, as in this paper) or study optimal waveform design for channels with ISI. These studies are possible and left as future work. Finally, there are other existing approaches in the literature for obtaining semianalytic solutions of chemical reaction-diffusion equations. Studying these approaches which might have a higher radius of convergence is also left as future work. \appendices \section{Convergence Analysis}\label{AppA0 } To show that the power series $\sum_{i=0}^{\infty}\lambda^{i} [\mathtt{A}]_{i}(x,t)$, $\sum_{i=0}^{\infty}\lambda^{i} [\mathtt{B}]_{i}(x,t)$ and $\sum_{i=0}^{\infty}\lambda^{i} [\mathtt{C}]_{i}(x,t)$ are convergent to functions that satisfy the original reaction-diffusion differential equation, we consider time $t\in[0,T]$ for some fixed $T$ and prove that \begin{align}\label{eqnNewN14} &\sum_{i=0}^{\infty}\lambda^{i} [\mathtt{A}]_{i}(x,t),\quad \sum_{i=0}^{\infty}\lambda^{i} \frac{\partial}{\partial x} [\mathtt{A}]_{i}(x,t),\quad \sum_{i=0}^{\infty}\lambda^{i} \frac{\partial^2}{\partial x^2}[\mathtt{A}]_{i}(x,t),\quad\sum_{i=0}^{\infty}\lambda^{i} \frac{\partial}{\partial t}[\mathtt{A}]_{i}(x,t) \end{align} uniformly converge over all $\lambda, x, t$. Similarly, we prove that the corresponding power series for molecules of types $\mathtt B$ and $\mathtt C$ also uniformly converge. Uniform convergence of the series given in equations \eqref{eqnNewN14} follows from Lemma \ref{LemmaBounds} given below. For a function $f_{\mathtt{A}}(x,t)$ defined for $x\in\mathbb{R}$ and $t\in[0,T]$, we define \begin{align}&\lVert f_{\mathtt{A}}\lVert_{\infty}=\sup_{x,t\in[0,T]}|f_{\mathtt{A}}(x,t)|, \lVert f_{\mathtt{A}}(x,0)\lVert_{\infty}=\sup_{x}|f_{\mathtt{A}}(x,0)|, \lVert f_{\mathtt{A}}(x,t)\lVert_{1}=\int_{0}^{T}\int_{x}|f_{\mathtt{A}}(x,t)| dx dt. \end{align} \begin{lem}\label{LemmaBounds} Let \begin{align} &M_0=\max\{T\lVert f_{\mathtt{A}}\lVert_{\infty},T\lVert f_{\mathtt{B}}\lVert_{\infty}\}, N_0=\max\big\{T\lVert \frac{\partial f_{\mathtt{A}}}{\partial t}\lVert_{\infty}+\lVert f_{\mathtt{A}}(x,0)\lVert_{\infty}, T\lVert \frac{\partial f_{\mathtt{B}}}{\partial t}\lVert_{\infty}+\lVert f_{\mathtt{B}}(x,0)\lVert_{\infty}\big\},\nonumber\\ &G_0=\max\{\sqrt{\frac{4T}{\pi D_\mathtt{A}}}\lVert f_{\mathtt{A}}\lVert_{\infty},\sqrt{\frac{4T}{\pi D_\mathtt{B}}}\lVert f_{\mathtt{B}}\lVert_{\infty}\},~ H_0=\max\{\sqrt{\frac{4T}{\pi D_\mathtt{A}}}\lVert \frac{\partial f_{\mathtt{A}}}{\partial x}\lVert_{\infty},\sqrt{\frac{4T}{\pi D_\mathtt{B}}}\lVert \frac{\partial f_{\mathtt{B}}}{\partial x}\lVert_{\infty}\},\nonumber\\ &\sigma=\max\{\rVert\frac{\partial\phi_\mathtt{A}}{\partial x}\lVert_{1},\rVert\frac{\partial\phi_\mathtt{B}}{\partial x}\lVert_{1},\rVert\frac{\partial\phi_\mathtt{C}}{\partial x}\lVert_{1}\}=\sqrt{\frac{4T}{\pi\min\{D_\mathtt{A},D_\mathtt{B},D_{\mathtt{C}}\}}}. \end{align} Then, for any $0<\lambda<\frac{1}{T(12M_0+10\gamma)}$, we have the following equations for any $i\geq 1$ \begin{align} &\lambda^{i}\rVert[\mathtt{A}]_{i}\lVert_{\infty}\leq \frac{M_0}{2^{i}},~ \lambda^{i}\rVert\frac{\partial [\mathtt{A}]_{i}}{\partial t}\lVert_{\infty}\leq \frac{N_0}{3(2^{i})},~\lambda^{i}\rVert\frac{\partial [\mathtt{A}]_{i}}{\partial x}\lVert_{\infty}\leq \frac{\sigma M_0 i}{4T(2^i)},\\&\lambda^{i}\rVert\frac{\partial^2 [\mathtt{A}]_{i}}{\partial x^2}\lVert_{\infty}\leq(\frac{1}{2})^{i} (\frac{\sigma(2M_0+\gamma) G_0}{4T(M_0+\gamma)}+\frac{\sigma^2(2M_{0}^{2}+ \gamma M_{0})}{32T^2(M_{0}+\gamma)}i(i-1)). \end{align} \end{lem} Using this lemma and assuming $|\lambda|<\frac{1}{T(12M_0+10\gamma)}$ where $M_0$ is defined in Lemma \ref{LemmaBounds}, we obtain $\sum_{i=N}^{\infty} \lambda^{i}\rVert[\mathtt{A}]_{i}\lVert_{\infty}\leq M_0/2^{N-1}$. Since $M_0/(2^{N-1})$ is a universal upper bound that does not depend on $(\lambda, x, t)$, the power series $\sum_{i=0}^{\infty}\lambda^{i} [\mathtt{A}]_{i}(x,t)$ will uniformly converge. Proof of the convergence of the other power series given above is similar. It remains to prove Lemma \ref{LemmaBounds}. \begin{proof}[Proof of Lemma \ref{LemmaBounds}] The proof is by induction on $i$. Suppose $M_i,i\geq1$, is an upper bound on $\rVert[\mathtt{A}]_i\lVert_{\infty}$, $\lVert[\mathtt{B}]_i\rVert_{\infty}$, and $\lVert[\mathtt{C}]_i\rVert_{\infty}$ we have: \begin{align} \rVert[\mathtt{A}]_i\lVert_{\infty}&=\rVert \phi_\mathtt{A}**([\mathtt{A}]_{0:i-1}*^d[\mathtt{B}]_{0:i-1}-\gamma[\mathtt{C}]_{i-1})\lVert_{\infty}\leq\rVert\phi_{\mathtt{A}}\lVert_{1}(\sum_{j=0}^{i-1}\rVert [\mathtt{A}]_{j}\lVert_{\infty} \rVert [\mathtt{B}]_{i-1-j}\lVert_{\infty}+\gamma\rVert [\mathtt{C}]_{i-1}\lVert_{\infty})\nonumber\\ &\leq T (\sum_{j=0}^{i-1} M_jM_{i-1-j}+\gamma M_{i-1})\leq T(1+\frac{\gamma}{M_{0}})\sum_{j=0}^{i-1} M_jM_{i-1-j} \end{align} A similar bound for $\rVert[\mathtt{B}]_i\lVert_{\infty}$ and $\rVert[\mathtt{C}]_i\lVert_{\infty}$ can be written. Thus, using induction we can set $M_i=T(1+\frac{\gamma}{M_{0}}) \sum_{j=0}^{i-1} M_jM_{i-1-j}$. The solution of this recursive equation is given in the following form: $ M_i=(T+\frac{\gamma T}{M_0})^iM_{0}^{i+1}\mathcal{C}_i ,~i\geq 0, $ where $\mathcal{C}_i$ is the Catalan number and has an explicit formula: $ \mathcal{C}_i=\frac{(2i)!}{(i+1)!(i)!}. $ Using the Sterling formula, we have $ \mathcal{C}_i\leq 4^i. $ Hence for $i\geq 0$ we obtain: \begin{align} \lambda^{i}\max(\rVert[\mathtt{A}]_i\lVert_{\infty}, \rVert[\mathtt{B}]_i\lVert_{\infty})&\leq M_0(\frac{4M_0+4\gamma}{12M_0+10\gamma})^i\leq \frac{M_0}{2^i}. \end{align} Suppose $N_i$ for $i\geq1$ is an upper bound on $\rVert\frac{\partial[\mathtt{A}]_i}{\partial t}\lVert_{\infty},\lVert \frac{\partial[\mathtt{B}]_i}{\partial t}\rVert_{\infty}$ and $\lVert \frac{\partial[\mathtt{C}]_i}{\partial t}\rVert_{\infty}$ . We have: \begin{align} \rVert\frac{\partial[\mathtt{A}]_i}{\partial t}\lVert_{\infty}&=\rVert \phi_\mathtt{A}**\frac{\partial}{\partial t}([\mathtt{A}]_{0:i-1}*^d[\mathtt{B}]_{0:i-1}-\gamma [\mathtt{C}]_{i-1})\lVert_{\infty}\nonumber\\ &\leq \rVert\phi_{\mathtt{A}}\lVert_{1}(2\sum_{j=0}^{i-1} \rVert\frac{\partial[\mathtt{A}]_j}{\partial t}\lVert_{\infty} \rVert [\mathtt{B}]_{i-1-j}\lVert_{\infty}+\gamma \rVert\frac{\partial[\mathtt{C}]_{i-1}}{\partial t}\lVert_{\infty})\nonumber\\&\leq (2T+\frac{\gamma T}{M_0})\sum_{j=0}^{i-1}N_{j}M_{i-1-j}\leq (2TM_0+\gamma T) \sum_{j=0}^{i-1} N_j(4TM_0)^{i-1-j}. \end{align} A similar equation can be written for $\rVert\frac{\partial[\mathtt{B}]_i}{\partial t}\lVert_{\infty}$ and $\rVert\frac{\partial[\mathtt{C}]_i}{\partial t}\lVert_{\infty}$. Thus, setting $N_i=(2TM_0+\gamma T) \sum_{j=0}^{i-1} N_j(4TM_0)^{i-1-j}$ yields a valid upper bound on $\rVert\frac{\partial[\mathtt{A}]_i}{\partial t}\lVert_{\infty},\lVert \frac{\partial[\mathtt{B}]_i}{\partial t}\rVert_{\infty}$ and $\lVert \frac{\partial[\mathtt{C}]_i}{\partial t}\rVert_{\infty}$ by induction. The solution of this recursive equation is as follows: \begin{equation} N_i=N_0(\frac{2M_0+\gamma}{6M_0+5\gamma})(6TM_0+5T\gamma)^{i},~i\geq 1. \end{equation} For $0<\lambda<\frac{1}{T(12M_0+10\gamma)}$, we obtain that \begin{equation} \lambda^{i}\max(\rVert\frac{\partial [\mathtt{A}]_{i}}{\partial t}\lVert_{\infty},\rVert\frac{\partial [\mathtt{B}]_{i}}{\partial t}\lVert_{\infty}\big)\leq \frac{N_0}{3(2^{i})}. \end{equation} Next, we have \begin{align} \rVert\frac{\partial[\mathtt{A}]_i}{\partial x}\lVert_{\infty}&=\rVert \frac{\partial\phi_\mathtt{A}}{\partial x} **([\mathtt{A}]_{0:i-1}*^d[\mathtt{B}]_{0:i-1}-\gamma [\mathtt{C}]_{i-1})\lVert_{\infty}\nonumber\\&\leq \rVert\frac{\partial\phi_\mathtt{A}}{\partial x}\lVert_{1}(\sum_{j=0}^{i-1} \rVert[\mathtt{A}]_j\lVert_{\infty} \rVert [\mathtt{B}]_{i-1-j}\lVert_{\infty}+\gamma \rVert [\mathtt{C}]_{i-1}\lVert_{\infty} )\leq \sigma(1+\frac{\gamma}{M_0})\sum_{j=0}^{i-1}M_{j}M_{i-1-j}\nonumber\\ &\leq \frac{\sigma M_0}{4T} \sum_{j=0}^{i-1} (4T(M_0+\gamma))^{i} \leq \frac{\sigma M_0}{4T}i (4T(M_0+\gamma))^{i}, \end{align} thus, $ G_i=\frac{\sigma M_0}{4T}i (4T(M_0+\gamma))^{i}, $ for $i\geq 1$, serves as an upper bound on $\rVert\frac{\partial[\mathtt{A}]_i}{\partial x}\lVert_{\infty}$ (and by a similar argument $\lVert \frac{\partial[\mathtt{B}]_i}{\partial x}\rVert_{\infty}$ and $\lVert \frac{\partial[\mathtt{C}]_i}{\partial x}\rVert_{\infty}$ ). Finally, \begin{align} \rVert\frac{\partial^2[\mathtt{A}]_i}{\partial x^2}\lVert_{\infty}&=\rVert \frac{\partial \phi_\mathtt{A}}{\partial x} **(\frac{\partial}{\partial x}([\mathtt{A}]_{0:i-1}*^d[\mathtt{B}]_{0:i-1}-\gamma [\mathtt{C}]_{i-1})\lVert_{\infty} \nonumber\\&\leq \rVert\frac{\partial \phi_\mathtt{A}}{\partial x} \lVert_{1}(2\sum_{j=0}^{i-1} \rVert\frac{\partial[\mathtt{A}]_j}{\partial x}\lVert_{\infty} \rVert [\mathtt{B}]_{i-1-j}\lVert_{\infty}+ \gamma \rVert\frac{\partial[\mathtt{C}]_{i-1}}{\partial x}\lVert_{\infty} )\leq\sigma(2\sum_{j=0}^{i-1} G_jM_{i-1-j}+\gamma G_{i-1}) \nonumber\\&\leq\sigma(2+\frac{\gamma}{M_0}) \sum_{j=0}^{i-1} G_jM_{i-1-j}=\sigma(2+\frac{\gamma}{M_0})(G_0 M_{i-1}+\sum_{j=1}^{i-1} G_jM_{i-1-j})\nonumber\\&\leq(\frac{\sigma(2M_0+\gamma) G_0}{4T(M_0+\gamma)}+\frac{\sigma^2(2M_{0}^{2}+ \gamma M_{0})}{32T^2(M_{0}+\gamma)}i(i-1))\times (4T(M_0+\gamma))^{i}. \end{align} Therefore, $ H_i=(\frac{\sigma(2M_0+\gamma) G_0}{4T(M_0+\gamma)}+\frac{\sigma^2(2M_{0}^{2}+ \gamma M_{0})}{32T^2(M_{0}+\gamma)}i(i-1))\times (4T(M_0+\gamma))^{i}, i\geq 1, $ is an upper bound on $\rVert\frac{\partial^2[\mathtt{A}]_i}{\partial x^2}\lVert_{\infty}$ (an on $\lVert \frac{\partial^2[\mathtt{B}]_i}{\partial x^2}\rVert_{\infty}$ and $\lVert \frac{\partial^2[\mathtt{C}]_i}{\partial x^2}\rVert_{\infty}$ by a similar argument). The proof is complete. \end{proof} \iffalse \section{Increasing Radius of Convergence }\label{AppA:1 } For simplicity, assume $\gamma=0$. We can extend our solution for given$(\lambda,T,f_{\mathtt A}(x,t),f_{\mathtt B}(x,t))$. If $\lambda\leq 1/(12TM_0)$ we proved in Appendix \ref{AppA0 } of paper, the solution is convergent($M_0=max\{\lVert \phi_{\mathtt A}**f_{\mathtt A} \rVert_{\infty},\lVert \phi_{\mathtt B}**f_{\mathtt B} \rVert_{\infty}\}$). Let $\lambda_{0}=1/(12TM_0)$ and $[\mathtt A]^{\lambda_0}$ and $[\mathtt B]^{\lambda_0}$ be solution of reaction-diffusion equation for $\lambda=\lambda_0$. Now for $\lambda>\lambda_{0}$,consider the solution as $[\mathtt{A}]=\sum_{i=0}^{\infty}(\lambda-\lambda_0)^{i}[\mathtt{A}]_{i}$ and $[\mathtt{B}]=\sum_{i=0}^{\infty}(\lambda-\lambda_0)^{i}[\mathtt{B}]_{i}$. By substituting these form in reaction-diffusion equations, we have : \begin{align} &[\mathtt A]_0=[\mathtt A]^{\lambda_0},~~[\mathtt B]_0=[\mathtt B]^{\lambda_0},\\ &[\mathtt A]_i=-\phi_{\mathtt A}**([\mathtt A]_{0:i-1}*^{d}[\mathtt B]_{0:i-1}) ~,i\geq 1,\\ &[\mathtt B]_i=-\phi_{\mathtt B}**([\mathtt A]_{0:i-1}*^{d}[\mathtt B]_{0:i-1}) ~,i\geq 1. \end{align} The solution are convergent if $\lambda-\lambda_0\leq 1/(12TM')$, where $M'=max\{\lVert [\mathtt A]^{\lambda_0} \rVert_{\infty},\lVert [\mathtt B]^{\lambda_0} \rVert_{\infty}\}$. In the following lemma we show $M'\leq M_0$. \begin{lem} $M'\leq M$ \end{lem} \begin{proof} It is suffient to prove $[\mathtt A](x,t)\leq \phi_{\mathtt A}**f_\mathtt{A}$. Concentration of molecules are non negative functions, i.e.,$[\mathtt A](x,t),[\mathtt B](x,t)\geq 0$, we have, \begin{align*} & [\mathtt A](x,t)=\phi_{\mathtt A}**(f_{\mathtt A}-\lambda [\mathtt A][\mathtt B])=\phi_{\mathtt A}**f_{\mathtt A}-\lambda \phi_{\mathtt A}** [\mathtt A][\mathtt B]\leq \phi_{\mathtt A}**f_{\mathtt A}, \end{align*} similarly $[\mathtt B](x,t)]\leq \phi_{\mathtt B}**f_{\mathtt B} $, hence $M'\leq M$. \end{proof} Therefore, in the worse case $\lambda-\lambda_0\leq 1/(12TM_0)=\lambda_0$, so we have $\lambda\leq 2\lambda_0$. For $\lambda=k\lambda_0+r(r<\lambda_0)$ ,we repeat $k+1$ times this procedure. We proved that for any inputs one can compute solution by repeating perturbation method. \fi \iffalse \section{Low Rate Region for Especial reaction-diffusion Equation}\label{AppA:2 } For $g(\lambda)=\sum_{i=0}^{\infty}a_i\lambda^{i}$, and given $\alpha$, we define two $n-$th approximations as below: \begin{align} &Approximation~1:~g(\lambda)\approx \sum_{i=0}^{n}a_i\lambda^{i}~~if~~ \lambda \lVert \frac{a_{n+1}}{a_n} \rVert_{\infty}\leq \alpha,\\ &Approximation~2:~g(\lambda)\approx \sum_{i=0}^{n}a_i\lambda^{i}~~if~~ \lVert \frac{\sum_{i=n+1}^{\infty}a_i\lambda^{i}}{\sum_{i=0}^{n}a_i\lambda^{i}} \rVert_{\infty}\leq \alpha. \end{align} For given $\alpha$ and observation time $T$, if $\lambda\leq\frac{3\alpha}{T^2}$, we have first kind of approximation of order $1$. For For given $n$ and $\alpha$, we say $\lambda$ is low rate of order $n$ if $\lambda$ satisfies approximation $1$ or $2$. The common values for $\alpha$ are $.1,.05$. In this paper we approximate solution up tp first term. Unfortunately, in chemical reaction-diffusion, derivation explicit formula for low rate region of solution is not tractable. In other words for given arbitrary $f_{\mathtt{A}},f_{\mathtt{B}},D_{\mathtt{A}},D_\mathtt{B}$ and $\alpha$ the range of low rate solution can be obtained only by simulation. Here we consider very special case. For given $\alpha$ and observation time $T$, if $\lambda\leq\frac{3\alpha}{T^2}$, we have first kind of approximation of order $1$. For second kind of approximation of order $1$, consider $I=\sum_{i=1}^{\infty}\lambda^{i}[\mathtt{A}]_i=\sum_{i=0}^{\infty}\lambda^{i}(-1)^{i}\alpha_{i}t^{2i+1}=I_1-I_2$, where $I_1=\sum_{i=1}^{\infty}\alpha_{2i}\lambda^{2i}t^{4i+1}$ and $I_2=\sum_{i=0}^{\infty}\alpha_{2i+1}\lambda^{2i+1}t^{4i+3}$. Using upper and lower bound on $\alpha_{i}$, for $\lambda\leq\frac{2}{T^2}$ we have: \begin{align*} &\dfrac{\lambda^2t^5}{9-\lambda^2t^4}\leq I_1\leq \dfrac{\lambda^2t^5}{4-\lambda^2t^4}\\ &\dfrac{3\lambda t^3}{9-\lambda^2t^4}\leq I_2\leq \dfrac{2\lambda t^3}{4-\lambda^2t^4}, \end{align*} we obtain: \begin{align*} &\dfrac{\lambda^2t^4}{9-\lambda^2t^4}-\dfrac{2\lambda t^2}{4-\lambda^2t^4}\leq \frac{I}{[\mathtt{A}]_{0}}\leq \dfrac{\lambda^2t^4}{4-\lambda^2t^4}-\dfrac{3\lambda t^2}{9-\lambda^2t^4}. \end{align*} Let $u=\lambda t^2$, we have: \begin{align*} &g_d(u)=\dfrac{u^2}{9-u^2}-\dfrac{2u}{4-u^2}\leq \frac{I}{[\mathtt{A}]_{0}}\leq g_{up}(u)=\dfrac{u^2}{4-u^2}-\dfrac{3u}{9-u^2}. \end{align*} For given $\alpha$, we obtain two fourth order equations($g_{up}(u)=\pm \alpha, g_{d}(u)=- \alpha $). By solving those equations, we can obtain upper bound on $\lambda$. For example for $\alpha=0.1$ we have $\lambda\leq \frac{1}{5T^2}$, and for $\alpha=0.01$ we obtain $\lambda\leq \frac{1}{50T^2}$. \fi \section{Proof of Theorem \ref{thmN1} }\label{AppA:3} The zero-order terms in the perturbation method satisfy \begin{align} &\frac{\partial [\mathtt{A}]_{0}}{\partial t}=D_\mathtt{A}~\frac{\partial^{2}[\mathtt{A}]_{0}}{{\partial x}^{2}}+f_\mathtt{A}(x,t),~~ \frac{\partial [\mathtt{B}]_{0}}{\partial t}=D_\mathtt{B}~\frac{\partial^{2} [\mathtt{B}]_{0}}{{\partial x}^{2}}+f_\mathtt{B}(x,t),~~ \frac{\partial [\mathtt{C}]_{0}}{\partial t}=D_\mathtt{C}~\frac{\partial^{2} [\mathtt{C}]_{0}}{{\partial x}^{2}},\\ &[\mathtt{A}]_{0}(x,0)=g_{\mathtt{A}}(x), ~[\mathtt{B}]_{0}(x,0)=g_{\mathtt{B}}(x), ~[\mathtt{C}]_{0}(x,0)=g_{\mathtt{C}}(x). \end{align} Setting $t=0$ in above equations we have: \begin{align} &\frac{\partial [\mathtt{A}]_{0}}{\partial t}(x,0)=D_\mathtt{A}~\frac{\partial^{2}[\mathtt{A}]_{0}(x,0)}{{\partial x}^{2}}+f_\mathtt{A}(x,0)=D_\mathtt{A} g_{\mathtt{A}}''(x)+f_\mathtt{A}(x,0). \end{align} Thus, $[\mathtt{A}]_{0}(x,t )=[\mathtt{A}]_{0}(x,0)+\frac{\partial [\mathtt{A}]_{0}}{\partial t}(x,0)t +o(t )=g_{\mathtt{A}}(x)+t D_\mathtt{A} g_{\mathtt{A}}''(x)+t f_\mathtt{A}(x,0)+o(t ). $ For other terms in perturbation solution we have ($i\geq 1$): \begin{align} &\frac{\partial[\mathtt{A}]_{i}}{\partial t}=D_\mathtt{A}~\frac{\partial^{2}[\mathtt{A}]_{i}}{{\partial x}^{2}}-[\mathtt{A}]_{0:i-1}*^d [\mathtt{B}]_{0:i-1}+\gamma[\mathtt{C}]_{i-1},~\quad[\mathtt{A}]_{i}(x,0)=0,\\ &\frac{\partial[\mathtt{B}]_{i}}{\partial t}=D_\mathtt{B}~\frac{\partial^{2}[\mathtt{B}]_{i}}{{\partial x}^{2}}-[\mathtt{A}]_{0:i-1}*^d [\mathtt{B}]_{0:i-1}+\gamma[\mathtt{C}]_{i-1},~\quad[\mathtt{B}]_{i}(x,0)=0,\\ &\frac{\partial[\mathtt{C}]_{i}}{\partial t}=D_\mathtt{C}~\frac{\partial^{2}[\mathtt{B}]_{i}}{{\partial x}^{2}}-[\mathtt{A}]_{0:i-1}*^d [\mathtt{B}]_{0:i-1}-\gamma[\mathtt{C}]_{i-1},~\quad[\mathtt{C}]_{i}(x,0)=0. \end{align} Setting $t=0$ in above equations we obtain: \begin{align} \frac{\partial[\mathtt{A}]_{1}}{\partial t}(x,0)= -g_{\mathtt{A}}(x)g_{\mathtt{B}}(x)+\gamma g_{\mathtt{C}}(x),\qquad \frac{\partial[\mathtt{A}]_{i}}{\partial t}(x,0)=0,\quad~~i\geq 2. \end{align} From the Taylor series expansion we have: \begin{align} &[\mathtt{A}]_{1}(x,t )=[\mathtt{A}]_{1}(x,0)+\frac{\partial [\mathtt{A}]_{1}}{\partial t}(x,0)t +o(t )=-t g_{\mathtt{A}}(x)g_{\mathtt{B}}(x)+t \gamma g_{\mathtt{C}}(x)+o(t ),\\ &[\mathtt{A}]_{i}(x,t )=[\mathtt{A}]_{i}(x,0)+ \frac{\partial [\mathtt{A}]_{i}}{\partial t}(x,0)t + \frac{\partial^{2}[\mathtt{A}]_{i}}{{\partial t}^2}(x,0)t ^2+o(t ^2)=\mathcal{O}(t ^2),~i\geq 2. \end{align} Therefore the perturbation solution is as follows: \begin{align} &[\mathtt{A}]_{PER}(x,t )=[\mathtt{A}]_{0}(x,t )+\lambda[\mathtt{A}]_{1}(x,t )+\sum_{i=2}^{\infty}\lambda^i[\mathtt{A}]_{i}(x,t )\nonumber\\ &=g_{\mathtt{A}}(x)+t D_\mathtt{A} g_{\mathtt{A}}''(x)+t f_\mathtt{A}(x,0)+\lambda(-t g_{\mathtt{A}}(x)g_{\mathtt{B}}(x)+t \gamma g_{\mathtt{C}}(x))+o(t )+\mathcal{O}(t^2). \end{align} Hence, $ [\mathtt{A}]_{PER}(x,t )=[\mathtt{A}]_{FDM}(x,t )+\mathcal{O}(t^2).$ \section{Poisson Hypothesis Testing }\label{AppB} In a Poisson hypothesis testing problem with two hypotheses, we take a sample from a Poisson random variable $X$ whose mean is either $\rho_0$ (under hypothesis $\textbf{H}_{0}$) or $\rho_1$ (under hypothesis $\textbf{H}_{1}$). Assume that the two hypotheses $\textbf{H}_{0}$ and $\textbf{H}_{1}$ are equally likely and $\rho_0<\rho_1$. The MAP decision rule compares the observed $X$ with threshold $\mathbb{T}_{h}=({\rho_1-\rho_0})/({\log{\rho_1}-\log{\rho_0}})$ and declares $\textbf{H}_{0}$ if and only if $X<\mathbb{T}_{h}$. The error probability of the MAP decision rule, denoted by $P_e(\rho_0, \rho_1)$, equals \begin{align} \frac{1}{2}\sum_{n\in\mathbb{Z}:~n\geq \mathbb{T}_{h}}^{\infty}\frac{e^{-\rho_0}\rho_{0}^{n}}{n!}+ \frac{1}{2}\sum_{n\in\mathbb{Z}:~0\leq n<\mathbb{T}_{h}}\frac{e^{-\rho_1}\rho_{1}^{n}}{n!} =\frac{1}{2}-TV(\mathsf{Poisson}(\rho_0),\mathsf{Poisson}(\rho_1)) \end{align} where $TV(\cdot,\cdot))$ is the total variation distance. \begin{lem}\label{decrese:error:pro} Fix some $\rho_0$. Then $P_e(\rho_0,\rho_1)$ is a decreasing continuous function of $\rho_1$ for $\rho_1\geq \rho_0$. \end{lem} \begin{proof} The above statement is equivalent with $TV(\mathsf{Poisson}(\rho_0),\mathsf{Poisson}(\rho_1))$ being an increasing continuous function of $\rho_1$ for $\rho_1\geq \rho_0$. When $\rho_1=\rho_0$, the total variation distance is zero and as we increase $\rho_1$, this distance increases. Since the distribution of $\mathsf{Poisson}(\rho_1)$ varies continuously, the changes in the total variation distance is also continuous in $\rho_1$. \end{proof} \section{Support Lemma}\label{AppC} Let $\mathbb{P}$ be the space of all unnormalized probability distributions on the interval $[0,T]$ (\emph{i.e.}, nonnegative functions with finite nonzero integral). For a distribution $p(t)\in\mathbb{P}$ and a continuous function $f(t)$, we define $ \mathbb{E}_{p}(f)=\int_{0}^{T} p(t)f(t) dt. $ \begin{lem} \label{SupportLemma} Take arbitrary continuous functions $f(t)$ and $f_i(t)$ for $i=1,2,\cdots, n$, and an arbitrary unnormalized distribution $p\in\mathbb{P}$. Then, there is another \emph{discrete} unnormalized distribution $q\in\mathbb{P}$ taking values in a set of size $n$, \emph{i.e.,} $q(t)=\sum_{i=1}^{n}{a}_{i}\delta(t-t_i)$ for some $a_i\geq 0$ and $t_i\in[0,T]$ such that \begin{align}\mathbb{E}_{q}(f)\leq \mathbb{E}_{p}(f)\label{eqn:C12}\end{align} and \begin{align}\mathbb{E}_{q}(f_i)= \mathbb{E}_{p}(f_i), \quad \text{for}~~i=1,\cdots, n.\label{eqn:Cn}\end{align} \end{lem} This lemma shows that by replacing $p$ with $q$, we preserve the $n$ linear constraints \eqref{eqn:Cn} and impose one linear inequality constraint \eqref{eqn:C12}. The support of $q$ (the number of delta functions) is at most the number of constraints which is $n$. Support lemmas of this type are commonly used in information theory, and follow from Fenchel-Bunt's extension of the Caratheodory theorem. For completeness, we give an intuitive sketch of the proof. For simplicity assume that $p(t)$ is discrete but with support on an arbitrarily large set, \emph{i.e.,} $p(t)=\sum_{i=1}^{N}g_{i}\delta(t-\tilde{t}_i)$ for some large $N$, and $g_i\geq 0$, $\tilde{t}_i\in[0,T]$. Consider functions of the form $\tilde{q}(t)=\sum_{i=1}^{N}x_{i}\delta(t-\tilde{t}_i) $ for some $x_1,\cdots, x_N\geq 0$. Consider the set of $(x_1, \cdots, x_N)$ for which we have $\mathbb{E}_{\tilde q}(f_i)= \mathbb{E}_{p}(f_i)$, for $i=1,\cdots, n$. This imposes $n$ linear constraints on $(x_1, \cdots, x_n)$. These $n$ linear constraints along with the inequality constraints $x_1, \cdots, x_N\geq 0$ define a polytope in the $N$-dimensional region. This polytope is nonempty since $(x_1, \cdots, x_N)=(g_1, \cdots, g_N)$ belongs to this polytope. To enforce the inequality \eqref{eqn:C12}, let us minimize $\mathbb{E}_{\tilde q}(f)$, which is a linear function in $(x_1, \cdots, x_N)$ over this polytope. The minimum of a linear function occurs at a vertex of the polytope. The key observation is that each vertex of the polytope has at most $n$ nonzero entries, \emph{i.e.,} if $(x^*_1, \cdots, x^*_N)$ is a vertex of the polytope, at most $n$ entries of $(x^*_1, \cdots, x^*_N)$ are nonzero. This would imply the desired identification for $q(x)$. To see this, observe that since the polytope is in $N$ dimensions, every vertex of the polytope lies at the intersection of $N$ hyperplanes. The hyperplanes defining the polytope are the $n$ linear constraints along with $x_1,\cdots, x_N\geq 0$. Any vertex has to satisfy $N$ of these equations with equality. Thus, the vertex needs to pick at least $N-n$ inequalities of the form $x_i\geq 0$ and satisfy them with equality. In other words, for any vertex, at least $N-n$ entries must be zero, meaning that the number of nonzero entries is at most $n$. \iffalse \section*{Acknowledgment} The authors would like to thank...\cite{6189388} \fi \ifCLASSOPTIONcaptionsoff \newpage \fi \section{Further Examples}\label{ex2,3} \subsection{Example 2: Reaction for Channel Amplification} The main example in Section \ref{sec::generalperturbation} used chemical reaction as a means to produce molecules that are detected by the receiver. However, reaction may be used for other purposes as well. For instance, it may be used to enhance the channel between the transmitter and the receiver. This concept is considered in the example below. Consider the following example with one transmitter and one receiver. The receiver can only measure the density of molecules of type $\mathtt{A}$ at its location. The transmitter is also able to release molecules of types $\mathtt{A}$ and $\mathtt{B}$ into the medium. Assume that there is an enzyme $\mathtt{C}$ in the medium (outside of our control) which reacts with molecules of type $\mathtt{A}$. If the level of enzyme $\mathtt{C}$ is high, molecules of type $\mathtt{A}$ are mostly dissolved before reaching the receiver. To overcome this, the transmitter may release molecules of a different type $\mathtt{B}$, which would also react with the enzyme $\mathtt{C}$ and thereby reduce the concentration of $\mathtt{C}$ in the medium. This ``cleaning" of the medium from molecules of type $\mathtt{C}$ would enhance the channel from the transmitter to the receiver. More specifically, assume that the medium is governed by the following chemical reactions: \begin{align} \ce{\mathtt{A} + \mathtt{C}&->[\lambda_1]\mathtt{P}_1},\label{eqnNew3}\\ \ce{\mathtt{B} + \beta \mathtt{C} &->[\lambda_2] \mathtt{P}_2},\label{eqnNew4} \end{align} where $\mathtt{P}_1$ and $\mathtt{P}_2$ are some products which do not include molecules of type $\mathtt{A},\mathtt{B}$ or $\mathtt{C}$. Here $\beta$ is a natural number. As an example, $\mathtt{A}$ and $\mathtt{B}$ can be two different acids, and $\mathtt{C}$ is a base substance (which reacts with acids $\mathtt{A}$ and $\mathtt{B}$). If $\mathtt{B}$ is a stronger acid than $\mathtt{A}$, the coefficient $\beta$ can be large, and release of $\mathtt{B}$ can be effective in canceling $\mathtt{C}$ from the medium. In \eqref{eqnNew3} and \eqref{eqnNew4}, let $\gamma=\lambda_2/\lambda_1$ be the ratio of the reaction rates. For simplicity of notation, set $\lambda_1=\lambda,\lambda_2=\gamma\lambda$. Assume that the reaction occurs in a two-dimensional medium. For our modeling purposes, suppose that the transmitter is located at the origin and the receiver is located at $(d,0)$. There is also an independent source that releases molecule of type $\mathtt{C}$ in the medium with a known concentration $f_{\mathtt{c}}(x,y,t)$ at time $t$. The source is assumed to be located at location $r_0$. See Fig \ref{fig:ex2} for a depiction of this setting. Following equations describe the system dynamic. \begin{align} &\frac{\partial[\mathtt{A}]}{\partial t}=D_\mathtt{A}~\bigtriangledown^2 [\mathtt{A}]-\lambda~[\mathtt{A}] [\mathtt{C}]+f_{\mathtt{A}}(x,y,t),\label{cartesian2dim:1}\\ &\frac{\partial[\mathtt{C}]}{\partial t}=D_\mathtt{C}~\bigtriangledown^2 [\mathtt{C}]-\lambda~([\mathtt{A}][\mathtt{C}]+\gamma[\mathtt{B}][\mathtt{C}]^{\beta})+f_{\mathtt{C}}(x,y,t),\label{cartesian2dim:2}\\ & \frac{\partial[\mathtt{B}]}{\partial t}=D_\mathtt{B}~\bigtriangledown^2 [\mathtt{B}]-\gamma\lambda~[\mathtt{B}] [\mathtt{C}]^{\beta}+f_{\mathtt{B}}(x,y,t),\label{cartesian2dim:3} \end{align} where $f_{\mathtt{A}}(x,y,t),f_{\mathtt{B}}(x,y,t)$ are input signals of the transmitter. The initial conditions for concentration of molecule of type $\mathtt{A}$ and type $\mathtt{B}$ are set to zero. For molecule of type $\mathtt{C}$, the initial condition is $[\mathtt{C}](x,y,0)=\mathcal{I}_{\text{int}}(x,y)$. We assume that $\mathcal{I}_{\text{int}}(x,y)$ is completely known. We assume that the diffusion occurs in the entire $\mathbb{R}^2$ and do not assume any boundaries for the medium. For the case of no reaction, $\lambda=0$, the system of equations has a closed-form solution. Consider a solution of the following form: \begin{align}\label{teylorex:2} &[\mathtt{A}](x,y,t)=\sum_{i=0}^{\infty}\lambda^{i}[\mathtt{A}]_{i}(x,y ,t),~ [\mathtt{C}](x,y,t)=\sum_{i=0}^{\infty}\lambda^{i}[\mathtt{C}]_{i}(x,y ,t),~ [\mathtt{B}](x,y,t)=\sum_{i=0}^{\infty}\lambda^{i}[\mathtt{B}]_{i}(x,y ,t). \end{align} By substituting \eqref{teylorex:2} in \eqref{cartesian2dim:1}, \eqref{cartesian2dim:2}, \eqref{cartesian2dim:3}, and matching the coefficients of $\lambda^0,\lambda^1,\lambda^2$ on both side of equations, we obtain the following equations: For particle $\mathtt{A}$ we have: \begin{align} &\frac{\partial[\mathtt{A}]_0}{\partial t}=D_\mathtt{A}~\nabla^2 [\mathtt{A}]_0+f_{\mathtt{A}}(x,y,t),~ \frac{\partial[\mathtt{A}]_1}{\partial t}=D_\mathtt{A}~\nabla^2 [\mathtt{A}]_1-[\mathtt{A}]_0 [\mathtt{C}]_0,\label{eq:ex2:A:01}\\ &\frac{\partial[\mathtt{A}]_2}{\partial t}=D_\mathtt{A}~\nabla^2 [\mathtt{A}]_2-([\mathtt{A}]_0 [\mathtt{C}]_1+[\mathtt{A}]_1 [\mathtt{C}]_0).\label{eq:ex2:A:2} \end{align} \newpage \begin{figure}[H] \centering \includegraphics[trim={1cm 0cm 0cm 0cm}, scale=.5]{slide2.png} \caption{MC system for Example $2$.} \label{fig:ex2} \vspace{-3em} \end{figure} \begin{figure}[H] \centering \includegraphics[trim={1cm 0cm 0cm 0cm}, scale=0.5]{slide3.png} \caption{MC system for Example $3$.} \label{fig:ex3} \end{figure} For molecule of type $\mathtt{C}$ we have: \begin{align}\label{eq:ex2:C} & \frac{\partial[\mathtt{C}_0]}{\partial t}=D_\mathtt{C}~\nabla^2 [\mathtt{C}]_0+f_{\mathtt{C}}(x,y,t),~~ \frac{\partial[\mathtt{C}]_1}{\partial t}=D_\mathtt{C}~\nabla^2 [\mathtt{C}]_1-(\gamma[\mathtt{C}]_{0}^{\beta} [\mathtt{B}]_0+[\mathtt{C}]_{0}[\mathtt{A}]_0). \end{align} To impose the initial condition for concentration of molecule of type $\mathtt{C}$, We set $[\mathtt{C}]_{0}(x,y,0)=\mathcal{I}_{\text{int}}(x,y)$ and for $i\geq 1$ we set $[\mathtt{C}]_{i}(x,y,0)=0$. For particle $\mathtt{B}$ we have: \begin{align}\label{eq:ex2:B} &\frac{\partial[\mathtt{B}]_0}{\partial t}=D_\mathtt{B}~\nabla^2 [\mathtt{B}]_0+f_{\mathtt{B}}(x,y,t). \end{align} Let $\phi_{\mathtt{A}}(x,y,t)$ be the impulse response of heat equation with $D_\mathtt{A}$, \begin{align} \frac{\partial \phi_\mathtt{A}}{\partial t}=D_\mathtt{A}~\nabla^2(\phi_\mathtt{A})+\delta(x)\delta(y)\delta(t). \end{align} we have: \begin{align}\label{greentwo} \phi_\mathtt{A}(x,y,t)=\frac{1}{4\pi D_\mathtt{A} t}\exp(-\frac{x^2+y^2}{4 D_\mathtt{A} t}),~~t\geq 0. \end{align} Similarly, $\phi_{\mathtt{B}}(x,y,t)$ and $\phi_{\mathtt{C}}(x,y,t)$ are the impulse responses of the heat equations with diffusion coefficients $D_\mathtt{B}$ and $D_\mathtt{C}$ respectively. The solutions of \eqref{eq:ex2:A:01},\eqref{eq:ex2:A:2},\eqref{eq:ex2:C}, and \eqref{eq:ex2:B} are: \begin{align} &[\mathtt{A}]_0=\phi_\mathtt{A}**f_{\mathtt{A}},~[\mathtt{C}]_0= \phi_\mathtt{C}**(f_{\mathtt{C}}+D_{\mathtt{C}}\nabla^{2}\mathcal{I}_{\text{int}})+\mathcal{I}_{\text{int}}, ~[\mathtt{B}]_0=\phi_\mathtt{B}**f_{\mathtt{B}},\label{ex2:final:sol:1}\\&[\mathtt{A}]_1=- \phi_\mathtt{A}**([\mathtt{A}]_0 [\mathtt{C}]_0), ~[\mathtt{C}]_1=-\phi_\mathtt{C}**(\gamma[\mathtt{B}]_0 [\mathtt{C}]_0^{\beta}+[\mathtt{C}]_0 [\mathtt{A}]_0),\label{ex2:final:sol:2}\\ &[\mathtt{A}]_2=-\phi_{\mathtt{A}}**([\mathtt{A}]_0 [\mathtt{C}]_1+ [\mathtt{A}]_1 [\mathtt{C}]_0).\label{ex2:final:sol:3} \end{align} The density of molecule $\mathtt{A}$ is equal to: \begin{align}\label{ex2:Asol} [\mathtt{A}](x,y,t)= [\mathtt{A}]_0+\lambda [\mathtt{A}]_1+\lambda^{2} [\mathtt{A}]_2 +\mathcal{O}(\lambda^3) \end{align} For low reaction rates, we can approximate \eqref{ex2:Asol} as follows: \begin{align}\label{ex2:Asol2} [\mathtt{A}](x,y,t)\approx [\mathtt{A}]_0+\lambda [\mathtt{A}]_1+\lambda^{2} [\mathtt{A}]_2(x,y,t) \end{align} Using the above model, we design a modulation scheme in Section \ref{mod:ex2}. \subsection{Modulation Design For Example 2}\label{mod:ex2} Consider a communication scenario consisting of a transmitter and a receiver. The transmitter releases molecules of type $\mathtt{A}$ and $\mathtt{B}$ into the medium to encodes a message $M_{\mathtt{A}}\in\{0,1\}$. The concentration of the released molecules of type $\mathtt{A}$ is described by the input signal $f_{\mathtt{A}}^{i}(x,y,t) =a_i(t)\delta(x)\delta(y)$,$0\le t\le T$ for $i=0,1$. In other words, the density of released molecules of type $\mathtt{A}$ at time $t$ is $a_{M_{\mathtt{A}}}(t)$ if message $M_{\mathtt{A}}$ is transmitted for $t\in[0,T]$. Similarly, $f_{\mathtt{B}}(x,y,t)=b_{M_{\mathtt{A}}}(t)\delta(x)\delta(y)$ is the released concentration of molecules of type $\mathtt{B}$ where $b_0(t)$ and $b_1(t)$ are two nonnegative waveforms for $t\in[0,T]$. The total amount of released molecules of type $\mathtt A ,\mathtt B $ during the transmission period $T$ is assumed to be at most $s_{\mathtt A},s_{\mathtt B}$ respectively, \emph{i.e.,} \begin{align}\int_{0}^T a_i(t)dt\leq s_{\mathtt A},~\int_{0}^T b_i(t)dt\leq s_{\mathtt B} \quad i=0,1.\label{eqn:power2a} \end{align} Finally, we assume that molecules of type $\mathtt C$ are being continuously generated throughout the medium according to some function $f_{\mathtt{C}}(x,y,t)$ for $x,y\in\mathbb{R}$, $t\in[0,T]$. The function $f_{\mathtt{C}}(x,y,t)$ and the initial density $[\mathtt{C}](x,y,0)$ at time $t=0$ are assumed to be completely known to the receiver and the transmitter. Receiver samples the number of molecules of type $\mathtt{A}$ at $(x=0,y=d,t=T)$. Similar to Example 1, receiver gets a number from a Poisson distribution with parameter $[\mathtt{A}](0,d,T)$. As before, the probability of error is defined as \begin{equation} Pr(e)=Pr\{ M_{\mathtt{A}}\neq \hat{M}_\mathtt{A}\}, \end{equation} where $\hat{M}_\mathtt{A}\in\{0,1\}$ is the receiver's decoded message bit. Similar to Example 1, we wish to minimize the error probability by choosing the best possible waveforms $a_i(t)$ and $b_j(t)$. The following theorem states that in the low reaction rate regime (for the approximate reaction-diffusion equations when we consider first terms in the Taylor series expansion), one possible optimal waveforms $a_i(t)$ and $b_i(t)$ that achieve minimum probability of error are as follows: \begin{theorem}\label{th::2} For any given noise source $f_{\mathtt{C}}(x,y,t)$, and any arbitrary initial condition $\mathcal{I}_{int}(x,y)$, one choice for optimal order one waveforms $a_i(t),b_i(t)$ are as follows: \begin{align} &a_0(t)=0,~a_1(t)= s_\mathtt{A}\delta(t-t^{[a_1]}),~b_0(t)=0,~b_1(t)=s_{\mathtt{B}}\delta(t-t^{[b_1]}). \end{align} for some $t^{[a_1]},t^{[b_1]}\in [0,T]$ which depend on $f_{\mathtt{C}}(x,y,t)$, and $\mathcal{I}_{int}(x,y)$. \end{theorem} \begin{proof}\label{AppF} Substituting $f_\mathtt{A}^{i}(x,t),f_\mathtt{B}^{i}(x,t),i=0,1$ in \eqref{recu-eq1}-\eqref{recu-eq3}, one obtains an explicit formula for the (first-order approximation of the) concentration of molecules $\mathtt{A}$ in terms of the input signals. In particular, the concentration $[\mathtt{A}]$ at receiver's location at the sampling time $T$ is as follows: \begin{equation*}\label{rho::ex2} \begin{aligned} [\mathtt{A}](d,0,T)=&[\mathtt{A}]_{0}(d,0,T)+\lambda [\mathtt{A}]_{1}(d,0,T)+\lambda^2[\mathtt{A}]_{2}(d,0,T).\\ \end{aligned} \end{equation*} Observe from \eqref{ex2:final:sol:1}, \eqref{ex2:final:sol:2}, and \eqref{ex2:final:sol:3} that $[A]_{0}(x,y,t)$ and $[A]_{1}(x,y,t)$ are linear functions of $a_{M_{\mathtt{A}}}(t)$ and do not depend on $b_{M_{\mathtt{A}}}(t)$. However, $[A]_{2}(x,y,t)$ depends on both $a_{M_{\mathtt{A}}}(t)$ and $b_{M_{\mathtt{A}}}(t)$. It is a nonlinear function of $a_{M_{\mathtt{A}}}(t)$. However, if we fix $a_{M_{\mathtt{A}}}(t)$, $[A]_{2}(x,y,t)$ is a linear and positive function in $b_{M_{\mathtt{A}}}(t)$. Let \begin{equation}\label{densitiees::ex2:final} \rho=\left\{ {\begin{array}{*{20}{llll}} \rho_{0}=[\mathtt{A}](d,0,T)& & \text{if}&M_{\mathtt{A}}=0\\ \rho_{1}=[\mathtt{A}](d,0,T)& & \text{if}&M_{\mathtt{A}}=1.\\ \end{array}}\right. \end{equation} Receiver is assumed to be transparent and due to the particle counting noise, it observes a sample from $\mathsf{Poisson}(V\rho_{ M_{\mathtt{A}}}) $ for some constant $V$. Since the effect of molecule $\mathtt{B}$ appears in $\lambda^{2}$ coefficient in the expansion $[\mathtt{A}]=\sum_{=i=0}^{\infty}\lambda^{i}[A]_{i}(x,y,t)$ (i.e, $[\mathtt{A}]_{2}(d,0,T)$), we find optimal waveform of order two for $b_{M_{\mathtt{A}}}(t)$. For $a_{M_{\mathtt{A}}}(t)$ we find optimal waveform of order one. According to Lemma \ref{decrese:error:pro} in Appendix \ref{AppB}, the error probability is a decreasing function of $|\rho_1-\rho_0|$, hence by minimizing $\rho_0$ and maximizing $\rho_1$ the optimal solution can be obtained. Since $\rho_0\geq 0$, we set $a_0(t),b_0(t)=0$ to minimize $\rho_0$ and we get $\rho_0=0$. Fix some $a_1(t)$, and let $b_{1}^{\text{opt}}(t)$ be a maximizer of $\rho_1$. Since the expression for $\rho_1(a_1(t),b_{1}(t))$, up to its second-order term, is linear in $b_1(t)$ for a fixed value of $a_1(t)$, according to Lemma \ref{SupportLemma} there is waveform of the form $b_{1}^{*}(t)=\hat{b}_{1}\delta(t-t^{[b_1]})$ with a total power \eqref{eqn:power2a} less than or equal to the power of $b_{1}^{\text{opt}}(t)$ such that (up to the second-order terms), we have $\rho_1(a_1(t),b_{1}^{\text{opt}}(t))=\rho_1(a_1(t),b_{1}^{*}(t))$. In other words, replacing $b_{1}^{\text{opt}}(t)$ with $b_{1}^{*}(t)$ would not change the value of $\rho_1$, or the error probability. As $b_{1}^{*}(t)=\hat{b}_{1}\delta(t-t^{[b_1]})$ has a total power constraint $s_{\mathtt{B}}$, we obtain $b_{1}\leq s_{\mathtt{B}}$. Since $\rho_1(a_1(t),b_{1}^{*}(t))$ is an increasing function in $\hat{b}_{1}$, we deduce that $\hat{b}_1=s_{\mathtt{B}}$ maximizes $\rho_1$. Next, in order to obtain the first-order optimal waveform for $a_1(t)$, we recall that $\rho_1$ up to the first-order is a linear function of only $a_1(t)$. According to Lemma \ref{SupportLemma} for any arbitrary $a_{1}(t)$ there is some ${a}_{1}^{*}(t)=\hat{a}_{1}\delta(t-t^{[a_1]})$ with a total power less than or equal to the power of $a_1(t)$ such that (up to order one terms) $\rho_{1}(a_1(t))=\rho_{1}(a_{1}^{*}(t))$. Then, as above the power constraint implies that $\hat{a}_{1}\leq s_{\mathtt{A}}$. Since (up to order one terms), $\rho_{1}(a_{1}^{*}(t))$ is an increasing function with respect to $\hat{a}_{1}$ we deduce $\hat{a}_{1}=s_{\mathtt{A}}$. That completes the proof. \end{proof} In order to determine parameters in the statement of Theorem \ref{th::2} we need optimize over constants $t^{[a_1]},t^{[b_1]}$. As an example, consider the values of system parameters as follows in Table \ref{tabex2}. \begin{table} \centering \caption{Parameters} \label{tabex2} \begin{tabular}{ |c|c|c| } \hline \multirow{2}{*}{$(D_{\mathtt{A}},D_{\mathtt{B}},D_{\mathtt{C}})[m^{2}s^{-1}]$} &\multirow{2}{*} {$10^{-10}\times(10,1.1,1)$}\\ &\\ \hline \multirow{2}{*} {$\lambda[molecules^{-1}.m^{3}.s^{-1}]$} & \multirow{2}{*}{$ 10^{-23}$}\\ &\\ \hline \multirow{2}{*}{$V[m^{3}]$} &\multirow{2}{*} {$2.5\times10^{-7}$}\\ &\\ \hline \multirow{2}{*}{$(T[s],\beta,\gamma)$ }& \multirow{2}{*}{$(10,2,1)$} \\ &\\ \hline \multirow{2}{*}{$(d_{\mathtt{B}} [m],d_{\mathtt{c}} [m])$} & \multirow{2}{*}{$5\times 10^{-5}\times((1,1),(10,0))$ } \\ &\\ \hline \multirow{2}{*}{$(\mathcal{I}_{int}(x,y),f_{mathtt{c}}(x,y,t))$} & \multirow{2}{*}{$(0,4\times 10^{4}\delta(x-5\times 10^{5})\delta(y-5\times 10^{5})\delta(t))$} \\ &\\ \hline \multirow{2}{*}{$s_{\mathtt{A}}[molecules.m^{-3}],s_{\mathtt{B}}[molecules.m^{-3}])$} & \multirow{2}{*}{$10^8\times(5,24)$} \\ &\\ \hline \end{tabular} \end{table} Simulation results yield the optimal values for $t^{[a_1]},t^{[b_1]}$ as $t^{[a_1]}=5.62,t^{[b_1]}=0$. Also, when we vary $s_{\mathtt A}\in [500,5\times 10^{11}]$ while we fix the other parameters, we observe that $t^{[b_1]}$ remains zero. In other words, it is best to release molecules of type $\mathtt B$ as soon as interfering molecules of type $\mathtt C$ are released. Moreover, the value of $t^{[a_1]}$ is almost constant as we vary $s_{\mathtt A}$. \subsection{Example 3: Reaction for Two-way Communication } Finally, our third example considers two transceivers (who are able to both transmit and receive signals) in a three-dimensional setting. Consider two molecular transceivers $\mathsf T_1$ and $\mathsf T_2$. The transceiver $\mathsf T_1$ is able to release molecules of type $\mathtt{A}$ and receive molecules of type $\mathtt{B}$. On the other hand, the transceiver $\mathsf T_2$ is able to release molecules of type $\mathtt{B}$ and receive molecules of type $\mathtt{A}$. If there is no reaction between $\mathtt{A}$ and $\mathtt{B}$, we have two distinct directional channels between the two transceivers (e.g., one channel is formed by $\mathsf T_1$ releasing molecules of type $\mathtt{A}$ and $\mathsf T_2$ receiving them). However, if $\mathtt{A}$ reacts with $\mathtt{B}$ in the medium, the two channels become entangled. This would impact the transmission strategy of the two transceivers if they wish to establish a two-way communication channel, and send and receive messages at the same time. The chemical reaction would weaken both signals in this case. Assume that \begin{equation} \ce{\mathtt{A} + \mathtt{B} ->[\lambda] \mathtt{P}}. \end{equation} The following equations describe the dynamic of the system: \begin{align} &\frac{\partial[\mathtt{A}]}{\partial t}=D_\mathtt{A}\nabla^2[\mathtt{A}]-\lambda~[\mathtt{A}][\mathtt{B}]+f_\mathtt{A}(\vec{x},t),~\frac{\partial[\mathtt{B}]}{\partial t}=D_\mathtt{B}\nabla^2[\mathtt{B}]-\lambda~[\mathtt{A}][\mathtt{B}]+f_\mathtt{B}(\vec{x},t),\label{ex3:eq} \end{align} where $f_\mathtt{A}(\vec{x},t),f_\mathtt{B}(\vec{x},t)$ are input signals of the two transceivers. The initial conditions are set to zero, and we allow diffusion in the entire $\mathbb{R}^3$ with no boundaries. As before, for $\lambda=0$ the system of equations is linear and analytically solvable. Consider a solution of the following form: \begin{align}\label{teylorex:2N} &[\mathtt{A}](\vec{x},t)=\sum_{i=0}^{\infty}\lambda^{i}[\mathtt{A}]_{i}(\vec{x} ,t),~[\mathtt{B}](\vec{x},t)=\sum_{i=0}^{\infty}\lambda^{i}[\mathtt{B}]_{i}(\vec{x} ,t). \end{align} By matching the coefficients of $\lambda^0,\lambda^1$ on the both side of equations, we can find a solution for in low reaction rate regime. By matching the constant terms, we obtain \begin{align}\label{ex3:firstterm} &\frac{\partial[\mathtt{A}]_0}{\partial t}=D_\mathtt{A} \nabla^{2}[\mathtt{A}]_0 +f_\mathtt{A}(\vec{x},t),~\frac{\partial[\mathtt{B}]_0}{\partial t}=D_\mathtt{B}\nabla^{2}[\mathtt{B}]_0 +f_\mathtt{B}(\vec{x},t). \end{align} By matching the coefficients of $\lambda$, we get \begin{align}\label{ex3:secondterm} &\frac{\partial[\mathtt{A}]_1}{\partial t}=D_\mathtt{A} \nabla^{2}[\mathtt{A}]_1 -[\mathtt{A}]_{0}[\mathtt{B}]_{0},~\frac{\partial[\mathtt{B}]_1}{\partial t}=D_\mathtt{B}\nabla^{2}[\mathtt{B}]_1 -[\mathtt{A}]_{0}[\mathtt{B}]_{0}. \end{align} The impulse response for heat equation is as follows: \begin{equation}\label{greenthree} \phi_\mathtt{A}(\vec{x},t)=\frac{1}{(4\pi D_\mathtt{A}t)^{\frac{3}{2}} }\exp(-\frac{\lVert\vec{x}\rVert_{2}^{2}}{4 D_\mathtt{A} t}), ~~\vec{x}\in \mathbb{R}^{3}~,t\geq 0. \end{equation} The solution of \eqref{ex3:firstterm}, \eqref{ex3:secondterm} are given in the following form. \begin{align}\label{ex:3:final:density} &[\mathtt{A}]_0=\phi**f_\mathtt{A},~ [\mathtt{B}]_0=\phi**f_\mathtt{B},~ [\mathtt{A}]_1=- \phi_{\mathtt{A}}**([\mathtt{A}]_0 [\mathtt{B}]_0),~ [\mathtt{B}]_1=- \phi_{\mathtt{B}}**([\mathtt{A}]_0 [\mathtt{B}]_0). \end{align} This results in the following solution for low reaction rates: \begin{align}\label{ex3::finalsol} &[\mathtt{A}](\vec{x},t)= [\mathtt{A}]_0(\vec{x},t)+\lambda [\mathtt{A}]_1(\vec{x}, ,t)+\mathcal{O}(\lambda^2),~[\mathtt{B}](\vec{x},t)= [\mathtt{B}]_0(\vec{x},t)+\lambda [\mathtt{B}]_1(\vec{x}, ,t)+\mathcal{O}(\lambda^2). \end{align} Using these equations, we design a modulation scheme in Section \ref{mod:ex3}. \subsection{Design of Modulation For Example 3}\label{mod:ex3} Suppose transceivers $ \mathsf T_{\mathtt {A}}, \mathsf T_{\mathtt {B}}$ encode messages $M_{\mathtt{A}},M_{\mathtt{B}}\in\{0,1\}$ with input signals $f_{\mathtt{A}}^{i}(\vec{x},t) =a_i(t)\delta(\vec{x}),f_{\mathtt{B}}^{i}(\vec{x},t) =b_i(t)\delta(\vec{x}-\vec{d_{\mathtt{B}}})$, for $0\le t\le T$ and $i=0,1$, where $\vec{d_\mathtt{B}}=(d,0,0) $ is the location of $\mathsf T_{\mathtt {B}}$. In other words, transceiver $ \mathsf T_{\mathtt {A}}$ releases a concentration of $a_{M_{\mathtt{A}}}(t)$ at origin, and transceiver $ \mathsf T_{\mathtt {B}}$ releases a concentration of $b_{M_{\mathtt{B}}}(t)$ at its location $\vec{d_\mathtt{B}}$. As before, we restrict the total amount of released molecules of types $\mathtt A$ and $\mathtt B$ during the transmission period $T$ as follows: \begin{align}\int_{0}^T a_i(t)dt\leq s_{\mathtt A},~\int_{0}^T b_j(t)dt\leq s_{\mathtt B} \quad i=0,1.\label{eqn:power3a} \end{align} Transceiver $\mathsf{T_{\mathtt {A}}}$ samples the medium for molecules of type $\mathtt {A}$ at the end of the time slot at time $t=T$, and uses its observation to decode the message $\hat{M}_{\mathtt{B}}$. Similarly, transceiver $\mathsf{T_{\mathtt {B}}}$ decodes the message $\hat{M}_{\mathtt{A}}$ using its sample at time $T$. Four error probabilities could be considered in our problem: since transceiver $ \mathsf T_{\mathtt {B}}$ knows transmitted message $M_{\mathtt{B}}$, for this transceiver we can consider error probabilities \begin{align*}&J_1:= Pr(M_{\mathtt{A}}\neq \hat M_{\mathtt{A}}|M_{\mathtt{B}}=0), ~J_2:= Pr(M_{\mathtt{A}}\neq \hat M_{\mathtt{A}}|M_{\mathtt{B}}=1)\end{align*} Similarly, for transceiver $ \mathsf T_{\mathtt {A}}$, we can consider \begin{align*}&J_3:= Pr(M_{\mathtt{B}}\neq \hat M_{\mathtt{B}}|M_{\mathtt{A}}=0),~ J_4:= Pr(M_{\mathtt{B}}\neq \hat M_{\mathtt{B}}|M_{\mathtt{A}}=1)\end{align*} We would like to make $J_1, J_2, J_3, J_4$ as small as possible by choosing optimal waveforms $a_i(t)$ and $b_j(t)$. Since there is a tradeoff between minimizing $J_1, J_2, J_3$ and $J_4$, we can choose a cost function $\mathcal{H}:[0,1]^{4}\rightarrow \mathbb{R}$ and minimize $\mathcal{H}(J_{1},J_{2},J_{3},J_{4})$. While we could choose any arbitrary cost function, for simplicity of exposition, we adopt $\mathcal{H}(J_1,J_2,J_3,J_4)=\sum_{i=1}^{4}\omega_{i}\log(J_{i}) $ for some constants $\omega_{i}, i=1, \cdots,4$. This particular choice for $\mathcal{H}$ leads to very simple optimal waveforms $a_i(t)$ and $b_j(t)$ in the low reaction regime as shown in the following theorem (other choices for $\mathcal{H}$ result in more delta terms in the optimal waveform). \begin{theorem}\label{th::3} One choice for optimal order one waveforms $a_i(t), b_i(t)$ is as follows: \begin{align} &a_0(t)=0,~a_1(t)=\hat{a}_{1}\delta(t-t^{[a_1]}),~b_0(t)=0,~b_1(t)=\hat{b}_{1}\delta(t-t^{[b_1]}). \end{align} for some $\hat{a}_{1},\hat{b}_{1},t^{[a_1]},t^{[b_1]}$. \end{theorem} \begin{proof} By substituting $f_{\mathtt{A}}^{0}(\vec{x},t),f_{\mathtt{A}}^{1}(\vec{x},t),f_{\mathtt{B}}^{0}(\vec{x},t)$ and $f_{\mathtt{B}}^{1} (\vec{x},t)$ in \eqref{ex:3:final:density}, \eqref{ex3::finalsol}, the density of molecule $\mathtt{A}$ at $\vec{d}_{\mathtt{B}}$ and density of molecule $\mathtt{B}$ at $\vec{d}_{\mathtt{A}}=\vec{0}$ have an explicit formula with respect to input signals. The concentration of molecule of type $\mathtt{A}$ at location of $\mathsf{T_{\mathtt {B}}}$ at the sampling time $T$ is $ [\mathtt{A}](\vec{d}_ {\mathtt{B}},T)=\zeta_1-\zeta_2,$ where: \begin{align} \zeta_1=\int_{0}^{T} \phi_{\mathtt{A}}(\vec{d}_{\mathtt{B}},T-t^{'})a_{M_\mathtt{A}}(t^{'})dt^{'}, \end{align} and \begin{align} \zeta_2= \lambda \int_{0}^{T} \int_{\mathbb{R}^3}\int_{0}^{t'} \int_{0}^{t'} &\phi_{\mathtt{A}}(\vec{d}_{\mathtt{B}}-\vec{x}',T-t')\phi_{\mathtt{A}}(\vec{x}',t'-t_1) \phi_{\mathtt{B}}(\vec{x}'-\vec{d}_{\mathtt{B}},t'-t_2) \nonumber\\&a_{M_{\mathtt{A}}}(t_1) b_{M_{\mathtt{B}}}(t_2) dt_{1}dt_{2}d\vec{x}'dt'. \end{align} A similar expression holds for the concentration of molecule $[\mathtt B]$ at the location of $\mathsf{T_{\mathtt {A}}}$ at sampling time $T$ (by simply swapping $\mathtt{A}\rightleftharpoons\mathtt{B}$ in the above formula). Observe that $[\mathtt{A}](\vec{d}_{\mathtt{B}},T)$ and $[\mathtt{B}](\vec{0},T)$ are bilinear functions with respect to input signals. Let $\rho_{m_{\mathtt{B}}=0}^{\mathtt{A}}$ be the concentration of molecules of type $\mathtt{A}$ at transceiver $\mathtt{B}$ if $m_{\mathtt{B}}=0$. Similarly, we define $\rho_{m_{\mathtt{B}}=1}^{\mathtt{A}}$. Also, $\rho_{m_{\mathtt{A}}=1}^{\mathtt{B}}$ denotes the concentration of molecules of type $\mathtt{B}$ at transceiver $\mathtt{A}$ if $m_{\mathtt{A}}=0$, etc. Transceivers are assumed to be transparent. Due to the counting noise transceiver $\mathtt{A}$ observes a sample from $\mathsf{Poisson}(V\rho^{\mathtt{A}}_{m_{\mathtt{B}}})$ for some constant $V$. A similar statement holds for transceiver $\mathtt{B}$. According to Lemma \ref{decrese:error:pro} error probabilities $J_1,J_2,J_3,J_4$ are decreasing functions of $|\rho_{01}^{\mathtt{B}}-\rho_{00}^{\mathtt{B}}|, |\rho_{11}^{\mathtt{B}}-\rho_{10}^{\mathtt{B}}|, |\rho_{01}^{\mathtt{A}}-\rho_{00}^{\mathtt{A}}|, |\rho_{11}^{\mathtt{A}}-\rho_{10}^{\mathtt{A}}|$ respectively. By minimizing non negative numbers $\rho_{00}^{\mathtt{B}}, \rho_{10}^{\mathtt{B}}$, $\rho_{00}^{\mathtt{A}},\rho_{10}^{\mathtt{A}}$ the probabilities reduce. We set $a_0(t),b_0(t)=0$ to achieve $(\rho_{00}^{\mathtt{B}}, \rho_{10}^{\mathtt{B}}, \rho_{00}^{\mathtt{A}},\rho_{10}^{\mathtt{A}})=(0,0,0,0)$. To obtain $a_1(t),b_1(t)$, we consider cost function $\mathcal{H}(J_1,J_2,J_3,J_4)=\sum_{i=1}^{4}\omega_{i}\log(J_{i})$ for some constants $\omega_{i}, i=1, \cdots,4$. The expression for $\mathcal{H}(J_1,J_2,J_3,J_4)$ becomes a bilinear function of $a_1(t),b_1(t)$ since \begin{align} \mathcal{H}(J_1,J_2,J_3,J_4)=&-\omega_{1}\zeta_{1}(\vec{d}_{\mathtt{B}},a_{1})-\omega_{2}\zeta_{2}(\vec{d}_{\mathtt{B}},a_{1},b_{1})-\omega_{3}\zeta_{1}(\vec{d}_{\mathtt{A}},b_{1})-\omega_{4}\zeta_{2}(\vec{d}_{\mathtt{A}},a_{1},b_{1})\nonumber\\&-\sum_{i=1}^{4}\omega_{i}\log(2). \end{align} Fix some $b_{1}(t)$ and let $a_{1}^{\text{opt}}(t)$ be maximizer of $\mathcal{H}$, according to Lemma \ref{SupportLemma} there is a waveform of the form ${a}_{1}^{*}(t)=\hat{a}_{1}\delta(t-t^{[a_1]})$ with a total power \eqref{eqn:power3a} less than or equal to $a_{1}^{\text{opt}}(t)$ such that it dos not affect the value of $\mathcal{H}$, \emph{i.e.}, $\mathcal{H}(a_{1}^{\text{opt}}(t),b_{1}(t))=\mathcal{H}(a_{1}^{*}(t),b_{1}(t))$. As ${a}_{1}^{*}(t)=\hat{a}_1\delta(t-t^{[a_1]})$ has a total power constraint $s_{\mathtt{A}}$, we obtain $\hat{a}_{1}\leq s_{\mathtt{A}}$. Hence ${a}_{1}^{\text{opt}}(t)=\hat{a}_1\delta(t-t^{[a_1]})$. By similar argument we can deduce that the one choice for optimal waveform $b_{1}(t)$ is ${b}_{1}^{*}(t)=\hat{b}_1\delta(t-t^{[b_1]})$ for some constant $\hat{b}_1\leq s_{\mathtt{B}},t^{[b_1]}\leq T$ . That completes the proof. \end{proof} In order to determine parameters in the statement of Theorem \ref{th::3} we need optimize over constants $\hat{a}_{1},\hat{b}_{1},t^{[a_1]},t^{[b_1]}$. \begin{table} \centering \caption{Parameters} \label{tabex3} \begin{tabular}{ |c|c|c| } \hline \multirow{2}{*}{$(D_{\mathtt{A}},D_{\mathtt{B}})[m^{2}s^{-1}]$} &\multirow{2}{*} {$10^{-10}\times(10,1.1)$}\\ &\\ \hline \multirow{2}{*} {$\lambda[molecules^{-1}.m^{3}.s^{-1}]$} & \multirow{2}{*}{$ 10^{-30}$}\\ &\\ \hline \multirow{2}{*}{$V[m^{3}]$} &\multirow{2}{*} {$2.5\times10^{-14}$}\\ &\\ \hline \multirow{2}{*}{$T[s]$ }& \multirow{2}{*}{$10$} \\ &\\ \hline \multirow{2}{*}{$d_{\mathtt{B}} [m]$} & \multirow{2}{*}{$10^{-4}\times(1,1,1)$ } \\ &\\ \hline \multirow{2}{*}{$(s_{\mathtt{A}}[molecules.m^{-3}],s_{\mathtt{B}}[molecules.m^{-3}])$} & \multirow{2}{*}{$10^8\times(5,24)$} \\ &\\ \hline \end{tabular} \end{table} Simulation results yield the optimal values for $\hat{a}_{1},\hat{b}_{1},t^{[a_1]},t^{[b_1]}$ as $\hat{a}_{1}=2\times 10^{8} ,\hat{b}_{1}=2.4\times 10^{9},t^{[a_1]}=0,$ and $t^{[b_1]}=0$. \bibliographystyle{IEEEtran}
{'timestamp': '2021-06-04T02:07:55', 'yymm': '2005', 'arxiv_id': '2005.14296', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14296'}
arxiv
\section{Introduction} Crowdsourced software engineering offers many opportunities for reducing time-to-market, producing alternative solutions, employing experts, learning through work, and democratizing participation in software engineering. There are several types of crowdsourced software engineering. One of the oldest and most common is open source software development. Another approach is competition-based crowdsourcing, where platforms such as TopCoder have increasingly become very popular with over 1,500,000 users. A more recent form of crowdsourced software engineering is microtask programming. Microtask programming decontextualizes work into self-contained microtasks, reducing the context necessary to onboard onto a software project and thereby decreasing joining barriers. At the same time, it may reduce the time to market for completing software work through parallelism. Several prior systems have explored approaches for microtasking programming work, using either manual or automatic approaches for decomposing programming tasks into microtasks. Manual approaches rely on a developer~\cite{codeon2017} or client to author each microtask~\cite{lasecki2015apparition}. Microtask programming environments can reduce onboarding barriers through preconfigured web-based environments, such as Codepilot, CrowdCode, and Collabode\cite{CodePilot:2017,Collabode:2011,latoza2018microtask}. However, existing approaches for crowdsourced software development have significant limitations. Open-source software development and competition-based approaches suffer from onboarding barriers, both technical and social. Although there are countless examples of successful open-source projects, onboarding challenges for newcomers can make it difficult to quickly onboard new developers and dissuade casual contributors. Microtask programming approaches can reduce onboarding barriers, both by offering a preconfigured environment as well as by enabling developers to do programming work with less prior knowledge or awareness of the complete project. But existing approaches are still limited in their support for design and architecture activities necessary to scale to larger software projects. Moreover, decontextualizing programming work is hard, bringing with it many challenges in doing it effectively. For example, conflicts may occur when two crowd workers make conflicting assumptions, necessitating approaches to reduce or repair conflicts as they occur~\cite{latoza2018microtask}. In my work, I have been exploring new ways to increase the \textit{scale} of microtask programming. I have developed a new behavior-driven development approach to microtask programming and conducted a series of studies to investigate the costs and benefits of microtask programming. In future work, I expect to continue to work to scale microtask programming to larger and more complex projects. \begin{figure*} \includegraphics[width=\textwidth,width=18cm, height= 8cm,keepaspectratio,clip]{figures/Implement_task2.pdf} \centering \caption{In our behavior-driven microtask programming approach, developers complete microtasks where they (1) identify a behavior, (2) write a test for the behavior, and (3) implement the behavior~\cite{aghayi2019crowdsourced}. } ~\label{fig:workflow} \end{figure*} \section{Crowdsourced Behavior-Driven Development} To make microtask programming more efficient and reduce the potential for conflicts between contributors, I developed a new behavior-driven approach to microtasking programming. In our approach, each microtask asks developers to identify a behavior behavior from a high-level description of a function, implement a unit test for it, implement the behavior, and debug it. It enables developers to work on functions in isolation through high-level function descriptions and stubs. In addition, I developed the first approach for building microservices through microtasks. Building microservices through microtasks is a good match because our approach requires a client to first specify the functionality the crowd will create through an API. This API can then take the form of a microservice description. A traditional project may ask a crowd to implement a new microservice by simply describing the desired behavior in a API and recruiting a crowd. We implemented our approach in a web-based IDE, \textit{Crowd Microservices}\footnote{https://youtu.be/mIn2EOqsDYw} (Fig.~\ref{fig:workflow}). It includes an editor for clients to describe the system requirements through endpoint descriptions as well as a web-based programming environment where crowd workers can identify, test, implement, and debug behaviors (Figure \ref{fig:workflow}). The system automatically creates, manages, assigns microtasks. After the crowd finishes, the system automatically deploys the microservice to a hosting site.\par \textit{Study 1: Feasibility.} To evaluate the feasibility of this approach, we conducted a small study where 9 developers together worked to build a microservice. The results were promising. Participants submitted their first microtask less than half an hour after beginning, successfully submitted 350 microtasks, implemented 13 functions and 36 tests, completed microtasks in a median time under 5 minutes, correctly implemented 27 of 34 behaviors, and together implemented most of a functioning ToDo microservice~\cite{aghayi2019crowdsourced}. \textit{Study 2: Comparing microtask programming to traditional development.} To directly compare traditional programming to microtasked programming, we conducted a controlled experiment. Twenty-eight developers worked either on traditional programming tasks, described through issues, or programming microtasks. We found that, compared to traditional software development, microtasking had important advantages in reducing onboarding time and time-to-market and, surprisingly, in increasing the quality of code and individual developer productivity.\par \textit{Study 3: Using microtask programming in industry.} Our early studies were conducted entirely in artificial contexts, using artificial tasks and developers recruited specifically to work in the study. To examine the potential for using microtask programming in industry, we partnered with NTT, a large telecommunication company, to conduct a study of microtask programming within a real software project. We found that a microtask programming approach was successful in implementing and testing a project with 8000 lines of code in 14 functions. We also found that developers took time to understand the new concepts in microtask programming approach and be productive. We also found the value of having dedicated developers responsible for managing microtask projects. \par \section{Future Work} My studies have offered initial evidence that microtask programming can be effective in small crowds with a few developers. But much of the promise of microtasking comes from large crowds, and there exists a direct relationship between the number of independent tasks and the parallelism in microtask programming which may reduce time to market. However, there are a number of significant challenges in scaling microtask programming to larger crowds. \par To date, the largest crowd we have used is only 9 developers. To begin to examine microtask programming at scale, we are planning to conduct a virtual hackathon with around 100 developers. Based on our findings, we will develop new techniques to scale microtask programming and more fully encompass software development work. One direction we expect to pursue is with team organization. In our current approach, clients specify a microservice and crowd developers work in a flat organization to complete microtasks. This organization may not work well for all projects. For instance, some projects have security considerations, like private APIs that they do not want to expose to the public. Or projects may benefit from more experienced team leads who tackle more complex tasks or help less experienced developers when they get stuck. We will explore ways to make better use of more experienced developers in crowds through defining separate roles for crowd workers. TopCoder is one successful example of this hybrid collaboration, and we will explore ways to adapt these ideas within microtask programming~\cite{Stol2014:TwoCompany}.\par \section*{Acknowledgment} This work was supported in part by the National Science Foundation under grants CCF-1414197 and CCF-1845508. \bibliographystyle{IEEEtran}
{'timestamp': '2020-06-01T02:03:44', 'yymm': '2005', 'arxiv_id': '2005.14306', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14306'}
arxiv
\section{Introduction} Visual content recognition and understanding have greatly made progress based on the advances of deep learning methods that construct the discriminative model by training large-scale labeled data. In fact, two reasons limit the current deep learning methods for efficiently learning new categories. One is that human annotation cost is high for large-scale data (for example, thousands of the diversity samples in the same category and hundreds of the various categories in one cognition domain), the other is that the rare samples of some categories are not enough for the discriminative model training. Therefore, it is still a challenge question that the discriminative model is learned from the rare samples of the categories. To solve this question, few-shot learning \cite{vinyals2016matching} \cite{snell2017prototypical} \cite{finn2017model} \cite{RaviL17} \cite{sung2018learning} \cite{qi2018low} \cite{SatorrasE18} \cite{kim2019edge} \cite{lee2019meta} \cite{sun2019meta} \cite{peng2019few} \cite{chen2019a}proposed from the inspiration of human visual system has been an attracted research to generalize the learning model to new classes with the rare samples of each novel category by feature learning \cite{ghiasi2018dropblock} \cite{wu2018unsupervised} \cite{donahue2019large} \cite{8955914} \cite{8948295} \cite{saikia2020optimized}or meta-learning \cite{chen2019a} \cite{ravichandran2019few} \cite{dhillon2019baseline}\cite{fei2020meta} \cite{zhang2020rethinking} \cite{luo2019learning}. Feature learning emphasises on feature generation and extraction model construction based on invariance transfer information, while meta-learning focuses on the relevance model between the samples for mining the common relationship of data samples by the episode training. Meta-learning can transfer the available knowledge between the collection of the separated tasks, and propagate the latent structure information to enhance the model generalization and to avoid the model overfitting. Therefore, meta-learning is one of most promising directions for few-shot learning. However, meta-learning is constructed based on the large-scale separated tasks, and each task have the respective metric criterion that causes the gap of the transfer information between the samples of the separated tasks(the details in figure \ref{fig-2}). Although existing methods can relieve this gap to a certain extend by the same sample filling into the different tasks, it is still difficult to build the approximated metric criterion of the different tasks for efficiently information transfer and propagation. Therefore, we present HOSP-GNN that attempts to construct the approximated metric criterion by mining high-order structure and updates these metric values between samples by constraining data manifold structure for few-shot learning. Figure \ref{fig-1} illustrates the difference between HOSP-GNN and the most meta-learning for few-shot learning conceptually. \begin{figure*}[ht] \begin{center} \includegraphics[width=1\linewidth]{fig1.png} \end{center} \vspace{-0.2in} \caption{The illustration of the difference between HOSP-GNN and the most meta-learning for few-shot learning.$S$ stands for support set; $Q$ is query set;the different color circles describe the labeled samples of the different classes in $S$; the gray color circles represent unlabeled samples in $Q$;the black solid lines between circles show the structure relationship of the labeled samples;the black dot lines between circles are the predicted structure relationship between labeled and unlabeled samples; the blue dot lines between circles across tasks indicate the latent high-order structure of samples.} \label{fig-1} \end{figure*} Our contributions mainly have two points as follow. \begin{itemize} \item One is to find the high-order structure for bridging the gap between the metric criterion of the separated tasks. The importance of this point is to balance the consistence of the same samples in the different tasks, and to enhance the transferability of the similar structure in the learning model. \item Another is to smooth the structure evolution for improving the propagation stability of the model transfer by manifold structure constraints. This point try to minimize the difference of the transformation projection between the similar samples, and to maximize the divergence of the transformation projection between the dissimilar samples for efficiently preserving the graph structure learning of data samples. \end{itemize} \section{Related Works} In recent few-shot learning, there mainly are two kinds of methods according to the different learning focuses. One is feature learning based on the data representation of model extraction, and another is meta-learning based on the metric relationship of model description. \subsection{Feature Learning} Feature learning \cite{cubuk2019autoaugment} \cite{cubuk2019randaugment} \cite{lim2019fast} \cite{ghiasi2018dropblock} \cite{wu2018unsupervised} \cite{donahue2019large}for few-shot learning expects to inherit and generalize the well characteristics of the pre-train model based on large-scale samples training for recognizing new classes with few samples. Because few samples often can not satisfy the necessary of the whole model training, the recent representative methods usually optimize the part parameters or structure of the pre-trained model by few samples for feature learning. For example,Bayesian optimization to Hyperband (BOHB) optimizes hyper-parameters by searching the smaller parameter space to maximize the validation performance for generic feature learning \cite{saikia2020optimized}; Geometric constraints fine-tune the parameters of one network layer with a few training samples for extracting the discriminative features for the new categories \cite{8948295}; Bidirectional projection learning (BPL) \cite{8955914} utilizes semantic embedding to synthesize the unseen classes features for obtaining enough samples features by competitive learning. These methods attempt to find the features invariance by partly fine-tuning the pre-trained model with the different constraints for recognizing the new classes with the few instances. However, these methods can not explicitly formulate the metric rules for learning the discriminative model between new categories, moreover, these methods need retrain the model to adapt the distribution of new categories. It can lead to the degraded classification performance for few-shot learning and the more complicated optimization strategy in validation and test phases. \subsection{Meta-Learning} \label{ML} Meta-learning \cite{vinyals2016matching} \cite{sung2018learning} \cite{chen2019a}\cite{gidaris2018dynamic} \cite{oreshkin2018tadam} \cite{ravichandran2019few} \cite{dhillon2019baseline}for few-shot learning tries to construct the relevances between samples in the base classes for generalizing the model to the new classes. These methods can learn the common structure relationship between samples by training on the collection of the separated tasks.In terms of the coupling between the model and the data, meta-learning can mainly be divided into two groups. One group is the model optimization to quickly fit the distribution of new categories. Typical methods attempt to update the model parameters or optimizer for this purpose. For instance, meta-learner long short-term memory (LSTM) \cite{RaviL17} can update the model parameters to initialize the classifier network for the quick training convergence in the few samples of each classes; Model-agnostic meta-learning (MAML) \cite{finn2017model} can train the small gradient updating based on few learning data from a new task to obtain the well generalization performance; Latent embedding optimization(LEO)\cite{rusu2019metalearning} can learn the latent generative representation of model parameters based on data dependence to decouple the gradient adaptation from the high-dimension parameters space. Another group is metric learning to describe the structure relationship of the samples between support and query data for directly simulating the similarity metric of the new categories. The recent methods trend to enhance the metric structure by constraint information for the better model generalization in the new categories. For example,edge-labeling graph neural network (EGNN)\cite{kim2019edge} can update graph structure relationship to directly exploit the intra-cluster similarity and the inter-cluster dissimilarity by iterative computation; Meta-learning across meta-tasks (MLMT) \cite{fei2020meta} can explore their relationships between the random tasks by meta-domain adaptation or meta-knowledge distillation for boosting the performance of existing few-shot learning methods; Absolute-relative Learning (ArL)\cite{zhang2020rethinking} can both consider the class concepts and the similarity learning to complement their structure relationship for improving the recognition performance of the new categories; Continual meta-learning approach with Bayesian graph neural networks(CML-BGNN) \cite{luo2019learning} can implement the continual learning of a sequence of tasks to preserve the intra-task and inter-task correlations by message-passing and history transition. In recent work, meta-learning based on metric learning shows the promising performance for recognizing the new categories with the few samples. These methods initially focus on the structure relation exploitation between support set and query set by modeling metric distances, and subsequent works further mine the relevance by mimicking the dependence between the separated tasks for enhancing the discrimination of the new categories. However, these methods depend on the projection loss between the seen and unseen classes \cite{fei2020meta} or Bayesian inference based on low-order structure (the metric of the pairwise data) \cite{luo2019learning} for considering the structure relationship between the intra or inter tasks. It is difficult to describe the latent high-order structure from the global observation. Therefore, the proposed HOSP-GNN expects to capture the high-order structure relationship based on samples metric for naturally correlating the relevance between the intra or inter tasks for improving the performance of few-shot learning. \section{High-order structure preserving graph neural network} Few-shot classification attempts to learn a classifier model for identifying the new classes with the rare samples. $C_{e}$ or $C_{n}$ respectively stands for a existing classes set with the large samples or a new classes set with the rare samples, and $C_{e}\bigcap C_{n}=\emptyset$,but they belong to the same cognise domain. The existing classes data set $D_{e}=\{(x_{i},y_{i})|y_{i} \in C_{e}, i=1,...,|D_{e} |\}$, where $x_{i}$ indicates the $i$-th image with the class label $y_{i}$, $|D_{e}|$ is the number of the elements in $D_{e}$. Similarly, the new classes data set $D_{n}=\{(x_{i},y_{i})|y_{i} \in C_{n}, i=1,...,|D_{n} |\}$, where $x_{i}$ indicates the $i$-th image with the class label $y_{i}$, $|D_{n}|$ is the number of the elements in $D_{n}$. If each new class includes $K$ labeled samples, the new classes data set is $K$-shot sample set. In other word, $|D_{n}|=K|C_{n}|$, where $|C_{n}|$ is the number of the elements in $C_{n}$. Few-shot learning is to learn the discriminative model from $D_{n}$ to predict the label of the image sample in the test set $D_{t}$ that comes from $C_{n}$ and $D_{n} \bigcap D_{t}=\emptyset$. \subsection{Meta-learning for few-shot learning based on graph neural network} In meta-learning, the classifier model can be constructed based on the collection of the separated tasks $\mathcal{T}=\{S,Q\}$ that contains a support set $S$ from the labeled samples in $D_{n}$ and a query set $Q$ from unlabeled samples in $D_{t}$. To build the learning model for few-shot learning, $S$ includes $K$ labeled samples and $N$ classes, so this situation is called $N$-way-$K$-shot few-shot classification that is to distinguish the unlabeled samples from $N$ classes in $Q$. In practise, few-shot classification often faces the insufficient model learning based on the new classes data set $D_{n}$ with the rare labeled samples and $D_{t}$ with unlabeled samples. In this situation, the model difficultly identifies the new categories. Therefore, many methods usually draw support from the transfer information of $D_{e}$ with a large labels samples to enhance the model learning for recognizing the new classes. Episodic training \cite{sung2018learning} \cite{kim2019edge} is an efficient meta-learning for few-shot classification. This method can mimic $N$-way-$K$-shot few-shot classification in $D_{n}$ and $D_{t}$ by randomly sampling the differently separated tasks in $D_{e}$ as the various episodics of the model training. In each episode, $\mathcal{T}_{ep}=(S_{ep},Q_{ep})$ indicates the separated tasks with $N$-way-$K$-shot $T$ query samples, where the support set $S_{ep}=\{(x_{i},y_{i})|y_{i}\in C_{ep}, i=1,...,N\times K\}$, the query set $Q_{ep}=\{(x_{i},y_{i})|y_{i}\in C_{ep}, i=1,...,N\times T\}$, $S_{ep}\cap Q_{ep}=\emptyset$, and the class number $|C_{ep}|=N$. In the training phase, the class set $C_{ep}\in C_{e}$, while in test phase, the class set $C_{ep}\in C_{n}$. Many episodic tasks can be randomly sampled from $D_{e}$ to simulate $N$-way-$K$-shot learning for training the few-shot model, whereas the learned model can test the random tasks from $D_{n}$ for few-shot classification by $N$-way-$K$-shot fashion. If we construct a graph $G_{ep}=(\mathcal{V}_{ep},\mathcal{E}_{ep},\mathcal{T}_{ep})$ (here, $\mathcal{V}_{ep}$ is the vertex set of the image features in $\mathcal{T}_{ep}$, and $\mathcal{E}_{ep}$ is the edge set between the image features in $\mathcal{T}_{ep}$.) for describing the sample structure relationship in each episodic task, meta-learning for few-shot learning based on $L$ layers graph neural network can be reformulated by the cross-entropy loss $L_{ep}$ as following. \begin{align} \label{Eq1} \begin{aligned} L_{ep}&=-\sum_{l=1}^{L}\sum_{(x_{i},y_{i})\in Q_{ep}}y_{i}\log (h_{W}^{l}(f(x_{i},W_{f});S_{ep},G_{ep}))\\ &=-\sum_{l=1}^{L}\sum_{(x_{i},y_{i})\in Q_{ep}}y_{i}\log (\hat{y_{i}^{l}}) \end{aligned} \end{align} \begin{align} \label{Eq1-1} \begin{aligned} \hat{y_{i}^{l}}=softmax(\sum_{j\neq i~~and~~c\in C_{ep}}e_{ij}^{l}\delta(y_{i}=c)) \end{aligned} \end{align} here, $\hat{y_{i}^{l}}$ is the estimation value of $y_{i}$ in $l$th layer;$e_{ij}^{l}$ is edge feature of the $l$th layer in graph $G_{ep}$; $\delta(y_{i}=c)$ is equal one when $y_{i}=c$ and zero otherwise;$f(\bullet)$ with the parameter set $W_{f}$ denotes the feature extracting function or network shown in Figure \ref{fig-4}(a); $h_{W}^{l}(f(x_{i});S_{ep},G_{ep})$ indicates few-shot learning model in the $l$th layer by training on $S_{ep}$ and $G_{ep}$, and $W$ is the parameter set of this model. This few-shot learning model can be exploited by the meta-training minimizing the loss function \ref{Eq1}, and then recognize the new categories with the rare samples. \subsection{High-order structure description} In few-shot learning based on graph neural network, the evolution and generation of the graph plays a very important role for identifying the different classes. In each episodic task of meta-learning, existing methods usually measure the structure relationship of the samples by pairwise way, and an independence metric space with the unique metric criteria is formed by the similarity matrix in graph. In many episodic tasks training, the various metric criteria lead to the divergence between the different samples structure relationship in Figure \ref{fig-2}. It is the main reason that the unsatisfactory classification of the new categories. \begin{figure*}[ht] \begin{center} \includegraphics[width=1\linewidth]{fig2.png} \end{center} \vspace{-0.2in} \caption{The difference between the metric criteria of the episodic tasks. In each episodic training and testing, $S_{ep}$ stands for support set; $Q_{ep}$ is query set;the different color circles describe the labeled sample of the different classes in $S_{ep}$; the gray color circles represent unlabeled samples in $Q_{ep}$;the black solid lines between circles show the structure relationship of the labeled samples;the black dot lines between circles are the predicted structure relationship between labeled and unlabeled samples.} \label{fig-2} \end{figure*} To reduce the difference between the metric criteria of the episodic tasks, we attempt to explore the high-order structure of the samples by building the latent connection. The traditional pairwise metric loses the uniform bench marking because of the normalization of the sample separation in independence tasks. However, the absolutely uniform bench marking is difficult to build the high-order structure relation between the samples of the different tasks. Therefore, \textbf{we define the relative metric graph of multi-samples in a task as high-order structure relation}, and the same samples by random falling into the independence task make this relative metric relationship widely propagate to the other samples for approximating to the uniform bench marking under the consideration with the interaction relationship between the episodic tasks. More concretely, the relative metric graph $\hat{G}_{ep}=(\hat{\mathcal{V}}_{ep},\hat{\mathcal{E}}_{ep},\mathcal{T}_{ep})$, where $\mathcal{T}_{ep}=\{(x_{i},y_{i})|(x_{i},y_{i})\in S_{ep}~~or~~(x_{i},y_{i})\in Q_{ep}, y_{i}\in C_{ep},S_{ep}\bigcap Q_{ep}=\emptyset, i=1,...,N\times (K+T)\}$, the vertex set $\hat{\mathcal{V}}_{ep}=\{v_{i}|i=1,...,N\times (K+T)\}$, the edge set $\hat{\mathcal{E}}_{ep}=\{e_{ij}|i=1,...,N\times (K+T)~~and~~j=1,...,N\times (K+T)\}$. To describe the relative relationship between features, we can build $L$ layers graph neural network for learning edge feature $e_{ij}^{l}$ (graph structure relationship) and feature representation $v_{i}^{l}$ in each layer, where $l=0,...,L$. In the initial layer, each vertex feature $v_{i}^{0}$ can be computed by feature difference as following. \begin{align} \label{Eq2-1} \begin{aligned} &u_{i}^{0}=f(x_{i}),~~~~~~i=1,...,N\times (K+T), \end{aligned} \end{align} \begin{align} \label{Eq2} \begin{aligned} v_{i}^{0}=\left\{ \begin{aligned} &u_{i}^{0}-u_{i+1}^{0},~~~~~~i=1,...,N\times (K+T)-1, \\ &u_{i}^{0}-u_{1}^{0},~~~~~~~~~~i=N\times (K+T), \end{aligned} \right. \end{aligned} \end{align} here, $f(\bullet)$ is the feature extracting network shown in Figure \ref{fig-4}(a). The vertex can represented by two ways. One is that the initial vertex feature $u_{i}^{0}$ is described by the original feature. Another is that $v_{i}^{0}$ is a relative metric based on $u_{i}^{0}$ in $0$th layer. We expect to construct the higher order structure $e_{ij1}^{l}$ (the first dimension value of edge feature between vertex $i$ and $j$ in $l$ layer) based on this relative metric for representing edge feature under the condition with the pairwise similarity structure $e_{ij2}^{l}$ and dissimilarity structure $e_{ij3}^{l}$(these initial value of $0$ layer is defined by the labeled information of $S_{ep}$ in Equation \ref{Eq3}). Therefore, the initial edge feature can be represented by the different metric method as following. \begin{align} \label{Eq3} \begin{aligned} e_{ij}^{0}=\left\{ \begin{aligned} & [e_{ij1}^{0}~||~ e_{ij2}^{0}=1~||~ e_{ij3}^{0}=0],~~~~y_{i}=y_{j}~~and~~(x_{i},y_{i})\in S_{ep}, \\ & [e_{ij1}^{0}~||~ e_{ij2}^{0}=0~||~ e_{ij3}^{0}=1],~~~~y_{i}\neq y_{j}~~and~~(x_{i},y_{i})\in S_{ep}, \\ & [e_{ij1}^{0}~||~ e_{ij2}^{0}=0.5~||~ e_{ij3}^{0}=0.5],~~~~ otherwise, \end{aligned} \right. \end{aligned} \end{align} here, $||$ is concatenation symbol, $e_{ij1}^{0}$ can be calculated by the metric distance of the difference in Equation \ref{Eq4}, and $e_{ij1}^{l}$ can be updated by Equation \ref{Eq7}. It shows the further relevance between the relative metric, and indicates the high-order structure relation of the original features. \begin{align} \label{Eq4} \begin{aligned} e_{ij1}^{0}=1-\parallel v_{i}^{0}-v_{j}^{0} \parallel_{2}/\sum_{k}\parallel v_{i}^{0}-v_{k}^{0} \parallel_{2},~~~~(x_{i},y_{i})\in S_{ep}\bigcup Q_{ep}, \end{aligned} \end{align} Figure \ref{fig-3} shows the relationship between pairwise metric and high-order metric in $l$th layer, and the high-order metric involves any triple vertex features $u_{i}^{l}$,$u_{j}^{l}$ and $u_{k}^{l}$ in $\hat{G}_{ep}$ in each task. In these features, $u_{j}^{l}$ is a benchmark feature that is randomly sampled by the separated tasks. The common benchmark feature can reduce the metric difference between samples of the separated tasks. \begin{figure*}[ht] \begin{center} \includegraphics[width=1\linewidth]{fig3.png} \end{center} \vspace{-0.2in} \caption{The relationship between pairwise metric $d_{pairwise\_metric}^{l}$(left figure) and high-order metric $d_{high-order\_metric}^{l}$(right figure) in $l$th layer. $f_{p}^{l}(\bullet)$ and $W_{p}^{l}$ respectively are pairwise metric network projection and parameter set in $l$th layer, while $f_{h}^{l}(\bullet)$ and $W_{h}^{l}$ respectively are high-order metric network projection and parameter set in $l$th layer.The black vector indicates the original vertex, the blue vector is the low-order metric vector ( the relative metric based on the original vertex), and the red vector stands for the high-order metric vector.} \label{fig-3} \end{figure*} \subsection{High-order structure preserving} HOSP-GNN can construct $L$ layers graph neural network for evolving the graph structure by updating the vertex and edge features. Moreover, we expect to preserve the high-order structure layer by layer for learning the discriminative structure between samples in the separated tasks. $l=1,...,L$ is defined as the layer number. In detail, $u_{i}^{l}$ can be updated by $u_{i}^{l-1}$,$v_{i}^{l-1}$ and $e_{ij}^{l-1}$ in Equation \ref{Eq5}, while $e_{ij}^{l}$ can be updated by$u_{i}^{l-1}$, $v_{i}^{l-1}$ and $e_{ij}^{l-1}$ in Equation \ref{Eq7},\ref{Eq8} and \ref{Eq9}. \begin{align} \label{Eq5} \begin{aligned} u_{i}^{l}=f_{v}^{l}([\sum_{j}\tilde{e}_{ij1}^{l-1}v_{j}^{l-1}~||~\sum_{j}\tilde{e}_{ij2}^{l-1}u_{j}^{l-1}~||~\sum_{j}\tilde{e}_{ij3}^{l-1}u_{j}^{l-1}], W_{v}^{l}), \end{aligned} \end{align} \begin{align} \label{Eq5-1} \begin{aligned} v_{i}^{l}=\left\{ \begin{aligned} &u_{i}^{l}-u_{i+1}^{l},~~~~~~i=1,...,N\times (K+T)-1, \\ &u_{i}^{l}-u_{1}^{l},~~~~~~~~~~i=N\times (K+T), \end{aligned} \right. \end{aligned} \end{align} here,$||$ is concatenation symbol, $\tilde{e}_{ijk}^{l-1}=e_{ijk}^{l-1}/\sum_{k}e_{ijk}^{l-1}$ ($k=1,2,3$), and $f_{v}^{l}(\bullet)$ is the vertex feature updating network shown in Figure \ref{fig-4}(b),and $W_{v}^{l}$ is the network parameters in $l$th layer. This updating process shows that the current vertex feature is the aggregative transformation of the previous layer vertex and edge feature in the different metrics, and can propagate the representation information under the consideration with edge feature (high-order structure information) layer by layer evolution. In \ref{Eq5}, high-order structure influences the vertex representation by transforming aggregation computation, but can not efficiently transfer layer by layer. Therefore, we expect to preserve high-order structure layer by layer by updating edge features. According to manifold learning \cite{he2004locality} and structure fusion\cite{Lin2014146}, structure information (the similarity relationship of samples) can be held from the original space to the projection space by minimizing the metric difference of these spaces. Similarly, high-order evolution based on graph neural network may obey the same rule for computing edge feature of each layer with the vertex feature updating. Therefore, we can construct the manifold loss by layer-by-layer computation for constraining the model optimization. \begin{align} \label{Eq6} \begin{aligned} L_{ml}=&\sum_{i,j,l}f_{h}^{l}(\|v_{i}^{l}-v_{j}^{l}\|_{2},W_{h}^{l})e_{ij1}^{l-1}+\\ &\sum_{i,j,l}f_{p}^{l}(\|u_{i}^{l}-u_{j}^{l}\|_{2},W_{p}^{l})e_{ij2}^{l-1}+\\ &\sum_{i,j,l}(1-f_{p}^{l}(\|u_{i}^{l}-u_{j}^{l}\|_{2},W_{h}^{l}))e_{ij3}^{l-1}, \end{aligned} \end{align} here,$L_{ml}$ is the loss of the manifold structure in the different layer and metric method (The first term is the manifold constrain for high-order structure, while the second and third terms are respectively the manifold constrain for similarity and dissimilarity); $f_{h}^{l}(\bullet)$ is the high-order metric network in Figure \ref{fig-4}(c) between vertex features, and $W_{h}^{l}$ is the parameter set of this network in $l$th layer; $f_{p}^{l}(\bullet)$ is the pairwise metric network in Figure \ref{fig-4}(c) between vertex features, and $W_{p}^{l}$ is it's parameter set in $l$th layer. \ref{Eq6} shows that the different manifold structures between layers can be preserved for minimizing $L_{ml}$. The edge updating based on high-order structure preserving is as following. \begin{align} \label{Eq7} \begin{aligned} \bar{e}_{ij1}^{l}=\frac{f_{h}^{l}(\|v_{i}^{l}-v_{j}^{l}\|_{2},W_{h}^{l})e_{ij1}^{l-1}}{\sum_{k}f_{h}^{l}(\|v_{i}^{l}-v_{k}^{l}\|_{2},W_{h}^{l})e_{ik1}^{l-1}/\sum_{k}e_{ik1}^{l-1}}, \end{aligned} \end{align} \begin{align} \label{Eq8} \begin{aligned} \bar{e}_{ij2}^{l}=\frac{f_{p}^{l}(\|u_{i}^{l}-u_{j}^{l}\|_{2},W_{p}^{l})e_{ij2}^{l-1}}{\sum_{k}f_{p}^{l}(\|u_{i}^{l}-u_{k}^{l}\|_{2},W_{p}^{l})e_{ik2}^{l-1}/\sum_{k}e_{ik2}^{l-1}}, \end{aligned} \end{align} \begin{align} \label{Eq9} \begin{aligned} \bar{e}_{ij3}^{l}=\frac{(1-f_{p}^{l}(\|u_{i}^{l}-u_{j}^{l}\|_{2},W_{p}^{l}))e_{ij3}^{l-1}}{\sum_{k}(1-f_{p}^{l}(\|u_{i}^{l}-u_{k}^{l}\|_{2},W_{p}^{l}))e_{ik3}^{l-1}/\sum_{k}e_{ik3}^{l-1}}, \end{aligned} \end{align} \begin{align} \label{Eq10} \begin{aligned} e_{ij}^{l}=\bar{e}_{ij}^{l}/\|\bar{e}_{ij}^{l}\|_{1}. \end{aligned} \end{align} Therefore, The total loss $L_{total}$ of the whole network includes $L_{ep}$ and $L_{ml}$. \begin{align} \label{Eq11} \begin{aligned} L_{total}=L_{ep}+\lambda L_{ml}, \end{aligned} \end{align} here, $\lambda$ is the tradeoff parameter for balancing the influence of the different loss. Figure \ref{fig-4} shows the network architecture of the proposed HOSP-GNN. \begin{figure*}[hbp] \begin{center} \includegraphics[width=1\linewidth]{fig4.png} \end{center} \vspace{-0.2in} \caption{The network architecture of the proposed HOSP-GNN.(a) is the total network structure, (b) and (c) respectively are vertex and edge updating network in (a). MLP is a multilayer perceptron; DU indicates the difference unit for the relative metric; Conv stands for a convolutional block that includes $96$ channels of $1\times 1$ convolution kernel, batch normalization unit, and LeakReLU unit;$S_{ep}$ stands for support set; $Q_{ep}$ is query set;the different color circles describe the labeled samples of the different classes in $S_{ep}$; the gray color circles represent unlabeled samples in $Q_{ep}$;the black solid lines between circles show the structure relationship of the labeled samples;the black dot lines between circles are the predicted structure relationship between labeled and unlabeled samples;$L_{ep}$ is the loss metric between the real labels and the predicted labels; $L_{ml}$ is the loss metric between high structures layer by layer;$v_{i}^{l}$ is the $i$th vertex feature in the $l$th layer of graph;$e_{ij}^{l}$ is the edge feature between the vertex $i$ and $j$ in the $l$th layer of graph;$f(\bullet)$ denotes the feature extracting network;$f_{v}^{l}(\bullet)$ indicates the vertex feature updating network in the $l$th layer; $f_{h}^{l}(\bullet)$ denotes the high-order metric network between vertex features in the $l$th layer; $f_{p}^{l}(\bullet)$ stands for the pairwise metric network between vertex features in the $l$th layer.} \label{fig-4} \end{figure*} To indicate the inference details of HOSP-GNN, algorithm \ref{algHOSP-GNN} shows the pseudo code of the proposed HOSP-GNN for predicting the labels of the rare samples. This algorithm process contains four steps. The first step (line 1 and line 2) initializes the vertex feature and the edge feature. The second step (line 4 and line 5) updates the vertex features layer by layer. The third step (from line 6 to line 8) updates the edge features layer by layer. The forth step (line 9) predicts the labels of the query samples. \begin{algorithm}[ht] \caption{The inference of the HOSP-GNN for few-shot learning} \begin{algorithmic}[1] \label{algHOSP-GNN} \renewcommand{\algorithmicrequire}{\textbf{Input:}} \renewcommand{\algorithmicensure}{\textbf{Output:}} \renewcommand{\algorithmicreturn}{\textbf{Iteration:}} \REQUIRE \textit{Graph}, $\hat{G}_{ep}=(\hat{\mathcal{V}}_{ep},\hat{\mathcal{E}}_{ep},\mathcal{T}_{ep})$, where $\mathcal{T}_{ep}=\{(x_{i},y_{i})|(x_{i},y_{i})\in S_{ep}~~or~~x_{i}\in Q_{ep}, y_{i}\in C_{ep},S_{ep}\bigcap Q_{ep}=\emptyset, i=1,...,N\times (K+T)\}$,$\hat{\mathcal{V}}_{ep}=\{v_{i}|i=1,...,N\times (K+T)\}$, $\hat{\mathcal{E}}_{ep}=\{e_{ij}|i=1,...,N\times (K+T)~~and~~j=1,...,N\times (K+T)\}$;\\ \textit{Model parameter}, $W=\{W_{f},W_{v}^{l},W_{h}^{l}|l=1,...,L\}$ \ENSURE The query samples of the predicted labels $\{\hat{y}_{i}^{l}|i=1,...,N\times T~~~~and~~~~l=1,...,L\}$ \STATE Computing the initial vertex feature $v_{i}^{0}$ by feature difference in Equation \ref{Eq2} \STATE Computing the initial edge feature $e_{ij}^{0}$ as high-order structure in Equation \ref{Eq3} \FOR {$1\leq l\leq L$} \FOR {$1\leq i\leq N\times (K+T)$} \STATE Updating vertex feature $v_{i}^{l}$ by Equation \ref{Eq5} \FOR {$1\leq j\leq N\times (K+T)$} \STATE Updating edge feature $e_{ij}^{l}$ by Equation \ref{Eq7},\ref{Eq8},\ref{Eq9} and \ref{Eq10} \ENDFOR \STATE Predicting the query sample labels $\hat{y}_{i}^{l}$ by Equation\ref{Eq1-1} \ENDFOR \ENDFOR \end{algorithmic} \end{algorithm} \section{Experiment} To evaluating the proposed HOSP-GNN, we carry out four experiments. The first experiment involves the baseline methods comparison. The second experiment conducts the state-of-the-art methods comparison. The third experiment implements semi-supervised fashion for few-shot learning. The forth experiment assesses the layer effect for graph model, and the loss influence for the manifold constraint. \subsection{Datasets} In experiments, we use three benchmark datasets that are miniImageNet\cite{vinyals2016matching}, tieredImageNet \cite{Mengye2018}, and FC100\cite{NIPS20187352}. In miniImageNet dataset from ILSVRC-12 \cite{ILSVRC15}, RGB images include $100$ different classes, and each class has $600$ samples. We adopt the splits configuration \cite{kim2019edge} that respectively is 64,16,and 20 classes for training, validation and testing. In tieredImageNet dataset from ILSVRC-12 \cite{ILSVRC15}, there are more than $700k$ images from $608$ classes. Moreover, $608$ classes is collected for $34$ higher-level semantic classes, each of which has $10$ to $20$ classes. We also use the splits configuration \cite{kim2019edge} that respectively is $351$,$97$, and $160$ for training, validation and testing. Each class has about $1281$ images. In FC100 dataset from CIFAR-100\cite{Krizhevsky}, there are $100$ classes images grouped into $20$ higher-level classes. Classes respectively are divided into $60$,$20$, and $20$ for training, validation and testing. Each classes have $600$ images of size $32\times 32$. Table \ref{tab1} shows the statistics information of these datasets. \begin{table*}[!ht] \small \renewcommand{\arraystretch}{1.0} \caption{Datasets statistics information in experiments. $\sharp$ denotes the number. } \label{tab1} \begin{center} \newcommand{\tabincell}[2]{\begin{tabular}{@{}#1@{}}#2\end{tabular}} \begin{tabular}{lp{1.0cm}p{1.5cm}p{1.5cm}p{1.5cm}p{1.5cm}p{0.5cm}} \hline \bfseries Datasets & \bfseries \tabincell{l}{$\sharp$ Classes } & \bfseries \tabincell{l}{$\sharp$ training\\ classes} & \bfseries \tabincell{l}{$\sharp$ validation \\classes} & \bfseries \tabincell{l}{$\sharp$ testing \\classes} &\bfseries \tabincell{l}{$\sharp$ images}\\ \hline \hline miniImageNet & $100$ &$64$& $16$ & $20$ & $60000$\\ \hline tieredImageNet & $608$ &$351$& $97$ & $160$ & $778848$\\ \hline FC100 & $100$ &$60$& $20$ & $20$ & $60000$\\ \hline \end{tabular} \end{center} \end{table*} \subsection{Experimental Configuration} Figure \ref{fig-4} describes the network architecture of the proposed HOSP-GNN in details. The feature extracting network is the same architecture in the recent works\cite{vinyals2016matching} \cite{snell2017prototypical} \cite{finn2017model} \cite{kim2019edge}, and specifically includes four convolutional blocks with $3\times 3$ kernel, one linear unit, one bach normalization and one leakReLU unit for few-shot models. Other parts of network is detailed in figure \ref{fig-4}. To conveniently compare with other methods(baseline methods and state-of-the-art methods), we set the layer number $L$ to $3$ in the proposed HOSP-GNN. To train the proposed HOSP-GNN model, we use Adam optimizer with the learning rate $5\times 10^{-4}$ and weight decay $10^{-6}$. The mini-batch size of meta-learning task is set to $40$ or $20$ for 5-way-1-shot or 5-way-5-shot experiments. The loss coefficient $\lambda$ is set to $10^{-5}$. Experimental results in this paper can be obtained by 100K iterations training for miniImageNet and FC100, 200K iterations training for tieredImageNet. We implement 5-way-1-shot or 5-way-5-shot experiments for evaluating the proposed method. Specifically, we averagely sample $15$ queries from each classes, and randomly generate $600$ episodes from the test set for calculating the averaged performance of the queries classes. \subsection{Comparison with baseline approaches} The main framework of the proposed HOSP-GNN is constructed based on edge-labeling graph neural network (EGNN)\cite{kim2019edge}. Their differences are the graph construction and the manifold constraint for model training in episodic tasks. EGNN method mainly considers the similarity and dissimilarity relationship between the pair-wise samples, but does not involve the manifold structure constraint of each layer for learning few-shot model.In contrast, HOSP-GNN tries to capture the high-order structure relationship between multi-samples ,fuses the similarity and dissimilarity relationship between the pair-wise samples, and constrains the model training by layer by layer manifold structure loss. Therefore, the base-line methods include EGNN, HOSP-GNN-H-S(the proposed HOSP-GNN only considers the high-order structure relationship and the similarity relationship),HOSP-GNN-H-D(the proposed HOSP-GNN only considers the high-order structure relationship and the dissimilarity relationship),HOSP-GNN-H (the proposed HOSP-GNN only considers the high-order structure relationship),HOSP-GNN-S (the proposed HOSP-GNN only considers the similarity relationship),and HOSP-GNN-D (the proposed HOSP-GNN only considers the dissimilarity relationship), in which H denotes the high-order structure relationship, S strands for the similarity relationship, and D represents the dissimilarity relationship. \begin{table}[!ht] \small \renewcommand{\arraystretch}{1.0} \caption{Comparison of the methods related the high-order structure (HOSP-GNN,HOSP-GNN-H-S,HOSP-GNN-H-D,and HOSP-GNN-H)with baseline methods (EGNN,HOSP-GNN-S,and HOSP-GNN-D) for 5-way-1-shot learning. Average accuracy (\%)of the query classes is reported in random episodic tasks.} \label{tab2} \begin{center} \newcommand{\tabincell}[2]{\begin{tabular}{@{}#1@{}}#2\end{tabular}} \begin{tabular}{l|p{2.0cm}p{2.0cm}p{2.0cm}p{2.0cm}} \hline \bfseries Method &\bfseries 5-way-1-shot &\bfseries &\bfseries \\ \cline{2-4} \bfseries &\bfseries miniImageNet &\bfseries tieredImageNet &\bfseries FC100 \\ \hline \hline EGNN \cite{kim2019edge} & $52.46\pm0.45$ &$57.94\pm0.42$ & $35.00\pm0.39$ \\ \hline HOSP-GNN-D & $52.44\pm0.43$ &$57.91\pm0.39$ & $35.55\pm0.40$ \\ \hline HOSP-GNN-S & $52.86\pm0.41$ &$57.84\pm0.44$ & $35.48\pm0.42$ \\ \hline\hline HOSP-GNN-H & $69.52\pm0.41$ &$91.71\pm 0.28$ & $76.24\pm0.41$ \\ \hline HOSP-GNN-H-D & $78.82\pm0.45$ &$82.63\pm0.26$ & $82.27\pm0.44$ \\ \hline HOSP-GNN-H-S & $88.15\pm0.35$ &$\textbf{95.39}\pm\textbf{0.20}$ & $\textbf{83.65}\pm\textbf{0.38}$ \\ \hline HOSP-GNN & $\textbf{93.93}\pm\textbf{0.37}$ &$94.00\pm0.24$ & $76.79\pm0.46$ \\ \hline \end{tabular} \end{center} \end{table} \begin{table}[!ht] \small \renewcommand{\arraystretch}{1.0} \caption{Comparison of Comparison of the methods related the high-order structure (HOSP-GNN,HOSP-GNN-H-S,HOSP-GNN-H-D,and HOSP-GNN-H) with baseline methods (EGNN,HOSP-GNN-S,and HOSP-GNN-D) for 5-way-5-shot learning. Average accuracy (\%)of the query classes is reported in random episodic tasks.} \label{tab3} \begin{center} \newcommand{\tabincell}[2]{\begin{tabular}{@{}#1@{}}#2\end{tabular}} \begin{tabular}{l|p{2.0cm}p{2.0cm}p{2.0cm}p{2.0cm}} \hline \bfseries Method &\bfseries 5-way-5-shot &\bfseries &\bfseries \\ \cline{2-4} \bfseries &\bfseries miniImageNet &\bfseries tieredImageNet &\bfseries FC100 \\ \hline \hline EGNN \cite{kim2019edge} & $67.33\pm0.40$ &$68.93\pm0.40$ & $47.77\pm0.42$ \\ \hline HOSP-GNN-D & $65.75\pm0.43$ &$68.30\pm 0.40$ & $47.00\pm0.41$ \\ \hline HOSP-GNN-S & $66.10\pm0.42$ &$68.64\pm0.41$ & $47.69\pm0.41$ \\ \hline\hline HOSP-GNN-H & $69.19\pm0.44$ &$90.06\pm 0.30$ & $70.82\pm0.46$ \\ \hline HOSP-GNN-H-D & $68.39\pm0.42$ &$91.11\pm0.29$ & $48.48\pm0.43$ \\ \hline HOSP-GNN-H-S & $68.85\pm0.42$ &$91.16\pm0.29$ & $48.25\pm0.43$ \\ \hline HOSP-GNN & $\textbf{95.98}\pm\textbf{0.21}$ &$\textbf{98.44}\pm\textbf{0.12}$ & $\textbf{70.94}\pm\textbf{0.51}$ \\ \hline \end{tabular} \end{center} \end{table} In Table \ref{tab2} and \ref{tab3}, the methods related the high-order structure relationship show the better performance in the base-line methods. However, the performance of HOSP-GNN based on the high-order structure combination is different because of the adaptability and coupling between the high-order structure and the pair-wise structure (similarity or dissimilarity). Figure \ref{fig-5} demonstrates the validation accuracy with iteration increasing for 5-way-1-shot or 5-way-5-shot in the different datasets. These processes also indicate the effectiveness of the high-order structure for training few-shot model. The details is analyzed in section \ref{analysis}. \begin{figure} \subfigure[]{ \centering \includegraphics[width=2.4in]{fig5-1.png} } \subfigure[]{ \centering \includegraphics[width=2.4in]{fig5-2.png} } \subfigure[]{ \centering \includegraphics[width=2.4in]{fig5-3.png} } \subfigure[]{ \centering \includegraphics[width=2.4in]{fig5-4.png} } \subfigure[]{ \centering \includegraphics[width=2.4in]{fig5-5.png} } \subfigure[]{ \centering \includegraphics[width=2.4in]{fig5-6.png} } \caption{Validation accuracy with iteration increasing for 5-way-1-shot or 5-way-5-shot in the different datasets.(a),(c) and (e) for 5-way-1-shot in miniImageNet,tieredImageNet and FC100; (b),(d) and (f) for 5-way-5-shot in miniImageNet,tieredImageNet and FC100.} \label{fig-5} \end{figure} \subsection{Comparison with state-of-the-arts} In this section, we compare the proposed HOSP-GNN with the state-of-the-art methods, which include EGNN\cite{kim2019edge},MLMT \cite{fei2020meta},ArL\cite{zhang2020rethinking}, and CML-BGNN\cite{luo2019learning}, which are detailed in section \ref{ML}. These methods can capture the structure relationship of the samples in the episodic tasks based on meta-learning for few-shot learning. The difference of these method are based on the various processing ways to mine the structure relationship for few-shot models. Therefore,these methods denote the different classification performance in the benchmark datasets. Table \ref{tab4} and \ref{tab5} express that the performance of the proposed HOSP-GNN is greatly better than that of other methods. It shows that the dependence of the episodic tasks can be better described by high-order structure based on HOSP-GNN. The detailed analysis is demonstrated in section \ref{analysis}. \begin{table}[!ht] \small \renewcommand{\arraystretch}{1.0} \caption{Comparison of HOSP-GNN method with state-of-art methods (EGNN,MLMT,ArL,and CML-BGNN) for 5-way-1-shot learning. Average accuracy (\%)of the query classes is reported in random episodic tasks.} \label{tab4} \begin{center} \newcommand{\tabincell}[2]{\begin{tabular}{@{}#1@{}}#2\end{tabular}} \begin{tabular}{l|p{2.0cm}p{2.0cm}p{2.0cm}p{2.0cm}} \hline \bfseries Method &\bfseries 5-way-1-shot &\bfseries &\bfseries \\ \cline{2-4} \bfseries &\bfseries miniImageNet &\bfseries tieredImageNet &\bfseries FC100 \\ \hline \hline EGNN \cite{kim2019edge} & $52.46\pm0.45$ &$57.94\pm0.42$ & $35.00\pm0.39$ \\ \hline MLMT \cite{fei2020meta} & $72.41\pm0.49$ &$72.82\pm0.52$ & $null$ \\ \hline ArL \cite{zhang2020rethinking} & $59.12\pm0.67$ &$null$ & $null$ \\ \hline CML-BGNN \cite{luo2019learning} & $88.62\pm0.43$ &$88.87\pm 0.51$ & $67.67\pm1.02$ \\ \hline\hline HOSP-GNN & $\textbf{93.93}\pm\textbf{0.37}$ &$\textbf{94.00}\pm\textbf{0.24}$ & $\textbf{76.79}\pm\textbf{0.46}$ \\ \hline \end{tabular} \end{center} \end{table} \begin{table}[!ht] \small \renewcommand{\arraystretch}{1.0} \caption{Comparison of HOSP-GNN method with state-of-art methods (EGNN,MLMT,ArL,and CML-BGNN) for 5-way-5-shot learning. Average accuracy (\%)of the query classes is reported in random episodic tasks.} \label{tab5} \begin{center} \newcommand{\tabincell}[2]{\begin{tabular}{@{}#1@{}}#2\end{tabular}} \begin{tabular}{l|p{2.0cm}p{2.0cm}p{2.0cm}p{2.0cm}} \hline \bfseries Method &\bfseries 5-way-5-shot &\bfseries &\bfseries \\ \cline{2-4} \bfseries &\bfseries miniImageNet &\bfseries tieredImageNet &\bfseries FC100 \\ \hline \hline EGNN \cite{kim2019edge} & $67.33\pm0.40$ &$68.93\pm0.40$ & $47.77\pm0.42$ \\ \hline MLMT \cite{fei2020meta} & $84.96\pm0.34$ &$85.97\pm0.35$ & $null$ \\ \hline ArL \cite{zhang2020rethinking} & $73.56\pm0.45$ &$null$ & $null$ \\ \hline CML-BGNN \cite{luo2019learning} & $92.69\pm 0.31$ &$92.77\pm 0.28$ & $63.93\pm 0.67$ \\ \hline\hline HOSP-GNN & $\textbf{95.98}\pm\textbf{0.21}$ &$\textbf{98.44}\pm\textbf{0.12}$ & $\textbf{70.94}\pm\textbf{0.51}$ \\ \hline \end{tabular} \end{center} \end{table} \subsection{Semi-supervised few-shot learning} In support set, we label the part of samples on all classes for the robust test of the learning model, and this situation is called semi-supervised few-shot learning. Therefore, we set $20\%$, $40\%$, and $100\%$ labeled samples of the support set for 5-way-5-shot learning in miniImageNet dataset. In this section, we compare the proposed HOSP-GNN with three graph related methods, which are GNN\cite{SatorrasE18},EGNN\cite{kim2019edge} and CML-BGNN\cite{luo2019learning}. The common of these methods is based on graph for describing the structure of the samples, while the difference of these methods is the various ways for mining the structure of the samples. For example, GNN focuses on generic message-passing mechanism for optimizing the samples structure;EGNN emphasizes on updating mechanism for evolving the edge feature;CML-BGNN cares about the continual information of the episode tasks for structure complement; The proposed HOSP-GNN expects to mine the high-order structure for connecting the separated tasks and preserves the layer-by-layer manifold structure of the samples for constraining the model learning.The detailed analysis is indicated in section \ref{analysis}. \begin{table}[!ht] \small \renewcommand{\arraystretch}{1.0} \caption{Semi-supervised few-shot learning for the graph related methods(GNN,EGNN,CML-BGNN and the proposed HOSP-GNN) in miniImageNet dataset. Average accuracy (\%)of the query classes is reported in random episodic tasks.} \label{tab6} \begin{center} \newcommand{\tabincell}[2]{\begin{tabular}{@{}#1@{}}#2\end{tabular}} \begin{tabular}{l|p{2.0cm}p{2.0cm}p{2.0cm}p{2.0cm}} \hline \bfseries Method &\bfseries miniImageNet &\bfseries 5-way-5-shot &\bfseries \\ \cline{2-4} \bfseries &\bfseries $20\%$-labeled &\bfseries $40\%$-labeled &\bfseries $100\%$-labeled \\ \hline \hline GNN \cite{SatorrasE18} & $52.45\pm0.88$ &$58.76\pm0.86$ & $66.41\pm0.63$ \\ \hline EGNN \cite{kim2019edge} & $63.62\pm0.00$ &$64.32\pm0.00$ & $75.25\pm0.49$ \\ \hline CML-BGNN \cite{luo2019learning} & $\textbf{88.95}\pm\textbf{0.32}$ &$\textbf{89.70}\pm\textbf{0.32}$ &$92.69\pm0.31$ \\ \hline\hline HOSP-GNN & $65.93\pm0.38$ &$67.06\pm0.40$ & $\textbf{95.98}\pm\textbf{0.21}$ \\ \hline \end{tabular} \end{center} \end{table} \subsection{Ablation experiments for the layer number and the loss} The proposed HOSP-GNN have two key points about structure evolution. One is the influence of the layer for model learning in graph. Another is the layer-by-layer manifold structure constraint for generating the better model with the preserved structure. Therefore, we respectively evaluate these points by ablating the part of the components from the whole model. The first experiment is about layers ablation, in which we train one layer model, two layer model and tree layer model for few-shot learning in Table \ref{tab7}. The second experiment is about the different loss, in which we set the various losses propagation for optimizing the model in Table \ref{tab8}.Table \ref{tab9} shows the parameter $\lambda$ influence to the proposed HOSP-GNN. The detailed analysis of these experimental results is shown in section \ref{analysis}. \begin{table}[!ht] \small \renewcommand{\arraystretch}{1.0} \caption{Comparison of the different layer model for the graph related methods(GNN,EGNN,CML-BGNN and the proposed HOSP-GNN) in miniImageNet dataset. Average accuracy (\%)of the query classes is reported in random episodic tasks.} \label{tab7} \begin{center} \newcommand{\tabincell}[2]{\begin{tabular}{@{}#1@{}}#2\end{tabular}} \begin{tabular}{l|p{2.5cm}p{2.5cm}p{2.5cm}p{2.5cm}p{2.5cm}} \hline \bfseries Method &\bfseries miniImageNet &\bfseries 5-way-1-shot &\bfseries \\ \cline{2-4} \bfseries &\bfseries one layer model &\bfseries two layer model &\bfseries three layer model \\ \hline \hline GNN \cite{SatorrasE18} & $48.25\pm0.65$ &$49.17\pm0.35$ & $50.32\pm0.41$ \\ \hline EGNN \cite{kim2019edge} & $55.13\pm0.44$ &$57.47\pm0.53$ & $58.65\pm0.55$ \\ \hline CML-BGNN \cite{luo2019learning} & $\textbf{85.75}\pm\textbf{0.47}$ &$87.67\pm0.47$ &$88.62\pm0.43$ \\ \hline HOSP-GNN & $75.13\pm0.44$ &$\textbf{87.77}\pm\textbf{0.37}$ & $\textbf{93.93}\pm\textbf{0.37}$ \\ \hline\hline \bfseries Method &\bfseries miniImageNet &\bfseries 5-way-5-shot &\bfseries \\ \cline{2-4} \bfseries &\bfseries one layer model &\bfseries two layer model &\bfseries three layer model \\ \hline \hline GNN \cite{SatorrasE18} & $65.58\pm0.34$ &$67.21\pm0.49$ & $66.99\pm0.43$ \\ \hline EGNN \cite{kim2019edge} & $67.76\pm0.42$ &$74.70\pm0.46$ & $75.25\pm0.49$ \\ \hline CML-BGNN \cite{luo2019learning} & $\textbf{90.85}\pm\textbf{0.27}$ &$\textbf{91.63}\pm\textbf{0.26}$ &$92.69\pm0.31$ \\ \hline HOSP-GNN & $67.86\pm0.41$ &$72.48\pm0.37$ & $\textbf{95.98}\pm\textbf{0.21}$ \\ \hline \end{tabular} \end{center} \end{table} \begin{table}[!ht] \small \renewcommand{\arraystretch}{1.0} \caption{Comparison of the different loss model for the proposed HOSP-GNN (HOSP-GNN-loss1 for label loss in support set , and HOSP-GNN for the consideration of the label and manifold structure loss). Average accuracy (\%)of the query classes is reported in random episodic tasks.} \label{tab8} \begin{center} \newcommand{\tabincell}[2]{\begin{tabular}{@{}#1@{}}#2\end{tabular}} \begin{tabular}{l|p{2.0cm}p{2.0cm}p{2.0cm}p{2.0cm}} \hline \bfseries Method &\bfseries 5-way-5-shot &\bfseries &\bfseries \\ \cline{2-4} \bfseries &\bfseries miniImageNet &\bfseries tieredImageNet &\bfseries FC100 \\ \hline \hline HOSP-GNN-loss1 & $92.29\pm0.28$ &$98.41\pm0.12$ & $65.47\pm0.51$ \\ \hline\hline HOSP-GNN & $\textbf{95.98}\pm\textbf{0.21}$ &$\textbf{98.44}\pm\textbf{0.12}$ & $\textbf{70.94}\pm\textbf{0.51}$ \\ \hline \end{tabular} \end{center} \end{table} \begin{table}[!ht] \small \renewcommand{\arraystretch}{1.0} \caption{The tradeoff parameter $\lambda$ influence to few-show learning in miniImageNet.} \label{tab9} \begin{center} \newcommand{\tabincell}[2]{\begin{tabular}{@{}#1@{}}#2\end{tabular}} \begin{tabular}{l|p{1.0cm}p{1.0cm}p{1.0cm}p{1.0cm}p{1.0cm}p{1.0cm}p{1.0cm}} \hline \bfseries Method &\bfseries miniImageNet &\bfseries &\bfseries 5-way-5-shot &\bfseries $\lambda$ &\bfseries \\ \cline{2-7} \bfseries &\bfseries $10^{-2}$ &\bfseries $10^{-3}$ &\bfseries $10^{-4}$ &\bfseries $10^{-5}$ &\bfseries $10^{-6}$ &\bfseries $10^{-7}$ \\ \hline \hline HOSP-GNN & $94.65\pm0.22$ &$93.71\pm0.25$ & $93.43\pm0.25$ & $95.98\pm0.21$ &$95.31\pm0.21$ & $91.89\pm0.30$\\ \hline \end{tabular} \end{center} \end{table} \subsection{Experimental results analysis} \label{analysis} In above experiments, there are ten methods used for comparing with the proposed HOSP-GNN. In the baseline methods (HOSP-GNN,EGNN \cite{kim2019edge}, HOSP-GNN-H-S, HOSP-GNN-H-D, HOSP-GNN-H, HOSP-GNN-S and HOSP-GNN-D),we can capture the various structure information of the samples for constructing the similar learning model. In the state-of-the-art methods (EGNN\cite{kim2019edge}, MLMT \cite{fei2020meta}, ArL\cite{zhang2020rethinking}, ,CML-BGNN\cite{luo2019learning} and HOSP-GNN), we demonstrate the model learning results based on the different networks framework for mining the relevance between the separated tasks. In the semi-supervised methods (GNN\cite{SatorrasE18},EGNN\cite{kim2019edge} , CML-BGNN\cite{luo2019learning} and HOSP-GNN), we can find the labeled samples number to the performance influence for the robust testing of these methods. In ablation experiments, we build the different layers model(one layer model, two layer model and three layer model) and the various loss model (HOSP-GNN-loss1 and HOSP-GNN) for indicating their effects. The proposed HOSP-GNN can jointly consider the high-order structure and the layer-by-layer manifold structure constraints to effectively recognize the new categories. From these experiments, we have the following observations and analysis. \begin{itemize} \item The proposed HOSP-GNN and its Variants (HOSP-GNN-H-S, HOSP-GNN-H-D and HOSP-GNN-H) greatly outperform the base-line methods(HOSP-GNN-S, HOSP-GNN-D and EGNN) in table \ref{tab2},table \ref{tab3}, and figure \ref{fig-5}. The common characteristic of these methods (the proposed HOSP-GNN and its Variants) involves the high-order structure for learning model. Therefore,it shows that the high-order structure can better associate with the samples from the different tasks for improving the performance of few-shot learning. \item The performance of the proposed HOSP-GNN and its Variants(HOSP-GNN-H-S, HOSP-GNN-H-D and HOSP-GNN-H) indicate the different results in the various dataset and experimental configuration in table \ref{tab2}, table \ref{tab3}, and figure \ref{fig-5}. In 5-way-1-shot learning, HOSP-GNN has the better performance than other methods in miniImageNet, while HOSP-GNN-H-S indicates the better results than others in tieredImageNet and FC100. In 5-way-5-shot learning, HOSP-GNN also shows the better performance than others in miniImageNet,tierdImageNet,and FC100. It shows that similarity, dissimilarity and high-order structure have the different influence to the model performance in the various datasets. For example, similarity,dissimilarity and high-order structure have the positive effect for recognizing the new categories in miniImageNet and tierdImageNet, while dissimilarity produces the negative effect for learning model in FC100. In any situation, high-order structure has an important and positive role for improving the model performance. \item The proposed HOSP-GNN obviously is superior to other state-of-the-art methods in table \ref{tab4} and \ref{tab5}. These methods focus on the different aspects, which are the graph information mining based on EGNN\cite{kim2019edge}, the across task information exploitation based on MLMT \cite{fei2020meta}, the semantic-class relationship utilization based on ArL\cite{zhang2020rethinking}, the history information association based on CML-BGNN\cite{luo2019learning}, and the high-order structure exploration based on HOSP-GNN. The proposed HOSP-GNN can not only exploit the across task structure by the extension association of the high-order structure , but also use the latent manifold structure to constrain the model learning, so the proposed HOSP-GNN obtains the best performance in these methods. \item The proposed HOSP-GNN demonstrates the better performance than the graph related methods(GNN\cite{SatorrasE18}, EGNN\cite{kim2019edge}, and CML-BGNN\cite{luo2019learning}) based on the more labeled samples in table \ref{tab6}. The enhanced structure of the more labeled samples can efficiently propagate the discriminative information to the new categories by the high-order information evolution based on the graph. The labeled sample number has few influence on model learning based on CML-BGNN\cite{luo2019learning}. In contrast, labeled sample number has an important impact on model learning based on the graph related methods(GNN\cite{SatorrasE18}, EGNN\cite{kim2019edge}, and HOSP-GNN). \item In the different layer model experiments, the proposed HOSP-GNN indicates the various performance with layer number changing in table \ref{tab7}. In 5-way-1-shot learning, HOSP-GNN has the better performance than other methods, while in 5-way-5-shot learning, CML-BGNN\cite{luo2019learning} shows the more challenging results than other methods. It demonstrates that layer number has an important impact on the high-order structure evolution. We can obtain the significant improvement based on the more layer model of HOSP-GNN for 5-way-5-shot in miniImageNet, while the performances of other methods almost are not changing with the layer number increasing. Therefore, the proposed HOSP-GNN trends to the more layers to exploit the high-order structure for few-shot learning. \item In table \ref{tab8}, the different losses (supervised label loss and manifold structure loss) are considered for constructing few-shot model. HOSP-GNN (the method model based on supervised label loss and manifold structure loss) can show the better performance than HOSP-GNN-loss1(the approach involves the model with the supervised label loss). It expresses that manifold constraint with the layer-by-layer evolution can enhance the performance of model because of the intrinsic distribution consistence on the samples of the different task. \end{itemize} \section{Conclusion} To associate and mine the samples relationship in the different tasks, we have presented high-order structure preserving graph neural network(HOSP-GNN) for few-shot learning. HOSP-GNN can not only describe high-order structure relationship by the relative metric in multi-samples, but also reformulate the updating rules of graph structure by the alternate computation between vertexes and edges based on high-order structure. Moreover, HOSP-GNN can enhance the model learning performance by the layer-by-layer manifold structure constraint for few-shot classification. Finally, HOSP-GNN can jointly consider similarity, dissimilarity and high-order structure to exploit the metric consistence between the separated tasks for recognizing the new categories. For evaluating the proposed HOSP-GNN, we carry out the comparison experiments about the baseline methods,the state of the art methods, the semi-supervised fashion, and the layer or loss ablation on miniImageNet, tieredImageNet and FC100. In experiments, HOSP-GNN demonstrates the prominent results for few-shot learning. \section{Acknowledgements} The authors would like to thank the anonymous reviewers for their insightful comments that help improve the quality of this paper. Especially, this work was supported by NSFC (Program No.61771386,Program No.61671376 and Program No.61671374), Research and Development Program of Shaanxi (Program No.2020SF-359).
{'timestamp': '2020-06-01T02:07:25', 'yymm': '2005', 'arxiv_id': '2005.14415', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14415'}
arxiv
\section*{Acknowledgment} We thank anonymous reviewers for their helpful comments to improve this research. Yanhao Wang has been supported by the MLDB project of Academy of Finland (decision number: 322046). The research of Raymond Chi-Wing Wong is supported by HKRGC GRF 16219816. \bibliographystyle{IEEEtran} \section{Introduction} \label{sec:intro} In many real-world applications such as multi-criteria decision making~\cite{DBLP:journals/pvldb/NanongkaiSLLX10}, web search~\cite{DBLP:conf/edbt/StoyanovichYJ18}, recommendation~\cite{DBLP:journals/tkde/WangLT19,DBLP:conf/recsys/LiuMLY11}, and data description~\cite{DBLP:conf/kdd/WangLT19}, it is crucial to find a succinct representative subset from a large database to meet the requirements of various users. For example, when a user queries for a hotel on a website (e.g.,~booking.com and~expedia.com), she/he will receive thousands of available options as results. The website would like to display the best choices in the first few pages from which almost all users could find what they are most interested in. A common method is to rank all results using a utility function that denotes a user's preference on different attributes (e.g.,~\emph{price}, \emph{rating}, and \emph{distance to destination} for hotels) and only present the top-$k$ tuples with the highest scores according to this function to the user. However, due to the wide diversity of user preferences, it is infeasible to represent the preferences of all users by any single utility function. Therefore, to select a set of highly representative tuples, it is necessary to take all (possible) user preferences into account. A well-established approach to finding such representatives from databases is the \emph{skyline} operator~\cite{DBLP:conf/icde/BorzsonyiKS01} based on the concept of \emph{domination}: a tuple $p$ dominates a tuple $q$ iff $p$ is as good as $q$ on all attributes and strictly better than $q$ on at least one attribute. For a given database, a skyline query returns its \emph{Pareto-optimal} subset which consists of all tuples that are not dominated by any tuple. It is guaranteed that any user can find her/his best choice from the skyline because the top-ranked result according to any monotone function must not be dominated. Unfortunately, although skyline queries are effective for representing low-dimensional databases, their result sizes cannot be controlled and increase rapidly as the dimensionality (i.e.,~number of attributes in a tuple) grows, particularly so for databases with anti-correlated attributes. Recently, the $k$-regret minimizing set ($k$-RMS) problem~\cite{DBLP:journals/pvldb/NanongkaiSLLX10,DBLP:conf/icde/PengW14,DBLP:journals/pvldb/ChesterTVW14,DBLP:conf/wea/AgarwalKSS17,DBLP:conf/icdt/CaoLWWWWZ17,DBLP:conf/sigmod/AsudehN0D17,DBLP:conf/alenex/KumarS18,DBLP:conf/sigmod/XieW0LL18} was proposed to alleviate the deficiency of skyline queries. Specifically, given a database $P$ of tuples with $d$ numeric attributes, the $k$-RMS problem aims to find a subset $Q \subseteq P$ such that, for any possible utility function, the top-$1$ tuple in $Q$ can approximate the top-$k$ tuples in $P$ within a small error. Here, the \emph{maximum $k$-regret ratio}~\cite{DBLP:journals/pvldb/ChesterTVW14} ($\mathtt{mrr}_k$) is used to measure how well $Q$ can represent $P$. For a utility function $f$, the $k$-regret ratio ($\mathtt{rr}_k$) of $Q$ over $P$ is defined to be $0$ if the top-$1$ tuple in $Q$ is among the top-$k$ tuples in $P$ w.r.t.~$f$, or otherwise, to be one minus the ratio between the score of the top-$1$ tuple in $Q$ and the score of the $k$\textsuperscript{th}-ranked tuple in $P$ w.r.t.~$f$. Then, the \emph{maximum $k$-regret ratio} ($\mathtt{mrr}_k$) is defined by the maximum of $\mathtt{rr}_k$ over a class of (possibly infinite) utility functions. Given a positive integer $r$, a $k$-RMS on a database $P$ returns a subset $Q \subseteq P$ of size $r$ to minimize $\mathtt{mrr}_k$. As an illustrative example, the website could run a $k$-RMS on all available hotels to pick a set of $r$ candidates from which all users can find at least one close to her/his top-$k$ choices. The $k$-RMS problem has been extensively studied recently. Theoretically, it is NP-hard~\cite{DBLP:journals/pvldb/ChesterTVW14,DBLP:conf/wea/AgarwalKSS17,DBLP:conf/icdt/CaoLWWWWZ17} on any database with $d \geq 3$. In general, we categorize existing $k$-RMS algorithms into three types. The first type is dynamic programming algorithms~\cite{DBLP:conf/sigmod/AsudehN0D17,DBLP:journals/pvldb/ChesterTVW14,DBLP:conf/icdt/CaoLWWWWZ17} for $k$-RMS on two-dimensional data. Although they can provide optimal solutions when $d = 2$, they are not suitable for higher dimensions due to the NP-hardness of $k$-RMS. The second type is the greedy heuristic~\cite{DBLP:journals/pvldb/NanongkaiSLLX10,DBLP:conf/icde/PengW14,DBLP:journals/pvldb/ChesterTVW14}, which always adds a tuple that maximally reduces $\mathtt{mrr}_k$ at each iteration. Although these algorithms can provide high-quality results empirically, they have no theoretical guarantee and suffer from low efficiency on high-dimensional data. The third type is to transform $k$-RMS into another problem such as $\varepsilon$-kernel~\cite{DBLP:conf/sigmod/XieW0LL18,DBLP:conf/alenex/KumarS18,DBLP:conf/wea/AgarwalKSS17,DBLP:conf/icdt/CaoLWWWWZ17}, discretized matrix min-max~\cite{DBLP:conf/sigmod/AsudehN0D17}, hitting set~\cite{DBLP:conf/alenex/KumarS18,DBLP:conf/wea/AgarwalKSS17}, and $k$-\textsc{medoid} clustering~\cite{Shetiya2019}, and then to utilize existing solutions of the transformed problem for $k$-RMS computation. Although these algorithms are more efficient than greedy heuristics while having theoretical bounds, they are designed for the static setting and cannot process database updates efficiently. Typically, most of them precompute the skyline as an input to compute the result of $k$-RMS. Once a tuple insertion or deletion triggers any change in the skyline, they are unable to maintain the result without re-running from scratch. Hence, existing $k$-RMS algorithms become very inefficient in highly dynamic environments where tuples in the databases are frequently inserted and deleted. However, dynamic databases are very common in real-world scenarios, especially for online services. For example, in a hotel booking system, the \emph{prices} and \emph{availabilities} of rooms are frequently changed over time. As another example, in an IoT network, a large number of sensors may often connect or disconnect with the server. Moreover, sensors also update their statistics regularly. Therefore, it is essential to address the problem of maintaining an up-to-date result for $k$-RMS when the database is frequently updated. In this paper, we propose the first fully-dynamic $k$-RMS algorithm that can efficiently maintain the result of $k$-RMS w.r.t.~any tuple insertion and deletion in the database with both theoretical guarantee and good empirical performance. Our main contributions are summarized as follows. \begin{itemize} \item We formally define the notion of \emph{maximum $k$-regret ratio} and the \emph{$k$-regret minimizing set} ($k$-RMS) problem in a fully-dynamic setting. (Section~\ref{sec:definition}) \item We propose the first fully-dynamic algorithm called FD-RMS to maintain the $k$-RMS result over tuple insertions and deletions in a database. Our basic idea is to transform \emph{fully-dynamic $k$-RMS} into a \emph{dynamic set cover} problem. Specifically, FD-RMS computes the (approximate) top-$k$ tuples for a set of randomly sampled utility functions and builds a set system based on the top-$k$ results. Then, the $k$-RMS result can be retrieved from an approximate solution for \emph{set cover} on the set system. Furthermore, we devise a novel algorithm for dynamic set cover by introducing the notion of \emph{stable solution}, which is used to efficiently update the $k$-RMS result whenever an insertion or deletion triggers some changes in top-$k$ results as well as the set system. We also provide detailed theoretical analyses of FD-RMS. (Section~\ref{sec:framework}) \item We conduct extensive experiments on several real-world and synthetic datasets to evaluate the performance of FD-RMS. The results show that FD-RMS achieves up to four orders of magnitude speedup over existing $k$-RMS algorithms while providing results of nearly equal quality in a fully dynamic setting. (Section~\ref{sec:exp}) \end{itemize} \section{The FD-RMS Algorithm} \label{sec:framework} \begin{figure} \centering \includegraphics[width=.475\textwidth]{framework.pdf} \caption{An illustration of FD-RMS} \label{fig:framework} \end{figure} In this section, we present our FD-RMS algorithm for $k$-RMS in a fully dynamic setting. The general framework of FD-RMS is illustrated in Fig.~\ref{fig:framework}. The basic idea is to transform \emph{fully-dynamic $k$-RMS} to a \emph{dynamic set cover} problem. Let us consider how to compute the result of $\mathtt{RMS}(k,r)$ on database $P_t$. First of all, we draw a set of $m$ random utility vectors $\{u_1,\ldots,u_m\}$ from $ \mathbb{U} $ and maintain the $\varepsilon$-approximate top-$k$ result of each $u_i$ ($i \in [1,m]$) on $P_t$, i.e., $ \Phi_{k,\varepsilon}(u_i,P_t) $. Note that $\varepsilon$ should be given as an input parameter of FD-RMS and we will discuss how to specify its value at the end of Section~\ref{sec:framework}. Then, we construct a set system $ \Sigma = (\mathcal{U},\mathcal{S}) $ based on the approximate top-$k$ results, where the universe $\mathcal{U}=\{u_1,\ldots,u_m\}$ and the collection $\mathcal{S}$ consists of $n_t$ sets ($n_t=|P_t|$) each of which corresponds to one tuple in $P_t$. Specifically, for each tuple $p \in P_t$, we define $S(p)$ as a set of utility vectors for which $p$ is an $\varepsilon$-approximate top-$k$ result on $P_t$. Or formally, $S(p) = \{u \in \mathcal{U} : p \in \Phi_{k,\varepsilon}(u,P_t)\}$ and $\mathcal{S}=\{ S(p) : p \in P_t \}$. After that, we compute a result $Q_t$ for $\mathtt{RMS}(k,r)$ on $P_t$ using an (approximate) solution for set cover on $\Sigma$. Let $\mathcal{C} \subseteq \mathcal{S}$ be a set-cover solution of $\Sigma$, i.e., $\bigcup_{S(p) \in \mathcal{C}} S(p)=\mathcal{U}$. We use the set $Q_t$ of tuples corresponding to $\mathcal{C}$, i.e., $Q_t=\{p \in P_t : S(p) \in \mathcal{C}\}$, as the result of $\mathtt{RMS}(k,r)$ on $P_t$. Given the above framework, there are still two challenges of updating the result of $k$-RMS in a fully dynamic setting. Firstly, because the size of $Q_t$ is restricted to $r$, it is necessary to always keep an appropriate value of $m$ over time so that $|\mathcal{C}| \leq r$. Secondly, the updates in approximate top-$k$ results triggered by tuple insertions and deletions in the database lead to the changes in the set collection $\mathcal{S}$. Therefore, it is essential to maintain the set-cover solution $\mathcal{C}$ over time for the changes in $\mathcal{S}$. In fact, both challenges can be treated as a \emph{dynamic set cover} problem that keeps a set-cover solution w.r.t.~changes in both $\mathcal{U}$ and $\mathcal{S}$. Therefore, we will first introduce the background on \emph{dynamic set cover} in Section~\ref{subsec:set:cover}. After that, we will elaborate on how FD-RMS processes $k$-RMS in a fully dynamic setting using the \emph{dynamic set cover} algorithm in Section~\ref{subsec:alg}. \subsection{Background: Dynamic Set Cover} \label{subsec:set:cover} Given a set system $\Sigma=(\mathcal{U},\mathcal{S})$, the \emph{set cover} problem asks for the smallest subset $\mathcal{C}^{*}$ of $\mathcal{S}$ whose union equals to the universe $\mathcal{U}$. It is one of Karp's 21 NP-complete problems~\cite{DBLP:conf/coco/Karp72}, and cannot be approximated to $(1-o(1))\cdot\ln{m}$ ($m=|\mathcal{U}|$) unless P=NP~\cite{DBLP:journals/jacm/Feige98}. A common method to find an approximate set-cover solution is the greedy algorithm. Starting from $\mathcal{C} = \varnothing$, it always adds the set that contains the largest number of uncovered elements in $\mathcal{U}$ to $\mathcal{C}$ at each iteration until $\bigcup_{S \in \mathcal{C}}S=\mathcal{U}$. Theoretically, the solution $\mathcal{C}$ achieves an approximation ratio of $(1+\ln{m})$, i.e., $|\mathcal{C}| \leq (1+\ln{m}) \cdot |\mathcal{C}^{*}|$. But obviously, the greedy algorithm cannot dynamically update the set-cover solution when the set system $\Sigma$ is changed. Recently, there are some theoretical advances on covering and relevant problems (e.g., vertex cover, maximum matching, set cover, and maximal independent set) in dynamic settings~\cite{DBLP:journals/siamcomp/BhattacharyaHI18,DBLP:conf/stoc/GuptaK0P17,DBLP:conf/stoc/AbboudA0PS19,DBLP:conf/stacs/HjulerIPS19}. Although these theoretical results have opened up new ways to design dynamic set cover algorithms, they cannot be directly applied to the update procedure of FD-RMS because of two limitations. First, existing dynamic algorithms for set cover~\cite{DBLP:conf/stoc/AbboudA0PS19,DBLP:conf/stoc/GuptaK0P17} can only handle the update in the universe $\mathcal{U}$ but assume that the set collection $\mathcal{S}$ is not changed. But in our scenario, the changes in top-$k$ results lead to the update of $\mathcal{S}$. Second, due to the extremely large constants introduced in their analyses, the solutions returned may be far away from the optima in practice. Therefore, we devise a more practical approach to dynamic set cover that supports any update in both $\mathcal{U}$ and $\mathcal{S}$. Our basic idea is to introduce the notion of \emph{stability} to a set-cover solution. Then, we prove that any stable solution is $O(\log{m})$-approximate ($m=|\mathcal{U}|$) for set cover. Based on this result, we are able to design an algorithm to maintain a set-cover solution w.r.t.~any change in $\Sigma$ by guaranteeing its \emph{stability}. We first formalize the concept of \emph{stability} of a set-cover solution. Let $\mathcal{C} \subseteq \mathcal{S}$ be a set-cover solution on $\Sigma=(\mathcal{U},\mathcal{S})$. We define an assignment $\phi$ from each element $u \in \mathcal{U}$ to a \emph{unique} set $S \in \mathcal{C}$ that contains $u$ (or formally, $\phi: \mathcal{U} \rightarrow \mathcal{C}$). For each set $S \in \mathcal{C}$, its cover set $\mathtt{cov}(S)$ is defined as the set of elements assigned to $S$, i.e., $\mathtt{cov}(S) = \{u \in \mathcal{U} \,:\, \phi(u)=S\}$. By definition, the cover sets of different sets in $\mathcal{C}$ are \emph{mutually disjoint} from each other. Then, we can organize the sets in $\mathcal{C}$ into hierarchies according to the numbers of elements covered by them. Specifically, we put a set $S \in \mathcal{C}$ in a higher level if it covers more elements and vice versa. We associate each level $\mathcal{L}_j$ ($j \in \mathbb{N}$) with a range of cover number\footnote{Here, the base $2$ may be replaced by any constant greater than 1.} $[2^{j},2^{j+1})$. Each set $S \in \mathcal{C}$ is assigned to a level $\mathcal{L}_j$ if $2^{j} \leq |\mathtt{cov}(S)| < 2^{j+1}$. We use $A_j$ to denote the set of elements assigned to any set in $\mathcal{L}_j$, i.e., $A_j = \{u \in \mathcal{U} \,:\, \phi(u) \in \mathcal{L}_j\}$. Moreover, the notations $\mathcal{L}$ with subscripts, i.e., $\mathcal{L}_{>j}$ or $\mathcal{L}_{\geq j}$ and $\mathcal{L}_{<j}$ or $\mathcal{L}_{\leq j}$, represent the sets in all the levels above (excl.~or incl.) and below $\mathcal{L}_j$ (excl.~or incl.), respectively. The same subscripts are also used for $A$. Based on the above notions, we formally define the \emph{stability} of a set-cover solution in Definition~\ref{def:stable} and give its approximation ratio in Theorem~\ref{thm:approx:ratio}. \begin{definition}[Stable Set-Cover Solution]\label{def:stable} A solution $\mathcal{C}$ for \emph{set cover} on $\Sigma=(\mathcal{U},\mathcal{S})$ is stable if: \begin{enumerate} \item For each set $S \in \mathcal{L}_j$, $2^{j} \leq |\mathtt{cov}(S)| < 2^{j+1}$; \item For each level $\mathcal{L}_j$, there is no $S \in \mathcal{S}$ s.t. $|S \cap A_j| \geq 2^{j+1}$. \end{enumerate} \end{definition} \begin{theorem}\label{thm:approx:ratio} If a set-cover solution $\mathcal{C}$ is stable, then it satisfies that $|\mathcal{C}| \leq O(\log m) \cdot |\mathcal{C}^{*}|$. \end{theorem} \begin{proof} Let $\mathtt{OPT}=|\mathcal{C}^{*}|$, $\rho^{*}=\frac{m}{\mathtt{OPT}}$, and $j^{*}$ be the level index such that $2^{j^{*}} \leq \rho^{*} < 2^{j^{*}+1}$. According to Condition (1) of Definition~\ref{def:stable}, we have $|\mathtt{cov}(S)| \geq 2^{j^{*}}$ for any $S \in \mathcal{L}_{\geq j^{*}}$. Thus, it holds that $|\mathcal{L}_{\geq j^{*}}| \leq \frac{|A_{\geq j^{*}}|}{2^{j^{*}}} \leq \frac{m}{2^{j^{*}}} \leq \frac{\rho^{*}}{2^{j^{*}}} \cdot \mathtt{OPT} \leq 2 \cdot \mathtt{OPT}$. For some level $\mathcal{L}_j$ with $j < j^{*}$, according to Condition (2) of Definition~\ref{def:stable}, any $S \in \mathcal{S}$ covers at most $2^{j+1}$ elements in $A_j$. Hence, $\mathcal{S}^{*}$ needs at least $\frac{|A_j|}{2^{j+1}}$ sets to cover $A_j$, i.e., $\mathtt{OPT} \geq \frac{|A_j|}{2^{j+1}}$. Since $|\mathtt{cov}(S)| \geq 2^{j}$ for each $S \in \mathcal{L}_j$, it holds that $|\mathcal{L}_j| \leq \frac{|A_j|}{2^{j}} \leq 2 \cdot \mathtt{OPT}$. As $1 \leq |\mathtt{cov}(S)| \leq m$, the range of level index is $[0,\log_{2}{m}]$. Thus, the number of levels below $\mathcal{L}_{j^{*}}$ is at most $\log_{2}{m}$. To sum up, we prove that \begin{equation*}\textstyle |\mathcal{C}| = |\mathcal{L}_{\geq j^{*}}| + |\mathcal{L}_{< j^{*}}| \leq (2 + 2 \log_{2}{m}) \cdot \mathtt{OPT} \end{equation*} and conclude the proof. \end{proof} \begin{algorithm}[t] \caption{\textsc{Dynamic Set Cover}}\label{alg:set:cover} \Input{Set system $\Sigma$, set operation $\sigma$} \Output{Stable set-cover solution $\mathcal{C}$} \tcc{compute an initial solution $\mathcal{C}$ on $\Sigma$} $ \mathcal{C} \gets$ \textsc{Greedy}$(\Sigma)$\;\label{ln:cover:init} \tcc{update $\mathcal{C}$ for $\sigma=(u,S,\pm)$ or $(u,\mathcal{U},\pm)$} \uIf{$\sigma=(u,S,-)$ and $u \in \mathtt{cov}(S)$\label{ln:sigma:s}}{ $ \mathtt{cov}(S) \gets \mathtt{cov}(S) \setminus \{u\} $\; $ \mathtt{cov}(S^+) \gets \mathtt{cov}(S^+) \cup \{u\} $ for $S^+ \in \mathcal{S}$ s.t.~$u \in S^+$\; \textsc{ReLevel}$(S)$ and \textsc{ReLevel}$(S^+)$\;\label{ln:move:1} } \uElseIf{$\sigma=(u,\mathcal{U},+)$}{ $ \mathtt{cov}(S^+) \gets \mathtt{cov}(S^+) \cup \{u\} $ for $S^+ \in \mathcal{S}$ s.t.~$u \in S^+$\; \textsc{ReLevel}$(S^+)$\;\label{ln:move:2} } \ElseIf{$\sigma=(u,\mathcal{U},-)$}{ $ \mathtt{cov}(S^-) \gets \mathtt{cov}(S^-) \setminus \{u\} $ if $u \in \mathtt{cov}(S^-)$\; \textsc{ReLevel}$(S^-)$\;\label{ln:move:3} } \textsc{Stabilize}$(\mathcal{C})$\;\label{ln:sigma:t} \BlankLine \Fn{\textnormal{\textsc{Greedy}$(\Sigma)$}\label{ln:greedy:s}}{ $I \gets \mathcal{U}$, $\mathcal{L}_j \gets \varnothing$ for every $j \geq 0$\; \While{$I \neq \varnothing$}{ $S^* \gets \arg\max_{S \in \mathcal{S}} |I \cap S|$, $\mathtt{cov}(S^*) \gets I \cap S^*$\;\label{ln:cover:max} Add $S^*$ to $\mathcal{L}_j$ s.t.~$2^{j} \leq |\mathtt{cov}(S^*)| < 2^{j+1}$\; $I \gets I \setminus \mathtt{cov}(S^*)$\; } \Return{$\mathcal{C} \gets \bigcup_{j \geq 0} \mathcal{L}_j$}\;\label{ln:greedy:t} } \Fn{\textnormal{\textsc{ReLevel}$(S)$}\label{ln:move:s}}{ \uIf{$\mathtt{cov}(S) = \varnothing$}{ $\mathcal{C} \gets \mathcal{C} \setminus \{S\}$\; } \Else{ Let $\mathcal{L}_{j}$ be the current level of $S$\; \If{$|\mathtt{cov}(S)| < 2^{j}$ or $|\mathtt{cov}(S)| \geq 2^{j+1}$}{ Let $j'$ be the index s.t. $2^{j'} \leq |\mathtt{cov}(S)| < 2^{j'+1}$\; Move $S$ from $\mathcal{L}_{j}$ to $\mathcal{L}_{j'}$\; } } \label{ln:move:t} } \Fn{\textnormal{\textsc{Stabilize}$(\mathcal{C})$}\label{ln:stable:s}}{ \While{$\exists S \in \mathcal{S}$ and $\mathcal{L}_j$ s.t. $|S \cap A_{j}| \geq 2^{j+1}$}{ $\mathtt{cov}(S) \gets \mathtt{cov}(S) \cup (S \cap A_{j})$, \textsc{ReLevel}($S$)\; \While{$\exists S' \in \mathcal{C} : \mathtt{cov}(S) \cap \mathtt{cov}(S') \neq \varnothing$}{ $\mathtt{cov}(S') \gets \mathtt{cov}(S') \setminus \mathtt{cov}(S)$, \textsc{ReLevel}($S'$)\; } \label{ln:stable:t} } } \end{algorithm} We then describe our method for \emph{dynamic set cover} in Algorithm~\ref{alg:set:cover}. First of all, we use \textsc{Greedy} to initialize a set-cover solution $\mathcal{C}$ on $\Sigma$ (Line~\ref{ln:cover:init}). As shown in Lines~\ref{ln:greedy:s}--\ref{ln:greedy:t}, \textsc{Greedy} follows the classic greedy algorithm for set cover, and the only difference is that all the sets in $\mathcal{C}$ are assigned to different levels according to the sizes of their cover sets. Then, the procedure of updating $\mathcal{C}$ for set operation $\sigma$ is shown in Lines~\ref{ln:sigma:s}--\ref{ln:sigma:t}. Our method supports four types of set operations to update $\Sigma$ as follows: $\sigma=(u,S,\pm)$, i.e., to add/remove an element $u$ to/from a set $S \in \mathcal{S}$; $\sigma=(u,\mathcal{U},\pm)$, i.e., to add/remove an element $u$ to/from the universe $\mathcal{U}$. We identify three cases in which the assignment of $u$ must be changed for $\sigma$. When $\sigma=(u,S,-)$ and $\phi(u)=S$, it will reassign $u$ to another set containing $u$; For $\sigma=(u,\mathcal{U},\pm)$, it will add or delete the assignment of $u$ accordingly. After that, for each set with some change in its cover set, it calls \textsc{ReLevel} (e.g., Lines~\ref{ln:move:1},~\ref{ln:move:2}, and~\ref{ln:move:3}) to check whether the set should be moved to a new level based on the updated size of its cover set. The detailed procedure of \textsc{ReLevel} is given in Lines~\ref{ln:move:s}--\ref{ln:move:t}. Finally, \textsc{Stabilize} (Line~\ref{ln:sigma:t}) is always called for every $\sigma$ to guarantee the stability of $\mathcal{C}$ since $\mathcal{C}$ may become unstable due to the changes in $\Sigma$ and $\phi(u)$. The procedure of stabilization is presented in Lines~\ref{ln:stable:s}--\ref{ln:stable:t}. It finds all sets that violate Condition~(2) of Definition~\ref{def:stable} and adjust $\mathcal{C}$ for these sets until no set should be adjusted anymore. \noindent\textbf{Theoretical Analysis:} Next, we will analyze Algorithm~\ref{alg:set:cover} theoretically. We first show that a set-cover solution returned by \textsc{Greedy} is stable. Then, we prove that \textsc{Stabilize} converges to a stable solution in finite steps. \begin{lemma}\label{lm:stability} The solution $\mathcal{C}$ returned by \textnormal{\textsc{Greedy}} is stable. \end{lemma} \begin{proof} First of all, it is obvious that each set $S \in \mathcal{C}$ is assigned to the correct level according to the size of its cover set and Condition (1) of Definition~\ref{def:stable} is satisfied. Then, we sort the sets in $\mathcal{C}$ as $S^*_1,\ldots,S^*_{|\mathcal{C}|}$ by the order in which they are added. Let $S^*_i$ be the set s.t.~$|\mathtt{cov}(S^*_i)| < 2^{j+1}$ and $|\mathtt{cov}(S^*_{i'})| \geq 2^{j+1}$ for any $i'<i$, i.e., $S^*_i$ is the first set added to level $\mathcal{L}_j$. We have $|I \cap S^*_i| = |\mathtt{cov}(S^*_i)| < 2^{j+1}$ where $I$ is the set of uncovered elements before $S^*_i$ is added to $\mathcal{C}$. If there were a set $S \in \mathcal{S}$ such that $|S \cap A_j| > 2^{j+1}$, we would acquire $|I \cap S| \geq |S \cap A_j| > 2^{j+1}$ and $|I \cap S|>|I \cap S^*_i|$, which contradicts with Line~\ref{ln:cover:max} of Algorithm~\ref{alg:rms:init}. Thus, $\mathcal{C}$ must satisfy Condition (2) of Definition~\ref{def:stable}. To sum up, $\mathcal{C}$ is a stable solution. \end{proof} \begin{lemma}\label{lm:termination} The procedure \textnormal{\textsc{Stabilize}} converges to a stable solution in $O(m\log{m})$ steps. \end{lemma} \begin{proof} For an iteration of the \texttt{while} loop (i.e., Lines~\ref{ln:stable:s}--\ref{ln:stable:t}) that picks a set $S$ and a level $\mathcal{L}_j$, the new level $\mathcal{L}_{j'}$ of $S$ always satisfies $j' > j$. Accordingly, all the elements in $\mathtt{cov}(S)$ are moved from $A_{\leq j}$ to $A_{j'}$. At the same time, no element in $A_{\geq j'}$ is moved to lower levels. Since each level contains at most $m$ elements ($|A_j| \leq m$), \textsc{Stabilize} moves at most $m$ elements across $O(\log m)$ levels. Therefore, it must terminate in $O(m \log m)$ steps. Furthermore, after termination, the set-cover solution $\mathcal{C}$ must satisfy both conditions in Definition~\ref{def:stable}. Thus, we conclude the proof. \end{proof} The above two lemmas can guarantee that the set-cover solution provided by Algorithm~\ref{alg:set:cover} is always stable after any change in the set system. In the next subsection, we will present how to use it for fully-dynamic $k$-RMS. \subsection{Algorithmic Description}\label{subsec:alg} Next, we will present how FD-RMS maintains the $k$-RMS result by always keeping a \emph{stable} set-cover solution on a dynamic set system built from the approximate top-$k$ results over tuple insertions and deletions. \begin{algorithm}[t] \caption{\textsc{Initialization}}\label{alg:rms:init} \Input{Query $\mathtt{RMS}(k,r)$, initial database $P_0$, parameters $\varepsilon \in (0,1)$ and $M \in \mathbb{Z}^+$ ($M>r$)} \Output{Result $Q_0$ of $\mathtt{RMS}(k,r)$ on $P_0$} Draw $M$ vectors $\{u_i \in \mathbb{U} : i \in [1,M]\}$ where the first $d$ are the standard basis of $\mathbb{R}^d_+$ and the remaining are uniformly sampled from $\mathbb{U}$\; Compute $\Phi_{k,\varepsilon}(u_i,P_0)$ of every $u_i$ where $i \in [1,M]$\; \label{ln:rms:init:topk} $L \gets r$, $H \gets M$, $m \gets (L+H)/2$\;\label{ln:rms:search:s} \While{$\mathtt{true}$}{ \ForEach{$p \in P_0$\label{ln:rms:set:s}}{ $S(p) \gets \{u_i \,:\, i \in [1,m] \wedge p \in \Phi_{k,\varepsilon}(u_i,P_0) \}$\; } $\Sigma = (\mathcal{U},\mathcal{S})$ where $\mathcal{U}=\{u_i : i \in [1,m]\}$ and $\mathcal{S}=\{S(p) : p \in P_0\})$\;\label{ln:rms:set:t} $\mathcal{C} \gets$ \textsc{Greedy}$(\Sigma)$\; \uIf{$|\mathcal{C}| < r$}{ $L \gets m+1$, $m \gets (L+H)/2$\; } \uElseIf{$|\mathcal{C}| > r$}{ $H \gets m-1$, $m \gets (L+H)/2$\; } \ElseIf{$|\mathcal{C}| = r$ or $m = M$}{ \textbf{break}\;\label{ln:rms:search:t} } } \Return{$Q_0 \gets \{ p \in P_0 \,:\, S(p) \in \mathcal{C} \}$}\; \label{ln:rms:init:return} \end{algorithm} \noindent\textbf{Initialization:} We first present how FD-RMS computes an initial result $Q_0$ for $\mathtt{RMS}(k,r)$ on $P_0$ from scratch in Algorithm~\ref{alg:rms:init}. There are two parameters in FD-RMS: the approximation factor of top-$k$ results $\varepsilon$ and the upper bound of sample size $M$. The lower bound of sample size is set to $r$ because we can always find a set-cover solution of size equal to the size of the universe (i.e., $m$ in FD-RMS). First of all, it draws $M$ utility vectors $\{u_1,\ldots,u_M\}$, where the first $d$ vectors are the standard basis of $\mathbb{R}^d_+$ and the remaining are uniformly sampled from $\mathbb{U}$, and computes the $\varepsilon$-approximate top-$k$ result of each vector. Subsequently, it finds an appropriate $m \in [r,M]$ so that the size of the set-cover solution on the set system $\Sigma$ built on $\mathcal{U} = \{u_1,\ldots,u_m\}$ is exactly $r$. The detailed procedure is as presented in Lines~\ref{ln:rms:search:s}--\ref{ln:rms:search:t}. Specifically, it performs a binary search on range $[r,M]$ to determine the value of $m$. For a given $m$, it first constructs a set system $\Sigma$ according to Lines~\ref{ln:rms:set:s}--\ref{ln:rms:set:t}. Next, it runs \textsc{Greedy} in Algorithm~\ref{alg:set:cover} to compute a set-cover solution $\mathcal{C}$ on $\Sigma$. After that, if $|\mathcal{C}| \neq r$ and $m < M$, it will refresh the value of $m$ and rerun the above procedures; Otherwise, $m$ is determined and the current set-cover solution $\mathcal{C}$ will be used to compute $Q_0$ for $\mathtt{RMS}(k,r)$. Finally, it returns all the tuples whose corresponding sets are included in $\mathcal{C}$ as the result $Q_0$ for $\mathtt{RMS}(k,r)$ on $P_0$ (Line~\ref{ln:rms:init:return}). \begin{algorithm}[t] \caption{\textsc{Update}}\label{alg:rms:update} \Input{Query $\mathtt{RMS}(k,r)$, database $P_{t-1}$, operation $\Delta_t$, set-cover solution $\mathcal{C}$} \Output{Result $Q_t$ for $\mathtt{RMS}(k,r)$ on $P_t$} Update $P_{t-1}$ to $P_t$ w.r.t.~$\Delta_t$\;\label{ln:update:database} \For{$i \gets 1,\ldots,M$}{ Update $\Phi_{k,\varepsilon}(u_i,P_{t-1})$ to $\Phi_{k,\varepsilon}(u_i,P_{t})$ w.r.t.~$\Delta_t$\;\label{ln:update:topk} } Maintain $\Sigma$ based on $\Phi_{k,\varepsilon}(u_i,P_{t})$\; \label{ln:update:sets} \uIf{$\Delta_t=\langle p,+ \rangle$\label{ln:insert:s}}{ \ForEach{$u \in S(p)$}{ \If{$u \in \mathtt{cov}(S(p'))$ and $u \notin S(p')$}{ Update $\mathcal{C}$ for $\sigma=(u,S(p'),-)$\;\label{ln:insert:t} } } } \ElseIf{$\Delta_t=\langle p,- \rangle$\label{ln:delete:s}}{ Delete $S(p)$ from $\mathcal{C}$ if $S(p) \in \mathcal{C}$\; \ForEach{$u \in \mathtt{cov}(S(p))$}{ Update $\mathcal{C}$ for $\sigma=(u,S(p),-)$\;\label{ln:delete:t} } } \If{$|\mathcal{C}| \neq r$}{ $m, \mathcal{C} \gets$ \textsc{UpdateM}$(\Sigma)$\; } \Return{$Q_t \gets \{ p \in P_t \,:\, S(p) \in \mathcal{C} \}$}\; \end{algorithm} \begin{figure*}[t] \centering \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=\textwidth]{example-dataset.pdf} \caption{Dataset}\label{fig:example:database} \end{subfigure} \hfill \begin{subfigure}{0.225\textwidth} \centering \includegraphics[width=\textwidth]{example-P0.pdf} \caption{Initial construction}\label{fig:example:fdrms:P0} \end{subfigure} \hfill \begin{subfigure}{0.225\textwidth} \centering \includegraphics[width=\textwidth]{example-P1.pdf} \caption{Add tuple $p_9$}\label{fig:example:fdrms:P1} \end{subfigure} \hfill \begin{subfigure}{0.225\textwidth} \centering \includegraphics[width=\textwidth]{example-P2.pdf} \caption{Delete tuple $p_1$}\label{fig:example:fdrms:P2} \end{subfigure} \caption{An example of using FD-RMS to process a $k$-RMS with $k=1$ and $r=3$} \label{fig:example:fdrms} \end{figure*} \noindent\textbf{Update:} The procedure of updating the result of $\mathtt{RMS}(k,r)$ w.r.t.~$\Delta_t$ is shown in Algorithm~\ref{alg:rms:update}. First, it updates the database from $P_{t-1}$ to $P_t$ and the approximate top-$k$ result from $\Phi_{k,\varepsilon}(u_i,P_{t-1})$ to $\Phi_{k,\varepsilon}(u_i,P_t)$ for each $u_i$ w.r.t.~$\Delta_t$ (Lines~\ref{ln:update:database}--\ref{ln:update:topk}). Then, it also maintains the set system $\Sigma$ according to the changes in approximate top-$k$ results (Line~\ref{ln:update:sets}). Next, it updates the set-cover solution $\mathcal{C}$ for the changes in $\Sigma$ as follows. \begin{itemize} \item \textbf{Insertion:} The procedure of updating $\mathcal{C}$ w.r.t.~an insertion $\Delta_t=\langle p,+ \rangle$ is presented in Lines~\ref{ln:insert:s}--\ref{ln:insert:t}. The changes in top-$k$ results lead to two updates in $\Sigma$: (1) the insertion of $S(p)$ to $\mathcal{S}$ and (2) a series of deletions each of which represents a tuple $p'$ is deleted from $\Phi_{k,\varepsilon}(u,P_t)$ due to the insertion of $p$. For each deletion, it needs to check whether $u$ is previously assigned to $S(p')$. If so, it will update $\mathcal{C}$ by reassigning $u$ to a new set according to Algorithm~\ref{alg:set:cover} because $u$ has been deleted from $S(p')$. \item \textbf{Deletion:} The procedure of updating $\mathcal{C}$ w.r.t.~a deletion $ \Delta_t=\langle p,- \rangle $ is shown in Lines~\ref{ln:delete:s}--\ref{ln:delete:t}. In contrast to an insertion, the deletion of $p$ leads to the removal of $S(p)$ from $\mathcal{S}$ and a series of insertions. Thus, it must delete $S(p)$ from $\mathcal{C}$. Next, it will reassign each $u \in \mathtt{cov}(S(p))$ to a new set according to Algorithm~\ref{alg:set:cover}. \end{itemize} Then, it checks whether the size of $\mathcal{C}$ is still $r$. If not, it will update the sample size $m$ and the universe $\mathcal{U}$ so that the set-cover solution $\mathcal{C}$ consists of $r$ sets. The procedure of updating $m$ and $\mathcal{U}$ as well as maintaining $\mathcal{C}$ on the updated $\mathcal{U}$ is shown in Algorithm~\ref{alg:rms:update:m}. When $|\mathcal{C}|<r$, it will add new utility vectors from $u_{m+1}$, and so on, to the universe and maintain $\mathcal{C}$ until $|\mathcal{C}|=r$ or $m=M$. On the contrary, if $|\mathcal{C}| > r$, it will drop existing utility vectors from $u_{m}$, and so on, from the universe and maintain $\mathcal{C}$ until $|\mathcal{C}|=r$. Finally, the updated $m$ and $\mathcal{C}$ are returned. After all above procedures, it also returns $Q_t$ corresponding to the set-cover solution $\mathcal{C}$ on the updated $\Sigma$ as the result of $\mathtt{RMS}(k,r)$ on $P_t$. \begin{algorithm}[t] \caption{\textsc{UpdateM}$(\Sigma)$}\label{alg:rms:update:m} \Output{Updated sample size $m$ and solution $\mathcal{C}$ on $\Sigma$} \uIf{$|\mathcal{C}| < r$}{ \While{$m < M$ and $|\mathcal{C}| < r$}{ $m \gets m+1$, $\mathcal{U} \gets \mathcal{U} \cup \{u_m\}$\; \ForEach{$p \in \Phi_{k,\varepsilon}(u_m,P_t)$}{ $S(p) \gets S(p) \cup \{u_m\}$\; } Update $\mathcal{C}$ for $\sigma=(u_m,\mathcal{U},+)$\; } } \ElseIf{$|\mathcal{C}| > r$}{ \While{$|\mathcal{C}| > r$}{ $\mathcal{U} \gets \mathcal{U} \setminus \{u_m\}$\; \ForEach{$p \in \Phi_{k,\varepsilon}(u_m,P_t)$}{ $S(p) \gets S(p) \setminus \{u_m\}$\; } Update $\mathcal{C}$ for $\sigma=(u_m,\mathcal{U},-)$\; $m \gets m-1$\; } } \Return{$m, \mathcal{C}$}\; \end{algorithm} \begin{example} Fig.~\ref{fig:example:fdrms} illustrates an example of using FD-RMS to process a $k$-RMS with $k=1$ and $r=3$. Here, we set $\varepsilon=0.002$ and $M=9$. In Fig.~\ref{fig:example:fdrms:P0}, we show how to compute $Q_0$ for $\mathtt{RMS}(1,3)$ on $P_0=\{p_1,\ldots,p_8\}$. It first uses $m=(3+9)/2=6$ and runs \textnormal{\textsc{Greedy}} to get a set-cover solution $\mathcal{C}=\{S(p_1), S(p_2), S(p_4)\}$. Since $|\mathcal{C}|=3$, it does not change $m$ anymore and returns $Q_0=\{p_1,p_2,p_4\}$ for $\mathtt{RMS}(1,3)$ on $P_0$. Then, the result of FD-RMS after the update procedures for~$\Delta_1 = \langle p_9,+ \rangle$ as Algorithm~\ref{alg:rms:update} is shown in Fig.~\ref{fig:example:fdrms:P1}. For $\mathtt{RMS}(1,3)$ on $P_1=\{p_1,\ldots,p_9\}$, the result $Q_1$ is updated to $\{p_1,p_4,p_9\}$. Finally, after the update procedures for $ \Delta_2 = \langle p_1,- \rangle $, as shown in Fig.~\ref{fig:example:fdrms:P2}, $m$ is updated to $4$ and the result $Q_2$ for $\mathtt{RMS}(1,3)$ on $P_2$ is $\{p_4,p_7,p_9\}$. \end{example} \noindent\textbf{Theoretical Bound:} The theoretical bound of FD-RMS is analyzed as follows. First of all, we need to verify the set-cover solution $\mathcal{C}$ maintained by Algorithms~\ref{alg:rms:init}--\ref{alg:rms:update:m} is always stable. According to Lemma~\ref{lm:stability}, it is guaranteed that the set-cover solution $\mathcal{C}$ returned by Algorithm~\ref{alg:rms:init} is stable. Then, we need to show it remains stable after the update procedures of Algorithms~\ref{alg:rms:update} and~\ref{alg:rms:update:m}. In fact, both algorithms use Algorithm~\ref{alg:set:cover} to maintain the set-cover solution $\mathcal{C}$. Hence, the stability of $\mathcal{C}$ can be guaranteed by Lemma~\ref{lm:termination} since \textsc{Stabilize} is always called after every update in Algorithm~\ref{alg:set:cover}. Next, we indicate the relationship between the result of $k$-RMS and the \emph{set-cover} solution and provide the bound on the maximum-$k$ regret ratio of $Q_{t}$ returned by FD-RMS on $P_t$. \begin{theorem}\label{thm:rms:ratio} The result $Q_t$ returned by FD-RMS is a $\big(k,O(\varepsilon^{*}_{k,r'}+\delta)\big)$-regret set of $P_t$ with high probability where $r'=O(\frac{r}{\log{m}})$ and $\delta=O(m^{-\frac{1}{d}})$. \end{theorem} \begin{proof} Given a parameter $\delta > 0$, a $\delta$-net~\cite{DBLP:conf/wea/AgarwalKSS17} of $\mathbb{U}$ is a finite set $U \subset \mathbb{U}$ where there exists a vector $\overline{u}$ with $\| u-\overline{u} \| \leq \delta$ for any $u \in \mathbb{U}$. Since a random set of $O(\frac{1}{\delta^{d-1}}\log\frac{1}{\delta})$ vectors in $\mathbb{U}$ is a $\delta$-net with probability at least $\frac{1}{2}$~\cite{DBLP:conf/wea/AgarwalKSS17}, one can generate a $\delta$-net of size $O(\frac{1}{\delta^{d-1}}\log\frac{1}{\delta})$ with high probability by random sampling from $\mathbb{U}$ in $O(1)$ repeated trials. Let $B$ be the standard basis of $\mathbb{R}^d_+$ and $U$ be a $\delta$-net of $\mathbb{U}$ where $B=\{u_1,\ldots,u_d\} \subset U$. Since $p \in P_t$ is scaled to $p[i] \leq 1$ for $i \in [1,d]$, we have $\| p \| \leq \sqrt{d}$. According to the definition of $\delta$-net, there exists a vector $\overline{u} \in U$ such that $\| \overline{u} - u \| \leq \delta$ for every $u \in \mathbb{U}$. Hence, for any tuple $p \in P_t$, \begin{equation}\label{eq:1} | \langle \overline{u},p \rangle - \langle u,p \rangle | = | \langle \overline{u} - u,p \rangle | \leq \| \overline{u} - u \| \cdot \| p \| \leq \delta \cdot \sqrt{d} \end{equation} Moreover, as $Q_{t}$ corresponds to a set-cover solution $\mathcal{C}$ on $\Sigma$, there exists a tuple $q \in Q_{t}$ such that $\langle \overline{u},q \rangle \geq (1-\varepsilon) \cdot \omega_{k}(\overline{u},P_t)$ for any $\overline{u} \in U$. We first consider a basis vector $u_i \in U$ for some $i \in [1,d]$. We have $\omega(u_i,Q_t) \geq (1-\varepsilon) \cdot \omega_{k}(u_i,P_t)$ and thus $ \omega(u_i,Q_t) \geq (1-\varepsilon) \cdot c $ where $c = \min_{i \in [1,d]} \omega_{k}(u_i,P_t)$. Since $\| u \| = 1$, there must exist some $i$ with $u[i] \geq \frac{1}{\sqrt{d}}$ for any $u \in \mathbb{U}$. Therefore, it holds that $\omega(u,Q_{t}) \geq \omega(u_i,Q_{t}) \cdot \frac{1}{\sqrt{d}} \geq (1-\varepsilon)\cdot\frac{c}{\sqrt{d}}$ for any $u \in \mathbb{U}$. Next, we discuss two cases for $u \in \mathbb{U}$ separately. \begin{itemize} \item \textbf{Case 1 ($\omega_k(u,P_t) \leq \frac{c}{\sqrt{d}}$):} In this case, there always exists $q \in Q_{t}$ such that $\langle u,q \rangle \geq (1-\varepsilon)\cdot\omega_k(u,P_t)$. \item \textbf{Case 2 ($\omega_k(u,P_t) > \frac{c}{\sqrt{d}}$):} Let $\overline{u} \in U$ be the utility vector such that $\| \overline{u} - u \| \leq \delta$. Let $\Phi_{k}(u,P_t)=\{p_1,\ldots,p_k\}$ be the top-$k$ results of $u$ on $P_t$. According to Equation~\ref{eq:1}, we have $\langle \overline{u},p_i \rangle \geq \langle u,p_i \rangle - \delta\cdot\sqrt{d}$ for all $i \in [1,k]$ and thus $\langle \overline{u},p_i \rangle \geq \omega_{k}(u,P_t) - \delta\cdot\sqrt{d}$. Thus, there exists $k$ tuples in $P_t$ with scores at least $\omega_{k}(u,P_t) - \delta\cdot\sqrt{d}$ for $\overline{u}$. We can acquire $\omega_{k}(\overline{u},P_t) \geq \omega_{k}(u,P_t) - \delta\cdot\sqrt{d}$. Therefore, there exists $q \in Q_{t}$ such that \begin{align*} \langle u,q \rangle & \geq \langle \overline{u},q \rangle - \delta\cdot\sqrt{d} \geq (1-\varepsilon) \cdot \omega_k(\overline{u},P_t) - \delta\cdot\sqrt{d} \\ & \geq (1-\varepsilon) \cdot \big(\omega_{k}(u,P_t) - \delta\cdot\sqrt{d}\big) - \delta\cdot\sqrt{d} \\ & \geq \big(1-\varepsilon-\frac{(1-\varepsilon)d\delta}{c}-\frac{d\delta}{c}\big) \cdot \omega_{k}(u,P_t) \\ & \geq (1-\varepsilon-\frac{2d\delta}{c})\cdot\omega_{k}(u,P_t) \end{align*} \end{itemize} Considering both cases, we have $\omega(u,Q_t) \geq (1-\varepsilon-\frac{2d\delta}{c})\cdot\omega_{k}(u,P_t)$ for any $u \in \mathbb{U}$ and thus $\mathtt{mrr}_k(Q_{t})$ over $P_t$ is at most $\varepsilon+\frac{2d\delta}{c}$. In all of our experiments, the value of $c$ is always between $0.5$ and $1$, and thus we regard $c$ as a constant in this proof. Therefore, $Q_t$ is a $\big(k,O(\varepsilon+\delta)\big)$-regret set of $P_t$ with high probability for any $c,d=O(1)$. Moreover, since FD-RMS uses $m$ utility vectors including $B$ to compute $Q_t$ and $m=O(\frac{1}{\delta^{d-1}}\log\frac{1}{\delta})$, we can acquire $\delta=O(m^{-\frac{1}{d}})$. Finally, because any $(k,\varepsilon)$-regret set of $P_t$ corresponds to a set-cover solution on $\Sigma$ (otherwise, the regret ratio is larger than $\varepsilon$ for some utility vector) and the size of the optimal set-cover solution on $\Sigma$ is $O(\frac{r}{\log{m}})$ according to Theorem~\ref{thm:approx:ratio}, the maximum $k$-regret ratio of any size-$r'$ subset of $P_t$ is at least $\varepsilon$ where $r'=O(\frac{r}{\log{m}})$, i.e., $\varepsilon^{*}_{k,r'} \geq \varepsilon$. Therefore, we conclude that $Q_t$ is a $\big(k,O(\varepsilon^{*}_{k,r'}+\delta)\big)$-regret set of $P_t$ with high probability. \end{proof} Finally, the upper bound of the maximum $k$-regret ratio of $Q_{t}$ returned by FD-RMS on $P_t$ is analyzed in the following corollary derived from the result of Theorem~\ref{thm:rms:ratio}. \begin{corollary}\label{col:rms:bound} It satisfies that $\mathtt{mrr}_k(Q_{t}) = O(r^{-\frac{1}{d}})$ with high probability if we assume $\varepsilon = O(m^{-\frac{1}{d}})$. \end{corollary} \begin{proof} As indicated in the proof of Theorem~\ref{thm:rms:ratio}, $\mathcal{U}=\{u_1,u_2,$ $\ldots,u_{m}\}$ is a $\delta$-net of $\mathbb{U}$ where $\delta=O(m^{-\frac{1}{d}})$ with high probability. Moreover, we have $\mathtt{mrr}_k(Q_{t}) = O(\varepsilon + \delta)$ and thus $\mathtt{mrr}_k(Q_{t}) = O(m^{-\frac{1}{d}})$ if $\varepsilon = O(m^{-\frac{1}{d}})$. In addition, at any time, $\mathcal{U}$ must have at least $r$ utility vectors, i.e., $m \geq r$. Thus, we have $\mathtt{mrr}_k(Q_{t}) = O(r^{-\frac{1}{d}})$ since $m^{-\frac{1}{d}} \leq r^{-\frac{1}{d}}$ for any $d>1$ and conclude the proof. \end{proof} Since $\varepsilon$ is tunable in FD-RMS, by trying different values of $\varepsilon$, we can always find an appropriate one such that $\varepsilon = O(m^{-\frac{1}{d}})$. Hence, from Corollary~\ref{col:rms:bound}, we show that the upper bound of FD-RMS is slightly higher than that of \textsc{Cube}~\cite{DBLP:journals/pvldb/NanongkaiSLLX10} and \textsc{Sphere}~\cite{DBLP:conf/sigmod/XieW0LL18} (i.e., $O(r^{-\frac{1}{d-1}}$)) under a mild assumption. \noindent\textbf{Complexity Analysis:} First, we use tree-based methods to maintain the approximate top-$k$ results for FD-RMS (see Section~\ref{subsec:impl} for details). Here, the time complexity of each top-$k$ query is $O(n_0)$ where $n_0=|P_0|$ because the size of $\varepsilon$-approximate top-$k$ tuples can be $O(n_0)$. Hence, it takes $O(M \cdot n_0)$ time to compute the top-$k$ results. Then, \textsc{Greedy} runs $O(r)$ iterations to get a set-cover solution. At each iteration, it evaluates $O(n_0)$ sets to find $S^*$ in Line~\ref{ln:cover:max} of Algorithm~\ref{alg:set:cover}. Thus, the time complexity of \textsc{Greedy} is $O(r \cdot n_0)$. FD-RMS calls \textsc{Greedy} $O(\log{M})$ times to determine the value of $m$. Therefore, the time complexity of computing $Q_{0}$ on $P_0$ is $O\big((M + r\log{M}) \cdot n_0\big)$. In Algorithm~\ref{alg:rms:update}, the time complexity of updating the top-$k$ results and set system $\Sigma$ is $O\big(\mathtt{u}(\Delta_t)\cdot n_t \big)$ where $\mathtt{u}(\Delta_t)$ is the number of utility vectors whose top-$k$ results are changed by $\Delta_t$. Then, the maximum number of reassignments in cover sets is $|S(p)|$ for $\Delta_t$, which is bounded by $O(\mathtt{u}(\Delta_t))$. In addition, the time complexity of \textsc{Stabilize} is $O(m \log{m})$ according to Lemma~\ref{lm:termination}. Moreover, the maximum difference between the old and new values of $m$ is bounded by $O(m)$. Hence, the total time complexity of updating $Q_t$ w.r.t.~$\Delta_t$ is $O\big(\mathtt{u}(\Delta_t) \cdot n_t + m^2 \log{m}\big)$. \subsection{Implementation Issues}\label{subsec:impl} \noindent\textbf{Index Structures:} As indicated in Line~\ref{ln:rms:init:topk} of Algorithm~\ref{alg:rms:init} and Line~\ref{ln:update:topk} of Algorithm~\ref{alg:rms:update}, FD-RMS should compute the $\varepsilon$-approximate top-$k$ result of each $u_i$ ($i \in [1,M]$) on $P_0$ and update it w.r.t.~$\Delta_t$. Here, we elaborate on our implementation for top-$k$ maintenance. In order to process a large number of (approximate) top-$k$ queries with frequent updates in the database, we implement a \emph{dual-tree}~\cite{DBLP:conf/kdd/RamG12,DBLP:conf/sigmod/YuAY12,DBLP:conf/sdm/CurtinGR13} that comprises a tuple index $\mathtt{TI}$ and a utility index $\mathtt{UI}$. The goal of $\mathtt{TI}$ is to efficiently retrieve the $\varepsilon$-approximate top-$k$ result $\Phi_{k,\varepsilon}(u,P_t)$ of any utility vector $u$ on the up-to-date $P_t$. Hence, any space-partitioning index, e.g., \emph{k-d tree}~\cite{DBLP:journals/cacm/Bentley75} and \emph{Quadtree}~\cite{DBLP:journals/acta/FinkelB74}, can serve as $\mathtt{TI}$ for top-$k$ query processing. In practice, we use \emph{k-d tree} as $\mathtt{TI}$. We adopt the scheme of~\cite{DBLP:conf/recsys/BachrachFGKKNP14} to transform a top-$k$ query in $\mathbb{R}^d$ into a $k$NN query in $\mathbb{R}^{d+1}$. Then, we implement the standard top-down methods to construct $\mathtt{TI}$ on $P_0$ and update it w.r.t.~$\Delta_t$. The branch-and-bound algorithm is used for top-$k$ queries on $\mathtt{TI}$. The goal of $\mathtt{UI}$ is to cluster the sampled utility vectors so as to efficiently find each vector whose $\varepsilon$-approximate top-$k$ result is updated by~$\Delta_t$. Since the top-$k$ results of linear functions are merely determined by directions, the basic idea of $\mathtt{UI}$ is to cluster the utilities with high \emph{cosine similarities} together. Therefore, we adopt an angular-based binary space partitioning tree called \emph{cone tree}~\cite{DBLP:conf/kdd/RamG12} as $\mathtt{UI}$. We generally follow Algorithms 8--9 in~\cite{DBLP:conf/kdd/RamG12} to build $\mathtt{UI}$ for $\{u_1,\ldots,u_M\}$. We implement a top-down approach based on Section 3.2 of~\cite{DBLP:conf/sigmod/YuAY12} to update the top-$k$ results affected by~$\Delta_t$. \noindent\textbf{Parameter Tuning:} Now, we discuss how to specify the values of $\varepsilon$, i.e., the approximation factor of top-$k$ queries, and $M$, i.e., the upper bound of $m$, in FD-RMS. In general, the value of $\varepsilon$ has direct effect on $m$ as well as the efficiency and quality of results of FD-RMS. In particular, if $\varepsilon$ is larger, the $\varepsilon$-approximate top-$k$ result of each utility vector will include more tuples and the set system built on top-$k$ results will be more dense. As a result, to guarantee the result size to be exactly $r$, FD-RMS will use more utility vectors (i.e., a larger $m$) for a larger $\varepsilon$. Therefore, a smaller $\varepsilon$ leads to higher efficiency and lower solution quality due to smaller $m$ and larger $\delta$, and vice versa. In our implementation, we use a trial-and-error method to find appropriate values of $\varepsilon$ and $M$: For each query $\mathtt{RMS}(k,r)$ on a dataset, we test different values of $\varepsilon$ chosen from $[0.0001, \ldots, 0.1024]$ and, for each value of $\varepsilon$, $M$ is set to the smallest one chosen from $[2^{10},\ldots,2^{20}]$ that always guarantees $m < M$. If the result size is still smaller than $r$ when $m=M=2^{20}$, we will not use larger $M$ anymore due to efficiency issue. The values of $\varepsilon$ and $M$ that strike the best balance between efficiency and quality of results will be used. In Fig.~\ref{fig:eps}, we present how the value of $\varepsilon$ affects the performance of FD-RMS empirically. \section{Related Work} \label{sec:related:work} There have been extensive studies on the $k$-regret minimizing set ($k$-RMS) problem (see~\cite{DBLP:journals/vldb/XieWL20} for a survey). Nanongkai et al.~\cite{DBLP:journals/pvldb/NanongkaiSLLX10} first introduced the notions of \emph{maximum regret ratio} and \emph{$r$-regret query} (i.e., maximum $1$-regret ratio and $1$-RMS in this paper). They proposed the \textsc{Cube} algorithm to provide an upper-bound guarantee for the maximum regret ratio of the optimal solution of $1$-RMS. They also proposed the \textsc{Greedy} heuristic for $1$-RMS, which always picked a tuple that maximally reduced the maximum regret ratio at each iteration. Peng and Wong~\cite{DBLP:conf/icde/PengW14} proposed the \textsc{GeoGreedy} algorithm to improve the efficiency of \textsc{Greedy} by utilizing the geometric properties of $1$-RMS. Asudeh et al.~\cite{DBLP:conf/sigmod/AsudehN0D17} proposed two discretized matrix min-max (DMM) based algorithms for $1$-RMS. Xie et al.~\cite{DBLP:conf/sigmod/XieW0LL18} designed the \textsc{Sphere} algorithm for $1$-RMS based on the notion of $\varepsilon$-kernel~\cite{DBLP:journals/jacm/AgarwalHV04}. Shetiya et al.~\cite{Shetiya2019} proposed a unified algorithm called URM based on $k$-\textsc{Medoid} clustering for $l^p$-norm RMS problems, of which $1$-RMS was a special case when $p=\infty$. The aforementioned algorithms cannot be used for $k$-RMS when $k > 1$. Chester et al.~\cite{DBLP:journals/pvldb/ChesterTVW14} first extended the notion of $1$-RMS to $k$-RMS. They also proposed a randomized \textsc{Greedy}$^*$ algorithm that extended the \textsc{Greedy} heuristic to support $k$-RMS when $k > 1$. The min-size version of $k$-RMS that returned the minimum subset whose maximum $k$-regret ratio was at most $\varepsilon$ for a given $\varepsilon \in (0,1)$ was studied in~\cite{DBLP:conf/wea/AgarwalKSS17,DBLP:conf/alenex/KumarS18}. They proposed two algorithms for min-size $k$-RMS based on the notion of $\varepsilon$-kernel~\cite{DBLP:journals/jacm/AgarwalHV04} and hitting-set, respectively. However, all above algorithms are designed for the static setting and very inefficient to process database updates. To the best of our knowledge, FD-RMS is the first $k$-RMS algorithm that is optimized for the fully dynamic setting and efficiently maintains the result for dynamic updates. Different variations of regret minimizing set problems were also studied recently. The $1$-RMS problem with nonlinear utility functions were studied in~\cite{DBLP:journals/pvldb/FaulknerBL15,DBLP:journals/tods/QiZSY18,DBLP:conf/aaai/SomaY17a}. Specifically, they generalized the class of utility functions to \emph{convex functions}~\cite{DBLP:journals/pvldb/FaulknerBL15}, \emph{multiplicative functions}~\cite{DBLP:journals/tods/QiZSY18}, and \emph{submodular functions}~\cite{DBLP:conf/aaai/SomaY17a}, respectively. Asudeh et al.~\cite{DBLP:conf/sigmod/AsudehN00J19} proposed the rank-regret representative (RRR) problem. The difference between RRR and RMS is that the regret in RRR is defined by ranking while the regret in RMS is defined by score. Several studies~\cite{DBLP:conf/icde/ZeighamiW19,DBLP:conf/aaai/StorandtF19,Shetiya2019} investigated the \emph{average regret minimization} (ARM) problem. Instead of minimizing the maximum regret ratio, ARM returns a subset of $r$ tuples such that the average regret of all possible users is minimized. The problem of \emph{interactive regret minimization} that aimed to enhance the regret minimization problem with user interactions was studied in~\cite{DBLP:conf/sigmod/NanongkaiLSM12,DBLP:conf/sigmod/XieWL19}. Xie et al.~\cite{Xie2020} proposed a variation of min-size RMS called $\alpha$-happiness query. Since these variations have different formulations from the original $k$-RMS problem, the algorithms proposed for them cannot be directly applied to the $k$-RMS problem. Moreover, these algorithms are still proposed for the static setting without considering database updates. \section{Preliminaries} \label{sec:definition} In this section, we formally define the problem we study in this paper. We first introduce the notion of maximum $k$-regret ratio. Then, we formulate the $k$-regret minimizing set ($k$-RMS) problem in a fully dynamic setting. Finally, we present the challenges of solving fully-dynamic $k$-RMS. \begin{figure} \centering \includegraphics[width=.32\textwidth]{data.pdf} \caption{A two-dimensional database of 8 tuples.} \label{fig:database} \end{figure} \subsection{Maximum K-Regret Ratio} Let us consider a database $P$ where each tuple $p \in P$ has $d$ nonnegative numerical attributes $p[1],\ldots,p[d]$ and is represented as a point in the nonnegative orthant $\mathbb{R}_+^d$. A user's preference is denoted by a utility function $f:\mathbb{R}_+^d \rightarrow \mathbb{R}^+$ that assigns a positive score $f(p)$ to each tuple $p$. Following~\cite{DBLP:journals/pvldb/NanongkaiSLLX10,DBLP:conf/icde/PengW14,DBLP:journals/pvldb/ChesterTVW14,DBLP:conf/sigmod/AsudehN0D17,DBLP:conf/sigmod/XieW0LL18}, we restrict the class of utility functions to \emph{linear functions}. A function $f$ is linear if and only if there exists a $d$-dimensional vector $u=(u[1],\ldots,u[d]) \in \mathbb{R}_+^d$ such that $f(p)=\langle u,p \rangle =\sum_{i=1}^{d} u[i] \cdot p[i]$ for any $p \in \mathbb{R}_+^d$. W.l.o.g., we assume the range of values on each dimension is scaled to $[0,1]$ and any utility vector is normalized to be a unit\footnote{The normalization does not affect our results because the maximum $k$-regret ratio is \emph{scale-invariant}~\cite{DBLP:journals/pvldb/NanongkaiSLLX10}.}, i.e., $\| u \|=1$. Intuitively, the class of linear functions corresponds to the nonnegative orthant of $d$-dimensional unit sphere $ \mathbb{U}=\{ u \in \mathbb{R}_+^d \,:\, \lVert u \rVert=1 \} $. We use $\varphi_j(u,P)$ to denote the tuple $p \in P$ with the $j$\textsuperscript{th}-largest score w.r.t.~vector $u$ and $\omega_j(u,P)$ to denote its score. Note that multiple tuples may have the same score w.r.t.~$u$ and any consistent rule can be adopted to break ties. For brevity, we drop the subscript $j$ from the above notations when $j=1$, i.e., $\varphi(u,P)=\arg\max_{p \in P} \langle u,p \rangle$ and $\omega(u,P)=\max_{p \in P} \langle u,p \rangle$. The top-$k$ tuples in $P$ w.r.t.~$u$ is represented as $\Phi_{k}(u,P)=\{\varphi_{j}(u,P) : 1 \leq j \leq k\}$. Given a real number $\varepsilon \in (0,1)$, the $\varepsilon$-approximate top-$k$ tuples in $P$ w.r.t.~$u$ is denoted as $\Phi_{k,\varepsilon}(u,P)=\{p \in P \,:\, \langle u,p \rangle \geq (1-\varepsilon)\cdot\omega_{k}(u,P)\}$, i.e., the set of tuples whose scores are at least $(1-\varepsilon)\cdot\omega_{k}(u,P)$. For a subset $Q \subseteq P$ and an integer $k \geq 1$, we define the \emph{$k$-regret ratio} of $Q$ over $P$ for a utility vector $u$ by $\mathtt{rr}_k(u,Q)=\max\big(0,1-\frac{\omega(u,Q)}{\omega_{k}(u,P)}\big)$, i.e., the relative loss of replacing the $k$\textsuperscript{th}-ranked tuple in $P$ by the top-ranked tuple in $Q$. Since it is required to consider the preferences of all possible users, our goal is to find a subset whose $k$-regret ratio is small for an arbitrary utility vector. Therefore, we define the \emph{maximum $k$-regret ratio} of $Q$ over $P$ by $\mathtt{mrr}_k(Q)=\max_{u \in \mathbb{U}}\mathtt{rr}_k(u,Q)$. Intuitively, $\mathtt{mrr}_k(Q)$ measures how well the top-ranked tuple of $Q$ approximates the $k$\textsuperscript{th}-ranked tuple of $P$ in the worst case. For a real number $\varepsilon \in (0,1)$, $Q$ is said to be a $(k,\varepsilon)$-regret set of $P$ iff $\mathtt{mrr}_k(Q) \leq \varepsilon$, or equivalently, $\varphi(u,Q) \in \Phi_{k,\varepsilon}(u,P)$ for any $u \in \mathbb{U}$. By definition, it holds that $\mathtt{mrr}_k(Q) \in [0,1]$. \begin{example} Fig.~\ref{fig:database} illustrates a database $P$ in $\mathbb{R}^2_+$ with $8$ tuples $\{p_1,\ldots,p_8\}$. For utility vectors $u_1=(0.42,0.91)$ and $u_2=(0.91,0.42)$, their top-$2$ results are $\Phi_2(u_1,P)=\{p_1,p_2\}$ and $\Phi_2(u_2,P)=\{p_2,p_4\}$, respectively. Given a subset $Q_1=\{p_3,p_4\}$ of $P$, $\mathtt{rr}_2(u_1,Q_1)=1-\frac{0.749}{0.98} \approx 0.236$ as $\omega(u_1,Q_1)=\langle u_1,p_3 \rangle=0.749$ and $\omega_2(u_1,P)=\langle u_1,p_2 \rangle=0.98$. Furthermore, $\mathtt{mrr}_2(Q_1) \approx 0.444$ because $\mathtt{rr}_2(u,Q_1)$ is the maximum when $u=(0.0,1.0)$ with $\mathtt{rr}_2(u,Q_1) = 1-\frac{5}{9} \approx 0.444$. Finally, $Q_2=\{p_1,p_2,p_4\}$ is a $(2,0)$-regret set of $P$ since $\mathtt{mrr}_2(Q_2)=0$. \end{example} \subsection{K-Regret Minimizing Set} Based on the notion of \emph{maximum $k$-regret ratio}, we can formally define the $k$-\emph{regret minimizing set} ($k$-RMS) problem in the following. \begin{definition}[$k$-Regret Minimizing Set]\label{def:k-rms} Given a database $P \subset \mathbb{R}_+^d$ and a size constraint $r \in \mathbb{Z}^+$ ($r \geq d$), the $k$-regret minimizing set ($k$-RMS) problem returns a subset $Q^{*} \subseteq P$ of at most $r$ tuples with the smallest \emph{maximum $k$-regret ratio}, i.e., $Q^{*}=\arg\min_{Q \subseteq P \,:\, |Q| \leq r} \mathtt{mrr}_k(Q)$. \end{definition} For any given $k$ and $r$, we denote the $k$-RMS problem by $\mathtt{RMS}(k,r)$ and the \emph{maximum $k$-regret ratio} of the optimal result $Q^{*}$ for $\mathtt{RMS}(k,r)$ by $\varepsilon^{*}_{k,r}$. In particular, the $r$-regret query studied in~\cite{DBLP:conf/icde/PengW14,DBLP:conf/sigmod/AsudehN0D17,DBLP:conf/sigmod/XieW0LL18, DBLP:journals/pvldb/NanongkaiSLLX10} is a special case of our $k$-RMS problem when $k=1$, i.e., $1$-RMS. \begin{example} Let us continue with the example in Fig.~\ref{fig:database}. For a query $\mathtt{RMS}(2,2)$ on $P$, we have $Q^*=\{p_1,p_4\}$ with $\varepsilon^*_{2,2}=\mathtt{mrr}_2(Q^*) \approx 0.05$ because $\{p_1,p_4\}$ has the smallest maximum $2$-regret ratio among all size-$2$ subsets of $P$. \end{example} In this paper, we focus on the fully-dynamic $k$-RMS problem. We consider an initial database $P_0$ and a (possibly countably infinite) sequence of operations $\Delta = \langle \Delta_1,\Delta_2,\ldots \rangle$. At each timestamp $t$ ($t \in \mathbb{Z}^+$), the database is updated from $P_{t-1}$ to $P_t$ by performing an operation $\Delta_t$ of one of the following two types: \begin{itemize} \item \textbf{Tuple insertion} $\Delta_t=\langle p,+ \rangle$: add a new tuple $p$ to $P_{t-1}$, i.e., $P_t \gets P_{t-1}\cup\{p\}$; \item \textbf{Tuple deletion} $\Delta_t=\langle p,- \rangle$: delete an existing tuple $p$ from $P_{t-1}$, i.e., $P_t \gets P_{t-1}\setminus\{p\}$. \end{itemize} Note that the update of a tuple can be processed by a deletion followed by an insertion, and thus is not discussed separately in this paper. Given an initial database $P_0$, a sequence of operations $\Delta$, and a query $\mathtt{RMS}(k,r)$, we aim to keep track of the result $Q^{*}_t$ for $\mathtt{RMS}(k,r)$ on $P_t$ at any time $t$. Fully-dynamic $k$-RMS faces two challenges. First, the $k$-RMS problem is NP-hard~\cite{DBLP:conf/icdt/CaoLWWWWZ17,DBLP:journals/pvldb/ChesterTVW14,DBLP:conf/wea/AgarwalKSS17} for any $d \geq 3$. Thus, the optimal solution of $k$-RMS is intractable for any database with three or more attributes unless P=NP in both static and dynamic settings. Hence, we will focus on maintaining an approximate result of $k$-RMS in this paper. Second, existing $k$-RMS algorithms can only work in the static setting. They must recompute the result from scratch once an operation triggers any update in the skyline (Note that since the result of $k$-RMS is a subset of the skyline~\cite{DBLP:journals/pvldb/NanongkaiSLLX10,DBLP:journals/pvldb/ChesterTVW14}, it remains unchanged for any operation on non-skyline tuples). However, frequent recomputation leads to significant overhead and causes low efficiency on highly dynamic databases. Therefore, we will propose a novel method for fully-dynamic $k$-RMS that can maintain a high-quality result for $\mathtt{RMS}(k,r)$ on a database w.r.t.~any tuple insertion and deletion efficiently. \section{Conclusion}\label{sec:conclusion} In this paper, we studied the problem of maintaining $k$-regret minimizing sets ($k$-RMS) on dynamic datasets with arbitrary insertions and deletions of tuples. We proposed the first fully-dynamic $k$-RMS algorithm called FD-RMS. FD-RMS was based on transforming fully-dynamic $k$-RMS to a dynamic set cover problem, and it could dynamically maintain the result of $k$-RMS with a theoretical guarantee. Extensive experiments on real-world and synthetic datasets confirmed the efficiency, effectiveness, and scalability of FD-RMS compared with existing static approaches to $k$-RMS. For future work, it would be interesting to investigate whether our techniques can be extended to $k$-RMS and related problems on higher dimensions (i.e.,~$d>10$) or with nonlinear utility functions (e.g.,~\cite{DBLP:journals/pvldb/FaulknerBL15,DBLP:journals/tods/QiZSY18,DBLP:conf/aaai/SomaY17a}) in dynamic settings. \section{Experiments}\label{sec:exp} In this section, we evaluate the performance of FD-RMS on real-world and synthetic datasets. We first introduce the experimental setup in Section~\ref{subsec:setup}. Then, we present the experimental results in Section~\ref{subsec:results}. \subsection{Experimental Setup}\label{subsec:setup} \noindent\textbf{Algorithms:} The algorithms compared are listed as follows. \begin{itemize} \item \textsc{Greedy}: the greedy algorithm for $1$-RMS in~\cite{DBLP:journals/pvldb/NanongkaiSLLX10}. \item \textsc{Greedy}$^*$: the randomized greedy algorithm for $k$-RMS when $k>1$ proposed in~\cite{DBLP:journals/pvldb/ChesterTVW14}. \item \textsc{GeoGreedy}: a variation of \textsc{Greedy} for $1$-RMS in~\cite{DBLP:conf/icde/PengW14}. \item DMM-RRMS: a discretized matrix min-max based algorithm for $1$-RMS in~\cite{DBLP:conf/sigmod/AsudehN0D17}. \item $\varepsilon$-\textsc{Kernel}: computing an $\varepsilon$-kernel coreset as the $k$-RMS result~\cite{DBLP:conf/wea/AgarwalKSS17,DBLP:conf/icdt/CaoLWWWWZ17} directly. \item HS: a hitting-set based algorithm for $k$-RMS in~\cite{DBLP:conf/wea/AgarwalKSS17}. \item \textsc{Sphere}: an algorithm that combines $\varepsilon$-\textsc{Kernel} with \textsc{Greedy} for $1$-RMS in~\cite{DBLP:conf/sigmod/XieW0LL18}. \item URM: a $k$-\textsc{medoid} clustering based algorithm for $1$-RMS in~\cite{Shetiya2019}. Following~\cite{Shetiya2019}, we use DMM-RRMS to compute an initial solution for URM. \item FD-RMS: our fully-dynamic $k$-RMS algorithm proposed in Section~\ref{sec:framework}. \end{itemize} The algorithms that only work in two dimensions are not compared. All the above algorithms except FD-RMS and URM\footnote{ The original URM in~\cite{Shetiya2019} is also a static algorithm. We extend URM to support dynamic updates as described in Algorithm~\ref{alg:urm} of Appendix~\ref{appendix:dynamic:urm}.} cannot directly work in a fully dynamic setting. In our experiments, they rerun from scratch to compute the up-to-date $k$-RMS result once the skyline is updated by any insertion or deletion. In addition, the algorithms that are not applicable when $k>1$ are not compared for the experiments with varying $k$. Since $\varepsilon$-\textsc{Kernel} and HS are proposed for min-size $k$-RMS that returns the smallest subset whose maximum $k$-regret ratio is at most $\varepsilon$, we adapt them to our problem by performing a binary search on $\varepsilon$ in the range $(0,1)$ to find the smallest value of $\varepsilon$ that guarantees the result size is at most $r$. Our implementation of FD-RMS and URM is in Java 8 and published on GitHub\footnote{https://github.com/yhwang1990/dynamic-rms}. We used the C++ implementations of baseline algorithms published by authors and followed the default parameter settings as described in the original papers. All the experiments were conducted on a server running Ubuntu 18.04.1 with a 2.3GHz processor and 256GB memory. \noindent\textbf{Datasets:} The datasets we use are listed as follows. \begin{itemize} \item \textbf{BB}\footnote{\url{www.basketball-reference.com}} is a basketball dataset that contains $21,961$ tuples, each of which represents one player/season combination with $5$ attributes such as \emph{points} and \emph{rebounds}. \item \textbf{AQ}\footnote{\url{archive.ics.uci.edu/ml/datasets/Beijing+Multi-Site+Air-Quality+Data}} includes hourly air-pollution and weather data from 12 monitoring sites in Beijing. It has $382,168$ tuples and each tuple has $9$ attributes including the concentrations of $6$ air pollutants like $\text{PM}_{\text{2.5}}$, as well as $3$ meteorological parameters like \emph{temperature}. \item \textbf{CT}\footnote{\url{archive.ics.uci.edu/ml/datasets/covertype}} contains the cartographic data of forest covers in the Roosevelt National Forest of northern Colorado. It has $581,012$ tuples and we choose $8$ numerical attributes, e.g., \emph{elevation} and \emph{slope}, for evaluation. \item \textbf{Movie}\footnote{\url{grouplens.org/datasets/movielens}} is the tag genome dataset published by MovieLens. We extract the relevance scores of $13,176$ movies and $12$ tags for evaluation. Each tuple represents the relevance scores of $12$ tags to a movie. \item \textbf{Indep} is generated as described in~\cite{DBLP:conf/icde/BorzsonyiKS01}. It is a set of uniform points on the unit hypercube where different attributes are independent of each other. \item \textbf{AntiCor} is also generated as described in~\cite{DBLP:conf/icde/BorzsonyiKS01}. It is a set of random points with anti-correlated attributes. \end{itemize} \begin{table}[t] \centering \footnotesize \caption{Statistics of datasets}\label{tbl:stats} \begin{tabular}{|c|c|c|c|c|} \hline \textbf{Dataset} & $n$ & $d$ & \emph{\#skylines} & \emph{updates} (\%) \\ \hline \textbf{BB} & $21,961$ & $5$ & $200$ & $1.07$ \\ \hline \textbf{AQ} & $382,168$ & $9$ & $21,065$ & $5.60$ \\ \hline \textbf{CT} & $581,012$ & $8$ & $77,217$ & $13.4$ \\ \hline \textbf{Movie} & $13,176$ & $12$ & $3,293$ & $26.5$ \\ \hline \textbf{Indep} & $100$K--$1$M & $2$--$10$ & \multicolumn{2}{c|}{see Fig.~\ref{fig:stats}} \\ \hline \textbf{AntiCor} & $100$K--$1$M & $2$--$10$ & \multicolumn{2}{c|}{see Fig.~\ref{fig:stats}} \\ \hline \end{tabular} \end{table} \begin{figure}[t] \centering \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=\textwidth]{legend-dataset.pdf} \end{subfigure} \\ \begin{subfigure}{0.24\textwidth} \centering \includegraphics[width=\textwidth]{stat-d.pdf} \end{subfigure} \begin{subfigure}{0.24\textwidth} \centering \includegraphics[width=\textwidth]{stat-n.pdf} \end{subfigure} \caption{Sizes and update rates of the skylines of synthetic datasets} \label{fig:stats} \end{figure} The statistics of datasets are reported in Table~\ref{tbl:stats}. Here, $n$ is the number of tuples; $d$ is the dimensionality; \emph{\#skylines} is the number of tuples on the skyline; and \emph{updates} (\%) is the percentage of tuple operations that trigger any update on the skyline. Note that we generated several \textbf{Indep} and \textbf{AntiCor} datasets by varying $n$ from $100$K to $1$M and $d$ from $2$ to $10$ for scalability tests. By default, we used the ones with $n=100$K and $d=6$. The sizes and update rates of the skylines of synthetic datasets are shown in Fig.~\ref{fig:stats}. \noindent\textbf{Workloads:} The workload of each experiment was generated as follows: First, we randomly picked $50\%$ of tuples as the initial dataset $P_0$; Second, we inserted the remaining $50\%$ of tuples one by one into the dataset to test the performances for insertions; Third, we randomly deleted $50\%$ of tuples one by one from the dataset to test the performances for deletions. It is guaranteed that the orders of operations kept the same for all algorithms. The $k$-RMS results were recorded $10$ times when $10\%, 20\%, \ldots, 100\%$ of the operations were performed. \noindent\textbf{Performance Measures:} The efficiency of each algorithm was measured by \emph{average update time}, i.e., the average wall-clock time of an algorithm to update the result of $k$-RMS for each operation. For the static algorithms, we only took the time for $k$-RMS computation into account and ignored the time for skyline maintenance for fair comparison. The quality of results was measured by the \emph{maximum $k$-regret ratio} ($\mathtt{mrr}_k$) for a given size constraint $r$, and, of course, the smaller $\mathtt{mrr}_k$ the better. To compute $\mathtt{mrr}_k(Q)$ of a result $Q$, we generated a test set of $500$K random utility vectors and used the maximum regret value found as our estimate. Since the $k$-RMS results were recorded $10$ times for each query, we reported the average of the maximum $k$-regret ratios of $10$ results for evaluation. \subsection{Experimental Results}\label{subsec:results} \begin{figure*}[t] \centering \begin{subfigure}{.18\textwidth} \centering \includegraphics[width=\textwidth]{NBA-eps.pdf} \caption{BB} \end{subfigure} \begin{subfigure}{.18\textwidth} \centering \includegraphics[width=\textwidth]{AQ-eps.pdf} \caption{AQ} \end{subfigure} \begin{subfigure}{.18\textwidth} \centering \includegraphics[width=\textwidth]{CT-eps.pdf} \caption{CT} \end{subfigure} \\ \begin{subfigure}{.18\textwidth} \centering \includegraphics[width=\textwidth]{Movie-eps.pdf} \caption{Movie} \end{subfigure} \begin{subfigure}{.18\textwidth} \centering \includegraphics[width=\textwidth]{Indep-eps.pdf} \caption{Indep} \end{subfigure} \begin{subfigure}{.18\textwidth} \centering \includegraphics[width=\textwidth]{AC-eps.pdf} \caption{AntiCor} \end{subfigure} \caption{Performance of FD-RMS with varying $\varepsilon$ ($k=1$; $r=20$ for BB and $r=50$ for other datasets). Note that the red line represents the update time and the blue bars denote the maximum regret ratios.} \label{fig:eps} \end{figure*} \begin{figure*}[t] \centering \begin{subfigure}{.96\textwidth} \centering \includegraphics[width=\textwidth]{legend-k1.pdf} \end{subfigure} \begin{subfigure}{.36\textwidth} \centering \includegraphics[width=.48\textwidth]{k1-NBA-time.pdf} \includegraphics[width=.48\textwidth]{k1-NBA-mrr.pdf} \caption{BB} \end{subfigure} \begin{subfigure}{.36\textwidth} \centering \includegraphics[width=.48\textwidth]{k1-AQ-time.pdf} \includegraphics[width=.48\textwidth]{k1-AQ-mrr.pdf} \caption{AQ} \end{subfigure} \\ \begin{subfigure}{.36\textwidth} \centering \includegraphics[width=.48\textwidth]{k1-CT-time.pdf} \includegraphics[width=.48\textwidth]{k1-CT-mrr.pdf} \caption{CT} \end{subfigure} \begin{subfigure}{.36\textwidth} \centering \includegraphics[width=.48\textwidth]{k1-Movie-time.pdf} \includegraphics[width=.48\textwidth]{k1-Movie-mrr.pdf} \caption{Movie} \end{subfigure} \\ \begin{subfigure}{.36\textwidth} \centering \includegraphics[width=.48\textwidth]{k1-Indep-time.pdf} \includegraphics[width=.48\textwidth]{k1-Indep-mrr.pdf} \caption{Indep} \end{subfigure} \begin{subfigure}{.36\textwidth} \centering \includegraphics[width=.48\textwidth]{k1-AC-time.pdf} \includegraphics[width=.48\textwidth]{k1-AC-mrr.pdf} \caption{AntiCor} \end{subfigure} \caption{Update time and maximum regret ratios with varying the result size $r$ ($k=1$)} \label{fig:r} \end{figure*} \noindent\textbf{Effect of parameter $\varepsilon$ on FD-RMS:} In Fig.~\ref{fig:eps}, we present the effect of the parameter $\varepsilon$ on the performance of FD-RMS. We report the update time and maximum regret ratios of FD-RMS for $k=1$ and $r=50$ on each dataset (except $r=20$ on \textbf{BB}) with varying $\varepsilon$. We use the method described in Section~\ref{subsec:impl} to set the value of $M$ for each value of $\varepsilon$. First of all, the update time of FD-RMS increases significantly with $\varepsilon$. This is because both the time to process an $\varepsilon$-approximate top-$k$ query and the number of top-$k$ queries (i.e.,~$M$) grow with $\varepsilon$, which requires a larger overhead to maintain both top-$k$ results and set-cover solutions. Meanwhile, the quality of results first becomes better when $\varepsilon$ is larger but then could degrade if $\varepsilon$ is too large. The improvement in quality with increasing $\varepsilon$ is attributed to larger $m$ and thus smaller $\delta$. However, once $\varepsilon$ is greater than the maximum regret ratio $\varepsilon^*_{k,r}$ of the optimal result (whose upper bound can be inferred from practical results), e.g.,~$\varepsilon=0.0512$ on \textbf{BB}, the result of FD-RMS will contain less than $r$ tuples and its maximum regret ratio will be close to $\varepsilon$ no matter how large $m$ is. To sum up, by setting $\varepsilon$ to the one that is slightly lower than $\varepsilon^*_{k,r}$ among $[0.0001,\ldots,0.1024]$, FD-RMS performs better in terms of both efficiency and solution quality, and the values of $\varepsilon$ in FD-RMS are decided in this way for the remaining experiments. \noindent\textbf{Effect of result size $r$:} In Fig.~\ref{fig:r}, we present the performance of different algorithms for $1$-RMS (a.k.a.~$r$-regret query) with varying $r$. In particular, $r$ is ranged from $10$ to $100$ on each dataset (except \textbf{BB} where $r$ is ranged from $5$ to $25$). In general, the update time of each algorithm grows while the maximum regret ratios drop with increasing $r$. But, for FD-RMS, it could take less update time when $r$ is larger in some cases. The efficiency of FD-RMS is positively correlated with $m$ but negatively correlated with $\varepsilon$. On a specific dataset, FD-RMS typically chooses a smaller $\varepsilon$ when $r$ is large, and vice versa. When $\varepsilon$ is smaller, $m$ may decrease even though $r$ is larger. Therefore, the update time of FD-RMS decreases with $r$ in some cases because a smaller $\varepsilon$ is used. Among all algorithms tested, \textsc{Greedy} is the slowest and fails to provide results within one day on \textbf{AQ}, \textbf{CT}, and \textbf{AntiCor} when $r>80$. \textsc{GeoGreedy} runs much faster than \textsc{Greedy} while having equivalent quality on low-dimensional data. However, it cannot scale up to high dimensions (i.e., $d>7$) because the cost of finding \emph{happy points} grows significantly with $d$. DMM-RRMS suffers from two drawbacks: (1) it also cannot scale up to $d>7$ due to huge memory consumption; (2) its solution quality is not competitive when $r \geq 50$ because of the sparsity of space discretization. The solution quality of $\varepsilon$-\textsc{Kernel} is generally inferior to any other algorithm because the size of an $\varepsilon$-kernel coreset is much larger than the size of the minimum $(1,\varepsilon)$-regret set. Although HS provides results of good quality in most cases, it runs several orders of magnitude slower than FD-RMS. \textsc{Sphere} demonstrates better performance than other static algorithms. Nevertheless, its efficiency is still much lower than FD-RMS, especially on datasets with large skyline sizes, e.g., \textbf{CT} and \textbf{AntiCor}, where FD-RMS runs up to three orders of magnitude faster. URM shows good performance in both efficiency and solution quality for small $r$ (e.g., $r \leq 20$) and skyline sizes (e.g., on \textbf{BB} and \textbf{Indep}). However, it scales poorly to large $r$ and skyline sizes because the convergence of k-\textsc{medoid} becomes very slow and the number of linear programs for regret computation grows rapidly when $r$ and and skyline sizes increase. In addition, URM does not provide high-quality results in many cases since k-\textsc{medoid} cannot escape from local optima. To sum up, FD-RMS outperforms all other algorithms for fully-dynamic $1$-RMS in terms of efficiency. Meanwhile, the maximum regret ratios of the results of FD-RMS are very close (the differences are less than $0.01$ in almost all cases) to the best of static algorithms. \begin{figure*}[t] \centering \begin{subfigure}{.75\textwidth} \centering \includegraphics[width=\textwidth]{legend-k5.pdf} \end{subfigure} \begin{subfigure}{.36\textwidth} \centering \includegraphics[width=.48\textwidth]{k5-NBA-time.pdf} \includegraphics[width=.48\textwidth]{k5-NBA-mrr.pdf} \caption{BB} \end{subfigure} \begin{subfigure}{.36\textwidth} \centering \includegraphics[width=.48\textwidth]{k5-AQ-time.pdf} \includegraphics[width=.48\textwidth]{k5-AQ-mrr.pdf} \caption{AQ} \end{subfigure} \\ \begin{subfigure}{.36\textwidth} \centering \includegraphics[width=.48\textwidth]{k5-CT-time.pdf} \includegraphics[width=.48\textwidth]{k5-CT-mrr.pdf} \caption{CT} \end{subfigure} \begin{subfigure}{.36\textwidth} \centering \includegraphics[width=.48\textwidth]{k5-Movie-time.pdf} \includegraphics[width=.48\textwidth]{k5-Movie-mrr.pdf} \caption{Movie} \end{subfigure} \\ \begin{subfigure}{.36\textwidth} \centering \includegraphics[width=.48\textwidth]{k5-Indep-time.pdf} \includegraphics[width=.48\textwidth]{k5-Indep-mrr.pdf} \caption{Indep} \end{subfigure} \begin{subfigure}{.36\textwidth} \centering \includegraphics[width=.48\textwidth]{k5-AC-time.pdf} \includegraphics[width=.48\textwidth]{k5-AC-mrr.pdf} \caption{AntiCor} \end{subfigure} \caption{Update time and maximum regret ratios with varying $k$ ($r=10$ for BB and Indep; $r=50$ for other datasets)} \label{fig:k} \end{figure*} \begin{figure*}[t] \centering \begin{subfigure}{.96\textwidth} \centering \includegraphics[width=\textwidth]{legend-k1.pdf} \end{subfigure} \begin{subfigure}{.36\textwidth} \centering \includegraphics[width=.48\textwidth]{d-Indep-time.pdf} \includegraphics[width=.48\textwidth]{d-Indep-mrr.pdf} \caption{Indep, varying $d$}\label{fig:nd:a} \end{subfigure} \begin{subfigure}{.36\textwidth} \centering \includegraphics[width=.48\textwidth]{d-AC-time.pdf} \includegraphics[width=.48\textwidth]{d-AC-mrr.pdf} \caption{AntiCor, varying $d$}\label{fig:nd:b} \end{subfigure} \\ \begin{subfigure}{.36\textwidth} \centering \includegraphics[width=.48\textwidth]{n-Indep-time.pdf} \includegraphics[width=.48\textwidth]{n-Indep-mrr.pdf} \caption{Indep, varying $n$}\label{fig:nd:c} \end{subfigure} \begin{subfigure}{.36\textwidth} \centering \includegraphics[width=.48\textwidth]{n-AC-time.pdf} \includegraphics[width=.48\textwidth]{n-AC-mrr.pdf} \caption{AntiCor, varying $n$}\label{fig:nd:d} \end{subfigure} \caption{Scalability with varying the dimensionality $d$ and dataset size $n$ ($k=1, \; r=50$)} \label{fig:nd} \end{figure*} \noindent\textbf{Effect of $k$:} The results for $k$-RMS with varying $k$ from $1$ to $5$ are illustrated in Fig.~\ref{fig:k}. We only compare FD-RMS with \textsc{Greedy}$^*$, $\varepsilon$-\textsc{Kernel}, and HS because other algorithms are not applicable to the case when $k>1$. We set $r=10$ for \textbf{BB} and \textbf{Indep} and $r=50$ for the other datasets. The results of \textsc{Greedy}$^*$ for $k>1$ are only available on \textbf{BB} and \textbf{Indep}. For the other datasets, \textsc{Greedy}$^*$ fails to return any result within one day when $k>1$. We can see all algorithms run much slower when $k$ increases. For FD-RMS, lower efficiencies are caused by higher cost of maintaining top-$k$ results. HS and $\varepsilon$-\textsc{Kernel} must consider all tuples in the datasets instead of only skylines to validate that the maximum $k$-regret ratio is at most $\varepsilon$ when $k>1$. For \textsc{Greedy}$^*$, the number of linear programs to compute $k$-regret ratios increases drastically with $k$. Meanwhile, the maximum $k$-regret ratios drop with $k$, which is obvious according to its definition. FD-RMS achieves speedups of up to four orders of magnitude than the baselines on all datasets. At the same time, the solution quality of FD-RMS is also better on all datasets except \textbf{Movie} and \textbf{CT}, where the results of HS are of slightly higher quality in some cases. \noindent\textbf{Scalability:} Finally, we evaluate the scalability of different algorithms w.r.t.~the dimensionality $d$ and dataset size $n$. To test the impact of $d$, we fix $n=100$K, $k=1$, $r=50$, and vary $d$ from $2$ to $10$. The performance with varying $d$ is shown in Fig.~\ref{fig:nd:a}--\ref{fig:nd:b}. Both the update time and maximum regret ratios of all algorithms increase dramatically with $d$. Although almost all algorithms show good performance when $d=2,3$, most of them quickly become very inefficient in high dimensions. Nevertheless, FD-RMS has a significantly better scalability w.r.t.~$d$: It achieves speedups of at least $100$ times over any other algorithm while providing results of equivalent quality when $d \geq 7$. To test the impact of $n$, we fix $d=6$, $k=1$, $r=50$, and vary $n$ from $100$K to $1$M. The update time with varying $n$ is shown in Fig.~\ref{fig:nd:c}--\ref{fig:nd:d}. For static algorithms, we observe different trends in efficiency on two datasets: The update time slightly drops on \textbf{Indep} but keeps steady on \textbf{AntiCor}. The efficiencies are determined by two factors, i.e., \emph{the number of tuples on the skyline} and \emph{the frequency of skyline updates}. As shown in Fig.~\ref{fig:stats}, when $n$ is larger, the number of tuples on the skyline increases but the frequency of skyline updates decreases. On \textbf{Indep}, the benefits of lower update frequencies outweigh the cost of more skyline tuples; on \textbf{AntiCor}, two factors cancel each other. FD-RMS runs slower when $n$ increases due to higher cost of maintaining top-$k$ results on \textbf{Indep}. But, on \textbf{AntiCor}, the update time keeps steady with $n$ because of smaller values of $\varepsilon$ and $m$, which cancel the higher cost of maintaining top-$k$ results. We can observe that the maximum regret ratios of most algorithms are not not significantly affected by $n$. The solution quality of FD-RMS is close to the best of static algorithms. Generally, FD-RMS always outperforms all baselines for different values of $n$. \section{Frequently Used Notations} A list of frequently used notations in this paper is summarized in Table~\ref{tbl:notation}. \section{Additional Experimental Evaluation} \subsection{Extension of Greedy for Dynamic Updates} In Section~\ref{sec:exp}, all algorithms (except FD-RMS and URM) we compare are static algorithms that recompute the results each time when the skyline is updated. In fact, it is possible to extend a static algorithm, e.g., \textsc{Greedy}~\cite{DBLP:journals/pvldb/NanongkaiSLLX10}, to support dynamic updates as follows: Initially, it computes a $k$-regret minimizing set of size $r'=r+\Delta_r$ (where $\Delta_r$ is an integer parameter) using \textsc{Greedy}. Among this set, a set of $r$ tuples is reported as the result. The result is recomputed whenever (1) $\Delta_r$ tuples from the $k$-regret minimizing set of size $r'$ are deleted (in which case it recomputes a $k$-regret minimizing set of size $r'$); (2) there are a total of $\Delta_s$ number of insertions into the skyline where $\Delta_s$ is another parameter. We refer to this extension of \textsc{Greedy} as the Dynamic Greedy (DG) algorithm. In this subsection, we compare the Dynamic Greedy (DG) algorithm with \textsc{Greedy} and FD-RMS. Specifically, we test four sets of parameters $\Delta_s,\Delta_r$, namely DG-1 with $\Delta_s=10,\Delta_r=0.25r$, DG-2 with $\Delta_s=25,\Delta_r=0.5r$, DG-3 with $\Delta_s=50,\Delta_r=0.75r$, and DG-4 with $\Delta_s=100,\Delta_r=r$. The original \textsc{Greedy} is a special case of DG with $\Delta_s=1,\Delta_r=0$. The experimental results are shown in Fig.~\ref{fig:dynamic:greedy}. First of all, when $\Delta_s$ and $\Delta_r$ increase, DG runs faster because the recomputation is executed at lower frequencies. But unfortunately, DG still runs much slower than FD-RMS even when $\Delta_s=100,\Delta_r=r$ because of the huge gap in the efficiency of \textsc{Greedy} and FD-RMS. Meanwhile, the maximum regret ratios of the results of DG increase with $\Delta_s$ and $\Delta_r$, and become significantly higher than those of FD-RMS when $\Delta_s$ and $\Delta_r$ are large. This is because the results of DG could often be obsolete w.r.t.~up-to-date datasets. In general, DG is significantly inferior to FD-RMS in terms of both efficiency and quality of results for different parameters. Nevertheless, DG might be used to accelerate \textsc{Greedy} in dynamic settings if the requirement for quality is not so strict. \subsection{Effect of Update Patterns} In Section~\ref{sec:exp}, we consider the updates to datasets consist of all insertions first followed by all deletions to test the performance of different algorithms for tuple insertions and deletions separately. In this subsection, we evaluate the performance of FD-RMS in two update patterns: (1) First all insertions followed by all deletions as Section~\ref{sec:exp} (I+D); (2) A random mixture of insertions and deletions (Mixed). We note that the efficiency and solution quality of a static algorithm are not influenced by update patterns because the update rates of skylines are similar for tuple insertions and deletions, and it reruns from scratch for each skyline update. The update time of FD-RMS in two update patterns is shown in Fig.~\ref{fig:time:mixed}. We can see that the update time is nearly indifferent to update patterns. In addition, we also confirm that the results returned by FD-RMS remain the same in almost all cases regardless of the orders of tuple operations. In addition, we show the update time of FD-RMS with varying $r$ for tuple insertions and deletions in Fig.~\ref{fig:id}. The update time for deletions is slightly longer than that for insertions on all datasets. This is mainly attributed to the difference in the update of approximate top-$k$ results. For insertions, the dual-tree can incrementally update the current top-$k$ result using the utility index only; but for deletions, the dual-tree must retrieve the new top-$k$ result from scratch on the tuple index once a top-$k$ tuple is deleted. \subsection{Extension of URM for Dynamic Updates}\label{appendix:dynamic:urm} \begin{algorithm} \caption{\textsc{Dynamic URM}} \label{alg:urm} \Input{Initial database $P_0$, set of operations $\Delta$} \Output{Result $Q_t$ for $1$-RMS on $P_t$ at time $t$} \tcc{compute an initial result $Q_0$ on $P_0$} run DMM-RRMS to get an initial result $S_0$\; run $k$-\textsc{medoid} from $S_0$ until convergence as $Q_0$\; \tcc{update $Q_{t-1}$ to $Q_t$ for $\Delta_t = \langle p,\pm \rangle$} Update $P_{t-1}$ to $P_t$ w.r.t.~$\Delta_t$\; \uIf{$\Delta_t= \langle p,+ \rangle$}{ \uIf{there exists $p' \in Q_{t-1}$ such that the max regret ratio of $p$ in the region $R(p')$ of $p'$ is lower than $p'$} {$S' \gets Q_{t-1} \setminus \{p'\} \cup \{p\}$\; run $k$-\textsc{medoid} from $S'$ until convergence as $Q_t$\;} \Else{ $Q_t \gets Q_{t-1}$\; } } \Else{\tcc{for a deletion $\Delta_t= \langle p,- \rangle$} \uIf{$p \in Q_{t-1}$} {$S' \gets Q_{t-1} \setminus \{p\} \cup \{p'\}$ where $p' \notin Q_{t-1}$ is top-ranked for at least one utility vector in the region $R(p)$ of $p$\; run $k$-\textsc{medoid} from $S'$ until convergence as $Q_t$\;} \Else{ $Q_t \gets Q_{t-1}$\; } } \end{algorithm} Unlike other static algorithms, the URM algorithm~\cite{Shetiya2019} adopts an iterative framework based on the $k$-\textsc{medoid} clustering for RMS computation. It is intuitive to extend the iterative framework to support dynamic updates. The high-level idea of updating the result of URM for tuple operations without fully recomputation is as follows: If an operation does not affect the convergence of the current result, then skip it directly; Otherwise, first adjust the result for this operation and then run the iterative framework starting from the new result until it converges again. The detailed procedures of (dynamic) URM are presented in Algorithm~\ref{alg:urm}. \begin{figure*}[t] \captionsetup[subfigure]{aboveskip=2pt} \centering \begin{subfigure}{.32\textwidth} \centering \includegraphics[width=\textwidth]{NBA-Dynamic-r10.pdf} \caption{BB ($r=10$)} \end{subfigure} \begin{subfigure}{.32\textwidth} \centering \includegraphics[width=\textwidth]{Movie-Dynamic-r50.pdf} \caption{Movie ($r=50$)} \end{subfigure} \begin{subfigure}{.32\textwidth} \centering \includegraphics[width=\textwidth]{Indep-Dynamic-r50.pdf} \caption{Indep ($d=6,r=50$)} \end{subfigure} \caption{Performance of the Dynamic Greedy (DG) algorithm in comparison with \textsc{Greedy} and FD-RMS ($k=1$). Parameter settings for DG are listed as follows: DG-1 -- $\Delta_s=10,\Delta_r=0.25r$; DG-2 -- $\Delta_s=25,\Delta_r=0.5r$; DG-3 -- $\Delta_s=50,\Delta_r=0.75r$; DG-4 -- $\Delta_s=100,\Delta_r=r$.} \label{fig:dynamic:greedy} \end{figure*} \begin{figure*}[t] \centering \begin{subfigure}{.18\textwidth} \centering \includegraphics[width=\textwidth]{NBA-mixed.pdf} \caption{BB} \end{subfigure} \begin{subfigure}{.18\textwidth} \centering \includegraphics[width=\textwidth]{AQ-mixed.pdf} \caption{AQ} \end{subfigure} \begin{subfigure}{.18\textwidth} \centering \includegraphics[width=\textwidth]{CT-mixed.pdf} \caption{CT} \end{subfigure} \\ \begin{subfigure}{.18\textwidth} \centering \includegraphics[width=\textwidth]{Movie-mixed.pdf} \caption{Movie} \end{subfigure} \begin{subfigure}{.18\textwidth} \centering \includegraphics[width=\textwidth]{Indep-mixed.pdf} \caption{Indep ($d=6$)} \end{subfigure} \begin{subfigure}{.18\textwidth} \centering \includegraphics[width=\textwidth]{AC-mixed.pdf} \caption{AntiCor ($d=6$)} \end{subfigure} \caption{Update time of FD-RMS in different update patterns ($k=1$)} \label{fig:time:mixed} \end{figure*} \begin{figure*}[t] \centering \begin{subfigure}{.18\textwidth} \centering \includegraphics[width=\textwidth]{NBA-id.pdf} \caption{BB} \end{subfigure} \begin{subfigure}{.18\textwidth} \centering \includegraphics[width=\textwidth]{AQ-id.pdf} \caption{AQ} \end{subfigure} \begin{subfigure}{.18\textwidth} \centering \includegraphics[width=\textwidth]{CT-id.pdf} \caption{CT} \end{subfigure} \\ \begin{subfigure}{.18\textwidth} \centering \includegraphics[width=\textwidth]{Movie-id.pdf} \caption{Movie} \end{subfigure} \begin{subfigure}{.18\textwidth} \centering \includegraphics[width=\textwidth]{Indep-id.pdf} \caption{Indep} \end{subfigure} \begin{subfigure}{.18\textwidth} \centering \includegraphics[width=\textwidth]{AC-id.pdf} \caption{AntiCor} \end{subfigure} \caption{Update time of FD-RMS for tuple insertion and deletion ($k=1$). The red line denotes the average update time for all tuple operations.} \label{fig:id} \end{figure*}
{'timestamp': '2020-10-15T02:14:53', 'yymm': '2005', 'arxiv_id': '2005.14493', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14493'}
arxiv
\section{QM2 altered setting} \label{Sec:QM2A} The altered setting of the {QM2} \ model we study is motivated from \cite[Appendix C]{shah2019sequentialME}, and we describe it below. We have $k$ bins, one corresponding to each element of the support set, and a representative element in each bin. Any algorithm proceeds in rounds. In the $t^{th}$ round, the algorithm chooses a subset $\mathcal{C}(t)$ of these bins, and we compare the $t^{th}$ sample with the representative element from each bin in $\mathcal{C}(t)$. Note that these comparisons happen in parallel and the number of queries in round $t$ is the cardinality of the set $\mathcal{C}(t)$. In each round, the oracle response could be $+1$ for some bin $j$ $\in$ $\mathcal{C}(t)$ and $-1$ for all other bins in $\mathcal{C}(t)$ with probability $p_j$, or the response could be $-1$ for all bins in $\mathcal{C}(t)$ with probability $(1 - \sum_{j \in \mathcal{C}(t)} p_j)$. Based on the oracle responses obtained so far, the algorithm decides whether to stop or to proceed to the next round. When the algorithm decides to stop, it outputs an estimate $\widehat{S}$ of $S_{\mathcal{P}}^{\gamma}$, the set of support elements with a probability above $\gamma$. Note that this setting is different from our original setting in {QM2}. Firstly, the number of bins is fixed with one bin corresponding to each element of the support and furthermore, there is a priori one representative element present in each bin. Secondly, in the modified setting, we choose the set $\mathcal{C}(t)$ at the start of each round and all the $|\mathcal{C}(t)|$ replies from the oracle come in parallel. However, in {QM2}, we we perform queries sequentially in each round and terminate the round as soon as we get a $+1$ response from any one of the bins in $\mathcal{C}(t)$. In spite of these differences, we believe that the query complexity for both these models will be quite similar and as we see below, the alternate setting can be placed in a framework that is fairly well studied and can potentially provide provide pointers towards solving the original problem. We look at this new problem as a structured Multi-armed Bandit (MAB) problem \cite{MABbook} where there are $k$ arms, and each arm has a Bernoulli reward distribution with mean $p_i$. From the constraints of our original setup, the means must sum up to $1$ i.e. $\sum_{i} p_i = 1$. In each round we can pull a subset $\mathcal{C}(t)$ of arms and the output is a vector with $-1$ for all arms in $\mathcal{C}(t)$ with probability (1- $\sum_{i \in \mathcal{C}(t)} p_i$) or the output vector has $+ 1$ for some arm $j \in \mathcal{C}(t)$ and $-1$ for all other arms with probability $p_j$. The number of pulls in round $t$ is cardinality of the set $\mathcal{C}(t)$. Based on the responses from the arms, the algorithm decides whether to continue to the next round or stop and output an estimate for the set of arms with mean rewards above $\gamma$. The aim of the algorithm is to correctly identify this set of arms with probability at least (1- $\delta$). The total number of pulls across all rounds is defined as the query complexity of a $\delta$-true $\gamma$-threshold estimator in this setting. Ideally, we would like to get a tight lower bound on the query complexity for the aforementioned structured MAB problem. The key challenge in doing so is the simplex constraint on the class of mean rewards imposed by $\sum_i p_i =1$. Although we are unable to provide a lower bound for this constraint, we are able to provide a lower bound under a slightly relaxed constraint given by \begin{equation}{\label{QM2_pi_cond}} p_1 + p_2 +...+p_k + 2 \gamma < 1. \end{equation} % \begin{theorem}{\label{QM2_alter_lb}} For a MAB setting described above where the mean rewards of the individual arms satisfy the condition in equation \ref{QM2_pi_cond}, any $\delta$-true $\gamma$-threshold algorithm has the following lower bound in expectation on the total number of pulls $N$: $$ \mathbb{E}_{\mathcal{P}}[N] \geq \sum_{i=1}^{k} \frac{\log(\frac{1}{2.4\delta})}{2\cdot d(p_i||\gamma)}. $$ \end{theorem} Note that the expression in the lower bound above is very similar to the upper bound on the query complexity under the {QM2} \ model derived in Theorem~\ref{QM2ub}. Proving such a lower bound for the structured MAB under the true simplex constraint $\sum_{i} p_i = 1$ is part of our future work. There has been some recent work on similar problems which might provide us some pointers on how to pursue this problem. In particular, say we restrict attention to the class of schemes which compare to a single bin in each round, i.e., $|\mathcal{C}(t)| = 1$ for all $t$. The \textit{thresholding bandit problem} as described above, without the simplex constraint, was studied in \cite{locatelli2016optimal}, and the optimal query complexity expression turns out to be very similar to the one in Theorem~\ref{QM2_alter_lb}. On the other hand, \cite{simchowitz2017simulator} studies the related problem of identifying the arm with the largest mean reward and derives a tight lower bound on the query complexity under the simplex constraint. \section{THRESHOLD-ESTIMATOR UNDER {QM1}} \section{{QM1} \ THRESHOLD ESTIMATOR} \label{Sec:QM1} Under {QM1}, for every query with index $i$, the oracle returns the value $X_i$ of the $i^{th}$ sample. We now present an algorithm for this query model and analyze its query complexity, see Algorithm~\ref{QM1_alg}. \subsection{Algorithm} We first create $k$ bins numbered $1,2,...,k$. In each time step $t$, we query the oracle with the index $t$. The oracle reveals the value $X_t$ and the index $t$ is placed in the bin whose index matches $X_t$. We define $Z_i^t$ for $i\in \{1,2,..,k\}$ used in Algorithm \ref{QM1_alg} as follows: \begin{equation*} Z_i^t= \begin{cases} 1 & \text{if}\ X_t = i, \\ 0 & \text{otherwise}. \end{cases} \end{equation*} We can argue that for each given $i$, $\{Z_i^t\}$ is a collection of i.i.d. Bernoulli random variables with $\mathbb{E}[Z_i^t]=p_i$. Let $\tilde{p}_i^t $ denote the empirical probability estimate for support element $i$ at time $t$, and is given by \begin{equation}\label{eq1} \tilde{p}_i^t = \sum_{j=1}^{t} Z_i^j/t. \end{equation} Note that $\tilde{p}_i^t$ denotes the fraction of samples in Bin $i$, till time $t$. At each round $t$ and for every $i$, we choose the confidence interval of Bin $i$ such that $p_i$ lies within the interval with "sufficiently" high probability. For a given time $t$, let $u_i(t)$ and $l_i(t)$ denote the upper confidence bound (UCB) and lower confidence bound (LCB) of Bin $i$ respectively and the confidence interval of Bin $i$ is given by $[l_i(t),u_i(t)]$. {\begin{algorithm}{\label{QM1_alg}} { { \SetAlgoLined Create bins numbered $1,2...k$.\\ Initialize $\tilde{p}_i^{0}=0$, $l_i(0)=0$, $u_i(0)=1$, $\forall i\in\{1,2,...,k\}$.\\ $t = 0$ \\ \While{$\exists$ Bin $j$ s.t $l_j(t)$ $<$ $\gamma$ $<$ $u_j(t)$}{ { Obtain $X_{t+1}$. } $t = t +1$.\\ Place the index $t$ in the bin numbered $X_t$.\\ \text{Update the empirical estimate} $\tilde{p}_i^{t}$ according to \eqref{eq1}; upper and lower confidence bounds $l_i(t)$ according to \eqref{eqnlb} and $u_i(t)$ \eqref{eqnub} respectively for all bins.\\ } Output $\{i|l_i(t)>\gamma\}$. \caption{Estimator for {QM1}} }} \end{algorithm}} Motivated from the bounds in \cite{pmlr-v30-Kaufmann13}, for some given sequence of parameters $\{\beta^t\}$, we define $l_i(t)$ and $u_i(t)$ as follows: \begin{align} l_i(t) &= {\min}\{ q \in [0,\tilde{p}_i^t]: t\times d(\tilde{p}_i^t||q) \leq \beta^t \},\label{eqnlb} \\ u_i(t) &= {\max}\{ q \in [\tilde{p}_i^t,1]: t\times d(\tilde{p}_i^t||q) \leq \beta^t \}.\label{eqnub} \end{align} Here $d(p||q)$ denotes the Kullback-Leibler divergence between two Bernoulli distributions with means $p$ and $q$ respectively The algorithm keeps querying the oracle and updating the confidence intervals for each bin, until every bin has either its LCB above $\gamma$ or its UCB below $\gamma$ at which point the Algorithm~\ref{QM1_alg} terminates. The estimate $\widehat{S}$ is chosen to consist of all bin indices which have their LCBs above $\gamma$. We choose the sequence $\{\beta^t\}$ in such a way that the probability of error is bounded by $\delta$. The following lemma claims that Algorithm \ref{QM1_alg} returns the desired set $S_{\mathcal{P}}^{\gamma}$ for any underlying distribution $\mathcal{P}$ with probability at least $1- \delta$. \begin{lemma}{\label{Correctness_QM1}} Given the choice of $\beta^t = \log(2kt^2 / \delta)$ for each $t\ge 1$, Algorithm \ref{QM1_alg} is a $\delta$-true $\gamma$-threshold estimator under {QM1}. \end{lemma} \subsection{Query Complexity Analysis} Given two values $x$ and $y$ satisfying $0 \leq x,y \leq 1$, we define $d^{*} (x,y) = d(z||x)$ where $z$ satisfies the condition $d(z||x) = d(z||y)$. The quantity $d^{*} (x,y)$ represents the \textit{Chernoff information} between two Bernoulli distributions with means $x$ and $y$ respectively, and is a relevant quantity in hypothesis testing problems \cite[Section 11.8]{10.5555/1146355}. This definition plays a key role in the following theorem which provides an upper bound on the query complexity of our proposed estimator in Algorithm \ref{QM1_alg}. \begin{theorem}{\label{QM1ub}} Let $\mathcal{A}$ denote the estimator in Algorithm \ref{QM1_alg} with $\beta^t = \log(2kt^2 / \delta)$ for each $t\ge 1$ and let $Q_{\delta,\gamma}^{\mathcal{P}}(\mathcal{A})$ be the corresponding query complexity for a given distribution $\mathcal{P}$ under {QM1}. Then, we have $$Q_{\delta,\gamma}^{\mathcal{P}}(\mathcal{A})\leq \max_{j\in\{m,m+1\}} \Biggl\{\frac{2e\log \Bigl(\sqrt{\frac{2k}{\delta}}\frac{2}{d^{*}(p_j,\gamma)}\Bigr)}{(e-1)d^{*}(p_j,\gamma)} \Biggr\},$$ with probability at least $1-\delta$. \end{theorem} This is essentially argued as follows. For each $i$, we identify a time $T_i$ such that with high probability, Bin $i$ would have been classified as being either above $\gamma$ or below $\gamma$ by time $T_i$. We then show that $T_i$ is bounded by the expression given in Theorem \ref{QM1ub}, $\forall i \in\{1,2,...,k\}$. Next, we give a lower bound of the number of queries $Q_{\delta,\gamma}^{\mathcal{P}}(\mathcal{A})$ for any $\delta$-true $\gamma$-threshold estimator $\mathcal{A}$ under {QM1}. \begin{theorem}\label{QM1lb} For any $\delta$-true $\gamma$-threshold estimator $\mathcal{A}$ under {QM1}, let $Q_{\delta,\gamma}^{\mathcal{P}}(\mathcal{A})$ be the query complexity. Then, we have $$\mathbb{E}[Q_{\delta,\gamma}^{\mathcal{P}}(\mathcal{A})]\geq \max_{j\in\{m,m+1\}}\Bigg\{\frac{\log{\frac{1}{2.4\delta}}}{d(p_j||\gamma)}\Bigg\}.$$ \end{theorem} The proof of the above result is based on change of measure arguments similar to those in \cite{kaufmann2016complexity}. The detailed proof is given in Section~\ref{Sec:Thm2_proof}. Theorems~\ref{QM1ub} and \ref{QM1lb} provide a fairly tight characterization of the optimal query complexity under the QM1 query model, with the key difference between the upper and lower bound being the terms $d^{*}(p_j,\gamma)$ and $d(p_j||\gamma)$ respectively. {From the definition of $d^*(x,y)$, $\min\bigg\{d\Big(\frac{p_j+\gamma}{2}||p_j\Big),d\Big(\frac{p_j+\gamma}{2}||\gamma\Big)\bigg\}\leq d^{*}(p_j,\gamma) \leq \max\bigg\{d\Big(\frac{p_j+\gamma}{2}||p_j\Big),d\Big(\frac{p_j+\gamma}{2}||\gamma\Big)\bigg\}$. We also have $ 2(p_j-\gamma)^2 \leq d(p_j||\gamma) \leq \frac{(p_j-\gamma)^2}{\gamma(1-\gamma)}$ (\cite{popescu2016bounds}), and combining the above inequalities, we get $\frac{d(p_j||\gamma)}{d^{*}(p_j,\gamma)}\leq \frac{2}{\gamma(1-\gamma)}$. Thus, our bounds in Theorems \ref{QM1ub} and \ref{QM1lb} are tight up to logarithmic factors.} \begin{remark*} Our algorithms use the knowledge of the number of support elements ($k$) in the confidence intervals' design, whereas our lower bounds are independent of $k$. Whether the dependence on $k$ is fundamental or can it be removed by designing smarter algorithms and using more sophisticated concentration inequalities is an important question we want to address in the future. \end{remark*} % \section{{QM1-N} \ THRESHOLD ESTIMATOR } \label{Sec:QM1N} Under {QM1-N}, when queried with an index $i$, the oracle returns the true value of $X_i$ with probability $1-p_e$ and a uniformly at random chosen value in $\{1,2,\ldots,k\}$ with probability $p_e$. The responses of the oracle in this noisy setting would stochastically be the same as the responses from another oracle in the {QM1} \ model with an underlying distribution $p_i' = (1-p_e)p_i + {p_e}/{k}$ over the same support set. Since the responses from the oracles in the two settings described above are stochastically identical, Theorems \ref{QM1ub} and \ref{QM1lb} also provide upper and lower bounds on the query complexity of $\delta$-true $\gamma$-threshold estimators for the {QM1-N} \ model, by considering the underlying distribution as $\mathcal{P}'=\{p_1',p_2',...,p_k'\}$, and the threshold as $\gamma'$ = $(1-p_e)\gamma + {p_e}/{k}$. Note that the estimator proposed in Algorithm \ref{QM1_alg} for the {QM1} \ model is a $\delta$-true $\gamma$-threshold estimator for the noisy setting as well, with the threshold set to $\gamma' = (1-p_e)\gamma + {p_e}/{k}$. \section{{QM2} \ THRESHOLD-ESTIMATOR } \label{Sec:QM2} Recall that under the {QM2} \ model, the oracle only makes pairwise comparisons. When queried with two indices $i$ and $j$, the oracle response indicates whether the values $X_i$ and $X_j$ are equal or not. We now present $\delta$-true $\gamma$-threshold estimator for this query model and analyse its query complexity \subsection{Algorithm} % \textit{High-level description:} Recall that under the {QM1} \ model, we begin by creating $k$ bins, one corresponding to each element of the support of the underlying distribution. In each time slot $t$, the oracle reveals the value $X_t$ of the sample $t$, and the index $t$ is placed in the corresponding bin. A key challenge in the {QM2} \ model is that the oracle does not reveal the value of the samples. Instead, it just provides pairwise information about whether the values of two samples corresponding to the pair of queried indices are equal or not. Here, we create and update bins as the algorithm proceeds, while ensuring that each such bin contains samples representing the same support element. As with the previous models, the algorithm proceeds in rounds. Let $\mathcal{B}(t)$ denote the set of bins created by the end of round $t$. For each round $t >1 $, we choose a subset of bins $\mathcal{C}(t-1)$ from $\mathcal{B}(t-1)$. We go over the bins in $\mathcal{C}(t-1)$ one by one, and then query the oracle to compare the $t^{th}$ sample with a representative element from the current bin. Round $t$ stops when we either get a positive response from the oracle indicating that a matching bin has been found, or when all the bins in $\mathcal{C}(t-1)$ have been exhausted. As before, we maintain confidence intervals for the true probability value corresponding to each bin and our algorithm as described in Algorithm~\ref{QM2_alg} terminates, when its termination criterion is met, which we discuss below in the detailed description. \textit{Detailed description:} We define $\mathbb{Z}_i^t$ as follows: {\small \begin{equation*} \mathbb{Z}_i^t = \begin{cases} 1 & \text{ if } \mathcal{O}(i_r,t)=1 \text{ for } i_r \in \text{Bin } i , \text{ Bin } i \in \mathcal{B}(t-1)\\ 0 & \text{otherwise}. \end{cases} \end{equation*}} Let $\hat{p}_i^t${\footnote{Note that $\hat{p}_i^t$ denotes the fraction of samples in Bin $i$ and $\tilde{p}_i^t$ in Section \ref{Sec:QM1} denotes the fraction of samples of the support element $i$.}} denotes the fraction of samples present in Bin $i$ by the end of round $t$. We define it formally as follows: \begin{equation}{\label{emp_QM2}} \hat{p}_i^t = {\sum_{j=1}^{t} \mathbb{Z}_i^j }/{t}. \end{equation} \begin{algorithm}[h]{\label{QM2_alg}} {\small \SetAlgoLined $t$=1\\ Create a new bin and add sample $t$ to it.\\ Update the empirical estimate $\hat{p}_i^{t}$ according to \eqref{emp_QM2}, the upper bound $\hat{u}_i(t)$ and the lower bound $\hat{l}_i(t)$ according to \eqref{eqnubbin} and \eqref{eqnlbbin} for the created bin. Form $\mathcal{C}$($t$) according to $\eqref{eqn:c1t}$.\\ \While{( $t < T'$)}{ {$t=t+1$\\} flag = 0.\\ \ForAll{ $j$ $\in$ $\mathcal{C}(t-1)$ }{ Obtain $j_l \in \text{Bin } j$.\\ \If{$\mathcal{O}(t,j_l) == +1$}{ Add sample $t$ to corresponding bin.\\ flag = 1. BREAK.\\ } } \If{flag==0 } { Create a new bin and add sample $t$ to it. } Update the empirical estimate $\hat{p}_i^{t}$ according to \eqref{emp_QM2}, the upper bound $\hat{u}_i(t)$ and the lower bound $\hat{l}_i(t)$ according to \eqref{eqnubbin} and \eqref{eqnlbbin} for all the bins in $\mathcal{C}(t-1)$ and the newly created bin if created in this round.\\ {For all other bins, we keep the empirical means and LCB-UCB bounds unchanged.\\} % {Form $\mathcal{C}$($t$) according to $\eqref{eqn:c1t}$.}\\ } Initialise $\mathcal{S}=\{x|\hat{l}_x(t)>\gamma\}$.\\ \While{$\mathcal{C}(t)\neq \Phi$}{ { $t = t +1$}.\\ \ForAll{$j$ $\in$ $\mathcal{C}(t-1)$ }{ Obtain $j_l \in \text{Bin } j$.\\ \If{$\mathcal{O}(t,j_l) == +1$}{ Add sample $t$ to corresponding bin. BREAK.\\ } } Update the empirical estimate $\hat{p}_i^{t}$ according to \eqref{emp_QM2}, the upper bound $\hat{u}_i(t)$ and the lower bound $\hat{l}_i(t)$ according to \eqref{eqnubbin} and \eqref{eqnlbbin} for all the bins in $\mathcal{C}(t-1)$.\\ Update $\mathcal{S}$ by adding the bins with $\hat{l}_x(t)>\gamma$. % {Form $\mathcal{C}$($t$) according to $\eqref{eqn:c2t}$.} } Output $\mathcal{S}$. \caption{Estimator for {QM2}} } \end{algorithm} As before, let $\hat{l}_i(t)$ and $\hat{u}_i{(t)}$ denote the lower and upper confidence bounds for Bin $i$ respectively, and as before are defined as follows for some appropriate choice of $\{\beta^t\}$: \begin{align} \label{eqnlbbin} \hat{l}_i(t) & = {\min}\{ q \in [0,\hat{p}_i^t]: t\times d(\hat{p}_i^t||q) \leq \beta^t \},\\ \label{eqnubbin} \hat{u}_i(t) &= {\max}\{ q \in [\hat{p}_i^t,1]: t\times d(\hat{p}_i^t||q) \leq \beta^t \}. \end{align} We run the algorithm in 2 phases. The goal of the first phase is to ensure that one bin is created corresponding to each support element $\{1,2,...,m\}$ in $S_{\mathcal{P}}^{\gamma}$ with "high" probability. The first phase runs from round $1$ to round ${T'=\big(\log (2k/\delta)\big)/{\big(\log\frac{1}{1-\gamma}}\big)}$. For this phase, the subset of bins which have their UCB above $\gamma$ form the subset $\mathcal{C}(t-1)$ of the created bins which are compared against in round $t$, i.e., \begin{align}\label{eqn:c1t} \mathcal{C}(t)=\{x| \gamma<\hat{u}_x(t) , x \in \mathcal{B}(t) \}. \end{align} {In each round $t$, we choose a representative index ${i_r}\in$ Bin $i$ , $\forall i\in\mathcal{C}(t-1)$ and then go over the bins in $\mathcal{C}(t-1)$ one by one, querying the oracle with index pairs of the form ($i_r,t$)}. If we get a positive response from a bin, we place the index $t$ in the corresponding bin. If the replies from all the bins in $\mathcal{C}(t-1)$ is $-1$, we create a new bin with index $t$. We update the empirical estimates $\{\hat{p}_i^t\}$ as well as the UCB and LCBs of the created bins appropriately. The second phase runs from round ${T'=\big(\log (2k/\delta)\big)/{\big(\log\frac{1}{1-\gamma}}\big)}$ onwards. In this phase, we do not create any new bins since the first phase guarantees that a bin corresponding to each element in $S_{\mathcal{P}}^{\gamma}$ has already been created. The goal of this phase is to correctly identify the bins belonging to elements in $S_{\mathcal{P}}^{\gamma}$ from amongst the created bins. Bins for which the corresponding LCB is greater than the threshold $\gamma$ are classified as belonging to $S_{\mathcal{P}}^{\gamma}$; and vice versa for bins with UCB at most $\gamma$. At any round $t$ in this phase, the bins still in contention are those for which the UCB is above $\gamma$ and the LCB is below $\gamma$, and these are the ones that are chosen to form $\mathcal{C}(t)$, i.e., \begin{equation} \label{eqn:c2t} \mathcal{C}(t)=\{x| \hat{l}_x(t)< \gamma<\hat{u}_x(t) , x \in \mathcal{C}(t-1) \}. \end{equation} Similar to the first phase, in round $t$ we go over the bins in $\mathcal{C}(t-1)$ one by one, and then query the oracle to compare the $t^{th}$ sample with a representative element from the current bin. However, unlike the first phase, note that in this phase if we get a negative response from all the bins in $\mathcal{C}(t-1)$, we simply drop the index $t$. The algorithm terminates when $\mathcal{C}(t)$ is empty, i.e., all the bins either have their LCB greater than $\gamma$ or their UCB below $\gamma$. The following lemma claims that Algorithm \ref{QM2_alg} returns the desired set $S_{\mathcal{P}}^{\gamma}$ for any underlying distribution $\mathcal{P}$ under the {QM2} \ model, with probability at least ($1- \delta$). \begin{lemma}{\label{Correctness_QM2}} Given the choice of $\beta^t = \log(4kt^2/\delta)$ for each $t\ge1$, Algorithm \ref{QM2_alg} is a $\delta$-true $\gamma$-threshold estimator under {QM2}. \end{lemma} % % % % % \subsection{Query Complexity Analysis} The following theorem gives an upper bound on the query complexity of our proposed estimator in Algorithm \ref{QM2_alg}. \begin{theorem}\label{QM2ub} Let $\mathcal{A}$ denote the estimator in Algorithm~\ref{QM2_alg} with $\beta^t = \log(4kt^2 / \delta)$ for each $t\ge 1$ and let $Q_{\delta,\gamma}^{\mathcal{P}}(\mathcal{A})$ be the corresponding query complexity for a given distribution $\mathcal{P}$ under {QM2}. We define $q$ as $\min\left\{k,{T'=\big(\log (2k/\delta)\big)/{\big(\log\frac{1}{1-\gamma}}\big)}\right\}$. Then, we have \begin{align*} Q_{\delta,\gamma}^{\mathcal{P}}(\mathcal{A})\leq \sum_{i=1}^{m} \max \Biggl\{ \frac{2e\log \Bigl(\sqrt{\frac{4k}{\delta}}\frac{2}{d^{*}(p_i,\gamma)}\Bigr)}{(e-1).d^{*}(p_i,\gamma)} ,{\frac{\log (2k/\delta)}{\log\frac{1}{1-\gamma}} \Biggr\}} \hspace{0 em} + \sum_{i=m+1}^{q} \frac{2e.\log \Bigl(\sqrt{\frac{4k}{\delta}}\frac{2}{d^{*}(p_i,\gamma)}\Bigr)}{(e-1).d^{*}(p_i,\gamma)}, \end{align*} with probability at least $1-2\delta$. \end{theorem} We essentially argue this as follows. We show that with high probability, each bin created in the course of the algorithm \ref{QM2_alg} corresponding to the support element $i \in \mathcal{S}^{\gamma}_{\mathcal{P}} = \{1,2,...,m\}$ would be out of $\mathcal{C}(t)$ by $\max (T_i,T')$ rounds where $T_i$ is defined as in the argument of Theorem \ref{QM1ub}. Similarly, we show that each bin corresponding to a support element in $\{m+1,...,k\}$ would be out of $\mathcal{C}(t)$ by $T_i$ rounds with high probability. Combining together these two facts gives us the above result, details are provided in the formal proof. The following result provides a lower bound on the expected number of queries for any $\delta$-true $\gamma$-threshold estimator under the {QM2} \ model \begin{theorem}\label{QM2lb} For any $\delta$-true $\gamma$-threshold estimator $\mathcal{A}$ under {QM2}, let $Q_{\delta,\gamma}^{\mathcal{P}}(\mathcal{A})$ be the query complexity. Then, we have $$\mathbb{E}[Q_{\delta,\gamma}^{\mathcal{P}}(\mathcal{A})]\geq \max_{j\in\{m,m+1\}}\Bigg\{\frac{\log{\frac{1}{2.4\delta}}}{2\times d(p_j||\gamma)}\Bigg\}.$$ \end{theorem} The proof of the above result involves constructing a $\delta$-true $\gamma$-threshold estimator $\mathcal{A}'$ for the {QM1} \ model using a $\delta$-true $\gamma$-threshold estimator $\mathcal{A}$ under {QM2}. The lower bound on the query complexity as given in the Theorem \ref{QM2lb} is close to the upper bound in Theorem~\ref{QM2ub} when $\min\{d^{*}(p_m||\gamma),d^{*}(p_{m+1}||\gamma)\} \ll d^{*}(p_i||\gamma)$ $\forall$ $i \notin \{m, m+1\}$ and $T'$ is smaller than $\frac{2e\log \Bigl(\sqrt{\frac{4k}{\delta}}\frac{2}{d^{*}(p_1,\gamma)}\Bigr)}{(e-1).d^{*}(p_1,\gamma)}$. In this case, the terms corresponding to $i=m$ and $i=m+1$ dominate in the upper bound on the query complexity of Algorithm \ref{QM2_alg} as given in Theorem \ref{QM2ub}. We would like to have a lower bound on the query complexity of $\delta$-true $\gamma$-threshold estimators which matches the upper bound more generally and towards this goal, we consider a slightly altered setting which relates closely to the thresholding problem in the Multi Armed Bandit (MAB) setting \cite{MABbook}. \remove{The details are given in Section 1 of the supplementary material.} \remove{ } \section{INTRODUCTION} Estimating the likely `heavy hitters' amongst the possible outcomes of an unknown probability distribution can be a useful primitive for several applications, ranging from clustering and natural language processing to network flow / cache management and online advertising. In this work, we formulate and study a Probably Approximately Correct (PAC) sequential estimation problem in which the learner has access to a stream of independent and identically distributed (i.i.d.) samples from an underlying unknown distribution over a given support set via an oracle which it can query. The goal of the learner is to identify the set of elements in the support of the distribution whose probability value is above a pre-defined threshold. We will henceforth refer to this problem as \textit{threshold-based support identification}. We consider two natural models for oracle queries: \textit{(a) direct query} where the learner provides a sample index and the oracle responds with the value of the corresponding sample; and \textit{(b) pairwise query} where the learner queries the oracle with a pair of indices and the oracle responds with a binary answer confirming whether the sample values are identical or not. Note that in the pairwise query model, the true values of the samples are not revealed. While the former model has been a staple in the online learning literature \cite{devroye2002distribution}, the latter has also received significant attention recently under a wide variety of settings \cite{mazumdar2017clustering, chien2018query, jamieson2011active, mazumdar2016clustering,NIPS2016_6499}. The broad goal of our work is to design query-efficient schemes for these oracle models which can reliably estimate the support elements with probability values above a given threshold. A concrete application of the above setting (and a key motivation for the formulation) can be found in a clustering problem where we have an underlying collection of items which can be partitioned into a given number of clusters based on some inherent property, for example, products in a shopping platform based on category or a population of individuals based on their political preferences. However, unlike the usual setting where the goal is \textit{full clustering}, i.e., mapping each individual item to its corresponding cluster \cite{mazumdar2017clustering,mazumdar2017query}, we consider \textit{partial clustering} where the goal is relaxed to identifying cluster indices with size larger than a certain fraction of the population. Now, say a stream of samples is generated from the population by picking an item uniformly at random in each instant. Then, it is easy to see that the probability of picking an item from a certain cluster is proportional to the size of the cluster and thus, the problem of identifying clusters with size greater than a fraction of the population would correspond to solving the threshold-based support identification problem under the corresponding sampling distribution as mentioned above. Our results provide schemes for performing partial clustering which can have significantly smaller query complexity than the naive approach of performing full clustering and then selecting the appropriate clusters. For example, say we have $n$ items with a ground truth clustering with $k = \Theta(\sqrt{n})$ clusters, where the three largest clusters have size $n^{7/8}$ and the remaining clusters are of size $O(\sqrt{n})$. If we have to identify all the clusters with size more than $n^{3/4}$ with access to a pairwise oracle, Theorem~\ref{QM2ub} shows that this can be performed using $O(n)$ queries whereas the naive approach would require $O(nk) = O(n^{3/2})$ queries \cite{mazumdar2016clustering}. We make the following contributions to understanding the query complexity for this class of sequential estimation problems. For both the query models, we first design sequential algorithms which can provably solve the threshold-based support identification problem with large probability and also provide upper bounds on their query complexity. The estimators are based on maintaining empirical estimates and confidence intervals for the probability values associated with each element of the support. We also provide information-theoretic lower bounds on the query complexity of any reliable estimator under these query models. The bounds presented are instance-specific, i.e., they depend on the underlying probability distribution and the value of the threshold. Finally, we also consider noisy versions of both the direct query as well as the pairwise query models, and propose robust estimators which can effectively counter the noise in the oracle responses. \subsection{Related Work} Estimation of properties of distributions using samples is a direction of work which has a long and rich history. While some of the older works were concerned with the statistical properties of the estimators such as consistency etc., see for example \cite{chernoff1964estimation, parzen62estimation} which study mode estimation, there has been a lot of work recently on characterizing the optimal query complexity for estimating various properties of probability distributions including entropy \cite{caferov2015optimal, acharya2016estimating}, support size and coverage \cite{hao2019data, wu2018sample}, and `Lipschitz' properties \cite{hao2019unified} amongst others. Another related line of work is the `heavy hitter' estimation problem in the context of streaming algorithms \cite{sivaraman2017heavy, bhattacharyya2018optimal, karp2003simple} where given an \textit{arbitrary} stream of samples from a large alphabet, the goal is to identify those symbols whose frequency is above a certain threshold. The metric of performance is usually computational in nature such as the memory size, the number of passes or run time complexity. In contrast to these works, we study the threshold-based support identification problem in the \textit{stochastic} setting and our interest is in deriving instance-specific bounds on optimal query complexity which illustrate the dependence on the underlying distribution. Also, we study the query complexity for reliable estimation under several query models including the pairwise query model which isn't as prevalent in the literature. Online decision making and active learning are also key features of the popular framework of Multi-Armed Bandits (MABs) \cite{MABbook}. In particular, the problem of \textit{thresholding bandits} \cite{locatelli2016optimal} aims to find the set of arms whose mean reward is above a certain threshold, using the minimum number of arm pulls. Thinking of each element in the support set as an arm, the MAB problem is indeed quite related to the setting studied in this work, especially the one with pairwise queries and we explore this relationship in this paper. One key difference between the MAB problem and our setup is that in the former we can choose to pull any arm at each instance, whereas in our problem the arm to be pulled is determined exogenously by the samples generated by the underlying probability distribution. The two lines of work closest to ours in spirit are \cite{mazumdar2017clustering,mazumdar2017query} and \cite{shah2020sequential, 8732224}. The goal in \cite{mazumdar2017clustering,mazumdar2017query} is to fully cluster a collection of items and they characterize the optimal query complexity\footnote{Unlike our work, these results are worst-case and not instance-specific} for this task. In this context, our work corresponds to the less stringent objective of identifying the `significantly large' clusters which might be a natural objective in several unsupervised machine learning applications where we wish to associate labels to a large fraction of the unlabelled dataset and has not been studied before, to the best of our knowledge. On the other hand, \cite{shah2020sequential, 8732224} study the related problems of identifying the top-$m$ clusters and mode of an underlying distribution and find bounds on the optimal query complexity for these tasks. While the broad structure of our algorithms and lower bound techniques are similar, the details differ greatly, for example in the choice of confidence intervals in achievability and alternate instances for the converses. One additional technical challenge that we face due to our different objective is that the number of clusters to be recovered is not fixed apriori (all or one or $m$), but depends on the particular problem instance and this requires careful treatment in the algorithms as well as in the analysis. \section{Proofs} \label{Sec:Proofs} \input{proof_lemma1.tex} \input{proof_theorem1.tex} \input{proof_theorem2.tex} \input{proof_lemma2.tex} \input{proof_theorem3.tex} \input{proof_theorem4.tex} \input{proof_theorem5.tex} \input{proof_lemma3.tex} \input{proof_theorem6.tex} \input{proof_lemma10.tex} \input{proof_ineq.tex} \bibliographystyle{IEEEtran} \section{Thresholding under QM1 noisy setting } \section{Threshold-estimator under {QM2-N}} \label{Sec:QM2N} Recall that in this model, we make pair-wise comparisons between two samples, and the oracle responses are incorrect with a probability of error $p_e$. \subsection{Algorithm} Recall that for the noisy {QM1-N} \ model, we had established an equivalence to the noiseless {QM1} \ model with a modified threshold $\gamma '$. We would like to establish a similar relation of the {QM2-N} \ model to the noiseless {QM2} \ model studied before. But unlike the {QM1} \ and {QM1-N} \ models, where the $k$ distinct bins are available apriori, the bins need to be formed using pairwise queries in the {QM2} \ and {QM2-N} \ models. This represents the key challenge under the {QM2-N} \ model and in spite of the erroneous pairwise queries, we need to find a reliable method to create bins such that with high probability, all indices in a bin correspond to the same element in the support and different bins correspond to different elements. Broadly speaking, our scheme operates in two phases. The objective of the first phase is to extract a collection of bins, each with at least a certain number of indices in it, which includes one corresponding to each element in $\mathcal{S}^{\gamma}_{\mathcal{P}}$. For this phase, we borrow ideas from \cite{mazumdar2017clustering, 8732224} which study the problem of clustering using noisy pairwise queries. The second phase is similar in spirit to the second phase of the estimator for the {QM2} \ model as described in Algorithm~\ref{QM2_alg}. We create and maintain confidence intervals for each bin by comparing a new sample in each round with representative indices from a subset of the bins extracted in the first phase. We compare the confidence intervals thus created with a a modified threshold $\gamma '$ to reliably identify bins corresponding to elements in $\mathcal{S}^{\gamma}_{\mathcal{P}}$. We now describe the two phases of the estimator in some more detail, see Algorithm~\ref{QM2n_alg} for the pseudocode. In the first phase, we consider a natural number $T_0$ (defined as in \eqref{T0_defn}) and form a complete graph $\mathcal{G}$ using the first $T_0$ samples, such that each sample corresponds to a vertex of the graph. We query the oracle for each pair of vertices $i$ and $j$ and assign the oracle response as the weight to the edge between vertices $i$ and $j$. For any subgraph $\mathcal{S}$ of the graph $\mathcal{G}$, let $wt(\mathcal{S})$ denote its weight given by the sum of the weights on all the edges in $\mathcal{S}$. The maximum weighted subgraph (MWS) denotes the subgraph $\mathcal{S}$ corresponding to the largest weight $wt(\mathcal{S})$. Starting with the graph $\mathcal{G}$, we repeatedly extract and remove the MWS, as long as the size of the extracted MWS is greater than $S_0 = \frac{\gamma T_0}{4}$. Corresponding to each such extracted MWS, we create a different bin. Let $\mathcal{C}'(T_0)$ denotes the set of bins formed. We will argue that with high probability, each extracted bin corresponds to a unique element in the support and that there is a bin corresponding to each element in $\mathcal{S}^{\gamma}_{\mathcal{P}}$. The second phase is from round $T_0$ onwards. In this phase, we first choose an index from each bin as a representative element of the bin. In particular, say for each $j\in \mathcal{C}'(T_0)$ we choose index $j_l$ from Bin $j$ as its representative element. For each round $t > T_0$, we consider the $t^{th}$ sample and define $\mathcal{Z}_j^t$ as follows. \begin{equation}\label{indicator_noisy} \mathcal{Z}_j^t= \begin{cases} 1, & \text{if}\ \mathcal{O}(j_l,t)= +1 \\%\text{ for } j_l<T_0 \in \text{ Bin } j\\ 0, & \text{otherwise}. \end{cases} \end{equation} We define $\tilde{\rho}_j^t$ as the fraction of samples with index larger than $T_0$ that belong to Bin $j$, which can be formally written as follows. \begin{equation}\label{eq_noisy} \tilde{\rho}_j^t = \frac{\sum_{r=T_0+1}^{t} \mathcal{Z}_j^r }{t-T_0}. \end{equation} $\mathcal{L}_j(t)$ and $\mathcal{U}_j{(t)}$ denote the lower and upper confidence bounds of Bin $j$ respectively, and are defined as \begin{equation} \mathcal{L}_j(t)= {\min}\{ q \in [0,\tilde{\rho}_j^t]: (t-T_0)\times d(\tilde{\rho}_j^t||q) \leq \beta^t \},\label{eqn_noisylb} \end{equation} \begin{equation} \mathcal{U}_j(t) = {\max}\{ q \in [\tilde{\rho}_j^t,1]: (t-T_0)\times d(\tilde{\rho}_j^t||q) \leq \beta^t \}.\label{eqn_noisyub} \end{equation} In this phase, $\mathcal{C}'(t)$ is defined as \begin{align}\label{eqn:c2tnoise} \mathcal{C}'(t)=\{x| \mathcal{L}_x(t)< \gamma'<\mathcal{U}_x(t) , x \in \mathcal{C}'(t-1) \}. \end{align} where, $\gamma'=(1-2p_e)\gamma+p_e$. In each round $t> T_0$, we go over the bins in $\mathcal{C}'(t-1)$ one by one, and query about the samples ${j_l}$ and $t$, $\forall j\in\mathcal{C}'(t-1)$. We add Sample $t$ to all the bins for which the oracle provides a positive response. In this phase, we also initialize an empty set $\mathcal{S}$, and we update it in each round by adding any bin index $x$ such that $\mathcal{L}_x(t)>\gamma'$. These are the bin indices which the algorithm believes corresponds to elements in $\mathcal{S}_{\mathcal{P}}^{\gamma}$. We run this phase as long as $ \mathcal{C}'(t)$ is non-empty and return the set of bin indices $\mathcal{S}$ upon termination. The choice of the modified threshold $\gamma '$ above follows from the following observation. Consider a bin $j$ in the second phase and say it corresponds to some support element $i$. Then the expected fraction of indices added to each bin $j$ in the second phase by some round $t > T_0$, denoted by $\tilde{\rho}_j^t$, is equal to $(1-p_e)\times p_i + p_e \times (1 - p_i) = (1-2p_e)p_i + p_e$. \remove{ {\color{red} Intuitively, the idea behind choosing $\gamma'$ as $(1-2p_e)\gamma+p_e$ can be expressed as follows. This is because $\mathbb{E}[\mathcal{Z}_j^t]$ = ${p_i}'$ = $(1-2p_e)\times p_i+p_e$ if Bin $j$ contains indices corresponding to support element $i$. Since lower confidence bounds and upper confidence bounds are created with respect to (w.r.t) $\tilde{\rho}_j^t$, it makes more sense to create the termination criterion w.r.t $\gamma'= (1-2p_e)\gamma + p_e$. } } \begin{algorithm}{\label{QM2n_alg}} \footnotesize{ \SetAlgoLined Define $T_0$ as per \eqref{T0_defn} and $S_0= \frac{\gamma.T_0}{4}$\\ $t$= 1 \\ {Create a graph $\mathcal{G}$ with just one node labeled $t$.}\\ \While{$t$ {<} $T_0$}{ {$t=t+1$\\} Create a new node labelled $t$.\\ \remove{. COMMENT: Owing to red line above, won't this create a node for $t = 1$ again Reply: Changed.. } $j = 1$ \\ \While{$j < t$}{ Create an edge of weight $\mathcal{O}(j,t)$ between nodes $j$ and $t$.\\ $j = j + 1$\\ } \remove{$t = t+1$} } Extract Maximum Weighted Sub-graph (say $G'$) from this graph. \While{$|G'|> S_0$}{ Put all the nodes corresponding to $G'$ in a new bin. Remove all nodes from $\mathcal{G}$ which were part of $G'$ and edges which were incident to these nodes.\\ Extract a new Maximum Weighted Sub-graph $G'$ from $\mathcal{G}$.\\ } Denote this extracted set of bins by $\mathcal{C}'(T_0)$ \ForAll{ $j$ $\in$ $\mathcal{C}'(T_0)$}{ Pick representative index $j_l$ $\in$ Bin $j$; } Initialise $\mathcal{S}$ to $\Phi$.\\ \While{$\mathcal{C}'(t)$ $\neq$ $\phi$}{ {$t = t+1$\\} \remove{\color{red}Update $\mathcal{C}'(t)$ according to \eqref{eqn:c2tnoise}.} \ForAll{ $j$ $\in$ $\mathcal{C}'(t-1)$}{ \If{$\mathcal{O}(j_l,t) == +1$}{ Put index $t$ in bin $i$. } } Update the empirical estimate $\tilde{\rho}_j^t$ according to \eqref{eq_noisy} and the confidence bounds $\mathcal{L}_j(t)$ and $\mathcal{U}_j(t)$ according to \eqref{eqn_noisylb} and \eqref{eqn_noisyub} respectively $\forall$ bins $\in$ $\mathcal{C}'(t-1)$. Update $\mathcal{C}'(t)$ according to \eqref{eqn:c2tnoise}.\\ Update $\mathcal{S}$ by adding the bins with $\mathcal{L}_x(t)>\gamma$. \remove{$t = t + 1$} } Output $\mathcal{S}$.\\ \remove{\color{red}This pseudocode needs work. Firstly $b(t)$ should be replaced appropriately by $C'(T_0)$. Also 'forall the' can be replaced by `forall'. Also, I think the various while loops are off by one unit because the $t = t+1$ line comes at end. For eg, the while loop for second phase starts at $t = T_0$ again even though that should have been dealt with in first phase. Also first phase seems to have $T_0 - 1$ samples the way it is written now. Also, text said a list $\mathcal{S}$ is maintained which is updated with any bin with $LCB > \gamma '$ but that is not mentioned here at all. We need to be consistent with the text. This needs a careful read and adjustment.} \caption{Estimator for {QM2-N}} } \end{algorithm} The following lemma claims that Algorithm \ref{QM2n_alg} returns the desired set $S_{\mathcal{P}}^{\gamma}$ for any underlying distribution $\mathcal{P}$ with probability at least $1- \delta$. \begin{lemma}\label{correctness_noisy} Given the choice of $\beta^t = \log (\frac{4k(t-T_0)^2}{\delta})$ for each $t > T_0$, where $T_0$ is as defined in \eqref{T0_defn}, Algorithm \ref{QM2n_alg} is a $\delta$-true $\gamma$-threshold estimator under {QM2-N}. \end{lemma} \subsection{Query complexity Analysis} The following theorem provides an upper bound on the query complexity of our proposed estimator in Algorithm \ref{QM2n_alg}. \begin{theorem}\label{QM2_noisyub} Let $\mathcal{A}$ denote the estimator in Algorithm~\ref{QM2n_alg} with $\beta^t = \log (\frac{4k(t-T_0)^2}{\delta})$ for each $t > T_0$ where $T_0$ is as defined in \eqref{T0_defn}. Let $Q_{\delta,\gamma}^{\mathcal{P}}(\mathcal{A})$ be the corresponding query complexity for a given distribution $\mathcal{P}$ under {QM2-N} \ and define $q = \min\{T_0,k\}$, ${p_i}'= (1-2p_e)\times p_i+p_e$ and $\gamma' = (1-2p_e)\gamma+p_e$. Then we have $$Q_{\delta,\gamma}^{\mathcal{P}}(\mathcal{A}) \leq \Bigl(\sum_{i=1}^{q} \frac{2e.\log \Bigl(\sqrt{\frac{4k}{\delta}}\frac{2}{d^{*}({{p}_i}',\gamma')}\Bigr)}{(e-1).d^{*}({p_i}',\gamma')} + \frac{T_0(T_0-1)}{2} \Bigr)$$ with probability at least $(1- 2\delta)$. \end{theorem} \subsection{Proof of Lemma \ref{first_ineq}}{\label{first_ineq_proof}} Let us restate and prove Lemma \ref{first_ineq}. \begin{lemma* For all $1 \geq p_t, \gamma \geq 0$, the following inequality holds true. $$p_t \log \Bigl(\frac{p_t}{\gamma}\Bigr)+ (2.\gamma) \log\Bigl(\frac{2.\gamma}{p_t + \gamma}\Bigr) \leq 2 d(p_t||\gamma).$$ \end{lemma*} \begin{proof} Consider the function $f(\gamma) = - p_t \log (\frac{p_t}{\gamma-\epsilon})- (2.\gamma) \log(\frac{2.\gamma}{p_t + \gamma}) + 2 d(p_t||\gamma)$. On differentiating the function with respect to $\gamma$, we have $$f'(\gamma) = -\frac{p_t}{\gamma} + \frac{2(1-p_t)}{(1-\gamma)} - 2.\log\Bigl(\frac{2.\gamma}{p_t+\gamma}\Bigr) - \frac{2.p_t}{p_t+\gamma}.$$ Note that the $f'(\gamma) = f(\gamma) = 0$ for $\gamma = p _t$. Now on double differentiating $f(\gamma)$, we have \begin{align*} f''(\gamma) = & \frac{p_t}{\gamma^2} + \frac{2(1-p_t)}{(1-\gamma)^2} - \frac{2.{p_t}^2}{\gamma{(p_t+\gamma)}^2} = \frac{2(1-p_t)}{(1-\gamma)^2} + \frac{p_t({p_t}^2+\gamma^2)}{\gamma^2.{(p_t+\gamma)}^2} \geq 0. \end{align*} Using these results we conclude that $f(\gamma) \geq 0 $ $\forall$ $1 \geq p_t,\gamma \geq 0$, proving our lemma. \end{proof} \subsection{Proof of Lemma \ref{Correctness_QM1}} We use the following lemmas to prove Lemma \ref{Correctness_QM1}. The following lemma is motivated from Lemma 4 in \cite{pmlr-v30-Kaufmann13}. \begin{lemma}\label{lemma_cb} Let $l_i(t)$ and $u_i(t)$ be the lower and upper confidence bounds respectively of bin index $i$ and are defined in equations \eqref{eqnlb} and \eqref{eqnub} respectively. Then, \begin{center} $\mathbb{P}(l_i(t) > p_i) \leq \exp(-\beta^t)$,\\ $\mathbb{P}(u_i(t) < p_i) \leq \exp(-\beta^t)$. \end{center} \end{lemma} \begin{proof} If $l_i(t)=0$, then the corresponding bound is trivial. For $l_i(t) > 0$, we prove $\mathbb{P}(l_i(t) > p_i)\leq \exp(-\beta^t)$. From equation \eqref{eqnlb}, the event $l_i(t)>p_i$ implies that $t\times d(\tilde{p}_i^t||p_i) > \beta^t$. From the properties of continuity and monotonicity of KL-divergence, there exists $x$ such that $p_i < x < \tilde{p}_i^t$ and $t\times d(x||p_i)=\beta^t$. Thus, we have $\mathbb{P}(l_i(t) > p_i) \le $ $\mathbb{P} (\tilde{p}_i^t >x)\overset{(a)}{\leq}\exp(-t\times d(x||p_i))=\exp(-\beta^t)$, where $(a)$ follows from the Chernoff bound for Binomial random variables, see \cite[Section 1.3]{Concentration_Inequalities}. By following similar arguments, we can also prove that $\mathbb{P} (u_i(t) < p_i)\leq \exp(-\beta^t)$. \end{proof} \remove{ {\color{red}Comment: Added this lemma \ref{termination}- Might be needed for arguing termination... Have a look.. REPLY-NK: Let's discuss this separately. I didn't remove this lemma. You may remove it if you feel unimportant. } \begin{lemma}{\label{termination}} Given the choice of $\beta^t = \log(\frac{2kt^2}{\delta})$, there exists positive integer $T_{m}$ such that $t .d(\tilde{p}_i^t||\gamma) > \beta^t$ $\forall$ $t>T_{m}$ with probability 1 for every support element $i$. \end{lemma} \begin{proof} Let us try to compute the probability of the complementary event (denoted by $A^c$) i.e, the probability that there does not exist $T_m$ such that $t.d(\tilde{p}_i^t||\gamma) > \beta^t$ $\forall$ $t>T_{m}$. This event could equivalently expressed as there existing an infinite sequence of $\{t_i\}_{i \in \mathbb{N}}$ such that $t.d(\tilde{p}_i^t||\gamma) \leq \beta^t$ $\forall$ $t \in \{t_i\}_{i \in \mathbb{N}}$. Now, we know that $\frac{\beta^t}{t}$ is decreasing for sufficiently large $t$ and asymptotically goes to 0, thus the above event implies that $\lim_{n \to \infty} d(\tilde{p}_i^{t_n}||\gamma) \leq \lim_{n \to \infty} \frac{\beta^{t_n}}{t_n} = 0$, hence $\lim_{n \to \infty} \tilde{p}_i^{t_i} = \gamma$. Let us attempt to compute the probability of the event $A^c$. \begin{align*} & \mathbb{P}[A^c]\\ \leq & \lim_{n \to \infty} \mathbb{P}[\bigcup_i {t_n}.d(\tilde{p}_i^{t_n}||\gamma) \leq \beta^{t_n}]\\ \overset{(a)}{\leq} & \sum_{i=1}^{k} \mathbb{P}[\lim_{n \to \infty} {t_n}.d(\tilde{p}_i^{t_n}||\gamma) \leq \beta^{t_n}]\\ \overset{(b)}{\leq} & \sum_{i=1}^{k} \mathbb{P}[\lim_{n \to \infty} \tilde{p}_i^{t_n} = \gamma]\\ \overset{(c)}{\leq} & \sum_{i=1}^{k} \lim_{n \to \infty} \exp({t_n}.d(p_i||\gamma))\\ \overset{(d)}{\leq} & 0 \end{align*} Note the inequality $(a)$ follows from continuity of probability measure and union bound. $(b)$ follows from the statement proven in previous paragraph. $(c)$ follows from Chernoff inequality on Bernoulli random variable-section 1.3 in \cite{10.5555/1146355}. $(d)$ follows from the fact that $d(p_i||\gamma) > 0$ $\forall$ $i$ as $p_i \neq \gamma$. \end{proof} } Now we restate and prove Lemma \ref{Correctness_QM1}. \begin{lemma* Given the choice of $\beta^t = \log(2kt^2 / \delta)$ for each $t\ge 1$, Algorithm \ref{QM1_alg} is a $\delta$-true $\gamma$-threshold estimator. \end{lemma*} \begin{proof} \remove{ We first argue the termination of the algorithm. From Lemma \ref{termination}, we know there exists $T_m$ such that $t.d(\tilde{p}_i^t||\gamma) > \beta^t$ $\forall$ $t>T_m$ $\forall$ $i$. This would imply from \eqref{eqnlb} and \eqref{eqnub} that either both $u_i(t)$ and $l_i(t)$ is greater than $\gamma$ or both are less than $\gamma$, thus the algorithm terminates with probability 1. } % \remove{\color{red}Let $\mathcal{E}_i^t$ denote the event that $p_i$ does not lie in [$l_i(t)$, $u_i(t)$] at time $t$.} For each $i \leq m$, let $\mathcal{E}_i^t$ denote the event that $p_i > u_i(t)$ at time $t$. On the other hand, for $i > m$, let $\mathcal{E}_i^t$ denote the event that $p_i < l_i(t)$ at time $t$. From Lemma \ref{lemma_cb}, we have that $\mathbb{P} (\mathcal{E}_i^t) \leq \delta / 2kt^2$. \remove{= \delta / 2kt^2.} Let $\mathcal{E}$ denote the event that there exists a pair ($i$, $t$) such that $p_i$ lies above $u_i(t)$ if $i\leq m$, $t \geq 1$ or $p_i$ lies below $l_i(t)$ if $i>m$, $t \geq 1$.\remove{, $i \in \{1,2,\dots,k\}$.} Then, \begin{equation} \mathbb{P}[\mathcal{E}] = \displaystyle \mathbb{P}[ \bigcup_{i,t} \mathcal{E}_{i}^{t} ] \leq \sum_{i,t} \mathbb{P} [\mathcal{E}_{i}^{t}] \leq \sum_{i,t} \frac{\delta}{2kt^2} \leq \delta. \end{equation} We now argue that if the event $\mathcal{E}^{c}$ holds true, the algorithm will correctly return the desired set of support elements $\mathcal{S}_{\gamma}^{\mathcal{P}}$. The termination condition of the algorithm specifies that for each bin, either the LCB lies above $\gamma$ or the UCB lies below $\gamma$. Since we return the set of all bins which have their LCB above $\gamma$ as the estimate $\widehat{S}$ for $\mathcal{S}_{\gamma}^{\mathcal{P}}$, and the event $\mathcal{E}^{c}$ ensures that for each bin index $i\leq m$, $p_i \leq u_i(t)$, and for each index $i>m$ $p_i \geq l_i(t)$, the correctness of our estimator is guaranteed. In particular, the LCB can be greater than $\gamma$ only for indices $i$ such that $p_i > \gamma$. Similarly, the UCB can be smaller than $\gamma$ only for indices $j$ such that $p_j < \gamma$. Thus, $\mathbb{P}_{\mathcal{P}}[\widehat{S} = \mathcal{S}_{\gamma}^{\mathcal{P}}] \geq \mathbb{P}_{\mathcal{P}}[\mathcal{E}^c]$ $\geq$ $1-\delta$ and hence Algorithm \ref{QM1_alg} is a $\delta$-true $\gamma$-threshold estimator. \remove{\color{red} Comment: Need a line somewhere to argue that the algorithm will terminate. Not very sure whether we can argue that. Have to give more thought...} \end{proof} \subsection{Proof of Lemma \ref{lemma_extract}}{\label{lemma_extract_proof}} We use the following claims to prove Lemma \ref{lemma_extract}. These claims and their proofs are very similar to those in \cite{mazumdar2017clustering, 8732224}. Recall the following terms defined in main paper.\\ $c_1= (\log 2 + 1) $; $c_2 = \frac{3} {4} (1 - 2p_e)^2 $ ; ${k_1}'= \frac{e}{2\pi}$ ; ${k_2}'= \frac{1}{2} \exp (2(1-2p_e)^2)$. Additionally, let $c$ denote the largest root of the equation $e^{x(1-2p_e)^2} = x$. We now define $K'$ as follows. \begin{align}\label{K_prime_defn} K'= \max \Bigl\{c,\frac{2c_1}{c_2} ,\frac{c_1}{2.c_2} + \sqrt{ (1/c_2)(e/(e-1)) \Bigl(\log \Bigl(\frac{2k{k_1}'}{c_2 \delta}\Bigr)+ \Bigl(\frac{c_1^2}{4c_2}\Bigr)\Bigr) }, \nonumber\\ \frac{e}{e-1}\frac{\log\Bigl(\frac{{k_2}'}{ ((1-2p_e)^2)}\sqrt{\frac{2k}{\delta}} \Bigr)}{(1-2p_e)^2}\Bigr\}. \end{align} \begin{claim}\label{comp_subcluster} Consider a graph $\mathcal{G}(\hat{V},\hat{E})$ where $|\hat{V}| \geq K'$ defined in \eqref{K_prime_defn} and edge weights are i.i.d. random variables taking the value $-1$ with probability $p_e$ $< \frac{1}{2}$ and $1$ with probability $(1 - p_e)$. Then, $wt(\mathcal{G}) > wt(\mathcal{G}')$ for any subgraph $\mathcal{G}' \subset \mathcal{G}$, i.e., the MWS extracted from $\mathcal{G}$ will include the entire node set $\hat{V}$ with probability at least $(1- \frac{\delta}{k})$. \end{claim} \begin{proof} We will use the following inequalities in the proof below. \begin{equation}\label{bound1} \mbox{Stirling's inequality \cite{feller1}}: \sqrt{2\pi} n^{n+\frac{1}{2}}.e^{-n} < n! < e.n^{n+\frac{1}{2}}.e^{-n} \ \forall \ n \ge 1. \end{equation} \begin{equation}\label{bound2} \mbox{\cite[Appendix]{Concentration_Inequalities}} : \ \mathbb{P}(X \leq \mathbb{E}[X]-t) \leq \exp\Bigl(-\frac{t^2}{2n}\Bigr), \end{equation} \begin{equation} \text{where } t > 0, X = \sum_{i=1}^{n}X_i \text{ such that } \{X_i\} \text{is a set of i.i.d. radom varibles. } \nonumber \end{equation} Let $S$ be a subset of $\hat{V}$ and we try to compute the probability that the $wt(S)$ is greater than $wt(\hat{V})$. Let us denote the weights of the edge between node $i$ and node $j$ as $w_{ij}$. Then \begin{align*} \mathbb{P} \Big(\sum_{i,j \in \hat{V};i \neq j} w_{ij} < \sum_{i,j \in S; i \neq j ;S \subseteq \hat{V}} w_{ij} \Big) =& \mathbb{P} \Big(\sum_{(i,j) \in (\hat{V},\hat{V});(i,j) \notin (S,S);i \neq j} w_{ij} < 0 \Big)\\ \overset{(a)}{\leq} & \exp\Big( -2 {(1-2p_e)}^2 \Big[ { |\hat{V}| \choose 2} - { S \choose 2} \Big] \Big). \end{align*} Note that $(a)$ follows from \eqref{bound2}.\\ Applying the union bound gives us, \begin{align*} \hspace{-10.0 em}\mathbb{P}(\text{MWS} \neq \hat{V}) \leq &\sum_{|S|=1}^{|\hat{V}|-1} { |\hat{V}| \choose |S|} \mathbb{P}\Big(\sum_{(i,j) \in (\hat{V},\hat{V});(i,j) \notin (S,S);i \neq j} w_{ij} < 0 \Big)\\ \leq &\sum_{|S|=1}^{|\hat{V}|-1} { |\hat{V}| \choose |S|} \exp\Big( -2 {(1-2p_e)}^2 \Big[ { |\hat{V}| \choose 2} - { |S| \choose 2} \Big] \Big) \\ = & \sum_{|S|=1}^{\frac{|\hat{V}|}{2}} { |\hat{V}| \choose |S|} \exp\Big( -2 {(1-2p_e)}^2 \Big[ { |\hat{V}| \choose 2} - { |S| \choose 2} \Big] \Big) \\ & + \sum_{|S|= \frac{|\hat{V}|}{2}+1}^{|\hat{V}|-1} { |\hat{V}| \choose |S|} \exp\Big( -2 {(1-2p_e)}^2 \Big[ { |\hat{V}| \choose 2} - { |S| \choose 2} \Big] \Big) \\ \overset{(b)}{\leq} & \sum_{|S|=1}^{\frac{|\hat{V}|}{2}} { |\hat{V}| \choose \frac{|\hat{V}|}{2}} \exp\Bigl(-(1-2p_e)^2 \Bigl( \frac{3|\hat{V}|^2}{4} - \frac {|\hat{V}|}{2} \Bigr)\Bigr)\\ &+ \sum_{|S|=\frac{|\hat{V}|}{2}+1}^{|\hat{V}|} { |\hat{V}| \choose {|\hat{V}|-1}} \exp(-2(1-2p_e)^2 \Bigl( |\hat{V}| - 1 \Bigr) \Bigr)\\ \hspace{-0em} \overset{(c)}{\leq} & \frac{|\hat{V}|}{2} \frac{e}{\pi} \frac{2^{| \hat{V}|}}{\sqrt{|\hat{V}|}} \exp( \Bigl(-(1-2p_e)^2 \Bigl( \frac{3|\hat{V}|^2}{4} - \frac {|\hat{V}|}{2} \Bigr)\Bigr) \Bigr)\\ &+{k_2}' |\hat{V}|^2 \exp(-2(1-2p_e)^2(|\hat{V}|)) \\ \overset{(d)} {\leq} & {k_1}' \sqrt {|\hat{V}|} \exp(|\hat{V}| (\log 2 + 1) - (1 - 2p_e)^2 . \frac{3} {4} {|\hat{V}|^2}))\\ &+{k_2}' |\hat{V}|^2 \exp(-2(1-2p_e)^2(|\hat{V}|))\\ \overset{(e)}{\leq}& \frac{\delta}{2k} + \frac{\delta}{2k} \leq \frac{\delta}{k}. \end{align*} The inequality for the first term in $(b)$ follows since $\sum_{|S|=1}^{\frac{|\hat{V}|}{2}} { |\hat{V}| \choose |S|} \exp\Big( -2 {(1-2p_e)}^2 \Big[ { |\hat{V}| \choose 2} - { |S| \choose 2} \Big] \Big)$ takes maximum value at $|S| = \frac{|\hat{V}|}{2}$. The inequality at second term in $(b)$ can be shown by arguing that term $\sum_{|S|=\frac{|\hat{V}|}{2}+1}^{|\hat{V}|} { |\hat{V}| \choose {|\hat{V}|-1}} \exp(-2(1-2p_e)^2 \Bigl( |\hat{V}| - 1 \Bigr) \Bigr) $ takes maximum value at $S = |\hat{V}| - 1$ which we show below. Consider the function \begin{align*} f(a) = &{ |\hat{V}| \choose {|\hat{V}|-a}} \exp\Biggl(-2(1-2p_e)^2 \Biggl( {|\hat{V}| \choose 2} - {(|\hat{V}|-a) \choose 2} \Biggr) \Biggr)\\ = & { |\hat{V}| \choose {|\hat{V}|-a}} \exp((-(1-2p_e)^2) (2a|\hat{V}| - a^2+a)). \end{align*} We wish to show that the maximum of $f(a)$ occurs at $a = 1$. After the requisite algebraic simplification, \begin{align*} \frac{f(a)}{f(a+1)} = \frac{a+1}{|\hat{V}|-a} \frac{e^{2(1-2p_e)^2|\hat{V}|}}{e^{(1-2p_e)^2(2a+2)}} \overset{(f)}{\geq} \frac{2}{|\hat{V}|-1} \frac{e^{2(1-2p_e)^2|\hat{V}|}} {e^{(1-2p_e)^2(2.(\frac{|\hat{V}|}{2}-1)+2)}} \geq \frac{2}{|\hat{V}|} e^{(1-2p_e)^2|\hat{V}|} \overset{(g)}{\geq} 1. \end{align*} Note that $(f)$ follows on minimising each fraction individually. $(g)$ follows from the fact that $c$ is the largest solution of $e^{(1-2p_e)^2x} = x$ which implies that $e^{(1-2p_e)^2|\hat{V}|} > |\hat{V}|$ for $|\hat{V}| > c$. Therefore, $f(a)$ is a decreasing function of $a$ and takes maximum value at $a=1$. The inequality for first term in $(c)$ follows on applying \eqref{bound1} whereas for the second term follows on applying ${k_2}'$ = $(1/2)\exp(2(1-2p_e)^2)$. The inequality at $(d)$ follows by bounding $\exp((1-2p_e)^2\frac{|\hat{V}|}{2})$ with $\exp(|\hat{V}|)$. Now let us prove the inequality on first term in $(e)$ by proving \begin{equation*} {k_1}' \sqrt {|\hat{V}|} \exp\bigg(|\hat{V}| (\log 2 + 1) - (1 - 2p_e)^2 . \frac{3} {4} {|\hat{V}|^2}\bigg) \leq \frac{\delta}{2k}. \end{equation*} Since $|\hat{V}| > 2.\frac{c_1}{c_2}$ and $\frac{c_1}{c_2}>1$, $\sqrt {|\hat{V}|} < \Bigl(|\hat{V}|-\frac{c_1}{2.c_2}\Bigr)^2$. Now consider the first term in inequality in $(d)$. \begin{align*} {k_1}' \sqrt {|\hat{V}|} \exp\bigg(|\hat{V}|& (\log 2 + 1)- (1 - 2p_e)^2 . \frac{3} {4} {|\hat{V}|^2}\bigg) = {k_1}' \sqrt {|\hat{V}|} \exp(c_1|\hat{V}| - c_2 {|\hat{V}|^2})\\ \overset{(j)}{\leq} & {k_1}' \Bigl(|\hat{V}|-\frac{c_1}{2.c_2}\Bigr)^2 \exp\Bigl(\frac{c_1^2}{4c_2}\Bigr) \exp\Bigl(-c_2 \Bigl(|\hat{V}|-\frac{c_1}{2.c_2}\Bigr)^2 \Bigr) \overset{(l)}{\leq} \frac{\delta}{2} \end{align*} $(j)$ follows from $\sqrt {|\hat{V}|} < \Bigl(|\hat{V}|-\frac{c_1}{2.c_2}\Bigr)^2$. Let us now prove the inequality in $(l)$. We can say that \begin{align*} & \hspace{-0em} |\hat{V}| > \frac{c_1}{2.c_2} + \sqrt{\frac{e}{c_2(e-1)} \bigg(\log \Bigl(\frac{2k{k_1}'}{c_2 \delta}\Bigr)+ \Bigl(\frac{c_1^2}{4c_2}\Bigr)\bigg)} \\ & \hspace{-0em} \Rightarrow - c_2\Bigl(|\hat{V}| - \frac{c_1}{2.c_2}\Bigr)^2 < -\frac{e}{e-1} \bigg(\log \Bigl(\frac{2k{k_1}'}{c_2 \delta}\Bigr)+ \Bigl(\frac{c_1^2}{4c_2}\Bigr)\bigg)\\ & \hspace{-0em} \overset{(h)}{\Rightarrow} -c_2\Bigl(|\hat{V}|-\frac{c_1}{2.c_2}\Bigr)^2 < W_{-1} \Bigl(\frac{c_2.\delta}{2k{k_1}'}\exp\Bigl(-\frac{c_1^2}{4c_2}\Bigr)\Bigr)\\ & \hspace{-0em} \overset{(i)}{\Rightarrow} -c_2 \Bigl(|\hat{V}|-\frac{c_1}{2.c_2}\Bigr)^2 \exp \Bigl(-c_2 \Bigl(|\hat{V}|-\frac{c_1}{2.c_2}\Bigr)^2 \Bigr) > -c_2 \frac{\delta}{2k{k_1}'}\exp\Bigl(-\frac{c_1^2}{4c_2}\Bigr)\\ & \hspace{-0em} \Rightarrow {k_1}' \Bigl(|\hat{V}|-\frac{c_1}{2.c_2}\Bigr)^2 \exp\Bigl(\frac{c_1^2}{4c_2}\Bigr) \exp\Bigl(-c_2 \Bigl(|\hat{V}|-\frac{c_1}{2.c_2}\Bigr)^2 \Bigr) < \frac{\delta}{2k}. \end{align*} Recall that $W_{-1}$ is the lower root in lambert function as defined in the proof of Theorem 1 of our paper. Now using Theorem 3.1 of \cite{Lambert}, we say that $W_{-1}(-\frac{c_2.\delta}{2k{k_1}'}.\exp(-\frac{c_1^2}{4c_2}) )$ is lower bounded by $-(e/(e-1)) (\log (\frac{2k{k_1}'}{c_2 \delta})+ (\frac{c_1^2}{4c_2}))$. This would in turn imply the implication in $(h)$. Note that the implication in $(i)$ follows from the the fact that $W_{-1}$ is the lower root of the lambert function. Thus for $|\hat{V}| > \max\Bigl(\frac{c_1}{2.c_2} + \sqrt{ (1/c_2)(e/(e-1)) (\log (\frac{2k{k_1}'}{c_2 \delta})+ (\frac{c_1^2}{4c_2})) },\frac{2.c_1}{c_2},c\Bigr) $, the inequality in $(l)$ is proven. Therefore, the first term in $(e)$ is upper bounded by $\frac{\delta}{2k}$. Now consider the second term on the inequality in $(e)$. We can say the following: \begin{align*} & |\hat{V}| > \frac{e}{e-1}\frac{\log\Bigl(\frac{{k_2}'}{ (1-2p_e)^2}\sqrt{\frac{2k}{\delta}} \Bigr)}{(1-2p_e)^2}\\ \Rightarrow & -(1-2p_e)^2 |\hat{V}| < \frac{e}{e-1}\log\Bigl(\frac{{k_2}'}{ (1-2p_e)^2}\sqrt{\frac{2k}{\delta}} \Bigr)\\ \overset{(m)}{\Rightarrow} & -(1-2p_e)^2 |\hat{V}| < W_{-1}\Bigl(-\frac{((1-2p_e)^2)}{{k_2}'}\sqrt{\frac{\delta}{2k}} \Bigr)\\ \overset{(n)}{\Rightarrow} & (-(1-2p_e)^2|\hat{V}| \exp(-(1-2p_e)^2|\hat{V}|) > -\frac{((1-2p_e)^2)}{{k_2}'}\sqrt{\frac{\delta}{2k}} \\ \Rightarrow & |\hat{V}| \exp(-(1-2p_e)^2|\hat{V}|`) < \frac{1}{{k_2}'}\sqrt{\frac{\delta}{2k}}\\ \Rightarrow & {k_2}' |\hat{V}|^2 \exp(-2(1-2p_e)^2(|\hat{V}|)) < \frac{\delta}{2k}. \end{align*} Note that the implication in $(m)$ follows from theorem 3.1 of \cite{Lambert} which implies that the value of $W_{-1}\Bigl((\frac{((1-2p_e)^2)}{{k_2}'}\sqrt{\frac{\delta}{2k}} \Bigr) \Bigr)$ is lower bounded by $\frac{e}{e-1}\log\Bigl(\frac{{k_2}'}{ ((1-2p_e)^2)}\sqrt{\frac{2k}{\delta}} \Bigr)$. The implication in $(n)$ follows from the definition of $W_{-1}$ similar to the reasoning in $(i)$. Thus, the second inequality in $(e)$ is proven implying that the claim is also proven. \end{proof} Now we state and prove the next claim which would be used to prove Lemma \ref{lemma_extract}. \begin{claim}\label{no_overlap} Consider a graph $G'$ whose vertices are partitioned into multiple clusters. The weight of edges between any pair of nodes in the same cluster are random variables which take value $-1$ with probability $p_e$ and $1$ with probability $(1-p_e)$. Also weight of edges between two nodes which does not lie in the same cluster takes value $1$ with probability $p_e$ and $-1$ with probability $(1-p_e)$. We assume that all the weights of the edges are independent.\\ Let S be the MWS of $G'$. If $ |S| \Bigl(1+\frac{33\log (\frac{2}{\delta})}{(1-2p_e)^2}\Bigr) $ then we can say with probability at least $(1-\delta)$ that it can not contain nodes from multiple sub-clusters. \end{claim} \begin{proof} Let S be a sub-component contain nodes from at least two sub-clusters. Let the clusters be denoted by $V_i$ and we denote $C_i=S \cap V_i$ and $j* = \argmin_{i:C_i \neq \phi} |C_i|$. Let the weight of the edge in the graph between the nodes $i$ and $j$ be denoted by $w_{ij}$. We claim that $$\sum_{i,j \in S,i<j} w_{ij} < \sum_{i.j \in S \textbackslash C_{j*} , i<j } w_{ij} $$ with probability at least $(1-\delta)$. The above condition is equivalent to $$\sum_{i,j \in C_{j*},i<j} w_{ij} + \sum_{i \in S, j \in S \textbackslash C_{j*} } w_{ij} < 0$$ We use the following equations from appendix of \cite{Concentration_Inequalities} in the proof. \begin{equation}{\label{ ineq_1}} \mathbb{P}(X>(1+\epsilon)\mathbb{E}[X])< \exp\Bigl(-\frac{\epsilon^2}{3} \mathbb{E}[X]\Bigr) \text{ } 0<\epsilon<1. \end{equation} \begin{equation}{\label{ ineq_2}} \mathbb{P}(X<(1-\epsilon)\mathbb{E}[X])< \exp\Bigl(-\frac{\epsilon^2}{3} \mathbb{E}[X]\Bigr) \text{ } 0<\epsilon<1.\end{equation} where $ X = \sum_{i} X_i$ such that $\{X_i\}$ is a set of i.i.d. random variables. We divide the proof into two cases. \textbf {Case 1:} $|C_{j*}| > \sqrt{\frac{108}{1-2p_e} \log (\frac{2}{\delta})}$\\ Now \begin{align*} \mathbb{P}\Bigg( \sum_{i,j \in C_{j*},i<j} w_{ij}> \Big(1+\frac{1}{3}\Big) (1-2p_e) {|C_{j*}| \choose 2} \Bigg) \overset{(a)}{\leq} & \exp\Bigg(-(1/3)^3 (1-2p_e) {|C_{j*}| \choose 2}\Bigg)\\ < & \exp\bigg(-(1/3)^3 (1-2p_e) \frac{|C_{j*}|^2}{4} \bigg) \leq \delta / 2. \end{align*} $(a)$ follows from \eqref{ ineq_1} by putting $\epsilon = 1/3$. \begin{align*} \mathbb{P}\Bigl( \sum_{i \in C_{j*}, j \in S \textbackslash C_{j*} } w_{ij}> -(1-\frac{1}{3}) (1-2p_e) |C_{j*}| |S \textbackslash C_{j*}|\Bigr) \overset {(b)} {\leq} & \exp(-(1/3)^2 (1-2p_e) |C_{j*}| |S \textbackslash C_{j*}|)\\ \overset {(c)} {\leq} & \exp(-(1/3)^3 (1-2p_e) \frac{|C_{j*}|^2}{2}) \leq \delta /2. \end{align*} The inequality in $(b)$ holds from \eqref{ ineq_1} and the inequality in $(c)$ holds due to $|S \textbackslash C_{j*}| > |C_{j*}|$ since $C_{j*}$ is the smallest cluster. Now we apply union bound on the previous two proven events and can say with probability at least $(1-\delta)$. \begin{align*} \sum_{i,j \in C_{j*},i<j} w_{ij} + \sum_{i \in C_{j*}, j \in S \textbackslash C_{j*} } w_{ij} \leq & \Bigl((4/3) (1-2p_e) {|C_{j*}| \choose 2} - (2/3) (1-2p_e) |C_{j*}| |S \textbackslash C_{j*}|\Bigr) \\ \leq &\Bigl((4/3) (1-2p_e) \frac{|C_{j*}|^2}{2} -(2/3) (1-2p_e) |C_{j*}| |C_{j*}|\Bigr)\leq 0. \end{align*} \textbf {Case 2:} $|C_{j*}|< \sqrt{\frac{108}{1-2p_e} \log (\frac{2}{\delta})}$\\ \begin{align*} \mathbb{P}\Bigl( \sum_{i \in C_{j*}, j \in S \textbackslash C_{j*} } w_{ij}> -(1-\frac{1}{2}) (1-2p_e)& |C_{j*}| |S \textbackslash C_{j*}|\Bigr)\\ \leq &\exp(-(1/2)^2 (1/3) (1-2p_e) |C_{j*}| |S \textbackslash C_{j*}|)\\ \overset {(d)} {\leq} & \exp(-(1/2)^2 (1/3) (1-2p_e) (|S|-1) ) \overset {(e)} {\leq} \delta /2. \end{align*} The inequality $(d)$ follows since $|C_{j*}| |S \textbackslash C_{j*}|$ $\geq$ $(|S|-1)$. The inequality $(e)$ follows since \begin{align*} |S| \geq & \Bigl(1+\frac{33\log (\frac{2}{\delta})}{(1-2p_e)^2}\Bigr) \geq \Bigl(1+\frac{12\log (\frac{2}{\delta})}{(1-2p_e)^2}\Bigr). \end{align*} Now take $|C_{j*}| = x$. Hence, $$\sum_{i,j \in C_{j*},i<j} w_{ij} \leq \frac{x^2}{2}.$$ Thus, we say with probability at least (1- $\delta$) that \begin{align*} \sum_{i,j \in C_{j*},i<j} w_{ij} + \sum_{i \in C_{j*}, j \in S \textbackslash C_{j*} } w_{ij} &\leq \frac{x^2}{2} - (1-2p_e) |C_{j*}| |S \textbackslash C_{j*}|/2`\\ &\leq x^2 - (1/2) (1-2p_e) x(|S|-x)\\ &\leq x (\frac{3x}{2} - (1/2) (1-2p_e) |S|) \overset{(f)}{<} 0. \end{align*} The inequality at $(f)$ is true since \begin{align*} |S| > \Bigl(1+\frac{33\log (\frac{2}{\delta})}{(1-2p_e)^2}\Bigr)\geq \frac{3 \sqrt{\frac{108}{1-2p_e} \log (\frac{2}{\delta})}}{1-2p_e}. \end{align*} Thus we say with probability at least $(1-\delta)$ that the MWS contains points from a single cluster. \end{proof} \begin{claim}{\label{new_claim}} Consider a support element $a$ with less than $S_0$ samples denoting it in the graph. Consider another support element $b$ with at least than $2S_0$ samples denoting it. The probability that the weight of the sub-graph which is a subset of the samples corresponding to the support element $a$ is smaller than the weight of the sub-graph containing all the samples corresponding to the support element $b$ with probability at least $(1-\frac{\delta}{16k})$. \end{claim} \begin{proof} Denote the nodes corresponding to a support element $a$ as a cluster $c_a$ and denote its subset as $s_{c_a}$. Similarly, we denote the nodes corresponding to a support element $b$ as $c_b$. We denote the weights of edges between nodes $i$ and $j$ as $w_{ij}$. We consider the probability that $\sum_{i,j \in s_{c_a}} w_{ij} > \sum_{i,j \in c_b} w_{ij}$. \begin{align*} \mathbb{P}[\sum_{i,j \in {s_{c_a}}} w_{ij} > \sum_{i,j \in c_b} w_{ij}] \leq & \mathbb{P}[\sum_{i,j \in c_b} w_{ij} - \sum_{i,j \in s_{c_a}} w_{ij}<0]\\ \overset{(a)}{\leq} &\exp\Bigl(-\frac{1}{3} \mathbb{E}\Bigl[\sum_{i,j \in c_b} w_{ij} - \sum_{i,j \in s_{c_a}} w_{ij}\Bigr]\Bigr)\\ \overset{(b)}{\leq} & \exp(-\frac{1}{6} (1-2p_e) ((|c_b|-1)^2-|s_{c_a}|^2))\\ \overset{(c)}{\leq} & \exp(-\frac{1}{2} (1-2p_e) {{S_0}^2}) \overset{(d)}{\leq} \frac{\delta}{16k} \end{align*} Note that $(a)$ follows from \eqref{ ineq_2} and substituting $\epsilon=1$. $(b)$ follows since $\mathbb{E}\Bigl[\sum_{i,j \in c_b} w_{ij} - \sum_{i,j \in s_{c_a}} w_{ij}\Bigr] = (1-2p_e) (\frac{(|c_b|)(|c_b|-1)}{2}- \frac{(|s_{c_a}|)(|s_{c_a}|-1)}{2}) \leq \frac{1}{2}(1-2p_e) ((|c_b|-1)^2-|s_{c_a}|^2)$. $(c)$ follows since minimum value of $|c_b|$ is $2S_0$ whereas maximum value of $|s_{c_a}|$ is $(S_0-1)$, thus $((|c_b|-1)^2-|s_{c_a}|^2)$ is lower bounded by $3{S_0}^2$. $(d)$ follows since $S_0 \geq \Bigl(1+\frac{33\log (\frac{16k}{\delta})}{(1-2p_e)^2}\Bigr)$. \end{proof} Let us restate and prove Lemma \ref{lemma_extract}. \begin{lemma* The set of extracted bins from the graph $\mathcal{G}$ at the end of the first phase, denoted by $\mathcal{C}'(T_0)$, satisfies the following properties with probability at least $\Bigl(1-\frac{5\delta}{16}\Bigr)$. \begin{enumerate} \item No bin contains samples corresponding to two different support elements. \item All the support elements which have at least $2S_0$ samples corresponding to it in the first phase have an extracted bin representing it. \remove{\color{red} the bin contains all the samples denoting a support element.} \end{enumerate} \end{lemma*} \begin{proof} Let $\tilde{K}$ be defined by substituting $\frac{\delta}{8}$ for $\delta$ in the expression of $K'$ in \eqref{K_prime_defn}. By substituting $\frac{\delta}{8k}$ for $\delta$ in Claim \ref{no_overlap}, we can say any extracted Maximum Weighted SubGraph (MWS) of size larger than $\Bigl(1+\frac{33\log (\frac{16k}{\delta})}{(1-2p_e)^2}\Bigr)$ can have indices corresponding to multiple support element with probability at most $\frac{\delta}{8k}$. Consider each extracted MWS of size larger than $S_0$. Since, $S_0 > \Bigl(1+\frac{33\log (\frac{16k}{\delta})}{(1-2p_e)^2}\Bigr)$, we say that this MWS extracted has indices representing only a support element with probability at least $(1-\frac{\delta}{8k})$. Consider all support elements (denoted by $\tilde{S}_{min}$) with less than $S_0$ indices denoting it. Consider all support elements (denoted by $\tilde{S}_{max}$) with more than $2S_0$ indices denoting it. We argue that the events in Claim \ref{new_claim} and Claim \ref{comp_subcluster} (substituting $\frac{\delta}{8}$ for $\delta$) and Claim \ref{no_overlap} (substituting $\frac{\delta}{8k}$ for $\delta$) would imply for each MWS extracted, we can say that no MWS representing an element in $\tilde{S}_{min}$ would occur till MWS corresponding to all support elements in $\tilde{S}_{max}$ have been extracted. Suppose not. Consider that MWS corresponding to some support element in $\tilde{S}_{min}$ occurs before all elements in $\tilde{S}_{max}$ have occurred in some MWS created in previous rounds. Since there are some other elements in $\tilde{S}_{max}$ not a part of MWS extracted, it would imply that a subset of all indices denoting some support element in $\tilde{S}_{min}$ has higher weight than the sub-graph corresponding to the support element in $\tilde{S}_{max}$ implying event in Claim $\ref{new_claim}$ is violated. Now the event that no MWS representing an element in $\tilde{S}_{min}$ occurs till MWS corresponding to all support elements in $\tilde{S}_{max}$ have been extracted and events in Claim \ref{new_claim} and Claim \ref{comp_subcluster} (substituting $\frac{\delta}{8}$ for $\delta$) and Claim \ref{no_overlap} (substituting $\frac{\delta}{8k}$ for $\delta$) imply that extraction of MWS does not stop till all elements in $\tilde{S}_{max}$ have been extracted in some MWS. Suppose not. This would imply that we get an MWS of size less than $S_0$ before all elements in $\tilde{S}_{max}$ have been put in some MWS implying the event that some element in $\tilde{S}_{min}$ occurs MWS before all support elements in $\tilde{S}_{max}$ have been extracted as Claim $\ref{comp_subcluster}$ holds true for all support elements of size larger than $S_0$. Now the probability of the events described in Claim \ref{new_claim} and Claim \ref{comp_subcluster} (substituting $\frac{\delta}{8}$ for $\delta$) and Claim \ref{no_overlap} (substituting $\frac{\delta}{8k}$ for $\delta$) can be union bounded over all support elements to argue that the probability is at least $(1-\frac{5\delta}{16})$. Thus, we argue that both the events in theorem hold true with probability at least $(1-\frac{5\delta}{16})$. \remove{ Consider a support element $i$ which has at least $S_0$ samples denoting it. Since $S_0 \geq \tilde{K}$, we can say that there would exist no MWS which contains only some (not all) samples of support element $i$ with probability at least $(1-\frac{\delta}{8k})$ by substituting $\frac{\delta}{8}$ for $\delta$ in Claim \ref{comp_subcluster}. Thus with probability at least $(1-\frac{\delta}{8k})$, any MWS which contains support element $i$ would have size at least $S_0$ implying that it would be extracted from the graph and have a bin corresponding to it. However we have a total of $k$ clusters in the graph. Union bounding both the events described above for all the clusters present in the graph, we can say both the properties in Lemma \ref{all_occur} hold true with probability at least $(1- \frac{\delta}{4})$.} \remove{\color{red}I didn’t get the reason for this.} \end{proof} \subsection{Proof of Lemma \ref{Correctness_QM2}} We use the following lemmas to complete the proof. The first lemma shows that for each index in $\mathcal{S}^{\gamma}_{\mathcal{P}} = \{1,2,\ldots,m\}$, at least one bin corresponding to it is created in the first phase with high probability, while the second lemma bounds the probability of misclassification of any index $i$. Finally, we argue that two bins corresponding to the same index cannot be returned as part of the estimate $\widehat{S}$ of $\mathcal{S}^{\gamma}_{\mathcal{P}}$ and use the union bound to upper bound the total probability of error of the proposed algorithm. \begin{lemma}{\label{lemma1:QM2}} The probability of the event that an element from the index set $\mathcal{S}^{\gamma}_{\mathcal{P}} =\{1,2,...,m\}$ does not have any bin corresponding to it after the first phase of Algorithm \ref{QM2_alg} is bounded by $\delta/2$. \end{lemma} \begin{proof} The first phase runs for the first $T' = \frac{\log (\delta/2k)}{\log(1-\gamma)}$ rounds. Consider an element $i$ $\in$ $\{1,2,3,...,m\}$. The probability that $X_t \neq i$ for any $t\ge1$ is equal to ($1-p_i$) $<$ $(1-\gamma)$. Since the samples $X_l$ are i.i.d. $\forall$ $l \in \{1,2,...,T'\}$, we can say that the probability that $X_l \neq i$ $\forall$ $l \in \{1,2,...,T'\}$ is bounded by $(1-\gamma)^{T'}$ $\leq$ $\frac{\delta}{2k}$. Applying union bound over all the $m$ elements in $\mathcal{S}^{\gamma}_{\mathcal{P}}$, the probability that some element in $\{1,2,...,m\}$ does not have any bin corresponding to it after $T'$ rounds is bounded by $\frac{m\delta}{2k} \leq \frac{\delta}{2}$. \end{proof} \remove{ {\color{red} Changed the lemma and its proof as your suggestion. I feel it has become a bit simpler. However instead of restricting $p_i$ in $[l_i,u_i]$, restricted $p_i$ below $u_i$ for $i\leq m$ and $p_i$ above $l_i$ for $i > m$. This would reduce a factor of 2 inside $\log$ in beta expression if we do it in {QM1} \ as well.} } \begin{lemma}{\label{lemma2:QM2}} For a support element $i\leq m$, define $\mathcal{E}_i^t$ as the event that ${p}_i$ lies above the UCB $u_i(t)$ (defined in \eqref{eqnlb}). Similarly, for any support element $j > m$, define $\mathcal{E}_j^t$ as the event that ${p}_j$ lies below the LCB $l_i(t)$ (defined in \eqref{eqnub}). Then, a bin corresponding to support element $i$ can be misclassified by the algorithm \remove{at some round }only if the event ${\mathcal{E}}_i^t$ holds true for some $t$. \end{lemma} \begin{proof} % Before we begin, we need to distinguish between two related quantities. For a bin $b(i)$ corresponding to support element $i$, $\hat{p}_{b(i)}^t$ as defined in equation \eqref{emp_QM2} denotes the fraction of the samples till round $t$ which are placed in the bin; on the other hand, $\tilde{p}_i^t$ as defined in equation \eqref{eq1} denotes the total fraction of samples till round $t$ corresponding to support element $i$. These two can in general be different since during the course of the algorithm, multiple bins can get created corresponding to same support element. Next, let $m_u(i)$ denote the $u^{th}$ bin created corresponding to support element $i$. \textbf{Case 1: $i\leq m$ }: % % We prove the contrapositive statement here. The event $({\mathcal{E}}_i^t)^c$ $\forall$ $t$ would imply that ${p}_i$ would be less than $u_i(t)$ $\forall$ $t$ which would imply that the first bin corresponding to support element $i$ could never be classified below $\gamma$. As the first bin corresponding to support element $i$ cannot be classified below $\gamma$, multiple bins cannot be created for support element $i$ as per Algorithm \ref{QM2_alg}. This is because multiple bins can be created for a support element only if all previous bins corresponding to the same support element have been classified below $\gamma$. Now the empirical probability of the first bin for support element $i$ $(\hat{p}_{m_1(i)}^t)$ is same as the empirical probability of support element $i$ $(\tilde{p}_i^t)$ implying that $\hat{u}_{m_1(i)}(t) = u_{i}(t)$ . Thus, the event $({\mathcal{E}}_i^t)^c$ $\forall$ $t$ would imply that the first and only bin corresponding to support element $i$ is never misclassified. \textbf{Case 2: $i>m$}: Suppose the $l^{th}$ bin corresponding to support element $i$, $m_l(i)$ is misclassified at round $t$, i.e., the LCB corresponding to the bin ${\hat{l}_{m_l(i)}}(t) > \gamma$. We can say $\hat{p}_{m_l(i)}^t \leq {\tilde{p}}_i^t$ where equality would hold true iff $l = 1$. Now $\hat{p}_{m_l(i)}^t \leq \tilde{p}_i^t$ would imply that ${\hat{l}_{m_l(i)}}(t)$ $\leq$ ${l_i}(t)$. Thus ${\hat{l}_{m_l(i)}}(t) > \gamma$ would imply ${l_i}(t) \geq \gamma > p_i$ implying that event $\mathcal{E}_i^t$ occurs. % \end{proof} % Now we restate and prove Lemma $\ref{Correctness_QM2}$. % \begin{lemma* Given the choice of $\beta^t = \log(4kt^2/\delta)$ for each $t\ge1$, Algorithm \ref{QM2_alg} is a $\delta$-true $\gamma$-threshold estimator under {QM2}. \end{lemma*} \begin{proof} We first argue that there can be no two bins returned as part of the estimate $\widehat{S}$ of $\mathcal{S}^{\gamma}_{\mathcal{P}}$ can correspond to the same support element. We argue this as follows. Suppose there exists such a pair $B_1$ and $B_2$, then both these bins must have been created in the first phase. This is possible only if one of the bins, say $B_1$ was not in $\mathcal{C}(t)$ in the round $t$ when the other bin $B_2$ was created. This would imply that $B_1$ was classified as being below $\gamma$ in the first phase, which would contradict the fact that both the bins were returned. Next, let $\mathcal{E}_1$ denote the event that some element in $\mathcal{S}^{\gamma}_{\mathcal{P}} = \{1,2,...,m\}$ is not present in any of the bins. From Lemma \ref{lemma1:QM2}, we have $\mathbb{P}[\mathcal{E}_1] < \delta/2$. Next, let $\mathcal{E}_2$ denote the event that there exists a misclassified bin corresponding to some support element $i$. From Lemma \ref{lemma2:QM2}, this would imply that $\mathcal{E}_i^t$ occurs for some $(i,t)$ pair. However for $i\leq m$, $\mathcal{E}_i^t$ implies $u_i(t) > p_i$ whose probability can be bounded by Lemma \ref{lemma_cb} to be at most $\frac{\delta}{4kt^2}$. Similarly, for $i>m$, $\mathcal{E}_i^t$ implies $l_i(t)<p_i$ whose probability can be bounded by Lemma \ref{lemma_cb} to be at most $\frac{\delta}{4kt^2}$. {Taking the union bound over all such pairs $(i,t)$, we obtain $\mathbb{P}[\mathcal{E}_2]$ $\leq$ $\frac{\delta}{2}$}. \remove{ {\color{red} Comment: how? what is the probability for a given pair $(i,t)$, before you take sum ? Reply: Added in the description. } } % We can see that Algorithm \ref{QM2_alg} returns an incorrect set of bins only if at least one of the two events $\mathcal{E}_1$, $\mathcal{E}_2$ has occurred. Applying the union bound on events $\mathcal{E}_1$ and $\mathcal{E}_2$, we get that the probability of Algorithm \ref{QM2_alg} returning an incorrect set of bins is bounded by $\delta$. \end{proof} \subsection{Proof of Lemma \ref{correctness_noisy}} Let us now define the variable $T_0$ which represented the number of rounds in the first phase of Algorithm \ref{QM2n_alg}. To define $S_0$, we use the following new variables $c_1= (\log 2 + 1) $; $c_2 = \frac{3} {4} (1 - 2p_e)^2 $ ; ${k_1}'= \frac{e}{2\pi}$ ; ${k_2}'= \frac{1}{2} \exp (2(1-2p_e)^2)$. Additionally, let $c$ denote the largest root of the equation $e^{x(1-2p_e)^2} = x$. Then, $T_0$ is defined\footnote{If the expression in equation \eqref{T0_defn} is not integer, choose the smallest integer greater than or equal to it.} as follows: \begin{align} T_0 = \frac{4}{\gamma} \max \Bigg\{ c, \frac{2c_1}{c_2} ,\frac{c_1}{2.c_2} + &\sqrt{ (1/c_2)(e/(e-1)) (\log \Bigl(\frac{16k{k_1}'}{c_2 \delta}\Bigr)+ \Bigl(\frac{c_1^2}{4c_2}\Bigr)\Bigr) },\nonumber \\ &\hspace{0.75in}\frac{e}{e-1}\frac{\log\Bigl(\frac{{k_2}'}{ ((1-2p_e)^2)}\sqrt{\frac{16k}{\delta}} \Bigr)}{(1-2p_e)^2}, \Bigl(1+\frac{33\log (\frac{16k}{\delta})}{(1-2p_e)^2}\Bigr) \Bigg\} .{\label{T0_defn}} \end{align} The above definition for $T_0$ is a result of the various constraints that come up while proving the lemmas below. Also, recall that we define $S_0 = \gamma T_0 / 4$. We use the following lemmas to prove Lemma \ref{correctness_noisy}. \begin{lemma}{\label{lemma_extract}} The set of extracted bins from the graph $\mathcal{G}$ at the end of the first phase, denoted by $\mathcal{C}'(T_0)$, satisfies the following properties with probability at least $\Bigl(1-\frac{5\delta}{16}\Bigr)$. \begin{enumerate} \item No bin contains samples corresponding to two different support elements. \item All the support elements which have at least $2S_0$ samples corresponding to it in the in the first phase have an extracted bin representing it. \remove{\color{red} the bin contains all the samples denoting a support element.} \end{enumerate} \end{lemma} \remove{\color{red}This lemma follows from the ideas used in \cite{mazumdar2017clustering, 8732224}. We move the proof the above lemma to supplementary material.} The proof of this lemma follows from ideas presented in \cite{mazumdar2017clustering, 8732224}. We move the proof to Section~\ref{lemma_extract_proof}. \begin{lemma}\label{all_occur} With probability at least $(1 - \frac{\delta}{16})$, for each support element $i$ which belongs to $\mathcal{S}^{\gamma}_{\mathcal{P}}$, and thus has a probability value above $\gamma$, at least $2S_0$ corresponding samples with value $i$ would have been seen by the end of the first phase after $T_0$ rounds. \end{lemma} \begin{proof} We use the following inequality in our proof which follows from appendix of \cite{Concentration_Inequalities}. \begin{equation}{\label{ ineq_2}} \mathbb{P}(X<(1-\epsilon)\mathbb{E}[X])< \exp\Bigl(-\frac{\epsilon^2}{3} \mathbb{E}[X]\Bigr) \text{ } 0<\epsilon<1.\end{equation} where $ X = \sum_{i} X_i$ such that $\{X_i\}$ is a set of i.i.d. random variables For any support element $i$ in $\mathcal{S}^{\gamma}_{\mathcal{P}}$, the number of samples, say $N^i_{T_0}$, seen by the end of $T_0$ rounds with value $i$ satisfies the following: % \begin{align*} \mathbb{P}\Big(N^i_{T_0} \le 2S_0\Big) = \mathbb{P}\Big(N^i_{T_0} \le \frac{\gamma T_0}{2}\Big)\overset{(a)}{\leq} \mathbb{P}\Big(N^i_{T_0} \le \frac{\mathbb{E}[N^i_{T_0}]}{2}\Big) &\overset{(b)}{\leq} \exp(-\mathbb{E}[N^i_{T_0}] / 12)\\&\overset{(c)}{\leq} \exp(-\gamma T_0 / 12)\overset{(d)}{\leq} \delta/16k. \end{align*} % where $(a)$ and $(c)$ follow from $\mathbb{E}[N^i_{T_0}] \ge \gamma T_0$ for any $i \in \mathcal{S}^{\gamma}_{\mathcal{P}}$; $(b)$ follows from \eqref{ ineq_2} by substituting $\epsilon = \frac{1}{2}$ \remove{\color{red}which version of the bound is this? refer to it as discussed before Comment - SS : updated}and $(d)$ follows since from equation \eqref{T0_defn}. % \begin{align*} \frac{\gamma T_0}{12} \geq \ \frac{1}{3}\cdot \Bigl(1+\frac{33\log (\frac{16k}{\delta})}{(1-2p_e)^2}\Bigr) > \ {\log \Bigl(\frac{16k}{\delta}\Bigr)}. \end{align*} % The lemma follows by taking the union bound over all the support elements in $\mathcal{S}^{\gamma}_{\mathcal{P}}$. \end{proof} Now we restate and prove Lemma \ref{correctness_noisy}. \begin{lemma* Given the choice of $\beta^t = \log (\frac{4k(t-T_0)^2}{\delta})$ for each $t > T_0$, where $T_0$ is as defined in \eqref{T0_defn}, Algorithm \ref{QM2n_alg} is a $\delta$-true $\gamma$-threshold estimator under {QM2-N}. \end{lemma*} \begin{proof} Let $\mathcal{E}$ denote the event that Algorithm \ref{QM2n_alg} correctly identifies the support elements in $\mathcal{S}^{\gamma}_{\mathcal{P}}$. Also, let $\mathcal{E}_1$ and $\mathcal{E}_2$ be the events that the properties in Lemmas~\ref{lemma_extract} and \ref{all_occur} respectively are satisfied. Then, we have $$\mathbb{P}[\mathcal{E}^c] \leq \mathbb{P}[\mathcal{E}^c|(\mathcal{E}_1 \cap \mathcal{E}_2)] + \mathbb{P}[(\mathcal{E}_1 \cap \mathcal{E}_2)^c].$$ From Lemmas~\ref{lemma_extract} and \ref{all_occur}, we have $$ \mathbb{P}[(\mathcal{E}_1 \cap \mathcal{E}_2)^c] = \mathbb{P}[\mathcal{E}_1^c \cup \mathcal{E}_2^c] \le \frac{\delta}{2}.$$ What remains is to show that $\mathbb{P}[\mathcal{E}^c|(\mathcal{E}_1 \cap \mathcal{E}_2)] \le \delta / 2$. Henceforth, assume that the events $\mathcal{E}_1$ and $\mathcal{E}_2$ hold true. Note that this implies that when bins are extracted at the end of the first phase of Algorithm \ref{QM2n_alg} after $T_0$ rounds, there will be a unique bin corresponding to each element in $\mathcal{S}^{\gamma}_{\mathcal{P}}$. There might be additional bins corresponding to other support elements as well. Next, we consider the second phase of the algorithm where the goal is to identify the bins corresponding to support elements in $\mathcal{S}^{\gamma}_{\mathcal{P}}$. As done in the second phase of Algorithm \ref{QM2_alg} for {QM2}, for each round $t > T_0$, we compare the $t^{th}$ sample with a fixed representative element chosen from each bin belonging to a subset $\mathcal{C}'(t)$. Again similar to Algorithm \ref{QM2_alg}, confidence intervals are maintained for each bin and eventually those bins for which the LCB becomes larger than a threshold are identified as the ones corresponding to support elements in $\mathcal{S}^{\gamma}_{\mathcal{P}}$. The only differences between the second phases of Algorithms \ref{QM2_alg} and \ref{QM2n_alg} are in the values of the empirical estimates and the confidence intervals associated with each bin as well as the value of the threshold against which they are compared. Recall that for $t > T_0$ and a bin $j$ representing support element $i$, $\tilde{\rho}_j^t$ defined in equation \eqref{eq_noisy} represents the fraction of samples since the beginning of the second phase for which the oracle provided a positive response when queried with the representative index from bin $j$. Note that $\tilde{\rho}_j^t$ is a running average of a sequence of i.i.d Bernoulli random variables, each with expected value ${p_i}'$= $p_i\times(1-p_e) + p_e\times(1-p_i) = (1-2p_e)\times p_i + p_e$. Thus as before, Lemma \ref{lemma_cb} applies and can be used to devise the confidence bounds $\mathcal{L}_j(t)$ and $\mathcal{U}_j(t)$ for ${p_i}'$. Finally, the modified threshold is given by $\gamma '$ = $(1-2p_e)\gamma + p_e$ and the bins whose LCB becomes larger than $\gamma '$ will be classified as corresponding to elements from $\mathcal{S}^{\gamma}_{\mathcal{P}}$. Given the similarities of the two schemes, the arguments for proving the correctness of the above scheme run exactly parallel to the ones made in Lemma \ref{Correctness_QM2} for Algorithm \ref{QM2_alg} and we skip them here for brevity. \end{proof} \remove{ \begin{lemma}\label{correctness_cond_noisy} Given that the events $\mathcal{E}_1$ and $\mathcal{E}_2$ occurred, for the choice of ${\beta}^t = \log \Bigl(\frac{4k(t-T_0)^2}{\delta}\Bigr)$ $\forall \ t > T_0$, Algorithm when terminates returns the desired set of bins with probability at least $\Bigl(1- \frac{\delta}{2}\Bigl)$ \end{lemma} \begin{proof} Note that the event $\epsilon_1$ and $\epsilon_2$ imply that there is a unique distinct bin corresponding to each support element in $\{1,2,...,m\}$. We might have some bins corresponding to other support elements as well. Recall that in this phase of the algorithm we compare each new element with a fixed representative element chosen from each bin. Recall the indicator random variable $\mathcal{Z}_j^t$ as defined in \ref{indicator_noisy} for $t > T_0$. Therefore, $\mathbb{E}[\mathcal{Z}_j^t]$ = ${p_i}'$= $p_i\times(1-p_e) + p_e\times(1-p_i) = (1-2p_e)\times p_i + p_e$ where $i$ denotes the support element that indices less than $T_0$ in bin $j$ represent. We claim that Lemma \ref{lemma_cb} applies in our scenario for each bin where the confidence bounds are replaced by $\mathcal{L}_j(t)$ and $\mathcal{U}_j(t)$ respectively, the fraction of indices larger than $T_0$ in Bin $j$ post Round $T_0$ is $\tilde{\rho}^t_j$ and probability of a new index $t>T_0$ being classified in Bin $j$ is ${p_i}'$ where $i$ denotes the support element that indices in Bin $j$ less than $T_0$ represent. This is true because $\tilde{\rho}_j^t = \frac{\sum_{r=T_0}^{t} \mathcal{Z}_j^r }{t-T_0}$ where $\mathcal{Z}_j^r$ denotes a set of i.i.d random variables for each $j$ with expectation ${p_i}'$ which would be sufficient for proving Lemma \ref{lemma_cb} in our scenario. Thus the setting is similar to our {QM1} and by replacing $\gamma$ by $\gamma'$ and using similar arguments of Lemma \ref{Correctness_QM2}, we prove Lemma \ref{correctness_cond_noisy}. \end{proof} Recall the events $\epsilon_1$ and $\epsilon_2$ defined in Lemmas \ref{correctness_cond_noisy} respectively. Let $\epsilon$ denote the event that the algorithm when terminates, returns a correct set of bins. Using conditional probability, we can show that $\mathbb{P}[\epsilon^c] \leq \mathbb{P}[\epsilon^c|(\epsilon_1 \cap \epsilon_2)] + \mathbb{P}[(\epsilon_1 \cap \epsilon_2)^c] \leq \mathbb{P}[\epsilon^c|(\epsilon_1 \cap \epsilon_2)] + \mathbb{P}[\epsilon_1^{c} \cup \epsilon_{2}^{c}] \leq \mathbb{P}[\epsilon^c|(\epsilon_1 \cap \epsilon_2)] + \mathbb{P}[\epsilon_1^{c}] + \mathbb{P}[\epsilon_{2}^{c}].$ We use Lemma \ref{correctness_cond_noisy} to bound $\mathbb{P}[\epsilon^c|(\epsilon_1 \cap \epsilon_2)]$ by $\frac{\delta}{2}$, Lemma \ref{lemma_extract} to bound $\mathbb{P}[\epsilon_1^{c}]$ by $\frac{\delta}{4}$ and Lemma \ref{all_occur} to bound $\mathbb{P}[\epsilon_2^{c}]$ by $\frac{\delta}{4}$. Thus, we bound the probability of the algorithm returning an incorrect set of bins by ${\delta}$. \end{proof} } \subsection{Proof of Theorem \ref{QM1ub}} We use the following lemma to prove Theorem \ref{QM1ub} which effectively characterises the number of rounds by which a bin numbered $i$ is classified, i.e. either its LCB goes above $\gamma$ or UCB goes below $\gamma$. \begin{lemma}\label{lemma_exittime} Let $T_i$ be the smallest positive integer such that $\forall$ $t > T_i$ the condition $t \times d^{*} (p_i,\gamma) >\beta^t$ is satisfied. For any $t > T_i$, the bin corresponding to support element $i$ is not classified as either above $\gamma$ or below $\gamma$ after $t$ rounds with probability at most $\exp(-\beta^{t})$. \end{lemma} \begin{proof} Consider the event that a bin numbered $i$ for which $p_i < \gamma$ is not yet classified after $t > T_i$ rounds. If this happens, the upper confidence bound $u_i(t)$ is still above $\gamma$ and the lower confidence bound $l_i(t)$ is still below $\gamma$. From equation \eqref{eqnlb} and \eqref{eqnub}, the event $l_i (t) < \gamma < u_i (t)$ implies that $t \times d(\tilde{p}_i^{t}||\gamma) <\beta^{t}$. \remove{ Hence, \begin{align*} \mathbb{P}(l_i (T_i)<\gamma < u_i (T_i)) \ \leq \ & \mathbb{P}(T_i \times d(\tilde{p}_i^{T_i}||\gamma)<\beta^{T_i}) \end{align*} } {This implies that there exists $y$ such that $y < \gamma$ and $y < \tilde{p}_i^{t}$ such that $t \times d(y||\gamma) =\beta^{t}$. On the other hand, from the definition of $T_i$ in the statement of the lemma and given $p_i < \gamma$ and $t>T_i$, we have $y>p_i$. Thus, we have $p_i < y < \min\{\gamma, \tilde{p}_i^{t}\}$. Given the series of implications mentioned above, we have the following series of inequalities: \begin{align} \nonumber \mathbb{P}(l_i (t)<\gamma < u_i (t) ) \ \leq & \ \mathbb{P} (t \times d(\tilde{p}_i^{t}||\gamma) <\beta^{t}) \ \leq \ \mathbb{P}(\tilde{p_i}^{t} >y ) \ \leq \ \exp(-t \times d(y||p_i)) \label{eqn:ineq1} \end{align} % where, the last inequality follows from the Chernoff bound for Binomial random variables, see \cite[Section 1.3]{Concentration_Inequalities}. % Since $t \times d^{*} (p_i,\gamma) >\beta^{t}$ and {$t \times d(y||\gamma) =\beta^{t}$}, we have $t \times d(y||p_i) >\beta^{t}$. Then, \remove{from equation \eqref{eqn:ineq1}}we have $$ \mathbb{P}(l_i(t) <\gamma < u_i (t) ) \ \leq \ \exp(-\beta^{t}), $$ % thus proving the statement of the lemma for all bin indices $i$ such that $p_i < \gamma$. Similar arguments can be used to prove the result for the bins $j$ with $p_j > \gamma$. } \end{proof} \remove{\color{red} Comments: I have some doubts on the proof of Lemma 6 as written here. Had some suggestions which I highlighted in red. I believe $T_i$ should be bounded by the larger root of the equation not smaller root and the function is not decreasing $\forall$ $t$ only decreases for sufficietly large $t$.} \begin{lemma}\label{lemma_timeupper} Given $\beta^t = \log(2kt^2/ \delta)$ for $t \ge 1$, let $T_i$ be the smallest positive integer such that $\forall$ $t > T_i$ the condition $t \times d^{*} (p_i,\gamma) >\beta^t$ is satisfied. Then, setting $a_i = d^{*}(p_i,\gamma)/2$ and $b = \log(2k /\delta) / 2$, we have % $$ T_i \le \frac{e(b-\log(a_i))}{(e-1)a_i} . $$ \end{lemma} \begin{proof} % % % % % % Since $\frac{\beta^t}{t} = \frac{\log(2kt^2/ \delta)}{t}$ is decreasing in $t$ for sufficiently large $t$. \remove{\color{red}sufficiently large $t$ Comment NK- Checking manually for small $t$, it seems it is always decreasing..so are there multiple roots for this eqn Reply - SS: Yeah, there are two roots for this equation in most of the cases. Upto a very small value of $t=t_0$ the function increases very fast-, then rapidly decays. However $t_0$ is less than 2 (worst case for $k=1,\delta=1$), }Thus, it is clear that $T_i$ is upper bounded by the largest root $r^*$ of the equation $t \times d^{*} (p_i,\gamma) = \log(2kt^2 / \delta)$. Letting $a_i$ = $d^{*}({p}_i,\gamma)/2$, $b$ = $\log(\frac{2k}{\delta}) / 2$, this largest root is given by $r^* = \frac{-1}{a_i}\times W_{-1}(-a_i e^{-b})$ where $W_{-1}(y)$ provides the smallest root of $xe^x=y$ for $y < 0$ and denotes the Lambert function \cite{Lambert}. From \cite[Theorem 3.1]{Lambert}, we have $W_{-1}(y)> -\frac{e}{e-1}\log(-y)$ and thus $T_i \le r^* \le \frac{e(b-\log(a_i))}{(e-1)a_i}$. This concludes the proof of the lemma. \remove{ Consider the equation $t \times d^{*} (p_i,\gamma) = \log(2kt^2 / \delta)$ which can be written as $t\times a_i = b+\log t$ and can be solved as $\frac{-1}{a_i}\times W(-a_i e^{-b})$ where $a_i$ = $d^{*}({p}_i,\gamma)/2$, $b$ = (1/2)* $\log(\frac{2k}{\delta})$, and W denotes Lambert function. Note that the lambert function denotes roots for the equation $xe^x=y$ as a function of $y$. Note that the Lambert function takes 2 values for $y<0$ and let $W_{-1}(y)$ denote its smaller root of equation $xe^x=y$ (only defined for $y<0$). Using Theorem 3.1 of \cite{Lambert}, $W_{-1}(y)>-\frac{e}{e-1}\log(-y)$ and $xe^x>y$ $\forall x<W_{-1}(y)$. By applying this to $\frac{-1}{a_i}\times W_{-1}(-a_i e^{-b})$, we can say it is upper bounded by $\frac{e(b-\log(a_i))}{(e-1)a_i}$. Note that $T_i$ as defined in Lemma \ref{lemma_timeupper} is $W_{-1}(-a_i e^{-b})$ which has been upper bounded by $\frac{e(b-\log(a_i))}{(e-1)a_i}$. {\color{red} The above proof is currently in a really convoluted form and has to have a simpler exposition. It should be a simple thing. Please take another pass, even though I have a sense of what the argument is, its been written in such a winded form that I can't follow it} } \end{proof} Now, we will restate and prove Theorem \ref{QM1ub}. \begin{theorem* Let $\mathcal{A}$ denote the estimator in Algorithm~\ref{QM1_alg} with $\beta^t = \log(2kt^2 / \delta)$ for each $t\ge 1$ and let $Q_{\delta,\gamma}^{\mathcal{P}}(\mathcal{A})$ be the corresponding query complexity for a given distribution $\mathcal{P}$ under {QM1}. Then, we have $$Q_{\delta,\gamma}^{\mathcal{P}}(\mathcal{A})\leq \max_{j\in\{m,m+1\}} \Biggl\{\frac{2e\log \Bigl(\sqrt{\frac{2k}{\delta}}\frac{2}{d^{*}(p_j,\gamma)}\Bigr)}{(e-1)d^{*}(p_j,\gamma)} \Biggr\},$$ with probability at least $1-\delta$. \end{theorem*} \begin{proof} \remove{ {\color{red}Comment: Before editing the proof here, I want to understand two things: a) Why is the probability in the below paragraph $\frac{\delta}{2k{T_i}^2}$ and not $\frac{\delta}{4k{T_i}^2}$; and (b) why do we target the non-classification probability by $T_i$ for bin $i$ to be $\frac{\delta}{2k{T_i}^2}$ and not $\frac{\delta}{2k}$. Shouldn't this be sufficient since just a union bound over the various bins is needed and this bound will also suffice.} } From Lemmas \ref{lemma_exittime} and \ref{lemma_timeupper}, we have that for each $i \in \{1,2,\ldots,k\}$, the probability that bin $i$ has its UCB above $\gamma$ and LCB below $\gamma$ beyond $\frac{e.(b-\log(a_i))}{(e-1).a_i}$ rounds is bounded by $\frac{\delta}{2k{T_i}^2}$. Here, $a_i$ = $d^{*}({p}_i,\gamma)/2$ and $b = \frac{1}{2} \cdot \log(\frac{2k}{\delta})$. Taking the worst case number of rounds and applying the union bound over all the $k$ bins, we get that the probability that all bins have been classified by $\max_{i\in [1,k]} \frac{e.(b-\log(a_i))}{(e-1).a_i}$ rounds is greater than or equal to $1-\delta$. It can be verified that $\frac{e.(b-\log(x))}{(e-1)x}$ is decreasing in $x$. Since $a_m \leq a_j$ $\forall$ $j$ $<$ $m$ and $a_{m+1} \leq a_j$ $\forall$ $j$ $>$ $m+1$, the expression for query complexity can be simplified from $\max_{i\in [1,k]} \frac{e.(b-\log(a_i))}{(e-1).a_i}$ to $\max\Bigl\{\frac{e.(b-\log(a_m))}{a_m.(e-1)},\frac{e.(b-\log(a_{m+1}))}{a_{m+1}.(e-1)}\Bigr\}$. \remove{ {\color{red}. \\ COMMENT: Doesn't the above statement need that the expression for upper bound on $T_i$ be decreasing in $a_i$? Is that obvious? We can check that $\frac{e.(b-\log(a_i))}{a_i.(e-1)}$ is decreasing with $a_i$ by differentiating as long as it is greater than 0. } } \end{proof} \subsection{Proof of Theorem \ref{QM1lb}}{\label{Sec:Thm2_proof}} The following lemma follows from the proof of \cite[Theorem3]{shah2019sequentialME} and provides a recipe for deriving lower bounds on the query complexity of $\delta$-true $\gamma$-threshold estimators. The proof of this lemma follows along similar lines as that for \cite[Theorem3]{shah2019sequentialME} which is based on standard change of measure arguments \cite{kaufmann2016complexity}, and is skipped here for brevity. \begin{lemma}{\label{shah_paper}} For any $\delta$-true $\gamma$-threshold estimator $\mathcal{A}$, let $\tau$ be the stopping time of the algorithm. Then, we have \begin{equation*} \mathbb{E}_\mathcal{P}[\tau]\geq \frac{\log{\frac{1}{2.4\delta}}}{\displaystyle \inf_{\mathcal{P}': S_{\mathcal{P}}^{\gamma} \neq S_{\mathcal{P}'}^{\gamma}}D(\mathcal{P}||\mathcal{P}')} \end{equation*} \end{lemma} Now we restate and prove Theorem \ref{QM1lb}. \begin{theorem* For any $\delta$-true $\gamma$-threshold estimator $\mathcal{A}$ under {QM1}, let $Q_{\delta,\gamma}^{\mathcal{P}}(\mathcal{A})$ be the query complexity. Then, we have $$\mathbb{E}[Q_{\delta,\gamma}^{\mathcal{P}}(\mathcal{A})]\geq \max_{j\in\{m,m+1\}}\Bigg\{\frac{\log{\frac{1}{2.4\delta}}}{d(p_j||\gamma)}\Bigg\}.$$ \end{theorem*} \begin{proof} We show that $\mathbb{E}[Q_{\delta,\gamma}^{\mathcal{P}}(\mathcal{A})]\geq \frac{\log{1 / 2.4\delta}}{d(p_m||\gamma)}$, the other inequality follows similarly. Lemma~\ref{shah_paper} above requires a choice of distribution $\mathcal{P}'$ such that $S_{\mathcal{P}}^{\gamma} \neq S_{\mathcal{P}'}^{\gamma}$. For some small $\epsilon > 0$, we choose $\mathcal{P}'$ as follows: \begin{align*} p'_m=\gamma-\epsilon,\quad \text{ and } p'_i=\frac{1-\gamma+\epsilon}{1-p_m}p_i , \ \forall \ i\neq m. \end{align*} Then, we have % \begin{align*} D(\mathcal{P}||\mathcal{P}') &= p_m \log\left(\frac{p_m}{\gamma - \epsilon}\right) + \sum_{i \neq m} p_i \log\left(\frac{p_i}{\frac{1-\gamma+\epsilon}{1-p_m}p_i}\right) \\ &= p_m \log\left(\frac{p_m}{\gamma - \epsilon}\right) + (1-p_m)\log\left(\frac{1 - p_m}{1 - \gamma + \epsilon}\right)\overset{(a)}{\approx} d(p_m||\gamma), \end{align*} % where $(a)$ follows since $\epsilon$ can be made arbitrarily small. Then, from Lemma~\ref{shah_paper}, we have $$ \mathbb{E}[Q_{\delta,\gamma}^{\mathcal{P}}(\mathcal{A})] \geq \frac{\log{\frac{1}{2.4\delta}}}{d(p_m||\gamma)}. $$ % \remove{ We can similarly prove the other lower bound as well.} \end{proof} \subsection{Proof of Theorem \ref{QM2ub}} Recall that we defined $a_i = d^{*}({p}_i,\gamma)/2$ and $b = \frac{1}{2} \cdot \log(\frac{4k}{\delta})$. We use the following lemmas to prove Theorem \ref{QM2ub}. \remove{ \begin{lemma}{\label{union_bound_error_for_all_t}} Let $u_i(t)$ be defined as in $\eqref{eqnub}$. Then given any support element $i$, the probability that $\exists \ t>\frac{e(b-\log(a_i))}{(e-1)a_i}$ such that $u_i(t) > \gamma$ is bounded by $\frac{\delta}{2}$. \end{lemma} \begin{proof} Let $K_i = \frac{e(b-\log(a_i))}{(e-1)a_i}$. Then, \begin{align*} \mathbb{P} [\exists\ t>K_i \text{ s.t } u_i(t) > \gamma] \overset{(a)}{\leq} & \sum_{t=K_i+1} \mathbb{P} [u_i(t) > \gamma]\\ \overset{(b)}{\leq} & \sum_{t=K_i+1} \exp(-\beta^{t})\\ \leq & \frac{\delta}{2k} \end{align*} % where $(a)$ follows from the union bound and {\color{red}$(b)$ follows from Lemma \ref{lemma_exittime}. COMMENT: I don't see how?} \end{proof} } \remove{ \begin{lemma}{\label{union_bound_error_for_all_t}} Let $l_i(t)$ and $u_i(t)$ be as defined in equations \eqref{eqnlb} and \eqref{eqnub} respectively. Then given any support element $i>m$\remove{and $(\mathcal{E}_i^t)^c$ (defined in Lemma \ref{lemma2:QM2}) occurs $\forall$ $i,t$}, the probability that $\exists \ t>\frac{e(b-\log(a_i))}{(e-1)a_i}$ such that $u_i(t) > \gamma>l_i(t)$ is bounded by $\frac{\delta}{2k}$. \end{lemma} \begin{proof} Note that $l_i(t)$ and $u_i(t)$ denote the lower and upper confidence bounds for $p_i$ and involve $\tilde{p}_i^t$ which as defined in equation \eqref{eq1} denotes the total fraction of samples till round $t$ corresponding to support element $i$. Let $K_i = \frac{e(b-\log(a_i))}{(e-1)a_i}$. Then, \begin{align*} \mathbb{P} [\exists\ t>K_i \text{ s.t } u_i(t) > \gamma>l_i(t)] \overset{(a)}{\leq} & \sum_{t=K_i+1}^{\infty} \mathbb{P} [u_i(t) > \gamma>l_i(t)]\\ \overset{(b)}{\leq} & \sum_{t=K_i+1}^{\infty} \exp(-\beta^{t})\\ \leq & \frac{\delta}{2k} \end{align*} % where $(a)$ follows from the union bound and $(b)$ follows from Lemmas \ref{lemma_exittime} and \ref{lemma_timeupper}. \remove{COMMENT: I don't see how? Reply: $(b)$ follows since $l_i(t)<\gamma$, thus not classified. Thus from Lemma \ref{lemma_exittime} the probability of the bin not being classified after $t$ rounds is bounded by $\exp(-\beta^t)$.} \end{proof} } \remove{\color{red}Comment (SS) : Slightly changed the wordings in the lemma to make the proof more clear. I think it would be good if the wordings in proof of theorem 3 also reflects this change. Added a sentence to reflect this slight change. Highlighted those in red.} \begin{lemma}{\label{queries with each box}} \remove{Given that \remove{event $(\mathcal{E}_i^t)^c$ (defined in Lemma \ref{lemma2:QM2}) occurs $\forall$ $i,t$} the algorithm correctly returns all the bins,} Each of the following statements is true with probability at most $\frac{\delta}{k}$. \begin{itemize}{\Roman{enumii}} \item The total number of queries with all the bins representing support element $i\leq m$ is greater than $\max\left\{\frac{e(b-\log(a_i))}{(e-1)a_i},T'\right\}$ and the algorithm {correctly classifies all the bins\remove{\color{red} with no misclassification at any round}.}\remove{corresponding to support element $i$} \item The total number of queries with all the bins representing support element $i>m$ is greater than $\frac{e(b-\log(a_i))}{(e-1)a_i}$ and the algorithm correctly classifies all the bins\remove{\color{red} with no misclassification at any round}. \end{itemize} \end{lemma} \begin{proof} \remove{\color{red}Comment: Edited the proofs as per our discussion. } {Consider any bin which contains indices representing support element $i$.}\\ \remove{We know from Lemma \ref{lemma2:QM2} that $(\mathcal{E}_i^t)^c$ $\forall$ $i,t$ implies that the algorithm correctly returns the desired set of bins.} \begin{enumerate} \item $ i \leq m$: Let us denote the bin with samples representing support element $i$ as $m_i$. All bins corresponding to support element $i$ being correctly classified and $i \leq m$ would imply that Bin $m_i$ would be classified above $\gamma$. According to Algorithm \ref{QM2_alg}, no bin classified above $\gamma$ would have another bin corresponding to the same support element created again. Therefore, $m_i$ is the first and last bin created for support element $i$ implying $\hat{p}_{m_i}^t=\tilde{p}_i^{t}$. \remove{\color{red} Then Lemma \ref{lemma_exittime} tells us that after $\frac{e(b-\log(a_i))}{(e-1)a_i}$ rounds, Bin $m_i$ would have LCB below $\gamma$ and UCB above $\gamma$ with probability at most $\delta/ 2k$. However we know that no bin with UCB above $\gamma$ comes out of $\mathcal{C}(t)$ before $T'$ rounds. {Thus with probability at most $\delta/ 2k$, we say the bin $m_i$ would not exit the set $\mathcal{C}(t)$ after \\ $\max\left\{\frac{e(b-\log(a_i))}{(e-1)a_i},T'\right\}$ queries with bins representing support element $i$ and the algorithm correctly classifies $m_i$. \remove{the set of bins corresponding to support element $i$.}}} At round ${T_i}' = \max\left\{\frac{e(b-\log(a_i))}{(e-1)a_i},T'\right\}$, Algorithm \ref{QM2_alg} would have certainly proceeded to the second phase. Hence, the event that bin $m_i$ does not drop out of the subset of bins $\mathcal{C}(t)$ against which new samples are compared after ${T_i}'$ rounds would imply that the condition in equation \eqref{eqn:c2t} is satisfied after ${T_i}'$ rounds. This requires ${l}_i({T_i}') <\gamma < {u}_i({T_i}')$, which from Lemma \ref{lemma_exittime} and Lemma \ref{lemma_timeupper} is true with probability at most $\frac{\delta}{2k}$. \remove{During a run of Algorithm \ref{QM2_alg}, there might be multiple bins created for support element $i$. Let $m_l(i)$ denote the the $l^{th}$ bin created for support element $i$, if created. Now we can say Bin $m_l(i)$ would be in $\mathcal{C}(t)$ until it is classified below $\gamma$. Let us denote $\epsilon_i$ as the event that $\exists$ $t>\frac{e(b-\log(a_i))}{(e-1)a_i}$ s.t $u_i(t)>\gamma>l_i(t)$, where $u_i(t)$ and $l_i(t)$ are defined in \eqref{eqnub} and \eqref{eqnlb} respectively. We wish to compute the probability that there exists bin $m_l(i)$ of support element $i$ which is not classified after $t > \frac{e(b-\log(a_i))}{(e-1)a_i}$ rounds. We can show that $\hat{p}_{m_l(i)}^t \leq \tilde{p}_i^{t}$ where equality holds iff $l = 1$. This is because for $l>1$, at least one sample denoting support element $i$ has gone into Bin $m_1(i)$. Now $\hat{p}_{m_l(i)}^t \leq \tilde{p}_i^{t}$ implies $\hat{u}_{m_l(i)}^t \leq {u}_i^t$. Thus, the event $\hat{u}_{m_l(i)}^t>\gamma$ implies the event $u_i^t>\gamma$. Thus, the event $\hat{u}_{m_l(i)}^t>\gamma$ for some $t>\frac{e(b-\log(a_i))}{(e-1)a_i}$ implies the event $\epsilon_i$ or event $l_i(t) > \gamma$ for some $t$. This is true for all bins $m_l(i)$ created for support element $i$, hence the event $\exists$ bin $m_l(i)$ of support element $i$ which is not classified after $t>\frac{e(b-\log(a_i))}{(e-1)a_i}$ rounds implies the event $\epsilon_i$ or event $l_i(t)>\gamma$. Also the total number of rounds is lower bounded by the total number of queries with bins representing support element $i$. Thus the event that there exists bin $m_l(i)$ of support element $i$ which is not classified after more than $\frac{e(b-\log(a_i))}{(e-1)a_i}$ queries with bins representing support element $i$ implies the event that there exists bin $m_l(i)$ of support element $i$ which is not classified after $t > \frac{e(b-\log(a_i))}{(e-1)a_i}$ rounds which implies the event $\epsilon_i$ or event $l_i(t)>\gamma$ for some $t$ as shown in the previous paragraph. Thus the probability of the event $\exists$ bin $m_l(i)$ of support element $i$ which is not classified after more than $\frac{e(b-\log(a_i))}{(e-1)a_i}$ queries with bins representing support element $i$ is bounded by the sum of probability of $\epsilon_i$ which is bounded by Lemma \ref{union_bound_error_for_all_t} by $\frac{\delta}{2k}$ and probability of the event $\exists t \text{ s.t }l_i(t)>\gamma$ which can be bounded by Lemma \ref{lemma_cb} by union bound to be $\sum\limits_t \frac{\delta}{4kt^2}= \frac{\delta}{2k}$.\remove{since $(\mathcal{E}_i^t)^c$ holds true $\forall$ $i,t$.} Thus the probability of the event $\exists$ bin $m_l(i)$ of support element $i$ which is not classified after more than $\frac{e(b-\log(a_i))}{(e-1)a_i}$ queries with bins representing support element $i$ is bounded by $\frac{\delta}{k}$.} \item $i > m$: In the course of a run of Algorithm \ref{QM2_alg}, there might be multiple bins created for support element $i>m$ even if the algorithm correctly classifies all the bins. Let $m_l(i)$ denote the the $l^{th}$ bin created for support element $i$, if created. Recall that $\hat{p}_{m_l(i)}^t$ as defined in equation \eqref{emp_QM2} denotes the fraction of the samples till round $t$ which are placed in the bin $m_l(i)$; on the other hand, $\tilde{p}_i^t$ as defined in equation \eqref{eq1} denotes the total fraction of samples till round $t$ corresponding to support element $i$. It is easy to see that $\hat{p}_{m_l(i)}^t \leq \tilde{p}_i^{t}$ where equality holds iff $l = 1$. The bin $m_1(i)$ not being out of $\mathcal{C}(t)$ after $K_i = \frac{e(b-\log(a_i))}{(e-1)a_i}$ rounds\remove{the bin $m_1(i)$ not being misclassified} would imply the event $\hat{l}_{m_1(i)}(K_i)< \gamma < \hat{u}_{m_1(i)}(K_i)$ which is equivalent to the event $l_{i}(K_i)< \gamma < u_{i}(K_i)$ \remove{and whose probability can be bounded using Lemma \ref{lemma_exittime} and \ref{lemma_timeupper} by $\frac{\delta}{2k}$} or the event $\gamma <\hat{l}_{m_1(i)}(K_i) $ which is equivalent to the event $p_i<\gamma< l_i(K_i)$. \remove{whose probability can be bounded by Lemma \ref{lemma_cb} $\forall t$ by $\sum_i \frac{\delta}{4kt^2} \leq \frac{\delta}{2k}$} The probability of the event $p_i<\gamma< l_i(K_i)$ is bounded using Lemma \ref{lemma_cb} by $\frac{\delta}{2k}$. The probability of the event $l_i(K_i)<\gamma<u_i(K_i)$ is bounded by Lemma \ref{lemma_exittime} and Lemma \ref{lemma_timeupper} by $\frac{\delta}{2k}$. Thus the probability of the event bin $m_1(i)$ not being out of $\mathcal{C}(t)$ after $K_i$ rounds is bounded by sum of probabilities of the event $p_i<\gamma< l_i(K_i)$ and the event $l_{i}(K_i)< \gamma < u_{i}(K_i)$ which can be bounded by $\frac{\delta}{2k}+\frac{\delta}{2k} \leq \frac{\delta}{k}$. \remove{{\color{red}Comment: Why should the LCB be below $\gamma$ at $K_i$.\\ Reply-SS : If the LCB is not below $\gamma$, the bin $m_1(i)$ would be misclassified at round $K_i$ as both LCB and UCB are above $\gamma$ though it may not be out of $\mathcal{C}(t)$ if $K_i <T'$. To avoid confusion, I am adding the part no misclassification at any round. }} Now consider a bin $m_l(i)$, $l>1$ created at some round $t_l$. Since the bin $m_l(i)$ was created at some round $t_l$ and all bins are correctly classified, bin $m_1(i)$ must have been classified correctly below $\gamma$ in some previous round $t_1 < t_l$. It is easy to see that $\hat{p}_{m_l(i)}^{t_l} < \hat{p}_{m_1(i)}^{t_1}$ which would imply that $\hat{u}_{m_l(i)}^{t_l} < \hat{u}_{m_1(i)}^{t_1} \overset{(a)}{<} \gamma$ and thus the bin $m_l(i)$ would immediately be out of $\mathcal{C}(t)$ after its creation at round $t_l$ and there would be no queries with bin $m_l(i)$ $\forall$ $l>1$. Note that $(a)$ follows since the bin $m_1(i)$ is correctly classified below $\gamma$. \remove{\color{red}What does classification mean here? That might not happen till the end of phase 1. Also, is it clear that LCB and UCB are monotonic in time Reply-SS: UCB going below $\gamma$ immediately implies being out of $\mathcal{C}(t)$ irrespective of whichever phase the algorithm is in. Also since we know that the bounds i.e $\frac{\beta^t}{t}$ is decreasing, we can say if $\hat{p}_{m_l(i)}^{t_l} < \hat{p}_{m_1(i)}^{t_1}$ then, $\hat{u}_{m_l(i)}^{t_l} < \hat{u}_{m_1(i)}^{t_1}$ } Thus the probability of total number of queries with all the bins denoting support element $i>m$ is greater than $\frac{e(b-\log(a_i))}{(e-1)a_i}$ and the algorithm correctly classifies all the bins is upper bounded by $\frac{\delta}{k}$. \end{enumerate} \end{proof} Let us restate and prove Theorem \ref{QM2ub} \begin{theorem* Let $\mathcal{A}$ denote the estimator in Algorithm~\ref{QM2_alg} with $\beta^t = \log(4kt^2 / \delta)$ for each $t\ge 1$ and let $Q_{\delta,\gamma}^{\mathcal{P}}(\mathcal{A})$ be the corresponding query complexity for a given distribution $\mathcal{P}$ under {QM2}. We define $q$ as $\min\left\{k,\frac{\log (\delta/2k)}{\log(1-\gamma)}\right\}$. Then, we have \begin{align*} Q_{\delta,\gamma}^{\mathcal{P}}(\mathcal{A})\leq \sum_{i=1}^{m} \max \Biggl\{ \frac{2e\log \Bigl(\sqrt{\frac{4k}{\delta}}\frac{2}{d^{*}(p_i,\gamma)}\Bigr)}{(e-1).d^{*}(p_i,\gamma)} ,\frac{\log (\delta/2k)}{\log(1-\gamma)} \Biggr\} \hspace{0 em} + \sum_{i=m+1}^{q} \frac{2e.\log \Bigl(\sqrt{\frac{4k}{\delta}}\frac{2}{d^{*}(p_i,\gamma)}\Bigr)}{(e-1).d^{*}(p_i,\gamma)}, \end{align*} with probability at least $1-2\delta$. \end{theorem*} \remove{In the proof, we essentially bound the error probability by first conditioning on the correctness of algorithm and then bound the net error probability of algorithm.} \begin{proof} The total number of bins created during the course of the algorithm must be bounded by $T' = \frac{\log (\delta/2k)}{\log(1-\gamma)}$ since new bins are created only in the first phase of the algorithm and at most one new bin can be created in each round. Thus, the number of bins corresponding to distinct support elements is upper bounded by $q = \min\left\{k,\frac{\log (\delta/2k)}{\log(1-\gamma)}\right\}$. Furthermore, if the algorithm returns a correct set of bins, at least one bin corresponding to each element in $\{1,2,...,m\}$ must have been created. \remove{ However, the total number of bins corresponding to different support elements must be bounded by $T'$. Thus the total number of bins corresponding to distinct support elements created must be upper bounded by $q=\min(k,T')$. } \remove{Given that the algorithm returns a correct set of bins,} Using Lemma \ref{queries with each box} and taking the union bound over all support elements $i \in \{1,2,...,k\}$, the probability of the event that the algorithm correctly classifies all the bins \remove{with no misclassification at any round}\remove{correctly classifies all the bins}and there is\remove{some support element has a bin representing itself in $\mathcal{C}(t)$} an unclassified bin after $\sum_{i=1}^{m} \max\left\{\frac{e(b-\log(a_i))}{(e-1)a_i},T'\right\}$ + $\sum_{i=m+1}^{q} \frac{e(b-\log(a_i))}{(e-1)a_i}$ queries is at most ${\delta}$. {Also, using Lemma $\ref{Correctness_QM2}$, the probability that the algorithm returns an incorrect set of bins is bounded by $\delta$.} \remove{\color{red} Also using Lemma \ref{lemma2:QM2}, the probability that the algorithm misclassifies some bin at some round would be bounded by $\sum_{i,t}\mathbb{P}[\mathcal{E}_i^t] \leq \delta/2$ as done in the proof of Lemma \ref{Correctness_QM2}} Combining together these two observations, we have that the probability that the Algorithm $\ref{QM2_alg}$ does not terminate after $\sum_{i=1}^{m} \max\left\{\frac{e(b-\log(a_i))}{(e-1)a_i},T'\right\}$ + $\sum_{i=m+1}^{q} \frac{e(b-\log(a_i))}{(e-1)a_i}$ queries is bounded by 2$\delta$. This completes the proof of the result. \remove{ Thus, the probability of algorithm having some bin in $\mathcal{C}(t)$ after $\sum_{i=1}^{m} max(\frac{e(b-\log(a_i))}{(e-1)a_i},T')$ + $\sum_{i=m+1}^{q} \frac{e(b-\log(a_i))}{(e-1)a_i}$ queries is bounded by 2$\delta$ implying . } \remove{ {\color{red}Read the above to check if its ok after the edits. Reply- SS: Added the sentence highlighted in red to incorporate the slight change in lemma 11. Comment - SS: Reverted the proof back to original. }} \end{proof} \subsection{Proof of Theorem \ref{QM2lb}} Now, we restate and prove Theorem \ref{QM2lb}. \begin{theorem* For any $\delta$-true $\gamma$-threshold estimator $\mathcal{A}$ under {QM2}, let $Q_{\delta,\gamma}^{\mathcal{P}}(\mathcal{A})$ be the query complexity. Then, we have $$\mathbb{E}[Q_{\delta,\gamma}^{\mathcal{P}}(\mathcal{A})]\geq \max_{j\in\{m,m+1\}}\Bigg\{\frac{\log{\frac{1}{2.4\delta}}}{2\times d(p_j||\gamma)}\Bigg\}.$$ \end{theorem*} \begin{proof} Consider any $\delta$-true $\gamma-$threshold estimator $\mathcal{A}_3$ under {QM2} \ and let us denote the total number of queries by $\tau$ when the underlying distribution is $\mathcal{P}$. Using the above estimator let us construct a $\delta$ -true $\gamma-$threshold estimator for {QM1}. We create such an estimator $\mathcal{A}'$ by simply querying all the indices involved in {QM2}. Since we know that $\mathcal{A}_3$ is a $\delta$-true $\gamma-$threshold for {QM2}, we can argue that $\mathcal{A}'$ would also be a $\delta$-true $\gamma-$threshold for {QM1} \ and thus the query complexity of $\mathcal{A}_3$ would be $2.\tau$. Thus if the expected query complexity $\mathbb{E}[\tau]$ of $\mathcal{A}_3$ is less than $\max_{j\in\{m,m+1\}}\Bigg\{\frac{\log{\frac{1}{2.4\delta}}}{2\times d(p_j||\gamma)}\Bigg\}$ we can construct an estimator $\mathcal{A}'$ for noiseless query model 1 whose expected query complexity is less than $\max_{j\in\{m,m+1\}}\Bigg\{\frac{\log{\frac{1}{2.4\delta}}}{d(p_j||\gamma)}\Bigg\}$ which contradicts the Theorem \ref{QM1lb}. \end{proof} \subsection{Proof of Theorem \ref{QM2_alter_lb}} The following lemma, which we prove in \ref{first_ineq_proof}, will be used to prove this result. \begin{lemma}{\label{first_ineq}} For all $1 \geq p_t, \gamma \geq 0$, the following inequality holds true. $$p_t \log \Bigl(\frac{p_t}{\gamma}\Bigr)+ (2.\gamma) \log\Bigl(\frac{2.\gamma}{p_t + \gamma}\Bigr) \leq 2 d(p_t||\gamma).$$ \end{lemma} Now we restate and prove Theorem \ref{QM2_alter_lb}. \begin{theorem* For a MAB setting described above where the mean rewards of the individual arms satisfy the condition in equation \ref{QM2_pi_cond}, any $\delta$-true $\gamma$-threshold algorithm has the following lower bound in expectation on the total number of pulls $N$: $$ \mathbb{E}_{\mathcal{P}}[N] \geq \sum_{i=1}^{k} \frac{\log(\frac{1}{2.4\delta})}{2\cdot d(p_i||\gamma)}. $$ \end{theorem*} The proof of this result follows along similar lines as that of of \cite[Theorem 7]{shah2019sequentialME}. \begin{proof} Consider an estimator $\mathcal{A}$ which can correctly identify the arms with mean reward distribution above $\gamma$ with probability at least $(1 - \delta)$. We consider two such distributions with mean reward profiles as follows: \begin{align*} \mathcal{P} = (p_1,p_2,..,p_l,..,p_k),\quad \text{ and } \quad \mathcal{P}' = ({p_1}',{p_2}',..,{p_l}',..,{p_k}'). \end{align*} where as before, we assume for $\mathcal{P}$ that $p_1 \geq p_2 \geq \ldots \geq p_m > \gamma > p_{m+1} \geq \ldots p_k$. Also, let $l \leq m$ with ${p_l}'=\gamma - \epsilon$ for some small $\epsilon > 0$ and ${p_i}' = p_i$ $\forall$ $i \neq t$. Note that the sets of arms with mean reward distribution above $\gamma$ for the distributions $\mathcal{P}$ and $\mathcal{P}'$, $\mathcal{S}^{\gamma}_{\mathcal{P}}$ and $\mathcal{S}^{\gamma}_{\mathcal{P}'}$ respectively, are different. Recall that, we may decide to pull any subset $S$ of the arms in any round and there can be $2^k$ such subsets. For any subset $S$, with probability $p_j$, the output vector in any round can be $+1$ for some arm $j \in S$ and $-1$ for all other arms; and with probability (1 - $\sum_{i} p_i$) the output vector is $-1$ for all arms . Let ($Y_{S_a,s}$) be the output vector observed while pulling the subset $S_a$ for the $s^{th}$ time. Based on the observations till round $t$, we define the likelihood ratio $L_t$ as follows: \begin{equation*} L_t = \sum_{a=1}^{2^k} \sum_{s=1}^{N_{S_a}(t)} \log \Bigl(\frac{f_{S_a}(Y_{S_a,s})}{f'_{S_a}(Y_{S_a,s})}\Bigr). \end{equation*} Here $N_{S_a}(t)$ denotes the number of times the subset of arms $S_a$ was pulled till round $t$. With a slight misuse of notation, we let $N_i(t)$ denote the number of times arm $i$ was pulled till round $t$, which sums over all subsets containing $i$. We say \begin{equation*} \mathbb{E}_{\mathcal{P}}\Bigl[ \log \Bigl(\frac{f_{S_a}(Y_{S_a,s})}{f'_{S_a}(Y_{S_a,s})}\Bigr) \Bigr]= D(p_{S_a},{p_{S_a}}'). \end{equation*} Applying Wald's stopping lemma to $L_{\sigma}$ where $\sigma$ is the stopping time associated with estimator $\mathcal{A}$ we have, \begin{align} \mathbb{E}_{\mathcal{P}}[L_{\sigma}] = \sum_{a=1}^{2^k} \mathbb{E}_{\mathcal{P}}[N_{S_a}(\sigma)] D(p_{S_a},{p_{S_a}}') &\overset{(a)}{\leq} \mathbb{E}_{\mathcal{P}}[N_{l}(\sigma)] \max_{S_a: l \in S_a} D(p_{S_a},{p_{S_a}}'). {\label{expectation_likelihood}} \end{align} where $(a)$ follows from the definition of $\mathcal{P}$ and $\mathcal{P}'$ as $D(p_{S_a},{p_{S_a}}')$ is zero for those sets which don't contain arm $l$. Next, for any set $S_a$ such that $l \in S_a$ and $\sum_{i \in S_a \backslash \{l\}} p_i = s$, we have \begin{align*} D(p_{S_a},{p'_{S_a}}) = p_l.\log\Bigl(\frac{p_l}{\gamma-\epsilon}\Bigr) \hspace{0em} +(1-(p_l+s))\log\Bigl(\frac{1-(p_l+s)}{1-(\gamma-\epsilon+s)}\Bigr). \end{align*} We can show that the second term is increasing with $s$ and hence takes its maximum value when $s = \sum_i{p_i}-p_l$. Thus, \begin{align*} &\max_{S_a:t \in S_a} D(p_{S_a},{p_{S_a}}') = p_l \log \Bigl(\frac{p_l}{\gamma-\epsilon}\Bigr) + \hspace{0 em} (1-\sum_i{p_i})\log\Bigl(\frac{1-\sum_i{p_i}}{1-(\gamma-\epsilon+\sum_i p_i - p_l)}\Bigr)\\ & \overset{(a)}{\leq} p_l \log \Bigl(\frac{p_l}{\gamma-\epsilon}\Bigr)+ (2.\gamma) \log\Bigl(\frac{2.\gamma}{(p_l+\gamma+\epsilon)}\Bigr) \overset{(b)}{\approx} p_l \log \Bigl(\frac{p_l}{\gamma}\Bigr)+ (2.\gamma) \log\Bigl(\frac{2.\gamma}{(p_l+\gamma)}\Bigr) \overset{(c)}{\leq} 2 d(p_l||\gamma), \end{align*} where $(a)$ follows from the fact that $(1-\sum{p_i}) > 2\gamma$ {and $x \log (\frac{x}{x-\alpha})$ is decreasing in $x$ \remove{(Comment: is $\alpha$ positive in $(a)$ Reply:The function is decreasing for both positive and negative $\alpha$. Positive $\alpha$ needed for $l\leq m$, negative $\alpha$ for $l > m$.)}}; $(b)$ follows by making $\epsilon$ arbitrarily small; and (c) follows from Lemma~\ref{first_ineq}. Then, from \eqref{expectation_likelihood} we have \begin{equation*} \mathbb{E}_{\mathcal{P}}[L_{\sigma}] \leq 2\times \mathbb{E}_{\mathcal{P}}[N_l(\sigma)]\times d(p_l||\gamma). \end{equation*} On the other hand, it follows from \cite[Lemma 19]{DBLP:journals/jmlr/KaufmannCG16} that since the estimator $\mathcal{A}$ can correctly recover the set of arms $\mathcal{S}^{\gamma}_{\mathcal{P}}$ with probability at least $(1-\delta)$, $ \mathbb{E}_{\mathcal{P}}[L_{\sigma}] \geq \log \Bigl(\frac{1}{2.4\delta}\Bigr).$ Combining the two inequalities above and recalling the assumption that $l \le m$, we have $$ \mathbb{E}_{\mathcal{P}}[N_l(\sigma)] \geq \frac{\log(\frac{1}{2.4\delta})}{2d(p_l||\gamma)} \ \forall \ l \leq m.$$ \remove{ Now we prove the same for $t > m$. We reconstruct the two distributions with reward distributions as follows: \begin{align*} \mathcal{P} & = (p_1,p_2,..,p_t,..,p_k)\\ \mathcal{P}' &= ({p_1}',{p_2}',..,{p_t}',..,{p_k}') \end{align*} where $t > m$ is an integer. ${p_t}'=\gamma - \epsilon$ for some $\epsilon > 0$ and ${p_i}' = p_i$ $\forall$ $i \neq t$. Note that the sets of arms with mean reward distribution above $\gamma$ is different for the distributions $\mathcal{P}$ and $\mathcal{P}'$. By using similar arguments as that of previous case, we can prove \eqref{expectation_likelihood} in this case as well. We can still show the following inequality (using similar arguments as used in previous case): \begin{align*} & \max_{S_a:t \in S_a} (D(p_{S_a},{p_{S_a}}'))\\ & = p_t \log \Bigl(\frac{p_t}{\gamma+\epsilon}\Bigr) + \hspace{0 em} (1-\sum{p_i})\log\Bigl(\frac{1-\sum{p_i}}{1-(\sum{p_i}+\gamma-\epsilon+s-p_t)}\Bigr)\\ & \overset{(c)}{\leq} p_t \log \Bigl(\frac{p_t}{\gamma + \epsilon}\Bigr)+ (2.\gamma) \log\Bigl(\frac{2.\gamma}{p_t+\gamma-\epsilon}\Bigr)\\ & \overset{(d)}{\leq} 2 \Bigl(p_t \log \Bigl(\frac{p_t}{\gamma}\Bigr) + (1-p_t) \log \Bigl(\frac{1-p_t}{1-\gamma}\Bigr)\Bigr)\\ & = 2 d(p_t||\gamma). \end{align*} Note that (c) follows from the fact that $(1-\sum{p_i}) > 2\gamma$ and $x \log (\frac{x}{x+\alpha})$ is decreasing in $x$. (d) follows from the first inequality \eqref{first_ineq} by making $\epsilon$ arbitrarily small. We use same arguments as used in previous case to show the following inequalities. $$\mathbb{E}_{\mathcal{P}}[L_{\sigma}] \geq \log \Bigl(\frac{1}{2.4\delta}\Bigr). $$. $$ \mathbb{E}_{\mathcal{P}}[L_{\sigma}] \leq 2\times \mathbb{E}_{\mathcal{P}}[N_t(\sigma)]\times d(p_t||\gamma) ; t > m.$$ } Using similar arguments, we can also show that $$ \mathbb{E}_{\mathcal{P}}[N_l(\sigma)] \geq \frac{\log(\frac{1}{2.4\delta})}{2d(p_l||\gamma)} \ \forall \ l > m.$$ Hence, we have the following lower bound on the query complexity of any $\delta$-true $\gamma$-threshold estimator under this setting: $$\mathbb{E}_{\mathcal{P}}[N]\geq \sum_{l=1}^{k} \mathbb{E}_{\mathcal{P}}[N_l(\sigma)] > \sum_{l=1}^{k} \frac{\log(\frac{1}{2.4\delta})}{2d(p_l||\gamma)}.$$ \end{proof} \subsection{Proof of Theorem \ref{QM2_noisyub}} In this section, we define ${a_i}'$ as $d^{*}({p_i}',\gamma')/2$ and $b$ = $\frac{1}{2} \cdot \log(\frac{4k}{\delta})$. We start with the following lemma. \begin{lemma}\label{queries with each box noisy} Assume that the properties in Lemmas~\ref{lemma_extract} and \ref{all_occur} are satisfied. Then, the total number of queries with the bin representing support element $i$ in the second phase of Algorithm \ref{QM2n_alg} is upper bounded by $\frac{e(b-\log({a_i}'))}{(e-1){a_i}'}$ with probability at least $(1-\delta/4k)$. \end{lemma} \begin{proof} Since the properties in Lemmas~\ref{lemma_extract} and \ref{all_occur} are satisfied, every bin at the end of the first phase represents a different support element. Let bin $j$ denote support element $i$. Recall from equation \eqref{eq_noisy} that $\tilde{\rho}_j^t$ denotes the fraction of samples seen in the second phase till round $t$ that receive a positive response when compared to the representative element in Bin $j$. We have $\mathbb{E}[\tilde{\rho}_j^t] = {p_i}' = p_i\times (1-p_e) + p_e\times(1-p_i) = (1-2p_e)\times p_i + p_e$ and $\mathcal{L}_j(t)$ and $\mathcal{U}_j{(t)}$ denote the lower and upper confidence bounds of bin $j$ respectively, as defined in equations \eqref{eqn_noisylb} and \eqref{eqn_noisyub} respectively. Accordingly in equation \eqref{eqn:c2tnoise}, the LCB and UCB of bin $j$ are compared with a modified threshold given by $\gamma' = (1-2p_e)\times \gamma + p_e$ to decide how long it will be retained in the subset $\mathcal{C}'(t)$ of bins that new samples are compared against. The above setting of the second phase is similar to the {QM1} \ model where each new sample with index above $T_0$ would fall in the bin representing support element $i$ with probability ${p_i}'$. Thus similar results apply and in particular, Lemmas~\ref{lemma_exittime} and \ref{lemma_timeupper} can be used to show that the total number of queries with a bin representing support element $i$ is upper bounded by $\frac{e(b-\log({a_i}'))}{(e-1){a_i}'}$ with probability at least $(1-\frac{\delta}{4k})$. \remove{ This proof follows along the same lines as that of Lemmas \ref{lemma_exittime} and \ref{lemma_timeupper}. This is because, Recall that $\mathbb{E}[\mathcal{Z}_j^t]= {p_i}' = p_i\times (1-p_e) + p_e\times(1-p_i) = (1-2p_e)\times p_i + p_e$ for $t > T_0$ where indices less than $T_0$ in Bin $j$ denotes support element $i$. Thus the classifier would be $\gamma' = (1-2p_e)\times \gamma + p_e$ for $t > T_0$ to classify the bins which have the probability of the support elements of indices below $T_0$ above $\gamma$. Now the setting is similar as that in {QM1} \ model where each new sample with index above $T_0$ would fall in bin with support element $i$ with probability ${p_i}'$. Thus the same theorems and lemmas as that in \ref{lemma_exittime} and \ref{lemma_timeupper} can be used to show that the total number of queries with a bin which denoted support element $i$ at Round $T_0$ is upper bounded by $\frac{e(b-\log({a_i}'))}{(e-1){a_i}'}$ with probability at least $(1-\frac{\delta}{4k})$. } \end{proof} Now we restate and prove Theorem \ref{QM2_noisyub}. \begin{theorem* Let $\mathcal{A}$ denote the estimator in Algorithm~\ref{QM2n_alg} with $\beta^t = \log (\frac{4k(t-T_0)^2}{\delta})$ for each $t > T_0$ where $T_0$ is as defined in \eqref{T0_defn}. Let $Q_{\delta,\gamma}^{\mathcal{P}}(\mathcal{A})$ be the corresponding query complexity for a given distribution $\mathcal{P}$ under {QM2-N} \ and define $q = \min\{T_0,k\}$, ${p_i}'= (1-2p_e)\times p_i+p_e$ and $\gamma' = (1-2p_e)\gamma+p_e$. Then we have $$Q_{\delta,\gamma}^{\mathcal{P}}(\mathcal{A}) \leq \sum_{i=1}^{q} \frac{2e.\log \Bigl(\sqrt{\frac{4k}{\delta}}\frac{2}{d^{*}({{p}_i}',\gamma')}\Bigr)}{(e-1).d^{*}({p_i}',\gamma')} + \frac{T_0(T_0-1)}{2} $$ with probability at least $(1- 2\delta)$. \end{theorem*} \begin{proof} Let us first bound the total number of queries in the second phase, i.e., post round $T_0$. Since the bins are created only at the end of the first phase, the total number of bins must be upper bounded by $T_0$. Furthermore, if the properties in Lemmas~\ref{lemma_extract} and \ref{all_occur} are satisfied, there is at most one bin corresponding to each support element which implies the total number of bins must be upper bounded by $q= \min\{k,T_0\}$. Assuming that the properties in Lemmas~\ref{lemma_extract} and \ref{all_occur} are satisfied, from Lemma \ref{queries with each box noisy}, we have that the total number of queries with the bin representing support element $i$ is upper bounded by $\frac{e(b-\log({a_i}'))}{(e-1){a_i}'}$ with probability at least $(1-\frac{\delta}{4k})$. Taking the union bound over all the $q$ bins we can say with probability at least $(1-\delta)$ that total number of queries in the second phase is bounded by $\sum_{i=1}^{q} \frac{2e.\log \Bigl(\sqrt{\frac{4k}{\delta}}\frac{2}{d^{*}({{p}_i}',\gamma')}\Bigr)}{(e-1).d^{*}({p_i}',\gamma')}$. Now since the probability that the properties in Lemmas~\ref{lemma_extract} and \ref{all_occur} are all satisfied is at least $(1 - \delta)$, the total number of queries in the second phase is upper bounded by $\sum_{i=1}^{q} \frac{2e.\log \Bigl(\sqrt{\frac{4k}{\delta}}\frac{2}{d^{*}({{p}_i}',\gamma')}\Bigr)}{(e-1).d^{*}({p_i}',\gamma')}$ with probability at least $(1-2\delta)$. Finally, noting that there are exactly $\frac{T_0(T_0-1)}{2}$ queries in the first phase of the algorithm, our proof is complete. \end{proof} \section{PROBLEM FORMULATION} \label{sec: Problem} Consider an unknown discrete probability distribution $\mathcal{P}=\{p_1,p_2,...,p_k\}$ over a finite support set $\{1,2,...,k\}$. A random variable $X$ is said to be sampled from a distribution $\mathcal{P}$, if $\mathbb{P}_{\mathcal{P}}(X=i) = p_i$ for all $i\in\{1,2,...,k\}$. Our goal in this paper is to identify all the indices whose probability of occurrence is above a given threshold $\gamma$. Formally, we want to identify the set of support elements $S_{\mathcal{P}}^{\gamma} = \{i \ | \ p_i \geq \gamma\}$. Towards this, we have access to an independent and identically distributed (i.i.d.) sequence of samples $X_1,X_2,...$, from $\mathcal{P}$ via an oracle. We consider the following four types of oracle queries. \begin{itemize} \item \textit{Noiseless query model 1 ({QM1})}: Queried with an index $i$, the oracle response is given by $\mathcal{O}(i) = X_i$, i.e., the oracle returns the value $X_i$ of the $i^{th}$ sample. \item \textit{Noisy query model 1 ({QM1-N})}: Queried with an index $i$, the oracle returns the value $X_i$ of the $i^{th}$ sample with probability $1-p_e$ and a random value in $\{1,2,...,k\}$ with probability $p_e$, for some $p_e \in (0, 1/2)$. More formally, the oracle response\footnote{Note that the oracle response remains the same if the same index $i$ is queried repeatedly.} to query $i$ is given by $\mathcal{O}(i)= (1- K_i)\times X_i+ K_i \times U_i$, where $K_i$ is a Bernoulli random variable with mean $p_e$ and $U_i$ is a uniform random variable over the set $\{1,2,\ldots,k\}$. We assume that $\{U_i\}$, $\{K_i\}$ are all independent random variables and are also independent of the sequence of samples $X_1, X_2, \ldots$. \item \textit{Noiseless query model 2 ({QM2})}: In this model, the oracle makes pairwise comparisons. Given two indices $i$ and $j$, the oracle tells us whether the values $X_i$ and $X_j$ are equal or not. Formally, we denote the oracle response to a query pair $(i,j)$ as: \begin{equation*} \mathcal {O}(i,j)= \begin{cases} 1 & \text{if}\ X_i = X_j, \\ -1 & \text{otherwise.} \end{cases} \end{equation*} Note that the true values of $X_i$ or $X_j$ are not revealed in this model. \item \textit{Noisy query model 2 ({QM2-N})}: The oracle model here is the same as the one in {QM2}, except that the true noiseless {QM2} \ oracle response is flipped with probability $p_e$. In particular, given two indices $i$ and $j$, if the values $X_i$ and $X_j$ are equal, the oracle returns $+1$ with probability $1-p_e$ and $-1$ with probability $p_e$. Similarly, if the values of $X_i$ and $X_j$ are not equal, the oracle answers $+1$ with probability $p_e$ and $-1$ with probability $1-p_e$. Formally, we denote the oracle response to a query pair $(i,j)$ as: $$\mathcal{O} (i, j) = (2\times \mathbbm{1}_{X_i = X_j}-1) \times (1 - 2Z_{i,j}),$$ where $\mathbbm{1}_E$ denotes the indicator random variable corresponding to event $E$ and $Z_{i,j}$ denotes a Bernoulli random variable with mean $p_e$. We assume that $\{Z_{i,j}\}$ are independent random variables and are also independent of the sequence of samples $X_1, X_2, \ldots$. \end{itemize} For each of the query models described above, we aim to design efficient sequential algorithms which proceed in rounds as follows: \begin{itemize} \item The algorithm chooses a pair of indices (an index) for the {QM2} \textbackslash {QM2-N} \ ({QM1} \textbackslash {QM1-N}) models and queries the oracle with those indices (index). \item Based on all the responses received from the oracle thus far, the algorithm decides either to terminate or proceed to the next round. \end{itemize} When the algorithm decides to terminate, it returns a set of indices denoted by $\widehat{S}$ as an estimate of the set $S_{\mathcal{P}}^{\gamma}$ consisting of all indices $i$ in the support set for which the corresponding probability value $p_i$ is above $\gamma$. We measure the cost of an estimator in terms of the number of queries made before it stops and its accuracy in terms of the probability with which it successfully estimates the index set $S_{\mathcal{P}}^{\gamma}$. For $0<\delta<1$ and given $0<\gamma<1$, an algorithm is defined to be a $\delta$-true $\gamma$-threshold estimator, if for every underlying distribution $\mathcal{P}$, it identifies the set $S_{\mathcal{P}}^{\gamma}$ with probability at least $1- \delta$, i.e., $\mathbb{P}_\mathcal{P}[\widehat{S}= S_{\mathcal{P}}^{\gamma}] \geq (1- \delta)$, where $\widehat{S}$ is the estimated support set. In this work, we aim to design efficient $\delta$-true $\gamma$-threshold estimators which require as few queries as possible. For a $\delta$-true $\gamma$-threshold estimator $\mathcal{A}$ and a distribution $\mathcal{P}$, let $Q_{\delta,\gamma}^{\mathcal{P}}(\mathcal{A})$ denote the number of queries made by the estimator. Note that $Q_{\delta,\gamma}^{\mathcal{P}}(\mathcal{A})$ is itself a random variable and our results hold either with high probability or in expectation. Without loss of generality (W.L.O.G.), we assume $p_1 \geq p_2 \geq ...\geq p_m > \gamma> p_{m+1} \geq ...\geq p_k $, i.e., a $\delta$-true $\gamma$-threshold estimator must return the set $\{1,2,...,m\}$ with probability at least $1-\delta$. The rest of the paper is organized as follows. We propose sequential estimation algorithms for the {QM1} \ and {QM1-N} \ models in Sections~\ref{Sec:QM1} and \ref{Sec:QM1N} respectively, where we provide both upper and lower bounds on the query complexity. Section~\ref{Sec:QM2} discusses the query complexity and our proposed algorithm for the {QM2} \ model. Finally, Section~\ref{Sec:QM2N} proposes an estimator for the {QM2-N} \ model and analyses its query complexity. Some numerical results are provided in Section~\ref{Sec:Sim} and we relegate all the proofs to Section~\ref{Sec:Proofs}. \section{NUMERICAL RESULTS} \label{Sec:Sim} In this section, we simulate Algorithms \ref{QM1_alg} and \ref{QM2_alg} for the {QM1} \ and {QM2} \ models respectively, under two different probability distributions. \begin{figure}[h] \centering \begin{minipage}{.5\textwidth} \centering \includegraphics[width=0.8\linewidth, height=0.2\textheight]{thresholdqm13.jpg} \caption{ Query complexity plot of Algorithm \ref{QM1_alg} under different confidence bounds} \label{QM1_with_p3} \end{minipage}% \centering \begin{minipage}{.5\textwidth} \centering \includegraphics[width=0.8\linewidth, height=0.2\textheight]{figure6} \caption{ Query complexity plot for Algorithm \ref{QM2_alg} and a naive algorithm. } \label{QM2_with_p3} \end{minipage}% \end{figure \begin{enumerate}[label=(\alph*)] \item In the first setting, we choose the support size $k=30$ and set $p_1= 0.35$, $p_2=0.28$, vary $p_3$ from $0.13$ to $0.19$, and for all $i=3,4,...,k$, set $p_i= \frac{1-p_1-p_2-p_3}{k-3}$. We set the threshold to $\gamma = 0.1$ and the required error probability $\delta = 0.1$. For each datapoint, we simulate Algorithms \ref{QM1_alg} and \ref{QM2_alg} under {QM1} \ and {QM2} \ respectively $15$ times each and plot the average number of queries required against $1/{d^{*}(p_3,\gamma)}$ in Fig. \ref{QM1_with_p3} and Fig \ref{QM2_with_p3} respectively. {In Fig. \ref{QM1_with_p3}, we compare the query complexity for Algorithm \ref{QM1_alg} (using KL-divergence based bounds) with those using other popular confidence bounds namely Hoeffding and Empirical Bernstein (used in \cite{shah2019sequentialME})}. As predicted by our theoretical result, the query complexity of Algorithm \ref{QM1_alg} under {QM1} \ increases (almost) linearly with ${1}/{d^{*}(p_3,\gamma)}$ in Fig. \ref{QM1_with_p3}. In Fig \ref{QM2_with_p3}, we compare the query complexity for Algorithm \ref{QM2_alg} with that of a naive algorithm which in each round, queries the next sample with all the bins created so far. {We observe that Algorithm \ref{QM1_alg} the one with KL-divergence based bounds performs better than its counterparts with other popular confidence bounds.} We can see that the query complexity of our proposed estimator is much lower since it discards bins as we go along, thus reducing the number of queries. \begin{figure}[h] \centering \begin{minipage}{0.495\textwidth} \centering \includegraphics[width=0.8\linewidth, height=0.2\textheight]{gammaqm13.jpg} \caption{Query complexity plot of Algorithm \ref{QM1_alg} under different confidence bounds with $\gamma$} \label{QM1_with_gamma} \end{minipage} \centering \begin{minipage}{0.495\textwidth} \centering \includegraphics[width=0.8\linewidth, height=0.2\textheight]{gammaqm2.jpg} \caption{Query complexity plot of Algorithm \ref{QM2_alg} and a naive algorithm with $\gamma$} \label{QM2_with_gamma} \end{minipage} \end{figure} \item In the second setting, we choose a probability distribution $\{0.3, 0.25, 0.2, 0.15, 0.1\}$ and vary $\gamma$ from $0.02$ to $0.4$. As before, we simulate Algorithms \ref{QM1_alg} and \ref{QM2_alg} under {QM1} \ and {QM2} \ respectively 15 times each, and plot the average number of queries required against $\gamma$ in Figures~\ref{QM1_with_gamma} \ and \ref{QM2_with_gamma}. {In Fig. \ref{QM1_with_gamma}, we compare the query complexity for algorithm \ref{QM1_alg} (using KL-divergence based bounds) with those other popular confidence bounds namely Hoeffding and Empirical Bernstein (used in \cite{shah2019sequentialME}).} In Fig \ref{QM2_with_gamma}, we compare the query complexity for Algorithm \ref{QM2_alg} with that of a naive algorithm which in each round, queries the next sample with all the bins created so far. The query complexity has multiple peaks, each corresponding to the case where $\gamma$ approaches some $p_i$. \begin{figure}[h] \centering \begin{minipage}{0.495\textwidth} \centering \includegraphics[width=0.8\linewidth, height=0.2\textheight]{zipfqm13} \caption{Query complexity plot of Algorithm \ref{QM1_alg} using different confidence bounds for different values of Zipf parameter} \label{QM1_with_zipf} \end{minipage} \centering \begin{minipage}{0.495\textwidth} \centering \includegraphics[width=0.8\linewidth, height=0.2\textheight]{zipfqm21} \caption{Query complexity plot of Algorithm \ref{QM2_alg} and its naive variant for different values of Zipf paramter} \label{QM2_with_zipf} \end{minipage} \end{figure} \item {In this setting we simulate our algorithms for a fixed value of threshold $\gamma$ = 0.1 against Zipf distributions for various values of Zipf parameter $\beta$ from 0.5 to 4.5. As before we simulate each algorithm 15 times and plot the average query complexity of algorithms corresponding to {QM1} \ and {QM2}\ with $\max\Bigl\{\frac{1}{d^{*}(p_m,\gamma)},\frac{1}{d^{*}(p_{m+1},\gamma)}\Bigr\}$ and $\sum_i \frac{1}{d^{*}(p_i,\gamma)}$ respectively. In Fig. \ref{QM1_with_zipf}, we compare the query complexity for algorithm \ref{QM1_alg} (using KL-divergence based bounds) with those other popular confidence bounds namely Hoeffding and Empirical Bernstein (used in \cite{shah2019sequentialME}). In Fig \ref{QM2_with_zipf}, we compare the query complexity for Algorithm \ref{QM2_alg} with that of a naive algorithm which in each round, queries the next sample with all the bins created so far. Note that a very similar linear variation is observed similar to those in Fig. \ref{QM1_with_p3} and Fig. \ref{QM2_with_p3}.} \end{enumerate} { \textbf{Comparison on a real-world dataset}: We conduct a clustering experiment on a real-world purchase dataset \cite{clusterdatasets}, where we wish to only identify the clusters with size larger than a given threshold. We benchmark our proposed Algorithm \ref{QM2_alg} for pairwise queries and a naive variant of it with no UCB-based bin elimination against the full clustering algorithm of \cite{mazumdar2017clustering}. We use the dataset in \cite{clusterdatasets} to create a set of nodes (denoting the products in this case) with a label attached to each node such that all nodes attached with a common label represents a set of items belonging to the same product category. From the given dataset, we chose the top $k = 100$ clusters for our experiment so that the total number of items is $n= 9,07,101$. The size of the largest cluster is $53,551$ and we chose our threshold size as $17,688$ with $11$ clusters having size larger than it, with the sizes for the $11$-th and $12$-largest clusters being $19390$ and $16298$ respectively. For 99\% target confidence, Algorithm \ref{QM2_alg} terminated with $\sim$ $2.85 \times 10^6$ pairwise queries. In contrast, even for a target confidence of 80\%, the naive variant of Algorithm \ref{QM2_alg}'s where all bins are queried in every round required $\sim$ $17 \times 10^6$ queries ($6\times$ more). On the other hand, the algorithm that does the full clustering first is expected to take around $nk \sim 90 \times 10^6$ queries ($31\times$ more). { We also benchmark the performance of our schemes on the Movielens dataset\\ (https://grouplens.org/datasets/movielens/), with each movie associated with its most popular tag, and let each tag represents a cluster. We consider the top 100 clusters which contain 15,241 movies and choose our threshold as 409 with exactly 3 clusters above it. For the QM1 model and with 99 \% confidence, Algorithm 1 required 2,05,394 queries whereas its variants with Hoeffding and Empirical Bernstein - based confidence intervals needed 2,37,346 and 3,06,976 queries respectively. Under the QM2 model, Algorithm 2 terminated after 8,22,124 queries whereas its naive variant required 61,26,357 queries even under 80\% confidence. Also, the full clustering scheme of Mazumdar and Saha 2017 is expected to take around $nk$=15,24,100 queries}. }
{'timestamp': '2021-02-11T02:19:28', 'yymm': '2005', 'arxiv_id': '2005.14425', 'language': 'en', 'url': 'https://arxiv.org/abs/2005.14425'}
arxiv
\section{Introduction} In speech communication people make use of two types of information to convey their intentions: \textit{what} is said (linguistic information) and \textit{how} it is said (paralinguistic information) \cite{mitra2019leveraging}. Paralinguistic information is expressed by suprasegmental features such as duration, intensity and pitch. Even with the same linguistic information, changes in these prosodic features can communicate different implications. One such implication involves emphasis. As the terminology can be ambiguous, we follow Kohler's \cite{kohler2006emphasis} distinctions of two kinds of emphasis: \textit{emphasis for focus}; which `singles out elements of discourse by making them more salient than others'; and \textit{emphasis for intensity}; which `intensifies the meaning contained in the elements.' The current work addresses the first category of emphasis: focus. In the literature of a semantic framework called Alternative Semantics \cite{rooth1985association, rooth1992theory}, focus is understood as the indication of `the presence of alternatives that are relevant for the interpretation of linguistic expressions' \cite{krifka2008basic}. Consider this example: \begin{enumerate}[label=(\arabic*)] \item \begin{enumerate}[label=\alph*.] \item \label{emotive_a} \textbf{John} bought the apple. \item \label{emotive_b} John \textbf{bought} the apple. \end{enumerate} \end{enumerate} \noindent In (1a), \textit{John} is focused, as indicated by bold typeface. The speaker implies that \textit{It was John who bought the apple}, indicating the presence of contextually possible alternatives such as \textit{Peter} or \textit{Mary}, and at the same time indirectly ruling out these agents for the person who \textit{bought the apple}. In contrast, in (1b), focus falls on \textit{bought}, by which the speaker indicates that \textit{What John did was not sell the apple, but buy the apple}. Although (1a) and (1b) give identical linguistic information, the differences in the focused words create different connotations. In English speech, focus is marked by sentence stress, the most prominent stress within a sentence \cite{wells2006english}. To avoid misunderstanding, interlocutors must correctly perceive the placement of sentence stress and understand the associated focused meaning. While this inherent skill is taken for granted among native English speakers, non-natives find it challenging \cite{derwing2012longitudinal}. Therefore, cross-lingual interactions demand an automated system that can output the implied meaning for non-natives. \\ \indent The idea of speech translation (ST), which automatically translates speech in a source language (SL) to text or speech in a target language (TL), might be helpful toward achieving such cross-lingual communication. In recent years, ST systems have made significant progress in translating linguistic information correctly. However, most of the ST systems developed so far have not attained the capability to consider paralinguistic information, including focus. Translation by these systems is based on the transcription produced by automatic speech recognition (ASR), which is designed to transcribe only the contents of an utterance, resulting in the loss of paralinguistic information. The current ST models translate (1a) and (1b) the same way, even though they convey different implications. Recently, however, as the importance of paralinguistic information has become more widely acknowledged, some studies have tackled the translation of paralinguistic information such as voice quality \cite{jia2019direct}, emotions \cite{aguero2006prosody, akagi2014emotional} and emphasis \cite{aguero2006prosody, kano2012method, kano2013generalizing, anumanchipalli2012intent, tsiartas2013toward, do2016transferring, do2016preserving, do2018sequence} by mapping the prosodic cues in the SL, such as intensity, duration and fundamental frequency, to speech in the TL. \begin{figure*} \centering \includegraphics[width=0.75\textwidth]{images/proposed_method.png} \caption{Example of focus translation through paraphrased text. Before translating, within the SL, focus expressed by prosodic device in the original speech is transformed into that expressed with lexical and grammatical devices in text.} \label{fig: proposed_method} \end{figure*} While such efforts have advanced the research on translation of paralinguistic cues, it cannot be assumed that the TL necessarily has a prosodic counterpart that plays the same role as that in the SL. For instance, for information focusing, languages make use of not only prosodic devices but also lexical and grammatical devices \cite{cruttenden1997intonation}. Although English speech often uses sentence stress rather than linguistic devices for focus \cite{cruttenden1997intonation}, the degree of reliance on such methods vary from language to language \cite{cruttenden1997intonation, downing2006prosody, hartmann2008focus}. This observation partially limits the efforts of an acoustic-to-acoustic way of paralinguistic translation. Instead, we argue the potential of the acoustic-to-linguistic mapping of paralinguistic information by paraphrasing the speech into the linguistic domain within the SL, with the help of lexical and grammatical devices, and then passing the paraphrases on to the translation module (Figure \ref{fig: proposed_method}). Such a method could return different translations depending on the focused items, even with the same linguistic information. The achievement of acoustic-to-linguistic focus transformation requires data for training such a model. However, to the best of our knowledge, no existing English corpus contains pairs of: speech having different items in focus; and text reflecting the relevant implications. In the most related work, an English corpus \cite{do2018toward} was built with text items that differ in the degree of \textit{emphasis for intensity}, e.g. (\textit{It is a little bit hot} / \textit{It is extremely hot}), and the corresponding speech, e.g. (\textit{It is \textbf{hot}} / \textit{It is \textbf{HOT}}) which was recorded so that it would represent the same degree of emphasis as that in the text. Since their focus was on the degree of emphasis such as weak/strong, every speech sample fixed its position of focus on an adjective. The data was later used for building a model of speech-to-text emphasis translation \cite{tokuyama2021transcribing}. A recent work in text-to-speech (TTS) \cite{latif2021controlling} added the elements of \textit{emphasis for focus} to the previous efforts. Speech items which differed in the placement of focus were collected, e.g. (\textit{\textbf{Sarah} closed the door}, \textit{Sarah \textbf{closed} the door}). However, since the purpose of the work was to achieve prosodic prominence in a TTS model from annotated text, the data did not involve the corresponding implications of speech. Also, while words in a closed-class, e.g. \textit{the, is}, can be focused \cite{greenbaum1990student}, such cases remain to be addressed. \\ \indent We also argue the importance of understanding the relationships of focus representations in speech and text, i.e. how focus expressed in speech is paraphrased or transformed into the linguistic domain. In the literature, some studies addressed patterns of general paraphrase alternations, i.e. how an original text item is paraphrased into another one which has approximately the same meanings \cite{boonthum2004istart, dolan2004unsupervised, vila2014paraphrase}, and others examined how linguistic items can convey focus \cite{taglicht1984message, rooth1985association}. However, it has not been clear the methods of mapping focus from the paralinguistic dimension to the linguistic one. To these ends, we present the creation of an English corpus containing speech that differs in the placement of focus, where words in a closed-class are also the targets of focus, and text reflecting the relevant implications. We also perform quantitative and qualitative analyses of the transformation of focus from the paralinguistic domain to the linguistic domain. \subsection{Focus in English} This section briefly summarises how the English language employs prosodic and linguistic devices to convey focus. \subsubsection{Prosodic device} As mentioned in the previous section, English speech uses sentence stress to convey focus. Native English speakers highlight certain information and draw a listener's attention using the following procedure \cite{wells2006english}. Depending on the intention, they first break spoken materials into smaller chunks called intonation phrases (IPs). Then, in each IP they select the most important word and put sentence stress on that word's stressed syllable, i.e. syllable that has lexical stress. \subsubsection{Lexical and grammatical devices} Prosody is not the only device to convey focus. Lexical and grammatical devices are also available \cite{cruttenden1997intonation}. As one type of the lexical devices, a group of words called focus particles can convey focus \cite{konig2002meaning}. For instance, \textit{only}, \textit{even}, and \textit{alone} can serve this purpose \cite{rooth1985association}. Consider the following example: \begin{enumerate}[label=(\arabic*)]\addtocounter{enumi}{1} \item \begin{enumerate}[label=\alph*: ] \item \label{lexical_a} John bought an apple. \item \label{lexical_b} John bought only an \underline{apple}. \end{enumerate} \end{enumerate} \noindent Compared to (2a), (2b) explicitly states what \textit{John bought} was neither \textit{an orange} nor \textit{a banana}, resulting in \textit{an apple} being highlighted, as indicated by the underline. Similarly, \textit{let alone} \cite{fillmore1988regularity}, reflexive pronouns such as \textit{himself}/\textit{herself} \cite{konig2006focused}, \textit{particularly, mainly}, and many more such words \cite{konig2002meaning} can be used as lexical items for focus. \\ \indent A grammatical device can also perform focus by changing the structure of a sentence. Grammatical items include constructions of cleft (\textit{It was \underline{Simon} who kicked the door.}), pseudo-cleft (\textit{What Mary bought was an \underline{apple}}), inversion (\textit{And then appears a \underline{bear}}), and passivization (\textit{I was bit by a \underline{dog}}) \cite{greenbaum1990student}. It should be noted that grammatical reconstructions often involve shifting the target of focus toward the end of the sentence, since English information structure is governed mainly by the principles \textit{Given-Before-New} and \textit{End Weight} \cite{aarts2011oxford}. \section{Corpus construction} \begin{figure*}[t] \centering \includegraphics[width=0.90\textwidth]{images/corpus_design_revised_20220927.png} \caption{Corpus Design} \label{fig:overview} \end{figure*} \subsection{Text design} We started the text construction from Flickr8k \cite{rashtchian2010collecting}, which consists of over 8000 images that depict actions relating to people or animals. Five text descriptions are given for each image, with over 40,000 annotations. To select optimal captions, we removed sentences that fell under one of the following conditions: including punctuation other than a period; corrected by GECToR \cite{omelianchuk2020gector}, a grammatical error correction model; a noun phrase; more than six words; identical to another caption. We left only one caption if an image had multiple captions. Regarding the sentence length, for simplicity, we wanted each speech to have only one sentence stress, meaning that an entire sentence is treated as a single IP. To determine an optimal sentence length for a single IP, we examined the London-Lund corpus of spoken English \cite{svartvik1990london}, which consists of half a million words and prosodic transcriptions, including tone units, or IPs. We calculated word length for each IP, and chose 6, which equaled the third quartile in the corpus, as the maximum sentence length. After the filtering, we had 1375 sentences and selected the first 196 captions as the source sentences for our corpus. The text items included \textit{A biker enjoys a coffee}, for instance (Figure \ref{fig:overview}). \subsection{Speech collection} We employed Amazon's Mechanical Turk (MTurk) for data collection, a crowdsourcing platform allowing researchers to create tasks called HITs (Human Intelligence Task) and anonymous users (Workers) to complete them for a small monetary fee. \subsubsection{Recording application} MTurk does not provide an interface for audio collection, so we created a web-based recording application that could capture a user's recordings interactively and store them in a back-end server. To encourage subjects to speak properly, we enabled Google speech-to-text API so that the system could give the instant feedback `Speak Clearly' if it did not recognise incoming speech as English words. Speakers could use basic functions such as start and stop of the recordings, and re-recording. As an additional feature, for each utterance, we recorded an extra two seconds at the end while the speech evaluation was in progress; this was done to capture the environment's sound, and during this time, users were instructed to remain silent. \subsubsection{Recording procedure} We attempted to collect a set of speech samples, each with different placement of focus, for each caption using three different speakers (Figure \ref{fig:overview}). For future use, normal readings without focus was also collected from the same speakers. We asked Workers located in the UK to participate in the tasks. In the recording HITs, Workers were instructed as follows: Look at the displayed written sentence, e.g. (\textit{Two \underline{men} are ice fishing}); Make a recording emphasising the underlined word if it does not sound unnatural, otherwise, skip this recording; If there is no underlined word, e.g. (\textit{Two men are ice fishing}), read the sentence in a normal way. \\ \indent When using a crowdsourcing service, taking measures to ensure the quality of data is crucial \cite{rashtchian2010collecting, kennedy2020shape}. We prepared a qualification test, in which Workers needed to fill out general information such as age, gender and accent after an agreement. Then they conducted the step described above for three captions. After manually checking the results, we allowed those who made recordings as instructed to proceed to the main recording HITs. The collection resulted in 3423 speech items (normal: 588, emphasised: 2835) by 9 British natives (4 male, 5 female, age range 22--60 years with a median of 37 years). We paid Workers \$1.20 for processing two captions, and \$2 for three, resulting in \$30.9 per hour on average, surpassing \$15, which is considered to be fair among Workers in MTurk \cite{whiting2019fair}. \subsection{Paraphrase collection} \begin{figure}[h] \centering \includegraphics[width=0.71\linewidth]{images/paraphrase_instructions.png} \caption{Instructions for paraphrase collection} \label{fig:paraphrase_instruction} \end{figure} Free-form tasks, including the paraphrase collection, need to make sure that participants are native speakers \cite{rashtchian2010collecting}. To select native English speakers, we published tasks for Workers residing in an English speaking country (US, CA, UK, AU, NZ) and asked them what their first language was. 600 Workers participated in the task; 550 answered English as their first language. We regarded the 550 Workers as native English speakers, and divide them in half into two groups: G1 and G2.\\ \indent Figure \ref{fig:paraphrase_instruction} shows a screenshot of the main instructions given for the paraphrase HITs. Workers were asked to listen to a set of focused speech samples for one caption, where each speech item was randomly selected from available recordings (Figure \ref{fig:overview}), and then told to come up with a written sentence for that speech item which clearly conveyed the implied meaning in the emphasised speech. We encouraged Workers to freely make changes in grammar and vocabulary but not to use capitalisation, an exclamation mark, or the addition of their own inferences or text providing situational context. We prepared a qualification test for the native speakers in G1, in which they needed to make a brief summary of the instructions in their own words as well as complete the paraphrasing tasks. After manually checking the results, we allowed those who completed the task as instructed to start the main paraphrase HITs. Two workers performed each HIT, obtaining two paraphrases for each emphasised speech sample. We paid \$0.15 for each paraphrasing, resulting in \$16.5 per hour on average. We obtained 2130 paraphrases from 16 Workers. \subsection{Filtering paraphrases} The quality of the paraphrases produced by the Workers will influence future research using the corpus. To evaluate the quality, we set subjective evaluation HITs. Workers were presented with emphasised speech and a paraphrase and asked to evaluate its quality from two perspectives on a scale from one to five: (A) how accurately the paraphrase conveyed the implied meaning in speech; (B) how well-formatted the paraphrase sentence is. We set a qualification task for the native speakers in G2 in the same way as the paraphrase collection and asked those who passed to join the main evaluation HITs (16 Workers). Three different Workers evaluated each paraphrase. We calculated median values for both perspectives (Figure \ref{fig:overview}), and samples with a value of 3 or less for perspective (A) and 2 or less for (B) were discarded. We collected the paraphrases again for those removed samples, and repeated the same procedure of evaluation and removing as above. We paid \$0.10 for evaluating each paraphrase, resulting in \$25.0 per hour on average. After the evaluation in MTurk, we filtered out paraphrases which fell one of the following conditions: paraphrases with relatively high variance of the accuracy evaluation scores ($\sigma^2$ $>$ 1.6), e.g. scores: 2, 5, 5); The tense changed from present to past, e.g. (\textit{The men are climbing.} / \textit{The men were climbing on something.}) After the filtering, we had 1697 paraphrases. Table \ref{tab:corpus_example} shows an example of speech and paraphrase pairs. \begin{table}[h] \caption{Example speech-paraphrase pairs in the corpus} \scriptsize \centering \begin{tabular}{c|c} Focused speech & Paraphrase \\ \hline \textbf{A} biker enjoys a coffee & One biker enjoys a coffee \\ \textbf{A} biker enjoys a coffee & There is one biker enjoying a coffee \\ A \textbf{biker} enjoys a coffee & It's a biker enjoying a coffee \\ A \textbf{biker} enjoys a coffee & The person enjoying a coffee is a biker \\ A biker \textbf{enjoys} a coffee & A biker drinking a coffee is enjoying it \\ A biker \textbf{enjoys} a coffee & The biker seems to enjoy a coffee \\ A biker enjoys \textbf{a} coffee & A biker enjoys one coffee \\ A biker enjoys \textbf{a} coffee & A biker has one coffee he enjoys \\ A biker enjoys a \textbf{coffee} & What the biker enjoys is a coffee \\ A biker enjoys a \textbf{coffee} & It is coffee the biker enjoys \\ \end{tabular} \label{tab:corpus_example} \end{table} \section{Analysis} To explore how focus in speech was mapped into the linguistic domain, we hand-examined the samples of speech-paraphrase pairs and made broad categorisations of the transformation patterns as follows; from lexical and grammatical perspectives (the patterns do not cover all the transformation methods). \begin{itemize}[leftmargin=*] \item Lexical transformations \begin{itemize}[leftmargin=15pt] \item \label{substitution} \textbf{Substitution}:~substitute the focused word with its synonyms, e.g. (\textit{\textbf{dog}} / \textit{canine}), (\textit{\textbf{on}} / \textit{on top of}). \item \label{modification} \textbf{Modification}:~modify the focused word or its phrase with modifiers such as adverbs or a clause, e.g. (\textit{\textbf{play}} / \textit{play actively}), (\textit{\textbf{is}} / \textit{is indeed}). \item \label{negation} \textbf{Negation}:~explicitly state an alternative of the focused word and negate it (\textit{A \textbf{man}} / \textit{A man, not a woman}). \end{itemize} \item Grammatical transformations \begin{itemize}[leftmargin=12pt] \item \label{leftward} \textbf{Leftward shift}:~move the focused word towards the beginning of the sentence. Grammatical constructions such as cleft, reversed-pseudo-cleft and inversion were used, e.g. (\textit{\textbf{People} sit .. } / \textit{It's people who sit ..}), (\textit{.. play \textbf{baseball}} / \textit{baseball is what .. play}). \item \label{rightward} \textbf{Rightward shift}:~move the focused word towards the end of the sentence. Grammatical constructions such as pseudo-cleft, inversion and other methods were used, e.g. (\textit{Children \textbf{play} ..} / \textit{what children do .. is play}), (\textit{ .. is \textbf{rock} climbing} / \textit{.. is climbing a rock} \item \textbf{Tense change}:~change the tense from simple to progressive or vice versa, e.g. (\textit{\textbf{is} walking} / \textit{walks}). \end{itemize} \end{itemize} Furthermore, we observed that a certain part-of-speech is more likely to use a certain transformation method. To quantify this tendency, following a method taken for analysis of paraphrase alternations \cite{dolan2004unsupervised}, we randomly sampled 50 paraphrases for each part-of-speech if it had more than 50 occurrences in the corpus and compared the frequency of each transformation method. We counted each phenomenon for each sentence. We restricted the counting only if the focused word or the phrase of the focused word undergoes transformations listed above. Consider this example: (\textit{a dog trots through \textbf{the} grass} / \textit{\underline{the only grassy area} is what a dog trots through}). In this case, not only the focused word \textit{the}, but also the noun phrase it involved, indicated by underline, was under investigation; \textit{only} was inserted (modification), and \textit{grass} was replaced with \textit{grassy area} (substitution). As a grammatical method, reversed-pseudo-cleft (leftward shift) was used. Table \ref{tab: phenometa} shows the average number of occurrences of each transformation in each focused part-of-speech. The pattern of the tense change was counted only when the focused word was verbs or auxiliary verbs. \begin{table}[h]\centering \caption{Mean occurrences of each transformation method per part-of-speech (N: Noun, V: Verb, Adj: Adjective, Num: Numeral, Aux: Auxiliary, P: Preposition, Det: Determiner)}\label{tab: phenometa} \tiny \begin{tabular}{llccccccc} \toprule &&N &V & Adj &Num & Aux & P & Det \\ \midrule \multirow{3}{*}{Lexical}&Substitution &0.28 & 0.12 & 0.10 & 0.18 & 0.08 & 0.42 & 0.72 \\ &Modification &0.00 & 0.02 & 0.12 & 0.06 & 0.60 & 0.18 & 0.50\\ &Negation &0.10 & 0.06 & 0.06 & 0.12 & 0.10 & 0.12 & 0.00 \\ \midrule \multirow{3}{*}{Grammatical}&Leftward &0.10 & 0.20 & 0.04 & 0.08 & 0.00 & 0.10 & 0.00 \\ &Rightward &0.46 & 0.44 & 0.70 & 0.52 & 0.08 & 0.26 & 0.02\\ &Tense &-& 0.28 & -&-&0.20 & -& - \\ \bottomrule \end{tabular} \label{tab:phenomena} \end{table} \section{Discussion and conclusion} This study set out to create a corpus containing focused speech, where each speech item differs in the placement of focus, and the corresponding text which paraphrases the speech together with its paralinguistically expressed implications. Through our data analysis, we show that the transformation of focus information from the paralinguistic domain to the linguistic domain makes use of a variety of lexical and grammatical devices, and reliance on these methods vary depending on the syntactic category of the focused word. Many of the transformation methods observed in data were the types that have been reported as such devices in the literature, e.g. cleft-constructions in the leftward shift and pseudo-clefting in the leftward shift and negation, which serves the exact purpose of focus defined earlier; indicating the presence of alternatives. On the other hand, we also found some interesting methods such as lexical substitution, e.g. (\textit{\textbf{man}} / \textit{male adult}). \\ \indent One of the limitations of the current study is lack of context; \textit{Why do I/they emphasise this word?} In regular paraphrasing tasks, paraphrases and their evaluations can vary depending on context \cite{barzilay2001extracting}. The importance of context would also be the case for the collection of focused speech and the corresponding text. In future work, we will consider presenting contextual information when collecting recordings and paraphrases. \\ \indent Despite the limitations, the current work added a new direction toward further improvement of paralinguistic translation; we demonstrated the possibility of mapping paralinguistic information into the linguistic domain. The corpus and insights from our analysis will lead us to construct a ST model which uses the paraphrased text to preserve paralinguistic information. \section{Acknowledgement} Part of this work is supported by JSPS KAKENHI Grant Number JP21H05054. \bibliographystyle{IEEEtran}
{'timestamp': '2022-09-30T02:06:06', 'yymm': '2203', 'arxiv_id': '2203.15483', 'language': 'en', 'url': 'https://arxiv.org/abs/2203.15483'}
arxiv
\section{Introduction} Automatic speech recognition (ASR) is the task of converting speech audio into its text transcripts. Early methodologies trained linguistic, acoustic, and lexicon modules separately \cite{intro1, intro2}; however, up until a decade ago, neural networks showed an improvement of performance while also being significantly easier to train, with all of the modules trained altogether in an end-to-end fashion \cite{e2e_asr1, e2e_asr2}. With the recent successful use of end-to-end models in ASR, many of these have become commercially available as products, bringing in many benefits and conveniences to humans by enabling the control of several devices through speech. With such conveniences, ASR has the potential to benefit many people; however, disabled patients, who would benefit the most from these devices, are hindered from using these owing to their loss of control of their speech organs \cite{pathological_speech}. One common speech pathology is dysarthria, which makes them speak at a slower rate and with a slurred characteristic. Another speech pathology could be due to laryngectomy, which is the replacement of the larynx with an electro-larynx to recreate its function, but results in robotic-like speech production. In both of these speech pathologies, communication becomes difficult, which causes the produced speech to be misunderstood by most commercial ASR devices \cite{inclusive_asr}. Knowing the benefits of ASR, much more research to make ASR accessible to speakers with speech pathologies should be carried out. Unfortunately, only having a small number of publicly available datasets, coupled with the huge data requirements to train networks, have made this a difficult task. One mainstream method to resolve minimally resourced ASR is by pretraining, which is training the network on a large dataset of healthy speech before fine-tuning on limited pathological speech datasets. Investigations such as those in \cite{google1} show drastic improvements in performance through a pretraining framework using a Recurrent Neural Network Transducer (RNN-T) pretrained on 1,000 hours of healthy speech data, even with only less than an hour of pathological speech in the fine-tuning stage. Building on this study, increasing pretraining data to roughly 162,000 hours in \cite{google2, google3} makes personalized RNN-T models become capable of outperforming human listeners on speech with low intelligibility rates and allow 90\% of speakers to reach 15\% word error rate even with only using less than 250 utterances in fine-tuning. In the aforementioned investigations, using a good pretraining strategy and more data proves that the network can adapt to the pathological speech features easily even when only fine-tuned on a small number of data. However, one limitation in the previously mentioned works is that the model is pretrained in a supervised fashion, which heavily relies on having a dataset that provides both the speech audio and its corresponding text labels to succeed. Although many speech data has been made publicly available, large-scale data labeling is still a very tedious task, making it not a sustainable pretraining method for use in the future. In this paper, we investigate a novel pretraining method called self-supervised learning, which provides flexibility in the training requirements by removing the need for labeled data to train the network. The general idea of this method is to make the model learn a universal representation of the data using joint embedding objective functions \cite{joint-emb, joint-emb2} to compare embedding representations of the data. For speech in particular, several frameworks have been proposed \cite{yang2021superb} such as generative modeling \cite{generative}, discriminative/contrastive modeling \cite{w2v-2,w2v-xlsr,wavlm}, and multitask learning \cite{multitask}. Research in \cite{analysis_dysasr} has shown contrastive-learning-based SSL pretraining capable of outperforming supervised pretraining on dysarthric speech; however, the research could still be further extended by using more SSL frameworks, while also using other supervised pretraining setups as baseline. We contribute the following points in this investigation: \begin{itemize} \item We investigate two self-supervised learning pretraining frameworks (contrastive and masked region prediction) for pathological speech recognition and compare them with supervised pretraining. \item We analyze two types of pathological speech, namely, electrolaryngeal and dysarthric. \item We show that although SSL pretraining has been successful on minimally resourced healthy speech, extensive experiments show that this is not exactly the case for pathological speech. \end{itemize} \begin{figure*}[t!] \centering \includegraphics[width=15cm]{img/ssl_archi2.png} \caption{Overview of SSL training. The SSL models wav2vec 2.0 \cite{w2v-2} (left) and WavLM \cite{wavlm} (middle) are first pretrained by a contrastive or masked region prediction framework. The SSL model is then fine-tuned by supervised training, treated similarly to an end-to-end model (right).} \label{fig:architecture} \end{figure*} \section{Using self-supervised learning pretraining frameworks for ASR} With the successful use of previous pretraining methods, we explore the effectiveness of a new pretraining framework called self-supervised learning (SSL). In this section, we present how SSL models learn speech representations and how they can be used for ASR tasks. An overview of using SSL models, which is divided into pretraining and fine-tuning stages, is shown in Figure~\ref{fig:architecture}. \subsection{Pretraining SSL models to learn speech representations} We investigate two self-supervised pretraining frameworks that are similar to the one used in \cite{analysis_dysasr}: contrastive loss \cite{w2v-2} and masked region prediction \cite{wavlm}. The first framework is wav2vec 2.0 \cite{w2v-2}, one of the most widely used SSL frameworks in speech data based on contrastive loss and proven to be successfully used in different minimally resourced speech recognition tasks \cite{ssl_ind, ssl_l2}. This framework uses a multilayer convolutional neural network (CNN) to encode speech into a latent space $z_{1:j}$ (Eq. \ref{cnn}). The latent space representations are then quantized as $q_{1:j}$ (Eq. \ref{quantizer}) and randomly masked before being passed onto the multihead self-attention layers of the Transformer encoder backbone (Eq. \ref{tf}). The model is optimized using a contrastive loss function by identifying a $q$ from $q_{1:j}$ among a set of distractors $q'$ given the masked context representation vector $h_{1:j}$ from the Transformer encoder. \begin{equation} z_{1:j} = \operatorname{CNN}(x_{1:i}) \label{cnn} \end{equation} \begin{equation} q_{1:j} = \operatorname{quantization}(z_{1:j}) \label{quantizer} \end{equation} \begin{equation} h_{1:j} = \operatorname{Transformer}(\operatorname{masking}(z_{1:j})) \label{tf} \end{equation} Next, we investigate a new SSL framework called WavLM \cite{wavlm} that instead uses masked region prediction to learn speech representations. WavLM does this through a denoising and prediction framework, mixing utterances by adding interfering speech and noise to the input speech, and making the model predict the original clean speech. Its architecture is similar to that of wav2vec 2.0, where the noisy input speech is passed onto a set of CNN layers to make $z_{1:j}$ and randomly masked before passing it onto the Transformer network, which then predicts the pseudo-labels of the masked regions $h_{1:j}$. The target pseudo-labels $k_{1:j}$ are generated by performing two iterations of k-means clustering: one on the MFCC of the original clean speech $x_{1:i}$ (Eq. \ref{kmeans1}) and another on the latent representations $z_{1:j}$ (Eq. \ref{kmeans2}). Moreover, a gated relative position bias is added to the Transformer backbone to better capture the sequence ordering of the noisy input speech. Training the model through this denoising framework proves to make the model robust to acoustic variations in the speech. \begin{equation} k_{1:j} = \operatorname{k-means}(\operatorname{MFCC}(x_{1:i})) \label{kmeans1} \end{equation} \begin{equation} k_{1:j} = \operatorname{k-means}(z_{1:j}) \label{kmeans2} \end{equation} \subsection{Fine-tuning SSL models for ASR tasks} After learning the speech representations, the SSL model is then fine-tuned to predict the text tokens by attaching a decoder, making it similar to a regular end-to-end framework, as seen in the rightmost portion of Figure ~\ref{fig:architecture}. Given an input speech sequence of \(x_{1:i}\), the SSL model maps these into a hidden latent space as \(h_{1:j}\) and is decoded into the text \(y_{1:k}\). Another encoder can also be optionally added after the SSL model to further preprocess \(h_{1:j}\) into \(h'_{1:j}\). Frameworks such as the Connectionist Temporal Classification (CTC) \cite{ctc} decode \(h_{1:j}\) by predicting a text token for each frame. Other popular frameworks predict the text using attention (ATTN) with decoders such as the Recurrent Neural Network \cite{las} or the Transformer \cite{transformer}. Combining CTC and attention (CTC-A) \cite{ctc-attn, ctc-attn2} through a weighted sum has also proven to be effective to decode the text. \section{Pretraining implementation of pathological speech recognition} In the following subsections, we describe how we implement the pretraining frameworks for this investigation. In general, we first pretrain a model on a large dataset to make it learn a general idea of speech and subsequently fine-tune it on the pathological dataset for adaptation. \subsection{Self-supervised pretraining setup} After pretraining the SSL model, we fine-tune it by attaching a decoder to its last layer. Two decoder setups for fine-tuning are compared. The first is using the original ASR setup in wav2vec 2.0 and WavLM, where a linear projection layer is attached and trained by CTC. Next, following the convention in \cite{analysis_dysasr}, we train by CTC-A by using a vanilla 2-layer 1024-unit LSTM decoder, as recommended in the ASR setup in \cite{yang2021superb}. As pathological speech is extremely acoustically different from healthy speech, we also investigate the effectiveness of adding an extra encoder to further pre-process the SSL features before passing it onto the decoder. Two additional encoders are compared with preprocessing the SSL representations, the Conformer \cite{conformer} and Transformer \cite{transformer}, owing to the strong ability of self-attention to learn representations. We use two attention heads and two layer blocks for both encoders. We then refer to using the SSL representations directly as using an Identity encoder. We find better performance when only the CNN layers of the SSL models are frozen during fine-tuning. The rest of the SSL model components, the encoder, and the decoder are fine-tuned. \subsection{Supervised pretraining baseline setup} We compare SSL pretraining with the following supervised pretraining setups. We use the Transformer \cite{transformer} and Conformer \cite{conformer} as the encoders, both of which have produced the lowest word error rate when using the Librispeech \cite{librispeech} dataset in supervised training\footnote{\url{https://github.com/syhw/wer_are_we}}. Both encoders have eight attention heads, although the Transformer has 18 layer blocks, while the Conformer only has 12 layer blocks. The decoder for both encoders is a Transformer composed of eight attention heads and eight layer blocks, and trained by CTC-A. The pretraining stage outputs and predicts byte-pair encoding (bpe) tokens \cite{bpe}; however, in the fine-tuning stage, we initialize a new output layer to decode English and Japanese character tokens instead. For UASpeech, we also compare our results with those obtained using end-to-end models found in \cite{cuhk} that predict the character tokens by using a CONV+BLSTM encoder trained using CTC and ATTN with mel-scale filter banks and pitch as inputs. \section{Experimental setup} \subsection{Datasets} To pretrain the supervised models, we use the 960 hours of Librispeech \cite{librispeech}. On the other hand, SSL pretraining varies per model, with wav2vec 2.0 pretrained on 60k hours of speech and WavLM pretrained on 94k hours of speech. In the fine-tuning stage, we use two pathological speech datasets, as summarized in Table \ref{tab:datasets}. We first investigate an in-house recorded dataset of Japanese electrolaryngeal speech, which we refer to as ELSpeech in this paper. The dataset is recorded by a laryngeal speaker by speaking 1000 different sentence utterances both with an electrolarynx and with their normal voice. We use 85\% of the data for the training set, and the rest for the test set. Both the healthy and electrolaryngeal speeches are used in the train and dev sets but only the electrolarygneal speech used in the test set. As the dataset is in Japanese, we use the character error rate (CER) as the evaluation metric. The next dataset we use is UASpeech \cite{UASpeech}, a dataset containing parallel English word utterances of 15 dysarthric speakers and 13 healthy speakers. We follow the recommendations in \cite{cuhk} and use both the dysarthric and healthy speakers to train the ASR system but only use the dysarthric speakers for the test set, and remove excessive silences at the start and end of each utterance using a GMM-HMM system\footnote{\url{https://github.com/ffxiong/uaspeech}}. The train and dev sets are from the B1 and B3 blocks, whereas the test set is from the B2 block. We follow the convention of the said paper and use the word error rate (WER) as our evaluation metric. \begin{table}[th] \centering \caption{Duration (in number of hours) of each split used in the experiment. UASpeech results are obtained after silence removal.} \footnotesize \label{tab:datasets} \begin{tabular}{cccccc} \toprule & \multicolumn{2}{c}{\textbf{Healthy}} & \multicolumn{2}{c}{\textbf{Pathological}} & \\ \cmidrule(lr){2-3} \cmidrule(lr){4-5} \textbf{Dataset} & \textbf{Train} & \textbf{Dev} & \textbf{Train} & \textbf{Dev} & \textbf{Test} \\ \midrule \midrule UASpeech \cite{UASpeech} & 2.38 & 0.45 & 3.60 & 0.68 & 2.09 \\ ELSpeech & 1.21 & 0.37 & 1.40 & 0.46 & 0.42 \\% 1.40 & 0.46 & 1.21 & 0.37 & 0.42 \\ \bottomrule \end{tabular} \end{table} \begin{table}[h!] \centering \caption{CER comparison between using different SSL features and raw features in ELSpeech. ** indicates end-to-end models pretrained with 960h Librispeech.} \label{tab:el1} \scriptsize \begin{tabular}{rllllc \toprule \multicolumn{1}{r}{\textbf{Sys.}} & \multicolumn{1}{l}{\textbf{Features}} & \multicolumn{1}{l}{\textbf{Encoder}} & \multicolumn{1}{l}{\textbf{Decoder}} & \multicolumn{1}{l}{\textbf{Loss}} & \multicolumn{1}{l}{\textbf{CER\%}} \\ \midrule \midrule 1 & \multirow{2}{*}{\makecell[l]{Raw\\waveform}} & \textbf{Conf.**} & \textbf{Transf.**} & \textbf{CTC-A} & \textbf{27.9} \\ 2 & & Transf.** & Transf.** & CTC-A & 61.5 \\ \midrule 3 & \multirow{4}{*}{\begin{tabular}[c]{@{}l@{}}wav2vec 2.0\\\end{tabular}} & Identity & Linear & CTC & 93.3 \\ 4 & & Identity & LSTM & CTC-A & 89.2 \\ 5 & & Conf. & LSTM & CTC-A & 54.1 \\ 6 & & Transf. & LSTM & CTC-A & 50.2 \\ \midrule 7 & \multirow{4}{*}{\begin{tabular}[c]{@{}l@{}}wav2vec 2.0\\ (XLSR)\end{tabular}} & Identity & Linear & CTC & 99.6 \\ 8 & & Identity & LSTM & CTC-A & 89.9 \\ 9 & & Conf. & LSTM & CTC-A & 90.2 \\ 10 & & Transf. & LSTM & CTC-A & 71.5 \\ \midrule 11 & \multirow{4}{*}{WavLM} & Identity & Linear & CTC & 54.9 \\ 12 & & \textbf{Identity} & \textbf{LSTM} & \textbf{CTC-A} & \textbf{41.8} \\ 13 & & Conf. & LSTM & CTC-A & 42.5 \\ 14 & & Transf. & LSTM & CTC-A & 46.0 \\ \midrule \end{tabular} \end{table} \subsection{Implementation} We use ESPnet \cite{espnet, espnet-2020} to implement the end-to-end ASR models and the s3prl frontend \cite{yang2021superb} to use the SSL models. Both toolkits are open-sourced. The SSL models we use are the wav2vec 2.0 Large and WavLM Large models, which are both available to the public. All networks in this investigation target predicting the character tokens. We fine-tune the networks' learning rate in steps of $10^{-n}$ where $n \in \{ 0, 1, 2, 3, 4, 5 \}$ and use the best results from each run. The language models used are based on the Transformer \cite{transformer} architecture and trained on each dataset's training set text. In Tables \ref{tab:el1} and \ref{tab:ua1}, we will refer to the Conformer architecture as "Conf." and the Transformer architecture as "Transf.". \section{Results} \begin{table*}[h!] \centering \caption{WER comparison between using different SSL features, mel-scale filter bank, and raw waveforms in UASpeech. ** indicates models pretrained with 960h Librispeech.} \scriptsize \label{tab:ua1} \begin{tabular}{rllllccccc} \toprule & & & & & \multicolumn{5}{c}{\textbf{WER\% of each intelligibility rating}} \\ \cmidrule(lr){6-10} \textbf{Sys.} & \textbf{Features} & \textbf{Encoder} & \textbf{Decoder} & \textbf{Loss} & \textbf{Overall} & \textbf{Very Low} & \textbf{Low} & \textbf{Mid} & \textbf{High} \\ \midrule \midrule 1 & \multirow{2}{*}{Mel-scale filter bank} & Conv+BLSTM \cite{cuhk} & Linear & CTC & 58.0 & 87.1 & 62.4 & 55.3 & 37.8 \\ 2 & & \textbf{Conv+BLSTM**} \cite{cuhk} & \textbf{LSTM**} & \textbf{ATTN} & \textbf{35.0} & \textbf{68.7} & \textbf{39.0} & \textbf{32.5} & \textbf{12.2} \\ \midrule 3 & \multirow{2}{*}{Raw waveform} & Conf.** & Transf.** & CTC-A & 67.2 & 90.6 & 73.6 & 64.1 & 46.6 \\ 4 & & Transf.** & Transf.** & CTC-A & 68.2 & 89.6 & 73.9 & 66.2 & 48.7 \\ \midrule 5 & \multirow{4}{*}{wav2vec 2.0} & Identity & Linear & CTC & 75.7 & 93.1 & 79.4 & 74.1 & 60.4 \\ 6 & & Identity & LSTM & CTC-A & 96.4 & 97.9 & 97.5 & 95.8 & 95.0 \\ 7 & & Conf. & LSTM & CTC-A & 71.7 & 92.3 & 74.6 & 68.7 & 55.3 \\ 8 & & Transf. & LSTM & CTC-A & 71.8 & 93.8 & 83.7 & 69.7 & 48.4 \\ \midrule 9 & \multirow{4}{*}{WavLM} & Identity & Linear & CTC & 91.5 & 97.3 & 92.3 & 90.5 & 87.1 \\ 10 & & \textbf{Identity} & \textbf{LSTM} & \textbf{CTC-A} & \textbf{51.8} & \textbf{71.5} & \textbf{50.0} & \textbf{46.0} & \textbf{40.6} \\ 11 & & Conf. & LSTM & CTC-A & 70.1 & 94.1 & 81.3 & 67.1 & 48.5 \\ 12 & & Transf. & LSTM & CTC-A & 77.2 & 94.5 & 83.9 & 75.3 & 60.3 \\ \midrule \end{tabular} \end{table*} \subsection{Comparison of SSL frameworks} First, we analyze the two SSL model frameworks. As seen in Sys. 12 in Table \ref{tab:el1} and Sys. 10 in Table \ref{tab:ua1}, using the WavLM model with an LSTM decoder outperforms all setups using wav2vec 2.0 in both datasets, as it produces the lowest CER (41.8\%) and WER (51.8\%), making it the best SSL setup. This performance can be attributed to the speech denoising framework used in masked region prediction, which makes the model more robust to acoustic variations in speech features found in pathological speech and the attention-based LSTM decoder, thereby improving the representation learning. A similar trend in both datasets is also seen when using an additional Conformer or Transformer encoder (Sys. 5, 6, 13, and 14 in Table \ref{tab:el1} and Sys. 7, 8, 11, and 12 in Table \ref{tab:ua1}) to preprocess the SSL features, where it degrades the performance with WavLM, but improves wav2vec 2.0. This shows that the wav2vec 2.0 features are not as strong in projecting the pathological speech into a latent space and needs further processing for it to properly work. Moreover, as the SSL models are trained in English and the ELSpeech dataset is in Japanese, we also test the performance of the multilingually pretrained wav2vec XLSR model \cite{w2v-xlsr}, which has been successfully used in decoding languages not included in the pretraining data. However, we do not find any success to this approach, as seen in Table \ref{tab:el1}, where we see a degradation in performance when using XLSR for all setups compared with its wav2vec 2.0 counterparts. \subsection{Comparison of SSL pretraining and supervised pretraining} We present two findings when comparing these two pretraining methods. First, we see a trend similar to that in \cite{analysis_dysasr}, where the best SSL setups in Sys. 12 in Table \ref{tab:el1} and Sys. 10 in Table \ref{tab:ua1} outperform the pretrained Transformer setups in Sys. 2 in Table \ref{tab:el1} and Sys. 4 in Table \ref{tab:ua1}, proving that SSL pretraining has the potential to outperform supervised pretraining. However, our second finding is that other supervised setups not used in \cite{analysis_dysasr} may still outperform SSL pretraining. As seen Sys. 1 in Table \ref{tab:el1}, using a pretrained Conformer-Transformer model produces the lowest CER (27.9\%) for ELSpeech, outperforming the best SSL setup by 13.9\%. On the other hand, although the Conformer-Transformer setup (Sys. 3 in Table \ref{tab:ua1}) did not perform very well in UASpeech, \cite{cuhk} showed that using a pretrained Conv+LSTM model with 40-dimensional mel-scale filter banks as inputs can still outperform our best SSL setup by 16.8\%, as seen in Sys. 2 in Table \ref{tab:ua1}. \subsection{Visualizing differences of dysarthric speech in the latent space} As seen in the results, SSL pretraining did not exactly outperform supervised pretraining in both pathological speech datasets. We attribute this to the stark acoustical differences in pathological speech, as similarly seen in previous research on automatically categorizing dysarthric speech intelligibility \cite{analysis_dyscategorization}, where supervised models outperformed the pretrained SSL model. We then try to visualize the high-dimensional extractions using mel-log filterbank and pitch, raw waveforms, and SSL features with the UASpeech dataset and flatten these on a 2D space using t-SNE \cite{t-sne}. Each point represents one frame in the utterance and is colored according to the speakers' intelligibility rating. We use the first 20 utterances in the B1 block from three speakers in each intelligibility rating. We see in Figure ~\ref{fig:tsne} that raw audio waveforms are projected similarly to the SSL features, proving that there is space to further improve SSL models on pathological speech and improve them at the same level as supervised pretraining. Furthermore, more of the lower intelligibility utterances (green and red) are pushed to the outside, whereas more of the higher intelligibility utterances (purple and blue) are clustered at the center. However, we also see that the mel-scale filter bank extractions seem to blend together the pathological and healthy utterances. One hypothesis we draw from this is that the model may not be able to differentiate the pathological features from the healthy features when using this input, which may have improved the performance. \begin{figure}[th] \centering \includegraphics[width=8cm]{img/tsne2.png} \caption{Pathological speech frame extractions visualized in 2D via t-SNE \cite{t-sne}. Illustrated left to right are mel-scale filter banks with pitch, raw waveforms, WavLM, and wav2vec 2.0} \label{fig:tsne} \end{figure} \section{Conclusions} With ASR providing several conveniences to pathological speech patients, more work should be done to make commercial ASR devices useful for them. We investigated two types of SSL-based pretraining frameworks, contrastive and masked region prediction, on two different pathological speech datasets and compared them with a supervised pretraining framework. Although SSL pretraining frameworks have shown success with minimally resourced healthy speech, this does not seem to be the case with pathological speech. Further investigations in improving the training strategy can be conducted to improve performance in SSL pretraining. Training speaker-dependent models, which has been recommended in several studies \cite{google1, google2, google3}, will be one of the primary targets in the future. \section{Acknowledgements} This work was partly supported by AMED under Grant Number JP21dk0310114, Japan, and JST CREST Grant Number JPMJCR19A3. \bibliographystyle{IEEEtran}
{'timestamp': '2022-06-30T02:13:24', 'yymm': '2203', 'arxiv_id': '2203.15431', 'language': 'en', 'url': 'https://arxiv.org/abs/2203.15431'}
arxiv
\section{Background} \label{sec:background} \subsection{Event logs} \label{ssec:log} An \emph{event log} consists of traces representing executions of a process (a.k.a.~a case). A trace is a sequence of \emph{events}, each referring to the execution of an activity (a.k.a.~an event class). Besides timestamps, indicating the time in which the event has occurred, events in a trace may have a data payload consisting of attributes, such as, the resource(s) involved in the execution of an activity, or other data recorded during the event. Some of these attributes do not change throughout the different events in the trace, i.e., they refer to the whole case (\emph{trace attributes}); for instance, the personal data (\attr{Birth date}) of a customer in a loan request process. Other attributes are specific of an event (\emph{event attributes}), for instance, the employee who creates an offer (\attr{resource}), which is specific of the activity \act{Create offer}. \subsection{Prescriptive Process Monitoring} \label{ssec:prescriptive} Prescriptive Process Monitoring~\cite{fahrenkrog2019fire,metzger2020triggering} is a branch of Process Mining that aims at suggesting activities or triggering interventions for a process execution for optimizing a desired Key Performance Indicator (KPI). Differently from Predictive Process Monitoring approaches, which aim at predicting the future of an ongoing execution trace, Prescriptive Process Monitoring techniques aim at recommending the best interventions for achieving a target business goal. For instance, a bank could be interested in minimizing the cost of granting a loan to a customer. In such a scenario, the KPI of interest for the bank is the cost of the activities carried out by the bank's personnel in order to reach an agreement with the customer. The best actions that the bank should carry out to achieve the business goal (reaching the agreement while minimizing the processing time) can be recommended to the bank. \subsection{Reinforcement Learning} \label{ssec:reinforcement} Reinforcement Learning (RL)~\cite{Sutton1998,junyanhu} refers to techniques providing an intelligent agent the capability to act in an environment, while maximizing the total amount of reward received by its actions. At each time step $t$, the agent chooses and executes an \emph{action} $a$ in response to the observation of the \emph{state} of the environment $s$. The action execution causes, at the next time step $t+1$, the environment to stochastically move to a new state $s'$, and gives the agent a \emph{reward} $r_{t+1}=\mathcal{R}(s,a,s')$ that indicates how well the agent has performed. The probability that, given the current state $s$ and the action $a$, the environment moves into the new state $s'$ is given by the state transition function $\mathcal{P}(s,a,s')$. The learning problem is therefore described as a discrete-time Markov Decision Process (MDP), which is formally defined by a tuple $M=(\mathcal{S}, \mathcal{A}, \mathcal{P},\mathcal{R}, \gamma)$: \begin{itemize}[label=$\bullet$] \item $\mathcal{S}$ is the set of states. \item $\mathcal{A}$ is the set of agent's actions. \item $\mathcal{P}:\mathcal{S} \times \mathcal{A} \times \mathcal{S} \rightarrow [0,1]$ is the transition probability function. $\mathcal{P}(s,a,s') = Pr(s_{t+1} = s' | s_t = s, a_t = a)$ is the probability of transition (at time $t$) from state $s$ to state $s'$ under action $a \in \mathcal{A}$. \item $\mathcal{R}: \mathcal{S} \times \mathcal{A} \times \mathcal{S} \rightarrow \mathbb{R}$ is the reward function. $\mathcal{R}(s,a,s')$ is the immediate reward obtained by the transition from state $s$ to $s'$ with action $a$. \item $\gamma \in [0,1]$ is a parameter that measures how much the future rewards are discounted with respect to the immediate reward. Values of $\gamma$ lower than 1 model a decision maker that discount the reward obtained in the more distant future.\footnote{In this paper we set $\gamma=1$, hence equally weighting the reward obtained at each action points of the target actor.} \end{itemize} An MDP satisfies the \emph{Markov Property}, that is, given $s_t$ and $a_t$, the next state $s_{t+1}$ is conditionally independent from all prior states and actions and it only depends on the current state, i.e., $Pr(s_{t+1}| s_t, a_t)=Pr(s_{t+1}|s_0, \cdots, s_t, a_0, \cdots, a_t)$. The goal of RL is computing a \emph{policy} that allows the agent to maximize the cumulative reward. A policy $\pi: \mathcal{S} \rightarrow \mathcal{A}$ is a mapping from each state $s \in \mathcal{S}$ to an action $a \in \mathcal{A}$, and the \emph{cumulative reward} is the (discounted) sum of the rewards obtained by the agent while acting at the various time points $t$. The value of taking the action $a$ in state $s$ and then continuing to use the policy $\pi$, is the expected discounted cumulative reward of the agent, and it is given by the \emph{state-action value function}: $Q^{\pi}(s,a) = \mathbb{E}_\p (\Sigma_{k=0}^\infty\gamma^k r_{k+t+1} |s=s_t,a=a_t )$, where $r_{t+1}$ is the reward obtained at time $t$. The \textit{optimal} policy $\pi^*$ dictates to a user in state $s$ to perform the action that maximises $Q(s,\cdot)$. Hence, the optimal policy $\pi^*$ maximises the cumulative reward that the user obtains by following the actions recommended by the policy $\pi^*$. Action-value functions can be estimated from experience, e.g., by averaging the actual returns for each state (action taken in that state), as with \emph{Monte Carlo methods}. Different algorithms can be used in RL~\cite{Sutton1998}. Among them we can find the \emph{value} and the \emph{policy iteration} approaches. In the former the optimal action-value function $Q^{*}(s,a)$ is obtained by iteratively updating the estimate $Q^{\pi}(s, a)$. In the latter, the starting point is an arbitrary policy $\pi$ that is iteratively evaluated (\emph{evaluation phase}) and improved (\emph{optimization phase}) until convergence. Monte Carlo methods are used in the policy evaluation phase for computing, given a policy $\pi$, for each state-action pair ${(s,a)}$, the action-value function $Q^{\pi}(s,a)$. The estimate of the value of a given state-action pair $(s,a)$ can be computed by averaging the sampled returns that originated from $(s,a)$ over time. Given sufficient time, this procedure can construct a precise estimate $Q$ of the action-value function $Q^{\pi}$. In the policy improvement step, the next policy is obtained by computing a greedy policy with respect to $Q$: given a state $s$, this new policy returns an action that maximizes $Q(s,\cdot)$. \section{Conclusion} \label{sec:conclusion} In this paper we have proposed the use of RL in the solution of the problem of computing next activity recommendations in Prescriptive Process Monitoring problems. Differently from other state-of-the-art works our model handles non deterministic processes, in which only part of the activities are actually actionable and the rest of them are, from the target actor point of view, stochastically selected by the system environment. This is a common situation in multi-actors processes. By taking the decision making perspective of one of the actors involved in a process (target actor), we first learn from past executions the behaviour of the environment and we then use RL to recommend the best activities to carry on in order to optimize a measure of interest. The obtained results show the goodness of the proposed approach in comparison to the policy used by the actor, i.e., without using recommendations. We plan to extend this approach by including in the MDP state the raw information related to the history of the process execution, so as to automate as much as possible the pre-processing phase of our computational pipeline. However, in that case the consequent increase of the state space dimension and its cardinality would require the usage of state generalisation techniques, such as, those implemented with Deep Reinforcement Learning or by applying smart clustering techniques. Moreover, we would like to explore the possibility to use declarative constraints for defining and enforcing domain knowledge constraints. \section{Evaluation of the Recommendation Policy} \label{sec:evaluation} We investigate the capability of the proposed approach to recommend the process activities that allow the target actor to maximize a KPI of interest, i.e., the optimal policy $\pi^*$, (i) when no activity has been executed yet, that is, the whole process execution is recommended; (ii) at different time steps of the process execution (i.e., at different prefix lengths), that is, when only a (remaining) part of the process execution is recommended. We hence explore the following research questions: \begin{enumerate}[label=\textbf{RQ\arabic*},leftmargin=2\parindent,topsep=1.5pt] \item\label{RQ1} How does the recommended sequence of activities (suggested by the optimal policy $\pi^*$) perform in terms of the KPI of interest when no activity has been executed yet? \item\label{RQ2} How does the recommended sequence of activities (suggested by the optimal policy $\pi^*$) perform in terms of the KPI of interest at a given point of the execution? \end{enumerate} Unfortunately, the complexity of evaluating recommendations in the Prescriptive Process Monitoring domain is well known~\cite{DBLP:conf/bpm/Dumas21}. It relates to the difficulty to estimate the performance of recommendations that have possibly not been followed in practice. In order to answer our research questions, we therefore approximate the value of the KPI of interest (i) by leveraging a simulator (simulation evaluation\xspace); (ii) by looking at similar executions in the actual event log (test log evaluation\xspace). In the next subsections we describe the dataset (Section~\ref{ssec:datasets}), we detail the experimental setting (Section~\ref{ssec:setting}), and we finally report the evaluation results (Section~\ref{ssec:results}). \subsection{Datasets} \label{ssec:datasets} We have used two real-world publicly-available datasets that, describing the behaviour of more than one actor, allow us to take the perspective of one of them (target): the BPI Challenge 2012 event log~\cite{vandongen_2012} (\textsc{BPI2012}) and the Road Traffic Fine Management event log~\cite{deleoni_mannhardt_2015} (\textsc{Fines2015}). The BPI Challenge 2012 dataset relates to a Dutch Financial Institute. The process executions reported in the event log refer to an application process for personal loan (see the \emph{Loans}{} scenario in Section~\ref{sec:running}). In this scenario we want to optimize the profit of the bank (\emph{agent}), i.e., to minimize the cost $C$ of granting a loan to a customer (\emph{environment}) while maximizing the interest $I$ of the bank granting the loan. To this aim, we define the KPI of interest for a given execution $e$ as the difference between the amount of interest (if the bank offer is accepted and signed by the customer, namely if the activity \act{Offer accepted} occurs in the trace) and the cost of the employees working time, that is, the value of the KPI for the execution $e$ is $\text{KPI}_{\textsc{BPI2012}}(e) = I(e) - C(e)$. The amount of interest depends on the amount class of the loan request: low ($ \text{amount} \le 6000$), medium ($6000 < \text{amount} \le 15000$) and high ($\text{amount} > 15000$). For the low class, the average interest rate is 16\%, for the medium class, the average interest rate is 18\%, while for the high class is 20\% \footnote{The information on the average interest rate is extracted from the BPI2017~\cite{vandongen_2017} dataset which contains data from the same financial institution.} The cost of the employees' working time is computed assuming an average salary of $18$ euros/h.\footnote{We estimate the average salary of a bank employed in the Netherlands from https://www.salaryexpert.com/salary/job/banking-disbursement-clerk/netherlands.} \begin{table}[t] \centering \scalebox{0.8}{% \begin{tabular} {l@{\hskip 0.2in}c@{\hskip 0.2in}c@{\hskip 0.2in}c@{\hskip 0.2in}c@{\hskip 0.2in}c} \toprule \textbf{Dataset} & \textbf{Trace \#} & \textbf{Variant \#} & \textbf{Event \#} & \textbf{Event class \#} & \textbf{Avg.~trace length}\\ \hline \textsc{BPI2012} & 13087 & 4366 & 262200 & 36 & 20\\ \textsc{Fines2015} & 150370 & 231 & 561470 & 11 & 5\\ \bottomrule \end{tabular} } \vspace{0.3cm} \caption{Dataset Description} \vspace{-1 cm} \label{tab:dataset} \end{table} The second dataset collects data related to an information system of the Italian police. The information system deals with the management of road traffic fines procedures, starting from the fine creation, up to the potential offender's appeal to the judge or to the prefecture (see the \emph{Fines}{} scenario described in Section~\ref{sec:running}). Here, we want to maximize the credits received by the police department (\emph{agent}) based on the fine payments received by the offender (\emph{environment}). The department receives $3$, $2$ or $1$ credits if the fines are fully paid within 6, within 12 months, or after 12 months respectively; it does not receive any credits if the fine is not fully paid, while it receives a discredit if the offender appeals to a judge or to the prefecture and wins, since these cases correspond to a money waste of the police authority. The KPI value for the execution $e$ is KPI$_{\textsc{Fines2015}}(e)$, corresponding to the number of credits received for the execution. Table~\ref{tab:dataset} shows the number of traces, variants, events, event classes and average trace length of the considered datasets. Table~\ref{tab:scenarios} illustrates the MDP components for the two scenarios: the main MDP \emph{actions}; the main MDP \emph{state}{} components, i.e., the last activity (\textsc{LA}), the historical features (\textsc{HF}) and the environment features (\textsc{EF}); as well as the \emph{reward}{}, including the main attributes used for its computation.\footnote{The complete MDP description is available at \url{tinyurl.com/2p8aytrb}.} For example, Table~\ref{tab:preprocessing} shows how a trace related to the \emph{Fines}{} scenario is preprocessed and transformed into an annotated trace, and then into MDP actions, states and rewards. The trace activities are annotated according to whether they have been carried out either by the \emph{agent} or by the \emph{environment}, and the attributes \attr{2months} (the bimester since the fine creation), \attr{amClass} (the fine amount class) and \attr{payType} (type of payment performed) are computed. In the MDP construction step, the agent's activities (with the bimester interval \footnote{\label{note1}The MDP actions in this scenario take into account, besides the activity name, also the 2-month interval (since the creation of the fine) in which the activity has been carried out (\attr{2months}).}) are used as actions, while the state is built by leveraging the last executed activity (\textsc{LA}), the \attr{2months} and the \attr{amClass} attributes. The reward is not null when the payment is finally received and since in this trace the full payment is received after $6$ months, $2$ credits are awarded. Once the log is enriched it is passed to the MDP generation step. We build two MDPs: the MDP$_{\textsc{BPI2012}}$ for the \emph{Loan request handling}\xspace scenario (with 982 states and 15 actions) and the MDP$_{\textsc{Fines2015}}$ for the \emph{Traffic fine management}\xspace scenario (with 215 sates and 70 actions). \input{MDP_table} \begin{table}[t] \centering \scalebox{0.7}{% \begin{tabular}{l@{\hskip 0.1in} c@{\hskip 0.1in} c@{\hskip 0.3in} c@{\hskip 0.1in} c@{\hskip 0.1in} c@{\hskip 0.1in} c@{\hskip 0.3in} l@{\hskip 0.1in} l@{\hskip 0.1in} c} \toprule \multicolumn{3}{l}{\textbf{Trace}} & \multicolumn{4}{l}{\textbf{Enriched trace}} & \multicolumn{3}{l}{\textbf{MDP}} \\ \textbf{activity} & \textbf{timestamp} & \attr{amount} & \attr{2months} & \attr{amClass} & actor & \attr{payType} & \emph{action} & next \emph{state} & \emph{reward} \\ \hline \act{Create fine} & 13/1/21 & 40 & 0 & low & agent & - & \act{Create fine-0} & $\langle \text{\act{Create fine}, 0, low} \rangle$ & 0 \\ \act{Send fine} & 24/1/21 & 40 & 0 & low & agent & - & \act{Send fine-0} & $\langle \text{\act{Send fine}, 0, low} \rangle$ & 0\\ \act{Add penalty} & 18/3/21 & 60 & 1 & high & agent & - & \act{Add penalty-1} & - & -\\ \act{Payment} & 25/7/21 & 60 & 3 & high & env. & full & - & $\langle \text{\act{Payment}, 3, high} \rangle$ & 2 \\ \bottomrule \end{tabular} } \vspace{0.3cm} \caption{Example of the transformation of a trace in the corresponding MDP components. \vspace{-1cm} \label{tab:preprocessing} \end{table} \subsection{Experimental Setting} \label{ssec:setting} In order to answer our research questions, the two event logs have been split in a training part, which is used in in the \emph{RL phase}, and a test part, which is used for the evaluation of the learned policy. For evaluating the computed policies, since in this setting both training and test set size can impact the evaluation results, we use two different splitting criteria (defining the percentage of event log used for the training and the test set): (i) 60\%-40\%{} (60\% of the traces for the training set and 40\% for the test set) and (ii) 80\%-20\%{} (80\% for the training and 20\% for the testing). For the evaluation of the optimal policy obtained by RL and for answering our two research questions, two different evaluations have been carried out: a simulation evaluation\xspace and a test log evaluation\xspace. The simulation evaluation\xspace uses a Monte Carlo simulation similar to the one used in the training phase, but, differently from the training phase, where the MDP is obtained from the training log, here a test MDP, obtained from the test log, is leveraged to simulate the environment response. In this simulation, the optimal policy obtained from the RL approach is compared, in terms of the KPI of interest, against a random policy and against a policy corresponding to the most frequent decisions made by the actor in the actual traces. The value of the reward for each of the simulated policy is computed as the average over 100.000 simulated cases. This evaluation provides a preliminary answer to the first research question \ref{RQ1}. The test log evaluation\xspace aims at comparing the optimal policy obtained from RL with the actual policies used in the process. It is used for answering both our research questions. For \ref{RQ1}, we focus on the policy recommended when no activity has been executed yet. In this setting, we compare the value of the KPI of interest for the traces in the test event log that follow the optimal policy (from the first activity) (i) with the value of the KPI of interest of all the traces in the event log, and (ii) with the value of the KPI of interest of the traces in the event log that do not follow the recommended optimal policy. For \ref{RQ2}, we focus on the policy recommended for ongoing executions, i.e., when some activity has already been executed. We hence consider, for each trace in the test event log, all its prefixes and separately analyze each of them, as a potential ongoing execution. For each prefix $p$ of a trace $t$ in the test event log we compare the value of the KPI of interest of the trace $t$ once completed against an estimation of the value of the KPI obtained following the optimal policy from that execution point forward. The estimation is obtained by averaging the KPI values of the traces in the log that have the same prefix as the reference prefix $p$ and follow the optimal policy from there on. \subsection{Results} \label{ssec:results} In this section we report the results of the two scenarios related to the event logs described in Section~\ref{ssec:datasets}. For both scenarios, as described in Section~\ref{ssec:setting}, we show (i) the results related to the evaluation of the complete optimal policy (\ref{RQ1}) by reporting first the simulation evaluation\xspace and then the test log evaluation\xspace; and (ii) the results related to the evaluation of the optimal policy on the test log assuming that some events have already been executed (\ref{RQ2}). \vspace{0.15cm} \noindent \emph{Research Question \ref{RQ1}.} Table~\ref{tab:simulator} reports the results related to the simulation evaluation\xspace for both the \emph{Loan request handling}\xspace and the \emph{Traffic fine management}\xspace scenarios. For both splitting criterion (60\%-40\%{} and 80\%-20\%) and for each policy analysed, the average KPI value is displayed together with the percentage of executions for which the bank offer has been accepted by the customer (or the fines have been fully paid by the offender). The policies analysed are: the random policy (\textsc{Random}\xspace), the policy selecting the most frequent action in the log for each state (\textsc{Customary}\xspace) and the optimal (\textsc{Optimal}\xspace) policy. \begin{table}[t] \centering \scalebox{0.8}{% \begin{tabular}{l@{\hskip 0.2in} l@{\hskip 0.2in} l@{\hskip 0.2in} c@{\hskip 0.2in} c} \toprule \multirow{2}{*}{\textbf{Scenario}} & \textbf{Splitting} & \multirow{2}{*}{\textbf{Policy}} & \multirow{2}{*}{\textbf{avg. KPI}} & \textbf{\act{Offer accepted} / }\\ & \textbf{criterion} & & & \textbf{full \act{Payment} }\\\hline \multirow{6}{*}{\emph{Loans}} & \multirow{3}{*}{60\%-40\%} & \textsc{Random}\xspace & $36.8$ & $1.4\%$ \\ & & \textsc{Customary}\xspace & $1497.5$ & $38.9\%$ \\ & & \textsc{Optimal}\xspace & $1727$ & $53.7\%$ \\ \cline{2-5} & \multirow{3}{*}{80\%-20\%} & \textsc{Random}\xspace & $35.7$ & $1.5\%$ \\ & & \textsc{Customary}\xspace & $1710.5$ & $43.5\%$ \\ & & \textsc{Optimal}\xspace & $1965.1$ & $61.7\%$ \\ \hline \multirow{6}{*}{\emph{Fines}} & \multirow{3}{*}{60\%-40\%} & \textsc{Random}\xspace & $1.02$ & $36.9\%$ \\ & & \textsc{Customary}\xspace & $1.12$ & $41.7\%$ \\ & &\textsc{Optimal}\xspace & $1.17$ & $42.3\%$ \\ \cline{2-5} & \multirow{3}{*}{80\%-20\%} & \textsc{Random}\xspace & $0.84$ & $30.0\%$ \\ & & \textsc{Customary}\xspace & $0.97$ & $35.0\%$ \\ & & \textsc{Optimal}\xspace & $1.05$ & $37.1\%$ \\ \bottomrule \end{tabular} } \vspace{0.3cm} \caption{Results of the simulation evaluation\xspace for the \emph{Loan request handling}\xspace and the \emph{Traffic fine management}\xspace scenarios.} \vspace{-1cm} \label{tab:simulator} \end{table} The rows related to the \emph{Loan request handling}\xspace scenario (\emph{Loans}) show that for both splitting criteria, the optimal policy (\textsc{Optimal}\xspace) generates an average KPI value much higher than the one obtained with a random policy (\textsc{Random}\xspace), but also higher than the one obtained with a policy characterized by frequently taken actions (\textsc{Customary}\xspace). This result confirms that the proposed \textsc{Optimal}\xspace policy actually outperforms the policy that is frequently taken in the actual traces, which is considered to be an ``optimal'' policy by the target agent. Different optimal (and \textsc{Customary}\xspace) policies are returned with different splitting criteria. When learning with a larger training set and simulating on a smaller test set, the average KPI value increases, for the \textsc{Optimal}\xspace and the \textsc{Customary}\xspace policy, while slightly decreases for the \textsc{Random}\xspace policy. Moreover, the table also shows the percentage of traces that, based on the policy simulations, are finally accepted by the customer. By changing the data splitting criteria, the effect is similar to that observed for the average KPI value for the \textsc{Optimal}\xspace and the \textsc{Customary}\xspace policy, with a percentage of accepted offers raising from around $39\%$ to $43\%$ for the \textsc{Customary}\xspace policy and from around $53\%$ to more than $60\%$ with the \textsc{Optimal}\xspace policy. An almost null increase is observed instead for the \textsc{Random}\xspace policy. The results related to the \emph{Traffic fine management}\xspace scenario are similar to the results of the loan scenario, as shown in the row \emph{Fines}{} of Table~\ref{tab:simulator}. As for the loan scenario, also in this case, for both splitting criteria, the optimal policy returns higher average KPI values (and hence lower money waste) and produces a higher percentage of traces with fully paid fines than the \textsc{Random}\xspace and the \textsc{Customary}\xspace policies. Also in this case, the difference between the \textsc{Optimal}\xspace and the \textsc{Customary}\xspace policy confirms that the proposed recommendation policy improves the policy actually used in practice. In this scenario, however, the difference in terms of percentage of traces for which fines have fully been paid between the optimal and the random policy is lower than for the \emph{Loan request handling}\xspace case. This is possibly due to the overall higher percentage of traces in the \textsc{Fines2015}{} event log for which the fines have been fully paid (40\%) with respect to the percentage of traces in the \textsc{BPI2012}{} log for which the loan offer has been accepted by the customer (17\%), as well as to the higher number of actions of MDP$_{\textsc{Fines2015}}$ with respect to the number of actions of MDP$_{\textsc{BPI2012}}$. Moreover, differently from the \emph{Loan request handling}\xspace{} scenario, there is an overall decrease in terms of average KPI value and of traces with fully paid fines when using a larger training set and a smaller test set (80\%-20\%{} splitting criterion). Table~\ref{tab:log_analysis} shows the results related to the test log evaluation\xspace. For each of the two scenarios and for each splitting criterion, we report the number of traces, the average KPI value, as well as the percentage of traces for which the offer has been accepted (or the fines have been fully paid) for (i) all traces in the test set (\textsc{All}\xspace), (ii) the traces in the test set that follow the optimal policy (\textsc{Optimal P.}\xspace); (iii) the traces in the test set that do not follow the optimal policy (\textsc{Non-Optimal P.}\xspace). \begin{table}[t] \centering \scalebox{0.75}{% \begin{tabular}{l@{\hskip 0.2in} l@{\hskip 0.2in} l@{\hskip 0.2in} c@{\hskip 0.2in} c@{\hskip 0.2in} c} \toprule \multirow{2}{*}{\textbf{Scenario}} & \textbf{Splitting} & \multirow{2}{*}{\textbf{traces}} & \multirow{2}{*}{\textbf{trace \#}} & \textbf{avg} & \textbf{\act{Offer accepted} / } \\ & \textbf{criterion} & & & \textbf{KPI} & \textbf{full \act{Payment} }\\ \hline \multirow{6}{*}{\emph{Loans}} & \multirow{3}{*}{60\%-40\%} & \textsc{All}\xspace & $5197$ & $583.3$ & $16.1\%$ \\ & & \textsc{Optimal P.}\xspace & $1384$ ($26.6\%$) & $1249.7$ & $34.4\%$ \\ & & \textsc{Non-Optimal P.}\xspace & $3813$ ($73.4\%$) & $341.5$ & $9.4\%$ \\ \cline{2-6} & \multirow{3}{*}{80\%-20\%} & \textsc{All}\xspace & $2600$ & $537.2$ & $14.3\%$ \\ & & \textsc{Optimal P.}\xspace & $753$ ($29\%$) & $1082.2$ & $30.4\%$ \\ & & \textsc{Non-Optimal P.}\xspace & $1847$ ($71\%$) & $315.1$ & $7.7\%$ \\ \hline \multirow{6}{*}{\emph{Fines}} & \multirow{3}{*}{60\%-40\%} & \textsc{All}\xspace & $59946$ & $1.11$ & $40.5\%$ \\ & & \textsc{Optimal P.}\xspace & $22665$ ($37.8\%$) & $2.68$ & $90.9\%$ \\ & & \textsc{Non-Optimal P.}\xspace & $37281$ ($62.2\%$) & $0.15$ & $9.9\%$ \\ \cline{2-6} & \multirow{3}{*}{80\%-20\%} & \textsc{All}\xspace & $29973$ & $0.96$ & $34.7\%$ \\ & & \textsc{Optimal P.}\xspace & $9243$ ($30.8\%$) & $2.76$ & $92.7\%$ \\ & & \textsc{Non-Optimal P.}\xspace & $20730$ ($69.2\%$) & $0.16$ & $8.9\%$ \\ \bottomrule \end{tabular} } \vspace{0.3cm} \caption{Results related to the test log evaluation\xspace for the \emph{Loan request handling}\xspace and the \emph{Traffic fine management}\xspace scenario.} \vspace{-1cm} \label{tab:log_analysis} \end{table} The results of the test log evaluation\xspace for the \emph{Loan request handling}\xspace scenario \emph{Loans}) confirm the results obtained with the simulation evaluation\xspace. For both splitting criteria, indeed, the average KPI value of the traces following the optimal policy (\textsc{Optimal P.}\xspace) is higher than the average KPI value of all the traces (\textsc{All}\xspace), which in turn is higher than the average KPI value of the traces that do not follow the optimal policy (\textsc{Non-Optimal P.}\xspace). The traces following the optimal policy generate an average bank profit of more than 500 euros higher than the average bank profit of all the traces in the event log, as well as of more than 750 euros higher than the average bank profit of the traces that do not follow the optimal policy. The same ranking is obtained if the compared approaches are ordered by the percentage of traces for which the offer by the bank has been accepted by the customer: around 30\% for the traces following the optimal policy, around 15\% for all traces, and less than 10\% for the traces not following the optimal policy. No major differences can be observed between the two splitting criteria, except for a small decrease of the average KPI value and of the percentage of accepted offers Similarly to the \emph{Loan request handling}\xspace scenario, also in the \emph{Traffic fine management}\xspace scenario (rows \emph{Fines}{} in Table~\ref{tab:log_analysis}) the results of the test log evaluation\xspace confirm the findings of the simulation evaluation\xspace. Indeed, for both splitting criteria, the traces following the optimal policy (\textsc{Optimal P.}\xspace) obtain an average KPI value higher than the average KPI value of all the traces (\textsc{All}\xspace), which in turn is higher than the average KPI value of the traces that do not follow the optimal policy (\textsc{Non-Optimal P.}\xspace). The traces following the optimal policy can produce an average credit value of more than 1 credit higher than the average credit value of all the traces in the event log, as well as of more than 2 credits higher than the average credit value of the traces that do not follow the optimal policy. The trend is also similar for the percentage of traces for which the fine is fully paid. Around 90\% of the traces that follow the optimal policy are able to get fully paid fines for both the splitting criteria. While, as in the \emph{Loan request handling}\xspace, the percentage of traces with a fully paid fine decreases from the 40\% test event log to the 20\% event log for the \textsc{All}\xspace and \textsc{Non-Optimal P.}\xspace policies, for \textsc{Optimal P.}\xspace the percentage of traces for which the full payment is received is higher for the 20\% than for the 40\% test event log. The above results of the two scenarios clearly show that, when no activity has been executed before the target agent starts following the recommendations, the sequence of next activities suggested by the optimal policy generates an average value for the KPI of interest higher than a random policy and than a policy following the most frequently taken actions and, on average, higher than the average KPI value obtained by the actual executions in the test event log (\ref{RQ1}). No clear trends can be observed for different splitting criteria. \begin{figure}[t] \centering \subfloat[average delta KPI value]{\label{sublabel:avg_loan} \includegraphics[width=0.5\textwidth]{figures/loan_avg_delta_reward_scaled3_big.png}} \subfloat[number of traces for each prefix]{\label{sublabel:tot_loan} \includegraphics[width=0.5\textwidth]{figures/loan_count_prefix_big.png}} \caption{Prefix analysis for the \emph{Loan request handling}\xspace scenario.} \vspace{-0.5cm} \label{fig:loan_prefix} \end{figure} \vspace{0.15cm} \noindent \emph{Research Question \ref{RQ2}.} As described in Section~\ref{ssec:setting}, we also evaluate the optimal policies at different prefix lengths, that is, by assuming that a part of the execution has already been carried out, before the target agent starts adopting the optimal policy. \figurename~\ref{fig:loan_prefix} and \figurename~\ref{fig:fine_prefix} show the average delta KPI value for each prefix length, as well as the prefix occurrence per prefix length. The delta KPI value for each trace and prefix length is computed as the difference between the KPI value obtained by following the optimal policy from that prefix on and the KPI value of the complete trace related to that prefix. The plot corresponding to the \emph{Loan request handling}\xspace scenario (\figurename~\ref{sublabel:avg_loan}) shows that for both splitting criteria and for prefix lengths up to $18$ there is an average positive delta KPI value, while for longer prefixes a negative or almost null average KPI values are observed. These results can be explained by the low number of traces with length higher than $18$ in the test event logs, as it is shown in \figurename~\ref{sublabel:tot_loan}. \begin{figure}[t] \centering \subfloat[average delta KPI value]{\label{sublabel:avg_fines} \includegraphics[width=0.5\textwidth]{figures/fine_avg_delta_reward_big.png}} \subfloat[number of traces for each prefix]{\label{sublabel:tot_fines} \includegraphics[width=0.5\textwidth]{figures/fine_count_prefix_big.png}} \caption{Prefix analysis for the \emph{Traffic fine management}\xspace scenario.} \vspace{-0.5cm} \label{fig:fine_prefix} \end{figure} In the \emph{Traffic fine management}\xspace scenario, the plot in \figurename~\ref{sublabel:avg_fines} shows a relatively high delta average KPI value for short prefixes (prefixes of length 1 and 2), while the average delta KPI value starts decreasing for traces of prefix length 3. Also in this case, as for the other scenario, the decrease in terms of delta KPI value is mainly due to an overall decrease of the number of traces after prefix $3$ (see \figurename~\ref{sublabel:tot_fines}). Differently from the \emph{Loan request handling}\xspace scenario, as already observed during the discussion of \ref{RQ1}, the average delta KPI value obtained with the 80\%-20\%{} splitting criterion is higher than the one obtained with the 60\%-40\%{} splitting criterion, except that for prefix length $3$. In conclusion, these results confirm that even when considering ongoing executions, the recommended sequence of next activities suggested by the proposed optimal policy generates higher average KPI values than the ones obtained by actual executions in the test event log (\ref{RQ2}). Beyond the performance perspective, we briefly comment here on the plausibility of the optimal policies obtained. The major contributions of the policies for the two cases are clear and reasonable. In the \emph{Loan request handling}\xspace scenario the policy advises to accept more loan applications, so as to increase the number of possible accepted loans. Moreover, it advises to increase the interaction between the bank and the customer, with the creation of multiple offers and the subsequent call to the customer. In the \emph{Traffic fine management}\xspace scenario the policy advises to send the fine early to the offender, so as to raise the probability that he/she pays the fine on time. \section{Introduction} \label{sec:intro} In the last few years, a number of works have proposed approaches, solutions and benchmarks in the field of Predictive Process Monitoring~\cite{DBLP:conf/caise/MaggiFDG14,DBLP:conf/bpm/Francescomarino18}. Predictive Process Monitoring leverages the analysis of historical execution traces in order to predict the unrolling of a process instance that has been only partially executed. However, most of these efforts have not used the predictions to explicitly support user with recommendations, i.e., with a concrete usage of these predictions. In fact, there is a clear need of \emph{actionable} process management systems~\cite{DBLP:journals/corr/abs-2201-12855} able to support the users with recommendations about the best actions to take The overall goal of this paper is therefore moving a step forward, towards the implementation of a \emph{learning to act} system, in line with the ideas of Prescriptive Process Monitoring~\cite{fahrenkrog2019fire,metzger2020triggering}. Given an ongoing business process execution, Prescriptive Process Monitoring aims at recommending activities or interventions with the goal of optimizing a target measure of interest or Key Performance Indicator (KPI). State-of-the-art works have introduced methods for raising alarms or triggering interventions, to prevent or mitigate undesired outcomes, as well as for recommending the best resource allocation. Only few of them have targeted the generation of recommendations of the next activity(ies) to optimize a certain KPI of interest~\cite{weinzierl2020predictive,groger2014prescriptive,de2020design}, such as, the cycle time of the process execution. Moreover, none of them explicitly considers the process execution in the context of a complex environment that depends upon exogenous factors, including how the other process actors behave. In this setting, identifying the best strategy to follow for a target actor, is not straightforward. In this paper, we take the perspective of one target actor and we propose a solution based on Reinforcement Learning (RL): to recommend to the actor what to do next in order to optimize a given KPI of interest for this actor. To this aim, we first learn, from past executions, the response of the environment (actions taken by other actors) to the target actor's actions, and we then leverage RL to recommend the best activities/actions to carry on to optimize the KPI. In the remainder of the paper after introducing some background concepts (Section~\ref{sec:background}), we present two concrete Prescriptive Process Monitoring problems that we have targeted (Section~\ref{sec:running}). Section~\ref{sec:problem} shows how a Prescriptive Process Monitoring problem can be mapped into RL, while Section~\ref{sec:evaluation} applies the proposed RL approach to the considered problems and evaluates its effectiveness. Finally, Section~\ref{sec:related} and Section~\ref{sec:conclusion} present related works and conclusions, respectively. \subsubsection{Acknowledgements} Please place your acknowledgments at the end of the paper, preceded by an unnumbered run-in heading (i.e. 3rd-level heading). \bibliographystyle{splncs04} \section{Two Motivating Scenarios} \label{sec:running} We introduce here the considered problem by showcasing two real processes that involve one target actor, whose reward is to be maximised, and some more actors, contributing to determine the outcome of the process (environment) \paragraph{Loan request handling} (\emph{Loans}). In a financial institute handling loan requests, customers send loan request applications and the bank decide either to decline an application, or to request further details to the customer, or to make an offer and start a negotiation with the customer. During the negotiation phase, the bank can contact the customer and possibly change its offer to encourage the customer to finally accept the bank's offer. The bank aims at maximizing its payoff by trying to sign agreements with the customer, while reducing the costs of the negotiation phase, i.e., stopping negotiations that will not end up with an agreement. The bank is therefore interested to implement the best strategy to follow (actions) in order to maximize its interest. \paragraph{Traffic fine management} (\emph{Fines}). In a police department in charge to collect road traffic fines, as in the scenario presented in~\cite{DBLP:journals/computing/MannhardtLRA16}, fines can be paid (partly or fully) either immediately after the fine has been issued, or after the fine notification is sent by the police to the offender’s place of residence, or when the notification is received by the offender. If the entire amount is paid, the fine management process is closed. After being notified by post, the offender can appeal against the fine through a judge and/or the prefecture. If the appeal is successful, the case ends. In such a setting, the police department aims at collecting the payment of the invoice by the offender as soon as possible, so as to avoid money wastes due to delays in payments or the involvement of the prefecture/judge. The department indeed receives credits for fast payments, no credits for payments never received and discredits for incorrect fines. The department is therefore interested to receive best action recommendations to maximize the received credits. \section{Mapping PPM to RL} \label{sec:problem} We would like to support a target actor of interest in a process, such as, the financial institute or the police department (see Section~\ref{sec:running}), by providing them with recommendations for the best activities to execute in order to maximize their profit and their credits, respectively. To this aim, we leverage RL, by transforming the PPM problem of recommending the next activities to optimize a given KPI, into an RL problem, where the \emph{agent} is the actor we are supporting in the decision making (e.g., the bank or the police department), and the \emph{environment} is represented by the external factors---especially the activities carried out by the other actors involved in the process execution (e.g., the customer or the offender). We define our MDP so that: \begin{itemize}[label=$\bullet$,topsep=0.3pt] \item an \emph{action}, to be recommended, is an activity of the actor of interest (\emph{agent}) (e.g., the bank activity \act{Create offer}); \item a \emph{state} is defined by taking into account the following variables: \begin{itemize}[label=$-$] \item the last activity executed by the actor of interest (e.g., the creation of a new offer by the bank) or by the other actors defining the stochastic response of the environment (e.g., the bank offer acceptance by the customer); \item some relevant information about the history of the execution (e.g., the number of phone calls between the bank and the customer); \item other aspects defining the stochastic response of the environment (e.g., the amount of the requested loan) \end{itemize} A \emph{state}{} is hence represented by a tuple $\langle \textsc{LA}, \textsc{HF}, \textsc{EF} \rangle$, where \textsc{LA}{} is the last activity executed by the actor of interest or by one of the other actors involved in the process, \textsc{HF}{} is a vector of features describing some relevant information of the process execution history and \textsc{EF}{} is a vector of features further describing the environment response to the actions of the actor of interest. \item the \emph{reward function} is a numerical value that transforms the KPI of interest, computed on the complete execution, in a utility function at the level of single action. \end{itemize} Actions, states and reward function can be defined for each specific problem by leveraging the information contained in the event log and some domain knowledge. The activities we are interested to recommend and those describing the stochastic response of the environment can be extracted from the event log. The relevant information about the history of the process execution can also be extracted from the event log, with some domain-specific pre-processing (e.g., counting the number of phone calls between the bank and the customer). The stochastic responses of the environment to the actor's actions can also be mined from the event log through trace attributes (e.g., the amount of the requested loan). Finally, information contained in event logs can be used to estimate the reward function for each state transition and action (e.g., in case the reward function is related to the process/event cycle time, the average duration of events of a certain type can be used to estimate the reward of a given state). \section{Related Work} \label{sec:related} The state-of-the-art works related to this paper pertain to two fields: Prescriptive Process Monitoring and Reinforcement Learning. The section is hence structured by first presenting Prescriptive Process Monitoring related works and then Reinforcement Learning state-of-the-art works, applied to process mining problems. Several Prescriptive Process Monitoring techniques have been recently proposed in the literature. Focusing on the type of interventions that the approaches recommend~\cite{DBLP:journals/corr/abs-2112-01769}, we can roughly classify existing work in Prescriptive Process Monitoring in three main groups: (i) those that recommend different types of interventions to prevent or mitigate the occurrence of an undesired outcome~\cite{Teinemaaetal2018,fahrenkrog2019fire,metzger2019proactive,metzger2020triggering,DBLP:journals/corr/abs-2109-02894}; (ii) those that take a resource perspective and recommend a resource allocation~\cite{10.1007/978-3-319-39696-5_35,DBLP:conf/icpm/ParkS19}; (iii) those that provide recommendations related to the next activity to optimize a given KPI~\cite{weinzierl2020predictive,groger2014prescriptive,de2020design}. The approach presented in this paper falls under this third family of prescriptive process monitoring approaches. Only a small amount of research has been done in this third group of works. Weinzierl et al. in~\cite{weinzierl2020predictive} discuss how the most likely behavior does not guarantee to achieve the desired business goal. As a solution to this problem, they propose and evaluate a prescriptive business process monitoring technique that recommends next best actions to optimize a specific KPI, i.e., the time. Gröger et al. in~\cite{groger2014prescriptive} present a data-mining driven concept of recommendation-based business process optimization supporting adaptive and continuously optimized business processes. De Leoni et al. in~\cite{de2020design} discuss Process-aware Recommender (PAR) systems, in which a prescriptive-analytics component, in case of executions with a negative outcome prediction, recommends the next activities that minimize the risk to complete the process execution with a negative outcome. Differently from these state-of-the-art works, however, in this work we take the perspective of one of the actors of the process and we aim at optimizing a domain-specific KPI of interest for this actor by leveraging an RL approach. In the literature, only few RL approaches have been proposed for facing problems in the process mining field. Silvander proposes using Q-Learning with function approximation via a deep neural network (DQN) for the optimization of business processes~\cite{silvander2019business}. He suggests defining a so called decay rate to reduce the amount of exploration over time. Huang et al. employ RL for the dynamic optimization of resource allocation in business process executions~\cite{huang2011reinforcement}. Metzger et al. propose an alarm-based approach to prevent and mitigate an undesired outcome~\cite{metzger2020triggering}. They use online RL to learn when to trigger proactive process adaptations based on the reliability of predictions. Although all these works use RL in the process mining field, none of them use it for recommending the next actions to perform in order to optimize a certain KPI of interest, as in this work. Finally, some works have applied RL and Inverse Reinforcement Learning (IRL) approaches to recommend the next actions on temporal data~\cite{DBLP:conf/recsys/Massimo018} or on data constrained by temporal constraints~\cite{DBLP:conf/aips/GiacomoIFP19} \section{First Section} \subsection{A Subsection Sample} Please note that the first paragraph of a section or subsection is not indented. The first paragraph that follows a table, figure, equation etc. does not need an indent, either. Subsequent paragraphs, however, are indented. \subsubsection{Sample Heading (Third Level)} Only two levels of headings should be numbered. Lower level headings remain unnumbered; they are formatted as run-in headings. \paragraph{Sample Heading (Fourth Level)} The contribution should contain no more than four levels of headings. Table~\ref{tab1} gives a summary of all heading levels. \begin{table} \caption{Table captions should be placed above the tables.}\label{tab1} \begin{tabular}{|l|l|l|} \hline Heading level & Example & Font size and style\\ \hline Title (centered) & {\Large\bfseries Lecture Notes} & 14 point, bold\\ 1st-level heading & {\large\bfseries 1 Introduction} & 12 point, bold\\ 2nd-level heading & {\bfseries 2.1 Printing Area} & 10 point, bold\\ 3rd-level heading & {\bfseries Run-in Heading in Bold.} Text follows & 10 point, bold\\ 4th-level heading & {\itshape Lowest Level Heading.} Text follows & 10 point, italic\\ \hline \end{tabular} \end{table} \noindent Displayed equations are centered and set on a separate line. \begin{equation} x + y = z \end{equation} Please try to avoid rasterized images for line-art diagrams and schemas. Whenever possible, use vector graphics instead (see Fig.~\ref{fig1}). \begin{figure} \includegraphics[width=\textwidth]{fig1.eps} \caption{A figure caption is always placed below the illustration. Please note that short captions are centered, while long ones are justified by the macro package automatically.} \label{fig1} \end{figure} \begin{theorem} This is a sample theorem. The run-in heading is set in bold, while the following text appears in italics. Definitions, lemmas, propositions, and corollaries are styled the same way. \end{theorem} \begin{proof} Proofs, examples, and remarks have the initial word in italics, while the following text appears in normal font. \end{proof} For citations of references, we prefer the use of square brackets and consecutive numbers. Citations using labels or the author/year convention are also acceptable. The following bibliography provides a sample reference list with entries for journal articles~\cite{ref_article1}, an LNCS chapter~\cite{ref_lncs1}, a book~\cite{ref_book1}, proceedings without editors~\cite{ref_proc1}, and a homepage~\cite{ref_url1}. Multiple citations are grouped \cite{ref_article1,ref_lncs1,ref_book1}, \cite{ref_article1,ref_book1,ref_proc1,ref_url1}. \subsubsection{Acknowledgements} Please place your acknowledgments at the end of the paper, preceded by an unnumbered run-in heading (i.e. 3rd-level heading). \section{A RL Solution} Figure~\ref{fig:architecture} shows the architecture of the RL-based solution designed to solve the problem of recommending the next best activities to optimize a certain KPI. \begin{figure}[t] \centering \includegraphics[width=\textwidth]{figures/architecture.png} \caption{Architecture of the RL solution} \vspace{-0.5cm} \label{fig:architecture} \end{figure} The input is an event log containing historical traces related to the execution of a process, and some domain knowledge, specifying the KPI of interest and the information that allows for the identification of actions, states and of the reward function. There are three main processing phases: \begin{itemize}[label=$\bullet$,topsep=0.3pt] \item \emph{preprocessing phase:} the event log is preprocessed in order to learn a representation of the environment (i.e., the MDP). First, the event log is cleansed and the domain knowledge leveraged in order to annotate it. In detail, the event log is (i) filtered in order to remove low-frequency variants (with occurrence frequency lower than 10\%) and activities that are not relevant for the decision making problem; (ii) enriched with attributes obtained by aggregating and preprocessing information related to the execution; (iii) annotated by specifying the agent's activities to be considered as actions; attributes and environment activities to be used for the state definition; attributes to be used for the computation of the reward function. Once the event log has been enriched and annotated, it can be used for building the MDP that defines the RL problem. To this aim, we start from the scenario-specific definition of action and state and, by replaying the traces in the event log, we build a directed graph, where each node corresponds to a state and each edge is labelled with the activity allowing to move from one node state to the other. Moreover, for each edge, the probability of reaching the target node (computed based on the number of traces in the event log that reach the corresponding state) and the value of the reward function are computed. Each edge is hence mapped to the tuple $(s, a, s', \mathcal{P}(s'|s,a), \mathcal{R})$ where $s$ is the state corresponding to the source node of the edge, $a$ is the action used for labelling the edge, $s'$ is the state corresponding to the target node of the edge, $\mathcal{P}(s'|s,a)$ is computed as the percentage of the traces that reach the state $s'$ among the traces that reach state $s$ and execute $a$, and $\mathcal{R}$ is the value of the reward function. \item \emph{RL phase:} the RL algorithm is actually applied to compute the optimal policy $\pi^\ast$; in this paper we used policy iteration with Monte Carlo methods. \item \emph{runtime phase:} given an empty or ongoing execution trace, the policy is queried by the recommender system to return the best activities to be executed next. \end{itemize}
{'timestamp': '2022-06-16T02:19:56', 'yymm': '2203', 'arxiv_id': '2203.15398', 'language': 'en', 'url': 'https://arxiv.org/abs/2203.15398'}
arxiv
\section{Introduction} Differential privacy (DP) \cite{dwork2006calibrating} is a mathematical standard for quantifying the privacy performance of a data publishing or data analysis mechanism \cite{survey_2017}. To conceal the presence of any individual in the dataset, DP mechanisms perturb the query response or the outcome of an analysis according to a random distribution. The main DP parameter is called $\varepsilon$. If $\varepsilon$ is small, then any mechanism output is almost as likely to occur whether or not any particular individual's data was used in the database. Despite many scientific and operational challenges \cite{Censusissues}, the United States Census Bureau has implemented differential privacy for the 2020 Census release \cite{USCBadopts}. One challenge, which is also documented in many other works including \cite{epsilonvote, economic}, is the difficulty in choosing an appropriate value for $\varepsilon$. Two possible reasons for such a challenge are as follows. First, differential privacy is not well-equipped with theories that maximize utility subject to a privacy constraint or minimize $\varepsilon$ subject to a utility constraint \cite{Censusissues}. In \cite{staircase, ghosh2012universally, natashalaplace}, the staircase, geometric and Laplace mechanisms were respectively identified as utility-maximizing mechanisms under various notions of utility. However, only the global sensitivity of the query across all datasets is taken into account. Such \emph{data-independent} mechanisms can adversely affect utility, especially when an individual's response does not change the query outcome compared to any of its neighboring datasets \cite{individual}. \emph{Data-dependent} mechanisms aim to enhance utility. However, since utility is not provably optimized, the challenge remains to determine which data-dependent algorithm is best for a given application \cite{data_depenedent}. Second, a ``one-size-fits-all" \cite{personalized} approach to setting a global privacy level can be damaging to both utility and privacy. Current implementations of differential privacy lack sufficient flexibility for accommodating \emph{data-dependent} privacy setting. For example, there may be minority groups whose data must be better protected. There may also be statutory mandates, demanding publication of certain datasets with more accuracy. The authors of \cite{epsilonvote, personalized} present several social reasons in favor of incorporating users' preferences when choosing $\varepsilon$. Towards addressing these challenges, the authors in \cite{RafnoDP2colorPaper} proposed a methodology for data-dependent utility-optimal mechanism design for binary-valued queries. This was done via representing datasets as vertices and dataset neighborhoods as edges on a graph. \emph{Boundary} datasets are those where an individual's data changes the query outcome compared to its neighbors. For the case that the mechanism was defined only \emph{partially} at the boundary datasets, \cite{RafnoDP2colorPaper} showed it is possible to \emph{extend} the mechanism over the entire graph in an optimal manner. To solve the problem efficiently, \cite{RafnoDP2colorPaper} focused on the \emph{homogeneous} case where the partial mechanism had the same probability distribution at the boundary and also $\varepsilon$ was the same across the graph. However, an efficient solution to the general problem remained open. This paper generalizes the work \cite{RafnoDP2colorPaper} in two main directions.\footnote{We remark that \cite{RafnoDP2colorPaper} considered approximate $(\varepsilon, \delta)$-DP. Here we set $\delta = 0$ and consider pure-DP. This will make the analysis manageable.} First, we study \emph{heterogeneous mechanisms} where the partial mechanism can have different probability distributions at the boundary. Second, we study a \emph{general heterogeneous privacy setting} on neighboring datasets, which recovers personalized DP \cite{personalized} as a special case. Efficiently solving both generalizations required a radically different way of thinking about the problem compared to \cite{RafnoDP2colorPaper}. Instead of using graph morphism to simple path graphs, we use the partial mechanism as \emph{seed to optimally grow} via the concept of \emph{strongest induced DP condition}. We show this can be done in polynomial time. After recalling standard definitions for graphs and differential privacy in Section \ref{sec:standard}, we introduce heterogeneous DP in Section \ref{HDP}. Section \ref{sec:main} presents our main results in a semi-informal manner, focusing on insights and intuitions. Section \ref{sec:technical} contains the technical statements and the Algorithm for finding the optimal mechanism. \section{Differential Privacy and Utility via Graphs}\label{sec:standard} Let $\mathcal{G}(V,E)$ be a simple, connected, and undirected graph with vertex set $V$ and edge set $E$. A sequence of vertices $u = u_0, u_1, \cdots, u_n = v$ is said to form a path from $u$ to $v$, denoted by $(u,v)$-path, if $(u_0, u_1), \cdots, (u_{n-1},u_n) \in E$. \begin{definition}[$(u,v)$-path set] For every two vertices $u,v \in V$, we define $\mathcal{P}(u,v) := \{\text{all the } (u,v)\text{-paths in } \mathcal{G}\}$. For subsets $A_1,A_2 \subseteq V$, we define $\mathcal{P}(A_1,A_2):= \cup _{u \in A_1, v \in A_2} \mathcal{P}(u,v)$. Finally, $\mathcal{P}$ is the set of all paths in $\mathcal{G}$. \end{definition} Let $\rho$ be a path and $w$ be a neighbor of $\rho$'s tail not on $\rho$. The path obtained from adding $w$ to $\rho$ is denoted by $\rho w$. \begin{definition}[Neighborhood] The neighborhood of a subset $S \subseteq V$ of the vertices, denoted by $N(S)$ is the set of all the vertices in $V\setminus S$ which are connected to at least one element of $S$ by an edge. \end{definition} In this work, the vertices represent datasets and the edges represent neighborhood relationships between pairs of datasets. Neighboring datasets $u$ and $v$ are also denoted by $u\sim v$. The true query function $T: V\to Q$, associates to each dataset a query value from a finite set $Q$. \begin{definition}[Boundary set]\label{def:boundary} The \emph{boundary} set of $\mathcal G$ with respect to $T$ is denoted by $\partial _T (\mathcal{G})$ and is the set of vertices in $\mathcal G$ whose neighborhood contains at least one vertex with a different true query value. Formally, \begin{align*} \partial _T (\mathcal{G}) = \{u \in V: \exists v \in N(u), T(v) \neq T(u)\}. \end{align*} \end{definition} For privately responding to $T$, a privacy-preserving mechanism $\mathcal{M}$ randomizes the response. \begin{definition}[Differential privacy \cite{dwork2006calibrating}] \label{def:dp} Let $\varepsilon \geq 0$. Then, a mechanism $\mathcal{M}:V \to Q$ on $\mathcal{G}$ is $\varepsilon$-differentially private (in short is $\varepsilon$-DP) if, for every $u \sim v$ and $\mathcal{S} \subseteq Q$, \[ \Pr [\mathcal{M}(u) \in \mathcal{S}] \leq e^\varepsilon \Pr [\mathcal{M}(v) \in \mathcal{S}].\] \end{definition} In this paper we consider the case where $Q = \{1, 2\}$ of binary-valued queries. It then suffices to use the following notion of \emph{binary-valued} differential privacy. \begin{definition}[Binary-valued differential privacy]\label{def:binaryDP} Let $\varepsilon \geq 0$ and $p : V \to [0,1]$. We say $p$ is binary-valued $\varepsilon$-DP if for every pair $u \sim v$, we have: \begin{align} \label{eq: p1} p(u) &\leq e^\varepsilon p(v), \\ 1-p(v) &\leq e^\varepsilon (1-p(u)).\label{eq: p2} \end{align} \end{definition} Due to the symmetry of dataset neighborhood, $v \sim u$ will yield the other two inequalities involving $p(v)$ and $p(u)$. \begin{lemma} Let $\mathcal{M}: V \to \{1,2\}$ be a mechanism. Then, $\mathcal{M}$ is $\varepsilon$-DP if $p:=\Pr[\mathcal{M}(v)=1]$ is binary-valued $\varepsilon$-DP. \end{lemma} The proof is straightforward and is omitted here. The following definition captures the optimal utility of a binary mechanism over the space of datasets. Roughly speaking, a mechanism is said to be optimal if for every dataset $v \in V$, the probability of correctly outputting the true query value $T(v)$ is the highest it can be. Recall that $p := \Pr[\mathcal{M} (v) =1]$ and $1-p := \Pr[\mathcal{M} (v) = 2]$. \begin{definition}[Optimal binary mechanism]\label{def:optimal} A binary-valued $\varepsilon$-DP mechanism $p^*$ is said to be optimal on $\mathcal{G}$ if, for every other binary-valued $\varepsilon$-DP mechanism $p$ on $\mathcal{G}$ and every vertex $v \in V$, we have: \begin{align} \begin{cases} p^*(v) \geq p(v), \quad &\text{if } T(v) = 1,\\ 1-p^*(v) \geq 1-p(v), \quad &\text{if } T(v) = 2. \end{cases} \end{align} We denote this ordering with respect to $T$ by $p \leq_T p^*$. \end{definition} \section{Heterogeneous Differential Privacy}\label{HDP} The standard definition of differential privacy in Definition~\ref{def:dp} is \emph{homogeneous} in the sense that the privacy conditions between any two neighboring datasets are given by the same $\varepsilon$. In this section, we extend the homogeneous $\varepsilon$-DP to the heterogeneous case. For each edge $(u,v) \in E$, there is an $\varepsilon(u,v)$, which specifies how neighboring datasets $u$ and $v$ should be protected with respect to each other. Throughout the paper, we assume $\varepsilon(\cdot)$ is symmetric, i.e, $\varepsilon(u,v) = \varepsilon(v, u)$, for every $(u,v) \in E$. \begin{definition}[Heterogeneous differential privacy] \label{def:hetDP} A mechanism $\mathcal{M}:V \to Q$ on $\mathcal{G}$ is heterogeneous $\varepsilon(\cdot)$-differentially private if, for every $u \sim v$ and $\mathcal{S} \subseteq Q$, \[ \Pr [\mathcal{M}(u) \in \mathcal{S}] \leq e^{\varepsilon(u,v)} \Pr [\mathcal{M}(v) \in \mathcal{S}].\] \end{definition} If $\varepsilon(\cdot) = \varepsilon$ is a constant function, we recover the standard differential privacy in Definition \ref{def:dp}. A small $\varepsilon(u,v)$ means high privacy and vice versa. Whenever we write $\varepsilon(\cdot)$-DP as opposed to just $\varepsilon$-DP, it is to emphasize that we mean a heterogeneous DP mechanism on $\mathcal{G}$. Definition \ref{def:hetDP} is more general than the personalized DP \cite{personalized} as follows. In \cite{personalized}, the variability of $\varepsilon$ is tied to the identity of an individual $i$. To clarify, for any $v = (v^1, \cdots, v^i, \cdots, v^n) \in V$, where $n$ is the dimension of the dataset, let $V^{-i}(v) \subset V$ denote all vertices in $V$ whose $i$-th element differs from $v$. That is, $v^{-i}= (v^1, \cdots, v'^i, \cdots, v^n)$. In \cite{personalized}, $\varepsilon(v,v^{-i}) = \varepsilon_i$ for all $v^{-i} \in V^{-i}$. In this paper, there is no such constraint and $\varepsilon(v, v^{-i})$ has full degrees of freedom to depend on both $v$ and $v^{-i}$. In \cite{dmetric}, the authors define $\varepsilon(u,v)$ \emph{for all} $u,v \in V$ and assume $d(\cdot)$ is a metric function, which satisfies the triangle inequality $\varepsilon(u,v)\leq \varepsilon(u,w) + \varepsilon(w,v)$ for all $u,v, w \in V$. Here, we define $\varepsilon(u,v)$ for neighboring vertices $u \sim v$ only. See the examples in Fig. \ref{fig: ex graphs} that clarify these distinctions. \begin{figure*}[!t] \begin{subfigure}[t]{0.30\textwidth} \centering \input{tikz/cubehetero} \caption{Heterogeneous DP} \label{fig: ex graphs a} \end{subfigure} \begin{subfigure}[t]{0.30\textwidth} \centering \input{tikz/cubeindiv} \caption{Personalized DP} \label{fig: ex graphs b} \end{subfigure} \begin{subfigure}[t]{0.30\textwidth} \centering \input{tikz/dmetric} \caption{$d$-metric privacy} \label{fig: ex graphs b} \end{subfigure} \caption{Examples of heterogeneous DP in this paper, personalized DP \cite{personalized}, and $d$-metric DP \cite{dmetric}. Each dataset $v = (v^1, v^2, v^3)$ contains three votes, $v^i \in \{1,2\}$. The query is the majority vote which is color coded as \texttt{blue} or \texttt{red}. A higher privacy $\varepsilon_2 < \varepsilon_1$ is schematically shown with thicker lines . Imagine the first person's vote needs to better protected, \emph{but only if} it is the deciding vote. In heterogeneous DP, it is possible to assign higher privacy only on edges $(121)-(221)$ and $(112)-(212)$. In personalized DP, all datasets in which the first person's vote is different must be assigned the same privacy parameter. In $d$-metric privacy, privacy conditions between all datasets must be pre-specified subject to the triangular inequality.} \label{fig: ex graphs} \end{figure*} \section{Main Results}\label{sec:main} Let $\mathcal{G}$ be a graph with privacy function $\varepsilon(\cdot)$. Let $T$ be a binary-valued query function on $V$ and $p: S \to [0,1]$ be a \emph{partial} function such that $S \subseteq V$ contains the boundary set $\partial _T (\mathcal{G})$. An \emph{extension} of $p$ is a function $\tilde{p}: V \to [0,1]$ such that for all $v \in S$, we have $ \tilde{p}(v) = p(v)$. The main result of this paper is as follows. \begin{theorem}\label{theorem:main1} There exists a polynomial time algorithm which takes a graph $\mathcal{G}$, a privacy function $\varepsilon(\cdot)$, a binary-valued query $T$, and a partial function $p$ as input and outputs as follows. If $p$ cannot be extended to an $\varepsilon(\cdot)$-DP mechanism, it outputs ``no $\varepsilon$-DP extension of $p$ exists". Otherwise, it outputs an extension $\tilde{p}$ of $p$ which is $\varepsilon(\cdot)$-DP and is also the unique optimal with respect to the $\leq_T$ ordering. \end{theorem} Before we outline the main steps of the proof of Theorem~\ref{theorem:main1}, we explain some helpful facts. \subsection{Initial DP Conditions:} The notion of the $\varepsilon(\cdot)$-DP on $\mathcal{G}$ is a \emph{local} property in the sense that for a mechanism to be $\varepsilon(\cdot)$-DP, certain local conditions must be satisfied. For binary-valued heterogeneous mechanisms, this is captured in Definition \ref{def:binhetDP}. \begin{definition}[Binary-valued heterogeneous differential privacy]\label{def:binhetDP} The function $p:V\to [0,1]$ is called binary-valued heterogeneous $\varepsilon(\cdot)$-differentially private if, for every $u\sim v$, the following conditions are satisfied: \begin{align} \label{eq: r1} p(u) &\leq e^{\varepsilon(u,v)} p(v), \\ 1-p(u) &\leq e^{\varepsilon(u,v)}(1- p(v)).\label{eq: r2} \end{align} Furthermore, by the symmetry, the same set of inequalities hold if we interchange $u$ and $v$: \begin{align} \label{eq: r3} p(v) &\leq e^{\varepsilon(u,v)} p(u),\\ 1-p(v) &\leq e^{\varepsilon(u,v)}(1- p(u)).\label{eq: r4} \end{align} We refer to \eqref{eq: r1}-\eqref{eq: r4} as the \emph{initial DP conditions}. \end{definition} Note that \eqref{eq: r1}-\eqref{eq: r4} can be rearranged to obtain two upper bounds on $p(u)$ and two lower bounds on $p(u)$. In particular, \eqref{eq: r4} can be rewritten as \begin{align} \label{eq: 0DPW3} p(u) &\leq \frac{ p(v) -1 + e^{\varepsilon(u,v)} } {e^{\varepsilon(u,v)}}. \end{align} That is, \eqref{eq: r1} and \eqref{eq: 0DPW3} impose two upper bounds on the mechanism $p(u)$. Because of this simple fact and also the fact that neighboring relationship is a symmetric relationship, we may only consider the upper bounds. That is, if all the upper bound inequalities hold for every adjacent pair of vertices, the lower bounds automatically hold. \subsection{Strongest Induced DP Condition:} Despite the fact that an $\varepsilon(\cdot)$-DP mechanism has a very localized definition as described above, it must also satisfy \emph{less local} conditions as follows. If two vertices $u,v$ are not neighbors, but both satisfy local $\varepsilon(\cdot)$-DP conditions with a third mutual neighboring vertex $u_0$, then a weaker set of inequalities must hold for the value of the mechanism at $u$ and $v$. As we take different $(u,v)$-paths, still certain inequalities, depending on that path, on the value of the mechanism at the two end vertices must be satisfied. The upper bounds a vertex imposes on another vertex via some path are called \emph{induced DP conditions}. However, as the path is incremented, the induced conditions become weaker. In fact, for every pair of nodes $u,v \in V$, any $\varepsilon(\cdot)$-DP mechanism on $\mathcal{G}$, and any path $\rho \in \mathcal{P}(u,v)$, the vertex $u$ imposes an upper bound on $p(v)$, which depends on both $p(u)$ and $\rho$. We denote this upper bound by $U_{\rho , p(u)}(v)$. Thus, from now on, every time we talk about the best bound $u$ imposes on $p(v)$, we mean the smallest upper bound on $p(v)$ among all $\rho \in \mathcal{P}(u,v)$, i.e., $\min_{\rho\in \mathcal{P}(u,v)} U_{\rho , p(u)}(v)$. We call this smallest bound \emph{the strongest induced condition of $u$ on $p(v)$.} The following lemma summarizes these facts. \begin{lemma} \label{lem: increasing} Let $\rho$ be a $(u,v)$-path and $v'$ be a middle vertex of this path. Let $\rho'$ and $\rho''$ be $(u,v')$ and $(v',v)$ subpaths on $\rho$. Then, for the upper bound $U$ function we obtain the expression $U_{\rho, p(u)}(v) = U_{\rho'', U_{\rho', p(u)}(v')}(v)$. Also, for every $\varepsilon(\cdot)$-DP mechanism $p$, the upper bounds $u$ imposes on $p(v')$ are smaller than the ones it imposes on $p(v)$. \end{lemma} The above lemma follows from Theorem \ref{theo:path} that will appear later in the paper. \subsection{Finding the Strongest Induced DP Condition} For a single path graph, finding the strongest induced DP condition can be solved efficiently. The closed-form expression of the optimal induced DP conditions for a path graph is derived in Theorem \ref{theo:path}. However, finding the strongest induced condition is challenging in a general graph, since the number of the paths in the graph can be exponentially large on the number of vertices. However, in Algorithm \ref{algo: acomplete}, we show that this task can be accomplished in polynomial time. In the next section, we describe this algorithm, prove its correctness, and analyze its time complexity. We now explain the proof of Theorem \ref{theorem:main1} and the construction of Algorithm \ref{algo: acomplete}. \begin{itemize} \item{\textbf{Checking the extendibility:}} The idea is very simple. We find a necessary condition that any extendable function must satisfy to be $\varepsilon(\cdot)$-DP and we check it in polynomial time. If it is not satisfied, the algorithm declares that no $\varepsilon(\cdot)$-DP extension exists. Actually, the necessary conditions are the induced DP conditions over the pairs $u,v\in S$. In fact, all the induced conditions are necessary, but since we only have access to partial $p$, over the set $S$, we only consider those ones. Note that it is enough to only check the strongest induced conditions. The number of the ordered pairs in $S$ is $|S|\cdot(|S|-1)$ and hence, polynomial. Also checking if the strongest condition is satisfied over any pair in $S$ can be done using Algorithm \ref{algo: acomplete}. \item{\textbf{Finding an extension:}} Note that if the necessary condition is satisfied in the previous part, then Algorithm \ref{algo: acomplete} outputs some extension function of $p$. If we can prove that the output in this case is indeed an $\varepsilon(\cdot)$-DP mechanism, firstly it shows that the checking extendibility is indeed sufficient, and more importantly, the output satisfies $\varepsilon(\cdot)$-DP. The way the algorithm extends the function $p$ over the entire $V$ is as follows. For a vertex $v$ outside $S$, and based on the value of $T(v)$ it does the following. When $T(v)=1$, the algorithm searches over all the vertices $u\in S$ and finds the one whose strongest induced condition on the vertex $v$ is the smallest. In other words, among all the paths of the form $\rho \in \mathcal{P}(u,v)$ in which $u\in S$, it takes the one with minimum possible $U_{\rho , p(u)}(v)$. For any fixed $u$, this can be done by using Algorithm \ref{algo: subroutine}. Since $|S|$ has also polynomial size, the entire task can be done in polynomial time. When $T(v)=2$, the symmetry in the problem can be used to perform exactly the same steps except that we call Algorithm \ref{algo: acomplete} with the input $1-p$ instead of $p$. In Section \ref{TSaP.B}, we prove that the resulting extension of $p$ is $\varepsilon(\cdot)$-DP. \item{\textbf{Optimality with respect to $\leq_T$:}} This part is a direct consequence of the previous item. The reason is that for every vertex $v\in V \setminus S$, depending on whether $T(v)=1$ or $2$, we assigned the minimum upper bound (respectively, maximum lower bound) that is necessary for any $\varepsilon(\cdot)$-DP mechanism. In other words, if we increase the value of $p(v)$ (for the case $T(v)=1$) by any positive value, then one necessary condition fails and therefore the function cannot be $\varepsilon(\cdot)$-DP. \end{itemize} \section{Technical Statements and Proofs}\label{sec:technical} \subsection{The Path Graph} Let $\rho = v_0, \cdots, v_n$ be a path graph of length $n$ with the mechanism specified only at the head node $v_0$, i.e., $p(v_0) = \Pr[\mathcal{M}(v_0) = 1] =\alpha$ is given. The query value at $v_0$ can be either $T(v_0) = 1$ or $T(v_0) = 2$, but it is assumed $T(v_i) = 1$ across every other node on the path. This ensures that extending $p(v_0)$ in an optimal manner across the rest of the path is equivalent to maximizing $p(v_i)$, for $1 \leq i \leq n$. Since we are dealing with a path graph only and for simplicity of notation, we use the shorthand $\varepsilon_i \coloneqq\varepsilon(v_i,v_{i+1})$ here. Therefore, \eqref{eq: r1} and \eqref{eq: 0DPW3} are re-written for $i = 0, \cdots, n-1$ as \begin{align}\label{eq: d=0, ex+d} p(v_{i+1}) &\leq e^{\varepsilon_i} p(v_{i}),\\ p(v_{i+1}) &\leq \frac{ p(v_{i}) -1 + e^{\varepsilon_i}}{e^{\varepsilon_i}} \label{eq: d=0, e(1-a)+d}. \end{align} Among the two upper bounds \eqref{eq: d=0, ex+d} and \eqref{eq: d=0, e(1-a)+d} on $p(v_{i+1})$, the smallest one prevails at dictating the optimal mechanism: $$p(v_{i+1}) \leq \min \left\{ e^{\varepsilon_i} p(v_{i}), \frac{ p(v_{i}) -1 + e^{\varepsilon_i}}{e^{\varepsilon_i}}\right\}.$$ We first present a simple lemma that characterizes which upper bound among \eqref{eq: d=0, ex+d} and \eqref{eq: d=0, e(1-a)+d} is the tightest. \begin{lemma}\label{lem: iff} A necessary and sufficient condition for \[\min \left\{ e^{\varepsilon_i} p(v_{i}), \frac{ p(v_{i}) -1 + e^{\varepsilon_i}}{e^{\varepsilon_i}}\right\} = e^{\varepsilon_i} p(v_{i}) \] is that $p(v_i) \leq (e^{\varepsilon_i}+ 1)^{-1}$. \end{lemma} \begin{IEEEproof} \begin{align*} e^{\varepsilon_i} p(v_i) \leq \frac{ p(v_i) -1 + e^{\varepsilon_i}}{e^{\varepsilon_i}} &\iff\\ e^{2\varepsilon_i} p(v_i) \leq p(v_i) -1 + e^{\varepsilon_i} &\iff \\ e^{2\varepsilon_i} p(v_i) -p(v_i) \leq e^{\varepsilon_i} -1 &\iff \\ (e^{2\varepsilon_i}-1) p(v_i) \leq e^{\varepsilon_i} -1 &\iff p(v_i) \leq \frac{1}{e^{\varepsilon_i}+1} \end{align*} where the last step follows from $e^{\varepsilon_i} -1 \geq 0$. Note, that if $e^{\varepsilon_i}-1 = 0$ then, the inequality is trivial.\footnote{Note that Lemma \ref{lem: iff} is true for the general graph and general $\varepsilon(u,v)$.} \end{IEEEproof} The optimal binary-valued heterogeneous differentially private mechanism $p^*$ with initial condition $p^*(v_0) = \alpha$, follows from Lemma \ref{lem: iff} and induction on $i$, and is given by\footnote{We check if \eqref{eq: optimalp} gives a value greater than 1 and if so, set $ p^*(v_{i+1}) = 1$.} \begin{align}\label{eq: optimalp} p^*(v_{i+1}) = \min \left\{ e^{\varepsilon_i} p^*(v_{i}), \frac{ p^*(v_{i}) -1 + e^{\varepsilon_i}}{e^{\varepsilon_i}}\right\}. \end{align} \begin{theorem}\label{theo: pathupperboundary} The function $p^*$ given in \eqref{eq: optimalp} is the unique optimal $\varepsilon(\cdot)$-DP mechanism on the path graph $\rho$. \end{theorem} \begin{IEEEproof} Assume that $p^*$ is not optimal. Let $ p':V\to [0,1]$ be another binary-valued heterogeneous $\varepsilon(\cdot)$-differentially private function and let $k \in \mathbb{N}$ be the smallest number such that $p^*(v_k) < p'(v_k)$. As $k$ is the smallest number which satisfies the statement above, we obtain $ p'(v_{k-1}) \leq p^*(v_{k-1}) $. This means we have \begin{align}\label{eq:intermediate1} e^{\varepsilon_{k-1}} p'(v_{k-1}) &\leq e^{\varepsilon_{k-1}} p^*(v_{k-1}),\\ \frac{ p'(v_{k-1}) -1 + e^{\varepsilon_{k-1}}}{e^{\varepsilon_{k-1}}} &\leq \frac{ p^*(v_{k-1}) -1 + e^{\varepsilon_{k-1}}}{e^{\varepsilon_{k-1}}}.\label{eq:intermediate2} \end{align} Since $p'$ is an $\varepsilon(\cdot)$-differentially private function, it satisfies \eqref{eq: d=0, ex+d} and \eqref{eq: d=0, e(1-a)+d}. Combining this with \eqref{eq:intermediate1} and \eqref{eq:intermediate2} we obtain \begin{align} p'(v_{k}) &\leq \min \left\{e^{\varepsilon_{k-1}} p'(v_{k-1}) , \frac{ p'(v_{k-1}) -1 + e^{\varepsilon_i}}{e^{\varepsilon_{k-1}}} \right\}\\ &\leq \min \left\{e^{\varepsilon_i} p^*(v_{k-1}),\frac{ p^*(v_{k-1}) -1 + e^{\varepsilon_{k-1}}}{e^{\varepsilon_{k-1}}}\right\} \\&= p^*(v_{k}), \end{align} where the last equality is due to the construction of $p^*$ in Theorem \ref{theo: pathupperboundary}. This contradicts the first assumption. The proof of uniqueness is straightforward. \end{IEEEproof} We now show how to find the optimal $\varepsilon(\cdot)$-DP mechanism for the path graph. \begin{theorem}\label{theo:path} Let the path graph $\rho = v_0, \cdots, v_n$ and the mechanism at its head vertex $p(v_0) = \alpha$ be given. Assume that $T(v_i) = 1$ and $\varepsilon_i > 0$ is fixed, for $1\leq i\leq n$. Then, the optimal binary-valued heterogeneous differentially private mechanism $p^*$ is given by \begin{align*} p^*(v_i) \coloneqq \begin{cases} e^{\varepsilon_{i-1}+\cdots + \varepsilon_{0}} \alpha, & i \leq \tau, \\ e^{-\varepsilon_{i-1}-\dots - \varepsilon_{\tau+1} - \varepsilon_{\tau} +\varepsilon_{\tau-1}\dots + \varepsilon_{0}} \alpha & i > \tau. \\ \quad + 1 - e^{-\varepsilon_{i-1}-\dots - \varepsilon_{\tau}}, \end{cases} \end{align*} where \begin{align}\label{eq:tau0} \tau &= \argmin_{i \in [n]}\left\{\frac{1}{\alpha}\leq e^{\varepsilon_{i-1}+\varepsilon_{i-2} +\dots + \varepsilon_{0}}(e^{\varepsilon_{i}}+1)\right\}. \end{align} \end{theorem} \begin{IEEEproof} First assume that there exists some $k \in [n]$ such that for all $1 \leq i < k$, we have $\min \{ e^{\varepsilon_i} p(v_{i}), \frac{ p(v_{i}) -1 + e^{\varepsilon_i}}{e^{\varepsilon_i}}\} = e^{\varepsilon_i} p(v_{i})$. That is, \eqref{eq: d=0, ex+d} is the tightest upper bound on $p(v_{i+1})$. We will soon find the largest $k$ for which this can happen. Iterating over $i = k, k-1, \cdots, 1$, we will construct the mechanism $p^*$ through induction \begin{align}\label{eq:last1} \mathllap p^*(v_{k}) & = e^{\varepsilon_{k-1}} p^*(v_{k-1})\\ & = e^{\varepsilon_{k-1}}\big{(}e^{\varepsilon_{k-2}} p^*(v_{k-2})\big{)}\\ & \cdots\\ & = e^{\varepsilon_{k-1}}\bigg{(} e^{\varepsilon_{k-2}} \Big{(} \cdots \big{(}e^{\varepsilon_{0}} p(v_{0}) \big{)} \cdots \Big{)} \bigg{)}\\ &= e^{\varepsilon_{k-1}+\varepsilon_{k-2} +\dots + \varepsilon_{0}} \alpha.\label{eq:lastn} \end{align} We now want to find the smallest index on the path for which \eqref{eq: d=0, ex+d} is not tight. This is, we want to find the last index for which the iterations \eqref{eq:last1}-\eqref{eq:lastn} hold. Let this parameter to be $\tau$. Therefore, on the one hand, $\tau$ satisfies \begin{align}\label{eq:tau1} p^*(v_{\tau}) & = e^{\varepsilon_{\tau-1}+\varepsilon_{\tau-2} +\dots + \varepsilon_{0}}\alpha. \end{align} On the other hand, by the definition of $\tau$, for $i = \tau + 1$, \eqref{eq: d=0, e(1-a)+d} will give the tightest upper bound on $p(v_{\tau+1})$. That is, $$\min \left\{ e^{\varepsilon_\tau} p^*(v_{\tau}), \frac{ p^*(v_{\tau}) -1 + e^{\varepsilon_\tau}}{e^{\varepsilon_\tau}}\right\} = \frac{ p^*(v_{\tau}) -1 + e^{\varepsilon_\tau}}{e^{\varepsilon_\tau}}.$$ Therefore, from Lemma \ref{lem: iff}, we must have \begin{align}\label{eq:tau2} p^*(v_{\tau}) \geq \frac{1}{ e^{\varepsilon_{\tau}} + 1}. \end{align} Combining \eqref{eq:tau2} and \eqref{eq:tau1} and taking the minimum over all $i\in [n]$ gives \eqref{eq:tau0}. We need to verify that the upper bounds \eqref{eq: d=0, ex+d} and \eqref{eq: d=0, e(1-a)+d} do not ``toggle" or ``alternate" in providing the tightest bound on $p^*(v_i)$ for $i > \tau$. Referring to Lemma \ref{lem: iff}, this is equivalent to verifying that for every $\tau \leq i \leq n$ we will have \[p^*(v_{i}) \geq \frac{1}{ e^{\varepsilon_{i}} + 1}.\] For $i = \tau$ this holds by definition. For $\tau < i \leq n$, this can be proved via contradiction. Assume there exists $i> \tau$ such that the following statements are satisfied. \begin{align}\label{eq:firsttau} p^*(v_{i}) &\geq \frac{1}{ e^{\varepsilon_{i}} + 1},\\ p^*(v_{i+1}) &< \frac{1}{ e^{\varepsilon_{i+1}} + 1}.\label{eq:secondtau} \end{align} Since \eqref{eq:firsttau} is satisfied, from Lemma \ref{lem: iff}, we must have: \begin{align} p^*(v_{i+1})&= \min \left\{ e^{\varepsilon_i} p^*(v_{i}), \frac{ p^*(v_{i}) -1 + e^{\varepsilon_i}}{e^{\varepsilon_i}}\right\} \\&= \frac{ p^*(v_{i}) -1 + e^{\varepsilon_{i}}}{e^{\varepsilon_{i}}}. \end{align} Therefore, substituting $p^*(v_{i+1})$ with the above equation in \eqref{eq:secondtau} leads us to: \begin{align} \label{eq: <1} p^*(v_{i+1}) = \frac{ p^*(v_{i}) -1 + e^{\varepsilon_{i}}}{e^{\varepsilon_{i}}} <\frac{1}{ e^{\varepsilon_{i+1}} + 1}. \end{align} Using the bound in \eqref{eq:firsttau} on $p^*(v_i)$ in the above gives \[ \frac{ \frac{1}{ e^{\varepsilon_{i}} + 1} -1 + e^{\varepsilon_{i}}}{e^{\varepsilon_{i}}} < \frac{1}{ e^{\varepsilon_{i+1}} + 1}, \] which is equivalent to: \begin{align} \frac{ \frac{1+ e^{2\varepsilon_{i}} - 1}{ e^{\varepsilon_{i}} + 1}} {e^{\varepsilon_{i}}} &< \frac{1}{ e^{\varepsilon_{i+1}} + 1}\iff \\ \frac{ e^{\varepsilon_{i}}} { e^{\varepsilon_{i}} + 1} &< \frac{1}{ e^{\varepsilon_{i+1}} + 1} \iff e^{\varepsilon_{i}} e^{\varepsilon_{i+1}} < 1. \end{align} The last statement is a contradiction as $ 0< \varepsilon_{i} + \varepsilon_{i+1}$. Having proved that the optimal mechanism has at most two regimes, as determined by a single $\tau$, the last step is to provide a closed-form expression for the iterations $\tau < i \leq n $. Starting with $i = \tau+1$, we will have \begin{align} p^*(v_{\tau+1}) &= \frac{ p^*(v_{\tau}) -1 + e^{\varepsilon_\tau}}{e^{\varepsilon_\tau}}\\&=\frac{e^{\varepsilon_{\tau-1}+\varepsilon_{\tau-2} +\dots + \varepsilon_{0}}\alpha-1+e^{\varepsilon_\tau}}{e^{\varepsilon_\tau}}\\&=e^{-\varepsilon_\tau}e^{\varepsilon_{\tau-1}+\varepsilon_{\tau-2} +\dots + \varepsilon_{0}}\alpha-e^{-\varepsilon_\tau}+1. \end{align} For $i = \tau +2$, we will get \begin{align*} p^*(v_{\tau+2}) &= \frac{ p^*(v_{\tau+1}) -1 + e^{\varepsilon_{\tau+1}}}{e^{\varepsilon_{\tau+1}}}\\&=\frac{ e^{-\varepsilon_\tau+\varepsilon_{\tau-1}+\varepsilon_{\tau-2} +\dots + \varepsilon_{0}}\alpha-e^{-\varepsilon_\tau}+ e^{\varepsilon_{\tau+1}}}{e^{\varepsilon_{\tau+1}}}\\&= e^{-\varepsilon_{\tau+1}-\varepsilon_\tau+\varepsilon_{\tau-1}+\varepsilon_{\tau-2} +\dots + \varepsilon_{0}}\alpha-e^{-\varepsilon_{\tau+1}-\varepsilon_\tau}+1. \end{align*} continuing this for $i > \tau + 2$ completes the proof. \end{IEEEproof} We recover the result for the homogeneous case \cite{RafnoDP2colorPaper}. \begin{corollary} Let $\varepsilon > 0$ and set $\varepsilon_i = \varepsilon$ for $i \in [n]$. Theorem~\ref{theo:path} recovers the results in \cite{RafnoDP2colorPaper} for $\delta = 0$. \end{corollary} \begin{IEEEproof} For $\varepsilon_i = \varepsilon$ for $i \in [n]$, the value of $\tau$ from \eqref{eq:tau0} is \begin{align}\label{eq:tauspecial} \tau_1 &= \left\lceil\frac{1}{\varepsilon}\log\left(\frac{1}{\alpha(1+e^{\epsilon})}\right)\right\rceil. \end{align} Under $\varepsilon_i = \varepsilon$ for $i \in [n]$, $p^*$ given in Theorem \ref{theo:path} is simplified to \begin{align*} p^*(v_i) \coloneqq \begin{cases} e^{i\varepsilon} \alpha, & i \leq \tau_1, \\ 1-e^{(i-\tau_1)\varepsilon}+e^{(-i+2\tau_1)\varepsilon}\alpha, & i > \tau_1. \end{cases} \end{align*} Note the results in \cite{RafnoDP2colorPaper} were in terms of ``the probability of being red": $R_i = (1-p_i) = \Pr[\mathcal{M}(v_i) = 2]$. Also, the head vertex in \cite{RafnoDP2colorPaper} started at $i = n_B$ instead of $i=0$ here, which is adopted for easier notation in this paper. With appropriate index conversion, it can be verified that we recover the results in Theorem 10 in \cite{RafnoDP2colorPaper} for $\delta = 0$. \end{IEEEproof} \subsection{The General Case}\label{TSaP.B} In this section, we generalize the results of the previous section. We assume for a given general graph $\mathcal{G}$ and heterogeneous privacy budget $\varepsilon(\cdot)$ over $E$, the mechanism is specified a priori over a subset of vertices $S\subseteq V$, such that $\partial _T (\mathcal{G})\subseteq S$, i.e, $p(u) = \alpha_u$, for every $u\in S$, is given with no additional assumptions on $\alpha_u$. Our goal is to extend $p$ for all other vertices whose mechanism is to be specified in an optimal and computationally efficient manner. The following definition will come handy. \begin{definition}[The path upper bound function]\label{def: The path upper bound function} For every vertex $v \in \mathcal{G}$ and $(u,v)$-path $\rho \in \mathcal{P}(u,v)$ such that its head node $u\in S$, we define $U_{\rho, \alpha_u} (v)$ to be the upper bound on the value of $p(v)$ imposed by $p(u) = \alpha_u$. \end{definition} We prove that the following optimization problem can be solved in polynomial time for every vertex $u$ with a fixed value $\alpha \in [0,1]$. \[\minimize_{\rho \in \mathcal{P}(u,v)} \quad U_{\rho, \alpha}(v)\] To this end, we propose the polynomial Algorithm \ref{algo: subroutine} which takes $u,\alpha$ and $ \mathcal{G}$ as the input and outputs $A_{u, \alpha}(v)$ for every vertex $v \in V$ such that $A_{u, \alpha}(v) = \min _{\rho \in \mathcal{P}(u,v)} U_{\rho, \alpha}(v).$ \begin{theorem}\label{theo: aoptimal} If $A_{u, \alpha}(v)$ is the output of the Algorithm \ref{algo: subroutine} then, \[A_{u, \alpha}(v) = \min _{\rho \in \mathcal{P}(u,v)} U_{\rho, \alpha}(v).\] \end{theorem} \begin{IEEEproof} Let $v_1, \dots , v_{n-1}$ be the vertices of graph in the order Algorithm \ref{algo: subroutine} selects. By contradiction, let $k$ be the smallest index such that $A_{u, \alpha}(v_k) \not = \min _{\rho \in \mathcal{P}(u,v_k)} U_{\rho, \alpha}(v).$ First, assume that $A_{u, \alpha}(v_k) < \min _{\rho \in \mathcal{P}(u,v_k)} U_{\rho, \alpha}(v_k).$ From Algorithm \ref{algo: subroutine} (line 7), we have $A_{u, \alpha}(v_k) = \min_{v \in N(S_k)} \alpha^*(v)$. Define $u_k$ as: \[ \begin{aligned} u_k := \argmin_{v' \in N^*(v_k)} U_{(v',v_k),A_{u, \alpha}(v')}(v_k)\\ \Rightarrow A_{u, \alpha}(v_k) = U_{(u_k,v_k),A_{u, \alpha}(u_k)}(v_k). \end{aligned} \] Then, by the choice of $k$, $u_k $ belongs to $S_k$ and we have: \[A_{u, \alpha}(u_k) = \min _{\rho \in \mathcal{P}(u,u_k)} U_{\rho, \alpha}(u_k) = U_{\rho', \alpha}(u_k).\] Then, following from Lemma \ref{lem: increasing} we have: \[ \begin{aligned} A_{u, \alpha}(v_k) & = U_{(u_k,v_k),A_{u, \alpha}(u_k)}(v_k) &\\ & = U_{(u_k,v_k),U_{\rho', \alpha}(u_k)}(v_k)& = U_{\rho' v_k,\alpha}(v_k). \end{aligned} \] Thus, $ A_{u, \alpha}(v_k)$ ($=U_{\rho' v_k,\alpha}(v_k)$) cannot be less than $\min _{\rho \in \mathcal{P}(u,v)} U_{\rho, \alpha}(v_k)$. \\It remains to consider the case: $A_{u, \alpha}(v_k) > \min _{\rho:\rho \in \mathcal{P}(u,v_k)} U_{\rho, \alpha}(v_k).$ Let $\rho$ be the $(u,v_k)$-path that imposes the strongest induced condition on $v_k$. First observe that $\rho$ connects a vertex inside $S_k$ (i.e., $u$) to a vertex outside (i.e., $v_k$). Following from Lemma \ref{lem: increasing}, if we traverse this path from head to tail, the first time we leave $S_k$ must be the last step. Since, otherwise we would not have selected $v_k$. \\Let $w$ be the vertex on $\rho$ before we reach $v_k$. Hence, $w $ is also appeared in $N^*(v_k)$. Therefore, by the choice of $\alpha^*(v_k)$, we have $A_{u, \alpha}(v_k)=\alpha^*(v_k) \leq U_{(w,v_k),A_{u,\alpha}(w)}(v_k)$. The equality is because of the choice of $v_k$ and the inequality is because of the definition of $\alpha^*$ and the fact that $U_{(w,v_k),A_{u,\alpha}(w)}$ is one of the terms in minimizing the problem which defines $\alpha^*(v_k)$. \end{IEEEproof} Let $p: S \to [0,1]$ be a partial function. We want to know under what condition $p$ can be extended to an $\varepsilon$-DP function. To this end, first we define the notion of \say{compatible function} and then we show that the necessary and sufficient condition for $p$ to be extendable to a $\varepsilon$-DP function is the compatibility condition. We also prove that testing compatibility can be done in polynomial time. \begin{definition} A partial function $p:S \to [0,1]$ is called compatible if, for every vertices $u,v \in S$, it follows that $p(v) \leq \min _{\rho \in \mathcal{P}(u,v)} U_{\rho, \alpha}(u)$. \end{definition} Now we give the technical proof of Theorem \ref{theorem:main1}. \begin{algorithm}[t] \caption{Construction of the $A$ function}\label{algo: subroutine} \SetAlgoLined \SetAlgoNoLine \SetAlgoLined \textbf{Input:} Graph $\mathcal{G} $, $u \in V$, $\alpha_{u} = p(u)$. \textbf{Output: Function $A_{u, \alpha}: V \to [0,1]$} \nl $i \gets 1$ \nl $S_1 \gets \{u\}$ \nl $A_{u,\alpha}(u) \gets \alpha_{u} $ \While{$|S_i|< |V| $}{ \For{ $v \in N(S_i)$}{ \nl $N^*(v) \gets N(v) \cap S_i $ \nl $\alpha^*(v) \gets \min_{v' \in N^*(v)} U_{(v',v),A_{u,\alpha}(v')}(v)$ } \nl $v_i \gets \argmin_{v \in N(S_i)} \alpha^*(v)$ \nl $A_{u, \alpha}(v_i) \gets \min_{v \in N(S_i)} \alpha^*(v)$ \nl $S_{i+1} \gets S_i \cup \{v_i\}$ \nl $i \gets i+1$ } \end{algorithm} \begin{algorithm}[t] \caption{Construction of the extension of a mechanism} \label{algo: acomplete} \SetAlgoLined \textbf{Input:} Graph $\mathcal{G} $, subset $S \subseteq V$ which $\partial _T (\mathcal{G}) \subseteq S$, partial function $p: S \to [0,1]$. \textbf{Output: Function $\tilde{p}: V \to [0,1]$} \nl $S_1 \gets S$ \If{$p$ is not compatible}{ \nl \Return No $\varepsilon(\cdot)$-DP extension of $p$ exists. } \For{$v \in S $ }{ \nl $\tilde{p}(v) \gets p(v) $ } \For{ $v \in V \setminus S $}{ \If{$T(v) = 1$}{ \nl $\tilde{p}(v) \gets \min_{u \in S} A_{u, \tilde{p}(u)}(v)$ } \If{$T(v) = 2$}{ \nl $\tilde{p}(v) \gets \min_{u \in S} A_{u, 1- \tilde{p}(u)}(v)$ } } \end{algorithm} \begin{IEEEproof}[Proof of Theorem \ref{theorem:main1}] Since $\tilde{p}$ is an extension function of $p$, for the sake of simplicity, in the rest of the proof, we denote $\tilde{p}$ by $p$. In Section \ref{HDP}, we argued that to complete the proof of Theorem \ref{theorem:main1}, we must show that if Algorithm \ref{algo: acomplete} outputs a function $p$, then it is an $\varepsilon(\cdot)$-DP mechanism. By the definition, to show that a function is $\varepsilon(\cdot)$-DP, we must verify \eqref{eq: r1} and \eqref{eq: r2} hold for every edge $(u, v)$ in $E$. We consider three cases. \begin{itemize} \item{\textbf{Case 1: ($u,v \in S$)}} In this case, since the algorithm has passed the compatibility test, the value of $p$ at $u,v$ are consistent; that is, $p(v)$ is no more than the strongest condition $p(u)$ imposes on it via all possible $(u, v)$-paths. In particular, the one imposed by the edge $(u,v)$ is also guaranteed. Similarly, the condition $p(v)$ imposes on $p(u)$ must be satisfied. Thus, the initial conditions on the edge $(u,v)$ are satisfied. \item{\textbf{Case 2: ($u\in S, v\notin S$)}} First, because of the symmetry and without loss of generality, let us assume that $T(v)=1$. In this case, similar to the earlier case, we can observe that the condition $p(u)$ imposes on $p(v)$ is satisfied. We just have to show that the converse is also true. Assuming the opposite we have $U_{(v,u), p(v) } (u) < p(u)$. Since $p(v)$ is assigned by the algorithm as the least upper bounds imposed by all the vertices in $S$ via all the possible paths connecting them to $v$, let $\omega$ and $\rho_1$ be the vertex and the path that give the least upper bound to $p(v)$. Then, following from Lemma \ref{lem: increasing} we have: \begin{align}\label{eq: T5,e2} \begin{aligned} U_{\rho_1u, p(\omega) } (u) & = U_{(v,u), [U_{\rho_1, p(\omega) } (v) ]} (u) \\& = U_{(v,u), p(v)} (u) . \end{aligned} \end{align} Following from the compatibility condition, as $\omega, u \in S$: \begin{align}\label{eq: T5,e1} p(u) \leq U_{\rho_1u, p(\omega) } (u). \end{align} Finally, \eqref{eq: T5,e2} and \eqref{eq: T5,e1} lead us to the following contradiction: $p(u) \leq U_{\rho_1u, p(\omega) } (u) = U_{(v,u), p(v)} (u) < p(u) $. \item{\textbf{Case 3: ($u,v \notin S$)}} In this case, we first observe that $T(u)=T(v)$, since if it is not the case, then $u$ and $v$ are boundary vertices and therefore by the assumption, $u,v\in S$, which is a contradiction. Now, without loss of generality, let us assume that $T(u)=T(v)=1$ and $U_{(v,u), p(v) } (u) < p(u)$. Then, from the same setting of the previous case we obtain the following equation: $ U_{\rho_1u, p(\omega)}(u) = U_{(v,u), p(v) } (u) < p(u) $. Also, Algorithm \ref{algo: acomplete} (line 13) implies that $p(u) = \min_{\omega' \in S} A_{\omega', p(\omega')}(u)$ and, Theorem \ref{theo: aoptimal} leads us to the following: \[ p(u) = \min_{\omega' \in S} A_{\omega', p(\omega')}(u) = \min_{\omega' \in S, \rho \in \mathcal{P}(\omega',u)} U_{\rho, p(\omega')}(u),\] which contradicts $U_{\rho_1u, p(\omega)}(u)< p(u)$. \end{itemize} The proof of uniqueness is straightforward. The last part in Theorem \ref{theorem:main1} is regarding the time complexity of Algorithm \ref{algo: acomplete}. This is discussed in the next part. \end{IEEEproof} Now, we analyze the running time of Algorithms. In Algorithm \ref{algo: subroutine} at each iteration, every edge which has exactly one endpoint in $S$ is considered, and the one with the best (minimum) upper bound on the other end is selected. This will take at most $\mathcal{O}(|E|)$ time. Thus, Algorithm \ref{algo: subroutine} runs in $\mathcal{O}(|E|\cdot|V|)$ time. In Algorithm \ref{algo: acomplete}, compatibility test takes $\mathcal{O}(|V|^2)$ calls of Algorithm \ref{algo: subroutine}. If $p$ is compatible, then for every vertex $v\in V\setminus S$ we check the best bound. For that, we will call Algorithm \ref{algo: subroutine} $\mathcal{O}(|S| \cdot |V\setminus S| = \mathcal{O}(|V|^2) $ many times. In conclusion, we have the following theorem. \begin{theorem} Algorithm \ref{algo: subroutine} and \ref{algo: acomplete} run in $\mathcal{O}(|E| |V|)$ and $\mathcal{O}(|V|^3|E|)$ respectively. \end{theorem}
{'timestamp': '2022-03-30T02:30:04', 'yymm': '2203', 'arxiv_id': '2203.15429', 'language': 'en', 'url': 'https://arxiv.org/abs/2203.15429'}
arxiv
\section{Introduction}\label{intro} Let $\mathbb{Z}_{p^s}$ be the ring of integers modulo $p^s$ with $p$ prime and $s\geq1$. The set of $n$-tuples over $\mathbb{Z}_{p^s}$ is denoted by $\mathbb{Z}_{p^s}^n$. In this paper, the elements of $\mathbb{Z}^n_{p^s}$ will also be called vectors. The order of a vector $\mathbf u$ over $\mathbb{Z}_{p^s}$, denoted by $o(\mathbf{u})$, is the smallest positive integer $m$ such that $m \mathbf{u} ={\mathbf{0}}$. A code over $\mathbb{Z}_p$ of length $n$ is a nonempty subset of $\mathbb{Z}_p^n$, and it is linear if it is a subspace of $\mathbb{Z}_{p}^n$. Similarly, a nonempty subset of $\mathbb{Z}_{p^s}^n$ is a $\mathbb{Z}_{p^s}$-additive if it is a subgroup of $\mathbb{Z}_{p^s}^n$. Note that, when $p=2$ and $s=1$, a $\mathbb{Z}_{p^s}$-additive code is a binary linear code and, when $p=2$ and $s=2$ , it is a quaternary linear code or a linear code over $\mathbb{Z}_4$. In \cite{Sole}, a Gray map from $\mathbb{Z}_4$ to $\mathbb{Z}_2^2$ is defined as $\phi(0)=(0,0)$, $\phi(1)=(0,1)$, $\phi(2)=(1,1)$ and $\phi(3)=(1,0)$. There exist different generalizations of this Gray map, which go from $\mathbb{Z}_{2^s}$ to $\mathbb{Z}_2^{2^{s-1}}$ \cite{Carlet,Codes2k,dougherty,Nechaev,Krotov:2007}. The one given in \cite{Nechaev} can be defined in terms of the elements of a Hadamard code \cite{Krotov:2007}, and Carlet's Gray map \cite{Carlet} is a particular case of the one given in \cite{Krotov:2007} satisfying $\sum \lambda_i \phi(2^i) =\phi(\sum \lambda_i 2^i)$ \cite{KernelZ2s}. In this paper, we focus on a generalization of Carlet's Gray map, from $\mathbb{Z}_{p^s}$ to $\mathbb{Z}_p^{p^{s-1}}$, which is also a particular case of the one given in \cite{ShiKrotov2019}. Specifically, \begin{equation}\label{genGraymap} \phi_s(u)=(u_{s-1},\dots,u_{s-1})+(u_0,\dots,u_{s-2})Y_{s-1}, \end{equation} where $u\in\mathbb{Z}_{p^s}$, $[u_0,u_1, \ldots, u_{s-1}]_p$ is the p-ary expansion of $u$, that is $u=\sum_{i=0}^{s-1}p^{i}u_i$ ($u_i \in \mathbb{Z}_p$), and $Y_{s-1}$ is a matrix of size $(s-1)\times p^{s-1}$ whose columns are the elements of $\mathbb{Z}_p^{s-1}$. Then, we define $\Phi_s:\mathbb{Z}_{p^s}^ n\rightarrow\mathbb{Z}_p^{np^{s-1}}$ as the component-wise Gray map $\phi_s$. Let ${\cal C}$ be a $\mathbb{Z}_{p^s}$-additive code of length $n$. We say that its image $C=\Phi({\cal C})$ is a $\mathbb{Z}_{p^s}$-linear code of length $p^{s-1}n$. Since ${\cal C}$ is a subgroup of $\mathbb{Z}_{p^s}^n$, it is isomorphic to an abelian structure $\mathbb{Z}_{p^s}^{t_1}\times\mathbb{Z}_{p^{s-1}}^{t_2}\times \dots\times\mathbb{Z}_{p^2}^{t_{s-1}}\times\mathbb{Z}_p^{t_s}$, and we say that ${\cal C}$, or equivalently $C=\Phi({\cal C})$, is of type $(n;t_1,\dots,t_{s})$. Note that $|{\cal C}|=p^{st_1}p^{(s-1)t_2}\cdots p^{t_s}$. Unlike linear codes over finite fields, linear codes over rings do not have a basis, but there exists a generator matrix for these codes having minimum number of rows, that is, $t_1+\cdots+t_s$ rows. A $p$-linear combination of the elements of $\mathcal{B}=\{\mathbf{b}_1,\dots,\mathbf{b}_r\}\subseteq \mathbb{Z}_{p^s}^n$ is $\sum_{i=1}^{r}\lambda_i\mathbf{b}_i$, for $\lambda_i\in\mathbb{Z}_p$. We say that $\mathcal{B}$ is a $p$-basis of ${\cal C}$ if the elements in $\mathcal{B}$ are $p$-linearly independent and any $\mathbf{c}\in{\cal C}$ is a $p$-linear combination of the elements of $\cal{B}$. Let ${\cal S}_n$ be the symmetric group of permutations on the set $\{1,\dots,n\}$. Two codes $C_1$ and $C_2$ over $\mathbb{Z}_p$, are said to be equivalent if there is a vector $\textbf{a}\in \mathbb{Z}_p^n$ and a permutation of coordinates $\pi\in {\cal S}_n$ such that $C_2=\{ \textbf{a}+\pi(\textbf{c}) : \textbf{c} \in C_1 \}$. Two $\mathbb{Z}_{p^s}$-additive codes, ${\cal C}_1$ and ${\cal C}_2$, are said to be permutation equivalent if they differ only by a permutation of coordinates, that is, if there is a permutation of coordinates $\pi\in {\cal S}_n$ such that ${\cal C}_2=\{ \pi(\textbf{c}) : \textbf{c} \in {\cal C}_1 \}$. Two structural properties of codes over $\mathbb{Z}_p$ are the rank and dimension of the kernel. The rank of a code $C$ over $\mathbb{Z}_p$ is simply the dimension of the linear span, $\langle C \rangle$, of $C$. The kernel of a code $C$ over $\mathbb{Z}_p$ is defined as $\mathrm{K}(C)=\{\textbf{x}\in \mathbb{Z}_p^n : \textbf{x}+C=C \}$ \cite{BGH83,pKernel}. If the all-zero vector belongs to $C$, then $\mathrm{K}(C)$ is a linear subcode of $C$. Note also that if $C$ is linear, then $K(C)=C=\langle C \rangle$. We denote the rank of $C$ as $\text{rank}(C)$ and the dimension of the kernel as $\text{ker}(C)$. These parameters can be used to distinguish between non-equivalent codes, since equivalent ones have the same rank and dimension of the kernel. A generalized Hadamard $(GH)$ matrix $H(p,\lambda) = (h_{i j})$ of order $n = p\lambda$ over $\mathbb{Z}_p$ is a $p\lambda \times p\lambda$ matrix with entries from $\mathbb{Z}_p$ with the property that for every $i, j$, $1 \leq i < j \leq p\lambda,$ each of the multisets $\{h_{is}- h_{js} : 1 \leq s \leq p\lambda\}$ contains every element of $\mathbb{Z}_p$ exactly $\lambda$ times \cite{jungnickel1979}. An ordinary Hadamard matrix of order $4\mu$ corresponds to $GH$ matrix $H(2,\lambda)$ over $\mathbb{Z}_2$, where $\lambda = 2\mu$ \cite{Key}. Two $GH$ matrices $H_1$ and $H_2$ of order $n$ are said to be equivalent if one can be obtained from the other by a permutation of the rows and columns and adding the same element of $\mathbb{Z}_p$ to all the coordinates in a row or in a column. We can always change the first row and column of a $GH$ matrix into zeros and we obtain an equivalent $GH$ matrix which is called normalized. From a normalized Hadamard matrix $H$, we denote by $F_H$ the code over $\mathbb{Z}_p$ consisting of the rows of $H$, and $C_H$ the one defined as $C_H = \bigcup_{\alpha \in\mathbb{Z}_p} (F_H + \alpha \textbf{1})$, where $F_H + \alpha \textbf{1} = \{\textbf{h} + \alpha \textbf{1} : \textbf{h} \in F_H\}$ and $\textbf{1}$ denotes the all-one vector. The code $C_H$ over $\mathbb{Z}_p$ is called generalized Hadamard $(GH)$ code \cite{dougherty2015ranks}. Note that $C_H$ is generally a nonlinear code over $\mathbb{Z}_p$. Let ${\cal C}$ be a $\mathbb{Z}_{p^s}$-additive code such that $\Phi({\cal C})$ is a GH code. Then, we say that ${\cal C}$ is a $\mathbb{Z}_{p^s}$-additive GH code and $\Phi({\cal C})$ is a $\mathbb{Z}_{p^s}$-linear GH code. Note that a GH code over $\mathbb{Z}_p$ of length $N$ has $pN$ codewords and minimum distance $\frac{N(p-1)}{p}$. The $\mathbb{Z}_4$-linear Hadamard codes of length $2^t$ can be classified by using either the rank or the dimension of the kernel \cite{Kro:2001:Z4_Had_Perf,PheRifVil:2006}. There are exactly $\lfloor \frac{t-1}{2}\rfloor$ such codes for all $t\geq 2$. Later, in \cite{KernelZ2s}, an iterative construction for $\mathbb{Z}_{2^s}$-linear Hadamard codes was described, and the linearity and kernel of these codes were established. It was proved that the dimension of the kernel only provides a complete classification for some values of $t$ and $s$. A partial classification by using the kernel was obtained, and the exact amount of non-equivalent such codes was given up to $t=11$ for any $s\geq 2$. Authors also give a lower bound based on the rank and dimension of the kernel. Later, in paper \cite{EquivZ2s}, for $s\geq 2$, it was established that some $\mathbb{Z}_{2^s}$-linear Hadamard codes of length $2^t$ are equivalent, once $t$ is fixed, and this fact improved the known upper bounds for the number of such nonequivalent codes. Moreover, authors show that, up to $t = 11$, this new upper bound coincides with the known lower bound (based on the rank and dimension of the kernel). Finally, for $s \in \{2,3\}$, they establish the full classification of the $\mathbb{Z}_{2^s}$-linear Hadamard codes of length $2^t$ by giving the exact number of such codes. For $s\geq 2$, and $p\geq 3$ prime, the dimension of the kernel for $\mathbb{Z}_{p^s}$-linear GH codes of length $p^t$ is established in \cite{HadamardZps}, and it is proved that this invariant only provides a complete classification for certain values of $t$ and $s$. Lower and upper bounds are also established for the number of nonequivalent $\mathbb{Z}_{p^s}$-linear GH codes of length $p^t$, when both $t$ and $s$ are fixed, and when just $t$ is fixed; denoted by $\mathcal{A}_{t,s,p}$ and $\mathcal{A}_{t,p}$, respectively. From \cite{HadamardZps}, we can check that there are nonlinear codes having the same rank and dimension of the kernel for different values of $s$, once the length $p^t$ is fixed, for all $4\leq t\leq 11$. In this paper, we show that there are generalized Hadamard codes of length $p^t$, with $p\geq 3$ and $t\geq 1$, that can be seen up to permutations as $\mathbb{Z}_{p^s}$-linear codes for different values of $s$. Moreover, for $t\leq 10$, we see that the codes that are permutation equivalent are, in fact, those having the same pair of invariants, rank and dimension of the kernel. For example, in Table \ref{table:Types}, for $t=7$, the colored codes having same rank and dimension of the kernel are permutation equivalent. These equivalence results allow us to obtain a more accurate classification of the $\mathbb{Z}_{p^s}$-linear GH codes, than the one given in \cite{HadamardZps}. The paper is organized as follows. In Section \ref{Sec:construction}, we recall the recursive construction of the $\mathbb{Z}_{p^s}$-linear GH codes, the known partial classification, and some bounds on the number of nonequivalent such codes, presented in \cite{HadamardZps}. In Section \ref{sec:relations}, we prove some equivalence relations among the $\mathbb{Z}_{p^s}$-linear GH codes of the same length $p^t$. Later, in Section \ref{sec:Classification}, we improve the classification given in \cite{HadamardZps} by refining the known bounds. \section{Preliminaries and Partial classification} \label{Sec:construction} In this section, we provide some results presented in \cite{HadamardZps} and related to the recursive construction, partial classification and bounds on the number of nonequivalent $\mathbb{Z}_{p^s}$-linear GH codes of length $p^t$ with $t\geq 3$ and $p\geq 3$ prime. Let $T_i=\lbrace j\cdot p^{i-1}\, :\, j\in\lbrace0,1,\dots,p^{s-i+1}-1\rbrace \rbrace$ for all $i \in \{1,\ldots,s \}$. Note that $T_1=\lbrace0,\dots,p^{s}-1\rbrace$. Let $t_1$, $t_2$,\dots,$t_s$ be nonnegative integers with $t_1\geq1$. Consider the matrix $A_p^{t_1,\dots,t_s}$ whose columns are exactly all the vectors of the form $\mathbf{z}^T$, $\mathbf{z}\in\lbrace1\rbrace\times T_1^{t_1-1}\times T_{2}^{t_2}\times\cdots\times T_s^{t_s}$. We write $A^{t_1,\dots,t_s}$ instead of $A_p^{t_1,\dots,t_s}$ when the value of $p$ is clear by the context. Let $\mathbf{0}, \mathbf{1},\mathbf{2},\ldots, \mathbf{p^{s}-1}$ be the vectors having the same element $0, 1, 2, \ldots, p^s-1$ from $\mathbb{Z}_{p^s}$ in all its coordinates, respectively. Any matrix $A^{t_1,\dots,t_s}$ can be obtained by applying the following recursive construction. We start with $A^{1,0,\dots,0}=(1)$. Then, if we have a matrix $A=A^{t_1,\dots,t_s}$, for any $i\in \{1,\ldots,s\}$, we may construct the matrix \begin{equation}\label{eq:recGenMatrix} A_i= \left(\begin{array}{cccc} A & A &\cdots & A \\ 0\cdot \mathbf{p^{i-1}} & 1\cdot \mathbf{p^{i-1}} & \cdots & (p^{s-i+1}-1)\cdot \mathbf{p^{i-1}} \\ \end{array}\right). \end{equation} Finally, permuting the rows of $A_i$, we obtain a matrix $A^{t'_1,\ldots,t'_s}$, where $t'_j=t_j$ for $j\not=i$ and $t'_i=t_i+1$. Note that any permutation of columns of $A_i$ gives also a matrix $A^{t_1',\dots,t_s'}$. Along this paper, we consider that the matrices $A^{t_1,\ldots,t_s}$ are constructed recursively starting from $A^{1,0,\ldots,0}$ in the following way. First, we add $t_1-1$ rows of order $p^s$, up to obtain $A^{t_1,0,\ldots,0}$; then $t_2$ rows of order $p^{s-1}$ up to generate $A^{t_1,t_2,\ldots,0}$; and so on, until we add $t_s$ rows of order $p$ to achieve $A^{t_1,\ldots,t_s}$. See \cite{HadamardZps} for examples. Let $\mathcal{H}^{t_1,\dots,t_s}$ be the $\mathbb{Z}_{p^s}$-additive code generated by the matrix $A^{t_1,\dots,t_s}$, where $t_1,\dots,t_s$ are nonnegative integers with $t_1\geq1$. Let $n=p^{t-s+1}$, where $t=\left(\sum_{i=1}^{s}(s-i+1)\cdot t_i\right)-1$. The code $\mathcal{H}^{t_1,\dots,t_s}$ has length $n$, and the corresponding $\mathbb{Z}_{p^s}$-linear code $H^{t_1,\dots,t_s}=\Phi(\mathcal{H}^{t_1,\dots,t_s})$ is a GH code of length $p^t$ \cite{HadamardZps}. In order to classify the $\mathbb{Z}_{p^s}$-linear GH codes of length $p^t$, we can focus on $t\geq 5$ and $2\leq s \leq t-2$ for $p=2$ (\cite{KernelZ2s}), and on $t\geq 4$ and $2\leq s \leq t-2$ for $p\geq 3$ prime (\cite{HadamardZps}). Moreover, for any $t\geq 5$ and $2\leq s \leq t-2$, there are two $\mathbb{Z}_{2^s}$-linear Hadamard codes of length $2^t$ which are linear, say $H^{1,0,\ldots,0,t+1-s}$ and $H^{1,0\dots,0,1,t-1-s}$; and for any $t\geq 4$ and $2\leq s \leq t-2$, there is a unique $\mathbb{Z}_{p^s}$-linear GH code of length $p^t$ which is linear, say $H^{1,0,\ldots,0,t+1-s}$. Tables \ref{table:Types} and \ref{table:TypesB2}, for $4\leq t\leq 10$ and $2\leq s\leq t-2$, show all possible values $(t_1,\dots,t_s)$ for which there exists a nonlinear $\mathbb{Z}_{p^s}$-linear Hadamard code $H^{t_1,\ldots,t_s}$ of length $p^t$. For each one of them, the values $(r,k)$ are shown, where $r$ is the rank (computed by using the computer algebra system Magma \cite{Magma,Qarypackage}) and $k$ is the dimension of the kernel (\cite{HadamardZps,KernelZ2s,Kro:2001:Z4_Had_Perf}). Note that if two codes have different values $(r,k)$, then they are not equivalent. Therefore, from the values of the dimension of the kernel given in these tables, it is easy to see that this invariant does not classify. Also, considering only the rank, it is not possible to fully classify these codes either. \begin{table}[ht!] \footnotesize \centering \begin{tabular}{|c||cc|cc|cc|cc|} \cline{1-9} & \multicolumn{2}{c|}{$t=4$}& \multicolumn{2}{c|}{$t=5$}& \multicolumn{2}{c|}{$t=6$}& \multicolumn{2}{c|}{$t=7$}\\ \cline{2-9} & $(t_1,\ldots,t_s)$ & $(r,k)$ & $(t_1,\ldots,t_s)$ & $(r,k)$ & $(t_1,\ldots,t_s)$ & $(r,k)$ & $(t_1,\ldots,t_s)$ & $(r,k)$\\[0.2em] \hline \multirow{2}{*}{$\mathbb{Z}_9$} &$(2,1)$ & (6,3) &$(2,2)$ &(7,4) & $(3,1)$ & (12,4) & $(3,2)$ & (13,5) \\ && & $(3,0)$ & (11,3) &$(2,3)$ &(8,5) & $(4,0)$ & (21,4)\\ && && && &$\textcolor{blue}{(2,4)}$ & \textcolor{blue}{(9,6)} \\[0.2em] \hline \multirow{5}{*}{$\mathbb{Z}_{3^3}$} &$(1,1,0)$ & (6,3) & $(2,0,0)$ & (13,2) & $(1,2,0)$ & (12,4) & $(1,2,1)$ & (13,5) \\ && &$(1,1,1)$ &(7,4) & $(2,0,1)$ & (14,3) & $(2,0,2)$ & (15,4) \\ && & & & $(1,1,2)$ &(8,5) & $(2,1,0)$ & (25,3) \\ && & & & & &$\textcolor{blue}{(1,1,3)}$ &\textcolor{blue}{(9,6)} \\[0.2em] \hline \multirow{4}{*}{$\mathbb{Z}_{3^4}$} && &$(1,0,1,0)$ & (7,4) & $(1,1,0,0)$ & (14,3) & $(1,0,2,0)$ & (13,5) \\ && & & & $(1,0,1,1)$ &(8,5) & $(1,1,0,1)$ & (15,4) \\ && & & & & & $(2,0,0,0)$ & (14,2) \\ && & & & & &$\textcolor{blue}{(1,0,1,2)}$ &\textcolor{blue}{(9,6)} \\[0.2em] \hline \multirow{3}{*}{$\mathbb{Z}_{3^5}$} && & & &$(1,0,0,1,0)$ &(8,5) & $(1,0,1,0,0)$ & (15,4) \\ && & & & & & $\textcolor{blue}{(1,0,0,1,1)}$ &\textcolor{blue}{(9,6)} \\[0.2em] \hline \multirow{1}{*}{$\mathbb{Z}_{3^6}$} && & & & & &$\textcolor{blue}{(1,0,0,0,1,0)}$ &\textcolor{blue}{(9,6)} \\[0.2em] \hline \end{tabular} \caption{Rank and kernel for all nonlinear $\mathbb{Z}_{3^s}$-linear GH codes of length $3^t$.} \label{table:Types} \end{table} Let $X_{t,s,p}$ be the number of nonnegative integer solutions $(t_1,\ldots,t_s)\in {\mathbb{N}}^s$ of the equation $t=\left(\sum_{i=1}^{s}(s-i+1)\cdot t_i\right)-1$ with $t_1\geq 1$. This gives the number of $(t_1,\ldots,t_s)$ so that $H^{t_1,\ldots,t_s}$ is a $\mathbb{Z}_{p^s}$-linear GH codes of length $p^t$. Let ${\cal A}_{t,s,p}$ be the number of nonequivalent $\mathbb{Z}_{p^s}$-linear GH codes of length $p^t$ and a fixed $s\geq 2$. Then, for any $t \geq 5$ and $2 \leq s \leq t-1$, we have that ${\cal A}_{t,s,2} \leq X_{t,s,2}-1$, since there are exactly two codes which are linear \cite{KernelZ2s}. For $p\geq 3$ prime, $t \geq 4$ and $2 \leq s \leq t-1$, we have that ${\cal A}_{t,s,p} \leq X_{t,s,p}$, since there are exactly one code which is linear. Moreover, for $t \leq 10$ if $p\geq 3$ prime and for $t \leq 11$ if $p=2$ , this bound is tight. It is still an open problem to know whether this bound is tight for $t\geq 11$ if $p\geq 3$ prime and $t\geq 12$ if $p=2$. A partial classification for the $\mathbb{Z}_{p^s}$-linear GH codes of length $p^t$ is given in \cite{HadamardZps} for $p\geq 3$ prime, and for $p=2$, it is given in \cite{KernelZ2s}. Specifically, lower and upper bounds on the number of nonequivalent such codes, once only $t$ is fixed, are established. We first consider the case $p=2$. \begin{theorem}\label{theo:CardinalFirstBoundY} \cite{KernelZ2s} Let ${\cal A}_{t,2}$ be the number of nonequivalent $\mathbb{Z}_{2^s}$-linear Hadamard codes of length $2^t$ with $t\geq 3$. Then, \begin{equation}\label{eq:CardinalFirstBound} {\cal A}_{t,2} \leq 1+ \sum_{s=2}^{t-2} (X_{t,s,2}-2) \end{equation} and \begin{equation}\label{eq:CardinalFirstBoundY1} {\cal A}_{t,2} \leq 1+\sum_{s=2}^{t-2} ({\cal A}_{t,s,2}-1). \end{equation} \end{theorem} For $p=2$, the upper bound of the value of ${\cal A}_{t,2}$ is improved in \cite{EquivZ2s} where it was proved that for a fixed $t$ there are $\mathbb{Z}_{2^s}$-linear Hadamard codes of length $2^t$ that are equivalent. Let $\tilde{X}_{t,s,2}=|\{ (t_1,\ldots,t_s)\in {\mathbb{N}}^s : t+1=\sum_{i=1}^{s}(s-i+1) t_i, \ t_1\geq 2 \}|$ for $s\in\{3,\dots,\lfloor (t+1)/2\rfloor\}$ and $\tilde{X}_{t,2,2}=|\{ (t_1,t_2)\in {\mathbb{N}}^2 : t+1=2t_1+t_2, \ t_1\geq 3 \}|$. \begin{theorem}[\cite{EquivZ2s}] \label{teo:numNonEquiv100} For $t \geq 3$, \begin{equation}\label{eq:BoundAtNewX} {\cal A}_{t,2} \leq1+ \sum_{s=2}^{\lfloor\frac{t+1}{2}\rfloor} \tilde{X}_{t,s,2} \end{equation} and \begin{equation}\label{eq:BoundAtNew} {\cal A}_{t,2} \leq1+ \sum_{s=2}^{\lfloor\frac{t+1}{2}\rfloor} ({{\cal A}}_{t,s,2}-1). \end{equation} Moreover, for $3 \leq t \leq 11$, first bound is tight. \end{theorem} It is also proved that, for $5\leq t \leq 11$, the improved upper bound is the exact value of ${\cal A}_{t,2}$. Now we consider the case $p\geq 3$. \begin{theorem}\label{theo:CardinalFirstBound} \cite{HadamardZps} Let ${\cal A}_{t,p}$ be the number of nonequivalent $\mathbb{Z}_{p^s}$-linear GH codes of length $p^t$ with $t\geq 3$ and $p\geq 3$ prime. Then, \begin{equation}\label{eq:CardinalFirstBound-p} {\cal A}_{t,p} \leq 1+ \sum_{s=2}^{t-1} (X_{t,s,p}-1) \end{equation} and \begin{equation}\label{eq:CardinalFirstBoundX-p} {\cal A}_{t,p} \leq 1+\sum_{s=2}^{t-1} ({\cal A}_{t,s,p}-1). \end{equation} \end{theorem} In this paper, in order to improve this partial classification, we analyze the equivalence relations among the $\mathbb{Z}_{p^s}$-linear GH codes with the same length $p^t$ and different values of $s$. We prove that some of them are indeed permutation equivalent. For $5\leq t\leq 11$ if $p=2$ and for $4\leq t\leq 10$ if $p\geq 3$ prime, the ones that are permutation equivalent coincide with the ones that have the same invariants, rank and dimension of the kernel, that is, the same pair $(r,k)$ in the Tables. Finally, by using this equivalence relations, we improve the upper bounds on the number ${\cal A}_{t,p}$ of nonequivalent $\mathbb{Z}_{p^s}$-linear GH codes of length $p^t$ with $p\geq 3$ prime given by Theorem \ref{theo:CardinalFirstBound}. This allows us to determine the exact value of ${\cal A}_{t,p}$ for $5\leq t\leq 11$ if $p=2$ and for $4\leq t \leq 10$ if $p\geq 3$ prime, since one of the new upper bounds coincides with the lower bound $(r,k)$ for these cases. \begin{table}[H] \footnotesize \centering \begin{tabular}{|c||cc|cc|cc|} \cline{1-7} & \multicolumn{2}{c|}{$t=8$}& \multicolumn{2}{c|}{$t=9$}& \multicolumn{2}{c|}{$t=10$}\\ \cline{2-7} & $(t_1,\ldots,t_s)$ & $(r,k)$ & $(t_1,\ldots,t_s)$ & $(r,k)$ & $(t_1,\ldots,t_s)$ & $(r,k)$ \\[0.2em] \hline \multirow{4}{*}{$\mathbb{Z}_9$} & $(3,3)$ & (14,6) & $(3,4)$ & (15,7) & $(3,5)$ & (16,8) \\ & $(4,1)$ & (22,5) & $(4,2)$ & (23,6) & $(4,3)$ & (24,7) \\ &$(2,5)$ & (10,7) & $(5,0)$ & (36,5) & $(5,1)$ & (37,6) \\[0.2em] & & &$(2,6)$ & (11,8) & $(2,7)$ & (12,9) \\[0.2em] \hline \multirow{10}{*}{$\mathbb{Z}_{3^3}$}& $(1,2,2)$ & (14,6) & $(1,2,3)$ & (15,7) & $(1,2,4)$ & (16,8) \\ & $(1,3,0)$ & (22,5) & $(1,3,1)$ & (23,6) & $(1,3,2)$ & (24,7) \\ & $(2,0,3)$ & (16,5) & $(2,0,4)$ & (17,6) & $(1,4,0)$ & (37,6) \\ & $(2,1,1)$ & (26,4) & $(2,1,2)$ & (27,5) & $(2,0,5)$ & (18,7) \\ &$(3,0,0)$ & (48,3) & $(2,2,0)$ & (43,4) & $(2,1,3)$ & (28,6) \\ &$(1,1,4)$ & (10,7) & $(3,0,1)$ & (49,4) & $(2,2,1)$ & (44,5) \\ && & $(1,1,5)$ & (11,8) & $(3,0,2)$ & (50,5) \\ && & & & $(3,1,0)$ & (82,4) \\ && & & & $(1,1,6)$ & (12,9) \\[0.2em] \hline \multirow{13}{*}{$\mathbb{Z}_{3^4}$}& $(1,0,2,1)$ & (14,6) & $(1,0,2,2)$ & (15,7) & $(1,0,2,3)$ & (16,8) \\ & $(1,1,0,2)$ & (16,5) & $(1,0,3,0)$ & (23,6) & $(1,0,3,1)$ & (24,7) \\ & $(1,1,1,0)$ & (26,4) & $(1,2,0,0)$ & (49,4) & $(1,1,0,4)$ & (18,7) \\ & $(2,0,0,1)$ & (35,3) & $(1,1,0,3)$ & (17,6) & $(1,1,1,2)$ & (28,6) \\ &$(1,0,1,3)$&(10,7) & $(1,1,1,1)$ & (27,5) & $(1,1,2,0)$ & (44,5) \\ && & $(2,0,0,2)$ & (36,4) & $(1,2,0,1)$ & (50,5) \\ && & $(2,0,1,0)$ & (64,3) & $(2,0,0,3)$ & (37,5) \\ && & $(1,0,1,4)$ & (11,8) & $(2,0,1,1)$ & (65,4) \\ && & & & $(2,1,0,0)$ & (121,3) \\ && & & & $(1,0,1,5)$ & (12,9) \\[0.2em] \hline \multirow{11}{*}{$\mathbb{Z}_{3^5}$}& $(1,0,0,2,0)$ & (14,6) & $(1,0,0,2,1)$ & (15,7) & $(1,0,0,2,2)$ & (16,8) \\ & $(1,0,1,0,1)$ & (16,5) & $(1,0,1,0,2)$ & (17,6) & $(1,0,0,3,0)$ & (24,7) \\ & $(1,1,0,0,0)$ & (35,3) & $(1,0,1,1,0)$ & (27,5) & $(1,0,1,0,3)$ & (18,7) \\ &$(1,0,0,1,2)$ &(10,7) & $(1,1,0,0,1)$ & (36,4) & $(1,0,1,1,1)$ & (28,6) \\ && & $(2,0,0,0,0)$ & (96,2) & $(1,0,2,0,0)$ & (50,5) \\ && & $(1,0,0,1,3)$ & (11,8) & $(1,1,0,0,2)$ & (37,5) \\ && & & & $(1,1,0,1,0)$ & (65,4) \\ && & & & $(2,0,0,0,1)$ & (97,3) \\ && & & & $(1,0,0,1,4)$ & (12,9) \\[0.2em] \hline \multirow{9}{*}{$\mathbb{Z}_{3^6}$} & $(1,0,0,1,0,0)$ & (16,5) & $(1,0,0,0,2,0)$ & (15,7) & $(1,0,0,0,2,1)$ & (16,8) \\ &$(1,0,0,0,1,1)$ &(10,7) & $(1,0,0,1,0,1)$ & (17,6) & $(1,0,0,1,0,2)$ & (18,7) \\ && & $(1,0,1,0,0,0)$ & (36,4) & $(1,0,0,1,1,0)$ & (28,6) \\ && & $(1,0,0,0,1,2)$ & (11,8) & $(1,0,1,0,0,1)$ & (37,5) \\ && & & & $(1,1,0,0,0,0)$ & (97,3) \\ && & & & $(1,0,0,0,1,3)$ & (12,9) \\[0.2em] \hline \multirow{5}{*}{$\mathbb{Z}_{3^7}$}&$(1,0,0,0,0,1,0)$ &(10,7)& $(1,0,0,0,1,0,0)$ & (17,6) & $(1,0,0,0,0,2,0)$ & (16,8) \\ && & $(1,0,0,0,0,1,1)$ & (11,8) & $(1,0,0,0,1,0,1)$ & (18,7) \\ && & & & $(1,0,0,1,0,0,0)$ & (37,5) \\ && & & & $(1,0,0,0,0,1,2)$ &(12,9) \\[0.2em] \hline \multirow{3}{*}{$\mathbb{Z}_{3^8}$}&& & $(1,0,0,0,0,0,1,0)$ &(11,8) & $(1,0,0,0,0,1,0,0)$ & (18,7) \\ && & & & $(1,0,0,0,0,0,1,1)$ &(12,9) \\ [0.2em] \hline \multirow{1}{*}{$\mathbb{Z}_{3^9}$}&& & & &$(1,0,0,0,0,0,0,1,0)$ &(12,9)\\[0.2em] \hline \end{tabular} \caption{Rank and kernel for all nonlinear $\mathbb{Z}_{3^s}$-linear GH codes of length $3^t$.} \label{table:TypesB2} \end{table} \section{Equivalent $\mathbb{Z}_{p^s}$-linear GH codes} \label{sec:relations} In this section, we give some properties of the generalized Gray map $\phi_s$. We also prove that, for $p\geq 3$ prime, some of the $\mathbb{Z}_{p^s}$-linear GH codes of the same length $p^t$, having different values of $s$ are permutation equivalent. Moreover, we see that they coincide with the ones having the same rank and dimension of the kernel for $4\leq t\leq 10$. \begin{lemma}\label{lema4} Let $\lambda_i\in \mathbb{Z}_p$, $i\in\lbrace0,\dots,s-2\rbrace$. Then, $$ \sum_{i=0}^{s-2}\lambda_i\phi_s(p^ i)=\phi_s(\sum_{i=0}^{s-2}\lambda_ip^i). $$ \end{lemma} \begin{proof} Straightforward form the definition of $\phi_s$. \end{proof} \bigskip Let $\gamma_s\in\mathcal{S}_{p^{s-1}}$ be the permutation defined as follows: for a coordinate $k=jp^{s-2}+i+1 \in \{1,2,\dots, p^{s-1}\}$, where $j\in \{0,\dots, p-1\}$ and $i\in \{0,\dots, p^{s-2}-1\}$, $\gamma_s$ moves coordinate $k$ to coordinate $j+ip+1$. So, we can write $\gamma_s$ as \begin{equation*}\label{eq:gamma} \tiny \left( \begin{array}{ccccccccccccc} 1 & 2& \ldots & p^{s-2} & p^{s-2}+1 & p^{s-2}+2 &\ldots & p^{s-2}+p & \ldots & p^{s-1}-p+1 &p^{s-1}-p+2 &\ldots &p^{s-1} \\ 1 & p+1& \ldots &(p^{s-2}-1)p+1 &2 & p+2 & \ldots & (p^{s-2}-1)p+2 &\ldots & p &p+p & \ldots &p^{s-1}\\ \end{array} \right). \end{equation*} \begin{example} For $p=3$ and $s=3$, \begin{equation*} \gamma_3=\left( \begin{array}{ccccccccccc} 1 & 2& 3& & 4& 5& 6& &7& 8& 9 \\ 1 & 4& 7& & 2& 5& 8& &3& 6& 9 \\ \end{array} \right)=(2,4)(3,7)(6,8) \in \mathcal{S}_9. \end{equation*} and for $p=3$ and $s=4$, \begin{multline*} \footnotesize \arraycolsep=1.4pt\def{1} \gamma_4=\left( \begin{array}{ccccccccccccccccccccccccccccc} 1 & 2& 3& 4& 5& 6& 7& 8& 9& & 10& 11& 12& 13& 14& 15& 16& 17& 18 & &19& 20& 21& 22& 23& 24& 25& 26& 27 \\ 1 & 4& 7& 10& 13& 16& 19& 22& 25& & 2& 5& 8& 11& 14& 17& 20& 23& 26 & & 3& 6& 9& 12& 15& 18& 21& 24& 27 \\ \end{array} \right)\\ =(2,4,10)(3,7,19)(5,13,11)(6,16,20)(8,22,12)(9,25,21)(15,17,23)(18,26,24)\in \mathcal{S}_{27}. \end{multline*} \end{example} \begin{lemma}\label{lem:gamma} Let $s\geq 2$, $u=({\mathbf{0}}, {\mathbf{1}}, \dots, {\mathbf{p-1}})\in \mathbb{Z}_p^{p^{s-1}}$ and $v=(0,1,\dots,p-1)\in\mathbb{Z}_p^p$. Then, \begin{enumerate}[label=(\roman*)] \item $\gamma_s(u)=(v, \stackrel{p^{s-2}}{\dots},v)$, \item $\gamma_s(v, \stackrel{p^{s-2}}{\dots},v)=u$. \end{enumerate} \end{lemma} \begin{proof} Straightforward form the definition of $\gamma_s$. \end{proof} Then, we can define the map $\tau_s:\mathbb{Z}_{p^s}\rightarrow \mathbb{Z}_{p^{s-1}}^p$ as \begin{equation}\label{eq:tau} \tau_s(u)=\Phi_{s-1}^{-1}(\gamma_s^{-1}(\phi_s(u))), \end{equation} where $u\in\mathbb{Z}_{p^s}$. \begin{example} For $p=3$ and $s=3$, we have \footnotesize \begin{equation}\label{eq:equivbase} \left.\begin{array}{cccccccl} \phi_3(0) & = & (0,0,0,0,0,0,0,0,0) & = &\gamma_3(0,0,0,0,0,0,0,0,0) = \gamma_3(\Phi_2(0,0,0))&\\ \phi_3(1) & = & (0,1,2,0,1,2,0,1,2) & = &\gamma_3(0,0,0,1,1,1,2,2,2) = \gamma_3(\Phi_2(0,3,6))&\\ \phi_3(2) & = & (0,2,1,0,2,1,0,2,1) & = &\gamma_3(0,0,0,2,2,2,1,1,1) = \gamma_3(\Phi_2(0,6,3))&\\ \phi_3(3) & = & (0,0,0,1,1,1,2,2,2) & = &\gamma_3(0,1,2,0,1,2,0,1,2) = \gamma_3(\Phi_2(1,1,1))&\\ \phi_3(4) & = & (0,1,2,1,2,0,2,0,1) & = &\gamma_3(0,1,2,1,2,0,2,0,1) = \gamma_3(\Phi_2(1,4,7))&\\ \phi_3(5) & = & (0,2,1,1,0,2,2,1,0) & = &\gamma_3(0,1,2,2,0,1,1,2,0) = \gamma_3(\Phi_2(1,7,4))&\\ \phi_3(6) & = & (0,0,0,2,2,2,1,1,1) & = &\gamma_3(0,2,1,0,2,1,0,2,1) = \gamma_3(\Phi_2(2,2,2))&\\ \phi_3(7) & = & (0,1,2,2,0,1,1,2,0) & = &\gamma_3(0,2,1,1,0,2,2,1,0) = \gamma_3(\Phi_2(2,5,8))&\\ \phi_3(8) & = & (0,2,1,2,1,0,1,0,2) & = &\gamma_3(0,2,1,2,1,0,1,0,2) = \gamma_3(\Phi_2(2,8,5))&\\ \phi_3(9) & = & (1,1,1,1,1,1,1,1,1) & = &\gamma_3(1,1,1,1,1,1,1,1,1) = \gamma_3(\Phi_2(3,3,3))&\\ \phi_3(10) & = & (1,2,0,1,2,0,1,2,0) & = &\gamma_3(1,1,1,2,2,2,0,0,0) = \gamma_3(\Phi_2(3,6,0))&\\ \phi_3(11) & = & (1,0,2,1,0,2,1,0,2) & = &\gamma_3(1,1,1,0,0,0,2,2,2) = \gamma_3(\Phi_2(3,0,6))&\\ \phi_3(12) & = & (1,1,1,2,2,2,0,0,0) & = &\gamma_3(1,2,0,1,2,0,1,2,0) = \gamma_3(\Phi_2(4,4,4))&\\ \phi_3(13) & = & (1,2,0,2,0,1,0,1,2) & = &\gamma_3(1,2,0,2,0,1,0,1,2) = \gamma_3(\Phi_2(4,7,1))&\\ \phi_3(14) & = & (1,0,2,2,1,0,0,2,1) & = &\gamma_3(1,2,0,0,1,2,2,0,1) = \gamma_3(\Phi_2(4,1,7))&\\ \phi_3(15) & = & (1,1,1,0,0,0,2,2,2) & = &\gamma_3(1,0,2,1,0,2,1,0,2) = \gamma_3(\Phi_2(5,5,5))&\\ \phi_3(16) & = & (1,2,0,0,1,2,2,0,1) & = &\gamma_3(1,0,2,2,1,0,0,2,1) = \gamma_3(\Phi_2(5,8,2))&\\ \phi_3(17) & = & (1,0,2,0,2,1,2,1,0) & = &\gamma_3(1,0,2,0,2,1,2,1,0) = \gamma_3(\Phi_2(5,2,8))&\\ \phi_3(18) & = & (2,2,2,2,2,2,2,2,2) & = &\gamma_3(2,2,2,2,2,2,2,2,2) = \gamma_3(\Phi_2(6,6,6))&\\ \phi_3(19) & = & (2,0,1,2,0,1,2,0,1) & = &\gamma_3(2,2,2,0,0,0,1,1,1) = \gamma_3(\Phi_2(6,0,3))&\\ \phi_3(20) & = & (2,1,0,2,1,0,2,1,0) & = &\gamma_3(2,2,2,1,1,1,0,0,0) = \gamma_3(\Phi_2(6,3,0))&\\ \phi_3(21) & = & (2,2,2,0,0,0,1,1,1) & = &\gamma_3(2,0,1,2,0,1,2,0,1) = \gamma_3(\Phi_2(7,7,7))&\\ \phi_3(22) & = & (2,0,1,0,1,2,1,2,0) & = &\gamma_3(2,0,1,0,1,2,1,2,0) = \gamma_3(\Phi_2(7,1,4))&\\ \phi_3(23) & = & (2,1,0,0,2,1,1,0,2) & = &\gamma_3(2,0,1,1,2,0,0,1,2) = \gamma_3(\Phi_2(7,4,1))&\\ \phi_3(24) & = & (2,2,2,1,1,1,0,0,0) & = &\gamma_3(2,1,0,2,1,0,2,1,0) = \gamma_3(\Phi_2(8,8,8))&\\ \phi_3(25) & = & (2,0,1,1,2,0,0,1,2) & = &\gamma_3(2,1,0,0,2,1,1,0,2) = \gamma_3(\Phi_2(8,2,5))&\\ \phi_3(26) & = & (2,1,0,1,0,2,0,2,1) & = &\gamma_3(2,1,0,1,0,2,0,2,1) = \gamma_3(\Phi_2(8,5,2))&\\ \end{array}\right. \end{equation} These equalities define the map $\tau_3: \mathbb{Z}_{27} \rightarrow \mathbb{Z}_9^3$ as \begin{equation*} \left.\begin{array}{cccccccccl} \tau_3(0)=(0,0,0) && \tau_3(9) =(3,3,3) && \tau_3(18) =(6,6,6))\\ \tau_3(1)=(0,3,6) && \tau_3(10) =(3,6,0) && \tau_3(19) =(6,0,3) \\ \tau_3(2) =(0,6,3) && \tau_3(11) =(3,0,6) && \tau_3(20) =(6,3,0) \\ \tau_3(3) =(1,1,1) && \tau_3(12) =(4,4,4) &&\tau_3(21) =(7,7,7) \\ \tau_3(4) =(1,4,7) && \tau_3(13) =(4,7,1) && \tau_3(22) =(7,1,4) \\ \tau_3(5) =(1,7,4) && \tau_3(14) =(4,1,7) && \tau_3(23) =(7,4,1) \\ \tau_3(6) =(2,2,2) && \tau_3(15) =(5,5,5) && \tau_3(24) =(8,8,8) \\ \tau_3(7) =(2,5,8) && \tau_3(16) =(5,8,2) && \tau_3(25) =(8,2,5) \\ \tau_3(8) =(2,8,5) && \tau_3(17) =(5,2,8) && \tau_3(26) =(8,5,2) \\ \end{array}\right. \end{equation*} \end{example} \begin{lemma}\cite{HadamardZps}\label{lem:phi} Let $\lambda \in \mathbb{Z}_p$. Then, $\phi_s(\lambda p^{s-1})= (\lambda, \stackrel{p^{s-1}}{\dots},\lambda)$. \end{lemma} \begin{lemma} \label{lem:tau} Let $s\geq 2$. Then, \begin{enumerate}[label=(\roman*)] \item $\tau_s(1)=(0,p^{s-2},\dots,(p-1)p^{s-2})$, \item $\tau_s(p^iu)=p^{i-1}(u,\stackrel{p}{\dots},u)$ for all $i\in\{1,\dots,s-1\}$ and $u\in\{0,1,\dots,p^{s-1}-1\}$. \end{enumerate} \end{lemma} \begin{proof} First, let $v=(0,1,\dots,p-1)\in\mathbb{Z}_p^p$. Then, \begin{equation*} \begin{split} \tau_s(1) &=\Phi_{s-1}^{-1}(\gamma_s^{-1}(\phi_s(1)))\\ &=\Phi_{s-1}^{-1}(\gamma_s^{-1}(v, \stackrel{p^{s-2}}{\dots},v))\\ &=\Phi_{s-1}^{-1}(\mathbf{0},\mathbf{1},\dots,\mathbf{p-1}), \textrm {by Lemma \ref{lem:gamma}}. \end{split} \end{equation*} Therefore by Lemma \ref{lem:phi}, $\tau_s(1)=(0,p^{s-2},\dots,(p-1)p^{s-2})$, and $(i)$ holds. In order to prove $(ii)$, let $u\in\mathbb{Z}_{p^s}$ and $[u_0,\dots,u_{s-1}]_p$ be its p-ary expansion. The p-ary expansion of $p^{i}u$ is $[0,\stackrel{i}{\dots},0,u_0,\dots,u_{s-i-1}]_p$ and we have that $\phi_s(p^{i}u)=(u_{s-i-1},\dots,u_{s-i-1})+(0,\dots,0,u_0,\dots,u_{s-i-2})Y_{s-1}$. Recall that the matrix $Y_{s-1}$ given in (\ref{genGraymap}), related to the definition of $\phi_s$, is a matrix of size $(s-1)\times p^{s-1}$ whose columns are the elements of $\mathbb{Z}_p^{s-1}$. Without loss of generality, we consider that $Y_{s}$ is the matrix obtained recursively from $Y_{1}=(0~1~\cdots~p-1)$ and \begin{equation}\label{eq:RecursiveYs} Y_{s}=\left(\begin{array}{cccc} Y_{s-1} & Y_{s-1} &\cdots & Y_{s-1} \\ {\mathbf{0}} & {\mathbf{1}} & \cdots & \mathbf{p-1}\\ \end{array}\right). \end{equation} By Lemma \ref{lem:gamma}, we can write \begin{equation} \gamma_s^{-1}(Y_{s-1})=\left(\begin{array}{cccc} {\mathbf{0}} & {\mathbf{1}} &\cdots & \mathbf{p-1}\\ Y_{s-2} & Y_{s-2} &\cdots &Y_{s-2} \\ \end{array}\right). \end{equation} Then, we have that \begin{equation*} \begin{split} &\gamma_s^{-1}(\phi_s(p^{i}u))\\ &=(u_{s-i-1},\stackrel{p^{s-1}}{\dots},u_{s-i-1})+(0,\stackrel{i}{\dots},0,u_0,\dots,u_{s-i-2})\left(\begin{array}{cccc} {\mathbf{0}} & {\mathbf{1}} &\cdots & \mathbf{p-1}\\ Y_{s-2} & Y_{s-2} &\cdots &Y_{s-2} \\ \end{array}\right)\\ &=(u_{s-i-1},\stackrel{p^{s-1}}{\dots},u_{s-i-1})+(0,\stackrel{i-1}{\dots},0,u_0,\dots,u_{s-i-2})\left(\begin{array}{cccc}Y_{s-2} & Y_{s-2} &\cdots &Y_{s-2} \\\end{array}\right)\\ &=(\phi_{s-1}(p^{i-1}u),\phi_{s-1}(p^{i-1}u),\dots,\phi_{s-1}(p^{i-1}u))=\Phi_{s-1}(p^{i-1}(u,\stackrel{p}{\dots},u)). \end{split} \end{equation*} Therefore, $\tau_s(p^{i}u)=\Phi_{s-1}^{-1}(\gamma_s^{-1}(\phi_s(p^{i}u)))=p^{i-1}(u,\stackrel{p}{\dots},u)$, and $(ii)$ holds. \end{proof} \begin{proposition}\label{prop:formulaPhis} Let $s\geq2$ and $\lambda_i\in \{0,1,\dots,p-1\}$, $i\in\{0,\dots,s-1\}$. Then, \begin{equation}\label{eq:sumPhi8} \phi_s(\sum_{i=0}^{s-1} \lambda_ip^i)=\gamma_s(\Phi_{s-1}(\sum_{i=0}^{s-1}\tau_s(\lambda_ip^i))). \end{equation} \end{proposition} \begin{proof} By Lemma \ref{lem:tau}, we know that for all $i\in\{1,\dots,s-1\}$, $\tau_s(p^i)=(p^{i-1},p^{i-1}, \dots, p^{i-1})$ and $\tau_s(1)=(0,p^{s-2},\dots,(p-1)p^{s-2})$. Then, by Lemma \ref{lema4}, we have that \begin{equation*} \gamma_s(\Phi_{s-1}(\sum_{i=0}^{s-1}\tau_s(\lambda_ip^i)))= \gamma_s(\sum_{i=0}^{s-1}\Phi_{s-1}(\tau_s(\lambda_ip^i))). \end{equation*} Moreover, $\gamma_s$ commutes with the addition. Therefore, by applying the definition of the map $\tau_s$ given in (\ref{eq:tau}), we obtain that $$ \gamma_s(\Phi_{s-1}(\sum_{i=0}^{s-1}\tau_s(\lambda_ip^i)))= \sum_{i=0}^{s-1}\gamma_s(\Phi_{s-1}(\tau_s(\lambda_ip^i)))= \sum_{i=0}^{s-1}\phi_s(\lambda_ip^i), $$ which is equal to $\phi_s(\sum_{i=0}^{s-1} \lambda_ip^i)$ by Lemma \ref{lema4}. \end{proof} \begin{corollary}\label{coro:formulaPhis} Let $s\geq2$ and $\lambda_i\in\{0,1,\dots,p-1\}$, $i\in\{0,\dots,s-1\}$. Then, \begin{equation} \tau_{s}(\sum_{i=0}^{s-1} \lambda_ip^i)=\sum_{i=0}^{s-1}\tau_s(\lambda_ip^i). \end{equation} \end{corollary} \begin{proof} By Proposition \ref{prop:formulaPhis}, we have that \[ \phi_s(\sum_{i=0}^{s-1} \lambda_ip^i)=\gamma_s(\Phi_{s-1}(\sum_{i=0}^{s-1}\tau_s(\lambda_ip^i))), \] \noindent and, therefore, \[ \Phi_{s-1}^{-1}(\gamma_s^{-1}(\phi_s(\sum_{i=0}^{s-1} \lambda_ip^i)))=\sum_{i=0}^{s-1}\tau_s(\lambda_ip^i),\\ \] \noindent that is, $\tau_s(\sum_{i=0}^{s-1} \lambda_i2^i)=\sum_{i=0}^{s-1}\tau_s(\lambda_ip^i)$. \end{proof} Now, we extend the permutation $\gamma_s\in\mathcal{S}_{p^{s-1}}$ to a permutation $\gamma_s\in\mathcal{S}_{p^{s-1}n}$ such that restricted to each set of $p^{s-1}$ coordinates $\{p^{s-1}i+1,p^{s-1}i+2,\dots,$ $p^{s-1}(i+1)\}$, $i \in\{0,\dots,n-1\}$, acts as $\gamma_s \in \mathcal{S}_{p^{s-1}}$. Then, we component-wise extend function $\tau_s$ defined in (\ref{eq:tau}) to $\tau_s:\mathbb{Z}_{p^s}^n\rightarrow \mathbb{Z}_{p^{s-1}}^{pn}$ and define $\tilde{\tau}_s=\rho^{-1}\circ \tau_s$, where $\rho \in{\cal S}_{pn}$ is defined as follows: for a coordinate $k=jp+i+1 \in \{1,2,\dots, pn\}$, where $i,j \in \{0,\dots, n-1\}$, $\rho$ moves coordinate $k$ to coordinate $ip+j+1$. So, we can write $\rho$ as \begin{equation*} \footnotesize \left( \begin{array}{ccccccccccccc} 1 & 2& \ldots &n & n+1 & n+2 &\ldots & 2n & \ldots & pn-p+1 &pn-p+2 &\ldots &pn \\ 1 & p+1& \ldots &(n-1)p+1 &2 & p+2 & \ldots & (n-1)p+2 &\ldots & p &p+p & \ldots &pn\\ \end{array} \right). \end{equation*} \begin{example} For $p=3$ and $n=2$, \begin{equation*} \rho=\left( \begin{array}{ccccccccccc} 1 & 2& &3 & 4& &5& 6 \\ 1 & 4& &2 & 5& &3& 6 \\ \end{array} \right) \in \mathcal{S}_6. \end{equation*} and for $p=3$ and $n=4$, \begin{equation*} \rho=\left( \begin{array}{ccccccccccccccccccccccccccccc} 1 &2 &3 &4 & &5 &6 &7 &8 & &9 &10 &11 &12\\ 1 &4 &7 &10 & &2 &5 &8 &11 & &3 &6 &9 &12\\ \end{array} \right)\in \mathcal{S}_{12}. \end{equation*} \end{example} \begin{remark} If $\mathbf{u}=(u_1,u_2,\dots,u_n)\in \mathbb{Z}_{p^s}^n$ and $\tau_s(u_i)=(u_{i,1},u_{i,2},\dots,u_{i,p})$ for all $i \in \{1,\ldots,n\}$, then $$\tau_s(\mathbf{u})=(u_{1,1},u_{1,2},\dots,u_{1,p},u_{2,1},u_{2,2},\dots,u_{2,p},\dots,u_{n,1},u_{n,2},\dots,u_{n,p}),$$ and $$\tilde{\tau}_s(\mathbf{u})=(u_{1,1},u_{2,1}\dots,u_{n,1},u_{1,2},u_{2,2}\dots,u_{n,2},\dots, u_{1,p},\\u_{2,p},\dots,u_{n,p}).$$ \end{remark} \begin{lemma} Let $s\geq 2$. Then, $\Phi_s(\mathbf{u})=\gamma_s(\Phi_{s-1}(\rho( \tilde{\tau}_s(\mathbf{u}) )))$ for all $\mathbf{u}\in \mathbb{Z}_{p^s}^n$. \end{lemma} \begin{proof} It follows from $\tilde{\tau}_s(\mathbf{u})=\rho^{-1}(\tau_s(\mathbf{u}))=\rho^{-1}(\Phi_{s-1}^{-1}(\gamma_s^{-1}(\Phi_s(\mathbf{u}))))$. \end{proof} Let $\mathbf{w}_i^{(s)}$ be the $i$th row of $A^{t_1,\ldots,t_s}$, $1\leq i\leq t_1+\cdots+t_s$. By construction, $\mathbf{w}_1^{(s)}={\mathbf{1}}$ and $\operatorname{ord}(\mathbf{w}_i^{(s)})\leq \operatorname{ord}(\mathbf{w}_j^{(s)})$ if $i>j$. Let $\sigma_i$ be the integer such that $\operatorname{ord}(\mathbf{w}_i^{(s)} )=p^{\sigma_i}$. Then, $\mathcal{B}^{t_1,\dots,t_s}=\{ p^{q_i}\mathbf{w}_i^{(s)} : 1\leq i\leq t_1+\cdots+t_s,\, 0\leq q_i\leq \sigma_i-1 \}$ is a $p$-basis of $\mathcal{H}^{t_1,\ldots,t_s}$. \begin{lemma}\label{lem:WsWs1} Let $t_s\geq1$. Let $\mathbf{w}_i^{(s)}$ and $\mathbf{w}_i^{(s+1)}$ be the $i$th row of $A^{t_1,\ldots,t_s}$ and $A^{1,t_1-1,t_2,\ldots,t_{s-1},t_s-1}$, respectively. Then, $(\mathbf{w}_i^{(s+1)},\mathbf{w}_i^{(s+1)},\dots,\mathbf{w}_i^{(s+1)})=p\mathbf{w}_i^{(s)}$ and $\operatorname{ord}(\mathbf{w}_i^{(s)})=\operatorname{ord}(\mathbf{w}_i^{(s+1)})=p^{\sigma_i}$. \end{lemma} \begin{proof} Consider $A^{t_1,\dots,t_s}$ with $t_s\geq1$, and $\mathbf{w}_i^{(s)}$ its $i$th row for $i\in\{1,\dots,t_1+\cdots+t_s\}$. Then, the matrix over $\mathbb{Z}_{p^{s+1}}$ $$ \left(\begin{array}{c} \mathbf{w}_1^{(s)}\\ p\mathbf{w}_2^{(s)}\\ \vdots\\ p\mathbf{w}_{t_1+\cdots+t_s}^{(s)}\\ \end{array}\right) $$ is, by definition, $A^{1,t_1-1,t_2,\dots,t_{s-1},t_s}$. Moreover, by construction we have that $A^{1,t_1-1,t_2,\dots,t_{s-1},t_s}$ is the matrix $$ \left(\begin{array}{cccc} A^{1,t_1-1,t_2,\dots,t_{s-1},t_s-1} & A^{1,t_1-1,t_2,\dots,t_{s-1},t_s-1}&\cdots &A^{1,t_1-1,t_2,\dots,t_{s-1},t_s-1}\\ p^s\cdot {\mathbf{0}} & p^s\cdot\mathbf{1} &\cdots &p^s \cdot \mathbf{(p-1)}\\ \end{array}\right). $$ Therefore, if $\mathbf{w}_i^{(s+1)}$ is the $i$th row of $A^{1,t_1-1,t_2,\dots,t_{s-1},t_s-1}$ for $i\in\{2,\dots,t_1+t_2+\dots+t_s-1\}$, we have that $(\mathbf{w}_i^{(s+1)},\mathbf{w}_i^{(s+1)},\dots,\mathbf{w}_i^{(s+1)})=p\mathbf{w}_i^{(s)}$ and $\operatorname{ord}(\mathbf{w}_i^{(s)})=\operatorname{ord}(\mathbf{w}_i^{(s+1)})=p^{\sigma_i}$. \end{proof} \begin{example} \label{ex:2bases} Let ${\mathcal H}^{2,1}$ and ${\mathcal H}^{1,1,0}$ be the $\mathbb{Z}_9$-additive and $\mathbb{Z}_{27}$-additive GH codes, which are generated by $$ \footnotesize A^{2,1}=\left(\begin{array}{c} \mathbf{w}_1^{(2)}\\ \mathbf{w}_2^{(2)}\\ \mathbf{w}_3^{(2)} \end{array}\right) =\left(\begin{array}{ccc} {\mathbf{1}} & {\mathbf{1}} & {\mathbf{1}}\\ v & v & v \\ {\mathbf{0}} & \mathbf{3} & \mathbf{9} \end{array}\right), $$ where $v=(0,1,2,3,4,5,6,7,8)$, and $$ A^{1,1,0}=\left(\begin{array}{c} \mathbf{w}_1^{(3)}\\ \mathbf{w}_2^{(3)} \end{array}\right) =\left(\begin{array}{ccccccccc} 1&1&1&1&1&1&1&1&1 \\ 0&3&6&9&12&15&18&21&24 \\ \end{array}\right), $$ respectively. The corresponding $3$-bases are \begin{align*} \mathcal{B}^{2,1}=\{&\mathbf{w}_1^{(2)},3\mathbf{w}_1^{(2)},\mathbf{w}_2^{(2)},3\mathbf{w}_2^{(2)},\mathbf{w}_3^{(2)}\} \\ =\{&\mathbf{1},\mathbf{3},(0,1,2,3,4,5,6,7,8,\stackrel{3}{\dots},0,1,2,3,4,5,6,7,8),\\ &(0,3,6,9,12,15,18,21,24,\stackrel{3}{\dots},0,3,6,9,12,15,18,21,24)\},~ \mbox{and} \\ \mathcal{B}^{1,1,0}=\{&\mathbf{w}_1^{(3)},3\mathbf{w}_1^{(3)},3^2\mathbf{w}_1^{(3)},\mathbf{w}_2^{(3)},3\mathbf{w}_2^{(3)} \}\\ =\{&\mathbf{1},\mathbf{3},\mathbf{9},(0,3,6,9,12,15,18,21,24),(0,9,18,0,9,18,0,9,18)\}.\\ \end{align*} \end{example} \begin{proposition} \label{prop:basis} Let $t_s\geq1$, and $\mathcal{H}^{t_1,\ldots,t_s}$ and $\mathcal{H}^{1,t_1-1,t_2,\ldots,t_{s-1},t_s-1}$ be the $\mathbb{Z}_{p^s}$-additive and $\mathbb{Z}_{p^{s+1}}$-additive GH codes with generator matrices $A^{t_1,\ldots,t_s}$ and $A^{1,t_1-1,t_2,\ldots,t_{s-1},t_s-1}$, respectively. Let $\mathbf{w}_i^{(s)}$ and $\mathbf{w}_i^{(s+1)}$ be the $i$th row of $A^{t_1,\ldots,t_s}$ and $A^{1,t_1-1,t_2,\ldots,t_{s-1},t_s-1}$, respectively. Then, we have that \begin{enumerate}[label=(\roman*)] \item $\tilde{\tau}_{s+1}(p^{q_i}\mathbf{w}^{(s+1)}_i)=p^{q_i}\mathbf{w}^{(s)}_i$, for all $i \in \{2,\dots,t_1+\cdots+t_s-1\}$ and $q_i\in\{0,\dots,\sigma_i-1\}$, where $\operatorname{ord}(\mathbf{w}_i^{(s)})=p^{\sigma_i}$; \item $\tilde{\tau}_{s+1}(p^{j+1}\mathbf{w}^{(s+1)}_1)=p^{j}\mathbf{w}^{(s)}_1$, for all $j\in\{0,\dots,s-1\}$; \item $\tilde{\tau}_{s+1}(\mathbf{w}_1^{(s+1)})=\mathbf{w}^{(s)}_{t_1+\cdots +t_{s}}.$ \end{enumerate} \end{proposition} \begin{proof} By Lemma \ref{lem:WsWs1}, we have that $(\mathbf{w}_i^{(s+1)},\mathbf{w}_i^{(s+1)},\dots,\mathbf{w}_i^{(s+1)})=p\mathbf{w}_i^{(s)}$ and $\operatorname{ord}(\mathbf{w}_i^{(s)})=\operatorname{ord}(\mathbf{w}_i^{(s+1)})=p^{\sigma_i}$. Let $\mathbf{v}_i^{(s+1)}$ be the vector over $\mathbb{Z}_{p^{s+1}}$ such that $\mathbf{w}_i^{(s+1)}=p\mathbf{v}_i^{(s+1)}$ and $\mathbf{w}_i^{(s)}=(\mathbf{v}_i^{(s+1)},\mathbf{v}_i^{(s+1)},\dots,\mathbf{v}_i^{(s+1)})$. Let $(\mathbf{v}_i^{(s+1)})_j$ be the $j$th coordinate of $\mathbf{v}_i^{(s+1)}$. By the definition of $\tilde{\tau}_{s+1}$ and Lemma \ref{lem:tau}, for $q_i\in\{0,\dots,\sigma_i-1\}$, we have that \begin{equation*} \begin{split} &\tilde{\tau}_{s+1}(p^{q_i}\mathbf{w}^{(s+1)}_i)=\rho^{-1}(\tau_{s+1}(p^{q_i}\mathbf{w}^{(s+1)}_i))=\rho^{-1}(\tau_{s+1}(p^{q_i+1}\mathbf{v}_i^{(s+1)}))\\ &=\rho^{-1}(p^{q_i}((\mathbf{v}_i^{(s+1)})_1,\dots,(\mathbf{v}_i^{(s+1)})_1,\dots,(\mathbf{v}_i^{(s+1)})_n,\dots,(\mathbf{v}_i^{(s+1)})_n))\\ &=p^{q_i}(\mathbf{v}_i^{(s+1)},\mathbf{v}_i^{(s+1)},\dots,\mathbf{v}_i^{(s+1)})=p^{q_i}\mathbf{w}_i^{(s)}, \end{split} \end{equation*} and $(i)$ holds. Since $\mathbf{w}_1^{(s)}=(\mathbf{w}_1^{(s+1)},\dots,\mathbf{w}_1^{(s+1)})={\mathbf{1}}$ and $\mathbf{w}_{t_1+\cdots+t_s}^{(s)}=(p^{s-1} \cdot {\mathbf{0}},p^{s-1} \cdot \mathbf{1},\dots,p^{s-1}\cdot \mathbf{(p-1)})$, then the equalities in items $(ii)$ and $(iii)$ hold by the definition of $\tilde{\tau}_{s+1}$ and Lemma \ref{lem:tau}. \end{proof} Note that, from the previous proposition, we have that $\tilde{\tau}_{s+1}$ is a bijection between the $p$-bases, $\mathcal{B}^{t_1,\dots,t_s}$ and $\mathcal{B}^{1,t_1-1,\dots,t_{s-1},t_s-1}$. \begin{example} Let ${\mathcal H}^{2,1}$ and ${\mathcal H}^{1,1,0}$ be the same codes considered in Example \ref{ex:2bases}. The length of ${\mathcal H}^{1,1,0}$ is $n=9$. Then, the extension of $\gamma_3= (2,4)(3,7)(6,8)$ $ \in {\cal S}_9$ is $\gamma_3=(2,4)(3,7)(6,8)(11,13)(12,16)(15,17)(20,22)\\(21,25)(24,26)(29,31)(30,34)(33,35)(38,40)(39,43)(42,44)(47,49)(48,52)\\(51,53)(56,58)(57,61)(60,62)(65,67)(66,70)(69,71)(74,76)(75,79)(78,80)\in {\cal S}_{81}$, and \begin{equation} \tiny \rho=\left( \begin{array}{cccccccccccccccccccccccccccccc} 1 & 2& 3 & 4 & 5 & 6 & 7 & 8 &9 &10 &11 &12 &13 &14 &15 &16 &17 &18 &19 &20 &21 &22 &23 &24 &25 &26 &27 \\ 1 &4 &7 &10 &13 &16 &19 &22 &25 &2 &5 &8 &11 &14 &17 &20 &23 &26 &3 &6 &9 &12 &15 &18 &21 &24 &27 \\ \end{array} \right) \in {\cal S}_{27}. \end{equation} In this case, we have that $$ \footnotesize \arraycolsep=1pt\def{} \begin{array}{lccclcc} \Phi_3(1,1,1,1,1,1,1,1,1)&=&\gamma_3(\Phi_2(0,3,6, \stackrel{9}{\dots},0,3,6))&=&\gamma_3(\Phi_2(\rho(\mathbf{0},\mathbf{3},\mathbf{6}))), \\ \Phi_3(3,3,3,3,3,3,3,3,3)&=&\gamma_3(\Phi_2(1,1,1,\stackrel{9}{\dots},1,1,1))&=&\gamma_3(\Phi_2(\rho(1,1,1,\stackrel{9}{\dots},1,1,1))), \\ \Phi_3(9,9,9,9,9,9,9,9,9)&=&\gamma_3(\Phi_2(3,3,3,\stackrel{9}{\dots},3,3,3))&=&\gamma_3(\Phi_2(\rho(3,3,3,\stackrel{9}{\dots},3,3,3))), \\ \Phi_3(0,3,6,9,12,15,18,21,24)&=&\gamma_3(\Phi_2(0,0,0,1,1,1,\dots,8,8,8))&=&\gamma_3(\Phi_2(\rho(u,\stackrel{3}{\dots},u)), \\ \Phi_3(0,9,18,0,9,18,0,9,18)&=&\gamma_3(\Phi_2(v, \stackrel{3}{\dots}, v))&=&\gamma_3(\Phi_2(\rho(0,3,6, \stackrel{9}{\dots},0,3,6))), \end{array} $$ where $u=(0,1,2,3,4,5,6,7,8)$ and $v=(0,0,0,3,3,3,6,6,6).$ Since $\Phi_3(\mathbf{u})=\gamma_3(\Phi_{2}(\rho( \tilde{\tau}_3(\mathbf{u}) )))$ for all $\mathbf{u}\in \mathbb{Z}_{27}^9$, the map $\tilde{\tau}_3$ sends the elements of the $3$-basis $\mathcal{B}^{1,1,0}$ into the elements of the $3$-basis $\mathcal{B}^{2,1}$. That is, as it is shown in Proposition~\ref{prop:basis}, \begin{equation*} \arraycolsep=1pt\def{} \begin{array}{lcccccl} \tilde{\tau}_3(\mathbf{w}_1^{(3)}) & = & \tilde{\tau}_3(1,1,1,1,1,1,1,1,1) & = & (\mathbf{0},\mathbf{3},\mathbf{6}) & = & \mathbf{w}_3^{(2)},\\ \tilde{\tau}_3(3\mathbf{w}_1^{(3)}) & = & \tilde{\tau}_3(3,3,3,3,3,3,3,3,3) & = & (1,1,1,\stackrel{9}{\dots},1,1,1) & = & \mathbf{w}_1^{(2)},\\ \tilde{\tau}_3(9\mathbf{w}_1^{(3)}) & = & \tilde{\tau}_3(9,9,9,9,9,9,9,9,9) & = & (3,3,3,\stackrel{9}{\dots},3,3,3) & = & 3\mathbf{w}_1^{(2)},\\ \tilde{\tau}_3(\mathbf{w}_2^{(3)}) & = & \tilde{\tau}_3(0,3,6,9,12,15,18,21,24) & = & (u,\stackrel{3}{\dots}, u) & = & \mathbf{w}_2^{(2)},\\ \tilde{\tau}_3(3\mathbf{w}_2^{(3)}) & = & \tilde{\tau}_3(0,9,18,0,9,18,0,9,18) & = & (0,3,6,\stackrel{9}{\dots},0,3,6) & = & 3\mathbf{w}_2^{(2)},\\ \end{array} \end{equation*} so $\tilde{\tau}_3$ is a bijection between both $3$-bases. \end{example} \begin{lemma}\label{lemma:basisEquivcodes} Let $\mathcal{H}_s=\mathcal{H}^{t_1,\ldots,t_s}$ be a $\mathbb{Z}_{p^s}$-additive GH code with $t_s\geq1$, and $\mathcal{H}_{s+1}=\mathcal{H}^{1,t_1-1,t_2,\ldots,t_{s-1},t_s-1}$ be a $\mathbb{Z}_{p^{s+1}}$-additive GH code. Then, $H_s=\Phi_s(\mathcal{H}_s)$ is permutation equivalent to $H_{s+1}=\Phi_{s+1}(\mathcal{H}_{s+1})$. \end{lemma} \begin{proof} Let $t$ be the integer such that $H_s$ and $H_{s+1}$ are of length $p^t$. Let $\mathcal{B}_s=\{\mathbf{v}_1^{(s)},\dots,\mathbf{v}_{t+1}^{(s)}\}$ and $\mathcal{B}_{s+1}=\{\mathbf{v}_1^{(s+1)},\dots,\mathbf{v}_{t+1}^{(s+1)}\}$ be the $p$-basis of $\mathcal{H}_s$ and $\mathcal{H}_{s+1}$, respectively. By Proposition \ref{prop:basis}, $\tilde{\tau}_{s+1}$ is a bijection between $\mathcal{B}_s$ and $\mathcal{B}_{s+1}$. By the definition of $\tilde{\tau}_{s+1}$ and Corollary \ref{coro:formulaPhis}, we have that $\tilde{\tau}_{s+1}$ commutes with the addition, so $\tilde{\tau}_{s+1}(\mathcal{H}_{s+1})=\mathcal{H}_{s}$. Let $\rho_*\in\mathcal{S}_{p^t}$ be a permutation such that $\Phi_s(\rho(\mathbf{u}))=\rho_*(\Phi_s(\mathbf{u}))$ for all $\mathbf{u}\in\mathcal{H}_{s}$. Since $\mathcal{H}_s=\tilde{\tau}_{s+1}(\mathcal{H}_{s+1})=\rho^{-1}(\Phi_{s}^{-1}(\gamma^{-1}_{s+1}(\Phi_{s+1}(\mathcal{H}_{s+1}))))$, we have that $\Phi_{s}(\mathcal{H}_s)=\rho_*^{-1}(\gamma^{-1}_{s+1}(\Phi_{s+1}(\mathcal{H}_{s+1})))$. Therefore, we obtain $H_s=(\gamma_{s+1}\circ\rho_*)^{-1}(H_{s+1})$, where $\gamma_{s+1}\circ\rho_*\in\mathcal{S}_{p^t}$. \end{proof} The following theorem determines which $\mathbb{Z}_{p^{s'}}$-linear GH codes are equivalent to a given $\mathbb{Z}_{p^s}$-linear Hadamard code $H^{t_1,\dots,t_s}$. We denote by ${\mathbf{0}}^j$ the all-zero vector of length $j$. Let $\sigma$ be the integer such that $\operatorname{ord}(\mathbf{w}_2^{(s)})=p^{s+1-\sigma}$. Note that $\sigma =1$ if and only if $t_1\geq 2$. Moreover, since $\sigma_2$ is the integer such that $\operatorname{ord}(\mathbf{w}_2^{(s)})=p^{\sigma_2}$, we have that $\sigma=s+1-\sigma_2$. \begin{theorem}\label{theo:equi} Let $H^{t_1,\dots,t_s}$ be a $\mathbb{Z}_{2^s}$-linear GH code with $t_s\geq 1$. Then, $H^{t_1,\dots,t_s}$ is equivalent to the $\mathbb{Z}_{p^{s+\ell}}$-linear Hadamard code $H^{1,{\mathbf{0}}^{\ell-1},t_1-1,t_2,\dots,t_{s-1},t_s-\ell}$, for all $\ell\in\{1,\dots,t_s\}$. \end{theorem} \begin{proof} Consider $\mathcal{H}_0=\mathcal{H}^{t_1,\dots,t_s}$ and $\mathcal{H}_\ell=\mathcal{H}^{1,{\mathbf{0}}^{\ell-1},t_1-1,t_2,\dots,t_{s-1},t_s-\ell}$ for $\ell\in\{1,\dots,t_s\}$. By Lemma \ref{lemma:basisEquivcodes}, we have that $H_i=\Phi(\mathcal{H}_i)$ is permutation equivalent to $H_{i+1}=\Phi(\mathcal{H}_{i+1})$ for all $i\in\{0,\dots,\ell-1\}$ and $\ell\in\{1,\dots,t_s\}$. Therefore, we have that $H_0$ and $H_{\ell}$ are permutation equivalent for all $\ell\in\{1,\dots,t_s\}$. \end{proof} \medskip Let $t_1, t_2,\dots,t_s$ be nonnegative integers with $t_1\geq 2$. Let $C_H(t_1,\dots,t_s)=[H_1=H^{t_1,\dots,t_s},H_2,\dots, H_{t_s+1}]$ be the sequence of all $\mathbb{Z}_{p^{s'}}$-linear GH codes of length $p^t$, where $t=$ $\left(\sum_{i=1}^{s'}(s'-i+1)\cdot t_i\right)-1$, that are permutation equivalent to $H^{t_1,\dots,t_s}$ by Theorem \ref{theo:equi}. We denote by $C_H(t_1,\dots,t_s)[i]$ the $i$th code $H_i$ in the sequence, for $1\leq i\leq t_s+1$. We consider that the order of the codes in $C_H(t_1,\dots,t_s)$ is the following: \begin{equation}\label{eq:defCH} C_H(t_1,\dots,t_s)[i]= \begin{cases} H^{t_1,\dots,t_{s}},& \text{if } i= 1,\\ H^{1,{\mathbf{0}}^{i-2},t_1-1,t_2,\dots,t_{s-1},t_s-i+1}, & \text{otherwise.} \end{cases} \end{equation} We refer to $C_H(t_1,\dots,t_s)$ as the {\it chain of equivalences} of $H^{t_1,\dots,t_s}$. Note that if $t_s=0$, then $C_H(t_1,\dots,t_s)=[H^{t_1,\dots,t_s}]$. \begin{corollary}\label{lemma:CH} Let $t_1, t_2,\dots,t_s$ be nonnegative integers with $t_1\geq 2$. Then, $$|C_H(t_1,\dots,t_s)|=t_s+1.$$ \end{corollary} \begin{example}\label{examples:chain1} Let $p=3$. Then the chain of equivalences of $H^{3,3}$ is the sequence $C_H(3,3)=[H^{3,3}, H^{1,2,2}, H^{1,0,2,1}, H^{1,0,0,2,0}]$ and contains exactly $t_2+1=4$ codes. Note that this sequence contains all the codes of length $3^8$ having the pair $(r,k)=(14,6)$ in Table \ref{table:TypesB2}. In the table \ref{table:Types}, we can see that there is only one code of length $3^7$ having the pair $(r,k)=(25,3)$, named $H^{2,1,0}$. The chain of equivalences of this code is $C_H(2,1,0)=[H^{2,1,0}]$, which contains just this code, since $t_3+1=1$. \end{example} \begin{proposition}\label{lemma:pos-i-in-CH} Let $t_1,t_2,\dots,t_s$ be nonnegative integers with $t_1\geq 2$. Then, the $\mathbb{Z}_{p^{s'}}$-linear Hadamard code $H^{t'_1,\dots,t'_{s'}}= C_H(t_1,\dots,t_s)[i]$, $1\leq i\leq t_s+1$, satisfies \begin{enumerate}[label=(\roman*)] \item $s'=s+i-1$, \item $\sigma'=i$, \item $t'_{s'}=t_s-i+1$, \item $ (t'_1,\dots,t'_{s'})= \begin{cases} (t_1,\dots,t_{s}),& \text{if } i= 1,\\ (1,{\mathbf{0}}^{i-2},t_1-1,t_2,\dots,t_{s-1},t_s-i+1), & \text{otherwise.} \end{cases} $ \end{enumerate} \end{proposition} \begin{proof} Straightforward from Theorem \ref{theo:equi} and the definition of the chain of equivalences $C_H(t_1,\dots,t_s)$. \end{proof} Note that the value of $s'$ is different for every code $H^{t'_1,\dots,t'_{s'}}$ belonging to the same chain of equivalences $C_H(t_1,\dots,t_s)$. \begin{corollary}\label{coro:One-ts0} Let $t_1, t_2,\dots,t_s$ be nonnegative integers with $t_1\geq 2$. \begin{enumerate}[label=(\roman*)] \item The $\mathbb{Z}_{p^{s'}}$-linear Hadamard code $H^{t'_1,\dots,t'_{s'}}= C_H(t_1,\dots,t_s)[1]$ is the only one in $C_H(t_1,\dots,t_s)$ with $\sigma'=1$, that is, the only one with $t'_1\geq 2$. \item The $\mathbb{Z}_{p^{s'}}$-linear Hadamard code $H^{t'_1,\dots,t'_{s'}}= C_H(t_1,\dots,t_s)[t_s+1]$ is the only one in $C_H(t_1,\dots,t_s)$ with $t'_{s'}=0$. \end{enumerate} \end{corollary} Now, given any $\mathbb{Z}_{p^s}$-linear Hadamard code $H^{t_1,\dots,t_s}$, we determine the chain of equivalences containing this code, as well as its position in the sequence. Therefore, note that indeed we prove that any code $H^{t_1,\dots,t_s}$ (with $t_1\geq 1$) belongs to a unique chain of equivalences $C_H(t'_1,\dots,t'_{s'})$ with $t'_1 \geq 2$. \begin{proposition}\label{lemma:codeInChain} Let $t_1, t_2,\dots,t_s$ be nonnegative integers with $t_1\geq 1$. The $\mathbb{Z}_{p^{s}}$-linear Hadamard code $H^{t_1,\dots,t_{s}}$ belongs to an unique chain of equivalences. If $t_1\geq 2$, then $\sigma=1$ and $H^{t_1,\dots,t_s}=C_H(t_1,\dots,t_s)[1]$. Otherwise, if $t_1=1$, then $\sigma >1$ and $H^{t_1,\dots,t_s}=C_H(t'_1,\dots,t'_{s'})[\sigma]$, where $(t'_1,\dots,t'_{s'})= (t_\sigma+1,t_{\sigma+1},\dots,t_{s-1},t_s+\sigma-1)$ and $s'=s-\sigma+1$. \end{proposition} \begin{proof} If $t_1\geq 2$, it is clear by the definition of chain of equivalences and Corollary \ref{coro:One-ts0}. If $t_1=1$, then $\sigma >1$. By Proposition \ref{lemma:pos-i-in-CH}, since $H^{t_1,\dots,t_s}=C_H(t'_1,\dots,t'_{s'})[\sigma]$, we have that $(t_1,\dots,t_s)=(1,{\mathbf{0}}^{\sigma-2},t'_1-1, t'_2, \ldots,t'_{s'-1}, t'_{s'}-\sigma+1)$. Therefore, $t_\sigma=t'_1-1$, $t_{\sigma+1}=t'_2$, $\ldots$, $t_{s-1}=t'_{s'-1}$, $t_s=t'_{s'}-\sigma+1$, and the result follows. \end{proof} \begin{corollary}\label{coro:count-CH} Let $H^{t_1,\dots,t_{s}}$ be a $\mathbb{Z}_{p^{s}}$-linear Hadamard code and $C_H(t'_1,\dots,t'_{s'})$ the chain of equivalences such that $H^{t_1,\dots,t_{s}}=C_H(t'_1,\dots,t'_{s'})[\sigma]$. Then, $$ |C_H(t'_1,\dots,t'_{s'})|=t_s+\sigma.$$ \end{corollary} \begin{proof} If $t_1\geq 2$, then $H^{t_1,\dots,t_s}=C_H(t_1,\dots,t_{s})[1]$ by Proposition \ref{lemma:codeInChain}. By Corollary \ref{lemma:CH}, $|C_H(t_1,\dots,t_{s})|=t_s+1=t_s+\sigma$. Otherwise, if $t_1=1$, then $H^{t_1,\dots,t_s}=C_H(t_\sigma+1,t_{\sigma+1},\dots,$ $t_{s-1},t_s+\sigma-1)[\sigma]$ by Proposition \ref{lemma:codeInChain}. Finally, $|C_H(t_\sigma+1,t_{\sigma+1},\dots,$ $t_{s-1},t_s+\sigma-1)|=t_s+\sigma-1+1=t_s+\sigma$ by Corollary \ref{lemma:CH}. \end{proof} \begin{example}\label{examples:chainpos} The $\mathbb{Z}_{3^4}$-linear GH code $H^{1,0,2,1}$ has $t_1=1$, $\sigma=3$ and $s=4$. By Proposition \ref{lemma:codeInChain}, since $\sigma=3$ and $s'=s-\sigma+1=2$, this code is placed in the third position of the chain of equivalences $C_H(t'_1,t'_2)$, where $t'_1=t_3+1=2+1=3$ and $t'_2=t_4+\sigma-1=1+3-1=3$. Therefore, $H^{1,0,2,1}=C_H(3,3)[3]$. By Corollary \ref{coro:count-CH}, $C_H(3,3)$ contains exactly $t_4+\sigma=1+3=4$ codes, which are the ones described in Example \ref{examples:chain1}. \end{example} If $H^{t_1,\dots,t_s}$ is a $\mathbb{Z}_{3^s}$-linear GH code of length $3^t$ with $t_1\geq 2$ and $t_s=0$, then $|C_H(t_1,\dots,t_s)|=1$ by Corollary \ref{coro:count-CH}. In this case, from Tables \ref{table:Types} and \ref{table:TypesB2}, we can see that $H^{t_1,\dots,t_s}$ is not equivalent to any other code $H^{t'_1,\dots,t'_{s'}}$ of the same length $3^t$, for $t\leq 10$. We conjecture that this is true for any $t\geq 11$. The values of $(t_1,\dots,t_s)$ for which the codes $H^{t_1,\dots,t_s}$ are not equivalent to any other such code of the same length $3^t$, for $t\leq 10$, can be found in Table \ref{table:Types2}. \begin{table}[h] \centering \begin{tabular}{|c||l|} \hline $t=5$ & (3,0), (2,0,0)\\ \hline $t=7$ & (4,0), (2,1,0), (2,0,0,0)\\ \hline $t=8$ & (3,0,0)\\ \hline $t=9$ & (5,0), (2,2,0), (2,0,1,0), (2,0,0,0,0)\\ \hline $t=10$ & (3,1,0), (2,1,0,0)\\ \hline \end{tabular} \caption{Type of all $\mathbb{Z}_{3^s}$-linear GH codes of length $3^t$ with $\sigma=1$ and $t_s=0$ for $t \leq 10$.} \label{table:Types2} \end{table} From Tables \ref{table:Types} and \ref{table:TypesB2}, we can also see that the $\mathbb{Z}_{3^s}$-linear GH codes of length $3^t$ with $t\leq10$ having the same values $(r,k)$ are the ones which are equivalent by Theorem \ref{theo:equi}. We conjecture that this is true for any $t\geq 11$. \section{Improvement of the partial classification} \label{sec:Classification} In this section, we improve some results on the classification of the $\mathbb{Z}_{p^s}$-linear GH codes of length $p^t$, once $t$ is fixed. More precisely, we improve the upper bounds of ${\cal A}_{t,p}$ given by Theorem \ref{theo:CardinalFirstBound} and determine the exact value of ${\cal A}_{t,p}$ for $t\leq 10$ by using the equivalence results established in Section \ref{sec:relations}. Next, we prove two corollaries of Theorem \ref{theo:equi}, which allow us to improve the known upper bounds for ${\cal A}_{t,p}$. \begin{corollary} \label{coro:t1} Let $H^{t_1,\dots,t_s}$ be a $\mathbb{Z}_{p^s}$-linear GH code. Then, $H^{t_1,\dots,t_s}$ is equivalent to $t_s + \sigma$ $\mathbb{Z}_{p^{s'}}$-linear GH codes for $s'\in \{s+1-\sigma,\dots,s+t_s\}$. Among them, there is exactly one $H^{t'_1,\dots,t'_{s'}}$ with $t'_1\geq 2$, and there is exactly one $H^{t'_1,\dots,t'_{s'}}$ with $t'_{s'}=0$. \end{corollary} \begin{proof} The code $H^{t_1,\dots,t_s}$ belongs to a chain of equivalences $C$, which can be determined by Proposition \ref{lemma:codeInChain}. We have that $H^{t_1,\dots,t_s}$ is equivalent to any code in $C$ by Theorem \ref{theo:equi}, and the number of codes in $C$ is $t_s+\sigma$ by Corollary \ref{coro:count-CH}. By Proposition \ref{lemma:codeInChain}, the first code in $C$ has $s'=s-\sigma+1$. By Proposition \ref{lemma:pos-i-in-CH}, the $i$th code $H^{t'_1,\dots,t'_{s'}}=C[i]$ has $s'=s-\sigma+i$ for $i\in\{1,\dots, t_s+\sigma\}$. Therefore, $s'\in \{ s-\sigma+1, \dots, s+t_s \}$. Finally, by Corollary \ref{coro:One-ts0}, $C[1]$ is the only code in $C$ with $t'_1\geq 2$ and $C[t_s+\sigma]$ is the only code in $C$ with $t'_{s'}=0$. \end{proof} From Corollary \ref{coro:t1}, in order to determine the number of nonequivalent $\mathbb{Z}_{p^s}$-linear GH codes of length $p^t$, ${\cal A}_{t,p}$, we just have to consider one code out of the $t_s+\sigma$ codes that are equivalent. For example, we can consider the one with $t_1\geq 2$. \begin{corollary}\label{cor:sin} Let $H$ be a nonlinear $\mathbb{Z}_{p^s}$-linear GH code of length $p^t$. If $s\in\{\lfloor(t+1)/2\rfloor+1,\dots,t+1\}$, then there is an equivalent $\mathbb{Z}_{p^{s'}}$-linear Hadamard code of length $p^t$ with $s'\in\{2,\dots,\lfloor(t+1)/2\rfloor\}$. \end{corollary} \begin{proof} Let $H^{t_1,\dots,t_s}$ be a $\mathbb{Z}_{p^s}$-linear Hadamard code with $s\in\{\lfloor(t+1)/2\rfloor+1,\dots,t+1\}$. Since $\sum_{i=1}^s(s+1-i)t_i=t+1$, then $t_1=1$ and we have that $\sigma>1$. Therefore, by Proposition \ref{lemma:codeInChain}, $H^{t_1,\dots,t_s}$ is permutation equivalent to the $\mathbb{Z}_{p^{s-\sigma+1}}$-linear Hadamard code $H=H^{t_\sigma+1,t_{\sigma+1},\dots,t_{s-1},t_s+\sigma-1}$. Now, we just need to see that $s-\sigma+1<\lfloor(t+1)/2\rfloor$. Since the length of $H$ is $p^t$, we have that $t+1=(s-\sigma+1)(t_\sigma+1)+\sum_{i=2}^{s-\sigma+1}(s-\sigma+2-i)t_{\sigma-1+i}+\sigma-1$. Therefore, $(s-\sigma+1)(t_\sigma+1)\leq t+1$ and $s-\sigma+1\leq({t+1})/({t_\sigma+1})$. By the definition of $t_\sigma$, we know that $t_\sigma\geq1$, so $s-\sigma+1\leq \lfloor (t+1)/2\rfloor$. \end{proof} Note that we can focus on the $\mathbb{Z}_{p^s}$-linear GH codes of length $p^t$ with $s\in \{2,\dots,\lfloor (t+1)/2\rfloor\}$ by Corollary \ref{cor:sin}, and we can restrict ourselves to the codes having $t_1\geq 2$ by Corollary \ref{coro:t1}. With this on mind, in order to classify all such codes for a given $t\geq 3$, we define $\tilde{X}_{t,s,p}=|\{ (t_1,\ldots,t_s)\in {\mathbb{N}}^s : t+1=\sum_{i=1}^{s}(s-i+1) t_i, \ t_1\geq 2 \}|$ for $s\in\{2,\dots,\lfloor (t+1)/2\rfloor\}$. \begin{theorem} \label{teo:numNonEquiv100-p} Let ${\cal A}_{t,p}$ be the number of nonequivalent $\mathbb{Z}_{p^s}$-linear GH codes of length $p^t$ with $t\geq 3$ and $p\geq 3$ prime. Then, \begin{equation}\label{eq:BoundAtNewX-p} {\cal A}_{t,p} \leq1+ \sum_{s=2}^{\lfloor\frac{t+1}{2}\rfloor} \tilde{X}_{t,s,p} \end{equation} and \begin{equation}\label{eq:BoundAtNew-p} {\cal A}_{t,p} \leq1+ \sum_{s=2}^{\lfloor\frac{t+1}{2}\rfloor} ({{\cal A}}_{t,s,p}-1). \end{equation} Moreover, for $p\geq 3$ prime and $3 \leq t \leq 10$, the upper bound (\ref{eq:BoundAtNewX-p}) is tight. \end{theorem} \begin{proof} It is proven that the codes $H^{1,0,\dots,0,t_s}$ with $s\geq2$ and $t_s\geq0$, are the only $\mathbb{Z}_{p^s}$-linear GH codes which are linear. Note that they are not included in the definition of $\tilde{X}_{t,s,p}$ for $s\in \{2,\dots,\lfloor (t+1)/2\rfloor\}$. Therefore, the new upper bounds (\ref{eq:BoundAtNewX-p}) and (\ref{eq:BoundAtNew-p}) follow by Corollaries \ref{coro:t1} and \ref{cor:sin}, after adding $1$ to take into account the linear code. In Table \ref{table:ClassificationEquiv}, for any odd prime $p$ and $3\leq t \leq 10$, these new upper bounds together with previous bounds are shown. Note that the lower bound $(r,k)$ coincides with the upper bound (\ref{eq:BoundAtNewX-p}) for $t\leq10$, so this upper bound is tight for $t\leq10$. \end{proof} \begin{table}[h] \centering \begin{tabular}{|c||c|c|c|c|c|c|c|c|} \cline{0-8} $t$ & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 \\ \cline{0-8} previous lower bound $(r,k)$ & {\bf 2} & {\bf 2} & {\bf 4} & {\bf 4} & {\bf 7} & {\bf 8} & {\bf 12} & {\bf 14} \\\cline{0-8} new upper bound (\ref{eq:BoundAtNewX-p}) & {\bf 2} & {\bf 2} & {\bf 4} & {\bf 4} & {\bf 7} & {\bf 8} & {\bf 12} & {\bf 14} \\\cline{0-8} new upper bound (\ref{eq:BoundAtNew-p}) & 2 & 2 & 5 & 6 & 11 & 15 & 26 & 33 \\\cline{0-8} previous upper bound & 2 & 2 & 6 & 9 & 15 & 22 & 33 & 46 \\\cline{0-8} \end{tabular} \caption{Bounds for the number ${\cal A}_{t,p}$ of nonequivalent $\mathbb{Z}_{p^s}$-linear GH codes of length $p^t$ for $3\leq t \leq 10$.} \label{table:ClassificationEquiv} \end{table} This last result improves the partial classification. Actually, by definition, we have that $\tilde{X}_{t,s,p}\leq X_{t,s,p}-1$, so the upper bound (\ref{eq:BoundAtNewX-p}) is clearly better than (\ref{eq:CardinalFirstBound}). It is also clear that the upper bound (\ref{eq:BoundAtNew-p}) is better than (\ref{eq:CardinalFirstBoundX-p}) since there are fewer addends. Therefore, both new upper bounds improve the previous known upper bounds. Recall that ${\cal A}_{t,s,p}=X_{t,s,p}$ for any $3\leq t\leq 10$ and $2\leq s\leq t-2$. If this equation is also true for any $t\geq 11$, then upper bounds $(\ref{eq:CardinalFirstBound-p})$ and $(\ref{eq:CardinalFirstBoundX-p})$ coincide. Moreover, upper bound (\ref{eq:BoundAtNewX-p}) would always be better than (\ref{eq:BoundAtNew-p}) since $\tilde{X}_{t,s,p}\leq X_{t,s,p}-1 = {\cal A}_{t,s,p}-1$.
{'timestamp': '2022-03-30T02:28:39', 'yymm': '2203', 'arxiv_id': '2203.15407', 'language': 'en', 'url': 'https://arxiv.org/abs/2203.15407'}
arxiv
\section{Introduction} Neural image and video compression research has made great strides over the past few years. In particular, the latest models leverage advances in deep generative modeling to produce neural compression models, which outperform their state-of-the-art engineered counterparts by significant margins in rate-distortion performance when taking human perceptual quality into account \cite{mentzer2020high, mentzer2021towards}. Even larger gains can be achieved by learning a domain-specific compression model when the data domain is constrained. Designing and training compression models specific to video calls is one of the most recent breakthrough stories along these lines \cite{wang2021one,oquab2021low,konuko2021ultra}, with some works reporting an order of magnitude of bit rate reduction at a given perceptual quality compared to engineered codecs \cite{wang2021one}. In a nutshell, these face video compression algorithms rely on a source frame (view) of the face, warp this view to approximate the target frame to be transmitted, and process the warped source view (or features extracted from the source view) with a generator to compensate for imperfections in the warped source view. Thereby, the warp is parametrized using a small set of keypoints or local affine transforms, extracted from the target frame using a corresponding learned predictor, which enables highly efficient coding and transmission of the warp. While these models achieve excellent (perceptual) rate-distortion performance in the average case, they have some clear limitations due to relying on single source view. Indeed, a single view might not provide appearance details about one side of the face if the head in the source view is slightly rotated to the left or right. Similarly, a source view showing the face with a closed mouth does not provide any information about the appearance of the mouth interior. More generally, it is usually impossible to faithfully infer person-specific shape and appearance details for different facial expressions by solely relying on a single view of the face \cite{zollhofer2018state}. In this paper, we take a first step towards leveraging multiple views of the face to improve neural face video compression algorithms. Specifically, we explore two key questions of multi-view neural face compression, namely how to select different views, and how to fuse information across different views. We present ablations along these two axes, and show that our best 3-view model, which is based on a simple and computationally inexpensive backbone, outperforms the state-of-the art single frame model at significantly lower per-frame rate. Furthermore, we outline and discuss future research directions to push neural face compression algorithms to production quality. \begin{figure}[t] \vspace{-2mm} \centering \includegraphics[width=0.6\columnwidth]{rd-curve-2-small} \vspace{-2mm} \caption[rd-curve]{Rate-distortion performance comparison of our single-frame baseline, our max pooling model based random view sampling (for 3, 5, and 8 source views), and H264.} \label{fig:rd-curve} \vspace{-4mm} \end{figure} \section{Related work} While research on general neural video compression already features a rich body of literature (e.g. \cite{wu2018video,lu2019dvc,habibian2019video,rippel2021elfvc,mentzer2021towards}), there is only a handful of works on neural face video compression \cite{oquab2021low,konuko2021ultra,wang2021one}. Oquab \emph{et al.} \cite{oquab2021low} study the suitability of different talking head synthesis approaches for compression, targeting a mobile low-resource scenario. Konuko \emph{et al.} \cite{konuko2021ultra} propose a simple procedure to select one out of multiple source views used to reconstruct the target frame using exhaustive search on the reconstruction error at encoding time. Wang \emph{et al.} \cite{wang2021one} introduce a high-fidelity model which allows adapting the head pose while decoding. Closely related to neural face video compression is (2D) talking head synthesis, which uses different mechanisms for motion transfer from a source to a target view, including warping, supervised or unsupervised keypoints, conditional normalization or a combination of these to \cite{pumarola2018ganimation, wiles2018x2face, zakharov2019few, wang2019few, siarohin2019first, zakharov2020fast, ha2020marionette}. The resulting motion representations can have various forms and are often not suited for compression. One line of work attempts to overcome inaccurate modeling of subject identity by relying on multiple frames \cite{wang2019few,ha2020marionette}, but no approach considers careful frame selection beyond random sampling. \begin{figure*}[ht!] \vspace{-0.1cm} \centering \includegraphics[width=0.9\textwidth]{ablation-1-small} \vspace{-0.3cm} \caption[ablation]{How well do models trained with a fixed number of source views generalize to a different number of source views? This figure shows the performance of aggregation modules, source view sampling strategies, and number of training source views (legend format {\tt <aggregation strategy>-<sampling strategy>-<number of training source views>}) as a function of the number of testing source views. We report the L1 reconstruction error, PSNR, SSIM and MS-SSIM \cite{wang2003multiscale}, as well as LPIPS \cite{zhang2018unreasonable}. \vspace{-0.2cm} } \vspace{-0.2cm} \label{fig:ablation} \end{figure*} \section{Method} We build on top of the first order motion model (FOMM) from \cite{siarohin2019first}, which also underlies \cite{wang2021one}. We start by briefly summarizing the FOMM (cf. \cite[Fig.~2]{siarohin2019first}), which consists of a keypoint detector, a dense motion predictor, a generator and a corresponding encoder. Given a target frame $f$ and a source frame (view) $v$, the FOMM first extracts sparse keypoints and corresponding local affine transformations from $f$ and $v$, which together define a coarse flow field. The keypoints and transformations are then processed with the dense motion predictor, which refines the coarse flow field and also predicts an occlusion map. Finally, the flow is used to warp features extracted from $v$, mask them using the occlusion map, and to reconstruct $\hat f$ with the generator. Note that the keypoint extractor and the encoder only have to be applied once to $v$. In a video call, the source view is transmitted first, and all subsequent frames are encoded and transmitted via their corresponding keypoints and affines. The transmission cost of the source view is amortized across the entire call. To extend the FOMM to multiple source views $\{v_k\}_{k=1}^K$ we apply the keypoint detector to every view $v_k$ to obtain a coarse flow for every $k$ and corresponding refined flow by applying the dense motion predictor to every coarse flow. We then obtain warped and masked features for every view and pass them to an aggregation module (discussed in more detail below) whose output is fed to the generator to reconstruct the target frame $f$ (see Fig.~\ref{fig:schematic} for an overview). Preliminary experiments showed that when using multiple source views, predicting local affine transformations does not improve performance, so we rely on keypoints only. Note that as for the single frame model we transmit only the keypoints for the current target frame; each view only has to be transmitted once (and corresponding keypoints only have to be extracted once) so that transmission costs are again amortized for reasonably long video sequences. The only additional cost we incur compared to the single frame model is computational, namely we need to compute dense flow fields occlusion maps for $K$ source views instead of one, and apply the aggregation module to fuse the warped features from the $K$ source views. Given the architecture described in the preceding paragraph, the following two questions arise naturally. \begin{itemize} \item What is an effective and efficient architecture design for the aggregation module? \item How to select the source views in order to achieve substantial improvements over just using a single source view? \end{itemize} In this paper, we take a first step in exploring these questions, as described next. \subsection{View aggregation module \label{sec:aggregation}} The view aggregation module should have two properties, namely 1) it should be invariant to the order in which the views are aggregated, and 2) it should be able to aggregate a changing number of views as more views will arrive over time. Indeed, as discussed below, we are interested in having diverse views with complementary information, which will only become available over time, as the caller moves their head and shows different facial expressions. We consider two different architectures. The first one amounts to simple, permutation-invariant pooling such as max pooling and average pooling \cite{zaheer2017deep}. In order to facilitate fusion of the features, we first apply the same stack of two residual blocks to the features extracted from every view after warping/masking, and pool the features across views. \newcommand{\mathbb R}{\mathbb R} The second pooling architecture we consider is based on self-attention (SA) as formulated in \cite{wang2018non} between identical spatial locations in feature space, across views. This is in contrast to the more common SA across different spatial locations within one image. The motivation for attending to the same location across views is to allow our model to pixel-wise attend to the most useful (pre-warped) source view for reconstructing the target frame. In more detail, let $z_{i,j}^{(k)} \in \mathbb R^c$ be the feature extracted from view $k$ after warping and masking at spatial location $i,j$, and $Z_{i,j} = [z_{i,j}^{(1)}, \dots, z_{i,j}^{(K)}]^\top \in \mathbb R^{K \times c}$ the matrix obtained by stacking the $z_{i,j}^{(k)}$. We obtain query, key and value matrices as $Q_{i,j} = Z_{i,j} W_q$, $K_{i,j} = Z_{i,j} W_k$, and $V_{i,j} = Z_{i,j} W_v$, respectively, where $W_q, W_k \in \mathbb R^{c \times d}, W_v \in \mathbb R^{c \times c}$. The SA output at spatial location $i,j$ in feature space, for all $K$ views, is then computed as \begin{equation} A_{i,j} = \text{softmax}(Q_{i,j} K_{i,j}^\top / \sqrt{d}) V_{i,j}. \end{equation} Note that computing $Q_{i,j}$, $K_{i,j}$, and $V_{i,j}$ over all spatial locations amounts to $1 \times 1$ convolution. To build a SA block, we add a residual branch to the SA output, apply ChannelNorm \cite{mentzer2020high}, and append another $3 \times 3$ convolution layer (maintaining the number of channels) followed by ChannelNorm. We stack two such blocks and apply a convolution producing a $W \times H \times K$ output, which we normalize along the channel dimension using softmax. Finally, we average the $z_{i,j}^{(k)}$ across views with the softmax output as weights. \subsection{View selection strategies \label{sec:sampling}} We consider two different sampling strategies: Random sampling (RS) and furthest point sampling (FPS) based on facial landmarks. RS amounts to picking the first frame as well as $K-1$ frames at random among the remaining frames in the video sequence. For FPS \cite{katsavounidis1994new} we first extract 2D facial landmarks from each frame using a simple and efficient landmark detector similar to \cite{trigeorgis2016mnemonic}, and use the stacked coordinates of the landmarks as feature vectors for each frame. We then sample frames, selecting first the initial frame, and then at each iteration selecting the frame whose feature vector maximizes the minimal Euclidean distance to the feature vectors of the previously selected frames. For this initial study we focus on batch (per-video) sampling algorithms for simplicity, and note that online algorithms are necessary to enable a real-time video call scenario. Online uniform RS can be realized using reservoir sampling \cite{li1994reservoir}; a similar reservoir-based streaming algorithm can be derived for FPS. Note that these online approaches likely require careful tuning to ensure a small enough (amortized) bit rate increase. \section{Experiments} \paragraph{Experimental setup} We use the VoxCeleb2 data set \cite{chung2018voxceleb2} which contains 150k videos of 6k celebrities, split into 1.1M individual speech sequences, cropped and scaled to $224 \times 224$ pixels, and split into a train and test set with disjoint subject identities. As we are interested in modeling real-world scenarios where video calls can span several minutes to hours, unless stated otherwise, we concatenate speech sequences of every video and use the resulting videos for our evaluations. These videos are generally harder to compress than individual speech sequences as the target frames may deviate more from a given set of source views as the video length increases. Our baseline model is a precise re-implementation of the FOMM from \cite{siarohin2019first} without local affine transformations (as these did not significantly reduce reconstruction errors in our experiments). To obtain multi-frame models, we extend the baseline model with one of the view aggregation modules described in Sec.~\ref{sec:aggregation} and select views according to the strategies described in Sec.~\ref{sec:sampling}. We employ the multi-scale VGG-based perceptual loss from \cite{johnson2016perceptual} (following the implementation of \cite{siarohin2019first}) and the Adam optimizer, and select for every model the learning rate from $\{3\cdot10^{-6}, 1\cdot10^{-5},3\cdot10^{-5}\}$ that leads to the lowest training loss. We train our models on 4 V100 GPUs for 300k iterations with a batch size of 48 (we increase the number of iterations for smaller batch sizes such that the total number of training frames seen by all models is identical). \paragraph{Comparison of aggregation / view selection strategies} We combine the max pooling and SA view aggregation modules each with RS and FPS, and train the so-obtained models using 3 or 8 source views. We then evaluate these models with a number of source views in the range $\{3, \ldots, 12\}$. The results are shown in Fig.~\ref{fig:ablation}. It can be seen that, while all models obtain smaller reconstruction errors as the number of source views increases at evaluation time, the model MAX-RS-3 (i.e. the model with view aggregation based on max pooling combined with RS, trained on 3 source views) performs best. Upon visually inspecting the models that were trained with 8 source views, we observe that these models do not generalize well in situations where the target frame semantics differ significantly from those in the source views. Thus, it seems that the 8-view models do not see a diverse enough set of source views during training to learn to interpolate/aggregate the source views when the target frame semantics differ significantly from those in the source views. In contrast, models trained with 3 source views are forced to predict larger semantic changes during training. One possible explanation for RS performing better than facial landmark-based FPS could be that while FPS is beneficial for reconstruction the face region, it might lead to an increase in reconstruction error in the background region, and thereby of the overall reconstruction error. As for the simple max pooling outperforming the more complex SA-based aggregation, we speculate that SA might lead to larger benefits in scenarios where the source views are not pre-aligned with the keypoint-based warp so that the SA module is applied to the unmodified source view features as in \cite{ha2020marionette}, handling both feature alignment and aggregation. \paragraph{Comparison with prior work} We compare our single-view baseline model and our best 3-view model (MAX-RS-3) with \cite{wang2021one, zakharov2020fast, siarohin2019first, wang2019few} in Table~\ref{tab:rel-work} when evaluated on single speech sequences rather than concatenated speech sequences (as this is the evaluation protocol in the referenced papers). \emph{Our MAX-RS-3 outperforms the closest competitor \cite{wang2021one} in three out of four metrics while using one third of the (uncoded) bits to encode the keypoints (our model uses 10 2D keypoints resulting in 20 floats per frame while \cite{wang2021one} uses 20 3D keypoints resulting in 60 floats) and arguably a simpler model}. Note however, that the model from \cite{wang2021one} allows re-rendering the head from a different (angular) viewpoint, which our model cannot do. Further \cite{wang2021one} attain substantial reduction in the bits transmitted per frame by making the number of keypoints used adaptive and by using entropy coding. Both techniques can be applied to our model as well and are expected to achieve similar reductions. \paragraph{Comparison with H264} Work \cite{wang2021one} reports an order of magnitude rate reduction of their model over H264 at the same reconstruction quality in terms of learned perceptual image patch similarity (LPIPS) \cite{zhang2018unreasonable}, when trained and evaluated on a proprietary data set. Here, we compare the rate-distortion performance of our single view baseline as well as our best multi-view models MAX-RS-3/5/8 to H264 in Fig.~\ref{fig:rd-curve}. All of our models transmit the same information on a per-frame basis, namely 10 2D keypoints encoded as 16 bit floats. The only rate overhead incurred is due to the transmission of multiple source views. This rate overhead, even when amortized over hundreds of frames, still affects the rate distortion tradeoff quite significantly. However, asymptotically this overhead vanishes leaving a pure distortion complexity tradeoff, i.e., the blue marker and the orange curve would align vertically in Fig.~\ref{fig:rd-curve}. Further, our method obtains a rate reduction of only about $2\times$ over H264 which is a substantially smaller reduction than what is reported by \cite{wang2021one}. We reiterate that \cite{wang2021one} uses an adaptive number of keypoints as well as entropy coding, and evaluates on a higher-resolution data set. \begin{table}[t] \centering \small \begin{tabular}{lcccc} \toprule & L1 & PSNR & SSIM & MS-SSIM \\ \midrule fs-vid2vid \cite{wang2019few} & 17.10 & 20.36 & 0.710 & -- \\ FOMM \cite{siarohin2019first} & 12.66 & 23.25 & 0.770 & 0.830 \\ Bi-Layer \cite{zakharov2020fast} & 23.95 & 16.98 & 0.660 & 0.660 \\ NVIDIA \cite{wang2021one} & 10.74 & 24.37 & {\bf 0.800} & 0.850 \\ \midrule single-frame & 13.16 & 22.79 & 0.758 & 0.828 \\ MAX-RS-3 & {\bf 10.00} & {\bf 24.87} & 0.795 & {\bf 0.872} \\ \bottomrule \end{tabular} \vspace{-1mm} \caption[tab-rel-work]{ \label{tab:rel-work}Comparison of our single-view baseline and best performing 3 view model with prior work on VoxCeleb2; the prior work values are taken from \cite[Table 1]{wang2021one}.} \vspace{-4mm} \end{table} \section{Conclusions} We presented a first exploration and evaluation of different approaches to selecting and aggregating information across views in the context of neural face video compression. Our best 3-view model outperforms the state-of-the-art single view model at a significantly lower per-frame bit rate. Furthermore, we identified multi-view models as an effective means to navigate the tradeoff between distortion and decoding complexity. We conclude by outlining future research directions. \paragraph{Computationally efficient models} Neural models have excellent rate-distortion performance but still consume orders of magnitude more power than engineered codecs with dedicated hardware accelerators. Particularly important in the context of real-time on-device compression scenarios, such as video calls, is therefore to substantially improve the computational efficiency of neural compression models. We believe that relying on multiple views can help along these lines as less of the face modeling work needs to be done by the decoder model. \paragraph{Online view selection} Developing more sophisticated view selection mechanisms is important to gradually gather fine-grained appearance information about the caller in order to produce faithful reconstructions reflecting person-specific expression details. This selection mechanism should be computationally inexpensive (it could e.g. rely on the learned keypoints underlying the warp) and should potentially allow updating views, e.g. when the background or the lighting situation changes. Online updates of source views will, however, incur a transmission overhead so they cannot occur often. As a consequence the neural codec will need to model uncertainty about the face regions or expressions it has not seen and reliably identify frames that provide additional information. Work \cite{konuko2021ultra} proposes an online selection mechanism, but incurs a large increase in encoding complexity and is not suited for real-time scenarios. \paragraph{Better data sets} Whereas celebrity interview videos as abundantly available on the web and collected in the VoxCeleb2 data set present a good starting point, they are certainly not representative of all video call scenarios. To develop neural face codecs tailored to everyday situations data sets, featuring a broader set of video call situations (including e.g. calls from handheld devices while walking, and recorded with a large range of different cameras) are necessary. A corresponding public data set could greatly accelerate development of robust and product grade algorithms. {\small \bibliographystyle{ieee_fullname}
{'timestamp': '2022-04-14T02:22:14', 'yymm': '2203', 'arxiv_id': '2203.15401', 'language': 'en', 'url': 'https://arxiv.org/abs/2203.15401'}
arxiv
\section{Introduction} $\ \ \ $ \textsc{Firefighter} Problem on a graph is broadly described by saving vertices of a graph from fire by placing fire fighters on them, given a source vertex of fire and fire spreading to every neighbour of a burning vertex unless fire fighters are placed on them. Firefighter Problem can be classified in two main categories depending on the set of vertices to be saved by it, i.e. \textsc{Max-Save} and \textsc{Min-Budget}. In the \textsc{ Max-Save} version, the goal is to save maximum number of vertices possible. In contrast, in the \textsc{ Min-Budget} version, the goal is to save a given set of vertices using minimum number of fire fighters at each time step. Firefighter Problem has very important relevance to many real life problems. Suppose a virus is spreading through a network and our goal is to prevent some nodes in the network from this virus by using some preventive measure at some nodes, then this can be seen as a firefighter problem on this network where the virus is like the spreading fire and the preventive measure can be thought as firefighters. In another case, suppose a sensitive data or information has been leaked in a communication network and we need to restrict the flow of the information to some vulnerable or less secured nodes. This scenario also can be modeled as a firefighter problem, where the information can be seen as the spreading fire and the vulnerable nodes as the vertices to be saved using firefighters. \textsc{Unit Disk} Graph represents the intersection of disk graph and interval graph. For each vertex $u$ in the graph, there is a disk of radius $1$ in the Euclidean plane. There is an edge between vertex $u$ and $v$, if $v$ is inside the unit disk centered at $u$. Unit Disk Graphs are relevant to communication network as in almost all practical communication networks the towers or routers have same communicating range which can be modeled as disks of coverage area similar to unit disk graph and to prevent any virus or sensitive information from reaching a node we have to take preventive measures which is same as using some firefighters at some nodes in the firefighter problem case. In most of the practical scenario in a communication network the goal is to keep the sensitive data away from some specific nodes in the network given the network topology. This case resembles Firefighter \textsc{Min-Budget Problem}, where we are given the source of fire and a set of vertices to be saved from fire by putting firefighters in some node at different time instances and minimize our cost while doing so. The cost here is the number of firefighters required at each time instant to achieve our goal. \subsection{Our Results} In this paper, we prove the following two results. \begin{theorem} The Firefighter MIN-BUDGET problem on unit disk graph is NP hard. \end{theorem} \begin{theorem} There exists an approximate solution to Fighter MIN-BUDGET problem on unit disk graph with a constant approximation factor. \end{theorem} \subsection{Previous Works} The Freighter problem has a rich history of work. We mention some results which are most relevant to our work. For a detailed account, we refer the reader to the survey on results, directions and open questions related to firefighter problem by \cite{finbow2009firefighter}. The firefighter problem was introduced by \cite{hartnell1995firefighter} who studied the way to protect an infinite graph from a spreading virus. \cite{hartnell2000firefighting} showed that a simple 2-approximation algorithm exists for Firefighter Max-Save Problem. \cite{wang2002fire} showed 2 firefighters are required to control the fire in an finite 2 dimensional grid with minimum 8 steps and for (r-1) firefighters are required to save a r-regular graph . \cite{develin2007fire} further added that at least 18 vertices will burn to do so and (2d-1) firefighters can hold a fire in an n-dimensional grid if fire breaks out in a single vertex .\cite{macgillivray2003firefighter} proved NP-hardness of firefighter problem on Bipartite graphs and gave a polynomial time algorithm for the same problem on P-trees and also gave an integer programming to determine an optimal sequence of vaccinating the vertices . This work was followed by the work by \cite{hartke2004attempting} to narrow the integrality gap between the integer programming optimal and the optimal of the linear programming relaxation. \cite{finbow2007firefighter} showed that the firefighter problem is NP-hard on trees with maximum degree 3. However if fire breaks out at a vertex with degree 2, the problem is in P. \cite{king2010firefighter} showed that Resource Minimization for Fire Containment(RMFC) is NP-hard on full trees of degree 3. They also showed that the 2-approximation is hard as well, but on graphs of maximum degree 3, if fire breaks out at a vertex of degree 2, the problem is in P. In a follow-up work of \cite{chalermsook2010resource}, the authors showed an $O(\log n)$-approximation LP-rounding algorithm for RMFC on trees. \cite{chlebikova2014firefighter} showed that, the complexity of firefighter problem is governed by path width and maximum degree of a graph. Work on parameterized complexity of firefighter problem can be found in the works by \cite{bazgan2011parameterized,cygan2011parameterized}. \cite{anshelevich2009approximation} considered both spreading and non-spreading vaccination models of firefighter problem to show the NP-hardness of approximation of the problem within $n^{1-\epsilon}$ for any $\epsilon$. \cite{fomin2012making,fomin2016firefighter} considered the Max-Save Firefighter problem and gave polynomial time algorithm for interval graphs, split graphs, permutation graphs, and proved NP-hardness of the problem on Unit Disk Graphs. Online firefighter problem and fractional firefighter problem were introduced by \cite{coupechoux2019firefighting} and they also gave the optimal competitive ratio and asymptotic comparison of number of firefighters and the size of the tree levels. NP-completeness of different graph problems on unit disk graphs have been discussed by \cite{clark1990unit}. \section{Notation and Preliminaries} We use the following notations. If $S$ is a set, $|S|$ denotes size of the set. $d_{\ell_2}(u,v)$ denotes the $\ell_2$ distance of two points $u$ and $v$. An instance of the firefighter problem is denoted by $(G,s)$ where $G$ is an undirected, connected, simple graph, and the fire starts from the vertex $s$. $V_G$ and $E_G$ denote the vertex set and the edge set of $G$ respectively. \subsubsection*{{\sc Min-Budget} Firefighter Problem } \label{sec:min-budg-firef} The {\sc Min-Budget} Firefighter Problem is defined in the following way. {\em Given a undirected, connected, simple graph $G$, a vertex $s\in V_G$, $T\subseteq V_G$, find the minimum number of firefighters needs to be placed at every step to save $T$.} \subsubsection*{Decision Version of Min-Budget Firefighter Problem in Unit Disk Graph.} \begin{itemize} \item \textbf{Input}: A unit disk graph $G(V,E)$, a vertex $s\in V$, a subset $T\subseteq V$ \item \textbf{Question}: If the fire starts from $s$, can all vertices of $T$ be saved if at most $B$ number of firefighter can be placed at each step? \end{itemize} \subsubsection*{Interval Graph} \label{sec:interval-graph} Our approximation algorithm extends the exact algorithm for interval graphs. An interval Graph is an undirected graph formed by correspondence with a set of intervals on real line, where each interval corresponds to a vertex in the graph and two vertices have an edge in between them if their corresponding intervals intersect. \subsubsection*{Unit Disk Graph} \label{sec:unit-disk-graph} Unit Disk Graph is an undirected graph formed by correspondence with a set of disks of unit radius on euclidean plane, where each disk correspond to a vertex in the graph and two vertices have edge in between them if their corresponding disks intersect. \section{Proof of theorem 1.1: the Reduction} \label{sec:proof-hard} We show a reduction from the Firefighter Problem for Trees with maximum degree three which has been shown to be NP hard. The proof idea is similar to the one of the MAX-SAVE version due to \cite{fomin2016firefighter}. The first step is to transform an instance of the MIN-BUDGET Firefighter problem on Trees with maximum degree Three to an instance of the MIN-BUDGET firefighter problem on an Unit disk graph. In order to do that we show an embedding of any full rooted degree three tree into an unit disk graph. \subsection{The Construction} \label{sec:construction} Let $(T,\Gamma,B)$ be the input instance of the firefighter problem on Trees with maximum degree three. $\Gamma$ denotes the set of vertices to be saved and $B$ denotes the budget. The first step is embed $T$ into a unit disk graph $T_G$. \textsc{Rectilinear Embedding.} Let $T$ be a full rooted tree of maximum degree three and $r$ be the root of $T$. Let $m$ be the number of vertices in $T$. We add a new vertex $s$ in the tree and connect it to $r$. Let us call the new graph $T'$ rooted at $s$ with $N=m+1$ vertices. We number the leaves of the new graph $T'$ according to their appearance in the pre-order traversal starting from $s$. Then, for each non-leaf vertex, number it with the median of the numbers corresponding to its children. If any of them is having two children, then number it with the maximum number belonging to its children. We denote the number corresponding to the vertex $v$ after numbering in this fashion by $n(v)$. The embedding works in the following way. Put the vertex $s$ at the coordinate $(2n(s), 0)$. Let $v$ be any other vertex. Suppose the parent of $v$, say $u$, has been placed at $(X_u,Y_u)$. We place $v$ at $(X_v,Y_v)$, where $X_v=X_u+ 2\left(n(u)-n(v)\right)$, and $Y_v= Y_u+ 2 \left(N- \left|n(u)-n(v)\right|\right)$. The edges are mapped to paths parallel to axis. We draw the edge between $u$ and $v$ as follows. Draw a line of length $\left(N- \left|n(u)-n(v)\right|\right)$ in the positive $Y$ direction from $u$ and then a line of length $2|n(u) - n(v)|$ in the positive/negative direction of $X$ axis, according to the positive/negative values of $n(u) - n(v)$. By construction this embedding is indeed a rectilinear embedding. Moreover, in this embedding each edge is of length exactly $2N$ and has at most one bend. The final step of our transformation is the following. On each edge starting from a parent $u$ to a child $v$ in $T'$, we put $2N - 1$ new vertices, one at every point in the path joining $u$ to $v$. $W_v^1$ to $W_v^{2N-1}$ denotes these new vertices, where $W_v^1$ is adjacent to $u$ and $W_v^{2N-1}$ is adjacent to $v$. Finally, for each vertex $v$ in $T'$, we split $W_v^1$, $2N - 1$ times and split $W_v^2,W_v^3,....,W_v^{2N-1},v$, $4N - 1$ times. We call this graph $T_G$. \begin{lemma} \label{lemma:const} $T_G$ is a unit disk graph. \end{lemma} \begin{proof} Consider any edge $(w_1,w_2)$ in $T_G$. By construction, $w_1,w_2$ are two adjacent vertices in the path joining vertex $u$ and vertex $v$ of $T$. As all the paths are drawn parallel to one of the axis, $d_{\ell_2}(w_1,w_2)=1$.\\ For the other direction, consider any non-adjacent pair of vertices $w_1,w_2$ of $T_G$. If the vertices are in the same path (joining two vertices of $T$ in the embedding), then there is at least one vertex between $w_1$ and $w_2$ in the path. As the vertices are placed at distance $1$, and each path has only one bend, $d_{\ell_2}(w_1,w_2)\geq \sqrt{2}>1$. Suppose, $w_1$ and $w_2$ are in different paths. By construction, distance between two completely different paths in $T_G$ is at least $2$. If some part of the paths are same, then $d_{\ell_2}(w_1,w_2)\geq \sqrt{2}>1$. Hence, all the non adjacent vertices in $T_G$ are more than unit distance away from each other. \end{proof} The last step of the above construction produces $4N$ images of every vertex $v\in T$. Let $\Gamma_G$ be the set of all $4n$ images for each of the vertices $\Gamma$. The constructed instance of the firefighter problem is $(T_G,\Gamma_G,B)$. The following lemma proves the correctness of the reduction. \begin{lemma} \label{lemma:red} $(T_G ,\Gamma_G)$ is a YES instance for the Decision version of the Minimum Budget Firefighter Problem on unit disk graph, if and only if $(T,\Gamma)$ is a yes instance of the Minimum Budget Firefighter problem on tree. \end{lemma} \subsubsection{Proof of Lemma \ref{lemma:red}} \label{sec:proof-lemma-refl} The proof of Lemma \ref{lemma:red} follows from following two lemmas. \begin{lemma} There is a strategy to save all $4N$ images of some vertex $v$ of $T_G$ in firefighter game if and only if there is a strategy to save all $2N$ images of $W_v^1$ of $T_G$. \end{lemma} \begin{proof} If in the graph $T_G$ all the $4N$ images of some vertex $v$ is saved then it means at least one of the vertices $W_v^2,W_v^3,....,W_v^{2N-1},v$ had all its $4N$ images vaccinated till fire came to that level or all the $2N$ images of $W_v^1$ were vaccinated before fire came to it. Now, if the first case is true for $v$ or some $W_v^k$ where $k \in \{2, 3, . . . . . . , 2N - 1\}$ then at least $2N$ images of $W_v^k$ were vaccinated when fire reached to $W_v^1$. Then, in spite of vaccinating $2N$ images of $W_v^k$, we could have vaccinated all the images of $W_v^1$. Also in a contra-positive sense if by any optimal strategy we can't save all the $4N$ images of $v$ before it reaches that level, then at least one vertex of $W_v^1$ must be infected when fire reached its level. So in $T_G$, saving $v$ means saving $W_v^1$ and vice-versa. To make this argument valid for $W_t^1$, where $t$ is the child of $r$ in $T$, we added the extra vertex $s$ to $T$ in the construction. \end{proof} \begin{lemma} There is a strategy to save $W_v^1$ where $W_u^1$ can't be saved in $T_G$ in firefighter game, if and only if there is a strategy to save $v$ where $u$ can't be saved in $T$ given $v$ is the child of $u$ in $T$. \end{lemma} \begin{proof} Now to correspond unit disk graph problem to the case of full rooted tree of maximum degree three problem, it is sufficient to prove that \begin{enumerate} \item \label{en:1} If it is possible to save vertex $v$ while its parent $u$ can't be saved in a full rooted tree then it is possible to save $W_v^1$ when $W_u^1$ can't be saved in $T_G$. \item \label{en:2} In a contra-positive sense if there is no strategy to save $v$ while its parent $u$ is infected in $T$ then there is no strategy in $T_G$ to save $W_v^1$ when $W_u^1$ is infected and fire came ahead of it. \end{enumerate} Now, for case \ref{en:1}, when $u$ just gets infected and the fire is about to come towards $v$, we vaccinate $v$. The similar case in $T_G$ will be when fire reaches $W_u^1$ and affects some of its images, we start vaccinating the images of $W_v^1$ and it takes $2N$ time steps to reach $W_v^1$ by then we vaccinate all the images of it and save $W_v^1$. For case \ref{en:2}, when $u$ is infected and fire started to move towards $v$ and by no strategy we can vaccinate $v$, the similar case in $T_G$ will be when $W_u^1$ is already infected and fire moved towards $u$ and affected $W_u^2$ and none of the images of $W_v^1$ is vaccinated. Then by the time fire reaches $W_v^1$, we can't save all the images of it as it will take $2N - 1$ time steps and we have to vaccinate $2N$ vertices. So, $W_v^1$ can't be saved. \end{proof} In \textbf{Lemma 3}, the equivalence in terms of burning or saving between vertices $v$ and $W^1_v$ of graph $T_G$ has been shown and in \textbf{Lemma 4}, the equivalence of saving strategies of vertex $W^1_v$ in graph $T_G$ and vertex $v$ in graph $T$ has been shown. These two lemmas together prove that saving or burning of vertex $v$ in graphs $T_G$ and $T$ are equivalent and thus prove \textbf{Lemma 2}. \textbf{Lemma 1} and \textbf{Lemma 2} together proves \textbf{Theorem 1}. \section{Approximation Algorithm for MIN-BUDGET problem} $\ \ \ $ Firefighter problem on interval graphs are polynomial time solvable. Keeping this fact in mind, the underlying geometry of unit disk graph in Euclidean plane can be modified a bit to get another geometry which has a polynomial time solution. Following is a polynomial time algorithm for the firefighter problem on interval graphs, which will be extended later for an approximation algorithm for the same problem on unit disk graph. \subsection{Exact Algorithm for Interval Graph} \label{sec:min-budget-problem} Let $(G,s,T)$ be an instance of the MIN-BUDGET Firefighter problem where $s$ is the source vertex and $T \subset V_G$ is the set of vertices to be saved. Algorithm 1 formally describes algorithm. Algorithm \ref{alg:interval} is an exact algorithm. \begin{algorithm}[htb] \caption{Algorithm for Firefighter Min-Budget Problem on Interval Graph} \label{alg:interval} \begin{algorithmic} \STATE \textbf{INPUT}: $G(V,E),v,T|$ where $G$ is an Interval Graph, $v \in V$ be the source vertex of fire and $T \subseteq V$ be the set of vertices to save. \STATE $T_{1}=T \cap N(v)$ \STATE $T'=T \setminus T_{1}$ \STATE $V_{1}=V$ \STATE $A_{1}=|n(v)|$ \STATE $B_{1}=|T_{1}|$ \FOR{$i=2:n:1$} \IF{$|T'| \neq 0$} \STATE $V_{i}=V_{i-1} \setminus T_{i-1}$. \STATE $G_{i}(V_{i},E_{i})| \forall u,v \in V_{i}, (u,v) \in E \Rightarrow (u,v) \in E_{i}$ \STATE $T_{i}=\{t \in T'| Dist_{G_{i}}(v,t)=i\}$ \STATE $K_{i}=$ Minimum Cut-set of $T_{i}$ in $G_{i}$ \STATE $B_{i}=\Bigl\lceil\frac{\sum_{k=1}^{i}|T_{k}|}{i}\Bigr\rceil$ \STATE $A_{i}=\Bigl\lceil\frac{\sum_{k=1}^{i-1}|T_{k}|+|K_{i}|}{i}\Bigr\rceil$ \ENDIF \ENDFOR \IF{$\max_{i}B_{i} \leq \min_{i}A_{i}$} \STATE Then Budget is $\max_{i}B_{i}$ and firefighters are to be placed on $T$ \ELSE \STATE Let $\min_{i}A_{i}=A_{m}$, Then Budget is $\max(A_{m},\max_{k}B_{k}|k < m)$ and firefighters are to be placed on $\cup_{i=1}^{m-1} T_{i} \cup K_{m}$ \ENDIF \end{algorithmic} \end{algorithm} \paragraph{Correctness of Algorithm \ref{alg:interval}} $\ $ \begin{lemma} In the optimal strategy, Firefighters have to be placed on $T_{i}$, if not placed on all the vertices of $K_{i}$ at $i^{th}$ time instant. \end{lemma} \begin{proof} Consider the $i^{th}$ time instance. Suppose, there are some unprotected vertices of $T_i$. Moreover suppose there are some vertices in $K_{i}$ where no firefighter is placed. Then $\exists u_{i} \in T_{i}$, where fire reaches to the unprotected vertices of $T_{i}$ at $i^{th}$ or $(i+1)^{th}$ time instant, which is not permitted. So, we have to place firefighters on the unprotected vertices of $T_{i}$ at $i^{th}$ or $(i+1)^{th}$ time instant. So, placing the firefighters on $K_{i} \setminus T_{i}$ at $i^{th}$ time instant will be waste of firefighters and will also increase the budget. So, it will be wise to place the firefighters either on $K_{i}$ or on $T_{i}$ at $i^{th}$ time instant. \end{proof} \begin{lemma} If at $i^{th}$ time instant firefighters are placed on $K_{i}$ then fire will never reach to $T_{k} \forall k \geq i$. \end{lemma} \begin{proof} Suppose at $i^{th}$ time instant firefighters are placed on all vertices of $K_{i}$, then fire can never reach to any of the vertices of $W_{i}|W_{i}=T_{i} \setminus K_{i}$. The span of $W_{i} \geq 1$ as the intervals are of unit length. So, fire will never reach to $T_{k} \forall k \geq i$. \end{proof} \paragraph{} If at some level $i$, the better strategy is to put firefighters on $K_{i}$ then the fire fighting process will stop at that time instant. So, either we have to place fire fighter on $K_{i}$ at $i^{th}$ time instant and on $T_{k}$'s at corresponding time instant for $k < i$ or we have to put fire fighters on $T_{i}$'s $\forall i$. Now, if the optimum strategy is to place fire fighters on $K_{i}$ at $i^{th}$ step then the budget must be greater than both $A_{m}$ and $\max_{k}B_{k}|k < m$, where $\min_{i}A_{i}=A_{m}$ as both are the necessary conditions. But, if $\max_{i}B_{i} \leq \min_{i}A_{i}$, then $\max_{i}B_{i}$ gives the optimum budget as a necessary condition. This proves the correctness of the algorithm. \subsection{Approximation Algorithm for Unit Disk Graph} \label{sec:appr-algor-unit} \begin{lemma} Firefighter MIN-BUDGET problem on Unit Disk Graph has an approximate solution using the algorithm for MIN-BUDGET problem on Unit Interval Graph. \end{lemma} \begin{proof} Let, there be $n$ vertices in the unit disk graph $G(V,E)$. \textit{v} be the source vertex of fire and $T \subset V$ be the set of vertices to be saved. We first replace the disks with their circumscribing squares with sides parallel to the coordinate axes. Now, this problem can be seen as four firefighter MIN-BUDGET problems on Unit interval graphs by observing that fire can spread in the up, down, left or right direction accordingly starting from \textit{v}. So, we can use our algorithm for MIN-BUDGET problem on Unit Interval Graph simultaneously in the four direction around \textit{v}. Due to this modification in this solution an approximation factor will be introduced in the result. For a square(say $S_u$) in the Euclidean plane corresponding to a vertex(say $u$) of the graph, the leftmost boundary of $S_1^u$ is given by $x=X_l^u$ and the down most boundary is given by $y=Y_d^u$. Algorithm for solving firefighter MIN-BUDGET problem on this modified graph is given in Algorithm \ref{alg:unitdisk}. \begin{lemma} Due to approximating the firefighter MIN-BUDGET problem on Unit Disk Graph as combination of four firefighter MIN-BUDGET problem on Unit Interval Graph the solution introduces a constant approximation factor of $2$. \end{lemma} \begin{proof} Firstly, we eliminate the effect of modifying the disks into circumscribing squares by checking at each time step of the spread of fire whether the new disks are having any intersection with the disks defining the boundaries of the burning rectangle. In the algorithm a forced assumption is that the region in fire at any instant of time forms a rectangle in the Euclidean plane in not always true.Due to the burning rectangle approximation, a vertex corresponding to an unit disk centered at $(X,Y)$ can burn as early as at Max$(X,Y)$ time instant, while in actual case it can take at most $2(X+Y)$ time. As the fire has to travel at most $2k$ squares to reach $(k,0)$ point starting from $(0,0)$ (limiting case when every square has an neighbor square slightly shifted in $X$ direction). Due to this effect the partial average at each time instant can be as big as $2(X+Y)/$max$(X,Y)$ times of the actual. Here the approximation factor becomes $2(X+Y)/$ max$(X,Y)$, which is less than $2$. \end{proof} \textbf{Lemma 7} and \textbf{Lemma 8} together proves \textbf{Theorem 2}. \begin{algorithm}[] \small \caption{Firefighter Min-Budget Problem on Unit Disk Graph} \label{alg:unitdisk} \begin{algorithmic}[1] \STATE \textbf{INPUT}: $G(V,E),v,T|$ where $G$ is an Unit Disk Graph, $v \in V$ be the source vertex of fire and $T \subseteq V$ be the set of vertices to save. \STATE Replace all the disks by their circumscribing squares with sides parallel to coordinate axes and $G(V,E)$ becomes an Unit Square Graph. \STATE $\forall v_{i} \in V$ sort them according to the $X_{l}^{i}$ values of their corresponding Square $S_{i}$ in increasing order. If $X_{l}^{i}=X_{l}^{j}$ then sort them according to their increasing order of $Y_{d}^{i}$ and $Y_{d}^{j}$. \STATE $\forall v_{i} \in V$ sort them according to the $Y_{d}^{i}$ values of their corresponding Square $S_{i}$ in increasing order. If $Y_{d}^{i}=Y_{d}^{j}$ then sort them according to their increasing order of $X_{l}^{i}$ and $X_{l}^{j}$. \STATE The boundaries of the burning rectangle ($R$) be, $R_l^0=X_l^v, R_r^0=X_r^v, R_u^0=Y_u^v, R_d^0=Y_d^v$. \STATE $T^0=\phi$. \STATE $T'=T \setminus T^0$. \STATE $V_{0}=V$. \STATE $C_m^0=\{v\} \forall m \in \{l,r,u,d\}$. \FOR{$i=1:n:1$} \IF{$T' \neq \phi$} \STATE $V_r^i=W\ |\ \forall w \in W \subset V, R_r^{i-1}-1<S_l^w<R_r^{i-1} \ \& \ R_d^{i-1}-1<S_d^w<R_u^{i-1} \ \& \ \exists v \in C_r^{i-1}|(S_l^w-S_l^v)^2+(S_d^w-S_d^v)^2 \leq 1$. \STATE $V_l^i=W\ |\ \forall w \in W \subset V, R_l^{i-1}+1>S_r^w>R_l^{i-1} \ \& \ R_d^{i-1}-1<S_d^w<R_u^{i-1} \ \& \ \exists v \in C_l^{i-1}|(S_r^w-S_r^v)^2+(S_d^w-S_d^v)^2 \leq 1$. \STATE $V_u^i=W\ |\ \forall w \in W \subset V, R_u^{i-1}>S_d^w>R_u^{i-1}-1 \ \& \ R_l^{i-1}-1<S_l^w<R_r^{i-1} \ \& \ \exists v \in C_u^{i-1}|(S_l^w-S_l^v)^2+(S_d^w-S_d^v)^2 \leq 1$. \STATE $V_d^i=W\ |\ \forall w \in W \subset V, R_d^{i-1}<S_u^w<R_d^{i-1}+1 \ \& \ R_l^{i-1}-1<S_l^w<R_r^{i-1} \ \& \ \exists v \in C_d^{i-1}|(S_l^w-S_l^v)^2+(S_u^w-S_u^v)^2 \leq 1$. \FOR {$m \in \{l,r,u,d\}$} \STATE $T_m^i=T \cap V_m^i$. \IF{$V_m^i \setminus T_m^i \neq \phi$} \STATE $C_m^i=V_m^i \setminus T_m^i$ \ELSE \STATE $C_m^i=C_m^{i-1}$ \ENDIF \STATE $R_m^i=X_m^v||X_m^v|=\max_{w}|X_m^w|\forall w \in C_m^i$ \ENDFOR \STATE $T^i=T_r^i \cup T_l^i \cup T_u^i \cup T_d^i$. \STATE $T'=T'\setminus T^i$. \STATE $V_{i}=V_{i-1} \setminus T^i$. \STATE $G_{i}(V_{i},E_{i})| \forall u,v \in V_{i}, (u,v) \in E \Rightarrow (u,v) \in E_{i}$. \STATE $K_m^i=$ Minimum Cut-set of $V_m^i$ in $G_i$ where, $m \in \{r,l,u,d\}$. \STATE $B_m^i=\Bigl\lceil\frac{\sum_{k=1}^{i}|T_m^k|}{i}\Bigr\rceil$ where, $m \in \{r,l,u,d\}$. \STATE $A_m^i=\Bigl\lceil\frac{\sum_{k=1}^{i-1}|T_m^k|+|K_m^i|}{i}\Bigr\rceil$ where, $m \in \{r,l,u,d\}$. \ENDIF \ENDFOR \STATE $\mathfrak{B}=0, \mathcal{V}=\phi$. \FOR {each $m \in \{r,l,u,d\}$} \STATE $T_m= \cup_{i=1}^{n} T_m^i$. \STATE $\mathfrak{B}_m=0, \mathcal{V}_m=\phi$. \IF{$\max_{i}B_m^i \leq \min_{i}A_m^i$} \STATE Then Budget $\mathfrak{B}_m$ is $\max_{i}B_m^i$ and firefighters are to be placed on $\mathcal{V}_m=T_m$ \ELSE \STATE Let $\min_{i}A_m^i=A_m^t$, Then Budget $\mathfrak{B}_m$ is $\max(A_m^t,\max_{k}B_m^k|k < t)$ and firefighters are to be placed on $\mathcal{V}_m=\cup_{i=1}^{t-1} T_m^i \cup K_m^t$. \ENDIF \STATE $\mathfrak{B}=\mathfrak{B}+\mathfrak{B}_m$. \STATE $\mathcal{V}=\mathcal{V} \cup \mathcal{V}_m$. \ENDFOR \end{algorithmic} \end{algorithm} \end{proof} \subsection{Analysis of Algorithm \ref{alg:unitdisk}} The algorithm for minimum budget firefighter problem on unit disk graph is based on the algorithm for minimum budget firefighter problem on unit interval graph described in Algorithm \ref{alg:interval}. We consider the problem on unit disk graph as a combination of four simultaneous interval graph problems in four different directions, i.e. left($l$), right($r$), up($u$), down($d$). For a given graph $G(V,E)$ and a fire break-out point $v \in V$, we have to find the minimum budget of firefighters to be placed at each time step to save a given set of vertices $T \subseteq V$. As a first step, we replace all the unit disks corresponding to the vertices of $G$ with their circumscribing squares with sides parallel to the rectilinear axes of the plane. Then we sort the vertices of $G$ in two different arrays one according to the X-coordinates of the centers of their corresponding squares and the other according to the Y-coordinates of the centers of their corresponding squares. These two sorted arrays are for use in different stages of the algorithm later. Afterwards, we define and initialize a number of variables namely Squares corresponding to the disk $v$ i.e. $(S^v)$and its boundaries$(S^v_m)$, boundaries of the burning rectangle$(R^i_m)$ at $i^{th}$ iteration and direction $m$, Set of vertices saved$(T^i_m)$ at $i^{th}$ iteration and direction $m$, vertices saved in $i^{th}$ iteration$(T^i)$ and in each direction$(T^i_m)$, vertices at the boundary of the burning rectangle at $i^{th}$ iteration in each direction$(C^i_m)$, Budget required at each direction$(\mathfrak{B})_m$ and set of vertices on which firefighters to be placed$(\mathcal{V}_m)$. Now at each iteration, we find the new set of vertices whose corresponding squares have inter section with burning rectangle and also filter them depending on whether their corresponding disks have intersection with any of the disks corresponding to the set of vertices constituting the boundary of the burning rectangle at previous iteration. From this we update the burning rectangle and its boundary, vertices to be saved at current iteration, set of vertices constituting the new boundary of the burning rectangle and the minimum cut set of the vertices that completely holds the fire at current iteration. Depending on the cut set and the saved vertices at each iteration, we fix the budget for each direction along with the final budget and the set of vertices to be placed firefighter on. \subsection{Correctness of the Algorithm} In the algorithm for Minimum Budget Firefighter Problem on Unit Disk Graph, the algorithm for Minimum Budget Firefighter Problem on Unit Interval Graph has been applied simultaneously in four directions namely, upwards, downwards, left and right using the subscript $m$. So the correctness of the algorithm in each of these four directions is guaranteed by the correctness of the algorithm for interval graph that is already proved in this paper(section 4.1). It should also be noted that due to geometric assumption of burning rectangle an approximation factor of $2$ has been introduced by this algorithm as described in \textbf{Lemma 8}. \bibliographystyle{unsrt}
{'timestamp': '2022-03-30T02:33:10', 'yymm': '2203', 'arxiv_id': '2203.15509', 'language': 'en', 'url': 'https://arxiv.org/abs/2203.15509'}
arxiv
\section{Introduction} Mimicking human capability to recognize things never seen before, zero-shot video classification (ZSVC) only trains models on videos of seen classes and makes predictions on unobserved ones \cite{liu2011recognizing,vgan,multi,mettes2017spatial,mettes2021object,gao2020learning,kim2021daszl,zhu2018towards}. Correspondingly, existing ZSVC models map visual and semantic features into a unified representation, and hope the association can be generalized to unseen classes \cite{zhu2018towards,hahn2019action2vec,bishay2019tarn,brattoli2020rethinking,qiu2021boosting,chen2021elaborative}. However, these methods learn associated representations within limited classes, thus facing the following two critical problems \cite{fu2015transductive,gao2020learning}: (1) semantic-gap: manifolds inconsistency between visual and semantics features, and (2) domain-shift: the representations learned from training sets are biased when applied to the target sets due to disjoint classes between two groups. In ZSVC, these two problems cause side effects on model generalizability. \begin{figure} \centering \includegraphics[width=0.45\textwidth]{fig1} \caption{ {\bf Visual-semantic representations:} Comparisons of the learned representations between the SoTA \cite{brattoli2020rethinking} and our method. \protect\scalebox{1}{\textbullet} and \protect$\bigtriangleup$ represent visual and semantic features separately; colors are for different classes. Besides, we use two metrics to quantify feature qualities on alignment (closeness$\downarrow$ better) and uniformity (dispersion$\uparrow$ better). We observe that ours show better closeness within classes and more separations among semantic clusters.} \label{fig:fig1} \vspace{\figsep} \end{figure} Reviewing the literature, we observe that most methods focus on tackling the semantic-gap by learning alignment-aware representations, which ensure visual and semantic features of the same class close. To improve the alignment, MSE loss \cite{brattoli2020rethinking}, ranking loss \cite{hahn2019action2vec}, and center loss \cite{gao2020learning} are commonly used to optimize the similarity between visual and semantic features. Apart from the loss, improvements for alignment are attributed mainly to the designs of architectures. For instance, \cite{jain2015objects2action,gao2020learning,mettes2021object} first project global visual features to local object attributes, then optimize similarity between the attributes and final semantics. In contrast, URL \cite{zhu2018towards}, Action2Vec \cite{hahn2019action2vec}, and TARN \cite{bishay2019tarn} directly align visual and final semantic features, which are improved via attention modules. Since video features are hard to learn, the above methods utilize pre-trained models to extract visual features. The recent model \cite{brattoli2020rethinking} benefits from the efficient R(2+1)D module \cite{tran2018closer} in video classification and achieves the state-of-the-art (SoTA) results in ZSVC. However, the SoTA \cite{brattoli2020rethinking} neglects to learn semantic features; thus, it is still not a true end-to-end (e2e) framework for visual-semantic feature learning. We claim that e2e is critical for alignment since fixed visual/semantic features will bring obstacles to adjusting one to approach another. Noteworthily, the latest MUFI \cite{qiu2021boosting} and ER \cite{chen2021elaborative} get down to addressing the domain-shift problem by involving more semantic information, thus consuming extra resources. In particular, MUFI \cite{qiu2021boosting} augments semantics by training multi-stream models on multiple datasets. ER \cite{chen2021elaborative} expands class names by annotating amount of augmented words crawled from the website. Freeing complex models or additional annotations, we will design a compact model that preserves maximal semantic info of existing classes while synthesizing features of unseen classes. To tackle the two problems with one stone, we present an end-to-end framework that jointly preserves alignment and uniformity properties for representations on both seen and unseen classes. Here, alignment ensures closeness of visual-semantic features; uniformity encourages the features to distribute uniformly (maximal-info preserving), which improves the possibility that unseen features stand around seen features, mitigating the domain-shift implicitly. Specifically, we formulate a supervised contrastive loss as a combination of two separate terms: one regularizes alignment of features within classes, and the other guides uniformity between semantic clusters. To alleviate the domain-shift explicitly, we generate new features of unseen synthetic classes by our class generator that interpolates and extrapolates features of seen classes. In addition, we introduce closeness and dispersion scores to quantify the two properties and provide new measurements of model generalizability. Fig.~\ref{fig:fig1} illustrates the representations of our method and the SoTA alternative \cite{brattoli2020rethinking}. We train the two models on ten classes sampled from Kinetics-700 \cite{carreira2017quo} and map features on 3D hyperspheres. We observe that our representation shows better closeness within classes and preserves more dispersion between semantic clusters. Experiments validate that our method significantly outperforms SoTA by relative improvements of 28.1\% on UCF101 and 27.0\% on HMDB51. \section{Related Work} \label{sec:relatedwork} {\bf Supervised video classification (SVC):} SVC tackles general classes initially (\eg, YouTube-8M dataset \cite{abu2016youtube}), then specific to action recognition recently (\eg, large-scale Kinetics-700 dataset\cite{carreira2017quo}). Learning temporal features is the main task of SVC. In the beginning, video features are generated via NetVLAD \cite{miech2017learnable,lin2018nextvlad} that fuses static features of multiple frames. Then, temporal/motion features of videos are optimized directly. We categorize the methods into two-stream 2D-CNN and 3D-CNN based. Two-stream models \cite{simonyan2014two,wang2016temporal,lin2019tsm} extract spatial and temporal features by performing separate 2D-CNN modules. \cite{jiang2019stm,liu2020teinet} extracts motion features by computing 2D-CNN features' difference between neighboring frames. Furthermore, \cite{tran2015learning} proposes C3D to fuse spatial and temporal features via an independent 3D-CNN module. Even C3D helps achieve promising results \cite{feichtenhofer2019slowfast,sudhakaran2020gate}, its large parameters bring burdens to model optimization. Instead, I3D \cite{carreira2017quo} and P3D \cite{qiu2017learning} design 3D-CNN-like modules by combining 1D temporal and 2D spatial filters. Recently, a more efficient R(2+1)D module \cite{tran2018closer} has been widely used, which includes a pseudo-3D kernel (2D spatial + 1D temporal) in residual networks. In this paper, we apply our model in action recognition and perform R(2+1)D for better spatial-temporal feature extraction. \begin{figure*} \centering \includegraphics[width=0.9\textwidth]{fig2} \caption{ {\bf Architecture of AURL:} From left to right, we map a video sequence $I$ and the class name set $\mathcal{Y}$ to a unified representation ($f_v(g(I))$, $f_s(c(\mathcal{Y}))$). During training, to learn representations of seen classes, we introduce $\mathcal{L}_\text{S}$ to preserve {\em alignment} and {\em uniformity} properties. For synthetic unseen classes, we introduce $\mathcal{L}_\text{US}$ to learn the two properties on synthetic visual-semantic features ($\Theta, Z$). To synthesize features of unseen classes, we first utilize $\mathcal{L}_\text{C}$ to learn {\em visual centers} $W$, then propose {\em Class Generator} to transform $W$ and existing semantics $f_s(c(\mathcal{Y}))$ into the representation ($\Theta, Z$). During inference, we perform an NNS strategy to obtain the final class. } \label{fig:fig2} \vspace{\figsep} \end{figure*} {\bf Zero-shot video classification (ZSVC):} Existing ZSVC methods align visual and semantic features on a unified representation and hope the alignment can be generalized to unseen classes. Most methods design various frameworks to optimize the alignment. Similar to zero-shot image classification \cite{xian2018zero}, some methods \cite{liu2011recognizing,gan2016learning,jain2015objects2action,mettes2021object,kim2021daszl} learn video attributes first, then design stage-wise framework. Given input videos, \cite{liu2011recognizing,gan2016learning} learn classifiers for video attributes, then compare the predicted attributes and final class names. However, they cost intensive annotations of video attributes. Instead, \cite{jain2015objects2action,mettes2021object,kim2021daszl} utilize pre-trained object detectors to determine object-level class names, then compute similarities between object-level and final class names. Recent work directly computes the similarity between visual and semantic features, and their contributions focus on enhancing visual features. URL \cite{zhu2018towards}, TARN \cite{bishay2019tarn} and Action2Vec \cite{hahn2019action2vec} extract spatial-temporal features using a pre-trained C3D and then improve the features via attention modules. The latest model \cite{brattoli2020rethinking} learns visual embeddings by an efficient R(2+1)D module and achieves SoTA results. However, the above methods are not true end-to-end (e2e) models because those utilize Word2vec \cite{mikolov2013efficient} to extract semantic features. We will justify that lacking e2e learning weakens the alignment since fixed visual/semantic features will bring obstacles to adjusting one to approach another. Except for the above designs, MSE loss \cite{brattoli2020rethinking}, ranking loss \cite{hahn2019action2vec}, and center loss \cite{gao2020learning} are commonly used to regularize the alignment of features. In this paper, we propose a true e2e framework and formulate a supervised contrastive loss, which first considers both alignment and uniformity properties in ZSVC. {\bf Representation learning:} In self-supervised and zero-shot learning, representation learning learns features of observed data, which can extract helpful info when applied to downstream tasks. In self-supervised learning, given pairs of positive and negative images/videos, contrastive learning regularizes representations where positives stand close while negatives keep apart. The pioneering work, SimCLR \cite{chen2020simple} utilizes data augmentation to generate positive instances and maintains a large batch for choosing relatively enough negatives. \cite{qian2021spatiotemporal} applies SimCLR to the video domain. To save memory, MoCo \cite{he2020momentum} presents momentum update to cache a large number of negative instances, then \cite{kuang2021video, pan2021videomoco} extends MoCo to video understanding. \cite{zhu2021improving} introduces feature transformation on existing samples to obtain broader and diversified positives and negatives, thus enhancing discrimination. However, the above models learn instance pairs from the same domain, \eg, images or videos. Instead, CLIP \cite{radford2021learning} exploits features of two domains (\ie, images and texts) guided by a contrastive loss. Motivated by CLIP, the latest models in ZSVC, MUFI \cite{qiu2021boosting} and ER \cite{chen2021elaborative}, extend the self-supervised contrastive loss to a fully-supervised loss that contrasts visual and semantic features. However, MUFI and ER neglect the difference and similarities of the self-supervised and supervised contrastive losses. Considering alignment and uniformity properties, we build connections between the two losses and analyze the advantages of the supervised loss. Besides, MUFI and ER both require extra resources to improve model generalizability. We propose a compact model using a class generator to explicitly synthesize new features of synthetic unseen classes. \section{Alignment-Uniformity aware Representation Learning (AURL)} This section describes Alignment-Uniformity aware Representation Learning (AURL) involving a unified architecture, loss functions, class generator, and two novel metrics, followed by its training and inference strategy, and then discusses similarities and differences against alternatives. \subsection{Architecture} Fig. \ref{fig:fig2} shows the AURL architecture. Given complete $K$ class names $\mathcal{Y}=\{y_1, \dots, y_K\}$, and an input video $I$ of class $y_i\in \mathcal{Y}$ (\eg, playing basketball), we by end-to-end learn visual and semantic embeddings. We introduce R(2+1)D \cite{tran2018closer} as the backbone to generate visual features $g(I)$, and utilize a video projector $f_v$ to implement 3-layer MLP projection (2 fc+bn+ReLU and 1 fc+bn), thus obtain visual embeddings $f_v(g(I))\in\mathbb{R}^{d}$. Parallelly, we perform Word2vec $c$ \cite{mikolov2013efficient} to extract the initial word embeddings $c(\mathcal{Y})$, then learn semantic embeddings $f_s(c(\mathcal{Y}))\in\mathbb{R}^{K\times d}$ by a word projector $f_s$ that has one fc (\#node=512) and the 3-layer MLP projection. For convenience, we note $f_v(g(I))$ and $f_s(c(y_i))$ of $i$-th class as $v_{y_i}$ and $s_{y_i}$ for the below discussions. Compared with SoTA methods \cite{brattoli2020rethinking,qiu2021boosting} that only learn video parts, our AURL end-to-end trains the backbone, video and word projectors, providing more feature flexibility under the regularization of loss functions. \begin{comment} \begin{figure*} \centering \begin{minipage}{0.4\textwidth} \centering \includegraphics[width=0.9\linewidth]{mixup} \caption{Illustration of {\em mixup transformation}. We obtain unseen classes \protect\scalebox{1}{\color{red}{\textbullet}} by linearly combining all seen classes \protect\scalebox{0.75}{$\triangle$}; $\blacktriangle$ means classes appearing in test.} \label{fig:mixup} \vspace{\figsep} \end{minipage}% \hspace{8pt} \begin{minipage}{0.55\textwidth} \centering \includegraphics[width=0.9\linewidth]{alpha} \caption{Illustration of {\em mixup transformation}. We obtain unseen classes \protect\scalebox{1}{\color{red}{\textbullet}} by linearly combining all seen classes \protect\scalebox{0.75}{$\triangle$}; $\blacktriangle$ means classes appearing in test} \label{fig:fig3} \vspace{\figsep} \end{minipage} \end{figure*} \end{comment} \subsection{Alignment-uniformity aware Loss} {\em Can alignment and uniformity properties be preserved in supervised contrastive loss?} For self-supervised learning, \cite{chen2020intriguing} claims that contrastive loss \cite{chen2020simple,qian2021spatiotemporal} (see Eq.~\ref{eq:self} and {\em supplementary}) preserves alignment and uniformity properties. Alignment indicates that positive samples should be mapped to nearby features and thus be invariant to unneeded noises. Uniformity \cite{wang2020understanding} means feature vectors should be roughly uniformly distributed on the unit hypersphere, thus bringing better generalization to downstream tasks. \noindent \begin{align} \mathcal{L}^{self} \!=& \!-\! \log[\frac{\exp{[\lambda \text{sim}(f, f_+)]}}{\sum_{f_- \in \mathcal{N} }\exp{[\lambda \text{sim}(f, f_-)]}}]. \label{eq:self} \vspace{\eqsep} \end{align} Here, $(f, f_+), (f, f_-)$ are positive and negative pairs of images/videos, $\mathcal{N}$ is negative set; sim means a similarity function (thus in [-1, +1]); and $\lambda$ is a temperature parameter. Closeness in alignment and maximal-info preserving in uniformity are also essential properties of the unified representation learning in ZSVC. However, existing work mainly focuses on the alignment of visual-semantic features \cite{zhu2018towards,bishay2019tarn,hahn2019action2vec,brattoli2020rethinking}, the uniformity that improves generalization has not been discussed yet. Here, by leveraging video labels, we formulate a supervised contrastive loss as the combination of alignment and uniformity terms: \begin{align} \label{eq:sup} \mathcal{L}^{sup}\! =& \!-\! \log[\frac{\exp{[\lambda \text{sim}(v_{y_i}, s_{y_i})]}}{\sum_{y_j \in \mathcal{Y} }\exp{[\lambda \text{sim}(v_{y_i}, s_{y_j})]}}],\\ \nonumber \!=&\lambda \text{SP}_\lambda [ \underbrace{-\text{sim}(v_{y_i}, s_{y_i})}_\text{alignment} \!+ \frac{1}{\lambda} \underbrace{\text{LSE}(\lambda\text{sim}(v_{y_i}, s_{y_j})_{y_j \in \mathcal{Y}\setminus y_i})}_\text{uniformity} ],\\ \nonumber &\text{where,}\quad \;\text{SP}_\lambda(x)\! =\! \frac{1}{\lambda}\log(1\!+\!\exp(\lambda x)),\\ \nonumber & \quad\quad\quad\quad \text{LSE}(x) \!=\! \log(\sum_{x\in\mathcal{X}}\exp(x)). \vspace{\eqsep} \end{align} $v_{y_i}$ and $s_{y_i}$ are visual and semantic features of class $y_i$, and the complete class set is $\mathcal{Y}$. $\text{SP}_\lambda$ means the SoftPlus function and LSE is LogSumExp. Since Eq.~\ref{eq:sup} favors $\text{sim}(v_{y_i}, s_{y_i})$ larger, visual and semantic features of the same class will be aligned. The uniformity term tends to maximize the distances between features of different classes using a LogSumExp function, thus spreading features as much as possible. To sum up, our $\mathcal{L}^{sup}$ preserves the alignment and uniformity properties simultaneously. {\bf $\mathcal{L}^{sup}$ performs better:} Comparing $\mathcal{L}^{sup}$ with $\mathcal{L}^{self}$, we observe that $\mathcal{L}^{sup}$ includes positive pair $\text{sim}(v_{y_i}, s_{y_i})$ in the denominator. Even recent work MUFI \cite{qiu2021boosting} and ER \cite{chen2021elaborative} also utilize supervised contrastive loss, not only do they neglect the alignment and uniformity properties, but also miss the similarity and difference between the two losses. Here, we show that $\mathcal{L}^{sup}$ maintains advantages of both $\mathcal{L}^{self}$ and triplet loss \cite{schroff2015facenet}. We derive upper bounds of $\mathcal{L}^{sup}$ and $\mathcal{L}^{self}$ as follows (the full derivation in {\em supplementary}): \begin{align} \label{eq:bound} \mathcal{L}^{self} \!&\leq\!\lambda(\text{sim}_\text{max}\!-\!\text{sim}(v_{y_i}, s_{y_i})+\frac{\log(K\!-\!1)}{\lambda}),\\\nonumber \mathcal{L}^{sup} \!&\leq\! \lambda\max[\text{sim}_\text{max}\!-\!\text{sim}(v_{y_i}, s_{y_i})\!+\!\frac{\log(K\!-\!1)}{\lambda}, 0] \!+\!\log(2), \vspace{\eqsep} \end{align} where $K$ is the number of classes, $\text{sim}_\text{max}$ is the maximal similarity among all negative pairs ($\text{sim}_\text{max} = \max_{y_j \in \mathcal{Y}\setminus{y}}\text{sim}(v_{y_i},s_{y_j})$). For a fair comparison, we also reformulate $\mathcal{L}^{self}$ with class labels and obtain its upper bound in Eq.~\ref{eq:bound}. With the upper bounds, we summarize the advantages of $\mathcal{L}^{sup}$ as follows: \begin{compactenum} \item When $\frac{\log (K-1)}{\lambda}\geq 2$, the two upper bounds will be similar. At this time, $\mathcal{L}^{sup}$ performs as well as $\mathcal{L}^{self}$ in a representation learning task. \item When $0\leq\frac{\log(K-1)}{\lambda}\textless 2$, the upper bound of $\mathcal{L}^{sup}$ has a similar form as triplet loss \cite{schroff2015facenet} that facilitates intrinsic ability to perform hard positive/negative mining. \item $\mathcal{L}^{sup}$ preserves the summation over all negatives in the denominator, thus improving discrimination among classes \cite{sohn2016improved}, which has the same motivation with contrastive learning that makes the embedding distribution uniform by increasing the number of negatives \cite{chen2020simple}. \end{compactenum} In this paper, we take advantage of $\mathcal{L}^{sup}$ to regularize the representations of both seen and synthetic unseen classes. \begin{figure*} \centering \includegraphics[width=0.95\textwidth]{mixup} \caption{ {\bf Illustration of Class Generator:} (a) Synthetic classes \protect\scalebox{1}{\color{red}{\textbullet}} are generated by linearly combining features of seen classes (\protect\scalebox{0.75}{$\triangle$} with colors); $\blacktriangle$ means test classes. (b) Feature transformation w/ different $\alpha$ synthesizes semantics covering various size of regions.} \label{fig:generator} \vspace{\figsep} \end{figure*} {\bf $\mathcal{L}^{sup}$ for seen and unseen classes:} We learn $\mathcal{L}^{sup}$ for both seen and unseen classes (see $\mathcal{L}_\text{contrast}$ in Eq.~\ref{eq:contrast} where we utilize $\cos$ as a cosine function and map features on the hypersphere.). Specifically, we learn $\mathcal{L}_\text{S}$ on visual-semantic features (\ie, $v_{y_i}$ and $s_{y_i}\in\mathbb{R}^{1\times d}, y_i\in\mathcal{Y}$) for seen classes set $\mathcal{Y}$. From the formulation of $\mathcal{L}_\text{S}$, we jointly align features of the same class and introduce uniformity that encourages semantic clusters to spread as much as possible, improving the possibility that features of unseen classes fall around existing ones. To offer effective positive/negative visual and semantic pairs that enhance the feature embedding \cite{zhu2021improving}, we propose a {\em class generator} to generate visual and semantic features of synthetic classes $\mathcal{U}$, which are considered as ``unseen classes" in comparison with seen classes $\mathcal{Y}$. To retain the {\em alignment-uniformity} properties, we utilize $\mathcal{L}_\text{US}$ to regularize visual and semantic features of $K_u$ unseen classes (\ie, the synthetic features $\Theta $ and $Z \in \mathbb{R}^{K_u\times d}$). \begin{align} \label{eq:contrast} \mathcal{L}_\text{contrast} \!= &\mathcal{L}_\text{S} + \mathcal{L}_\text{US}\\\nonumber =&\!-\! \log[\frac{\exp{[\lambda \text{cos}(v_{y_i}, s_{y_i})]}}{\sum_{y_j \in \mathcal{Y} }\exp{[\lambda \text{cos}(v_{y_i}, s_{y_j})]}}] + \\ \nonumber & \frac{1}{K_u}\sum_{u_i\in\mathcal{U}}\!-\! \log[\frac{\exp{[\lambda \text{cos}(\Theta_{u_i}, Z_{u_i})]}}{\sum_{u_j \in \mathcal{U} }\exp{[\lambda \text{cos}(\Theta_{u_i}, Z_{u_j})]}}]. \vspace{\eqsep} \end{align} \subsection{Class Generator} To synthesize visual and semantic pairs ($\Theta, Z$), we propose a class generator that applies a uniformly sampled linear transformation to all pairs of visual/semantic features of seen classes. Especially, instead of using single visual feature as the transformed features, we select representative ``visual centers" learned from a supervised video classifier that interprets the parameter matrix of fc layer as the centers, as commonly used in \cite{wang2017normface,wang2018additive,du2019explicit,press2016using}. We propose to exploit $\mathcal{L}_\text{C}$ as the classification loss, which is an angular softmax loss, helping push all visual features towards their visual centers on the unit hyperspher \cite{Deepcosine}. \begin{align} \label{eq:visual} \mathcal{L}_\text{C} = -\log \frac{\exp[\lambda\cos (v_{y_i}, w_{y_i})]}{\sum_{y_j \in \mathcal{Y}}\exp[\lambda\cos(v_{y_i}, w_{y_j})]}. \vspace{\eqsep} \end{align} Here, $v_{y_i}$ and $w_{y_i}$ indicate a single visual feature and the learned visual center, respectively. With the visual centers $w_{y_i}$ and the corresponding semantic features $s_{y_i}$, we inter-and extra-polates (\ie, linearly combine) these features to fill in incomplete class points on the hypersphere: \begin{align} \vspace{-10cm} \label{eq:generator} \Theta &= M \times \text{norm}(W),\\\nonumber Z &= M \times \text{norm}(s_{\mathcal{Y}}),\\\nonumber \text{norm}(W) &= [\frac{w_{y_1}}{\left\|w_{y_1}\right\|},\dots,\frac{w_{y_D}}{\left\|w_{y_D}\right\|}],\\\nonumber \text{norm}(s_{\mathcal{Y}}) &=[\frac{s_{y_1}}{\left\|s_{y_1}\right\|},\dots,\frac{s_{y_{D}}}{\left\|s_{y_{D}}\right\|}]. \vspace{\eqsep} \end{align} Here, $\Theta$ and $Z$ $\in\mathbb{R}^{K_u\times d}$ separately represent the synthetic visual centers and semantic features of unseen classes; $K_u$ represents the number of unseen classes and $d$ is the feature dimension. Besides, we apply normalization on $W$ and $s_\mathcal{Y}$ (both are $D\times d$ matrix) because learning on a unit hypersphere helps model optimization \cite{wang2020understanding}; $D$ is a hyper-parameter that means how many classes are sampled for unseen-class generator. The matrix $M\in\mathbb{R}^{K_u\times D}$ is used for inter- and extra-polations, whose elements are randomly sampled from a uniform distribution $U(\alpha, 1)$, and $-1\leq\alpha\textless 1$. $\alpha$ is another hyper-parameter that controls the distributed range of the synthetic points. It is worth noting that the settings of hyper-parameters $D$ and $\alpha$ are non-trivial. For $D$, we prefer $D \geq d$, \ie, the number of seen classes should be larger than the dimension of a hypersphere. Because for a full rank matrix $W$, a linear combination of the column vector of $W$ can express any vector on the transformed space. We aim to generate as diverse unseen classes as possible to improve the possibility that the synthesized points can cover the classes in the test set. Thus, in experiments, we will select features of {\em all} seen classes for feature transformation. For $\alpha$, we choose positive values for interpolation where the synthetic clusters locate inside of seen points (see Fig.~\ref{fig:generator}(b)), and gradually enlarge the cluster regions by decreasing $\alpha$ where the negative value is for extrapolation. Fig.~\ref{fig:generator} (a) illustrates our {\em Class Generator} with $D=10, d=3, \alpha=-1$ on the Kinetics-700 dataset \cite{kay2017kinetics}. We can see our transformation not only provides unseen classes but also approaches test classes (\eg, UCF101 dataset \cite{soomro2012dataset}). \subsection{Closeness and Dispersion} To quantify the alignment and uniformity, we introduce two metrics: closeness and dispersion. Closeness measures the mean distance of features within the same class, reflecting the alignment of visual and semantic features. \begin{align} \label{eq:closeness} \text{Closeness} = \frac{1}{K}\sum_{y_i\in\mathcal{Y}}[\frac{1}{N_{y_i}}\sum_{n=1}^{N_{y_i}}(1-\cos{(v^{n}_{y_i},s^{n}_{y_i}}))], \vspace{\eqsep} \end{align} where, $N_{y_i}$ is the \# of training videos of class $y_i$. Besides, to evaluate the uniformity/separation of semantic clusters, we adopt minimal distances among all clusters to compute dispersion. Here, we consider all visual features within the same class as a semantic cluster instead of using one single semantic vector $s_{y_i}$. For example, $\bar{v}_{y_i}$ is the mean of visual features of the class $y_i$, and indicates one semantic cluster. \begin{align} \label{eq:dispersion} \text{Dispersion} &= \frac{1}{K}\sum_{y_i\in\mathcal{Y}}\min_{y_k\in\mathcal{Y}\setminus{y_i}}(1-\cos(\bar{v}_{y_i},\bar{v}_{y_k})). \vspace{\eqsep} \end{align} The experiments in Sec.~\ref{sec:ablation} show that models tested with higher accuracy preserve the lower closeness and higher dispersion in representations. We conclude our two metrics can serve as new measurements of model generalizability. \subsection{Training \& Inference} {\bf Training}: We end-to-end train visual and semantic features and jointly learn the contrastive loss $\mathcal{L}_\text{contrast}$ and classification loss $\mathcal{L}_\text{C}$, thus obtaining the following overall loss: \begin{align} \mathcal{L}_\text{AURL} = &\mathcal{L}_\text{S} + \mathcal{L}_\text{US} + \mathcal{L}_\text{C}. \end{align} We will justify our end-to-end training is critical for alignment and uniformity properties, and validate our compact model with $\mathcal{L}_\text{AURL}$ outperforms SoTA alternatives. {\bf Inference:} we train AURL on source dataset $\mathcal{I}$ with $K$ seen classes $\mathcal{Y}=\{y_1, \dots, y_K\}$, and evaluate the model on target dataset $\mathcal{I}^{t}$ with $T$ unseen classes $\mathcal{Y}^{t}=\{y^{t}_1, \dots, y^{t}_T\}$. In this paper, we follow the strict problem setting in \cite{brattoli2020rethinking}, which requires training classes $\mathcal{Y}$ have no overlap with test classes $\mathcal{Y}^{t}$. Mathematically, we re-write the requirement as: \begin{align} \forall {y \in \mathcal{Y}}, \; \min_{y^{t} \in \mathcal{Y}^{t}} (1-\cos(c_y, c_{y^{t}})) > \tau, \label{eq:label} \vspace{\eqsep} \end{align} where $c_i$ means Word2vec features of class i, $\tau$ is the distance threshold. We utilize the Nearest Neighbor Search (NNS) strategy to obtain the final label of query video $I^{t}$: \begin{align} \underset{y^{t} \in \mathcal{Y}^{t}}{\mathrm{argmax}} \cos(f_v(g(I^t)), s_{y^{t}}). \vspace{\eqsep} \label{eq:nns} \end{align} \subsection{Comparisons with Related Work} The closest studies to our AURL are SoTA \cite{brattoli2020rethinking}, MUFI \cite{qiu2021boosting}, and ER \cite{chen2021elaborative}. Table \ref{tab:related} summarizes their similarities and differences. SoTA only utilizes MSE loss to regularize feature alignment within seen classes, limiting model generalizability. MUFI and ER both implicitly increase semantic info to improve the generalization. MUFI trains multi-stream models across multiple datasets. ER crawls and annotates a number of web words to expand existing class names. Unlike that MUFI and ER both require extra resources, our AURL is a compact model to utilize the uniformity that helps preserve maximal info of existing features, and introduce a class generator to synthesize more semantics explicitly. Even MUFI and ER adopt the supervised contrastive loss, they neglect how alignment and uniformity properties affect ZSVC. Besides, our AURL follows the strict label requirement (in Eq.~\ref{eq:label}) that classes of training and test sets are far away from each other, which manifests the nature of ZSVC. At last, compared with ER that only trains the last fc layers, AURL utilizes a true e2e training strategy that is critical to realize the two properties. \begin{table} \centering\small \def\hspace{5pt}{\hspace{2.2pt}} \newcommand{\mv}[1]{\hspace{5pt} #1 \hspace{5pt}} \caption{Comparisons between AURL and alternative methods.} \rowcolors{1}{}{lightgray!80} \label{tab:related} \begin{tabular}{l*{5}{c}} \toprule {\bf Methods} & \mv{\bf{ET}} & \mv{\bf{AUL}} & \mv{\bf{ERF}} & \mv{\bf{UCG}} & \mv{\bf{SLR}}\\ \midrule SoTA \cite{brattoli2020rethinking} &$\times$ &$\times$ &$\checkmark$ & $\times$&$\checkmark$\\ MUFI \cite{qiu2021boosting} &$\times$ &$\times$ &$\times$ &$\times$&$\times$\\ ER \cite{chen2021elaborative}&$\checkmark$ &$\times$ &$\times$ &$\times$&$\times$\\ AURL (ours) & $\checkmark$ & $\checkmark$ & $\checkmark$ & $\checkmark$&$\checkmark$\\ \bottomrule \end{tabular} \vspace{-6pt} \flushleft{*{\bf ET}: end-to-end trainable, {\bf AUL}: alignment-uniformity learning, {\bf ERF}: extra resources free, {\bf UCG}: unseen class generator, {\bf SLR}: strict label requirement.} \vspace{\figsep} \end{table} \section{Experiments} \subsection{Settings} {\bf Datasets:} We train our AURL on the Kinetics-700 dataset \cite{kay2017kinetics} and evaluate it on UCF101 \cite{soomro2012dataset} and HMDB51 \cite{kuehne2011hmdb} datasets. The Kinetics-700 provides download links of YouTube videos annotated with 700 categories of human actions. We collect 555,774 videos using these links. The UCF101 contains 13,320 videos with 101 actions and the HMDB51 has 6,767 videos annotated with 51 actions. {\bf Training protocol:} For fair comparisons with the SoTA \cite{brattoli2020rethinking}, we select the training videos in Kinetics-700 whose classes have non-overlap with UCF101 and HMDB51 as described in Eq. \ref{eq:label}, and set the same $\tau$ = 0.05, thus obtaining 662 classes. AURL is inductive zero-shot learning, thus does not include any test data during training. {\bf Evaluation protocol:} Existing ZSVC methods adopt various evaluation protocols to report experimental results. For complete comparisons, we perform three protocols: 1, 3, and N test splits. 1 {\em test split} reports an accuracy on all videos of UCF101 or HMDB51 set. 3 {\em test splits} reports an average accuracy by averaging 3 accuracies that are separately evaluated on 3 test sets provided by the UCF101 or HMDB51. N {\em test splits} also reports the average by averaging N accuracies that are obtained by running N (10 in our method) times testing, in each, m classes are randomly selected (m=50 for UCF101 and m=25 for HMDB51). {\bf Implementation details:} We adopt one or multiple {\em video clips} as one input video of models. We follow the same SoTA settings \cite{brattoli2020rethinking} (\ie, 1 or 25 video clips and 16 frames/clip with size of $1\times16\times112\times112\times3$) for fair comparisons. If multiple video clips are used, we take the mean of multiple visual embeddings as the representative embedding. Besides, if a class name contains multiple words, we average the corresponding Word2vec features to represent the class prototype. For the AURL architecture, we set feature dimension of the R(2+1)D backbone as 512 (\ie, $g(I)\in\mathbb{R}^{512}$) and dimension of Word2vec as 300 (\ie, $c(\mathcal{Y})\in\mathbb{R}^{K\times300}$), and set the number of nodes in 3-layer MLP of the projector as 2048, 2048, and 2048 separately. During training, we empirically set $K_u$ as 662, $\lambda$ as 10, $D$ as 662, and $\alpha$ as 0. We deploy the training on 8 Nvidia Tesla V100 GPUs. We set batch size as 256 and synchronize all batch normalization across GPUs following \cite{chen2020simple,caron2020unsupervised}. We implement experiments using PyTorch and Horovod. SGD is our optimizer and a learning rate of 0.05 with a cosine decay schedule \cite{chen2020simple,loshchilov2016sgdr} is adopted. Then, we set the weight decay as 0.0001 and the SGD momentum as 0.9. The number of training iterations is 58,500 which takes 45 hours. \begin{figure*} \centering \includegraphics[width=0.95\textwidth]{loss} \caption{ {\bf Ablations:} The representations of ablations w/ MSE loss, our $\mathcal{L}_\text{S}$, e2e training, and the AURL. \protect\scalebox{1}{\textbullet} and \protect$\bigtriangleup$ represent visual and semantic features separately; colors are for different classes. Here, we randomly sample 10 classes from Kinetics-700 for visualization. } \label{fig:loss} \vspace{\figsep} \end{figure*} \subsection{Ablation Study} \label{sec:ablation} To analyze AURL, we performed extensive ablations that were trained on the Kinetics-700 and evaluated on UCF101 and HMDB51 using 1 {\em video clip} and 1 {\em test split} of evaluation protocols. Table~\ref{tab:ablations} summarizes the quantitative results. Fig.~\ref{fig:loss} visualizes the visual-semantic representation of ablations by sampling 10 classes from Kinetics-700 dataset and setting the features as 3-D for better visualization. We will justify: (1) our model that preserves alignment-uniformity properties performs better than the SoTA method \cite{brattoli2020rethinking} that focuses on alignment only; (2) end-to-end (e2e) training is critical to realize the two properties; (3) our AURL involving the class generator performs the best. From the justifications, we will show that our closeness and dispersion metrics can serve as new measurements of model generalizability. Here, we take the architecture of the SoTA \cite{brattoli2020rethinking} as our {\bf Base} model (\ie, base backbone + fc only for video parts). Per (1), we compare {\bf Base w/ MSE} (\ie, the SoTA) and {\bf Base w/ $\mathbf{\mathcal{L}_\text{S}}$}. From the accuracy in Table~\ref{tab:ablations}, {\bf Base w/ $\mathbf{\mathcal{L}_\text{S}}$} largely improves the results by (14.8\%, 35.1$\rightarrow$40.3) on UCF101 and by (13.6\%, 21.3$\rightarrow$24.2) on HMDB. Comparing the learned representation in Fig.~\ref{fig:loss} (a) {\bf w/ MSE} and (b) {\bf w/ $\mathbf{\mathcal{L}_\text{S}}$} , we observe the semantic clusters of (b) spread more than (a), but the alignment within classes gets worse, for example, visual and semantic features are not calibrated for classes ``skipping rope" and ``abseiling". Similarly, we find the same trend in closeness and dispersion metrics shown in Fig.~\ref{fig:loss} and Table~\ref{tab:ablations}, where closeness gets worse (0.029$\rightarrow$0.065, 0.30$\rightarrow$0.45) but dispersion becomes much better (0.330$\rightarrow$0.414, 0.09$\rightarrow$0.29). We can see our {\bf Base w/ $\mathbf{\mathcal{L}_\text{S}}$} presesrving higher uniformity in the trained representation can achieve better generalization when making inference on the test set, even scarify a little alignment. Per (2), we involve {\bf e2e} training strategy (\ie, base backbone + video projector for video parts; word projector for semantic parts) to the {\bf Base w/ $\mathbf{\mathcal{L}_\text{S}}$}, and get the {\bf Base w/ $\mathbf{\mathcal{L}_\text{S}}$ + e2e}, which further improves the accuracy from 40.3 to 43.2 on UCF-101 and from 24.2 to 26.2 on HMDB. Not surprisingly, we observe the alignment is tuned better and uniformity is maintained in good quality, thus obtaining a better trade-off. Referring to Fig.~\ref{fig:loss} (b) and (c), we see {\bf Base w/ $\mathbf{\mathcal{L}_\text{S}}$ + e2e} encourages better uniformity that semantic clusters are relatively distributed uniformly across the hypersphere while achieves a satisfying alignment that visual and semantic features are apparently aligned (see classes ``skipping rope" and ``abseiling" again for comparisons). The similar trends also occur in closeness and dispersion metrics, \ie, (0.024 and 0.340; 0.30 and 0.29) in Fig.~\ref{fig:loss} and Table~\ref{tab:ablations}. We conclude that e2e is critical for adjusting features to meet the regularizations of alignment and uniformity. Per (3), we apply {\bf $\mathbf{\mathcal{L}_\text{US}}$} to unseen classes coupling with the class generator ({\bf CG}), \ie, our {\bf AURL}. Compared {\bf AURL} with {\bf Base w/ $\mathbf{\mathcal{L}_\text{S}}$ + e2e}, {\bf AURL} steadily improves 2.8\% on UCF and 4.6\% on HMDB, achieving the best accuracy. Quantitatively, closeness and dispersion reach the best scores, such as (0.29, 0.32) in Table~\ref{tab:ablations} and (0.020, 0.354) in Fig.~\ref{fig:loss}. From the representation of Fig.~\ref{fig:loss} (d), we see the semantic clusters cover most regions of the hypersphere, which improves the possibility that unseen features fall around existing points, thus bringing a better generalization. Furthermore, we remove {\bf CG} from AURL (\ie, {\bf AURL w/o CG}) to validate the effectiveness of the class generator. Comparing {\bf AURL} and {\bf AURL w/o CG}, we find that the performances of {\bf AURL w/o CG} on UCF and HMDB both decrease, and the accuracy on HMDB even degrades lower than {\bf Base w/ $\mathbf{\mathcal{L}_\text{S}}$ + e2e}. Thus, we conclude the {\bf CG} is a critical module to enhance the generalization. Last but not least, from the above justifications, we summarize that our models consistently improve the accuracy by involving the proposed modules; closeness/dispersion measured on the learned representations have agreements with the accuracy evaluated on test sets, providing model evaluations even prior to making inference. \def\hspace{5pt}{\hspace{3pt}} \begin{table}[t] \small \centering \caption{ Ablations of our modules using 1 video clip under the {\em 1 test split} protocol ($\tau$=0.05). {\color{red}{Red}} numbers indicate the best. Closeness$\downarrow$ better, dispersion$\uparrow$ better, and top-1 accuracy $\uparrow$ better.} \label{tab:ablations} \begin{tabular}{@{}l@{\hspace{5pt}}|c@{\hspace{5pt}}c@{\hspace{5pt}}c@{\hspace{5pt}}|c@{\hspace{7pt}}c@{\hspace{7pt}}|c@{\hspace{5pt}}c@{}} \toprule {\bf Method} & {\bf $\mathbf{\mathcal{L}_\text{S}}$} &\bf{e2e} & \shortstack{{\bf $\mathbf{\mathcal{L}_\text{US}}$}\\ +{\bf CG}} &\shortstack{\bf{Clo-} \\ \bf{se.}}&\shortstack{\bf{Dis-} \\ \bf{per.}} &\shortstack{\bf{UCF} \\ \bf{top-1}}& \shortstack{\bf{HMDB} \\ \bf{top-1}}\\ \midrule \bf{Base w/ MSE} && & &0.30&0.09&35.1&21.3\\ \bf{Base w/ $\mathbf{\mathcal{L}_\text{S}}$} &\checkmark&&&0.45&0.29&40.3&24.2\\ \bf{Base w/ $\mathbf{\mathcal{L}_\text{S}}$ + e2e} &\checkmark& \checkmark &&0.30&0.29&43.2&26.2\\ \rowcolor{gray!10} \bf{AURL (ours)} &\checkmark&\checkmark &\checkmark &{\color{red} 0.29}&\color{red}{0.32}&\color{red}{44.4}&\color{red}{27.4}\\ \bf{AURL w/o CG} &\checkmark&\checkmark &$\bcancel{\text{CG}}$ & 0.33 &0.32&43.7&25.8\\ \bottomrule \end{tabular} \vspace{\figsep} \end{table} \subsection{Comparisons with the Closest SoTA} The closest SoTA to our AURL is the recent work \cite{brattoli2020rethinking}, which utilizes a compact model that achieves the SoTA results even under a strict setting (\ie, Eq.~\ref{eq:label}). Table \ref{tab:related} summarizes the similarity and difference between the SoTA and our AURL. Table \ref{tab:closest} shows the comprehensive comparisons quantitatively. We reported the SoTA results using the same settings and the authors’ released code. For comprehensive comparisons, we include various evaluation protocols including Pre-training, Video clips, and Test splits. Pre-training means that SoTA fine-tunes the pre-trained models on the SUN dataset \cite{xiao2010sun}. From the comparisons, we see our AURL consistently surpasses the SoTA under each evaluation protocol. Specifically, the smallest improvements happen at (25 Video clips, 1 Test splits) by (17.6, 16.5)\% improvements on UCF top-1 and HMDB top-1, and the largest comes at (1 Video clip, 10 Test split) by (28.1, 27.0)\% increases on UCF top-1 and HMDB top-1. {\bf To conclude, AURL outperforms the SoTA by a large margin.} \def\hspace{5pt}{\hspace{3.1pt}} \begin{table}[t] \small \centering \caption{ Comparisons with the closest SoTA \cite{brattoli2020rethinking} on both UCF and HMDB datasets. {\color{red}{Red}} numbers indicate the best.} \label{tab:closest} \begin{tabular}{@{}l@{\hspace{2pt}}|c@{\hspace{5pt}}c@{\hspace{5pt}}c@{\hspace{5pt}}|c@{\hspace{5.2pt}}c@{\hspace{5.2pt}}c@{\hspace{5pt}}c@{}} \toprule \rb{4}{\ {\bf Method}\ } & {\shortstack{{\bf Pre-}\\{\bf training}}} &{\shortstack{{\bf Video}\\{\bf clips}}} &{\shortstack{{\bf Test}\\{\bf splits}}} &{\shortstack{{\bf UCF}\\{\bf top-1}}}&{\shortstack{{\bf UCF}\\{\bf top-5}}}&{\shortstack{{\bf HMDB}\\{\bf top-1}}}&{\shortstack{{\bf HMDB}\\{\bf top-5}}}\\ \midrule &~ &1 &10 &43.0 &68.2 &27.0&54.4\\ \multirow{-2}{*}{SoTA}&\checkmark &1 &10 &45.6 &73.1 &28.1 &51.8 \\ \rowcolor{gray!10} AURL & &1 &10 & {\color{red} 55.1} &{\color{red} 79.3} &{\color{red} 34.3} &{\color{red} 65.1}\\ \midrule & &25 &10 &48.0 &74.2 &31.2 &58.3\\ \multirow{-2}{*}{SoTA} &$\checkmark$ &25 &10 &49.2 &77.0 &32.6 &57.1 \\ \rowcolor{gray!10} AURL & &25 &10 &{\color{red} 58.0} &{\color{red} 82.0} &{\color{red} 39.0} &{\color{red} 69.5}\\ \midrule & &1 &1 &35.1 &56.4 &21.3 &42.2\\ \multirow{-2}{*}{SoTA}&\checkmark &1 &1 &36.8 &61.7 &23.0 &41.3\\ \rowcolor{gray!10} AURL & &1 &1 &{\color{red} 44.4} &{\color{red} 70.0} &{\color{red} 27.4} &{\color{red} 53.2}\\ \midrule & &25 &1 &37.6 &62.5 &26.9 &49.8\\ \multirow{-2}{*}{SoTA} &$\checkmark$ &25 &1 &39.8 &65.6 &27.2 &47.4\\ \rowcolor{gray!10} AURL & &25 &1 &{\color{red} 46.8} &{\color{red} 73.1} &{\color{red} 31.7} &{\color{red} 58.9}\\ \bottomrule \end{tabular} \vspace{\figsep} \end{table} \subsection{Comparisons with the Alternatives} Table \ref{tab:comparisons} shows the comparisons with the alternatives. The SoTA \cite{brattoli2020rethinking} and our AURL with $\star$ mean the two methods follow the strict label requirement in Eq.\ref{eq:label}. From the results, we observe that our AURL surpasses all the alternatives in various challenging situations. Specifically, we summarize the challenges: first, fewer test splits are harder testing situations, \eg, for SAOE \cite{mettes2017spatial}, 3 \vs 10 splits corresponds to 32.8 \vs 40.4 on UCF; second, strict label requirement ($\star$) serves more difficult situation, \eg, our AURL$^\star$ w/ 10 (the more) test splits achieves even worse results than AURL w/ 3 splits; third, some methods acquire extra training datasets (\eg, Kinetics + extra 5 datasets trained in MUFI \cite{qiu2021boosting}), additional semantic classes (\eg, web words used in ER \cite{chen2021elaborative} ), and even training videos sampled from the same domain as the test set (\eg, tr/te are both UCF or HMDB in TARN \cite{bishay2019tarn}, Act2Vec \cite{hahn2019action2vec}, PSGNN \cite{gao2020learning}, and ER \cite{chen2021elaborative}), which provide more difficulties to be competed against for other methods. Correspondingly, we find the superiority of our AURL as below: (1) AURL w/ 1 (the fewest) test split outperforms most methods w/ 3 or 50 splits, \eg, (46.8, 31.7) of AURL \vs (36.3, -) of OPCL and (43.0, 32.6) of PSGNN on (UCF, HMDB) dataset; (2) AURL$^\star$ w/ more strict requirements but w/o extra datasets competes against all the SoTA alternatives, \eg, (58.0, 39.0) of AURL \vs (51.8, 35.3) of ER, and (56.3, 31.0) of MUFI on (UCF, HMDB) dataset. {\bf To sum up, our AURL reaches the new SoTA in ZSVC}. Finally, we conduct AURL$^\star$ with pre-extracted features (trained only on video and word projectors). We observe AURL w/ pre-extracted features achieves comparable performance with the e2e AURL -- (59.5, 38.2) \vs (58.0, 39.0) on UCF and HMDB. This suggests AURL can achieve high performance without carefully finetuning video features. {\bf Limitations and possible solutions.} Even our AURL achieves promising results, there are still two problems to be concerned. (1) Uniformity of visual features within classes could be included to further increase info-preserving, introducing contrastive learning between videos may be a possible solution. (2) It will be helpful to study how the class generator affects the overall optimization during training. \def\hspace{5pt}{\hspace{5pt}} \begin{table}[t] \small \centering \caption{ Comparisons with SoTA alternatives on both UCF and HMDB datasets. Results of alternatives were obtained from original papers, and the higher, the better. {\color{red}{Red}} and {\color{blue}{blue}} numbers indicate the best and second best. $\star$ means using $\tau$=0.05 in Eq.\ref{eq:label}.} \label{tab:comparisons} \begin{tabular}{@{\hspace{10pt}}l@{\hspace{5pt}}|c@{\hspace{5pt}}|c@{\hspace{5pt}}c@{\hspace{5pt}}|c@{\hspace{5pt}}c@{\hspace{5pt}}} \toprule {\bf Method} &{\shortstack{{\bf Test}\\{\bf splits}}}&{\shortstack{{\bf Train}\\{\bf dataset}}}&{\shortstack{{\bf UCF}\\{\bf top-1}}} &{\shortstack{{\bf Train}\\{\bf dataset}}}&{\shortstack{{\bf HMDB}\\{\bf top-1}}}\\ \midrule SoTA$^{\star}$ \cite{brattoli2020rethinking} &1 &Kinetics&37.6 &Kinetics&26.9\\ \rowcolor{gray!10} AURL$^{\star}$ & 1 &Kinetics&{\color{red} 46.8} &Kinetics&{\color{red} 31.7}\\ \midrule Obj2act \cite{jain2015objects2action}&3 &-&30.3 &-&15.6\\ SAOE \cite{mettes2017spatial}&3 &-&32.8 &-&-\\ OPCL \cite{gao2020learning}&3 &-&36.3 &-&-\\ MUFI\cite{qiu2021boosting} &3 &Kinetics+&{\color{blue} 56.3} &Kinetics+&{\color{blue} 31.0}\\ \rowcolor{gray!10} AURL &3 &Kinetics&{\color{red} 60.9} &Kinetics&{\color{red} 40.4}\\ \midrule TARN \cite{bishay2019tarn} &30 &UCF&23.2 &HMDB&19.5\\ Act2Vec \cite{hahn2019action2vec}&- &UCF&22.1 &HMDB&23.5\\ SAOE\cite{mettes2017spatial} &10 &-&40.4 &-&-\\ PSGNN \cite{gao2020learning} &50 &UCF&43.0 &HMDB&32.6\\ OPCL \cite{gao2020learning}&10 &-&47.3 &-&-\\ SoTA$^{\star}$\cite{brattoli2020rethinking} &10 &Kinetics&48.0 &Kinetics&{32.7}\\ DASZL \cite{kim2021daszl} &10 &-&{48.9} &-&-\\ ER \cite{chen2021elaborative} &50 &UCF&\color{blue}{51.8}&HMDB&\color{blue}{35.3}\\ \rowcolor{gray!10} AURL$^{\star}$ &10 &Kinetics&{\color{red} 58.0} &Kinetics&{\color{red} 39.0}\\ \bottomrule \end{tabular} \vspace{\figsep} \end{table} \section{Conclusion} This paper learns representation awareness of both alignment and uniformity properties for seen and unseen classes. We reformulate a supervised contrastive loss to jointly align visual-semantic features and encourage semantic clusters to distribute uniformly. To explicitly synthesize features of unseen semantics, we propose a class generator that performs feature transformation on features of seen classes. Besides, we introduce closeness and dispersion to quantify the two properties, providing new measurements for generalization. Extensive ablations justify the effectiveness of each module in our model. Comparisons with the SoTA alternatives validate our model reaches the new SoTA results. {\bf Acknowledgement.} Research was supported by Natural Science Foundation of China under grant 62076036. {\small \bibliographystyle{ieee_fullname}
{'timestamp': '2022-03-30T02:27:17', 'yymm': '2203', 'arxiv_id': '2203.15381', 'language': 'en', 'url': 'https://arxiv.org/abs/2203.15381'}
arxiv
\section{Introduction}\label{sec:introduction} According to \cite{Corbett:2000:Number}, grammatical number in English can be conceptualized as a `feature' \citep[see also][]{Jakobson:1928} with two opposing values: singular and plural. For English, the formal realization of the nominal plural is the addition of the suffix \textit{-s}, a marker whose absence signals the nominal singular. Textbooks such as \citet{Lieber:2010} and \citet{aronoff2011morphology} take the semantics of plurality for granted and call attention to the way in which the plural is realized. According to \citet[][p. 156]{aronoff2011morphology}, number is generally not marked in the English lexicon, with the exception of pluralia tantum such as {\em pants}. Two major approaches to morphology, compositional and realizational morphology, analyze English pluralization in subtly different ways. In compositional models, pluralization is argued to be a process that operates on the less complex word (the singular) and results in the more complex word (the plural). The \textit{morpheme} \textit{-s} is concatenated with the stem, and in parallel, the abstract meaning `plural' that is registered in the \textit{lexical entry} of the \textit{morpheme} \textit{-s} overrides the singular meaning associated with the stem. In realizational models, the semantic part of the \textit{word-schema} for plural nouns contains the description `plurality of $x$s' to capture the semantic similarity of all things plural while abstracting away from their differences; hence the use of the variable `$x$'. The schema for plural nouns stands in correspondence to a schema for singular words with the same semantic symbol `$x$' \citep{Haspelmath:Sims:2010,Booij:2010}. The operator `plurality of' is assumed to implement the same semantic change for all instances `$x$' to which it is applied. While compositional models and realizational models are rather different with respect to how they view the relationship between form and meaning at the level of sub-word units, they are in remarkable agreement when it comes to how the semantics of number for nouns is understood. Both models assume that English plural formation amounts to a change in form that goes hand in hand with the addition of an abstract semantic feature of plurality to a singular word, shifting its denotation from one entity to more than one entity. As a matter of fact, formal semantics also has assumed a simple theory of plural meaning. \cite{Lasersohn:1995} opens with ``Plurality is a simple notion -- it just means `more than one'.'' Similarly, \cite{Link:1983} in his study of the logical analysis of plurals restricts the domain of entities from which singular nominals take values to atoms (or, ordinary individuals), and plural nominals to non-atomic summations of more than one atom. This interpretation of the plural nominal is often called \textit{exclusive} since it excludes atoms from its denotation \citep{Farkas:deSwart:2010}. It applies to the example \ref{ex:1-a} below. Although an exclusive interpretation of plural meaning is often fine, there are cases where a plural can refer inclusively to one or more entities, as in \ref{ex:1-b}. Here, \textit{children} in \ref{ex:1-b} is number neutral -- it can mean `one' child or `more than one' children. This is an \textit{inclusive} interpretation that includes atoms and non-atomic sums in its denotation. \ex. \a. You're welcome to bring your two children. \label{ex:1-a} \b. You're welcome to bring your children. \label{ex:1-b} \z. \citep[adapted from][]{Sauerland:Anderssen:Yatsushiro:2005} Following the maximize presupposition principle in pragmatics \citep{Heim:1991}, \citet{Sauerland:Anderssen:Yatsushiro:2005} and \citet{Liter:Heffner:Schmitt:2017} argue that an exclusive interpretation of a plural form is a consequence of pragmatic inference, which depends on a range of contextual factors \citep{Chemla:2008}. In a situation where the speaker is unsure of the addressee's number of children, \ref{ex:1-b} is appropriate and \ref{ex:2-a} is odd. Assuming that these two sentences are in competition, the use of the singular \textit{child} in \ref{ex:2-a} is blocked because we know from experience that people may have more than one child and the sentence in \ref{ex:1-b} with stronger presuppositions is preferred. \ex. \textbf{Context}: People can have more than one child. \a. *You're welcome to bring your child. \label{ex:2-a} \z. \citep[adapted from][]{Sauerland:Anderssen:Yatsushiro:2005} In other words, a plural form can be used to denote an unspecified quantity (one, more than one, one or more than one) \citep[see also][]{Mattens:1970} and the exact quantity has to be resolved through interpretation from context. A principal presupposition that underlies this approach to plurality is that the conceptualization of the number feature is orthogonal to the meaning of the nominal phrase. \cite{Sauerland:2003} argues for an additional syntactic (zero) head above the determiner phrase which contains the number feature and its semantic content. In what follows, we question this presupposition by using distributional semantics (DS). DS represents words' meanings with high-dimensional numeric vectors, which we will refer to primarily as `semantic vectors' and alternatively as `word embeddings'---as they are known in Natural Language Processing (NLP). Distributional semantics builds on the hypotheses that words that are similar in meaning occur in similar contexts \citep{Rubenstein:Goodenough:1965} and ``words that occur in the same contexts tend to have similar meaning'' \citep{Pantel:2005}. There are many different ways in which semantic vectors for words can be constructed. Early implementations made use of word by document contingency tables \citep{Landauer:Dumais:1997} or word by context-word contingency tables \citep{Lund:Burgess:1996,Shaoul:Westbury:2010}. These tables typically yield very high-dimensional vectors with thousands or tens of thousands of dimensions. By means of dimensionality reduction techniques such as singular value decomposition, the dimensionality of semantic vectors is substantially reduced. \citet{Landauer:Dumais:1997} recommended 300-dimensional vectors, as in their experience lower-dimensional vectors performed with higher accuracy in a range of tasks such as synonymy detection. More recent models make use of artificial neural networks that are trained to predict target words from the words in their immediate context \citep[e.g., CBOW;][]{Mikolov:Chen:Corrado:Dean:2013} or to predict the words in the immediate context of a target word from that target word \citep[e.g., Skip-gram;][]{Mikolov:Chen:Corrado:Dean:2013}. A simple three-layer neural network for the Skip-gram model was implemented by \cite{Mikolov:Sutskever:Chen:Corrado:Dean:2013}, using stochastic gradient descent and back-propagation of error. The model was trained on 100 billion words from the Google News corpus, and the resulting {\tt word2vec} semantic vectors were made available at \url{https://code.google.com/archive/p/word2vec/}. Other word embeddings extend the word2vec methodology by incorporating character n-grams of words \citep[fastText;][]{Bojanowski:2017:fastText} or by modifying the objective function being optimized \citep[GloVe;][]{Pennington:2014:GloVe}. All these methods extract the semantic vectors purely from textual information. Other studies integrate visual information on top of that and create multi-modal embeddings \citep[e.g.,][]{Shahmohammadi:Lensch:Baayen:2021}. Word embeddings are employed advantageously in several tasks within NLP such as named entity recognition, part of speech tagging, sentiment analysis, word sense disambiguation \citep{Wang:Wang:Chen:Wang:Kuo:2019}, and in many areas of psychology and psycholinguistics \citep{Gunther:Rinaldi:Marelli:2019}. \cite{Boleda:2020} discusses their relevance for theoretical linguistics in the areas of diachronic semantic change, polysemy, and the interface between semantics and syntax or semantics and morphology. The traditional demarcation of morphology and semantics in linguistics is less prominent in DS models. Nevertheless, the statistics used in these models have been shown to encode morphological and syntactic information besides semantic information \citep{Westbury:Hollis:2019}. For morphologically related words, measurements from DS models, such as vector similarity, are consistent with human semantic similarity ratings and lexical decision latencies \citep{Rastle:Davis:Marslen-Wilson:Lorraine:2000, Rastle:Davis:New:2004,MoscosodelPradoMartin:Deutsch:Frost:Schreuder:Jong:Baayen:2005, Milin:Kuperman:Kostic:Baayen:2009}. The degree of semantic transparency in English derivation \citep{Marelli:Baroni:2015} and Dutch compounds \citep{Heylen:DeHertog:2012} were explained by DS similarity measures. Findings of \cite{Smolka:Preller:Eulitz:2014} regarding the effect of semantic transparency on morphological priming of German complex verbs were replicated with DS similarity measures by \cite{Pado:Zeller:Snajder:2015} \citep[although][could not fully replicate the latter study]{Shafaei:2017:thesis} \citep[see also][]{Baayen:Smolka:2020}. \cite{Shen:Baayen:2021} find that semantic transparency measured by DS is linked to the productivity of adjective–noun compounds in Mandarin. DS models used in investigating the paradigmatic relation between two Indonesian prefixes \citep{Denistia:Shafaei:Baayen:2021} corroborated the findings of earlier corpus-based analyses. The discriminative lexicon model of \cite{Baayen:Chuang:Shafaei:Blevins:2019} is a computational model of lexical processing, including morphologically complex words, that incorporates insights from distributional semantics for the representation of word meanings. In what follows, we utilize word embeddings to study the meaning of English nominal pluralization. DS models from machine learning produce semantic vectors for both singular and plural word forms. However, in order to be useful for the study of morphology, we need to consider additional questions: What does the process of English pluralization, i.e., going from the singular to the plural semantics, mean in this context? How can we model this process? Given a singular meaning, can we conceptualize the plural, and conversely, given the plural meaning, can we conceptualize the singular? As it is more likely that we encounter previously unseen plurals of known singulars, than previously unseen singulars given known plurals, we focus specifically on the productivity of the conceptualization of plural forms and ask: How well can we estimate the semantics of previously unseen plural words? And how does form relate to the estimations for meaning? In the following section, we first introduce the corpus used in the present study. Sections \ref{sec:realizational-morphology} and \ref{sec:compositional-morphology} investigate the aforementioned questions using methods inspired by realizational morphology and compositional morphology, respectively. In doing so, we illustrate that the widespread assumption in morphology about plural meaning is too simplistic, and we study alternative approaches that stay closer to the actual complexity of noun pluralization in English. In section \ref{sec:ldl}, the semantic vectors developed by the best-performing methods (formalizing realizational and compositional morphological theories) are put to use in a word comprehension model \citep[based on the discriminative lexicon model by][]{Baayen:Chuang:Shafaei:Blevins:2019} to study which kind of vectors are optimal for the recognition of previously unseen plural words. A discussion of the findings concludes the study. \section{Data}\label{sec:data} The corpus data used in this study is taken from the NewsScape English Corpus \citep{Uhrig:2018, Uhrig:Habil}. The corpus consists of 269 million tokens from the subtitles of more than 35,000 hours of recordings of US-American TV news collected in the UCLA Library Broadcast NewsScape \citep{Steen:etal:2018}. After capture, the recordings undergo compression, during which the audio channel is recoded into a 96 kbit/sec AAC stream with the Fraunhofer FDK library. For this project, the subtitles collected in the NewsScape text files were processed in an NLP pipeline. In a first step of this pipeline, sentence splitting was carried out with a purpose-built splitter that takes into account the fact that captions are transmitted in upper case. The resulting sentences were processed with Stanford CoreNLP \citep{Manning:etal:2014:CoreNLP} version 3.7.0, i.e. with PTB3 tokenization. The caseless model included in CoreNLP1 was used to tag every word with a Penn Treebank part-of-speech tag.\footnote{Note that the caseless mode is only available for the left3distsim model but not for the slower but usually better bidirectional tagger model.} Then CoreNLP’s TrueCase annotator was deployed, which overwrites the original text for further processing (preserving the original on a separate level). Dependency Parsing, Named-Entity Recognition and any further processing steps are then based on the case-restored text to ensure consistent results from tools that do not offer caseless models. After the NLP pipeline, the data was run through a modified version of the forced alignment system Gentle \citep{Ochshorn:Hawkins:2015:Gentle}, which basically runs an automatic speech recognition process with a language model created from the subtitles and then attempts to match the recognized words with the words in the subtitles. The quality of the forced alignment results crucially depends on the accurateness of the transcript it is fed. However, TV subtitles are not exact transcripts. Not only do they often ignore disfluencies such as false starts, but they also omit words and sometimes even change them. The commercials included in the recordings do not systematically come with subtitles either. Thus, Gentle only aligns between 90 and 95 percent of the words in the subtitles successfully, and of these, 92.5\% in a manual evaluation were deemed to be aligned correctly by a human annotator listening to them \citep{Uhrig:Habil}. We have to bear in mind, though that the cutoff points may not have been exact on these words. To increase the quality of the dataset used in the present study, only files where Gentle reported at least 97\% of successfully aligned words were used. Words' meanings are represented with semantic vectors of word2vec, which is widely used within NLP and theoretical linguistics. The nearest neighbors of a target word in this semantic space are often semantically similar (e.g., \textit{good} and \textit{great}) or related (\textit{good} and \textit{bad}) words. The top 10 closest neighbors to \textit{Germany} are \textit{German}, \textit{Europe}, \textit{European}, \textit{Sweden}, \textit{Switzerland}, \textit{Austria}, \textit{France}, \textit{Spain}, \textit{Poland}, and \textit{Russia}. \cite{Wang:Wang:Chen:Wang:Kuo:2019} show that similarities computed between pairs of word2vec vectors are highly correlated ($r(2998)=0.72$) with similarity ratings between word pairs obtained from human subjects in the MEN data set \citep{Bruni:Tran:Baroni:2014}, and that word2vec vectors are best performing on syntactic word analogy tasks (see section \ref{sec:realizational-morphology}) juxtaposed with 5 other semantic spaces. \cite{Westbury:Hollis:2019} argue that \cite{Mikolov:Chen:Corrado:Dean:2013}'s approach for training of the word2vec vectors is closely related to the cognitively plausible learning rule of \cite{Rescorla:Wagner:1972}. We compiled a \textit{noun pluralization} dataset with 14,699 singular-plural noun pairs from the NewsScape English Corpus with a word2vec vector. Proper names, plurals endings with anything other than an \textit{-s}, plural-singular pairs with the same word-form, and named entities were excluded from the dataset. A second set brought together 500,000 tokens of 14,640 orthographic word types from more than 100 television programs in the NewsScape English Corpus with no restriction on their morphological and syntactic categories. The 13,902 words from this set that have a vector available in word2vec compose a \textit{vocabulary} dataset. \section{Pluralization with realizational morphology} \label{sec:realizational-morphology} Realizational morphology \citep[also known as word and paradigm morphology;][]{Matthews:1991:Morphology,Stump:2001} posits whole words rather than morphemes as the basic units. A central notion in this theory is the paradigm. In English, the inflectional paradigm for the verb \textit{talk} is \{\textit{talk, talks, talked, talking}\} and for the noun \textit{talk} is \{\textit{talk, talks}\}. Productivity of the lexicon as a system emerges from proportional analogies between words within paradigms, such as $talk:talks :: walk:walks$ (\textit{talk} is to \textit{talks} as \textit{walk} is to \textit{walks}). \subsection{Proportional analogies with word embeddings} Analogical reasoning using word embeddings has been studied for different types of analogical relations including semantic analogies, such as $$man:king::woman:queen,$$ derivational analogies, as in $$quiet:quietly::happy:happily,$$ and inflectional analogies similar to \begin{equation}\label{eq:inflectional-analogy-example} pen:pens::table:tables. \end{equation} \noindent Various implementations of proportional analogies with word embeddings have been worked out, such as 3CosAdd \citep{Mikolov:Yih:Zweig:2013}, 3CosMul \citep{Levy:Goldberg:2014}, LRCos, and 3CosAvg \citep{Drozd:Gladkova:Matsuoka:2016}. Performance varies extensively for the different methods and the different types of analogical relations. \cite{Rogers:Drozd:Li:2017} report that, for English, analogical reasoning with embeddings is most successful for inflectional analogies across different methods. These methods are considered below in the context of plural formation. Most of the aforementioned methods operate on three input vectors to estimate a vector for the target word in a given analogy. For instance, to implement the analogy in (\ref{eq:inflectional-analogy-example}), 3CosAdd predicts a vector for \textit{tables}, labeled $\overrightarrow{tables}_p$, by computing \begin{equation} \overrightarrow{tables}_p= \overrightarrow{pens}-\overrightarrow{pen}+\overrightarrow{table}. \end{equation} The word selected as the predicted plural is the word the vector of which is closest to the composed vector, $\overrightarrow{tables}_p$ in (\theequation), in terms of cosine similarity. As a consequence, evaluation of these methods is restricted to predefined analogy test sets such as Google's \citep{Mikolov:Chen:Corrado:Dean:2013} which provide a series of analogies similar to the examples above. Another limitation of these methods is that their prediction for the target word \textit{tables} highly depends on the prime word pair, here \textit{pen} and \textit{pens}, and not on just the singular word \textit{table} \citep{Rogers:Drozd:Li:2017}. Thus, the predicted plural vector for \textit{tables} is different when the prediction builds on another analogy such as $$banana:bananas::table:tables.$$ \noindent 3CosAvg, on the other hand, operates on just one input vector, the vector of the base word. Given the input word \textit{table}, the predicted plural vector by 3CosAvg is $$ \overrightarrow{tables}_p=\overrightarrow{table}+\overrightarrow{\textsc{avg shift}}. $$ \noindent The word selected as the plural form is again, exactly as for 3CosAdd, that word the vector of which is closest to the assembled vector. For plural analogies, \cite{Drozd:Gladkova:Matsuoka:2016} define the average shift vector as \begin{equation} \overrightarrow{\textsc{avg shift}} = \frac{1}{m} \sum_{i=1}^m \Vec{p_i} - \frac{1}{n} \sum_{i=1}^n \Vec{s_i}, \end{equation} assuming there are $m$ plural word-forms with vectors $\Vec{p_i}$ and $n$ singular word-forms with vectors $\Vec{s_i}$. The average shift vector is fixed given the data, and represents the semantics of pluralization, just as the plural vector in the discriminative lexicon model \citep{Baayen:Chuang:Shafaei:Blevins:2019} provides a fixed representation for plurality. For a dataset with $m$ plural and $m$ singular word-forms, the average shift vector, i.e., the difference vector between the average vector of plurals and the average vector of singulars, formulated in (\ref{eq:linear-property-of-offset-vector-line1}), is equal to the average vector of the difference vectors between plurals and singulars, formulated in (\ref{eq:linear-property-of-offset-vector-line3}): \begin{align} \overrightarrow{\textsc{avg shift}} &= \frac{1}{m} \sum_{i=1}^m \Vec{p_i} - \frac{1}{m} \sum_{i=1}^m \Vec{s_i} \label{eq:linear-property-of-offset-vector-line1}\\ &= \frac{1}{m} (\sum_{i=1}^m \Vec{p_i} -\sum_{i=1}^m \Vec{s_i})\nonumber\\ &= \frac{1}{m} \sum_{i=1}^m (\Vec{p_i} - \Vec{s_i}). \label{eq:linear-property-of-offset-vector-line3} \end{align} \noindent Henceforth, we refer to the vector $\Vec{p_i} - \Vec{s_i}$ for word $i$ as this word's individual \textit{shift vector}. Such a shift vector is exemplified in Figure~\ref{fig:shift-vector}. Importantly, if plural and singular forms for different lexemes are consistently used across similar contexts, as captured by word embeddings, then the difference between individual shift vectors and the average shift vector is expected to be small. \begin{figure}[th] \centering \includegraphics{shift-vector.pdf} \caption{Individual shift vector for the lexeme \textit{pen} is calculated as $\protect\overrightarrow{\text{pens}} - \protect\overrightarrow{\text{pen}}$.} \label{fig:shift-vector} \end{figure} A range of studies have adopted shift vectors to study the semantics of various lexical relations. For instance, \cite{Roller:Erk:Boleda:Gemma:2014} and \cite{Weeds:2014} used shift vectors for hypernymy detection. \cite{Bonami:Paperno:2018} used shift vectors to model inflectional and derivational contrasts in French, and \cite{Mickus:Bonami:Paperno:2019} made use of shift vectors for tracing contrasts in grammatical gender of nouns and adjectives. \subsection{Individual and average shift vectors} \label{subsec:shift-vectors} How well does an average shift vector approximate the shifts between individual singulars and their plurals? To address this question, we investigated what the individual shift vectors look like and whether the average shift vector is representative for the individual shift vectors. For each noun pair in the pluralization dataset represented by word2vec semantic vectors, we first calculated its individual shift vector by subtracting the singular vector from the plural vector. As a next step, we calculated the length (or magnitude), the direction, and the neighborhood structure of the shift vectors. We gauged the length of vectors with the $\ell _{2}$ norm, i.e., the Euclidean distance of a vector from the origin. Fig.~\ref{fig:boxplot-len-sg-pl-shift} shows notched box and whiskers plots for the length of singular, plural, and individual shift vectors. Vector lengths differed in the mean for singular, plural and shift vectors (Friedman test, $\tilde{\chi}^2(2) = 7201$, $p\ll 0.0001$). Pairwise Wilcoxon signed-rank test between groups with Bonferroni correction revealed significant differences in length for all pairwise comparisons (all $p\ll 0.0001$). Plural vectors are, on average, longer than singular vectors (the difference between the medians $\Delta \mathrm{MD}$ is 0.13). This fits well with the intuition that English plurals are semantically more complex than their corresponding singulars. Shift vectors are, on average, smaller than the singular ($\Delta \mathrm{MD}=0.43$) and the plural vectors ($\Delta \mathrm{MD}=0.56$), which is only to be expected given that the shift vectors are, by definition, difference vectors. Although the average length of the shift vectors is smaller than the average lengths of singular or plural vectors, shift vectors turn out to nevertheless be surprisingly long. Their range ($1.1-6.8$, $\mathrm{MD}=2.88$) is nearly as wide as the ranges of the singular vectors and the plural vectors. \begin{figure} \centering \includegraphics[width=0.8\textwidth]{w2v-len-sg-pl-shift.png} \caption Box plots for the length of 14,699 word2vec's singular, plural, and individual shift vectors. } \label{fig:boxplot-len-sg-pl-shift} \end{figure} We quantified the angles of vectors in word2vec's 300-dimensional vector space with respect to the standard unit vector $\Vec{e}_{300}$ in degrees, using (\ref{eq:theta}). This 300-dimensional unit vector has a 1 as the last element and zeros elsewhere. Notched boxplots for angle are presented in Fig.~\ref{fig:boxplot-angle-sg-pl-shift}. The range of angles for shift vectors is even more similar to the ranges of angles of the singular and plural vectors, compared to vector lengths. \begin{align}\label{eq:theta} \theta(\Vec{v}) &= \frac{180}{\pi} (\arccos { \frac{\Vec{v} \cdot \Vec{e}_{300}}{ \left\lVert \Vec{v}\right\rVert_2 \left\lVert \Vec{e}_{300}\right\rVert_2 }) } \nonumber \\ &= \frac{180}{\pi} (\arccos {\frac {v_{300}}{{\sqrt {\sum \limits _{i=1}^{300}{v_{i}^{2}}}}}}) \end{align} \begin{figure} \centering \includegraphics[width=0.8\textwidth]{w2v-angle-sg-pl-shift.png} \caption{Box plots for the angle of 14,699 word2vec's singular, plural, and individual shift vectors. } \label{fig:boxplot-angle-sg-pl-shift} \end{figure} Fig.~\ref{fig:scatter-r-theta-shift} plots the length of shift vectors against their angle. Considerable variability is visible in the length and the angle of individual shift vectors. The average of a set of vectors radiating from the origin that point in various directions and have various lengths will inevitably end up close to the origin of that vector space. The average shift vector, in red, at (89.25, 0.64) is smaller than all of the individual shift vectors, and has an $\ell _2$ norm of only 0.64. When such a small vector is added to the singular, it is hardly distinguishable from the singular vector, and at a large distance from the actual corresponding plural vector. \begin{figure} \centering \includegraphics[width=0.85\textwidth]{w2v-scatter-angle-length2.png} \caption{Scatter plot visualizing the relationship between the length, on the y-axis, and angle, on the x-axis, for the individual shift vectors. The isolated red dot below the cloud of all other data points at (89.25, 0.64) belongs to the average shift vector.} \label{fig:scatter-r-theta-shift} \end{figure} Upon closer inspection, it turns out that, rather than being random, the set of individual shift vectors exhibits structure. The length of plural vectors increases with the length of their singular vectors, and likewise, the length of shift vectors increases with the length of the singular vectors, as illustrated in Fig.~\ref{fig:len-shift-depends-len-sg}. From this, we can draw the conclusion that the semantics of shift vectors is changing in close association with the semantics of the singular and plural words. \begin{figure} \centering \includegraphics[width=\textwidth]{w2v-scatter-len-pl-shift-against-sg-xEqy-14699.png} \caption{Scatterplots for the length of plural vectors (vertical axis in the left panel) and length of shift vectors (vertical axis in the right panel) against the length of singular vectors (horizontal axis in both plots), with Locally WEighted Scatterplot Smoothing (LOWESS) trend lines in red. The dashed black lines represent the identity line $y=x$.} \label{fig:len-shift-depends-len-sg} \end{figure} Given that singular words that have similar semantics have closer vectors, and singular words with less similar meanings have more diverging vectors, we now consider the question of whether the shift vectors themselves show structuring that goes beyond the structure provided at the level of individual lexemes. To address this question, we made use of the t-SNE algorithm for visualizing high-dimensional data \citep{Maaten:Hinton:2008} as implemented in the \texttt{scikit-learn} Python library \citep{scikit-learn}, version 1.0.1, to plot the 300-dimensional shift vectors in a two-dimensional plane.\footnote{Following the recommendations of \cite{vanderMaaten:2021}, we searched the t-SNE's parameter space between possible combinations of \textit{perplexity} (either 10, 15, 20, 25, 30, or 35), \textit{number of iterations} (either 500, 1000, 2000, 3000, or 4000), \textit{random state} (either 1, 12, or 123), and \textit{initialization} method (either random or PCA) for the t-SNE with the lowest Kullback-Leibler divergence. The lowest KL-divergence was obtained with the following setting: perplexity $=$ 35, number of iterations = 4000, early exaggeration = 12, random state = 1, learning rate = `auto', metric=`euclidean', and initialization = `random'.} This visualization technique is known to have a very high chance of recovering the clustering structure present in the input space in the reduced output space \citep{Linderman2019, Arora2018}. Fig.~\ref{fig:tsne-shift-w2v} presents the scatter of data points in this plane, coloured with the label of the first synset in WordNet \citep{Fellbaum:1998,Miller:1995} for the singular word form. From the 14,699 pairs in our pluralization dataset, 11,749 pairs are found in WordNet and used in the remainder of this study. The labels, indicated in the figure's legend, often referred to as supersenses, include 26 broad semantic categories for nouns \citep{Ciaramita:Johnson:2003}. Interestingly, the individual shift vectors form clusters that are reasonably well approximated by the WordNet supersenses. Some supersenses show well-defined clusters, such as \textit{person} towards the bottom right corner of the plane and \textit{animal} towards the top right corner. This indicates that pluralization is similar for nouns denoting animal nouns and is different for nouns denoting persons. Importantly, the average shift vector (highlighted by a red cross) is located near the origin of this space at $(0.4,\, -1.8)$. Interpretation of the t-SNE dimensions is not very straightforward. Preliminary investigation suggests that the first dimension is to a very large extent differentiating between concrete and abstract words (see supplementary materials for details). The second dimension is less interpretable, and rather similar to the first dimension. \begin{figure} \centering \includegraphics[width=\textwidth]{w2v-tsne-shift-bestKL2.png} \caption{A projection of shift vectors onto a two-dimensional plane using t-SNE reveals semantic clustering. Colors correspond to WordNet supersenses. The average shift vector marked with a red cross, which is located very close to the origin at $(0.4,\, -1.8)$, is blind to this rich structure. This figure is available as an interactive plot in the supplementary materials. } \label{fig:tsne-shift-w2v} \end{figure} Although some well-defined clusters are present in Fig.~\ref{fig:tsne-shift-w2v}, other clusters show considerable overlap. This is due to two problems. The first problem is that nouns can have multiple senses. We selected the first sense listed in WordNet, which, according to \citet{Jurafsky:Martin:2021}, is the most frequent sense and hence a strong baseline. However, inaccuracies are inevitable. For instance, \textit{strawberry} is assigned the food category while \textit{blueberry} is labeled as a plant. A related problem is that we have one embedding for all senses, instead of sense-specific embeddings. The second problem is that the supersenses are often too broad and too over-populated to form semantically coherent groups. For instance, the supersense \textit{artifact} brings together musical instruments, vehicles, clothes, guns, and buildings among others. In the t-SNE plane, this supersense is found in two distinct regions. The fuzziness of the 26 supersenses is clearly demonstrated by Linear Discriminant Analysis (LDA) given the task of assigning shift vectors to supersenses. From an evaluation of the LDA on all of the data points ($N=11749)$, accuracy and weighted average F-score were both 58.4\% . To put the multiclass classification performance of the LDA into perspective, the weighted average F-score by the LDA is 7 times greater than the weighted average F-score of a baseline classifier that always predicts the most frequent superset. The LDA's performance indicates that on the one hand there is structure and the structure is captured by both a supervised algorithm, i.e., LDA, and an unsupervised algorithm, i.e., t-SNE. On the other hand, it indicates that there is also considerable uncertainty about superset membership. To address the first problem, one would have to make use of techniques for word-sense disambiguation. Word sense disambiguation has a very long history in computational linguistics and there are many supervised and unsupervised algorithms designed for this task. One might combine WordNet and FrameNet \citep{Baker:Fillmore:Lowe:1998} annotations as proposed by \cite{Baker:Fellbaum:2009}, train a supervised model \citep[e.g.,][]{Zhong:Ng:2010}, or search for words' nearest neighbors in a contextual word embeddings space \citep{Loureiro:Jorge:2019}. Given a high-accuracy word sense disambiguation pipeline, one could then apply word sense disambiguation before calculating embeddings using word2vec. Such a programme, if at all feasible, is outside the scope of the present study. The second problem is more straightforward to address. Instead of using the 26 supersenses shown in Fig.~\ref{fig:tsne-shift-w2v}, we can zoom in on smaller, more semantically homogeneous sense sets. For instance, the supersense \textit{person} covers 2725 lexemes in our data. By moving to semantic classes one level below this supersense, we obtain more coherent subsets such as \textit{relative}, \textit{scientist}, and \textit{lover}. For our pluralization dataset, we constructed a total of 411 classes, by moving zero steps or one step down from the supersenses. On average, a class has 28.6 ($SD=39.8$) members. No class has fewer than 5 members. The most populous class has 481 members. These new semantic classes are more semantically cohesive, as can be seen in Figure~\ref{fig:extra} for a number of sub-classes within the supersense \textit{artifact} as an example. Furthermore, the performance of LDA increased despite the substantial increase in the number of classes. Accuracy and weighted average F-score are both 61\% from an evaluation of an LDA that predicts 411 classes given the shift vectors. In comparison, the weighted average F-score by this model is 189 times greater than the weighted average F-score of a baseline classifier that always predicts the most frequent class. \begin{figure} \centering \includegraphics[width=0.9\textwidth]{w2v-tsne-shift-bestKL-411classes-artifact-subset.png} \caption{A projection of shift vectors onto a two-dimensional plane using t-SNE for a subset of data points within the supersense \textit{artifact} that form rudimentary sub-clusters such as \textit{clothing} and \textit{musical instruments}.} \label{fig:extra} \end{figure} Although the idea of an abstract semantic representation is appealing, it turns out that a simple average shift vector fails to do justice to the intricate semantic structure that characterizes nominal pluralization in English. Apparently, English pluralization is substantially more subtle, and varies systematically with the semantic category (supersense) of a noun. \subsection{CosClassAvg}\label{subsec:cosclassavg} This new set of 411 classes, or a similarly cohesive set of classes of semantically highly related words, makes it possible to formalize a new model for plural semantics. We first calculated the average shift vector for each of the 411 classes. The mean length of these average shift vectors is 1.2, and its standard deviation was 0.3. Compared to the distribution of shift vectors shown in Fig.~\ref{fig:boxplot-len-sg-pl-shift}, both mean and standard deviation are substantially reduced. The same holds for their angles ($M=89.1$, $\mathrm{SD}=2.6$). This clarifies that by-class shift vectors are more similar to each other than is the case for the shift vectors in the undifferentiated set of all nouns. We can now introduce our `CosClassAvg' theory for noun plurals. Given an input word and its semantic class, the plural vector predicted by CosClassAvg is obtained by taking the singular vector and adding to it the average shift vector for that class. Thus, the vector for \textit{bananas} is predicted using $$\overrightarrow{bananas}_p=\overrightarrow{banana}+\overrightarrow{\textsc{avg-shift}}_{\textsc{fruit}},$$ while the vector for \textit{cars} is predicted based on $$\overrightarrow{cars}_p=\overrightarrow{car}+\overrightarrow{\textsc{avg-shift}}_{\textsc{vehicle}}.$$ We can assess the quality of predicted vectors by inspecting the cosine similarities of a predicted vector with the vectors of all words. Ideally, the vector that is closest to the predicted vector represents the meaning of the targeted plural. How well does CosClassAvg perform? To address this question, we first investigated whether predicted plurals are better differentiated from their singular counterparts. As our baseline for comparisons, we used the \textsc{Only-b} method introduced in \cite{Linzen:2016}, where \textsc{b} represents the vector for the base word. This method simply returns the input singular vector, without adding anything to it, as the predicted plural vector. As a consequence, this method will always predict the nearest neighbor in terms of cosine similarity, i.e. the word that is most similar to the base word in the vocabulary. We calculated the predicted plural vectors for all singular words in our pluralization dataset ($N=11,749$) using 3CosAvg, CosClassAvg, and the baseline method. Many implementations of proportional analogies with word embeddings exclude the input words such as the singular word from the vocabulary as a potential predicted word. However, in an ``honest'' practice, as \cite{Rogers:Drozd:Li:2017} put it, we do not exclude any words from the vocabulary. We therefore compared predicted vectors with a broader set of words covering all 30,497 word-form types in our pluralization and our vocabulary datasets. The notched boxplots in Fig.~\ref{fig:3methods-similarity-hatpl-pl} summarize the distributions of cosine similarities (left) and Euclidean distances (right), for the baseline model (Only-B), the 3CosAvg model, and the new CosClassAvg model, of the predicted vectors and the corresponding plural vectors provided by word2vec. The lowest boxplots in blue produced by the baseline method, indicate that the singular and the plural vectors in word2vec are already astonishingly similar. Both 3CosAvg and CosClassAvg improve on the baseline and generate more similar and less distant vectors to the actual plural vector, with CosClassAvg in the lead. \begin{figure} \centering \includegraphics[width=\textwidth]{hatpl_pl2.png} \caption{Comparison between the predicted plural vectors and the corpus-extracted plural vectors using cosine similarity (left panel) and Euclidean distance (right) for the Only-B, the 3CosAvg, and the CosClassAvg method. } \label{fig:3methods-similarity-hatpl-pl} \end{figure} For predicted vectors to well approximate the true plural vectors, they should be less close to their corresponding singular vectors. Fig.~\ref{fig:3methods-similarity-hatpl-sg} visualizes cosine similarity to singular vectors and Euclidean distance from singular vectors of the predicted plural vectors. Similarity decreases from one and distance increases from zero with 3CosAvg and CosClassAvg plural vectors. The Euclidean distance between 3CosAvg plural vectors and their singular vectors is always equal to the length of the average shift vector. The length of this overall average shift vector is smaller than the length of any CosClassAvg class-specific shift vector. \begin{figure} \centering \includegraphics[width=\textwidth]{hatpl_sg2.png} \caption{Comparison between the predicted plural vectors and the singular vectors using cosine similarity (left panel) and Euclidean distance (right) for the Only-B, the 3CosAvg, and the CosClassAvg method. } \label{fig:3methods-similarity-hatpl-sg} \end{figure} When we use the stringent criterion that any word, including the singular, can be a neighbor of the predicted plural, then performance of both 3CosAvg and CosClassAvg is disappointing. 3CosAvg always selects the singular as closest neighbor, and CosClassAvg only correctly selects 42 plurals (0.4\%). Although CosClassAvg yields predicted vectors that are further away from their singulars and closer to their plurals, compared to 3CosAvg, predicted plural vectors remain very close to their singular vectors. Table.~\ref{tab:CosClassAvg-predicts-pl-better} lists the percentages of lexemes for which the targeted plural vector is among the top-n neighbors. Of the three methods, CosClassAvg clearly outperforms the other two, with percentages ranging from 79\% to 95\%. In other words, if we relax our criterion and filter out singular vectors as candidates, the accuracy of CosClassAvg is at 79\%. \begin{table}[ht] \begin{center} \begin{minipage}{197pt} \caption{Percentage of the lexemes ($N=11,749$) for which the plural vector is among the 2 (Top 2), 3 (Top 3), 10 (Top 10), and 20 nearest neighbors (Top 20) of the predicted plural vector.} \label{tab:CosClassAvg-predicts-pl-better}% \begin{tabular}{@{}lrrrr@{}} \toprule Method & Top 2 & Top 3 & Top 10 & Top 20 \\ \midrule Only-B & 61 & 74 & 88 & 92 \\ 3CosAvg & 70 & 80 & 91 & 93 \\ CosClassAvg & 79 & 86 & 93 & 95 \\ \botrule \end{tabular} \end{minipage} \end{center} \end{table} \subsection{Discussion} According to the 3CosAvg method proposed by \citet{Drozd:Gladkova:Matsuoka:2016}, pluralization can be formalized as a function adding an \textit{average shift vector} to the singular vector: $$ \bm{v}_{\text{pl}} = f_{\text{\tiny{3CosAvg}}}(\bm{v}_{\text{sg}}) = \bm{v}_{\text{sg}} +\bm{v}_{\textsc{pl}}. $$ We have shown that this formalization of plurality is too simple: shift vectors form semantically motivated clusters. CosClassAvg brings these classes into a modified function $$ \bm{v}_{\text{pl}} = g_{\text{\tiny{CosClassAvg}}}(\bm{v}_{\text{sg}}) = \bm{v}_{\text{sg}} +\bm{v}_{\textsc{pl} \mid \text{semantic class}}. $$ The meaning shift in pluralization is similar for lexemes within a semantic class and is different for lexemes from different semantic classes. CosClassAvg capitalizes on this observation, computes several average shift vectors, one per semantic class, which enables it to generate improved predictions for plurals. Pluralization with CosClassAvg requires two pieces of information to make a prediction, namely, information on the semantic clusters (and their centroids) and information on the semantic class membership of a given singular noun. The current study shows that, given this information, more precise predictions for plural vectors are obtained. Although outside the scope of this contribution, it may well be possible to develop an end-to-end model that does class induction and pluralization jointly. To that end, semantically cohesive clusters within the shift space may be obtained using unsupervised clustering algorithms. We have shown that clusters found by the unsupervised t-SNE algorithm independently of the WordNet tags, are well-supported by the supervised LDA classification using WordNet tags. In the present approach, we accept the 411 classes as given, leaving it to further research to address the question of how these classes might be grounded in unsupervised learning. Regarding the second source of information, we gauged how straightforward it is to classify singular nouns according to their semantics. From a 5-fold stratified cross-validation evaluation of an LDA predicting the 411 semantic classes from \textit{singular} vectors, the mean weighted average F-score was 61\% ($\mathrm{SD} = 0.1$) on the training sets and 32\% ($\mathrm{SD} = 0.5$) on the test sets. The weighted average F-scores by the LDA from the 5 evaluations are on average 190.3 times ($\mathrm{SD} = 0.5$) greater on the training sets and on average 100.1 times ($\mathrm{SD} = 2.3$) greater on the the test sets than the weighted average F-scores of a baseline classifier that always predicts the most frequent class. A straightforward LDA performs quite well under cross-validation. Thus, the classes that we derived from WordNet are to a large extent implicit in the word embeddings. The CosClassAvg method may also provide enhanced predictivity for human lexical processing, compared to the 3CosAvg method. For instance, \cite{Westbury:Hollis:2019} calculated average vectors for words belonging to different syntactic categories, or containing different derivational affixes, and showed that these average vectors can be leveraged to model human categorization decisions. Following their approach, we computed the average vector of plural nouns ($\frac{1}{m} \sum_{i=0}^m \Vec{p_i}$ in equation \ref{eq:linear-property-of-offset-vector-line1}) using the 14,699 plural words in our pluralization dataset introduced in section \ref{sec:data}. Nearest neighbors to the average plural were retrieved among our vocabulary dataset. We replicated \cite{Westbury:Hollis:2019}'s findings for the average plural vector. Within the closest neighbors of the average plural vector, 79\% are plural nouns. However, other than being plural, these nouns are semantically highly heterogeneous. If human category decisions are also influenced by the lexical semantics of nouns, more precise predictions can perhaps be obtained by further conditioning on the semantic class of the noun. We leave this issue to further research. The clustering of plural shift vectors by semantic class likely reflects differences in how plural objects configure in our (culture-specific) constructions of the world. Multiple cars occur in different configurations which tend to share alignments, as in parking lots or traffic jams. Multiple oranges or multiple cherries occur in very different configurations, typically piled up in boxes or on plates, and bananas occur in hands on banana plants and fruit stands. Apparently, the different properties of the objects that we refer to in the plural are reflected in our language use, as captured by distributional semantics. However, apples and oranges are more similar than apples and bananas. As a consequence, the vectors predicted by CosClassAvg will always be a bit off for individual words. This observation necessitates updating the plural semantic function $g$ with an error term, as follows $$ \bm{v}_{\text{pl}} = g_{\text{\tiny{CosClassAvg}}}(\bm{v}_{\text{sg}}) = \bm{v}_{\text{sg}} +\bm{v}_{\textsc{pl} \mid \text{semantic class}} + \bm{\epsilon}_\text{lexeme}. $$ The error vector $\bm{\epsilon}_\text{lexeme}$ represents the lexeme-specific semantics that cannot be captured by the semantic commonalities of the lexeme's semantic class. In usage-based grammar and corpus linguistics, individual words, including inflected words, have been argued to have their own highly specific usage profiles \citep[see, e.g.,][]{Sinclair:1991}. `Error' components such as $\bm{\epsilon}_\text{lexeme}$ formalize this important insight. However, since semantic vectors themselves are measurements, and as such subject to measurement error, we need to add a second error vector representing measurement noise: $$ \bm{v}_{\text{pl}} = g_{\text{\tiny{CosClassAvg}}}(\bm{v}_{\text{sg}}) = \bm{v}_{\text{sg}} +\bm{v}_{\textsc{pl} \mid \text{semantic class}} + \bm{\epsilon}_\text{lexeme} + \bm{\epsilon}. $$ Since CosClassAvg decomposes semantic vectors into constituent semantic vectors, it constitutes a `decompositional' or `analytical' method for accounting for inflectional semantics. In the next section, we compare decompositional CosClassAvg with a compositional method, FRACCS \citep{Marelli:Baroni:2015}. \section{Pluralization with FRACSS}\label{sec:compositional-morphology} \cite{Marelli:Baroni:2015}, building on previous research on compositional semantics \citep{Mitchell:Lapata:2008,Baroni:Zamparelli:2010,Lazaridou:Marelli:Zamparelli:Baroni:2013}, proposed to model derivational semantics with the help of a linear transformation that takes the semantic vector of the base word as input, and maps it onto the semantic vector of the corresponding plural using a linear mapping $\bm{B}$: $$ \bm{v}_{\text{pl}} = h_{\text{\tiny{FRACSS}}}(\bm{v}_{\text{sg}}) = \bm{v}_{\text{sg}}\bm{B}. $$ This model, known as the FRACSS model, has been applied to German complex verbs \citep{Gunther:Smolka:Marelli:2019}, and an extended version has been used to study compounding in English and German \citep{Gunther:Marelli:2016, Gunther:Marelli:2019, Marelli:Gagne:Spalding:2017, Gunther:Marelli:Bolte:2020}. In the following, we apply FRACSS to English plural inflection, and compare its predictions with those of CosClassAvg. FRACSS transforms singular vectors into plural vectors using straightforward matrix multiplication. Let $\bm{X}$ denote a matrix with as row vectors the word embeddings of singulars, and let $\bm{Y}$ denote a matrix with the same number of row and column vectors representing the meanings of the corresponding plurals: \begin{equation*} {\displaystyle \bm{X = {\begin{pmatrix} x_{1,1} & x_{1,2} & \cdots & x_{1,n}\\ x_{2,1} & x_{2,2} & \cdots & x_{2,n}\\ \vdots &\vdots &\ddots & \vdots\\ x_{t,1}&x_{t,2}&\cdots & x_{t,n}\\ \end{pmatrix}}, \quad \bm{Y = {\begin{pmatrix} y_{1,1} & y_{1,2} & \cdots & y_{1,n}\\ y_{2,1} & y_{2,2} & \cdots & y_{2,n}\\ \vdots & \vdots & \ddots & \vdots\\ y_{t,1} & y_{t,2} & \cdots & y_{t,n}\\ \end{pmatrix}}. } \end{equation*} \noindent The mapping $\bm{B}$ is a $n\times n$ dimensional matrix that satisfies $$ \bm{X} \bm{B} = \bm{Y}. $$ We estimate $\bm{B}$ as follows: $$ \bm{B} = \bm{X}^+ \bm{Y} = (\bm{X}^T \bm{X})^{-1} \bm{X}^T \bm{Y}, $$ where $\bm{X}^+$ is the pseudo-inverse of $\bm{X}$ and $\bm{X}^T$ is its transpose, and $(.)^{-1}$ denotes a matrix inverse operation. Given $\bm{B}$ and the vector of a singular, the predicted plural vector is given by \begin{equation*}\label{eq:matrix-multiplication-1vec} {\displaystyle {\begin{bmatrix} x_1 & x_2 & \cdots & x_{n} \end{bmatrix}} {\begin{pmatrix} b_{1,1} & b_{1,2} & \cdots &b_{1,m}\\ b_{2,1} & b_{2,2} & \cdots &b_{2,m}\\ \vdots &\vdots &\ddots &\vdots\\ b_{n,1} &b_{n,2}&\cdots &b_{n,m}\\ \end{pmatrix}} = {\begin{bmatrix} \hat{y}_1 & \hat{y}_2 & \cdots & \hat{y}_{m} \end{bmatrix}}, } \end{equation*} which, according to the definition of matrix multiplication, implies that \begin{equation* \hat{y}_j = \sum_{i=1}^{n} b_{i,j} \cdot x_{i}, \qquad {\small \text{for } 1\leq j \leq m }. \end{equation*} In other words, the $j$-th element of the semantic vector of a given plural is a weighted sum of the values of its singular vector. \subsection{Conceptualizing noun plurals with FRACSS} \label{subsec:fracss} We estimated the mapping matrix $\bm{B}$ for 90\% of the singular-plural pairs in our pluralization dataset (10,574 pairs) using 300-dimensional word2vec vectors. The remaining 1,175 word pairs were set aside as held-out testing data. The resulting 300$\times$300 $\bm{B}$ matrix implements the change in the meaning of singular words that goes hand in hand with the affixation of the plural \textit{-s}. With $\bm{B}$ in hand, we can calculate predicted plural vectors for both the training data and the test data. The model correctly predicts plural forms for 88\% of training items and for 76\% of test items. Clearly, the mapping appears robust as a memory for seen items and it is also productive for unseen items. To better understand the performance of the FRACSS model, recall that in section \ref{sec:realizational-morphology} we observed that word2vec's singular and plural vectors are very similar. That is to say, any model for finding a mapping between the singular and the plural space is a-priori in an advantageous position since the relationship between the two spaces is already a given property of the semantic space constructed by word2vec. In other words, the mapping matrix $\bm{B}$ must be somewhat similar to an identity matrix (i.e., a matrix with ones on the diagonal and zeroes elsewhere). The cool-to-warm heat map in Fig.~\ref{fig:fracss-weights}, that visualizes the FRACSS matrix, shows that this is indeed the case. Input vector dimensions are on the vertical axis, indexed by $i$ from 1 to 300, and output vector dimensions, indexed by $j$ from 1 to 300, are on the horizontal axis. The color indicates the magnitude of the value at index $(i,j)$. The value at index $(i,j)$ of this matrix, $b_{i,j}$, shows the association strength between the $i$-th dimension of the singular vectors and the $j$-th dimension of the plural vectors. Association strengths are highest on the diagonal entries of this matrix, which links every singular with its own plural. \begin{figure} \centering \includegraphics[width=0.9\textwidth]{fracss_weights.png} \caption{FRACSS matrix for English plural suffix -s.} \label{fig:fracss-weights} \end{figure} The mean value of the diagonal elements is 0.57 ($SD=0.02$). Barely any structure is evident elsewhere: the mean value of off-diagonal elements is a mere $9.8\times 10^{-5}$ ($SD=0.017$). We can therefore approximate the effect of multiplication with $\bm{B}$ with a much simpler operation: \begin{equation} \hat{\bm{Y}} = 0.57 \bm{X} \bm{I} + \bm{\epsilon}, \bm{\epsilon} \sim {\cal N}_{300}({\bf -0.001}, 0.08\bm{I}), \end{equation} \noindent where $\bm{I}$ is the identity matrix, $\bm{\epsilon}$ is a matrix of 300-dimensional random vectors as row vectors all chosen from the same multivariate normal distribution with mean vector $\bf{-0.001}$ (a 300-dimensional vector with -0.001 everywhere) and covariance matrix $0.08\bm{I}$.\footnote{For almost all predicted plural and singular vector pairs, the epsilons were normally distributed with an average mean of -0.001 and an average standard deviation of 0.08 (D'Agostino's $K^2$ departure from normality hypothesis test; $p > 0.001$ for 99.8\% of 11749 tests).} Note that this approximation of $\bm{B}$ predicts that the semantic vectors predicted by FRACSS are shorter in length than their singulars: this follows from the multiplication factor 0.57. How do the FRACSS predicted vectors compare to the vectors predicted by CosClassAvg? To address this question, we first consider similarity evaluated by means of the angle between vectors, and subsequently by means of the Euclidean distance of the corpus-extracted vectors. The median cosine similarity of predicted and target vectors is 0.75 for FRACSS and 0.71 for CosClassAvg (Wilcoxon signed-rank test $W=65105609.0$, $p \ll 0.0001$ one-tailed, $N=11749$). Furthermore, the median cosine similarity between singular vectors and predicted vectors is 0.87 for FRACSS and 0.95 for CosClassAvg (Wilcoxon signed-rank test $W=649018.0$, $p \ll 0.0001$ one-tailed). When accuracy is evaluated with the cosine similarity measure, the FRACSS plural vectors are now close enough to the target plural vectors to capture the plural word correctly as the first nearest neighbor in 1520 cases (13\%). Similar results are obtained when we use the Euclidean distance measure. The median Euclidean distance to corpus-extracted plural vectors is shorter from predicted vectors for FRACSS at 2.28 in comparison with vectors for CosClassAvg at 2.64 (Wilcoxon signed-rank test $W=1530725.0$, $p \ll 0.0001$ one-tailed). Inversely, the median Euclidean distance between singular vectors and predicted vectors is 1.67 for FRACSS and 1.04 for CosClassAvg (Wilcoxon signed-rank test $W=68556852.0$, $p \ll 0.0001$ one-tailed). Thus far, we have based our evaluation on the angle and distance between vectors. We have seen that FRACSS vectors have smaller angles and shorter distances to plural vectors than CosClassAvg vectors. What about the Euclidean length of the predicted plural vectors? Fig.~\ref{fig:predicted-pl-length} plots the length of predicted plural vectors against the length of singular vectors, for CosClassAvg (left) and FRACSS (right). For both methods, length of predicted plural vectors increases with the length of singular vectors, similar to the trend observed in Fig.~\ref{fig:len-shift-depends-len-sg} for the length of corpus-extracted plural and singular vectors. However, there is a striking difference. Most plural vectors predicted by CosClassAvg are longer than their singular vector (74\%). By contrast, as anticipated above on the basis of an analysis of the $\bm{B}$ matrix, all plural vectors predicted by FRACSS are shorter than their corresponding singular vectors.\footnote{The signed difference between the length of the target plural vectors and the length of the predicted plural vectors is lower for CosClassAvg compared to FRACSS (Wilcoxon signed-rank test $W=69025375.0, p \ll 0.0001, \mathrm{MD}_{\text{CosClassAvg}}=0.09, \mathrm{MD}_{\text{FRACSS}}=0.89, N=11749$).} However, for the corpus-based actual word2vec vectors, 66\% of the plural vectors are longer than the corresponding singular vectors. \begin{figure} \centering \includegraphics[width=\textwidth]{scatter-len-hatpl-against-sg-2methods.png} \caption{Scatter plots depicting the length of predicted plural vectors, on the vertical axis, versus the length of singular vectors, on the horizontal axis, by CosClassAvg (left panel) and FRACSS (right panel) with the Locally WEighted Scatterplot Smoothing (LOWESS) trend lines in red. The dashed black lines represent the identity line $y=x$.} \label{fig:predicted-pl-length} \end{figure} \subsection{Discussion} We have seen that FRACSS outperforms CosClassAvg when evaluation is based on the angle or distance between vectors, but CosClassAvg outperforms FRACSS when we consider vector lengths. In section~\ref{sec:ldl} we propose another measure for evaluating the relative merits of the two methods. , we first reflect on some technical and conceptual problems that come with the FRACSS approach. One conceptual problem concerns the interpretation of the $\bm{B}$ matrix. Our t-SNE analysis of shift vectors revealed clustering by semantic class. However, $\bm{B}$ is calculated by evaluating all singulars and plurals simultaneously. It is an empirical question whether this is advantageous for understanding human lexical processing, an issue we pursue in more detail in section~\ref{sec:ldl}. If we assume, for the sake of the argument, that FRACSS is a more precise version of CosClassAvg, then CosClassAvg provides us with insight into what FRACSS is actually achieving: semantic-cluster driven local generalization. In other words, the FRACSS matrix $\bm{B}$ does not represent a single operation of pluralization that is independent and orthogonal to the lexical meaning of the singular. To the contrary, $\bm{B}$ captures a wide range of different local pluralization functions. Another conceptual problem concerns the directionality of semantic operations. \cite{Baroni:Bernardi:Zamparelli:2014} argue that semantic composition is intrinsically asymmetric (compare `water under the bridge' and `bridge under the water'), and that therefore implementations of semantic functions using matrix multiplication is superior to functions using vector addition. \cite{Marelli:Baroni:2015} likewise assert that representing affixes as functions over base forms in FRACSS captures this important asymmetry. However, a FRACSS matrix such as $\bm{B}$ has a pseudo-inverse, and technically it is straightforward to construct a mapping from plurals to singulars. Such a linear mapping trained in the inverse direction on the same data correctly predicts singular semantics for 87\% of training items and 74\% of test items from plural semantics. We conclude that FRACSS is not intrinsically asymmetric. There are also some technical issues worth mentioning. First, updating FRACSS matrices is more costly than updating the CosClassAvg model. Introducing new word pairs, or even a single pair, to the training dataset necessitates re-computation of the whole FRACSS network. For CosClassAvg, a new word pair merely requires re-calibration of the average shift vector for the semantic class of the pertinent lexeme. Second, FRACSS requires large numbers of parameters: given vectors of dimension $n$, it requires a mapping with $n^2$ parameters (which can be conceptualized as the beta weights of a multivariate multiple regression model). For the present word2vec vectors, we have no less than 300 $\times$ 300 = 90,000 parameters. As our current dataset has more than 11,000 datapoints, we have more data than parameters, and FRACSS works just fine. However, when the number of datapoints is substantially less than the number of parameters, the FRACSS approach will overfit the data, and not generalize well. For example, in the study of \cite{Lazaridou:Marelli:Zamparelli:Baroni:2013}, 12 out of 18 affixes have fewer than 350 words (training samples), whereas the semantic vectors used had a dimensionality equal to 350. Likewise, 27 out of 34 affixes studied by \cite{Marelli:Baroni:2015} are trained on fewer observations than their vectors' dimensionality. To avoid the problem of overfitting, one could model the complete set of derivational affixes of English with one FRACSS mapping. Under the assumption that the number of derived words is substantially larger than the dimensionality squared of the embeddings, the model should show good generalization performance. However, even though data sparsity would no longer be a problem, the model would not be very informative about the semantics of the different affixes. In the light of these considerations, we consider how well the two models for conceptualizing plurals, FRACSS and CosClassAvg, perform when integrated into a model of morphology that addresses the mappings between form and meaning, the Discriminative Lexicon (DL) model proposed by \citep{Baayen:Chuang:Shafaei:Blevins:2019}. \section{Conceptualization and the mapping from form to meaning} \label{sec:ldl} Up till now, we have considered how the meanings of singulars and plurals are related to each other, and we have considered two alternative mathematical formalizations of how to conceptualize a plural given a singular. Both formalizations provide an account of the semantic productivity of pluralization. However, for understanding or producing actual words, we need to consider mappings between form and meaning. In the ensuing paragraphs, we focus on comprehension, and investigate which of the two formalizations provides semantic vectors that are better aligned with words' forms. An initial question is whether words' form representations make systematic contact with the semantic vectors of CosClassAvg and FRACSS. If there exists systematicity between the form space and these semantic spaces, it should be possible to find accurate mappings from forms to meanings, not only for training data, but also for held-out test data. \subsection{Comprehension with FRACSS and CosClassAvg} We model comprehension with the discriminative lexicon model of \cite{Baayen:Chuang:Shafaei:Blevins:2019}. This model makes use of linear mappings from numeric representations of words' forms to numeric representations of words' meanings. The DL model is well-suited for our purposes as it has been shown to be successful in modeling comprehension of morphologically complex words for various languages \citep{Chuang:Loo:Blevins:Baayen:2020, Heitmeier:Chuang:Baayen:2021, Denistia:Baayen:2022, Heitmeier:Baayen:2020} and, importantly, because it is flexible in terms of which semantic space is selected to represent words' meanings. Keeping form representations and the representations for singular meanings the same, meaning representations for plurals can be created according to CosClassAvg, or alternatively, according to FRACSS. For our modeling experiments, we extracted all singular and plural tokens from the vocabulary dataset introduced in section \ref{sec:data}. This subset comprises 9541 English singular and plural tokens of 8762 unique orthographic word-form types. There are more tokens than types because 728 words have two or more pronunciations in the NewsScape English Corpus. We constructed training data and test data in such a way that plurals in the test data always had the corresponding singular in the training data. The training data also included plural forms that do not have a corresponding singular in the dataset. Of all plurals with corresponding singulars, 70\% were assigned to the training data, and 30\% to the testing data. This resulted in training data comprising 8,507 tokens of 7,886 types, and test data comprising 1034 tokens of 1002 types. Table~\ref{tab:ldl-modeling-data} provides further information on the composition of the training and test sets. \begin{table}[ht] \begin{center} \begin{minipage}{275pt} \caption{Number of word-form types and tokens in the datasets used for the DL simulations.}\label{tab:ldl-modeling-data}% \begin{tabular}{@{}lrrr@{}} \toprule Dataset & Word-form Types & Word-form Tokens \\ \midrule \textsc{Training set}\\ \hspace{7mm}Singular & 5073 & 5511 \\ \hspace{7mm}Plural with seen stem & 2253 & 2412 \\ \hspace{7mm}Plural with unseen stem & 560 & 584 \\ \textsc{Test set}\\ \hspace{7mm}Plural with seen stem & 1002 & 1034 \\ \botrule \end{tabular} \end{minipage} \end{center} \end{table} \cite{Heitmeier:Chuang:Baayen:2021} discuss several methods with which numeric representations for word forms can constructed. In the present study, we make use of numeric form vectors that are based on triphones, i.e., context-sensitive phone units that include information about neighboring segments. For the word \textit{cities}, the triphone cues are \texttt{\#s\textsci}, \texttt{s\textsci t}, \texttt{\textsci ti}, \texttt{tiz}, and \texttt{iz\#}, where the \texttt{\#} symbol is used to denote word boundaries. For our dataset, there are 6,375 unique triphones. A word's form vector is defined as a vector with length 6,375 that has values that are either zero or one, depending on whether a triphone is present in a word (1) or not (0). Words' form vectors can be brought together in a matrix $\bm{C}$ with words on rows and triphones on columns \citep[For form vectors derived from the audio signal, see][]{Shafaei:Tari:Uhrig:Baayen:2021}. As a result, the matrix with word form vectors $\bm{C}$ used for deriving mappings from form to meaning had 8,507 rows and 6,375 columns. The form vectors for words are based on the phone transcriptions in the NewsScape English Corpus, which are obtained from the Gentle forced aligner. Gentle’s ASR backend is kaldi \citep{Povey:etal:2011:Kaldi}, which is set up to run with a version of the CMUDict machine-readable pronunciation dictionary (\url{https://github.com/cmusphinx/cmudict}), but with information on stress removed. For various words, the dictionary offers pronunciation variants, such as \texttt{d\_B ae\_I t\_I ah\_E} and \texttt{d\_B ey\_I t\_I ah\_E} for \textit{data}. Here, CMUDict combines ARPABET phone representations with additional information on whether a segment is at the beginning of a word, at an intermediate position, or at the end of a word (\texttt{B}, \texttt{I}, and \texttt{E} respectively). We note here that the list of pronunciation variants provided by CMUDict is far from complete. For instance, for \textit{ideology}, it provides the transcription /a\textsci di\textscripta l\textturnv d\textyogh i/ but not the alternative /idi\textscripta l\textturnv d\textyogh i/. Various reduced forms of function words as typically found in spoken language are not represented in the dictionary. For instance, the conjunction \textit{and} is listed with two variants, /\ae nd/ and /\textturnv nd/, but forms such as /\textturnv n/ or even /n/ are not included. As a consequence, the representations we used for words' forms may not correspond to the exact way in which these words were actually spoken. For evaluating the advantages and disadvantages of semantic vectors based on CosClassAvg and FRACSS, we set up two semantic matrices, $\bm{S}_{\text{\tiny{CosClassAvg}}}$ and $\bm{S}_{\text{\tiny{FRACSS}}}$ that were based on word2vec. The vectors for singulars were straightforwardly taken from word2vec, but the vectors for plurals were calculated either according to CosClassAvg or according to FRACSS. The two semantic matrices had 8,507 rows and 300 columns. We then calculated two 6,375$\times$300 mappings, $\bm{F}_{\text{\tiny{CosClassAvg}}}$ and $\bm{F}_{\text{\tiny{FRACSS}}}$, by solving the equations \begin{eqnarray*} \bm{S}_{\text{\tiny{CosClassAvg}}} & = & \bm{C}\bm{F}_{\text{\tiny{CosClassAvg}}} \\ \bm{S}_{\text{\tiny{FRACSS}}} & = & \bm{C}\bm{F}_{\text{\tiny{FRACSS}}}. \end{eqnarray*} With these the two mappings, we obtained two sets of predicted semantic vectors for the training data: \begin{eqnarray*} \hat{\bm{S}}_{\text{\tiny{CosClassAvg}}} & = & \bm{C}\bm{F}_{\text{\tiny{CosClassAvg}}} \\ \hat{\bm{S}}_{\text{\tiny{FRACSS}}} & = & \bm{C}\bm{F}_{\text{\tiny{FRACSS}}}. \end{eqnarray*} Given the form vectors of the held-out plurals, which we collect as the row vectors of a form matrix $\bm{C}_{\text{\tiny{test}}}$, we also obtain two matrices with predicted plurals: \begin{eqnarray*} \hat{\bm{S}}_{\text{\tiny{CosClassAvg}}, \text{\tiny{test}}} & = & \bm{C}{\text{\tiny{test}}}\bm{F}_{\text{\tiny{CosClassAvg}}} \\ \hat{\bm{S}}_{\text{\tiny{FRACSS}},\text{\tiny{test}} } & = & \bm{C}{\text{\tiny{test}}}\bm{F}_{\text{\tiny{FRACSS}}}. \end{eqnarray*} Prediction accuracy was evaluated by inspecting which gold-standard row vector is closest to the corresponding predicted semantic vector in terms of Pearson's correlation coefficient. If these vectors belong to the same word (i.e., they have the same row index), prediction is taken to be accurate. In the same way, we can check whether the gold-standard vector is among the top $n$ nearest semantic neighbors. Making a prediction for a given test token always involves choosing among 7,886 $+$ 1 different semantic vectors---the semantic vectors for the word types in the training set plus the semantic vector for the current test word. Henceforth, we will refer to the DL model with FRACSS vectors as DL-FRACSS and the model with CosClassAvg embeddings as DL-CosClassAvg. Fig.~\ref{fig:ldl-top5-accuracy} presents the top 1 to top 5 accuracy of word recognition evaluated on the training set in dark bars and on the test set in light bars. Recognition accuracy on the training set by both models is 96\% for models' top 1 predictions and increases to almost 100\% as we consider top 2 to top 5 predicted words. With respect to the test data, DL-CosClassAvg outperforms DL-FRACCS by a wide margin in terms of accuracy (top 1)\footnote{The median correlation between the predicted semantic vectors and the target semantic vector is larger for the DL-CosClassAvg model compared to DL-FRACSS ($W=214575.0$, $p < 0.0001$, $\mathrm{MD}_{\text{DL-CosClassAvg}}=0.78$, $\mathrm{MD}_{\text{DL-FRACSS}}=0.77$, $N=1034$). }, whereas DL-FRACSS has slightly better performance when the top 2 or top 3 candidates are considered. \begin{figure} \centering \includegraphics[width=0.95\textwidth]{ldl-top5-accuracy-both-models-notsplit.png} \caption{Accuracy of word recognition (\%) on the training set ($N=8507$) and on the test set ($N=1034$) by DL-CosClassAvg on the left panel and by DL-FRACSS on the right panel.} \label{fig:ldl-top5-accuracy} \end{figure} Recall that our dataset contains words with multiple pronunciations. The random selection for inclusion in the held-out dataset of seen-stem plural words may result in either having no instances of the plural word in the training set (e.g., both pronunciations recorded for \textit{reports} occur in the test set), or having one pronunciation in the training data and another pronunciation in the test set (e.g., \textit{results} is trained on /\textturnr \textsci z\textturnv lts/ and tested on /\textturnr iz\textturnv lts/). DL-CosClassAvg recognizes at least one instance of a word in the test set correctly for 63\% of words with multiple pronunciations ($N=155$). DL-FRACSS performs slightly worse at 46\%. Fig.~\ref{fig:ldl-top1-accuracy-train-categories} summarizes model accuracy for the training data. DL-FRACSS is slightly better at recognizing singulars, whereas DL-CosClassAvg performs slightly better for plurals with unseen stems. \begin{figure} \centering \includegraphics[width=0.7\textwidth]{ldl-top1-accuracy-train-categories-both-models-side.png} \caption{Recognition accuracy on the training set for the singular words, the plural words with a corresponding singular in the training set (seen-stem), and the plural words without a singular in the training set (unseen-stem) by DL-CosClassAvg shown in dark green bars and by DL-FRACSS in light green bars.} \label{fig:ldl-top1-accuracy-train-categories} \end{figure} We also examined the kind of errors made by the DL mappings for the words in the test data. Overall, DL-FRACSS makes 726 errors in the evaluation of the test set, and DL-CosClassAvg 501 errors. There are 439 word tokens that both models fail to predict correctly. We distinguished between three types of errors, tabulated in Fig.~\ref{fig:ldl-errors}. First, many seen-stem plural words of the test set are recognized as their singular word. FRACSS tends to make more errors of this sort, for which both models frequently get the plural word as their second-best guess, and they always find the plural word among their first four guesses. Highly-ranked competitors tend to be synonyms or semantically related words. \begin{figure} \centering \includegraphics[width=0.7\textwidth]{ldl-errors.png} \caption{Different types of errors made by the DL-CosClassAvg ($N=501$) and the DL-FRACSS ($N=726$) model on the test set with 1034 tokens.} \label{fig:ldl-errors} \end{figure} Most of the remaining errors are observed for words with similar forms. To assess this quantitatively, we computed the recall and the overlap indices between the set of target triphones $t$ and the set of predicted triphones $p$ as follows: \begin{align*} \text{recall } (t, p) &= \frac{\lvert t \cap p\rvert}{\lvert p\rvert},\\ \text{overlap } (t, p) &= \frac{\lvert t \cap p\rvert}{\min (\lvert t \rvert, \lvert p\rvert)}.\\ \end{align*} For example, the word \textit{bribes} is recognized as \textit{tribes} by both models. The predicted and the target word share many form features with a recall and an overlap index of 0.6. We classified words as `similar sounding' when the overlap index was greater than 0.3 and the recall index was greater than 0.2. The remaining words were assigned to the `other' class. The set of words for which a similar-sounding error was made by DL-FRACSS is a subset of that of DL-CosClassAvg. The two models are in error for the same 33 words assigned to the `other' category. \subsection{Discussion} Both CosClassAvg and FRACSS generate high-quality plural vectors. FRACSS plurals are somewhat better aligned with respect to angle, whereas CosClassAvg plurals are better positioned in terms of length. We used the DL model to assess whether FRACSS or CosClassAvg vectors are closer aligned with words' forms. On training data, both models have very similar performance. On held-out test data, CosClassAvg is more accurate. We take this as evidence that plural vectors generated by CosClassAvg are better aligned with the corresponding plural forms. \section{General Discussion}\label{sec:general-discussion} Using distributional semantics, visualization with t-SNE, and WordNet, we have documented for nearly 15,000 pairs of English singulars and their corresponding plurals that how plural semantics is realized in semantic space varies with the semantic class of the base word. Instead of there being one universal shift from singulars to plurals in distributional space, the direction and length of shift vectors depends on a lexeme's own semantics. As a consequence, shift vectors for fruits are substantially different from shift vectors for instruments. We proposed the CosClassAvg model to account for the conceptualization of a plural given the singular. This model proposes that an empirical plural vector is the sum of four vectors: the vector of the lexeme, the shift vector appropriate for its semantic class, a lexeme-specific vector representing the lexeme's own lexical properties, and an error vector representing measurement noise. We showed that CosClassAvg provides more precise approximations of plural vectors than a model based on a general average shift vector (3CosAvg). We compared the CosClassAvg model with the FRACSS model \citep{Marelli:Baroni:2015}. The FRACSS model also takes the semantic vector of the singular as input, but makes use of matrix multiplication instead of vector addition to calculate the semantic vector of the plural. The FRACSS model generates plural vectors that are closer to the target plural vectors. However, the plural vectors produced by FRACSS are shorter than the target plural vectors. To better understand the merits of the two models, we also considered how well the FRACSS plural vectors and the CosClassAvg vectors are aligned with words' form vectors. We evaluated the quality of the alignment with the Discriminative Lexicon model \citep{Baayen:Chuang:Shafaei:Blevins:2019}, focusing on its comprehension network. We created form vectors by first collecting all possible triphones and then specified, for a given word, in a high-dimensional binary vector, which triphones are present (1) in that word and which are absent (0). We created two mappings from form vectors to semantic vectors, one for semantic vectors that use FRACSS to generate plural vectors, and a second mapping for semantic vectors that use CosClassAvg to produce plural vectors. For training data, both types of vectors allowed highly accurate mappings to be set up. However, for the held-out test data, plural vectors could be predicted with substantially higher accuracy when plural vectors were created using CosClassAvg. This suggests that plural vectors created with CosClassAvg are better aligned with plurals' forms compared to vectors generated with FRACSS. CosClassAvg offers two advantages compared to FRACSS. First, FRACSS models run the risk of overparameterization, especially for small datasets with numbers of observations that are substantially smaller than the square of the dimension of the semantic vectors. Second, the FRACSS matrix operation seems to suggest that pluralization is a unitary operation, represented by one transformation matrix. However, what this model is actually doing is to capture, within one highly-parameterized mapping operation, a wide range of different ways in which plurals are realized, depending on the semantic class of their lexemes. For comparison, one can set up a single FRACSS model for all bi-morphemic suffixed derived words of English, with high accuracy on both training and test data (see the supplementary materials for further details). However, the different derivational suffixes of English serve different semantic goals, which emerge immediately from a t-SNE visualization. Thus, being able to obtain a high-quality mapping between singulars and plurals does not guarantee that the same semantic operation is governing all transitions from singulars to their plurals in semantic space. This conclusion has important consequences for the principle of semantic compositionality \citep{Pelletier2001} as applied to morphology. According to this principle, the meaning of a plural is determined by the meaning of the singular and the meaning of the plural suffix, or the meaning that is realized by the rule that creates plurals from singulars. As we have seen, a general shift vector that is the same for all lexemes (as formalized by the 3CosAvg method) has some value, but fails to have the required precision. FRACSS does not provide a uniform pluralization operation either, as, thanks to its large numbers of parameters, it can wrap itself around the many individual clusters of shift vectors that are characteristic of a large number of specific semantic classes. It is, of course, possible to adjust the CosClassAvg model $$ \bm{v}_{\text{pl}} = \bm{v}_{\text{sg}} + \bm{v}_{\textsc{pl} \mid \text{semantic class}} + \bm{\epsilon}_\text{lexeme} + \bm{\epsilon} $$ by subtracting the average plural vector $\bar{\bm{v}}$ from all class-specific vectors: $$ \bm{v}_{\text{pl}} = \bm{v}_{\text{sg}} + \bar{\bm{v}} + [\bm{v}_{\textsc{pl} \mid \text{semantic class}} - \bar{\bm{v}}] + \bm{\epsilon}_\text{lexeme} + \bm{\epsilon}. $$ This formulation of CosClassAvg isolates what is common to all plurals. Unfortunately, this common core is a shift vector that is located far outside the cluster of actual shift vectors (see Fig. \ref{fig:scatter-r-theta-shift}), and hence it remains unclear what is gained by incorporating it into the CosClassAvg model. As a consequence, it is also unclear in what sense English plurals are `compositional' in the sense of, e.g., \cite{Pelletier:1994}. At the same time, the present findings dovetail well with the insight from usage-based grammar and corpus linguistics that individual words, including inflected words, often have their own highly specific usage profiles \citep[see, e.g.,][]{Sinclair:1991}. Noun pluralization has been characterized as being rather close to derivation: \cite{Booij:1996} characterizes it as inherent inflection, rather than contextual inflection. It remains an issue for further research to clarify whether the present conclusions for nominal pluralization generalize to contextual inflection. Agreement marking on English simple present verbs makes for an interesting case to pursue in parallel with the present results on nominal plurals. We conclude this study of the semantics of English noun pluralization by placing English in a broader cross-linguistic perspective. Many languages have rules that are sensitive to semantic subsets of nouns. Some languages split nouns into a group for which plurality marking is relevant, and a group for which it is irrelevant. Typically, such splits are made along an animacy hierarchy, from kinship nouns at the highest rank, to human nouns, to (higher and lower) animate nouns, to inanimate nouns at the lowest rank \citep{Corbett:2000:Number}. In Slave, an Athabaskan language in Northwest Territories, Canada, plural marking occurs optionally only for human nouns and dogs \citep{Rice:1989:Slave}. The World Atlas of Language Structures documents 60 other languages that have an optional or obligatory plural marking for human nouns and lack a plural for nouns further down the animacy hierarchy \citep{WALS:34-Haspelmath:2013}. In Persian, subject-verb agreement in person and number coded on the verb is obligatory for animate plural nouns but optional for inanimate ones \citep[][p.~145]{Mahootian:2002:Persian}. \cite{Smith-Stark:1974} reports a similar rule in Georgian. Maori provides a case where number marking is obligatory only for kinship nouns such as \textit{matua} `parent' and \textit{teina} `younger sibling' \citep{Bauer:1993:Maori}. Kiowa, an endangered Tanoan language spoken in Oklahoma, exhibits a strong relationship between semantically coherent noun classes and number agreement behavior. Table~\ref{tab:kiowa-noun-classes} summarizes the nine classes distinguished by \cite{Harbour:2011, Harbour:2008:MorphosemanticNumber}, on the basis of which he argues for a \textit{morphosemantic theory} of number. Bantu languages are known for their large numbers of semantically motivated noun classes \citep[see, e.g.,][for Swahili]{polome1967swahili}. \begin{table}[ht] \begin{center} \begin{minipage}{250pt} \caption{Kiowa noun classes based on \cite{Harbour:2011, Harbour:2008:MorphosemanticNumber}} \label{tab:kiowa-noun-classes}% \begin{tabular}{@{}clll@{}} \toprule Class & Semantic characteristics & Example \\ \midrule 1 & First person only & `I' \\ 2 & Animates & `boy', `bird' \\ & and independently mobile inanimates & `leg', `moon' \\ 3 & Default for vegetation & `grass' \\ & and implements & `pencil' \\ 4 & Vegetation forming natural collections & `tree' \\ & and implements that act collectively & `ember' \\ % 5 & Hair types & `eyelash' \\ & and midsize fruit growing in clusters & `tomato' \\ 6 & Individuable objects & `river' \\ 7 & Non-granular mass nouns & `water' \\ 8 & Pluralia tantum nouns, & `trousers' \\ & composite nouns & `necklace' \\ & and granular mass nouns & `rice' \\ 9 & Default & `shoe' \\ \botrule \end{tabular} \end{minipage} \end{center} \end{table} English has in few instances grammaticalized the diverse ways in which our minds perceive and structure the objects and ideas in the world with which we interact. For English nouns, the distinction between mass and count nouns comes to mind. Additionally, a major part of present-day English count nouns that never or occasionally take the suffix \textit{-s} in their plural form are animal nouns that are hunted (e.g., \textit{duck}, \textit{woodcock}, and \textit{elk}) or fished (\textit{salmon} and \textit{crab}) \citep[see][for lexemes other than animal names]{Quirk:etal:85} \citep[see][for an extended list of 85 animal nouns]{Toupin:2015}. We kept the stimuli in the present study simple and consistent by focusing on regular singular and plural forms. Further research is required that investigates varieties of plurals including irregular plurals (e.g., \textit{man} $\sim$ \textit{men}), zero plurals (\textit{fish} $\sim$ \textit{fish}), pluralia tantum (\textit{scissors} with no singular variant), singularia tantum (\textit{wealth} with no plural variant), or sense-specific plural formations (\textit{mouse} $\sim$ \textit{mice} for rodents and \textit{mouse} $\sim$ \textit{mouses} for computer input devices; \citealp{Acquaviva:2008:LexicalPlurals}). Many other languages reflect in their grammars a variety of ways in which nouns are perceived to cluster semantically. Whereas semantic differentiation in the nominal system is explicitly grammaticalized in these languages, semantic noun classes also play a role in the grammar of English, albeit mainly implicitly. By combining distributional semantics, WordNet, and t-SNE visualization, we have been able to detect that semantic noun clusters also structure English language use. \section*{Declarations} \subsection*{Funding} This research was funded by the European Research Council under the ERC grant number 742545, Project WIDE, awarded to the last author. The data processing of the NewsScape corpus was funded by the Competence Network for Scientific High Performance Computing in Bavaria to the third author. \subsection*{Conflict of interest/Competing interests} No potential conflict of interest was reported by the authors. \subsection*{Authors' contributions} E. S-B was responsible for data collection, analysis, interpretation, and wrote the first draft of the manuscript. M. M-T contributed to the~ data collection, analyses, and interpretation. P. U assembled the auditory resources, and contributed to data collection, interpretation, and writing. R. H. B contributed to the research planning, data analysis, interpretation, and writing. \noindent
{'timestamp': '2022-03-30T02:29:57', 'yymm': '2203', 'arxiv_id': '2203.15424', 'language': 'en', 'url': 'https://arxiv.org/abs/2203.15424'}
arxiv
\subsection{Visual Grounding} The visual grounding methods can be categorized into two-stage methods and one-stage methods. \textbf{Two-stage methods} divide the visual grounding process into two steps: generation and ranking. Specifically, a module such as selective search~\cite{uijlings2013selective}, region proposal network~\cite{ren2015faster}, or pre-trained detector~\cite{girshick2014rich,girshick2015fast,ren2015faster} is firstly used to generate proposals that contain objects. Then a multimodal ranking network will measure the similarity between the query sentence and proposals and select the best matching result. Early works~\cite{rohrbach2016grounding,mao2016generation,hu2016natural} only consider sentence-region level similarity. \citet{yu2018mattnet} decompose the query sentence and image into three modular components related to the subject, location, and relationship to model fine-grained similarity. Several studies~\cite{bajaj2019g3raphground,yang2019dynamic,yang2020graph,mu2021disentangled} incorporate graph learning to better model cross-modal alignment. The more related work to ours is Ref-NMS~\cite{chen2021ref}, which uses the query feature to guide the Non-Maximum Suppression on region proposals to increase the recall of critical objects. However, Ref-NMS~\cite{chen2021ref} can only be integrated into two-stage methods. Moreover, it cannot affect the visual backbone in feature extraction and proposal generation. \textbf{One-stage methods} extract visual feature maps that maintain the spatial structure and perform cross-modal interaction at pixel level. The fused feature maps are further used to predict bounding boxes. \citet{yang2019fast} use a Darknet~\cite{redmon2018yolov3} to extract feature maps and broadcast the query embedding to each spatial location. Several recent works~\cite{liao2020real,yang2020improving,ye2021one} regard multimodal interaction as a multi-step reasoning process to better understand the input query. \citet{huang2021look} extract landmark features with the guidance of a linguistic description. The more recent work TransVG~\cite{deng2021transvg} incorporates DETR encoder to extract visual features and proposes a transformer-based visual grounding framework. \citet{kamath2021mdetr} model the visual grounding as a modulated detection task and propose a novel framework MDETR derived from the DETR detector. \subsection{Transformer-based Visual Backbones} \citet{dosovitskiy2021an} propose to extract image features by applying a pure Transformer architecture on image patches. This method is called Vision Transformer (ViT) and achieves excellent results compared to state-of-the-art convolutional networks. \citet{pmlr-v139-touvron21a} introduce improved training strategies to train a data-efficient ViT. \citet{yuan2021tokens} propose a Tokens-to-Token transformation to obtain a global representation and a deep-narrow structure to improve the efficiency. Some recent works~\cite{chu2021we,han2021transformer} modify the ViT architecture for better performance. \citet{liu2021Swin} present a novel hierarchical ViT called Swin Transformer. It computes the representation with shifted windowing scheme to allow for cross-window connection. Due to the fixed window size, the architecture has linear computational complexity with respect to image size. \subsection{Multimodal Interaction} In early studies, multimodal systems use simple interaction methods such as concatenation, element-wise product, summation, and multilayer perception to learn the interaction~\cite{zadeh2017tensor,baltruvsaitis2018multimodal}. \citet{fukui2016multimodal} introduce a compact bilinear pooling to learn a more complex interaction. \citet{arevalo2017gated} present a gated unit that can learn to decide how modalities influence the activation. \cite{nguyen2018improved,nagrani2021attention} use the cross-attention mechanism to enable dense, bi-directional interactions between the visual and textual modalities. \citet{NIPS2017_6fab6e3a} introduce Conditional Batch Normalization at channel-level to modulate visual feature maps by a linguistic embedding. \citet{vaezi20mmtm} use squeeze and excitation operations to fuse the multimodal features and recalibrate the channel-wise visual features. There are also methods~\cite{zadeh2017tensor,baltruvsaitis2018multimodal,arevalo2017gated,vaezi20mmtm,NIPS2017_6fab6e3a} that only perform interaction at channel-level. However, spatial-level information is also important to some downstream tasks, e.g., visual grounding and visual commonsense reasoning. Other methods~\cite{fukui2016multimodal,nguyen2018improved,nagrani2021attention} maintain the spatial structure to perform interaction but have a high computational cost. \subsection{Visual Grounding} The visual grounding methods can be categorized into two-stage methods and one-stage methods. \textbf{Two-stage methods} divide the visual grounding process into two steps: generation and ranking. Specifically, a module such as selective search~\cite{uijlings2013selective}, Edge-box~\cite{zitnick2014edge}, Region Proposal Network, or pre-trained detector~\cite{girshick2014rich,girshick2015fast,ren2015faster} will generate proposals that contain objects. Then a multimodal ranking network will measure the similarity between the query sentence and proposals and select the best matching. Early works~\cite{rohrbach2016grounding,mao2016generation,hu2016natural} only considered sentence-region level similarity. \citet{yu2018mattnet} decomposed the query sentence and image into three modular components related to subject, location, and relationship to models fine-grained similarity. Several studies~\cite{bajaj2019g3raphground,yang2019dynamic,yang2020graph,mu2021disentangled} incorporated graph learning to better model cross-modal alignment. \citet{chen2021ref} proposed Ref-NMS to use the query feature to guide the Non-Maximum Suppression to increase the recall of critical objects. \textbf{One-stage methods} extract visual feature maps that maintaining the spatial structure and perform cross-modal interaction at pixel-level. The fused feature maps are further used to predict bounding boxes. \citet{yang2019fast} used a darknet\cite{redmon2018yolov3} to extract feature maps and broadcast the query embedding to each spatial location. Several works~\cite{liao2020real,yang2020improving,ye2021one} regarded multimodal interaction as a multiple step reasoning process to better understand the input query. \citet{huang2021look} extracted landmark feature with the guidance of linguistic description. The recent work TransVG~\cite{deng2021transvg} incorporated DETR encoder to extract visual features and proposed a transformer-based visual grounding framework. \citet{kamath2021mdetr} modeled the visual grounding as a modulated detection task and proposed a novel framework MDETR derived from the DETR detector. The most similar work to ours is Ref-NMS~\cite{chen2021ref} and MDETR~\cite{kamath2021mdetr}. However, Ref-NMS~\cite{chen2021ref} can only be integrated into two-stage methods. Moreover, it can not affect proposal generation and feature extraction. MDETR~\cite{kamath2021mdetr} requires 1.3M text-image pairs with explicit alignment annotation to train from scratch instead of initializing from the pre-trained DETR. In contrast, our MMSwin\ \ can be trained end-to-end and does not need multimodal pretraining. \subsection{Transformer based Visual Backbones} \citet{dosovitskiy2021an} proposed to extract image features by applying a pure Transformer architecture on image patches. The method achieves excellent results compared to state-of-the-art convolutional networks. These transformer-based visual backbones are called Vision Transformer (ViT). \citet{pmlr-v139-touvron21a} introduced training strategies to train a data-efficient ViT. \citet{yuan2021tokens} proposed a Tokens-to-Token transformation to obtain a global representation and a deep-narrow structure to improve its efficiency. Some works~\cite{chu2021we,han2021transformer} modified the ViT architecture for better performance. \citet{liu2021Swin} presented a novel hierarchical ViT called Swin Transformer. It computes the representation with shifted windowing scheme to allow for cross-window connection. Due to the fixed window size, the architecture has linear computational complexity with respect to image size. \subsection{Multimodal Interaction} In early studies, multimodal systems used simple interaction methods such as concatenation, element-wise product or summation, and fed to multilayer perception to learn the interaction~\cite{zadeh2017tensor,baltruvsaitis2018multimodal}. \citet{fukui2016multimodal} introduced a compact bilinear pooling to learn a more complex interaction. \citet{arevalo2017gated} presented a gated unit that can learn to decide how modalities influence the activation. \citet{nguyen2018improved,nagrani2021attention} used the cross-attention mechanism to enable dense, bi-directional interactions between the visual and textual modalities. \citet{NIPS2017_6fab6e3a} introduced Conditional Batch Normalization at channel-level to modulate visual feature maps by a linguistic embedding. \citet{vaezi20mmtm} used squeeze and excitation operations to fuse the multimodal features and recalibrate the channel-wise visual features. Some of these methods\cite{zadeh2017tensor,baltruvsaitis2018multimodal,arevalo2017gated,vaezi20mmtm,NIPS2017_6fab6e3a} only perform interaction at channel-level. However, spatial-level information is important to some downstream tasks, e.g., visual grounding and visual commonsense reasoning. The other methods~\cite{fukui2016multimodal,nguyen2018improved,nagrani2021attention} maintain the spatial structure to perform interaction but have a high computational cost. Moreover, these methods lead to uncertain feature spaces after their interactions, which is harmful to plug into the pre-trained networks. \subsection{Architecture} \begin{figure*}[htb] \includegraphics[width=1\textwidth]{figs/overview_2_cropped.pdf} \caption{(a) The QRNet-based visual grounding framework used in this paper. (b) An overview of our Query-modulated Refinement Network. (c) Illustration of Query-aware Dynamic Attention.} \label{fig:model} \end{figure*} In this section, we first formulate the visual grounding task and then present the architecture of the adopted framework. Visual grounding task aims at grounding a query onto a region of an image. The query refers to an object in the image and can be a sentence or a phrase. It can be formulated as: given an image $I$ and a query $q$, the model needs to predict a bounding box $\mathbf{b}=\{x,y,w,h\}$ which exactly contains the target object expressed by the query. As shown in \Cref{fig:model} (a), our framework is designed based on a typical end-to-end visual grounding architecture TransVG~\cite{deng2021transvg}\footnote{https://github.com/djiajunustc/TransVG}. Given an image and a query sentence, there is a linguistic backbone, typically a pre-trained BERT model, extracting a sequence of 1D feature $\mathbf{T}\in \mathbb{R}^{D_l\times N_l}$. For the visual backbone, we adopt a new Query-modulated Refinement Network\ (described in \Cref{sec:network}) to extract a flattened sequence of visual feature $\mathbf{V} \in \mathbb{R}^{D_v\times N_v}$. The major difference between the proposed Query-modulated Refinement Network\ and existing visual backbones is that we take the contextual textual feature from the linguistic backbone to guide the feature extraction and multiscale fusion with the help of Query-aware Dynamic Attention\ (described in \Cref{sec:QDA}). Two projection layers map the visual and linguistic features into the same feature space $\mathbb{R}^{D}$. The projected visual and linguistic features are denoted by $\mathbf{p}_v\in \mathbb{R}^{D\times N_v}$ and $\mathbf{p}_l\in \mathbb{R}^{D\times N_l}$. Then $\mathbf{p}_v$ and $\mathbf{p}_l$ are concatenated by inserting a learnable embedding (i.e., a [REG] token) at the beginning of the concatenated sequence. The joint sequence is formulated as: \begin{equation} \begin{aligned} \boldsymbol{X}=[\mathbf{p}_{r}, \underbrace{\mathbf{p}_{v}^{1}, \mathbf{p}_{v}^{2}, \cdots, \mathbf{p}_{v}^{N_{v}}}_{\text {visual tokens } \boldsymbol{p}_{v}}, \underbrace{\mathbf{p}_{l}^{c}, \mathbf{p}_{l}^{1}, \cdots, \mathbf{p}_{l}^{N_{l}}}_{\text {linguistic tokens } \boldsymbol{p}_{l}}], \end{aligned} \end{equation} where $\mathbf{p}_r$ is the learnable embedding of [REG] token. $\mathbf{p}_l^c$ is the [CLS] token's representation which is regarded as the contextual textual feature. Next, a multi-layer visual-linguistic transformer is applied to perform intra- and inter-modal reasoning on the joint sequence. Finally, a prediction head takes the output representation of the [REG] token to predict the bounding box coordinates $\mathbf{b}$. The smooth L1 loss~\cite{girshick2015fast} and giou loss~\cite{rezatofighi2019generalized} are used to train the framework. The training objective can be formulated as: \begin{equation} \begin{aligned} \mathcal{L}=\mathcal{L}_{smooth-l1}{(\mathbf{b},\mathbf{\hat{b}})}+\mathcal{L}_{giou}{(\mathbf{b},\mathbf{\hat{b}})}, \end{aligned} \end{equation} where $\mathbf{\hat{b}}$ is the ground-truth box. \subsection{Query-modulated Refinement Network} \label{sec:network} In this section, we introduce the proposed visual backbone of Query-modulated Refinement Network\ (MMSwin\ ). An overview of the network is shown in \Cref{fig:model} (b). The network consists of two phases: (1) Query-refined Feature Extraction for extracting query-refined visual feature maps with a hierarchical structure, (2) Query-aware Multiscale Fusion for fusing the extracted feature maps at different scales with the guidance of the query feature. The two phases both rely on a novel Query-aware Dynamic Attention (QD-ATT), which dynamically computes textual-dependent visual attentions at spatial and channel levels, to enable to compute features with query guidance. In the following, we will first introduce the implementation of the Query-aware Dynamic Attention. Then we detail the Query-refined Feature Extraction and Multiscale Fusion. \subsubsection{Query-aware Dynamic Attention} \label{sec:QDA} Now, we will describe the details of our Query-aware Dynamic Attention (shown in \cref{fig:model}(c)). We first introduce the dynamic linear layer, which learns a linear transformation that can be applied to the visual features to compute the query-aware attentions. Different from the conventional trainable linear layer, the parameters of the dynamic linear layer are generated dynamically based on textual features. Next, we will illustrate how to use the dynamic linear layer to compute query-aware channel and spatial attentions and obtain the query-consistent visual features. A pseudo-code is presented in the Appendix for better comprehension. \paragraph{Dynamic Linear Layer.} Existing visual backbones use modules with static parameters to compute the visual feature maps, where feeding in the same image will output the same feature maps. However, in visual grounding, different queries for a single image may reveal different semantic information and intentions, which require different visual features. We present a dynamic linear layer which can leverage the contextual textual feature $\mathbf{p}_l^c\in \mathbb{R}^{D_l}$ to guide the mapping from an given input vector $\mathbf{z}_{in}\in \mathbb{R}^{D^{in}}$ to the output $\mathbf{z}_{out}\in \mathbb{R}^{D^{out}}$. The dynamic linear layer is formalized as follow: \begin{equation} \begin{aligned} \mathbf{z}_{out}&=\mathrm{DyLinear}_{\mathcal{M}_l}(\mathbf{z}_{in})=\mathbf{W}_l^\intercal \mathbf{z}_{in}+\mathbf{b}_l \end{aligned} \end{equation} where $\mathcal{M}_l=\{\mathbf{W}_l,\mathbf{b}_l\},\,\mathbf{W}_l\in \mathbb{R}^{D^{in}\times D^{out}},\, \mathbf{b}_l\in \mathbb{R}^{D^{out}}$. $D^{in}$ and $D^{out}$ are the dimensions of input and output, respectively. We use a plain linear layer to generate the $\mathcal{M}_l$. The generator is denoted by $\mathcal{M}^{'}_l=\Psi(\mathbf{p}_l^c)$, where $\mathcal{M}^{'}_l\in\mathbb{R}^{(D^{in}+1)\ast D^{out}}$. In detail, we predict a $(D^{in}+1)*D^{out}$ vector which can be reshaped to $\mathcal{M}_l$. However, it is easy to find that the number of parameters in the generator, i.e., $D_l\ast ((D^{in}+1)\ast D^{out})$, is too large. Such large-scale parameters will slow down the speed of the network and make it easier to be overfitting. Inspired by matrix factorization, we consider decomposing the $\mathcal{M}_l$ into two factors $\mathbf{U}\in \mathbb{R}^{(D^{in}+1)\times K}$ and $\mathbf{S}\in \mathbb{R}^{K\times D^{out}}$, where $\mathbf{U}$ is a matrix generated from $\mathbf{p}_l^c$, $\mathbf{S}$ is a static learnable matrix, $K$ is a hyper-parameter denoting the factor dimension. The factor generator $\{\mathbf{W}_l,\mathbf{b}_l\}=\Psi^*(\mathbf{p}_l^c)$ can be formulated as follow: \begin{equation} \begin{aligned} & \mathbf{U}=\mathrm{Reshape}({\mathbf{W}_{g}}^\intercal \mathbf{p}_l^c+\mathbf{b}_{g}),\\ & \mathcal{M}_l=\mathbf{U}\mathbf{S},\\ & \{\mathbf{W}_l,\mathbf{b}_l\}= \mathrm{Split}(\mathcal{M}_l),\\ \end{aligned} \end{equation} where $\mathbf{W}_{g}\in \mathbb{R}^{D_l\times (D^{in}+1)\ast K}$ and $ \mathbf{b}_{g}\in \mathbb{R}^{(D^{in}+1)\ast K}$ are trainable parameters of the factor generator. The parameter matrix $\mathcal{M}_l$ of the dynamic linear layer can be reconstructed by multiplying $\mathbf{U}$ and $\mathbf{S}$. The $\mathbf{W}_l$ and $\mathbf{b}_l$ can be split from the matrix $\mathcal{M}_l$ along the first dimension. Finally, we reformulate the dynamic linear layer as follows: \begin{equation} \begin{aligned} \mathbf{z}_{out}&=\mathrm{DyLinear}_{\mathcal{M}_l}(\mathbf{z}_{in})=\mathrm{DyLinear}_{\Psi^*(\mathbf{p}_l^c)}(\mathbf{z}_{in}). \end{aligned} \end{equation} Unless otherwise specified, we use $\mathrm{DyLinear}(\mathbf{z}_{in})$ to represent a dynamic linear layer with $\mathbf{p}_l^c$ for simplify. And the different dynamic linear layers do not share parameters. When the input is a multidimensional tensor, the dynamic linear layer transforms the input at the last dimension. \paragraph{Channel and Spatial Attention.} As explained above, the pre-trained visual backbone is sensitive to all the objects it learned in the pre-training task. However, only the object which is referred to by the query text is useful. Besides, the features useful for the bounding box prediction highly depend on the semantics contained in the query sentence (e.g. entities, descriptions of attributes, and relationships). In other words, the importance of each channel or each region of the feature map should change dynamically according to the query sentence. Inspired by Convolutional Block Attention Module~\cite{woo2018cbam}, we consider inferring channel and spatial attentions, i.e., $\mathbf{A}^{cl}$ and $\mathbf{A}^{sl}$, along the separate dimensions of the feature map to obtain adaptively refined features for a better cross-modal alignment. Specifically, for a given visual feature map $\mathbf{F}\in \mathbb{R}^{H\times W\times D_v}$, we first aggregate its spatial information by average and maximum pooling and produce $\mathbf{F}^c_{max},\,\mathbf{F}^c_{mean}\in \mathbb{R}^{1\times 1\times D_v}$. Then, a dynamic multilayer perception consisting of two dynamic linear layers with a ReLU activation in the middle is built to process the pooled features. The output dimension is the same as the input dimension. To reduce the number of parameters, we set the dimension of multilayer perception's hidden states as $D_v/r$, where $r=16$ is a reduction ratio. By feeding the $\mathbf{F}^c_{max}$ and $\mathbf{F}^c_{mean}$ to the dynamic multilayer perception, a Sigmoid function is applied to the summation of the two output features. The channel attention map $\mathbf{A}^{cl}$ can be captured as follow: \begin{equation} \begin{aligned} \mathbf{F}^{cl}_{mean}&=\mathrm{DyLinear}_{1}(\mathrm{ReLU}(\mathrm{DyLinear}_{2}(\mathbf{F}^c_{mean}))\\ \mathbf{F}^{cl}_{max}&=\mathrm{DyLinear}_{1}(\mathrm{ReLU}(\mathrm{DyLinear}_{2}(\mathbf{F}^c_{max}))\\ \mathbf{A}^{cl}&=\mathrm{Sigmoid}(\mathbf{F}^{cl}_{mean}+\mathbf{F}^{cl}_{max}). \end{aligned} \end{equation} We perform element-wise multiplication between $\mathbf{F}$ and $\mathbf{A}^{cl}$ to form the channel-wise refined visual feature, where the $\mathbf{A}^{cl}$ is broadcast along the spatial dimension: \begin{equation} \begin{aligned} \mathbf{F}^{'}&=\mathbf{A}^{cl}\otimes \mathbf{F}. \end{aligned} \end{equation} To generate a spatial attention map, instead of squeezing the channel dimension, we leverage another dynamic linear layer to reduce the channel dimension to learn areas of interest to the query and apply an activation function Sigmoid to generate the attention map. In short, the computing process is formulated as follows: \begin{equation} \begin{aligned} \mathbf{A}^{sl}&=\mathrm{Sigmoid}(\mathrm{DyLinear}_{3}(\mathbf{F}^{'}))\\ \mathbf{F}^{''}&=\mathbf{A}^{sl}\otimes \mathbf{F}^{'} \end{aligned} \end{equation} where $\mathbf{A}^{sl}\in \mathbb{R}^{H\times W\times 1}$ is the spatial attention map and $\mathbf{F}^{''}$ is the spatially refined visual feature and also the output of our Query-aware Dynamic Attention. \subsubsection{Query-refined Feature Extraction} To extract refined feature maps with the guidance of the query feature, we extend the Swin-Transformer\footnote{https://github.com/SwinTransformer/Swin-Transformer-Object-Detection} to a modulated visual feature extractor. As shown in \Cref{fig:model} (b), for a given image $I \in \mathbb{R}^{H\times W\times 3}$, a patch partition operation is firstly adopted to embed $I$ to $\mathbf{F}_0 \in \mathbb{R}^{\frac{H}{4}\times \frac{W}{4}\times C}$, where $C$ is the embed dimension. Then $\mathbf{F}_0$ is fed into four cascaded stages, where each stage consists of multiple Swin-Transformer blocks and a QD-ATT\ module. In this work, we take the [CLS] representation of the input query sentence from BERT~\cite{devlin2018bert} as the contextual query representation $\mathbf{p}_l^c$ to compute the query-aware dynamic attention. The $k$-th stage receives the visual feature map $\mathbf{F}_{k-1}^*$ (or $\mathbf{F}_0$ if $k=1$) obtained in the previous stage and generates a transformed feature map $\mathbf{F}_{k}$ through the Swin-Transformer blocks. Then, the QD-ATT\ module takes the transformed feature $\mathbf{F}_{k}$ and produces a query-aware feature $\mathbf{F}_k^{*}$ that will be further used in the next stage. The output of the query-refined feature extractor is a list of hierarchical features $[\mathbf{F}_{1}^{*},\mathbf{F}_{2}^{*},\mathbf{F}_{3}^{*},\mathbf{F}_{4}^{*}]$. \subsubsection{Query-aware Multiscale Fusion}\label{sec:multiscale} Multiscale features are beneficial to detecting objects at different scales~\cite{DBLP:conf/eccv/CaiFFV16}. However, because visual grounding requires fine-grained interaction after visual backbone (\eg Cross Attention), high-resolution features will dramatically increase the computation. Therefore, previous works always use the low-resolution features or fuse the multiscale features in a query-agnostic manner, which will lose scale information or incorporate noise. Thanks to the hierarchical structure of the modulated Swin-Transformer, we can obtain multiscale features. We fuse the features obtained from different stages with the help of Query-aware Dynamic Attention mechanism and pooling operation. We flatten and concatenate the low-resolution features as the output token sequence of the backbone. Specifically, except for the first stage, each stage reduces the resolution of the feature map by a patch merging operator. In other words, the resolutions of the output feature maps at four stages are $\frac{H}{4}\times\frac{W}{4},\,\frac{H}{8}\times\frac{W}{8},\,\frac{H}{16}\times\frac{W}{16}$ and $\frac{H}{32}\times\frac{W}{32}$, respectively. Besides, the patch merging operator fuses the patch features into the channel which doubles the channel dimension. Thus the channel dimensions of the output at the four stages are $C,\,2C,\,4C$ and $8C$, respectively. Next, we will introduce how to efficiently fuse these multiscale features with the guidance of the query text. As shown in \Cref{fig:model} (b), we propose to fuse the output features at different stages with the help of QD-ATT. Specifically, we first use four $1\times 1$ convolutional layers to unify the channel dimensions to $D$. To filter out noisy signals in the feature maps, we build QD-ATT\ modules for the feature maps $\{\mathbf{F}^{*}_k |\,k=1,2,3 \}$ of the first three stages. From $\mathbf{F}^{*}_k$, the QD-ATT\ module produces a weighted feature map with the same size as the input. We apply a $2\times 2$ mean pooling with stride=2 to reduce the resolution to be the same as the next feature map $\mathbf{F}^{*}_{k+1}$ and compute the average of them to obtain $\mathbf{\bar{F}}^{*}_{k+1}$. Finally, the last feature map $\mathbf{\bar{F}}^{*}_{4}$ contains features of interest to the query from all scales. To detect very large objects, we also apply a $2\times 2$ max pooling to obtain a $\frac{H}{64}\times\frac{W}{64}$ feature map $\mathbf{\bar{F}}^{*}_{5}$. We flatten and concatenate the $\mathbf{\bar{F}}^{*}_{4}$ and $\mathbf{\bar{F}}^{*}_{5}$ as the output token sequence $\mathbf{V}$. \subsection{Preliminary} Visual grounding task aims at grounding a query sentence onto a region of an image. It can be formulated as: given an image $I$ and a query sentence $q$, the model needs to learn to predict a bounding box $\mathbf{b}=\{x,y,w,h\}$ which exactly contains the target object expressed by the sentence. Before introducing our method, we firstly present a typical end-to-end visual grounding architecture TransVG~\cite{deng2021transvg}. Given an image and a query sentence, there is a linguistic backbone, typically a pre-trained BERT model, extracting a 1D feature sequence $\mathbf{T}\in \mathbb{R}^{D_l\times N_l}$. There is also a visual backbone (\eg DETR Encoder\cite{carion2020end}) extracting a flattened visual feature sequence $\mathbf{V} \in \mathbb{R}^{D_v\times N_v}$. Two projection layers map the visual and linguistic features into the same feature space $\mathbb{R}^{D}$. The projected visual and linguistic features are denoted by $\mathbf{p}_v\in \mathbb{R}^{D\times N_v}$ and $\mathbf{p}_l\in \mathbb{R}^{D\times N_l}$. Then $p_v$ and $p_l$ are concatenated by inserting a learnable embedding (i.e., a [REG] token) at the beginning of the concatenated sequence. The joint sequence is formulated as: \begin{equation} \begin{aligned} \boldsymbol{x}_{0}=[\mathbf{p}_{r}, \underbrace{\mathbf{p}_{v}^{1}, \mathbf{p}_{v}^{2}, \cdots, \mathbf{p}_{v}^{N_{v}}}_{\text {visual tokens } \boldsymbol{p}_{v}}, \underbrace{\mathbf{p}_{l}^{1}, \mathbf{p}_{l}^{2}, \cdots, \mathbf{p}_{l}^{N_{l}}}_{\text {linguistic tokens } \boldsymbol{p}_{l}}], \end{aligned} \end{equation} where $p_r$ is the learnable embedding of [REG] token. Next, a multi-layer visual-linguistic transformer is applied to perform intra- and inter-modal reasoning on the joint sequence. Finally, a prediction head takes the output representation of the [REG] token to predict the bounding box coordinates $\mathbf{b}$. The smooth L1 loss~\cite{girshick2015fast} and giou loss~\cite{rezatofighi2019generalized} are used to train the framework. The training objective can be formulated as: \begin{equation} \begin{aligned} \mathcal{L}=\mathcal{L}_{smooth-l1}{(\mathbf{b},\mathbf{\hat{b}})}+\mathcal{L}_{giou}{(\mathbf{b},\mathbf{\hat{b}})}, \end{aligned} \end{equation} where $\mathbf{\hat{b}}$ is the ground-truth box. \begin{figure*}[tb] \includegraphics[width=1\textwidth]{figs/overview_2_cropped.pdf} \caption{(a) The typical visual grounding framework we used in this paper. (b) An overview of our MMSwin\ . The image is } \label{fig:model} \end{figure*} \subsection{Motivation and Overview} \paragraph{Motivation} As explained earlier, the visual features extracted from query-agnostic visual backbones have spatial and semantic inconsistencies. The inconsistencies hinder the multimodal interaction and hurt the models' performance. In this paper, we propose to mitigate the spatial and semantic inconsistent issues by leveraging textual features to guide the visual backbone with Query-aware Dynamic Attention, which dynamically computes textual-dependent visual attention maps at spatial and channel level. We refine the feature maps during the feature extraction and multiscale fusion processes and output a query-consistent visual feature. We designing a flexible visual grounding framework based on the TransVG\footnote{https://github.com/djiajunustc/TransVG} by replacing the visual backbone with our MMSwin\ . The complete framework is shown in \Cref{fig:model} (a). We next focus on the visual backbone proposed in this paper. \paragraph{Overview} We build the modulated multiscale visual backbone on a hierarchical visual backbone Swin-Transformer. We show the overall architecture in \Cref{fig:model} (b). During the feature extraction, a patch merge downsamples the input image and divides it into patches, and then there are four cascading stages. For simple representation, we denote the modules from pre-trained Swin-Transformer in the stage as Swin-Transformer Modules. Each stage also contains a Query-aware Dynamic Attention which takes the textual representation to refine the visual feature maps. Except for the first stage, the other three stages will obtain the feature of resolution divided by 2. During the multi-scale fusion stage, we fuse the features from each scale with the help of Query-aware Dynamic Attention and pooling operation. We flatten and concatenate the low-resolution features as the output token sequence of the backbone. In the following, we first introduce the Query-aware Dynamic Attention (in \Cref{sec:QDA}) and how we build a modulated multiscale visual backbone with the Query-aware Dynamic Attention (in \Cref{sec:MMSwin}). \subsection{Query-aware Dynamic Attention} \label{sec:QDA} In this section, we describe the details of our Query-aware Dynamic Attention (shown in \cref{fig:model}(c)). We first introduce the dynamic linear layer, which learns a linear transformation applied to the visual features. The difference is that the parameters of the linear transformation is not static and will be generated dynamically by textual features. We use dynamic linear layers to extract query-aware visual clues from the input visual features. We further introduce channel and spatial attention to refine the visual features with help of visual clues to produce query-consistent visual features. \paragraph{Dynamic Linear Layer} The existing visual feature extractor uses modules with static parameters to compute the visual feature maps. Feeding in the same image will output the same feature maps. However, in visual grounding, the textual features reveals the intention of the query. We present a dynamic linear which leverages the contextual textual feature $\mathbf{p}_l^c$ to guide the linear transformation to map an input vector $\mathbf{z}_{in}\in \mathbb{R}^{D^{in}}$ to $\mathbf{z}_{out}\in \mathbb{R}^{D^{out}}$. The dynamic linear layer can be formalized as follow: \begin{equation} \begin{aligned} \mathbf{z}_{out}&=\mathrm{DyLinear}_{\mathcal{M}_l}(\mathbf{z}_{in})=\mathbf{W}_l^\intercal \mathbf{z}_{in}+\mathbf{b}_l \end{aligned} \end{equation} where $\mathcal{M}_l=\{\mathbf{W}_l,\mathbf{b}_l\},\,\mathbf{W}_l\in \mathbb{R}^{D^{in}\times D^{out}},\, \mathbf{b}_l\in \mathbb{R}^{D^{out}}$, and $D^{in}$ and $D^{out}$ are the dimensions of input and output respectively. We use a plain linear layer to generate the $\mathcal{M}_l$. The generator is denoted by $\mathcal{M}_l=\Psi(\mathbf{p}_l^c)$, where $\mathcal{M}^{'}_l\in\mathbb{R}^{(D^{in}+1)\ast D^{out}}$. In detail, we obtain a vector with shape $(D^{in}+1)*D^{out}$ and reshape it to $\mathcal{M}_l$. However, it is easy to find that the number of parameters in the generator is $D_l\ast ((D^{in}+1)\ast D^{out})$. We find that such large-scale parameters will slow down the training speed of the network and make it easier to be overfitting. Inspired by matrix factorization, we consider decomposing the $\mathcal{M}_l$ into two factor $\mathbf{U}\in \mathbb{R}^{(D^{in}+1)\times K}$ and $\mathbf{S}\in \mathbb{R}^{K\times D^{out}}$, where $\mathbf{U}$ is a matrix generate from $\mathbf{p}_l^c$, $\mathbf{S}$ is a static learnable matrix, $K$ is a hyper-parameter denote the factor dimension. The factor generator $\{\mathbf{W}_l,\mathbf{b}_l\}=\Psi^*(\mathbf{p}_l^c)$ can be formulated as follow: \begin{equation} \begin{aligned} \mathbf{U}&=\mathrm{Reshape}({\mathbf{W}_{g}}^\intercal \mathbf{p}_l^c+\mathbf{b}_{g}) \end{aligned} \end{equation} where $\mathbf{W}_{g}\in \mathbb{R}^{D_l\times (D^{in}+1)\ast K}$ and $ \mathbf{b}_{g}\in \mathbb{R}^{(D^{in}+1)\ast K}$ are the parameters of the factor generator \begin{equation} \begin{aligned} \mathcal{M}_l&=\mathbf{U}\mathbf{S}\\ \{\mathbf{W}_l,\mathbf{b}_l\} &= \mathrm{Split}(\mathcal{M}_l)\\ \end{aligned} \end{equation} Then the parameter matrix of dynamic linear layer $\mathcal{M}_l$ can be reconstructed by multiply $\mathbf{U}$ and $\mathbf{S}$. The $\mathbf{W}_l$ and $\mathbf{b}_l$ can be split from the matrix $\mathcal{M}_l$ along the first dimension. Finally, we reformulate the guidance function as follow: \begin{equation} \begin{aligned} \mathbf{z}_{out}&=\mathrm{DyLinear}_{\mathcal{M}_l}(\mathbf{z}_{in})=\mathrm{DyLinear}_{\Psi^*(\mathbf{p}_l^c)}(\mathbf{z}_{in}) \end{aligned} \end{equation} Unless otherwise specified, the different $\mathrm{DyLinears}$ do not share parameters. And when the input is a multidimensional tensor, the layer transforms the input at the channel dimension. \paragraph{Channel and Spatial Attention} As we can obtain the visual clues, we consider refining the visual feature map by attention mechanism. As explained earlier, the pre-trained visual backbone is sensitive to all salient objects. Most of them are irrelevant to the query text. Therefore, The backbone only needs to attend to a few areas. Besides, The features useful for localization depend on the semantics contained in the query sentence (e.g. entities, descriptions of attributes and relationships). In other words, the importance of each channel in the features should change dynamically according to the query sentence. Inspired by the Convolutional Block Attention Module\cite{woo2018cbam}, we consider inferring a channel attention map $\mathbf{A}^{cl}$ to calibrate the semantic of feature for a better cross-modal alignment. And we further infer a spatial attention map $\mathbf{A}^{sl}$ from calibrated feature to reveal where the referent located. Specifically, for a given visual feature $\mathbf{v}\in \mathbb{R}^{H\times W\times D_v}$, we first aggregate its spatial information by average pooling and maximum pooling and produce $\mathbf{v}^c_{max},\,\mathbf{v}^c_{mean}\in \mathbb{R}^{1\times 1\times D_v}$. We further build a dynamic multilayer perception consists of two dynamic linear layers. We use a ReLU activation after the first layer. The output dimension is the same as the input dimension. To reduce the number of parameter, we set the dimension of hidden states as $D_v/r$, where $r$ is the reduction ratio. By feeding the $\mathbf{v}^c_{max}$ and $\mathbf{v}^c_{mean}$ to the dynamic multilayer perception. We merge the two output features using summation. The channel attention map $\mathbf{A}^{cl}$ can be captured as follow: \begin{equation} \begin{aligned} \mathbf{v}^{cl}_{mean}&=\mathrm{DyLinear}_1(\mathrm{ReLU}(\mathrm{DyLinear}_0(\mathbf{v}^c_{mean},p_l^c)),\mathbf{p}_l^c)\\ \mathbf{v}^{cl}_{max}&=\mathrm{DyLinear}_1(\mathrm{ReLU}(\mathrm{DyLinear}_0(\mathbf{v}^c_{max},p_l^c)),\mathbf{p}_l^c)\\ \mathbf{A}^{cl}&=\mathrm{sigmoid}(\mathbf{v}^{cl}_{mean}+\mathbf{v}^{cl}_{max}) \end{aligned} \end{equation} We perform element-wise multiplication between $\mathbf{v}$ and $\mathbf{A}^{cl}$ to form the representation of the channel refined visual feature, where the $A^{cl}$ are broadcast along the spatial dimension: \begin{equation} \begin{aligned} \mathbf{V}^{'}&=\mathbf{A}^{cl}\otimes \mathbf{V} \end{aligned} \end{equation} To generate a spatial attention map, instead pooling the channel dimension, we leverage another dynamic linear layer to reduce the channel dimension to learn areas interest to the query and apply a sigmoid function to generate the attention map. In short, The computing process is formulated as follow: \begin{equation} \begin{aligned} \mathbf{A}^{sl}&=\mathrm{sigmoid}(\mathrm{DyLinear}_2(\mathbf{v}^{'},\mathbf{p}_l^c))\\ \mathbf{v}^{''}&=\mathbf{A}^{cl}\otimes \mathbf{v}^{'} \end{aligned} \end{equation} where $\mathbf{A}^{sl}\in \mathbb{R}^{H\times W\times 1}$ is the spatial attention map and $\mathbf{v}^{''}$ is the spatial refined visual feature and also the output of our Query-aware Dynamic Attention. \subsection{Query-modulated Transformer} \label{sec:MMSwin} In this section, we discuss how to use query-aware dynamic attention to extend Swin-Transformer\footnote{https://github.com/SwinTransformer/Swin-Transformer-Object-Detection} to a modulated visual backbone. \paragraph{Query-aware Attention in Feature Extraction} For a given image $I \in \mathbb{R}^{H\times W\times 3}$, a plain Swin-Transformer first embed $I$ to a $\mathbf{v}_0 \in \mathbb{R}^{\frac{H}{4}\times \frac{W}{4}\times 48}$. Then $\mathbf{v}_0$ is fed into four cascaded stages. Each stage $k$ receives the visual feature map $\mathbf{v}_{k-1}^*$ or $\mathbf{v}_0$ and generates a transformed feature map $\mathbf{v}_{k}$. We take the [CLS] representation of the input query sentence from BERT\cite{devlin2018bert} as the contextual query representation $\mathbf{p}_l^c$. We append a query-aware dynamic attention module at the end of each stage. It receives the transformed feature $\mathbf{v}_{k}$ from Swin-Transformer Blocks and produces a query-aware feature $\mathbf{v}_k^{*}$ to the next stage. \paragraph{Query-aware Attention in Multiscale Fusion} \label{sec:multiscale} Thanks to the hierarchical structure, we can obtain features at different scales from each stage. Specifically, except the first stage, each stage reduce the resolution of feature map by a patch merging operator. In other words, the resolutions of the output of each stage are $\frac{H}{4}\times\frac{W}{4},\,\frac{H}{8}\times\frac{W}{8},\,\frac{H}{16}\times\frac{W}{16}$ and $\frac{H}{32}\times\frac{W}{32}$, respectively. Beside, the patch merging operator fuse the patch feature into channel which double the channel dimension. Thus the channel dimensions of the output of each stage are $C,\,2C,\,4C$ and $8C$. Multiscale features are benefit to detect objects at different scale. however, because visual grounding require fine-grained interaction after visual backbone (\eg Cross Attention), high-resolution features will dramatically increase the computation. Previous works using the last feature or fuse the multiscale features by a query-agnostic fusion will obviously lose scale information or incorporate noise. As shown in \Cref{fig:model} (b), we propose to fuse the features with the QD-ATT. Specifically, we first use four $1\times 1$ convolutional layers to unify the channel dimensions to $D$. To filter out noisy signals in the feature maps, we build QD-ATT\ modules for the first three feature maps $\{\mathbf{v}^{*}_k |\,k=1,2,3 \}$. From $\mathbf{v}^{*}_0$, each module produce a weighted feature map with the same shape as before. We apply a $2\times 2$ mean pooling with stride=2 to reduce the resolution to be the same as next feature map $\mathbf{v}^{*}_k$ and compute the average of them to obtain $\mathbf{\bar{v}}^{*}_{k+1}$. Finally, the last feature map $\mathbf{\bar{v}}^{*}_{4}$ contains features interest to the query from all scales. To detect very large objects, we also apply a $2\times 2$ max pooling to obtain a $\frac{H}{64}\times\frac{W}{64}$ feature map $\mathbf{\bar{v}}^{*}_{5}$. We flatten and concatenate the $\mathbf{\bar{v}}^{*}_{4}$ and $\mathbf{\bar{v}}^{*}_{5}$ as the output token sequence $\mathbf{V}$. \subsection{Architecture} {\color{red}In this section, we first formulate the visual grounding task and present the architecture of the framework we used.} Visual grounding task aims at grounding a query sentence onto a region of an image. It can be formulated as: given an image $I$ and a query sentence $q$, the model needs to learn to predict a bounding box $\mathbf{b}=\{x,y,w,h\}$ which exactly contains the target object expressed by the sentence. {\color{red}As shown in \Cref{fig:model} (a), our framework is based on a typical end-to-end visual grounding architecture TransVG~\cite{deng2021transvg}\footnote{https://github.com/djiajunustc/TransVG}} Given an image and a query sentence, there is a linguistic backbone, typically a pre-trained BERT model, extracting a 1D feature sequence $\mathbf{T}\in \mathbb{R}^{D_l\times N_l}$. {\color{red}We propose the Query-modulated Refinement Network\ (described in \Cref{sec:network}) as a visual backbone to extract a flattened visual feature sequence $\mathbf{V} \in \mathbb{R}^{D_v\times N_v}$. The different is that the backbone take the contextual textual feature from the linguistic backbone to refine the feature extraction and multiscale fusion with the help of Query-aware Dynamic Attention\ (described in \Cref{sec:QDA}).} Two projection layers map the visual and linguistic features into the same feature space $\mathbb{R}^{D}$. The projected visual and linguistic features are denoted by $\mathbf{p}_v\in \mathbb{R}^{D\times N_v}$ and $\mathbf{p}_l\in \mathbb{R}^{D\times N_l}$. Then $\mathbf{p}_v$ and $\mathbf{p}_l$ are concatenated by inserting a learnable embedding (i.e., a [REG] token) at the beginning of the concatenated sequence. The joint sequence is formulated as: \begin{equation} \begin{aligned} \boldsymbol{X}=[\mathbf{p}_{r}, \underbrace{\mathbf{p}_{v}^{1}, \mathbf{p}_{v}^{2}, \cdots, \mathbf{p}_{v}^{N_{v}}}_{\text {visual tokens } \boldsymbol{p}_{v}}, \underbrace{\mathbf{p}_{l}^{c}, \mathbf{p}_{l}^{1}, \cdots, \mathbf{p}_{l}^{N_{l}}}_{\text {linguistic tokens } \boldsymbol{p}_{l}}], \end{aligned} \end{equation} where $p_r$ is the learnable embedding of [REG] token. Next, a multi-layer visual-linguistic transformer is applied to perform intra- and inter-modal reasoning on the joint sequence. Finally, a prediction head takes the output representation of the [REG] token to predict the bounding box coordinates $\mathbf{b}$. The smooth L1 loss~\cite{girshick2015fast} and giou loss~\cite{rezatofighi2019generalized} are used to train the framework. The training objective can be formulated as: \begin{equation} \begin{aligned} \mathcal{L}=\mathcal{L}_{smooth-l1}{(\mathbf{b},\mathbf{\hat{b}})}+\mathcal{L}_{giou}{(\mathbf{b},\mathbf{\hat{b}})}, \end{aligned} \end{equation} where $\mathbf{\hat{b}}$ is the ground-truth box. \begin{figure*}[tb] \includegraphics[width=1\textwidth]{figs/overview_2_cropped.pdf} \caption{(a) The QRNet-based visual grounding framework we used in this paper. (b) An overview of our Query-modulated Refinement Network. (c) The illustration of Query-aware Dynamic Attention.} \label{fig:model} \end{figure*} \subsection{Query-modulated Refinement Network} \label{sec:network} {\color{red} In this section, we introduce our modulated visual backbone Query-modulated Refinement Network\ (MMSwin\ ). An overview of the network is shown in \Cref{fig:model} (b). The network consists of two phases: (1) Query-refined Feature Extraction extracts query-refined visual feature maps with a hierarchical structure. (2) Multi-scale Fusion fuses the maps at different scales with the guidance of the query feature. The two phases both rely on a novel Query-aware Dynamic Attention (QD-ATT), which dynamically computes textual-dependent visual attentions at spatial and channel level, to enable to compute features with query guidance. Thus, in the following, we will first introduce implementation of the Query-aware Dynamic Attention. Then we detail the Query-refined Feature Extraction and Multi-scale Fusion. } \subsubsection{Query-aware Dynamic Attention} \label{sec:QDA} In this section, we describe the details of our Query-aware Dynamic Attention (shown in \cref{fig:model}(c)). We first introduce the dynamic linear layer, which learns a linear transformation that can be applied on the visual features to compute the query-aware attentions. Different from the conventional trainable linear layer, the parameters of the dynamic linear layer are generated dynamically based on textual features. Next, we will illustrate how to use the dynamic linear layer to compute query-aware channel and spatial attentions and obtain the query-consistent visual features. A pseudo-code is presented in the Appendix for better comprehension. \paragraph{Dynamic Linear Layer} Existing visual backbones use modules with static parameters to compute the visual feature maps, where feeding in the same image will output the same feature maps. However, in visual grounding, different queries for a single image may reveal different semantic information and intentions, which require different visual features. We present a dynamic linear layer which can leverage the {\color{red}contextual textual feature $\mathbf{p}_l^c\in \mathbb{R}^{D_l}$} to guide the mapping from an given input vector $\mathbf{z}_{in}\in \mathbb{R}^{D^{in}}$ to the output $\mathbf{z}_{out}\in \mathbb{R}^{D^{out}}$. The dynamic linear layer is formalized as follow: \begin{equation} \begin{aligned} \mathbf{z}_{out}&=\mathrm{DyLinear}_{\mathcal{M}_l}(\mathbf{z}_{in})=\mathbf{W}_l^\intercal \mathbf{z}_{in}+\mathbf{b}_l \end{aligned} \end{equation} where $\mathcal{M}_l=\{\mathbf{W}_l,\mathbf{b}_l\},\,\mathbf{W}_l\in \mathbb{R}^{D^{in}\times D^{out}},\, \mathbf{b}_l\in \mathbb{R}^{D^{out}}$. $D^{in}$ and $D^{out}$ are the dimensions of input and output, respectively. We use a plain linear layer to generate the $\mathcal{M}_l$. The generator is denoted by $\mathcal{M}^{'}_l=\Psi(\mathbf{p}_l^c)$, where $\mathcal{M}^{'}_l\in\mathbb{R}^{(D^{in}+1)\ast D^{out}}$. In detail, we predict a vector with shape $(D^{in}+1)*D^{out}$ which can be reshaped to $\mathcal{M}_l$. However, it is easy to find that the number of parameters in the generator, i.e., {\color{red}$D_l\ast ((D^{in}+1)\ast D^{out})$}, is too large. Such large-scale parameters will slow down the training speed of the network and make it easier to be overfitting. Inspired by matrix factorization, we consider decomposing the $\mathcal{M}_l$ into two factors $\mathbf{U}\in \mathbb{R}^{(D^{in}+1)\times K}$ and $\mathbf{S}\in \mathbb{R}^{K\times D^{out}}$, where $\mathbf{U}$ is a matrix generate from $\mathbf{p}_l^c$, $\mathbf{S}$ is a static learnable matrix, $K$ is a hyper-parameter denoting the factor dimension. The factor generator $\{\mathbf{W}_l,\mathbf{b}_l\}=\Psi^*(\mathbf{p}_l^c)$ can be formulated as follow: \begin{equation} \begin{aligned} & \mathbf{U}=\mathrm{Reshape}({\mathbf{W}_{g}}^\intercal \mathbf{p}_l^c+\mathbf{b}_{g}),\\ & \mathcal{M}_l=\mathbf{U}\mathbf{S},\\ & \{\mathbf{W}_l,\mathbf{b}_l\}= \mathrm{Split}(\mathcal{M}_l),\\ \end{aligned} \end{equation} where $\mathbf{W}_{g}\in \mathbb{R}^{D_l\times (D^{in}+1)\ast K}$ and $ \mathbf{b}_{g}\in \mathbb{R}^{(D^{in}+1)\ast K}$ are trainable parameters of the factor generator. The parameter matrix $\mathcal{M}_l$ of the dynamic linear layer can be reconstructed by multiply $\mathbf{U}$ and $\mathbf{S}$. The $\mathbf{W}_l$ and $\mathbf{b}_l$ can be split from the matrix $\mathcal{M}_l$ along the first dimension. Finally, we reformulate the dynamic linear layer as follows: \begin{equation} \begin{aligned} \mathbf{z}_{out}&=\mathrm{DyLinear}_{\mathcal{M}_l}(\mathbf{z}_{in})=\mathrm{DyLinear}_{\Psi^*(\mathbf{p}_l^c)}(\mathbf{z}_{in}). \end{aligned} \end{equation} Unless otherwise specified, we use $\mathrm{DyLinear}(\mathbf{z}_{in})$ to represent a dynamic linear layer with $\mathbf{p}_l^c$ for simplify. And the different dynamic linear layers do not share parameters. When the input is a multidimensional tensor, the dynamic linear layer transforms the input at the last dimension. \paragraph{Channel and Spatial Attention} As explained in the introduction, the pre-trained visual backbone is sensitive to the objects defined in the pre-training task. However, most of these objects are irrelevant to the query text in visual grounding. Besides, the features useful for localization highly depend on the semantics contained in the query sentence (e.g. entities, descriptions of attributes and relationships). In other words, the importance of each channel or each region of the feature map should change dynamically according to the query sentence. Inspired by Convolutional Block Attention Module~\cite{woo2018cbam}, we consider inferring channel and spatial attentions, i.e., $\mathbf{A}^{cl}$ and $\mathbf{A}^{sl}$, along the separate dimensions of the feature map to obtain adaptively refined features for a better cross-modal alignment. Specifically, for a given visual feature map $\mathbf{F}\in \mathbb{R}^{H\times W\times D_v}$, we first aggregate its spatial information by average pooling and maximum pooling and produce $\mathbf{F}^c_{max}\in \mathbb{R}^{1\times 1\times D_v},\mathbf{F}^c_{mean}\in \mathbb{R}^{1\times 1\times D_v}$. Then, we build a dynamic multilayer perception consists of two dynamic linear layers. We use a ReLU activation after the first layer. The output dimension is the same as the input dimension. To reduce the number of parameter, we set the dimension of hidden states as $D_v/r$, {\color{red}where $r=16$ is the reduction ratio.} By feeding the $\mathbf{F}^c_{max}$ and $\mathbf{F}^c_{mean}$ to the dynamic multilayer perception, we merge the two output features using summation. {\color{red}The channel attention map $\mathbf{A}^{cl}$} can be captured as follow: {\color{red} \begin{equation} \begin{aligned} \mathbf{F}^{cl}_{mean}&=\mathrm{DyLinear}_{1}(\mathrm{ReLU}(\mathrm{DyLinear}_{2}(\mathbf{F}^c_{mean}))\\ \mathbf{F}^{cl}_{max}&=\mathrm{DyLinear}_{1}(\mathrm{ReLU}(\mathrm{DyLinear}_{2}(\mathbf{F}^c_{max}))\\ \mathbf{A}^{cl}&=\mathrm{Sigmoid}(\mathbf{F}^{cl}_{mean}+\mathbf{F}^{cl}_{max}). \end{aligned} \end{equation} } We perform element-wise multiplication between $\mathbf{F}$ and $\mathbf{A}^{cl}$ to form the channel-wise refined visual feature, where the $\mathbf{A}^{cl}$ is broadcast along the spatial dimension: \begin{equation} \begin{aligned} \mathbf{F}^{'}&=\mathbf{A}^{cl}\otimes \mathbf{F}. \end{aligned} \end{equation} To generate a spatial attention map, instead of pooling the channel dimension, we leverage another dynamic linear layer to reduce the channel dimension to learn areas of interest to the query and apply a Sigmoid function to generate the attention map. In short, the computing process is formulated as follows: \begin{equation} \begin{aligned} \mathbf{A}^{sl}&=\mathrm{Sigmoid}(\mathrm{DyLinear}_{3}(\mathbf{F}^{'}))\\ \mathbf{F}^{''}&=\mathbf{A}^{sl}\otimes \mathbf{F}^{'} \end{aligned} \end{equation} where $\mathbf{A}^{sl}\in \mathbb{R}^{H\times W\times 1}$ is the spatial attention map and $\mathbf{F}^{''}$ is the spatially refined visual feature and also the output of our Query-aware Dynamic Attention. \subsubsection{Query-refined Feature Extraction} {\color{red}To extract query-aware feature maps, we extend the Swin-Transformer\footnote{https://github.com/SwinTransformer/Swin-Transformer-Object-Detection} to a modulated visual feature extractor.} As shown in \Cref{fig:model} (b), {\color{red}For a given image $I \in \mathbb{R}^{H\times W\times 3}$, a plain Swin-Transformer first embeds $I$ to $\mathbf{F}_0 \in \mathbb{R}^{\frac{H}{4}\times \frac{W}{4}\times 48}$ by a patch partition operation. Then $\mathbf{F}_0$ is fed into four cascaded stages. The $k$-th stage receives the visual feature map $\mathbf{F}_{k-1}$ and generates a transformed feature map $\mathbf{F}_{k}$. In this work, we take the [CLS] representation of the input query sentence from BERT~\cite{devlin2018bert} as the contextual query representation $\mathbf{p}_l^c$. We append a query-aware dynamic attention module at the end of each stage. It take the transformed feature $\mathbf{F}_{k}$ from Swin-Transformer blocks and produces a query-aware feature $\mathbf{F}_k^{*}$ to the next stage. Thus in the modulated Swin-Transformer, the last three stage receive the refined feature map $\mathbf{F}_{k-1}^{*}$ instead. The output of the query-refined feature extraction is a hierarchical feature list $[\mathbf{F}_{1}^{*},\mathbf{F}_{2}^{*},\mathbf{F}_{3}^{*},\mathbf{F}_{4}^{*}]$.} \subsubsection{Query-aware Multiscale Fusion.}\label{sec:multiscale} Multiscale features are benefit to detect objects at different scales~\cite{DBLP:conf/eccv/CaiFFV16}. However, becuase visual grounding requires fine-grained interaction after visual backbone (\eg Cross Attention), high-resolution features will dramatically increase the computation. Therefore, previous works always use the low-resolution features or fuse the multiscale features in a query-agnostic manner, which will obviously lose scale information or incorporate noise. Thanks to the hierarchical structure of the modulated Swin-Transformer, we can obtain multiscale features. We fuse the features obtained from different stages with the help of Query-aware Dynamic Attention mechanism and pooling operation. We flatten and concatenate the low-resolution features as the output token sequence of the backbone. Specifically, except the first stage, each stage reduces the resolution of feature map by a patch merging operator. In other words, the resolutions of the output feature maps at four stages are $\frac{H}{4}\times\frac{W}{4},\,\frac{H}{8}\times\frac{W}{8},\,\frac{H}{16}\times\frac{W}{16}$ and $\frac{H}{32}\times\frac{W}{32}$, respectively. Besides, the patch merging operator fuses the patch feature into the channel which doubles the channel dimension. Thus the channel dimensions of the output at the four stages are $C,\,2C,\,4C$ and $8C$, respectively. Next, we will introduce how to efficiently fuse these multiscale features with the guidance of the query text. As shown in \Cref{fig:model} (b), we propose to fuse the output features at different stages with the help of QD-ATT. Specifically, we first use four $1\times 1$ convolutional layers to unify the channel dimensions to $D$. To filter out noisy signals in the feature maps, we build QD-ATT\ modules for the feature maps $\{\mathbf{F}^{*}_k |\,k=1,2,3 \}$ of the first three stages. From {\color{red}$\mathbf{F}^{*}_k$}, the QD-ATT\ module produces a weighted feature map with the same size as the {\color{red}input}. We apply a $2\times 2$ mean pooling with stride=2 to reduce the resolution to be the same as next feature map {\color{red}$\mathbf{F}^{*}_{k+1}$} and compute the average of them to obtain $\mathbf{\bar{F}}^{*}_{k+1}$. Finally, the last feature map $\mathbf{\bar{F}}^{*}_{4}$ contains features of interest to the query from all scales. To detect very large objects, we also apply a $2\times 2$ max pooling to obtain a $\frac{H}{64}\times\frac{W}{64}$ feature map $\mathbf{\bar{F}}^{*}_{5}$. We flatten and concatenate the $\mathbf{\bar{F}}^{*}_{4}$ and $\mathbf{\bar{F}}^{*}_{5}$ as the output token sequence $\mathbf{V}$. \subsection{Datasets and Evaluation We evaluate our method on phrase grounding dataset Flickr30K Entities\cite{plummer2015flickr30k} and referring expression grounding datasets RefCOCO\cite{yu2016modeling}, RefCOCO+\cite{yu2016modeling}, RefCOCOg\cite{mao2016generation} and ReferItGame\cite{kazemzadeh2014referitgame}. The details and statistics are summarized in Appendix. In phrase grounding the queries are phrases and in referring expression grounding, they are referring expressions corresponding to the referred objects. We follow the same metric used in \cite{deng2021transvg}. Specifically, a prediction is right if the IoU between the grounding-truth box and the predicted bounding box is larger than 0.5. \subsection{Implementation Details} The QRNet is built based on Swin-Transformer, i.e., Swin-S pre-trained with Mask-RCNN on MSCOCO~\cite{lin2014microsoft}\footnote{We excluded images in the validation and test set of the RefCOCO series from MSCOCO training set and retrained Swin-Transformer for fair comparison.}. We use $\mathrm{BERT}_{\mathrm{base}}$(uncased) for linguistic feature extraction. We set the intermediate dimension $D=256$ and the factor dimension $K=30$. We follow the TransVG~\cite{deng2021transvg} to process the input images and sentences. We also follow the training setting used in TransVG, which uses a AdamW optimizer with weight decay $10^{-4}$, sets the batch size to 64 and the dropout ratio to 0.1 for FFN in Transformer. The learning rate is set to $10^{-5}$ for pre-trained parameters and $10^{-4}$ for other parameters. The parameters without pre-training are randomly initialized with Xavier. We train our model for 160 epochs. The learning rate is multiplied by a factor of 0.1 at epoch 40 for Flickr30K Entities and at epoch 60 for other datasets. We also follow the commonly used data augmentation strategies in ~\cite{liao2020real,yang2020improving,yang2019fast}. \subsection{Quantitative Results} We show the comparison results on ReferItGame and Flickr30k Entities in \Cref{tab:sub_main}. The ReferItGame collects queries by a cooperative game, requiring one player to write a referring expression for a specified object. The other one needs to click on the correct object. Queries in Flickr30k Entities are phrases in the caption. We observe that the proposed MMSwin\ \ outperforms previous works. We replace the visual branch of TransVG with Swin-Transformer and denote it by TransVG(Swin) to explore the impact of backbone. The performance is similar to the original TransVG, indicating that the accuracy gains are not from Swin-Transformer. \begin{table}[t] \small \centering \begin{tabular}{@{}cccc@{}} \toprule \multicolumn{1}{c|}{\multirow{2}{*}{Module}} & \multicolumn{1}{c|}{\multirow{2}{*}{Backbone}} & \multicolumn{1}{c|}{ReferItGame} & Flickr30K \\ \multicolumn{1}{c|}{} & \multicolumn{1}{c|}{} & \multicolumn{1}{c|}{test} & test \\ \midrule \multicolumn{4}{l}{\textbf{Two-stage}} \\ \midrule \multicolumn{1}{c|}{VC~\cite{zhang2018grounding}} & \multicolumn{1}{c|}{VGG16} & \multicolumn{1}{c|}{31.13} & - \\ \multicolumn{1}{c|}{MAttNet~\cite{yu2018mattnet}} & \multicolumn{1}{c|}{ResNet-101} & \multicolumn{1}{c|}{29.04} & - \\ \multicolumn{1}{c|}{Similarity net~\cite{wang2018learning}} & \multicolumn{1}{c|}{ResNet-101} & \multicolumn{1}{c|}{34.54} & 50.89 \\ \multicolumn{1}{c|}{LCMCG~\cite{liu2020learning}} & \multicolumn{1}{c|}{ResNet-101} & \multicolumn{1}{c|}{-} & 76.74 \\ \multicolumn{1}{c|}{DIGN~\cite{mu2021disentangled}} & \multicolumn{1}{c|}{VGG-16} & \multicolumn{1}{c|}{{\ul 65.15}} & {\ul 78.73} \\ \midrule \multicolumn{4}{l}{\textbf{One-stage}} \\ \midrule \multicolumn{1}{c|}{FAOA~\cite{yang2019fast}} & \multicolumn{1}{c|}{DarkNet-53} & \multicolumn{1}{c|}{60.67} & 68.71 \\ \multicolumn{1}{c|}{RCCF~\cite{liao2020real}} & \multicolumn{1}{c|}{DLA-34} & \multicolumn{1}{c|}{63.79} & - \\ \multicolumn{1}{c|}{ReSC-Large~\cite{yang2020improving}} & \multicolumn{1}{c|}{DarkNet-53} & \multicolumn{1}{c|}{64.60} & 69.28 \\ \multicolumn{1}{c|}{SAFF~\cite{ye2021one}} & \multicolumn{1}{c|}{DarkNet-53} & \multicolumn{1}{c|}{66.01} & 70.71 \\ \multicolumn{1}{c|}{TransVG~\cite{deng2021transvg}} & \multicolumn{1}{c|}{ResNet-101} & \multicolumn{1}{c|}{70.73} & {\ul 79.10} \\ \multicolumn{1}{c|}{TransVG\ (Swin)} & \multicolumn{1}{c|}{Swin-S} & \multicolumn{1}{c|}{{\ul 70.86}} & 78.18 \\ \midrule \multicolumn{1}{c|}{MMSwin\ \ (ours)} & \multicolumn{1}{c|}{Swin-S} & \multicolumn{1}{c|}{\textbf{74.61}} & \textbf{81.95} \\ \bottomrule \end{tabular} \caption{The performance comparisons (Acc@0.5) on ReferItGame and Flickr30K Entities.} \label{tab:sub_main} \end{table} \begin{table*}[ht] \centering \begin{tabular}{@{}ccccccccccc@{}} \toprule \multicolumn{1}{c|}{\multirow{2}{*}{Models}} & \multicolumn{1}{c|}{\multirow{2}{*}{Backbone}} & \multicolumn{3}{c|}{RefCOCO} & \multicolumn{3}{c|}{RefCOCO+} & \multicolumn{3}{c}{RefCOCOg} \\ \multicolumn{1}{c|}{} & \multicolumn{1}{c|}{} & val & testA & \multicolumn{1}{c|}{testB} & val & testA & \multicolumn{1}{c|}{testB} & val-g & val-u & test-u \\ \midrule \multicolumn{11}{l}{\textbf{Two-stage}} \\ \midrule \multicolumn{1}{c|}{VC~\cite{zhang2018grounding}} & \multicolumn{1}{c|}{VGG16} & - & 73.33 & \multicolumn{1}{c|}{67.44} & - & 58.40 & \multicolumn{1}{c|}{53.18} & 62.30 & - & - \\ \multicolumn{1}{c|}{MAttNet~\cite{yu2018mattnet}} & \multicolumn{1}{c|}{ResNet-101} & 76.65 & 81.14 & \multicolumn{1}{c|}{69.99} & 65.33 & 71.62 & \multicolumn{1}{c|}{56.02} & - & 66.58 & 67.27 \\ \multicolumn{1}{c|}{Ref-NMS~\cite{chen2021ref}} & \multicolumn{1}{c|}{ResNet-101} & {\ul 78.82} & 82.71 & \multicolumn{1}{c|}{{\ul 73.94}} & 66.95 & 71.29 & \multicolumn{1}{c|}{{\ul 58.40}} & - & {\ul 68.89} & {\ul 68.67} \\ \multicolumn{1}{c|}{LGRANs~\cite{wang2019neighbourhood}} & \multicolumn{1}{c|}{VGG16} & - & 76.60 & \multicolumn{1}{c|}{66.40} & - & 64.00 & \multicolumn{1}{c|}{53.40} & 61.78 & - & - \\ \multicolumn{1}{c|}{RvG-Tree~\cite{hong2019learning}} & \multicolumn{1}{c|}{ResNet-101} & 75.06 & 78.61 & \multicolumn{1}{c|}{69.85} & 63.51 & 67.45 & \multicolumn{1}{c|}{56.66} & - & 66.95 & 66.51 \\ \multicolumn{1}{c|}{CM-Att-Erase~\cite{liu2019improving}} & \multicolumn{1}{c|}{ResNet-101} & 78.35 & {\ul 83.14} & \multicolumn{1}{c|}{71.32} & {\ul 68.09} & {\ul 73.65} & \multicolumn{1}{c|}{58.03} & {\ul 68.67} & - & - \\ \multicolumn{1}{c|}{NMTree~\cite{liu2019learning}} & \multicolumn{1}{c|}{ResNet-101} & 76.41 & 81.21 & \multicolumn{1}{c|}{70.09} & 66.46 & 72.02 & \multicolumn{1}{c|}{57.52} & 64.62 & 65.87 & 66.44 \\ \midrule \multicolumn{11}{l}{\textbf{One-stage}} \\ \midrule \multicolumn{1}{c|}{FAOA~\cite{yang2019fast}} & \multicolumn{1}{c|}{DarkNet-53} & 72.54 & 74.35 & \multicolumn{1}{c|}{68.50} & 56.81 & 60.23 & \multicolumn{1}{c|}{49.60} & 56.12 & 61.33 & 60.36 \\ \multicolumn{1}{c|}{RCCF~\cite{liao2020real}} & \multicolumn{1}{c|}{DLA-34} & - & 81.06 & \multicolumn{1}{c|}{71.85} & - & 70.35 & \multicolumn{1}{c|}{56.32} & - & - & 65.73 \\ \multicolumn{1}{c|}{ReSC-Large~\cite{yang2020improving}} & \multicolumn{1}{c|}{DarkNet-53} & 77.63 & 80.45 & \multicolumn{1}{c|}{72.30} & 63.59 & 68.36 & \multicolumn{1}{c|}{56.81} & 63.12 & 67.30 & 67.20 \\ \multicolumn{1}{c|}{SAFF~\cite{ye2021one}} & \multicolumn{1}{c|}{DarkNet-53} & 79.26 & 81.09 & \multicolumn{1}{c|}{76.55} & 64.43 & 68.46 & \multicolumn{1}{c|}{58.43} & - & 68.94 & 68.91 \\ \multicolumn{1}{c|}{HFRN~\cite{qiu2020language}} & \multicolumn{1}{c|}{ResNet-101} & 79.76 & {83.12} & \multicolumn{1}{c|}{75.51} & 66.80 & 72.53 & \multicolumn{1}{c|}{59.09} & - & {\ul 69.71} & 69.08 \\ \multicolumn{1}{c|}{ISRL~\cite{sun2021iterative}} & \multicolumn{1}{c|}{ResNet-101} & - & 74.27 & \multicolumn{1}{c|}{68.10} & - & 71.05 & \multicolumn{1}{c|}{58.25} & - & - & {\ul 70.05} \\ \multicolumn{1}{c|}{LBYL-Net~\cite{huang2021look}} & \multicolumn{1}{c|}{DarkNet-53} & 79.67 & 82.91 & \multicolumn{1}{c|}{74.15} & {\ul 68.64} & {\ul 73.38} & \multicolumn{1}{c|}{{\ul 59.49}} & 62.70 & - & - \\ \multicolumn{1}{c|}{TransVG~\cite{deng2021transvg}} & \multicolumn{1}{c|}{ResNet-101} & {81.02} & 82.72 & \multicolumn{1}{c|}{{78.35}} & 64.82 & 70.70 & \multicolumn{1}{c|}{56.94} & {67.02} & 68.67 & 67.73 \\ \multicolumn{1}{c|}{TransVG\ (Swin)} & \multicolumn{1}{c|}{Swin-S} & {\ul 82.33} & {\ul 84.01} & \multicolumn{1}{c|}{{\ul 79.83}} & 64.94 & 70.19 & \multicolumn{1}{c|}{56.47} & {\ul 67.81} & 69.34 & 68.99 \\ \midrule \multicolumn{1}{c|}{MMSwin\ \ (ours)} & \multicolumn{1}{c|}{Swin-S} & \textbf{84.01} & \textbf{85.85} & \multicolumn{1}{c|}{\textbf{82.34}} & \textbf{72.94} & \textbf{76.17} & \multicolumn{1}{c|}{\textbf{63.81}} & \textbf{71.89} & \textbf{73.03} & \textbf{72.52} \\ \bottomrule \end{tabular} \caption{The performance comparisons (Acc@0.5) on ReferCOCO, ReferCOCO+, and ReferCOCOg. The results of previous best two-stage and one-stage methods are highlighted with underlines. We highlight our results in bold. The results demonstrate that our method outperforms all state-of-the-art one-stage and two-stage methods.} \label{tab:main} \end{table*} We also present the accuracy comparison with state-of-the-art methods on ReferCOCO, ReferCOCO+, and ReferCOCOg in \Cref{tab:main}. In ReferCOCO and ReferCOCO+ datasets, referred objects are people in ``testA" and could be common objects in ``testB". The expressions in ReferCOCOg are much longer than the ones in other datasets. Note that TransVG uses a ResNet-101 and a DETR encoder split from a pre-trained DETR framework. Its backbone is more powerful than a single ResNet-101. We observe that our MMSwin\ \ greatly outperforms all two-stage and one-stage state-of-the-art methods. On RefCOCO and RefCOCO+ datasets, our method gains 1.84\%$\sim$2.52\% absolute improvement in ``testA" and 2.51\%$\sim$4.32\% in ``testB". When the referred objects are arbitrary, the inconsistent issue will be more serious, and our modulated backbone can better filter irrelevant objects and correct the representation with textual guidance. In the RefCOCOg test split, we notice that ISRL~\cite{sun2021iterative} performs better than TransVG~\cite{deng2021transvg}. It models the visual grounding as a Markov decision process that handles long expressions iterative by filtering out irrelevant areas. However, the limited action space makes it easy to converge to a local optimum. Our model does not modify the Visual-Linguistic Transformer in the TransVG and only provides query-consistent visual features. The performance is greatly improved, which demonstrates that our query-aware refinement is more effective to model the representation for visual grounding. \subsection{Ablation Study} We conduct ablation studies on ReferItGame and Flickr30k to reveal the effectiveness of the proposed MMSwin\ . We first study the effectiveness of QD-ATT\ in query-refined feature extraction and query-aware multiscale fusion. As shown in \Cref{tab:abl_module}, we use a checkmark to denote enabling QD-ATT\ in the corresponding module, and a cross mark to denote disabling QD-ATT\ and passing the feature without modification. When disabling QD-ATT\ in multiscale fusion, the performance is dropped by 2.52\% in ReferItGame-\textit{test} and 0.79\% in Flickr30k-\textit{test}, respectively. When disabling QD-ATT\ in query-refined feature extraction, the performance is dropped by 3.22\% and 1.51\%. When completely disabling QD-ATT, the performance is dropped by 3.75\% and 3.77\%. We find that QD-ATT\ is more important in query-refined feature extraction than in multiscale fusion. We also notice that, when compared with completely disabling QD-ATT, only enabling QD-ATT\ in multiscale fusion gains little improvement because the features from the transformer are still noise and query-inconsistent. We further study the effectiveness of spatial attention and channel attention in the QD-ATT. Spatial attention can filter out irrelevant areas. And channel attention can redistribute the importance of the features to fit different query sentences. The results shown in the \Cref{tab:abl_attention} demonstrate that spatial and channel attention are both effective. \begin{table}[tb] \small \centering \setlength{\tabcolsep}{4pt} \begin{tabular}{c|cc|cc|cc} \toprule \multirow{2}{*}{Models} & \multirow{2}{*}{\tabincell{c}{{\scriptsize Feature} \\ {\scriptsize Extraction}}} & \multirow{2}{*}{\tabincell{c}{{\scriptsize Multiscale} \\ {\scriptsize Fusion}}} & \multicolumn{2}{c}{ReferItGame} & \multicolumn{2}{c}{Flickr30k} \\ & & & val & test & val & test \\ \midrule MMSwin\ & \CheckmarkBold & \CheckmarkBold & \bf 76.84 & \bf 74.61 & \bf 80.83 & \bf 81.95 \\ \midrule (a) & \CheckmarkBold & \XSolidBrush & 74.31 & 72.09 & 80.09 & 81.16 \\ (b) & \XSolidBrush & \CheckmarkBold & 73.63 & 71.39 & 79.35 & 80.44\\ (c) & \XSolidBrush & \XSolidBrush & 73.25 & 70.86 & 77.17 & 78.18\\ \bottomrule \end{tabular} \caption{Ablation studies of QD-ATT\ in two phases of MMSwin\ .} \label{tab:abl_module} \vspace{1.2em} \small \setlength{\tabcolsep}{4pt} \begin{tabular}{c|cc|cc|cc} \toprule \multirow{2}{*}{Models} & \multirow{2}{*}{\tabincell{c}{{\scriptsize Channel} \\ {\scriptsize Attention}}} & \multirow{2}{*}{\tabincell{c}{{\scriptsize Spatial}\\{\scriptsize Attention}}} & \multicolumn{2}{c}{ReferItGame} & \multicolumn{2}{c}{Flickr30k} \\ & & & val & test & val & test \\ \midrule MMSwin\ & \CheckmarkBold & \CheckmarkBold & \bf 76.84 & \bf 74.61 & \bf 80.83 & \bf 81.95 \\ \midrule (d) & \CheckmarkBold & \XSolidBrush & 74.35 & 72.02 & 80.22 & 81.35 \\ (e) & \XSolidBrush & \CheckmarkBold & 74.41 & 71.80 & 80.67 & 81.55\\ \bottomrule \end{tabular} \caption{Ablation studies of different attentions in QD-ATT.} \label{tab:abl_attention} \end{table} \subsection{Qualitative Results} \begin{figure}[tb] \centering \includegraphics[width=1\linewidth]{figs/sup_vis.pdf} \caption{Visualization of activation maps from the backbone of our MMSwin\ \ and other popular models. Red: the predicted box. White: the ground-truth box.} \label{fig:vis} \vspace{-1em} \end{figure} We show the qualitative comparison between our MMSwin\ \ and three popular methods in \Cref{fig:vis}. The feature maps are extract from the backbone of each model. We can see that previous methods are sensitive to many query-unrelated areas, which may lead to wrong predictions, e.g., the results of TransVG and ReSC for the queries of ``glass upper righ" and ``light blue tall board", and the result of Swin-S for the query of ``upper left cake". In contrast, our QRNet generates query-consistent features and makes more accurate predictions. More results can be found in the supplementary. \subsection{Datasets and Evaluation We evaluate our method on phrase grounding dataset Flickr30K Entities\cite{plummer2015flickr30k} and referring expression grounding datasets RefCOCO\cite{yu2016modeling}, RefCOCO+\cite{yu2016modeling}, RefCOCOg\cite{mao2016generation} and ReferitGame\cite{kazemzadeh2014referitgame}. The details and statistics are summarized in Appendix. In phrase grounding the queries are phrases split from the captions and in referring expression grounding, they are referring expressions corresponding to the referred objects. We follow the same metric in \cite{deng2021transvg}. Specifically, a prediction is right if the IoU $>$ 0.5 between grounding-truth box and predicted bounding box. \subsection{Implementation Details} The Swin-Transformer we extend is the Swin-S pre-trained with Mask-RCNN on MSCOCO~\cite{lin2014microsoft}\footnote{We excluded images in the validation and test split of the refcoco series from mscoco training set and retrained Swin-Transformer for fair comparison.}. We use $\mathrm{BERT}_{\mathrm{base}}$(uncased)\footnote{https://github.com/huggingface/pytorch-pretrained-BERT} for linguistic feature extraction. We set the intermediate dimension $D=256$ and the factor dimension $K=30$. We follow the TransVG~\cite{deng2021transvg} to process the input images and sentences. We also follow the training setting used in TransVG, which uses a AdamW optimizer with weight decay $10^{-4}$, sets the batch size to 64 and the dropout ratio to 0.1 for FFN in transformer. The learning rate of pre-trained parameters is set to $10^{-5}$ and the other is set to $10^{-4}$. The parameters without pre-training are randomly initialized with Xavier. We training our model for 160 epoches. The learning rate is multiplied by a factor of 0.1 at the epoch 60 for most dataset and 40 for Flickr30K Entities. We also follow the common used data augmentation strategies in ~\cite{liao2020real,yang2020improving,yang2019fast}. \subsection{Quantitative Results} We show the comparison results on ReferItGame and Flickr30k Entities in \Cref{tab:sub_main}. The ReferItGame collects queries by a cooperative game, requiring one player to write a referring expression for a specified object. The other one needs to click on the correct object. Queries in Flickr30k Entities are phrases in the caption. MMSwin\ \ also outperforms previous works. We replace the visual branch of TransVG with Swin-Transformer and denote it as TransVG(Swin) to explore the impact of replacing the backbone. The performance is similar to the origin TransVG, indicating that the accuracy gains are not from Swin-Transformer. \begin{table}[t] \small \centering \begin{tabular}{@{}cccc@{}} \toprule \multicolumn{1}{c|}{\multirow{2}{*}{Module}} & \multicolumn{1}{c|}{\multirow{2}{*}{Backbone}} & \multicolumn{1}{c|}{ReferItGame} & Flickr30K \\ \multicolumn{1}{c|}{} & \multicolumn{1}{c|}{} & \multicolumn{1}{c|}{test} & test \\ \midrule \multicolumn{4}{l}{\textbf{Two-stage}} \\ \midrule \multicolumn{1}{c|}{CMN~\cite{hu2017modeling}} & \multicolumn{1}{c|}{VGG16} & \multicolumn{1}{c|}{28.33} & - \\ \multicolumn{1}{c|}{VC~\cite{zhang2018grounding}} & \multicolumn{1}{c|}{VGG16} & \multicolumn{1}{c|}{31.13} & - \\ \multicolumn{1}{c|}{MAttNet~\cite{yu2018mattnet}} & \multicolumn{1}{c|}{ResNet-101} & \multicolumn{1}{c|}{29.04} & - \\ \multicolumn{1}{c|}{Similarity net~\cite{wang2018learning}} & \multicolumn{1}{c|}{ResNet-101} & \multicolumn{1}{c|}{34.54} & 50.89 \\ \multicolumn{1}{c|}{LCMCG~\cite{liu2020learning}} & \multicolumn{1}{c|}{ResNet-101} & \multicolumn{1}{c|}{-} & 76.74 \\ \multicolumn{1}{c|}{DIGN~\cite{mu2021disentangled}} & \multicolumn{1}{c|}{VGG-16} & \multicolumn{1}{c|}{{\ul 65.15}} & {\ul 78.73} \\ \midrule \multicolumn{4}{l}{\textbf{One-stage}} \\ \midrule \multicolumn{1}{c|}{SSG~\cite{chen2018real}} & \multicolumn{1}{c|}{DarkNet-53} & \multicolumn{1}{c|}{54.24} & - \\ \multicolumn{1}{c|}{FAOA~\cite{yang2019fast}} & \multicolumn{1}{c|}{DarkNet-53} & \multicolumn{1}{c|}{60.67} & 68.71 \\ \multicolumn{1}{c|}{RCCF~\cite{liao2020real}} & \multicolumn{1}{c|}{DLA-34} & \multicolumn{1}{c|}{63.79} & - \\ \multicolumn{1}{c|}{ReSC-Large~\cite{yang2020improving}} & \multicolumn{1}{c|}{DarkNet-53} & \multicolumn{1}{c|}{64.60} & 69.28 \\ \multicolumn{1}{c|}{SAFF~\cite{ye2021one}} & \multicolumn{1}{c|}{DarkNet-53} & \multicolumn{1}{c|}{66.01} & 70.71 \\ \multicolumn{1}{c|}{TransVG~\cite{deng2021transvg}} & \multicolumn{1}{c|}{ResNet-101} & \multicolumn{1}{c|}{70.73} & {\ul 79.10} \\ \multicolumn{1}{c|}{TransVG\,(Swin)} & \multicolumn{1}{c|}{Swin-S} & \multicolumn{1}{c|}{{\ul 70.86}} & 78.18 \\ \midrule \multicolumn{1}{c|}{MMSwin\ \ (ours)} & \multicolumn{1}{c|}{Swin-S} & \multicolumn{1}{c|}{\textbf{74.61}} & \textbf{81.95} \\ \bottomrule \end{tabular} \caption{The performance comparisons (Acc@0.5) on ReferItGame and Flickr30K Entities.} \label{tab:sub_main} \end{table} \begin{table*}[ht] \centering \begin{tabular}{@{}ccccccccccc@{}} \toprule \multicolumn{1}{c|}{\multirow{2}{*}{Models}} & \multicolumn{1}{c|}{\multirow{2}{*}{Backbone}} & \multicolumn{3}{c|}{RefCOCO} & \multicolumn{3}{c|}{RefCOCO+} & \multicolumn{3}{c}{RefCOCOg} \\ \multicolumn{1}{c|}{} & \multicolumn{1}{c|}{} & val & testA & \multicolumn{1}{c|}{testB} & val & testA & \multicolumn{1}{c|}{testB} & val-g & val-u & test-u \\ \midrule \multicolumn{11}{l}{\textbf{Two-stage}} \\ \midrule \multicolumn{1}{c|}{CMN~\cite{hu2017modeling}} & \multicolumn{1}{c|}{VGG16} & - & 71.03 & \multicolumn{1}{c|}{65.77} & - & 54.32 & \multicolumn{1}{c|}{47.76} & 57.47 & - & - \\ \multicolumn{1}{c|}{VC~\cite{zhang2018grounding}} & \multicolumn{1}{c|}{VGG16} & - & 73.33 & \multicolumn{1}{c|}{67.44} & - & 58.40 & \multicolumn{1}{c|}{53.18} & 62.30 & - & - \\ \multicolumn{1}{c|}{MAttNet~\cite{yu2018mattnet}} & \multicolumn{1}{c|}{ResNet-101} & 76.65 & 81.14 & \multicolumn{1}{c|}{69.99} & 65.33 & 71.62 & \multicolumn{1}{c|}{56.02} & - & 66.58 & 67.27 \\ \multicolumn{1}{c|}{Ref-NMS~\cite{chen2021ref}} & \multicolumn{1}{c|}{ResNet-101} & {\ul 78.82} & 82.71 & \multicolumn{1}{c|}{{\ul 73.94}} & 66.95 & 71.29 & \multicolumn{1}{c|}{{\ul 58.40}} & - & {\ul 68.89} & {\ul 68.67} \\ \multicolumn{1}{c|}{LGRANs~\cite{wang2019neighbourhood}} & \multicolumn{1}{c|}{VGG16} & - & 76.60 & \multicolumn{1}{c|}{66.40} & - & 64.00 & \multicolumn{1}{c|}{53.40} & 61.78 & - & - \\ \multicolumn{1}{c|}{RvG-Tree~\cite{hong2019learning}} & \multicolumn{1}{c|}{ResNet-101} & 75.06 & 78.61 & \multicolumn{1}{c|}{69.85} & 63.51 & 67.45 & \multicolumn{1}{c|}{56.66} & - & 66.95 & 66.51 \\ \multicolumn{1}{c|}{CM-Att-Erase~\cite{liu2019improving}} & \multicolumn{1}{c|}{ResNet-101} & 78.35 & {\ul 83.14} & \multicolumn{1}{c|}{71.32} & {\ul 68.09} & {\ul 73.65} & \multicolumn{1}{c|}{58.03} & {\ul 68.67} & - & - \\ \multicolumn{1}{c|}{NMTree~\cite{liu2019learning}} & \multicolumn{1}{c|}{ResNet-101} & 76.41 & 81.21 & \multicolumn{1}{c|}{70.09} & 66.46 & 72.02 & \multicolumn{1}{c|}{57.52} & 64.62 & 65.87 & 66.44 \\ \midrule \multicolumn{11}{l}{\textbf{One-stage}} \\ \midrule \multicolumn{1}{c|}{SSG~\cite{chen2018real}} & \multicolumn{1}{c|}{DarkNet-53} & - & 76.51 & \multicolumn{1}{c|}{67.50} & - & 62.14 & \multicolumn{1}{c|}{49.27} & 47.47 & 58.80 & - \\ \multicolumn{1}{c|}{FAOA~\cite{yang2019fast}} & \multicolumn{1}{c|}{DarkNet-53} & 72.54 & 74.35 & \multicolumn{1}{c|}{68.50} & 56.81 & 60.23 & \multicolumn{1}{c|}{49.60} & 56.12 & 61.33 & 60.36 \\ \multicolumn{1}{c|}{RCCF~\cite{liao2020real}} & \multicolumn{1}{c|}{DLA-34} & - & 81.06 & \multicolumn{1}{c|}{71.85} & - & 70.35 & \multicolumn{1}{c|}{56.32} & - & - & 65.73 \\ \multicolumn{1}{c|}{ReSC-Large~\cite{yang2020improving}} & \multicolumn{1}{c|}{DarkNet-53} & 77.63 & 80.45 & \multicolumn{1}{c|}{72.30} & 63.59 & 68.36 & \multicolumn{1}{c|}{56.81} & 63.12 & 67.30 & 67.20 \\ \multicolumn{1}{c|}{SAFF~\cite{ye2021one}} & \multicolumn{1}{c|}{DarkNet-53} & 79.26 & 81.09 & \multicolumn{1}{c|}{76.55} & 64.43 & 68.46 & \multicolumn{1}{c|}{58.43} & - & 68.94 & 68.91 \\ \multicolumn{1}{c|}{HFRN~\cite{qiu2020language}} & \multicolumn{1}{c|}{ResNet-101} & 79.76 & {\ul 83.12} & \multicolumn{1}{c|}{75.51} & 66.80 & 72.53 & \multicolumn{1}{c|}{59.09} & - & {\ul 69.71} & 69.08 \\ \multicolumn{1}{c|}{ISRL~\cite{sun2021iterative}} & \multicolumn{1}{c|}{ResNet-101} & - & 74.27 & \multicolumn{1}{c|}{68.10} & - & 71.05 & \multicolumn{1}{c|}{58.25} & - & - & {\ul 70.05} \\ \multicolumn{1}{c|}{LBYL-Net~\cite{huang2021look}} & \multicolumn{1}{c|}{DarkNet-53} & 79.67 & 82.91 & \multicolumn{1}{c|}{74.15} & {\ul 68.64} & {\ul 73.38} & \multicolumn{1}{c|}{{\ul 59.49}} & 62.70 & - & - \\ \multicolumn{1}{c|}{TransVG~\cite{deng2021transvg}} & \multicolumn{1}{c|}{ResNet-101} & {\ul 81.02} & 82.72 & \multicolumn{1}{c|}{{\ul 78.35}} & 64.82 & 70.70 & \multicolumn{1}{c|}{56.94} & {\ul 67.02} & 68.67 & 67.73 \\ \midrule \multicolumn{1}{c|}{MMSwin\ \ (ours)} & \multicolumn{1}{c|}{Swin-S} & \textbf{84.01} & \textbf{85.85} & \multicolumn{1}{c|}{\textbf{82.34}} & \textbf{72.94} & \textbf{76.17} & \multicolumn{1}{c|}{\textbf{63.81}} & \textbf{74.05} & \textbf{75.80} & \textbf{75.52} \\ \bottomrule \end{tabular} \caption{The performance comparisons (Acc@0.5) on ReferCOCO, ReferCOCO+,ReferCOCOg. The previous best two-stage and one-stage performances are highlighted with underline, respectively. We highlight our results in bold. The results demonstrate our method outperforms all state-of-the-art one-stage and two-stage methods.} \label{tab:main} \end{table*} We also present the accuracy comparison with state-of-the-art methods on ReferCOCO, ReferCOCO+ and ReferCOCOg in \Cref{tab:main}. In ReferCOCO and ReferCOCO+ datasets, referred objects are people in ``testA" and could be common objects in ``testB". The expressions in ReferCOCOg are much longer than in other datasets. Note that TransVG uses a ResNet-101 and a DETR encoder split from a pre-trained DETR framework. The visual backbone is more powerful than other ResNet-101. Because the MDETR\cite{kamath2021mdetr} uses large-scale image-caption pairs with bounding box annotations for pre-training, the other methods only use the corresponding train split when evaluated on each dataset. For fair, we do not present its performances. We observe that our MMSwin\ \ greatly outperforms all two-stage and one-stage stage-of-the-art methods. In RefCOCO and RefCOCO+ datasets, our method gains 2.37\%$\sim$2.79\% absolute improvement in ``testA" and 3.99\%$\sim$4.32\% in ``testB". When the referred objects are arbitrary, the inconsistent issue will be more obvious, and our modulated backbone can better filter irrelevant objects and correct the representation with textual guidance. In the RefCOCOg test split, we notice that ISRL~\cite{sun2021iterative} performs better than TransVG~\cite{deng2021transvg}. It models the visual grounding to a Markov decision process that handles long expressions iterative by filtering out irrelevant areas. However, the limited action space makes it easy to converge to a local optimum. Our model does not modify the Visual-Linguistic Transformer in the TransVG but only provides query-consistent visual features. The performance is greatly improved which proves that our query-aware refinement is more effective to model the multimodal representation for visual grounding. \subsection{Ablation Study} \begin{table}[tb] \small \setlength{\tabcolsep}{8pt} \centering \begin{tabular}{c|cc|cc} \toprule \multirow{2}{*}{Models} & \multirow{2}{*}{\begin{tabular}[c]{@{}c@{}}Feature \\ Extraction\end{tabular}} & \multirow{2}{*}{\begin{tabular}[c]{@{}c@{}}Multiscale\\ Fusion\end{tabular}} & \multicolumn{2}{l}{ReferItGame} \\ & & & val & test \\ \midrule MMSwin\ & \CheckmarkBold & \CheckmarkBold & \bf 76.84 & \bf 74.61 \\ \midrule (a) & \CheckmarkBold & \XSolidBrush & 74.31 & 72.09 \\ (b) & \XSolidBrush & \CheckmarkBold & 73.63 & 71.39 \\ (c) & \XSolidBrush & \XSolidBrush & 73.25 & 70.86 \\ \bottomrule \end{tabular} \caption{The ablations of the proposed two modules.} \label{tab:abl_module} \vspace{1.5em} \begin{tabular}{c|cc|cc} \toprule \multirow{2}{*}{Models} & \multirow{2}{*}{\tabincell{c}{Channel\\ Attention}} & \multirow{2}{*}{\tabincell{c}{Spatial\\ Attention}} & \multicolumn{2}{c}{ReferItGame} \\ & & & val & test \\ \midrule MMSwin\ & \CheckmarkBold & \CheckmarkBold & \bf 76.84 & \bf 74.61 \\ \midrule (d) & \CheckmarkBold & \XSolidBrush & 74.35 & 72.02 \\ (e) & \XSolidBrush & \CheckmarkBold & 74.41 & 71.80 \\ \bottomrule \end{tabular} \caption{The ablations of the query-driven attention.} \label{tab:abl_attention} \end{table} We conduct several ablation studies on ReferItGame to reveal the effectiveness of our proposed modules. We first study the effectiveness of the two proposed modules. As shown in \Cref{tab:abl_module}, when only adopting QD-ATT\ during feature extraction, the performance is improved by 1.06\% in ``val" and 1.27\% in ``test", respectively. When only adopting QD-ATT\ during multiscale fusion, the performance is improved by 0.38\% and 0.53\%. When enhancing both two processes, the performance is improved by 3.63\% and 3.59\%. We find that when the feature extraction is not modified, the features of each scale are still query-inconsistent. {\color{red}It is hard for the fusion module to learn both feature refinement and query-aware multiscale fusion from scratch without the help of pre-training knowledge.} Thus there is still much noise in the fused multiscale features, which limits its improvement. When the feature extraction is query-aware, the multiscale fusion can significantly improve the model's performance. We further study the effectiveness of spatial attention and channel attention in the QD-ATT. Note that the settings affect both the feature extraction and multiscale fusion. Spatial attention can filter out irrelevant areas. And channel attention can redistribution the importance of the features to fit different query sentences. The results shown in the \Cref{tab:abl_attention} demonstrate that spatial and channel attention are both effective. \begin{figure}[tb] \centering \includegraphics[width=\linewidth]{figs/factor.pdf} \caption{The effect of factor dimension $K$.} \label{fig:factor} \end{figure} We study the hyper-parameter $K$ which denotes the factor dimension. We report the accuracy of model with $K=\{10,30,50,70\}$ in \Cref{fig:factor}. When $K$ is small, the QD-ATT\ can not learn the transformation well. And when $K$ is large, the QD-ATT\ is easy to overfitting and perform worse on validation set. We take the best $K=30$ on validation set as our default setting. \subsection{Qualitative Results} \begin{figure}[tb] \centering \includegraphics[width=\linewidth]{figs/vis_1_cropped.pdf} \caption{Visualization of activation maps from plain Swin-Transformer and the modulated backbone of our MMSwin\ \ . Green: grounding truth; blue: prediction of our model} \label{fig:vis} \end{figure} We show the qualitative examples of our MMSwin\ \ framework on the RefCOCO dataset in \Cref{fig:vis}. The first row shows the activation maps from plain Swin-Transformer. The second row shows the activation maps from our modulated visual backbone. We observe that query-agnostic Swin-Transformer tends to extract features of all salient objects. In comparison, our query-aware backbone can understand entities words, \eg, ``glass'', and appearance descriptions, \eg, ``light blue tall''. It also can perform reasoning through location words, \eg, ``upper left'' and ``nearest''. The produced activation maps are highly relevant to the query sentences. \subsection{Language} All manuscripts must be in English. \subsection{Dual submission} Please refer to the author guidelines on the CVPR\ 2022\ web page for a discussion of the policy on dual submissions. \subsection{Paper length} Papers, excluding the references section, must be no longer than eight pages in length. The references section will not be included in the page count, and there is no limit on the length of the references section. For example, a paper of eight pages with two pages of references would have a total length of 10 pages. {\bf There will be no extra page charges for CVPR\ 2022.} Overlength papers will simply not be reviewed. This includes papers where the margins and formatting are deemed to have been significantly altered from those laid down by this style guide. Note that this \LaTeX\ guide already sets figure captions and references in a smaller font. The reason such papers will not be reviewed is that there is no provision for supervised revisions of manuscripts. The reviewing process cannot determine the suitability of the paper for presentation in eight pages if it is reviewed in eleven. \subsection{The ruler} The \LaTeX\ style defines a printed ruler which should be present in the version submitted for review. The ruler is provided in order that reviewers may comment on particular lines in the paper without circumlocution. If you are preparing a document using a non-\LaTeX\ document preparation system, please arrange for an equivalent ruler to appear on the final output pages. The presence or absence of the ruler should not change the appearance of any other content on the page. The camera-ready copy should not contain a ruler. (\LaTeX\ users may use options of cvpr.sty to switch between different versions.) Reviewers: note that the ruler measurements do not align well with lines in the paper --- this turns out to be very difficult to do well when the paper contains many figures and equations, and, when done, looks ugly. Just use fractional references (\eg, this line is $087.5$), although in most cases one would expect that the approximate location will be adequate. \subsection{Paper ID} Make sure that the Paper ID from the submission system is visible in the version submitted for review (replacing the ``*****'' you see in this document). If you are using the \LaTeX\ template, \textbf{make sure to update paper ID in the appropriate place in the tex file}. \subsection{Mathematics} Please number all of your sections and displayed equations as in these examples: \begin{equation} E = m\cdot c^2 \label{eq:important} \end{equation} and \begin{equation} v = a\cdot t. \label{eq:also-important} \end{equation} It is important for readers to be able to refer to any particular equation. Just because you did not refer to it in the text does not mean some future reader might not need to refer to it. It is cumbersome to have to use circumlocutions like ``the equation second from the top of page 3 column 1''. (Note that the ruler will not be present in the final copy, so is not an alternative to equation numbers). All authors will benefit from reading Mermin's description of how to write mathematics: \url{http://www.pamitc.org/documents/mermin.pdf}. \subsection{Blind review} Many authors misunderstand the concept of anonymizing for blind review. Blind review does not mean that one must remove citations to one's own work---in fact it is often impossible to review a paper unless the previous citations are known and available. Blind review means that you do not use the words ``my'' or ``our'' when citing previous work. That is all. (But see below for tech reports.) Saying ``this builds on the work of Lucy Smith [1]'' does not say that you are Lucy Smith; it says that you are building on her work. If you are Smith and Jones, do not say ``as we show in [7]'', say ``as Smith and Jones show in [7]'' and at the end of the paper, include reference 7 as you would any other cited work. An example of a bad paper just asking to be rejected: \begin{quote} \begin{center} An analysis of the frobnicatable foo filter. \end{center} In this paper we present a performance analysis of our previous paper [1], and show it to be inferior to all previously known methods. Why the previous paper was accepted without this analysis is beyond me. [1] Removed for blind review \end{quote} An example of an acceptable paper: \begin{quote} \begin{center} An analysis of the frobnicatable foo filter. \end{center} In this paper we present a performance analysis of the paper of Smith \etal [1], and show it to be inferior to all previously known methods. Why the previous paper was accepted without this analysis is beyond me. [1] Smith, L and Jones, C. ``The frobnicatable foo filter, a fundamental contribution to human knowledge''. Nature 381(12), 1-213. \end{quote} If you are making a submission to another conference at the same time, which covers similar or overlapping material, you may need to refer to that submission in order to explain the differences, just as you would if you had previously published related work. In such cases, include the anonymized parallel submission~\cite{Authors14} as supplemental material and cite it as \begin{quote} [1] Authors. ``The frobnicatable foo filter'', F\&G 2014 Submission ID 324, Supplied as supplemental material {\tt fg324.pdf}. \end{quote} Finally, you may feel you need to tell the reader that more details can be found elsewhere, and refer them to a technical report. For conference submissions, the paper must stand on its own, and not {\em require} the reviewer to go to a tech report for further details. Thus, you may say in the body of the paper ``further details may be found in~\cite{Authors14b}''. Then submit the tech report as supplemental material. Again, you may not assume the reviewers will read this material. Sometimes your paper is about a problem which you tested using a tool that is widely known to be restricted to a single institution. For example, let's say it's 1969, you have solved a key problem on the Apollo lander, and you believe that the CVPR70 audience would like to hear about your solution. The work is a development of your celebrated 1968 paper entitled ``Zero-g frobnication: How being the only people in the world with access to the Apollo lander source code makes us a wow at parties'', by Zeus \etal. You can handle this paper like any other. Do not write ``We show how to improve our previous work [Anonymous, 1968]. This time we tested the algorithm on a lunar lander [name of lander removed for blind review]''. That would be silly, and would immediately identify the authors. Instead write the following: \begin{quotation} \noindent We describe a system for zero-g frobnication. This system is new because it handles the following cases: A, B. Previous systems [Zeus et al. 1968] did not handle case B properly. Ours handles it by including a foo term in the bar integral. ... The proposed system was integrated with the Apollo lunar lander, and went all the way to the moon, don't you know. It displayed the following behaviours, which show how well we solved cases A and B: ... \end{quotation} As you can see, the above text follows standard scientific convention, reads better than the first version, and does not explicitly name you as the authors. A reviewer might think it likely that the new paper was written by Zeus \etal, but cannot make any decision based on that guess. He or she would have to be sure that no other authors could have been contracted to solve problem B. \medskip \noindent FAQ\medskip\\ {\bf Q:} Are acknowledgements OK?\\ {\bf A:} No. Leave them for the final copy.\medskip\\ {\bf Q:} How do I cite my results reported in open challenges? {\bf A:} To conform with the double-blind review policy, you can report results of other challenge participants together with your results in your paper. For your results, however, you should not identify yourself and should not mention your participation in the challenge. Instead present your results referring to the method proposed in your paper and draw conclusions based on the experimental comparison to other results.\medskip\\ \begin{figure}[t] \centering \fbox{\rule{0pt}{2in} \rule{0.9\linewidth}{0pt}} \caption{Example of caption. It is set in Roman so that mathematics (always set in Roman: $B \sin A = A \sin B$) may be included without an ugly clash.} \label{fig:onecol} \end{figure} \subsection{Miscellaneous} \noindent Compare the following:\\ \begin{tabular}{ll} \verb'$conf_a$' & $conf_a$ \\ \verb'$\mathit{conf}_a$' & $\mathit{conf}_a$ \end{tabular}\\ See The \TeX book, p165. The space after \eg, meaning ``for example'', should not be a sentence-ending space. So \eg is correct, {\em e.g.} is not. The provided \verb'\eg' macro takes care of this. When citing a multi-author paper, you may save space by using ``et alia'', shortened to ``\etal'' (not ``{\em et.\ al.}'' as ``{\em et}'' is a complete word). If you use the \verb'\etal' macro provided, then you need not worry about double periods when used at the end of a sentence as in Alpher \etal. However, use it only when there are three or more authors. Thus, the following is correct: ``Frobnication has been trendy lately. It was introduced by Alpher~\cite{Alpher02}, and subsequently developed by Alpher and Fotheringham-Smythe~\cite{Alpher03}, and Alpher \etal~\cite{Alpher04}.'' This is incorrect: ``... subsequently developed by Alpher \etal~\cite{Alpher03} ...'' because reference~\cite{Alpher03} has just two authors. \begin{figure*} \centering \begin{subfigure}{0.68\linewidth} \fbox{\rule{0pt}{2in} \rule{.9\linewidth}{0pt}} \caption{An example of a subfigure.} \label{fig:short-a} \end{subfigure} \hfill \begin{subfigure}{0.28\linewidth} \fbox{\rule{0pt}{2in} \rule{.9\linewidth}{0pt}} \caption{Another example of a subfigure.} \label{fig:short-b} \end{subfigure} \caption{Example of a short caption, which should be centered.} \label{fig:short} \end{figure*} \section{Formatting your paper} \label{sec:formatting} All text must be in a two-column format. The total allowable size of the text area is $6\frac78$ inches (17.46 cm) wide by $8\frac78$ inches (22.54 cm) high. Columns are to be $3\frac14$ inches (8.25 cm) wide, with a $\frac{5}{16}$ inch (0.8 cm) space between them. The main title (on the first page) should begin 1 inch (2.54 cm) from the top edge of the page. The second and following pages should begin 1 inch (2.54 cm) from the top edge. On all pages, the bottom margin should be $1\frac{1}{8}$ inches (2.86 cm) from the bottom edge of the page for $8.5 \times 11$-inch paper; for A4 paper, approximately $1\frac{5}{8}$ inches (4.13 cm) from the bottom edge of the page. \subsection{Margins and page numbering} All printed material, including text, illustrations, and charts, must be kept within a print area $6\frac{7}{8}$ inches (17.46 cm) wide by $8\frac{7}{8}$ inches (22.54 cm) high. Page numbers should be in the footer, centered and $\frac{3}{4}$ inches from the bottom of the page. The review version should have page numbers, yet the final version submitted as camera ready should not show any page numbers. The \LaTeX\ template takes care of this when used properly. \subsection{Type style and fonts} Wherever Times is specified, Times Roman may also be used. If neither is available on your word processor, please use the font closest in appearance to Times to which you have access. MAIN TITLE. Center the title $1\frac{3}{8}$ inches (3.49 cm) from the top edge of the first page. The title should be in Times 14-point, boldface type. Capitalize the first letter of nouns, pronouns, verbs, adjectives, and adverbs; do not capitalize articles, coordinate conjunctions, or prepositions (unless the title begins with such a word). Leave two blank lines after the title. AUTHOR NAME(s) and AFFILIATION(s) are to be centered beneath the title and printed in Times 12-point, non-boldface type. This information is to be followed by two blank lines. The ABSTRACT and MAIN TEXT are to be in a two-column format. MAIN TEXT. Type main text in 10-point Times, single-spaced. Do NOT use double-spacing. All paragraphs should be indented 1 pica (approx.~$\frac{1}{6}$ inch or 0.422 cm). Make sure your text is fully justified---that is, flush left and flush right. Please do not place any additional blank lines between paragraphs. Figure and table captions should be 9-point Roman type as in \cref{fig:onecol,fig:short}. Short captions should be centred. \noindent Callouts should be 9-point Helvetica, non-boldface type. Initially capitalize only the first word of section titles and first-, second-, and third-order headings. FIRST-ORDER HEADINGS. (For example, {\large \bf 1. Introduction}) should be Times 12-point boldface, initially capitalized, flush left, with one blank line before, and one blank line after. SECOND-ORDER HEADINGS. (For example, { \bf 1.1. Database elements}) should be Times 11-point boldface, initially capitalized, flush left, with one blank line before, and one after. If you require a third-order heading (we discourage it), use 10-point Times, boldface, initially capitalized, flush left, preceded by one blank line, followed by a period and your text on the same line. \subsection{Footnotes} Please use footnotes\footnote{This is what a footnote looks like. It often distracts the reader from the main flow of the argument.} sparingly. Indeed, try to avoid footnotes altogether and include necessary peripheral observations in the text (within parentheses, if you prefer, as in this sentence). If you wish to use a footnote, place it at the bottom of the column on the page on which it is referenced. Use Times 8-point type, single-spaced. \subsection{Cross-references} For the benefit of author(s) and readers, please use the {\small\begin{verbatim} \cref{...} \end{verbatim}} command for cross-referencing to figures, tables, equations, or sections. This will automatically insert the appropriate label alongside the cross-reference as in this example: \begin{quotation} To see how our method outperforms previous work, please see \cref{fig:onecol} and \cref{tab:example}. It is also possible to refer to multiple targets as once, \eg~to \cref{fig:onecol,fig:short-a}. You may also return to \cref{sec:formatting} or look at \cref{eq:also-important}. \end{quotation} If you do not wish to abbreviate the label, for example at the beginning of the sentence, you can use the {\small\begin{verbatim} \Cref{...} \end{verbatim}} command. Here is an example: \begin{quotation} \Cref{fig:onecol} is also quite important. \end{quotation} \subsection{References} List and number all bibliographical references in 9-point Times, single-spaced, at the end of your paper. When referenced in the text, enclose the citation number in square brackets, for example~\cite{Authors14}. Where appropriate, include page numbers and the name(s) of editors of referenced books. When you cite multiple papers at once, please make sure that you cite them in numerical order like this \cite{Alpher02,Alpher03,Alpher05,Authors14b,Authors14}. If you use the template as advised, this will be taken care of automatically. \begin{table} \centering \begin{tabular}{@{}lc@{}} \toprule Method & Frobnability \\ \midrule Theirs & Frumpy \\ Yours & Frobbly \\ Ours & Makes one's heart Frob\\ \bottomrule \end{tabular} \caption{Results. Ours is better.} \label{tab:example} \end{table} \subsection{Illustrations, graphs, and photographs} All graphics should be centered. In \LaTeX, avoid using the \texttt{center} environment for this purpose, as this adds potentially unwanted whitespace. Instead use {\small\begin{verbatim} \centering \end{verbatim}} at the beginning of your figure. Please ensure that any point you wish to make is resolvable in a printed copy of the paper. Resize fonts in figures to match the font in the body text, and choose line widths that render effectively in print. Readers (and reviewers), even of an electronic copy, may choose to print your paper in order to read it. You cannot insist that they do otherwise, and therefore must not assume that they can zoom in to see tiny details on a graphic. When placing figures in \LaTeX, it's almost always best to use \verb+\includegraphics+, and to specify the figure width as a multiple of the line width as in the example below {\small\begin{verbatim} \usepackage{graphicx} ... \includegraphics[width=0.8\linewidth] {myfile.pdf} \end{verbatim} } \subsection{Color} Please refer to the author guidelines on the CVPR\ 2022\ web page for a discussion of the use of color in your document. If you use color in your plots, please keep in mind that a significant subset of reviewers and readers may have a color vision deficiency; red-green blindness is the most frequent kind. Hence avoid relying only on color as the discriminative feature in plots (such as red \vs green lines), but add a second discriminative feature to ease disambiguation. \section{Final copy} You must include your signed IEEE copyright release form when you submit your finished paper. We MUST have this form before your paper can be published in the proceedings. Please direct any questions to the production editor in charge of these proceedings at the IEEE Computer Society Press: \url{https://www.computer.org/about/contact}. \section{Introduction} \label{sec:intro} Please follow the steps outlined below when submitting your manuscript to the IEEE Computer Society Press. This style guide now has several important modifications (for example, you are no longer warned against the use of sticky tape to attach your artwork to the paper), so all authors should read this new version. \subsection{Language} All manuscripts must be in English. \subsection{Dual submission} Please refer to the author guidelines on the CVPR\ 2022\ web page for a discussion of the policy on dual submissions. \subsection{Paper length} Papers, excluding the references section, must be no longer than eight pages in length. The references section will not be included in the page count, and there is no limit on the length of the references section. For example, a paper of eight pages with two pages of references would have a total length of 10 pages. {\bf There will be no extra page charges for CVPR\ 2022.} Overlength papers will simply not be reviewed. This includes papers where the margins and formatting are deemed to have been significantly altered from those laid down by this style guide. Note that this \LaTeX\ guide already sets figure captions and references in a smaller font. The reason such papers will not be reviewed is that there is no provision for supervised revisions of manuscripts. The reviewing process cannot determine the suitability of the paper for presentation in eight pages if it is reviewed in eleven. \subsection{The ruler} The \LaTeX\ style defines a printed ruler which should be present in the version submitted for review. The ruler is provided in order that reviewers may comment on particular lines in the paper without circumlocution. If you are preparing a document using a non-\LaTeX\ document preparation system, please arrange for an equivalent ruler to appear on the final output pages. The presence or absence of the ruler should not change the appearance of any other content on the page. The camera-ready copy should not contain a ruler. (\LaTeX\ users may use options of cvpr.sty to switch between different versions.) Reviewers: note that the ruler measurements do not align well with lines in the paper --- this turns out to be very difficult to do well when the paper contains many figures and equations, and, when done, looks ugly. Just use fractional references (\eg, this line is $087.5$), although in most cases one would expect that the approximate location will be adequate. \subsection{Paper ID} Make sure that the Paper ID from the submission system is visible in the version submitted for review (replacing the ``*****'' you see in this document). If you are using the \LaTeX\ template, \textbf{make sure to update paper ID in the appropriate place in the tex file}. \subsection{Mathematics} Please number all of your sections and displayed equations as in these examples: \begin{equation} E = m\cdot c^2 \label{eq:important} \end{equation} and \begin{equation} v = a\cdot t. \label{eq:also-important} \end{equation} It is important for readers to be able to refer to any particular equation. Just because you did not refer to it in the text does not mean some future reader might not need to refer to it. It is cumbersome to have to use circumlocutions like ``the equation second from the top of page 3 column 1''. (Note that the ruler will not be present in the final copy, so is not an alternative to equation numbers). All authors will benefit from reading Mermin's description of how to write mathematics: \url{http://www.pamitc.org/documents/mermin.pdf}. \subsection{Blind review} Many authors misunderstand the concept of anonymizing for blind review. Blind review does not mean that one must remove citations to one's own work---in fact it is often impossible to review a paper unless the previous citations are known and available. Blind review means that you do not use the words ``my'' or ``our'' when citing previous work. That is all. (But see below for tech reports.) Saying ``this builds on the work of Lucy Smith [1]'' does not say that you are Lucy Smith; it says that you are building on her work. If you are Smith and Jones, do not say ``as we show in [7]'', say ``as Smith and Jones show in [7]'' and at the end of the paper, include reference 7 as you would any other cited work. An example of a bad paper just asking to be rejected: \begin{quote} \begin{center} An analysis of the frobnicatable foo filter. \end{center} In this paper we present a performance analysis of our previous paper [1], and show it to be inferior to all previously known methods. Why the previous paper was accepted without this analysis is beyond me. [1] Removed for blind review \end{quote} An example of an acceptable paper: \begin{quote} \begin{center} An analysis of the frobnicatable foo filter. \end{center} In this paper we present a performance analysis of the paper of Smith \etal [1], and show it to be inferior to all previously known methods. Why the previous paper was accepted without this analysis is beyond me. [1] Smith, L and Jones, C. ``The frobnicatable foo filter, a fundamental contribution to human knowledge''. Nature 381(12), 1-213. \end{quote} If you are making a submission to another conference at the same time, which covers similar or overlapping material, you may need to refer to that submission in order to explain the differences, just as you would if you had previously published related work. In such cases, include the anonymized parallel submission~\cite{Authors14} as supplemental material and cite it as \begin{quote} [1] Authors. ``The frobnicatable foo filter'', F\&G 2014 Submission ID 324, Supplied as supplemental material {\tt fg324.pdf}. \end{quote} Finally, you may feel you need to tell the reader that more details can be found elsewhere, and refer them to a technical report. For conference submissions, the paper must stand on its own, and not {\em require} the reviewer to go to a tech report for further details. Thus, you may say in the body of the paper ``further details may be found in~\cite{Authors14b}''. Then submit the tech report as supplemental material. Again, you may not assume the reviewers will read this material. Sometimes your paper is about a problem which you tested using a tool that is widely known to be restricted to a single institution. For example, let's say it's 1969, you have solved a key problem on the Apollo lander, and you believe that the CVPR70 audience would like to hear about your solution. The work is a development of your celebrated 1968 paper entitled ``Zero-g frobnication: How being the only people in the world with access to the Apollo lander source code makes us a wow at parties'', by Zeus \etal. You can handle this paper like any other. Do not write ``We show how to improve our previous work [Anonymous, 1968]. This time we tested the algorithm on a lunar lander [name of lander removed for blind review]''. That would be silly, and would immediately identify the authors. Instead write the following: \begin{quotation} \noindent We describe a system for zero-g frobnication. This system is new because it handles the following cases: A, B. Previous systems [Zeus et al. 1968] did not handle case B properly. Ours handles it by including a foo term in the bar integral. ... The proposed system was integrated with the Apollo lunar lander, and went all the way to the moon, don't you know. It displayed the following behaviours, which show how well we solved cases A and B: ... \end{quotation} As you can see, the above text follows standard scientific convention, reads better than the first version, and does not explicitly name you as the authors. A reviewer might think it likely that the new paper was written by Zeus \etal, but cannot make any decision based on that guess. He or she would have to be sure that no other authors could have been contracted to solve problem B. \medskip \noindent FAQ\medskip\\ {\bf Q:} Are acknowledgements OK?\\ {\bf A:} No. Leave them for the final copy.\medskip\\ {\bf Q:} How do I cite my results reported in open challenges? {\bf A:} To conform with the double-blind review policy, you can report results of other challenge participants together with your results in your paper. For your results, however, you should not identify yourself and should not mention your participation in the challenge. Instead present your results referring to the method proposed in your paper and draw conclusions based on the experimental comparison to other results.\medskip\\ \begin{figure}[t] \centering \fbox{\rule{0pt}{2in} \rule{0.9\linewidth}{0pt}} \caption{Example of caption. It is set in Roman so that mathematics (always set in Roman: $B \sin A = A \sin B$) may be included without an ugly clash.} \label{fig:onecol} \end{figure} \subsection{Miscellaneous} \noindent Compare the following:\\ \begin{tabular}{ll} \verb'$conf_a$' & $conf_a$ \\ \verb'$\mathit{conf}_a$' & $\mathit{conf}_a$ \end{tabular}\\ See The \TeX book, p165. The space after \eg, meaning ``for example'', should not be a sentence-ending space. So \eg is correct, {\em e.g.} is not. The provided \verb'\eg' macro takes care of this. When citing a multi-author paper, you may save space by using ``et alia'', shortened to ``\etal'' (not ``{\em et.\ al.}'' as ``{\em et}'' is a complete word). If you use the \verb'\etal' macro provided, then you need not worry about double periods when used at the end of a sentence as in Alpher \etal. However, use it only when there are three or more authors. Thus, the following is correct: ``Frobnication has been trendy lately. It was introduced by Alpher~\cite{Alpher02}, and subsequently developed by Alpher and Fotheringham-Smythe~\cite{Alpher03}, and Alpher \etal~\cite{Alpher04}.'' This is incorrect: ``... subsequently developed by Alpher \etal~\cite{Alpher03} ...'' because reference~\cite{Alpher03} has just two authors. \begin{figure*} \centering \begin{subfigure}{0.68\linewidth} \fbox{\rule{0pt}{2in} \rule{.9\linewidth}{0pt}} \caption{An example of a subfigure.} \label{fig:short-a} \end{subfigure} \hfill \begin{subfigure}{0.28\linewidth} \fbox{\rule{0pt}{2in} \rule{.9\linewidth}{0pt}} \caption{Another example of a subfigure.} \label{fig:short-b} \end{subfigure} \caption{Example of a short caption, which should be centered.} \label{fig:short} \end{figure*} \section{Formatting your paper} \label{sec:formatting} All text must be in a two-column format. The total allowable size of the text area is $6\frac78$ inches (17.46 cm) wide by $8\frac78$ inches (22.54 cm) high. Columns are to be $3\frac14$ inches (8.25 cm) wide, with a $\frac{5}{16}$ inch (0.8 cm) space between them. The main title (on the first page) should begin 1 inch (2.54 cm) from the top edge of the page. The second and following pages should begin 1 inch (2.54 cm) from the top edge. On all pages, the bottom margin should be $1\frac{1}{8}$ inches (2.86 cm) from the bottom edge of the page for $8.5 \times 11$-inch paper; for A4 paper, approximately $1\frac{5}{8}$ inches (4.13 cm) from the bottom edge of the page. \subsection{Margins and page numbering} All printed material, including text, illustrations, and charts, must be kept within a print area $6\frac{7}{8}$ inches (17.46 cm) wide by $8\frac{7}{8}$ inches (22.54 cm) high. Page numbers should be in the footer, centered and $\frac{3}{4}$ inches from the bottom of the page. The review version should have page numbers, yet the final version submitted as camera ready should not show any page numbers. The \LaTeX\ template takes care of this when used properly. \subsection{Type style and fonts} Wherever Times is specified, Times Roman may also be used. If neither is available on your word processor, please use the font closest in appearance to Times to which you have access. MAIN TITLE. Center the title $1\frac{3}{8}$ inches (3.49 cm) from the top edge of the first page. The title should be in Times 14-point, boldface type. Capitalize the first letter of nouns, pronouns, verbs, adjectives, and adverbs; do not capitalize articles, coordinate conjunctions, or prepositions (unless the title begins with such a word). Leave two blank lines after the title. AUTHOR NAME(s) and AFFILIATION(s) are to be centered beneath the title and printed in Times 12-point, non-boldface type. This information is to be followed by two blank lines. The ABSTRACT and MAIN TEXT are to be in a two-column format. MAIN TEXT. Type main text in 10-point Times, single-spaced. Do NOT use double-spacing. All paragraphs should be indented 1 pica (approx.~$\frac{1}{6}$ inch or 0.422 cm). Make sure your text is fully justified---that is, flush left and flush right. Please do not place any additional blank lines between paragraphs. Figure and table captions should be 9-point Roman type as in \cref{fig:onecol,fig:short}. Short captions should be centred. \noindent Callouts should be 9-point Helvetica, non-boldface type. Initially capitalize only the first word of section titles and first-, second-, and third-order headings. FIRST-ORDER HEADINGS. (For example, {\large \bf 1. Introduction}) should be Times 12-point boldface, initially capitalized, flush left, with one blank line before, and one blank line after. SECOND-ORDER HEADINGS. (For example, { \bf 1.1. Database elements}) should be Times 11-point boldface, initially capitalized, flush left, with one blank line before, and one after. If you require a third-order heading (we discourage it), use 10-point Times, boldface, initially capitalized, flush left, preceded by one blank line, followed by a period and your text on the same line. \subsection{Footnotes} Please use footnotes\footnote{This is what a footnote looks like. It often distracts the reader from the main flow of the argument.} sparingly. Indeed, try to avoid footnotes altogether and include necessary peripheral observations in the text (within parentheses, if you prefer, as in this sentence). If you wish to use a footnote, place it at the bottom of the column on the page on which it is referenced. Use Times 8-point type, single-spaced. \subsection{Cross-references} For the benefit of author(s) and readers, please use the {\small\begin{verbatim} \cref{...} \end{verbatim}} command for cross-referencing to figures, tables, equations, or sections. This will automatically insert the appropriate label alongside the cross-reference as in this example: \begin{quotation} To see how our method outperforms previous work, please see \cref{fig:onecol} and \cref{tab:example}. It is also possible to refer to multiple targets as once, \eg~to \cref{fig:onecol,fig:short-a}. You may also return to \cref{sec:formatting} or look at \cref{eq:also-important}. \end{quotation} If you do not wish to abbreviate the label, for example at the beginning of the sentence, you can use the {\small\begin{verbatim} \Cref{...} \end{verbatim}} command. Here is an example: \begin{quotation} \Cref{fig:onecol} is also quite important. \end{quotation} \subsection{References} List and number all bibliographical references in 9-point Times, single-spaced, at the end of your paper. When referenced in the text, enclose the citation number in square brackets, for example~\cite{Authors14}. Where appropriate, include page numbers and the name(s) of editors of referenced books. When you cite multiple papers at once, please make sure that you cite them in numerical order like this \cite{Alpher02,Alpher03,Alpher05,Authors14b,Authors14}. If you use the template as advised, this will be taken care of automatically. \begin{table} \centering \begin{tabular}{@{}lc@{}} \toprule Method & Frobnability \\ \midrule Theirs & Frumpy \\ Yours & Frobbly \\ Ours & Makes one's heart Frob\\ \bottomrule \end{tabular} \caption{Results. Ours is better.} \label{tab:example} \end{table} \subsection{Illustrations, graphs, and photographs} All graphics should be centered. In \LaTeX, avoid using the \texttt{center} environment for this purpose, as this adds potentially unwanted whitespace. Instead use {\small\begin{verbatim} \centering \end{verbatim}} at the beginning of your figure. Please ensure that any point you wish to make is resolvable in a printed copy of the paper. Resize fonts in figures to match the font in the body text, and choose line widths that render effectively in print. Readers (and reviewers), even of an electronic copy, may choose to print your paper in order to read it. You cannot insist that they do otherwise, and therefore must not assume that they can zoom in to see tiny details on a graphic. When placing figures in \LaTeX, it's almost always best to use \verb+\includegraphics+, and to specify the figure width as a multiple of the line width as in the example below {\small\begin{verbatim} \usepackage{graphicx} ... \includegraphics[width=0.8\linewidth] {myfile.pdf} \end{verbatim} } \subsection{Color} Please refer to the author guidelines on the CVPR\ 2022\ web page for a discussion of the use of color in your document. If you use color in your plots, please keep in mind that a significant subset of reviewers and readers may have a color vision deficiency; red-green blindness is the most frequent kind. Hence avoid relying only on color as the discriminative feature in plots (such as red \vs green lines), but add a second discriminative feature to ease disambiguation. \section{Final copy} You must include your signed IEEE copyright release form when you submit your finished paper. We MUST have this form before your paper can be published in the proceedings. Please direct any questions to the production editor in charge of these proceedings at the IEEE Computer Society Press: \url{https://www.computer.org/about/contact}. {\small \bibliographystyle{ieee_fullname} \section{Dataset Analysis} We present the statistics about five datasets we used in our experiments. Table~\ref{tab:dataset_st} shows the statistics. \paragraph{ReferItGame:} ReferItGame~\cite{kazemzadeh2014referitgame} contains images from SAIAPR12~\cite{escalante2010segmented} and collects expressions by a two-player game. In this game, the first player is shown an image with an object annotation and asked to write a natural language expression referring to the object. The second player is shown the same image and the written expression and asked to click the object's corresponding area. If the clicking is correct, the two players receive points and swap roles. If not, the new image would be presented. \paragraph{RefCOCO, RefCOCO+, RefCOCOg:} These three datasets contain images from MSCOCO~\cite{lin2014microsoft}. Expressions in RefCOCO~\cite{yu2016modeling} and RefCOCO+~\cite{yu2016modeling} are also collected by the two-player game proposed in ReferitGame~\cite{kazemzadeh2014referitgame}. There are two test splits called ``testA'' and ``testB''. Images in ``testA'' only contain multiple people annotation. In contrast, images in ``testB'' contain all other objects. Expressions in RefCOCOg~\cite{mao2016generation} are collected on Amazon Mechanical Turk in a non-interactive setting. Thus, the expressions in RefCOCOg are longer and more complex. RefCOCOg has ``google'' and ``umd'' splits. The ``google'' split does not have a public test set. And there is an overlap between the training and validation image set. The ``umd'' split does not have this overlap. We denote these splits by ``val-g'', ``val-u'' and ``test-u'', respectively. \paragraph{Flickr30k Entities:} Flickr30k Entities~\cite{plummer2015flickr30k} contains images in Flickr30k dataset. The query sentences are short noun phrases in the captions of the image. The queries are easier to understand. \section{QD-ATT in Other Vision Backbones} The experimental results in our paper have shown that the Query-aware Dynamic Attention can help improve the transformer-based visual backbone. In this section, we present the performance improvement in visual grounding by applying the Query-aware Dynamic Attention to DarkNet53~\cite{redmon2018yolov3} and ResNet~\cite{he2016deep} to show its generalizability in different backbones. \paragraph{DarkNet53.} We use a state-of-the-art one-stage visual grounding framework ReSC~\cite{yang2020improving}, which adopts the visual feature map from the 102-th convolutional layer of DarkNet53. We append Query-aware Dynamic Attention modules after the 78-th, 91-th and 102-th convolutional layer of DarkNet53. We take the visual feature map from the last Query-aware Dynamic Attention module as the output of the visual backbone. \paragraph{ResNet.} We consider the TransVG~\cite{deng2021transvg} framework, which uses ResNet50 as the visual backbone. We apply Query-aware Dynamic Attention modules to the C2, C3, C4, and C5 layers. The evaluation results using different visual backbones on the ReferItGame dataset are shown in \Cref{tab:qd_imp}. The proposed QD-ATT can also significantly improve the performance. \begin{table}[t] \centering \begin{tabular}{@{}llll@{}} \toprule Dataset & Images & Instances & Queries \\ \midrule RefCOCO & 19,994 & 50,000 & 142,210 \\ RefCOCO+ & 19,992 & 49,856 & 141,564 \\ RefCOCOg & 25,799 & 49,822 & 95,010 \\ ReferItGame & 20,000 & 19,987 & 120,072 \\ Flickr30K Entities & 31,783 & 427,000 & 427,000 \\ \bottomrule \end{tabular} \caption{Data statistics of RefCOCO, RefCOCO+, RefCOCOg, ReferItGame and Flickr30K Entities.} \label{tab:dataset_st} \end{table} \begin{table}[t] \centering \begin{tabular}{@{}lcc@{}} \toprule \multicolumn{1}{l|}{\multirow{2}{*}{Model}} & \multicolumn{2}{c}{ReferItGame} \\ \multicolumn{1}{l|}{} & val & test \\ \midrule \multicolumn{3}{l}{\textbf{\emph{DarkNet53}}} \\ \midrule \multicolumn{1}{l|}{ReSC-Base} & 66.78 & 64.33 \\ \multicolumn{1}{l|}{\quad +QD-ATT} & $\text{67.85}_{\text{+1.07}}$ & $\text{65.21}_{\text{+0.88}}$ \\ \midrule \multicolumn{3}{l}{\textbf{\emph{ResNet50}}} \\ \midrule \multicolumn{1}{l|}{TransVG} & 71.60 & 69.76 \\ \multicolumn{1}{l|}{\quad +QD-ATT} & $\text{75.01}_{\text{+3.41}}$ & $\text{72.67}_{\text{+2.91}}$ \\ \bottomrule \end{tabular} \caption{Performance of ReSC and TransVG when QD-ATT is adopted.} \label{tab:qd_imp} \end{table} \section{Ablation study on RefCOCO} We also present the ablation study results on RefCOCO dataset in \Cref{tab:sub_abl_module} and \Cref{tab:sub_abl_attention}. The experimental results reveal similar conclusions. We also notice that spatial attention is more useful in ``testA'' split and channel attention is more useful in ``testB'' split. It is because the referents in ``testB'' can be arbitrary objects but images in ``testA'' only contain multiple people annotation. \section{Analysis of hyper-parameter K} We study the impact of hyper-parameter $K$ which denotes the factor dimension. We report the accuracy of our model with $K=\{10,30,50,70\}$ in \Cref{fig:factor}. When $K$ is small, the QD-ATT\ cannot learn the transformation well. And when $K$ is large, the QD-ATT\ is easy to overfit and performs worse on validation set. We take the best $K=30$ on the validation set as our default setting. \section{Efficiency Analysis} We study the running time of our model with different factor dimensions in the Query-aware Dynamic Attention. We set $K=\{0,10,30,50,70\}$. $K=0$ is a special setting which means the Query-aware Dynamic Attention directly returns the input feature without any computation. We conduct the experiment on a single NVIDIA RTX3090 GPU. The results are shown in \Cref{fig:factor_time}. We notice that the running time increases linearly with the growth of K. We also observe that incorporating the Query-aware Dynamic Attention does not introduce excessive computation cost, which means our QD-ATT is efficient and effective. \begin{table}[t] \centering \begin{minipage}{1\linewidth} \centering \small \begin{tabular}{c|cc} \toprule &\multicolumn{2}{c}{RefCOCO}\\ & testA & testB \\ \midrule (a) & 84.63 & 81.42 \\ (b) & 84.46 & 80.96 \\ (c) & 84.01 & 79.83 \\ \bottomrule \end{tabular} \caption{Ablation studies of QD-ATT in two phases of QRNet.} \label{tab:sub_abl_module} \vspace{1em} \end{minipage}% \hspace{.01\linewidth} \begin{minipage}{1\linewidth} \centering \small \begin{tabular}{c|cc} \toprule &\multicolumn{2}{c}{RefCOCO} \\ & testA & testB \\ \midrule (d) & 84.61 & 81.25 \\ (e) & 85.43 & 80.91 \\ \bottomrule \end{tabular} \caption{Ablation studies of different attentions in QD-ATT.} \label{tab:sub_abl_attention} \end{minipage} \end{table} \begin{figure}[tb] \centering \includegraphics[width=1\linewidth]{figs/factor.pdf} \caption{The effect of factor dimension $K$ on the validation split of ReferItGame dataset.} \label{fig:factor} \vspace{-1.4em} \end{figure} \begin{figure}[tb] \centering \includegraphics[width=1\linewidth]{figs/factor_time.pdf} \caption{The running time (ms) of our model with different factor dimension $K$ on the validation split of ReferItGame.} \label{fig:factor_time} \end{figure} \section{Qualitative Analysis} \paragraph{Feature Refinement Visualization.} We present more visualize cases in \Cref{fig:vis_wide}. It shows the ability of our QRNet to refine general purposed feature maps to query-aware feature maps. \begin{figure*}[htb] \centering \includegraphics[width=\textwidth]{figs/wide_vis.pdf} \caption{Visualization of activation maps from the backbone of our MMSwin\ \ and original Swin-Transformer. Red: the predicted box. White: the ground-truth box.} \label{fig:vis_wide} \end{figure*} \paragraph{Comparison with TransVG.} We quantitatively compare the results predicted by our model and the TransVG in \Cref{fig:case}. Green boxes are the ground truth. Yellow and red boxes are the predictions of our model and TransVG, respectively. In the first row, we notice that the predictions of TransVG are close to the ground truth. However, sometimes the TransVG only localizes the significant areas of the target objects (e.g., ``mountain on right"), and sometimes the predicted boxes cover the irrelevant areas around the target objects (e.g., ``person in white"), resulting in failures. In the second row, the TransVG does not fully capture the semantics of queries and is vulnerable to the interference of significantly noisy objects in the image, resulting in incorrect predictions. Our model utilizes query sentence representation to guide the visual backbone to obtain query-aware visual features, which helps the framework give correct predictions. \paragraph{Failure Cases.} We show some typical failure cases in \Cref{fig:failure_case}. One type of error is the long tail description. For the first example, our model does not recognize ``slats'' correctly. During both the pre-training the fine-tuning, the samples of long-tail concepts are infrequent. Thus, our method fails. For the second image, we notice that ``crazy'' is an abstract word, and its visual appearance can be completely different in different contexts. Therefore, it is also hard for our model to learn. In the third example, we found that our model understands the query's intention, but it tends to predict a box containing some objects, and the annotator does not have such bias. For the last example, we find that our model may make mistakes when facing long sentence queries. Our model only takes the [CLS] representation rather than the complete sequence representation from BERT to refine the visual features, limiting the ability to understand long text. \section{Limitation} In this paper, we propose QD-ATT\ to extract query-consistent features from the visual backbone. However, we only take the contextual textual representation of the query to keep it efficient. Due to the lack of fine-grained multimodal interaction, we still need a post-interaction module in the visual grounding framework. It also hinders generalizing our module to the task requiring complex reasoning, \eg, multimodal dialogue~\cite{nie2019multimodal} and visual storytelling~\cite{huang2016visual}. \begin{figure*}[b] \centering \includegraphics[width=0.8\linewidth]{figs/case_cropped.pdf} \caption{ % Qualitative comparison with TransVG. % Green boxes are the ground-truth, yellow boxes are the predictions of our model, and red boxes denote the predictions of TransVG.} \label{fig:case} \end{figure*} \begin{figure*}[b] \centering \includegraphics[width=0.8\linewidth]{figs/fail_case_cropped.pdf} \caption{The failure cases of our model. Green boxes are the ground-truth, yellow boxes are the predictions of our model.} \label{fig:failure_case} \end{figure*} \section{Online Deployment Setting} We apply QRNet to enhance the search engine in Pailitao at Alibaba and perform A/B testing. In order to reduce the discrepancy between the images from consumers and sellers, it is important to locate the target from the item image. Note that a detection-based two-stage method is already deployed online. The A/B testing system split online users equally into two groups and direct them into two separate buckets, respectively. Then in bucket A (i.e., the baseline group), the target boxes from images are generated by a detection-based method. While for users in the B bucket (i.e., the experimental group), the target boxes are generated by the proposed QRNet. All the conditions of the two buckets are identical except for the target grounding methods. We calculate the clicked query rate and the number of transactions for all the categories in the two buckets. The online A/B testing lasts for two days, and over 1.5 million daily active users are in each bucket. We find that the performance in the experimental bucket (i.e., QRNet) is significantly better (p $<$ 0.05) than that in the baseline bucket (i.e., detection-based) on both measures. QRNet decreases the no click rate by 1.47\% and improves the number of transactions by 2.20\% over the baseline. More specifically, the decrease of the no click rate implies that QRNet can generate more accurate target boxes so that users are more likely to click. The improvement of the number of transactions means that the clicked item is exactly what the users want to purchase, which also reveals the great performance of QRNet. \section{Pseudo-code of QD-ATT} We present a Pytorch-style pseudo-code in Listing~\ref{lst:qda}. \begin{figure*} \begin{lstlisting}[language=Python, caption=Pytorch-style pseudo-code of Query-aware Dynamic Attention, label={lst:qda},xleftmargin=.05\textwidth, xrightmargin=.05\textwidth] # Perform linear transform to change the dimension of the vector space from in_dim to out_dim # Inputs: # F: the input visual features (B, H, W, D_in) # q: the input linguistic feature (B, D_q) # Return: # F_q: the output transformed visual features (B, H, W, D_out) # Parameters: # linear: a plain linear layer to generate factor U # S: a random-initialized factor matrix (K, D_out) def dynamic_linear(F, q): # Parameter generation # K is the factor dimension # generate the factor matrix U U = reshape(linear(q), (B, D_in+1, K)) # reconstructed matrix by U x S M = einsum("bik,kj->bij", U, S) Weight, bias = M[:,:-1], M[:,-1] # Perform linear transform F_q = einsum("b...d,bde->b...e", F, Weight) + bias return F_q # Perform dynamic attention on visual feature map by textual guidance. # Inputs: # F: input visual feature map (B, H, W, C) # q: [CLS] token's last hiddenn states from BERT (B, D_q) # Return: # F_refined: refined visual feature (B, H, W, C) def query_aware_dynamic_attention(F, q): # Channel Attention B,H,W,C = F.shape F_flatten = reshape(F, (B, -1, C)) avg_pool = mean(F_flatten, dim=1) # The mlp transform the channel dimension C -> C/16 -> C att_avg = dynamic_linear(relu((dynamic_linear(avg_pool, q))), q) max_pool = max(F_flatten, dim=1) att_max = dynamic_linear(relu((dynamic_linear(max_pool, q))), q) attn = sigmoid(att_avg + att_max) F = F * reshape(attn, (B, 1, 1, C)) # Spatial Attention # dynamic_linear transform channel dimension C -> 1 attn = sigmoid(dynamic_linear(F, q)) F_refined = F * attn return F_refined \end{lstlisting} \end{figure*} \section{Introduction} \label{sec:intro} \input{1.intro} \section{Related Work} \label{sec:related} \input{2.related_work} \section{Approach} \label{sec:method} \input{3.method} \section{Experiments} \label{sec:experiment} \input{4.experiment} \section{Online Deployment} Previous experimental results have proven the advantages of our proposed QRNet, so we deploy it in a real-world online environment to test its practical performance. Specifically, we apply QRNet to enhance the search engine in Pailitao at Alibaba and perform A/B testing to evaluate the impact of our model. Details can be found in supplementary materials. We observe that QRNet decreases the no click rate by 1.47\% and improves the number of transactions by 2.20\% over the baseline. More specifically, the decrease of no click rate implies that QRNet can generate more accurate target boxes so that users are more likely to click. The improvement of the number of transactions means that the clicked item is exactly the users want to purchase, which also reveals the great performance of QRNet. \section{Conclusion} In this paper, we argue that pre-trained visual backbones cannot produce visual features that are consistent with the requirement of visual grounding. To overcome the weaknesses, we propose a Query-modulated Refinement Network\ (MMSwin\ )\ to adjust the visual feature maps with the guidance of query text. The MMSwin\ \ is designed based on a novel Query-aware Dynamic Attention mechanism, which can dynamically compute query-dependent spatial and channel attentions for refining visual features. Extensive experiments indicate that the improved framework significantly outperforms the state-of-the-art methods. The proposed MMSwin\ \ exhibits vast potential to improve multimodal reasoning. In future work, we plan to improve the fine-grained interaction ability of MMSwin\ \ and discard the post-interaction modules to simplify the existing end-to-end visual grounding frameworks. \paragraph{Acknowledgement} We thank Zenghui Sun, Quan Zheng and Weilin Huang at Alibaba Group for their help on online deployment and the anonymous reviewers for their valuable suggestions. This work was supported by the National Innovation 2030 Major S\&T Project of China (No.2020AAA0104200 \& 2020AAA0104205), the Science and Technology Commission of Shanghai Municipality (No. 19511120200 \& 21511100100 \& 18DZ2270800), the Open Fund of PDL, and Alibaba Group through Alibaba Research Intern Program. {\small \bibliographystyle{ieee_fullname} \section{Introduction} \label{sec:intro} \input{1.intro} {\small \bibliographystyle{ieee_fullname} \subsection{Overall Architecture} \begin{figure}[tb] \includegraphics[width=1\linewidth]{figs/overview_cropped.pdf} \caption{An overview of the MMSwin\ . (1) The language model first extract textual feature sequence. (2) Our query-aware vision backbone extracts and fuse multiscale visual features with textual guidance. (3) The visual and textual feature sequences are fed into a transformer, and a [REG] token representation is used to regress the bounding box.} \label{fig:model} \end{figure} Before detailing the proposed mechanism and modules, we first present a typical visual grounding architecture used in this paper. We followed the recently proposed state-of-the-art architecture TransVG\cite{deng2021transvg}. Given an image and a query sentence, there is a linguistic backbone, typically a pre-trained BERT model, extracting a 1D feature sequence $t\in \mathbb{R}^{D_l\times N_l}$. There is also a vision backbone extracting a 2D feature map $v'\in \mathbb{R}^{D_v\times H\times W}$. Generally, the resolution of the feature map is $\frac{1}{2^s}$ of the origin image resolution, where $s$ is the number of downsample operators. The 2D feature map $v'$ is further flatten into a feature sequence $v \in \mathbb{R}^{D_v\times N_v}$, where $N_v=H\times W$. Two projection layers project the visual and linguistic features into the same feature space $\mathbb{R}^{D}$. The projected visual and linguistic features are denoted by $p_v\in \mathbb{R}^{D\times N_v}$ and $p_l\in \mathbb{R}^{D\times N_l}$. Then it concatenates $p_v$ and $p_l$ and inserts a learnable embedding (namely a [REG] token) at the begining of the concatenated sequence. The joint sequence is formulated as: \begin{equation} \begin{aligned} \boldsymbol{x}_{0}=[p_{r}, \underbrace{p_{v}^{1}, p_{v}^{2}, \cdots, p_{v}^{N_{v}}}_{\text {visual tokens } \boldsymbol{p}_{v}}, \overbrace{p_{l}^{1}, p_{l}^{2}, \cdots, p_{l}^{N_{l}}}^{\text {linguistic tokens } p_{l}}] \end{aligned} \end{equation} where $p^r$ is the learnable embedding of [REG] token. A multi-layer visual-linguistic transformer with positional encoding is applied to perform inta- and inter- modal reasoning on the joint sequence. Finally, a prediction head takes the output representation of the [REG] token to predict the bounding box coordinates. Specifically, an MLP with ReLU activations transforms the $D$-dim [REG] embedding to 4-dim coordinates $b$. The smooth L1 loss and giou loss are using to train the framework. The training object can be formulated as: \begin{equation} \begin{aligned} \mathcal{L}=\mathcal{L}_{smooth-l1}{(b,\hat{b})}+\mathcal{L}_{giou}{(b,\hat{b})} \end{aligned} \end{equation} where $\hat{b}$ is the ground-truth box. The structure of TransVG is elegant and representative of most visual grounding frameworks. We notice a widespread problem that not all visual signals in images are helpful for the grounding task. However, the vision backbone pre-trained on detection tasks tends to extract all objects it has learned. Moreover, the backbone is trained to extract features for classification and is not enough for cross-modal alignment. There is also a problem that the cross-modal interaction module takes the feature map from the last layer or a query-agnostic multi-scale fusion whose scale may be inconsistent with the referent object or be noisy. To deal with these problems, we propose infusing the linguistic embedding into the vision backbone to guide the feature extraction and multi-scale feature fusion. To utilize the multi-scale feature, we first discard the vision backbone of TransVG because it only produces single-scale features. Instead, we use Swin-Transformer to extract multi-scale features. Then we introduce a novel Query-Driven Attention Mechanism, which leverages the linguistic embedding to drive the visual feature refinement. We further integrated the mechanism within the Swin-Transformer to guide the hierarchical feature extraction and multi-scale fusion. The improved backbone is called Modulated and Multiscale Swin-Transformer. We will cover the details in the following sections. \subsection{Query-Driven Attention Mechanism} In this section, we describe how we produce textual guidance and computing the visual attention distribution. Given an contextual textual representation $p_l^c \in \mathbb{R}^{D_l}$ (\eg a [CLS] token embedding), we introduce a Query Guidance Generator to generate a guide function $v_{clue}=G(v,\Theta_l)$. Then for each intermediate visual feature map $v$. We use a Multi-level Feature Refinement module to produce a refined feature map $v^*=R(v,p_l^c)$ with the help of the decoder \subsubsection{Query Guidance Function} The existing visual feature extractor uses modules with static parameters to process the visual feature map. For different data points with the same image, the outputs are the same. However, in visual grounding, the text reveals the intention of the query. For different query text, the crucial visual clues are also different. Thus we propose a dynamic linear layer as our guidance function which parameters are decoded from the contextual textual representation $p_l^c$. For the guidance function, we define its parameters by $\Theta_l=\{W_l,b_l\},\,W_l\in \mathbb{R}^{D^{in}\times D^{out}},\, b_l\in \mathbb{R}^{D^{out}}$, where $D^{in}$ and $D^{out}$ are the dimensions of input and output respectively. The guidance function can be formulized as follow: \begin{equation} \begin{aligned} v_{clue}&=G(v,\Theta_l)=vW_l+b_l \end{aligned} \end{equation} A intuitive way to decode these parameters is introduce another larger linear module, which is denoted by $\Theta^{'}_l=\mathrm{Decoder}(p_l^c)$, where $\Theta^{'}_l\in\mathbb{R}^{(D^{in}+1)\ast D^{out}}$. We can simply reshape and split $\Theta^{'}_l$ to obtain $\{W_l,b_l\}$. However, it's easy to find that the number of parameters in the decoder is $D_l\ast ((D^{in}+1)\ast D^{out})$. We found that such large-scale parameters will slow down the training speed of the network and make it easier to be overfitting. Inspired by the application of matrix factorization, we consider decomposing the $\Theta_l$ into two factor $U\in \mathbb{R}^{(D^{in}+1)\times K}$ and $V\in \mathbb{R}^{K\times D^{out}}$, where $U$ is a matrix decoded from $p_l^c$, $V$ is a static learnable matrix, $K$ is a hyper-parameter denote the dimension of factor matrixes. The decompose-based decode $\{W_l,b_l\}=\mathrm{Decoder}^*(p_l^c)$ can be formulated as follow: \begin{equation} \begin{aligned} U^{'} &= p_l^c W^{dec}+b^{dec}\\ U&=\mathrm{Reshape}(U^{'}) \end{aligned} \end{equation} where $W^{dec}\in \mathbb{R}^{D_l\times (D^{in}+1)\ast K}$ and $ b^{dec}\in \mathbb{R}^{(D^{in}+1)\ast K}$ are the paramemters of the factor decoder. We first use the factor decoder to calculate the vector $U^{'}\in \mathbb{R}^{(D^{in}+1)\ast K}$, We further reshape it into a matrix $U\in \mathbb{R}^{(D^{in}+1)\times K}$. \begin{equation} \begin{aligned} \Theta_l&=UV\\ \{W_l,b_l\} &= \mathrm{Split}(\Theta_l)\\ \end{aligned} \end{equation} Then the parameter matrix of guidance function $\Theta_l$ can be reconstruct by multiply $U$ and $V$. The $W_l$ and $b_l$ can be split from the matrix $U$ along the first dimension. Finally, we reformulized the guidance function as follow: \begin{equation} \begin{aligned} v_{clue}&=G^*(v,p_l^c)=G(v,\mathrm{Decoder}^*(p_l^c)) \end{aligned} \end{equation} \subsubsection{Multi-level Feature Refinement} \begin{figure}[tb] \centering \includegraphics[width=1\linewidth]{figs/sc-attention_1_cropped.pdf} \caption{Diagram of the Query-Driven Attention Mechanism} \label{fig:query_attention} \end{figure} After obtaining the textual guidance, we consider refining the visual feature map. As explained earlier, the pre-trained vision backbone is sensitive to all salient objects. Most of them are irrelevant to the query text. Therefore, The backbone only needs to attend to a few areas. Besides, the extracted feature is suitable for the pretraining classification task instead of visual grounding. In other words, the importance of channels is different. Inspired by the Convolutional Block Attention Module\cite{woo2018cbam}, we consider infer a channel attention map $A_c$ to calibrate the semantic of feature for a better cross-modal alignment. And we further infer a spatial attention map $A_s$ from calibrated feature to reveal where the referent located. Specifically, for a given visual feature $v\in \mathbb{R}^{H\times W\times D_v}$, we first aggregate its spatial information by average pooling and maximum pooling and produce $v^c_{max}\in \mathbb{R}^{1\times 1\times D_v}$ and $v^c_{mean}\in \mathbb{R}^{1\times 1\times D_v}$. We further build a query-driven multilayer perception (QMLP) consists of two guide functions. We use a ReLU activation after the first guide function. The output dimension is the same as the input dimension. To reduce the number of parameter, we set the dimension of hidden states as $D_v/r$, where $r$ is the reduction ratio. By feeding the $v^c_{max}$ and $v^c_{mean}$ to the QMLP, we merge the two output features using summation. The channel attention map $A_c$ can be captured as follow: \begin{equation} \begin{aligned} v^{cl}_{mean}&=G^*_1(\mathrm{ReLU}(G^*_0(v^c_{mean},p_l^c)),p_l^c)\\ v^{cl}_{max}&=G^*_1(\mathrm{ReLU}(G^*_0(v^c_{max},p_l^c)),p_l^c)\\ A_c&=\mathrm{sigmoid}(v^{cl}_{mean}+v^{cl}_{max}) \end{aligned} \end{equation} We perform element-wise multiplication between $v$ and $A_c$ to form the representation of the channel refined visual feature: \begin{equation} \begin{aligned} \dot{v}&=A_c\otimes v \end{aligned} \end{equation} The $A_c$ are broadcast along the spatial dimension. To generate a spatial attention map, instead pooling the channel dimension, we leverage a guidance function to reduce the channel dimension to learn areas interest to the query and apply a sigmoid function to generate the attention map. In short, The computing process is formulated as follow: \begin{equation} \begin{aligned} A_s&=\mathrm{sigmoid}(G(\dot{v},p_l^c))\\ \ddot{v}&=A_c\otimes \dot{v} \end{aligned} \end{equation} where $A_s\in \mathbb{R}^{H\times W\times 1}$ is the spatial attention map and $\ddot{v}$ is the spatial refined visual feature and also the output of our multi-level feature refinement. \subsection{Modulated and Multiscale Swin-Transformer} In this section, we discuss how to use query-driven attention to extend Swin-Transformer to a modulated vision backbone. We propose a Modulated Swin-Transformer Block to plug into each stage of Swin-Transformer architecture to help extract query-aware visual features. Thanks to the hierarchical structure, we can obtain features at different scales from each stage. We introduce a Query-guided Multiscale Feature Fusion to compute a scale-consist visual feature map. We present the proposed modules below. \subsubsection{Modulated Swin-Transformer Block} For a given image $I \in \mathbb{R}^{H\times W\times 3}$, a plain Swin-Transformer first embed $I$ to a $v_0 \in \mathbb{R}^{\frac{H}{4}\times \frac{W}{4}\times 48}$. Then $v_0$ is feeded into four cascaded stages. Each stage $k$ receives the visual feature map $v_{k-1}$ and generates a transformed feature map $v_{k}$. As shown in \Cref{fig:stage}, we take the [CLS] representation of the input query sentence from BERT as the contextual query representation $p_l^c$. We append a Query-Driven Attention module after each Swin Transformer Block. It recieves the transformed feature $v_{k}$ and produces a query-aware feature $v_k^{*}$ to the next stage. \begin{figure}[tb] \centering \includegraphics[width=1\linewidth]{figs/block_cropped.pdf} \caption{Modulated Swin-Transformer Block} \label{fig:stage} \end{figure} \subsubsection{Query-guided Multiscale Feature Fusion} \label{sec:multiscale} Except the first stage, each stage reduce the resolution of feature map by a patch merging operator. In other words, the resolutions of the output of each stage are $\frac{H}{4}\times\frac{H}{4},\,\frac{H}{8}\times\frac{H}{8},\,\frac{H}{16}\times\frac{H}{16}$ and $\frac{H}{32}\times\frac{H}{32}$, respectively. Beside, the patch merging operator fuse the patch feature into channel which double the channel dimension. Thus the channel dimensions of the output of each stage are $C,\,2C,\,4C$ and $8C$. Note that because visual grounding require fine-grained interaction (\eg Cross Attention), high-resolution features will dramatically increase the computation. Besides they will bring in noise and hurt the accuracy. Previous works using the last feature will obviously lose scale information. We propose to fuse the features with query guidance follow a bottom-up pathway. Specifically, we first use four $1\times 1$ convolutional layers to unify the channel dimensions to $D$. To filter out noisy signals in the feature maps, we build query-driven attention modules for the first three feature maps $\{v^{*}_k |\,k=1,2,3 \}$. Each module produce a weighted feature map with the same shape as before. Instead of interpolating the visual feature map to low-resolution, we consider apply a $2\times 2$ mean pooling with stride=2 to reduce the resolution to be the same as next feature map and add it to the next feature map $v^{*}_{k+1}$. Finally, the last feature map $v^{*}_{4}$ contains features interest to the query from all scales. We also apply a max pooling to obtain a smaller faeture map $v^{*}_{5} \in\frac{H}{64}\times\frac{H}{64}$. We flatten and concatenate the $v^{*}_{4}$ and $v^{*}_{5}$ as the output token sequence of our Modulated and Multiscale Swin-Transformer.
{'timestamp': '2022-03-30T02:30:34', 'yymm': '2203', 'arxiv_id': '2203.15442', 'language': 'en', 'url': 'https://arxiv.org/abs/2203.15442'}
arxiv
\section{Introduction} Open Source Software (OSS) has become ubiquitous and provides developers with a free-to-use platform for open public collaboration. With project developers spread across the world, OSS projects bring in diverse perspectives which are important for the success and sustainability of a project. In terms of OSS, GitHub has become the most popular web-based open-source software for developers to store and manage their code as well as track and control changes to their code.\\ In software development, developers and users (in the form of outside external contributors) utilize GitHub as an issue tracker and code collaboration tool across various projects. It is critically important to understand that software development across various developers is more productive when there is communication amongst developers across different projects. In addition, the progress of software development can be demonstrated through communication within the team and even across outside teams not working on this project. This phenomenon can be observed when developers accurately respond to any code-related bugs (commonly termed an issue in GitHub) report if there are any. \\ In this project, we intend to study the effect of increased communication via shared code development on the productivity of the projects on GitHub. We particularly intend to find the most significant factors that influence the productivity of a project. To analyze the productivity within a software development medium, we decided to leverage the metric of average latency of issue closure associated with a project (we consider a repository as one project). It is computed by calculating the sum of all the issue lifetime (time taken to close an issue) for every issue within a project and dividing it by the number of closed issues for a given repository. For considering the communication across developers beyond the considered project, we measured a metric that measured cross-development across multiple open source repositories. This metric was the average (mean) number of repositories worked by the top ten contributors (based on their involvement in the current project) outside the current project. In addition to this, we also analyzed certain other standard metrics relating to a project such as the number of contributors (team size), age of a project (how long it is active since its creation), total closed issues, etc. The goal of this project is to investigate the correlation between shared development and productivity on GitHub and find the critical features that influence issue closure latency. \footnote{https://github.com/Sairamvinay/Github-Drilling-Shared-vs-Solo} \subsection{Research Questions} Research and practice of software development are performed under various assumptions, their relationship with hypotheses, and discovered facts for validation. Based on the extensive empirical studies we have investigated, we have constructed several hypotheses for this research: \subsubsection*{Research Question I:} In general, we know that more people working on development can improve productivity. Hence, we want to discover whether in open source software development: In an OSS medium, we can observe in general that more people working on development tends to improve productivity (by solving the proposed problems faster), but will this trend persist whenever there are more people working on the same project. We seek to answer whether for any project: With a larger software development team (more developers working on the same project), is there effectively a lower issue closure latency in open source projects? \subsubsection*{Research Question II:} In terms of one project’s productivity, would the presence of more shared developers reduce the issue closure latency? For the research purpose of this project, we consider shared developers as those who have contributed to multiple projects other than the current working project during the current project’s age time frame. \subsubsection*{Research Question III:} We analyze whether the project’s average latency of issue closure time reduces when the number of developers communicates knowledge across projects in terms of sharing knowledge? We consider this since we firmly believe that working on multiple projects would facilitate the transfer of knowledge across developers and improve the productivity of a software development team. \subsubsection*{Hypothesis I:} An increase in the number of developers working on the same project (team size) can lead to lower latency in resolving issues \subsubsection*{Hypothesis II:} An increase in the number of shared developers indicates more communication and collaboration between them, which leads to lower latency in resolving issues \subsubsection*{Hypothesis III:} The project’s average latency of issue closure time can be reduced due to having developers that communicate knowledge across projects in terms of sharing knowledge. Based on the research questions, we attempt to validate our hypothesis on the role of communication during software development. \section{Literature Review} In this research project, our team has decided to investigate the role of communication among shared developers during open-source software (OSS) development and how different team sizes of software developers can affect the overall productivity of the software development. \\ In the beginning, our focus is to evaluate the OSS development process by modeling and evaluating issue closure latencies against various features pertaining to the project and cross-development of contributors. For example, in the paper \cite{krishnan2000empirical}, the author examines different factors that can positively affect quality and productivity, such as the personnel capability of developers, product size, software process factors, and usage of tools. The author specifies the quality of the product as a function of product size, personnel capability, usage of tools, process factors, and proportion of investment in front-end development. The quality measures the number of unique problems reported by customers that are being solved. The author uses nonlinear data analysis and Ordinary Least Squares for the estimation procedures which is the first model method that we intend to use. The paper provides several insights for managers of commercial software products. The results of the quality equation identify several drivers of product quality. For example, the authors find that size of the software product personnel capability of project team members significantly affects quality. \\ Furthermore, we want to explore the effectiveness of having the software developer that is involved in many development projects on the overall productivity of those projects. There is limited theoretical work that exists in this field pertaining to the OSS research community. From previous research \cite{vasilescu2016sky}, multitasking has proved highly beneficial to productivity across GitHub projects through load balancing, more efficient work practices, learning, and cross-fertilization. Through our project, we have chosen to investigate how multitasking by shared developers across projects can facilitate communication of knowledge resulting in a lower latency in issue closure but the paper provides inspiration to using shared developers as the feature. In paper \cite{box1964analysis}, the authors talk about the importance of multi-discussing where developers can contribute their comments on multiple issues and switch their discussions between various issues they are handling at any given point in time. The paper claims that the work efficiency of developers increases on a per-issue basis, as multiple issues are discussed simultaneously by these developers. However, they also argue that multi-discussing may involve developers re-allocating their time and focus, which can cause a hindrance to the efficiency involved in issue closure. The datasets they have used (obtained using GHTorrent) are relatively small and their study indicates that there is more research needed in this area. We also observe that \cite{jarczyk2018surgical} the researchers emphasized the influence of having multiple developers working on a project and its effect on the overall quality of software development. \\ Furthermore, we wants to see how does the communication factor affects productivity. The researchers illustrated that the integration of information technology could increase the developers’ productivity by communicating and collaborating much faster. Since communication among the developers is essential to increase productivity, it is strictly essential to many industries that care about software quality which inspires our curiosity on the communication factor. In \cite{jarczyk2018surgical}, the researchers have used GHTorrent for their data collection and utilized survival analysis to understand the factors that affect issue closure rates in OSS projects. However, the researchers did not consider how important communication was. Hence, although it provides a good overview of the research direction, we decided not to do survival analysis but instead use polynomial regression because there are many parameters to consider when determining the productivity of developers in OSS projects. \\ Eventually, we are firmly believed that team sizes has a positive correlation with productivity. For example, in the paper \cite{tohidi2006productivity}, has explored the effectiveness of team sizes in projects which address our research question 1. As many projects may depend primarily on team members and how much they contribute to the projects, the researchers emphasized how the organizational structure on team sizes may be affected by communication and how tasks can be improved and promote the efficiency of organizations. However, the researchers did not consider the performance metrics regarding how many issues were closed after successfully communicating with team members. They also did not consider how one developer with more experience in a higher hierarchy may affect the overall productivity of the other developers in the team. The researchers also asserted that a well-developed organization may still have defects in their products and delay communication among the developers. With the advent of DSCM’s (distributed source code management systems) like GitHub, the ease with which developers can switch between projects has dramatically increased. Developers can find themselves working on different projects due to dependencies between projects or projects being in similar domains, which becomes important to identify and evaluate the productivity of shared developers. By handling multiple projects, developers can be more efficient in resolving issues and can also pass on knowledge/communicate across projects they have been involved with. Specifically, we want to explore the effectiveness of having how the one software developer that is involved that involved in many development projects can influence the overall productivity of those projects.\\ In comparison to previous works, we can observe some research regarding cross-project developments \cite{vasilescu2016sky}\cite{jarczyk2018surgical} and product quality. However, those research did not propose analyzing latency of productivity among shared developers. Similarly, some works have analyzed the team size \cite{vasilescu2016sky}\cite{krishnan2000empirical} and other important metrics such as organizational structures \cite{tohidi2006productivity} to determine the productivity of developers. However, to the best of our knowledge, there is very little work done with analyzing the cross-development factor in GitHub and several other parameters such as team size and the number of issues, which are being used for predicting the issue closure latency. There have been separate works in predicting and analyzing the issue closure latency, but none of those works have investigated the cross-development factor. Similarly, communication parameters have been analyzed, but there is very minimal work using the same variable we defined for cross-development. In addition, most of the works did not consider many analysis methodologies that we considered when conducting this research; for instance, we could not observe many papers that used polynomial regression for analyzing regression of productivity. \\ Some works have analyzed the team size \cite{vasilescu2016sky}\cite{krishnan2000empirical} and other important metrics such as organizational structures \cite{tohidi2006productivity} to determine the productivity of developers. However, to the best of our knowledge, there is very little work done with analyzing the cross-development factor in GitHub and several other parameters such as team size and the number of issues, which are being used for predicting the issue closure latency. There have been separate works in predicting and analyzing the issue closure latency, but none of those works have investigated the cross-development factor. Our work bridges the gap between predicting latency of issues using communication-based metrics such as cross-development factors as defined by our team in addition to the number of collaborators and other key metrics. \\ \section{Methodology} For our project, we chose quantitative analysis since we were primarily analyzing data with numeric values and we wanted to derive conclusions from our data by statistical modeling techniques. In comparison to our progress report, we improved the number of samples by collecting more data by crawling the GitHub-based APIs. For the inputs, we decided to use the project size, the team size (number of contributors), total closed issues, the average number of cross-development repositories by a contributor for each repository, the average comments, project age, and the number of forks as the independent variables(features). We plan to fit a simple regression model that validates our hypothesis based on the learned regression coefficients and the significance values tests for identifying the most critical features for predicting the latency of issues. We use statistical tests learned from the course, particularly the P-value significance for these analyses. We report the standard metrics used for regression models, such as the R squared metric. For solving the regression models, we only used the Ordinary Least Squares (OLS) method since it was the most widely used regression solution method. We leveraged more tools such as the inverse of an error function (erfinv) for transforming some of our input variables into a Gaussian Distribution. We will also explain some of the challenges that we faced and our choices for feature transforming techniques. \\ Our design for modeling was straightforward just like how regular statistical models are trained. We collect our data from Github API, pre-process using outlier detection techniques and then transform some features for changing their raw distribution into a Gaussian-like distribution. Finally, we scaled our data using centering techniques and then predicted using a polynomial regression model. \subsection{Data} \subsubsection{Data Extraction: Features and Response Variables} We have decided to investigate public repositories that have been created during the last five years (2016 - 2021) from GitHub. The GitHub Search API provides the ability to gather certain information about each repository, such as repository creation time, the number of issues within a repository, whether the issues are closed or open, the creation date, the issue closure date (if closed), the project size, and the number of comments per issue. Since the GitHub API imposed a rate limit while extraction, each person within our team was delegated to gather one year’s worth of public repositories in terms of their creation date. To make sure we don’t miss any crucial information, we crawl the API for the creation date of a project each day of the year, on a monthly basis. Results from this search are returned sorted based on “best matches/most relevant” as defined by the API. GitHub describes their “best matches/most relevant” as “Multiple factors which are combined to boost the most relevant to the top of the result list.”\cite{githubdocs}\\ We then used the name of Repos and users in conjunction with GitHub issues Search API to gather the issue closure information, the contributors working on a repository, the commit logs associated with the repository, and each issue's open date and closure date. Each of these unique repositories was considered as individual projects for this project’s scope. With this data, we can compute the average time to close an issue easily by averaging the lifetime of all closed issues of a repository. In order to determine the cross-development factor, we leverage a metric of measuring the average number of projects other than the current project being worked on by each of the top ten contributors during the time frame of this current project. The project’s top 10 contributors (based on their increased involvement in this project) were found and then the number of repositories that have been created after this project in a chronological sense by each of these ten contributors were accumulated and then finally averaged across all the ten contributors. \\ We gathered GitHub’s top 50 projects each day as returned by the search API, which allowed us to collect 12,800 samples initially. We filtered our search then to identify those repositories with at least one closed issue and obtained around 10381 samples before processing. \subsubsection{Data Preprocessing and Analysis} There are many outliers in our data and all our features did not possess a perfect Gaussian distribution but the average number of comments. For the outlier detection, we performed a simple outlier removal technique entirely based on the percentile values of the features. We calculated the 97.5th percentile of each of the features we collected and removed values larger than the 97.5th percentile by using these as a cutoff to remove the outlier samples. We also calculated the 2.5th percentile of our entire dataset which was leveraged as a cutoff for removing those samples which have feature values that are lesser than its 2.5th percentile. After outlier detection, we had a final dataset of 6757 samples. \\ For the purpose of analyzing parameters and displaying the analyzed results using Gaussian distribution, we intended to transform our features into a normal distribution. For our transformations, we leveraged the square root, logarithmic, and cubic root for each corresponding parameter, and we did not use more than one transformation for converting the features into normal Gaussian-like distributions. We did a logarithmic transformation for the project size (in KB) and the number of forks. Similarly, we applied a square root method for transforming the cross-development factor and a cube root method for transforming the closed issues. \\ For the age and team size variables of a project, we decided to choose a slightly different method from regular transformation methods. We chose to apply the inverse of an error function (erfinv) which was widely believed to be particularly useful in statistical applications for converting uniform random numbers into Normal random numbers. For the age variable (measured in days), we scaled into a [0,1] range and then applied an erfinv transformation to obtain the Gaussian Distribution. Similarly, we applied the same technique for the team size feature which however did not exactly transform into a Gaussian distribution because of its more discrete set of values. \\ Finally, after all our transformations, we chose to apply a simple centering technique that ensured that our variable distributions had a mean of 0 and standard deviation close to 1. It was performed by subtracting the mean of the variable from the variable values and then dividing by the standard deviation. From the frequency distribution in histograms, there were six parameters (besides team size) out of seven parameters that showed a widely spread out Gaussian distribution, which was a promising result for prediction in polynomial regression indicating that the transformation applied were powerful in obtaining Gaussian distributions. Refer to Figure [\ref{fig:histo}].\\ In addition to the features being transformed, we chose to model the latency after ensuring it possessed a normal Gaussian distribution, as referred to Figure [\ref{fig:Latency}]. We simply applied a log transformation on the average transformation and that was our output variable for predicting. \begin{figure}[!ht] \centering \includegraphics[width=\linewidth]{ECS_260_2.png} \caption{Output latency - Before and after Log Transformation} \label{fig:Latency} \end{figure} The graph in the appendix Figure [\ref{fig:scatter}] shows a scatter matrix among all variables collected. Although we can observe specific quick trends, more data need to be collected to verify this in a very general way. We can observe that with respect to the average latency, we can observe a slight downward trend with respect to the average number of repositories outside the current project and similarly another slight downward trend with respect to the number of contributors. Another observation was that our data displayed that there was no a visible linear relationship between latency and any of the input features and therefore we opted to work on a polynomial regression algorithm. \subsection*{Methodologies Used:} \subsubsection*{Ordinary Least Squares} The ordinary least squares method is commonly used in statistics to determine the unknown parameters of a regression model. It calculates the sum of the squares of the residuals from the sample data-point values indicated by the polynomial function. However, as we worked on the OLS method, we observed that from our progress reports, transforming variables into a Gaussian distribution (which we incorporated recently) improved the modeling results. Having Gaussian distribution allowed us to analyze the dataset in more detail and it would be better for us to predict the latency of the developers, but we could not see any distribution and could not proceed with the analysis of the data. We did not consider adopting OLS for this research even though the OLS would be great for linear regression for observing linear relationships between input and output variables. \subsubsection*{Polynomial Regression} A form of statistical analysis that uses the relationship between the dependent variable y and the independent variable x by fitting a polynomial function is called polynomial regression. It is a simple method that considers a simple polynomial function for modeling a response variable by solving the unknown parameters (simply coefficients) of the variables via optimization techniques. \\ We chose this method since it had a perfect balance between a simplistic method and non-linear behavior across the input and output variables. We chose this method over more complex methods such as Poisson regression and negative binomial regression since our data had a small number of samples and we still wanted to capture the non-linear relationships across the input and output variables. Hence we chose to proceed to model with these models for the scope of this project. We modeled our data via polynomial regression to explore the non-linear behavior of the features with respect to the response variable. Another advantage of using these methods allowed us to obtain more variables (although they were powered expressions of the features) for modeling. Hence we moved on to leverage polynomial regression to consider many dependent variables that may result in higher accuracy of predicting the response variable latency. Most of these analyses were conducted in Python (which includes crawling the API, pre-processing, and modeling our data).\\ \begin{figure}[!ht] \centering \includegraphics[scale=0.7]{Rsquare.png} \caption{$R^2$-values} \label{fig:Rsquare} \end{figure} We noticed that from the scatter matrix Figure [\ref{fig:scatter}] most of the features bear a nonlinear relationship with the latency of closing issues, so we modeled using polynomial regression. We picked the degree of polynomial regression based on the performance of regression models of various degrees from 1 to 20 [\ref{fig:Rsquare}]. As we observed from the plot, we found that the polynomial regression models do not improve after a degree of 5 and hence we chose to stick with a small degree which also adds more non-linear behavior to our model. \section{Results} We present the regression summary results we have obtained after fitting a polynomial regression model of degree 5 on the data features, see Figure [\ref{fig:OLS}]. \begin{figure}[!ht] \centering \includegraphics[width=1\linewidth]{OLS_Regression_results.png} \caption{OLS Polynomial Regression results} \label{fig:OLS} \end{figure} The results show that based on the p-value significance (variables that have a significance $<$ 0.05)) indicates that the age of projects, contributors, cross-development factor (the number of repositories created outside a current project during its timeline), and total closed issues of the second degree are critical predictors for the response variable (log of the average latency). We also find that for all the power raised for the features: forks, average comments, and forks are not very significant. The results confirm our hypotheses and in fact, we are able to validate our questions by confirming with the p-values of the features. Clearly, we can observe that the cross-development factor has a negative coefficient with respect to the output variable and hence it shows that an increase in the cross-development would decrease the average latency of closing issues. Similarly, we hypothesized that team size is correctly a strong predictor for latency. The positive coefficient for team size is a deduction where the results disagree with our hypotheses that it would bear a negative correlation with the output variable (that a larger team size would reduce the latency of closing issues). \subsubsection*{RQ1:} Our results do not agree with our hypotheses of verifying whether a larger number of people within a team working on the same project during its lifetime would reduce the latency output variable. We strongly attribute this with the positive coefficient but, the variable of team size is definitely a strong predictor based on the p-value significance. We find that from our results that as a team size grows, we find an increase in the latency, which means it takes a longer time to close issues. We attribute the disagreement in the trend with what we observe and we hypothesize because we probably did not consider any other correlating factor (like weighting it based on the experience of each developer in the team) along with the team size which might have improved or shown a different trend. \subsubsection*{RQ2:} The presence of shared developers was not directly gauged in our project; however, we consider the involvement of both the variables: forks and the cross-development factor for analyzing the presence of shared developers. We mainly focus on these variables because they have a straight connection with shared development: forks represent the number of various versions working on the same project and cross-development represents the number of other different projects worked during the same time. The results reveal that the forks do not have a huge influence on the latency while the cross-development factor does bear a negative relationship. We came to a conclusion that shared developers working more on this project do influence the latency of closed issues on the basis of these two factors. The negative coefficients of both these variables suggest that they bear a negative relationship as we had proposed in our hypothesis. We conclude that our results agree with the RQ2 we proposed. \subsubsection*{RQ3:} There is a healthy agreement between the cross-development factor and the output variable of latency. We can observe that the cross-development factor indeed was a critical feature as a predictor for predicting latency and its coefficient was negative (-0.1093) which implied that an increase in this factor reduces the latency. This was in direct agreement with what we hypothesized and this research question was validated by our research results, which corresponds to the fact that cross-development between developers outside the current project is very helpful in resolving issues in open source software development because of possible increased sharing of knowledge across developers. \section{Discussion} \subsection*{Main Findings from Our Results} Our final project results demonstrate that we have found the best predictors of latency, which was considered as a measure of productivity. Amongst those best predictors, we deduce that the average number of created repositories outside the current project by each of the top ten contributors is a strong variable that negatively influences the latency. This leads to a conclusion that cross-development across developers beyond the current project leads to more sharing of knowledge that allows more productivity and hence the developers are able to solve the issue quicker than the regular cases without shared development. In conclusion, we have validated our overall aim that collaboration between developers beyond the current working project improves the latency and hence increases productivity. \\ \subsection*{Strengths and Limitations} We confirm that our project was successful in validating all our research questions and we were fairly successful in correctly stating and validating the relations in the form of our research questions. We had collected and modeled a simple dataset with a small set of features using polynomial regression. However, our results prove to be in good agreement with our hypotheses. While we have been successful in completing research on this topic, we wanted to explore more complex models such as Poisson and Negative Binomial with a larger dataset. Poisson distribution is a statistical procedure that shows the probability of a given number (events) of events happening in a fixed time interval and can use the results for estimating events of varying sizes (area or distance). We could have considered adopting the Poisson Distribution methodology to predict the number of days taken to resolve issues as a discrete variable. Also, we didn't apply Box-Cox Transformation in our features although it was one of the transformation methods of transforming non-normal dependent variables into a normal distribution. This was because it employed a complicated methodology and we didn't want to explore a very complicated function into our simplistic dataset. Similarly, we did not consider certain critical features such as the experience of developers, lines of code, and a number of edited files for modeling. Also, we considered a plain domain and did not consider our work within a particular domain: such as pertaining to only application development or entirely based on back-end development, etc.\\ \section{Conclusion} We have seen several aspects of interpreting the relationship between the productivity of the developers in the open-source software and the collaboration across various developers., From our quantitative analysis, based on the data we have collected from the open-source software, GitHub, there are a few parameters that influence the latency of closing issues within software development. We have used certain statistical methodologies to analyze the data we collected from the scripts we have written and we have shown how to model the data we collected for a better understanding of the dataset and for better prediction of the latency of software development among the shared developers. Most importantly we have utilized simple but effective analysis methodologies such as Polynomial regression of a small degree 5 to predict the latency and we have observed that our method has provided many unique results, and have shown how to predict and measure the quality of open-source software. For further research, we can observe more on polynomial regression results and measure the actual results in a specific time period of the development and may apply other statistical techniques for a better understanding of productivity. \\ \section{Team Membership and Attestation of Work} Seongwoo Choi, Terry Guan, Sutej Kulkarni, Jason (Jinxiao) Song, and Sairamvinay Vijayaraghavan agree to participate and work on this project with the understanding of the project. \newpage \bibliographystyle{plain}
{'timestamp': '2022-03-30T02:31:00', 'yymm': '2203', 'arxiv_id': '2203.15459', 'language': 'en', 'url': 'https://arxiv.org/abs/2203.15459'}
arxiv
\section{Introduction} In recent years, many computer vision (CV) researchers make efforts to design CV-oriented vision Transformer to surpass the performance of the convolutional neural networks (CNNs). Due to a high capability in modeling the long-range dependencies, vision Transformer achieves prominent results in diversified vision tasks, such as image classification \cite{ViT,Deit,TNT,Swin,Twins,CSWin}, semantic segmentation \cite{Segformer,zheng2021rethinking,wang2021max}, object detection \cite{DETR,zhu2020deformable,dai2021up} and etc. However, the powerful performance usually comes at a cost of heavy computational complexity. \begin{figure} \centering \includegraphics[height=4cm]{throughput_latency} \caption{Comparison of throughput and latency on ImageNet-1K classification. The throughput and the latency are tested based on the PyTorch framework with a V100 GPU and TensorRT framework with a T4 GPU, respectively. } \label{fig:throughput_latency} \end{figure} Primordially, ViT \cite{ViT} firstly introduces Transformer to the image recognition tasks. It splits the whole image into patches and feeds each patch as a token into Transformer. However, the patch-based Transformer is hard to deploy due to the computationally inefficient full-attention mechanism. To relieve this problem, Swin \cite{Swin} proposes the window-based self-attention to limit the computation of self-attention in non-overlapping sub-windows. Obviously, the window-based self-attention helps to reduce the complexity to a great extent, but the shifted operator for building connection among the windows brings difficulty for ONNX or TensorRT deployment. Twins \cite{Twins} takes advantage of the window-based self-attention and the spatial reduction attention from PVT \cite{PVT_v1} and proposes the spatially separable self-attention. Although Twins is deployment-friendly and achieves outstanding performance, its computational complexity is hardly reduced. CSWin \cite{CSWin} shows state-of-the-art performance via the novel cross-shaped window self-attention, but its throughput is low. Albeit, with varying degrees of progress in these famous vision Transformers, most of its recent successes are accompanied with huge resource demands. To overcome the aforementioned issues, we propose an efficient Transformer backbone, called {\bf Separable Vision Transformer (SepViT)}, which captures both local and global dependencies in a sequential order. A key design element of SepViT is its {\bf depthwise separable self-attention} module, as shown in Fig. \ref{fig:SepViT}. Inspired by the depthwise separable convolution in MobileNets \cite{MobileNet_v1,MobileNet_v2,Mobilenet_v3}, we re-design the self-attention module and propose the depthwise separable self-attention, which consists of a depthwise self-attention and a pointwise self-attention that can correspond to depthwise and pointwise convolution in MobileNets, respectively. The depthwise self-attention is used to capture local feature within each window while the pointwise self-attention is for building connections among windows that notably improve the expressive power. Moreover, to get the global representation of a local window, we develop a novel {\bf window token embedding}, which can model the attention relationship among windows with negligible cost. Furthermore, we also extend the idea of grouped convolution from AlexNet \cite{AlexNet} to our depthwise separable self-attention and present the {\bf grouped self-attention} to further improve the performance. To demonstrate the effectiveness of SepViT, we conduct a series of experiments on some typical vision tasks, including ImageNet-1K \cite{ImageNet-1K} classification, ADE20K \cite{ADE20K} semantic segmentation and COCO \cite{COCO} object detection and instance segmentation. The experimental results show that SepViT can achieve a better trade-off between performance and latency than other competitive vision Transformers \cite{PVT_v1,Swin,Twins,CSWin}. As shown in Fig. \ref{fig:throughput_latency}, SepViT achieves better accuracy at the same latency constraint and costs less inference time than the methods with the same accuracy. Furthermore, SepViT can be expediently applied and deployed since it only contains some universal operators (e.g., transpose and matrix multiplication). To sum up, the contributions of our work can be summarized as follows: \begin{enumerate} \item We propose the Separable Vision Transformer (SepViT) with a depthwise separable self-attention. It can achieve local information communication within the windows and global information exchange among the windows in a single Transformer block. \item We propose the window token embedding to learn a global feature representation of each window, which helps SepViT to model the attention relationship among windows with negligible computational cost. \item We extend depthwise separable self-attention to grouped self-attention in SepViT. It can capture more contextual concepts across multiple windows and achieve better performance. \end{enumerate} \section{Related work} \subsection{Vision Transformer} In the computer vision field, CNN has been dominant for decades due to its advantages of the spatial inductive biases. Later, in order to model the global dependencies of pixels, ViT \cite{ViT} introduces Transformer to computer vision for the first time and achieves an excellent performance on image classification task. In quick succession, a series of vision Transformers have been produced based on ViT. DeiT \cite{Deit} introduces the knowledge distillation scheme and proposes the data-efficient image Transformer. T2T-ViT \cite{T2T} progressively structurizes the image to tokens by recursively aggregating neighboring tokens into one token. TNT \cite{TNT} proposes the inner and outer Transformers to model the relationship of the word embeddings and the sentence embeddings, respectively. CPVT \cite{CPVT} produces the conditional position encoding which is conditioned on the local neighborhood of input tokens and is adaptable to arbitrary input sizes. Recently, PVT \cite{PVT_v1} and Swin \cite{Swin} synchronously propose the hierarchical architecture which is friendly for the dense prediction tasks, such as object detection, semantic and instance segmentation. Meanwhile, Swin \cite{Swin} as a pioneer proposes the window-based self-attention to compute attention within local windows. Soon after, Twins \cite{Twins} and CSWin \cite{CSWin} sequentially propose the spatial separable self-attention and cross-shaped window self-attention based on the hierarchical architecture. On the other hand, some researchers incorporate the spatial inductive biases of CNNs into Transformer. CoaT \cite{CoaT}, CVT \cite{CvT} and LeViT \cite{LeViT} introduce the convolutions before or after self-attentions and obtain well-pleasing results. Regarding to the design of lightweight Transformer, Mobile-Former \cite{Mobile-Former} and MobileViT \cite{MobileViT} combine Transformer blocks with the inverted bottleneck blocks in MobileNet-V2 \cite{MobileNet_v2} in series and parallel. Besides, another direction of research \cite{so2019evolved,Autoformer,Glit,Bossnas} is to automatically search the structure details of Transformer with neural architecture search \cite{zoph2016neural,Bignas} technology. \subsection{Lightweight Convolutions} Many lightweight and mobile-friendly convolutions are proposed for mobile vision tasks. Of these, grouped convolution is the first to be proposed by AlexNet \cite{AlexNet}, which groups the feature maps and conducts the distributed training. Then the representative work of mobile-friendly convolution must be the MobileNets \cite{MobileNet_v1,MobileNet_v2,Mobilenet_v3} with depthwise separable convolution. The depthwise separable convolution contains a depthwise convolution for spatial information communication and a pointwise convolution for information exchange across the channels. As time goes on, plenty of variants based on the aforementioned works are developed, such as \cite{ShuffleNet,ShuffleNet_v2,EfficientNet,GhostNet}. In our work, we adapt the ideology of depthwise separable convolution to Transformer, which aims to reduce the Transformer's computational complexity without the sacrifice of performance. \section{Methodology: SepViT} In this section, we first illustrate the design overview for SepViT, and then discuss some key modules within the SepViT block. Finally, we provide the architecture specifications and variants with different FLOPs. \subsection{Overview} As illustrated in Fig. \ref{fig:SepViT}, SepViT follows the widely-used hierarchical architecture \cite{PVT_v1,Swin,Twins,CSWin} and the window-based self-attention \cite{Swin}. Besides, SepViT also employs conditional position encoding (CPE) from \cite{CPVT,Twins}. For each stage, there is an overlapping patch merging layer for feature map downsampling followed by a series of SepViT blocks. The spatial resolution will be progressively reduced by 32$\times$ with either stride 4 or 2, and the channel dimension will be doubled stage by stage. It is worth noting that both local contextual concepts and global abstraction can be captured in a single SepViT block, while other works \cite{Swin,Twins} should employ two successive blocks to accomplish this local-global modeling. \begin{figure}[th] \centering \includegraphics[width=12cm]{SepViT} \caption{Separable Vision Transformer (SepViT). The top row is the overall hierarchical architecture of SepViT. The bottom row is the SepViT block and the detailed visualization of our depthwise separable self-attention and the window token embedding scheme.} \label{fig:SepViT} \end{figure} In the SepViT block, local information communication within each window is achieved by depthwise self-attention (DWA), and global information exchange among the windows is performed via pointwise self-attention (PWA). \subsection{Depthwise Separable Self-Attention} \subsubsection{Depthwise Self-Attention (DWA).} Similar to some pioneering works \cite{Swin,Twins}, SepViT is built on top of the window-based self-attention scheme. Firstly, we perform a window partition on the input feature map. Each window can be seen as an input channel of the feature map, while different windows contain diverse information. Different from previous works, we create a window token for each window, which serves as a global representation and is used to model the attention relationship in the following pointwise self-attention module. Then, a depthwise self-attention (DWA) is performed on all the pixel tokens within each window as well as its corresponding window token. This window-wise operation is quite similar to a depthwise convolution layer in MobileNets, aiming to fuse the spatial information within each channel. The implementation of DWA can be summarized as follows: \begin{equation} \label{eqution:DWA} \text{DWA}(z)= \text{Attention}(z \cdot W_Q, z \cdot W_K, z \cdot W_V) \; \end{equation} where $z$ is the feature tokens, consisted of the pixel and window tokens. $W_Q$, $W_K$, and $W_V$ denote three Linear layers for query, key and value computation in a regular self-attention. Attention means a standard self-attention operator that works on local windows. \subsubsection{Window Token Embedding.} A straightforward solution to model the attention relationship among windows is to employ all pixel tokens. However, it will bring huge computational costs and make the whole model very complicated. To better establish the attention relationship among windows, we present a window token embedding scheme, which leverages a single token to encapsulate the core information for each sub-window. This window token can be initialized either as a fixed zero vector or a learnable vector with the initialization of zero. While passing through DWA, there is an informational interaction between the window token and pixel tokens in each window. Thus the window token can learn a global representation of this window. Thanks to the effective window token, we can model the attention relationship among windows with negligible computational cost. \subsubsection{Pointwise Self-Attention (PWA).} The famous pointwise convolution in MobileNets is utilized to fuse the information from different channels. In our work, we imitate pointwise convolution to develop the pointwise self-attention (PWA) module to establish connections among windows. PWA is also mainly used to fuse the information across windows and obtain a final representation of the input feature map. More specifically, we extract the feature maps and window tokens from the output of DWA. Then, window tokens are used to model the attention relationship among windows and generate the attention map after a LayerNormalization (LN) layer and a Gelu activation function. Meanwhile, we directly treat the feature maps as the value branch of PWA without any other extra operation. With the attention map and the feature maps which are in the form of windows, we perform an attention computation among the windows for global information exchange. Formally, the implementation of PWA can be depicted as follows: \begin{equation} \text{PWA}(z, wt) = \text{Attention}(\text{Gelu}(\text{LN}(wt)) \cdot W_Q, \text{Gelu}(\text{LN}(wt)) \cdot W_K, z) \; \end{equation} where $wt$ denotes the window token. Here, Attention is a standard self-attention operator but works on all of the windows $z$. \subsubsection{Complexity Analysis.} \label{sec:complexity} Given an input feature with size $H \times W \times C$, the computational complexity of the multi-head self-attention (MSA) is $4HWC^2 + 2H^2W^2C$ in the global Transformer block of ViT \cite{ViT}. The complexity of the MSA in a window-based Transformer with window size $M \times M$ (Usually, $M$ is a common factor of $H$ and $W$, so the number of the windows is $N=\frac{HW}{M^2}$) can be decreased to $4HWC^2 + 2M^2HWC$ in Swin \cite{Swin}. As for the depthwise separable self-attention in SepViT, the complexity contains two parts, DWA and PWA. {\bf DWA.} Building on top of a window-based self-attention, DWA shares a similar computational cost to it. Additionally, the introduction of window tokens will cause an extra cost, but it is negligible compared to the overall cost of DWA. The complexity of DWA can be calculated as follows: \begin{equation} \varOmega(\text{DWA}) = 3HWC^2 + 3NC^2 + 2N(M^2+1)^2C \; \end{equation} where $3NC^2$ is the extra cost of encoding window tokens in Linear layers. $2N(M^2+1)^2C$ indicates the matrix multiplications involved in the self-attention for $N$ windows, where $M^2+1$ represents the $M^2$ pixel tokens in a window and its corresponding window token. Thanks to that the number of sub-windows $N$ is usually a small value, the extra costs caused by window tokens can be ignored. {\bf PWA.} Since the window token summarizes the global information of a local window, the proposed PWA helps to efficiently perform information exchange among windows in a window level instead of pixel level. Concretely, the complexity of PWA is given as follows: \begin{equation} \varOmega(\text{PWA}) = HWC^2 + 2NC^2 + N^2C + NHWC \; \end{equation} where $2NC^2$ represents the little cost of computing the query and key with $N$ window tokens, while the value branch is zero-cost. $N^2C$ indicates the computation of generating attention map with $N$ window tokens in a window level, which saves computational cost for PWA to a great extent. Finally, $NHWC$ indicates the matrix multiplication between the attention map and the feature maps. \subsection{Grouped Self-Attention} Motivated by the excellent performance of grouped convolution in visual recognition \cite{AlexNet}, we make an extension of our depthwise separable self-attention with the ideology of group, and propose the grouped self-attention. As shown in Fig. \ref{fig:grouped_attn}, we splice several neighboring sub-windows to form a larger window, which is similar to dividing the windows into groups and conducting a depthwise self-attention communication inside a group of windows. In this way, the grouped self-attention can capture long-range visual dependencies of multiple windows. In terms of computational cost and performance gains, the grouped self-attention has a certain extra cost compared with the depthwise separable self-attention but results in a better performance. Ultimately, we apply the block with grouped self-attention to SepViT and run it alternately with the depthwise separable self-attention block in the late stages of the network. \begin{figure} \centering\ \includegraphics[width=10cm]{grouped_attn} \caption{A macro view of the similarities and differences between the depthwise separable self-attention and the grouped self-attention.} \label{fig:grouped_attn} \end{figure} \subsection{SepViT Block} To summarize, our SepViT block can be formulated as follows: \begin{align} \label{eqution:SepViT} & \tilde{z}^l = \text{Concat}(z^{l-1}, wt) \; \\ & \ddot{z}^l = \text{DWA}(\text{LN}(\tilde{z}^l)) \; \\ & \dot{z}^l, \dot{wt} = \text{Slice}(\ddot{z}^l) \; \\ & \hat{z}^l = \text{PWA}(\dot{z}^l, \dot{wt}) + z^{l-1} \; \\ & z^l = \text{MLP}(\text{LN}(\hat{z}^l)) + \hat{z}^l \; \end{align} where $\ddot{z}^l$, $\hat{z}^l$ and $z^{l}$ denote the outputs of the DWA, PWA and SepViT block $l$, respectively. $\dot{z}^l$ and $\dot{wt}$ are feature maps and the learned window tokens. Concat represents the concatenation operation while Slice represents the slice operation. {\bf Comparison of Complexity.} We compare the complexity of our proposed SepViT block with two other SOTA blocks (Swin \cite{Swin}, Twins \cite{Twins}). As we stated before, the information interaction within and among windows is completed in a single SepViT block, while Swin \cite{Swin} and Twins \cite{Twins} require two successive blocks. As shown in Fig. \ref{fig:complexity}, we can observe that the SepViT block only costs about half the MACs of its competitors in each stage of the network. The reason lies in two aspects: i) SepViT block is more lightweight; ii) SepViT block removes many redundant layers, e.g., there is only one MLP layer and two LN layers in a single SepViT block while there are double MLP and LN layers in two successive Swin or Twins blocks. \begin{figure} \centering \includegraphics[height=4cm]{flops} \caption{Complexity comparison of an information interaction within and among windows in a single SepViT block with those two-block pattern works in each stage.} \label{fig:complexity} \end{figure} \begin{table} \centering \caption{Detailed configurations of SepViT variants in different stages.} \label{tab:configs} \resizebox{0.9\textwidth}{!}{ \begin{tabular}{@{}c|c|c|c|c@{}} \toprule Configuration & SepViT-Lite & SepViT-T & SepViT-S & SepViT-B \\ \midrule Blocks & [1, 2, 6, 2] & [1, 2, 6, 2] & [1, 2, 14, 2] & [1, 2, 14, 2] \\ \midrule Channels & [32, 64, 128, 256] & [96, 192, 384, 768] & [96, 192, 384, 768] & [128, 256, 512, 1024] \\ \midrule Heads & [1, 2, 4, 8] & [3, 6, 12, 24] & [3, 6, 12, 24] & [4, 8 ,16, 32] \\ \midrule Block Type & \multicolumn{4}{c}{[DSSA, DSSA\&GSA, DSSA\&GSA, DSSA]} \\ \bottomrule \end{tabular}} \end{table} \subsection{Architecture Configurations} To provide a fair comparison with other vision Transformers, we propose the SepViT-T (Tiny), SepViT-S (Small) and SepViT-B (Base) variants. Moreover, we also design the SepViT-Lite variant with a very light model size. The specific configurations of SepViT variants are shown in Table \ref{tab:configs}, the block depth of SepViT is smaller in some stages than the competitors since SepViT is more efficient. DSSA and GSA denote the blocks with depthwise separable self-attention and grouped self-attention, respectively. Additionally, the expansion ratio of each MLP layer is set as 4, the window sizes are 7$\times$7 and 14$\times$14 for DSSA and GSA in all SepViT variants. \section{Experimental Results} \subsection{ImageNet-1K Classification} \subsubsection{Settings.} We carry out the image classification experiment on the ImageNet-1K \cite{ImageNet-1K}, which contains about 1.28M training images and 50K validation images from 1K categories. For a fair comparison, we follow the training settings of the recent vision Transformer \cite{Twins}. Concretely, all of the SepViT variants are trained for 300 epochs on 8 V100 GPUs with a total batch size of 1024. The resolution of the input image is resized to 224 $\times$ 224. We adopt the AdamW \cite{AdamW} as the optimizer with weight decay 0.1 for SepViT-B and 0.05 for SepViT-S/T. The learning rate is gradually decayed based on the cosine strategy with the initialization of 0.001. We use a linear warm-up strategy with 20 epochs for SepViT-B and 5 epochs for SepViT-S/T. Besides, we have also employed the increasing stochastic depth augmentation \cite{Stochasticdepth} with the maximum drop-path rate of 0.2, 0.3, 0.5 for our SepViT-T/S/B models. \begin{table}[ht] \centering \caption{Comparison of different state-of-the-art methods on ImageNet-1K classification. Throughput and latency are tested based on the PyTorch framework with a V100 GPU (batchsize=192) and TensorRT framework with a T4 GPU (batchsize=8).} \label{tab:ImageNet_1K} \scalebox{0.7}{ \begin{tabular}{c|cccc|c} \toprule \multirow{2}{*}{Method} & Param & FLOPs & Throughput & Latency & Top-1 Acc \\ & (M) & (G) & (Images/s) & (ms) & (\%) \\ \midrule \multicolumn{6}{c}{ConvNet} \\ \midrule RegNetY-4G\cite{RegNet} & 21.0 & 4.0 & 1064 & - & 80.0 \\ RegNetY-8G\cite{RegNet} & 39.0 & 8.0 & 548 & - & 81.7 \\ RegNetY-16G\cite{RegNet} & 84.0 & 16.0 & 305 & - & 82.9 \\ \midrule \multicolumn{6}{c}{Transformer} \\ \midrule DeiT-Small/16\cite{Deit} & 22.0 & 4.6 & 406 & - & 79.9 \\ T2T-ViT-14\cite{T2T} & 22.0 & 5.2 & - & - & 81.5 \\ TNT-S\cite{TNT} & 23.8 & 5.2 & - & - & 81.3 \\ CoaT-Lite-Small\cite{CoaT} & 20.0 & 4.0 & - & - & 81.9 \\ CvT-13\cite{CvT} & 20.0 & 4.5 & - & - & 81.6 \\ PVT-Small\cite{PVT_v1} & 24.5 & 3.8 & 794 & 20.7 & 79.8 \\ Swin-T\cite{Swin} & 29.0 & 4.5 & 704 & - & 81.3 \\ Twins-PCPVT-S\cite{Twins} & 24.1 & 3.8 & 778 & 20.2 & 81.7 \\ Twins-SVT-S\cite{Twins} & 24.0 & 2.9 & 979 & 18.8 & 81.7 \\ CSWin-T\cite{CSWin} & 23.0 & 4.3 & 627 & 30.2 & 82.7 \\ PVT-v2-B2\cite{PVT_v2} & 25.4 & 4.0 & 664 & 37.8 & 82.0 \\ {\textbf{SepViT-T}} & 31.2 & 4.5 & 738 & 23.7 & 82.5 \\ \midrule T2T-ViT-19\cite{T2T} & 39.2 & 8.9 & - & - & 81.9 \\ CoaT-Lite-Medium\cite{CoaT} & 45.0 & 9.8 & - & - & 83.6 \\ CvT-21\cite{CvT} & 32.0 & 7.1 & - & - & 82.5 \\ PVT-Medium\cite{PVT_v1} & 44.2 & 6.7 & 511 & 30.0 & 81.2 \\ Swin-S\cite{Swin} & 50.0 & 8.7 & 412 & - & 83.0 \\ Twins-PCPVT-B\cite{Twins} & 43.8 & 6.7 & 502 & 29.1 & 82.7 \\ Twins-SVT-B\cite{Twins} & 56.0 & 8.6 & 433 & 38.9 & 83.2 \\ CSWin-S\cite{CSWin} & 35.0 & 6.9 & 390 & 52.0 & 83.6 \\ PVT-v2-B3\cite{PVT_v2} & 45.2 & 6.9 & 443 & 54.1 & 83.2 \\ \textbf{SepViT-S} & 46.6 & 7.5 & 476 & 34.5 & 83.5 \\ \midrule Deit-Base/16\cite{Deit} & 86.6 & 17.6 & 273 & - & 81.8 \\ T2T-ViT-24\cite{T2T} & 64.1 & 14.1 & - & - & 82.3 \\ TNT-B\cite{TNT} & 66.0 & 14.1 & - & - & 82.8 \\ PVT-Large\cite{PVT_v1} & 61.4 & 9.8 & 357 & 43.2 & 81.7 \\ Swin-B\cite{Swin} & 88.0 & 15.4 & 255 & - & 83.3 \\ Twins-PCPVT-L\cite{Twins} & 60.9 & 9.8 & 339 & 39.8 & 83.1 \\ Twins-SVT-L\cite{Twins} & 99.2 & 15.1 & 271 & 48.3 & 83.7 \\ CSWin-B\cite{CSWin} & 78.0 & 15.0 & 216 & 76.1 & 84.2 \\ PVT-v2-B4\cite{PVT_v2} & 62.6 & 10.1 & 298 & 75.5 & 83.6 \\ PVT-v2-B5\cite{PVT_v2} & 82.0 & 11.8 & 285 & 77.5 & 83.8 \\ \textbf{SepViT-B} & 82.3 & 13.1 & 308 & 46.0 & 84.0 \\ \bottomrule \end{tabular} } \end{table} \subsubsection{Results.} As shown in Table \ref{tab:ImageNet_1K}, compared to the latest state-of-the-art methods, our SepViT achieves the best trade-off between accuracy and latency. To be more specific, our SepViT-B and SepViT-S achieve 84.0\% and 83.5\% top-1 accuracy, surpassing Swin by 0.7\% and 0.5\% with about 14\% fewer FLOPs. And for the tiny variant, our SepViT-T outperforms the Swin-T by 1.2\% with the same FLOPs of 4.5G. In terms of latency, compared to the recent methods (e.g., PVT-v2 \cite{PVT_v2} and CSWin \cite{CSWin}) with similar performance, both of our small and base models cost about 40\% less inference time. Moreover, our SepViT shows very promising performance by comparison with the CNNs counterparts. \subsection{ADE20K Semantic Segmentation} \begin{table} \centering \caption{Comparison of different backbones on ADE20K semantic segmentation task. FLOPs are measured with the input size of 512$\times$2048.} \label{tab:ADE20K} \resizebox{0.9\textwidth}{!}{ \begin{tabular}{c|ccc|ccc} \toprule \multirow{2.5}{*}{Backbone} & \multicolumn{3}{c|}{Semantic FPN 80k} & \multicolumn{3}{c}{UperNet 160k} \\ \cmidrule(l){2-7} & Param(M) & FLOPs(G) & mIoU(\%) & Param(M) & FLOPs(G) & mIoU/MS mIoU(\%) \\ \midrule ResNet50\cite{ResNet} & 28.5 & 183 & 36.7 & - & - & -/- \\ PVT-Small\cite{PVT_v1} & 28.2 & 161 & 39.8 & - & - & -/- \\ Swin-T\cite{Swin} & 31.9 & 182 & 41.5 & 59.9 & 945 & 44.5/45.8 \\ Twins-PCPVT-S\cite{Twins} & 28.4 & 162 & 44.3 & 54.6 & 919 & 46.2/47.5 \\ Twins-SVT-S\cite{Twins} & 28.3 & 144 & 43.2 & 54.4 & 901 & 46.2/47.1 \\ \textbf{SepViT-T} & 38.8 & 181 & \textbf{44.3} & 66.8 & 940 & \textbf{46.9}/\textbf{47.7} \\ \midrule ResNet101\cite{ResNet} & 47.5 & 260 & 38.8 & 86.0 & 1092 & -/44.9 \\ PVT-Medium\cite{PVT_v1} & 48.0 & 219 & 41.6 & - & - & -/- \\ Swin-S\cite{Swin} & 53.2 & 274 & 45.2 & 81.3 & 1038 & 47.6/\textbf{49.5} \\ Twins-PCPVT-B\cite{Twins} & 48.1 & 220 & 44.9 & 74.3 & 977 & 47.1/48.4 \\ Twins-SVT-B\cite{Twins} & 60.4 & 261 & 45.3 & 88.5 & 1020 & 47.7/48.9 \\ \textbf{SepViT-S} & 55.4 & 244 & \textbf{46.1} & 83.4 & 1003 & \textbf{48.1}/49.2 \\ \midrule ResNeXt101-64$\times$4d\cite{ResNeXt} & 86.4 & - & 40.2 & - & - & -/- \\ PVT-Large\cite{PVT_v1} & 65.1 & 283 & 42.1 & - & - & -/- \\ Swin-B\cite{Swin} & 91.2 & 422 & 46.0 & 121.0 & 1188 & 48.1/49.7 \\ Twins-PCPVT-L\cite{Twins} & 65.3 & 283 & 46.4 & 91.5 & 1041 & 48.6/49.8 \\ Twins-SVT-L\cite{Twins} & 103.7 & 404 & 46.7 & 133.0 & 1164 & 48.8/49.7 \\ \textbf{SepViT-B} & 94.7 & 367 & \textbf{47.3} & 124.8 & 1128 & \textbf{49.1}/\textbf{50.4} \\ \bottomrule \end{tabular} } \end{table} \subsubsection{Settings.} To further verify the capacity of our SepViT, we conduct the semantic segmentation experiment on ADE20K \cite{ADE20K}, which contains about 20K training images and 2K validation images from 150 categories. To make fair comparisons, we also follow the training conventions of the previous vision Transformers \cite{PVT_v1,Swin,Twins} on the Semantic FPN \cite{Semantic_FPN} and UperNet \cite{UperNet} frameworks. All of our models are pre-trained on the ImageNet-1k and then finetuned on ADE20K with the input size of 512$\times$512. For the Semantic FPN framework, we adopt the AdamW optimizer with both the learning rate and weight decay being 0.0001. Then we train the whole networks for 80K iterations with the total batch size of 16 based on the stochastic depth of 0.2, 0.3, and 0.4 for SepViT-T/S/B. For the training and testing on the UperNet framework, we train the models for 160K iterations with the stochastic depth of 0.3, 0.3, and 0.5. AdamW optimizer is used as well but with the learning rate $6\times10^{-5}$, total batch size 16 and weight decay 0.01 for SepViT-T/S and 0.03 for SepViT-B. Then we test the mIoU based on both single-scale and multi-scale (MS) where the scale goes from 0.5 to 1.75 with an interval of 0.25. \subsubsection{Results.} In Table \ref{tab:ADE20K}, we make a comparison with the recent vision Transformer and CNN backbones. Based on the Semantic FPN framework, SepViT-T, SepViT-S and SepViT-B surpass Swin's variants by 2.8\%, 0.9\% and 1.3\% mIoU with about 1G, 30G and 55G fewer FLOPs, respectively. Meanwhile, our SepViT shows great advantage over CNNs (e.g., ResNet\cite{ResNet}). By contrast to Swin on the UperNet framework, our models achieve 2.4\%, 0.5\% and 1.0\% higher mIoU with fewer FLOPs in terms of single-scale testing. Extensive experiments reveal that our SepViT shows great potential on segmentation tasks. \subsection{COCO Object Detection and Instance Segmentation} \begin{table}[th] \caption{Comparison of different backbones on RetinaNet-based object detection task. FLOPs are measured with the input size of $800 \times 1280$.} \label{tab:RetinaNet_COCO} \centering \resizebox{0.9\textwidth}{!}{ \begin{tabular}{c|cc|cccccc|cccccc} \toprule \multirow{2}{*}{Backbone} & Param & FLOPs & \multicolumn{6}{c|}{RetinaNet 1$\times$} & \multicolumn{6}{c}{RetinaNet 3$\times$ + MS} \\ \cline{4-15} & (M) & (G) & AP & AP$_{50}$ & AP$_{75}$ & AP$_S$ & AP$_M$ & AP$_L$ & AP & AP$_{50}$ & AP$_{75}$ & AP$_S$ & AP$_M$ & AP$_L$ \\ \midrule ResNet50\cite{ResNet} & 37.7 & 239 & 36.3 & 55.3 & 38.6 & 19.3 & 40.0 & 48.8 & 39.0 & 58.4 & 41.8 & 22.4 & 42.8 & 51.6 \\ PVT-Small\cite{PVT_v1} & 34.2 & 226 & 40.4 & 61.3 & 43.0 & 25.0 & 42.9 & 55.7 & 42.2 & 62.7 & 45.0 & 26.2 & 45.2 & 57.2 \\ Swin-T\cite{Swin} & 38.5 & 245 & 41.5 & 62.1 & 44.2 & 25.1 & 44.9 & 55.5 & 43.9 & 64.8 & 47.1 & 28.4 & 47.2 & 57.8 \\ Twins-PCPVT-S\cite{Twins} & 34.4 & 226 & 43.0 & 64.1 & 46.0 & 27.5 & 46.3 & 57.3 & 45.2 & 66.5 & 48.6 & 30.0 & 48.8 & 58.9 \\ Twins-SVT-S\cite{Twins} & 34.4 & 210 & 43.0 & 64.2 & \textbf{46.3} & 28.0 & 46.4 & 57.5 & 45.6 & 67.1 & 48.6 & 29.8 & 49.3 & 60.0 \\ \textbf{SepViT-T} & 45.4 & 243 & \textbf{43.9} & \textbf{65.1} & 46.2 & \textbf{28.4} & \textbf{47.3} & \textbf{58.5} &\textbf{ 46.2} & \textbf{67.7} & \textbf{49.4 } & \textbf{30.3 } & \textbf{49.8 } & \textbf{60.7} \\ \midrule ResNet101\cite{ResNet} & 58.0 & 315 & 38.5 & 57.8 & 41.2 & 21.4 & 42.6 & 51.1 & 40.9 & 60.1 & 44.0 & 23.7 & 45.0 & 53.8 \\ PVT-Medium\cite{PVT_v1} & 53.9 & 283 & 41.9 & 63.1 & 44.3 & 25.0 & 44.9 & 57.6 & 43.2 & 63.8 & 46.1 & 27.3 & 46.3 & 58.9 \\ Swin-S\cite{Swin} & 59.8 & 335 & 44.5 & 65.7 & 47.5 & 27.4 & 48.0 & 59.9 & 46.3 & 67.4 & 49.8 & 31.1 & 50.3 & 60.9 \\ Twins-PCPVT-S\cite{Twins} & 54.1 & 283 & 44.3 & 65.6 & 47.3 & 27.9 & 47.9 & 59.6 & 46.4 & 67.7 & 49.8 & 31.3 & 50.2 & 61.4 \\ Twins-SVT-B\cite{Twins} & 67.0 & 326 & 45.3 & 66.7 & 48.1 & 28.5 & 48.9 & 60.6 & 46.9 & 68.0 & 50.2 & 31.7 & 50.3 & 61.8 \\ \textbf{SepViT-S} & 61.9 & 302 &\textbf{ 45.5 } &\textbf{ 66.8} &\textbf{ 48.3} & \textbf{28.9} & \textbf{49.4 } & \textbf{60.8 } & \textbf{47.5} & \textbf{68.9} & \textbf{50.9} & \textbf{32.4} & \textbf{51.1} &\textbf{ 62.5} \\ \bottomrule \end{tabular} } \end{table} \subsubsection{Settings.} Next, we evaluate SepViT on the objection detection and instance segmentation task \cite{COCO} based the RetinaNet \cite{RetinaNet} and Mask R-CNN \cite{Mask_RCNN} frameworks with COCO2017 \cite{COCO}. Specifically, all of our models are pre-trained on ImageNet-1K and then finetuned following the settings of the previous works \cite{PVT_v1,Swin,Twins}. As for the 12 epochs (1$\times$) experiment, both the RetinaNet-based and the Mask R-CNN-based models use the AdamW optimizer with the weight decay 0.001 for SepViT-T and 0.0001 for SepViT-S. And they are trained with the total batch size of 16 based on the stochastic depth of 0.2 and 0.3 for SepViT-T/S. \begin{table}[ht] \centering \caption{Comparison of different backbones on Mask R-CNN-based object detection and instance segmentation tasks. FLOPs are measured with the inpus size of $800 \times 1280$. The superscript $b$ and $m$ denote the box detection and mask instance segmentation.} \label{tab:MaskRCNN_COCO} \resizebox{0.9\textwidth}{!}{ \begin{tabular}{c|cc|cccccc|cccccc} \toprule \multirow{2}{*}{Backbone} & Param & FLOPs & \multicolumn{6}{c|}{Mask R-CNN 1$\times$} & \multicolumn{6}{c}{Mask R-CNN 3$\times$ + MS} \\ \cline{4-15} & (M) & (G) & AP$^b$ & AP$_{50}^b$ & AP$_{75}^b$ & AP$^m$ & AP$_{50}^m$ & AP$_{75}^m$ & AP$^b$ & AP$_{50}^b$ & AP$_{75}^b$ & AP$^m$ & AP$_{50}^m$ & AP$_{75}^m$ \\ \midrule ResNet50\cite{ResNet} & 44.2 & 260 & 38.0 & 58.6 & 41.4 & 34.4 & 55.1 & 36.7 & 41.0 & 61.7 & 44.9 & 37.1 & 58.4 & 40.1 \\ PVT-Small\cite{PVT_v1} & 44.1 & 245 & 40.4 & 62.9 & 43.8 & 37.8 & 60.1 & 40.3 & 43.0 & 65.3 & 46.9 & 39.9 & 62.5 & 42.8 \\ Swin-T\cite{Swin} & 47.8 & 264 & 42.2 & 64.4 & 46.2 & 39.1 & 64.6 & 42.0 & 46.0 & 68.2 & 50.2 & 41.6 & 65.1 & 44.8 \\ Twins-PCPVT-S\cite{Twins} & 44.0 & 245 & 42.9 & 65.8 & 47.1 & 40.0 & 62.7 & 42.9 & 46.8 & 69.3 & 51.8 & 42.6 & 66.3 & 46.0 \\ Twins-SVT-S\cite{Twins} & 44.0 & 228 & 43.4 & 66.0 & 47.3 & 40.3 & 63.2 & 43.4 & 46.8 & 69.2 & 51.2 & 42.6 & 66.3 & 45.8 \\ \textbf{SepViT-T} & 54.7 & 261 & \textbf{44.4} & \textbf{67.1 } & \textbf{48.3} &\textbf{41.1} & \textbf{64.1} & \textbf{43.9} & \textbf{47.5} & \textbf{70.0} & \textbf{52.3} & \textbf{43.2} & \textbf{67.1} & \textbf{46.3} \\ \midrule ResNet101\cite{ResNet} & 63.2 & 336 & 40.4 & 61.1 & 44.2 & 36.4 & 57.7 & 38.8 & 42.8 & 63.2 & 47.1 & 38.5 & 60.1 & 41.3 \\ ResNeXt101-32$\times$4d\cite{ResNeXt} & 63.0 & 340 & 41.9 & 62.5 & 45.9 & 37.5 & 59.4 & 40.2 & 44.0 & 64.4 & 48.0 & 39.2 & 61.4 & 41.9 \\ PVT-Medium\cite{PVT_v1} & 63.9 & 302 & 42.0 & 64.4 & 45.6 & 39.0 & 61.6 & 42.1 & 44.2 & 66.0 & 48.2 & 40.5 & 63.1 & 43.5 \\ Swin-S\cite{Swin} & 69.1 & 354 & 44.8 & 66.6 & 48.9 & 40.9 & 63.4 & 44.2 & 48.5 & 70.2 & 53.5 & 43.3 & 67.3 & 46.6 \\ Twins-PCPVT-B\cite{Twins} & 64.0 & 302 & 44.6 & 66.7 & 48.9 & 40.9 & 63.8 & 44.2 & 47.9 & 70.1 & 52.5 & 43.2 & 67.2 & 46.3 \\ Twins-SVT-B\cite{Twins} & 76.3 & 340 & 45.2 & 67.6 & 49.3 & 41.5 & 64.5 & 44.8 & 48.0 & 69.5 & 52.7 & 43.0 & 66.8 & 46.6 \\ \textbf{SepViT-S} & 71.3 & 321 &\textbf{ 46.3} &\textbf{ 68.0} & \textbf{49.8 } & \textbf{42.3} & \textbf{65.8} & \textbf{45.3} & \textbf{48.7 } & \textbf{70.5} &\textbf{ 53.7} &\textbf{ 43.9} &\textbf{ 67.7 } & \textbf{47.1} \\ \bottomrule \end{tabular} } \end{table} During the training, there are 500 iterations for warm-up and the learning rate will decline by 10$\times$ at epochs 8 and 11. For the 36 epochs (3$\times$) experiment with multi-scale (MS) training, models are trained with the resized images such that the shorter side ranges from 480 to 800 and the longer side is at most 1333. Moreover, most of all the other settings are the same as the 1$\times$ except that the stochastic depth is 0.3 for SepViT-T, the weight decay becomes 0.05 and 0.1 for SepViT-T/S, and the decay epochs are 27 and 33. \subsubsection{Results.} Table \ref{tab:RetinaNet_COCO} reports object detection results using the RetinaNet framework. It indicates that our SepViT can achieve competitive performance, compared with the recent vision Transformers and CNNs. For the 1$\times$ schedule, our SepViT-T and SepViT-S surpass the Swin by 2.4 AP and 1.0 AP with fewer FLOPs. In particular, our SepViT variants achieve a state-of-the-art performance with 46.2 AP and 47.5 AP in the 3$\times$ experiment. Table \ref{tab:MaskRCNN_COCO} shows the evaluation result with Mask R-CNN framework. We can see that our SepViT-T outperforms Swin-T by 2.2 box AP, 2.0 mask AP with 1$\times$ schedule, and 1.5 box AP, 1.6 mask AP with 3$\times$ schedule. For the SepViT-S variant, it achieves a similar performance gain while saving a certain amount of computation overhead. \begin{table}[t] \centering \caption{Ablation studies of the key components in our SepViT. LWT means initializing the window tokens with learnable vectors.} \label{tab:Ablation1} \resizebox{0.85\textwidth}{!}{ \begin{tabular}{@{}c|ccc|ccc|c@{}} \toprule Model & DSSA & GSA & LWT & Param(M) & FLOPs(G) & Throughput(Images/s)) & Top-1 Acc(\(\% \)) \\ \midrule Swin-T+CPVT \cite{Twins} & & & & 28.0 & 4.4 & 704 & 81.2 \\ SepViT-T$\dagger$ & $\surd$ & & & 29.3 & 4.3 & 755 & 81.7 \\ \midrule \multirow{3}{*}{SepViT-T} & $\surd$ & & & 32.1 & 4.4 & 746 & 82.0 \\ & $\surd$ & $\surd$ & & 31.2 & 4.5 & 738 & 82.3 \\ & $\surd$ & $\surd$ & $\surd$ & 31.2 & 4.5 & 738 & \textbf{82.5} \\ \bottomrule \end{tabular} } \end{table} \subsection{Ablation Study} To better demonstrate the significance of each key component, including depthwise separable self-attention, grouped self-attention and the novel window token embedding scheme in SepViT, we conduct a series of ablation experiments on ImageNet-1K classification with SepViT-T variant. \subsubsection{Efficient Components.} As mentioned above, SepViT adopts the conditional position encoding (CPE) \cite{CPVT} and the overlapping patch embedding (OPE) \cite{ViT}. Therefore, we take the Swin-T+CPVT reported in \cite{Twins} as the baseline and we produce the SepViT-T$\dagger$ with CPE but without OPE to eliminate the influence of other factors. As shown in Table \ref{tab:Ablation1} where each component is added in turn to verify their benefits, our SepViT-T$\dagger$ simply equipped with the depthwise separable self-attention block (DSSA) outperforms Swin+CPVT by 0.5\% and it is much faster than Swin with the throughput of 755 images/s. Meanwhile, our SepViT-T with CPE, OPE and DSSA achieves 82.0\% top-1 accuracy. After employing grouped self-attention block (GSA) and DSSA alternately in the second and third stages, we gain an accuracy improvement of 0.3\%. \subsubsection{Window Token Embedding.} We further study whether it makes a difference if the window token is initialized with a fixed zero vector or a learnable vector. In contrast to the fixed zero initialization scheme, the learnable window token helps our SepViT-T to boost the performance to 82.5\%, as shown in the last row of Table \ref{tab:Ablation1}. \begin{table}[th] \centering \caption{Comparison of different approaches of getting the global representation of each window in SepViT.} \label{tab:Ablation2} \resizebox{0.75\textwidth}{!}{ \begin{tabular}{@{}c|ccc|c@{}} \toprule Method & Param(M) & FLOPs(G) & Throughput(Images/s)) & Top-1 Acc(\(\% \)) \\ \midrule Win\_Tokens & 31.2 & 4.5 & 738 & \textbf{82.5} \\ Avg\_Pooling & 31.2 & 4.5 & 743 & 82.1 \\ Dw\_Conv & 31.3 & 4.5 & 735 & 82.3 \\ \bottomrule \end{tabular} } \end{table} Moreover, to verify the effectiveness of learning the global representation of each window with our window token embedding scheme (Win\_Tokens), we further study some other methods that directly get the global representations from the output feature maps of DWA, such as average pooling (Avg\_Pooling) and depthwise convolution (DW\_Conv). As the results illustrated in Table \ref{tab:Ablation2}, our window token embedding scheme achieves the best performance among these approaches. Meanwhile, the comparison of parameters and FLOPs between Win\_Token and Avg\_Pooling methods demonstrates that our window token embedding scheme brings negligible computational cost. \begin{table}[t] \centering \caption{Comparison of lite models on ImageNet-1K classification.} \label{tab:Ablation3} \resizebox{0.6\textwidth}{!}{ \begin{tabular}{c|cc|c} \toprule Method & Param(M) & FLOPs(G) & Top-1 Acc(\(\% \)) \\ \midrule MobileNet-V2 \cite{MobileNet_v2} & 3.4 & 0.3 & 71.8 \\ ResNet18 \cite{ResNet} & 11.1 & 1.8 & 69.8 \\ PVTv2-B0 \cite{PVT_v2} & 3.4 & 0.6 & 70.5 \\ {\bf SepViT-Lite} & 3.7 & 0.6 & \textbf{72.3} \\ \bottomrule \end{tabular} } \end{table} \subsubsection{Comparison with Lite Models.} To further explore the potential of SepViT, we scale down SepViT to a lite model size (SepViT-Lite). As we can observe in Table \ref{tab:Ablation3}, SepViT-Lite obtains an excellent top-1 accuracy of 72.3\%, outperforming its counterparts with similar model sizes. \section{Conclusion} In this paper, we have presented an efficient Separable Vision Transformer, dubbed SepViT, which consists of three core designs. Firstly, depthwise separable self-attention enables SepViT to achieve information interaction within and among the windows in a single block. Next, the window token embedding scheme helps SepViT to model the attention relationship among windows with negligible computational cost. Thirdly, grouped self-attention enables SepViT to capture long-range visual dependencies across multiple windows for better performance. Experimental results on various vision tasks verify that SepViT achieves a better trade-off between performance and latency. \bibliographystyle{splncs04}
{'timestamp': '2022-05-10T02:09:10', 'yymm': '2203', 'arxiv_id': '2203.15380', 'language': 'en', 'url': 'https://arxiv.org/abs/2203.15380'}
arxiv
\section{Introduction} Modern warfare situations are fluid and require rapid ad hoc countermeasure decisions. Military technology is also advancing with the development of artificial intelligence, and the future warfare can be said to be dominated by the participation of few combatants and the unmanned nature of actual combat. Here to use NetLogo software simulation to build a dynamic projection of both sides tanks in complex terrain confrontation thought\cite{b1}, both sides confrontation terrain environment as shown in Figure 1. \begin{figure*}[t] \centerline{\includegraphics[width=6.7in]{dixingtu}} \caption{Diagram of the Game Environment of both Sides.} \label{fig1} \end{figure*} The dynamic projection of the two sides' tank confrontation in complex terrain is conceived as a situation where the Red side is preparing to achieve a strike against the Blue side's chain of command in the complex terrain of the mountain peaks and valleys, and the Blue side intends to send a significant portion of its armor numbers to intervene in order to achieve the objective of stopping the strike and maintain the intention of containing the Red side's course. After the Red side learns of the Blue side's strategic intent, it sends its absolute superior armor numbers to execute counter-intervention operations at the first opportunity. The OODA cycle connects the two sides in the confrontation process, forming a complete game process, and finally using hierarchical analysis to provide a reference for the weight value of the mixed game strategy. -Decision-action" cycle. The "Orientation" and "Decision" steps are the most critical in the OODA cycle, and if the enemy's threat is misjudged or the surrounding environment is misunderstood, then the judgment and decision will be wrong\cite{b2,b3,b4,b5}. The goal is to interfere with the enemy's OODA cycle by taking prompt action after the first OODA cycle is completed by the own side. In constructing a complex combat system adversarial analysis, NetLogo modeling software will be used to model the system dynamics of the game process on both sides\cite{b6,b7,b8,b9,b10,b11}. \section{Complex system confrontation model construction theory} In the 1970s, the U.S. Air Force Colonel Boyd proposed the "$OODA$ Loop" theory. $OODA$ is the abbreviation of the four English words Observation, Orientation, Decision, and Action. Its meaning is to observe, Orientation, make decisions, and Action.\cite{b11,b12}The OODA Loop theory (Observation, Orientation, Decesion, Action) proposed by John Boyd provides a way to describe conflicts in the cycle of detection, judgment, decision-making, and action. Decision-making processing is widely used in the study of military issues. The OODA loop theory points out that the characteristic of command and control operations is to fight in accordance with the observation-judgment-decision-action loop, which can be divided into the following four stages: The first stage is observation (Observation), mainly through various sensing equipment and The use of the network for intelligence collection, for example, early warning detection information, battlefield environment information, enemy coordinate information, etc. The second stage is Orientation. The battlefield situation is changing rapidly and there is great uncertainty. Judgment is to convert data into useful information. Effective and rapid judgment of the results can assist the commander in making correct decisions and even changes. The battlefield situation. The third stage is Decision, where the commander clearly formulates a mission plan and issues a battle plan. The rapid formation of decision-making is of decisive significance to the battlefield situation. The fourth stage is action. Actions on the battlefield are usually described as taking corresponding operational deployments and performing actions based on the operational plan issued by the superior. The OODA Loop has periodicity and nesting. Periodicity means that when a loop ends, another new loop begins. The size of the period is related to the scale of combat forces, spatial scope, and combat style; nesting means that the loop and The loops are related in the form of nesting. For example, in the tactical combat system, the smallest OODA Loop is the firepower closed-loop control loop of the close-range weapon system. There are also OODA Loops at the unit level. These command and control loops are nested within each other, and the inner loop The cycle is short and the outer loop cycle is long. In combat, the opposing parties will continuously observe the surrounding environment, obtain relevant information, judge threats, make immediate adjustments, make decisions, and take corresponding actions. This is specifically reflected in the competition of OODA Loop response capabilities. If they can try to shorten their own side The enemy's OODA Loop and increase the enemy's OODA Loop as much as possible. New actions are initiated before the enemy responds to its previous action, causing the enemy to lose the ability to react, so that the initiative can be mastered and a huge advantage can be obtained..The schematic diagram of the $OODA$ Loop is shown in Figure 2. \begin{figure*}[t] \centerline{\includegraphics[width=5.0in]{OODA}} \caption{Diagram of the Game Environment of both Sides.} \label{fig2} \end{figure*} The first is observation. Before the implementation of command operations, a clear observation plan is required. The two sides started by observing the new situation from the beginning of the war and the reaction of the other side. In the experiment, the red and blue sides were simulated and designed for the $OODA$ Loop, and the deployment was judged by observing the strength of the opposing sides before the war. The second is to judge and observe the situation and make reasonable decisions. In order to reflect the process of dynamically deploying the amount of armor, the slider value adjustment in the judgment and decision-making link in $NetLogo$ is used. At the end, the actual output of the red and blue sides is used as the execution link, and the amount of armor that needs to be dispatched for the next $OODA$ Loop is made according to the previous three links.\cite{b13,b14,b15} The $OODA$ Loop is a closed ring for decision-making and control actions, and it has the characteristics of a periodic cycle. The law of future warfare is that combat units that make quick judgments and decisions will take the initiative. From the $OODA$ Loop theory, it can be concluded that the timeliness of military operations research. Each time period of the system combat command cycle depends on different factors. $\lambda_{d}$ and $\lambda_{f}$ are defined separately as the mobile deployment rhythm and engagement rhythm of the combat system in the physical domain.$\lambda_{C 2}$ is the decision-making rhythm of the combat system in the cognitive domain,$\lambda_{T}$is the rhythm of interaction between the information domain, the physical domain, and the cognitive domain,$\Delta t_{1}, \Delta t_{2}, \Delta t_{3}, \Delta t_{4}$is defined as the combat time of the observation, judgment, decision-making and action links of the OODA Loop,then complete the OODA Loop and the time required for each link, as shown in Equation 1 and Equation 2. \begin{equation}\label{eq1} \left\{\begin{array}{l} \Delta t_{1} \geq \frac{1}{\lambda_{T}} \\ \Delta t_{2} \geq \frac{1}{\lambda_{T}}+\frac{1}{\lambda_{C 2}} \\ \Delta t_{3} \geq \frac{1}{\lambda_{T}}+\frac{1}{\lambda_{d}} \\ \Delta t_{4} \geq \frac{1}{\lambda_{T}}+\frac{1}{\lambda_{f}} \end{array}\right. \end{equation} \begin{equation}\label{eq2} \begin{aligned} T_{O O D A} &=\Delta t_{1}+\Delta t_{2}+\Delta t_{3}+\Delta t_{4} \\ & \geq \frac{4}{\lambda_{T}}+\frac{1}{\lambda_{C 2}}+\frac{1}{\lambda_{d}}+\frac{1}{\lambda_{f}} \end{aligned} \end{equation} According to Shannon's information entropy theory, the probability of occurrence of each part of the observation, judgment, decision-making and action links in the OODA Loop is defined as $P(O 1), P(O 2), P(D), P(A)$.Then the information entropy of each part of the observation, judgment, decision and action links in the OODA Loop is shown in Equation 3. \begin{scriptsize} \begin{equation}\label{eq3} \left\{\begin{array}{l} H\left(O 1_{i}\right)=-\sum_{i=1}^{n} P\left(O 1_{i}\right) \log \left(P\left(O 1_{i}\right)\right) \\ H\left(O 2_{i}\right)=-\sum_{i=1}^{n} P\left(O 2_{i}\right) \log \left(P\left(O 2_{i}\right)\right) \\ H\left(D_{i}\right)=-\sum_{i=1}^{n} P\left(D_{i}\right) \log \left(P\left(D_{i}\right)\right) \\ H\left(A_{i}\right)=-\sum_{i=1}^{n} P\left(A_{i}\right) \log \left(P\left(A_{i}\right)\right) \end{array}\right. \end{equation} \end{scriptsize} In the formula, n indicates that the OODA Loop can be multiple cycles. The information entropy of all OODA Loop of complex operations systems is shown in formula 4. \begin{scriptsize} \begin{equation}\label{eq4} \begin{aligned} H(O O D A) &=H\left(O 1_{i}\right)+H\left(O 2_{i}\right)+H(D)+H(A) \\ &=-\sum_{i=1}^{n} P\left(O O D A_{i}\right) \log \left(P\left(O O D A_{i}\right)\right) \end{aligned} \end{equation} \end{scriptsize} \emph{Statement: According to the information entropy of each link of the OODA Loop, the information entropy of the OODA Loop of the complex combat system can be described. An OODA Loop is composed of four links to solve the maximum information entropy of all OODA Loop in a complex combat system.The information entropy of all OODA Loop of the system is $H(O O D A)=-\sum_{i=1}^{n} P\left(O O D A_{i}\right) \log \left(P\left(O O D A_{i}\right)\right)$,Then prove $H(O O D A) \leq \log _{2} n$.} \begin{proof} The information entropy of the complex system is abbreviated as Equation 5, and the constraint condition is Equation 6. The problem of solving the maximum value of the original Equation 4 is equivalent to the minimum value of Equation 5.. \end{proof} \begin{equation}\label{eq5} H(D)=\sum_{i=1}^{n} X_{i} \log _{2} X_{i} \\ \end{equation} \begin{equation}\label{eq6} \sum_{i=1}^{n} X_{i}=1 \end{equation} Then construct the Lagrangian function as formula 7 \begin{scriptsize} \begin{equation}\label{eq7} L\left(X_{1}, \cdots \cdots, X_{n}\right)=\sum_{i=1}^{n} X_{i} \log _{2} X_{i}+\lambda\left(\sum_{i=1}^{n} X_{i}-1\right) \end{equation} \end{scriptsize} \begin{tiny} \begin{equation} \begin{aligned} \frac{\partial L\left(X_{1}, \cdots \cdots, X_{n}\right)}{\partial X_{1}} &=\frac{\partial}{\partial X_{1}}\left[\sum_{i=1}^{n} X_{i} \log _{2} X_{i}+\lambda\left(\sum_{i=1}^{n} X_{i}-1\right)\right]=0 \\ &=\log _{2} X_{1}+\frac{1}{\ln 2}+\lambda=0 \\ & \Rightarrow \lambda=-\log _{2} X_{1}-\frac{1}{\ln 2} \\ \frac{\partial L\left(X_{1}, \cdots \cdots, X_{n}\right)}{\partial X_{2}} &=\frac{\partial}{\partial X_{2}}\left[\sum_{i=1}^{n} X_{i} \log _{2} X_{i}+\lambda\left(\sum_{i=1}^{n} X_{i}-1\right)\right]=0 \\ &=\log _{2} X_{2}+\frac{1}{\ln 2}+\lambda=0 \\ & \Rightarrow \lambda=-\log _{2} X_{2}-\frac{1}{\ln 2} \end{aligned} \end{equation} ...... \begin{equation} \begin{aligned} \frac{\partial L\left(X_{1}, \cdots \cdots, X_{n}\right)}{\partial X_{n}} &=\frac{\partial}{\partial X_{n}}\left[\sum_{i=1}^{n} X_{i} \log _{2} X_{i}+\lambda\left(\sum_{i=1}^{n} X_{i}-1\right)\right]=0 \\ &=\log _{2} X_{n}+\frac{1}{\ln 2}+\lambda=0 \\ & \Rightarrow \lambda=-\log _{2} X_{n}-\frac{1}{\ln 2} \end{aligned} \end{equation} \begin{equation} \begin{aligned} \frac{\partial L\left(X_{1}, \cdots \cdots, X_{n}\right)}{\partial \lambda}=& \frac{\partial}{\partial \lambda}\left[\sum_{i=1}^{n} X_{i} \log _{2} X_{i}+\lambda\left(\sum_{i=1}^{n} X_{i}-1\right)\right]=0 \\ & \Rightarrow \sum_{i=1}^{n} X_{i}=1 \end{aligned} \end{equation} \end{tiny} The above equation can be solved. \begin{equation} X_{1}=X_{2}=\ldots=X_{n}=\frac{1}{n} \end{equation} So $H(O O D A)=-\sum_{i=1}^{n} \frac{1}{n} \log _{2} \frac{1}{n}=\log _{2} n$. The information entropy value of all OODA Loop of a complex combat system is a system that increases as the number of system cycles increases, indicating that the system is a highly complex entropy increasing system and the entropy value is in a state of divergence. For the highly complex entropy increase system, Swarm, $NetLogo$ and other software are needed to assist the analysis. $NetLogo$ has the characteristics of simple model description language and rapid modeling. In the third section, $NetLogo$ modeling specifically analyzes the process of confronting both parties. \section{Netlogo modeling based on OODA Loop} $Netlogo$ is a programmable modeling environment used to simulate natural and social phenomena.\cite{b16,b17,b18}When the internal operating rules of a complex system are not obvious and it is difficult to grasp the rules, $NetLogo$ software can be used to simulate the system.\cite{b19}The red and blue confrontation experiment simulation is based on the hardware platform of $Inter(R) Core(TM) i7-10750H CPU @2.60GHZ$ and the software platform of $NetLogo 6.1.1$. Taking the construction of the red OODA Loop as an example, the modeling is carried out from four aspects: observation, judgment, decision-making and action.The research of complex nonlinear combat with multi-agent systems in modern combat is an important direction of war simulation. NetLogo is a powerful multi-agent simulation tool, which greatly improves the simple analytical model and analytical combat methods. Due to the simplification of the research, this article limits the combat process to the micro process of OODA Loop combat. In the future, the simulation can be extended and expanded to achieve OODA Loop stacking and cumulative confrontation. Use NetLogo to improve the level of human-computer interaction, establish models and calculation formulas with a higher degree of reduction, and analyze the process and results of simulation operations to draw more credible evaluation conclusions. By analyzing the problems, finding the gaps, laying the foundation for the formulation of combat plans, so that simulation can truly serve the combat decision-making. The functions of each module in the OODA Loop are defined as follows: Based on practical foundation and facts, the difference in the amount of armor between the two opposing parties is relatively large, so the party with the less armor will take a longer time to think and need more time to deploy armor to achieve the goal of winning with less. Select the value of the $NetLogo$ slider for the judgment and decision-making links of the red and blue parties. For example, 500 armors of the red side and 400 armors of the blue side appear at one of the nodes of the OODA Loop, and Then the red and blue sides in the NetLogo simulation software slider affiliation value is adjusted to 1 and 0.5 respectively. as shown in Figure 3, Figure 4. \begin{figurehere} \begin{center} \centerline{\includegraphics[width=2in]{rbpanduan}} \caption{Time adjustment module of the judgment link.} \label{fig3} \end{center} \end{figurehere} \begin{figurehere} \begin{center} \centerline{\includegraphics[width=2in]{rbjuece}} \caption{Time adjustment module for the decision-making link.} \label{fig4} \end{center} \end{figurehere} In order to quickly select $ROTime$, $BOTime$, $RDTime$, and $BDTime$ values, some judgment and decision time values are now listed, as shown in $Table 1$. \end{multicols} \begin{tablehere} \tbl{OODA combat Loop part Orientation and Decision-making time value reference table. \label{tab1}} {\begin{tabular*}{16.4cm}{ccccc} \toprule \begin{tabular}[c]{@{}c@{}}Red and Blue \\ Armmored Quantity(X,Y)\end{tabular} & \begin{tabular}[c]{@{}c@{}}Red Determine the \\ time value\end{tabular} & \begin{tabular}[c]{@{}c@{}}Blue Determine the \\ time value\end{tabular} & \begin{tabular}[c]{@{}c@{}}Red Decision \\ time value\end{tabular} & \begin{tabular}[c]{@{}c@{}}Blue Decision \\ time value\end{tabular} \\ \colrule (500,200) & 0.3 & 1.0 & 0.3 & 1.0 \\ (500,300) & 0.4 & 1.0 & 0.4 & 1.0 \\ (500,400) & 0.4 & 0.7 & 0.4 & 0.7 \\ (600,200) & 0.2 & 1.0 & 0.2 & 1.0 \\ (600,300) & 0.3 & 1.0 & 0.3 & 1.0 \\ (600,400) & 0.2 & 0.5 & 0.2 & 0.5 \\ (700,200) & 0.1 & 1.0 & 0.1 & 1.0 \\ (700,300) & 0.1 & 0.9 & 0.1 & 0.9 \\ (700,400) & 0.2 & 0.7 & 0.2 & 0.7 \\ \botrule \end{tabular*}} \end{tablehere} \begin{multicols}{2} \subsection{Investigation link} The reconnaissance behavior model mainly describes the combat behavior of various detection, reconnaissance equipment and various sensing devices, which is the main means to obtain intelligence information on the battlefield. In the OODA Loop, the information acquisition of the investigation link is related to the pre-war deployment, command and decision-making, etc. The Red investigation consists of three modules, the speed at which the Red obtains intelligence ($RIS$), the speed preventing the Red from acquiring intelligence ($BZuA$), and the speed the Red actually obtains intelligence ($R-Actual-S$). The system dynamics module composed of the three modules is as shown in Figure 5. \begin{figurehere} \begin{center} \centerline{\includegraphics[width=2in]{redO1}} \caption{Dynical model of Red Square investigation link.} \label{fig5} \end{center} \end{figurehere} \subsection{Judgment link} This part of the OODA Loop is to analyze the collected intelligence, determine the authenticity of the intelligence, and study the current situation. It is mainly completed by the red judgment ($RO$) and the red judgment time ($ROTime$) in the combat elements of the command system. It is an accusation The processing center of the information flow in the system. The red side judgment link is composed of two modules, namely, red side judgment ($RO$) and red side judgment flow input ($RIn$). The system dynamics module composed of two modules is shown in Figure 6. \begin{figurehere} \begin{center} \centerline{\includegraphics[width=2in]{redO2}} \caption{Dynical model of red square judgment link.} \label{fig6} \end{center} \end{figurehere} \subsection{Decision link} The decision-making link in the OODA Loop is based on the situation judgment, assigning the action and task plan, mainly by the red decision ($RD$) module in the combat elements of the accusation system, generating a new command and control information flow. The decision link consists of red temporary storage module ($RlinshiCun$) and red decision module ($RD$). The system dynamics model of the decision-making link is shown in Figure 7. \begin{figurehere} \begin{center} \centerline{\includegraphics[width=1in]{redD}} \caption{Red square decision link dynamics model.} \label{fig7} \end{center} \end{figurehere} \subsection{Action link} The action link in the OODA Loop is the corresponding action behavior based on the decision made and the designated action plan, mainly through the red square armor module ($Reds$), the red side loss factor module ($RSunhaoxishu$), the red side actual output module ($Redsshijishuchu$), and the blue side Decision Module ($BD$),It is the specific implementation of the charge system information flow,as shown in Figure 8. \begin{figurehere} \begin{center} \centerline{\includegraphics[width=1.5in]{redA}} \caption{Red square action link dynamics model.} \label{fig8} \end{center} \end{figurehere} The dynamic model of the Observation, Orientation, Decision, Action link of the blue OODA Loop is shown in Figure 9 below. \begin{figurehere} \begin{center} \begin{tabular}{c} \centerline{\includegraphics[width=2in]{blueO1}}\\ {\footnotesize\sf {(a)Dynical model of blue fang investigation link.}}\\ \centerline{\includegraphics[width=2in]{blueO2}}\\ {\footnotesize\sf {(b)Blue side judgment link dynamics model.}}\\ \centerline{\includegraphics[width=1in]{blueD}}\\ {\footnotesize\sf {(c)Blue square decision-making link dynamics model.}} \\ \centerline{\includegraphics[width=2in]{blueA}}\\ {\footnotesize\sf {(d)Blue square action link dynamics model.}} \\ \end{tabular} \caption{The logic pattern of Blue with OODA loop.} \end{center} \end{figurehere} \section{Traditional methods are compared with OODA Loop}\label{sec4} The simple system uses two influencing factors as the OODA Loop of NetLogo simulation. Compared analysis shows the difference between the two methods and whether OODA Loop can improve operational thinking. \subsection{Simple system} Assuming the amount of red and blue armor, the two sides fight according to certain rules of engagement. Both parties then adjust their armor numbers and operational capabilities to simulate their operations. The kinetic model of a simple system is shown in $Fig.10$ and $Fig.11$.The combat system is a complex system composed of personnel, equipment, and organization. The combat process is affected by many factors such as combat missions, technical support, logistical support, suddenness, morale, and command art. It is very difficult and tedious to comprehensively analyze and model the factors in the combat process. Therefore, the combat process is specifically abstracted as the link of dynamic combat interaction, and only the system process of red and blue tank confrontation is analyzed, which can also play a good simulation role. By adjusting the number and combat capabilities of the tanks on both sides, let them conduct simulation operations. Simulate the number of tanks on both sides, represented by R-Tank and G-Tank. As the confrontation between the two warring parties continues, the number of tanks will show a certain consumption trend. If the number of subsequent tanks is supplemented, it will lead to a certain decrease or increase in the scale of the tanks of both sides. The confrontation between the two sides is a fierce process. The number of tanks is high. In order to ensure the continuity of combat effectiveness, continuous replenishment of tank armor is required. R-Input and G-Input are used to indicate the number of replenishment of the red and blue sides. At the same time, use R- lost and G-lost indicate the amount of equipment lost by both red and blue. There are four variables in this model, namely the loss rate of the red and blue tanks and the replenishment rate of the red and blue tanks. R-lost-rate, G-lost-rate, R-input-rate and G-input-rate are used respectively. Express. In the process of this model test, the Red Army tanks are replenishing (R-input) and losing (R-lost). The confrontation is carried out step by step. Due to the short process of modern warfare and the fierce confrontation, the speed of equipment replenishment is often lower than that of The speed at which weapons and equipment are consumed. \begin{figurehere} \begin{center} \centerline{\includegraphics[width=3in]{NetLogojiandan}} \caption{Schematic of simple system dynamics model.} \label{fig10} \end{center} \end{figurehere} \begin{figurehere} \begin{center} \centerline{\includegraphics[width=2.5in]{NetLogofangzhen}} \caption{Schematic diagram of the red and blue confrontation results of the simple system.} \label{fig11} \end{center} \end{figurehere} \subsection{OODA Loop system} Through simulation of red and blue OODA Loop by NetLogo in Fig.5-Fig.9, the dynamic model of complex combat system is shown in Figure 12, and the schematic diagram of red and blue confrontation results of OODA Loop system is shown in Figure 13. \begin{figure*}[tbh] \centering \includegraphics[scale=0.6]{quanju.eps} \caption{Dynamical models of complex combat systems based on OODA Loop.} \end{figure*} \begin{figurehere} \begin{center} \centerline{\includegraphics[width=2.5in]{OODAxitong}} \caption{Schematic diagram of the red and blue confrontation results of the OODA Loop system.} \label{fig13} \end{center} \end{figurehere} \subsection{OODA Loop system feasibility verification} The OODA cycle complex OS scheme is selected according to the Operations Research Hierarchy Analysis Method (The Analytic Hierarchy Process, or AHP). Hierarchical analysis is a systematic and quantitative approach proposed by operations strategist Professor T. L. Saaty in the early 1970s. The analytic hierarchy process refers to a complex multi-objective decision-making problem as a system, the goal is decomposed into multiple goals or criteria, and then decomposed into multiple indicators (or criteria, constraints) several levels, through the qualitative index fuzzy quantitative method to calculate the level Single ranking (weight) and total ranking are used as a systematic method for target (multi-index) and multi-scheme optimization decision-making.The analytic hierarchy process is to decompose the decision-making problem into different hierarchical structures in the order of the overall goal, the sub-goals of each level, the evaluation criteria, and the specific investment plan, and then use the method of solving the eigenvectors of the judgment matrix to obtain each level The priority of an element to an element of the previous level, and finally the weighted sum method is recursively merged and the final weight of each alternative plan to the overall goal, and the one with the largest final weight is the optimal plan.The analytic hierarchy process is more suitable for decision-making problems with hierarchical and interlaced evaluation indicators, and the target value is difficult to describe quantitatively.\cite{b20} First OODA Loop complex CS scheme hierarchical hierarchy, as shown in Figure 14. The hierarchical hierarchy includes three levels, target, criterion and scheme. The target layer selects options for complex combat systems; the criterion layer includes four modules: reconnaissance, judgment, decision, and execution; the program layer includes three schemes: support, continuation and retreat. \begin{figurehere} \begin{center} \centerline{\includegraphics[width=2.5in]{AHP}} \caption{Hierarchical structure of OODA Loop complex combat system plan.} \label{fig14} \end{center} \end{figurehere} Secondly, according to the scale value table of the analytic hierarchy process, the consistency matrix of the complex combat system plan to the four criterion modules (as shown in $Table 2$ and $Table 3$) and the consistency matrix of the three combat plans to each part of the OODA Loop are constructed. Due to space limitations, here only the consistency matrix of the four criterion modules of the complex combat system plan and the selection weight matrix of the complex combat system plan (as shown in Table 4) are constructed here, and the consistency of the three combat plans for each part of the OODA Loop The matrix will be explained in the appendix. botrule \end{multicols} \begin{tablehere} \tbl{The scale value matrix of the four criterion modules of the complex combat system plan.\label{tab2}} {\begin{tabular}{ccccc} \toprule \begin{tabular}[c]{@{}c@{}}Complex combat system \\ plan selection(A)\end{tabular} & Observation & Orientation & Decision & Action \\ \colrule Observation & 1.0000 & 3.0000 & 4.0000 & 7.0000 \\ Orientation & 0.3333 & 1.0000 & 2.0000 & 3.0000 \\ Decision & 0.2500 & 0.5000 & 1.0000 & 2.0000 \\ Action & 0.1429 & 0.3333 & 0.5000 & 1.0000 \\ Sum of scaled values & 1.7262 & 4.8333 & 7.5000 & 13.0000 \\ \botrule \end{tabular}} \end{tablehere} \begin{tablehere} \tbl{Consistency matrix of complex combat system plan to four criterion modules.\label{tab3}} {\begin{tabular}{ccccccc} \toprule \begin{tabular}[c]{@{}c@{}}Complex combat system \\ plan selection\end{tabular} & Observation & Orientation & Decision & Action & Weights(w) & Aw \\ \colrule Observation & 0.5793 & 0.6207 & 0.5333 & 0.5385 & 0.5679 & 2.2933 \\ Orientation & 0.1931 & 0.2069 & 0.2667 & 0.2308 & 0.2244 & 0.9029 \\ Decision & 0.1448 & 0.1034 & 0.1333 & 0.1538 & 0.1339 & 0.5357 \\ Action & 0.0828 & 0.0690 & 0.0667 & 0.0769 & 0.0738 & 0.2967 \\ \botrule \end{tabular}} \end{tablehere} \begin{multicols}{2} According to the above table data, the $Expert Choice 11.5$ software is used to calculate the value of its natural attributes to judge whether the matrix construction conforms to logical consistency. Among them, the characteristic maximum value $\lambda_{\max }$=4.0206, $CI=0.0069$, $RI=0.89$, $CR=0.0077$, since $CR<0.1$, the consistency matrix is logical. \end{multicols} \begin{tablehere} \tbl{Selection Weight Matrix of Complex Combat System Scheme.\label{tab4}} {\begin{tabular}{ccccc} \toprule \begin{tabular}[c]{@{}c@{}}Complex combat system \\ scheme selection\end{tabular} & \begin{tabular}[c]{@{}c@{}}Comprehensive \\ weight ratio\end{tabular} & \begin{tabular}[c]{@{}c@{}}Support \\ weight ratio\end{tabular} & \begin{tabular}[c]{@{}c@{}}Continue with the \\ operational weight ratio\end{tabular} & \begin{tabular}[c]{@{}c@{}}Retreback \\ weight ratio\end{tabular} \\ \colrule Observation & 0.5679 & 0.4577 & 0.1263 & 0.4160 \\ Orientation & 0.2244 & 0.5571 & 0.3202 & 0.1226 \\ Decision & 0.1339 & 0.5571 & 0.3202 & 0.1226 \\ Action & 0.0738 & 0.7015 & 0.2267 & 0.0718 \\ \begin{tabular}[c]{@{}c@{}}Weighted \\ weight ratio\end{tabular} & & 0.5113 & 0.2032 & 0.2855 \\ \botrule \end{tabular}} \end{tablehere} \begin{multicols}{2} According to the selection weight matrix of the complex combat system scheme, it can be concluded that in the simulation combat, it is not the mode described by the simple system. The two sides are simply fighting, and the amount of armor continues to decline; instead, through the description of the combat mode like the OODA Loop, the two sides Confrontation is a reciprocating process. At the same time, the dynamic process of the zigzag fluctuation of the armor quantity shown in the schematic diagram of the confrontation between the red and blue sides of the OODA Loop system is verified from the side. It can be concluded from $Table 4$ that the weight ratios of the three combat plans are respectively, the support weight ratio is $0.5113$, and the continued combat weight and the retreat weight ratio are roughly the same. It shows that when using the OODA Loop to analyze the combat plan, the warring parties should support their own operations as much as possible, but the continued combat and retreat plan also accounted for nearly half of the proportion, and the choice to continue combat or retreat based on the confrontation situation. \section{Conclusions} This paper simulates a complex environment combat model based on OODA loop through NetLogo software and uses hierarchical analysis to embody the game strategy under three scenarios of attack, retreat, and continued reinforcement that the red side should take after the current OODA loop is executed in terms of the number of armor. It can be concluded from the experimental results that the simulation system of OODA loop is more exploratory and feasible compared to the traditional simple system approach simulation. The OODA cycle is a correct practice of modern military theory, and the full use of the OODA cycle can form a closed-loop control of the combat confrontation and make the combat analysis comprehensive and concrete. \section*{Acknowledgments} This research is partially supported by Nature Science Foundation of China with ID 62076028 and by National Key Research and Development Program of China with ID 2018AAA0101000.
{'timestamp': '2022-03-30T02:33:01', 'yymm': '2203', 'arxiv_id': '2203.15502', 'language': 'en', 'url': 'https://arxiv.org/abs/2203.15502'}
arxiv
\section{Introduction} \label{sec:introduction} The success of deep learning and machine learning (ML) in general in recent years is attributed to the availability of large datasets, more efficient algorithms, and specialized hardware \cite{Chollet2017}. Based on the current hype, more and more companies try to integrate ML into their products, leading to an ever increasing demand of data scientists. Software developers who already know the targeted application domain could fill this gap but typically lack a scientific ML background. Therefore, they need \emph{guidance} that helps them correctly use ML. We define guidance to encompass all means to facilitate or enforce correct usage of a tool or an API or proper adherence to a workflow. Guidance includes, on one hand, preventing, detecting, explaining and fixing erroneous usage and, on the other hand, communicating best practices and helping apply them. In a traditional software engineering (SE) context, guidance can help developers when learning an API or the use of a tool, developing a program using the API or tool, and debugging the program when something went wrong. This paper analyses how current ML tools and APIs fail to provide guidance to developers and presents ideas for improvement. Sec. \ref{sec:workflows} reviews a typical workflow of ML application development, points out differences to traditional software engineering, and elaborates the desirable guidance for each step of the ML workflow. Sec. \ref{sec:stateOfArt} reviews how the main APIs, languages, and development environments currently used for ML application development fail to provide guidance. Sec. \ref{sec:simpleml} discusses how better guidance can be offered by applying and adapting various SE concepts to the specific requirements of ML application development. \section{ML Workflows are Different} \label{sec:workflows} Due to space constraints, we focus without loss of generality on supervised learning, the currently most widely-used ML workflow \cite{Chollet2017}. The task in supervised learning is to learn a function $H$ on the basis of some \emph{training data}, which is a (typically very large) set of examples containing \emph{features} and \emph{labels}. Given the features, $H$ should ideally produce the labels. If the labels are from a continuous set, we call it a \emph{regression} problem, if the labels are from a discrete set we call it a \emph{classification} problem. A traditional SE workflow involves activities such as requirement engineering, design, implementation, refactoring, and testing. In an ML workflow, most of these activities are performed in a quite specific way (e.g. Sec. \ref{subsec:requirements} and \ref{subsec:tdd}), if at all\footnote{What, for instance, is the equivalent of refactoring in ML?}. Moreover, an ML workflow involves additional essential activities, such as Data Engineering (Sec. \ref{subsec:data_engineering}), Model Engineering (Sec. \ref{subsec:model_engineering}), and Model Quality Engineering (Sec. \ref{subsec:quality_engineering}). \subsection{Evaluation-Focussed Requirements Engineering} \label{subsec:requirements} Requirements Engineering (RE) for ML reflects the fact that ML development includes empirical evaluation of results as part of the indispensable Model Quality Engineering activity (Sec. \ref{subsec:quality_engineering}). Accordingly, the definition of quality metrics and the required level of quality for each metric is not an optional best practice but an essential part of the workflow. One quality metric we might define upfront, for instance, is that at least $80\%$ accuracy must be achieved. This gives as clear metric to assess the usefulness of a model and a stopping criteria for the workflow. \paragraph{Requirements Engineering Guidance} Desirable guidance for RE for ML includes: \begin{itemize} \item Automated suggestions of suitable quality metrics based on problem (regression / classification) and data. \item Automated checking if a comparable task has been solved before and achieved the desired quality. \end{itemize} \subsection{Test-Driven Development the ML Way} \label{subsec:tdd} Before we can start learning, we must first ensure that a large amount of data is available and split it into a \begin{itemize} \item a \emph{training set} that will be used for the actual learning / training (Sec. \ref{subsec:model_engineering}), \item a \emph{validation set} that will be used for assessing whether the training results are good enough and to fine-tune the model\footnote{Alternatively, we can use \emph{cross-validation} \cite{Chollet2017}.} (Sec. \ref{subsec:quality_engineering}). \item a \emph{test set}, that will be used to get a last measure of how well the model performs on real-world data before pushing the model into production (Sec. \ref{subsec:quality_engineering}). \end{itemize} \paragraph{Test-Driven Development Guidance} Desirable guidance for Test-Driven Development in ML includes: \begin{itemize} \item Automated suggestion whether to use cross-validation or a specific validation set based on desired quality, training time and the amount of data available. \item Automated suggestion of what percentage of the data should go into each of the sets. \item Automated verification of best practices for a `good' split of the data. For instance, the distribution of labels and significant features in the three sets should be as similar as possible (\emph{stratified sampling} \cite{Geron2017}). \item Automatically hiding the test set away until needed, so it does not influence decisions in subsequent steps of the workflow like the choice of the model \cite{Chollet2017}. \end{itemize} \subsection{Data Engineering} \label{subsec:data_engineering} Next, we must ensure that the available training data is of sufficient quality. If not, we need to perform \emph{data engineering}, which involves \begin{itemize} \item handling of missing values, \item turning categorical into numerical values, \item normalization of numerical values, \item assessing the statistical relevance of available features, \item selecting the features used for learning, possibly combining several features. \end{itemize} Data engineering is typically the most time consuming step in an ML project but also the most important one: If the data used for learning is of poor quality, so will be the learned function $H$. \paragraph{Data Engineering Guidance} Desirable guidance for data engineering includes: \begin{itemize} \item Automated detection of missing values and automated suggestions for handling them, ideally specific to the type of data or learning task at hand. For instance, for numeric values, missing values could be substituted by the mean of the other values. This is not possible for a feature that represents street names. \item Automatic conversion of categorical into numerical values, or at least suggestions for possible conversions, again taking into account the specific data types and application semantics. For instance, if categorical values can be ordered (e.g. `poor', `middle class', `rich', `billionaire'), we can replace them by an increasing sequence of numbers (\emph{label encoding}). Otherwise, we can perform a \emph{one-hot encoding}, which maps each different value to a sparse vector \cite{Geron2017}. \item Automated normalization of numerical values. \item Automated computation of the entropy of the distribution of a feature or of any other measure for the statistical relevance of the available features. \item Automated suggestions for sensible feature combinations in a specific application domain. \item Ideally, any data processing step performed on the training data, should be automatically applied also to the validation and test set in order to avoid inconsistencies or tedious and error-prone manual application of each step on each dataset. \end{itemize} \subsection{Model Engineering} \label{subsec:model_engineering} The next step in the ML workflow is the selection of an existing ML API and the choice of a supported \emph{learning algorithm}, such as \emph{decision trees} or \emph{neural networks} (NNs). At first glance, this might appear similar to the choice of proper algorithms and data structures in SE. However, it was shown by Wolpert in \cite{Wolpert1996} that lacking specific assumptions no learning algorithm performs better than any other. This makes it impossible to provide a general guideline to always use, say NNs. Choosing a learning algorithm instead requires significant background in ML and a careful consideration of the application goal\footnote{Do we need explainability?} and the properties of the data available after data engineering. Even with this knowledge, though, the final choice of the proper learning algorithm is typically the outcome of a lot of experimentation, involving several iterations of the entire ML development workflow. Given a choice of an algorithm, a developer then writes a \emph{training program} and starts the learning process on the prepared training data. Depending on the circumstances (hardware, data size, learning algorithm, etc.) this step can take a few seconds or several days. Its outcome is a \emph{model} representing the learned function $H$. It is worth noting that, unlike in SE, the learned model is the final output of the workflow, not the written program. \paragraph{Model Engineering Guidance} Desirable guidance for model engineering includes: \begin{itemize} \item Automated suggestions of suitable learning algorithms based on the available data and the application domain. \item Well-documented APIs and all kinds of teaching and training material that help quickly learn how to use them. \item Automated checking of correct API use, ideally during program development (static checking) but at least at runtime. Given that a single training run can take hours and days and the entire workflow involves many iterations, the importance of static checking cannot be overstated. Costs incurred in statically detecting and fixing errors in the training program that would be prohibitive in traditional SE appear small in an ML context. \item Help in understanding and fixing errors, ranging from sensible error messages, ideally enriched with suggestions how to resolve the error, to automated quickfixes. \end{itemize} \subsection{Model Quality Engineering} \label{subsec:quality_engineering} Next, the performance of the model is evaluated by running it on the validation set (Sec. \ref{subsec:tdd}), to get a measure of how well the model performs on data not seen during training. By measuring the metrics established in the RE phase (Sec. \ref{subsec:requirements}) we check that the model learned the characteristics of the training data well enough (no \emph{underfitting}) and did not simply learn the training data by heart (no \emph{overfitting}). The gathered metrics are used to fine-tune the training program by setting different \emph{hyperparameters} that control the behaviour of the learning algorithm. For example, the maximum number of nodes in a decision tree can be a hyperparameter. A low value can lead to underfitting, while a high value can lead to overfitting. With the improved settings, a new training is started and the entire process is repeated from there. If the results are still not satisfactory, one might go further back to select a different learning algorithm (Sec. \ref{subsec:model_engineering}) or even rethink and enhance data engineering (Sec. \ref{subsec:data_engineering}). Finally, when the model has passed the validation stage, we use the test set (Sec. \ref{subsec:tdd}) to get a last measure of how well the model performs on unseen data before pushing the model into production. We cannot use the validation set for this, since we selected the model that works best on the validation set, which introduces a risk of overfitting \cite{Geron2017}. \paragraph{Model Quality Engineering Guidance} Desirable guidance for quality engineering includes: \begin{itemize} \item Automated experiment management, that is, saving of the $n$ models that achieved the highest performance values during validation along with the related training program and fully data-engineered datasets (including training, validation and test data) in order to support reproducibility of results. \item Automated detection of overfitting and related suggestions how to combat it, e.g. by inserting drop-out layers \cite{Hinton2012} in a neural network. \item Automated detection of underfitting and related suggestions how to combat it, e.g. by choosing a more powerful learning algorithm. \end{itemize} \section{State of the Art} \label{sec:stateOfArt} The highly explorative and iterative workflow described in Sec. \ref{sec:workflows} is supported by high-level APIs for ML (Sec. \ref{subsec:api}), dynamic languages (Sec. \ref{subsec:languages}), and dynamic development environments (Sec. \ref{subsec:ide}). In this section, we review each of them with respect to the guidance they provide. \subsection{Efficient, High-Level APIs} \label{subsec:api} Based on a survey of ML APIs by Nguyen and others from 2019 \cite{Nguyen2019} we investigated scikit-learn \cite{Pedregosa2011}, a representative of an API for `classical' ML, as well as Keras \cite{chollet2015keras} and PyTorch \cite{Paszke2019}, which are APIs for deep learning. These APIs provide high-level abstractions to apply and adapt learning algorithms (model engineering), to ensure sufficient prediction quality (model quality engineering) and even to perform data engineering, thereby providing all functionality needed to rapidly iterate the ML workflow from Sec. \ref{sec:workflows}. With respect to guidance, though, we identified several shortcomings: \paragraph{Criticism: Hidden and Inconsistent Constraints in the API Documentation} The broadness of these APIs makes it difficult to use them correctly, especially since many constraints are hard to understand from the documentation. By looking just at the documentation of the support vector machine learning algorithm for classification (SVC) in scikit-learn\footnote{\url{https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html}} we can already identify four different categories of constraints documented only in natural language or documented inconsistently: \begin{itemize} \item \emph{type constraints} limit values of expressions in any context, \item \emph{dependencies} limit values depending on other values, \item \emph{temporal constraints} limit the order of operations, \item \emph{execution context constraints} express restrictions specific to the used programming language or executions platform. \end{itemize} \begin{figure}[H] \centering \captionsetup{justification=centering} \fbox{\includegraphics[width=0.8\linewidth]{img/scikit_docs_kernel.png}} \caption{Type constraints (scikit-learn)} \label{fig:scikit_docs_kernel} \end{figure} Hidden and inconsistent \emph{type constraints} are illustrated in Fig. \ref{fig:scikit_docs_kernel}: According to the first line of the documentation, the constructor parameter \verb|kernel| of the SVC must be of type string. However, the rest of the text (see highlighting), reveals that only the five string literals `linear', `poly', `rbf', `sigmoid' and `precomputed' are allowed and that we can additionally pass a \emph{callable}, thus something that is not a string. Reading on, we learn that the signature of the callable is further restricted: It must have a single parameter that must be an array of shape n\_samples by n\_samples. \begin{figure}[H] \centering \captionsetup{justification=centering} \fbox{\includegraphics[width=0.8\linewidth]{img/scikit_docs_degree.png}} \caption{Dependent API elements (scikit-learn)} \label{fig:scikit_docs_degree} \end{figure} A \emph{dependency constraint} is shown in Fig. \ref{fig:scikit_docs_degree}: The value of the constructor parameter \verb|degree| is only relevant if the constructor parameter \verb|kernel| has the value `poly'. \begin{figure}[H] \centering \captionsetup{justification=centering} \fbox{\includegraphics[width=0.8\linewidth]{img/scikit_docs_probability.png}} \caption{Temporal constraint (scikit-learn)} \label{fig:scikit_docs_probabilty} \end{figure} A \emph{temporal constraint} is shown in Fig. \ref{fig:scikit_docs_probabilty}: We must set the attribute \verb|probability| to `True' prior to the first call of the \verb|fit| method (which starts the learning process). \begin{figure}[H] \centering \captionsetup{justification=centering} \fbox{\includegraphics[width=0.8\linewidth]{img/scikit_docs_verbose.png}} \caption{Constraint of execution context (scikit-learn)} \label{fig:scikit_docs_verbose} \end{figure} An \emph{execution context constraint} is shown in Fig. \ref{fig:scikit_docs_verbose}: Verbose output may not work in a multithreaded environment. \paragraph{Criticism: Lack of Constraint Checking and Helpful Error Messages} Let us now investigate what happens if we run a program that does not comply with some of the restrictions shown above. We begin with the simple program in List. \ref{fig:scikit_errors_no_error}. There, we create an SVC with the invalid kernel `line' (see Fig. \ref{fig:scikit_docs_kernel}) --- the programmer probably meant 'linear'. But despite the wrong value, the code executes without error. The programmer therefore adds more code to preprocess the data and initiate training, which leads to the program state in List. \ref{fig:scikit_errors_bad_error_program}. Executing this program throws the error shown in List. \ref{fig:scikit_errors_bad_error_output}: \setcounter{figure}{0} \renewcommand{\figurename}{Listing} \begin{figure}[H] \centering \captionsetup{justification=centering} \fbox{\includegraphics[width=0.8\linewidth]{img/scikit_errors_no_error.png}} \caption{Incorrect, but throws no error (scikit-learn)} \label{fig:scikit_errors_no_error} \end{figure} \begin{figure}[H] \centering \captionsetup{justification=centering} \fbox{\includegraphics[width=0.8\linewidth]{img/scikit_errors_bad_error_program.png}} \caption{Throws a misleading error (scikit-learn)} \label{fig:scikit_errors_bad_error_program} \end{figure} \begin{figure}[H] \centering \captionsetup{justification=centering} \fbox{\includegraphics[width=0.85\linewidth]{img/scikit_errors_bad_error_output.png}} \caption{Error thrown by program in List. \ref{fig:scikit_errors_bad_error_program} (scikit-learn)} \label{fig:scikit_errors_bad_error_output} \end{figure} \setcounter{figure}{4} \renewcommand{\figurename}{Figure} There are multiple issues with this behaviour: \begin{itemize} \item \emph{No precondition checking in API function.} First, the error is not thrown by the API at the place where the illegal value was set, misleading the programmer to think that the first two lines are correct. \item \emph{Misleading, generic error messages.} A generic error is thrown by the runtime system when stumbling over the illegal value, which is much too late. At this point, the error message and shown stacktrace further mislead the programmer. Since lines 3 and 4 contain Python lists that indeed do not contain the string `line', the programmer could try to find a bug there. Going back to line 2, which apparently executed flawlessly, requires deep internal knowledge of the API, which is unlikely for anybody except its authors. One could argue that the string literal `line' shows up in line 2, which could point the programmer to the true issue. But note that the code for data preprocessing is normally much longer than shown here, so the line where the error originated might not be visible in the context where it manifests itself. \item \emph{No hint how to recover.} Finally, once the programmer has found the true bug, he must consult the documentation to find the correct value since the generic error message does not specify the valid inputs. \end{itemize} \paragraph{Criticism: No Checking of ML Best Practices} We only looked at constraints of the API so far. For general ML best practices (Sec. \ref{sec:workflows}), the situation is even more dire: For them none of the APIs provides any checking or feedback. In addition, due to the differences between the APIs, each one would have to implement checking of these best practices separately, even though they apply regardless of the API that is used. \paragraph{Criticism: No Static Checking} In either case, even the best documentation and ideal runtime error checking still requires developers to wait for (possibly long) training runs just to find out that an error occured. The effect is an annoying loop of editing, running, debugging, fixing and re-running the training program in order to see if the fix was successful --- the runtime acts like a test oracle. Ideally, the developer would get guidance while he writes the program but this is poorly supported in the programming languages used for ML development, which brings us to the next point. \subsection{Languages} \label{subsec:languages} The above-mentioned study by Nguyen, et al. from 2019 \cite{Nguyen2019} found that Python is the most popular language for ML. This can be attributed to its readability and to the fact that it is an interpreted language and, thus, well suited for highly interactive and explorative development. Moreover, Python has a vast ecosystem of scientific APIs that are useful for ML. Being a general-purpose programming language, Python provides the flexibility needed to implement new learning algorithms and highly customized ML-workflows. However, much of this flexibility --- and therefore complexity of the language --- is not needed if one is just using the functionality of an API for data, model and quality engineering to accomplish standard tasks. \paragraph{Criticism: Static Checking is Hard} Because Python is such a dynamic, general-purpose programming language, it is difficult to statically check the constraints of an API. Since the 2015 release of version 3.5, Python at least supports optional \emph{type hints}, defined in PEP 484 \cite{PEP484}. Still, the authors stress that ``Python will remain a dynamically typed language, and the authors have no desire to ever make type hints mandatory, even by convention''. Thus, taking advantage of type hints requires the use of an external tool such as the static type checker mypy\footnote{http://mypy-lang.org/}. However, of the three ML APIs we observed, only the most recent one, PyTorch, includes type hints. In addition, dependencies, temporal constraints, execution context constraints and ML best practices are beyond the scope of type hints. Even a simple constraint such as "the value must be a float between 0 and 1" cannot be expressed. The impact of static type checking was quantified (among others) in a study by Fischer and Hanenberg from 2015 \cite{Fischer2015}, where they found the development time of a program in the statically typed JavaScript-superset TypeScript\footnote{\url{https://www.typescriptlang.org}} to be significantly shorter than in the dynamically typed JavaScript itself. We argue that static checking of non-type errors has a similar positive effect. \subsection{Development Environments} \label{subsec:ide} Last but not least, notebooks for Python and other languages, e.g. Jupyter Notebooks\footnote{\url{https://jupyter.org/}}, have become a popular learning and development environment for ML and have recently been integrated into the generic Python IDE PyCharm\footnote{\url{https://www.jetbrains.com/pycharm/}}. In a notebook, a program can be split into cells that can be evaluated independently without deleting the results created by other cells. Results, including complex visualizations, are shown directly in the notebook next to the cell. It is possible to include text cells between code cells for documentation purposes and to structure the notebook. This feature also makes notebooks ideal for creating executable teaching materials for novices. Due to their interactivity, they are used in practice as a development environment for ML, especially for data exploration. We claim that the popularity of notebooks, even when used within PyCharm, points to the lack of IDEs that are adapted to the needs of ML development. \paragraph{Criticism: No Support for Data Engineering} Notebooks and generic Python IDEs such as PyCharm (henceforth called altogether `\emph{ML tools}') provide no specific support for data engineering. There are no built-in automated analyses of a dataset, as suggested in Sec. \ref{subsec:data_engineering}, or visualizations of them. Developers must rely on external tools or the functionality provided through APIs. \paragraph{Criticism: No Support for Introspection} While developing a training program, developers need to inspect the current state of data or models. There is no support for this in current ML tools. Instead, developers need to call specific API functions that provide introspection support. Keras, for example, has a \verb|summary| method that displays the layers of an NN, the shape of their outputs and the number of trainable parameters, which is a good measure of how long training is going to take and whether the model is likely to overfit or underfit. Fig. \ref{fig:keras_introspection_summary_output} shows an example output of this method. \begin{figure}[h] \centering \captionsetup{justification=centering} \fbox{\includegraphics[width=0.85\linewidth]{img/keras_introspection_summary_output.png}} \caption{Output of the summary method (Keras)} \label{fig:keras_introspection_summary_output} \end{figure} Although introspection is not conceptually part of the learning program, we must mix the two concerns in the notebook environment. A dedicated ML IDE could provide a clearer separation of concerns. \paragraph{Criticism: No Experiment Management} For experiment management developers must also invent their own solutions or choose external tools. A dedicated IDE could fulfill this need instead and also improve the discoverability of past experiments by automatically comparing the current task and available data to a database, thereby preventing duplicate work. \section{The Simple-ML Approach} \label{sec:simpleml} The Simple-ML project\footnote{https://simple-ml.de/} is dedicated to the development of solutions for the above-mentioned gaps in the state of the art. Its core ideas, summarized in Fig. \ref{fig:simple_ml_approach}, are: (1) the development of a unified ML API, (2) the development of a domain specific language (DSL) for ML, (3) the development of a dedicated ML IDE, and (4) last but not least, as a common basis for (2) and (3), the development of metamodels of the ML domain, ML APIs, and application-specific datasets. \begin{figure}[h] \centering \captionsetup{justification=centering} \includegraphics[width=0.8\linewidth]{img/simple-ml-approach-2.png} \caption{Our Simple-ML Approach} \label{fig:simple_ml_approach} \end{figure} \paragraph{Towards a Unified ML API} In its first release, the unified ML API will generalize the functionality of scikit-learn, Keras and PyTorch. Development of an own API lets us (a) ensure the quality of its documentation, and (b) ensure the existence of runtime checks where no static checking is possible. This enables checking of compliance with general, \emph{API-independent} ML best practices once and for all. The unified API will be based on adapters to the different existing APIs and will shield the higher levels from their details. In particular, it will serve as a unified target for code generation by the compiler of the DSL. \paragraph{A DSL with ML-aware Static Analysis Capabilities} The Simple-ML DSL, will provide ML-specific abstractions as first-class language elements, and will make them available via a textual \emph{and} a visual syntax. This will make it easy to learn by developers who want to experiment with ML but are not experienced programmers. In addition, the DSL will statically catch errors related to all the types of constraints identified in Sec. \ref{subsec:api}. Under the hood the DSL compiler will generate code for a general purpose programming language such as Python, using the implemented adapters to target an individual framework. This avoids locking users into the Simple-ML DSL. If they eventually need the flexibility of a general purpose programming language, they can take the generated code and modify it as desired. \paragraph{Using Ontologies to Store Metadata} ML-specific error detection will be done based on metadata in the form of ontologies. We will create ontologies that describe ML concepts, such as learning algorithms and quality metrics, to capture information like the hyperparameters of learning algorithms or whether a learning algorithm and a quality metric are compatible. For this we consider improving the MEX ontology \cite{Esteves2015}. The ML-specific metadata will be complemented by metadata about available datasets. Each dataset will be associated with a semantic description of its features \cite{Gottschalk2019}. For each feature, we will store metainformation like its semantic category (e.g. the fact that it represents the name of a person), or the associated unit of measurement (e.g. whether a distance is measured in metres or miles). We will also store general statistical properties of a feature, like minimum and maximum values, standard deviation etc. Using this metadata we can provide the desirable data engineering guidance identified in Sec. \ref{subsec:data_engineering}. For instance, we will be able to quickly detect if data is normalized and normalize it automatically if desired, or provide targeted suggestions for feature combinations based on the semantic categories. For model engineering (Sec. \ref{subsec:model_engineering}) we can also provide guidance, e.g. by suggesting suitable models given the data and the task. Ontologies can also provide the technical basis for model quality engineering guidance (Sec. \ref{subsec:quality_engineering}). \paragraph{An IDE to Tie Everything Together} Further guidance will be provided by an ML-specific IDE that will support the entire ML workflow (Sec. \ref{sec:workflows}) through GUI features. The error checking and fixing capabilities of the DSL will be used to display errors and to provide quickfixes while the training program is being written. The ontology-based metadata will be used for elaborate suggestions of preprocessing steps during data engineering (Sec. \ref{subsec:data_engineering}), for suggestions of suitable models during model engineering (Sec. \ref{subsec:model_engineering}), and for experiment management and suggestions of model improvements during quality engineering (Sec. \ref{subsec:quality_engineering}). The GUI of the IDE will also provide introspection (Sec. \ref{subsec:ide}) capabilities, allowing us to eliminate introspection from the user-visible part of the unified ML API, thus making it easier to learn. \section{Conclusion} This paper introduced the concept of guidance as the means offered by an API or tool to facilitate or enforce correct usage or to help follow a predetermined workflow or established best practices. Guidance speeds up learning, development and debugging. We discussed key differences between ML and SE workflows, derived the desirable ML-specific guidance and analyzed how existing APIs, languages and tools used for ML application development fail to provide most of it. As a possible solution, we identified static analysis, meta-modeling, and support by an IDE with an advanced GUI as key SE concepts, whose combined use could provide the missing guidance. Finally, we sketched the Simple-ML project, which will implement this solution in order make ML available as a well-understood tool for software developers. \begin{acks} This work was partially funded by the Federal Ministry of Education and Research (BMBF), Germany under Simple-ML (01IS18054). \end{acks} \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2022-03-30T02:33:10', 'yymm': '2203', 'arxiv_id': '2203.15510', 'language': 'en', 'url': 'https://arxiv.org/abs/2203.15510'}
arxiv
\section{Introduction} Self-supervised pre-training \cite{beit,simclr,mocov3,ibot,vicreg,barlow,clip} is attracting emerging attention due to its effectiveness and flexibility in exploiting large-scale uncurated data, which demonstrates its superiority to supervised pre-training in a wide range of downstream applications, such as classification, detection, and segmentation, \textit{etc.} Recently, the introduction of vision Transformers \cite{vit,deit,swinT} brings about a new revolution to self-supervised learning \cite{beit,mocov3,dino}. Inspired by the great success of BERT \cite{BERT} in natural language processing (NLP) tasks, masked image modeling (MIM) has been introduced for visual pre-training as a new pretext task. It is not trivial, because one key barrier lies in that the visual signal is continuous and cannot be properly classified as is done in masked language modeling (MLM) of BERT. A pioneer work, BEiT \cite{beit}, tackles the challenge by ``tokenizing'' continuous visual signals into discrete vision tokens resorting to a pre-learned codebook \cite{dalle}, which plays the role of a pre-defined vocabulary in MLM. The pre-training objective is to predict the vision token id of the masked image patch based on its context and semantics. \begin{figure}[t] \begin{center} \includegraphics[width=0.9\textwidth]{drawback.png} \caption{ The improper token ids for image discretization, where a better tokenizer \cite{taming} is used here. We observe that semantically-similar patches might be allocated with different token ids while patches with different semantics might be allocated with the same token id, indicting that the hard-label classification with unique token ids in BEiT \cite{beit} may hinder the pre-training performance. } \label{fig:drawback} \end{center} \end{figure} Despite the impressive performances of BEiT on image pre-training, there remain some questions under-developed. (1) \textit{Does the masked patch prediction have ground-truth answers?} Unlike the linguistic vocabulary which is naturally composed of discrete words, the image tokenizer is relatively subjective, \textit{i.e.}, there is no perfect answer to visual discretization and the tokenizer carries inevitable label noise even a better tokenizer is obtained in \cite{taming}. For example, as shown in Fig. \ref{fig:drawback}, patches of the dog and the shoe are discretized into the same vision token (\#319) due to their similar pixel-level representations. (2) \textit{Should the masked patch be assigned a unique token id given a pre-learned tokenizer?} Not really. As illustrated in Fig. \ref{fig:drawback}, semantically-similar patches of the grass are discretized into different vision tokens, \textit{i.e.}, they are classified into distinct and unique ids in BEiT pre-training, neglecting their semantic relations. Given the observation of the above two issues, we argue that performing MIM with a strict mapping between patch predictions and unique token ids by a hard-label classification loss in BEiT limits the visual context capturing and the pre-training performance. To tackle the challenge, we introduce to effectively boost BERT-style image pre-training with eased and refined masked prediction targets, that is, \textit{multi-choice vision token ids}. Rather than retraining the tokenizer with perceptual regularizations \cite{peco,ibot}, we efficiently inject the semantic relations into off-the-shelf vision tokens without any extra computational overhead. Specifically, to enable multi-choice answers for masked patches, we adopt the soft id probability vectors, rather than the hard predicted id over a pre-learned codebook, as the supervision signals for masked image modeling. Although the off-the-shelf image tokenizer \cite{taming} can capture some local semantics with the training objectives of both pixel-level and perceptually-aware regularizations, it is proven to be still vulnerable to various low-level changes (see Fig. \ref{fig:drawback}). Therefore, we introduce to refine the predicted soft id probabilities by inter-patch semantic similarities, which are estimated by the vision Transformers being trained. Under the observation that patches with similar high-level visual perceptions ought to share their predictions, we propagate the soft id probabilities of different patches in an image based on their semantic similarities and form ensembled learning targets for masked image patches (see Fig. \ref{fig:overview}). The final training objective is formulated as a soft-label cross-entropy loss. To fully evaluate our novel, flexible and effective method, we pre-train the vision Transformers with various scales on the widely-acknowledged ImageNet-1K \cite{imagenet1k} dataset and fine-tune the pre-trained models on multiple downstream tasks, including image classification, instance/semantic segmentation, and object detection. The empirical results show that our method impressively outperforms supervised pre-training as well as recent self-supervised learning methods \cite{mocov3,dino,beit,ibot}. Concretely, we achieve 84.1\% top-1 accuracy on ImageNet-1K classification with a ViT-B model, outperforming the state-of-the-art iBOT \cite{ibot} by +0.3\% with 800 fewer epochs. Regarding the transfer learning ability on different downstream tasks, our pre-trained ViT-B model achieves 49.2\% $\text{AP}^{b}$ and 44.0\% $\text{AP}^{m}$ of object detection and instance segmentation on COCO \cite{coco}, 50.8\% mIOU on downstream ADE20K \cite{ade20k} semantic segmentation, outperforming all existing methods. \section{Related Works} Self-supervised learning (SSL) has gained great popularity benefiting from its capability of exploiting the tremendous amounts of unlabeled data, which leverages input data itself as supervision. Substantial works \cite{moco,simclr,beit,BERT,GPT3,miles,liu2021self,cpc,decpc} have shown that the pre-training can be beneficial for downstream tasks and enable faster training convergence, which shows its impressive potentials on various machine learning tasks, especially in the fields of natural language processing and computer vision. \subsection{BERT pre-training with masked language modeling} Self-supervised learning has been studied in NLP for decades. Masked language modeling (MLM) is firstly widely acknowledged because of BERT \cite{BERT}. BERT encourages bidirectional textual context understanding and adopts the masked language modeling approach for pre-training, which randomly masks 15\% tokens and predicts the missing words as the target. After that, various MLM variants are proposed, \textit{e.g.,} GPT \cite{GPT3}, XLM \cite{xlm}, and RoBERTa \cite{roberta}, \textit{etc}. These MLM works achieve huge success and show impressive performances on various downstream tasks, which greatly advance the development of language pre-training. \subsection{Self-supervised visual pre-training} In the past few years, various pretext tasks are designed for self-supervised visual pre-training. For example, earlier pretext-based works adopt the pseudo labels based on the attributes of images to learn the representation, such as image colorization \cite{color}, jigsaw puzzle \cite{jigsaw}, context prediction \cite{doersch2015}, and rotation prediction \cite{rotation}, etc. Besides these approaches, there are two mainstream paradigms, \textit{i.e.}, contrastive learning and masked image modeling approaches, which will be further analyzed in the following subsection. \textbf{Contrastive learning:} Contrastive learning is an instance-level discriminative approach and has occupied a dominant position in visual pre-training. Contrastive learning methods, such as SimCLR \cite{simclr,simclr_v2}, MoCo \cite{moco,mocov2,mocov3}, and Swav \cite{swav}, \textit{etc.}, typically rely on data augmentation to create the counterparts of the images and aim at learning such an embedding space, where similar sample pairs are close to each other while dissimilar ones are far apart. Swav \cite{swav} proposes a cluster-based contrastive learning method to enforce consistency between cluster assignments under different augmentations. BYOL \cite{byol} and SiamSim \cite{siamsam} abandons the negative samples and avoids the collapse with either an additional momentum network or the stop-gradient operation. MoCov3 \cite{mocov3} extends the contrastive learning framework for transformers and further promotes the development of self-supervised vision Transformers. \textbf{Masked Image Modeling:} Motivated by the great success of BERT, masked image modeling (MIM) \cite{beit,ibot,mae,conmim,maskfeat,simmim,cae} becomes a new trend in self-supervised visual pre-training, which randomly masks parts of images and reconstructs them based on the corrupted image. ViT \cite{vit} attempts to adopt masked patch prediction for self-supervised learning. BEiT \cite{beit} predicts the discrete tokens of masked token resorting to an off-the-shelf discrete VAE. Instead of discretizing the visual information, MAE \cite{mae} and SimMIM \cite{simmim} propose to directly predict the pixel-level value as the reconstruction target. MaskFeat \cite{maskfeat} further exploits different supervision signals such as HOG feature to be the objective. iBOT \cite{ibot} performs masked prediction and adopts the teacher network as an online tokenizer to provide the supervision. PeCo \cite{peco} further provides the evidence that the perceptually-aware tokenizer will provide better pre-training performance for the masked image modeling. \section{Preliminaries} \subsection{Image BERT Pre-training with Masked Image Modeling} The paradigm of mask-and-then-predict is first introduced in BERT pre-training \cite{BERT} of NLP tasks to encourage bidirectional context understanding of the textual signals. Recent works \cite{beit,ibot} reproduce the success of BERT by employing the proxy task of masked image modeling (MIM) on image pre-training of vision Transformers \cite{vit,deit,swinT}. MIM requires randomly masking a proportion of the image patches and then training the vision Transformer to recover the corrupted image via reasoning among the visual context. The pretext task of MIM enables a more fine-grained understanding of the local visual semantics compared to the contrastive counterparts \cite{simclr,moco}. Vision Transformers pre-trained with MIM objectives can be well transferred to a wide range of downstream tasks, \textit{i.e.}, classification, segmentation, and detection, after fine-tuning. \subsection{Masked Image Modeling as Single-choice Classification} Introducing the mask-and-then-predict paradigm into image pre-training is actually non-trivial, because the visual signals are continuous and cannot be predicted resorting to a well-defined vocabulary. A pioneering work, BEiT \cite{beit}, tackles the challenge by casting masked patch prediction as a single-choice classification problem via discretizing the image into vision tokens with an off-the-shelf ``tokenizer''. The ``tokenizer'' can be a discrete auto-encoder \cite{dalle,taming} pre-learned towards the reconstruction objective. Formally, given a raw image $x\in\mathbb{R}^{C\times H \times W}$, it is initially divided into $N$ patches $\{x_i\}_{i=1}^{N}$ and then mapped into compact patch embeddings. We denote the corrupted image as $\hat{x}$, which is formed by masking part of the patches in $x$, and we denote the set of masked patch indices as $\mathcal{M}$. We encode the image patch features $f(\hat{x})\in\mathbb{R}^{N\times D}$ with high-level perceptions by feeding $\hat{x}$ into the vision Transformer. The patch features are further projected to the probabilities of the vision token ids using an MLP head which will be dropped for downstream tasks. We denote the probability vectors as $q(f(\hat{x}))\in\mathbb{R}^{N\times V}$ where $V$ is the length of the visual vocabulary defined by the pre-learned image ``tokenizer''. To receive the answers for the masked image modeling, we discrete the raw image $x$ into vision tokens $\{z_i\}_{i=1}^{N}$ using the image ``tokenizer'', where $z_i\in\mathbb{R}^{V}$. The assigned token id with the maximal probability in $z_i$ is termed as $y_i$. The pre-training objective is formulated as a hard-label cross-entropy loss to encourage masked patch prediction with unique token ids as follow, \begin{equation} \mathcal{L}_\text{mim}(x)={\mathbb{E}_{i\in\mathcal{M}}\left[-\log q\left(y_i|f(\hat{x}_i)\right)\right]}. \end{equation} \section{\emph{mc}-BEiT} BEiT provides inspiring insights of casting masked image modeling (MIM) as a classification problem to bridge the gap between discrete words in NLP tasks and continuous visual signals in computer vision tasks. However, as there are no perfect answers for visual discretization, performing a strict mapping between patch predictions and unique token ids as a single-choice classification problem is actually a sub-optimal solution for MIM pre-training. As illustrated in Fig. \ref{fig:drawback}, there may exist multiple appropriate token ids for a certain patch, motivating us to boost the BEiT pre-training with multi-choice classification. \subsection{Masked Image Modeling as Multi-choice Classification} \begin{figure}[t] \begin{center} \includegraphics[width=0.9\textwidth]{overview.png} \caption{The overview of the proposed method, \emph{mc}-BEiT. We improve image BERT pre-training with multi-choice training objectives, which is composed of the soft probability vectors predicted by the off-the-shelf image “tokenizer” and further refined by high-level inter-patch perceptions. A proportion of image patches are randomly masked and then fed into the vision Transformer. The masked patch prediction is optimized towards eased and refined multi-choice token ids in the form of a soft-label cross-entropy loss. } \label{fig:overview} \end{center} \end{figure} We introduce an improved BERT-style image pre-training with eased and refined masked prediction targets, \textit{i.e.,} {multi-choice vision token ids}, rather than a unique answer. All possible token ids in the visual vocabulary will be assigned possibilities to be chosen. To this end, we soften the training objective from the original hard-label cross-entropy loss to a soft-label cross-entropy loss with the multi-choice targets $\hat{z}\in\mathbb{R}^{N\times V}$ as follow, \begin{equation}\label{eq:mc-mim} \mathcal{L}_\text{mc-mim}(x)={\mathbb{E}_{i\in\mathcal{M}}\left[-\sum_{k=1}^{V}\hat{z}_{i,k} \log q\left(f(\hat{x}_{i})\right)_k\right]}, \end{equation} where $\sum_{k=1}^{V}\hat{z}_{i,k}=1, \forall i$ and $q\left(f(\hat{x}_{i})\right)\in\mathbb{R}^{V}$. We will go over how to produce such refined multi-choice answers for MIM pre-training in the following section. \subsection{Multi-choice Visual Discretization} To produce multi-choice discretization without extra training stages or computational overhead, we attempt to exploit the predictions from the off-the-shelf image tokenizer. Given the discretization predictions $z\in\mathbb{R}^{N\times V}$ from the image tokenizer, we estimate the soft probabilities $p(z)\in\mathbb{R}^{N\times V}$ rather than using the unique predicted token id as done in the single-choice version. Specifically, the soft probability vector is obtained using a softmax operation, where a temperature coefficient $\tau$ is used to move between the sharpness (single-choice) and smoothness (multi-choice), \begin{equation} p(z_i)_k = \frac{\text{exp}(z_{i,k}/\tau)}{\sum_{j=1}^{V}\text{exp}(z_{i,j}/\tau)}. \end{equation} As discussed in the introduction section and illustrated in Fig \ref{fig:drawback}, semantically-similar patches may be allocated with discrepant token ids and semantically-dissimilar patches may be allocated with the same token id due to their low-level similarities, indicating that the raw predictions from the off-the-shelf tokenizer are sub-optimal to fully represent the semantic relations among patches. The phenomenon motivates us to refine the predictions of the tokenizer with inter-patch relations. The inter-patch relations can be estimated with their high-level perceptions, which are encoded by the in-training vision Transformer. Specifically, we calculate the cosine similarity between patch features to measure their affinities, \begin{equation} W(\hat{x}_i)_k=\frac{\text{exp}{\langle f(\hat{x}_i)}, {f(\hat{x}_k)}\rangle}{\sum_{j=1}^N{\text{exp}\langle{f(\hat{x}_i)}, {f(\hat{x}_j)}\rangle}}, \end{equation} where $W(\hat{x})\in\mathbb{R}^{N\times N}$ and $\langle\cdot,\cdot\rangle$ indicates the inner product between two feature vectors after $\ell_2$ normalization. Based on the observation that perceptually-similar patches ought to share their choices, we propagate the soft probabilities $p$ of different patches in an image $x$ to form a refined target $W(\hat{x}) p(z)\in\mathbb{R}^{N\times V}$. In this way, patches with similar high-level perceptions can provide complementary supervision signals for the masked patches. The overall objective of multi-choice image discretization is composed of the weighted sum of the aforementioned parts, where the semantic equilibrium coefficient $\omega$ is introduced to move between low-level semantics (directly predicted by the tokenizer) and high-level semantics (ensembled from the perceptually-similar patches). The former one adopts the eased supervision directly predicted from the tokenizer, while the latter one injects high-level perceptions by propagating among other semantically-similar patches, together forming the refined multi-choice targets $\hat{z}\in\mathbb{R}^{N\times V}$ as follow: \begin{equation} \hat{z}=\omega p(z) + (1-\omega)W(\hat{x})p(z), \end{equation} which is further used as the objectives for masked patch predictions in Eq. (\ref{eq:mc-mim}). \section{Experiments} \subsection{Pre-Training Setup} In our experiments, the images of 224$\times$224 resolution are divided into 14$\times$14 image sequences with 16$\times$16 patch size. We use different architectures such as ViT-Base/16 and ViT-Large/16 for pre-training and the backbone implementation follows \cite{vit} for fair comparisons. For the BERT-style visual pre-training, we randomly mask 75\% patches for masked image modeling. Inspired by PeCo \cite{peco}, we employ the off-the-shelf VQGAN of \cite{taming} as a better tokenizer, which is pre-trained on OpenImages \cite{OpenImages2} with the vocabulary size of 8192. In our experiments, the semantic equilibrium coefficient $\omega$ is 0.8 and the temperature coefficient $\tau$ is 4.0 by default. The vision Transformers are pre-trained for 800 epochs on the widely-acknowledged ImageNet-1K \cite{imagenet1k} dataset, which includes 1.28 million images. Note that the ground-truth labels are disabled for pre-training. We use 16 Nvidia A100 GPUs for pre-training and a batch size of 128 per GPU. We adopt simple image augmentation for pre-training, including random resized cropping and horizontal flipping. The detailed recipe of pre-training and finetuning is summarized in the Appendix. \begin{table}[t] \small \centering \caption{The top-1 fine-tuning accuracy of ImageNet-1K using ViT-Base and ViT-Large with different pre-training methods.} \label{table:imagenet1k} \setlength{\tabcolsep}{6mm}{ \begin{tabular}{llcc} \toprule[1pt] \multicolumn{1}{l}{Method} & Reference & Pre-train Epoch & Acc (\%) \\ \hline \multicolumn{4}{l}{\textsl{Supervised Pre-training (training from scratch):}}\\ \hline ViT-B/16 \cite{vit} & ICLR 2021 & - & 77.9 \\ ViT-L/16 \cite{vit} & ICLR 2021 & - & 76.5 \\ DeiT-B/16 \cite{deit} & ICML 2021 & - & 81.8 \\ \hline \multicolumn{4}{l}{\textsl{Self-supervised Pre-training using} ViT-B/16:}\\ \hline MoCo v3 \cite{mocov3} & CVPR 2021 & 300 & 83.2 \\ DINO \cite{dino} & ICCV 2021 & 300 & 82.8 \\ BEiT \cite{beit} & ICLR 2022 & 800 & 83.2 \\ iBOT \cite{ibot} & ICLR 2022 & 1600 & 83.8 \\ MAE \cite{mae} & CVPR 2022 & 1600 & 83.6 \\ SimMIM \cite{simmim} & CVPR 2022 & 800 & 83.8 \\ Ours & this paper & 800 & \bf{84.1} \\ \hline \multicolumn{4}{l}{\textsl{Self-supervised Pre-training using} ViT-L/16:}\\ \hline MoCo v3 \cite{mocov3} & CVPR 2021 & 300 & 84.1 \\ BEiT \cite{beit} & ICLR 2022 & 800 & 85.2 \\ MAE \cite{mae} & CVPR 2022 & 1600 & \textbf{85.9} \\ Ours & this paper & 800 & 85.6 \\ \bottomrule[1pt] \end{tabular} } \end{table} \subsection{Image Classification} For the ImageNet classification task, the fully-connected layer is employed as the classifier after the average pooling of the feature embeddings. We adopt top-1 accuracy after fine-tuning as the evaluation metric and we thoroughly compare our method with the supervised methods, \textit{i.e.,} ViT \cite{vit}, DeiT \cite{deit}, and recently published state-of-the-art self-supervised learning methods, \textit{i.e.,} MoCo v3 \cite{mocov3}, DINO \cite{dino}, BEiT \cite{beit}, and iBOT \cite{ibot}. Besides, we also compare with the very recent pixel-level MIM methods, \textit{i.e.,} MAE \cite{mae} and SimMIM \cite{simmim}. The experiment results are listed in Tab. \ref{table:imagenet1k}. As observed from the results, the proposed method obtains 84.1\% top-1 accuracy on ViT-B, outperforming the competing methods and achieving state-of-the-art performance. We can see that our \emph{mc}-BEiT shows significant gains compared to the baseline BEiT, which verifies the effectiveness of our introduced multi-choice objectives. Concretely, our method outperforms the recent state-of-the-art method iBOT \cite{ibot} by +0.3\% with the fewer 800 epochs pre-training. It is noted that iBOT adopts an extra teacher network and enables multi-crops for pre-training, showing lower efficiency than our method. \begin{table}[h] \small \centering \caption{The top-1 fine-tuning accuracy of ImageNet-1K using our \emph{mc}-BEiT with different training epochs and backbone architectures.} \label{table:imagenet_epochs} \setlength{\tabcolsep}{5mm}{ \begin{tabular}{lcccc} \toprule[1pt] \multicolumn{1}{c}{Method} & Arch. & Model Size& Pre-train Epoch & Acc (\%) \\ \hline \multicolumn{4}{l}{\textsl{Self-supervised Pre-training using} ViT-B/16:}\\ \hline Ours & ViT-B & 86M & 100 & 83.3 \\ Ours & ViT-B & 86M & 300 & 83.9 \\ Ours & ViT-B & 86M & 800 & \textbf{84.1} \\ \hline \multicolumn{4}{l}{\textsl{Self-supervised Pre-training using} ViT-L/16:}\\ \hline Ours & ViT-L & 307M & 300 & 85.2 \\ Ours & ViT-L & 307M & 800 & \textbf{85.6} \\ \bottomrule[1pt] \end{tabular} } \end{table} \noindent\textbf{Different training epochs and architectures:} We also provide more comprehensive results of different training epochs and architectures in Tab. \ref{table:imagenet_epochs}. From the table, we can see that our method can adapt well to different scales of vision tranformers, \textit{e.g.,} the mostly used ViT-B and ViT-L. It is worth noting that our method obtains a relatively high accuracy (already achieves the state-of-the-art performance) when pre-training for only 300 epochs. Moreover, the performance can be further improved with longer pre-training epochs, \textit{e.g.}, the accuracy reaches 84.1\% pre-training for 800 epochs. \begin{figure}[t] \begin{center} \includegraphics[width=0.7\textwidth]{convergence.png} \caption{The convergence curves when fine-tuning ViT-B models on ImageNet-1K classification. The models are pre-trained by different methods.} \label{fig:conver} \end{center} \end{figure} \noindent\textbf{Convergence curve:} In Fig \ref{fig:conver}, we further demonstrate the convergence curve of the supervised learning method and self-supervised learning methods, \textit{i.e.,} the baseline BEiT and our method, when fine-tuning ViT-B models. As shown in the figure, the proposed method achieves faster convergence as well as better performance than training DeiT from scratch \cite{deit}. Meanwhile, our method obtains obvious and consistent performance gains compared to the baseline method BEiT, showing the superiority of the proposed multi-choice training objectives. \subsection{Object Detection and Instance Segmentation} For object detection and instance segmentation tasks, COCO \cite{coco} benchmark is employed to validate the pre-training performances. We follow the implementation of \cite{benchmarking,mimdet} and the model is trained for 25 epochs (we also provide another evaluation setting following iBOT \cite{ibot} in the Appendix). ViT-B is adopted as the backbone and Mask-RCNN \cite{maskrcnn} is used as the task head. The evaluation metrics for objection detection and instance segmentation are bounding box AP and mask AP, respectively. \begin{table}[h] \small \centering \caption{Experiment results of object detection and instance segmentation on COCO. We follow the implementation of \cite{benchmarking,mimdet} and the model is trained for 25 epochs. Intermediate fine-tuning denotes the model is further fine-tuned on ImageNet-1K. } \label{coco} \setlength{\tabcolsep}{3.5mm}{ \begin{tabular}{l|lcc} \toprule[1pt] \multicolumn{1}{l|}{\multirow{2}{*}{Method}} & \multicolumn{1}{l}{\multirow{2}{*}{Reference}} & \multicolumn{1}{c}{Object Det.} & Instance Seg. \\ \multicolumn{1}{l|}{} & \multicolumn{1}{c}{} & \multicolumn{1}{c}{$\text{AP}^{b}$} & \multicolumn{1}{c}{$\text{AP}^{m}$} \\ \hline Supervised \cite{deit} & ICML 2021 & 46.5 & 41.7\\ MoCo v3 \cite{mocov3} & CVPR 2021 & 46.6 & 41.9 \\ DINO \cite{dino} & ICCV 2021 & 47.6 & 42.3 \\ MAE \cite{mae} & CVPR 2022 & 48.0 & 43.0 \\ iBOT \cite{ibot} & ICLR 2022 & 48.4 & 42.9 \\ BEiT \cite{beit} & ICLR 2022 & 47.6 & 42.2 \\ Ours & this paper & 48.5 & 43.1 \\ \hline +Intermediate Fine-tuning \\ \hline BEiT \cite{beit} & ICLR 2022 & 48.4 & 43.5 \\ Ours & this paper & \textbf{49.2} & \textbf{44.0} \\ \bottomrule[1pt] \end{tabular} } \end{table} As observed in Tab. \ref{coco}, the BERT style pre-training shows superiority to supervised pre-training in terms of performances. Our method achieves 48.5\% and 43.1\% in $\text{AP}^{b}$ and $\text{AP}^{m}$. Meanwhile, the proposed method outperforms the competitor BEiT with +0.9\%/+0.9\% gain in $\text{AP}^{b}$ and $\text{AP}^{m}$. We also evaluate the performance after intermediate fine-tuning, the relative improvement is still obvious, \textit{i.e.,} +0.8\%/+0.5\% to BEiT. Our method even outperforms the recent pixel-level MIM method MAE and obtains better performances compared to state-of-the-art methods. \subsection{Semantic Segmentation} Semantic segmentation belongs to the pixel-level classification task and is often adopted to evaluate the pre-training performance on downstream tasks. Here we evaluate the performance on ADE20k \cite{ade20k} benchmark and mean intersection over union (mIOU) averaged over all semantic categories is adopted as the evaluation metric. Following the common setting in \cite{beit,ibot}, ViT-B is adopted as the default backbone and UPerNet \cite{upernet} is used for semantic segmentation task head. \begin{table}[t] \small \centering \caption{Results of semantic segmentation on ADE20K. Intermediate fine-tuning denotes the pre-trained model has been fine-tuned on ImageNet-1K classification. } \label{table:ade20k} \setlength{\tabcolsep}{7mm}{ \begin{tabular}{l|lc} \toprule[1pt] \multicolumn{1}{l|}{Method} & Reference & mIOU \\ \hline Supervised \cite{deit} & ICML 2021 & 45.3 \\ MoCo v3 \cite{mocov3} & CVPR 2021 & 47.2 \\ DINO \cite{dino} & ICCV 2021 & 46.8 \\ MAE \cite{mae} & CVPR 2022 & 48.1 \\ iBOT \cite{ibot} & ICLR 2022 & 50.0 \\ BEiT \cite{beit} & ICLR 2022 & 45.6 \\ Ours & this paper & 47.0 \\ \hline +Intermediate Fine-tuning \\ \hline BEiT \cite{beit} & ICLR 2022 & 47.7 \\ Ours & this paper & \textbf{50.8} \\ \bottomrule[1pt] \end{tabular} } \end{table} Because the pre-training process does not introduce the instance discrimination, the performance can be further improved after intermediate fine-tuning on ImageNet-1K according to BEiT \cite{beit}. Therefore we also compare the performance after intermediate fine-tuning. Tab. \ref{table:ade20k} shows that our method significantly improves the transferability of pre-trained models compared to the supervised learning, with +5.5\% performance gain. It is also noticed that our method outperforms recent state-of-the-art self-supervised methods. It achieves better results as 47.0\%/50.8\% mIOU and improves +1.4\%/3.1\% gain to its pre-training only version. \section{Ablation Study} In this section, we conduct an extensive ablation study of our method on ImageNet-1K. Considering the time expenditure, all ablation experiments are performed under 100-epoch pre-trained ViT-B/16 on ImageNet-1K. \subsection{The temperature coefficient $\tau$} The hyper-parameter of temperature coefficient $\tau$ is to scale the logits from the tokenizer, which moves between the sharpness (single-choice) and smoothness (multi-choice). We adopt the common values for temperature to ablate its effect. In general, the small temperature will sharp the probability distribution and the large one will smooth it conversely. When $\tau$ is extremely small, it is an approximate single-choice classification task. The ablation is shown in the Fig. \ref{fig:hyper}(a), where \textit{single-choice label} indicates training with the strict mapping to the unique answer. From the result, we can observe that multi-choice vision token improves the BERT style pre-training performance and it behaves better when setting temperature factor at 4.0 empirically. \subsection{The semantic equilibrium coefficient $\omega$} The semantic equilibrium coefficient $\omega$ is introduced to move between low-level semantics (directly predicted by the tokenizer) and high-level semantics (ensembled from the perceptually-similar patches). The ablation study is shown in Fig. \ref{fig:hyper}(b). When setting $\omega$ to 0, the objective relies on totally the inter-relationship guided objective and it achieves only 81.8\% accuracy, which is because the inevitable noise of calculating patch similarity, especially in the early epochs, will cause collapse and degrade the pre-learning performance. As the coefficient goes larger, it shows consistent gains over baseline. When setting $\omega$ to 1.0, the objective comes only from the low-level signals of the tokenizer and the performance is still higher than baseline, which shows the superiority of multi-choice to single-choice. As observed from the results, the semantic equilibrium coefficient is thus set to be 0.8 for better performances. \begin{figure}[H] \begin{center} \includegraphics[width=0.8\textwidth]{hyper.png} \caption{Ablation study on the hyper-parameters.} \label{fig:hyper} \end{center} \end{figure} \subsection{Masking strategy} In the masked image modeling approach, the masking strategy determines the difficulty of inferring the missing patches. Tab. 3 shows the influence of different mask strategies, where \textit{Block} and \textit{Random} masking types and different mask ratios are conducted for ablation. It is observed from the results that the random masking strategy with 75\% masking ratio makes the best performances, which is thus adopted as the default setting for pre-training. \begin{table}[t] \small \centering \caption{Ablation study on different masking strategies.} \label{table:pacs} \setlength{\tabcolsep}{7mm}{ \begin{tabular}{c|cc} \toprule[1pt] \multicolumn{1}{c|}{Masking Strategy} & Masking Ratio & Acc (\%) \\ \hline Block & 45 \% & 83.2 \\ Block & 60 \% & 83.2 \\ Block & 75 \% & 82.8 \\ \hline Random & 45 \% & 83.0 \\ Random & 60 \% & 83.1 \\ Random & 75 \% & \textbf{83.3} \\ Random & 90 \% & 83.0 \\ \bottomrule[1pt] \end{tabular} } \end{table} \subsection{Tokenizer} In the BERT-style visual pre-training, the tokenizer plays the role of a vocabulary in texts and is used to produce the discrete vision token as supervision. As discussed in PeCo \cite{peco}, perceptually-aware tokenizer may benefit the image BERT pre-training, so we introduce to use off-the-shelf VQGAN \cite{taming} as a better tokenizer throughout our experiments. Besides, we would like to also verify the effectiveness of our multi-choice objectives on top of the vanilla BEiT. \begin{table}[h] \small \centering \caption{Ablation study on the different tokenizer.} \label{tokenizer} \setlength{\tabcolsep}{4mm}{ \begin{tabular}{c|c|c|c|c} \toprule[1pt] \multicolumn{1}{l|}{} & \multicolumn{2}{c|}{Training Data} & \multicolumn{2}{c}{Top 1 Acc. (100 / 800 epochs)} \\ \cline{2-5} \multicolumn{1}{l|}{} & \multicolumn{1}{c|}{Source} & \multicolumn{1}{c|}{Scale} & BEiT & \multicolumn{1}{c}{Ours} \\ \hline \multicolumn{1}{c|}{DALL-E \cite{dalle}} & Private & 250M & 82.3 / 83.2 & 82.6 / 83.7 \\ \multicolumn{1}{c|}{VQGAN \cite{taming}} & OpenImage & 9M & 82.9 / 83.8 & 83.3 / 84.1\\ \bottomrule[1pt] \end{tabular} } \end{table} The influence of tokenizers is shown in Tab. \ref{tokenizer}. It is shown that adopting the VQGAN as the tokenizer brings better performance than DALL-E, which verify our observation that tokenizer with high semantics can indeed improve the pre-training performance. It also indicates that enhancing the semantic relation is beneficial to visual pre-training. Meanwhile, it is noticed that the relative improvement of our method is consistent regardless of different kinds of tokenizers, which demonstrates the effectiveness of the proposed method. \subsection{Visualization} Besides the quantitative experiment results, we further provide some visualizations in Fig. \ref{vis} for better understanding the effects of our multi-choice answers. 75\% patches of the images are randomly masked for prediction. It can be observed from the blue box in Fig. \ref{vis}(a), the adjacent patches with similar semantics are still allocated with different vision token ids, indicating that the hard vision token id directly from the tokenizer neglects the semantic relations and is a sub-optimal objective. In contrast, the proposed eased and refined objective can provide diverse possible vision tokens for the prediction. As shown in our multi-choice token signals, the semantically-similar patches have the possibility to be allocated with the same vision token, which refines the objective with inter-patch perceptions. Furthermore, we randomly select a masked patch and shows the inter-patch perception relations (obtained from the patch feature similarity) learned by the pre-trained model in Fig. \ref{vis}(c). The similar patches can still be well estimated even under heavy random masking and the inter-patch relation shows higher responses, \textit{e.g,} the skeleton of the car. It demonstrates that the informative semantic relations estimated by the in-training vision Transformer can properly enhance the multi-choice discretization for pre-training. \begin{figure}[t] \begin{center} \includegraphics[width=0.75\textwidth]{vis.png} \caption{The visualization is obtained using the off-the-shelf tokenizer and our pre-trained vision Transformer. The inter-patch perception relation is equipped with contour lines for better visual effect.} \label{vis} \end{center} \end{figure} \section{Conclusion} In this paper, we propose the \emph{mc}-BEiT, \textit{i.e.,} multi-choice discretization for improving image BERT pre-training. Instead of adopting the unique label signals from the tokenizer, we introduce an eased and refined objective for providing multi-choice answers. Extensive experiments are conducted to evaluate the performances of our method. The empirical results show that \emph{mc}-BEiT achieves the state-of-the-art performances on various tasks, such as image classification, semantic/instance segmentation, and objection detection. \section*{Acknowledgement} \label{acknowlegement} This work was supported by the National Natural Science Foundation of China under Grant 62088102, and in part by the PKU-NTU Joint Research Institute (JRI) sponsored by a donation from the Ng Teng Fong Charitable Foundation. \clearpage \bibliographystyle{splncs04}
{'timestamp': '2022-07-29T02:09:10', 'yymm': '2203', 'arxiv_id': '2203.15371', 'language': 'en', 'url': 'https://arxiv.org/abs/2203.15371'}
arxiv
\section{Introduction} \label{sec_intro} Many real-world applications can be modeled as multiobjective combinatorial optimization (MOCO) problems~\citep{ehrgott2000survey}. Examples include the multiobjective traveling salesman problem (MOTSP)~\citep{lust2010multiobjective}, the multiobjective vehicle routing problem (MOVRP)~\citep{jozefowiez2008multi} and the multiobjective knapsack problem (MOKP)~\citep{bazgan2009solving}. These problems have multiple objectives to optimize, and no single solution can optimize all the objectives at the same time. Instead, there is a set of Pareto optimal solutions with different trade-offs among the objectives. It is very challenging to find all the exact Pareto optimal solutions for a MOCO problem. Actually, finding one single Pareto optimal solution can be NP-hard for many problems~\citep{ehrgott2000survey}, and the number of Pareto solutions could be exponentially large with regard to the problem size~\citep{ehrgott2005multicriteria,herzel2021approximation}. The decision-maker's preference among different objectives is usually unknown in advance, making it very difficult to reduce the problem into a single-objective one. Over the past several decades, many methods have been developed to find an approximate Pareto set for different MOCO problems within a reasonable computational time. These methods often need carefully handcrafted and specialized heuristics for each problem. It can be very labor-intensive in practice. In many real-world applications, practitioners need to solve many different instances for the same particular problem, where the instances can be easily obtained or generated~\citep{bengio2020machine}. It is desirable to learn the patterns behind these problem instances explicitly or implicitly to design efficient algorithms~\citep{cappart2021combinatorial}. Machine learning techniques can be naturally used for this purpose. Some learning-based methods have been recently proposed for solving single-objective combinatorial optimization problems~\citep{bengio2020machine,vesselinova2020learning,mazyavkina2020reinforcement,cappart2021combinatorial}. In this work, we extend the learning-based method to solve MOCO problems in a principled way as shown in Figure~\ref{fig_moco_framework}. Our main contributions include: \begin{itemize} \item We propose a novel neural multiobjective combinatorial optimization method to approximate the whole Pareto set via a single preference-conditioned model. It allows decision makers to obtain any preferred trade-off solution without any search effort. \item We develop an efficient end-to-end reinforcement learning algorithm to train the single model for all different preferences simultaneously, and a simple yet powerful active adaption method to handle out-of-distribution problem instances. \item We conduct comprehensive experiments on MOTSP, MOVR and MOKP of different settings. The results show that our proposed method can successfully approximate the Pareto sets for different problems in an efficient way. It also significantly outperforms other methods in terms of solution quality, speed, and model efficiency. \end{itemize} \section{Background and Related Work} \label{sec_related_work} \begin{figure}[t] \centering \includegraphics[width= 1.0 \linewidth]{Figures/neural_moco_idea.pdf} \caption{\textbf{Preference-Conditioned Neural Multiobjective Combinatorial Optimization:} \textbf{a)} The model takes a problem instance as its input. \textbf{b)} The decision makers assign their preferences on different objectives to the model. \textbf{c)} The model directly generates approximate Pareto solutions with different trade-offs via fast forward inference. In this example, the problem is the MOTSP with two cost objectives to minimize. The generated solutions $P_1$,$P_2$ and $P_3$ are different optimal trade-offs between the two cost objectives. The ideal model can generate solutions for all possible optimal trade-offs on the Pareto front and not generate a poor solution such as $P_4$.} \label{fig_moco_framework} \vspace{-0.2in} \end{figure} \textbf{Multiobjective Combinatorial Optimization (MOCO). } MOCO has been attracting growing research efforts from different communities over the past several decades~\citep{sawaragi1985theory, wallenius2008multiple, herzel2021approximation}. There are two main approaches to tackle the MOCO problems: the exact methods and the approximation methods~\citep{ehrgott2005multicriteria}. Exact methods could be prohibitively costly when, as it often happens, the MOCO problem is NP-hard and the problem size is very large~\citep{florios2014generation}. For this reason, many heuristics~\citep{jaszkiewicz2002genetic,zhang2007moea, ehrgott2008hybrid} and approximation methods~\citep{papadimitriou2000approximability, herzel2021approximation} have been developed to find a manageable number of approximated Pareto solutions with a reasonable computational budget. However, these methods usually depend on carefully handcrafted designs for each specific problem~\citep{ehrgott2000survey}, and the required effort is often nontrivial in real-world applications. \textbf{Machine Learning for Combinatorial Optimization. } As summarized in \citet{bengio2020machine}, there are three main learning-based approaches for combinatorial optimization: learning to configure algorithms~\citep{kruber2017learning,bonami2018learning}, learning alongside the algorithms~\citep{lodi2017learning, gasse2019exact, chen2019learning}, and learning to directly predict the solutions~\citep{nowak2018revised,emami2018learning,larsen2018predicting}. Neural combinatorial optimization (NCO) belongs to the last category where the model directly produces a good solution for a given problem instance. \citet{vinyals2015pointer} proposed a pointer network to sequentially construct a solution for the TSP problem. \citet{bello2016neural} made a critical improvement to use reinforcement learning to train the model, eliminating the impractical optimal solutions collection for NP-hard problems. Some other improvements on model structure and training procedure have been proposed in the past few years~\citep{nazari2018reinforcement, deudon2018learning, kool2019attention, velivckovic2021neural}, especially with graph neural networks (GNNs)~\citep{dai2017learning,li2018combinatorial,joshi2019efficient,dwivedi2020benchmarking, drori2020learning}. Recent efforts have been made on more efficient learning strategies~\citep{kwon2020pomo, karalias2020erdos, lisicki2020evaluating, geisler2022generalization}, learning-based graph search~\citep{cappart2021combining, kool2021deep,fu2021generalize, xin2021neurolkh, hudson2022graph}, and iterative improvement methods~\citep{wu2021learning,ma2021learning,li2021learning}. \textbf{Neural MOCO.} Most of the existing learning-based methods are for single-objective combinatorial problems. Recently, a few attempts have been made to solve MOCO problems~\citep{li2020deep,wu2020modrl, zhang2021modrl,zhang2021meta}. These methods adopt the MOEA/D framework~\citep{zhang2007moea} to decompose a MOCO problem into a number of single-objective subproblems, and then build a set of models to solve each subproblem separately. However, since the number of Pareto solutions would be exponentially large~\citep{ehrgott2005multicriteria}, the required number of models would be huge for finding the whole Pareto set. In this work, we propose a single preference-conditioned model for solving MOCO problems, with which the decision makers can easily obtain any trade-off solutions. The proposed single neural MOCO solver could be much easier to use in a real-world system~\citep{velivckovic2021neural}, than those using a large set of different models. \section{Problem Formulation} \label{sec_pareto_mtl} \subsection{Multiobjective Combinatorial Optimization} A multiobjective combinatorial optimization (MOCO) problem can be defined as follows: \begin{align}\label{problem_moco} \min_{x \in \mathcal{X}} \ F(x) = (f_1(x),f_2(x),\ldots, f_m(x)), \end{align} where $\mathcal{X}$ is a discrete search space, and $F(x) = (f_1(x),\ldots, f_m(x))$ is an $m$-objective vector. Since the individual objectives conflict each other, no single solution can optimize all of them at the same time. Therefore, practitioners are interested in Pareto optimal solutions, defined as follows. \textbf{Definition 1 (Pareto Dominance).} Let $x_a,x_b \in \mathcal{X}$, $x_a$ is said to dominate $x_b$ ($x_a \prec x_b$) if and only if $f_i(x_a) \leq f_i(x_b), \forall i \in \{1,...,m\}$ and $f_j(x_a) < f_j(x_b), \exists j \in \{1,...,m\}$. \textbf{Definition 2 (Pareto Optimality).} A solution $x^{\ast} \in \mathcal{X}$ is a Pareto optimal solution if there does not exist $\hat x \in \mathcal{X}$ such that $\hat x \prec x^{\ast}$. The set of all Pareto optimal solutions is called the Pareto set, and the image of the Pareto set in the objective space is called the Pareto front. Each Pareto solution represents an optimal trade-off among the objectives, and it is impossible to further improve one of the objectives without deteriorating any other objectives. \subsection{Decomposition and Preference-based Scalarization} \label{subsec_preference} Decomposition is a mainstream strategy for solving multiobjective optimization problem~\citep{zhang2007moea}. It decomposes a multiobjective problem into a number of subproblems, each of which can be a single objective or multiobjective optimization problem. MOEA/D~\citep{zhang2007moea} and its variants~\citep{trivedi2016survey} solve these subproblems in a collaborative manner and generate a finite set of Pareto solutions to approximate the Pareto front. The most widely used way for constructing a single objective subproblem is the preference-based scalarization ~\citep{ehrgott2005multicriteria,miettinen2012nonlinear}. For an $m$-objective optimization problem, a preference vector for the objective functions can be defined as $\lambda \in R^m$ that satisfies $\lambda_i \geq 0$ and $\sum_{i=1}^{m} \lambda_i = 1$. \textbf{Weighted-Sum Aggregation} is the simplest approach. It defines the aggregation function to minimize in the subproblem associated with $\lambda$ as \begin{eqnarray}\label{ws_decomposition} g_{\text{ws}}(x|\lambda) = \sum_{i=1}^{m}\lambda_i f_i(x). \end{eqnarray} However, this approach can only find solutions on the convex hull of the Pareto front~\citep{ehrgott2005multicriteria}. \textbf{Weighted-Tchebycheff (Weighted-TCH) Aggregation} is an alternative approach to minimize: \begin{eqnarray}\label{tch_decomposition} g_{\text{tch}}(x|\lambda) = \max_{1 \leq i \leq m} \{ \lambda_i |f_i(x) - z^*_i| \}, \end{eqnarray} where $z^*_i < \min_{x \in \mathcal{X}} f_i(x)$ is an ideal value for $f_i(x)$. Any Pareto optimal solution could be an optimal solution of problem~(\ref{tch_decomposition}) with a specific (but unknown) preference $\lambda$~\citep{choo1983proper}. \subsection{Current Drawbacks and Our Method} \begin{figure*}[!t] \centering \subfloat[$105$ Preferences]{\includegraphics[width = 0.25\textwidth]{Figures/3obj_MOTSP50_pref105_v2.pdf}} \subfloat[$105$ Solutions]{\includegraphics[width = 0.25\textwidth]{Figures/3obj_MOTSP50_sample105_v2.pdf}} \subfloat[$1,035$ Solutions]{\includegraphics[width = 0.25\textwidth]{Figures/3obj_MOTSP50_sample1035_v2.pdf}} \subfloat[$10,011$ Solutions]{\includegraphics[width = 0.25\textwidth]{Figures/3obj_MOTSP50_sample10011_v2.pdf}} \caption{ \textbf{Pareto Set Approximation for a New Problem Instance:} Our method with different numbers of preferences on three objective MOTSP with 50 nodes. \textbf{a)\&b)} With a small number of preferences, our model can generate a sparse approximation to the Pareto set. \textbf{c)\&d)} With a large number of preferences, it can generate a dense approximation. Our method can generate any trade-off solutions with a single model without searching, whereas other methods need to solve or build a model for each preference separately. More discussions can be found in Appendix~\ref{supp_subsec_weight}~\ref{supp_subsec_connection}~\ref{supp_subsec_motsp_asymmetric}~\ref{supp_subsec_pref_inference}.} \label{fig_3obj_motsp} \vspace{-0.2in} \end{figure*} \textbf{Drawbacks of Existing Methods.} For many MOCO problems, the size of the Pareto set would be exponentially large with respect to the input size (e.g., nodes in MOTSP). It is computationally impractical for existing methods to find the whole Pareto set~\citep{herzel2021approximation}. For this reason, all of the existing heuristic-based and learning-based methods are to find a small subset of approximate Pareto solutions. Decision makers can only select solutions from this small set, which often does not contain their preferred solutions. In addition, scalarization may also produce a complicated single objective subproblem. For example, the Tchebycheff scalarized subproblem of MOTSP is not a classic TSP, and thus cannot be solved by the highly specialized TSP solvers such as LKH~\citep{helsgaun2000effective} or Concorde~\citep{applegate2007traveling}. \textbf{Our Method.} Instead of finding a set of finite solutions, we propose a novel way to approximate the whole Pareto set using a single model. With our proposed model, decision makers can easily obtain any solution from the approximate Pareto set to satisfy their preferred trade-offs in real time as shown in Figure~\ref{fig_3obj_motsp}. This is a clear advantage to support interactive decision making. In addition, our proposed reinforcement learning based method can use a scalarization method to combine multiobjective rewards, and does not need to consider the problem-specific condition. In this paper, we mainly consider learning the whole Pareto front. It is possible to incorporate decision-maker's preferences on specific regions for model building and inference as discussed in Appendix~\ref{supp_subsec_motsp_asymmetric}. We believe our proposed method is a new principled way to solve multiobjective combinatorial optimization problems. \section{The Proposed Model: Preference-Conditioned Neural MOCO} \label{proposed_method} \subsection{Preference-Conditioned Solution Construction} Decomposition and scalarization link preferences to their corresponding Pareto solutions. This work builds a preference-conditioned model to accommodate all the preferences. We use the MOTSP as an example to explain our model design. In an MOTSP instance $s$, a fully connected graph of $n$ nodes (cities) with $m$ distance metrics on each edge is given. A feasible solution is a tour that visits each city exactly once and returns to the starting city. The $i$-th objective to minimize is the tour length (total cost) based on the $i$-th distance metric. A tour can be represented as $\vpi = (\pi_1, \cdots, \pi_t, \cdots, \pi_n), \pi_t \in \{1,\cdots, n\}$, a permutation of all the nodes defining the order in which $n$ cities is visited. Our model defines a preference-conditioned stochastic policy $p_{{\bm{\theta}}(\lambda)}(\vpi|s)$ parameterized by ${\bm{\theta}}(\lambda)$ to construct a valid solution in sequence: \begin{eqnarray}\label{stochastic_policy} p_{{\bm{\theta}}(\lambda)}(\vpi | s) = \textstyle\prod_{t = 1}^{n} p_{{\bm{\theta}}(\lambda)}(\vpi_t | s, \vpi_{1: t-1}). \end{eqnarray} The goal is to learn an optimal preference-conditioned policy $p_{{\bm{\theta}}(\lambda)}(\pi | s)$ to construct tours with the lowest scalarized costs for each preference $\lambda$. \subsection{The Proposed Model} \begin{figure*}[t] \centering \includegraphics[width= 0.85\linewidth]{Figures/neural_moco_model.pdf} \caption{\textbf{Preference-conditioned Neural MOCO Model:} \textbf{a)} The input is a problem instance $s$ (e.g., a graph). \textbf{b)} A shared attention encoder transfers the instance $s$ into a set of embeddings. \textbf{c)} The embeddings for all nodes would be used by the decoder multiple times with different preferences. \textbf{d)} A MLP takes the preference $\lambda$ as input, and generates the parameters for the decoder. \textbf{e)} The preference-conditioned attention decoder directly generates different approximate Pareto solutions for different preferences. The trainable parameters are in the \textcolor{applegreen}{\textbf{attention encoder}} and \textcolor{arylideyellow}{\textbf{MLP model}}. } \label{fig_neural_moco_model} \vspace{-0.2in} \end{figure*} We propose to use an Attention Model (AM)~\citep{kool2019attention} as our basic encoder-decoder model as shown in Figure~\ref{fig_neural_moco_model}. For the MOCO problems considered in this work, a preference-agnostic encoder is capable to transfer problem instances into embeddings (e.g., embedding for all cities) used in the preference-conditioned decoder. In our model, only the decoder's parameters ${\bm{\theta}}_{\text{decoder}}(\lambda)$ are conditioned on the preference $\lambda$: \begin{eqnarray}\label{shared_encoder} {\bm{\theta}}(\lambda) = [{\bm{\theta}}_{\text{encoder}},{\bm{\theta}}_{\text{decoder}}(\lambda)]. \end{eqnarray} \textbf{Preference-agnostic Encoder.} The encoder takes a problem instance $s$ (e.g., an MOTSP instance with $n$ cities) as its input, and outputs a set of $d$-dimensional node embeddings $\{{\bm{h}}_1, \cdots, {\bm{h}}_n \}$ for each city. For a given instance, the same embeddings can be used for different preferences. Hence we only need a single forward pass for the dense encoder. We use the attention-based encoder as in \citet{kool2019attention} for all preferences. \textbf{Preference-based Attention Decoder.} The decoder has the same structure as in the attention-based model~\citep{kool2019attention}, but with parameters ${\bm{\theta}}_{\text{decoder}}(\lambda) = [W_Q(\lambda), W_K(\lambda), W_V(\lambda), W_{\text{MHA}}(\lambda)]$ conditioned on the preference $\lambda$. It takes the nodes embeddings for all cities as input, and sequentially selects the next node $\vpi_t$ with probability $p_{{\bm{\theta}}(\lambda)}(\vpi_t | s, \vpi_{1: t-1})$. At time step $t$, the decoder first constructs a context embedding $\hat {\bm{h}}_{(C)} = [{\bm{h}}_{\vpi_1}, {\bm{h}}_{\vpi_{t-1}}]W_Q(\lambda)$ from the first selected node ${\bm{h}}_{\vpi_1}$, and the last selected node ${\bm{h}}_{\vpi_{t-1}}$. The matrix $W_Q(\lambda) \in \bbR^{2d \times d}$ projects the concatenated $2d$-dimensional vector to a $d$-dimensional vector. Then we further aggregate the context embedding via a Multi-Head Attention (MHA)~\citep{vaswani2017attention} with the embeddings for all cities $\{{\bm{h}}_1,\cdots,{\bm{h}}_n\}$: \begin{eqnarray}\label{multi_head_embedding} {\bm{h}}_{(C)} = \textbf{MHA}(Q = \hat {\bm{h}}_{(C)}, K = \{{\bm{h}}_1,\cdots,{\bm{h}}_n\}W_K(\lambda), V = \{{\bm{h}}_1,\cdots,{\bm{h}}_n\}W_V(\lambda))W_{\textbf{MHA}}(\lambda), \end{eqnarray} where $Q,K,V$ are the query, key and value for MHA, respectively. $W_{\textbf{MHA}}(\lambda)$ represents the MHA parameters. The context embedding $h_{(C)}$ contains all information for the instance and the current partial tour at step $t$. We can calculate the logit for selecting each city with its embedding $h_j$: \begin{eqnarray}\label{single_head_logits} \text{logit}_j = \left\{ \begin{array}{ll} C \cdot \tanh(\frac{{\bm{h}}_{(C)}^T{\bm{h}}_j}{\sqrt{d}}) &\text{if } j \neq \vpi_{t^{\prime}} \quad \forall t^{\prime} < t, \\ -\infty & \text{otherwise}. \end{array} \right. \end{eqnarray} All already visited cities are masked with $-\infty$ and will not be selected as the next city. The logits of the rest cities are clipped into $[-C,C]\ (C = 10)$ as in the AM model~\citep{kool2019attention}. The probability for choosing the $j$-th city at time step $t$ can be calculated as $p_{{\bm{\theta}}(\lambda)}(\vpi_t = j | s, \vpi_{1: t-1}) = {e^{\text{logit}_j}} / {\sum_k e^{\text{logit}_k}}$. With this probability, the decoder can construct a feasible tour. One remaining designing issue is how to generate the preference-conditioned parameters ${\bm{\theta}}_{\text{decoder}}(\lambda)$. Multiplicative interactions~\citep{jayakumar2020multiplicative} and hypernetwork~\citep{schmidhuber1992learning,ha2017hypernetworks} provide a powerful and efficient way for conditional computation, which is widely used for transfer learning~\citep{oswald2020continual,ehret2020continual, lin2020controllable, navon2021learning}. We use a simple MLP hypernetwork ${\bm{\theta}}_{\text{decoder}}(\lambda) = \text{MLP}(\lambda | \vpsi)$ to generate the decoder parameters conditioned on the preference. The details of our proposed model can be found in Appendix~\ref{supp_sec_model_detail}. \textbf{Instance Augmentation for MOCO.} Our proposed model only has a small extra computational and memory overhead to the original single-objective AM solver. We keep our model as simple as possible, making it easy for our approach to use other models and other improvements developed for single-objective NCO. These properties are crucially important for generalizing the NCO to multiobjective problems. In this work, we simply extend the instance augmentation method~\citep{kwon2020pomo} to MOCO. The details can be found in Appendix~\ref{supp_subsec_augmentation}. \section{Preference-conditioned Multiobjective Policy Optimization} \subsection{Cost Function} Our proposed node selection strategy guarantees that the model can always generate feasible solutions. In this section, we develop an efficient multiobjective policy optimization method to train the model for all the preferences simultaneously. For an MOTSP problem, the objective functions are a vector of $m$ different costs (i.e. lengths) for a tour $L(\vpi) = [L_1(\vpi),\cdots,L_m(\vpi)]$. We can define a weighted-Tchebycheff scalarized cost for each preference $\lambda$: \begin{eqnarray}\label{scalar_cost_tch} L(\vpi|\lambda) = \max_{1 \leq i \leq m} \{ \lambda_i |L_i(\vpi) - (z^*_i - \varepsilon)| \}, \end{eqnarray} where $z^*_i$ is an ideal cost for the $i$-th objective. For a given instance $s$, our goal is to minimize the expected cost for all preferences: \begin{eqnarray}\label{expected_cost} \mathcal{J}({\bm{\theta}} | s) = \bbE_{\lambda \sim \Lambda, \vpi \sim p_{{\bm{\theta}}(\lambda)}(\cdot | s)} L(\vpi|\lambda), \end{eqnarray} where $\Lambda$ is the uniform distribution over all valid preferences. To train the model, we repeatedly sample different instances $s \sim \mathcal{S}$ at each iteration. We define the training loss as $\mathcal{J}({\bm{\theta}} ) = \bbE_{s \sim \mathcal{S}} \mathcal{J}({\bm{\theta}}|s)$. \subsection{Multiobjective REINFORCE} \begin{algorithm}[t] \caption{Neural MOCO Training} \label{alg_neural_moco_training} \begin{algorithmic}[1] \STATE \textbf{Input:} preference distribution $\Lambda$, instances distribution $\mathcal{S}$, number of training steps $T$, number of preferences per iteration $K$, batch size $B$, number of tours $N$ \STATE Initialize the model parameters ${\bm{\theta}}$ \FOR{$t = 1$ to $T$} \STATE $\lambda_k \sim \textbf{SamplePreference}(\Lambda) \quad \forall k \in \{1,\cdots,K\}$ \STATE $s_i \sim \textbf{SampleInstance}(\mathcal{S}) \quad \forall i \in \{1,\cdots,B\}$ \STATE $\vpi_{ki}^{j} \sim \textbf{SampleTour}(p_{{\bm{\theta}}(\lambda_k)}(\cdot | s_i)) \quad \forall k, i \quad \forall j \in \{1,\cdots,N\}$ \STATE $b(s_i|\lambda_k) \leftarrow \frac{1}{N} \sum_{j=1}^{N} L(\vpi_{ki}^{j}|\lambda_k, s_i) \quad \forall k \in \{1,\cdots,K\} \quad \forall i \in \{1,\cdots,B\}$ \STATE $\nabla \mathcal{J}({\bm{\theta}}) \leftarrow \frac{1}{KBN} \sum_{k=1}^{K} \sum_{i=1}^{B} \sum_{j=1}^{N} [ (L(\vpi_{ki}^{j}|\lambda_k, s_i) - b(s_i|\lambda_k)) \nabla_{{\bm{\theta}}(\lambda_k)} \log p_{{\bm{\theta}}(\lambda_k)}(\vpi_{ki}^{j}| s_i)]$ \STATE $\theta \leftarrow \textbf{ADAM}(\theta,\nabla \mathcal{J}({\bm{\theta}}))$ \ENDFOR \STATE \textbf{Output:} The model parameter ${\bm{\theta}}$ \end{algorithmic} \end{algorithm} For a given instance $s$ and a specific preference $\lambda$, we use the REINFORCE~\citep{williams1992simple} to estimate the gradient for the preference-conditioned scalar cost: \begin{eqnarray}\label{reinforce_grad} \nabla \mathcal{J}({\bm{\theta}} |\lambda, s) = \bbE_{\vpi \sim p_{{\bm{\theta}}(\lambda)}(\cdot | s)} [ (L(\vpi|\lambda, s) - b(s|\lambda)) \nabla_{{\bm{\theta}}(\lambda)} \log p_{{\bm{\theta}}(\lambda)}(\vpi| s)], \end{eqnarray} where $b(s|\lambda)$ is the baseline of expected cost to reduce the gradient variance. This gradient can be estimated by Monte Carlo sampling. At each update step, we randomly sample $K$ preference $\{\lambda_1,\cdots, \lambda_K\} \sim \Lambda$, $B$ instances $\{s_1, \cdots, s_B\} \sim \mathcal{S}$, and $N$ different tour $\{\vpi_i^1, \cdots, \vpi_i^N\} \sim p_{{\bm{\theta}}(\lambda_k)}(\cdot | s_i)$ for each $\lambda_k$-$s_i$ combination. The approximated gradient is: \begin{eqnarray}\label{reinforce_approx_grad} \nabla \mathcal{J}({\bm{\theta}}) \approx \frac{1}{KBN} \sum_{k=1}^{K} \sum_{i=1}^{B} \sum_{j=1}^{N} [ (L(\vpi_{i}^{j}|\lambda_k, s_i) - b(s_i|\lambda_k)) \nabla_{{\bm{\theta}}(\lambda_k)} \log p_{{\bm{\theta}}(\lambda_k)}(\vpi_{i}^{j}| s_i)]. \end{eqnarray} We use the shared baseline $b_{\text{shared}}(s_i|\lambda_k) = \frac{1}{N} \sum_{j=1}^{N} L(\vpi_{ki}^{j}|\lambda_k, s_i)$ over $N$ sampled tours for each $\lambda_k-s_i$ combination. The starting node for each tour $\vpi_{ki}^{j}$ is chosen in random to force diverse rollouts as proposed in~\citep{kwon2020pomo}. The algorithm is shown in \textbf{Algorithm \ref{alg_neural_moco_training}}. \subsection{Active Adaption} We also propose a simple yet powerful active adaption approach to further adjust the whole model to approximate the Pareto front for a given test instance in Appendix~\ref{supp_subsec_active_adaption}. The proposed method does not depend on specific instance distribution $\mathcal{S}$, and is suitable for out-of-distribution adaption. \section{Experiments} \label{sec_exp} \textbf{Problems and Model Setting. } We consider MOTSP~\citep{lust2010multiobjective}, MOCVRP~\citep{lacomme2006genetic} and MOKP~\citep{bazgan2009solving} in our experimental studies, and use the same model settings for all problems with different task-specific input sizes and mask methods. The main policy model encoder is the Attention Model~\citep{kool2019attention} and the hypernetwork is an MLP. We randomly generate $100,000$ problem instances on the fly for each epoch, and train the model for $200$ epochs. The optimizer is ADAM with learning rate $\eta = 10^{-4}$ and weight decay $10^{-6}$. We train our models on a single RTX $2080$-Ti GPU, and it costs about $10$ minutes for an epoch on MOTSP100. We give detailed model settings, problem formulations, and more experimental results in Appendix~\ref{supp_sec_model_detail}\ref{supp_sec_problem_detail}\ref{supp_sec_exp_results}. The source code can be found in \url{https://github.com/Xi-L/PMOCO}. \textbf{Baseline.} We call our proposed preference-conditioned multiobjective combinatorial optimization as \textbf{P-MOCO}. We compare it with three widely-used evolutionary algorithm frameworks for MOCO: \textbf{MOGLS}~\citep{jaszkiewicz2002genetic} is a multiobjective genetic local search algorithm, \textbf{NSGAII}~\citep{deb2002fast} is a Pareto dominance-based multiobjective genetic algorithm, and \textbf{MOEA/D}~\citep{zhang2007moea} is a decomposition-based multiobjective evolutionary algorithm. All these algorithm frameworks need problem-specific heuristics to generate and search feasible solutions for different problems. We also compare \textbf{P-MOCO} with two other learning-based methods: \textbf{DRL-MOA}~\citep{li2020deep} decomposes a MOCO with different preferences and builds a Pointer Network~\citep{vinyals2015pointer,bello2016neural} to solve each subproblem, and \textbf{AM-MOCO} is a multi-models variant of our proposed model, which builds Attention Model~\citep{kool2019attention} for each subproblem. The \textbf{Weight-Sum} scalarization of MOTSP and MOKP are their respective single-objective counterpart. Therefore, we also compare our method with the approach that uses some state-of-the-art single-objective solvers for each weight-sum subproblem. \begin{table*}[ht] \centering \caption{Model Information for the learning-based methods.} \label{table_model_info} \tabcolsep=0.12cm \begin{tabular}{llccc} \hline & \multicolumn{1}{c}{Model} & \#Models & \#Params & \#Pref. \\ \hline DRL-MOA & Pointer-Network & 101 & $101 \times$ 0.2M $=$ 20.2M ($7\%$) & Fixed 101 \\ AM-MOCO & Attention Model & 101 & $101 \times$ 1.3M $=$ 131.3M ($1.1\%$) & Fixed 101 \\ P-MOCO (Ours) & Pref-Conditioned AM & 1 & 1.4M & Flexible \\ \hline \end{tabular} \end{table*} \textbf{Model Information} for the learning-based methods is shown in Table~\ref{table_model_info}. Our model supports flexible preference assignment and only has $1.1\%$ total parameters to the multi-model counterpart. \textbf{Inference and Metrics.} We report the results and run time for solving $200$ random test instances for each problem, with normally $101$ to $105$ different trade-offed solutions, and up to $10,011$ solutions for our proposed method. In most cases, we report our model's zero-shot generalization performance without any search and fine-tune. We use the hypervolume indicator~\citep{zitzler2003performance} to measure the performance for each method. For a set $P \subset \mathbb{R}^m$ in the objective space, we can find a reference point $r^*$ that dominated by all solutions in $P$, and define the hypervolume $\text{HV}(P)$ as volume for: \begin{eqnarray} S = \{r \in \mathbb{R}^m \mid \exists \ y \in P \mbox{ such that } y \prec r \prec r^{*}\}, \end{eqnarray} where $\text{HV}(P) = \textbf{Vol}(S)$. In general, the larger the hypervolume, the better the solution set tends to be. The ground truth Pareto set always has the largest hypervolume. We report the normalized hypervolume values in $[0,1]$ with respect to the same $r^*$ for all the methods, and also the ratios of hypervolume difference to our method. A Wilcoxon rank-sum test with a significance level $1\%$ is conducted to compare the results for each experiment. More details can be found in Appendix~\ref{supp_subsec_hypervolume}. \subsection{Results and Analysis} \begin{table*}[t] \centering \caption{Experimental results on two-objective MOTSP, MOCVRP and MOKP with different input sizes (20,50 and 100). HV is the hypervolume metric, Gap is the ratio of hypervolume difference with respect to our method, and Time is the running run for solving 200 random test instances. The best result and its statistically indifferent results are highlighted in \textbf{bold}.} \vspace{-0.1in} \label{table_results_motsp_2obj} \tabcolsep=0.12cm \begin{tabular}{lccccccccc} \hline \multicolumn{10}{c}{MOTSP} \\ \hline \multicolumn{1}{l|}{} & \multicolumn{3}{c|}{MOTSP20} & \multicolumn{3}{c|}{MOTSP50} & \multicolumn{3}{c}{MOTSP100} \\ \multicolumn{1}{l|}{Method} & HV & Gap & \multicolumn{1}{c|}{Time} & HV & Gap & \multicolumn{1}{c|}{Time} & HV & Gap & Time \\ \hline \multicolumn{1}{l|}{Weight-Sum LKH} & 0.51 & 2.44\% & \multicolumn{1}{c|}{(3.9m)} & \textbf{0.58} & \textbf{-0.26\%} & \multicolumn{1}{c|}{(42m)} & \textbf{0.68} & \textbf{-0.58\%} & (3.1h) \\ \multicolumn{1}{l|}{Weight-Sum OR Tools} & 0.48 & 7.29\% & \multicolumn{1}{c|}{(3.7m)} & 0.52 & 9.66\% & \multicolumn{1}{c|}{(38m)} & 0.63 & 5.64\% & (2.8h) \\ \multicolumn{1}{l|}{MOGLS-TSP} & 0.48 & 7.96\% & \multicolumn{1}{c|}{(1.7h)} & 0.51 & 10.7\% & \multicolumn{1}{c|}{(4.5h)} & 0.59 & 14.7\% & (12h) \\ \multicolumn{1}{l|}{NSGAII-TSP} & 0.47 & 9.88\% & \multicolumn{1}{c|}{(45m)} & 0.46 & 19.7\% & \multicolumn{1}{c|}{(49m)} & 0.51 & 26.5\% & (53m) \\ \multicolumn{1}{l|}{MOEA/D-TSP} & 0.48 & 7.82\% & \multicolumn{1}{c|}{(3.1h)} & 0.47 & 18.9\% & \multicolumn{1}{c|}{(3.3h)} & 0.52 & 25.0\% & (3.7h) \\ \hline \multicolumn{1}{l|}{DRL-MOA (101 models)} & 0.46 & 11.3\% & \multicolumn{1}{c|}{(2s)} & 0.49 & 15.0\% & \multicolumn{1}{c|}{(5s)} & 0.57 & 17.0\% & (15s) \\ \multicolumn{1}{l|}{AM-MOCO (101 models)} & \textbf{0.52} & \textbf{0.22\%} & \multicolumn{1}{c|}{(2s)} & 0.57 & 1.72\% & \multicolumn{1}{c|}{(7s)} & 0.67 & 0.72\% & (18s) \\ \hline \multicolumn{1}{l|}{P-MOCO (101 pref.)} & \textbf{0.52} & \textbf{0.19\%} & \multicolumn{1}{c|}{(2s)} & 0.57 & 1.80\% & \multicolumn{1}{c|}{(5s)} & 0.67 & 0.60\% & (16s) \\ \multicolumn{1}{l|}{P-MOCO (101 pref., aug)} & \textbf{0.52} & \textbf{0.00\%} & \multicolumn{1}{c|}{(2.1m)} & 0.58 & 0.00\% & \multicolumn{1}{c|}{(4.2m)} & 0.67 & 0.00\% & (12m) \\ \hline \multicolumn{10}{c}{MOCVRP} \\ \hline \multicolumn{1}{l|}{} & \multicolumn{3}{c|}{MOCVRP20} & \multicolumn{3}{c|}{MOCVRP50} & \multicolumn{3}{c}{MOCVRP100} \\ \multicolumn{1}{l|}{Method} & HV & Gap & \multicolumn{1}{c|}{Time} & HV & Gap & \multicolumn{1}{c|}{Time} & HV & Gap & Time \\ \hline \multicolumn{1}{l|}{MOGLS-MOCVRP} & 0.33 & 6.66\% & \multicolumn{1}{c|}{(2.9h)} & 0.39 & 10.5\% & \multicolumn{1}{c|}{(4.1h)} & 0.38 & 13.0\% & (5h) \\ \multicolumn{1}{l|}{NSGAII-MOCVRP} & 0.31 & 12.3\% & \multicolumn{1}{c|}{(39m)} & 0.36 & 18.0\% & \multicolumn{1}{c|}{(39m)} & 0.35 & 20.8\% & (41m) \\ \multicolumn{1}{l|}{MOEAD-MOCVRP} & 0.29 & 17.9\% & \multicolumn{1}{c|}{(1.7h)} & 0.33 & 24.8\% & \multicolumn{1}{c|}{(1.8h)} & 0.34 & 22.3\% & (2h) \\ \hline \multicolumn{1}{l|}{DRL-MOA (101 models)} & 0.32 & 9.19\% & \multicolumn{1}{c|}{(6s)} & 0.37 & 16.0\% & \multicolumn{1}{c|}{(15s)} & 0.37 & 16.0\% & (33s) \\ \multicolumn{1}{l|}{AM-MOCO (101 models)} & 0.35 & 0.71\% & \multicolumn{1}{c|}{(8s)} & 0.43 & 2.84\% & \multicolumn{1}{c|}{(21s)} & 0.43 & 3.04\% & (39s) \\ \hline \multicolumn{1}{l|}{P-MOCO (101 pref.)} & 0.35 & 0.58\% & \multicolumn{1}{c|}{(8s)} & 0.44 & 0.65\% & \multicolumn{1}{c|}{(18s)} & 0.44 & 0.51\% & (36s) \\ \multicolumn{1}{l|}{P-MOCO (101 pref., aug)} & \textbf{0.35} & \textbf{0.00\%} & \multicolumn{1}{c|}{(1m)} & \textbf{0.44} & \textbf{0.00\%} & \multicolumn{1}{c|}{(2.1m)} & \textbf{0.45} & \textbf{0.00\%} & (4.5m) \\ \hline \multicolumn{10}{c}{MOKP} \\ \hline \multicolumn{1}{l|}{} & \multicolumn{3}{c|}{MOKP50} & \multicolumn{3}{c|}{MOKP100} & \multicolumn{3}{c}{MOKP200} \\ \multicolumn{1}{l|}{Method} & HV & Gap & \multicolumn{1}{c|}{Time} & HV & Gap & \multicolumn{1}{c|}{Time} & HV & Gap & Time \\ \hline \multicolumn{1}{l|}{Weight-Sum DP} & 0.70 & 2.11\% & \multicolumn{1}{c|}{(16m)} & 0.83 & 2.74\% & \multicolumn{1}{c|}{(1.5h)} & 0.66 & 2.86\% & (4.2h) \\ \multicolumn{1}{l|}{Weight-Sum Greedy} & \multicolumn{1}{l}{0.62} & 14.0\% & \multicolumn{1}{c|}{(2s)} & \multicolumn{1}{l}{0.77} & 10.1\% & \multicolumn{1}{c|}{(4s)} & \multicolumn{1}{l}{0.63} & 7.49\% & (7s) \\ \multicolumn{1}{l|}{MOGLS-KP} & 0.58 & 19.1\% & \multicolumn{1}{c|}{(1.8h)} & 0.72 & 15.6\% & \multicolumn{1}{c|}{(3.9h)} & 0.62 & 9.49\% & (9.8h) \\ \multicolumn{1}{l|}{NSGAII-KP} & 0.56 & 22.0\% & \multicolumn{1}{c|}{(34m)} & 0.69 & 19.8\% & \multicolumn{1}{c|}{(33m)} & 0.58 & 14.7\% & (34m) \\ \multicolumn{1}{l|}{MOEAD-KP} & 0.59 & 18.2\% & \multicolumn{1}{c|}{(1.5h)} & 0.76 & 11.1\% & \multicolumn{1}{c|}{(1.4h)} & 0.65 & 5.38\% & (1.6h) \\ \hline \multicolumn{1}{l|}{DRL-MOA (101 models)} & 0.63 & 12.9\% & \multicolumn{1}{c|}{(5s)} & 0.78 & 9.32\% & \multicolumn{1}{c|}{(17s)} & 0.65 & 4.39\% & (35s) \\ \multicolumn{1}{l|}{AM-MOCO (101 models)} & \textbf{0.72} & \textbf{0.21\%} & \multicolumn{1}{c|}{(7s)} & \textbf{0.86} & \textbf{0.41\%} & \multicolumn{1}{c|}{(16s)} & \textbf{0.68} & \textbf{0.32\%} & (42s) \\ \hline \multicolumn{1}{l|}{P-MOCO (101 pref.)} & \textbf{0.72} & \textbf{0.00\%} & \multicolumn{1}{c|}{(7s)} & \textbf{0.86} & \textbf{0.00\%} & \multicolumn{1}{c|}{(15s)} & \textbf{0.68} & \textbf{0.00\%} & (40s) \\ \hline \end{tabular} \vspace{-0.1in} \end{table*} \textbf{MOTSP.} The results on two and three objective MOTSP are shown in Table~\ref{table_results_motsp_2obj} and Table~\ref{table_results_motsp_3obj} respectively. MOGLS, NSGAII and MOEA/D all use $2$-opt local search heuristic~\citep{jaszkiewicz2002genetic} to search for promising solutions. We also include two weight-sum scalarization baselines with the state-of-the-art LKH solver~\citep{helsgaun2000effective,tinos2018efficient} and Google OR tools~\citep{ortools2019}. For the bi-objective problems, our proposed method with a single model has similar performances compared with AM-MOCO on all problems. It achieves the best performance with instance augmentation, which significantly outperforms other methods but is beaten by the LKH solver. For the three objective problems, our method can further improve its performance by generating much more trade-off solutions within a reasonable amount of time, which other methods cannot do. As shown in Figure~\ref{fig_3obj_motsp} and Figure~\ref{fig_supp_motsp_3obj}, our method can successfully learn the mapping from preferences to the corresponding solutions, and can generate a good prediction to the whole Pareto front. Decision makers can easily obtain any preferred trade-off solutions as they like. This flexibility could be desirable in many real-world applications. More discussion on the connection between the preference and Pareto solution for three-objective TSP can be found in Appendix~\ref{supp_subsec_connection}~\ref{supp_subsec_motsp_asymmetric}~\ref{supp_subsec_pref_inference}. \begin{table*}[t] \centering \caption{Experimental results on three-objective MOTSP with different input sizes (20, 50 and 100). The best result and its statistically indifferent results are highlighted in \textbf{bold}.} \vspace{-0.1in} \label{table_results_motsp_3obj} \tabcolsep=0.12cm \begin{tabular}{l|ccc|ccc|ccc} \hline & \multicolumn{3}{c|}{MOTSP20} & \multicolumn{3}{c|}{MOTSP50} & \multicolumn{3}{c}{MOTSP100} \\ Method & HV & Gap & Time & HV & Gap & Time & HV & Gap & Time \\ \hline Weight-Sum LKH & 0.32 & 5.83\% & (4.5m) & 0.36 & 5.48\% & (44m) & 0.45 & 4.03\% & (3.5h) \\ Weight-Sum OR Tools & 0.31 & 8.48\% & (4.1m) & 0.31 & 15.5\% & (39m) & 0.41 & 11.2\% & (3.1h) \\ MOGLS-MOTSP & 0.27 & 19.6\% & (2h) & 0.27 & 27.4\% & (5h) & 0.33 & 30.5\% & (13h) \\ NSGAII-MOTSP & 0.20 & 39.9\% & (47m) & 0.18 & 49.3\% & (56m) & 0.25 & 48.4\% & (1h) \\ MOEA/D-MOTSP & 0.21 & 36.6\% & (3.3h) & 0.20 & 46.7\% & (3.7h) & 0.27 & 42.7\% & (4.1h) \\ \hline DRL-MOA (105 models) & 0.26 & 21.6\% & (2s) & 0.28 & 23.0\% & (5s) & 0.34 & 28.8\% & (19s) \\ AM-MOCO (105 models) & 0.32 & 5.52\% & (2s) & 0.33 & 6.02\% & (7s) & 0.42 & 6.53\% & (21s) \\ \hline P-MOCO (105 pref.) & 0.32 & 5.65\% & (2s) & 0.36 & 5.76\% & (6s) & 0.44 & 5.52\% & (19s) \\ P-MOCO (105 pref., aug) & \multicolumn{1}{l}{0.32} & 5.46\% & (2.1m) & \multicolumn{1}{l}{0.36} & 5.43\% & (6.5m) & \multicolumn{1}{l}{0.45} & \multicolumn{1}{l}{4.39\%} & \multicolumn{1}{l}{(20m)} \\ P-MOCO (1,035 pref.) & 0.33 & 2.08\% & (19s) & 0.36 & 4.03\% & (48s) & 0.46 & 2.12\% & (2.9m) \\ P-MOCO (10,011 pref.) & \textbf{0.34} & \textbf{0.00\%} & (3m) & \textbf{0.38} & \textbf{0.00\%} & (9m) & \textbf{0.47} & \textbf{0.00\%} & (33m) \\ \hline \end{tabular} \vspace{-0.2in} \end{table*} \textbf{MOCVRP.} In this problem, each node has a demand, and we need to construct multiple return routes for a vehicle with a fixed capacity from the same depot to handle all demands. The objectives we consider are to minimize the tour length for all routes and also the tour length for the longest routes (the makespan in scheduling)~\citep{lacomme2006genetic}. All the non-learning algorithm frameworks use the problem-specific constructive heuristics and local search method proposed in \citet{lacomme2006genetic} to search feasible non-dominated solutions. The results in Table~\ref{table_results_motsp_2obj} show that our method significantly outperforms the non-learning heuristics in terms of both solution quality and running time. It also outperforms AM-MOCO with $100$ individual models, which could be due to the asymmetric objective scales. We provide further analysis in Appendix~\ref{supp_subsec_connection_2obj}. \textbf{MOKP.} The multiobjective $0$-$1$ knapsack problem can be found in many real-world applications~\citep{bazgan2009solving}. We consider the uni-dimension problem, where each item has multiple values and one weight. The goal is to select a subset of items to maximize all obtained values with a weight constraint. The non-learning methods use binary coding with a greedy transformation heuristic to maintain feasibility \citep{ishibuchi2014behavior}. We also include weight-sum scalarization baselines with dynamic programming (DP) and a strong greedy search based on the value-weight ratio. According to the results in Table~\ref{table_results_motsp_2obj}, our method has the best performance on all problems. The DP method is also outperformed by our method since the weight-sum scalarization can only find the convex hull of the Pareto front. The Tchebycheff scalarization of MOKP is not a KP problem, while our method is more flexible to use Tchebycheff scalarization on the reward function. We also report the results on $10$ objective MOKP100 and the generalization performance to problem with $500$ items in Appendix~\ref{supp_subsec_many_obj}. \textbf{Out-of-Distribution Problems and Active Adaption.} We also validate the generalization performance of our method on $6$ out-of-distribution (OOD) MOTSP problems from \citet{fonseca2006improved}. Their ground truth Pareto fronts can be obtained by exhaustive search. The results are shown in Appendix~\ref{supp_subsec_exact_front} due to the page limit. With active adaption, our method can achieve good performance ($1\%$ - $1.5\%$ HV gap to the ground truth Pareto fronts) on these OOD problems. \section{Conclusion and Future Work} \label{sec_conclusion} \textbf{Conclusion.} We have proposed a novel preference-conditioned method to approximate the whole Pareto front for MOCO problems using a single model. It allows decision makers to directly obtain any trade-off solutions without any search procedure. Experiments on different problems have shown that our proposed method significantly outperforms other methods in terms of performance, speed and model efficiency. We believe the proposed method is a principled way for solving MOCO. \textbf{Future Work.} In a sense, our method can be regarded as a learning version of the decomposition-based algorithm (MOEA/D~\citep{zhang2007moea}) dealing with all the possible trade-off preferences. Instead of maintaining a set of finite solutions as in other MOEA/D vaiants~\citep{trivedi2016survey}, we build a single learning-based model to solve the subproblems for all the preferences simultaneously in a collaborative manner. We believe the single-model-for-all-preference approach is a promising alternative to the current default finite-population-based methods, and it could be an important research direction for multiobjective optimization. Our method can be further improved with other advanced models and efficient multiobjective training procedures. In the future, we will study fundamental issues of multiobjective optimization (e.g., convergence v.s. diversity, exploitation v.s. exploration trade-off) for Pareto set learning methods. \textbf{Limitation.} It is very difficult to give a convergence guarantee for learning-based MOCO, where each preference-based subproblem could be already NP-hard, and the number of Pareto solutions is exponentially large with respect to the input size. See detailed discussion in Appendix~\ref{supp_sec_approximation}. \subsubsection*{Acknowledgments} We thank Prof. Hisao Ishibuchi for his valuable comments on an earlier version of this work. This work was supported by the Hong Kong General Research Fund (11208121, CityU-9043148).
{'timestamp': '2022-05-10T02:41:41', 'yymm': '2203', 'arxiv_id': '2203.15386', 'language': 'en', 'url': 'https://arxiv.org/abs/2203.15386'}
arxiv
\section{Evaluation}\label{sec:evaluation} We have implemented \textsc{ZK-SecreC}\xspace compiler in about 20 kLoC of Haskell code, which includes the parser, type-checker, \lstinline+@public+ precomputation engine, and translator to circuits. With it, we illustrate the expressiveness and efficiency of the \textsc{ZK-SecreC}\xspace language on a number of small examples. We have implemented them, and translated them to arithmetic circuits. The \textsc{ZK-SecreC}\xspace source of our examples is given in the supplementary material. Table~\ref{tbl:circsize} shows the size of generated circuits, including the number of inputs (both for the instance, and the witness), and different arithmetic operations. We distinguish between linear and non-linear (i.e. multiplication) operations, as only the latter are costly for a cryptographic ZKP technique. If our generated circuits compute modulo $2^{61}-1$, then they can be ingested by EMP toolkit~\cite{emp-toolkit}, in which case we also report the running time, network traffic, and memory use of Prover and Verifier. The Verifier process, running on a laptop, talks to a Prover process running on a server. They are connected over a link with 5 ms latency and bandwidth of around 450 Mbit/s. \input{benchmarks-table-submit} \paragraph{Knowing the factors} Our first example is the program in Fig.~\ref{language:factor}, with performance reported in row ``F'' of Table~\ref{tbl:circsize}. \paragraph{Historical millionaires} In this example~\cite{Viaduct}, two millionaires are comparing their net worths over time, and want to figure out whose minimum net worth was larger. In~\cite{Viaduct}, this was an example for secure two-party computation. In our setting, we let both arrays of historical net worths (expressed as integers) to be a part of the witness, and check that the smallest element of the first array is larger than the smallest element of the second array. As such, the instance of the relation appears to be empty, and the relation itself trivially satisfied. The setting is still interesting if we consider it to be part of some larger application where Prover has committed to both arrays, the commitments are part of the instance, and the verification that the witness matches the commitments happens elsewhere. \paragraph{Subset check} In this example, which is part of a larger application developed in \textsc{ZK-SecreC}\xspace, the input consists of two arrays, one held by Verifier and the other one by Prover, and Prover wants to convince Verifier that all elements of the first array are also elements of the second. We show this by sorting the concatenation of two arrays and checking that each element which originated from the first array is followed by an element which is equal to it. \paragraph{ECDSA verification} In this example (again part of a larger application), Verifier has a public key for the ECDSA digital signature scheme~\cite{kerry2013fips}. Prover wants to convince Verifier that he has a message digest and a signature that verifies with respect to the public key. We express this by implementing the ECDSA verification procedure in \textsc{ZK-SecreC}\xspace. The main part of this verification is the computation of two scalar multiplications in the elliptic curve group, where the scalars originate from the signature and the digest. In one of them, the multiplied point is the public key. We use the standard double-and-add method for computing the scalar multiple. In the second multiplication, the multiplied point is the generator of the group. The second point is public, and we use a windowed method to compute its scalar multiples. The implementation of point doublings and additions follows their standard definitions, which require the inversion of certain elements of the field, which we have implemented with the standard compute-and-verify technique. In ECDSA verification, computations are performed in two different fields. The computing of scalar multiplications takes place in the field $\mathbb{Z}_P$, over which the elliptic curve has been defined. But some multiplications and comparisons also take place in the field $\mathbb{Z}_Q$, where $Q$ is the cardinality of the elliptic curve group. \textsc{ZK-SecreC}\xspace thus supports the use of several different moduli (e.g. \lstinline+uint[P]+ and \lstinline+uint[Q]+) in the same program. In this case, the compilation procedure creates several circuits. In order to relate the computations by different moduli, there is an operation for asserting the equality of two values in \lstinline+$post+ stage, these values may belong to different types \lstinline+uint[N]+. These assertions are translated into assertions about the equality of values in the wires of different circuits. It is up to the cryptographic ZKP technique to correctly interpret the produced circuits and relationships between them. Techniques like MPC-in-the-head~\cite{DBLP:conf/stoc/IshaiKOS07,ZKBoo} can likely handle them, using the ring conversions developed for secure multiparty computation protocols~\cite{DBLP:journals/ijisec/BogdanovNTW12}. In Table~\ref{tbl:circsize} we report the sizes of the circuit for different standardized curves~\cite{kerry2013fips}, adding up the numbers of operations for both moduli. As EMP toolkit does not support fields of this size, we do not report any running times. \paragraph{Single-Source Shortest Paths (SSSP)} In this example, the input, known by Prover, is a directed graph with weighted edges. The graph has an \emph{initial vertex}, from which all other vertices are reachable. The graph is represented in sparse manner, i.e. the representation consists of the number of vertices $n$, the number of edges $m$ (also known to Verifier), and, for each edge, its starting vertex, its ending vertex, and its length (all known only to Prover). Prover wants to convince Verifier that the distances from a the initial vertex to all other vertices have certain values. Here Prover finds the shortest distances by himself, as well as the shortest-path tree represented by giving for each vertex (except the initial) the last edge on the shortest path from the origin to this vertex. He makes both of these sets of data available to the computation, after which the circuit checks that they match with the edges. The check consists of three parts. First, for each vertex we check that its reported distance from the origin is equal to the length of the last edge on the shortest path (found through the shortest-path tree), plus the distance of the source vertex of that last edge. Second, for each edge we check that it is \emph{relaxed }, i.e. the distance to its starting vertex, plus its length, is not less than the distance to its ending vertex. Third, we check that the shortest-path tree is indeed a tree rooted in the origin vertex. We do this by pointer-jumping~\cite[Sec.~30.1]{cormen2009introduction} the shortest-path tree for $\lceil \log n\rceil$ times, and check that in the result, all pointers point to the origin vertex. Due to the sparse representation of both the graph itself and the shortest-path tree, the SSSP example makes extensive use of dictionaries (Sec.~\ref{ssec:dictionaries}). It is a nice example of interleaving computation and verification. The shortest distances, and the shortest-path tree are verified in the circuit, which involves the computation of permutations sorting the keys used in the dictionaries, which are verified by comparing the neighboring elements in the sorted list of keys, which requires the computation of bit extractions of these elements, the correctness of which is again verified. \section{Proofs of Theorems~\ref{thm:can_compile}--\ref{thm:correct_compilation}}\label{compilation-proofs} \begin{lemma}\label{compilation:alltoplemma} Let $u\in U$ and let $q$ be a qualified type such that $\uopl{allpre}_d(q)$ for $d=\mbox{\lstinline+@public+}$. If $\uopl{allpure}(u)$ is $q$-exact in $\mbox{\lstinline+@public+}$ then $\uopl{allpuretop}(u)$ is $q$-exact. \end{lemma} \begin{proof} Let $q=(\qualty{t_0}{s_0}{d_0})$. By assumptions, $s_0=\mbox{\lstinline+$pre+}$ and $d_0=\mbox{\lstinline+@public+}$. By definition, $\uopl{allpure}(u)=\uopl{pure} v$ for some~$v$. We proceed by induction on the structure of~$t_0$. \begin{itemize} \item Let $t_0$ be a primitive type. Then, by exactness, $v\in t_0$. This is possible only if $u=v$. Hence $\uopl{allpuretop}(u)=(\uopl{pure} v,\top)$. This pair is $q$-exact by Definition~\ref{compilation:exact}. \item Let $t_0=\listty{q'}$ for some qualified type~$q'$. By $\uopl{allpre}_d(q)$, we must have $\uopl{allpre}_d(q')$. By exactness, $v=(\monadic{v}_1,\ldots,\monadic{v}_n)$ where $n\in\mathbb{N}$ and $\monadic{v}_i$ is $q'$-exact in $\mbox{\lstinline+@public+}$ for every $i=1,\ldots,n$. By definition of $\uopl{allpure}$, all $\monadic{v}_i$ are of the form $\uopl{allpure}(u_i)$ for some $u_i\in U$ such that $u=(u_1,\ldots,u_n)$. By the induction hypothesis, $\uopl{allpuretop}(u_i)$ are $q'$-exact. Thus $\uopl{allpuretop}(u)=(\uopl{pure}(\uopl{allpuretop}(u_1),\ldots,\uopl{allpuretop}(u_n)),\top)$ is $q'$-exact. \end{itemize} \end{proof} \begin{lemma}\label{compilation:getlemma} If $v\in U$ and $\pi\in(\mathbb{N}^*)^2$ then $\uopl{allpuretop}(v)\bullet\pi=\uopl{allpure}(v)$. \end{lemma} \begin{proof} We proceed by induction on the structure of~$v$. If $v$ is of a primitive type then \[ \uopl{allpuretop}(v)\bullet\pi =(\uopl{pure} v,\top)\bullet\pi =\uopl{pure} v =\uopl{allpure}(v)\mbox{.} \] If $v=(v_1,\ldots,v_n)$ then \[ \begin{array}{lcl} \uopl{allpuretop}(v)\bullet\pi &=&(\uopl{pure}(\uopl{allpuretop}(v_1),\ldots,\uopl{allpuretop}(v_n)),\top)\bullet\pi\\ &=&\uopl{pure}(\uopl{allpuretop}(v_1)\bullet\pi,\ldots,\uopl{allpuretop}(v_n)\bullet\pi)\mbox{.} \end{array} \] On the other hand, \[ \uopl{allpure}(v) =\uopl{pure}(\uopl{allpure}(v_1),\ldots,\uopl{allpure}(v_n))\mbox{.} \] The desired claim follows by the induction hypothesis. \end{proof} \begin{lemma}\label{compilation:updexactlemma} Let $d_1,\ldots,d_n$ be domains and $q$ be a qualified type. Moreover, let $q_k=(\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_k})$ for every $k=1,\ldots,n$ and $q'=(\qualty{\listty{\ldots\listty{\qualty{\listty{\qualty{\listty{q}}{\mbox{\lstinline+$pre+}}{d_n}}}{\mbox{\lstinline+$pre+}}{d_{n-1}}}\ldots}}{\mbox{\lstinline+$pre+}}{d_1})$. Assume $(\monadic{v},\monadic{c})$ being $q'$-exact, let $(\monadic{i}_k,\top)$ be $q_k$-exact for every $k=1,\ldots,n$, and let $(\monadic{v}',\monadic{c}')$ be $q$-exact. Then $\uopl{upd}_{\mathrm{C}}((\monadic{v},\monadic{c}),\monadic{i}_1\ldots\monadic{i}_n,(\monadic{v}',\monadic{c}'))$ (assuming that it is well defined) is $q'$-exact. \end{lemma} \begin{proof} We proceed by induction on~$n$. If $n=0$ then $q'=q$ and $\uopl{upd}_{\mathrm{C}}((\monadic{v},\monadic{c}),\monadic{i}_1\ldots\monadic{i}_n,(\monadic{v}',\monadic{c}'))=(\monadic{v}',\monadic{c}')$ which is $q$-exact by assumption. Let now $n>0$ and assume that the claim holds for $n-1$. Denote $q'_1=(\qualty{\listty{\ldots\listty{\qualty{\listty{\qualty{\listty{q}}{\mbox{\lstinline+$pre+}}{d_n}}}{\mbox{\lstinline+$pre+}}{d_{n-1}}}\ldots}}{\mbox{\lstinline+$pre+}}{d_2})$. In order to show that $\uopl{upd}_{\mathrm{C}}((\monadic{v},\monadic{c}),\monadic{i}_1\ldots\monadic{i}_n,(\monadic{v}',\monadic{c}'))$ is $q'$-exact, we have to prove the implications in Definition~\ref{compilation:exact}: \begin{itemize} \item If $d_1=\mbox{\lstinline+@public+}$ then, by exactness, $\monadic{v}=\uopl{pure}((\monadic{v}_1,\monadic{c}_1),\ldots,(\monadic{v}_{l_1},\monadic{c}_{l_1}))$ where all pairs $(\monadic{v}_k,\monadic{c}_k)$ ($k=1,\ldots,l_1$) are $q'_1$-exact and $\monadic{i}_1=\uopl{pure} i_1$ with $i_1\in\mathbb{N}$. Then $\uopl{upd}_{\mathrm{C}}((\monadic{v},\monadic{c}),\monadic{i}_1\ldots\monadic{i}_n,(\monadic{v}',\monadic{c}'))=(\monadic{v}'',\top)$ where $\monadic{v}''=\mcomp{a\gets\monadic{v};\; i_1\gets\monadic{i}_1;\;\uopl{pure}([i_1\mapsto\uopl{upd}_{\mathrm{C}}(a_{i_1},\monadic{i}_2\ldots\monadic{i}_n,(\monadic{v}',\monadic{c}'))]a)}$; as the latter is well-defined, $i_1\leq l_1$. As $\uopl{upd}_{\mathrm{C}}((\monadic{v}_{i_1},\monadic{c}_{i_1}),\monadic{i}_2\ldots\monadic{i}_n,(\monadic{v}',\monadic{c}'))$ is $q'_1$-exact by the induction hypothesis, all components of $v''$ are $q'_1$-exact as required. \item As the qualified type $q'$ has stage $\mbox{\lstinline+$pre+}$, $\top$ as the circuit part of the compound value corresponds to the definition. \item Finally, suppose that $d_1\ne\mbox{\lstinline+@public+}$. By $q'$-exactness of $(\monadic{v},\monadic{c})$, we have $\monadic{v}=\top$. Hence $\uopl{upd}_{\mathrm{C}}((\monadic{v},\monadic{c}),\monadic{i}_1\ldots\monadic{i}_n,(\monadic{v}',\monadic{c}'))=(\top,\top)$, matching the definition. \end{itemize} This establishes the required claim. \end{proof} \begin{lemma}\label{compilation:updlemma} Let $d_1,\ldots,d_n$ be domains and $q$ be a qualified type. Denote $q_k=(\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_k})$ for every $k=1,\ldots,n$ and $q'=(\qualty{\listty{\ldots\listty{\qualty{\listty{\qualty{\listty{q}}{\mbox{\lstinline+$pre+}}{d_n}}}{\mbox{\lstinline+$pre+}}{d_{n-1}}}\ldots}}{\mbox{\lstinline+$pre+}}{d_1})$. Let $\pi\in\left(\mathbb{N}^*\right)^2$ be a pair of circuit input sequences (for $\mbox{\lstinline+@prover+}$ and $\mbox{\lstinline+@verifier+}$). Let $(\monadic{a},\monadic{c}_0)$ be $q'$-exact and $\monadic{a}'$ be $q'$-exact in circuit; for all $k=1,\ldots,n$, let $(\monadic{i}_k,\top)$ be $q_k$-exact and $\monadic{i}'_k$ be $q_k$-exact in circuit; let $(\monadic{v},\monadic{c}_1)$ be $q$-exact and $\monadic{v}'$ be \mbox{$q$-exact} in circuit. Moreover, assume that $(\monadic{a},\monadic{c}_0)\bullet\pi\sim\monadic{a}'$, for every $k=1,\ldots,n$ we have $(\monadic{i},\top)\bullet\pi\sim\monadic{i}'_k$, and $(\monadic{v},\monadic{c}_1)\bullet\pi\sim\monadic{v}'$. If $\uopl{upd}_{\mathrm{C}}((\monadic{a},\monadic{c}_0),\monadic{i}_1\ldots\monadic{i}_n,(\monadic{v},\monadic{c}_1))$ is well-defined then $\uopl{upd}(\monadic{a}',\monadic{i}'_1\ldots\monadic{i}'_n,\monadic{v}')$ is well-defined, too, whereby $\uopl{upd}_{\mathrm{C}}((\monadic{a},\monadic{c}_0),\monadic{i}_1\ldots\monadic{i}_n,(\monadic{v},\monadic{c}_1))\bullet\pi\sim\uopl{upd}(\monadic{a}',\monadic{i}'_1\ldots\monadic{i}'_n,\monadic{v}')$. \end{lemma} \begin{proof} We proceed by induction on~$n$. If $n=0$ then $q'=q$, and $\uopl{upd}_{\mathrm{C}}((\monadic{a},\monadic{c}_0),\monadic{i}_1\ldots\monadic{i}_n,(\monadic{v},\monadic{c}_1))=(\monadic{v},\monadic{c}_1)$, $\uopl{upd}(\monadic{a}',\monadic{i}'_1\ldots\monadic{i}'_n,\monadic{v})=\monadic{v}'$. By assumption, $(\monadic{v},\monadic{c}_1)\bullet\pi\sim\monadic{v}'$. Let now $n>0$ and assume that the claim holds for $n-1$. Denoting $q'_1=(\qualty{\listty{\ldots\listty{\qualty{\listty{\qualty{\listty{q}}{\mbox{\lstinline+$pre+}}{d_n}}}{\mbox{\lstinline+$pre+}}{d_{n-1}}}\ldots}}{\mbox{\lstinline+$pre+}}{d_2})$, consider two cases: \begin{itemize} \item Assume that $d_1=\mbox{\lstinline+@public+}$. By the exactness assumptions, $\monadic{a}=\uopl{pure}((\monadic{a}_1,\monadic{c}'_1),\ldots,(\monadic{a}_{l_1},\monadic{c}'_{l_1}))$ and $\monadic{a}'=\uopl{pure}(\monadic{a}'_1,\ldots,\monadic{a}'_{l_1})$ with $(\monadic{a}_k,\monadic{c}'_k)$ being $q'_1$-exact and $a'_k$ being $q'_1$-exact in circuit, whereby $(\monadic{a},\monadic{c}_0)\bullet\pi\sim\monadic{a}'$ implies $(\monadic{a}_k,\monadic{c}'_k)\bullet\pi\sim\monadic{a}'_k$ for every $k=1,\ldots,n$. Similarly, we must have $\monadic{i}_1=\monadic{i}'_1=\uopl{pure} i_1$ with $i_1\in\mathbb{N}$. As $\uopl{upd}_{\mathrm{C}}((\monadic{a},\monadic{c}_0),\monadic{i}_1\ldots\monadic{i}_n,(\monadic{v},\monadic{c}_1))$ is well-defined, so is $\uopl{upd}_{\mathrm{C}}((\monadic{a}_{i_1},\monadic{c}'_{i_1}),\monadic{i}_2\ldots\monadic{i}_n,(\monadic{v},\monadic{c}_1))$ and $i_1\leq l_1$. By the induction hypothesis, $\uopl{upd}(\monadic{a}_{i_1},\monadic{i}'_2\ldots\monadic{i}'_n,\monadic{v}')$ is well-defined and $\uopl{upd}_{\mathrm{C}}((\monadic{a}_{i_1},\monadic{c}'_{i_1}),\monadic{i}_2\ldots\monadic{i}_n,(\monadic{v},\monadic{c}_1))\bullet\pi\sim\uopl{upd}(\monadic{a}_{i_1},\monadic{i}'_2\ldots\monadic{i}'_n,\monadic{v}')$. All this implies that $\uopl{upd}(\monadic{a}',\monadic{i}'_1\ldots\monadic{i}'_n,\monadic{v}')$ is also well-defined. Using the definitions of $\uopl{upd}_{\mathrm{C}}$ and $\uopl{upd}$, we obtain $\uopl{upd}_{\mathrm{C}}((\monadic{a},\monadic{c}_0),\monadic{i}_1\ldots\monadic{i}_n,(\monadic{v},\monadic{c}_1))\bullet\pi\sim\uopl{upd}(\monadic{a}',\monadic{i}'_1\ldots\monadic{i}'_n,\monadic{v}')$ as desired. \item Now assume that $d_1\ne\mbox{\lstinline+@public+}$. Then $(\monadic{a},\monadic{c}_0)=(\top,\top)$ and $\monadic{a}'=\top$ by exactness and exactness in circuit. Hence also $\uopl{upd}_{\mathrm{C}}((\monadic{a},\monadic{c}_0),\monadic{i}_1\ldots\monadic{i}_n,(\monadic{v},\monadic{c}_1))=(\top,\top)$ and $\uopl{upd}(\monadic{a}',\monadic{i}'_1\ldots\monadic{i}'_n,\monadic{v}')=\top$ which is well-defined. The desired claim follows since $(\top,\top)\bullet\pi=\top$. \end{itemize} \end{proof} \begin{theorem}[Theorem~\ref{thm:can_compile}] Let $\Gamma \mbox{\ $\vdash$\ } e : q! D$ with well-structured~$\Gamma$. Let $\gamma\in\mathbf{Env}_\mathrm{C}$ be $\Gamma$-exact. Let $\phi\in\mathbf{In}^3$ such that, for all subexpressions of~$e$ of the form $\ofty{\getexpr{d}{k}}{q'}$ where $d=\mbox{\lstinline+@public+}$, the value $\uopl{allpure}(\phi_{d}(k))$ is $q'$-exact in~$d$. Let $\nu\in\mathbb{N}^2$. Unless an array lookup fails due to an index being out of bounds, we have $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\gamma',\omicron,\nu')$ for some $\monadic{v}$, $\monadic{c}$, $\gamma'$, $\omicron$ and $\nu'$, whereby $(\monadic{v},\monadic{c})$ is $q$-exact and $\gamma'$ is $\Gamma$-exact. \end{theorem} \begin{proof} Let $q=(\qualty{t_0}{s_0}{d_0})$. We proceed by induction on the structure of~$e$. Assume that no array lookup fails due to an index being out of bounds. \begin{itemize} \item If $e=\epsilon$ then $t_0=\mbox{\lstinline+()+}$, $s_0=\mbox{\lstinline+$pre+}$, $d_0=\mbox{\lstinline+@public+}$. We obtain $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\gamma',\omicron,\nu')$ where \[ (\monadic{v},\monadic{c})=\uopl{pure}\mbox{\textoneoldstyle}\mbox{,}\quad\gamma'=\gamma\mbox{,}\quad\omicron=\epsilon\mbox{,}\quad\nu'=\nu\mbox{.} \] The pair $(\monadic{v},\monadic{c})$ is $q$-exact since $\mbox{\textoneoldstyle}\in\mbox{\lstinline+()+}$. Finally, $\gamma'$ is $\Gamma$-exact by assumption about~$\gamma$. \item If $e=\overline{n}$ where $n\in\mathbb{N}$ then $t_0=\uintmodty{\mbox{\lstinline+N+}}$. We obtain $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\gamma',\omicron,\nu')$ where \[ \begin{array}{l} (\monadic{v},\monadic{c})=(\branching{\uopl{pure} n&\mbox{if $d_0=\mbox{\lstinline+@public+}$}\\\top&\mbox{otherwise}},\branching{\uopl{pure}(\mknode{\uopl{con}(n)})&\mbox{if $s_0=\mbox{\lstinline+$post+}$}\\\top&\mbox{otherwise}})\mbox{,}\\\gamma'=\gamma\mbox{,}\quad\omicron=\epsilon\mbox{,}\quad\nu'=\nu\mbox{.} \end{array} \] The pair $(\monadic{v},\monadic{c})$ is $q$-exact since $|\mknode{\uopl{con}(n)}|=\uopl{pure} n=\uopl{pure}(\mknode{\uopl{con}(n)}(\pi))$. Finally, $\gamma'$ is $\Gamma$-exact by assumption about~$\gamma$. \item If $e=\overline{b}$ where $b\in\mathbb{B}$ then $t_0=\boolmodty{\mbox{\lstinline+N+}}$. We obtain $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\gamma',\omicron,\nu')$ where \[ \begin{array}{l} (\monadic{v},\monadic{c})=(\branching{\uopl{pure} b&\mbox{if $d_0=\mbox{\lstinline+@public+}$}\\\top&\mbox{otherwise}},\branching{\uopl{pure}(\mknode{\uopl{con}(|b|)})&\mbox{if $s_0=\mbox{\lstinline+$post+}$}\\\top&\mbox{otherwise}})\mbox{,}\\\gamma'=\gamma\mbox{,}\quad\omicron=\epsilon\mbox{,}\quad\nu'=\nu\mbox{.} \end{array} \] The pair $(\monadic{v},\monadic{c})$ is $q$-exact since $|\mknode{\uopl{con}(|b|)}|=\uopl{pure}|b|=\uopl{pure}(\mknode{\uopl{con}(|b|)}(\pi))$. Finally, $\gamma'$ is $\Gamma$-exact by assumption about~$\gamma$. \item If $e=x$ then $\lookup{\Gamma}{x}=q$. We obtain $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\gamma',\omicron,\nu')$ where \[ (\monadic{v},\monadic{c})=\lookup{\gamma}{x}\mbox{,}\quad\gamma'=\gamma\mbox{,}\quad\omicron=\epsilon\mbox{,}\quad\nu'=\nu\mbox{.} \] By assumption, $\gamma$ is $\Gamma$-exact, whence $\lookup{\gamma}{x}$ is $q$-exact and $\gamma'$ is $\Gamma$-exact as needed. \item If $e=\addexpr{e_1}{e_2}$ then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:q\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:q\mbox{.} \end{array} \] By the induction hypothesis about $e_1$, we have $\semc{e_1}\gamma\phi\nu=\uopl{pure}((\monadic{v}_1,\monadic{c}_1),\gamma_1,\omicron_1,\nu_1)$ where $(\monadic{v}_1,\monadic{c}_1)$ is $q$-exact and $\gamma_1$ is $\Gamma$-exact. Hence by the induction hypothesis about $e_2$, we have $\semc{e_2}\gamma_1\phi\nu_1=\uopl{pure}((\monadic{v}_2,\monadic{c}_2),\gamma_2,\omicron_2,\nu_2)$ where $(\monadic{v}_2,\monadic{c}_2)$ is $q$-exact and $\gamma_2$ is $\Gamma$-exact. We obtain $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\gamma',\omicron,\nu')$ where \[ \begin{array}{l} \monadic{v}=\mcomp{i_1\gets\monadic{v}_1;\; i_2\gets\monadic{v}_2;\;\uopl{pure}(i_1+i_2)}\mbox{,}\\ \monadic{c}=\mcomp{c_1\gets\monadic{c}_1;\; c_2\gets\monadic{c}_2;\;\uopl{pure}(\mknode{\uopl{op}(+)}(c_1,c_2))}\mbox{,}\\ \gamma'=\gamma_2\mbox{,}\quad\omicron=\omicron_1\omicron_2\mbox{,}\quad\nu'=\nu_2\mbox{.} \end{array} \] The desired claim about~$\gamma'$ holds because of $\gamma_2$ being $\Gamma$-exact. For proving that $(\monadic{v},\monadic{c})$ is $q$-exact, we have to establish all implications in Definition~\ref{compilation:exact}. \begin{itemize} \item If $s_0=\mbox{\lstinline+$post+}$ then $\monadic{c}_1=\uopl{pure} c_1$ and $\monadic{c}_2=\uopl{pure} c_2$ by exactness. Hence we obtain $\monadic{c}=\uopl{pure}(\mknode{\uopl{op}(+)}(c_1,c_2))$. Suppose that $\monadic{v}=\uopl{pure} n$, $n\in\mathbb{N}$. Then $\monadic{v}_1=\uopl{pure} i_1$, $\monadic{v}_2=\uopl{pure} i_2$, $n=i_1+i_2$. Moreover, $|c_1|=\uopl{pure} i_1=\uopl{pure}(c_1(\pi))$ and $|c_2|=\uopl{pure} i_2=\uopl{pure}(c_2(\pi))$. This implies $|c|=\uopl{pure}(i_1+i_2)=\uopl{pure} n$ and $|c|=\uopl{pure}(c_1(\pi)+c_2(\pi))=\uopl{pure}(\mknode{\uopl{op}(+)}(c_1,c_2)(\pi))$ as desired. \item If $d_0=\mbox{\lstinline+@public+}$ then $\monadic{v}_1=\uopl{pure} i_1$ and $\monadic{v}_2=\uopl{pure} i_2$ where $i_1,i_2\in\mathbb{N}$. Hence $\monadic{v}=\uopl{pure}(i_1+i_2)$, $i_1+i_2\in\mathbb{N}$ as desired. \item If $s_0=\mbox{\lstinline+$pre+}$ then $\monadic{c}_1=\monadic{c}_2=\top$. Hence $\monadic{c}=\top$. \item If $d_0\ne\mbox{\lstinline+@public+}$ then $\monadic{v}_1=\monadic{v}_2=\top$. Hence $\monadic{v}=\top$. \end{itemize} \item If $e=\assertexpr{e_1}$ then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{\boolmodty{\mbox{\lstinline+N+}}}{\mbox{\lstinline+$post+}}{d_1}\mbox{,}\\ t_0=\mbox{\lstinline+()+}\mbox{,}\quad s_0=\mbox{\lstinline+$pre+}\mbox{,}\quad d_0=\mbox{\lstinline+@public+}\mbox{.} \end{array} \] Denote $q'=(\qualty{\boolmodty{\mbox{\lstinline+N+}}}{\mbox{\lstinline+$post+}}{d_1})$. By the induction hypothesis about $e_1$, we have $\semc{e_1}\gamma\phi\nu=\uopl{pure}((\monadic{v}_1,\monadic{c}_1),\gamma_1,\omicron_1,\nu_1)$ where $(\monadic{v}_1,\monadic{c}_1)$ is $q'$-exact and $\gamma_1$ is $\Gamma$-exact. The former guarantees $\monadic{c}_1=\uopl{pure} c_1$ for some $c_1\in T$. Therefore we have $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\gamma',\omicron,\nu')$ where \[ \begin{array}{l} (\monadic{v},\monadic{c})=(\uopl{pure}\mbox{\textoneoldstyle},\top)\mbox{,}\quad\gamma'=\gamma_1\mbox{,}\quad\omicron=\omicron_1c_1\mbox{,}\quad\nu'=\nu_1\mbox{.} \end{array} \] The desired claim about~$\gamma'$ holds because of $\gamma_1$ being $\Gamma$-exact. The pair $(\monadic{v},\monadic{c})$ is $q$-exact since $\mbox{\textoneoldstyle}\in\mbox{\lstinline+()+}$. \item If $e=\getexpr{d}{k}$ then $s_0=\mbox{\lstinline+$pre+}$ and $d_0=d$. We obtain $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\gamma',\omicron,\nu')$ where \[ (\monadic{v},\monadic{c})=\branching{\uopl{allpuretop}(\phi_d(k))&\mbox{if $d=\mbox{\lstinline+@public+}$}\\(\top,\top)&\mbox{otherwise}}\mbox{,}\quad\gamma'=\gamma\mbox{,}\quad\omicron=\epsilon\mbox{,}\quad\nu'=\nu\mbox{.} \] If $d=\mbox{\lstinline+@public+}$ then, by assumption, $\uopl{allpure}(\phi_d(k))$ is $q$-exact in $\mbox{\lstinline+@public+}$, which implies $\uopl{allpuretop}(\phi_d(k))$ being $q$-exact by Lemma~\ref{compilation:alltoplemma}. Hence if $d=\mbox{\lstinline+@public+}$ then $(\monadic{v},\monadic{c})$ is $q$-exact. Otherwise, $(\top,\top)$ is $q$-exact by Definition~\ref{compilation:exact}. Finally, $\gamma'$ is $\Gamma$-exact by the assumption about~$\gamma$. \item If $e=\ifexpr{e_1}{e_2}{e_3}$ then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{\boolmodty{\mbox{\lstinline+N+}}}{\mbox{\lstinline+$pre+}}{d_1}\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:q\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_3:q\mbox{,}\\ \gen{d_1}\supseteq\gen{s_0}\cup\gen{d_0}\mbox{.} \end{array} \] Denote $q'=\qualty{\boolmodty{\mbox{\lstinline+N+}}}{\mbox{\lstinline+$pre+}}{d_1}$. By the induction hypothesis about~$e_1$, we have $\semc{e_1}\gamma\phi\nu=\uopl{pure}((\monadic{v}_1,\monadic{c}_1),\gamma_1,\omicron_1,\nu_1)$ where $(\monadic{v}_1,\monadic{c}_1)$ is $q'$-exact and $\gamma_1$ is $\Gamma$-exact. Consider three cases: \begin{itemize} \item Suppose $\monadic{v}_1=\uopl{pure}\mbox{\bfseries tt}$. By the induction hypothesis about~$e_2$, we have $\semc{e_2}\gamma_1\phi\nu_1=\uopl{pure}((\monadic{v}_2,\monadic{c}_2),\gamma_2,\omicron_2,\nu_2)$ where $(\monadic{v}_2,\monadic{c}_2)$ is $q$-exact and $\gamma_2$ is $\Gamma$-exact. We obtain $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\gamma',\omicron,\nu')$ where \[ \begin{array}{l} (\monadic{v},\monadic{c})=(\monadic{v}_2,\monadic{c}_2)\mbox{,}\quad\gamma'=\gamma_2\mbox{,}\quad\omicron=\omicron_1\omicron_2\mbox{,}\quad\nu'=\nu_2\mbox{.} \end{array} \] The desired claim follows. \item Suppose $\monadic{v}_1=\uopl{pure}\mbox{\bfseries ff}$. By the induction hypothesis about~$e_3$, we have $\semc{e_3}\gamma_1\phi\nu_1=\uopl{pure}((\monadic{v}_3,\monadic{c}_3),\gamma_3,\omicron_3,\nu_3)$ where $(\monadic{v}_3,\monadic{c}_3)$ is $q$-exact and $\gamma_3$ is $\Gamma$-exact. We obtain $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\gamma',\omicron,\nu')$ where \[ \begin{array}{l} (\monadic{v},\monadic{c})=(\monadic{v}_3,\monadic{c}_3)\mbox{,}\quad\gamma'=\gamma_3\mbox{,}\quad\omicron=\omicron_1\omicron_3\mbox{,}\quad\nu'=\nu_3\mbox{.} \end{array} \] The desired claim follows. \item If $\monadic{v}_1\ne\uopl{pure} b$ for $b\in\mathbb{B}$ then we obtain $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\gamma',\omicron,\nu')$ where \[ (\monadic{v},\monadic{c})=(\top,\top)\mbox{,}\quad\gamma'=\gamma_1\mbox{,}\quad\omicron=\omicron_1\mbox{,}\quad\nu'=\nu_1\mbox{.} \] By $\gamma_1$ being $\Gamma$-exact, we obtain the desired result about~$\gamma'$. Moreover, $q'$-exactness of $(\monadic{v}_1,\monadic{c}_1)$ implies $d_1\ne\mbox{\lstinline+@public+}$. Now $\gen{d_1}\supseteq\gen{s_0}\cup\gen{d_0}$ implies $d_0\ne\mbox{\lstinline+@public+}$ and $s_0=\mbox{\lstinline+$pre+}$. Consequently, $(\top,\top)$ is $q$-exact as desired. \end{itemize} \item If $e=\forexpr{x}{e_1}{e_2}{e_3}$ then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0}\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0}\mbox{,}\\ (x:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0}),\Gamma\mbox{\ $\vdash$\ } e_3:q_1\mbox{,}\\ t_0=\listty{q_1}\mbox{,}\quad s_0=\mbox{\lstinline+$pre+}\mbox{.} \end{array} \] Denote $q'=(\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0})$. By the induction hypothesis about $e_1$, we have $\semc{e_1}\gamma\phi\nu=\uopl{pure}((\monadic{v}_1,\monadic{c}_1),\gamma_1,\omicron_1,\nu_1)$ where $(\monadic{v}_1,\monadic{c}_1)$ is $q'$-exact and $\gamma_1$ is $\Gamma$-exact. Hence by the induction hypothesis about $e_2$, we have $\semc{e_2}\gamma_1\phi\nu_1=\uopl{pure}((\monadic{v}_2,\monadic{c}_2),\gamma_2,\omicron_2,\nu_2)$ where $(\monadic{v}_2,\monadic{c}_2)$ is $q'$-exact and $\gamma_2$ is $\Gamma$-exact. Note that $q'$-exactness implies $\monadic{c}_1=\monadic{c}_2=\top$. Consider two cases: \begin{itemize} \item Suppose $\monadic{v}_1=\uopl{pure} i_1$ and $\monadic{v}_2=\uopl{pure} i_2$. By $q'$-exactness, $d_0=\mbox{\lstinline+@public+}$. Denote $n=\max(0,i_2-i_1)$. All pairs of the form $(\uopl{pure}(i_1+k),\top)$ are $q'$-exact as $(\uopl{pure} i_1,\top)$ is \mbox{$q'$-exact} by the above. Hence $\left((x,(\uopl{pure} i_1,\top)),\gamma_2\right)$ is $\Gamma'$-exact where $\Gamma'=((x:q'),\Gamma)$. By the induction hypothesis about~$e_3$, we have $\semc{e_3}((x,(\uopl{pure} i_1,\top)),\gamma_2)\phi\nu_2=\uopl{pure}((\monadic{v}_3,\monadic{c}_3),\gamma_3,\omicron_3,\nu_3)$ where $(\monadic{v}_3,\monadic{c}_3)$ is $q_1$-exact and $\gamma_3$ is $\Gamma'$-exact. As the updated environment $[x\mapsto(\uopl{pure}(i_1+1),\top)]\gamma_3$ is also $\Gamma'$-exact, the induction hypothesis also implies $\semc{e_3}([x\mapsto(\uopl{pure}(i_1+1),\top)]\gamma_3)\phi\nu_3=\uopl{pure}((\monadic{v}_4,\monadic{c}_4),\gamma_4,\omicron_4,\nu_4)$ where $(\monadic{v}_4,\monadic{c}_4)$ being $q_1$-exact and $\gamma_4$ being $\Gamma'$-exact. Analogously, for all $k=5,\ldots,n+2$, we obtain $\semc{e_3}([x\mapsto(\uopl{pure}(i_1+k-3),\top)]\gamma_{k-1})\phi\nu_{k-1}=\uopl{pure}((\monadic{v}_k,\monadic{c}_k),\gamma_k,\omicron_k,\nu_k)$ where $(\monadic{v}_k,\monadic{c}_k)$ is $q_1$-exact and $\gamma_k$ is $\Gamma'$-exact. We obtain $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\gamma',\omicron,\nu')$ where \[ \begin{array}{l} (\monadic{v},\monadic{c})=(\uopl{pure}((\monadic{v}_3,\monadic{c}_3),\ldots,(\monadic{v}_{n+2},\monadic{c}_{n+2})),\top)\mbox{,}\\\gamma'=\uopl{tail}\gamma_{n+2}\mbox{,}\quad\omicron=\omicron_1\ldots\omicron_{n+2}\mbox{,}\quad\nu'=\nu_{n+2}\mbox{.} \end{array} \] Hence $(\monadic{v},\monadic{c})$ is $q$-exact since $d_0=\mbox{\lstinline+@public+}$ and $s_0=\mbox{\lstinline+$pre+}$. As $\gamma_{n+2}$ is $\Gamma'$-exact, $\uopl{tail}\gamma_{n+2}$ is $\Gamma$-exact, implying also the desired claim about~$\gamma'$. \item If $\monadic{v}_1\ne\uopl{pure} n$ or $\monadic{v}_2\ne\uopl{pure} n$ for $n\in\mathbb{N}$ then we obtain $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\gamma',\omicron,\nu')$ where \[ (\monadic{v},\monadic{c})=(\top,\top)\mbox{,}\quad\gamma'=\gamma_2\mbox{,}\quad\omicron=\omicron_1\omicron_2\mbox{,}\quad\nu'=\nu_2\mbox{.} \] By $\gamma_2$ being $\Gamma$-exact, we obtain the desired result about~$\gamma'$. Moreover, $q'$-exactness of $(\monadic{v}_i,\monadic{c}_i)$ for $i=1,2$ implies $d_0\ne\mbox{\lstinline+@public+}$. As $s_0=\mbox{\lstinline+$pre+}$, this implies $(\top,\top)$ being $q$-exact. \end{itemize} \item If $e=\wireexpr{e_1}$ then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{t_0}{\mbox{\lstinline+$post+}}{d_0}\mbox{,}\\ t_0\in\left\lbrace\uintmodty{\mbox{\lstinline{N}}},\boolmodty{\mbox{\lstinline{N}}}\right\rbrace\mbox{.} \end{array} \] Denote $q'=\qualty{t_0}{\mbox{\lstinline+$post+}}{d_0}$. By the induction hypothesis about $e_1$, we have $\semc{e_1}\gamma\phi\nu=\uopl{pure}((\monadic{v}_1,\monadic{c}_1),\gamma_1,\omicron_1,\nu_1)$ where $(\monadic{v}_1,\monadic{c}_1)$ is $q'$-exact and $\gamma_1$ is $\Gamma$-exact. We obtain $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\gamma',\omicron,\nu')$ where \[ \begin{array}{l} (\monadic{v},\monadic{c})=(\monadic{v}_1,\branching{\uopl{pure}(\mknode{\uopl{con}(n)})&\mbox{if $\monadic{v}_1=\uopl{pure} n$, $n\in\mathbb{N}$}\\\uopl{pure}(\mknode{\uopl{con}(|b|)})&\mbox{if $\monadic{v}_1=\uopl{pure} b$, $b\in\mathbb{B}$}\\\uopl{pure}(\mknode{\uopl{in}_d({(\nu_1)}_d)})&\mbox{if $\monadic{v}_1=\top$}})\mbox{,}\\\gamma'=\gamma_1\mbox{,}\quad\omicron=\omicron_1\mbox{,}\quad\nu'=\lam{d'}{\branching{(\nu_1)_{d'}+1&\mbox{if $d'=d$}\\(\nu_1)_{d'}&\mbox{otherwise}}}\mbox{.} \end{array} \] To establish that $(\monadic{v},\monadic{c})$ is $q$-exact, note that in all cases $\monadic{c}=\uopl{pure} c$ for some circuit~$c$. Furthermore, consider two cases: \begin{itemize} \item Suppose that $\monadic{v}=\uopl{pure} n$ for some $n\in\mathbb{N}$. Since $\monadic{v}=\monadic{v}_1$, we must have $c=\mknode{\uopl{con}(n)}$. Hence $|c|=\uopl{pure} n=\uopl{pure}(c(\pi))$. \item Suppose that $\monadic{v}=\uopl{pure} b$ for some $b\in\mathbb{B}$. Since $\monadic{v}=\monadic{v}_1$, we must have $c=\mknode{\uopl{con}(|b|)}$. Hence $|c|=\uopl{pure}|b|=\uopl{pure}(c(\pi))$. \end{itemize} The clauses of Definition~\ref{compilation:exact} about $\monadic{v}$ hold by $\monadic{v}=\monadic{v}_1$ and $(\monadic{v}_1,\monadic{c}_1)$ being $q'$-exact. Finally, $\gamma'$ is $\Gamma$-exact since $\gamma'=\gamma_1$ and $\gamma_1$ is $\Gamma$-exact. \item If $e=(\castexpr{e_1}{q})$ then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{t_0}{s_1}{d_1}\mbox{,}\\ s_1\mathrel{\mathchar"13C\mathchar"3A} s_0\mbox{,}\quad d_1\mathrel{\mathchar"13C\mathchar"3A} d_0\mbox{.} \end{array} \] Denote $q_1=\qualty{t_0}{s_1}{d_1}$. The induction hypothesis implies $\semc{e_1}\gamma\phi\nu=\uopl{pure}((\monadic{v}_1,\monadic{c}_1),\gamma_1,\omicron_1,\nu_1)$ where $(\monadic{v}_1,\monadic{c}_1)$ is $q_1$-exact and $\gamma_1$ is $\Gamma$-exact. We obtain $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\gamma',\omicron,\nu')$ where \[ (\monadic{v},\monadic{c})=(\branching{\monadic{v}_1&\mbox{if $d_0=\mbox{\lstinline+@public+}$}\\\top&\mbox{otherwise}},\branching{\monadic{c}_1&\mbox{if $s_0=\mbox{\lstinline+$post+}$}\\\top&\mbox{otherwise}})\mbox{,}\quad\gamma'=\gamma_1\mbox{,}\quad\omicron=\omicron_1\mbox{,}\quad\nu'=\nu_1\mbox{.} \] To establish that $(\monadic{v},\monadic{c})$ is $q$-exact, consider cases: \begin{itemize} \item Suppose that $s_0=\mbox{\lstinline+$post+}$. Then $\monadic{c}=\monadic{c}_1$. By $s_1\mathrel{\mathchar"13C\mathchar"3A} s_0$, we also have $s_1=\mbox{\lstinline+$post+}$. By $(\monadic{v}_1,\monadic{c}_1)$ being $q_1$-exact, $\monadic{c}=\uopl{pure} c$ for some circuit~$c$. If $\monadic{v}=\uopl{pure} v$ for some~$v$ then $d_0=\mbox{\lstinline+@public+}$ and $\monadic{v}_1=\monadic{v}$. By $d_1\mathrel{\mathchar"13C\mathchar"3A} d_0$, also $d_1=\mbox{\lstinline+@public+}$. Consequently, $q_0=q_1$, whence $(\monadic{v},\monadic{c})$ is $q$-exact because $(\monadic{v}_1,\monadic{c}_1)$ is $q_1$-exact. \item Suppose that $d_0=\mbox{\lstinline+@public+}$ and $t_0$ is a primitive type. Then $\monadic{v}=\monadic{v}_1$. As $d_1\mathrel{\mathchar"13C\mathchar"3A} d_0$ implies $d_1=\mbox{\lstinline+@public+}$, we have $\monadic{v}_1=\uopl{pure} v$ with $v\in t_0$ by $(\monadic{v}_1,\monadic{c}_1)$ being $q_1$-exact. \item Suppose that $d_0=\mbox{\lstinline+@public+}$ and $t_0=\listty{q'}$. Then $\monadic{v}=\monadic{v}_1$. As $d_1\mathrel{\mathchar"13C\mathchar"3A} d_0$ implies $d_1=\mbox{\lstinline+@public+}$ and $(\monadic{v}_1,\monadic{c}_1)$ is $q_1$-exact, we have $\monadic{v}_1=\uopl{pure}((\monadic{v}'_1,\monadic{c}'_1),\ldots,(\monadic{v}'_l,\monadic{c}'_l))$ where all $(\monadic{v}'_i,\monadic{c}'_i)$ are $q'$-exact. \item Suppose that $d_0\ne\mbox{\lstinline+@public+}$. Then $\monadic{v}=\top$ by definition. \end{itemize} Hence $(\monadic{v},\monadic{c})$ is $q$-exact indeed. Finally, $\gamma'$ is $\Gamma$-exact since $\gamma'=\gamma_1$ and $\gamma_1$ is $\Gamma$-exact. \item If $e=(\assignexpr{e_1}{e_2})$ then $q=\qualty{\mbox{\lstinline+()+}}{\mbox{\lstinline+$pre+}}{\mbox{\lstinline+@public+}}$. Let $e_1=\loadexpr{\loadexpr{\loadexpr{x}{y_1}}{y_2}\ldots}{y_n}$ where $x$ is a variable. By Lemma~\ref{typesystem:lhslemma}, there exist domains $d_1,\ldots,d_n$ such that \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } x:q'\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } y_i:q_i\mbox{ for every $i=1,\ldots,n$,}\\ \Gamma\mbox{\ $\vdash$\ } e_1:q_{n+1}\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:q_{n+1}\mbox{,} \end{array} \] where $q_i=\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_i}$ for each $i=1,\ldots,n$ and \[ q'=\qualty{\listty{\ldots\listty{\qualty{\listty{\qualty{\listty{q_{n+1}}}{\mbox{\lstinline+$pre+}}{d_n}}}{\mbox{\lstinline+$pre+}}{d_{n-1}}}\ldots}}{\mbox{\lstinline+$pre+}}{d_1}\mbox{.} \] By the induction hypothesis, we have \[ \begin{array}{l} \semc{y_1}\gamma\phi\nu=\uopl{pure}((\monadic{v}_1,\monadic{c}_1),\gamma_1,\omicron_1,\nu_1)\mbox{,}\\ \semc{y_2}\gamma_1\phi\nu_1=\uopl{pure}((\monadic{v}_2,\monadic{c}_2),\gamma_2,\omicron_2,\nu_2)\mbox{,}\\ \dotfill\\ \semc{y_n}\gamma_{n-1}\phi\nu_{n-1}=\uopl{pure}((\monadic{v}_n,\monadic{c}_n),\gamma_n,\omicron_n,\nu_n)\mbox{,}\\ \semc{e_2}\gamma_n\phi\nu_n=\uopl{pure}((\monadic{v}_{n+1},\monadic{c}_{n+1}),\gamma_{n+1},\omicron_{n+1},\nu_{n+1})\mbox{,} \end{array} \] where $(\monadic{v}_i,\monadic{c}_i)$ is $q_i$-exact and $\gamma_i$ is $\Gamma$-exact for every $i=1,\ldots,n+1$. Hence we obtain $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\gamma',\omicron,\nu')$ where \[ \begin{array}{l} (\monadic{v},\monadic{c})=(\uopl{pure}\mbox{\textoneoldstyle},\top)\mbox{,}\\\gamma'=[x\mapsto\uopl{upd}_{\mathrm{C}}(\lookup{\gamma}{x},\monadic{v}_1\ldots\monadic{v}_n,(\monadic{v}_{n+1},\monadic{c}_{n+1}))]\gamma_{n+1}\mbox{,}\\\omicron=\omicron_1\ldots\omicron_{n+1}\mbox{,}\\\nu'=\nu_{n+1}\mbox{.} \end{array} \] Obviously $(\uopl{pure}\mbox{\textoneoldstyle},\top)$ is $q$-exact. By Lemma~\ref{compilation:updexactlemma}, $\uopl{upd}_{\mathrm{C}}(\lookup{\gamma}{x},\monadic{v}_1\ldots\monadic{v}_n,(\monadic{v}_{n+1},\monadic{c}_{n+1}))$ is $q'$-exact. Hence also $\gamma'$ is $\Gamma$-exact. \item If $e=\loadexpr{e_1}{e_2}$ then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{\listty{q}}{\mbox{\lstinline+$pre+}}{d_1}\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_1}\mbox{.} \end{array} \] Denote $q_1=\qualty{\listty{q}}{\mbox{\lstinline+$pre+}}{d_1}$ and $q'=\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_1}$. By the induction hypothesis about $e_1$, we have $\semc{e_1}\gamma\phi\nu=\uopl{pure}((\monadic{v}_1,\monadic{c}_1),\gamma_1,\omicron_1,\nu_1)$ where $(\monadic{v}_1,\monadic{c}_1)$ is $q_1$-exact and $\gamma_1$ is $\Gamma$-exact. Hence by the induction hypothesis about~$e_2$, we have $\semc{e_2}\gamma_1\phi\nu_1=\uopl{pure}((\monadic{v}_2,\monadic{c}_2),\gamma_2,\omicron_2,\nu_2)$ where $(\monadic{v}_2,\monadic{c}_2)$ is $q'$-exact and $\gamma_2$ is $\Gamma$-exact. Let $\monadic{r}=\mcomp{a\gets\monadic{v}_1;\; i\gets\monadic{v}_2;\;\uopl{pure} a_i}$; then $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\gamma',\omicron,\nu')$ where \[ \begin{array}{l} (\monadic{v},\monadic{c})=\branching{(\monadic{v}',\monadic{c}')&\mbox{if $\monadic{r}=\uopl{pure}(\monadic{v}',\monadic{c}')$}\\(\top,\top)&\mbox{otherwise}}\mbox{,}\\ \gamma'=\gamma_2\mbox{,}\quad\omicron=\omicron_1\omicron_2\mbox{,}\quad\nu'=\nu_2\mbox{,} \end{array} \] Consider two cases: \begin{itemize} \item If $d_1=\mbox{\lstinline+@public+}$ then, by exactness, $\monadic{v}_1=\uopl{pure}((\monadic{v}'_1,\monadic{c}'_1),\ldots,(\monadic{v}'_l,\monadic{c}'_l))$ where $(\monadic{v}'_k,\monadic{c}'_k)$ is $q$-exact for every $k=1,\ldots,l$, and $\monadic{v}_2=\uopl{pure} i$ for some $i\in\mathbb{N}$. Therefore $\monadic{r}=\uopl{pure}(\monadic{v}'_i,\monadic{c}'_i)$ and $(\monadic{v},\monadic{c})=(\monadic{v}'_i,\monadic{c}'_i)$. The latter pair is $q$-exact by the above. \item If $d_1\ne\mbox{\lstinline+@public+}$ then $d_0\ne\mbox{\lstinline+@public+}$ and $s_0=\mbox{\lstinline+$pre+}$ because of $q_1$ being well-structured by Theorem~\ref{typesystem:thm}. By exactness, $\monadic{v}_1=\top$. Therefore also $\monadic{r}=\top$ and $(\monadic{v},\monadic{c})=(\top,\top)$. The latter pair is $q$-exact because of $d_0\ne\mbox{\lstinline+@public+}$ and $s_0=\mbox{\lstinline+$pre+}$. \end{itemize} Finally, $\gamma'$ is $\Gamma$-exact since $\gamma'=\gamma_2$ and $\gamma_2$ is $\Gamma$-exact. \item If $e=\stmtcomp{\letexpr{x}{e_1}}{e_2}$ then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{t_1}{s_1}{d_1}\mbox{,}\\ (x:\qualty{t_1}{s_1}{d_1}),\Gamma\mbox{\ $\vdash$\ } e_2:\qualty{t_0}{s_0}{d_0}\mbox{.} \end{array} \] Denote $q_1=(\qualty{t_1}{s_1}{d_1})$. By the induction hypothesis, $\semc{e_1}\gamma\phi\nu=\uopl{pure}((\monadic{v}_1,\monadic{c}_1),\gamma_1,\omicron_1,\nu_1)$ where $(\monadic{v}_1,\monadic{c}_1)$ is $q_1$-exact and $\gamma_1$ is $\Gamma$-exact. This implies $\left((x,(\monadic{v}_1,\monadic{c}_1)),\gamma_1\right)$ being $\Gamma'$-exact where $\Gamma'=((x:q_1),\Gamma)$. Hence by the induction hypothesis, $\semc{e_2}((x,(\monadic{v}_1,\monadic{c}_1)),\gamma_1)\phi\nu_1=\uopl{pure}((\monadic{v}_2,\monadic{c}_2),\gamma_2,\omicron_2,\nu_2)$ where $(\monadic{v}_2,\monadic{c}_2)$ is $q$-exact and $\gamma_2$ is $\Gamma'$-exact. Obviously $\uopl{tail}\gamma_2$ is \mbox{$\Gamma$-exact}. We obtain $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\gamma',\omicron,\nu')$ where \[ (\monadic{v},\monadic{c})=(\monadic{v}_2,\monadic{c}_2)\mbox{,}\quad\gamma'=\uopl{tail}\gamma_2\mbox{,}\quad\omicron=\omicron_1\omicron_2\mbox{,}\quad\nu'=\nu_2\mbox{.} \] The desired claim follows. \item If $e=\stmtcomp{e_1}{e_2}$ then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{t_1}{s_1}{d_1}\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:\qualty{t_0}{s_0}{d_0}\mbox{.} \end{array} \] Denote $q_1=(\qualty{t_1}{s_1}{d_1})$. By the induction hypothesis, $\semc{e_1}\gamma\phi\nu=\uopl{pure}((\monadic{v}_1,\monadic{c}_1),\gamma_1,\omicron_1,\nu_1)$ where $(\monadic{v}_1,\monadic{c}_1)$ is $q_1$-exact and $\gamma_1$ is $\Gamma$-exact. Hence by the induction hypothesis, $\semc{e_2}\gamma_1\phi\nu_1=\uopl{pure}((\monadic{v}_2,\monadic{c}_2),\gamma_2,\omicron_2,\nu_2)$ where $(\monadic{v}_2,\monadic{c}_2)$ is $q$-exact and $\gamma_2$ is $\Gamma$-exact. We obtain $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\gamma',\omicron,\nu')$ where \[ (\monadic{v},\monadic{c})=(\monadic{v}_2,\monadic{c}_2)\mbox{,}\quad\gamma'=\gamma_2\mbox{,}\quad\omicron=\omicron_1\omicron_2\mbox{,}\quad\nu'=\nu_2\mbox{.} \] The desired claim follows. \end{itemize} \end{proof} \begin{theorem}[Theorem \ref{thm:correct_compilation}] Let $\Gamma \mbox{\ $\vdash$\ } e:\qualty{t}{s}{d}! D$ with well-structured~$\Gamma$. Let $\gamma\in\mathbf{Env}_\mathrm{C}$ be $\Gamma$-exact, $\phi\in\mathbf{In}^3$ be a triple of type correct input dictionaries, and $\nu\in\mathbb{N}^2$. Let $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\tilde{\gamma},\tilde{\omicron},\tilde{\nu})$. Let $\pi\in(\mathbb{N}^*)^2$, $\gamma'\in\mathbf{Env}$, $\omicron'\in\mathbf{Out}^2$ be such that $\gamma'$ is $\Gamma$-exact in circuit, $\gamma\bullet\pi\sim\gamma'$ and $\nu\bullet\pi\sim\omicron'$. Then: \begin{enumerate} \item If $\sem{e}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}',\tilde{\gamma}',\tilde{\omicron}')$ then $\tilde{\omicron}$ accepts $\pi$; moreover, $\tilde{\gamma}\bullet\pi\sim\tilde{\gamma}'$ and $\tilde{\nu}\bullet\pi\sim\tilde{\omicron}'$, and $d=\mbox{\lstinline+@public+}$ or $s=\mbox{\lstinline+$post+}$ implies $(\monadic{v},\monadic{c})\bullet\pi\sim\monadic{v}'$; \item If $\sem{e}\gamma'\phi\omicron'$ fails (i.e., it is not of the form $\uopl{pure}(\monadic{v}',\tilde{\gamma}',\tilde{\omicron}')$), while all circuits that arise during compilation need only inputs in~$\pi$, then $\tilde{\omicron}$~{}does not accept~$\pi$. \end{enumerate} \end{theorem} \begin{proof} We proceed by induction on the structure of~$e$. \begin{itemize} \item If $e=\epsilon$ then \[ t=\mbox{\lstinline+()+}\mbox{,}\quad s=\mbox{\lstinline+$pre+}\mbox{,}\quad d=\mbox{\lstinline+@public+}\mbox{.} \] Furthermore, $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\tilde{\gamma},\tilde{\omicron},\tilde{\nu})$ where \[ (\monadic{v},\monadic{c})=(\uopl{pure}\mbox{\textoneoldstyle},\top)\mbox{,}\quad\tilde{\gamma}=\gamma\mbox{,}\quad\tilde{\omicron}=\epsilon\mbox{,}\quad\tilde{\nu}=\nu\mbox{,} \] and $\sem{e}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}',\tilde{\gamma}',\tilde{\omicron}')$ where \[ \monadic{v}'=\uopl{pure}\mbox{\textoneoldstyle}\mbox{,}\quad\tilde{\gamma}'=\gamma'\mbox{,}\quad\tilde{\omicron}'=\omicron'\mbox{.} \] The empty output circuit vacuously accepts~$\pi$. As $\tilde{\gamma}=\gamma$ and $\tilde{\gamma}'=\gamma'$, the claim $\tilde{\gamma}\bullet\pi\sim\tilde{\gamma}'$ follows from assumptions. As $\tilde{\nu}=\nu$ and $\tilde{\omicron}'=\omicron'$, the claim $\tilde{\nu}\bullet\pi\sim\tilde{\omicron}'$ also follows from assumptions. Finally, \[ (\monadic{v},\monadic{c})\bullet\pi=(\uopl{pure}\mbox{\textoneoldstyle},\top)\bullet\pi=\uopl{pure}\mbox{\textoneoldstyle}=\monadic{v}'\mbox{,} \] implying $(\monadic{v},\monadic{c})\bullet\pi\sim\monadic{v}'$. \item If $e=\overline{n}$ where $n\in\mathbb{N}$ then \[ t=\uintmodty{\mbox{\lstinline+N+}}\mbox{.} \] Furthermore, $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\tilde{\gamma},\tilde{\omicron},\tilde{\nu})$ where \[ \begin{array}{l} (\monadic{v},\monadic{c})=(\branching{\uopl{pure} n&\mbox{if $d=\mbox{\lstinline+@public+}$}\\\top&\mbox{otherwise}},\branching{\uopl{pure}(\mknode{\uopl{con}(n)})&\mbox{if $s=\mbox{\lstinline+$post+}$}\\\top&\mbox{otherwise}})\mbox{,}\\\tilde{\gamma}=\gamma\mbox{,}\quad\tilde{\omicron}=\epsilon\mbox{,}\quad\tilde{\nu}=\nu\mbox{,} \end{array} \] and $\sem{e}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}',\tilde{\gamma}',\tilde{\omicron}')$ where \[ \monadic{v}'=\branching{\uopl{pure} n&\mbox{if $s=\mbox{\lstinline+$post+}$ or $d=\mbox{\lstinline+@public+}$}\\\top&\mbox{otherwise}}\mbox{,}\quad\tilde{\gamma}'=\gamma'\mbox{,}\quad\tilde{\omicron}'=\omicron'\mbox{.} \] The empty output circuit vacuously accepts~$\pi$. As $\tilde{\gamma}=\gamma$ and $\tilde{\gamma}'=\gamma'$, the claim $\tilde{\gamma}\bullet\pi\sim\tilde{\gamma}'$ follows from assumptions. As $\tilde{\nu}=\nu$ and $\tilde{\omicron}'=\omicron'$, the claim $\tilde{\nu}\bullet\pi\sim\tilde{\omicron}'$ also follows from assumptions. Finally, if $d=\mbox{\lstinline+@public+}$ then \[ (\monadic{v},\monadic{c})\bullet\pi=(\uopl{pure} n,\monadic{c})\bullet\pi=\uopl{pure} n=\monadic{v}'\mbox{,} \] and if $d\ne\mbox{\lstinline+@public+}$ but $s=\mbox{\lstinline+$post+}$ then \[ (\monadic{v},\monadic{c})\bullet\pi=(\top,\uopl{pure}(\mknode{\uopl{con}(n)}))\bullet\pi=\uopl{pure}(\mknode{\uopl{con}(n)}(\pi))=\uopl{pure} n=\monadic{v}'\mbox{,} \] implying $(\monadic{v},\monadic{c})\bullet\pi\sim\monadic{v}'$. \item If $e=\overline{b}$ where $b\in\mathbb{B}$ then \[ t=\boolmodty{\mbox{\lstinline+N+}}\mbox{.} \] Furthermore, $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\tilde{\gamma},\tilde{\omicron},\tilde{\nu})$ where \[ \begin{array}{l} (\monadic{v},\monadic{c})=(\branching{\uopl{pure} b&\mbox{if $d=\mbox{\lstinline+@public+}$}\\\top&\mbox{otherwise}},\branching{\uopl{pure}(\mknode{\uopl{con}(|b|)})&\mbox{if $s=\mbox{\lstinline+$post+}$}\\\top&\mbox{otherwise}})\mbox{,}\\\tilde{\gamma}=\gamma\mbox{,}\quad\tilde{\omicron}=\epsilon\mbox{,}\quad\tilde{\nu}=\nu\mbox{,} \end{array} \] and $\sem{e}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}',\tilde{\gamma}',\tilde{\omicron}')$ where \[ \monadic{v}'=\branching{\uopl{pure} b&\mbox{if $s=\mbox{\lstinline+$post+}$ or $d=\mbox{\lstinline+@public+}$}\\\top&\mbox{otherwise}}\mbox{,}\quad\tilde{\gamma}'=\gamma'\mbox{,}\quad\tilde{\omicron}'=\omicron'\mbox{.} \] The empty output circuit vacuously accepts~$\pi$. As $\tilde{\gamma}=\gamma$ and $\tilde{\gamma}'=\gamma'$, the claim $\tilde{\gamma}\bullet\pi\sim\tilde{\gamma}'$ follows from assumptions. As $\tilde{\nu}=\nu$ and $\tilde{\omicron}'=\omicron'$, the claim $\tilde{\nu}\bullet\pi\sim\tilde{\omicron}'$ also follows from assumptions. Finally, if $d=\mbox{\lstinline+@public+}$ then \[ (\monadic{v},\monadic{c})\bullet\pi=(\uopl{pure} b,\monadic{c})\bullet\pi=\uopl{pure}|b|\sim\uopl{pure} b=\monadic{v}'\mbox{,} \] and if $d\ne\mbox{\lstinline+@public+}$ but $s=\mbox{\lstinline+$post+}$ then \[ \begin{array}{lcl} (\monadic{v},\monadic{c})\bullet\pi &=&(\top,\uopl{pure}(\mknode{\uopl{con}(|b|)}))\bullet\pi\\ &=&\uopl{pure}(\mknode{\uopl{con}(|b|)}(\pi))=\uopl{pure} |b|\sim\uopl{pure} b=\monadic{v}'\mbox{.} \end{array} \] \item If $e=x$ then $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\tilde{\gamma},\tilde{\omicron},\tilde{\nu})$ where \[ (\monadic{v},\monadic{c})=\lookup{\gamma}{x}\mbox{,}\quad\tilde{\gamma}=\gamma\mbox{,}\quad\tilde{\omicron}=\epsilon\mbox{,}\quad\tilde{\nu}=\nu\mbox{,} \] and $\sem{e}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}',\tilde{\gamma}',\tilde{\omicron}')$ where \[ \monadic{v}'=\lookup{\gamma'}{x}\mbox{,}\quad\tilde{\gamma}'=\gamma'\mbox{,}\quad\tilde{\omicron}'=\omicron'\mbox{.} \] The empty output circuit vacuously accepts~$\pi$. As $\tilde{\gamma}=\gamma$ and $\tilde{\gamma}'=\gamma'$, the claim $\tilde{\gamma}\bullet\pi\sim\tilde{\gamma}'$ follows from assumptions. As $\tilde{\nu}=\nu$ and $\tilde{\omicron}'=\omicron'$, the claim $\tilde{\nu}\bullet\pi\sim\tilde{\omicron}'$ also follows from assumptions. Finally, \[ (\monadic{v},\monadic{c})\bullet\pi=(\lookup{\gamma}{x})\bullet\pi=\lookup{(\gamma\bullet\pi)}{x}\sim\gamma' x=\monadic{v}'\mbox{.} \] \item Let $e=\addexpr{e_1}{e_2}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:q\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:q\mbox{,}\\ t=\uintmodty{\mbox{\lstinline+N+}}\mbox{.} \end{array} \] Furthermore, \[ \begin{array}{l} \semc{e_1}\gamma\phi\nu=\uopl{pure}((\monadic{v}_1,\monadic{c}_1),\gamma_1,\omicron_1,\nu_1)\mbox{,}\\ \semc{e_2}\gamma_1\phi\nu_1=\uopl{pure}((\monadic{v}_2,\monadic{c}_2),\gamma_2,\omicron_2,\nu_2)\mbox{,} \end{array} \] and $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\tilde{\gamma},\tilde{\omicron},\tilde{\nu})$ where \[ \begin{array}{l} \monadic{v}=\mcomp{i_1\gets\monadic{v}_1;\; i_2\gets\monadic{v}_2;\;\uopl{pure}(i_1+i_2)}\mbox{,}\\ \monadic{c}=\mcomp{c_1\gets\monadic{c}_1;\; c_2\gets\monadic{c}_2;\;\uopl{pure}(\mknode{\uopl{op}(+)}(c_1,c_2))}\mbox{,}\\ \tilde{\gamma}=\gamma_2\mbox{,}\quad\tilde{\omicron}=\omicron_1\omicron_2\mbox{,}\quad\tilde{\nu}=\nu_2\mbox{.} \end{array} \] Firstly, suppose that $\sem{e}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}',\tilde{\gamma}',\tilde{\omicron}')$. Then \[ \begin{array}{l} \sem{e_1}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}'_1,\gamma'_1,\omicron'_1)\mbox{,}\\ \sem{e_2}\gamma'_1\phi\omicron'_1=\uopl{pure}(\monadic{v}'_2,\gamma'_2,\omicron'_2)\mbox{,}\\ \monadic{v}'=\mcomp{v_1\gets\monadic{v}'_1;\; v_2\gets\monadic{v}'_2;\;\uopl{pure}(v_1+v_2)}\mbox{,}\quad\tilde{\gamma}'=\gamma'_2\mbox{,}\quad\tilde{\omicron}'=\omicron'_2\mbox{.} \end{array} \] By the induction hypothesis, $\omicron_1$ accepts~$\pi$, whereby $\gamma_1\bullet\pi\sim\gamma'_1$, $\nu_1\bullet\pi\sim\omicron'_1$, and $d=\mbox{\lstinline+@public+}$ or $s=\mbox{\lstinline+$post+}$ implies $(\monadic{v}_1,\monadic{c}_1)\bullet\pi\sim\monadic{v}'_1$. By the induction hypothesis again, $\omicron_2$ accepts~$\pi$, whereby $\gamma_2\bullet\pi\sim\gamma'_2$, $\nu_2\bullet\pi\sim\omicron'_2$, and $d=\mbox{\lstinline+@public+}$ or $s=\mbox{\lstinline+$post+}$ implies $(\monadic{v}_2,\monadic{c}_2)\bullet\pi\sim\monadic{v}'_2$. Hence $\tilde{\omicron}$ accepts~$\pi$, whereby $\tilde{\gamma}\bullet\pi\sim\tilde{\gamma}'$ and $\tilde{\nu}\bullet\pi\sim\tilde{\omicron}'$. Suppose that $d=\mbox{\lstinline+@public+}$ or $s=\mbox{\lstinline+$post+}$. Consider two cases: \begin{itemize} \item If $d=\mbox{\lstinline+@public+}$ then, by exactness, $\monadic{v}_1=\uopl{pure} v_1$, $\monadic{v}_2=\uopl{pure} v_2$ and $\monadic{v}=\uopl{pure}(v_1+v_2)$ where $v_1,v_2\in\mathbb{N}$. Thus $(\monadic{v}_1,\monadic{c}_1)\bullet\pi=\uopl{pure} v_1$, $(\monadic{v}_2,\monadic{c}_2)\bullet\pi=\uopl{pure} v_2$ and $(\monadic{v},\monadic{c})\bullet\pi=\uopl{pure}(v_1+v_2)$. Hence $\uopl{pure} v_1\sim\monadic{v}'_1$ and $\uopl{pure} v_2\sim\monadic{v}'_2$, implying $\monadic{v}'_1=\uopl{pure} v_1$ and $\monadic{v}'_2=\uopl{pure} v_2$. Therefore $\monadic{v}'=\uopl{pure}(v_1+v_2)$, leading to $(\monadic{v},\monadic{c})\bullet\pi\sim\monadic{v}'$ as needed. \item If $s=\mbox{\lstinline+$post+}$ and $d_0\ne\mbox{\lstinline+@public+}$ then, by exactness, $\monadic{c}_1=\uopl{pure} c_1$, $\monadic{c}_2=\uopl{pure} c_2$ and $\monadic{c}=\mcomp{c_1\gets\monadic{c}_1;\; c_2\gets\monadic{c}_2;\;\uopl{pure}(\mknode{\uopl{op}(+)}(c_1,c_2))}$. Thus $(\monadic{v}_1,\monadic{c}_1)\bullet\pi=\uopl{pure}(c_1(\pi))$, $(\monadic{v}_2,\monadic{c}_2)\bullet\pi=\uopl{pure}(c_2(\pi))$ and $(\monadic{v},\monadic{c})\bullet\pi=\uopl{pure}(c_1(\pi)+c_2(\pi))$. Let $c_1(\pi)=v_1$ and $c_2(\pi)=v_2$; then $\uopl{pure} v_1\sim\monadic{v}'_1$ and $\uopl{pure} v_2\sim\monadic{v}'_2$, implying $\monadic{v}'_1=\uopl{pure} v_1$ and $\monadic{v}'_2=\uopl{pure} v_2$. Therefore $\monadic{v}'=\uopl{pure}(v_1+v_2)$, leading to $(\monadic{v},\monadic{c})\bullet\pi\sim\monadic{v}'$ as needed. \end{itemize} Conversely, assume that $\tilde{\omicron}$ accepts~$\pi$. Then both $\omicron_1$ and $\omicron_2$ accept~$\pi$. By the induction hypothesis, $\sem{e_1}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}'_1,\gamma'_1,\omicron'_1)$ where $\gamma_1\bullet\pi\sim\gamma'_1$ and $\nu_1\bullet\pi\sim\omicron'_1$. By the induction hypothesis, $\sem{e_2}\gamma'_1\phi\omicron'_1=\uopl{pure}(\monadic{v}'_2,\gamma'_2,\omicron'_2)$. Therefore $\sem{e}\gamma'\phi\omicron'$ does not fail. \item Let $e=\assertexpr{e_1}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{\boolmodty{\mbox{\lstinline+N+}}}{\mbox{\lstinline+$post+}}{d'}\mbox{,}\\ t=\mbox{\lstinline+()+}\mbox{,}\quad s=\mbox{\lstinline+$pre+}\mbox{,}\quad d=\mbox{\lstinline+@public+}\mbox{.} \end{array} \] Furthermore, \[ \begin{array}{l} \semc{e_1}\gamma\phi\nu=\uopl{pure}((\monadic{v}_1,\monadic{c}_1),\gamma_1,\omicron_1,\nu_1) \end{array} \] with $\monadic{c}_1=\uopl{pure} c_1$, and $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\tilde{\gamma},\tilde{\omicron},\tilde{\nu})$ where \[ \begin{array}{l} (\monadic{v},\monadic{c})=(\uopl{pure}\mbox{\textoneoldstyle},\top)\mbox{,}\\ \tilde{\gamma}=\gamma_1\mbox{,}\quad\tilde{\omicron}=\omicron_1c_1\mbox{,}\quad\tilde{\nu}=\nu_1\mbox{.} \end{array} \] Firstly, suppose that $\sem{e}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}',\tilde{\gamma}',\tilde{\omicron}')$. Then \[ \begin{array}{l} \sem{e_1}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}'_1,\gamma'_1,\omicron'_1)\mbox{,}\\ \monadic{v}'_1\ne\uopl{pure}\mbox{\bfseries ff}\mbox{,}\quad\monadic{v}'=\uopl{pure}\mbox{\textoneoldstyle}\mbox{,}\quad\tilde{\gamma}'=\gamma'_1\mbox{,}\quad\tilde{\omicron}'=\omicron'_1\mbox{.} \end{array} \] By the induction hypothesis, $\omicron_1$ accepts~$\pi$, whereby $\gamma_1\bullet\pi\sim\gamma'_1$, $\nu_1\bullet\pi\sim\omicron'_1$, and $(\monadic{v}_1,\monadic{c}_1)\bullet\pi\sim\monadic{v}'_1$. If $d'=\mbox{\lstinline+@public+}$ then, by exactness, $\monadic{v}_1=\uopl{pure} v_1$ where $v_1\in\mathbb{B}$ and $|c_1|=\uopl{pure}|v_1|=\uopl{pure}(c_1(\pi))$. Hence $(\monadic{v}_1,\monadic{c}_1)\bullet\pi=\uopl{pure}|v_1|=\uopl{pure}(c_1(\pi))$. If $d'\ne\mbox{\lstinline+@public+}$ then, by exactness, $\monadic{v}_1=\top$. Therefore $(\monadic{v}_1,\monadic{c}_1)\bullet\pi=\uopl{pure}(c_1(\pi))$ again. By $\uopl{pure}(c_1(\pi))\sim\monadic{v}'_1$, we obtain $\monadic{v}'_1=\uopl{pure} v'_1$ where $|v'_1|=c_1(\pi)$. As $\monadic{v}'_1\ne\uopl{pure}\mbox{\bfseries ff}$, we must have $v'_1=\mbox{\bfseries tt}$, whence $c_1(\pi)=0$. Altogether, we proved that $\tilde{\omicron}$ accepts~$\pi$. We have also obtained that $\tilde{\gamma}\bullet\pi\sim\tilde{\gamma}'$ and $\tilde{\nu}\bullet\pi\sim\tilde{\omicron}'$. In addition, $(\monadic{v},\monadic{c})\bullet\pi=\uopl{pure}\mbox{\textoneoldstyle}=\monadic{v}'$. Conversely, assume that $\tilde{\omicron}$ accepts~$\pi$. Then $\omicron_1$ accepts~$\pi$ and $c_1(\pi)=0$. By the induction hypothesis, $\sem{e_1}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}'_1,\gamma'_1,\omicron'_1)$ where $\gamma_1\bullet\pi\sim\gamma'_1$, $\nu_1\bullet\pi\sim\omicron'_1$ and $(\monadic{v}_1,\monadic{c}_1)\bullet\pi\sim\monadic{v}'_1$. If $d'=\mbox{\lstinline+@public+}$ then, by exactness, $\monadic{v}_1=\uopl{pure} v_1$ where $v_1\in\mathbb{B}$ and $|c_1|=\uopl{pure}|v_1|=\uopl{pure}(c_1(\pi))$. Hence $(\monadic{v}_1,\monadic{c}_1)\bullet\pi=\uopl{pure}|v_1|=\uopl{pure}(c_1(\pi))$. If $d'\ne\mbox{\lstinline+@public+}$ then, by exactness, $\monadic{v}_1=\top$. Therefore $(\monadic{v}_1,\monadic{c}_1)\bullet\pi=\uopl{pure}(c_1(\pi))$ again. As $c_1(\pi)\sim\monadic{v}'_1$ and $c_1(\pi)=0$, we must have $\monadic{v}'_1=\uopl{pure}\mbox{\bfseries tt}$. Consequently, $\sem{e}\gamma'\phi\omicron'=\uopl{pure}(\uopl{pure}\mbox{\textoneoldstyle},\gamma'_1,\omicron'_1)$. The desired result follows. \item If $e=\getexpr{d'}{k}$ where $d'$ is a domain and $k$ is an input key then \[ \uopl{allpre}_{d'}(q)\mbox{,} \] which implies $d=d'$ and $s=\mbox{\lstinline+$pre+}$. Furthermore, $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\tilde{\gamma},\tilde{\omicron},\tilde{\nu})$ where \[ \begin{array}{l} (\monadic{v},\monadic{c})=\branching{\uopl{allpuretop}(\phi_{d'}(k))&\mbox{if $d'=\mbox{\lstinline+@public+}$}\\(\top,\top)&\mbox{otherwise}}\mbox{,}\\\tilde{\gamma}=\gamma\mbox{,}\quad\tilde{\omicron}=\epsilon\mbox{,}\quad\tilde{\nu}=\nu\mbox{,} \end{array} \] and $\sem{e}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}',\tilde{\gamma}',\tilde{\omicron}')$ where \[ \monadic{v}'=\branching{\uopl{allpure}(\phi_{d'}(k))&\mbox{if $d'=\mbox{\lstinline+@public+}$}\\\top&\mbox{otherwise}}\mbox{,}\quad\tilde{\gamma}'=\gamma'\mbox{,}\quad\tilde{\omicron}'=\omicron'\mbox{.} \] The empty output circuit vacuously accepts~$\pi$. As $\tilde{\gamma}=\gamma$ and $\tilde{\gamma}'=\gamma'$, the claim $\tilde{\gamma}\bullet\pi\sim\tilde{\gamma}'$ follows from assumptions. As $\tilde{\nu}=\nu$ and $\tilde{\omicron}'=\omicron'$, the claim $\tilde{\nu}\bullet\pi\sim\tilde{\omicron}'$ also follows from assumptions. Finally, $\uopl{allpuretop}_{d'}(\phi_{d'}(k))\bullet\pi=\uopl{allpure}_{d'}(\phi_{d'}(k))$ by Lemma~\ref{compilation:getlemma}, whence $(\monadic{v},\monadic{c})\bullet\pi\sim\monadic{v}'$ in the case $d=\mbox{\lstinline+@public+}$. \item Let $e=\ifexpr{e_1}{e_2}{e_3}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{\boolmodty{\mbox{\lstinline+N+}}}{\mbox{\lstinline+$pre+}}{d'}\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:q\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_3:q\mbox{.} \end{array} \] Furthermore, \[ \begin{array}{l} \semc{e_1}\gamma\phi\nu=\uopl{pure}((\monadic{v}_1,\monadic{c}_1),\gamma_1,\omicron_1,\nu_1)\mbox{.} \end{array} \] Firstly, suppose that $\sem{e}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}',\tilde{\gamma}',\tilde{\omicron}')$. Then, for some $\monadic{v}'_1$, $\gamma'_1$, $\omicron'_1$, \[ \begin{array}{l} \sem{e_1}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}'_1,\gamma'_1,\omicron'_1)\mbox{.} \end{array} \] By the induction hypothesis, $\omicron_1$ accepts~$\pi$, whereby $\gamma_1\bullet\pi\sim\gamma'_1$, $\nu_1\bullet\pi\sim\omicron'_1$, and $d'=\mbox{\lstinline+@public+}$ implies $(\monadic{v}_1,\monadic{c}_1)\bullet\pi\sim\monadic{v}'_1$. Consider three cases: \begin{itemize} \item Let $\monadic{v}_1=\uopl{pure}\mbox{\bfseries tt}$. Then \[ \semc{e_2}\gamma_1\phi\nu_1=\uopl{pure}((\monadic{v}_2,\monadic{c}_2),\gamma_2,\omicron_2,\nu_2)\mbox{,} \] and $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\tilde{\gamma},\tilde{\omicron},\tilde{\nu})$ where \[ \begin{array}{l} (\monadic{v},\monadic{c})=(\monadic{v}_2,\monadic{c}_2)\mbox{,}\quad\tilde{\gamma}=\gamma_2\mbox{,}\quad\tilde{\omicron}=\omicron_1\omicron_2\mbox{,}\quad\tilde{\nu}=\nu_2\mbox{.} \end{array} \] If $d'\ne\mbox{\lstinline+@public+}$ then, by exactness, $\monadic{v}_1=\top$. Thus $d'=\mbox{\lstinline+@public+}$ must hold. Hence $(\monadic{v}_1,\monadic{c}_1)\bullet\pi\sim\monadic{v}'_1$ which implies $\monadic{v}'_1=\uopl{pure}\mbox{\bfseries tt}$. Consequently, \[ \begin{array}{l} \sem{e_2}\gamma'_1\phi\omicron'_1=\uopl{pure}(\monadic{v}'_2,\gamma'_2,\omicron'_2)\mbox{,}\\ \monadic{v}'=\monadic{v}'_2\mbox{,}\quad\tilde{\gamma}'=\gamma'_2\mbox{,}\quad\tilde{\omicron}'=\omicron'_2\mbox{.} \end{array} \] By the induction hypothesis, $\omicron_2$ accepts~$\pi$, whereby $\gamma_2\bullet\pi\sim\gamma'_2$, $\nu_2\bullet\pi\sim\omicron'_2$, and $d=\mbox{\lstinline+@public+}$ or $s=\mbox{\lstinline+$post+}$ implies $(\monadic{v}_2,\monadic{c}_2)\bullet\pi\sim\monadic{v}'_2$. Hence $\omicron_1\omicron_2$ accepts~$\pi$, whereby $\tilde{\gamma}\bullet\pi\sim\tilde{\gamma}'$, $\tilde{\nu}\bullet\pi\sim\tilde{\omicron}'$, and $d=\mbox{\lstinline+@public+}$ or $s=\mbox{\lstinline+$post+}$ implies $(\monadic{v},\monadic{c})\bullet\pi\sim\monadic{v}'$. \item The case $\monadic{v}_1=\uopl{pure}\mbox{\bfseries ff}$ is similar to the previous case. \item If $\monadic{v}_1\ne\uopl{pure} b$ for $b\in\mathbb{B}$ then, by exactness, $d'\ne\mbox{\lstinline+@public+}$ and $\monadic{v}_1=\top$. Hence $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\tilde{\gamma},\tilde{\omicron},\tilde{\nu})$ where \[ \begin{array}{l} (\monadic{v},\monadic{c})=(\top,\top)\mbox{,}\quad\tilde{\gamma}=\gamma_1\mbox{,}\quad\tilde{\omicron}=\omicron_1\mbox{,}\quad\tilde{\nu}=\nu_1\mbox{.} \end{array} \] As $d'\ne\mbox{\lstinline+@public+}$ and $e_1$ has stage $\mbox{\lstinline+$pre+}$, we must have $\monadic{v}'_1=\top$ by exactness in circuit. Consequently, \[ \monadic{v}'=\top\mbox{,}\quad\tilde{\gamma}'=\gamma'_1\mbox{,}\quad\tilde{\omicron}'=\omicron'_1\mbox{.} \] We obtain all the desired claims. \end{itemize} Conversely, suppose that $\tilde{\omicron}$ accepts~$\pi$. In all possible cases, this implies that $\omicron_1$ accepts~$\pi$. By the induction hypothesis, $\sem{e_1}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}'_1,\gamma'_1,\omicron'_1)$, whereby $\gamma_1\bullet\pi\sim\gamma'_1$, $\nu_1\bullet\pi\sim\omicron'_1$, and $d'=\mbox{\lstinline+@public+}$ implies $(\monadic{v}_1,\monadic{c}_1)\bullet\pi\sim\monadic{v}'_1$. Consider three cases: \begin{itemize} \item Let $\monadic{v}_1=\uopl{pure}\mbox{\bfseries tt}$. Then \[ \semc{e_2}\gamma_1\phi\nu_1=\uopl{pure}((\monadic{v}_2,\monadic{c}_2),\gamma_2,\omicron_2,\nu_2)\mbox{,} \] and $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\tilde{\gamma},\tilde{\omicron},\tilde{\nu})$ where \[ \begin{array}{l} (\monadic{v},\monadic{c})=(\monadic{v}_2,\monadic{c}_2)\mbox{,}\quad\tilde{\gamma}=\gamma_2\mbox{,}\quad\tilde{\omicron}=\omicron_1\omicron_2\mbox{,}\quad\tilde{\nu}=\nu_2\mbox{.} \end{array} \] If $d'\ne\mbox{\lstinline+@public+}$ then, by exactness, $\monadic{v}_1=\top$. Thus $d'=\mbox{\lstinline+@public+}$ must hold. Hence $(\monadic{v}_1,\monadic{c}_1)\bullet\pi\sim\monadic{v}'_1$ which implies $\monadic{v}'_1=\uopl{pure}\mbox{\bfseries tt}$. The assumption that $\tilde{\omicron}$ accepts~$\pi$ implies that $\omicron_2$ accepts~$\pi$. By the induction hypothesis, $\sem{e_2}\gamma'_1\phi\omicron'_1=\uopl{pure}(\monadic{v}'_2,\gamma'_2,\omicron'_2)$, whereby $\gamma_2\bullet\pi\sim\gamma'_2$, $\nu_2\bullet\pi\sim\omicron'_2$, and $d=\mbox{\lstinline+@public+}$ or $s=\mbox{\lstinline+$post+}$ implies $(\monadic{v}_2,\monadic{c}_2)\bullet\pi\sim\monadic{v}'_2$. We obtain $\sem{e}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}'_2,\gamma'_2,\omicron'_2)$ which implies the desired result. \item The case $\monadic{v}_1=\uopl{pure}\mbox{\bfseries ff}$ is similar to the previous case. \item If $\monadic{v}_1\ne\uopl{pure} b$ for $b\in\mathbb{B}$ then, by exactness, $d'\ne\mbox{\lstinline+@public+}$ and $\monadic{v}_1=\top$. As $d'\ne\mbox{\lstinline+@public+}$ and $e_1$ has stage $\mbox{\lstinline+$pre+}$, we must have $\monadic{v}'_1=\top$ by exactness in circuit. Hence $\sem{e}\gamma'\phi\omicron'=\uopl{pure}(\top,\gamma'_1,\omicron'_1)$ which implies the desired result. \end{itemize} \item Let $e=\forexpr{x}{e_1}{e_2}{e_3}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d}\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d}\mbox{,}\\ (x:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d}),\Gamma\mbox{\ $\vdash$\ } e_3:\qualty{t_1}{s_1}{d_1}\mbox{,}\\ t=\listty{\qualty{t_1}{s_1}{d_1}}\mbox{,}\quad s=\mbox{\lstinline+$pre+}\mbox{.} \end{array} \] Furthermore, \[ \begin{array}{l} \semc{e_1}\gamma\phi\nu=\uopl{pure}((\monadic{v}_1,\monadic{c}_1),\gamma_1,\omicron_1,\nu_1)\mbox{,}\\ \semc{e_2}\gamma_1\phi\nu_1=\uopl{pure}((\monadic{v}_2,\monadic{c}_2),\gamma_2,\omicron_2,\nu_2)\mbox{.} \end{array} \] Firstly, suppose that $\sem{e}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}',\tilde{\gamma}',\tilde{\omicron}')$. Then \[ \begin{array}{l} \sem{e_1}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}'_1,\gamma'_1,\omicron'_1)\mbox{,}\\ \sem{e_2}\gamma'_1\phi\omicron'_1=\uopl{pure}(\monadic{v}'_2,\gamma'_2,\omicron'_2)\mbox{.} \end{array} \] By the induction hypothesis, $\omicron_1$ accepts~$\pi$, whereby $\gamma_1\bullet\pi\sim\gamma'_1$, $\nu_1\bullet\pi\sim\omicron'_1$, and $d=\mbox{\lstinline+@public+}$ implies $(\monadic{v}_1,\monadic{c}_1)\bullet\pi\sim\monadic{v}'_1$. Again by the induction hypothesis, $\omicron_2$ accepts~$\pi$, whereby $\gamma_2\bullet\pi\sim\gamma'_2$, $\nu_2\bullet\pi\sim\omicron'_2$, and $d=\mbox{\lstinline+@public+}$ implies $(\monadic{v}_2,\monadic{c}_2)\bullet\pi\sim\monadic{v}'_2$. Consider two cases: \begin{itemize} \item Let $\monadic{v}_1=\uopl{pure} i_1$ and $\monadic{v}_2=\uopl{pure} i_2$, where $i_1,i_2\in\mathbb{N}$. Denoting $n=\max(0,i_2-i_1)$, we obtain \[ \begin{array}{l} \semc{e_3}\left((x,(\uopl{pure} i_1,\top)),\gamma_2\right)\phi\nu_2=\uopl{pure}((\monadic{v}_3,\monadic{c}_3),\gamma_3,\omicron_3,\nu_3)\mbox{,}\\ \semc{e_3}([x\mapsto(\uopl{pure}(i_1+1),\top)]\gamma_3)\phi\nu_3=\uopl{pure}((\monadic{v}_4,\monadic{c}_4),\gamma_4,\omicron_4,\nu_4)\mbox{,}\\ \dotfill\\ \semc{e_3}([x\mapsto(\uopl{pure}(i_1+n-1),\top)]\gamma_{n+1})\phi\nu_{n+1}=\uopl{pure}((\monadic{v}_{n+2},\monadic{c}_{n+2}),\gamma_{n+2},\omicron_{n+2},\nu_{n+2})\mbox{,}\\ \end{array} \] and $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\tilde{\gamma},\tilde{\omicron},\tilde{\nu})$ where \[ \begin{array}{l} (\monadic{v},\monadic{c})=(\uopl{pure}((\monadic{v}_3,\monadic{c}_3),\ldots,(\monadic{v}_{n+2},\monadic{c}_{n+2})),\top)\mbox{,}\quad\tilde{\gamma}=\uopl{tail}\gamma_{n+2}\mbox{,}\quad\tilde{\omicron}=\omicron_1\ldots\omicron_{n+2}\mbox{,}\quad\tilde{\nu}=\nu_{n+2}\mbox{.} \end{array} \] If $d\ne\mbox{\lstinline+@public+}$ then, by exactness, $\monadic{v}_1=\monadic{v}_2=\top$. Thus $d=\mbox{\lstinline+@public+}$ must hold. Hence $(\monadic{v}_1,\monadic{c}_1)\bullet\pi\sim\monadic{v}'_1$, $(\monadic{v}_2,\monadic{c}_2)\bullet\pi\sim\monadic{v}'_2$ which imply $\monadic{v}'_1=\uopl{pure} i_1$, $\monadic{v}'_2=\uopl{pure} i_2$. Consequently, \[ \begin{array}{l} \sem{e_3}\left((x,\uopl{pure} i_1),\gamma'_2\right)\phi\omicron'_2=\uopl{pure}(\monadic{v}'_3,\gamma'_3,\omicron'_3)\mbox{,}\\ \sem{e_3}([x\mapsto\uopl{pure}(i_1+1)]\gamma'_3)\phi\omicron'_3=\uopl{pure}(\monadic{v}'_4,\gamma'_4,\omicron'_4)\mbox{,}\\ \dotfill\\ \sem{e_3}([x\mapsto\uopl{pure}(i_1+n-1)]\gamma'_{n+1})\phi\omicron'_{n+1}=\uopl{pure}(\monadic{v}'_{n+2},\gamma'_{n+2},\omicron'_{n+2})\mbox{,}\\ \monadic{v}'=\uopl{pure}(\monadic{v}'_3,\ldots,\monadic{v}'_{n+2})\mbox{,}\quad\tilde{\gamma}'=\uopl{tail}\gamma'_{n+2}\mbox{,}\quad\tilde{\omicron}'=\omicron'_{n+2}\mbox{.} \end{array} \] As $\gamma_2\bullet\pi\sim\gamma'_2$ and $(\uopl{pure} i_1,\top)\bullet\pi\sim\uopl{pure} i_1$, we have $\left((x,(\uopl{pure} i_1,\top)),\gamma_2\right)\bullet\pi\sim\left((x,\uopl{pure} i_1),\gamma'_2\right)$. Hence by the induction hypothesis, $\omicron_3$ accepts~$\pi$, whereby $\gamma_3\bullet\pi\sim\gamma'_3$, $\nu_3\bullet\pi\sim\omicron'_3$, and $d_1=\mbox{\lstinline+@public+}$ or $s_1=\mbox{\lstinline+$post+}$ implies $(\monadic{v}_3,\monadic{c}_3)\bullet\pi\sim\monadic{v}'_3$. Similarly, we get $\omicron_k$ accepting~$\pi$, $\gamma_k\bullet\pi\sim\gamma'_k$, $\nu_k\bullet\pi\sim\omicron'_k$, and $d_1=\mbox{\lstinline+@public+}$ or $s_1=\mbox{\lstinline+$post+}$ implying $(\monadic{v}_k,\monadic{c}_k)\bullet\pi\sim\monadic{v}'_k$ for every $k=4,\ldots,n+2$. Obviously also $\uopl{tail}\gamma_{n+2}\bullet\pi\sim\uopl{tail}\gamma'_{n+2}$. Altogether, we have proved that $\omicron_1\ldots\omicron_{n+2}$ accepts~$\pi$, whereby $\tilde{\gamma}\bullet\pi\sim\tilde{\gamma}'$ and $\tilde{\nu}\bullet\pi\sim\tilde{\omicron}'$. Assume $d=\mbox{\lstinline+@public+}$. If $d_1=\mbox{\lstinline+@public+}$ or $s_1=\mbox{\lstinline+$post+}$ then \[ (\monadic{v},\monadic{c})\bullet\pi =\uopl{pure}((\monadic{v}_3,\monadic{c}_3)\bullet\pi,\ldots,(\monadic{v}_{n+2},\monadic{c}_{n+2})\bullet\pi) \sim\uopl{pure}(\monadic{v}'_3,\ldots,\monadic{v}'_{n+2}) =\monadic{v}' \] as required. If $d_1\ne\mbox{\lstinline+@public+}$ and $s_1=\mbox{\lstinline+$pre+}$ then, by exactness and exactness in circuit, $(\monadic{v}_k,\monadic{c}_k)=(\top,\top)$ and $\monadic{v}'_k=\top$. Hence $(\monadic{v}_k,\monadic{c}_k)\bullet\pi\sim\monadic{v}'_k$ in this case, too, whence all the desired claims follow. \item If $\monadic{v}_1\ne\uopl{pure} i_1$ or $\monadic{v}_2\ne\uopl{pure} i_2$ for $i_1,i_2\in\mathbb{N}$ then, by exactness, $d\ne\mbox{\lstinline+@public+}$ and $\monadic{v}_1=\monadic{v}_2=\top$. Hence $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\tilde{\gamma},\tilde{\omicron},\tilde{\nu})$ where \[ \begin{array}{l} (\monadic{v},\monadic{c})=(\top,\top)\mbox{,}\quad\tilde{\gamma}=\gamma_2\mbox{,}\quad\tilde{\omicron}=\omicron_1\omicron_2\mbox{,}\quad\tilde{\nu}=\nu_2\mbox{.} \end{array} \] As $d\ne\mbox{\lstinline+@public+}$ and $e_1,e_2$ have stage $\mbox{\lstinline+$pre+}$, we must have $\monadic{v}'_1=\monadic{v}'_2=\top$ by exactness in circuit. Consequently, \[ \monadic{v}'=\top\mbox{,}\quad\tilde{\gamma}'=\gamma'_2\mbox{,}\quad\tilde{\omicron}'=\omicron'_2\mbox{.} \] We obtain all the desired claims. \end{itemize} Conversely, suppose that $\tilde{\omicron}$ accepts~$\pi$. In all possible cases, this implies that $\omicron_1$ and $\omicron_2$ accept~$\pi$. By the induction hypothesis, $\sem{e_1}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}'_1,\gamma'_1,\omicron'_1)$, whereby $\gamma_1\bullet\pi\sim\gamma'_1$, $\nu_1\bullet\pi\sim\omicron'_1$, and $d=\mbox{\lstinline+@public+}$ implies $(\monadic{v}_1,\monadic{c}_1)\bullet\pi\sim\monadic{v}'_1$. By the induction hypothesis, $\sem{e_2}\gamma'_1\phi\omicron'_1=\uopl{pure}(\monadic{v}'_2,\gamma'_2,\omicron'_2)$, whereby $\gamma_2\bullet\pi\sim\gamma'_2$, $\nu_2\bullet\pi\sim\omicron'_2$, and $d=\mbox{\lstinline+@public+}$ implies $(\monadic{v}_2,\monadic{c}_2)\bullet\pi\sim\monadic{v}'_2$. Consider two cases: \begin{itemize} \item Let $\monadic{v}_1=\uopl{pure} i_1$ and $\monadic{v}_2=\uopl{pure} i_2$ where $i_1,i_2\in\mathbb{N}$. Denoting $n=\max(0,i_2-i_1)$, we obtain \[ \begin{array}{l} \semc{e_3}\left((x,(\uopl{pure} i_1,\top)),\gamma_2\right)\phi\nu_2=\uopl{pure}((\monadic{v}_3,\monadic{c}_3),\gamma_3,\omicron_3,\nu_3)\mbox{,}\\ \semc{e_3}([x\mapsto(\uopl{pure}(i_1+1),\top)]\gamma_3)\phi\nu_3=\uopl{pure}((\monadic{v}_4,\monadic{c}_4),\gamma_4,\omicron_4,\nu_4)\mbox{,}\\ \dotfill\\ \semc{e_3}([x\mapsto(\uopl{pure}(i_1+n-1),\top)]\gamma_{n+1})\phi\nu_{n+1}=\uopl{pure}((\monadic{v}_{n+2},\monadic{c}_{n+2}),\gamma_{n+2},\omicron_{n+2},\nu_{n+2})\mbox{,}\\ \end{array} \] and $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\tilde{\gamma},\tilde{\omicron},\tilde{\nu})$ where \[ \begin{array}{l} (\monadic{v},\monadic{c})=(\uopl{pure}((\monadic{v}_3,\monadic{c}_3),\ldots,(\monadic{v}_{n+2},\monadic{c}_{n+2})),\top)\mbox{,}\\\tilde{\gamma}=\uopl{tail}\gamma_{n+2}\mbox{,}\quad\tilde{\omicron}=\omicron_1\ldots\omicron_{n+2}\mbox{,}\quad\tilde{\nu}=\nu_{n+2}\mbox{.} \end{array} \] If $d\ne\mbox{\lstinline+@public+}$ then, by exactness, $\monadic{v}_1=\monadic{v}_2=\top$. Thus $d=\mbox{\lstinline+@public+}$ must hold. Hence $(\monadic{v}_1,\monadic{c}_1)\bullet\pi\sim\monadic{v}'_1$ and $(\monadic{v}_2,\monadic{c}_2)\bullet\pi\sim\monadic{v}'_2$, which imply $\monadic{v}'_1=\uopl{pure} i_1$, $\monadic{v}'_2=\uopl{pure} i_2$. The assumption that $\tilde{\omicron}$ accepts~$\pi$ implies that $\omicron_3,\ldots,\omicron_{n+2}$ all accept~$\pi$. As $\gamma_2\bullet\pi\sim\gamma'_2$ and $(\uopl{pure} i_1,\top)\bullet\pi\sim\uopl{pure} i_1$, we have $\left((x,(\uopl{pure} i_1,\top)),\gamma_2\right)\bullet\pi\sim\left((x,\uopl{pure} i_1),\gamma'_2\right)$. By the induction hypothesis, $\sem{e_3}\left((x,\uopl{pure} i_1),\gamma'_2\right)\phi\omicron'_2=\uopl{pure}(\monadic{v}'_3,\gamma'_3,\omicron'_3)$, whereby $\gamma_3\bullet\pi\sim\gamma'_3$, $\nu_3\bullet\pi\sim\omicron'_3$, and $d_1=\mbox{\lstinline+@public+}$ or $s_1=\mbox{\lstinline+$post+}$ implies $(\monadic{v}_3,\monadic{c}_3)\bullet\pi\sim\monadic{v}'_3$. Similarly, we get $\sem{e_k}([x\mapsto\uopl{pure}(i_1+k-3)]\gamma'_{k-1})\phi\omicron'_{k-1}=\uopl{pure}(\monadic{v}'_k,\gamma'_k,\omicron'_k)$ where $\gamma_k\bullet\pi\sim\gamma'_k$, $\nu_k\bullet\pi\sim\omicron'_k$, and $d_1=\mbox{\lstinline+@public+}$ or $s_1=\mbox{\lstinline+$post+}$ implies $(\monadic{v}_k,\monadic{c}_k)\bullet\pi\sim\monadic{v}'_k$ for every $k=4,\ldots,n+2$. We obtain $\sem{e}\gamma'\phi\omicron'=\uopl{pure}(\uopl{pure}(\monadic{v}'_3,\ldots,\monadic{v}'_{n+2}),\gamma'_{n+2},\omicron'_{n+2})$ which implies the desired result. \item If $\monadic{v}_1\ne\uopl{pure} i_1$ or $\monadic{v}_1\ne\uopl{pure} i_2$ for $i_1,i_2\in\mathbb{N}$ then, by exactness, $d\ne\mbox{\lstinline+@public+}$ and $\monadic{v}_1=\monadic{v}_2=\top$. As $d\ne\mbox{\lstinline+@public+}$ and $e_1,e_2$ have stage $\mbox{\lstinline+$pre+}$, we must have $\monadic{v}'_1=\monadic{v}'_2=\top$ by exactness in circuit. Hence $\sem{e}\gamma'\phi\omicron'=\uopl{pure}(\top,\gamma'_2,\omicron'_2)$ which implies the desired result. \end{itemize} \item Let $e=\wireexpr{e_1}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{t}{\mbox{\lstinline+$pre+}}{d}\mbox{,}\\ t\in\set{\uintmodty{\mbox{\lstinline+N+}},\boolmodty{\mbox{\lstinline+N+}}}\mbox{,}\quad s=\mbox{\lstinline+$post+}\mbox{.} \end{array} \] Furthermore, \[ \begin{array}{l} \semc{e_1}\gamma\phi\nu=\uopl{pure}((\monadic{v}_1,\monadic{c}_1),\gamma_1,\omicron_1,\nu_1)\mbox{,}\\ \end{array} \] and $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\tilde{\gamma},\tilde{\omicron},\tilde{\nu})$ where \[ \begin{array}{l} (\monadic{v},\monadic{c})=(\monadic{v}_1,\branching{\uopl{pure}(\mknode{\uopl{con}(n)})&\mbox{if $\monadic{v}_1=\uopl{pure} n$, $n\in\mathbb{N}$}\\\uopl{pure}(\mknode{\uopl{con}(|b|)})&\mbox{if $\monadic{v}_1=\uopl{pure} b$, $b\in\mathbb{B}$}\\\uopl{pure}(\mknode{\uopl{in}_d(\left(\nu_1\right)_d)})&\mbox{if $\monadic{v}_1=\top$}})\mbox{,}\\ \tilde{\gamma}=\gamma_1\mbox{,}\quad\tilde{\omicron}=\omicron_1\mbox{,}\quad\tilde{\nu}=\lam{d'}{\branching{\left(\nu_1\right)_{d'}+1&\mbox{if $d'=d$}\\\left(\nu_1\right)_{d'}&\mbox{otherwise}}}\mbox{.} \end{array} \] Firstly, suppose that $\sem{e}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}',\tilde{\gamma}',\tilde{\omicron}')$. Then \[ \begin{array}{l} \sem{e_1}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}'_1,\gamma'_1,\omicron'_1)\mbox{,}\\ \monadic{v}'=\branching{\monadic{v}'_1&\mbox{if $d=\mbox{\lstinline+@public+}$}\\\uopl{head}\left(\omicron'_1\right)_d&\mbox{otherwise}}\mbox{,}\\\tilde{\gamma}'=\gamma'_1\mbox{,}\quad\tilde{\omicron}'=\lam{d'}{\branching{\uopl{tail}\left(\omicron'_1\right)_{d'}&\mbox{if $d'=d$}\\\left(\omicron'_1\right)_{d'}&\mbox{otherwise}}}\mbox{.} \end{array} \] By the induction hypothesis, $\omicron_1$ accepts~$\pi$, whereby $\gamma_1\bullet\pi\sim\gamma'_1$, $\nu_1\bullet\pi\sim\omicron'_1$, and $d=\mbox{\lstinline+@public+}$ implies $(\monadic{v}_1,\monadic{c}_1)\bullet\pi\sim\monadic{v}'_1$. Hence $\tilde{\omicron}$ accepts~$\pi$ and $\tilde{\gamma}\bullet\pi\sim\tilde{\gamma}'$. We also get $\tilde{\nu}\bullet\pi\sim\tilde{\omicron}'$ since dropping one more item from the input list results in the tail of the result that would be obtained otherwise. To complete, we have to prove $(\monadic{v},\monadic{c})\bullet\pi\sim\monadic{v}'$. Consider two cases: \begin{itemize} \item If $d=\mbox{\lstinline+@public+}$ then $(\monadic{v}_1,\monadic{c}_1)\bullet\pi\sim\monadic{v}'_1$. By exactness and exactness in circuit, $\monadic{v}_1=\uopl{pure} v_1$ and $\monadic{v}'_1=\uopl{pure} v'_1$ where $v_1,v'_1\in t$. Thus $(\monadic{v},\monadic{c})\bullet\pi=(\monadic{v}_1,\monadic{c}_1)\bullet\pi\in\set{\uopl{pure} v_1,\uopl{pure}|v_1|}$ where the outcome depends on whether $t=\uintmodty{\mbox{\lstinline+N+}}$ or $t=\boolmodty{\mbox{\lstinline+N+}}$. In both cases, $\monadic{v}'_1=\uopl{pure} v_1$, leading to $(\monadic{v},\monadic{c})\bullet\pi\sim\monadic{v}'$ as needed. \item If $d\ne\mbox{\lstinline+@public+}$ then, by exactness, $\monadic{v}_1=\top$. Hence \[ \begin{array}{lcl} (\monadic{v},\monadic{c})\bullet\pi &=&(\top,\uopl{pure}(\mknode{\uopl{in}_d(\left(\nu_1\right)_d)}))\bullet\pi\\ &=&\uopl{pure}(\mknode{\uopl{in}_d(\left(\nu_1\right)_d)}(\pi))\\ &=&\uopl{pure}(\pi_d(\left(\nu_1\right)_d))\mbox{.} \end{array} \] From $\nu_1\bullet\pi\sim\omicron'_1$, we get $\uopl{map}\uopl{pure}\left(\uopl{drop}\left(\nu_1\right)_d\pi_d\right)\sim\left(\omicron'_1\right)_d$, and taking the first elements in the lists occurring in the latter statement gives $\uopl{pure}(\pi_d(\left(\nu_1\right)_d))\sim\uopl{head}\left(\omicron'_1\right)_d$ as needed. \end{itemize} Conversely, assume that $\tilde{\omicron}$ accepts~$\pi$. Then $\omicron_1$ accepts~$\pi$. By the induction hypothesis, $\sem{e_1}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}'_1,\gamma'_1,\omicron'_1)$ where $\gamma_1\bullet\pi\sim\gamma'_1$ and $\nu_1\bullet\pi\sim\omicron'_1$. Then $\sem{e}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}',\tilde{\gamma},\tilde{\omicron}')$ where $\monadic{v}'=\branching{\monadic{v}'_1&\mbox{if $d=\mbox{\lstinline+@public+}$}\\\uopl{head}\left(\omicron'_1\right)_d&\mbox{otherwise}}$. The latter is well-defined if $d=\mbox{\lstinline+@public+}$; if $d\ne\mbox{\lstinline+@public+}$ then it is well defined, provided that $\left(\omicron'_1\right)_d$ is non-empty. As $\nu_1\bullet\pi\sim\omicron'_1$, this condition is equivalent to $(\nu_1)_d$ being smaller than the length of $\pi_d$. Since $(\monadic{v},\monadic{c})=(\top,\uopl{pure}(\mknode{\uopl{in}_d((\nu_1)_d)}))$ and $(\monadic{v},\monadic{c})\bullet\pi$ is well-defined, $(\nu_1)_d$ must indeed be smaller than the length of~$\pi_d$. The desired claim follows. \item Let $e=\castexpr{e_1}{q}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{t}{s'}{d'}\mbox{,}\\ s'\mathrel{\mathchar"13C\mathchar"3A} s\mbox{,}\quad d'\mathrel{\mathchar"13C\mathchar"3A} d\mbox{.} \end{array} \] Furthermore, \[ \begin{array}{l} \semc{e_1}\gamma\phi\nu=\uopl{pure}((\monadic{v}_1,\monadic{c}_1),\gamma_1,\omicron_1,\nu_1)\mbox{,}\\ \end{array} \] and $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\tilde{\gamma},\tilde{\omicron},\tilde{\nu})$ where \[ \begin{array}{l} (\monadic{v},\monadic{c})=(\branching{\monadic{v}_1&\mbox{if $d=\mbox{\lstinline+@public+}$}\\\top&\mbox{otherwise}},\branching{\monadic{c}_1&\mbox{if $s=\mbox{\lstinline+$post+}$}\\\top&\mbox{otherwise}})\mbox{,}\\ \tilde{\gamma}=\gamma_1\mbox{,}\quad\tilde{\omicron}=\omicron_1\mbox{,}\quad\tilde{\nu}=\nu_1\mbox{.} \end{array} \] Firstly, suppose that $\sem{e}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}',\tilde{\gamma}',\tilde{\omicron}')$. Then \[ \begin{array}{l} \sem{e_1}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}'_1,\gamma'_1,\omicron'_1)\mbox{,}\\ \monadic{v}'=\branching{\monadic{v}'_1&\mbox{if $d=\mbox{\lstinline+@public+}$ or $s=\mbox{\lstinline+$post+}$}\\\top&\mbox{otherwise}}\mbox{,}\\\tilde{\gamma}'=\gamma'_1\mbox{,}\quad\tilde{\omicron}'=\omicron'_1\mbox{.} \end{array} \] By the induction hypothesis, $\omicron_1$ accepts~$\pi$, whereby $\gamma_1\bullet\pi\sim\gamma'_1$, $\nu_1\bullet\pi\sim\omicron'_1$, and $d'=\mbox{\lstinline+@public+}$ or $s'=\mbox{\lstinline+$post+}$ implies $(\monadic{v}_1,\monadic{c}_1)\bullet\pi\sim\monadic{v}'_1$. Hence $\tilde{\omicron}$ accepts~$\pi$, whereby $\tilde{\gamma}\bullet\pi\sim\tilde{\gamma}'$ and $\tilde{\nu}\bullet\pi\sim\tilde{\omicron}'$. Suppose that $d=\mbox{\lstinline+@public+}$ or $s=\mbox{\lstinline+$post+}$. Then $d'=\mbox{\lstinline+@public+}$ or $s'=\mbox{\lstinline+$post+}$ since $d'\mathrel{\mathchar"13C\mathchar"3A} d$ and $s'\mathrel{\mathchar"13C\mathchar"3A} s$. Thus $(\monadic{v}_1,\monadic{c}_1)\bullet\pi\sim\monadic{v}'_1$ and $\monadic{v}'=\monadic{v}'_1$. Consider two cases: \begin{itemize} \item If $d=\mbox{\lstinline+@public+}$ then $(\monadic{v},\monadic{c})\bullet\pi=(\monadic{v},\monadic{c}_1)\bullet\pi=(\monadic{v}_1,\monadic{c}_1)\bullet\pi$ and the desired claim follows. \item If $d\ne\mbox{\lstinline+@public+}$ and $s=\mbox{\lstinline+$post+}$ then $s'=\mbox{\lstinline+$post+}$. If $d'\ne\mbox{\lstinline+@public+}$ then $\monadic{v}_1=\top$ by exactness, whence $(\monadic{v},\monadic{c})=(\monadic{v}_1,\monadic{c}_1)$ and the desired claim follows. Suppose now that $d'=\mbox{\lstinline+@public+}$. By types being well-structured, $t=\uintmodty{\mbox{\lstinline+N+}}$ or $t=\boolmodty{\mbox{\lstinline+N+}}$, whence exactness implies $\monadic{v}_1=\uopl{pure} v_1$ where $v_1\in\mathbb{N}$ or $v_1\in\mathbb{B}$. Thus $(\monadic{v}_1,\monadic{c}_1)\bullet\pi=(\uopl{pure} v_1,\monadic{c}_1)\bullet\pi\sim\uopl{pure} v_1$. As by exactness, $\monadic{c}_1=\uopl{pure} c_1$ and $\uopl{pure}(c_1(\pi))\sim\uopl{pure} v_1$, we obtain \[ (\monadic{v},\monadic{c})\bullet\pi=(\top,\monadic{c}_1)\bullet\pi=\uopl{pure}(c_1(\pi))\sim\uopl{pure} v_1\mbox{.} \] But $(\uopl{pure} v_1,\uopl{pure} c_1)\bullet\pi\sim\uopl{pure} v_1$, too, while we also know that $(\uopl{pure} v_1,\uopl{pure} c_1)\bullet\pi\sim\monadic{v}'_1$. Hence $\uopl{pure} v_1\sim\monadic{v}'_1$ and the desired claim follows. \end{itemize} Conversely, assume that $\tilde{\omicron}$ accepts~$\pi$. Then $\omicron_1$ accepts~$\pi$. By the induction hypothesis, $\sem{e_1}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}'_1,\gamma'_1,\omicron'_1)$ for some $\monadic{v}'_1,\gamma'_1,\omicron'_1$. Hence $\sem{e}\gamma'\phi\omicron'$ does not fail. \item Let $e=\assignexpr{e_1}{e_2}$ where $e_1=\loadexpr{\loadexpr{\loadexpr{x}{y_1}}{y_2}\ldots}{y_n}$. By Lemma~\ref{typesystem:lhslemma}, \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } x:q'\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } y_k:q_k\mbox{ for every $k=1,\ldots,n$,}\\ \Gamma\mbox{\ $\vdash$\ } e_1:q_{n+1}\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:q_{n+1}\mbox{,}\\ t=\mbox{\lstinline+()+}\mbox{,}\quad s=\mbox{\lstinline+$pre+}\mbox{,}\quad d=\mbox{\lstinline+@public+}\mbox{,} \end{array} \] where $q_k=\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_k}$ for each $k=1,\ldots,n$, and \[ q'=\qualty{\listty{\ldots\listty{\qualty{\listty{\qualty{\listty{q_{n+1}}}{\mbox{\lstinline+$pre+}}{d_n}}}{\mbox{\lstinline+$pre+}}{d_{n-1}}}\ldots}}{\mbox{\lstinline+$pre+}}{d_1}\mbox{.} \] Denote $q_{n+1}=(\qualty{t_{n+1}}{s_{n+1}}{d_{n+1}})$. Furthermore, \[ \begin{array}{l} \semc{y_1}\gamma\phi\nu=\uopl{pure}((\monadic{i}_1,\monadic{c}_1),\gamma_1,\omicron_1,\nu_1)\mbox{,}\\ \semc{y_2}\gamma_1\phi\nu_1=\uopl{pure}((\monadic{i}_2,\monadic{c}_2),\gamma_2,\omicron_2,\nu_2)\mbox{,}\\ \dotfill\\ \semc{y_n}\gamma_{n-1}\phi\nu_{n-1}=\uopl{pure}((\monadic{i}_n,\monadic{c}_n),\gamma_n,\omicron_n,\nu_n)\mbox{,}\\ \sem{e_2}\gamma_n\phi\nu_n=\uopl{pure}((\monadic{v}_1,\monadic{c}_{n+1}),\gamma_{n+1},\omicron_{n+1},\nu_{n+1})\mbox{,} \end{array} \] and $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\tilde{\gamma},\tilde{\omicron},\tilde{\nu})$ where \[ \begin{array}{l} (\monadic{v},\monadic{c})=(\uopl{pure}\mbox{\textoneoldstyle},\top)\mbox{,}\\ \tilde{\gamma}=[x\mapsto\uopl{upd}_{\mathrm{C}}(\gamma(x),\monadic{i}_1\ldots\monadic{i}_n,(\monadic{v}_1,\monadic{c}_{n+1}))]\gamma_{n+1}\mbox{,}\quad\tilde{\omicron}=\omicron_1\ldots\omicron_{n+1}\mbox{,}\quad\tilde{\nu}=\nu_{n+1}\mbox{.} \end{array} \] Firstly, suppose that $\sem{e}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}',\tilde{\gamma}',\tilde{\omicron}')$. Then \[ \begin{array}{l} \sem{y_1}\gamma'\phi\omicron'=\uopl{pure}(\monadic{i}'_1,\gamma'_1,\omicron'_1)\mbox{,}\\ \sem{y_2}\gamma'_1\phi\omicron'_1=\uopl{pure}(\monadic{i}'_2,\gamma'_2,\omicron'_2)\mbox{,}\\ \dotfill\\ \sem{y_n}\gamma'_{n-1}\phi\omicron'_{n-1}=\uopl{pure}(\monadic{i}'_n,\gamma'_n,\omicron'_n)\mbox{,}\\ \sem{e_2}\gamma'_n\phi\omicron'_n=\uopl{pure}(\monadic{v}'_1,\gamma'_{n+1},\omicron'_{n+1})\mbox{,}\\ \monadic{v}'=\uopl{pure}\mbox{\textoneoldstyle}\mbox{,}\quad\tilde{\gamma}'=[x\mapsto\uopl{upd}(\gamma'(x),\monadic{i}'_1\ldots\monadic{i}'_n,\monadic{v}'_1)]\gamma'_{n+1}\mbox{,}\quad\tilde{\omicron}'=\omicron'_{n+1}\mbox{.} \end{array} \] By the induction hypothesis, $\omicron_1$ accepts~$\pi$, whereby $\gamma_1\bullet\pi\sim\gamma'_1$, $\nu_1\bullet\pi\sim\omicron'_1$, and $d_1=\mbox{\lstinline+@public+}$ implies $(\monadic{i}_1,\monadic{c}_1)\bullet\pi\sim\monadic{i}'_1$. Similarly, we see that $\omicron_k$ accepts~$\pi$, whereby $\gamma_k\bullet\pi\sim\gamma'_k$, $\nu_k\bullet\pi\sim\omicron'_k$, and $d_k=\mbox{\lstinline+@public+}$ implies $(\monadic{i}_k,\monadic{c}_k)\bullet\pi\sim\monadic{i}'_k$ for every $k=2,\ldots,n$. Furthermore, the induction hypothesis implies $\omicron_{n+1}$ accepting~$\pi$, whereby $\gamma_{n+1}\bullet\pi\sim\gamma'_1$, $\nu_{n+1}\bullet\pi\sim\omicron'_{n+1}$, and $d_{n+1}=\mbox{\lstinline+@public+}$ or $s_{n+1}=\mbox{\lstinline+$post+}$ implying $(\monadic{v}_1,\monadic{c}_{n+1})\bullet\pi\sim\monadic{v}'_1$. Hence $\tilde{\omicron}$ accepts~$\pi$ and $\tilde{\nu}\bullet\pi\sim\tilde{\omicron}'$. We also have $(\monadic{v},\monadic{c})\bullet\pi\sim\monadic{v}'$ since $(\uopl{pure}\mbox{\textoneoldstyle},\top)\bullet\pi=\uopl{pure}\mbox{\textoneoldstyle}$. Finally, note that $d_k\ne\mbox{\lstinline+@public+}$ for any $k=1,\ldots,n$ implies $(\monadic{i}_k,\monadic{c}_k)=(\top,\top)$ and $\monadic{i}'_k=\top$ by exactness and exactness in circuit, respectively. As $(\top,\top)\bullet\pi=\top$, we have $(\monadic{i}_k,\monadic{c}_k)\bullet\pi\sim\monadic{i}'_k$ for every $k=1,\ldots,n$. In addition, if $d_{n+1}\ne\mbox{\lstinline+@public+}$ and $s_{n+1}=\mbox{\lstinline+$pre+}$ then $(\monadic{v}_1,\monadic{c}_{n+1})=(\top,\top)$ and $\monadic{v}'_1=\top$ by exactness and exactness in circuit, respectively, whence $(\monadic{v}_1,\monadic{c}_{n+1})\bullet\pi\sim\monadic{v}'_1$ in all cases. By Lemma~\ref{compilation:updlemma}, $\uopl{upd}_{\mathrm{C}}(\gamma(x),\monadic{i}_1\ldots\monadic{i}_n,(\monadic{v}_1,\monadic{c}_{n+1}))\bullet\pi\sim\uopl{upd}(\gamma'(x),\monadic{i}'_1\ldots\monadic{i}'_n,\monadic{v}'_1)$. Consequently, $[x\mapsto\uopl{upd}_{\mathrm{C}}(\gamma(x),\monadic{i}_1\ldots\monadic{i}_n,(\monadic{v}_1,\monadic{c}_{n+1}))]\gamma_{n+1}\bullet\pi\sim[x\mapsto\uopl{upd}(\gamma'(x),\monadic{i}'_1\ldots\monadic{i}'_n,\monadic{v}'_1)]\gamma'_{n+1}$ and the desired claim follows. Conversely, assume that $\tilde{\omicron}$ accepts~$\pi$. Then $\omicron_1,\ldots,\omicron_{n+1}$ all accept~$\pi$. By the induction hypothesis, $\sem{y_1}\gamma'\phi\omicron'=\uopl{pure}(\monadic{i}'_1,\gamma'_1,\omicron'_1)$ where $\gamma_1\bullet\pi\sim\gamma'_1$, $\nu_1\bullet\pi\sim\omicron'_1$ and $d_1=\mbox{\lstinline+@public+}$ implies $(\monadic{i}_1,\monadic{c}_1)\bullet\pi\sim\monadic{i}'_1$. Similarly, we see for every $k=2,\ldots,n$ that $\sem{y_k}\gamma'_{k-1}\phi\omicron'_{k-1}=\uopl{pure}(\monadic{i}'_k,\gamma'_k,\omicron'_k)$ where $\gamma_k\bullet\pi\sim\gamma'_k$, $\nu_k\bullet\pi\sim\omicron'_k$ and $d_k=\mbox{\lstinline+@public+}$ implies $(\monadic{i}_k,\monadic{c}_k)\bullet\pi\sim\monadic{i}'_k$. Furthermore, $\sem{e_2}\gamma'_n\phi\omicron'_n=\uopl{pure}(\monadic{v}'_1,\gamma'_{n+1},\omicron'_{n+1})$ where $d_{n+1}=\mbox{\lstinline+@public+}$ or $s_{n+1}=\mbox{\lstinline+$post+}$ implies $(\monadic{v}_1,\monadic{c}_{n+1})\bullet\pi\sim\monadic{v}'_1$. Similarly to the first part of the proof, we see that $(\monadic{i}_k,\monadic{c}_k)\bullet\pi\sim\monadic{i}'_k$ and $(\monadic{v}_1,\monadic{c}_{n+1})\bullet\pi\sim\monadic{v}'_1$ in all cases. By Lemma~\ref{compilation:updlemma}, $\uopl{upd}(\gamma'(x),\monadic{i}'_1\ldots\monadic{i}'_n,\monadic{v}'_1)$ is well-defined. Therefore $\sem{e}\gamma'\phi\omicron'$ does not fail. \item Let $e=\loadexpr{e_1}{e_2}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{\listty{q}}{\mbox{\lstinline+$pre+}}{d_1}\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_1}\mbox{.} \end{array} \] Furthermore, \[ \begin{array}{l} \semc{e_1}\gamma\phi\nu=\uopl{pure}((\monadic{a},\monadic{c}_1),\gamma_1,\omicron_1,\nu_1)\mbox{,}\\ \semc{e_2}\gamma_1\phi\nu_1=\uopl{pure}((\monadic{i},\monadic{c}_2),\gamma_2,\omicron_2,\nu_2)\mbox{,} \end{array} \] and $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\tilde{\gamma},\tilde{\omicron},\tilde{\nu})$ where \[ \begin{array}{l} (\monadic{v},\monadic{c})=\branching{(\monadic{v}_1,\monadic{c}_3)&\mbox{if $\mcomp{a\gets\monadic{a};\; i\gets\monadic{i};\;\uopl{pure} a_i}=\uopl{pure}(\monadic{v}_1,\monadic{c}_3)$}\\(\top,\top)&\mbox{otherwise}}\mbox{,}\\ \tilde{\gamma}=\gamma_2\mbox{,}\quad\tilde{\omicron}=\omicron_1\omicron_2\mbox{,}\quad\tilde{\nu}=\nu_2\mbox{.} \end{array} \] Firstly, suppose that $\sem{e}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}',\tilde{\gamma}',\tilde{\omicron}')$. Then \[ \begin{array}{l} \sem{e_1}\gamma'\phi\omicron'=\uopl{pure}(\monadic{a}',\gamma'_1,\omicron'_1)\mbox{,}\\ \sem{e_2}\gamma'_1\phi\omicron'_1=\uopl{pure}(\monadic{i}',\gamma'_2,\omicron'_2)\mbox{,}\\ \monadic{v}'=\mcomp{a\gets\monadic{a}';\; i\gets\monadic{i}';\; a_i}\mbox{,}\quad\tilde{\gamma}'=\gamma'_2\mbox{,}\quad\tilde{\omicron}'=\omicron'_2\mbox{.} \end{array} \] By the induction hypothesis, $\omicron_1$ accepts~$\pi$, whereby $\gamma_1\bullet\pi\sim\gamma'_1$, $\nu_1\bullet\pi\sim\omicron'_1$, and $d_1=\mbox{\lstinline+@public+}$ implies $(\monadic{a},\monadic{c}_1)\bullet\pi\sim\monadic{a}'$. By the induction hypothesis again, $\omicron_2$ accepts~$\pi$, whereby $\gamma_2\bullet\pi\sim\gamma'_2$, $\nu_2\bullet\pi\sim\omicron'_2$, and $d_1=\mbox{\lstinline+@public+}$ implies $(\monadic{i},\monadic{c}_2)\bullet\pi\sim\monadic{i}'$. Hence $\tilde{\omicron}$ accepts~$\pi$, whereby $\tilde{\gamma}\bullet\pi\sim\tilde{\gamma}'$ and $\tilde{\nu}\bullet\pi\sim\tilde{\omicron}'$. Suppose that $d=\mbox{\lstinline+@public+}$ or $s=\mbox{\lstinline+$post+}$. Then $d_1=\mbox{\lstinline+@public+}$ because types are well-structured. Thus $(\monadic{a},\monadic{c}_1)\bullet\pi\sim\monadic{a}'$ and $(\monadic{i},\monadic{c}_2)\bullet\pi\sim\monadic{i}'$. By exactness and exactness in circuit, $\monadic{a}=\uopl{pure}((\monadic{a}_1,\monadic{c}'_1),\ldots,(\monadic{a}_l,\monadic{c}'_l))$ and $\monadic{a}'=\uopl{pure}(\monadic{a}'_1,\ldots,\monadic{a}'_{l'})$. By $(\monadic{a},\monadic{i})\bullet\pi\sim\monadic{a}'$, we obtain $l=l'$ and $(\monadic{a}_k,\monadic{c}'_k)\bullet\pi\sim\monadic{a}'_k$ for every $k=1,\ldots,l$. For similar reasons, we obtain $\monadic{i}=\monadic{i}'=\uopl{pure} i$. Thus $(\monadic{v},\monadic{c})=(\monadic{a}_i,\monadic{c}'_i)$ and $\monadic{v}'=\monadic{a}'_i$. The desired result follows by $(\monadic{a}_i,\monadic{c}'_i)\bullet\pi\sim\monadic{a}'_i$. Conversely, assume that $\tilde{\omicron}$ accepts~$\pi$. Then both $\omicron_1$ and $\omicron_2$ accept~$\pi$. By the induction hypothesis, $\sem{e_1}\gamma'\phi\omicron'=\uopl{pure}(\monadic{a}',\gamma'_1,\omicron'_1)$ where $\gamma_1\bullet\pi\sim\gamma'_1$, $\nu_1\bullet\pi\sim\omicron'_1$ and $d_1=\mbox{\lstinline+@public+}$ implies $(\monadic{a},\monadic{c}_1)\bullet\pi\sim\monadic{a}'$. By the induction hypothesis, $\sem{e_2}\gamma'_1\phi\omicron'_1=\uopl{pure}(\monadic{i}',\gamma'_2,\omicron'_2)$, whereby $d_1=\mbox{\lstinline+@public+}$ implies $(\monadic{i},\monadic{c}_2)\bullet\pi\sim\monadic{i}'$. Consider two cases: \begin{itemize} \item If $d=\mbox{\lstinline+@public+}$ or $s=\mbox{\lstinline+$post+}$ then, like in the first half of the proof, we obtain $\monadic{a}=\uopl{pure}((\monadic{a}_1,\monadic{c}'_1),\ldots,(\monadic{a}_l,\monadic{c}'_l))$, $\monadic{a}'=\uopl{pure}(\monadic{a}'_1,\ldots,\monadic{a}'_l)$ and $\monadic{i}=\monadic{i}'=\uopl{pure} i$, whereby $i\leq l$ since $(\monadic{v},\monadic{c})$ is well-defined. Hence $\sem{e}\gamma'\phi\omicron'$ is of the form $\uopl{pure}(\monadic{v}',\tilde{\gamma},\tilde{\omicron}')$, implying the desired result. \item If $d\ne\mbox{\lstinline+@public+}$ and $s=\mbox{\lstinline+$pre+}$ then, by exactness in circuit, $\monadic{a}'=\top$ and $\monadic{i}'=\top$, whence $\sem{e}\gamma'\phi\omicron'=\uopl{pure}(\top,\gamma'_2,\omicron'_2)$, implying the desired result. \end{itemize} \item Let $e=\stmtcomp{\letexpr{x}{e_1}}{e_2}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{t_1}{s_1}{d_1}\mbox{,}\\ (x:\qualty{t_1}{s_1}{d_1}),\Gamma\mbox{\ $\vdash$\ } e_2:q\mbox{.} \end{array} \] Furthermore, \[ \begin{array}{l} \semc{e_1}\gamma\phi\nu=\uopl{pure}((\monadic{v}_1,\monadic{c}_1),\gamma_1,\omicron_1,\nu_1)\mbox{,}\\ \semc{e_2}((x,(\monadic{v}_1,\monadic{c}_1)),\gamma_1)\phi\nu_1=\uopl{pure}((\monadic{v}_2,\monadic{c}_2),\gamma_2,\omicron_2,\nu_2)\mbox{,} \end{array} \] and $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\tilde{\gamma},\tilde{\omicron},\tilde{\nu})$ where \[ \begin{array}{l} (\monadic{v},\monadic{c})=(\monadic{v}_2,\monadic{c}_2)\mbox{,}\quad\tilde{\gamma}=\uopl{tail}\gamma_2\mbox{,}\quad\tilde{\omicron}=\omicron_1\omicron_2\mbox{,}\quad\tilde{\nu}=\nu_2\mbox{.} \end{array} \] Firstly, suppose that $\sem{e}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}',\tilde{\gamma}',\tilde{\omicron}')$. Then \[ \begin{array}{l} \sem{e_1}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}'_1,\gamma'_1,\omicron'_1)\mbox{,}\\ \sem{e_2}((x,\monadic{v}'_1),\gamma'_1)\phi\omicron'_1=\uopl{pure}(\monadic{v}'_2,\gamma'_2,\omicron'_2)\mbox{,}\\ \monadic{v}'=\monadic{v}'_2\mbox{,}\quad\tilde{\gamma}'=\uopl{tail}\gamma'_2\mbox{,}\quad\tilde{\omicron}'=\omicron'_2\mbox{.} \end{array} \] By the induction hypothesis, $\omicron_1$ accepts~$\pi$, whereby $\gamma_1\bullet\pi\sim\gamma'_1$, $\nu_1\bullet\pi\sim\omicron'_1$, and $d_1=\mbox{\lstinline+@public+}$ or $s_1=\mbox{\lstinline+$post+}$ implies $(\monadic{v}_1,\monadic{c}_1)\bullet\pi\sim\monadic{v}'_1$. If $d_1\ne\mbox{\lstinline+@public+}$ and $s_1=\mbox{\lstinline+$pre+}$ then $(\monadic{v}_1,\monadic{c}_1)=(\top,\top)$ and $\monadic{v}'_1=\top$ by exactness and exactness in circuit, respectively. Hence $(\monadic{v}_1,\monadic{c}_1)\bullet\pi\sim\monadic{v}'_1$ in all cases, establishing $((x,(\monadic{v}_1,\monadic{c}_1)),\gamma_1)\bullet\pi\sim((x,\monadic{v}'_1),\gamma'_1)$. By the induction hypothesis again, $\omicron_2$ accepts~$\pi$, whereby $\gamma_2\bullet\pi\sim\gamma'_2$, $\nu_2\bullet\pi\sim\omicron'_2$, and $d=\mbox{\lstinline+@public+}$ or $s=\mbox{\lstinline+$post+}$ implies $(\monadic{v}_2,\monadic{c}_2)\bullet\pi\sim\monadic{v}'_2$. Hence $\tilde{\omicron}$ accepts~$\pi$, whereby $\tilde{\nu}\bullet\pi\sim\tilde{\omicron}'$ and $d=\mbox{\lstinline+@public+}$ or $s=\mbox{\lstinline+$post+}$ implies $(\monadic{v},\monadic{c})\bullet\pi\sim\monadic{v}'$. We obviously obtain also $\tilde{\gamma}\bullet\pi\sim\tilde{\gamma}'$. Conversely, assume that $\tilde{\omicron}$ accepts~$\pi$. Then both $\omicron_1$ and $\omicron_2$ accept~$\pi$. By the induction hypothesis, $\sem{e_1}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}'_1,\gamma'_1,\omicron'_1)$ where $\gamma_1\bullet\pi\sim\gamma'_1$, $\nu_1\bullet\pi\sim\omicron'_1$, and $d_1=\mbox{\lstinline+@public+}$ or $s_1=\mbox{\lstinline+$post+}$ implies $(\monadic{v}_1,\monadic{c}_1)\bullet\pi\sim\monadic{v}'_1$. Like in the proof of the first half, we obtain $((x,(\monadic{v}_1,\monadic{c}_1)),\gamma_1)\bullet\pi\sim((x,\monadic{v}'_1),\gamma'_1)$. By the induction hypothesis, $\sem{e_2}((x,\monadic{v}'_1),\gamma'_1)\phi\omicron'_1=\uopl{pure}(\monadic{v}'_2,\gamma'_2,\omicron'_2)$. Therefore $\sem{e}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}'_2,\uopl{tail}\gamma'_2,\omicron'_2)$ and the desired result follows. \item Let $e=\stmtcomp{e_1}{e_2}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{t_1}{s_1}{d_1}\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:q\mbox{.} \end{array} \] Furthermore, \[ \begin{array}{l} \semc{e_1}\gamma\phi\nu=\uopl{pure}((\monadic{v}_1,\monadic{c}_1),\gamma_1,\omicron_1,\nu_1)\mbox{,}\\ \semc{e_2}\gamma_1\phi\nu_1=\uopl{pure}((\monadic{v}_2,\monadic{c}_2),\gamma_2,\omicron_2,\nu_2)\mbox{,} \end{array} \] and $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\tilde{\gamma},\tilde{\omicron},\tilde{\nu})$ where \[ \begin{array}{l} (\monadic{v},\monadic{c})=(\monadic{v}_2,\monadic{c}_2)\mbox{,}\quad\tilde{\gamma}=\gamma_2\mbox{,}\quad\tilde{\omicron}=\omicron_1\omicron_2\mbox{,}\quad\tilde{\nu}=\nu_2\mbox{.} \end{array} \] Firstly, suppose that $\sem{e}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}',\tilde{\gamma}',\tilde{\omicron}')$. Then \[ \begin{array}{l} \sem{e_1}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}'_1,\gamma'_1,\omicron'_1)\mbox{,}\\ \sem{e_2}\gamma'_1\phi\omicron'_1=\uopl{pure}(\monadic{v}'_2,\gamma'_2,\omicron'_2)\mbox{,}\\ \monadic{v}'=\monadic{v}'_2\mbox{,}\quad\tilde{\gamma}'=\gamma'_2\mbox{,}\quad\tilde{\omicron}'=\omicron'_2\mbox{.} \end{array} \] By the induction hypothesis, $\omicron_1$ accepts~$\pi$, whereby $\gamma_1\bullet\pi\sim\gamma'_1$, $\nu_1\bullet\pi\sim\omicron'_1$, and $d_1=\mbox{\lstinline+@public+}$ or $s_1=\mbox{\lstinline+$post+}$ implies $(\monadic{v}_1,\monadic{c}_1)\bullet\pi\sim\monadic{v}'_1$. By the induction hypothesis again, $\omicron_2$ accepts~$\pi$, whereby $\gamma_2\bullet\pi\sim\gamma'_2$, $\nu_2\bullet\pi\sim\omicron'_2$, and $d=\mbox{\lstinline+@public+}$ or $s=\mbox{\lstinline+$post+}$ implies $(\monadic{v}_2,\monadic{c}_2)\bullet\pi\sim\monadic{v}'_2$. Hence $\tilde{\omicron}$ accepts~$\pi$, whereby $\tilde{\gamma}\bullet\pi\sim\tilde{\gamma}'$, $\tilde{\nu}\bullet\pi\sim\tilde{\omicron}'$, and $d=\mbox{\lstinline+@public+}$ or $s=\mbox{\lstinline+$post+}$ implies $(\monadic{v},\monadic{c})\bullet\pi\sim\monadic{v}'$. Conversely, assume that $\tilde{\omicron}$ accepts~$\pi$. Then both $\omicron_1$ and $\omicron_2$ accept~$\pi$. By the induction hypothesis, $\sem{e_1}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}'_1,\gamma'_1,\omicron'_1)$ where $\gamma_1\bullet\pi\sim\gamma'_1$ and $\nu_1\bullet\pi\sim\omicron'_1$. By the induction hypothesis, $\sem{e_2}\gamma'_1\phi\omicron'_1=\uopl{pure}(\monadic{v}'_2,\gamma'_2,\omicron'_2)$. Therefore $\sem{e}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}'_2,\gamma'_2,\omicron'_2)$, implying the desired result. \end{itemize} \end{proof} \section{Compilation}\label{sec:compilation} \textsc{ZK-SecreC}\xspace programs are compiled into arithmetic circuits corresponding to the circuit semantics defined in Sect.~\ref{sec:semantics}. An \emph{arithmetic circuit $\mathcal{C}$ over a ring $R$} is a directed acyclic graph, the nodes of which are partitioned into \emph{input}, \emph{constant}, and \emph{operation} nodes, such that each operation node has exactly two incoming arcs and other nodes have none. Additionally, $\mathcal{C}$ assigns an element of~$R$ to each constant node, an operation --- either addition or multiplication --- to each operation node, and a domain --- either \lstinline+@prover+ or \lstinline+@verifier+ --- to each input node in it, and specifies a subset of nodes as output nodes. Also, $\mathcal{C}$~defines an enumeration of its input nodes of each domain. Let $\mathcal{V}$ be the set of all nodes in~$\mathcal{C}$ and $\mathcal{I}\subseteq\mathcal{V}$ the set of all input nodes. An assignment $\alpha\in R^{\mathcal{I}}$ of values to the input nodes extends naturally to an assignment $\alpha^\star\in R^{\mathcal{V}}$ to all nodes (the values for the constant nodes are given in the definition of~$\mathcal{C}$ and the value for each operation node is found by applying the operation in it to the values of its predecessors). We say that $\mathcal{C}$ \emph{accepts input $\alpha\in R^{\mathcal{I}}$}, if $\alpha^\star$ assigns~$0$ to all output nodes. If $R$ is a finite field of characteristic \lstinline+N+, then such circuits can be evaluated by various ZKP techniques (perhaps with additional restrictions on \lstinline+N+). \begin{figure}[b]\figsize \renewcommand{\arraycolsep}{2pt} \begin{tabular}{@{}l@{}} $\begin{array}{lcl} V_\mathrm{C}&=&\mathbb{N}\cup\mathbb{B}\cup()\cup(M\apV_\mathrm{C}\times M\, T)^*\quad\mbox{the set of composite values} \end{array}$\\[1.5ex] $\begin{array}{lcl} C_\mathrm{C}\, A&=&\mathbf{Env}_\mathrm{C}\to\mathbf{In}^3\to\mathbb{N}^2\to\mathds{1}+A\times\mathbf{Env}_\mathrm{C}\times\mathbf{Out}_\mathrm{C}\times\mathbb{N}^2\\ \end{array}$\\[1.5ex] $\begin{array}{lcl@{\quad}l} \mathbf{Env}_\mathrm{C}&=&(X\times(M\apV_\mathrm{C}\times M\, T))^+&\mbox{composite value environments}\\ \mathbf{Out}_\mathrm{C}&=&T^*&\mbox{streams of subcircuits} \end{array}$\\[4.5ex] $\begin{array}{lcl@{\quad}l} \semc{e}&:&C_\mathrm{C}\,(M\apV_\mathrm{C}\times M\, T)&\mbox{the result of compilation of expression~$e$}\\ \end{array}$ \end{tabular} \caption{\label{compilation:types} Types of semantic objects} \end{figure} Denote the set of all circuits by~$T$. Compilation to an arithmetic circuit proceeds in the lines of the dynamic semantics, using a new monad~$C_\mathrm{C}$. To get all types right, we replace the sets $V$, $\mathbf{Env}$, $\mathbf{Out}$ defined in Fig.~\ref{semantics:types} by $V_\mathrm{C}$, $\mathbf{Env}_\mathrm{C}$, $\mathbf{Out}_\mathrm{C}$ defined in Fig.~\ref{compilation:types}. The main difference is that $M\, V$ is replaced with $M\apV_\mathrm{C}\times M\, T$ at most places, meaning that value-circuit pairs occur here as results of computation. We call these pairs \emph{composite values}. The compiler still has to carry values along with circuits for making stage casts from $\mbox{\lstinline+$post+}$ to $\mbox{\lstinline+$pre+}$ if necessary. The value and the circuit component of a composite value can independently of each other be missing. For instance, if $e$ is in $\qual{\mbox{\lstinline+$pre+}}{\mbox{\lstinline+@public+}}$ then the value component is known but there is no circuit but if $e$ is in $\qual{\mbox{\lstinline+$post+}}{\mbox{\lstinline+@prover+}}$ then the circuit exists but the value is unknown. In $\qual{\mbox{\lstinline+$post+}}{\mbox{\lstinline+@public+}}$, both components are given. The set $\mathbf{Out}_\mathrm{C}$ contains output streams of subtrees of the circuit under construction rooted at its output nodes (this is to define the output nodes). The monad~$C_\mathrm{C}$ has an extra inner state not occurring in dynamic semantics, a pair of natural numbers, for counting how many input nodes of domains $\mbox{\lstinline+@prover+}$ and $\mbox{\lstinline+@verifier+}$ have been created. \begin{figure*}\figsize \renewcommand{\arraycolsep}{2pt}\renewcommand{\arraystretch}{1.2} \[ \begin{array}{lcl} \semc{\epsilon}\gamma\phi\nu&=&\uopl{pure}((\uopl{pure}\mbox{\textoneoldstyle},\top),\gamma,\epsilon,\nu)\\ \semc{\overline{n}}\gamma\phi\nu&=&\uopl{pure}((\branching{\uopl{pure} n&\mbox{if $d=\mbox{\lstinline+@public+}$}\\\top&\mbox{otherwise}},\branching{\uopl{pure}(\mknode{\uopl{con}(n)})&\mbox{if $s=\mbox{\lstinline+$post+}$}\\\top&\mbox{otherwise}}),\gamma,\epsilon,\nu)\\ \semc{\overline{b}}\gamma\phi\nu&=&\uopl{pure}((\branching{\uopl{pure} b&\mbox{if $d=\mbox{\lstinline+@public+}$}\\\top&\mbox{otherwise}},\branching{\uopl{pure}(\mknode{\uopl{con}(|b|)})&\mbox{if $s=\mbox{\lstinline+$post+}$}\\\top&\mbox{otherwise}}),\gamma,\epsilon,\nu)\\ \semc{x}\gamma\phi\nu&=&\uopl{pure}(\lookup{\gamma}{x},\gamma,\epsilon,\nu)\\ \semc{\addexpr{e_1}{e_2}}\gamma_0\phi\nu_0&=&\mcompv{((\monadic{v}_1,\monadic{c}_1),\gamma_1,\omicron_1,\nu_1)\gets\semc{e_1}\gamma_0\phi\nu_0;\;\\((\monadic{v}_2,\monadic{c}_2),\gamma_2,\omicron_2,\nu_2)\gets\semc{e_2}\gamma_1\phi\nu_1;\;\\\uopl{pure}((\monadic{s},\monadic{t}),\gamma_2,\omicron_1\omicron_2,\nu_2)}\\ \multicolumn{2}{r}{\mbox{where}}&\monadic{s}=\mcomp{i_1\gets\monadic{v}_1;\; i_2\gets\monadic{v}_2;\;\uopl{pure}(i_1+i_2)},\\&&\monadic{t}=\mcomp{c_1\gets\monadic{c}_1;\; c_2\gets\monadic{c}_2;\;\uopl{pure}(\mknode{\uopl{op}{(+)}}(c_1,c_2))}\\ \semc{\assertexpr{e}}\gamma_0\phi\nu_0&=&\mcomp{((\monadic{v}_1,\!\monadic{c}_1),\!\gamma_1,\!\omicron_1,\!\nu_1)\gets\semc{e}\gamma_0\phi\nu_0;\;\uopl{guard}(\monadic{c}_1\ne\top);\;\uopl{pure}((\uopl{pure}\mbox{\textoneoldstyle},\!\top),\!\gamma_1,\!\omicron_1c_1,\!\nu_1)}\\ \multicolumn{2}{r}{\mbox{where}}&\monadic{c}_1=\uopl{pure}(c_1)\\ \semc{\getexpr{d}{k}}\gamma\phi\nu&=&\branching{\uopl{pure}(\uopl{allpuretop}(\phi_d(k)),\gamma,\epsilon,\nu)&\mbox{if $d=\mbox{\lstinline+@public+}$}\\\uopl{pure}((\top,\top),\gamma,\epsilon,\nu)&\mbox{otherwise}}\\ \semc{\castexpr{e}{\qualty{t}{s}{d}}}\gamma_0\phi\nu_0&=&\mcompv{((\monadic{v}_1,\monadic{c}_1),\gamma_1,\omicron_1,\nu_1)\gets\semc{e}\gamma_0\phi\nu_0;\;\\\uopl{pure}((\branching{\monadic{v}_1&\mbox{if $d=\mbox{\lstinline+@public+}$}\\\top&\mbox{otherwise}},\branching{\monadic{c}_1&\mbox{if $s=\mbox{\lstinline+$post+}$}\\\top&\mbox{otherwise}}),\gamma_1,\omicron_1,\nu_1)}\\ \semc{\assignexpr{l}{e}}\gamma_0\phi\nu_0&=&\mcompv{(\monadic{a},\monadic{c})\gets\uopl{pure}(\lookup{\gamma_0}{x});\;\\\forall k=1,\ldots,n:((\monadic{i}_k,\monadic{c}_k),\gamma_k,\omicron_k,\nu_k)\gets\semc{y_k}\gamma_{k-1}\phi\nu_{k-1};\;\\((\monadic{v},\monadic{c}'),\gamma',\omicron',\nu')\gets\semc{e}\gamma_n\phi\nu_n;\;\\\uopl{pure}((\uopl{pure}\mbox{\textoneoldstyle},\top),[x\mapsto\uopl{upd}_{\mathrm{C}}((\monadic{a},\monadic{c}),\monadic{i}_1\ldots\monadic{i}_n,(\monadic{v},\monadic{c}'))]\gamma',\omicron_1\ldots\omicron_n\omicron',\nu')}\\ \multicolumn{2}{r}{\mbox{where}}&\loadexpr{\loadexpr{\loadexpr{x}{y_1}}{y_2}\ldots}{y_n}=l\\ \semc{\loadexpr{l}{e}}\gamma_0\phi\nu_0&=&\mcompv{((\monadic{a},\monadic{c}_1),\gamma_1,\omicron_1,\nu_1)\gets\semc{l}\gamma_0\phi\nu_0;\;\\((\monadic{i},\monadic{c}_2),\gamma_2,\omicron_2,\nu_2)\gets\semc{e}\gamma_1\phi\nu_1;\;\\\monadic{r}\gets\uopl{pure}(\mcomp{a\gets\monadic{a};\; i\gets\monadic{i};\;\uopl{pure} a_i});\;\\\branching{\uopl{pure}((\monadic{v},\monadic{c}),\gamma_2,\omicron_1\omicron_2,\nu_2)&\mbox{if $\monadic{r}=\uopl{pure}(\monadic{v},\monadic{c})$}\\\uopl{pure}((\top,\top),\gamma_2,\omicron_1\omicron_2,\nu_2)&\mbox{otherwise}}} \end{array} \] \caption{\label{fig:compilationsmall} Compilation to an arithmetic circuit: ``Small'' expressions} \end{figure*} \begin{figure*}\figsize \renewcommand{\arraycolsep}{2pt}\renewcommand{\arraystretch}{1.2} \[ \begin{array}{lcl@{}} \semc{\ifexpr{e_1}{e_2}{e_3}}\gamma_0\phi\nu_0&=&\mcompv{((\monadic{v}_1,\monadic{c}_1),\gamma_1,\omicron_1,\nu_1)\gets\semc{e_1}\gamma_0\phi\nu_0;\;\\\branching{\mcomp{(\!(\monadic{v}_2,\!\monadic{c}_2),\!\gamma_2,\!\omicron_2,\!\nu_2)\gets\semc{e_2}\gamma_1\phi\nu_1;\;\uopl{pure}(\!(\monadic{v}_2,\!\monadic{c}_2),\!\gamma_2,\!\omicron_1\omicron_2,\!\nu_2)}&\mbox{if $\monadic{v}_1\!=\!\uopl{pure}\mbox{\bfseries tt}$}\\\mcomp{(\!(\monadic{v}_3,\!\monadic{c}_3),\!\gamma_3,\!\omicron_3,\!\nu_3)\gets\semc{e_3}\gamma_1\phi\nu_1;\;\uopl{pure}(\!(\monadic{v}_3,\!\monadic{c}_3),\!\gamma_3,\!\omicron_1\omicron_3,\!\nu_3)}&\mbox{if $\monadic{v}_1\!=\!\uopl{pure}\mbox{\bfseries ff}$}\\\uopl{pure}(\!(\top,\!\top),\!\gamma_1,\!\omicron_1,\!\nu_1)&\mbox{otherwise}}}\\ \semc{\forexpr{x}{e_1}{e_2}{e_3}}\gamma_0\phi\nu_0&=&\mcompv{((\monadic{v}_1,\monadic{c}_1),\gamma_1,\omicron_1,\nu_1)\gets\semc{e_1}\gamma_0\phi\nu_0;\;\\((\monadic{v}_2,\monadic{c}_2),\gamma_2,\omicron_2,\nu_2)\gets\semc{e_2}\gamma_1\phi\nu_1;\;\\\branching{\uopl{main}(\max(0,i_2-i_1))&\mbox{where $\monadic{v}_j=\uopl{pure} i_j$}\\\uopl{pure}((\top,\top),\gamma_2,\omicron_1\omicron_2,\nu_2)&\mbox{if $\monadic{v}_1=\top$ or $\monadic{v}_2=\top$}}}\\ \multicolumn{2}{r@{}}{\mbox{where}}&\uopl{main}(n)=\mcompv{((\monadic{a}_1,\monadic{c}'_1),\gamma'_1,\omicron'_1,\nu'_1)\gets\semc{e_3}((x,(\uopl{pure} i_1,\top)),\gamma_2)\phi\nu_2;\;\\\forall k\!\!=\!\!2,\!...,\!n\!:\!(\!(\!\monadic{a}_{k},\!\monadic{c}'_{\!k}\!),\!\gamma'_{\!k},\!\omicron'_{\!k},\!\!\nu'_{\!k})\!\!\gets\!\!\semc{\!e_3\!}\!(\!(x,\!(\uopl{pure}(\!i_1\!+\!k\!-\!1)\!,\!\top)\!),\gamma'_{k\!-\!1})\phi\nu'_{k\!-\!1}\!;\;\\\uopl{pure}((\uopl{pure}((\monadic{a}_1,\monadic{c}'_1),\!...,\!(\monadic{a}_n,\monadic{c}'_n)),\top),\uopl{tail}\gamma'_n,\omicron_1\omicron_2\omicron'_1...\omicron'_n,\nu'_n)}\\ \semc{\wireexpr{e}}\gamma\phi\nu&=&\mcompv{((\monadic{v}',\monadic{c}'),\gamma',\omicron',\nu')\gets\semc{e}\gamma\phi\nu;\;\\\uopl{pure}((\monadic{v}',\branching{\uopl{pure}(\mknode{\uopl{con}(n)})&\mbox{if $\monadic{v}'=\uopl{pure} n$, $n\in\mathbb{N}$}\\\uopl{pure}(\mknode{\uopl{con}(|b|)})&\mbox{if $\monadic{v}'=\uopl{pure} b$, $b\in\mathbb{B}$}\\\uopl{pure}(\mknode{\uopl{in}_d(\nu'_d)})&\mbox{if $\monadic{v}'=\top$}}),\gamma',\omicron',\nu'')}\\ \multicolumn{2}{r}{\mbox{where}}&\mbox{$d$ is the domain of~$e$ and $\nu''=\lam{d'}{\branching{\nu'_{d'}+1&\mbox{if $d'=d$}\\\nu'_{d'}&\mbox{otherwise}}}$}\\ \semc{\stmtcomp{\letexpr{x}{e_1}}{e_2}}\gamma_0\phi\nu_0&=&\mcompv{((\monadic{v}_1,\monadic{c}_1),\gamma_1,\omicron_1,\nu_1)\gets\semc{e_1}\gamma_0\phi\nu_0;\;\\((\monadic{v}_2,\monadic{c}_2),\gamma_2,\omicron_2,\nu_2)\gets\semc{e_2}((x,(\monadic{v}_1,\monadic{c}_1)),\gamma_1)\phi\nu_1;\;\\\uopl{pure}((\monadic{v}_2,\monadic{c}_2),\uopl{tail}\gamma_2,\omicron_1\omicron_2,\nu_2)}\\ \semc{\stmtcomp{e_1}{e_2}}\gamma_0\phi\nu_0&=&\mcompv{((\monadic{v}_1,\monadic{c}_1),\gamma_1,\omicron_1,\nu_1)\gets\semd{e_1}\gamma_0\phi\nu_0;\;\\((\monadic{v}_2,\monadic{c}_2),\gamma_2,\omicron_2,\nu_2)\gets\semd{e_2}\gamma_1\phi\nu_1;\;\\\uopl{pure}((\monadic{v}_2,\monadic{c}_2),\gamma_2,\omicron_1\omicron_2)} \end{array} \] \caption{\label{fig:compilationlarge} Compilation to an arithmetic circuit: ``Large'' expressions and statements} \end{figure*} Our compilation semantics $\semc{\cdot}$ is presented in Figures~\ref{fig:compilationsmall} and~\ref{fig:compilationlarge}. We denote by $\mknode{\mathit{t}}(c_1,\ldots,c_n)$ the circuit with a node of the given class~$t$ as root and the circuits referenced by $c_1,\ldots,c_n$ as subtrees. Here, $n$ is $0$ or $2$ depending on~$t$, and $t$ can be $\uopl{con}(v)$ (a node of constant value~$v$), $\uopl{op}(\oplus)$ (a node of operation~$\oplus$), or $\uopl{in}_d(k)$ (the input node number~$k$ of domain~$d$). So the compiler builds up the arithmetic circuit from small pieces as subtrees. As explained above, we consider a node to be an output node iff it is a root of some output subcircuit. Output occurs in the \lstinline{assert} case only. Any Boolean~$b$ is replaced with its representative integer~$|b|$ where $|\mbox{\bfseries tt}|=0$, $|\mbox{\bfseries ff}|=1$ because the circuit only does (modular) arithmetic. Representing~$\mbox{\bfseries tt}$ by~$0$ arises from the fact that a \textsc{ZK-SecreC}\xspace program succeeds if all arguments of occurrences of \lstinline{assert} evaluate to~$\mbox{\bfseries tt}$ whereas the circuit checks if all its outputs are zero. Input nodes are created if a \lstinline{wire} construct is applied to a value in domain \lstinline{@prover} or \lstinline{@verifier}. This way, Verifier's and Prover's private values passed to the circuit via the \lstinline{wire} construct form an assignment that the circuit either accepts or not. Note that the $\uopl{upd}_{\mathrm{C}}$ function used in the assignment clause is here defined slightly differently from $\uopl{upd}$: \[\renewcommand{\arraycolsep}{2pt} \begin{array}{@{}lcl@{}} \uopl{upd}_{\mathrm{C}}((\monadic{v},\monadic{c}),\monadic{i}_1\ldots\monadic{i}_n,(\monadic{v}',\monadic{c}'))&=&\branching{(\monadic{v}',\monadic{c}')&\mbox{if $n=0$}\\\left(\monadic{v}'',\top\right)&\mbox{if $n>0$}}\\ \multicolumn{2}{r}{\mbox{where}}&\monadic{v}''=\mcomp{a\gets\monadic{a};\; i_1\gets\monadic{i}_1;\;\uopl{pure}([i_1\!\mapsto\!\uopl{upd}_{\mathrm{C}}(a_{i_1},\!\monadic{i}_2\ldots\monadic{i}_n,\!(\monadic{v}',\!\monadic{c}'))]a)}\mbox{.} \end{array} \] In the clause for \lstinline+get+, we use a new variant of the $\uopl{allpure}$ operation, $\uopl{allpuretop}$, that lifts a value in $U$ to $M\apV_\mathrm{C}\times M\, T$ in a straightforward manner by inserting $\uopl{pure}$ and $\top$ at each level: \[ \uopl{allpuretop}(v)=\branching{(\uopl{pure} v,\top)&\mbox{if $v$ is of a primitive type}\\(\uopl{pure}(\uopl{allpuretop}(v_1),\ldots,\uopl{allpuretop}(v_n)),\top)&\mbox{if $v=(v_1,\ldots,v_n)$}} \] In the following, we refer to the following auxiliary operation $|\cdot|:T\to M\,\mathbb{N}$ that evaluates a given circuit: \[\figsize |c|=\branching{\uopl{pure} n&\mbox{if $c=\mknode{\uopl{con}(n)}$}\\\mcomp{i_1\gets|c_1|;\; i_2\gets|c_2|;\;\uopl{pure}(i_1\oplus i_2)}&\mbox{if $c=\mknode{\uopl{op}(\oplus)}(c_1,c_2)$}\\\top&\mbox{if $c=\mknode{\uopl{in}_d(k)}$}} \] The results must be monadic since the input nodes do not refer to particular values and must be mapped to~$\top$. We also need an analogous operation that takes the circuit input into account. For any circuit~$c$ and $\pi\in(\mathbb{N}^*)^2$ (a sequence of input values for both Prover and Verifier), we define \[\figsize c(\pi)=\branching{n&\mbox{if $c=\mknode{\uopl{con}(n)}$}\\c_1(\pi)\oplus c_2(\pi)&\mbox{if $c=\mknode{(\uopl{op}(\oplus))}(c_1,c_2)$}\\\pi_d(i)&\mbox{if $c=\mknode{\uopl{in}_d(i)}$}} \] This operation always results in a pure value. If the output of compilation of an expression of a statement is $\omicron$ then the resulting circuit accepts an input~$\pi$ iff $\omicron_i(\pi)=0$ for all~$i$ such that $\omicron_i$ exists (where $\omicron_i$ denotes the $i$th component of the sequence~$\omicron$). We can prove Theorems~\ref{thm:can_compile} and~\ref{thm:correct_compilation} below. Theorem~\ref{thm:can_compile} establishes conditions under which well-typed programs can be compiled into a circuit. Theorem~\ref{thm:correct_compilation} states that compilation into a circuit preserves semantics. For establishing the claims in a mathematically precise form, we need several new notions. Definition~\ref{compilation:exact} introduces one more exactness property that is analogous to those in Sect.~\ref{sec:semantics}. Definition~\ref{compilation:eval} introduces an operation that calculates a monadic value that represents the given composite value. It uses the first component of the given composite value if it is pure, and finds the value of the circuit (in the second component of the composite value) on the given input if the circuit exists. This operation is needed to establish correspondence between composite values the compiler is computing with and the monadic values in the circuit semantics. Definition~\ref{compilation:equiv} introduces an equivalence relation on $M\, V$ that identifies integer and Boolean values that are encoded the same in the circuit. Definition~\ref{compilation:env} lifts the introduced operations pointwise to value environments. \begin{definition}\label{compilation:exact} For any well-structured qualified type $q=\qualty{t}{s}{d}$ and $(\monadic{v},\monadic{c})\in M\apV_\mathrm{C}\times M\, T$, we say that $(\monadic{v},\monadic{c})$ is \emph{$q$-exact} if all the following implications hold: \begin{enumerate} \item If $s=\mbox{\lstinline+$post+}$ then there is a circuit~$c$ such that $\monadic{c}=\uopl{pure} c , whereby $\monadic{v}=\uopl{pure} n$ with $n\in\mathbb{N}$ implies $|c|=\uopl{pure} n$, and $\monadic{v}=\uopl{pure} b$ with $b\in\mathbb{B}$ implies $|c|=\uopl{pure}|b|$, and in both latter cases $|c|=\uopl{pure}(c(\pi))$ for any input sequence~$\pi$. \item If $d=\mbox{\lstinline+@public+}$ and $t$~{}is a primitive type then $\monadic{v}=\uopl{pure} v$ where $v\in t$; \item If $d=\mbox{\lstinline+@public+}$ and $t=\listty{q'}$ then $\monadic{v}=\uopl{pure}((\monadic{v}_1,\monadic{c}_1),\ldots,(\monadic{v}_n,\monadic{c}_n))$ where $n\in\mathbb{N}$ and all $(\monadic{v}_1,\monadic{c}_1),\ldots,(\monadic{v}_n,\monadic{c}_n)\in M\apV_\mathrm{C}\times M\, T$ are $q'$-exact; \item If $s=\mbox{\lstinline+$pre+}$ then $\monadic{c}=\top$; \item If $d\ne\mbox{\lstinline+@public+}$ then $\monadic{v}=\top$. \end{enumerate} \end{definition} \begin{definition}\label{compilation:eval} Define $(\_,\_)\bullet\_:(M\apV_\mathrm{C}\times M\, T)\times(\mathbb{N}^*)^2\to M\, V$ as follows: For every pair $(\monadic{v},\monadic{c})\in M\apV_\mathrm{C}\times M\, T$ and circuit input $\pi\in(\mathbb{N}^*)^2$, \[ (\monadic{v},\monadic{c})\bullet\pi=\branching{\uopl{pure} n&\mbox{if $\monadic{v}=\uopl{pure} n$, $n\in\mathbb{N}$}\\\uopl{pure}|b|&\mbox{if $\monadic{v}=\uopl{pure} b$, $b\in\mathbb{B}$}\\\uopl{pure}\mbox{\textoneoldstyle}&\mbox{if $\monadic{v}=\uopl{pure}\mbox{\textoneoldstyle}$}\\\uopl{pure}((\monadic{v}_1,\monadic{c}_1)\bullet\pi,\ldots,(\monadic{v}_n,\monadic{c}_n)\bullet\pi)&\mbox{if $\monadic{v}=\uopl{pure}((\monadic{v}_1,\monadic{c}_1),\ldots,(\monadic{v}_n,\monadic{c}_n))$}\\\uopl{pure}(c(\pi))&\mbox{if $\monadic{v}=\top$ but $\monadic{c}=\uopl{pure} c$}\\\top&\mbox{if $\monadic{v}=\top$ and $\monadic{c}=\top$}} \] \end{definition} \begin{definition}\label{compilation:equiv} Define a binary predicate $\sim$ on $M\, V$ as follows: For every pair $(\monadic{v},\monadic{v}')\in M\, V\times M\, V$, we write $\monadic{v}\sim\monadic{v}'$ iff one of the following alternatives holds: \begin{enumerate} \item $\monadic{v}=\uopl{pure} v$ and $\monadic{v}'=\uopl{pure} v'$ where $v=v'$ or $|v|=v'$ or $v=|v'|$ or $|v| = |v'|$ (where $|\cdot|$ is applied to Boolean values but not to integers); \item $\monadic{v}=\uopl{pure}\mbox{\textoneoldstyle}=\monadic{v}'$; \item $\monadic{v}=\uopl{pure}(\monadic{v}_1,\ldots,\monadic{v}_n)$ and $\monadic{v}'=\uopl{pure}(\monadic{v}'_1,\ldots,\monadic{v}'_n)$ where $\monadic{v}_1\sim\monadic{v}'_1, \ldots, \monadic{v}_n\sim\monadic{v}'_n$; \item $\monadic{v}=\top=\monadic{v}'$. \end{enumerate} \end{definition} \begin{definition}\label{compilation:env} \begin{enumerate} \item Let $\Gamma$ be a well-structured type environment. We say that $\gamma\in\mathbf{Env}_\mathrm{C}$ is \emph{$\Gamma$-exact} iff $\uopl{vars}\gamma=\uopl{vars}\Gamma$ and, for every association $(x_i:q_i)$ occurring in $\Gamma$, the value in the corresponding association $(x_i,(\monadic{v}_i,\monadic{c}_i))$ is $q_i$-exact. \item For $\gamma\in\mathbf{Env}_\mathrm{C}$ and $\pi\in(\mathbb{N}^*)^2$, we define $\gamma\bullet\pi\in\mathbf{Env}$ by lifting the bullet operation pointwise to association lists. \item For $\gamma,\gamma'\in\mathbf{Env}$, we write $\gamma\sim\gamma'$ iff $\uopl{vars}\gamma=\uopl{vars}\gamma'$ and $\lookup{\gamma}{x}\sim\lookup{\gamma'}{x}$ for each defined variable~$x$. \end{enumerate} \end{definition} We also extend $\sim$ pointwise to sequences (of equal length) of monadic values and, furthermore, to tuples of such sequences. For any natural number~$n$ and list~$l$, we write $\uopl{drop} n\, l$ to denote the part of list~$l$ remaining if the first $n$ elements are removed. We write $\uopl{map} f\, l$ for the result of applying~$f$ to all elements of~$l$. Using these auxiliary operations, we extend the bullet notation to denote $\nu\bullet\pi=\lam{d}{\uopl{map}\uopl{pure}\left(\uopl{drop}\nu_d\pi_d\right)}$ where $\nu\in\mathbb{N}^2$, $\pi\in(\mathbb{N}^*)^2$ and $d$ ranges over $\set{\mbox{\lstinline+@prover+},\mbox{\lstinline+@verifier+}}$. \begin{theorem}\label{thm:can_compile} Let $\Gamma \mbox{\ $\vdash$\ } e : q! D$ with well-structured~$\Gamma$. Let $\gamma\in\mathbf{Env}_\mathrm{C}$ be $\Gamma$-exact. Let $\phi\in\mathbf{In}^3$ such that, for all subexpressions of~$e$ of the form $\ofty{\getexpr{d}{k}}{q'}$ where $d=\mbox{\lstinline+@public+}$, the value $\uopl{allpure}(\phi_{d}(k))$ is $q'$-exact in~$d$. Let $\nu\in\mathbb{N}^2$. Unless an array lookup fails due to an index being out of bounds, we have $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\gamma',\omicron,\nu')$ for some $\monadic{v}$, $\monadic{c}$, $\gamma'$, $\omicron$ and $\nu'$, whereby $(\monadic{v},\monadic{c})$ is $q$-exact and $\gamma'$ is $\Gamma$-exact. \end{theorem} In the following theorem: \begin{itemize} \item Letters without tilde denote the original states and those with tilde denote result states; \item Letters without prime denote compiler states while those with prime denote states in circuit semantics. \end{itemize} \begin{theorem}\label{thm:correct_compilation} Let $\Gamma \mbox{\ $\vdash$\ } e:\qualty{t}{s}{d}! D$ with well-structured~$\Gamma$. Let $\gamma\in\mathbf{Env}_\mathrm{C}$ be $\Gamma$-exact, $\phi\in\mathbf{In}^3$ be a triple of type correct input dictionaries, and $\nu\in\mathbb{N}^2$. Let $\semc{e}\gamma\phi\nu=\uopl{pure}((\monadic{v},\monadic{c}),\tilde{\gamma},\tilde{\omicron},\tilde{\nu})$. Let $\pi\in(\mathbb{N}^*)^2$, $\gamma'\in\mathbf{Env}$, $\omicron'\in\mathbf{Out}^2$ be such that $\gamma'$ is $\Gamma$-exact in circuit, $\gamma\bullet\pi\sim\gamma'$ and $\nu\bullet\pi\sim\omicron'$. Then: \begin{enumerate} \item If $\sem{e}\gamma'\phi\omicron'=\uopl{pure}(\monadic{v}',\tilde{\gamma}',\tilde{\omicron}')$ then $\tilde{\omicron}$ accepts $\pi$; moreover, $\tilde{\gamma}\bullet\pi\sim\tilde{\gamma}'$ and $\tilde{\nu}\bullet\pi\sim\tilde{\omicron}'$, and $d=\mbox{\lstinline+@public+}$ or $s=\mbox{\lstinline+$post+}$ implies $(\monadic{v},\monadic{c})\bullet\pi\sim\monadic{v}'$; \item If $\sem{e}\gamma'\phi\omicron'$ fails (i.e., it is not of the form $\uopl{pure}(\monadic{v}',\tilde{\gamma}',\tilde{\omicron}')$), while all circuits that arise during compilation need only inputs in~$\pi$, then $\tilde{\omicron}$~{}does not accept $\pi$. \end{enumerate} \end{theorem} The theorems are proved by structural induction on~$e$. The details are given in Appendix~\ref{compilation-proofs}. \section{Useful constructions}\label{sec:extensions}\label{ssec:dictionaries} Our choice of the details of the type system is validated by the ease of implementing certain constructions that often occur in the statements to be proved in ZK. We will describe them next, after two simple extensions to \textsc{ZK-SecreC}\xspace. First, whenever $s_1,\ldots,s_n$ are identifiers and $t_1,\ldots,t_n$ are qualified types, then $\{s_1:t_1,\ldots,s_n:t_n\}$ is a qualified type. Records are defined by specifying the values of all fields, and the values of the fields can be read. The record itself is implicitly qualified \lstinline+$pre @public+. \textsc{ZK-SecreC}\xspace allows to declare type synonyms for record types using the keyword \lstinline{struct}. Second, parameters of functions can also be passed by reference. Changes to a by-reference parameter inside the called function are visible in the calling function. A parameter preceded by the keyword \lstinline+ref+ in a function declaration is passed by reference. \paragraph{Bit extraction} Arithmetic circuits naturally support addition and multiplication of values. To compare two values, they have to be split into bits as in Fig.~\ref{language:factor}. We see that each invocation of \lstinline+less_than+ causes the bits of both of its arguments being computed. Hence the value of variable \lstinline+z+ is split into bits twice, resulting in different lists of bits created by the \lstinline+wire+ expression in the function \lstinline+bitextract+, but with equal values. It is conceivable that an optimizing compiler is able to detect that these lists of bits have to be equal. However, in a DSL like \textsc{ZK-SecreC}\xspace, we prefer to be able to explicitly indicate the availability of such language-specific optimizations. If the value of a variable \lstinline+v+ of type \lstinline+uint[N] $post @D+ could be split into bits, then we could define it with the following type instead (note polymorphism over \lstinline+N+, as well as \lstinline+@D+): \begin{lstlisting} struct uint_with_bits[N : Nat, @D] { value : uint[N] $post @D, hasBits : bool $pre @public, bits : list[bool[N] $post @D] } \end{lstlisting} When creating or updating the value, we define the field \lstinline+value+ and set \lstinline+hasBits+ to \lstinline+false+. The function \lstinline+bitextract+ checks the field \lstinline+hasBits+ of its argument (which is passed by reference) and returns the content of the field \lstinline+bits+ if it is true. The function performs the actual splitting into bits only if the field \lstinline+hasBits+ is false; in this case it updates \lstinline+bits+ and sets \lstinline+hasBits+. \paragraph{Dictionaries} Dictionaries generalize arrays, allowing the keys (indices) to come from any set, not just from a segment of integers, and supporting the operations \lstinline+load(key)+ and \lstinline+store(key,value)+. In \textsc{ZK-SecreC}\xspace, lists (which play the role of arrays) have rather restrictive typing rules associated with them, making sure that computations with them can be converted into circuit operations. Having the keys in \lstinline+$post+ and in an arbitrary domain requires the use of \emph{Oblivious RAM} (ORAM)~\cite{DBLP:journals/jacm/GoldreichO96}, which has had a number of solutions proposed in the context of ZK proofs~\cite{DBLP:conf/ccs/Neff01,buffet,DBLP:conf/asiacrypt/BootleCGJM18}. A general method for ORAM in ZKP context~\cite{buffet} performs no correctness checks while the \lstinline+load+ and \lstinline+store+ operations are executed. Rather, all checks for a particular dictionary will be performed when it is no longer used; these checks involve sorting the list of operations by the values of keys, and checking that the equality of certain keys implies the equality of accompanying values. We refer to~\cite{buffet} for details. The type and the supported operations of a dictionary are given in Fig.~\ref{fig:dictionaries}. During the execution, the performed operations have to be recorded. Both the \lstinline+load+ and \lstinline+store+ operations log the key, the value, and the performed operation (where \lstinline+false+ means loading, and \lstinline+true+ means storing). When logging, the key and the value (which may be private) are kept in the stage \lstinline+$post+, thereby fixing the values in the circuit. The performed operation, however, is public, because \lstinline+load+ and \lstinline+store+ can only be invoked in a public context. The functions \lstinline+find+ and \lstinline+update+ work with values in the stage \lstinline+$pre+ only, looking up a binding or updating them; their specification is mundane. The function \lstinline+finalize+ is run on the field \lstinline+log+ of a dictionary before that dictionary goes out of scope, it implements the checks in~\cite{buffet}. \textsc{ZK-SecreC}\xspace contains syntactic sugar for dictionary creation, and loading and storing of values. It also automatically adds the calls to \lstinline+finalize+ at the end of the block containing the creation of the dictionary. \begin{figure} \begin{lstlisting} struct keyValuePair[N : Nat,$S,@D] { key : uint[N] $S @D, val : uint[N] $S @D } struct operation[N : Nat,@D] { kv : keyValuePair[N,$post,@D], op : bool $pre @public } struct map[N : Nat,@D] { bindings : list[keyValuePair[N,$pre,@D]], log : list[operation[N,@D]] } fn create[N : Nat,@D]() -> map[N,@D] { { bindings = [], log = [] } } fn load[N : Nat,@D](ref d : map[N,@D], k : uint[N] $post @D) -> uint[N] $post @D { let v : uint[N] $post @D = wire { find(d.bindings, k as $pre) }; d.log = cons({ kv = { key = k, val = v }, op = false }, d.log); v } fn store[N : Nat,@D](ref d : map[N,@D], k : uint[N] $post @D, v : uint[N] $post @D) { d.bindings = update(d.bindings, k as $pre, v as $pre); d.log = cons({ kv = { key = k, val = v }, op = true }, d.log); } fn finalize[N : Nat,@D](ops : list[operation[N,@D]]) { // sorting and assertions omitted } \end{lstlisting} \caption{Implementing dictionaries}\label{fig:dictionaries} \end{figure} Depending on the number of loads and stores, as well as other characteristics of the operations of the dictionary, different ways of performing finalization may be most efficient~\cite{xJSnark}. If these characteristics can be derived or predicted from public data, the best way can be chosen in \lstinline+finalize+. \section{Introduction}\label{intro} Zero-knowledge proofs (ZKP)~\cite{DBLP:conf/stoc/GoldwasserMR85} are two-party protocols between Prover and Verifier, where the former attempts to convince the latter that he has a piece of knowledge that validates a statement, while not revealing anything about this knowledge. Here this statement is seen as a binary relation $R$ that takes as inputs the \emph{instance} --- common knowledge of Prover and Verifier ---, and the \emph{witness} --- Prover's private knowledge ---, and decides whether the latter validates the former. Among the first practical instances of ZKP was privacy-preserving identification~\cite{DBLP:journals/joc/Schnorr91}, where both the client and the server knew client's public key $h$ --- an element in a cyclic group $\mathbb{G}$ of size $p$ with a hard discrete logarithm problem ---, and the client proved to the server that he knew the discrete logarithm $x$ of $h$ (to the basis of a generator $g$). Considering $g$ a public parameter, the relation $R$ here is a subset of $\mathbb{G}\times\mathbb{Z}_p$, where $\mathbb{Z}_p=\{0,1,\ldots,p-1\}$ is the ring of integers modulo $p$. We have $(h,x)\in R$ iff $g^x=h$. Both the client and the server knew the first component, but only the client knew the second one. The protocol convinced the server of having established communication with someone who knows $x$ such that $(h,x)\in R$, but gave no further information about $x$. Later advances in ZKP~\cite{DBLP:conf/stoc/IshaiKOS07,ZKBoo,DBLP:conf/eurocrypt/Groth16,bunz2018bulletproofs} allow the creation of ZKP for statements that are significantly bigger and more complex than the described identification protocol, with privacy-preserving distributed ledgers~\cite{DBLP:conf/sp/MiersG0R13,narula2018zkledger} showing a large variety. More applications from a heterogeneous variety of areas are expected in the future~\cite{ZKProofApplicationsTrackProceeding}. All these applications need tools for expressing the binary relation. All cryptographic techniques for ZKP expect the relation to be expressed as an arithmetic circuit over some finite ring (for most techniques, a field, often with additional constraints), handling only a very limited number of operations. For example, even if there existed a field $\mathbb{F}$ that suitably embedded $\mathbb{G}$ and $\mathbb{Z}_p$ from our first example, and there were ZKP techniques for circuits over $\mathbb{F}$, the relation $R$ probably would not be directly representable as an arithmetic circuit over $\mathbb{F}$, because exponentiation is not among the supported operations. Additions and multiplications are supported, hence we could express $R$ if we represented $x$ as a sequence of bits. These bits can be computed by Prover, and added to the second component of $R$ (changing its type in the process). If $R$ is but a part of a larger relation, then we may need $x$ being represented in various ways. Prover can add all these representations to the inputs of that relation. But then Verifier needs to be convinced that all these representations correspond to the same value of $x$, hence there need to be checks for that. When expressing a relation for the subsequent use of ZKP techniques, we want to state what extra values should be added to the witness and the instance in order to make the circuit simpler (or computable at all), and which checks should be included. Describing and encoding a circuit and the \emph{expansion} of its inputs directly is error-prone; it is difficult to specify the circuit, as well as to understand what it does. Such state of affairs may be acceptable if ZK proofs are expected to be given only for a small number of relations $R$, but a high-level domain-specific language and associated compilation tools for specifying the relations $R$ are desirable for wide-spread adoption. The specification should mostly be in terms used by common programming languages, exposing only those ZKP-specific details that are highly significant for obtaining a circuit that is handled efficiently by the cryptographic technique and does not reveal Prover's inputs. The specified relation should be automatically translated into the arithmetic circuit, while being optimized for the performance profiles of ZKP techniques. Besides the construction of the arithmetic circuit, the language and compilation tools must help in the preparation of common and Prover's inputs for it. The features of the language have to support the execution by the two parties and a common ZKP protocol between them, with these components not fully trusting each other. In this paper, we propose \textsc{ZK-SecreC}\xspace --- a programming language for specifying relations between instances and witnesses, together with a toolchain that produces circuits suitable as inputs for ZKP techniques. In their design, we have aimed to tackle the following issues. \paragraph{Execution at multiple locations} A \textsc{ZK-SecreC}\xspace program specifies, and the \textsc{ZK-SecreC}\xspace compiler produces the description of a circuit, which both Prover and Verifier use as one of the inputs to a cryptographic technique for ZK proofs. Besides running the cryptographic protocol, both parties may need to run some parts of the program locally for the purpose of increasing the efficiency of computations. A \textsc{ZK-SecreC}\xspace program can thus specify local computations, and the compiler can produce code that Verifier will and Prover should execute with their inputs. \paragraph{Compilation into a circuit} Having the arithmetic circuit as an intermediate representation makes our compiler agnostic towards the used cryptographic techniques, and allows the compilation result to be retargeted easily, so that it may be created once and then used multiple times by Prover to convince Verifier that it knows the witnesses for several different instances. Even though the circuit may only contain a very restricted set of operations, targeting only a particular ZKP technology will not significantly increase the supported set. Our type system for \textsc{ZK-SecreC}\xspace makes sure that non-supported operations cannot be added to the arithmetic circuit, and that the shape of the circuit and the operations in its nodes are public. \paragraph{Witness and instance expansion} Adding more inputs to the circuit and verifying that they are correctly related to previous inputs is a pervasive technique for improving the efficiency of computations of the relation. \textsc{ZK-SecreC}\xspace allows to freely mix computations on circuit and off circuit. The results of the latter become additional inputs of the circuit. Tackling these issues allows us to support the deployment model that we consider likely for many use-cases of ZKP; the model is depicted in Fig.~\ref{fig:deploymentmodel}. \begin{figure} \includegraphics[width=\textwidth]{ZKSC-deployment.pdf} \caption{Deploying ZK proofs with \textsc{ZK-SecreC}\xspace tools. (1) Prover and Verifier agree on the description of the relation $R$. (2) The relation $R$ is compiled, perhaps by a service provider, perhaps by Prover and Verifier themselves, producing the description of the circuit, and executables for processing the instance and witness. (3) Prover and Verifier agree on the instance for which the proof will be made; the Prover must also have a witness. (4) Prover and Verifier expand the given instance and witness. (5) The implementation of a (cryptographic) ZKP technology gets as input the circuit, and the instance and the witness in the form ingested by the circuit. (6) ZKP protocol is executed. (7) Verifier obtains the verification result.}\label{fig:deploymentmodel} \end{figure} \paragraph{Semantics} The statement to be proven is commonly seen as a binary relation, but its meaning is really the left projection of that relation. The semantics of \textsc{ZK-SecreC}\xspace precisely defines the meaning of its program . The language constructions and the type system of \textsc{ZK-SecreC}\xspace capture the essential details common to all ZK proofs. A ZK proof aims to give both confidentiality and integrity guarantees. \textsc{ZK-SecreC}\xspace precisely fixes the possible movements of data between different domains, enforcing the ``no read up'' and ``no write down'' properties without exceptions. The viability of such strong restrictions shows that the confidentiality guarantees are similar for all ZK proofs, and do not really depend on the particular relation, to which the ZK proofs technique has been applied. On the other hand, the necessary checks for making sure that the relation is satisfied are very much a part of the description of that relation; their inclusion is the responsibility of the programmer encoding this relation in \textsc{ZK-SecreC}\xspace. Hence, the language cannot offer much of \emph{formal} support in verifying that the desired integrity properties have been specified by the programmer. We start this paper in Sect.~\ref{sec:zkscexample} with an example program in \textsc{ZK-SecreC}\xspace, showing off its features. We continue with the description of the syntax of \textsc{ZK-SecreC}\xspace in Sect.~\ref{sec:syntax} and its type system in Sect.~\ref{sec:typesystem}. The execution of a well-typed program can be split between different domains in the manner that we desire, with necessary data available at each domain. An arithmetic circuit, suitable as an input to a ZKP technique, can also be statically extracted from a well-typed program. In Sect.~\ref{sec:semantics} we give a formal semantics of \textsc{ZK-SecreC}\xspace, stating the language that is accepted by a \textsc{ZK-SecreC}\xspace program. Following up on it, we describe the compilation into an arithmetic circuit in Sect.~\ref{sec:compilation}. We continue with the evaluation of expressivity and efficiency of \textsc{ZK-SecreC}\xspace, first showing in Sect.~\ref{sec:extensions} how some data structures and methods useful for ZKP can be straightforwardly encoded, and then discussing in Sect.~\ref{sec:evaluation} the circuits output by \textsc{ZK-SecreC}\xspace compiler for various example problems. We finish the paper in Sect.~\ref{sec:relwork} by comparing \textsc{ZK-SecreC}\xspace against other existing languages and means of specifying statements proved in ZK. The appendices provide full proofs of the lemmas and theorems. \section{\textsc{ZK-SecreC}\xspace on an Example}\label{sec:zkscexample} Let us start the description of the language with an example. Suppose that Prover and Verifier both know a large integer~$z$. Prover wants to convince Verifier that he also knows a factor~$x$ of~$z$ such that $1<x<z$. In ZKP terms, $z$~is the \emph{instance} and $x$~is the \emph{witness}. The relation between $z$ and~$x$ can be specified in \textsc{ZK-SecreC}\xspace as shown in Fig.~\ref{language:factor}. This program specifies an arithmetic circuit that Prover and Verifier have to execute on top of a ZKP technology of their choice, as well as the local computations they both should perform. \begin{figure}[tbp] \begin{lstlisting} fn bitextract_pre[@D](x : uint[N] $pre @D, fbw : uint $pre @public) -> list[bool[N] $pre @D] { let rec xx = for i in 0 .. fbw { // generates a list of length fbw if (i == 0) { x } else { xx[i - 1] / 2 } }; for i in 0 .. fbw { // generates a list of booleans, which is returned let b = xx[i] b == 1 } } fn check_bitextract[@D](x : uint[N] $post @D, xb : list[bool[N] $post @D]) { let mut s = xb[length(xb) - 1] as uint[N]; // variable s is mutable for i in 0 .. length(xb) - 1 { s = 2 * s + xb[length(xb) - i - 2] as uint[N]; }; assert_zero(x - s); } fn bitextract[@D](x : uint[N] $post @D, fbw : uint $pre @public) -> list[bool[N] $post @D] { let xb_pre = bitextract_pre(x as $pre, fbw); let xb = for i in 0 .. length(xb_pre) { wire { xb_pre[i] } }; if (@prover <= @D) { check_bitextract(x, xb); }; xb } fn less_than[@D1, @D2, @D](x : uint[N] $post @D1, y : uint[N] $post @D2, fbw : uint $pre @public) -> bool[N] $post @D where @D1 <= @D, @D2 <= @D { let xb = bitextract(x as @D, fbw); let yb = bitextract(y as @D, fbw); // lexicographic comparison of lists of bits xb and yb omitted } fn main() { let fbw : uint $pre @public = get_public("fixed bit width"); let z : uint[N] $post @verifier = wire { get_instance("z") }; let x : uint[N] $post @prover = wire { get_witness("x") }; let y = wire { z as $pre as @prover / x as $pre }; assert_zero(x * y - (z as @prover)); assert(less_than(x, z, fbw)); assert(less_than(y, z, fbw)); } \end{lstlisting} \caption{\label{language:factor} A \textsc{ZK-SecreC}\xspace program for verifying that Prover knows a proper factor of a given positive integer} \end{figure} Execution of the program starts from the function \lstinline{main}. It first loads a public constant \lstinline+fbw+, determining the size of the inputs handled by the circuit. As next, the two inputs $z$ and $x$ are loaded, with the former being visible to both Prover and Verifier, while the latter is seen by Prover only. Both inputs of the program are made inputs to the arithmetic circuit that the compilation of the program produces, using the \lstinline+wire+ construct. The \emph{stage} \lstinline+$pre+ denotes that the value is only available for the local computations by Prover and Verifier, while \lstinline+$post+ denotes its availability in the circuit. The \emph{domain} \lstinline+@prover+ denotes that only Prover knows this value, while \lstinline+@verifier+ denotes that Verifier also has knowledge of it, and \lstinline+@public+ means that this value is known at compile time. Note that the domain only informs about the availability of the value in \emph{local} computations. The ZKP technology will interpret the operations of the arithmetic circuit over some finite field, and its structure may be important in specifying the relation. We have found that hiding the size of the field from the programmer is not a sensible choice, as too much depends on it. However, the code can be polymorphic over that size. Hence the \emph{data type} \lstinline+uint[N]+ denotes unsigned integers modulo an integer \lstinline+N+ (a compile-time parameter). Unbounded integers, available only in \lstinline+$pre+ stage, have the data type \lstinline+uint+. In the next line, Prover \emph{expands the witness}. In order to show that $x$ divides~$z$, Prover has to come up with a value~$y$ satisfying $x\cdot y=z$. The division operation is only available for local computations. Hence, in the program, the values \lstinline+z+ and \lstinline+x+ are turned back into values available for local computations using the \lstinline+as $pre+ operation, and divided; the result of the division is turned to another input of the arithmetic circuit. The domain of \lstinline+z as $pre+ is still \lstinline+@verifier+, hence it is cast up to \lstinline+@prover+, because the division operator expects its arguments to have equal types. The type of~\lstinline+y+ is automatically inferred as \lstinline+uint[N] $post @prover+. The types of \lstinline+fbw+, \lstinline+z+, and \lstinline+x+ could have been inferred automatically, too. The next line in the function \lstinline+main+ specifies the check that the expression \lstinline+x*y-z+ is evaluated to zero, i.e., the product of \lstinline+x+ and \lstinline+y+ indeed equals \lstinline+z+. Multiplication and subtraction operations are available in \lstinline+$post+ stage (both expect arguments to have equal types), likewise is the check that a number is zero. Even though the previous line has stated that Prover should compute $y$ as $z/x$, Verifier cannot trust that it was computed like this, hence this check is necessary. The computations done in the circuit are trusted by Verifier. The last two lines in \lstinline+main+ check that $x<z$ and $y<z$. The comparison is made by obtaining the bitwise representations (of width \lstinline+fbw+) of both arguments, which can be straightforwardly compared. We see that the function \lstinline+less_than+ is polymorphic in its argument and result domains. The size \lstinline+N+ also matters for booleans, because they are represented as integers when translated to the arithmetic circuit. The bit representations are computed by the function \lstinline+bitextract+. Well, they are actually computed in the stage \lstinline+$pre+ by the function \lstinline+bitextract_pre+, making use of operations not available in the arithmetic circuit. The result is then added as inputs to the circuit by \lstinline+bitextract+ that also checks its correctness if needed. The correctness check is necessary only if the argument and the result are in the domain \lstinline+@prover+. In the case of domains of lower privacy, Verifier can check correctness of the result directly. Representing some integer as a sequence of bits is a typical instance/witness expansion. As this example shows, \textsc{ZK-SecreC}\xspace (intentionally) enables interleaving circuit computation with local computation and specifying both of them within one language. Although one cannot be sure that computations outside the circuit are performed exactly like in the code, specifying the intended behavior using the same notation is good for readability and reduces the amount of code (as \textsc{ZK-SecreC}\xspace allows stage polymorphism). As mingling of circuit computation and local computation can be arbitrarily complex, attempts to keep the corresponding pieces of code separate lead to big difficulties. \section{Appendix} \end{document} \section{Related Work}\label{sec:relwork} The ZKP use-case proliferation has brought with it a number of tools for either generating the circuits for some cryptographic ZK technique, or for directly describing the computation that runs under a ZKP technique. If the toolset contains a domain-specific language, then its features may often be given the following description in terms \textsc{ZK-SecreC}\xspace. The included DSL has mainly imperative features, it is strongly typed, and the possible qualifiers of the types are \lstinline+$post @prover+ and \lstinline+$pre @public+. The latter type is used in computations defining the structure of the circuit (e.g. for loop counters), while the computations with the former are translated into the circuit or invoked using the ZKP technique. The instance and witness to the computation both receive the qualifiers \lstinline+$post @prover+. The language also allows local computations. Typically, it allows casts from \lstinline+$pre @public+ to \lstinline+$post @prover+, and perhaps to use \lstinline+$post @prover+ values also in the computations at \lstinline+$pre @public+, the results of which must be cast back to \lstinline+$post @prover+. Such languages include \textsc{circom}~\cite{circom} and ZoKrates~\cite{zokrates}. The latter also includes branchings over \lstinline+$post @prover+ conditions, translating them into executions of both branches, followed by an oblivious choice. We have purposefully excluded such construction, believing it will confuse the developer. The languages to generate circuits (or rank-1 constraint systems) also include \textsc{Sn\r{a}rkl}~\cite{DBLP:conf/padl/StewartML18}, a DSL embedded in Haskell. The necessary local computations are introduced during compilation, in the style of \textsc{Pinocchio}~\cite{DBLP:journals/cacm/ParnoHG016} and Setty et al.~\cite{DBLP:conf/uss/SettyVPBBW12}. \textsc{Pinocchio} is an early example of a system for \emph{verifiable computation}, aiming to make the correctness of the execution of C programs verifiable in a manner that is cheaper than re-running the program. This approach, refined in~\cite{Geppetto}, as well as in~\cite{ben2014succinct,DBLP:conf/sp/WahbyHGSW16} for hardware-like descriptions, uses a common high-level language to define the circuit, with any \lstinline+$pre+-stage computation inserted through compiler optimizations. We consider the language of the xJSnark system~\cite{xJSnark} to be the closest to \textsc{ZK-SecreC}\xspace. It follows the description given above. For local computations, it offers blocks of code which take values with both \lstinline+$post @prover+ and \lstinline+$pre @public+ qualifiers, and return the results back to \lstinline+$post @prover+. While it is more expressive than~\cite{circom,zokrates}, we consider our type system to be superior to its method for mixing local computations with those on the circuit. Indeed, our type system offers distinction between \lstinline+$pre @prover+ and \lstinline+$pre @verifier+, and the integrity properties inherent in them. We made use of this distinction in Fig.~\ref{language:factor}. Additionally, in \textsc{ZK-SecreC}\xspace, values in the \lstinline+$pre+-stage can be long-lived, the usefulness of which we showed in Sec.~\ref{ssec:dictionaries}. Finally, we can be polymorphic over stages, allowing same or similar computations performed either locally or in the circuit to be expressed only once. Hastings et al.~\cite{DBLP:conf/sp/HastingsHNZ19} review 11 different MPC suites from the point of view of the language support the offer for the specification of secure MPC protocols. While the proposed languages often distinguish between private and public values, only Wysteria~\cite{Wysteria,Wys-star} offers constructions to specify the computations done by one or several parties, either locally or using a secure multiparty computation protocol. Their handling of parties is very expressive and general, but the notion of malicious parties is lacking. The recent Viaduct suite~\cite{Viaduct} expands on Wysteria's type system with integrity types, and incorporates also ZK proofs and other secure computation techniques besides MPC in its back-end. However, Viaduct's type system does not distinguish between \lstinline+@verifier+ and \lstinline+@public+, and thus does not support the compilation into a circuit. The distinctions between other qualifiers of \textsc{ZK-SecreC}\xspace are present in Viaduct. Additionally, the handling of data structures by Viaduct's type system is simplified, with e.g. no distinction between read- and write-access to arrays. \section{Proofs of Theorems \ref{semantics:compthm}--\ref{semantics:correctness}}\label{semantics-proofs} We start with proving some auxiliary lemmas. \begin{lemma}\label{semantics:reintlemma} \begin{enumerate} \item Let $q=(\qualty{t}{s}{d})$ be a qualified type and $P$ be a predicate defined on qualified types. If $\monadic{v}\in M\, V$ is $q$-exact in~$P$ then $\monadic{v}$ is $q$-exposed in~$P$. \item Let $\Gamma$ be a well-structured type environment and $P$ be a predicate defined on qualified types. If $\gamma\in\mathbf{Env}$ is $\Gamma$-exact in~$P$ then $\gamma$ is $\Gamma$-exposed in~$P$. \end{enumerate} \end{lemma} \begin{proof} \begin{enumerate} \item If $P(q)$ is false then the claim holds trivially by Definition~\ref{semantics:exposeddef}. Assume $P(q)$ being true. We proceed by induction on the structure of the data type~$t$. If $t$ is a primitive type then the claim again follows directly from Definitions~\ref{semantics:exposeddef} and \ref{semantics:exactdef}. If $t=\listty{q'}$ then, by Definition~\ref{semantics:exactdef}, $\monadic{v}=\uopl{pure}(\monadic{v}_1,\ldots,\monadic{v}_n)$ where all $\monadic{v}_i$ are $q'$-exact in~$P$. By the induction hypothesis, $\monadic{v}_i$ are $q'$-exposed in~$P$. Hence by Definition~\ref{semantics:exposeddef}, $\monadic{v}$ is $q$-exposed in~$P$. \item Let $\uopl{vars}\Gamma=(x_1,\ldots,x_n)$ and the corresponding types be $q_1,\ldots,q_n$. By $\gamma$ being $\Gamma$-exact in~$P$, $\gamma=((x_1,\monadic{v}_1),\ldots,(x_n,\monadic{v}_n))$ for some $\monadic{v}_1,\ldots,\monadic{v}_n$ such that, for every $i=1,\ldots,n$, the corresponding value $\monadic{v}_i$ is $q_i$-exact in~$P$. By part~(1), $\monadic{v}_i$ is $q_i$-exposed in~$P$. Hence $\gamma$ is \mbox{$\Gamma$-exposed} in~$P$. \end{enumerate} \end{proof} \begin{lemma}\label{semantics:approxlemma} \begin{enumerate} \item Let $q=(\qualty{t}{s}{d})$ be a qualified type and $P,Q$ be predicates on qualified types such that $Q(q')\Rightarrow P(q')$ for all qualified types~$q'$. If $\monadic{v}\in M\, V$ is $q$-exposed in~$P$ then $\monadic{v}$ is $q$-exposed in~$Q$. \item Let $\Gamma$ be a well-structured type environment and $P,Q$ be predicates on qualified types such that $Q(q')\Rightarrow P(q')$ for all qualified types~$q'$. If $\gamma\in\mathbf{Env}$ is $\Gamma$-exposed in~$P$ then $\gamma$ is $\Gamma$-exposed in~$Q$. \end{enumerate} \end{lemma} \begin{proof} \begin{enumerate} \item If $Q(q)$ does not hold then the desired claim holds by clause~3 of Definition~\ref{semantics:exposeddef}. Assume now $Q(q)$. Then also $P(q)$. We proceed by induction on the structure of the data type~$t$. If $t$ is a primitive type then clause~1 of Definition~\ref{semantics:exposeddef} implies $\monadic{v}=\uopl{pure} v$, $v\in t$, which in turn gives $\monadic{v}$ being $q$-exposed in~$Q$. If $t=\listty{q'}$ then clause~2 of Definition~\ref{semantics:exposeddef} implies $\monadic{v}=\uopl{pure}(\monadic{v}_1,\ldots,\monadic{v}_n)$ where $\monadic{v}_i$ being $q'$-exposed in~$P$ for all $i=1,\ldots,n$. By the induction hypothesis, all $\monadic{v}_i$ are $q'$-exposed in~$Q$. So, by clause~2 of Definition~\ref{semantics:exposeddef}, $\monadic{v}$ is $q$-exposed in~$Q$. \item Let $\uopl{vars}\Gamma=(x_1,\ldots,x_n)$ and the corresponding types be $q_1,\ldots,q_n$. Let $\gamma$ be $\Gamma$-exposed in~$P$. Then $\gamma=((x_1,\monadic{v}_1),\ldots,(x_n,\monadic{v}_n))$ where, for every $i=1,\ldots,n$, $\monadic{v}_i$ is $q_i$-exposed in~$P$. By part~(1), $\monadic{v}_i$ is $q_i$-exposed in~$Q$. Hence $\gamma$ is $\Gamma$-exposed in~$Q$. \end{enumerate} \end{proof} \begin{lemma}\label{semantics:approxcirclemma} Let $q$ be a qualified type such that $\uopl{allpre}_{d_0}q$ where $d_0=\mbox{\lstinline+@public+}$. If $\monadic{v}$ is $q$-exact in $\mbox{\lstinline+@prover+}$ then $\monadic{v}$ is $q$-exact in circuit. \end{lemma} \begin{proof} Let $q=(\qualty{t}{s}{d})$. We proceed by induction on the structure of~$t$. If $t$ is a primitive type then, by $\monadic{v}$ being $q$-exact in $\mbox{\lstinline+@prover+}$, $\monadic{v}=\uopl{pure} v$ where $v\in t$. But $\uopl{allpre}_{d_0}q$ implies $d=d_0=\mbox{\lstinline+@public+}$. Hence $\uopl{pure} v$ is $q$-exact in circuit. Now assume $t=\listty{q'}$. By $\monadic{v}$ being $q$-exact in $\mbox{\lstinline+@prover+}$, $\monadic{v}=\uopl{pure}(\monadic{v}_1,\ldots,\monadic{v}_n)$ where $n\in\mathbb{N}$ and all $\monadic{v}_i$ are $q'$-exact in $\mbox{\lstinline+@prover+}$. Note that $\uopl{allpre}_{d_0}q$ implies $\uopl{allpre}_{d_0}q'$. Hence by the induction hypothesis, all $\monadic{v}_i$ are $q'$-exact in circuit. Consequently, $\monadic{v}$ is $q$-exact in circuit. \end{proof} \begin{lemma}\label{semantics:castcoinlemma} Let $q_0=\qualty{t}{s}{d_0}$ and $q_1=\qualty{t}{s}{d_1}$ where $d_1\mathrel{\mathchar"13C\mathchar"3A} d_0$. Let $d$ be any domain. If $\monadic{v}\coin{q_1}{d}\monadic{v}'$ then $\monadic{v}\coin{q_0}{d}\monadic{v}'$. \end{lemma} \begin{proof} Suppose $d_0\mathrel{\mathchar"13C\mathchar"3A} d$. Then also $d_1\mathrel{\mathchar"13C\mathchar"3A} d$. If $t$ is a primitive type then $\monadic{v}\coin{q_1}{d}\monadic{v}'$ implies $\monadic{v}=\uopl{pure} v=\monadic{v}'$ where $v\in t$. Hence $\monadic{v}\coin{q_0}{d}\monadic{v}'$. If $t=\listty{q'}$ then $\monadic{v}\coin{q_1}{d}\monadic{v}'$ implies $\monadic{v}=\uopl{pure}(\monadic{v}_1,\ldots,\monadic{v}_n)$, $\monadic{v}'=\uopl{pure}(\monadic{v}'_1,\ldots,\monadic{v}'_n)$ where $\monadic{v}_i\coin{q'}{d}\monadic{v}'_i$ for every $i=1,\ldots,n$. Consequently, $\monadic{v}\coin{q_0}{d}\monadic{v}'$. If $d_0$ is a strict superdomain of~$d$ then the claim holds vacuously. \end{proof} \begin{lemma}\label{semantics:coinlemma} \begin{enumerate} \item Let $q=(\qualty{t}{s}{d})$ be a qualified type and $P$~be a predicate defined on qualified types. The relation $\coin{q}{P}$ is an equivalence on monadic values that are $q$-exposed in~$P$. \item Let $\Gamma$ be a well-structured type environment and $P$~be a predicate defined on qualified types. The relation $\coin{\Gamma}{P}$ is an equivalence on value environments that are $\Gamma$-exposed in~$P$. \end{enumerate} \end{lemma} \begin{proof} In both parts, we have to establish reflexivity, transitivity and symmetry. \begin{enumerate} \item If $P(q)$ does not hold then all $\monadic{v}\in M\, V$ are $q$-coincident in~$P$, whence all required properties hold. Now assume $P(q)$. We proceed by induction on the structure of the data type~$t$. Let $t$ be a primitive type. For reflexivity, take $\monadic{v}$ which is $q$-exposed in~$P$. Then $\monadic{v}=\uopl{pure} v$ where $v\in t$. As $\monadic{v}=\monadic{v}$, this implies $\monadic{v}\coin{q}{P}\monadic{v}$. For transitivity, assume $\monadic{v}\coin{q}{P}\monadic{v}'$ and $\monadic{v}'\coin{q}{P}\monadic{v}''$. Then $\monadic{v}=\monadic{v}'=\monadic{v}''=\uopl{pure} v$ where $v\in t$. Consequently, $\monadic{v}\coin{q}{P}\monadic{v}''$. For symmetry, assume $\monadic{v}\coin{q}{P}\monadic{v}'$. Then $\monadic{v}=\monadic{v}'=\uopl{pure} v$ where $v\in t$. Consequently, $\monadic{v}'\coin{q}{P}\monadic{v}$. Now let $t=\listty{q'}$ and $q'=(\qualty{t'}{s'}{d'})$. For reflexivity, take $\monadic{v}$ which is $q$-exposed in~$P$. Then $\monadic{v}=\uopl{pure}(\monadic{v}_1,\ldots,\monadic{v}_n)$ where $\monadic{v}_i$ is $q'$-exposed in~$P$ for every $i=1,\ldots,n$. By the induction hypothesis, reflexivity applies to each~$i$ and gives $\monadic{v}_i\coin{q'}{P}\monadic{v}_i$. Hence $\monadic{v}\coin{q}{P}\monadic{v}$. For transitivity, assume $\monadic{v}\coin{q}{P}\monadic{v}'$ and $\monadic{v}'\coin{q}{P}\monadic{v}''$. Then $\monadic{v}=\uopl{pure}(\monadic{v}_1,\ldots,\monadic{v}_n)$, $\monadic{v}'=\uopl{pure}(\monadic{v}'_1,\ldots,\monadic{v}'_n)$, $\monadic{v}''=\uopl{pure}(\monadic{v}''_1,\ldots,\monadic{v}''_n)$, where $\monadic{v}_i\coin{q'}{P}\monadic{v}'_i$ and $\monadic{v}'_i\coin{q'}{P}\monadic{v}''_i$ for every $i=1,\ldots,n$. By the induction hypothesis, transitivity applies to each~$i$ and gives $\monadic{v}_i\coin{q'}{P}\monadic{v}''_i$. Hence $\monadic{v}\coin{q}{P}\monadic{v}''$. For symmetry, assume $\monadic{v}\coin{q}{P}\monadic{v}'$. Then $\monadic{v}=\uopl{pure}(\monadic{v}_1,\ldots,\monadic{v}_n)$, $\monadic{v}'=\uopl{pure}(\monadic{v}'_1,\ldots,\monadic{v}'_n)$ where $\monadic{v}_i\coin{q'}{P}\monadic{v}'_i$ for every $i=1,\ldots,n$. By the induction hypothesis, symmetry applies to each~$i$ and gives $\monadic{v}'_i\coin{q'}{P}\monadic{v}_i$. Hence $\monadic{v}'\coin{q'}{P}\monadic{v}$. \item Let $\uopl{vars}\Gamma=(x_1,\ldots,x_n)$ and the corresponding types be $q_1,\ldots,q_n$. For reflexivity, take $\gamma$ being $\Gamma$-exposed in~$P$. Then $\gamma=((x_1,\monadic{v}_1),\ldots,(x_n,\monadic{v}_n))$ where $\monadic{v}_i$ is $q_i$-exposed for every $i=1,\ldots,n$. By part~(1), $\monadic{v}_i\coin{q_i}{P}\monadic{v}_i$ for every $i=1,\ldots,n$. The desired claim follows. For transitivity, assume $\gamma\coin{\Gamma}{P}\gamma'$ and $\gamma'\coin{\Gamma}{P}\gamma''$. Then we must have $\gamma=((x_1,\monadic{v}_1),\ldots,(x_n,\monadic{v}_n))$, $\gamma'=((x_1,\monadic{v}'_1),\ldots,(x_n,\monadic{v}'_n))$ and $\gamma''=((x_1,\monadic{v}''_1),\ldots,(x_n,\monadic{v}''_n))$ where $\monadic{v}_i\coin{q_i}{P}\monadic{v}'_i$ and $\monadic{v}'_i\coin{q_i}{P}\monadic{v}''_i$ for every $i=1,\ldots,n$. By part~(1), $\monadic{v}_i\coin{q_i}{P}\monadic{v}''_i$ for every $i=1,\ldots,n$. The desired claim follows. For symmetry, assume $\gamma\coin{\Gamma}{P}\gamma'$. Then $\gamma=((x_1,\monadic{v}_1),\ldots,(x_n,\monadic{v}_n))$ and $\gamma'=((x_1,\monadic{v}'_1),\ldots,(x_n,\monadic{v}'_n))$ where $\monadic{v}_i\coin{q_i}{P}\monadic{v}'_i$ for every $i=1,\ldots,n$. By part~(1), $\monadic{v}'_i\coin{q_i}{P}\monadic{v}_i$ for every $i=1,\ldots,n$. The desired claim follows. \end{enumerate} \end{proof} \begin{lemma} Let $\Gamma$ be a well-structured type environment. Let $x$ be a variable occurring in $\uopl{vars}\Gamma$ and let $q=\lookup{\Gamma}{x}$. \begin{thmlist} \item\label{semantics:lookupexposedlemma} Let $P$ be a predicate defined on qualified types. If $\gamma\in\mathbf{Env}$ is $\Gamma$-exposed in~$P$ then $\lookup{\gamma}{x}$ is $q$-exposed in~$P$. \item\label{semantics:lookupexactlemma} Let $P$ be a predicate defined on qualified types. If $\gamma\in\mathbf{Env}$ is $\Gamma$-exact in~$P$ then $\lookup{\gamma}{x}$ is $q$-exact in~$P$. \item\label{semantics:lookupcoinlemma} Let $P$, $Q$ be predicates defined on qualified types such that $Q(q')\Rightarrow P(q')$ for every qualified type~$q'$. Let $\gamma,\gamma'\in\mathbf{Env}$ be $\Gamma$-exact in~$P$ and $Q$, respectively. If $\gamma\coin{\Gamma}{Q}\gamma'$ then $\lookup{\gamma}{x}\coin{q}{Q}\lookup{\gamma'}{x}$. \end{thmlist} \end{lemma} \begin{proof} Let $\uopl{vars}\Gamma=(x_1,\ldots,x_n)$ and the corresponding types be $q_1,\ldots,q_n$. \begin{enumerate} \item Let $\gamma$ be $\Gamma$-exposed in~$P$. Then $\gamma=((x_1,\monadic{v}_1),\ldots,(x_n,\monadic{v}_n))$ where $\monadic{v}_i$ is $q_i$-exposed in~$P$ for every $i=1,\ldots,n$. Let $k$ be the least index such that $x_k=x$. Then $q=\lookup{\Gamma}{x}=q_k$ and $\lookup{\gamma}{x}=\monadic{v}_k$. Hence $\lookup{\gamma}{x}$ is $q$-exposed in~$P$. \item Similar to the proof of Lemma~\ref{semantics:lookupexposedlemma}. \item Let $\gamma,\gamma'\in\mathbf{Env}$ be $\Gamma$-exact in~$P$ and $Q$, respectively, such that $\gamma\coin{\Gamma}{Q}\gamma'$. Then we have $\gamma=((x_1,\monadic{v}_1),\ldots,(x_n,\monadic{v}_n))$ and $\gamma'=((x_1,\monadic{v}'_1),\ldots,(x_n,\monadic{v}'_n))$ where, for every $i=1,\ldots,n$, $\monadic{v}_i$ and $\monadic{v}'_i$ are $q_i$-exact in $P$ and $Q$, respectively, and $\monadic{v}_i\coin{q_i}{Q}\monadic{v}'_i$. Let $k$ be the least index such that $x_k=x$. Then $q=\lookup{\Gamma}{x}=q_k$ and $\lookup{\gamma}{x}=\monadic{v}_k$, $\lookup{\gamma'}{x}=\monadic{v}'_k$. Hence $\lookup{\gamma}{x}\coin{q}{Q}\lookup{\gamma'}{x}$. \end{enumerate} \end{proof} \begin{lemma}\label{semantics:updexactlemma} Let $P$ be any data insensitive predicate defined on qualified types. Let $d_1,\ldots,d_n$ be domains and $q$ be a qualified type. Moreover, let $q_k=(\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_k})$ for every $k=1,\ldots,n$ and $q'=(\qualty{\listty{\ldots\listty{\qualty{\listty{\qualty{\listty{q}}{\mbox{\lstinline+$pre+}}{d_n}}}{\mbox{\lstinline+$pre+}}{d_{n-1}}}\ldots}}{\mbox{\lstinline+$pre+}}{d_1})$. Assume $\monadic{a}$ being $q'$-exact in~$P$, let $\monadic{i}_k$ be $q_k$-exact in~$P$ for every $k=1,\ldots,n$, and let $\monadic{v}$ be $q$-exact in~$P$. Then $\uopl{upd}(\monadic{a},\monadic{i}_1\ldots\monadic{i}_n,\monadic{v})$ (assuming that it is well defined) is $q'$-exact in~$P$. \end{lemma} \begin{proof} We proceed by induction on~$n$. If $n=0$ then $q'=q$ and $\uopl{upd}(\monadic{a},\monadic{i}_1\ldots\monadic{i}_n,\monadic{v})=\monadic{v}$ which is $q$-exact in~$P$ by assumption. Let now $n>0$ and assume that the claim holds for $n-1$. Denoting $q'_1=(\qualty{\listty{\ldots\listty{\qualty{\listty{\qualty{\listty{q}}{\mbox{\lstinline+$pre+}}{d_n}}}{\mbox{\lstinline+$pre+}}{d_{n-1}}}\ldots}}{\mbox{\lstinline+$pre+}}{d_2})$, consider two cases: \begin{itemize} \item If $P(q')$ is true then, by data insensitivity, also $P(q_1)$ holds. By exactness, $\monadic{a}=\uopl{pure}(\monadic{a}_1,\ldots,\monadic{a}_{l_1})$ where all $\monadic{a}_k$ ($k=1,\ldots,l_1$) are $q'_1$-exact in~$P$, and also $\monadic{i}_1=\uopl{pure} i_1$ with $i_1\in\mathbb{N}$. As $\uopl{upd}(\monadic{a},\monadic{i}_1\ldots\monadic{i}_n,\monadic{v})$ is well-defined, $i_1\leq l_1$. Now $\uopl{upd}(\monadic{a}_{i_1},\monadic{i}_2\ldots\monadic{i}_n,\monadic{v})$ is $q'_1$-exact in~$P$ by the induction hypothesis. Hence also $\uopl{pure}(\monadic{a}_1,\ldots,\monadic{a}_{i_1-1},\uopl{upd}(\monadic{a}_{i_1},\monadic{i}_2\ldots\monadic{i}_n,\monadic{v}),\monadic{a}_{i_1+1},\ldots,\monadic{a}_{l_1})$ must be $q'$-exact in~$P$. The desired claim follows. \item If $P(q')$ does not hold then, by exactness, $\monadic{a}=\top$. Hence $\uopl{upd}(\monadic{a},\monadic{i}_1\ldots\monadic{i}_n,\monadic{v})=\top$ which is $q'$-exact in~$P$. \end{itemize} \end{proof} \begin{lemma}\label{semantics:updcoin0lemma} Let $P,Q$ be data insensitive predicates defined on qualified types such that $Q(q'')\Rightarrow P(q'')$ for every qualified type $q''$. Let $d_1,\ldots,d_n$ be domains and $q$ be a qualified type such that $Q(q)$ does not hold. Denote $q'=(\qualty{\listty{\ldots\listty{\qualty{\listty{\qualty{\listty{q}}{\mbox{\lstinline+$pre+}}{d_n}}}{\mbox{\lstinline+$pre+}}{d_{n-1}}}\ldots}}{\mbox{\lstinline+$pre+}}{d_1})$ and $q_k=(\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_k})$ for every $k=1,\ldots,n$. Let $\monadic{a}$ be $q'$-exposed in~$P$, let $\monadic{i}_k$ be $q_k$-exposed in~$P$ for every $k=1,\ldots,n$ and let $\monadic{v}$ be $q$-exposed in~$P$. Then $\monadic{a}\coin{q'}{Q}\uopl{upd}(\monadic{a},\monadic{i}_1\ldots\monadic{i}_n,\monadic{v})$ (provided that the right-hand side is well-defined). \end{lemma} \begin{proof} We proceed by induction on~$n$. If $n=0$ then $\uopl{upd}(\monadic{a},\monadic{i}_1\ldots\monadic{i}_n,\monadic{v})=\monadic{v}$ and $q'=q$. By Definition~\ref{semantics:coincidentdef}, $\monadic{a}\coin{q}{Q}\monadic{v}$ since $Q(q)$ is false. Now suppose that $n>0$ and the claim holds for $n-1$. Denoting $q'_1=(\qualty{\listty{\ldots\listty{\qualty{\listty{\qualty{\listty{q}}{\mbox{\lstinline+$pre+}}{d_n}}}{\mbox{\lstinline+$pre+}}{d_{n-1}}}\ldots}}{\mbox{\lstinline+$pre+}}{d_2})$, consider two cases: \begin{itemize} \item If $P(q')$ holds then, by data insensitivity, also $P(q_1)$ is true. We have $\monadic{a}=\uopl{pure}(\monadic{a}_1,\ldots,\monadic{a}_{l_1})$ and $\monadic{i}_1=\uopl{pure} i_1$ where all $\monadic{a}_k$ are $q'_1$-exposed and $l_1,i_1\in\mathbb{N}$ (and, by $\uopl{upd}(\monadic{a},\monadic{i_1}\ldots\monadic{i}_n,\monadic{v})$ being well-defined, $i_1\leq l_1$). Hence \[ \uopl{upd}(\monadic{a},\monadic{i}_1\ldots\monadic{i}_n,\monadic{v})=\uopl{pure}(\monadic{a}_1,\ldots,\monadic{a}_{i_1-1},\uopl{upd}(\monadic{a}_{i_1},\monadic{i}_2\ldots\monadic{i}_n,\monadic{v}),\monadic{a}_{i_1+1},\ldots,\monadic{a}_{l_1})\mbox{.} \] For every $k=1,\ldots,l_1$ except~$k=i_1$, the $k$th component of $\monadic{a}$ and that of $\uopl{upd}(\monadic{a},\monadic{i}_1\ldots\monadic{i}_n,\monadic{v})$ are equal. By the induction hypothesis, $\monadic{a}_{i_1}\coin{q'_1}{Q}\uopl{upd}(\monadic{a}_{i_1},\monadic{i}_2\ldots\monadic{i}_n,\monadic{v})$. Consequently, we obtain $\monadic{a}\coin{q'}{Q}\uopl{upd}(\monadic{a},\monadic{i}_1\ldots\monadic{i}_n,\monadic{v})$. \item If $P(q')$ does not hold then $Q(q')$ does not hold either. Therefore $\monadic{a}\coin{q'}{Q}\uopl{upd}(\monadic{a},\monadic{i}_1\ldots\monadic{i}_n,\monadic{v})$ by clause~3 of Definition~\ref{semantics:coincidentdef}. \end{itemize} \end{proof} \begin{lemma}\label{semantics:updexactcoinlemma} Let $P,Q$ be data insensitive predicates defined on qualified types such that $Q(q'')\Rightarrow P(q'')$ for every qualified type $q''$. Let $d_1,\ldots,d_n$ be domains and $q$ be a qualified type. Denote $q_k=(\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_k})$ for every $k=1,\ldots,n$ and $q'=(\qualty{\listty{\ldots\listty{\qualty{\listty{\qualty{\listty{q}}{\mbox{\lstinline+$pre+}}{d_n}}}{\mbox{\lstinline+$pre+}}{d_{n-1}}}\ldots}}{\mbox{\lstinline+$pre+}}{d_1})$. Let $\monadic{a}_P,\monadic{a}_Q$ be $q'$-exact in $P$ and $Q$, respectively; for all $k=1,\ldots,n$, let $\monadic{i}_P^k,\monadic{i}_Q^k$ be $q_k$-exact in $P$ and $Q$, respectively; let $\monadic{v}_P,\monadic{v}_Q$ be $q$-exact in $P$ and $Q$, respectively. Moreover, assume that $\monadic{a}_P\coin{q'}{Q}\monadic{a}_Q$, for every $k=1,\ldots,n$ we have $\monadic{i}_P^k\coin{q_k}{Q}\monadic{i}_Q^k$, and $\monadic{v}_P\coin{q}{Q}\monadic{v}_Q$. If $\uopl{upd}(\monadic{a}_P,\monadic{i}_P^1\ldots\monadic{i}_P^n,\monadic{v}_P)$ is well-defined then $\uopl{upd}(\monadic{a}_Q,\monadic{i}_Q^1\ldots\monadic{i}_Q^n,\monadic{v}_Q)$ is well-defined, too, whereby $\uopl{upd}(\monadic{a}_P,\monadic{i}_P^1\ldots\monadic{i}_P^n,\monadic{v}_P)\coin{q'}{Q}\uopl{upd}(\monadic{a}_Q,\monadic{i}_Q^1\ldots\monadic{i}_Q^n,\monadic{v}_Q)$. \end{lemma} \begin{proof} We proceed by induction on~$n$. If $n=0$ then $q'=q$, whereby $\uopl{upd}(\monadic{a}_P,\monadic{i}_P^1\ldots\monadic{i}_P^n,\monadic{v}_P)=\monadic{v}_P$ and $\uopl{upd}(\monadic{a}_Q,\monadic{i}_Q^1\ldots\monadic{i}_Q^n,\monadic{v}_Q)=\monadic{v}_Q$. By assumption, $\monadic{v}_P\coin{q}{Q}\monadic{v}_Q$. Let now $n>0$ and assume that the claim holds for $n-1$. Denoting $q'_1=(\qualty{\listty{\ldots\listty{\qualty{\listty{\qualty{\listty{q}}{\mbox{\lstinline+$pre+}}{d_n}}}{\mbox{\lstinline+$pre+}}{d_{n-1}}}\ldots}}{\mbox{\lstinline+$pre+}}{d_2})$, consider two cases: \begin{itemize} \item If $Q(q')$ holds then also $P(q')$ holds. By data insensitivity, $Q(q_1)$ and $P(q_1)$ are true, too. Hence $\monadic{a}_P\coin{q'}{Q}\monadic{a}_Q$ implies $\monadic{a}_P=\uopl{pure}(\monadic{a}_P^1,\ldots,\monadic{a}_P^{l_1})$, $\monadic{a}_Q=\uopl{pure}(\monadic{a}_Q^1,\ldots,\monadic{a}_Q^{l_1})$ where $\monadic{a}_P^k\coin{q'_1}{Q}\monadic{a}_Q^k$ for every $k=1,\ldots,n$ and $\monadic{i}_P^1\coin{q_1}{Q}\monadic{i}_Q^1$ implies $\monadic{i}_P^1=\monadic{i}_Q^1=\uopl{pure} i_1$ with $i_1\in\mathbb{N}$. By the induction hypothesis, $\uopl{upd}(\monadic{a}_Q^{i_1},\monadic{i}_Q^2\ldots\monadic{i}_Q^n,\monadic{v}_Q)$ is well-defined and $\uopl{upd}(\monadic{a}_P^{i_1},\monadic{i}_P^2\ldots\monadic{i}_P^n,\monadic{v}_P)\coin{q'_1}{Q}\uopl{upd}(\monadic{a}_Q^{i_1},\monadic{i}_Q^2\ldots\monadic{i}_Q^n,\monadic{v}_Q)$. As $\uopl{upd}(\monadic{a}_P,\monadic{i}_P^1\ldots\monadic{i}_P^n,\monadic{v}_P)$ is well-defined, $i_1\leq l_1$. All this implies that $\uopl{upd}(\monadic{a}_Q,\monadic{i}_Q^1\ldots\monadic{i}_Q^n,\monadic{v}_Q)$ is also well-defined and, since \[ \begin{array}{l} \uopl{upd}(\monadic{a}_P,\monadic{i}_P^1\ldots\monadic{i}_P^n,\monadic{v}_P)=\uopl{pure}(\monadic{a}_P^1,\ldots,\monadic{a}_P^{i_1-1},\uopl{upd}(\monadic{a}_P^{i_1},\monadic{i}_P^2\ldots\monadic{i}_P^n,\monadic{v}_P),\monadic{a}_P^{i_1+1},\ldots,\monadic{a}_P^{l_1})\mbox{,}\\ \uopl{upd}(\monadic{a}_Q,\monadic{i}_Q^1\ldots\monadic{i}_Q^n,\monadic{v}_Q)=\uopl{pure}(\monadic{a}_Q^1,\ldots,\monadic{a}_Q^{i_1-1},\uopl{upd}(\monadic{a}_Q^{i_1},\monadic{i}_Q^2\ldots\monadic{i}_Q^n,\monadic{v}_Q),\monadic{a}_Q^{i_1+1},\ldots,\monadic{a}_Q^{l_1})\mbox{,} \end{array} \] we obtain $\uopl{upd}(\monadic{a}_P,\monadic{i}_P^1\ldots\monadic{i}_P^n,\monadic{v}_P)\coin{q'}{Q}\uopl{upd}(\monadic{a}_Q,\monadic{i}_Q^1\ldots\monadic{i}_Q^n,\monadic{v}_Q)$ as desired. \item Assume that $Q(q')$ is false. By assumption, $\monadic{a}_Q$ is $q'$-exact in~$Q$, whence $\monadic{a}_Q=\top$. Hence also $\uopl{upd}(\monadic{a}_Q,\monadic{i}_Q^1\ldots\monadic{i}_Q^n,\monadic{v}_Q)=\top$ which is well-defined. The claim $\uopl{upd}(\monadic{a}_P,\monadic{i}_P^1\ldots\monadic{i}_P^n,\monadic{v}_P)\coin{q'}{Q}\top$ holds vacuously. \end{itemize} \end{proof} \begin{lemma}\label{semantics:outputlemma} Let $d$ be any domain and let $\omicron,\omicron'\in\mathbf{Out}^2$ be both exact in~$d$. Then the pointwise concatenation $\omicron\omicron'$ is exact in~$d$. \end{lemma} \begin{proof} Trivial. \end{proof} \begin{lemma}\label{semantics:outputcoinlemma} Let $d,d'$ be domains such that $d'\mathrel{\mathchar"13C\mathchar"3A} d$ and let $\omicron_1,\omicron_2,\omicron'_1,\omicron'_2\in\mathbf{Out}^2$ such that $\omicron_1\coinpure{d'}\omicron'_1$ and $\omicron_2\coinpure{d'}\omicron'_2$. Then $\omicron_1\omicron_2\coinpure{d'}\omicron'_1\omicron'_2$. \end{lemma} \begin{proof} Trivial. \end{proof} \begin{theorem}[Theorem~\ref{semantics:localthm}] Let $\Gamma \mbox{\ $\vdash$\ } e : q! D$ with well-structured~$\Gamma$ and $\gamma\in\mathbf{Env}$ be $\Gamma$-exact in~$d$ for some domain~$d$. Assume that for all subexpressions of~$e$ of the form $\ofty{\getexpr{d'}{k}}{q'}$ where $d'\mathrel{\mathchar"13C\mathchar"3A} d$, the value $\uopl{allpure}(\phi_{d'}(k))$ is $q'$-exact in~$d$. If $\semd{e}\gamma\phi=\uopl{pure}(\monadic{v},\gamma',\omicron)$ then $\monadic{v}$~{}is $q$-exact, $\gamma'$~{}is $\Gamma$-exact and $\omicron$~{}is exact in~$d$. \end{theorem} \begin{proof} Let $q=t_0\ s_0\ d_0$. We proceed by induction on the structure of~$e$: \begin{itemize} \item Let $e=\epsilon$. Then $t_0=\mbox{\lstinline+()+}$, $d_0=\mbox{\lstinline+@public+}$ and we have $\monadic{v}=\uopl{pure}\mbox{\textoneoldstyle}$, $\gamma'=\gamma$, $\omicron=\epsilon$. As $d_0\mathrel{\mathchar"13C\mathchar"3A} d$ and $t_0$ is primitive, establishing that $\monadic{v}$ is $q$-exact in~$d$ reduces to clause~1 of Definition~\ref{semantics:exactdef}. It holds since $\mbox{\textoneoldstyle}\in\mbox{\lstinline+()+}$. The environment~$\gamma'$ is $\Gamma$-exact in~$d$ by assumption and the output~$\epsilon$ is exact in~$d$ trivially. \item Let $e=\overline{n}$ where $n\in\mathbb{N}$. Then $t_0=\uintmodty{\mbox{\lstinline+N+}}$, $\gamma'=\gamma$, $\omicron=\epsilon$. We have to study two cases: \begin{itemize} \item If $d_0\mathrel{\mathchar"13C\mathchar"3A} d$ then $\monadic{v}=\uopl{pure} n$. As $t_0$ is primitive, establishing that $\monadic{v}$ is $q$-exact in~$d$ reduces to clause~1 of Definition~\ref{semantics:exactdef}. It holds since $n$ is an integer. \item If $d_0$ is a strict superdomain of~$d$ then $\monadic{v}=\top$ and establishing that $\monadic{v}$ is $q$-exact in~$d$ reduces to clause~3 of Definition~\ref{semantics:exactdef}. The former equality is exactly what clause~3 requires. \end{itemize} The environment~$\gamma'$ is $\Gamma$-exact in~$d$ by assumption and the output~$\epsilon$ is exact in~$d$ trivially. \item Let $e=\overline{b}$ where $b\in\mathbb{B}$. This case is analogous to the previous one. \item Let $e=x$. Then $\lookup{\Gamma}{x}=q$ and $\monadic{v}=\lookup{\gamma}{x}$, $\gamma'=\gamma$, $\omicron=\epsilon$. Hence $\monadic{v}$ is $q$-exact in~$d$ by the assumption that $\gamma$ is $\Gamma$-exact in~$d$ and Lemma~\ref{semantics:lookupexactlemma}. Also $\gamma'$ being $\Gamma$-exact in~$d$ directly follows from assumption and the output~$\epsilon$ is exact in~$d$ trivially. \item Let $e=\addexpr{e_1}{e_2}$. Then $t_0=\uintmodty{\mbox{\lstinline+N+}}$ and \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:q! D_1\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:q! D_2\mbox{,} \end{array} \] and also \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_1\phi=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{,}\\ \monadic{v}=\mcomp{v_1\gets\monadic{v}_1;\; v_2\gets\monadic{v}_2;\;\uopl{pure}(v_1+v_2)},\quad\gamma'=\gamma_2\mbox{,}\quad\omicron=\omicron_1\omicron_2\mbox{.} \end{array} \] By the induction hypothesis about~$e_1$, $\monadic{v}_1$ is $q$-exact, $\gamma_1$ is $\Gamma$-exact and $\omicron_1$ is exact in~$d$. Now by the induction hypothesis about~$e_2$, $\monadic{v}_2$ is $q$-exact, $\gamma_2$ is $\Gamma$-exact and $\omicron_2$ is exact in~$d$. Finally, we have to consider two cases: \begin{itemize} \item If $d_0\mathrel{\mathchar"13C\mathchar"3A} d$ then, by $\monadic{v}_1$ and $\monadic{v}_2$ being $q$-exact in~$d$, we have $\monadic{v}_1=\uopl{pure} v_1$ and $\monadic{v}_2=\uopl{pure} v_2$ for integers $v_1,v_2$. Hence $\monadic{v}=\uopl{pure}(v_1+v_2)$ which shows that $\monadic{v}$ is $q$-exact in~$d$ by clause~1 of Definition~\ref{semantics:exactdef}. \item If $d_0$ is a strict superdomain of~$d$ then, by $\monadic{v}_1$ and $\monadic{v}_2$ being $q$-exact in~$d$, we have $\monadic{v}_1=\monadic{v}_2=\top$ and hence also $\monadic{v}=\top$. By clause~3 of Definition~\ref{semantics:exactdef}, $\monadic{v}$ is $q$-exact in~$d$. \end{itemize} The desired exactness claim about~$\gamma'$ holds by the above and $\omicron$ is exact in~$d$ by Lemma~\ref{semantics:outputlemma}. \item Let $e=\assertexpr{e_1}$. Then $t_0=\mbox{\lstinline+()+}$, $d_0=\mbox{\lstinline+@public+}$ and \[ \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{\boolmodty{\mbox{\lstinline+N+}}}{\mbox{\lstinline+$post+}}{d_1}! D \] and also \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \monadic{v}_1\ne\uopl{pure}\mbox{\bfseries ff}\mbox{,}\quad\monadic{v}=\uopl{pure}\mbox{\textoneoldstyle}\mbox{,}\quad\gamma'=\gamma_1\mbox{,}\quad\omicron=\omicron_1\mbox{.} \end{array} \] As $d_0\mathrel{\mathchar"13C\mathchar"3A} d$ and $t_0$ is primitive, establishing that $\monadic{v}$ is $q$-exact in~$d$ reduces to clause~1 of Definition~\ref{semantics:exactdef} which holds as $\mbox{\textoneoldstyle}\in\mbox{\lstinline+()+}$. By the induction hypothesis about~$e_1$, $\gamma_1$ is $\Gamma$-exact and $\omicron_1$ is exact in~$d$ which establish the desired exactness claims about~$\gamma'$ and $\omicron$. \item Let $e=\ofty{\getexpr{d''}{k}}{q}$. Then $\uopl{allpre}_{d''}(q)$, implying $d_0=d''$. Moreover, $\gamma'=\gamma$, whence $\gamma'$ is $\Gamma$-exact in~$d$ by assumption. The output $\epsilon$ is exact in~$d$ trivially. For the remaining desired exactness claim, consider two cases: \begin{itemize} \item If $d''\mathrel{\mathchar"13C\mathchar"3A} d$ then $\monadic{v}=\uopl{allpure}(\phi_{d''}(k))$ which is $q$-exact in~$d$ by assumption of the theorem. \item If $d''$ is a strict superdomain of~$d$ then $\monadic{v}=\top$ and establishing that $\monadic{v}$ is $q$-exact in~$d$ reduces to clause~3 of Definition~\ref{semantics:exactdef}. The former equality is exactly what clause~3 requires. \end{itemize} \item Let $e=\ifexpr{e_1}{e_2}{e_3}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{\boolmodty{\mbox{\lstinline+N+}}}{\mbox{\lstinline+$pre+}}{d_1}! D_1\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:q! D_2\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_3:q! D_3\mbox{,}\\ \gen{d_1}\supseteq\gen{s_0}\cup \gen{d_0}\cup D_2\cup D_3\mbox{,} \end{array} \] and \[ \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{.} \] By the induction hypothesis about $e_1$, $\monadic{v}_1$ is $(\qualty{\boolmodty{\mbox{\lstinline+N+}}}{\mbox{\lstinline+$pre+}}{d_1})$-exact, $\gamma_1$ is $\Gamma$-exact and $\omicron_1$ is exact in~$d$. We have to consider three cases: \begin{itemize} \item If $\monadic{v}_1=\uopl{pure}\mbox{\bfseries tt}$ then $\semd{e_2}\gamma_1\phi=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)$, $\monadic{v}=\monadic{v}_2$, $\gamma'=\gamma_2$, $\omicron=\omicron_1\omicron_2$. By the induction hypothesis about $e_2$, $\monadic{v}_2$ is $q$-exact, $\gamma_2$ is $\Gamma$-exact and $\omicron_2$ is exact in~$d$. Hence the desired claim follows. \item If $\monadic{v}_1=\uopl{pure}\mbox{\bfseries ff}$ then $\semd{e_3}\gamma_1\phi=\uopl{pure}(\monadic{v}_3,\gamma_3,\omicron_3)$, $\monadic{v}=\monadic{v}_3$, $\gamma'=\gamma_3$, $\omicron=\omicron_1\omicron_3$. By the induction hypothesis about $e_3$, $\monadic{v}_3$ is $q$-exact, $\gamma_3$ is $\Gamma$-exact and $\omicron_3$ is exact in~$d$. Hence the desired claim follows. \item If $\monadic{v}_1\ne\uopl{pure} b$ for $b\not\in\mathbb{B}$ then $\monadic{v}=\top$, $\gamma'=\gamma_1$, $\omicron=\omicron_1$. As $\monadic{v}_1$ is $(\qualty{\boolmodty{\mbox{\lstinline+N+}}}{\mbox{\lstinline+$pre+}}{d_1})$-exact in~$d$, the only possibility is $\monadic{v}_1=\top$, whereby $d_1$ has to be a strict superdomain of~$d$. But $\gen{d_1}\supseteq\gen{d_0}$ implies $d_1\mathrel{\mathchar"13C\mathchar"3A} d_0$, meaning that also $d_0$ must be a strict superdomain of~$d$. Hence by clause~3 of Definition~\ref{semantics:exactdef}, $\top$ is $q$-exact in~$d$. The desired claim follows. \end{itemize} \item Let $e=\forexpr{x}{e_1}{e_2}{e_3}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0}! D_1\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0}! D_2\mbox{,}\\ (x:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0}),\Gamma\mbox{\ $\vdash$\ } e_3:\qualty{t_1}{s_1}{d_1}! D_3\mbox{,}\\ \gen{d_0}\supseteq\gen{s_1}\cup\gen{d_1}\cup D_3\mbox{,}\\ t_0=\listty{\qualty{t_1}{s_1}{d_1}}\mbox{,}\quad s_0=\mbox{\lstinline+$pre+}\mbox{,} \end{array} \] and \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_1\phi=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{.} \end{array} \] By the induction hypothesis about~$e_1$, $\monadic{v}_1$ is $(\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0})$-exact, $\gamma_1$ is $\Gamma$-exact and $\omicron_1$ is exact in~$d$. Now by the induction hypothesis about~$e_2$, $\monadic{v}_2$ is $(\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0})$-exact, $\gamma_2$ is $\Gamma$-exact and $\omicron_2$ is exact in~$d$. We have to consider two cases: \begin{itemize} \item If $\monadic{v}_1=\uopl{pure} i_1$, $\monadic{v}_2=\uopl{pure} i_2$ then, by exactness, $i_1,i_2\in\mathbb{N}$. Denoting $n=\max(0,i_2-i_1)$, \[ \begin{array}{l} \semd{e_3}((x,\uopl{pure} i_1),\gamma_2)\phi=\uopl{pure}(\monadic{v}_3,\gamma_3,\omicron_3)\mbox{,}\\ \semd{e_3}([x\mapsto\uopl{pure}(i_1+1)]\gamma_3)\phi=\uopl{pure}(\monadic{v}_4,\gamma_4,\omicron_4)\mbox{,}\\ \dotfill\\ \semd{e_3}([x\mapsto\uopl{pure}(i_1+n-1)]\gamma_{n+1})\phi=\uopl{pure}(\monadic{v}_{n+2},\gamma_{n+2},\omicron_{n+2})\mbox{,}\\ \monadic{v}=\uopl{pure}(\monadic{v}_3,\ldots,\monadic{v}_{n+2})\mbox{,}\quad\gamma'=\uopl{tail}\gamma_{n+2}\mbox{,}\quad\omicron=\omicron_1\ldots\omicron_{n+2}\mbox{.} \end{array} \] As $\gamma_2$ is $\Gamma$-exact and $\uopl{pure} i_1$ is $(\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0})$-exact in~$d$, the updated environment $(x,\uopl{pure} i_1),\gamma_2$ is $((x:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0}),\Gamma)$-exact in~$d$. Hence the induction hypothesis about $e_3$ applies and gives $\monadic{v}_3$ being $(\qualty{t_1}{s_1}{d_1})$-exact, $\gamma_3$ being $((x:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0}),\Gamma)$-exact and $\omicron_3$ being exact in~$d$. Replacing $i_1$ by $i_1+1$ does not violate exactness, so $[x\mapsto\uopl{pure}(i_1+1)]\gamma_3$ is also $((x:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0}),\Gamma)$-exact in~$d$. Hence the induction hypothesis about $e_3$ applies and gives $\monadic{v}_4$ being $(\qualty{t_1}{s_1}{d_1})$-exact, $\gamma_4$ being $((x:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0}),\Gamma)$-exact and $\omicron_4$ being exact in~$d$. Analogously we obtain $\monadic{v}_k$ being $(\qualty{t_1}{s_1}{d_1})$-exact and $\omicron_k$ being exact for all $k=3,4,\ldots,n+2$, as well as $\gamma_{n+2}$ being $((x:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0}),\Gamma)$-exact in~$d$. Obviously the latter implies $\uopl{tail}\gamma_{n+2}$ being $\Gamma$-exact in~$d$. By clause~2 of Definition~\ref{semantics:exactdef}, $\uopl{pure}(\monadic{v}_3,\ldots,\monadic{v}_{n+2})$ is $(\qualty{\listty{\qualty{t_1}{s_1}{d_1}}}{\mbox{\lstinline+$pre+}}{d_0})$-exact in~$d$. The desired claim follows. \item If $\monadic{v}_1=\top$ or $\monadic{v}_2=\top$ then $\monadic{v}=\top$, $\gamma'=\gamma_2$, $\omicron=\omicron_1\omicron_2$ and, by exactness, $d_0$ is a strict supertype of~$d$. Hence $\top$ is also $q$-exact in~$d$ by clause~3 of Definition~\ref{semantics:exactdef}. The desired claim follows. \end{itemize} \item Let $e=\wireexpr{e_1}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{t_0}{\mbox{\lstinline+$pre+}}{d_0}! D_1\mbox{,}\\ s_0=\mbox{\lstinline+$post+}\mbox{,}\quad\mbox{$t_0$ is $\uintmodty{\mbox{\lstinline+N+}}$ or $\boolmodty{\mbox{\lstinline+N+}}$}\mbox{,} \end{array} \] and \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \monadic{v}=\monadic{v}_1\mbox{,}\quad\gamma'=\gamma_1\mbox{,}\quad\omicron=\lam{d'}{\branching{(\omicron_1)_{d'}\monadic{v}_1&\mbox{if $d'=d_0$}\\(\omicron_1)_{d'}&\mbox{otherwise}}}\mbox{.} \end{array} \] By the induction hypothesis about~$e_1$, $\monadic{v}_1$ is $(\qualty{t_0}{\mbox{\lstinline+$pre+}}{d_0})$-exact, $\gamma_1$ is $\Gamma$-exact and $\omicron_1$ is exact in~$d$. Then $\monadic{v}_1$ is also $(\qualty{t_0}{\mbox{\lstinline+$post+}}{d_0})$-exact in~$d$. As $t_0$ is $\uintmodty{\mbox{\lstinline+N+}}$ or $\boolmodty{\mbox{\lstinline+N+}}$, $\monadic{v}_1=\uopl{pure} v_1$ for some $v_1\in\mathbb{N}\cup\mathbb{B}$ if $d_0\mathrel{\mathchar"13C\mathchar"3A} d$ and $\monadic{v}_1=\top$ if $d_0$ is a strict superdomain of~$d$. As $\monadic{v}_1$ is concatenated to $(\omicron_1)_{d_0}$, the component corresponding to~$d_0$ of $\omicron$ contains only pure values if $d_0\mathrel{\mathchar"13C\mathchar"3A} d$ and only tops if $d_0$ is a strict superdomain of~$d$. Thus $\omicron$ is exact in~$d$. The desired claim follows. \item Let $e=\castexpr{e_1}{d_0}$. Let the domain of $e_1$ be $d_1$, i.e., \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{t_0}{s_0}{d_1}! D\mbox{,}\\ d_1\mathrel{\mathchar"13C\mathchar"3A} d_0\mbox{,}\quad\gen{d_0}\supseteq\gen{t_0}\mbox{.} \end{array} \] We have \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \monadic{v}=\branching{\monadic{v}_1&\mbox{if $d_0\mathrel{\mathchar"13C\mathchar"3A} d$}\\\top&\mbox{otherwise}}\mbox{,}\quad\gamma'=\gamma_1\mbox{,}\quad\omicron=\omicron_1\mbox{.} \end{array} \] By the induction hypothesis, $\monadic{v}_1$ is $(\qualty{t_0}{s_0}{d_1})$-exact and $\gamma_1$ is $\Gamma$-exact in~$d$. Consider two cases: \begin{itemize} \item If $d_0\mathrel{\mathchar"13C\mathchar"3A} d$ then $\monadic{v}=\monadic{v}_1$. As $d_1\mathrel{\mathchar"13C\mathchar"3A} d_0$, we also have $d_1\mathrel{\mathchar"13C\mathchar"3A} d$. Hence $\monadic{v}_1$ being $(\qualty{t_0}{s_0}{d_1})$-exact in~$d$ implies $\monadic{v}_1$ being $(\qualty{t_0}{s_0}{d_0})$-exact in~$d$. The desired claim follows. \item If $d_0$ is a strict supertype of~$d$ then $\monadic{v}=\top$. The desired claim follows as $\top$ is $(\qualty{t_0}{s_0}{d_0})$-exact in~$d$. \end{itemize} \item Let $e=(\assignexpr{e_1}{e_2})$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{t_1}{s_1}{d_1}\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:\qualty{t_1}{s_1}{d_1}\mbox{,}\\ t_0=\mbox{\lstinline+()+}\mbox{,}\quad s_0=\mbox{\lstinline+$pre+}\mbox{,}\quad d_0=\mbox{\lstinline+@public+}\mbox{.} \end{array} \] Let $e_1=\loadexpr{\loadexpr{\loadexpr{x}{y_1}}{y_2}\ldots}{y_n}$ and denote $\monadic{a}=\lookup{\gamma}{x}$; then \[ \begin{array}{l} \semd{y_1}\gamma\phi=\uopl{pure}(\monadic{i}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{y_2}\gamma_1\phi=\uopl{pure}(\monadic{i}_2,\gamma_2,\omicron_2)\mbox{,}\\ \dotfill\\ \semd{y_n}\gamma_{n-1}\phi=\uopl{pure}(\monadic{i}_n,\gamma_n,\omicron_n)\mbox{,}\\ \semd{e_2}\gamma_n\phi=\uopl{pure}(\monadic{v}_1,\gamma_{n+1},\omicron_{n+1})\mbox{,}\\ \monadic{v}=\uopl{pure}\mbox{\textoneoldstyle}\mbox{,}\quad\gamma'=[x\mapsto\uopl{upd}(\monadic{a},\monadic{i}_1\ldots\monadic{i}_n,\monadic{v}_1)]\gamma_{n+1}\mbox{,}\quad\omicron=\omicron_1\ldots\omicron_{n+1}\mbox{.} \end{array} \] By Lemma~\ref{typesystem:lhslemma}, $\Gamma\mbox{\ $\vdash$\ } y_i:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d'_i}$ for each $i=1,\ldots,n$ and \[ \Gamma\mbox{\ $\vdash$\ } x:\qualty{\listty{\ldots\listty{\qualty{\listty{\qualty{\listty{\qualty{t'}{s'}{d'_{n+1}}}}{\mbox{\lstinline+$pre+}}{d'_n}}}{\mbox{\lstinline+$pre+}}{d'_{n-1}}}\ldots}}{\mbox{\lstinline+$pre+}}{d'_1}\mbox{.} \] Hence $\monadic{a}$ is $(\qualty{\listty{\ldots\listty{\qualty{\listty{\qualty{\listty{\qualty{t'}{s'}{d'_{n+1}}}}{\mbox{\lstinline+$pre+}}{d'_n}}}{\mbox{\lstinline+$pre+}}{d'_{n-1}}}\ldots}}{\mbox{\lstinline+$pre+}}{d'_1})$-exact in~$d$ by exactness of~$\gamma$. By the induction hypothesis about~$y_1$, $\monadic{i}_1$ is $(\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d'_1})$-exact, $\gamma_1$ is $\Gamma$-exact and $\omicron_1$~{}is exact in~$d$. Now by the induction hypothesis about~$y_2$, $\monadic{i}_2$ is $(\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d'_2})$-exact, $\gamma_2$ is $\Gamma$-exact and $\omicron_2$ is exact in~$d$. Similarly, we obtain that, for each $i=1,2,\ldots,n$, $y_i$ is $(\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d'_i})$-exact, $\gamma_i$ is $\Gamma$-exact and $\omicron_k$ is exact in~$d$. The induction hypothesis about~$e_2$ implies that $\monadic{v}_1$ is $(\qualty{t_1}{s_1}{d_1})$-exact, $\gamma_{n+1}$ is $\Gamma$-exact and $\omicron_{n+1}$ is exact in~$d$. Now $\uopl{upd}(\monadic{a},\monadic{i}_1\ldots\monadic{i}_n,\monadic{v}_1)$ is $(\qualty{\listty{\ldots\listty{\qualty{\listty{\qualty{\listty{\qualty{t'}{s'}{d'_{n+1}}}}{\mbox{\lstinline+$pre+}}{d'_n}}}{\mbox{\lstinline+$pre+}}{d'_{n-1}}}\ldots}}{\mbox{\lstinline+$pre+}}{d'_1})$-exact in~$d$ by Lemma~\ref{semantics:updexactlemma}. Hence $[x\mapsto\uopl{upd}(\monadic{a},\monadic{i}_1\ldots\monadic{i}_n,\monadic{v}_1)]\gamma_{n+1}$ is $\Gamma$-exact in~$d$. As $\uopl{pure}\mbox{\textoneoldstyle}$ is $(\qualty{\mbox{\lstinline+()+}}{\mbox{\lstinline+$pre+}}{\mbox{\lstinline+@public+}})$-exact in~$d$, we are done. \item Let $e=\loadexpr{e_1}{e_2}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{\listty{q}}{s_1}{d_1}\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:\qualty{\mbox{\lstinline+uint+}}{s_1}{d_1}\mbox{,} \end{array} \] and \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{a},\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_1\phi=\uopl{pure}(\monadic{i},\gamma_2,\omicron_2)\mbox{,}\\ \monadic{v}=\mcomp{a\gets\monadic{a};\; i\gets\monadic{i};\; a_i}\mbox{,}\quad\gamma'=\gamma_2\mbox{,}\quad\omicron=\omicron_1\omicron_2\mbox{.} \end{array} \] By the induction hypothesis about $e_1$, $\monadic{a}$ is $(\qualty{\listty{q}}{s_1}{d_1})$-exact, $\gamma_1$ is $\Gamma$-exact and $\omicron_1$ is exact in~$d$. Now by the induction hypothesis about $e_2$, $\monadic{i}$ is $(\qualty{\mbox{\lstinline+uint+}}{s_1}{d_1})$-exact, $\gamma_2$ is $\Gamma$-exact and $\omicron_2$~{}is exact in~$d$. Consider two cases: \begin{itemize} \item If $d_1\mathrel{\mathchar"13C\mathchar"3A} d$ then, by exactness, $\monadic{a}=\uopl{pure}(\monadic{a}_1,\ldots,\monadic{a}_n)$ for some $n\in\mathbb{N}$ and $\monadic{i}=\uopl{pure} i$ for some $i\in\mathbb{N}$, whereby $\monadic{a}_1,\ldots,\monadic{a}_n$ are $q$-exact in~$d$. Moreover, to obtain a pure value, we must have $i\leq n$. Hence $\monadic{v}=\monadic{a}_i$ exists and is $q$-exact in~$d$. \item If $d_1$ is a strict supertype of~$d$ then, by exactness, $\monadic{a}=\top$ and $\monadic{i}=\top$, whence $\monadic{v}=\top$. As $\Gamma$ is well-structured, $\qualty{\listty{q}}{s_1}{d_1}$ is well-structured by Theorem~\ref{typesystem:thm}. Hence $d_1\mathrel{\mathchar"13C\mathchar"3A} d_0$, implying that $d_0$ is a strict supertype of~$d$. By clause~3 of Definition~\ref{semantics:exactdef}, $\top$ is $q$-exact in~$d$. \end{itemize} \item Let $e=\stmtcomp{\letexpr{x}{e_1}}{e_2}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:q_1! D_1\mbox{,}\\ (x:q_1),\Gamma\mbox{\ $\vdash$\ } e_2:q! D_2\mbox{,} \end{array} \] and \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}((x,\monadic{v}_1),\gamma_1)\phi=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{,}\\ \monadic{v}=\monadic{v}_2\mbox{,}\quad\gamma'=\uopl{tail}\gamma_2\mbox{,}\quad\omicron=\omicron_1\omicron_2\mbox{.} \end{array} \] By the induction hypothesis about~$e_1$, $\monadic{v}_1$ is $q_1$-exact, $\gamma_1$ is $\Gamma$-exact and $\omicron_1$ is exact in~$d$. Hence $(x,\monadic{v}_1),\gamma_1$ is $((x:q_1),\Gamma)$-exact in~$d$. Now the induction hypothesis about~$e_2$ applies and implies $\monadic{v}_2$ being $q$-exact, $\gamma_2$ being $((x:q_1),\Gamma)$-exact and $\omicron_2$ being exact in~$d$. Then $\uopl{tail}\gamma_2$ is $\Gamma$-exact in~$d$. The desired claim follows. \item Let $e=\stmtcomp{e_1}{e_2}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:q_1! D_1\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:q! D_2\mbox{,} \end{array} \] and \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_1\phi=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{,}\\ \monadic{v}=\monadic{v}_2\mbox{,}\quad\gamma'=\gamma_2\mbox{,}\quad\omicron=\omicron_1\omicron_2\mbox{.} \end{array} \] By the induction hypothesis about~$e_1$, $\monadic{v}_1$ is $q_1$-exact, $\gamma_1$ is $\Gamma$-exact and $\omicron_1$ is exact in~$d$. Now by the induction hypothesis about~$e_2$, $\monadic{v}_2$ is $q$-exact, $\gamma_2$ is $\Gamma$-exact and $\omicron_2$ is exact in~$d$. The desired claim follows. \end{itemize} \end{proof} \begin{theorem}[Theorem~\ref{semantics:effthm}] Let $\Gamma \mbox{\ $\vdash$\ } e : q! D$ with well-structured~$\Gamma$ and $\gamma\in\mathbf{Env}$ be $\Gamma$-exact in~$d$ for some domain~$d$. Assume that for all subexpressions of~$e$ of the form $\ofty{\getexpr{d'}{k}}{q'}$ where $d'\mathrel{\mathchar"13C\mathchar"3A} d$, the value $\uopl{allpure}(\phi_{d'}(k))$ is $q'$-exact in~$d$. If $\semd{e}\gamma\phi=\uopl{pure}(\monadic{v},\gamma',\omicron)$ then, for any domain~$d''$ such that $d''\mathrel{\mathchar"13C\mathchar"3A} d$ and $d''\notin D$, we have $\gamma\coin{\Gamma}{d''}\gamma'$. \end{theorem} \begin{proof} By Theorem~\ref{semantics:localthm}, $\gamma'$ is $\Gamma$-exact in~$d$. By Lemma~\ref{semantics:reintlemma}, $\gamma$ and $\gamma'$ are $\Gamma$-exposed in~$d$. Take $d''$ such that $d''\mathrel{\mathchar"13C\mathchar"3A} d$ and $d''\notin D$. By Lemma~\ref{semantics:approxlemma}, $\gamma$ and $\gamma'$ are also $\Gamma$-exposed in~$d''$. Let $q=\qualty{t_0}{s_0}{d_0}$. We proceed by induction on the structure of~$e$. If $e=\epsilon$ or $e=\overline{n}$ where $n\in\mathbb{N}$ or $e=\overline{b}$ where $b\in\mathbb{B}$ or $e=x$ or $e=\getexpr{d'}{k}$ then $\gamma=\gamma'$. Hence by Lemma~\ref{semantics:coinlemma}, $\gamma\coin{\Gamma}{d''}\gamma'$. If $e=\assertexpr{e_1}$ or $e=\wireexpr{e_1}$ then the claim holds vacuously since $D=\gen{\mbox{\lstinline+@public+}}$. We study the remaining cases. \begin{itemize} \item Let $e=\addexpr{e_1}{e_2}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:q! D_1\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:q! D_2\mbox{,}\\ D=\gen{s_0}\cup D_1\cup D_2\mbox{,} \end{array} \] whence we must have $d''\notin D_1$ and $d''\notin D_2$. We also have \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_1\phi=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{,}\\ \gamma'=\gamma_2\mbox{.} \end{array} \] By the induction hypothesis, $\gamma\coin{\Gamma}{d''}\gamma_1$ and $\gamma_1\coin{\Gamma}{d''}\gamma_2$. By Lemma~\ref{semantics:coinlemma}, $\gamma\coin{\Gamma}{d''}\gamma_2$. The desired claim follows. \item Let $e=\ifexpr{e_1}{e_2}{e_3}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{\boolmodty{\mbox{\lstinline+N+}}}{\mbox{\lstinline+$pre+}}{d_1}! D_1\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:q! D_2\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_3:q! D_3\mbox{,}\\ \gen{d_1}\supseteq\gen{s_0}\cup\gen{d_0}\cup D_2\cup D_3\mbox{,}\quad D=D_1\cup D_2\cup D_3\mbox{,} \end{array} \] whence we must have $d''\notin D_1$, $d''\notin D_2$ and $d''\notin D_3$. We also have \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{.} \end{array} \] Consider three cases: \begin{itemize} \item If $\monadic{v}_1=\uopl{pure}\mbox{\bfseries tt}$ then \[ \begin{array}{l} \semd{e_2}\gamma_1\phi=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{,}\\ \gamma'=\gamma_2\mbox{.} \end{array} \] By the induction hypothesis, $\gamma\coin{\Gamma}{d''}\gamma_1$ and $\gamma_1\coin{\Gamma}{d''}\gamma_2$. By Lemma~\ref{semantics:coinlemma}, $\gamma\coin{\Gamma}{d''}\gamma_2$. The desired claim follows. \item If $\monadic{v}_1=\uopl{pure}\mbox{\bfseries ff}$ then \[ \begin{array}{l} \semd{e_3}\gamma_1\phi=\uopl{pure}(\monadic{v}_3,\gamma_3,\omicron_3)\mbox{,}\\ \gamma'=\gamma_3\mbox{.} \end{array} \] By the induction hypothesis, $\gamma\coin{\Gamma}{d''}\gamma_1$ and $\gamma_1\coin{\Gamma}{d''}\gamma_3$. By Lemma~\ref{semantics:coinlemma}, $\gamma\coin{\Gamma}{d''}\gamma_3$. The desired claim follows. \item If $\monadic{v}_1\ne\uopl{pure} b$ where $b\in\mathbb{B}$ then $\gamma'=\gamma_1$. By the induction hypothesis, $\gamma\coin{\Gamma}{d''}\gamma_1$. The desired claim follows. \end{itemize} \item Let $e=\forexpr{x}{e_1}{e_2}{e_3}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0}! D_1\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0}! D_2\mbox{,}\\ (x:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0}),\Gamma\mbox{\ $\vdash$\ } e_3:\qualty{t_1}{s_1}{d_1}! D_3\mbox{,}\\ \gen{d_0}\supseteq\gen{s_1}\cup\gen{d_1}\cup D_3\mbox{,}\quad D=D_1\cup D_2\cup D_3\mbox{,} \end{array} \] whence we have $d''\notin D_1$, $d''\notin D_2$ and $d''\notin D_3$. We also have \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_1\phi=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{.} \end{array} \] Consider two cases: \begin{itemize} \item If $\monadic{v}_1=\uopl{pure} i_1$ and $\monadic{v}_2=\uopl{pure} i_2$ for $i_1,i_2\in\mathbb{N}$ then, denoting $n=\max(0,i_2-i_1)$, we have \[ \begin{array}{l} \semd{e_3}((x,\uopl{pure} i_1),\gamma_2)\phi=\uopl{pure}(\monadic{v}_3,\gamma_3,\omicron_3)\mbox{,}\\ \semd{e_3}([x\mapsto\uopl{pure}(i_1+1)]\gamma_3)\phi=\uopl{pure}(\monadic{v}_4,\gamma_4,\omicron_4)\mbox{,}\\ \dotfill\\ \semd{e_3}([x\mapsto\uopl{pure}(i_1+n-1)]\gamma_{n+1})\phi=\uopl{pure}(\monadic{v}_{n+2},\gamma_{n+2},\omicron_{n+2})\mbox{,}\\ \gamma'=\uopl{tail}\gamma_{n+2}\mbox{.} \end{array} \] By the induction hypothesis, $\gamma\coin{\Gamma}{d''}\gamma_1$ and $\gamma_1\coin{\Gamma}{d''}\gamma_2$, and also $(x,\uopl{pure} i_1),\gamma_2\coin{\Gamma'}{d''}\gamma_3$ and $[x\mapsto\uopl{pure}(i_1+k-3)]\gamma_{k-1}\coin{\Gamma'}{d''}\gamma_k$ for each $k=4,\ldots,n+2$ where $\Gamma'=((x:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0}),\Gamma)$. Then also $\gamma_2\coin{\Gamma}{d''}\uopl{tail}\gamma_3$ and $\uopl{tail}\gamma_{k-1}\coin{\Gamma}{d''}\uopl{tail}\gamma_k$ for every $k=4,\ldots,n+2$. By Lemma~\ref{semantics:coinlemma}, $\gamma\coin{\Gamma}{d''}\uopl{tail}\gamma_{n+2}$. The desired claim follows. \item If $\monadic{v}_1\ne\uopl{pure} i_1$ or $\monadic{v}_2\ne\uopl{pure} i_2$ with $i_1,i_2\in\mathbb{N}$ then $\gamma'=\gamma_2$. By the induction hypothesis, $\gamma\coin{\Gamma}{d''}\gamma_1$ and $\gamma_1\coin{\Gamma}{d''}\gamma_2$. By Lemma~\ref{semantics:coinlemma}, $\gamma\coin{\Gamma}{d''}\gamma_2$. The desired claim follows. \end{itemize} \item Let $e=\castexpr{e_1}{d_0}$. Then \[ \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{t_1}{s_1}{d_1}! D\mbox{,} \] and \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \gamma'=\gamma_1\mbox{.} \end{array} \] By the induction hypothesis, $\gamma\coin{\Gamma}{d''}\gamma_1$. The desired claim follows. \item Let $e=(\assignexpr{e_1}{e_2})$. Let $e_1=\loadexpr{\loadexpr{\loadexpr{x}{y_1}}{y_2}\ldots}{y_n}$. By Lemma~\ref{typesystem:lhslemma}, \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } y_i:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_i}! D_i\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } x:\qualty{\listty{\ldots\listty{\qualty{\listty{\qualty{\listty{\qualty{t}{s}{d_{n+1}}}}{\mbox{\lstinline+$pre+}}{d_n}}}{\mbox{\lstinline+$pre+}}{d_{n-1}}}\ldots}}{\mbox{\lstinline+$pre+}}{d_1}! D_0 \end{array} \] and \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{t}{s}{d_{n+1}}! D_1\cup\ldots\cup D_n\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:\qualty{t}{s}{d_{n+1}}! D_{n+1}\mbox{,}\\ D=\gen{s}\cup\gen{d_{n+1}}\cup D_1\cup\ldots\cup D_{n+1}\mbox{,} \end{array} \] for some $D_1,\ldots,D_{n+1}$. Hence we must have $d''\notin D_k$ for every $k=1,\ldots,n+1$ and $d''\notin\gen{d_{n+1}}$ meaning that $d_{n+1}$ is a strict superdomain of~$d''$. We also have \[ \begin{array}{l} \semd{y_1}\gamma\phi=\uopl{pure}(\monadic{i}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{y_2}\gamma_1\phi=\uopl{pure}(\monadic{i}_2,\gamma_2,\omicron_2)\mbox{,}\\ \dotfill\\ \semd{y_n}\gamma_{n-1}\phi=\uopl{pure}(\monadic{i}_n,\gamma_n,\omicron_n)\mbox{,}\\ \semd{e_2}\gamma_n\phi=\uopl{pure}(\monadic{v},\gamma_{n+1},\omicron_{n+1})\mbox{,}\\ \gamma'=[x\mapsto\uopl{upd}(\lookup{\gamma}{x},\monadic{i}_1\ldots\monadic{i}_n,\monadic{v})]\gamma_{n+1}\mbox{.} \end{array} \] By the induction hypothesis, $\gamma_{k-1}\coin{\Gamma}{d''}\gamma_k$ for each $k=1,\ldots,n+1$ (denoting $\gamma_0=\gamma$). Let $\uopl{vars}\Gamma=(z_1,\ldots,z_l)$ and let the corresponding types be $q_1,\ldots,q_l$. Let $k$ be the least index such that $z_k=x$. For every $i\ne k$, we have $\lookup{\gamma_{n+1}}{z_i}=\lookup{\gamma'}{z_i}$. Hence, by Lemma~\ref{semantics:coinlemma}, $\lookup{\gamma}{z_i}\coin{q_i}{d''}\lookup{\gamma'}{z_i}$. Moreover, Lemma~\ref{semantics:updcoin0lemma} implies $\lookup{\gamma}{z_k}\coin{q_k}{d''}\uopl{upd}(\lookup{\gamma}{z_k},\monadic{i}_1\ldots\monadic{i}_n,\monadic{v})$. Consequently, $\gamma\coin{\Gamma}{d''}\gamma'$. The desired claim follows. \item Let $e=\loadexpr{e_1}{e_2}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{\listty{q}}{\mbox{\lstinline+$pre+}}{d_1}! D_1\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_1}! D_2\mbox{,}\\ D=D_1\cup D_2\mbox{,} \end{array} \] whence we have $d''\notin D_1$ and $d''\notin D_2$. We also have \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{a},\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_1\phi=\uopl{pure}(\monadic{i},\gamma_2,\omicron_2)\mbox{,}\\ \gamma'=\gamma_2\mbox{.} \end{array} \] By the induction hypothesis, $\gamma\coin{\Gamma}{d''}\gamma_1$ and $\gamma_1\coin{\Gamma}{d''}\gamma_2$. The desired claim follows by Lemma~\ref{semantics:coinlemma}. \item Let $e=(\stmtcomp{\letexpr{x}{e_1}}{e_2})$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{t_1}{s_1}{d_1}! D_1\mbox{,}\\ (x:\qualty{t_1}{s_1}{d_1}),\Gamma\mbox{\ $\vdash$\ } e_2:q\mbox{,}\\ D=\gen{d_1}\cup D_1\cup D_2\mbox{,} \end{array} \] whence $d''\notin D_1$ and $d''\notin D_2$. We also have \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}((x,\monadic{v}_1),\gamma_1)\phi=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{,}\\ \gamma'=\uopl{tail}\gamma_2\mbox{.} \end{array} \] The induction hypothesis implies $\gamma\coin{\Gamma}{d''}\gamma_1$ and $(x,\monadic{v}_1),\gamma_1\coin{\Gamma'}{d''}\gamma_2$ where $\Gamma'=((x:\qualty{t_1}{s_1}{d_1}),\Gamma)$. The latter implies $\gamma_1\coin{\Gamma}{d''}\uopl{tail}\gamma_2$. The desired claim follows by Lemma~\ref{semantics:coinlemma}. \item Let $e=\stmtcomp{e_1}{e_2}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{t_1}{s_1}{d_1}! D_1\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:q\mbox{,}\\ D=D_1\cup D_2\mbox{,} \end{array} \] whence $d''\notin D_1$ and $d''\notin D_2$. We also have \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_1\phi=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{,}\\ \gamma'=\gamma_2\mbox{.} \end{array} \] By the induction hypothesis, $\gamma\coin{\Gamma}{d''}\gamma_1$ and $\gamma_1\coin{\Gamma}{d''}\gamma_2$. The desired claim follows by Lemma~\ref{semantics:coinlemma}. \end{itemize} \end{proof} \begin{theorem}[Theorem~\ref{semantics:outputthm}] Let $\Gamma \mbox{\ $\vdash$\ } e : q! D$ with well-structured~$\Gamma$ and $\gamma\in\mathbf{Env}$ be $\Gamma$-exact in~$d$ for some domain~$d$. Assume that for all subexpressions of~$e$ of the form $\ofty{\getexpr{d'}{k}}{q'}$ where $d'\mathrel{\mathchar"13C\mathchar"3A} d$, the value $\uopl{allpure}(\phi_{d'}(k))$ is $q'$-exact in~$d$. If $\semd{e}\gamma\phi=\uopl{pure}(\monadic{v},\gamma',\omicron)$ and $\mbox{\lstinline+@public+}\notin D$ then $\omicron=\epsilon$. \end{theorem} \begin{proof} Let $q=\qualty{t_0}{s_0}{d_0}$. We proceed by induction on the structure of~$e$. If $e=\epsilon$ or $e=\overline{n}$ where $n\in\mathbb{N}$ or $e=\overline{b}$ where $b\in\mathbb{B}$ or $e=x$ or $e=\getexpr{d'}{k}$ then $\omicron=\epsilon$. If $e=\assertexpr{e_1}$ or $e=\wireexpr{e_1}$ then the claim holds vacuously since $D=\gen{\mbox{\lstinline+@public+}}$. We study the remaining cases. \begin{itemize} \item Let $e=\addexpr{e_1}{e_2}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:q! D_1\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:q! D_2\mbox{,}\\ D=\gen{s_0}\cup D_1\cup D_2\mbox{,} \end{array} \] whence we must have $\mbox{\lstinline+@public+}\notin D_1$ and $\mbox{\lstinline+@public+}\notin D_2$. We also have \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_1\phi=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{,}\\ \omicron=\omicron_1\omicron_2\mbox{.} \end{array} \] By Theorem~\ref{semantics:localthm}, $\gamma_1$ and $\gamma_2$ are $q$-exact in~$d$. By the induction hypothesis, $\omicron_1=\epsilon$ and $\omicron_2=\epsilon$. Hence $\omicron=\epsilon$. \item Let $e=\ifexpr{e_1}{e_2}{e_3}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{\boolmodty{\mbox{\lstinline+N+}}}{\mbox{\lstinline+$pre+}}{d_1}! D_1\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:q! D_2\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_3:q! D_3\mbox{,}\\ \gen{d_1}\supseteq\gen{s_0}\cup\gen{d_0}\cup D_2\cup D_3\mbox{,}\quad D=D_1\cup D_2\cup D_3\mbox{,} \end{array} \] whence we must have $\mbox{\lstinline+@public+}\notin D_1$, $\mbox{\lstinline+@public+}\notin D_2$ and $\mbox{\lstinline+@public+}\notin D_3$. We also have \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{.} \end{array} \] Consider three cases: \begin{itemize} \item If $\monadic{v}_1=\uopl{pure}\mbox{\bfseries tt}$ then \[ \begin{array}{l} \semd{e_2}\gamma_1\phi=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{,}\\ \omicron=\omicron_1\omicron_2\mbox{.} \end{array} \] By Theorem~\ref{semantics:localthm}, $\gamma_1$ and $\gamma_2$ are $\Gamma$-exact in~$d$. By the induction hypothesis, $\omicron_1=\epsilon$ and $\omicron_2=\epsilon$. Hence $\omicron=\epsilon$. \item If $\monadic{v}_1=\uopl{pure}\mbox{\bfseries ff}$ then \[ \begin{array}{l} \semd{e_3}\gamma_1\phi=\uopl{pure}(\monadic{v}_3,\gamma_3,\omicron_3)\mbox{,}\\ \omicron=\omicron_1\omicron_3\mbox{.} \end{array} \] By Theorem~\ref{semantics:localthm}, $\gamma_1$ and $\gamma_3$ are $\Gamma$-exact in~$d$. By the induction hypothesis, $\omicron_1=\epsilon$ and $\omicron_3=\epsilon$. Hence $\omicron=\epsilon$. \item If $\monadic{v}_1\ne\uopl{pure} b$ where $b\in\mathbb{B}$ then $\omicron=\omicron_1$. By the induction hypothesis, $\omicron_1=\epsilon$. The desired claim follows. \end{itemize} \item Let $e=\forexpr{x}{e_1}{e_2}{e_3}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0}! D_1\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0}! D_2\mbox{,}\\ (x:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0}),\Gamma\mbox{\ $\vdash$\ } e_3:\qualty{t_1}{s_1}{d_1}! D_3\mbox{,}\\ \gen{d_0}\supseteq\gen{s_1}\cup\gen{d_1}\cup D_3\mbox{,}\quad D=D_1\cup D_2\cup D_3\mbox{,} \end{array} \] whence we have $\mbox{\lstinline+@public+}\notin D_1$, $\mbox{\lstinline+@public+}\notin D_2$ and $\mbox{\lstinline+@public+}\notin D_3$. We also have \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_1\phi=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{.} \end{array} \] By Theorem~\ref{semantics:localthm}, $\monadic{v}_1$ and $\monadic{v}_2$ are $(\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0})$-exact in~$d$ and $\gamma_1$ and $\gamma_2$ are $\Gamma$-exact in~$d$. Consider two cases: \begin{itemize} \item If $\monadic{v}_1=\uopl{pure} i_1$ and $\monadic{v}_2=\uopl{pure} i_2$ for $i_1,i_2\in\mathbb{N}$ then, denoting $n=\max(0,i_2-i_1)$, we have \[ \begin{array}{l} \semd{e_3}((x,\uopl{pure} i_1),\gamma_2)\phi=\uopl{pure}(\monadic{v}_3,\gamma_3,\omicron_3)\mbox{,}\\ \semd{e_3}([x\mapsto\uopl{pure}(i_1+1)]\gamma_3)\phi=\uopl{pure}(\monadic{v}_4,\gamma_4,\omicron_4)\mbox{,}\\ \dotfill\\ \semd{e_3}([x\mapsto\uopl{pure}(i_1+n-1)]\gamma_{n+1})\phi=\uopl{pure}(\monadic{v}_{n+2},\gamma_{n+2},\omicron_{n+2})\mbox{,}\\ \omicron=\omicron_1\ldots\omicron_{n+2}\mbox{.} \end{array} \] By the above, $((x,\uopl{pure} i_1),\gamma_2)$ is $\Gamma'$-exact in~$d$ where $\Gamma'=((x:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0}),\Gamma)$. By Theorem~\ref{semantics:localthm}, $\gamma_3,\ldots,\gamma_{n+2}$ are also $\Gamma'$-exact in~$d$ since increasing $i_1$ does not change this property. Hence by the induction hypothesis, $\omicron_1=\ldots=\omicron_{n+2}=\epsilon$, implying $\omicron=\epsilon$. \item If $\monadic{v}_1\ne\uopl{pure} i_1$ or $\monadic{v}_2\ne\uopl{pure} i_2$ with $i_1,i_2\in\mathbb{N}$ then $\omicron=\omicron_1\omicron_2$. By the induction hypothesis, $\omicron_1=\epsilon$ and $\omicron_2=\epsilon$. Hence $\omicron=\epsilon$. \end{itemize} \item Let $e=\castexpr{e_1}{d_0}$. Then \[ \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{t_1}{s_1}{d_1}! D\mbox{,} \] and \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \omicron=\omicron_1\mbox{.} \end{array} \] By the induction hypothesis, $\omicron_1=\epsilon$. The desired claim follows. \item Let $e=(\assignexpr{e_1}{e_2})$. Let $e_1=\loadexpr{\loadexpr{\loadexpr{x}{y_1}}{y_2}\ldots}{y_n}$. By Lemma~\ref{typesystem:lhslemma}, \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } y_i:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_i}! D_i\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } x:\qualty{\listty{\ldots\listty{\qualty{\listty{\qualty{\listty{\qualty{t}{s}{d_{n+1}}}}{\mbox{\lstinline+$pre+}}{d_n}}}{\mbox{\lstinline+$pre+}}{d_{n-1}}}\ldots}}{\mbox{\lstinline+$pre+}}{d_1}! D_0 \end{array} \] and \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{t}{s}{d_{n+1}}! D_1\cup\ldots\cup D_n\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:\qualty{t}{s}{d_{n+1}}! D_{n+1}\mbox{,}\\ D=\gen{s}\cup\gen{d_{n+1}}\cup D_1\cup\ldots\cup D_{n+1}\mbox{,} \end{array} \] for some $D_1,\ldots,D_{n+1}$. Hence we must have $\mbox{\lstinline+@public+}\notin D_k$ for every $k=1,\ldots,n+1$. We also have \[ \begin{array}{l} \semd{y_1}\gamma\phi=\uopl{pure}(\monadic{i}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{y_2}\gamma_1\phi=\uopl{pure}(\monadic{i}_2,\gamma_2,\omicron_2)\mbox{,}\\ \dotfill\\ \semd{y_n}\gamma_{n-1}\phi=\uopl{pure}(\monadic{i}_n,\gamma_n,\omicron_n)\mbox{,}\\ \semd{e_2}\gamma_n\phi=\uopl{pure}(\monadic{v},\gamma_{n+1},\omicron_{n+1})\mbox{,}\\ \omicron=\omicron_1\ldots\omicron_{n+1}\mbox{.} \end{array} \] By Theorem~\ref{semantics:localthm}, $\gamma_1,\ldots,\gamma_n$ are $\Gamma$-exact in~$d$. By the induction hypothesis, $\omicron_1=\ldots=\omicron_{n+1}=\epsilon$, implying $\omicron=\epsilon$. \item Let $e=\loadexpr{e_1}{e_2}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{\listty{q}}{\mbox{\lstinline+$pre+}}{d_1}! D_1\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_1}! D_2\mbox{,}\\ D=D_1\cup D_2\mbox{,} \end{array} \] whence we have $\mbox{\lstinline+@public+}\notin D_1$ and $\mbox{\lstinline+@public+}\notin D_2$. We also have \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{a},\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_1\phi=\uopl{pure}(\monadic{i},\gamma_2,\omicron_2)\mbox{,}\\ \omicron=\omicron_1\omicron_2\mbox{.} \end{array} \] By Theorem~\ref{semantics:localthm}, $\gamma_1$ and $\gamma_2$ are $\Gamma$-exact in~$d$. By the induction hypothesis, $\omicron_1=\epsilon$ and $\omicron_2=\epsilon$. Hence $\omicron=\epsilon$. \item Let $e=(\stmtcomp{\letexpr{x}{e_1}}{e_2})$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{t_1}{s_1}{d_1}! D_1\mbox{,}\\ (x:\qualty{t_1}{s_1}{d_1}),\Gamma\mbox{\ $\vdash$\ } e_2:q\mbox{,}\\ D=\gen{d_1}\cup D_1\cup D_2\mbox{,} \end{array} \] whence $\mbox{\lstinline+@public+}\notin D_1$ and $\mbox{\lstinline+@public+}\notin D_2$. We also have \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}((x,\monadic{v}_1),\gamma_1)\phi=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{,}\\ \omicron=\omicron_1\omicron_2\mbox{.} \end{array} \] By Theorem~\ref{semantics:localthm}, $\monadic{v}_1$ is $(\qualty{t_1}{s_1}{d_1})$-exact and $\gamma_1$ is $\Gamma$-exact in~$d$. Hence $\left((x,\monadic{v}_1),\gamma_1\right)$ is $\Gamma'$-exact in~$d$ where $\Gamma'=((x:\qualty{t_1}{s_1}{d_1}),\Gamma)$. The induction hypothesis implies $\omicron_1=\epsilon$ and $\omicron_2=\epsilon$. Hence $\omicron=\epsilon$. \item Let $e=\stmtcomp{e_1}{e_2}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{t_1}{s_1}{d_1}! D_1\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:q\mbox{,}\\ D=D_1\cup D_2\mbox{,} \end{array} \] whence $\mbox{\lstinline+@public+}\notin D_1$ and $\mbox{\lstinline+@public+}\notin D_2$. We also have \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_1\phi=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{,}\\ \omicron=\omicron_1\omicron_2\mbox{.} \end{array} \] By Theorem~\ref{semantics:localthm}, $\gamma_1$ and $\gamma_2$ are $\Gamma$-exact in~$d$. By the induction hypothesis, $\omicron_1=\epsilon$ and $\omicron_2=\epsilon$. Hence $\omicron=\epsilon$. \end{itemize} \end{proof} \begin{theorem}[Theorem~\ref{semantics:effcircthm}] Let $\Gamma \mbox{\ $\vdash$\ } e : q! D$ with well-structured~$\Gamma$ and $\gamma\in\mathbf{Env}$ be $\Gamma$-exact in $d$ for $d=\mbox{\lstinline+@prover+}$. Assume that for all subexpressions of~$e$ of the form $\ofty{\getexpr{d'}{k}}{q'}$, the value $\uopl{allpure}(\phi_{d'}(k))$ is $q'$-exact in~$d$. If $\semd{e}\gamma\phi=\uopl{pure}(\monadic{v},\gamma',\omicron)$ and $\mbox{\lstinline+@public+}\notin D$ then $\gamma\coincirc{\Gamma}\gamma'$. \end{theorem} \begin{proof} By Theorem~\ref{semantics:localthm}, $\gamma'$ is $\Gamma$-exact in $\mbox{\lstinline+@prover+}$. By Lemma~\ref{semantics:reintlemma}, $\gamma$ and $\gamma'$ are $\Gamma$-exposed in $\mbox{\lstinline+@prover+}$. By Lemma~\ref{semantics:approxlemma}, $\gamma$ and $\gamma'$ are also $\Gamma$-exposed in circuit. Let $q=\qualty{t_0}{s_0}{d_0}$. We proceed by induction on the structure of~$e$. If $e=\epsilon$ or $e=\overline{n}$ where $n\in\mathbb{N}$ or $e=\overline{b}$ where $b\in\mathbb{B}$ or $e=x$ or $e=\getexpr{d'}{k}$ then $\gamma=\gamma'$. By Lemma~\ref{semantics:coinlemma}, $\gamma\coincirc{\Gamma}\gamma'$. If $e=\assertexpr{e_1}$ or $e=\wireexpr{e_1}$ then the claim holds vacuously since $D=\gen{\mbox{\lstinline+@public+}}$. We study the remaining cases. \begin{itemize} \item Let $e=\addexpr{e_1}{e_2}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:q! D_1\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:q! D_2\mbox{,}\\ D=\gen{s_0}\cup D_1\cup D_2\mbox{,} \end{array} \] whence we must have $\mbox{\lstinline+@public+}\notin D_1$ and $\mbox{\lstinline+@public+}\notin D_2$. We also have \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_1\phi=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{,}\\ \gamma'=\gamma_2\mbox{.} \end{array} \] By the induction hypothesis, $\gamma\coincirc{\Gamma}\gamma_1$ and $\gamma_1\coincirc{\Gamma}\gamma_2$. By Lemma~\ref{semantics:coinlemma}, $\gamma\coincirc{\Gamma}\gamma_2$. Hence $\gamma\coincirc{\Gamma}\gamma'$. \item Let $e=\ifexpr{e_1}{e_2}{e_3}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{\boolmodty{\mbox{\lstinline+N+}}}{\mbox{\lstinline+$pre+}}{d_1}! D_1\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:q! D_2\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_3:q! D_3\mbox{,}\\ \gen{d_1}\supseteq\gen{s_0}\cup\gen{d_0}\cup D_2\cup D_3\mbox{,}\quad D=D_1\cup D_2\cup D_3\mbox{,} \end{array} \] whence we must have $\mbox{\lstinline+@public+}\notin D_1$, $\mbox{\lstinline+@public+}\notin D_2$ and $\mbox{\lstinline+@public+}\notin D_3$. We also have \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{.} \end{array} \] By Theorem~\ref{semantics:localthm}, $\monadic{v}_1$ is $(\qualty{\boolmodty{\mbox{\lstinline+N+}}}{\mbox{\lstinline+$pre+}}{d_1})$-exact in $\mbox{\lstinline+@prover+}$, whence we have to consider two cases: \begin{itemize} \item If $\monadic{v}_1=\uopl{pure}\mbox{\bfseries tt}$ then \[ \begin{array}{l} \semd{e_2}\gamma_1\phi=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{,}\\ \gamma'=\gamma_2\mbox{.} \end{array} \] By the induction hypothesis, $\gamma\coincirc{\Gamma}\gamma_1$ and $\gamma_1\coincirc{\Gamma}\gamma_2$. By Lemma~\ref{semantics:coinlemma}, $\gamma\coincirc{\Gamma}\gamma_2$. Hence $\gamma\coincirc{\Gamma}\gamma'$. \item If $\monadic{v}_1=\uopl{pure}\mbox{\bfseries ff}$ then \[ \begin{array}{l} \semd{e_3}\gamma_1\phi=\uopl{pure}(\monadic{v}_3,\gamma_3,\omicron_3)\mbox{,}\\ \gamma'=\gamma_3\mbox{.} \end{array} \] By the induction hypothesis, $\gamma\coincirc{\Gamma}\gamma_1$ and $\gamma_1\coincirc{\Gamma}\gamma_3$. By Lemma~\ref{semantics:coinlemma}, $\gamma\coincirc{\Gamma}\gamma_3$. Hence $\gamma\coincirc{\Gamma}\gamma'$. \end{itemize} \item Let $e=\forexpr{x}{e_1}{e_2}{e_3}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0}! D_1\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0}! D_2\mbox{,}\\ (x:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0}),\Gamma\mbox{\ $\vdash$\ } e_3:\qualty{t_1}{s_1}{d_1}! D_3\mbox{,}\\ \gen{d_0}\supseteq\gen{s_1}\cup\gen{d_1}\cup D_3\mbox{,}\quad D=D_1\cup D_2\cup D_3\mbox{,} \end{array} \] whence we have $\mbox{\lstinline+@public+}\notin D_1$, $\mbox{\lstinline+@public+}\notin D_2$ and $\mbox{\lstinline+@public+}\notin D_3$. We also have \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_1\phi=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{.} \end{array} \] By Theorem~\ref{semantics:localthm}, $\monadic{v}_1$ and $\monadic{v}_2$ are $(\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0})$-exact in $\mbox{\lstinline+@prover+}$, whence $\monadic{v}_1=\uopl{pure} i_1$ and $\monadic{v}_2=\uopl{pure} i_2$ for $i_1,i_2\in\mathbb{N}$. Denoting $n=\max(0,i_2-i_1)$, we have \[ \begin{array}{l} \semd{e_3}((x,\uopl{pure} i_1),\gamma_2)\phi=\uopl{pure}(\monadic{v}_3,\gamma_3,\omicron_3)\mbox{,}\\ \semd{e_3}([x\mapsto\uopl{pure}(i_1+1)]\gamma_3)\phi=\uopl{pure}(\monadic{v}_4,\gamma_4,\omicron_4)\mbox{,}\\ \dotfill\\ \semd{e_3}([x\mapsto\uopl{pure}(i_1+n-1)]\gamma_{n+1})\phi=\uopl{pure}(\monadic{v}_{n+2},\gamma_{n+2},\omicron_{n+2})\mbox{,}\\ \gamma'=\uopl{tail}\gamma_{n+2}\mbox{.} \end{array} \] By the induction hypothesis, $\gamma\coincirc{\Gamma}\gamma_1$ and $\gamma_1\coincirc{\Gamma}\gamma_2$, and also $\left((x,\uopl{pure} i_1),\gamma_2\right)\coincirc{\Gamma'}\gamma_3$ and $[x\mapsto\uopl{pure}(i_1+k-3)]\gamma_{k-1}\coincirc{\Gamma'}\gamma_k$ for each $k=4,\ldots,n+2$ where $\Gamma'=((x:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0}),\Gamma)$. Then also $\gamma_2\coincirc{\Gamma}\uopl{tail}\gamma_3$ and $\uopl{tail}\gamma_{k-1}\coincirc{\Gamma}\uopl{tail}\gamma_k$ for every $k=4,\ldots,n+2$. By Lemma~\ref{semantics:coinlemma}, $\gamma\coincirc{\Gamma}\uopl{tail}\gamma_{n+2}$. Hence $\gamma\coincirc{\Gamma}\gamma'$. \item Let $e=\castexpr{e_1}{d_0}$. Then \[ \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{t_1}{s_1}{d_1}! D\mbox{,} \] and \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \gamma'=\gamma_1\mbox{.} \end{array} \] By the induction hypothesis, $\gamma\coincirc{\Gamma}\gamma_1$. Hence $\gamma\coincirc{\Gamma}\gamma'$. \item Let $e=(\assignexpr{e_1}{e_2})$. Let $e_1=\loadexpr{\loadexpr{\loadexpr{x}{y_1}}{y_2}\ldots}{y_n}$. By Lemma~\ref{typesystem:lhslemma}, \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } y_i:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_i}! D_i\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } x:\qualty{\listty{\ldots\listty{\qualty{\listty{\qualty{\listty{\qualty{t}{s}{d_{n+1}}}}{\mbox{\lstinline+$pre+}}{d_n}}}{\mbox{\lstinline+$pre+}}{d_{n-1}}}\ldots}}{\mbox{\lstinline+$pre+}}{d_1}! D_0 \end{array} \] and \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{t}{s}{d_{n+1}}! D_1\cup\ldots\cup D_n\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:\qualty{t}{s}{d_{n+1}}! D_{n+1}\mbox{,}\\ D=\gen{s}\cup\gen{d_{n+1}}\cup D_1\cup\ldots\cup D_{n+1}\mbox{,} \end{array} \] for some $D_1,\ldots,D_{n+1}$. Hence we must have $\mbox{\lstinline+@public+}\notin D_k$ for every $k=1,\ldots,n+1$ and $\mbox{\lstinline+@public+}\notin\gen{d_{n+1}}$ meaning that $d_{n+1}$ is a strict superdomain of~$\mbox{\lstinline+@public+}$. We also have \[ \begin{array}{l} \semd{y_1}\gamma\phi=\uopl{pure}(\monadic{i}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{y_2}\gamma_1\phi=\uopl{pure}(\monadic{i}_2,\gamma_2,\omicron_2)\mbox{,}\\ \dotfill\\ \semd{y_n}\gamma_{n-1}\phi=\uopl{pure}(\monadic{i}_n,\gamma_n,\omicron_n)\mbox{,}\\ \semd{e_2}\gamma_n\phi=\uopl{pure}(\monadic{v},\gamma_{n+1},\omicron_{n+1})\mbox{,}\\ \gamma'=[x\mapsto\uopl{upd}(\lookup{\gamma}{x},\monadic{i}_1\ldots\monadic{i}_n,\monadic{v})]\gamma_{n+1}\mbox{.} \end{array} \] By the induction hypothesis, $\gamma_{k-1}\coincirc{\Gamma}\gamma_k$ for each $k=1,\ldots,n+1$ (denoting $\gamma_0=\gamma$). Let $\uopl{vars}\Gamma=(z_1,\ldots,z_l)$ and let the corresponding types be $q_1,\ldots,q_l$. Let $k$ be the least index such that $z_k=x$. For every $i\ne k$, we have $\lookup{\gamma_{n+1}}{z_i}=\lookup{\gamma'}{z_i}$. Hence, by Lemma~\ref{semantics:coinlemma}, $\lookup{\gamma}{z_i}\coincirc{q_i}\lookup{\gamma'}{z_i}$. Moreover, Lemma~\ref{semantics:updcoin0lemma} implies $\lookup{\gamma}{z_k}\coincirc{q_k}\uopl{upd}(\lookup{\gamma}{z_k},\monadic{i}_1\ldots\monadic{i}_n,\monadic{v})$. Consequently, $\gamma\coincirc{\Gamma}\gamma'$. The desired claim follows. \item Let $e=\loadexpr{e_1}{e_2}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{\listty{q}}{\mbox{\lstinline+$pre+}}{d_1}! D_1\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_1}! D_2\mbox{,}\\ D=D_1\cup D_2\mbox{,} \end{array} \] whence we have $\mbox{\lstinline+@public+}\notin D_1$ and $\mbox{\lstinline+@public+}\notin D_2$. We also have \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{a},\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_1\phi=\uopl{pure}(\monadic{i},\gamma_2,\omicron_2)\mbox{,}\\ \gamma'=\gamma_2\mbox{.} \end{array} \] By the induction hypothesis, $\gamma\coincirc{\Gamma}\gamma_1$ and $\gamma_1\coincirc{\Gamma}\gamma_2$. By Lemma~\ref{semantics:coinlemma}, $\gamma\coincirc{\Gamma}\gamma_2$. Hence $\gamma\coincirc{\Gamma}\gamma'$. \item Let $e=(\stmtcomp{\letexpr{x}{e_1}}{e_2})$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{t_1}{s_1}{d_1}! D_1\mbox{,}\\ (x:\qualty{t_1}{s_1}{d_1}),\Gamma\mbox{\ $\vdash$\ } e_2:q\mbox{,}\\ D=\gen{d_1}\cup D_1\cup D_2\mbox{,} \end{array} \] whence $\mbox{\lstinline+@public+}\notin D_1$ and $\mbox{\lstinline+@public+}\notin D_2$. We also have \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}((x,\monadic{v}_1),\gamma_1)\phi=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{,}\\ \gamma'=\uopl{tail}\gamma_2\mbox{.} \end{array} \] The induction hypothesis implies $\gamma\coincirc{\Gamma}\gamma_1$ and $\left((x,\monadic{v}_1),\gamma_1\right)\coincirc{\Gamma'}\gamma_2$ where $\Gamma'=((x:\qualty{t_1}{s_1}{d_1}),\Gamma)$. The latter implies $\gamma_1\coincirc{\Gamma}\uopl{tail}\gamma_2$. The desired claim follows by Lemma~\ref{semantics:coinlemma}. \item Let $e=\stmtcomp{e_1}{e_2}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{t_1}{s_1}{d_1}! D_1\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:q\mbox{,}\\ D=D_1\cup D_2\mbox{,} \end{array} \] whence $\mbox{\lstinline+@public+}\notin D_1$ and $\mbox{\lstinline+@public+}\notin D_2$. We also have \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_1\phi=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{,}\\ \gamma'=\gamma_2\mbox{.} \end{array} \] By the induction hypothesis, $\gamma\coincirc{\Gamma}\gamma_1$ and $\gamma_1\coincirc{\Gamma}\gamma_2$. The desired claim follows by Lemma~\ref{semantics:coinlemma}. \end{itemize} \end{proof} \begin{theorem}[Theorem~\ref{semantics:safety}] If $\semd{e}\gamma\phi=\uopl{pure}(\monadic{v},\gamma',\omicron)$ and $\phi'_{d'}=\phi_{d'}$ for every $d'\mathrel{\mathchar"13C\mathchar"3A} d$ then $\semd{e}\gamma\phi'=\semd{e}\gamma\phi$. \end{theorem} \begin{proof} Let $\phi':\mathbf{In}^3$ be such that $\phi_{d'}=\phi'_{d'}$ for every $d'\mathrel{\mathchar"13C\mathchar"3A} d$. We proceed by induction on the structure of~$e$. \begin{itemize} \item If $e=\epsilon$, $e=\overline{n}$ where $n\in\mathbb{N}$, $e=\overline{b}$ where $b\in\mathbb{B}$, or $e=x$, then $\semd{e}\gamma\phi'=\semd{e}\gamma\phi$ because the semantics in these cases does not depend on the input dictionaries. \item Let $e=\addexpr{e_1}{e_2}$. Then \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_1\phi=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{,}\\ \monadic{v}=\mcomp{v_1\gets\monadic{v}_1;\; v_2\gets\monadic{v}_2;\;\uopl{pure}(v_1+v_2)}\mbox{,}\quad\gamma'=\gamma_2\mbox{,}\quad\omicron=\omicron_1\omicron_2\mbox{.} \end{array} \] By the induction hypothesis about $e_1$ and $e_2$, \[ \begin{array}{l} \semd{e_1}\gamma\phi'=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_1\phi'=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{.} \end{array} \] Hence $\semd{\addexpr{e_1}{e_2}}\gamma\phi'=\uopl{pure}(\mcomp{v_1\gets\monadic{v}_1;\; v_2\gets\monadic{v}_2;\;\uopl{pure}(v_1+v_2)},\gamma_2,\omicron_1\omicron_2)=\semd{\addexpr{e_1}{e_2}}\gamma\phi$ as needed. \item Let $e=\assertexpr{e_1}$. Then \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \monadic{v}_1\ne\uopl{pure}\mbox{\bfseries ff}\mbox{,}\quad\monadic{v}=\uopl{pure}\mbox{\textoneoldstyle}\mbox{,}\quad\gamma'=\gamma_1\mbox{,}\quad\omicron=\omicron_1\mbox{.} \end{array} \] By the induction hypothesis about~$e_1$, \[ \begin{array}{l} \semd{e_1}\gamma\phi'=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{.} \end{array} \] Hence $\semd{\assertexpr{e_1}}\gamma\phi'=\uopl{pure}(\uopl{pure}\mbox{\textoneoldstyle},\gamma_1,\omicron_1)=\semd{\assertexpr{e_1}}\gamma\phi$. \item Let $e=\ofty{\getexpr{d''}{k}}{q}$. Then $\semd{e}\gamma\phi'=\semd{e}\gamma\phi$ since the semantics depends only on inputs of subdomains of~$d$. \item Let $e=\ifexpr{e_1}{e_2}{e_3}$. Then \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1) \end{array} \] and, by the induction hypothesis about~$e_1$, \[ \begin{array}{l} \semd{e_1}\gamma\phi'=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{.} \end{array} \] Consider three cases: \begin{itemize} \item If $\monadic{v}_1=\uopl{pure}\mbox{\bfseries tt}$ then \[ \begin{array}{l} \semd{e_2}\gamma_1\phi=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{,}\\ \monadic{v}=\monadic{v}_2\mbox{,}\quad\gamma'=\gamma_2\mbox{,}\quad\omicron=\omicron_1\omicron_2\mbox{.} \end{array} \] By the induction hypothesis about~$e_2$, \[ \semd{e_2}\gamma_1\phi'=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{.} \] Hence $\semd{\ifexpr{e_1}{e_2}{e_3}}\gamma\phi'=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_1\omicron_2)=\semd{\ifexpr{e_1}{e_2}{e_3}}\gamma\phi$. \item If $\monadic{v}_1=\uopl{pure}\mbox{\bfseries ff}$ then \[ \begin{array}{l} \semd{e_3}\gamma_1\phi=\uopl{pure}(\monadic{v}_3,\gamma_3,\omicron_3)\mbox{,}\\ \monadic{v}=\monadic{v}_3\mbox{,}\quad\gamma'=\gamma_3\mbox{,}\quad\omicron=\omicron_1\omicron_3\mbox{.} \end{array} \] By the induction hypothesis about~$e_3$, \[ \semd{e_3}\gamma_1\phi'=\uopl{pure}(\monadic{v}_3,\gamma_3,\omicron_3)\mbox{.} \] Hence $\semd{\ifexpr{e_1}{e_2}{e_3}}\gamma\phi'=\uopl{pure}(\monadic{v}_3,\gamma_3,\omicron_1\omicron_3)=\semd{\ifexpr{e_1}{e_2}{e_3}}\gamma\phi$. \item If $\monadic{v}_1\ne\uopl{pure} b$ where $b\in\mathbb{B}$ then $\monadic{v}=\top$, $\gamma'=\gamma_1$ and $\omicron=\omicron_1$. Since we similarly have $\semd{\ifexpr{e_1}{e_2}{e_3}}\gamma\phi'=\uopl{pure}(\top,\gamma_1,\omicron_1)$, the desired claim follows. \end{itemize} \item Let $e=\forexpr{x}{e_1}{e_2}{e_3}$. Then \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_1\phi=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{,} \end{array} \] and, by the induction hypothesis about $e_1$ and $e_2$, \[ \begin{array}{l} \semd{e_1}\gamma\phi'=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma\phi'=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{.} \end{array} \] Consider two cases: \begin{itemize} \item If $\monadic{v}_1=\uopl{pure} i_1$ and $\monadic{v}_2=\uopl{pure} i_2$ for $i_1,i_2\in\mathbb{N}$ then, denoting $n=\max(0,i_2-i_1)$, we have \[ \begin{array}{l} \semd{e_3}((x,\uopl{pure} i_1),\gamma_2)\phi=\uopl{pure}(\monadic{v}_3,\gamma_3,\omicron_3)\mbox{,}\\ \semd{e_3}([x\mapsto\uopl{pure}(i_1+1)]\gamma_3)\phi=\uopl{pure}(\monadic{v}_4,\gamma_4,\omicron_4)\mbox{,}\\ \dotfill\\ \semd{e_3}([x\mapsto\uopl{pure}(i_1+n-1)]\gamma_{n+1})\phi=\uopl{pure}(\monadic{v}_{n+2},\gamma_{n+2},\omicron_{n+2})\mbox{,}\\ \monadic{v}=\uopl{pure}(\monadic{v}_3,\ldots,\monadic{v}_{n+2})\mbox{,}\quad\gamma'=\uopl{tail}\gamma_{n+2}\mbox{,}\quad\omicron=\omicron_1\ldots\omicron_{n+2}\mbox{.} \end{array} \] By the induction hypothesis about $e_3$, \[ \begin{array}{l} \semd{e_3}((x,\uopl{pure} i_1),\gamma_2)\phi'=\uopl{pure}(\monadic{v}_3,\gamma_3,\omicron_3)\mbox{,}\\ \semd{e_3}([x\mapsto\uopl{pure}(i_1+1)]\gamma_3)\phi'=\uopl{pure}(\monadic{v}_4,\gamma_4,\omicron_4)\mbox{,}\\ \dotfill\\ \semd{e_3}([x\mapsto\uopl{pure}(i_1+n-1)]\gamma_{n+1})\phi'=\uopl{pure}(\monadic{v}_{n+2},\gamma_{n+2},\omicron_{n+2})\mbox{.} \end{array} \] Hence $\semd{\forexpr{x}{e_1}{e_2}{e_3}}\gamma\phi'=\uopl{pure}(\uopl{pure}(\monadic{v}_3,\ldots,\monadic{v}_{n+2}),\uopl{tail}\gamma_{n+2},\omicron_1\ldots\omicron_{n+2})$ and the desired claim follows. \item If $\monadic{v}_1\ne\uopl{pure} i_1$ or $\monadic{v}_2\ne\uopl{pure} i_2$ with $i_1,i_2\in\mathbb{N}$ then $\monadic{v}=\top$, $\gamma'=\gamma_2$ and $\omicron=\omicron_1\omicron_2$. As we similarly get $\semd{\forexpr{x}{e_1}{e_2}{e_3}}\gamma\phi'=\uopl{pure}(\top,\gamma_2,\omicron_1\omicron_2)$, the desired claim follows. \end{itemize} \item Let $e=\wireexpr{e_1}$. Then \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \monadic{v}=\monadic{v}_1\mbox{,}\quad\gamma'=\gamma_1\mbox{,}\quad\omicron=\lam{d'}{\branching{(\omicron_1)_{d'}\monadic{v}_1&\mbox{if $e_1$ is in domain~$d'$}\\(\omicron_1)_{d'}&\mbox{otherwise}}}\mbox{.} \end{array} \] By the induction hypothesis about~$e_1$, \[ \semd{e_1}\gamma\phi'=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{.} \] Hence \[ \begin{array}{lcl} \semd{\wireexpr{e_1}}\gamma\phi' &=&\uopl{pure}(\monadic{v}_1,\gamma_1,\lam{d'}{\branching{(\omicron_1)_{d'}\monadic{v}_1&\mbox{if $e_1$ is in domain~$d'$}\\(\omicron_1)_{d'}&\mbox{otherwise}}})\\ &=&\semd{\wireexpr{e_1}}\gamma\phi \end{array} \] and the desired claim follows. \item Let $e=\castexpr{e_1}{d_0}$. Let the domain of~$e_1$ be $d_1$. Then \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \monadic{v}=\branching{\monadic{v}_1&\mbox{if $d_0\mathrel{\mathchar"13C\mathchar"3A} d$}\\\top&\mbox{otherwise}}\mbox{,}\quad\gamma'=\gamma_1\mbox{,}\quad\omicron=\omicron_1\mbox{.} \end{array} \] By the induction hypothesis, \[ \semd{e_1}\gamma\phi'=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{.} \] Hence $\semd{\castexpr{e_1}{d_0}}\gamma\phi'=\uopl{pure}(\branching{\monadic{v}_1&\mbox{if $d_0\mathrel{\mathchar"13C\mathchar"3A} d$}\\\top&\mbox{otherwise}},\gamma_1,\omicron_1)=\semd{\castexpr{e_1}{d_0}}\gamma\phi$ and the desired claim follows. \item Let $e=(\assignexpr{e_1}{e_2})$. Let $e_1=\loadexpr{\loadexpr{\loadexpr{x}{y_1}}{y_2}\ldots}{y_n}$. Then \[ \begin{array}{l} \semd{y_1}\gamma\phi=\uopl{pure}(\monadic{i}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{y_2}\gamma_1\phi=\uopl{pure}(\monadic{i}_2,\gamma_2,\omicron_2)\mbox{,}\\ \dotfill\\ \semd{y_n}\gamma_{n-1}\phi=\uopl{pure}(\monadic{i}_n,\gamma_n,\omicron_n)\mbox{,}\\ \semd{e_2}\gamma_n\phi=\uopl{pure}(\monadic{r},\gamma_{n+1},\omicron_{n+1})\mbox{,}\\ \monadic{v}=\uopl{pure}\mbox{\textoneoldstyle}\mbox{,}\quad\gamma'=[x\mapsto\uopl{upd}(\lookup{\gamma}{x},\monadic{i}_1\ldots\monadic{i}_n,\monadic{r})]\gamma_{n+1}\mbox{,}\quad\omicron=\omicron_1\ldots\omicron_{n+1}\mbox{.} \end{array} \] By the induction hypothesis, \[ \begin{array}{l} \semd{y_1}\gamma\phi'=\uopl{pure}(\monadic{i}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{y_2}\gamma_1\phi'=\uopl{pure}(\monadic{i}_2,\gamma_2,\omicron_2)\mbox{,}\\ \dotfill\\ \semd{y_n}\gamma_{n-1}\phi'=\uopl{pure}(\monadic{i}_n,\gamma_n,\omicron_n)\mbox{,}\\ \semd{e_2}\gamma_n\phi'=\uopl{pure}(\monadic{r},\gamma_{n+1},\omicron_{n+1})\mbox{.} \end{array} \] Hence \[ \semd{\assignexpr{e_1}{e_2}}\gamma\phi'=\uopl{pure}(\uopl{pure}\mbox{\textoneoldstyle},[x\mapsto\uopl{upd}(\lookup{\gamma}{x},\monadic{i}_1\ldots\monadic{i}_n,\monadic{v})]\gamma_{n+1},\omicron_1\ldots\omicron_{n+1})=\semd{\assignexpr{e_1}{e_2}}\gamma\phi \] and the desired claim follows. \item Let $e=\loadexpr{e_1}{e_2}$. Then \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{a},\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_1\phi=\uopl{pure}(\monadic{i},\gamma_2,\omicron_2)\mbox{,}\\ \monadic{v}=\mcomp{a\gets\monadic{a};\; i\gets\monadic{i};\; a_i}\mbox{,}\quad\gamma'=\gamma_2\mbox{,}\quad\omicron=\omicron_1\omicron_2\mbox{.} \end{array} \] By the induction hypothesis, \[ \begin{array}{l} \semd{e_1}\gamma\phi'=\uopl{pure}(\monadic{a},\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_1\phi'=\uopl{pure}(\monadic{i},\gamma_2,\omicron_2)\mbox{.}\\ \end{array} \] Hence $\semd{\loadexpr{e_1}{e_2}}\gamma\phi'=\uopl{pure}(\mcomp{a\gets\monadic{a};\; i\gets\monadic{i};\; a_i},\gamma_2,\omicron_1\omicron_2)=\semd{\loadexpr{e_1}{e_2}}$ and the desired claim follows. \item Let $e=\stmtcomp{\letexpr{x}{e_1}}{e_2}$. Then \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}((x,\monadic{v}_1),\gamma_1)\phi=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{,}\\ \monadic{v}=\monadic{v}_2\mbox{,}\quad\gamma'=\uopl{tail}\gamma_2\mbox{,}\quad\omicron=\omicron_1\omicron_2\mbox{.} \end{array} \] By the induction hypothesis, \[ \begin{array}{l} \semd{e_1}\gamma\phi'=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}((x,\monadic{v}_1),\gamma_1)\phi'=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{.} \end{array} \] Hence $\semd{\stmtcomp{\letexpr{x}{e_1}}{e_2}}\gamma\phi'=\uopl{pure}(\monadic{v}_2,\uopl{tail}\gamma_2,\omicron_1\omicron_2)=\semd{\stmtcomp{\letexpr{x}{e_1}}{e_2}}\gamma\phi$ and the desired claim follows. \item Let $e=\stmtcomp{e_1}{e_2}$. Then \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_1\phi=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{,}\\ \monadic{v}=\monadic{v}_2\mbox{,}\quad\gamma'=\gamma_2\mbox{,}\quad\omicron=\omicron_1\omicron_2\mbox{.} \end{array} \] By the induction hypothesis, \[ \begin{array}{l} \semd{e_1}\gamma\phi'=\uopl{pure}(\monadic{v}_1,\gamma_1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_1\phi'=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_2)\mbox{.} \end{array} \] Hence $\semd{\stmtcomp{e_1}{e_2}}\gamma\phi'=\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_1\omicron_2)=\semd{\stmtcomp{e_1}{e_2}}\gamma\phi$ and the desired claim follows. \end{itemize} \end{proof} \begin{theorem}[Theorem~\ref{semantics:soundness}] Let $\Gamma\mbox{\ $\vdash$\ } e:q! D$ with well-structured $\Gamma$. Let $d,d'$ be domains such that $d'\mathrel{\mathchar"13C\mathchar"3A} d$. Let $\gamma_d,\gamma_{d'}\in\mathbf{Env}$ be $\Gamma$-exact in~$d$ and $d'$, respectively, and let $\gamma_d\coin{\Gamma}{d'}\gamma_{d'}$. Assume that for all subexpressions of~$e$ of the form $\ofty{\getexpr{d''}{k}}{q'}$, the value $\uopl{allpure}(\phi_{d''}(k))$ is $q'$-exact in~$d''$. Assume that there exist $\monadic{v}_d,\gamma'_d,\omicron$ such that $\semd{e}\gamma_d\phi=\uopl{pure}(\monadic{v}_d,\gamma'_d,\omicron)$. Then there exist $\monadic{v}_{d'},\gamma'_{d'},\omicron'$ such that $\sem{e}_{d'}\gamma_{d'}\phi=\uopl{pure}(\monadic{v}_{d'},\gamma'_{d'},\omicron')$, whereby $\monadic{v}_d\coin{q}{d'}\monadic{v}_{d'}$, $\gamma_d\coin{\Gamma}{d'}\gamma_{d'}$ and $\omicron\coinpure{d'}\omicron'$. \end{theorem} \begin{proof} Let $q=\qualty{t_0}{s_0}{d_0}$. We proceed by induction on the structure of~$e$: \begin{itemize} \item Let $e=\epsilon$. Then $\monadic{v}_d=\uopl{pure}\mbox{\textoneoldstyle}$, $\gamma'_d=\gamma_d$, $\omicron=\epsilon$ and $\sem{\epsilon}_{d'}\gamma_{d'}\phi=\uopl{pure}(\uopl{pure}\mbox{\textoneoldstyle},\gamma_{d'},\epsilon)$. The desired claim follows since $\uopl{pure}\mbox{\textoneoldstyle}\coin{q}{d'}\uopl{pure}\mbox{\textoneoldstyle}$ and, by assumption, $\gamma_d\coin{\Gamma}{d'}\gamma_{d'}$. \item Let $e=\overline{n}$ where $n\in\mathbb{N}$. Then $\monadic{v}_d=\branching{\uopl{pure} n&\mbox{if $d_0\mathrel{\mathchar"13C\mathchar"3A} d$}\\\top&\mbox{otherwise}}$, $\gamma'_d=\gamma_d$, $\omicron=\epsilon$. On the other hand, $\sem{\overline{n}}_{d'}\gamma_{d'}\phi=\uopl{pure}(\branching{\uopl{pure} n&\mbox{if $d_0\mathrel{\mathchar"13C\mathchar"3A} d'$}\\\top&\mbox{otherwise}},\gamma_{d'},\epsilon)$. Consider two cases: \begin{itemize} \item If $d_0\mathrel{\mathchar"13C\mathchar"3A} d'$ then also $d_0\mathrel{\mathchar"13C\mathchar"3A} d$, whence $\monadic{v}_d=\uopl{pure} n=\monadic{v}_{d'}$. Consequently, $\monadic{v}_d\coin{q}{d'}\monadic{v}'$. \item If $d_0$ is a strict superdomain of~$d'$ then $\monadic{v}_d\coin{q}{d'}\monadic{v}'$ vacuously. \end{itemize} Moreover, $\gamma_{d}\coin{\Gamma}{d'}\gamma_{d'}$ by assumption. The desired claim follows. \item The case $e=\overline{b}$ with $b\in\mathbb{B}$ is similar to the previous case. \item If $e=x$ then $\monadic{v}_d=\lookup{\gamma_d}{x}$, $\gamma'_d=\gamma_d$, $\omicron=\epsilon$. On the other hand, $\sem{x}_{d'}\gamma_{d'}\phi=\uopl{pure}(\lookup{\gamma_{d'}}{x},\gamma_{d'},\epsilon)$. The desired claim follows since, by assumption, $\gamma_d\coin{\Gamma}{d'}\gamma_{d'}$ which also implies $\lookup{\gamma_d}{x}\coin{q}{d'}\lookup{\gamma_{d'}}{x}$ by Lemma~\ref{semantics:lookupcoinlemma}. \item Let $e=\addexpr{e_1}{e_2}$. Then \[ \begin{array}{l} \semd{e_1}\gamma_d\phi=\uopl{pure}(\monadic{v}_d^1,\gamma_d^1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_d^1\phi=\uopl{pure}(\monadic{v}_d^2,\gamma_d^2,\omicron_2)\mbox{,}\\ \monadic{v}_d=\mcomp{v_d^1\gets\monadic{v}_d^1;\; v_d^2\gets\monadic{v}_d^2;\;\uopl{pure}(v_d^1+v_d^2)}\mbox{,}\quad\gamma'_d=\gamma_d^2\mbox{,}\quad\omicron=\omicron_1\omicron_2\mbox{.} \end{array} \] By the induction hypothesis about $e_1$, $\sem{e_1}_{d'}\gamma_{d'}\phi=\uopl{pure}(\monadic{v}_{d'}^1,\gamma_{d'}^1,\omicron'_1)$ where $\monadic{v}_d^1\coin{q}{d'}\monadic{v}_{d'}^1$, $\gamma_d^1\coin{\Gamma}{d'}\gamma_{d'}^1$ and $\omicron_1\coinpure{d'}\omicron'_1$. Hence by the induction hypothesis about $e_2$, $\sem{e_2}_{d'}\gamma_{d'}^1\phi=\uopl{pure}(\monadic{v}_{d'}^2,\gamma_{d'}^2,\omicron'_2)$ where $\monadic{v}_d^2\coin{q}{d'}\monadic{v}_{d'}^2$, $\gamma_d^2\coin{\Gamma}{d'}\gamma_{d'}^2$ and $\omicron_2\coinpure{d'}\omicron'_2$. Thus \[ \begin{array}{l} \sem{\addexpr{e_1}{e_2}}_{d'}\gamma_{d'}\phi=\uopl{pure}(\monadic{v}_{d'},\gamma'_{d'},\omicron')\mbox{,}\\ \monadic{v}_{d'}=\mcomp{v_{d'}^1\gets\monadic{v}_{d'}^1;\; v_{d'}^2\gets\monadic{v}_{d'}^2;\;\uopl{pure}(v_{d'}^1+v_{d'}^2)}\mbox{,}\quad\gamma'_{d'}=\gamma_{d'}^2\mbox{,}\quad\omicron'=\omicron'_1\omicron'_2\mbox{.} \end{array} \] Consider two cases: \begin{itemize} \item If $d_0\mathrel{\mathchar"13C\mathchar"3A} d'$ then also $d_0\mathrel{\mathchar"13C\mathchar"3A} d$ and we have $\monadic{v}_d^1=\uopl{pure} v_d^1$, $\monadic{v}_2=\uopl{pure} v_d^2$, $\monadic{v}_{d'}^1=\uopl{pure} v_{d'}^1$, $\monadic{v}_{d'}^2=\uopl{pure} v_{d'}^2$ by exactness. This implies $\monadic{v}_d=\uopl{pure}(v_d^1+v_d^2)$ and $\monadic{v}_{d'}=\uopl{pure}(v_{d'}^1+v_{d'}^2)$. By $\monadic{v}_d^1\coin{q}{d'}\monadic{v}_{d'}^1$ and $\monadic{v}_d^2\coin{q}{d'}\monadic{v}_{d'}^2$, we have $v_d^1=v_{d'}^1$ and $v_d^2=v_{d'}^2$, whence $\monadic{v}_d=\monadic{v}_{d'}$. Consequently, $\monadic{v}_d\coin{q}{d'}\monadic{v}_{d'}$. \item If $d_0$ is a strict supertype of~$d'$ then $\monadic{v}_d\coin{q}{d'}\monadic{v}_{d'}$ vacuously. \end{itemize} Along with $\gamma_d^2\coin{\Gamma}{d'}\gamma_{d'}^2$ and $\omicron_1\omicron_2\coinpure{d'}\omicron'_1\omicron'_2$, this implies the desired claim. \item Let $e=\assertexpr{e_1}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:q'\mbox{,}\\ q'=\qualty{\boolmodty{\mbox{\lstinline+N+}}}{\mbox{\lstinline+$post+}}{d_1} \end{array} \] and \[ \begin{array}{l} \semd{e_1}\gamma_d\phi=\uopl{pure}(\monadic{v}_d^1,\gamma_d^1,\omicron_1)\mbox{,}\\ \monadic{v}_d^1\ne\uopl{pure}\mbox{\bfseries ff}\mbox{,}\quad\monadic{v}_d=\uopl{pure}\mbox{\textoneoldstyle}\mbox{,}\quad\gamma'_d=\gamma_d^1\mbox{,}\quad\omicron=\omicron_1\mbox{.} \end{array} \] By the induction hypothesis about~$e_1$, $\sem{e_1}_{d'}\gamma_{d'}\phi=\uopl{pure}(\monadic{v}_{d'}^1,\gamma_{d'}^1,\omicron'_1)$ where $\monadic{v}_d^1\coin{q'}{d'}\monadic{v}_{d'}^1$, $\gamma_d^1\coin{\Gamma}{d'}\gamma_{d'}^1$ and $\omicron_1\coinpure{d'}\omicron'_1$. If $d_1\mathrel{\mathchar"13C\mathchar"3A} d'$ then $\monadic{v}_d^1\coin{q'}{d'}\monadic{v}_{d'}^1$ implies $\monadic{v}_d^1=\uopl{pure}\mbox{\bfseries tt}=\monadic{v}_{d'}^1$, establishing $\monadic{v}_{d'}^1\ne\uopl{pure}\mbox{\bfseries ff}$. If $d_1$ is a strict superdomain of $d'$ then, by exactness, $\monadic{v}_{d'}^1=\top\ne\uopl{pure}\mbox{\bfseries ff}$. Therefore, \[ \begin{array}{l} \sem{\assertexpr{e_1}}_{d'}\gamma_{d'}\phi=\uopl{pure}(\monadic{v}_{d'},\gamma'_{d'},\omicron')\mbox{,}\\ \monadic{v}_{d'}=\uopl{pure}\mbox{\textoneoldstyle}\mbox{,}\quad\gamma'_{d'}=\gamma_{d'}^1\mbox{,}\quad\omicron'=\omicron'_1\mbox{.} \end{array} \] The desired claim follows since $\uopl{pure}\mbox{\textoneoldstyle}\coin{q}{d'}\uopl{pure}\mbox{\textoneoldstyle}$, $\gamma_d^1\coin{\Gamma}{d'}\gamma_{d'}^1$ and $\omicron_1\coinpure{d'}\omicron'_1$. \item Let $e=\ofty{\getexpr{d''}{e_1}}{q}$. Then $\monadic{v}_d=\branching{\uopl{allpure}(\phi_{d''}(k))&\mbox{if $d''\mathrel{\mathchar"13C\mathchar"3A} d$}\\\top&\mbox{otherwise}}$, $\gamma'_d=\gamma_d$ and $\omicron=\epsilon$. On the other hand, $\sem{\getexpr{d''}{e_1}}_{d'}\gamma_{d'}\phi=\uopl{pure}(\monadic{v}_{d'},\gamma'_{d'},\omicron')$ where $\monadic{v}_{d'}=\branching{\uopl{allpure}(\phi_{d''}(k))&\mbox{if $d''\mathrel{\mathchar"13C\mathchar"3A} d'$}\\\top&\mbox{otherwise}}$, $\gamma'_{d'}=\gamma_{d'}$, $\omicron'=\epsilon$. Consider three cases: \begin{itemize} \item If $d''\mathrel{\mathchar"13C\mathchar"3A} d'$ then $d''\mathrel{\mathchar"13C\mathchar"3A} d$, whence $\monadic{v}_d=\uopl{allpure}(\phi_{d''}(k))=\monadic{v}_{d'}$ and therefore $\monadic{v}_d\coin{q}{d'}\monadic{v}_{d'}$; \item If $d''$ is a strict superdomain of~$d'$ then $\monadic{v}_d\coin{q}{d'}\monadic{v}_{d''}$ vacuously. \end{itemize} Moreover, $\gamma_d\coin{\Gamma}{d'}\gamma_{d'}$ by assumption. The desired claim follows. \item Let $e=\ifexpr{e_1}{e_2}{e_3}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:q'! D_1\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:q! D_2\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_3:q! D_3\mbox{,}\\ q'=\qualty{\boolmodty{\mbox{\lstinline+N+}}}{\mbox{\lstinline+$pre+}}{d_1}\mbox{,}\quad \gen{d_1}\supseteq\gen{s_0}\cup\gen{d_0}\cup D_2\cup D_3\mbox{,} \end{array} \] and \[ \semd{e_1}\gamma_d\phi=\uopl{pure}(\monadic{v}_d^1,\gamma_d^1,\omicron_1)\mbox{.} \] By the induction hypothesis, $\sem{e_1}_{d'}\gamma_{d'}\phi=\uopl{pure}(\monadic{v}_{d'}^1,\gamma_{d'}^1,\omicron'_1)$ where $\monadic{v}_d^1\coin{q'}{d'}\monadic{v}_{d'}^1$, $\gamma_d^1\coin{\Gamma}{d'}\gamma_{d'}^1$ and $\omicron_1\coinpure{d'}\omicron'_1$. Consider three cases: \begin{itemize} \item If $\monadic{v}_d^1=\uopl{pure}\mbox{\bfseries tt}$ then $\semd{e_2}\gamma_d^1\phi=\uopl{pure}(\monadic{v}_d^2,\gamma_d^2,\omicron_2)$ and $\monadic{v}_d=\monadic{v}_d^2$, $\gamma'_d=\gamma_d^2$, $\omicron=\omicron_1\omicron_2$. By the induction hypothesis, $\sem{e_2}_{d'}\gamma_{d'}^1\phi=\uopl{pure}(\monadic{v}_{d'}^2,\gamma_{d'}^2,\omicron'_2)$ where $\monadic{v}_d^2\coin{q}{d'}\monadic{v}_{d'}^2$, $\gamma_d^2\coin{\Gamma}{d'}\gamma_{d'}^2$, $\omicron_2\coinpure{d'}\omicron'_2$. If $d_1\mathrel{\mathchar"13C\mathchar"3A} d'$ then $\monadic{v}_{d'}^1=\uopl{pure}\mbox{\bfseries tt}$, whence $\sem{\ifexpr{e_1}{e_2}{e_3}}_{d'}\gamma_{d'}\phi=\uopl{pure}(\monadic{v}_{d'},\gamma'_{d'},\omicron')$ where $\monadic{v}_{d'}=\monadic{v}_{d'}^2$, $\gamma'_{d'}=\gamma_{d'}^2$, $\omicron'=\omicron'_1\omicron'_2$. The desired claim follows. If $d_1$ is a strict supertype of~$d'$ then, by exactness, $\monadic{v}_{d'}^1=\top$. Therefore we obtain $\sem{\ifexpr{e_1}{e_2}{e_3}}_{d'}\gamma_{d'}\phi=\uopl{pure}(\monadic{v}_{d'},\gamma'_{d'},\omicron')$ where $\monadic{v}_{d'}=\top$, $\gamma'_{d'}=\gamma_{d'}^1$, $\omicron'=\omicron'_1$. As $d_1\mathrel{\mathchar"13C\mathchar"3A} d_0$, also $d_0$ is a strict supertype of~$d'$, vacuously implying $\monadic{v}_d\coin{q}{d'}\monadic{v}_{d'}$. Finally, note that $d'\in D_2$ would imply $d_1\mathrel{\mathchar"13C\mathchar"3A} d'$ and introduce contradiction, thus $d'\notin D_2$. By Theorem~\ref{semantics:effthm}, $\gamma_d^1\coin{\Gamma}{d'}\gamma_d^2$. As also $\gamma_d^1\coin{\Gamma}{d'}\gamma_{d'}^1$, Lemma~\ref{semantics:coinlemma} establishes $\gamma_d^2\coin{\Gamma}{d'}\gamma_{d'}^1$. By $D_2$ being upward closed, we also have $\mbox{\lstinline+@public+}\notin D_2$, whence Theorem~\ref{semantics:outputthm} gives $\omicron_2=\epsilon$. Thus $\omicron=\omicron_1$. The desired result follows. \item The case $\monadic{v}_d^1=\uopl{pure}\mbox{\bfseries ff}$ is similar to the previous case. \item If $\monadic{v}_d^1=\top$ then $\monadic{v}_d=\top$, $\gamma'_d=\gamma_d^1$, $\omicron=\omicron_1$. By exactness, $d_1$ is a strict supertype of~$d$. Hence $d_1$ is a strict supertype of~$d'$, implying $\monadic{v}_{d'}^1=\top$. We get $\sem{\ifexpr{e_1}{e_2}{e_3}}_{d'}\gamma_{d'}\phi=\uopl{pure}(\monadic{v}_{d'},\gamma'_{d'},\omicron')$ where $\monadic{v}_{d'}=\top$, $\gamma'_{d'}=\gamma_{d'}^1$, $\omicron'=\omicron'_1$. The desired claim follows. \end{itemize} \item Let $e=\forexpr{x}{e_1}{e_2}{e_3}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:q'! D_1\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:q'! D_2\mbox{,}\\ (x:q'),\Gamma\mbox{\ $\vdash$\ } e_3:q''! D_3\mbox{,}\\ q'=\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0}\mbox{,}\quad q''=\qualty{t_1}{s_1}{d_1}\mbox{,}\quad t_0=\listty{q''}\mbox{,}\quad s_0=\mbox{\lstinline+$pre+}\mbox{,}\\ \gen{d_0}\supseteq\gen{s_1}\cup\gen{d_1}\cup D_3\mbox{,} \end{array} \] and \[ \begin{array}{l} \semd{e_1}\gamma_d\phi=\uopl{pure}(\monadic{v}_d^1,\gamma_d^1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_d^1\phi=\uopl{pure}(\monadic{v}_d^2,\gamma_d^2,\omicron_2)\mbox{.} \end{array} \] By the induction hypothesis, $\sem{e_1}_{d'}\gamma_{d'}\phi=\uopl{pure}(\monadic{v}_{d'}^1,\gamma_{d'}^1,\omicron'_1)$ where $\monadic{v}_d^1\coin{q'}{d'}\monadic{v}_{d'}^1$, $\gamma_d^1\coin{\Gamma}{d'}\gamma_{d'}^1$, $\omicron_1\coinpure{d'}\omicron'_1$. Now the induction hypothesis gives $\sem{e_2}_{d'}\gamma_{d'}^1\phi=\uopl{pure}(\monadic{v}_{d'}^2,\gamma_{d'}^2,\omicron'_2)$ where $\monadic{v}_d^2\coin{q'}{d'}\monadic{v}_{d'}^2$, $\gamma_d^2\coin{\Gamma}{d'}\gamma_{d'}^2$, $\omicron_2\coinpure{d'}\omicron'_2$. Consider two cases: \begin{itemize} \item If $\monadic{v}_d^1=\uopl{pure} i_1$, $\monadic{v}_d^2=\uopl{pure} i_2$ then, denoting $n=\max(0,i_2-i_1)$, we have \[ \begin{array}{l} \semd{e_3}((x,\uopl{pure} i_1),\gamma_d^2)\phi=\uopl{pure}(\monadic{v}_d^3,\gamma_d^3,\omicron_3)\mbox{,}\\ \semd{e_3}([x\mapsto\uopl{pure}(i_1+1)]\gamma_d^3)\phi=\uopl{pure}(\monadic{v}_d^4,\gamma_d^4,\omicron_4)\mbox{,}\\ \dotfill\\ \semd{e_3}([x\mapsto\uopl{pure}(i_1+n-1)]\gamma_d^{n+1})\phi=\uopl{pure}(\monadic{v}_d^{n+2},\gamma_d^{n+2},\omicron_{n+2})\mbox{,}\\ \monadic{v}_d=\uopl{pure}(\monadic{v}_d^3,\ldots,\monadic{v}_d^{n+2})\mbox{,}\quad\gamma'_d=\uopl{tail}\gamma_d^{n+2}\mbox{,}\quad\omicron=\omicron_1\ldots\omicron_{n+2}\mbox{.} \end{array} \] As $\uopl{pure} i_1\coin{q'}{d'}\uopl{pure} i_1$ and $\gamma_d^2\coin{\Gamma}{d'}\gamma_{d'}^2$, we have $(x,\uopl{pure} i_1),\gamma_d^2\coin{\Gamma'}{d'}\left((x,\uopl{pure} i_1),\gamma_{d'}^2\right)$ where $\Gamma'=((x:q'),\Gamma)$. By the induction hypothesis, $\sem{e_3}_{d'}((x,\uopl{pure} i_1),\gamma_{d'}^2)\phi=\uopl{pure}(\monadic{v}_{d'}^3,\gamma_{d'}^3,\omicron'_3)$ where $\monadic{v}_d^3\coin{q''}{d'}\monadic{v}_{d'}^3$, $\gamma_d^3\coin{\Gamma'}{d'}\gamma_{d'}^3$ and $\omicron_3\coinpure{d'}\omicron'_3$. Replacing $i_1$ with $i_1+k$ does not violate the necessary properties, so we similarly get $\sem{e_3}_{d'}([x\mapsto\uopl{pure}(i_1+k-3)]\gamma_{d'}^{k-1})\phi=\uopl{pure}(\monadic{v}_{d'}^k,\gamma_{d'}^k,\omicron'_k)$ where $\monadic{v}_d^k\coin{q''}{d'}\monadic{v}_{d'}^k$, $\gamma_d^k\coin{\Gamma'}{d'}\gamma_{d'}^k$ and $\omicron_k\coinpure{d'}\omicron'_k$, for every $k=4,\ldots,n+2$. If $d_0\mathrel{\mathchar"13C\mathchar"3A} d'$ then the above implies $\monadic{v}_{d'}^1=\uopl{pure} i_1$ and $\monadic{v}_{d'}^2=\uopl{pure} i_2$, whence we obtain $\sem{\forexpr{x}{e_1}{e_2}{e_3}}_{d'}\gamma_{d'}\phi=\uopl{pure}(\monadic{v}_{d'},\gamma'_{d'},\omicron')$ where $\monadic{v}_{d'}=\uopl{pure}(\monadic{v}_{d'}^3,\ldots,\monadic{v}_{d'}^{n+2})$, $\gamma'_{d'}=\gamma_{d'}^{n+2}$ and $\omicron'=\omicron'_1\ldots\omicron'_{n+2}$. Thus $\monadic{v}_d\coin{q_0}{d'}\monadic{v}_{d'}$, $\gamma'_d\coin{\Gamma}{d'}\gamma'_{d'}$, $\omicron\coinpure{d'}\omicron'$ and the desired claim follows. If $d_0$ is a strict superdomain of~$d'$ then $\monadic{v}_{d'}^1=\monadic{v}_{d'}^2=\top$ and $\sem{\forexpr{x}{e_1}{e_2}{e_3}}_{d'}\gamma_{d'}\phi=\uopl{pure}(\monadic{v}_{d'},\gamma'_{d'},\omicron')$ where $\monadic{v}_{d'}=\top$, $\gamma'_{d'}=\gamma_{d'}^2$, $\omicron'=\omicron'_1\omicron'_2$. Then $\monadic{v}_d^{n+2}\coin{q_0}{d'}\top$ vacuously. Assuming $d'\in D_3$ would give $d_0\mathrel{\mathchar"13C\mathchar"3A} d'$ by $\gen{d_0}\supseteq D_3$, hence $d'\notin D_3$. So Theorem~\ref{semantics:effthm} implies \[ \begin{array}{l} \left((x,\uopl{pure} i_1),\gamma_d^2\right)\coin{\Gamma'}{d'}\gamma_d^3\mbox{,}\\{} [x\mapsto\uopl{pure}(i_1+1)]\gamma_d^3\coin{\Gamma'}{d'}\gamma_d^4\mbox{,}\\ \dotfill\\{} [x\mapsto\uopl{pure}(i_1+n-1)]\gamma_d^{n+1}\coin{\Gamma'}{d'}\gamma_d^{n+2}\mbox{.} \end{array} \] We also have $\gamma_d^k\coin{\Gamma'}{d'}[x\mapsto\uopl{pure}(i_1+k-2)]\gamma_d^k$ for every $k=3,\ldots,n+1$ since monadic values of the additional variable~$x$ are coincident vacuously. Lemma~\ref{semantics:coinlemma} now implies $\left((x,\uopl{pure} i_1),\gamma_d^2\right)\coin{\Gamma'}{d'}\gamma_d^{n+2}$. Hence also $\gamma_d^2\coin{\Gamma}{d'}\uopl{tail}\gamma_d^{n+2}$. As we also have $\gamma_d^2\coin{\Gamma}{d'}\gamma_{d'}^2$, Lemma~\ref{semantics:coinlemma} gives $\gamma_d^{n+2}\coin{\Gamma}{d'}\gamma_{d'}^2$. Furthermore, as $d'\notin D_3$ implies $\mbox{\lstinline+@public+}\notin D_3$ by $D_3$ being upward closed, Theorem~\ref{semantics:outputthm} gives $\omicron_3=\ldots=\omicron_{n+2}=\epsilon$. Hence $\omicron=\omicron_1\omicron_2$ and the desired result follows. \item If $\monadic{v}_d^1=\top$ or $\monadic{v}_d^2=\top$ then \[ \monadic{v}_d=\top\mbox{,}\quad\gamma'_d=\gamma_d^2\mbox{,}\quad\omicron=\omicron_1\omicron_2\mbox{.} \] By exactness, $d_0$ is a strict superdomain of~$d$, implying that $d_0$ is also a strict superdomain of~$d'$. Hence, by exactness, $\monadic{v}_{d'}^1=\top$ or $\monadic{v}_{d'}^2=\top$, implying $\sem{\forexpr{x}{e_1}{e_2}{e_3}}_{d'}\gamma_{d'}\phi=\uopl{pure}(\monadic{v}_{d'},\gamma'_{d'},\omicron')$ where $\monadic{v}_{d'}=\top$, $\gamma'_{d'}=\gamma_{d'}^2$, $\omicron'=\omicron'_1\omicron'_2$. The desired claim follows. \end{itemize} \item Let $e=\wireexpr{e_1}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:q'\mbox{,}\\ s_0=\mbox{\lstinline+$post+}\mbox{,}\quad q'=\qualty{t_0}{\mbox{\lstinline+$pre+}}{d_0}\mbox{,} \end{array} \] where $t_0$ is $\uintmodty{\mbox{\lstinline+N+}}$ or $\boolmodty{\mbox{\lstinline+N+}}$, and \[ \begin{array}{l} \semd{e_1}\gamma_d\phi=\uopl{pure}(\monadic{v}_d^1,\gamma_d^1,\omicron_1)\mbox{,}\\ \monadic{v}_d=\monadic{v}_d^1\mbox{,}\quad\gamma'_d=\gamma_d^1\mbox{,}\quad\omicron=\lam{d''}{\branching{(\omicron_1)_{d''}\monadic{v}_d^1&\mbox{if $d''=d_0$}\\(\omicron_1)_{d''}&\mbox{otherwise}}}\mbox{.} \end{array} \] By the induction hypothesis about~$e_1$, $\sem{e_1}_{d'}\gamma_{d'}\phi=\uopl{pure}(\monadic{v}_{d'}^1,\gamma_{d'}^1,\omicron'_1)$ where $\monadic{v}_d^1\coin{q'}{d'}\monadic{v}_{d'}^1$, $\gamma_d^1\coin{\Gamma}{d'}\gamma_{d'}^1$ and $\omicron_1\coinpure{d'}\omicron'_1$. Hence \[ \begin{array}{l} \sem{\wireexpr{e_1}}_{d'}\gamma_{d'}\phi=\uopl{pure}(\monadic{v}_{d'},\gamma'_{d'},\omicron')\mbox{,}\\ \monadic{v}_{d'}=\monadic{v}_{d'}^1\mbox{,}\quad\gamma'_{d'}=\gamma_{d'}^1\mbox{,}\quad\omicron'=\lam{d''}{\branching{(\omicron'_1)_{d''}\monadic{v}_{d'}^1&\mbox{if $d''=d_0$}\\(\omicron'_1)_{d''}&\mbox{otherwise}}}\mbox{.} \end{array} \] The claim $\monadic{v}_d\coin{q}{d'}\monadic{v}_{d'}$ follows since relations $\coin{q}{d'}$ and $\coin{q'}{d'}$ are equal. The claim $\gamma'_d\coin{\Gamma}{d'}\gamma'_{d'}$ is implied by the above. Finally, $\monadic{v}_d^1\coin{q}{d'}\monadic{v}_{d'}^1$ means that if $d_0\mathrel{\mathchar"13C\mathchar"3A} d'$ then $\monadic{v}_d^1=\uopl{pure} v_d^1=\monadic{v}_{d'}^1$ where $v_d^1\in\mathbb{N}\cup\mathbb{B}$. Hence if $d_0\mathrel{\mathchar"13C\mathchar"3A} d'$ then $\omicron_{d_0}=\omicron'_{d_0}$. If $d_0$~{}is a strict superdomain of~$d'$ then the lengths of $\omicron_{d_0}$ and $\omicron'_{d_0}$ are equal since both are one more than the common length of $(\omicron_1)_{d_0}$ and $(\omicron'_1)_{d_0}$. \item Let $e=\castexpr{e_1}{d_0}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:q'\mbox{,}\\ q'=\qualty{t_0}{s_0}{d_1}\mbox{,}\quad d_1\mathrel{\mathchar"13C\mathchar"3A} d_0\mbox{,}\quad\gen{d_0}\supseteq\gen{t_0} \end{array} \] and \[ \begin{array}{l} \semd{e_1}\gamma_d\phi=\uopl{pure}(\monadic{v}_d^1,\gamma_d^1,\omicron_1)\mbox{,}\\ \monadic{v}_d=\branching{\monadic{v}_d^1&\mbox{if $d_0\mathrel{\mathchar"13C\mathchar"3A} d$}\\\top&\mbox{otherwise}}\mbox{,}\quad\gamma'_d=\gamma_d^1\mbox{,}\quad\omicron=\omicron_1\mbox{.} \end{array} \] By the induction hypothesis about~$e_1$, $\sem{e_1}_{d'}\gamma_{d'}\phi=\uopl{pure}(\monadic{v}_{d'}^1,\gamma_{d'}^1,\omicron'_1)$ where $\monadic{v}_d^1\coin{q'}{d'}\monadic{v}_{d'}^1$, $\gamma_d^1\coin{\Gamma}{d'}\gamma_{d'}^1$, $\omicron_1\coinpure{d'}\omicron'_1$. By Lemma~\ref{semantics:castcoinlemma}, the first of these implies $\monadic{v}_d^1\coin{q}{d'}\monadic{v}_{d'}^1$. We obtain $\sem{\castexpr{e_1}{d_0}}_{d'}\gamma_{d'}\phi=\uopl{pure}(\monadic{v}_{d'},\gamma'_{d'},\omicron')$ where $\monadic{v}_{d'}=\branching{\monadic{v}_{d'}^1&\mbox{if $d_0\mathrel{\mathchar"13C\mathchar"3A} d'$}\\\top&\mbox{otherwise}}$, $\gamma'_{d'}=\gamma_{d'}^1$, $\omicron'=\omicron'_1$. Consider two cases: \begin{itemize} \item If $d_0\mathrel{\mathchar"13C\mathchar"3A} d'$ then $d_0\mathrel{\mathchar"13C\mathchar"3A} d$, implying $\monadic{v}_d=\monadic{v}_d^1$ and $\monadic{v}_{d'}=\monadic{v}_{d'}^1$. The desired claim follows. \item If $d_0$ is a strict superdomain of~$d'$ then $\monadic{v}_d\coin{q}{d'}\monadic{v}_{d'}$ holds vacuously. The desired claim follows. \end{itemize} \item Let $e=(\assignexpr{e_1}{e_2})$. Then $q=\qualty{\mbox{\lstinline+()+}}{\mbox{\lstinline+$pre+}}{\mbox{\lstinline+@public+}}$. Let $e_1=\loadexpr{\loadexpr{\loadexpr{x}{y_1}}{y_2}\ldots}{y_n}$. By Lemma~\ref{typesystem:lhslemma}, \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } y_k:q_k\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } x:q'\mbox{,}\\ q_k=\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_k}\mbox{,}\quad q'=\qualty{\listty{\ldots\listty{\qualty{\listty{\qualty{\listty{q_{n+1}}}{\mbox{\lstinline+$pre+}}{d_n}}}{\mbox{\lstinline+$pre+}}{d_{n-1}}}\ldots}}{\mbox{\lstinline+$pre+}}{d_1} \end{array} \] and \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:q_{n+1}\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:q_{n+1}\mbox{,}\\ q_{n+1}=\qualty{t}{s}{d_{n+1}}\mbox{.} \end{array} \] We also have \[ \begin{array}{l} \semd{y_1}\gamma_d\phi=\uopl{pure}(\monadic{i}_d^1,\gamma_d^1,\omicron_1)\mbox{,}\\ \semd{y_2}\gamma_d^1\phi=\uopl{pure}(\monadic{i}_d^2,\gamma_d^2,\omicron_2)\mbox{,}\\ \dotfill\\ \semd{y_n}\gamma_d^{n-1}\phi=\uopl{pure}(\monadic{i}_d^n,\gamma_d^n,\omicron_n)\mbox{,}\\ \semd{e_2}\gamma_d^n\phi=\uopl{pure}(\monadic{r}_d,\gamma_d^{n+1},\omicron_{n+1})\mbox{,}\\ \monadic{v}_d=\uopl{pure}\mbox{\textoneoldstyle}\mbox{,}\quad\gamma'_d=[x\mapsto\uopl{upd}(\lookup{\gamma_d}{x},\monadic{i}_d^1\ldots\monadic{i}_d^n,\monadic{r}_d)]\gamma_d^{n+1}\mbox{,}\quad\omicron=\omicron_1\ldots\omicron_{n+1}\mbox{.} \end{array} \] Applying repeatedly the induction hypothesis, we get $\sem{y_k}_{d'}\gamma_{d'}^{k-1}\phi=\uopl{pure}(\monadic{i}_{d'}^k,\gamma_{d'}^k,\omicron'_k)$ where $\monadic{i}_d^k\coin{q_k}{d'}\monadic{i}_{d'}^k$, $\gamma_d^k\coin{\Gamma}{d'}\gamma_{d'}^k$ and $\omicron_k\coinpure{d'}\omicron'_k$ for each $k=1,\ldots,n$ (denoting $\gamma_{d'}^0=\gamma_{d'}$). In addition, $\sem{e_2}_{d'}\gamma_{d'}^n\phi=\uopl{pure}(\monadic{r}_{d'},\gamma_{d'}^{n+1},\omicron'_{k+1})$ where $\monadic{r}_d\coin{q_{n+1}}{d'}\monadic{r}_{d'}$, $\gamma_d^{n+1}\coin{\Gamma}{d'}\gamma_{d'}^{n+1}$ and $\omicron_{n+1}\coinpure{d'}\omicron'_{n+1}$. By Lemma~\ref{semantics:updexactcoinlemma}, $\uopl{upd}(\lookup{\gamma_{d'}}{x},\monadic{i}_{d'}^1\ldots\monadic{i}_{d'}^n,\monadic{r}_{d'})$ is well-defined and \[ \uopl{upd}(\lookup{\gamma_d}{x},\monadic{i}_d^1\ldots\monadic{i}_d^n,\monadic{r}_d)\coin{q'}{d'}\uopl{upd}(\lookup{\gamma_{d'}}{x},\monadic{i}_{d'}^1\ldots\monadic{i}_{d'}^n,\monadic{r}_{d'})\mbox{.} \] We conclude $[x\mapsto\uopl{upd}(\lookup{\gamma_d}{x},\monadic{i}_d^1\ldots\monadic{i}_d^n,\monadic{r}_d)]\gamma_d^{n+1}\coin{\Gamma}{d'}[x\mapsto\uopl{upd}(\lookup{\gamma_{d'}}{x},\monadic{i}_{d'}^1\ldots\monadic{i}_{d'}^n,\monadic{r}_{d'})]\gamma_{d'}^{n+1}$ and the desired claim follows. \item Let $e=\loadexpr{e_1}{e_2}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:q_1\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:q_2\mbox{,}\\ q_1=\qualty{\listty{q}}{\mbox{\lstinline+$pre+}}{d_1}\mbox{,}\quad q_2=\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_1} \end{array} \] and \[ \begin{array}{l} \semd{e_1}\gamma_d\phi=\uopl{pure}(\monadic{a}_d,\gamma_d^1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_d^1\phi=\uopl{pure}(\monadic{i}_d,\gamma_d^2,\omicron_2)\mbox{,}\\ \monadic{v}_d=\mcomp{a_d\gets\monadic{a}_d;\; i_d\gets\monadic{i}_d;\; (a_d)_{i_d}}\mbox{,}\quad\gamma'_d=\gamma_d^2\mbox{,}\quad\omicron=\omicron_1\omicron_2\mbox{.} \end{array} \] By the induction hypothesis about $e_1$, $\sem{e_1}_{d'}\gamma_{d'}\phi=\uopl{pure}(\monadic{a}_{d'},\gamma_{d'}^1,\omicron'_1)$ where $\monadic{a}_d\coin{q_1}{d'}\monadic{a}_{d'}$, $\gamma_d^1\coin{\Gamma}{d'}\gamma_{d'}^1$ and $\omicron_1\coinpure{d'}\omicron'_1$. Hence by the induction hypothesis about $e_2$, $\sem{e_2}_{d'}\gamma_{d'}^1\phi=\uopl{pure}(\monadic{i}_{d'},\gamma_{d'}^2,\omicron'_2)$ where $\monadic{i}_d\coin{q_2}{d'}\monadic{i}_{d'}$, $\gamma_d^2\coin{\Gamma}{d'}\gamma_{d'}^2$ and $\omicron_2\coinpure{d'}\omicron'_2$. Thus \[ \begin{array}{l} \sem{\loadexpr{e_1}{e_2}}_{d'}\gamma_{d'}\phi=\uopl{pure}(\monadic{v}_{d'},\gamma'_{d'},\omicron')\mbox{,}\\ \monadic{v}_{d'}=\mcomp{a_{d'}\gets\monadic{a}_{d'};\; i_{d'}\gets\monadic{i}_{d'};\;(a_{d'})_{i_{d'}}}\mbox{,}\quad\gamma'_{d'}=\gamma_{d'}^2\mbox{,}\quad\omicron'=\omicron'_1\omicron'_2\mbox{.} \end{array} \] Consider two cases: \begin{itemize} \item If $d_0\mathrel{\mathchar"13C\mathchar"3A} d'$ then, by $q$ being well-structured, also $d_1\mathrel{\mathchar"13C\mathchar"3A} d_0\mathrel{\mathchar"13C\mathchar"3A} d'\mathrel{\mathchar"13C\mathchar"3A} d$. Hence we have $\monadic{a}_d=\uopl{pure}(\monadic{a}_d^1,\ldots,\monadic{a}_d^n)$, $\monadic{i}_d=\uopl{pure} i_d$, $\monadic{a}_{d'}=\uopl{pure}(\monadic{a}_{d'}^1,\ldots,\monadic{a}_{d'}^n)$, $\monadic{i}_{d'}=\uopl{pure} i_{d'}$ where $\monadic{a}_d^k\coin{q}{d'}\monadic{a}_{d'}^k$ for every $k=1,\ldots,n$ and $n\geq i_d=i_{d'}\in\mathbb{N}$. This implies $\monadic{v}_d=\monadic{a}_d^{i_d}$ and $\monadic{v}_{d'}=\monadic{a}_{d'}^{i_{d'}}$, whence $\monadic{v}_d\coin{q}{d'}\monadic{v}_{d'}$. \item If $d_0$ is a strict supertype of~$d'$ then $\monadic{v}_d\coin{q}{d'}\monadic{v}_{d'}$ holds vacuously. \end{itemize} Along with $\gamma_d^2\coin{\Gamma}{d'}\gamma_{d'}^2$ and $\omicron_1\omicron_2\coinpure{d'}\omicron'_1\omicron'_2$, this implies the desired claim. \item Let $e=\stmtcomp{\letexpr{x}{e_1}}{e_2}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:q_1\mbox{,}\\ (x:q_1),\Gamma\mbox{\ $\vdash$\ } e_2:q \end{array} \] and \[ \begin{array}{l} \semd{e_1}\gamma_d\phi=\uopl{pure}(\monadic{v}_d^1,\gamma_d^1,\omicron_1)\mbox{,}\\ \semd{e_2}((x,\monadic{v}_d^1),\gamma_d^1)\phi=\uopl{pure}(\monadic{v}_d^2,\gamma_d^2,\omicron_2)\mbox{,}\\ \monadic{v}_d=\monadic{v}_d^2\mbox{,}\quad\gamma'_d=\uopl{tail}\gamma_d^2\mbox{,}\quad\omicron=\omicron_1\omicron_2\mbox{.} \end{array} \] By the induction hypothesis about $e_1$, $\sem{e_1}_{d'}\gamma_{d'}\phi=\uopl{pure}(\monadic{v}_{d'}^1,\gamma_{d'}^1,\omicron'_1)$ where $\monadic{v}_d^1\coin{q_1}{d'}\monadic{v}_{d'}^1$, $\gamma_d^1\coin{\Gamma}{d'}\gamma_{d'}^1$ and $\omicron_1\coinpure{d'}\omicron'_1$. Denoting $\Gamma'=((x:q_1),\Gamma)$, we therefore obtain $\left((x,\monadic{v}_d^1),\gamma_d^1\right)\coin{\Gamma'}{d'}\left((x,\monadic{v}_{d'}^1),\gamma_{d'}^1\right)$. By the induction hypothesis about $e_2$, $\sem{e_2}_{d'}((x,\monadic{v}_{d'}^1),\gamma_{d'}^1)\phi=\uopl{pure}(\monadic{v}_{d'}^2,\gamma_{d'}^2,\omicron'_2)$ where $\monadic{v}_d^2\coin{q}{d'}\monadic{v}_{d'}^2$, $\gamma_d^2\coin{\Gamma'}{d'}\gamma_{d'}^2$ and $\omicron_2\coinpure{d'}\omicron'_2$. Thus also $\uopl{tail}\gamma_d^2\coin{\Gamma}{d'}\uopl{tail}\gamma_{d'}^2$. As \[ \begin{array}{l} \sem{\stmtcomp{\letexpr{x}{e_1}}{e_2}}_{d'}\gamma_{d'}\phi=\uopl{pure}(\monadic{v}_{d'},\gamma'_{d'},\omicron')\mbox{,}\\ \monadic{v}_{d'}=\monadic{v}_{d'}^2\mbox{,}\quad\gamma'_{d'}=\uopl{tail}\gamma_{d'}^2\mbox{,}\quad\omicron'=\omicron'_1\omicron'_2\mbox{,} \end{array} \] the desired claim follows. \item Let $e=\stmtcomp{e_1}{e_2}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:q_1\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:q \end{array} \] and \[ \begin{array}{l} \semd{e_1}\gamma_d\phi=\uopl{pure}(\monadic{v}_d^1,\gamma_d^1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_d^1\phi=\uopl{pure}(\monadic{v}_d^2,\gamma_d^2,\omicron_2)\mbox{,}\\ \monadic{v}_d=\monadic{v}_d^2\mbox{,}\quad\gamma'_d=\gamma_d^2\mbox{,}\quad\omicron=\omicron_1\omicron_2\mbox{.} \end{array} \] By the induction hypothesis about $e_1$, $\sem{e_1}_{d'}\gamma_{d'}\phi=\uopl{pure}(\monadic{v}_{d'}^1,\gamma_{d'}^1,\omicron'_1)$ where $\monadic{v}_d^1\coin{q_1}{d'}\monadic{v}_{d'}^1$, $\gamma_d^1\coin{\Gamma}{d'}\gamma_{d'}^1$ and $\omicron_1\coinpure{d'}\omicron'_1$. By the induction hypothesis about $e_2$, $\sem{e_2}_{d'}\gamma_{d'}^1\phi=\uopl{pure}(\monadic{v}_{d'}^2,\gamma_{d'}^2,\omicron'_2)$ where $\monadic{v}_d^2\coin{q}{d'}\monadic{v}_{d'}^2$, $\gamma_d^2\coin{\Gamma}{d'}\gamma_{d'}^2$ and $\omicron_2\coinpure{d'}\omicron'_2$. As \[ \begin{array}{l} \sem{\stmtcomp{e_1}{e_2}}_{d'}\gamma_{d'}\phi=\uopl{pure}(\monadic{v}_{d'},\gamma'_{d'},\omicron')\mbox{,}\\ \monadic{v}_{d'}=\monadic{v}_{d'}^2\mbox{,}\quad\gamma'_{d'}=\gamma_{d'}^2\mbox{,}\quad\omicron'=\omicron'_1\omicron'_2\mbox{,} \end{array} \] the desired claim follows. \end{itemize} \end{proof} \begin{theorem}[Theorem~\ref{semantics:correctness}] Let $\Gamma \mbox{\ $\vdash$\ } e : q! D$ with well-structured~$\Gamma$. Let $\gamma_d$, $\gamma\in\mathbf{Env}$ be $\Gamma$-exact in $\mbox{\lstinline+@prover+}$ and in circuit, respectively, such that $\gamma_d\coincirc{\Gamma}\gamma$. Assume that, for all subexpressions of~$e$ of the form $\ofty{\getexpr{d'}{k}}{q'}$, the value $\uopl{allpure}(\phi_{d'}(k))$ is $q'$-exact in $\mbox{\lstinline+@prover+}$. Assume that, for $d=\mbox{\lstinline+@prover+}$, there exist $\monadic{v}_d,\gamma'_d,\omicron$ such that $\semd{e}\gamma_d\phi=\uopl{pure}(\monadic{v}_d,\gamma'_d,\omicron)$. If $\rho$~{}is any pair of stream continuations (one for each of $\mbox{\lstinline+@prover+}$ and $\mbox{\lstinline+@verifier+}$) then $\sem{e}\gamma\phi(\omicron\rho)=\uopl{pure}(\monadic{v},\gamma',\rho)$, where $\monadic{v}$ is $q$-exact and $\gamma'$ is $\Gamma$-exact in circuit. Thereby, $\monadic{v}_d\coincirc{q}\monadic{v}$ and $\gamma'_d\coincirc{\Gamma}\gamma'$. (Here, $\omicron\rho$ denotes the pointwise concatenation of $\omicron$ and $\rho$.) \end{theorem} \begin{proof} Let $q=\qualty{t_0}{s_0}{d_0}$. We proceed by induction on the structure of~$e$: \begin{itemize} \item Let $e=\epsilon$. Then $t_0=\mbox{\lstinline+()+}$, $s_0=\mbox{\lstinline+$pre+}$, $d_0=\mbox{\lstinline+@public+}$ and we have $\monadic{v}_d=\uopl{pure}\mbox{\textoneoldstyle}$, $\gamma'_d=\gamma_d$, $\omicron=\epsilon$. We also have $\sem{e}\gamma\phi\rho=\uopl{pure}(\monadic{v},\gamma',\rho)$ where $\monadic{v}=\uopl{pure}\mbox{\textoneoldstyle}$ and $\gamma'=\gamma$. As $d_0=\mbox{\lstinline+@public+}$ and $t_0$ is primitive, establishing that $\uopl{pure}\mbox{\textoneoldstyle}$ is $q$-exact in circuit reduces to clause~1 of Definition~\ref{semantics:exactdef}. It holds since $\mbox{\textoneoldstyle}\in\mbox{\lstinline+()+}$. Similarly, we obtain $\uopl{pure}\mbox{\textoneoldstyle}\coincirc{q}\uopl{pure}\mbox{\textoneoldstyle}$. By assumption, $\gamma'$ is $\Gamma$-exact in circuit and $\gamma'_d\coincirc{\Gamma}\gamma'$. \item Let $e=\overline{n}$ where $n\in\mathbb{N}$. Then $t_0=\uintmodty{\mbox{\lstinline+N+}}$ and $\monadic{v}_d=\uopl{pure} n$, $\gamma'_d=\gamma_d$, $\omicron=\epsilon$. We also have $\sem{e}\gamma\phi\rho=\uopl{pure}(\monadic{v},\gamma',\rho)$ where $\monadic{v}=\branching{\uopl{pure} n&\mbox{if $s_0=\mbox{\lstinline+$post+}$ or $d_0=\mbox{\lstinline+@public+}$}\\\top&\mbox{otherwise}}$ and $\gamma'=\gamma$. By assumption, $\gamma'$ is $\Gamma$-exact in circuit and $\gamma'_d\coincirc{\Gamma}\gamma'$. Furthermore, we have to study two cases: \begin{itemize} \item If $s_0=\mbox{\lstinline+$post+}$ or $d_0=\mbox{\lstinline+@public+}$ then $\monadic{v}=\uopl{pure} n$. As $t_0$ is primitive, establishing that $\monadic{v}$ is $q$-exact in circuit reduces to clause~1 of Definition~\ref{semantics:exactdef}. It holds since $n$ is an integer. Similarly, we obtain $\uopl{pure} n\coincirc{q}\uopl{pure} n$. \item If $s_0=\mbox{\lstinline+$pre+}$ and $d_0\ne\mbox{\lstinline+@public+}$ then $\monadic{v}=\top$ and establishing that $\monadic{v}$ is $q$-exact in circuit reduces to clause~3 of Definition~\ref{semantics:exactdef}. The former equality is exactly what clause~3 requires. The claim $\monadic{v}_d\coincirc{q}\monadic{v}$ holds vacuously. \end{itemize} \item Let $e=\overline{b}$ where $b\in\mathbb{B}$. This case is analogous to the previous one. \item Let $e=x$. Then $\lookup{\Gamma}{x}=q$ and $\monadic{v}_d=\lookup{\gamma_d}{x}$, $\gamma'_d=\gamma_d$, $\omicron=\epsilon$. We also have $\sem{e}\gamma\phi\rho=\uopl{pure}(\monadic{v},\gamma',\rho)$ where $\monadic{v}=\lookup{\gamma}{x}$, $\gamma'=\gamma$. Hence $\monadic{v}$ is $q$-exact in circuit by the assumption that $\gamma$ is $\Gamma$-exact in circuit and Lemma~\ref{semantics:lookupexactlemma}. Also $\gamma'$ being $\Gamma$-exact in circuit directly follows from assumption. Finally, $\monadic{v}_d\coincirc{q}\monadic{v}$ by $\gamma_d\coincirc{\Gamma}\gamma$, and $\gamma'_d\coincirc{\Gamma}\gamma'$ by assumption. \item Let $e=\addexpr{e_1}{e_2}$. Then $t_0=\uintmodty{\mbox{\lstinline+N+}}$ and \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:q! D_1\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:q! D_2\mbox{,} \end{array} \] and also \[ \begin{array}{l} \semd{e_1}\gamma_d\phi=\uopl{pure}(\monadic{v}_d^1,\gamma_d^1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_d^1\phi=\uopl{pure}(\monadic{v}_d^2,\gamma_d^2,\omicron_2)\mbox{,}\\ \monadic{v}_d=\mcomp{v_d^1\gets\monadic{v}_d^1;\; v_d^2\gets\monadic{v}_d^2;\;\uopl{pure}(v_d^1+v_d^2)},\quad\gamma'_d=\gamma_d^2\mbox{,}\quad\omicron=\omicron_1\omicron_2\mbox{.} \end{array} \] By $\monadic{v}_d^1,\monadic{v}_d^2$ being $q$-exact in $\mbox{\lstinline+@prover+}$, we must have $\monadic{v}_d^1=\uopl{pure} v_d^1$ and $\monadic{v}_d^2=\uopl{pure} v_d^2$, whence $\monadic{v}_d=\uopl{pure}(v_d^1+v_d^2)$. By the induction hypothesis about~$e_1$, $\sem{e_1}\gamma\phi(\omicron_1\omicron_2\rho)=\uopl{pure}(\monadic{v}^1,\gamma^1,\omicron_2\rho)$ where $\monadic{v}^1$ is $q$-exact and $\gamma^1$ is $\Gamma$-exact in circuit, $\monadic{v}_d^1\coincirc{q}\monadic{v}^1$ and $\gamma_d^1\coincirc{\Gamma}\gamma^1$. Now by the induction hypothesis about~$e_2$, $\sem{e_2}\gamma^1\phi(\omicron_1\rho)=\uopl{pure}(\monadic{v}^2,\gamma^2,\rho)$ where $\monadic{v}^2$ is $q$-exact and $\gamma^2$ is $\Gamma$-exact in circuit, $\monadic{v}_d^2\coincirc{q}\monadic{v}^2$ and $\gamma_d^2\coincirc{\Gamma}\gamma^2$. Hence $\sem{e}\gamma\phi(\omicron\rho)=\uopl{pure}(\monadic{v},\gamma',\rho)$ where \[ \monadic{v}=\mcomp{v^1\gets\monadic{v}^1;\; v^2\gets\monadic{v}^2;\;\uopl{pure}(v^1+v^2)},\quad\gamma'=\gamma^2\mbox{.} \] Then $\gamma'$ being $\Gamma$-exact in circuit and $\gamma'_d\coincirc{\Gamma}\gamma'$ are implied by the above. Finally, we have to consider two cases: \begin{itemize} \item If $s_0=\mbox{\lstinline+$post+}$ or $d_0=\mbox{\lstinline+@public+}$ then, by $\monadic{v}^1$ and $\monadic{v}^2$ being $q$-exact in circuit, we have $\monadic{v}^1=\uopl{pure} v^1$ and $\monadic{v}^2=\uopl{pure} v^2$ for integers $v^1,v^2$. Hence $\monadic{v}=\uopl{pure}(v^1+v^2)$ which shows that $\monadic{v}$ is $q$-exact in circuit by clause~1 of Definition~\ref{semantics:exactdef}. Moreover, $\monadic{v}_d^1\coincirc{q}\monadic{v}^1$ and $\monadic{v}_d^2\coincirc{q}\monadic{v}^2$ imply $v_d^1=v^1$ and $v_d^2=v^2$. Hence $\monadic{v}_d\coincirc{q}\monadic{v}$. \item If $s_0=\mbox{\lstinline+$pre+}$ and $d_0\ne\mbox{\lstinline+@public+}$ then, by $\monadic{v}^1$ and $\monadic{v}^2$ being $q$-exact in circuit, we have $\monadic{v}^1=\monadic{v}^2=\top$ and hence also $\monadic{v}=\top$. By clause~3 of Definition~\ref{semantics:exactdef}, $\monadic{v}$ is $q$-exact in circuit. The claim $\monadic{v}_d\coincirc{q}\monadic{v}$ holds vacuously. \end{itemize} \item Let $e=\assertexpr{e_1}$. Then $t_0=\mbox{\lstinline+()+}$, $s_0=\mbox{\lstinline+$pre+}$, $d_0=\mbox{\lstinline+@public+}$ and \[ \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{\boolmodty{\mbox{\lstinline+N+}}}{\mbox{\lstinline+$post+}}{d_1}! D \] and also \[ \begin{array}{l} \semd{e_1}\gamma_d\phi=\uopl{pure}(\monadic{v}_d^1,\gamma_d^1,\omicron_1)\mbox{,}\\ \monadic{v}_d^1\ne\uopl{pure}\mbox{\bfseries ff}\mbox{,}\quad\monadic{v}_d=\uopl{pure}\mbox{\textoneoldstyle}\mbox{,}\quad\gamma'_d=\gamma_d^1\mbox{,}\quad\omicron=\omicron_1\mbox{.} \end{array} \] Denote $q_1=(\qualty{\boolmodty{\mbox{\lstinline+N+}}}{\mbox{\lstinline+$post+}}{d_1})$. By $\monadic{v}_d^1$ being $q_1$-exact in $\mbox{\lstinline+@prover+}$ and $\monadic{v}_d^1\ne\uopl{pure}\mbox{\bfseries ff}$, the only possibility is $\monadic{v}_d^1=\uopl{pure}\mbox{\bfseries tt}$. By the induction hypothesis about $e_1$, $\sem{e_1}\gamma\phi(\omicron_1\rho)=\uopl{pure}(\monadic{v}^1,\gamma^1,\rho)$ where $\monadic{v}^1$ is $q_1$-exact and $\gamma^1$ is $\Gamma$-exact in circuit, $\monadic{v}_d^1\coincirc{q_1}\monadic{v}^1$ and $\gamma_d^1\coincirc{\Gamma}\gamma^1$. Hence $\monadic{v}^1\ne\uopl{pure}\mbox{\bfseries ff}$ since $e_1$ is in $\mbox{\lstinline+$post+}$ which implies that $\uopl{pure}\mbox{\bfseries tt}$ and $\uopl{pure}\mbox{\bfseries ff}$ cannot be $q_1$-coincident in circuit. Consequently, $\sem{e}\gamma\phi(\omicron\rho)=\uopl{pure}(\monadic{v},\gamma',\rho)$ where $\monadic{v}=\uopl{pure}\mbox{\textoneoldstyle}$, $\gamma'=\gamma^1$, whence we have $\monadic{v}$ being $q$-exact in circuit and $\monadic{v}_d\coincirc{q}\monadic{v}$. By the above, we also have $\gamma'$ being $\Gamma$-exact in circuit and $\gamma'_d\coincirc{\Gamma}\gamma'$. \item Let $e=\ofty{\getexpr{d'}{k}}{q}$. Then $\uopl{allpre}_{d'}(q)$, implying $s_0=\mbox{\lstinline+$pre+}$ and $d_0=d'$. Moreover, $\monadic{v}_d=\uopl{allpure}(\phi_{d'}(k))$, $\gamma'_d=\gamma_d$ and $\omicron=\epsilon$. We also have $\sem{e}\gamma\phi\rho=\uopl{pure}(\monadic{v},\gamma',\rho)$ where $\monadic{v}=\branching{\uopl{allpure}(\phi_{d'}(k))&\mbox{if $d'=\mbox{\lstinline+@public+}$}\\\top&\mbox{otherwise}}$ and $\gamma'=\gamma$. Hence, by assumptions, $\gamma'$ is $\Gamma$-exact in circuit and $\gamma'_d\coincirc{\Gamma}\gamma'$. For the other desired claims, consider two cases: \begin{itemize} \item If $d'=\mbox{\lstinline+@public+}$ then $\monadic{v}_d=\uopl{allpure}(\phi_{d'}(k))=\monadic{v}$, implying $\monadic{v}_d\coincirc{q}\monadic{v}$. Moreover, $\monadic{v}$ is $q$-exact in circuit by Lemma~\ref{semantics:approxcirclemma}. \item If $d'\ne\mbox{\lstinline+@public+}$ then $\monadic{v}=\top$ which is $q$-exact since $s_0=\mbox{\lstinline+$pre+}$. Finally, $\monadic{v}_d\coincirc{q}\monadic{v}$ holds vacuously. \end{itemize} \item Let $e=\ifexpr{e_1}{e_2}{e_3}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{\boolmodty{\mbox{\lstinline+N+}}}{\mbox{\lstinline+$pre+}}{d_1}! D_1\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:q! D_2\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_3:q! D_3\mbox{,}\\ \gen{d_1}\supseteq\gen{s_0}\cup \gen{d_0}\cup D_2\cup D_3\mbox{,} \end{array} \] and \[ \semd{e_1}\gamma_d\phi=\uopl{pure}(\monadic{v}_d^1,\gamma_d^1,\omicron_1)\mbox{.} \] Denote $q_1=(\qualty{\boolmodty{\mbox{\lstinline+N+}}}{\mbox{\lstinline+$pre+}}{d_1})$. Note that $\monadic{v}_d^1$ is $q_1$-exact in $\mbox{\lstinline+@prover+}$, whence $\monadic{v}_d^1=\uopl{pure} v_d^1$ where $v_d^1\in\left\{\mbox{\bfseries tt},\mbox{\bfseries ff}\right\}$. Thus we have to consider two cases: \begin{itemize} \item If $\monadic{v}_d^1=\uopl{pure}\mbox{\bfseries tt}$ then $\semd{e_2}\gamma_d^1\phi\omicron_1=\uopl{pure}(\monadic{v}_d^2,\gamma_d^2,\omicron_2)$, $\monadic{v}_d=\monadic{v}_d^2$, $\gamma'_d=\gamma_d^2$, $\omicron=\omicron_1\omicron_2$. By the induction hypothesis about $e_1$, $\sem{e_1}\gamma\phi(\omicron_1\omicron_2\rho)=\uopl{pure}(\monadic{v}^1,\gamma^1,\omicron_2\rho)$ where $\monadic{v}^1$ is $q_1$-exact and $\gamma^1$ is $\Gamma$-exact in circuit, $\monadic{v}_d^1\coincirc{q_1}\monadic{v}^1$ and $\gamma_d^1\coincirc{\Gamma}\gamma^1$. If $d_1=\mbox{\lstinline+@public+}$ then $\monadic{v}_d^1\coincirc{q_1}\monadic{v}^1$ implies $\monadic{v}^1=\uopl{pure}\mbox{\bfseries tt}$. By the induction hypothesis about $e_2$, $\sem{e_2}\gamma^1\phi(\omicron_2\rho)=\uopl{pure}(\monadic{v}^2,\gamma^2,\rho)$ where $\monadic{v}^2$ is $q$-exact and $\gamma^2$ is $\Gamma$-exact in circuit, $\monadic{v}_d^2\coincirc{q}\monadic{v}^2$ and $\gamma_d^2\coincirc{\Gamma}\gamma^2$. Hence $\sem{e}\gamma\phi(\omicron\rho)=\uopl{pure}(\monadic{v},\gamma',\rho)$ where $\monadic{v}=\monadic{v}^2$ and $\gamma'=\gamma^2$. The desired claim follows in this case. If $d_1\ne\mbox{\lstinline+@public+}$ then $\monadic{v}^1$ being $q_1$-exact in circuit implies $\monadic{v}^1=\top$. As $\gen{d_1}\supseteq D_2$ implies $\mbox{\lstinline+@public+}\notin D_2$, Theorems~\ref{semantics:outputthm} and~\ref{semantics:effcircthm} imply $\omicron_2=\epsilon$ and $\gamma_d^1\coincirc{q}\gamma_d^2$. Hence $\sem{e}\gamma\phi(\omicron\rho)=\sem{e}\gamma\phi(\omicron_1\rho)=\uopl{pure}(\monadic{v},\gamma',\rho)$ where $\monadic{v}=\top$ and $\gamma'=\gamma^1$. As $\gen{d_1}\supseteq\gen{d_0}$ implies $d_1\mathrel{\mathchar"13C\mathchar"3A} d_0$, also $d_0\ne\mbox{\lstinline+@public+}$. As $\gen{d_1}\supseteq\gen{s_0}$ implies $s_0=\mbox{\lstinline+$pre+}$, this means that $\top$ is $q$-exact in circuit and $\monadic{v}_d\coincirc{q}\top$ vacuously. We also have $\gamma'_d\coincirc{\Gamma}\gamma'$ because of $\gamma_d^1\coincirc{q}\gamma_d^2$, $\gamma_d^1\coincirc{q}\gamma^1$ and Lemma~\ref{semantics:coinlemma}. Finally, $\gamma'$ is $\Gamma$-exact in circuit by the above. \item The case $\monadic{v}_d^1=\uopl{pure}\mbox{\bfseries ff}$ is analogous. \end{itemize} \item Let $e=\forexpr{x}{e_1}{e_2}{e_3}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0}! D_1\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0}! D_2\mbox{,}\\ (x:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0}),\Gamma\mbox{\ $\vdash$\ } e_3:\qualty{t_1}{s_1}{d_1}! D_3\mbox{,}\\ \gen{d_0}\supseteq\gen{s_1}\cup\gen{d_1}\cup D_3\mbox{,}\\ t_0=\listty{\qualty{t_1}{s_1}{d_1}}\mbox{,}\quad s_0=\mbox{\lstinline+$pre+}\mbox{,} \end{array} \] and \[ \begin{array}{l} \semd{e_1}\gamma_d\phi=\uopl{pure}(\monadic{v}_d^1,\gamma_d^1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_d^1\phi=\uopl{pure}(\monadic{v}_d^2,\gamma_d^2,\omicron_2)\mbox{.} \end{array} \] Denote $q'=(\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_0})$ and $q_1=(\qualty{t_1}{s_1}{d_1})$. Note that $\monadic{v}_d^1,\monadic{v}_d^2$ are $q'$-exact in $\mbox{\lstinline+@prover+}$ by Theorem~\ref{semantics:localthm}. Hence $\monadic{v}_d^1=\uopl{pure} i_1$ and $\monadic{v}_d^2=\uopl{pure} i_2$ where $i_1,i_2\in\mathbb{N}$. Denoting $n=\max(0,i_2-i_1)$, we obtain \[ \begin{array}{l} \semd{e_3}((x,\uopl{pure} i_1),\gamma_d^2)\phi=\uopl{pure}(\monadic{v}_d^3,\gamma_d^3,\omicron_3)\mbox{,}\\ \semd{e_3}([x\mapsto\uopl{pure}(i_1+1)]\gamma_d^3)\phi=\uopl{pure}(\monadic{v}_d^4,\gamma_d^4,\omicron_4)\mbox{,}\\ \dotfill\\ \semd{e_3}([x\mapsto\uopl{pure}(i_1+n-1)]\gamma_d^{n+1})\phi=\uopl{pure}(\monadic{v}_d^{n+2},\gamma_d^{n+2},\omicron_d^{n+2})\mbox{,}\\ \monadic{v}_d=\uopl{pure}(\monadic{v}_d^3,\ldots,\monadic{v}_d^{n+2})\mbox{,}\quad\gamma'_d=\uopl{tail}\gamma_d^{n+2}\mbox{,}\quad\omicron=\omicron_1\ldots\omicron_{n+2}\mbox{.} \end{array} \] By the induction hypothesis about~$e_1$, $\sem{e_1}\gamma\phi(\omicron_1\ldots\omicron_{n+2}\rho)=\uopl{pure}(\monadic{v}^1,\gamma^1,\omicron_2\ldots\omicron_{n+2}\rho)$ where $\monadic{v}^1$ is $q'$-exact and $\gamma^1$ is $\Gamma$-exact in circuit, $\monadic{v}_d^1\coincirc{q'}\monadic{v}^1$ and $\gamma_d^1\coincirc{\Gamma}\gamma^1$. Hence by the induction hypothesis about~$e_2$, $\sem{e_2}\gamma^1\phi(\omicron_2\ldots\omicron_{n+2}\rho)=\uopl{pure}(\monadic{v}^2,\gamma^2,\omicron_3\ldots\omicron_{n+2}\rho)$ where $\monadic{v}^2$ is $q'$-exact and $\gamma^2$ is $\Gamma$-exact in circuit, $\monadic{v}_d^2\coincirc{q'}\monadic{v}^2$ and $\gamma_d^2\coincirc{\Gamma}\gamma^2$. If $d_0=\mbox{\lstinline+@public+}$ then $\monadic{v}_d^1\coincirc{q'}\monadic{v}^1$ and $\monadic{v}_d^2\coincirc{q'}\monadic{v}^2$ imply $\monadic{v}^1=\uopl{pure} i_1$ and $\monadic{v}^2=\uopl{pure} i_2$. As $\gamma^2$ is $\Gamma$-exact and $\uopl{pure} i_1$ is $q'$-exact in circuit, the updated environment $\left((x,\uopl{pure} i_1),\gamma^2\right)$ is $((x:q'),\Gamma)$-exact in circuit. Moreover, $\gamma_d^2\coincirc{\Gamma}\gamma^2$ and $\uopl{pure} i_1\coincirc{q'}\uopl{pure} i_1$ together give $\left((x,\uopl{pure} i_1),\gamma_d^2\right)\coincirc{\Gamma'}\left((x,\uopl{pure} i_1),\gamma^2\right)$ where $\Gamma'=((x:q'),\Gamma)$. Hence the induction hypothesis about~$e_3$ applies and gives $\sem{e_3}\gamma^2\phi(\omicron_3\ldots\omicron_{n+2}\rho)=\uopl{pure}(\monadic{v}^3,\gamma^3,\omicron_4\ldots\omicron_{n+2}\rho)$ where $\monadic{v}^3$ is $q_1$-exact and $\gamma_3$ is $\Gamma'$-exact in circuit, $\monadic{v}_d^3\coincirc{q_1}\monadic{v}^3$ and $\gamma_d^3\coincirc{\Gamma'}\gamma^3$. Replacing $i_1$ by $i_1+1$ does not violate the required properties, so we analogously obtain $\sem{e_3}\gamma^{k-1}\phi(\omicron_k\ldots\omicron_{n+2}\rho)=\uopl{pure}(\monadic{v}^k,\gamma^k,\omicron_{k+1}\ldots\omicron_{n+2}\rho)$ where $\monadic{v}^k$ is $q_1$-exact in circuit and $\monadic{v}_d^k\coincirc{q_1}\monadic{v}^k$ for all $k=3,4,\ldots,n+2$, $\gamma^{n+2}$ is $\Gamma'$-exact in circuit and $\gamma_d^{n+2}\coincirc{\Gamma'}\gamma^{n+2}$. Obviously the latter implies $\uopl{tail}\gamma^{n+2}$ being $\Gamma$-exact in circuit and $\uopl{tail}\gamma_d^{n+2}\coincirc{\Gamma}\uopl{tail}\gamma^{n+2}$. Thus we obtain $\sem{e}\gamma\phi(\omicron\rho)=\uopl{pure}(\monadic{v},\gamma',\rho)$ where $\monadic{v}=\uopl{pure}(\monadic{v}^3,\ldots,\monadic{v}^{n+2})$ and $\gamma'=\gamma^{n+2}$. By clause~2 of Definitions~\ref{semantics:exactdef} and~\ref{semantics:coincidentdef}, $\uopl{pure}(\monadic{v}^3,\ldots,\monadic{v}^{n+2})$ is $q$-exact in circuit and $\uopl{pure}(\monadic{v}_d^3,\ldots,\monadic{v}_d^{n+2})\coincirc{q}\uopl{pure}(\monadic{v}^3,\ldots,\monadic{v}^{n+2})$. The desired claim follows in this case. If $d_0\ne\mbox{\lstinline+@public+}$ then $\monadic{v}^1,\monadic{v}^2$ being $q'$-exact in circuit implies $\monadic{v}^1=\monadic{v}^2=\top$. As $\gen{d_0}\supseteq D_3$ implies $\mbox{\lstinline+@public+}\notin D_3$, Theorems~\ref{semantics:outputthm} and~\ref{semantics:effcircthm} imply $\omicron_3=\epsilon$, $\left((x,\uopl{pure} i_1),\gamma_d^2\right)\coincirc{\Gamma'}\gamma_d^3$ and also $\omicron_k=\epsilon$, $[x\mapsto(i_1+k-3)]\gamma_d^{k-1}\coincirc{\Gamma'}\gamma_d^k$ for every $k=4,\ldots,n+2$. Obviously this implies $\gamma_d^2\coincirc{\Gamma}\uopl{tail}\gamma_d^3$ and $\uopl{tail}\gamma_d^{k-1}\coincirc{\Gamma}\uopl{tail}\gamma_d^k$ for every $k=4,\ldots,n+2$. By Lemma~\ref{semantics:coinlemma}, $\gamma_d^2\coincirc{\Gamma}\uopl{tail}\gamma_{n+2}$ which is the same as $\gamma_d^2\coincirc{\Gamma}\gamma'_d$. We obtain $\sem{e}\gamma\phi(\omicron\rho)=\sem{e}\gamma\phi(\omicron_1\omicron_2\rho)=\uopl{pure}(\monadic{v},\gamma',\rho)$ where $\monadic{v}=\top$ and $\gamma'=\gamma^2$. As $d_0\ne\mbox{\lstinline+@public+}$ and $s_0=\mbox{\lstinline+$pre+}$, $\top$ is $q$-exact in circuit and $\monadic{v}_d\coincirc{q}\top$ vacuously. By Lemma~\ref{semantics:coinlemma}, $\gamma_d^2\coincirc{\Gamma}\gamma'_d$ and $\gamma_d^2\coincirc{\Gamma}\gamma^2$ together imply $\gamma'_d\coincirc{\Gamma}\gamma'$. By the above, we also get $\gamma'$ being $\Gamma$-exact in circuit. The desired claim follows. \item Let $e=\wireexpr{e_1}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{t_0}{\mbox{\lstinline+$pre+}}{d_0}! D_1\mbox{,}\\ s_0=\mbox{\lstinline+$post+}\mbox{,}\quad\mbox{$t_0$ is $\uintmodty{\mbox{\lstinline+N+}}$ or $\boolmodty{\mbox{\lstinline+N+}}$}\mbox{,} \end{array} \] and \[ \begin{array}{l} \semd{e_1}\gamma\phi=\uopl{pure}(\monadic{v}_d^1,\gamma_d^1,\omicron_1)\mbox{,}\\ \monadic{v}_d=\monadic{v}_d^1\mbox{,}\quad\gamma'_d=\gamma_d^1\mbox{,}\quad\omicron=\lam{d'}{\branching{(\omicron_1)_{d'}\monadic{v}_d^1&\mbox{if $d'$ is the domain of~$e_1$}\\(\omicron_1)_{d'}&\mbox{otherwise}}}\mbox{.} \end{array} \] Here, $(\omicron_1)_{d'}$ denotes the member of the pair of streams $\omicron_1$ that corresponds to domain~$d'$ (for $d'\in\set{\mbox{\lstinline+@prover+},\mbox{\lstinline+@verifier+}}$). Denote $q'=(\qualty{t_0}{\mbox{\lstinline+$pre+}}{d_0})$. By the induction hypothesis about~$e_1$, \[ \sem{e_1}\gamma\phi(\omicron\rho)=\uopl{pure}(\monadic{v}^1,\gamma^1,\lam{d'}{\branching{\monadic{v}_d^1\rho&\mbox{if $d'$ is the domain of~$e_1$}\\\rho&\mbox{otherwise}}}) \] where $\monadic{v}^1$ is $q'$-exact and $\gamma^1$ is $\Gamma$-exact in circuit, $\monadic{v}_d^1\coincirc{q'}\monadic{v}^1$ and $\gamma_d^1\coincirc{\Gamma}\gamma^1$. Hence $\sem{e}\gamma\phi(\omicron\rho)=\uopl{pure}(\monadic{v},\gamma',\rho)$ where $\monadic{v}=\branching{\monadic{v}^1&\mbox{if $d_0=\mbox{\lstinline+@public+}$}\\\monadic{v}_d^1&\mbox{otherwise}}$ and $\gamma'=\gamma^1$. Obviously we have $\gamma'$ being $\Gamma$-exact in circuit and $\gamma'_d\coincirc{\Gamma}\gamma'$. By Lemma~\ref{semantics:coinlemma}, $\monadic{v}_d\coincirc{q}\monadic{v}$. By $\monadic{v}_d^1$ being $q'$-exact in $\mbox{\lstinline+@prover+}$, we know that $\monadic{v}_d^1=\uopl{pure} v_d^1$ where $v_d^1\in t_0$. As $s_0=\mbox{\lstinline+$post+}$, $\uopl{pure} v_d^1$ is $q$-exact in circuit. Moreover, as $\monadic{v}^1$ is $q'$-exact in circuit, if $d_0=\mbox{\lstinline+@public+}$ then $\monadic{v}^1$ is $q$-exact in circuit. The desired claim follows. \item Let $e=\castexpr{e_1}{q_0}$. Let the type of $e_1$ be $q_1$, i.e., \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{t_0}{s_1}{d_1}! D\mbox{,}\\ s_1\mathrel{\mathchar"13C\mathchar"3A} s_0\mbox{,}\quad d_1\mathrel{\mathchar"13C\mathchar"3A} d_0\mbox{,}\quad\gen{d_0}\supseteq\gen{t_0}\mbox{.} \end{array} \] We have \[ \begin{array}{l} \semd{e_1}\gamma_d\phi=\uopl{pure}(\monadic{v}_d^1,\gamma_d^1,\omicron_1)\mbox{,}\\ \monadic{v}_d=\monadic{v}_d^1\mbox{,}\quad\gamma'_d=\gamma_d^1\mbox{,}\quad\omicron=\omicron_1\mbox{.} \end{array} \] By the induction hypothesis, $\sem{e_1}\gamma\phi(\omicron_1\rho)=\uopl{pure}(\monadic{v}^1,\gamma^1,\rho)$ where $\monadic{v}^1$ is $q_1$-exact and $\gamma^1$ is $\Gamma$-exact in circuit, $\monadic{v}_d^1\coincirc{q_1}\monadic{v}^1$ and $\gamma_d^1\coincirc{\Gamma}\gamma^1$. Hence $\sem{e}\gamma\phi(\omicron\rho)=\uopl{pure}(\monadic{v},\gamma',\rho)$ where $\monadic{v}=\branching{\monadic{v}^1&\mbox{if $s_0=\mbox{\lstinline+$post+}$ or $d_0=\mbox{\lstinline+@public+}$}\\\top&\mbox{otherwise}}$ and $\gamma'=\gamma^1$. Consider two cases: \begin{itemize} \item If $s_0=\mbox{\lstinline+$post+}$ or $d_0=\mbox{\lstinline+@public+}$ then $\monadic{v}=\monadic{v}^1$. As $s_1\mathrel{\mathchar"13C\mathchar"3A} s_0$ and $d_1\mathrel{\mathchar"13C\mathchar"3A} d_0$, we have $s_1=\mbox{\lstinline+$post+}$ or $d_1=\mbox{\lstinline+@public+}$. Hence $\monadic{v}^1$ being $q_1$-exact in circuit and $\monadic{v}_d^1\coincirc{q_1}\monadic{v}^1$ imply $\monadic{v}^1$ being $q_0$-exact in circuit and $\monadic{v}_d^1\coincirc{q_0}\monadic{v}^1$, respectively. The desired claim follows. \item If $s_0=\mbox{\lstinline+$pre+}$ and $d_0\ne\mbox{\lstinline+@public+}$ then $\monadic{v}=\top$. We have $\top$ being $q$-exact in circuit and $\monadic{v}_d\coincirc{q}\top$ vacuously. The desired claim follows. \end{itemize} \item Let $e=(\assignexpr{e_1}{e_2})$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{t_1}{s_1}{d_1}\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:\qualty{t_1}{s_1}{d_1}\mbox{,}\\ t_0=\mbox{\lstinline+()+}\mbox{,}\quad s_0=\mbox{\lstinline+$pre+}\mbox{,}\quad d_0=\mbox{\lstinline+@public+}\mbox{.} \end{array} \] Let $e_1=\loadexpr{\loadexpr{\loadexpr{x}{y_1}}{y_2}\ldots}{y_n}$ and denote $\monadic{a}_d=\lookup{\gamma_d}{x}$, $\monadic{a}=\lookup{\gamma}{x}$. Then \[ \begin{array}{l} \semd{y_1}\gamma_d\phi=\uopl{pure}(\monadic{i}_d^1,\gamma_d^1,\omicron_1)\mbox{,}\\ \semd{y_2}\gamma_d^1\phi=\uopl{pure}(\monadic{i}_d^2,\gamma_d^2,\omicron_2)\mbox{,}\\ \dotfill\\ \semd{y_n}\gamma_d^{n-1}\phi=\uopl{pure}(\monadic{i}_d^n,\gamma_d^n,\omicron_n)\mbox{,}\\ \semd{e_2}\gamma_d^n\phi=\uopl{pure}(\monadic{r}_d,\gamma_d^{n+1},\omicron_{n+1})\mbox{,}\\ \monadic{v}_d=\uopl{pure}\mbox{\textoneoldstyle}\mbox{,}\quad\gamma'_d=[x\mapsto\uopl{upd}(\monadic{a}_d,\monadic{i}_d^1\ldots\monadic{i}_d^n,\monadic{r}_d)]\gamma_d^{n+1}\mbox{,}\quad\omicron=\omicron_1\ldots\omicron_{n+1}\mbox{.} \end{array} \] Denote $q_1=(\qualty{t_1}{s_1}{d_1})$, $q'_i=\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d'_i}$ for every $i=1,\ldots,n$, and \[ q'=\qualty{\listty{\ldots\listty{\qualty{\listty{\qualty{\listty{\qualty{t_1}{s_1}{d_1}}}{\mbox{\lstinline+$pre+}}{d'_n}}}{\mbox{\lstinline+$pre+}}{d'_{n-1}}}\ldots}}{\mbox{\lstinline+$pre+}}{d'_1}\mbox{.} \] By Lemma~\ref{typesystem:lhslemma}, $\Gamma\mbox{\ $\vdash$\ } y_i:q'_i$ for each $i=1,\ldots,n$ and $\Gamma\mbox{\ $\vdash$\ } x:q'$. Hence $\monadic{a}_d$ is $q'$-exact in $\mbox{\lstinline+@prover+}$ by exactness of~$\gamma$. By the induction hypothesis about all~$y_k$, $\sem{y_k}\gamma^{k-1}\phi(\omicron_k\ldots\omicron_{n+1}\rho)=\uopl{pure}(\monadic{i}^k,\gamma^k,\omicron_{k+1}\ldots\omicron_{n+1}\rho)$ where $\monadic{i}^k$ is $q'_k$-exact and $\gamma^k$ is $\Gamma$-exact in circuit, $\monadic{i}_d^k\coincirc{q'_k}\monadic{i}^k$ and $\gamma_d^k\coincirc{\Gamma}\gamma^k$. The induction hypothesis about~$e_2$ implies that $\sem{e_2}\gamma^k\phi(\omicron_{n+1}\rho)=\uopl{pure}(\monadic{r},\gamma^{n+1},\rho)$ where $\monadic{r}$ is $q_1$-exact and $\gamma^{n+1}$ is $\Gamma$-exact in circuit, $\monadic{r}_d\coincirc{q_1}\monadic{r}$ and $\gamma_d^{n+1}\coincirc{\Gamma}\gamma^{n+1}$. By Lemma~\ref{semantics:updexactcoinlemma}, $\uopl{upd}(\monadic{a},\monadic{i}^1\ldots\monadic{i}^n,\monadic{r})$ is a well-defined monadic value which is $q'$-exact in circuit, whereby $\uopl{upd}(\monadic{a}_d,\monadic{i}_d^1\ldots\monadic{i}_d^n,\monadic{r}_d)\coincirc{q'}\uopl{upd}(\monadic{a},\monadic{i}^1\ldots\monadic{i}^n,\monadic{r})$. Hence $\sem{e}\gamma\phi(\omicron\rho)=\uopl{pure}(\monadic{v},\gamma',\rho)$ where $\monadic{v}=\uopl{pure}\mbox{\textoneoldstyle}$ and $\gamma'=[x\mapsto\uopl{upd}(\monadic{a},\monadic{i}^1\ldots\monadic{i}^n,\monadic{r})]\gamma^{n+1}$. Thereby, $[x\mapsto\uopl{upd}(\monadic{a},\monadic{i}^1\ldots\monadic{i}^n,\monadic{r})]\gamma^{n+1}$ is $\Gamma$-exact in circuit by the above and \[ [x\mapsto\uopl{upd}(\monadic{a}_d,\monadic{i}_d^1\ldots\monadic{i}_d^n,\monadic{r}_d)]\gamma_d^{n+1}\coincirc{\Gamma}[x\mapsto\uopl{upd}(\monadic{a},\monadic{i}^1\ldots\monadic{i}^n,\monadic{r})]\gamma^{n+1}\mbox{.} \] As $\uopl{pure}\mbox{\textoneoldstyle}$ is $q$-exact in circuit and $\uopl{pure}\mbox{\textoneoldstyle}\coincirc{q}\uopl{pure}\mbox{\textoneoldstyle}$, we are done. \item Let $e=\loadexpr{e_1}{e_2}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:\qualty{\listty{q}}{s_1}{d_1}\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:\qualty{\mbox{\lstinline+uint+}}{s_1}{d_1}\mbox{,} \end{array} \] and \[ \begin{array}{l} \semd{e_1}\gamma_d\phi=\uopl{pure}(\monadic{a}_d,\gamma_d^1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_d^1\phi=\uopl{pure}(\monadic{i}_d,\gamma_d^2,\omicron_2)\mbox{,}\\ \monadic{v}_d=\mcomp{a_d\gets\monadic{a}_d;\; i_d\gets\monadic{i}_d;\; (a_d)_{i_d}}\mbox{,}\quad\gamma'_d=\gamma_d^2\mbox{,}\quad\omicron=\omicron_1\omicron_2\mbox{.} \end{array} \] Denote $q'=(\qualty{\listty{q}}{s_1}{d_1})$ and $q_1=(\qualty{\mbox{\lstinline+uint+}}{s_1}{d_1})$. By $\monadic{a}_d,\monadic{i}_d$ being $q'$-exact and $q_1$-exact, respectively, in $\mbox{\lstinline+@prover+}$, we have $\monadic{a}=\uopl{pure}(\monadic{a}_d^1,\ldots,\monadic{a}_d^n)$, where all $\monadic{a}_d^k$ are $q$-exact in $\mbox{\lstinline+@prover+}$, and $\monadic{i}_d=\uopl{pure} i$ where $i\in\mathbb{N}$. Thus $\monadic{v}_d=\monadic{a}_d^i$ (whereby $i\leq n$ as the result is well-defined). By the induction hypothesis about $e_1$, $\sem{e_1}\gamma\phi(\omicron_1\omicron_2\rho)=\uopl{pure}(\monadic{a},\gamma^1,\omicron_2\rho)$ where $\monadic{a}$ is $q'$-exact and $\gamma^1$ is $\Gamma$-exact in circuit, $\monadic{a}_d\coincirc{q'}\monadic{a}$ and $\gamma_d^1\coincirc{\Gamma}\gamma^1$. Now by the induction hypothesis about $e_2$, $\sem{e_2}\gamma^1\phi(\omicron_2\rho)=\uopl{pure}(\monadic{i},\gamma^2,\rho)$ where $\monadic{i}$ is $q_1$-exact and $\gamma^2$ is $\Gamma$-exact in circuit, $\monadic{i}_d\coincirc{q_1}\monadic{i}$ and $\gamma_d^2\coincirc{\Gamma}\gamma^2$. Hence $\sem{e}\gamma\phi(\omicron\rho)=\uopl{pure}(\monadic{v},\gamma',\rho)$ where \[ \monadic{v}=\mcomp{a\gets\monadic{a};\; i\gets\monadic{i};\; a_i}\mbox{,}\quad\gamma'=\gamma^2\mbox{.} \] Consider two cases: \begin{itemize} \item If $d_1=\mbox{\lstinline+@public+}$ then, by $\monadic{a}_d\coincirc{q'}\monadic{a}$, $\monadic{i}_d\coincirc{q_1}\monadic{i}$ and exactness in circuit, we get $\monadic{a}=\uopl{pure}(\monadic{a}^1,\ldots,\monadic{a}^n)$ where $\monadic{a}_d^k\coincirc{q}\monadic{a}^k$ for every $k=1,\ldots,n$ and $\monadic{i}=\uopl{pure} i$, whereby $\monadic{a}^1,\ldots,\monadic{a}^n$ are $q$-exact in circuit. Hence $\monadic{v}=\monadic{a}^i$ exists, is $q$-exact in circuit and satisfies $\monadic{v}_d\coincirc{q}\monadic{v}$. \item If $d_1\ne\mbox{\lstinline+@public+}$ then $\monadic{a}=\top$ and $\monadic{i}=\top$ by $s_1=\mbox{\lstinline+$pre+}$ and exactness in circuit. Hence $\monadic{v}=\top$. As $\Gamma$ is well-structured, $\qualty{\listty{q}}{s_1}{d_1}$ is well-structured by Theorem~\ref{typesystem:thm}. Thus $\gen{d_1}\supseteq\gen{d_0}\cup\gen{s_0}$, implying that $s_0=\mbox{\lstinline+$pre+}$ and $d_0\ne\mbox{\lstinline+@public+}$. Hence $\top$ is $q$-exact in circuit and $\monadic{v}_d\coincirc{q}\monadic{v}$ vacuously. \end{itemize} In both cases, we obtain $\gamma'$ being $\Gamma$-exact in circuit and $\gamma'_d\coincirc{\Gamma}\gamma'$ by the above. \item Let $e=\stmtcomp{\letexpr{x}{e_1}}{e_2}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:q_1! D_1\mbox{,}\\ (x:q_1),\Gamma\mbox{\ $\vdash$\ } e_2:q! D_2\mbox{,} \end{array} \] and \[ \begin{array}{l} \semd{e_1}\gamma_d\phi=\uopl{pure}(\monadic{v}_d^1,\gamma_d^1,\omicron_1)\mbox{,}\\ \semd{e_2}((x,\monadic{v}_d^1),\gamma_d^1)\phi=\uopl{pure}(\monadic{v}_d^2,\gamma_d^2,\omicron_2)\mbox{,}\\ \monadic{v}_d=\monadic{v}_d^2\mbox{,}\quad\gamma'_d=\uopl{tail}\gamma_d^2\mbox{,}\quad\omicron=\omicron_1\omicron_2\mbox{.} \end{array} \] By the induction hypothesis about~$e_1$, $\sem{e_1}\gamma\phi(\omicron_1\omicron_2\rho)=\uopl{pure}(\monadic{v}^1,\gamma^1,\omicron_2\rho)$ where $\monadic{v}^1$ is \mbox{$q_1$-exact} and $\gamma^1$ is $\Gamma$-exact in circuit, $\monadic{v}_d^1\coincirc{q_1}\monadic{v}^1$ and $\gamma_d^1\coincirc{\Gamma}\gamma^1$. Denote $\Gamma'=((x:q_1),\Gamma)$; then $\left((x,\monadic{v}^1),\gamma^1\right)$ is $\Gamma'$-exact in circuit and $\left((x,\monadic{v}_d^1),\gamma_d^1\right)\coincirc{\Gamma'}\left((x,\monadic{v}^1),\gamma^1\right)$ by the above. Hence by the induction hypothesis about~$e_2$, $\sem{e_2}((x,\monadic{v}^1),\gamma^1)\phi(\omicron_2\rho)=\uopl{pure}(\monadic{v}^2,\gamma^2,\rho)$ where $\monadic{v}^2$ is $q$-exact and $\gamma^2$ is $\Gamma'$-exact in circuit, $\monadic{v}_d^2\coincirc{q}\monadic{v}^2$ and $\gamma_d^2\coincirc{\Gamma'}\gamma^2$. Thus $\sem{e}\gamma\phi(\omicron\rho)=\uopl{pure}(\monadic{v},\gamma',\rho)$ where $\monadic{v}=\monadic{v}^2$ and $\gamma'=\uopl{tail}\gamma^2$. Here $\monadic{v}$ is $q$-exact in circuit and $\monadic{v}_d\coincirc{q}\monadic{v}$ by the above. Obviously $\uopl{tail}\gamma^2$ is $\Gamma$-exact in circuit and $\uopl{tail}\gamma_d^2\coincirc{\Gamma}\uopl{tail}\gamma^2$, hence the other desired claims also follow. \item Let $e=\stmtcomp{e_1}{e_2}$. Then \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ } e_1:q_1! D_1\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } e_2:q! D_2\mbox{,} \end{array} \] and \[ \begin{array}{l} \semd{e_1}\gamma_d\phi=\uopl{pure}(\monadic{v}_d^1,\gamma_d^1,\omicron_1)\mbox{,}\\ \semd{e_2}\gamma_d^1\phi=\uopl{pure}(\monadic{v}_d^2,\gamma_d^2,\omicron_2)\mbox{,}\\ \monadic{v}_d=\monadic{v}_d^2\mbox{,}\quad\gamma'_d=\gamma_d^2\mbox{,}\quad\omicron=\omicron_1\omicron_2\mbox{.} \end{array} \] By the induction hypothesis about~$e_1$, $\sem{e_1}\gamma\phi(\omicron_1\omicron_2\rho)=\uopl{pure}(\monadic{v}^1,\gamma^1,\omicron_2\rho)$ where $\monadic{v}^1$ is \mbox{$q_1$-exact} and $\gamma^1$ is $\Gamma$-exact in circuit, $\monadic{v}_d^1\coincirc{q_1}\monadic{v}^1$ and $\gamma_d^1\coincirc{\Gamma}\gamma^1$. By the induction hypothesis about~$e_2$, $\sem{e_2}\gamma^1\phi(\omicron_2\rho)=\uopl{pure}(\monadic{v}^2,\gamma^2,\rho)$ where $\monadic{v}^2$ is $q$-exact and $\gamma^2$ is $\Gamma$-exact in circuit, $\monadic{v}_d^2\coincirc{q}\monadic{v}^2$ and $\gamma_d^2\coincirc{\Gamma}\gamma^2$. Thus $\sem{e}\gamma\phi(\omicron\rho)=\uopl{pure}(\monadic{v},\gamma',\rho)$ where $\monadic{v}=\monadic{v}^2$ and $\gamma'=\gamma^2$. The desired claims follow directly. \end{itemize} \end{proof} \section{Dynamic Semantics}\label{sec:semantics} We present dynamic semantics of our language in a denotational style. In fact, the overall setting assumes four different dynamic semantics, loosely corresponding to the views of three domains and the circuit. We call the three semantics corresponding to the domains \emph{local} since they describe what is computed by different parties locally. For example, Prover's view contains all computations that are performed as $\qual{\mbox{\lstinline+$pre+}}{\mbox{\lstinline+@prover+}}$, Verifier's view contains all computations performed as $\qual{\mbox{\lstinline+$pre+}}{\mbox{\lstinline+@verifier+}}$, etc. Values of all expressions and statements in Prover's domain are unknown from Verifier's point of view; we denote the unknown value by~$\top$. Likewise, the local semantics for the public domain evaluates all expressions and statements in the higher domains to~$\top$. Computations in the public domain are performed by the compiler. As $\mbox{\lstinline+$pre+}$ and $\mbox{\lstinline+@prover+}$ are the topmost elements of the stage and domain hierarchy, Prover's view encompasses the whole program. Basically, this view describes \emph{what should actually happen}, nevertheless ignoring the special way computation is performed in the circuit due to limited supply of operations The circuit semantics describes computations performed as $\qual{\mbox{\lstinline+$post+}}{\mbox{\lstinline{@D}}}$ for any \lstinline{@D}, and also everything in $\qual{\mbox{\lstinline+$pre+}}{\mbox{\lstinline+@public+}}$. Although not computed by the circuit, values in $\qual{\mbox{\lstinline+$pre+}}{\mbox{\lstinline+@public+}}$ are inevitably needed in performing branching computations as conditions of if expressions and loop bounds belong to stage $\mbox{\lstinline+$pre+}$. In reality, the compiler unrolls conditionals and loops for the circuit as the latter has no means for branching. We define all three local semantics via a common set of equations. The differences arise from domain inclusion conditions that can be either true or false depending on the party and can introduce~$\top$. The type system ensures that computing the program parts of the lower domains is not impeded by not knowing the values of the higher domains. The main notation and types are summarized in Fig.~\ref{semantics:types}. The set of values that our semantics can produce consists of non-negative integers, booleans $\mbox{\bfseries tt}$ and~$\mbox{\bfseries ff}$, the only value of the unit type, and finite sequences of (possibly unknown) values. We need two sets of values, $U$ and $V$, both defined recursively as the least fixpoint satisfying the corresponding equation. Values in the set~$U$ (which we sometimes call the ``core'' values) are built without making use of~$\top$, while the definition of~$V$ involves also $\top$. Core values are used only for representing the input of local computation; we can be sure that each party can fully read its input whence $\top$ will never occur there. By $\mathds{1}+A$, we denote the disjoint sum of a singleton set and set~$A$; in the case of~$M\, V$, we assume $\mathds{1}=\set{\top}$. We refer to the elements of the main summand (i.e., not $\mathds{1}$) as \emph{pure}. The local semantics of an expression takes a value environment and a triple of input dictionaries (one for each domain) as arguments, and normally produces a triple containing the value of the expression, an updated environment and a pair of finite sequences of values to be delivered to the circuit (one sequence for each of $\mbox{\lstinline+@prover+}$ and $\mbox{\lstinline+@verifier+}$; the circuit does not take public input). In exceptional cases, the semantics can fail, which is shown by the addend~$\mathds{1}$ in the equation for $C_d\, A$ and means a runtime error. For simplicity, we ignore runtime errors other than assertion failures in the semantics; in practice, all other runtime errors are considered semantically equivalent to a failed assertion. \begin{figure}\figsize \renewcommand{\arraycolsep}{2pt} \begin{tabular}{@{}l@{}} $\begin{array}{lcl} \mathbb{N}&=&\set{0,1,2,\ldots}\\ \mathbb{B}&=&\set{\mbox{\bfseries tt},\mbox{\bfseries ff}}\\ ()&=&\set{\mbox{\textoneoldstyle}} \end{array}$\qquad $\begin{array}{lcl} X&&\mbox{the set of variables}\\ K&&\mbox{the set of input keys}\\ U&=&\mathbb{N}\cup\mathbb{B}\cup()\cup U^*\quad\mbox{the set of core values}\\ V&=&\mathbb{N}\cup\mathbb{B}\cup()\cup(M\, V)^*\quad\mbox{the set of values} \end{array}$\\[4.5ex] $\begin{array}{lcl} M\, A&=&\mathds{1}+A\\ C_d\, A&=&\mathbf{Env}\to\mathbf{In}^3\to\mathds{1}+A\times\mathbf{Env}\times\mathbf{Out}^2\\ C\, A&=&\mathbf{Env}\to\mathbf{In}^3\to\mathbf{Out}^2\to\mathds{1}+A\times\mathbf{Env}\times\mathbf{Out}^2 \end{array}$\\[4.5ex] $\begin{array}{lcl@{\quad}l} \mathbf{Env}&=&(X\times M\, V)^+&\mbox{value environments}\\ \mathbf{In}&=&K\to U&\mbox{inputs of local computation}\\ \mathbf{Out}&=&(M\,(\mathbb{N}\cup\mathbb{B}))^*&\mbox{streams of values delivered to the circuit} \end{array}$\\[4.5ex] $\begin{array}{lcl@{\quad}l} \semd{e}&:&C_d\,(M\, V)&\mbox{the local semantics of expression~$e$ in domain~$d$}\\ \sem{e}&:&C\,(M\, V)&\mbox{the circuit semantics of expression~$e$} \end{array}$ \end{tabular} \caption{\label{semantics:types} Types of semantic objects} \end{figure} A value environment is a finite association list. It is operated as a stack. We use the following notation for lookup and update of variable~$x$ in any environment~$\gamma=((x_1,a_1),\ldots,(x_n,a_n))$, where $i$ is the least index such that $x_i=x$: \[ \lookup{\gamma}{x}=a_i\mbox{,}\quad [x\mapsto a]\gamma=((x_1,a_1),\ldots,(x_{i-1},a_{i-1}),(x_i,a),(x_{i+1},a_{i+1}),\ldots,(x_n,a_n))\mbox{.} \] Note that an update is performed in the stack element where the variable~$x$ is defined. If a new definition of~$x$ is desired, we instead write $(x,a),\gamma$ which means pushing a new association to the stack. To omit the topmost element of the stack~$\gamma$, we write $\uopl{tail}\gamma$. If $\gamma=((x_1,a_1),\ldots,(x_n,a_n))$ then we write $\uopl{vars}\gamma=(x_1,\ldots,x_n)$. The definition of local semantics is given in Fig.~\ref{semantics:exprstmt}. The notation of syntactic objects coincides with that in the type rules (e.g., $x$ stands for a variable etc.); in addition, $\gamma$, $\phi$ and $\omicron$ denote value environments, inputs and outputs, respectively. To avoid the need to study exceptional cases separately, we use the monad comprehension syntax of the functional programming language Haskell. This notation was first advocated by Wadler~\cite{DBLP:journals/mscs/Wadler92} for succinct description of computations that may involve side effects. We only use the notation for the \emph{maybe monad} $A\mapsto\mathds{1}+A$. For example, the sum of values $\monadic{v}_1,\monadic{v}_2\in M\, V$ (the static type system ensures that their types are correct, but either value can be unknown) is written as \[ \mcomp{i_1\gets\monadic{v}_1;\; i_2\gets\monadic{v}_2;\;\uopl{pure}(i_1+i_2)}\mbox{.} \] Here, the first two clauses define $i_1$ and $i_2$ as pure representatives of $\monadic{v}_1$ and $\monadic{v}_2$, respectively, and the last clause specifies the sum $i_1+i_2$ as the final outcome. The latter is wrapped into a monadic value (i.e., an element of $M\, V$) by function $\uopl{pure}$. Any of the clauses evaluating to~$\top$ turns the final result $\top$ immediately. In general, monad comprehension can contain any finite number of clauses, all of which except the last one may bind new pure values. Evaluation is strict and progresses from left to right. Note that here and below, we denote monadic values by letters with hat for clarity. Since $C_d$ also involves exceptional cases, we use monad comprehension for~$C_d$, too. So we have a two-layer monadic specification of semantics ($M$ is inside and $C_d$ outside). In the outer layer, we use function $\uopl{guard}$ that on a false condition raises an exception (and jumps out of comprehension) and has no effect otherwise. Due to the two-layer representation, the unknown value~$\top$ causes no exception in the outer layer. \begin{figure*}\figsize\renewcommand{\arraycolsep}{2pt}\renewcommand{\arraystretch}{1.2} \[\begin{array}{lcl} \semd{\epsilon}\gamma\phi&=&\uopl{pure}(\uopl{pure}\mbox{\textoneoldstyle},\gamma,\epsilon)\\ \semd{\overline{n}}\gamma\phi&=&\branching{\uopl{pure}(\uopl{pure} n,\gamma,\epsilon)&\mbox{if $\overline{n}$ is in domain~$d$ or lower}\\\uopl{pure}(\top,\gamma,\epsilon)&\mbox{otherwise}}\\ \semd{\overline{b}}\gamma\phi&=&\branching{\uopl{pure}(\uopl{pure} b,\gamma,\epsilon)&\mbox{if $\overline{b}$ is in domain~$d$ or lower}\\\uopl{pure}(\top,\gamma,\epsilon)&\mbox{otherwise}}\\ \semd{x}\gamma\phi&=&\uopl{pure}(\lookup{\gamma}{x},\gamma,\epsilon)\\ \semd{\addexpr{e_1}{e_2}}\gamma_0\phi&=&\mcompv{(\monadic{v}_1,\gamma_1,\omicron_1)\gets\semd{e_1}\gamma_0\phi;\;\\(\monadic{v}_2,\gamma_2,\omicron_2)\gets\semd{e_2}\gamma_1\phi;\;\\\uopl{pure}(\mcomp{v_1\gets\monadic{v}_1;\; v_2\gets\monadic{v}_2;\;\uopl{pure}(v_1+v_2)},\gamma_2,\omicron_1\omicron_2)}\\ \semd{\assertexpr{e}}\gamma_0\phi&=&\mcomp{(\monadic{v},\gamma_1,\omicron_1)\gets\semd{e}\gamma_0\phi;\;\uopl{guard}(\monadic{v}\ne\uopl{pure}\mbox{\bfseries ff});\;\uopl{pure}(\uopl{pure}\mbox{\textoneoldstyle},\gamma_1,\omicron_1)}\\ \semd{\getexpr{d'}{k}}\gamma\phi&=&\branching{\uopl{pure}(\uopl{allpure}(\phi_{d'}(k)),\gamma,\epsilon)&\mbox{if $d'\mathrel{\mathchar"13C\mathchar"3A} d$}\\\uopl{pure}(\top,\gamma,\epsilon)&\mbox{otherwise}}\\ \semd{\ifexpr{e_1}{e_2}{e_3}}\gamma_0\phi&=&\mcompv{(\monadic{v}_1,\gamma_1,\omicron_1)\gets\semd{e_1}\gamma_0\phi;\;\\\branching{\mcomp{(\monadic{v}_2,\gamma_2,\omicron_2)\gets\semd{e_2}\gamma_1\phi;\;\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_1\omicron_2)}&\mbox{if $\monadic{v}_1=\uopl{pure}\mbox{\bfseries tt}$}\\\mcomp{(\monadic{v}_3,\gamma_3,\omicron_3)\gets\semd{e_3}\gamma_1\phi;\;\uopl{pure}(\monadic{v}_3,\gamma_3,\omicron_1\omicron_3)}&\mbox{if $\monadic{v}_1=\uopl{pure}\mbox{\bfseries ff}$}\\\uopl{pure}(\top,\gamma_1,\omicron_1)&\mbox{otherwise}}}\\ \semd{\forexpr{x}{e_1}{e_2}{e_3}}\gamma_0\phi&=&\begin{array}[t]{@{}l@{}}\mcompv{(\monadic{v}_1,\gamma_1,\omicron_1)\gets\semd{e_1}\gamma_0\phi;\;\\(\monadic{v}_2,\gamma_2,\omicron_2)\gets\semd{e_2}\gamma_1\phi;\;\\\branching{\uopl{main}(\max(0,i_2-i_1))&\mbox{where $\monadic{v}_j=\uopl{pure} i_j$, $j=1,2$}\\\uopl{pure}(\top,\gamma_2,\omicron_1\omicron_2)&\mbox{if $\monadic{v}_1=\top$ or $\monadic{v}_2=\top$}}}\end{array}\\ \multicolumn{2}{r}{\mbox{where}}&\uopl{main}(n)=\mcompv{(\monadic{a}_1,\gamma'_1,\omicron'_1)\gets\semd{e}((x,\uopl{pure} i_1),\gamma_2)\phi;\;\\\forall k=2,\ldots,n:(\monadic{a}_k,\gamma'_k,\omicron'_k)\gets\semd{e_3}([x\mapsto\uopl{pure}(i_1\!\!+\!\!k\!\!-\!\!1)]\gamma'_{k-1})\phi;\;\\\uopl{pure}(\uopl{pure}(\monadic{a}_1,\ldots,\monadic{a}_n),\uopl{tail}\gamma'_n,\omicron_1\omicron_2\omicron'_1\ldots\omicron'_n)}\\ \semd{\wireexpr{e}}\gamma_0\phi&=&\mcomp{(\monadic{v},\gamma_1,\omicron_1)\gets\semd{e}\gamma_0\phi;\;\uopl{pure}(\monadic{v},\gamma_1,\lam{d'}{\branching{(\omicron_1)_{d'}\monadic{v}&\mbox{if $e$ is in domain~$d'$}\\(\omicron_1)_{d'}&\mbox{otherwise}}})}\\ \semd{\castexpr{e}{d'}}\gamma_0\phi&=&\branching{\semd{e}\gamma_0\phi&\mbox{if $d'\mathrel{\mathchar"13C\mathchar"3A} d$}\\\mcomp{(\monadic{v}_1,\gamma_1,\omicron_1)\gets\semd{e}\gamma_0\phi;\;\uopl{pure}(\top,\gamma_1,\omicron_1)}&\mbox{otherwise}}\\ \semd{\assignexpr{l}{e}}\gamma_0\phi&=&\begin{array}[t]{@{}l@{}}\mcompv{\monadic{a}\gets\uopl{pure}(\lookup{\gamma_0}{x});\;\\\forall k=1,\ldots,n:(\monadic{i}_k,\gamma_k,\omicron_k)\gets\semd{y_k}\gamma_{k-1}\phi;\;\\(\monadic{v},\gamma',\omicron')\gets\semd{e}\gamma_n\phi;\;\\\uopl{pure}(\uopl{pure}\mbox{\textoneoldstyle},[x\mapsto\uopl{upd}(\monadic{a},\monadic{i}_1\ldots\monadic{i}_n,\monadic{v})]\gamma',\omicron_1\ldots\omicron_n\omicron')}\end{array}\\ \multicolumn{2}{r}{\mbox{where}}&\loadexpr{\loadexpr{\loadexpr{x}{y_1}}{y_2}\ldots}{y_n}=l\\ \semd{\loadexpr{l}{e}}\gamma_0\phi&=&\mcompv{(\monadic{a},\gamma_1,\omicron_1)\gets\semd{l}\gamma_0\phi;\;\\(\monadic{i},\gamma_2,\omicron_2)\gets\semd{e}\gamma_1\phi;\;\\\uopl{pure}(\mcomp{a\gets\monadic{a};\; i\gets\monadic{i};\; a_i},\gamma_2,\omicron_1\omicron_2)}\\ \semd{\stmtcomp{\letexpr{x}{e_1}}{e_2}}\gamma_0\phi&=&\mcompv{(\monadic{v}_1,\gamma_1,\omicron_1)\gets\semd{e_1}\gamma_0\phi;\;\\(\monadic{v}_2,\gamma_2,\omicron_2)\gets\semd{e_2}((x,\monadic{v}_1),\gamma_1)\phi;\;\\\uopl{pure}(\monadic{v}_2,\uopl{tail}\gamma_2,\omicron_1\omicron_2)}\\ \semd{\stmtcomp{e_1}{e_2}}\gamma_0\phi&=&\mcomp{(\monadic{v}_1,\gamma_1,\omicron_1)\gets\semd{e_1}\gamma_0\phi;\;(\monadic{v}_2,\gamma_2,\omicron_2)\gets\semd{e_2}\gamma_1\phi;\;\uopl{pure}(\monadic{v}_2,\gamma_2,\omicron_1\omicron_2)} \end{array} \] \caption{\label{semantics:exprstmt} Local dynamic semantics of expressions and statements} \end{figure*} The semantics of~$+$ is included as an example of a built-in operator. Arithmetic is implicitly performed modulo some positive integer if that is required by the type ($\uintmodty{\mbox{\lstinline{N}}}$). The only case that uses core values is that of $\mbox{\lstinline{get}}$. To transform a core value to a value in $M\, V$, we use the function $\uopl{allpure}:U\to M\, V$ defined as \[ \uopl{allpure} v=\branching{\uopl{pure} v&\mbox{if $v$ belongs to a primitive type}\\\uopl{pure}(\uopl{allpure} v_1,\ldots,\uopl{allpure} v_n)&\mbox{if $v=(v_1,\ldots,v_n)$}}\mbox{.} \] Concerning type casts, we show only the variant with domain cast as only domain matters here. The assignment case uses an auxiliary function $\uopl{upd}:M\, V\times(M\, V)^*\times M\, V\to M\, V$ that takes a value that can be a list with $0$ or more dimensions (i.e., a primitive value or a list of primitives or a matrix etc.), an index vector, and a value, and returns a new list where the cell indicated by the index vector has been updated with the given value. More formally, \[ \uopl{upd}(\monadic{a},\monadic{i}_1\ldots\monadic{i}_n,\monadic{v})=\branching{\monadic{v}&\mbox{if $n=0$}\\\mcomp{a\gets\monadic{a};\; i_1\gets\monadic{i}_1;\;\uopl{pure}([i_1\mapsto\uopl{upd}(a_{i_1},\monadic{i}_2\ldots\monadic{i}_n,\monadic{v})]a)}&\mbox{if $n>0$}}\mbox{.} \] The circuit semantics is defined mostly analogously; the definition is given in Fig.~\ref{semantics:circuit}. Again, we present only one case of type cast; the other cases are defined in similar lines. The most important difference from local semantics is concerning the \lstinline{wire} construct that reads non-public values from the output streams of local computations. For this reason, the circuit semantics takes a pair of streams as a supplementary argument. Execution of each wire expression in a non-public domain removes the first value from the stream corresponding to the domain of that expression; the updated pair of streams is included in the result. \begin{figure*}\figsize\renewcommand{\arraycolsep}{2pt}\renewcommand{\arraystretch}{1.2} \[ \begin{array}{lcl} \sem{\epsilon}\gamma\phi\omicron&=&\uopl{pure}(\uopl{pure}\mbox{\textoneoldstyle},\gamma,\omicron)\\ \sem{\overline{n}}\gamma\phi\omicron&=&\branching{\uopl{pure}(\uopl{pure} n,\gamma,\omicron)&\mbox{if $\overline{n}$ is in \lstinline+$post+ or \lstinline+@public+}\\\uopl{pure}(\top,\gamma,\omicron)&\mbox{otherwise}}\\ \sem{\overline{b}}\gamma\phi\omicron&=&\branching{\uopl{pure}(\uopl{pure} b,\gamma,\omicron)&\mbox{if $\overline{b}$ is in \lstinline+$post+ or \lstinline+@public+}\\\uopl{pure}(\top,\gamma,\omicron)&\mbox{otherwise}}\\ \sem{x}\gamma\phi\omicron&=&\uopl{pure}(\lookup{\gamma}{x},\gamma,\omicron)\\ \sem{\addexpr{e_1}{e_2}}\gamma_0\phi\omicron_0&=&\mcompv{(\monadic{v}_1,\gamma_1,\omicron_1)\gets\sem{e_1}\gamma_0\phi\omicron_0;\;\\(\monadic{v}_2,\gamma_2,\omicron_2)\gets\sem{e_2}\gamma_1\phi\omicron_1;\;\\\uopl{pure}(\mcomp{v_1\gets\monadic{v}_1;\; v_2\gets\monadic{v}_2;\;\uopl{pure}(v_1+v_2)},\gamma_2,\omicron_2)}\\ \sem{\assertexpr{e}}\gamma_0\phi\omicron_0&=&\mcomp{(\monadic{v},\gamma_1,\omicron_1)\gets\sem{e}\gamma_0\phi\omicron_0;\;\uopl{guard}(\monadic{v}\ne\uopl{pure}\mbox{\bfseries ff});\;\uopl{pure}(\uopl{pure}\mbox{\textoneoldstyle},\gamma_1,\omicron_1)}\\ \sem{\getexpr{d}{k}}\gamma\phi\omicron&=&\branching{\uopl{pure}(\uopl{allpure}(\phi_{d}(k)),\gamma,\omicron)&\mbox{if $d=\mbox{\lstinline+@public+}$}\\\uopl{pure}(\top,\gamma,\omicron)&\mbox{otherwise}}\\ \sem{\ifexpr{e_1}{e_2}{e_3}}\gamma_0\phi\omicron_0&=&\mcomp{(\monadic{v}_1,\gamma_1,\omicron_1)\gets\sem{e_1}\gamma_0\phi\omicron_0;\;\branching{\sem{e_2}\gamma_1\phi\omicron_1&\mbox{if $\monadic{v}_1=\uopl{pure}\mbox{\bfseries tt}$}\\\sem{e_3}\gamma_1\phi\omicron_1&\mbox{if $\monadic{v}_1=\uopl{pure}\mbox{\bfseries ff}$}\\\uopl{pure}(\top,\gamma_1,\omicron_1)&\mbox{otherwise}}}\\ \sem{\forexpr{x}{e_1}{e_2}{e_3}}\gamma_0\phi\omicron_0&=&\begin{array}[t]{@{}l@{}}\mcompv{(\monadic{v}_1,\gamma_1,\omicron_1)\gets\sem{e_1}\gamma_0\phi\omicron_0;\;\\(\monadic{v}_2,\gamma_2,\omicron_2)\gets\sem{e_2}\gamma_1\phi\omicron_1;\;\\\branching{\uopl{main}(\max(0,i_2-i_1))&\mbox{where $\monadic{v}_j=\uopl{pure} i_j$, $j=1,2$}\\\uopl{pure}(\top,\gamma_2,\omicron_2)&\mbox{if $\monadic{v}_1=\top$ or $\monadic{v}_2=\top$}}}\end{array}\\ \multicolumn{2}{r}{\mbox{where}}&\uopl{main}(n)=\mcompv{(\monadic{a}_1,\gamma'_1,\omicron'_1)\gets\sem{e_3}((x,\uopl{pure} i_1),\gamma_2)\phi\omicron_2;\;\\\forall k=2,...,n:(\monadic{a}_k,\!\gamma'_k,\!\omicron'_k)\gets\sem{e_3}([x\mapsto\uopl{pure}(i_1\!\!+\!\!k\!\!-\!\!1)]\gamma'_{k-1})\phi\omicron'_{k-1};\;\\\uopl{pure}(\uopl{pure}(\monadic{a}_1,\ldots,\monadic{a}_n),\uopl{tail}\gamma'_n,\omicron'_n)}\\ \sem{\wireexpr{e}}\gamma\phi\omicron&=&\mcompv{(\monadic{v},\gamma',\omicron')\gets\sem{e}\gamma\phi\omicron;\;\\\uopl{pure}(\branching{\monadic{v}&\mbox{if $d=\mbox{\lstinline+@public+}$}\\\uopl{head}\omicron'_d&\mbox{otherwise}},\gamma',\lam{d'}{\branching{\uopl{tail}\omicron'_{d'}&\mbox{if $d'=d$}\\\omicron'_{d'}&\mbox{otherwise}}})}\\ \multicolumn{2}{r}{\mbox{where}}&\mbox{$d$ is the domain of~$e$}\\ \sem{\castexpr{e}{\qualty{t}{s}{d}}}\gamma\phi\omicron&=&\branching{\sem{e}\gamma\phi\omicron&\mbox{if $s=\mbox{\lstinline+$post+}$ or $d=\mbox{\lstinline+@public+}$}\\\mcomp{(\monadic{v},\gamma',\omicron')\gets\sem{e}\gamma\phi\omicron;\;\uopl{pure}(\top,\gamma',\omicron')}&\mbox{otherwise}}\\ \sem{\assignexpr{l}{e}}\gamma_0\phi\omicron_0&=&\begin{array}[t]{@{}l@{}}\mcompv{\monadic{a}\gets\uopl{pure}(\lookup{\gamma_0}{x});\;\\\forall k=1,\ldots,n:(\monadic{i}_k,\gamma_k,\omicron_k)\gets\sem{y_k}\gamma_{k-1}\phi\omicron_{k-1};\;\\(\monadic{v},\gamma',\omicron')\gets\sem{e}\gamma_n\phi\omicron_n;\;\\\uopl{pure}(\uopl{pure}\mbox{\textoneoldstyle},[x\mapsto\uopl{upd}(\monadic{a},\monadic{i}_1\ldots\monadic{i}_n,\monadic{v})]\gamma',\omicron')}\end{array}\\ \multicolumn{2}{r}{\mbox{where}}&\loadexpr{\loadexpr{\loadexpr{x}{y_1}}{y_2}\ldots}{y_n}=l\\ \sem{\loadexpr{l}{e}}\gamma_0\phi\omicron_0&=&\mcompv{(\monadic{a},\gamma_1,\omicron_1)\gets\sem{l}\gamma_0\phi\omicron_0;\;\\(\monadic{i},\gamma_2,\omicron_2)\gets\sem{e}\gamma_1\phi\omicron_1;\;\\\uopl{pure}(\mcomp{a\gets\monadic{a};\; i\gets\monadic{i};\; a_i},\gamma_2,\omicron_2)}\\ \sem{\stmtcomp{\letexpr{x}{e_1}}{e_2}}\gamma_0\phi\omicron_0&=&\begin{array}[t]{@{}l@{}}\mcompv{(\monadic{v}_1,\gamma_1,\omicron_1)\gets\sem{e_1}\gamma_0\phi\omicron_0;\;\\(\monadic{v}_2,\gamma_2,\omicron_2)\gets\sem{e_2}((x,\monadic{v}_1),\gamma_1)\phi\omicron_1;\;\\\uopl{pure}(\monadic{v}_2,\uopl{tail}\gamma_2,\omicron_2)}\end{array}\\ \sem{\stmtcomp{e_1}{e_2}}\gamma_0\phi\omicron_0&=&\mcomp{(\monadic{v}_1,\gamma_1,\omicron_1)\gets\sem{e_1}\gamma_0\phi\omicron_0;\;\sem{e_2}\gamma_1\phi\omicron_1} \end{array} \] \caption{\label{semantics:circuit} Circuit semantics} \end{figure*} We can prove Theorems \ref{semantics:compthm}--\ref{semantics:correctness} below. Theorem~\ref{semantics:localthm} implies (via repeated application) that every party can compute all data that belong to its domain or lower domains despite not knowing values of the higher domains. Theorem~\ref{semantics:effthm} states that evaluating an expression can change only those values of the value environment that live in domains where the expression is effectful according to the type system. Theorem~\ref{semantics:outputthm} states that an expression can output values to the circuit only if the expression is effectful in $\mbox{\lstinline+@public+}$. Theorem~\ref{semantics:effcircthm} is similar to Theorem~\ref{semantics:effthm} but is concerning values in the environment that are visible to the circuit. Theorem~\ref{semantics:safety} states that inputs of higher domains do not influence computation results in the lower domains. Theorem~\ref{semantics:soundness} states that executions of the same code in different domains agree on values visible in the lower domain. Theorem~\ref{semantics:correctness} establishes that if a program succeeds in Prover's semantics then it succeeds in the circuit semantics, provided that it is given the same input and Prover's and Verifier's correct output. Proofs of the theorems use induction on the structure of the expression; the details are given in Appendix~\ref{semantics-proofs}. Before the theorems can be precisely formulated, a few notions must be introduced which the formulations rely on. The notions basically specify, for a fixed domain's or the circuit's point of view, what are good relationships between monadic values and types, and between two monadic values. \begin{definition}\label{semantics:exposeddef} Let a predicate~$P$ on qualified types be fixed. For any well-structured qualified type $q=\qualty{t}{s}{d}$ and $\monadic{v}\in M\, V$, we say that $\monadic{v}$ is \emph{$q$-exposed in~$P$} if one of the following alternatives holds: \begin{enumerate} \item $P(q)$ is true and $t$~{}is a primitive type and $\monadic{v}=\uopl{pure} v$ where $v\in t$ (e.g., if $t=\boolmodty{\mbox{\lstinline{N}}}$ then $v\in\set{\mbox{\bfseries tt},\mbox{\bfseries ff}}$); \item $P(q)$ is true and $t=\listty{q'}$ and $\monadic{v}=\uopl{pure}(\monadic{v}_1,\ldots,\monadic{v}_n)$ where $n\in\mathbb{N}$ and all $\monadic{v}_1,\ldots,\monadic{v}_n\in M\, V$ are $q'$-exposed in~$P$; \item $P(q)$ is false. \end{enumerate} \end{definition} \begin{definition}\label{semantics:exactdef} Let a predicate~$P$ on qualified types be fixed. For any well-structured qualified type $q=\qualty{t}{s}{d}$ and $\monadic{v}\in M\, V$, we say that $\monadic{v}$ is \emph{$q$-exact in~$P$} if one of the following alternatives holds: \begin{enumerate} \item $P(q)$ is true and $t$~{}is a primitive type and $\monadic{v}=\uopl{pure} v$ where $v\in t$ (e.g., if $t=\boolmodty{\mbox{\lstinline{N}}}$ then $v\in\set{\mbox{\bfseries tt},\mbox{\bfseries ff}}$); \item $P(q)$ is true and $t=\listty{q'}$ and $\monadic{v}=\uopl{pure}(\monadic{v}_1,\ldots,\monadic{v}_n)$ where $n\in\mathbb{N}$ and all $\monadic{v}_1,\ldots,\monadic{v}_n\in M\, V$ are $q'$-exact in~$P$; \item $P(q)$ is false and $\monadic{v}=\top$. \end{enumerate} \end{definition} \begin{definition}\label{semantics:coincidentdef} Let a predicate~$P$ on qualified types be fixed. For any well-structured qualified type $q=\qualty{t}{s}{d}$ and $\monadic{v},\monadic{v}'\in M\, V$, we say that $\monadic{v}$ and $\monadic{v}'$ are \emph{$q$-coincident in~$P$} and write $\monadic{v}\coin{q}{P}\monadic{v}'$ iff one of the following alternatives holds: \begin{enumerate} \item $P(q)$ is true and $t$~{}is a primitive type and $\monadic{v}=\monadic{v}'=\uopl{pure} v$ where $v\in t$; \item $P(q)$ is true and $t=\listty{q'}$ and $\monadic{v}=\uopl{pure}(\monadic{v}_1,\ldots,\monadic{v}_n)$, $\monadic{v}'=\uopl{pure}(\monadic{v}'_1,\ldots,\monadic{v}'_n)$ where $n\in\mathbb{N}$ and $\monadic{v}_i$, $\monadic{v}'_i$ are $q'$-coincident in~$P$ for every $i=1,\ldots,n$; \item $P(q)$ is false. \end{enumerate} \end{definition} \begin{definition} Let $\Gamma$ be a well-structured type environment and $P$ be a predicate defined on qualified types. \begin{enumerate} \item We say that $\gamma\in\mathbf{Env}$ is \emph{$\Gamma$-exposed in~$P$} iff $\uopl{vars}\Gamma=\uopl{vars}\gamma$ and, for every association $(x_i:q_i)$ occurring in~$\Gamma$, the value in the corresponding association $(x_i,\monadic{v}_i)$ in $\gamma$ is $q_i$-exposed in~$P$. \item We say that $\gamma\in\mathbf{Env}$ is \emph{$\Gamma$-exact in~$P$} iff $\uopl{vars}\Gamma=\uopl{vars}\gamma$ and, for every association $(x_i:q_i)$ occurring in $\Gamma$, the value in the corresponding association $(x_i,\monadic{v}_i)$ in $\gamma$ is $q_i$-exact in~$P$. \item We say that $\gamma,\gamma'\in\mathbf{Env}$ are \emph{$\Gamma$-coincident in~$P$} and write $\gamma\coin{\Gamma}{P}\gamma'$ iff $\uopl{vars}\Gamma=\uopl{vars}\gamma=\uopl{vars}\gamma'$ and, for every association $(x_i:q_i)$ occurring in $\Gamma$, the values in the corresponding associations $(x_i,\monadic{v}_i)$ and $(x_i,\monadic{v}'_i)$ in $\gamma$ and $\gamma'$, respectively, are $q_i$-coincident in~$P$. \end{enumerate} \end{definition} \begin{definition}\label{semantics:interpretdef} For any fixed domain~$d'$, we shall say ``-exposed in~$d'$'', ``-exact in~$d'$'' and ``\mbox{-}co\-incident in~$d'$'' instead of ``-exposed in~$P$'', ``-exact in~$P$'' and ``-coincident in~$P$'' where $P(\qualty{t}{s}{d})\rightleftharpoons(d\mathrel{\mathchar"13C\mathchar"3A} d')$. We shall say ``-exact in circuit'' and ``-coincident in circuit'' instead of ``-exact in~$P$'' and ``\mbox{-}co\-incident in~$P$'' where $P(\qualty{t}{s}{d})\rightleftharpoons(s=\mbox{\lstinline+$post+}\vee d=\mbox{\lstinline+@public+})$. We write $\coin{q}{d}$ and $\coin{\Gamma}{d}$ for coincidence in~$d$, and $\coincirc{q}$ and $\coincirc{\Gamma}$ for coincidence in circuit. \end{definition} \begin{definition} Call a predicate~$P$ defined on qualified types \emph{data insensitive} if $P(\qualty{t_1}{s}{d})=P(\qualty{t_2}{s}{d})$ for all data types $t_1,t_2$, stage~$s$ and domain~$d$. \end{definition} Note that all predicates used in Definition~\ref{semantics:interpretdef} are data insensitive. \begin{definition} Let $d$ be a fixed domain. \begin{enumerate} \item Let $\omicron\in\mathbf{Out}^2$. We say that $\omicron$ is \emph{exact in~$d$} iff, for any $d'\in\set{\mbox{\lstinline+@prover+},\mbox{\lstinline+@verifier+}}$, each component of $\omicron_{d'}$ is of the form $\uopl{pure} v$ for $v\in\mathbb{N}\cup\mathbb{B}$ if $d'\mathrel{\mathchar"13C\mathchar"3A} d$ and $\top$ if $d'$ is a strict superdomain of~$d$. \item Let $\omicron,\omicron'\in\mathbf{Out}^2$. We say that $\omicron$ and $\omicron'$ are \emph{coincident in~$d$} and write $\omicron\coinpure{d}\omicron'$ iff, for any $d'\in\set{\mbox{\lstinline+@prover+},\mbox{\lstinline+@verifier+}}$, the lengths of $\omicron_{d'}$ and $\omicron'_{d'}$ are equal and if $d'\mathrel{\mathchar"13C\mathchar"3A} d$ then $\omicron_{d'}=\omicron'_{d'}$. \end{enumerate} \end{definition} \begin{theorem}\label{semantics:compthm} Let $\Gamma \mbox{\ $\vdash$\ } e : q! D$ with well-structured~$\Gamma$ and $\gamma\in\mathbf{Env}$ be $\Gamma$-exact in~$d$ for some domain~$d$. Assume that for all subexpressions of~$e$ of the form $\ofty{\getexpr{d'}{k}}{q'}$ where $d'\mathrel{\mathchar"13C\mathchar"3A} d$, the value $\uopl{allpure}(\phi_{d'}(k))$ is $q'$-exact in~$d$. Assume that $\semd{e}\gamma\phi=\uopl{pure}(\monadic{v},\gamma',\omicron)$. Then: \begin{thmlist} \item\label{semantics:localthm} $\monadic{v}$~{}is $q$-exact, $\gamma'$~{}is $\Gamma$-exact and $\omicron$~{}is exact in~$d$; \item\label{semantics:effthm} $\gamma\coin{\Gamma}{d''}\gamma'$ for any domain~$d''$ such that $d''\mathrel{\mathchar"13C\mathchar"3A} d$ and $d''\notin D$; \item\label{semantics:outputthm} If $\mbox{\lstinline+@public+}\notin D$ then $\omicron=\epsilon$; \item\label{semantics:effcircthm} If $d=\mbox{\lstinline+@prover+}$ and $\mbox{\lstinline+@public+}\notin D$ then $\gamma\coincirc{\Gamma}\gamma'$. \end{thmlist} \end{theorem} \begin{theorem}\label{semantics:safety} If $\semd{e}\gamma\phi=\uopl{pure}(\monadic{v},\gamma',\omicron)$ and $\phi'_{d'}=\phi_{d'}$ for every $d'\mathrel{\mathchar"13C\mathchar"3A} d$ then $\semd{e}\gamma\phi'=\semd{e}\gamma\phi$. \end{theorem} \begin{theorem}\label{semantics:soundness} Let $\Gamma\mbox{\ $\vdash$\ } e:q! D$ with well-structured $\Gamma$. Let $d,d'$ be domains such that $d'\mathrel{\mathchar"13C\mathchar"3A} d$. Let $\gamma_d,\gamma_{d'}\in\mathbf{Env}$ be $\Gamma$-exact in~$d$ and $d'$, respectively, and let $\gamma_d\coin{\Gamma}{d'}\gamma_{d'}$. Assume that for all subexpressions of~$e$ of the form $\ofty{\getexpr{d''}{k}}{q'}$, the value $\uopl{allpure}(\phi_{d''}(k))$ is $q'$-exact in~$d''$. Assume that there exist $\monadic{v}_d,\gamma'_d,\omicron$ such that $\semd{e}\gamma_d\phi=\uopl{pure}(\monadic{v}_d,\gamma'_d,\omicron)$. Then there exist $\monadic{v}_{d'},\gamma'_{d'},\omicron'$ such that $\sem{e}_{d'}\gamma_{d'}\phi=\uopl{pure}(\monadic{v}_{d'},\gamma'_{d'},\omicron')$, whereby $\monadic{v}_d\coin{q}{d'}\monadic{v}_{d'}$, $\gamma_d\coin{\Gamma}{d'}\gamma_{d'}$ and $\omicron\coinpure{d'}\omicron'$. \end{theorem} \begin{theorem}\label{semantics:correctness} Let $\Gamma \mbox{\ $\vdash$\ } e : q! D$ with well-structured~$\Gamma$. Let $\gamma_d$, $\gamma\in\mathbf{Env}$ be $\Gamma$-exact in $\mbox{\lstinline+@prover+}$ and in circuit, respectively, such that $\gamma_d\coincirc{\Gamma}\gamma$. Assume that, for all subexpressions of~$e$ of the form $\ofty{\getexpr{d'}{k}}{q'}$, the value $\uopl{allpure}(\phi_{d'}(k))$ is $q'$-exact in $\mbox{\lstinline+@prover+}$. Assume that, for $d=\mbox{\lstinline+@prover+}$, there exist $\monadic{v}_d,\gamma'_d,\omicron$ such that $\semd{e}\gamma_d\phi=\uopl{pure}(\monadic{v}_d,\gamma'_d,\omicron)$. If $\rho$~{}is any pair of stream continuations (one for each of $\mbox{\lstinline+@prover+}$ and $\mbox{\lstinline+@verifier+}$) then $\sem{e}\gamma\phi(\omicron\rho)=\uopl{pure}(\monadic{v},\gamma',\rho)$, where $\monadic{v}$ is $q$-exact and $\gamma'$ is $\Gamma$-exact in circuit. Thereby, $\monadic{v}_d\coincirc{q}\monadic{v}$ and $\gamma'_d\coincirc{\Gamma}\gamma'$. (Here, $\omicron\rho$ denotes the pointwise concatenation of $\omicron$ and $\rho$.) \end{theorem} \section{The Syntax of \textsc{ZK-SecreC}\xspace}\label{sec:syntax} Figure~\ref{syntax:ebnf} describes the syntax of a subset of \textsc{ZK-SecreC}\xspace that contains its most important features via the extended Backus-Naur forms (EBNF). We use the following conventions: \begin{itemize} \item The l.h.s. and r.h.s. of productions are separated by the symbol $\mathrel{::=}$; \item Non-terminals and terminals are written in italic and typewriter font, respectively; \item Zero or more repetitions of a term~$t$ is denoted by $\lizt{t\/}$; \item An optional occurrence of a term~$t$ is denoted by $\mebbe{t}$. \end{itemize} \iffalse \begin{figure}[tbp] \figsize\newcommand{\newitem}[1]{\multicolumn{3}{@{}l}{\bullet\hspace{1em}\mbox{#1}}} \[\setlength{\arraycolsep}{4pt}\begin{array}{@{}ll@{}} \begin{array}[t]{lcl} \newitem{Top-level structure of \textsc{ZK-SecreC}\xspace programs:}\\ &&\\ \nterm{prog} &\mathrel{::=}&\lizt{\nterm{fundef}}\\ \nterm{fundef} &\mathrel{::=}&\mbox{\lstinline{fn}}\ \nterm{sig}\ \nterm{expr}\ \mbox{\lstinline{;}}\\ \nterm{sig} &\mathrel{::=}&\nterm{name}\ \mnterm{typarams}\nterm{params}\ \mnterm{rettype}\ \mnterm{typreds}\\ \nterm{typarams} &\mathrel{::=}&\inbracks{\csl{\nterm{typaram}}}\\ \nterm{typaram} &\mathrel{::=}&\nterm{name} \mid\mbox{\lstinline{$}}\nterm{name} \mid\mbox{\lstinline{@}}\nterm{name}\\ \nterm{params} &\mathrel{::=}&\inpars{\csl{\nterm{param}}}\\ \nterm{param} &\mathrel{::=}&\ofty{\nterm{name}}{\nterm{type}}\\ \nterm{rettype} &\mathrel{::=}&\mbox{\lstinline{->}}\ \nterm{type}\\ \nterm{typreds} &\mathrel{::=}&\mbox{\lstinline{where}}\ \csl{\nterm{typred}}\\ \nterm{typred} &\mathrel{::=}&\nterm{domain}\ \mbox{\lstinline{<=}}\ \nterm{domain}\\ &&\\ \newitem{Types:}\\ &&\\ \nterm{type} &\mathrel{::=}&\nterm{qualtype}\ \mnterm{rettype}\\ \nterm{qualtype} &\mathrel{::=}&\nterm{datatype}\ \mnterm{stage}\ \mnterm{domain}\\ \nterm{datatype} &\mathrel{::=}&\nterm{uintty} \mid\nterm{boolty} \mid\mbox{\lstinline+()+} \mid\listty{\nterm{type}\ \mebbe{\mbox{\lstinline{,}}}}\\ \nterm{uintty} &\mathrel{::=}&\mbox{\lstinline+uint+} \mid\uintmodty{\nterm{mod}}\\ \nterm{boolty} &\mathrel{::=}&\mbox{\lstinline+bool+} \mid\boolmodty{\nterm{mod}}\\ \nterm{mod} &\mathrel{::=}&\nterm{name} \mid\nterm{uintlit}\\ \nterm{stage} &\mathrel{::=}&\mbox{\lstinline+$pre+} \mid\mbox{\lstinline+$post+} \mid\mbox{\lstinline{$}}\nterm{name}\\ \nterm{domain} &\mathrel{::=}&\mbox{\lstinline+@public+} \mid\mbox{\lstinline+@verifier+} \mid\mbox{\lstinline+@prover+} \mid\mbox{\lstinline{@}}\nterm{name}\\ &&\\ \newitem{General classification of expressions:}\\ &&\\ \nterm{expr} &\mathrel{::=}&\nterm{largeexpr} \mid\nterm{smallexpr}\\ \nterm{largeexpr} &\mathrel{::=}&\nterm{blockexpr} \mid\nterm{ifexpr} \mid\nterm{forexpr} \mid\nterm{wireexpr}\\ \nterm{smallexpr} &\mathrel{::=}&\nterm{compexpr} \mid\nterm{primexpr}\\ \nterm{compexpr} &\mathrel{::=}&\nterm{assignexpr} \mid\nterm{loadexpr} \mid\nterm{opexpr} \mid\nterm{callexpr} \mid\nterm{castexpr}\\ \nterm{primexpr} &\mathrel{::=}&\nterm{name} \mid\nterm{uintlit} \mid\nterm{boollit} \mid\inpars{\nterm{expr}} \end{array}&\hspace{-9mm}\begin{array}[t]{lcl@{}} \newitem{``Large'' expressions and statements:}\\ &&\\ \nterm{blockexpr} &\mathrel{::=}&\inbraces{\lizt{\nterm{stmt}}\ \mnterm{smallexpr}}\\ \nterm{stmt} &\mathrel{::=}&\nterm{vardef}\ \mbox{\lstinline{;}} \mid\nterm{smallexpr}\ \mbox{\lstinline{;}} \mid\nterm{largeexpr}\ \mebbe{\mbox{\lstinline{;}}}\\ \nterm{vardef} &\mathrel{::=}&\letexpr{\mebbe{\mbox{\lstinline{rec}}}\ \mebbe{\mbox{\lstinline{mut}}}\ \nterm{name}\ \mebbep{\mbox{\lstinline{:}}\ \nterm{type}}}{\nterm{expr}}\\ \nterm{ifexpr} &\mathrel{::=}&\mbox{\lstinline{if}}\ \nterm{expr}\ \nterm{blockexpr}\ \mebbep{\mbox{\lstinline{else}}\ \nterm{blockexpr}}\\ \nterm{forexpr} &\mathrel{::=}&\forexpr{\nterm{name}}{\nterm{expr}}{\nterm{expr}}{\nterm{blockexpr}}\\ \nterm{wireexpr} &\mathrel{::=}&\wireexpr{\nterm{blockexpr}}\\ &&\\ \newitem{``Small'' expressions:}\\ &&\\ \nterm{assignexpr} &\mathrel{::=}&\assignexpr{\nterm{lvalexpr}}{\nterm{expr}}\\ \nterm{lvalexpr} &\mathrel{::=}&\nterm{name} \mid\nterm{loadexpr}\\ \nterm{loadexpr} &\mathrel{::=}&\loadexpr{\nterm{lvalexpr}}{\nterm{expr}}\\ \nterm{opexpr} &\mathrel{::=}&\opexpr{\nterm{smallexpr}}{\nterm{oper}}{\nterm{smallexpr}}\\ \nterm{callexpr} &\mathrel{::=}&\nterm{name}\ \inpars{\csl{\nterm{expr}}}\\ \nterm{castexpr} &\mathrel{::=}&\castexpr{\nterm{smallexpr}}{\nterm{casttype}}\\ \nterm{casttype} &\mathrel{::=}&\nterm{type} \mid\nterm{stage} \mid\nterm{domain} \end{array} \end{array} \] \caption{\label{syntax:ebnf} The syntax of a subset of \textsc{ZK-SecreC}\xspace} \end{figure} \fi \begin{figure}[tbp] \figsize\newcommand{\newitem}[1]{\multicolumn{3}{@{}l}{\bullet\hspace{1em}\mbox{#1}}} \[\setlength{\arraycolsep}{4pt}\begin{array}{@{}ll@{}} \begin{array}[t]{lcl} \newitem{Top-level structure of \textsc{ZK-SecreC}\xspace programs:}\\ &&\\ \nterm{prog} &\mathrel{::=}&\lizt{\nterm{fundef}}\\ \nterm{fundef} &\mathrel{::=}&\nterm{sig}\ \inbraces{\nterm{ex}}\\ \nterm{sig} &\mathrel{::=}&\nterm{name}\ \inpars{\lizt{\nterm{param}}}\ \nterm{rettype}\\ \nterm{param} &\mathrel{::=}&\ofty{\nterm{name}}{\nterm{type}}\\ \nterm{rettype} &\mathrel{::=}&\mbox{\lstinline{->}}\ \nterm{type}\\ &&\\ \newitem{Types:}\\ &&\\ \nterm{type} &\mathrel{::=}&\nterm{qualtype}\ \mnterm{rettype}\\ \nterm{qualtype} &\mathrel{::=}&\nterm{datatype}\ \mnterm{stage}\ \mnterm{domain}\\ \nterm{datatype} &\mathrel{::=}&\nterm{valtype} \mid\mbox{\lstinline+()+} \mid\listty{\nterm{type}}\\ \nterm{valtype} &\mathrel{::=}&\mbox{\lstinline+uint+} \mid\uintmodty{\nterm{mod}} \mid\mbox{\lstinline+bool+} \mid\boolmodty{\nterm{mod}}\\ \nterm{mod} &\mathrel{::=}&\nterm{uintlit}\\ \nterm{stage} &\mathrel{::=}&\mbox{\lstinline+$pre+} \mid\mbox{\lstinline+$post+}\\ \nterm{domain} &\mathrel{::=}&\mbox{\lstinline+@public+} \mid\mbox{\lstinline+@verifier+} \mid\mbox{\lstinline+@prover+} \end{array}&\begin{array}[t]{lcl@{}} \newitem{Expressions and statements:}\\ &&\\ \nterm{seqex} &\mathrel{::=}&\nterm{ex}\ \mbox{\lstinline{;}}\ \nterm{ex}\\ \nterm{vdex} &\mathrel{::=}&\nterm{vardef}\ \mbox{\lstinline{;}}\ \nterm{ex}\\ \nterm{vardef} &\mathrel{::=}&\letexpr{\mebbe{\mbox{\lstinline{mut}}}\ \nterm{name}\ \mebbep{\mbox{\lstinline{:}}\ \nterm{type}}}{\nterm{ex}}\\ \nterm{ifex} &\mathrel{::=}&\mbox{\lstinline{if}}\ \nterm{ex}\ \inbraces{\nterm{ex}}\ \mbox{\lstinline{else}}\ \inbraces{\nterm{ex}}\\ \nterm{forex} &\mathrel{::=}&\forexpr{\nterm{name}}{\nterm{ex}}{\nterm{ex}}{\nterm{ex}}\\ \nterm{wireex} &\mathrel{::=}&\wireexpr{\nterm{ex}}\\ \nterm{assignex} &\mathrel{::=}&\assignexpr{\nterm{lvalex}}{\nterm{ex}}\\ \nterm{lvalex} &\mathrel{::=}&\nterm{name} \mid\nterm{loadex}\\ \nterm{loadex} &\mathrel{::=}&\loadexpr{\nterm{lvalex}}{\nterm{ex}}\\ \nterm{opex} &\mathrel{::=}&\opexpr{\nterm{ex}}{\nterm{oper}}{\nterm{ex}}\\ \nterm{callex} &\mathrel{::=}&\nterm{name}\ \inpars{\lizt{\nterm{ex}}}\\ \nterm{castex} &\mathrel{::=}&\castexpr{\nterm{ex}}{\nterm{casttype}}\\ \nterm{casttype} &\mathrel{::=}&\nterm{qualtype} \mid\nterm{stage} \mid\nterm{domain} \end{array}\\ \multicolumn{2}{c}{ \begin{array}{lcl@{}} &&\\ \nterm{ex} &\mathrel{::=}&\nterm{seqex} \mid\nterm{vdex} \mid\nterm{ifex} \mid\nterm{forex} \mid\nterm{wireex} \mid\nterm{assignex} \mid\nterm{loadex} \mid\nterm{opex} \mid\nterm{callex} \mid\nterm{castex} \mid\nterm{name} \mid\nterm{uintlit} \mid\nterm{boollit} \end{array} } \end{array} \] \caption{\label{syntax:ebnf} The syntax of a subset of \textsc{ZK-SecreC}\xspace} \end{figure} A \textsc{ZK-SecreC}\xspace \emph{program} consists of \emph{function definitions}, including the main function. Every function definition contains its \emph{signature} and \emph{body}, the latter of which is an expression. Although \textsc{ZK-SecreC}\xspace supports type inference, due to which the types of local variables can be omitted, declaring the types of parameters in function definitions is still required. The type system of \textsc{ZK-SecreC}\xspace supports both parametric and ad-hoc polymorphism. The example in Fig.~\ref{language:factor} showed the use of \emph{type parameters} and \emph{type predicates} in the signatures of functions. An example of ad-hoc polymorphism occurs in the function \lstinline{bitextract}, where the control flow depends on the value of the type parameter \lstinline{@D}. Polymorphism is important in the reuse of \textsc{ZK-SecreC}\xspace code (i.e. libraries), but since it is orthogonal to the ZKP aspects of the language, we leave it out of consideration in Sects.~\ref{sec:syntax}--\ref{sec:compilation}. The polymorphic language can be converted to an internal monomorphic form using standard monomorphization techniques (code duplication, instantiation) since we do not support polymorphic recursion. The outermost structure of a \emph{type} represents it as a (curried) function type with zero or more argument types, each of which is a \emph{qualified type}. All qualified types in \textsc{ZK-SecreC}\xspace are triples consisting of a \emph{data type}, a \emph{stage} (prefixed with \lstinline{$}) and a \emph{domain} (prefixed with \lstinline{@}); the latter two are called \emph{qualifiers}. Stage and domain are allowed to be omitted; an omitted stage is inferred, whereas an omitted domain is read as the domain \lstinline{@public}. Currently, the primitive types in \textsc{ZK-SecreC}\xspace are \emph{Booleans}, \emph{(unsigned) integers}, and the unit type~$\mbox{\lstinline+()+}$ consisting of a single value. A list is a data structure of linear shape where all elements have equal type; the element type is given to the list type as parameter. The qualifiers of a list type do not necessarily coincide with those of the element type. For example, a list of domain $\mbox{\lstinline+@public+}$ can contain elements of domain $\mbox{\lstinline+@prover+}$, meaning that the shape of the list is known to the compiler while the elements are known to Prover only. The \emph{expressions} and \emph{statements} (which are not distinguished in \textsc{ZK-SecreC}\xspace; e.g. the if-then-else construct can be used both as a statement with side effects in the branches, or as a pure expression similar to the ternary conditional operator in C-style languages) are largely self-explanatory. Each expression returns a value (which may be of type~$\mbox{\lstinline+()+}$ in particular). Sequential execution ignores the return value of the first expression. A \emph{variable definition} introduces and initializes an immutable or a mutable (if the modifier \lstinline{mut} is present) variable; its type may be omitted, in which case it will be inferred. A \emph{for loop} of the form $\forexpr{x}{e_1}{e_2}{e_3}$ introduces a new variable~$x$, executes the loop body $e_3$ for each value of~$x$ in the half-open segment between the values of $e_1$ and~$e_2$, and returns all values of the loop body as a list. A \emph{wire expression} transforms local values to circuit inputs. We have omitted definitions for names and literals as they are intuitive. Most of the given definitions of composed expressions are intuitive, too. The nonterminal $\nterm{opex}$ expands to expressions constructed via binary operator application. Standard operator precedence is assumed which allows some pairs of parentheses to be omitted (it is not made explicit in the grammar). A \emph{cast expression} enables the programmer to convert between different types. One can provide either a complete type expression or just the domain or the stage instead. \section{Proof of Theorem~\ref{typesystem:thm} and Lemma~\ref{typesystem:lhslemma}}\label{typesystem-proofs} Before proving Theorem~\ref{typesystem:thm}, we have to establish that $\uopl{allpre}_{d'}$ holds on well-structured types only. \begin{lemma}\label{typesystem:lemma} Let $q=\qualty{t}{s}{d}$ be a qualified type and $d'$ be a domain. If $\uopl{allpre}_{d'}q$ then $q$ is well-structured. \end{lemma} \begin{proof} By induction on the structure of~$t$: \begin{itemize} \item If $t$ is a primitive type then $q=\qualty{t}{\mbox{\lstinline+$pre+}}{d'}$ which is well-structured by Definition~\ref{typesystem:def}. \item Let $t=\listty{q'}$. Then $q=\qualty{\listty{q'}}{\mbox{\lstinline+$pre+}}{d'}$, i.e., $s=\mbox{\lstinline+$pre+}$ and $d=d'$, and $\uopl{allpre}_{d'}q'$. By the induction hypothesis, $q'$ is well-structured. We know by the definition of $\uopl{allpre}_{d'}$ that $q'=\qualty{t'}{\mbox{\lstinline+$pre+}}{d'}$ for some datatype $t'$. Hence $\gen{d}=\gen{d'}=\varnothing\cup\gen{d'}=\gen{\mbox{\lstinline+$pre+}}\cup\gen{d'}$ which completes the proof. \end{itemize} \end{proof} \begin{theorem}[Theorem~\ref{typesystem:thm}] If\/ $\Gamma\mbox{\ $\vdash$\ } e : q! D$ with a well-structured~$\Gamma$ then $q$ is well-structured. \end{theorem} \begin{proof} Let $q=\qualty{t}{s}{d}$. We proceed by induction of the structure of~$e$: \begin{itemize} \item If $e=\epsilon$, $e=\overline{n}$, $e=\overline{b}$, $e=\mbox{\lstinline+assert+}(e')$, $e=\mbox{\lstinline+wire+ }\inbraces{e'}$ or $e=(\mbox{$l$ \lstinline+=+ $e'$})$ then $t$ is primitive, whereby $t=()$ implies $s=\mbox{\lstinline+$pre+}$. Hence $q$ is well-structured. \item If $e=x$ then the claim follows from the assumption that $\Gamma$ is well-structured. \item If $e=\ofty{\getexpr{d}{k}}{q}$ then $\uopl{allpre}_dq$ and the claim follows from Lemma~\ref{typesystem:lemma}. \item Suppose $e=\mbox{$e_1$ \lstinline{+} $e_2$}$. Then $t=\mbox{\lstinline{uint[N]}}$, and $\Gamma\mbox{\ $\vdash$\ } e_1:t\ s\ d! D_1$ and $\Gamma\mbox{\ $\vdash$\ } e_2:t\ s\ d! D_2$. Hence by the induction hypothesis, $t\ s\ d$ is well-structured, and the desired claim follows. \item Suppose $e=\mbox{\lstinline+if+ $e_1$ \inbraces{$e_2$} \lstinline+else+ \inbraces{$e_3$}}$. Then $\Gamma\mbox{\ $\vdash$\ } e_2:t\ s\ d! D_2$ and $\Gamma\mbox{\ $\vdash$\ } e_3:t\ s\ d! D_3$. Hence by the induction hypothesis, $t\ s\ d$ is well-structured, and the desired claim follows. \item Suppose $e=\mbox{\lstinline+for+ $x$ \lstinline+in+ $e_1$ \lstinline+..+ $e_2$ }\inbraces{e_3}$. Then $t=\mbox{\lstinline+list+ }\inbracks{t'\ s'\ d'}$, $s=\mbox{\lstinline+$pre+}$ and $\Gamma\mbox{\ $\vdash$\ } e_i:\mbox{\lstinline{uint[N]} \lstinline+$pre+}\ d! D_i$ ($i=1,2$), $(x:\mbox{\lstinline+uint[N]+ \lstinline+$pre+}\ d),\Gamma\mbox{\ $\vdash$\ } e_3:t'\ s'\ d'! D_3$, whereby $\gen{d}\supseteq\gen{s'}\cup\gen{d'}\cup D_3$. By the induction hypothesis for $e_1$ and $e_2$, the qualified type $\mbox{\lstinline{uint[N]} \lstinline+$pre+}\ d$ is well-structured. Therefore, the extended type environment $(x:\mbox{\lstinline+uint[N]+ \lstinline+$pre+}\ d),\Gamma$ is well-structured. Hence the induction hypothesis for $e_3$ implies that $t'\ s'\ d'$ is well-structured. This completes checking the assumptions of $\mbox{\lstinline+list+ }\inbracks{t'\ s'\ d'}\ s\ d$ being well-structured by Definition~\ref{typesystem:def}, hence the desired claim follows. \item Suppose $e=e'\mbox{ \lstinline{as} }t\ s\ d$. Then $\Gamma\mbox{\ $\vdash$\ } e':t\ s'\ d'$, $s'\mathrel{\mathchar"13C\mathchar"3A} s$, $d'\mathrel{\mathchar"13C\mathchar"3A} d$, and $\gen{d}\supseteq\gen{t}$. By the induction hypothesis, $t\ s'\ d'$ is well-structured. If $t$ is a primitive type then $t\ s\ d$ is well-structured, too, as $s'=\mbox{\lstinline+$pre+}$ implies $s=\mbox{\lstinline+$pre+}$. Now let $t=\mbox{\lstinline+list+ }\inbracks{t''\ s''\ d''}$; by $t\ s'\ d'$ being well-structured, we have $s'=\mbox{\lstinline+$pre+}$, $\gen{d'}\supseteq\gen{s''}\cup\gen{d''}$ and $t''\ s''\ d''$ well-structured. Therefore $s=\mbox{\lstinline+$pre+}$. Moreover, using $\gen{d}\supseteq\gen{t}$ and the definition of $\gen{t}$, we obtain $\gen{d}\supseteq\gen{t''}\cup\gen{s''}\cup\gen{d''}\supseteq\gen{s''}\cup\gen{d''}$. Hence $t\ s\ d$ is well-structured by Definition~\ref{typesystem:def}. \item Suppose $e=l\inbracks{e'}$. Then $\Gamma\mbox{\ $\vdash$\ } l:t'\ s'\ d'! D'$ where $t'=\mbox{\lstinline+list+}\inbracks{t\ s\ d}$. By the induction hypothesis, $t'\ s'\ d'$ is well-structured. Definition~\ref{typesystem:def} now implies $t\ s\ d$ also being well-structured. \item Suppose $e=\mbox{\lstinline+let+ }x:t'\ s'\ d'\mbox{ \lstinline+=+ }e_1\mbox{\lstinline{;}}\ e_2$. Then $\Gamma\mbox{\ $\vdash$\ } e_1:t'\ s'\ d'! D_1$ and $(x:t'\ s'\ d'),\Gamma\mbox{\ $\vdash$\ } e_2:t\ s\ d! D_2$. By the induction hypothesis for $e_1$, qualified type $t'\ s'\ d'$ is well-structured. Therefore, the extended type environment $(x:t'\ s'\ d'),\Gamma$ is well-structured. Hence the induction hypothesis for $e_2$ implies that $t\ s\ d$ is well-structured. \item If $e=e_1\mbox{\lstinline{;}}\ e_2$ then $\Gamma\mbox{\ $\vdash$\ } e_2:t\ s\ d! D_2$, whence the induction hypothesis implies $t\ s\ d$ being well-structured. \end{itemize} \end{proof} \begin{lemma}[Lemma~\ref{typesystem:lhslemma}] Let $\Gamma\mbox{\ $\vdash$\ } e:q! D$, where $q=(\qualty{t}{s}{d})$ and $\Gamma$ is well-structured. Let $e=\loadexpr{\loadexpr{\loadexpr{x}{y_1}}{y_2}\ldots}{y_n}$ where $x$ is a variable. Then there exist domains $d_1,\ldots,d_n$ and upward closed domain sets $D_1,\ldots,D_n$ such that $\Gamma\mbox{\ $\vdash$\ } y_i:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_i}! D_i$ for each $i=1,\ldots,n$ and \[ \Gamma\mbox{\ $\vdash$\ } x:\qualty{\listty{\ldots\listty{\qualty{\listty{\qualty{\listty{q}}{\mbox{\lstinline+$pre+}}{d_n}}}{\mbox{\lstinline+$pre+}}{d_{n-1}}}\ldots}}{\mbox{\lstinline+$pre+}}{d_1}!\varnothing\mbox{,} \] whereby $d_1\mathrel{\mathchar"13C\mathchar"3A}\ldots\mathrel{\mathchar"13C\mathchar"3A} d_{n-1}\mathrel{\mathchar"13C\mathchar"3A} d_n\mathrel{\mathchar"13C\mathchar"3A} d$ and $D=D_1\cup\ldots\cup D_n$. \end{lemma} \begin{proof} We prove the claim by induction on~$n$. If $n=0$ then $x=e$ and the claim holds trivially. Now suppose that $n>0$ and the claim holds for $n-1$. As $\Gamma\mbox{\ $\vdash$\ }\loadexpr{\loadexpr{\loadexpr{x}{y_1}}{y_2}\ldots}{y_n}:q! D$, we must have a domain $d_n$ and upward closed domain sets~$D',D_n$ such that \[ \begin{array}{l} \Gamma\mbox{\ $\vdash$\ }\loadexpr{\loadexpr{\loadexpr{x}{y_1}}{y_2}\ldots}{y_{n-1}}:\qualty{\listty{q}}{\mbox{\lstinline+$pre+}}{d_n}! D'\mbox{,}\\ \Gamma\mbox{\ $\vdash$\ } y_n:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_n}! D_n\mbox{,}\\ D=D'\cup D_n\mbox{.} \end{array} \] By the induction hypothesis, $\Gamma\mbox{\ $\vdash$\ } y_i:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_i}! D_i$ for each $i=1,\ldots,n-1$, and \[ \Gamma\mbox{\ $\vdash$\ } x:\qualty{\listty{\ldots\listty{\qualty{\listty{\qualty{\listty{q}}{\mbox{\lstinline+$pre+}}{d_n}}}{\mbox{\lstinline+$pre+}}{d_{n-1}}}\ldots}}{\mbox{\lstinline+$pre+}}{d_1}!\varnothing\mbox{,} \] whereby $d_1\mathrel{\mathchar"13C\mathchar"3A}\ldots\mathrel{\mathchar"13C\mathchar"3A} d_{n-1}\mathrel{\mathchar"13C\mathchar"3A} d_n$ and $D'=D_1\cup\ldots\cup D_{n-1}$. As $D=D'\cup D_n$, the latter implies $D=D_1\cup\ldots\cup D_n$. By $\Gamma$ being well-structured and Theorem~\ref{typesystem:thm}, the type of~$x$ is well-structured, whence also $d_n\mathrel{\mathchar"13C\mathchar"3A} d$. \end{proof} \section{Static Semantics}\label{sec:typesystem} The security guarantees of \textsc{ZK-SecreC}\xspace are established by its type system. Types are checked (and inferred in certain cases) during compile time, hence the type system is part of the static semantics of \textsc{ZK-SecreC}\xspace. In this section, we describe a static semantics that traces also effects (e.g., assertions and mutable variable updates) that expression evaluation can cause. The type system makes sure that the program can be translated into the circuit, and into Prover's and Verifier's local computations. In Sec.~\ref{sec:syntax}, we explained our non-treatment of type parameters. For analogous reasons, we skip function definitions and user-defined function calls in our treatment; a few most important or representative built-in functions are considered. Assertions in the type rules are of the form $\Gamma \mbox{\ $\vdash$\ } e : t ! D$. Here, $\Gamma$~is a type environment, $e$~is an expression, $t$~is a qualified type, and $D$~is an upward closed set of domains, assuming the ordering $\mbox{\lstinline+@public+}\mathrel{\mathchar"13C\mathchar"3A}\mbox{\lstinline+@verifier+}\mathrel{\mathchar"13C\mathchar"3A}\mbox{\lstinline+@prover+}$ of growing privacy. A type assertion states that under the constraints imposed by~$\Gamma$, the expression~$e$ has type~$t$ and running it can cause effects in domains belonging to the set~$D$. For example, an assignment to a mutable variable whose domain is $\mbox{\lstinline+@prover+}$ causes an effect in domain $\mbox{\lstinline+@prover+}$. In discussions, we will sometimes omit effects from type assertions if the effects are not important. A type environment is a finite association list consisting of the following kinds of components: \begin{itemize} \item Variable typings written in the form $x:q$, where $x$~is a variable and $q$ is a qualified type; \item Mutability statements in the form $\uopl{mut} x:b$ where $x$ is a variable and $b$~is its mutability status ($0$ or $1$). \end{itemize} We write $(z:w),\Gamma$ to denote a new type environment containing the association $(z:w)$ followed by all associations in~$\Gamma$. We also write $\lookup{\Gamma}{z}$ for lookup of~$z$ in the type environment~$\Gamma$, i.e., if $\Gamma=((z_1:w_1),\ldots,(z_n:w_n))$ then $\lookup{\Gamma}{z}=w_i$ where $i$ is the least index such that $z_i=z$. Note that $z$ is a variable possibly equipped with $\uopl{mut}$, and $w$ is either a qualified type or a mutability status, respectively. If the associations of variables to qualified types of $\Gamma$ are $(x_1:q_1),\ldots,(x_n:q_n)$, in this order, then we denote $\uopl{vars}\Gamma=(x_1,\ldots,x_n)$. \begin{figure*}\figsize\renewcommand{\arraystretch}{2.2} \begin{tabular}{@{}c@{}} \begin{prooftree} \infer0{\Gamma \mbox{\ $\vdash$\ } \epsilon : \qualty{\mbox{\lstinline+()+}}{\mbox{\lstinline+$pre+}}{\mbox{\lstinline+@public+}} ! \varnothing} \end{prooftree}\quad \begin{prooftree} \hypo{n\in\mathbb{N}} \infer1{\Gamma \mbox{\ $\vdash$\ } \overline{n} : \qualty{\uintmodty{\mbox{\lstinline{N}}}}{s}{d} ! \gen{s}} \end{prooftree}\quad \begin{prooftree} \hypo{b\in\mathbb{B}} \infer1{\Gamma \mbox{\ $\vdash$\ } \overline{b} : \qualty{\boolmodty{\mbox{\lstinline{N}}}}{s}{d} ! \gen{s}} \end{prooftree}\quad \begin{prooftree} \hypo{\lookup{\Gamma}{x}=(\qualty{t}{s}{d})} \infer1{\Gamma \mbox{\ $\vdash$\ } x : \qualty{t}{s}{d} ! \varnothing} \end{prooftree}\\ \begin{prooftree} \hypo{\Gamma \mbox{\ $\vdash$\ } e_1 : \qualty{\uintmodty{\mbox{\lstinline{N}}}}{s}{d} ! D_1} \hypo{\Gamma \mbox{\ $\vdash$\ } e_2 : \qualty{\uintmodty{\mbox{\lstinline{N}}}}{s}{d} ! D_2} \infer2{\Gamma \mbox{\ $\vdash$\ } \addexpr{e_1}{e_2} : \qualty{\uintmodty{\mbox{\lstinline+N+}}}{s}{d} ! \gen{s}\cup D_1\cup D_2} \end{prooftree}\quad \begin{prooftree} \hypo{\Gamma \mbox{\ $\vdash$\ } e : \qualty{\boolmodty{\mbox{\lstinline{N}}}}{\mbox{\lstinline+$post+}}{d} ! D} \infer1{\Gamma \mbox{\ $\vdash$\ } \assertexpr{e} : \qualty{\mbox{\lstinline+()+}}{\mbox{\lstinline+$pre+}}{\mbox{\lstinline+@public+}} ! \gen{\mbox{\lstinline+@public+}}} \end{prooftree}\\ \begin{prooftree} \hypo{\uopl{allpre}_{d'}(\qualty{t}{s}{d})} \infer1{\Gamma \mbox{\ $\vdash$\ } (\ofty{\getexpr{d'}{k}\!}{\!\qualty{t}{\!s\!}{d}})\!:\!\qualty{t}{\!s\!}{d}!\!\varnothing} \end{prooftree}\quad \begin{prooftree} \hypo{\Gamma \mbox{\ $\vdash$\ } e_1 : \qualty{\boolmodty{\mbox{\lstinline{N}}}}{\mbox{\lstinline+$pre+}}{d'} ! D_1} \hypo{\Gamma \mbox{\ $\vdash$\ } e_i : \qualty{t}{s}{d} ! D_i\ (i=2,3)} \hypo{\gen{d'}\supseteq\gen{s}\cup\gen{d} \cup D_2 \cup D_3} \infer3{\Gamma \mbox{\ $\vdash$\ } \ifexpr{e_1}{e_2}{e_3} : \qualty{t}{s}{d} ! D_1 \cup D_2 \cup D_3} \end{prooftree}\\ \begin{prooftree} \hypo{\Gamma \mbox{\ $\vdash$\ } e_i : \qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d'} ! D_i\ (i=1,2)} \hypo{(x : \qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d'}), \Gamma \mbox{\ $\vdash$\ } e_3 : \qualty{t}{s}{d} ! D_3} \hypo{\gen{d'} \supseteq \gen{s}\cup\gen{d}\cup D_3} \infer3{\Gamma \mbox{\ $\vdash$\ } \forexpr{x}{e_1}{e_2}{e_3} : \qualty{\listty{\qualty{t}{s}{d}}}{\mbox{\lstinline+$pre+}}{d'} ! D_1 \cup D_2 \cup D_3} \end{prooftree}\\ \begin{prooftree} \hypo{\Gamma \mbox{\ $\vdash$\ } e : \qualty{t}{\mbox{\lstinline+$pre+}}{d} ! D} \hypo{t\in\set{\uintmodty{\mbox{\lstinline{N}}},\boolmodty{\mbox{\lstinline{N}}}}} \infer2{\Gamma \mbox{\ $\vdash$\ } \wireexpr{e} : \qualty{t}{\mbox{\lstinline+$post+}}{d}! \gen{\mbox{\lstinline+@public+}}} \end{prooftree}\qquad \begin{prooftree} \hypo{\Gamma \mbox{\ $\vdash$\ } e : \qualty{t}{s}{d} ! D} \hypo{s \mathrel{\mathchar"13C\mathchar"3A} s'} \hypo{d \mathrel{\mathchar"13C\mathchar"3A} d'} \hypo{\gen{d'}\supseteq\gen{t}} \infer4{\Gamma \mbox{\ $\vdash$\ } \castexpr{e}{\qualty{t}{s'}{d'}} : \qualty{t}{s'}{d'} ! D} \end{prooftree}\\ \begin{prooftree} \hypo{\Gamma \mbox{\ $\vdash$\ } e : \qualty{t}{s}{d} ! D} \hypo{\Gamma \mbox{\ $\vdash$\ } l : \qualty{t}{s}{d} ! D'} \hypo{\lookup{\Gamma}{\uopl{mut}(\uopl{var} l)}=1} \infer3{\Gamma \mbox{\ $\vdash$\ } \assignexpr{l}{e} : \qualty{\mbox{\lstinline+()+}}{\mbox{\lstinline+$pre+}}{\mbox{\lstinline+@public+}} ! \gen{s}\cup\gen{d} \cup D \cup D'} \end{prooftree}\quad \begin{prooftree} \hypo{\Gamma \mbox{\ $\vdash$\ } l : \qualty{\listty{\qualty{t}{s}{d}}}{s'}{d'} ! D'} \hypo{\Gamma \mbox{\ $\vdash$\ } e : \qualty{\mbox{\lstinline+uint+}}{s'}{d'} ! D} \infer2{\Gamma \mbox{\ $\vdash$\ } \loadexpr{l}{e} : \qualty{t}{s}{d} ! D \cup D'} \end{prooftree}\\ \begin{prooftree} \hypo{\Gamma \mbox{\ $\vdash$\ } e_1 : \qualty{t_1}{s_1}{d_1} ! D_1} \hypo{(\uopl{mut} x : b), (x : \qualty{t_1}{s_1}{d_1}), \Gamma \mbox{\ $\vdash$\ } e_2 : \qualty{t_2}{s_2}{d_2} ! D_2} \infer2{\Gamma \mbox{\ $\vdash$\ } \stmtcomp{\letexpr{\mbox{\lstinline{mut}}^b\ x}{e_1}}{e_2} : \qualty{t_2}{s_2}{d_2} ! \gen{d_1} \cup D_1 \cup D_2} \end{prooftree}\quad \begin{prooftree} \hypo{\Gamma \mbox{\ $\vdash$\ } e_1 : \qualty{t_1}{s_1}{d_1} ! D_1} \hypo{\Gamma \mbox{\ $\vdash$\ } e_2 : \qualty{t_2}{s_2}{d_2} ! D_2} \infer2{\Gamma \mbox{\ $\vdash$\ } \stmtcomp{e_1}{e_2} : \qualty{t_2}{s_2}{d_2} ! D_1 \cup D_2} \end{prooftree} \end{tabular} \caption{\label{typesystem:exprstmt} Typing rules of expressions and statements of a subset of \textsc{ZK-SecreC}\xspace without parametric polymorphism} \end{figure*} The static semantics is presented in Fig.~\ref{typesystem:exprstmt}. The data type derivation parts of the rules are standard. Hence we mainly comment on stages, domains and effects. There exist four upward closed domain sets linearly ordered by inclusion: $\varnothing\subset\gen{\mbox{\lstinline+@prover+}}\subset\gen{\mbox{\lstinline+@verifier+}}\subset\gen{\mbox{\lstinline+@public+}}$, where $\gen{d}$ denotes the set consisting of domain~$d$ and all larger domains. Thus the union of upward closed sets always equals the largest set in the union. We also order stages as $\mbox{\lstinline+$post+}\mathrel{\mathchar"13C\mathchar"3A}\mbox{\lstinline+$pre+}$, reflecting that data computed in the circuit are also computed locally in the corresponding domain in order to be ready to provide expanded instances/witnesses to the circuit. \textsc{ZK-SecreC}\xspace requires conversion to supertype to be made explicit using the \lstinline{as} keyword. The first rule in Fig.~\ref{typesystem:exprstmt} handles missing expression~$\epsilon$; it is needed for the case where the last expression of a sequential execution is absent. Integer and Boolean literals are denoted by overlined constants. We show only rules for $\uintmodty{\mbox{\lstinline{N}}}$ and $\boolmodty{\mbox{\lstinline{N}}}$; rules for $\mbox{\lstinline+uint+}$ and $\mbox{\lstinline+bool+}$ in stage $\mbox{\lstinline+$pre+}$ are similar. Literals can be typed with any stage and domain (i.e., no type cast is required). The effect of literals depends on their actual stage: In stage $\mbox{\lstinline+$pre+}$ they do not have any effect, while in stage $\mbox{\lstinline+$post+}$, they have public effect since there they contribute to constructing of the circuit. In general, any operation in the circuit is considered a public effect. To specify the possible effects concisely in the rules, we extend the $\gen{\cdot}$ notation to stages by $\gen{\mbox{\lstinline+$pre+}}=\varnothing$, $\gen{\mbox{\lstinline+$post+}}=\gen{\mbox{\lstinline+@public+}}$, and also to data types by $\gen{t}=\varnothing$ if $t$~{}is a primitive type and $\gen{t}=\gen{t'}\cup\gen{s'}\cup\gen{d'}$ if $t=\listty{\qualty{t'}{s'}{d'}}$. (This way, the result of the $\gen{\cdot}$ operation is always an upward closed set of domains.) Types of variables are read directly from the type environment without an effect. The rule for addition allows this operation to be performed in any domain and stage, but the domain of the arguments and the result must be the same and similarly for stages. The rule for \lstinline+assert+ establishes the result data type to be the unit type. The unit type, as well as list types, is always in the stage $\mbox{\lstinline+$pre+}$ since the circuit does not deal with values of these types. In any domain, the slice of the program available to local computation of that domain can read input data. The \textsc{ZK-SecreC}\xspace functions for that are \lstinline{get_public}, \lstinline{get_instance} and \lstinline{get_witness} which read the public constants, the instance, and the witness, respectively (all non-expanded). Here we denote these functions uniformly by $\mbox{\lstinline{get}}_d$ where $d=\mbox{\lstinline+@public+}$, $d=\mbox{\lstinline+@verifier+}$ and $d=\mbox{\lstinline+@prover+}$, respectively, so the rule for $\mbox{\lstinline+get+}_d$ captures all three cases. An argument of the function $\mbox{\lstinline{get}}_d$ is a key of a dictionary and the function returns the corresponding value in the dictionary. String literals are used as keys. The type of an expression of the form $\getexpr{d'}{k}$ cannot be derived from its constituents as the dictionary need not be available for the type checker. Therefore, the type rule for such expressions requires them to be explicitly typed. The only restriction we impose on the result type is $\uopl{allpre}_{d'}(\qualty{t}{s}{d})$ which is to denote that all types occurring in $\qualty{t}{s}{d}$ must be qualified with $\qual{\mbox{\lstinline+$pre+}}{d'}$. More precisely, $\uopl{allpre}_{d'}(\qualty{t}{s}{d})$ is true iff $s=\mbox{\lstinline+$pre+}$, $d=d'$ and in the case $t=\listty{q'}$ also $\uopl{allpre}_{d'}(q')$. The rules for conditional expressions and loops restrict the stage of guards to $\mbox{\lstinline+$pre+}$, meaning that branchings happen only in local computations. For conditional expressions, the restriction $\gen{d'}\supseteq\gen{s}\cup\gen{d}\cup D_2\cup D_3$ serves the following purposes: \begin{itemize} \item $\gen{d'}\supseteq\gen{d}$ (i.e., $d'\mathrel{\mathchar"13C\mathchar"3A} d$) makes the output of the conditional expression to have at least as high privacy level as the guard (the \emph{no-read-up} property); \item $\gen{d'}\supseteq D_2\cup D_3$ disallows information flows through side effects of the branches (the \emph{no-write-down} property); \item $\gen{d'}\supseteq\gen{s}$ ensures that, if the expression is computed by the circuit, then the branch that must be taken is known at the compile-time (also an instance of \emph{no-write-down}, as all computations by the circuit have visible side-effects). \end{itemize} The restriction $\gen{d'}\supseteq\gen{s}\cup\gen{d}\cup D_3$ in the loop rule provides similar guarantees. For example, if the body of a loop performs assertions then the loop bounds must be in the domain $\mbox{\lstinline+@public+}$. A type cast can extend the type of a given expression but not reduce it. Moreover, the condition $\gen{d'}\supseteq\gen{t}$ of the cast rule guarantees a type invariant that prevents list elements from revealing information about the list structure to domains of lower privacy (via lookups). This invariant is formally established in Definition~\ref{typesystem:def} and Theorem~\ref{typesystem:thm}. The l.h.s. of an assignment can be complex, consisting of a variable followed by an index vector. Let $\uopl{var} l$ for any L-value expression~$l$ denote the variable whose mutability permits assignment to this L-value, i.e., $\uopl{var} l=l$ if $l$~is a variable, and $\uopl{var} l=\uopl{var} l'$ if $l$ is $\mbox{$l'$\inbracks{$e$}}$. The assignment rule states that the return value of an assignment expression is of the unit data type and the effect of an assignment belongs to the domain $\mbox{\lstinline+@public+}$ if the operands are in stage $\mbox{\lstinline+$post+}$, otherwise the effect belongs to the same domain~$d$ as the operands. The type structure and effects of the contents of the l.h.s. is the topic of Lemma~\ref{typesystem:lhslemma}. In the list element access rule, the index must be in the same domain as the list structure since accessing an element via its index may reveal information about the length of the list. Reading does not introduce new effects. In the rule for let statements, $\mbox{\lstinline{mut}}^1$ stands for $\mbox{\lstinline{mut}}$ keyword and $\mbox{\lstinline{mut}}^0$ means empty string, so the rule applies to both immutable and mutable variable definitions. Mutability information is reflected in the type environment when type checking the expression~$e_2$. We consider variable definition to be effectful, whence~$\gen{d_1}$ is added into the set of effects. The last rule similarly handles statement sequences but applies to the case where the first statement does not define new variables. The following definition~\ref{typesystem:def} and theorem~\ref{typesystem:thm} are essential. Proof of the theorem goes by induction on the structure of~$e$. The details are given in Appendix~\ref{typesystem-proofs}. \begin{definition}\label{typesystem:def} Let $q=\qualty{t}{s}{d}$ be a qualified type. We call $q$ \emph{well-structured} if either $t$~{}is a primitive type, whereby $s=\mbox{\lstinline+$pre+}$ in the case of $t=\mbox{\lstinline+()+}$; or $s=\mbox{\lstinline+$pre+}$ and $t=\listty{\qualty{t'}{s'}{d'}}$ such that $\gen{d}\supseteq\gen{s'}\cup\gen{d'}$ and $\qualty{t'}{s'}{d'}$ is well-structured. Call a type environment $\Gamma$ \emph{well-structured} if all qualified types occurring in it are well-structured. \end{definition} \begin{theorem}\label{typesystem:thm} If\/ $\Gamma$ is well-structured and $\Gamma\mbox{\ $\vdash$\ } e : q! D$, then $q$ is well-structured. \end{theorem} Proofs of many theorems of the following sections rely on Lemma~\ref{typesystem:lhslemma}, which is itself proved by induction on the length of index vector: \begin{lemma}\label{typesystem:lhslemma} Let $e=\loadexpr{\loadexpr{\loadexpr{x}{y_1}}{y_2}\ldots}{y_n}$ where $x$ is a variable. Let $\Gamma\mbox{\ $\vdash$\ } e:q! D$, where $q=(\qualty{t}{s}{d})$ and $\Gamma$ is well-structured. Then there exist domains $d_1,\ldots,d_n$ and upward closed domain sets $D_1,\ldots,D_n$ such that $\Gamma\mbox{\ $\vdash$\ } y_i:\qualty{\mbox{\lstinline+uint+}}{\mbox{\lstinline+$pre+}}{d_i}! D_i$ for each $i=1,\ldots,n$ and \[ \Gamma\mbox{\ $\vdash$\ } x:\qualty{\listty{\ldots\listty{\qualty{\listty{\qualty{\listty{q}}{\mbox{\lstinline+$pre+}}{d_n}}}{\mbox{\lstinline+$pre+}}{d_{n-1}}}\ldots}}{\mbox{\lstinline+$pre+}}{d_1}!\varnothing\mbox{,} \] whereby $d_1\mathrel{\mathchar"13C\mathchar"3A}\ldots\mathrel{\mathchar"13C\mathchar"3A} d_{n-1}\mathrel{\mathchar"13C\mathchar"3A} d_n\mathrel{\mathchar"13C\mathchar"3A} d$ and $D=D_1\cup\ldots\cup D_n$. \end{lemma} The details of the proof are given in Appendix~\ref{typesystem-proofs}.
{'timestamp': '2022-08-29T02:13:36', 'yymm': '2203', 'arxiv_id': '2203.15448', 'language': 'en', 'url': 'https://arxiv.org/abs/2203.15448'}
arxiv