Algorithm Search⌘K

Algorithmresearch

Tukey median

Also called halfspace median, deepest point.

The point of maximal halfspace depth, a multivariate median with breakdown point at least 1/(d + 1). In the plane it can be computed in O(n log n) expected time.

Time
O(n^3 log n) worst · best
Space
O(n^3) extra
Where
n = the number of points in the plane
Properties
affine equivariantdeterministicexact in exact arithmeticnot in placeoffline
Origin
John W. Tukey, David L. Donoho, Miriam Gasko, Peter J. Rousseeuw, Ida Ruts, Timothy M. Chan, 1975

The Tukey median of a cloud of points is the deepest point in the sense of halfspace depth: every closed halfspace that contains it also contains many data points. In dd dimensions its depth is at least ⌈n/(d+1)⌉\lceil n/(d+1) \rceil, so it stays bounded while fewer than about n/(d+1)n/(d+1) points are replaced by outliers. It is affine equivariant, which the coordinatewise median and the geometric median are not. This page gives an exact algorithm for the plane that is easy to check, and lists the faster ones.

In plain words

Put pins on a map, one for each data point. Pick a spot and draw any straight line through it. Count the pins on the side of the line where there are fewer. The worst count over all lines is the depth of the spot. A spot near the edge of the cloud has a line with almost no pins on one side, so it is shallow. A spot in the middle has many pins on every side.

The Tukey median is the deepest spot. If several spots tie, they form a convex region, and we take its centre of gravity. A few wild points far away cannot pull the deepest spot far, because each of them adds at most one pin to each side.

The problem

The input is a sample P=(p1,…,pn)P = (p_1, \ldots, p_n) of points in the plane; repeated points are allowed. Let hd⁡(x)\operatorname{hd}(x) be the halfspace depth of xx in PP, and Dk={x:hd⁡(x)≥k}D_k = \{x : \operatorname{hd}(x) \ge k\} the depth region of level kk. The output is the maximal depth k∗=max⁡xhd⁡(x)k^* = \max_x \operatorname{hd}(x) and the Tukey median T(P)T(P), the centre of gravity of Dk∗D_{k^*}. This tie rule is the one of Donoho and Gasko (1992) and of Rousseeuw and Ruts (1998). When all points lie on one line, Dk∗D_{k^*} is the one-dimensional median interval on that line, and T(P)T(P) is its midpoint.

The algorithm

DEPTH computes the depth of one point. TUKEY-MEDIAN searches for the largest kk with Dk≠∅D_k \ne \emptyset. REGION builds DkD_k by clipping a box with one halfplane for each critical direction. For a direction uu, the kk-th largest of u⊤p1,…,u⊤pnu^\top p_1, \ldots, u^\top p_n is written qu(k)q_u(k).

  1. DEPTH(x, P) ▷ the halfspace depth of x
  2. 1k0 ← the number of points of P equal to x
  3. 2D ← the vectors p − x for the points p ≠ x; m ← |D|
  4. 3sort D by polar angle, exactly ▷ upper or lower half, then the sign of a cross product
  5. 4best ← m; e ← 0
  6. 5for each j in 0 .. m − 1 that starts a group of equal angle do
  7. 6e ← max(e, j)
  8. 7while e < j + m and angle(D[e mod m]) ∈ [angle(D[j]), angle(D[j]) + π) do e ← e + 1
  9. 8best ← min(best, e − j, m − (e − j))
  10. 9return k0 + best
  11. TUKEY-MEDIAN(P)
  12. 10if all points of P lie on one line then return the midpoint of the median interval on it
  13. 11U ← the two normals ±(a₂ − b₂, b₁ − a₁) of each pair of points a ≠ b
  14. 12for each u in U, sort the projections uᵀp, p in P, in decreasing order
  15. 13lo ← ⌈n/3⌉; hi ← n ▷ D_lo is not empty by the centerpoint theorem
  16. 14while lo < hi do
  17. 15k ← ⌈(lo + hi)/2⌉
  18. 16if REGION(k) ≠ ∅ then lo ← k else hi ← k − 1
  19. 17R ← REGION(lo)
  20. 18return the centre of gravity of R, and k* = lo
  21. REGION(k) ▷ D_k as a convex polygon
  22. 19R ← the bounding box of P
  23. 20for each u in U do
  24. 21q ← q_u(k) ▷ the k-th largest projection
  25. 22R ← R ∩ {x : uᵀx ≤ q} ▷ clip a convex polygon by a halfplane
  26. 23if R = ∅ then return ∅
  27. 24return R

The idea of REGION is that the depth of xx is at least kk exactly when, for every direction uu, at least kk points project at or beyond xx, that is u⊤x≤qu(k)u^\top x \le q_u(k). Between two directions where two projections swap, the kk-th point does not change, so it is enough to test the directions of UU. The centre of gravity in line L18 is the area centroid of a polygon, the midpoint of a segment, or the point itself.

Example

Take the seven points

P={(0,0),(6,0),(0,6),(6,6),(2,3),(3,1),(9,9)}.P = \{(0, 0), (6, 0), (0, 6), (6, 6), (2, 3), (3, 1), (9, 9)\}.

Three of the 21 pairs, on the diagonal, give the same normals, so UU has 32 distinct directions. The depths of the data points are 1,1,1,2,2,2,11, 1, 1, 2, 2, 2, 1.

