Companion notebook#

Companion of the research report The Exact Stabilization Time of Self-Stabilizing Coloring: Mean, Variance, and Distribution, by Élie de Panafieu, Fabien Mathieu, Maria Potop-Butucaru and Sébastien Tixeuil.

It reproduces the numerical statements of the report with tinto. Each statement is checked by confronting independent sources:

  • closed forms, evaluated by tinto.theory;

  • exact enumeration of small cases, by tinto.exact;

  • Monte Carlo, by tinto.oracle and by the dynamics of tinto.

The three sources share no code beyond the definition of the graphs (a test of tinto enforces it), so an agreement between two of them is evidence, not a tautology.

This notebook is not self-contained: the report gives the statements, their proofs and their context. The report cites a tagged version of tinto; this page follows the current one. With the default settings, the whole notebook runs in a few minutes on a laptop.

Setting#

A graph with \(n\) nodes starts from a uniform random coloring with \(k\) colors. A node that shares its color with a neighbor is enabled; when activated, it recolors itself with a color absent from its neighborhood, from a palette of at least \(\Delta + 1\) colors. Under the random central daemon, one enabled node is activated at a time, uniformly. The stabilization time \(T\) is the number of moves until no node is enabled.

The report reduces \(T\) to a static statistic (reduction lemma). Label the nodes by a uniform random permutation; a node is a peak when its label exceeds the labels of all its neighbors that share its initial color. Then \(T = n - S\) in law, where \(S\) is the number of peaks.

Two consequences shape this notebook:

  • \(T\) can be sampled without running the dynamics: draw the colors and the labels, count the peaks. This is tinto.oracle, used for the figures. The statistic is defined for every \(k\), including \(k < \Delta + 1\), since the oracle never runs the dynamics.

  • For this rule, tinto’s Shuffled scheduler (a round-robin over a random permutation) has the law of the random central daemon: a disabled node never becomes enabled again, so each node moves at most once, at its first visit, exactly when a same-colored neighbor is still unvisited.

The section on the reduction lemma itself checks the dynamics against exact enumeration, with a daemon that activates a uniform enabled node, as in the report.

[1]:
import time
from fractions import Fraction
from math import exp, factorial, prod

import matplotlib.pyplot as plt
import numpy as np
import sympy as sp
from numba import int64, njit, prange
from numba.experimental import jitclass
from scipy import integrate
from scipy.sparse import csr_array
from scipy.sparse.csgraph import connected_components
from sympy.polys.rings import ring as polynomial_ring

from tinto import configs, exact, oracle, runners, solvers, starters
from tinto.graphs import edges_to_graph, erdos_renyi as gnp, line, ring
from tinto.io import set_seed
from tinto.theory import bipartite, cayley, erdos_renyi, general, path_cycle, star

set_seed(42)
TRIALS = 60_000  # samples per point, as in the report
START = time.perf_counter()

Test graphs#

The exact checks run on fourteen graphs with at most seven nodes, small enough to enumerate every labeling and every coloring. The \(G(7, 1/2)\) graph and the tree are fixed samples, drawn once.

[2]:
EDGES = {
    "path P5": (5, [(0, 1), (1, 2), (2, 3), (3, 4)]),
    "path P7": (7, [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]),
    "cycle C6": (6, [(0, 1), (0, 5), (1, 2), (2, 3), (3, 4), (4, 5)]),
    "cycle C7": (7, [(0, 1), (0, 6), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]),
    "star K(1,6)": (7, [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6)]),
    "complete K5": (
        5,
        [
            (0, 1),
            (0, 2),
            (0, 3),
            (0, 4),
            (1, 2),
            (1, 3),
            (1, 4),
            (2, 3),
            (2, 4),
            (3, 4),
        ],
    ),
    "complete bipartite K(2,3)": (5, [(0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4)]),
    "complete bipartite K(3,3)": (
        6,
        [(0, 3), (0, 4), (0, 5), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)],
    ),
    "bull": (5, [(0, 1), (0, 2), (1, 2), (1, 3), (2, 4)]),
    "house": (5, [(0, 1), (0, 3), (0, 4), (1, 2), (1, 4), (2, 3)]),
    "grid 2x3": (6, [(0, 1), (0, 3), (1, 2), (1, 4), (2, 5), (3, 4), (4, 5)]),
    "wheel W6 (7 nodes)": (
        7,
        [
            (0, 1),
            (0, 2),
            (0, 3),
            (0, 4),
            (0, 5),
            (0, 6),
            (1, 2),
            (1, 6),
            (2, 3),
            (3, 4),
            (4, 5),
            (5, 6),
        ],
    ),
    "G(7, 1/2) sample": (
        7,
        [(0, 2), (0, 4), (0, 5), (1, 2), (1, 5), (2, 3), (2, 4), (2, 5), (3, 6)],
    ),
    "uniform tree sample (7 nodes)": (
        7,
        [(0, 5), (0, 6), (1, 3), (2, 3), (3, 5), (4, 6)],
    ),
}
TEST_GRAPHS = {
    name: edges_to_graph(n, np.array(edges)) for name, (n, edges) in EDGES.items()
}

Reduction lemma: the dynamics against the exact law#

The report proves that \(T\) and \(n - S\) have the same law (reduction lemma). Here the dynamics runs for real, and its number of moves is compared with the exact law of \(n - S\), obtained by enumerating every labeling and every coloring (tinto.exact).

The daemon is the one of the report: at each step, one enabled node is drawn uniformly among the enabled ones. tinto does not ship it, because for this rule Shuffled has the same law (see the setting). Using Shuffled here would only test the second half of the lemma: once the activation order is a uniform permutation, the moves are the non-peaks. Defining the daemon of the report keeps the first half under test as well. In tinto, a scheduler is a jitclass whose draw(config) returns the nodes to activate, here at most one.

[3]:
@jitclass
class UniformEnabled:
    """Random central daemon: one enabled node, drawn uniformly."""

    one: int64[:]
    empty: int64[:]

    def __init__(self):
        self.one = np.zeros(1, dtype=np.int64)
        self.empty = np.zeros(0, dtype=np.int64)

    def draw(self, config):
        if config.total == 0:
            return self.empty
        r = np.random.randint(
            config.total
        )  # rank of the chosen node among the enabled ones
        for i in range(config.graph.n):
            if config.enabled[i]:
                if r == 0:
                    self.one[0] = i
                    return self.one
                r -= 1
        return self.empty

The initial coloring draws \(k\) colors and the palette has \(\max(k, \Delta + 1)\) colors (the k_init option of the starters); the activated node recolors itself with a uniform free color. For each of the fourteen graphs and \(k \in \{1, 2, 3\}\), the dynamics runs 4,000 times. For every value \(t\), the observed count is compared with \(4000\, \mathbb P(n - S = t)\) in standard deviations of a binomial count; a value outside the support of the exact law would fail the check.

[4]:
Config = (
    configs.make()
)  # conflict guard: a node is enabled when a neighbor shares its color
solver = solvers.make(solvers.colorer_random)  # a uniform free color
RUNS = 4000


def moves(graph, k, runs):
    starter = starters.from_graph(Config)(graph, k_init=k)
    return np.array(
        [
            runners.simple(starter.draw(), UniformEnabled(), solver)[0]
            for _ in range(runs)
        ]
    )


t0 = time.perf_counter()
worst = 0.0
for name, g in TEST_GRAPHS.items():
    line_ = []
    for k in (1, 2, 3):
        hist = exact.peaks_distribution(g, k)
        law = hist[::-1] / hist.sum()  # law of T = n - S
        counts = np.bincount(moves(g, k, RUNS), minlength=g.n + 1)
        assert not counts[law == 0].any(), (
            name,
            k,
            "move count outside the exact support",
        )
        p = law[law > 0]
        sd = np.sqrt(RUNS * p * (1 - p))
        dev = np.max(np.abs(counts[law > 0] - RUNS * p) / np.where(sd > 0, sd, 1.0))
        worst = max(worst, dev)
        line_.append(f"k={k}: {dev:4.2f}")
    print(f"{name:30s} " + "   ".join(line_))
