Algorithm Search⌘K

Algorithmadvanced

Hodges-Lehmann estimator

Also called Hodges-Lehmann shift estimator, median of Walsh averages.

Estimates a location as the median of all pairwise averages, or a shift as the median of all pairwise differences. It inverts the Wilcoxon test and breaks down at 29 percent.

Time
O(n^3) worstΘ(n log n) average · best
Space
Θ(n) extra
Where
N = the number of Walsh averages or differences; n = the sample size (m + n for two samples)
Properties
randomizedexact in exact arithmeticnot in placeofflinerandomized
Origin
Joseph L. Hodges Jr., Erich L. Lehmann, 1963

The Hodges-Lehmann estimator of location is the median of the n(n+1)/2n(n+1)/2 Walsh averages (xi+xj)/2(x_i + x_j)/2 with i≤ji \le j. The two-sample version estimates a shift as the median of the mnmn differences yj−xiy_j - x_i. Both come from rank tests: they are the values of the parameter at which the Wilcoxon signed-rank test or the Mann-Whitney test is most balanced. The estimator has 95.5 percent efficiency at the normal law and breaks down at 1−1/2≈29.31 - 1/\sqrt2 \approx 29.3 percent contamination. Listing all averages costs Θ(n2)\Theta(n^2), but a selection in a sorted matrix finds the median in expected Θ(nlog⁡n)\Theta(n \log n) time.

In plain words

Take every pair of values in the sample, and also each value with itself, and write down the midpoint of the pair. The estimate is the middle one of all these midpoints. A single wild value spoils only the midpoints that use it, and those are a small share. So the result stays near the bulk of the data. It is close to the mean when the data are clean, and close to the median when they are not.

To find the middle midpoint fast, sort the sample first. Then the midpoints form a table in which each row and each column increases. You can count how many entries of such a table are below a guess in one sweep, and that lets you close in on the middle entry without listing all of them.

The problem

One sample. Input x1,…,xnx_1, \ldots, x_n. Output

θ^HL=med⁡{xi+xj2:1≤i≤j≤n},\hat\theta_{HL} = \operatorname{med}\Big\{\tfrac{x_i + x_j}{2} : 1 \le i \le j \le n\Big\},

the median of N=n(n+1)/2N = n(n+1)/2 numbers, with the average of the two middle values when NN is even.

Two samples. Input x1,…,xmx_1, \ldots, x_m and y1,…,yny_1, \ldots, y_n. Output Δ^=med⁡{yj−xi}\hat\Delta = \operatorname{med}\{y_j - x_i\} over the N=mnN = mn pairs.

Both are the median of a set {ai+bj:j≥Li}\{a_i + b_j : j \ge L_i\} with aa and bb sorted ascending and LL nondecreasing. For one sample, $a = b = $ sorted xx and Li=iL_i = i; the answer is half the median sum. For two samples, $a = $ sorted (−x)(-x), $b = $ sorted yy and Li=0L_i = 0. Each row ii is nondecreasing in jj, and each column is nondecreasing in ii. This is a sorted matrix.

The algorithm

SELECT-SUM finds the kk-th smallest cell. It keeps, for each row, an active column range [loi,hii][lo_i, hi_i]. Every cell left of the range is known to be at most the answer, and every cell right of it is known to be at least the answer. Each round takes a random active cell as pivot vv, counts the cells ≤v\le v and <v< v in the whole matrix, and moves the bounds past vv.

  1. SELECT-SUM(a, b, L, k) ▷ k-th smallest of a[i] + b[j], j ≥ L[i]
  2. 1for each row i: lo[i] ← L[i], hi[i] ← n − 1
  3. 2loop
  4. 3W ← Σ max(0, hi[i] − lo[i] + 1) ▷ active cells
  5. 4pick an active cell (i, j) uniformly at random; v ← a[i] + b[j]
  6. 5(c≤, le[ ]) ← COUNT(v, ≤); (c<, lt[ ]) ← COUNT(v, <)
  7. 6if c< ≥ k then for each i: hi[i] ← min(hi[i], lt[i])
  8. 7else if c≤ ≥ k then return v
  9. 8else for each i: lo[i] ← max(lo[i], le[i] + 1)
  10. HODGES-LEHMANN(x)
  11. 9sort x; N ← n(n + 1)/2; k ← ⌈N/2⌉
  12. 10s1 ← SELECT-SUM(x, x, (0, 1, ..., n − 1), k)
  13. 11s2 ← s1 if N is odd or COUNT(s1, ≤) ≥ k + 1, else the least cell > s1
  14. 12return (s1 + s2)/4
  15. COUNT(v, ≤) ▷ staircase walk over the rows
  16. 13j ← n − 1, c ← 0; for i ← 0 to m − 1 do
  17. 14while j ≥ 0 and a[i] + b[j] > v do j ← j − 1
  18. 15le[i] ← j ▷ last column with a cell ≤ v
  19. 16c ← c + max(0, j − L[i] + 1)