Depth of one point. For x=(3,3)x = (3, 3), line L3 sorts the seven vectors p−xp - x by angle:

vector angle in the half-turn [θj,θj+π)[\theta_j, \theta_j + \pi) outside
(3, 3), (6, 6) 45° 4 3
(−3, 3) 135° 4 3
(−1, 0) 180° 4 3
(−3, −3) 225° 3 4
(0, −2) 270° 4 3
(3, −3) 315° 3 4

The smallest entry is 3, and k0=0k_0 = 0, so hd⁡((3,3))=3\operatorname{hd}((3,3)) = 3. The half-turn that starts at (−3,−3)(-3, -3) holds the points (0,0)(0,0), (3,1)(3,1) and (6,0)(6,0). They are the points on or below the line through (3,3)(3, 3) with slope 9/119/11.

The search. Line L13 sets lo=⌈7/3⌉=3lo = \lceil 7/3 \rceil = 3 and hi=7hi = 7.

step kk REGION(kk) new range
1 5 empty [3, 4]
2 4 empty [3, 3]

The regions of the levels that are not empty are:

kk DkD_k
1 the hull, with vertices (0, 0), (6, 0), (9, 9), (0, 6)
2 the hexagon (3, 1), (6, 5), (6, 6), (11/2, 6), (2, 3), (36/19, 54/19)
3 the segment from (18/7, 18/7) to (3, 3)

So k∗=3k^* = 3, and the Tukey median is the midpoint of the segment, (39/14,39/14)≈(2.786,2.786)(39/14, 39/14) \approx (2.786, 2.786). The mean is (26/7,25/7)≈(3.71,3.57)(26/7, 25/7) \approx (3.71, 3.57); the point (9,9)(9, 9) pulls it up and to the right. If (9,9)(9,9) moves to (900,900)(900, 900), the program gives the same D3D_3 and the same Tukey median, while the mean moves to about (131,130.9)(131, 130.9). If it moves to (900,−900)(900, -900), the Tukey median moves only to about (3.06,2.08)(3.06, 2.08), inside the hull of the six other points.

Correctness

DEPTH is correct because the closed halfplanes through xx correspond to closed half-turns of directions, and the least count over closed half-turns equals the least count over the half-open half-turns [θj,θj+π)[\theta_j, \theta_j + \pi) and their complements; the two-pointer loop counts each of these. REGION is correct because the depth condition u⊤x≤qu(k)u^\top x \le q_u(k) for the finitely many directions of UU implies it for all directions: between two neighbours a,b∈Ua, b \in U the kk-th point psp_s is fixed, and each direction between them is a nonnegative combination of aa and bb. The binary search is correct because the regions are nested and D⌈n/3⌉D_{\lceil n/3 \rceil} is not empty.

The centerpoint bound. In Rd\mathbb{R}^d, k∗≥⌈n/(d+1)⌉k^* \ge \lceil n/(d+1) \rceil. Let k=⌈n/(d+1)⌉k = \lceil n/(d+1) \rceil. The region DkD_k is the intersection of the closed halfspaces that hold at least n−k+1n - k + 1 points. Replace each such halfspace by the convex hull of the points in it. Any d+1d + 1 of these hulls share a data point, because together they miss at most (d+1)(k−1)<n(d+1)(k-1) < n points. By Helly's theorem all the hulls share a point, and it lies in DkD_k. The bound is tight: for three tight groups of n/3n/3 points at the corners of a large triangle, k∗=n/3k^* = n/3. The full proofs are below.

Proof: DEPTH computes the halfspace depth, REGION computes the depth region, and TUKEY-MEDIAN returns the centre of the deepest regionfull

Setting. P=(p1,…,pn)P = (p_1, \ldots, p_n) is a sample of points in the plane, with repeats allowed. For a direction u≠0u \ne 0 and a point xx, Nu(x)=#{i:u⊤pi≥u⊤x}N_u(x) = \#\{i : u^\top p_i \ge u^\top x\} is the number of points in the closed halfplane {y:u⊤y≥u⊤x}\{y : u^\top y \ge u^\top x\}, which has xx on its boundary. The depth is hd⁡(x)=min⁡uNu(x)\operatorname{hd}(x) = \min_u N_u(x), and Dk={x:hd⁡(x)≥k}D_k = \{x : \operatorname{hd}(x) \ge k\}. All arithmetic is exact.

Part 1. DEPTH

Lines L1 and L2 set k0k_0 to the number of points equal to xx and DD to the mm nonzero vectors di=pi−xd_i = p_i - x. For each uu, the points equal to xx are in every halfplane of the form above, so Nu(x)=k0+g(u)N_u(x) = k_0 + g(u) with g(u)=#{i:u⊤di≥0}g(u) = \#\{i : u^\top d_i \ge 0\}. If m=0m = 0, the depth is k0k_0. Assume m≥1m \ge 1 from now on.

Write ∠v∈[0,2π)\angle v \in [0, 2\pi) for the polar angle of a vector vv. The vectors dd with u⊤d≥0u^\top d \ge 0 are those whose angle lies in the closed arc [∠u−π/2,∠u+π/2][\angle u - \pi/2, \angle u + \pi/2] of length π\pi. So min⁡ug(u)\min_u g(u) is the least number of the angles ∠di\angle d_i in a closed arc of length π\pi (a closed half-turn). For a half-open arc [α,α+π)[\alpha, \alpha + \pi), let c(α)c(\alpha) be the number of angles in it. For j=1,…,mj = 1, \ldots, m, put θj=∠dj\theta_j = \angle d_j and cj=c(θj)c_j = c(\theta_j).

