Testing Bipartiteness
Bipartiteness is the test case that shows how much the access model matters in graph property testing. In the dense graph model the graph is an adjacency matrix, a query asks "is an edge?", and distance is measured in units of entries; there, bipartiteness can be tested by looking at a random subgraph whose size does not depend on . In the bounded-degree model the graph is given by adjacency lists of length at most , a query asks "who is the -th neighbour of ?", and distance is measured in units of edges; there, queries (up to polylogarithmic factors) are necessary and sufficient. Both testers have one-sided error: they reject only after finding an odd cycle.
The dense graph model
A graph is -far from bipartite in the dense model if more than edges must be removed to make it bipartite; equivalently, every partition of the vertices leaves more than edges inside or inside . A random graph , for example, is about -far, since its best cut still leaves about half of its edges uncut.
Dense bipartiteness tester (Goldreich, Goldwasser and Ron, 1998)
1 S ← a uniformly random set of s = O(log(1/ε) / ε²) vertices
2 query all pairs in S (s² queries)
3 accept iff the subgraph induced by S is bipartiteTheorem (Goldreich, Goldwasser and Ron, 1998). The tester accepts every bipartite graph and rejects every graph that is -far from bipartite with probability at least . Alon and Krivelevich (2002) showed that vertices suffice, so the query complexity is , independent of .
Idea of the proof (sketch). Split the sample into a small part of vertices and a larger part . Any 2-colouring of suggests a colouring of most of the graph: put a vertex on the side opposite to its neighbours in . Because is -far, this suggested partition leaves many edges violated, and a random set of size hits one of them, with an endpoint whose colour is forced by , with high probability. A union bound over the colourings of (which is where the logarithmic factor comes from) shows that, with probability at least , no colouring of extends to a proper colouring of , so the sample is not bipartite. The care in the real proof goes into vertices with few neighbours in , whose colour is not forced.
The program builds three graphs on 400 vertices, a bipartite one, the same graph with 30 edges added inside one side (very close to bipartite), and , and runs the tester with several sample sizes.
import random
from collections import deque
def is_bipartite(vertices, adj):
"""BFS 2-colouring of the subgraph induced by `vertices` (adj is the full adjacency matrix)."""
colour = {}
for s in vertices:
if s in colour:
continue
colour[s] = 0
queue = deque([s])
while queue:
u = queue.popleft()
for v in vertices:
if adj[u][v]:
if v not in colour:
colour[v] = colour[u] ^ 1
queue.append(v)
elif colour[v] == colour[u]:
return False
return True
def dense_tester(adj, s, rng):
"""Sample s vertices and accept iff the induced subgraph is bipartite (one-sided error)."""
return is_bipartite(rng.sample(range(len(adj)), s), adj)
rng = random.Random(1998)
n, p = 400, 0.1
side = [rng.randrange(2) for _ in range(n)]
bip = [[0] * n for _ in range(n)]
gnp = [[0] * n for _ in range(n)]
for u in range(n):
for v in range(u + 1, n):
if side[u] != side[v] and rng.random() < 2 * p:
bip[u][v] = bip[v][u] = 1
if rng.random() < p:
gnp[u][v] = gnp[v][u] = 1
close = [row[:] for row in bip]
for _ in range(30): # 30 edges inside the sides: very close to bipartite
u, v = rng.sample([x for x in range(n) if side[x] == 0], 2)
close[u][v] = close[v][u] = 1
graphs = {"bipartite": bip, "bipartite + 30 bad edges": close, "random G(n, 0.1)": gnp}
print(f"n = {n}; rejection rate over 200 runs for sample size s")
print("graph s = 5 s = 10 s = 20 s = 40")
for name, adj in graphs.items():
rates = [sum(not dense_tester(adj, s, rng) for _ in range(200)) / 200 for s in [5, 10, 20, 40]]
print(f"{name:26}" + "".join(f"{r:9.3f}" for r in rates))n = 400; rejection rate over 200 runs for sample size s
graph s = 5 s = 10 s = 20 s = 40
bipartite 0.000 0.000 0.000 0.000
bipartite + 30 bad edges 0.000 0.010 0.035 0.255
random G(n, 0.1) 0.010 0.095 0.780 1.000
The bipartite graph is never rejected (one-sided error). The random graph is far from bipartite and is rejected with near certainty once the sample has 40 vertices, a tenth of the graph here but the same 40 for a graph with a billion vertices. The nearly bipartite graph is rejected only occasionally: it is close to the property, so either answer is allowed, and a sample sees one of its 30 bad edges only if it contains both ends.
The bounded-degree model
Now the graph has maximum degree and is -far if more than edges must be removed. A random graph with constant degree is far from bipartite, yet its shortest odd cycles have length about , and a small sample of vertices sees no edges at all. Exploration is needed. Goldreich and Ron (1999) used random walks:
Bounded-degree bipartiteness tester (Goldreich and Ron, 1999), simplified
1 repeat O(1/ε) times:
2 s ← a random vertex
3 perform K = Õ(√n) random walks of length L = poly(log n / ε) from s
4 if some vertex is reached once after an even and once after an odd number of steps: reject
5 acceptReaching a vertex along two walks of different parity closes an odd closed walk through and , which contains an odd cycle, so the tester never rejects a bipartite graph. The is a birthday paradox: after steps a walk on a well-connected graph is spread over about vertices, and walks must collide; independent endpoints collide once .
Theorem (Goldreich and Ron, 1999, 1997). Bipartiteness in the bounded-degree model can be tested with queries, and every tester needs queries, even for constant and .
The lower bound is the birthday paradox in reverse: a random 3-regular bipartite graph and a random 3-regular graph (far from bipartite) look the same, cycle-free, to any algorithm that explores fewer than about vertices. The program runs walks on random cubic graphs (unions of three random perfect matchings), with about walks of length , and also with only 8 walks.
import math, random
def random_cubic(n, rng, bipartite):
"""A random 3-regular multigraph from 3 random perfect matchings (between the halves if bipartite)."""
adj = [[] for _ in range(n)]
for _ in range(3):
if bipartite:
right = list(range(n // 2, n))
rng.shuffle(right)
pairs = zip(range(n // 2), right)
else:
perm = list(range(n))
rng.shuffle(perm)
pairs = zip(perm[0::2], perm[1::2])
for u, v in pairs:
adj[u].append(v)
adj[v].append(u)
return adj
def walk_tester(adj, walks, length, rng):
"""Goldreich-Ron style: random walks from one start; reject if a vertex is reached at both parities."""
s = rng.randrange(len(adj))
seen = {s: {0}}
queries = 0
for _ in range(walks):
v, par = s, 0
for _ in range(length):
v = rng.choice(adj[v])
queries += 1
par ^= 1
seen.setdefault(v, set()).add(par)
if len(seen[v]) == 2:
return False, queries # two walks of different parity meet: odd cycle
return True, queries
rng = random.Random(1999)
print(" n walks bipartite: rejected random cubic: rejected (with only 8 walks) queries")
for n in [1000, 4000, 16000]:
walks, length = int(math.sqrt(n)), int(2 * math.log2(n))
gb, gr = random_cubic(n, rng, True), random_cubic(n, rng, False)
rb = sum(not walk_tester(gb, walks, length, rng)[0] for _ in range(100))
rr = sum(not walk_tester(gr, walks, length, rng)[0] for _ in range(100))
few = sum(not walk_tester(gr, 8, length, rng)[0] for _ in range(100))
print(f"{n:6} {walks:5} {rb:13} / 100 {rr:16} / 100 {few:13} / 100 {walks * length:7}") n walks bipartite: rejected random cubic: rejected (with only 8 walks) queries
1000 31 0 / 100 92 / 100 40 / 100 589
4000 63 0 / 100 98 / 100 10 / 100 1449
16000 126 0 / 100 100 / 100 2 / 100 3402
With walks the non-bipartite graphs are rejected almost always; with a fixed number of walks the rejection rate collapses as grows, exactly as the lower bound predicts.
In C++
The same tester on graphs with 200 000 vertices: 447 walks of length 40, under 18 000 queries.
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <random>
#include <unordered_map>
#include <utility>
#include <vector>
using Graph = std::vector<std::vector<std::uint32_t>>;
Graph random_cubic(std::uint32_t n, bool bipartite, std::mt19937_64& rng) {
Graph adj(n);
std::vector<std::uint32_t> p(n);
for (int round = 0; round < 3; ++round) { // union of 3 random perfect matchings
for (std::uint32_t i = 0; i < n; ++i) p[i] = i;
std::uint32_t lo = bipartite ? n / 2 : 0; // bipartite: shuffle only the right half
for (std::uint32_t i = n - 1; i > lo; --i) std::swap(p[i], p[lo + rng() % (i - lo + 1)]);
for (std::uint32_t i = 0; i < n / 2; ++i) {
std::uint32_t u = bipartite ? i : p[2 * i], v = bipartite ? p[n / 2 + i] : p[2 * i + 1];
adj[u].push_back(v); adj[v].push_back(u);
}
}
return adj;
}
// Random walks from one start vertex; reject when some vertex is reached with both parities.
bool walk_tester(const Graph& g, int walks, int length, std::mt19937_64& rng) {
std::uint32_t s = rng() % g.size();
std::unordered_map<std::uint32_t, std::uint8_t> parities{{s, 1}}; // bit 0: even seen, bit 1: odd seen
for (int w = 0; w < walks; ++w) {
std::uint32_t v = s; int par = 0;
for (int t = 0; t < length; ++t) {
v = g[v][rng() % g[v].size()];
par ^= 1;
if ((parities[v] |= std::uint8_t(1 << par)) == 3) return false;
}
}
return true;
}
int main() {
std::mt19937_64 rng(1999);
const std::uint32_t n = 200000;
Graph bip = random_cubic(n, true, rng), other = random_cubic(n, false, rng);
int walks = (int)std::sqrt(double(n)), length = 40;
int rb = 0, rg = 0;
for (int r = 0; r < 50; ++r) { rb += !walk_tester(bip, walks, length, rng); rg += !walk_tester(other, walks, length, rng); }
std::printf("n = %u, %d walks of length %d (%d queries, %.1f%% of the vertices)\n",
n, walks, length, walks * length, 100.0 * walks * length / n);
std::printf("bipartite cubic graph: rejected %d of 50 runs\nrandom cubic graph: rejected %d of 50 runs\n", rb, rg);
}n = 200000, 447 walks of length 40 (17880 queries, 8.9% of the vertices)
bipartite cubic graph: rejected 0 of 50 runs
random cubic graph: rejected 50 of 50 runs
The general picture
| Model | Distance unit | Bipartiteness | General picture |
|---|---|---|---|
| dense (adjacency matrix) | entries | queries | every hereditary property (closed under removing vertices) is testable with query complexity independent of (Alon and Shapira, 2008, via Szemerédi's regularity lemma), and the testable properties are characterized by regularity (Alon, Fischer, Newman and Shapira, 2009) |
| bounded degree (adjacency lists) | edges | queries | connectivity and (with two-sided error) cycle-freeness need queries; bipartiteness and expansion need about ; 3-colourability needs (Bogdanov, Obata and Trevisan, 2002) |
In the dense model even -colourability for any fixed is testable in time independent of (Goldreich, Goldwasser and Ron, 1998), although deciding it exactly is NP-hard: the tester accepts with a small sample and, when it does, there is a -colouring with few violated edges, but finding it is a different problem.
Test yourself
In the dense graph model, how does the bipartiteness tester decide?
- It computes a maximum cut
- It samples a set of vertices whose size depends only on , queries all pairs among them, and accepts iff the induced subgraph is bipartite
- It runs random walks
- It counts triangles
Why can the bounded-degree tester never reject a bipartite graph?
- Because it samples few vertices
- Because it rejects only when a vertex is reached by walks of different parity, which exhibits an odd closed walk and therefore an odd cycle
- Because bipartite graphs have no cycles
- Because the walks are short
Where does the in the bounded-degree bipartiteness bounds come from?
- From the degree bound
- From the birthday paradox: walks that have mixed over about vertices collide only after about of them, and a smaller exploration cannot tell a random bipartite cubic graph from a random cubic graph
- From the number of edges
- From Chernoff bounds