COUNT(v,<)(v, <) is the same walk with ≥\ge in line L14. The walk is correct because the last column with ai+bj≤va_i + b_j \le v can only move left as ii grows. The least cell greater than s1s_1 in line L11 is the minimum over the rows of the first cell right of le[i]le[i], one more walk.

Example

Take x=(3,7,1,20,4)x = (3, 7, 1, 20, 4), sorted (1,3,4,7,20)(1, 3, 4, 7, 20). The matrix of sums xi+xjx_i + x_j, j≥ij \ge i:

row sums
i=0i = 0 (x=1x = 1) 2, 4, 5, 8, 21
i=1i = 1 (x=3x = 3) 6, 7, 10, 23
i=2i = 2 (x=4x = 4) 8, 11, 24
i=3i = 3 (x=7x = 7) 14, 27
i=4i = 4 (x=20x = 20) 40

N=15N = 15 is odd, so k=8k = 8. One run of SELECT-SUM:

round WW pivot vv c<c_< c≤c_\le action
1 15 2 0 1 raise lolo: the cell 2 is out
2 14 11 8 9 lower hihi: cells ≥11\ge 11 are out
3 7 6 3 4 raise lolo: cells ≤6\le 6 are out
4 4 8 5 7 raise lolo: cells ≤8\le 8 are out
5 1 10 7 8 c<<8≤c≤c_< < 8 \le c_\le: return 10

So the median sum is 10 and θ^HL=5\hat\theta_{HL} = 5. The sorted sums are (2,4,5,6,7,8,8,10,11,14,21,23,24,27,40)(2, 4, 5, 6, 7, 8, 8, 10, 11, 14, 21, 23, 24, 27, 40), and the 8th is 10, as found. For comparison, the mean is 7, pulled up by the value 20, and the median is 4.

Correctness

The invariant of the loop: every cell left of the active range of its row is less than the answer v∗v^*, and every cell right of it is greater than v∗v^*. So every cell with value v∗v^* is active, and the active range is never empty. A round with c<≥kc_< \ge k shows that v∗<vv^* < v, so every cell ≥v\ge v is greater than v∗v^* and can leave on the right. A round with c≤<kc_\le < k shows v∗>vv^* > v, so every cell ≤v\le v can leave on the left. Otherwise c<<k≤c≤c_< < k \le c_\le, which means that the kk-th smallest cell equals vv. Each round removes at least the pivot, so the loop ends. The full proof is in proofs/correctness.md.

Proof: SELECT-SUM returns the k-th smallest cell, and HODGES-LEHMANN the median of the Walsh averagesfull

Setting. a0≤⋯≤am−1a_0 \le \cdots \le a_{m-1} and b0≤⋯≤bn−1b_0 \le \cdots \le b_{n-1} are sorted, and L0≤L1≤⋯≤Lm−1L_0 \le L_1 \le \cdots \le L_{m-1}. The cells are the pairs (i,j)(i, j) with Li≤j≤n−1L_i \le j \le n - 1, and the value of a cell is ai+bja_i + b_j. There are NN cells, and 1≤k≤N1 \le k \le N. Let s1≤⋯≤sNs_1 \le \cdots \le s_N be the sorted cell values (with multiplicity) and v∗=skv^* = s_k. For a value vv, c≤(v)c_\le(v) and c<(v)c_<(v) are the numbers of cells with value ≤v\le v and <v< v.

Lemma 0. A value vv equals sks_k if and only if

c<(v)<k≤c≤(v).(1)c_<(v) < k \le c_\le(v). \tag{1}

Proof. If v=skv = s_k, the cells <v< v are among s1,…,sk−1s_1, \ldots, s_{k-1}, so c<(v)≤k−1c_<(v) \le k - 1, and s1,…,sks_1, \ldots, s_k are ≤v\le v, so c≤(v)≥kc_\le(v) \ge k. Conversely, if (1) holds, then at least kk cells are ≤v\le v, so sk≤vs_k \le v; and fewer than kk cells are <v< v, so sk≮vs_k \not< v. Thus sk=vs_k = v. □\square