Lemma 1. min⁡ug(u)=min⁡jmin⁡(cj,m−cj)\min_u g(u) = \min_j \min(c_j, m - c_j).

Proof. (≤\le) The number c(α)c(\alpha) of a half-open half-turn is the count of a closed half-turn: for small ε>0\varepsilon > 0, the closed arc [α−ε,α+π−ε][\alpha - \varepsilon, \alpha + \pi - \varepsilon] holds the same angles as [α,α+π)[\alpha, \alpha + \pi), because only finitely many angles exist and none lies in [α−ε,α)[\alpha - \varepsilon, \alpha) or in (α+π−ε,α+π)(\alpha + \pi - \varepsilon, \alpha + \pi) when ε\varepsilon is small. Both cj=c(θj)c_j = c(\theta_j) and m−cj=c(θj+π)m - c_j = c(\theta_j + \pi) are of this form. So each is at least the minimum over closed half-turns.

(≥\ge) Let [β,β+π][\beta, \beta + \pi] be a closed half-turn with the least count. Its count is at least the count of [β,β+π)[\beta, \beta + \pi). Now turn the half-open arc [β+t,β+π+t)[\beta + t, \beta + \pi + t) forward, from t=0t = 0, and stop at the first t≥0t \ge 0 where the open end β+π+t\beta + \pi + t is an angle θj\theta_j. A turn of the arc can add an angle only when the end passes it, and the end is open, so no angle enters before the stop. Angles can leave at the start. So the count does not increase, and at the stop the arc is [θj−π,θj)[\theta_j - \pi, \theta_j), which holds m−cjm - c_j angles. □\square

Lemma 2. After the sort of line L3, for each index jj that starts a group of equal angles, the loop of line L7 ends with e−j=cje - j = c_j. The loop of lines L5 to L8 takes O(m)O(m) steps in total.

