Algorithm Search⌘K

Algorithmadvanced

Cluster-robust standard errors

Also called clustered standard errors, Liang-Zeger standard errors.

A sandwich covariance that sums score contributions within clusters, so that inference stays valid when errors are correlated inside groups.

Time
Θ(n p^2) worst · best
Space
Θ(n p) extra
Where
G = the number of clusters; n = the number of observations; p = the number of columns of X, with p < n
Properties
deterministicexactofflineiterative
Origin
Kung Yee Liang, Scott L. Zeger, Manuel Arellano, A. Colin Cameron, Jonah B. Gelbach, Douglas L. Miller, 1986

Cluster-robust standard errors, also called clustered or Liang-Zeger standard errors, keep the ordinary least squares fit and estimate its covariance when the observations fall into GG groups, such as pupils in schools or years of one firm, and the errors may be correlated in any way inside a group but are independent between groups. Each cluster contributes its total score sg=∑i∈gxieis_g = \sum_{i \in g}x_ie_i, and the covariance estimate is the sandwich (X⊤X)−1(∑gsgsg⊤)(X⊤X)−1(X^\top X)^{-1}\bigl(\sum_gs_gs_g^\top\bigr)(X^\top X)^{-1}, usually times a small sample factor. With one observation per cluster it is the heteroscedasticity-consistent estimate HC0. Its theory needs many clusters: the information about the variance comes from GG cluster totals, not from nn observations, so with few clusters the t intervals are too short and a wild cluster bootstrap is better.

In plain words

When observations come in groups that share something, such as pupils in the same school, their errors tend to move together. The usual standard error treats every observation as new information, so it claims more certainty than the data give. This method first adds up, inside each group, how much the group pushes on the fitted line. It then measures how much these group totals vary. A group of a hundred similar pupils counts as roughly one piece of evidence about the noise, not a hundred. The method needs many groups to work well. With only a handful of groups it is still too optimistic.

The problem

Model. y=Xb+εy = Xb + \varepsilon with XX a fixed real n×pn \times p matrix of rank p<np < n (the intercept is one of the columns). The rows are split into GG clusters, with XgX_g, ygy_g and εg\varepsilon_g the rows of cluster gg. The errors satisfy E[ε]=0\mathrm E[\varepsilon] = 0, Cov⁡(εg)=Σg\operatorname{Cov}(\varepsilon_g) = \Sigma_g of any form, and εg\varepsilon_g is independent of εh\varepsilon_h for g≠hg \ne h. Then

Cov⁡(b^)=(X⊤X)−1(∑gXg⊤ΣgXg)(X⊤X)−1.\operatorname{Cov}(\hat b) = (X^\top X)^{-1}\Bigl(\sum_gX_g^\top\Sigma_gX_g\Bigr)(X^\top X)^{-1}.

Input. XX, yy, a cluster label for each row, and the version.

Output. b^\hat b and V^=a(X⊤X)−1(∑gsgsg⊤)(X⊤X)−1\widehat V = a(X^\top X)^{-1}\bigl(\sum_gs_gs_g^\top\bigr)(X^\top X)^{-1} with sg=Xg⊤egs_g = X_g^\top e_g, where a=1a = 1 for CR0 and

a=GG−1⋅n−1n−pa = \frac{G}{G - 1}\cdot\frac{n - 1}{n - p}

for CR1, the default of most software. Intervals and tests use tG−1t_{G-1}, not tn−pt_{n-p}.

The algorithm

  1. CLUSTER-COVARIANCE(X[1..n, 1..p], y[1..n], cluster[1..n], version)
  2. 1(R, c) ← Householder QR of X, applied to y ▷ X = Q₁R, c = Qᵀy
  3. 2b̂ ← solve R b = c[1..p]
  4. 3eᵢ ← yᵢ - xᵢᵀ b̂ for all i
  5. 4for each cluster g: s_g ← Σ_{i in g} xᵢ eᵢ; u_g ← R⁻ᵀ s_g
  6. 5a ← 1 for CR0, or G/(G - 1) · (n - 1)/(n - p) for CR1
  7. 6V ← a · R⁻¹ (Σ_g u_g u_gᵀ) R⁻ᵀ
  8. 7seⱼ ← √Vⱼⱼ for j = 1..p
  9. 8return (b̂, V, se) with G - 1 degrees of freedom

Line L4 needs one pass over the rows and one triangular solve per cluster. Line L6 is the sandwich in factored form, because R−1R−⊤=(X⊤X)−1R^{-1}R^{-\top} = (X^\top X)^{-1}. A Wald test of Cb=dCb = d with qq rows uses (Cb^−d)⊤(CVC⊤)−1(Cb^−d)/q(C\hat b - d)^\top(CVC^\top)^{-1}(C\hat b - d)/q against Fq,G−1F_{q, G-1}, which needs q≤G−1q \le G - 1.