print(
    f"largest deviation {worst:.2f} standard deviations ({time.perf_counter() - t0:.0f} s)"
)
assert worst <= 4.5
path P5                        k=1: 0.11   k=2: 1.26   k=3: 0.94
path P7                        k=1: 1.17   k=2: 0.94   k=3: 2.50
cycle C6                       k=1: 0.59   k=2: 1.45   k=3: 0.82
cycle C7                       k=1: 1.17   k=2: 1.33   k=3: 1.53
star K(1,6)                    k=1: 1.16   k=2: 1.24   k=3: 1.14
complete K5                    k=1: 0.00   k=2: 0.26   k=3: 1.47
complete bipartite K(2,3)      k=1: 1.05   k=2: 1.25   k=3: 1.45
complete bipartite K(3,3)      k=1: 1.00   k=2: 1.54   k=3: 1.87
bull                           k=1: 2.06   k=2: 1.63   k=3: 1.06
house                          k=1: 1.04   k=2: 3.39   k=3: 1.08
grid 2x3                       k=1: 0.28   k=2: 2.25   k=3: 2.03
wheel W6 (7 nodes)             k=1: 2.58   k=2: 1.12   k=3: 2.80
G(7, 1/2) sample               k=1: 1.03   k=2: 2.63   k=3: 3.04
uniform tree sample (7 nodes)  k=1: 1.26   k=2: 1.60   k=3: 1.33
largest deviation 3.39 standard deviations (8 s)

Theorems 1 and 3: mean and second factorial moment on any graph#

Theorem 1 gives \(\mathbb E S = \sum_v \rho(d_v, k)\). Theorem 3 gives \(\mathbb E S(S-1)\) as a sum over pairs of nodes, through their private and common neighbors: a double integral over the labels of the pair, of a polynomial, evaluated exactly. tinto.theory.general computes both in rational arithmetic; they must equal, as fractions, the moments of the exact law.

[5]:
print(
    f"{'graph':30s} {'E S':>12s} {'E S(S-1)':>14s}   (monochrome; k = 1, 2, 3 all checked)"
)
for name, g in TEST_GRAPHS.items():
    for k in (1, 2, 3):
        formula = general.moments(g, k)
        assert formula == exact.factorial_moments(exact.peaks_distribution(g, k)), (
            name,
            k,
        )
    es, ess = general.moments(g, 1)
    print(f"{name:30s} {str(es):>12s} {str(ess):>14s}")
print(
    "Theorems 1 and 3 agree exactly with the enumeration on the 14 graphs, k = 1, 2, 3"
)
graph                                   E S       E S(S-1)   (monochrome; k = 1, 2, 3 all checked)
path P5                                   2          34/15
path P7                                 8/3           24/5
cycle C6                                  2          34/15
cycle C7                                7/3         154/45
star K(1,6)                            22/7             10
complete K5                               1              0
complete bipartite K(2,3)               3/2            6/5
complete bipartite K(3,3)               3/2            6/5
bull                                   11/6          29/15
house                                   3/2              1
grid 2x3                               11/6          86/45
wheel W6 (7 nodes)                    23/14           10/7
G(7, 1/2) sample                       13/6        949/315
uniform tree sample (7 nodes)          11/4        983/180
Theorems 1 and 3 agree exactly with the enumeration on the 14 graphs, k = 1, 2, 3

The star maximizes the variance#

Monochrome, the report shows that the variance of \(T\) is largest on the star \(\mathrm{St}_n\) (one center, \(n - 1\) leaves), for every \(n \ge 3\), and on no other graph (exact variance maximizer). On the star, \(T\) is the label rank of the center, up to one value: \(\mathbb P(T = j) = 1/n\) for \(1 \le j \le n - 2\) and \(\mathbb P(T = n - 1) = 2/n\) (star law, tinto.theory.star). The proof goes through the covariances of the peak indicators \(X_u\): \(-\mathbb E X_u\, \mathbb E X_v\) for adjacent nodes, and

\[\mathrm{Cov}(X_u, X_v) = \frac{b}{(a + b + 1)(b + c + 1)(a + b + c + 2)}\]

for non-adjacent nodes with \(a\) private neighbors of \(u\), \(b\) common neighbors and \(c\) private neighbors of \(v\) (pairwise covariance). general.monochrome_variance sums them in floating point, compiled, for the loops over millions of graphs below. First the star, then this variance, against the enumeration:

[6]:
for n in range(3, 8):
    st = edges_to_graph(n, np.array([(0, i) for i in range(1, n)]))
    hist = exact.peaks_distribution(st)
    es, ess = exact.factorial_moments(hist)
    assert [Fraction(int(h), factorial(n)) for h in hist] == star.law(n)
    assert (n - es, ess + es - es * es) == (star.mean(n), star.variance(n))
print("star: law, mean and variance = enumeration, 3 <= n <= 7")

worst = 0.0
for g in TEST_GRAPHS.values():
    es, ess = exact.factorial_moments(exact.peaks_distribution(g))
    var = general.monochrome_variance(g.to_adja().astype(np.bool_))
    worst = max(worst, abs(var - float(ess + es - es * es)))
print(
    f"float variance against the enumeration, 14 test graphs: largest gap {worst:.1e}"
)
assert worst < 1e-12
star: law, mean and variance = enumeration, 3 <= n <= 7
float variance against the enumeration, 14 test graphs: largest gap 4.4e-16

For \(n \ge 7\), the proof bounds the variance of a graph without isolated nodes by its profile: with \(L\) leaves (nodes of degree 1), \(x = n - L\) other nodes, and at most \(\ell^*\) leaves on a single node,

\[\mathrm{Var}\, T \le \frac L4 + \frac{2x}9 + \frac{L(\ell^* - 1)}{12} + \frac{L(x - 1)}{12} + \frac{x(x - 1) - 2(x - L)^+}{18} - \frac Ln,\]

and this bound falls below the variance of the star unless the graph is the star (\(\ell^* = n - 1\)). The cases \(n \le 6\) rest on an exhaustive enumeration, which the report extends to \(n = 7\). Below, every labeled graph on \(n \le 7\) nodes, as a bit mask of its edges (\(2^{21}\) graphs at \(n = 7\)):

  • the largest variance is the star’s, attained by exactly \(n\) labeled graphs (the choice of the center);

  • the profile bound holds on every graph without isolated nodes, and at \(n = 7\) falls below the star on every other graph;

  • the variance vanishes exactly on the disjoint unions of cliques (zero variance), that is, the graphs without an induced path on three nodes; there is one per set partition of the nodes, so they number the Bell numbers.

[7]:
@njit
def degrees(adj):
    n = adj.shape[0]
    deg = np.zeros(n, dtype=np.int64)
    for u in range(n):
        for w in range(n):
            deg[u] += adj[u, w]
    return deg


@njit
def profile_bound(adj):
    # The bound of the proof, and the largest number of leaves on a single node.
    n = adj.shape[0]
    deg = degrees(adj)
    ell = np.zeros(n, dtype=np.int64)
    for u in range(n):
        if deg[u] == 1:
            for w in range(n):
                if adj[u, w]:
                    ell[w] += 1
    leaves = (deg == 1).sum()
    x, top = n - leaves, ell.max()
    # x = 0 is a perfect matching, of variance 0: (x - 1)^+ keeps the bound valid there
    bound = (
        leaves / 4
        + 2 * x / 9
        + leaves * (top - 1) / 12
        + leaves * max(x - 1, 0) / 12
        + (x * (x - 1) - 2 * max(x - leaves, 0)) / 18
        - leaves / n
    )
    return bound, top


@njit
def has_induced_p3(adj):
    n = adj.shape[0]
    for u in range(n):
        for v in range(u + 1, n):
            if not adj[u, v]:
                for w in range(n):
                    if adj[u, w] and adj[v, w]:
                        return True
    return False


@njit
def scan_all_graphs(n, star_var):
    pairs = [(u, v) for u in range(n) for v in range(u + 1, n)]
    adj = np.zeros((n, n), dtype=np.bool_)
    best, maximizers, zero, zero_mismatch, bound_fail = -1.0, 0, 0, 0, 0
    for mask in range(1 << len(pairs)):
        for i, (u, v) in enumerate(pairs):
            adj[u, v] = adj[v, u] = ((mask >> i) & 1) == 1
        var = general.monochrome_variance(adj)
        if var > best + 1e-9:
            best, maximizers = var, 1
        elif var > best - 1e-9:
            maximizers += 1
        vanishes = abs(var) < 1e-12
        zero += vanishes
        zero_mismatch += vanishes == has_induced_p3(adj)
        if degrees(adj).min() > 0:
            bound, top = profile_bound(adj)
            if var > bound + 1e-9 or (
                n >= 7 and top < n - 1 and bound > star_var - 1e-9
            ):
                bound_fail += 1
    return best, maximizers, zero, zero_mismatch, bound_fail