Lemma 1 (COUNT). For each row ii, line L15 sets le[i]=pile[i] = p_i, where pi=max⁡{j:ai+bj≤v}p_i = \max\{j : a_i + b_j \le v\} (and pi=−1p_i = -1 if there is no such jj). Line L16 adds the number of cells ≤v\le v in row ii. So COUNT returns c≤(v)c_\le(v).

Proof. If ai+1+bj≤va_{i+1} + b_j \le v, then ai+bj≤va_i + b_j \le v because ai≤ai+1a_i \le a_{i+1}. So pi+1≤pip_{i+1} \le p_i. We show by induction that j≥pij \ge p_i when row ii starts. For i=0i = 0, j=n−1≥p0j = n - 1 \ge p_0. For row i+1i + 1, jj starts at the end value of row ii, which is pi≥pi+1p_i \ge p_{i+1}. In row ii, line L14 lowers jj while ai+bj>va_i + b_j > v. Every column j>pij > p_i has ai+bj>va_i + b_j > v, because bb is sorted, and column pip_i has ai+bpi≤va_i + b_{p_i} \le v. So the loop stops at j=pij = p_i. The cells ≤v\le v of row ii are the columns Li,…,piL_i, \ldots, p_i, and there are max⁡(0,pi−Li+1)\max(0, p_i - L_i + 1) of them. This is the value that line L16 adds. The strict count is the same proof with << in place of ≤\le. □\square

The index jj only moves down, so one COUNT takes O(m+n)O(m + n) steps.

The parts of a row. In row ii, the columns Li≤j<loiL_i \le j < lo_i are the left part, the columns loi≤j≤hiilo_i \le j \le hi_i are the active part, and the columns hii<j≤n−1hi_i < j \le n - 1 are the right part. WW is the number of active cells.

Invariant. At the start of each round of the loop of line L2:

  • (I) every left cell has value <v∗< v^*, and every right cell has value >v∗> v^*.

Line L1 makes all left and right parts empty, so (I) holds before the first round.

Lemma 2. If (I) holds, then every cell with value v∗v^* is active, and W≥1W \ge 1.

Proof. A cell with value v∗v^* is neither <v∗< v^* nor >v∗> v^*, so by (I) it is not left and not right. There is at least one such cell, sks_k. □\square

Lemma 3 (one round). Assume (I) at the start of a round with pivot vv. Then the round returns v∗v^*, or (I) holds at the end of the round and WW is at least 1 smaller.

Proof. By Lemma 2, line L4 can pick an active cell, and vv is its value. By Lemma 1, line L5 computes c≤(v)c_\le(v), c<(v)c_<(v), and the last columns le[i]le[i] and lt[i]lt[i] whose cells are ≤v\le v and <v< v.

Case c<(v)≥kc_<(v) \ge k (line L6). If v≤v∗v \le v^*, then c<(v∗)≥c<(v)≥kc_<(v^*) \ge c_<(v) \ge k, which is false by Lemma 0. So v∗<vv^* < v. Line L6 sets hii←min⁡(hii,lti)hi_i \leftarrow \min(hi_i, lt_i), and the left parts do not change. A cell that joins the right part of row ii has a column >lti> lt_i, so its value is ≥v>v∗\ge v > v^*. So (I) holds. The pivot has value vv, which is not <v< v, so its column is >lti> lt_i, and it leaves the active part.

Case c<(v)<k≤c≤(v)c_<(v) < k \le c_\le(v) (line L7). By Lemma 0, v=v∗v = v^*, and the round returns v∗v^*.

Case c≤(v)<kc_\le(v) < k (line L8). If v≥v∗v \ge v^*, then c≤(v)≥c≤(v∗)≥kc_\le(v) \ge c_\le(v^*) \ge k, which is false by Lemma 0. So v∗>vv^* > v. Line L8 sets loi←max⁡(loi,lei+1)lo_i \leftarrow \max(lo_i, le_i + 1), and the right parts do not change. A cell that joins the left part of row ii has a column ≤lei\le le_i, so its value is ≤v<v∗\le v < v^*. So (I) holds. The pivot has value v≤vv \le v, so its column is ≤lei\le le_i, and it leaves the active part.

In the first and third cases the active parts only shrink, and the pivot leaves them, so WW drops by at least 1. □\square

Theorem 1. SELECT-SUM(a,b,L,k)(a, b, L, k) returns sks_k, the kk-th smallest cell value.

Proof. By Lemma 3 and induction, (I) holds at the start of every round. W≤NW \le N at the start, every round that does not return lowers WW by at least 1, and W≥1W \ge 1 at every start by Lemma 2. So the loop returns after at most NN rounds. It returns only at line L7, and there the value is v∗v^* by Lemma 3. □\square

