Algorithm Search⌘K

Algorithmcore

Anderson-Darling test

Also called Anderson-Darling statistic.

A goodness-of-fit test by a weighted squared distance between the empirical and the model CDF, with weights that stress the tails.

Time
Θ(b n log n) worstΘ(n log n) best
Space
Θ(n) extra
Where
b = the number of simulated samples for the Monte Carlo p-value; n = the sample size
Properties
randomizednot exactofflineiterative
Origin
Theodore W. Anderson, Donald A. Darling, 1952

The Anderson-Darling test checks whether a sample x1,…,xnx_1, \ldots, x_n comes from a given continuous distribution function F0F_0. Its statistic is

A2=n∫−∞∞(Fn(t)−F0(t))2F0(t)(1−F0(t)) dF0(t),A^2 = n \int_{-\infty}^{\infty} \frac{(F_n(t) - F_0(t))^2}{F_0(t)(1 - F_0(t))} \, dF_0(t),

the squared distance between the empirical distribution function FnF_n and F0F_0, with each point weighted by the inverse of the variance of Fn(t)F_n(t). The weight is large in both tails, so the test reacts to differences in the tails that the Kolmogorov-Smirnov test misses. After sorting, A2A^2 is a sum of nn logarithms. Its null law does not depend on F0F_0, and the page takes the p-value from the limit law or from a Monte Carlo simulation of uniform samples.

In plain words

A model says how the data should spread out. Compare the share of data below each point with the share that the model expects. A gap of a given size is more surprising in the tails than in the middle, because few points fall in the tails, so the shares there should match closely. The test squares each gap, divides it by how much the gap usually varies at that point, and adds the results over the whole range.

A large total means that the data and the model disagree somewhere, often in a tail. The same table serves every continuous model, because a fixed change of scale turns any such model into the uniform model. For a small sample one can also simulate many uniform samples and count how often their total is at least as large.

The problem

Model. X1,…,XnX_1, \ldots, X_n are independent with an unknown distribution function FF. F0F_0 is a fully specified continuous distribution function.

Hypotheses. H0H_0: F=F0F = F_0. H1H_1: F≠F0F \ne F_0.

Statistic. With ui=F0(x(i))u_i = F_0(x_{(i)}) for the sorted data,

A2=−n−1n∑i=1n(2i−1)[ln⁡ui+ln⁡(1−un+1−i)].A^2 = -n - \frac{1}{n} \sum_{i=1}^{n} (2i - 1) \left[\ln u_i + \ln(1 - u_{n+1-i})\right].

It equals the integral above. If some uiu_i is 0 or 1, the integral is infinite.

Null distribution. Under H0H_0, u1,…,unu_1, \ldots, u_n are the order statistics of nn independent uniforms, so the law of A2A^2 depends on nn and not on F0F_0. For n=1n = 1, A2=−1−ln⁡u−ln⁡(1−u)A^2 = -1 - \ln u - \ln(1 - u) and P(A2≤a)=1−4e−(1+a)P(A^2 \le a) = \sqrt{1 - 4e^{-(1+a)}} for a≥ln⁡4−1=0.3863a \ge \ln 4 - 1 = 0.3863. For larger nn the exact law has no closed form. As n→∞n \to \infty, A2A^2 converges in law to A∞2=∑j≥1Zj2/(j(j+1))A^2_\infty = \sum_{j \ge 1} Z_j^2 / (j(j+1)) with independent standard normal ZjZ_j; its mean is 1. The page uses this limit, which is asymptotic, or a Monte Carlo estimate of the exact law.

P-values. The test is one-sided in A2A^2: large values speak against H0H_0, and no doubling rule applies. The asymptotic p-value is 1−ADINF(A2)1 - \mathrm{ADINF}(A^2), with ADINF\mathrm{ADINF} the distribution function of A∞2A^2_\infty. The Monte Carlo p-value is (1+c)/(1+b)(1 + c)/(1 + b), where cc is the number of bb simulated uniform samples of size nn whose statistic is at least the observed one.

