Algorithm Search⌘K

Algorithmadvanced

Hammersley sampling for coordinate measurement

Also called Woo-Liang sampling.

Places the N probe points of a measuring machine on a surface patch at the Hammersley points (i/N, radical inverse of i), which have a lower discrepancy than a grid or random points.

Time
Θ(N log N) worst
Space
Θ(1) extra
Where
N = the number of probe points
Properties
deterministicexactofflineiterative
Origin
T. C. Woo, R. Liang, 1993

Hammersley sampling places the probe points of a coordinate measuring machine on a surface patch. For NN points it takes the Hammersley set (i/N,φ2(i))(i/N, \varphi_2(i)), 0≤i<N0 \le i < N, where the radical inverse φ2(i)\varphi_2(i) mirrors the binary digits of ii about the binary point, and maps it from the unit square onto the patch. Woo and Liang proposed it in 1993, after the use of the same set in quasi-Monte Carlo integration. The set has a star discrepancy of O(log⁡N/N)O(\log N / N), against about N−1/2N^{-1/2} for a grid or random points, so averages over the patch, such as the moments of a least-squares fit, are estimated better from the same number of points. This page proves the bound (m+1)/N(m + 1)/N for N=2mN = 2^m and cites the general constant. It also proves two limits: low discrepancy does not mean small holes, and a sample can only underestimate a minimum zone form error. The order in which the probe visits the points is CMM probe path planning.

In plain words

A machine checks a surface by touching it at some points, and each touch takes time. We want few points that still tell us the shape well. A square grid leaves long empty strips between its rows, and it can line up with marks left by the cutting tool. Random points leave clumps and gaps.

The Hammersley points fix this. Number the points from 0. Across the surface, the points go in equal steps. For the other direction, write the point's number in binary and read the digits backward, after a point. Point 1 goes halfway up, point 2 a quarter up, point 3 three quarters up. Each new point lands in a gap left by the earlier ones. When the number of points is a power of two, cut the surface into as many equal strips as there are points: each strip holds exactly one point.

The problem

The input is a number NN of probe points and a surface patch, either a rectangle [x0,x0+w)×[y0,y0+h)[x_0, x_0 + w) \times [y_0, y_0 + h) of a planar face or a parameterized patch S(u,v)S(u, v), (u,v)∈[0,1)2(u, v) \in [0, 1)^2. The output is NN points on the patch, to be measured and then fitted by a reference feature or evaluated for form error. The aim is a point set that represents the whole patch: its star discrepancy

DN∗=sup⁡y∈[0,1]2∣#{points in [0,y1)×[0,y2)}N−y1y2∣D^*_N = \sup_{y \in [0, 1]^2} \Bigl\lvert \frac{\#\{\text{points in } [0, y_1) \times [0, y_2)\}}{N} - y_1 y_2 \Bigr\rvert

in the parameter square should be small. The radical inverse in base bb of i=∑jajbji = \sum_j a_j b^j is φb(i)=∑jajb−j−1\varphi_b(i) = \sum_j a_j b^{-j-1}, as on the Halton sequence page.

The algorithm

  1. HAMMERSLEY-PROBES(N, patch)
  2. 1for i ← 0 to N − 1
  3. 2u ← i / N
  4. 3v ← φ_2(i) ▷ reverse the binary digits of i after the point
  5. 4if patch is a rectangle (x0, y0, w, h) then probe at (x0 + u·w, y0 + v·h)
  6. 5else probe at S(u, v)

Line L3, the radical inverse. The code takes the digits of ii from the least significant one by repeated division and builds φb(i)\varphi_b(i) as an exact fraction. For i<2mi < 2^m, φ2(i)\varphi_2(i) is the mm-bit reversal of ii divided by 2m2^m, so the first 2m2^m values are the multiples of 2−m2^{-m} in a mixed order. For a dimension k>2k > 2, the code puts φbt(i)\varphi_{b_t}(i) for the first k−1k - 1 primes btb_t in the other coordinates.

Lines L4 and L5, the map. A rectangle is an affine image of the square, and the mapped points keep their discrepancy relative to the rectangle. A parameterized patch keeps the points even in (u,v)(u, v), which is even on the surface only when the area element ∣Su×Sv∣\lvert S_u \times S_v \rvert is constant, as on a cylinder in the angle and the height. On other patches, reparameterize by area first, or the points crowd where the map shrinks area.

Example

Eight points on a face. For N=8N = 8 the binary reversal gives

φ2(0),…,φ2(7)=0,12,14,34,18,58,38,78,\varphi_2(0), \dots, \varphi_2(7) = 0, \tfrac12, \tfrac14, \tfrac34, \tfrac18, \tfrac58, \tfrac38, \tfrac78 ,

so the set is (0,0),(18,12),(14,14),(38,34),(12,18),(58,58),(34,38),(78,78)(0, 0), (\frac18, \frac12), (\frac14, \frac14), (\frac38, \frac34), (\frac12, \frac18), (\frac58, \frac58), (\frac34, \frac38), (\frac78, \frac78). On a face of 40×1640 \times 16 mm with a corner at the origin, the probe points are (0,0),(5,8),(10,4),(15,12),(20,2),(25,10),(30,6),(35,14)(0, 0), (5, 8), (10, 4), (15, 12), (20, 2), (25, 10), (30, 6), (35, 14) in mm. Each of the eight columns of width 55 mm and each of the eight rows of height 22 mm holds one point, and so does each cell of the 2×42 \times 4 and 4×24 \times 2 partitions.

