TExcelTAD
Home › Streaming, Sketching & Sublinear Algorithms › Property Testing: Queries and Distance

Property Testing: Queries and Distance

Streaming algorithms read all of their input once with little memory. Sublinear-time algorithms do not even read all of it: they have random access to the input and look at only a few positions. That is plainly impossible for exact questions ("is this array sorted?" can hinge on a single pair), so the question is relaxed in a precise way. A property tester must accept every input that has the property and reject every input that is far from having it; inputs that are close but not in the property may go either way. With this relaxation many properties can be tested with a number of queries that does not depend on the input size at all. The framework goes back to Blum, Luby and Rubinfeld (1993) for linearity, Rubinfeld and Sudan (1996) for algebraic properties, and Goldreich, Goldwasser and Ron (1998) for graphs and combinatorial objects.

Definitions

Model the input as a function x:D→Rx : D \to R over a domain of size nn that the algorithm can query: an array (D=[n]D = [n]), a Boolean function (D={0,1}kD = \{0,1\}^k), or a graph given by its adjacency matrix or adjacency lists. A property P\mathcal{P} is a set of such functions (all sorted arrays, all linear functions, all bipartite graphs).

  • The distance of xx to P\mathcal{P} is the smallest fraction of positions that must be changed to put xx into P\mathcal{P}:
dist⁡(x,P)=min⁡y∈P∣{i:x(i)≠y(i)}∣n.\operatorname{dist}(x, \mathcal{P}) = \min_{y \in \mathcal{P}} \frac{\lvert \{ i : x(i) \ne y(i) \} \rvert}{n} .
  • xx is ε\varepsilon-far from P\mathcal{P} if dist⁡(x,P)≥ε\operatorname{dist}(x, \mathcal{P}) \ge \varepsilon, and ε\varepsilon-close otherwise.

  • An ε\varepsilon-tester for P\mathcal{P} is a randomized algorithm that, given query access to xx and the parameter ε\varepsilon,

    • accepts with probability at least 23\frac{2}{3} if x∈Px \in \mathcal{P},
    • rejects with probability at least 23\frac{2}{3} if xx is ε\varepsilon-far from P\mathcal{P}.

    It has one-sided error if it accepts every x∈Px \in \mathcal{P} with probability 1; it then rejects only with a witness, a set of queried positions that no member of P\mathcal{P} could produce.

  • The query complexity q(n,ε)q(n, \varepsilon) is the number of queries in the worst case. The tester is efficient if qq is sublinear in nn, and remarkable if it is independent of nn.

The constant 23\frac{2}{3} is arbitrary: repeating the tester O(log⁡1δ)O(\log \frac{1}{\delta}) times and taking the majority (or, for one-sided testers, rejecting if any run rejects) brings the error to δ\delta. The distance is relative to the domain size, and each object class has its own notion: for dense graphs, distance counts changed entries of the n×nn \times n adjacency matrix (εn2\varepsilon n^2 edges); for graphs of degree at most dd given by adjacency lists, it counts εdn\varepsilon d n edges. These two models behave very differently (Testing Bipartiteness).

The simplest tester

Is a bit string all zeros? Query q=⌈2/ε⌉q = \lceil 2/\varepsilon \rceil random positions and accept if all are 0. If xx is all zeros, the tester always accepts. If xx is ε\varepsilon-far, at least εn\varepsilon n positions hold a 1 (one change per 1 is needed and suffices), so all qq queries miss them with probability at most (1−ε)q≤e−εq≤e−2<13(1 - \varepsilon)^q \le e^{-\varepsilon q} \le e^{-2} < \frac{1}{3}. The query count does not depend on nn, and Ω(1/ε)\Omega(1/\varepsilon) queries are also necessary, since an input with exactly εn\varepsilon n ones hidden at random positions looks all-zero to fewer queries.

python · try it yourself
import math, random

def zero_tester(x, eps, rng):
    """One-sided tester for 'x is all zeros': q = ceil(2/eps) random positions."""
    q = math.ceil(2 / eps)
    return all(x[rng.randrange(len(x))] == 0 for _ in range(q))     # True = accept

rng = random.Random(1998)
n, eps = 100000, 0.05
print(f"n = {n}, eps = {eps}, queries q = {math.ceil(2 / eps)} (independent of n)")
print("  fraction of ones   distance to P   rejection rate over 2000 runs")
for frac in [0, 0.005, 0.02, 0.05, 0.1]:
    ones = int(frac * n)
    x = [1] * ones + [0] * (n - ones)
    rng.shuffle(x)
    rej = sum(not zero_tester(x, eps, rng) for _ in range(2000)) / 2000
    print(f"  {frac:16}   {ones / n:13}   {rej:29.3f}")
print(f"guarantee for eps-far inputs: rejection >= 1 - (1 - eps)^q >= 1 - e^-2 = {1 - math.exp(-2):.3f}")
n = 100000, eps = 0.05, queries q = 40 (independent of n)
  fraction of ones   distance to P   rejection rate over 2000 runs
                 0             0.0                           0.000
             0.005           0.005                           0.171
              0.02            0.02                           0.553
              0.05            0.05                           0.877
               0.1             0.1                           0.985
guarantee for eps-far inputs: rejection >= 1 - (1 - eps)^q >= 1 - e^-2 = 0.865

The table shows the typical shape of a tester's behaviour: never rejecting members of the property, rejecting ε\varepsilon-far inputs with probability at least 1−e−21 - e^{-2}, and doing anything in between for close inputs (a string with 0.5% ones is rejected 17% of the time, which is allowed).