Theorem 2. HODGES-LEHMANN(x)(x) returns the median of the Walsh averages (xi+xj)/2(x_i + x_j)/2, i≤ji \le j.

Proof. After line L9, xx is sorted. Take a=b=xa = b = x and Li=iL_i = i. The cells are the pairs i≤ji \le j of sorted positions, and each Walsh average is half the value of exactly one cell. So the median of the Walsh averages is half the median of the cell values. Line L9 sets k=⌈N/2⌉k = \lceil N/2 \rceil, and by Theorem 1 line L10 gives s1=sks_1 = s_k.

If NN is odd, the median of the cell values is sks_k, line L11 sets s2=sks_2 = s_k, and line L12 returns (sk+sk)/4=sk/2(s_k + s_k)/4 = s_k/2.

If NN is even, the median of the cell values is (sk+sk+1)/2(s_k + s_{k+1})/2. If c≤(sk)≥k+1c_\le(s_k) \ge k + 1, then sk+1≤sks_{k+1} \le s_k, so sk+1=sks_{k+1} = s_k. Else c≤(sk)=kc_\le(s_k) = k by Lemma 0, so sk+1s_{k+1} is the least cell value greater than sks_k. In row ii the cells greater than sks_k are the columns from max⁡(lei+1,Li)\max(le_i + 1, L_i) to n−1n - 1, and the least of them is the first one, because bb is sorted. The minimum of these first cells over all rows is sk+1s_{k+1}, which line L11 takes. In both cases line L12 returns (sk+sk+1)/4(s_k + s_{k+1})/4, which is half the median of the cell values. □\square

The two-sample estimator uses the same proof with aa the sorted values −xi-x_i, bb the sorted yy, and Li=0L_i = 0. Then the cells are all the pairs, with the values yj−xiy_j - x_i.

Expected number of rounds. Put the active cells in order by value, with ties broken by position. The pivot is uniform among the WW active cells. Let rr be its rank. In the case of line L6, every active cell with value ≥v\ge v leaves, and there are at least W−r+1W - r + 1 of them. In the case of line L8, every active cell with value ≤v\le v leaves, and there are at least rr of them. If W/4≤r≤3W/4+1W/4 \le r \le 3W/4 + 1, at least W/4W/4 cells leave in both cases. This occurs with probability at least 1/21/2. So in expectation at most 2 rounds make WW drop by the factor 3/43/4, and the expected number of rounds is at most 2log⁡4/3N+O(1)2 \log_{4/3} N + O(1). With N≤n2N \le n^2, this is O(log⁡n)O(\log n) rounds of cost O(m+n)O(m + n) each.

Complexity

  • One round costs O(m+n)O(m + n): line L3 and the random pick scan the rows, and each COUNT is one staircase walk.
  • Number of rounds. The pivot is uniform among the WW active cells. With probability at least 1/21/2 its rank among them is in the middle half, and then at least W/4W/4 cells leave. So the expected number of rounds is O(log⁡N)O(\log N), and the expected time of SELECT-SUM is O((m+n)log⁡N)=O(nlog⁡n)O((m + n) \log N) = O(n \log n). The worst case removes one cell per round: O(N(m+n))=O(n3)O(N (m + n)) = O(n^3) for this version. It has probability close to zero, and the deterministic methods below avoid it.
  • Total. The sort in line L9 takes Θ(nlog⁡n)\Theta(n \log n). So the expected time is Θ(nlog⁡n)\Theta(n \log n), with Θ(n)\Theta(n) extra space for the bounds.
  • Naive method. List all NN averages and select their median with quickselect: expected Θ(n2)\Theta(n^2) time and Θ(n2)\Theta(n^2) space. With a sort it is Θ(n2log⁡n)\Theta(n^2 \log n).
  • Deterministic. Johnson and Mizoguchi (1978) select in X+YX + Y in O(nlog⁡n)O(n \log n) worst-case time, and Frederickson and Johnson select in a sorted matrix in O(n)O(n) after the sort; see sorted matrix selection.

In exact arithmetic the result is exact: the implementation works with the integer or rational sums and halves once at the end.