Exact discrepancies. The brute force of the tests gives, for N=2mN = 2^m:

mm NN DN∗D^*_N NDN∗N D^*_N proved bound m+1m + 1 cited bound N⋅(72N+log⁡N2Nlog⁡2)N \cdot (\frac{7}{2N} + \frac{\log N}{2N \log 2})
2 4 1/21/2 2 3 4.5
3 8 5/165/16 2.5 4 5
4 16 11/6411/64 2.75 5 5.5
5 32 25/25625/256 3.125 6 6
6 64 55/102455/1024 3.4375 7 6.5

NDN∗N D^*_N grows by less than 0.50.5 when NN doubles, the log⁡N\log N growth. The discrepancy page has a measured table that compares Hammersley points with random points, a grid and the Halton sequence.

Holes. On a grid of 201×201201 \times 201 candidate centers, the largest empty disk inside the square measured for N=64N = 64 has the radius 0.0970.097 for the Hammersley set, and 0.0880.088 for the centered 8×88 \times 8 grid. The Hammersley set is more even on boxes, not on disks.

Correctness

The correctness file proves:

  • The radical inverse. The code computes φb(i)\varphi_b(i), and for i<bmi < b^m it is the reversal of the mm digits of ii divided by bmb^m, a bijection onto the multiples of b−mb^{-m}.
  • The net property. For N=2mN = 2^m, every box [a2−j,(a+1)2−j)×[c2−(m−j),(c+1)2−(m−j))[a 2^{-j}, (a+1) 2^{-j}) \times [c 2^{-(m-j)}, (c+1) 2^{-(m-j)}) of area 1/N1/N holds exactly one point.
  • The bound. For N=2mN = 2^m, DN∗≤(m+1)/ND^*_N \le (m + 1)/N: split an anchored box into strips along the binary digits of its width, and each strip makes an error of less than one point.
  • The cited constant. Niederreiter's Theorem 3.8 gives, in dimension kk with the bases b1,…,bk−1b_1, \dots, b_{k-1},
DN∗<kN+1N∏t=1k−1(bt−12log⁡btlog⁡N+bt+12)=O((log⁡N)k−1N),D^*_N < \frac{k}{N} + \frac{1}{N} \prod_{t=1}^{k-1} \Bigl( \frac{b_t - 1}{2 \log b_t} \log N + \frac{b_t + 1}{2} \Bigr) = O\Bigl( \frac{(\log N)^{k-1}}{N} \Bigr),

which for k=2k = 2, b1=2b_1 = 2 is 72N+log⁡N2Nlog⁡2\frac{7}{2N} + \frac{\log N}{2 N \log 2} for every NN. The file cites it and does not prove it.

  • The brute force over the corners formed by the point coordinates is the exact star discrepancy.
  • Holes. An empty disk inside the square has a radius of at most 2DN∗\sqrt{2 D^*_N}.
  • Underestimation. The minimum zone of a sample is never wider than the minimum zone of the whole surface.
  • The map to a rectangle keeps the discrepancy.
Proof: The radical inverse, the net property of the base-2 Hammersley set, its star discrepancy bound (m + 1)/N for N = 2^m, the size of empty disks, and why a sample never overstates the minimum zonefull

Setup. For an integer base b≥2b \ge 2 and an integer i≥0i \ge 0 with base-bb digits i=∑j≥0ajbji = \sum_{j \ge 0} a_j b^j, 0≤aj<b0 \le a_j < b, the radical inverse is

φb(i)=∑j≥0aj b−j−1.\varphi_b(i) = \sum_{j \ge 0} a_j \, b^{-j-1} .

The NN-point Hammersley set in dimension kk is PN={(i/N,φb1(i),…,φbk−1(i)):0≤i<N}P_N = \{ (i/N, \varphi_{b_1}(i), \dots, \varphi_{b_{k-1}}(i)) : 0 \le i < N \} with b1,b2,…b_1, b_2, \dots the first primes. For a set PP of NN points in [0,1)k[0, 1)^k, the star discrepancy is

DN∗(P)=sup⁡y∈[0,1]k∣#{x∈P:x∈[0,y)}N−∏jyj∣,D^*_N(P) = \sup_{y \in [0, 1]^k} \Bigl\lvert \frac{\#\{x \in P : x \in [0, y)\}}{N} - \prod_{j} y_j \Bigr\rvert ,

where [0,y)[0, y) is the box [0,y1)×⋯×[0,yk)[0, y_1) \times \dots \times [0, y_k).