Rejection rule and size. Reject at level α\alpha when p≤αp \le \alpha. The Monte Carlo p-value gives size at most α\alpha for every nn and bb. The percentiles of the limit law are 0.77420.7742 (50%), 1.9331.933 (90%), 2.49242.4924 (95%), 3.07753.0775 (97.5%) and 3.87813.8781 (99%). The limit test is close to the exact one already for small nn. In a Monte Carlo run with r=20000r = 20000 uniform samples per case, the simulated 95% points were 2.49732.4973, 2.53132.5313 and 2.54022.5402 for n=5n = 5, 1010 and 2020 (seeds 71, 72 and 73), and the limit test at 5%5\% rejected 5.04%5.04\%, 5.26%5.26\% and 5.275%5.275\% of the samples.

Sensitivity and power. The test is consistent against every fixed F≠F0F \ne F_0. The weight 1/(F0(1−F0))1/(F_0(1 - F_0)) makes it more sensitive than the Kolmogorov-Smirnov test to differences in the tails and in spread. In a Monte Carlo run against F0=N(0,1)F_0 = N(0, 1) with n=20n = 20, r=2000r = 2000 samples per case and α=0.05\alpha = 0.05, both tests on the same samples gave these rejection rates:

Data Seed Anderson-Darling Kolmogorov-Smirnov
N(0.5,1)N(0.5, 1) 62 0.6040.604 0.51550.5155
N(0,1.52)N(0, 1.5^2) 63 0.48050.4805 0.1750.175
Student tt with 3 degrees of freedom 65 0.32950.3295 0.0660.066
N(0,0.62)N(0, 0.6^2) 66 0.0680.068 0.0990.099

The last row shows a weak point: against a smaller spread, a sample of 20 points has no values far in the tails, and the test has almost no power.

The algorithm

  1. ANDERSON-DARLING(x_1, ..., x_n, F_0, method, b)
  2. 1u ← the values F_0(x_i), sorted
  3. 2if u_1 = 0 or u_n = 1 then return ∞, 0
  4. 3S ← sum over i = 1, ..., n of (2i - 1) · (ln u_i + ln(1 - u_(n+1-i)))
  5. 4A² ← -n - S/n
  6. 5if method = asymptotic then return A², 1 - ADINF(A²)
  7. 6c ← number of j = 1, ..., b where A² of a sorted sample of n uniforms ≥ A²
  8. 7return A², (1 + c)/(1 + b)

Lines L1 to L4 compute the statistic. The code uses log1p for ln⁡(1−u)\ln(1 - u), so values of uu near 0 keep their digits, and a compensated sum for SS. ADINF\mathrm{ADINF} evaluates the series of Anderson and Darling (1954) in the form of Marsaglia and Marsaglia (2004),

ADINF(z)=2πz∑j≥0(−1/2j)(4j+1)e−aj∫0∞exp⁡(z8(w2+1)−ajw2)dw,aj=(4j+1)2π28z.\mathrm{ADINF}(z) = \frac{\sqrt{2\pi}}{z} \sum_{j \ge 0} \binom{-1/2}{j} (4j + 1) e^{-a_j} \int_0^\infty \exp\left(\frac{z}{8(w^2 + 1)} - a_j w^2\right) dw, \qquad a_j = \frac{(4j+1)^2 \pi^2}{8z}.

The terms fall fast, and the code stops when a term is below 10−1710^{-17}. Each integral uses Simpson's rule on [0,W][0, W], where WW is chosen so that the integrand is below e−40e^{-40} beyond WW. Lines L6 and L7 simulate the exact null law with a seeded generator; this is a Monte Carlo test, and the p-value has a random part of standard deviation about p(1−p)/b\sqrt{p(1-p)/b}.

Example

The model is the exponential law with mean 1, F0(t)=1−e−tF_0(t) = 1 - e^{-t}, and the data are those of the Kolmogorov-Smirnov page: 0.42,0.06,1.95,0.88,0.13,3.10,0.27,0.71,0.09,0.350.42, 0.06, 1.95, 0.88, 0.13, 3.10, 0.27, 0.71, 0.09, 0.35. Line L1 gives

