TExcelTAD

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 {u,v}\{u, v\} an edge?", and distance is measured in units of n2n^2 entries; there, bipartiteness can be tested by looking at a random subgraph whose size does not depend on nn. In the bounded-degree model the graph is given by adjacency lists of length at most dd, a query asks "who is the jj-th neighbour of vv?", and distance is measured in units of dndn edges; there, Θ(n)\Theta(\sqrt{n}) 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 ε\varepsilon-far from bipartite in the dense model if more than εn2\varepsilon n^2 edges must be removed to make it bipartite; equivalently, every partition (L,R)(L, R) of the vertices leaves more than εn2\varepsilon n^2 edges inside LL or inside RR. A random graph G(n,p)G(n, p), for example, is about p4\frac{p}{4}-far, since its best cut still leaves about half of its p2n2\frac{p}{2}n^2 edges uncut.

text
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 bipartite

Theorem (Goldreich, Goldwasser and Ron, 1998). The tester accepts every bipartite graph and rejects every graph that is ε\varepsilon-far from bipartite with probability at least 23\frac{2}{3}. Alon and Krivelevich (2002) showed that s=O~(1/ε)s = \tilde O(1/\varepsilon) vertices suffice, so the query complexity is O~(1/ε2)\tilde O(1/\varepsilon^2), independent of nn.

Idea of the proof (sketch). Split the sample into a small part UU of O(1εlog⁡1ε)O(\frac{1}{\varepsilon}\log\frac{1}{\varepsilon}) vertices and a larger part WW. Any 2-colouring of UU suggests a colouring of most of the graph: put a vertex on the side opposite to its neighbours in UU. Because GG is ε\varepsilon-far, this suggested partition leaves many edges violated, and a random set WW of size O(1ε2log⁡1ε)O(\frac{1}{\varepsilon^2}\log\frac{1}{\varepsilon}) hits one of them, with an endpoint whose colour is forced by UU, with high probability. A union bound over the 2∣U∣2^{\lvert U \rvert} colourings of UU (which is where the logarithmic factor comes from) shows that, with probability at least 23\frac{2}{3}, no colouring of UU extends to a proper colouring of U∪WU \cup W, so the sample is not bipartite. The care in the real proof goes into vertices with few neighbours in UU, 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 G(400,0.1)G(400, 0.1), and runs the tester with several sample sizes.

python · try it yourself
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 dd and is ε\varepsilon-far if more than εdn\varepsilon d n edges must be removed. A random graph with constant degree is far from bipartite, yet its shortest odd cycles have length about log⁡n\log n, and a small sample of vertices sees no edges at all. Exploration is needed. Goldreich and Ron (1999) used random walks:

text
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  accept

Reaching a vertex vv along two walks of different parity closes an odd closed walk through ss and vv, which contains an odd cycle, so the tester never rejects a bipartite graph. The n\sqrt{n} is a birthday paradox: after LL steps a walk on a well-connected graph is spread over about nn vertices, and KK walks must collide; KK independent endpoints collide once K≈nK \approx \sqrt{n}.

Theorem (Goldreich and Ron, 1999, 1997). Bipartiteness in the bounded-degree model can be tested with O(n poly⁡(log⁡n/ε))O(\sqrt{n}\,\operatorname{poly}(\log n/\varepsilon)) queries, and every tester needs Ω(n)\Omega(\sqrt{n}) queries, even for constant ε\varepsilon and d=3d = 3.

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 n\sqrt{n} vertices. The program runs walks on random cubic graphs (unions of three random perfect matchings), with about n\sqrt{n} walks of length 2log⁡2n2\log_2 n, and also with only 8 walks.

python · try it yourself
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 n\sqrt{n} walks the non-bipartite graphs are rejected almost always; with a fixed number of walks the rejection rate collapses as nn grows, exactly as the Ω(n)\Omega(\sqrt{n}) lower bound predicts.

In C++

The same tester on graphs with 200 000 vertices: 447 walks of length 40, under 18 000 queries.

cpp · try it yourself
#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) n2n^2 entries O~(1/ε2)\tilde O(1/\varepsilon^2) queries every hereditary property (closed under removing vertices) is testable with query complexity independent of nn (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 dd (adjacency lists) dndn edges Θ~(n)\tilde\Theta(\sqrt{n}) queries connectivity and (with two-sided error) cycle-freeness need poly⁡(1/ε)\operatorname{poly}(1/\varepsilon) queries; bipartiteness and expansion need about n\sqrt{n}; 3-colourability needs Ω(n)\Omega(n) (Bogdanov, Obata and Trevisan, 2002)

In the dense model even kk-colourability for any fixed kk is testable in time independent of nn (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 kk-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?

  1. It computes a maximum cut
  2. It samples a set of vertices whose size depends only on ε\varepsilon, queries all pairs among them, and accepts iff the induced subgraph is bipartite
  3. It runs random walks
  4. It counts triangles

Why can the bounded-degree tester never reject a bipartite graph?

  1. Because it samples few vertices
  2. 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
  3. Because bipartite graphs have no cycles
  4. Because the walks are short

Where does the n\sqrt{n} in the bounded-degree bipartiteness bounds come from?

  1. From the degree bound
  2. From the birthday paradox: walks that have mixed over about nn vertices collide only after about n\sqrt{n} of them, and a smaller exploration cannot tell a random bipartite cubic graph from a random cubic graph
  3. From the number of edges
  4. From Chernoff bounds