Lemma 1 (the radical inverse). The code returns φb(i)\varphi_b(i), and it stops after ⌊log⁡bi⌋+1\lfloor \log_b i \rfloor + 1 steps for i≥1i \ge 1. If i<bmi < b^m, then φb(i)=r/bm\varphi_b(i) = r/b^m, where rr is the integer whose mm base-bb digits are those of ii in reverse order. So φb\varphi_b maps {0,…,bm−1}\{0, \dots, b^m - 1\} one to one onto {0,1/bm,…,(bm−1)/bm}\{0, 1/b^m, \dots, (b^m - 1)/b^m\}, and 0≤φb(i)<10 \le \varphi_b(i) < 1 for all ii.

Proof. The loop takes the digits a0,a1,…a_0, a_1, \dots of ii from the least significant one by divmod, and keeps num/den\mathrm{num}/\mathrm{den} with num=a0bt−1+a1bt−2+⋯+at−1\mathrm{num} = a_0 b^{t-1} + a_1 b^{t-2} + \dots + a_{t-1} and den=bt\mathrm{den} = b^t after tt steps, which is ∑j<tajb−j−1\sum_{j < t} a_j b^{-j-1}. It stops when the quotient is 00, after the number of digits of ii. If i<bmi < b^m, pad its digits to length mm; then bmφb(i)=∑j<majbm−1−jb^m \varphi_b(i) = \sum_{j < m} a_j b^{m-1-j}, which is the integer with the digits in reverse order. Reversal of mm digits is a bijection of {0,…,bm−1}\{0, \dots, b^m - 1\}, and r≤bm−1r \le b^m - 1 gives φb(i)<1\varphi_b(i) < 1. □\square

Lemma 2 (the net property). Let N=2mN = 2^m and k=2k = 2 with base 22. For every jj with 0≤j≤m0 \le j \le m and all integers 0≤a<2j0 \le a < 2^j, 0≤c<2m−j0 \le c < 2^{m-j}, the box

E=[a2−j,(a+1)2−j)×[c2−(m−j),(c+1)2−(m−j))E = \bigl[ a 2^{-j}, (a+1) 2^{-j} \bigr) \times \bigl[ c 2^{-(m-j)}, (c+1) 2^{-(m-j)} \bigr)

of area 2−m2^{-m} holds exactly one point of PNP_N.

Proof. Write ii with mm binary digits. The first coordinate i/2mi/2^m lies in [a2−j,(a+1)2−j)[a 2^{-j}, (a+1) 2^{-j}) exactly when the jj leading digits of ii form the number aa. By Lemma 1, φ2(i)=∑t<mat2−t−1\varphi_2(i) = \sum_{t < m} a_t 2^{-t-1}, so its first m−jm - j binary digits after the point are a0,…,am−j−1a_0, \dots, a_{m-j-1}, the m−jm - j trailing digits of ii; and φ2(i)\varphi_2(i) lies in [c2−(m−j),(c+1)2−(m−j))[c 2^{-(m-j)}, (c+1) 2^{-(m-j)}) exactly when those digits, read in this order, form cc. The leading jj digits and the trailing m−jm - j digits are disjoint and together are all mm digits, so exactly one i<2mi < 2^m meets both conditions. □\square

A set with this property is a (0,m,2)(0, m, 2)-net in base 22 in Niederreiter's terms.

Theorem 3 (discrepancy for N = 2^m). For N=2mN = 2^m, the base-2 Hammersley set has DN∗(PN)≤(m+1)/ND^*_N(P_N) \le (m + 1)/N.

Proof. Fix y=(x,z)∈[0,1]2y = (x, z) \in [0, 1]^2 and let AA be the number of points in [0,x)×[0,z)[0, x) \times [0, z). Write x=∑j≥1xj2−jx = \sum_{j \ge 1} x_j 2^{-j} in binary, and let sj=∑t<jxt2−ts_j = \sum_{t < j} x_t 2^{-t}. Then [0,x)[0, x) is the disjoint union of the intervals Ij=[sj,sj+2−j)I_j = [s_j, s_j + 2^{-j}) for the j≤mj \le m with xj=1x_j = 1, and a rest I∞=[sm+1,x)I_\infty = [s_{m+1}, x) of length less than 2−m2^{-m}. Each IjI_j has the form [a2−j,(a+1)2−j)[a 2^{-j}, (a+1) 2^{-j}).

Consider one strip Ij×[0,z)I_j \times [0, z) with j≤mj \le m. Split [0,z)[0, z) into q=⌊z2m−j⌋q = \lfloor z 2^{m-j} \rfloor intervals of length 2−(m−j)2^{-(m-j)} and a rest RR of length less than 2−(m−j)2^{-(m-j)}. Each of the qq boxes is a box EE of Lemma 2, so it holds one point and has area 2−m2^{-m}: count and NN times area agree there. The rest Ij×RI_j \times R lies inside one box EE (or is empty when z=1z = 1 and RR is empty), so it holds 00 or 11 point and has area in [0,2−m)[0, 2^{-m}); there the count and NN times the area differ by less than 11. The strip I∞×[0,z)I_\infty \times [0, z) lies inside a column [a2−m,(a+1)2−m)×[0,1)[a 2^{-m}, (a+1) 2^{-m}) \times [0, 1), a box EE with j=mj = m, so the same holds for it.

Add over the at most mm strips IjI_j and the strip I∞I_\infty: ∣A−Nxz∣<m+1\lvert A - N x z \rvert < m + 1. Divide by NN and take the supremum over yy. □\square