Proof. Line L7 tests whether the angle of D[e mod m]D[e \bmod m] lies in [θj,θj+π)[\theta_j, \theta_j + \pi), by the sign of the cross product, and by the dot product for a parallel vector. Because jj is the first index of its group, the angles in [θj,θj+π)[\theta_j, \theta_j + \pi) are exactly the entries D[j],D[j+1],…D[j], D[j+1], \ldots that follow jj in cyclic order up to the first entry outside the arc. So the loop stops at e=j+cje = j + c_j if it starts at some e≤j+cje \le j + c_j. For the first group start, ee starts at jj. For two group starts j<j′j < j', the arc of j′j' starts later than the arc of jj and ends later, so j+cj≤j′+cj′j + c_j \le j' + c_{j'}; line L6 then starts the loop at max⁡(e,j′)≤j′+cj′\max(e, j') \le j' + c_{j'}. The index ee never decreases and stays below 2m2m, so the inner loop runs O(m)O(m) times in total. □\square

By Lemmas 1 and 2, line L9 returns k0+min⁡ug(u)=hd⁡(x)k_0 + \min_u g(u) = \operatorname{hd}(x). The angular sort uses exact comparisons (the half of the plane, then the cross product), so DEPTH takes O(nlog⁡n)O(n \log n) time.

Part 2. The depth region as a finite intersection

For a direction uu, let qu(k)q_u(k) be the kk-th largest of the numbers u⊤p1,…,u⊤pnu^\top p_1, \ldots, u^\top p_n.

Lemma 3. hd⁡(x)≥k\operatorname{hd}(x) \ge k if and only if u⊤x≤qu(k)u^\top x \le q_u(k) for every direction uu.

Proof. Nu(x)≥kN_u(x) \ge k means that at least kk of the projections are ≥u⊤x\ge u^\top x, which is the same as qu(k)≥u⊤xq_u(k) \ge u^\top x. The depth is at least kk when this holds for all uu. □\square

Let UU be the set of the two normals ±(a2−b2,b1−a1)\pm(a_2 - b_2, b_1 - a_1) of a−ba - b, over all pairs of sample points a≠ba \ne b. These are the directions where two projections are equal.

Lemma 4. If the points are not all on one line, then hd⁡(x)≥k\operatorname{hd}(x) \ge k if and only if u⊤x≤qu(k)u^\top x \le q_u(k) for every u∈Uu \in U.

Proof. One direction is Lemma 3. For the other, take any direction ww. On the unit circle, the directions of UU cut the circle into arcs. Inside one arc no two projections are equal, so the order of the projections is fixed, and some index ss is the kk-th largest for every direction in the open arc. By continuity of u↦u⊤piu \mapsto u^\top p_i, qu(k)=u⊤psq_u(k) = u^\top p_s also holds at the two ends aa and bb of the arc. The points are not all on one line, so at least two non-parallel differences a−ba - b exist, UU has at least four directions, and U=−UU = -U. So each arc is shorter than π\pi, and every direction ww in the closed arc is w=λa+μbw = \lambda a + \mu b with λ,μ≥0\lambda, \mu \ge 0. If a⊤x≤qa(k)=a⊤psa^\top x \le q_a(k) = a^\top p_s and b⊤x≤b⊤psb^\top x \le b^\top p_s, then

w⊤x=λa⊤x+μb⊤x≤λa⊤ps+μb⊤ps=w⊤ps=qw(k).w^\top x = \lambda a^\top x + \mu b^\top x \le \lambda a^\top p_s + \mu b^\top p_s = w^\top p_s = q_w(k).

So the condition on UU gives the condition for every ww, and Lemma 3 ends the proof. □\square

Lemma 5 (REGION). If the points are not all on one line and k≥1k \ge 1, REGION(k)(k) returns DkD_k, as a convex polygon, a segment, a point, or the empty set.

Proof. Each x∈Dkx \in D_k with k≥1k \ge 1 is in the convex hull of PP (a point outside the hull has depth 0), so DkD_k lies in the bounding box of line L19. Line L22 replaces the convex set RR by R∩{x:u⊤x≤q}R \cap \{x : u^\top x \le q\}. For a convex polygon, the intersection with a halfplane is the convex polygon whose vertices are the old vertices that satisfy the inequality and the points where an edge crosses the boundary line, in the same cyclic order. This is what the clipping step computes; with exact arithmetic it also works when RR has become a segment or a point. After the loop, RR is the box intersected with all the halfplanes of Lemma 4, which is DkD_k. Line L23 stops early when RR is empty, and then DkD_k is empty. □\square

Part 3. The centerpoint bound

Theorem 6. For a sample of nn points in Rd\mathbb{R}^d, Dk≠∅D_k \ne \emptyset for k=⌈n/(d+1)⌉k = \lceil n/(d+1) \rceil.

Proof. By the region property on the halfspace depth page, DkD_k is the intersection of the closed halfspaces HH with #{i:pi∈H}≥n−k+1\#\{i : p_i \in H\} \ge n - k + 1. For each such HH, let CHC_H be the convex hull of the sample points in HH. Then CH⊆HC_H \subseteq H, and CHC_H is compact and convex. The sets {i:pi∈H}\{i : p_i \in H\} are subsets of {1,…,n}\{1, \ldots, n\}, so the family {CH}\{C_H\} is finite.

Take any d+1d + 1 of these halfspaces. Each misses at most k−1k - 1 indices, so together they miss at most (d+1)(k−1)(d+1)(k-1) indices. Since k−1<n/(d+1)k - 1 < n/(d+1), this is less than nn, so some index ii lies in all d+1d + 1 index sets, and pip_i lies in all d+1d + 1 hulls. By Helly's theorem, all the sets CHC_H have a common point cc. Then cc lies in each HH, so c∈Dkc \in D_k. □\square

In the plane this gives k∗≥⌈n/3⌉k^* \ge \lceil n/3 \rceil. The bound is tight: for three tight groups of n/3n/3 points near the corners of a large triangle, every point has a closed halfplane through it that holds only one group. The test file checks a case with n=9n = 9 and k∗=3k^* = 3.

Part 4. TUKEY-MEDIAN

If all points are on one line (line L10), a closed halfplane meets the line in a closed half-line or in the whole line, so the depth of a point on the line is the one-dimensional depth min⁡(#{ti≤t},#{ti≥t})\min(\#\{t_i \le t\}, \#\{t_i \ge t\}) of its parameter tt, and points off the line have depth 0. The deepest set is the median interval, and its midpoint is returned.

Otherwise, D1⊇D2⊇⋯D_1 \supseteq D_2 \supseteq \cdots, so the property "Dk≠∅D_k \ne \emptyset" holds for all kk up to k∗k^* and fails above it. Line L13 starts with lo=⌈n/3⌉lo = \lceil n/3 \rceil, and Dlo≠∅D_{lo} \ne \emptyset by Theorem 6; hi=nhi = n is at least k∗k^*. The loop of lines L14 to L16 keeps Dlo≠∅D_{lo} \ne \emptyset and k∗≤hik^* \le hi, and the interval shrinks in each round, so it ends with lo=k∗lo = k^*. By Lemma 5, line L17 gets Dk∗D_{k^*}, and line L18 returns its centre of gravity (area centroid, or the midpoint of a segment, or the point). The centre of gravity of a convex set lies in the set, so the returned point has depth k∗k^*. □\square

Part 5. Cost

∣U∣≤n(n−1)|U| \le n(n - 1). Line L12 sorts nn projections for each direction: O(n3log⁡n)O(n^3 \log n) time and O(n3)O(n^3) space.

Lemma 7. During REGION, each polygon has at most 2n+42n + 4 vertices.

Proof. Each edge of RR lies on a box edge or on a line {x:u⊤x=qu(k)}\{x : u^\top x = q_u(k)\}, and qu(k)=u⊤psq_u(k) = u^\top p_s for some sample point psp_s, so the line passes through psp_s. A line that holds an edge of a convex polygon is a supporting line of it. Through one point there are at most two supporting lines that hold edges: two tangents from a point outside, the lines of the at most two edges at a point on the boundary, and none from an interior point. So at most 2n2n edges come from the sample, and 4 from the box. □\square

So one clip takes O(n)O(n) time, REGION takes O(n3)O(n^3) time, and the binary search calls it O(log⁡n)O(\log n) times. The total is O(n3log⁡n)O(n^3 \log n) time and O(n3)O(n^3) space. This is a simple exact method, not the fastest one; the page lists the faster algorithms.

Complexity

  • DEPTH takes O(nlog⁡n)O(n \log n) time for the sort, then O(n)O(n) for the loop. This is optimal: Aloupis and others proved an Ω(nlog⁡n)\Omega(n \log n) lower bound in 2002.
  • TUKEY-MEDIAN as written. ∣U∣≤n(n−1)|U| \le n(n-1). The sorts of line L12 take O(n3log⁡n)O(n^3 \log n) time and O(n3)O(n^3) space. Every polygon in REGION has at most 2n+42n + 4 vertices, because each edge lies on a line through a data point, and at most two edge lines of a convex polygon pass through one point. So one clip takes O(n)O(n) time, REGION takes O(n3)O(n^3), and the binary search adds a factor O(log⁡n)O(\log n). The total is O(n3log⁡n)O(n^3 \log n) time.
  • Faster algorithms. Rousseeuw and Ruts (1998) compute the median in O(n2log⁡2n)O(n^2 \log^2 n) time with HALFMED. Miller and others (2003) compute all the depth contours in O(n2)O(n^2) time by a topological sweep of the dual line arrangement. Chan (2004) finds a deepest point in the plane in O(nlog⁡n)O(n \log n) expected time, which is optimal, by his randomized optimization technique (see Chan's randomized optimization). For d≥3d \ge 3 his algorithm takes O(nd−1)O(n^{d-1}) expected time.

Properties

  • Affine equivariant. T(AP+b)=A T(P)+bT(AP + b) = A\,T(P) + b for each invertible AA, because depth is affine invariant and the centre of gravity commutes with affine maps.
  • Breakdown point. By Donoho and Gasko (1992), for data in general position in Rd\mathbb{R}^d the breakdown point εn∗(T,X)\varepsilon^*_n(T, X) is at least 1/(d+1)1/(d+1), up to rounding, and for samples from an absolutely continuous centrosymmetric distribution it tends to 1/31/3 in every dimension. The idea of the lower bound: mm replaced points change each halfplane count by at most mm, so while mm is small the clean points keep a region of depth larger than mm inside their hull, and no deep point can go far.
  • Not unique without a rule. Dk∗D_{k^*} can be a polygon, a segment or a point. The centre of gravity is a convention. Any point of Dk∗D_{k^*} is a deepest point.
  • In one dimension it is the ordinary median, with the midpoint rule for an even sample.
  • Exact. With integer or rational input, all the steps use exact rational arithmetic.

Variants and improvements

  • Depth contours. The regions D1⊇D2⊇⋯D_1 \supseteq D_2 \supseteq \cdots describe the shape of the cloud. The bagplot of Rousseeuw, Ruts and Tukey (1999) draws the region that holds half the points around the Tukey median, a bivariate box plot.
  • Approximate depth in high dimension. The minimum of Nu(x)N_u(x) over a finite random set of directions uu is an upper bound on the depth. Exact depth in dimension dd takes O(nd−1log⁡n)O(n^{d-1} \log n) time (Dyckerhoff and Mozharovskyi 2016), and with dd in the input it is NP-hard (see halfspace depth).
  • Projection depth and other depths. Donoho and Gasko (1992) also study a depth from projected outlyingness, sup⁡u∣u⊤x−med⁡(u⊤X)∣/MAD⁡(u⊤X)\sup_u |u^\top x - \operatorname{med}(u^\top X)| / \operatorname{MAD}(u^\top X), with the median absolute deviation. Its deepest point has breakdown near 1/2, at a higher cost.
  • Regression depth. Rousseeuw and Hubert define a depth for regression lines in the same spirit; the deepest line is a robust fit, with breakdown near 1/3, like the Theil-Sen estimator of about 0.29.

When to use it

Use the Tukey median for a robust centre of two- or three-dimensional data when the answer must not depend on the units or the orientation of the axes. Use it with the depth contours to draw and to trim bivariate data. In more than a few dimensions the exact computation is too slow; there the minimum covariance determinant or a projection method is the practical choice. If rotation equivariance is enough, the geometric median is cheaper and breaks down at 1/2.

Pitfalls

  • Floating-point angles. Sorting by atan2 puts almost parallel vectors in the wrong order, and the depth can be wrong by one. Compare angles by the half of the plane and the sign of a cross product, in exact arithmetic when you can.
  • Counting only one side. The half-turns that start at a data direction do not cover all halfplanes. Line L8 must also use the complement m−(e−j)m - (e - j). Without it, the depth of (0,0)(0, 0) in the points (0,0)(0,0), (4,0)(4,0), (0,4)(0,4), (4,4)(4,4) comes out as 2, not 1.
  • Collinear data. If all points are on one line, the two-dimensional regions are segments and the normals of UU are all parallel. Treat this case by the one-dimensional median, as line L10 does.
  • Repeated points. Each copy counts in the depth. A point equal to xx is in every halfplane through xx, which is why line L1 counts them apart.
  • Breakdown is not 1/2. The Tukey median tolerates at most about one third of bad points. For samples from a centrosymmetric continuous law its breakdown point tends to 1/3 in every dimension; only the guaranteed lower bound 1/(d+1)1/(d+1) for data in general position falls with dd. A claim of 50 percent is wrong.
  • The deepest data point is not the Tukey median. The deepest data point can be much shallower than k∗k^*; in the example the data points have depth at most 2, while k∗=3k^* = 3.

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.

tukey_median.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tukey-median/. The authors are listed in prov/ES2QKG.jsonl.

from fractions import Fraction
from functools import cmp_to_key
from math import ceil


def _half(v):
    """0 for the angles in [0, pi), 1 for the angles in [pi, 2 pi)."""
    return 0 if (v[1] > 0 or (v[1] == 0 and v[0] > 0)) else 1


def _cross(a, b):
    return a[0] * b[1] - a[1] * b[0]


def _dot(a, b):
    return a[0] * b[0] + a[1] * b[1]


def _angle_cmp(a, b):
    """Exact comparison of the polar angles of two nonzero vectors."""
    ha, hb = _half(a), _half(b)
    if ha != hb:
        return ha - hb
    c = _cross(a, b)
    return -1 if c > 0 else (1 if c < 0 else 0)


def _in_half_turn(a, v):
    """True when the angle of v is in [angle(a), angle(a) + pi)."""
    c = _cross(a, v)
    return c > 0 or (c == 0 and _dot(a, v) > 0)


def depth(x, points):
    """Halfspace depth of x in a planar sample, in O(n log n) exact steps.

    The depth is the least number of sample points in a closed halfplane
    that contains x. The coordinates can be int or Fraction.
    """
    k0 = sum(1 for p in points if p[0] == x[0] and p[1] == x[1])  # @line L1
    d = [(p[0] - x[0], p[1] - x[1]) for p in points
         if p[0] != x[0] or p[1] != x[1]]  # @line L2
    m = len(d)
    if m == 0:
        return k0
    d.sort(key=cmp_to_key(_angle_cmp))  # @line L3
    best, e = m, 0  # @line L4
    for j in range(m):  # @line L5
        if j > 0 and _angle_cmp(d[j - 1], d[j]) == 0:
            continue  # only the first vector of a group of equal angle
        e = max(e, j)  # @line L6
        while e < j + m and _in_half_turn(d[j], d[e % m]):  # @line L7
            e += 1
        best = min(best, e - j, m - (e - j))  # @line L8
    return k0 + best  # @line L9


def _collinear(points):
    a = points[0]
    b = next((p for p in points if p != a), None)
    if b is None:
        return True
    ab = (b[0] - a[0], b[1] - a[1])
    return all(_cross(ab, (p[0] - a[0], p[1] - a[1])) == 0 for p in points)


def _median_on_line(points):
    """Deepest point and its depth when all points lie on one line."""
    n = len(points)
    a = points[0]
    b = next((p for p in points if p != a), a)
    v = (b[0] - a[0], b[1] - a[1])
    if v == (0, 0):
        return (Fraction(a[0]), Fraction(a[1])), n
    t = sorted(Fraction(_dot(v, (p[0] - a[0], p[1] - a[1]))) / _dot(v, v)
               for p in points)
    mid = (t[(n - 1) // 2] + t[n // 2]) / 2
    point = (a[0] + mid * v[0], a[1] + mid * v[1])
    dep = min(sum(1 for s in t if s <= mid), sum(1 for s in t if s >= mid))
    return point, dep


def _clip(poly, u, q):
    """Clip a convex polygon (a list of vertices) to the halfplane u.x <= q."""
    out = []
    k = len(poly)
    for i in range(k):
        p, r = poly[i], poly[(i + 1) % k]
        fp, fr = _dot(u, p) - q, _dot(u, r) - q
        if fp <= 0:
            out.append(p)
        if (fp < 0 < fr) or (fr < 0 < fp):
            t = fp / (fp - fr)
            out.append((p[0] + t * (r[0] - p[0]), p[1] + t * (r[1] - p[1])))
    clean = []
    for p in out:
        if not clean or clean[-1] != p:
            clean.append(p)
    while len(clean) > 1 and clean[0] == clean[-1]:
        clean.pop()
    return clean


def _directions(points):
    """The critical directions: both normals of each line through two points."""
    seen = set()
    dirs = []
    for i in range(len(points)):
        for j in range(i + 1, len(points)):
            a, b = points[i], points[j]
            if a == b:
                continue
            for u in ((a[1] - b[1], b[0] - a[0]), (b[1] - a[1], a[0] - b[0])):
                key = (Fraction(u[0]), Fraction(u[1]))
                g = max(abs(key[0]), abs(key[1]))
                key = (key[0] / g, key[1] / g)
                if key not in seen:
                    seen.add(key)
                    dirs.append(u)
    return dirs


def depth_region(points, k, dirs=None, proj=None):
    """The depth region D_k = {x : depth(x) >= k} as a list of polygon vertices."""
    if dirs is None:
        dirs = _directions(points)
    if proj is None:
        proj = [sorted((_dot(u, p) for p in points), reverse=True) for u in dirs]
    xs = [Fraction(p[0]) for p in points]
    ys = [Fraction(p[1]) for p in points]
    region = [(min(xs), min(ys)), (max(xs), min(ys)),
              (max(xs), max(ys)), (min(xs), max(ys))]  # @line L19
    for u, pr in zip(dirs, proj):  # @line L20
        q = pr[k - 1]  # @line L21
        region = _clip(region, u, q)  # @line L22
        if not region:  # @line L23
            return []
    return region  # @line L24


def centroid(poly):
    """Centre of gravity of a convex polygon, segment or point (exact)."""
    k = len(poly)
    area2 = Fraction(0)
    cx = cy = Fraction(0)
    for i in range(k):
        p, r = poly[i], poly[(i + 1) % k]
        c = _cross(p, r)
        area2 += c
        cx += (p[0] + r[0]) * c
        cy += (p[1] + r[1]) * c
    if area2 != 0:
        return (cx / (3 * area2), cy / (3 * area2))
    lo = min(poly)
    hi = max(poly)
    return ((lo[0] + hi[0]) / 2, (lo[1] + hi[1]) / 2)


def tukey_median(points):
    """Return (median, max_depth) for a planar sample, in exact arithmetic.

    The median is the centre of gravity of the deepest depth region.
    """
    points = [(Fraction(p[0]), Fraction(p[1])) for p in points]
    n = len(points)
    if n == 0:
        raise ValueError("empty sample")
    if _collinear(points):  # @line L10
        return _median_on_line(points)
    dirs = _directions(points)  # @line L11
    proj = [sorted((_dot(u, p) for p in points), reverse=True) for u in dirs]  # @line L12
    lo, hi = ceil(n / 3), n  # @line L13
    while lo < hi:  # @line L14
        k = (lo + hi + 1) // 2  # @line L15
        if depth_region(points, k, dirs, proj):  # @line L16
            lo = k
        else:
            hi = k - 1
    region = depth_region(points, lo, dirs, proj)  # @line L17
    return centroid(region), lo  # @line L18
test_tukey_median.py 176 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tukey-median/. The authors are listed in prov/ES2QKG.jsonl.

import random
from fractions import Fraction
from math import ceil

from tukey_median import centroid, depth, depth_region, tukey_median


def brute_depth(x, points):
    """Oracle: the least count over closed halfplanes {y : u.(y - x) >= 0}.

    The count changes only at the normals of the vectors p - x. Every arc
    between two such normals contains a sum of two of them, or one of the
    vectors p - x itself, so this finite list of u meets every arc.
    """
    d = [(p[0] - x[0], p[1] - x[1]) for p in points]
    crit = []
    for v in d:
        if v != (0, 0):
            crit += [(-v[1], v[0]), (v[1], -v[0]), v, (-v[0], -v[1])]
    cands = list(crit)
    for a in crit:
        for b in crit:
            s = (a[0] + b[0], a[1] + b[1])
            if s != (0, 0):
                cands.append(s)
    if not cands:
        return len(points)
    return min(sum(1 for v in d if u[0] * v[0] + u[1] * v[1] >= 0) for u in cands)


def line_vertices(points):
    """All points where two lines through pairs of sample points cross."""
    lines = []
    for i in range(len(points)):
        for j in range(i + 1, len(points)):
            a, b = points[i], points[j]
            if a != b:
                lines.append((a, b))
    out = set(points)
    for i in range(len(lines)):
        (a, b) = lines[i]
        for j in range(i + 1, len(lines)):
            (c, e) = lines[j]
            r = (b[0] - a[0], b[1] - a[1])
            s = (e[0] - c[0], e[1] - c[1])
            den = r[0] * s[1] - r[1] * s[0]
            if den == 0:
                continue
            t = Fraction((c[0] - a[0]) * s[1] - (c[1] - a[1]) * s[0], den)
            out.add((a[0] + t * r[0], a[1] + t * r[1]))
    return out


def hull(pts):
    """Convex hull by the monotone chain, exact. Returns the vertices CCW."""
    pts = sorted(set(pts))
    if len(pts) <= 2:
        return pts

    def turn(o, a, b):
        return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])

    low, up = [], []
    for p in pts:
        while len(low) >= 2 and turn(low[-2], low[-1], p) <= 0:
            low.pop()
        low.append(p)
    for p in reversed(pts):
        while len(up) >= 2 and turn(up[-2], up[-1], p) <= 0:
            up.pop()
        up.append(p)
    return low[:-1] + up[:-1]


def random_points(rng, n, span):
    return [(rng.randint(-span, span), rng.randint(-span, span)) for _ in range(n)]


def test_depth_small_cases() -> None:
    sq = [(0, 0), (4, 0), (0, 4), (4, 4), (1, 2)]
    assert depth((1, 2), sq) == 2
    assert depth((2, 2), sq) == 2
    assert depth((0, 0), sq) == 1
    assert depth((9, 9), sq) == 0
    # On a line the depth is the one-dimensional depth min(#<=, #>=).
    line = [(i, 2 * i) for i in range(5)]
    assert [depth(p, line) for p in line] == [1, 2, 3, 2, 1]
    # Repeated points all count.
    assert depth((0, 0), [(0, 0)] * 4) == 4


def test_depth_against_brute_force() -> None:
    rng = random.Random(1)
    for trial in range(300):
        n = rng.randint(1, 9)
        pts = random_points(rng, n, 3)
        x = (Fraction(rng.randint(-8, 8), 2), Fraction(rng.randint(-8, 8), 2))
        if trial % 3 == 0:
            x = pts[rng.randrange(n)]
        assert depth(x, pts) == brute_depth(x, pts)


def test_median_against_vertex_search() -> None:
    rng = random.Random(2)
    for _ in range(25):
        n = rng.randint(3, 7)
        pts = random_points(rng, n, 4)
        med, kstar = tukey_median(pts)
        cands = line_vertices([(Fraction(a), Fraction(b)) for a, b in pts])
        best = max(depth(c, pts) for c in cands)
        assert kstar == best
        assert depth(med, pts) == kstar
        deepest = [c for c in cands if depth(c, pts) == kstar]
        assert centroid(hull(deepest)) == med or len(set(deepest)) == 1 and med == deepest[0]


def test_grid_never_deeper() -> None:
    rng = random.Random(3)
    for _ in range(8):
        pts = random_points(rng, 9, 5)
        med, kstar = tukey_median(pts)
        for gx in range(-10, 11):
            for gy in range(-10, 11):
                assert depth((Fraction(gx, 2), Fraction(gy, 2)), pts) <= kstar


def test_centerpoint_bound() -> None:
    rng = random.Random(4)
    for _ in range(40):
        n = rng.randint(1, 14)
        pts = random_points(rng, n, 6)
        med, kstar = tukey_median(pts)
        assert kstar >= ceil(n / 3)
        assert depth(med, pts) == kstar


def test_three_clusters_reach_the_bound() -> None:
    # Three tight groups at the corners of a triangle: max depth is n/3.
    pts = []
    for cx, cy in ((0, 0), (30, 0), (0, 30)):
        pts += [(cx, cy), (cx + 1, cy), (cx, cy + 1)]
    med, kstar = tukey_median(pts)
    assert kstar == 3


def test_regions_are_nested() -> None:
    rng = random.Random(5)
    pts = random_points(rng, 10, 6)
    med, kstar = tukey_median(pts)
    for k in range(1, kstar + 1):
        region = depth_region(pts, k)
        assert region
        for v in region:
            assert depth(v, pts) >= k
    assert depth_region(pts, kstar + 1) == []


def test_collinear_and_tiny() -> None:
    assert tukey_median([(3, 1)]) == ((3, 1), 1)
    med, k = tukey_median([(0, 0), (2, 2), (10, 10), (4, 4)])
    assert med == (3, 3) and k == 2
    med, k = tukey_median([(0, 0), (1, 0), (5, 0)])
    assert med == (1, 0) and k == 2


def test_page_example() -> None:
    pts = [(0, 0), (6, 0), (0, 6), (6, 6), (2, 3), (3, 1), (9, 9)]
    med, k = tukey_median(pts)
    assert k == 3
    assert med == (Fraction(39, 14), Fraction(39, 14))
    assert sorted(depth_region(pts, 3)) == [(Fraction(18, 7), Fraction(18, 7)), (3, 3)]
    assert depth_region(pts, 4) == []
    assert [depth(p, pts) for p in pts] == [1, 1, 1, 2, 2, 2, 1]

History

Tukey introduced halfspace depth in his address "Mathematics and the picturing of data" at the International Congress of Mathematicians in Vancouver in 1974, published in 1975, as a tool to draw bivariate data. Donoho and Gasko (1992) studied the deepest point as an estimator and proved its breakdown properties. Rousseeuw and Ruts gave the O(nlog⁡n)O(n \log n) depth algorithm in 1996 and the first practical median algorithm in 1998, and Miller and others computed all contours in O(n2)O(n^2) time in 2003. Chan closed the question of the planar time bound with an expected O(nlog⁡n)O(n \log n) algorithm in 2004.

References

  1. David L. Donoho and Miriam Gasko, Breakdown properties of location estimates based on halfspace depth and projected outlyingness, The Annals of Statistics 20(4), 1992, pp. 1803 to 1827 (the maximal depth is at least ceil(n/(d+1)), the breakdown point of the deepest point, and its limit 1/3 for symmetric distributions)
  2. John W. Tukey, Mathematics and the picturing of data, in R. D. James (ed.), Proceedings of the International Congress of Mathematicians, Vancouver 1974, Volume 2, Canadian Mathematical Congress, Montreal, 1975, pp. 523 to 531, The whole paper (halfspace depth and the deepest point as a bivariate median)
  3. Peter J. Rousseeuw and Ida Ruts, Constructing the bivariate Tukey median, Statistica Sinica 8(3), 1998, pp. 827 to 839, The whole paper (the median as the centre of gravity of the deepest region, a direct O(n^5 log n) method and the HALFMED algorithm in O(n^2 log^2 n) time)
  4. Peter J. Rousseeuw and Ida Ruts, Algorithm AS 307: Bivariate location depth, Journal of the Royal Statistical Society, Series C (Applied Statistics) 45(4), 1996, pp. 516 to 526, The whole paper (the depth of one point in O(n log n) time)
  5. K. Miller, S. Ramaswami, P. J. Rousseeuw, J. A. Sellarès, D. Souvaine, I. Streinu and A. Struyf, Efficient computation of location depth contours by methods of computational geometry, Statistics and Computing 13(2), 2003, pp. 153 to 162 (all depth contours in O(n^2) time by a topological sweep of the dual arrangement)
  6. Timothy M. Chan, An optimal randomized algorithm for maximum Tukey depth, Proceedings of the Fifteenth Annual ACM-SIAM Symposium on Discrete Algorithms (SODA 2004), 2004, The whole paper (the deepest point in the plane in O(n log n) expected time, and in O(n^(d-1)) expected time for d >= 3)
  7. Jiří Matoušek, Lectures on Discrete Geometry, Springer, 2002, Section 1.3 (Helly's theorem) and Section 1.4 (the centerpoint theorem)

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