t0 = time.perf_counter()
print(
    f"{'n':>2s} {'graphs':>10s} {'max Var T':>10s} {'star':>10s} {'attained':>9s} {'Var T = 0':>10s}"
)
for n in range(3, 8):
    star_var = float(star.variance(n))
    best, maximizers, zero, zero_mismatch, bound_fail = scan_all_graphs(n, star_var)
    print(
        f"{n:2d} {2 ** (n * (n - 1) // 2):10,d} {best:10.6f} {star_var:10.6f} {maximizers:9d} {zero:10d}"
    )
    assert abs(best - star_var) < 1e-9 and maximizers == n
    assert zero == sp.bell(n) and zero_mismatch == 0 and bound_fail == 0
print(
    f"star the unique maximizer up to its labelings, profile bound and zero variance checked ({time.perf_counter() - t0:.0f} s)"
)
 n     graphs  max Var T       star  attained  Var T = 0
 3          8   0.222222   0.222222         3          5
 4         64   0.687500   0.687500         4         15
 5      1,024   1.360000   1.360000         5         52
 6     32,768   2.222222   2.222222         6        203
 7  2,097,152   3.265306   3.265306         7        877
star the unique maximizer up to its labelings, profile bound and zero variance checked (3 s)

The bound beyond \(n = 7\), on random graphs and on graphs close to the star, for \(7 \le n \le 30\): per \(n\), 300 samples of \(G(n, p)\) with \(p\) uniform in \([0.03, 0.6]\), the complete bipartite graph \(K_{2, n-2}\), a double star, and, for \(0 \le e \le 5\), the star with \(e\) disjoint edges among its leaves and the star with a pendant path of \(e\) nodes. Isolated nodes are linked to their successor.

[8]:
def probe_graphs(n, rng):
    graphs = []
    for _ in range(300):
        a = np.triu(rng.random((n, n)) < rng.uniform(0.03, 0.6), 1)
        graphs.append(a | a.T)
    a = np.zeros((n, n), dtype=np.bool_)  # K(2, n - 2)
    a[:2, 2:] = a[2:, :2] = True
    graphs.append(a)
    a = np.zeros((n, n), dtype=np.bool_)  # double star
    h = n // 2
    a[0, 2:h] = a[2:h, 0] = a[1, h:] = a[h:, 1] = a[0, 1] = a[1, 0] = True
    graphs.append(a)
    for e in range(min(6, n - 2)):
        a = np.zeros((n, n), dtype=np.bool_)  # star with e edges among its leaves
        a[0, 1:] = a[1:, 0] = True
        for j in range(e):
            if 2 + 2 * j < n:
                a[1 + 2 * j, 2 + 2 * j] = a[2 + 2 * j, 1 + 2 * j] = True
        graphs.append(a)
        a = np.zeros((n, n), dtype=np.bool_)  # star with a pendant path
        a[0, 1 : n - e] = a[1 : n - e, 0] = True
        for j in range(n - e, n):
            a[j - 1, j] = a[j, j - 1] = True
        graphs.append(a)
    for a in graphs:
        for u in np.flatnonzero(a.sum(axis=1) == 0):
            a[u, (u + 1) % n] = a[(u + 1) % n, u] = True
    return graphs


rng = np.random.default_rng(1)
count = 0
for n in range(7, 31):
    star_var = float(star.variance(n))
    for a in probe_graphs(n, rng):
        bound, top = profile_bound(a)
        assert general.monochrome_variance(a) <= bound + 1e-9
        assert top == n - 1 or bound < star_var - 1e-9
        count += 1
print(
    f"profile bound on {count:,} graphs, 7 <= n <= 30: always holds, below the star except on the star"
)
profile bound on 7,534 graphs, 7 <= n <= 30: always holds, below the star except on the star

Last, a consistency check by local search: simulated annealing over the graphs without isolated nodes, maximizing the variance by edge flips, for \(8 \le n \le 71\), with six restarts of 4,000 flips each, from the star, from two hubs sharing the leaves, and from four samples of \(G(n, p)\). No graph above the star may appear. The restarts run in parallel, so the random streams, and the restarts from \(G(n, p)\) that reach the star, vary from one run to the next; with this budget they reach it only for the smaller \(n\).

[9]:
@njit
def anneal(adj, iters):
    # Best variance seen along the annealing; adj is modified in place.
    n = adj.shape[0]
    deg = degrees(adj)
    cur = best = general.monochrome_variance(adj)
    for it in range(iters):
        temp = 0.5 * 0.01 ** (it / max(1, iters - 1))  # from 0.5 down to 0.005
        u, v = np.random.randint(n), np.random.randint(n)
        if u == v:
            continue
        step = -1 if adj[u, v] else 1
        if min(deg[u], deg[v]) + step == 0:
            continue  # never isolate a node
        adj[u, v] = adj[v, u] = not adj[u, v]
        deg[u] += step
        deg[v] += step
        new = general.monochrome_variance(adj)
        if new >= cur or np.random.random() < np.exp((new - cur) / temp):
            cur = new
            best = max(best, cur)
        else:
            adj[u, v] = adj[v, u] = not adj[u, v]
            deg[u] -= step
            deg[v] -= step
    return best


@njit
def restart(n, r):
    adj = np.zeros((n, n), dtype=np.bool_)
    if r == 0:  # the star
        adj[0, 1:] = True
        adj[1:, 0] = True
    elif r == 1:  # two hubs sharing the leaves
        adj[:2, 2:] = True
        adj[2:, :2] = True
    else:  # G(n, p), p uniform in [0.05, 0.5], isolated nodes linked to their successor
        p = 0.05 + 0.45 * np.random.random()
        for u in range(n):
            for v in range(u + 1, n):
                if np.random.random() < p:
                    adj[u, v] = adj[v, u] = True
        for u in range(n):
            if not adj[u].any():
                adj[u, (u + 1) % n] = adj[(u + 1) % n, u] = True
    return adj


@njit(parallel=True)
def search(ns, restarts, iters):
    best = np.zeros((len(ns), restarts))
    for task in prange(len(ns) * restarts):
        i, r = task // restarts, task % restarts
        best[i, r] = anneal(restart(ns[i], r), iters)
    return best


t0 = time.perf_counter()
ns = np.arange(8, 72)
best = search(ns, 6, 4000)
star_vars = np.array([float(star.variance(n)) for n in ns])
above = ns[best.max(axis=1) > star_vars + 1e-9]
reached = ns[best[:, 2:].max(axis=1) > star_vars - 1e-9]
print(
    f"annealing, 8 <= n <= 71 ({time.perf_counter() - t0:.0f} s): {len(above)} n with a graph above the star; "
    f"the restarts from G(n, p) reach the star for {len(reached)} values of n, the largest {reached.max() if len(reached) else '-'}"
)
assert len(above) == 0
annealing, 8 <= n <= 71 (20 s): 0 n with a graph above the star; the restarts from G(n, p) reach the star for 17 values of n, the largest 24

Path and cycle: generating functions and exact laws#

On the path, the report encodes the labelings by their peaks in an exponential generating function. The monochrome series \(P(z, v)\) solves the Riccati equation \(\partial_z P = v + 2P + P^2\); with \(k\) colors the series are rational in \(P\), split by whether the two ends share their color; the cycle series \(Y\) follows by opening the cycle at its smallest label. tinto.theory.path_cycle computes these series in exact integers: the coefficient of order \(n\) counts the (labeling, coloring) pairs by their number of peaks. Coefficient by coefficient, they must equal the enumeration.

[10]:
def strip(hist):
    out = [int(x) for x in hist]
    while out and out[-1] == 0:
        out.pop()
    return out


for k in (1, 2, 3):
    nmax = {1: 8, 2: 7, 3: 6}[k]
    total, same, dist = path_cycle.path_counts(nmax, k)
    cyc = path_cycle.cycle_counts(nmax, k)
    for n in range(1, nmax + 1):
        assert total[n] == strip(exact.peaks_distribution(line(n), k))
        if n >= 2:
            hs, hd = exact.peaks_distribution(line(n), k, split=(0, n - 1))
            assert (same[n], dist[n]) == (strip(hs), strip(hd))
        if (
            n >= 3
        ):  # the series fixes the smallest label on node 0: n times fewer labelings
            assert [n * c for c in cyc[n]] == strip(
                exact.peaks_distribution(ring(n), k)
            )
print(
    "path series (all, same ends, distinct ends) and cycle series = enumeration, n <= 8 monochrome, 7 for k = 2, 6 for k = 3"
)
print(
    "monochrome path on 5 nodes, labelings by number of peaks:",
    path_cycle.path_counts(5)[0][5],
)
path series (all, same ends, distinct ends) and cycle series = enumeration, n <= 8 monochrome, 7 for k = 2, 6 for k = 3
monochrome path on 5 nodes, labelings by number of peaks: [0, 16, 88, 16]