u=(0.0582,0.0861,0.1219,0.2366,0.2953,0.3430,0.5084,0.5852,0.8577,0.9550).u = (0.0582, 0.0861, 0.1219, 0.2366, 0.2953, 0.3430, 0.5084, 0.5852, 0.8577, 0.9550).

The first term of SS is 1⋅(ln⁡0.0582+ln⁡(1−0.9550))1 \cdot (\ln 0.0582 + \ln(1 - 0.9550)), which pairs the smallest and the largest value. In total S=−107.9589S = -107.9589, so A2=−10+10.7959=0.7959A^2 = -10 + 10.7959 = 0.7959. The limit law gives p=0.4840p = 0.4840. The Monte Carlo p-value with b=9999b = 9999 and seed 7 is 0.48130.4813. The Kolmogorov-Smirnov test gave p=0.4493p = 0.4493 on the same data, so both tests accept the model. Against the exponential law with mean 0.50.5, A2=0.8448A^2 = 0.8448 and p=0.4498p = 0.4498.

One observation. For n=1n = 1 the smallest value of A2A^2 is ln⁡4−1=0.3863\ln 4 - 1 = 0.3863, at u=1/2u = 1/2. The formula above gives P(A2≤1)=0.6772P(A^2 \le 1) = 0.6772 and P(A2≤2)=0.8949P(A^2 \le 2) = 0.8949.

Correctness

The proof is in proofs/correctness.md. On each interval between two sorted values, FnF_n is a constant cc, and the integrand is c2/t+(1−c)2/(1−t)−1c^2/t + (1 - c)^2/(1 - t) - 1 in the variable t=F0t = F_0. Integrating these pieces and collecting the logarithms by summation by parts gives the formula of lines L3 and L4. The probability integral transform shows that the null law of A2A^2 is that of uniform samples, so the simulated values in line L6 have the exact null law. The observed and the bb simulated values are then exchangeable, and the rank argument gives P(p≤α)≤αP(p \le \alpha) \le \alpha for the p-value of line L7. The asymptotic p-value relies on the limit law, which we cite.

Proof: The Anderson-Darling computing formula and the validity of its p-valuesfull

We use the pseudocode of the page. F0F_0 is continuous, u1≤⋯≤unu_1 \le \cdots \le u_n are the sorted values F0(xi)F_0(x_i) from line L1, and we set u0=0u_0 = 0, un+1=1u_{n+1} = 1 and ci=i/nc_i = i/n.

Claim 1 (the computing formula). If 0<u10 < u_1 and un<1u_n < 1, then

n∫(Fn(t)−F0(t))2F0(t)(1−F0(t)) dF0(t)=−n−1n∑i=1n(2i−1)[ln⁡ui+ln⁡(1−un+1−i)].n \int \frac{(F_n(t) - F_0(t))^2}{F_0(t)(1 - F_0(t))} \, dF_0(t) = -n - \frac{1}{n} \sum_{i=1}^{n} (2i - 1) \left[\ln u_i + \ln(1 - u_{n+1-i})\right].

If u1=0u_1 = 0 or un=1u_n = 1, the integral is infinite.

Proof. Substitute s=F0(t)s = F_0(t). For continuous F0F_0, ss is uniform under the measure dF0dF_0, and Fn(t)=G(s)F_n(t) = G(s), where GG is the empirical distribution function of the uiu_i. So the integral is n∫01(G(s)−s)2/(s(1−s)) dsn \int_0^1 (G(s) - s)^2 / (s(1 - s)) \, ds. On [ui,ui+1)[u_i, u_{i+1}), G=ciG = c_i, and

(c−s)2s(1−s)=c2s+(1−c)21−s−1,\frac{(c - s)^2}{s(1 - s)} = \frac{c^2}{s} + \frac{(1 - c)^2}{1 - s} - 1,