The exact values for m=0,…,6m = 0, \dots, 6 are 1,34,12,516,1164,25256,5510241, \frac34, \frac12, \frac5{16}, \frac{11}{64}, \frac{25}{256}, \frac{55}{1024}, so NDN∗N D^*_N is 1,1.5,2,2.5,2.75,3.125,3.43751, 1.5, 2, 2.5, 2.75, 3.125, 3.4375, below m+1m + 1. They are computed by the brute force of Lemma 4 in the tests.

The general bound (cited). Niederreiter (1992, Theorem 3.8) proves that the NN-point Hammersley set in dimension k≥2k \ge 2 with pairwise coprime bases b1,…,bk−1b_1, \dots, b_{k-1} has

DN∗(PN)<kN+1N∏t=1k−1(bt−12log⁡btlog⁡N+bt+12)=O((log⁡N)k−1N),D^*_N(P_N) < \frac{k}{N} + \frac{1}{N} \prod_{t=1}^{k-1} \Bigl( \frac{b_t - 1}{2 \log b_t} \log N + \frac{b_t + 1}{2} \Bigr) = O\Bigl( \frac{(\log N)^{k-1}}{N} \Bigr),

with the leading constant ∏t(bt−1)/(2log⁡bt)\prod_t (b_t - 1)/(2 \log b_t). For k=2k = 2 and b1=2b_1 = 2 it reads DN∗<72N+log⁡N2Nlog⁡2D^*_N < \frac{7}{2N} + \frac{\log N}{2 N \log 2}, for every NN, not only powers of 22. At N=2mN = 2^m this is (m/2+7/2)/N(m/2 + 7/2)/N, which is sharper than Theorem 3 for m≥6m \ge 6. This file does not prove the general bound; the tests check it against the exact discrepancy for N≤48N \le 48 in two dimensions and for small NN in three.

Lemma 4 (the brute force is exact). For NN points in [0,1)2[0, 1)^2, let XX be the set of first coordinates together with 11, and ZZ likewise. Then

DN∗=max⁡x∈X,  z∈Zmax⁡(xz−A∘(x,z)N,  Aˉ(x,z)N−xz),D^*_N = \max_{x \in X, \; z \in Z} \max\Bigl( xz - \frac{A^{\circ}(x, z)}{N}, \; \frac{\bar A(x, z)}{N} - xz \Bigr),

where A∘A^{\circ} counts the points with p<x,q<zp < x, q < z and Aˉ\bar A the points with p≤x,q≤zp \le x, q \le z.

Proof. If x=0x = 0 or z=0z = 0, the box is empty and has area 00. Otherwise let x′<x′′x' < x'' be consecutive values of X∪{0}X \cup \{0\} with x∈(x′,x′′]x \in (x', x''], and z′,z′′z', z'' likewise. No coordinate lies strictly between x′x' and x′′x'', so a point has p<xp < x exactly when p<x′′p < x'', and exactly when p≤x′p \le x'; the same holds for zz. So on the cell the count AA of [0,x)×[0,z)[0, x) \times [0, z) is constant and equals both A∘(x′′,z′′)A^{\circ}(x'', z'') and Aˉ(x′,z′)\bar A(x', z'). On the cell, xz−A/Nxz - A/N is largest at (x′′,z′′)(x'', z''), which is a candidate of the first kind. And A/N−xzA/N - xz has the supremum Aˉ(x′,z′)/N−x′z′\bar A(x', z')/N - x' z', approached as (x,z)→(x′,z′)(x, z) \to (x', z') from above; if x′=0x' = 0 or z′=0z' = 0 and 00 is not a coordinate, this value is 00, and otherwise (x′,z′)(x', z') is a candidate of the second kind. Every candidate value is attained or approached by local discrepancies, so the maximum equals the supremum. □\square

Lemma 5 (empty disks). If an open disk of radius ρ\rho inside [0,1)2[0, 1)^2 holds no point of PP, then ρ≤2DN∗(P)\rho \le \sqrt{2 D^*_N(P)}.

Proof. For a box B=[u,u′)×[v,v′)B = [u, u') \times [v, v'), the count of BB is A(u′,v′)−A(u,v′)−A(u′,v)+A(u,v)A(u', v') - A(u, v') - A(u', v) + A(u, v) in terms of the counts of anchored boxes, and the area is the same signed sum of the four products. Each of the four terms has an error of at most NDN∗N D^*_N, so the count of BB differs from NN times its area by at most 4NDN∗4 N D^*_N. The disk contains half-open squares of side ss for every s<2ρs < \sqrt 2 \rho, which are empty, so s2≤4DN∗s^2 \le 4 D^*_N for all such ss, and 2ρ2≤4DN∗2 \rho^2 \le 4 D^*_N. □\square

So the Hammersley set leaves no hole larger than 2(m+1)/N\sqrt{2(m+1)/N} for N=2mN = 2^m. This is weaker than the centered N×N\sqrt N \times \sqrt N grid, whose largest empty disk has the radius 1/2N1/\sqrt{2N}. Low discrepancy is a statement about averages over boxes, not about the worst gap.