Wild cluster bootstrap. To test bj=β0b_j = \beta_0 with few clusters: fit the model with bj=β0b_j = \beta_0 imposed, keep its fitted values y~\tilde y and residuals e~\tilde e, and compute the CR1 statistic t=(b^j−β0)/sejt = (\hat b_j - \beta_0)/\mathrm{se}_j. For BB repetitions, draw an independent sign vg=±1v_g = \pm1 for each cluster, set y∗=y~+vge~y^* = \tilde y + v_g\tilde e on the rows of cluster gg, refit, and compute t∗t^* in the same way. The p-value is (1+#{∣t∗∣≥∣t∣})/(1+B)(1 + \#\{|t^*| \ge |t|\})/(1 + B). Because XX does not change, the QR of line L1 is computed once, and each repetition costs Θ(np)\Theta(np).

Example

Take x=(1,2,3,4,5,6)x = (1, 2, 3, 4, 5, 6), y=(2,3,2,4,7,8)y = (2, 3, 2, 4, 7, 8) with an intercept, and three clusters of two rows: {1,2}\{1, 2\}, {3,4}\{3, 4\}, {5,6}\{5, 6\}. Exact arithmetic gives b^=(−1/15,44/35)\hat b = (-1/15, 44/35), and the residuals have the same sign inside each cluster: (0.81,0.55)(0.81, 0.55), (−1.70,−0.96)(-1.70, -0.96), (0.78,0.52)(0.78, 0.52). The cluster scores sgs_g have intercept parts 143/105143/105, −8/3-8/3 and 137/105137/105, which add to 0, as do the slope parts 67/3567/35, −941/105-941/105 and 148/21148/21.

method se of slope
usual, s2(X⊤X)−1s^2(X^\top X)^{-1} 0.2848
HC1 0.2079
CR0 0.2171
CR1 0.2972

CR1 multiplies CR0's variance by 32⋅54=1.875\frac{3}{2}\cdot\frac{5}{4} = 1.875. With G=3G = 3 the estimate rests on two degrees of freedom, so the interval uses t2t_2, whose 0.975 quantile is 4.30. The example only shows the steps; three clusters are far too few for the asymptotic theory.

Measured coverage. In each sample, cluster gg has m=10m = 10 rows with xi=zg+wix_i = z_g + w_i and yi=1+xi+ag+ηiy_i = 1 + x_i + a_g + \eta_i, all of zg,wi,ag,ηiz_g, w_i, a_g, \eta_i independent standard normal, so xx and the errors each have intraclass correlation 1/2. The nominal 95% intervals for the slope gave:

setting usual, tn−2t_{n-2} HC1, tn−2t_{n-2} CR1, normal CR1, tG−1t_{G-1} wild cluster bootstrap
G=20G = 20, r=1000r = 1000 0.707 0.691 0.897 0.920
G=6G = 6, r=1000r = 1000 0.736 0.713 0.822 0.905
G=6G = 6, r=200r = 200, B=99B = 99 0.950

For the bootstrap the entry is 1 minus the rejection rate of the 5% test of b1=1b_1 = 1. The seeds were 20261114, 20261115 and 20261116 for random.Random. Ignoring the clusters is badly wrong, and HC1 does not help, because the problem is correlation, not unequal variance. CR1 with tG−1t_{G-1} is much better but still short; the bootstrap test held its size. These are measurements for one design, with a Monte Carlo standard error of about 0.007 for r=1000r = 1000 and 0.015 for r=200r = 200.

Correctness

The proof shows four exact facts. Lines L1 to L6 return exactly a(X⊤X)−1(∑gsgsg⊤)(X⊤X)−1a(X^\top X)^{-1}\bigl(\sum_gs_gs_g^\top\bigr)(X^\top X)^{-1}. With one row per cluster CR0 is HC0 and CR1 is HC1. The cluster scores add to X⊤e=0X^\top e = 0, so the middle matrix has rank at most G−1G - 1; with one cluster the estimate is the zero matrix. In the wild cluster bootstrap with the null imposed, ∣t∗∣|t^*| is the same for the signs vv and −v-v, so it has at most 2G−12^{G-1} values. The proof also gives the exact expectation of the middle matrix, ∑gXg⊤[(I−H)Σ(I−H)]ggXg\sum_gX_g^\top[(I - H)\Sigma(I - H)]_{gg}X_g, which shows why CR0 is biased down.

The statistical property is cited, not proved: as G→∞G \to \infty, with independent clusters whose sizes do not dominate and with moment conditions, GV^G\widehat V is consistent for the limit of GCov⁡(b^)G\operatorname{Cov}(\hat b) under any within-cluster correlation, and the t statistic is asymptotically normal (Liang and Zeger 1986, Arellano 1987). Using tG−1t_{G-1} is a convention that works better in simulations. The bootstrap gives no exact size either.

Proof: The QR form of the cluster-robust covariance equals the sandwich formula, the cluster scores sum to zero, and the wild cluster bootstrap statistic is even in the signsfull

The arithmetic is exact. XX is a fixed real n×pn \times p matrix of rank p<np < n with rows xi⊤x_i^\top, the rows are split into G≥2G \ge 2 clusters, XgX_g and ege_g are the rows of cluster gg, b^=(X⊤X)−1X⊤y\hat b = (X^\top X)^{-1}X^\top y, e=y−Xb^e = y - X\hat b and H=X(X⊤X)−1X⊤H = X(X^\top X)^{-1}X^\top. The cluster score is sg=Xg⊤eg=∑i∈gxieis_g = X_g^\top e_g = \sum_{i \in g}x_ie_i, and the target is

V^=a (X⊤X)−1(∑g=1Gsgsg⊤)(X⊤X)−1,a=1 (CR0),a=GG−1⋅n−1n−p (CR1).\widehat V = a\,(X^\top X)^{-1}\Bigl(\sum_{g=1}^Gs_gs_g^\top\Bigr)(X^\top X)^{-1}, \qquad a = 1 \text{ (CR0)}, \quad a = \frac{G}{G - 1}\cdot\frac{n - 1}{n - p} \text{ (CR1)}.

Lemma 1 (lines L1 to L6 compute the sandwich). With X⊤X=R⊤RX^\top X = R^\top R from line L1 and ug=R−⊤sgu_g = R^{-\top}s_g from line L4, aR−1(∑gugug⊤)R−⊤=V^aR^{-1}\bigl(\sum_gu_gu_g^\top\bigr)R^{-\top} = \widehat V.

Proof. Line L1 gives an upper triangular nonsingular RR with X=Q1RX = Q_1R and Q1⊤Q1=IQ_1^\top Q_1 = I, so X⊤X=R⊤RX^\top X = R^\top R, and line L2 gives b^\hat b (Lemma 1 of the proof on the weighted least squares page, with unit weights). Then ∑gugug⊤=R−⊤(∑gsgsg⊤)R−1\sum_gu_gu_g^\top = R^{-\top}\bigl(\sum_gs_gs_g^\top\bigr)R^{-1}, and R−1R−⊤=(R⊤R)−1=(X⊤X)−1R^{-1}R^{-\top} = (R^\top R)^{-1} = (X^\top X)^{-1} on each side. □\square

Lemma 2 (singletons and rank). (a) If every cluster has one row, CR0 is HC0 and CR1 is HC1. (b) ∑gsg=0\sum_gs_g = 0, so the middle matrix ∑gsgsg⊤\sum_gs_gs_g^\top has rank at most min⁡(p,G−1)\min(p, G - 1), and with G=1G = 1 it is the zero matrix.

Proof. (a) With one row per cluster, si=xieis_i = x_ie_i and sisi⊤=ei2xixi⊤s_is_i^\top = e_i^2x_ix_i^\top, which is the HC0 middle matrix; with G=nG = n the factor of CR1 is nn−1⋅n−1n−p=nn−p\frac{n}{n - 1}\cdot\frac{n - 1}{n - p} = \frac{n}{n - p}, the factor of HC1. (b) ∑gsg=X⊤e=X⊤(I−H)y=0\sum_gs_g = X^\top e = X^\top(I - H)y = 0, the normal equations. So the GG vectors sgs_g lie in a space of dimension at most G−1G - 1, and the middle matrix is a sum of outer products of vectors in that space. □\square

So with GG clusters a Wald test of more than G−1G - 1 linear restrictions has a singular covariance, and the estimate of any single variance comes from at most G−1G - 1 independent pieces of information. This is why the page uses tG−1t_{G-1} and why few clusters are a problem.

Lemma 3 (expected value). If E[ε]=0\mathrm E[\varepsilon] = 0 and Cov⁡(ε)=Σ\operatorname{Cov}(\varepsilon) = \Sigma with any block structure, then

E[∑gsgsg⊤]=∑gXg⊤[(I−H)Σ(I−H)]ggXg,\mathrm E\Bigl[\sum_gs_gs_g^\top\Bigr] = \sum_gX_g^\top\bigl[(I - H)\Sigma(I - H)\bigr]_{gg}X_g,

where [⋅]gg[\cdot]_{gg} is the diagonal block of cluster gg, while the true covariance is Cov⁡(b^)=(X⊤X)−1X⊤ΣX(X⊤X)−1\operatorname{Cov}(\hat b) = (X^\top X)^{-1}X^\top\Sigma X(X^\top X)^{-1}.

Proof. e=(I−H)εe = (I - H)\varepsilon, so ege_g is the gg block of (I−H)ε(I - H)\varepsilon and E[egeg⊤]=[(I−H)Σ(I−H)]gg\mathrm E[e_ge_g^\top] = [(I - H)\Sigma(I - H)]_{gg}. Then E[sgsg⊤]=Xg⊤E[egeg⊤]Xg\mathrm E[s_gs_g^\top] = X_g^\top\mathrm E[e_ge_g^\top]X_g. □\square

If Σ\Sigma is block diagonal by cluster, X⊤ΣX=∑gXg⊤ΣggXgX^\top\Sigma X = \sum_gX_g^\top\Sigma_{gg}X_g, and the two differ only by the replacement of Σ\Sigma by (I−H)Σ(I−H)(I - H)\Sigma(I - H). When some clusters carry a large share of the leverage this shrinks the middle matrix, so CR0 is biased down; the factor of CR1 is a rough correction, not an exact one.

Lemma 4 (the wild cluster bootstrap statistic is even in the signs). In the bootstrap with the null bj=β0b_j = \beta_0 imposed, let y~\tilde y be the restricted fit and e~=y−y~\tilde e = y - \tilde y, and for a sign vector v∈{−1,1}Gv \in \{-1, 1\}^G let y∗(v)=y~+D(v)e~y^*(v) = \tilde y + D(v)\tilde e, where D(v)D(v) multiplies the rows of cluster gg by vgv_g. Then ∣t∗(v)∣=∣t∗(−v)∣|t^*(v)| = |t^*(-v)|, so ∣t∗∣|t^*| takes at most 2G−12^{G-1} distinct values.

Proof. y~=Xb~\tilde y = X\tilde b for a vector b~\tilde b with b~j=β0\tilde b_j = \beta_0, so b^∗(v)−b~=(X⊤X)−1X⊤D(v)e~\hat b^*(v) - \tilde b = (X^\top X)^{-1}X^\top D(v)\tilde e, which is linear in vv and changes sign with vv. The residuals e∗(v)=(I−H)D(v)e~e^*(v) = (I - H)D(v)\tilde e change sign too, so each sg∗s_g^* changes sign and ∑gsg∗sg∗⊤\sum_gs_g^*s_g^{*\top} does not change. Hence b^j∗−β0\hat b_j^* - \beta_0 changes sign and sej∗\mathrm{se}_j^* is unchanged. □\square

With G=6G = 6 the bootstrap p-value can take at most 32 values, so it cannot go below about 1/321/32; this is a property of the Rademacher weights, not of the data.

What is cited, not proved. As G→∞G \to \infty with independent clusters, bounded cluster sizes or sizes that do not dominate, and moment and design conditions, GV^G\widehat V is consistent for the limit of GCov⁡(b^)G\operatorname{Cov}(\hat b) for any within-cluster correlation, and the t statistics are asymptotically standard normal (Liang and Zeger 1986 for estimating equations, Arellano 1987 for fixed effects panel regressions). That the wild cluster bootstrap gives better small GG tests is a simulation finding (Cameron, Gelbach and Miller 2008), with asymptotic support but no exact guarantee. None of these is proved here, and the coverage and size figures on the page are measured.

Termination. Line L1 is pp Householder steps, line L2 one triangular solve, line L3 nn dot products, line L4 nn updates of size pp and GG triangular solves, and lines L5 to L7 finite sums: Θ(np2)\Theta(np^2) operations in total, since G≤nG \le n.

Complexity

The QR costs Θ(np2)\Theta(np^2), the residuals and the cluster scores Θ(np)\Theta(np), the GG triangular solves Θ(Gp2)\Theta(Gp^2), and the sum and the sandwich Θ(Gp2+p3)\Theta(Gp^2 + p^3). Since G≤nG \le n and p<np < n, the total is Θ(np2)\Theta(np^2) time with Θ(np)\Theta(np) extra space for the QR. Grouping the rows by cluster costs Θ(n)\Theta(n) expected time with a hash table. Each wild bootstrap repetition costs Θ(np+Gp2)\Theta(np + Gp^2) because the QR is reused.

Properties

  • Any within-cluster correlation. No model for Σg\Sigma_g is used, so heteroscedasticity and correlation inside clusters are both covered.
  • Nesting. If the clusters are merged into larger ones, the estimate stays valid but has fewer degrees of freedom. Clustering at a level that is too fine, for example by person when the treatment is assigned by school, misses correlation and gives intervals that are too short.
  • Rank. The middle matrix has rank at most min⁡(p,G−1)\min(p, G - 1), so joint tests of more than G−1G - 1 restrictions are impossible.
  • Sandwich form. It is the general sandwich of an M-estimator with the scores summed by cluster first, and the same construction gives the variance of generalized estimating equations.
  • Equivariance. Replacing XX by XAXA for a nonsingular AA maps V^\widehat V to A−1V^A−⊤A^{-1}\widehat VA^{-\top}. The labels of the clusters and the order of the rows do not matter.

Variants and improvements

  • CR2 and CR3. These replace ege_g by (I−Hgg)−1/2eg(I - H_{gg})^{-1/2}e_g or (I−Hgg)−1eg(I - H_{gg})^{-1}e_g, the cluster forms of HC2 and HC3, and reduce the downward bias. With a degrees of freedom correction for the t reference, CR2 is the usual recommendation for few clusters.
  • Wild cluster bootstrap. The version above, with the null imposed, gives tests close to the nominal size with as few as 6 clusters in many designs. With Rademacher signs and GG clusters there are only 2G−12^{G-1} distinct values of ∣t∗∣|t^*|, so for G<10G < 10 software often uses weights with six values.
  • Multiway clustering. For errors correlated within firms and within years, add the one-way estimates for each dimension and subtract the estimate for their intersection. The result can fail to be positive semidefinite.
  • Fixed effects. With cluster fixed effects, the scores of the transformed model are used, as in Arellano (1987); the degrees of freedom correction must not count the fixed effects as parameters when they are nested in the clusters.
  • Efficient alternatives. If the correlation has a known form, such as a random intercept, generalized least squares or a linear mixed model is more efficient, and the cluster sandwich can still be used on top of it to protect against a wrong correlation model.

When to use it

Use clustered standard errors whenever the observations come in groups that may share unobserved shocks and there are many groups, say 40 or more: panels of firms or people over time, surveys sampled by area, experiments randomized by school or village, and difference-in-differences designs with state-level policies. Cluster at the level at which the treatment is assigned or at which the shocks are shared. With fewer than about 40 clusters, or with clusters of very unequal size, use CR2 or the wild cluster bootstrap. If there is only one or two treated clusters, no version of the method gives reliable inference.

Pitfalls

  • Few clusters. The estimate is consistent only as GG grows. With GG below about 40, CR1 with normal critical values over-rejects, sometimes badly; use tG−1t_{G-1} at least and preferably the wild cluster bootstrap.
  • Unequal cluster sizes. A few large clusters dominate the sum and act like few clusters, even when GG is large.
  • Wrong level. Clustering below the level of the shared shock leaves correlation between clusters and the standard errors too small. Clustering at a much coarser level than needed wastes degrees of freedom but is not invalid.
  • Not a fix for bias. The method corrects the variance of OLS, not the estimate. Correlation with the regressors, for example a cluster effect correlated with xx, still biases b^\hat b and needs fixed effects or another design.
  • Version. Packages differ in the factor aa and in the reference law; state both.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

cluster_robust_standard_errors.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cluster-robust-standard-errors/. The authors are listed in prov/X126D2.jsonl.
"""Cluster-robust covariance of the least squares estimate, CR0 and CR1, and the wild cluster bootstrap.

With X = Q1 R (thin QR) and s_g = sum over the rows i of cluster g of x_i e_i, the sandwich
(X^T X)^(-1) (sum_g s_g s_g^T) (X^T X)^(-1) equals R^(-1) (sum_g u_g u_g^T) R^(-T) with u_g = R^(-T) s_g.
  CR0: factor 1
  CR1: factor G/(G - 1) * (n - 1)/(n - p)
Inference uses t with G - 1 degrees of freedom. Nothing of size n x n is formed.
"""

import math
import random
from typing import NamedTuple

from stdist import t_ppf

RANK_TOL = 1e-12
KINDS = ("CR0", "CR1")


class CRFit(NamedTuple):
    b: list          # least squares coefficients
    cov: list        # the cluster-robust covariance estimate, p x p
    se: list         # square roots of its diagonal
    residuals: list  # e_i
    clusters: int    # G
    df: int          # G - 1, used for t intervals


def householder_r(a: list, y: list) -> tuple[list, list]:
    """R of a Householder QR of the n x p matrix a, and Q^T y. Raises ValueError if rank < p."""
    n = len(a)
    p = len(a[0]) if n else 0
    if p == 0 or n < p:
        raise ValueError("need a design with n >= p >= 1")
    a = [[float(v) for v in row] for row in a]
    c = [float(v) for v in y]
    col = [math.sqrt(math.fsum(a[i][j] ** 2 for i in range(n))) for j in range(p)]
    for j in range(p):
        norm = math.sqrt(math.fsum(a[i][j] ** 2 for i in range(j, n)))
        if norm == 0.0 or norm <= RANK_TOL * col[j]:
            raise ValueError("the design has rank below its number of columns")
        alpha = -norm if a[j][j] >= 0.0 else norm
        v = [a[j][j] - alpha] + [a[i][j] for i in range(j + 1, n)]
        vv = math.fsum(t * t for t in v)
        for k in range(j, p):
            s = 2.0 * math.fsum(v[i - j] * a[i][k] for i in range(j, n)) / vv
            for i in range(j, n):
                a[i][k] -= s * v[i - j]
        s = 2.0 * math.fsum(v[i - j] * c[i] for i in range(j, n)) / vv
        for i in range(j, n):
            c[i] -= s * v[i - j]
    return [[a[i][k] if k >= i else 0.0 for k in range(p)] for i in range(p)], c


def back_substitute(r: list, c: list) -> list:
    p = len(r)
    x = [0.0] * p
    for i in range(p - 1, -1, -1):
        x[i] = (c[i] - math.fsum(r[i][k] * x[k] for k in range(i + 1, p))) / r[i][i]
    return x


def forward_substitute_rt(r: list, c: list) -> list:
    """Solve R^T u = c for upper triangular R (R^T is lower triangular)."""
    p = len(r)
    u = [0.0] * p
    for i in range(p):
        u[i] = (c[i] - math.fsum(r[k][i] * u[k] for k in range(i))) / r[i][i]
    return u


def sandwich(r: list, u: list, factor: float) -> list:
    """factor * R^(-1) (sum_g u_g u_g^T) R^(-T) for upper triangular R."""
    p = len(r)
    m = [[factor * math.fsum(ug[a] * ug[b] for ug in u) for b in range(p)] for a in range(p)]
    t = [back_substitute(r, [m[a][b] for a in range(p)]) for b in range(p)]   # columns of R^(-1) M
    rows = [back_substitute(r, [t[b][a] for b in range(p)]) for a in range(p)]  # rows of (R^(-1) M) R^(-T)
    return [[rows[a][b] for b in range(p)] for a in range(p)]


def cluster_index(groups: list) -> list:
    """Lists of row indices, one per cluster, in the order of first appearance of each label."""
    where = {}
    for i, g in enumerate(groups):
        where.setdefault(g, []).append(i)
    return list(where.values())


def _cr_from_qr(x, y, r, c, members, kind):
    n, p = len(x), len(r)
    big_g = len(members)
    b = back_substitute(r, c[:p])  # @line L2
    e = [yi - math.fsum(a * bb for a, bb in zip(xi, b)) for xi, yi in zip(x, y)]  # @line L3
    s = [[math.fsum(x[i][j] * e[i] for i in rows) for j in range(p)] for rows in members]  # @line L4
    u = [forward_substitute_rt(r, sg) for sg in s]  # @line L4
    factor = 1.0 if kind == "CR0" else big_g / (big_g - 1) * (n - 1) / (n - p)  # @line L5
    cov = sandwich(r, u, factor)  # @line L6
    se = [math.sqrt(max(cov[j][j], 0.0)) for j in range(p)]  # @line L7
    return CRFit(b, cov, se, e, big_g, big_g - 1)  # @line L8


def cluster_covariance(x: list, y: list, groups: list, kind: str = "CR1") -> CRFit:
    """Least squares fit with the cluster-robust covariance; groups[i] is the cluster label of row i.

    Cost: Theta(n p^2) time, Theta(n p) space.
    """
    if kind not in KINDS:
        raise ValueError("kind must be one of " + ", ".join(KINDS))
    n = len(x)
    if len(y) != n or len(groups) != n:
        raise ValueError("x, y and groups must have the same length")
    members = cluster_index(groups)
    if len(members) < 2:
        raise ValueError("need at least two clusters")
    r, c = householder_r(x, y)  # @line L1
    if n <= len(r):
        raise ValueError("need n > p")
    return _cr_from_qr(x, y, r, c, members, kind)


def confidence_intervals(fit: CRFit, level: float = 0.95) -> list:
    """b_j +- t_(G-1, (1 + level)/2) se_j. The level is only approximate: the theory is asymptotic in G."""
    qt = t_ppf(0.5 + level / 2.0, fit.df)
    return [(bj - qt * s, bj + qt * s) for bj, s in zip(fit.b, fit.se)]


def wild_cluster_bootstrap(x: list, y: list, groups: list, j: int, value: float = 0.0,
                           reps: int = 999, seed: int = 1) -> tuple[float, float]:
    """Wild cluster bootstrap p-value for H0: b_j = value, with the null imposed and Rademacher weights.

    Returns (t, p) where t = (b_j - value)/se_j uses CR1 and p = (1 + #{|t*| >= |t|})/(1 + reps).
    """
    n, p = len(x), len(x[0])
    members = cluster_index(groups)
    r, c = householder_r(x, y)
    fit = _cr_from_qr(x, y, r, c, members, "CR1")
    t_obs = (fit.b[j] - value) / fit.se[j]
    # Restricted fit: drop column j and move value * x_j to the left side.
    xr = [[v for k, v in enumerate(row) if k != j] for row in x]
    yr = [yi - value * row[j] for yi, row in zip(y, x)]
    if p > 1:
        rr, cr = householder_r(xr, yr)
        br = back_substitute(rr, cr[:p - 1])
        fitted = [value * row[j] + math.fsum(a * bb for a, bb in zip(xrow, br)) for row, xrow in zip(x, xr)]
    else:
        fitted = [value * row[j] for row in x]
    er = [yi - fi for yi, fi in zip(y, fitted)]
    q = [forward_substitute_rt(r, xi) for xi in x]  # rows of Q1, so Q1^T y* = sum q_i y*_i
    rng = random.Random(seed)
    extreme = 0
    for _ in range(reps):
        ystar = list(fitted)
        for rows in members:
            sign = 1.0 if rng.random() < 0.5 else -1.0
            for i in rows:
                ystar[i] += sign * er[i]
        cstar = [math.fsum(qi[k] * yi for qi, yi in zip(q, ystar)) for k in range(p)]
        f = _cr_from_qr(x, ystar, r, cstar, members, "CR1")
        if abs((f.b[j] - value) / f.se[j]) >= abs(t_obs):
            extreme += 1
    return t_obs, (1 + extreme) / (1 + reps)
stdist.py 238 lines
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Normal, chi-square, t and F distribution functions in the standard library.

The incomplete gamma and beta functions return a lower tail and an upper
tail, and each tail is computed directly where it is small, so an upper tail
such as chi2_sf(200, 3) does not come from 1 - cdf and does not cancel.
Quantiles use a safeguarded bisection on the CDF (lower half) or on the upper
tail (upper half); the bracket shrinks until floating point stops it, so the
probability error is that of the CDF, below 1e-12 for moderate parameters.
"""

import math
from statistics import NormalDist

_STD = NormalDist()
_EPS = 1e-16
_TINY = 1e-300
_MAXIT = 10000


def norm_cdf(x: float) -> float:
    """P(Z <= x) for a standard normal Z."""
    return 0.5 * math.erfc(-x / math.sqrt(2.0))


def norm_sf(x: float) -> float:
    """P(Z > x), computed with erfc, so it is accurate for large x."""
    return 0.5 * math.erfc(x / math.sqrt(2.0))


def norm_ppf(p: float) -> float:
    """The lower p-quantile z_p of the standard normal, 0 < p < 1."""
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    return _STD.inv_cdf(p)


def _gamma_tails(a: float, x: float) -> tuple[float, float]:
    """(P(a, x), Q(a, x)), the regularized lower and upper incomplete gamma."""
    if a <= 0.0 or x < 0.0:
        raise ValueError("need a > 0 and x >= 0")
    if x == 0.0:
        return 0.0, 1.0
    if math.isinf(x):
        return 1.0, 0.0
    front = math.exp(-x + a * math.log(x) - math.lgamma(a))
    if x < a + 1.0:
        # Series: P = front * sum_{j >= 0} x^j / (a (a + 1) ... (a + j)).
        ap, term = a, 1.0 / a
        total = term
        for _ in range(_MAXIT):
            ap += 1.0
            term *= x / ap
            total += term
            if abs(term) < abs(total) * _EPS:
                break
        p = front * total
        return p, 1.0 - p
    # Continued fraction for Q, modified Lentz.
    b = x + 1.0 - a
    c = 1.0 / _TINY
    d = 1.0 / b
    h = d
    for i in range(1, _MAXIT):
        an = -i * (i - a)
        b += 2.0
        d = an * d + b
        if abs(d) < _TINY:
            d = _TINY
        c = b + an / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        step = d * c
        h *= step
        if abs(step - 1.0) < _EPS:
            break
    q = front * h
    return 1.0 - q, q


def gamma_p(a: float, x: float) -> float:
    """Regularized lower incomplete gamma P(a, x)."""
    return _gamma_tails(a, x)[0]


def gamma_q(a: float, x: float) -> float:
    """Regularized upper incomplete gamma Q(a, x) = 1 - P(a, x)."""
    return _gamma_tails(a, x)[1]


def _beta_cf(a: float, b: float, x: float) -> float:
    """The continued fraction of I_x(a, b), modified Lentz."""
    qab, qap, qam = a + b, a + 1.0, a - 1.0
    c = 1.0
    d = 1.0 - qab * x / qap
    if abs(d) < _TINY:
        d = _TINY
    d = 1.0 / d
    h = d
    for m in range(1, _MAXIT):
        m2 = 2 * m
        aa = m * (b - m) * x / ((qam + m2) * (a + m2))
        d = 1.0 + aa * d
        if abs(d) < _TINY:
            d = _TINY
        c = 1.0 + aa / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        h *= d * c
        aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
        d = 1.0 + aa * d
        if abs(d) < _TINY:
            d = _TINY
        c = 1.0 + aa / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        step = d * c
        h *= step
        if abs(step - 1.0) < _EPS:
            break
    return h


def _beta_tails(a: float, b: float, x: float, y: float | None = None) -> tuple[float, float]:
    """(I_x(a, b), 1 - I_x(a, b)), each computed directly where it is small.

    y is 1 - x; pass it when it is known more accurately than 1 - x.
    """
    if a <= 0.0 or b <= 0.0:
        raise ValueError("need a > 0 and b > 0")
    if y is None:
        y = 1.0 - x
    if x <= 0.0:
        return 0.0, 1.0
    if y <= 0.0:
        return 1.0, 0.0
    front = math.exp(
        math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
        + a * math.log(x) + b * math.log(y)
    )
    if x < (a + 1.0) / (a + b + 2.0):
        low = front * _beta_cf(a, b, x) / a
        return low, 1.0 - low
    # Symmetry: I_x(a, b) = 1 - I_(1-x)(b, a).
    up = front * _beta_cf(b, a, y) / b
    return 1.0 - up, up


def beta_inc(a: float, b: float, x: float) -> float:
    """Regularized incomplete beta function I_x(a, b)."""
    return _beta_tails(a, b, x)[0]


def chi2_cdf(x: float, k: float) -> float:
    """P(X <= x) for X chi-square with k > 0 degrees of freedom."""
    return 0.0 if x <= 0.0 else gamma_p(k / 2.0, x / 2.0)


def chi2_sf(x: float, k: float) -> float:
    """P(X > x) for X chi-square with k degrees of freedom, without 1 - cdf."""
    return 1.0 if x <= 0.0 else gamma_q(k / 2.0, x / 2.0)


def t_sf(x: float, k: float) -> float:
    """P(T > x) for T Student t with k > 0 degrees of freedom."""
    if math.isfinite(x):
        s = k + x * x
        half = 0.5 * _beta_tails(k / 2.0, 0.5, k / s, x * x / s)[0]  # P(|T| > |x|) / 2
    else:
        half = 0.0
    return half if x >= 0.0 else 1.0 - half


def t_cdf(x: float, k: float) -> float:
    """P(T <= x) for T Student t with k degrees of freedom."""
    return t_sf(-x, k)


def f_cdf(x: float, k1: float, k2: float) -> float:
    """P(F <= x) for F with (k1, k2) degrees of freedom."""
    if x <= 0.0:
        return 0.0
    return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[1]


def f_sf(x: float, k1: float, k2: float) -> float:
    """P(F > x) = I_(k2 / (k2 + k1 x))(k2 / 2, k1 / 2)."""
    if x <= 0.0:
        return 1.0
    return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[0]


def _quantile(cdf, sf, p: float, lo: float, hi: float) -> float:
    """The x with cdf(x) = p, by bisection on cdf (p <= 1/2) or on sf (p > 1/2).

    lo must satisfy cdf(lo) <= p; hi is doubled until cdf(hi) >= p.
    """
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    if p <= 0.5:
        g = lambda x: cdf(x) - p  # increasing in x
    else:
        q = 1.0 - p
        g = lambda x: q - sf(x)  # increasing in x, and no cancellation in sf
    while g(hi) < 0.0:
        lo, hi = hi, 2.0 * hi if hi > 0.0 else 1.0
    for _ in range(400):
        mid = 0.5 * (lo + hi)
        if mid <= lo or mid >= hi:
            break
        if g(mid) < 0.0:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi)


def chi2_ppf(p: float, k: float) -> float:
    """The lower p-quantile chi^2_(k, p)."""
    return _quantile(lambda x: chi2_cdf(x, k), lambda x: chi2_sf(x, k), p, 0.0, max(1.0, k))


def t_ppf(p: float, k: float) -> float:
    """The lower p-quantile t_(k, p)."""
    if p == 0.5:
        return 0.0
    if p < 0.5:
        return -t_ppf(1.0 - p, k)
    return _quantile(lambda x: t_cdf(x, k), lambda x: t_sf(x, k), p, 0.0, 1.0)


def f_ppf(p: float, k1: float, k2: float) -> float:
    """The lower p-quantile F_(k1, k2, p)."""
    return _quantile(lambda x: f_cdf(x, k1, k2), lambda x: f_sf(x, k1, k2), p, 0.0, 1.0)
test_cluster_robust_standard_errors.py 202 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cluster-robust-standard-errors/. The authors are listed in prov/X126D2.jsonl.

import math
import random
from fractions import Fraction

import pytest

from cluster_robust_standard_errors import (KINDS, cluster_covariance, confidence_intervals,
                                            wild_cluster_bootstrap)
from stdist import t_ppf

EX_X = [[1, v] for v in [1, 2, 3, 4, 5, 6]]
EX_Y = [2, 3, 2, 4, 7, 8]
EX_G = ["a", "a", "b", "b", "c", "c"]


def solve(a, b):
    k = len(a)
    m = [[Fraction(v) for v in row] + [Fraction(b[i])] for i, row in enumerate(a)]
    for c in range(k):
        piv = next(r for r in range(c, k) if m[r][c] != 0)
        m[c], m[piv] = m[piv], m[c]
        for r in range(k):
            if r != c and m[r][c] != 0:
                f = m[r][c] / m[c][c]
                m[r] = [u - f * v for u, v in zip(m[r], m[c])]
    return [m[i][k] / m[i][i] for i in range(k)]


def inverse(a):
    n = len(a)
    cols = [solve(a, [int(i == j) for i in range(n)]) for j in range(n)]
    return [[cols[j][i] for j in range(n)] for i in range(n)]


def gram(x):
    p = len(x[0])
    return [[sum(Fraction(r[i]) * r[j] for r in x) for j in range(p)] for i in range(p)]


def fit_exact(x, y):
    p = len(x[0])
    b = solve(gram(x), [sum(Fraction(r[i]) * v for r, v in zip(x, y)) for i in range(p)])
    e = [v - sum(Fraction(a) * c for a, c in zip(r, b)) for r, v in zip(x, y)]
    return b, e


def direct(x, y, groups, kind):
    """(X^T X)^(-1) (sum_g s_g s_g^T) (X^T X)^(-1) times the factor, with explicit exact matrices."""
    n, p = len(x), len(x[0])
    gi = inverse(gram(x))
    b, e = fit_exact(x, y)
    labels = list(dict.fromkeys(groups))
    s = [[sum(Fraction(x[i][j]) * e[i] for i in range(n) if groups[i] == g) for j in range(p)] for g in labels]
    big_g = len(labels)
    factor = 1 if kind == "CR0" else Fraction(big_g, big_g - 1) * Fraction(n - 1, n - p)
    meat = [[factor * sum(sg[i] * sg[j] for sg in s) for j in range(p)] for i in range(p)]
    v = [[sum(gi[i][k] * meat[k][l] * gi[l][j] for k in range(p) for l in range(p)) for j in range(p)]
         for i in range(p)]
    return b, e, s, v


def hc_direct(x, y, kind):
    """HC0 or HC1 with explicit exact matrices."""
    n, p = len(x), len(x[0])
    gi = inverse(gram(x))
    _, e = fit_exact(x, y)
    factor = 1 if kind == "HC0" else Fraction(n, n - p)
    meat = [[factor * sum(ei * ei * r[i] * r[j] for ei, r in zip(e, x)) for j in range(p)] for i in range(p)]
    return [[sum(gi[i][k] * meat[k][l] * gi[l][j] for k in range(p) for l in range(p)) for j in range(p)]
            for i in range(p)]


def close(a, b):
    for row_a, row_b in zip(a, b):
        assert row_a == pytest.approx([float(t) for t in row_b], rel=1e-9, abs=1e-12)


def test_page_example_exact():
    b, e, s, v0 = direct(EX_X, EX_Y, EX_G, "CR0")
    assert b == [Fraction(-1, 15), Fraction(44, 35)]
    assert all(e[i] > 0 for i in (0, 1, 4, 5)) and e[2] < 0 and e[3] < 0  # residuals share signs in clusters
    assert sum(sg[0] for sg in s) == 0 and sum(sg[1] for sg in s) == 0  # the scores add to X^T e = 0
    v1 = direct(EX_X, EX_Y, EX_G, "CR1")[3]
    assert v1[1][1] == v0[1][1] * Fraction(3, 2) * Fraction(5, 4)
    for kind, v in (("CR0", v0), ("CR1", v1)):
        fit = cluster_covariance(EX_X, EX_Y, EX_G, kind)
        close(fit.cov, v)
        assert fit.clusters == 3 and fit.df == 2
    assert cluster_covariance(EX_X, EX_Y, EX_G, "CR0").se[1] == pytest.approx(0.2171, abs=1e-4)
    assert cluster_covariance(EX_X, EX_Y, EX_G, "CR1").se[1] == pytest.approx(0.2972, abs=1e-4)
    assert math.sqrt(float(hc_direct(EX_X, EX_Y, "HC1")[1][1])) == pytest.approx(0.2079, abs=1e-4)


def test_matches_direct_matrices_on_random_designs_exact():
    rng = random.Random(11)
    done = 0
    while done < 10:
        n = rng.randint(8, 14)
        x = [[1, rng.randint(-4, 4), rng.randint(0, 5)] for _ in range(n)]
        y = [rng.randint(-9, 9) for _ in range(n)]
        groups = [rng.randint(0, 3) for _ in range(n)]
        if len(set(groups)) < 2:
            continue
        try:
            ref = {k: direct(x, y, groups, k)[3] for k in KINDS}
        except StopIteration:
            continue  # singular design
        for kind in KINDS:
            close(cluster_covariance(x, y, groups, kind).cov, ref[kind])
        done += 1


def test_singleton_clusters_give_hc0_and_hc1_exact():
    """With one row per cluster s_i = x_i e_i, so CR0 = HC0, and G = n turns the CR1 factor into n/(n - p)."""
    rng = random.Random(12)
    for _ in range(5):
        n = 9
        x = [[1, rng.randint(-5, 5), rng.randint(-5, 5)] for _ in range(n)]
        y = [rng.randint(-9, 9) for _ in range(n)]
        try:
            hc0, hc1 = hc_direct(x, y, "HC0"), hc_direct(x, y, "HC1")
        except StopIteration:
            continue
        groups = list(range(n))
        assert direct(x, y, groups, "CR0")[3] == hc0
        assert direct(x, y, groups, "CR1")[3] == hc1
        close(cluster_covariance(x, y, groups, "CR0").cov, hc0)
        close(cluster_covariance(x, y, groups, "CR1").cov, hc1)


def test_rank_is_at_most_g_minus_one_exact():
    """The cluster scores sum to X^T e = 0, so the middle matrix has rank at most G - 1."""
    rng = random.Random(13)
    x = [[1, rng.randint(-5, 5), rng.randint(-5, 5)] for _ in range(10)]
    y = [rng.randint(-9, 9) for _ in range(10)]
    groups = [0] * 5 + [1] * 5
    _, _, s, v = direct(x, y, groups, "CR0")
    assert [s[0][j] + s[1][j] for j in range(3)] == [0, 0, 0]
    det = (v[0][0] * (v[1][1] * v[2][2] - v[1][2] * v[2][1]) - v[0][1] * (v[1][0] * v[2][2] - v[1][2] * v[2][0])
           + v[0][2] * (v[1][0] * v[2][1] - v[1][1] * v[2][0]))
    assert det == 0
    with pytest.raises(ValueError):
        cluster_covariance(x, y, [7] * 10)  # one cluster: the estimate would be the zero matrix
    with pytest.raises(ValueError):
        cluster_covariance(x, y, groups, "CR9")


def test_labels_and_row_order_do_not_matter():
    perm = [3, 0, 5, 1, 4, 2]
    a = cluster_covariance(EX_X, EX_Y, EX_G, "CR1")
    b = cluster_covariance([EX_X[i] for i in perm], [EX_Y[i] for i in perm], [{"a": 9, "b": 4, "c": 1}[EX_G[i]] for i in perm])
    close(b.cov, [[Fraction(t) for t in row] for row in a.cov])


def draw(rng, big_g, m):
    """Random intercepts in the errors and a cluster component in x: both intraclass correlations are 1/2."""
    x, y, grp = [], [], []
    for g in range(big_g):
        zg, ag = rng.gauss(0.0, 1.0), rng.gauss(0.0, 1.0)
        for _ in range(m):
            xv = zg + rng.gauss(0.0, 1.0)
            x.append([1.0, xv])
            y.append(1.0 + xv + ag + rng.gauss(0.0, 1.0))
            grp.append(g)
    return x, y, grp


def test_coverage_measured():
    """G = 20 clusters of 10. Measured with r = 1000: CR1 with t_19 covered 0.920, the usual and
    HC1 intervals 0.707 and 0.691. Here r = 300 (4 SE about 0.06 near 0.9): CR1 at least 0.86, the usual
    interval at most 0.80."""
    rng = random.Random(20261114)
    r, hit_cr, hit_naive = 300, 0, 0
    for _ in range(r):
        x, y, grp = draw(rng, 20, 10)
        f = cluster_covariance(x, y, grp, "CR1")
        lo, hi = confidence_intervals(f)[1]
        hit_cr += lo <= 1.0 <= hi
        n = len(y)
        xb = sum(row[1] for row in x) / n
        se = math.sqrt(sum(t * t for t in f.residuals) / (n - 2) / sum((row[1] - xb) ** 2 for row in x))
        hit_naive += abs(f.b[1] - 1.0) <= t_ppf(0.975, n - 2) * se
    assert hit_cr / r >= 0.86
    assert hit_naive / r <= 0.80


def test_wild_cluster_bootstrap_size_and_power_measured():
    """G = 6 clusters of 10. Measured with r = 200 and B = 99: rejection rate 0.050 at the 5% level,
    while CR1 with t_5 covered only 0.905. Here r = 100 (4 SE about 0.09): rate at most 0.14."""
    rng = random.Random(20261116)
    r, rej = 100, 0
    for rep in range(r):
        x, y, grp = draw(rng, 6, 10)
        _, pv = wild_cluster_bootstrap(x, y, grp, 1, 1.0, reps=99, seed=rep + 1)
        rej += pv <= 0.05
    assert rej / r <= 0.14
    x, y, grp = draw(random.Random(5), 12, 10)
    t, pv = wild_cluster_bootstrap(x, y, grp, 1, 0.0, reps=199, seed=3)  # the true slope is 1
    assert abs(t) > 4 and pv <= 0.01

History

The idea of summing score products within independent units goes back to the sandwich covariance of Huber (1967) and the heteroscedasticity-consistent estimate of White (1980). Liang and Zeger (1986) used it for longitudinal data in their generalized estimating equations, and Arellano (1987) gave it for within-groups estimators in econometric panels; the two forms are the same computation. Cameron, Gelbach and Miller (2008) showed the over-rejection with few clusters and proposed the wild cluster bootstrap, and Cameron and Miller (2015) wrote the standard practical guide.

References

  1. Kung-Yee Liang and Scott L. Zeger, Longitudinal data analysis using generalized linear models, Biometrika 73(1), 1986, pp. 13 to 22, The whole paper (estimating equations for clustered data and the sandwich variance that sums score products within subjects)
  2. Manuel Arellano, Computing robust standard errors for within-groups estimators, Oxford Bulletin of Economics and Statistics 49(4), 1987, pp. 431 to 434, The whole paper (the cluster sandwich for the fixed effects panel regression, consistent as the number of units grows)
  3. A. Colin Cameron, Jonah B. Gelbach and Douglas L. Miller, Bootstrap-based improvements for inference with clustered errors, The Review of Economics and Statistics 90(3), 2008, pp. 414 to 427, The whole paper (over-rejection with 5 to 30 clusters, and the wild cluster bootstrap with the null imposed)
  4. A. Colin Cameron and Douglas L. Miller, A practitioner's guide to cluster-robust inference, Journal of Human Resources 50(2), 2015, pp. 317 to 372, The whole paper (the CR1 factor, the choice of the cluster level, few clusters, and multiway clustering)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example