The report also gives the closed forms \(P(z, v) = \frac{v \tan(zr)}{r - \tan(zr)}\) and \(Y(z, v) = -\log\left(\cos(zr) - \frac{\sin(zr)}{r}\right)\), with \(r = \sqrt{v - 1}\). Against the series truncated at order 24:

[11]:
p24, y24 = path_cycle.path_counts(24)[0], path_cycle.cycle_counts(24)


def evaluate(series, z, v):
    return sum(
        sum(c * v**j for j, c in enumerate(series[m])) * z**m / factorial(m)
        for m in range(len(series))
    )


worst = max(
    max(
        abs(path_cycle.path_series(z, v) - evaluate(p24, z, v))
        / abs(evaluate(p24, z, v)),
        abs(path_cycle.cycle_series(z, v) - evaluate(y24, z, v))
        / abs(evaluate(y24, z, v)),
    )
    for v in (0.5, 1.5, 2.0, 3.0)
    for z in (0.05, 0.1, 0.2)
)
print(f"closed forms against the series: largest relative gap {worst:.1e}")
assert worst < 1e-10
closed forms against the series: largest relative gap 1.7e-13

Erdős-Rényi graphs: exact moments#

On \(G(n, p)\), \(\mathbb E S\) and \(\mathbb E S(S-1)\) have closed forms, rational in \(p\) (mean, second factorial moment). Averaging the exact moments of every graph on \(n \le 5\) nodes, weighted by \(p^m (1-p)^{\binom n2 - m}\), must give the same fractions. The variance also has an integral form, the one used for the figures; it must agree numerically.