Lemma 6 (a sample never overstates the minimum zone). Let SS be the surface of a part and Q⊂SQ \subset S the sampled points. For every form tolerance whose zone is a region that must hold the points, the minimum zone width of QQ is at most that of SS.

Proof. Every zone that holds SS holds QQ, so the minimum over the zones that hold QQ is over a larger set. □\square

So a sample can only underestimate the minimum zone form error, and the gap is the error of the sampling. By Lemma 5, a parameter point at distance at least ρ\rho from the edge of the domain has a sample at a distance of at most ρ=2DN∗\rho = \sqrt{2 D^*_N}. So when the deviation from the nominal surface is Lipschitz in the parameters with the constant λ\lambda, the sample underestimates the deviation of a peak away from the edge by at most λρ\lambda \rho.

Least-squares references (cited). The least-squares plane of points spread over a patch depends on the mean and covariance of the points, which are averages of polynomials of the coordinates. For a parameterization S(u,v)S(u, v) with constant area element, these averages are quadrature sums of integrals over the patch, and the Koksma-Hlawka inequality bounds their errors by V(f)DN∗V(f) D^*_N, with VV the variation of the integrand in the sense of Hardy and Krause. This is why a low discrepancy helps the least-squares fit, while Lemma 5 is what matters for the minimum zone.

Lemma 7 (the mapped points). On a rectangle [x0,x0+w)×[y0,y0+h)[x_0, x_0 + w) \times [y_0, y_0 + h), the affine map (u,v)↦(x0+uw,y0+vh)(u, v) \mapsto (x_0 + u w, y_0 + v h) sends each anchored box of the unit square to an anchored box of the rectangle with the same fraction of the area, so the mapped points have the same star discrepancy relative to the rectangle. On a patch S(u,v)S(u, v), the points are even in the parameters, and even on the surface only when the area element ∣Su×Sv∣\lvert S_u \times S_v \rvert is constant.

Proof. The map is a bijection of boxes to boxes that multiplies all areas by whw h and keeps the counts. For a patch, the area of the image of a region UU is ∫U∣Su×Sv∣ du dv\int_U \lvert S_u \times S_v \rvert \, du \, dv, which is a constant times the area of UU for every UU exactly when the area element is constant. □\square

Termination. The main loop runs NN times, and each radical inverse stops by Lemma 1. The brute-force discrepancy loops over at most (N+1)2(N + 1)^2 corners.

Complexity

The radical inverse of ii takes ⌊log⁡2i⌋+1\lfloor \log_2 i \rfloor + 1 divisions on the word RAM, so NN points take Θ(Nlog⁡N)\Theta(N \log N) time. A bit reversal by table lookup, or an update of φ2(i+1)\varphi_2(i+1) from φ2(i)\varphi_2(i) by the carry of the increment, gives O(1)O(1) amortized time per point and Θ(N)\Theta(N) in total. The extra space is Θ(1)\Theta(1) beyond the output. The brute-force star discrepancy used in the tests takes O(N3)O(N^3) time in two dimensions.

Properties

  • Deterministic. The same NN always gives the same points, which makes measurements repeatable.
  • Not extensible. The first coordinate i/Ni/N depends on NN, so the NN-point set is not a prefix of the 2N2N-point set. To add points to a measurement already made, use the Halton sequence, with a discrepancy larger by a factor of order log⁡N\log N.
  • Best order in the plane. By Schmidt's lower bound, cited on the discrepancy page, every NN-point set in the square has DN∗≥clog⁡N/ND^*_N \ge c \log N / N, so the Hammersley set has the best possible order.
  • Exact. The code returns exact fractions.
  • Distinct coordinates. The first coordinates are the NN values i/Ni/N, and for N=2mN = 2^m the second coordinates are the same NN values in another order, so no two points share a row or a column.

Variants and improvements

  • Halton-Zaremba points. Woo, Liang, Hsieh and Lee (1995) compared the Hammersley set with the Halton-Zaremba set, a variant of the second coordinate, and with uniform sampling.
  • Stratification. Lee, Mou and Shen (1997) combined the Hammersley sequence with stratified sampling in sampling strategies for common features.
  • Other low-discrepancy sets. A Sobol sequence or a scrambled net gives the same order. Latin hypercube sampling and stratified sampling are randomized alternatives with one point per row or per cell.
  • Curves and higher dimensions. On a line or a circle, the centered points (i+12)/N(i + \frac12)/N have the least star discrepancy, 12N\frac{1}{2N}, and the order φ2(i)\varphi_2(i) of the one-dimensional radical inverse is useful only to stop early with even coverage. In dimension kk the code uses k−1k - 1 prime bases.
  • Adaptive sampling. Measure a first Hammersley set, fit, and add points where the residuals are large. This targets the peaks that decide a minimum zone.

When to use it

Use it to choose a fixed number of probe points on a planar face or on a patch with a near-constant area element, when the result is a least-squares fit or another average over the surface. It is simple, deterministic and better than a grid on boxes. Use a grid or a hole-minimizing set when the worst gap matters, and an adaptive scheme when the minimum zone form error must not be missed. Use the Halton sequence when the number of points is not known in advance.

