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 over a domain of size that the algorithm can query: an array (), a Boolean function (), or a graph given by its adjacency matrix or adjacency lists. A property is a set of such functions (all sorted arrays, all linear functions, all bipartite graphs).
- The distance of to is the smallest fraction of positions that must be changed to put into :
is -far from if , and -close otherwise.
An -tester for is a randomized algorithm that, given query access to and the parameter ,
- accepts with probability at least if ,
- rejects with probability at least if is -far from .
It has one-sided error if it accepts every with probability 1; it then rejects only with a witness, a set of queried positions that no member of could produce.
The query complexity is the number of queries in the worst case. The tester is efficient if is sublinear in , and remarkable if it is independent of .
The constant is arbitrary: repeating the tester times and taking the majority (or, for one-sided testers, rejecting if any run rejects) brings the error to . 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 adjacency matrix ( edges); for graphs of degree at most given by adjacency lists, it counts edges. These two models behave very differently (Testing Bipartiteness).
The simplest tester
Is a bit string all zeros? Query random positions and accept if all are 0. If is all zeros, the tester always accepts. If is -far, at least positions hold a 1 (one change per 1 is needed and suffices), so all queries miss them with probability at most . The query count does not depend on , and queries are also necessary, since an input with exactly ones hidden at random positions looks all-zero to fewer queries.
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 -far inputs with probability at least , 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 ) and runs the adjacent-pair tester on four arrays.
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 -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 | this one | |
| sortedness (monotone array) | array of length | Testing Sortedness | |
| monotonicity of | Boolean hypercube | ; | same lesson |
| linearity of | Boolean function | Linearity Testing: BLR | |
| bipartiteness | dense graph | sampled vertices, queries | Testing Bipartiteness |
| bipartiteness | bounded degree | same lesson | |
| number of components, average degree | graphs | estimated in time independent of , or | Sublinear Estimation |
Related notions, mentioned for orientation: tolerant testing distinguishes -close from -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 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 -tester do on an input that is in the property, one that is -far, and one that is -far but not in the property?
- Accept, reject, reject
- Accept with probability at least , reject with probability at least , anything
- Accept, reject, accept
- Compute the distance in all three cases
Why does the all-zeros tester need only queries, whatever is?
- Because is small
- Because an -far string has at least ones, so each random query finds one with probability at least , and queries all miss with probability at most
- Because it reads a prefix
- Because it uses hashing
Why does checking random adjacent pairs fail to test sortedness?
- It uses too many queries
- An array can be far from sorted (two swapped sorted halves are -far) while having only one adjacent pair out of order
- Adjacent pairs are never out of order
- It has two-sided error
What does one-sided error mean for a tester?
- It never rejects
- It accepts every input in the property with probability 1, so a rejection always comes with a witness of non-membership
- It errs only on far inputs with probability and never on close ones
- It is deterministic