[12]:
worst = 0.0
for n in (3, 4, 5):
    pairs = n * (n - 1) // 2
    graphs = list(exact.all_graphs(n))
    for k in (1, 2, 3):
        per_graph = [
            (len(g.ind) // 2, *exact.factorial_moments(exact.peaks_distribution(g, k)))
            for g in graphs
        ]
        for p in (Fraction(1, 4), Fraction(1, 2), Fraction(3, 4)):
            es = sum(p**m * (1 - p) ** (pairs - m) * a for m, a, _ in per_graph)
            ess = sum(p**m * (1 - p) ** (pairs - m) * b for m, _, b in per_graph)
            assert erdos_renyi.factorial_moments(n, p, k) == (es, ess), (n, k, p)
            worst = max(
                worst,
                abs(erdos_renyi.variance(n, float(p), k) - float(ess + es - es * es)),
            )
print(
    "G(n, p): mean and second factorial moment = enumeration, n <= 5, k <= 3, p in {1/4, 1/2, 3/4}"
)
print(f"integral form of the variance: largest gap {worst:.1e}")
print(
    "for instance G(5, 1/2), k = 2: (E S, E S(S-1)) =",
    tuple(map(str, erdos_renyi.factorial_moments(5, Fraction(1, 2), 2))),
)
assert worst < 1e-8
G(n, p): mean and second factorial moment = enumeration, n <= 5, k <= 3, p in {1/4, 1/2, 3/4}
integral form of the variance: largest gap 8.9e-15
for instance G(5, 1/2), k = 2: (E S, E S(S-1)) = ('781/256', '7175/1024')

Erdős-Rényi graphs: limit laws#

At fixed \(p\), \(S\) converges in law, without normalization: monochrome, to \(S_\infty = \sum_{i \ge 0} B_i\) with independent \(B_i \sim \mathrm{Bernoulli}((1-p)^i)\), and with \(k\) colors to the \(k\)-fold convolution (erdos_renyi.limit_law). In the sparse regime \(p \to 0\), the mean is close to \(k/p\), the variance to \(k/(2p)\), and the law becomes normal.

[13]:
n, p, k = 300, 0.3, 2
s = n - oracle.sample_erdos_renyi(n, p, k, TRIALS)
emp = np.bincount(np.minimum(s, 60), minlength=61) / len(s)
limit = erdos_renyi.limit_law(p, k, smax=60)
tv = 0.5 * np.abs(emp - limit).sum()
print(
    f"fixed p = {p}, k = {k}, n = {n}: total variation to the limit law {tv:.4f}, mean {s.mean():.3f} (limit {k / p * (1 - (1 - p) ** 1000):.3f})"
)
assert tv < 0.02

n, p, k = 2000, 0.04, 2
s = n - oracle.sample_erdos_renyi(n, p, k, 10_000)
skew = ((s - s.mean()) ** 3).mean() / s.std() ** 3
print(
    f"sparse p = {p}, k = {k}, n = {n}: mean {s.mean():.2f} (k/p = {k / p:.0f}), variance {s.var():.2f} (k/2p = {k / (2 * p):.0f}), skewness {skew:.3f}"
)
assert (
    abs(s.mean() - k / p) < 0.03 * k / p
    and abs(s.var() - k / (2 * p)) < 0.15 * k / (2 * p)
    and abs(skew) < 0.15
)
fixed p = 0.3, k = 2, n = 300: total variation to the limit law 0.0044, mean 6.671 (limit 6.667)
sparse p = 0.04, k = 2, n = 2000: mean 49.97 (k/p = 50), variance 24.77 (k/2p = 25), skewness 0.086

The same statements on the exact law. Monochrome, \(S_n = \sum_{i < n} B_i\) with independent \(B_i \sim \mathrm{Bernoulli}((1-p)^i)\), at every \(n\): the node with \(i\) larger labels is a peak iff it has no edge to them. At fixed \(p\), the law at \(n = 200\), by convolution, is already the limit law; its mean is \(1/p\). With \(p = n^{-1/2}\), the cumulants add up over the \(B_i\): \(p\, \mathbb E S \to 1\), \(2p\, \mathrm{Var}\, S \to 1\), and the skewness decreases to zero.

[14]:
for p in (0.1, 0.3):
    law = np.array([1.0])
    for q in (1 - p) ** np.arange(200):
        law = np.convolve(law, [1 - q, q])
    limit = erdos_renyi.limit_law(p, smax=len(law) - 1)
    tv = 0.5 * np.abs(law - limit).sum()
    limit_mean = (np.arange(len(limit)) * limit).sum()
    print(
        f"p = {p}: total variation between n = 200 and the limit {tv:.1e}, limit mean {limit_mean:.10f} (1/p = {1 / p:.10f})"
    )
    assert tv < 1e-6 and abs(limit_mean - 1 / p) < 1e-9

skews = []
for n in (400, 1600, 6400, 25600):
    p = n**-0.5
    q = (1 - p) ** np.arange(n)
    var = (q * (1 - q)).sum()
    skews.append((q * (1 - q) * (1 - 2 * q)).sum() / var**1.5)
    print(
        f"n = {n:5d}, p = n^(-1/2): p E S = {p * q.sum():.4f}, 2p Var S = {2 * p * var:.4f}, skewness {skews[-1]:.4f}"
    )
assert all(a > b for a, b in zip(skews, skews[1:])) and skews[-1] < 0.05
assert abs(2 * p * var - 1) < 0.02
p = 0.1: total variation between n = 200 and the limit 1.3e-09, limit mean 10.0000000000 (1/p = 10.0000000000)
p = 0.3: total variation between n = 200 and the limit 1.0e-31, limit mean 3.3333333333 (1/p = 3.3333333333)
n =   400, p = n^(-1/2): p E S = 1.0000, 2p Var S = 0.9744, skewness 0.1070
n =  1600, p = n^(-1/2): p E S = 1.0000, 2p Var S = 0.9873, skewness 0.0750
n =  6400, p = n^(-1/2): p E S = 1.0000, 2p Var S = 0.9937, skewness 0.0529
n = 25600, p = n^(-1/2): p E S = 1.0000, 2p Var S = 0.9969, skewness 0.0373

Bipartite graphs#

Monochrome, given the interleaving of the two sides in decreasing label order, a node is a peak iff it has no edge to the larger nodes of the other side, independently of the others: the conditional generating function is a product. bipartite.law averages it over the interleavings, exactly for a rational \(p\). Against the empirical law of the oracle, and its mean against the closed form:

[15]:
n1, n2, p = 5, 4, Fraction(7, 20)
law = bipartite.law(n1, n2, p)
s = n1 + n2 - oracle.sample_bipartite(n1, n2, float(p), 1, TRIALS)
emp = np.bincount(s, minlength=n1 + n2 + 1) / len(s)
tv = 0.5 * sum(abs(e - float(x)) for e, x in zip(emp, law))
mean_t = n1 + n2 - sum(j * x for j, x in enumerate(law))
print(
    f"G({n1}, {n2}, {p}): total variation {tv:.4f}; E T from the law {mean_t} = {float(mean_t):.10f}, closed form {bipartite.mean(n1, n2, float(p)):.10f}"
)
assert tv < 0.01 and abs(float(mean_t) - bipartite.mean(n1, n2, float(p))) < 1e-12
G(5, 4, 7/20): total variation 0.0038; E T from the law 7541219/1600000 = 4.7132618750, closed form 4.7132618750

With a fraction \(\lambda\) of the nodes on the first side, \(\mathbb E S \to \frac{\lambda}{(1-\lambda)p} + \frac{1-\lambda}{\lambda p}\):

[16]:
for n1, n2, p in ((300, 300, 0.3), (200, 400, 0.3)):
    lam = n1 / (n1 + n2)
    s = n1 + n2 - oracle.sample_bipartite(n1, n2, p, 1, 20_000)
    finite = n1 + n2 - bipartite.mean(n1, n2, p)
    limit = bipartite.limit_mean(lam, p)
    print(
        f"lambda = {lam:.2f}: oracle {s.mean():.3f}, finite-n formula {finite:.3f}, limit {limit:.3f}"
    )
    assert abs(s.mean() - limit) < 0.05 * limit and abs(finite - limit) < 0.02 * limit
lambda = 0.50: oracle 6.650, finite-n formula 6.645, limit 6.667
lambda = 0.33: oracle 8.328, finite-n formula 8.296, limit 8.333

Path and cycle with k colors: central limit theorem#

With \(k\) colors the variance stays linear in \(n\), and \(T\) is asymptotically normal: the skewness shrinks as \(n\) grows. Here \(k = 3\), against the variance formula:

[17]:
k = 3
for cycle in (False, True):
    graph = ring if cycle else line
    skews = []
    for n in (40, 400):
        t = oracle.sample_graph(graph(n), k, TRIALS)
        skews.append(((t - t.mean()) ** 3).mean() / t.std() ** 3)
        print(
            f"{'cycle' if cycle else 'path ':5s} n = {n:3d}: variance {t.var():8.3f} (formula {path_cycle.variance(n, k, cycle):8.3f}), skewness {skews[-1]:+.3f}"
        )
    assert abs(skews[1]) < 0.12 and abs(skews[1]) < abs(skews[0]) + 0.02
path  n =  40: variance    6.216 (formula    6.187), skewness +0.052
path  n = 400: variance   63.173 (formula   62.681), skewness +0.002
cycle n =  40: variance    6.290 (formula    6.277), skewness +0.041
cycle n = 400: variance   62.836 (formula   62.771), skewness +0.001

Fixed initial configuration#

From a fixed coloring \(\gamma\), only the labeling is random. Let \(G_\gamma\) keep the edges whose ends share their color (the conflict graph). The report shows (fixed initial configuration) that \(T(G, \gamma) = n - S(G_\gamma)\), that \(\mathbb E\, T = \sum_v d_v(\gamma) / (d_v(\gamma) + 1)\) with \(d_v(\gamma)\) the number of same-colored neighbors, that \(S(G_\gamma) \ge S(G)\) for every labeling (the monochrome start is the worst), and that \(S\) ranges exactly over \([\kappa(G_\gamma), \alpha(G_\gamma)]\), the number of connected components and the independence number, both ends being attained. Three samples of \(G(12, 0.4)\) with a random 3-coloring; the dynamics runs with the daemon of the report.

[18]:
def independence_number(n, edges):
    neighbors = [0] * n
    for u, v in edges:
        neighbors[u] |= 1 << v
        neighbors[v] |= 1 << u
    best, best_set = 0, 0
    for subset in range(1 << n):
        size = bin(subset).count("1")
        if size > best and all(
            not (neighbors[v] & subset) for v in range(n) if subset >> v & 1
        ):
            best, best_set = size, subset
    return best, best_set


def decreasing_bfs_labels(graph):
    """Labels decreasing along a BFS from one root per component: one peak per component."""
    order, seen = [], set()
    for root in range(graph.n):
        if root in seen:
            continue
        seen.add(root)
        queue = [root]
        while queue:
            u = queue.pop(0)
            order.append(u)
            for w in graph.neighbors(u).tolist():
                if w not in seen:
                    seen.add(w)
                    queue.append(w)
    labels = np.empty(graph.n)
    labels[order] = np.arange(graph.n, 0, -1)
    return labels


n = 12
mono = np.zeros(n, dtype=np.int64)
for trial in range(3):
    g = gnp(n, 0.4)
    gamma = np.random.randint(0, 3, n)
    q = max(3, g.max_degree + 1)

    def moves_from_gamma():
        c = Config(g, q)
        c.colors[:] = gamma
        c.check_all()
        return runners.simple(c, UniformEnabled(), solver)[0]

    t_dyn = np.array([moves_from_gamma() for _ in range(3000)], dtype=float)
    t_red = np.array(
        [n - oracle.count_peaks(g, gamma, np.random.random(n)) for _ in range(20_000)],
        dtype=float,
    )
    formula = float(general.fixed_coloring_mean(g, gamma))
    z_dyn = abs(t_dyn.mean() - formula) / (t_dyn.std() / np.sqrt(len(t_dyn)))
    z_red = abs(t_red.mean() - formula) / (t_red.std() / np.sqrt(len(t_red)))
    assert z_dyn < 5 and z_red < 5

    labelings = [np.random.random(n) for _ in range(5000)]
    violations = sum(
        oracle.count_peaks(g, gamma, lab) < oracle.count_peaks(g, mono, lab)
        for lab in labelings
    )
    assert violations == 0

    conflict = [
        (u, v)
        for u in range(n)
        for v in g.neighbors(u).tolist()
        if u < v and gamma[u] == gamma[v]
    ]
    gc = edges_to_graph(n, np.array(conflict, dtype=np.int64).reshape(-1, 2))
    kappa = connected_components(csr_array(gc.to_adja()), directed=False)[0]
    alpha, mis = independence_number(n, conflict)
    mis_labels = np.array([n + v if mis >> v & 1 else v for v in range(n)], dtype=float)
    s_bfs = oracle.count_peaks(gc, mono, decreasing_bfs_labels(gc))
    s_mis = oracle.count_peaks(gc, mono, mis_labels)
    s_random = [oracle.count_peaks(gc, mono, lab) for lab in labelings]
    assert (
        s_bfs == kappa
        and s_mis == alpha
        and kappa <= min(s_random)
        and max(s_random) <= alpha
    )
    print(
        f"trial {trial}: E T formula {formula:.3f}, dynamics {t_dyn.mean():.3f} ({z_dyn:.1f} se), reduction {t_red.mean():.3f} ({z_red:.1f} se); "
        f"S(G_gamma) >= S(G) on 5000 labelings; kappa = {kappa}, alpha = {alpha}, both attained, random range [{min(s_random)}, {max(s_random)}]"
    )
trial 0: E T formula 3.250, dynamics 3.277 (1.8 se), reduction 3.260 (1.8 se); S(G_gamma) >= S(G) on 5000 labelings; kappa = 8, alpha = 10, both attained, random range [8, 10]
trial 1: E T formula 5.767, dynamics 5.750 (2.1 se), reduction 5.767 (0.2 se); S(G_gamma) >= S(G) on 5000 labelings; kappa = 6, alpha = 7, both attained, random range [6, 7]
trial 2: E T formula 7.467, dynamics 7.471 (0.2 se), reduction 7.467 (0.0 se); S(G_gamma) >= S(G) on 5000 labelings; kappa = 3, alpha = 6, both attained, random range [3, 6]

Uniform labeled tree with k colors#

The degree of a node is \(1 + \mathrm{Binomial}(n - 2, 1/n)\), which gives the mean, as a finite sum or as an integral; the variance needs the joint degree laws of pairs of nodes, adjacent, at distance two, or further apart; the exact law follows from percolating the monochrome edges and Lagrange inversion. A uniform labeled tree is already uniformly labeled, so the enumeration can fix the labeling to the node indices and run over the trees and the colorings only.

The mean, against its integral form \(n - nk\int_{1-1/k}^1 t \left(\frac{n - 1 + t}{n}\right)^{n-2} dt\) and the oracle, and the limit coefficient \(1 - e^{-1/k}\):

[19]:
for n, k in ((8, 2), (12, 3), (30, 2), (30, 1)):
    integral = (
        n
        - n
        * k
        * integrate.quad(
            lambda t: t * ((n - 1 + t) / n) ** (n - 2), 1 - 1 / k, 1, epsabs=1e-13
        )[0]
    )
    t = oracle.sample_cayley(n, k, TRIALS)
    z = abs(t.mean() - cayley.mean(n, k)) / (t.std() / np.sqrt(len(t)))
    print(
        f"n = {n:2d}, k = {k}: sum {cayley.mean(n, k):.6f}, integral {integral:.6f}, oracle {t.mean():.4f} ({z:.1f} se)"
    )
    assert abs(integral - cayley.mean(n, k)) < 1e-9 and z < 5
for k in (1, 2, 3, 5):
    coefficient = 1 - exp(-1) * sum(
        general.rho(j + 1, k) / factorial(j) for j in range(60)
    )
    assert abs(coefficient - (1 - exp(-1 / k))) < 1e-12
print("limit of E T / n: 1 - exp(-1/k), checked for k = 1, 2, 3, 5")
n =  8, k = 2: sum 2.907994, integral 2.907994, oracle 2.9101 (0.5 se)
n = 12, k = 3: sum 3.197577, integral 3.197577, oracle 3.1956 (0.4 se)
n = 30, k = 2: sum 11.573480, integral 11.573480, oracle 11.5815 (0.9 se)
n = 30, k = 1: sum 18.776022, integral 18.776022, oracle 18.7724 (0.5 se)
limit of E T / n: 1 - exp(-1/k), checked for k = 1, 2, 3, 5

The pair-degree laws, exactly against the enumeration of all labeled trees (nodes 0 and 1 stand for any pair):

[20]:
for n in (5, 6, 7):
    joint, adjacent, distance_two, count = {}, {}, {}, 0
    for t in exact.all_trees(n):
        count += 1
        nb0, nb1 = set(t.neighbors(0).tolist()), set(t.neighbors(1).tolist())
        key = (len(nb0), len(nb1))
        joint[key] = joint.get(key, 0) + 1
        if 1 in nb0:
            adjacent[key] = adjacent.get(key, 0) + 1
        elif nb0 & nb1:
            distance_two[key] = distance_two.get(key, 0) + 1
    n_adj, n_two = sum(adjacent.values()), sum(distance_two.values())
    assert count == n ** (n - 2) and (
        Fraction(n_adj, count),
        Fraction(n_two, count),
    ) == cayley.pair_distances(n)
    assert all(
        cayley.pair_degrees(n, i, j) == Fraction(c, count)
        for (i, j), c in joint.items()
    )
    assert all(
        cayley.adjacent_pair_degrees(n, i - 1, j - 1) == Fraction(c, n_adj)
        for (i, j), c in adjacent.items()
    )
    assert all(
        cayley.distance_two_pair_degrees(n, i - 1, j - 1) == Fraction(c, n_two)
        for (i, j), c in distance_two.items()
    )
    print(
        f"n = {n}: {count} trees, P(adjacent) = {n_adj}/{count}, P(distance two) = {n_two}/{count}, the three pair laws exact"
    )
n = 5: 125 trees, P(adjacent) = 50/125, P(distance two) = 45/125, the three pair laws exact
n = 6: 1296 trees, P(adjacent) = 432/1296, P(distance two) = 432/1296, the three pair laws exact
n = 7: 16807 trees, P(adjacent) = 4802/16807, P(distance two) = 5145/16807, the three pair laws exact

The variance, against the enumeration over all trees and colorings for \(n \le 6\), and against the oracle for larger \(n\); then the asymptotic slope \(\mathrm{Var}\, T_n / n \to e^{-1/k} - (1 + k^{-2}) e^{-2/k}\), against the integrals of the \(1/n\) expansion and against finite differences:

[21]:
TREES = {n: list(exact.all_trees(n)) for n in (5, 6, 7)}


def tree_histogram(n, k):
    return sum(exact.peaks_distribution(t, k, labels=range(n)) for t in TREES[n])


for n, k in ((5, 1), (5, 2), (5, 3), (6, 1), (6, 2), (6, 3)):
    es, ess = exact.factorial_moments(tree_histogram(n, k))
    gap = abs(cayley.variance(n, k) - float(ess + es - es * es))
    print(
        f"n = {n}, k = {k}: variance {cayley.variance(n, k):.8f}, enumeration {float(ess + es - es * es):.8f}"
    )
    assert gap < 1e-6
for n, k in ((30, 2), (30, 3), (100, 2)):
    t = oracle.sample_cayley(n, k, TRIALS)
    se = np.sqrt((np.mean((t - t.mean()) ** 4) - t.var() ** 2) / len(t))
    print(
        f"n = {n}, k = {k}: oracle variance {t.var():.3f}, formula {cayley.variance(n, k):.3f} ({abs(t.var() - cayley.variance(n, k)) / se:.1f} se)"
    )
    assert abs(t.var() - cayley.variance(n, k)) < 5 * se
n = 5, k = 1: variance 0.44569600, enumeration 0.44569600
n = 5, k = 2: variance 0.71081975, enumeration 0.71081975
n = 5, k = 3: variance 0.68178333, enumeration 0.68178333
n = 6, k = 1: variance 0.54768173, enumeration 0.54768173
n = 6, k = 2: variance 0.85915429, enumeration 0.85915429
n = 6, k = 3: variance 0.82969179, enumeration 0.82969179
n = 30, k = 2: oracle variance 4.372, formula 4.385 (0.5 se)
n = 30, k = 3: oracle variance 4.306, formula 4.342 (1.5 se)
n = 100, k = 2: oracle variance 14.541, formula 14.654 (1.4 se)
[22]:
def bracket(f, k):
    lo = 1 - 1 / k
    return (
        k
        * k
        * integrate.dblquad(
            lambda t, s: f(s, t), lo, 1, lo, 1, epsabs=1e-12, epsrel=1e-12
        )[0]
    )


def bracket_min(f, k):
    lo, opts = 1 - 1 / k, dict(epsabs=1e-12, epsrel=1e-12)
    lower = integrate.dblquad(
        lambda s, t: s * f(s, t), lo, 1, lambda t: lo, lambda t: t, **opts
    )[0]
    upper = integrate.dblquad(
        lambda s, t: t * f(s, t), lo, 1, lambda t: t, lambda t: 1, **opts
    )[0]
    return k * k * (lower + upper)


for k in (1, 2, 3, 5):
    mu = k * integrate.quad(lambda s: s * exp(s - 1), 1 - 1 / k, 1, epsabs=1e-13)[0]
    mu1 = (
        -k
        * integrate.quad(
            lambda s: s * exp(s - 1) * ((s - 1) ** 2 / 2 + 2 * (s - 1)),
            1 - 1 / k,
            1,
            epsabs=1e-13,
        )[0]
    )
    nu1 = (
        -bracket(
            lambda s, t: (
                s * t * exp(s + t - 2) * ((s + t - 2) ** 2 / 2 + 2 * (s + t - 2))
            ),
            k,
        )
        + bracket(lambda s, t: (s + t) * exp(s + t - 2) * ((k - 1) / k - s * t), k)
        + bracket_min(lambda s, t: (s + t + 1) * exp(s + t - 2), k) / k
        + bracket(
            lambda s, t: (
                (s + t + 1) * exp(s + t - 2) * ((k - 1) / k * (s + t - 1) - s * t)
            ),
            k,
        )
    )
    from_integrals = nu1 - mu**2 + mu - 2 * mu * mu1
    finite = (cayley.variance(400, k) - cayley.variance(200, k)) / 200
    print(
        f"k = {k}: slope {cayley.slope(k):.9f}, 1/n-expansion integrals {from_integrals:.9f}, finite differences (200 to 400) {finite:.5f}"
    )
    assert (
        abs(from_integrals - cayley.slope(k)) < 1e-8
        and abs(finite - cayley.slope(k)) < 2e-3
    )
k = 1: slope 0.097208875, 1/n-expansion integrals 0.097208875, finite differences (200 to 400) 0.09721
k = 2: slope 0.146681358, 1/n-expansion integrals 0.146681358, finite differences (200 to 400) 0.14668
k = 3: slope 0.146067845, 1/n-expansion integrals 0.146067845, finite differences (200 to 400) 0.14607
k = 5: slope 0.121597905, 1/n-expansion integrals 0.121597905, finite differences (200 to 400) 0.12160

The exact law, through its generating function \(\mathbb E\, v^{S_n}\), against the enumeration:

[23]:
for n, k in ((5, 2), (5, 3), (6, 2), (6, 3), (7, 2), (7, 3)):
    hist = tree_histogram(n, k).astype(float)
    hist /= hist.sum()
    worst = max(
        abs(cayley.pgf(n, k, v) - (hist * v ** np.arange(n + 1)).sum())
        for v in (0.3, 0.8, 1.0, 1.5)
    )
    print(f"n = {n}, k = {k}: largest gap over v in {{0.3, 0.8, 1, 1.5}}: {worst:.1e}")
    assert worst < 1e-9
n = 5, k = 2: largest gap over v in {0.3, 0.8, 1, 1.5}: 8.9e-16
n = 5, k = 3: largest gap over v in {0.3, 0.8, 1, 1.5}: 3.5e-18
n = 6, k = 2: largest gap over v in {0.3, 0.8, 1, 1.5}: 1.1e-16
n = 6, k = 3: largest gap over v in {0.3, 0.8, 1, 1.5}: 1.1e-16
n = 7, k = 2: largest gap over v in {0.3, 0.8, 1, 1.5}: 1.8e-15
n = 7, k = 3: largest gap over v in {0.3, 0.8, 1, 1.5}: 8.7e-19

General rooted trees: the catalytic equation#

The report extends the tree analysis to rooted labeled plane trees with a weight \(\phi_c\) on each node with \(c\) children, \(\Phi(z) = \sum_c \phi_c z^c\); the Cayley weights \(\phi_c = 1/c!\) give the uniform labeled tree. With \(z\) marking the nodes, \(v\) the peaks (monochrome) and \(x\) the holes (the slots where a further child could be inserted), the generating function \(A(z, v, x)\) satisfies

\[\partial_z A = (v - 1)\, \Phi(x) + \Phi(A + x) + (\partial_x A)\, \Phi(A + x),\]

and the peaks are counted by \(A(z, v, 0)\). Under a uniform \(k\)-coloring, the trees whose root has a prescribed color have a generating function \(B_k\) that satisfies \(B_k = A(z, v, (k - 1) B_k)\).

The equation fixes the coefficients one by one: \(n A_n\) is the coefficient of \(z^{n-1}\) in the right-hand side, which involves only \(A_1, \dots, A_{n-1}\). sympy computes them exactly, in a polynomial ring over the rationals, up to \(z^6\).

[24]:
Q, z, v, x = polynomial_ring("z, v, x", sp.QQ)
ORDER = 6


def truncate(p, order=ORDER):
    # Drop the terms of degree above order in z.
    return Q({m: c for m, c in p.items() if m[0] <= order})


def substitute_x(p, q, order=ORDER):
    # p(z, v, q), truncated.
    out, power = Q.zero, Q.one
    for d in range(p.degree(x) + 1):
        part = Q({(m[0], m[1], 0): c for m, c in p.items() if m[2] == d})
        out += truncate(part * power, order)
        power = truncate(power * q, order)
    return out


def solve_catalytic(phi):
    # A(z, v, x) up to z^ORDER, for the weights phi = {c: phi_c}.
    Phi = sum((c * x**d for d, c in phi.items()), Q.zero)
    A = Q.zero
    for n in range(1, ORDER + 1):
        rhs = (v - 1) * Phi + truncate(
            substitute_x(Phi, A + x, n - 1) * (1 + A.diff(x)), n - 1
        )
        A += Q({(n, *m[1:]): c / n for m, c in rhs.items() if m[0] == n - 1})
    return A


def counts(p, n):
    # n! [z^n] p, as {number of peaks: count}.
    return {m[1]: c * factorial(n) for m, c in p.items() if m[0] == n}

With the Cayley weights (cut at \(c \le 6\), which leaves \(A(z, v, 0)\) unchanged up to \(z^6\)), \(A(z, v, 0)\) must be the series \(F(z, v) = C(z e^{(v-1)z}) + (v - 1) z\) of the uniform tree, with \(C(z) = \sum_{m \ge 1} m^{m-1} z^m / m!\):

[25]:
t0 = time.perf_counter()
A = solve_catalytic({c: sp.QQ(1, factorial(c)) for c in range(ORDER + 1)})
inner = sum(
    (sp.QQ(1, factorial(i)) * (v - 1) ** i * z ** (i + 1) for i in range(ORDER)), Q.zero
)  # z exp((v - 1) z)
F = (v - 1) * z + sum(
    (
        sp.QQ(m ** (m - 1), factorial(m)) * truncate(inner**m)
        for m in range(1, ORDER + 1)
    ),
    Q.zero,
)
assert substitute_x(A, Q.zero) == F
print(
    f"Cayley weights: A(z, v, 0) = F(z, v) up to z^6 ({time.perf_counter() - t0:.1f} s)"
)
Cayley weights: A(z, v, 0) = F(z, v) up to z^6 (1.4 s)

For other weights, \(n!\,[z^n] A(z, v, 0)\) counts the rooted labeled trees on \(n\) nodes by their peaks, each weighted by \(\prod_u c_u!\, \phi_{c_u}\) over its nodes, \(c_u\) being the number of children of \(u\) (the \(c_u!\) orders of the children make the plane trees). The enumeration roots each labeled tree of exact.all_trees at each of its nodes, the labels being the node indices; with \(k\) colors it runs over the \(k^n\) colorings, which counts the trees of every root color, that is \(k B_k\). The fixed point \(B_k = A(z, v, (k - 1) B_k)\) is reached by iteration, each step fixing one more coefficient. Three weight systems, \(2 \le n \le 5\), \(k \le 3\):

[26]:
def rooted_trees(n):
    # Rooted labeled trees on n >= 2 nodes, as (tree, number of children of each node).
    for t in exact.all_trees(n):
        for root in range(n):
            children, parent, order = [0] * n, [-1] * n, [root]
            for u in order:
                for w in t.neighbors(u).tolist():
                    if w != parent[u]:
                        parent[w] = u
                        children[u] += 1
                        order.append(w)
            yield t, children


def enumeration(phi, n, k):
    out = {}
    for t, children in rooted_trees(n):
        weight = prod(factorial(c) * phi.get(c, 0) for c in children)
        if weight:
            for j, h in enumerate(exact.peaks_distribution(t, k, labels=range(n))):
                if h:
                    out[j] = out.get(j, 0) + weight * int(h)
    return out


t0 = time.perf_counter()
for phi in ({0: 1, 1: 1, 2: 1}, {0: 1, 1: 1, 2: 1, 3: 1}, {0: 2, 1: 3, 2: 1}):
    A = solve_catalytic({c: sp.QQ(w) for c, w in phi.items()})
    for k in (1, 2, 3):
        B = Q.zero
        for _ in range(ORDER):
            B = substitute_x(A, (k - 1) * B)
        for n in range(2, 6):
            assert counts(k * B, n) == enumeration(phi, n, k), (phi, k, n)
print(
    f"three weight systems: A(z, v, 0) and k B_k = enumeration, 2 <= n <= 5, k <= 3 ({time.perf_counter() - t0:.1f} s)"
)
three weight systems: A(z, v, 0) and k B_k = enumeration, 2 <= n <= 5, k <= 3 (0.3 s)

The report also notes that, unlike the Cayley case, peaks and leaves are not equidistributed in general: under the full binary law (\(\phi_0 = \phi_2 = 1\)), the tree on three nodes has peak generating function \((2v + v^2)/3\), while its two leaves are always leaves.

[27]:
three = counts(substitute_x(solve_catalytic({0: sp.QQ(1), 2: sp.QQ(1)}), Q.zero), 3)
law3 = {j: c / sum(three.values()) for j, c in three.items()}
print("full binary law, three nodes, P(S = j):", {j: str(c) for j, c in law3.items()})
assert law3 == {1: sp.QQ(2, 3), 2: sp.QQ(1, 3)}
full binary law, three nodes, P(S = j): {1: '2/3', 2: '1/3'}

Binary plane trees with a single peak#

The report observes, without a proof, that on the rooted full binary plane trees with \(2m + 1\) nodes, the labelings with exactly one peak number \((2m)!\,[z^{2m}] \cos(z)^{-4}\) (OEIS A395382), and checks it for \(m \le 10\).

A labeling of a tree has a single peak, its largest label, iff every other node has a larger neighbor, that is, iff each prefix of the nodes in decreasing label order is connected. In a tree, such an order starts at some node \(r\), and each later node comes after its neighbor towards \(r\): it is a linear extension of the tree rooted at \(r\). By the hook length formula for trees, there are \(n! / \prod_u h_u\) of them, \(h_u\) being the size of the subtree of \(u\). Summed over the roots and over the Catalan\((m)\) shapes, against the series for \(m \le 10\); and shape by shape against the enumeration of all labelings for \(m \le 4\):

[28]:
def shapes(m):
    # Full binary plane trees with m internal nodes, as nested pairs (None is a leaf).
    if m == 0:
        yield None
        return
    for i in range(m):
        for left in shapes(i):
            for right in shapes(m - 1 - i):
                yield left, right


def adjacency(shape):
    nbrs = []

    def build(s):
        u = len(nbrs)
        nbrs.append([])
        for child in s or ():
            w = build(child)
            nbrs[u].append(w)
            nbrs[w].append(u)
        return u

    build(shape)
    return nbrs


def single_peak_labelings(nbrs):
    n, total = len(nbrs), 0
    for root in range(n):
        parent, order = [-1] * n, [root]
        for u in order:
            for w in nbrs[u]:
                if w != parent[u]:
                    parent[w] = u
                    order.append(w)
        size = [1] * n
        for u in reversed(order[1:]):
            size[parent[u]] += size[u]
        total += factorial(n) // prod(size)
    return total


t0 = time.perf_counter()
y = sp.Symbol("y")
sec4 = sp.series(sp.cos(y) ** -4, y, 0, 21).removeO()
for m in range(1, 11):
    total = 0
    for s in shapes(m):
        nbrs = adjacency(s)
        count = single_peak_labelings(nbrs)
        if m <= 4:
            edges = np.array(
                [(u, w) for u in range(len(nbrs)) for w in nbrs[u] if u < w]
            )
            assert (
                count == exact.peaks_distribution(edges_to_graph(len(nbrs), edges))[1]
            )
        total += count
    assert total == sec4.coeff(y, 2 * m) * factorial(2 * m)
    print(f"m = {m:2d}: {total:,} labelings with a single peak")
print(
    f"= (2m)! [z^2m] cos(z)^-4 for m <= 10, = enumeration for m <= 4 ({time.perf_counter() - t0:.0f} s)"
)
m =  1: 4 labelings with a single peak
m =  2: 56 labelings with a single peak
m =  3: 1,504 labelings with a single peak
m =  4: 64,256 labelings with a single peak
m =  5: 3,963,904 labelings with a single peak
m =  6: 332,205,056 labelings with a single peak
m =  7: 36,246,728,704 labelings with a single peak
m =  8: 4,988,057,747,456 labelings with a single peak
m =  9: 844,642,265,595,904 labelings with a single peak
m = 10: 172,538,313,119,891,456 labelings with a single peak
= (2m)! [z^2m] cos(z)^-4 for m <= 10, = enumeration for m <= 4 (2 s)

Figures: mean and variance on five families#

The report gives the exact mean and variance of \(T\) on five families: the path, the cycle, the Erdős-Rényi graph \(G(n, p)\), the balanced bipartite graph \(G(n/2, n/2, p)\) and the uniform labeled tree, here with \(p = 0.1\) and \(k \in \{1, 2, 3, 5\}\) colors (\(k = 1\) is the monochrome start). Each point confronts the closed form with a Monte-Carlo estimate from the peak oracle. On the random families, a fresh graph is drawn for each sample, so the variance is taken over the graph, the coloring and the labeling together.

The standard error of a variance estimate is taken from the fourth central moment of the samples, \(\sqrt{(\hat\mu_4 - \hat\sigma^4) / N}\), which stays valid for laws with heavy tails.

[29]:
P = 0.1
NS = list(range(20, 201, 20))
KS = (1, 2, 3, 5)

FAMILIES = {
    "path": (
        lambda n, k: oracle.sample_graph(line(n), k, TRIALS),
        lambda n, k: path_cycle.mean(n, k),
        lambda n, k: path_cycle.variance(n, k),
    ),
    "cycle": (
        lambda n, k: oracle.sample_graph(ring(n), k, TRIALS),
        lambda n, k: path_cycle.mean(n, k, cycle=True),
        lambda n, k: path_cycle.variance(n, k, cycle=True),
    ),
    "G(n, 0.1)": (
        lambda n, k: oracle.sample_erdos_renyi(n, P, k, TRIALS),
        lambda n, k: erdos_renyi.mean(n, P, k),
        lambda n, k: erdos_renyi.variance(n, P, k),
    ),
    "G(n/2, n/2, 0.1)": (
        lambda n, k: oracle.sample_bipartite(n // 2, n - n // 2, P, k, TRIALS),
        lambda n, k: bipartite.mean(n // 2, n - n // 2, P, k),
        lambda n, k: bipartite.variance(n // 2, n - n // 2, P, k),
    ),
    "uniform tree": (
        lambda n, k: oracle.sample_cayley(n, k, TRIALS),
        lambda n, k: cayley.mean(n, k),
        lambda n, k: cayley.variance(n, k),
    ),
}


def point(sample, mean_f, var_f, n, k):
    t = sample(n, k)
    m, v = t.mean(), t.var()
    return {
        "mean": m,
        "se_mean": np.sqrt(v / len(t)),
        "mean_f": mean_f(n, k),
        "var": v,
        "se_var": np.sqrt((np.mean((t - m) ** 4) - v**2) / len(t)),
        "var_f": var_f(n, k),
    }


t0 = time.perf_counter()
results = {
    (family, k): [point(*funcs, n, k) for n in NS]
    for family, funcs in FAMILIES.items()
    for k in KS
}
points = sum(len(rs) for rs in results.values())
print(
    f"{points} points, {points * TRIALS:,} samples in {time.perf_counter() - t0:.0f} s"
)
200 points, 12,000,000 samples in 60 s

Every point agrees with its closed form within a few standard errors (the check fails beyond six):

[30]:
def largest(stat, se):
    return max(
        (abs(r[stat] - r[stat + "_f"]) / r[se], family, n, k)
        for (family, k), rs in results.items()
        for n, r in zip(NS, rs)
    )


dev_mean, dev_var = largest("mean", "se_mean"), largest("var", "se_var")
for label, (z, family, n, k) in (("mean", dev_mean), ("variance", dev_var)):
    print(
        f"largest deviation on the {label} over {points} points: {z:.2f} se ({family}, n = {n}, k = {k})"
    )
assert dev_mean[0] < 6 and dev_var[0] < 6
largest deviation on the mean over 200 points: 3.02 se (cycle, n = 40, k = 3)
largest deviation on the variance over 200 points: 2.98 se (path, n = 40, k = 1)
[31]:
fig, axes = plt.subplots(2, len(KS), figsize=(16, 7), sharex=True)
for j, k in enumerate(KS):
    for family in FAMILIES:
        rs = results[family, k]
        for i, (stat, se) in enumerate((("mean", "se_mean"), ("var", "se_var"))):
            (curve,) = axes[i, j].plot(NS, [r[stat + "_f"] for r in rs], lw=1)
            axes[i, j].errorbar(
                NS,
                [r[stat] for r in rs],
                yerr=[2 * r[se] for r in rs],
                fmt="o",
                ms=3,
                color=curve.get_color(),
                label=family,
            )
    axes[0, j].set_title("monochrome" if k == 1 else f"k = {k} colors")
    axes[1, j].set_xlabel("n")
axes[0, 0].set_ylabel("mean of T")
axes[1, 0].set_ylabel("variance of T")
axes[0, 0].legend(fontsize=8)
fig.suptitle(
    "Closed forms (lines) against the peak oracle (points, two standard errors)"
)
fig.tight_layout()
plt.show()
../../_images/papers_exact_stabilization_time_companion_60_0.png

Figure: the law of \(T\) on the path#

On the path, \(T\) is asymptotically normal. At \(n = 60\), monochrome, the empirical law from the oracle against the exact law from the generating function, and the normal density with the exact mean and variance (as in the figure of the report):

[32]:
n0 = 60
t = oracle.sample_graph(line(n0), 1, TRIALS)
values, counts = np.unique(t, return_counts=True)
exact_law = np.array([float(x) for x in path_cycle.law(n0)])[
    ::-1
]  # P(T = t) = P(S = n0 - t)
tv = 0.5 * np.abs(np.bincount(t, minlength=n0 + 1) / len(t) - exact_law).sum()
mu, sigma = path_cycle.mean(n0), np.sqrt(path_cycle.variance(n0))
xs = np.linspace(values.min() - 1, values.max() + 1, 400)
plt.figure(figsize=(7, 4))
plt.bar(
    values,
    counts / len(t),
    width=0.8,
    alpha=0.6,
    label=f"peak oracle, {TRIALS:,} samples",
)
plt.plot(
    np.arange(n0 + 1), exact_law, "ko", ms=4, label="exact law (generating function)"
)
plt.plot(
    xs,
    np.exp(-((xs - mu) ** 2) / (2 * sigma**2)) / (sigma * np.sqrt(2 * np.pi)),
    "k",
    lw=1,
    label="normal, exact mean and variance",
)
plt.xlim(values.min() - 1, values.max() + 1)
plt.xlabel("T")
plt.title(f"Monochrome path, n = {n0}")
plt.legend(loc="upper left", fontsize=8)
plt.show()
print(f"total variation between the oracle and the exact law: {tv:.4f}")
assert tv < 0.01
../../_images/papers_exact_stabilization_time_companion_62_0.png
total variation between the oracle and the exact law: 0.0052
[33]:
print(f"notebook run in {time.perf_counter() - START:.0f} s")
notebook run in 152 s