Pitfalls

  • Low discrepancy is not small holes. The measured largest hole of 6464 Hammersley points is slightly larger than that of an 8×88 \times 8 grid. A narrow dent can fall between points.
  • A sample underestimates the minimum zone. Every zone of the surface holds the sample, so the form error from the points is never larger than the true one. Report it as a lower bound of the true form error, with the number of points.
  • Distorted maps. On a patch whose area element varies, such as a cone near its apex or a trimmed spline surface, points even in (u,v)(u, v) are not even on the surface.
  • Inaccessible points. Some points may be hard to reach for the probe or may lie on trimmed-away regions. Skip them and record it, or move them by a small amount, but do not silently replace them by a grid.
  • Edge points. The point i=0i = 0 is at the corner (0,0)(0, 0) of the patch, on an edge where a probe can slip. Shift the set by half a step, using (i+12)/N(i + \frac12)/N, or shrink the patch by the probe radius.

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.

hammersley_sampling_for_cmm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hammersley-sampling-for-cmm/. The authors are listed in prov/9X9MZP.jsonl.

"""Hammersley sampling of a surface patch for coordinate measurement.

The Hammersley set of N points in the unit square is (i/N, phi_2(i)) for
i = 0, ..., N-1, where phi_2 reverses the binary digits of i about the
binary point. Woo and Liang (1993) proposed it to place the probe points of a
coordinate measuring machine on a surface. The points are mapped to a
rectangle or through a parameterization of the patch.

All coordinates are exact Fractions. The module also has the exact star
discrepancy of a planar point set by brute force, for checks.
"""

from fractions import Fraction
from math import log

PRIMES = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29)


def radical_inverse(i, base=2):
    """phi_b(i): the base-b digits of i mirrored about the radix point."""
    if i < 0 or base < 2:
        raise ValueError("need i >= 0 and base >= 2")
    num, den = 0, 1
    while i > 0:
        i, digit = divmod(i, base)
        num = num * base + digit
        den *= base
    return Fraction(num, den)


def hammersley(n, dim=2):
    """The n-point Hammersley set in [0, 1)^dim, as tuples of Fractions.

    The first coordinate is i/n and coordinate k + 1 is the radical inverse
    of i in the k-th prime base.
    """
    if n < 1 or not 1 <= dim <= len(PRIMES) + 1:
        raise ValueError("bad n or dim")
    pts = []
    for i in range(n):  # @line L1
        u = Fraction(i, n)  # @line L2
        rest = tuple(radical_inverse(i, PRIMES[k]) for k in range(dim - 1))  # @line L3
        pts.append((u,) + rest)
    return pts


def probe_points_on_rectangle(n, x0, y0, width, height):
    """Hammersley probe points (x, y) on the rectangle [x0, x0+width) x [y0, y0+height)."""
    return [(x0 + u * width, y0 + v * height) for u, v in hammersley(n, 2)]  # @line L4


def probe_points_on_patch(n, surface):
    """Hammersley probe points on a patch surface(u, v) with (u, v) in [0, 1)^2.

    The map should be close to area preserving, or the points crowd where it
    shrinks area.
    """
    return [surface(u, v) for u, v in hammersley(n, 2)]  # @line L5


def star_discrepancy_2d(points):
    """Exact star discrepancy of points in [0, 1)^2.

    D* = sup over boxes [0, x) x [0, y) of |count / N - x y|. The supremum is
    approached at x and y taken from the point coordinates and 1: with open
    boxes from above (count too small) and closed boxes from below (count
    too large). Time O(N^3).
    """
    pts = [(Fraction(x), Fraction(y)) for x, y in points]
    n = len(pts)
    xs = sorted({x for x, _ in pts} | {Fraction(1)})
    ys = sorted({y for _, y in pts} | {Fraction(1)})
    best = Fraction(0)
    for x in xs:
        for y in ys:
            vol = x * y
            open_count = sum(1 for p, q in pts if p < x and q < y)
            closed_count = sum(1 for p, q in pts if p <= x and q <= y)
            best = max(best, vol - Fraction(open_count, n), Fraction(closed_count, n) - vol)
    return best


def niederreiter_bound(n, dim=2):
    """Niederreiter's bound (Theorem 3.8) on the star discrepancy of the
    n-point Hammersley set in the first dim - 1 prime bases:
    dim/n + (1/n) prod_k ((b_k - 1)/(2 log b_k) log n + (b_k + 1)/2)."""
    prod = 1.0
    for k in range(dim - 1):
        b = PRIMES[k]
        prod *= (b - 1) / (2 * log(b)) * log(n) + (b + 1) / 2
    return dim / n + prod / n


def net_bound(m):
    """The bound (m + 1)/2^m for the base-2 Hammersley set of 2^m points,
    proved on the correctness page from the net property."""
    return Fraction(m + 1, 2 ** m)


if __name__ == "__main__":
    for n in (4, 16, 64):
        d = star_discrepancy_2d(hammersley(n))
        print(n, float(d), niederreiter_bound(n))
test_hammersley_sampling_for_cmm.py 197 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hammersley-sampling-for-cmm/. The authors are listed in prov/9X9MZP.jsonl.