Properties

  • Location and scale equivariant. θ^HL(ax+b)=a θ^HL(x)+b\hat\theta_{HL}(ax + b) = a\,\hat\theta_{HL}(x) + b, also for a<0a < 0, because the set of Walsh averages maps in the same way.
  • Link to the signed-rank test (Tukey's identity). For differences di=xi−θd_i = x_i - \theta with no zeros and distinct ∣di∣|d_i|, the signed-rank statistic is W+=#{i≤j:di+dj>0}W^+ = \#\{i \le j : d_i + d_j > 0\}. Proof. A pair with di+dj>0d_i + d_j > 0 has its member of larger ∣⋅∣|\cdot| positive. Assign each such pair to that member. A positive did_i with rank RiR_i of ∣di∣|d_i| gets exactly the RiR_i pairs (i,j)(i, j) with ∣dj∣≤∣di∣|d_j| \le |d_i|, each with a positive sum. So the count is ∑di>0Ri=W+\sum_{d_i > 0} R_i = W^+. □\square So W+(θ)W^+(\theta) counts the Walsh averages above θ\theta, and θ^HL\hat\theta_{HL} is the θ\theta where W+W^+ crosses its null mean N/2N/2. Inverting the test the same way gives a confidence interval between two order statistics of the Walsh averages.
  • Breakdown point (proved here). Let N=n(n+1)/2N = n(n+1)/2 and
m∗=min⁡{m:N−(n−m)(n−m+1)2≥⌈N/2⌉}.m^* = \min\Big\{ m : N - \tfrac{(n-m)(n-m+1)}{2} \ge \lceil N/2 \rceil \Big\}.

Then the finite-sample breakdown point is m∗/nm^*/n, and it tends to 1−1/2≈0.29291 - 1/\sqrt2 \approx 0.2929.

Proof. Replace mm points. The Walsh averages of two clean points, C=(n−m)(n−m+1)/2C = (n-m)(n-m+1)/2 of them, lie in the range [c−,c+][c_-, c_+] of the clean points. The other N−CN - C averages use a replaced point. If N−C<⌈N/2⌉N - C < \lceil N/2 \rceil, at most ⌈N/2⌉−1\lceil N/2 \rceil - 1 averages are outside [c−,c+][c_-, c_+]. For odd N=2r+1N = 2r + 1 that is at most rr, so the (r+1)(r+1)-th smallest average has at most rr values below it and above it that could leave the range, and it stays in [c−,c+][c_-, c_+]. For even N=2rN = 2r at most r−1r - 1 averages leave, so the rr-th and (r+1)(r+1)-th smallest stay in the range, and so does their mean. If N−C≥⌈N/2⌉N - C \ge \lceil N/2 \rceil, move the mm points to tt. Each average with a replaced point is at least (c−+t)/2(c_- + t)/2, and there are at least ⌈N/2⌉\lceil N/2 \rceil of them, so the upper middle average, and with it the median, tends to infinity. For the limit, m∗m^* is the least mm with (n−m)(n−m+1)≤2⌊N/2⌋(n-m)(n-m+1) \le 2\lfloor N/2 \rfloor, and 2⌊N/2⌋=n2/2+O(n)2\lfloor N/2 \rfloor = n^2/2 + O(n). So (1−m∗/n)2→1/2(1 - m^*/n)^2 \to 1/2, which gives m∗/n→1−1/2m^*/n \to 1 - 1/\sqrt 2. □\square

For n=5,10,20,100n = 5, 10, 20, 100 the values of m∗m^* are 2,4,6,302, 4, 6, 30. In the contamination model the same number appears: a Walsh average of two independent draws is clean with probability (1−ε)2(1-\varepsilon)^2, and the median of their law stays bounded while (1−ε)2>1/2(1-\varepsilon)^2 > 1/2.

  • Efficiency (cited). At a law FF symmetric about θ\theta with density ff, the influence function is (F(x)−1/2)/∫f2(F(x) - 1/2)/\int f^2 and the asymptotic variance is 1/(12(∫f2)2)1/(12 (\int f^2)^2). At the normal this gives π/3\pi/3, so the efficiency relative to the mean is 3/π≈0.9553/\pi \approx 0.955. Hodges and Lehmann (1956) showed that the efficiency is at least 108/125=0.864108/125 = 0.864 for every symmetric FF, and it can be infinite for heavy tails.
  • Assumptions. The one-sample estimator targets the center of a symmetric law. For a skewed law it estimates the pseudo-median, the median of the law of (X1+X2)/2(X_1 + X_2)/2, which is neither the mean nor the median.

Variants and improvements

  • Two-sample shift. The median of yj−xiy_j - x_i; see above. It inverts the Mann-Whitney test, and it estimates the shift Δ\Delta in the model G(x)=F(x−Δ)G(x) = F(x - \Delta).
  • Excluding i=ji = j. Some texts use only i<ji < j. The two versions differ by O(1/n)O(1/n) and have the same asymptotics.
  • Deterministic selection. Use the Johnson and Mizoguchi or the Frederickson and Johnson selection for a guaranteed O(nlog⁡n)O(n \log n).
  • Confidence intervals. The interval with the CC-th smallest and CC-th largest Walsh average, with CC from the null law of W+W^+, has exact coverage under symmetry. The same selection routine computes both ends.
  • Regression. The Theil-Sen estimator is the analogue for a slope: the median of the pairwise slopes, with the same breakdown point 1−1/21 - 1/\sqrt2.

When to use it

Use it for a location or a shift when the law is roughly symmetric and may have heavy tails. It is the natural point estimate to report next to a Wilcoxon or Mann-Whitney test. It is more efficient than the median at the normal (0.955 against 0.637) and more robust than the mean. Use the median when more than about 29 percent of the data can be bad, and the Huber M-estimator when you also want a smooth estimating equation for a regression.

Pitfalls

  • Listing all averages. For n=105n = 10^5 there are 5×1095 \times 10^9 Walsh averages. The naive method runs out of memory; the selection method does not.
  • Even NN. When NN is even, the median is the mean of two cells. The second one is not always equal to the first. Find it with one more count, as in line L11.
  • Halving early. Halving each sum in floating point before the comparison is harmless, but halving integers with integer division is not. Select on the sums and halve once.
  • The breakdown point is not 1/2. About 29 percent bad data is enough to carry the estimate away.
  • Ties. Ties in the data are harmless for the estimate, but the exact null law of the test with ties needs the tie-corrected version.

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.

hodges_lehmann_estimator.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hodges-lehmann-estimator/. The authors are listed in prov/WF6BA7.jsonl.

import random
from fractions import Fraction


def count_le(a, b, start, v, strict=False):
    """Count the cells a[i] + b[j] <= v (or < v when strict) with j >= start[i].

    a and b are sorted ascending and start is nondecreasing. Returns the count and,
    for each row i, the last column last[i] whose cell is <= v (or < v); last[i]
    can be below start[i]. One staircase walk: O(len(a) + len(b)).
    """
    n = len(b)
    j = n - 1
    c = 0
    last = [0] * len(a)
    for i, ai in enumerate(a):  # @line L13
        if strict:
            while j >= 0 and ai + b[j] >= v:
                j -= 1
        else:
            while j >= 0 and ai + b[j] > v:  # @line L14
                j -= 1
        last[i] = j  # @line L15
        if j >= start[i]:
            c += j - start[i] + 1  # @line L16
    return c, last


def select_sum(a, b, start, k, rng):
    """Return the k-th smallest (k >= 1) of the cells a[i] + b[j] with j >= start[i].

    Randomized selection in the sorted matrix: each round takes a random active
    cell as pivot and moves the per-row bounds lo[i] and hi[i] past it.
    Expected O((len(a) + len(b)) log N) time for N cells.
    """
    m, n = len(a), len(b)
    lo = list(start)  # @line L1
    hi = [n - 1] * m  # @line L1
    while True:  # @line L2
        widths = [max(0, hi[i] - lo[i] + 1) for i in range(m)]
        w = sum(widths)  # @line L3
        if w == 0:
            raise ValueError("k is out of range")
        r = rng.randrange(w)  # @line L4
        i = 0
        while r >= widths[i]:
            r -= widths[i]
            i += 1
        v = a[i] + b[lo[i] + r]  # @line L4
        cle, le = count_le(a, b, start, v)  # @line L5
        clt, lt = count_le(a, b, start, v, strict=True)  # @line L5
        if clt >= k:  # @line L6
            for t in range(m):
                hi[t] = min(hi[t], lt[t])
        elif cle >= k:  # @line L7
            return v
        else:  # @line L8
            for t in range(m):
                lo[t] = max(lo[t], le[t] + 1)


def successor_sum(a, b, start, v):
    """Smallest cell value > v, or None. O(len(a) + len(b))."""
    _, le = count_le(a, b, start, v)
    best = None
    for i, ai in enumerate(a):
        j = max(le[i] + 1, start[i])
        if j < len(b):
            s = ai + b[j]
            if best is None or s < best:
                best = s
    return best


def _median_of_cells(a, b, start, total, rng):
    """Median of the multiset of cells (the average of the two middle ones if total is even)."""
    k = (total + 1) // 2
    s1 = select_sum(a, b, start, k, rng)  # @line L10
    if total % 2 == 1:
        s2 = s1
    else:
        cle, _ = count_le(a, b, start, s1)
        s2 = s1 if cle >= k + 1 else successor_sum(a, b, start, s1)  # @line L11
    if _exact(a) and _exact(b):
        return (Fraction(s1) + Fraction(s2)) / 2
    return (s1 + s2) / 2


def _exact(a):
    return all(isinstance(v, (int, Fraction)) for v in a)


def hodges_lehmann(xs, seed: int = 0):
    """One-sample Hodges-Lehmann estimate: the median of the Walsh averages (x_i + x_j)/2, i <= j.

    Exact (a Fraction) for int or Fraction data. Expected O(n log n) time, O(n) space.
    """
    x = sorted(xs)  # @line L9
    n = len(x)
    if n == 0:
        raise ValueError("empty sample")
    total = n * (n + 1) // 2  # @line L9
    med_sum = _median_of_cells(x, x, list(range(n)), total, random.Random(seed))  # @line L10
    return med_sum / 2  # @line L12


def hodges_lehmann_shift(xs, ys, seed: int = 0):
    """Two-sample Hodges-Lehmann shift estimate: the median of all y_j - x_i.

    Exact for int or Fraction data. Expected O((m + n) log(m n)) time after sorting.
    """
    if not xs or not ys:
        raise ValueError("empty sample")
    a = sorted(-v for v in xs)  # ascending, so a[i] = -x in descending order of x
    b = sorted(ys)
    return _median_of_cells(a, b, [0] * len(a), len(a) * len(b), random.Random(seed))
test_hodges_lehmann_estimator.py 126 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hodges-lehmann-estimator/. The authors are listed in prov/WF6BA7.jsonl.

import random
from fractions import Fraction
from statistics import median

import pytest

from hodges_lehmann_estimator import (
    count_le, hodges_lehmann, hodges_lehmann_shift, select_sum,
)


def naive_hl(xs):
    """Oracle: list all n(n + 1)/2 Walsh averages, sort, take the median."""
    n = len(xs)
    walsh = [Fraction(xs[i] + xs[j], 2) for i in range(n) for j in range(i, n)]
    return median(walsh)


def naive_shift(xs, ys):
    return median([Fraction(y - x) for x in xs for y in ys])


def test_small_by_hand() -> None:
    # Walsh averages of (1, 2, 9): 1, 1.5, 5, 2, 5.5, 9 -> sorted 1 1.5 2 5 5.5 9, median 3.5.
    assert hodges_lehmann([1, 2, 9]) == Fraction(7, 2)
    # (0, 1): averages 0, 0.5, 1, median 0.5.
    assert hodges_lehmann([0, 1]) == Fraction(1, 2)
    assert hodges_lehmann([5]) == 5
    # The example of the page.
    assert hodges_lehmann([3, 7, 1, 20, 4]) == 5
    # Shift: x = (1, 2), y = (4, 9): differences 3 8 2 7, median 5.
    assert hodges_lehmann_shift([1, 2], [4, 9]) == 5


def test_against_all_walsh_averages() -> None:
    rng = random.Random(11)
    for _ in range(300):
        n = rng.randint(1, 40)
        xs = [rng.randint(-20, 20) for _ in range(n)]
        assert hodges_lehmann(xs, seed=rng.randint(0, 10**6)) == naive_hl(xs)


def test_shift_against_all_differences() -> None:
    rng = random.Random(12)
    for _ in range(200):
        m, n = rng.randint(1, 25), rng.randint(1, 25)
        xs = [rng.randint(-9, 9) for _ in range(m)]
        ys = [rng.randint(-9, 9) for _ in range(n)]
        assert hodges_lehmann_shift(xs, ys, seed=rng.randint(0, 10**6)) == naive_shift(xs, ys)


def test_every_rank_of_select() -> None:
    rng = random.Random(13)
    for _ in range(40):
        n = rng.randint(1, 15)
        x = sorted(rng.randint(0, 8) for _ in range(n))
        cells = sorted(x[i] + x[j] for i in range(n) for j in range(i, n))
        for k in range(1, len(cells) + 1):
            assert select_sum(x, x, list(range(n)), k, rng) == cells[k - 1]


def test_count_le_matches_brute_force() -> None:
    rng = random.Random(14)
    for _ in range(200):
        n = rng.randint(1, 12)
        x = sorted(rng.randint(0, 10) for _ in range(n))
        v = rng.randint(-1, 21)
        c, _ = count_le(x, x, list(range(n)), v)
        assert c == sum(1 for i in range(n) for j in range(i, n) if x[i] + x[j] <= v)
        c, _ = count_le(x, x, list(range(n)), v, strict=True)
        assert c == sum(1 for i in range(n) for j in range(i, n) if x[i] + x[j] < v)


def test_large_input_is_fast_and_correct() -> None:
    rng = random.Random(15)
    xs = [rng.gauss(0.0, 1.0) for _ in range(2000)]
    est = hodges_lehmann(xs)
    walsh = sorted((xs[i] + xs[j]) / 2 for i in range(0, 2000, 1) for j in range(i, 2000))
    assert est == pytest.approx((walsh[len(walsh) // 2 - 1] + walsh[len(walsh) // 2]) / 2, abs=1e-12)


def test_tukey_identity() -> None:
    # W+ (sum of the ranks of |d_i| over d_i > 0) equals #{i <= j : d_i + d_j > 0}.
    rng = random.Random(16)
    for _ in range(200):
        n = rng.randint(1, 15)
        mags = rng.sample(range(1, 100), n)
        d = [m if rng.random() < 0.5 else -m for m in mags]
        order = sorted(range(n), key=lambda i: abs(d[i]))
        rank = {i: r + 1 for r, i in enumerate(order)}
        w_plus = sum(rank[i] for i in range(n) if d[i] > 0)
        pairs = sum(1 for i in range(n) for j in range(i, n) if d[i] + d[j] > 0)
        assert w_plus == pairs


def finite_breakdown_count(n):
    total = n * (n + 1) // 2
    need = (total + 1) // 2
    return next(m for m in range(n + 1) if total - (n - m) * (n - m + 1) // 2 >= need)


def test_empirical_breakdown() -> None:
    # Move k points to a huge t: bounded for k < m*, unbounded at k = m*.
    rng = random.Random(17)
    for n in (5, 10, 20):
        mstar = finite_breakdown_count(n)
        clean = [rng.randint(0, 50) for _ in range(n)]
        for t in (10**9, 10**18):
            for k in range(mstar + 1):
                ys = clean[:n - k] + [t] * k
                v = hodges_lehmann(ys)
                if k < mstar:
                    assert min(clean[:n - k]) <= v <= max(clean[:n - k])
                else:
                    assert v >= Fraction(t, 4)
    assert [finite_breakdown_count(n) for n in (5, 10, 20, 100)] == [2, 4, 6, 30]


def test_errors() -> None:
    with pytest.raises(ValueError):
        hodges_lehmann([])
    with pytest.raises(ValueError):
        hodges_lehmann_shift([], [1])

History

Hodges and Lehmann (1963) showed how to turn a rank test into an estimator of location or shift, and they derived the median of the Walsh averages from the signed-rank test. Their 1956 paper had already found the efficiency of the Wilcoxon tests relative to the tt test: 3/π3/\pi at the normal and never below 0.864. Johnson and Mizoguchi (1978) gave an O(nlog⁡n)O(n \log n) selection in X+YX + Y, and Monahan (1984) published a practical randomized algorithm for the Hodges-Lehmann estimate as ACM Algorithm 616.

References

  1. J. L. Hodges Jr. and E. L. Lehmann, Estimates of location based on rank tests, The Annals of Mathematical Statistics 34(2), 1963, pp. 598 to 611 (the estimator from the signed-rank and rank-sum tests, and its asymptotic efficiency)
  2. J. L. Hodges Jr. and E. L. Lehmann, The efficiency of some nonparametric competitors of the t-test, The Annals of Mathematical Statistics 27(2), 1956, pp. 324 to 335 (the efficiency 3/pi at the normal and the lower bound 0.864)
  3. John F. Monahan, Algorithm 616, fast computation of the Hodges-Lehmann location estimator, ACM Transactions on Mathematical Software 10(3), 1984, pp. 265 to 270 (randomized selection among the Walsh averages in expected O(n log n) time)
  4. Donald B. Johnson and Tetsuo Mizoguchi, Selecting the Kth element in X + Y and X1 + X2 + ... + Xm, SIAM Journal on Computing 7(2), 1978, pp. 147 to 153 (deterministic selection in X + Y in O(n log n) time)
  5. Peter J. Huber and Elvezio M. Ronchetti, Robust Statistics, second edition, Wiley, 2009, Chapter 3 (R-estimators, their influence function and breakdown point)
  6. Myles Hollander, Douglas A. Wolfe and Eric Chicken, Nonparametric Statistical Methods, third edition, Wiley, 2014, Chapter 3 (the one-sample location estimator and its confidence interval) and Chapter 4 (the two-sample shift estimator)

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.average
  • 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