which one checks by putting the right side over the common denominator s(1−s)s(1-s): the numerator is c2(1−s)+(1−c)2s−s(1−s)=c2−2cs+s2c^2(1 - s) + (1 - c)^2 s - s(1 - s) = c^2 - 2cs + s^2. On the first piece c0=0c_0 = 0, and on the last piece cn=1c_n = 1, so the terms c2/sc^2/s near s=0s = 0 and (1−c)2/(1−s)(1-c)^2/(1-s) near s=1s = 1 do not appear there, and every piece has a finite integral when 0<u10 < u_1 and un<1u_n < 1. If u1=0u_1 = 0, the piece [u1,u2)[u_1, u_2) has c1>0c_1 > 0 and ∫0c12/s ds=∞\int_0 c_1^2/s \, ds = \infty; the case un=1u_n = 1 is the same by symmetry.

The terms −1-1 add up to −1-1, which gives −n-n after the factor nn. The terms c2/sc^2/s give, by summation by parts,

∑i=0nci2(ln⁡ui+1−ln⁡ui)=∑i=1n(ci−12−ci2)ln⁡ui=−1n2∑i=1n(2i−1)ln⁡ui,\sum_{i=0}^{n} c_i^2 (\ln u_{i+1} - \ln u_i) = \sum_{i=1}^{n} (c_{i-1}^2 - c_i^2) \ln u_i = -\frac{1}{n^2} \sum_{i=1}^{n} (2i - 1) \ln u_i,

because c0=0c_0 = 0 and ln⁡un+1=0\ln u_{n+1} = 0. The terms (1−c)2/(1−s)(1 - c)^2/(1 - s) give

∑i=0n(1−ci)2(ln⁡(1−ui)−ln⁡(1−ui+1))=∑i=1n((1−ci)2−(1−ci−1)2)ln⁡(1−ui)=−1n2∑i=1n(2(n−i)+1)ln⁡(1−ui),\sum_{i=0}^{n} (1 - c_i)^2 (\ln(1 - u_i) - \ln(1 - u_{i+1})) = \sum_{i=1}^{n} \left((1 - c_i)^2 - (1 - c_{i-1})^2\right) \ln(1 - u_i) = -\frac{1}{n^2} \sum_{i=1}^{n} (2(n - i) + 1) \ln(1 - u_i),

because ln⁡(1−u0)=0\ln(1 - u_0) = 0 and 1−cn=01 - c_n = 0. With j=n+1−ij = n + 1 - i, 2(n−i)+1=2j−12(n - i) + 1 = 2j - 1, so the last sum is −1n2∑j(2j−1)ln⁡(1−un+1−j)-\frac{1}{n^2} \sum_{j} (2j - 1) \ln(1 - u_{n+1-j}). Multiply by nn and add. Ties among the uiu_i give empty pieces and change nothing. □\square

So lines L2 to L4 return A2A^2, with A2=∞A^2 = \infty in line L2.

Claim 2 (distribution-free). Under H0H_0, (u1,…,un)(u_1, \ldots, u_n) has the law of the order statistics of nn independent uniforms on (0,1)(0, 1), so the law of A2A^2 depends only on nn.

Proof. For continuous F0F_0, P(F0(X)≤s)=sP(F_0(X) \le s) = s for s∈[0,1]s \in [0, 1], so each F0(Xi)F_0(X_i) is uniform, the values are independent, and sorting commutes with the nondecreasing map F0F_0. By Claim 1, A2A^2 is a function of these values. □\square

Claim 3 (the Monte Carlo p-value). Under H0H_0, the p-value p=(1+c)/(1+b)p = (1 + c)/(1 + b) of line L7 satisfies P(p≤α)≤αP(p \le \alpha) \le \alpha for every α∈(0,1)\alpha \in (0, 1) and every b≥1b \ge 1.