import random
import unittest
from fractions import Fraction

from hammersley_sampling_for_cmm import (
    PRIMES,
    hammersley,
    net_bound,
    niederreiter_bound,
    probe_points_on_patch,
    probe_points_on_rectangle,
    radical_inverse,
    star_discrepancy_2d,
)


def digits(i, base):
    """Base-b digits of i, least significant first."""
    out = []
    while i > 0:
        i, d = divmod(i, base)
        out.append(d)
    return out


def radical_inverse_by_definition(i, base):
    """phi_b(i) = sum_j a_j b^-(j+1) for i = sum_j a_j b^j."""
    return sum((Fraction(a, base ** (j + 1)) for j, a in enumerate(digits(i, base))), Fraction(0))


def star_discrepancy_3d(points):
    """Exact star discrepancy in [0, 1)^3 by the same corner argument as in
    two dimensions; time O(N^4)."""
    pts = [tuple(Fraction(c) for c in p) for p in points]
    n = len(pts)
    axes = [sorted({p[k] for p in pts} | {Fraction(1)}) for k in range(3)]
    best = Fraction(0)
    for x in axes[0]:
        for y in axes[1]:
            for z in axes[2]:
                vol = x * y * z
                op = sum(1 for p in pts if p[0] < x and p[1] < y and p[2] < z)
                cl = sum(1 for p in pts if p[0] <= x and p[1] <= y and p[2] <= z)
                best = max(best, vol - Fraction(op, n), Fraction(cl, n) - vol)
    return best


def local_discrepancy(points, x, y):
    n = len(points)
    count = sum(1 for p, q in points if p < x and q < y)
    return abs(Fraction(count, n) - x * y)


class TestDefinition(unittest.TestCase):
    def test_radical_inverse_matches_definition(self):
        for base in (2, 3, 5, 7):
            for i in range(500):
                self.assertEqual(radical_inverse(i, base), radical_inverse_by_definition(i, base))

    def test_small_values(self):
        self.assertEqual([radical_inverse(i) for i in range(8)],
                         [Fraction(k, 8) for k in (0, 4, 2, 6, 1, 5, 3, 7)])
        self.assertEqual([radical_inverse(i, 3) for i in range(4)],
                         [Fraction(0), Fraction(1, 3), Fraction(2, 3), Fraction(1, 9)])

    def test_points_match_definition(self):
        for n in (1, 2, 7, 16, 50):
            for dim in (1, 2, 3, 4):
                pts = hammersley(n, dim)
                self.assertEqual(len(pts), n)
                for i, p in enumerate(pts):
                    self.assertEqual(p[0], Fraction(i, n))
                    for k in range(1, dim):
                        self.assertEqual(p[k], radical_inverse_by_definition(i, PRIMES[k - 1]))
                    self.assertTrue(all(0 <= c < 1 for c in p))

    def test_van_der_corput_permutation(self):
        # The first b^m values of phi_b are the multiples of b^-m in some order.
        for base, m in ((2, 6), (3, 4), (5, 3)):
            n = base ** m
            got = sorted(radical_inverse(i, base) for i in range(n))
            self.assertEqual(got, [Fraction(k, n) for k in range(n)])

    def test_net_property(self):
        # For N = 2^m, every box of the form
        # [a 2^-j, (a+1) 2^-j) x [c 2^-(m-j), (c+1) 2^-(m-j)) holds one point.
        for m in range(0, 8):
            n = 2 ** m
            pts = hammersley(n, 2)
            for j in range(m + 1):
                counts = {}
                for u, v in pts:
                    key = (int(u * 2 ** j), int(v * 2 ** (m - j)))
                    counts[key] = counts.get(key, 0) + 1
                self.assertEqual(len(counts), n)
                self.assertTrue(all(c == 1 for c in counts.values()))


