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
- Model
- Real RAM
- Properties
- affine equivariantdeterministicexact in exact arithmeticnot in placeoffline
- Evidence
- Proof sketchCode in 1 languages
- 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 dimensions its depth is at least , so it stays bounded while fewer than about 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 of points in the plane; repeated points are allowed. Let be the halfspace depth of in , and the depth region of level . The output is the maximal depth and the Tukey median , the centre of gravity of . This tie rule is the one of Donoho and Gasko (1992) and of Rousseeuw and Ruts (1998). When all points lie on one line, is the one-dimensional median interval on that line, and is its midpoint.
The algorithm
DEPTH computes the depth of one point. TUKEY-MEDIAN searches for the largest with . REGION builds by clipping a box with one halfplane for each critical direction. For a direction , the -th largest of is written .
DEPTH(x, P) ▷ the halfspace depth of x- 1
k0 ← the number of points of P equal to x - 2
D ← the vectors p − x for the points p ≠ x; m ← |D| - 3
sort D by polar angle, exactly ▷ upper or lower half, then the sign of a cross product - 4
best ← m; e ← 0 - 5
for each j in 0 .. m − 1 that starts a group of equal angle do - 6
e ← max(e, j) - 7
while e < j + m and angle(D[e mod m]) ∈ [angle(D[j]), angle(D[j]) + π) do e ← e + 1 - 8
best ← min(best, e − j, m − (e − j)) - 9
return k0 + best TUKEY-MEDIAN(P)- 10
if all points of P lie on one line then return the midpoint of the median interval on it - 11
U ← the two normals ±(a₂ − b₂, b₁ − a₁) of each pair of points a ≠ b - 12
for each u in U, sort the projections uᵀp, p in P, in decreasing order - 13
lo ← ⌈n/3⌉; hi ← n ▷ D_lo is not empty by the centerpoint theorem - 14
while lo < hi do - 15
k ← ⌈(lo + hi)/2⌉ - 16
if REGION(k) ≠ ∅ then lo ← k else hi ← k − 1 - 17
R ← REGION(lo) - 18
return the centre of gravity of R, and k* = lo REGION(k) ▷ D_k as a convex polygon- 19
R ← the bounding box of P - 20
for each u in U do - 21
q ← q_u(k) ▷ the k-th largest projection - 22
R ← R ∩ {x : uᵀx ≤ q} ▷ clip a convex polygon by a halfplane - 23
if R = ∅ then return ∅ - 24
return R
The idea of REGION is that the depth of is at least exactly when, for every direction , at least points project at or beyond , that is . Between two directions where two projections swap, the -th point does not change, so it is enough to test the directions of . 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
Three of the 21 pairs, on the diagonal, give the same normals, so has 32 distinct directions. The depths of the data points are .
Depth of one point. For , line L3 sorts the seven vectors by angle:
| vector | angle | in the half-turn | 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 , so . The half-turn that starts at holds the points , and . They are the points on or below the line through with slope .
The search. Line L13 sets and .
| step | REGION() | new range | |
|---|---|---|---|
| 1 | 5 | empty | [3, 4] |
| 2 | 4 | empty | [3, 3] |
The regions of the levels that are not empty are:
| 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 , and the Tukey median is the midpoint of the segment, . The mean is ; the point pulls it up and to the right. If moves to , the program gives the same and the same Tukey median, while the mean moves to about . If it moves to , the Tukey median moves only to about , inside the hull of the six other points.
Correctness
DEPTH is correct because the closed halfplanes through 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 and their complements; the two-pointer loop counts each of these. REGION is correct because the depth condition for the finitely many directions of implies it for all directions: between two neighbours the -th point is fixed, and each direction between them is a nonnegative combination of and . The binary search is correct because the regions are nested and is not empty.
The centerpoint bound. In , . Let . The region is the intersection of the closed halfspaces that hold at least points. Replace each such halfspace by the convex hull of the points in it. Any of these hulls share a data point, because together they miss at most points. By Helly's theorem all the hulls share a point, and it lies in . The bound is tight: for three tight groups of points at the corners of a large triangle, . 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. is a sample of points in the plane, with repeats allowed. For a direction and a point , is the number of points in the closed halfplane , which has on its boundary. The depth is , and . All arithmetic is exact.
Part 1. DEPTH
Lines L1 and L2 set to the number of points equal to and to the nonzero vectors . For each , the points equal to are in every halfplane of the form above, so with . If , the depth is . Assume from now on.
Write for the polar angle of a vector . The vectors with are those whose angle lies in the closed arc of length . So is the least number of the angles in a closed arc of length (a closed half-turn). For a half-open arc , let be the number of angles in it. For , put and .
Lemma 1. .
Proof. () The number of a half-open half-turn is the count of a closed half-turn: for small , the closed arc holds the same angles as , because only finitely many angles exist and none lies in or in when is small. Both and are of this form. So each is at least the minimum over closed half-turns.
() Let be a closed half-turn with the least count. Its count is at least the count of . Now turn the half-open arc forward, from , and stop at the first where the open end is an angle . 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 , which holds angles.
Lemma 2. After the sort of line L3, for each index that starts a group of equal angles, the loop of line L7 ends with . The loop of lines L5 to L8 takes steps in total.
Proof. Line L7 tests whether the angle of lies in , by the sign of the cross product, and by the dot product for a parallel vector. Because is the first index of its group, the angles in are exactly the entries that follow in cyclic order up to the first entry outside the arc. So the loop stops at if it starts at some . For the first group start, starts at . For two group starts , the arc of starts later than the arc of and ends later, so ; line L6 then starts the loop at . The index never decreases and stays below , so the inner loop runs times in total.
By Lemmas 1 and 2, line L9 returns . The angular sort uses exact comparisons (the half of the plane, then the cross product), so DEPTH takes time.
Part 2. The depth region as a finite intersection
For a direction , let be the -th largest of the numbers .
Lemma 3. if and only if for every direction .
Proof. means that at least of the projections are , which is the same as . The depth is at least when this holds for all .
Let be the set of the two normals of , over all pairs of sample points . These are the directions where two projections are equal.
Lemma 4. If the points are not all on one line, then if and only if for every .
Proof. One direction is Lemma 3. For the other, take any direction . On the unit circle, the directions of cut the circle into arcs. Inside one arc no two projections are equal, so the order of the projections is fixed, and some index is the -th largest for every direction in the open arc. By continuity of , also holds at the two ends and of the arc. The points are not all on one line, so at least two non-parallel differences exist, has at least four directions, and . So each arc is shorter than , and every direction in the closed arc is with . If and , then
So the condition on gives the condition for every , and Lemma 3 ends the proof.
Lemma 5 (REGION). If the points are not all on one line and , REGION returns , as a convex polygon, a segment, a point, or the empty set.
Proof. Each with is in the convex hull of (a point outside the hull has depth 0), so lies in the bounding box of line L19. Line L22 replaces the convex set by . 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 has become a segment or a point. After the loop, is the box intersected with all the halfplanes of Lemma 4, which is . Line L23 stops early when is empty, and then is empty.
Part 3. The centerpoint bound
Theorem 6. For a sample of points in , for .
Proof. By the region property on the halfspace depth page, is the intersection of the closed halfspaces with . For each such , let be the convex hull of the sample points in . Then , and is compact and convex. The sets are subsets of , so the family is finite.
Take any of these halfspaces. Each misses at most indices, so together they miss at most indices. Since , this is less than , so some index lies in all index sets, and lies in all hulls. By Helly's theorem, all the sets have a common point . Then lies in each , so .
In the plane this gives . The bound is tight: for three tight groups of 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 and .
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 of its parameter , and points off the line have depth 0. The deepest set is the median interval, and its midpoint is returned.
Otherwise, , so the property "" holds for all up to and fails above it. Line L13 starts with , and by Theorem 6; is at least . The loop of lines L14 to L16 keeps and , and the interval shrinks in each round, so it ends with . By Lemma 5, line L17 gets , 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 .
Part 5. Cost
. Line L12 sorts projections for each direction: time and space.
Lemma 7. During REGION, each polygon has at most vertices.
Proof. Each edge of lies on a box edge or on a line , and for some sample point , so the line passes through . 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 edges come from the sample, and 4 from the box.
So one clip takes time, REGION takes time, and the binary search calls it times. The total is time and space. This is a simple exact method, not the fastest one; the page lists the faster algorithms.
Complexity
- DEPTH takes time for the sort, then for the loop. This is optimal: Aloupis and others proved an lower bound in 2002.
- TUKEY-MEDIAN as written. . The sorts of line L12 take time and space. Every polygon in REGION has at most 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 time, REGION takes , and the binary search adds a factor . The total is time.
- Faster algorithms. Rousseeuw and Ruts (1998) compute the median in time with HALFMED. Miller and others (2003) compute all the depth contours in time by a topological sweep of the dual line arrangement. Chan (2004) finds a deepest point in the plane in expected time, which is optimal, by his randomized optimization technique (see Chan's randomized optimization). For his algorithm takes expected time.
Properties
- Affine equivariant. for each invertible , 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 the breakdown point is at least , up to rounding, and for samples from an absolutely continuous centrosymmetric distribution it tends to in every dimension. The idea of the lower bound: replaced points change each halfplane count by at most , so while is small the clean points keep a region of depth larger than inside their hull, and no deep point can go far.
- Not unique without a rule. can be a polygon, a segment or a point. The centre of gravity is a convention. Any point of 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 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 over a finite random set of directions is an upper bound on the depth. Exact depth in dimension takes time (Dyckerhoff and Mozharovskyi 2016), and with 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, , 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
atan2puts 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 . Without it, the depth of in the points , , , 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 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 is in every halfplane through , 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 for data in general position falls with . 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 ; in the example the data points have depth at most 2, while .
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.
# 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 depth algorithm in 1996 and the first practical median algorithm in 1998, and Miller and others computed all contours in time in 2003. Chan closed the question of the planar time bound with an expected algorithm in 2004.
References
- 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)
- 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)
- 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)
- 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)
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag ES2QKG Edit this page History Report an error Markdown