Dataset Preview Go to dataset viewer
text (string)label (class label)
Constrained Submodular Maximization via a Non-symmetric Technique arXiv:1611.03253v1 [cs.DS] 10 Nov 2016 Niv Buchbinder∗ Moran Feldman† November 11, 2016 Abstract The study of combinatorial optimization problems with a submodular objective has attracted much attention in recent years. Such problems are important in both theory and practice because their objective functions are very general. Obtaining further improvements for many submodular maximization problems boils down to finding better algorithms for optimizing a relaxation of them known as the multilinear extension. In this work we present an algorithm for optimizing the multilinear relaxation whose guarantee improves over the guarantee of the best previous algorithm (which was given by Ene and Nguyen (2016)). Moreover, our algorithm is based on a new technique which is, arguably, simpler and more natural for the problem at hand. In a nutshell, previous algorithms for this problem rely on symmetry properties which are natural only in the absence of a constraint. Our technique avoids the need to resort to such properties, and thus, seems to be a better fit for constrained problems. ∗ Department of Statistics and Operations Research, School of Mathematical Sciences, Tel Aviv university, Israel. Email: niv.buchbinder@gmail.com. † Depart. of Mathematics and Computer Science, The Open University of Israel. Email: moranfe@openu.ac.il. 1 Introduction The study of combinatorial optimization problems with a submodular objective has attracted much attention in recent years. Such problems are important in both theory and practice because their objective functions are very general—submodular functions generalize, for example, cuts functions of graphs and directed graphs, the mutual information function, matroid weighted rank functions and log-determinants. More specifically, from a theoretical perspective, many well-known problems in combinatorial optimization are in fact submodular maximization problems, including: Max-Cut [30, 33, 38, 40, 56], Max-DiCut [20, 30, 31], Generalized Assignment [10, 14, 22, 27], Max-k-Coverage [19, 41], Max-Bisection [3, 28] and Facility Location [1, 16, 17]. From a practical perspective, submodular maximization problems have found uses in social networks [32, 39], vision [5, 36], machine learning [43, 44, 45, 49, 50] and many other areas (the reader is referred, for example, to a comprehensive survey by Bach [4]). The techniques used by approximation algorithms for submodular maximization problems usually fall into one of two main approaches. The first approach is combinatorial in nature, and is mostly based on local search techniques and greedy rules. This approach has been used as early as the late 70’s for maximizing a monotone submodular function subject to a matroid constraint (some of these works apply only to specific types of matroids) [15, 26, 34, 35, 37, 42, 53, 54]. Later works used this approach to handle also problems with non-monotone submodular objective functions and different constraints [6, 21, 25, 47, 48], yielding in some cases optimal algorithms [6, 55]. However, algorithms based on this approach tend to be highly tailored for the specific structure of the problem at hand, making extensions quite difficult. The second approach used by approximation algorithms for submodular maximization problems overcomes the above obstacle. This approach resembles a common paradigm for designing approximation algorithms and involves two steps. In the first step a fractional solution is found for a relaxation of the problem, known as the multilinear relaxation. In the second step the fractional solution is rounded to obtain an integral one while incurring a bounded loss in the objective. This approach has been used to obtain improved approximations for many problems [8, 11, 12, 24, 46]. Various techniques have been developed for rounding the fractional solution. These techniques tend to be quite flexible, and usually can extend to many related problem. In particular, the Contention Resolution Schemes framework of [12] yields a rounding procedure for every constraint which can be presented as the intersection of a few basic constraints such as knapsack constraints, matroid constraints and matching constraints. Given this wealth of rounding procedures, obtaining further improvements for many important submodular maximization problems (such as maximizing a submodular function subject to a matroid or knapsack constraint) boils down to obtaining improved algorithms for finding a good fractional solution, i.e., optimizing the multilinear relaxation. 1.1 Maximizing the Multilinear Relaxation At this point we would like to present some terms more formally. A submodular function is a set function f : 2N → R obeying f (A) + f (B) ≥ f (A ∪ B) + f (A ∩ B) for any sets A, B ⊆ N . A submodular maximization problem is the problem of finding a set S ⊆ N maximizing f subject to some constraint. Formally, let I be the set of subsets of N obeying the constraint. Then, we are interested in the following problem. max f (A) s.t. A ∈ I ⊆ 2N A relaxation of the above problem replaces I with a polytope P ⊆ [0, 1]N containing the 1 characteristic vectors of all the sets of I. In addition, a relaxation must replace the function f with an extension function F : [0, 1]N → R. Thus, a relaxation is a fractional problem of the following format. max F (x) s.t. x ∈ P ⊆ [0, 1]N Defining the “right” extension function, F , for the relaxation is a challenge, as, unlike the linear case, there is no single natural candidate. The objective that turned out to be useful, and is, thus, used by multilinear relaxation is known as the multilinear extension (first introduced by [8]). The value F (x) of this extension for any vector x ∈ [0, 1]N is defined as the expected value of f over a random subset R(x) ⊆ N containing every element u ∈ N independently with probability xu . Formally, for every x ∈ [0, 1]N , Y X Y (1 − xu ) . F (x) = E[R(x)] = f (S) xu S⊆N u∈S u∈S / The first algorithm for optimizing the multilinear relaxation was the Continuous Greedy algorithm designed by Calinescu et al. [8]. When the submodular function f is non-negative and monotone1 and P is solvable2 this algorithm finds a vector x ∈ P such that E[F (x)] ≥ (1 − 1/e − o(1)) · f (OP T ) (where OP T is the set maximizing f among all sets whose characteristic vectors belongs to P ). Interestingly, the guarantee of Continuous Greedy is optimal for monotone functions even when P is a simple cardinality constraint [8, 53]. Optimizing the multilinear relaxation when f is not necessarily monotone proved to be a more challenging task. Initially, several algorithms for specific polytopes were suggested [29, 47, 57]. Later on, improved general algorithms were designed that work whenever f is non-negative and P is down-closed3 and solvable [13, 24]. Designing algorithms that work in this general setting is highly important as many natural constraints fall into this framework. Moreover, the restriction of the algorithms to down-closed polytopes is unavoidable as Vondrák [57] proved that no algorithm can produce a vector x ∈ P obeying E[F (x)] ≥ c · f (OP T ) for any constant c > 0 when P is solvable but not down-closed. Up until recently, the best algorithm for this general setting was called Measured Continuous Greedy [24]. It guaranteed to produce a vector x ∈ P obeying E[F (x)] ≥ (1/e − o(1)) · f (OP T ) ≈ 0.367 · f (OP T ) [24]. The natural feel of the guarantee of Measured Continuous Greedy and the fact that it was not improved for a few years made some people suspect that it is optimal. Recently, an evidence against this conjecture was given by [7], which described an algorithm for the special case of a cardinality constraint with an improved approximation guarantee of 0.371. Even more recently, Ene and Nguyen [18] shuttered the conjecture completely. By extending the technique used by [7], they showed that one can get an approximation guarantee 0.372 for every down-closed and solvable polytope P . On the inapproximability side, Oveis Gharan and Vondrák [29] proved that no algorithm can achieve approximation better than 0.478 even when P is the matroid polytope of a partition matroid. Closing the gap between the best algorithm and inapproximability result for this fundamental problem remains an important open problem. 1 A A 3 A upper 2 set function f : 2N → R is monotone if f (A) ≤ f (B) for every A ⊆ B ⊆ N . polytope is solvable if one can optimize linear functions over it. polytope P ⊆ [0, 1]N is down-closed if y ∈ P implies that every vector x ∈ [0, 1]N which is coordinate-wise bounded by y must belong to P as well. 2 1.2 Our Contribution Our main contribution is an algorithm with an improved guarantee for maximizing the multilinear relaxation. Theorem 1.1. There exists a polynomial time algorithm that given a non-negative submodular function f : 2N → R≥0 and a solvable down-closed polytope P ⊆ [0, 1]N finds a vector x ∈ P obeying F (x) ≥ 0.385 · f (OP T ), where OP T = arg max{f (S) : 1S ∈ P } and F is the multilinear extension of f . Admittedly, the improvement in the guarantee obtained by our algorithm compared to the 0.372 guarantee of [18] is relatively small. However, the technique underlying our algorithm is very different, and, arguably, much cleaner, than the technique underlying the previous results improving over the natural guarantee of 1/e [7, 18]. Moreover, we believe our technique is more natural for the problem at hand, and thus, is likely to yield further improvements in the future. In the rest of this section we explain the intuition on which we base this belief. The results of [7, 18] are based on the observation that the guarantee of Measured Continuous Greedy improves when the algorithm manages to increase all the coordinates of its solution at a slow rate. Based on this observation, [7, 18] run an instance of Measured Continuous Greedy (or a discretized version of it), and force it to raise the coordinates slowly. If this extra restriction does not affect the behavior of the algorithm significantly, then it produces a solution with an improved guarantee. Otherwise, [7, 18] argue that the point in which the extra restriction affect the behavior of Measured Continuous Greedy reveals a vector x ∈ P which contains a significant fraction of OP T . Once x is available, one can use the technique of unconstrained submodular maximization, described by [6], that has higher approximation guarantee of 1/2 > 1/e, to extract from x a vector 0 ≤ y ≤ x of large value. The down-closeness of P guarantees that y belongs to P as well. Unfortunately, the use of the unconstrained submodular maximization technique in the above approach is very problematic for two reasons. First, this technique is based on ideas that are very different from the ideas used by the analysis of Measured Continuous Greedy. This makes the combination of the two quite involved. Second, on a more abstract level, the unconstrained submodular maximization technique is based on a symmetry which exists in the absence of a constraint since f¯(S) = f (N \ S) is non-negative and submodular whenever f has these properties. However, this symmetry breaks when a constraint is introduced, and thus, the unconstrained submodular maximization technique does not seem to be a good fit for a constrained problem. Our algorithm replaces the symmetry based unconstrained submodular maximization technique with a local search algorithm. More specifically, it first executes the local search algorithm. If the output of the local search algorithm is good, then our algorithm simply returns it. Otherwise, we observe that the poor value of the output of the local search algorithm guarantees that it is also far from OP T in some sense. Our algorithm then uses this far from OP T solution to guide an instance of Measured Continuous Greedy, and help it avoid bad decisions. As it turns out, the analysis of Measured Continuous Greedy and the local search algorithm use similar ideas and notions. Thus, the two algorithms combine quite cleanly, as can be observed from Section 3. 3 2 Preliminaries Our analysis uses another useful extension of submodular functions. Given a submodular function f : 2N → R, its Lovász extension is a function fˆ: [0, 1]N → R defined by fˆ(x) = Z 1 f (Tλ (x))dλ , 0 where Tλ (x) = {u ∈ N : xu < λ}. The Lovász extension has many important applications (see, e.g., [9, 52]), however, in this paper we only use it in the context of the following known result (which is an immediate corollary of the work of [51]). Lemma 2.1. Given the multilinear extension F and the Lovász extension fˆ of a submodular function f : 2N → R, it holds that F (x) ≥ fˆ(x) for every vector x ∈ [0, 1]N . We now define some additional notation that we use. Given a set S ⊆ N and an element u ∈ N , we denote by 1S and 1u the characteristic vectors of the sets S and {u}, respectively, and by S + u and S − u the sets S ∪ {u} and S \ {u}, respectively. Given two vectors x, y ∈ [0, 1]N , we denote by x ∨ y, x ∧ y and x ◦ y the coordinate-wise maximum, minimum and multiplication, respectively, of x and y.4 Finally, given a vector x ∈ [0, 1]N and an element u ∈ N , we denote by ∂u F (x) the derivative of F with respect to u at the point x. The following observation gives a simple formula for ∂u F (x). This observation holds because F is a multilinear function. Observation 2.2. Let F (x) be the multilinear extension of a submodular function f : 2N → R. Then, for every u ∈ N and x ∈ [0, 1]N , (1 − xu ) · ∂u F (x) = F (x ∨ 1u ) − F (x) . In the rest of the paper we assume, without loss of generality, that 1u ∈ P for every element u ∈ N and that n is larger than any given constant. The first assumption is justified by the observation that every element u violating this assumption can be safely removed from N since it cannot belong to OP T . The second assumption is justified by the observation that it is possible to find a set S obeying 1S ∈ P and f (S) = f (OP T ) in constant time when n is a constant. Another issue that needs to be kept in mind is the representation of submodular functions. We are interested in algorithms whose time complexity is polynomial in |N |. However, the representation of the submodular function f might be exponential in this size; thus, we cannot assume that the representation of f is given as part of the input for the algorithm. The standard way to bypass this difficulty is to assume that the algorithm has access to f through an oracle. We assume the standard value oracle that is used in most of the previous works on submodular maximization. This oracle returns, given any subset S ⊆ N , the value f (S). 3 Main Algorithm In this section we present the algorithm used to prove Theorem 1.1. This algorithm uses two components. The first component is a close variant of a fractional local search algorithm suggested by Chekuri et al. [13] which has the following properties. 4 More formally, for every element u ∈ N , (x ∨ y)u = max{xu , yu }, (x ∧ y)u = min{xu , yu } and (x ◦ y)u = xu · yu . 4 Lemma 3.1 (Follows from Chekuri et al. [13]). There exists a polynomial time algorithm which returns vector x ∈ P such that, with high probability, for every vector y ∈ P , 1 1 F (x) ≥ F (x ∧ y) + F (x ∨ y) − o(1) · f (OP T ) . 2 2 (1) Proof. Let M = max{f (u), f (N − u) : u ∈ N }, and let a be an arbitrary constant larger than 3. Then, Lemmata 3.7 and 3.8 of Chekuri et al. [13] imply that, with high probability, the fractional local search algorithm they suggest terminates in polynomial time and outputs a vector x ∈ P obeying, for every vector y ∈ P , 2F (x) ≥ F (x ∧ y) + F (x ∨ y) − 5M . na−2 Moreover, the output vector x is in P whenever the fractional local search algorithm terminates. Our assumption that 1u ∈ P for every element u ∈ N implies, by submodularity, that f (S) ≤ n · f (OP T ) for every set S ⊆ N . Since M is the maximum over values of f , we get also M ≤ n · f (OP T ). Using this observation, and plugging a = 4, we get that there exists an algorithm which, with high probability, terminates after T (n) operations (for some polynomial function T (n)) T) for every vector y ∈ P . and outputs a vector x ∈ P obeying 2F (x) ≥ F (x ∧ y) + F (x ∨ y) − 5·f (OP n Moreover, the output vector x belongs to P whenever the algorithm terminates. To complete the lemma, we consider a procedure that executes the above algorithm for T (n) operations, and return its output if it terminates within this number of operations. If the algorithm fails to terminate within this number of operations, which happens with a diminishing probability, then the procedure simply returns 1∅ (which always belongs to P since P is down-closed). One can observe that this procedure has all the properties guaranteed by the lemma. The second component of our algorithm is a new auxiliary algorithm which we present and analyze in Section 4. This auxiliary algorithm is the main technical contribution of this paper, and its guarantee is given by the following theorem. Theorem 3.2. There exists a polynomial time algorithm that given a vector z ∈ [0, 1]N and a value ts ∈ [0, 1] outputs a vector x ∈ P obeying E[F (x)] ≥ ets −1 · [(2 − ts − e−ts − o(1)) · f (OP T ) − (1 − e−ts ) · F (z ∧ 1OP T ) −ts − (2 − ts − 2e (2) ) · F (z ∨ 1OP T )] . Our main algorithm executes the algorithms suggested by Lemma 3.1 followed by the algorithm suggested by Theorem 3.2. Notice that the second of these algorithms has two parameters in addition to f and P : a parameter z which is set to be the output of the first algorithm, and a parameter ts which is set to be a constant to be determined later. After the two above algorithms terminate, our algorithm returns the output of the first algorithm with probability p, for a constant p to be determined later, and with the remaining probability it returns the output of the second algorithm.5 A formal description of our algorithm is given as Algorithm 1. Observe that Lemma 3.1 and Theorem 3.2 imply together that Algorithm 1 is a polynomial time algorithm which always outputs a vector in P . To prove Theorem 1.1, it remains to analyze the quality of the solution produced by Algorithm 1. 5 Clearly it is always better to return the better of the two solution instead of randomizing between them. However, doing so will require the algorithm to either have an oracle access to F or estimate the values of the solutions using sampling (the later can be done using standard techniques—see, e.g., [8]). For the sake of simplicity, we chose here the easier to analyze approach of randomizing between the two solutions. 5 Algorithm 1: Main Algorithm(f, P ) 1 2 3 Execute the algorithm suggested by Lemma 3.1, and let x1 ∈ P be its output. Execute the algorithm suggested by Theorem 3.2 with z = x1 , and let x2 be its output. return with probability p the solution x1 , and the solution x2 otherwise. Lemma 3.3. When its parameters are set to ts = 0.372 and p = 0.23, Algorithm 1 produces a solution whose expected value is at least 0.385 · f (OP T ). Proof. Let E be the event that x1 , the output of the algorithm suggested by Lemma 3.1, satisfies Inequality (1). Since E is a high probability event, it is enough to prove that, conditioned on E, Algorithm 1 produces a solution whose expected value is at least c · f (OP T ) for some constant c > 0.385. The rest of the proof of the lemma is devoted to proving the last claim. Throughout it, everything is implicitly conditioned on E. As we are conditioning on E, we can plug y = 1OP T and, respectively, y = x1 ∧ 1OP T into Inequality (1) to get 1 1 F (x1 ) ≥ F (x1 ∧ 1OP T ) + F (x1 ∨ 1OP T ) − o(1) · f (OP T ) (3) 2 2 and F (x1 ) ≥ F (x1 ∧ 1OP T ) − o(1) · f (OP T ) , (4) where the last inequality follows by noticing that x1 ∨ (x1 ∧ 1OP T ) = x1 . Next, let E[F (x2 ) | x1 ] denote the expected value of F (x2 ) conditioned on the given value of x1 . Inequality (2) guarantees that E[F (x2 ) | x1 ] ≥ ets −1 · [(2 − ts − e−ts − o(1)) · f (OP T ) − (1 − e−ts ) · F (x1 ∧ 1OP T ) −ts − (2 − ts − 2e (5) ) · F (x1 ∨ 1OP T )] . Recall that Algorithm 1 returns x1 with probability p, and x2 otherwise. Hence, the expected value of its output is E[p · F (x1 ) + (1 − p) · E[F (x2 ) | x1 ]] , (6) where the expectation is over x1 . Optimizing the constants. We would like to derive from Inequalities (3), (4) and (5) the best lower bound we can get on (6). To this end, let p1 and p2 be two non-negative numbers such that p1 + p2 = p, and let p3 = 1 − p. Using the above inequalities and this notation, (6) can now be lower bounded by   1 1 p1 · E[F (x1 ∧ 1OP T )] + E[F (x1 ∨ 1OP T )] − o(1) · f (OP T ) 2 2 + p2 · [E[F (x1 ∧ 1OP T )] − o(1) · f (OP T )] + p3 · ets −1 · [(2 − ts − e−ts − o(1)) · f (OP T ) − (1 − e−ts ) · E[F (x1 ∧ 1OP T )] − (2 − ts − 2e−ts ) · E[F (x1 ∨ 1OP T )]] , which can be rewritten as p  + p2 − p3 · ets −1 (1 − e−ts ) · E[F (x1 ∧ 1OP T )]   p2 1 − p3 · ets −1 (2 − ts − 2e−ts ) · E[F (x1 ∨ 1OP T )] + 2 + p3 · ets −1 (2 − ts − e−ts ) · f (OP T ) − o(1) · f (OP T ) . 1 6 To get the most out of this lower bound we need to maximize the coefficient of f (OP T ) while keeping the coefficients of E[F (x1 ∧ 1OP T )] and E[F (x1 ∨ 1OP T )] non-negative (so that they can be ignored due to non-negativity of f ). This objective is formalized by the following non-convex program. max p3 · ets −1 (2 − ts − e−ts ) s.t. p1 /2 + p2 − p3 · ets −1 (1 − e−ts ) p1 /2 − p3 · ets −1 (2 − ts − 2e−ts ) p1 + p2 + p3 p 1 , p 2 , p 3 , ts ≥0 ≥0 =1 ≥0 Solving the program, we get that the best solution is approximately p1 = 0.205, p2 = 0.025, p3 = 0.770 and ts = 0.372, and the objective function value corresponding to this solution is at least 0.3856. Hence, we have managed to lower bound (6) (and thus, also the expected value of the output of Algorithm 1) by 0.3856 · f (OP T ) for p = 0.23 and ts = 0.372, which completes the proof of the lemma. 4 Aided Measured Continuous Greedy In this section we present the algorithm used to prove Theorem 3.2. Proving the above theorem directly is made more involved by the fact that the vector z might be fractional. Instead, we prove the following simplified version of Theorem 3.2 for integral values, and show that the simplified version implies the original one. Theorem 4.1. There exists a polynomial time algorithm that given a set Z ⊆ N and a value ts ∈ [0, 1] outputs a vector x ∈ P obeying E[F (x)] ≥ ets −1 · [(2 − ts − e−ts − o(1)) · f (OP T ) − (1 − e−ts ) · f (Z ∩ OP T ) − (2 − ts − 2e−ts ) · f (Z ∪ OP T )] . Next is the promised proof that Theorem 4.1 implies Theorem 3.2. Proof of Theorem 3.2 given Theorem 4.1. Consider an algorithm ALG that given the z and ts arguments specified by Theorem 3.2 executes the algorithm guaranteed by Theorem 4.1 with the same value ts and with a random set Z distributed like R(z). The output of ALG is then the output produced by the algorithm guaranteed by Theorem 4.1. Let us denote this output by x. Theorem 4.1 guarantees that, for every given Z, E[F (x) | Z] ≥ ets −1 · [(2 − ts − e−ts − o(1)) · f (OP T ) − (1 − e−ts ) · f (Z ∩ OP T ) − (2 − ts − 2e−ts ) · f (Z ∪ OP T )] . To complete the proof we take the expectation over Z over the two sides of the last inequality and observe that E[f (Z ∩ OP T )] = E[f (R(z) ∩ OP T )] = E[f (R(z ∧ 1OP T ))] = F (z ∧ 1OP T ) and E[f (Z ∪ OP T )] = E[f (R(z) ∪ OP T )] = E[f (R(z ∨ 1OP T ))] = F (z ∨ 1OP T ) . 7 In the rest of this section we give a non-formal proof of Theorem 4.1. This proof explains the main ideas necessary for proving the theorem, but uses some non-formal simplifications such as allowing a direct oracle access to the multilinear extension F and giving the algorithm in the form of a continuous time algorithm (which cannot be implemented on a discrete computer). There are known techniques for getting rid of these simplifications (see, e.g., [8]), and a formal proof of Theorem 4.1 based on these techniques is given in Appendix A. The algorithm we use for the non-formal proof of Theorem 4.1 is given as Algorithm 2. This algorithm starts with the empty solution y(0) = 1∅ at time 0, and grows this solution over time until it reaches the final solution y(1) at time 1. The way the solution grows varies over time. During the time range [ts , 1) the solution grows like in the Measured Continuous Greedy algorithm of [24]. On the other hand, during the earlier time range of [0, ts ) the algorithm pretends that the elements of Z do not exist (by giving them negative marginal profits), and grows the solution in the way Measured Continuous Greedy would have grown it if it was given the ground set N \ Z. The value ts is the time in which the algorithm switches between the two ways it uses to grow its solution, thus, the s in the notation ts stands for “switch”. Algorithm 2: Aided Measured Continuous Greedy (non-formal)(f, P, Z, ts ) 1 2 3 4 5 6 Let y(0) ← 1∅ . foreach t ∈ [0, 1) do For each u ∈ N let wu (t) ← F (y(t) ∨ 1u ) − F (y(t)). P P  arg maxx∈P { u∈N \Z wu (t) · xu (t) − u∈Z xu (t)} if t ∈ [0, ts ) , P Let x(t) ← arg maxx∈P if t ∈ [ts , 1) . u∈N wu (t) · xu (t) Increase y(t) at a rate of dy(t) dt = (1N − y(t)) ◦ x(t). return y(1). We first note that algorithm outputs a vector in P . Observation 4.2. y(1) ∈ P . Proof. Observe that x(t) ∈ P at eachR time t, which implies that (1N − y(t)) · x(t) is also in P since 1 P is down-closed. Therefore, y(1) = 0 (1N − y(t)) · x(t)dt is a convex combination of vectors in P , and thus, belongs to P . The following lemma lower bounds the increase in F (y(t)) as a function of t. Lemma 4.3. For every t ∈ [0, 1), ( F (y(t) ∨ 1OP T \Z ) − F (y(t)) dF (y(t)) ≥ dt F (y(t) ∨ 1OP T ) − F (y(t)) if t ∈ [0, ts ) , if t ∈ [ts , 1) . Proof. By the chain rule, ! ! X X dyu (t) ∂F (y) ∂F (y) dF (y(t)) = (1 − yu (t)) · xu (t) · = · dt dt ∂yu y=y(t) ∂yu y=y(t) u∈N u∈N X X = (xu (t) · [F (y(t) ∨ 1u ) − F (y(t))]) = xu (t) · wu (t) = x(t) · w(t) . u∈N (7) u∈N Consider first the case this time period Algorithm 2 chooses x(t) as the P t ∈ [0, ts ). During P vector in P maximizing u∈N \Z wu (t) · xu (t) − u∈Z xu (t). Since P is down-closed x(t) = 1OP T \Z 8 is in P and has value 1OP T \Z · w(t) and thus, we have x(t) · w(t) ≥ 1OP T \Z · w(t). Plugging this observation into Equality (7) yields dF (y(t)) = x(t) · w(t) ≥ 1OP T \Z · w(t) = dt ≥ F (y(t) ∨ 1OP T \Z ) − F (y(t)) , X [F (y(t) ∨ 1u ) − F (y(t))] u∈OP T \Z where the last inequality holds by the submodularity of f . Similarity, when t ∈ [ts , 1) Algorithm 2 chooses x(t) as the vector in P maximizing x(t) · w(t). Since 1OP T ∈ P , we get this time x(t) · w(t) ≥ 1OP T · w(t). Plugging this observation into Equality (7) yields X dF (y(t)) = x(t) · w(t) ≥ 1OP T · w(t) = [F (y(t) ∨ 1u ) − F (y(t))] dt u∈OP T ≥ F (y(t) ∨ 1OP T ) − F (y(t)) , where the last inequality holds again by the submodularity of f . Lemma 4.4. For every time t ∈ [0, 1) and set A ⊆ N it holds that   F (y(t) ∨ 1A ) ≥ e− max{0,t−ts } − e−t max {0, f (A) − f (A ∪ Z)} + e−t · f (A) . Proof. First, we note that for every time t ∈ [0, 1] and element u ∈ N , ( 1 − e−t if u 6∈ Z , yu (t) ≤ − max{0,t−t s} 1−e if u ∈ Z . (8) This follows for the following reason. Since x(t) is always in P ⊆ [0, 1]N , yu (t) obeys the differential inequality dy(t) = (1 − yu (t)) · x(t) ≤ (1 − yu (t)) . dt Using the initial condition yu (0) = 0, the solution for this differential inequality is yu (t) ≤ 1 − e−t . To get the tighter bound for u ∈ Z, we note that at every time t ∈ [0, ts ) Algorithm 2 chooses as x(t) a vector maximizing a linear function in P which assigns a negative weight to elements of Z. Since P is down-closed this maximum must have xu (t) = 0 for every element u ∈ Z. This means that yu (t) = 0 whenever u ∈ Z and t ∈ [0, ts ]. Moreover, plugging the improved initial condition yu (ts ) = 0 into the above differential inequality yields the promised tighter bound also for the range (ts , 1]. Next, let fˆ be the Lovász extension of f . Then, by Lemma 2.1, Z 1 ˆ f (Tλ (y(t) ∨ 1A ))dλ F (y(t) ∨ 1A ) ≥ f (y(t) ∨ 1A ) = 0 ≥ Z 1−e−t 1−e− max{0,t−ts } Z 1−e−t f (Tλ (y(t) ∨ 1A ))dλ + Z 1 1−e−t f (Tλ (y(t) ∨ 1A ))dλ f (Tλ (y(t) ∨ 1A ))dλ + e−t · f (A)   ≥ e− max{0,t−ts } − e−t max {0, f (A) − f (A ∪ Z)} + e−t · f (A) . = (9) (10) 1−e− max{0,t−ts } 9 (11) Inequality (9) follows by the non-negativity of f . Equality (10) follows since, for λ ∈ [1 − e−t , 1), Inequality (8) guarantees that yu (t) ≤ λ for every u ∈ N , and thus, Tλ (y(t) ∨ 1A ) = A. Finally Inequality (11) follows since, for λ ∈ [1 − e− max{0,t−ts } , 1 − e−t ), Inequality (8) guarantees that yu (t) ≤ λ for every u ∈ Z, and thus, Tλ (y(t) ∨ 1A ) = B(λ) ∪ A for some B(λ) ⊆ N \ Z. By the non-negativity of f , f (B(λ) ∪ A) ≥ 0. Also, by the submodularity and non-negativity of f , for every such set B(λ) f (B(λ) ∪ A) ≥ f (A) + f (B(λ) ∪ Z ∪ A) − f (Z ∪ A) ≥ f (A) − f (Z ∪ A) . Plugging the results of Lemma 4.4 into the lower bound given by Lemma 4.3 on the improvement in F (y(t)) as a function of t yields immediately the useful lower bound given by the next corollary.6 Corollary 4.5. For every t ∈ [0, 1), ( f (OP T \ Z) − (1 − e−t ) · f (Z ∪ OP T ) − F (y(t)) dF (y(t)) ≥ dt ets −t · f (OP T ) − (ets −t − e−t ) · f (Z ∪ OP T ) − F (y(t)) if t ∈ [0, ts ) , if t ∈ [ts , 1) . Using the last corollary we can complete the proof of Theorem 4.1. Proof of Theorem 4.1. We have already seen that y(1)—the output of Algorithm 2—belongs to P . It remains to show that F (y(1)) ≥ ets −1 · [(2 − ts − e−ts ) · f (OP T ) − (1 − e−ts ) · f (Z ∩ OP T ) − (2 − ts − 2e−ts ) · f (Z ∪ OP T )] . Corollary 4.5 describes a differential inequality for F (y(t)). Given the boundary condition F (y(0)) ≥ 0, the solution for this differential inequality within the range t ∈ [0, ts ] is F (y(t)) ≥ (1 − e−t ) · f (OP T \ Z) − (1 − e−t − te−t ) · f (Z ∪ OP T ) . Plugging t = ts into the last inequality, we get F (y(ts )) ≥ (1 − e−ts ) · f (OP T \ Z) − (1 − e−ts − ts e−ts ) · f (Z ∪ OP T ) . Let v = (1 − e−ts ) · f (OP T \ Z) − (1 − e−ts − ts e−ts ) · f (Z ∪ OP T ) be the right hand side of the last inequality. Next, we solve again the differential inequality given by Corollary 4.5 for the range t ∈ [ts , 1] with the boundary condition F (y(ts )) ≥ v. The resulting solution is    F (y(t)) ≥ e−t (t − ts ) ets · f (OP T ) − (ets − 1) · f (Z ∪ OP T ) + vets Plugging t = 1 and the value of v we get    F (y(1)) ≥ e−1 (1 − ts ) ets · f (OP T ) − (ets − 1) · f (Z ∪ OP T ) + vets  1 − ts ts e · f (OP T ) − (ets − 1) · f (Z ∪ OP T ) (12) ≥ e + ets −1 · {(1 − e−ts ) · [f (OP T ) − f (OP T ∩ Z)] − (1 − e−ts − ts e−ts ) · f (Z ∪ OP T )} = ets −1 · [(2 − ts − e−ts ) · f (OP T ) − (1 − e−ts ) · f (Z ∩ OP T ) − (2 − ts − 2e−ts ) · f (Z ∪ OP T )] , where Inequality (12) follows since, by the submodularity and non-negativity of f , f (OP T \ Z) ≥ f (OP T ) − f (OP T ∩ Z) + f (∅) ≥ f (OP T ) − f (OP T ∩ Z) . 6 Note that Corollary 4.5 follows from a weaker version of Lemma 4.4 which only guarantees F (y(t) ∨ 1A ) ≥ (e − e−t ) · [f (A) − f (A ∪ Z)] + e−t · f (A). We proved the stronger version of the lemma above because it is useful in the formal proof of Theorem 4.1 given in Appendix A. − max{0,t−ts } 10 References [1] A. A. Ageev and M. I. Sviridenko. An 0.828 approximation algorithm for the uncapacitated facility location problem. Discrete Appl. Math., 93:149–156, July 1999. [2] Noga Alon and Joel H. Spencer. The Probabilistic Method. Wiley Interscience, second edition, 2000. [3] Per Austrin, Siavosh Benabbas, and Konstantinos Georgiou. Better balance by being biased: A 0.8776-approximation for max bisection. In SODA, pages 277–294, 2013. [4] Francis Bach. Learning with submodular functions: A convex optimization perspective. Foundations and Trends in Machine Learning, 6(2-3):145–373, 2013. [5] Y. Y. Boykov and M. P. Jolly. Interactive graph cuts for optimal boundary & region segmentation of objects in N-D images. In ICCV, volume 1, pages 105–112, 2001. [6] Niv Buchbinder, Moran Feldman, Joseph (Seffi) Naor, and Roy Schwartz. A tight linear time (1/2)-approximation for unconstrained submodular maximization. In FOCS, pages 649–658, 2012. [7] Niv Buchbinder, Moran Feldman, Joseph (Seffi) Naor, and Roy Schwartz. Submodular maximization with cardinality constraints. In SODA, pages 1433–1452, 2014. [8] Gruia Călinescu, Chandra Chekuri, Martin Pál, and Jan Vondrák. Maximizing a monotone submodular function subject to a matroid constraint. SIAM J. Comput., 40(6):1740–1766, 2011. [9] Chandra Chekuri and Alina Ene. Approximation algorithms for submodular multiway partition. In FOCS, pages 807–816, 2011. [10] Chandra Chekuri and Sanjeev Khanna. A polynomial time approximation scheme for the multiple knapsack problem. SIAM J. Comput., 35(3):713–728, September 2005. [11] Chandra Chekuri, Jan Vondrák, and Rico Zenklusen. Dependent randomized rounding via exchange properties of combinatorial structures. In FOCS, pages 575–584, 2010. [12] Chandra Chekuri, Jan Vondrák, and Rico Zenklusen. Submodular function maximization via the multilinear relaxation and contention resolution schemes. In STOC, pages 783–792, 2011. [13] Chandra Chekuri, Jan Vondrák, and Rico Zenklusen. Submodular function maximization via the multilinear relaxation and contention resolution schemes. SIAM J. Comput., 43(6):1831– 1879, 2014. [14] Reuven Cohen, Liran Katzir, and Danny Raz. An efficient approximation for the generalized assignment problem. Information Processing Letters, 100(4):162–166, 2006. [15] M. Conforti and G. Cornuèjols. Submodular set functions, matroids and the greedy algorithm. tight worstcase bounds and some generalizations of the radoedmonds theorem. Disc. Appl. Math., 7(3):251–274, 1984. [16] G. Cornuejols, M. L. Fisher, and G. L. Nemhauser. Location of bank accounts to optimize float: an analytic study of exact and approximate algorithms. Management Sciences, 23:789–810, 1977. 11 [17] G. Cornuejols, M. L. Fisher, and G. L. Nemhauser. On the uncapacitated location problem. Annals of Discrete Mathematics, 1:163–177, 1977. [18] Alina Ene and Huy L. Nguyen. Constrained submodular maximization: Beyond 1/e. In FOCS, 2016. [19] Uriel Feige. A threshold of ln n for approximating set cover. J. ACM, 45(4):634–652, 1998. [20] Uriel Feige and Michel X. Goemans. Aproximating the value of two prover proof systems, with applications to max 2sat and max dicut. In ISTCS, pages 182–189, 1995. [21] Uriel Feige, Vahab S. Mirrokni, and Jan Vondrák. Maximizing non-monotone submodular functions. SIAM Journal on Computing, 40(4):1133–1153, 2011. [22] Uriel Feige and Jan Vondrák. Approximation algorithms for allocation problems: Improving the factor of 1 − 1/e. In FOCS, pages 667–676, 2006. [23] Moran Feldman. Maximization Problems with Submodular Objective Functions. PhD thesis, Technion – Israel Institute of Technology, June 2013. [24] Moran Feldman, Joseph Naor, and Roy Schwartz. A unified continuous greedy algorithm for submodular maximization. In FOCS, pages 570–579, 2011. [25] Moran Feldman, Joseph (Seffi) Naor, Roy Schwartz, and Justin Ward. Improved approximations for k-exchange systems. In ESA, pages 784–798, 2011. [26] M. L. Fisher, G. L. Nemhauser, and L. A. Wolsey. An analysis of approximations for maximizing submodular set functions – ii. In Polyhedral Combinatorics, volume 8 of Mathematical Programming Studies, pages 73–87. Springer Berlin Heidelberg, 1978. [27] Lisa Fleischer, Michel X. Goemans, Vahab S. Mirrokni, and Maxim Sviridenko. Tight approximation algorithms for maximum general assignment problems. In SODA, pages 611–620, 2006. [28] Alan M. Frieze and Mark Jerrum. Improved approximation algorithms for max k-cut and max bisection. In IPCO, pages 1–13, 1995. [29] Shayan Oveis Gharan and Jan Vondrák. Submodular maximization by simulated annealing. In SODA, pages 1098–1117, 2011. [30] Michel X. Goemans and David P. Williamson. Improved approximation algorithms for maximum cut and satisfiability problems using semidefinite programming. Journal of the ACM, 42(6):1115–1145, 1995. [31] Eran Halperin and Uri Zwick. Combinatorial approximation algorithms for the maximum directed cut problem. In SODA, pages 1–7, 2001. [32] Jason Hartline, Vahab Mirrokni, and Mukund Sundararajan. Optimal marketing strategies over social networks. In WWW, pages 189–198, 2008. [33] Johan Hȧstad. Some optimal inapproximability results. J. ACM, 48:798–859, July 2001. [34] D. Hausmann and B. Korte. K-greedy algorithms for independence systems. Oper. Res. Ser. A-B, 22(1):219–228, 1978. 12 [35] D. Hausmann, B. Korte, and T. Jenkyns. Worst case analysis of greedy type algorithms for independence systems. Math. Prog. Study, 12:120–131, 1980. [36] S. Jegelka and J. Bilmes. Submodularity beyond submodular energies: Coupling edges in graph cuts. 2012 IEEE Conference on Computer Vision and Pattern Recognition, 0:1897–1904, 2011. [37] T. Jenkyns. The efficacy of the greedy algorithm. Cong. Num., 17:341–350, 1976. [38] Richard M. Karp. Reducibility among combinatorial problems. In R. E. Miller and J. W. Thatcher, editors, Complexity of Computer Computations, pages 85–103. Plenum Press, 1972. [39] David Kempe, Jon Kleinberg, and Éva Tardos. Maximizing the spread of influence through a social network. In SIGKDD, pages 137–146, 2003. [40] Subhash Khot, Guy Kindler, Elchanan Mossel, and Ryan O’Donnell. Optimal inapproximability results for max-cut and other 2-variable csps? SIAM J. Comput., 37:319–357, April 2007. [41] S. Khuller, A. Moss, and J. Naor. The budgeted maximum coverage problem. Information Processing Letters, 70(1):39–45, 1999. [42] B. Korte and D. Hausmann. An analysis of the greedy heuristic for independence systems. Annals of Discrete Math., 2:65–74, 1978. [43] Andreas Krause, AjitSingh, and Carlos Guestrin. Near-optimal sensor placements in gaussian processes: Theory, efficient algorithms and empirical studies. J. Mach. Learn. Res., 9:235–284, January 2008. [44] Andreas Krause and Carlos Guestrin. Near-optimal nonmyopic value of information in graphical models. In UAI, page 5, 2005. [45] Andreas Krause, Jure Leskovec, Carlos Guestrin, Jeanne VanBriesen, and Christos Faloutsos. Efficient sensor placement optimization for securing large water distribution networks. Journal of Water Resources Planning and Management, 134(6):516–526, November 2008. [46] Ariel Kulik, Hadas Shachnai, and Tami Tamir. Approximations for monotone and nonmonotone submodular maximization with knapsack constraints. Math. Oper. Res., 38(4):729–739, 2013. [47] Jon Lee, Vahab S. Mirrokni, Viswanath Nagarajan, and Maxim Sviridenko. Maximizing nonmonotone submodular functions under matroid or knapsack constraints. SIAM Journal on Discrete Mathematics, 23(4):2053–2078, 2010. [48] Jon Lee, Maxim Sviridenko, and Jan Vondrák. Submodular maximization over multiple matroids via generalized exchange properties. In APPROX, pages 244–257, 2009. [49] Hui Lin and Jeff Bilmes. Multi-document summarization via budgeted maximization of submodular functions. In North American chapter of the Association for Computational Linguistics/Human Language Technology Conference (NAACL/HLT-2010), Los Angeles, CA, June 2010. [50] Hui Lin and Jeff Bilmes. A class of submodular functions for document summarization. In HLT, pages 510–520, 2011. 13 [51] László Lovász. Submodular functions and convexity. In A. Bachem, M. Grötschel, and B. Korte, editors, Mathematical Programming: the State of the Art, pages 235–257. Springer, 1983. [52] L. Lovász M. Grötschel and A. Schrijver. The ellipsoid method and its consequences in combinatorial optimization. Combinatoria, 1(2):169–197, 1981. [53] G. L. Nemhauser and L. A. Wolsey. Best algorithms for approximating the maximum of a submodular set function. Mathematics of Operations Research, 3(3):177–188, 1978. [54] G. L. Nemhauser, L. A. Wolsey, and M. L. Fisher. An analysis of approximations for maximizing submodular set functionsi. Mathematical Programming, 14:265–294, 1978. [55] Maxim Sviridenko. A note on maximizing a submodular set function subject to knapsack constraint. Operations Research Letters, 32:41–43, 2004. [56] Luca Trevisan, Gregory B. Sorkin, Madhu Sudan, and David P. Williamson. Gadgets, approximation, and linear programming. SIAM J. Comput., 29:2074–2097, April 2000. [57] Jan Vondrák. Symmetry and approximability of submodular maximization problems. SIAM J. Comput., 42(1):265–304, 2013. A A Formal Proof of Theorem 4.1 In this section we give a formal proof of Theorem 4.1. This proof is based on the same ideas used in the non-formal proof of this theorem in Section 4, but employs also additional known techniques in order to get rid of the issues that make the proof from Section 4 non-formal. The algorithm we use to prove Theorem 4.1 is given as Algorithm 3. This algorithm is a discrete variant of Algorithm 2. While reading the algorithm, it is important to observe that the choice of the values δ̄1 and δ̄2 guarantees that the variable t takes each one of the values ts and 1 at some point, and thus, the vectors y(ts ) and y(1) are well defined. Algorithm 3: Aided Measured Continuous Greedy(f, P, Z, ts ) 1 2 3 4 5 6 7 8 9 10 // Initialization Let δ̄1 ← ts · n−4 and δ̄2 ← (1 − ts ) · n−4 . Let t ← 0 and y(t) ← 1∅ . // Growing y(t) while t < 1 do foreach u ∈ N do Let wu (t) be an estimate of E[f (u | R(y(t))] obtained by averaging the values of f (u | R(y(t)) for r = ⌈48n6 ln(2n)⌉ independent samples of R(y(t)). P P  arg maxx∈P { u∈N \Z wu (t) · xu (t) − u∈Z xu (t)} if t ∈ [0, ts ) , P Let x(t) ← if t ∈ [ts , 1) . arg maxx∈P u∈N wu (t) · xu (t) Let δt be δ̄1 when t < ts and δ̄2 when t ≥ ts . Let y(t + δt ) ← y(t) + δt (1N − y(t)) ◦ x(t). Update t ← t + δt . return y(1). 14 We begin the analysis of Algorithm 3 by showing that y(t) remains within the cube [0, 1]N throughout the execution of the algorithm. Without this observation, the algorithm is not welldefined. Observation A.1. For every value of t, y(t) ∈ [0, 1]N . Proof. We prove the observation by induction on t. Clearly the observation holds for y(0) = 1∅ . Assume the observation holds for some time t, then, for every u ∈ N , yu (t + δt ) = yu (t) + δt (1 − yu (t)) · xu (t) ≥ 0 , where the inequality holds since the induction hypothesis implies 1 − yu (t) ∈ [0, 1]. A similar argument also implies yu (t + δt ) = yu (t) + δt (1 − yu (t)) · xu (t) ≤ yu (t) + (1 − yu (t)) = 1 . Using the last observation it is now possible to prove the following counterpart of Observation 4.2. Corollary A.2. Algorithm 3 always outputs a vector in P . Proof. Let T be the set of values t takes P P during the execution of Algorithm 3. We observe that δ = 1, which implies that t∈T \{1} t t∈T \{1} δt · x(t) is a convex combination of the vectors {x(t) : t ∈ T \ {1}}. P As all these vectors belong to P , and P is convex, any convex combination of them, including t∈T \{1} δt · x(t), must be in P . Next, we rewrite the output of Algorithm 3 as X X δt · x(t) . δt (1N − y(t)) ◦ x(t) ≤ y(1) = t∈T \{1} t∈T \{1} By the above discussion the rightmost hand side of this inequality is a vector in P , which implies that y(1) ∈ P since P is down-closed. The next step towards showing that Algorithm 3 proves Theorem 4.1 is analyzing its approximation ratio. We start this analysis by showing that with high probability all the estimations made by the algorithm are quite accurate. Let A be the event that |wu (t)−E[f (u | R(y(t)))]| ≤ n−2 ·f (OP T ) for every u ∈ N and time t. Lemma A.3 (The symmetric version of Theorem A.1.16 in [2]). Let Xi , 1 ≤ i ≤ k, be mutually independent with all E[Xi ] = 0 and all |Xi | ≤ 1. Set S = X1 + · · · + Xk . Then, Pr[|S| > a] ≤ 2 2e−a /2k . Corollary A.4. Pr[A] ≥ 1 − n−1 . Proof. Consider the calculation of wu (t) for a given u ∈ N and time t. This calculation is done by averaging the value of f (u | R(y(t))) for r independent samples of R(y(t)). Let Yi denote the value (u|R(y(t)))] . Then, by definition, of f (u | R(y(t))) obtained for the i-th sample, and let Xi = Yi −E[f 2n·f (OP T ) wu (t) = Pr i=1 Yi r = [2n · f (OP T )] · Pr i=1 Xi r + E[f (u | R(y(t)))] . Since Yi is distributed like f (u | R(y(t))), the definition of Xi guarantees that E[Xi ] = 0 for every 1 ≤ i ≤ r. Additionally, |Xi | ≤ 1 for every such i since the absolute values of both Yi and 15 E[f (u | R(y(t)))] are upper bounded by maxS⊆N f (S) ≤ n · f (OP T ) (the last inequality follows from our assumption that 1u ∈ P for every element u ∈ N ). Thus, by Lemma A.3, # " r X r −3 2 Xi > 3 ≤ 2e−[rn /2] /2r Pr[|wu (t) − E[f (u | R(y(t)))]| > n−2 · f (OP T )] = Pr 2n i=1  6 1 1 −rn−6 /8 −6 ln(2n) = 2e ≤ 2e =2· ≤ 6 . 2n 2n Observe that Algorithm 3 calculates wu (t) for every combination of element u ∈ N and time t < 1. Since there are n elements in N and 2n4 times smaller than 1, the union bound implies that the probability that for at least one such value wu (t) we have |wu (t) − E[f (u | R(y(t)))]| > n−2 · f (OP T ) is upper bounded by  1 1 · n · 2n4 = , 6 2n n which completes the proof of the corollary. Our next step is to give a lower bound on the increase in F (y(t)) as a function of t given A. This lower bound is given by Corollary A.7, which follows from the next two lemmata. The statement and proof of the corollary and the next lemma is easier with the following definition. Let OP Tt′ denote the set OP T \ Z when t < ts , and OP T otherwise. P Lemma A.5. Given A, for every time t < 1, u∈N (1 − yu (t)) · xu (t) · ∂u F (y(t)) ≥ F (y(t) ∨ −1 1OP Tt′ ) − F (y(t)) − O(n ) · f (OP T ). Proof. Let us calculate the weight of OP Tt′ according to the weight function w(t). X X wu (t) ≥ [E[f (u | R(y(t)))] − n−2 · f (OP T )] w(t) · 1OP Tt′ = u∈OP Tt′  ≥ E X u∈OP Tt′ u∈OP Tt′  f (R(y(t)) + u) − f (R(y(t))) − n−1 · f (OP T )  ≥ E f (R(y(t)) ∪ OP Tt′ ) − f (R(y(t))) − n−1 · f (OP T )  = F (y(t) ∨ 1OP T ′t ) − F (y(t)) − n−1 · f (OP T ) , where the first inequality follows from the definition of A, and the last follows from the submodularity of f . Recall that x(t) is the vector in P maximizing some objective function (which depends on t). For t < ts , the objective function maximized by x(t) assigns the value w(t)·1OP T \Z = w(t)·1OP Tt′ to the vector 1OP Tt′ ∈ P . Similarly, for t ≥ ts , the objective function maximized by x(t) assigns the value w(t) · 1OP T = w(t) · 1OP Tt′ to the vector 1OP Tt′ ∈ P . Thus, the definition of x(t) guarantees that in both cases we have w(t) · x(t) ≥ w(t) · 1OP Tt′ ≥ F (y(t) ∨ 1OP Tt′ ) − F (y(t)) − n−1 · f (OP T ) . 16 Hence, X (1 − yu (t)) · xu (t)·∂u F (y(t)) = u∈N X xu (t) · [F (y(t) ∨ 1u ) − F (y(t))] u∈N X = xu (t) · E[f (u | R(y(t)))] u∈N X ≥ xu (t) · [wu (t) − n−2 · f (OP T )] = x(t) · w(t) − n−1 · f (OP T ) u∈N ≥ F (y(t) ∨ 1OP Tt′ ) − F (y(t)) − 2n−1 · f (OP T ) , where the first inequality holds by the definition of A and the second equality holds since F (y(t) ∨ 1u ) − F (y(t)) = E[f (R(y(t)) + u)] − E[f (R(y(t)))] = E[f (u | R(y(t)))] . Lemma A.6 (A rephrased version of Lemma 2.3.7 in [23]). Consider two vectors x, x′ ∈ [0, 1]N P such that |xu − x′u | ≤ δ for every u ∈ N . Then, F (x′ ) − F (x) ≥ u∈N (x′u − xu ) · ∂u F (x) − O(n3 δ2 ) · maxu∈N f ({u}). Corollary A.7. Given A, for every time t < 1, F (y(t + δt )) − F (y(t)) ≥ δt [F (y(t) ∨ 1OP Tt′ ) − F (y(t))] − O(n−1 δt ) · f (OP T ). Proof. Observe that for every u ∈ N , |yu (t + δt ) − yu (t)| = |δt (1 − yu (t))xu (t)| ≤ δt . Hence, by Lemma A.6, X F (y(t + δt )) − F (y(t)) ≥ [yu (t + δt )) − yu (t)] · ∂u F (y(t)) − O(n3 δt2 ) · max f ({u}) u∈N u∈N = X δt (1 − yu (t)) · xu (t) · ∂u F (y(t)) − O(n3 δt2 ) · max f ({u}) . u∈N u∈N (13) Consider the rightmost hand side of the last inequality. By Lemma A.5, the first term on this side can be bounded by X δt (1 − yu (t)) · xu (t) · ∂u F (y(t)) ≥ δt · [F (y(t) ∨ 1OP Tt′ ) − F (y(t)) − O(n−1 ) · f (OP T )] u∈N = δt · [F (y(t) ∨ 1OP Tt′ ) − F (y(t))] − O(n−1 δt ) · f (OP T ) . On the other hand, the second term of (13) can be bounded by O(n3 δt2 ) · max f ({u}) = O(n−1 δt ) · f (OP T ) u∈N since δt ≤ n−4 by definition and maxu∈N f ({u}) ≤ f (OP T ) by our assumption that 1u ∈ P for every u ∈ N . The lower bound given by the last corollary is in terms of F (y(t) ∨ 1OP Tt′ ). To make this lower bound useful, we need to lower bound the term F (y(t) ∨ 1OP Tt′ ). This is done by the following two lemma which corresponds to Lemma 4.4. Lemma A.8. [corresponds to Lemma 4.4] For every time t < 1 and set A ⊆ N it holds that   F (y(t) ∨ 1A ) ≥ e− max{0,t−ts } − e−t − O(n−4 ) · max {0, f (A) − f (A ∪ Z)} + (e−t − O(n−4 )) · f (A) . 17 The proof of this lemma goes along the same lines as the proof of its corresponding lemma in Section 4, except that the bounds on the coordinates of y(t) used by the proof from Section 4 are replaced with the (slightly weaker) bounds given by the following lemma. Lemma A.9. For every time t and element u ∈ N , ( 1 − e−t + O(n−4 ) yu (t) ≤ 1 − e− max{0,t−ts } + O(n−4 ) if u 6∈ Z , if u ∈ Z . Proof. Let ε = n−4 , and observe that δt ≤ ε for every time t. Our first objective is to prove by induction on t that, if yu (τ ) = 0 for some time τ ∈ [0, 1], then yu (t) ≤ 1 − (1 − ε)(t−τ )/ε for every time t ∈ [τ, 1]. For t = τ the claim holds because yu (τ ) = 0 = 1 − (1 − ε)(τ −τ )/ε . Next, assume the claim holds for some t, and let us prove it for t + δt . yu (t + δt ) = yu (t) + δt (1 − yu (t)) · xu (t) ≤ yu (t) + δt (1 − yu (t)) = yu (t)(1 − δt ) + δt ≤ (1 − (1 − ε)(t−τ )/ε )(1 − δt ) + δt = 1 − (1 − δt )(1 − ε)(t−τ )/ε ≤ 1 − (1 − ε)δt /ε (1 − ε)(t−τ )/ε = 1 − (1 − ε)(t+δt −τ )/ε , where the last inequality holds since (1 − x)1/x is a decreasing function for x ∈ (0, 1]. We complete the proof for the case u 6∈ Z by choosing τ = 0 (clearly yu (0) = 0) and observing that, for every time t, 1 − (1 − ε)t/ε ≤ 1 − [e−1 (1 − ε)]t = 1 − e−t (1 − ε)t ≤ 1 − e−t (1 − ε) = 1 − e−t + O(ε) . It remains to prove the lemma for the case u ∈ Z. Note that at every time t ∈ [0, ts ) Algorithm 3 chooses as x(t) a vector maximizing a linear function in P which assigns a negative weight to elements of Z. Since P is down-closed this maximum must have xu (t) = 0 for an element u ∈ Z. This means that yu (t) = 0 for t ∈ [0, ts ]. In addition to proving the lemma for this time range, the last inequality also allows us to choose τ = ts , which gives, for t ∈ [ts , 1], yu (t) ≥ 1 − (1 − ε)(t−ts )/ε ≥ 1 − ets −t + O(ε) . Combining Corollary A.7 with Lemma A.8 gives us the following corollary. Corollary A.10. Given A, for every time t ∈ [0, ts ), F (y(t + δt )) − F (y(t)) ≥ δt [f (OP T \ Z) − (1 − e−t ) · f (Z ∪ OP T ) − F (y(t)))] − O(n−1 δt ) · f (OP T ) and, for every time t ∈ [ts , 1), F (y(t + δt )) − F (y(t)) ≥ δt [e−t · f (OP T ) + (ets −t − e−t ) · max{f (OP T ) − f (Z ∪ OP T ), 0} − F (y(t))] − O(n−1 δt ) · f (OP T ) . Proof. For every time t ∈ [0, ts ), Corollary A.7 and Lemma A.8 imply together F (y(t + δt )) − F (y(t)) ≥ δt [(1 − e−t − O(n−4 )) · max {0, f (OP T \ Z) − f (OP T ∪ Z)} + (e−t − O(n−4 )) · f (OP T \ Z)] − O(n−1 δt ) · f (OP T ) ≥ δt [(1 − O(n−4 )) · f (OP T \ Z) − (1 − e−t ) · f (Z ∪ OP T ) − F (y(t)))] − O(n−1 δt ) · f (OP T ) . 18 We observe that this inequality is identical to the inequality promised for this time range by the corollary, except that it has an extra term of −δt · O(n−4 ) · f (OP T \ Z) on its right hand side. Since f (OP T \ Z) is upper bounded by f (OP T ), due to the down-closeness of P , the absolute value of this extra term is at most δt · O(n−4 ) · f (OP T ) = O(n−1 δt ) · f (OP T ) , which completes the proof for the time range t ∈ [0, ts ). Consider now the time range t ∈ [ts , 1). For this time range Corollary A.7 and Lemma A.8 imply together F (y(t + δt )) − F (y(t)) ≥ δt [(ets −t − e−t − O(n−4 )) · max {0, f (OP T ) − f (OP T ∪ Z)} + (e−t − O(n−4 )) · f (OP T )] − O(n−1 δt ) · f (OP T ) . We observe again that this inequality is identical to the inequality promised for this time range by the corollary, except that it has extra terms of −δt · O(n−4 ) · f (OP T ) and −δt · O(n−4 ) · max{0, f (OP T ) − f (OP T ∪ Z)} on its right hand side. The corollary now follows since the absolute value of both these terms is upper bounded by O(n−1 δt ) · f (OP T ). Corollary A.10 bounds the increase in F (y(t)) in terms of F (y(t)) itself. Thus, it gives a recursive formula which can be used to lower bound F (y(t)). Our remaining task is to solve this formula and get a closed-form lower bound on F (y(t)). Let g(t) be defined as follows. g(0) = 0 and for every time t < 1, g(t+δt ) ( g(t) + δt [f (OP T \ Z) − (1 − e−t ) · f (Z ∪ OP T ) − g(t)] = g(t) + δt [e−t · f (OP T ) + (ets −t − e−t ) · max{f (OP T ) − f (Z ∪ OP T ), 0} − g(t)] if t < ts , if t ≥ ts . The next lemma shows that a lower bound on g(t) yields a lower bound on F (y(t)). Lemma A.11. Given A, for every time t, g(t) ≤ F (y(t)) + O(n−1 ) · t · f (OP T ). Proof. Let c be the larger constant among the constants hiding behind the big O notations in Corollary A.10. We prove by induction on t that g(t) ≤ F (y(t)) + (ct/n) · f (OP T ). For t = 0, this clearly holds since g(0) = 0 ≤ F (y(0)). Assume now that the claim holds for some t, and let us prove it for t + δt . There are two cases to consider. If t < ts , then the induction hypothesis and Corollary A.10 imply, for a large enough n, g(t + δt ) = g(t) + δt [f (OP T \ Z) − (1 − e−t ) · f (Z ∪ OP T ) − g(t)] = (1 − δt )g(t) + δt [f (OP T \ Z) − (1 − e−t ) · f (Z ∪ OP T )] ≤ (1 − δt )[F (y(t)) + (ct/n) · f (OP T )] + δt [f (OP T \ Z) − (1 − e−t ) · f (Z ∪ OP T )] = F (y(t)) + δt [f (OP T \ Z) − (1 − e−t ) · f (Z ∪ OP T ) − F (y(t))] + (ct/n) · (1 − δt ) · f (OP T ) ≤ F (y(t + δt )) + (cδt /n) · f (OP T ) + (ct/n) · (1 − δt ) · f (OP T ) ≤ F (y(t + δt )) + [c(t + δt )/n] · f (OP T ) . Similarly, if t ≥ ts , then we get g(t + δt ) = g(t) + δt [e−t · f (OP T ) + (ets −t − e−t ) · max{f (OP T ) − f (Z ∪ OP T ), 0} − g(t)] 19 = (1 − δt )g(t) + δt [e−t · f (OP T ) + (ets −t − e−t ) · max{f (OP T ) − f (Z ∪ OP T ), 0}] ≤ (1 − δt )[F (y(t)) + (ct/n) · f (OP T )] + δt [e−t · f (OP T ) + (ets −t − e−t ) · max{f (OP T ) − f (Z ∪ OP T ), 0}] = F (y(t)) + δt [e−t · f (OP T ) + (ets −t − e−t ) · max{f (OP T ) − f (Z ∪ OP T ), 0} − F (y(t))] + (ct/n) · (1 − δt ) · f (OP T ) ≤ F (y(t + δt )) + (cδt /n) · f (OP T ) + (ct/n) · (1 − δt ) · f (OP T ) ≤ F (y(t + δt )) + [c(t + δt )/n] · f (OP T ) . It remains to find a closed-form expression that lower bounds g(t) (and thus, also F (y(t))). Let h1 (t) : [0, ts ] → R and h2 (t) : [ts , 1] → R be defined as follows. h1 (t) = (1 − e−t ) · f (OP T \ Z) − (1 − e−t − te−t ) · f (Z ∪ OP T ) , and h2 (t) = e−t · {(t − ts ) · [f (OP T ) + (ets − 1) · max{f (OP T ) − f (OP T ∪ Z), 0}] + ets · h1 (ts )} . Lemma A.12. For every time t ≤ ts , h1 (t) ≤ g(t). Proof. The proof is by induction on t. For t = 0, g(0) = 0 = (1 − e0 ) · f (OP T \ Z) − (1 − e0 − 0 · e0 ) · f (Z ∪ OP T ) = h1 (0). Assume now that the lemma holds for some t < ts , and let us prove it holds also for t + δt . By the induction hypothesis, Z t+δt h′ (τ )dτ h1 (t + δt ) = h1 (t) + t Z t+δt {e−τ · f (OP T \ Z) − τ e−τ · f (Z ∪ OP T )}dτ = h1 (t) + t ≤ h1 (t) + δt · {e−t · f (OP T \ Z) − te−t · f (Z ∪ OP T )}dτ = (1 − δt )h1 (t) + δt · {f (OP T \ Z) − (1 − e−t ) · f (Z ∪ OP T )} ≤ (1 − δt )g(t) + δt · {f (OP T \ Z) − (1 − e−t ) · f (Z ∪ OP T )} = g(t + δt ) , where the first inequality holds since e−τ is a decreasing function of τ and τ e−τ is an increasing function of τ in the range τ ∈ [0, 1]. Lemma A.13. For every time ts ≤ t ≤ 1, h2 (t) ≤ g(t). Proof. The proof is by induction on t. For t = ts , by Lemma A.12, h2 (ts ) = h1 (ts ) ≤ g(ts ). Assume now that the lemma holds for some ts ≤ t < 1, and let us prove it holds also for t + δt . To avoid repeating complex expressions, let us denote A = f (OP T ) + (ets − 1) · max{f (OP T ) − f (Z ∪ OP T ), 0}. Notice that A is independent of t. Moreover, using this notation we can rewrite h2 (t) as h2 (t) = e−t · {(t − ts ) · A + ets · h1 (ts )}. Thus, for every τ ∈ (ts , 1), h′2 (τ ) = −e−τ · {(τ − ts ) · A + ets · h1 (ts )} + e−τ · A = e−τ · {(1 − τ + ts ) · A − ets · h1 (ts )} . The definition of A and the non-negativity of f imply immediately that A ≥ 0. We would like to prove also that ts · A − ets · h1 (ts ) ≥ 0. There are two cases to consider. First, if f (OP T ) ≥ f (Z ∪ OP T ), then ts · A − ets · h1 (ts ) = ts · f (OP T ) + ts (ets − 1) · max{f (OP T ) − f (Z ∪ OP T ), 0} 20 − (ets − 1) · f (OP T \ Z) + (ets − 1 − ts ) · f (Z ∪ OP T ) ≥ ts ets · f (OP T ) − ts (ets − 1) · f (Z ∪ OP T ) − (ets − 1) · f (OP T ) + (ets − 1 − ts ) · f (Z ∪ OP T ) = (ts ets − ets + 1) · [f (OP T ) − f (Z ∪ OP T )] ≥ 0 . where the inequality uses the fact that f (OP T ) ≥ f (OP T \ Z) because of the down-closure of P . On the other hand, if f (OP T ) < f (Z ∪ OP T ), then ts · A − ets · h1 (ts ) = ts · f (OP T ) − (ets − 1) · f (OP T \ Z) + (ets − 1 − ts ) · f (Z ∪ OP T ) ≥ ts · f (OP T ) − (ets − 1) · f (OP T ) + (ets − 1 − ts ) · f (OP T ) = 0 . Using the above observations and the induction hypothesis, we can now get h2 (t + δt ) = h2 (t) + Z t+δt h′ (τ )dτ = h2 (t) + Z t+δt e−τ · {(1 − τ + ts ) · A − ets · h1 (ts )}dτ t t ≤ h2 (t) + δt · e−t · {(1 − t + ts ) · A − ets · h1 (ts )} = (1 − δt )h2 (t) + δt · e−t · A ≤ (1 − δt )g(t) + δt · e−t · A = g(t + δt ) . The last two lemmata give us the promised closed-form lower bound on g(t), which can be used to lower bound the approximation ratio of Algorithm 3. Corollary A.14. E[F (y(1))] ≥ ets −1 · [(2 − ts − e−ts − O(n−1 )) · f (OP T ) − (1 − e−ts ) · f (Z ∩ OP T ) − (2 − ts − 2e−ts ) · f (Z ∪ OP T )]. Proof. By Lemma A.11, given A, F (y(1)) ≥ g(1) − O(n−1 ) · f (OP T ) . By Lemma A.13, g(1) ≥ h2 (1) = e−1 · {(1 − ts ) · [f (OP T ) + (ets − 1) · max{f (OP T ) − f (Z ∪ OP T ), 0}] + (ets − 1) · f (OP T \ Z) − (ets − 1 − ts ) · f (Z ∪ OP T )} ≥ e−1 · {(1 − ts ) · [ets · f (OP T ) − (ets − 1) · f (Z ∪ OP T )] + (ets − 1) · [f (OP T ) − f (Z ∩ OP T )] − (ets − 1 − ts ) · f (Z ∪ OP T )} = ets −1 · [(2 − ts − e−ts ) · f (OP T ) − (1 − e−ts ) · f (Z ∩ OP T ) − (2 − ts − 2e−ts ) · f (Z ∪ OP T )] , where the second inequality holds since the submodularity and non-negativity of f imply f (OP T \ Z) ≥ f (OP T ) + f (∅) − f (Z ∩ OP T ) ≥ f (OP T ) − f (Z ∩ OP T ) . Combining the above observations we get that, given A, F (y(1)) ≥ ets −1 · [(2 − ts − e−ts − O(n−1 )) · f (OP T ) − (1 − e−ts ) · f (Z ∩ OP T ) − (2 − ts − 2e−ts ) · f (Z ∪ OP T )] . 21 Since F (y(1)) is always non-negative, this implies, by the law of total expectation, E[F (y(1))] ≥ Pr[A] · {ets −1 · [(2 − ts − e−ts − O(n−1 )) · f (OP T ) − (1 − e−ts ) · f (Z ∩ OP T ) − (2 − ts − 2e−ts ) · f (Z ∪ OP T )]} ≥ {ets −1 · [(2 − ts − e−ts − O(n−1 )) · f (OP T ) − (1 − e−ts ) · f (Z ∩ OP T ) − (2 − ts − 2e−ts ) · f (Z ∪ OP T )]} 1 − · ets −1 · (2 − ts − e−ts − O(n−1 )) · f (OP T ) n = ets −1 · [(2 − ts − e−ts − O(n−1 )) · f (OP T ) − (1 − e−ts ) · f (Z ∩ OP T ) − (2 − ts − 2e−ts ) · f (Z ∪ OP T )] , where the second inequality holds since Pr[A] ≥ 1 − n−1 by Corollary A.4. Theorem 4.1 now follows immediately by combining Corollaries A.2 and A.14. 22
8 (cs.DS)
Self Organizing Maps Whose Topologies Can Be Learned With Adaptive Binary Search Trees Using Conditional Rotations arXiv:1506.02750v1 [cs.NE] 9 Jun 2015 César A. Astudillo ∗ † B. John Oommen‡ § Abstract Numerous variants of Self-Organizing Maps (SOMs) have been proposed in the literature, including those which also possess an underlying structure, and in some cases, this structure itself can be defined by the user Although the concepts of growing the SOM and updating it have been studied, the whole issue of using a self-organizing Adaptive Data Structure (ADS) to further enhance the properties of the underlying SOM, has been unexplored. In an earlier work, we impose an arbitrary, user-defined, tree-like topology onto the codebooks, which consequently enforced a neighborhood phenomenon and the so-called tree-based Bubble of Activity (BoA). In this paper, we consider how the underlying tree itself can be rendered dynamic and adaptively transformed. To do this, we present methods by which a SOM with an underlying Binary Search Tree (BST) structure can be adaptively re-structured using Conditional Rotations (CONROT). These rotations on the nodes of the tree are local, can be done in constant time, and performed so as to decrease the Weighted Path Length (WPL) of the entire tree. In doing this, we introduce the pioneering concept referred to as Neural Promotion, where neurons gain prominence in the Neural Network (NN) as their significance increases. We are not aware of any research which deals with the issue of Neural Promotion. The advantages of such a scheme is that the user need not be aware of any of the topological peculiarities of the stochastic data distribution. Rather, the algorithm, referred to as the TTOSOM with Conditional Rotations (TTOCONROT), converges in such a manner that the neurons are ultimately placed in the input space so as to represent its stochastic distribution, and additionally, the neighborhood properties of the neurons suit the best BST that represents the data. These properties have been confirmed by our experimental results on a variety of data sets. We submit that all of these concepts are both novel and of a pioneering sort. Keywords: Adaptive Data Structures, Binary Search Trees, Self-Organizing Maps ∗ Universidad † This de Talca, Merced 437 Curicó, Chile. castudillo@utalca.cl author is Assistant Professor at the Department of Computer Science, with the Universidad de Talca. This work is partially supported by the FONDECYT grant 11121350, Chile. A very preliminary version of this paper was presented at AI’09, the 2009 Australasian Joint Conference on Artificial Intelligence, Melbourne, Australia, in December 2009. That paper won the award of being the Best Paper of the Conference. We are also very grateful for the comments made by the Associate Editor and the anonymous Referees. Their input helped in improving the quality of the final version of this paper. Thank you very much! ‡ School of Computer Science, Carleton University, Ottawa, Canada : K1S 5B6. oommen@scs.carleton.ca § Chancellor’s Professor ; Fellow : IEEE and Fellow : IAPR. This author is also an Adjunct Professor with the University of Agder in Grimstad, Norway. The work of this author was partially supported by NSERC, the Natural Sciences and Engineering Research Council of Canada. 1 1 Introduction This paper is a pioneering attempt to merge the areas of Self-Organizing Maps (SOMs) with the theory of Adaptive Data Structures (ADSs). Put in a nutshell, we can describe the goal of this paper as follows: Consider a SOM with n neurons. Rather than having the neurons merely possess information about the feature space, we also attempt to link them together by means of an underlying Data Structure (DS). This DS could be a singly-linked list, a doubly-linked list or a Binary Search Tree (BST), etc. The intention is that the neurons are governed by the laws of the SOM and the underlying DS. Observe now that the concepts of “neighborhood” and Bubble of Activity (BoA) are not based on the nearness of the neurons in the feature space, but rather on their proximity in the underlying DS. Having accepted the above-mentioned premise, we intent to take this entire concept to a higher level of abstraction and propose to modify this DS itself adaptively using operations specific to it. As far as we know, the combination of these concepts has been unreported in the literature. Before we proceed, to place our results in the right perspective, it is probably wise to see how the concept of neighborhood has been defined in the SOM literature. Kohonen, in his book [36], mentions that it is possible to distinguish between two basic types of neighborhood functions. The first family involves a kernel function (which is usually of a Gaussian nature). The second, is the so-called neighborhood set, also known as the Bubble of Activity (BoA). This paper focuses on the second type of neighborhood function. Even though the traditional SOM is dependent on the neural distance to estimate the subset of neurons to be incorporated into the BoA, this is not always the case for the SOM-variants included in the literature. Indeed, the different strategies described in the state-of-the-art utilize families of schemes to define the BoA. We mainly identify three sub-classes. The first type of BoA uses the concept of the neural distance as in the case of the traditional SOM. Once the Best Matching Unit (BMU) is identified, the neural distance is calculated by traversing the underlying structure that holds the neurons. An important property of the neural distance between two neurons is that it is proportional to the number of connections separating them. Examples of strategies that use the neural distance to determine the BoA are the Growing Cell Structures (GCS) [24], the Growing Grid (GG) [25], the Incremental Grid Growing (IGG) [13], the Growing SOM (GSOM) [3], the Tree-Structured SOM (TSSOM) [37], the Hierarchical Feature Map (HFM) [43], the Growing Hierarchical SOM (GHSOM) [50], the SelfOrganizing Tree Algorithm (SOTA) [22], the Evolving Tree (ET) [46], the Tree-based Topology Oriented SOM (TTOSOM) [8], among others. A second subset of strategies employ a scheme for determining the BoA that does not depend on the inter-neural connections. Instead, such strategies utilize the distance in the feature space. In these cases, it is possible to distinguish between two types of Neural Networks (NNs). The simplest situation occurs when the BoA only considers the BMU, i.e., it constitutes an instance of hard Competitive Learning (CL), as in the case of the Tree-Structured VQ (TSVQ) [37] and the Self-Organizing Tree Map (SOTM) [27]. A more sophisticated and computationally expensive scheme involves ranking the neurons as per their respective distances to the stimulus. In this scenario, the BoA is determined by selecting a subset of the 2 closest neurons. An example of a SOM variant that uses such a ranking is the Neural Gas (NG) [40]. According to the authors of [46], the SOM-based variants included in the literature attempt to tackle two main goals: They either try to design a more flexible topology, which is usually useful to analyze large datasets, or to reduce the the most time-consuming task required by the SOM, namely, the search for the BMU when the input set has a complex nature. In this paper we focus on the former of the two mentioned goals. In other words, our goal is to enhance the capabilities of the original SOM algorithm so as to represent the underlying data distribution and its structure in a more accurate manner. We also intend to do so by constraining the neurons so that they are related to each other, not just based on their neural indices and stochastic distribution, but also based on a BST relationship. Furthermore, as a long term ambition, we also anticipate methods which can accelerate the task of locating the nearest neuron during the CL phase. This work will present the details of the design and implementation of how an adaptive process applied to the BST, can be integrated into the SOM. Regardless of the fact that numerous variants of the SOM has been devised, few of them possess the ability of modifying the underlying topology [13, 21, 22, 26, 27, 42, 46, 52]. Moreover, only a small subset use a tree as their underlying DS [8, 21, 22, 27, 46, 52]. These strategies attempt to dynamically modify the nodes of the SOM, for example, by adding nodes, which can be a single neuron or a layer of a SOM-grid. However, our hypothesis is that it is also possible to attain to a better understanding of the unknown data distribution by performing structural tree-based modifications on the tree, which although they preserve the general topology, attempt to modify the overall configuration, i.e., by altering the way by which nodes are interconnected, and yet continue as a BST. We accomplish this by dynamically adapting the edges that connect the neurons, by rotating1 the nodes within the BST that holds the whole structure of neurons. As we will explain later, this is further achieved by local modifications to the overall structure in a constant number of steps. Thus, we attempt to use rotations, tree-based neighbors and the feature space to improve the quality of the SOM. 1.1 Motivations Acquiring information about a set of stimuli in an unsupervised manner, usually demands the deduction of its structure. In general, the topology employed by any Artificial Neural Network (ANN) possessing this ability has an important impact on the manner by which it will “absorb” and display the properties of the input set. Consider for example, the following: A user may want to devise an algorithm that is capable of learning a triangle-shaped distribution as the one depicted in Figure 1. The SOM tries to achieve this by defining an underlying grid-based topology and to fit the grid within the overall shape, as shown in Figure 1a (duplicated from [36]). However, from our perspective, a grid-like topology does not naturally fit a triangular-shaped distribution, and thus, one experiences a deformation of the original lattice during the modeling phase. As opposed to this, Figure 1b, shows the result of applying one of the techniques developed by us, namely the TTOSOM [8]. As the reader can observe from Figure 1b, a 3-ary tree seems to be a far more superior choice for representing the particular shape in question. 1 The operation of rotation is the one associated with BSTs, as will be presently explained. 3 (a) The grid learned by the SOM. (b) The tree learned by the TTOSOM. Figure 1: How a triangle-shaped distribution is learned through unsupervised learning. On closer inspection, Figure 1b depicts how the complete tree fills in the triangle formed by the set of stimuli, and further, seems to do it uniformly. The final position of the nodes of the tree suggests that the underlying structure of the data distribution corresponds to the triangle. Additionally, the root of the tree is placed roughly in the center of mass of the triangle. It is also interesting to note that each of the three main branches of the tree, cover the areas directed towards a vertex of the triangle respectively, and their sub-branches fill in the surrounding space around them in a recursive manner, which we identify as being a holograph-like behavior. Of course, the triangle of Figure 1b serves only as a very simple prima facie example to demonstrate to the reader, in an informal manner, how both techniques will try to learn the set of stimuli. Indeed, in real-world problems, these techniques can be employed to extract the properties of high-dimensional samples. One can argue that imposing an initial topological configuration is not in accordance with the founding principles of unsupervised learning, the phenomenon that is supposed to occur without “supervision” within the human brain. As an initial response we argue that this “supervision” is required to enhance the training phase, while the information we provide relates to the initialization phase. Indeed, this is in line with the well-accepted principle [23], that very little can be automatically learned about a data distribution if no assumptions are made! As the next step of motivating this research endeavor, we venture into a world where the neural topology and structure are themselves learned during the training process. This is achieved by the method that we propose in this paper, namely the TTOSOM with Conditional Rotations (TTOCONROT), which, in essence, dynamically extends the properties of the above-mentioned TTOSOM. Again, to accomplish this we need key concepts that are completely new to the field of SOMs, namely those related to tree-based Adaptive Data Structure (ADS). Indeed, as demonstrated by our experiments, the results that we have already obtained have been applauded by the research community2 , and these, to the best of our knowledge, have remained unreported in the literature. Another reason why we are interested in such an inter-area integration, deals with the issue for devising efficient methods that add neurons to the tree. Even though the schemes that we are currently proposing 2 As mentioned earlier, a paper which reported the preliminary results of this study, won the Best Paper Award in a well-known international AI conference [7]. 4 in this paper focus on tree adaptation by means of rotations, we envision another type of dynamism,i.e., one which involves the expansion of the tree structure through the insertion of newly created nodes. The state-of-the-art considers different strategies that expand trees by inserting nodes (which can be a single neuron or a SOM-layer) that essentially are based on a Quantization Error (QE) measure. In some of these strategies, the error measure is based on the “hits”, i.e., the number of times a neuron has been selected as the BMU, c.f., [13, 24, 37, 46]. The strategy that we have chosen for adapting the tree, namely using Conditional Rotations (CONROT), already utilizes this BMU counter, and, distinct to the previous strategies that attempt to search for a node to be expanded (which in the case of tree-based SOMs is usually at the level of the leaves [37, 46]), we foresee and advocate a different approach. Our TTOCONROT method asymptotically positions frequently accessed nodes close to the root, and so, according to this property, it is the root node which should be split. Observe that if we follow such a philosophy, one would not have to search for a node with a higher QE measure. Rather, the CONROT, will be hopefully, able to migrate the candidates closer to the root. Of course, this works with assumption that a larger number of hits indicates that the degree of granularity of a particular neuron justifies refinement. The concept of using the root of the tree for growing a tree-based SOM is, in and of itself, pioneering, as far as we know. 1.2 Contributions of the Paper The contributions of the paper can be summarized as follows: 1. We present an integration of the fields of SOMs and ADS. This, we respectfully, submit as pioneering. 2. The neurons of the SOM are linked together using an underlying tree-based DS, and they are governed by the laws of the TTOSOM tree-based paradigm, and simultaneously the restructuring adaptation provided by CONROT. 3. The definition of distance between the neurons is based on the tree structure, and not in the feature space. This is valid also for the BoA, rendering the migrations distinct from the state-of-the-art. 4. The adaptive nature of the TTOCONROT is unique because adaptation is perceived in two forms: The migration of the codebook vectors in the feature space is a consequence of the SOM update rule, and the rearrangement of the neurons within the tree as a result of the rotations. 1.3 Organization of the Paper The rest of the paper is organized as follows. The next section surveys the relevant literature3 , which involves both the field of SOMs including their tree-based instantiations, and the respective field of BSTs with conditional rotations. After that, in Section 2, we provide an in-depth explanation of the TTOCONROT philosophy, which is our primary contribution. The subsequent section shows the capabilities of the approach through a series of experiments, and finally, Section 5 concludes the paper. 3 For the sake of space the literature review has been considerably condensed. However, given that there is no survey paper on the area of tree-based SOMs reported in the literature, we are currently preparing a paper that summarizes the field. 5 2 Literature Review 2.1 The SOM One of the most important families of ANNs used to tackle clustering problems is the well known SOM [36]. Typically, the SOM is trained using (un)supervised learning, so as to produce a neural representation in a space whose dimension is usually smaller than that in which the training samples lie. Further, the neurons attempt to preserve the topological properties of the input space. The SOM concentrates all the information contained in a set of n input samples belonging to the ddimensional space, say X = {x1 , x2 , . . . , xn }, utilizing a much smaller set of neurons, C = {c1 , c2 , . . . , cm }, each of which is represented as a vector. Each of the m neurons contains a weight vector w = [w1 , w2 , . . . , wd ]t ∈ IRd associated with it. These vectors are synonymously called “weights”, “prototypes” or “codebook” vectors. The vector wi may be perceived as the position of neuron ci in the feature space. During the training phase, the values of these weights are adjusted simultaneously so as to represent the data distribution and its structure. In each training step a stimulus (a representative input sample from the data distribution) x is presented to the network, and the neurons compete between themselves so as to identify which is the “winner”, also known as the Best Matching Unit (BMU). After identifying the BMU, a subset of the neurons “close” to it are considered to be within the so-called Bubble of Activity (BoA), which further depends on a parameter specified to the algorithm, namely, the so-called radius. Thereafter, this scheme performs a migration of the codebooks within that BoA so as to position them closer to the sample being examined. The migration factor by which this update is effected, depends on a parameter known as the learning rate, which is typically expected to be large initially, and which decreases as the algorithm proceeds, and which ultimately results in no migration at all. Algorithm 1 describes the details of the SOM philosophy. In Algorithm 1, the parameters are scheduled by defining a sequence S = hS1 , S2 , . . . , Ss i, where each Si corresponds to a tuple (ηi , ri , ti ) that specifies the learning rate, ηi , and the radius, ri , for a fixed number of training steps, ti . The way in which the parameters decay is not specified in the original algorithm, and some alternatives are, e.g., that the parameters remain fixed, decrease linearly, exponentially, etc. Algorithm 1 SOM(X ,S) Input: i) X , the input sample set. ii) S, the schedule for the parameters. Method: 1: Initialize the weights w1 , w2 , . . . , wm , e.g., by randomly selecting elements from X . 2: repeat 3: Obtain a sample x from X . 4: Find the Winner neuron, i.e., the one which is most similar to x. 5: Determine a subset of neurons close to the winner. 6: Migrate the closest neuron and its neighbors towards x. 7: Modify the learning factor and radius as per the pre-defined schedule. 8: until no noticeable changes are observed. End Algorithm Although the SOM has demonstrated an ability to solve problems over a wide spectrum, it possesses some 6 fundamental drawbacks. One of these drawbacks is that the user must specify the lattice a priori, which has the effect that he must run the ANN a number of times to obtain a suitable configuration. Other handicaps involve the size of the maps, where a lesser number of neurons often represent the data inaccurately. The state-of-the-art approaches attempt to render the topology more flexible, so as to represent complicated data distributions in a better way and/or to make the process faster by, for instance, speeding up the task of determining the BMU. There are a vast number of domain fields where the SOM has demonstrated to be useful; a compendium with all the articles that take advantage of the properties of the SOM is surveyed in [32, 45]. These survey papers classify the publications related to the SOM according to their year of release. The report [32] includes the bibliography published between the year 1981 and 1998, while the report [45] includes the analogous papers published between 1998 and 2001. Further, additional recent references including the related work up to the year 2005 have been collected in a technical report [48]. The more recent literature reports a host of application domains, including Medical Image Processing [2], Human Eye Detection [33], Handwriting Recognition [39], Image Segmentation [56], Information Retrieval [20], Object Tracking [30], etc. 2.2 Tree-Based SOMs Although an important number of variants of the original SOM have been presented through the years, we focus our attention on a specific family of enhancements in which the neurons are inter-connected using a tree topology. The Tree-Structured VQ (TSVQ) algorithm [37] is a tree-based SOM variant, whose topology is defined a priori and which is static. The training first takes place at highest levels of the tree. The TSVQ incorporates the concept of a “frozen” node, which implies that after a node is trained for a certain amount of time, it becomes static. The algorithm then allows subsequent units, i.e., the direct children, to be trained. The strategy utilizes a heuristic search algorithm for rapidly identifying a BMU. It starts from the root and recursively traverses the path towards the leaves. If the unit currently being analyzed is frozen, the algorithm identifies the child which is closest to the stimulus, and performs a recursive call. The algorithm terminates when the node currently being analyzed is not a frozen node (i.e., it is currently being trained), and is returned as the BMU. Koikkalainen and Oja, in the same paper [37] refine the idea of the TSVQ by defining the TSSOM, which inherits all the properties of the TSVQ, but redefines the search procedure and BoA. In the case of the TSSOM, SOM layers of different dimensions are arranged in a pyramidal shape (which can be perceived as a SOM with different degrees of granularity). It differs from the TSVQ, in the sense that, once the BMU is found, the direct proximity is examined to check for the BMU. On the other hand, the BoA differs in that, instead of considering only the BMU, its direct neighbors (in the pyramid) will also be considered. The Self-Organizing Tree Algorithm (SOTA) [22] is a dynamically growing tree-based SOM which, according to their authors, take some analogies from the Growing Cell Structures (GCS) [24]. The SOTA utilizes a binary tree as the underlying structure, and similarly to other strategies (e.g., the TSSOM [37] and the Evolving Tree (ET) [46] explained below), it considers the migration of the neurons only if they 7 correspond to leaf nodes within the tree structure. Its BoA depends on the neural tree and is defined for two cases. The most general case occurs when the parent of the BMU is not the root, i.e., a situation in which the BoA is composed by the BMU, its sibling and its parent node. Otherwise, the BoA constitutes the BMU only. The SOTA triggers a growing mechanism that utilizes a QE to determine the node to be split into two new descendants. In [21] the authors presented a tree-based SOM called the Growing Hierarchical SOM (GHSOM), in which each node corresponds to an independent SOM. The expansion of the structure is dual: The first type of adaptation is conceived by inserting new rows (or columns) to the SOM grid that is currently being trained, while the second type is implemented by adding layers to the hierarchical structure. Both types of dynamism depend on the verification of QE measures. The SOTM [27] is a tree-based SOM which is also inspired by the Adaptive Resonance Theory (ART) [15]. In the SOTM, when the input is within a threshold distance from the BMU, the latter is migrated. Otherwise, a new neuron is added to the tree. Thus, in the SOTM, the subset of neurons to be migrated depends only on the distance in the feature space, and not in the neural distance, as most of the tree-based SOM families. In [46], the authors have proposed a tree-structured NN called the Evolving Tree (ET), which takes advantage of a sub-optimal procedure (adapted from the one utilized by the TSVQ) to identify the BMU in O(log |V |) time, where V is the set of neurons. The ET adds neurons dynamically, and incorporates the concept of a “frozen” neuron (explained above), which is a non-leaf node that does not participate in the training process, and which is thus removed from the BoA. Similar to the TSVQ, the training phase terminates when all the nodes become frozen. The Tree-based Topology Oriented SOM (TTOSOM) [8], which is central to this paper, is a tree-based SOM in which each node can possess an arbitrary number of children. Furthermore, it is assumed that the user has the ability to describe/create such a tree whose topological configuration is preserved through the training process. The TTOSOM uses a particular BoA that includes nodes (leaf and non-leaf ones) that are within a certain neural distance (the so-called “radius”). An interesting property displayed by this strategy is its ability to reproduce the results obtained by Kohonen, when the nodes of the SOM are arranged linearly, i.e., in a list. In this case, the TTOSOM is able to adapt this 1-dimensional grid to a 2-dimensional (or multi-dimensional) object in the same way as the SOM algorithm does [8]. This was a phenomenon that was not possessed by prior hierarchical SOM-based networks reported in the literature4 . Additionally, if the original topology of the tree followed the overall shape of the data distribution, the results reported in [8] (and also depicted in the motivational section) showed that is also possible to obtain a symmetric topology for the codebook vectors. In a more recent work [9], the authors have enhanced the TTOSOM to perform classification in a semi-supervised fashion. The method presented in [9] first learns the data distribution in an unsupervised manner. Once labeled instances become available, the clusters are labeled using the evidence. According to the results presented in [9], the number of neurons required to accurately predict the category 4 The SOM possesses the ability to learn the data distribution by utilizing a unidimensional topology [36], i.e., the neighbors are defined along a grid in each direction. Further, when this is the case, one can encounter that the unidimensional topology forms a so-called Peano curve [47]. The TTOSOM also possesses this interesting property, when the tree topology is linear. The details of how this is achieved is presented in detail in [8], including the explanation of how other tree-based techniques fail to achieve this task. 8 of novel data are only a small portion of the cardinality of the input set. 3 Merging ADS and TTOSOM 3.1 Adaptive Data Structures (ADSs) for BSTs One of the primary goals of the area of ADS is to achieve an optimal arrangement of the elements, placed at the nodes of the structure, as the number of iterations increases. This reorganization can be perceived to be both automatic and adaptive, such that on convergence, the DS tends towards an optimal configuration with a minimum average access time. In most cases, the most probable element will be positioned at the root (head) of the tree (DS), while the rest of the tree is recursively positioned in the same manner. The solution to obtain the optimal BST is well known when the access probabilities of the nodes are known a priori [35]. However, our research concentrates on the case when these access probabilities are not known a priori. In this setting, one effective solution is due to Cheetham et al. and uses the concept of CONROT [16], which reorganizes the BST so as to asymptotically produce the optimal form. Additionally, unlike most of the algorithms that are otherwise reported in the literature, this move is not done on every data access operation – it is performed if and only if the overall Weighted Path Length (WPL) of the resulting BST decreases. A BST may be used to store records whose keys are members of an ordered set A = {A1 , A2 , . . . , AN }. The records are stored in such a way that a symmetric-order traversal of the tree will yield the records in an ascending order. If we are given A and the set of access probabilities Q = {Q1 , Q2 , . . . , QN }, the problem of constructing efficient BSTs has been extensively studied. The optimal algorithm due to Knuth [35], uses dynamic programming and produces the optimal BST using O(N 2 ) time and space. In this paper, we consider the scenario in which Q, the access probability vector, is not known a priori. We seek a scheme which dynamically rearranges itself and asymptotically generates a tree which minimizes the access cost of the keys. The primitive tree restructuring operation used in most BST schemes is the well known operation of Rotation [1]. We describe this operation as follows. Suppose that there exists a node i in a BST, and that it has a parent node j, a left child, iL , and a right child, iR . The function P (i) = j relates node i with its parent j (if it exists). Also, let B(i) = k relate node i with its sibling k, i.e., the node (if it exists) that shares the same parent as i. Consider the case when i is itself a left child (see Figure 2a). A rotation is performed on node i as follows: j now becomes the right child, iR becomes the left child of node j, and all the other nodes remain in their same relative positions (see Figure 2b). The case when node i is a right child is treated in a symmetric manner. This operation has the effect of raising (or promoting) a specified node in the tree structure while preserving the lexicographic order of the elements (refer again to Figure2b). A few memory-less tree reorganizing schemes5 which use this operation have been presented in the literature among which are the Move-to-Root and the simple Exchange rules [4]. In the Move-to-Root Heuristic, each time a record is accessed, rotations are performed on it in an upwards direction until it becomes the 5 This review is necessary brief. A more detailed version is found in [18, 38]. 9 (a) The tree before a rotation is performed. The contents of the nodes are their data values, which in this case are the characters {a, b, c, d, e}. (b) The tree after a rotation is performed on node i. Figure 2: The BST before and after a Rotation is performed. root of the tree. On the other hand, the simple Exchange rule rotates the accessed element one level towards the root. Sleator and Tarjan [54] introduced a technique, which also moves the accessed record up to the root of the tree using a restructuring operation called “Splaying”, which actually is a multi-level generalization of the rotation. Their structure, called the Splay Tree, was shown to have an amortized time complexity of O(log N ) for a complete set of tree operations which included insertion, deletion, access, split, and join. The literature also records various schemes which adaptively restructure the tree with the aid of additional memory locations. Prominent among them is the Monotonic Tree (MT) [12] and Mehlhorn’s D-Tree (DT) [41]. The MT is a dynamic version of a tree structuring method originally suggested by Knuth [35]. In spite of all their advantages, all of the schemes mentioned above have drawbacks, some of which are more serious than others. The memory-less schemes have one major disadvantage, which is that both the Move-to-Root and Splaying rules always move the accessed record up to the root of the tree. This means that if a nearly-optimal arrangement is reached, a single access of a seldomly-used record will disarrange the tree along the entire access path, as the element is moved upwards to the root. As opposed to these schemes, the MT rule does not move the accessed element to the root every time. But, as reported in [16], in practice, it does not perform well. The weakness of the MT lies in the fact that it considers only the frequency counts for the records, which leads to the undesirable property that a single rotation may move a subtree with a relatively large probability weight downwards, thus increasing the cost of the tree. This paper uses a particular heuristic, namely, the Conditional Rotations for a BST (CONROT-BST) [16], which has been shown to reorganize a BST so as to asymptotically arrive at an optimal form. In its optimized version, the scheme, referred to Algorithm CONROT-BST, requires the maintenance of a single memory location per record, which keeps track of the number of accesses to the subtree rooted at that record. The CONROT-BST algorithm specifies how an accessed element can be rotated towards the root of the tree so as to minimize the overall cost of the entire tree. Finally, unlike most of the algorithms that are currently 10 in the literature, this move is not done on every data access operation. It is performed if and only if the overall WPL of the resulting BST decreases. In essence Algorithm CONROT-BST attempts to minimize the WPL by incorporating the statistical information about the accesses to the various nodes and subtrees rooted at the corresponding nodes. The basic condition for the rotation of a node is that the WPL of the entire tree must decrease as a result of a single rotation. This is achieved by a so-called Conditional Rotation. To define the concept of a Conditional Rotation, we define τi (n) as the total number of accesses to the subtree rooted at node i. One of the biggest advantages of the CONROT-BST heuristic is that it only requires the maintenance and processing of the values stored at a specific node and its direct neighbors, i.e., its parent and both children, if they exist. Algorithm CONROT-BST, formally given in Algorithm 2, describes the process of the conditional rotations for a BST. The algorithm receives two parameters, the first of which corresponds to a pointer to the root of the tree, and the second which corresponds to the key to be searched, which is assumed to be present in the tree. When a node access is requested, the algorithm seeks for the node from the root down towards the leaves. Algorithm 2 CONROT-BST(j,ki) Input: i) j, A pointer to the root of a binary search tree T ii) ki , A search key, assumed to be in T Output: i) The restructured tree T ′ ii) A pointer to the record i containing ki Method: 1: τj ← τj + 1 2: if ki = kj then 3: if is-left-child(j) = TRUE then 4: Ψj ← 2τj − τjR − τP (j) 5: else 6: Ψj ← 2τj − τjL − τP (j) 7: end if 8: if Ψj > 0 then 9: rotate-upwards(j) 10: recalculate-tau(j) 11: recalculate-tau(P (j)) 12: end if 13: return record j 14: else 15: if ki < kj then 16: CONROT-BST( left-child(j) , ki ) 17: else 18: CONROT-BST( right-child(j) , ki ) 19: end if 20: end if End Algorithm The first task accomplished by the Algorithm CONROT-BST is the updating of the counter τ for the present node along the path traversed. After that, the next step consists of determining whether or not the 11 node with the requested key has been found. When this occurs, the quantities defined by Equations (1) and (2) are computed to determine the value of a quantity referred to as Ψ, where: Ψj = 2τj − τjR − τP (j) (1) when j is the left child of its parent, P (j), and Ψj = 2τj − τjL − τP (j) (2) when j is a right descendant of P (j). When Ψ is less than zero, an upward rotation is performed. The authors of [16] have shown that this single rotation leads to a decrease in the overall WPL of the entire tree. This occur in line 9 of the algorithm, in which the method rotate-upwards is invoked. The parameter to this method is a pointer to the node j. The method does the necessary operations required to rotate the node upwards, which means that if the node j is the left child of the parent, then this is equivalent to performing a right rotation over P (j), the parent of j. Analogously, when j is the right child of its parent, the parent of j is left-rotated instead. Once the rotation takes place, it is necessary to update the corresponding counters, τ . Fortunately this task only involve the updating of τi , for the rotated node, and the counter of its parent, τP (i) . The last part of the algorithm, namely lines 14–19, deals with the further search for the key, which in this case is achieved recursively. The reader will observe that all the tasks invoked in the algorithm are performed in constant time, and in the worst case, the recursive call is done from the root down to the leaves, leading to a O(h) running complexity, where h is the height of the tree. 3.2 The TTOSOM with Conditional Rotations (TTOCONROT) This section concentrates on the details of the integration between the fields of ADS and the SOM, and in particular, the TTOSOM. Although merging ADS and the SOM is relevant to a wide spectrum of DSs, we focus our scope by considering only tree-based structures. More specifically we shall concentrate on the integration of the CONROT-BST heuristic [16] into a TTOSOM [8], both of which were explained in the preceding sections. We can conceptually distinguish our method, namely, the Tree-based Topology Oriented SOM with Conditional Rotations (TTOCONROT) from its components and properties. In terms of components, we detect five elements. First of all, the TTOCONROT has a set of neurons, which, like all SOM-based methods, represents the data space in a condensed manner. Secondly, the TTOCONROT possesses a connection between the neurons, where the neighbor of any specific neuron is based on a nearness measure that is tree-based. The third and fourth components involve the migration of the neurons. Similar to the reported families of SOMs, a subset of neurons closest to the winning neuron are moved towards the sample point using a Vector Quantization (VQ) rule. However, unlike the reported families of SOMs, the identity of the neurons that are moved is based on the tree-based proximity and not on 12 the feature-space proximity. Finally, the TTOCONROT possesses tree-based mutating operations, namely the above-mentioned conditional rotations. With respect to the properties of the TTOCONROT, we mention the following. First of all, it is adaptive, with regard to the migration of the points. Secondly, it is also adaptive with regard to the identity of the neurons moved. Thirdly, the distribution of the neurons in the feature space mimics the distribution of the sample points. Finally, by virtue of the conditional rotations, the entire tree is optimized with regard to the overall accesses, which is a unique phenomenon (when compared to the reported family of SOMs) as far as we know. As mentioned in the introductory section, the general dynamic adaptation of SOM lattices reported in the literature considers essentially adding (and in some cases deleting) nodes/edges. However the concept of modifying the underlying structure’s shape itself has been unrecorded. Our hypothesis is that this is advantageous by means of a repositioning of the nodes and the consequent edges, as seen when one performs rotations on a BST. In other words, we place our emphasis on the self-arrangement which occurs as a result of restructuring the DS representing the SOM. In this case, as alluded to earlier, the restructuring process is done between the connections of the neurons so as to attain an asymptotically optimal configuration, where nodes that are accessed more frequently will tend to be placed close to the root. We thus obtain a new species of tree-based SOMs which is self-arranged by performing rotations conditionally, locally and in a constant number of steps. The primary goal of the field of ADS is to have the structure and its elements attain an optimal configuration as the number of iterations increases. Particularly, among the ADSs that use trees as the underlying topology, the common goal is to minimize the overall access cost, and this roughly means that one places the most frequently accessed nodes close to the root, which is also what CONROT-BST moves towards. Although such an adaptation can be made on any SOM paradigm, the CONROT is relevant to a tree structure, and thus to the TTOSOM. This further implies that some specific settings/modifications must be applied to achieve the integration between the two paradigms. We start by defining a Binary Search Tree SOM (BSTSOM) as a special instantiation of a SOM which uses a BST as the underlying topology. An Adaptive BSTSOM (ABSTSOM) is a further refinement of the BSTSOM which, during the training process, employs a technique that automatically modifies the configuration of the tree. The goal of this adaptation is to facilitate and enhance the search process. This assertion must be viewed from the perspective that for a SOM, neurons that represent areas with a higher density, will be queried more often. Every ABSTSOM is characterized by the following properties. First, it is adaptive, where, by virtue of the BST representation this adaptation is done by means of rotations, rather than by merely deleting or adding nodes. Second, the neural network corresponds to a BST. The goal is that the NN maintains the essential stochastic and topological properties of the SOM. 3.2.1 Neural Distance As in the case of the TTOSOM [8], the Neural Distance, dN , between two neurons depends on the number of unweighted connections that separate them in the user-defined tree. It is consequently the number of edges 13 in the shortest path that connects the two given nodes. More explicitly, the distance between two nodes in the tree, is defined as the minimum number of edges required to go from one to the other. In the case of trees, the fact that there is only a single path connecting two nodes implies the uniqueness of the shortest path, and permits the efficient calculation of the distance between them by a node traversal algorithm. Note however, that in the case of the TTOSOM, since the tree itself was static, the inter-node distances can be pre-computed a priori, simplifying the computational process. The situation changes when the tree is dynamically modified as we shall explain below. The implications of having the tree which describes the SOM to be dynamic, are three-fold. First of all, the siblings of any given node may change at every time instant. Secondly, the parents and ancestors of the node under consideration could also change at every instant. But most importantly, the structure of the tree itself could change, implying that nodes that were neighbors at any time instant may not continue to be neighbors at the next. Indeed, in the extreme case, if a node was migrated to become the root, the fact that it had a parent at a previous time instant is irrelevant at the next. This, of course, changes the entire landscape, rendering the resultant SOM to be unique and distinct from the state-of-the-art. An example will clarify this. Consider Figure 3, which illustrates the computation of the neural distance for various scenarios. First, in Figure 3a, we present the scenario when the node accessed is B. Observe that the distances are depicted with dotted arrows, with an adjacent numeric index specifying the current distance from node B. In the example, prior to an access, nodes H, C and E are all at a distance of 2 from node B, even though they are at different levels in the tree. The reader should be aware that non-leaf nodes may also be involved in the calculation, as in the case of node H. Figures 3b and 3c show the process when node B is queried, which in turn triggers a rotation of node B upwards. Observe that the rotation itself only requires local modifications, leaving the rest of the tree untouched. For the sake of simplicity and explicitness, unmodified areas of the tree are represented by dashed lines. Finally, Figure 3d depicts the configuration of the tree after the rotation is performed. At this time instant, C and E are both at distance of 3 from B, which means that they have increased their distance to B by unity. Moreover, although node H has changed its position, its distance to B remains unmodified. Clearly, the original distances are not necessarily preserved as a consequence of the rotation. Generally speaking, there are four regions of the tree that remain unchanged. These are, namely, the portion of the tree above the parent of the node being rotated, the portion of tree rooted at the right child of the node being rotated, the portion of tree rooted at the left child of the node being rotated, and the portion of tree rooted at the sibling of the node being rotated. Even though these four regions remain unmodified, the neural distance in these regions are affected, because the rotation could lead to a modification of the distances to the nodes. Another consequence of this operation that is worth mentioning is the following: The distance between any two given nodes that belong to the same unmodified region of the tree is preserved after a rotation is performed. The proof of this assertion is obvious, inasmuch as the fact remains that every path between nodes in any unmodified sub-tree remains with the same sub-tree. This property is interesting because it has the potential to accelerate the computation of the respective neural distances. 14 (a) (b) (c) (d) Figure 3: Example of the neural distance before and after a rotation. In Figure 3a nodes H, C and E are equidistant from B even though they are at different levels in the tree. Figures 3b and 3c show the process of rotating node A upwards. Finally, Figure 3d depicts the state of the tree after the rotation when only C and E are equidistant from B, and their distance to B has increased by unity. On the other hand, although H has changed its position, its distance to B remains the same. 3.2.2 The Bubble of Activity A concept closely related to the neural distance, is the one referred to as the Bubble of Activity (BoA) which is the subset of nodes within a distance of r away from the node currently examined. Those nodes are in essence those which are to be migrated toward the signal presented to the network. This concept is valid for all SOM-like NNs, and in particular for the TTOSOM. We shall now consider how this bubble is modified in the context of rotations. The concept of the bubble involves the consideration of a quantity, the so-called radius, which establishes how big the BoA is, and which therefore has a direct impact on the number of nodes to be considered. The BoA can be formally defined as [8] B(vi ; T, r) = {v|dN (vi , v; T ) ≤ r}, (3) where vi is the node currently being examined, and v is an arbitrary node in the tree T , whose nodes are V . Note that B(vi , T, 0) = {vi }, B(vi , T, i) ⊇ B(vi , T, i − 1) and B(vi , T, |V |) = V which generalizes the special case when the tree is a (simple) directed path. To clarify how the bubble changes in the context of rotations, we first describe the context when the tree is static. As presented in [8], the function TTOSOM Calculate Neighborhood (see Algorithm 3) specifies the steps involved in the calculation of the subset of neurons that are part of the neighborhood of the BMU. This computation involves a collection of parameters, including B, the current subset of neurons in the proximity of the neuron being examined, v, the BMU itself, and r ∈ IN the current radius of the neighborhood. When the function is invoked for the first time, the set B contains only the BMU marked as the current node, and 15 Algorithm 3 TTOSOM Calculate Neighborhood(B,v,r) Input: i) B, the set of the nodes in the bubble of activity identified so far. ii) v, the node from where the bubble of activity is calculated. iii) r, the current radius of the bubble of activity. Output: i) The set of nodes in the bubble of activity. Method: 1: if r ≤ 0 then 2: return 3: else 4: for all child ∈ v.getChildren() do 5: if child ∈ / B then 6: B ← B + {child } 7: TTOSOM Calculate Neighborhood(B,child , r − 1) 8: end if 9: end for 10: parent =v.getParent(); 11: if parent 6= NULL and parent ∈ / B then 12: B ← B + {parent } 13: TTOSOM Calculate Neighborhood(B,parent , r − 1) 14: end if 15: end if End Algorithm through a recursive call, B will end up storing the entire set of units within a radius r of the BMU. The tree is recursively traversed for all the direct topological neighbors of the current node, i.e., in the direction of the direct parent and children. Every time a new neuron is identified as part of the neighborhood, it is added to B and a recursive call is made with the radius decremented by one unit6 , marking the recently added neuron as the current node. The question of whether or not a neuron should be part of the current bubble, depends on the number of connections that separate the nodes rather than the distance that separate the networks in the solution space (for instance, the Euclidean distance). Figure 4 depicts how the BoA differs from the one defined by the TTOSOM as a result of applying a rotation. Figure 4a shows the BoA around the node B, using the same configuration of the tree as in Figure 3a, i.e., before the rotation takes place. Here, the BoA when r = 1 involves the nodes {B, A, D, F }, and when r = 2 the nodes contained in the bubble are {B, A, D, F, C, E, H}. Subsequently, considering a radius equal to 3, the resulting BoA contains the nodes {B, A, D, F, C, E, H, G, I}. Finally, the r = 5 case leads to a BoA which includes the whole set of nodes. Now, observe the case presented in Figure 4b, which corresponds to the BoA around B after the rotation upwards has been effected, i.e., the same configuration of the tree used in Figure 3d. In this case, when the radius is unity, nodes {B, A, F } are the only nodes within the bubble, which is different from the corresponding bubble before the rotation is invoked. Similarly, when r = 2, we obtain a set different from the analogous pre-rotation case, which in this case is {B, A, F, D, H}. Note that coincidentally, for the case of a radius equal to 3, the bubbles are identical before and after the rotation, i.e., they invoke the nodes {B, A, D, F, G, I}. Trivially, again, when r = 5, the BoA invokes the entire tree. 6 This fact will ensure that the algorithm reaches the base case when r = 0. 16 (a) Before. (b) After. Figure 4: The BoA associated with the TTOSOM before and after a rotation is invoked at node B. As explained, Equation (3) describes the criteria for a BoA calculated on a static tree. It happens that, as a result of the conditional rotations, the tree will be dynamically adapted, and so the entire phenomenon has to be re-visited. Consequently, the BoA around a particular node becomes a function of time, and, to reflect this fact, Equation (3) should be reformulated as: B(vi ; T, r, t) = {v|dN (vi , v; T, t) ≤ r}, (4) where t is the discrete time index. The algorithm to obtain the BoA for a specific node in such a setting is identical to Algorithm 3, except that the input tree itself dynamically changes. Further, even though the formal notation includes the time parameter, “t”, it happens that, in practice, the latter is needed only if the user/application requires a history of the BoA for any or all the nodes. Storing the history of BoAs will require the maintenance of a DS that will primarily store the changes made to the tree itself. Although storing the history of changes made to the tree can be done optimally [31], the question of explicitly storing the entire history of the BoAs for all the nodes in the tree remains open. 3.2.3 Enforcing the BST Property The CONROT-BST heuristic [16] requires that the tree should possess the BST property [18]: Let x be a node in a BST. If y is a node in the left subtree of x, then key[y] ≤ key[x]. Further, if y is a node in the right subtree of x, then key[x] ≤ key[y]. To satisfy the BST property, first of all we see that, the tree must be binary7 . As a general TTOSOM utilizes an arbitrary number of children per node, one possibility is to bound the value of the branching factor to be 2. In other words, the tree trained by the TTOSOM is restricted to contain at most two children per node. Additionally, the tree must implicitly involve a comparison operator between the two children so as to discern between the branches and thus perform the search process. This comparison can be achieved by defining a unique key that must be maintained for each node in the tree, and which will, in turn, allow a 7 Of course, this is a severe constraint. But we are forced to require this, because the phenomenon of achieving conditional rotations for arbitrary k-ary trees is unsolved. This research, however, is currently being undertaken. 17 lexicographical arrangement of the nodes. This leads to a different, but closely related concept, which concerns the preservation of the topology of the SOM. During the training process, the configuration of the tree will change as the tree evolves, positioning nodes that are accessed more often closer to the root. This probability-based ordering, will hopefully, be preserved by the rotations. A particularly interesting case occurs when the imposed tree corresponds to a list of neurons, i.e., a 1-ary tree. If the TTOSOM is trained using such a tree where each node has at most two children, then the adaptive process will alter the original list. The rotations will then modify the original configuration, generating a new state, where the non-leaf nodes might have one or two children each. In this case the consequence of incorporating ADS-based enhancements to the TTOSOM will imply that the results obtained will be significantly different from those shown in [8]. As shown in [35], an optimal arrangement of the nodes of the tree can be obtained using the probabilities of accesses. If these probabilities are not known a priori, then the CONROT-BST heuristic offers a solution, which involves a decision of whether or not to perform a single rotation towards the root. It happens that the concept of the “just accessed” node in the CONROT-BST is compatible with the corresponding BMU defined for the CL model. In CL, a neuron may be accessed more often than others and some techniques take advantage of this phenomenon through the inclusion of strategies that add or delete nodes The CONROT-BST implicitly stores the information acquired by the currently accessed node by incrementing a counter for that node. This is (in a distant sense) akin to the concept of a BMU counter which adds or delete nodes in competitive networks. During the training phase, when a neuron is a frequent winner of the CL, it gains prominence in the sense that it can represent more points from the original data set. This phenomenon is registered by increasing the BMU counter for that neuron. We propose that during the training phase, we can verify if it is worth modifying the configuration of the tree by moving this neuron one level up towards the root as per the CONROT-BST algorithm, and consequently explicitly recording the relevant role of the particular node with respect to its nearby neurons. CONROT-BST achieves this by performing a local movement of the node, where only its direct parent and children are aware of the neuron promotion. Neural Promotion is the process by which a neuron is relocated in a more privileged position8 in the network with respect to the other neurons in the NN. Thus, while all “all neurons are born equal”, their importance in the society of neurons is determined by what they represent. This is achieved, by an explicit advancement of its rank or position. Given this premise, the nodes in the tree will be adapted in such a way that neurons that have been BMUs more frequently, will tend to move towards the root if an only if a reduction in the overall WPL is obtained as a consequence of such a promotion. The properties of CONROT-BST guarantee this. Once the SOM and BST are “tied” together in a symbiotic manner (where one enhances the other and vice versa), the adaptation can be achieved by affecting the configuration of the BST. This task will be performed every time a training step of the SOM is performed. Clearly, it is our task to achieve an integration of the 8 As far as we know, we are not aware of any research which deals with the issue of Neural Promotion. Thus, we believe that this concept, itself, is pioneering. 18 BST and the SOM, and Figure 5 depicts the main architecture used to accomplish this. It transforms the structure of the SOM by modifying the configuration of the BST that, in turn, holds the structure of the neurons. Figure 5: Architectural view of an Adaptive Tree-Based SOM. As this work constitutes the first attempt to constraint a tree-based SOM using a BST, our focus is placed on the self-adaptation of the nodes. In this sense, the unique identifiers of the nodes are employed to maintain the BST structure and to promote nodes that are frequently accessed towards the root. We are currently examining ways to enhance this technique so as to improve the time required to identify the BMU as well. 3.2.4 Initialization Initialization, in the case of the BST-based TTOSOM, is accomplished in two main steps which involve defining the initial value of each neuron and the connections among them. The initialization of the codebook vectors are performed in the same manner as in the basic TTOSOM. The neurons can assume a starting value arbitrarily, for instance, by placing them on randomly selected input samples. On the other hand, a major enhancement with respect to the basic TTOSOM lays in the way the neurons are linked together. The basic definition of the TTOSOM utilizes connections that remain static through time. The beauty of such an arrangement is that it is capable of reflecting the user’s perspective at the time of describing the topology, and it is able to preserve this configuration until the algorithm reaches convergence. The inclusion of the rotations renders this dynamic. 3.2.5 The Required Local Information In our proposed approach, the codebooks of the SOM correspond to the nodes of a BST. Apart from the information regarding the codebooks themselves in the feature space, each neuron requires the maintenance of additional fields to achieve the adaptation. Besides this, each node inherits the properties of a BST Node, and it thus includes a pointer to the left and right children, as well as (to make the implementation easier), a pointer to its parent. Each node also contains a label which is able to uniquely identify the neuron when it is in the “company” of other neurons. This identification index constitutes the lexicographical key used to sort the nodes of the tree and remains static as time proceeds. Figure 6 depicts all the fields included in a 19 neuron of a BST-based SOM. Figure 6: Fields included in a BST-based SOM neuron. 3.2.6 The Neural State The different states that a neuron may assume during its lifetime are illustrated in Figure 7. At first, when the node is created, it is assigned a unique identifier, and the rest of the data fields are populated with their initial values. Here, the codebook vector assumes a starting value in the feature space, and the pointers are configured so as to appropriately link the neuron with the rest of the neurons in the tree in a BST configuration. Next, during the most significant portion of the algorithm, the NN enters a main loop, where training is effected. This training phase, involves adjusting the codebooks and may also trigger optional modules that affect the neuron. Once the BMU is identified, the neuron might assume the “restructured” state, which means that a restructuring technique, such as the CONROT algorithm, will be applied. Alternatively, the neuron might be ready to accept queries, i.e., be part of the CL process in the mapping mode. Additionally, an option that we are currently investigating, involves the case when a neuron is no longer necessary and may thus be eliminated from the main neural structure. We refer to this state as the so-called “deleted” state, and it is depicted using dashed lines. Finally, we foresee an alternative state referred to as the “frozen” state, in which the neuron does not participate in the CL during the training mode although it may continue to be part of the overall NN structure. Figure 7: Possible states that a neuron may assume. 3.2.7 The Training Step of the TTOCONROT The training module of the TTOCONROT is responsible of determining the BMU, performing restructuring, calculating the BoA and migrating the neurons within the BoA. Basically, what has to be done, is to integrate the CONROT algorithm into the sequence of steps responsible for the training phase of the TTOSOM. 20 Algorithm 4 describes the details of how this integration is accomplished. Line 1 performs the first task of the algorithm, which involves determining the BMU. After that, line 2 invokes the CONROT procedure. The rationale for following this sequence of steps is that the parameters needed to perform the conditional rotation, as specified in [16], includes the “key” of the element queried, which, in the present context, corresponds to the identity of the BMU. At this stage of the algorithm, the BMU may be rotated or not depending on the optimizing criterion given by equations (1) and (2), and the BoA is determined after this restructuring is done. These are performed in lines 3 and 4 of the algorithm respectively. Finally, lines 5 to 7, are responsible for the neural migration itself, and oversee the movement of the neurons within the BoA towards the input sample. Algorithm 4 TTOCONROT-BST train(x,p) Input: i) x, a sample signal. ii) p, the pointer to the tree. Method: 1: v ← TTOSOM Find BMU(x,p) 2: cond-rot-bst(p,v.getID()) 3: B ← {v} 4: TTOSOM Calculate Neighborhood(B,v,radius) 5: for all b ∈ B do 6: update rule(b.getCodebook(),x) 7: end for End Algorithm 3.2.8 Alternative Restructuring Techniques Even though, we have explained the advantages of the CONROT algorithm, the architecture that we are proposing allows the inclusion of alternative restructuring modules other than the CONROT. Potential candidates which can be used to perform the adaptation are the ones mentioned in Section 3.1 and include the splay and the MT algorithms, among others. 4 Experimental Results To illustrate the capabilities of our method, the experiments reported in the present work are primarily focused in lower dimensional feature spaces. This will help the reader in geometrically visualizing the results we have obtained. However, it is important to remark that the algorithm is also capable of solving problems in higher dimensions, although a graphical representation of the results will not be as illustrative. We know that, as per the results obtained in [8], the TTOSOM is capable of inferring the distribution and structure of the data. However, in this present setting, we are interested in investigating the effects of applying the neural rotation as part of the training process. To render the results comparable, the experiments in this section use the same schedule for the learning rate and radius, i.e., no particular refinement of the parameters has been done for any specific data set. Additionally, the parameters follow a rather “slow” decrement of the so-called decay parameters, allowing us to understand how the prototype vectors are moved as convergence 21 takes place. When solving practical problems, we recommend a further refinement of the parameters so as to increase the speed of the convergence process. 4.1 TTOCONROT’s Structure Learning Capabilities We shall describe the performance of TTOCONROT with data sets in 1, 2 and 3 dimensions, as well as experiments in the multidimensional domain. The specific advantages of the algorithm for various scenarios will also be highlighted. 4.1.1 One Dimensional Objects Since our entire learning paradigm assumes that the data has a tree-shaped model, our first attempt was to see how the philosophy is relevant to a unidimensional object (i.e., a curve), which really possesses a “linear” topology. Thus, as a prima facie case, we tested the strength of the TTOCONROT to infer the properties of data sets generated from linear functions in the plane. Figure 8 shows different snapshots of how the TTOCONROT learns the data generated from a curve. Random initialization was used by uniformly drawing points from the unit square. Observe that the original data points do not lie in the curve. Our aim here was to show how our algorithm could learn the structure of the data using arbitrary (initial and “non-realistic”) values for the codebook vectors. Figures 8b and 8c depict the middle phase of the training process, where the edges connecting the neurons are omitted for simplicity. It is interesting to see how, after a few hundred training steps, the original chaotic placement of the neurons are rearranged so as to fall within the line described by the data points. The final configuration is shown in Figure 8d. The reader should observe that after convergence has been achieved, the neurons are placed almost equidistantly along the curve. Even though the codebooks are not sorted in and increasing numerical order, the hidden tree and its root, denoted by two concentric squares, are configured in such a way that nodes that are queried more frequently will tend to be closer to the root. In this sense, the algorithm is not only capturing the essence of the topological properties of the data set, but at the same time rearranging the internal order of the neurons according to their importance in terms of their probabilities of access. 4.1.2 Two Dimensional Data Points To demonstrate the power of including ADS in SOMs, we shall now consider the same two-dimensional data sets studied in [8]. First we consider the data generated from a triangular-spaced distribution, as shown in Figures 9a-9d. In this case, the initial tree topology is unidirectional, i.e., a list, although, realistically, this is quite inadvisable considering the true (unknown) topology of the distribution. In other words, we assume that the user has no a priori information about the data distribution. Thus, for the initialization phase, a 1-ary tree is employed as the tree structure, and the respective keys are assigned in an increasing order. Observe that in this way we are providing minimal information to the algorithm. The root of the tree is marked with two concentric squares, i.e., the neuron labeled with the index 0 in Figure 9a. Also, with regards to the feature space, the prototype vectors are initially randomly placed. In the first iteration, the linear topology is lost, which is attributable to the randomness of the data points. As the prototypes are migrated 22 1 9 5 8 7 3 4 3 2 0 7 6 9 0 5 2 1 8 4 6 (a) After 0 iterations (b) After 1,000 iterations 7 6 7 6 8 8 4 4 9 3 0 9 3 5 5 0 2 1 1 (c) After 3,000 iterations 2 (d) After 5,000 iterations Figure 8: A 1-ary tree, i.e., a list topology, learns a curve. For the sake of simplicity, the edges are ommitted. and reallocated (see Figures 9b and 9c ), the 1-ary tree is modified as a consequence of the rotations. Such a transformation is completely novel to the field of SOMs. Finally, Figure 9d depicts the case after convergence has taken place. Here, the tree nodes are uniformly distributed over the entire triangular domain. The BST property is still preserved, and further rotations are still possible if the training process continues. This experiment serves as an excellent example to show the differences between our current method and the original TTOSOM algorithm [8], where the same data set with similar settings was utilized. In the case of the TTOCONROT the points effectively represent the entire data set. However, the reader must observe that we do not have to provide the algorithm with any particular a priori information about the structure of the data distribution – this is learned during the training process, as shown in Figure 9d. Thus, the specification of the initial “user-defined” tree topology (representing his perspective of the data space) required by the TTOSOM is no longer mandatory, and an alternative specification which only requires the number of nodes in the initial 1-ary tree is sufficient. A second experiment involves a Gaussian distribution. Here a 2-dimensional Gaussian ellipsoid is learned using the TTOCONROT algorithm. The convergence of the entire training execution phase is displayed in Figure 10. This experiment considers a complete BST of depth 4, i.e., containing 15 nodes. For simplicity the labels of the nodes have been removed. In Figure 10, the tree structure generated by the neurons suggest an ellipsoidal structure for the data distribution. This experiment is a good example to show how the nodes close to the root represent dense areas of the ellipsoid, and at the same time, those node that are far from the root (in tree space) occupy regions with low density, e.g., in the “extremes” of the ellipse. The TTOCONROT infers this structure without receiving any a priori information about the distribution or its structure. The experiment shown in Figures 11a-11d considers data generated from an irregular shape with a concave surface. Again, as in the case of the experiments described earlier, the original tree includes 15 neurons arranged unidirectionally, i.e., as in a list. As a result of the training, the distribution is learned and the 23 2 10 14 12 8 4 5 2 7 3 9 1 0 0 3 89 10 7 1 6 4 13 14 12 11 13 6 5 11 (a) After 0 iterations (b) After 1,000 iterations 2 2 6 6 3 3 9 1 1 0 7 4 10 12 11 8 0 9 10 7 14 13 5 11 (c) After 3,000 iterations 8 4 12 14 13 5 (d) After 5,000 iterations Figure 9: A 1-ary tree, i.e., a list topology, learns a triangular distribution. The DS is self-adapted so that nodes accessed more frequently are moved closer to the root conditionally. The BST property is also preserved. Figure 10: A tree learns a Gaussian distribution. The neurons that are accessed more frequently are promoted closer to the root. tree is adapted accordingly, as illustrated in Figure 11d. Observe that the random initialization is performed by randomly selecting points from the unit square, and this points thus do not necessarily fall within the concave boundaries. Although this initialization scheme is responsible of placing codebook vectors outside 24 of the irregular shape, the reader should observe that in a few training steps, they are repositioned inside the contour. It is important to indicate that, even though after the convergence of the algorithm, a line connecting two points passes outside the overall “unknown” shape, one must take into account that the TTOCONROT tree attempts to mimic the stochastic properties in terms of access probabilities. When the user desires the topological mimicry in terms of skeletal structure, we recommend the use of the TTOSOM instead. The final distribution of the points is quite amazing! 6 138 7 4 7 9 10 8 10 0 6 7 8 8 3 9 6 6 9 9 10 10 0 0 1 1 5 11 5 12 13 11 12 7 14 5 11 2 3 14 1 10 (a) After 0 iterations 12 14 4 2 (b) After 1,000 iterations 2 11 13 12 4 13 2 5 3 (c) After 3,000 iterations 14 4 3 (d) After 5,000 iterations Figure 11: A 1-ary tree, i.e., a list topology, learns different distributions from a concave object using the TTOCONROT algorithm. The set of parameters is the same as in the other examples. 4.1.3 Three Dimensional Data Points We will now explain the results obtained when applying the algorithm with and without CONROT. To do this we opt to consider three-dimensional objects. The experiments utilize the data generated from the contour of the unit sphere. It also initially involves an uni-dimensional chain of 31 neurons. Additionally, in order to show the power of the algorithm, both cases initialize the codebooks by randomly drawing points from the unit cube, which thus initially places the points outside the sphere itself. Figure 12 presents the case when the basic TTO algorithm (without CONROT) learns the unit sphere without performing conditional rotations. The illustration presented in Figure 12a show the state of the neurons before the first iteration is completed. Here, as shown, the codebooks lie inside the unit cube, although some of the neurons are positioned outside the boundary of the respective circumscribed sphere, which is the one we want to learn. Secondly, Figures 12b and 12c depict intermediate steps of the learning phase. As the algorithm processes the information provided by the sample points and the neurons are repositioned, the chain of neurons is constantly “twisted” so as to adequately represent the entire manifold. Finally, Figure 12d illustrates the case when the convergence is reached. In this case, the one-dimensional list of neurons is evenly distributed over the sphere, preserving the original properties of the 3-dimensional object and also presenting a shape which reminds the viewer of the so-called Peano curve [47]. A complimentary set of experiments which involved the learning of the same unit sphere where the TTO scheme was augmented by conditional rotations (i.e., CONROT) was also conducted. Figure 13a shows the initialization of the codebooks. Here, the starting positions of the neurons fall within the unit cube as in the case displayed in Figure 12a. Figures 13b and 13c show snapshots after 1, 000 and 3, 000 iterations respectively. In this case the tree configuration obtained in the intermediate phases differ significantly from those obtained by the corresponding configurations shown in Figure 12, i.e., those that involved no rotations. In this case, the list rearranges itself as per CONROT, modifying the original chain structure to yield a more25 14 7 7 19 10 8 26 28 24 22 15 25 28 1 17 27 12 4 26 31 21 121718 16 15 14 13 23 22 21 20 19 22 28 13 3 16 26 6 4 21 5 19 30 29 31 9 10 4 5 6 7 89 2 18 3 2 11 11 29 24 23 5 24 17 31 30 0 27 11 6 0 29 6 25 910 30 23 7 25 20 0 1 2 3 24 20 15 27 1 14 15 0 3 2 16 18 8 22 13 18 20 12 5 23 21 14 17 1 4 19 12 11 10 9 29 28 27 26 25 31 30 8 13 16 (a) After 0 iterations (b) After 1,000 iter. (c) After 3,000 iter. (d) After 5,000 iter. Figure 12: A 1-ary tree, i.e., a list topology, learns a sphere distribution when the algorithm does not utilize any conditional rotation. or-less balanced tree. Finally, from the results obtained after convergence, and illustrated in Figure 13d, it is possible to compare both scenarios. In both cases, we see that the tree is accurately learned. However, in the first case, the structure of the nodes is maintained as a list throughout the learning phase, while, in the case when CONROT is applied, the configuration of the tree is constantly revised, promoting those neurons that are queried more frequently. Additionally, the experiments show us how the dimensionality reduction property evidenced in the traditional SOM, is also present in the TTOCONROT. Here, an object in the 3-dimensional domain is successfully learned by our algorithm, and the properties of the original manifold are captured from the perspective of a tree. 13 24 25 9 9 11 7 25 18 9 10 30 30 10 24 11 4 6 27 12 8 20 23 19 8 14 1 02 3 15 14 27 19 6 24 12 16 14 15 13 30 18 17 15 17 21 20 21 13 22 13 22 26 29 30 28 27 11 14 0 20 17 21 15 28 22 8 5 11 10 20 3 16 16 25 23 5 7 2421 22 23 16 4 23 26 2 4 25 5 7 29 98 29 12 27 26 2 29 26 10 18 18 6 28 0 4 17 12 75 6 19 0 28 3 19 3 1 1 1 2 (a) After 0 iterations (b) After 1,000 iter. (c) After 3,000 iter. (d) After 5,000 iter. Figure 13: A 1-ary tree, i.e., a list topology, learns a sphere distribution. 4.1.4 Multidimensional Data Points The well known Iris dataset was chosen for showing the power of our scheme in a scenario when the dimensionality is increased. This data set gives the measurements (in centimeters) of the variables which are the sepal length, sepal width, petal length and petal width, respectively, for 50 flowers from each of 3 species of the iris family. The species are the Iris Setosa, Versicolor, and Virginica. In this set of experiments, the Iris data set was learned under three different configurations, using a fixed schedule for the learning rate and radius but with a distinct tree configuration. The results of the experiments are depicted in Figure 14 and involve a complete binary tree of depth 3, 4 and 5, respectively. Taking into 26 account that the dataset possesses a high dimensionality, we present the projection in the 2-dimensional space to facilitate the visualization. We also removed the labels from the nodes in Figure 14c to improve understandability. (a) Using 7 nodes. (b) Using 15 nodes. (c) Using 31 nodes. Figure 14: Three different experiments where the TTOCONROT effectively captures the fundamental structure of the iris dataset (2-dimensional projection of the data is shown). The experiment utilizes a underlying tree topology of a complete binary tree with different levels of depth. By this we attempt to show examples of how exactly the same parameters of the TTOCONROT, can be utilized to learn the structure from data belonging to the 2-dimensional, 3-dimensional and also 4-dimensional spaces. After executing the TTO-SOM, each of the main branches of the tree were migrated towards the center of mass of the cloud of points in the hyper-space belonging to each of the three categories of flowers, respectively. Since the TTOCONROT is an unsupervised learning algorithm, it performs learning without knowing the true labels of the samples. However, when these labels are available, one can use them to evaluate the quality of the tree. To do so, each sample is assigned to its closest neuron, and tagging the neuron with the class which is most frequent. Table 1 presents the evaluation for the tree in Figure 14a. Assigned to neuron → Iris-setosa Iris-versicolor Iris-virginica 1 0 0 12 2 0 0 22 3 0 20 0 4 0 7 0 5 0 20 1 6 50 0 0 7 0 3 15 Table 1: “Cluster to class” evaluation for the tree in Figure 14a. Using the simple voting scheme explained above, it is possible to see from Table 1, that only 4 instances are incorrectly classified, i.e., 97.3% of the instances are correctly classified. Additionally, observe that node 6 contains all the 50 instances corresponding to the class Iris-setosa. It is well known that the Iris-setosa class is linearly separable from the other two classes, and our algorithm was able to discover this without providing it with the labels. We find this result quite fascinating! The experimental results shown in Table 1, not only demonstrate the potential capabilities of the TTOCONROT for performing clustering, but also suggest the possibilities of using it for pattern classification. According to [23], there are several reasons for performing pattern classification using an unsupervised approach. We are currently investigating such a classification strategy. 27 4.2 Skeletonization In general, the main objective of skeletonization consists of generating a simpler representation of the shape of an object. The authors of [44] refer to skeletonization in the plane as the process by which a 2-dimensional shape is transformed into a 1-dimensional one, similar to a “stick” figure. The applications of skeletonization are diverse, including the fields of Computer Vision and Pattern Recognition. As explained in [8], the traditional methods for skeletonization assume the connectivity of the data points and when this is not the case, more sophisticated methods are required. Previous efforts involving SOM variants to achieve skeletonization has been proposed [8, 19, 53]. We remark that the TTOSOM [8] is the only one which uses a tree-based structure. The TTOSOM assumed that the shape of the object is not known a priori. Rather, this is learned by accessing a single point of the entire shape at any time instant. Our results reported in [8] confirm that this is actually possible, and we now focus on how the conditional rotations will affect such a skeletonization. Figure 15 shows how the TTOCONROT learned the skeleton of different objects in the 2-dimensional and the 3-dimensional domain. In all the cases the same schedule of parameters were used, and only the number of neurons employed was chosen proportionally to the number of data points contained in the respective data sets. It is important to remark that we did not invoke any post-processing of the edges, e.g., minimum spanning tree, and that the skeleton observed was exactly what our BSTSOM learned. Firstly, Figures 15a-15d illustrate the shapes of the silhouette of a human, a rhinoceros, a 3d representation of a head, and a 3d representation of a woman. The figures also show the trees learned from the respective data sets. Additionally figures 15e-15h display only the data points, which in our opinion are capable of representing the fundamental structure of the four objects in a 1-dimensional way effectively. As a final comment, we stress that all the shapes employed in the experiments involve the learning of the “external” structure of the objects. For the case of solid objects, if the internal data points are also provided, the TTOCONROT is able to give an approximation of the so-called endo-skeleton, i.e., a representation in which the skeleton is built inside the solid object. 4.3 Theoretical Analysis According to Kiviluoto [34], there are three different criteria for evaluating the quality of a map. The first criterion indicates how continuous the mapping is, implying that input signals that are close (in the input space) should be mapped to codebooks that are close in the output space as well. A second criterion involves the resolution of the mapping. Maps with high resolution possess the additional property that input signals that are distant in the input space should be represented by distant codebooks in the output space. A third criterion imposed on the accuracy of the mapping is aimed to reflect the probability distribution of the input set. There exist a variety of measures for quantifying the quality of the topology preservation [5]. The author of [49] surveys a number of relevant measures for the quality of maps, and these include the Quantization Error, the Topographic Product [11], the Topographic Error [34] and the Trustworthiness and Neighborhood Preservation [55]. Although we are currently investigating [6] how the quality of any tree-based SOM (not just our scheme) can be quantified using these metrics. The following arguments are pertinent. 28 (a) (b) (c) (d) (e) (f) (g) (h) Figure 15: TTOCONROT effectively captures the fundamental structure of four objects in a 1-dimensional way. Figures 15a-15d show the silhouette of a human, a rhinoceros, a 3d representation of a head, and a 3d representation of a woman, as well as the respective trees learned. Figures 15e-15h show only the respective data points. The ordering of the weights (with respect to the position) of the neurons of the SOM has been proved for unidimensional topologies [17, 36, 51]. Extending these results to higher dimensional configurations or topologies leads to numerous unresolved problems. First of all, the question of what one means by “ordering” in higher dimensional spaces has to be defined. Further, the issue of the “absorbing” nature of the “ordered state” is open. Budinich, in [14], explains intuitively the problems related to the ordering of neurons in higher dimensional configurations. Huang et al. [29] introduce a definition of the ordering and show that even though the position of the codebook vectors of the SOM have been ordered, there is still the possibility that a sequence of stimuli will cause their disarrangement. Some statistical indexes of correlation between the measures of the weights and distances of the related positions have been introduced in [10]. With regard to the topographic product, the authors of [11] have shown the power of the metric by applying it on different artificial and real-world data sets, and also compared it with different measures to quantify the topology [10]. Their study concentrates on the traditional SOM, implying that the topologies evaluated were of a “linear” nature, with the consequential extension to 2-dimensions and 3-dimensions by means of grids only. In [28], Haykin mention that the Topographic Product may be employed to compare the quality of different maps, even when these maps possess different dimensionality. However, he also noted that this measurement is only possible when the dimensionality of the topological structure is the same as the dimensionality of the feature space. Further, tree-like topologies were not considered in their study. To be more precise, most of the effort towards determining the concept of topology preservation for dimensions greater than unity are specifically focused on the SOM [11, 17, 36, 14, 29, 10], and do not define how a treelike topology should be measured nor how to define the order in topologies which are not grid-based. Thus, we believe that even the tools to analyze the TTOCONROT are currently not available. The experimental 29 results obtained in our paper, suggest that the TTOCONROT is able to train the NN so as to preserve the stimuli. However, in order to quantify the quality of this topology, the matter of defining a concept of ordering on tree-based structure has yet to be resolved. Although this issue is of great interest to us, this rather ambitious task lies beyond the scope of our present manuscript. 5 Conclusions and Discussions 5.1 Concluding Remarks In this paper, we have proposed a novel integration between the areas of Adaptive Data Structures (ADSs) and the Self-Organizing Maps (SOMs). In particular we have shown how a tree-based SOM can be adaptively transformed by the employment of an underlying Binary Search Tree (BST) structure and subsequently, restructured using rotations that are performed conditionally. These rotations on the nodes of the tree are local, can be done in constant time, and performed so as to decrease the Weighted Path Length (WPL) of the entire tree. One of the main advantages of the algorithm, is that the user does not need to have a priori knowledge about the topology of the input data set. Instead, our proposed method, namely the TTOSOM with Conditional Rotations (TTOCONROT), infers the topological properties of the stochastic distribution, and at the same time, attempt to build the best BST that represents the data set. Incorporating the data structure’s constraints in this ways has not being achieved by any of the related approaches included in the state-of-the-art. Our premise is that regions of the hyper-space that are accessed more often should be promoted to preferential spots in the tree representation, which yields to an improved stochastic representation. As our experimental results suggest, the TTOCONROT tree is indeed able to absorb the stochastic properties of the input manifold. It is also possible to obtain a tree configuration that can learn both, the stochastic properties in terms of access probabilities and at the same time preserve the topological properties in terms of its skeletal structure. 5.2 Discussions and Future Work As explained in Section 4.3, the work associated with measuring the topology preservation of the SOM, including the proof of its convergence for the unidimensional case, has been performed for the traditional SOM only. The questions are unanswered for how a tree-like topology should be measured, and for defining the order in topologies which are not grid-based. Thus, we believe that even the tools for formally analyzing the TTOCONROT are currently not available. The experimental results obtained in our paper, suggest that the TTOCONROT is able to train the Neural Network (NN) so as to preserve the stimuli for which the concept of ordering on tree-based structures has yet to be resolved. Even though our principal goal was to obtain a more accurate representation of the stochastic distribution, our results also suggest that the special configuration of the tree obtained by the TTOCONROT can be further exploited so as to improve the time required for identifying the Best Matching Unit (BMU). The state-ofthe-art includes different strategies that expand trees by inserting nodes (which can be a single neuron or a 30 SOM-layer) that essentially are based on a Quantization Error (QE) measure. In some of these strategies, the error measure is based on the “hits”, i.e., the number of times a neuron has been selected as the BMU, which is, in principle, the same type of counter utilized by the Conditional Rotations (CONROT). Our strategy, TTOCONROT, which asymptotically positions frequently accessed nodes close to the root, might incorporate a module, that taking advantage of the “optimal” tree and the BMU counters already present in the TTOCONROT, splits the node at the root level. Thus, the splitting operation will occur without the necessity of searching for the node with the largest QE, under the assumption that a higher number of hits indicates that the degree of granularity of a particular neuron is lacking refinement. The concept of using the root of the tree for growing a tree-based SOM is itself pioneering, as far as we know, and the design and implementation details of this are currently being investigated. References [1] M. Adelson-Velskii and M. E. Landis. An algorithm for the organization of information. Sov. Math. DokL, 3:1259–1262, 1962. [2] M. U. Akram, S. Khalid, and S. A. Khan. Identification and classification of microaneurysms for early detection of diabetic retinopathy. Pattern Recognition, 46(1):107–116, 2013. [3] D. Alahakoon, S. K. Halgamuge, and B. Srinivasan. Dynamic self-organizing maps with controlled growth for knowledge discovery. IEEE Transactions on Neural Networks, 11(3):601–614, 2000. [4] B. Allen and I. Munro. Self-organizing binary search trees. J. ACM, 25(4):526–535, 1978. [5] E. Arsuaga Uriarte and F. Dı́az Martı́n. Topology preservation in SOM. International Journal of Applied Mathematics and Computer Sciences, 1(1):19–22, 2005. [6] C. A. Astudillo. Self Organizing Maps Constrained by Data Structures. PhD thesis, Carleton University, 2011. [7] C. A. Astudillo and B. J. Oommen. On using adaptive binary search trees to enhance self organizing maps. In A. Nicholson and X. Li, editors, 22nd Australasian Joint Conference on Artificial Intelligence (AI 2009), pages 199–209, 2009. [8] C. A. Astudillo and B. J. Oommen. Imposing tree-based topologies onto self organizing maps. Information Sciences, 181(18):3798–3815, 2011. [9] C. A. Astudillo and B. J. Oommen. On achieving semi-supervised pattern recognition by utilizing tree-based SOMs. Pattern Recognition, 46(1):293 – 304, 2013. [10] H. U. Bauer, M. Herrmann, and T. Villmann. Neural maps and topographic vector quantization. Neural Networks, 12(4-5):659 – 676, 1999. [11] H. U. Bauer and K. R. Pawelzik. Quantifying the neighborhood preservation of self-organizing feature maps. Neural Networks, 3(4):570–579, July 1992. 31 [12] J. R. Bitner. Heuristics that dynamically organize data structures. SIAM J. Comput., 8:82–110, 1979. [13] J. Blackmore. Visualizing high-dimensional structure with the incremental grid growing neural network. Master’s thesis, University of Texas at Austin, 1995. [14] M. Budinich. On the ordering conditions for self-organizing maps. Neural Computation, 7(2):284–289, 1995. [15] G. A. Carpenter and S. Grossberg. The art of adaptive pattern recognition by a self-organizing neural network. Computer, 21(3):77–88, 1988. [16] R. P. Cheetham, B. J. Oommen, and D. T. H. Ng. Adaptive structuring of binary search trees using conditional rotations. IEEE Trans. on Knowl. and Data Eng., 5(4):695–704, 1993. [17] P. L. Conti and L. De Giovanni. On the mathematical treatment of self organization: extension of some classical results. In Artificial Neural Networks - ICANN 1991, International Conference, volume 2, pages 1089–1812, 1991. [18] T. H. Cormen, C. E. Leiserson, R. L. Rivest, and C. Stein. Introduction to Algorithms, Second Edition. McGraw-Hill Science/Engineering/Math, July 2001. [19] A. Datta, S. M. Parui, and B. B. Chaudhuri. Skeletal shape extraction from dot patterns by selforganization. Pattern Recognition, 1996., Proceedings of the 13th International Conference on, 4:80–84 vol.4, Aug 1996. [20] D. Deng. Content-based image collection summarization and comparison using self-organizing maps. Pattern Recognition, 40(2):718 – 727, 2007. [21] M. Dittenbach, D. Merkl, and A. Rauber. The growing hierarchical self-organizing map. In Neural Networks, 2000. IJCNN 2000, Proceedings of the IEEE-INNS-ENNS International Joint Conference on, volume 6, pages 15–19 vol.6, 2000. [22] J. Dopazo and J. M. Carazo. Phylogenetic reconstruction using an unsupervised growing neural network that adopts the topology of a phylogenetic tree. Journal of Molecular Evolution, 44(2):226–233, February 1997. [23] R. Duda, P. E. Hart, and D. G. Stork. Pattern Classification (2nd Edition). Wiley-Interscience, 2000. [24] B. Fritzke. Growing Cell Structures – a self-organizing network for unsupervised and supervised learning. Neural Networks, 7(9):1441–1460, 1994. [25] B. Fritzke. Growing Grid - a self-organizing network with constant neighborhood range and adaptation strength. Neural Processing Letters, 2(5):9–13, 1995. [26] B. Fritzke. A growing neural gas network learns topologies. In G. Tesauro, D. S. Touretzky, and T. K. Leen, editors, Advances in Neural Information Processing Systems 7, pages 625–632, Cambridge MA, 1995. MIT Press. 32 [27] L. Guan. Self-organizing trees and forests: A powerful tool in pattern clustering and recognition. In Image Analysis and Recognition, Third International Conference, ICIAR 2006, Póvoa de Varzim, Portugal, September 18-20, 2006, Proceedings, Part I, pages I: 1–14, 2006. [28] S. Haykin. Neural Networks and Learning Machines. Prentice Hall, 3rd edition edition, 2008. [29] G. Huang, H. A. Babri, and H. Li. Ordering of self-organizing maps in multi-dimensional cases. Neural Computation, 10:19–24, 1998. [30] H.-G. Kang and D. Kim. Real-time multiple people tracking using competitive condensation. Pattern Recognition, 38(7):1045 – 1058, 2005. [31] H. Kaplan. Handbook of Data Structures and Applications, chapter 31: Persistent Data Structures, pages 31.1 – 31.26. Chapman and Hall/CRC, 2004. [32] S. Kaski, J. Kangas, and T. Kohonen. Bibliography of self-organizing map (SOM) papers: 1981–1997. Neural Computing Surveys, 1:102–350, 1998. [33] M. H. Khosravi and R. Safabakhsh. Human eye sclera detection and tracking using a modified timeadaptive self-organizing map. Pattern Recognition, 41(8):2571–2593, 2008. [34] K. Kiviluoto. Topology preservation in self-organizing maps. In P. IEEE Neural Networks Council, editor, Proceedings of International Conference on Neural Networks, ICNN’96, volume 1, pages 294–299, New Jersey, USA, 1996. [35] D. E. Knuth. The art of computer programming, volume 3: (2nd ed.) sorting and searching. Addison Wesley Longman Publishing Co., Inc., Redwood City, CA, USA, 1998. [36] T. Kohonen. Self-Organizing Maps. Springer-Verlag New York, Inc., Secaucus, NJ, USA, 1995. [37] P. Koikkalainen and E. Oja. Self-organizing hierarchical feature maps. IJCNN International Joint Conference on Neural Networks, 2:279–284, June 1990. [38] T. W. H. Lai. Efficient maintenance of binary search trees. PhD thesis, University of Waterloo, Waterloo, Ont., Canada, 1990. [39] Y. Liang, M. C. Fairhurst, and R. M. Guest. No titlea synthesised word approach to word retrieval in handwritten documents. Pattern Recognition, 45(12):4225–4236, 2012. [40] M. Martinetz and K. J. Schulten. A “neural-gas” network learns topologies. In in Proceedings of International Conference on Articial Neural Networks, volume I, pages 397–402, North-Holland, Amsterdam, 1991. [41] K. Mehlhorn. Dynamic binary search. SIAM Journal on Computing, 8(2):175–198, 1979. [42] D. Merkl, S. Hui-He, M. Dittenbach, and A. Rauber. Adaptive hierarchical incremental grid growing: An architecture for high-dimensional data visualization. In In Proceedings of the 4th Workshop on Self-Organizing Maps, Advances in Self-Organizing Maps, pages 293–298, 2003. 33 [43] R. Miikkulainen. Script recognition with hierarchical feature maps. Connection Science, 2(1&2):83–101, 1990. [44] R. L. Ogniewicz and O. Kübler. Hierarchic voronoi skeletons. Pattern Recognition, 28(3):343–359, 1995. [45] M. Oja, S. Kaski, and T. Kohonen. Bibliography of self-organizing map (SOM) papers: 1998-2001 addendum. Neural Computing Surveys, 3:1–156, 2003. [46] J. Pakkanen, J. Iivarinen, and E. Oja. The Evolving Tree — a novel self-organizing network for data analysis. Neural Processing Letters, 20(3):199–211, December 2004. [47] G. Peano. Sur une courbe, qui remplit toute une aire plane. Mathematische Annalen, 36(1):157–160, 1890. [48] M. Pöllä, T. Honkela, and T. Kohonen. Bibliography of self-organizing map (SOM) papers: 20022005 addendum. Technical Report TKK-ICS-R23, Helsinki University of Technology, Department of Information and Computer Science, Espoo, Finland, December 2009. [49] G. Pölzlbauer. Survey and comparison of quality measures for self-organizing maps. In Ján Paralič, Georg Pölzlbauer, and Andreas Rauber, editors, Proceedings of the Fifth Workshop on Data Analysis (WDA’04), pages 67–82, Sliezsky dom, Vysoké Tatry, Slovakia, June 24–27 2004. Elfa Academic Press. [50] A. Rauber, D. Merkl, and M. Dittenbach. The Growing Hierarchical Self-Organizing Map: exploratory analysis of high-dimensional data. IEEE Transactions on Neural Networks, 13(6):1331–1341, 2002. [51] R. Rojas. Neural networks: a systematic introduction. Springer-Verlag New York, Inc., New York, NY, USA, 1996. [52] E. V. Samsonova, J. N. Kok, and A. P. IJzerman. Treesom: Cluster analysis in the self-organizing map. Neural Networks, 19(6–7):935 – 949, 2006. Advances in Self Organising Maps - WSOM’05. [53] R. Singh, V. Cherkassky, and N. Papanikolopoulos. Self-Organizing Maps for the skeletonization of sparse shapes. Neural Networks, IEEE Transactions on, 11(1):241–248, Jan 2000. [54] D. D. Sleator and R. E. Tarjan. Self-adjusting binary search trees. J. ACM, 32(3):652–686, 1985. [55] J. Venna and S. Kaski. Neighborhood preservation in nonlinear projection methods: An experimental study. In Georg Dorffner, Horst Bischof, and Kurt Hornik, editors, ICANN, volume 2130 of Lecture Notes in Computer Science, pages 485–491. Springer, 2001. [56] K. C. Yao, M. Mignotte, C. Collet, P. Galerne, and G. Burel. Unsupervised segmentation using a selforganizing map and a noise model estimation in sonar imagery. Pattern Recognition, 33(9):1575 – 1584, 2000. 34
9 (cs.NE)
Robust Satisfaction of Temporal Logic Specifications via Reinforcement Learning arXiv:1510.06460v1 [cs.SY] 22 Oct 2015 Austin Jones1 , Derya Aksaray2 , Zhaodan Kong3 , Mac Schwager4 , and Calin Belta2,5 Abstract— We consider the problem of steering a system with unknown, stochastic dynamics to satisfy a rich, temporallylayered task given as a signal temporal logic formula. We represent the system as a Markov decision process in which the states are built from a partition of the statespace and the transition probabilities are unknown. We present provably convergent reinforcement learning algorithms to maximize the probability of satisfying a given formula and to maximize the average expected robustness, i.e., a measure of how strongly the formula is satisfied. We demonstrate via a pair of robot navigation simulation case studies that reinforcement learning with robustness maximization performs better than probability maximization in terms of both probability of satisfaction and expected robustness. I. I NTRODUCTION We consider the problem of controlling a system with unknown, stochastic dynamics, i.e., a “black box”, to achieve a complex, time-sensitive task. An example is controlling a noisy aerial vehicle with partially known dynamics to visit a pre-specified set of regions in some desired order while avoiding hazardous areas. We consider tasks given as temporal logic (TL) formulae [2], an extension of first order Boolean logic that can be used to reason about how the state of a system evolves over time. When a stochastic dynamical model is known, there exist algorithms to find control policies for maximizing the probability of achieving a given TL specification [18], [17], [23], [13] by planning over stochastic abstractions [12], [1], [17]. However, only a handful of papers have considered the problem of enforcing TL specifications to a system with unknown dynamics. Passive [3] and active [21], [9] reinforcement learning has been used to find a policy that maximizes the probability of satisfying a given linear temporal logic formula. In this paper, in contrast to the above works on reinforcement learning which use propositional temporal logic, we use signal temporal logic (STL), a rich predicate logic that can be used to describe tasks involving bounds on physical parameters and time intervals [7]. An example of such a *This work was partially supported at Boston University by ONR grant number N00014-14-1-0554 and by the NSF under grant numbers NRI1426907, CMMI-1400167, and CNS-1035588. 1 Author is with Mechanical Engineering and Electrical Engineering, Georgia Institute of Technology, Atlanta, GA, USA. austinjones@gatech.edu 2 Authors are with Mechanical Engineering, Boston University, Boston, MA, USA. {cbelta,daksaray}@bu.edu 3 Author is with Mechanical and Aerospace Engineering, University of California Davis, Davis, CA, USA. zdkong@ucdavis.edu 4 Author is with Aeronautics and Astronautics, Stanford University, Stanford, CA, USA. schwager@stanford.edu 5 Author is with Systems Engineering, Boston University, Boston, MA, USA. property is “Within t1 seconds, a region in which y is less than π1 is reached, and regions in which y is larger than π2 are avoided for t2 seconds.” STL admits a continuous measure called robustness degree that quantifies how strongly a given sample path exhibits an STL property as a real number rather than just providing a yes or no answer [8], [7]. This measure enables the use of continuous optimization methods to solve inference (e.g., [10], [11], [14]) or formal synthesis problems (e.g., [20]) involving STL. One of the difficulties in solving problems with TL formulae is the history-dependence of their satisfaction. For instance, if the specification requires visiting region A before region B, whether or not the system should steer towards region B depends on whether or not it has previously visited region A. For linear temporal logic (LTL) formulae with time-abstract semantics, this history-dependence can be broken by translating the formula to a deterministic Rabin automaton (DRA), a model that automatically takes care of the history-dependent “book-keeping” [4], [21]. In the case of STL, such a construction is difficult due to the timebounded semantics. We circumvent this problem by defining a fragment of STL such that the progress towards satisfaction is checked with some finite number τ of state measurements. We thus define an MDP, called the τ-MDP whose states correspond to the τ-step history of the system. The inputs to the τ-MDP are a finite collection of control actions. We use a reinforcement learning strategy called Q-learning [24], in which a policy is constructed by taking actions, observing outcomes, and reinforcing actions that improve a given reward. Our algorithms either maximize the probability of satisfying a given STL formula, or maximize the expected robustness with respect to the given STL formula. These procedures provably converge to the optimal policy for each case. Furthermore, we propose that maximizing expected robustness is typically more effective than maximizing probability of satisfaction. We prove that in certain cases, the policy that maximizes expected robustness also maximizes the probability of satisfaction. However, if the given specification is not satisfiable, the probability maximization will return an arbitrary policy, while the robustness maximization will return a policy that gets as close to satisfying the policy as possible. Finally, we demonstrate through simulation case studies that the policy that maximizes expected robustness in some cases gives better performance in terms of both probability of satisfaction and expected robustness when fewer training episodes are available. II. S IGNAL T EMPORAL L OGIC (STL) STL is defined with respect to continuously valued signals. Let F (A, B) denote the set of mappings from A to B and define a signal as a member of F (N, Rn ). For a signal s, we denote st as the value of s at time t and st1 :t2 as the sequence of values st1 st1 +1 . . . st2 . Moreover, we denote s[t] as the suffix 0 from time t, i.e., s[t] = {st |t 0 ≥ t}. In this paper, the desired mission specification is described by an STL fragment with the following syntax : φ ψ := F[0,T ] ψ|G[0,T ] ψ, := f (s) ≤ d|¬ϕ|ϕ1 ∧ ϕ2 |ϕ1U[a,b) ϕ2 , (1) where T is a finite time bound, φ , ψ, and ϕ are STL formulae, a and b are non-negative real-valued constants, and f (s) < d is a predicate where s is a signal, f ∈ F (Rn , R) is a function, and d ∈ R is a constant. The Boolean operators ¬ and ∧ are negation (“not”) and conjunction (“and”), respectively. The other Boolean operators are defined as usual. The temporal operators F, G, and U stand for “Finally (eventually)” , “Globally (always)”, and “Until”, respectively. Note that in this paper, we use a discrete-time version of STL rather than the typical continuous-time formulation. The semantics of STL is recursively defined as s[t] |= ( f (s) < d) s[t] |= φ1 ∧ φ2 s[t] |= φ1 ∨ φ2 s[t] |= G[a,b) φ iff iff iff iff s[t] |= F[a,b) φ iff s[t] |= φ1U[a,b) φ2 iff f (st ) < d s[t] |= φ1 and s[t] |= φ2 s[t] |= φ1 or s[t] |= φ2 s[t 0 ] |= φ ∀t 0 ∈ [t + a,t + b) ∃t 0 ∈ [t + a,t + b) s.t. s[t 0 ] |= φ ∃t 0 ∈ [t + a,t + b) s.t. s[t 00 ] |= φ1 ∀t 00 ∈ [t,t 0 ) and s[t 0 ] |= φ2 . In plain English, F[a,b) φ means “within a and b time units in the future, φ is true,” G[a,b) φ means “for all times between a and b time units in the future φ is true,” and φ1U[a,b) φ2 means “There exists a time c between a and b time units in the future such that φ1 is true until c and φ2 is true at c.” STL is equipped with a robustness degree [8], [7] (also called “degree of satisfaction”) that quantifies how well a given signal s satisfies a given formula φ . The robustness is calculated recursively according to the quantitative semantics r(s, ( f (s) < d),t) r(s, φ1 ∧ φ2 ,t) r(s, φ1 ∨ φ2 ,t) r(s, G[a,b) φ ,t) = d − f (st )  = min r(s, φ1 ,t), r(s, φ2 ,t)  = max r(s, φ1 ,t), r(s, φ2 ,t) = min r(s, φ ,t 0 ) t 0 ∈[t+a,t+b) r(s, φ ,t 0 ),  r(s, φ1U[a,b) φ2 ,t) = supt 0 ∈[t+a,t+b] min r(φ2 , s,t 0 ),  inft 00 ∈[t,t 0 ] r(φ1 , s,t 00 ) . r(s, F[a,b) φ ,t) = Similar to [6], let hrz(φ ) denote the horizon length of an STL formula φ . The horizon length is the required number of samples to resolve any (future or past) requirements of φ . The horizon length can be computed recursively as hrz(p) hrz(¬φ ) hrz(φ1 ∨ φ2 ) hrz(φ1 ∧ φ2 ) hrz(φ1U[a,b] φ2 ) = 0, = hrz(φ ), = max{hrz(φ1 ), hrz(φ2 )}, = max{hrz(φ1 ), hrz(φ2 )}, = max{hrz(φ1 ) + b − 1, hrz(φ2 ) + b}, (2) where φ , φ1 , φ2 are STL formulae. Example 1: Consider the robot navigation problem illustrated in Figure 1(a). The specification is “Visit Regions A or B and visit Regions C or D every 4 time unitsalong a mission T horizon of 100 units.” Let s(t) = x(t) y(t) , where x and y are the x− and y− components of the signal s. This task can be formulated in STL as φ= G[0,100)  F[0,4) ψ= ∧F[0,4) ψ (x > 2 ∧ x < 3 ∧ y > 2 ∧ y < 3)  ∨(x > 4 ∧ x < 5 ∧ y > 4 ∧ y < 5) (x > 2 ∧ x < 3 ∧ y > 4 ∧ y < 5)   ∨(x > 4 ∧ x < 5 ∧ y > 2 ∧ y < 3) . (3) Figure 1(a) shows two trajectories of the system beginning at the initial location of R and ending in region C that each satisfies the inner specification ψ given in (3). Note that s2 barely satisfies ψ, as it only slightly penetrates region A, while s1 appears to satisfy it strongly, as it passes through the center of region A and the center of region C. The robustness degrees confirm this: r(s1 , ψ) = 0.3 while r(s2 , ψ) = 0.05. The horizon length of the inner specification ψ of (3) is  hrz(ψ) = max 4 + max(0, 0), 4 + max(0, 0) = 4. III. M ODELS FOR R EINFORCEMENT L EARNING For a system with unknown and stochastic dynamics, a critical problem is how to synthesize control to achieve a desired behavior. A typical approach is to discretize the state and action spaces of the system and then use a reinforcement learning strategy, i.e., by learning how to take actions through trial and error interactions with an unknown environment [22]. In this section, we present models of systems that are amenable for reinforcement learning to enforce temporal logic specifications. We start with a discussion on the widely used LTL before introducing the particular model that we will use for reinforcement learning with STL. max t 0 ∈[t+a,t+b) We use r(s, φ ) to denote r(s, φ , 0). If r(s, φ ) is large and positive, then s would have to change by a large deviation in order to violate φ . Similarly, if r(s, φ ) is large in absolute value and negative, then s strongly violates φ . A. Reinforcement Learning with LTL One approach to the problem of enforcing LTL satisfaction in a stochastic system is to partition the statespace and design control primitives that can (nominally) drive the system from one region to another. These controllers, the stochastic dynamical model of the system, and the quotient obtained from the partition are used to construct a Markob decision process (MDP), called a bounded parameter MDP or BMDP, whose transition probabilities are interval-valued [1]. These BMDPs can then be composed with a DRA constructed from a given LTL formula to form a product BMDP. Dynamic programming (DP) can then be applied over this product MDP to generate a policy that maximizes the probability of satisfaction. Other approaches to this problem include aggregating the states of a given quotient until an MDP can be constructed such that the transition probability can be considered constant (with bounded error) [16]. The optimal policy can be computed over the resulting MDP using DP [15] or approximate DP, e.g., actor-critic methods [5]. Thus, even when the stochastic dynamics of a system are known and the logic that encodes constraints has timeabstract semantics, the problem of constructing an abstraction of the system that is amenable to control policy synthesis is difficult and computationally intensive. Reinforcement learning methods for enforcing LTL constraints make the assumption that the underlying model under control is an MDP [3], [21], [9]. Implicitly, these procedures compute a frequentist approximation of the transition probabilities that asymptotically approaches the true (unknown) value as the number of observed sample paths increases. Since this algorithm doesn’t explicitly rely on any a priori knowledge of the transition probability, it could be applied to an abstraction of a continuous-space system that is built from a propositionpreserving partition. In this case, the uncertainty on the motion described by intervals in the BMDP that is reduced via computation would instead be described by complete ignorance that is reduced via learning. The resulting policy would map regions of the statespace to discrete actions that will optimally drive the real-valued state of the system to satisfy the given LTL specification. Different partitions will result in different policies. In the next section, we extend the above observation to derive a discrete model that is amenable for reinforcement learning for STL formulae. B. Reinforcement learning with STL: τ-MDP In order to reduce the search space of the problem, we partition the statespace of the system to form the quotient graph G = (Σ, E), where Σ is a set of discrete states corresponding to the regions of the statespace and E corresponds to the set of edges. An edge between two states σ and σ 0 exists in E if and only if σ and σ 0 are neighbors (share a boundary) in the partition. In our case, since STL has time-bounded semantics, we cannot use an automaton with a time-abstract acceptance condition (e.g., a DRA) to check its satisfaction. In general, whether or not a given trajectory s0:T satisfies an STL formula would be determined by directly using the qualitative semantics. The STL fragment (1) consists of a sub-formula ψ with horizon length hrz(ψ) = τ that is modified by either a F[0,T ) or G[0,T ) temporal operator. This means that in order to update at time t whether or not the given formula φ has been satisfied or violated, we can use the τ previous state values st−τ+1:t For this reason, we choose to learn policies over an MDP with finite memory, called a τ-MDP, whose states correspond to sequences of length τ of regions in the defined partition. Example 1 (cont’d): Let the robot evolve according to the discrete-time Dubins dynamics xt+1 = xt + vδ t cos θ t yt+1 = yt + vδ t sin θ t , (4) where xt and yt are the x and y coordinates of the robot at time t, v is its forward speed, δ t is a time interval, and the robot’s orientation is given by θ t . The control primitives in this case are given by Act = {up, down, le f t, right} which correspond to the directions on the grid. Each (noisy) control primitive induces a distribution with support θdes ± ∆θ , where θdes is the orientation where the robot is facing the desired cell. When a motion primitive is enacted, the robot rotates to an angle θ t drawn from the distribution and moves along that direction for δ t time units. The partition of the statespace and the induced quotient G are shown in Figures 1(b) and 1(c), respectively. A state σ(i, j) in the quotient (Figure 1(c)) represents the region in the partition of the statespace (Figure 1(b)) with the point (i, j) in the lower left hand corner. Definition 1: Given a quotient of a system G = (Σ, E) and a finite set of actions Act, a τ-Markov Decision Process (τMDP) is a tuple Mτ = hS , Act, Pi, where • S ⊆ (Σ ∪ ε)τ is the set of finite states, where ε is the empty string. Each state στ ∈ S corresponds to a τ−horizon (or shorter) path in G . Shorter paths of length n < τ (representing the case in which the system has not yet evolved for τ time steps) have ε prepended τ − n times. • P : S × Act × S → [0, 1] is a probabilistic transition relation. P(στ , a, στ0 ) can be positive only if the first τ − 1 states of στ0 are equal to the last τ − 1 states of στ and there exists an edge in G between the final state of στ and the final state of στ0 . We denote the state of the τ-MDP at time t as στt . Definition 2: Given a trajectory st−τ+1:t of the original system, we define its induced trace in the τ-MDP Mτ as Tr(st−τ+1:t ) = σ t−τ+1:t = στt . That is, στt corresponds to the previous τ regions of the statespace that the state has resided in from time t − τ + 1 to time t. The construction of a τ-MDP from a given quotient and set of actions is straightforward. The details are omitted due to length constraints. We make the following key assumptions on the quotient and the resulting τ-MDP: • The defined control actions Act will drive the system either to a point in the current region or to a point in a neighboring region of the partition, e.g.,no regions are “skipped”. • The transition relation P is Markovian. For every τ state στt , there exists a continuous set of sample paths {st−τ+1:t } whose traces could be that state. The dynamics of the underlying system produces an unknown distribution p(st−τ+1:t |Tr(st−τ+1:t ) = στt ). Since the robustness degree is a function of sample paths of length τ and an STL formula ψ, we can define a distribution p(r(st−τ+1:t , ψ)|Tr(st−τ+1:t ) = στt ). 6 s2 5 C 5 B 4 y (m) y (m) 6 s1 3 C B A D 4 3 A D 2 2 R 1 1 R 2 3 4 5 6 1 1 2 x (m) 3 4 5 6 x (m) (a) (b) (c) Fig. 1: (a) Example of robot navigation problem. (b) Partitioned space. (c) Subsection of the quotient. Example 1 (cont’d): Figure 2 shows a portion of the τMDP constructed from Figure 1. The states in M4 are labeled with the corresponding sample paths of length 4 in G . The green and blue σ ’s in the states in M4 correspond to green and blue regions from Figure 1. IV. P ROBLEM F ORMULATION In this paper, we address the following two problems. Problem 1 (Maximizing Probability of Satisfaction): Let Mτ be a τ-MDP as described in the previous section. Given an STL formula φ with syntax (1), find a policy ∗ ∈ F (S × N, Act) such that µmp ∗ µmp = arg max Prs0:T [s0:T |= φ ] (5) Problem 2 (Maximizing Average Robustness): Let Mτ be as defined in Problem 1. Given an STL formula φ with syntax ∗ ∈ F (S , Act) such that (1), find a policy µmr ∗ = µmr µ∈F (S ×N,Act) arg max Es0:T [r(s0:T , φ )] µ∈F (S ×N,Act) (6) ∗ . Furthermore, if φ same probability of satisfaction as µmp is not satisfiable, any arbitrary policy could be a solution to Problem 1, as all policies will result in a satisfaction probability of 0. If φ is unsatisfiable, Problem 2 yields a solution that attempts to get as close as possible to satisfying the formula, as the optimal solution will have an average robustness value that is least negative. The forms of the objective functions differ for the two different types of formula, φ = F[0,T ) ψ and φ = G[0,T ) ψ. Case 1: Consider an STL formula φ = F[0,T ) ψ. In this case, the objective function in (5) can be rewritten as Prs0:T [∃t = τ, . . . , T − τ s.t. st−τ+1:t |= ψ], (7) and the objective function in (6) can be rewritten as Es0:T [ max r(st−τ+1:t , ψ)]. t=τ,...,T −τ (8) Case 2: Now, consider an STL formula φ = G[0,T ) ψ. The objective function in (5) can be rewritten as Prs0:T [∀t = τ, . . . , T − τ, st−τ:t |= ψ], (9) and the objective function in (6) can be rewritten as Es0:T [ min t=τ,...,T −τ Fig. 2: Part of the τ-MDP constructed from the robot navigation MDP shown in Figure 1 Problems 1 and 2 are two alternate solutions to enforce a given STL specification. The policy found by Problem 1, ∗ , maximizes the chance that φ will be satisfied, while i.e. µmp ∗ , drives the system the policy found by Problem 2, i.e. µmr to satisfy φ as strongly as possible on average. Problems similar to (5) have already been considered in the literature (e.g., [9], [21]). However, Problem 2 is a novel formulation that provides some advantages over Problem 1. As we show ∗ achieves the in Section V, for some special systems, µmr r(st−τ+1:t , ψ)]. (10) V. M AXIMIZING E XPECTED ROBUSTNESS VS . M AXIMIZING P ROBABILITY OF S ATISFACTION Here, we demonstrate that the solution to (6) subsumes the solution to (5) for a certain class of systems. Due to space limitations, we only consider formulae of the type φ = F[0,t) ψ. Let Mτ = (Sτ , Pτ , Act) be a τ-MDP. For simplicity, we make the following assumption on Sτ . Assumption 1: For every state στ ∈ Sτ , either every trajectory st+τ−1:t whose trace is στ satisfies ψ, denoted στ |= ψ, or every trajectory that passes through the sequence of regions associated with στ does not satisfy ψ, denoted στ 6|= ψ. Assumption 1 can be enforced in practice during partitioning. We define the set A = {στ ∈ Sτ |στ |= ψ}. (11) Definition 3: The signed graph distance of a τ−state στi ∈ S to a set X ⊆ S is  l(στi , στj ) στi 6∈ X   min j σ ∈X τ (12) d(στi , X) = j i i   − j min l(στ , στ ) στ ∈ X στ ∈Sτ \X where l(στi , στj ) is the length of the shortest path from στi to στj . We also make the following two assumptions. Assumption 2: For any signal st−τ+1:t such that Tr(st−τ+1:t ) ∈ Sτ , let r(st−τ+1:t , ψ) be bounded from below by Rmin and from above by Rmax . Assumption 3: Let Dστ (δ ) = Pr[r(st:t+τ , ψ) > t:t+τ δ |Tr(s ) = στ ]. For any two states, d(στi , A) < d(στj , A) ⇒ Dστi (δ ) ≥ Dσ j (δ ) ∀δ ∈ [Rmin , Rmax ] τ (13) ∗ and µ ∗ over M as Now we define the policies µmp τ mr h i ∗ = µmp arg max Prστ0:T ∃t ∈ [0, T ] s.t. στt |= ψ (14) µ∈F (S ×N,Act) ∗ = µmr arg max Eστ0:T h µ∈F (S ×N,Act) i max r(στt , ψ) t=0,...,T (15) Proposition 1: If Assumptions 1,2, and 3 hold, then the ∗ maximizes the expected probability of satisfacpolicy µmr tion. Proof: Given any policy µ, its associated reachability probability can be defined as " # Prµ (στ ) = Prµ στ = arg min d(στ , A) . (16) στ0 ,...,στT −τ Let I(.) be the indicator function such that I(B) is 1 if B is true and 0 if B is false. By definition, the expected probability of satisfaction for a given policy µ is   EPS(µ) = E I(∃0 < k < T − τ s.t. στk |= ψ) = ∑ Prµ (στ )I(στ ∈ A) (17) στ ∈Sτ = ∑ Prµ (στ ). στ ∈A Also, the expected robustness of policy µ becomes   ER(µ) = E max r(στk , ψ)  −τ  R k=0,...,T = 0Rmax Pr max r(στk , ψ) > x dx+ k=0,...,T −τ   R0 max r(στk , ψ) > x dx Rmin 1 − Pr  k=0,...T −τ  R = 0Rmax Pr max r(στk , ψ) > x dx−  k=0,...,T −τ k  R0 max r(στ , ψ) > x dx − Rmin Rmin Pr k=0,...,T −τ = R Rmax 0 R0 Rmin = ∑ Prµ (στ )Dστ (x)dx− στ ∈Sτ ∑ Prµ (στ )Dστ (x)dx − Rmin στ ∈Sτ ∑ Prµ (στ ) R Rmax ∑ Prµ (στ ) R0 στ ∈A στ 6∈A 0 Dστ (x)dx− Rmin Dστ (x)dx − Rmin . (18) Since Rmin is constant, maximizing (18) is equivalent to  R max ∑ Prµ (στ ) 0Rmax Dστ (x)dx µ στ ∈A  (19) R − ∑ Prµ (στ ) R0min Dστ (x)dx στ 6∈A Let p be the satisfaction probability such that p = ∑ Prµ (στ ). Then, we can rewrite the objective in (19) as στ ∈A   p ∑ Prµ στ = arg min d(στ , A)|στ ∈ A J(µ) = στ ∈A στ0 ,...,στT −τ R Rmax × 0 Dστ (x)dx  −(1 − p)Prµ στ = arg min d(στ , A)|στ στ0 ,...,στT −τ R × R0min Dστ (x)dx.  6∈ A (20) Now, ∂ J(µ) ∂p   ∑ Prµ στ = arg min d(στ , A)|στ ∈ A = στ ∈A στ0 ,...,στT −τ R Rmax × 0  Dστ (x)dx +Prµ στ = arg min d(στ , A)|στ στ0 ,...,στT −τ R0 × Rmin Dστ (x)dx  6∈ A > 0 (21) Thus, any policy µ increasing J(µ) also leads to an increase in p. Since increasing J(µ) is equivalent to increasing ER(µ), then we can conclude that the policy that maximizes the robustness also achieves the maximum satisfaction probability. VI. C ONTROL S YNTHESIS TO M AXIMIZE ROBUSTNESS A. Policy Generation through Q-Learning Since we do not know the dynamics of the system under control, we cannot a priori predict how a given control action will affect the evolution of the system and hence its progress towards satisfying/dissatisfying a given specification. Thus, we use the well-known paradigm of reinforcement learning to learn policies to solve Problems 1 and 2. In reinforcement learning, the system takes actions and records the rewards associated with the state-action pair. These rewards are then used to update a feedback policy that maximizes the expected gathered reward. In our cases, the rewards that we collect over Mτ are related to whether or not ψ is satisfied (Problem 1) or how robustly ψ is satisfied/violated (Problem 2). Our solutions to these problems rely on a Q-learning formulation [24]. Let R(στt , a) be the reward collected when action a ∈ Act was taken in state στt ∈ S . Define the function Q : S × Act × N as Q(στT −t , a,t) = R(στT −t , a)+  max E ∑Tl=T −t−1 R(στl , µl (στl )) = {µl ∈}Tl=T −t−1 R(στT −t , a) + max Q(στT −t+1 , a0 ,t − 1). a0 ∈Act (22) For an optimization problem with a cumulative objective function of the form ∑ R(στl , al ), (23) l=τ:T the optimal policy µ ∗ ∈ F (S , Act) can be found by µ ∗ (στt , T − t) = arg maxQ(στt , a, T − t). a∈Act (24) Applying the update rule C. Convergence of Batch Q-learning Qt+1 (στt , at , T − t) = Given a formula of the form φ = F[0,T ) ψ and an objective of maximizing the expected robustness (Problem 2), we will show that applying Algorithm 1 converges to the optimal solution. The other three cases discussed in Section IV can be proven similarly. The following analysis is based on [19]. The optimal Q function derived from (8) is (1 − αt )Qt (στt , at , T − t)+ αt [R(στt , at ) + γ max Qt (στt+1 , a0 )] a0 ∈A (25) where 0 < γ < 1 will cause Qt converges to Q w.p. 1 as t goes to infinity [24]. B. Batch Q-learning We cannot reformulate Problems 1 and 2 into the form (23) (see Section IV). Thus, we propose an alternate Q−learning formulation, called batch Q-learning , to solve these problems. Instead of updating the Q-function after each action is taken, we wait until an entire episode s[0:T ) is completed before updating the Q-function. The batch Q-learning procedure is summarized in Algorithm 1. Algorithm 1 The Batch Q learning algorithm. function BatchQLearn(Sys,probType,Nep ,φ ) Q ← RandomInitialization µ ← InitializePolicy(Q) for n = 1 to Nep do s[0,T ) ←Simulate(Sys, µ) Q ← UpdateQFunction(Q,µ,s0:T ,φ ,probType) µ ← UpdatePolicy(µ, Q) return Q,µ Algorithm 2 Function used to update Q function used in Algorithm 1. function UpdateQFunction(Q,µ,s0:T ,φ ,γ,probType) for n = T − τ − 1 to τ do if probType is MaximumProbability then Qtmp (στn , µ(στn , T − n)) ← max(I(sn−τ+1:n |= φ ), γQtmp (στn+1 , µ(στn+1 , T − n − 1)) else Qtmp (στn , µ(στn , T − n)) ← max(r(sn−τ+1:n , φ ), γQtmp (στn+1 , µ(στn+1 , T − n − 1)) Qnew (στn , µ(στn , T − n) ← (1 − α)Qtmp (στn , µ(στn , T − n) +αQ(στn , µ(στn , T − n) return Qnew The Q function is initialized to random values and µ is computed from the initial Q values. Then, for Nep episodes, the system is simulated using µ. Randomization is used to encourage exploration of the policy space. The observed trajectory is then used to update the Q function according to Algorithm 2. The new value of the Q function is used to update the policy µ. For compactness, Algorithm 2 as written only covers the case φ = F[0,T ) ψ. The case in which φ = G[0,T ) ψ can be addressed similarly. Q∗ (στk , a, T − k) = ∑σ t+1 P(στt , a, σ t+1 ) max(r(στt , ψ), τ max γQ∗ (στt+1 , b, T − t − 1)). b∈Act (26) This gives the following convergence result. Proposition 2: The Q-learning rule given by Qk+1 (στt , at , T − t) = (1 − αk )Qk (στt , at , T − t) +αk max(r(στt , ψ), max γQk (στt+1 , b, T − t − 1)), b∈Act (27) converges to the optimal Q function (26) if the sequence ∞ ∞ 2 {αk }∞ k=0 is such that ∑k=0 αk = ∞ and ∑k=0 (αk ) < ∞. Proof: (Sketch) The proof of Proposition 2 relies primarily on Proposition 3. Once this is established, the rest of the proof varies only slightly from the presentation in [19]. Note that in this case, k ranges over the number of episodes and t ranges over the time coordinate of the signal. Proposition 3: The optimal Q-function given by (26) is a fixed point of the contraction mapping H where (Hq)(στt , a, T − t) = ∑σ t+1 P(στt , a, σ t+1 ) max(r(στt , ψ), τ γ max q(στt+1 , b, T − t − 1)). b∈Act (28) Proof: By (26), if H is a contraction mapping, then Q∗ is a fixed point of H. Consider = max ∑ P(στ , a, στ0 )(max(r(στ , ψ), ||Hq1 − Hq2 ||∞ στ ,a σ 0 τ γ max q1 (στ0 , b, T − t − 1)) b∈Act − max(r(στ , ψ), γ q2 (στ0 , b, T − t − 1)). b∈Act (29) Define q∗j (t) = max γq1 (στ0 , b,t). b∈Act (30) WOLOG let q∗1 (T − t − 1) > q∗2 (T − t − 1). Define R(στ0 ) = (max(r(στ , ψ), q∗1 (T − t − 1) − max(r(στ , ψ), q∗2 (T − t − 1)) (31) There exist 3 possibilities for the value of R(στ ). r(στ , ψ) > q∗1 (T − t − 1) > q∗2 (T − t − 1) . ⇒ R(στ0 ) = 0 (32a) q∗1 (T − t − 1) > r(στ , ψ) > q∗2 (T − t − 1) ⇒ R(στ0 ) = ||q∗1 (T − t − 1) − r||∞ < γ||q1 − q2 ||∞ (32b) q∗1 (T − t − 1) > q∗2 (T − t − 1) > r(στ , ψ) ⇒ R(στ0 ) < γ||q1 − q2 ||∞ . (32c) Trained Performance, µmp Trained Performance, µmr Trained Performance, µmp Trained Performance, µmr 80 80 80 80 60 60 60 60 40 20 20 0 0 40 0.1 0 0 0.2 0.3 0.4 Robustness Count 100 Count 100 Count 100 40 0.1 (a) 0 −1 0.2 0.3 0.4 Robustness −0.5 0 Robustness (b) 0 −1 0.5 (b) 5 5 4 4 4 4 3 3 3 3 y y y 5 2 2 2 2 1 1 1 1 0 0 0 0 0 0 2 x 3 4 5 1 (c) 2 x 3 4 5 (d) Thus, this means that R(στ0 ) ≤ γ||q1 − q2 ||∞ ∀στ0 . Hence, = maxστ ,a ∑στ0 P(στ , a, στ0 )R(στ0 ) ≤ maxστ ,a ∑στ0 P(στ , a, στ0 )γ||q1 − q2 ||∞ ≤ γ||q1 − q2 ||∞ . (33) Therefore, H is a contraction mapping. ||Hq1 − Hq2 ||∞ VII. C ASE S TUDY We implemented the batch-Q learning algorithm (Algorithm 1) and applied it to two case studies that adapt the robot navigation model from Example 1. For each case study, we solved Problems 1 and 2 and compared the performance of the resulting policies. All simulations were implemented in Matlab and performed on a PC with a 2.6 GHz processor and 7.8 GB RAM. A. Case Study 1: Reachability First, we consider a simple reachability problem. The given STL specification is φcs1 = F[0,20) (F[0,1) ϕblue ∧ G[1,4) ¬ϕblue ), 1 2 x 3 4 5 0 0 1 (c) Fig. 3: Comparison of Policies for Case Study 1. Histogram of robustness values for trained policies for solution to (a) Problem 1 and (b) Problem 2. Trajectory generated from policies for solution to (c) Problem 1 and (d) Problem 2. 0.5 Example Trajectory, µmr Example Trajectory, µmp 5 1 −0.5 0 Robustness (a) Example Trajectory, µmr Example Trajectory, µmp 40 20 20 y Count 100 2 x 3 4 5 (d) Fig. 4: Comparison of Policies for Case Study 2.. The subplots have the same meaning as in Figure 3. generated from the system simulated using each of the trained policies after learning has completed, i.e. without the randomization that is used during the learning phase. Note that both trained policies satisfied the specification with probability 1. The performance of the two algorithms are very similar, as the mean robustness is 0.2287 with standard deviation 0.1020 for probability maximization and 0.2617 and 0.1004,resp., for robustness maximization. In the second row, we see trajectories simulated by each of the trained policies. The similarity of the solutions in this case study is not surprising. If the state of the system is deep within A or B, then the probability that it will remain inside that region in the next 3 time steps (satisfy φ ) is higher than if it is at the edge of the region. Trajectories that remain deeper in the interior of region A or B also have a high robustness value. Thus, for this particular problem, there is an inherent coupling between the policies that satisfy the formula with high probability and those that satisfy the formula as robustly as possible on average. B. Case Study 2: Repeated Satisfaction (34) where ϕblue is the STL subformula corresponding to being in a blue region. In plain English, (34) can be stated as “Within 20 time units, reach a blue region and then don’t revisit a blue region for 4 time units.” The results from applying Algorithm 1 are summarized in Figure 3. We used the parameters γ = 1, αt = 0.95, Nep = 300 and ε t = 0.995t , where ε t is the probability at iteration t of selecting an action at random 1 . Constructing the τ-MDP took 17.2s. Algorithm 1 took 161s to solve Problem 1 and 184s to solve Problem 2. The two approaches perform very similarly. In the first row, we show a histogram of the robustness of 500 trials 1 Although the conditions γ < 1 and ∞ α 2 < ∞ are technically required ∑k=0 k to prove convergence, in practice these conditions can be relaxed without having adverse effects on learning performance In this second case study, we look at a problem involving repeatedly satisfying a condition finitely many times. The specification of interest is φcs2 = G[0,12) (F[0,4) (ϕblue ) ∧ F[0,4) (ϕgreen )), (35) In plain English, (35) is “Ensure that every 4 time units over a 12 unit interval, a green region and a blue region is entered.” Results from this case study are shown in Figure 4. We used the same parameters as listed in Section VII-A, except Ne p = 1200,α = 0.4, and ε t = 0.9t . Constructing the τ-MDP took 16.5s. Applying Algorithm 1 took 257.7s for Problem 1 and 258.3s for Problem 2. In the first row, we see that the solution to Problem 1 satisfies the formula with probability 0 while the solution to Problem 2 satisfies the formula with probability 1. At first, this seems counterintuitive, as Proposition 2 indicates that a policy that maximizes probability would achieve a probability of satisfaction at least as high as the policy that maximizes the expected robustness. However, this is only guaranteed with an infinite number of learning trials. The performance in terms of robustness is obviously better for the robustness maximization (mean 0.1052, standard deviation 0.0742) than for the probability maximization (mean -0.6432, standard deviation 0.2081). In the second row, we see that the maximum robustness policy enforces convergence to a cycle between two regions, while the maximum probability policy deviates from this cycle. The discrepancy between the two solutions can be explained by what happens when trajectories that almost satisfy (35) occur. If a trajectory that almost oscillates between a blue and green region every four seconds is encountered when solving Problem 1, it collects 0 reward. On the other hand, when solving Problem 2, the policy that produces the almost oscillatory trajectory will be reinforced much more strongly, as the resulting robustness is less negative. However, since the robustness degree gives “partial credit” for trajectories that are close to satisfying the policy, the reinforcement learning algorithm performs a directed search to find policies that satisfy the formula. Since probability maximization gives no partial credit, the reinforcement learning algorithm is essentially performing a random search until it encounters a trajectory that satisfies the given formula. Therefore, if the family of policies that satisfy the formula with positive probability is small, it will on average take the Q-learning algorithm solving Problem 1 a longer time to converge to a solution that enforces formula satisfaction. VIII. C ONCLUSIONS AND F UTURE W ORK In this paper, we presented a new reinforcement learning paradigm to enforce temporal logic specifications when the dynamics of the system are a priori unknown. In contrast to existing works on this topic, we use a logic (signal temporal logic) whose formulation is directly related to a system’s statespace. We present a novel, convergent Q-learning algorithm that uses the robustness degree, a continuous measure of how well a trajectory satisfies a formula, to enforce the given specification. In certain cases, robustness maximization subsumes the established paradigm of probability maximization and, in certain cases, robustness maximization performs better in terms of both probability and robustness under partial training. Future research includes formally connecting our approach to abstractions of linear stochastic systems. R EFERENCES [1] A. Abate, A. D’Innocenzo, and M. Di Benedetto. Approximate abstractions of stochastic hybrid systems. Automatic Control, IEEE Transactions on, 56(11):2688–2694, Nov 2011. [2] C. Baier and J.-P. Katoen. Principles of model checking, volume 26202649. MIT press Cambridge, 2008. [3] T. Brazdil, K. Chatterjee, M. Chmelik, M.k, V. Forejt, J. Kretinsky, M. Kwiatkowska, D. Parker, and M. Ujma. Verification of markov decision processes using learning algorithms. In F. Cassez and J.-F. Raskin, editors, Automated Technology for Verification and Analysis, volume 8837 of Lecture Notes in Computer Science, pages 98–114. Springer International Publishing, 2014. [4] X. C. Ding, S. L. Smith, C. Belta, and D. Rus. Optimal control of markov decision processes with linear temporal logic constraints. IEEE Transactions on Automatic Control, 59(5):1244–1257, 2014. [5] X. C. Ding, J. Wang, M. Lahijanian, I. Paschalidis, and C. Belta. Temporal logic motion control using actor-critic methods. In Robotics and Automation (ICRA), 2012 IEEE International Conference on, pages 4687–4692, May 2012. [6] A. Dokhanchi, B. Hoxha, and G. Fainekos. On-line monitoring for temporal logic robustness. In Runtime Verification, pages 231–246. Springer, 2014. [7] A. Donzé and O. Maler. Robust satisfaction of temporal logic over real-valued signals. Formal Modeling and Analysis of Timed Systems, pages 92–106, 2010. [8] G. E. Fainekos and G. J. Pappas. Robustness of temporal logic specifications for continuous-time signals. Theoretical Computer Science, 410(42):4262–4291, 2009. [9] J. Fu and U. Topcu. Probably approximately correct MDP learning and control with temporal logic constraints. CoRR, abs/1404.7073, 2014. [10] X. Jin, A. Donze, J. V. Deshmukh, and S. A. Seshia. Mining requirements from closed-loop control models. In Proceedings of the 16th international conference on Hybrid systems: computation and contro, pages 43–52, 2013. [11] A. Jones, Z. Kong, and C. Belta. Anomaly detection in cyber-physical systems: A formal methods approach. In IEEE Conference on Decision and Control (CDC), pages 848–853, 2014. [12] A. Julius and G. Pappas. Approximations of stochastic hybrid systems. Automatic Control, IEEE Transactions on, 54(6):1193–1203, June 2009. [13] M. Kamgarpour, J. Ding, S. Summers, A. Abate, J. Lygeros, and C. Tomlin. Discrete time stochastic hybrid dynamic games: Verification and controller synthesis. In Proceedings of the 50th IEEE Conference on Decision and Control and European Control Conference, pages 6122–6127, 2011. [14] Z. Kong, A. Jones, A. Medina Ayala, E. Aydin Gol, and C. Belta. Temporal logic inference for classification and prediction from data. In Proceedings of the 17th international conference on Hybrid systems: computation and control, pages 273–282. ACM, 2014. [15] M. Lahijanian, S. Andersson, and C. Belta. Temporal logic motion planning and control with probabilistic satisfaction guarantees. Robotics, IEEE Transactions on, 28(2):396–409, April 2012. [16] M. Lahijanian, S. B. Andersson, and C. Belta. Approximate markovian abstractions for linear stochastic systems. In Proc. of the IEEE Conference on Decision and Control, pages 5966–5971, Maui, HI, USA, Dec. 2012. [17] M. Lahijanian, S. B. Andersson, and C. Belta. Formal verification and synthesis for discrete-time stochastic systems. IEEE Transactions on Automatic Control, 6(8):2031–2045, 2015. [18] R. Luna, M. Lahijanian, M. Moll, and L. E. Kavraki. Asymptotically optimal stochastic motion planning with temporal goals. In Workshop on the Algorithmic Foundations of Robotics, Istanbul, Turkey, 03/08/2014 2014. [19] F. S. Melo. Convergence of q-learning: a simple proof. http://users.isr.ist.utl.pt/ mtjspaan/readingGroup/ProofQlearning.pdf. [20] V. Raman, A. Donze, M. Maasoumy, R. M. Murray, A. SangiovanniVincentelli, and S. A. Seshia. Model predictive control with signal temporal logic specifications. In Proceedings of IEEE Conference on Decision and Control (CDC), pages 81–87, 2014. [21] D. Sadigh, E. S. Kim, S. Coogan, S. S. Sastry, and S. A. Seshia. A learning based approach to control synthesis of markov decision processes for linear temporal logic specifications. CoRR, abs/1409.5486, 2014. [22] R. S. Sutton and A. G. Barto. Reinforcement learning: An introduction, volume 1. MIT press Cambridge, 1998. [23] M. Svorenova, J. Kretı́nský, M. Chmelik, K. Chatterjee, I. Cerná, and C. Belta. Temporal logic control for stochastic linear systems using abstraction refinement of probabilistic games. In Hybrid Systems Computation and Control (HSCC) 2015, volume abs/1410.5387, 2015. (To appear). [24] J. N. Tsitsiklis. Asynchronous stochastic approximation and qlearning. Machine Learning, 16(3):185–202, 1994.
3 (cs.SY)
BATCHED QR AND SVD ALGORITHMS ON GPUS WITH APPLICATIONS IN HIERARCHICAL MATRIX COMPRESSION arXiv:1707.05141v1 [cs.MS] 13 Jul 2017 WAJIH HALIM BOUKARAM1 , GEORGE TURKIYYAH2 , HATEM LTAIEF1 , AND DAVID E. KEYES1 Abstract. We present high performance implementations of the QR and the singular value decomposition of a batch of small matrices hosted on the GPU with applications in the compression of hierarchical matrices. The one-sided Jacobi algorithm is used for its simplicity and inherent parallelism as a building block for the SVD of low rank blocks using randomized methods. We implement multiple kernels based on the level of the GPU memory hierarchy in which the matrices can reside and show substantial speedups against streamed cuSOLVER SVDs. The resulting batched routine is a key component of hierarchical matrix compression, opening up opportunities to perform H-matrix arithmetic efficiently on GPUs. 1. Introduction The singular value decomposition (SVD) is a factorization of a general m × n matrix A of the form A = U ΣV ∗ . U is an m × m orthonormal matrix whose columns Ui are called the left singular vectors. Σ is an m × n diagonal matrix whose diagonal entries σi are called the singular values and are sorted in decreasing order. V is an n × n orthonormal matrix whose columns Vi are called the right singular vectors. When m > n, we can compute a reduced form A = Û Σ̂V ∗ where Û is an m × n matrix and Σ̂ is an n × n diagonal matrix. One can easily obtain the full form from the reduced one by extending Û with (m − n) orthogonal vectors and Σ̂ with an (m − n) zero block row. Without any loss of generality, we will focus on the reduced SVD of real matrices in our discussions. The SVD of a matrix is a crucial component in many applications in signal processing and statistics as well as matrix compression, where truncating the (n − k) singular values that are smaller than some threshold gives us a rank-k approximation à of the matrix A. This matrix is the unique minimizer of the function fk (B) = ||A − B||F . In the context of hierarchical matrix operations, effective compression relies on the ability to perform the computation of large batches of independent SVDs of small matrices of low numerical rank. Randomized methods [1] are well suited for computing a truncated SVD of these types of matrices and are built on three computational kernels: the QR factorization, matrix-matrix multiplications and SVDs of smaller k × k matrices. Motivated by this task, we discuss the implementation of high performance batched QR and SVD kernels on the GPU, focusing on the more challenging SVD tasks. The remainder of this paper is organized as follows. Section 2 presents different algorithms used to compute the QR factorization and the SVD as well as some considerations when optimizing 1 Extreme Computing Research Center (ECRC), King Abdullah University of Science and Technology (KAUST), Thuwal 23955, Saudi Arabia. 2 Department of Computer Science, American University of Beirut (AUB), Beirut, Lebanon. E-mail addresses: wajihhalim.boukaram@kaust.edu.sa, gt02@aub.edu.lb, hatem.ltaief@kaust.edu.sa, david.keyes@kaust.edu.sa. 1 2 BATCHED QR AND SVD ALGORITHMS Algorithm 1 Householder QR procedure QR(A, Q, R) [Q, R] = [I, A] for i = 1 → A.n do v = house(R(i)) 5: R = (I − 2vv T )R 6: Q = Q(I − 2vv T ) 1: 2: 3: 4: for GPUs. Section 3 discusses the batched QR factorization and compares its performance with existing libraries. Sections 4, 5 and 6 discuss the various implementations of the SVD based on the level of the memory hierarchy in which the matrices can reside. Specifically, Section 4 describes the implementation for very small matrix sizes that can fit in registers, Section 5 describes the implementation for matrices that can reside in shared memory, and Section 6 describes the block Jacobi implementation for larger matrix sizes that must reside in global memory. Section 7 details the implementation of the batched randomized SVD routine. We then discuss some details of the application to hierarchical matrix compression in Section 8. We conclude and discuss future work in Section 9. 2. Background In this section we give a review of the most common algorithms used to compute the QR factorization and the SVD of a matrix as well as discuss some considerations when optimizing on the GPU. 2.1. QR Factorization The QR factorization decomposes an m × n matrix A into the product of an orthogonal m × m matrix Q and an upper triangular m × n matrix R [2]. We can also compute a reduced form of the decomposition where Q is an m × n matrix and R is n × n upper triangular. The most common QR algorithm is based on transforming A into an upper triangular matrix using a series of orthogonal transformations generated using Householder reflectors. Other algorithms such as the Gram-Schmidt or Modified Gram-Schmidt can produce the QR factorization by orthogonalizing a column with all previous columns; however, these methods are less stable than the Householder orthogonalization and the orthogonality of the resulting Q factor suffers with the condition number of the matrix. Another method is based on Givens rotations, where entries in the subdiagonal part of the matrix are zeroed out to form the triangular factor and the rotations are accumulated to form the orthogonal factor. This method is very stable and has more parallelism than the Householder method; however it is more expensive, doing about 50% more work, and it is more challenging to extract the parallelism efficiently on the GPU. For our implementation, we rely on the Householder method due to its numerical stability and simplicity. The method is described in pseudo-code in Algorithm 1. 2.2. SVD Algorithms Most implementations of the SVD are based on the two-phase approach popularized by Trefethen et al. [3], where the matrix A first undergoes bidiagonalization of the form A = QU BQTV where QU and QV are orthonormal matrices and B is a bidiagonal matrix. The matrix B is then diagonalized using some variant of the QR algorithm, the divide and conquer method or a combination of both to produce a decomposition B = UB ΣVBT . The complete SVD is then determined BATCHED QR AND SVD ALGORITHMS 3 as A = (QU UB )Σ(QV VB )T during the backward transformation. These methods require significant algorithmic and programming effort to become robust and efficient while still suffering from a loss of relative accuracy [4]. An alternative is the one-sided Jacobi method where all n(n−1)/2 pairs of columns are repeatedly orthogonalized in sweeps using plane rotations until all columns are mutually orthogonal. When the process converges (i.e., all columns are mutually orthogonal up to machine precision), the left singular vectors are the normalized columns of the modified matrix with the singular values as the norms of those columns. The right singular vectors can be computed either by accumulating the rotations or by solving a system of equations. Our application does not need the right vectors, so we omit the details of computing them. Algorithm 2 describes the one-sided Jacobi method. Since each pair of columns can be orthogonalized independently, the method is also easily parallelized. The simplicity and inherent parallelism of the method make it an attractive first choice for an implementation on the GPU. 2.3. GPU Optimization Considerations GPU kernels are launched by specifying a grid configuration which lets us organize threads into blocks and blocks into a grid. Launching a GPU kernel causes a short stall (as much as 10 microseconds) as the kernel is prepared for execution. This kernel launch overhead prevents kernels that complete their work faster than the overhead from executing in parallel, essentially serializing them. To overcome this limitation when processing small workloads, the work is batched into a single kernel call when possible [5, 6]. All operations can then be executed in parallel without incurring the kernel launch overhead, with the grid configuration used to determine thread work assignment. A warp is a group of threads (32 threads in current generation GPUs, such as the NVIDIA K40) within a block that executes a single instruction in lockstep, without requiring any explicit synchronization. The occupancy of a kernel tells us the ratio of active warps to the maximum number of warps that a multiprocessor can host. This metric is dependent on the amount of resources that a kernel uses, such as register and shared memory usage and kernel launch configuration, as well as the compute capability of the card ([7] for more details). While not a requirement for good performance [8], it is generally a good idea to aim for high occupancy. Memory on the GPU is organized into a hierarchy of memory spaces as shown in Figure 1. At the bottom, we have global memory which is accessible by all threads and is the most plentiful but the slowest memory. The next space of interest is the shared memory which is accessible only by threads within the same block and is configurable with the L1 cache to be at most 48KB per thread block on current generation GPUs. Shared memory is very fast and acts as a programmer controllable cache. Finally, we have the registers which are local to the threads. Registers are the fastest of all memory, but the total number of registers usable by a thread without performance implications is limited. If a kernel needs more registers than the limit, then registers are spilled to “local” memory, which is in the slow but cached global memory. Making good use of the faster memories and avoiding excessive Algorithm 2 One-sided Jacobi SVD while not converged do for each pair of columns Aij = [Ai , Aj ] do 3: G = ATij Aij 4: R = rot(G) 5: Aij = Aij R 1: 2: 4 BATCHED QR AND SVD ALGORITHMS Registers Shared Memory L1 Cache Read-Only Cache On-chip L2 Cache Global memory Off-chip Figure 1. The memory hierarchy of a modern GPU. accesses to the slower ones is key to good performance on the GPU. As such, it is common to use blocking techniques in many algorithms, where a block of data is brought in from global memory and processed in one of the faster memories. 2.4. Related Work Batched GPU routines for LU, Cholesky and QR factorizations have been developed in [5, 6, 9] using a block recursive approach which increases data reuse and leads to very good performance for relatively large matrix sizes. GPU routines optimized for computing the QR decomposition of very tall and skinny matrices are presented in [10] where they develop an efficient transpose matrix-vector computation that is employed with some minor changes in this work. GPU-CPU hybrid algorithms for batched SVD using Jacobi and bidiagonalization methods are introduced in [11] where pair generation for the Jacobi method and the solver phase of the bidiagonalization are handled on the CPU. The work in [12] employs the power method to construct a rank 1 approximation for 2D filters in convolutional neural networks. Routines to handle the SVD of many matrices on GPUs is presented in [13] where each thread within a warp computes the SVD of a single matrix. 3. Batched QR Decomposition In this section, we discuss implementation details of our batched QR kernel and compare it with other implementations from the MAGMA 2.2 [14] and CUBLAS 8 [15] libraries. 3.1. Implementation One benefit of the Householder algorithm is that the application of reflectors to the trailing matrix (line 5 of the algorithm) can be blocked together and expressed as a matrix-matrix multiplication (Level 3 BLAS) instead of multiple matrix-vector multiplications (Level 2 BLAS). The increased arithmetic intensity typically allows performance to improve when the trailing matrix is large. However, for small matrix blocks, the overhead of generating the blocked reflectors from their vector form as well as the lower performance of the matrix-matrix multiplication for small matrices hinder performance. We can obtain better performance by applying multiple reflectors in their vector form and performing the transpose matrix-vector multiplication efficiently within a thread block [10]. First, we perform the regular factorization on a column block P (called a panel). The entire panel is stored in registers, with each thread storing one row of the panel, and the transpose matrix-vector product is computed using a series of reductions using shared memory and warp shuffles [16] which BATCHED QR AND SVD ALGORITHMS Registers 5 ShueXOR Lane 1 Lane 1 Lane 2 Lane 2 Lane 3 Lane 3 Lane 4 Lane 4 Lane 5 Lane 5 Lane 6 Lane 6 Lane 7 Lane 7 Lane 8 Lane 8 Warp Figure 2. Left: matrix rows allocated to thread registers in a warp. Right: parallel warp reduction using shuffles within registers. allow threads within a warp to read each other’s registers. Figure 2 shows the data layout for a theoretical warp of size 8 with 4 columns in registers and a warp reduction using shuffles. Once we factor the panel, we can apply the reflectors to the trailing sub-matrix in a separate kernel that is optimized for performing the core matrix-vector product in the update. In this second kernel, we load both the factored panel P and a panel Mi of the trailing sub-matrix M to registers and apply the reflectors one at a time, updating the trailing panel in registers. Let us take an example of a 32 × 8 trailing panel Mi . For each reflector, we compute the matrix-vector product MiT v by flattening the 32×8 product into a reduction of a 256 vector in shared memory that has been padded to avoid bank conflicts. The reduction can then be serialized until it reaches a size of 32, where a partial reduction to a vector of size 8 can take place in 2 steps. This final vector is the product MiT v which can then be quickly applied to the registers storing Mi . This process is repeated for each trailing panel within the same kernel to maximize the use of the reflectors which have been stored in registers. Figure 3 shows one step of a panel factorization and the application of its reflectors to the trailing submatrix. Since threads are limited to 1024 per block on current architectures, we use the approach developed in [17] to factorize larger matrices. We first factorize panels up to the thread block limit in a single kernel call. The panels below the first are then factorized by first loading the triangular factor into shared memory and then proceeding with the panel factorization as before, taking the triangular portion into consideration when computing reflectors and updates. To keep occupancy up for the small matrices on devices where the resident block limit could be reached before the thread limit, we assign multiple operations to a single thread block. For a batch of N matrices of dimensions m × n, kernels can be launched using N/b thread blocks of size m × b, where each thread block handles b operations. 3.2. Performance Figures 4a and 4b show the performance of our batched QR for 1000 square and rectangular matrices with a panel width of 16, tuned for the P100 GPU. We compare against the vendor implementation in CUBLAS as well as the high performance library MAGMA. We can see that our proposed version performs well for rectangular matrices with column size of 32 and starts losing ground against MAGMA for the larger square matrix sizes where the blocked algorithm starts to 6 BATCHED QR AND SVD ALGORITHMS R R0 V P M V0 M0 Figure 3. One step of the QR factorization where a panel P is factored to produce a triangular factor R and reflectors V which are used to update the trailing submatrix M. Our QR DP MAGMA QR DP CUBLAS QR DP Our QR SP MAGMA QR SP CUBLAS QR SP Our QR DP MAGMA QR DP CUBLAS QR DP Our QR SP MAGMA QR SP CUBLAS QR SP 1,000 400 300 600 Gflop/s Gflop/s 800 400 200 100 200 0 0 5 2 6 2 7 2 Matrix Size 2 8 9 2 (a) Batched QR kernel performance for square matrices. 25 26 27 28 29 Matrix Rows 210 211 (b) Batched QR kernel performance for rectangular matrices with a fixed column size of 32. Figure 4. Comparing batched QR kernels for 1000 matrices of varying size on a P100 GPU in single and double precision. show its performance benefits. A nested implementation where our kernel can be used to factor relatively large panels in a blocked algorithm will likely show some additional performance improvements for the large square matrices, but we leave that as future work. 4. Register Memory One-Sided Jacobi In this section we will discuss the first batched SVD kernel where the matrix data is hosted in registers and analyze the performance of the resulting kernel. 4.1. Implementation In this implementation, to avoid repeated global memory accesses, we attempt to fit the matrix in register memory using the same layout as the panel in the QR factorization, i.e. one row per BATCHED QR AND SVD ALGORITHMS 0.35 DP Performance SP Performance 200 7 0.3 Occupancy Gflop/s 150 100 0.25 0.2 50 0.15 DP Occupancy SP Occupancy 0 0 5 10 15 20 Matrix Size 25 30 35 (a) Kernel performance in GFLOP/s and achieved occupancy. 0.1 0 5 10 15 20 Matrix Size 25 30 35 (b) The effect of increasing the matrix size on the occupancy of the register kernel. Figure 5. Performance of the batched register memory SVD on a P100 GPU for 1000 matrices of varying size in single and double precision arithmetics. thread; however, the number of registers that a thread uses has an impact on occupancy which can potentially lead to lower performance. In addition, once the register count exceeds the limit set by the GPU’s compute capability, the registers spill into “local” memory which resides in cached slow global memory. Since we store an entire matrix row in the registers of one thread, we use the serial one-sided Jacobi algorithm to compute the SVD where column pairs are processed by the threads one at a time. The bulk of the work lies in the computation of the Gram matrix G = ATij Aij (line 3 of Algorithm 2) and in the update of the columns (line 5). Since the Gram matrix is symmetric, this boils down to three dot products which are executed as parallel reductions within the warp using warp shuffles. The computation of the 2 × 2 rotation matrix as well as the convergence test is performed redundantly in each thread. Finally, the column update is done in parallel by each thread on its own register data. As with the QR kernel, we keep occupancy up for the smaller matrix sizes by assigning multiple SVD operations to a single block of threads with each operation assigned to a warp to avoid unnecessary synchronizations. 4.2. Performance We generate batches of 1000 test matrices with varying condition numbers using the latms LAPACK routine and calculate performance based on the total number of rotations needed for convergence. Figures 5a and 5b show the performance on a P100 GPU of the register-based batched SVD kernel and the effect increased register usage has on occupancy. Profiling the kernel, we see that the Gram matrix computation takes about 500 cycles, column rotations take about 240 cycles, and the redundantly computed convergence test and rotation matrices dominate at 1900 cycles. The fact that the redundant portion of the computation dominates means that it is preferable to assign as few threads as possible when processing column pairs. Due to the low occupancy for the larger matrix sizes and the register spills to local memory for matrices larger than 30, it is obvious that the register approach will not suffice for larger matrix sizes. This leads us to our next implementation based on the slower but more parallel-friendly shared memory. 6 8 5 3 1 8 7 6 4 2 3 1 2 8 5 7 6 4 1 2 4 8 3 5 7 6 Warp 4 4 Warp 3 2 Step 1: Warp 2 BATCHED QR AND SVD ALGORITHMS Warp 1 8 Step 5: 1 3 5 7 4 6 7 8 Step 2: Step 6: 2 1 3 5 6 7 5 8 Step 3: Step 7: 4 2 1 3 7 5 3 8 6 4 2 1 Step 4: Figure 6. Distribution of column pairs to warps at each step of a sweep. 5. Shared Memory One-Sided Jacobi While the register based SVD performs well for very small matrix sizes, we need a kernel that can handle larger sizes and maintain reasonably high occupancy. This leads us to building a kernel based on shared memory, the next level of the GPU memory hierarchy. This section discusses the implementation details of this kernel and analyze its performance when compared with the register kernel. 5.1. Implementation In this version, the matrix is stored entirely in shared memory, which is limited to at most 48 KB per thread block on current generation GPUs. Using the same thread assignment as the register based kernel would lead to very poor occupancy due to the high shared memory consumption, where potentially only a few warps will be active in a multiprocessor. Instead, we exploit the inherent parallelism of the one-sided Jacobi to assign a warp to a pair of columns, i.e., there are n/2 warps processing an m×n matrix stored in shared memory. There are a total of n(n−1)/2 pairs of columns, so we must generate all pairings in n − 1 steps, with each step processing n/2 pairs in parallel. There are many ways of generating these pairs, including round robin, odd-even, and ring ordering [18, 19]. We implement the round robin ordering using shared memory to keep track of the column indexes of the pairs with the first warp in the block responsible for updating the index list after each step. Figure 6 shows this ordering for a matrix with 8 columns. When the number of matrix rows exceeds the size of the warp, the thread-per-row assignment no longer allows us to use fast warp reductions, which would force us to use even more resources, as the reductions would now have to be done in shared memory. Instead, we assign multiple rows to a thread, serializing a portion of the reduction over those rows until warp reductions can be used. This follows our observation in Section 4.2 to assign as few threads as possible to process column pairs, frees up valuable resources and increases the overall performance of the reduction. Row padding is used to keep the rows at multiples of the warp size, and column padding is used to keep the number of columns even. Kernels can then be launched using 32 × n/2 threads to process each matrix. Figures 7a and 7b show examples of the thread allocation and reductions for a 8 × 8 matrix using a theoretical warp size of 4. BATCHED QR AND SVD ALGORITHMS 9 Shared Memory Serial Reduction ShuffleXOR Lane 1 Lane 1 Lane 2 Lane 2 Lane 3 Lane 3 Lane 4 Lane 4 Lane 1 Lane 2 Lane 1 Lane 3 Lane 2 Lane 4 Lane 3 Warp 1 Warp 2 Warp 3 Warp 4 (a) Matrix columns assigned in pairs to multiple warps and stored in shared memory. Lane 4 (b) Parallel reduction of a column of data in shared memory using register shuffles after an initial serial reduction step. Figure 7. Shared memory kernel implementation details. 5.2. Performance Figures 8a and 8b show the performance of the parallel shared SVD kernel compared to the serial register SVD kernel on a P100 GPU. We can see the improved growth in performance in the shared memory kernel due to the greater occupancy as well as the absence of any local memory transactions. Looking at the double precision occupancy, we notice two dips in occupancy at matrix sizes 22 and 32 as the number of resident blocks become limited by the registers/block limits of the device, dropping to 2 and then 1 resident blocks. Performance increases steadily from there as we increase the number of threads assigned to the operation until we reach a matrix size of 64 × 64 where we reach the block limit of 1024 threads. To handle larger sizes, we must use a blocked version of the algorithm or the randomized SVD as we see in Sections 6 and 7, respectively. 6. Global Memory One-Sided Block Jacobi When we can no longer store the entire matrix in shared memory, we have to operate on the matrix in the slower global memory. Instead of repeatedly reading and updating the columns one at a time, block algorithms that facilitate cache reuse have been developed [20, 21, 22]. The main benefit of the block Jacobi algorithm is its high degree of parallelism; however, since we implement a batched routine for independent operations, we will use the serial block Jacobi algorithm for individual matrices and rely on the parallelism of the batch processing. The parallel version, where multiple blocks are processed simultaneously, can still be used when the batch size is very small, but we will focus on the serial version. In this section we will discuss the implementation details for two global memory block Jacobi algorithms that differ only in the way block columns are orthogonalized and compare their performance with parallel streamed calls to the cuSOLVER 8 [23] library routines. 6.1. Gram Matrix Block Jacobi SVD The block Jacobi algorithm is very similar to the vector Algorithm 2, orthogonalizing pairs of blocks columns instead of vectors. The first method of orthogonalizing pairs of block columns is based (p) on the SVD of their Gram matrix. During the p-th sweep, each pair of m × k block columns Ai and 10 BATCHED QR AND SVD ALGORITHMS REG DP Occupancy REG SP Occupancy DP Register Kernel DP SMEM Kernel SP Register Kernel SP SMEM Kernel 0.6 Occupancy Gflop/s 600 SMEM DP Occupancy SMEM SP Occupancy 400 200 0.4 0.2 0 0 10 20 30 40 Matrix Size 50 0 60 (a) Shared memory kernel performance in GFLOPs/s compared to the register kernel. 10 20 30 40 Matrix Size 50 60 70 (b) Comparison of the occupancy achieved by the register and shared memory kernels. Figure 8. Performance of the batched shared memory SVD on a P100 GPU for 1000 matrices of varying size in single and double precision arithmetics. (p) Aj (p) (p) (p) T (p) (p) (p) T (p) Aij (p) singular vectors of Gij (or (p) Updating Ap+1 = Apij Uij ij is orthogonalized by forming a 2k × 2k Gram matrix Gij = [Ai Aj ] [Ai Aj ] = Aij and generating a block rotation matrix (p) Uij , computed as the left equivalently its eigenvectors, since it is symmetric positive definite). orthogonalizes the block columns, since we have T (p) T Ap+1 Ap+1 = Uij ij ij T (p) (p) T Apij Apij Uij = Uij (p) (p) Gij Uij = Λpij , (p) where Λpij is a diagonal matrix of the singular values of Gij . Orthogonalizing all pairs of block columns until the entire matrix is orthogonal will give us the left singular vectors as the normalized columns and the singular values as the corresponding column norms. If the right singular vectors are needed, we can accumulate the action of the block rotation matrices on the identity matrix. For our batched implementation, we use highly optimized batched syrk and gemm routines from MAGMA to compute G and to apply the block rotations, while the SVD is computed by our shared memory batched kernel. Since different matrices will converge in different numbers of sweeps, we keep track of the convergence of each operation l by computing the norm el of the off-diagonal entries of G scaled by its diagonal entries. While this term is an inexact approximation of the off-diagonal terms of the full matrix in each sweep, it is still a good indication of convergence and will cost us at most an extra cheap sweep, since the final sweep will not actually perform any rotations within the SVD of G. The entire batched operation will then converge when e = max el < , where  is our convergence tolerance. This gives us the Gram matrix path of the batched block Jacobi Algorithm 3 to compute the SVD of a batch of matrices in global memory. It is worth noting that the computation of the Gram matrix can be optimized by taking advantage of the special structure of G, but since the bulk of the computation is in the SVD of G, it will not result in any significant performance gains. 6.2. Direct Block Jacobi SVD The Gram matrix method is an indirect way of orthogonalizing block columns and may fail to converge if the matrix is very ill-conditioned. Ill-conditioned matrices can be handled by directly BATCHED QR AND SVD ALGORITHMS 11 Algorithm 3 Batched One-sided block Jacobi SVD 1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: while e >  do el = 0 for each pair of block columns Aij = [Ai , Aj ] do if method = GRAM then G = batchSyrk(Aij ) else [Aij , G] = batchQR(Aij ) el = max(el , scaledOffdiag(G)) U = batchSvd(G) Aij = batchGemm(Aij , U ) e = max(el ) orthogonalizing the columns using their SVD. Since the block columns are rectangular, we first compute their QR decomposition followed by the SVD of the triangular factor R. Overwriting the block column Apij by the orthogonal factor Q and multiplying it by the left singular vectors of R scaled by the singular values will give us the new block column Ap+1 ij :  T p p p pT Apij = Qpij Rij = Qpij Uij Σij Vijp = Ap+1 ij Vij . If the right singular vectors are needed, we can accumulate the action of Vijp on the identity matrix. For our batched implementation, we use the batch QR routine developed in Section 3 and gemm routines from MAGMA to multiply the orthogonal factor by the left singular vectors, while the SVD is computed by our shared memory batched kernel. The same convergence test used in the Gram matrix method can be used on the triangular factor, since the triangular factor should be close to a diagonal matrix if a pair of block columns are orthogonal. This gives us the direct path of the batched block Jacobi Algorithm 3 to compute the SVD of a batch of matrices in global memory. 6.3. Performance Figures 9a and 9a show the profiling of the different computational kernels involved in the batched block algorithms with a block width of 32, specifically percentages of total execution time for determining convergence and memory operations, matrix multiplications, QR decompositions and the SVD of the Gram matrix. For the Gram matrix approach, the SVD is the most costly phase, even for the larger operations, while the QR and SVD decompositions take almost the same time for the larger matrices in the direct approach. Figure 10a shows the performance of the batched block Jacobi SVD of 200 matrices using both methods and Figure 10b compares the performance of our batched SVD routine with a batched routine that uses the cuSOLVER SVD routine using 20 concurrent streams on a P100 GPU. Increasing the number of streams for cuSOLVER showed little to no performance benefits, highlighting the performance limitations of routines that are bound by kernel launch overhead. The matrices are generated randomly using the latms LAPACK routine with a condition number of 107 . The Gram matrix approach fails to converge in single precision for these types of matrices, whereas the direct approach always converges; however the Gram matrix approach performs better when it is applicable for the larger matrices due to the strong performance of the matrix-matrix multiplcations. The performance of the block algorithm can be improved by preprocessing the matrix using QR and LQ decompositions to decrease the number of sweeps required for convergence [24] as well as by adaptively selecting pairs of block columns based on the 12 BATCHED QR AND SVD ALGORITHMS 100 80 80 Misc. 40 GEMM SVD 60 Misc. 40 GEMM SVD 20 20 0 0 QR 96 128 160 192 224 256 288 320 352 384 416 448 480 512 60 % total time 100 96 128 160 192 224 256 288 320 352 384 416 448 480 512 % total time computed offdiagonal norms of their Gram matrices. These changes are beyond the scope of this paper and will be the focus of future work. Matrix size Matrix size (a) Gram Matrix batched block Jacobi SVD profile. (b) Direct batched block Jacobi SVD profile. Figure 9. Profile of the different phases of the block Jacobi SVD for 200 matrices of varying size on a P100 GPU in double precision. Single precision exhibits similar behavior. 7. Randomized SVD As mentioned in Section 1, we are often interested in a rank-k approximation of a matrix A ≈ Ũ S̃ Ṽ . We can compute this approximation by first determining the singular value decomposition of the full m × n matrix A and then truncating the n − k smallest singular values with their corresponding singular vectors; however, when the matrix has low numerical rank k, we can obtain the approximation using very fast randomization methods [1]. This section will discuss some details DP Gram DP Direct SP Direct 500 102 Time Gflop/s 101 400 100 Streamed DP CUSolver Streamed SP CUSolver Batched DP Direct Batched SP Direct Batched DP Gram 10−1 300 100 200 300 400 Matrix Size 500 (a) Batched block Jacobi SVD performance. 100 200 300 400 Matrix Size 500 (b) Comparison between streamed cuSOLVER and the batched block Jacobi. Figure 10. Batched block Jacobi performance for 200 matrices of varying size on a P100 GPU in single and double precision arithmetics. BATCHED QR AND SVD ALGORITHMS 13 Algorithm 4 Batched Randomized SVD 1: 2: 3: 4: 5: 6: 7: 8: 9: 10: procedure RSVD(A, k, p) [m, n] = size(A) Ω = Rand(n, k + p) Y = batchGemm(A, Ω) [Q, Ry ] = batchQR(Y ) B = batchGemm(QT , A) [QB , RB ] = batchQR(B T ) T [UR , S, VR ] = batchSvd(RB ) U = batchGemm(Q, UR ) V = batchGemm(QB , VR ) of the algorithm and compare its performance with the full SVD using our one-sided block Jacobi kernel. 7.1. Implementation When the singular values of a matrix decay rapidly, we can compute an approximate SVD using a simple two phase randomization method: (1) The first phase determines an approximate orthogonal basis Q for the columns of A ensuring that A ≈ QQT A. When the numerical rank k of A is low, we can be sure that Q has a small number of columns as well. In [1] we see that by drawing k + p sample vectors y = Aw from random input vectors w, we can obtain a reliable approximate basis for A which can then be orthogonalized. This boils down to computing a matrix Y = AΩ, where Ω is a n × (k + p) random Gaussian sampling matrix, and then computing the QR decomposition of Y = QRy , where Q is the desired approximate orthogonal basis. (2) The second phase uses the fact that A ≈ QQT A to compute a matrix B = QT A so that we now have A ≈ QB. Forming the SVD of B = UB SV T , we finalize our approximation A ≈ QUB SV T = U SV T . For the wide (k + p) × n matrix B, we can first compute a QR decomposition of its transpose, followed by the SVD of the upper triangular factor. Algorithm 4 shows that the core computations for the randomized method are matrix-matrix multiplications, QR decompositions, and the singular value decompositions of small matrices. Using the batched routines from the previous sections, it is straightforward to form the required randomized batched SVD. More robust randomized SVD algorithms would employ randomized subspace iteration methods to obtain a better basis Q for the columns of A and rely on these same core kernels, but will not be further discussed here. 7.2. Performance Figure 11 shows the profiling of the different kernels used in the randomized batched routine for determining the top 64 singular values and vectors of randomly generated low rank matrices using the latms LAPACK routine. The miscellaneous portion includes random number generation using the CURAND library’s default random number generator and a Gaussian distribution, batched transpose operations and memory operations. We can see that the performance of all kernels play almost equally important roles in the performance of the randomized routine as the matrix size grows while keeping the computed rank the same. Figure 12a shows the performance of the batched 14 BATCHED QR AND SVD ALGORITHMS randomized SVD of 200 operations and Figure 12b compares the runtimes of the direct block onesided Jacobi routine with the randomized SVD on a P100 GPU for the same set of matrices, showing that significant time savings can be achieved even for relatively small blocks. 100 % total time 80 60 Misc. 40 GEMM SVD QR 0 96 128 160 192 224 256 288 320 352 384 416 448 480 512 20 Matrix size Figure 11. Profile of the different phases of the batched randomized SVD for 200 matrices of varying size on a P100 GPU in double precision. Single precision exhibits similar behavior. 8. Application to Hierarchical Matrix Compression As an application of the batched kernels presented, we consider the problem of compressing/recompressing hierarchical matrices. This is a problem of significant importance for building hierarchical matrix algorithms and in fact was our primary motivation for the development of the batched kernels. Hierarchical matrices [25, 26, 27] have received substantial attention in recent years because of their ability to store and perform algebraic operations in near linear complexity rather than the O(n2 ) and O(n3 ) that regular dense matrices require. The effectiveness of hierarchical matrices comes from 101 DP Randomized SVD SP Randomized SVD 1,000 100 Time Gflop/s 800 600 DP Randomized SVD DP Direct Block SVD SP Randomized SVD SP Direct Block SVD 10−1 400 200 10−2 100 200 300 400 Matrix Size 500 (a) Batched randomized SVD performance. 100 200 300 400 Matrix Size 500 (b) Comparison between the batched block Jacobi and the batched randomized SVD. Figure 12. Batched randomized SVD performance for 200 matrices of varying size on a P100 GPU in single and double precision for the first 64 singular values and vectors. BATCHED QR AND SVD ALGORITHMS U11 15 2 A212 = U12 S12 U22 E12 T E22 U12 U22 E13 E23 E33 E43 U13 U23 U33 U43 (a) Basis tree U of an H2 -matrix. Leaf nodes are stored explicitly, whereas inner nodes are represented implicitly using the transfer matrices E. (b) Leaves of matrix tree for a simple hierarchical matrix. Red blocks represent dense leaves and green blocks are low rank leaves. Figure 13. The basis tree and matrix tree leaves of a simple H2 -matrix. the fact they can approximate a matrix by a (quad)-tree of blocks where many of the blocks in the off-diagonal regions have a rapidly decaying spectrum and can therefore be well-approximated by numerically low rank representations. It is these low rank representations, at different levels of the hierarchical tree, that reduce the memory footprint and operations complexity of the associated matrix algorithms. Hackbush [28] shows that many of the large dense matrices that appear in scientific computing, such as from the discretization of integral operators, Schur complements of discretized PDE operators, and covariance matrices, can be well approximated by these hierarchical representations. Reviewing and analyzing hierarchical matrix algorithms is beyond the scope of this paper. Here we focus on the narrow task of compressing hierarchical matrices. This compression task may be viewed as a generalization of the well-known compression (i.e., low rank approximation) of large dense matrices to the case of hierarchical matrices. For large dense matrices, one way to perform the compression is to generate a single exact or approximate SVD (U ΣV T ) and truncate the spectrum Σ to the desired tolerance, to produce a truncated or “compressed” representation (Ū Σ̄V̄ T ). For hierarchical matrices, the equivalent operations involve batched SVDs on small blocks, with one batched kernel call per level of the tree in the hierarchical representation. The size of the batch in every such call is the number of nodes at the corresponding level in the tree. Compression algorithms with controllable accuracy are important practically, because it is often the case that the hierarchical matrices generated by analytical methods can be compressed with no significant loss of accuracy. Even more importantly, when performing matrix operations such as additiona and multiplication, the apparent ranks of the blocks often grow and have to be recompressed regularly during the operations to prevent superlinear growth in memory requirements. 8.1. H2 -matrix representation For our application, we use the memory efficient H2 variant of hierarchical matrices which exhibit linear complexity in time and space for many of its core operations. In the H2 -matrix format, a hierarchical matrix is actually represented by three trees: 16 BATCHED QR AND SVD ALGORITHMS • Row and column basis column trees U and V that organize the row and column indices of the matrix hierarchically. Each node represents a set of basis vectors for the row and column spaces of the blocks of A. Nodes at the leaves of the tree store these vectors explicitly, while inner nodes store only transfer matrices that allow us to implicitly represent basis vectors in terms of their children. A basis tree with this parent-child relationship of the nodes is called a nested basis. For example, in a binary row basis tree U with transfer matrices E, we can explicitly compute the basis vectors for a node i with children i1 and i2 at level l as:  l   l Ei1 Ui1 l−1 . Ui = Uil2 Eil2 Figure 13a shows an example of a binary basis tree. • A matrix tree for the hierarchical blocking of A formed by a dual traversal of the nodes of the two basis trees. A leaf is determined when the block is either small enough and stored as an m × m dense matrix, or when a low rank approximation of the block meets a specified accuracy tolerance. For the latter case, the node is stored as a kl × kl coupling matrix S at each level l of the tree, where kl is the rank at level l. The block Ats of the matrix, where t is the index set of a node in the row basis tree U and s is the index set of a node in the column basis V , is then approximated as Ats ≈ Ut Sts VsT . Figure 13b shows the leaves of the matrix quadtree of a simple hierarchical matrix. For the case of symmetric matrices, the U and V trees are identical. Our numerical results below are from a symmetric covariance matrix. 8.2. Compression The compression of a symmetric H2 -matrix AH , represented by the two trees U (with its transfer e (with its transfer matrices E) e in matrices E) and S, involves generating a new optimal basis tree U a truncation phase, and a new Se that expresses the contents of the matrix blocks in this new basis in a projection phase. e , E] e We present a version of the truncation algorithm that generates a memory efficient basis [U from a representation of the matrix in a given [U, E] basis. More sophisticated algebraic compression algorithms that involve the use of S in the truncation phase in order to generate a more efficient basis will be the subject of future work. The truncation phase computes the SVD of the nodes of the basis tree U level by level, with e . We have an explicit all nodes in a level being processed in parallel to produce the new basis U representation of the basis vectors at the leaves, so we can compute the SVD of all leaf nodes in parallel with our batched kernels and truncate the singular vectors whose singular values are lower than our relative compression threshold . Truncating the node to the relative threshold using the e ||F −U SVD will give us an approximation of the leaf such that ||U||U ≤ . With the new leaf nodes, we ||F T fd U d and d is the leaf level. can compute projection matrices in a tree T , where each node i, Tid = U i i Sweeping up the tree, we process the inner nodes while preserving the nested basis property. Using the parent-child relationship of a node i with children i1 and i2 at level l, we have: # #  l  l  " l  " l l l e e U E U T E U i1 i1 i1 i1 i1 Uil−1 = i1 ≈ = el e l T Ei Uil2 Eil2 Til2 Eil2 U U i2 i2 After forming the T E matrices using batched matrix-matrix multiplication, we compute their SVD T E = QSW T using the batched SVD kernel and truncate as we did for the leaves to form the BATCHED QR AND SVD ALGORITHMS 17 g truncated T E matrices as: " #   el T g e i Sei W fi = Ei1 T l−1 T Ei = Q i el E i2 e l , the block rows of Q, e are the new transfer matrices at level l of our compressed nested where E basis and T l−1 are the projection matrices for level (l − 1). The key computations involved in this truncation phase consist then of one batched SVD involving the leaves of the tree, followed by a sequence of batched SVDs, one per level of the tree, involving the transfer matrices and data from the lower levels. The projection phase consists of transforming the coupling matrices in the matrix tree using the generated projection matrices of the truncation phase. For each coupling matrix Sts , we compute a new coupling matrix Sets = Tt Sts TsT using batched matrix-matrix multiplications. This phase of the operation consumes much less time than the truncation phase on GPUs, because of substantial efficiencies in executing regular arithmetically intensive operations on them. 8.3. Results As an illustration of the effectiveness of the algebraic compression procedure, we generate covariance matrices of various sizes for a spatial Gaussian process with n observation points placed on a random perturbation of a regular discretization of the unit square [0, 1] × [0, 1] and an isotropic exponential kernel with correlation length of 0.1. Hierarchical representations of the formally dense n × n covariance matrices are formed analytically by first clustering the points in a KD-tree using a mean split giving us the hierarchical index sets of the basis tree. The basis vectors and transfer nodes are generated using Chebyshev interpolation [29]. The matrix tree is constructed using a dual traversal of the basis tree [25, 30], and the coupling matrices are generated by evaluating the kernel at the interpolation points. The approximation error of the constructed matrix is then controlled by varying the number of interpolation points and by varying the leaf admissibility condition during the dual tree traversal. An approximation error of 10−7 has been used in the following tests e H −AH ||F ≤ 10−7 has been used to maintain the accuracy of and a relative truncation error  = ||A||A H ||F the compressed matrices. Figure 14a shows the memory consumption before and after compression of hierachical covariance matrices with leaf size 64 and initial rank 64 (corresponding to an 8 × 8 Chebyshev grid). The dense part remains untouched, while the low rank part of the representation sees a substantial decrease in memory consumption after compression with minimal loss of accuracy. Figure 14b shows the expected asymptotic linear growth in time of the compression algorithm and shows the effect of using the randomized SVD with 32 samples instead of the full SVD as computed by the shared memory kernel. Figure 15 shows another example where the admissibility condition is weakened to generate a coarser matrix tree with an increased rank of 121 (corresponding to an 11 × 11 Chebyshev grid) and the randomized SVD with 64 samples also reduces compression time when compared to the full SVD using the direct block Jacobi kernels. 9. Conclusions and Future Work In this paper, we described the implementation of efficient batched kernels for the QR decomposition and randomized singular value decomposition of low rank matrices hosted on the GPU. Our batched QR kernel provides significant performance improvements for small matrices over existing state of the art libraries, and our batched SVD routines are the first of their kind on the GPU, with performance exceeding 800/400 GFLOP/s on a batch of 1000 matrices of size 512 × 512 in 18 BATCHED QR AND SVD ALGORITHMS DP Dense portion DP Original low rank DP Compressed low rank SP Dense portion SP Original low rank SP Compressed low rank DP Full SVD SP Full SVD 20 Compression Time(s) Memory Consumption (GB) 23 DP Randomized SVD SP Randomized SVD 21 2−1 2−3 2−1 2−2 2−3 −5 2 214 215 216 217 Problem Size 218 219 214 (a) Memory savings. 215 216 217 Problem Size 218 219 (b) Compression time using randomized SVD with 32 samples and the full SVD using the shared memory kernel. Figure 14. Compression results for sample covariance matrices generated from 2D spatial statistics on a P100 GPU in single and double precision, using a relative Frobenius norm threshold of 10−7 and initial rank 64. DP Full SVD SP Full SVD DP Randomized SVD SP Randomized SVD Compression Time(s) 21 20 2−1 2−2 214 215 216 217 Problem Size 218 219 Figure 15. Compression time for a coarser matrix tree with initial rank 121 comparing the randomized SVD with 64 samples and the full SVD. single/double precision. We illustrated the power of these kernels on a problem involving the algebraic compression of hierarchical matrices stored entirely in GPU memory, and demonstrated a high-performance compression algorithm yielding significant memory savings on practical problems. In the future, we plan to investigate alternatives to the one-sided Jacobi algorithm for the SVD of the small blocks in the randomized algorithm and improve the performance of the blocked algorithms using preconditioning and adaptive block column pair selection. We also plan to develop a suite of hierarchical matrix operations suited for execution on modern GPU and manycore architectures. BATCHED QR AND SVD ALGORITHMS 19 Acknowledgments We thank the NVIDIA Corporation for providing access to the P100 GPU used in this work. References [1] N. Halko, P.-G. Martinsson, and J. A. Tropp, “Finding structure with randomness: Probabilistic algorithms for constructing approximate matrix decompositions,” SIAM Review, vol. 53, no. 2, pp. 217–288, 2011. [2] G. Golub and C. Van Loan, Matrix Computations. Johns Hopkins University Press, 2013. [3] L. Trefethen and D. Bau, Numerical Linear Algebra. Society for Industrial and Applied Mathematics, 1997. [4] J. Demmel and K. Veselic, “Jacobi’s method is more accurate than QR,” SIAM Journal on Matrix Analysis and Applications, vol. 13, no. 4, pp. 1204–1245, 1992. [5] A. Haidar, T. T. Dong, S. Tomov, P. Luszczek, and J. Dongarra, “A framework for batched and GPU-resident factorization algorithms applied to block Householder transformations.” in ISC, ser. Lecture Notes in Computer Science, J. M. Kunkel and T. Ludwig, Eds., vol. 9137. Springer, 2015, pp. 31–47. [6] A. Haidar, T. Dong, P. Luszczek, S. Tomov, and J. Dongarra, “Optimization for performance and energy for batched matrix computations on GPUs,” in Proceedings of the 8th Workshop on General Purpose Processing Using GPUs, ser. GPGPU-8. New York, NY, USA: ACM, 2015, pp. 59–69. [7] N. Wilt, The CUDA Handbook: A Comprehensive Guide to GPU Programming. Pearson Education, 2013. [8] V. Volkov, “Better performance at lower occupancy,” Proceedings of the GPU technology conference, GTC, vol. 10, 2010. [9] A. Charara, D. E. Keyes, and H. Ltaief, “Batched Triangular Dense Linear Algebra Kernels for Very Small Matrix Sizes on GPUs,” Submitted to ACM Transactions on Mathematical Software. [Online]. Available: http://hdl.handle.net/10754/622975 [10] M. Anderson, G. Ballard, J. Demmel, and K. Keutzer, “Communication-avoiding QR decomposition for GPUs,” in Parallel Distributed Processing Symposium (IPDPS), 2011 IEEE International, May 2011, pp. 48–58. [11] C. Kotas and J. Barhen, “Singular value decomposition utilizing parallel algorithms on graphical processors,” in OCEANS’11 MTS/IEEE KONA, Sept 2011, pp. 1–7. [12] H.-P. Kang and C.-R. Lee, Improving Performance of Convolutional Neural Networks by Separable Filters on GPU. Berlin, Heidelberg: Springer Berlin Heidelberg, 2015, pp. 638–649. [13] I. Badolato, L. d. Paula, and R. Farias, “Many svds on gpu for image mosaic assemble,” in 2015 International Symposium on Computer Architecture and High Performance Computing Workshop (SBAC-PADW), Oct 2015, pp. 37–42. [14] S. Tomov, R. Nath, H. Ltaief, and J. Dongarra, “Dense linear algebra solvers for multicore with GPU accelerators,” in Proc. of the IEEE IPDPS’10. Atlanta, GA: IEEE Computer Society, April 19-23 2010, pp. 1–8, DOI: 10.1109/IPDPSW.2010.5470941. [15] NVIDIA, CUBLAS Library User Guide, v8.0 ed., http://docs.nvidia.com/cuda/cublas, NVIDIA, 2017. [Online]. Available: http://docs.nvidia.com/cuda/cublas [16] J. Cheng, M. Grossman, and T. McKercher, Professional CUDA C Programming, ser. EBL-Schweitzer. Wiley, 2014. [17] J. Kurzak, H. Ltaief, J. Dongarra, and R. M. Badia, “Scheduling dense linear algebra operations on multicore processors,” Concurrency and Computation: Practice and Experience, vol. 22, no. 1, pp. 15–44, 2010. [Online]. Available: http://dx.doi.org/10.1002/cpe.1467 [18] B. B. Zhou and R. P. Brent, “On parallel implementation of the one-sided Jacobi algorithm for singular value decompositions,” in Parallel and Distributed Processing, 1995. Proceedings. Euromicro Workshop on, Jan 1995, pp. 401–408. [19] B. Zhou and R. Brent, “A parallel ring ordering algorithm for efficient one-sided Jacobi SVD computations,” Journal of Parallel and Distributed Computing, vol. 42, no. 1, pp. 1 – 10, 1997. [20] M. BEČKA and M. Vajteršic, “Block-Jacobi SVD algorithms for distributed memory systems I: Hypercubes and rings*,” Parallel Algorithms and Applications, vol. 13, no. 3, pp. 265–287, 1999. [21] ——, “Block-jacobi svd algorithms for distributed memory systems II: Meshes,” Parallel Algorithms and Applications, vol. 14, no. 1, pp. 37–56, 1999. [22] M. Bečka, G. Okša, and M. Vajteršic, “New dynamic orderings for the parallel one–sided block-Jacobi SVD algorithm,” Parallel Processing Letters, vol. 25, no. 02, p. 1550003, 2015. [23] NVIDIA, cuSOLVER Library User Guide, v8.0 ed., http://docs.nvidia.com/cuda/cusolver/, NVIDIA, 2017. [Online]. Available: http://docs.nvidia.com/cuda/cusolver 20 BATCHED QR AND SVD ALGORITHMS [24] G. Okša and M. Vajteršic, “Efficient pre-processing in the parallel block-Jacobi SVD algorithm,” Parallel Comput., vol. 32, no. 2, pp. 166–176, Feb. 2006. [Online]. Available: http://dx.doi.org/10.1016/j.parco.2005.06. 006 [25] W. Hackbusch and B. N. Khoromskij, “A sparse H-matrix arithmetic. Part II: Application to multi-dimensional problems,” Computing, vol. 64, no. 1, pp. 21–47, 2000. [26] W. Hackbusch, B. Khoromskij, and S. Sauter, “On H2 -matrices,” in Lectures on Applied Mathematics, H.-J. Bungartz, R. Hoppe, and C. Zenger, Eds. Springer Berlin Heidelberg, 2000, pp. 9–29. [27] W. Hackbusch, “A sparse matrix arithmetic based on H-matrices. Part I: Introduction to H-matrices,” Computing, vol. 62, no. 2, pp. 89–108, 1999. [28] ——, Hierarchical matrices : Algorithms and Analysis, ser. Springer series in computational mathematics. Berlin: Springer, 2015, vol. 49. [29] S. Börm and J. Garcke, “Approximating gaussian processes with H2 -matrices,” in European Conference on Machine Learning. Springer, 2007, pp. 42–53. [30] L. Grasedyck and W. Hackbusch, “Construction and arithmetics of H-matrices,” Computing, vol. 70, no. 4, pp. 295–334, 2003.
8 (cs.DS)
Analytical and simplified models for dynamic analysis of short skew bridges under moving loads arXiv:1704.07285v2 [cs.CE] 12 Feb 2018 K. Nguyena,∗, J.M. Goicoleaa a Group of Computational Mechanic, School of Civil Engineering, UPM, Spain Abstract Skew bridges are common in highways and railway lines when non perpendicular crossings are encountered. The structural effect of skewness is an additional torsion on the bridge deck which may have a considerable effect, making its analysis and design more complex. In this paper, an analytical model following 3D beam theory is firstly derived in order to evaluate the dynamic response of skew bridges under moving loads. Following, a simplified 2D model is also considered which includes only vertical beam bending. The natural frequencies, eigenmodes and orthogonality relationships are determined from the boundary conditions. The dynamic response is determined in time domain by using the “exact” integration. Both models are validated through some numerical examples by comparing with the results obtained by 3D FE models. A parametric study is performed with the simplified model in order to identify parameters that significantly influence the vertical dynamic response of the skew bridge under traffic loads. The results show that the grade of skewness has an important influence on the vertical displacement, but hardly on the vertical acceleration of the bridge. The torsional stiffness really has effect on the vertical displacement when the skew angle is large. The span length reduces the skewness effect on the dynamic behavior of the skew bridge. Keywords: skew bridge, bridge modelling, modal analysis, moving load ∗ Corresponding author Email addresses: khanh@mecanica.upm.es (K. Nguyen), jose.goicolea@upm.es (J.M. Goicolea) Preprint submitted to Engineering Structures February 13, 2018 1. Introduction Skew bridges are common in highways and railway lines when non perpendicular crossings are encountered. The structural effect of the skewness is an additional torsion on the bridge deck [1, 2] which may have a considerable effect, making its analysis and design more complex. A large research effort using the analytical, numerical as well as experimental approaches have been made during the last decades in order to better understand the behavior of this type of bridge under the static and dynamic loadings. Special attention is given in researches related to the highway skew bridge subjected to earthquake loadings. In fact, the first work on this subject was reported in 1974 by Ghobarah and Tso [3], in which a closed-form solution based on the beam model capable of capturing both flexural and torsional modes was proposed to study the dynamic response of the skewed highway bridges with intermediate supports. Maragakis and Jennings [4] obtained the earthquake response of the skew bridge, modelling the bridge deck as a rigid body. Using the Finite Element (FE) Models, the socalled stick model is firstly introduced by Wakefield et al. [5]. The stick model consists of a beam element representing the bridge deck, rigid or flexible beam elements for the cap-beam and an array of translational and rotational springs for the substructure of the bridge. This type of model is then successfully used in the later works [6, 7, 8, 9, 10, 11]. Despite its simplicity, the stick model can provide reasonably good approximations for the preliminary assessment. More sophisticated 3D models using the shell and beam elements are also proposed to study this subject [6, 12, 9, 13, 14, 15]. Regarding the behavior of the skew bridges under the traffic loads, the most of the work about this subject has been performed on the FE models using the combination of shell and beam elements and assisted by experimental testing [16, 17, 18, 19, 20, 21]. The FE models give a good approximation but require the end user more effort to introduce information in modelling the structure such as element types and sizes, dimension, material properties, connection types, etc. Therefore, its use is limited in determined case studies and challenged for a parametric study as Monte Carlo 2 simulations or large number of case studies. A possible alternative is to develop an analytical solution that is able to capture the behavior of the skew bridge and to give a sufficient accuracy. The advantage of the analytical solution is that the data input is much simpler (general information of structure such as mass, span length, flexural and torsional stiffness) and, therefore, its use is more easy for the end user and ,of course, is able for parametric study. In this context, the main objective of this work is to derive an analytical solution based on the beam theory for the simply-supported skew bridge under the moving loads. After that, a simplified 2D model is proposed in order to assimilate the effect of the skewness of the support on the vertical vibration of the bridge. An ”exact” integration in the time domain is used to solve the differential equations. Both models are validated through some numerical examples by comparing with the results obtained by 3D FE models. A parametric study is performed with the simplified model in order to identify parameters that significantly influence the vertical dynamic response of the skew bridge under traffic loads 2. Formulation of problem A simply-supported skew bridge as shown in Fig. 1 is considered to study in this work. The line of abutment support forms with the orthogonal line of the centreline an angle α defined as angle of skewness. The length of bridge is taken as the clear-span length L. The bridge is idealized using following assumptions: • The bridge deck is modelled as 3D Euler-Bernoulli beam supported at the ends and has a linear elastic behavior. • The bridge deck is very stiff in the horizontal XY plane, so the flexural deflection in Y direction will be neglected. • The bending stiffness EI, torsional stiffness GJ and mass per unit length m are constant over the length L. 3 • Warping and distortion effects in the torsion of the bridge deck is small enough to be neglected. y α y′ x Longitudinal axis x′ Deck width: B Abutment α m, r, EI, GJ, α Bridge clear-span: L Figure 1: A simply-supported skew bridge: in plane view and bridge model’s sketch With these assumptions, the bending of the bridge in XZ plane and its twisting about the X axis are the principal types of deformation of the bridge deck. The governing equations of motion for transverse and torsional vibration under transverse and torsional loads are: ∂4u = p(x, t) ∂x4 ∂2θ mr2 θ̈ − GJ 2 = mt (x, t) ∂x mü + cu̇ + EI (1a) (1b) where r is the radius of gyration; u(x, t) and θ(x, t) are the transverse deflection and torsional rotation of the bridge deck; p(x, t) and mt (x, t) are the transverse and torsional loads applied on the bridge at distance x and at time t, respectively. The external damping mechanism is introduced by the familiar term cu̇ and is assumed to be proportional to the mass (c = 2mξn ωn ) 2.1. Natural frequencies and mode shapes Using the modal superposition technique, the solution for free vibrations of the bridge deck can be decoupled into an infinite set of modal generalized 4 coordinates and mode shapes as: u(x, t) = θ(x, t) = ∞ X n=1 ∞ X qn (t)φn (x) (2a) pn (t)ϕn (x) (2b) n=1 in which φn (x) and ϕn (x) the nth flexural and torsional mode shape, and qn (t) and pn (t) are the generalized flexural and torsional coordinates at nth mode shape and are assumed to be eiωn t . The governing equations for free vibrations can be rewritten for each mode of vibration as: 1 d4 φn (x) mωn2 = φn (x) dx4 EI mr2 ωn2 1 d2 ϕn (x) = − ϕn (x) dx2 GJ (3a) (3b) The solutions of the above equations can found in many textbooks on dynamic, and can be expressed in the following form: φn (x) = Cn,1 sin(βn x) + Cn,2 cos(βn x) + Cn,3 sinh(βn x) + Cn,4 cosh(βn x) (4a) ϕn (x) = Cn,5 sin(λn x) + Cn,6 cos(λn x) (4b) where βn4 = mωn2 /EI and λ2n = mr2 ωn2 /GJ; Cn,1 , Cn,2 , Cn,3 , Cn,4 , Cn,5 , Cn,6 are six constants that are determined by the boundary conditions. The boundary conditions for the problem are shown in Fig. 1. The bridge is simply-supported at the ends by abutments. Therefore, at the support lines, there are not the vertical displacement (u(0, t) = u(L, t) = 0), rotation about the X ′ axis (θx′ (0, t) = θx′ (L, t) = 0) and bending moment in X ′ axis (My′ (0, t) = My′ (L, t) = 0). Using the change of coordinates as shown in Fig. 2, the following relationships are obtained: 5 Figure 2: Coordinate systems θx′ = θ cos(α) − ∂u sin(α) ∂x (5a) My′ = Mx sin(α) + My cos(α) = GJ ∂2u ∂θ sin(α) + EI 2 cos(α) ∂x ∂x (5b) Hence, the boundary conditions for the problem can be written as: φ(0) = φ(L) = 0 d φ(0) sin(α) = 0 dx d φ(L) sin(α) = 0 ϕ(L) cos(α) − dx d2 d GJ ϕ(0) sin(α) + EI 2 φ(0) cos(α) = 0 dx dx d d2 GJ ϕ(L) sin(α) + EI 2 φ(L) cos(α) = 0 dx dx ϕ(0) cos(α) − (6a) (6b) (6c) (6d) (6e) From these six conditions, a homogeneous system of equations is obtained as: AX = 0 (7) where X = [Cn,1 , Cn,2 , Cn,3 , Cn,4 , Cn,5 , Cn,6 ]T is the vector of six constants 6 to be determined, and the matrix A is expressed as:  0 1 0 1    sin(βL) cos(βL) sinh(βL) cosh(βL)    −a1 0 −a1 0 A=  −a1 cos(βL) a1 sin(βL) −a1 cosh(βL) −a1 sinh(βL)    0 −a2 0 a2  −a2 sin(βL) −a2 cos(βL) a2 sinh(βL) a2 cosh(βL) 0 0 0 sin(λL) cos(α) a3 a3 cos(λL) (8) with a1 = β sin(α), a2 = EIβ 2 cos(α) and a3 = GJλ sin(α). The eigenvalues are calculated by solving det(A) = 0. It is noted that the determinant of the matrix p A can be expressed in a function of unique variable β (λ = rβ 2 EI/GJ). The extraction of the eigenvalues can be performed by using any symbolic mathe- matical program (e.g. Maple or Matlab). In fact, in this study the symbolic calculation implemented in Matlab is used to extract the values of β for desired modes used in the dynamic calculation. The eigenvector corresponding to the nht mode is obtained by applying singular value decomposition to the matrix A. 2.2. Orthogonality Relationship In order to apply the modal superposition technique for solving the forced vibration problems in the skew bridges, it is necessary to determine the orthogonality relationship between the mode shapes. On the basis of the equations (3), these equations can be reformulated by multiplying both sides of these by an arbitrary mode φm (x) and ϕm (x), respectively, and integrating with respect to x over the length L, one obtains Z L 0 Z 0 ′′′′ EIφn (x)φm (x)dx − mωn2 L ′′ GJϕn (x)ϕm (x) + mr2 ωn2 7 Z L 0 Z L 0       cos(α)   cos(λL) cos(α)    0  −a3 sin(λL) 0 0 φn (x)φm (x)dx = 0 (9a) ϕn (x)ϕm (x)dx = 0 (9b)  By means of using the integration by parts of the left-hand side of the equations (9) (twice for Eq. (9a) and once for Eq. 9b) and applying the boundary conditions derived for the problem, gives: EI Z 0 L ′′ ′′ ′ ′ ′ ′ φn (x)φm (x)dx + GJ tan(α)[ϕn (L)φm (L) − ϕn (0)φm (0)] − mωn2 " ′ ′ ′ ′ GJ tan(α)[ϕm (L)φm (L) − ϕm (0)φm (0)] − Z 0 Z L φn (x)φm (x)dx = 0 0 (10a) Z L L ′ ′ ϕn (x)ϕm (x)dx = 0 ϕn (x)ϕm (x)dx + mr2 ωn2 # 0 (10b) Interchanging the indices n by m in the equation (10) and subtracting from its original form, which gives the following relations for any n 6= m: ′ ′ ′ ′ ′ ′ ′ ′ GJ tan(α)[ϕn (L)φm (L) − ϕn (0)φm (0) − ϕm (L)φn (L) + ϕm (0)φn (0)] Z L 2 2 −m(ωn − ωm ) φn (x)φm (x)dx = 0 (11a) 0 ′ ′ ′ ′ ′ ′ ′ ′ GJ tan(α)[ϕn (L)φm (L) − ϕn (0)φm (0) − ϕm (L)φn (L) + ϕm (0)φn (0)] Z L 2 mr2 (ωn2 − ωm ) ϕn (x)ϕm (x)dx = 0 (11b) 0 Next, subtracting the equation (11a) from the equation (11b) gives rise to: (ωn2 − 2 ωm ) m Z L φn (x)φm (x)dx + mr 0 2 Z ! L ϕn (x)ϕm (x)dx 0 Due to the fact that ωn 6= ωm and RL 0 φn (x)φm (x)dx ≥ 0 and RL 0 =0 (12) ϕn (x)ϕm (x)dx ≥ 0 for any n 6= m, the condition established in Eq. (12) will be fulfilled when: m mr2 Z L 0 Z L φn (x)φm (x)dx = 0 (13a) ϕn (x)ϕm (x)dx = 0 (13b) 0 8 which corresponds to the orthogonality relationship of the simply-supported skew bridge. 2.3. Vibration induced by a moving load and a convoy of moving loads Once the natural frequencies and the associated mode shapes are found, and the orthogonality relationship between the modes is known, it is possible to apply the modal superposition technique for obtaining the response of the skew bridge due to a moving load. The vertical load and the twisting moment apply on the bridge deck can be determined as: p(x, t) = P δ(x − vt) (14a) 2 mt (x, t) = P δ(x − vt)L(ǫ − ǫ ) cot(α) + P δ(x − vt)e 2(1 + K cot2 (α)) (14b) where P is the magnitude of the moving load, δ is the Dirac delta function, ǫ = vt/L, K = EI/GJ and e is the load eccentricity respect to the mass centre of the bridge deck section. The first part of the right side of Eq. (14b) is due to the skewness of the bridge [1, 2], and the second part is due to the load eccentricity. Using the modal superposition technique and applying the orthogonality relationship, the differential equations in the generalized coordinates are uncoupled: q̈n (t) + 2ξωn q̇n (t) + ωn2 qn (t) = R L 0 p̈n (t) + ωn2 pn (t) = R L 0 P φn (vt) (15a) mφn (x)2 dx  P L(ǫ − ǫ2 ) cot(α) + P e ϕn (vt) 2 mr2 ϕn (x)2 dx 2(1 + K cot (α)) 1  (15b) In order to solve the differential equations (15), several techniques can be applied. In this work, the solution of Eq. (15) is obtained by using the integration method based on the interpolation of excitation [22], which has the advantage that it gives an exact solution and a highly efficient numerical procedure. The 9 solution of Eq. (15) at time i + 1 can be determined as: wi+1 = Awi + B ẇi + CQi + DQi+1 (16) and its velocity is given by ẇi+1 = A′ wi + B ′ ẇi + C ′ Qi + D′ Qi+1 (17) i h φn (vt) P L(ǫ−ǫ2 ) cot(α) 1 RL where w = [qn , pn ]T , Q = [ R L Pmφ + P e ϕn (vt)]T , , 2 (x)2 dx mr 2 ϕ (x)2 dx 2(1+K cot (α)) n 0 0 n ′ and A, B, C, ..., D are the coefficients that depend on the structure parameters ωn , ξn and on the time step ∆t (detail formulations can be found in Appendix A) (a) a moving load (b) a convoy of moving loads Figure 3: Moving loads For the case that the bridge is forced by a convoy of moving loads as shown in Fig. 3(b), the uncoupled differential equations in the generalized coordinates for each mode of vibration n are given as nP X Pk φn (vt − dk ) (18a) RL 2 k=1 0 mφn (x) dx   nP X ϕn (vt − dk ) Pk L(ǫk − ǫ2k ) cot(α) 2 p̈n (t) + ωn pn (t) = + Pk e RL 2 2 2(1 + K cot2 (α)) k=1 0 mr ϕn (x)dx q̈n (t) + 2ξωn q̇n (t) + ωn2 qn (t) = (18b) where nP is the number of moving loads, dk is the distance between the first load and the k th load, Pk is the magnitude of the k th load, and ǫk = (vt−dk )/L. 10 The solution of Eq. (18) is obtained in similar way as in the case of a moving load. Attention needs to be paid in the determination of the modal loads in the right side of Eq. (18). For the loads that do not enter the bridge (vt − dk < 0) or leave the bridge (vt − dk > L) the modal loads associated with those loads are zero. 3. A simplified model In this part of the work, a simplified 2D model is developed in order to assimilate the effect of the skewness of the support on the vertical vibration of the simply-supported skew bridges. It is well known that the skewness of the supports causes the torsional moment on the bridge even for the vertical, centric loads. Those torsional moments in turn have a certain influence on the bending moment. In particular, a negative bending moment is introduced at the supports as shown in Fig. 4a [1, 2], making that for the purpose of vertical flexure the simply-supported skew beam behaves like as an elastically-fixed beam, or in other words, as a beam with rotational support with stiffness kθ as shown in Fig. 4b. It is noted that the negative bending moments at the supports change with the load position on the bridge. Therefore, the stiffness of the rotational support is also changed and can be different at different supports. In order to simplify the calculation the stiffness of the rotational support are considered the same in both supports. With this assumption, the stiffness of the rotational support can be determined as: kθ1 = kθ2 = kθ = 2GJ L cot2 (α) (19) In additions to the previously adopted assumptions, the following additional assumptions are used for the simplified model: • Only the vertical vibration is taken into account in the model. The load eccentricity is not considered. • The bridge deck is modelled by the 2D Euler-Bernoulli beam theory. 11 Figure 4: a) Diagram of bending moment of a skew bridge under a static load, b) Simplified model adopted for simply-supported skew bridge 3.1. Natural frequencies and mode shapes The governing equation for the free vibration of the simplified model is similar to Eq. (3a). The solution of this equation is given in (4a). The determination of the frequencies and its correspondent mode shapes is solving the homogeneous system of equations: BJ = 0 (20) where J = [C1 , C2 , C3 , C4 ]T is a vector containing the four mode shape coefficients, B is the characteristic matrix that can be determined by applying the boundary conditions. For the simplified model proposed in this study, the boundary conditions are: • There is not vertical displacement at the supports u(0, t) = u(L, t) = 0 =⇒ φn (0) = φn (L) = 0 12 (21) • Equilibrium of moments at the supports: EI EI ∂2u ∂x2 ∂2u ∂x2 = kθ 0 ∂u ∂x = −kθ L =⇒ EIφ′′n (0) = kθ φ′n (0) (22) =⇒ EIφ′′n (L) = −kθ φ′n (L) (23) 0 ∂u ∂x L Therefore, the characteristic matrix B is obtained as  in which 0 1 0   sin(βL) cos(βL) B=   −kθ β −EIβ 2  a41 a42 a41 = kθ β cos(βL) − EIβ 2 sin(βL);  1   sinh(βL) cosh(βL)   −kθ β EIβ 2   a43 a44 (24) a42 = −kθ β sin(βL) − EIβ 2 cos(βL); (25) a43 = kθ β cosh(βL) + EIβ 2 sinh(βL); a44 = kθ β sinh(βL) + EIβ 2 cosh(βL) (26) The procedure to obtain the eigenvalues and eigenvector is similar to the previously described in section 2.1. 3.2. Orthogonality relationship Similar to the analysis in section 2.2, the equation (3a) can be rewritten, using the boundary conditions of the simplified model, as: EI Z 0 L φ′′n (x)φ′′m (x)dx+kθ [φ′n (0)φ′m (0)+φ′n (L)φ′m (L)]−mωn2 Z 0 L φn (x)φm (x)dx = 0 (27) Interchanging the indices n and m in Eq. (27) and subtracting the resulting equation from its original form gives Z Z L 2 φn (x)φm (x)dx = 0 or m m(ωn2 − ωm ) 0 0 L φn (x)φm (x)dx = 0 (ωn 6= ωm ) (28) which is the orthogonality relationship between the mode shapes for the simplified model. 13 3.3. Vibration-induced by a moving load and a convoy of moving loads The dynamic response of the bridge under moving loads is obtained by using the same way described for the analytical model in section 2.3. The only difference is that the torsional response is eliminated in the calculation. 4. Numerical validations Two numerical examples are used in order to validate the proposed models. The results obtained by proposed models are compared with those obtained by Finite Element (FE) simulations. For each example, a FE model is developed in the program FEAP [23], built with 3D Euler-Bernoulli beam element (stick model). A moving load or a convoy of moving loads is applied to the nodal forces along the centreline axis, using time-dependent amplitude functions. The dynamic responses in FE models are obtained by solving in the time domain using the modal superposition technique with a time step of 0.001 s. For all examples, the first five modes of vibration are considered in the calculation and a constant damping ratio is assumed for all considered modes (ξn = ξ). Attention should be paid to select the total number of modes of vibration considered in the FE models, since the first five modes of vibration obtained by FE model are not always corresponding to the first five modes obtained by analytical and simplified models. (a) (b) Figure 5: Cross sections: a) for example 1, b) for example 2 4.1. Example 1: a simply-supported skew slab bridge under a moving load A simply-supported skew slab bridge is considered in this example. The skew angle of the bridge is 20o . The bridge clear-span is 15.0 m. The cross section 14 of the bridge is shown in Fig. 5(a) and the following geometric and mechanical characteristics are used in the calculation: • Elastic modulus E is 3.2e10 N/m2 with Poisson coefficient ν = 0.25. • Properties of the cross section: I = 0.4987 m4 , J = 1.7067 m4 , m = 22.5 t/m and r = 0.2354 m. • Damping ratio ξ is 2%. The bridge is subjected to the action of a moving load of 170 kN with a constant speed of 100 km/h. The frequencies of the first five modes considered in the calculation are extracted and listed in Table 1 for all models. It can be noted that there is a very good agreement in the natural frequency between the analytical, simplified and FE models. In fact, the maximum difference in the frequency between models does not exceed 2%. The similar agreement is also observed with the dynamic responses in terms of vertical displacement and acceleration at the mid-span for three models, as shown in Fig. 6. From this result it can be remarked that the proposed simplified model is enable to simulate the vertical dynamic response of the simply-supported skew bridge. Table 1: Frequencies of first five modes of vibration of different models (in Hz) Modes Anal. Model Simpl. Model FE Model Description st 1 6.259 6.259 6.259 1 mode in FE model 2 23.548 23.910 23.518 2nd mode in FE model 3 53.361 53.312 53.312 3rd mode in FE model 4 94.423 94.471 94.072 4th mode in FE model 5 147.716 147.387 147.387 6th mode in FE model 4.2. Example 2: a simply-supported skew box-slab bridge under a convoy of moving loads This example attempts to simulate the dynamic response of a railway bridge under an HSLM A1 train [24] which is the desired application of the proposed 15 Displacement (mm) 0.2 0.0 −0.2 −0.4 Anal. model Simpl. model FE model −0.6 −0.8 0.0 0.2 0.4 0.6 0.8 1.0 Times (s) (a) Acceleration (m/s2 ) 0.2 0.1 0.0 −0.1 −0.2 0.0 Anal. model Simpl. model FE model 0.2 0.4 0.6 0.8 1.0 Times (s) (b) Figure 6: Dynamic responses at the mid-span under a moving load: a) displacement, b) acceleration analytical and simplified methods presented in this paper. The studied bridge is a typical box-slab bridge designed for single-track and has a cross section as shown in Fig. 5(b). A skew angle of 10o is considered. The bridge clear-span is 24.0 m. The geometric and mechanical properties of the bridge’s cross section used in the calculation are: • Elastic modulus E = 3.2e10 n/m2 with Poisson coefficient of 0.25. • I = 1.3921 m4 , J = 2.6741 m4 , m = 9.774 t/m and r = 0.5967 m. • Damping ratio ξ is 1%. The HSLM-A1 train consists of 18 intermediate coaches, a power coach and a 16 end coach on either sides of the train. In total, the train has 50 axles with a load of 170 kN/axle. The dynamic analysis are carried out for different train speeds ranging from 100 km/h to 300 km/h in increment of 5 km/h. The vertical displacement and acceleration at the mid-span are obtained and compared between the models. The envelope of maximum vertical displacement and acceleration are also depicted for all models in order to validate the proposed analytical and simplified model presented in this paper. Table 2 gives the natural frequencies of the first five modes of vibration considered in the calculation. It is known that for the simply-supported bridge the train velocities of resonance can be estimated using the following formula [24]: vi = f0 D with i = 1, 2, 3, ..., ∞ i (29) where f0 is the fundamental frequency; D is the regular distance between load axles and is 18 m for the HSLM-A1 train. According with this Eq. (29), the first three resonance peaks occur at train velocities of almost 382 km/h, 191 km/h and 127 km/h. The dynamic response at the train speed of 190 km/h is shown in Fig. 7. It can be observed that at this train speed (near the second critical speed) the responses are amplified by each axle passing the bridge. The envelope curves for the maximum vertical displacement and acceleration at the mid-span are shown in Fig. 8. It can be noted in Fig. 8 that in the considered range of train velocities two peaks of response (both displacement and acceleration) occur at speeds of 190 km/h and 125 km/h which are closed to the predicted critical trains. Therefore, it can be remarked that the estimation of the train velocities of resonance proposed by [24] is still valid for the skew bridge. Furthermore, from both Figs. 7 and 8 it can be concluded that the results obtained using the analytical and simplified model agree well with the ones obtained using the FE model. It should be noted that the time consumed for the calculation using the analytical or simplified model is approximately 50 times faster than the ones using the FE model: the CPU time required for completing a analysis using the 17 analytical model was 1.9 s while 130.5 s was the time for FE model in a standard PC equipped with Intel Xeon processor of 2.33 GHz and 4 GB of RAM. Table 2: Frequencies of first five modes of vibration of different models (in Hz) Modes Anal. Model Simpl. Model FE Model Description 1 5.878 5.878 5.878 1st mode in FE model 2 23.305 23.344 23.288 2nd mode in FE model 3 52.482 52.455 52.455 4th mode in FE model 4 93.276 93.209 93.153 6th mode in FE model 5 145.748 145.608 145.642 8th mode in FE model 5. Parametric study In this part of the paper, three parametric studies are performed using the simplified model in order to identify parameters that influence significantly the vertical dynamic response of the simply-supported skew bridge under the moving loads. In each study, the value of the studied parameter are changed. The dynamic responses under the HSLM-A1 train corresponding to each value of the parameter are obtained and depicted in function of the studied parameter. The basic properties of the skew bridge in Example 2 are adopted in this section. 5.1. Effect of skew angle Figure 9 shows how the maximum dynamic responses vary with the skew angle when the bridge is forced by the HSLM-A1 train. It can be observed from Fig. 9 that the skewness has an important influence on the maximum vertical displacement at the mid-span of the bridge: in general the displacement decreases as the skew angle increases. A sharp change in slope can be observed at the skew angle of 15◦ . From this value of the skew angle, the displacement decreases more quickly. Furthermore, the changing in the train velocity of resonance is also observed when the skewness is changed. In fact, the train velocity 18 Anal. model Simpl. model FE model Displacement (mm) 2 0 −2 −4 −6 0 1 2 3 4 5 Times (s) 6 7 8 9 6 7 8 9 (a) 4 Anal. model Simpl. model FE model Acceleration (m/s2 ) 3 2 1 0 −1 −2 −3 −4 0 1 2 3 4 5 Times (s) (b) Figure 7: Dynamic responses at the mid-span under the HSLM-A1 train at velocity of 190 km/h: a) displacement, b) acceleration of resonance increases as the skewness increases. Regarding the maximum acceleration at the mid-span, the skew angle does not has pronounced influence on it: the acceleration hardly increases when the skew angle grows. 5.2. Effect of torsional to flexural stiffness ratio For this study, the torsional stiffness (GJ) is changed with respect to the flexural stiffness (EI) such that the ratio between GJ and EI varies in a range from 0.5 to 1.5. Figure 10 shows the variation of the maximum dynamic responses at the mid-span as a function of the torsional to flexural stiffness ratio. It can be observed that the maximum vertical displacement increases slightly 19 Displacement (mm) 7 Anal. model Simpl. model FE model 6 5 4 3 100 120 140 160 180 200 220 Velocity (km/h) 240 260 280 300 (a) Acceleration (m/s2 ) 4 Anal. model Simpl. model FE model 3 2 1 0 100 120 140 160 180 200 220 Velocity (km/h) 240 260 280 300 (b) Figure 8: Envelope of the maximum response at the mid-span under the HSLM-A1 train: a) displacement, b) acceleration as the ratio increases, while the maximum acceleration is barely changed. It should be noted that the skew angle used for this study is constant and is 10◦ . This skew angle is in a range from 0◦ to 15◦ in which the skewness has small influence on the dynamic response of the bridge as mentioned in the preceding section and shown in Fig. 9(a). As a result of this, the torsional stiffness does not have a pronounced influence in the vertical deflection for small skew angles. For larger skew angle, 30◦ for example, the torsional stiffness has a noticeable effect on the maximum vertical displacement, as shown in Fig. 11(a). The maximum acceleration is almost completely unaffected by the torsional stiffness for 20 0 Acceleration (m/s2) Displacement (mm) 6.0 5.5 5.0 4.5 4.0 3.5 3.0 3.0 2.5 2.0 1.5 1.0 0.5 300 250 /h) m 200 (k y 5 10 150 ocit 15 20 Skew l e angle 25◦ 30 () 35 40 100 V 0 300 250 /h) m 200 (k y 5 10 150 ocit 15 20 Skew l e angle 25◦ 30 () 35 40 100 V (a) (b) Figure 9: Effect of skewness on the dynamic responses: a) displacement, b) acceleration both skew angles selected (see Fig. 10(b) and 11(b)). Displacement (mm) Acceleration (m/s2) 3.5 6.0 3.0 2.5 5.5 2.0 5.0 1.5 4.5 1.0 4.0 0.6 0.8 GJ1.0 /EI 1.2 1.4 0.5 300 250 /h) 200 (km y 150 ocit el 100 V 0.6 (a) 0.8 GJ1.0 /EI 1.2 1.4 100 300 250 /h) 200 (km y 150 ocit l Ve (b) Figure 10: Effect of torsional to flexural stiffness ratio on the dynamic responses for a skew angle of 10◦ : a) displacement, b) acceleration 5.3. Effect of the span length In this part of the paper, the influence of the span length on the dynamic response of the simply-support skew bridge is carried out. The span length is changed from 15 m to 35 m in increment of 5 m. In order to obtain a consistent comparison between the results obtained from the parametric study, the cross section of the bridge is redesigned for each span length, using the design criteria that the ratio between the depth of the cross section (h) and the span length 21 3.0 2.5 4.5 2.0 4.0 1.5 1.0 3.5 0.6 0.8 GJ1.0 /EI 1.2 1.4 Acceleration (m/s2) Displacement (mm) 5.5 5.0 0.5 3.0 300 250 /h) 200 (km y 150 ocit el 100 V 0.6 0.8 (a) GJ1.0 /EI 1.2 1.4 300 250 /h) m 200 (k y 150 ocit l e 100 V (b) Figure 11: Effect of torsional to flexural stiffness ratio on the maximum dynamic responses for a skew angle of 30◦ : a) displacement, b) acceleration (L) is constant and is 1/14. This ratio is usually applied in the railway bridge design. The depth of the cross section will be changed with the bridge’s length. The other dimensions of the cross section are considered as unmodified. The basic properties of the cross section needed for the parametric study are listed in Table 3. Table 3: Principal properties of the bridge for the parametric study L (m) h (m) EI (N.m2 ) GJ (N.m2 ) m (t/m) h/L 15.0 1.07 11.66e09 9.75e09 9.092 1/14 20.0 1.42 28.70e09 22.61e09 9.616 1/14 25.0 1.78 50.85e09 36.26e09 10.101 1/14 30.0 2.14 80.40e09 53.21e09 10.603 1/14 35.0 2.50 117.91e09 71.34e09 11.116 1/14 The first natural frequency corresponding to each span length is obtained and depicted in Fig. 12(a) for different skew angles varying from 0◦ to 40◦ and the variation of magnitude of the first natural frequency between the skew angle of 0◦ and 40◦ for each span length is also obtained and shown in Fig. 12(b). It can be observed that the variation of frequency for each span length is generated by the skewness effect. This variation is greater when the span length is shorter 22 and decreases almost linearly with span length. Therefore, it can be remarked that the span length decreases the skewness effect on the bridge in term of the natural frequency. 20 α = 0◦ α = 40◦ 9 15 Variation (%) First natural frequency (Hz) 10 8 7 6 10 5 5 4 15 20 25 30 Span length (m) 0 35 15.0 (a) 17.5 20.0 22.5 Span length (m) 25.0 (b) Figure 12: Influence of the span length on the natural frequency of the simply-supported skew bridge: a) first natural frequency, b) variation of frequency It is well known that the dynamic response of a bridge under the traffic loads depends on the properties of the vehicle traveling on the bridge and on the proper characteristics of the bridge. In this parametric study, the traffic loads are unmodified, but the characteristics of the bridge are changed with the span length. Therefore, the comparison of dynamic responses in term of displacement and acceleration in time-history at the determined train velocity is not consistent. For a consistent comparison, the peak corresponding to the second train velocity of resonance for each span length is compared, in particular, the dynamic amplification factor (DAF) of the vertical displacement and the maximum vertical acceleration at mid-span are used to compare and are depicted in Fig. 13. It can be observed that the DAF decreases as the span length increases. There is not a reduction of variation of magnitude of DAF of the displacement for different skew angles when the span length increases. However, the reduction of variation of magnitude of the maximum acceleration can be observed for different skew angles, for which it can be remarked that the span length reduces the skewness effect on the dynamic response of the bridge 23 in term of the vertical acceleration. 2.5 Acceleration (m/s2 ) 10 DAF 2.0 1.5 8 6 4 2 1.0 15 20 25 30 Span length (m) 35 15 (a) 20 25 30 Span length (m) 35 (b) Figure 13: Maximum dynamic responses at mid-span of the skew bridge at the peak corresponding to the second velocity of resonance for different skew angles: a) dynamic amplification factor of displacement, b) acceleration 6. Conclusions In this paper, an analytical model for determining the dynamic response of the simply-supported skew bridge under the moving loads is presented and a simplified model is also proposed. The modal superposition technique is used in both models to decompose the differential equation of motions. The natural frequencies and mode shapes and the orthogonality relationship are determined from the boundary conditions. The time-dependent modal equations are solved by the exact integration, and therefore, the both models are highly accurate, robust and computationally efficient. The proposed models have been validated with results obtained from the FE models using the same modal superposition method. Furthermore, from the results obtained in this paper, the following conclusions are made: • The estimation of the train velocities of resonance proposed by [24] is still valid for the simply-supported skew bridge. • The grade of skewness of the bridge plays important role in the dynamic behavior of the bridge in term of the vertical displacement. The maximum 24 vertical displacement decreases as the skew angle increases. The vibration of bridge in term of the vertical acceleration is hardly affected by the skewness. • There is a critical skew angle from which the effect of the skewness is more noticeable. For the cross section used in the parametric study, the critical skew angle is 15◦ . • The torsional stiffness really has important influence on the vibration of the bridge in term of the vertical displacement when the skew angle is larger than the critical skew angle. The vertical acceleration is unaffected by the torsional stiffness. • The span length reduces the skewness effect on the dynamic behavior of the skew bridge in term of the natural frequency and acceleration. 25 Appendix A. Parameters for the exact integration ! ξn p A=e sin ωD ∆t + cos ωD ∆t (A.1) 1 − ξn2   1 B = e−ξn ωn ∆t sin ωD ∆t (A.2) ωD ( " #) !   1 2ξn ξn 1 − 2ξn2 2ξn −ξn ωn ∆t C= 2 +e −p cos ωD ∆t sin ωD ∆t − 1 + ωn ωn ∆t ωD ∆t ωn ∆t 1 − ξn2 −ξn ωn ∆t (A.3) D=  2ξn 1 1− + e−ξn ωn ∆t ωn2 ωn ∆t  2ξn2 − 1 2ξn sin ωD ∆t + cos ωD ∆t ωD ∆t ωn ∆t  (A.4) A′ = −e−ξn ωn ∆t ωn p sin ωD ∆t 1 − ξn2 ! (A.5)  ξn sin ωD ∆t (A.6) B =e 1 − ξn2 " ( #) ! 1 1 ωn ξn 1 ′ −ξn ωn ∆t p C = 2 − +e cos ωD ∆t +p sin ωD ∆t + ωn ∆t ∆t 1 − ξn2 1 − ξn2 −ξn ωn ∆t ′  cos ωD ∆t − (A.7) D′ = " 1 1 − e−ξn ωn ∆t ωn2 ∆t where ωD = ωn p 1 − ξn2 ξ p n sin ωD ∆t + cos ωD ∆t 1 − ξn2 !# (A.8) Acknowledgement The authors are grateful to the support of MINECO of Spanish Government through the project EDINPF (Ref. BIA2015-71016-R) and to the support provided by the Technical University of Madrid, Spain. References [1] C. F. Kollbrunner, K. Basler, Torsion in Strucutres: an engineering approach, Springer-Verlag, Berlin, 1969. 26 [2] J. Manterola, Bridges: design, calculation and construction (in Spanish), Colegio de Ingenieros de Caminos, Canales y Puertos, Madrid, Spain, 2006. [3] A. A. Ghobarah, W. K. Tso, Seismic analysis of skewed highway bridges with intermediate supports, Earthquake Engineering & Structural Dynamics 2 (3) (1974) 235–248. [4] E. A. Maragakis, P. C. Jennings, Analytical models for the rigid body motions, Earthquake Engineering & Structural Dynamics 15 (January) (1987) 923–944. [5] R. R. Wakefield, A. S. Nazmy, D. P. Billington, ANALYSIS OF SEISMIC FAILURE IN SKEW RC BRIDGE, Journal of Structural Engineering 117 (3) (1991) 972–986. [6] J. Y. Meng, E. M. Lui, Seismic analysis and assessment of a skew highway bridge, Engineering Structures 22 (11) (2000) 1433–1452. [7] J. Y. MENG, E. M. LUI, Y. LIU, Dynamic Response of Skew Highway Bridges, Journal of Earthquake Engineering 5 (2) (2001) 205–223. [8] B. G. Nielson, R. DesRoches, Analytical seismic fragility curves for typical bridges in the central and southeastern United States, Earthquake Spectra 23 (3) (2007) 615–633. [9] A. Abdel-Mohti, G. Pekcan, Seismic response of skewed RC box-girder bridges, Earthquake Engineering and Engineering Vibration 7 (4) (2008) 415–426. [10] P. Kaviani, F. Zareian, E. Taciroglu, Seismic behavior of reinforced concrete bridges with skew-angled seat-type abutments, Engineering Structures 45 (2012) 137–150. [11] C. S. W. Yang, S. D. Werner, R. DesRoches, Seismic fragility analysis of skewed bridges in the central southeastern United States, Engineering Structures 83 (2015) 116–128. 27 [12] J.-Y. Meng, E. M. Lui, Refined stick model for dynamic analysis of skew highway bridges, Journal of Bridge Engineering 7 (3) (2002) 184–194. [13] G. Nouri, Z. Ahmadi, Influence of Skew Angle on Continuous Composite Girder Bridge, Journal of Bridge Engineering 17 (4) (2012) 617–623. [14] Y. Deng, B. M. Phares, L. Greimann, G. L. Shryack, J. J. Hoffman, Behavior of curved and skewed bridges with integral abutments, Journal of Constructional Steel Research 109 (2015) 115–136. [15] M. Mallick, P. Raychowdhury, Seismic analysis of highway skew bridges with nonlinear soil-pile interaction, Transportation Geotechnics 3 (2015) 36–47. [16] A. G. Bishara, M. C. Liu, N. D. El-Ali, Skew I-Beam Composite Bridges, Journal of Structural Engineering 119 (2) (1993) 399–419. [17] A. Helba, J. B. Kennedy, Skew composite bridges ultimate load, Canadian Journal of Civil Engineering 22 (1995) 1092–1103. [18] A. R. Khaloo, H. Mirzabozorg, Load Distribution Factors in Simply Supported Skew Bridges, Journal of Bridge Engineering 8 (4) (2003) 241–244. [19] C. Menassa, M. Mabsout, K. Tarhini, G. Frederick, Influence of skew angle on reinforced concrete slab bridges, Journal of Bridge Engineering 12 (2) (2007) 205–214. [20] D. B. Ashebo, T. H. T. Chan, L. Yu, Evaluation of dynamic loads on a skew box girder continuous bridge Part I: Field test and modal analysis, Engineering Structures 29 (6) (2007) 1052–1063. [21] X. H. He, X. W. Sheng, A. Scanlon, D. G. Linzell, X. D. Yu, Skewed concrete box girder bridge static and dynamic testing and analysis, Engineering Structures 39 (2012) 38–49. [22] A. K. Chopra, Dynamics of Structures: Theory and Applications to Earthquake Engineering, 4th Edition, Prentice Hall, 2012. 28 [23] R. Taylor, FEAP-finite element analysis program (2014). URL http://www.ce.berkeley/feap [24] CEN, EN 1991-2:2003 Actions on Structures - Part 2: Traffic loads on bridges, rue de Stassart, 36B-1050 Brussels (2003). 29
5 (cs.CE)
Efficient PAC Learning from the Crowd arXiv:1703.07432v2 [cs.LG] 13 Apr 2017 Pranjal Awasthi∗ Avrim Blum† Nika Haghtalab‡ Yishay Mansour§ Abstract In recent years crowdsourcing has become the method of choice for gathering labeled training data for learning algorithms. Standard approaches to crowdsourcing view the process of acquiring labeled data separately from the process of learning a classifier from the gathered data. This can give rise to computational and statistical challenges. For example, in most cases there are no known computationally efficient learning algorithms that are robust to the high level of noise that exists in crowdsourced data, and efforts to eliminate noise through voting often require a large number of queries per example. In this paper, we show how by interleaving the process of labeling and learning, we can attain computational efficiency with much less overhead in the labeling cost. In particular, we consider the realizable setting where there exists a true target function in F and consider a pool of labelers. When a noticeable fraction of the labelers are perfect, and the rest behave arbitrarily, we show that any F that can be efficiently learned in the traditional realizable PAC model can be learned in a computationally efficient manner by querying the crowd, despite high amounts of noise in the responses. Moreover, we show that this can be done while each labeler only labels a constant number of examples and the number of labels requested per example, on average, is a constant. When no perfect labelers exist, a related task is to find a set of the labelers which are good but not perfect. We show that we can identify all good labelers, when at least the majority of labelers are good. 1 Introduction Over the last decade, research in machine learning and AI has seen tremendous growth, partly due to the ease with which we can collect and annotate massive amounts of data across various domains. This rate of data annotation has been made possible due to crowdsourcing tools, such as Amazon Mechanical TurkTM , that facilitate individuals’ participation in a labeling task. In the context of classification, a crowdsourced model uses a large pool of workers to gather labels for a given training data set that will be used for the purpose of learning a good classifier. Such learning environments that involve the crowd give rise to a multitude of design choices that do not appear in traditional learning environments. These include: How does the goal of learning from the crowd differs from the goal of annotating data by the crowd? What challenges does the high amount of noise typically found in curated data sets [Wais et al., 2010, Kittur et al., 2008, Ipeirotis et al., 2010] pose to the learning algorithms? How do learning and labeling processes interplay? How many labels are we willing to take per example? And, how much load can a labeler handle? ∗ Rutgers University, pranjal.awasthi@rutgers.edu Carnegie Mellon University, avrim@cs.cmu.edu. Supported in part by NSF grants CCF-1525971 and CCF-1535967. This work was done in part while the author was visiting the Simons Institute for the Theory of Computing. ‡ Carnegie Mellon University, nhaghtal@cs.cmu.edu. Supported in part by NSF grants CCF-1525971 and CCF-1535967 and a Microsoft Research Ph.D. Fellowship. This work was done in part while the author was visiting the Simons Institute for the Theory of Computing. § Blavatnik School of Computer Science, Tel-Aviv University, mansour@tau.ac.il. This work was done while the author was at Microsoft Research, Herzliya. Supported in part by a grant from the Science Foundation (ISF), by a grant from United States-Israel Binational Science Foundation (BSF), and by The Israeli Centers of Research Excellence (I-CORE) program (Center No. 4/11). † 1 In recent years, there have been many exciting works addressing various theoretical aspects of these and other questions [Slivkins and Vaughan, 2014], such as reducing noise in crowdsourced data [Dekel and Shamir, 2009], task assignment [Badanidiyuru et al., 2013, Tran-Thanh et al., 2014] in online or offline settings [Karger et al., 2014], and the role of incentives [Ho et al., 2013]. In this paper we focus on one such aspect, namely, how to efficiently learn and generalize from the crowd with minimal cost? The standard approach is to view the process of acquiring labeled data through crowdsourcing and the process of learning a classifier in isolation. In other words, a typical learning process involves collecting data labeled by many labelers via a crowdsourcing platform followed by running a passive learning algorithm to extract a good hypothesis from the labeled data. As a result, approaches to crowdsourcing focus on getting high quality labels per example and not so much on the task further down in the pipeline. Naive techniques such as taking majority votes to obtain almost perfect labels have a cost per labeled example that scales with the data size, namely log( m δ ) queries per label where m is the training data size and δ is the desired failure probability. This is undesirable in many scenarios when data size is large. Furthermore, if only a small fraction of the labelers in the crowd are perfect, such approaches will inevitably fail. An alternative is to feed the noisy labeled data to existing passive learning algorithms. However, we currently lack computationally efficient PAC learning algorithms that are provably robust to high amounts of noise that exists in crowdsourced data. Hence separating the learning process from the data annotation process results in high labeling costs or suboptimal learning algorithms. In light of the above, we initiate the study of designing efficient PAC learning algorithms in a crowdsourced setting where learning and acquiring labels are done in tandem. We consider a natural model of crowdsourcing and ask the fundamental question of whether efficient learning with little overhead in labeling cost is possible in this scenario. We focus on the classical PAC setting of Valiant [1984] where there exists a true target classifier f ∗ ∈ F and the goal is to learn F from a finite training set generated from the underlying distribution. We assume that one has access to a large pool of labelers that can provide (noisy) labels for the training set. We seek algorithms that run in polynomial time and produce a hypothesis with small error. We are especially interested in settings where there are computationally efficient algorithms for learning F in the consistency model, i.e. the realizable PAC setting. Additionally, we also want our algorithms to make as few label queries as possible, ideally requesting a total number of labels that is within a constant factor of the amount of labeled data needed in the realizable PAC setting. We call this O(1) overhead or cost per labeled example. Furthermore, in a realistic scenario each labeler can only provide labels for a constant number of examples, hence we cannot ask too many queries to a single labeler. We call the number of queries asked to a particular labeler the load of that labeler. Perhaps surprisingly, we show that when a noticeable fraction of the labelers in our pool are perfect all of the above objectives can be achieved simultaneously. That is, if F can be efficiently PAC learned in the realizable PAC model, then it can be efficiently PAC learned in the noisy crowdsourcing model with a constant cost per labeled example. In other words, the ratio of the number of label requests in the noisy crowdsourcing model to the number of labeled examples needed in the traditional PAC model with a perfect labeler is a constant and does not increase with the size of the data set. Additionally, each labeler is asked to label only a constant number of examples, i.e., O(1) load per labeler. Our results also answer an open question of Dekel and Shamir [2009] regarding the possibility of efficient noise robust PAC learning by performing labeling and learning simultaneously. When no perfect labelers exist, a related task is to find a set of the labelers which are good but not perfect. We show that we can identify the set of all good labelers, when at least the majority of labelers are good. 1.1 Overview of Results We study various versions of the model described above. In the most basic setting we assume that a large percentage, say 70% of the labelers are perfect, i.e., they always label according to the target function f ∗ . 2 The remaining 30% of the labelers could behave arbitrarily and we make no assumptions on them. Since the perfect labelers are in strong majority, a straightforward approach is to label each example with the majority vote over a few randomly chosen labelers, to produce the correct label on every instance with high probability. However, such an approach leads to a query bound of O(log m δ ) per labeled example, where m is the size of the training set and δ is the acceptable probability of failure. In other words, the cost per labeled example is O(log m δ ) and scales with the size of the data set. Another easy approach is to pick a few labelers at random and ask them to label all the examples. Here, the cost per labeled example is a constant but the approach is infeasible in a crowdsourcing environment since it requires a single or a constant number of labelers to label the entire data set. Yet another approach is to label each example with the majority vote of O(log 1ǫ ) labelers. While the labeled sample set created in this way only has error of ǫ, it is still unsuitable for being used with PAC learning algorithms as they are not robust to even small amounts of noise, if the noise is heterogeneous. So, the computational challenges still persist. Nevertheless, we introduce an algorithm that performs efficient learning with O(1) cost per labeled example and O(1) load per labeler. Theorem 4.3 (Informal) Let F be a hypothesis class that can be PAC learned in polynomial time to ǫ error with probability 1 − δ using mǫ,δ samples. Then F can be learned in polynomial time using O(mǫ,δ ) samples in a crowdsourced setting with O(1) cost per labeled example, provided a 21 + Θ(1) fraction of the labelers are perfect. Furthermore, every labeler is asked to label only 1 example. Notice that the above theorem immediately implies that each example is queried only O(1) times on average as opposed to the data size dependent O(log( m δ )) cost incurred by the naive majority vote style procedures. We next extend our result to the setting where the fraction of perfect labelers is significant but might be less than 12 , say 0.4. Here we again show that F can be efficiently PAC learned using O(mǫ,δ ) queries provided we have access to an “expert” that can correctly label a constant number of examples. We call such queries that are made to an expert golden queries. When the fraction of perfect labelers is close to 1 2 , say 0.4, we show that just one golden query is enough to learn. More generally, when the fraction of the perfect labelers is some α, we show that O(1/α) golden queries is sufficient to learn a classifier efficiently. We describe our results in terms of α, but we are particularly interested in regimes where α = Θ(1). Theorem 4.13 (Informal) Let F be a hypothesis class that can be PAC learned in polynomial time to ǫ error with probability 1 − δ using mǫ,δ samples. Then F can be learned in polynomial time using O(mǫ,δ ) samples in a crowdsourced setting with O( α1 ) cost per labeled example, provided more than an α fraction of the labelers are perfect for some constant α > 0. Furthermore, every labeler is asked to label only O( α1 ) examples and the algorithm uses at most α2 golden queries. The above two theorems highlight the importance of incorporating the structure of the crowd in algorithm design. Being oblivious to the labelers will result in noise models that are notoriously hard. For instance, if one were to assume that each example is labeled by a single random labeler drawn from the crowd, one would recover the Malicious Misclassification Noise of Rivest and Sloan [1994]. Getting computationally efficient learning algorithms even for very simple hypothesis classes has been a long standing open problem in this space. Our results highlight that by incorporating the structure of the crowd, one can efficiently learn any hypothesis class with a small overhead. Finally, we study the scenario when none of the labelers are perfect. Here we assume that the majority of the labelers are “good”, that is they provide labels according to functions that are all ǫ-close to the target function. In this scenario generating a hypothesis of low error is as hard as agnostic learning1 . Nonetheless, we show that one can detect all of the good labelers using expected O( 1ǫ log(n)) queries per labeler, where n is the target number of labelers desired in the pool. Theorem 5.1 (Informal) Assume we have a target set of n labelers that are partitioned into two sets, good and bad. Furthermore, assume that there are at least n2 good labelers who always provide labels according to 1 This can happen for instance when all the labelers label according to a single function f that is ǫ-far from f ∗ . 3 functions that are ǫ-close to a target function f ∗ . The set of bad labelers always provide labels according to functions that are at least 4ǫ away from the target. Then there is a polynomial time algorithm that identifies, with probability at least 1−δ, all the good labelers and none of the bad labelers using expected O( 1ǫ log( nδ )) queries per labeler. 1.2 Related Work Crowdsourcing has received significant attention in the machine learning community. As mentioned in the introduction, crowdsourcing platforms require one to address several questions that are not present in traditional modes of learning. The work of Dekel and Shamir [2009] shows how to use crowdsourcing to reduce the noise in a training set before feeding it to a learning algorithm. Our results answer an open question in their work by showing that performing data labeling and learning in tandem can lead to significant benefits. A large body of work in crowdsourcing has focused on the problem of task assignment. Here, workers arrive in an online fashion and a requester has to choose to assign specific tasks to specific workers. Additionally, workers might have different abilities and might charge differently for the same task. The goal from the requester’s point of view is to finish multiple tasks within a given budget while maintaining a certain minimum quality [Ho et al., 2013, Tran-Thanh et al., 2014]. There is also significant work on dynamic procurement where the focus is on assigning prices to the given tasks so as to provide incentive to the crowd to perform as many of them as possible within a given budget [Badanidiyuru et al., 2012, 2013, Singla and Krause, 2013]. Unlike our setting, the goal in these works is not to obtain a generalization guarantee or learn a function, but rather to complete as many tasks as possible within the budget. The work of Karger et al. [2011, 2014] also studies the problem of task assignment in offline and online settings. In the offline setting, the authors provide an algorithm based on belief propagation that infers the correct answers for each task by pooling together the answers from each worker. They show that their approach performs better than simply taking majority votes. Unlike our setting, their goal is to get an approximately correct set of answers for the given data set and not to generalize from the answers. Furthermore, their model assumes that each labeler makes an error at random independently with a certain probability. We, on the other hand, make no assumptions on the nature of the bad labelers. Another related model is the recent work of Steinhardt et al. [2016]. Here the authors look at the problem of extracting top rated items by a group of labelers among whom a constant fraction are consistent with the true ratings of the items. The authors use ideas from matrix completion to design an algorithm that can recover the top rated items with an ǫ fraction of the noise provided every labeler rates ∼ ǫ14 items and one has access to ∼ ǫ12 ratings from a trusted expert. Their model is incomparable to ours since their goal is to recover the top rated items and not to learn a hypothesis that generalizes to a test set. Our results also shed insights into the notorious problem of PAC learning with noise. Despite decades of research into PAC learning, noise tolerant polynomial time learning algorithms remain elusive. There has been substantial work on PAC learning under realistic noise models such as the Massart noise or the Tsybakov noise models [Bousquet et al., 2005]. However, computationally efficient algorithms for such models are known in very restricted cases [Awasthi et al., 2015, 2016]. In contrast, we show that by using the structure of the crowd, one can indeed design polynomial time PAC learning algorithms even when the noise is of the type mentioned above. More generally, interactive models of learning have been studied in the machine learning community [Cohn et al., 1994, Dasgupta, 2005, Balcan et al., 2006, Koltchinskii, 2010, Hanneke, 2011, Zhang and Chaudhuri, 2015, Yan et al., 2016]. We describe some of these works in Appendix A. 4 2 Model and Notations Let X be an instance space and Y = {+1, −1} be the set of possible labels. A hypothesis is a function f : X → Y that maps an instance x ∈ X to its classification y. We consider the realizable setting where there is a distribution over X × Y and a true target function in hypothesis class F. More formally, we consider a distribution D over X × Y and an unknown hypothesis f ∗ ∈ F, where errD (f ∗ ) = 0. We denote the marginal of D over X by D|X . The error of a hypothesis f with respect to distribution D is defined as errD (f ) = Pr(x,f ∗ (x))∼D [f (x) 6= f ∗ (x)]. In order to achieve our goal of learning f ∗ well with respect to distribution D, we consider having access to a large pool of labelers, some of whom label according to f ∗ and some who do not. Formally, labeler i is defined by its corresponding classification function gi : X → Y. We say that gi is perfect if errD (gi ) = 0. We consider a distribution P that is uniform over all labelers and let α = Pri∼P [errD (gi ) = 0] be the fraction of perfect labelers. We allow an algorithm to query labelers on instances drawn from D|X . Our goal is to design learning algorithms that efficiently learn a low error classifier while maintaining a small overhead in the number of labels. We compare the computational and statistical aspects of our algorithms to their PAC counterparts in the realizable setting. In the traditional PAC setting with a realizable distribution, mǫ,δ denotes the number of samples needed for learning F. That is, mǫ,δ is the total number of labeled samples drawn from the realizable distribution D needed to output a classifier f that has errD (f ) ≤ ǫ, with probability 1 − δ. We know from the VC theory [Anthony and Bartlett, 1999], that for  a hypothesis  class F with VC-dimension d and no additional . Furthermore, we assume that efficient algorithms assumptions on F, mǫ,δ ∈ O ǫ−1 d ln 1ǫ + ln 1δ for the realizable setting exist. That is, we consider an oracle OF that for a set of labeled instances S, returns a function f ∈ F that is consistent with the labels in S, if one such function exists, and outputs “None” otherwise. Given an algorithm in the noisy crowd-sourcing setting, we define the average cost per labeled example of the algorithm, denoted by Λ, to be the ratio of the number of label queries made by the algorithm to the number of labeled examples needed in the traditional realizable PAC model, mǫ,δ . The load of an algorithm, denoted by λ, is the maximum number of label queries that have to be answered by an individual labeler. In other words, λ is the maximum number of labels queried from one labeler, when P has an infinitely large support. 2 When the number of labelers is fixed, such as in Section 5, we define the load to simply be the number of queries answered by a single labeler. Moreover, we allow an algorithm to directly query the target hypothesis f ∗ on a few, e.g., O(1), instances drawn from D|X . We call these “golden queries” and denote their total number by Γ. Given a set of labelers L and an instance x ∈ X , we define MajL (x) to be the label assigned to x by the majority of labelers in L. Moreover, we denote by Maj-sizeL (x) the fraction of the labelers in L that agree with the label MajL (x). Given a set of classifiers H, we denote by MAJ (H) the classifier that for each x returns prediction MajH (x). Given a distribution P over labelers and a set of labeled examples S, we denote by P|S the distribution P conditioned on labelers that agree with labeled samples (x, y) ∈ S. We consider S to be small, typically of size O(1). Note that we can draw a labeler from P|S by first drawing a labeler according to P and querying it on all the labeled instances in S. Therefore, when P has infinitely large support, the load of an algorithm is the maximum size of S that P is ever conditioned on. 2 The concepts of total number of queries and load may be seen as analogous to work and depth in parallel algorithms, where work is the total number of operations performed by an algorithm and depth is the maximum number of operations that one processor has to perform in a system with infinitely many processors. 5 3 A Baseline Algorithm and a Road-map for Improvement In this section, we briefly describe a simple algorithm and the approach we use to improve over it. Consider a very simple baseline algorithm for the case of α > 21 : BASELINE: Draw a sample of size m = mǫ,δ from D|X and label each x ∈ S by MajL (x),  where L ∼ P k for k = O (α − 0.5)−2 ln m is a set of randomly drawn labelers. Return δ classifier OF (S). That is, the baseline algorithm queries enough labelers on each sample such that with probability 1 − δ all the labels are correct. Then, it learns a classifier using this labeled set. It is clear that the performance of BASELINE is far from being desirable. First, this approach takes log(m/δ) more labels than it requires samples, leading to an average cost per labeled example that increases with the size of the sample set. Moreover, when perfect labelers form a small majority of the labelers, i.e., α = 12 + o(1), the number of labels needed to correctly label an instance increases drastically. Perhaps even more troubling is that if the perfect labelers are in minority, i.e., α < 21 , S may be mislabeled and OF (S) may return a classifier that has large error, or no classifier at all. In this work, we improve over BASELINE in both aspects. In Section 4, we improve the log(m/δ) average cost per labeled example by interleaving the two processes responsible for learning a classifier and querying labels. In particular, BASELINE first finds high quality labels, i.e., labels that are correct with high probability, and then learns a classifier that is consistent with those labeled samples. However, interleaving the process of learning and acquiring high quality labels can make both processes more efficient. At a high level, for a given classifier h that has a larger than desirable error, one may be able to find regions where h performs particularly poorly. That is, the classifications provided by h may differ from the correct label of the instances. In turn, by focusing our effort for getting high quality labels on these regions we can output a correctly labeled sample set using less label queries overall. These additional correctly labeled instances from regions where h performs poorly can help us improve the error rate of h in return. In Section 4, we introduce an algorithm that draws on ideas from boosting and a probabilistic filtering approach that we develop in this work to facilitate interactions between learning and querying. In Section 4.1, we remove the dependence of label complexity on (α − 0.5)−2 using O(1/α) golden queries. At a high level, instances where only a small majority of labelers agree are difficult to label using queries asked from labelers. But, these instances are great test cases that help us identify a large fraction of imperfect labelers. That is, we can first ask a golden query on one such instance to get its correct label and from then on only consider labelers that got this label correctly. In other words, we first test the labelers on one or very few tests questions, if they pass the tests, then we ask them real label queries for the remainder of the algorithm, if not, we never consider them again. 4 An Interleaving Algorithm In this section, we improve over the average cost per labeled example of the BASELINE algorithm, by interleaving the process of learning and acquiring high quality labels. Our Algorithm 2 facilitates the interactions between the learning process and the querying process using ideas from classical PAC learning and adaptive techniques we develop in this work. For ease of presentation, we first consider the case where α = 12 +Θ(1), say α ≥ 0.7, and introduce an algorithm and techniques that work in this regime. In Section 4.1, we show how our algorithm can be modified to work with any value of α. For convenience, we assume in the analysis below that distribution D is over a discrete space. This is in fact without loss of generality, since using uniform convergence one can instead work with the uniform distribution over an unlabeled sample multiset of size O( ǫd2 ) drawn from D|X . Here, we provide an overview of the techniques and ideas used in this algorithm. 6 Boosting: In general, boosting algorithms [Schapire, 1990, Freund, 1990, Freund and Schapire, 1995] provide a mechanism for producing a classifier of error ǫ using learning algorithms that are only capable of producing classifiers with considerably larger error rates, typically of error p = 12 − γ for small γ. In particular, early work of Schapire [1990] in this space shows how one can combine 3 classifiers of error p to get a classifier of error O(p2 ), for any p > 0. Theorem 4.1 (Schapire [1990]). For any p > 0 and distribution D, consider three classifiers: 1) classifier h1 such that errD (h1 ) ≤ p; 2) classifier h2 such that errD2 (h2 ) ≤ p, where D2 = 12 DC + 21 DI for distributions DC and DI that denote distribution D conditioned on {x | h1 (x) = f ∗ (x)} and {x | h1 (x) 6= f ∗ (x)}, respectively; 3) classifier h3 such that errD3 (h3 ) ≤ p, where D3 is D conditioned on {x | h1 (x) 6= h2 (x)}. Then, errD (MAJ (h1 , h2 , h3 )) ≤ 3p2 − 2p3 . As opposed to the main motivation for boosting where the learner only has access to a learning algorithm of error p = 12 − γ, in our setting we can learn a classifier to any desired error rate p as long as we have a sample set of mp,δ correctly labeled instances. The larger the error rate p, the smaller the total number of label queries needed for producing a correctly labeled set of the appropriate size. We use this idea in √ Algorithm 2. In particular, we learn classifiers of error O( ǫ) using sample sets of size O(m√ǫ,δ ) that are labeled by majority vote of O(log(m√ǫ,δ )) labelers, using fewer label queries overall than BASELINE. Probabilistic Filtering: Given classifier h1 , the second step of the classical boosting algorithm requires distribution D to be reweighed based on the correctness of h1 . This step can be done by a filtering process as follows: Take a large set of labeled samples from D and divide them to two sets depending on whether or not the instances are mislabeled by h1 . Distribution D2 , in which instances mislabeled by h1 make up half of the weight, can be simulated by picking each set with probability 12 and taking an instance from that set uniformly at random. To implement filtering in our setting, however, we would need to first get high quality labels for the set of instances used for simulating D2 . Furthermore, this sample set is typically large, since at least 1p mp,δ random samples from D are needed to simulate D2 that has half of its weight on the points that √ h1 mislabels (which is a p fraction of the total points). In ourcase where p = O( ǫ), getting high quality m labels for such a large sample set requires O mǫ,δ ln δǫ,δ label queries, which is as large as the total number of labels queried by BASELINE. Algorithm 1 F ILTER(S, h)  Let SI = ∅ and N = log 1ǫ . for x ∈ S do for t = 1, . . . , N do Draw a random labeler i ∼ P and let yt = gi (x) If t is odd and Maj(y1:t ) = h(x), then break. end Let SI = SI ∪ {x}. // Reaches this step when for all t, Maj(y1:t ) 6= h(x) end return SI In this work, we introduce a probabilistic filtering approach, called F ILTER, that only requires O (mǫ,δ ) label queries, i.e., O(1) cost per labeled example. Given classifier h1 and an unlabeled sample set S, F ILTER (S, h1 ) returns a set SI ⊆ S such that for any x ∈ S that is mislabeled by h1 , x ∈ SI with probability at least Θ(1). Moreover, any x that is correctly labeled by h1 is most likely not included in SI . This procedure is described in detail in Algorithm 1. Here, we provide a brief description of its working: For any x ∈ S, F ILTER queries one labeler at a time, drawn at random, until the majority of the labels it has 7 acquired so far agree with h1 (x), at which point F ILTER removes x from consideration. On the other hand, if the majority of the labels never agree with h1 (x), F ILTER adds x to the output set SI . Consider x ∈ S that is correctly labeled by h. Since each additional label agrees with h1 (x) = f ∗ (x) with probability ≥ 0.7, with high probability the majority of the labels on x will agree with f ∗ (x) at some point, in which case F ILTER stops asking for more queries and removes x. As we show in Lemma 4.9 this happens within O(1) queries most of the time. On the other hand, for x that is mislabeled by h, a labeler agrees with h1 (x) with probability ≤ 0.3. Clearly, for one set of random labelers —one snapshot of the labels queried by F ILTER— the majority label agrees with h1 (x) with a very small probability. As we show in Lemma 4.6, even when considering the progression of all labels queried by F ILTER throughout the process, with probability Θ(1) the majority label never agrees with h1 (x). Therefore, x is added to SI with probability Θ(1). Super-sampling: Another key technique we use in this work is super-sampling. In short, this means that as long as we have the correct label of the sampled points and we are in the realizable setting, more samples never hurt the algorithm. Although this seems trivial at first, it does play an important role in our approach. In particular, our probabilistic filtering procedure does not necessarily simulate D2 but a distribution D ′ , such that Θ(1)d2 (x) ≤ d′ (x) for all x, where d2 and d′ are the densities of D2 and D ′ , respectively. At a high level, sampling Θ(m) instances from D ′ simulates a super-sampling process that samples m instances from D2 and then adds in some arbitrary instances. This is formally stated below and is proved in Appendix B. Lemma 4.2. Given a hypothesis class F consider any two discrete distributions D and D ′ such that for all x, d′ (x) ≥ c · d(x) for an absolute constant c > 0, and both distributions are labeled according to f ∗ ∈ F. There exists a constant c′ > 1 such that for any ǫ and δ, with probability 1 − δ over a labeled sample set S of size c′ mǫ,δ drawn from D ′ , OF (S) has error of at most ǫ with respect to distribution D. With these techniques at hand, we present Algorithm 2. At a high level, the algorithm proceeds in three phases, one for each classifier used by Theorem 4.1. In Phase 1, the algorithm learns h1 such that √ errD (h1 ) ≤ 12 ǫ. In Phase 2, the algorithm first filters a set of size O(mǫ,δ ) into the set SI and takes an m additional set SC of Θ(m√ǫ,δ ) samples. Then, it queries O(log( δǫ,δ )) labelers on each instance in SI and SC to get their correct labels with high probability. Next, it partitions these instances to two different sets based on whether or not h1 made a mistake on them. It then learns h2 on a sample set W that is drawn by √ weighting these two sets equally. As we show in Lemma 4.8, errD2 (h2 ) ≤ 12 ǫ. In phase 3, the algorithm learns h3 on a sample set S3 drawn from D|X conditioned on h1 and h2 disagreeing. Finally, the algorithm returns MAJ (h1 , h2 , h3 ). + Θ(1) case). Algorithm 2 uses oracle OF , runs in time poly(d, 1ǫ , ln( 1δ )) and with  √  m√  ǫ,δ + 1 cost per labeled probability 1 − δ returns f ∈ F with errD (f ) ≤ ǫ, using Λ = O ǫ log δm√  ǫ,δ example, Γ = 0 golden queries, and λ = 1 load. Note that when √1ǫ ≥ log , the above cost per δ labeled sample is O(1). Theorem 4.3 (α = 1 2 We start our analysis of Algorithm 2 by stating that C ORRECT-L ABEL (S, δ) labels S correctly, with probability 1 − δ. This is direct application of the Hoeffding bound and its proof is omitted. Lemma 4.4. For any unlabeled sample set S, δ > 0, and S = C ORRECT-L ABEL (S, δ), with probability 1 − δ, for all (x, y) ∈ S, y = f ∗ (x). √ Note that as a direct consequence of the above lemma, Phase 1 of Algorithm 2 achieves error of O( ǫ). √ Lemma 4.5. In Algorithm 2, with probability 1 − 3δ , errD (h1 ) ≤ 12 ǫ. 8 Algorithm 2 I NTERLEAVING : B OOSTING B Y P ROBABILISTIC F ILTERING FOR α = 21 + Θ(1) Input: Given a distribution D|X , a class of hypotheses F, parameters ǫ and δ. Phase 1: Let S1 = C ORRECT-L ABEL (S1 , δ/6), for a set of sample S1 of size 2m√ǫ,δ/6 from D|X . Let h1 = OF (S1 ). Phase 2: Let SI = F ILTER (S2 , h1 ), for a set of samples S2 of size Θ(mǫ,δ ) drawn from D|X . Let SC be a sample set of size Θ(m√ǫ,δ ) drawn from D|X . Let SAll = C ORRECT-L ABEL (SI ∪ SC , δ/6). Let WI = {(x, y) ∈ SAll | y 6= h1 (x)} and Let WC = SAll \ WI . Draw a sample set W of size Θ(m√ǫ,δ ) from a distribution that equally weights WI and WC . Let h2 = OF (W ). Phase 3: Let S3 = C ORRECT-L ABEL (S3 , δ/6), for a sample set S3 of size 2m√ǫ,δ/6 drawn from D|X conditioned on h1 (x) 6= h2 (x). Let h3 = OF (S3 ). return Maj(h1 , h2 , h3 ). C ORRECT-L ABEL(S, δ): for x ∈ S do Let L ∼ P k for a set of k = O(log( |S| δ )) labelers drawn from P and S ← S ∪ {(x, Maj L (x))}. end return S. Next, we prove that F ILTER removes instances that are correctly labeled by h1 with good probability and retains instances that are mislabeled by h1 with at least a constant probability. Lemma 4.6. Given any sample set S and classifier h, for every x ∈ S √ 1. If h(x) = f ∗ (x), then x ∈ F ILTER (S, h) with probability < ǫ. 2. If h(x) 6= f ∗ (x), then x ∈ F ILTER (S, h) with probability ≥ 0.5. Proof. For the first claim, note that x ∈ SI only if Maj(y1:t ) 6= h(x) for all t ≤ N . Consider t = N time step. Since each random query agrees with f ∗ (x) = h(x) with probability ≥ 0.7 independently, majority of √ √ N = O(log(1/ ǫ)) labels are correct with probability at least 1 − ǫ. Therefore, the probability that the √ majority label disagrees with h(x) = f ∗ (x) at every time step is at most ǫ. In the second claim, we are interested in the probability that there exists some t ≤ N , for which Maj(y1:t ) = h(x) 6= f ∗ (x). This is the same as the probability of return in biased random walks, also called the probability of ruin in gambling [Feller, 2008], where we are given a random walk that takes a step to the right with probability ≥ 0.7 and takes a step to the left with the remaining probability and we are interested in the probability that this walk ever crosses the origin to the left while taking N or even infinitely E.1), the probability that many steps. Using the probability of return for biased random (see Theorem   walks  N N +1   0.7 0.7 Maj(y1:t ) 6= f ∗ (x) ever is at most 1 − 1−0.7 / 1 − 1−0.7 < 37 . Therefore, for each x such that h(x) 6= f ∗ (x), x ∈ SI with probability at least 4/7. √ In the remainder of the proof, for ease of exposition we assume that not only errD (h1 ) ≤ 12 ǫ as per √ Lemma 4.5, but in fact errD (h1 ) = 21 ǫ. This assumption is not needed for the correctness of the results but it helps simplify the notation and analysis. As a direct consequence of Lemma 4.6 and application of the 9 Chernoff bound, we deduce that with high probability W I , W C , and SI all have size Θ(m√ǫ,δ ). The next lemma, whose proof appears in Appendix C, formalizes this claim. Lemma 4.7. With probability 1 − exp(−Ω(m√ǫ,δ )), W I , W C , and SI all have size Θ(m√ǫ,δ ). The next lemma combines the probabilistic filtering and super-sampling techniques to show that h2 has √ the desired error O( ǫ) on D2 . Lemma 4.8. Let DC and DI denote distribution D when it is conditioned on {x | h1 (x) = f ∗ (x)} and √ {x | h1 (x) 6= f ∗ (x)}, respectively, and let D2 = 12 DI + 21 DC . With probability 1−2δ/3, errD2 (h2 ) ≤ 12 ǫ. Proof. Consider distribution D ′ that has equal probability on the distributions induced by WI and WC and let d′ (x) denote the density of point x in this distribution. Relying on our super-sampling technique (see Lemma 4.2), it is sufficient to show that for any x, d′ (x) = Θ(d2 (x)). √ For ease of presentation, we assume that Lemma 4.5 holds with equality, i.e., errD (h1 ) is exactly 12 ǫ with probability 1 − δ/3. Let d(x), d2 (x), dC (x), and dI (x) be the density of instance x in distributions D, D2 , DC , and DI , respectively. Note that, for any x such that h1 (x) = f ∗ (x), we have d(x) = dC (x)(1 − 1√ 1√ ∗ 2 ǫ). Similarly, for any x such that h1 (x) 6= f (x), we have d(x) = dI (x) 2 ǫ. Let NC (x), NI (x), MC (x) and MI (x) be the number of occurrences of x in the sets SC , SI , WC and WI , respectively. For any x, there are two cases: If h1 (x) = f ∗ (x): Then, there exist absolute constants c1 and c2 according to Lemma 4.7, such that   E[NC (x)] |SC | · d(x) E[MC (x)] 1 MC (x) ′ ≥ = ≥ d (x) = E √ √ 2 c · m c · m c1 · m√ǫ,δ |WC | 1 1 ǫ,δ ǫ,δ √ |SC | · dC (x) · (1 − 12 ǫ) c2 d2 (x) ≥ c2 dC (x) = = , √ c1 · m ǫ,δ 2 where the second and sixth transitions are by the sizes of WC and |SC | and the third transition is by the fact that if h(x) = f ∗ (x), MC (x) > NC (x). If h1 (x) 6= f ∗ (x): Then, there exist absolute constants c′1 and c′2 according to Lemma 4.7, such that   4 E[NI (x)] 1 E[MI (x)] MI (x) 7 d(x)|S2 | ≥ ≥ d (x) = E ≥ ′ 2 c1 · m√ǫ,δ c′1 · m√ǫ,δ c′1 · m√ǫ,δ |WI | 1√ 4 c′2 d2 (x) ′ 7 dI (x) 2 ǫ · |S2 | ≥ c d (x) = = , I 2 ′ c1 · m√ǫ,δ 2 ′ where the second and sixth transitions are by the sizes of WI and |S2 |, the third transition is by the fact that if h(x) 6= f ∗ (x), MI (x) > NI (x), and the fourth transition holds by part 2 of Lemma 4.6. √ Using the super-sampling guarantees of Lemma 4.2, with probability 1 − 2δ/3, errD2 (h2 ) ≤ ǫ/2. The next claim shows that the probabilistic filtering step queries a few labels only. At a high level, this is achieved by showing that any instance x for which h1 (x) = f ∗ (x) contributes only O(1) queries, with high probability. On the other hand, instances that h1 mislabeled may each get log( 1ǫ ) queries. But, because there are only few such points, the total number of queries these instances require is a lower order term. √ Lemma 4.9. Let S be a sample set drawn from distribution D and let h be such that errD (h) ≤ ǫ. With √ probability 1 − exp(−Ω(|S| ǫ)), F ILTER (S, h) makes O(|S|) label queries. 10 √ Proof. Using Chernoff bound, with probability 1 − exp (−|S| ǫ) the total number of points in S where h √ √ disagrees with f ∗ is O(|S| ǫ). The number of queries spent on these points is at most O (|S| ǫ log(1/ǫ)) ≤ O(|S|). Next, we show that for each x such that h(x) = f ∗ (x), the number of queries taken until a majority of them agree with h(x) is a constant. Let us first show that this is the case in expectation. Let Ni be the expected number of labels queried until we have i more correct labels than incorrect ones. Then N1 ≤ 0.7(1) + 0.3(N2 + 1), since with probability at least α ≥ 0.7, we receive one more correct label and stop, and with probability ≤ 0.3 we get a wrong label in which case we have to get two more correct labels in future. Moreover, N2 = 2N1 , since we have to get one more correct label to move from N2 to N1 and then one more. Solving these, we have that N1 ≤ 2.5. Therefore, the expected total number of queries is at most O(|S|). Next, we show that this random variable is also well-concentrated. Let Lx be a random variable that indicates the total number of queries on x before we have one more correct label than incorrect labels. Note that Lx is an unbounded random variable, therefore concentration bounds such as Hoeffding or Chernoff do not work here. Instead, to show that Lx is well-concentrated, we prove that the Bernstein inequality (see Theorem E.2) holds. That is, as we show in Appendix D, for any x, the Bernstein inequality is statisfied by the fact that for any i > 1, E[(Lx − E[Lx ])i ] ≤ 50(i + 1)! e4i . Therefore, over all instances P in S, x∈S Lx ∈ O(|S|) with probability 1 − exp(−|S|). Finally, we have all of the ingredients needed for proving our main theorem. Proof of Theorem 4.3. We first discuss the number of label queries Algorithm 2 makes. The total number of labels queried by Phases 1 and 3 is attributed to the labels  queried by C ORRECT-L ABEL (S1 , δ) and  √ √ C ORRECT-L ABEL (S3 , δ/6), which is O m ǫ,δ log(m ǫ,δ /δ) . By Lemma 4.7, |SI ∪ SC | ≤ O(m√ǫ,δ )   almost surely. Therefore, C ORRECT-L ABEL (SI ∪ SC , δ/6) contributes O m√ǫ,δ log(m√ǫ,δ /δ) labels. Moreover, as we showed in Lemma 4.9, F ILTER (S2 , h1 ) queries O(mǫ,δ) labels,   almost surely. So, the m√ ǫ,δ total number of labels queried by Algorithm 2 is at most O m√ǫ,δ log + mǫ,δ . This leads to δ  √  m√  ǫ,δ + 1 cost per labeled example. Λ=O ǫ log δ It remains to show that MAJ (h1 , h2 , h3 ) has error ≤ ǫ on D. Since C ORRECT-L ABEL (S1 , δ/6) and √ √ C ORRECT-L ABEL (S3 , δ/6) return correctly labeled sets , errD (h1 ) ≤ 21 ǫ and errD3 (h3 ) ≤ 12 ǫ, where √ D3 is distribution D conditioned on {x | h1 (x) 6= h2 (x)}. As we showed in Lemma 4.8, errD2 (h2 ) ≤ 12 ǫ with probability 1 − 2δ/3. Using the boosting technique of Schapire [1990] described in Theorem 4.1, we conclude that MAJ (h1 , h2 , h3 ) has error ≤ ǫ on D. 4.1 The General Case of Any α In this section, we extend Algorithm 2 to handle any value of α, that does not necessarily satisfy α > 1 1 2 + Θ(1). We show that by using O( α ) golden queries, it is possible to efficiently learn any function class with a small overhead. There are two key challenges that one needs to overcome when α < 21 + o(1). First, we can no longer assume that by taking the majority vote over a few random labelers we get the correct label of an instance. Therefore, C ORRECT-L ABEL (S, δ) may return a highly noisy labeled sample set. This is problematic, since efficiently learning h1 , h2 , and h3 using oracle OF crucially depends on the correctness of the input labeled set. Second, F ILTER (S, h1 ) no longer “filters” the instances correctly based on the classification error of h1 . In particular, F ILTER may retain a constant fraction of instances where h1 is in fact correct, and it may throw out instances where h1 was incorrect with high probability. Therefore, the per-instance guarantees of Lemma 4.6 fall apart, immediately. We overcome both of these challenges by using two key ideas outlined below. 11 Pruning: As we alluded to in Section 3, instances where only a small majority of labelers are in agreement are great for identifying and pruning away a noticeable fraction of the bad labelers. We call these instances good test cases. In particular, if we ever encounter a good test case x, we can ask a golden query y = f ∗ (x) and from then on only consider the labelers who got this test correctly, i.e., P ← P|{(x,y)} . Note that if we make our golden queries when Maj-sizeP (x) ≤ 1 − α2 , at least an α2 fraction of the labelers would be pruned. This can be repeated at most O( α1 ) times before the number of good labelers form a strong majority, in which case Algorithm 2 succeeds. The natural question is how would we measure Maj-sizeP (x) using few label queries? Interestingly, C ORRECT-L ABEL (S, δ) can be modified to detect such good test cases by measuring the empirical agreement rate on a set L of O( α12 log( |S| δ )) labelers. This is shown in procedure P RUNE - AND -L ABEL as part Algorithm 3. That is, if Maj-sizeL (x) > 1 − α/4, we take MajL (x) to be the label, otherwise we test and prune the labelers, and then restart the procedure. This ensures that whenever we use a sample set that is labeled by P RUNE - AND -L ABEL , we can be certain of the correctness of the labels. This is stated in the following lemma, and proved in Appendix F.1. Lemma 4.10. For any unlabeled sample set S, δ > 0, with probability 1−δ, either P RUNE - AND -L ABEL (S, δ) prunes the set of labelers or S = P RUNE - AND -L ABEL (S, δ) is such that for all (x, y) ∈ S, y = f ∗ (x). As an immediate result, the first phase of Algorithm 3 succeeds in computing h1 , such that errD (h1 ) ≤ Moreover, every time P RUNE - AND -L ABEL prunes the set of labelers, the total fraction of good labeler among all remaining labelers increase. As we show, after O(1/α) prunings, the set of good labelers is guaranteed to form a large majority, in which case Algorithm 2 for the case of α = 21 + Θ(1) can be used. This is stated in the next lemma and proved in Appendix F.2. 1√ 2 ǫ. Lemma 4.11. For any δ, with probability 1 − δ, the total number of times that Algorithm 3 is restarted as a result of pruning is O( α1 ). Robust Super-sampling: The filtering step faces a completely different challenge: Any point that is a good test case can be filtered the wrong way. However, instances where still a strong majority of the labelers agree are not affected by this problem and will be filtered correctly. Therefore, as a first step we ensure that the total number of good test cases that were not caught before F ILTER starts is small. For this purpose, we start the algorithm by calling C ORRECT-L ABEL on a sample of size O( 1ǫ log( 1δ )), and if no test points were found in this set, then with high probability the total fraction of good test cases in the underlying distribution is at most 2ǫ . Since the fraction of good test cases is very small, one can show that except for √ an ǫ fraction, the noisy distribution constructed by the filtering process will, for the purposes of boosting, satisfy the conditions needed for the super-sampling technique. Here, we introduce a robust version of the √ super-sampling technique to argue that the filtering step will indeed produce h2 of error O( ǫ). Lemma 4.12 (Robust Super-Sampling Lemma). Given a hypothesis class F consider any two discrete distributions D and D ′ such that except for an ǫ fraction of the mass under D, we have that for all x, d′ (x) ≥ c · d(x) for an absolute constant c > 0 and both distributions are labeled according to f ∗ ∈ F. There exists a constant c′ > 1 such that for any ǫ and δ, with probability 1 − δ over a labeled sample set S of size c′ mǫ,δ drawn from D ′ , OF (S) has error of at most 2ǫ with respect to D. By combining these techniques at every execution of our algorithm we ensure that if a good test case is ever detected we prune a small fraction of the bad labelers and restart the algorithm, and if it is never detected, our algorithm returns a classifier of error ǫ. Theorem 4.13 (Any α). Suppose the fraction of the perfect labelers is α and let δ′ = cαδ for small enough constant c > 0. Algorithm 3 uses oracle OF , runs in time poly(d, α1 , 1ǫ , ln( 1δ )), uses a training set of size 12 Algorithm 3 B OOSTING B Y P ROBABILISTIC F ILTERING FOR ANY α Input: Given a distribution D|X and P , a class of hypothesis F, parameters ǫ, δ, and α. Phase 0: If α > 43 , run Algorithm 2 and quit. Let δ′ = cαδ for small enough c > 0 and draw S0 of O( 1ǫ log( δ1′ )) examples from the distribution D. P RUNE - AND -L ABEL (S0 , δ′ ). Phase 1: Let S1 = P RUNE - AND -L ABEL (S1 , δ′ ), for a set of sample S1 of size 2m√ǫ,δ′ from D. Let h1 = OF (S1 ). Phase 2: Let SI = F ILTER (S2 , h1 ), for a set of samples S2 of size Θ(mǫ,δ′ ) drawn from D. Let SC be a sample set of size Θ(m√ǫ,δ′ ) drawn from D. Let SAll = P RUNE - AND -L ABEL (SI ∪ SC , δ′ ). Let WI = {(x, y) ∈ SAll | y 6= h1 (x)} and Let WC = SAll \ WI . Draw a sample set W of size Θ(m√ǫ,δ′ ) from a distribution that equally weights WI and WC . Let h2 = OF (W ). Phase 3: Let S3 = P RUNE - AND -L ABEL (S3 , δ′ ), for a sample set S3 of size 2m√ǫ,δ′ drawn from D conditioned on h1 (x) 6= h2 (x). Let h3 = OF (S3 ). return Maj(h1 , h2 , h3 ). P RUNE - AND -L ABEL(S, δ): for x ∈ S do Let L ∼ P k for a set of k = O( α12 log( |S| δ )) labelers drawn from P . if Maj-sizeL (x) ≤ 1 − α4 then Get a golden query y ∗ = f ∗ (x), Restart Algorithm 3 with distribution P ← P|{(x,y∗ )} and α ← 1−αα . 8 else S ← S ∪ {(x, MajL (x))}. end end return S. O( α1 mǫ,δ′ ) size and with probability 1 − δ returns f ∈ F with errD (f ) ≤ ǫ using O( α1 ) golden queries, load of α1 per labeler, and a total number of queries   m√ǫ,δ′ 1 1 1 1 1 √ ′ O mǫ,δ + log( ′ ) log( ′ ) + 3 m ǫ,δ′ log( ) . α αǫ δ ǫδ α δ′  m√  ǫ,δ 1 Note that when α21√ǫ ≥ log ) < d, the cost per labeled query is O( α1 ). and log( αδ αδ Proof Sketch. Let B = {x | Maj-sizeP (x) ≤ 1 − α/2} be the set of good test cases and let β = D[B] be the total density on such points. Note that if β > 4ǫ , with high probability S0 includes one such point, in which case P RUNE - AND -L ABEL identifies it and prunes the set of labelers. Therefore, we can assume that β ≤ 4ǫ . By Lemma 4.10, it is easy to see that Phase 1 and Phase 3 of Algorithm 3 succeed in producing h1 and √ √ h3 such that errD (h1 ) ≤ 21 ǫ and errD3 (h3 ) ≤ 21 ǫ. It remains to show that Phase 2 of Algorithm 3 also 13 √ produces h2 such that errD2 (h2 ) ≤ 12 ǫ. Consider the filtering step of Phase 2. First note that for any x ∈ / B, the per-point guarantees of F ILTER expressed in Lemma 4.6 still hold. Let D ′ be the distribution that has equal probability on the distributions induced by WI and WC , and is used for simulating D2 . Similarly as in Lemma 4.8 one can show that for √ any x 6∈ B, d′ (x) = Θ(d2 (x)). Since D[B] ≤ 4ǫ , we have that D2 [B] ≤ 41 ǫ. Therefore, D ′ and D2 satisfy the conditions of the robust super-sampling lemma (Lemma 4.12) where the fraction of bad points is at most √ √ ǫ ǫ 4 . Hence, we can argue that errD2 (h2 ) ≤ 2 . The remainder of the proof follows by using the boosting technique of Schapire [1990] described in Theorem 4.1. 5 No Perfect Labelers In this section, we consider a scenario where our pool of labelers does not include any perfect labelers. Unfortunately, learning f ∗ in this setting reduces to the notoriously difficult agnostic learning problem. A related task is to find a set of the labelers which are good but not perfect. In this section, we show how to identify the set of all good labelers, when at least the majority of the labelers are good. We consider a setting where the fraction of the perfect labelers, α, is arbitrarily small or 0. We further assume that at least half of the labelers are good, while others have considerably worst performance. More formally, we are given a set of labelers g1 , . . . , gn and a distribution D with an unknown target classifier f ∗ ∈ F. We assume that more than half of these labelers are “good”, that is they have error of ≤ ǫ on distribution D. On the other hand, the remaining labelers, which we call “bad”, have error rates ≥ 4ǫ on distribution D. We are interested in identifying all of the good labelers with high probability by querying the labelers on an unlabeled sample set drawn from D|X . This model presents an interesting community structure: Two good labelers agree on at least 1 − 2ǫ fraction of the data, while a bad and a good labeler agree on at most 1 − 3ǫ of the data. Note that the rate of agreement between two bad labelers can be arbitrary. This is due to the fact that there can be multiple bad labelers with the same classification function, in which case they completely agree with each other, or two bad labelers who disagree on the classification of every instance. This structure serves as the basis of Algorithm 4 and its analysis. Here we provide an overview of its working and analysis. Algorithm 4 G OOD L ABELER D ETECTION Input: Given n labelers, parameters ǫ and δ Let G = ([n], ∅) be a graph on n vertices with no edges. Take set Q of 16 ln(2)n random pairs of nodes from G. 1 for (i, j) ∈ Q do if DISAGREE (i, j) < 2.5ǫ then add edge (i, j) to G; end 2 Let C be the set of connected components of G each with ≥ n/4 nodes.  S 3 for i ∈ [n] \ C and C ∈ C do C∈C Take one node j ∈ C, if DISAGREE (i, j) < 2.5ǫ add edge (i, j) to G. end return The largest connected component of G DISAGREE (i, j): Take set S ofPΘ( 1ǫ ln( nδ )) samples from D. 1 return |S| x∈S 1(gi (x)6=gj (x)) . 14 Theorem 5.1 (Informal). Suppose that any good labeler i is such that errD (gi ) ≤ ǫ. Furthermore, assume that errD (gj ) 6∈ (ǫ, 4ǫ) for any j ∈ [n]. And let the number of good labelers be at least ⌊ n2 ⌋ + 1. Then, Algorithm  4, returns the set of all good labeler with probability 1 − δ, using an expected load of λ = O 1ǫ ln nδ per labeler. We view the labelers as nodes in a graph that has no edges at the start of the algorithm. In step 1, the algorithm takes O(n) random pairs of labelers  and estimates their level of disagreement by querying them on an unlabeled sample set of size O 1ǫ ln nδ and measuring their empirical disagreement. By an application of Chernoff bound, we know that with probability 1 − δ, for any i, j ∈ [n], D ISAGREE (i, j) − Pr [gi (x) 6= gj (x)] < x∼D|X ǫ . 2 Therefore, for any pair of good labelers i and j tested by the algorithm, D ISAGREE (i, j) < 2.5ǫ, and for any pair of labelers i and j that one is good and the other is bad, D ISAGREE (i, j) ≥ 2.5ǫ. Therefore, the connected components of such a graph only include labelers from a single community. Next, we show that at step 2 of Algorithm 4 with probability 1 − δ there exists at least one connected component of size n/4 of good labelers. To see this we first prove that for any two good labelers i and j, the probability of (i, j) existing is at least Θ(1/n). Let Vg be the set of nodes corresponding to good labelers. For i, j ∈ Vg , we have   2 ln(2) 1 4 ln(2)n 4 ln(2) ≈ ≥ . Pr[(i, j) ∈ G] = 1 − 1 − 2 n n |Vg | By the properties of random graphs, with very high probability there is a component of size β|Vg | in a random graph whose edges exists with probability c/|Vg |, for β + e−βc = 1 [Janson et al., 2011]. Therefore, with probability 1 − δ, there is a component of size |Vg |/2 > n/4 over the vertices in Vg . Finally, at step 3 the algorithm considers smaller connected components and tests whether they join any of the bigger components, by measuring the disagreement of two arbitrary labelers from these components.,At this point, all good labelers form one single connected component of size > n2 . So, the algorithm succeeds in identifying all good labelers. Next, we briefly discuss the expected load per labeler in Algorithm 4. Each labeler participates in O(1) pairs of disagreement tests in expectation, each requiring O( 1ǫ ln(n/δ)) queries. So, in expectation each labeler labels O( 1ǫ ln(n/δ)) instances. References M. Anthony and P. L. Bartlett. Neural Network Learning: Theoretical Foundations. Cambridge University Press, 1999. Pranjal Awasthi, Maria Florina Balcan, Nika Haghtalab, and Ruth Urner. Efficient learning of linear separators under bounded noise. In Proceedings of the 28th Conference on Computational Learning Theory (COLT), pages 167–190, 2015. Pranjal Awasthi, Maria-Florina Balcan, Nika Haghtalab, and Hongyang Zhang. Learning and 1-bit compressed sensing under asymmetric noise. In Proceedings of the 29th Conference on Computational Learning Theory (COLT), pages 152–192, 2016. Ashwinkumar Badanidiyuru, Robert Kleinberg, and Yaron Singer. Learning on a budget: posted price mechanisms for online procurement. In Proceedings of the13thACM Conference on Economics and Computation (EC), pages 128–145. ACM, 2012. 15 Ashwinkumar Badanidiyuru, Robert Kleinberg, and Aleksandrs Slivkins. Bandits with knapsacks: Dynamic procurement for crowdsourcing. In The 3rd Workshop on Social Computing and User Generated Content, co-located with ACM EC, 2013. Maria-Florina Balcan, A. Beygelzimer, and J. Langford. Agnostic active learning. In Proceedings of the23rdInternational Conference on Machine Learning (ICML), pages 65–72. ACM, 2006. O. Bousquet, S. Boucheron, and G. Lugosi. Theory of classification: a survey of recent advances. ESAIM: Probability and Statistics, 9:323–375, 2005. D. Cohn, L. Atlas, and R. Ladner. Improving generalization with active learning. Machine Learning, 15(2), 1994. Sanjoy Dasgupta. Coarse sample complexity bounds for active learning. In Proceedings of the 19th Annual Conference on Neural Information Processing Systems (NIPS), 2005. Ofer Dekel and Ohad Shamir. Vox populi: Collecting high-quality labels from a crowd. In Proceedings of the 22nd Conference on Computational Learning Theory (COLT), 2009. Willliam Feller. An introduction to probability theory and its applications, volume 2. John Wiley & Sons, 2008. Yoav Freund. Boosting a weak learning algorithm by majority. In Proceedings of the 22nd Conference on Computational Learning Theory (COLT), volume 90, pages 202–216, 1990. Yoav Freund and Robert E Schapire. A desicion-theoretic generalization of on-line learning and an application to boosting. In European conference on computational learning theory, pages 23–37. Springer, 1995. S. Hanneke. Rates of convergence in active learning. The Annals of Statistics, 39(1):333–361, 2011. Chien-Ju Ho, Shahin Jabbari, and Jennifer Wortman Vaughan. Adaptive task assignment for crowdsourced classification. Proceedings of the 30th International Conference on Machine Learning (ICML), 2013. Panagiotis G Ipeirotis, Foster Provost, and Jing Wang. Quality management on amazon mechanical turk. In Proceedings of the International Conference on Knowledge Discovery and Data Mining (KDD), pages 64–67. ACM, 2010. Svante Janson, Tomasz Luczak, and Andrzej Rucinski. Random graphs, volume 45. John Wiley & Sons, 2011. David R Karger, Sewoong Oh, and Devavrat Shah. Iterative learning for reliable crowdsourcing systems. In Proceedings of the 25th Annual Conference on Neural Information Processing Systems (NIPS), pages 1953–1961, 2011. David R Karger, Sewoong Oh, and Devavrat Shah. Budget-optimal task allocation for reliable crowdsourcing systems. Operations Research, 62(1):1–24, 2014. Aniket Kittur, Ed H Chi, and Bongwon Suh. Crowdsourcing user studies with mechanical turk. In Proceedings of the SIGCHI conference on human factors in computing systems, pages 453–456. ACM, 2008. V. Koltchinskii. Rademacher complexities and bounding the excess risk in active learning. Journal of Machine Learning Research, 11:2457–2485, 2010. 16 Ronald L Rivest and Robert Sloan. A formal model of hierarchical concept-learning. Information and Computation, 114(1):88–114, 1994. Robert E Schapire. The strength of weak learnability. Machine learning, 5(2):197–227, 1990. Adish Singla and Andreas Krause. Truthful incentives in crowdsourcing tasks using regret minimization mechanisms. In Proceedings of the 22nd international conference on World Wide Web, pages 1167–1178. ACM, 2013. Aleksandrs Slivkins and Jennifer Wortman Vaughan. Online decision making in crowdsourcing markets: Theoretical challenges. ACM SIGecom Exchanges, 12(2):4–23, 2014. Jacob Steinhardt, Gregory Valiant, and Moses Charikar. Avoiding imposters and delinquents: Adversarial crowdsourcing and peer prediction. In Proceedings of the 30th Annual Conference on Neural Information Processing Systems (NIPS), pages 4439–4447, 2016. Long Tran-Thanh, Sebastian Stein, Alex Rogers, and Nicholas R Jennings. Efficient crowdsourcing of unknown experts using bounded multi-armed bandits. Artificial Intelligence, 214:89–111, 2014. L. G. Valiant. A theory of the learnable. Communications of the ACM, 27(11):1134–1142, 1984. Paul Wais, Shivaram Lingamneni, Duncan Cook, Jason Fennell, Benjamin Goldenberg, Daniel Lubarov, David Marin, and Hari Simons. Towards building a high-quality workforce with mechanical turk. Presented at the NIPS Workshop on Computational Social Science and the Wisdom of Crowds, pages 1–5, 2010. Songbai Yan, Kamalika Chaudhuri, and Tara Javidi. Active learning from imperfect labelers. In Proceedings of the 30th Annual Conference on Neural Information Processing Systems (NIPS), pages 2128–2136, 2016. Chicheng Zhang and Kamalika Chaudhuri. Active learning from weak and strong labelers. In Proceedings of the 29th Annual Conference on Neural Information Processing Systems (NIPS), pages 703–711, 2015. 17 A Additional Related Work More generally, interactive models of learning have been studied in the machine learning community. The most popular among them is the area of active learning [Cohn et al., 1994, Dasgupta, 2005, Balcan et al., 2006, Koltchinskii, 2010, Hanneke, 2011]. In this model, the learning algorithm can adaptively query for the labels of a few examples in the training set and use them to produce an accurate hypothesis. The goal is to use as few label queries as possible. The number of labeled queries used is called the label complexity of the algorithm. It is known that certain hypothesis classes can be learned in this model using much fewer labeled queries than predicted by the VC theory. In particular, in many instances the label complexity scales only logarithmically in 1ǫ as opposed to linearly in 1ǫ . However, to achieve computational efficiency, the algorithms in this model rely on the fact that one can get perfect labels for every example queried. This would be hard to achieve in our model since in the worst case it would lead to each labeler answering log( dǫ ) many queries. In contrast, we want to keep the query load of a labeler to a constant and hence the techniques developed for active learning are insufficient for our purposes. Furthermore, in noisy settings most work on efficient active learning algorithms assumes the existence of an empirical risk minimizer (ERM) oracle that can minimize training error even when the instances aren’t labeled according to the target classifier. However, in most cases such an ERM oracle is hard to implement and the improvements obtained in the label complexity are less drastic in such noisy scenarios. Another line of work initiated by Zhang and Chaudhuri [2015] models related notions of weak and strong labelers in the context of active learning. The authors study scenarios where the label queries to the strong labeler can be reduced by querying the weak and potentially noisy labelers more often. However, as discussed above, the model does not yield relevant algorithms for our setting as in the worst case one might end up querying for dǫ high quality labels leading to a prohibitively large load per labeler in our setting. The work of Yan et al. [2016] studies a model of active learning where the labeler abstains from providing a label prediction more often on instances that are closer to the decision boundary. The authors then show how to use the abstentions in order to approximate the decision boundary. Our setting is inherently different, since we make no assumptions on the bad labelers. B Proof of Lemma 4.2 First, notice that because D and D ′ are both labeled according to f ∗ ∈ F, for any f ∈ F we have, X X d′ (x)1f (x)6=f ∗ (x) ≥ c · d(x)1f (x)6=f ∗ (x) = c · errD (f ). errD′ (f ) = x x Therefore, if errD′ (f ) ≤ cǫ, then errD (f ) ≤ ǫ. Let m′ = mcǫ,δ , we have δ> ≥ Pr [∃f ∈ F, s.t. errS ′ (f ) = 0 ∧ errD′ (f ) ≥ cǫ] Pr [∃f ∈ F, s.t. errS ′ (f ) = 0 ∧ errD (f ) ≥ ǫ]. S ′ ∼D ′m′ S ′ ∼D ′m′ The claim follows by the fact that mcǫ,δ = O C 1 c mǫ,δ  . Proof of Lemma 4.7 Let us first consider the expected size of sets SI , W I , and W C . Using Lemma 4.6, we have   √ √ √ 1 1 1 O(m√ǫ,δ ) ≥ ǫ|S2 | + ǫ|S2 | ≥ E[|SI |] ≥ ǫ |S2 | ≥ Ω(m√ǫ,δ ). 2 2 2 18 Similarly, O(m√ 1 ǫ,δ ) ≥ E[SI ] + |SC | ≥ E[W I ] ≥ 2   1√ ǫ |S2 | ≥ Ω(m√ǫ,δ ). 2 Similarly, O(m√ ǫ,δ ) ≥ E[SI ] + |SC | ≥ E[W C ] ≥   1√ 1− ǫ |SC | ≥ Ω(m√ǫ,δ ). 2 The claim follows by the Chernoff bound. D Remainder of the Proof of Lemma 4.9 We prove that the Bernstein inequality holds for the total number of queries y1 , y2 , . . . , made before their majority agrees with f ∗ (x). Let Lx be the random variable denoting the number of queries the algorithm makes on instance x for which h(x) = f ∗ (x). Consider the probability that Lx = 2k +1 for some k. That is, Maj(y1:t ) = f ∗ (x) for the first time when t = 2k + 1. This is at most the probability that Maj(y1:2k−1 ) 6= f ∗ (x). By Chernoff bound, we have that   2 2 ∗ Pr[Lx = 2k + 1] ≤ Pr[Maj(y1:2k−1 ) 6= f (x)] ≤ exp −0.7(2k − 1)( ) /2 7 ≤ exp (−0.02(2k − 1)) . For each i > 1, we have i E[(Lx − E[Lx ]) ] ≤ ≤ ∞ X k=0 ∞ X Pr[Lx = 2k + 1](2k + 1 − E[Lx ])i e−0.02(2k−1) (2k + 1)i k=0 0.04 ≤e ≤ e0.04 ∞ X e−0.02(2k+1) (2k + 1)i k=0 ∞ X e−0.02k ki k=0 ≤ 50(i + 1)! e4i+0.04 , where the last inequality is done by integration. This satisfies the Bernstein condition stated in Theorem E.2. Therefore, # " X Lx − |S| E[Lx ] ≥ O(|S|)] ≤ exp (−|S|) . Pr x∈S Therefore, the total number of queries over all points in x ∈ S where h(x) = f ∗ (x) is at most O(|S|) with very high probability. E Probability Lemmas Theorem E.1 (Probability of Ruin [Feller, 2008]). Consider a player who starts with i dollars against an adversary that has N dollars. The player bets one dollar in each gamble, which he wins with probability p. 19 The probability that the player ends up with no money at any point in the game is  N p 1 − 1−p  N +i . p 1 − 1−p Theorem E.2 (Bernstein Inequality). Let X1 , . . . , Xn be independent random variables with expectation µ. Supposed that for some positive real number L and every k > 1, 1 E[(Xi − µ)k ] ≤ E[(Xi − µ)2 ]Lk−2 k!. 2 Then, v   u n n X uX 1 p E[(Xi − µ)2 ]. Pr  E[(Xi − µ)2 ] < exp(−t2 ), for 0 < t ≤ Xi − nµ ≥ 2tt 2L i=1 F i=1 Omitted Proofs from Section 4.1 In this section, we prove Theorem 4.13 and present the proofs that were omitted from Section 4.1. Theorem 4.13 (restated) Suppose the fraction of the perfect labelers is α and let δ′ = Θ(αδ). Algorithm 3 uses oracle OF , runs in time poly(d, α1 , 1ǫ , ln( 1δ )), uses a training set of size O( α1 mǫ,δ′ ) size and with probability 1 − δ returns f ∈ F with errD (f ) ≤ ǫ using O( α1 ) golden queries, load of α1 per labeler, and a total number of queries   m√ǫ,δ′ 1 1 1 1 √ 1 mǫ,δ′ + log( ′ ) log( ′ ) + 3 m ǫ,δ′ log( ) . O α αǫ δ ǫδ α δ′  m√  ǫ,δ 1 Note that when α21√ǫ ≥ log ) < d, the cost per labeled query is O( α1 ). and log( αδ αδ F.1 Proof of Lemma 4.10 By Chernoff bound, with probability ≥ 1 − δ, for every x ∈ S we have that α |Maj-sizeP (x) − Maj-sizeL (x)| ≤ , 8 where L is the set of labelers P RUNE - AND -L ABEL (S, δ) queries on x. Hence, if x is such that Maj-sizeP (x) ≤ 1 − α2 , then it will be identified and the set of labelers is pruned. Otherwise, MajL (x) agrees with the good labelers and x gets labeled correctly according to the target function. F.2 Proof of Lemma 4.11 Recall that δ′ = c · αδ for some small enough constant c > 0. Each time P RUNE - AND -L ABEL (S, δ′ ) is called, by Hoeffding bound, it is guaranteed that with probability ≥ 1 − δ′ , for each x ∈ S, α |Maj-sizeP (x) − Maj-sizeL (x)| ≤ , 8 ′ where L is the set of labelers P RUNE - AND -L ABEL (S, δ ) queries on x. Hence, when we issue a golden query for x such that Maj-sizeL (x) ≤ 1 − α4 and prune away bad labelers, we are guaranteed to remove at least an α8 fraction of the labelers. Furthermore, no good labeler is ever removed. Hence, the fraction of good labelers increases from α to α/(1 − α8 ). So, in O( α1 ) calls, the fraction of the good labelers surpasses 3 4 and we switch to using Algorithm 2. Therefore, with probability 1 − δ overall, the total number of golden queries is O(1/α). 20 F.3 Proof of Lemma 4.12 Let B be the set of points that do not satisfy the condition that d′ (x) ≥ c · d(x). Notice that because D and D ′ are both labeled according to f ∗ ∈ F, for any f ∈ F we have, X X X d′ (x)1f (x)6=f ∗ (x) + d′ (x)1f (x)6=f ∗ (x) ≥ c · d(x)1f (x)6=f ∗ (x) ≥ c · (errD (f ) − ǫ). errD′ (f ) = x∈B x∈B / x∈B / Therefore, if errD′ (f ) ≤ cǫ, then errD (f ) ≤ 2ǫ. Let m′ = mcǫ,δ , we have δ> ≥ Pr [∃f ∈ F, s.t. errS ′ (f ) = 0 ∧ errD′ (f ) ≥ cǫ] Pr [∃f ∈ F, s.t. errS ′ (f ) = 0 ∧ errD (f ) ≥ 2ǫ]. S ′ ∼D ′m′ S ′ ∼D ′m′ The claim follows by the fact that mcǫ,δ = O F.4 Proof of Theorem 4.13 1 c mǫ,δ  . Recall that δ′ = c · αδ for a small enough constant c > 0. Let B = {x | Maj-sizeP (x) ≤ 1 − α/2} be the set of good test cases and and let β = D[B] be the total density on such points. Note that if β > 4ǫ , with high probability S0 includes one such point, in which case P RUNE - AND -L ABEL identifies it and prunes the set √ of labelers. Therefore, we can assume that β ≤ 4ǫ . By Lemma 4.10, it is easy to see that errD (h1 ) ≤ 12 ǫ. √ We now analyze the filtering step of Phase 2. As in Section 4, our goal is to argue that errD2 (h2 ) ≤ 12 ǫ. Consider distribution D ′ that has equal probability on the distributions induced by WI and WC and let d′ (x) denote the density of point x in this distribution. We will show that for any x ∈ / B we have that ǫ 1√ ′ ′ d (x) = Θ(d2 (x)). Since D[B] ≤ 4 , we have that D2 [B] ≤ 4 ǫ. Therefore, D and D2 satisfy the conditions of the robust super-sampling lemma (Lemma 4.12) where the fraction of bad points is at most √ ǫ 1√ 4 . Hence, errD2 (h2 ) ≤ 2 ǫ. We now show that for any x ∈ B, d′ (x) = Θ(d2 (x)). The proof is identical to the one in Lemma 4.8. √ For ease of representation, we assume that errD (h1 ) is exactly 12 ǫ. Let d(x), d2 (x), dC (x), and dI (x) be the density of instance x in distributions D, D2 , DC , and DI , respectively. Note that, for any x such that √ h1 (x) = f ∗ (x), we have d(x) = dC (x)(1 − 21 ǫ). Similarly, for any x such that h1 (x) 6= f ∗ (x), we have √ d(x) = dI (x) 12 ǫ. Let NC (x), NI (x), MC (x) and MI (x) be the number of occurrences of x in the sets SC , SI , WC and WI , respectively. For any x, there are two cases: If h1 (x) = f ∗ (x): Then, there exist absolute constants c1 and c2 according to Lemma 4.7, such that   |SC | · d(x) MC (x) 1 E[MC (x)] E[NC (x)] ′ = d (x) = E ≥ ≥ √ √ 2 c · m c · m c1 · m√ǫ,δ |WC | 1 1 ǫ,δ ǫ,δ √ |SC | · dC (x) · (1 − 12 ǫ) c2 d2 (x) ≥ c2 dC (x) = = , √ c1 · m ǫ,δ 2 where the second and sixth transitions are by the sizes of WC and |SC | and the third transition is by the fact that if h(x) = f ∗ (x), MC (x) > NC (x). If h1 (x) 6= f ∗ (x): Then, there exist absolute constants c′1 and c′2 according to Lemma 4.7, such that   MI (x) E[MI (x)] E[NI (x)] 0.5 d(x)|S2 | 1 ′ ≥ ′ ≥ ′ ≥ ′ d (x) = E √ √ 2 c1 · m ǫ,δ c1 · m ǫ,δ c1 · m√ǫ,δ |WI | 21 √ 0.5 dI (x) 21 ǫ · |S2 | c′2 d2 (x) ′ , = = c d (x) = I 2 c′1 · m√ǫ,δ 2 where the second and sixth transitions are by the sizes of WI and |S2 |, the third transition is by the fact that if h(x) 6= f ∗ (x), MI (x) > NI (x), and the fourth transition holds by part 2 of Lemma 4.6. √ Finally, we have that errD3 (h3 ) ≤ 21 ǫ, where D3 is distribution D conditioned on {x | h1 (x) 6= h2 (x)}. Using the boosting technique of Schapire [1990] describe in Theorem 4.1, we conclude that MAJ (h1 , h2 , h3 ) has error ≤ ǫ on D. The label complexity claim follows by the fact that we restart Algorithm 3 at most O(1/α) times, take an additional O( 1ǫ log( δ1′ )) high quality labeled set, and each run of Algorithm 3 uses the same label complexity as in Theorem 4.3 before getting restarted. 22
8 (cs.DS)
Automated Identification of Trampoline Skills Using Computer Vision Extracted Pose Estimation Paul W. Connolly, Guenole C. Silvestre and Chris J. Bleakley arXiv:1709.03399v1 [cs.CV] 11 Sep 2017 School of Computer Science, University College Dublin, Belfield, Dublin 4, Ireland. Abstract A novel method to identify trampoline skills using a single video camera is proposed herein. Conventional computer vision techniques are used for identification, estimation, and tracking of the gymnast’s body in a video recording of the routine. For each frame, an open source convolutional neural network is used to estimate the pose of the athlete’s body. Body orientation and joint angle estimates are extracted from these pose estimates. The trajectories of these angle estimates over time are compared with those of labelled reference skills. A nearest neighbour classifier utilising a mean squared error distance metric is used to identify the skill performed. A dataset containing 714 skill examples with 20 distinct skills performed by adult male and female gymnasts was recorded and used for evaluation of the system. The system was found to achieve a skill identification accuracy of 80.7% for the dataset. 1 Introduction Originating in the 1930s, trampolining became a competitive Olympic sport in Sydney 2000. In competition, athletes perform a routine consisting of a series of skills performed over a number of jumps. The skills are scored by human judges according to the Trampoline Code of Points [FIG, 2017]. Although more explicit and objective judging criteria have been introduced in recent years, the scores awarded can still vary between judges leading to highly contentious final decisions. Eliminating human error by means of reliable, automated judging of trampoline routines is desirable. Herein, we describe a first step towards this goal: a novel automated system for identification of trampoline skills using a single video camera. Identification of skills is necessary prior to judging since different skills are scored in different ways. While still a challenging problem, identification of trampoline skills from video has been enabled by recent advances in human pose estimation. In [Andriluka et al., 2014], improved accuracy over model-based approaches was achieved with the introduction of convolutional neural network (ConvNet) based estimation. Estimators such as this rely on new ConvNet algorithms coupled with recent gains in GPU performance. In addition, the introduction of larger, more varied general pose datasets [Sapp and Taskar, 2013, Johnson and Everingham, 2011], leveraging crowd-sourced annotation, has vastly increased the quantity of training data available. To the best of the authors’ knowledge, no previous work has been reported on identification of trampolining skills from video. The closest previous work on identification of trampoline skills required the gymnast to wear a full-body motion capture suit containing inertial sensors [Helten et al., 2011]. Wearing special suits is cumbersome and is not allowed in competition due to the strict rules regarding gymnast attire [FIG, 2017]. Previous work on automated judging of rhythmic gymnastics from video was reported in [Díaz-Pereira et al., 2014]. However, their method differs from the method used in this work. The algorithm proposed herein consists of a number of stages. The bounding box of the gymnast is extracted using conventional image processing techniques. The pose of the athlete is subsequently determined, allowing body orientation and joint angles to be estimated. The angle trajectories over time are compared with those obtained for reference skills. The skill performed is identified as the nearest neighbour in the reference dataset based on a mean square error metric. The system was evaluated using a large number of video recordings capturing the movements of male and female gymnasts performing trampoline routines. A wide variety of skills, lighting conditions, and backgrounds were recorded. The gymnasts did not wear special clothes or markers. The camera was placed side-on to the performance, in the same position as a human judge. The structure of the paper is as follows. In section 2, background information on trampolining is given. In section 3, further detail is provided on approaches to analysis of sporting movement and pose estimation using video recordings. The proposed algorithm is described in section 4. Section 5 discusses the experimental procedure and organisation of the dataset. The experimental results and discussion are provided in section 6. Conclusions, including future work, follow in section 7. 2 Background A trampoline routine consists of a sequence of high, continuous rhythmic rotational jumps performed without hesitation or intermediate straight bounces. The routine should show good form, execution, height, and maintenance of height in all jumps so as to demonstrate control of the body during the flying phase. A competition routine consists of 10 such jumps, referred to, in this work, as skills. For simplicity, a straight bounce is taken to be a skill. A competitor can perform a variable number of straight bounces before the beginning of a routine (so called in-bounces) while an optional straight bounce (out-bounce) can be taken after completing a routine, to control height before the gymnast is required to stop completely. Skills involve take-off and landing in one of four positions: feet, seat, front, or back. Rotations about the body’s longitudinal and lateral axes are referred to as twist and somersault rotations, respectively. Skills combine these rotations with a body shape: tuck, pike, straddle, or straight. These take-off and landing positions and shapes are illustrated in Figure 1. The score for a performance is calculated as the sum of four metrics: degree of difficulty (tariff), execution, horizontal displacement, and time of flight. Degree of difficulty is scored based on the difficulty of the skill performed. For example, a full somersault is awarded more points than a three-quarter somersault. The tariff assigned is found by a simple look-up based on skill identification. Examples of tariff scores can be seen in Table 2. The execution score is allocated based on how well the skill was judged to be performed. The horizontal displacement and the time of flight are measured electronically using force plates on the legs of the trampoline. 3 Related Work One of the problems with the capture of trampoline skills is the large performance space. Elite performers can reach up to 10m in height. Tracking such a large volume is prohibitively difficult for many existing motion capture solutions including RGB-D devices such as the Microsoft Kinect. In [Helten et al., 2011], inertial sensors were used to measure body point acceleration and orientation. The gymnast was required to wear a body suit containing ten inertial measurement units. The sensor data streams were transformed into a feature sequence for classification. For each skill, a motion template was learned. The feature sequence of the unknown trampoline motions were compared with a set of skill templates using a variant of dynamic time warping. The best accuracy achieved was 84.7% over 14 skill types. A survey of vision-based methods for general human motion representation, segmentation and recognition can be found in [Weinland et al., 2011]. In [Díaz-Pereira et al., 2014], judging of rhythmic gymnastics skills from video was investigated. The movement of the gymnast was tracked using optical flow. Velocity field information was extracted across all frames of a skill and projected into a velocity covariance eigenspace. Similar movements were found to trace out unique, but similar, trajectories. New video recordings were classified based on their distance from reference trajectories. The system’s specificity was approximately 85% and the sensitivity was approximately 90% for the 3 skills considered. (a) (b) (c) (d) (e) (f) (g) (h) Figure 1: Take-off and landing positions: (a) feet, (b) seat, (c) front and (d) back. Trampoline shapes: (e) tuck, (f) pike, (g) straddle and (h) straight. Human pose estimation is the process of estimating the configuration of the body, typically from a single image. Robust 2D pose estimation has proven to be a powerful starting point for obtaining 3D pose estimates for human bodies. An overview of the 2D pose estimation problem and proposed methods can be found in [Sigal, 2011, Poppe, 2007]. Model-based methods have been successful for images in which all the limbs of the subject are visible. However, they are unsuitable for the side-on view of a trampoline routine where self-occlusions are inherent. ConvNet based systems do not assume a particular explicit body model since they learn the mapping between image and body pose. These machine learning based techniques provide greater robustness to variations in clothing and accessories than model-based approaches. The MPII benchmark [Andriluka et al., 2014] has been used to access the accuracy of pose estimators. The model-based approach described in [Pishchulin et al., 2013] achieved an accuracy of 44.1% whereas the ConvNet based method proposed in [Newell et al., 2016] achieved 90.9%. The work described herein differs from previous work in that the system performs skill identification for trampolining using a single monocular video camera. The work takes advantage of recently developed, high accuracy, open source ConvNet based pose estimators. The Stacked Hourglass Network [Newell et al., 2016] and MonoCap [Zhou et al., 2016] methods were selected for estimation and filtering of the 2D pose, respectively. In the Stacked Hourglass Network, 2D pose estimates are provided by a ConvNet architecture where features are processed across all scales and consolidated to best capture the spatial relationships of the body parts. Repeated steps of pooling and upsampling, in conjunction with intermediate supervision, out-perform previous methods. In MonoCap, 3D pose is estimated via an expectation-maximization algorithm over a sequence of images with 2D pose predictions. Conveniently, the 2D joint location uncertainties can be marginalized out during inference. 4 Proposed Algorithm The complete algorithm is illustrated in Figure 2. Video is recorded and pre-processed to reduce resolution and remove audio. After pre-processing, the body extraction stage identifies and tracks the convex hull of the athlete over all video frames. The video is segmented according to the detected bounces. The feature extraction stage estimates the pose of the athlete and from this, the body orientation and joint angles in each frame. Based on the extracted feature angles, classification is performed to identify the skill. In our experiments, the accuracy Segment Bounces Record Footage Label Ground Truth Skill Downsample Video Subtract Background Track Gymnast Dim & Blur Background Save Video Frames Estimate Pose Filter Pose Temporally Calculate Angles Identify Skill Annotation Classification Body Extraction Feature Extraction Calculate Accuracy Evaluation Figure 2: Flow chart illustrating the proposed method. of the system was evaluated by comparing the detected skills to manually marked ground truth. The algorithm stages are explained in more detail in the following sections. 4.1 Body Extraction The top of the trampoline is identified based on its hue characteristics and is presented as a best guess on a user interface that allows the position to be fine tuned. The gymnast is tracked by assuming that they are the largest moving object above the trampoline. A background subtractor generates a foreground mask for each frame. All static image components over multiple frames are taken to be part of the background. The camera is assumed to be static without changing focus during the recording. The foreground mask is eroded for one iteration and dilated for ten iterations with a 2 × 2 kernel. The largest segment of this morphed mask is taken to be the silhouette of the gymnast. The method of moments is used to determine the centroid of this silhouette. The video is segmented into individual skills based on the position of this centroid. A peak detection algorithm identifies the local minima of the vertical position of the centroid. These local minima are taken to indicate the start and end frames of a skill. A threshold is applied to peaks between the local minima to identify the start and end jumps of the routine. The convex hull of the silhouette is used to generate a bounding box for the athlete’s image. The bottom of the bounding box is compared to the position of the top of the trampoline to detect the contact phase of a bounce. Examples of the application of this method are shown in Figure 3. Images of the body are saved for frames in which the athlete is not in contact with the trampoline. The maximum size of the bounding box across all frames of the routine is found. Each image is squarely cropped to this size, centred on the centroid of the gymnast. Based on the extracted foreground mask, the background of each image is blurred and darkened. This helps to reduce the number of incorrect pose estimates. (a) (b) (c) (d) Figure 3: Processed images. (a) Original frame. (b) Background model. (c) Foreground mask. (d) Body silhouette and convex hull after erosion and dilation. i θi (t ) 1, 2 R, L Elbow 3, 4 R, L Shoulder 5, 6 R, L Hip 7, 8 R, L Knee 9, 10 R, L Leg 11 Torso 12 Twist Table 1: Feature angles by name and index. 4.2 Feature Extraction The Stacked Hourglass Network and MonoCap are used for 2D pose estimation and filtering, respectively. The 2D pose estimator generates pose predictions for 16 joint locations. The 3D pose estimator is then used to filter the 2D pose predictions across the sequence of images. From the smoothed 2D pose, the 2D joint angles and orientation angles that represent the athlete’s body position are calculated. These feature angles are denoted as θ i for i ∈ [1 . . . M ] where M = 12 is the total number of feature angles. Each of the M feature angles is part of a time series θi (t ), where t is the frame number, t ∈ [1 . . . T ]. The angles are listed in Table 1 and example trajectories can be seen in Figure 4. Twist around the body’s longitudinal axis is estimated from the 2D distance between the pose points labelled as right and left shoulder. The shoulder separation in the image is at a maximum when the gymnast’s back or front is facing the camera and is approximately zero when sideways to the camera. By finding the maximum 2D separation over the whole routine, the separation can be normalised to a value between 0°and 180°. In this way, the angle does not depend on the size of the performer. Right Angle (deg) 180 Torso with Vertical Left Elbow Shoulder Hip Knee Leg with Vertical Twist Angle Torso & Twist 135 90 45 0 0.5 1.0 0.5 1.0 0.5 1.0 0.5 1.0 0.5 1.0 0.5 1.0 Time (s) Figure 4: The motion sequence of a tuck jump with the estimated angles shown beneath. 4.3 Classification The M feature angle trajectories are compared to those in a labelled reference set by calculation of the mean squared error (MSE). The observed skill is identified as equivalent to the reference giving the minimum MSE. The feature angle trajectories of the references θ Ri (t ) are aligned through re-sampling by means of interpolation so as to have the same number of data points T as the observed angle trajectory θO i (t ). MSE = T X M ¡ ¢2 1 X R θO i (t ) − θ i (t ) T M t =1 i =1 (1) 5 5.1 Experimental Procedure Data Acquisition The procedure for data collection was submitted to and approved by the UCD Office of Research Ethics. Videos of routines were recorded at training sessions and competitions of the UCD Trampoline Club. Consent was sought from members of the UCD Trampoline Club prior to recording video for the purposes of the project. Routines were collected in UCD Sports Centre under normal sports hall lighting conditions. The background was not modified, typically consisting of a brick wall or nets. The routines were recorded at a resolution of 1920 × 1080 at 30 frames per second (fps) using a consumer grade camera with a shutter speed of 1/120 to reduce motion blur. The camera was positioned at the typical location and viewing angle of the judging panel. All bounces were within the field of view of the camera. The video was subsequently downsampled to 896 × 504, maintaining a 16:9 aspect ratio, and audio was removed. These steps significantly reduced data file size and processing time while maintaining usable resolution. The videos were manually annotated with ground-truth labels by means of a custom built web interface. 5.2 Datasets The resulting dataset consists of 49 routines by 30 adult athletes, 18 male and 31 female, totalling 23 minutes of video. This contained 28 distinct skills and 771 skill examples. The names and distribution of these skills are summarised in Table 2. The accuracy of the identification algorithm was tested using 10-fold cross validation. The skills with fewer than 10 examples were not included in the test, leaving N = 20 distinct skills. In each iteration of the evaluation, a subset of 10 examples of each skill were randomly selected from the database. Each subset was split evenly to give the number of reference examples S r = 5 and the number of test examples S t = 5. The total size of the reference set was N × S r = 100 skill examples. The test set was of the same size. The average accuracy over 20 iterations of the evaluation is reported herein. 6 Results and Discussion The average accuracy of the system was 80.7% for the 20 distinct skills listed as included in classification in Table 2. The confusion matrix for the experiment is shown in Figure 5. It was noted that subject identification can sometimes incorrectly focus on people in the background, particularly during seat, front and back landings, when the gymnast becomes obscured by the trampoline bed. This causes errors in trampoline contact detection resulting in frames without an obvious subject being presented to the pose estimator. The resulting angles are not representative of the skill performed. This can also cause errors in jump segmentation due to incorrect centroid extraction. Jump segmentation failed in 2 cases. Significant confusion in skill identification occurs between FPF (pike jumps shown in Figure 1f) and FSF (straddle jumps shown in Figure 1g). From a side-on view, it is difficult to distinguish these movements. Another area of confusion is between the tuck and pike shape of the Barani skill (BRI). The features which distinguish these shapes are the angles of the hip and knees. The tuck shape in this skill is often performed loosely. This results in the angle of the hip being similar to that of the pike shape. For identification, the angle of the knees becomes the deciding feature and may be overwhelmed by noise from other features. Use of a support vector machine might improve classification accuracy. For example, the difficulty in estimating the wrist and ankle joints for the 2D pose estimator can lead to noise in the angles for the elbows and knees. Weighting these features as less important might improve overall accuracy. Tariff Occurrences Straight Bounce Tuck Jump Pike Jump Straddle Jump Half Twist Jump Full Twist Jump Seat Drop Half Twist to Seat Drop Seat Half Twist To Seat To Feet from Seat Half Twist to Feet from Seat Front Drop To Feet from Front Back Drop To Feet from Back Half Twist to Feet from Back Front Somersault (Tuck) Front Somersault (Pike) Barani (Tuck) Barani (Pike) Barani (Straight) Crash Dive Back Somersault (Tuck) Back Somersault (Pike) Back Somersault (Straight) Back Somersault to Seat (Tuck) Lazy Back Cody (Tuck) Back Half Barani Ball Out (Tuck) Rudolph / Rudi Full Front Full Back F0F FTF FPF FSF F1F F2F F0S F1S S1S S0F S1F F0R R0F F0B B0F B1F FSSt FSSp BRIt BRIp BRIs CDI BSSt BSSp BSSs BSTt LBK CDYt BHA BBOt RUI FFR FUB 0.0 0.0 0.0 0.0 0.1 0.2 0.0 0.1 0.1 0.0 0.1 0.1 0.1 0.1 0.1 0.2 0.5 0.6 0.6 0.6 0.6 0.3 0.5 0.6 0.6 0.5 0.3 0.6 0.6 0.7 0.8 0.7 0.7 286 58 40 42 18 19 13 10 24 11 24 4† 5† 10 8† 12 4† 7† 24 19 9† 18 28 18 30 10 3† 3† 1† 7† 3† 1† 2† F0F FTF FPF FSF F1F F2F F0S F1S S1S S0F S1F F0B B1F BRIt BRIp CDI BSSt BSSp BSSs BSTt F0F FTF FPF FSF F1F F2F F0S F1S S1S S0F S1F F0B B1F BRIt BRIp CDI BSSt BSSp BSSs BSTt Code Ground Truth Skill Skill Name Identified Skill Figure 5: Confusion matrix showing the relative errors for each skill. This is the average of 20 iterations of 10-fold cross validation. Table 2: Skill dataset. († excluded from classification) It is likely that accuracy could be improved by increasing the amount of data. Current pose estimation algorithms take a single image as input. It seems likely that performance could be improved by tracking pose over a video sequence. Adding a second video camera pointed towards the front of the gymnast would likely improve accuracy by allowing greater discrimination of motion parallel to the axis between the subject and the first camera. However, there are issues regarding the extra user effort in setting up the second camera and in synchronisation of the two devices. Modern trampoline judging systems incorporate force plates for detection of the centrality of landing on the trampoline bed. Fusing such information with the video data could possibly also result in improved accuracy. Body extraction was performed at 15 fps on a 2 core Intel i7–3517U 2.4 GHz CPU. Estimation of pose using the Stacked Hourglass Network ran at 20 fps on an Ubuntu 16.04 with an Nvidia Titan X (Pascal) GPU and a 4 core Intel i7–920 2.67 GHz CPU with default parameter settings. Execution of the MonoCap algorithm ran at 0.3 fps on the same machine also with default parameters. 7 Conclusion A system for identifying trampolining skills using a single monocular video camera was developed. The system incorporated algorithms for background subtraction, erosion and dilation, pose estimation, pose filtering and classification. The system was found to provide 80.7% accuracy in identifying the 20 distinct skills present in a dataset contain 712 skill examples. In future work, we plan to extend the classification algorithms to perform automated execution judging. References [Andriluka et al., 2014] Andriluka, M., Pishchulin, L., Gehler, P., and Schiele, B. (2014). 2D Human Pose Estimation: New Benchmark and State of the Art Analysis. In 2014 IEEE Conference on Computer Vision and Pattern Recognition (CVPR), pages 3686–3693. [Díaz-Pereira et al., 2014] Díaz-Pereira, M. P., Gómez-Conde, I., Escalona, M., and Olivieri, D. N. (2014). Automatic recognition and scoring of olympic rhythmic gymnastic movements. Human Movement Science, 34:63–80. [FIG, 2017] FIG (2017). Trampoline Code Of Points. [Accessed 2017-03-30]. [Helten et al., 2011] Helten, T., Brock, H., Müller, M., and Seidel, H.-P. (2011). Classification of trampoline jumps using inertial sensors. Sports Engineering, 14(2):155–164. [Johnson and Everingham, 2011] Johnson, S. and Everingham, M. (2011). Learning effective human pose estimation from inaccurate annotation. In 2011 IEEE Conference on Computer Vision and Pattern Recognition (CVPR), pages 1465–1472. [Newell et al., 2016] Newell, A., Yang, K., and Deng, J. (2016). Stacked Hourglass Networks for Human Pose Estimation. CoRR, abs/1603.06937. [Pishchulin et al., 2013] Pishchulin, L., Andriluka, M., Gehler, P., and Schiele, B. (2013). Poselet conditioned pictorial structures. In 2013 IEEE Conference on Computer Vision and Pattern Recognition (CVPR), pages 588–595. [Poppe, 2007] Poppe, R. (2007). Vision-based human motion analysis: An overview. Computer Vision and Image Understanding, 108(1–2):4–18. Special Issue on Vision for Human-Computer Interaction. [Sapp and Taskar, 2013] Sapp, B. and Taskar, B. (2013). MODEC: Multimodal Decomposable Models for Human Pose Estimation. In 2013 IEEE Conference on Computer Vision and Pattern Recognition (CVPR), pages 3674–3681. [Sigal, 2011] Sigal, L. (2011). Human pose estimation. [Accessed 2017-03-30]. [Weinland et al., 2011] Weinland, D., Ronfard, R., and Boyer, E. (2011). A survey of vision-based methods for action representation, segmentation and recognition. Computer Vision and Image Understanding, 115(2):224–241. [Zhou et al., 2016] Zhou, X., Zhu, M., Leonardos, S., Derpanis, K. G., and Daniilidis, K. (2016). Sparseness Meets Deepness: 3D Human Pose Estimation from Monocular Video. In 2016 IEEE Conference on Computer Vision and Pattern Recognition (CVPR), pages 4966–4975.
1 (cs.CV)
Parsing methods streamlined arXiv:1309.7584v1 [cs.FL] 29 Sep 2013 Luca Breveglieri Stefano Crespi Reghizzi Angelo Morzenti Dipartimento di Elettronica, Informazione e Bioingegneria (DEIB) Politecnico di Milano Piazza Leonardo Da Vinci 32, I-20133 Milano, Italy email: { luca.breveglieri, stefano.crespireghizzi, angelo.morzenti }@polimi.it This paper has the goals (1) of unifying top-down parsing with shift-reduce parsing to yield a single simple and consistent framework, and (2) of producing provably correct parsing methods, deterministic as well as tabular ones, for extended context-free grammars (EBNF ) represented as state-transition networks. Departing from the traditional way of presenting as independent algorithms the deterministic bottom-up LR (1), the top-down LL (1) and the general tabular (Earley) parsers, we unify them in a coherent minimalist framework. We present a simple general construction method for EBNF ELR (1) parsers, where the new category of convergence conflicts is added to the classical shift-reduce and reduce-reduce conflicts; we prove its correctness and show two implementations by deterministic push-down machines and by vector-stack machines, the latter to be also used for Earley parsers. Then the Beatty’s theoretical characterization of LL (1) grammars is adapted to derive the extended ELL (1) parsing method, first by minimizing the ELR (1) parser and then by simplifying its state information. Through using the same notations in the ELR (1) case, the extended Earley parser is obtained. Since all the parsers operate on compatible representations, it is feasible to combine them into mixed mode algorithms. Categories and Subject Descriptors: parsing [of formal languages]: theory General Terms: language parsing algorithm, syntax analysis, syntax analyzer Additional Key Words and Phrases: extended BNF grammar, EBNF grammar, deterministic parsing, shift-reduce parser, bottom-up parser, ELR (1), recursive descent parser, top-down parser, ELL (1), tabular Earley parser October 1, 2013 0 See Formal Languages and Compilation, S. Crespi Reghizzi, L. Breveglieri, A. Morzenti, Springer, London, 2nd edition, (planned) 2014 2 · Parsing methods streamlined Contents 1 Introduction 3 2 Preliminaries 2.1 Derivation for machine nets . . . . . . . . . . . . . . . . . . . . . . . . . 2.1.1 Right-linearized grammar . . . . . . . . . . . . . . . . . . . . . 2.2 Call sites, machine activation, and look-ahead . . . . . . . . . . . . . . . 4 8 8 9 3 Shift-reduce parsing 3.1 Construction of ELR (1) parsers . . . . . . . . . . . . . . 3.1.1 Base closure and kernel of a m-state . . . . . . . . 3.2 ELR (1) condition . . . . . . . . . . . . . . . . . . . . . . 3.2.1 ELR (1) versus classical LR (1) definitions . . . . . 3.2.2 Parser algorithm . . . . . . . . . . . . . . . . . . 3.3 Simplified parsing for BNF grammars . . . . . . . . . . . 3.4 Parser implementation using an indexable stack . . . . . . 3.5 Related work on shift-reduce parsing of EBNF grammars. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 11 12 14 14 17 21 23 24 Deterministic top-down parsing 4.1 Single-transition property and pilot compaction . . . . 4.1.1 Merging kernel-identical m-states . . . . . . . 4.1.2 Properties of compact pilots . . . . . . . . . . 4.1.3 Candidate identifiers or pointers unnecessary . 4.2 ELL (1) condition . . . . . . . . . . . . . . . . . . . . 4.2.1 Discussion . . . . . . . . . . . . . . . . . . . 4.3 Stack contraction and predictive parser . . . . . . . . . 4.3.1 Parser control-flow graph . . . . . . . . . . . . 4.3.2 Predictive parser . . . . . . . . . . . . . . . . 4.3.3 Computing left derivations . . . . . . . . . . . 4.3.4 Parser implementation by recursive procedures 4.4 Direct construction of parser control-flow graph . . . . 4.4.1 Equations defining the prospect sets . . . . . . 4.4.2 Equations defining the guide sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 28 30 30 32 36 36 38 38 41 42 43 43 43 44 5 Tabular parsing 5.1 String recognition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.2 Syntax tree construction . . . . . . . . . . . . . . . . . . . . . . . . . . 45 46 50 6 Conclusion 52 7 Appendix 55 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . Parsing methods streamlined · 3 1. INTRODUCTION In many applications such as compilation, program analysis, and document or natural language processing, a language defined by a formal grammar has to be processed using the classical approach based on syntax analysis (or parsing) followed by syntax-directed translation. Efficient deterministic parsing algorithms have been invented in the 1960’s and improved in the following decade; they are described in compiler related textbooks (for instance [Aho et al. 2006; Grune and Jacobs 2004; Crespi Reghizzi 2009]), and efficient implementations are available and widely used. But research in the last decade or so has focused on issues raised by technological advances, such as parsers for XML-like datadescription languages, more efficient general tabular parsing for context-free grammars, and probabilistic parsing for natural language processing, to mention just some leading research lines. This paper has the goals (1) of unifying top-down parsing with shift-reduce parsing and, to a minor extend, also with tabular Earley parsing, to yield a single simple and consistent framework, and (2) of producing provably correct parsing methods, deterministic and also tabular ones, for extended context-free grammars (EBNF) represented as state-transition networks. We address the first goal. Compiler and language developers, and those who are familiar with the technical aspects of parsing, invariably feel that there ought to be room for an improvement of the classical parsing methods: annoyingly similar yet incompatible notions are used in shift-reduce (i.e., LR (1)), top-down (i.e., LL (1)) and tabular Earley parsers. Moreover, the parsers are presented as independent algorithms, as indeed they were when first invented, without taking advantage of the known grammar inclusion properties (LL (k) ⊂ LR (k) ⊂ context-free) to tighten and simplify constructions and proofs. This may be a consequence of the excellent quality of the original presentations (particularly but not exclusively [Knuth 1965; Rosenkrantz and Stearns 1970; Earley 1970]) by distinguished scientists, which made revision and systematization less necessary. Our first contribution is to conceptual economy and clarity. We have reanalyzed the traditional deterministic parsers on the view provided by Beatty’s [Beatty 1982] rigorous characterization of LL (1) grammars as a special case of the LR (1). This allows us to show how to transform shift-reduce parsers into the top-down parsers by merging and simplifying parser states and by anticipating parser decisions. The result is that only one set of technical definitions suffices to present all parser types. Moving to the second goal, the best known shift-reduce and tabular parsers do not accept the extended form of BNF grammars known as EBNF (or ECFG or also as regular rightpart RRPG) that make use of regular expressions, and are widely used in the language reference manuals and are popular among designers of top-down parsers using recursive descent methods. We systematically use a graphic representation of EBNF grammars by means of state-transition networks (also known as syntax charts. Brevity prevents to discuss in detail the long history of the research on parsing methods for EBNF grammars. It suffices to say that the existing top-down deterministic method is well-founded and very popular, at least since its use in the elegant recursive descent Pascal compiler [Wirth 1975] where EBNF grammars are represented by a network of finite-state machines, a formalism already in use since at least [Lomet 1973]). On the other hand, there have been numerous interesting but non-conclusive proposals for shift-reduce methods for EBNF grammars, which operate under more or less general assumptions and are implemented by various 4 · Parsing methods streamlined types of push-down parsers (more of that in Section 3.5). But a recent survey [Hemerik 2009] concludes rather negatively: What has been published about LR-like parsing theory is so complex that not many feel tempted to use it; . . . it is a striking phenomenon that the ideas behind recursive descent parsing of ECFGs can be grasped and applied immediately, whereas most of the literature on LR-like parsing of RRPGs is very difficult to access. . . . Tabular parsing seems feasible but is largely unexplored. We have decided to represent extended grammars as transition diagram systems, which are of course equivalent to grammars, since any regular expression can be easily mapped to its finite-state recognizer; moreover, transition networks (which we dub machine nets) are often more readable than grammar rules. We stress that all our constructions operate on machine nets that represent EBNF grammars and, unlike many past proposals, do not make restrictive assumptions on the form of regular expressions. For EBNF grammars, most past shift-reduce methods had met with a difficulty: how to formulate a condition that ensures deterministic parsing in the presence of recursive invocations and of cycles in the transition graphs. Here we offer a simple and rigorous formulation that adds to the two classical conditions (neither shift-reduce nor reduce-reduce conflicts) a third one: no convergence conflict. Our shift-reduce parser is presented in two variants, which use different devices for identifying the right part or handle (typically a substring of unbounded length) to be reduced: a deterministic pushdown automaton, and an implementation, to be named vector-stack machine, using unbounded integers as pointers into the stack. The vector-stack device is also used in our last development: the tabular Earley-like parser for EBNF grammars. At last, since all parser types described operate on uniform assumptions and use compatible notations, we suggest the possibility to combine them into mixed-mode algorithms. After half a century research on parsing, certain facts and properties that had to be formally proved in the early studies have become obvious, yet the endemic presence of errors or inaccuracies (listed in [Hemerik 2009]) in published constructions for EBNF grammars, warrants that all new constructions be proved correct. In the interest of readability and brevity, we first present the enabling properties and the constructions semi-formally also relying on significant examples; then, for the properties and constructions that are new, we provide correctness proofs in the appendix. The paper is organized as follows. Section 2 sets the terminology and notation for grammars and transition networks. Section 3 presents the construction of shift-reduce ELR (1) parsers. Section 4 derives top-down ELL (1) parsers, first by transformation of shift-reduce parsers and then also directly. Section 5 deals with tabular Earley parsers. 2. PRELIMINARIES The concepts and terminology for grammars and automata are classical (e.g., see [Aho et al. 2006; Crespi Reghizzi 2009]) and we only have to introduce some specific notations. A BNF or context-free grammar G is specified by the terminal alphabet Σ, the set of nonterminal symbols V , the set of rules P and the starting symbol or axiom S. An element of Σ ∪ V is called a grammar symbol. A rule has the form A → α, where A, the left part, is a nonterminal and α, the right part, is a possibly empty (denoted by ε) string over Parsing methods streamlined · 5 Σ ∪ V . Two rules such as A → α and A → β are called alternative and can be shortened to A → α | β. An Extended BNF (EBNF) grammar G generalizes the rule form by allowing the right part to be a regular expression (r.e.) over Σ ∪ V . A r.e. is a formula that as operators uses union (written “|”), concatenation, Kleene star and parentheses. The language defined by a r.e. α is denoted R (α). For each nonterminal A we assume, without any loss of generality, that G contains exactly one rule A → α. A derivation between strings is a relation u A v ⇒ u w v, with u, w and v possibly empty strings, and w ∈ R (α). The derivation is leftmost (respectively rightmost), if u does not contain a nonterminal (resp. if v does not contain a nonterminal). A series of ∗ ∗ derivations is denoted by ⇒. A derivation A ⇒ A v, with v 6= ε, is called left-recursive. For a derivation u ⇒ v, the reverse relation is named reduction and denoted by v ❀ u. ∗ The language L (G) generated by grammar G is the set L (G) = { x ∈ Σ∗ | S ⇒ x }. ∗ The language L (A) generated by nonterminal A is the set LA (G) = { x ∈ Σ∗ | A ⇒ x }. A language is nullable if it contains the empty string. A nonterminal that generates a nullable language is also called nullable. Following a tradition dating at least to [Lomet 1973], we are going to represent a grammar rule A → α as a graph: the state-transition graph of a finite automaton to be named machine1 MA that recognizes a regular expression α. The collection M of all such graphs for the set V of nonterminals, is named a network of finite machines and is a graphic representation of a grammar (see Fig. 1). This has well-known advantages: it offers a pictorial representation, permits to directly handle EBN F grammars and maps quite nicely on the recursive-descent parser implementation. In the simple case when α contains just terminal symbols, machine MA recognizes the language LA (G). But if α contains a nonterminal B, machine MA has a state-transition edge labeled with B. This can be thought of as the invocation of the machine MB associated to rule B → β; and if nonterminals B and A coincide, the invocation is recursive. It is convenient although not necessary, to assume that the machines are deterministic, at no loss of generality since a nondeterministic finite state machine can always be made deterministic. Definition 2.1. Recursive net of finite deterministic machines. —Let G be an EBN F grammar with nonterminal set V = { S, A, B, . . . } and grammar rules S → σ, A → α, B → β, . . . —Symbols RS , RA , RB , . . . denote the regular languages over alphabet Σ ∪ V , respectively defined by the r.e. σ, α, β, . . . —Symbols MS , MA , MB , . . . are the names of finite deterministic machines that accept the corresponding regular languages RS , RA , RB , . . . . As usual, we assume the machines to be reduced, in the sense that every state is reachable from the initial state and reaches a final state. The set of all machines, i.e., the (machine) net, is denoted by M. —To prevent confusion, the names of the states of any two machines are made different by appending the machine name as subscript. The set of states of machine MA is QA = 1 To avoid confusion we call “machines” the finite automata of grammar rules, and we reserve the term “automaton” for the pushdown automaton that accepts language L (G). 6 · Parsing methods streamlined Machine net M EBNF grammar G T E → T∗ ME → 0E 1E ↓ ↓ T a T → ‘(’ E ‘)’ | a MT → 0T 1T ( 3T → 2T E ) Fig. 1. EBN F grammar G (axiom E) and machine network M = { ME , MT } (axiom ME ) of the running example 2.2; initial (respectively final) states are tagged by an incoming (resp. outgoing) dangling dart. { 0A , . . . , qA , . . . }, the initial state is 0A and the S set of final states is FA ⊆ QA . The state set of the net is the union of all states Q = MA ∈M QA . The transition function of every machine is denoted by the same symbol δ, at no risk of confusion as the state sets are disjoint. —For state qA of machine MA , the symbol R (MA , qA ) or for brevity R (qA ), denotes the regular language of alphabet Σ ∪ V accepted by the machine starting from state qA . If qA is the initial state 0A , language R (0A ) ≡ RA includes every string that labels a path, qualified as accepting, from the initial to a final state. —Normalization disallowing reentrance into initial states. To simplify the parsing algoc rithms, we stipulate that for every machine MA no edge qA −→ 0A exists, where qA ∈ QA and c is a grammar symbol. In words, no edges may enter the initial state. The above normalization ensures that the initial state 0A is not visited again within a computation that stays inside machine MA ; clearly, any machine can be so normalized by adding one state and a few transitions, with a negligible overhead. Such minor adjustment greatly simplifies the reduction moves of bottom-up parsers. For an arbitrary r.e. α, several well-known algorithms such as MacNaughton-Yamada and Berry-Sethi (described for instance in [Crespi Reghizzi 2009]) produce a machine recognizing the corresponding regular language. In practice, the r.e. used in the right parts of grammars are so simple that they can be immediately translated by hand into an equivalent machine. We neither assume nor forbid that the machines be minimal with respect to the number of states. In facts, in syntax-directed translation it is not always desirable to use the minimal machine, because different semantic actions may be required in two states that would be indistinguishable by pure language theoretical definitions. If the grammar is purely BN F then each right part has the form α = α1 | α2 | . . . | αk , where every alternative αi is a finite string; therefore RA is a finite language and any machine for RA has an acyclic graph, which can be made into a tree if we accept to have a non-minimal machine. In the general case, the graph of machine MA representing rule A → α is not acyclic. In any case there is a one-to-one mapping between the strings in language RA and the set of accepting paths of machine MA . Therefore, the net M = { MS , MA , . . . } is essentially a notational variant of a grammar G, as witnessed by the common practice to include both EBN F productions and syntax diagrams in language specifications. We indifferently denote the language as L (G) or as L (M). Parsing methods streamlined · 7 We need also the context-free terminal language defined by the net, starting from a state qA of machine MA possibly other than the initial one: n o ∗ L (MA , qA ) ≡ L (qA ) = y ∈ Σ∗ | η ∈ R (qA ) and η ⇒ y In the formula, η is a string over terminals and nonterminals, accepted by machine MA starting from state qA . The derivations originating from η produce the terminal strings of language L (qA ). In particular, from previous definitions it follows that: L (MA , 0A ) ≡ L (0A ) = LA (G) and L (MS , 0S ) ≡ L (0S ) ≡ L (M) = L (G) Example 2.2. Running example. The EBN F grammar G and machine net M are shown in Figure 1. The language generated can be viewed as obtained from the language of well-parenthesized strings, by allowing character a to replace a well-parenthesized substring. All machines are deterministic and the initial states are not reentered. Most features needed to exercise different aspects of parsing are present: self-nesting, iteration, branching, multiple final states and the nullability of a nonterminal. To illustrate, we list a language defined by its net and component machines, along with their aliases: R (ME , 0E ) = R (0E ) = T ∗  R (MT , 1T ) = R (1T ) = E L (ME , 0E ) = L (0E ) = L (G) = L (M) = { ε, a, a a, ( ), a a a, ( a ), a ( ), ( ) a, ( ) ( ), . . . } L (MT , 0T ) = L (0T ) = LT (G) = { a, ( ), ( a ), ( a a ), ( ( ) ), . . . } To identify machine states, an alternative convention quite used for BN F grammars, relies on marked grammar rules: for instance the states of machine MT have the aliases: 0T ≡ T → • a | • ( E ) 2T ≡ T → ( E • ) 1T ≡ T → ( • E ) 3T ≡ a • | T → ( E ) • where the bullet is a character not in Σ. We need to define the set of initial characters for the strings recognized starting from a given state. Definition 2.3. Set of initials. Ini (qA ) = Ini L (qA )  = { a ∈ Σ | a Σ∗ ∩ L (qA ) 6= ∅ } The set can be computed by applying the following logical clauses until a fixed point is reached. Let a be a terminal, A, B, C nonterminals, and qA , rA states of the same machine. The clauses are: a a ∈ Ini (qA ) if ∃ edge qA −→ rA B a ∈ Ini (qA ) if ∃ edge qA −→ rA ∧ a ∈ Ini (0B ) B a ∈ Ini (qA ) if ∃ edge qA −→ rA ∧ L (0B ) is nullable ∧ a ∈ Ini (rA ) To illustrate, we have Ini (0E ) = Ini (0T ) = { a, ( }. 8 · Parsing methods streamlined 2.1 Derivation for machine nets For machine nets and EBN F grammars, the preceding definition of derivation, which models a rule such as E → T ∗ as the infinite set of BN F alternatives E → ε | T | T T | . . ., has shortcomings because a derivation step, such as E ⇒ T T T , replaces a nonterminal E by a string of possibly unbounded length; thus a multi-step computation inside a machine is equated to just one derivation step. For application to parsing, a more analytical definition is needed to split such large step into a series of state transitions. We recall that a BN F grammar is right-linear (RL) if the rule form is A → a B or A → ε, where a ∈ Σ and B ∈ V . Every finite-state machine can be represented by an equivalent RL grammar that has the machine states as nonterminal symbols. 2.1.1 Right-linearized grammar. Each machine MA of the net can be replaced with an equivalent right linear RL grammar, to be used to provide a rigorous semantic for the derivations constructed by our parsers. It is straightforward to write the RL grammar, named ĜA , equivalent with respect to the regular language R (MA , 0A ). The nonterminals of ĜA are the states of QA , and the axiom is 0A ; there exists a rule pA → X rA if an edge X pA −→ rA is in δ, and the empty rule pA → ε if pA is a final state. Notice that X can be a nonterminal B of the original grammar, therefore a rule of ĜA may have the form pA → B rA , which is still RL since the first symbol of the right part as a “terminal” symbol for grammar ĜA . With this provision, the identity   is viewed L ĜA = R (MA , 0A ) clearly holds. Next, for every RL grammar of the net we replace with 0B each symbol B ∈ V occurring in a rule such as pA → B rA , and thus we obtain rules of the form pA → 0B rA . The resulting BN F grammar, non-RL, is denoted Ĝ and named the right-linearized grammar of the net: it has terminal alphabet Σ, nonterminal set Q and axiom 0S . The right parts have length zero or two, and may contain two nonterminal symbols, thus the grammar is not RL. Obviously, Ĝ and G are equivalent, i.e., they both generate language L (G). Example 2.4. Right-linearized grammar Ĝ of the running example. ĜE : 0E → 0T 1E | ε 1E → 0T 1E | ε ĜT : 0T → a 3T | ( 1T 1T → 0E 2T 2T →) 3T 3T → ε As said, in right-linearized grammars we choose to name nonterminals by their alias states; an instance of non-RL rule is 1T → 0E 2T . Using Ĝ instead of G, we obtain derivations the steps of which are elementary state transitions instead of an entire sub-computation on a machine. An example should suffice. Example 2.5. Derivation. For grammar G the “classical” leftmost derivation: E ⇒ T T ⇒ aT ⇒ a(E ) ⇒ a() G G G G (1) Parsing methods streamlined · 9 is expanded into the series of truly atomic derivation steps of the right-linearized grammar: 0E ⇒ 0T 1E ⇒ a 1E ⇒ a 0T 1E Ĝ Ĝ Ĝ ⇒ a ( 1T 1E ⇒ a ( 0E 2T 1E ⇒ a ( ε 2T 1E Ĝ Ĝ Ĝ ⇒ a ( ) 3T 1E ⇒ a ( ) ε 1E ⇒ a()ε Ĝ Ĝ Ĝ (2) = a() We may also work bottom-up and consider reductions such as a ( 1T 1E ❀ a 0T 1E . As said, the right-linearized grammar is only used in our proofs to assign a precise semantic to the parser steps, but has otherwise no use as a readable specification of the language to be parsed. Clearly, an RL grammar has many more rules than the original EBN F grammar and is less readable than a syntax diagram or machine net, because it needs to introduce a plethora of nonterminal names to identify the machine states. 2.2 Call sites, machine activation, and look-ahead B An edge labeled with a nonterminal, qA −→ rA , is named a call site for machine MB , and rA is the corresponding return state. Parsing can be viewed as a process that at call sites activates a machine, which on its own graph performs scanning operations and further calls until it reaches a final state, then performs a reduction and returns. Initially the axiom machine, MS , is activated by the program that invokes the parser. At any step in the derivation, the nonterminal suffix of the derived string contains the current state of the active machine followed by the return points of the suspended machines; these are ordered from right to left according to their activation sequence. Example 2.6. Derivation and machine return points. ∗ Looking at derivation (2), we find 0E ⇒ a ( 0E 2T 1E : machine ME is active and its current state is 0E ; previously machine MT was suspended and will resume in state 2T ; an earlier activation of ME was also suspended and will resume in state 1E . Upon termination of MB when MA resumes in return state rA , the collection of all the first legal tokens that can be scanned is named the look-ahead set of this activation of MB ; this intuitive concept is made more precise in the following definition of a candidate. By inspecting the next token, the parser can avoid invalid machine call actions. For uniformity, when the input string has been entirely scanned, we assume the next token to be the special character ⊣ (string terminator or end-marker). A 1-candidate (or 1-item), or simply a candidate since we exclusively deal with lookahead length 1, is a pair hqB , ai in Q × ( Σ ∪ {⊣} ). The intended meaning is that token a is a legal look-ahead token for the current activation of machine MB . We reformulate the classical [Knuth 1965] notion of closure function for a machine net and we use it to compute the set of legal candidates. Definition 2.7. Closure functions. The initial activation of machine MS is encoded by candidate h0S , ⊣i. Let C be a set candidates initialized to {h0S , ⊣i}. The closure of C is the function 10 · Parsing methods streamlined defined by applying the following clauses until a fixed point is reached: c ∈ closure (C) h0B , bi ∈ closure (C) if c ∈ C B if ∃ hq, ai ∈ closure (C) and ∃ edge q −→ r in M  and b ∈ Ini L (r) · a (3) Thus closure functions compute the set of machines reachable from a given call site through one or more invocations, without any intervening state transition. For conciseness, we group together the candidates that have the same state and we write q, { a1 , . . . , ak } instead of { hq, a1 i, . . . , hq, ak i }. The collection { a1 , a2 , . . . , ak } is termed look-ahead set and by definition it cannot be empty. We list a few values of closure function for the grammar of Ex. 2.2: function closure h0E , ⊣i h0E , ⊣i 0T , { ⊣, a, ( } h1T , ⊣i h1T , ⊣i 0E , ) 0T , { a, (, ) } 3. SHIFT-REDUCE PARSING We show how to construct deterministic bottom-up parsers directly for EBN F grammars represented by machine nets. As we deviate from the classical Knuth’s method, which operates on pure BN F grammars, we call our method ELR (1) instead of LR (1). For brevity, whenever some passages are identical or immediately obtainable from classical ones, we do not spend much time to justify them. On the other hand, we include correctness proofs of the main constructions because past works on Extended BN F parsers have been found not rarely to be flawed [Hemerik 2009]. At the end of this section we briefly compare our method with older ones. An ELR (1) parser is a deterministic pushdown automaton (DP DA) equipped with a set of states named macrostates (for short m-states) to avoid confusion with net states. An m-state consists of a set of 1-candidates (for brevity candidate). The automaton performs moves of two types. A shift action reads the current input character (i.e., a token) and applies the P DA state-transition function to compute the next m-state; then the token and the next m-state are pushed on the stack. A reduce action is applied when the grammar symbols from the stack top match a recognizing path on a machine MA and the current token is admitted by the look-ahead set. For the parser to be deterministic in any configuration, if a shift is permitted then reduction should be impossible, and in any configuration at most one should be possible. A reduce action grows bottom-up the syntax forest, pops the matched part of the stack, and pushes the nonterminal symbol recognized and the next m-state. The P DA accepts the input string if the last move reduces to the axiom and the input is exhausted; the latter condition can be expressed by saying that the special end-marker character ⊣ is the current token. The presence of convergent paths in a machine graph complicates reduction moves because two such paths may require to pop different stack segments (so-called reduction handles); this difficulty is acknowledged in past research on shift-reduce methods for EBNF grammars, but the proposed solutions differ in the technique used and in generality. To implement such reduction moves, we enrich the stack organization with pointers, which enable the parser to trace back a recognizing path while popping the stack. Such a pointer Parsing methods streamlined · 11 can be implemented in two ways: as a bounded integer offset that identifies a candidate in the previous stack element, or as an unbounded integer pointer to a distant stack element. In the former case the parser still qualifies as DP DA because the stack symbols are taken from a a finite set. Not so in the latter case, where the pointers are unbounded integers; this organization is an indexable stack to be called a vector-stack and will be also used by Earley parsers. 3.1 Construction of ELR (1) parsers Given an EBN F grammar represented by a machine net, we show how to construct an ELR (1) parser if certain conditions are met. The method operates in three phases: (1) From the net we construct a DF A, to be called a pilot automaton.2 A pilot state, named macro-state (m-state), includes a non empty set of candidates, i.e., of pairs of states and terminal tokens (look-ahead set). (2) The pilot is examined to check the conditions for deterministic bottom-up parsing; the check involves an inspection of the components of each m-state and of the transitions outgoing from it. Three types of failures may occur: shift-reduce or reduce-reduce conflicts, respectively signify that in a parser configuration both a shift and a reduction are possible or multiple reductions; a convergence conflict occurs when two different parser computations that share a look-ahead character, lead to the same machine state. (3) If the test is passed, we construct the deterministic P DA, i.e., the parser, through using the pilot DF A as its finite-state control and adding the operations needed for managing reductions of unbounded length. At last, it would be a simple exercise to encode the P DA in a programming language. For a candidate hpA , ρi and a terminal or nonterminal symbol X, the shift3 under X (qualified as terminal/nonterminal depending on X being a terminal or non- ) is: ( X ϑ ( hpA , ρi , X ) = hqA , ρi if edge pA −→ qA exists the empty set otherwise For a set C of candidates, the shift under a symbol X is the union of the shifts of the candidates in C. Algorithm 3.1. Construction of the ELR (1) pilot graph. The pilot is the DF A, named P, defined by: —the set R of m-states —the pilot alphabet is the union Σ ∪ V of the terminal and nonterminal alphabets —the initial m-state I0 is the set: I0 = closure (h0S , ⊣i) —the m-state set R = { I0 , I1 , . . . } and the state-transition function4 ϑ : R × (Σ ∪ V ) → R are computed starting from I0 by the following steps: R′ := { I0 } do 2 Its traditional lengthy name is “recognizer of viable LR (1) prefixes”. known as “go to” function. 4 Named theta, ϑ, to avoid confusion with the traditional name delta, δ, of the transition function of the net. 3 Also 12 · Parsing methods streamlined R := R′  for all the m-states I ∈ R and symbols X ∈ Σ ∪ V do I ′ := closure  ϑ (I, X) ′ if I 6= ∅ then X add the edge I −→ I ′ to the graph of ϑ if I ′ 6∈ R then add the m-state I ′ to the set R′ end if end if end for  while R 6= R′ 3.1.1 Base closure and kernel of a m-state. For every m-state I the set of candidates is partitioned into two subsets: base and closure. The base includes the non-initial candidates: I|base = { hq, πi ∈ I | q is not an initial state } ′ Clearly, for the m-state I ′ computed at line 3 of the algorithm, the base I|base coincides with the pairs computed by ϑ (I, X). The closure contains the remaining candidates of m-state I: I|closure = { hq, π i ∈ I | q is an initial state } The initial m-state I0 has an empty base by definition. All other m-states have a non-empty base, while the closure may be empty. The kernel of a m-state is the projection on the first component: I|kernel = { q ∈ Q | hq, πi ∈ I } A particular condition that may affect determinism occurs when, for two states that belong to the same m-state I, the outgoing transitions are defined under the same grammar symbol. Definition 3.2. Multiple Transition Property and Convergence. A pilot m-state I has the multiple transition property (M T P ) if it includes two candidates hq, πi and hr, ρi, such that for some grammar symbol X both transitions δ (q, X) and δ (r, X) are defined. Such a m-state I and the pilot transition ϑ (I, X) are called convergent if δ (q, X) = δ (r, X). A convergent transition has a convergence conflict if the look-ahead sets overlap, i.e., if π ∩ ρ 6= ∅. To illustrate, we consider two examples. Example 3.3. Pilot of the running example. The pilot graph P of the EBN F grammar and net of Example 2.2 (see Figure 1) is shown in Figure 2. In each m-state the top and bottom parts contain the base and the closure, respectively; when either part is missing, the double-line side of the m-state shows which part is present (e.g., I0 has no base and I2 has no closure); the look-ahead tokens are grouped by state; and final states are evidenced by encircling. None of the edges of the graph is convergent. Parsing methods streamlined T 0E ⊣ 0T a(⊣ 1E ⊣ 0T a(⊣ T ( a a ( I3 13 I1 I0 P → · 1T a(⊣ 0E ) 0T a() 2T a ( ⊣ E a ( ⊣ I2 3T ) I8 T I4 1E ) 0T a() ( T ( a a T a I6 1T a() 0E ) 0T a() E 2T a ( ) 3T ) a ( ) I5 I7 ( Fig. 2. ELR (1) pilot graph P of the machine net in Figure 1. Two m-states, such as I1 and I4 , having the same kernel, i.e., differing just for some look-ahead sets, are called kernel-equivalent. Some simplified parser constructions to be later introduced, rely on kernel equivalence to reduce the number of m-states. We observe that for any two kernel-equivalent m-states I and I ′ , and for any grammar symbol X, the m-states ϑ (I, X) and ϑ (I ′ , X) are either both defined or neither one, and are kernelequivalent. To illustrate the notion of convergent transition with and without conflict, we refer to Figure 4, where m-states I10 and I11 have convergent transitions, the latter with a conflict. 14 · Parsing methods streamlined 3.2 ELR (1) condition The presence of a final candidate in a m-state tells the parser that a reduction move ought to be considered. The look-ahead set specifies which tokens should occur next, to confirm the decision to reduce. For a machine net, more than one reduction may be applied in the same final state, and to choose the correct one, the parser stores additional information in the stack, as later explained. We formalize the conditions ensuring that all parser decisions are deterministic. Definition 3.4. ELR (1) condition. A grammar or machine net meets condition ELR (1) if the corresponding pilot satisfies the following conditions: Condition 1 . Every m-state I satisfies the next two clauses: no shift-reduce conflict: a for all candidates hq, πi ∈ I s.t. q is final and for all edges I −→ I ′ : a 6∈ π (4) no reduce-reduce conflict: for all candidates hq, πi, hr, ρi ∈ I s.t. q and r are final : π ∩ ρ = ∅ (5) Condition 2 . No transition of the pilot graph has a convergence conflict. The pilot in Figure 2 meets conditions (4) and (5), and no edge of ϑ is convergent. 3.2.1 ELR (1) versus classical LR (1) definitions. First, we discuss the relation between this definition and the classical one [Knuth 1965] in the case that the grammar is BN F , i.e., each nonterminal A has finitely many alternatives A → α | β | . . .. Since the alternatives do not contain star or union operations, a straightforward (nondeterministic) N F A machine, NA , has an acyclic graph shaped as a tree with as many legs originating from the initial state 0A as there are alternative rules for A. Clearly the graph of NA satisfies the no reentrance hypothesis for the initial state. In general NA is not minimal. No m-state in the classical LR (1) pilot machine can exhibit the multiple transition property, and the only requirement for parser determinism comes from clauses (4) and (5) of Def. 3.4. In our representation, machine MA may differ from NA in two ways. First, we assume that machine MA is deterministic, out of convenience not of necessity. Thus consider a nonterminal C with two alternatives, C → if E then I | if E then I else I. Determinization has the effect of normalizing the alternatives by left factoring the longest common prefix, i.e., of using the equivalent EBN F grammar C → if E then I ( ε | else I ). Second, we allow (and actually recommend) that the graph of MA be minimal with respect to the number of states. In particular, the final states of NA are merged together by state reduction if they are undistinguishable for the DF A MA . Also a non-final state of MA may correspond to multiple states of NA . Such state reduction may cause some pilot edges to become convergent. Therefore, in addition to checking conditions (4) and (5), Def. 3.4 imposes that any convergent edge be free from conflicts. Since this point is quite subtle, we illustrate it by the next example. Example 3.5. State-reduction and convergent transitions. Consider the equivalent BN F and EBN F grammars and the corresponding machines in Fig. 3. After determinizing, the states 31 S , 32 S , 33 S , 34 S of machine NS are equivalent Parsing methods streamlined · 15 Grammars BNF EBNF S → abc | abd | bc | Ae S → ab (c | d) | bc | Ae A → aS A → aS Machine nets b 1S a c 2S 31S → a a NS → 0S 1′S b 2′S d MS → 0S 4S c 33S → e 4S 3S → c A 5S A 5S c, d 2S 32S → b b b 1S e 34S → Net Common Part a NA ≡ MA → 0A S 1A 2A → Fig. 3. BN F and EBN F grammars and networks { NS , NA } and { MS , MA ≡ NA }. and are merged into the state 3S of machine MS . Turning our attention to the LR and ELR conditions, we find that the BN F grammar has a reduce-reduce conflict caused by the derivations below: S⇒Ae⇒aSe⇒abce and S ⇒ A e ⇒ a S e ⇒ a a b c e On the other hand, for the EBN F grammar the pilot P{ MS , MA } , shown in Fig. 4, has the two convergent edges highlighted as double-line arrows, one with a conflict and the c other without. Arc I8 → I11 violates the ELR (1) condition because the look-aheads of 2S and 4S in I8 are not disjoint. Notice in Fig.4 that, for explanatory purposes, in m-state I10 the two candidates h3S , ⊣i and h3S , ei deriving from a convergent transition with no conflict, have been kept separate and are not depicted as only one candidate with a single look-ahead, as it is usually done with candidates that have the same state. We observe that in general a state-reduction in the machines of the net has the effect, in the pilot automaton, to transform reduce-reduce violations into convergence conflicts. Next, we prove the essential property that justifies the practical value of our theoretical development: an EBN F grammar is ELR (1) if, and only if, the equivalent rightlinearized grammar (defined in Sect. 2.1.1) is LR (1). T HEOREM 3.6. Let G be an EBN F grammar represented by a machine net M and let Ĝ be the equivalent right-linearized grammar. Then net M meets the ELR (1) condition if, and only if, grammar Ĝ meets the LR (1) condition. The proof is in the Appendix. · 16 Parsing methods streamlined a I1 I0 a 0S 0A b A a 1A 0S e 0A b 4S e 2S I5 4S c convergent 3S ⊣ S 2A e I7 e e ⊣ e I8 c conflictual d 3S I10 e b 2S ⊣ d 4S ⊣ c I9 1S 1A e 0A e I2 I4 1S ⊣ 0S ⊣ S 3S e I11 A e 5S ⊣ I3 A I6 5S e e Fig. 4. Pilot graph of machine net { MS , MA } in Fig. 3; the double-line edges are convergent. Although this proposition may sound intuitively obvious to knowledgeable readers, we believe a formal proof is due: past proposals to extend LR (1) definitions to the EBN F (albeit often with restricted types of regular expressions), having omitted formal proofs, have been later found to be inaccurate (see Sect. 3.5). The fact that shift-reduce conflicts are preserved by the two pilots is quite easy to prove. The less obvious part of the proof concerns the correspondence between convergence conflicts in the ELR (1) pilot and reduce-reduce conflicts in the right-linearized grammar. To have a grasp without reading the proof, the convergence conflict in Fig. 4 corresponds to the reduce-reduce conflict in the m-state I11 of Fig. 21. We address a possible criticism to the significance of Theorem 3.6: that, starting from an EBN F grammar, several equivalent BN F grammars can be obtained by removing the regular expression operations in different ways. Such grammars may or may not be LR (1), a fact that would seem to make somewhat arbitrary our definition of ELR (1), which is based on the highly constrained left-linearized form. We defend the significance and generality of our choice on two grounds. First, our original grammar specification is not a set of r.e.’s, but a set of machines (DF A), and the choice to transform the DF A into a right-linear grammar is standard and almost obliged because, as already shown by [Heilbrunner 1979], the other standard form - left-linear - would exhibit conflicts in most cases. Second, the same author proves that if a right-linearized grammar equivalent to G is LR (1), then every right-linearized grammar equivalent to G, provided it is not ambiguous, is LR (1); besides, he shows that this definition of ELR (1) grammar dominates all the Parsing methods streamlined · 17 preexisting alternative definitions. We believe that also the new definitions of later years are dominated by the present one. To illustrate the discussion, it helps us consider a simple example where the machine net is ELR (1), i.e., by Theorem 3.6 Ĝ is LR (1), yet another equivalent grammar obtained by a very natural transformation, has conflicts. Example 3.7. A phrase S has the structure E ( s E)∗ , where a construct E has either the form b+ bn en or bn en e with n ≥ 0. The language is defined by the ELR (1) net below: s E MS → 0S 1S ↓ 2S E b 4E ↓ e 3E F ME ↓ 0E b 1E F MF ↓ 2E ↓ 0F ↓ b 1F F 2F e 3F ↓ On the contrary, there is a conflict in the equivalent grammar: S → E sS | E E →BF | F e F → bEf | ε B → bB | b caused by the indecision whether to reduce b+ to B or shift. The right-linearized grammar postpones any reduction decision as long as possible and avoids conflicts. 3.2.2 Parser algorithm. Given the pilot DF A of an ELR (1) grammar or machine net, we explain how to obtain a deterministic pushdown automaton DP DA that recognizes and parses the sentences. At the cost of some repetition, we recall the three sorts of abstract machines involved: the net M of DF A’s MS , MA , . . . with state set Q = { q, . . . } (states are drawn as circular nodes); the pilot DF A P with m-state set R = { I0 , I1 , . . . } (states are drawn as rectangular nodes); and the DP DA A to be next defined. As said, the DP DA stores in the stack the series of m-states entered during the computation, enriched with additional information used in the parsing steps. Moreover, the m-states are interleaved with terminal or nonterminal grammar symbols. The current m-state, i.e., the one on top of stack, determines the next move: either a shift that scans the next token, or a reduction of a topmost stack segment (also called reduction handle) to a nonterminal identified by a final candidate included in the current m-state. The absence of shift-reduce conflicts makes the choice between shift and reduction operations deterministic. Similarly, the absence of reduce-reduce conflicts allows the parser to uniquely identify the final state of a machine. However, this leaves open the problem to determine the stack segment to be reduced. For that two designs will be presented: the first uses a finite pushdown alphabet; the second uses unbounded integer pointers and, strictly speaking, no longer qualifies as a pushdown automaton. First, we specify the pushdown stack alphabet. Since for a given net M there are finitely many different candidates, the number of m-states is bounded and the number of candidates in any m-state is also bounded by CMax = |Q| × ( |Σ| + 1 ). The DP DA stack elements 18 · Parsing methods streamlined are of two types: grammar symbols and stack m-states (sms). An sms, denoted by J, contains an ordered set of triples of the form (state, look-ahead, candidate identifier (cid)), named stack candidates, specified as: hqA , π, cidi where qA ∈ Q, π ⊆ Σ ∪ { ⊣ } and 1 ≤ cid ≤ CMax or cid = ⊥ For readability, a cid value will be prefixed by a ♯ marker. The parser makes use of a surjective mapping from the set of sms to the set of m-states, denoted by µ, with the property that µ(J) = I if, and only if, the set of stack candidates of J, deprived of the candidate identifiers, equals the set of candidates of I. For notational convenience, we stipulate that identically subscripted symbols Jk and Ik are related by µ(Jk ) = Ik . As said, in the stack the sms are interleaved with grammar symbols. Algorithm 3.8. ELR (1) parser as DP DA A. Let J[0] a1 J[1] a2 . . . ak J[k] be the current stack, where ai is a grammar symbol and the top element is J[k]. Initialization. The analysis starts by pushing on the stack the sms: J0 = { s | s = hq, π, ⊥i for every candidate hq, πi ∈ I0 } (thus µ(J0 ) = I0 , the initial m-state of the pilot). Shift move. Let the top sms be J, I = µ(J) and the current token be a ∈ Σ. Assume that, by inspecting I, the pilot has decided to shift and let ϑ (I, a) = I ′ . The shift move does: (1) push token a on stack and get next token (2) push on stack the sms J ′ computed as follows: o n a (6) J ′ = hqA ′ , ρ, ♯ii | hqA , ρ, ♯ji is at position i in J ∧ qA → qA ′ ∈ δ o n ′ (7) ∪ h0A , σ, ⊥i | h0A , σi ∈ I|closure (thus µ(J ′ ) = I ′ ) Notice that the last condition in (6) implies that qA ′ is a state of the base of I ′ . Reduction move (non-initial state). The stack is J[0] a1 J[1] a2 . . . ak J[k] and let the corresponding m-states be I[i] = µ ( J[i] ) with 0 ≤ i ≤ k. Assume that, by inspecting I[k], the pilot chooses the reduction candidate c = hqA , πi ∈ I[k], where qA is a final but non-initial state. Let tk = hqA , ρ, ♯ik i ∈ J[k] be the (only) stack candidate such that the current token a ∈ ρ. From ik , a cid chain starts, which links tk to a stack candidate tk−1 = hpA , ρ, ♯ik−1 i ∈ J[k − 1], and so on until a stack candidate th ∈ J[h] is reached that has cid = ⊥ (therefore its state is initial) th = h0A , ρ, ⊥i The reduction move does: (1) grow the syntax forest by applying reduction ah+1 ah+2 . . . ak ❀ A (2) pop the stack symbols in the following order: J[k] ak J[k − 1] ak−1 . . . J[h + 1] ah+1 (3) execute the nonterminal shift move ϑ ( I[h], A ) (see below). Reduction move (initial state). It differs from the preceding case in that the chosen candidate is c = h0A , π, ⊥i. The parser move grows the syntax forest by the reduction ε ❀ A and performs the nonterminal shift move corresponding to ϑ ( I[k], A ). Parsing methods streamlined Machine MA Pilot: I ′ = ϑ (I, a) · 19 Pushdown stack: . . . J a J ′ a ′ qA qA ... B ′′ qA ′ , πi hqA ... a 1 ... −→ ... ... hqA , πi h0B , σi ... ... i hqA ′ , ρ, ♯ii ... ... a hqA , ρ, ♯ji h0B , σ, ⊥i ... ... a ′ (plus completion) in the parser stack with pointers. Fig. 5. Schematization of the shift move qA → qA Nonterminal shift move. It is the same as a shift move, except that the shifted symbol, A, is a nonterminal. The only difference is that the parser does not read the next input token at line (1) of Shift move. Acceptance. The parser accepts and halts when the stack is J0 , the move is the nonterminal shift defined by ϑ ( I0 , S ) and the current token is ⊣. For shift moves, we note that the m-states computed by Alg. 3.1, may contain multiple stack candidates that have the same state; this happens whenever edge I → θ (I, a) is convergent. It may help to look at the situation of a shift move (eq. (6) and (7)) schematized in Figure 5. Example 3.9. Parsing trace. The step by step execution of the parser on input string ( ( ) a ) produces the trace shown in Figure 6. For clarity there are two parallel tracks: the input string, progressively replaced by the nonterminal symbols shifted on the stack; and the stack of stack m-states. The stack has one more entry than the scanned prefix; the suffix yet to be scanned is to the right of the stack. Inside a stack element J[k], each 3-tuple is identified by its ordinal position, starting from 1 for the first 3-tuple; a value ♯i in a cid field of element J[k + 1] encodes a pointer to the i-th 3-tuple of J[k]. To ease reading the parser trace simulation, the m-state number appears framed in each stack element, e.g., I0 is denoted 0 , etc.; the final candidates are encircled, e.g., 1E , etc.; and to avoid clogging, look-ahead sets are not shown as they are only needed for convergent transitions, which do not occur here. But the look-aheads can always be found by inspecting the pilot graph. Fig. 6 highlights the shift moves as dashed forward arrows that link two topmost stack ( candidates. For instance, the first (from the Figure top) terminal shift, on (, is h0T , ⊥i → E h1T , ♯2i. The first nonterminal shift is the third one, on E, i.e., h1T , ♯3i → h2T , ♯1i, after the null reduction ε ❀ E. Similarly for all the other shifts. Fig. 6 highlights the reduction handles, by means of solid backward arrows that link the candidates involved. For instance, see reduction ( E ) ❀ T : the stack configuration above shows the chain of three pointers ♯1, ♯1 and ♯3 - these three stack elements form the handle and are popped - and finally the initial pointer ⊥ - this stack element is the reduction origin and is not popped. The initial pointer ⊥ marks the initial candidate h0T , ⊥i, which is obtained by means of a closure operation applied to candidate h0E , ⊥i in the same stack element, see the dotted arrow that links them, from which the subsequent shift on T starts, see the dashed arrow in the stack configuration below. The solid self-loop on candidate · 20 Parsing methods streamlined string to be parsed (with end-marker) and stack contents stack base effect after 1 2 3 4 5 ( ( ) a ) ⊣ initialisation of the stack ( 3 ( 1T ♯2 0E ⊥ 0T ⊥ ( 1T ♯2 0E ⊥ 0T ⊥ 6 ( 3 ♯2 0E ⊥ 0T ⊥ 6 ( 3 ) 1T ♯3 0E ⊥ 0T ⊥ ( 1T ♯2 0E ⊥ 0T ⊥ ♯3 0E ⊥ 0T ⊥ 6 0 ⊥ 0T ⊥ 3 ♯3 0E ⊥ 0T ⊥ ♯2 0E ⊥ 0T ⊥ 4 ♯2 0E ⊥ 0T ⊥ 4 ( 3 ) 1E ♯2 0T ⊥ ♯2 0T ⊥ ♯2 0E ⊥ 0T ⊥ 4 ) ♯2 0T ⊥ ) 5 3T 4 ♯2 0E ⊥ 0T ⊥ shift on a ) 1E ♯1 0T ⊥ ♯2 0E ⊥ 0T ⊥ ⊣ reduction a ❀ T and shift on T ) ⊣ reduction T T ❀ E and shift on E 8 2T ♯1 ) E 1T ⊣ ♯2 E 1T ⊣ reduction ( E ) ❀ T and shift on T T 1E ( 3 shift on ) a 1E ⊣ ♯1 a ( 3 3T 5 T 1T ⊣ ) a T 1T ) a T 1T ⊣ reduction ε ❀ E and shift on E 7 2T ♯1 ( 3 ) E 1T ) a 7 2T ♯1 ( 0E ⊣ shift on ( E 1T ( 1T ) a shift on ( ( 3 ) 8 2T ♯1 1E ♯1 0T ⊥ E 3T ♯1 shift on ) ⊣ T 1 2 ⊣ reduction ( E ) ❀ T and shift on T ⊣ reduction T ❀ E and accept without shifting on E Fig. 6. Parsing steps for string ( ( ) a ) (grammar and ELR (1) pilot in Figures 1 and 2); the name Jh of a sms maps onto the corresponding m-state µ(Jh ) = Ih . h0E , ⊥i (at the 2nd shift of token ( - see the effect on the line below) highlights the null reduction ε ❀ E, which does not pop anything from the stack and is immediately followed by a shift on E. We observe that the parser must store on stack the scanned grammar symbols, because Parsing methods streamlined · 21 in a reduction move, at step (2), they may be necessary for selecting the correct reduction handle and build the subtree to be added to the syntax forest. Returning to the example, the execution order of reductions is: ε❀E (E ) ❀ T a❀T (E ) ❀ T TT ❀E T ❀E Pasting together the reductions, we obtain this syntax tree, where the order of reductions is displayed: E 6 T 5 ( ) E 4 T T 2 ( 3 E ) a 1 ε Clearly, the reduction order matches a rightmost derivation but in reversed order. It is worth examining more closely the case of convergent conflict-free edges. Returning to Figure 5, notice that the stack candidates linked by a cid chain are mapped onto m′ state candidates that have the same machine state (here the stack candidate hqA , ρ, ♯ii is linked via ♯i to hqA , ρ, ♯ji): the look-ahead set π of such m-state candidates is in general a superset of the set ρ included in the stack candidate, due to the possible presence of convergent transitions; the two sets ρ and π coincide when no convergent transition is taken on the pilot automaton at parsing time. An ELR(1) grammar with convergent edges is studied next. Example 3.10. The net, pilot graph and the trace of a parse are shown in Figure 7, where, for readability, the cid values in the stack candidates are visualized as backward pointing arrows. Stack m-state J3 contains two candidates which just differ in their lookahead sets. In the corresponding pilot m-state I3 , the two candidates are the targets of a convergent non-conflictual m-state transition (highlighted double-line in the pilot graph). 3.3 Simplified parsing for BNF grammars For LR (1) grammars that do not use regular expressions in the rules, some features of the ELR (1) parsing algorithm become superfluous. We briefly discuss them to highlight the differences between extended and basic shift-reduce parsers. Since the graph of every machine is a tree, there are no edges entering the same machine state, which rules out the presence of convergent edges in the pilot. Moreover, the alternatives of a nonterminal, A → α | β | . . ., are recognized in distinct final states qα, A , qβ, A , . . . of machine MA . Therefore, if the candidate chosen by the parser is qα, A , the DP DA simply pops 2 × |α| stack elements and performs the reduction α ❀ A. Since pointers to a preceding stack candidate are no longer needed, the stack m-states coincide with the pilot ones. Second, for a related reason the interleaved grammar symbols are no longer needed on the stack, because the pilot of an LR (1) grammar has the well-known property that all the edges entering an m-state carry the same terminal/nonterminal label. Therefore the reduction handle is uniquely determined by the final candidate of the current m-state. 22 · Parsing methods streamlined Machine Net 2S A MS → 0S a e d 4S → 1S MA → 0A 1A b e 2A → A b 3S Pilot Graph I2 I1 I0 a 0S ⊣ 1S ⊣ I3 3S ⊣ b e 2A 1A d 0A d convergent edge 0A ⊣ A d ⊣ A 4S 2S ⊣ ⊣ d I4 I5 Parse Traces J0 a J1 b J0 J1 1S ⊣ 0S ⊣ 1A d 0A d a e 3S ⊣ 1S ⊣ 0S ⊣ J2 J3 d 2A d 2A ⊣ 0A ⊣ A J4 2S ⊣ d ⊣ J5 4S ⊣ 0A d reductions b e ❀ A (above) and a A d ❀ S (below) Fig. 7. ELR (1) net, pilot with convergent edges (double line) and parsing trace of string a b e d ⊣. ⊣ Parsing methods streamlined · 23 The simplifications have some effect on the formal notation: for BN F grammars the use of machine nets and their states becomes subjectively less attractive than the classical notation based on marked grammar rules. 3.4 Parser implementation using an indexable stack Before finishing with bottom-up parsing, we present an alternative implementation of the parser for EBN F grammars (Algorithm 3.8, p. 18), where the memory of the analyzer is an array of elements such that any element can be directly accessed by means of an integer index, to be named a vector-stack. The reason for presenting the new implementation is twofold: this technique is compatible with the implementation of non-deterministic tabular parsers (Sect. 5) and is potentially faster. On the other hand, a vector-stack as data-type is more general than a pushdown stack, therefore this parser cannot be viewed as a pure DP DA. As before, the elements in the vector-stack are of two alternating types: vector-stack m-states vsms and grammar symbols. A vsms, denoted by J, is a set of triples, named vector-stack candidates, the form of which hqA , π, elemidi simply differs from the earlier stack candidates because the third component is a positive integer named element identifier instead of a cid. Notice also that now the set is not ordered. The surjective mapping from vector-stack m-states to pilot m-states is denoted µ, as before. Each elemid points back to the vector-stack element containing the initial state of the current machine, so that, when a reduction move is performed, the length of the string to be reduced - and the reduction handle - can be obtained directly without inspecting the stack elements below the top one. Clearly the value of elemid ranges from 1 to the maximum vector-stack height. Algorithm 3.11. ELR(1) parser automaton A using a vector-stack. Let J[0] a1 J[1] a2 . . . ak J[k] be the current stack, where ai is a grammar symbol and the top element is J[k]. Initialization. The analysis starts by pushing on the stack the sms: J0 = { s | s = hq, π, 0i for every candidate hq, πi ∈ I0 } (thus µ(J0 ) = I0 , the initial m-state of the pilot). Shift move. Let the top vsms be J, I = µ(J) and the current token be a ∈ Σ. Assume that, by inspecting I, the pilot has decided to shift and let ϑ (I, a) = I ′ . The shift move does: (1) push token a on stack and get next token (2) push on stack the sms J ′ (more precisely, k := k + 1 and J[k] := J ′ ) computed as follows: o n a (8) J ′ = hqA ′ , ρ, ji | hqA , ρ, ji is in J ∧ qA → qA ′ ∈ δ o n ′ (9) ∪ h0A , σ, ki | h0A , σi ∈ I|closure (thus µ(J ′ ) = I ′ ) Reduction move (non-initial state). The stack is J[0] a1 J[1] a2 . . . ak J[k] and let the corresponding m-states be I[i] = µ ( J[i] ) with 0 ≤ i ≤ k. Assume that, by inspecting I[k], the pilot chooses the reduction candidate c = hqA , πi ∈ I[k], where qA is a final but non-initial state. Let tk = hqA , ρ, hi ∈ J[k] be the (only) stack candidate such that the current token a ∈ ρ. 24 · Parsing methods streamlined The reduction move does: (1) grow the syntax forest by applying reduction ah+1 ah+2 . . . ak ❀ A (2) pop the stack symbols in the following order: J[k] ak J[k − 1] ak−1 . . . J[h + 1] ah+1 (3) execute the nonterminal shift move ϑ ( I[h], A ) (see below). Reduction move (initial state). It differs from the preceding case in that the chosen candidate is c = h0A , π, ki. The parser move grows the syntax forest by the reduction ε ❀ A and performs the nonterminal shift move corresponding to ϑ ( I[k], A ). Nonterminal shift move. It is the same as a shift move, except that the shifted symbol, A, is a nonterminal. The only difference is that the parser does not read the next input token at line (1) of Shift move. Acceptance. The parser accepts and halts when the stack is J0 , the move is the nonterminal shift defined by ϑ ( I0 , S ) and the current token is ⊣. Although the algorithm uses a stack, it cannot be viewed as a P DA because the stack alphabet is unbounded since a vsms contains integer values. Example 3.12. Parsing trace. Figure 8, to be compared with Figure 6, shows the same step by step execution of the parser as in Example 3.9, on input string ( ( ) a ); the graphical conventions are the same. In every stack element of type vsms the second field of each candidate is the elemid index, which points back to some inner position of the stack; elemid is equal to the current stack position for all the candidates in the closure part of a stack element, and points to some previous position for the candidates of the base. As in Figure 6, the reduction handles are highlighted by means of solid backward pointers, and by a dotted arrow to locate the candidate to be shifted soon after reducing. Notice that now the arrows span a longer distance than in Figure 6, as the elemid goes directly to the origin of the reduction handle. The forward shift arrows are the same as those in Fig. 6 and are here not shown. The results of the analysis, i.e., the execution order of the reductions and the obtained syntax tree, are identical to those of Example 3.9. We illustrate the use of the vector-stack on the previous example of a net featuring a convergent edge (net in Figure 7): the parsing traces are shown in Figure 9, where the integer pointers are represented by backward pointing solid arrows. 3.5 Related work on shift-reduce parsing of EBNF grammars. Over the years many contributions have been published to extend Knuth’s LR (k) method to EBN F grammars. The very number of papers, each one purporting to improve over previous attempts, testifies that no clear-cut optimal solution has been found. Most papers usually start with critical reviews of related proposals, from which we can grasp the difficulties and motivations then perceived. The following discussion particularly draws from the later papers [Morimoto and Sassa 2001; Kannapinn 2001; Hemerik 2009]. The first dichotomy concerns which format of EBN F specification is taken as input: either a grammar with regular expressions in the right parts, or a grammar with finiteautomata (F A) as right parts. Since it is nowadays perfectly clear that r.e. and F A are interchangeable notations for regular languages, the distinction is no longer relevant. Yet some authors insisted that a language designer should be allowed to specify syntax constructs by arbitrary r.e.’s, even ambiguous ones, which allegedly permit a more flexible Parsing methods streamlined stack base string to be parsed (with end-marker) and stack contents (with indices) 0 · 25 effect after 1 2 3 4 5 ( ( ) a ) ⊣ initialisation of the stack ( 1T 3 ( 0E 1 0T 1 3 ( 0 0E 1 0T 1 3 6 1T 6 0E 2 0T 2 1 0E 2 0T 2 0 1T 1 1 6 0 0 0T 0 1T 3 1 1 0E 2 0T 2 7 2T 1 4 ( 1T 3 0E 1 0T 1 0 0E 1 0T 1 3 1 0T 2 4 4 ) 1 0T 2 ) 5 3T 1 0T 2 4 ⊣ 2 shift on a ) T 1E ⊣ reduction ( E ) ❀ T and shift on T a 1E 1E 1 0T 3 ⊣ reduction a ❀ T and shift on T ) E 1 0T 1 ⊣ reduction T T ❀ E and shift on E 8 2T 0 ( 3 shift on ) 0 0E 1T ⊣ 1 a 1E ( 1T 3T 5 T 1T ) a T 0 ( 3 ) T 0T ⊣ reduction ε ❀ E and shift on E E 0 0E ) a 1 ( 0E ) 7 2T 1 ( 0T ⊣ shift on ( E 1 0E ) a 1 0T ( 3 ⊣ 1 ( 0 0E 1T ) 1T ( 1T ) a shift on ( ( 1T ) 0 ) E ⊣ 0 0E 1 0T 1 8 2T 0 2 1E 0 0T 1 E 0 shift on ) ⊣ T 1 3T reduction ( E ) ❀ T and shift on T ⊣ reduction T ❀ E and accept without shifting on E Fig. 8. Tabulation of parsing steps of the parser using a vector-stack for string ( ( ) a ) generated by the grammar in Figure 1 having the ELR (1) pilot of Figure 2. 26 · Parsing methods streamlined Pilot Graph I2 I1 I0 a 0S ⊣ 1S ⊣ I3 3S ⊣ b e 2A 1A d 0A d 0A ⊣ A d ⊣ convergent edge A 4S 2S ⊣ ⊣ d I4 I5 Parse Traces J0 a J1 b J0 J1 1S ⊣ 0S ⊣ 1A d 0A d a e 3S ⊣ 1S ⊣ 0S ⊣ J2 J3 d 2A d 2A ⊣ ⊣ 0A ⊣ A J4 2S ⊣ d ⊣ J5 4S ⊣ 0A d reductions b e ❀ A (above) and a A d ❀ S (below) Fig. 9. Parsing steps of the parser using a vector-stack for string a b e d ⊣ recognized by the net in Figure 7, with the pilot here reproduced for convenience. mapping from syntax to semantics. In their view, which we do not share, transforming the original r.e.’s to DF A’s is not entirely satisfactory. Others have imposed restrictions on the r.e.’s, for instance limiting the depth of Kleene star nesting or forbidding common subexpressions, and so on. Although the original motivation to simplify parser construction has since vanished, it is fair to say that the r.e.’s used in language reference manuals are typically very simple, for the reason of avoiding Parsing methods streamlined · 27 obscurity. Others prefer to specify right parts by using the very readable graphical notations of syntax diagrams, which are a pictorial variant of FA state-transition diagrams. Whether the F A’s are deterministic or non- does not really make a difference, either in terms of grammar readability or ease of parser generation. Even when the source specification includes N F A’s, it is as simple to transform them into DF A’s by the standard construction, as it is to leave the responsibility of removing finite-state non-determinism to the algorithm that constructs the LR (1) automaton (pilot). On the other hand, we have found that an inexpensive normalization of F A’s (disallowing reentrance into initial states, Def. 2.1) pays off in terms of parser construction simplification. Assuming that the grammar is specified by a net of F A’s, two approaches for building a parser have been followed: (A) transform the grammar into a BN F grammar and apply Knuth’s LR (1) construction, or (B) directly construct an ELR (1) parser from the given machine net. It is generally agreed that “approach (B) is better than approach (A) because the transformation adds inefficiency and makes it harder to determine the semantic structure due to the additional structure added by the transformation” [Morimoto and Sassa 2001]. But since approach (A) leverages on existing parser generators such as Bison, it is quite common for language reference manuals featuring syntax chart notations to include also an equivalent BN F LR (1) (or even LALR (1)) grammar. In [Celentano 1981] a systematic transformation from EBN F to BN F is used to obtain, for an EBN F grammar, an ELR (1) parser that simulates the classical Knuth’s parser for the BN F grammar. The technical difficulty of approach (B), which all authors had to deal with, is how to identify the left end of a reduction handle, since its length is variable and possibly unbounded. A list of different solutions can be found in the already cited surveys. In particular, many algorithms (including ours) use a special shift move, sometimes called stackshift, to record into the stack the left end of the handle when a new computation on a net machine is started. But, whenever such algorithms permit an initial state to be reentered, a conflict between stack-shift and normal shift is unavoidable, and various devices have been invented to arbitrate the conflict. Some add read-back states to control how the parser should dig into the stack [Chapman 1984; LaLonde 1979], while others (e.g., [Sassa and Nakata 1987]) use counters for the same purpose, not to mention other proposed devices. Unfortunately it was shown in [Gálvez 1994; Kannapinn 2001] that several proposals do not precisely characterize the grammars they apply to, and in some cases may fall into unexpected errors. Motivated by the mentioned flaws of previous attempts, the paper by [Lee and Kim 1997] aims at characterizing the LR (k) property for ECF G grammars defined by a network of FA’s. Although their definition is intended to ensure that such grammars “can be parsed from left to right with a look-ahead of k symbols”, the authors admit that “the subject of efficient techniques for locating the left end of a handle is beyond the scope of this paper”. After such a long history of interesting but non-conclusive proposals, our finding of a rather simple formulation of the ELR (1) condition leading to a naturally corresponding parser, was rather unexpected. Our definition simply adds the treatment of convergent edges to Knuth’s definition. The technical difficulties were well understood since long and we combined existing ideas into a simple and provably correct solution. Of course, more experimental work would be needed to evaluate the performance of our algorithms 28 · Parsing methods streamlined on real-sized grammars. 4. DETERMINISTIC TOP-DOWN PARSING A simpler and very flexible top-down parsing method, traditionally called ELL (1),5 applies if an ELR (1) grammar satisfies further conditions. Although less general than the ELR (1), this method has several assets, primarily the ability to anticipate parsing decisions thus offering better support for syntax-directed translation, and to be implemented by a neat modular structure made of recursive procedures that mirror the graphs of network machines. In the next sections, our presentation rigorously derives step by step the properties of topdown deterministic parsers, as we add one by one some simple restrictions to the ELR( 1) condition. First, we consider the Single Transition Property and how it simplifies the shiftreduce parser: the number of m-states is reduced to the number of net states, convergent edges are no longer possible and the chain of stack pointers can be disposed. Second, we add the requirement that the grammar is not left-recursive and we obtain the traditional predictive top-down parser, which constructs the syntax tree in pre-order. At last, the direct construction of ELL (1) parsers sums up. Historical note. In contrast to the twisted story of ELR (1) methods, early efforts to develop top-down parsing algorithms for EBN F grammars have met with remarkable success and we do not need to critically discuss them, but just to cite the main references and to explain why our work adds value to them. Deterministic parsers operating topdown were among the first to be constructed by compilation pioneers, and their theory for BN F grammars was shortly after developed by [Rosenkrantz and Stearns 1970; Knuth 1971]. A sound method to extend such parsers to EBN F grammars was popularized by [Wirth 1975] recursive-descent compiler, systematized in the book [Lewi et al. 1979], and included in widely known compiler textbooks (e.g., [Aho et al. 2006]). However in such books top-down deterministic parsing is presented before shift-reduce methods and independently of them, presumably because it is easier to understand. On the contrary, this section shows that top-down parsing for EBN F grammars is a corollary of the ELR (1) parser construction that we have just presented. Of course, for pure BN F grammars the relationship between LR (k) and LL (k) grammar and language families has been carefully investigated in the past, see in particular [Beatty 1982]. Building on the concept of multiple transitions, which we introduced for ELR (1) analysis, we extend Beatty’s characterization to the EBN F case and we derive in a minimalist and provably correct way the ELL (1) parsing algorithms. As a by-product of our unified approach, we mention in the Conclusion the use of heterogeneous parsers for different language parts. 4.1 Single-transition property and pilot compaction Given an ELR (1) net M and its ELR (1) pilot P, recall that a m-state has the multipletransition property 3.2 (M T P ) if two identically labeled state transitions originate from two candidates present in the m-state. For brevity we also say that such m-state violates the single-transition property (ST P ). The next example illustrates several cases of violation. Example 4.1. Violations of ST P . 5 Extended, Left to right, Leftmost, with length of look-ahead equal to one. · Parsing methods streamlined 29 a Machine Net 1S a N a 1N 3N → 2N ↓ 2S → MS → 0S b N MN → 0N N Pilot Graph I1 I0 1S P → 0S ⊣ a 1N 0N 0N N I3 2S I2 ⊣ a b ⊣ N ⊣ 2S I4 ⊣ 2N 3N ⊣ b ⊣ 0N b ⊣ a N I5 2S ⊣ 2N b ⊣ b b I6 1S 1N ⊣ I7 3N b ⊣ Fig. 10. ELR(1) net of Ex. 4.1 with multiple candidates in the m-state base of I1 , I2 , I4 , I5 . Three cases are examined. First, grammar S → a∗ N , N → a N b | ε, generating the deterministic non-LL (k) language { an bm | n ≥ m ≥ 0 }, is represented by the net in Fig. 10, top. The presence of two candidates in I1|base (and also in other m-states) reveals that the parser has to carry on two simultaneous attempts at parsing until a reduction takes place, which is unique, since the pilot satisfies the ELR (1) condition: there are neither shift-reduction nor reduction-reduction conflicts, nor convergence conflicts. Second, the net in Figure 7 illustrates the case of multiple candidates in the base of a m-state (I3 ) that is entered by a convergent edge. Third, grammar S → b ( a | S c ) | a has a pilot that violates ST P , yet it contains only one candidate in each m-state base. On the other hand, if every m-state base contains one candidate, the parser configuration space can be reduced as well as the range of parsing choices. Furthermore, ST P entails that there are no convergent edges in the pilot. Next we show that m-states having the same kernel, qualified for brevity as kernelidentical, can be safely coalesced, to obtain a smaller pilot that is equivalent to the original one and bears closer resemblance to the machine net. We hasten to say that such transformation does not work in general for an ELR (1) pilot, but it will be proved to be correct under the ST P hypothesis. 30 · Parsing methods streamlined 4.1.1 Merging kernel-identical m-states. The merging operation coalesces two kernelidentical m-states I1 and I2 , suitably adjusts the pilot graph, then possibly merges more kernel-identical m-states. It is defined as follows: Algorithm 4.2. M erge ( I1 , I2 ) (1) replace I1 , I2 by a new kernel-identical m-state, denoted by I1, 2 , where each lookahead set is the union of the corresponding ones in the merged m-states: hp, πi ∈ I1, 2 ⇐⇒ hp, π1 i ∈ I1 and hp, π2 i ∈ I2 and π = π1 ∪ π2 (2) the m-state I1, 2 becomes the target for all the edges that entered I1 or I2 : X X X I −→ I1, 2 ⇐⇒ I −→ I1 or I −→ I2 (3) for each pair of edges from I1 and I2 , labeled X, the target m-states (which clearly are kernel-identical) are merged:  if ϑ ( I1 , X ) 6= ϑ ( I2 , X ) then call M erge ϑ (I1 , X ), ϑ ( I2 , X ) Clearly the merge operation terminates with a graph with fewer nodes. The set of all kernel-equivalent m-states is an equivalence class. By applying the Merge algorithm to the members of every equivalence class, we construct a new graph, to be called the compact pilot and denoted by C.6 Example 4.3. Compact pilot. We reproduce in Figure 11 the machine net, the original ELR (1) pilot and, in the bottom part, the compact pilot, where for convenience the m-states have been renumbered. Notice that the look-ahead sets have expanded: e.g., in K1T the look-ahead in the first row is the union of the corresponding look-aheads in the merged m-states I3 and I6 . We are going to prove that this loss of precision is not harmful for parser determinism thanks to the stronger constraints imposed by ST P . We anticipate from Section 4.4 that the compact pilot can be directly constructed from the machine net, saving some work to compute the larger ELR (1) pilot and then to merge kernel-identical nodes. 4.1.2 Properties of compact pilots. We are going to show that we can safely use the compact pilot as parser controller. P ROPERTY 4.4. Let P and C be respectively the ELR (1) pilot and the compact pilot of a net M satisfying ST P 7 . The ELR (1) parsers controlled by P and by C are equivalent, i.e., they recognize language L (M) and construct the same syntax tree for every x ∈ L (M). P ROOF. We show that, for every m-state, the compact pilot has no ELR (1) conflicts. Since the merge operation does not change the kernel, it is obvious that every C m-state 6 For the compact pilot the number of m-states is the same as for the LR (0) and LALR (1) pilots, which are historical simpler variants of LR (1) parsers not considered here, see for instance [Crespi Reghizzi 2009]. However neither LR (0) nor LALR (1) pilots have to comply with the ST P condition. 7 A weaker hypothesis would suffice: that every m-state has at most one candidate in its base, but for simplicity we have preferred to assume also that convergent edges are not present. · Parsing methods streamlined Machine Net 31 a T ME → 0E 1E ↓ ↓ MT → 0T T 1T 3T → 2T E ( ) Pilot Graph I1 I0 P → 0E ⊣ 0T a(⊣ T 1E ⊣ 0T a(⊣ T ( I3 1T a(⊣ 0E ) 0T a() 2T a ( ⊣ E a ( ⊣ I2 3T ) I8 I4 T 1E ) 0T a() ( T ( I6 a a ( 1T a() 0E ) 0T a() a 2T a ( ) E a a T 3T ) a ( ) I5 I7 ( Compact Pilot Graph K1E ≡ I1,4 K0E ≡ I0 L→ 0E ⊣ 0T a(⊣ 1T a() ⊣ 0E ) 0T a() 1E ) ⊣ 0T a() ⊣ T a ( ( K1T ≡ I3,6 T T E a a 2T a ( ) ⊣ 3T a() ⊣ ) K2T ≡ I7,8 K3T ≡ I2,5 ( Fig. 11. From top to bottom: machine net M, ELR (1) pilot graph P and compact pilot C; the equivalence classes of m-states are: { I0 }, { I1 , I4 }, { I2 , I5 }, { I3 , I6 } and { I7 , I8 }; the m-states of C are named K0E , . . . , K3T to evidence their correspondence with the states of net M. 32 · Parsing methods streamlined satisfies ST P . Therefore non-initial reduce-reduce conflicts can be excluded, since they involve two candidates in a base, a condition which is ruled out by ST P . Next, suppose by contradiction that a reduce-shift conflict between a final non-initial a ′ , occurs in I1, 2 , but neither in I1 nor in I2 . Since hqA , ai is state qA and a shift of qB → qB in the base of I1, 2 , it must also be in the bases of I1 or I2 , and an a labeled edge originates from I1 or I2 . Therefore the conflict was already there, in one or both m-states I1 , I2 . Next, suppose by contradiction that I1, 2 has a new initial reduce-shift conflict between an outgoing a labeled edge and an initial-final candidate h0A , ai. By definition of merge, h0A , ai is already in the look-ahead set of, say, I1 . Moreover, for any two kernel-identical m-states I1 and I2 , for any symbol X ∈ Σ ∪ V , either both ϑ (I1 , X) = I1′ and ϑ (I2 , X) = I2′ are defined or neither one, and the m-states I1′ , I2′ are kernel-identical. Therefore, an a labeled edge originates from I1 , which thus has a reduce-shift conflict, a contradiction. Last, suppose by contradiction that I1, 2 contains a new initial reduce-reduce conflict between 0A and 0B for some terminal character a that is in both look-ahead sets. Clearly in one of the merged m-states, say I1 , there are (in the closure) the candidates: h0A , π1 i with a ∈ π1 and h0B , ρ1 i with a 6∈ ρ1 and in I2 there are (in the closure) the candidates: h0A , π2 i with a 6∈ π2 and h0B , ρ2 i with a ∈ ρ2 To show the contradiction, we recall how look-aheads are computed. Let the bases be respectively hqC , σ1 i for I1 and hqC , σ2 i for I2 . Then any character in, say, π1 comes in two possible ways: 1) it is present in σ1 , or 2) it is a character that follows some state that is in the closure of I1 . Focusing on character a, the second possibility is excluded because a 6∈ π2 , whereas the look-ahead elements brought by case 2) are necessarily the same for m-states I1 and I2 . It remains that the presence of a in π1 and in ρ2 comes from its presence in σ1 and in σ2 . Hence a must be also in π2 , a contradiction. The parser algorithms differ only in their controllers, P and C. First, take a string accepted by the parser controlled by P. Since any m-state created by merge encodes exactly the same cases for reduction and for shift as the original merged m-states, the parsers will perform exactly the same moves for both pilots. Moreover, the chains of candidate identifiers are clearly identical since the candidate offset are not affected by merge. Therefore, at any time the parser stacks store the same elements, up to the merge relation, and the compact parser recognizes the same strings and constructs the same tree. Second, suppose by contradiction that an illegal string is recognized using the compact parser. For this string consider the first parsing time where P stops in error in m-state I1 , whereas C is able to move from I1, 2 . If the move is a terminal shift, the same shift is necessarily present in I1 . If it is a reduction, since the candidate identifier chains are identical, the same string is reduced to the same nonterminal. Therefore also the following nonterminal shift operated by C is legal also for P, which is a contradiction. We have thus established that the parser controlled by the compact pilot is equivalent to the original one. 4.1.3 Candidate identifiers or pointers unnecessary. Thanks to the ST P property, the parser can be simplified to remove the need for cid’s (or stack pointers). We recall that a cid was needed to find the reach of a non-empty reduction move into the stack: elements Parsing methods streamlined · 33 were popped until the cid chain reached an initial state, the end-of-list sentinel. Under ST P hypothesis, that test is now replaced by a simpler device, to be later incorporated in the final ELL (1) parser (Alg. 4.13). With reference to Alg. 3.8, only shift and reduction moves are modified. First, let us focus on the situation when the old parser, with J on top of stack and J|base = hqA , πi, performs the shift of X (terminal or non-) from state qA , which is necessarily non-initial; the shift would require to compute and record a non-null cid into the sms J ′ to be pushed on stack. In the same situation, the pointerless parser cancels from the top-of-stack element J all candidates other than qA , since they correspond to discarded parsing alternatives. Notice that the canceled candidates are necessarily in J|closure , hence they contain only initial states. Their elimination from the stack allows the parser to uniquely identify the reduction to be made when a final state of machine MA is entered, by a simple rule: keep popping the stack until the first occurrence of initial state 0A is found. Second, consider a shift from an initial state h0A , πi, which is necessarily in J|closure . In this case the pointerless parser leaves J unchanged and pushes ϑ (J, X) on the stack. The other candidates present in J cannot be canceled because they may be the origin of future nonterminal shifts. Since cid’s are not used by this parser, a stack element is identical to an m-state (of the compact pilot). Thus a shift move first updates the top of stack element, then it pushes the input token and the next m-state. We specify only the moves that differ from Alg. 3.8. Algorithm 4.5. Pointerless parser AP L . Let the pilot be compacted; m-states are denoted Ki and stack symbols Hi ; the set of candidates of Hi is weakly included in Ki . Shift move. Let the current character be a, H be the top of stack element, containing a candidate hqA , πi. Let qA → qA ′ and ϑ (K, a) = K ′ be respectively the state transition and m-state transition, to be applied. The shift move does: (1) if qA ∈ K|base (i.e., qA is not initial), eliminate all other candidates from H, i.e., set H equal to K|base (2) push a on stack and get next token (3) push H ′ = K ′ on the stack Reduction move (non-initial state). Let the stack be H[0] a1 H[1] a2 . . . ak H[k]. Assume that the pilot chooses the reduction candidate hqA , πi ∈ K[k], where qA is a final but non-initial state. Let H[h] be the topmost stack element such that 0A ∈ K[h]|kernel . The move does: (1) grow the syntax forest by applying the reduction ah+1 ah+2 . . . ak ❀ A and pop the stack symbols H[k], ak , H[k − 1], ak−1 , . . . , H[h + 1], ah+1 (2) execute the nonterminal shift move ϑ (K[h], A) Reduction move (initial state). It differs from the preceding case in that, for the chosen reduction candidate h0A , πi, the state is initial and final. Reduction ε ❀ A is applied to grow the syntax forest. Then the parser performs the nonterminal shift move ϑ (K[k], A). Nonterminal shift move. It is the same as a shift move, except that the shifted symbol is a nonterminal. The only difference is that the parser does not read the next input token at line (2) of Shift move. Clearly this reorganization removes the need of cid’s or pointers while preserving correctness. 34 · Parsing methods streamlined P ROPERTY 4.6. If the ELR (1) pilot of an EBN F grammar or machine net satisfies the ST P condition, the pointerless parser AP L of Alg. 4.5 is equivalent to the ELR (1) parser A of Alg. 3.8. P ROOF. There are two parts to the proof, both straightforward to check. First, after parsing the same string, the stacks of parsers A and AP L contain the same number k of stack elements, respectively J[0] . . . J[k] and K[0] . . . K[k], and for every pair of corresponding elements, the set of states included in K[i] is a subset of the set of states included in J[i] because Alg. 4.5 may have discarded a few candidates. Furthermore, we claim the next relation for any pair of stack elements at position i and i − 1. in J[i] candidate hqA , π, ♯ji points to hpA , π, ♯li in J[i − 1]|base ⇐⇒ hqA , πi ∈ K[i] and the only candidate in K[i − 1] is hpA , πi in J[i] candidate hqA , π, ♯ji points to h0A , π, ⊥i in J[i − 1]|closure ⇐⇒ hqA , πi ∈ K[i] and K[i − 1] equals the projection of J[i − 1] on hstate, look-aheadi Then by the specification of reduction moves, A performs reduction: ah+1 ah+2 . . . ak ❀ A ⇐⇒ AP L performs the same reduction Example 4.7. Pointerless parser trace. Such a parser is characterized by having in each stack element only one non-initial machine state, plus possibly a few initial ones. Therefore the parser explores only one possible reduction at a time and candidate pointers are not needed. Given the input string ( ( ) a ) ⊣, Figure 12 shows the execution trace of a pointerless parser for the same input as in Figure 6 (parser using cid’s). The graphical conventions are unchanged: the m-state (of the compact pilot) in each cell is framed, e.g., K0S is denoted 0S , etc.; the final candidates are encircled, e.g., 3T , etc.; and the look-aheads are omitted to avoid clogging. So a candidate appears as a pure machine state. Of course, here there are no pointers; instead, the initial candidates canceled by Alg. 4.5 from a mstate, are striked out. We observe that upon starting a reduction, the initial state of the active machine might in principle show up in a few stack elements to be popped. For instance the first (from the Figure top) reduction ( E ) ❀ T of machine MT , pops three stack elements, namely K3T , K2T and K1T , and the one popped last, i.e., K1T , contains a striked out candidate 0T that would be initial for machine MT . But the real initial state for the reduction remains instead unstriked below in the stack in element K1T , which in fact is not popped and thus is the origin of the shift on T soon after executed. We also point out that Alg. 4.5 does not cancel any initial candidates from a stack element, if a shift move is executed from one such candidate (see the Shift move case of Alg. 4.5). The motivation for not canceling is twofold. First, these candidates will not cause any early stop of the series of pop moves in the reductions that may come later, or said differently, they will not break any reduction handle. For instance the first (from the Figure top) shift on ( of machine MT , keeps both initial candidates 0E and 0T in the Parsing methods streamlined string to be parsed (with end-marker) and stack contents stack base · 35 effect after 1 2 3 4 5 ( ( ) a ) ⊣ initialisation of the stack ( ( ) ) a ⊣ 1T 1T 0E shift on ( 0T ( ( 1T 1T 0E 1T 0T 1T ( 1T 0E reduction ε ❀ E ) E 1T 0E 2T 3T shifts on E and ) reduction (E) ❀ T and shift on T T ⊣ 3T 3T shift on a 0T ( T 1T 0T ) a 1E 1E 0T 0E ⊣ 0T 1T 0E ) a 1E 0T 1T 3T 2T 1E ( 1T ⊣ 0T T 0E ) a 1T 1T 1T ⊣ 0E ( 0T ) a 0T ( 0E ) E 0T 0T shift on ( 1T 0E 0E ⊣ 0E ( 1T 1T ) a 0T ( 1T ) 1T 1E ) T 1E 1E 0T ⊣ 1E reduction a ❀ T and shift on T 0T ( ) E ⊣ 1T 1T 0E 27 2T 37 reduction T T ❀ E and shifts on E and ) 3T 0T ⊣ T 1E 1E reduction (E) ❀ T and shift on T 0T E ⊣ reduction T ❀ E and accept without shitting on E Fig. 12. Steps of the pointerless parsing algorithm APL ; the candidates are canceled by the shift moves as explained in Algorithm 4.5. 36 · Parsing methods streamlined stack m-state K1T , as the shift originates from the initial candidate 0T . This candidate will instead be canceled (i.e., it will show striked) when a shift on E is executed (soon after reduction T T ❀ E), as the shift originates from the non-initial candidate 1T . Second, some of such initial candidates may be needed for a subsequent nonterminal shift move. To sum up, we have shown that condition ST P permits to construct a simpler shift-reduce parser, which has a reduced stack alphabet and does not need pointers to manage reductions. The same parser can be further simplified, if we make another hypothesis: that the grammar is not left-recursive. 4.2 ELL (1) condition Our definition of top-down deterministically parsable grammar or network comes next. Definition 4.8. ELL (1) condition.8 A machine net M meets the ELL(1) condition if the following three clauses are satisfied: (1) there are no left-recursive derivations (2) the net meets the ELR(1) condition (3) the net has the single transition property (ST P ) Condition (1) can be easily checked by drawing a graph, denoted by G, that has as nodes the initial states of the net and has an edge 0A −→ 0B if in machine MA there exists an B edge 0A −→ rA , or more generally a path: A A A B 2 1 k . . . −→ qk −→ rA q1 −→ 0A −→ k≥0 where all the nonterminals A1 , A2 , . . ., Ak are nullable. The net is left-recursive if, and only if, graph G contains a circuit. Actually, left recursive derivations cause, in all but one situations, a violation of clause (2) or (3) of Def. 4.8. The only case that would remain undetected is a left-recursive derivation involving the axiom 0S and caused by state-transitions of the form: S 0S −→ 1S or A 1 1S 0S −→ A 2 1 A1 0A1 −→ ... S 0Ak −→ 1Ak k ≥ 1 (10) Three different types of left-recursive derivations are illustrated in Figure 13. The first two cause violations of clause (2) or (3), so that only the third needs to be checked on graph G: the graph contains a self-loop on node 0E . It would not be difficult to formalize the properties illustrated by the examples and to restate clause (1) of Definition 4.8 as follows: the net has no left-recursive derivation of the form (10), i.e., involving the axiom and not using ε-rules. This apparently weaker but indeed equivalent condition is stated by [Beatty 1982], in his definition of (non-extended) LL (1) grammars. 4.2.1 Discussion. To sum up, ELL (1) grammars, as defined here, are ELR (1) grammars that do not allow left-recursive derivations and satisfy the single-transition property (no multiple candidates in m-state bases and hence no convergent transitions). This is 8 The historical acronym “ELL (1)” has been introduced over and over in the past by several authors with slight differences. We hope that reusing again the acronym will not be considered an abuse. · Parsing methods streamlined E→XE + a | a 37 X→ε | b a ME → 0E 4E 1E X 2E b 3E → a + E MX → 0X 1X → ↓ a shift-reduce conflict in m-state I0 caused by a left-recursive derivation that makes use of ε-rules I0 0E ⊣ 0X ab a ⊣ I1 3E S→aA A→Ab | b b a MS → 0S A 1S 2S → MA → 0A 2A → 1A A b a left-recursive derivation through a nonterminal other than the axiom has the effect of creating two candidates in the base of m-state I2 and thus violates clause (2) I2 I1 I0 1S ⊣ a 0S ⊣ 2S A ⊣ 1A 0A ⊣ a E→E + a | a ME → 0E 1E 2E + E a 3E → clauses (1) and (2) are met and the left-recursive derivation 0E ⇒ 0E 1E is entirely contained in m-state I0 I0 0E + ⊣ a E I2 1E + ⊣ 3E + ⊣ I1 a + 2E + ⊣ I3 Fig. 13. Left-recursive nets violating ELL (1) conditions. Top: left-recursion with ε-rules violates clause (2). Middle: left-recursion on A 6= axiom violates clause (3). Bottom: left-recursive axiom E is undetected by clauses (2) and (3). a more precise reformulation of the definitions of “LL (1)” and “ELL (1)” grammars, which have accumulated in half a century. To be fair to the perhaps most popular definition of LL(1) grammar, we contrast it with ours. There are marginal contrived examples where 38 · Parsing methods streamlined a violation of ST P caused by the presence of multiple candidates in the base of a m-state, does not hinder a top-down parser from working deterministically [Beatty 1982]. A typical case is the LR (1) grammar { S → A a | B b, A → C, B → C, C → ε }. One of the m-states has two candidates in the base: hA → C •, ai, hB → C •, bi . The choice between the alternatives of S is determined by the following character, a or b, yet the grammar violates ST P . It easy to see that a necessary condition for such a situation to occur is that the language derived from some nonterminal of the grammar in question consists only of the empty string: ∃ A ∈ V such that LA (G) = { ǫ }. However this case can be usually removed without any penalty, nor a loss of generality, in all grammar applications. In fact, the grammar above can be simplified and the equivalent grammar { S → A | B, A → a, B → b } is obtained, which complies with ST P . 4.3 Stack contraction and predictive parser The last development, to be next presented, transforms the already compacted pilot graph into the Control Flow Graph of a predictive parser. The way the latter parser uses the stack differs from the previous models, the shift-reduce and pointerless parsers. More precisely, now a terminal shift move, which always executes a push operation, is sometimes implemented without a push and sometimes with multiple pushes. The former case happens when the shift remains inside the same machine: the predictive parser does not push an element upon performing a terminal shift, but it updates the top of stack element to record the new state. Multiple pushes happen when the shift determines one or more transfers from the current machine to others; the predictive parser performs a push for each transfer. The essential information to be kept on stack, is the sequence of machines that have been activated and have not reached a final state (where a reduction occurs). At each parsing time, the current or active machine is the one that is doing the analysis, and the current state is kept in the top of stack element. Previous non-terminated activations of the same or other machines are in the suspended state. For each suspended machine MA , a stack entry is needed to store the state qA , from where the machine will resume the computation when control is returned after performing the relevant reductions. The main advantage of predictive parsing is that the construction of the syntax tree can be anticipated: the parser can generate on-line the left derivation of the input. 4.3.1 Parser control-flow graph. Moving from the above considerations, first we slightly transform the compact pilot graph C and make it isomorphic to the original machine net M. The new graph is named parser control-flow graph (P CF G) because it represents the blueprint of parser code. The first step of the transformation splits every m-node of C that contains multiple candidates, into a few nodes that contain only one candidate. Second, the kernel-equivalent nodes are coalesced and the original look-ahead sets are combined into one. The third step creates new edges, named call edges, whenever a machine transfers control to another machine. At last, each call edge is labeled with a set of characters, named guide set, which is a summary of the information needed for the parsing decision to transfer control to another machine. Definition 4.9. Parser Control-Flow Graph. Every node of the P CF G, denoted by F , is identified by a state q of machine net M Parsing methods streamlined · 39 and denoted, without ambiguity, by q. Moreover, every node qA , where qA ∈ FA is final, consists of a pair hqA , πi, where set π, named prospect9 set, is the union of the look-ahead sets πi of every candidate hqA , πi i existing in the compact pilot graph C: [ πi π= ∀ hqA , πi i ∈ C The edges of F are of two types, named shift and call: X (1) There exists in F a shift edge qA → rA with X terminal or non-, if the same edge is in machine MA . γ1 (2) There exists in F a call edge qA 99K 0A1 , where A1 is a nonterminal possibly differA ent from A, if qA →1 rA is in MA , hence necessarily in some m-state K of C there exist candidates hqA , πi and h0A1 , ρi; and the m-state ϑ (K, A1 ) contains candidate hrA , πrA i. The call edge label γ1 ⊆ Σ ∪ { ⊣ }, named guide set,10 is recursively defined as follows: —it holds b ∈ γ1 if, and only if, any conditions below hold:  (11) b ∈ Ini L (0A1 )  A1 is nullable and b ∈ Ini L (rA ) (12) (13) A1 and L (rA ) are both nullable and b ∈ πrA γ2 ∃ in F a call edge 0A1 99K 0A2 and b ∈ γ2 (14) Relations (11), (12), (13) are not recursive and respectively consider that b is generated by MA1 called by MA ; or by MA but starting from state rA ; or that b follows MA . Rel. (14) is recursive and traverses the net as far as the chain of call sites activated. We observe that Rel. (14) determines an inclusion relation γ1 ⊇ γ2 between any two concatenated call γ1 γ2 γ1 edges qA 99K 0A1 99K 0A2 . We also write γ1 = Gui (qA 99K 0A1 ) instead of qA 99K 0A1 . We next extend the definition of guide set to the terminal shift edges and to the dangling a darts that tag the final  nodes. For each terminal shift edge p → q labeled with a ∈ Σ, a we set Gui p → q := { a }. For each dart that tags a final node containing a candidate hfA , πi with fA ∈ FA , we set Gui (fA →) := π. Then in the P CF G all edges (except the nonterminal shifts) can be interpreted as conditional instructions, enabled if the current character cc belongs to the associated guide set: a terminal shift edge labeled with { a } is enabled by a predicate cc = a (or cc ∈ { a } for uniformity); a call edge labeled with γ represents a conditional procedure invocation, where the enabling predicate is cc ∈ γ; a final node dart labeled with π is interpreted as a conditional return-from-procedure instruction to be executed if cc ∈ π. The remaining P CF G edges are nonterminal shifts, which are interpreted as unconditional return-from-procedure instructions. We show that for the same state such predicates never conflict with one another. P ROPERTY 4.10. For every node q of the P CF G of a grammar satisfying the ELL (1) condition, the guide sets of any two edges originating from q are disjoint. 9 Although traditionally the same word “look-ahead” has been used for both shift-reduce and top-down parsers, the set definitions differ and we prefer to differentiate their names. 10 It is the same as a “predictive parsing table element” in [Aho et al. 2006]. 40 · Parsing methods streamlined P ROOF. Since every machine is deterministic, identically labeled shift edges cannot originate from the same node, and it remains to consider the cases of shift-call and call-call edge pairs. γC γB a Consider a shift edge qA → rA with a ∈ Σ, and two call edges qA 99K 0B and qA 99K 0C . First, assume by contradiction a ∈ γB . If a ∈ γB comes from Rel. (11), then in the pilot m-state ϑ (qA , a) there are two base candidates, a condition that is ruled out by ST P . If it comes from Rel. (12), in the m-state with base qA , i.e., m-state K, there is a conflict between the shift of a and the reduction 0B , which owes its look-ahead a to a path from rA in machine MA . If it comes from Rel. (13), in m-state K there is the same shift-reduce conflict as before, though now reduction 0B owes its-look ahead a to some other machine that previously invoked machine MA . Finally, it may come from Rel. (14), which is the recursive case and defers the three cases before to some other machine that is immediately invoked by machine MB : there is either a violation of ST P or a shift-reduce conflict. Second, assume by contradiction a ∈ γB and a ∈ γC . Since a comes from one of four relations, twelve combinations should be examined. But since they are similar to the previous argumentation, we deal only with one, namely case (11)-(11): clearly, m-state ϑ (qA , a) violates ST P . The converse of Property 4.10 also holds, which makes the condition of having disjoint guide sets a characteristic property of ELL (1) grammars. We will see that this condition can be checked easily on the P CF G, with no need to build the ELR (1) pilot automaton. P ROPERTY 4.11. If the guide sets of a P CF G are disjoint, then the net satisfies the ELL (1) condition of Definition 4.8. The proof is in the Appendix. Example 4.12. For the running example, the P CF G is represented in Figure 14 with the same layout as the machine net for comparability. In the P CF G there are new nodes (only node 0T in this example), which derive from the initial candidates (excluding those containing the axiom 0S ) extracted from the closure part of the m-states of C. Having added such nodes, the closure part of the C nodes (except for node I0 ) becomes redundant and has been eliminated from P CF G node contents. As said, prospect sets are needed only in final states; they have the following properties: —For final states that are not initial, the prospect set coincides with the corresponding look-ahead set of the compact pilot C. This is the case of nodes 1E and 3T . —For a final-initial state, such as 0E , the prospect set is the union of the look-ahead sets of every candidate h0E , πi that occurs in C. For instance, h0E , { ), ⊣ }i takes ⊣ from m-state K0E and ) from K1T . Solid edges represent the shift ones, already present in the machine net and pilot graph. Dashed edges represent the call ones, labeled by guide sets, and how to compute them is next illustrated: —the guide set of call edge 0E 99K 0T (and of 1E 99K 0T ) is { a, ) }, since from state 0T both characters can be shifted —the guide set of edge 1T 99K 0E includes the terminals: E ) since 1T → 2T is in MT , language L (0E ) is nullable and ) ∈ Ini (2T ) a, ( since from 0E a call edge goes out to 0T with prospect set { a, ( } · Parsing methods streamlined Compact Pilot Graph Machine Network K1E K0E T ME → 0E 1E ↓ ↓ L→ T T 0E ⊣ 0T a(⊣ ) ⊣ 0T a() ⊣ T ( ( 1E T 1T 1T ( E K1T 3T → 2T ) a a a a MT → 0T 41 a() ⊣ 0E ) 0T a() E 2T a ( ) ⊣ 3T a() ⊣ ) K2T K3T ( Parser Control-Flow Graph 0E ME → ↑  ) ⊣   MT → 0T ( 1T 1E T ↑  ) ⊣ T a(  a() E ) 2T 3T  a() ⊣ a( → a Fig. 14. The Parser Control-Flow Graph F of the running example, from the net and the compact pilot. In accordance with Prop. 4.10, the terminal labels of all the edges that originate from the same node, do not overlap. 4.3.2 Predictive parser. It is straightforward to derive the parser from the P CF G; its nodes are the pushdown stack elements; the top of stack element identifies the state of the active machine, while inner stack elements refer to states of suspended machines, in the correct order of suspension. There are four sorts of moves. A scan move, associated with a terminal shift edge, reads the current character, cc, as the corresponding machine would do. A call move, associated with a call edge, checks the enabling predicate, saves on stack the return state, and switches to the invoked machine without consuming cc. A return move is triggered when the active machine enters a final state whose prospect set includes cc: the active state is set to the return state of the most recently suspended machine. A recognizing move terminates parsing. Algorithm 4.13. Predictive recognizer, A. —The stack elements are the states of P CF G F . At the beginning the stack contains the initial candidate h0S i. —Let hqA i be the top element, meaning that the active machine MA is in state qA . Moves are next specified, this way: 42 · Parsing methods streamlined —scan move cc if the shift edge qA −→ rA exists, then scan the next character and replace the stack top by hrA i (the active machine does not change) —call move γ B if there exists a call edge qA 99K 0B such that cc ∈ γ, let qA → rA be the corresponding nonterminal shift edge; then pop, push element hrA i and push element h0B i —return move if qA is a final state and cc is in the prospect set associated with qA in the P CF G F , then pop —recognition move if MA is the axiom machine, qA is a final state and cc =⊣, then accept and halt —in any other case, reject the string and halt From Prop. 4.10 it follows that for every parsing configuration at most one move is possible, i.e., the algorithm is deterministic. 4.3.3 Computing left derivations. To construct the syntax tree, the algorithm is next extended with an output function, thus turning the DP DA into a pushdown transducer that computes the left derivation of the input string, using the right-linearized grammar Ĝ. The output actions are specified in Table I and are so straightforward that we do not need to prove their correctness. Moreover, we recall that the syntax tree for grammar Ĝ is essentially an encoding of the syntax tree for the original EBN F grammar G, such that each node has at most two child nodes. Table I. Derivation steps computed by predictive parser. Current character is cc = b. Parser move Output derivation step b Scan move for transition qA −→ rA qA =⇒ b rA Ĝ γ 0B Call move for call edge qA 99K 0B and transition qA → rA qA =⇒ 0B rA Return move for state qA ∈ FA qA =⇒ ε Ĝ Ĝ Example 4.14. Running example: trace of predictive parser for input x = ( a ). Parsing methods streamlined stack x h0E i · predicate left derivation (a) ⊣ (∈ γ = { a ( } 0E ⇒ 0T 1E h1E i h0T i (a) ⊣ scan 0E ⇒ ( 1T 1E h1E i h1T i a) ⊣ a ∈ γ = {a(} 0E ⇒ ( 0E 2T 1E h1E i h2T ih0E i a) ⊣ a ∈ γ = {a(} 0E ⇒ ( 0T 1E 2T 1E h1E i h2T ih1E ih0T i a) ⊣ scan h1E i h2T ih1E ih3T i ) ⊣ ) ∈ π = {a() ⊣} h1E i h2T ih1E i ) ⊣ ) ∈ π = {) ⊣} 0E ⇒ ( a ε 2T 1E h1E i h2T i ) ⊣ scan 0E ⇒ ( a ) 3T 1E h1E i h3T i ⊣ ⊣∈ π = {a() ⊣} h1E i ⊣ ⊣ ∈ π = { ) ⊣ } accept 43 + + + + 0E ⇒ ( a 3T 1E 2T 1E + 0E ⇒ ( a ε 1E 2T 1E + + + 0E ⇒ ( a ) ε 1E + 0E ⇒ ( a ) ε For the original grammar, the corresponding derivation is: E ⇒ T ⇒ (E ) ⇒ (T ) ⇒ (a) 4.3.4 Parser implementation by recursive procedures. Predictive parsers are often implemented using recursive procedures. Each machine is transformed into a parameter-less so-called syntactic procedure, having a CF G matching the corresponding P CF G subgraph, so that the current state of a machine is encoded at runtime by the program counter. Parsing starts in the axiom procedure and successfully terminates when the input has been exhausted, unless an error has occurred before. The standard runtime mechanism of procedure invocation and return automatically implements the call and return moves. An example should suffice to show that the procedure pseudo-code is mechanically obtained from the P CF G. Example 4.15. Recursive descent parser. For the P CF G of Figure 14, the syntactic procedures are shown in Figure 15. The pseudo-code can be optimized in several ways. 4.4 Direct construction of parser control-flow graph We have presented and justified a series of rigorous steps that lead from an ELR (1) pilot to the compact pointer-less parser, and finally, to the parser control-flow graph. However, for a human wishing to design a predictive parser it would be tedious to perform all those steps. We therefore provide a simpler procedure for checking that an EBN F grammar satisfies the ELL (1) condition. The procedure operates directly on the grammar Parser Control Flow Graph and does not require the construction of the ELR (1) pilot. It uses a set of recursive equations defining the prospect and guide sets for all the states and edges of the P CF G; the equations are interpreted as instructions to compute iteratively the guide sets, after which the ELL (1) check simply verifies, according to Property 4.11, that the guide sets are disjoint. 4.4.1 Equations defining the prospect sets 44 · Parsing methods streamlined Recursive Descent Parser Machine Network procedure T - - state 0T if cc ∈ { a } then cc = next else if cc ∈ { ( } then cc = next - - state 1T if cc ∈ { a ( ) } then call E else error end if - - state 2T if cc ∈ { ) } then cc = next else error end if else error end if - - state 3T if cc ∈ { a ( ) ⊣ } then return else error end if end procedure T ME → 0E 1E ↓ ↓ T a MT → 0T 1T 3T → 2T E ( ) Recursive Descent Parser program ELL P ARSER cc = next call E if cc ∈ { ⊣ } then accept else reject end if end program procedure E - - optimized while cc ∈ { a ( } do call T end while if cc ∈ { ) ⊣ } then return else error end if end procedure Fig. 15. Main program and syntactic procedures of a recursive descent parser (Ex. 4.15 and Fig. 14); function next is the programming interface to the lexical analyzer or scanner; function error is the messaging interface. X (1) If the net includes shift edges of the kind pi →i q then the prospect set πq of state q is: [ πpi πq := X i pi →q A (2) If the net includes nonterminal shift edge qi → ri and the corresponding call edge in the PCFG is qi 99K 0A , then the prospect set for the initial state 0A of machine MA is:  [    Ini L (ri ) ∪ if N ullable L (ri ) then πqi else ∅ π0A := π0A ∪ A qi →ri Notice that the two sets of rules apply in an exclusive way to disjoints sets of nodes, because the normalization of the machines disallows re-entrance into initial states. 4.4.2 Equations defining the guide sets A (1) For each call edge qA 99K 0A1 associated with a nonterminal shift edge qA →1 rA , · Parsing methods streamlined 45 such that possibly other call edges 0A1 99K 0Bi depart from state 0A1 , the guide set Gui (qA 99K 0A1 ) of the call edge is defined as follows, see also conditions (11-14):    Ini L (A1        if N ullable (A1) then Ini L (rA ) else ∅ [  Gui (qA 99K 0A1 ) :=  if N ullable (A1) ∧ N ullable L (rA ) then πrA else ∅    S    Gui (0A1 99K 0Bi )  0A1 99K0Bi (2) For a final state fA ∈ FA , the guide set of the tagging dart equals the prospect set: Gui (fA →) := πfA a (3) For a terminal shift edge qA → rA with a ∈ Σ, the guide set is simply the shifted terminal:   a Gui qA → rA := { a } A computation starts by assigning to the prospect set of 0S (initial state of axiom machine) the end-marker: π0S := { ⊣ }. All other sets are initialized to empty. Then the above rules are repeatedly applied until a fixpoint is reached. Notice that the rules for computing the prospect sets are consistent with the definition of look-ahead set given in Section 2.2; furthermore, the rules for computing the guide sets are consistent with the definition of Parser Control Flow Graph provided in Section 4.9. Example 4.16. Running example: computing the prospect and guide sets. The following table shows the computation of most prospect and guide sets for the P CF G of Figure 14 (p. 41). The computation is completed at the third step. Prospect sets of Guide sets of 0E 1E 0T 1T 2T 3T ⊣ ∅ ∅ ∅ ∅ ∅ 0E 99K 0T 1E 99K 0T 1T 99K 0E ∅ ∅ ∅ ) ⊣ ) ⊣ a() ⊣ a() ⊣ a() ⊣ a() ⊣ a( a( a() ) ⊣ ) ⊣ a() ⊣ a() ⊣ a() ⊣ a() ⊣ a( a( a() Example 4.17. Guide sets in a non-ELL(1) grammar. The grammar { S → a∗ N, N → a N b | ε } of example 4.1 (p.28) violates the single transition property, as shown in Figure 10, hence it is not ELL (1). This can be verified also by computing the guide sets on the P CF G. We have Gui(0S 99K 0N ) ∩  a a 6 ∅: the Gui 0S → 1S = { a } 6= ∅ and Gui (1S 99K 0N ) ∩ Gui 1S → 1S = { a } = guide sets on the edges departing from states 0S and 1S are not disjoint. 5. TABULAR PARSING The LR and LL parsing methods are inadequate for dealing with nondeterministic and ambiguous grammars. The seminal work [Earley 1970] introduced a cubic-time algorithm 46 · Parsing methods streamlined for recognizing strings of any context-free grammar, even of an ambiguous one, though it did not explicitly present a parsing method, i.e., a means for constructing the (potentially numerous) parsing trees of the accepted string. Later, efficient representations of parse forests have been invented, which do not duplicate the common subtrees and thus achieve a polynomial-time complexity for the tree construction algorithm. Until recently [Aycock and Borsotti 2009], Earley parsers performed a complete recognition of the input before constructing any syntax tree [Grune and Jacobs 2009]. Concerning the possibility of directly using extended BN F grammars, Earley himself already gave some hints and later a few parser generators have been implemented, but no authoritative work exists, to the best of our knowledge. Another long-standing discussion concerns the pros and cons of using look-ahead. Since this issue is out of scope here, and a few experimental studies (see [Aycock and Horspool 2002]) have indicated that look-ahead-less algorithms can be faster at least for programming languages, we present the simpler version that does not use look-ahead. This is in line with the classical theoretical presentations of the Earley parsers for BN F grammars, such as the one in [Révész 1991]. Actually, our focus in the present work is on programming languages that are nonambiguous formal notations (unlike natural languages). Therefore our variant of the Earley algorithm is well suited for non-ambiguous EBN F grammars, though possibly nondeterministic, and the related procedure for building parse trees does not deal with multiple trees or forests. 5.1 String recognition Our algorithm is straightforward to understand, if one comes from the Vector Stack implementation of the ELR (1) parser of Section 3.4. When analyzing a string x = x1 . . . xn (with | x | = n ≥ 1) or x = ε (with | x | = n = 0), the algorithm uses a vector E [0 . . . n] or E [0], respectively, of n + 1 ≥ 1 elements, called Earley vector. Every vector element E [i] contains a set of pairs h pX , j i that consist of a state pX of the machine MX for some nonterminal X, and of an integer index j (with 0 ≤ j ≤ i ≤ n) that points back to the element E [j] that contains a corresponding pair with the initial state 0X of the same machine MX . This index marks the position in the input string, from where the currently assumed derivation from nonterminal X may have started. Before introducing our variant of the Earley Algorithm for EBN F grammars, we preliminarily define the operations Completion and TerminalShift. Completion (E, i) - - with index 0 ≤ i ≤ n do - - loop that computes the closure operation - - for each pair that launches machine MX   X for each pair h p, j i ∈ E [i] and X, q ∈ V, Q s.t. p → q do add pair h 0X , i i to element E [i] end for - - nested loops that compute the nonterminal shift operation - - for each final pair that enables a shift on nonterminal X Parsing methods streamlined · 47  for each pair h f, j i ∈ E [i] and X ∈ V such that f ∈ FX do - - for each pair that shifts on nonterminal X   X for each pair h p, l i ∈ E [j] and q ∈ Q s.t. p → q do add pair h q, l i to element E [i] end for end for while some pair has been added  Notice that in the Completion operation the nullable nonterminals are dealt with by a combination of closure and nonterminal shift operations. TerminalShift (E, i) - - with index 1 ≤ i ≤ n - - loop that computes the terminal shift operation - - for each preceding pair that shifts on terminal xi   x for each pair h p, j i ∈ E [i − 1] and q ∈ Q s.t. p →i q do add pair h q, j i to element E [i] end for The algorithm below for Earley syntactic analysis uses Completion and T erminalShif t. Algorithm 5.1. Earley syntactic analysis. - - analyze the terminal string x for possible acceptance - - define the Earley vector E [0 . . . n] with |x| = n ≥ 0 E [0] := { h 0S , 0 i } - - initialize the first elem. E [0] for i := 1 to n do - - initialize all elem.s E [1 . . . n] E [i] := ∅ end for Completion (E, 0) - - complete the first elem. E [0] i := 1 - - while the vector is not finished and the previous elem. is not empty  while i ≤ n ∧ E [i − 1] 6= ∅ do TerminalShift (E, i) - - put into the current elem. E [i] Completion (E, i) - - complete the current elem. E [i] i++ end while Example 5.2. Non-deterministic EBN F grammar with nullable nonterminal. 48 · Parsing methods streamlined The Earley acceptance condition if the following: h f, 0 i ∈ E [n] with f ∈ FS . A string x belongs to language L (G) if and only of the Earley acceptance condition is true. Figure 16 lists a non-ambiguous, non-deterministic EBN F grammar and shows the corresponding machine net. The string a a b b a a is analyzed: its syntax tree and analysis trace are in Figures 17 and 18, respectively; the edges in the latter figure ought to be ignored as they are related with the syntax tree construction discussed later. Machine Network Extended Grammar (EBNF) a A b S→ a+ ( b B a) ∗ | MS A+ ← 5S ↓ A a 0S b 1S 2S 3S B ↓ a 4S → b a MA → 0A A→aAb | ab 1A 3A → 2A A b c B→ bBa | c | ε MB → 0B 1B ↓ Fig. 16. 2B B b 3B → a Non-deterministic EBN F grammar G and network of Example 5.2. S a a b B b B a a ε Fig. 17. Syntax tree for the string a a b b a a of Example 5.2. The following lemma correlates the presence of certain pairs in the Earley vector elements, with the existence of a leftmost derivation for the string prefix analyzed up to that · Parsing methods streamlined 49 1B 3 2S 0 1S 0 1S 0 0B 0B 3 2B 3 3A 1 3A 0 3S 0 4S 0 1A 4 1A 5 0A 5 0A 6 0S 0 1A 0 1A 1 3S 0 5S 0A 0 0A 1 0A 2 2A 0 0A 4 E0 a E1 Fig. 18. a E2 b 4 E3 b E4 3B a E5 3 a 0 E6 Tabular parsing trace of string a a b b a a with the machine net in Figure 16. point and, together with the associated corollary, provides a proof of the correctness of the algorithm. L EMMA 5.3. If it holds h qA , j i ∈ E [i], which implies inequality j ≤ i, with qA ∈ QA , i.e., state qA belongs to the machine MA of nonterminal A, then it holds h 0A , j i ∈ ∗ E [j] and the right-linearized grammar Ĝ admits a leftmost derivation 0A ⇒ xj+1 . . . xi qA ∗ if j < i or 0A ⇒ qA if j = i. The proof is in the Appendix. C OROLLARY 5.4. If the Earley acceptance condition is satisfied, i.e., if h fS , 0 i ∈ + E [n] with fS ∈ FS , then the EBNF grammar G admits a derivation S ⇒ x, i.e., x ∈ L (S), and string x belongs to language L (G). The following lemma, which is the converse of Lemma 5.3, states the completeness of the Earley Algorithm. L EMMA 5.5. Take an EBNF grammar G and a string x = x1 . . . xn of length n that belongs to language L (G). In the right-linearized grammar Ĝ, consider any leftmost derivation d of a prefix x1 . . . xi (i ≤ n) of x, that is: + d : 0S ⇒ x1 . . . xi qA W with qA ∈ QA and W ∈ Q∗A . The two points below apply: (1) if it holds W 6= ε, i.e., W = rB Z for some rB ∈ QB , then it holds ∃ j 0 ≤ j ≤ i and A ∃ pB ∈ QB such that the machine net has an arc pB → rB and grammar Ĝ admits 50 · Parsing methods streamlined + + two leftmost derivations d1 : 0S ⇒ x1 . . . xj pB Z and d2 : 0A ⇒ xj+1 . . . xi qA , so that derivation d decomposes as follows: d pB →0A rB d2 = d : 0S ⇒1 x1 . . . xj pB Z =⇒ ⇒ x1 . . . xj xj+1 . . . xi qA rB Z x1 . . . xj 0A rB Z x1 . . . xi qA W A as an arc pB → rB in the net maps to a rule pB → 0A rB in grammar Ĝ (2) this point is split into two steps, the second being the crucial one: (a) if it holds W = ε, then it holds A = S, i.e., nonterminal A is the axiom, qA ∈ QS and h qA , 0 i ∈ E [i] (b) if it also holds x1 . . . xi ∈ L (G), i.e., the prefix also belongs to language L (G), then it holds qA = fS ∈ FS , i.e., state qA = fS is final for the axiomatic machine MS , and the prefix is accepted by the Earley algorithm Limit cases: if it holds i = 0 then it holds x1 . . . xi = ε; if it holds j = i then it holds xj+1 . . . xi = ε; and if it holds x = ε (so n = 0) then both cases hold, i.e., j = i = 0. If the prefix coincides with the whole string x, i.e., i = n, then step (2b) implies that string x, which by hypothesis belongs to language L (G), is accepted by the Earley algorithm, which therefore is complete. The proof is in the Appendix. 5.2 Syntax tree construction The next procedure BuildTree (BT) builds the parse tree of a recognized string through processing the vector E constructed by the Earley algorithm. Function BT is recursive and has four formal parameters: nonterminal X ∈ V , state f , and two nonnegative indices j and i. Nonterminal X is the root of the (sub)tree to be built. State f is final for machine MX ; it is the end of the computation path in MX that corresponds to analyzing the substring generated by X. Indices j and i satisfy the inequality 0 ≤ j ≤ i ≤ n; they respectively specify the left and right ends of the substring generated by X: + X =⇒ xj+1 . . . xi G + + X =⇒ ε if j = i if j < i G + Grammar G admits derivation S ⇒ x1 . . . xn or S ⇒ ε, and the Earley algorithm accepts string x. Thus, element E [n] contains the final axiomatic pair h f, 0 i. To build the tree of string x with root node S, function BT is called with parameters BT ( S, f, 0, n ); then the function will recursively build all the subtrees and will assemble them in the final tree. Function BT returns the syntax tree in the form of a parenthesized string, with brackets labeled by the root nonterminal of each (sub)tree. The commented code follows. BuildTree ( X, f, j, i ) - - X is a nonterminal, f is a final state of MX and 0 ≤ j ≤ i ≤ n - - return as parenthesized string the syntax tree rooted at node X - - node X will have a list C of terminal and nonterminal child nodes - - either list C will remain empty or it will be filled from right to left C := ε - - set to ε the list C of child nodes of X Parsing methods streamlined q := f - - set to f the state q in machine MX k := i - - set to i the index k of vector E · 51 - - walk back the sequence of term. & nonterm. shift oper.s in MX while ( q 6= 0X ) do - - while current state q is not initial x (a) - - try to backwards recover a terminal shift move p →k q, i.e., - - check if node X has terminal xk as its current child leaf ! ∃ h = k − 1 ∃ p ∈ QX such that if then x h p, j i ∈ E [h] ∧ net has p →k q C := xk · C - - concatenate leaf xk to list C end if Y (b) - - try to backwards recover a nonterm. shift oper. p → q, i.e., - - check if node X has nonterm. Y as its current child node ! ∃ Y ∈ V ∃ e ∈ FY ∃ h j ≤ h ≤ k ≤ i ∃ p ∈ QX s.t. if then Y h e, h i ∈ E [k] ∧ h p, j i ∈ E [h] ∧ net has p → q - - recursively build the subtree of the derivation: + + - - Y ⇒ xh+1 . . . xk if h < k or Y ⇒ ε if h = k G G - - and concatenate to list C the subtree of node Y C := BuildTree ( Y, e, h, k ) · C end if q := p - - shift the current state q back to p k := h - - drag the current index k back to h end while return ( C )X - - return the tree rooted at node X Figure 18 reports the analysis trace of Example 5.2 and also shows solid edges that correspond to iterations of the while loop in the procedure, and dashed edges that match the recursive calls. Notice that calling function BT with equal indices i and j, means building a subtree of the empty string, which may be made of one or more nullable nonterminals. This happens in the Figure 19, witch shows the tree of the BT calls and of the returned subtrees for Example 5.2, with the call BT (B, 0B , 4, 4 ). Notice that since a leftmost derivation uniquely identifies a syntax tree, the conditions in the two mutually exclusive if-then conditionals inside the while loop, are always satisfied in only one way: otherwise the analyzed string would admit several distinct left derivations and therefore it would be ambiguous. As previously remarked, nullable terms are dealt with by the Earley algorithm through a chain of Closure and Nonterminal Shift operations. An optimized version of the algorithm can be defined to perform the analysis of nullable terminals in a single step, along the same 52 · Parsing methods streamlined = a1 a2  BT ( S, 4S , 0, 6 )   a a b b ( ε )B a B a S BT ( B, 3B , 3, 5 )  = b ( ε )B a B b3 b4 BT ( B, 0B , 4, 4 ) a6 a5 = ( ε )B ε Fig. 19. Calls and return values of BuildTree for Example 5.2. lines as defined by [Aycock and Horspool 2002]; further work by the same authors also defines optimized procedures for building the parse tree in the presence of nullable nonterminals, which can also be adjusted and applied to our version of the Earley algorithm. 6. CONCLUSION We hope that this extension and conceptual compaction of classical parser construction methods, will be appreciated by compiler and language designers as well as by instructors. Starting from syntax diagrams, which are the most readable representation of grammars in language reference manuals, our method directly constructs deterministic shift-reduce parsers, which are more general and accurate than all preceding proposals. Then we have extended to the EBN F case Beatty’s old theoretical comparisons of LL (1) versus LR (1) grammars, and exploited it to derive general deterministic top-down parsers through stepwise simplifications of shift-reduce parsers. We have evidenced that such simplifications are correct if multiple-transitions and left-recursive derivations are excluded. For completeness, to address the needs of non-deterministic EBN F grammars, we have included an accurate presentation of the tabular Earley parsers, including syntax tree generatio. Our goal of coming up with a minimalist comprehensive presentation of parsing methods for Extended BN F grammars, has thus been attained. To finish we mention a practical development. There are circumstances that suggest or impose to use separate parsers, for different language parts identified by a grammar partition, i.e., by the sublanguages generated by certain subgrammars. The idea of grammar partition dates back to [Korenjak 1969], who wanted to reduce the size of an LR (1) pilot by decomposing the original parser into a family of subgrammar parsers, and to thus reduce the number of candidates and macro-states. Parser size reduction remains a goal of parser partitioning in the domain of natural language processing, e.g., see [Meng et al. 2002]. In such projects the component parsers are all homogeneous, whereas we are more interested in heterogeneous partitions, which use different parsing algorithms. Why should one want to diversify the algorithms used for different language parts? First, a language may contain Parsing methods streamlined · 53 parts that are harder to parse than others; thus a simpler ELL (1) parser should be used whenever possible, limiting the use of an ELR (1) parser - or even of an Earley one to the sublanguages that warrant a more powerful method. Second, there are well-known examples of language embedding, such as SQL inside C, where the two languages may be biased towards different parsing methods. Although heterogeneous parsers can be built on top of legacy parsing programs, past experimentation of mixed-mode parsers (e.g., [Crespi-Reghizzi and Psaila 1998]) has met with practical rather than conceptual difficulties, caused by the need to interface different parser systems. Our unifying approach looks promising for building seamless heterogeneous parsers that switch from an algorithm to another as they proceed. This is due to the homogeneous representation of the parsing stacks and tables, and to the exact formulation of the conditions that enable to switch from a more to a less general algorithm. Within the current approach, mixed mode parsing should have little or no implementation overhead, and can be viewed as a pragmatic technique for achieving greater parsing power without committing to a more general but less efficient non-deterministic algorithm, such as the so-called generalized LR parsers initiated by [Tomita 1986]. Aknowledgement. We are grateful to the students of Formal Languages and Compiler courses at Politecnico di Milano, who bravely accepted to study this theory while in progress. We also thank Giorgio Satta for helpful discussions of Earley algorithms. REFERENCES A HO , A., L AM , M., S ETHI , R., AND U LLMAN , J. 2006. Compilers: principles, techniques and tools. PrenticeHall, Englewoof Cliffs, NJ. AYCOCK , J. AND B ORSOTTI , A. 2009. Early action in an Earley parser. Acta Informatica 46, 8, 549–559. AYCOCK , J. AND H ORSPOOL , R. 2002. Practical Earley parsing. Comput. J. 45, 6, 620–630. B EATTY, J. C. 1982. On the relationship between the LL(1) and LR(1) grammars. Journal of the ACM 29, 4, 1007–1022. C ELENTANO , A. 1981. LR parsing technique for extended context-free grammars. Computer Languages 6, 2, 95–107. C HAPMAN , N. P. 1984. LALR (1, 1) parser generation for regular right part grammars. Acta Inf 21, 29–45. C RESPI R EGHIZZI , S. 2009. Formal languages and compilation. Springer, London. C RESPI -R EGHIZZI , S. AND P SAILA , G. 1998. Grammar partitioning and modular deterministic parsing. Computer Languages 24, 4, 197–227. E ARLEY, J. 1970. An efficient context-free parsing algorithm. Commun. ACM 13, 94–102. G ÁLVEZ , J. F. 1994. A note on a proposed LALR parser for extended context-free grammars. Inf. Process. Lett. 50, 6, 303–305. G RUNE , D. AND JACOBS , C. 2004. Parsing techniques: a practical guide. Vrije Universiteit, Amsterdam. G RUNE , D. AND JACOBS , C. 2009. Parsing techniques: a practical guide, 2nd ed. Springer, London. H EILBRUNNER , S. 1979. On the definition of ELR(k) and ELL(k) grammars. Acta Informatica 11, 169–176. H EMERIK , K. 2009. Towards a taxonomy for ECFG and RRPG parsing. In Language and Automata Theory and Applications, A. H. Dediu, A.-M. Ionescu, and C. Martı́n-Vide, Eds. LNCS, vol. 5457. Springer, 410–421. K ANNAPINN , S. 2001. Reconstructing LR theory to eliminate redundance, with an application to the construction of ELR parsers (in German). Ph.D. thesis, Technical University of Berlin. K NUTH , D. 1965. On the translation of languages from left to right. Information and Control 8, 607–639. K NUTH , D. E. 1971. Top-down syntax analysis. Acta Informatica 1, 79–110. K ORENJAK , A. J. 1969. A practical method for constructing LR(k) processors. Commun. ACM 12, 11, 613–623. L A L ONDE , W. R. 1979. Constructing LR parsers for regular right part grammars. Acta Informatica 11, 177–193. L EE , G.-O. AND K IM , D.-H. 1997. Characterization of extended LR(k) grammars. Inf. Process. Lett. 64, 2, 75–82. 54 · Parsing methods streamlined L EWI , J., D E V LAMINCK , K., H UENS , J., AND H UYBRECHTS , M. 1979. A programming methodology in compiler construction. North-Holland, Amsterdam. I and II. L OMET, D. B. 1973. A formalization of transition diagram systems. J. ACM 20, 2, 235–257. M ENG , H., L UK , P.-C., X U , K., AND W ENG , F. 2002. GLR parsing with multiple grammars for natural language queries. ACM Trans. on Asian Language Information Processing 1, 2 (June), 123–144. M ORIMOTO , S. AND S ASSA , M. 2001. Yet another generation of LALR parsers for regular right part grammars. Acta Informatica 37, 671–697. R ÉV ÉSZ , G. 1991. Introduction to formal languages. Dover, New York. ROSENKRANTZ , D. J. AND S TEARNS , R. E. 1970. Properties of deterministic top-down parsing. Information and Control 17, 3 (Oct.), 226–256. S ASSA , M. AND N AKATA , I. 1987. A simple realization of LR-parsers for regular right part grammars. Inf. Process. Lett. 24, 2, 113–120. T OMITA , M. 1986. Efficient parsing for natural language: a fast algorithm for practical systems. Kluwer, Boston. W IRTH , N. 1975. Algorithms + Data Structures = Programs. Prentice-Hall publishers, Englewood Cliffs, NJ. Parsing methods streamlined · 55 7. APPENDIX Proof of theorem 3.6 Let G be an EBN F grammar represented by machine net M and let Ĝ be the equivalent right-linearized grammar. Then net M meets the ELR (1) condition if, and only if, grammar Ĝ meets the LR (1) condition. P ROOF. Let Q be the set of the states of M. Clearly, for any non-empty rule X → Y Z of Ĝ, it holds X ∈ Q, Y ∈ Σ ∪ { 0A | 0A ∈ Q } and Z ∈ Q \ { 0A | 0A ∈ Q }. Let P and P̂ be the ELR and LR pilots of G and Ĝ, respectively. Preliminarily we study the correspondence between their transition functions, ϑ and ϑ̂, and their m-states, ˆ It helps us compare the pilot graphs for the running example in Figures denoted by I and I. 2 and 20, and for Example 3.5 in Figure 21. Notice that in the m-states of the LR pilot P̂, the candidates are denoted by marked rules (with a •). We observe that since grammar Ĝ is BN F , the graph of P̂ has the well-known property that all the edges entering the same m-state, have identical labels. In contrast, the identicallabel property (which is a form of locality) does not hold for P and therefore a m-state of P is possibly split into several m-states of P̂. Due to the very special right-linearized grammar form, the following mutually exclusive classification of the m-states of P̂, is exhaustive: —the m-state Iˆ0 is initial —a m-state Iˆ is intermediate if every candidate in Iˆ|base has the form pA → Y • qA —a m-state Iˆ is a sink reduction if every candidate has the form pA → Y qA • For instance, in Figure 20 the intermediate m-states are numbered from 1 to 12 and the sink reduction m-states from 13 to 24. We say that a candidate hqX , λi of P corresponds to a candidate of P̂ of the form hpX → s • qX , ρi, if the look-ahead sets are identical, i.e., if λ = ρ. Then two mstates I and Iˆ of P and P̂, respectively, are called correspondent if the candidates in I|base and in Iˆ|base correspond to each other. Moreover, we arbitrarily define as correspondent the initial m-states I0 and Iˆ0 . To illustrate, in the running example a few pairs of correspondent m-states are: (Iˆ1 , I1 ), (Iˆ9 , I1 ), (Iˆ4 , I4 ) and (Iˆ10 , I4 ). The following straightforward properties of correspondent m-states will be needed. L EMMA 7.1. The mapping defined by the correspondence relation from the set containing m-state Iˆ0 and the intermediate m-states of P̂, to the set of the m-states of P, is total, many-to-one and onto (surjective). (1) For any terminal or nonterminal symbol s and for any correspondent m-states I and ˆ transition ϑ (I, s) = I ′ is defined ⇐⇒ transition ϑ (I, ˆ s) = Iˆ′ is defined and I, ′ ˆ′ ′ ˆ m-state I is intermediate. moreover I , I are correspondent. (2) Let state fA be final non-initial. Candidate hfA , λi is in m-state I (actually in its base I|base ) ⇐⇒ a correspondent m-state Iˆ contains candidates hpA → s • fA , λi and hfA → ε •, λi. (3) Let state 0A be final initial with A 6= S. Candidate h0A , πi is in m-state I ⇐⇒ a correspondent m-state Iˆ contains candidate h0A → ε •, πi. (4) Let state 0S be final. Candidate h0S , πi is in m-state I0 ⇐⇒ candidate h0S → ε •, πi is in m-state Iˆ0 . · 56 Parsing methods streamlined 1T → 0E 2T • a ( ⊣ Iˆ20 Iˆ8 2T → ) 3T • a ( ⊣ Iˆ24 2T ր 3T ր ) 1T → 0E • 2T a ( ⊣ 2T → • ) 3T 2T → ) • 3T a(⊣ a(⊣ 3T → • ε = ε • a ( ⊣ Iˆ1 Iˆ0 a 0E → 0T • 1E 0E → • 0T 1E 0E P̂ → 0E → • ε = ε • 0T → • a 3T 0T → • ( 1T Iˆ12 ⊣ 1E → • 0T 1E 0T 1E → • ε = ε • a(⊣ 0T → • a 3T 0T → a 3T • a ( ⊣ Iˆ14 ⊣ 3T ր a ⊣ 0T → a • 3T a(⊣ 3T → • ε = ε • a ( ⊣ Iˆ2 a(⊣ 0T → • ( 1T ց 1E 0E → 0T 1E • ⊣ Iˆ13 0T a 1E → 0T • 1E 1E → • 0T 1E ( ( Iˆ9 1E → • ε = ε • ⊣ ⊣ 1E 0T → • a 3T a ( ⊣ −→ 0T → • ( 1T 1E → 0T 1E • ⊣ Iˆ21 0T ( Iˆ4 Iˆ3 0T → ( • 1T a(⊣ 1T → • 0E 2T a(⊣ 0E → • 0T 1E 0E → • ε = ε • 0T → • a 3T 0T → • ( 1T a 0E → 0T • 1E 0T ) 1E → • 0T 1E 1E → • ε = ε • 0T → • a 3T a() 0T → a 3T • a ( ) Iˆ17 ) 3T ր a ) 0T → a • 3T a() 3T → • ε = ε • a ( ) Iˆ5 a() 0T → • ( 1T ց 1E ւ 1T 0E → 0T 1E • ) Iˆ16 Iˆ15 0T → ( 1T • a ( ⊣ 0T a 0T 1E → 0T • 1E 1E → • 0T 1E ( ( 1E → • ε = ε • 0T → • a 3T 0T → • ( 1T ) ) a() 0T ւ 1E ( Iˆ10 1E → 0T 1E • ) Iˆ22 a Iˆ6 0T → ( • 1T a() 1T → • 0E 2T a() 0E → • 0T 1E 0E → • ε = ε • 0T → • a 3T 0T → • ( 1T 1T → 0E • 2T a ( ) ) 0E 2T → • ) 3T Iˆ7 a() ( a() 2T → ) • 3T ) a() 3T → • ε = ε • a ( ) 2T ց 1T → 0E 2T • a ( ) Iˆ19 Iˆ11 3T ց 2T → ) 3T • a ( ) Iˆ23 ւ 1T Iˆ18 0T → ( 1T • a ( ) Fig. 20. Pilot graph of the right-linearized grammar Ĝ of the running example (see Ex. 2.4, p.8). Parsing methods streamlined · 57 ˆ and for any initial state 0A , it holds (5) For any pair of correspondent m-states I and I, 0A ∈ I|closure ⇐⇒ 0A → • α ∈ Iˆ|closure for every alternative α of 0A . P ROOF. (of Lemma). First, to prove that the mapping is onto, assume by contradiction that a m-state I such that hqA , λi ∈ I, has no correspondent intermediate m-state in P̂. Clearly, there exists a Iˆ such that the kernels of Iˆ|base and I|base are identical because the right-linearized grammar has the same derivations as M (vs Sect. 2.1), and it remains that the look-aheads of a correspondent candidate in Iˆ|base and I|base differ. The definition of look-ahead set for a BN F grammar (not included) is the traditional one; it is easy to check that our Def. 2.7 of closure function computes exactly the same sets, a contradiction. Item 1. We observe that the bases of I and Iˆ are identical, therefore any candidate ˆ with h0B → • s qB , πi computed h0B , πi computed by Def. 2.7, matches a candidate in I, ˆ s) is by the traditional closure function for P̂. Therefore if ϑ (I, s) is defined, also ϑ (I, defined and yields an intermediate m-state. Moreover the next m-states are clearly correˆ s) is a sink reduction spondent since their bases are identical. On the other hand, if ϑ̂ (I, m-state then ϑ (I, s) is undefined. s Item 2. Consider an edge pA → fA entering state fA . By item 1, consider J and Jˆ as correspondent m-states that include the predecessor state pA , resp. within the candidate ˆ s) includes hpA , λi and hqA → t • pA , λi. Then ϑ (J, s) includes hfA , λi and ϑ̂ (J, ˆ hpA → s • fA , λi, hence also ϑ̂ (J , s)|closure includes hfA → ε •, λi. Item 3. If candidate h0A , πi is in I, it is in I|closure . Thus I|base contains a candidate hpB , λi such that closure (hpB , λi) ∋ h0A , πi. Therefore, some intermediate m-state contains a candidate hqB → s • pB , λi in the base and candidate h0A → ε •, πi in its closure. The converse reasoning is analogous. Item 4. This case is obvious. Item 5. We consider the case where the m-state I is not initial and the state 0A ∈ I|closure results from the closure operation applied to a candidate of I|base (the other cases, where I is the initial m-state I0 or the state 0A results from the closure operation applied to a candidate of I|closure , can be similarly dealt with): 0A ∈ I|closure ⇐⇒ some machine A MB includes the edge pB → qB ⇐⇒ pB ∈ I|base ⇐⇒ for every correspondent state Iˆ there are some suitable X and rB such that rB → X • pB ∈ Iˆ|base ⇐⇒ pB → • 0A qB ∈ Iˆ|closure ⇐⇒ 0A → • α ∈ Iˆ|closure for every alternative α of nonterminal 0A . This concludes the proof of the Lemma. Part “if” (of Theorem). We argue that a violation of the ELR (1) condition in P implies an LR (1) conflict in P̂. Three cases need to be examined. Shift - Reduce conflict. Consider a conflict in m-state: I ∋ hfB , { a }i where fB is final non-initial and ϑ (I, a) is defined ˆ a) By Lemma 7.1, items (1) and (2), there exists a correspondent m-state Iˆ such that ϑ (I, ˆ thus proving that the same conflict is in P̂. is defined and hfB → ε •, { a }i ∈ I, Similarly, consider a conflict in m-state: I ∋ h0B , { a }i where 0B is final and initial and ϑ (I, a) is defined 58 · Parsing methods streamlined ˆ a) By Lemma 7.1, items (1) and (3), there exists a correspondent m-state Iˆ such that ϑ (I, ˆ thus proving that the same conflict is in P̂. is defined and h0B → ε •, { a }i ∈ I, Reduce - Reduce conflict. Consider a conflict in m-state:  I ⊇ hfA , { a }i, hfB , { a }i where fA and fB are final non-initial By item (2) of the Lemma, the same conflict exists in a m-state:  Iˆ ⊇ hfA → ε •, { a }i, hfB → ε •, { a }i Similarly, a conflict in m-state:  I ⊇ h0A , { a }i, hfB , { a }i where 0A and fB are final corresponds, by items (2) and (3), to a conflict in m-state:  Iˆ ⊇ h0A → ε •, { a }i, hfB → ε •, { a }i By item (4) the same holds true for the special case 0A = 0S . X Convergence conflict. Consider a convergence conflict I → I ′ , where:  I ⊇ hpA , { a }i, hqA , { a }i δ (pA , X) = δ (qA , X) = ra ′ I|base ∋ hrA , { a }i First, if neither pA nor qA are the initial state, both candidates are in the base of I. By X item (1) there are correspondent intermediate m-states and transition Iˆ → Iˆ′ with Iˆ′ ⊇  hpA → X • rA , { a }i, hpA → X • rA , { a }i . Therefore m-state ϑ̂ (Iˆ′ , rA ) contains two reduction candidates with identical look-ahead, which is a conflict. Quite similarly, if (arbitrarily) qA ≡ 0A , then candidate hpA , { a }i is in the base of I and I|base necessarily contains a candidate C = hs, ρi such that closure (C) = h0A , { a }i. Therefore for some t and Y , there exists a m-state Iˆ correspondent of I such that ht → Y • s, ρi ∈ Iˆ|base and h0A → • X rA , { a }i ∈ Iˆ|closure , hence it holds ˆ X) = Iˆ′ , and h0A → X • rA , { a }i ∈ Iˆ′ . ϑ̂ (I, Part “only if” (of Theorem). We argue that every LR (1) conflict in P̂ entails a violation of the ELR (1) condition in P. Shift - Reduce conflict. The conflict occurs in a m-state Iˆ such that hfB → ε •, { a }i ∈ ˆ ˆ a) is defined. By items (1) and (2) (or (3)) of the Lemma, the correspondent I and ϑ (I, m-state I contains hfB , { a }i and the move ϑ (I, a) is defined, thus resulting in the same conflict. Reduce - Reduce conflict. First, consider a m-state having the form:  Iˆ|closure ⊇ hfA → ε •, { a }i, hfB → ε •, { a }i where fA and fB are final non-initial. By item (2) of the Lemma, the correspondent m-state  I contains the candidates I ⊇ hfA , { a }i, hfB , { a }i and has the same conflict. Second, consider a m-state having the form:  Iˆ|closure ⊇ hfA → ε •, { a }i, h0B → ε •, { a }i where fA is final non-initial. By items (2) and (3) the same conflict is in the correspondent m-state I. Parsing methods streamlined · 59 At last, consider a reduce-reduce conflict in a sink reduction m-state:  Iˆ ⊇ hpA → X rA •, { a }i, hqA → X rA •, { a }i rA ˆ I such that Iˆ′ contains candidates hpA → Then there exist a m-state and a transition Iˆ′ → X • rA , { a }i and hqA → X • rA , { a }i. Therefore the correspondent m-state I ′ X contains candidate hrA , { a }i, and there are a m-state Iˆ′′ and a transition Iˆ′′ → Iˆ′ such  ′′ that it holds hpA → • X rA , { a }i, hqA → • X rA , { a }i ⊆ Iˆ|closure . Since ′′ ′′ ′′ Iˆ 6= ∅, Iˆ is not a sink reduction state; let us call I its correspondent state. Then: |closure ′′ —If pA is initial then hpA , { a }i ∈ I|closure by virtue of Item 5. ′′ —If pA is not initial then there exists a candidate htA → Z • pA , { a }i ∈ Iˆ|base (notice that the look-ahead is the same because we are still in the same machine MA ) and hpA , { a }i ∈ I ′′ . A similar reasoning applies to state qA . Therefore hpA , { a }i ∈ I ′′ X and I ′′ → I ′ has a convergence conflict. This concludes the ‘if” and “only if” parts, and the Theorem itself. As a second example to illustrate convergence conflicts, the pilot graph P̂ equivalent to P of Figure 4, p.16, is shown in Figure 21. Proof of property 4.11 If the guide sets of a P CF G are disjoint, then the machine net satisfies the ELL (1) condition of Definition 4.8. P ROOF. Since the ELL (1) condition consists of the three properties of the ELR (1) pilot: (1) absence of left recursion; (2) ST P , i.e., absence of multiple transitions; and (3) absence of shift-reduce and reduce-reduce conflicts, we will prove that the presence of disjoint guide sets in the P CF G implies that all these three conditions hold. (1) We prove that if a grammar (represented as a net) is left recursive then its guide sets are not disjoint. If the grammar is left recursive then ∃ n > 1 such that in the P CF G there are n call edges 0A1 99K 0A2 , 0A2 99K 0A3 , . . ., 0An 99K 0A1 . Then since ∄ A ∈ V such that LA (G) = { ε }, it holds ∃ a ∈ Σ and ∃ Ai ∈ V such that there is a a shift edge 0Ai → pA and a ∈ Gui (0Ai 99K 0Ai+1 ), hence the guide sets for these two edges in the P CF G are not disjoint. Notice that the presence of left recursion due to rules of the kind A → X A . . . with X a nullable nonterminal, can be ruled out because this kind of left recursion leads to a shift-reduce conflict, as discussed in Section 4.2 and shown in Figure 13. (2) We prove that the presence of multiple transitions implies that the guide sets in the P CF G are not all disjoint. This is done by induction, through starting from the initial m-state of the pilot automaton (which has an empty base) and showing that all reachable m-states of the pilot automaton satisfy the Single Transition Property (ST P ), unless the guide sets of the P CF G are not all disjoint. We also note that the transitions from the m-states satisfying ST P lead to m-states the base of which is a singleton set: we call such m-states Singleton Base and we say that they satisfy the Singleton Base Property (SBP ). Induction base: Assume there exists a multiple transition from the initial m-state I0 = closure (h0S , { ⊣ }i). Hence I0 includes n > 1 candidates h0X1 , π1 i, h0X2 , π2 i, 60 · Parsing methods streamlined Iˆ1 0S → a • 1S Iˆ0 0S → • a 1S P̂ → 0S → • b 4S a ⊣ 0S → • b 4S e Iˆ5 1A → • 0S 2A 0S → • a 1S e 0S → • b 4S 0S → • 0A 5S 0S → • 0A 5S 0A → • a 1A 0A → • a 1A b b 1S → b • 2S ⊣ 1S → b • 2S 0S → b • 4S e 0S → b • 4S 2S → • c 3S 2S → • d 3S 4S → • c 3S ⊣ Iˆ8 ⊣ 4S → c • 3S e e 4S → • c 3S 2S → c • 3S Iˆ11 3S → • ε = ε • e ⊣ 2S → c 3S • ⊣ e 4S → c • 3S 3S → • ε = ε • e 3S 4S → c 3S • e e c 2S → c • 3S Iˆ10 sink a e 2S → • c 3S 2S → • d 3S e c Iˆ10 e 1S → • b 2S a 0S → • a 1S right-linearized grammar for Ex. 3.5   0S → a 1S      0  S → b 4S     0 → 0A 5S  S      1 → b 2S S      2 → c 3S S     2 → d3 S S   3S → ε     4S → c 3S       5S → e 3S      0A → a 1A      1  A → 0S 2A   2 → ε A 0S → a • 1S 0A → a • 1A 1A → • 0S 2A 0S → • 0A 5S 0A → • a 1A ⊣ 0A → a • 1A e 1S → • b 2S ⊣ Iˆ4 3S Iˆ11 sink 2S → c 3S • 4S → c 3S • e reduce-reduce conflict ⇐⇒ convergence conflict Fig. 21. Part of the (traditional - with marked rules) pilot of the right-linearized grammar for Ex. 3.5; the reducec reduce conflict in m-state Iˆ11 sink matches the convergence conflict of the edge I8 → I11 of P (Fig. 4, p.16). . . ., h0Xn , πn i, and for some h and k with 1 ≤ h < k ≤ n, the machine net inX X cludes transitions 0Xh → pXh and 0Xk → pXk , with X being a terminal symbol s.t. X = a ∈ Σ or being a nonterminal one s.t. X = Z ∈ V . Let us first consider the case X = a ∈ Σ and assume the candidate h0Xk , πk i derives from candidate h0Xh , πh i through a (possibly iterated) closure operation; then the P CF G includes the call edges 0Xh 99K 0Xh+1 , . . ., 0Xk−1 99K 0Xk , the inclusions { a } ⊆ Gui (0Xk−1 99K 0Xk ) ⊆ . . . ⊆ Gui (0Xh 99K 0Xh+1 ) hold, and there are two nona disjoint guide sets Gui (0Xh → pXh ) = { a } and Gui (0Xh 99K 0Xh+1 ) ⊇ { a }. Assuming instead that there is a candidate 0Xj , πj such that both h0Xh , πh i and h0Xk , πk i are derived by the closure operation through distinct paths, then the P CF G includes the call edges 0Xj 99K 0Xjh1 , . . ., 0Xjh−1 99K 0Xjh with 0Xjh = 0Xh and Parsing methods streamlined · 61 0Xj 99K 0Xjk1 . . . 0Xjk−1 99K 0Xjk with 0Xjk = 0Xk ; thus the following inclusions hold: { a } ⊆ Gui (0Xjh−1 99K 0Xjh ) ⊆ . . . ⊆ Gui (0Xj 99K 0Xjh1 ) and { a } ⊆ Gui (0Xjk−1 99K 0Xjk ) ⊆ . . . ⊆ Gui (0Xj 99K 0Xjk1 ); therefore the two guide sets Gui (0Xj 99K 0Xjh1 ) and Gui (0Xj 99K 0Xjk1 ) are not disjoint. Let us now consider the case X = Z ∈ V . Then if the candidate h0Xk , πk i derives from h0Xh , πh i, the P CF G includes the call edges 0Xh 99K 0Xh+1 , . . ., 0Xk−1 99K 0Xk , as well as 0Xh 99K 0Z and 0Xk 99K 0Z , hence Ini (0Z ) ⊆ Gui (0Xh 99K 0Z ) and Ini (0Z ) ⊆ Gui (0Xk 99K 0Z ) ⊆ Gui (0Xh 99K 0Xh+1 ), and the two guide sets Gui (0Xh 99K 0Z ) and Gui (0Xh 99K 0Xh+1 ) are not disjoint. The case of both candidates h0Xh , πh i and h0Xk , πk i deriving from a common candidate 0Xj , πj through distinct sequences of closure operations, is similarly dealt with and leads to the conclusion that in the P CF G there are two call edges originating from state 0Xj , the guide sets of which are not disjoint. This concludes the induction base. Inductive step: Consider a non-initial, singleton base m-state I, such that a multiple transition ϑ (I, X) is defined. Since I has a singleton base, of the two candidates from where the multiple transition originates, at least one is in I|closure . The case of both candidates in the closure is at all similar to the one treated in the base case of the induction. Therefore, we consider the case of one candidate in the base with a non-initial state qA and one in the closure with an initial state 0Y . Then if X = a ∈ Σ the P CF G has: states rA , rY and 0Y1 , . . ., 0Yn , with n ≥ 1 and Yn = Y ; shift edges a a qA → rA and 0Y → rY ; and call edges qA 99K 0Y1 , . . ., 0Yn−1 99K 0Y such that { a }⊆ Ini (0Y) ⊆ Gui (0Yn−1 99K 0Y ) ⊆ . . .⊆ Gui (q A 99K 0Y1 ) and { a } = a a Gui qA → rA . Thus the two guide sets Gui qA → rA and Gui (qA 99K 0Y1 ) are not disjoint. Otherwise if X = Z ∈ V , the P CF G includes the nonterminal shift Z Z edges qA → rA and 0Yn → rYn with rYn ∈ QYn , and the call edges qA 99K 0Y1 , . . ., 0Yn−1 99K 0Yn , and also the two call edges qA 99K 0Z and 0Yn 99K 0Z . Then it holds Gui (qA 99K 0Z ) ∩ Gui (qA 99K 0Y1 ) ⊇ Ini (Z), and the two guide sets Gui (qA 99K 0Z ) and Gui (qA 99K 0Y1 ) are not disjoint. This concludes the induction. (3) We prove that the presence of shift-reduce or reduce-reduce conflicts implies that the guide sets are not disjoint. We can assume that all m-states are singleton base, hence if there are two conflicting candidates at most one of them is in the base, as in the point (2) above. So: (a) First we consider reduce-reduce conflicts and the two cases of candidates being both in the closure or only one. i. If both candidates are in the closure then there are n > 1 candidates h0X1 , π1 i, . . ., h0Xn , πn i such that the candidates h0X1 , π1 i and h0Xn , πn i are conflicting, hence for some a ∈ Σ it holds a ∈ Gui (0X1 →) and a ∈ Gui (0Xn →). If the candidate h0Xn , πn i derives from candidate h0X1 , π1 i through a sequence of closure operations, then the P CF G includes the chain of call edges 0X1 99K 0X2 , . . ., 0Xn−1 99K 0Xn with a ∈ Gui (0Xn−1 99K 0Xn ) ⊆ . . . ⊆ Gui (0X1 99K 0X2 ), therefore a ∈ Gui (0X1 →) ∩ Gui (0X1 99K 0X2 ) and these two guide sets are not disjoint. If instead there is a candidate 0Xj , πj such that both h0X1 , π1 i and h0Xn , πn i are obtained from that candidate through distinct paths, it can be shown that in the P CF G there are two call edges departing from state 0Xj , the guide sets of which are not 62 · Parsing methods streamlined disjoint, as in the point (2) above. ii. The case where one candidate is in the base and one is in the closure, is quite similar to the one in the previous point: there are a candidate hfA , πi and n ≥ 1 candidates h0X1 , π1 i, . . ., h0Xn , πn i such that the candidates hfA , πi and h0Xn , πn i are conflicting, hence for some a ∈ Σ it holds a ∈ Gui (fA →) and a ∈ Gui (0Xn →), the P CF G includes the call edges fA 99K 0X1 , . . ., 0Xn−1 99K 0Xn , whence a ∈ Gui (fA →) ∩ Gui (fA 99K 0X1 ) and these two guide sets are not disjoint. (b) Then we consider shift-reduce conflicts and the three cases that arise depending on whether the conflicting candidates are both in the closure or only one, or whether there is one candidate that is both shift and reduction. i. If there are two conflicting candidates, both in the closure of m-state I, then either the closure of I includes n > 1 candidates h0X1 , π1 i, . . ., h0Xn , πn i and the P CF G includes the call edges 0X1 99K 0X2 , . . ., 0Xn−1 99K 0Xn , or the closure includes three candidates 0Xj , πj , h0Xh , πh i and h0Xk , πk i such that h0Xh , πh i and h0Xk , πk i derive from 0Xj , πj through distinct chains of closure operations. We first consider a linear chain of closure operations from h0X1 , π1 i to h0Xn , πn i. Let us first consider the case where h0X1 , π1 i is a reduction candidate (hence 0X1 is a final state), and ∃ a ∈ Σ such that a ∈ π1 and ∃ q ∈  a QXn such that 0Xn → q. Then it holds a ∈ Gui 0Xn−1 99K 0Xn ⊆ . . . ⊆ Gui (0X1 99K 0X2 ), therefore a ∈ Gui (0X1 →) ∩ Gui (0X1 99K 0X2 ) and these two guide sets are not disjoint. Let us then consider the symmetric case where 0Xn is a final state (hence h0Xn , πn i is a reduction candidate), a and ∃ a ∈ Σ such that a ∈ πn and  ∃ q ∈ QX1 such that 0X1 → q. Then it holds a ∈ Gui  0Xn−199K 0Xn ⊆ . . . ⊆ Gui (0X1 99K 0X2 ), therefore a ii. { a } = Gui 0X1 → q ∩ Gui (0X1 99K 0X2 ) and these two guide sets are not disjoint. The other case, where two candidates h0Xh , πh i and h0Xk , πk i derive from a third one 0Xj , πj through distinct chains of closure operations, is treated in a similar way and leads to the conclusion that in the P CF G there are two call edges departing from state 0Xj , the guide sets of which are not disjoint. If there are two conflicting candidates, one in the base and one in the closure, then we consider the two cases that arise depending on whether the reduction candidate is in the closure or in the base, similarly to point 3(b)i above. Let us first consider the case where the base contains the candidate hpA , πi, the closure includes n ≥ 1 candidates h0X1 , π1 i, . . ., h0Xn , πn i, state 0Xn is final hence h0Xn , πn i is a reduction candidate, and ∃ a ∈ Σ such that a a ∈ πn and ∃ q ∈ QA such that pA → q. Then since 0Xn is final, it holds N ullable (Xn) and { a } ∈ Gui (0Xn−1  99K 0Xn ) ⊆ . . . ⊆ Gui (0pA 99K a 0X1 ), whence { a } = Gui pA → q ∩ Gui (pA 99K 0X1 ) and these two guide sets are not disjoint. Let us then consider the symmetric case where the base contains a candidate hfA , πi with fA ∈ FA (hence hfA , πi is a reduction candidate), the closure includes n ≥ 1 candidates h0X1 , π1 i, . . ., h0Xn , πn i, and ∃ a ∈ Σ Parsing methods streamlined · 63 a such that a ∈ π and ∃ q ∈ QXn such that 0Xn → q. Then it holds a ∈ Gui (0Xn−1 99K 0Xn ) ⊆ . . . ⊆ Gui (fA 99K 0X1 ), therefore { a } ⊆ Gui (fA →) ∩ Gui (fA 99K 0X1 ) and these two guide sets are not disjoint. iii. If there is one candidate hpA , πi that is both shift and reduce, then pA ∈ FA , a and ∃ a ∈ Σ such that a ∈ π and ∃  qA ∈ QA such  that pA → qA . Then it a holds { a } = Gui (pA →) ∩ Gui pA → qA and so there are two guide sets on edges departing from the same P CF G node, that are not disjoint. This concludes the proof of the Property. Proof of lemma 5.3 If it holds h qA , j i ∈ E [i], which implies inequality j ≤ i, with qA ∈ QA , i.e., state qA belongs to the machine MA of nonterminal A, then it holds h 0A , j i ∈ E [j] and the ∗ right-linearized grammar Ĝ admits a leftmost derivation 0A ⇒ xj+1 . . . xi qA if j < i or ∗ 0A ⇒ qA if j = i. P ROOF. By induction on the sequence of insertion operations performed in the vector E by the Analysis Algorithm. Base. h0S , 0i ∈ E [0] and the property stated by the Lemma is trivially satisfied: ∗ h0S , 0i ∈ E [0] and 0S ⇒ 0S . Induction. We examine the three operations below: TerminalShift: if hqA , ji ∈ E [i] results from a TerminalShift operation, then it holds ′ ′ ′ ∃ qA such that δ (qA , xi ) = qA and hqA , ji ∈ E [i − 1], as well as h0A , ji ∈ E [j] and ∗ ∗ ′ 0A ⇒ xj+1 . . . xi−1 qA by the inductive hypothesis; hence 0A ⇒ xj+1 . . . xi−1 xi qA . Closure: if h0B , ii ∈ E [i] then the property is trivially satisfied: h0B , ii ∈ E [i] and ∗ 0B ⇒ 0B . NonterminalShift: suppose first that j < i; if hqFA , ji ∈ E [i] then h0A , ji ∈ E [j] ∗ and 0A ⇒ xj+1 . . . xi qFA by the inductive hypothesis; furthermore, if hqB , ki ∈ E [j] ∗ then h0B , ki ∈ E [k] and 0B ⇒ xk+1 . . . xj qB by the inductive hypothesis; also if ′ ′ ′ δ (qB , A) = qB then qB ⇒ 0A qB ; and since hqB , ki is added to E [i], it is eventually ′ proved that hqB , ki ∈ E [i] implies h0B , ki ∈ E [k] and: ∗ 0B ⇒ xk+1 . . . xj qB ∗ ′ ⇒ xk+1 . . . xj 0A qB ∗ ′ ⇒ xk+1 . . . xj xj+1 . . . xi qFA qB ′ ⇒ xk+1 . . . xi qB If j = i then the same reasoning applies, but there is not any TerminalShift since the derivation does not generate any terminal. In particular, for the NonterminalShift case, ∗ we have that if hqFA , ii ∈ E [i], then h0A , ii ∈ E [i] and 0A ⇒ qFA by the inductive ∗ hypothesis; and the rest follows as before but with k = i and 0B ⇒ qB . The reader may easily complete by himself with the two remaining proof cases where k < j = i or k = j < i, which are combinations. This concludes the proof of the Lemma. 64 · Parsing methods streamlined Proof of lemma 5.5 Take an EBNF grammar G and a string x = x1 . . . xn of length n that belongs to language L (G). In the right-linearized grammar Ĝ, consider any leftmost derivation d of a prefix x1 . . . xi (i ≤ n) of x, that is: + d : 0S ⇒ x1 . . . xi qA W with qA ∈ QA and W ∈ Q∗A . The two points below apply: (1) if it holds W 6= ε, i.e., W = rB Z for some rB ∈ QB , then it holds ∃ j 0 ≤ j ≤ i and A ∃ pB ∈ QB such that the machine net has an arc pB → rB and grammar Ĝ admits + + two leftmost derivations d1 : 0S ⇒ x1 . . . xj pB Z and d2 : 0A ⇒ xj+1 . . . xi qA , so that derivation d decomposes as follows: d pB →0A rB d = d : 0S ⇒1 x1 . . . xj pB Z ⇒2 x1 . . . xj xj+1 . . . xi qA rB Z =⇒ x1 . . . xj 0A rB Z x1 . . . xi qA W A as an arc pB → rB in the net maps to a rule pB → 0A rB in grammar Ĝ (2) this point is split into two steps, the second being the crucial one: (a) if it holds W = ε, then it holds A = S, i.e., nonterminal A is the axiom, qA ∈ QS and h qA , 0 i ∈ E [i] (b) if it also holds x1 . . . xi ∈ L (G), i.e., the prefix also belongs to language L (G), then it holds qA = fS ∈ FS , i.e., state qA = fS is final for the axiomatic machine MS , and the prefix is accepted by the Earley algorithm Limit cases: if it holds i = 0 then it holds x1 . . . xi = ε; if it holds j = i then it holds xj+1 . . . xi = ε; and if it holds x = ε (so n = 0) then both cases hold, i.e., j = i = 0. If the prefix coincides with the whole string x, i.e., i = n, then step (2b) implies that string x, which by hypothesis belongs to language L (G), is accepted by the Earley algorithm, which therefore is complete. ∗ P ROOF. By induction on the length of the derivation S ⇒ x. ∗ Base. Since 0S ⇒ 0S the thesis (case (1)) is satisfied by taking i = 0. Induction. We examine a few cases: X ∗ —If 0S ⇒ x1 . . . xi qA W ⇒ x1 . . . xi 0X rA W (because qA → rA ) then the closure operation adds to E [i] the item h0X , ii, hence the thesis (case (1)) holds by taking for j the value i, for qA the value 0X , for qB the value rA and for W the value rA Z. xi+1 ∗ —If 0S ⇒ x1 . . . xi qA W ⇒ x1 . . . xi xi+1 rA W (because qA → rA ) then the operation TerminalShift (E, i + 1) adds to E [i + 1] the item hrA , ji, hence the thesis (case (1)) holds by taking for j the same value and for qA the value rA . ∗ —If 0S ⇒ x1 . . . xi qA W ⇒ x1 . . . xi W (because qA = fA ∈ FA and fA → ε) then: ∗ —If Z = ε, qA = fS ∈ FS and 0S ⇒ x1 . . . xi fS ⇒ x1 . . . xi , then the current derivation step is the last one and the string is accepted because the pair hfS , 0i ∈ E [i] by the inductive hypothesis. —If W = qB Z, then by applying the inductive hypothesis to x1 . . . xj , the following ∗ B facts hold: ∃ k 0 ≤ k ≤ j, ∃ pC ∈ QC such that 0S ⇒ x1 . . . xk pC Z ′ , pC → qC , · Parsing methods streamlined ∗ 65 A 0B ⇒ xk+1 . . . xj pB , pB → qB , and the vector E is such that hpC , hi ∈ E [k], h0B , ki ∈ E [k], hpB , ki ∈ E [j], h0A , ji ∈ E [j] and hqA , ji ∈ E [i]; then the nonterminal shift operation in the Completion procedure adds to E [i] the pair hqB , ki. ∗ A ∗ First, we notice that from 0B ⇒ xk+1 . . . xj pB , pB → qB and 0A ⇒ xj+1 . . . xi fA , ∗ B it follows that 0B ⇒ xk+1 . . . xi qB . Next, since pC → qC , it holds: ∗ 0S ⇒ x1 . . . xk pC Z ⇒ x1 . . . xk 0B qC Z ′ therefore: ∗ 0S ⇒ x1 . . . xk xk+1 . . . xi qB qC Z ′ and the thesis holds by taking for j the value k, for qA the value qB , for qB the value qC and for W the value qC Z ′ . The above situation is schematized in Figure 22. E0 a1 E1 ... ak hpC , hi hpB , ki hpA , ji h0B , ki h0A , ji hqB , ki Ek Fig. 22. ak+1 ... aj Ej Schematic trace of tabular parsing. This concludes the proof of the Lemma. aj+1 Ej+1 ai Ei
6 (cs.PL)
I/O-Efficient Similarity Join⋆ Rasmus Pagh, Ninh Pham, Francesco Silvestri⋆⋆ , and Morten Stöckel⋆ ⋆ ⋆ arXiv:1507.00552v2 [cs.DS] 28 Mar 2017 IT University of Copenhagen, Denmark Abstract. We present an I/O-efficient algorithm for computing similarity joins based on locality-sensitive hashing (LSH). In contrast to the filtering methods commonly suggested our method has provable subquadratic dependency on the data size. Further, in contrast to straightforward implementations of known LSH-based algorithms on external memory, our approach is able to take significant advantage of the available internal memory: Whereas the time complexity of classical algorithms includes a factor of N ρ , where ρ is a parameter of the LSH used, the I/O complexity of our algorithm merely includes a factor (N/M )ρ , where N is the data size and M is the size of internal memory. Our algorithm is randomized and outputs the correct result with high probability. It is a simple, recursive, cache-oblivious procedure, and we believe that it will be useful also in other computational settings such as parallel computation. Keywords: Similarity join; locality sensitive hashing; cache aware; cache oblivious; 1 Introduction The ability to handle noisy or imprecise data is becoming increasingly important in computing. In database settings this kind of capability is often achieved using similarity join primitives that replace equality predicates with a condition on similarity. To make this more precise consider a space U and a distance function d : U × U → R. The similarity join of sets R, S ⊆ U is the following: Given a radius r, compute the set R ⊲⊳≤r S = {(x, y) ∈ R × S | d(x, y) ≤ r}. This problem occurs in numerous applications, such as web deduplication [3, 13, 19], document clustering [4], data cleaning [2, 6]. As such applications arise in large-scale datasets, the problem of scaling up similarity join for different metric distances is getting more important and more challenging. Many known similarity join techniques (e.g., prefix filtering [2, 6], positional filtering [19], inverted index-based filtering [3]) are based on filtering techniques ⋆ ⋆⋆ ⋆⋆⋆ The research leading to these results has received funding from the European Research Council under the EU 7th Framework Programme, ERC grant agreement no. 614331. In part supported by University of Padova project CPDA121378 and by MIUR of Italy project AMANDA while working at the University of Padova. Supported by the Danish National Research Foundation / Sapere Aude program. that often, but not always, succeed in reducing computational costs. If we let N = |R| + |S| these techniques generally require Ω(N 2 ) comparisons for worstcase data. Another approach is locality-sensitive hashing (LSH) where candidate output pairs are generated using collisions of carefully chosen hash functions. The LSH is defined as follows. Definition 1. Fix a distance function d : U × U → R. For positive reals r, c, p1 , p2 , and p1 > p2 , c > 1, a family of functions H is (r, cr, p1 , p2 )-sensitive if for uniformly chosen h ∈ H and all x, y ∈ U: – If d(x, y) ≤ r then Pr [h(x) = h(y)] ≥ p1 ; – If d(x, y) ≥ cr then Pr [h(x) = h(y)] ≤ p2 . We say that H is monotonic if Pr [h(x) = h(y)] is a non-increasing function of the distance function d(x, y). We also say that H uses space s if a function h ∈ H can be stored and evaluated using space s. LSH is able to break the N 2 barrier in cases where for some constant c > 1 the number of pairs in R ⊲⊳≤cr S is not too large. In other words, there should not be too many pairs that have distance within a factor c of the threshold, the reason being that such pairs are likely to become candidates, yet considering them does not contribute to the output. For notational simplicity, we will talk about far pairs at distance greater than cr (those that should not be reported), near pairs at distance at most r (those that should be reported), and c-near pairs at distance between r and cr (those that should not be reported but the LSH provides no collision guarantees). Our contribution. In this paper we study I/O-efficient similarity join methods based on LSH. That is, we are interested in minimizing the number of I/O operations where a block of B points from U is transferred between an external memory and an internal memory with capacity for M points from U. Our main result is the first cache-oblivious algorithm for similarity join that has provably sub-quadratic dependency on the data size N and at the same time inverse polynomial dependency on M . In essence, where previous methods have an overhead factor of either N/M or (N/B)ρ we obtain an overhead of (N/M )ρ , where 0 < ρ < 1 is a parameter of the LSH employed, strictly improving both. We show: Theorem 1. Consider R, S ⊆ U, let N = |R| + |S|, assume 18 log N + 3B ≤ M < N and that there exists a monotonic (r, cr, p1 , p2 )-sensitive family of functions with respect to distance measure d, using space B and with p2 < p1 < 1/2. Let ρ = log p1 / log p2 . Then there exists a cache-oblivious randomized algorithm computing R ⊲⊳≤r S (w.r.t. d) with probability 1 − O (1/N ) using      ρ |R ⊲⊳ S| |R ⊲⊳ S| N N ≤cr ≤r  + +  I/Os.1 Õ  M B MB MB 1 The Õ (·)-notation hides polylog(N ) factors. 2 We conjecture that the bound in Theorem 1 is close to the best possible for the class of “signature based” algorithms that work by generating a set of LSH values (from a black-box and monotonic family) and checking all pairs that collide. Our conjecture is based on an informal argument, given in full in Section 4. We describe a worst-case input, where it seems significant advances are required to beat Theorem 1 asymptotically. Further, we observe that for M = N our bound coincides with the optimal bound of reading the input, and when M = 1 our bound coincides with the bounds of the best known internal memory algorithms. It is worth noting that whereas most methods in the literature focus on a single (or a few) distance measure, our method works for an arbitrary space and distance measure that allows LSH, e.g., Hamming, Manhattan (ℓ1 ), Euclidean (ℓ2 ), Jaccard, and angular metric distances. Since our approach makes use of LSH as a black box, the problem of reporting the complete join result with certainty would require major advances in LSH methods (see [16, 17] for recent progress in this direction). A primary technical hurdle in the paper is that we cannot use any kind of strong concentration bounds on the number of points having a particular value, since hash values of an LSH family may be correlated by definition. Another hurdle is duplicate elimination in the output stemming from pairs having multiple LSH collisions. However, in the context of I/O-efficient algorithms it is natural to not require the listing of all near pairs, but rather we simply require that the algorithm enumerates all such near pairs. More precisely, the algorithm calls for each near pair (x, y) a function emit(x, y). This is a natural assumption in external memory since it reduces the I/O complexity. In addition, it is desired in many applications where join results are intermediate results pipelined to a subsequent computation, and are not required to be stored on external memory. Our upper bound can be easily adapted to list all instances by increasing the I/O complexity of an unavoidable additive term of Θ (|R ⊲⊳≤r S|/B) I/Os. Organization. The organization of the paper is as follows. In Section 2, we briefly review related work. Section 3 describes our algorithms including a warm-up cache-aware approach and the main results, a cache-oblivious solution, its analysis, and a randomized approach to remove duplicates. Section 4 provides some discussions on our algorithms with some real datasets. Section 5 concludes the paper. 2 Related Work In this section, we briefly review LSH, the computational I/O model, and some state-of-the-art similarity join techniques. Locality-sensitive hashing (LSH). LSH was originally introduced by Indyk and Motwani [14] for similarity search problems in high dimensional data. This technique obtains a sublinear (i.e., O (N ρ )) time complexity by increasing the gap of collision probability between near points and far points using the LSH family as defined in Definition 1. The gap of collision probability is polynomial, with an exponent of ρ = log p1 / log p2 dependent on c. 3 It is worth noting that the standard LSHs for metric distances, including Hamming [14], ℓ1 [7], ℓ2 [1, 7], Jaccard [4] and angular distances [5] are monotonic. These common LSHs are space-efficient, and use space comparable to that required to store a point, except the LSH of [1] which requires space N o(1) . We do not explicitly require the hash values themselves to be particularly small. However, using universal hashing we can always map to small bit strings while introducing no new collisions with high probability. Thus we assume that B hash values fit in one memory block. Computational I/O model. We study algorithms for similarity join in the external memory model, which has been widely adopted in the literature (see, e.g., the survey by Vitter [18]). The external memory model consists of an internal memory of M words and an external memory of unbounded size. The processor can only access data stored in the internal memory and move data between the two memories in blocks of size B. For simplicity we will here measure block and internal memory size in units of points from U, such that they can contain B points and M points, respectively. The I/O complexity of any algorithm is defined as the number of input/output blocks moved between the two memories by the algorithm. The cache-aware approach makes explicit use of the parameters M and B to achieve its I/O complexity, whereas the cache-oblivious one [9] does not explicitly use any model parameters. The latter approach is desirable as it implies optimality on all levels of the memory hierarchy and does not require parameter tuning when executed on different physical machines. Note that the cache-oblivious model assumes that the internal memory is ideal in the sense that it has an optimal cachereplacement policy. Such cache-replacement policy can evict the block that is used furthest in the future, and can place a block anywhere in the cache (full associativity). Similarity join techniques. We review some state-of-the-art of similarity join techniques most closely related to our work. – Index-based similarity join. A popular approach is to make use of indexing techniques to build a data structure for one relation, and then perform queries using the points of the other relation. The indexes typically perform some kind of filtering to reduce the number of points that a given query point is compared to (see, e.g., [3, 6, 10]). Indexing can be space consuming, in particular for LSH, but in the context of similarity join this is not a big concern since we have many queries, and thus can afford to construct each hash table “on the fly”. On the other hand, it is clear that index-based similarity join techniques will not be able to take significant advantage of internal memory when N ≫ M . Indeed, the query complexity stated in [10] is O ((N/B)ρ ) I/Os. Thus the I/O complexity of using indexing for similarity join will be high. – Sorting-based. The indexing technique of [10] can be adapted to compute similarity joins more efficiently by using the fact that many points are being looked up in the hash tables. This means that all lookups can be done in 4 a batched fashion using sorting. This results in a dependency on N that is  Õ (N/B)1+ρ I/Os, where ρ ∈ (0; 1) is a parameter of the LSH family. – Generic joins. When N is close to M the I/O-complexity can be improved by using general join operators optimized for this case. It is easy to see that when N/M is an integer, a nested loop join requires N 2 /(M B) I/Os. Our cache-oblivious algorithm will make use of the following result on cacheoblivious nested loop joins: Theorem 2. (He and Luo [12]) Given a similarity join condition, the join of relations R and S can be computed by a cache-oblivious algorithm in   |R| + |S| |R||S| O I/Os. + B MB This number of I/Os suffices to generate the result in memory, but may not suffice to write it to disk. We note that a similarity join can be part of a multi-way join involving more than two relations. For the class of acyclic joins, where the variables compared in join conditions can be organized in a tree structure, one can initially apply a full reducer [20] that removes tuples that will not be part of the output. This efficiently reduces any acyclic join to a sequence of binary joins. Handling cyclic joins is much harder (see e.g. [15]) and outside the scope of this paper. 3 Our Algorithms In this section we describe our I/O efficient algorithms. We start in Section 3.1 with a warm-up cache-aware algorithm. It uses an LSH family where the value of the collision probability is set to be a function of the internal memory size. Section 3.2 presents our main result, a recursive and cache-oblivious algorithm, which uses the LSH with a black-box approach and does not make any assumption on the value of collision probability. Section 3.3 describes the analysis and Section 3.4 shows how to reduce the expected number of times of emitting near pairs. 3.1 Cache-aware algorithm: ASimJoin We will now describe a simple cache-aware algorithm called ASimJoin, which achieves the worst case I/O bounds as stated in Theorem 1. ASimJoin relies on an (r, cr, p′1 , p′2 )-sensitive family H′ of hash functions with the following properties: p′2 ≤ M/N and p′1 ≥ (M/N )ρ , for a suitable value 0 < ρ < 1. Given an arbitrary monotonic (r, cr, p1 , p2 )-sensitive family H, the family H′ can be built by concatenating ⌈logp2 (M/N )⌉ hash functions from H. For simplicity, we assume that logp2 (M/N ) is an integer and thus the probabilities p′1 and p′2 can be exactly obtained. Nevertheless, the algorithm and its analysis can be extended 5 Algorithm ASimJoin(R, S): R, S are the input sets. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Repeat 3 log (N ) times Associate to each point in R and S a counter initially set to 0; Repeat L = 2/p′1 times Choose h′i ∈ H′ uniformly at random; Use h′i to partition (in-place) R and S in buckets Rv , Sv of points with the hash value v; For each hash value v generated in the previous step /* For simplicity we assume that |Rv | ≤ |Sv | */ Split Rv and Sv into chunks Ri,v and Si,v of size at most M/2; For every chunk Ri,v of Rv Load in memory Ri,v ; For every chunk Si,v of Sv do Load in memory Si,v ; Compute Ri,v × Si,v and emit all near pairs. For each far pair, increment the associated counters by 1; Remove from Si,v and Ri,v all points with the associated counter larger than 8LM , and write Si,v back to external memory; Write Ri,v back to external memory; to the general case by increasing the I/O complexity by a factor at most p−1 1 in the worst case; in practical scenarios, this factor is a small constant [4, 7, 10]. ASimJoin assumes that each point in R and S is associated with a counter initially set to 0. This counter can be thought as an additional dimension of the point which hash functions and comparisons do not take into account. The algorithm repeats L = 2/p′1 times the following procedure. A hash function is randomly drawn from the (r, cr, p′1 , p′2 )-sensitive family, and it is used for partitioning the sets R and S into buckets of points with the same hash value. We let Rv and Sv denote the buckets respectively containing points of R and S with the same hash value v. Then, the algorithm iterates through every hash value and, for each hash value v, it uses a double nested loop for generating all pairs of points in Rv × Sv . The double nested loop loads consecutive chunks of Rv and Sv of size at most M/2: the outer loop runs on the smaller set (say Rv ), while the inner one runs on the larger one (say Sv ). For each pair (x, y), the algorithm emits the pair if d(x, y) ≤ r, increases by 1 counters associated with x and y if d(x, y) > cr, or ignores the pair if r < d(x, y) ≤ cr. Every time the counter of a point exceeds 8LM , the point is considered to be far away from all points and will be removed from the bucket. Chunks will be moved back in memory when they are no more needed. The entire ASimJoin algorithm is repeated 3 log N times to find all near pairs with high probability. The following theorem shows the I/O bounds of the cache-aware approach. Theorem 3. Consider R, S ⊆ U and let N = |R| + |S| be sufficiently large. Assume there exists a monotonic (r, cr, p′1 , p′2 )-sensitive family of functions with 6 respect to distance measure d with p′1 = (M/N )ρ and p′2 = M/N , for a suitable value 0 < ρ < 1. With probability 1 − 1/N , the ASimJoin algorithm enumerates all near pairs using      ρ |R ⊲⊳ S| |R ⊲⊳ S| N N ≤r ≤cr  + +  I/Os. Õ  M B MB MB Proof. We observe that the I/O cost of Steps 4-5, that is of partitioningsets N ρ N ) · B for R and S according to a hash function h′i , is L · sort(N ) = Õ ( M N ρ 2 L ≤ ( M ) repetitions . We now consider the I/O cost of an iteration of the loop in Step 6 for a given hash value v. When the size of one bucket (say Rv ) is smaller than M/2, we are able to load the whole Rv into the internal memory and then load consecutive blocks of Sv to execute join operations. Hence, the I/O cost of this step is at most (|Rv | + |Sv |)/B. The total I/O cost of the 3L log (N ) iterations of Step 6 among all possible hash values where at least one bucket has size smaller than N ρ N M/2 is at most L · N B = 2( M ) · B I/Os. The I/O cost of Step 6 when both buckets Rv and Sv are larger than M/2 is 2|Rv ||Sv |/(BM ). This means that the amortized cost of each pair in Rv × Sv is 2/(BM ). Therefore the amortized I/O cost of all iterations of Step 6, when there are no bucket size less than M/2, can be upper bounded by multiplying the total number of generated pairs by 2/(BM ). Based on this observation, we classify and enumerate generated pairs into three groups: near pairs, c-near pairs and far pairs. We denote by Cn , Ccn and Cf the respective size of each group, and upper bound these quantities to derive the proof. 1. Number of near pairs. By definition, LSH gives a lower bound on the probability of collision of near pairs. It may happen that the collision probability of near pairs is 1. Thus, two near points might collide in all L repetitions of Step 3 and in all 3 log (N ) repetitions of Step 1. This means that Cn ≤ 3L log (N )|R ⊲⊳≤r S|. Note that this bound is a deterministic worst case bound. 2. Number of c-near pairs. Any c-near pair from R ⊲⊳≤cr S appears in a bucket with probability at most p′1 due to monotonicity of our LSH family. Since we have L = 2/p′1 repetitions, each c-near pair collides at most 2 in expectation. In other words, the expected number of c-near pair collisions among L repetitions is at most 2|R ⊲⊳≤cr S|. By using the Chernoff bound [8, Exercise 1.1] with 3 log (N ) independent L repetitions (in Step 1), we have Pr [Ccn ≥ 6 log (N )|R ⊲⊳≤cr S|] ≤ 1/N 2 , Pr [Ccn ≤ 6 log (N )|R ⊲⊳≤cr S|] ≥ 1 − 1/N 2 . 2   We let sort(N ) = O (N/B) log M/B (N/B) be shorthand for the I/O complexity [18] of sorting N points. 7 3. Number of far pairs. If x ∈ R ∪ S is far away from all points, the expected number of collisions of x in L hash table (including duplicates) is at most 8LM , since then the point is removed by Step 14. Hence the total number of examined far pairs is Cf ≤ 24N LM log (N ). Therefore, by summing the number of near pairs Cn , c-near pairs Ccn , and far pairs Cf , and multiplying these quantities by the amortized I/O complexity 2/(BM ), we upper bound the I/O cost of all iterations of Step 6, when there are no buckets of size less than M/2, is Õ  N M ρ  N |R ⊲⊳≤r S| + B BM  |R ⊲⊳≤cr S| + BM  , with probability at least 1 − 1/N 2 . By summing all the previous bounds, we get the claimed I/O bound with high probability. We now analyze the probability to enumerate all near pairs. Consider one iteration of Step 1. A near pair is not emitted if at least one of the following events happen: 1. The two points do not collide in the same bucket in each of the L iterations ′ of Step 3. This happens with probability (1 − p′1 )L = (1 − p′1 )2/p1 ≤ 1/e2 . 2. One of the two points is removed by Step 14 because it collides with more than 8LM far points. By the Markov’s inequality and since there are at most N far points, the probability that x collides with at least 8LM points in the L iterations is at most 1/8. Then, this event happens with probability at most 1/4. Therefore, a near pair does not collide in one iteration of Step 1 with probability at most 1/e2 + 1/4 < 1/2 and never collides in the 3 log N iterations with probability at most (1/2)3 log N = 1/N 3 . Then, by an union bound, it follows that all near pairs (there are at most N 2 of them) collide with probability at least 1 − 1/N and the theorem follows. ⊓ ⊔ As already mentioned in the introduction, a near pair (x, y) can be emitted many times during the algorithm since points x and y can be hashed on the same value in p(x, y)L rounds of Step 3, where p(x, y) ≥ p′1 denotes the actual collision probability. A simple approach for avoiding duplicates is the following: for each near pair found during the i-th iteration of Step 3, the pair is emitted only if the two points did not collide by all hash functions used in the previous i − 1 rounds. The check starts from the hash function used in the previous round and backtracks until a collision is found or there are no more hash functions. This approach increases the worst case complexity by a factor L. Section 3.4 shows a more efficient randomized algorithm that reduces the number of replica per near pair to a constant. This technique also applies to the cache-oblivious algorithm described in the next section. 8 Algorithm OSimJoin(R, S, ψ): R, S are the input sets, and ψ is the recursion depth. If |R| > |S|, then swap (the references to) the sets such that |R| ≤ |S|; If ψ = Ψ or |R| ≤ 1, then compute R ⊲⊳≤r S using the algorithm of Theorem 2 and return; Pick a random sample S ′ of 18∆ points from S (or all points if |S| < 18∆); Compute R′ containing all points of R that have distance smaller than cr to at least half points in S ′ ; Compute R′ ⊲⊳≤r S using the algorithm of Theorem 2; Repeat L = 1/p1 times Choose h ∈ H uniformly at random; Use h to partition (in-place) R\R′ and S in buckets Rv , Sv of points with hash value v; For each v where Rv and Sv are nonempty, recursively call OSimJoin (Rv , Sv , ψ + 1); 1 2 3 4 5 6 7 8 9 3.2 Cache-oblivious algorithm: OSimJoin The above cache-aware algorithm uses an (r, cr, p′1 , p′2 )-sensitive family of functions H′ , with p′1 ∼ (M/N )ρ and p′2 ∼ M/N , for partitioning the initial sets into smaller buckets, which are then efficiently processed in the internal memory using the nested loop algorithm. If we know the internal memory size M , this LSH family can be constructed by concatenating ⌈logp2 (M/N )⌉ hash functions from any given primitive (r, cr, p1 , p2 )-sensitive family H. Without knowing M in the cache-oblivious setting, such family cannot be built. Therefore, we propose OSimJoin, a cache-oblivious algorithm that efficiently computes the similarity join without knowing the internal memory size M and the block length B. OSimJoin uses as a black-box a given monotonic (r, cr, p1 , p2 )-sensitive family H.3 The value of p1 and p2 can be considered constant in a practical scenario. As common in cache-oblivious settings, we use a recursive approach for splitting the problem into smaller and smaller subproblems that at some point will fit the internal memory, although this point is not known in the algorithm. We first give a high level description of the cache-oblivious algorithm and an intuitive explanation. We then provide a more detailed description and analysis. OSimJoin receives in input the two sets R and S of similarity join, and a parameter ψ denoting the depth in the recursion tree (initially, ψ = 0) that is used for recognizing the base case. Let |R| ≤ |S|, N = |R| + |S|, and denote with ∆ = log N and Ψ = ⌈log1/p2 N ⌉ two global values that are kept invariant in the recursive levels and computed using the initial input size N . For simplicity we assume that 1/p1 and 1/p2 are integers, and further assume without loss of generality that the initial size N is a power of two. Note that, if 1/p1 is not an 3 The monotonicity requirement can be relaxed to the following: Pr [h(x) = h(y)] ≥ Pr [h(x′ ) = h(y ′ )] for every two pairs (x, y) and (x′ , y ′ ) where d(x, y) ≤ r and d(x′ , y ′ ) > r. A monotonic LSH family clearly satisfies this assumption. 9 integer, the last iteration in Step 6 can be performed with a random variable L ∈ {⌊1/p1⌋, ⌈1/p1 ⌉} such that E [L] = 1/p1 . OSimJoin works as follows. If the problem is currently at the recursive level Ψ = ⌈log1/p2 N ⌉ or |R| ≤ 1, the recursion ends and the problem is solved using the cache-oblivious nested loop described in Theorem 2. Otherwise, the following operations are executed. By exploiting sampling, the algorithm identifies a subset R′ of R containing (almost) all points that are near or c-near to a constant fraction of points in S (Steps 3 – 4). Then we compute R′ ⊲⊳≤r S using the cacheoblivious nested-loop of Theorem 2 and remove points in R′ from R (Step 5). Subsequently, the algorithm repeats L = 1/p1 times the following operations: a hash function is extracted from the (r, cr, p1 , p2 )-sensitive family and used for partitioning R and S into buckets, denoted with Rv and Sv with any hash value v (Steps 7 – 8); then, the join Rv ⊲⊳≤r Sv is computed recursively by OSimJoin(Step 9). The explanation of our approach is the following. By recursively partitioning input points with hash functions from H, the algorithm decreases the probability of collision between two far points. In particular, the collision probability of a far pair is pi2 at the i-th recursive level. On the other hand, by repeating the partitioning 1/p1 times in each level, the algorithm guarantees that a near pair is enumerated with constant probability since the probability that a near pair collide is pi1 at the i-th recursive level. It deserves to be noticed that the collision probability of far and near pairs at the recursive level log1/p2 (N/M ) is Θ (M/N ) and Θ ((M/N )ρ ), respectively, which are asymptotically equivalent to the values in the cache-aware algorithm. In other words, the partitioning of points at this level is equivalent to the one in the cache-aware algorithm with collision probability for a far pair p′2 = M/N . Finally, we observe that, when a point in R becomes close to many points in S, it is more efficient to detect and remove it, instead of propagating it down to the base cases. This is due to the fact that the collision probability of very near pairs is always large (close to 1) and the algorithm is not able to split them into subproblems that fit in memory. 3.3 I/O Complexity and Correctness of OSimJoin Analysis of I/O Complexity. We will bound the expected number of I/Os of the algorithm rather than the worst case. This can be converted to an high probability bound by running log N parallel instances of our algorithm (without loss of generality we assume that the optimal cache replacement splits the cache into M/ log N parts that are assigned to each instance). The total execution stops when the first parallel instance terminates, which with probability at least 1 − 1/N is within a logarithmic factor of the expected I/O bound (logarithmic factors are absorbed in the Õ-notation). For notational simplicity, in this section we let R and S denote the initial input sets and let R̃ and S̃ denote the subsets given in input to a particular recursive subproblem (note that, due to Step 1, R̃ can denote a subset of R but also of S; similarly for S̃). We also let S̃ ′ denote the sampling of S̃ in Step 3, and with R̃′ the subset of R̃ computed in Step 4. Lemma 1 says that two properties 10 of the choice of random sample in Step 3 are almost certain, and the proof relies on Chernoff bounds on the choice of S̃ ′ . In the remainder of the paper, we assume that Lemma 1 holds and refer to this event as A holding with probability 1 − O (1/N ). Lemma 1. With probability at least 1 − O (1/N ) over the random choices in Step 3, the following bounds hold for every subproblem OSimJoin(R̃, S̃, ψ): |R̃′ ⊲⊳ S̃| > ≤cr |(R̃\R̃′ ) ⊲⊳ S̃| > >cr |R̃′ ||S̃| , 6 |R̃\R̃′ ||S̃| . 6 (1) (2) Proof. Let x ∈ R̃ be a point which is c-near to at most one sixth of the points in S̃, i.e., |x ⊲⊳≤cr S̃| ≤ |S̃|/6. The point x enters R̃′ if there are at least 9∆ cnear points in S̃ ′ and this happens, for a Chernoff bound [8, Theorem 1.1], with Pi=Ψ −1 probability at most 1/N 4 . Each point of R∪S appears in at most 2 i=0 Li < 2LΨ < 2N 2 subproblems and there are at most N points in R ∪ S. Therefore, with probability 1 − 2N 3 N −4 = 1 − 2N −1 , we have that in every subproblem OSimJoin(R̃, S̃, ψ) no point with at most |S̃|/6 c-near points in S̃ is in R̃′ . Hence each point in R̃ has at least |S̃|/6 c-near points in S̃, and the bound in Equation 1 follows. We can similarly show that, with probability 1 − 2N 3 N −4 = 1 − 2N −1 , we have that in every subproblem OSimJoin(R̃, S̃, ψ) all points with at least 5|S̃|/6 c-near points in S̃ are in R̃′ . Then, each point in R̃\R̃′ has |S̃|/6 far points in S̃ and Equation 2 follows. ⊓ ⊔ To analyze the number of I/Os for subproblems of size more than M we bound the cost in terms of different types of collisions of pairs in R × S that end up in the same subproblem of the recursion. We say that (x, y) is in a particular subproblem OSimJoin(R̃, S̃, ψ) if (x, y) ∈ (R̃ × S̃) ∪ (S̃ × R̃). Observe that a pair (x, y) is in a subproblem if and only if x and y have colliding hash values on every step of the call path from the initial invocation of OSimJoin. Definition 2. Given Q ⊆ R × S let Ci (Q) be the number of times a pair in Q is in a call to OSimJoin at the i-th level of recursion. We also let Ci,k (Q), with 0 ≤ k ≤ log M , denote the number of times a pair in Q is in a call to OSimJoin at the i-th level of recursion where the smallest input set has size in [2k , 2k+1 ) if 0 ≤ k < log M , and in [M, +∞) if k = log M . The count is over all pairs and with multiplicity, so if (x, y) is in several subproblems at the i-th level, all these are counted. Next we bound the I/O complexity of OSimJoin in terms of Ci (R ⊲⊳≤cr S) and Ci,k (R ⊲⊳>cr S), for any 0 ≤ i < Ψ . We will later upper bound the expected size of these quantities in Lemma 3 and then get the claim of Theorem 1. 11 Lemma 2. Let ℓ = ⌈log1/p2 (N/M )⌉ and M ≥ 18 log N + 3B. Given that A holds, the I/O complexity of OSimJoin(R, S, 0) is       C R ⊲⊳ S C R ⊲⊳ S L log M ℓ Ψ −1 i i,k X X  N Lℓ X >cr ≤cr  Õ  + +  B  MB B2k i=0 i=ℓ k=0 Proof. To ease the analysis we assume that no more than 1/3 of internal memory is used to store blocks containing elements of R and S, respectively. Since the cache-oblivious model assumes an optimal cache replacement policy this cannot decrease the I/O complexity. Also, internal memory space used for other things than data (input and output buffers, the recursion stack of size at most Ψ ) is less than M/3 by our assumption that M ≥ 18 log n + 3B. As a consequence, we have that the number of I/Os for solving a subproblem OSimJoin (R̃, S̃, ·)   where |R̃| ≤ M/3 and |S̃| ≤ M/3 is O (|R̃| + |S̃|)/B , including all recursive calls. This is because there is space M/3 dedicated to both input sets and only I/Os for reading the input are required. By charging the cost of such subproblems to the writing of the inputs in the parent problem, we can focus on subproblems where the largest set (i.e., S̃) has size more than M/3. We notice that the cost of Steps 3–4 is dominated by other costs by our assumption that the set S̃ ′ fits in internal memory, which implies that it suffices to scan data once to implement these steps. This cost is clearly negligible with respect to the remaining steps and thus we ignore them. We first provide an upper bound on the I/O complexity required by all subproblems at a recursive level above ℓ. Let OSimJoin (R̃, S̃, i) be a recursive call at the i-th recursive level, for 0 ≤ i ≤ ℓ. The I/O cost of thenested loop join in Step 5 in OSimJoin (R̃, S̃, i) is O |S̃|/B + |R̃′ ||S̃|/(M B) by Theorem 2.   We can ignore the O |S̃|/B term since it is asymptotically negligible with respect to the cost of each iteration of Step 6, which is upper bounded later. By than |R̃′ ||S̃|/6 pairs, and thus Equation 1, we have that R̃′ ⊲⊳≤cr S̃ contains more   the cost of Step 5 in OSimJoin(R̃, S̃, i) is O |R̃′ ⊲⊳≤cr S̃|/(M B) . This means that we can bound the total I/O cost of all executions of Step 5 at level i of the recursion with O (Ci (R ⊲⊳≤cr S) /(M B)) since each near pair (x, y) appears in Ci ((x, y)) subproblems at level i. The second major part of the I/O complexity is the cost of preparing recursive calls in OSimJoin( R̃, S̃, i) (i.e.,   Steps 7–8). In fact, in each iteration of Step 6, the I/O cost is Õ (|R̃| + |S̃|)/B , which includes the cost of hashing and of sorting to form buckets. Since each point of R̃ and S̃ is replicated in L subproblems in Step 6, we have that each point of the initial sets R and S is replicated Li+1 times at level i. Since the average cost per entry is Õ (1/B), we have that the total cost for preparing recursive calls at level i is Õ N Li+1 /B . By summing the above terms, we have that the total I/O complexity of all subproblems in the i-th recursive level is upper bounded by: 12    R ⊲⊳ S C i  ≤cr N Li+1  . + Õ   MB B   (3) We now focus our analysis to bound the I/O complexity required by all subproblems at a recursive level below ℓ. Let again OSimJoin(R̃, S̃, i) be a recursive call at the i-th recursive level, for ℓ ≤ i ≤ Ψ . We observe that (part of) the cost of a subproblem at level i ≥ ℓ can be upper bounded by a suitable function of collisions among far points in OSimJoin (R̃, S̃, i). More specifically, consider an iteration of Step 6 in a subproblem at level i. Then, the cost for preparing the recursive calls and for performing Step 5 in each subproblem (at level i + 1) generated during the iteration, can be upper bounded as ! |R̃\R̃′ | + |S̃| |(R̃\R̃′ ) ⊲⊳≤cr S̃| Õ , + B BM since each near pair in (R̃\R̃′ ) ⊲⊳≤cr S̃ is found in Step 5 in at most one subproblem at level i + 1 generated during the iteration. Since we have that |(R̃\R̃′ ) ⊲⊳≤cr S̃| ≤ |R̃\R̃′ ||S̃|, we easily get  that the above bound can be rewrit- ten as Õ |R̃\R̃′ ||S̃|/(B min{M, |R̃\R̃′ |}) . We observe that this bound holds even when i = Ψ − 1: in this case the cost includes all I/Os required for solving the subproblems at level Ψ called in the iteration and which are solved using the nested loop in Theorem 2 (see Step 2). By Lemma 1, we have that the above quantity can  be upper bounded with the number of far  collisions between R̃ and ′ ′ S̃, getting Õ (|R̃\R̃ ⊲⊳>cr S̃|)/(B min{M, |R̃\R̃ |}) . Recall that Ci,k (Q) denotes the number of times a pair in Q is in a call to OSimJoin at the i-th level of recursion where the smallest input set has size in [2k , 2k+1 ) if 0 ≤ k < log M , and in [M, +∞) if k = log M . Then, the total cost for preparing the recursive calls in Steps 7–8 in all subproblems at level i and for performing Step 5 in all subproblems at level (i + 1) is:4 Õ log M X k=0 Ci,k (R ⊲⊳>cr S) L B2k ! . (4) The L factor in the above bound follows since far collisions at level i are used for amortizing the cost of Step 5 for each one of the L iterations of Step 6. To get the total I/O complexity of the algorithm we sum the I/O complexity required by each recursive level. We bound the cost of each level as follows: for a level i < ℓ we use the bound in Equation 3; for a level i > ℓ we use the bound 4 We note that the true input size of a subproblem is |R̃| and not |R̃\R̃′ |. However, the expected value of Ci,k (R ⊲⊳>cr S) is computed assuming the worst case where there are no close pairs an thus R̃′ = ∅. 13 in Equation 4; for level i = ℓ, we use the bound given in Equation 4 to which we add the first term in Equation 3 since the cost of Step 5 at level ℓ is not included in Equation 4 (note that the addition of Equations 3 and 4 gives a weak upper bound for level ℓ). The lemma follows. ⊓ ⊔ We will now analyze the expected sizes of the terms in Lemma 2. Clearly each pair from R × S is in the top level call, so the number of collisions is |R||S| < N 2 . But in lower levels we show that the expected number of times that a pair collides either decreases or increases geometrically, depending on whether the collision probability is smaller or larger than p1 (or equivalently, depending on whether the distance is greater or smaller than the radius r). The lemma follows by expressing the number of collisions of the pairs at the i-th recursive level as a Galton-Watson branching process [11]. Lemma 3. Given that A holds, for each 0 ≤ i ≤ Ψ we have 1. 2. 3. 4.   ≤ |R ⊲⊳ S| (p2 /p1 )i ; E Ci R ⊲⊳ S >cr >cr    ≤ |R ⊲⊳ S| ; E Ci R ⊲⊳ S >r,≤cr    >r,≤cr ≤ |R ⊲⊳ S| Li ; E Ci R ⊲⊳ S ≤r ≤r    ≤ N 2k+1 (p2 /p1 )i , for any 0 ≤ k < log M . E Ci,k R ⊲⊳ S  >cr Proof. Let x ∈ R and y ∈ S. We are interested in upper bounding the number of collisions of the pair at the i-th recursive level. We envision the problem as branching process (more specifically a GaltonWatson process, see e.g. [11]) where the expected number of children (i.e., recursive calls that preserve a particular collision) is Pr [h(x) = h(y)] /p1 for random h ∈ H. It is a standard fact from this theory that the expected population size at generation i (i.e., number of times (x, y) is in a problem at recursive level i) is (Pr [h(x) = h(y)] /p1 )i [11, Theorem 5.1]. If d(x, y) > cr, we have that Pr [h(x) = h(y)] ≤ p2 and each far pair appears at most (p2 /p1 )i times in expectation at level i, from which follows Equation 1. Moreover, since the probability of collisions is monotonic in the distance, we have that Pr [h(x) = h(y)] ≤ 1 if d(x, y) ≤ r, and Pr [h(x) = h(y)] ≤ p1 if r < d(x, y) ≤ cr, from which follow Equations 2 and 3. In order to get the last bound we observe that each entry of R and S is k+1 i replicated Li = p−i L is the total 1 times at level i. Thus, we have that N 2 maximum number of far collisions in subproblems at level i where the smallest input set has size in [2k , 2k+1 ). Each one of these collisions survives up to level i with probability pi2 , and thus the expected number of these collisions is N 2k+1 (p1 /p2 )i . ⊓ ⊔ We are now ready to prove the I/O complexity of OSimJoin as claimed in Theorem 1. By the linearity of expectation and Lemma 2, we get that the 14 expected I/O complexity of OSimJoin is         L M E Ci,k R ⊲⊳ S ℓ E Ci R ⊲⊳ S Ψ −1 log X X  N Lℓ X >cr ≤cr  , Õ  + +  B  k M B B2 i=0 i=ℓ k=0 where ℓ = ⌈log1/p2 (N/M )⌉. Note that Ci,log M (R ⊲⊳>cr S) ≤ Ci (R ⊲⊳>cr S) we have |R ⊲⊳>cr S| ≤ N 2 and Ci (R ⊲⊳≤cr S) = Ci (R ⊲⊳≤r S) + Ci (R ⊲⊳>r,≤cr S). By plugging in the bounds on the expected number of collisions given in Lemma 3, we get the claimed result. Analysis of Correctness. The following lemma shows that OSimJoin outputs with probability 1 − O (1/N ) all near pairs, as claimed in Theorem 1.   Lemma 4. Let R, S ⊆ U and |R| + |S| = N . Executing O log3/2 N indepen- dent repetitions of OSimJoin(R,S,0) outputs R ⊲⊳≤r S with probability at least 1 − O (1/N ). Proof.√ We now argue that a pair (x, y) with d(x, y) ≤ r is output with probability Ω(1/ log N ). Let Xi = Ci ((x, y)) be the number of subproblems at the level i containing (x, y). By applying Galton-Watson branching process, we get that E [Xi ] = (Pr [h(x) = h(y)] /p1 )i . If Pr [h(x) = h(y)] /p1 > 1 then in fact there is positive constant probability that (x, y) survives indefinitely, i.e., does not go extinct [11]. Since at every branch of the recursion we eventually compare points that collide under all hash functions on the path from the root call, this implies that (x, y) is reported with a positive constant probability. In the critical case where Pr [h(x) = h(y)] /p1 = 1 we need to consider the variance of Xi , which by [11, Theorem 5.1] is equal to iσ 2 , where σ 2 is the variance of the number of children (hash collisions in recursive calls). If 1/p1 is integer, the number of children in our branching process follows a binomial distribution with mean 1. This implies that σ 2 < 1. Also in the case where 1/p1 is not integer, it is easy to see that the variance is bounded by 2. That is, we have Var √ (Xi ) ≤ 2i, which by Chebychev’s inequality means that for some integer j ∗ = 2 i + O (1): ∞ X j=j ∗ Pr [Xi ≥ j] ≤ ∞ X j=j ∗ Var (Xi ) /j 2 ≤ 1/2 . P∞ Pj ∗ −1 Since we have E [Xi ] = j=1 Pr [Xi ≥ j] = 1 then j=1 Pr [Xi ≥ j] > 1/2, and since Pr [Xi √ ≥ j] is non-increasing with j this implies that Pr [Xi ≥ 1] ≥ 1/(2j ∗ ) = Ω 1/ i . Furthermore, the recursion depth O (log N ) implies  the   √ probability that a near pair is found is Ω 1/ log N . Thus, by repeating O log3/2 N  times we can make the error probability O 1/N 3 for a particular pair and O (1/N ) for the entire output by applying the union bound. 15 3.4 Removing duplicates Given two near points x and y, the definition of LSH requires their collision probability p(x, y) = Pr [h(x) = h(y)] ≥ p1 . If p(x, y) ≫ p1 , our OSimJoin algorithm can emit (x, y) many times. As an example suppose that the algorithm ends in one recursive call: then, the pair (x, y) is expected to be in the same bucket for p(x, y)L iterations of Step 6 and thus it is emitted p(x, y)L ≫ 1 times in expectation. Moreover, if the pair is not emitted in the first recursive level, the expected number of emitted pairs increases as (p(x, y)L)i since the pair (x, y) is contained in (p(x, y)L)i subproblems at the i-th recursive level. A simple solution requires to store all emitted near pairs on the external memory, and then using a cache-oblivious sorting algorithm [9] for removing repetitions.   |R⊲⊳ S| I/Os, where κ is the expected However, this approach requires Õ κ B≤r average replication of each emitted pair, which can dominate the complexity of OSimJoin. A similar issue appears in the cache-aware algorithm ASimJoin as well: a near pair is emitted at most L′ = (N/M )ρ times since there is no recursion and the partitioning of the two input sets is repeated only L′ times. If the collision probability Pr [h(x) = h(y)] can be explicitly computed in O (1) time and no I/Os for each pair (x, y), it is possible to emit each near pair once in expectation without storing near pairs on the external memory. We note that the collision probability can be computed for many metrics, including Hamming [14], ℓ1 and ℓ2 [7], Jaccard [4], and angular [5] distances. For the cache-oblivious algorithm, the approach is the following: for each near pair (x, y) that is found at the i-th recursive level, with i ≥ 0, the pair is emitted with probability 1/(p(x, y)L)i ; otherwise, we ignore it. For the cache-aware algorithm, the idea is the same but a near pair is emitted with probability 1/(p(x, y)L′ ) with L′ = (N/M )ρ . Theorem 4. The above approaches guarantee that each near pair is emitted with constant probability in both ASimJoin and OSimJoin. Proof. The claim easily follows for the cache-aware algorithm: indeed the two points of a near pair (x, y) have the same hash value in p(x, y)L (in expectation) of the L′ = (N/M )ρ repetitions of Step 3. Therefore, by emitting the pair with probability 1/(p(x, y)L) we get the claim. We now focus on the cache-oblivious algorithm, where the claim requires a more articulated proof. Given a near pair (x, y), let Gi and Hi be random variables denoting respectively the number of subproblems at level i containing the pair (x, y), and the number of subproblems at level i where (x, y) is not found by the cache-oblivious nested loop join algorithm in Theorem 2. Let also Ki be a random variable denoting the actual number of times the pair (x, y) is emitted at level i. We have followings properties: 1. E [Ki |Gi , Hi ] = (Gi − Hi )/(p(x, y)L)i since a near pair is emitted with probability 1/(p(x, y)L)i only in those subproblems where the pair is found by the join algorithm. 16 2. E [Gi ] = (p(x, y)L)i since a near pair is in the same bucket with probability p(x, y)i (it follows from the previous analysis based on standard branching). 3. G0 = 1 since each pair exists at the beginning of the algorithm. 4. HΨ = 0 since each pair surviving up to the last recursive level is found by the nested loop join algorithm. i hP Ψ We are interested in upper bounding E i=0 Ki by induction that E " l X i=0 # Ki = 1 − E [Hl ] , (p(x, y)L)l for any 0 ≤ l ≤ Ψ . For l = 0 (i.e., the first call to OSimJoin) and note that E [G0 ] = G0 = 1, the equality is verified since E [K0 ] = E [E [K0 |G0 , H0 ]] = E [G0 − H0 ] = 1 − E [H0 ] . We now consider a generic level l > 0. Since a pair propagates in a lower recursive level with probability p(x, y), we have E [Gl ] = E [E [Gl |Hl−1 ]] = p(x, y)LE [Hl−1 ] . Thus,  Gl − Hl E [Kl ] = E [E [Kl |Gl , Hl ]] = E (p(x, y)L)l E [Hℓ−1 ] E [Hℓ ] = − (p(x, y)L)l−1 (p(x, y)L)l  . By exploiting the inductive hypothesis, we get E " l X i=0 # Ki = E [Kl ] + E Since HΨ = 0, we have E " l−1 X i=0 hP Ψ i=0 i # Ki = 1 − E [Hl ] . (p(x, y)L)l Ki = 1 and the claim follows. ⊓ ⊔ We observe that the proposed approach is equivalent to use an LSH where p(x, y) = p1 for each near pair. Finally, we remark that this approach does not avoid replica of the same near pair when the algorithm is repeated for increasing the collision of near pairs. Thus, the probability of emitting  probability  a pair is  √  at least Ω 1/ Ψ as shown in the second part of Section 3.3 and O log3/2 N repetitions of OSimJoin suffices to find all pairs with high probability (however,   the expected number of replica of a given near pair becomes O log3/2 N , even with the proposed approach). 17 4 Discussion We will argue informally that our I/O complexity of Theorem 1 is close to the optimal. For simple arguments, we split the I/O complexity of our algorithms in two parts:    ρ |R ⊲⊳ S| N N ≤r  + , T1 = M B MB T2 = |R ⊲⊳ S| ≤cr MB . We now argue that T1 I/Os are necessary. First, notice that we need O (N/B) I/Os per hash function for transferring data between memories, computing and writing hash values to disk to find collisions. Second, since each I/O brings at most B points in order to compute the distance with M points residing in the internal memory, we need N/B I/Os to examine M N pairs. This means that when the collision probability of far pairs p2 ≤ M/N and the number of collisions of far pairs is at most M N in expectation, we only need O (N/B)  I/Os to detect such far pairs. Now we consider the case where there are Ω N 2 pairs at distance cr. Due to the monotonicity of LSH family, the collision probability for each such pair must be O (M/N ) to ensure that O (N/B) I/Os suffices to examine such pairs. In turn, this means that the collision probability for near pairs within distance r must be at most O ((M/N )ρ ). So we need Ω ((N/M )ρ ) repetitions (different hash functions) to expect at least one collision for any near pair. Then, a worst-case data set can be given so that we might need to examine, for each of the Ω ((N/M )ρ ) hash functions, a constant fraction the pairs in R ⊲⊳≤r S whose collision probability is constant. For example, this can happen if R and S include two clusters of very near points. One could speculate that some pairs could be marked as “finished” during computation such that we do not have to compute their distances again. However, it seems hard to make this idea work for an arbitrary distance measure where there may be very little structure for the output set, hence the O (|R ⊲⊳≤r S|/(M B)) additional I/Os per repetition is needed. In order to argue that the term T2 is needed, we consider the case where all pairs in R ⊲⊳≤cr S have distance r + ε for a value ε small enough to make the collision probability of pair at distance r + ε indistinguishable from the collision probability of pair at distance r. Then every pair in R ⊲⊳≤cr S must be brought into the internal memory to ensure the correct result, which requires T2 I/Os. This holds for any algorithm enumerating or listing the near pairs. Therefore, there does not exist an algorithm that beats the quadratic dependency on N for such worst-case input sets, unless the distribution of the input is known beforehand. However, when |R ⊲⊳≤cr S| is subquadratic regarding N , a potential approach to achieve subquadratic dependency in expectation for similarity join problem is filtering invalid pairs based on their distances — currently LSH-based method is the only way to do this. 18 0 0 10 CDF of pairwise distances CDF of pairwise similarities 10 −1 10 −2 10 −3 10 −4 10 Jaccard similarity Cosine similarity −5 10 0 10 −1 10 −2 −3 10 −2 10 −3 10 −4 10 −5 −4 10 L1 distance L2 distance −1 10 10 10 2 10 3 10 4 10 Jaccard and cosine similarity L1 and L2 distance (a) Enron email dataset (b) MNIST dataset 5 10 Fig. 1. The cumulative distributions of pairwise similarities and pairwise distances on samples of 10,000 points from Enron Email and MNIST datasets. We note that values decrease on the x-axis of Figure 1.a, while they increase in Figure 1.b. Note that when M = N our I/O cost is O (N/B) as we would expect, since just reading the input is optimal. At the other extreme, when B = M = 1 our bound matches the time complexity of internal memory techniques. When |R ⊲⊳≤cr S| are bounded by M N then our algorithm achieves subquadratic dependency on N/M . Such an assumption is realistic in some real-world datasets as shown in the experimental evaluation section. To complement the above discussion we will evaluate our complexity by computing explicit constants and then evaluating the total number of I/Os spent by analyzing real datasets. Performing these “simulated experiments” has the advantage over real experiments that we are not impacted by any properties of a physical machine. We again split the I/O complexity of our algorithms in two parts:    ρ |R ⊲⊳ S| N N ≤r  +  T1 = M B MB T2 = |R ⊲⊳ S| ≤cr MB and carry out experiments to demonstrate that the first term T1 often dominates the second term T2 in real datasets. In particular, we depict the cumulative distribution function (cdf) in log-log scale of all pairwise distances (i.e., ℓ1 , ℓ2 ) and all pairwise similarities (i.e., Jaccard and cosine) on two commonly used datasets: Enron Email5 and MNIST6 , as shown in Figure 1. Since the Enron data set does not have a fixed data size per point, we consider a version of the data set where the dimension has been reduced such that each vector has a fixed size. 5 6 https://archive.ics.uci.edu/ml/datasets/Bag+of+Words http://yann.lecun.com/exdb/mnist/ 19 |R ⊲⊳ S| Data set Metric r cr Enron Jaccard 0.5 0.1 Enron Cosine 0.7 0.2 MNIST L1 3000 6000 ≤r |R ⊲⊳ S| ≤cr ρ N N 0.30 1.8 · 103 16 · 103 0.51 1.6 · 103 16 · 103 0.50 1.8 42 Standard LSH > 7.5 · 109 I/Os > 212 · 109 I/Os > 29 · 106 I/Os Nested loop ASimJoin 8 · 109 I/Os 3.2 · 109 I/Os 8 · 109 I/Os 6.6 · 109 I/Os 60 · 106 I/Os 12 · 106 I/Os Fig. 2. A comparison of I/O cost for similarity joins on the standard LSH, nested loop and ASimJoin algorithms. Figure 1.a shows an inverse polynomial relationship with a small exponent m between similarity threshold s and the number of pairwise similarities greater than s. The degree of the polynomial is particularly low when s > 0.5. This setting s > 0.5 is commonly used in many applications for both Jaccard and cosine similarities [2, 3, 19]. Similarly, Figure 1.b also shows a monomial relationship between the distance threshold r and the number of pairwise distances smaller than r. In turn, this means that the number of c-near pairs |R ⊲⊳≤cr S| is not much greater than cm |R ⊲⊳≤r S|. In other words, the second term T2 is often much smaller than the first term T1 . Finally, for the same data sets and metrics, we simulated the cache-aware algorithm with explicit constants and examined the I/Os cost to compare with a standard nested loop method (Section 2) and a lower bound on the standard LSH method (Section 2). We set the cache size M = N/1000, which is reasonable for judging a number of cache misses since the size ratio between CPU caches and RAM is in that order of magnitude. In general such setting allows us to investigate what happens when the data size is much larger than fast memory. For simplicity we use B = 1 since all methods contain a multiplicative factor 1/B on the I/O complexity. The values of ρ were computed using good LSH families for the specific metric and parameters r and c. These parameters are picked according to Figure 1 such that the number of c-near pairs are only an order of magnitude larger than the number of near pairs. The I/O complexity used for nested loop join is 2N + N 2 /M B (here we assume both sets have size N ) and the complexity for the standard LSH approach is lower bounded by sort N 1+ρ . This complexity is a lower bound on the standard sorting based approaches as it lacks the additional cost that depends on how LSH distributes the points. Since M = N/1000 we can bound the log-factor of the sorting complexity and use sort (N ) ≤ 8N since 2N points read and written twice. The I/O complexity of our approach is stated in Theorem 3. The computed I/O-values in Figure 2 show that the complexity of our algorithm is lower than that of all instances examined. Nested loop suffers from quadratic dependency on N , while the standard LSH bounds lack the dependency on M . Overall the I/O cost indicates that our cache-aware algorithm is practical on the examined data sets. 20 5 Conclusion In this paper we examine the problem of computing the similarity join of two relations in an external memory setting. Our new cache-aware algorithm of Section 3.1 and cache-oblivious algorithm of Section 3.2 improve upon current state of the art by around a factor of (M/B)ρ I/Os unless the number of c-near pairs is huge (more than N M ). We believe this is the first cache-oblivious algorithm for similarity join, and more importantly the first subquadratic algorithm whose I/O performance improves significantly when the size of internal memory grows. It would be interesting to investigate if our cache-oblivious approach is also practical — this might require adjusting parameters such as L. Our I/O bound is probably not easy to improve significantly, but interesting open problems are to remove the error probability of the algorithm and to improve the implicit dependence on dimension in B and M . Note that our work assumes for simplicity that the unit of M and B is number of points, but in general we may get tighter bounds by taking into account the gap between the space required to store a point and the space for hash values. Also, the result in this paper is made with general spaces in mind and it is an interesting direction to examine if the dependence on dimension could be made explicit and improved in specific spaces. References 1. Alexandr Andoni and Piotr Indyk. Near-optimal hashing algorithms for approximate nearest neighbor in high dimensions. In Proceedings of FOCS’06, pages 459–468, 2006. 2. Arvind Arasu, Venkatesh Ganti, and Raghav Kaushik. Efficient exact set-similarity joins. In Proceedings of VLDB’06, pages 918–929, 2006. 3. Roberto J. Bayardo, Yiming Ma, and Ramakrishnan Srikant. Scaling up all pairs similarity search. In Proceedings of WWW’07, pages 131–140, 2007. 4. Andrei Z. Broder, Steven C. Glassman, Mark S. Manasse, and Geoffrey Zweig. Syntactic clustering of the web. Computer Networks, 29(8-13):1157–1166, 1997. 5. Moses S. Charikar. Similarity estimation techniques from rounding algorithms. In Proceedings of STOC’02, pages 380–388, 2002. 6. Surajit Chaudhuri, Venkatesh Ganti, and Raghav Kaushik. A primitive operator for similarity joins in data cleaning. In Proceedings of ICDE’06, page 5, 2006. 7. Mayur Datar, Nicole Immorlica, Piotr Indyk, and Vahab S. Mirrokni. Localitysensitive hashing scheme based on p-stable distributions. In Proceedings of SOCG’04, pages 253–262, 2004. 8. Devdatt P. Dubhashi and Alessandro Panconesi. Concentration of Measure for the Analysis of Randomized Algorithms. Cambridge University Press, 2009. 9. Matteo Frigo, Charles E Leiserson, Harald Prokop, and Sridhar Ramachandran. Cache-oblivious algorithms. In Proceedings of FOCS’99, pages 285–297, 1999. 10. Aristides Gionis, Piotr Indyk, and Rajeev Motwani. Similarity search in high dimensions via hashing. In Proceedings of VLDB’99, pages 518–529, 1999. 11. Theodore E Harris. The theory of branching processes. Courier Dover Publications, 2002. 12. Bingsheng He and Qiong Luo. Cache-oblivious nested-loop joins. In Proceedings of CIKM’06, pages 718–727, 2006. 21 13. Monika Rauch Henzinger. Finding near-duplicate web pages: a large-scale evaluation of algorithms. In Proceedings of SIGIR’06, pages 284–291, 2006. 14. Piotr Indyk and Rajeev Motwani. Approximate nearest neighbors: Towards removing the curse of dimensionality. In Proceedings of STOC’98, pages 604–613, 1998. 15. Hung Q. Ngo, Christopher Ré, and Atri Rudra. Skew strikes back: new developments in the theory of join algorithms. SIGMOD Record, 42(4):5–16, 2013. 16. Andrzej Pacuk, Piotr Sankowski, Karol Wegrzycki, and Piotr Wygocki. Localitysensitive hashing without false negatives for l p. In Proceedings of COCOON’16, pages 105–118, 2016. 17. Rasmus Pagh. Locality-sensitive hashing without false negatives. In Proceedings of SODA’16, pages 1–9, 2016. 18. Jeffrey Scott Vitter. Algorithms and Data Structures for External Memory. Now Publishers Inc., 2008. 19. Chuan Xiao, Wei Wang, Xuemin Lin, and Jeffrey Xu Yu. Efficient similarity joins for near duplicate detection. In Proceedings of WWW’08, pages 131–140, 2008. 20. Mihalis Yannakakis. Algorithms for acyclic database schemes. In Proceedings of VLDB’81, pages 82–94, 1981. 22
8 (cs.DS)
arXiv:1207.0612v2 [math.AC] 21 Jan 2013 COMPLETION BY DERIVED DOUBLE CENTRALIZER MARCO PORTA, LIRAN SHAUL AND AMNON YEKUTIELI Abstract. Let A be a commutative ring, and let a be a weakly proregular ideal in A. (If A is noetherian then any ideal in it is weakly proregular.) Suppose M is a compact generator of the category of cohomologically a-torsion complexes. We prove that the derived double centralizer of M is isomorphic to the a-adic completion of A. The proof relies on the MGM equivalence from [PSY] and on derived Morita equivalence. Our result extends earlier work of Dwyer-Greenlees-Iyengar [DGI] and Efimov [Ef]. 0. Introduction Let A be a commutative ring. We denote by D(Mod A) the derived category of A-modules. Given M ∈ D(Mod A) we define M (0.1) ExtA (M ) := HomD(Mod A) (M, M [i]). i∈Z This is a graded A-algebra with the Yoneda multiplication, which we call the Ext algebra of M . Suppose we choose a K-projective resolution P → M . The resulting DG Aalgebra B := EndA (P ) is called a derived endomorphism DG algebra of M . It turns out (see Proposition 2.3) that the DG algebra B is unique up to quasiL i isomorphism; and of course its cohomology H(B) := i∈Z H (B) is canonically isomorphic to ExtA (M ) as graded A-algebra. Consider the derived category D̃(DGMod B) of left DG B-modules. We can view P as an object of D̃(DGMod B), and thus, like in (0.1), we get the graded Aalgebra ExtB (P ). This is the derived double centralizer algebra of M . By Corollary 2.4, the graded algebra ExtB (P ) is independent of the resolution P → M , up to isomorphism. Let a be an ideal in A. The a-torsion functor Γa can be right derived, giving a triangulated functor RΓa from D(Mod A) to itself. A complex M ∈ D(Mod A) is called a cohomologically a-torsion complex if the canonical morphism RΓa (M ) → M is an isomorphism. The full triangulated category on the cohomologically torsion complexes is denoted by D(Mod A)a-tor . It is known that when a is finitely generated, the category D(Mod A)a-tor is compactly generated (for instance by the Koszul complex K(A; a) associated to a finite generating sequence a = (a1 , . . . , an ) of a). Date: 11 December 2012. Key words and phrases. Adic completion, derived functors, derived Morita theory. Mathematics Subject Classification 2010. Primary: 13D07; Secondary: 13B35, 13C12, 13D09, 18E30. This research was supported by the Israel Science Foundation and the Center for Advanced Studies at BGU. 1 2 MARCO PORTA, LIRAN SHAUL AND AMNON YEKUTIELI b the a-adic completion of A. This is a commutative A-algebra, Let us denote by A b If a is finitely generated, then the ring A b is and in it there is the ideal b a := a · A. b a-adically complete. A weakly proregular sequence in A is a finite sequence a of elements of A, whose Koszul cohomology satisfies certain vanishing conditions; see Definition 1.2. This concept was introduced by Alonso-Jeremias-Lipman [AJL] and Schenzel [Sc]. An ideal a in A is called weakly proregular if it can be generated by a weakly proregular sequence. It is important to note that if A is noetherian, then any finite sequence in it is weakly proregular, so that any ideal in A is weakly proregular. But there are some fairly natural non-noetherian examples (see [AJL, Example 3.0(b)] and [PSY, Example 4.35]). Here is our main result (repeated as Theorem 4.2 in the body of the paper). Theorem 0.2. Let A be a commutative ring, let a be a weakly proregular ideal in A, and let M be a compact generator of D(Mod A)a-tor . Choose a K-projective resolution P → M , and define B := EndA (P ). Then there is a unique isomorphism b of graded A-algebras ExtB (P ) ∼ = A. Our result extends earlier work of Dwyer-Greenlees-Iyengar [DGI] and Efimov [Ef]; see Remark 4.8 for a discussion. Let us say a few words on the proof of Theorem 0.2. We use derived Morita theory to find an isomorphism of graded algebras between ExtB (P ) and ExtA (N )op , where N := RΓa (A). The necessary facts about derived Morita theory are recalled in Section 3. We then use MGM equivalence (recalled in Section 1) to prove that b b ∼ ExtA (N ) ∼ = A. = ExtA (A) Acknowledgments. We wish to thank Bernhard Keller, John Greenlees, Alexander Efimov, Maxim Kontsevich, Vladimir Hinich and Peter Jørgensen for helpful discussions. We are also grateful to the anonymous referee for a careful reading of the paper and constructive remarks. 1. Weak Proregularity and MGM Equivalence Let A be a commutative ring, and let a be an ideal in it. (We do not assume that A is noetherian or a-adically complete.) There are two operations on A-modules associated to this data: the a-adic completion and the a-torsion. For an A-module c := lim←i M/ai M . An M its a-adic completion is the A-module Λa (M ) = M i element m ∈ M is called an a-torsion element if a m = 0 for i ≫ 0. The a-torsion elements form the a-torsion submodule Γa (M ) of M . Let us denote by Mod A the category of A-modules. So we have additive functors Λa and Γa from Mod A to itself. The functor Γa is left exact; whereas Λa is neither left exact nor right exact. An A-module is called a-adically complete if the canonical homomorphism τM : M → Λa (M ) is bijective (some texts would say that M is complete and separated); and M is a-torsion if the canonical homomorphism σM : Γa (M ) → M is bijective. If the ideal a is finitely generated, then the functor Λa is idempotent; namely for any module M , its completion Λa (M ) is a-adically complete. (There are counterexamples to that for infinitely generated ideals – see [Ye, Example 1.8].) The derived category of Mod A is denoted by D(Mod A). The derived functors LΛa , RΓa : D(Mod A) → D(Mod A) COMPLETION BY DERIVED DOUBLE CENTRALIZER 3 exist. The left derived functor LΛa is constructed using K-flat resolutions, and the right derived functor RΓa is constructed using K-injective resolutions. This means that for any K-flat complex P , the canonical morphism ξP : LΛa (P ) → Λa (P ) is an isomorphism; and for any K-injective complex I, the canonical morphism ξI : Γa (I) → RΓa (I) is an isomorphism. The relationship between the derived functors RΓa and LΛa was first studied in [AJL], where the Greenlees-May duality was established (following the paper [GM]). A complex M ∈ D(Mod A) is called a cohomologically a-torsion complex if R the canonical morphism σM : RΓa (M ) → M is an isomorphism. The complex M is called a cohomologically a-adically complete complex if the canonical morL phism τM : M → LΛa (M ) is an isomorphism. We denote by D(Mod A)a-tor and D(Mod A)a-com the full subcategories of D(Mod A) consisting of cohomologically atorsion complexes and cohomologically a-adically complete complexes, respectively. These are triangulated subcategories. Very little can be said about the functors LΛa and RΓa , and about the corresponding triangulated categories D(Mod A)a-tor and D(Mod A)a-com , in general. However we know a lot when the ideal a is weakly proregular. Before defining weak proregularity we have to talk about Koszul complexes. Recall that for an element a ∈ A the Koszul complex is  a· K(A; a) := · · · → 0 → A −→ A → 0 → · · · , concentrated in degrees −1 and 0. Given a finite sequence a = (a1 , . . . , an ) of elements of A, the Koszul complex associated to this sequence is K(A; a) := K(A; a1 ) ⊗A · · · ⊗A K(A; an ). This is a complex of finitely generated free A-modules, concentrated in degrees −n, . . . , 0. There is a canonical isomorphism of A-modules H0 (K(A; a)) ∼ = A/(a), where (a) is the ideal generated by the sequence a. For any i ≥ 1 let ai := (ai1 , . . . , ain ). If j ≥ i then there is a canonical homomorphism of complexes pj,i : K(A; aj ) → K(A; ai ), which in H0 corresponds to the surjection A/(aj ) → A/(ai ). Thus for every k ∈ Z we get an inverse system of A-modules  k (1.1) H (K(A; ai )) i∈N , with transition homomorphisms Hk (pj,i ) : Hk (K(A; aj )) → Hk (K(A; ai )). Of course for k = 0 the inverse limit equals the (a)-adic completion of A. What turns out to be crucial is the behavior of this inverse system for k < 0. For more details please see [PSY, Section 4]. An inverse system {Mi }i∈N of abelian groups, with transition maps pj,i : Mj → Mi , is called pro-zero if for every i there exists j ≥ i such that pj,i is zero. Definition 1.2. (1) Let a be a finite sequence in A. The sequence a is called a weakly proregular sequence if for every k ≤ −1 the inverse system (1.1) is pro-zero. (2) An ideal a in A is called a a weakly proregular ideal if it is generated by some weakly proregular sequence. The etymology of the name “weakly proregular sequence”, and the history of related concepts, are explained in [AJL] and [Sc]. 4 MARCO PORTA, LIRAN SHAUL AND AMNON YEKUTIELI If a is a regular sequence, then it is weakly proregular. More important is the following result. Theorem 1.3 ([AJL]). If A is noetherian, then every finite sequence in A is weakly proregular, so that every ideal in A is weakly proregular. Here is another useful fact. Theorem 1.4 ([Sc]). Let a be a weakly proregular ideal in a ring A. Then any finite sequence that generates a is weakly proregular. These theorems are repeated (with different proofs) as [PSY, Theorem 4.34] and [PSY, Corollary 6.3] respectively. As the next theorem shows, weak proregularity is the correct condition for the derived torsion functor to be “well-behaved”. Suppose a is a finite sequence that generates the ideal a ⊂ A. Consider the infinite dual Koszul complex  i K∨ ∞ (A; a) := lim HomA K(A; a ), A . i→ Given a complex M , there is a canonical morphism RΓa (M ) → K∨ ∞ (A; a) ⊗A M (1.5) in D(Mod A). Theorem 1.6 ([Sc]). The sequence a is weakly proregular iff the morphism (1.5) is an isomorphism for every M ∈ D(Mod A). The following theorem, which is [PSY, Theorem 1.1], plays a central role in our work. Theorem 1.7 (MGM Equivalence). Let A be a commutative ring, and a a weakly proregular ideal in it. (1) For any M ∈ D(Mod A) one has RΓa (M ) ∈ D(Mod A)a-tor and LΛa (M ) ∈ D(Mod A)a-com . (2) The functor RΓa : D(Mod A)a-com → D(Mod A)a-tor is an equivalence, with quasi-inverse LΛa . Remark 1.8. Slightly weaker versions of Theorem 1.7 appeared previously; they are [AJL, Theorem (0.3)∗ ] and [Sc, Theorem 4.5]. The difference is that in these earlier results it was assumed that the ideal a is generated by a sequence (a1 , . . . , an ) that is weakly proregular, and moreover each ai has bounded torsion. This extra condition certainly holds when A is noetherian. For the sake of convenience, in the present paper we quote [PSY] regarding derived completion and torsion. It is tacitly understood that in the noetherian case the results of [AJL] and [Sc] suffice. 2. The Derived Double Centralizer In this section we define the derived double centralizer of a DG module. See Remarks 2.6 and 2.7 for a discussion of this concept L and related literature. Let K be a commutative ring, and let A = i∈Z Ai be a DG K-algebra (associative and unital, but not necessarily commutative). Given left DG A-modules M COMPLETION BY DERIVED DOUBLE CENTRALIZER 5 and N , we denote by HomiA (M, N ) the K-module of A-linear homomorphisms of degree i. We get a DG K-module M HomA (M, N ) := HomiA (M, N ) i∈Z with the usual differential. The object EndA (M ) := HomA (M, M ) is a DG K-algebra. Since the left actions of A and EndA (M ) on M commute, we see that M is a left DG module over the DG algebra A ⊗K EndA (M ). The category of left DG A-modules is denoted by DGMod A. The set of morphisms HomDGMod A (M, N ) is precisely the set of 0-cocycles in the DG K-module HomA (M, N ). Note that DGMod A is a K-linear abelian category. Let K̃(DGMod A) be the homotopy category of DGMod A, so that  HomK̃(DGMod A) (M, N ) = H0 HomA (M, N ) . The derived category D̃(DGMod A) is gotten by inverting the quasi-isomorphisms in K̃(DGMod A). The categories K̃(DGMod A) and D̃(DGMod A) are K-linear and triangulated. If A happens to be a ring (i.e. Ai = 0 for i 6= 0) then DGMod A = C(Mod A), the category of complexes in Mod A, and D̃(DGMod A) = D(Mod A), the usual derived category. For M, N ∈ DGMod A we define ExtiA (M, N ) := HomD̃(DGMod A) (M, N [i]) and ExtA (M, N ) := M ExtiA (M, N ). i∈Z Definition 2.1. Let A be a DG K-algebra and M ∈ DGMod A. Define ExtA (M ) := ExtA (M, M ). This is a graded K-algebra with the Yoneda multiplication (i.e. composition of morphisms in D̃(DGMod A)). We call ExtA (M ) the Ext algebra of M . There is a canonical homomorphism of graded K-algebras H(EndA (M )) → ExtA (M ). If M is either K-projective or K-injective, then this homomorphism is bijective. Definition 2.2. Let A be a DG K-algebra and M a DG A-module. Choose a K-projective resolution P → M in DGMod A. The DG K-algebra B := EndA (P ) is called a derived endomorphism DG algebra of M . Note that there are isomorphisms of graded K-algebras H(B) ∼ = ExtA (P ) ∼ = ExtA (M ). The dependence of the derived endomorphism DG algebra B = EndA (P ) on the resolution P → M is explained in the next proposition. Proposition 2.3. Let M be a DG A-module, and let P → M and P ′ → M be K-projective resolutions in DGMod A. Define B := EndA (P ) and B ′ := EndA (P ′ ). Then there is a DG K-algebra B ′′ , and a DG B ′′ -module P ′′ , with DG K-algebra quasi-isomorphisms B ′′ → B and B ′′ → B ′ , and DG B ′′ -module quasi-isomorphisms P ′′ → P and P ′′ → P ′ . 6 MARCO PORTA, LIRAN SHAUL AND AMNON YEKUTIELI Proof. Choose a quasi-isomorphism φ : P ′ → P in DGMod A lifting the given quasiisomorphisms to M ; this can be done of course. Let L := cone(φ) i∈ h P ′ DGMod A, the mapping cone of φ. So as graded A-module L = P ⊕ P [1] = P ′ [1] ; h i d φ and the differential is dL = 0P dP ′ [1] , where φ is viewed as a degree 1 homomorphism P ′ [1] → P . Of course L is an acyclic DG module. Takeh Q :=iHomA (P ′ [1], P ), and let B ′′ be the triangular matrix graded algebra B ′′ := B Q 0 B′ with the obvious matrix multiplication. This makes sense because there is a canonical isomorphism of DG algebras B ′ ∼ = EndA (P ′ [1]). Note that ′′ ′′ B is a subalgebra of EndA (L). We make B into a DG algebra with differential dB ′′ := dEndA (L) |B ′′ . The projections B ′′ → B and B ′′ → B ′ on the diagonal entries are DG algebra quasi-isomorphisms, because their kernels are the acyclic complexes HomA (P ′ [1], L) and HomA (L, P ) respectively. Now under the restriction functor DGMod(B) → DGMod(B ′′ ) we have P 7→ [ P0 ],  0  ′ and likewise P 7→ P ′ . Consider the exact sequence i h 0 → [ P0 ] → L → P ′0[1] → 0   χ △ → [ P0 ] → L − → in in DGMod(B ′′ ). There is an induced distinguished triangle P0′ − D̃(DGMod(B ′′ )). But L is acyclic, so χ is an isomorphism.   Finally let us choose a K-projective resolution P ′′ → P0′ in DGMod(B ′′ ). Then χ induces a quasi-isomorphism P ′′ → [ P0 ] in DGMod(B ′′ ).  Corollary 2.4. In the situation of Proposition 2.3, there is an isomorphism of graded K-algebras ExtB (P ) ∼ = ExtB ′ (P ′ ). Proof. Since B ′′ → B is a quasi-isomorphism of DG algebras, it follows that the restriction functor D̃(DGMod(B)) → D̃(DGMod(B ′′ )) is an equivalence of triangulated categories. Therefore we get an induced isomorphism of graded K≃ algebras ExtB (P ) − → ExtB ′′ (P ′′ ). Similarly we get a graded K-algebra isomorphism ≃  → ExtB ′′ (P ′′ ). ExtB ′ (P ′ ) − Definition 2.5. Let M be a DG A-module, and let P → M be a K-projective resolution in DGMod A. The graded K-algebra ExtB (P ) is called a derived double centralizer of M . Remark 2.6. The uniqueness of the graded K-algebra ExtB (P ) provided by Corollary 2.4 is sufficient for the purposes of this paper (see Theorem 0.2). It is possible to show by a more detailed calculation that the isomorphism provided by Corollary 2.4 is in fact canonical (it does not depend on the choices made in the proof of Proposition 2.3, e.g. the quasi-isomorphism φ). Let us choose a K-projective resolution Q → P in DGMod(B), and define the DG algebra C := EndB (Q). Then C should be called a double endomorphism DG algebra of M . Of course H(C) ∼ = ExtB (P ) as graded algebras. There should be a canonical DG algebra homomorphism A → C. We tried to work out a comprehensive treatment of derived endomorphism algebras and their iterates, using the old-fashioned methods, and did not get very far (hence it is not included in the paper). We expect that a full treatment is only possible in terms of ∞-categories. COMPLETION BY DERIVED DOUBLE CENTRALIZER 7 Remark 2.7. Derived endomorphism DG algebras (and the double derived ones) were treated in several earlier the papers, including [DGI], [Jo] and [Ef]. These papers do not mention any uniqueness properties of these DG algebras; indeed, as far as we can tell, they just pick a convenient resolution P → M , and work with the DG algebra EndA (P ). Cf. Subsection 1.5 of [DGI] where this issue is briefly discussed. The most detailed treatment of derived endomorphism DG algebras that we know is in Keller’s paper [Ke]. In [Ke, Section 7.3] the concept of a lift of a DG module is introduced. The pair (B, P ) from Definition 2.2 is called a standard lift in [Ke]. It is proved that lifts are unique up to quasi-isomorphism (this is basically what is done in our Proposition 2.3); but there is no statement regarding uniqueness of these quasi-isomorphisms. Also there is no discussion of derived double centralizers. 3. Supplement on Derived Morita Equivalence Derived Morita theory goes back to Rickard’s paper [Ri], which dealt with rings and two-sided tilting complexes. Further generalizations can be found in [Ke, BV, Jo]. For our purposes (in Section 4) we need to know certain precise details about derived Morita equivalence in the case of DG algebras and compact generators (specifically, formula (3.3) for the functor F appearing in Theorem 3.5); and hence we give the full proof here. Let E be a triangulated category with infinite direct sums. Recall that an object M ∈ E is called compact (or small) if for any collection {Nz }z∈Z of objects of E, the canonical homomorphism   M M Nz HomE (M, Nz ) → HomE M, z∈Z z∈Z is bijective. The object M is called generator of E if for any nonzero object N ∈ E there is some i ∈ Z such that HomE (M, N [i]) 6= 0. As in Section 2 we consider a commutative ring K and a DG K-algebra A. The next lemma seems to be known, but we could not find a reference. Lemma 3.1. Let E be a triangulated category with infinite direct sums, let F, G : D̃(DGMod A) → E be triangulated functors that commute with infinite direct sums, and let η : F → G be a morphism of triangulated functors. Assume that ηA : F (A) → G(A) is an isomorphism. Then η is an isomorphism. △ → in Proof. Suppose we are given a distinguished triangle M ′ → M → M ′′ − D̃(DGMod A), such that two of the three morphisms ηM ′ , ηM and ηM ′′ are isomorphisms. Then the third is also an isomorphism. Since both functors F, G commute with shifts and direct sums, and since ηA is an isomorphism, it follows that ηP is an isomorphism for any free DG A-module P. S Next consider a semi-free DG module P . Choose any semi-basis Z = j≥0 Zj of P . This gives rise to an exhaustive ascending filtration {Pj }j≥−1 of P by DG submodules, with P−1 = 0. For every j we have a distinguished triangle θj △ → Pj−1 −→ Pj → Pj /Pj−1 − in D̃(DGMod A), where θj : Pj−1 → Pj is the inclusion. Since Pj /Pj−1 is a free DG module, by induction we conclude that ηPj is an isomorphism for every j. The 8 MARCO PORTA, LIRAN SHAUL AND AMNON YEKUTIELI telescope construction (see [BN, Remark 2.2]) gives a distinguished triangle M M Θ △ Pj −−→ Pj → P − →, j∈N j∈N with Θ|Pj−1 := (1, −θj ) : Pj−1 → Pj−1 ⊕ Pj . This shows that ηP is an isomorphism. Finally, any DG module M admits a quasi-isomorphism P → M with P semifree. Therefore ηM is an isomorphism.  Let E be a be a full triangulated subcategory of D̃(DGMod A) which is closed under infinite direct sums, and let M ∈ E. Fix a K-projective resolution P → M in DGMod A, and let B := EndA (P ). So B is a derived endomorphism DG algebra of M (Definition 2.2). Since P ∈ DGMod A ⊗K B, there is a triangulated functor (3.2) G : D̃(DGMod B op ) → D̃(DGMod A) , G(N ) := N ⊗LB P which is calculated by K-flat resolutions in DGMod B op . (Warning: P is usually not K-flat over B.) The functor G commutes with infinite direct sums, and G(B) ∼ = P ∼ = M in D̃(DGMod A). Therefore G(N ) ∈ E for every N ∈ D̃(DGMod B op ). Because P is K-projective over A, there is a triangulated functor (3.3) F : D̃(DGMod A) → D̃(DGMod B op ) , F (L) := HomA (P, L). We have F (M ) ∼ = B in D̃(DGMod B op ). = F (P ) ∼ Lemma 3.4. The functor F |E : E → D̃(DGMod B op ) commutes with infinite direct sums if and only if M is a compact object of E. Proof. We know that HomD̃(DGMod A) (M, L[j]) ∼ = Hj (RHomA (M, L)) ∼ = Hj (F (L)), functorially for L ∈ D̃(DGMod A). So M is compact relative to E if and only if the functors Hj ◦ F commute with direct sums in E. But that is the same as asking F to commute with direct sums in E.  Theorem 3.5. Let A be a DG K-algebra, let E be a be a full triangulated subcategory of D̃(DGMod A) which is closed under infinite direct sums, and let M be a compact generator of E. Choose a K-projective resolution P → M in DGMod A, and define B := EndA (P ). Then the functor F |E : E → D̃(DGMod B op ) from (3.3) is an equivalence of triangulated categories, with quasi-inverse the functor G from (3.2) . Proof. Let us write D(A) := D̃(DGMod A) etc. We begin by proving that the functors F and G are adjoints. Take any L ∈ D(A) and N ∈ D(B op ). We have to construct a bijection HomD(A) (G(N ), L) ∼ = HomD(B op ) (N, F (L)), COMPLETION BY DERIVED DOUBLE CENTRALIZER 9 which is bifunctorial. Choose a K-projective resolution Q → N in DGMod B op . Since the DG A-module Q⊗B P is K-projective, we have a sequence of isomorphisms (of K-modules) HomD(A) (G(N ), L) ∼ = H0 (RHomA (G(N ), L))  ∼ = H0 HomB op (Q, HomA (P, L)) = H0 (HomA (Q ⊗B P, L)) ∼ ∼ = H0 (RHomB op (N, F (L)) ∼ = HomD(B op ) (N, F (L)). The only choice made was in the K-projective resolution Q → N , so all is bifunctorial. The corresponding morphisms 1 → F ◦ G and G ◦ F → 1 are denoted by η and ζ respectively. Next we will prove that G is fully faithful. We do this by showing that for every N the morphism ηN : N → (F ◦G)(N ) in D(B op ) is an isomorphism. We know that G factors via the full subcategory E ⊂ D(A), and therefore, using Lemma 3.4, we know that the functor F ◦ G commutes with infinite direct sums. So by Lemma 3.1 it suffices to check for N = B. But in this case ηB is the canonical homomorphism of DG B op -modules B → HomA (P, B ⊗B P ), which is clearly bijective. It remains to prove that the essential image of the functor G is E. Take any ζL △ L ∈ E, and consider the distinguished triangle (G ◦ F )(L) −→ L → L′ − → in E, ′ in which L ∈ E is the mapping cone of ζL . Applying F and using η we get a 1F (L) △ distinguished triangle F (L) −−−→ F (L) → F (L′ ) − →. Therefore F (L′ ) = 0. But ′ ∼ ′ RHomA (M, L ) = F (L ), and therefore HomD(A) (M, L′ [i]) = 0 for every i. Since M is a generator of E we get L′ = 0. Hence ζL is an isomorphism, and so L is in the essential image of G.  4. The Main Theorem This is our interpretation of the completion appearing in Efimov’s recent paper [Ef], that is attributed to Kontsevich; cf. Remark 4.8 below for a comparison to [Ef] and to similar results in recent literature. Here is the setup for this section: A is a commutative ring, and a is a weakly proregular ideal in A. We do not assume that b := Λa (A), the a-adic completion of A is noetherian nor a-adically complete. Let A b b A, and let b a := a · A, which is an ideal of A. Since the ideal a is finitely generated, b is a-adically complete, and hence as a ring A b is it follows that the A-module A b a-adically complete. The full subcategory D(Mod A)a-tor ⊂ D(Mod A) is triangulated and closed under infinite direct sums. The results of Sections 2 and 3 are invoked with K := A. Recall the Koszul complex K(A; a) associated to a finite sequence a in A; see Section 1. It is a bounded complex of free A-modules, and hence it is a K-projective DG A-module. The next result was proved by several authors (see [BN, Proposition 6.1], [LN, Corollary 5.7.1(ii)] and [Ro, Proposition 6.6]). Proposition 4.1. Let a be a finite sequence that generates a. Then the Koszul complex K(A; a) is a compact generator of D(Mod A)a-tor . Of course there are other compact generators of D(Mod A)a-tor . Theorem 4.2. Let A be a commutative ring, let a be a weakly proregular ideal in A, and let M be a compact generator of D(Mod A)a-tor . Choose some K-projective resolution P → M in C(Mod A), and let B := EndA (P ). Then ExtiB (P ) = 0 for b all i 6= 0, and there is a unique isomorphism of A-algebras Ext0B (P ) ∼ = A. 10 MARCO PORTA, LIRAN SHAUL AND AMNON YEKUTIELI Recall that the DG A-algebra B is a derived endomorphism DG algebra of M (Definition 2.2), and the graded A-algebra ExtB (P ) is a derived double centralizer of M (Definition 2.5). We need a few lemmas before proving the theorem. Lemma 4.3. Let M be a compact object of D(Mod A)a-tor . Then M is also compact in D(Mod A), so it is a perfect complex of A-modules. Proof. Choose a finite sequence a that generates a. By [PSY, Corollary 4.26] there ∨ is an isomorphism of functors RΓa ∼ = K∨ ∞ (A; a) ⊗A −, where K∞ (A; a) is the infinite dual Koszul complex. Therefore the functor RΓa commutes with infinite direct sums. Let N ∈ D(Mod A), and consider the function R Hom(1, σN ) : HomD(Mod A) (M, RΓa (N )) → HomD(Mod A) (M, N ). Given a morphism α : M → N in D(Mod A) define R −1 β := RΓa (α) ◦ (σM ) : M → RΓa (N ). Since the functor RΓa is idempotent (Theorem 1.7(1)), the function α 7→ β is an R inverse to Hom(1, σN ), so the latter is bijective. Let {Nz }z∈Z be a collection of objects of D(Mod A). Due to the fact that M is a compact object of D(Mod A)a-tor , and to the observations above, we get isomorphisms M M ∼ HomD(Mod A) (M, Nz ) = HomD(Mod A) (M, RΓa (Nz )) z ∼ = HomD(Mod A) M z M   RΓa (Nz ) ∼ Nz = HomD(Mod A) M, RΓa z z M  M, Nz . ∼ = HomD(Mod A) M, z We see that M is also compact in D(Mod A).  Consider the contravariant functor D : D(Mod B) → D(Mod B op ) defined by choosing an injective resolution A → I over A, and letting D := HomA (−, I). Lemma 4.4. The functor D induces a duality (i.e. a contravariant equivalence) between the full subcategory of D(Mod B) consisting of objects perfect over A, and the full subcategory of D(Mod B op ) consisting of objects perfect over A. Proof. Take M ∈ D(Mod B) which is perfect over A. It is enough to show that the canonical homomorphism of DG B-modules (4.5) M → (D ◦ D)(M ) = HomA (HomA (M, I), I) is a quasi-isomorphism. For this we can forget the B-module structure, and just view this as a homomorphism of DG A-modules. Choose a resolution P → M where P is a bounded complex of finitely generated projective A-modules. We can replace M with P in equation (4.5); and after that we can replace I with A; now it is clear that this is a quasi-isomorphism.  c := Lemma 4.6. Let M and N be K-flat complexes of A-modules. We write M b Λa (M ) and N := Λa (N ). COMPLETION BY DERIVED DOUBLE CENTRALIZER 11 c and τ L : M c → LΛa (M c) are isomor(1) The morphisms ξM : LΛa (M ) → M b M phisms. (2) The homomorphism c, N b ) → HomD(Mod A) (M, N b) Hom(τM , 1) : HomD(Mod A) (M is bijective. Proof. (1) The morphism ξM is an isomorphism by [PSY, Proposition 3.6]. By Theorem 1.7(1) the complex LΛa (M ) is cohomologically complete; and therefore c is also cohomologically complete. But this means that τ L is an isomorphism. M b M b (2) Take a morphism α : M → N in D(Mod A). By part (1) we know that ξM and τ L are isomorphisms, so we can define b N −1 c b. :M →N β := (τ Lb )−1 ◦ LΛa (α) ◦ ξM N The function α 7→ β is an inverse to Hom(τM , 1).  Proof of Theorem 4.2. We shall calculate ExtB (P ) indirectly. By Lemma 4.3 we know that M , and hence also P , is perfect over A. So according to Lemma 4.4 there is an isomorphism of graded A-algebras ∼ ExtB op (D(P ))op . ExtB (P ) = Next we note that D(P ) = HomA (P, I) ∼ = HomA (P, A) = F (A) in D̃(DGMod B op ). Here F is the functor from (3.3). Therefore we get an isomorphism of graded A-algebras ExtB op (D(P )) ∼ = ExtB op (F (A)). Let N := RΓa (A) ∈ D(Mod A). We claim that F (A) ∼ = F (N ) in D̃(DGMod B op ). R To see this, we first note that the canonical morphism σA : N → A in D(Mod A) can be represented by an actual DG module homomorphism N → A (say by replacing N with a K-projective resolution of it). Consider the induced homomorphism HomA (P, N ) → HomA (P, A) of DG B op -modules. Like in the proof of Lemma 4.4, it suffices to show that this is a quasi-isomorphism of DG A-modules. This is true since, by GM Duality [PSY, Theorem 7.12], the canonical morphism R RHom(1, σA ) : RHomA (M, N ) → RHomA (M, A) in D(Mod A) is an isomorphism. We conclude that there is a graded A-algebra isomorphism ExtB op (F (A)) ∼ = ExtB op (F (N )). Take E := D(Mod A)a-tor in Theorem 3.5. Since F |E : E → D̃(DGMod B op ) is an equivalence, and E is full in D(Mod A), we see that F induces an isomorphism of graded A-algebras ExtA (N ) ∼ = ExtB op (F (N )). b in The next step is to use the MGM equivalence. We know that LΛa (N ) ∼ =A D(Mod A). And the functor LΛa induces an isomorphism of graded A-algebras b ExtA (N ) ∼ = ExtA (A). 12 MARCO PORTA, LIRAN SHAUL AND AMNON YEKUTIELI b By Lemma 4.6 the homoIt remains to analyze the graded A-algebra ExtA (A). morphism b A[i]) b b Hom(τA , 1) : HomD(Mod A) (A, → RHomD(Mod A) (A, A[i]) b = 0 for i 6= 0, and the A-algebra is bijective for every i. Therefore ExtiA (A) 0 b b homomorphism A → ExtA (A) is bijective. Combining all the steps above we see that ExtiB (P ) = 0 for i 6= 0, and there is bop . But A b is commutative, so A bop = A. b an A-algebra isomorphism Ext0B (P ) ∼ =A b Regarding the uniqueness: since the image of the ring homomorphism A → A b is dense, and A is b a-adically complete, it follows that the only A-algebra automorb is the identity. Therefore the A-algebra isomorphism Ext0B (P ) ∼ b phism of A = A that we produced is unique.  Remark 4.7. To explain how surprising this theorem is, take the case P = M := K(A; a), the Koszul complex associated to a sequence a = (a1 , . . . , an ) that generates the ideal a. As a free A-module (forgetting the grading and the differential), we have P ∼ = n2 A . The grading of P depends on n only (it is an exterior algebra). The differential of P is the only place where the sequence a enters. Similarly, the DG algebra B = EndA (P ) is a graded matrix algebra over A, of size n2 × n2 . The differential of B is where a is expressed. Forgetting the differentials, i.e. working with the graded A-module P ♮ , classical Morita theory tells us that EndB ♮ (P ♮ ) ∼ = A as graded A-algebras. Furthermore, P ♮ ♮ is a projective B -module, so we even have ExtB ♮ (P ♮ ) ∼ = A. However, the theorem tells us that for the DG-module structure of P we have b Thus we get a transcendental outcome – the completion A b – by ExtB (P ) ∼ = A. a homological operation with finite input (basically finite linear algebra over A together with a differential). Remark 4.8. Our motivation to work on completion by derived double centralizer came from looking at the recent paper [Ef] by Efimov. The main result of [Ef] is Theorem 1.1 about the completion of the category D(QCoh X) of a noetherian scheme X along a closed subscheme Y . This idea is attributed to Kontsevich. Corollary 1.2 of [Ef] is a special case of our Theorem 4.2: it has the extra assumptions that the ring A is noetherian and regular (i.e. it has finite global cohomological dimension). After writing the first version of our paper, we learned that a similar result was proved by Dwyer-Greenlees-Iyengar [DGI]. In that paper the authors continue the work of [DG] on derived completion and torsion. Their main result is Theorem 4.10, which is a combination of MGM equivalence and derived Morita equivalence in an abstract setup (that includes algebra and topology). The manifestation of this main result in commutative algebra is [DGI, Proposition 4.20], that is also a special case of our Theorem 4.2: the ring A is noetherian, and the quotient ring A/a is regular. Recall that our Theorem 4.2 only requires the ideal a to be weakly proregular, and there is no regularity condition on the rings A and A/a (the word “regular” has a double meaning here!). It is quite possible that the methods of [DGI] or [Ef] can be pushed further to remove the regularity conditions from the rings A and COMPLETION BY DERIVED DOUBLE CENTRALIZER 13 A/a. However, it is less likely that these methods can handle the non-noetherian case (i.e. assuming only that the ideal a is weakly proregular). References [AJL] [BN] [BV] [DG] [DGI] [Ef] [GM] [Jo] [Ke] [LN] [PSY] [Ri] [Ro] [Sc] [Ye] L. Alonso, A. Jeremias and J. Lipman, Local homology and cohomology on schemes, Ann. Sci. ENS 30 (1997), 1-39. Correction, availabe online at http://www.math.purdue.edu/~lipman/papers/homologyfix.pdf. M. Bokstedt and A. Neeman, Homotopy limits in triangulated categories, Compositio Math. 86 (1993), 209-234. A. Bondal and M. Van den Bergh, Generators and representability of functors in commutative and noncommutative geometry, Moscow Math. J. 3 (2003), 1-36. W. G. Dwyer and J. P. C. Greenless, Complete Modules and Torsion Modules, American J. Math. 124, No. 1 (2002), 199-220. W.G. Dwyer, J.P.C. Greenlees and S. Iyengar, Duality in algebra and topology, Advances Math. 200 (2006), 357-402. A.I Efimov, Formal completion of a category along a subcategory, eprint arXiv:1006.4721 at http://arxiv.org. J.P.C. Greenlees and J.P. May, Derived functors of I-adic completion and local homology, J. Algebra 149 (1992), 438-453. P. Jørgensen, Recollement for differential graded algebras, J. Algebra 299 (2006) 589-601. B. Keller, Deriving DG categories, Ann. Sci. Ecole Norm. Sup. 27, (1994) 63-102. J. Lipman and A. Neeman, Quasi-perfect scheme-maps and boundedness of the twisted inverse image functor, Illinois J. Math. 51, Number 1 (2007), 209-236. M. Porta, L. Shaul and A. Yekutieli, On the Homology of Completion and Torsion, to appear in Algebras and Representation Theory. J. Rickard, Derived equivalences as derived functors, J. London Math. Soc. 43 (1991), 37-48. R. Rouquier, Dimensions of triangulated categories, Journal of K-theory (2008), 1:193256. P. Schenzel, Proregular sequences, Local Cohomology, and Completion, Math. Scand. 92 (2003), 161-180. A. Yekutieli, On Flatness and Completion for Infinitely Generated Modules over Noetherian Rings, Comm. Algebra 39, Issue 11 (2011), 4221-4245. Department of Mathematics, Ben Gurion University, Be’er Sheva 84105, Israel E-mail address: (Porta) marcoporta1@libero.it, (Shaul) shlir@math.bgu.ac.il, (Yekutieli) amyekut@math.bgu.ac.il
0 (math.AC)
NDT: Neual Decision Tree Towards Fully Functioned Neural Graph Han Xiao 1 arXiv:1712.05934v1 [cs.NE] 16 Dec 2017 Abstract Though traditional algorithms could be embedded into neural architectures with the proposed principle of (Xiao, 2017), the variables that only occur in the condition of branch could not be updated as a special case. To tackle this issue, we multiply the conditioned branches with Dirac symbol (i.e. 1x>0 ), then approximate Dirac symbol with the continuous functions (e.g. 1 − e−α|x| ). In this way, the gradients of condition-specific variables could be worked out in the back-propagation process, approximately, making a fully functioned neural graph. Within our novel principle, we propose the neural decision tree (NDT), which takes simplified neural networks as decision function in each branch and employs complex neural networks to generate the output in each leaf. Extensive experiments verify our theoretical analysis and demonstrate the effectiveness of our model. 1. Introduction Inspired by brain science, neural architectures have been proposed in 1943, (Mcculloch & Pitts, 1943). This branch of artificial intelligence develops from single perception (Casper et al., 1969) to deep complex network (Lecun et al., 2015), achieving several critical successes such as AlphaGo (Silver et al., 2016). Notably, all the operators (i.e. matrix multiply, non-linear function, convolution, etc.) in traditional neural networks are numerical and continuous, which could benefit from back-propagation algorithm, (Rumelhart et al., 1988). Recently, logics-based methods (e.g. Hungarian algorithm, max-flow algorithm, A∗ searching) are embedded into neural architectures in a dynamically graph-constructing manner, opening a new chapter for intelligence system, (Xiao, 1 State Key Laboratory of Intelligent Technology and Systems, National Laboratory for Information Science and Technology, Department of Computer Science and Technology, Tsinghua University, Beijing 100084, PR China. Correspondence to: Han Xiao <Almighty.Xiao.Han@iCloud.com>. Proceedings of the 35 th International Conference on Machine Learning, Stockholm, Sweden, PMLR 80, 2018. Copyright 2018 by the author(s). 2017). Generally, neural graph is defined as the intelligence architecture, which is characterized by both logics and neurons. With this proposed principle from the seminal work, we attempt to tackle image classification. Specifically, regarding this task, the overfull categories make too much burden for classifiers, which is a normal issue for large-scale datasets such as ImageNet (Deng et al., 2009). We conjecture that it would make effects to roughly classify the samples with decision tree, then category the corresponding samples with strong neural network in each leaf, because in each leaf, there are much fewer categories to predict. The attribute split in traditional decision trees (e.g. ID3, Random Forest, etc.) is oversimplified for precise pre-classification, (Zhou & Feng, 2017). Thus, we propose the method of neural decision tree (NDT), which applies neural network as decision function to strengthen the performance. Regarding the calculus procedure of NDT, the basic principle is to treat the logic flow (i.e. “if, for, while” in the sense of programming language) as a dynamic graph-constructing process, which is illustrated in Figure 1. This figure demonstrates the classification of four categories (i.e. sun, moon, car and pen), where an if structure is employed to split the samples into two branches (i.e. sun-moon, car-pen), where the fully connected networks generate the results respectively. In the forward propagation, our methodology activates some branch according to the condition of if, then dynamically constructs the graph according to the instructions in the activated branch. In this way, the calculus graph is constructed as a non-branching and continuous structure, where backward propagation could be performed conventionally, demonstrated in Figure 1 (b). Generally, we should note that the repeat (i.e. for, while) could be treated as performing if in multiple times, which could also be tackled by the proposed principle. Thus, all the traditional algorithms could be embedded into neural architectures. For more details, please refer to (Xiao, 2017). However, as a special challenge of this paper, the variables that are only introduced in the condition of branch could not be updated in the backward propagation, because they are outside the dynamically constructed graph, for the example of W in Figure 1. Thus, to make a completely functioned neural graph, this paper attempts to tackle this issue in an ap- NDT: Neual Decision Tree Towards Fully Functioned Neural Graph cantly, which illustrates the effectiveness of our methodology. The most important conclusion is that “our model is differentiable”, which verifies our theory and provides the novel methodology of fully functioned neural graph. Contributions (1.) We complete the principle of neural graph, which characterizes the intelligence systems with both logics and neurons. Also, we provide the proof that neural graph is Turing complete, which makes a learnable Turing machine for the theory of computation. (2.) To tackle the issue of overfull categories, we propose the method of neural decision tree (NDT), which takes simplified neural networks as decision function in each branch and employs complex neural networks to generate the output in each leaf. (3.) Our model outperforms other baselines extensively, verifying the effectiveness of our theory and method. Organization. In the Section 2, our methodology and neural architecture are discussed. In the Section 3, we specific the implementation of fully functioned neural graph in detail. In the Section 4, we provide the proof that neural graph is Turing complete. In the Section 5, we conduct the experiments for performance and verification. In the Section 6, we briefly introduce the related work. In Section 7, we list the potential future work from a developing perspective. Finally in the Section 8, we conclude our paper and publish our codes. Figure 1. Illustration of how logic flow is processed in our methodology. Referring to (b), we process the if-else structure of (a) in a dynamically graph-constructing manner. Theoretically, we construct the graph according to the active branch, in the forward propagation. When the forward propagation has constructed the graph according to logic instructions, the backward propagation would be performed as usual in a continuous and non-branching graph. Practically, the dynamically constructed process corresponds to batch operations. The samples with id 1,3,4 are activated in if branch, while those with id 2,5 are tackled in else branch. After the end of if-else instruction, the sub-batch hidden representations are joined as the classified results. proximated manner. Simply, we multiply the symbols inside the branch with Dirac function (i.e. 1x>0 or 1x≤0 ). Specifically, regarding Figure 1, we reform F CN etwork(img) as F CN etwork(img ⊗1tanh>0 ) in the if branch and perform the corresponding transformation in the else branch, where ⊗ is element-wise multiplication. The forward propagation would not be modified by the reformulation, while as to the backward process, we approximate the Dirac symbol with a continuous function to work out the gradients of condition, which solves this issue. It is noted that in this paper, the continuous function is 1 − e−α|x| ≈ 1x>0 . We conduct our experiments on public benchmark datasets: MNIST and CIFAR. Experimental results illustrate that our model outperforms other baselines extensively and signifi- 2. Methodology First, we introduce the overview of our model. Then, we discuss each component, specifically. Last, we discuss our model from the ensemble perspective. 2.1. Architecture Our architecture is illustrated in Figure 2, which is composed by three customized components namely feature, condition and target network. Firstly, The input is transformed by feature network and then the hidden features are classified by decision tree component composed by hierarchal condition networks. Secondly, the target networks predict the categories for each sample in each leaf. Finally, the targets are joined to work out the cross entropy objective. The process is exemplified in Algorithm 1. Feature Network. To extract the abstract features with deep neural structures, we introduce the feature network, which is often a stacked CNN and LSTM. Condition Network. To exactly pre-classify each sample, we employ a simplified neural network as condition network, which is usually a one- or two-layer multi-perceptions with the non-linear function of tanh. This layer is only applied in the inner nodes of decision tree. Actually, the effectiveness of traditional decision tree stems from the information gain NDT: Neual Decision Tree Towards Fully Functioned Neural Graph t = plef j pright = j PNtotal 1cn>0,j Li,j i=0 PNtotal 1cn>0 i=0 PNtotal 1cn≤0,j Li,j i=0 PNtotal 1cn≤0 i=0 (4) (5) where cn is short for condition network and Li,j is the adhoc label vector of i-th sample, where the true label position is 1 and otherwise 0. By simple computations, we have: PNtotal t Li,j ln(plef ) ∂IG j i=0 = (6) ∂1cn>0 Ntotal PNtotal Li,j ln(pright ) ∂IG j i=0 = (7) ∂1cn≤0 Ntotal where IG is short for Inf oGain. As discussed in Introduction, we approximate the Dirac symbol as a continuous function, specifically as 1 − e−α|x| ≈ 1x>0 . Thus, the gradient of condition network could be deducted as: ∂IG ∂IG ∂(1 − e−α|cn|) ∂IG ≈ = (αe−α|x| s(cn)) (8) ∂cn ∂1cn>0 ∂cn ∂1cn>0 ∂IG ∂(1 − e−α|cn|) ∂IG ∂IG ≈ = (αe−α|x| s(cn)) (9) ∂cn ∂1cn≤0 ∂cn ∂1cn≤0 Figure 2. The neural architecture of NDT (depth = 2). The input is classified by decision tree component with the condition networks, then the target networks predict the categories for each sample in each leaf. Notably, the tree component takes advantages of subbatch technique, while the targets are joined in batch to compute the cross entropy objective. splitting rules, which could not be learned by condition networks, directly. Thus, we involve an objective item for each decision node to maximize the information gain as: max Inf oGain = |F | Nright X right p ln(pright ) (1) j Ntotal j=0 j where N is the corresponding count, |F | is the feature number and p is the corresponding probabilistic distribution of features. Regarding the derivatives relative to Dirac symbol, we firstly reformulate the information gain in the form of Dirac symbol as: Nlef t = 1cn>0 (2) 1cn≤0 (3) i=1 Nright = NX total i=1 Actually, all the reduction could be performed automatically within the proposed principle, that to multiply the symbols inside the branch with Dirac function. PNtotal Specifically, as an example of the count, Nlef t = i=1 1 × 1cn>0 . Target Network. To finally predict the category of each sample, we apply a complex network as the target network, which often is a stacked convolution one for image or an LSTM for sentence. 2.2. Analysis From Ensemble Perspective |F | Nlef t X lef t t p ln(plef )+ j Ntotal j=0 j NX total where s is the sign function. NDT could be treated as an ensemble model, which ensembles many target networks with the hard branching condition networks. Currently, there exist two branches of ensemble methods, namely split by features, or split by samples, both of which increases the difficulty of single classifier. However, NDT splits the data by categories, which means single classifier deals with a simpler task. The key point is the split purity of condition networks, because the branching reduces the sample numbers for each leaf. Relatively to single classifier, if our model keeps the sample number per category, NDT could make more effects. For an example of one leaf, the sample number reduces to 30%, while the category number reduces from 10 to 3. With similarly sufficient samples, our model deals with 3classification, which is much easier than 10-classification. Thus, our model benefits from the strengthen of single classifier. NDT: Neual Decision Tree Towards Fully Functioned Neural Graph Algorithm 1 Neural Decision Tree (NDT) To implement symbol-specific logic component, we propose two batch operations, namely sub- and join-batch operation. Take the example of Figure 1 (c). To begin, there are five samples in the batch. In the forward pass, once processing in the branch, according to the condition, the batch is split into two sub-batches, each of which is respectively tackled by the instructions in the corresponding branch, simultaneously. After processed by two branches, the sub-batches are joined into one batch, according to the original order. In the backward propagation, the gradients of joined batch are split into two parts, which correspond to two sub-batches. When the process has propagated through two branches, the gradients of two sub-batches are joined again to form the gradients of stacked CNN. Theoretically, a sample in some sub-batch means the corresponding branch is activated for this sample and the other branch is deactivated. On the other word, the hidden representations of this sample connect to the activated branch rather than the deactivated one. Thus, the symbol-specific logic components perform our proposed principle, in the manner of sub- and join-batch operation. Notably, if there is no variable that is only introduced in the condition, it is unnecessary to update the condition, which makes corresponding neural graph an exact method. 3. Dynamical Graph Construction Previously introduced, neural graph is the intelligence architecture, which is characterized by both logics and neurons. Mathematically, the component of neurons are continuous functions, such as matrix multiply, hyperbolic tangent (tanh), convolution layer, etc, which could be implemented as mathematical operations. Obviously, simple principal implementation for non-batch mode is easy and direct. But practically, all the latest training methods take the advantages of batched mode. Hence, we focus on the batched implementation of neural graph in this section. Conventionally, neural graph is composed by two styles of variable, namely symbols such as W in Figure 1, and atomic types such as the integer d in Algorithm 1 Line 2. In essence, symbolic variables originate from the weights between neurons, while the atomic types are introduced by the embedded traditional algorithms. Therefore, regarding the component of logics, there exist two styles: symbol- and atomic-type-specific logic components, which are differentiated in implementation. Symbolspecific logics indicates the condition involves the symbols, such as Line 5 ∼ 9 in Algorithm 1, while atomic-typespecific logics means there are only atomic types in the condition such as Line 2 in Algorithm 1. However, our proposed principle, that dynamically constructing neural graph, could process both the situations. To implement atomic-type-specific logic component, we propose a more flexible batch operation namely allocatebatch. Take the example of Hungarian Layer (Xiao, 2017). The Hungarian algorithm deals with the similarity matrix to provide the alignment information, according to which, the dynamic links between symbols are dynamically allocated, shown in Figure 4 of (Xiao, 2017). Thus, the forward and backward propagation could be performed in a continuous calculus graph. Simply, in the forward pass, we record the allocated dynamic links of each sample in the batch, while in the backward pass, we propagate the gradients along these dynamic links. Obviously, the atomic-type-specific logic components perform our proposed principle, in the manner of allocate-batch operation. The traditional algorithms are a combination of branch (i.e. if ) and repeat (i.e. for, while). Repeat could be treated as performing branch in multiple times. Thus, the three batch operations, namely sub-, join- and allocate-batch operation, could process all the traditional algorithms, such as resolution method, A∗ searching, Q-learning, label propagation, PCA, K-Means, Multi-Armed Bandit (MAB), AdaBoost. 4. Neural Graph is Turing Complete Actually, if neural graph could simulate the Turing machine, it is Turing complete. Turing machine is composed by four parts: a cell-divided tape, reading/writing head, state register and a finite table of instructions. Correspondingly, NDT: Neual Decision Tree Towards Fully Functioned Neural Graph symbols are based on tensor arrays, which simulate the celldivided tape. Forward/Backward process indicate where to read/write. Atomic-type-specific variables record the state. Last, the logic flow (i.e. if, while, for) constructs the finite instruction table. In summary, neural graph is Turing complete. Specifically, neural graph is a learnable Turing machine rather than a static one. Learnable Turing machine could adjust the behaviors/performance, according to data and environment. Traditional computation models focus on static algorithms, while neural graph takes advantages of data and perception to strengthen the rationality of behaviors. 5. Experiment In the section, we verify our model on two datasets: MNIST (Lecun et al., 1998) and CIFAR (Krizhevsky, 2009). We first introduce the experimental settings in Section 4.1. Then, in Section 4.2, we conduct performance experiments to testify our model. Last, in Section 4.3, to further verify our theoretical analysis, that NDT could reduce the category number of leaf nodes, we perform a case study to justify our assumption. 5.1. Experimental Setting There exist three customized networks in our model, that the feature, condition and target network. We simply apply identify mapping as feature network. Regarding the condition network, we apply a two-layer fully connected perceptions, with the hyper-parameter input-300-1 for MNIST and input-3000-1 for CIFAR. Regarding the target network, we also employ a three-layer fully connected perceptions, with the hyper-parameter input-300-100-10 for MNIST, input3000-1000-10 for CIFAR-10 and input-3000-1000-100 for CIFAR-100. 1 To train the model, we leverage AdaDelta (Zeiler, 2012) as our optimizer, with hyper-parameter as moment factor η = 0.6 and  = 1 × 10−6 . We train the model until convergence, but at most 1,000 rounds. Regarding the batch size, we always choose the largest one to fully utilize the computing devices. Notably, the hyper-parameters of approximated continuous function is α = 1000. 5.2. Performance Verification MNIST. The MNIST dataset (Lecun et al., 1998) is a classic benchmark dataset, which consists of handwritten digit images, 28 x 28 pixels in size, organized into 10 classes (0 to 9) with 60,000 training and 10,000 test samples. We select some representative and competitive baselines: modern 1 We know the feature and target network are too oversimplified for this task. But this version targets at an exemplified model, which still could verify our conclusions. We will perform a complex feature and target network in the next/final version. Table 1. Performance Evaluation on MNIST Dataset. Methods Single Target Network LeNet-5 Multi-Perspective CNN Deep Belief Net SVM (RBF kernel) Random Forest Accuracy (%) 96.95 99.50 81.38 98.75 98.60 96.80 NDT (depth = 2) 97.90 CNN-based architecture LeNet-5 with dropout and ReLUs, classic linear classifier SVM with RBF kernel, Deep Belief Nets and a standard Random Forest with 2,000 trees. We could observe that: 1. NDT will beat all the baselines, verifying our theory and justifying the effectiveness of our model. 2. Compared to single target network, NDT promotes 0.65 point, which illustrates the ensemble of target network is effective. 3. Compared to Random Forest that is also a tree-based method, NDT promotes 0.75 point, which demonstrates the neurons indeed strengthen the decision trees. CIFAR. The CIFAR-10/100 dataset (Krizhevsky, 2009), is also a classic benchmark for overfull category classification, which consists of color natural images, 32 x 32 pixels in size, from 10/100 classes with 50,000 training and 10,000 test images. Several representative baselines are selected as Network in Network (NIN) (Lin et al., 2013), FitNets (Rao et al., 2016), Deep Supervised Network (DSN) (Lee et al., 2014), High-Way (Srivastava et al., 2015), All-CNN (Springenberg et al., 2014), Exponential Linear Units (ELU) (Clevert et al., 2015), FitResNets (Mishkin & Matas, 2015), gcForest (Zhou & Feng, 2017) and Deep ResNet (He et al., 2016). We could conclude that: 1. NDT will beat all the strong baselines, which verifies the effectiveness of neural decision trees and justifies the theoretical analysis. 2. Compared to single target network, NDT promotes 4.85 point, which illustrates the ensemble of target network is effective. 3. Compared with gcForest, the performance improves - points, which illustrates that neurons empower the decision trees more effectively than direct ensembles. 4. Compared with ResNet that is the strongest baseline, we promote the results over - points, which justifies NDT: Neual Decision Tree Towards Fully Functioned Neural Graph Figure 3. Case Study for NDT in MNIST with depth = 2 (a) and depth = 3 (b). The left tables are the test sample numbers that correspond to row-th leaf node and col-th category. For example, the sliced “1105” means there are 1105 test samples of category “1” in leaf node “A”. We slice the main component of a leaf and draw the corresponding decision trees in the right panel. Notably, “X” indicates the empty class. Table 2. Performance Evaluation (Error (%)) on CIFAR. Methods NIN DSN FitNets High-Way All-CNN ELU FitResNets ResNet gcForest Random Forest Single Target Network CIFAR-10 8.81 8.22 8.39 7.72 7.25 6.55 5.84 6.61 31.00 50.17 - CIFAR-100 35.68 34.57 35.04 32.39 33.71 24.28 27.66 25.16 89.37 NDT (depth = 4) - 84.52 our assumption, that NDT could reduce the category number of leaf nodes to enhance the intelligence systems. 5.3. Case Study To further testify our assumption that NDT could reduce the category number of leaf nodes, we perform a case study in MNIST. We make a statistics of test samples for each leaf node, illustrated in Figure 3. The item of table means row-th leaf node has how many samples in col-th category. For example, the “1105” in the first row and second column, means that there are 1,105 test samples of category “1” are pre-classified into leaf node “A”. Correspondingly, we draw the decision trees in the right panel with labeled categories, which specifically illustrates the decision process of NDT. For a complete verification, we vary the depth of NDT with 2 and 3. Firstly, we could clearly draw the conclusion from Figure 3, that each leaf node needs to predict less categories, which justifies our assumption. For example, in the bottom figure, the node “A” only needs to predict the category “1”, which is a single classification, and the node “H” only needs to predict the categories “0,3,5,8” which is a four classification. Because small classification is less difficult than large one, our target network in the leaf could perform better, which leads to performance promotion in a tree-ensemble manner. Secondly, from Figure 3, split purity could be worked out. Generally, the two-layer tanh multi-perception achieves a decent split purity. Indeed, the most difficult leaf nodes (e.g. “D” in the top and “H” in the bottom) are not perfect, but others gain a competitive split purity. Statistically, the main component or the sliced grid takes 92.4% share of total samples, which in a large probability, NDT would perform better than 92.4% accuracy in this case. NDT: Neual Decision Tree Towards Fully Functioned Neural Graph Finally, we discuss the hyper-parameter depth. From the top to the bottom of Figure 3, the categories are further split. For example, the node “B” in the top is split into “C” and “D” in the bottom, which means that the category “2” and “6” are further pre-classified. In this way, deep neural decision tree is advantageous. But much deeper NDT makes less sense, because the categories have been already split well. There would be mostly no difference for 1- or 2-classification. However, considering the efficiency and consuming resources, we suggest to apply a suitable depth, or theoretically about log2 (|C|), where |C| is the total category number. 6. Related Work In this section, we briefly introduce three lines of related work: image recognition, decision tree and neural graph. Convolution layer is necessary in current neural architectures for image recognition. Almost every model is a convolutional model with different configurations and layers, such as All-CNN (Springenberg et al., 2014) and DSN (Lee et al., 2014). Empirically, deeper network produces better accuracy. But it is difficult to train much deeper network for the issue of vanishing/exploding gradients, (Glorot & Bengio, 2010). Recently, there emerge two ways to tackle this problem: High-Way (Srivastava et al., 2015) and Residual Network (He et al., 2015). Inspired by LSTM, high-way network applies transform- and carry-gates for each layer, which allow information to flow across layers along the computation path without attenuation. For a more direct manner, residual network simply employs identity mappings to connect relatively top and bottom layers, which propagates the gradients more effectively to the whole network. Notably, achieving the state-of-the-art performance, residual network (ResNet) is the strongest model for image recognition, temporarily. Decision tree is a classic paradigm of artificial intelligence, while random forest is the representative methodology of this branch. During recent years, completely random tree forest has been proposed, such as iForest (Liu et al., 2008) for anomaly detection. However, with the popularity of deep neural network, lots of researches focus on the fusion between neurons and random forest. For example, (Richmond et al., 2015) converts cascaded random forests to convolutional neural network, (Welbl, 2014) leverages random forests to initialize neural network. Specially, as the stateof-the-art model, gcForest (Zhou & Feng, 2017) allocates a very deep architecture for forests, which is experimentally verified on several tasks. Notably, all of this branch could not jointly train the neurons and decision trees, which is the main disadvantage. To jointly fuse neurons and logics, (Xiao, 2017) proposes the basic principle of neural graph, which could embed traditional logics-based algorithms into neural architectures. The seminal paper merges the Hungarian algorithm with neurons as Hungarian layer, which could effectively recognize matched/unmatched sentence pairs. However, as a special case, the variables only introduced in the condition could not be updated, which is a disadvantage for characterizing complex systems. Thus, this paper focuses on this issue to make a fully functioned neural graph. 7. Future Work We list three lines of future work: design new components of neural graph, implement a script language for neural graph and analyze the theoretical properties of learnable Turing machine. This paper exemplifies an approach to embed decision tree into neural architectures. Actually, many traditional algorithms could promote intelligence system with neurons. For example, neural A∗ searching could learn the heuristic rules from data, which could be more effective and less resource consuming. For a further example, we could represent the data with deep neural networks, and conduct label propagation upon the hidden representations, where the propagation graph is constructed by K-NN method. Because the label propagation, K-NN and deep neural networks are trained jointly, the performance promotion could be expected. In fact, a fully functioned neural graph may be extremely hard and complex to implement. Thus, we expect to publish a script language for modeling neural graph and also a library that includes all the mainstream intelligence methods. Based on these instruments, neural graph could be more convenient for practical usage. Finally, as we discussed, neural graph is Turing complete, making a learnable Turing machine. We believe theoretical analysis is necessary for compilation and ability of neural graph. Take an example. Do the learnable and static Turing machine have the same ability? Take a further example. Could our brain excel Turing machine? If not, some excellent neural graphs may gain advantages over biological brain, because both of them are learnable Turing machines. If it could, the theoretical foundations of intelligence should be reformed. Take the final example. What is the best computation model for intelligence? 8. Conclusion This paper proposes the principle of fully functioned neural graph. Based on this principle, we design the neural decision tree (NDT) for image recognition. Experimental results on benchmark datasets demonstrate the effectiveness of our proposed method. NDT: Neual Decision Tree Towards Fully Functioned Neural Graph References Casper, M, Mengel, M, Fuhrmann, C, Herrmann, E, Appenrodt, B, Schiedermaier, P, Reichert, M, Bruns, T, Engelmann, C, and Grnhage, F. Perceptrons: An introduction to computational geometry. 75(3):3356–62, 1969. Clevert, DjorkArn, Unterthiner, Thomas, and Hochreiter, Sepp. Fast and accurate deep network learning by exponential linear units (elus). Computer Science, 2015. Deng, Jia, Dong, Wei, Socher, Richard, Li, Li-Jia, Li, Kai, and Fei-Fei, Li. Imagenet: A large-scale hierarchical image database. In Computer Vision and Pattern Recognition, 2009. CVPR 2009. IEEE Conference on, pp. 248– 255. IEEE, 2009. Glorot, Xavier and Bengio, Yoshua. Understanding the difficulty of training deep feedforward neural networks. In Proceedings of the Thirteenth International Conference on Artificial Intelligence and Statistics, pp. 249–256, 2010. He, Kaiming, Zhang, Xiangyu, Ren, Shaoqing, and Sun, Jian. Deep residual learning for image recognition. pp. 770–778, 2015. He, Kaiming, Zhang, Xiangyu, Ren, Shaoqing, and Sun, Jian. Deep residual learning for image recognition. In Computer Vision and Pattern Recognition, pp. 770–778, 2016. Krizhevsky, Alex. Learning multiple layers of features from tiny images. 2009. Lecun, Y., Bottou, L., Bengio, Y., and Haffner, P. Gradientbased learning applied to document recognition. Proceedings of the IEEE, 86(11):2278–2324, 1998. Lecun, Yann, Bengio, Yoshua, and Hinton, Geoffrey. Deep learning. Nature, 521(7553):436–444, 2015. Lee, Chen Yu, Xie, Saining, Gallagher, Patrick, Zhang, Zhengyou, and Tu, Zhuowen. Deeply-supervised nets. Eprint Arxiv, pp. 562–570, 2014. Lin, Min, Chen, Qiang, and Yan, Shuicheng. Network in network. Computer Science, 2013. Liu, Fei Tony, Kai, Ming Ting, and Zhou, Zhi Hua. Isolation forest. In Eighth IEEE International Conference on Data Mining, pp. 413–422, 2008. Mcculloch, Warren S and Pitts, Walter H. A logical calculus of ideas imminent in nervous activity. 1943. Mishkin, Dmytro and Matas, Jiri. All you need is a good init. 69(14):3013–3018, 2015. Rao, Jinfeng, He, Hua, and Lin, Jimmy. Noise-contrastive estimation for answer selection with deep neural networks. In ACM International on Conference on Information and Knowledge Management, pp. 1913–1916, 2016. Richmond, David L., Kainmueller, Dagmar, Yang, Michael Y., Myers, Eugene W., and Rother, Carsten. Relating cascaded random forests to deep convolutional neural networks for semantic segmentation. Computer Science, 2015. Rumelhart, D. E., Hinton, G. E., and Williams, R. J. Learning internal representations by error propagation. MIT Press, 1988. Silver, David, Huang, Aja, Maddison, Chris J., Guez, Arthur, Sifre, Laurent, Driessche, George Van Den, Schrittwieser, Julian, Antonoglou, Ioannis, Panneershelvam, Veda, and Lanctot, Marc. Mastering the game of go with deep neural networks and tree search. Nature, 529(7587):484, 2016. Springenberg, Jost Tobias, Dosovitskiy, Alexey, Brox, Thomas, and Riedmiller, Martin. Striving for simplicity: The all convolutional net. Eprint Arxiv, 2014. Srivastava, Rupesh Kumar, Greff, Klaus, and Schmidhuber, Jrgen. Training very deep networks. Computer Science, 2015. Welbl, Johannes. Casting random forests as artificial neural networks (and profiting from it). In German Conference on Pattern Recognition, pp. 765–771. Springer, 2014. Xiao, Han. Hungarian layer: Logics empowered neural architecture. arXiv preprint arXiv:1712.02555, 2017. Zeiler, Matthew D. Adadelta: An adaptive learning rate method. Computer Science, 2012. Zhou, Zhi Hua and Feng, Ji. Deep forest: Towards an alternative to deep neural networks. 2017.
9 (cs.NE)
Alignment Elimination from Adams’ Grammars Härmel Nestra1 1 Institute of Computer Science, University of Tartu, J. Liivi 2, 50409 Tartu, Estonia harmel.nestra@ut.ee arXiv:1706.06497v1 [cs.PL] 20 Jun 2017 Abstract Adams’ extension of parsing expression grammars enables specifying indentation sensitivity using two non-standard grammar constructs — indentation by a binary relation and alignment. This paper proposes a step-by-step transformation of well-formed Adams’ grammars for elimination of the alignment construct from the grammar. The idea that alignment could be avoided was suggested by Adams but no process for achieving this aim has been described before. 1998 ACM Subject Classification D.3.1 Formal Definitions and Theory; D.3.4 Processors; F.4.2 Grammars and Other Rewriting Systems Keywords and phrases Parsing expression grammars, indentation, grammar transformation 1 Introduction Parsing expression grammars (PEG) introduced by Ford [6] serve as a modern framework for specifying the syntax of programming languages and are an alternative to the classic context-free grammars (CFG). The core difference between CFG and PEG is that descriptions in CFG can be ambiguous while PEGs are inherently deterministic. A syntax specification written in PEG can in principle be interpreted as a top-down parser for that syntax; in the case of left recursion, this treatment is not straightforward but doable (see, e.g., [8]). Formally, a PEG is a quadruple G = (N, T, δ, s) where: N is a finite set of non-terminals; T is a finite set of terminals; δ is a function mapping each non-terminal to its replacement (corresponding to the set of productions of CFG); s is the start expression (corresponding to the start symbol of CFG). So δ : N → EG and s ∈ EG , where the set EG of all parsing expressions writable in G is defined inductively as follows: 1. ε ∈ EG (the empty string); 2. a ∈ EG for every a ∈ T (the terminals); 3. X ∈ EG for every X ∈ N (the non-terminals); 4. pq ∈ EG whenever p ∈ EG , q ∈ EG (concatenation) 5. p/q ∈ EG whenever p ∈ EG , q ∈ EG (choice); 6. !p ∈ EG whenever p ∈ EG (negation, or lookahead); 7. p ∗ ∈ EG whenever p ∈ EG (repetition). All constructs of PEG except for negation are direct analogues of constructs of the EBNF form of CFG, but their semantics is always deterministic. So p ∗ repeats parsing of p until failure, and p/q always tries to parse p first, q is parsed only if p fails. For example, the expression ab/a consumes the input string ab entirely while a/ab only consumes its first character. The corresponding EBNF expressions ab | a and a | ab are equivalent, both can match either a or ab from the input string. Negation !p tries to parse p and fails if p succeeds; © Härmel Nestra; licensed under Creative Commons License CC-BY 2 Alignment Elimination from Adams’ Grammars if p fails then !p succeeds with consuming no input. Other constructs of EBNF like non-null repetition p + and optional occurrence [p] can be introduced to PEG as syntactic sugar. Languages like Python and Haskell allow the syntactic structure of programs to be shown by indentation and alignment, instead of the more conventional braces and semicolons. Handling indentation and alignment in Python has been specified in terms of extra tokens INDENT and DEDENT that mark increasing and decreasing of indentation and must be generated by the lexer. In Haskell, rules for handling indentation and alignment are more sophisticated. Both these languages enable to locally use a different layout mode where indentation does not matter, which additionally complicates the task of formal syntax specification. Adams and Ağacan [3] proposed an extension of PEG notation for specifying indentation sensitivity and argued that it considerably simplifies this task for Python, Haskell and many other indentation-sensitive languages. In this extension, expression p > , for example, denotes parsing of p while assuming a greater indentation than that of the surrounding block. In general, parsing expressions may be equipped with binary relations (as was > in the example) that must hold between the baselines of the local and the current indentation block. In addition, ¦p¦ denotes parsing of p while assuming the first token of the input being aligned, i.e., positioned on the current indentation baseline. For example, the do expressions in Haskell can be specified by <doexp> <istmts> <stmts> ::= ::= ::= do> (<istmts>/<stmts>) + (¦<stmt>¦ )> > { (<stmt>(;<stmt>)∗ [;]})~ Here, <istmts> and <stmts> stand for statement lists in the indentation and relaxed mode, respectively. In the indentation mode, a statement list is indented (marked by > in the second production) and all statements in it are aligned (marked by ¦ · ¦). In the relaxed mode, however, relation ~ is used to indicate that the indentation baseline of the contents can be anything. (Technically, ~ is the binary relation containing all pairs of natural numbers.) Terminals do and { are also equipped with > to meet the Haskell requirement that subsequent tokens of aligned blocks must be indented more than the first token. Alignment construct provides fulcra for disambiguating the often large variety of indentation baseline candidates. Besides simplicity of this grammar extension and its use, a strength of it lies in the fact that grammars can still serve as parsers. The rest of the paper is organized as follows. Section 2 formally introduces additional constructs of PEG for specifying code layout, defines their semantics and studies their semantic properties. In Sect. 3, a semantics-preserving process of eliminating the alignment construct from grammars is described. Section 4 refers to related work and Sect. 5 concludes. 2 Indentation extension of PEG Adams and Ağacan [3] extend PEGs with the indentation and alignment constructs. We propose a slightly different extension with three rather than two extra constructs. Our approach agrees with that implemented by Adams in his indentation package for Haskell [1], whence calling the grammars in our approach Adams’ grammars is justified. All differences between the definitions in this paper and in [3] are listed and discussed in Subsect. 2.4. Let N denote the set of all natural numbers, and let B = {tt, ff } (the Boolean domain). Denote by ℘(X) the set of all subsets of set X, and let <(X) denote the set of all binary relations on set X, i.e., <(X) = ℘(X × X). Standard examples are >∈ <(N) (consisting of all pairs (n, m) of natural numbers such that n > m) and 4 ∈ <(N) (the identity H. Nestra relation consisting of all pairs of equal natural numbers); the indentation extension also makes use of ~ ∈ <(N) (the relation containing all pairs of natural numbers). Whenever ρ ∈ <(X) and Y ⊆ X, denote ρ(Y ) = {x ∈ X : ∃y ∈ Y.(y, x) ∈ ρ} (the image of Y under relation ρ). The inverse relation of ρ is defined by ρ−1 = {(x, y) : (y, x) ∈ ρ}, and the composition of relations σ and ρ by σ ◦ ρ = {(x, z) : ∃y.(x, y) ∈ σ ∧ (y, z) ∈ ρ}. Finally,  denote <+ (X) = ρ ∈ <(X) : ∀x ∈ X.ρ−1 ({x}) 6= ∅ = {ρ ∈ <(X) : ρ(X) = X}. 2.1 Adams’ grammars Extend the definition of EG given in Sect. 1 with the following three additional clauses: 8. p ρ ∈ EG for every p ∈ EG and ρ ∈ <(N) (indentation); 9. p σ ∈ EG for every p ∈ EG and σ ∈ <(N) (token position); 10. ¦p¦ ∈ EG for every p ∈ EG (alignment). Parsing of an expression p ρ means parsing of p while assuming that the part of the input string corresponding to p forms a new indentation block whose baseline is in relation ρ to the baseline of the surrounding block. (Baselines are identified with column numbers.) The position construct p σ , missing in [3], determines how tokens of the input can be situated w.r.t. the current indentation baseline. Finally, parsing an expression ¦p¦ means parsing of p while assuming the first token of the input being positioned on the current indentation baseline (unlike the position operator, this construct does not affect processing the subsequent tokens). Inspired by the indentation package [1], we call the relations that determine token positioning w.r.t. the indentation baseline token modes. In the token mode > for example, tokens may appear only to the right of the indentation baseline. Applying the position operator with relation > to parts of Haskell grammar to be parsed in the indentation mode avoids indenting every single terminal in the example in Sect. 1. Also, indenting terminals with > is inadequate for do expressions occurring inside a block of relaxed mode but the position construct can be easily used to change the token mode for such blocks (e.g., to ≥). We call a PEG extended with these three constructs a PEG> . Recall from Sect. 1 that N and T denote the set of non-terminal and terminal symbols of the grammar, respectively, and δ : N → EG is the production function. Concerning the semantics of PEG> , each expression parses an input string of terminals (w ∈ T ∗ ) in the context of a current set of indentation baseline candidates (I ∈ ℘(N)) and a current alignment flag indicating whether the next terminal should be aligned or not (b ∈ B), assuming a certain token mode (τ ∈ <(N)). Parsing may succeed, fail, or diverge. If parsing succeeds, it returns as a result a new triple containing the rest of the input w0 , a new set I 0 of baseline candidates updated according to the information gathered during parsing, and a new alignment flag b0 . This result is denoted by >(w0 , I 0 , b0 ). If parsing fails, there is no result in a triple form; failure is denoted by ⊥. Triples of the form (w, I, b) ∈ T ∗ × ℘(N) × B are behaving as operation states of parsing, as each parsing step may use these data and update them. We will write State = T ∗ × ℘(N) × B (as we never deal with different terminal sets, dependence on T is not explicitly marked), and denote by State + 1 the set of possible results of parsing, i.e., {>(s) : s ∈ State} ∪ {⊥}. The assertion that parsing expression e in grammar G with input string w in the context of I and b assuming token mode τ results in o ∈ State + 1 is denoted by e, τ `G (w, I, b) → o. The formal definition below must be interpreted inductively, i.e., an assertion of the form G, τ `e s → o is valid iff it has a finite derivation by the following ten rules: 1. ε, τ `G s → >(s). 2. For every a ∈ T , a, τ `G (w, I, b) → o holds in two cases: 3 4 Alignment Elimination from Adams’ Grammars If o = >(w0 , I 0 , ff ) for w0 , I 0 , i such that w = ai w0 (ai denotes a occurring at column i) and either b = ff and i ∈ τ−1 (I), I 0 = I ∩ τ({i}), or b = tt and i ∈ I, I 0 = {i}; If o = ⊥, and there are no w0 and i such that w = ai w0 with either b = ff and i ∈ τ−1 (I) or b = tt and i ∈ I. 3. For every X ∈ N , X, τ `G s → o holds if δ(X), τ `G s → o holds. 4. For every p, q ∈ EG , pq, τ `G s → o holds in two cases: If there exists a triple s0 such that p, τ `G s → >(s0 ) and q, τ `G s0 → o; If p, τ `G s → ⊥ and o = ⊥. 5. For every p, q ∈ EG , p/q, τ `G s → o holds in two cases: If there exists a triple s0 such that p, τ `G s → >(s0 ) and o = >(s0 ); If p, τ `G s → ⊥ and q, τ `G s → o. 6. For every p ∈ EG , !p, τ `G s → o holds in two cases: If p, τ `G s → ⊥ and o = >(s); If there exists a triple s0 such that p, τ `G s → >(s0 ) and o = ⊥. 7. For every p ∈ EG , p ∗ , τ `G s → o holds in two cases: If p, τ `G s → ⊥ and o = >(s); If there exists a triple s0 such that p, τ `G s → >(s0 ) and p ∗ , τ `G s0 → o. 8. For every p ∈ EG and ρ ∈ <(N), p ρ , τ `G (w, I, b) → o holds in two cases: If there exists a triple (w0 , I 0 , b0 ) such that p, τ `G (w, ρ−1 (I), b) → >(w0 , I 0 , b0 ) and o = >(w0 , I ∩ ρ(I 0 ), b0 ); If p, τ `G (w, ρ−1 (I), b) → ⊥ and o = ⊥. 9. For every p ∈ EG and σ ∈ <(N), p σ , τ `G s → o holds if p, σ `G s → o holds. 10. For every p ∈ EG , ¦p¦, τ `G (w, I, b) → o holds in two cases: If there exists a triple (w0 , I 0 , b0 ) such that p, τ `G (w, I, tt) → >(w0 , I 0 , b0 ) and o = >(w0 , I 0 , b ∧ b0 ); If p, τ `G (w, I, tt) → ⊥ and o = ⊥. The idea behind the conditions i ∈ τ−1 (I) and i ∈ I occurring in clause 2 is that any column i where a token may appear is in relation τ with the current indentation baseline (known to be in I) if no alignment flag is set, and coincide with the indentation baseline otherwise. For the same reason, consuming a token in column i restricts the set of allowed indentations to τ({i}) or {i} depending on the alignment flag. In both cases, the alignment flag is set to ff . In clause 8 for p ρ , the set I of allowed indentation is replaced by ρ−1 (I) as the local indentation baseline must be in relation ρ with the current indentation baseline known to be in I. After successful parsing of p with the resulting set of allowed local indentations being I 0 , the set of allowed indentations of the surrounding block is restricted to ρ(I 0 ). Clause 10 similarly operates on the alignment flag. > For a toy example, consider parsing of ¦ab¦ with the operation state (a2 b3 , N, ff ) assuming the token mode ≥. For that, we must parse ¦ab¦ with (a2 b3 , N \ {0} , ff ) by clause 8 since >−1 (N) = N \ {0}. For that in turn, we must parse ab with (a2 b3 , N \ {0} , tt) by clause 10. By clause 2, we have a, ≥ `G (a2 b3 , N \ {0} , tt) → >(b3 , {2} , ff ) (as 2 ∈ N \ {0}) and b, ≥ `G (b3 , {2} , ff ) → >(ε, {2} , ff ) (as (2, 3) ∈ ≥−1 ). Therefore, by clause 4, ab, ≥ `G (a2 b3 , N \ {0} , tt) → >(ε, {2} , ff ). Finally, ¦ab¦, ≥ `G (a2 b3 , N \ {0} , ff ) → >(ε, {2} , ff ) and > ¦ab¦ , ≥ `G (a2 b3 , N, ff ) → >(ε, {0, 1} , ff ) by clauses 10 and 8. The set {0, 1} in the final state shows that only 0 and 1 are still candidates for the indentation baseline outside the parsed part of the input (before parsing, the candidate set was the whole N). Note that this definition involves circular dependencies. For instance, if δ(X) = X for some X ∈ N then X, τ `G s → o if X, τ `G s → o by clause 3. There is no result of parsing in such cases (not even ⊥). We call this behaviour divergence. H. Nestra 2.2 5 Properties of the semantics Ford [6] proves that parsing in PEG is unambiguous, whereby the consumed part of an input string always is its prefix. Theorem 2.1 below is an analogous result for PEG> . Besides the uniqueness of the result of parsing, it states that if we only consider relations in <+ (N) then the whole operation state in our setting is in a certain sense decreasing during parsing. Denote by ≥ the suffix order of strings (i.e., w ≥ w0 iff w = uw0 for some u ∈ T ∗ ) and by w the implication order of truth values (i.e., tt A ff ). Denote by > the pointwise order on operation states, i.e., (w, I, b) > (w0 , I 0 , b0 ) iff w ≥ w0 , I ⊇ I 0 and b w b0 . I Theorem 2.1. Let G = (N, T, δ, s) be a PEG> , e ∈ EG , τ ∈ <+ (N) and s ∈ State. Then e, τ `G s → o for at most one o, whereby o = >(s0 ) implies s > s0 . Also if s = (w, I, b) and s0 = (w0 , I 0 , b0 ) then s 6= s0 implies both w > w0 and b0 = ff , and I 6= ∅ implies I 0 6= ∅. Proof. By induction on the shape of the derivation tree of the assertion e, τ `G s → o. J Theorem 2.1 enables to observe a common pattern in the semantics of indentation and alignment. Denoting by κ(p) either p ρ or ¦p¦, both clauses 8 and 10 have the following form, parametrized on two mappings α, γ : State → State: For p ∈ EG , κ(p), τ `G s → o holds in two cases: If there exists a state s0 such that p, τ `G α(s) → >(s0 ) and o = >(s ∧ γ(s0 )); If p, τ `G α(s) → ⊥ and o = ⊥. The meanings of indentation and alignment constructs are distinguished solely by α and γ. For many properties, proofs that rely on this abstract common definition can be carried out, assuming that γ is monotone, preserves the largest element and follows together with α the axiom x ∧ γ(y) ≤ γ(α(x) ∧ y). The class of all meet semilattices L with top element, equipped with mappings α, γ satisfying these three conditions, contains identities (i.e., semilattices L with α = γ = idL ) and is closed under compositions (of different α, γ defined on the same semilattice L) and under direct products. If ρ ∈ <+ (N) then the conditions hold for α1 , γ1 : ℘(N) → ℘(N) with α1 (I) = ρ−1 (I), γ1 (I) = ρ(I), similarly in the case if α2 , γ2 : B → B with α2 (b) = tt, γ2 (b) = b. Now the direct product of the identities of T ∗ and B with (α1 , γ1 ) on ℘(N) gives the indentation case, and the direct product of the identities of T ∗ and ℘(N) and the Boolean lattice B with (α2 , γ2 ) gives the alignment case. If α, γ satisfy the conditions then γ(α(x)) ≥ x since x = x∧> = x∧γ(>) ≤ γ(α(x)∧>) = γ(α(x)). Adding dual conditions (α monotone, α(⊥) = ⊥ and α(x) ∨ y ≥ α(x ∨ γ(y))) would make (α, γ) a Galois’ connection. In our cases, the dual axioms do not hold. 2.3 Semantic equivalence I Definition 2.2. Let G = (N, T, δ, s) be a PEG> and p, q ∈ EG . We say that p and q are semantically equivalent in G and denote p ∼G q iff p, τ `G s → o ⇐⇒ q, τ `G s → o for every τ ∈ <+ (N), s ∈ State and o ∈ State + 1. For example, one can easily prove that pε ∼G p ∼G εp, p(qr ) ∼G (pq)r , p/(q/r ) ∼G (p/q)/r , p(q/r ) ∼G pq/pr , p/q ∼G p/!pq for all p, q, r ∈ EG [6]. We are particularly interested in equivalences involving the additional operators of PEG> . In Sect. 3, they will be useful in eliminating alignment and position operators. The following Theorem 2.3 states distributivity laws of the three new operators of PEG> w.r.t. other constructs: I Theorem 2.3. Let G = (N, T, δ, s) be a PEG> . Then: 6 Alignment Elimination from Adams’ Grammars 1. εσ ∼G ε, (pq)σ ∼G p σ q σ , (p/q)σ ∼G p σ /q σ , (!p)σ ∼G !p σ , (p ∗ )σ ∼G (p σ )∗ , (p ρ )σ ∼G (p σ )ρ , ¦p¦σ ∼G ¦p σ ¦ for all σ ∈ <+ (N); 2. ερ ∼G ε, (p/q)ρ ∼G p ρ /q ρ , (!p)ρ ∼G !p ρ , (p σ )ρ ∼G (p ρ )σ for all ρ ∈ <+ (N); 3. ¦ε¦ ∼G ε, ¦p/q¦ ∼G ¦p¦/¦q¦, ¦!p¦ ∼G !¦p¦, ¦p σ ¦ ∼G ¦p¦σ . Proof. The equivalences in claim 1 hold as the token mode steadily distributes to each case of the semantics definition. Those in claims 2 and 3 have straightforward proofs using the joint form of the semantics of indentation and alignment and the axioms of α, γ. J Note that indentation does not distribute with concatenation, i.e., (pq)ρ G p ρ q ρ . This is because (pq)ρ assumes one indentation block with a baseline common to p and q while p ρ q ρ tolerates different baselines for p and q. For example, take p = a ∈ T , q = b ∈ T , let the token mode be 4 and the input state be (a1 b2 , N, ff ) (recall that ai means terminal a occurring in column i). We have a, 4 `G (a1 b2 , N \ {0} , ff ) → >(b2 , {1} , ff ) and b, 4 `G (b2 , {1} , ff ) → ⊥ (since (2, 1) ∈ / 4), therefore ab, 4 `G (a1 b2 , N \ {0} , ff ) → ⊥ > 1 2 and (ab) , 4 `G (a b , N, ff ) → ⊥. On the other hand, a, 4 `G (a1 b2 , N \ {0} , ff ) → >(b2 , {1} , ff ) implies a> , 4 `G (a1 b2 , N, ff ) → >(b2 , {0} , ff ) (since N ∩ (> ({1})) = {0}) and, analogously, b> , 4 `G (b2 , {0} , ff ) → >(ε, {0} , ff ) (since >−1 ({0}) = N \ {0} 3 2 and {0} ∩ (> ({2})) = {0}). Consequently, a> b> , 4 `G (a1 b2 , N, ff ) → >(ε, {0} , ff ). We can however prove the following facts: I Theorem 2.4. Let G = (N, T, δ, s) be a PEG> . 1. Identity indentation law: For all p ∈ EG , p 4 ∼G p. 2. Composition law of indentations: For all p ∈ EG and ρ, σ ∈ <+ (N), (p ρ )σ ∼G p σ◦ρ . ρ 3. Distributivity of indentation and alignment: For all p ∈ EG and ρ ∈ <+ (N), ¦p¦ ∼G ¦p ρ ¦. 4. Idempotence of alignment: For all p ∈ EG , ¦¦p¦¦ ∼G ¦p¦. 5. Cancellation of outer token modes: For all p ∈ EG and σ, τ ∈ <(N), (p σ )τ ∼G p σ . 6. Terminal alignment property: For all a ∈ T , ¦a¦ ∼G a4 . Proof. For claim 1, note that an indentation with the identity relation 4 corresponds to α, γ being identity mappings. Hence   0 0 0  ∃s .p, τ `G s → >(s ) ∧ o = >(s ∧ s )  p 4 , τ `G s → o ⇐⇒ or   p, τ `G s → ⊥ ∧ o = ⊥   0 0 0  ∃s .p, τ `G s → >(s ) ∧ o = >(s )  ⇐⇒ or   p, τ `G s → ⊥ ∧ o = ⊥ ⇐⇒ p, τ `G s → o, where s ∧ s0 can be replaced with s0 because s > s0 by Theorem 2.1. Concerning claims 2–4, let κ1 , κ2 be two constructs whose semantics follow the common pattern of indentation and alignment with mapping pairs (α1 , γ1 ) and (α2 , γ2 ), respectively. Then κ2 (κ1 (p)), τ `G s → o   0 0 0  ∃s .κ1 (p), τ `G α2 (s) → >(s ) ∧ o = >(s ∧ γ2 (s ))  ⇐⇒ or   κ1 (p), τ `G α2 (s) → ⊥ ∧ o = ⊥   00 00 00  ∃s .p, τ `G α1 (α2 (s)) → >(s ) ∧ o = >(s ∧ γ2 (α2 (s) ∧ γ1 (s )))  ⇐⇒ . or   p, τ `G α1 (α2 (s)) → ⊥ ∧ o = ⊥ H. Nestra 7 By monotonicity of γ2 and the fact that s 6 γ2 (α2 (s)), we have s ∧ γ2 (α2 (s) ∧ γ1 (s00 )) 6 s ∧ γ2 (α2 (s)) ∧ γ2 (γ1 (s00 )) = s ∧ γ2 (γ1 (s00 )). By the third axiom of α2 and γ2 , we also have γ2 (α2 (s) ∧ γ1 (s00 )) > s ∧ γ2 (γ1 (s00 )) whence s ∧ γ2 (α2 (s) ∧ γ1 (s00 )) > s ∧ γ2 (γ1 (s00 )). Consequently, s ∧ γ2 (α2 (s) ∧ γ1 (s00 )) can be replaced with s ∧ γ2 (γ1 (s00 )). Hence the semantics of the composition of κ1 and κ2 follows the pattern of semantics of indentation and alignment for mappings α1 ◦α2 and γ2 ◦γ1 . To prove claim 2, it now suffices to observe that the mappings α, γ in the semantics of (·)σ◦ρ equal the compositions of the corresponding mappings for the semantics of (·)ρ and (·)σ . For claim 3, it suffices to observe that the mappings α, γ given for an indentation and for alignment modify different parts of the operation state whence their order of application is irrelevant. Claim 4 holds because the mappings α, γ in the alignment semantics are both idempotent. Finally, claim 5 is trivial and claim 6 follows from a straightforward case study. J Theorems 2.3 and 2.4 enact bringing alignments through all syntactic constructs except concatenation. Alignment does not distribute with concatenation, because in parsing of an expression of the form ¦pq¦, the terminal to be aligned can be in the part of the input consumed by p or (if parsing of p succeeds with consuming no input) by q. Alignment can nevertheless be moved through concatenation if any successful parsing of the first expression in the concatenation either never consumes any input or always consumes some input: I Theorem 2.5. Let G = (N, T, δ, s) be a PEG> and p, q ∈ EG . 1. If p, τ `G s → >(s0 ) implies s0 = s for all τ ∈ <+ (N), s, s0 ∈ State, then ¦pq¦ ∼G ¦p¦¦q¦. 2. If p, τ `G s → >(s0 ) implies s0 6= s for all τ ∈ <+ (N), s, s0 ∈ State, then ¦pq¦ ∼G ¦p¦q. Proof. Straightforward case study. J Theorem 2.5 (1) holds also for indentation (instead of alignment), the same proof in terms of α, γ is valid. Finally, the following theorem states that position and indentation of terminals are equivalent if the alignment flag is false and the token mode is the identity: I Theorem 2.6. Let G = (N, T, δ, s) be a PEG> . Let a ∈ T , σ ∈ <+ (N) and w ∈ T ∗ , I ∈ ℘(N), o ∈ State + 1. Then aσ , 4 `G (w, I, ff ) → o ⇐⇒ aσ , 4 `G (w, I, ff ) → o. Proof. Straightforward case study. 2.4 J Differences of our approach from previous work Our specification of PEG> differs from the definition used by Adams and Ağacan [3] by three essential aspects listed below. The last two discrepancies can be understood as bugs in the original description that have been corrected in the Haskell indentation package by Adams [1]. This package also provides means for locally changing the token mode. All in all, our modifications fully agree with the indentation package. 1. The position operator p σ is missing in [3]. The treatment there assumes just one default token mode applying to the whole grammar, whence token positions deviating from the default must be specified using the indentation operator. The benefits of the position operator were shortly discussed in Subsect. 2.1. 2. According to the grammar semantics provided in [3], the alignment flag is never changed at the end of parsing of an expression of the form ¦p¦. This is not appropriate if p succeeds without consuming any token, as the alignment flag would unexpectedly remain true during parsing of the next token that is out of scope of the alignment operator. The value the alignment flag had before starting parsing ¦p¦ should be restored in this case. This is the purpose of conjunction in the alignment semantics described in this paper. 8 Alignment Elimination from Adams’ Grammars 3. In [3], an alignment is interpreted w.r.t. the indentation baseline of the block that corresponds to the parsing expression to which the alignment operator is applied. Indentation operators occurring inside this expression and processed while the alignment flag is true are neglected. In the semantics described in our paper, raising the alignment flag does not suppress new indentations. Alignments are interpreted w.r.t. the indentation baseline in force at the aligned token site. This seems more appropriate than the former approach where the indentations cancelled because of an alignment do not apply even to the subsequent non-aligned tokens. Distributivity of indentation and alignment fails in the semantics of [3]. Note that alignment of a block nevertheless suppresses the influence of position operators whose scope extend over the first token of the block. Our grammar semantics has also two purely formal deviations from the semantics used by Adams and Ağacan [3] and Ford [6]. 1. We keep track of the rest of the input in the operation state while both [3, 6] expose the consumed part of the input instead. This difference was introduced for simplicity and to achieve uniform decreasing of operation states in Theorem 2.1. 2. We do not have explicit step counts. They were used in [6] to compose proofs by induction. We provide analogous proofs by induction on the shape of derivation trees. 3 Elimination of alignment and position operators Adams [2] describes alignment elimination in the context of CFGs. In [3], Adams and Ağacan claim that alignment elimination process for PEGs is more difficult due to the lookahead construct. To our knowledge, no concrete process of semantics-preserving alignment elimination is described for PEGs before. We provide one below for well-formed grammars. We rely on the existence of position operators in the grammar; this is not an issue since we also show that position operators can be eliminated from alignment-free grammars. 3.1 Approximation semantics and well-formed expressions For defining well-formedness, we first need to introduce approximation semantics that consists of assertions of the form e *G n where e ∈ EG and n ∈ {−1, 0, 1}. This semantics is a decidable extension of the predicate that tells whether parsing of e may succeed with consuming no input (result 0), succeed with consuming some input (result 1) or fail (result −1). No particular input strings, indentation sets etc. are involved, whence the semantics is not deterministic. The following set of clauses define the approximation semantics inductively. ε *G 0. For every a ∈ T , a *G 1 and a *G −1. For every X ∈ N , X *G n if δ(X) *G n. For every p, q ∈ EG , pq *G n holds in four cases: p *G 0, q *G 0 and n = 0; There exist n0 , n00 ∈ {0, 1} such that p *G n0 , q *G n00 , 1 ∈ {n0 , n00 } and n = 1; There exists n0 ∈ {0, 1} such that p *G n0 , q *G −1 and n = −1; p *G −1 and n = −1. 5. For every p, q ∈ EG , p/q *G n holds in two cases: p *G n and n ∈ {0, 1}; p *G −1 and q *G n. 6. For every p ∈ EG , !p *G n holds in two cases: 1. 2. 3. 4. H. Nestra 7. 8. 9. 10. 9 p *G −1 and n = 0; There exists n0 ∈ {0, 1} such that p *G n0 and n = −1. For every p ∈ EG , p ∗ *G n holds in two cases: p *G −1 and n = 0; p *G −1, p *G 1 and n = 1. For every p ∈ EG and ρ ∈ <(N), p ρ *G n if p *G n. For every p ∈ EG and σ ∈ <(N), p σ *G n if p *G n. For every p ∈ EG , ¦p¦ *G n if p *G n. On the PEG constructs (1–7), our definition basically copies that given by Ford [6], except for the case p ∗ *G 1 where our definition requires p *G −1 besides p *G 1. This is sound since if parsing of p never fails then parsing of p ∗ cannot terminate. The difference does not matter in the grammar transformations below as they assume repetition-free grammars. I Theorem 3.1. Let G = (N, T, δ, s) be a PEG> . Assume that e, τ `G s → o for some τ ∈ <(N) and s ∈ State, o ∈ State + 1. Then: 1. If o = >(s) then e *G 0; 2. If o = >(s0 ) for some s0 6= s then e *G 1; 3. If o = ⊥ then e *G −1. Proof. By induction on the shape of the derivation tree of the assertion e, τ `G s → o. J Well-formedness is a decidable conservative approximation of the predicate that is true iff parsing in G never diverges (it definitely excludes grammars with left recursion but can exclude also some safe grammars). Well-formedness of PEGs was introduced by Ford [6]. The following set of clauses is an inductive definition of predicate WF G , well-formedness of expressions, for PEG> : 1. ε ∈ WF G ; 2. For every a ∈ T , a ∈ WF G ; 3. For every X ∈ N , X ∈ WF G if δ(X) ∈ WF G ; 4. For every p, q ∈ EG , pq ∈ WF G if p ∈ WF G and, in addition, p *G 0 implies q ∈ WF G ; 5. For every p, q ∈ EG , p/q ∈ WF G if p ∈ WF G and, in addition, p *G −1 implies q ∈ WF G ; 6. For every p ∈ EG , !p ∈ WF G if p ∈ WF G ; 7. For every p ∈ EG , p ∗ ∈ WF G if p 6*G 0 and p ∈ WF G ; 8. For every p ∈ EG and ρ ∈ <+ (N), p ρ ∈ WF G if p ∈ WF G ; 9. For every p ∈ EG and σ ∈ <+ (N), p σ ∈ WF G if p ∈ WF G ; 10. For every p ∈ EG , ¦p¦ ∈ WF G if p ∈ WF G . This definition rejects non-terminals with directly or indirectly left recursive rules since for a concatenation pq to be well-formed, p must be well-formed, leading to an infinite derivation in the case of any kind of left recursion. On the other hand, requiring both p ∈ WF G and q ∈ WF G in the clause for pq ∈ WF G would be too restrictive since this would reject non-terminals with meaningful recursive productions like X 7→ aX/ε. Again, clauses for PEG constructs (1–7) mostly copy the definition given by Ford [6]. This time, the choice case is an exception. In [6], p/q is considered well-formed only if both p and q are well-formed, which needlessly rejects non-terminals with safe recursive rules like X 7→ ε/X. We require q ∈ WF G only if q could possibly be executed, i.e. if p *G −1. A grammar G = (N, T, δ, s) is called well-formed if p ∈ WF G for every expression p occurring as a subexpression in some δ(X) or s. Ford [6] proves by induction on the length 10 Alignment Elimination from Adams’ Grammars of the input string that, in well-formed grammars, parsing of every expression whose all subexpressions are well-formed terminates on every input string. We can prove an analogous result in a similar way but we prefer to generalize the statement to a stricter semantics which enables to occasionally construct easier proofs later. The new semantics, which we call strict, is defined by replacing the choice clause in the definition of Subsect. 2.1 with the following: 5. For every p, q ∈ EG , p/q, τ `G s → o holds in two cases: There exists a triple s0 such that p, τ `G s → >(s0 ), o = >(s0 ) and, in addition, p *G −1 implies q, τ `G s → o0 for some o0 ∈ State + 1; p, τ `G s → ⊥ and q, τ `G s → o. The new semantics is more restrictive since, to finish parsing of an expression of the form p/q after parsing p successfully, also q must be parsed if p *G −1 happens to be the case. In the standard semantics, parsing of p/q does not have to try q if parsing of p is successful. So, if parsing of an expression terminates in the strict semantics then it terminates with the same result in the standard semantics (but not necessarily vice versa). Therefore proving that parsing always gives a result in the strict semantics will establish this also for the standard semantics. In the rest, we sign strict semantics with exclamation mark, i.e., parsing assertions will be of the form e, τ `! G s → o. I Theorem 3.2. Let G = (N, T, δ, s) be a well-formed PEG> and let e ∈ EG . Assume that all subexpressions of e are well-formed. Then for every τ ∈ <+ (N) and s ∈ State, there exists o ∈ State + 1 such that e, τ `! G s → o. Proof. By induction on the length of the input string (i.e., the first component of s). The induction step uses induction on the shape of the derivation tree of the assertion e ∈ WF G . J 3.2 Splitting As the repetition operator can always be eliminated (by adding a new non-terminal Ap with δ(Ap ) = pAp /ε for each subexpression p that occurs under the star operator), we may assume that the input grammar G is repetition-free. The first stage of our process also assumes that G is well-formed, all negations are applied to atomic expressions, and all choices are disjoint. A choice expression p/q is called disjoint if parsing of p and q cannot succeed in the same input state and token mode. Achieving the last two preconditions can be considered as a preparatory and previously studied (e.g. in [6] as stage 1 of negation elimination) step of the process. Issues concerning this are discussed briefly in Subsect. 3.5. We use in principle the same splitting algorithm as in stage 2 of the negation elimination process described by Ford [6], adding clauses for the extra operators in PEG> . The approach defines two functions γ0 : WF G → EG and γ1 : EG → EG as follows (F is a metavariable denoting any expression that always fails, e.g., !ε): γ0 (ε) γ0 (a) γ0 (X) γ0 (pq) γ0 (p/q) γ0 (!p) γ0 (p ρ ) γ0 (p σ ) γ0 (¦p¦) =ε = F = γ0 (δ(X))   γ0 (p)γ0 (q) if p *G 0 = F otherwise   γ0 (p)/γ0 (q) if p *G −1 = γ0 (p) otherwise = !(γ1 (p)/γ0 (p)) = (γ0 (p))ρ = (γ0 (p))σ = ¦γ0 (p)¦ γ1 (ε) γ1 (a) γ1 (X) =F = a =X γ1 (pq) = γ1 (p)γ1 (q)/γ1 (p)γ0 (q)/γ0 (p)γ1 (q)   γ1 (p)/γ1 (q) if p *G −1 γ1 (p/q) = γ1 (p) otherwise γ1 (!p) = F γ1 (p ρ ) = (γ1 (p))ρ γ1 (p σ ) = (γ1 (p))σ γ1 (¦p¦) = ¦γ1 (p)¦ H. Nestra 11 Correctness of the definition of γ0 follows by induction on the shape of the derivation tree of the assertion e ∈ WF G . In the negation case, we use that negations are applied to atomic expressions, whence the reference to γ1 can be eliminated by a replacement from its definition. The definition of γ1 is sound by induction on the shape of the expression e. A new grammar G0 = (N, T, δ0 , s 0 ) is defined using γ0 , γ1 by equations δ0 (X) = γ1 (δ(X)), 0 s = γ1 (s)/γ0 (s). The equivalence of the input and output grammars relies on the splitting invariant established by Theorem 3.3 below which allows instead of each parsing expression e with negations in front of atoms and disjoint choices in G to equivalently use parsing expression γ1 (e)/γ0 (e) in G0 . The claim is analogous to the splitting invariant used by [6] but we can provide a simpler proof using the strict semantics (an analogous proof using the standard semantics would fail in the choice case). I Theorem 3.3. Let e, τ `G s → o where e ∈ EG , τ ∈ <+ (N) and s ∈ State, o ∈ State + 1. Assuming that all choices in the rules of G and expression e are disjoint and the negations are applied to atoms, the following holds: 1. If o = >(s) then γ0 (e), τ `G0 s → >(s) and γ1 (e), τ `G0 s → ⊥; 2. If o = >(s0 ) where s0 6= s then γ0 (e), τ `G0 s → ⊥ and γ1 (e), τ `G0 s → >(s0 ); 3. If o = ⊥ then γ0 (e), τ `G0 s → ⊥ and γ1 (e), τ `G0 s → ⊥. Proof. We don’t use the repetition operator, whence all expressions in well-formed grammars are well-formed (this fact follows from an easy induction on the expression structure). By Theorems 3.2 and 2.1, e, τ `! G s → o. The desired result follows by induction of the shape of the derivation tree of e, τ `! G s → o, using the disjointness assumption in the choice case. J As the result of this transformation, the sizes of the right-hand sides of the productions can grow exponentially though the number of productions stays unchanged. Preprocessing the grammar via introducing new non-terminals in such a way that all concatenations were applied to atoms (similarly to Ford [6]) would hinder the growth, but the size in the worst case remains exponential. The subsequent transformations cause at most a linear growth of right-hand sides. 3.3 Alignment elimination In a grammar G = (N, T, δ, s) obtained via splitting, we can eliminate alignments using the following three steps: 1. Introduce a copy X 0 of each non-terminal X and define δ(X 0 ) = ¦δ(X)¦. 2. In all right-hand sides of productions and the start expression, apply distributivity laws (Theorem 2.3 (3), Theorem 2.4 (3), Theorem 2.5) and idempotence (Theorem 2.4 (4)) to bring all alignment operators down to terminals and non-terminals. Replace alignment of terminals by position (Theorem 2.4 (6)). 3. In all right-hand sides of productions and the start expression, replace all subexpressions of the form ¦X¦ with the corresponding new non-terminal X 0 . For establishing the equivalence of the original and the obtained grammar, the following general theorem can be used. I Theorem 3.4. Let G1 = (N, T, δ1 , s 1 ) and G2 = (N, T, δ2 , s 2 ) be PEG> s. If for every X ∈ N , δ1 (X) ∼G1 δ2 (X) then e, τ `G2 s → o always implies e, τ `G1 s → o. Proof. Easy induction on the shape of the derivation tree of e, τ `G2 s → o. J 12 Alignment Elimination from Adams’ Grammars Denote by φ the function defined on EG that performs transformations of steps 2–3, i.e., distributes alignment operators to the non-terminals and replaces aligned non-terminals with corresponding new non-terminals. Denote by G0 the grammar obtained after step 3. Note that step 1 does not change the semantics of expressions written in the original grammar. Steps 2 and 3 replace the right-hand sides of productions with expressions that are semantically equivalent with them in the grammar obtained after step 1. By Theorem 3.4, this implies that whenever parsing of some e ∈ EG in the final grammar G0 produces some result then the same result is obtained when parsing e with the same input state and token mode in the original grammar G. In order to be able to apply Theorem 3.4 with grammars interchanged, we need the equivalence of the right-hand sides of productions also in grammar G0 . For this, it is sufficient to show ¦X¦ ∼G0 X 0 for every X ∈ N , which in turn would follow from the statement ¦φ(δ(X))¦ ∼G0 φ(¦δ(X)¦). Consequently, the equivalence of the initial and final grammars is implied by the following theorem. I Theorem 3.5. For every e ∈ EG , φ(¦e¦) ∼G0 ¦φ(e)¦. Proof. The claim is a direct consequence of the following two lemmas, both holding for arbitrary s ∈ State, o ∈ State + 1: If φ(¦e¦), τ `G0 s → o then ¦φ(e)¦, τ `G0 s → o and ¦φ(¦e¦)¦, τ `G0 s → o; If ¦φ(e)¦, τ `G0 s → o or ¦φ(¦e¦)¦, τ `G0 s → o then φ(¦e¦), τ `G0 s → o. Both lemmas are proven by induction on the shape of derivation trees. The assertion with two alignments (both outside and inside) is needed in the case where e itself is of the form ¦p¦. J 3.4 Elimination of position operators In an alignment-free PEG> G = (N, T, δ, s), we can get rid of position operations using a process largely analogous to the alignment elimination, consisting of the following four steps: 1. Introduce a new non-terminal hX, τi for each existing non-terminal X and relation τ used by a position operator, with δ(hX, τi) = (δ(X))τ . 2. Apply distributivity laws (Theorem 2.3 (1)) and cancellation (Theorem 2.4 (5)) to bring all position operators down to terminals and non-terminals. 3. Replace all subexpressions of the form Xτ with corresponding new non-terminals hX, τi. 4. Replace all subexpressions of the form aτ with aτ . Again, denote by φ the function defined on EG that performs transformations of steps 2–3, i.e., distributes position operators to the terminals and non-terminals and replaces non-terminals under position operators with corresponding new non-terminals. Denote by G0 the grammar obtained after step 3. Theorem 3.4 applies here as well, whence the equivalence of the grammar obtained after step 3 and the initial grammar is implied by the following Theorem 3.6. I Theorem 3.6. For every e ∈ EG and σ ∈ <+ (N), φ(e σ ) ∼G0 (φ(e))σ . Proof. The claim is a direct consequence of the following two lemmas, both holding for arbitrary s ∈ State, o ∈ State + 1 and τ, υ ∈ <+ (N): If φ(e σ ), τ `G0 s → o then (φ(e))σ , τ `G0 s → o and (φ(e σ ))υ , τ `G0 s → o; If (φ(e))σ , τ `G0 s → o or (φ(e σ ))υ , τ `G0 s → o then φ(e σ ), τ `G0 s → o. Both lemmas are proven by induction on the shape of the derivation trees. The claim with position operator both outside and inside ((φ(e σ ))υ ) is needed in the case when e itself is an application of the position operator. J H. Nestra Correctness of step 4 can be proven by induction on the shape of the derivation trees, using Theorem 2.6. Note that here we must assume that parsing according to the final grammar is performed with the alignment flag false (a natural assumption as the grammar is alignment-free) and the token mode 4. 3.5 Discussion on the preconditions Alignment elimination was correctly defined under the assumption that the input grammar is well-formed, has negations only in front of atoms, and disjoint choices (all these conditions are needed at stage 1 only). The second assumption can be easily established by introducing a new non-terminal for each expression p such that !p occurs in the productions or in the start expression. This can be done in the lines of the first stage of the negation elimination process described by Ford [6]. This transformation preserves well-formedness of the grammar. Achieving disjoint choices is a more subtle topic. A straightforward way would be replacing choices of the form p/q with disjoint choices p/!pq which seems to work well as p/q and p/!pq are equivalent in the standard semantics. Alas, p/q and p/!pq are not equivalent in the approximation semantics, because if p *G 1, p *G −1, q *G 0 but q 6*G −1, then p/!pq *G −1 while p/q 6*G −1. Due to this, replacing p/q with p/!pq can break well-formedness. Take X ∈ N such that δ(X) =!(a/ε)X. Then X ∈ WF G due to !(a/ε) ∈ WF G alone, no recursive call to X ∈ WF G arises as !(a/ε) 6*G 0. However, if δ0 (X) =!(a/!aε)X in G0 then !(a/!aε) *G0 0 whence well-formedness of X now recursively requires well-formedness of X. Thus X ∈ / WF G0 . (An argument similar to this shows that the first stage of the negation elimination process in Ford [6] also can break well-formedness. As the second stage is correctly defined only for well-formed grammars, the whole process fails.) One solution would be changing the approximation semantics by adding, to the inductive definition in Subsect. 3.1, a general clause 0. e *G −1 if e *G 0 or e *G 1. This forces e *G −1 to hold whenever an assertion of the form e *G n holds, and in particular, p/q becomes equivalent to p/!pq. Then replacing p/q with p/!pq preserves well-formedness. Although well-formedness predicate becomes more restrictive and rejects more safe grammars, the loss seems to be little and acceptable in practice (expressions q such that q *G 0 or q *G 1 while q 6*G −1 seem to occur not very commonly in influenced productions such as X 7→!(p/q)X, but a further investigation is needed to clarify this). 4 Related work PEGs were first introduced and studied by Ford [6] who also showed them to be closely related with the TS system [5] and TDPL [4], as well as to their generalized forms [5, 4]. Adams [2] and Adams and Ağacan [3] provide an excellent overview of previous approaches to describing indentation-sensitive languages and attempts of building indentation features into parser libraries. Our work is a theoretical study of the approach proposed in [3] while some details of the semantics used in our paper were “corrected” in the lines of Adams’ indentation package for Haskell [1]. This package enables specifying indentation sensitivity within the Parsec and Trifecta parser combinator libraries. A process of alignment operator elimination is previously described for CFGs by Adams [2]. Matsumura and Kuramitsu [7] develop a very general extension of PEG that also enables to specify indentation. Their framework is powerful but complicated. The approach proposed 13 14 Alignment Elimination from Adams’ Grammars in [3] and followed by us is in contrast with [7] by focusing on indentation and aiming to maximal simplicity and convenience of usage. 5 Conclusion We studied the extension of PEG proposed by Adams and Ağacan [3] for indentationsensitive parsing. This extension uses operators for marking indentation and alignment besides the classic ones. Having added one more operator (position) for convenience, we found a lot of useful semantic equivalences that are valid on expressions written in the extended grammars. We applied these equivalences subsequently for defining a process that algorithmically eliminates all alignment and position operators from well-formed grammars. References 1 2 3 4 5 6 7 8 Michael D. Adams. The indentation package. URL: http://hackage.haskell.org/ package/indentation. Michael D. Adams. Principled parsing for indentation-sensitive languages: Revisiting Landin’s offside rule. In Roberto Giacobazzi and Radhia Cousot, editors, The 40th Annual ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages, POPL ’13, Rome, Italy - January 23 - 25, 2013, pages 511–522. ACM, 2013. URL: http://doi.acm.org/10.1145/2429069.2429129, doi:10.1145/2429069.2429129. Michael D. Adams and Ömer S. Ağacan. Indentation-sensitive parsing for Parsec. In Wouter Swierstra, editor, Proceedings of the 2014 ACM SIGPLAN symposium on Haskell, Gothenburg, Sweden, September 4-5, 2014, pages 121–132. ACM, 2014. URL: http://doi. acm.org/10.1145/2633357.2633369, doi:10.1145/2633357.2633369. Alfred V. Aho and Jeffrey D. Ullman. The Theory of Parsing, Translation, and Compiling. Prentice-Hall, Inc., Upper Saddle River, NJ, USA, 1972. Alexander Birman and Jeffrey D. Ullman. Parsing algorithms with backtrack. Information and Control, 23(1):1–34, 1973. URL: http://dx.doi.org/10.1016/S0019-9958(73) 90851-6, doi:10.1016/S0019-9958(73)90851-6. Bryan Ford. Parsing expression grammars: A recognition-based syntactic foundation. In Neil D. Jones and Xavier Leroy, editors, Proceedings of the 31st ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages, POPL 2004, Venice, Italy, January 14-16, 2004, pages 111–122. ACM, 2004. URL: http://doi.acm.org/10.1145/964001. 964011, doi:10.1145/964001.964011. Tetsuro Matsumura and Kimio Kuramitsu. A declarative extension of parsing expression grammars for recognizing most programming languages. JIP, 24(2):256–264, 2016. URL: http://dx.doi.org/10.2197/ipsjjip.24.256, doi:10.2197/ipsjjip.24.256. Sérgio Medeiros, Fabio Mascarenhas, and Roberto Ierusalimschy. Left recursion in parsing expression grammars. In Francisco Heron de Carvalho Junior and Luís Soares Barbosa, editors, Programming Languages - 16th Brazilian Symposium, SBLP 2012, Natal, Brazil, September 23-28, 2012. Proceedings, volume 7554 of Lecture Notes in Computer Science, pages 27–41. Springer, 2012. URL: http://dx.doi.org/10.1007/978-3-642-33182-4_4, doi:10.1007/978-3-642-33182-4_4.
6 (cs.PL)
Bridging Static and Dynamic Program Analysis using Fuzzy Logic Jacob Lidman & Josef Svenningsson Chalmers University of Technology {lidman, josefs}@chalmers.se Static program analysis is used to summarize properties over all dynamic executions. In a unifying approach based on 3-valued logic properties are either assigned a definite value or unknown. But in summarizing a set of executions, a property is more accurately represented as being biased towards true, or towards false. Compilers use program analysis to determine benefit of an optimization. Since benefit (e.g., performance) is justified based on the common case understanding bias is essential in guiding the compiler. Furthermore, successful optimization also relies on understanding the quality of the information, i.e. the plausibility of the bias. If the quality of the static information is too low to form a decision we would like a mechanism that improves dynamically. We consider the problem of building such a reasoning framework and present the fuzzy data-flow analysis. Our approach generalize previous work that use 3-valued logic. We derive fuzzy extensions of data-flow analyses used by the lazy code motion optimization and unveil opportunities previous work would not detect due to limited expressiveness. Furthermore we show how the results of our analysis can be used in an adaptive classifier that improve as the application executes. 1 Introduction How can one reconcile static and dynamic program analysis? These two forms of analysis complement each other: static analysis summarizes all possible runs of a program and thus provide soundness guarantees, while dynamic analysis provides information about the particular runs of a program which actually happen in practice and can therefore provide more relevant information. Being able to combine these two paradigms has applications on many forms on analyses, such as alias analysis [15, 19] and dependence analysis [17]. Compilers use program analysis frameworks to prove legality as well as determining benefit of transformations. Specifications for legality are composed of safety and liveness assertions (i.e. universal and existentially quantified properties), while specifications for benefit use assertions that hold in the common case. This reason for adopting the common case is that few transformations improve performance in general (i.e., for every input, environment). Similarly most transformations could potentially improve performance in a least one case. As such, compiler optimizations are instead motivated based on (an approximation of) the majority case, i.e. the (weighted) mean. While determining legality has improved due to advances in the verification community the progress in establishing benefit has been slow. In this paper we introduce fuzzy data-flow analysis, a framework for static program analysis based on fuzzy logic. The salient feature of our framework is that it can naturally incorporate dynamic information while still being a static analysis. This ability comes thanks to a shift from “crisp” sets where membership is binary, as employed in conventional static analysis, to fuzzy sets where membership is gradual. De Vink and Wiklicky (Eds.): QAPL 2017 EPTCS 250, 2017, pp. 111–126, doi:10.4204/EPTCS.250.7 © J. Lidman & J. Svenningsson This work is licensed under the Creative Commons Attribution License. 112 Bridging Static and Dynamic Program Analysis using Fuzzy Logic We make the following contributions: • Section 3 introduces our main contribution, the fuzzy data-flow framework. • Section 4 demonstrates the benefit of our framework by presenting a generalization of a wellknown code motion algorithm and we show how this generalization provides new opportunities for optimizations previous approaches would not discover. • Section 4 shows how fuzzy logic can benefit program analysis by (1) using second-order fuzzy sets to separate uncertainty in data-flow and control-flow and hence improve an inter-procedural analysis and (2) using fuzzy regulators to refine the results of our static analysis, hence improving the precision dynamically. 2 Preliminaries We introduce and define fuzzy sets and the operators that form fuzzy logic. These concepts will be used in Section 3 to define the transfer functions of our data-flow analysis. 2.1 Fuzzy set Elements of a crisp set1 are either members or non-members w.r.t to a universe of discourse. A fuzzy set (FS) instead allow partial membership denoted by a number from the unit interval [0, 1]. The membership degree typically denotes vagueness. The process to convert crisp membership to fuzzy grades is called fuzzification and the inverse is called defuzzification. Following Dubois et al. [8, 7] let S be a crisp set and µ : S 7→ [0, 1] a membership function (MF) then hS, µi is a fuzzy set. As a convention, if S is understood from context we sometimes refer to µ as a fuzzy set. The membership function formalizes the fuzzification. Fuzzy sets are ordered point-wise, i.e. (S, µA ) ≤ (S, µB ) ⇔ ∀s ∈ S : µA (s) ≤ µB (s). We can accommodate some notion about uncertainty of vagueness by considering a type-2 fuzzy set where the membership degree itself is a fuzzy set. Type-2 FS (T2FS) membership functions are composed of a primary (Js ) and secondary (µ) membership {h(s, u), µ(s, u)i | s ∈ S, u ∈ Js ⊆ [0, 1]}. Here uncertainty is represented by the secondary membership that define the possibility of the primary membership. When for each x and u, it holds µ(x, u) = 1 the T2FS is called an interval T2FS. Gehrke et al. [9] showed that this can equivalently be described as an interval valued fuzzy sets (IVFS) where µ : S → {[l, u] |⊥ ≤ l ≤ u ≤ > }. IVFS are a special case of lattice valued fuzzy sets (L-fuzzy sets) where the membership domain forms a lattice over [0, 1]. Defuzzification of T2FS often proceeds in two phases. The first phase applies type reduction to transform the T2FS to a type-1 FS (T1FS). The second phase then applies a type-1 defuzzification. 2.2 Fuzzy logic Fuzzy logic defines many-valued formal systems to reason about truth in the presence of vagueness. Contrary to classical logic the law of excluded middle (p ∨ ¬p = >) and the law of non-contradiction (p ∧ ¬p = ⊥) does not, in general, hold for these systems. Fuzzy logic uses T-, S- and C- norms to ˜ ∨, ˜ ¬i ˜ 2 which generalize the logical operators ∧, ∨ and ¬. We compactly represent a fuzzy logic by h∧, is sometimes called a De Morgan system [8] because it satisfies a generalization of De Morgans laws: ˜ Q) ⇔ ¬ ˜¬ ˜ Q) ⇔ ¬ ˜¬ ¬(P ˜ ∧ ˜ P∨ ˜ Q and ¬(P ˜ ∨ ˜ P∧ ˜ Q. 1 In the context of fuzzy logic, crisp or Boolean set refer to a classical set to avoid confusion with fuzzy sets. one would expect the definition of a fuzzy logic to include a “fuzzy implication” operator in this work we do not consider it. 2 Although J. Lidman & J. Svenningsson 113 1 2 3 Fuzzy logic Min-Max Algebraic Sum-product Lukasiewicz 4 Nilpotent T-norm min(x, y) xy max(x + y − 1, 0) ( min(x, y) x + y > 1 0 otherwise S-norm max(x, y) x + y − xy min(x + y, 1) ( max(x, y) x + y < 1 1 otherwise C-norm 1−x 1−x 1−x 1−x Table 1: Common instantiations of fuzzy logics Definition 1. Let U be a binary function [0, 1]2 → [0, 1] that is commutative, associative and increasing and has an identity element e ∈ [0, 1]. If e = 1 then U is a Triangular norm (T-norm) and if e = 0 then U is a Triangular conorm (S-norm)3 . Definition 2. A C-norm is a unary function n : [0, 1] → [0, 1] that is decreasing, involutory (i.e., n(n(x)) = x) with boundary conditions (i.e, n(0) = 1, n(1) = 0). Standard examples of fuzzy logics are shown in Table 1 [8, 7]. Examples 1-3 are special cases (and limits) of the Frank family of fuzzy logics that are central to our work and formally defined in Definition 3. Definition 3. Let  s ∈ [0, 1] ∪ {∞} then the Frank family of T-norms is defined by:  min(x, y) s=0    xy s=1 T s (x, y) = max(x    + y − 1, 0)  s = ∞   log 1 + (sx −1)(sy −1) otherwise s s−1 The set of intervals in [0, 1] forms a bounded partial order hI, v, >, ⊥i4 where [lx , ux ] ≤ [ly , uy ] ⇔ (lx ≤ ly ) ∧ (ux ≤ uy ) , > = [1, 1] and ⊥ = [0, 0]. As per Gehrke et al. [9] we can point-wise lift a T1FS fuzzy logic ˜ ∨, ˜ ¬i ˜ ∨} ˜ and ¬[l, h∧, ˜ to a IVFS fuzzy logic, i.e., [lx , ux ] [ly , uy ] = [lx ly , ux uy ], ˆ ∈ {∧, ˜ u] = [¬ ˜ u, ¬ ˜ l]. 3 Fuzzy data-flow analysis Static data-flow analyses deduce values of semantic properties that are satisfied the dynamics of the application. The dynamics is formalized as a system of monotone transfer functions and collector functions. Transfer functions describe how blocks alter the semantic properties. Collectors functions merge results from different, possibly mutual exclusive, branches of the application. The solution of the analysis is obtained through Kleene iteration and is a unique fixed-point of the system of equations. In a classical framework the domain of the values is binary, i.e. either true (1) or false (0). The interpretation of these values depends on the type of analysis. The value true means that the property can possibly hold in a may-analysis (i.e., it is impossible that the value is always false) while it means that the property always holds in a must-analysis. The value false could mean either the opposite of true or that the result is inconclusive. Our fuzzy data-flow analysis instead computes the partial truth of the property, i.e. values are elements of [0, 1]. A value closer to 0 means that the property is biased towards false and vice versa. Furthermore the transfer functions are logical formulas from a Frank family fuzzy logic and the collector 3 The general concept, allowing any e ∈ [0, 1], is called a uninorm [8] and is either orlike (i.e., U(0, 1) = U(1, 0) = 1) or andlike (i.e., U(0, 1) = U(1, 0) = 0). Our work does not require the full generality. 4 This should not be confused with the partial order used in the interval abstraction. 114 Bridging Static and Dynamic Program Analysis using Fuzzy Logic functions are weighted average functions where the constant α is determined prior to performing the analysis. In contrast to the classical framework Kleene iteration proceeds until the results differ by a constant ε which is the maximal error allowed by the solution. The error can be made arbitrarily small. This section introduces the fuzzy data-flow framework and we prove termination using continuity properties and Banach’s fixed-point theorem. Section 4 then presents an example analysis to demonstrate the benefit of the framework. The analysis is performed on a weighted flow-graph G = hV, E, αi where V is a set of logical formulas (denoting the transfer function of each block), E ⊆ V × V is a set of edges (denoting control transfers) and αe ∈ [0, 1] denotes the normalized contribution for each edge e. As a running example we will use Figure 1 (left) which shows a flow-graph with four nodes and their corresponding logical formula. The flow graph has four control edges denoting contributions between nodes. For instance, Block 1 (B1) receives 0.1 of its contribution from B0 and 0.9 from B2, i.e. αhB0,B1i = 0.1 and αhB2,B1i = 0.9. B0 Out = 0.0 0.1 B1 Out = In 1.0 0.9 1.0 Out = In  Out(B0) = 0.0     Out(B1) = 0.1Out(B0) + 0.9Out(B2)  Out(B2) = min (0.8, max(1 − Out(B1), 0.3))    Out(B3) = Out(B1) B3 Out = 0.8 ∧ (¬In ∨ ¬0.7) B2 Figure 1: Example flow-graph (left) and its corresponding equation system (middle) and the analysis result and error as a function of iteration (right) Definition 4. Let P be a finite set of properties and V S : P 7→ [0, 1] a valuation for each property. We use [[φ ]] (V S) to denote the interpretation of the fuzzy formula φ given a V S. Given a flow-graph G = hV, E, αi with a unique start node vstart the map GS : V 7→ V S describes the value of each property at each node and a fuzzy data-flow analysis is a Kleene iteration of F : GS 7→ GS: S(vstart ) v = vstart F(S) = λ v.  ∑ αhw,vi [[v]] (S(w)) otherwise hw,vi∈E Figure 1 (middle) shows the equation system, as implied by Definition 4, interpreted in a min-max fuzzy logic for the example flow-graph. The red colored text corresponds to the collector function, i.e. the weighted average, and the normal text is the interpretation of the logical formula. In order to prove termination of a fuzzy analysis we need to introduce a continuity property. Definition 5. A function f : [0, 1]n 7→ [0, 1] is K-Lipschitz continuous5 iff ∀x, h : | f (~x −~h) − f (~x)|1 ≤ K|~h|1 . Where |~x|1 is l1 -norm (i.e., the absolute value) of ~x6 . If 0 ≤ K < 1 then f is called a contraction mapping and if 0 ≤ K ≤ 1 then f is called a non-expansive mapping. In a sequence of applications of a contraction mapping the difference between two consecutive applications will decrease and in the limit reach zero. By imposing a bounded error we guarantee that this 5 Our definition restricts the domain and metric of both metric spaces (i.e., for the domain and co-domain of f ) compared to the more general, and common, definition of a Lipschitz continuous function. 6 Other l -norms can be used but only if we restrict the logic to the min-max fuzzy logic [14]. p J. Lidman & J. Svenningsson 115 sequence terminates in a bounded amount of time. The analysis error and result of B2 as a function of iteration for the example is shown in Figure 1 (right). Note that the error (red line) is decreasing and the value of B2 (blue line) tends towards a final value. We next proceed to prove that any fuzzy data-flow analysis iteratively computes more precise results and terminates in a bounded amount of time for a finite maximum error 21q from some q ∈ N − {0}. We let [0, 1]q denote the maximal congruence set of elements from [0, 1] that are at least 21q apart, i.e. [0, 1]q = { 2iq | 0 ≤ i ≤ 2q }. The set of intervals on [0, 1], i.e. I are defined analogously. For this we prove the non-expansive property of fuzzy formulas. Theorem 1. Let x, y,C, wi ∈ [0, 1]q , for some i ∈ N, fi (~x) : [0, 1]nq 7→ [0, 1]q be 1-Lipschitz and gi (~x) : [0, 1]nq 7→ [0, 1]q be Ki -Lipschitz. • Functions x + y, x − y, xy, min(x, y) and abs(x) are 1-Lipschitz. Constants are 0-Lipschitz. N−1 x) is 1-Lipschitz. • If ∑N−1 i=0 wi = 1 then ∑i=0 wi f i (~ • The composition ga ◦ gb is Ka Kb -Lipschitz. Finally, • Formulas defined in a Frank family Fuzzy logic are 1-Lipschitz. • If F : Inq → Iq satisfies ∀x ∈ Inq : y ∈ x ⇒ f (y) ∈ F(x) then F is 1-Lipschitz. In summary, as per Theorem 1: • Transfer functions in a Frank family fuzzy logic are non-expansive mappings. • S(vstart ) is constant and hence a contraction mapping. • The composition of 1) Two non-expansive functions is a non-expansive function and 2) A nonexpansive and a contraction function is a contraction function. As the analysis is performed on the unit interval which together with the l1 -norm forms a complete metric space we can guarantee termination by Banach’s fixed-point theorem. Theorem 2 (Banach fixed-point theorem). Let (X, d) be a complete metric space and f : X 7→ X a contraction. Then f has a unique fixed-point x∗ in X. This concludes our development of fuzzy data-flow analysis. 4 Lazy code motion Improving performance often means removing redundant computations. Computations are said to be fully redundant, but not dead, if the operands at all points remain the same. For two such computations it is enough to keep one and store away the result for later. We can eliminate this redundancy using (global) common sub-expression elimination (GCSE). Furthermore a computation that does not change on some paths is said to be partially redundant. Loop invariant code motion (LICM) finds partially redundant computations inside loops and move these to the entry block of the loop. Lazy code motion is a compiler optimization that eliminate both fully and partially redundant computations, and hence subsumes both CSE and LICM. Knoop-Rüthing-Steffen (KRS) algorithm [12, 6] performs LCM in production compilers such as GCC when optimizing for speed. 116 Bridging Static and Dynamic Program Analysis using Fuzzy Logic B0 v o i d diffPCM ( ) { b = 0 , A = 0 , B = 0; f o r ( i = 0 ; i < N ; i ++) i f ( i n [ i ] != b ) b = a b s ( i n [ i ]−b ) ; B = Transform ( b ) ; A = IncRate ( i ) ; o u t [ i ] = A*B ; } B1 i<N 1 N N−1 N B2 in[i] != b B5 1− p p b = abs(a[i]-b) B3 B4 B = Transform(b); A = IncRate(i); out[i] = A*B i=i+1 v o i d diffPCM ( ) { b = 0 , A = 0 , B = 0; f o r ( i = 0 ; i < N ; i ++) Update← ANFIS decision of updating b Leave← ANFIS decision of leaving b i f ( i n [ i ] != b ) b = a b s ( i n [ i ]−b ) ; If Update < Leave: Decision error! else If Update > Leave: Decision error! B = Transform ( b ) ; A = IncRate ( i ) ; o u t [ i ] = A*B ; } Figure 2: diffPCM function (left), the corresponding flow-chart (middle) and the version used in Section 4.3 which is annotated with ANFIS classifier invocations (right) It consists of a series of data-flow analyses and can be summarized in these four steps: 1. Solve a very busy expression7 and an available expression data-flow problem [16]. 2. Introduce a set that describes the earliest block where an expression must be evaluated. 3. Determine the latest control flow edge where the expression must be computed. 4. Introduce Insert and Delete sets which describe where expressions should be evaluated. The target domain of the analysis is the set of static expressions in a program. Input to the analysis is three predicates determining properties about the expressions in different blocks: • An expression “e” is downward exposed if it produces the same result if evaluated at the end of the block where it is defined. We use DEE(b, e) to denote if “e” is downward exposed in block “b”. • An expression “e” is upward exposed if it produces the same result if evaluated at the start of the block where it is defined. We use UEE(b, e) to denote this. • An expression “e” is killed in block “b” if any variable appearing in “e” is updated in “b”. We use KILL(b, e) to denote this. Very busy expression analysis is a backward-must data-flow analysis that depends on UEE and KILL and computes the set of expressions that is guaranteed to be computed at some time in the future. Similarly Available expression analysis is a forward-must data-flow analysis that depends on DEE and KILL and deduces the set of previously computed expressions that may be reused. The fixed-point system of these two analyses are shown in Figure 3. It is beyond the scope of this paper to further elaborate on the details of these analyses, the interested reader should consider Nielson et al. [16]. Here the LCM algorithm and the data-flow analyses it depends on, are applications we use to demonstrate the benefit of our framework. As such a rudimentary understanding is sufficient. Consider the simplified differential pulse-code modulation routine diffPCM in Figure 2 (left). We assume that N and the relative number of times block B3 (denoted p) is statically known8 . In each iteration diffPCM invokes the pure functions Transform, to encode the differential output, and IncRate to get a quantification rate. We use the KRS-LCM algorithm to determine if these invocations can be made prior to entering the loop and contrast this to a situation where the data-flow analyses are performed 7 Knoop 8 In et al. [12] refer to this as anticipatable expression data-flow problem. this demonstration we let p = 0.999 and N = 1000, but our conclusions hold as N increases and p approaches 1. J. Lidman & J. Svenningsson 117 Block Knoop-Ruthing-Steffen LCM Available expression ( V AvIn(b) = b0 ∈Pred(b) AvOut(b0 ), b 6= B0 AvOut(b) = DEE(b) ∨ [AvIn(b) ∧ ¬Kill(b)] Very busy expression ( V AnIn(b) = b0 ∈Succ(b) AnOut(b0 ), b 6= B5 AnOut(b) = UEE(b) ∨ [AnIn(b) ∧ ¬Kill(b)] B0 B1 B2 B3 B4 B5 (1) DEE 6543210 0000000 0000001 0000010 0000000 0101000 0000000 UEE 6543210 0000000 0000001 0000010 1000000 0110100 0000000 Block (2) B0 B1 B2 B3 B4 B5 ( AnIn( j) ∧ ¬AvOut(i) ∧ [Kill(i) ∨ AnOut(i)] i 6= B0 Earliest(i, j) = AnIn( j) ∧ ¬AvOut(B0) otherwise (3) ( V LaterIn( j) = j0 ∈Pred( j) LaterOut(:, j), j 6= B0 LaterOut(i, j) = Earliest(i, j) ∨ [LaterIn(i) ∧ ¬UEE(i)] (4) 6 0.0 0.0 0.0 0.0 0.0 0.0 5 0.0 0.0 0.0 0.0 1.0 0.0 4 0.0 0.0 0.0 0.0 0.0 0.0 DEE 3 0.0 0.0 0.0 0.0 1.0 0.0 2 0.0 0.0 0.0 0.0 0.0 0.0 1 0.0 0.0 1.0 0.0 0.0 0.0 0 0.0 1.0 0.0 0.0 0.0 0.0 6 0.0 0.0 0.0 1.0 0.0 0.0 5 0.0 0.0 0.0 0.0 1.0 0.0 4 0.0 0.0 0.0 0.0 1.0 0.0 UEE 3 0.0 0.0 0.0 0.0 0.0 0.0 2 0.0 0.0 0.0 0.0 1.0 0.0 1 0.0 0.0 1.0 0.0 0.0 0.0 0 0.0 1.0 0.0 0.0 0.0 0.0 6 1.0 0.0 0.0 1.0 1.0 0.0 5 1.0 0.0 0.0 1.0 0.0 0.0 4 1.0 0.0 0.0 0.0 1.0 0.0 KILL 3 1.0 0.0 0.0 0.0 1.0 0.0 2 1.0 0.0 0.0 0.0 1.0 0.0 1 1.0 0.0 0.0 1.0 1.0 0.0 0 1.0 0.0 0.0 0.0 1.0 0.0 Block B0 B1 B2 B3 B4 B5 Insert(i, j) = LaterOut( j) ∧ ¬LaterIn( j) Delete(k) = UEE(k) ∧ ¬LaterIn(k), k 6= B0 Block Edge B0→B1 B1→B5 B1→B2 B2→B3 B2→B4 B3→B4 B4→B1 6 5 4 Insert 3 0.001 0.001 0.001 0.001 0.001 0.000 0.001 0.998 0.001 0.001 0.001 0.001 0.998 0.000 0.001 0.001 0.001 0.001 0.001 0.001 0.001 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.001 0.001 0.001 0.001 0.001 0.001 0.001 0.001 0.001 0.001 0.000 0.000 0.000 0.001 0.000 0.000 0.000 0.000 0.000 0.000 0.000 2 1 0 0.000 0.000 0.000 0.000 0.001 0.000 0.000 0.000 0.001 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 Block B0 B1 B2 B3 B4 B5 Expression Index 6 5 4 Delete 3 0.000 0.000 0.000 0.001 0.000 0.000 0.000 0.000 0.000 0.000 0.998 0.000 0.000 0.000 0.000 0.000 0.001 0.000 0.000 0.000 0.000 0.000 0.000 0.000 abs(a[i]-b) 6 Transform(b) 5 2 1 0 IncRate(i) 4 A*B 3 i+1 2 B0 B1 B2 B3 B4 B5 Edge B0→B1 B1→B5 B1→B3 B2→B3 B2→B4 B3→B4 B4→B1 in[i] != b 1 KILL 6543210 1111111 0000000 0000000 1100010 1011111 0000000 Insert 6543210 0000000 0000000 0000000 0000000 0000000 0000000 0000000 Block B0 B1 B2 B3 B4 B5 Delete 6543210 0000000 0000000 0000000 0000000 0000000 0000000 i≤N 0 Figure 3: Knoop-Rüthing-Steffen LCM formulation (middle) using classical (left) and fuzzy (right/bottom) data-flow analysis 118 Bridging Static and Dynamic Program Analysis using Fuzzy Logic in the fuzzy framework. As we will show the “fuzzy KRS-LCM” allows us to uncover opportunites the classical KRS-LCM would miss. 4.1 Type-1 static analysis The data-flow problems of the KRS algorithm use expressions as domain. The mapping between expressions of diffPCM and indexes are listed in Figure 3 (bottom) together with the values of DEE, UEE and KILL for each block (top right). The classical KRS algorithm conclude that both calls must be evaluated in B4 (bottom light gray box, “Delete” matrix, Column 4 and 5). For the fuzzy data-flow analyses we use the Type-1 Min-Max fuzzy logic. The corresponding fuzzy sets of DEE, UEE and KILL are given in Figure 3 (top dark gray box). Step (1) of the fuzzy KRS-LCM is hence the fixed-point to below system of equations: Available expression analysis system  AvOut(B0) = 0.0         AvOut(B4) ∧ ¬Kill(B1) AvOut(B1) = DEE(B1) ∨ N1 AvOut(B0) + N−1  N   AvOut(B2) = DEE(B2) ∨ (AvOut(B1) ∧ ¬Kill(B2))  AvOut(B3) = DEE(B3) ∨ (AvOut(B2) ∧ ¬Kill(B3))     AvOut(B4) = DEE(B4) ∨ ([pAvOut(B2) + (1 − p)AvOut(B3)] ∧ ¬Kill(B4))    AvOut(B5) = DEE(B5) ∨ (AvOut(B1) ∧ ¬Kill(B4)) Very busy expression analysis system  ∧ ¬Kill(B1))  AnOut(B0) = UEE(B0) ∨ (AnOut(B1)   N−1     AnOut(B2) + N1 AnOut(B5) ∧ ¬Kill(B1) AnOut(B1) = UEE(B1) ∨ N   AnOut(B2) = UEE(B2) ∨ ([pAnOut(B4) + (1 − p)AnOut(B3)] ∧ ¬Kill(B2))  AnOut(B3) = UEE(B3) ∨ (AnOut(B4) ∧ ¬Kill(B3))      AnOut(B4) = UEE(B4) ∨ (AnOut(B1) ∧ ¬Kill(B4))    AnOut(B5) = 0.0 Steps (2) and (4) introduce (constant) predicates and are performed outside the analysis framework. Step (3) is done similarly to step (1). Figure 3 (bottom dark gray box) shows the result from step (4). In contrast to the classical LCM the result implies that it is very plausible (0.998) that we can delete the invocation of Transform (“Delete” matrix, Column 5) from block B4 and instead add it at the end of B0 and B3 (or start of B1 and B4). However, result for the invocation of IncRate remains. This is because the invocation depends on the value of i which is updated at the end of B4. 4.2 Type-2 static analysis To increase data-flow analysis precision a function call is sometimes inlined at the call site. The improvement can however be reduced if the control-flow analysis is inaccurate and multiple targets are considered for a particular call site. We show how the uncertainty in control-flow and data-flow can be quantified in two different dimensions using type-2 interval fuzzy sets. As per Section 2 we can lift an arbitrary fuzzy predicate to intervals. Here we assume no knowledge about the relative number of calls to each target and treat the different calls non-deterministically. We assume two different IncRate functions, as in Figure 4 (left), have been determined as targets. Their respective UEE and Kill entries are the same but since i is updated at the end of block B4 their DEE entry will differ. The result of IncRate_1 depends on the variable i and therefore DEE(B41 ) = 0101000, in contrast the entry for IncRate_2 is DEE(B42 ) = 0111000, where 0 = [0, 0] and 1 = [1, 1]. The new J. Lidman & J. Svenningsson B = Transform(b); ... = IncRate(i); i n t IncRate 1 ( i n t i ) { r e t u r n 2* i ; i n t IncRate 2 ( i n t i ) { return 1; } } A = ... out[i] = A*B i=i+1 119 Block 6 5 4 3 2 1 0 Edge B0→B1 B1→B5 B1→B3 B2→B3 B2→B4 B3→B4 B4→B1 Kill DEE UEE [1.0, 1.0] [0.0, 0.0] [0.0, 0.0] [0.0, 0.0] [1.0, 1.0] [1.0, 1.0] [1.0, 1.0] [0.0, 1.0] [1.0, 1.0] [1.0, 1.0] [1.0, 1.0] [0.0, 0.0] [1.0, 1.0] [0.0, 0.0] [1.0, 1.0] [1.0, 1.0] [0.0, 0.0] [0.0, 0.0] [1.0, 1.0] [0.0, 0.0] [0.0, 0.0] Insert Block Delete [0.001, 0.999] B0 [0.000, 0.000] [0.001, 0.999] B1 [0.000, 0.000] [0.001, 0.999] B2 [0.000, 0.000] [0.001, 0.999] B3 [0.000, 0.000] [0.001, 0.999] B4 [0.002, 0.999] [0.001, 0.999] B5 [0.000, 0.000] [0.000, 0.999] Figure 4: Implementations of IncRate inlined in block B4 (left); DEE, UEE and Kill vectors of block B4 and Delete Insert analysis result for expression IncRate(i) (right) ˜ DEE(B42 ) = h0, 1, [0, 1], 1, 0, 0, 0i. The new entry for block B4 is given by DEE(B4) = DEE(B41 ) ∨ Kill, DEE and UEE sets are given in Figure 4 (right). Applying the fuzzy KRS-LCM, but with Type-1 min-max fuzzy logic lifted to Interval type-2 minmax fuzzy logic gives the values of Delete and Insert for expression IncRate(i) in Figure 4 (right). The result for invoking IncRate prior to the loop is [0.001, 0.999] as opposed to 0.001 from the Type-1 analysis in Section 4.1. The added dimension in the result of the type-2 fuzzy analysis allows us to differentiate uncertain results from pessimistic results. In the given example we showed that the result of Section 4.1 is a pessimistic over-generalization and that the two paths need to be considered seperately to increase precision. 4.3 Hybrid analysis The result from a fuzzy data-flow analysis is a set of fuzzy membership degrees. This section shows how the result can automatically be improved following the static analysis using a fuzzy regulator/classifier, if more specific information is provided at a later point. The classifier, a Takagi-Sugeno Adaptive-Networkbased fuzzy inference system (TS-ANFIS) [10, 11] shown in Figure 5, is composed of five layers: 1. Lookup fuzzy membership degree of the input value. 2. Compute the firing strength of a rule, i.e. conjunction of all membership degrees from each rule. 3. Normalize the firing strengths, i.e., w̄i = wi / ∑ j w j . 4. Weight the normalized firing strength to the consequent output of the rule fi (x). 5. Combine all rule classifiers, i.e. f = ∑i w̄i fi . This classifier uses a polynomial (i.e., the consequent part of the adaptive IF-THEN rules) to decide the output membership. The order of the TS-ANFIS is the order of the polynomial. The classification accuracy of the TS-ANFIS can be improved online/offline by fitting the polynomial to the input data. For a first-order TS-ANFIS this can be implemented as follows: • (Offline) (Affine) Least square (LS) optimization [10] is a convex optimization problem that finds an affine function (i.e., y = a0 + ∑ni=1 ai xi ) which minimizes ||A[1; X] −Y ||22 where X and Y are the input and output vectors of the training set. • (Online) Least mean square  (LMS) [10] is an adaptive filter that gradually (in steps of a given constant µ) minimizes E |y − f (x)|2 , where hx, yi is an input/output sample. 120 Bridging Static and Dynamic Program Analysis using Fuzzy Logic IF x0 is A0 and x1 is B0 THEN f = c(1,0) + c(1,1) x0 + c(1,2) x1 IF x0 is A1 and x1 is B1 THEN f = c(2,0) + c(2,1) x0 + c(2,2) x1 µA0 µB0 0.6 A0 0.5 x0 x1 x0 A1 ∏ w1 N w¯1 µA1 w¯1 f1 ∑ B0 x1 B1 ∏ w2 N w¯2 f2 w¯2 x0 x1 µB1 f 0.286 0.1 x0 = 0.6 x1 = 0.2 Figure 5: First-order Takagi-Sugeno ANFIS with two rules and two variables (left) and four example fuzzy sets (right) To exemplify the functionality of the TS-ANFIS we consider the classification of~x = h0.6, 0.2i using the two rule TS-ANFIS from Figure 5 (left). Let f1 (~x) = 0.2x0 −0.43x1 , f2 (~x) = 0.1x1 +0.5 and membership functions be given as in Figure 5 (right). The membership degrees are marked in the figure as µA0 (x0) = 0.6, µB0 (x1) = 0.5 for the first rule and µA1 (x0) = 0.286, µB1 (x0) = 0.1 for the second rule. Hence the weight of the first rule (i.e., w1 ) is 0.6 ∧ 0.5 = 0.5 and the second rule (i.e., w2 ) is 0.286 ∧ 0.1 = 0.1. The normalized weights are then w¯1 = 0.833 and w¯1 = 0.167. As the consequence functions output f1 (~x) = 0.034 and f2 (~x) = 0.52 we produce the prediction 0.833 f1 (~x) + 0.167 f2 (~x) = 0.115. We return to the diffPCM function and again consider if we can invoke Transform(b) prior to entering the loop. We saw in Section 4.1 that the fuzzy membership degree was 0.998. To improve classification accuracy we let the TS-ANFIS also use the i variable and the first input value (i.e., in[0]). These variables were not part of the analysis and so we conservatively assume the fuzzy membership degree to be the same for any value of these variables (in our experiments: 1.0). As shown in Figure 2 (right), we inserted calls to compute the ANFIS decision of updating and keeping the variable b constant in the diffPCM function. If the incorrect decision was made the error was noted and an error rate computed after handling all input samples. We consider invoking the diffPCM function on four different input sets. Each input set defined as 10 periods with 25 input values in each period. The input sets (i.e., in[...]) is given in Figure 6 (left). We use the LMS algorithm9 after each incorrect classification and the LS algorithm if the error rate of a period was larger than or equal to 80%. Note that the values of a period is not always perfectly representable by a linear classifier and sometimes varies between different periods, although periods are “similar”. Hence we do not expect the classifier to be monotonically improving with increasing period. As shown in the result in Figure 6 (right) the classification error decreases fast with both period and input sample. In two cases a small residual error remains after the final period. This show that the TS-ANFIS can improve the analysis result dynamically and hence increase the accuracy of when Transform can be invoked prior to entering the loop. 9 The constant µ for the four different runs was set to 0.001, 0.05, 0.15 and 0.1 respectively. 121 2 1 1.8 0.9 1.6 0.8 1.4 0.7 1.2 0.6 Error rate Input value J. Lidman & J. Svenningsson 1 0.8 0.5 0.4 0.6 0.3 0.4 0.2 0.2 0.1 0 0 0 50 100 150 200 250 1 2 3 4 Sample 5 6 7 8 9 10 6 7 8 9 10 6 7 8 9 10 6 7 8 9 10 Period 60 1 0.9 50 0.8 0.7 0.6 Error rate Input value 40 30 20 0.5 0.4 0.3 0.2 10 0.1 0 0 0 50 100 150 200 250 1 2 3 4 Sample 5 Period 12 1 0.9 10 0.8 0.7 0.6 Error rate Input value 8 6 4 0.5 0.4 0.3 0.2 2 0.1 0 0 0 50 100 150 200 250 1 2 3 4 Sample 5 Period 25 1 0.9 20 0.8 0.6 Error rate Input value 0.7 15 10 0.5 0.4 0.3 5 0.2 0.1 0 0 0 50 100 150 Sample 200 250 1 2 3 4 5 Period Figure 6: 10 × 25 input values (left) and the corresponding classification error rate (right) 122 5 Bridging Static and Dynamic Program Analysis using Fuzzy Logic Related work Most systems include elements (e.g., input values, environment state) where information is limited but probabilistic and/or non-deterministic uncertainty can be formulated. For these systems a most likely or even quantitative analysis of properties is possible. Often this analysis relies on a probability theory for logical soundness. Cousot and Monerau [3] introduced a unifying framework for probabilistic abstract interpretation. Much work have since, although perhaps implicitly, relied on their formulation. Often probabilistic descriptions are known with imprecision that manifests as non-deterministic uncertainty [2]. Adje et al. [1] introduced an abstraction based on the zonotope abstraction for Dempster-Shafer structures and P-boxes10 . Di Pierro et al. [5] developed a probabilistic abstract interpretation framework and demonstrated an alias analysis algorithm that could guide the compiler in this decision. They later formulated data-flow problems (e.g., liveness analysis) in the same framework [4]. An important distinction between their (or similar probabilistic frameworks) and classical frameworks is the definition of the confluence operator. In contrast to a classical may- or must framework they use the weighted average. This is similar to the work by Ramalingam [18] that showed that the meet-over-paths (MOP) solution exists for such confluence operator with a transfer function defined in terms of min, max and negation (i.e., the Min-max fuzzy logic). Our work extends this to allow other transfer functions and integrates the static data-flow analysis with a dynamic refinement mechanism through fuzzy control theory. 6 Conclusion A major problem for static program analysis is the limited input information and hence the conservative results. To alleviate the situation dynamic program analysis is sometimes used. Here accurate information is available, but in contrast to its static counter-part the results only cover a single or few runs. To bridge the gap, and find a promising middle-ground, probabilistic/speculative program analysis frameworks have been proposed. These frameworks can be considered to intersect both by being a static program analysis that uses dynamic information. We have introduced an data-flow framework based on fuzzy sets that supports such analyses. We solved data-flow problems of use for speculative compilation and showed how our analysis unveils opportunities that previous approaches could not express and reason about. We furthermore showed that our data-flow framework based on fuzzy sets admit mechanisms from fuzzy control theory to enhance the analysis result dynamically allowing for a hybrid analysis framework. References [1] Assale Adje, Olivier Bouissou, Jean Goubault-Larrecq, Eric Goubault & Sylvie Putot (2014): Static Analysis of Programs with Imprecise Probabilistic Inputs. In: Verified Software: Theories, Tools, Experiments, Lecture Notes in Computer Science 8164, Springer Berlin Heidelberg, pp. 22–47, doi:10.1007/978-3-64254108-7 2. [2] Patrick Cousot & Radhia Cousot (2014): Abstract Interpretation: Past, Present and Future. In: Proceedings of the Joint Meeting of the Twenty-Third EACSL Annual Conference on Computer Science Logic (CSL) and the Twenty-Ninth Annual ACM/IEEE Symposium on Logic in Computer Science (LICS), CSL-LICS ’14, ACM, pp. 2:1–2:10, doi:10.1145/2603088.2603165. 10 Lower and upper bounds on a cumulative probability distribution functions J. Lidman & J. Svenningsson 123 [3] Patrick Cousot & Michaël Monerau (2012): Probabilistic Abstract Interpretation. In: 22nd European Symposium on Programming (ESOP 2012), Lecture Notes in Computer Science 7211, Springer-Verlag, pp. 166– 190, doi:10.1007/978-3-642-28891-3 3. [4] Pierro A Di & H Wiklicky (2013): Probabilistic data flow analysis: a linear equational approach. In: Proceedings of the Fourth International Symposium on Games, Automata, Logics and Formal Verification, pp. 150–165, doi:10.4204/EPTCS.119.14. [5] Alessandra Di Pierro, Chris Hankin & Herbert Wiklicky (2007): A Systematic Approach to Probabilistic Pointer Analysis. In: Programming Languages and Systems, Lecture Notes in Computer Science 4807, Springer Berlin Heidelberg, pp. 335–350, doi:10.1007/978-3-540-76637-7 23. [6] Karl-Heinz Drechsler & Manfred P. Stadel (1993): A Variation of Knoop, Rüthing, and Steffen’s Lazy Code Motion. SIGPLAN Not. 28(5), pp. 29–38, doi:10.1145/152819.152823. [7] D. Dubois & H. Prade (1980): Fuzzy sets and systems - Theory and applications. Academic press, New York. [8] D. Dubois, H.M. Prade & H. Prade (2000): Fundamentals of Fuzzy Sets. The Handbooks of Fuzzy Sets, Springer US, doi:10.1007/978-1-4615-4429-6. [9] Mai Gehrke, Carol Walker & Elbert Walker (1996): Some comments on interval valued fuzzy sets. International Journal of Intelligent Systems 11(10), pp. 751–759, doi:10.1002/(SICI)1098111X(199610)11:10¡751::AID-INT3¿3.0.CO;2-Y. [10] J.-S.R. Jang (1993): ANFIS: adaptive-network-based fuzzy inference system. Systems, Man and Cybernetics, IEEE Transactions on 23(3), pp. 665–685, doi:10.1109/21.256541. [11] Jyh-Shing Roger Jang & Chuen-Tsai Sun (1997): Neuro-fuzzy and Soft Computing: A Computational Approach to Learning and Machine Intelligence. Prentice-Hall, Inc., Upper Saddle River, NJ, USA. [12] Jens Knoop, Oliver Rüthing & Bernhard Steffen (1992): Lazy Code Motion. In: Proceedings of the ACM SIGPLAN 1992 Conference on Programming Language Design and Implementation, PLDI ’92, ACM, pp. 224–234, doi:10.1145/143095.143136. [13] S. Maleki, Yaoqing Gao, M.J. Garzaran, T. Wong & D.A. Padua (2011): An Evaluation of Vectorizing Compilers. In: Parallel Architectures and Compilation Techniques (PACT), 2011 International Conference on, pp. 372–382, doi:10.1109/PACT.2011.68. [14] A. Mesiarov (2007): k-lp-Lipschitz t-norms. International Journal of Approximate Reasoning 46(3), pp. 596 – 604, doi:10.1016/j.ijar.2007.02.002. Special Section: Aggregation Operators. [15] Markus Mock, Manuvir Das, Craig Chambers & Susan J. Eggers (2001): Dynamic Points-to Sets: A Comparison with Static Analyses and Potential Applications in Program Understanding and Optimization. In: Proceedings of the 2001 ACM SIGPLAN-SIGSOFT Workshop on Program Analysis for Software Tools and Engineering, PASTE ’01, ACM, pp. 66–72, doi:10.1145/379605.379671. [16] Flemming Nielson, Hanne R. Nielson & Chris Hankin (1999): Principles of Program Analysis. SpringerVerlag New York, Inc., doi:10.1007/978-3-662-03811-6. [17] P.M. Petersen & D.A. Padua (1996): Static and dynamic evaluation of data dependence analysis techniques. Parallel and Distributed Systems, IEEE Transactions on 7(11), pp. 1121–1132, doi:10.1109/71.544354. [18] G. Ramalingam (1996): Data Flow Frequency Analysis. In: Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language Design and Implementation, PLDI ’96, ACM, pp. 267–277, doi:10.1145/231379.231433. [19] ConstantinoG. Ribeiro & Marcelo Cintra (2007): Quantifying Uncertainty in Points-To Relations. In: Languages and Compilers for Parallel Computing, Lecture Notes in Computer Science 4382, Springer Berlin Heidelberg, pp. 190–204, doi:10.1007/978-3-540-72521-3 15. 124 Bridging Static and Dynamic Program Analysis using Fuzzy Logic Appendix A: Omitted proofs of Theorem 1. Let x, y,C, wi ∈ [0, 1], for some i ∈ N, fi (~x) : [0, 1]nq 7→ [0, 1]q be 1-Lipschitz and gi (~x) : [0, 1]nq 7→ [0, 1]q be Ki -Lipschitz. 1. Functions x + y, x − y, xy, min(x, y) and abs(x) are 1-Lipschitz. Constants are 0-Lipschitz Let b ∈ [x, x + h] for some 0 ≤ x ≤ x + h ≤ 1: (a) g(x) = abs (x): |g(x + h) − g(x)| = |abs (x + h) − abs (x)| = |x + h − x| By definition x, h ∈ [0, 1] ≤ 1|h| (b) g(x, y) = x + y: |g(x + h1 , y + h2 ) − g(x, y)| = |((x + h1 ) + (y + h2 )) − (x + y)| By definition = |h1 + h2 | ≤ |h1 | + |h2 | Triangle inequality = 1|h| Distributivity |g(x + h1 , y + h2 ) − g(x, y)| = |((x + h1 ) − (y + h2 )) − (x − y)| By definition (c) g(x, y) = x − y: = |h1 + (−1)h2 | ≤ |h1 | + | − 1||h2 | Triangle inequality = 1|h| Distributivity (d) g(x, y) = xy: |g(x + h1 , y + h2 ) − g(x, y)| = g(x + h1 , y0 ) − g(x, y0 − h2 ) 0 0 = (x + h1 )y − x(y − h2 ) Substitution y0 = y + h2 By definition 0 = |h1 y + xh2 | ≤ |h1 + h2 | 0 ≤ x, y0 ≤ 1 ≤ |h1 | + |h2 | Triangle inequality = 1|h| Distributivity (e) g(x, y) = min(x, y): |g(x + h1 , y + h2 ) − g(x, y)| = |min(x + h1 , y + h2 ) − min(x, y)|   x + h1 + y + h2 |x + h1 − y − h2 | − − 2 2 =   x + y |x − y| − 2 2 h1 + h2 |x| + | − 1||y| + |h1 − h2 | − + 2 2 ≤ |x| + | − 1||y| 2 h1 + h2 |h1 − h2 | = − 2 2 By definition min(x, y) = x + y |x − y| − 2 2 = | min(h1 , h2 )| ≤ |h1 + h2 | = 1|h| Triangle inequality J. Lidman & J. Svenningsson 125 (f) g(x, y) = C |g(x + h) − g(x)| = |C −C| = 0 ≤ 0|h| N−1 x) is 1-Lipschitz 2. If ∑N−1 i=0 wi = 1 then ∑i=0 wi f i (~ g(~x +~h) − g(~x) = N−1 ∑ wi f (x ~+ h) − i=0 N−1 = ∑ wi N−1 ∑ wi f (~x) By definition i=0   f (x ~+ h) − f (~x) Associativitiy and commutativity i=0 ! N−1 ≤ ∑ wi Ki |h| Triangle inequality, distributivity and wi ≥ 0 i=0 = 1|h| Ki = 1 and ∑ wi = 1 i 3. The composition ga ◦ gb is Ka Kb -Lipschitz g(~x) = fa (~x) ◦ fa (~x): |g(x + h) − g(x)| = fa ( fb (x ~+ h)) − fa ( fb (~x)) By definition ≤ Ka fb (x ~+ h) − fb (~x) Definition 5 ≤ Ka Kb |h| Definition 5 4. Formulas defined in a Frank family Fuzzy logic are 1-Lipschitz. This follows from structural induction on the height of parse tree of the predicate P(x). By De Morgan’s laws it is enough to show the induction step for ∨ and ¬. • Base case: – v: g(x) = x: |g(x + h) − g(x)| = |x + h − x| ≤ 1|h|. – > or ⊥: g(x) = C: 1-Lipschitz by 3. • Induction step: – ¬φ ≡ 1 − φ : 1-Lipschitz from the base case for constants (> and ⊥) and cases 1c and 3 and assumption that φ is 1-Lipschitz.  min(x, y) 1-Lipschitz from Theorem 1 case 1e     1-Lipschitz from Theorem 1 case 1d  xy max(x + y − 1, 0) Equal to 1 − min(2 − x − y, 1) using De Morgans law. – φ1 ∨ φ2 :   This expression is 1-Lipschitz from Theorem 1    case 1c, 1e and 3 5. If F : Inq → Iq satisfy ∀x ∈ Inq : y ∈ x ⇒ f (y) ∈ F(x) then F is 1-Lipschitz F : Inq → Iq can be decomposed into two functions Fl : Inq → [0, 1]q and Fu : Inq → [0, 1]q such that ∀i : F(i) = [Fl (i), Fu (i)], i.e., Fl (i) gives the infimum of f (i) and Fu (i) gives the supremum of i. We show that both Fl and Fu are 1-Lipschitz continuous: • Fl (I) = inf f (i): Assume I = [l, u], since I is finite we can rewrite the operation as pairi∈I wise applications of min, i.e., min( f (l), min( f (l + 21q ), min( f (l + 222 ), ...))). As per above case 1e min is 1-Lipschitz. Similarly the composition of two 1-Lipschitz functions is also 1-Lipschitz, or in extension, a finite number of compositions. 126 Bridging Static and Dynamic Program Analysis using Fuzzy Logic • Fu (I) = sup f (i): max(x, y) is equivalent to 1 − min(1 − x, 1 − y) which is 1-Lipschitz by i∈I above case 1c and 1e so proof follows in the same way as the Fl (I) case.
6 (cs.PL)
Complexity of Manipulation with Partial Information in Voting arXiv:1604.04359v2 [cs.MA] 13 Jul 2017 Palash Dey Tata Institute of Fundamental Research, Mumbai palash.dey@tifr.res.in Neeldhara Misra Indian Institute of Technology, Gandhinagar mail@neeldhara.com Y. Narahari Indian Institute of Science, Bangalore hari@csa.iisc.ernet.in January 2, 2018 Abstract The Coalitional Manipulation problem has been studied extensively in the literature for many voting rules. However, most studies have focused on the complete information setting, wherein the manipulators know the votes of the non-manipulators. While this assumption is reasonable for purposes of showing intractability, it is unrealistic for algorithmic considerations. In most real-world scenarios, it is impractical to assume that the manipulators to have accurate knowledge of all the other votes. In this work, we investigate manipulation with incomplete information. In our framework, the manipulators know a partial order for each voter that is consistent with the true preference of that voter. In this setting, we formulate three natural computational notions of manipulation, namely weak, opportunistic, and strong manipulation. We say that an extension of a partial order is viable if there exists a manipulative vote for that extension. We propose the following notions of manipulation when manipulators have incomplete information about the votes of other voters. 1. W EAK M ANIPULATION: the manipulators seek to vote in a way that makes their preferred candidate win in at least one extension of the partial votes of the non-manipulators. 2. O PPORTUNISTIC M ANIPULATION: the manipulators seek to vote in a way that makes their preferred candidate win in every viable extension of the partial votes of the nonmanipulators. 3. S TRONG M ANIPULATION: the manipulators seek to vote in a way that makes their preferred candidate win in every extension of the partial votes of the non-manipulators. We consider several scenarios for which the traditional manipulation problems are easy (for instance, Borda with a single manipulator). For many of them, the corresponding manipulative questions that we propose turn out to be computationally intractable. Our hardness results often hold even when very little information is missing, or in other words, even when the instances are very close to the complete information setting. Our results show that the impact of paucity of information on the computational complexity of manipulation crucially depends on the notion of manipulation under consideration. Our overall conclusion is that computational hardness continues to be a valid obstruction to manipulation, in the context of a more realistic model. Keywords: voting, manipulation, incomplete information, algorithm, computational complexity 1 1 Introduction In many real life and AI related applications, agents often need to agree upon a common decision although they have different preferences over the available alternatives. A natural tool used in these situations is voting. Some classic examples of the use of voting rules in the context of multiagent systems include Clarke tax [ER91], collaborative filtering [PHG00], and similarity search [FKS03], etc. In a typical voting scenario, we have a set of candidates and a set of voters reporting their rankings of the candidates called their preferences or votes. A voting rule selects one candidate as the winner once all voters provide their votes. A set of votes over a set of candidates along with a voting rule is called an election. A central issue in voting is the possibility of manipulation. For many voting rules, it turns out that even a single vote, if cast differently, can alter the outcome. In particular, a voter manipulates an election if, by misrepresenting her preference, she obtains an outcome that she prefers over the “honest” outcome. In a cornerstone impossibility result, Gibbard and Satterthwaite [Gib73, Sat75] show that every unanimous and non-dictatorial voting rule with three candidates or more is manipulable. We refer to [BCE+ 15] for an excellent introduction to various strategic issues in computational social choice theory. Considering that voting rules are indeed susceptible to manipulation, it is natural to seek ways by which elections can be protected from manipulations. The works of Bartholdi et al. [BITT89, BIO91] approach the problem from the perspective of computational intractability. They exploit the possibility that voting rules, despite being vulnerable to manipulation in theory, may be hard to manipulate in practice. Indeed, a manipulator is faced with the following decision problem: given a collection of votes P and a distinguished candidate c, does there exist a vote v that, when tallied with P, makes c win for a (fixed) voting rule r? The manipulation problem has subsequently been generalized to the problem of C OALITIONAL MANIPULATION by Conitzer et al. [CSL07], where one or more manipulators collude together and try to make a distinguished candidate win the election. The manipulation problem, fortunately, turns out to be NP-hard in several settings. This established the success of the approach of demonstrating a computational barrier to manipulation. However, despite having set out to demonstrate the hardness of manipulation, the initial results in [BITT89] were to the contrary, indicating that many voting rules are in fact easy to manipulate. Moreover, even with multiple manipulators involved, popular voting rules like plurality, veto, kapproval, Bucklin, and Fallback continue to be easy to manipulate [XZP+ 09]. While we know that the computational intractability may not provide a strong barrier [PR06, PR07, FKN08, XC08a, XC08b, FHH10, Wal10, Wal11, IKM12, Dey15, DMN15b, DMN16, DMN15a, DN14, DN15] even for rules for which the coalitional manipulation problem turns out to be NP-hard, in all other cases the possibility of manipulation is a much more serious concern. 1.1 Motivation and Problem Formulation In our work, we propose to extend the argument of computational intractability to address the cases where the approach appears to fail. We note that most incarnations of the manipulation problem studied so far are in the complete information setting, where the manipulators have complete knowledge of the preferences of the truthful voters. While these assumptions are indeed the best possible for the computationally negative results, we note that they are not reflective of typical real-world scenarios. Indeed, concerns regarding privacy of information, and in other cases, the sheer volume of information, would be significant hurdles for manipulators to obtain complete information. Motivated by this, we consider the manipulation problem in a natural partial infor2 mation setting. In particular, we model the partial information of the manipulators about the votes of the non-manipulators as partial orders over the set of candidates. A partial order over the set of candidates will be called a partial vote. Our results show that several of the voting rules that are easy to manipulate in the complete information setting become intractable when the manipulators know only partial votes. Indeed, for many voting rules, we show that even if the ordering of a small number of pairs of candidates is missing from the profile, manipulation becomes an intractable problem. Our results therefore strengthen the view that manipulation may not be practical if we limit the information the manipulators have at their disposal about the votes of other voters [CWX11]. We introduce three new computational problems that, in a natural way, extend the question of manipulation to the partial information setting. In these problems, the input is a set of partial votes P corresponding to the votes of the non-manipulators, a non-empty set of manipulators M, and a preferred candidate c. The task in the W EAK M ANIPULATION (WM) problem is to determine if there is a way to cast the manipulators’ votes such that c wins the election for at least one extension of the partial votes in P. On the other hand, in the S TRONG M ANIPULATION (SM) problem, we would like to know if there is a way of casting the manipulators’ votes such that c wins the election in every extension of the partial votes in P. We also introduce the problem of O PPORTUNISTIC M ANIPULATION (OM), which is an “intermediate” notion of manipulation. Let us call an extension of a partial profile viable if it is possible for the manipulators to vote in such a way that the manipulators’ desired candidate wins in that extension. In other words, a viable extension is a Y ES-instance of the standard C OALITIONAL M ANIPULATION problem. We have an opportunistic manipulation when it is possible for the manipulators to cast a vote which makes c win the election in all viable extensions. Note that any Y ES-instance of S TRONG M ANIPULATION is also an Y ES-instance of O PPORTUNISTIC M ANIPULATION, but this may not be true in the reverse direction. As a particularly extreme example, consider a partial profile where there are no viable extensions: this would be a N O-instance for S TRONG M ANIPULATION, but a (vacuous) Y ES-instance of O PPORTUNISTIC M ANIPULATION. The O PPORTUNISTIC M ANIPULATION problem allows us to explore a more relaxed notion of manipulation: one where the manipulators are obliged to be successful only in extensions where it is possible to be successful. Note that the goal with S TRONG M ANIPULATION is to be successful in all extensions, and therefore the only interesting instances are the ones where all extensions are viable. It is easy to see that Y ES instance of S TRONG M ANIPULATION is also a Y ES instance of O PPOR TUNISTIC M ANIPULATION and W EAK M ANIPULATION . Beyond this, we remark that all the three problems are questions with different goals, and neither of them render the other redundant. We refer the reader to Figure 1 for a simple example distinguishing these scenarios. All the problems above generalize C OALITIONAL M ANIPULATION, and hence any computational intractability result for C OALITIONAL M ANIPULATION immediately yields a corresponding intractability result for W EAK M ANIPULATION, S TRONG M ANIPULATION, and O PPORTUNISTIC M A NIPULATION under the same setting. For example, it is known that the C OALITIONAL M ANIPULA TION problem is intractable for the maximin voting rule when we have at least two manipulators [XZP+ 09]. Hence, the W EAK M ANIPULATION, S TRONG M ANIPULATION, and O PPORTUNISTIC M ANIPULATION problems are intractable for the maximin voting rule when we have at least two manipulators. 3 Figure 1: An example of a partial profile. Consider the plurality voting rule with one manipulator. If the favorite candidate is A, then the manipulator simply has to place A on the top of his vote to make A win in any extension. If the favorite candidate is B, there is no vote that makes B win in any extension. Finally, if the favorite candidate is C, then with a vote that places C on top, the manipulator can make C win in the only viable extension (Extension 2). 1.2 Related Work A notion of manipulation under partial information has been considered by Conitzer et al. [CWX11]. They focus on whether or not there exists a dominating manipulation and show that this problem is NP-hard for many common voting rules. Given some partial votes, a dominating manipulation is a non-truthful vote that the manipulator can cast which makes the winner at least as preferable (and sometimes more preferable) as the winner when the manipulator votes truthfully. The dominating manipulation problem and the W EAK M ANIPULATION, O PPOR TUNISTIC M ANIPULATION , and S TRONG M ANIPULATION problems do not seem to have any apparent complexity-theoretic connection. For example, the dominating manipulation problem is NP-hard for all the common voting rules except plurality and veto, whereas, the S TRONG M ANIPULATION problem is easy for most of the cases (see Table 1). However, the results in [CWX11] establish the fact that it is indeed possible to make manipulation intractable by restricting the amount of information the manipulators possess about the votes of the other voters. Elkind and Erdélyi [EE12] study manipulation under voting rule uncertainty. However, in our work, the voting rule is fixed and known to the manipulators. Two closely related problems that have been extensively studied in the context of incomplete votes are P OSSIBLE W INNER and N ECESSARY W INNER [KL05]. In the P OSSIBLE W INNER problem, we are given a set of partial votes P and a candidate c, and the question is whether there exists an extension of P where c wins, while in the N ECESSARY W INNER problem, the question is whether c is a winner in every extension of P. Following the work in [KL05], a number of special cases and variants of the P OSSIBLE W INNER problem have been studied in the literature [CLMM10, BBF10, BRR11, BRR+ 12, GNNW14, XC11, DL13, NW14, BFLR12, ML15]. The flavor of the W EAK M ANIPULATION problem is clearly similar to P OSSIBLE W INNER. However, we emphasize that there are subtle distinctions between the two problems. A more elaborate comparison is made in the next section. 4 1.3 Our Contribution Our primary contribution in this work is to propose and study three natural and realistic generalizations of the computational problem of manipulation in the incomplete information setting. We summarize the complexity results in this work in Table 1. Our results provide the following interesting insights on the impact of lack of information on the computational difficulty of manipulation. We note that the number of undetermined pairs of candidates per vote are small constants in all our hardness results. B We observe that the computational problem of manipulation for the plurality and veto voting rules remains polynomial time solvable even with lack of information, irrespective of the notion of manipulation under consideration [Proposition 1, Theorem 11 and 15, and Observation 4]. We note that the plurality and veto voting rule also remain vulnerable under the notion of dominating manipulation [CWX11]. B The impact of absence of information on the computational complexity of manipulation is more dynamic for the k-approval, k-veto, Bucklin, Borda, and maximin voting rules. Only the W EAK M ANIPULATION and O PPORTUNISTIC M ANIPULATION problems are computationally intractable for the k-approval [Theorem 1 and 5], k-veto [Theorem 2 and 6], Bucklin [Theorem 3 and 10], Borda [Observation 3 and Theorem 7], and maximin [Observation 3 and Theorem 8] voting rules, whereas the S TRONG M ANIPULATION problem remains computationally tractable [Theorem 11 to 14]. B Table 1 shows an interesting behavior of the Fallback voting rule. The Fallback voting rule is the only voting rule among the voting rules we study here for which the W EAK M ANIPULATION problem is NP-hard [Theorem 3] but both the O PPORTUNISTIC M ANIPULATION and S TRONG M ANIPULATION problems are polynomial time solvable [Theorem 13 and Observation 4]. This is because the O PPORTUNISTIC M ANIPULATION problem can be solved for the Fallback voting rule by simply making manipulators vote for their desired candidate. B Our results show that absence of information makes all the three notions of manipulations intractable for the Copelandα voting rule for every rational α ∈ [0, 1] \ {0.5} for the W EAK M ANIPULATION problem [Observation 3] and for every α ∈ [0, 1] for the O PPORTUNISTIC M ANIPULATION and S TRONG M ANIPULATION problems [Theorem 4 and 9]. Our results (see Table 1) show that whether lack of information makes the manipulation problems harder, crucially depends on the notion of manipulation applicable to the situation under consideration. All the three notions of manipulations are, in our view, natural extension of manipulation to the incomplete information setting and tries to capture different behaviors of manipulators. For example, the W EAK M ANIPULATION problem maybe applicable to an optimistic manipulator whereas for an pessimistic manipulator, the S TRONG M ANIPULATION problem may make more sense. Organization of the paper: We define the problems and introduce the basic terminology in the next section. We present our hardness results in Section 3. In Section 4, we present our polynomially solvable algorithms. Finally we conclude with future directions of research in Section 5. 5 WM, ` = 1 Plurality Veto k-Approval k-Veto Bucklin Fallback Borda maximin Copelandα WM OM, ` = 1 P NP-complete OM SM, ` = 1 SM P P coNP-hard P NP-complete coNP-hard P NP-hard coNP-hard Table 1: Summary of Results (` denotes the number of manipulators). The results in white follow immediately from the literature (Observation 1 to 3). Our results for the Copelandα voting rule hold for every rational α ∈ [0, 1]\{0.5} for the W EAK M ANIPULATION problem and for every α ∈ [0, 1] for the O PPORTUNISTIC M ANIPULATION and S TRONG M ANIPULATION problems. 2 Preliminaries In this section, we begin by providing the technical definitions and notations that we will need in the subsequent sections. We then formulate the problems that capture our notions of manipulation when the votes are given as partial orders, and finally draw comparisons with related problems that are already studied in the literature of computational social choice theory. 2.1 Notations and Definitions Let V = {v1 , . . . , vn } be the set of all voters and C = {c1 , . . . , cm } the set of all candidates. If not specified explicitly, n and m denote the total number of voters and the total number of candidates respectively. Each voter vi ’s vote is a preference i over the candidates which is a linear order over C. For example, for two candidates a and b, a i b means that the voter vi prefers a to b. We denote the set of all linear orders over C by L(C). Hence, L(C)n denotes the set of all n-voters’ preference profile (1 , . . . , n ). A map r : ∪n,|C|∈N+ L(C)n −→ 2C \ {∅} is called a voting rule. For some preference profile  ∈ L(C)n , if r() = {w}, then we say w wins uniquely and we write r() = w. From here on, whenever we say some candidate w wins, we mean that the candidate w wins uniquely. For simplicity, we restrict ourselves to the unique winner case in this paper. All our proofs can be easily extended in the co-winner case. A more general setting is an election where the votes are only partial orders over candidates. A partial order is a relation that is reflexive, antisymmetric, and transitive. A partial vote can be extended to possibly more than one linear vote depending on how we fix the order of the unspecified pairs of candidates. For example, in an election with the set of candidates C = {a, b, c}, a valid partial vote can be a  b. This partial vote can be extended to three linear votes namely, a  b  c, 6 a  c  b, c  a  b. In this paper, we often define a partial vote like  \A, where  ∈ L(C) and A ⊂ C × C, by which we mean the partial vote obtained by removing the order among the pair of candidates in A from . Also, whenever we do not specify the order among a set of candidates while describing a complete vote, the statement/proof is correct in whichever way we fix the order among them. We now give examples of some common voting rules. B Positional scoring rules: An m-dimensional vector α ~ = (α1 , α2 , . . . , αm ) ∈ Rm with α1 > α2 > . . . > αm and α1 > αm naturally defines a voting rule – a candidate gets score αi from a vote if it is placed at the ith position, and the score of a candidate is the sum of the scores it receives from all the votes. The winners are the candidates with maximum score. Scoring rules remain unchanged if we multiply every αi by any constant λ > 0 and/or add any constant µ. Hence, we assume without loss of generality that for any score vector α ~ , there exists a j such that αj − αj+1 = 1 and αk = 0 for all k > j. We call such a α ~ a normalized score vector. For α ~ = (m − 1, m − 2, . . . , 1, 0), we get the Borda voting rule. With αi = 1 ∀i 6 k and 0 else, the voting rule we get is known as k-approval. For the k-veto voting rule, we have αi = 0 ∀i 6 m − k and −1 else. Plurality is 1-approval and veto is 1-veto. B Bucklin and simplified Bucklin: Let ` be the minimum integer such that at least one candidate gets majority within top ` positions of the votes. The winners under the simplified Bucklin voting rule are the candidates having more than n/2 votes within top ` positions. The winners under the Bucklin voting rule are the candidates appearing within top ` positions of the votes highest number of times. B Fallback and simplified Fallback: For these voting rules, each voter v ranks a subset Xv ⊂ C of candidates and disapproves the rest of the candidates [BS09]. Now for the Fallback and simplified Fallback voting rules, we apply the Bucklin and simplified Bucklin voting rules respectively to define winners. If there is no integer ` for which at least one candidate gets more than n/2 votes, both the Fallback and simplified Fallback voting rules output the candidates with most approvals as winners. We assume, for simplicity, that the number of candidates each partial vote approves is known. B Maximin: For any two candidates x and y, let D(x, y) be N(x, y) − N(y, x), where N(x, y) (respectively N(y, x)) is the number of voters who prefer x to y (respectively y to x). The election we get by restricting all the votes to x and y only is called the pairwise election between x and y. The maximin score of a candidate x is miny6=x D(x, y). The winners are the candidates with maximum maximin score. B Copelandα . The Copelandα score of a candidate x is |{y 6= x : DE (x, y) > 0}| + α|{y 6= x : DE (x, y) = 0}|, where α ∈ [0, 1]. That is, the Copelandα of a candidate x is the number of other candidates it defeats in pairwise election plus α times the number of other candidates it ties with in pairwise elections. The winners are the candidates with the maximum Copelandα score. 2.2 Problem Definitions We now formally define the three problems that we consider in this work, namely W EAK M ANIPU LATION , O PPORTUNISTIC M ANIPULATION , and S TRONG M ANIPULATION . Let r be a fixed voting rule. We first introduce the W EAK M ANIPULATION problem. 7 Definition 1. r-W EAK M ANIPULATION Given a set of partial votes P over a set of candidates C, a positive integer ` (> 0) denoting the number of manipulators, and a candidate c, do there exist votes 1 , . . . , ` ∈ L(C) such that there exists an extension  ∈ L(C)|P| of P with r(, 1 , . . . , ` ) = c? To define the O PPORTUNISTIC M ANIPULATION problem, we first introduce the notion of an (r, c)opportunistic voting profile, where r is a voting rule and c is any particular candidate. Definition 2. (r, c)-Opportunistic Voting Profile Let ` be the number of manipulators and P a set of partial votes. An `-voter profile (i )i∈[`] ∈ L(C)` is called an (r, c)-opportunistic voting  profile if for each extension P  of P for which  there exists an `-vote profile (0i )i∈[`] ∈ L(C)` with r P ∪ 0i i∈[`] = c, we have r P ∪ (i )i∈[`] = c. In other words, an `-vote profile is (r, c)-opportunistic with respect to a partial profile if, when put together with the truthful votes of any extension, c wins if the extension is viable to begin with. We are now ready to define the O PPORTUNISTIC M ANIPULATION problem. Definition 3. r-O PPORTUNISTIC M ANIPULATION Given a set of partial votes P over a set of candidates C, a positive integer ` (> 0) denoting the number of manipulators, and a candidate c, does there exist an (r, c)-opportunistic `-vote profile? We finally define the S TRONG M ANIPULATION problem. Definition 4. r-S TRONG M ANIPULATION Given a set of partial votes P over a set of candidates C, a positive integer ` (> 0) denoting the number of manipulators, and a candidate c, do there exist votes (i )i∈` ∈ L(C)` such that for every extension  ∈ L(C)|P| of P, we have r(, (i )i∈[`] ) = c? We use (P, `, c) to denote instances of W EAK M ANIPULATION, O PPORTUNISTIC M ANIPULATION, and S TRONG M ANIPULATION, where P denotes a profile of partial votes, ` denotes the number of manipulators, and c denotes the desired winner. For the sake of completeness, we provide the definitions of the C OALITIONAL M ANIPULATION and P OSSIBLE W INNER problems below. Definition 5. r-C OALITIONAL M ANIPULATION Given a set of complete votes  over a set of candidates C, a positive integer ` (> 0) denoting the number   ` of manipulators, and a candidate c, do there exist votes (i )i∈` ∈ L(C) such that r , (i )i∈[`] = c? Definition 6. r-P OSSIBLE W INNER Given a set of partial votes P and a candidate c, does there exist an extension  of the partial votes in P to linear votes such that r() = c? 2.3 Comparison with Possible Winner and Coalitional Manipulation For any fixed voting rule, the W EAK M ANIPULATION problem with ` manipulators reduces to the P OSSIBLE W INNER problem. This is achieved by simply using the same set as truthful votes and introducing ` empty votes. We summarize this in the observation below. 8 Observation 1. The W EAK M ANIPULATION problem many-to-one reduces to the P OSSIBLE W INNER problem for every voting rule. Proof. Let (P, `, c) be an instance of W EAK M ANIPULATION. Let Q be the set consisting of ` many copies of partial votes {∅}. Clearly the W EAK M ANIPULATION instance (P, `, c) is equivalent to the P OSSIBLE W INNER instance (P ∪ Q, c). However, whether the P OSSIBLE W INNER problem reduces to the W EAK M ANIPULATION problem or not is not clear since in any W EAK M ANIPULATION problem instance, there must exist at least one manipulator and a P OSSIBLE W INNER instance may have no empty vote. From a technical point of view, the difference between the W EAK M ANIPULATION and P OSSIBLE W INNER problems may look marginal; however we believe that the W EAK M ANIPULATION problem is a very natural generalization of the C OALITIONAL M ANIPULATION problem in the partial information setting and thus worth studying. Similarly, it is easy to show, that the C OALITIONAL M ANIPULATION problem with ` manipulators reduces to W EAK M ANIPULATION, O PPORTUNISTIC M ANIPULATION, and S TRONG M ANIPULATION problems with ` manipulators, since the former is a special case of the latter ones. Observation 2. The C OALITIONAL M ANIPULATION problem with ` manipulators many-to-one reduces to W EAK M ANIPULATION, O PPORTUNISTIC M ANIPULATION, and S TRONG M ANIPULATION problems with ` manipulators for all voting rules and for all positive integers `. Proof. Follows from the fact that every instance of the C OALITIONAL M ANIPULATION problem is also an equivalent instance of the W EAK M ANIPULATION, O PPORTUNISTIC M ANIPULATION, and S TRONG M ANIPULATION problems. Finally, we note that the C OALITIONAL M ANIPULATION problem with ` manipulators can be reduced to the W EAK M ANIPULATION problem with just one manipulator, by introducing `−1 empty votes. These votes can be used to witness a good extension in the forward direction. In the reverse direction, given an extension where the manipulator is successful, the extension can be used as the manipulator’s votes. This argument leads to the following observation. Observation 3. The C OALITIONAL M ANIPULATION problem with ` manipulators many-to-one reduces to the W EAK M ANIPULATION problem with one manipulator for every voting rule and for every positive integer `. Proof. Let (P, `, c) be an instance of C OALITIONAL M ANIPULATION. Let Q be the set of consisting of `−1 many copies of partial vote {c  others}. Clearly the W EAK M ANIPULATION instance (P∪Q, 1, c) is equivalent to the C OALITIONAL M ANIPULATION instance (P, `, 1). This observation can be used to derive the hardness of W EAK M ANIPULATION even for one manipulator whenever the hardness for C OALITIONAL M ANIPULATION is known for any fixed number of manipulators (for instance, this is the case for the voting rules such as Borda, maximin and Copeland). However, determining the complexity of W EAK M ANIPULATION with one manipulator requires further work for voting rules where C OALITIONAL M ANIPULATION is polynomially solvable for any number of manipulators (such as k-approval, Plurality, Bucklin, and so on). 9 3 Hardness Results In this section, we present our hardness results. While some of our reductions are from the P OS SIBLE W INNER problem, the other reductions in this section are from the E XACT C OVER BY 3-S ETS problem, also referred to as X3C. This is a well-known NP-complete [GJ79] problem, and is defined as follows. Definition 7 (Exact Cover by 3-Sets (X3C)). Given a set U and a collection S = {S1 , S2 , . . . , St } of t subsets of U with |Si | = 3 ∀i = 1, . . . , t, does there exist a T ⊂ S with |T| = |U| 3 such that ∪X∈T X = U? We use X3C to refer to the complement of X3C, which is to say that an instance of X3C is a Y ES instance if and only if it is a N O instance of X3C. The rest of this section is organized according to the problems being addressed. 3.1 Weak Manipulation To begin with, recall that the C OALITIONAL M ANIPULATION problem is NP-complete for the Borda [DKNW11, BNW11], maximin [XZP+ 09], and Copelandα [FHS08, FHHR09, FHS10] voting rules for every rational α ∈ [0, 1] \ {0.5}, when we have two manipulators. Therefore, it follows from Observation 3 that the W EAK M ANIPULATION problem is NP-complete for the Borda, maximin, and Copelandα voting rules for every rational α ∈ [0, 1] \ {0.5}, even with one manipulator. For the k-approval and k-veto voting rules, we reduce from the corresponding P OSSIBLE W IN NER problems. While it is natural to start from the same voting profile, the main challenge is in undoing the advantage that the favorite candidate receives from the manipulator’s vote, in the reverse direction. We begin with proving that the W EAK M ANIPULATION problem is NP-complete for the k-approval voting rule even with one manipulator and at most 4 undetermined pairs per vote. Theorem 1. The W EAK M ANIPULATION problem is NP-complete for the k-approval voting rule even with one manipulator for any constant k > 1, even when the number of undetermined pairs in each vote is no more than 4. Proof. For simplicity of presentation, we prove the theorem for 2-approval. We reduce from the P OSSIBLE W INNER problem for 2-approval which is NP-complete [XC11], even when the number of undetermined pairs in each vote is no more than 4. Let P be the set of partial votes in a P OSSIBLE W INNER instance, and let C = {c1 , . . . , cm , c} be the set of candidates, where the goal is to check if there is an extension of P that makes c win. For developing the instance of W EAK M ANIPULATION, we need to “reverse” any advantage that the candidate c obtains from the vote of the manipulator. Notice that the most that the manipulator can do is to increase the score of c by one. Therefore, in our construction, we “artificially” increase the score of all the other candidates by one, so that despite of the manipulator’s vote, c will win the new election if and only if it was a possible winner in the P OSSIBLE W INNER instance. To this end, we introduce (m + 1) many dummy candidates d1 , . . . , dm+1 and the complete votes: wi = ci  di  others, for every i ∈ {1, . . . , m} Further, we extend the given partial votes of the P OSSIBLE W INNER instance to force the dummy candidates to be preferred least over the rest - by defining, for every vi ∈ P, the corresponding 10 partial vote v0i as follows. v0i = vi ∪ {C  {d1 , . . . , dm+1 }}. This ensures that all the dummy candidates do not receive any score from the modified partial votes corresponding to the partial votes of the P OSSIBLE W INNER instance. Notice that since the number of undetermined pairs in vi is no more than 4, the number of undetermined pairs in v0i is also no more than 4. Let (C0 , Q, c) denote this constructed W EAK M ANIPULATION instance. We claim that the two instances are equivalent. In the forward direction, suppose c is a possible winner with respect to P, and let P be an extension where c wins. Then it is easy to see that the manipulator can make c win in some extension by placing c and dm+1 in the first two positions of her vote (note that the partial score of dm+1 is zero in Q). Indeed, consider the extension of Q obtained by mimicking the extension P on the “common” partial votes, {v0i | vi ∈ P}. Notice that this is well-defined since vi and v0i have exactly the same set of incomparable pairs. In this extension, the score of c is strictly greater than the scores of all the other candidates, since the scores of all candidates in C is exactly one more than their scores in P, and all the dummy candidates have a score of at most one. In the reverse direction, notice that the manipulator puts the candidates c and dm+1 in the top two positions without loss of generality. Now suppose the manipulator’s vote c  dm+1  others makes c win the election for an extension Q of Q. Then consider the extension P obtained by restricting Q to C. Notice that the score of each candidate in C in this extension is one less than their scores in Q. Therefore, the candidate c wins this election as well, concluding the proof. The above proof can be imitated for any other constant values of k by reducing it from the P OSSIBLE W INNER problem for k-approval and introducing (m + 1)(k − 1) dummy candidates. We will use Lemma 1 in subsequent proofs which has been used before [BRR11, DMN15b, DMN16]. Lemma 1. Let C = {c1 , . . . , cm } ] D, (|D| > 0) be a set of candidates, and α ~ a normalized score vector of length |C|. Then, for any given X = (X1 , . . . , Xm ) ∈ Zm , there exists λ ∈ R and a voting profile such that the α ~ -score of ci is λ + Xi for all 1 6 i 6 m, and the score of candidates d ∈ D is less than λ. Pm Moreover, the number of votes is O(poly(|C| · i=1 |Xi |, λ)). Note that the number of votes used in Lemma 1 is polynomial in m if λ and |Xi | is polynomial in m for every i ∈ [m], which indeed is the case in all the proofs that use Lemma 1. We next show that the WM problem is NP-complete for the k-veto voting rule. Theorem 2. The W EAK M ANIPULATION problem for the k-veto voting rule is NP-complete even with one manipulator for any constant k > 1. Proof. We reduce from the P OSSIBLE W INNER problem for the k-veto voting rule which is known to be NP-complete [BD09]. Let P be the set of partial votes in a P OSSIBLE W INNER problem instance, and let C = {c1 , . . . , cm , c} be the set of candidates, where the goal is to check if there is an extension that makes c win with respect to k-veto. We assume without loss of generality that c’s position is fixed in all the partial votes (if not, then we fix the position of c as high as possible in every vote). We introduce k + 1 many dummy candidates d1 , . . . , dk , d. The role of the first k dummy candidates is to ensure that the manipulator is forced to place them at the “bottom k” positions of her vote, so that all the original candidates get the same score from the additional vote of the manipulator. The most natural way of achieving this is to ensure that the dummy candidates have the 11 same score as c in any extension (note that we know the score of c since c’s position is fixed in all the partial votes). This would force the manipulator to place these k candidates in the last k positions. Indeed, doing anything else will cause these candidates to tie with c, even when there is an extension of P that makes c win. To this end, we begin by placing the dummy candidates in the top k positions in all the partial votes. Formally, we modify every partial vote as follows: w = di  others, for every i ∈ {1, . . . , k} At this point, we know the scores of c and di , for every i ∈ {1, . . . , k}. Using Lemma 1, we add complete votes such that the final score of c is the same with the score of every di and the score of c is strictly more than the score of d. The relative score of every other candidate remains the same. This completes the description of the construction. We denote the augmented set of partial votes by P. We now argue the correctness. In the forward direction, if there is an extension of the votes that makes c win, then we repeat this extension, and the vote of the manipulator puts the candidate di at the position m + i + 2; and all the other candidates in an arbitrary fashion. Formally, we let the manipulator’s vote be: v = c  c1  · · ·  cm  d  d 1  · · ·  d k . By construction c wins the election in this particular setup. In the reverse direction, consider a vote of the manipulator and an extension Q of P in which c wins. Note that the manipulator’s vote necessarily places the candidates di in the bottom k positions — indeed, if not, then c cannot win the election by construction. We extend a partial vote w ∈ P by mimicking the extension of the corresponding partial vote w0 ∈ P, that is, we simply project the extension of w0 on the original set of candidates C. Let Q denote this proposed extension of P. We claim that c wins the election given by Q. Indeed, suppose not. Let ci be a candidate whose score is at least the score of c in the extension Q. Note that the scores of ci and c in the extension Q are exactly the same as their scores in Q, except for a constant offset — importantly, their scores are offset by the same amount. This implies that the score of ci is at least the score of c in Q as well, which is a contradiction. Hence, the two instances are equivalent. We next prove, by a reduction from X3C, that the W EAK M ANIPULATION problem for the Bucklin and simplified Bucklin voting rules is NP-complete even with one manipulator and at most 16 undetermined pairs per vote. Theorem 3. The W EAK M ANIPULATION problem is NP-complete for Bucklin, simplified Bucklin, Fallback, and simplified Fallback voting rules, even when we have only one manipulator and the number of undetermined pairs in each vote is no more than 16. Proof. We reduce the X3C problem to W EAK M ANIPULATION for simplified Bucklin. Let (U = {u1 , . . . , um }, S := {S1 , S2 , . . . , St }) be an instance of X3C, where each Si is a subset of U of size three. We construct a W EAK M ANIPULATION instance based on (U, S) as follows. Candidate set: C = W ∪ X ∪ D ∪ U ∪ {c, w, a, b}, where |W| = m − 3, |X| = 4, |D| = m + 1 We first introduce the following partial votes P in correspondence with the sets in the family as follows. W  X  Si  c  (U \ Si )  D \ ({X × ({c} ∪ Si )}) , ∀i 6 t 12 Notice that the number of undetermined pairs in every vote in P is 16. We introduce the following additional complete votes Q: B t copies of U  c  others B m/3 − 1 copies of U  a  c  others B m/3 + 1 copies of D  b  others The total number of voters, including the manipulator, is 2t + 2m/3 + 1. Now we show equivalence of the two instances. In the forward direction, suppose we have an exact set cover T ⊂ S. Let the vote of the manipulator v be c  D  others. We consider the following extension P of P. W  Si  c  X  (U \ Si )  D On the other hand, if Si ∈ S \ T, then we have: W  X  Si  c  (U \ Si )  D We claim that c is the unique simplified Bucklin winner in the profile (P, W, v). Notice that the simplified Bucklin score of c is m + 1 in this extension, since it appears in the top m + 1 positions in the m/3 votes corresponding to the set cover, t votes from the complete profile Q and one vote v of the manipulator. For any other candidate ui ∈ U, ui appears in the top m + 1 positions once in P and t + m 3 − 1 times in Q. Thus, ui does not get majority in top m + 1 positions making its simplified Bucklin score at least m + 2. Hence, c is the unique simplified Bucklin winner in the profile (P, W, v). Similarly, the candidate w1 appears only t times in the top m + 1 positions. The same can be argued for the remaining candidates in D, W, and w. In the reverse direction, suppose the W EAK M ANIPULATION is a Y ES instance. We may assume without loss of generality that the manipulator’s vote v is c  D  others, since the simplified Bucklin score of the candidates in D is at least 2m. Let P be the extension of P such that c is the unique winner in the profile (P, Q, v). As every candidate in W is ranked within top m + 2 positions m in t + m 3 + 1 votes in Q, for c to win, c  X must hold in at least 3 votes in P. In those votes, all the candidates in Si are also within top m + 2 positions. Now if any candidate in U is within top m + 1 positions in P more than once, then c will not be the unique winner. Hence, the Si ’s corresponding to the votes where c  X in P form an exact set cover. The reduction above also works for the Bucklin voting rule. Specifically, the argument for the forward direction is exactly the same as the simplified Bucklin above and the argument for the reverse direction is as follows. Every candidate in W is ranked within top m + 2 positions in t+ m 3 + 1 votes in Q and c is never placed within top m + 2 positions in any vote in Q. Hence, for c to win, c  X must hold in at least m 3 votes in P. In those votes, all the candidates in Si are also within top m positions. Notice that c never gets placed within top m positions in any vote in (P, Q). Now if any candidate x ∈ U is within top m positions in P more than once, then x gets majority within top m positions and thus c cannot win. The result for the Fallback and simplified Fallback voting rules follow from the corresponding results for the Bucklin and simplified Bucklin voting rules respectively since every Bucklin and simplified Bucklin election is also a Fallback and simplified Fallback election respectively. 13 3.2 Strong Manipulation We know that the C OALITIONAL M ANIPULATION problem is NP-complete for the Borda, maximin, and Copelandα voting rules for every rational α ∈ [0, 1] \ {0.5}, when we have two manipulators. Thus, it follows from Observation 2 that S TRONG M ANIPULATION is NP-hard for Borda, maximin, and Copelandα voting rules for every rational α ∈ [0, 1] \ {0.5} for at least two manipulators. For the case of one manipulator, S TRONG M ANIPULATION turns out to be polynomial-time solvable for most other voting rules. For Copelandα , however, we show that the problem is co-NP-hard for every α ∈ [0, 1] for a single manipulator, even when the number of undetermined pairs in each vote is bounded by a constant. This is achieved by a careful reduction from X3C. The following lemma has been used before [McG53]. Lemma 2. For any function f : C × C −→ Z, such that 1. ∀a, b ∈ C, f(a, b) = −f(b, a). 2. ∀a, b, c, d ∈ C, f(a, b) + f(c, d) is even, there exists a n-voters’ profile such that for all a, b ∈ C, a defeats b with a margin of f(a, b). Moreover,   X n is even and n = O  |f(a, b)| {a,b}∈C×C We have following intractability result for the S TRONG M ANIPULATION problem for the Copelandα rule with one manipulator and at most 10 undetermined pairs per vote. Theorem 4. S TRONG M ANIPULATION is co-NP-hard for Copelandα voting rule for every α ∈ [0, 1] even when we have only one manipulator and the number of undetermined pairs in each vote is no more than 10. Proof. We reduce X3C to S TRONG M ANIPULATION for Copelandα rule. Let (U = {u1 , . . . , um }, S = {S1 , S2 , . . . , St }) is an X3C instance. We assume, without loss of generality, t to be an even integer (if not, replicate any set from S). We construct a corresponding W EAK M ANIPULATION instance for Copelandα as follows. Candidate set C = U ∪ {c, w, z, d} Partial votes P: ∀i 6 t, (U \ Si )  c  z  d  Si  w \ {{z, c} × (Si ∪ {d, w})} Notice that the number of undetermined pairs in every vote in P is 10. Now we add a set Q of complete votes with |Q| even and |Q| = poly(m, t) using Lemma 2 to achieve the following margin of victories in pairwise elections. Figure 2 shows the weighted majority graph of the resulting election. B DQ (d, z) = DQ (z, c) = DQ (c, d) = DQ (w, z) = 4t B DQ (ui , d) = DQ (c, ui ) = 4t ∀ui ∈ U B DQ (z, ui ) = t ∀ui ∈ U 14 B DQ (c, w) = t − B DQ (ui , ui+1 2m 3 −2 (mod ∗)m ) = 4t ∀ui ∈ U B DQ (a, b) = 0 for every a, b ∈ C, a 6= b, not mentioned above d 4t uj 4t uj+1 w 4t 4t t 4t t− c 2m 3 4t −2 4t z Figure 2: Weighted majority graph of the reduced instance in Theorem 4. The weight of all the edges not shown in the figure are 0. For simplicity, we do not show edges among {u1 , . . . , um }. We have only one manipulator who tries to make c winner. Notice that the number of votes in the S TRONG M ANIPULATION instance (P ∪ Q, 1, c) including the manipulator’s vote is odd (since |P| and |Q| are even integers). Therefore, DP∗ ∪Q∪{v∗ } (a, b) is never zero for every a, b ∈ C, a 6= b in every extension P∗ of P and manipulators vote v∗ and consequently the particular value of α does not play any role in this reduction. Hence, we assume, without loss of generality, α to be zero from here on and simply use the term Copeland instead of Copelandα . Now we show that the X3C instance (U, S) is a Y ES instance if and only if the S TRONG M ANIPU LATION instance (P ∪ Q, 1, c) is a N O instance (a S TRONG M ANIPULATION instance is a N O instance if there does not exist a vote of the manipulator which makes c the unique winner in every extension of the partial votes). We can assume without loss of generality that manipulator puts c at first position and z at last position in her vote v. Assume that the X3C instance is a Y ES instance. Suppose (by renaming) that S1 , . . . , S m3 forms an exact set cover. We claim that the following extension P of P makes both z and c Copeland co-winners. Extension P of P: m i 6 , (U \ Si )  c  z  d  Si  w 3 m + 1, (U \ Si )  d  Si  w  c  z i> 3 We have summarize the pairwise margins between z and c and the rest of the candidates from the profile (P ∪ Q ∪ v) in Table 2. The candidates z and c are the co-winners with Copeland score (m + 1). 15 C \ {z} DP∪Q∪v (z, ·) C \ {c} DP∪Q∪v (c, ·) c > 3t z, ui ∈ U > 3t w, d 6 −3t w −1 ui ∈ U 1 d 6 −3t Table 2: DP∪Q∪v (z, ·) and DP∪Q∪v (c, ·) For the other direction, notice that Copeland score of c is at least m + 1 since c defeats d and every candidate in U in every extension of P. Also notice that the Copeland score of z can be at most m + 1 since z loses to w and d in every extension of P. Hence the only way c cannot be the unique winner is that z defeats all candidates in U and w defeats c. This requires w  c in at least t− m 3 extensions of P. We claim that the sets Si in the remaining of the extensions where c  w forms an exact set cover for (U, S). Indeed, otherwise some candidate ui ∈ U is not covered. Then, notice that ui  z in all t votes, making D(z, ui ) = −1. 3.3 Opportunistic Manipulation All our reductions for the co-NP-hardness for O PPORTUNISTIC M ANIPULATION start from X3C. We note that all our hardness results hold even when there is only one manipulator. Our overall approach is the following. We engineer a set of partial votes in such a way that the manipulator is forced to vote in a limited number of ways to have any hope of making her favorite candidate win. For each such vote, we demonstrate a viable extension where the vote fails to make the candidate a winner, leading to a N O instance of O PPORTUNISTIC M ANIPULATION. These extensions rely on the existence of an exact cover. On the other hand, we show that if there is no exact set cover, then there is no viable extension, thereby leading to an instance that is vacuously a Y ES instance of O PPORTUNISTIC M ANIPULATION. Our first result on O PPORTUNISTIC M ANIPULATION shows that the O PPORTUNISTIC M ANIPULATION problem is co-NP-hard for the k-approval voting rule for constant k > 3 even when the number of manipulators is one and the number of undetermined pairs in each vote is no more than 15. Theorem 5. The O PPORTUNISTIC M ANIPULATION problem is co-NP-hard for the k-approval voting rule for constant k > 3 even when the number of manipulators is one and the number of undetermined pairs in each vote is no more than 15. Proof. We reduce X3C to O PPORTUNISTIC M ANIPULATION for k-approval rule. Let (U = {u1 , . . . , um }, S = {S1 , S2 , . . . , St }) is an X3C instance. We construct a corresponding O PPORTUNISTIC M ANIPULATION instance for k-approval voting rule as follows. We begin by introducing a candidate for every element of the universe, along with k − 3 dummy candidates (denoted by W), and special candidates {c, z1 , z2 , d, x, y}. Formally, we have: Candidate set C = U ∪ {c, z1 , z2 , d, x, y} ∪ W. Now, for every set Si in the universe, we define the following total order on the candidate set, which we denote by P0i : W  Si  y  z1  z2  x  (U \ Si )  c  d 16 Using P0i , we define the partial vote Pi as follows: Pi = P0i \ ({{y, x, z1 , z2 } × Si } ∪ {(z1 , z2 ), (x, z1 ), (x, z2 )}). We denote the set of partial votes {Pi : i ∈ [t]} by P and {P0i : i ∈ [t]} by P0 . We remark that the number of undetermined pairs in each partial vote Pi is 15. We now invoke Lemma 1 from [DMN16], which allows to achieve any pre-defined scores on the candidates using only polynomially many additional votes. Using this, we add a set Q of complete votes with |Q| = poly(m, t) to ensure the following scores, where we denote the k-approval score of a candidate from a set of votes V by sV (·): sQ (z1 ) = sQ (z2 ) = sQ (y) = sQ (c) − m/3; sQ (d), sQ (w) 6 sQ (c) − 2t ∀w ∈ W; sQ (x) = sQ (c) − 1; sP0 ∪Q (uj ) = sQ (c) + 1 ∀j ∈ [m]. Our reduced instance is (P ∪ Q, 1, c). The reasoning for this score configuration will be apparent as we argue the equivalence. We first argue that if we had a Y ES instance of X3C (in other words, there is no exact cover), then we have a Y ES instance of O PPORTUNISTIC M ANIPULATION. It turns out that this will follow from the fact that there are no viable extensions, because, as we will show next, a viable extension implies the existence of an exact set cover. To this end, first observe that the partial votes are constructed in such a way that c gets no additional score from any extension. Assuming that the manipulator approves c (without loss of generality), the final score of c in any extension is going to be sQ (c) + 1. Now, in any viable extension, every candidate uj has to be “pushed out” of the top k positions at least once. Observe that whenever this happens, y is forced into the top k positions. Since y is behind the score of c by only m/3 votes, Si ’s can be pushed out of place in only m/3 votes. For every uj to lose one point, these votes must correspond to an exact cover. Therefore, if there is no exact cover, then there is no viable extension, showing one direction of the reduction. On the other hand, suppose we have a N O instance of X3C – that is, there is an exact cover. Let {Si : i ∈ [m/3]} forms an exact cover of U. We will now use the exact cover to come up with two viable extensions, both of which require the manipulator to vote in different ways to make c win. Therefore, there is no single manipulative vote that accounts for both extensions, leading us to a N O instance of O PPORTUNISTIC M ANIPULATION. First, consider this completion of the partial votes: i = 1, W  y  x  z1  z2  Si  (U \ Si )  c  d 2 6 i 6 m/3, W  y  z1  z2  x  Si  (U \ Si )  c  d m/3 + 1 6 i 6 t, W  Si  y  z1  z2  x  (U \ Si )  c  d Notice that in this completion, once accounted for along with the votes in Q, the score of c is tied with the scores of all uj ’s, z1 , x and y, while the score of z2 is one less than the score of c. Therefore, the only k candidates that the manipulator can afford to approve are W, the candidates c, d and z2 . However, consider the extension that is identical to the above except with the first vote changed to: W  y  x  z2  z1  Si  (U \ Si )  c  d Here, on the other hand, the only way for c to be an unique winner is if the manipulator approves W, c, d and z1 . Therefore, it is clear that there is no way for the manipulator to provide a consolidated vote for both these profiles. Therefore, we have a N O instance of O PPORTUNISTIC M ANIPULATION. 17 We next move on to the k-veto voting rule and show that the O PPORTUNISTIC M ANIPULATION problem for the k-veto is co-NP-hard for every constant k > 4 even when the number of manipulators is one and the number of undetermined pairs in each vote is no more than 15. Theorem 6. The O PPORTUNISTIC M ANIPULATION problem is co-NP-hard for the k-veto voting rule for every constant k > 4 even when the number of manipulators is one and the number of undetermined pairs in each vote is no more than 15. Proof. We reduce X3C to O PPORTUNISTIC M ANIPULATION for k-veto rule. Let (U = {u1 , . . . , um }, S = {S1 , S2 , . . . , St }) is an X3C instance. We construct a corresponding O PPORTUNISTIC M ANIPULATION instance for k-veto voting rule as follows. Candidate set C = U ∪ {c, z1 , z2 , d, x, y} ∪ A ∪ W, where A = {a1 , a2 , a3 }, |W| = k − 4 For every i ∈ [t], we define P0i as follows: ∀i 6 t, c  A  (U \ Si )  d  Si  y  x  z1  z2  W Using P0i , we define partial vote Pi = P0i \ ({{y, x, z1 , z2 } × Si } ∪ {(z1 , z2 ), (x, z1 ), (x, z2 )}) for every i ∈ [t]. We denote the set of partial votes {Pi : i ∈ [t]} by P and {P0i : i ∈ [t]} by P0 . We note that the number of undetermined pairs in each partial vote Pi is 15. Using Lemma 1, we add a set Q of complete votes with |Q| = poly(m, t) to ensure the following. We denote the k-veto score of a candidate from a set of votes W by sW (·). B sP0 ∪Q (z1 ) = sP0 ∪Q (z2 ) = sP0 ∪Q (c) − m/3 B sP0 ∪Q (ai ) = sP0 ∪Q (uj ) = sP0 ∪Q (w) = sP0 ∪Q (c) ∀ai ∈ A, uj ∈ U, w ∈ W B sP0 ∪Q (y) = sP0 ∪Q (c) − m/3 − 1 B sP0 ∪Q (x) = sP0 ∪Q (c) − 2 We have only one manipulator who tries to make c winner. Now we show that the X3C instance (U, S) is a Y ES instance if and only if the O PPORTUNISTIC M ANIPULATION instance (P ∪ Q, 1, c) is a N O instance. In the forward direction, let us now assume that the X3C instance is a Y ES instance. Suppose (by renaming) that S1 , . . . , Sm/3 forms an exact set cover. Let us assume that the manipulator’s vote v disapproves every candidate in W ∪ A since otherwise c can never win uniquely. We now show that if v does not disapprove z1 then, v is not a c-optimal vote. Suppose v does not disapprove z1 . Then we consider the following extension P of P. i = 1, c  A  (U \ Si )  d  y  z1  x  z2  Si  W 2 6 i 6 m/3, c  A  (U \ Si )  d  y  z1  z2  x  Si  W m/3 + 1 6 i 6 t, c  A  (U \ Si )  d  Si  y  x  z1  z2  W We have the following scores sP∪Q (c) = sP∪Q (z1 ) = sP∪Q (z2 ) + 1 = sP∪Q (x) + 1 = sP∪Q (uj ) + 1 ∀uj ∈ U. Hence, both c and z1 win for the votes P∪Q∪{v}. However, the vote v0 which disapproves a1 , a2 , a3 , z1 makes c a unique winner for the votes P ∪ Q ∪ {v0 }. Hence, v is not a c-optimal vote. Similarly, we can show that if the manipulator’s vote does not disapprove z2 then, the vote is not 18 c-optimal. Hence, there does not exist any c-optimal vote and the O PPORTUNISTIC M ANIPULATION instance is a N O instance. In the reverse direction, we show that if the X3C instance is a N O instance, then there does not exist a vote v of the manipulator and an extension P of P such that c is the unique winner for the votes P ∪ Q ∪ {v0 } thereby proving that the O PPORTUNISTIC M ANIPULATION instance is vacuously Y ES (and thus every vote is c-optimal). Notice that, there must be at least m/3 votes P1 in P where the corresponding Si gets pushed in bottom k positions since sP0 ∪Q (uj ) = sP0 ∪Q (c) ∀ai ∈ A, uj ∈ U. However, in each vote in P1 , y is placed within top m − k many position and thus we have |P1 | is exactly m/3 since sP0 ∪Q (y) = sP0 ∪Q (c) − m/3 − 1. Now notice that there must be at least one candidate u ∈ U which is not covered by the sets Si s corresponding to the votes P1 because the X3C instance is a N O instance. Hence, c cannot win the election uniquely irrespective of the manipulator’s vote. Thus every vote is c-optimal and the O PPORTUNISTIC M ANIPULATION instance is a Y ES instance. We show next similar intractability result for the Borda voting rule too with only at most 7 undetermined pairs per vote. Theorem 7. The O PPORTUNISTIC M ANIPULATION problem is co-NP-hard for the Borda voting rule even when the number of manipulators is one and the number of undetermined pairs in every vote is no more than 7. Proof. We reduce X3C to O PPORTUNISTIC M ANIPULATION for the Borda rule. Let (U = {u1 , . . . , um }, S = {S1 , S2 , . . . , St }) is an X3C instance. Without loss of generality we assume that m is not divisible by 6 (if not, then we add three new elements b1 , b2 , b3 to U and a set {b1 , b2 , b3 } to S). We construct a corresponding O PPORTUNISTIC M ANIPULATION instance for the Borda voting rule as follows. Candidate set C = U ∪ {c, z1 , z2 , d, y} For every i ∈ [t], we define P0i as follows: ∀i 6 t, y  Si  z1  z2  (U \ Si )  d  c Using P0i , we define partial vote Pi = P0i \ ({({y} ∪ Si ) × {z1 , z2 }} ∪ {(z1 , z2 )}) for every i ∈ [t]. We denote the set of partial votes {Pi : i ∈ [t]} by P and {P0i : i ∈ [t]} by P0 . We note that the number of undetermined pairs in each partial vote Pi is 7. Using Lemma 1, we add a set Q of complete votes with |Q| = poly(m, t) to ensure the following. We denote the Borda score of a candidate from a set of votes W by sW (·). B sP0 ∪Q (y) = sP0 ∪Q (c) + m + m/3 + 3 B sP0 ∪Q (z1 ) = sP0 ∪Q (c) − 3bm/6c − 2 B sP0 ∪Q (z2 ) = sP0 ∪Q (c) − 5bm/6c − 3 B sP0 ∪Q (ui ) = sP0 ∪Q (c) + m + 5 − i ∀i ∈ [m] B sP0 ∪Q (d) 6 sP0 ∪Q (c) − 5m 19 We have only one manipulator who tries to make c winner. Now we show that the X3C instance (U, S) is a Y ES instance if and only if the O PPORTUNISTIC M ANIPULATION instance (P∪Q, 1, c) is a N O instance. Notice that we can assume without loss of generality that the manipulator places c at the first position, d at the second position, the candidate ui at (m + 5 − i)th position for every i ∈ [m], and y at the last position, since otherwise c can never win uniquely irrespective of the extension of P (that it, the manipulator’s vote looks like c  d  {z1 , z2 }  um  um−1  · · ·  u1  y). In the forward direction, let us now assume that the X3C instance is a Y ES instance. Suppose (by renaming) that S1 , . . . , Sm/3 forms an exact set cover. Let the manipulator’s vote v be c  d  z1  z2  um  · · ·  u1  y. We now argue that v is not a c-optimal vote. The other case where the manipulator’s vote v0 be c  d  z2  z1  um  · · ·  u1  y can be argued similarly. We consider the following extension P of P. 1 6 i 6 bm/6c, z2  y  Si  z1  (U \ Si )  d  c dm/6e 6 i 6 m/3, z1  y  Si  z2  (U \ Si )  d  c m/3 + 1 6 i 6 t, y  Si  z1  z2  (U \ Si )  d  c We have the following Borda scores sP∪Q∪{v} (c) = sP∪Q∪{v} (y) + 1 = sP∪Q∪{v} (z2 ) + 6 = sP∪Q∪{v} (z1 ) = sP∪Q∪{v} (ui ) + 1 ∀i ∈ [m]. Hence, c does not win uniquely for the votes P ∪ Q ∪ {v}. However, c is the unique winner for the votes P ∪ Q ∪ {v0 }. Hence, there does not exist any c-optimal vote and the O PPORTUNISTIC M ANIPULATION instance is a N O instance. In the reverse direction, we show that if the X3C instance is a N O instance, then there does not exist a vote v of the manipulator and an extension P of P such that c is the unique winner for the votes P ∪ Q ∪ {v0 } thereby proving that the O PPORTUNISTIC M ANIPULATION instance is vacuously Y ES (and thus every vote is c-optimal). Notice that the score of y must decrease by at least m/3 for c to win uniquely. However, in every vote v where the score of y decreases by at least one in any extension P of P, at least one of z1 or z2 must be placed at top position of the vote v. However, the candidates z1 and z2 can be placed at top positions of the votes in P at most m/3 many times while ensuring c does not lose the election. Also, even after manipulator places the candidate ui at (m + 5 − i)th position for every i ∈ [m], for c to win uniquely, the score of every ui must decrease by at least one. Hence, altogether, there will be exactly m/3 votes (denoted by the set P1 ) in any extension of P where y is placed at the second position. However, since the X3C instance is a N O instance, the Si s corresponding to the votes in P1 does not form a set cover. Let u ∈ U be an element not covered by the Si s corresponding to the votes in P1 . Notice that the score of u does not decrease in the extension P and thus c does not win uniquely irrespective of the manipulator’s vote. Thus every vote is c-optimal and thus the O PPORTUNISTIC M ANIPULATION instance is a Y ES instance. Thus every vote is c-optimal and the O PPORTUNISTIC M ANIPULATION instance is a Y ES instance. For the maximin voting rule, we show intractability of O PPORTUNISTIC M ANIPULATION with one manipulator even when the number of undetermined pairs in every vote is at most 8. Theorem 8. The O PPORTUNISTIC M ANIPULATION problem is co-NP-hard for the maximin voting rule even when the number of manipulators is one and the number of undetermined pairs in every vote is no more than 8. 20 Proof. We reduce X3C to O PPORTUNISTIC M ANIPULATION for the maximin rule. Let (U = {u1 , . . . , um }, S = {S1 , S2 , . . . , St }) is an X3C instance. We construct a corresponding O PPORTUNISTIC M ANIPULATION instance for the maximin voting rule as follows. Candidate set C = U ∪ {c, z1 , z2 , z3 , d, x, y} For every i ∈ [t], we define P0i as follows: ∀i 6 t, Si  x  d  y  (U \ Si )  z1  z2  z3 Using P0i , we define partial vote Pi = P0i \ ({({x} ∪ Si ) × {d, y}}) for every i ∈ [t]. We denote the set of partial votes {Pi : i ∈ [t]} by P and {P0i : i ∈ [t]} by P0 . We note that the number of undetermined pairs in each partial vote Pi is 8. We define another partial vote p as follows. p = (z1  z2  z3  others ) \ {(z1 , z2 ), (z2 , z3 ), (z1 , z3 )} Using Lemma 2, we add a set Q of complete votes with |Q| = poly(m, t) to ensure the following pairwise margins (notice that the pairwise margins among z1 , z2 , and z3 does not include the partial vote p). Figure 3 shows the weighted majority graph of the resulting election. B DP0 ∪Q∪{p} (d, c) = 4t + 1 B DP0 ∪Q∪{p} (x, d) = 4t + 2m/3 + 1 B DP0 ∪Q∪{p} (y, x) = 4t − 2m/3 + 1 B DP0 ∪Q∪{p} (d, uj ) = 4t − 1 ∀uj ∈ U B DP0 ∪Q (z1 , z2 ) = DP0 ∪Q (z2 , z3 ) = DP0 ∪Q (z3 , z1 ) = 4t + 2 B |DP0 ∪Q∪{p} (a, b)| 6 1 for every a, b ∈ C not defined above. We have only one manipulator who tries to make c winner. Now we show that the X3C instance (U, S) is a Y ES instance if and only if the O PPORTUNISTIC M ANIPULATION instance (P ∪ Q ∪ {p}, 1, c) is a N O instance. Notice that we can assume without loss of generality that the manipulator’s vote prefers c to every other candidate, y to x, x to d, and d to uj for every uj ∈ U. In the forward direction, let us now assume that the X3C instance is a Y ES instance. Suppose (by renaming) that S1 , . . . , Sm/3 forms an exact set cover. Notice that the manipulator’s vote must prefer either z2 to z1 or z1 to z3 or z3 to z2 . We show that if the manipulator’s vote v prefers z2 to z1 , then v is not a c-optimal vote. The other two cases are symmetrical. Consider the following extension P of P and p of p. 1 6 i 6 m/3, d  y  Si  x  (U \ Si )  z1  z2  z3 m/3 + 1 6 i 6 t, Si  x  d  y  (U \ Si )  z1  z2  z3 p = z2  z3  z1  others From the votes in P ∪ Q ∪ {v, p}, the maximin score of c is −4t, of d, x, uj ∀uj ∈ U are −4t − 2, of z1 , z3 are at most than −4t − 2, and of z2 is −4t. Hence, c is not the unique maximn winner. 21 d 4t − 1 uj z1 4t + 2 4t + 2 z3 4t + 2 z2 4t + 1 4t + 2m/3 + 1 c y x 4t − 2m/3 + 1 Figure 3: Weighted majority graph of the reduced instance in Theorem 8. Solid line and dashed line represent pairwise margins in P0 ∪Q∪{p} and P0 ∪Q respectively. The weight of all the edges not shown in the figure are within −1 to 1. For simplicity, we do not show edges among {u1 , . . . , um }. However, the manipulator’s vote c  z1  z2  z3  other makes c the unique maximin winner. Hence, v is not a c-optimal vote. For the reverse direction, we show that if the X3C instance is a N O instance, then there does not exist a vote v of the manipulator and an extension P of P such that c is the unique winner for the votes P ∪ Q ∪ {v0 } thereby proving that the O PPORTUNISTIC M ANIPULATION instance is vacuously Y ES (and thus every vote is c-optimal). Consider any extension P of P. Notice that, for c to win uniquely, y  x must be at least m/3 of the votes in P; call these set of votes P1 . However, d  x in every vote in P1 and d  x can be in at most m/3 votes in P for c to win uniquely. Hence, we have |P1 | = m/3. Also for c to win, each d  uj must be at least one vote of P and d  uj is possible only in the votes in P1 . However, the sets Si s corresponding to the votes in P1 does not form a set cover since the X3C instance is a N O instance. Hence, there must exist a uj ∈ U for which uj  d in every vote in P and thus c cannot win uniquely irrespective of the vote of the manipulator. Thus every vote is c-optimal and the O PPORTUNISTIC M ANIPULATION instance is a Y ES instance. Our next result proves that the O PPORTUNISTIC M ANIPULATION problem is co-NP-hard for the Copelandα voting rule too for every α ∈ [0, 1] even with one manipulator and at most 8 undetermined pairs per vote. Theorem 9. The O PPORTUNISTIC M ANIPULATION problem is co-NP-hard for the Copelandα voting rule for every α ∈ [0, 1] even when the number of manipulators is one and the number of undetermined pairs in each vote is no more than 8. Proof. We reduce X3C to O PPORTUNISTIC M ANIPULATION for the Copelandα voting rule. Let (U = {u1 , . . . , um }, S = {S1 , S2 , . . . , St }) is an X3C instance. We construct a corresponding O PPORTUNISTIC M ANIPULATION instance for the Copelandα voting rule as follows. Candidate set C = U ∪ {c, z1 , z2 , z3 , d1 , d2 , d3 , x, y} For every i ∈ [t], we define P0i as follows: 22 ∀i 6 t, Si  x  y  c  others Using P0i , we define partial vote Pi = P0i \({({x}∪Si )×{c, y}}) for every i ∈ [t]. We denote the set of partial votes {Pi : i ∈ [t]} by P and {P0i : i ∈ [t]} by P0 . We note that the number of undetermined pairs in each partial vote Pi is 8. We define another partial vote p as follows. p = (z1  z2  z3  others ) \ {(z1 , z2 ), (z2 , z3 ), (z1 , z3 )} Using Lemma 2, we add a set Q of complete votes with |Q| = poly(m, t) to ensure the following pairwise margins (notice that the pairwise margins among z1 , z2 , and z3 does not include the partial vote p). Figure 4 shows the weighted majority graph of the resulting election. B DP0 ∪Q∪{p} (uj , c) = 2 ∀uj ∈ U B DP0 ∪Q∪{p} (x, y) = 2m/3 B DP0 ∪Q∪{p} (c, y) = DP0 ∪Q∪{p} (x, c) = DP0 ∪Q∪{p} (di , c) = DP0 ∪Q∪{p} (zk , c) DP0 ∪Q∪{p} (uj , x) = DP0 ∪Q∪{p} (x, zk ) = DP0 ∪Q∪{p} (di , x) = DP0 ∪Q∪{p} (y, uj ) DP0 ∪Q∪{p} (di , y) = DP0 ∪Q∪{p} (y, zk ) = DP0 ∪Q∪{p} (zk , uj ) = DP0 ∪Q∪{p} (uj , di ) DP0 ∪Q∪{p} (zk , d1 ) = DP0 ∪Q∪{p} (zk , d2 ) = DP0 ∪Q∪{p} (d3 , zk ) = 4t ∀i, k ∈ [3], j ∈ [m] = = = B DP0 ∪Q∪{p} (uj , u` ) = −4t for at least m/3 many u` ∈ U B DP0 ∪Q (z1 , z2 ) = DP0 ∪Q (z2 , z3 ) = DP0 ∪Q (z3 , z1 ) = 1 B |DP0 ∪Q∪{p} (a, b)| 6 1 for every a, b ∈ C not defined above. We have only one manipulator who tries to make c winner. Now we show that the X3C instance (U, S) is a Y ES instance if and only if the O PPORTUNISTIC M ANIPULATION instance (P ∪ Q ∪ {p}, 1, c) is a N O instance. Since the number of voters is odd, α does not play any role in the reduction and thus from here on we simply omit α. Notice that we can assume without loss of generality that the manipulator’s vote prefers c to every other candidate and x to y. In the forward direction, let us now assume that the X3C instance is a Y ES instance. Suppose (by renaming) that S1 , . . . , Sm/3 forms an exact set cover. Suppose the manipulator’s vote v order z1 , z2 , and z3 as z1  z2  z3 . We will show that v is not a c-optimal vote. Symmetrically, we can show that the manipulator’s vote ordering z1 , z2 , and z3 in any other order is not c-optimal. Consider the following extension P of P and p of p. 1 6 i 6 m/3, y  c  Si  x  others m/3 + 1 6 i 6 t, Si  x  y  c  others p = z1  z2  z3  others From the votes in P ∪ Q ∪ {v, p}, the Copeland score of c is m + 4 (defeating y, zk , uj ∀k ∈ [3], j ∈ [m]), of y is m+3 (defeating zk , uj ∀k ∈ [3], j ∈ [m]), of uj is at most 2m/3+4 (defeating x, di ∀i ∈ [3] and at most 2m/3 many u` ∈ U), of x is 5 (defeating c, y, zk ∀l ∈ [3]), of d1 , d2 is 2 (defeating y and c), of d3 is 5 (defeating y, c, zk ∀k ∈ [3]). of z3 is m + 3 (defeating di , uj ∀i ∈ [3], j ∈ [m]) for every k ∈ [3], of z3 is m + 2 (defeating d1 , d2 , uj i ∈ [3], j ∈ [m]), z2 is m + 3 (defeating 23 uj z1 1 2 z2 y c 1 z3 d1 2m/3 x d2 d3 1 Figure 4: Weighted majority graph of the reduced instance in Theorem 9. Solid line and dashed line represent pairwise margins in P0 ∪ Q ∪ {p} and P0 ∪ Q respectively. The weight of all the edges not shown in the figure are within −1 to 1. The weight of all unlabeled edges are 4t. For simplicity, we do not show edges among {u1 , . . . , um }. 24 d1 , d2 , z3 , uj i ∈ [3], j ∈ [m]), z1 is m + 4 (defeating d1 , d2 , z2 , z3 , uj i ∈ [3], j ∈ [m]). Hence, c co-wins with z1 with Copeland score m + 4. However, the manipulator’s vote c  z3  z2  z1 makes c win uniquely. Hence, v is not a c-optimal vote and thus the O PPORTUNISTIC M ANIPULATION instance is a N O instance. For the reverse direction, we show that if the X3C instance is a N O instance, then there does not exist a vote v of the manipulator and an extension P of P such that c is the unique winner for the votes P ∪ Q ∪ {v0 } thereby proving that the O PPORTUNISTIC M ANIPULATION instance is vacuously Y ES (and thus every vote is c-optimal). Consider any extension P of P. Notice that, for c to win uniquely, c must defeat each uj ∈ U and thus c is preferred over uj in at least one vote in P; we call these votes P1 . However, in every vote in P1 , y is preferred over x and thus |P1 | 6 m/3 because x must defeat y for c to win uniquely. Since the X3C instance is a N O instance, there must be a candidate u ∈ U which is not covered by the sets corresponding to the votes in P1 and thus u is preferred over c in every vote in P. Hence, c cannot win uniquely irrespective of the vote of the manipulator. Thus every vote is c-optimal and the O PPORTUNISTIC M ANIPULATION instance is a Y ES instance. For the Bucklin and simplified Bucklin voting rules, we show intractability of the O PPORTUNIS TIC M ANIPULATION problem with at most 15 undetermined pairs per vote and only one manipulator. Theorem 10. The O PPORTUNISTIC M ANIPULATION problem is co-NP-hard for the Bucklin and simplified Bucklin voting rules even when the number of manipulators is one and the number of undetermined pairs in each vote is no more than 15. Proof. We reduce X3C to O PPORTUNISTIC M ANIPULATION for the Bucklin and simplified Bucklin voting rules. Let (U = {u1 , . . . , um }, S = {S1 , S2 , . . . , St }) is an X3C instance. We assume without loss of generality that m is not divisible by 6 (if not, we introduce three elements in U and a set containing them in S) and t is an even integer (if not, we duplicate any set in S). We construct a corresponding O PPORTUNISTIC M ANIPULATION instance for the Bucklin and simplified Bucklin voting rules as follows. Candidate set C = U ∪ {c, z1 , z2 , x1 , x2 , d} ∪ W, where |W| = m − 3 For every i ∈ [t], we define P0i as follows: ∀i 6 t, (U \ Si )  Si  d  x1  x2  z1  z2  others P0i , Using we define partial vote Pi = P0i \ ({({d} ∪ Si ) × {x1 , x2 , z1 , z2 }} ∪ {(z1 , z2 )}) for every i ∈ [t]. We denote the set of partial votes {Pi : i ∈ [t]} by P and {P0i : i ∈ [t]} by P0 . We note that the number of undetermined pairs in each partial vote Pi is 15. We introduce the following additional complete votes Q: B t/2 − bm/6c − 1 copies of W  z1  z2  x1  c  others B t/2 − bm/6c − 1 copies of W  z1  z2  x2  c  others B 2dm/6e copies of W  z1  z2  d  c  others B bm/6c copies of W  z1  d  x1  c  others B bm/6c copies of W  z1  d  x2  c  others 25 B 2dm/6e − 1 copies of U  x1  others B One U  c  others We have only one manipulator who tries to make c winner. Now we show that the X3C instance (U, S) is a Y ES instance if and only if the O PPORTUNISTIC M ANIPULATION instance (P∪Q, 1, c) is a N O instance. The total number of voters in the O PPORTUNISTIC M ANIPULATION instance is 2t + 2m/3 + 1. We notice that within top m + 1 positions of the votes in P0 ∪ Q, c appears t + m/3 times, z1 and z2 appear t + bm/6c times, x1 appears t/2 + m/3 − 1 times, x2 appears t/2 − 1 times, every candidate in W appears t + m/3 − 1 times, every candidate in U appears t + m/3 + 1 times. Also every candidate in U appears t + m/3 + 1 times within top m positions of the votes in P ∪ Q. Hence, for both Bucklin and simplified Bucklin voting rules, we can assume without loss of generality that the manipulator puts c, every candidate in W, x1 , x2 , and exactly one of z1 and z2 . In the forward direction, let us now assume that the X3C instance is a Y ES instance. Suppose (by renaming) that S1 , . . . , Sm/3 forms an exact set cover. Suppose the manipulator’s vote v puts c, every candidate in W, x1 , x2 , and z1 within top m + 1 positions. We will show that v is not c-optimal. The other case where the manipulator’s vote v0 puts c, every candidate in W, x1 , x2 , and z2 within top m + 1 positions is symmetrical. Consider the following extension P of P: 1 6 i 6 bm/6c, (U \ Si )d  x1  x2  z2  Si  z1  others dm/6e 6 i 6 m/3, (U \ Si )d  x1  x2  z1  Si  z2  others m/3 + 1 6 i 6 t, (U \ Si )  Si  d  x1  x2  z1  z2  others For both Bucklin and simplified Bucklin voting rules, c co-wins with z1 for the votes in P ∪ Q ∪ {v}. However, c wins uniquely for the votes in P ∪ Q ∪ {v0 }. Hence, v is not a c-optimal vote and thus the O PPORTUNISTIC M ANIPULATION instance is a N O instance. For the reverse direction, we show that if the X3C instance is a N O instance, then there does not exist a vote v of the manipulator and an extension P of P such that c is the unique winner for the votes P ∪ Q ∪ {v0 } thereby proving that the O PPORTUNISTIC M ANIPULATION instance is vacuously Y ES (and thus every vote is c-optimal). Consider any extension P of P. Notice that, for c to win uniquely, every candidate must be pushed out of top m + 1 positions in at least one vote in P; we call these set of votes P1 . Notice that, |P1 | > m/3. However, in every vote in P1 , at least one of z1 and z2 appears within top m + 1 many positions. Since, the manipulator has to put at least one of z1 and z2 within its top m + 1 positions and z1 and z2 appear t + bm/6c times in the votes in P0 ∪ Q, we must have |P1 | 6 m/3 and thus |P1 | = m/3, for c to win uniquely. However, there exists a candidate u ∈ U not covered by the Si s corresponding to the votes in P1 . Notice that u gets majority within top m positions of the votes and c can never get majority within top m + 1 positions of the votes. Hence, c cannot win uniquely irrespective of the vote of the manipulator. Thus every vote is c-optimal and the O PPORTUNISTIC M ANIPULATION instance is a Y ES instance. 4 Polynomial Time Algorithms We now turn to the polynomial time cases depicted in Table 1. This section is organized in three parts, one for each problem considered. 26 4.1 Weak Manipulation Since the P OSSIBLE W INNER problem is in P for the plurality and the veto voting rules [BD09], it follows from Observation 1 that the W EAK M ANIPULATION problem is in P for the plurality and veto voting rules for any number of manipulators. Proposition 1. The W EAK M ANIPULATION problem is in P for the plurality and veto voting rules for any number of manipulators. Proof. The P OSSIBLE W INNER problem is in P for the plurality and the veto voting rules [BD09]. Hence, the result follows from Observation 1. 4.2 Strong Manipulation We now discuss our algorithms for the S TRONG M ANIPULATION problem. The common flavor in all our algorithms is the following: we try to devise an extension that is as adversarial as possible for the favorite candidate c, and if we can make c win in such an extension, then roughly speaking, such a strategy should work for other extensions as well (where the situation only improves for c). However, it is challenging to come up with an extension that is globally dominant over all the others in the sense that we just described. So what we do instead is we consider every potential nemesis w who might win instead of c, and we build profiles that are “as good as possible” for w and “as bad as possible” for c. Each such profile leads us to constraints on how much the manipulators can afford to favor w (in terms of which positions among the manipulative votes are safe for w). We then typically show that we can determine whether there exists a set of votes that respects these constraints, either by using a greedy strategy or by an appropriate reduction to a flow problem. We note that the overall spirit here is similar to the approaches commonly used for solving the N ECESSARY W INNER problem, but as we will see, there are non-trivial differences in the details. We begin with the k-approval and k-veto voting rules. Theorem 11. The S TRONG M ANIPULATION problem is in P for the k-approval and k-veto voting rules, for any k and any number of manipulators. Proof. For the time being, we just concentrate on non-manipulators’ votes. For each candidate 0 0 c0 ∈ C \ {c}, calculate the maximum possible value of smax NM (c, c ) = sNM (c ) − sNM (c) from nonmanipulators’ votes, where sNM (a) is the score that candidate a receives from the votes of the non-manipulators. This can be done by checking all 4 possible score combinations that c and c0 can get in each vote v and choosing the one which maximizes sv (c0 ) − sv (c) from that vote. We now fix the position of c at the top position for the manipulators’ votes and we check if it is possible to place 0 0 other candidates in the manipulators’ votes such that the final value of smax NM (c, c )+sM (c )−sM (c) is negative which can be solved easily by reducing it to the max flow problem which is polynomial time solvable. We now prove that the S TRONG M ANIPULATION problem for scoring rules is in P for one manipulator. Theorem 12. The S TRONG M ANIPULATION problem is in P for any scoring rule when we have only one manipulator. 27 0 Proof. For each candidate c0 ∈ C \ {c}, calculate smax NM (c, c ) using same technique described in the proof of Theorem 11. We now put c at the top position of the manipulator’s vote. For each candidate c0 ∈ C \ {c}, c0 can be placed at positions i ∈ {2, . . . , m} in the manipulator’s vote which 0 makes smax NM (c, c ) + αi − α1 negative. Using this, construct a bipartite graph with C \ {c} on left and {2, . . . , m} on right and there is an edge between c0 and i iff the candidate c0 can be placed at i in the manipulator’s vote according to the above criteria. Now solve the problem by finding existence of perfect matching in this graph. Our next result proves that the S TRONG M ANIPULATION problem for the Bucklin, simplified Bucklin, Fallback, and simplified Fallback voting rules are in P. Theorem 13. The S TRONG M ANIPULATION problem is in P for the Bucklin, simplified Bucklin, Fallback, and simplified Fallback voting rules, for any number of manipulators. Proof. Let (C, P, M, c) be an instance of S TRONG M ANIPULATION for simplified Bucklin, and let m denote the total number of candidates in this instance. Recall that the manipulators have to cast their votes so as to ensure that the candidate c wins in every possible extension of P. We use Q to denote the set of manipulating votes that we will construct. To begin with, without loss of generality, the manipulators place c in the top position of all their votes. We now have to organize the positioning of the remaining candidates across the votes of the manipulators to ensure that c is a necessary winner of the profile (P, Q). To this end, we would like to develop a system of constraints indicating the overall number of times that we are free to place a candidate w ∈ C \ {c} among the top ` positions in the profile Q. In particular, let us fix w ∈ C \ {c} and 2 6 ` 6 m. Let ηw,` be the maximum number of votes of Q in which w can appear in the top ` positions. Our first step is to compute necessary conditions for ηw,` . We use Pw,` to denote a set of complete votes that we will construct based on the given partial votes. Intuitively, these votes will represent the “worst” possible extensions from the point of view of c when pitted against w. These votes are engineered to ensure that the manipulators can make c win the elections Pw,` for all w ∈ C \ {c} and ` ∈ {2, . . . , m}, if, and only if, they can strongly manipulate in favor of c. More formally, there exists a voting profile Q of the manipulators so that c wins the election Pw,` ∪ Q, for all w ∈ C \ {c} and ` ∈ {2, . . . , m} if and only if c wins in every extension of the profile P ∪ Q. We now describe the profile Pw,` . The construction is based on the following case analysis, where our goal is to ensure that, to the extent possible, we position c out of the top ` − 1 positions, and incorporate w among the top ` positions. B Let v ∈ P be such that either c and w are incomparable or w  c. We add the complete vote v0 to Pw,` , where v0 is obtained from v by placing w at the highest possible position and c at the lowest possible position, and extending the remaining vote arbitrarily. B Let v ∈ P be such that c  w, but there are at least ` candidates that are preferred over w in v. We add the complete vote v0 to Pw,` , where v0 is obtained from v by placing c at the lowest possible position, and extending the remaining vote arbitrarily. B Let v ∈ P be such that c is forced to be within the top ` − 1 positions, then we add the complete vote v0 to Pw,` , where v0 is obtained from v by first placing w at the highest possible position followed by placing c at the lowest possible position, and extending the remaining vote arbitrarily. 28 B In the remaining votes, notice that whenever w is in the top ` positions, c is also in the top ` − 1 positions. Let P∗w,` denote this set of votes, and let t be the number of votes in P∗w,` . We now consider two cases. Let d` (c) be the number of times c is placed in the top ` − 1 positions in the profile Pw,` ∪ Q, and let d` (w) be the number of times w is placed in the top ` positions in the profile Pw,` . Let us now formulate the requirement that in Pw,` ∪ Q, the candidate c does not have a majority in the top ` − 1 positions and w does have a majority in the top ` positions. Note that if this requirement holds for any w and `, then strong manipulation is not possible. Therefore, to strongly manipulate in favor of c, we must ensure that for every choice of w and `, we are able to negate the conditions that we derive. The first condition from above simply translates to d` (c) 6 n/2. The second condition amounts to requiring first, that there are at least n/2 votes where w appears in the top ` positions, that is, d` (w) + ηw,` + t > n/2. Further, note that the gap between d` (w) + ηw,` and majority will be filled by using votes from P∗w,` to “push” w forward. However, these votes contribute equally to w and c being in the top ` and ` − 1 positions, respectively. Therefore, the difference between d` (w) + ηw,` and n/2 must be less than the difference between d` (c) and n/2. Summarizing, the following conditions, which we collectively denote by (?), are sufficient to defeat c in some extension: d` (c) 6 n/2, d` (w) + ηw,` + t > n/2, n/2 − d` (w) + ηw,` < n/2 − d` (c). From the manipulator’s point of view, the above provides a set of constraints to be satisfied as they place the remaining candidates across their votes. Whenever d` (c) > n/2, the manipulators place any of the other candidates among the top ` positions freely, because c already has majority. On the other hand, if d` (c) 6 n/2, then the manipulators must respect at least one of the following constraints: ηw,` 6 n/2 − t − d` (w) and ηw,` 6 d` (c) − d` (w). Extending the votes of the manipulator while respecting these constraints (or concluding that this is impossible to do) can be achieved by a natural greedy strategy — construct the manipulators’ votes by moving positionally from left to right. For each position, consider each manipulator and populate her vote for that position with any available candidate. We output the profile if the process terminates by completing all the votes, otherwise, we say N O. We now argue the proof of correctness. Suppose the algorithm returns N O. This implies that there exists a choice of w ∈ C \ {c} and ` ∈ {2, . . . , m} such that for any voting profile Q of the manipulators, the conditions in (?) are satisfied. (Indeed, if there exists a voting profile that violated at least one of these conditions, then the greedy algorithm would have discovered it.) Therefore, no matter how the manipulators cast their vote, there exists an extension where c is defeated. In particular, for the votes in P \ P∗w,` , this extension is given by Pw,` . Further, we choose n/2 − ηw,` − d` (w) votes among the votes in P∗w,` and extend them by placing w in the top ` positions (and extending the rest of the profile arbitrary). We extend the remaining votes in P∗w,` by positioning w outside the top ` positions. Clearly, in this extension, c fails to achieve majority in the top ` − 1 positions while w does achieve majority in the top ` positions. On the other hand, if the algorithm returns Y ES, then consider the voting profile of the manipulators. We claim that c wins in every extension of P ∪ Q. Suppose, to the contrary, that there exists an extension R and a candidate w such that the simplified Bucklin score of c is no more than the simplified Bucklin score of w in R. In this extension, therefore, there exists ` ∈ {2, . . . , m} for which w attains majority in the top ` positions and c fails to attain majority in the top ` − 1 positions. However, note that this is already impossible in any extension of the profile Pw,l ∪ P∗w,` , because of the design of the constraints. By construction, the number of votes in which c appears in the top ` − 1 positions in R is only greater than the number of times c appears in the top ` − 1 positions in 29 any extension of Pw,l ∪ P∗w,` (and similarly for w). This leads us to the desired contradiction. For the Bucklin voting rule, we do the following modifications to the algorithm. If d` (c) > d` (w) for some w ∈ C \ {c} and ` < m, then we make ηw,` = ∞. The proof of correctness for the Bucklin voting rule is similar to the proof of correctness for the simplified Bucklin voting rule above. For Fallback and simplified Fallback voting rules, we consider the number of candidates each voter approves while computing ηw,` . We output Y ES if and only if ηw,` > 0 for every w ∈ C \ {c} and every ` 6 m, since we can assume, without loss of generality, that the manipulator approves the candidate c only. Again the proof of correctness is along similar lines to the proof of correctness for the simplified Bucklin voting rule. We next show that the S TRONG M ANIPULATION problem for the maximin voting rule is polynomial-time solvable when we have only one manipulator. Theorem 14. The S TRONG M ANIPULATION problem for the maximin voting rules are in P, when we have only one manipulator. Proof. For the time being, just concentrate on non-manipulators’ votes. Using the algorithm for NW for maximin in [XC11], we compute for all pairs w, w0 ∈ C, N(w,w0 ) (w, d) and N(w,w0 ) (c, w0 ) for all d ∈ C \ {c}. This can be computed in polynomial time. Now we place c at the top position in the manipulator’s vote and increase all N(w,w0 ) (c, w0 ) by one. Now we place a candidate w at the second position if for all w0 ∈ C, N0(w,w0 ) (w, d) < N(w,w0 ) (c, w0 ) for all d ∈ C \ {c}, where N0(w,w0 ) (w, d) = N(w,w0 ) (w, d) of the candidate d has already been assigned some position in the manipulator’s vote, and N0(w,w0 ) (w, d) = N(w,w0 ) (w, d) + 1 else. The correctness argument is in the similar lines of the classical greedy manipulation algorithm of [BITT89]. 4.3 Opportunistic Manipulation For the plurality, Fallback, and simplified Fallback voting rules, it turns out that the voting profile where all the manipulators approve only c is a c-opportunistic voting profile, and therefore it is easy to devise a manipulative vote. Observation 4. The O PPORTUNISTIC M ANIPULATION problem is in P for the plurality and Fallback voting rules for a any number of manipulators. For the veto voting rule, however, a more intricate argument is needed, that requires building a system of constraints and a reduction to a suitable instance of the maximum flow problem in a network, to show polynomial time tractability of O PPORTUNISTIC M ANIPULATION. Theorem 15. The O PPORTUNISTIC M ANIPULATION problem is in P for the veto voting rule for a constant number of manipulators. Proof. Let (P, `, c) be an input instance of O PPORTUNISTIC M ANIPULATION. We may assume without loss of generality that the manipulators approve P c. We view the voting profile of the manipulators as a tuple (na )a∈C\{c} ∈ (N ∪ {0})m−1 with a∈C\{c} na = `, where the na many manipulators disapprove a. We denote the set of such tuples as T and we have |T| = O((2m)` ) which is polynomial in m since ` is a constant. A tuple (na )a∈C\{c} ∈ T is not c-optimal if there exists another tuple (n0a )a∈C\{c} ∈ T and an extension P of P with the following properties. We denote the veto score of a candidate from P by s(·). For every candidate a ∈ C \ {c}, we define two quantities w(a) and d(a) as follows. 30 B s(c) > s(a) for every a ∈ C \ {c} with na = n0a = 0 and we define w(a) = s(c) − 1, d(a) = 0 B s(c) > s(a)−n0a for every a ∈ C\{c} with na > n0a and we define w(a) = s(c)−n0a −1, d(a) = 0 B s(a) − na > s(c) > s(a) − n0a for every a ∈ C \ {c} with na < n0a and we define w(a) = s(c) − n0a , d(a) = s(a) − na We guess the value of s(c). Given a value of s(c), we check the above two conditions by reducing this to a max flow problem instance as follows. We have a source vertex s and a sink t. We have a vertex for every a ∈ C (call this set of vertices Y) and a vertex for every vote v ∈ P (call this set of vertices X). We add an edge from s to each in X of capacity one. We add an edge of capacity one from a vertex x ∈ X to a vertex y ∈ Y if the candidate corresponding to the vertex y can be placed at the last position in an extension of the partial vote corresponding to the vertex x. We add an edge from a vertex y to t of capacity w(a), where a is the voter corresponding to the vertex y. We also set the demand of every vertex y d(a) (that is the total amount of flow coming into vertex y must be at least d(a)), where a is the voter corresponding to the vertex y. Clearly, the above three conditions are met if and only if there is a feasible |P| amount of flow in the above flow graph. Since s(c) can have only |P| + 1 possible values (from 0 to P) and |T| = O((2m)` ), we can iterate over all possible pairs of tuples in T and all possible values of s(c) and find a c-optimal voting profile if there exists a one. 5 Conclusion We revisited many settings where the complexity barrier for manipulation was non-existent, and studied the problem under an incomplete information setting. Our results present a fresh perspective on the use of computational complexity as a barrier to manipulation, particularly in cases that were thought to be dead-ends (because the traditional manipulation problem was polynomially solvable). To resurrect the argument of computational hardness, we have to relax the model of complete information, but we propose that the incomplete information setting is more realistic, and many of our hardness results work even with very limited incompleteness of information. Our work is likely to be the starting point for further explorations. To begin with, we leave open the problem of completely establishing the complexity of strong, opportunistic, and weak manipulations for all the scoring rules. Other fundamental forms of manipulation and control do exist in voting, such as destructive manipulation and control by adding candidates. It would be interesting to investigate the complexity of these problems in a partial information setting. Another exciting direction is the study of average case complexity, as opposed to the worst case results that we have pursued. These studies have already been carried out in the setting of complete information [PR06, FP10, Wal10]. Studying the problems that we propose in the averagecase model would reveal further insights on the robustness of the incomplete information setting as captured by our model involving partial orders. Our results showed that the impact of paucity of information on the computational complexity of manipulation crucially depends on the notion of manipulation under consideration. We also argued that different notions of manipulation may be applicable to different situations, maybe based of how optimistic (or pessimistic) the manipulators are. One important direction of future research 31 is to run extensive experimentations on real and synthetic data to know how people manipulate in the absence of complete information. Acknowledgement Palash Dey wishes to gratefully acknowledge support from Google India for providing him with a special fellowship for carrying out his doctoral work. Neeldhara Misra acknowledges support by the INSPIRE Faculty Scheme, DST India (project IFA12-ENG-31). References [BBF10] Yoram Bachrach, Nadja Betzler, and Piotr Faliszewski. Probabilistic possible winner determination. In International Conference on Artificial Intelligence (AAAI), volume 10, pages 697–702, 2010. [BCE+ 15] Felix Brandt, Vincent Conitzer, Ulle Endriss, Jérôme Lang, and Ariel D Procaccia. Handbook of computational social choice, 2015. [BD09] Nadja Betzler and Britta Dorn. Towards a dichotomy of finding possible winners in elections based on scoring rules. In Mathematical Foundations of Computer Science (MFCS), pages 124–136. Springer, 2009. [BFLR12] Dorothea Baumeister, Piotr Faliszewski, Jérôme Lang, and Jörg Rothe. Campaigns for lazy voters: truncated ballots. In International Conference on Autonomous Agents and Multiagent Systems, AAMAS 2012, Valencia, Spain, June 4-8, 2012 (3 Volumes), pages 577–584, 2012. [BIO91] John Bartholdi III and James B. Orlin. Single transferable vote resists strategic voting. Soc. Choice Welf., 8(4):341–354, 1991. [BITT89] John Bartholdi III, C.A. Tovey, and M.A. Trick. The computational difficulty of manipulating an election. Soc. Choice Welf., 6(3):227–241, 1989. [BNW11] Nadja Betzler, Rolf Niedermeier, and Gerhard J Woeginger. Unweighted coalitional manipulation under the borda rule is NP-hard. In IJCAI, volume 11, pages 55–60, 2011. [BRR11] Dorothea Baumeister, Magnus Roos, and Jörg Rothe. Computational complexity of two variants of the possible winner problem. In The 10th International Conference on Autonomous Agents and Multiagent Systems (AAMAS), pages 853–860, 2011. [BRR+ 12] Dorothea Baumeister, Magnus Roos, Jörg Rothe, Lena Schend, and Lirong Xia. The possible winner problem with uncertain weights. In ECAI, pages 133–138, 2012. [BS09] Steven J Brams and M Remzi Sanver. Voting systems that combine approval and preference. In The mathematics of preference, choice and order, pages 215–237. Springer, 2009. 32 [CLMM10] Yann Chevaleyre, Jérôme Lang, Nicolas Maudet, and Jérôme Monnot. Possible winners when new candidates are added: The case of scoring rules. In Proc. International Conference on Artificial Intelligence (AAAI), 2010. [CSL07] Vincent Conitzer, Tuomas Sandholm, and Jérôme Lang. When are elections with few candidates hard to manipulate? J. ACM, 54(3):14, 2007. [CWX11] Vincent Conitzer, Toby Walsh, and Lirong Xia. Dominating manipulations in voting with partial information. In International Conference on Artificial Intelligence (AAAI), volume 11, pages 638–643, 2011. [Dey15] Palash Dey. Computational complexity of fundamental problems in social choice theory. In Proc. 2015 International Conference on Autonomous Agents and Multiagent Systems, pages 1973–1974. International Foundation for Autonomous Agents and Multiagent Systems, 2015. [DKNW11] Jessica Davies, George Katsirelos, Nina Narodytska, and Toby Walsh. Complexity of and algorithms for borda manipulation. In Proc. International Conference on Artificial Intelligence (AAAI), pages 657–662, 2011. [DL13] Ning Ding and Fangzhen Lin. Voting with partial information: what questions to ask? In Proc. 12th International Conference on Autonomous Agents and Multi-agent Systems (AAMAS), pages 1237–1238. International Foundation for Autonomous Agents and Multiagent Systems, 2013. [DMN15a] Palash Dey, Neeldhara Misra, and Y. Narahari. Detecting possible manipulators in elections. In Proc. 2015 International Conference on Autonomous Agents and Multiagent Systems, AAMAS 2015, Istanbul, Turkey, May 4-8, 2015, pages 1441–1450, 2015. [DMN15b] Palash Dey, Neeldhara Misra, and Y. Narahari. Kernelization complexity of possible winner and coalitional manipulation problems in voting. In Proc. 2015 International Conference on Autonomous Agents and Multiagent Systems, AAMAS 2015, Istanbul, Turkey, May 4-8, 2015, pages 87–96, 2015. [DMN16] Palash Dey, Neeldhara Misra, and Y. Narahari. Kernelization complexity of possible winner and coalitional manipulation problems in voting. Theor. Comput. Sci., 616:111– 125, 2016. [DN14] Palash Dey and Y Narahari. Asymptotic collusion-proofness of voting rules: the case of large number of candidates. In Proc. 13th International Conference on Autonomous Agents and Multiagent Systems (AAMAS), pages 1419–1420. International Foundation for Autonomous Agents and Multiagent Systems, 2014. [DN15] Palash Dey and Y Narahari. Asymptotic collusion-proofness of voting rules: The case of large number of candidates. Studies in Microeconomics, 3(2):120–139, 2015. [EE12] Edith Elkind and Gábor Erdélyi. Manipulation under voting rule uncertainty. In Proc. 11th International Conference on Autonomous Agents and Multiagent Systems (AAMAS), pages 627–634. International Foundation for Autonomous Agents and Multiagent Systems, 2012. 33 [ER91] Eithan Ephrati and Jeffrey S Rosenschein. The Clarke tax as a consensus mechanism among automated agents. In Proc. Ninth International Conference on Artificial Intelligence (AAAI), pages 173–178, 1991. [FHH10] Piotr Faliszewski, Edith Hemaspaandra, and Lane A Hemaspaandra. Using complexity to protect elections. Commun ACM, 53(11):74–82, 2010. [FHHR09] Piotr Faliszewski, Edith Hemaspaandra, Lane A. Hemaspaandra, and Jörg Rothe. Llull and copeland voting computationally resist bribery and constructive control. J. Artif. Intell. Res., 35:275–341, 2009. [FHS08] Piotr Faliszewski, Edith Hemaspaandra, and Henning Schnoor. Copeland voting: Ties matter. In Proc. 7th International Conference on Autonomous Agents and Multiagent Systems (AAMAS), pages 983–990. International Foundation for Autonomous Agents and Multiagent Systems, 2008. [FHS10] Piotr Faliszewski, Edith Hemaspaandra, and Henning Schnoor. Manipulation of copeland elections. In Proc. 9th International Conference on Autonomous Agents and Multiagent Systems (AAMAS), pages 367–374. International Foundation for Autonomous Agents and Multiagent Systems, 2010. [FKN08] Ehud Friedgut, Gil Kalai, and Noam Nisan. Elections can be manipulated often. In IEEE 49th Annual IEEE Symposium on Foundations of Computer Science (FOCS), pages 243–249. IEEE, 2008. [FKS03] Ronald Fagin, Ravi Kumar, and D. Sivakumar. Efficient similarity search and classification via rank aggregation. In Proc. 2003 ACM SIGMOD International Conference on Management of Data, SIGMOD ’03, pages 301–312, New York, NY, USA, 2003. ACM. [FP10] Piotr Faliszewski and Ariel D Procaccia. Ai’s war on manipulation: Are we winning? AI Magazine, 31(4):53–64, 2010. [Gib73] Allan Gibbard. Manipulation of voting schemes: a general result. Econometrica, pages 587–601, 1973. [GJ79] Michael R Garey and David S Johnson. Computers and Intractability, volume 174. freeman New York, 1979. [GNNW14] Serge Gaspers, Victor Naroditskiy, Nina Narodytska, and Toby Walsh. Possible and necessary winner problem in social polls. In Proc. 13th International Conference on Autonomous Agents and Multiagent Systems (AAMAS), pages 613–620. International Foundation for Autonomous Agents and Multiagent Systems, 2014. [IKM12] M. Isaksson, G. Kindler, and E. Mossel. The geometry of manipulation - a quantitative proof of the gibbard-satterthwaite theorem. Combinatorica, 32(2):221–250, 2012. [KL05] Kathrin Konczak and Jérôme Lang. Voting procedures with incomplete preferences. In Proc. International Joint Conference on Artificial Intelligence-05 Multidisciplinary Workshop on Advances in Preference Handling, volume 20, 2005. 34 [McG53] David C McGarvey. A theorem on the construction of voting paradoxes. Econometrica, pages 608–610, 1953. [ML15] Vijay Menon and Kate Larson. Complexity of manipulation in elections with partial votes. CoRR, abs/1505.05900, 2015. [NW14] Nina Narodytska and Toby Walsh. The computational impact of partial votes on strategic voting. In Proc. 21st European Conference on Artificial Intelligence, 18-22 August 2014, Prague, Czech Republic - Including Prestigious Applications of Intelligent Systems (PAIS 2014), pages 657–662, 2014. [PHG00] David M. Pennock, Eric Horvitz, and C. Lee Giles. Social choice theory and recommender systems: Analysis of the axiomatic foundations of collaborative filtering. In Proc. Seventeenth National Conference on Artificial Intelligence and Twelfth Conference on on Innovative Applications of Artificial Intelligence, July 30 - August 3, 2000, Austin, Texas, USA., pages 729–734, 2000. [PR06] Ariel D Procaccia and Jeffrey S Rosenschein. Junta distributions and the averagecase complexity of manipulating elections. In Proc. Fifth International Conference on Autonomous Agents and Multiagent Systems (AAMAS), pages 497–504. ACM, 2006. [PR07] Ariel D. Procaccia and Jeffrey S. Rosenschein. Average-case tractability of manipulation in voting via the fraction of manipulators. In Proc. 6th International Joint Conference on Autonomous Agents and Multiagent Systems (AAMAS 2007), Honolulu, Hawaii, USA, May 14-18, 2007, page 105, 2007. [Sat75] Mark Allen Satterthwaite. Strategy-proofness and Arrow’s conditions: Existence and correspondence theorems for voting procedures and social welfare functions. J. Econ. Theory, 10(2):187–217, 1975. [Wal10] Toby Walsh. An empirical study of the manipulability of single transferable voting. In Proc. 19th European Conference on Artificial Intelligence (ECAI), pages 257–262, 2010. [Wal11] Toby Walsh. Where are the hard manipulation problems? J. Artif. Intell. Res., pages 1–29, 2011. [XC08a] Lirong Xia and Vincent Conitzer. Generalized scoring rules and the frequency of coalitional manipulability. In Proc. 9th ACM conference on Electronic Commerce (EC), pages 109–118. ACM, 2008. [XC08b] Lirong Xia and Vincent Conitzer. A sufficient condition for voting rules to be frequently manipulable. In Proc. 9th ACM conference on Electronic Commerce (EC), pages 99–108. ACM, 2008. [XC11] Lirong Xia and Vincent Conitzer. Determining possible and necessary winners under common voting rules given partial orders. volume 41, pages 25–67. AI Access Foundation, 2011. 35 [XZP+ 09] Lirong Xia, Michael Zuckerman, Ariel D Procaccia, Vincent Conitzer, and Jeffrey S Rosenschein. Complexity of unweighted coalitional manipulation under some common voting rules. In Proc. 21st International Joint Conference on Artificial Intelligence (IJCAI), volume 9, pages 348–352, 2009. 36
8 (cs.DS)
Achieving the time of 1-NN, but the accuracy of k-NN arXiv:1712.02369v2 [math.ST] 22 Dec 2017 Lirong Xue Princeton University Abstract We propose a simple approach which, given distributed computing resources, can nearly achieve the accuracy of k-NN prediction, while matching (or improving) the faster prediction time of 1-NN. The approach consists of aggregating denoised 1-NN predictors over a small number of distributed subsamples. We show, both theoretically and experimentally, that small subsample sizes suffice to attain similar performance as k-NN, without sacrificing the computational efficiency of 1-NN. 1 INTRODUCTION While k-Nearest Neighbor (k-NN) classification or regression can achieve significantly better prediction accuracy that 1-NN (k = 1), practitioners often default to 1-NN as it can achieve much faster prediction that scales better with large sample size n. In fact, much of the commercial tools for nearest neighbor search remain optimized for 1-NN rather than for k-NN, further biasing practice towards 1-NN. Unfortunately, 1-NN is statistically inconsistent, i.e., its prediction accuracy plateaus early as sample size n increases, while k-NN n→∞ keeps improving longer for choices of k −−−−→ ∞. In this work we consider having access to a small number of distributed computing units, and ask whether better tradeoffs between k-NN and 1-NN can be achieved by harnessing parallelism at prediction time. A simple idea is bagging multiple 1-NN predictors computed over distributed subsamples; however this tends to require large number of subsamples, while the number of computing units is often constrained in practice. In fact, an infinite number of subsamples is assumed in all known consistency guarantees for the 1-NN bagging approach (Biau et al., 2010; Samworth et al., 2012). Here, we are Samory Kpotufe Princeton University particularly interested in small numbers of distributed subsamples (say 1 to 10) as a practical matter. Hence, we consider a simple variant of the above idea, consisting of aggregating a few denoised 1-NN predictors. With this simple change, we obtain the same theoretical error-rate guarantees as for k-NN, using few subsamples, while individual processing times are of the same order or better than 1-NN’s computation time. The main intuition behind denoising is as follows. The increase in variance due to subsampling is hard to counter if too few predictors are aggregated. We show that this problem is suitably addressed by denoising each subsample as a preprocessing step, i.e., replacing the subsample labels with k-NN estimates based on the original data. Prediction then consists of aggregating – by averaging or by majority – the 1-NN predictions from a few denoised subsamples (of small size m  n). Interestingly, as shown both theoretically and experimentally, we can let the subsampling ratio n→∞ (m/n) −−−−→ 0 while achieving a prediction accuracy of the same order as that of k-NN. Such improved accuracy over vanilla 1-NN is verified experimentally, even for relatively small number of distributed predictors. Note that, in practice, we aim to minimize the number of distributed predictors, or equivalently the number of computing units which is usually costly in its own right. This is therefore a main focus in our experiments. In particular, we will see that even with a single denoised 1-NN predictor, i.e., one computer, we can observe a significant improvement in accuracy over vanilla 1-NN while maintaining the prediction speed of 1-NN. Our main focus in this work is classification – perhaps the most common form of NN prediction – but our results readily extend to regression. Detailed Results And Related Work While nearest neighbor prediction methods are among the oldest and most enduring in data analysis (Fix and Hodges Jr, 1951; Cover and Hart, 1967; Kulkarni and Posner, 1995), their theoretical performance in practical settings is still being elucidated. For statistical consistency, it is well known that one needs a number n→∞ k −−−−→ ∞ of neighbors, i.e., the vanilla 1-NN method Manuscript under review by AISTATS 2018 is inconsistent for either regression or classification (Devroye et al., 1994). In the case of regression, Kpotufe (2011) shows that convergence rates (l2 excess error over Bayes) behave as O(n−2/(2+d) ), for Lipschitz regression functions over data with intrinsic dimension d; this then implies a rate of O(n−1/(2+d) ) for binary classification via known relations between regression and classification rates (see e.g. Devroye et al. (1996)). Similar rates are recovered in (Cannings et al., 2017) under much refined parametrization of the marginal input distribution, while a recent paper of Moscovich et al. (2016) recovers similar rates in semisupervised settings. Such classification rates can be sharpened by taking into account the noise margin, i.e., the mass of data away from the decision boundary. This is done in the recent work of Chaudhuri and Dasgupta (2014) which obtain faster rates of the form O(n−α(β+1)/(2α+d) ) – where the regression function is assumed α-smooth – which can be much faster for large β (characterizing the noise margin). However such rates require large number of neighbors k = O(n2α/(2α+d) ) growing as a root of sample size n; such large k implies much slower prediction time in practice, which is exacerbated by the scarcity of optimized tools for ‘k’ nearest neighbor search. In contrast, fast commercial tools for 1-NN search are readily available, building on various space partitioning data structures (Krauthgamer and Lee, 2004; Clarkson, 2005; Beygelzimer et al., 2006; Gionis et al., 1999). In this work we show that the classification error of the proposed approach, namely aggregated denoised 1NN’s, is of the same optimal order Õ(n−α(β+1)/(2α+d) ) plus a term Õ(m−α(β+1)/d ) where m ≤ n is the subsample size used for each denoised 1-NN. This additional term, due to subsampling, is of lower order provided m = Ω̃(nd/(2α+d) ); in other words we can let the subn→∞ sampling ratio (m/n) = Ω̃(n−2α/(2α+d) ) −−−−→ 0 while achieving the same rate as k-NN. We emphasize that the smaller the subsampling ratio, the faster the prediction time: rather than just maintaining the prediction time of vanilla 1-NN, we can actually get considerably better prediction time using smaller subsamples, while at the same time considerably improving prediction accuracy towards that of k-NN. Finally notice that the theoretical subsampling ratio of Ω̃(n−2α/(2α+d) ) is best with smaller d, the intrinsic dimension of the data, which is not assumed to be known a priori. Such intrinsic dimension d is smallest for structured data in IRD , e.g. data on an unknown manifold, or sparse data, and therefore suggests that much smaller subsamples – hence faster prediction times – are possible with structured data while achieving good prediction accuracy. As mentioned earlier, the even simpler approach of bagging 1-NN predictors is known to be consistent (Biau and Devroye, 2010; Biau et al., 2010; Samworth et al., 2012), however only in the case of an infinite bag size, corresponding to an infinite number of computing units in our setting – we assume one subsample per computing unit so as to maintain or beat the prediction time of 1-NN. Interestingly, as first shown in (Biau and Devroye, 2010; Biau et al., 2010), the subsampling ratio (m/n) can also tend to 0 as n → ∞, while achieving optimal prediction rates (for fixed α = 1, β = 0), albeit assuming an infinite number of subsamples. In contrast we show optimal rates – on par with those of k-NN – for even one denoised subsample. This suggests, as verified experimentally, that few such denoised subsamples are required for good prediction accuracy. The recent work of Kontorovich and Weiss (2015), of a more theoretical nature, considers a similar question as ours, and derives a penalized 1-NN approach shown to be statistically consistent unlike vanilla 1NN. The approach of Kontorovich and Weiss (2015) roughly consists of finding a subsample of the data whose induced 1-NN achieves a significant margin between classes (two classes in that work). Unfortunately finding such subsample can be prohibitive (computable in time O(n4.376 )) in the large data regimes of interest here. In contrast, our training phase only involves random subsamples, and cross-validation over a denoising parameter k (i.e., our training time is akin to the usual k-NN training time). Finally, unlike in the above cited works, our rates are established for multiclass classification (for the sake of completion), and depend logarithmically on the number of classes. Furthermore, as stated earlier, our results extend beyond classification to regression, and in fact are established by first obtaining regression rates for estimating the so-called regression function E [Y |X]. Paper outline. Section 2 presents our theoretical setup and the prediction approach. Theoretical results are discussed in Section 3, and the analysis in Section 4. Experimental evaluations on real-world datasets are presented in Section 5. 2 2.1 PRELIMINARIES Distributional Assumptions Our main focus is classification, although our results extend to regression. Henceforth we assume we are . n given an i.i.d. sample (X, Y) = (Xi , Yi )1 where X ∈ . D X ⊂ IR , and Y ∈ [L] = {1, 2, . . . , L}. The conditional distribution PY |X is fully captured by the so-called regression function, defined as η : X 7→ Manuscript under review by AISTATS 2018 [0, 1]L , where ηi (x) = P (Y = i|X = x). We assume the following on PX,Y . Assumption 1 (Intrinsic dimension and regularity of PX ). First, for any x ∈ X and r > 0, define the ball . B(x, r) = {x0 ∈ X : kx − x0 k ≤ r}. We assume, there exists an integer d, and a constant Cd such that, for all x ∈ X , r > 0, we have PX (B(x, r)) ≥ Cd rd . In this work d is unknown to the procedure. However, as is now understood from previous work (see e.g. Kpotufe (2011)), the performance of NN methods depends on such intrinsic d. We will see that the performance of the approach of interest here would also depends on such unknown d. In particular, as is argued in (Kpotufe, 2011), d is low for low-dimensional manifolds, or sparse data, so we would think of d  D for structured data. Note that the above assumption also imposes regularity on PX , namely by ensuring sufficient mass locally on X (so that NNs of a point x are not arbitrarily far from it). Assumption 2 (Smoothness of η). The function η is (λ, α)-Hölder for some λ > 0, 1 ≥ α > 0, i.e., 0 ∀x, x ∈ X , 0 α 0 kη(x) − η(x )k∞ ≤ λ kx − x k . We will use the following version of Tsybakov’s noise condition (Audibert and Tsybakov, 2007), adapted to the multiclass setting. Assumption 3 (Tsybakov noise condition). For any x ∈ X , let η(l) (x) denote the l’th largest element in {ηl (x)}L l=1 . There exists β > 0, and Cβ > 0 such that  ∀t > 0, P η(1) (X) − η(2) (X) ≤ t ≤ Cβ tβ . 2.2 Classification Procedure For any classifier h : X 7→ [L], we are interested in the 0-1 classification error err(h) = PX,Y (h(X) 6= Y ) . It is well known that the above error is mimimized by . the Bayes classifier h∗ (x) = argmaxl ηl (x). Therefore, for any estimated classifier ĥ, we are interested in the excess error err(ĥ) − err(h∗ ). We first recall the following basic nearest neighbor estimators. Definition 1 (k-NN prediction). Given k ∈ N, let kNN-I(x) denote the indices of the k nearest neighbors of x in the sample X. Assume, for simplicity, that ties are resolved so that |kNN-I(x)| = k. The k-NN classifier can be defined via the regression estimate η̂ : X 7→ [0, 1]L , where . 1 η̂l (x) = k X i∈kNN-I(x) 1 {Yi = l} . The k-NN classifier is then obtained as: hη̂ (x) = argmax η̂l (x). l Finally we let rk (x) denote the distance from x to its k-th nearest neighbor. We can now formally describe the approach considered in this work. Definition 2 (Denoised 1-NN). Consider a random subsample (without replacement) X0 of X of size m ≤ n. For any x ∈ X , let NN(X0 ; x) denote the nearest neighbor of x in X0 . The denoised 1-NN estimate at x is given as ĥ(x) = hη̂ (NN(X0 ; x)), where hη̂ is as defined above for some fixed k. This estimator corresponds to 1-NN over a sample X0 where each Xi0 ∈ X0 is prelabeled as hη̂ (Xi0 ). The resulting estimator, which we denote subNN for simplicity, is defined as follows. Definition 3 (subNN). Let {ĥi }Ii=1 , denote denoised 1-NN estimators defined over I independent subsamples of size m (i.e., the I sets of indices corresponding to each subsample are picked independently, although the indices in each set is picked with replacement in [n]). At any x ∈ X , the subNN estimate h̄(x) is the majority label in {ĥi (x)}Ii=1 . It is clear that the subNN estimate can be computed in parallel over I machines, while the final step – namely, computation of the majority vote – takes negligible time. Thus, we will view the prediction time complexity at any query x as the average time (over I machines) it takes to compute the 1-NN of x on each subsample. This time complexity gets better as (m/n) → 0. Furthermore, we will show that, even with relatively small I (increasing variability), we can let (m/n) get small while attaining an excess error on par with that of k-NN (here hη̂ ). This is verified experimentally. 3 OVERVIEW OF RESULTS Our main theoretical result, Theorem 1 below, concerns the statistical performance of subNN. The main technicality involves characterizing the effect of subsampling and denoising on performance. Interestingly, the rate below does not depend on the number I of subsamples: this is due to the averaging effect of taking majority vote accross the I submodels, and is discussed in detail in Section 4 (see proof and discussion of Lemma 2). In particular, the rate is bounded in terms of a bad event that is unlikely for a random submodel, and therefore unlikely to happen for a majority. Manuscript under review by AISTATS 2018 Theorem 1. Let 0 < δ < 1. Let V denote the VC dimension of balls on X . With probability at least 1−Lδ, there exists a choice of k ∈ [n], such that the estimate h̄ satisfies α(β+1)/(2α+d) V ln(Ln/δ) err(h̄) − err(h ) ≤ C1 · n  α(β+1)/d V ln(m/δ) + C2 · , m ∗  for constants C1 , C2 depending on PX,Y . The first term above is a function of the size n of the original sample, and recovers the recent optimal bounds for k-NN classification of Chaudhuri and Dasgupta (2014). We note however that the result of Chaudhuri and Dasgupta (2014) concerns binary classification, while here we consider the more general setting of multiclass. Matching lower bounds were established earlier in (Audibert and Tsybakov, 2007). The second term, a function of the subsample size m, characterizes the additional error (over vanilla k-NN hη̂ ) due to subsampling and due to using 1-NN’s at prediction time. As discussed earlier in the introduction, the first term dominates (i.e. we recover the same rates as for k-NN) whenever the subsampling ratio (m/n) = Ω̃(n−α/(2α+d) ) which goes to 0 as n → ∞. This is remarkable in that it suggests smaller subsample sizes are sufficient (for good accuracy) in the large sample regimes motivating the present work. We will see later that this is supported by experiments. As mentioned earlier, similar vanishing subsampling ratios were shown for bagged 1-NN in (Biau and Devroye, 2010; Biau et al., 2010; Samworth et al., 2012), but assuming a infinite number of subsamples. In contrast the above result holds for any number of subsamples, and the improvements over 1-NN are supported in experiments over varying number of subsamples, along with varying subsampling ratios. The main technicalities and insights in establishing Theorem 1 are discussed in Section 4 below, with some proof details relegated to the appendix. 4 ANALYSIS OVERVIEW The proof of Theorem 1 combines the statements of Propositions 3 and 2 below. The main technicality involved is in establishing Proposition 3 which brings together the effect of noise margin β, smoothness α, and the overall error due to denoising over a subsample. We overview these supporting results in the next subsection, followed by the proof of Theorem 1. 4.1 Supporting Results Theorem 1 relies on first establishing a rate of convergence for the k-NN regression estimate η̂, used in denoising the subsamples. While such rates exist in the literature under various assumptions (see e.g. Kpotufe (2011)), we require a high-probability rate that holds uniformly over all x ∈ X . This is given in Proposition 1 below, and is established for our particular setting where Y takes discrete multiclass values (i.e. η̂ and η are both multivariate functions). Its proof follows standard techniques adapted to our particular aim, and is given in the appendix (supplementary material). Proposition 1 (Uniform k-NN regression error). Let 0 < δ < 1. Let η̂ denote the k-NN regression estimate of Definition 1. The followingholds for a choice of   d 2α nL 2α+d (nCd ) 2α+d . With probability at k = O ln δ least 1 − 2δ over (X, Y), we have simultaneously for all x ∈ X :   α V ln(nL/δ) 2α+d kη̂(x) − η(x)k∞ ≤ C nCd where C is a function of α, λ. The above statement is obtained, by first remarking that, under structural assumptions on PX , (namely that there is sizable mass everywhere locally on X ), nearest neighbor distances can be uniformly bounded with high-probability. Such nearest neighbor distances control the bias of the k-NN estimator, while its variance behaves like O(1/k). Such a uniform bound on NN distances is given in Lemma 1 below and follows standard insights. Lemma 1 (Uniform bound on NN distances rk ). As in Definition 1, let rk (x) denote the distance from x ∈ X n to its k’th nearest neighbor in a sample X ∼ PX . Then, with probability at least 1 − δ over X, the following holds for all k ∈ [n]:  sup rk (x) ≤ x∈X 4.2 3 Cd  d1  · max k V ln 2n + ln 8δ , n n  d1 . SubNN Convergence We are ultimately interested in the particular regression estimates induced by subsampling: the denoised 1NN estimates ĥ over a subsample can be viewed as . ĥ = argmaxl∈[L] η̂l] for a regression estimate η̂ ] (x) = 0 η̂(NN(X ; x)), i.e., η̂ evaluated at the nearest neighbor NN(X0 ; x) of x in X0 . Our first step is to relate the error of η̂ ] to that of η̂. Here again the bound on NN distances of Lemma 1 above comes in handy since η̂ ] can be viewed as introducing additional bias to η̂, a bias which is in turn controlled by the distance from a Manuscript under review by AISTATS 2018 query x to its NN in the subsample X0 . By the above lemma, this distance is of order Õ(m−1/d ), introducing a bias of order Õ(m−α/d ) given the smoothness of η. Thus, combining the above two results yields the following regression error on denoised estimates. Proposition 2 (Uniform convergence of denoised 1-NN regression). Let 0 < δ < 1. Let η̂ denote the k-NN regression estimate of Definition 1. Let X0 denote a subsample (without replacement) of . X. Define the denoised 1-NN estimate η̂ ] (x) = 0 η̂(NN(X; x)). The following holds for a choice of  d 2α 2α+d (nC ) 2α+d k = O (V ln nL . With probability d δ ) at least 1 − 3δ over (X, Y), and X0 , we have simultaneously for all x ∈ X : kη̂ ] (x) − η(x)k∞  α V ln(nL/δ) 2α+d ≤C nCd  α V ln(m/δ) d +C , mCd  where C is a function of α, λ. Proof. Define x0 = NN(X0 ; x) so that η̂ ] (x) = η̂(x0 ). We then have the two parts decomposition: kη̂ ] (x) − η(x)k∞ = kη̂(x0 ) − η(x)k∞ Lemma 2 (Uniform convergence of aggregate regresI sion). Given independent subsamples {X0i }i=1 from (X, Y), define η̂i] (x) = η̂(NN(X0i ; x)), i.e., the regression estimate η̂ evaluated at the nearest neighbor NN(X0i ; x) of x in X0i . Suppose there exists φ = φ(n, m) such that,   max PX,Y,X0i ∃x ∈ X , kη̂i] (x) − η(x)k∞ > φ ≤ δ, i∈[I] for some 0 < δ < 1. Then, let h̄ denote the subNN I estimate using subsamples {X0i }i=1 . With probability at I least 1 − Lδ over the randomness in (X, Y) and {X0i }1 , the following holds simultaneously for all x ∈ X : ηh∗ (x) (x) − ηh̄(x) (x) ≤ 2φ. Remark. Notice that in the above statement, the probability of error goes from δ to Lδ, but does not depend on the number I of submodels. This is because of the averaging effect of the majority vote. For intuition, suppose B is a bad event and 1Bi is whether B happens for submodel i. Suppose further that E 1Bi ≤ δ for all i. Then the likelihood of B happening for a majority of more than I/2 of models is ( ) X X 2 E1 1Bi ≥ I/2 ≤ · E 1Bi ≤ 2δ, I i i (1) by a Markov inequality. We use this type of intuition in the proof, however over a sequence of related bad events, and using the fact that, the submodels’ estimates are independent conditioned on X, Y. where the last inequality follows (with probability 1 − 2δ) from Proposition 1. Proof. The result isnobtained by appropriately boundo ing the indicator 1 ∃x : ηh∗ (x) (x) − ηh̄(x) (x) > 2φ . To bound the second term in inequality (1), notice that X0 can be viewed as m i.i.d. samples from PX . Therefore kx0 − xk can be bounded using Lemma 1. Therefore by smoothness condition on η in Assumption 2, we have with probability at least 1−δ, simultaneously for all x ∈ X : Let ĥi denote the denoised 1-NN classifier on sample X0i , or for short, the i’th submodel. First notice that, if . the majority vote h̄(x) = l for some label l ∈ [L], then at least I/L submodels ĥi (x) predict l at x. In other words, we have ≤ kη̂(x0 ) − η(x0 )k∞ + kη(x0 ) − η(x)k∞  α  V ln(nL/δ) 2α+d + kη(x0 ) − η(x)k∞ , ≤C nCd I kη(x0 ) − η(x)k∞ ≤ λkx0 − xkα α  αd   3V ln 2m + 3 ln 8δ d V ln m δ . (2) ≤λ ≤C mCd mCd Combining (1) and (2) yields the statement. Next we consider aggregate regression error, i.e., the discrepancy (ηh∗ (x) (x) − ηh̄(x) (x)) between the coordinates of η given by the labels h∗ (x) and h̄(x). This will be bounded in terms of the error φ(n, m) attainable by the individual denoised regression estimates (as bounded in the above proposition). o LX n 1 ĥi (x) = l ≥ 1. I i=1 . Therefore, fix x ∈ X , and let h̄(x) = l; we then have:  1 ηh∗ (x) (x) − ηh̄(x) (x) > 2φ .  = 1 ηh∗ (x) (x) − ηl (x) > 2φ I o  LX n ≤ 1 ĥi (x) = l 1 ηh∗ (x) (x) − ηl (x) > 2φ I i=1 I ≤ o LX n 1 ηh∗ (x) (x) − ηĥi (x) (x) > 2φ . I i=1 (3) Manuscript under review by AISTATS 2018 . We bound the above as follows. Suppose ĥi (x) = li . ∗ ∗ ∗ and h (x) = l for some labels li and l in [L]. Now, ] if kη(x) − η̂i] (x)k∞ ≤ φ, then ηl∗ (x) ≤ η̂i,l ∗ (x) + φ and ] ηli (x) ≥ η̂i,l (x) − φ. Also by definition we know that i ] ĥi (x) is the maximum entry of η̂i] (x), so η̂i,l ∗ (x) ≤ ] η̂i,l (x). Therefore i ] ] ηh∗ (x) (x) − ηĥi (x) (x) ≤ (η̂i,l ∗ (x) + φ) − (η̂i,l (x) − φ) i ] ] = (η̂i,l ∗ (x) − η̂i,l (x)) + 2φ ≤ 2φ. i In other words, ηh∗ (x) (x) − ηĥi (x) (x) > 2φ only when kη(x) − η̂i] (x)k∞ > φ. Thus, bound (3) to obtain: n o 1 ηh∗ (x) (x) − ηh̄(x) (x) > 2φ ≤ I o LX n 1 kη(x) − η̂i] (x)k∞ > φ . I i=1 Finally we use the fact that, for an event A(x), we have 1 {∃x ∈ X : A(x)} = supx∈X 1 {A(x)}. Combine this fact with the above inequality to get: n o 1 ∃x ∈ X : ηh∗ (x) (x) − ηh̄(x) (x) > 2φ n o = sup 1 ηh∗ (x) (x) − ηh̄(x) (x) > 2φ x∈X ≤ sup x∈X I o LX n 1 kη(x) − η̂i] (x)k∞ > φ I i=1 ≤ I n o LX sup 1 kη(x) − η̂i] (x)k∞ > φ I i=1 x∈X = I o LX n 1 ∃x ∈ X : kη(x) − η̂i] (x)k∞ > φ . I i=1 . Proof. Since, for any classifier h, ηh(x) (x) = P (Y = h(x)), the excess error h of the sub-NN classii fier h̄ can be written as E X ηh∗ (X) (X) − ηh̄(X) (X) . Thus, the assumption in the proposition statement – that for all x ∈ X, ηh∗ (x) (x) − ηh̄(x) (x) < 2φ (with probability at least 1 − δ) – yields a trivial bound of 2φ on the excess error. We want to refine this bound. Let η(l) (x) be the l-th largest entry in the vector η(x) = . L {ηl }l=1 , and define ∆(x) = η(1) (x) − η(2) (x). Then at any fixed point x, we can refine the bound on excess error at x (namely ηh∗ (x) (x) − ηh̄(x) (x)), by separately considering the following exhaustive conditions A(x) and B(x) on x: A: ∆(x) ≥ 2φ, in which case the excess error is 0. This follows from η(1) (x) = ηh∗ (x) (x) and that: ηh∗ (x) (x) − ηh̄(x) (x) < 2φ ≤ ηh∗ (x) (x) − η(2) (x) In other words ηh̄(x) (x) is larger than η(2) , so . equals η(1) (x) = ηh∗(x) (x). B: ∆(x) < 2φ, in which case the excess error cannot be refined at x. However, the total mass of such x’s is at most Cβ (2φ)β by Tsybakov’s noise condition (Assumption 3). Combining these conditions, we have with probability at least 1 − δ that the excess error satisfies: h i err(h̄) − err(h∗ ) = E X ηh∗ (X) (X) − ηh̄(X) (X) ≤ E X [0 · 1 {A(X)} + 2φ · 1 {B(X)}] ≤ 2φ · E [1 {B(X)}] ≤ 2φ · P (∆(x) ≤ 2φ) ≤ Cβ (2φ)β+1 . The final statement is obtained by integrating both sides of the inequality over the randomness in X, Y and I the (conditionally) independent subsamples {X0i }1 . Next, Proposition 3 below states that the excess error of the subNN estimate h̄ can be bounded in terms of the aggregate regression error (ηh∗ − ηh̄ ) considered in Lemma 2. In particular, the proposition serves to account for the effect of the noise margin parameter β towards obtaining faster rates than those in terms of smoothness α only. Combining the results of this section yield the main theorem whose proof is given next. 4.3 Proof Of Theorem 1 Our main result follows easily from Propositions 2 and 3. This is given below. Proposition 3. Suppose there exists φ = φ(n, m) such that, with probability at least 1 − δ over the randomI ness in (X, Y) and the subsamples {X0i }i=1 , we have simultaneously for all x ∈ X , ηh∗ (x) (x) − ηh̄(x) (x) < 2φ. Proof. Fix any 0 < δ < 1. Note that the conditions of Lemma 2 are verified in Proposition 2, namely that, with probability 1 − 3δ, all regression errors (of submodels) are bounded by Then with probability at least 1 − δ, the excess classification error of the estimate h̄ satisfies: . φ= C err(h̄) − err(h∗ ) ≤ Cβ (2φ)β+1 .  V ln(Ln/δ) n α/(2α+d)  +C V ln(m/δ) m α/d , (4) Manuscript under review by AISTATS 2018 Table 1: Datasets Used In Evaluating SubNN Name MiniBooNE TwitterBuzz LetterBNG NewsGroups20 YearPredMSD WineQuality #train 120k 130k 34k 11k 34k 5.5k #test 10k 10k 10k 7.5k 10k 1.0k #dimension 50 50 16 130k 90 12 #classes 2 2 26 20 regression regression where C is a constant depending on α and λ. Next, the conditions of Proposition 3 are obtained in Lemma 2 with the same setting of φ. It follows that with probability at least 1 − 3Lδ, we have: err(h̄) − err(h∗ ) ≤ Cβ (2φ)β+1 , with φ as in (4). Given that g(x) = xβ+1 is a convex function, we conclude by applying Jensen’s inequality (viewing (1/2C) · φ as an average of two terms). 5 EXPERIMENTS Experimental Setup. Data is standardized along each coordinate of X. - Fitting subNN. We view the subsample size m and the number I of subsamples as exogenous parameters determined by the practical constraints of a given application domain. Namely, smaller m yields faster prediction and is driven by prediction time requirement, while larger I improves prediction error but is constrained by available computing units. However, much of our experiments concern the sensitivity of subNN to m and I, and yield clear insights into tradeoffs on these choices. Thus, for any fixed choice of m and I, we choose k by 2-fold cross-validation. The search for k is done in two stages: first, the best value k 0 (minimizdlog ne ing validation error) is picked on a log-scale {2i }i=1 , then a final choice for k is made on a refined linear range [dk 0 /2e − 10 : 2k 0 + 10]. - Fitting k-NN. k is also chosen in two stages as above. Description Particle identification (Roe, 2010) Buzz in social media (François Kawala, 2013) English alphabet (ML) Document classification (Mitchell, 1999) Release year of songs (Bertin-Mahieux, 2011) Quality of wine (Cortez, 2009) that of k-NN) for versions of subNN((m/n), I), where m/n is the subsampling ratio used, and I is the number of subsamples. For regression datasets, the error is the MSE, while for classification we use 0-1 error. The prediction time reported for the subNN methods is the maximum time over the I subsamples plus aggregation time, reflecting the effective prediction time for the distributed-computing settings motivating this work. The results support our theoretical insights, namely that subNN can achieve accuracy close or matching that of k-NN, while at the same time achieving fast prediction time, on par or better than those of 1-NN. - Sensitivity to m and I. As expected, better times are achievable with smaller subsample sizes, while better prediction accuracy is achievable as more subsamples tend to reduce variability. This is further illustrated for instance in Figure 1, where we vary the number of subsamples. Interestingly in this figure, for the MiniBoone dataset, the larger subsampling ratio 0.75 yields the best accuracy over any number of subsamples, but the gap essentially disappears when enough subsamples are used. We thus have the following prescription in choosing m and I: while small values of I work generally well, large values of I can only improve accuracy; on the other hand, subsampling ratios of 0.1 yield good time-accuracy tradeoffs accross datasets. Table 1 describes the datasets used in the experiments. We use k-d-tree for fast NN search from Python scikit-learn for all datasets but NewsGroups20 for which we perform a direct search (due to highdimensionality and sparsity). As explained earlier, our main focus is on classification, however theoretical insights from previous sections extend to regression, as substantiated in this section. The code in Python can be found at https://github.com/lirongx/SubNN. - Benefits of denoising. In Figure 2, we compare subNN with pure bagging of 1-NN models. As suggested by theory, we see that the bagging approach does indeed require considerably more subsamples to significantly improve over the error of vanilla 1-NN. In contrast, the accuracy of subNN quickly tends to that of k-NN, in particular for TwitterBuzz where 1 or 3 subsamples are sufficient to statistically close the gap, even for small subsampling ratio. This could be due to hidden but beneficial structural aspects of this data. In all cases, the experiments further highlights the benefits of our simple denoising step, as a variance reduction technique. This is further supported by the error-bars (std) over 5 repetitions as shown in Figure 2. Results. Our main experimental results are described in Table 2, showing the relative errors (error of the method divided by that of vanilla k-NN) and relative prediction time (prediction time divided by Conclusion. We propose a procedure with theoretical guarantees, which is easy to implement over distributed computing resources, and which achieves good time-accuracy tradeoffs for nearest neighbor methods. Manuscript under review by AISTATS 2018 Table 2: Ratios Of Error Rates and Prediction Times Over Corresponding Errors And Times Of k-NN. Data MiniBooNE TwitterBuzz LetterBNG NewsGroups20 YearPredMSD WineQuality Relative Error subNN(0.1,10) subNN(0.75,10) 1.039 1.027 1.000 1.005 1.086 1.144 1.206 1.002 1.082 1.110 1.011 1.018 1NN 1.280 1.405 1.127 1.122 1.859 1.276 0.15 40 subNN(0.1,−) subNN(0.5,−) subNN(0.75,−) 1NN kNN ● Time 30 subNN(0.1,−) subNN(0.5,−) subNN(0.75,−) 1NN kNN 0.14 0.13 Error Rate MiniBooNE prediction time 20 0.16 MiniBooNE Prediction Error ● Relative Time subNN(0.1,10) subNN(0.75,10) 0.247 0.547 0.185 0.522 0.219 0.396 0.081 0.668 0.025 0.249 0.885 0.906 1NN 0.609 0.550 0.459 0.610 0.847 0.989 ● 10 0.12 ● ● ● ● ● 0 0.11 ● ● ● ● 0 2 4 6 8 10 0 2 number of subsamples 4 6 8 10 number of subsamples Figure 1: Comparing the Effect Of Subsampling Ratios on Prediction And Time Performance Of SubNN. Shown are SubNN estimates using subsampling ratios 0.1, 0.5, and 0.75. 0.16 Error Rate ● 0.14 0.15 0.14 subNN(0.75,−) bag−1NN(0.75,−) 1NN kNN ● 0.15 subNN(0.1,−) bag−1NN(0.1,−) 1NN kNN ● 0.13 Error Rate MiniBooNE: subNN vs. bag−1NN(0.75,−) 0.13 0.16 MiniBooNE: subNN vs. bag−1NN(0.1,−) ● 0.12 0.12 ● ● ● 0 2 4 6 8 10 0 2 number of subsamples ● 2 0.050 ● ● ● 4 6 number of subsamples 8 10 subNN(0.75,−) bag−1NN(0.75,−) 1NN kNN ● 0.035 0.035 0 10 0.045 Error Rate ● ● 8 0.040 0.050 0.045 0.040 ● 6 TwitterBuzz: subNN vs. bag−1NN(0.75,−) subNN(0.1,−) bag−1NN(0.1,−) 1NN kNN ● 4 number of subsamples TwitterBuzz: subNN vs. bag−1NN(0.1,−) Error Rate ● ● ● 0.11 0.11 ● 0 2 ● ● ● 4 6 ● 8 10 number of subsamples Figure 2: Bagged 1NN Compared With SubNN Using Subsampling Ratios 0.1 (Left) And 0.75 (Right). Manuscript under review by AISTATS 2018 References Jean-Yves Audibert and Alexandre B. Tsybakov. Fast learning rates for plug-in classifiers. The Annals of Statistics, 35(2):608–633, 2007. T. Bertin-Mahieux. Yearpredictionmsd data https://archive.ics.uci.edu/ml/datasets/ YearPredictionMSD, 2011. set. A. Beygelzimer, S. Kakade, and J. Langford. Cover trees for nearest neighbors. International Conference on Machine Learning (ICML), 2006. Gérard Biau and Luc Devroye. On the layered nearest neighbour estimate, the bagged nearest neighbour estimate and the random forest method in regression and classification. Journal of Multivariate Analysis, 101(10): 2499–2518, 2010. Gérard Biau, Frédéric Cérou, and Arnaud Guyader. On the rate of convergence of the bagged nearest neighbor estimate. Journal of Machine Learning Research, 11 (Feb):687–712, 2010. Timothy I Cannings, Thomas B Berrett, and Richard J Samworth. Local nearest neighbour classification with applications to semi-supervised learning. arXiv preprint arXiv:1704.00642, 2017. Kamalika Chaudhuri and Sanjoy Dasgupta. Rates of convergence for nearest neighbor classification. In Advances in Neural Information Processing Systems, pages 3437–3445, 2014. Kenneth L. Clarkson. Nearest-neighbor searching and metric space dimensions. Nearest-Neighbor Methods for Learning and Vision: Theory and Practice, 2005. Paulo Cortez. Wine quality data set. https://archive. ics.uci.edu/ml/datasets/Wine+Quality, 2009. Thomas Cover and Peter Hart. Nearest neighbor pattern classification. IEEE transactions on information theory, 13(1):21–27, 1967. L. Devroye, L. Gyorfi, and G. Lugosi. A Probabilistic Theory of Pattern Recognition. Springer, 1996. Luc Devroye, Laszlo Gyorfi, Adam Krzyzak, and Gábor Lugosi. On the strong universal consistency of nearest neighbor regression function estimates. The Annals of Statistics, pages 1371–1385, 1994. Evelyn Fix and Joseph L Hodges Jr. Discriminatory analysis-nonparametric discrimination: consistency properties. Technical report, DTIC Document, 1951. et. al. François Kawala. Buzz in social media data set. https://archive.ics.uci.edu/ml/datasets/ Buzz+in+social+media+, 2013. Aristides Gionis, Piotr Indyk, Rajeev Motwani, et al. Similarity search in high dimensions via hashing. In VLDB, volume 99, pages 518–529, 1999. Aryeh Kontorovich and Roi Weiss. A bayes consistent 1-nn classifier. In AISTATS, 2015. S. Kpotufe. k-NN Regression Adapts to Local Intrinsic Dimension. Advances in Neural Information Processing Systems (NIPS), 2011. R. Krauthgamer and J. Lee. Navigating nets: Simple algorithms for proximity search. ACM-SIAM Symposium on Discrete Algorithms (SODA), 2004. Sanjeev R Kulkarni and Steven E Posner. Rates of convergence of nearest neighbor estimation under arbitrary sampling. IEEE Transactions on Information Theory, 41 (4):1028–1039, 1995. Tom Mitchell. Twenty newsgroups data set. https://archive.ics.uci.edu/ml/datasets/Twenty+ Newsgroups, 1999. Open ML. Open ml machine learning platform. https: //www.openml.org/d/1378. Amit Moscovich, Ariel Jaffe, and Boaz Nadler. Minimaxoptimal semi-supervised regression on unknown manifolds. arXiv preprint arXiv:1611.02221, 2016. Byron Roe. Miniboone particle identification data set. https://archive.ics.uci.edu/ml/datasets/ MiniBooNE+particle+identification, 2010. Richard J Samworth et al. Optimal weighted nearest neighbour classifiers. The Annals of Statistics, 40(5):2733– 2763, 2012. Manuscript under review by AISTATS 2018 A PROOF OF MAIN RESULTS In this section, we show the proof of Proposition 1 (uniform bound on kNN regression error). The proof is done by decomposing the regression error into bias and variance (Lemma 5) and bound each of them separately in Lemma 4 and 5. Lemma 1 will be proved first as a by-product. The decomposition is the following. Define η̃(x) as: η̃(x) = EY|X η̂(x) = 1 k X η(Xi ). i∈kNN-I(x) P (Bx (, k)) = P (B (x, (1 − ) rk (x))) ≥ Cd (1−)d rkd (x). Therefore, with probability at least 1 − δ, the following holds simultaneously for all x ∈ X : rk (x)  1 P(Bx (, k)) d ≤ Cd    d1 1 k V ln 2n + ln 8δ d 3 · max · (1 − )−1 . ≤ , Cd n n Viewing η̃ as the expectation of η̂ conditioning sample X, we can have the following variance and bias decomposition of error of η̂: Let  → 0 in the above inequality and conclude the proof. kη̂(x) − η(x)k∞ ≤ kη̂(x) − η̃(x)k∞ + kη̃(x) − η(x)k∞ . (5) Using Lemma 1 (uniform rk (x) bound), we can get a uniform bound on the bias of η̂: We start by introducing a known result on relative VC bound in Lemma 3. Then in Lemma 1, we use it to give a uniform bound on rk (x) - the distance between query point x and its k-th nearest neighborhood in data. After that we use Lemma 1 to bound bias and variance separately in Lemma 4 and 5. Proposition 1 is concluded by combing the two bounds. Lemma 4 (Bias of η̂). Let V be the VC dimension of the class of balls on X . For 0 < δ < 1 and k ≥ V ln 2n + ln 8δ , with probability at least 1 − δ over the randomness in the choice of X, the following inequality holds simultaneously for all x ∈ X :  α 3 k d kη̃(x) − η(x)k∞ ≤ λ · . · Cd n Lemma 3 (Relative VC Bound, Vapnik 1971). Let B be a set of subsets of X . B has finite VC dimension V. For n drawn sample X1 , . . . , Xn , the empirical probPn ability measure is defined as Pn (B) = n1 i=1 1Xi ∈B . Define αn = (V ln 2n + ln(8/δ))/n. Let 0 < δ < 1, with probability at least 1 − δ over the randomness in X1 , . . . , Xn , the following holds simultaneously for all B ∈ B: p P(B) ≤ Pn (B) + Pn (B)αn + αn . Proof. First, for a fixed sample X, by Assumption 2 (Smoothness of η) we have: kη̃(x) − η(x)k∞ X 1 = η(Xi ) − η(x) k i∈kNN-I(x) ≤ ≤ Using the above result, we can prove Lemma 1 (bound on rk ). Proof of Lemma 1. By Lemma 3, let αn = (V ln 2n + ln(8/δ)) /n, with probability at least 1 − δ over the randomness in X and  > 0, for any x ∈ X and closed ball Bx (, k) = B(x, (1 − )rk (x)), we have: p P(Bx (, k)) ≤ Pn (Bx (, k)) + Pn (Bx (, k))αn + αn ≤ 3 max (Pn (Bx (, k)), αn )   k V ln 2n + ln 8δ , . < 3 max n n By Assumption 1 (intrinsic dimension), for any x ∈ X and any  > 0, P (Bx (, k)) is lower-bounded as below. 1 k 1 k 1 ≤ k X ∞ kη(Xi ) − η(x)k∞ i∈kNN-I(x) X λkXi − xkα i∈kNN-I(x) X λrkα (x) = λrkα (x). i∈kNN-I(x) It follows by Lemma 1, that, with high probability at least 1 − δ over X, the following holds simultaneously for all x ∈ X .  α 3 k d α kη̃(x) − η(x)k∞ ≤ λrk (x) ≤ λ · · . Cd n Lemma 5 (Variance of η̂). Let V be the VC dimension of balls on X . For 0 < δ < 1, with probability at least 1 − δ over the randomness in (X, Y), the following inequality holds simultaneously for all x ∈ X : Manuscript under review by AISTATS 2018 kη̂(x) − η̃(x)k∞ < √ r V 1 − 2δ: 1 nL ln . k δ Proof. Consider the l-th value of η̂(x) − η̃(x): 1 (η̂(x) − η̃(x))l = k X  1 {Yi = l} − ηl (Xi ) . i∈kNN-I(x) Fix x, X and consider the randomness in Y conditioned on X. Use Hoeffding’s Inequality. There are k independent terms in the above summation and E(1 {Yi = l} |Xi ) = ηl (Xi ). So the following holds with probability at least 1 − δ0 over the randomness in Y: r 2 1 (η̂(x) − η̃(x))l ≤ ln . 2k δ0 Apply the above analysis to l = 1, . . . , L and combine them by union bound. So the following inequality holds with probability at least 1 − L · δ0 over the randomness in Y: r kη̂(x) − η̃(x)k∞ ≤ 2 1 ln . 2k δ0 Then consider variations in x. Given X fixed, the left hand side of the above inequality can be seen as a function of kNN-I(x). This is a subset of X covered by ball B(x, rk (x)). By Sauer’s Lemma, the number of V such subsets of X covered by a ball is bounded by en . V  en V So there are at most V many different variations of the above inequality when x varies. We combine the V variations by union bound. Let δ = δ0 · L · en , the V following happens with probability at least 1 − δ over the randomness in Y: r 1 2 ln sup kη̂(x) − η̃(x)k∞ ≤ 2k δ 0 x∈X r V en 1 2L ≤ ln + ln 2k V 2k δ r √ 1 nL ≤ V ln . k δ The above inequality holds for any fixed sample X and the right hand side do not depend on X. So it continue to hold for any drawn X. Thus we conclude the proof. Combining the bias and variance of η̂, we have the bound on uniform kNN regression error. Proof of Proposition 1. Apply Lemma 4 (bias) and 5 (variance) to inequality 5, with probability at least  kη̂(x)−η(x)k∞ ≤ λ 3 Cd r α/d  α/d √ k 1 nL · + V· ln . n k δ The aboved is minimized at k = 2α 2α+d (nC ) 2α+d , where C 0 depend only on C 0 (V ln nL ) d δ α and λ. Plug in this value of k into the statement α above, we obtain kη̂(x)−η(x)k∞ = C 00 ( V ln(nL/δ) ) 2α+d , nCd where C 00 depend solely on α and λ. B ADDITIONAL TABLES AND PLOTS In this section we present supplemental plots and tables. Table 3 shows the same experiment as in Table 2, but reports average prediction time (over the I subsamples) rather than the maximum prediction times, plus the aggregation time. Comparing the two tables, one can see that the differences between average and maximum times are small. In other words, prediction time is rather stable over the subsamples, which is to be expected as these times are mostly controlled by subsample size and computing resource. Figure 3 presents the same experiments as in Figure 1, for an additional dataset (TwitterBuzz). It compares the error and prediction time of subNN models as a function of the number I of subsamples used. Again, as we can see, subNN yields error rates similar to those of kNN, even for a small number of subsamples. As expected, the best prediction times are achieved with the smaller subsample ratio of 0.1. Manuscript under review by AISTATS 2018 Table 3: Ratios Of Error Rates and Average Prediction Times Over Corresponding Errors And Times Of k-NN. Data MiniBooNE TwitterBuzz LetterBNG NewsGroups20 YearPredMSD WineQuality Relative Error subNN(0.1,10) subNN(0.75,10) 1.039 1.027 1.000 1.005 1.086 1.144 1.206 1.002 1.082 1.110 1.011 1.018 1NN 1.280 1.405 1.127 1.122 1.859 1.276 50 TwitterBuzz prediction time ● subNN(0.1,−) subNN(0.5,−) subNN(0.75,−) 1NN kNN 20 Time 30 0.045 40 subNN(0.1,−) subNN(0.5,−) subNN(0.75,−) 1NN kNN 10 0.040 Error Rate 0.050 TwitterBuzz Prediction Error ● Relative Average Time subNN(0.1,10) subNN(0.75,10) 0.216 0.492 0.179 0.480 0.218 0.390 0.076 0.659 0.025 0.248 0.826 0.878 1NN 0.609 0.550 0.459 0.610 0.847 0.989 ● ● ● ● ● ● 0.035 ● ● ● 0 ● 0 2 4 6 number of subsamples 8 10 0 2 4 6 8 10 number of subsamples Figure 3: Comparing the Effect Of Subsampling Ratio And Number Of Models (TwitterBuzz). We find that all the subNN predictors reach error similar to that of k-NN even when using only a few subsamples (1 or 3). As expected, subNN with a subsampling ratio of 0.1 results in the best prediction times.
10 (math.ST)

Arxiv Classification: a classification of Arxiv Papers (11 classes).

This dataset is intended for long context classification (documents have all > 4k tokens).
Copied from "Long Document Classification From Local Word Glimpses via Recurrent Attention Learning"

@ARTICLE{8675939,
  author={He, Jun and Wang, Liqun and Liu, Liu and Feng, Jiao and Wu, Hao},
  journal={IEEE Access}, 
  title={Long Document Classification From Local Word Glimpses via Recurrent Attention Learning}, 
  year={2019},
  volume={7},
  number={},
  pages={40707-40718},
  doi={10.1109/ACCESS.2019.2907992}
  }

It contains 11 slightly unbalanced classes, 33k Arxiv Papers divided into 3 splits: train (28k), val (2.5k) and test (2.5k).

2 configs:

  • default
  • no_ref, removes references to the class inside the document (eg: [cs.LG] -> [])

Compatible with run_glue.py script:

export MODEL_NAME=roberta-base
export MAX_SEQ_LENGTH=512

python run_glue.py \
  --model_name_or_path $MODEL_NAME \
  --dataset_name ccdv/arxiv-classification  \
  --do_train \
  --do_eval \
  --max_seq_length $MAX_SEQ_LENGTH \
  --per_device_train_batch_size 8 \
  --gradient_accumulation_steps 4 \
  --learning_rate 2e-5 \
  --num_train_epochs 1 \
  --max_eval_samples 500 \
  --output_dir tmp/arxiv
Edit dataset card
Evaluate models HF Leaderboard