class TestDiscrepancy(unittest.TestCase):
    def test_brute_force_is_a_supremum(self):
        # No sampled box beats the computed value, and the value is attained
        # in the limit, so random boxes come close on small sets.
        rng = random.Random(11)
        for n in (3, 5, 8, 13):
            pts = [(Fraction(rng.randint(0, 99), 100), Fraction(rng.randint(0, 99), 100)) for _ in range(n)]
            d = star_discrepancy_2d(pts)
            for _ in range(2000):
                x, y = Fraction(rng.randint(0, 1000), 1000), Fraction(rng.randint(0, 1000), 1000)
                self.assertLessEqual(local_discrepancy(pts, x, y), d)
            near = max(
                local_discrepancy(pts, Fraction(a, 1000), Fraction(b, 1000))
                for a in range(0, 1001, 1)
                for b in (0, 1000)
            )
            self.assertLessEqual(near, d)

    def test_known_values(self):
        self.assertEqual(star_discrepancy_2d(hammersley(1)), 1)
        self.assertEqual(star_discrepancy_2d(hammersley(2)), Fraction(3, 4))
        self.assertEqual(star_discrepancy_2d(hammersley(4)), Fraction(1, 2))
        # One point at the center of the square: the worst box is [0,1)^2
        # minus the closed quadrant at the point, or the open quadrant.
        self.assertEqual(star_discrepancy_2d([(Fraction(1, 2), Fraction(1, 2))]), Fraction(3, 4))

    def test_niederreiter_bound_2d(self):
        for n in range(1, 49):
            d = star_discrepancy_2d(hammersley(n, 2))
            self.assertLessEqual(float(d), niederreiter_bound(n, 2))

    def test_net_bound(self):
        for m in range(0, 7):
            n = 2 ** m
            d = star_discrepancy_2d(hammersley(n, 2))
            self.assertLessEqual(d, net_bound(m))

    def test_niederreiter_bound_3d(self):
        for n in (1, 2, 3, 5, 8, 12, 16):
            d = star_discrepancy_3d(hammersley(n, 3))
            self.assertLessEqual(float(d), niederreiter_bound(n, 3))

    def test_empty_disk_bound(self):
        # Lemma 5 of the proof page: an empty disk inside the square has a
        # radius of at most sqrt(2 D*). Centers on a fine grid.
        for n in (16, 64):
            pts = [(float(u), float(v)) for u, v in hammersley(n)]
            bound = (2 * float(star_discrepancy_2d(hammersley(n)))) ** 0.5
            worst = 0.0
            steps = 100
            for a in range(steps + 1):
                for b in range(steps + 1):
                    cx, cy = a / steps, b / steps
                    r = min(((cx - x) ** 2 + (cy - y) ** 2) ** 0.5 for x, y in pts)
                    if min(cx, cy, 1 - cx, 1 - cy) >= r:
                        worst = max(worst, r)
            self.assertGreater(worst, 0.0)
            self.assertLessEqual(worst, bound)

    def test_better_than_random_on_average(self):
        # Measured, not a theorem for each seed: 64 Hammersley points against
        # the mean of ten sets of 64 uniform random points.
        rng = random.Random(12)
        d_h = star_discrepancy_2d(hammersley(64))
        rand = []
        for _ in range(10):
            pts = [(Fraction(rng.randint(0, 9999), 10000), Fraction(rng.randint(0, 9999), 10000)) for _ in range(64)]
            rand.append(star_discrepancy_2d(pts))
        self.assertLess(d_h, sum(rand) / len(rand))


class TestProbePoints(unittest.TestCase):
    def test_rectangle(self):
        pts = probe_points_on_rectangle(8, 10, 20, 40, 16)
        self.assertEqual(pts[0], (10, 20))
        self.assertEqual(pts[1], (15, 28))
        self.assertTrue(all(10 <= x < 50 and 20 <= y < 36 for x, y in pts))

    def test_patch(self):
        def cylinder(u, v):
            # A quarter of a cylinder of radius 5 and height 30: the map from
            # (u, v) scales area by a constant, so the points stay even.
            import math

            t = float(u) * math.pi / 2
            return (5 * math.cos(t), 5 * math.sin(t), 30 * float(v))

        pts = probe_points_on_patch(16, cylinder)
        self.assertEqual(len(pts), 16)
        for x, y, z in pts:
            self.assertAlmostEqual(x * x + y * y, 25.0, places=9)
            self.assertTrue(0 <= z < 30)


if __name__ == "__main__":
    unittest.main()

History

Hammersley introduced the point set in 1960 in a paper on Monte Carlo methods for multivariable problems, beside Halton's sequence of the same year. Niederreiter's monograph of 1992 gives the discrepancy bounds with explicit constants and the theory of nets. Woo and Liang brought the set to dimensional metrology in 1993, for the probe points on surfaces measured by a coordinate measuring machine. Woo, Liang, Hsieh and Lee extended the comparison to the Halton-Zaremba set in 1995, and Lee, Mou and Shen combined the method with stratified sampling in 1997.

References

  1. T. C. Woo and R. Liang, Dimensional measurement of surfaces and their sampling, Computer-Aided Design 25(4), 1993, 233 to 239, the proposal of the Hammersley sequence for the probe points of surface measurement and its comparison with uniform sampling
  2. T. C. Woo, R. Liang, C. C. Hsieh and N. K. Lee, Efficient sampling for surface measurements, Journal of Manufacturing Systems 14(5), 1995, 345 to 354, the comparison of the Hammersley and Halton-Zaremba sequences with uniform sampling for surface measurement
  3. G. Lee, J. Mou and Y. Shen, Sampling strategy design for dimensional measurement of geometric features using coordinate measuring machine, International Journal of Machine Tools and Manufacture 37(7), 1997, 917 to 934, sampling strategies for coordinate measurement that combine the Hammersley sequence with stratified sampling
  4. J. M. Hammersley, Monte Carlo methods for solving multivariable problems, Annals of the New York Academy of Sciences 86(3), 1960, 844 to 874, the fixed-size point set with first coordinate i/N and radical inverses in the other coordinates
  5. Harald Niederreiter, Random Number Generation and Quasi-Monte Carlo Methods, SIAM, CBMS-NSF Regional Conference Series in Applied Mathematics 63, 1992, Chapter 2 (star discrepancy, the Koksma-Hlawka inequality), Chapter 3, Theorem 3.8 (the discrepancy bound of the Hammersley point set), Chapter 4 ((t, m, s)-nets)

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