Proof. Let T0T_0 be the observed statistic and T1,…,TbT_1, \ldots, T_b the simulated ones. By Claim 2 the samples of line L6 have the null law of the data, so T0,…,TbT_0, \ldots, T_b are independent and identically distributed, hence exchangeable. Let Ri=#{j∈{0,…,b}:Tj≥Ti}R_i = \#\{j \in \{0, \ldots, b\} : T_j \ge T_i\}, so p=R0/(1+b)p = R_0/(1 + b). For an integer q≥1q \ge 1, let S={i:Ri≤q}S = \{i : R_i \le q\}. If SS is not empty, take i∗∈Si^* \in S with the smallest Ti∗T_{i^*}. Every i∈Si \in S has Ti≥Ti∗T_i \ge T_{i^*}, so ∣S∣≤Ri∗≤q\lvert S \rvert \le R_{i^*} \le q. By exchangeability, P(R0≤q)=1b+1E∣S∣≤qb+1P(R_0 \le q) = \frac{1}{b+1} E\lvert S \rvert \le \frac{q}{b+1}. With q=⌊α(1+b)⌋q = \lfloor \alpha (1 + b) \rfloor, P(p≤α)=P(R0≤q)≤q/(1+b)≤αP(p \le \alpha) = P(R_0 \le q) \le q/(1 + b) \le \alpha; if q=0q = 0 the event is empty. Ties among the TjT_j are allowed. □\square

The random part of the Monte Carlo p-value does not affect this bound: it holds for the joint law of the data and the simulation.

Claim 4 (the asymptotic p-value). As n→∞n \to \infty, A2A^2 converges in law to A∞2=∑j≥1Zj2/(j(j+1))A^2_\infty = \sum_{j \ge 1} Z_j^2/(j(j+1)), and the series for ADINF\mathrm{ADINF} is its distribution function. We cite both results from Anderson and Darling (1952, 1954) and do not prove them here. The p-value 1−ADINF(A2)1 - \mathrm{ADINF}(A^2) therefore has size that tends to α\alpha, and the page reports Monte Carlo sizes for small nn.

The numerical integrals. The integrand of the jj-th term is at most exp⁡(z/8−ajw2)\exp(z/8 - a_j w^2), because w2+1≥1w^2 + 1 \ge 1. The code takes W=(40+z/8)/ajW = \sqrt{(40 + z/8)/a_j}, so beyond WW the integrand is below e−40e^{-40} and falls like a Gaussian. Simpson's rule on [0,W][0, W] with 4000 steps has an error of order h4h^4 times the fourth derivative of a smooth integrand. The tests check the result against the published percentiles 2.49242.4924 and 3.87813.8781 to five digits, and check that the mean of the limit law is 1.

Cost. Line L1 sorts nn values. Lines L2 to L4 take O(n)O(n). Line L6 sorts bb samples of size nn. □\square

Complexity

Line L1 sorts in Θ(nlog⁡n)\Theta(n \log n) and lines L2 to L4 are linear, so the statistic costs Θ(nlog⁡n)\Theta(n \log n) time and Θ(n)\Theta(n) space. The asymptotic p-value costs a fixed amount of work for a given accuracy: a few terms of the series, each with a fixed number of Simpson steps. The Monte Carlo p-value sorts bb samples of size nn, which costs Θ(bnlog⁡n)\Theta(b n \log n) time and Θ(n)\Theta(n) extra space.

Properties

  • Distribution-free. For continuous F0F_0 the null law of A2A^2 depends only on nn.
  • Invariant. A2A^2 does not change under an increasing transformation applied to both the data and the model.
  • Tail weight. The variance of Fn(t)F_n(t) is F0(t)(1−F0(t))/nF_0(t)(1 - F_0(t))/n under H0H_0. Dividing by it gives every point the same null variance, so a gap in a tail counts as much as a gap of the same number of standard deviations in the middle.
  • Structure of the limit. The limit ∑jZj2/(j(j+1))\sum_j Z_j^2/(j(j+1)) comes from the Karhunen-Loeve expansion of the weighted Brownian bridge B(t)/t(1−t)B(t)/\sqrt{t(1-t)}, whose eigenfunctions are built from Legendre polynomials.
  • Parameters must be fixed in advance. In a Monte Carlo run with normal data, n=20n = 20, r=2000r = 2000 samples and seed 67, the test with the estimated mean and standard deviation and the limit 95% point rejected none of the samples.

Variants and improvements

  • Estimated parameters. For normal, exponential and other families, tables for A2A^2 with estimated parameters exist, often for a modified statistic, A2A^2 times a factor that depends on nn. A parametric bootstrap gives the null law for any model.
  • Finite-n correction. Marsaglia and Marsaglia (2004) give a correction to the limit law for finite nn.
  • Cramer-von Mises. The same integral without the weight gives the Cramer-von Mises statistic W2W^2, which is closer to the Kolmogorov-Smirnov test in where it looks.
  • k samples. Scholz and Stephens extended the statistic to compare several samples, with a permutation null law as for a permutation test.
  • Other tests. For normality the Shapiro-Wilk test is a strong alternative; for counts in classes, the chi-squared goodness-of-fit test.