Local checks are not enough

Most properties are defined by local conditions: an array is sorted when every adjacent pair is in order, a graph is bipartite when no odd cycle exists. The tempting tester checks random local conditions. The trap is that an input can be far from the property while violating very few local conditions. The program computes the true distance to sortedness (one minus the length of a longest non-decreasing subsequence, over nn) and runs the adjacent-pair tester on four arrays.

python · try it yourself
import bisect, random

def distance_to_sorted(a):
    """Fraction of entries that must change: 1 - (longest non-decreasing subsequence) / n."""
    tails = []
    for v in a:
        i = bisect.bisect_right(tails, v)
        if i == len(tails):
            tails.append(v)
        else:
            tails[i] = v
    return 1 - len(tails) / len(a)

def adjacent_pair_tester(a, q, rng):
    """A tempting but wrong tester: check q random adjacent pairs."""
    for _ in range(q):
        i = rng.randrange(len(a) - 1)
        if a[i] > a[i + 1]:
            return False
    return True

rng = random.Random(3)
n = 10000
inputs = {
    "sorted": list(range(n)),
    "two sorted halves swapped": list(range(n // 2, n)) + list(range(n // 2)),
    "sorted, then 5% random swaps": None,
    "pairs swapped (1 0 3 2 5 4 ...)": [i ^ 1 for i in range(n)],
}
b = list(range(n))
for _ in range(n // 40):
    i, j = rng.randrange(n), rng.randrange(n)
    b[i], b[j] = b[j], b[i]
inputs["sorted, then 5% random swaps"] = b
print("input                              distance   adjacent-pair tester, 100 queries: rejection rate")
for name, a in inputs.items():
    rej = sum(not adjacent_pair_tester(a, 100, rng) for _ in range(500)) / 500
    print(f"{name:34} {distance_to_sorted(a):8.3f}   {rej:.3f}")
input                              distance   adjacent-pair tester, 100 queries: rejection rate
sorted                                0.000   0.000
two sorted halves swapped             0.500   0.008
sorted, then 5% random swaps          0.049   1.000
pairs swapped (1 0 3 2 5 4 ...)       0.500   1.000

Swapping the two halves of a sorted array makes it 12\frac{1}{2}-far from sorted, yet only one adjacent pair is out of order, and 100 random pair checks almost never find it. A correct tester must use a more global structure, and the next lesson builds one from binary search. Behind this example is the main technical theme of property testing: proving that far from the property implies many local violations, a so-called robustness or rejection lemma, for a well-chosen family of local checks.

The landscape

Property Model Queries Lesson
all zeros, or any fixed string array Θ(1/ε)\Theta(1/\varepsilon) this one
sortedness (monotone array) array of length nn Θ(log⁡n/ε)\Theta(\log n / \varepsilon) Testing Sortedness
monotonicity of f:{0,1}d→{0,1}f : \{0,1\}^d \to \{0,1\} Boolean hypercube O(d/ε)O(d/\varepsilon); O~(d/ε2)\tilde O(\sqrt{d}/\varepsilon^2) same lesson
linearity of f:F2k→F2f : \mathbb{F}_2^k \to \mathbb{F}_2 Boolean function O(1/ε)O(1/\varepsilon) Linearity Testing: BLR
bipartiteness dense graph O~(1/ε)\tilde O(1/\varepsilon) sampled vertices, O~(1/ε2)\tilde O(1/\varepsilon^2) queries Testing Bipartiteness
bipartiteness bounded degree dd Θ~(n)\tilde\Theta(\sqrt{n}) same lesson
number of components, average degree graphs estimated in time independent of nn, or O~(n)\tilde O(\sqrt{n}) Sublinear Estimation

Related notions, mentioned for orientation: tolerant testing distinguishes ε1\varepsilon_1-close from ε2\varepsilon_2-far (Parnas, Ron and Rubinfeld, 2006), which is closer to estimating the distance; distribution testing asks the same questions about a probability distribution accessed through samples (uniformity needs Θ(n/ε2)\Theta(\sqrt{n}/\varepsilon^2) samples); and Goldreich, Goldwasser and Ron (1998) relate testing to learning: a property that can be learned with few queries can be tested with few, but testing is often much cheaper.

Test yourself

What must an ε\varepsilon-tester do on an input that is in the property, one that is ε\varepsilon-far, and one that is ε/2\varepsilon/2-far but not in the property?

  1. Accept, reject, reject
  2. Accept with probability at least 2/32/3, reject with probability at least 2/32/3, anything
  3. Accept, reject, accept
  4. Compute the distance in all three cases

Why does the all-zeros tester need only ⌈2/ε⌉\lceil 2/\varepsilon \rceil queries, whatever nn is?

  1. Because nn is small
  2. Because an ε\varepsilon-far string has at least εn\varepsilon n ones, so each random query finds one with probability at least ε\varepsilon, and 2/ε2/\varepsilon queries all miss with probability at most e−2e^{-2}
  3. Because it reads a prefix
  4. Because it uses hashing

Why does checking random adjacent pairs fail to test sortedness?

  1. It uses too many queries
  2. An array can be far from sorted (two swapped sorted halves are 1/21/2-far) while having only one adjacent pair out of order
  3. Adjacent pairs are never out of order
  4. It has two-sided error

What does one-sided error mean for a tester?

  1. It never rejects
  2. It accepts every input in the property with probability 1, so a rejection always comes with a witness of non-membership
  3. It errs only on far inputs with probability 1/31/3 and never on close ones
  4. It is deterministic