When to use it

Use it to test a fully specified continuous model when differences in the tails matter, as in risk models, reliability, or before a method that relies on the tails of a model. With estimated parameters, use the matching table or a parametric bootstrap. Look at a Q-Q plot as well, to see where the data and the model differ.

Pitfalls

  • Estimated parameters. Using the standard table after estimating the parameters makes the test far too conservative; in the run above it never rejected at 5%5\%.
  • Values at the edge of the support. If F0(xi)F_0(x_i) is 0 or 1, as for a value outside the support of the model, A2A^2 is infinite. In floating point a value far in a tail can round F0F_0 to 1; compute 1−F01 - F_0 directly from the survival function of the model when possible.
  • Discrete data. Ties and jumps in F0F_0 change the null law; the continuous tables do not apply.
  • Little power against a smaller spread. With n=20n = 20 the test rejected N(0,0.62)N(0, 0.6^2) against N(0,1)N(0, 1) in only 6.8%6.8\% of samples.
  • Old tables. Older tables list 3.8573.857 for the 1% point of the limit law. The series gives ADINF(3.857)=0.98976\mathrm{ADINF}(3.857) = 0.98976, and the 99% point is 3.87813.8781 (Marsaglia and Marsaglia 2004).

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.

ad_core.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/anderson-darling-test/. The authors are listed in prov/7ZCNKW.jsonl.

import math
import random
from typing import Callable


def ad_statistic_u(u: list[float]) -> float:
    """A^2 from the sorted values u_1 <= ... <= u_n of F_0 at the data."""
    n = len(u)
    if u[0] <= 0.0 or u[-1] >= 1.0:  # @line L2
        return math.inf
    s = math.fsum((2 * i - 1) * (math.log(u[i - 1]) + math.log1p(-u[n - i]))
                  for i in range(1, n + 1))  # @line L3
    return -n - s / n  # @line L4


def ad_statistic(x: list[float], cdf: Callable[[float], float]) -> float:
    """The Anderson-Darling statistic A^2 of the sample x against the CDF F_0."""
    return ad_statistic_u(sorted(cdf(v) for v in x))  # @line L1


def adinf_cdf(z: float, steps: int = 4000) -> float:
    """P(A^2_inf <= z) for the limit law A^2_inf = sum_j Z_j^2 / (j (j + 1)).

    Uses the series of Anderson and Darling (1954), in the form
    (sqrt(2 pi)/z) sum_j C(-1/2, j) (4j + 1) exp(-a_j) I_j with a_j = (4j + 1)^2 pi^2 / (8 z)
    and I_j = integral_0^inf exp(z / (8 (w^2 + 1)) - a_j w^2) dw, each I_j by Simpson's
    rule on [0, W] where the integrand is below exp(-40) beyond W.
    """
    if z <= 0.0:
        return 0.0
    total, coef, j = 0.0, 1.0, 0
    while True:
        a = (4 * j + 1) ** 2 * math.pi**2 / (8 * z)
        width = math.sqrt((40.0 + z / 8.0) / a)
        h = width / steps
        acc = 0.0
        for i in range(steps + 1):
            w = i * h
            f = math.exp(z / (8.0 * (w * w + 1.0)) - a * w * w)
            acc += f if i in (0, steps) else (4.0 * f if i % 2 else 2.0 * f)
        term = coef * (4 * j + 1) * math.exp(-a) * acc * h / 3.0
        total += term
        if abs(term) < 1e-17 and j > 2:
            break
        j += 1
        coef *= -(2 * j - 1) / (2 * j)
    return min(1.0, max(0.0, math.sqrt(2 * math.pi) / z * total))


def ad_test(
    x: list[float],
    cdf: Callable[[float], float],
    method: str = "asymptotic",
    b: int = 9999,
    rng: random.Random | None = None,
) -> tuple[float, float]:
    """Anderson-Darling test of H0: the data have the continuous, fully specified CDF F_0.

    Returns (A^2, p). method "asymptotic" uses the limit law; method
    "monte-carlo" simulates b samples of n uniforms (the exact null law of
    A^2 for every continuous F_0) and returns (1 + count) / (1 + b), where
    count is the number of simulated values at least the observed one.
    """
    if not x:
        raise ValueError("need at least one observation")
    a2 = ad_statistic(x, cdf)
    if math.isinf(a2):
        return a2, 0.0
    if method == "asymptotic":  # @line L5
        return a2, max(0.0, 1.0 - adinf_cdf(a2))
    if method != "monte-carlo":
        raise ValueError("unknown method")
    if rng is None:
        raise ValueError("pass rng = random.Random(seed) for the Monte Carlo p-value")
    n = len(x)
    count = 0
    for _ in range(b):  # @line L6
        sim = sorted(rng.random() for _ in range(n))
        if ad_statistic_u(sim) >= a2:
            count += 1
    return a2, (1 + count) / (1 + b)  # @line L7
anderson_darling_test.py 8 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/anderson-darling-test/. The authors are listed in prov/7ZCNKW.jsonl.
"""Entry point named after the slug. The code lives in ad_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""

from ad_core import ad_statistic, ad_statistic_u, ad_test, adinf_cdf

__all__ = ["ad_statistic", "ad_statistic_u", "ad_test", "adinf_cdf"]
test_anderson_darling_test.py 110 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/anderson-darling-test/. The authors are listed in prov/7ZCNKW.jsonl.

import math
import random

import pytest

from anderson_darling_test import ad_statistic, ad_statistic_u, ad_test, adinf_cdf

X = [0.42, 0.06, 1.95, 0.88, 0.13, 3.10, 0.27, 0.71, 0.09, 0.35]


def exp_cdf(v: float) -> float:
    return 1.0 - math.exp(-v) if v > 0 else 0.0


def a2_by_integration(u: list[float]) -> float:
    """n times the integral of (F_n(t) - t)^2 / (t (1 - t)) over (0, 1), piece by piece.

    On a piece where F_n = c the integrand is c^2/t + (1 - c)^2/(1 - t) - 1, which has
    a closed-form integral. This uses the definition, not the sum of the code."""
    n = len(u)
    pts = [0.0] + sorted(u) + [1.0]
    total = 0.0
    for i in range(n + 1):
        a, b, c = pts[i], pts[i + 1], i / n
        part = -(b - a)
        if c > 0:
            part += c * c * (math.log(b) - math.log(a))
        if c < 1:
            part += (1 - c) ** 2 * (math.log1p(-a) - math.log1p(-b))
        total += part
    return n * total


def test_page_example() -> None:
    assert ad_statistic(X, exp_cdf) == pytest.approx(0.79588947, abs=1e-7)
    assert ad_test(X, exp_cdf)[1] == pytest.approx(0.48400265, abs=1e-6)
    assert ad_test(X, exp_cdf, "monte-carlo", b=9999, rng=random.Random(7))[1] == pytest.approx(0.4813, abs=1e-12)


def test_statistic_against_the_integral() -> None:
    rng = random.Random(1)
    for _ in range(300):
        u = [rng.random() for _ in range(rng.randint(1, 15))]
        assert ad_statistic_u(sorted(u)) == pytest.approx(a2_by_integration(u), rel=1e-9, abs=1e-12)


def test_one_observation_law() -> None:
    # n = 1: A^2 = -1 - ln u - ln(1 - u), so P(A^2 <= a) = sqrt(1 - 4 e^{-(1 + a)}) for a >= ln 4 - 1.
    grid = 200000
    values = [ad_statistic_u([(i + 0.5) / grid]) for i in range(grid)]
    for a in (0.5, 1.0, 2.0, 3.0):
        share = sum(v <= a for v in values) / grid
        assert share == pytest.approx(math.sqrt(1 - 4 * math.exp(-(1 + a))), abs=1e-4)
    assert min(values) == pytest.approx(math.log(4) - 1, abs=1e-9)


def test_limit_law_percentiles() -> None:
    # Percentiles of the limit law (Marsaglia and Marsaglia 2004): 2.4924 and 3.8781.
    assert adinf_cdf(2.4924) == pytest.approx(0.95, abs=1e-5)
    assert adinf_cdf(3.8781) == pytest.approx(0.99, abs=1e-5)
    assert adinf_cdf(3.857) == pytest.approx(0.98976, abs=1e-5)  # the 1954 value is a bit low
    assert adinf_cdf(0.0) == 0.0
    assert adinf_cdf(40.0) == pytest.approx(1.0, abs=1e-12)


def test_limit_law_mean_is_one() -> None:
    # The limit is sum_j Z_j^2 / (j (j + 1)), with mean sum_j 1 / (j (j + 1)) = 1.
    h, top = 0.04, 30.0
    steps = int(top / h)
    acc = 0.0
    for i in range(steps + 1):
        f = 1.0 - adinf_cdf(i * h, steps=400)
        acc += f if i in (0, steps) else (4.0 * f if i % 2 else 2.0 * f)
    assert acc * h / 3.0 == pytest.approx(1.0, abs=2e-3)


def test_monte_carlo_p_value_is_valid() -> None:
    rng = random.Random(3)
    r, alpha = 400, 0.1
    hits = 0
    for _ in range(r):
        x = [rng.random() for _ in range(8)]
        hits += ad_test(x, lambda v: v, "monte-carlo", b=99, rng=rng)[1] <= alpha
    assert hits / r <= alpha + 4 * math.sqrt(alpha * (1 - alpha) / r)


def test_asymptotic_size_monte_carlo() -> None:
    rng = random.Random(4)
    r, alpha = 4000, 0.05
    crit = 2.4924  # the 95% point of the limit law
    hits = sum(ad_statistic_u(sorted(rng.random() for _ in range(10))) >= crit for _ in range(r))
    assert abs(hits / r - alpha) <= 4 * math.sqrt(alpha * (1 - alpha) / r)


def test_invariance_under_monotone_maps() -> None:
    y = [math.log(v) for v in X]  # if X has CDF F_0, log X has CDF F_0(e^t)
    assert ad_statistic(y, lambda t: exp_cdf(math.exp(t))) == pytest.approx(ad_statistic(X, exp_cdf), rel=1e-12)


def test_edges() -> None:
    with pytest.raises(ValueError):
        ad_test([], exp_cdf)
    with pytest.raises(ValueError):
        ad_test(X, exp_cdf, "monte-carlo")
    with pytest.raises(ValueError):
        ad_test(X, exp_cdf, "exact")
    assert ad_test([-1.0, 0.5], exp_cdf) == (math.inf, 0.0)  # a point where F_0 = 0

History

Theodore Anderson and Donald Darling (1952) studied a family of distances between the empirical and the model distribution function, weighted by a function of F0F_0, and found their limit laws through the eigenvalues of the weighted Brownian bridge. In a short paper in 1954 they singled out the weight 1/(F0(1−F0))1/(F_0(1 - F_0)), gave the computing formula with logarithms, and gave a table of the limit law from a series. Stephens later gave modified statistics and tables for the case of estimated parameters. Marsaglia and Marsaglia (2004) gave an accurate program for the limit law and a correction for finite samples.

References

  1. T. W. Anderson and D. A. Darling, Asymptotic theory of certain goodness of fit criteria based on stochastic processes, Annals of Mathematical Statistics 23(2), 1952, pp. 193 to 212 (the weighted criteria, the weight 1/(F(1 - F)), and the limit law as a weighted sum of chi-square variables)
  2. T. W. Anderson and D. A. Darling, A test of goodness of fit, Journal of the American Statistical Association 49, 1954, pages 765 to 769, the computing formula for A^2 from the sorted values and the series for the limit law with its percentage points
  3. George Marsaglia and John Marsaglia, Evaluating the Anderson-Darling distribution, Journal of Statistical Software 9(2), 2004, the accurate evaluation of the limit law and its percentiles, and a correction for finite n

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