42 Voxels Hinge on One Bit
The same rock from the other side
In a sandstone micro-CT scan, I picked a radius that rounds to 27.2543 micrometers when printed to four decimal places. Then I counted the pore voxel centers within that distance of the rock. SciPy counted 1,521,460. When I evaluated all the candidates with a fixed order for the products and sums, I got 1,521,502. The difference fits in the last binary digit of some of the distances. Once I apply the threshold, it acquires a much more tangible unit. It amounts to 42 pore voxels.
The question started with a different image. In my post on Dice, I compared masks with the same overlap whose contours were wrong in different ways. An island far from the object contributes little to its area and a great deal to its boundary distance. To measure that distance, I usually hand the computer a mask and the pixel spacing in millimeters. This time I wanted to know what happens between that call and the moment I decide whether two contours are close enough.1
I started with a test that needs no reference answer. I reversed the indices along all three axes of the sandstone volume, computed the Euclidean distance transform (EDT), then flipped the result back. Of the eight million values SciPy 1.18.1 returned, 84 changed. All 84 were pore voxels, and in each case the two values were adjacent floating-point numbers. Here I’m comparing SciPy with itself. For the 42 in the title I kept the original orientation and compared two ways of computing the distance. That distinction will matter when we return to the rock.2
Two points that trade places
Take a grid with 12 rows and 11 columns. Rows are 0.8 units apart and columns are 1.1 units apart. I’m at the origin. The marked points are \(P=(0,10)\) and \(R=(11,6)\). With the decimals written on paper, both points are 11 units away. Reaching \(P\) takes ten steps along a row. The two legs of the triangle for \(R\) have lengths 8.8 and 6.6.
On a computer, let \(a\) and \(b\) be the binary numbers actually stored for 0.8 and 1.1. I can treat them as exact fractions and redo the geometry with those fractions. The difference between the squared costs of \(R\) and \(P\) factors neatly. If \(\Delta=(11a)^2+(6b)^2-(10b)^2\), then
\[ \Delta=(11a-8b)(11a+8b). \]
The second factor is positive. The first is \(-1/2^{52}\). So \(R\) is strictly closer in the geometry defined by the stored spacings. Now I’ll do the products and the addition with ordinary 64-bit float operations.
from fractions import Fraction
from math import ulp
a, b = 0.8, 1.1
print(11 * Fraction(a) - 8 * Fraction(b))
def squared_distance(row, col):
x, y = row * a, col * b
return x * x + y * y
p = squared_distance(0, 10)
r = squared_distance(11, 6)
print(p, r)
print((r - p) / ulp(p))
The costs come out as 121.0 for \(P\) and 121.00000000000003 for \(R\). Near 121, one ulp (unit in the last place) is the step to the next representable number, about \(1.42\times10^{-14}\). The two results are two such steps apart. If I first pick the geometrically nearest neighbor and only then evaluate its floating-point cost, I’ve already discarded the point that would give the smaller answer.
The same reversal is possible with numbers that have exact binary representations. In a \(2\times3\times2\) mask, take spacings \((2^{27},3/4,11/8)\) and mark \(P=(1,1,1)\) and \(R=(1,2,0)\). At the origin, write \(A=2^{54}\). The exact costs are \(A+157/64\) for \(P\) and \(A+144/64\) for \(R\). Again \(R\) wins. But the next representable number above \(A\) is \(A+4\). For \(P\) I first add \(9/16\) to \(A\) and round back to \(A\). Then I add \(121/64\) and round back to \(A\) a second time. For \(R\) I add \(9/4\) in one go and round up to \(A+4\). Even the individual squares are exactly representable here. I can trace the reversal to the additions. A routine returning every tied geometric neighbor would still give me only \(R\), because the geometric minimum is strict.
A distance I can reproduce
To specify what I want to compute, I’ll use \(\rho\) for rounding to the nearest binary64 number, ties to an even significand, and \(u=2^{-53}\) for the unit roundoff. For integer displacement \(k\) and stored spacing \(h>0\), define the squared contribution
\[ T_h(k)=\rho\!\left(\rho(hk)^2\right). \]
Subtract the indices while they’re still integers. Multiply by the spacing, round, square, and round again. To evaluate the cost of a marked point \(p\) at query \(q\), start with \(A_0=0\) and add axes in array order. On axis \(\ell\), with displacement \(k_\ell=q_\ell-p_\ell\), compute
\[ A_\ell=\rho\!\left(A_{\ell-1}+T_{h_\ell}(k_\ell)\right). \]
For \(m\) axes, the squared EDT value I’ll study is \(d(q)=\min_p A_m(p,q)\). If the application wants a distance in meters, return \(\rho(\sqrt{d(q)})\). An image with no marked site gets \(+\infty\) everywhere. Addition order is as much a part of that definition as the choice to measure between voxel centers.3
That definition already predicts the reflection test. On an axis of length \(n\), indices \(q,p\) become \(n-1-q,n-1-p\). Their difference changes sign and \(T_h(-k)=T_h(k)\). Each candidate offers the same cost, with every term added at the same step. The argument works for any subset of axes, even if several sites tie. An integer translation of every site and the query also preserves the value when the translated grid retains every site. Adding a marked point can only preserve or lower the minimum. Permuting the axes changes the addition order. On the sandstone itself, a cyclic permutation changed 44,072 of the square roots of the enumerated costs after restoring the original coordinates.
How far can this definition take us from the geometry? Let \(R(p,q)\) be the real sum of squares using the stored spacings, \(R_1\) the smallest of these costs and \(R_2\) the second smallest. Write \(L_m=(1-u)^{m+2}\) and \(U_m=(1+u)^{m+2}\). Under the scale conditions below, each positive term is normal. The rounding of the scaled displacement enters twice when we square it, the square itself rounds once, and at most \(m-1\) nontrivial additions follow. All terms are nonnegative, so the factors bound the individual contributions and then the sum. In particular,
\[ L_m R_1\le d(q)\le U_m R_1. \]
The same pair of bounds holds for each candidate. If \(U_mR_1<L_mR_2\), the geometric winner is also the unique rounded winner. This gives a sufficient gap one can check in real arithmetic. There’s also a particularly good control for debugging. At unit spacing, if \(\sum_\ell(n_\ell-1)^2\le 2^{53}\), all offsets, squares and partial sums are exactly representable integers. The two objectives then agree even in the presence of ties.
Discarding parabolas without losing the minimum
Trying every solid voxel for every pore voxel would make an expensive distance map. A separable EDT works on one line at a time. Once the preceding axes are done, \(f_p\) holds the smallest accumulated cost at position \(p\). For spacing \(h\), the real parabola and the value I actually want to compare at an integer query \(q\) are, respectively,
\[ g_p(q)=f_p+h^2(q-p)^2,\qquad F_p(q)=\rho(f_p+T_h(q-p)). \]
The classical method of Felzenszwalb and Huttenlocher uses the fact that all the parabolas have the same curvature. The difference between any two is a straight line. Keep the sites on the lower envelope in order, together with the position where each starts to beat its predecessor. Each site enters the stack once and can leave once. A forward sweep then reads off the answer in linear time. This construction accepts general initial costs.4 For binary masks there are also linear-time algorithms for arbitrary dimension, including grids with different spacings on each axis.5
Here is how the floating-point stack is built. The stored coordinate is \(X_i=\rho(hi)\) and the intercept is \(C_i=\rho(f_i+\rho(X_i^2))\). For two candidates \(i<j\), compute \(N=\rho(C_j-C_i)\) and \(D=2\rho(X_j-X_i)\). The stored intersection is \(b_{ij}=\rho(N/D)\). The straight line uses two separately rounded physical coordinates. The evaluation of \(F_i(q)\) starts with the integer difference \(q-i\). Moving between these expressions is where we can lose the candidate we care about.
The margin below depends on the length and scale of the line. Assume \(1\le n\le2^{40}\), finite costs between zero and a representable upper bound \(B\), with \(+\infty\) also allowed, and a spacing between the binary64 values of \(10^{-100}\) and \(10^{100}\) inclusive. Compute \(G=\rho(B+T_h(n))\) and accept the line only if \(\rho(G/h)\le\rho(10^{300})\). The margin is \(\tau=\rho(\rho(2^{-46}G)/h)\) in physical position units. I assume separately rounded operations, gradual underflow, nontrapping IEEE exceptions, valid indices and inputs preserved throughout the calculation. Fusing a multiply and an add evaluates a different expression. On the first axis of a mask \(B=0\). Finishing an axis of length \(n^{\prime}\) and spacing \(h^{\prime}\) updates the upper bound to \(\rho(B+T_{h^{\prime}}(n^{\prime}-1))\).
On the stack, \(v_i\) holds a site index and \(b_i\) its crossing with the preceding site. The first site enters with \(b_0=-\infty\). When inserting a site, compare its \(N,D\) with the top entry. Keep the top if \(N>\rho(\rho(b_i-\tau)D)\), otherwise pop it and repeat. Allowing a candidate to survive near a crossing also allows the \(b_i\) to fall out of increasing order. For queries I need two small arrays. Let \(z_i\) be the largest crossing through slot \(i\), and \(m_i\) the smallest crossing from slot \(i\) to the end.
For query \(x=X_q\), advance the cursor while \(z_{j+1}<x\) and evaluate \(F_{v_j}(q)\). Look left while \(z_{i+1}\ge\rho(x-\tau)\) and right while \(m_i\le\rho(x+\tau)\). Return the smallest evaluated cost. Two things could go wrong. A point could disappear during construction, before the query is even considered. It could also survive and lie beyond the place where the scan stops. The proof has to rule out both.
The 32-tolerance mask
Before proving anything about the stack, consider one tempting explanation of \(\tau\). If it covered the rounding error in every crossing, checking neighbors within one tolerance would seem sufficient. A mask with two rows and two marked sites lets us test that idea on paper.
Take a \(2\times8194\) mask, with spacing \(2^{50}\) between rows and \(h=1+2^{-40}\) between columns. Mark \((0,8192)\) and \((1,8193)\). After the first pass the only finite costs on row zero are \(0\) and \(B=2^{100}\). Writing \(p=8192\), the real parabolas cross at physical position
\[ s=\frac{B}{2h}+h(p+\tfrac12). \]
Near \(hp\), representable numbers are \(2^{-39}\) apart. The real product \(h(p+1)\) lands halfway between \(X_p+1\) and its successor. The former has an even significand. Consequently \(X_{p+1}=X_p+1\) and the stored denominator is exactly \(D=2\). The squares of the two coordinates are below \(2^{28}\). The smaller half-gap between \(B\) and its neighbors is \(2^{46}\). Adding the right coordinate’s square to \(B\) rounds back to \(B\), as does subtracting the left one’s square. This gives \(N=G=B\). Thus \(b=2^{99}\) and \(\tau=\rho(2^{54}/h)\).
The error is \(b-s=2^{59}/h-h(p+\tfrac12)\). I can compare it with the tolerance without subtracting two huge float values. This snippet uses fractions for the real crossing and for the final difference. The operations that build the stack crossing stay in float.
from fractions import Fraction
p = 8192
h = 1.0 + 2.0**-40
B = 2.0**100
left, right = h * p, h * (p + 1)
N = (B + right * right) - left * left
D = 2 * (right - left)
b = N / D
extent = h * (p + 2)
tau = (2.0**-46 * (B + extent * extent)) / h
H = Fraction(h)
s = Fraction(B) / (2 * H) + H * Fraction(2 * p + 1, 2)
ratio = abs(Fraction(b) - s) / Fraction(tau)
print(Fraction("31.99") < ratio < 32)
The answer is True. Both crossings lie far beyond column 8193. In the CPU and GPU passes, all 16,388 outputs agreed bit for bit with enumeration. A crossing displaced by nearly \(32\tau\) can coexist with an entire image of correct answers. I can also move the site to \(p=2^k\) and use \(h=1+2^{k-53}\). The plot shows the ratio computed with fractions for each mask, without allocating the larger images.
Each point uses two candidates. The vertical axis measures displacement from the real crossing in units of the stack’s internal margin. The dashed line marks one tolerance. The diamond is the mask with 8,194 columns.
What I can bound inside the grid
Fix a query \(q\). Its answer depends on the sign of \(F_j(q)-F_i(q)\) for the candidates competing there. With \(x=X_q\), I can compare that difference with \(N-Dx\), evaluating the affine expression in real arithmetic on the stored operands. To get the scale of the error, write \(H=hn\) and \(S=uG/h\). In the computation of \(G\), the rounding of \(hn\) enters twice in the square, followed by rounding the square and the sum with \(B\). Hence \(G\ge(1-u)^4(B+H^2)\). Multiplication by \(2^{-46}=128u\) is exact in this range. Division by \(h\) gives \(127S\le\tau\le129S\).
For one candidate \(p\), compare \(F_p(q)\) with \(f_p+h^2(q-p)^2\), and \(C_p\) with \(f_p+(hp)^2\). Each discrepancy costs less than \(5uG\). Replacing \((hq)^2-2(hp)(hq)\) with \(x^2-2X_px\) costs less than \(7uG\). At zero displacement, the sum preserves the value of \(f_p\), even for subnormal input. Every nonzero displacement has a normal square over the allowed spacing range. Putting the terms together gives
\[ \left|F_p(q)-(x^2+C_p-2X_px)\right|<20uG. \]
Subtract the estimate for \(i\) from the one for \(j\) and the common \(x^2\) disappears. The two estimates together cost less than \(40uG\). Rounding \(C_j-C_i\) costs at most \(uG\), and rounding the coordinate difference in the denominator costs less than \(2.01uG\) after multiplication by \(x\). Also \(X_j-X_i\ge h(1-2un)\), so \(D>1.99h\) under the line-length limit. This is the inequality I’ll use for the stack,
\[ \bigl|(N-Dx)-(F_j(q)-F_i(q))\bigr|\le44uG. \]
What about the error in the physical crossing itself? For the real numerator and denominator \(N^{\ast},D^{\ast}\), write \(N^{\ast}=D^{\ast}s\). The quotient error contains a term \(|D-D^{\ast}|\,|s|/D\). If \(|s|\le H\), the denominator discrepancy multiplied by \(|s|\) is below \(6.01uG\), and the numerator discrepancy is below \(11uG\). After rounding the quotient this gives \(|b-s|<10S<0.079\tau\). Inside the sampled interval I can indeed bound the crossing error by a small fraction of the margin. In the 32-tolerance mask, the factor \(|s|\) grows because the intersection is an extrapolation. The comparison bound at \(q\) holds in either case.
Why a minimizer survives and gets visited
Let \(E\) bound the comparison error, let \(d_0\) be a positive lower bound on \(D\), and put \(r=E/d_0\). This puts \(r\) in position units. Write \(e_b\) for the error in storing \(N/D\), \(e_c\) for rounding the cutoff \(b-\tau\), \(De_p\) for a bound on the error in multiplying that cutoff by \(D\) when the product is finite, and \(e_x\) for rounding the scan endpoints \(x\pm\tau\). The stack argument needs these two margins,
\[ \tau>2r+e_b+e_c+e_p,\qquad \tau\ge r+e_b+e_x . \]
For the first one, pick any minimizing site \(w\) at \(q\), including a tied site. For \(a<w\), we have \(F_w(q)-F_a(q)\le0\). For \(t>w\), we have \(F_t(q)-F_w(q)\ge0\). Applying the comparison bound to both signs, dividing by \(D>0\) and allowing for rounding the crossing gives two one-sided bounds,
\[ b_{aw}\le x+r+e_b,\qquad b_{wt}\ge x-r-e_b. \]
After \(w\) enters the stack, the site immediately below it stays there until someone pops \(w\). Suppose a new site \(t\) attempts to do that. The computed cutoff satisfies \(c\le x+r+e_b-\tau+e_c\). For the pair \((w,t)\) we have \(N-Dx\ge-E\). Therefore \(N-cD\ge-E+D(\tau-r-e_b-e_c)>De_p\). Even after rounding the product, the test keeps \(w\). A product overflowing to \(-\infty\) also keeps it. Positive overflow would contradict \(cD<N\) with finite \(N\). The bottom entry is protected by its \(-\infty\) sentinel.
The stack is now finished, but the cursor may have stopped on the far side of the minimizer. If \(w\) is to its left, every prefix maximum tested on the way includes the crossing of \(w\) with its right neighbor, which is at least \(x-r-e_b\). The left scan keeps going. If \(w\) lies to the right, every suffix minimum along the way includes its entry crossing, at most \(x+r+e_b\). The right scan reaches it too. The second margin covers rounding at the two endpoints. The starting candidate is always evaluated.
For this pass, \(r=44uG/(1.99h)<23S\). Rounding the quotient costs less than \(S\), the cutoff and product allow \(e_c=e_p=2S\), and \(e_x=3S\) covers the scan thresholds. The respective budgets are below \(51S\) and \(27S\). The line has at least \(127S\) available. This gives the numerical tolerance a demonstrable job. A minimizer survives construction and reaches the final comparison at the query it minimizes.
One step remains from a line to an image. On the first axis of a mask, the costs are zero or infinity. Two integer sweeps find the smallest displacement, and \(T_h\) is nondecreasing in \(|k|\). On each remaining axis, for fixed \(t\ge0\), the mapping \(a\mapsto\rho(a+t)\) is also nondecreasing. Minimizing along the previous axes before adding the current contribution therefore returns the same value as enumerating all sites. A later addition can tie previously distinct partial costs, so recovering every globally tied site index would take a separate argument. A line with no site stays at \(+\infty\) throughout, and images in a batch are independent.
A five-sample line puts the assumption about exceptions to work. Take \(f=(0,2^{1023},+\infty,+\infty,2^{1023})\), \(h=2^{50}\) and \(B=2^{1023}\). The line passes the scale check. During construction, a product in the pop comparison can overflow and set the overflow flag. With nontrapping IEEE behavior, the five outputs are \((0,1,4,9,16)\,2^{100}\), exactly what enumeration gives. Looking only at the output map could make two different checks seem interchangeable here. Every returned value is finite, yet an intermediate operation can overflow.
A winning site can even move backward
There is another reason to fix a single query in the proof. In real arithmetic, as the query moves right, the winning site index on the envelope moves right or stays put. Take two sites, \((0,0,0)\) and \((1,1,1)\), with spacings \((2^{14}+2,2^{14}-2,1)\). Write \(J=2^{28}\). At query \((0,0,x)\) the first cost is \(\rho(x^2)\) and the second is \(\rho(2J+8+\rho((x-1)^2))\). Squaring and adding the first two spacings accounts for the constant \(2J+8\).
Near \(J^2\) one ulp is 16. At \(x=J+3\) the second site wins by one ulp. Advance to \(x=J+4\) and the first site wins by one ulp. In real geometry the first site is closer at both queries. It takes only a few lines to check those four values, without allocating an image with more than 268 million columns.
from math import ulp
J = 2**28
for x in (J + 3, J + 4):
first = float(x * x)
previous_square = float((x - 1) ** 2)
second = float(2 * J + 8) + previous_square
print(x - J, (second - first) / ulp(first))
The output is 3 -1.0 followed by 4 1.0. In the cost matrix for these two rows and columns, the strict minimum moves from column 2 to column 1. That submatrix violates the total monotonicity used by linear-time row-minimum search algorithms. That classical route to linear time would need an additional hypothesis for this arithmetic. A reversal at two queries, on its own, establishes no quadratic lower bound for the problem.6
The price of looking one site farther
The stack, prefix maxima and suffix minima take \(O(n)\) space. Construction and cursor advancement cost \(O(n)\) operations. What’s left to count is the work of inspecting neighbors. Let \(K\) be the number of these extra evaluations over all queries on a line. Total work is \(O(n+K)\). The width of the margin and how far the crossings fall out of order determine whether \(K\) stays small.
I can estimate \(K\) from the finished stack alone. Put \(\delta=h(1-2un)>0\) and \(a=\tau+3S\). With \(k+1\) candidates there are \(k\) edges between consecutive candidates. Each extra evaluation crosses exactly one edge. Crossing edge \(t\) to the left requires \(z_t<x\le z_t+a\). Crossing it to the right requires \(m_t-a\le x\le z_t\). The union spans an interval of length \(z_t-m_t+2a\). Consecutive queries are at least \(\delta\) apart, so I can count how many fit and sum over the edges,
\[ K\le k+\frac{2ka+\sum_{t=1}^k(z_t-m_t)}{\delta}. \]
If the crossings are ordered, \(z_t=m_t=b_t\). A uniform bound on \(a/h\) is then sufficient for linear work. When crossings fall out of order, the sum accounts for how much wider the region to search becomes at each edge.
Two dense examples give the bound some scale. First take a fully marked \(1\times n\) unit-grid mask. On the final axis all initial costs are zero, the crossings at the lengths considered here are the half-integers \(t-1/2\), and through \(n=2^{22}\) the margin \(2^{-46}n^2\) is at most \(1/4\). No query reaches a neighbor. For \(n=2^r\) through \(r=26\), the window endpoints are still representable. With \(g=\min(n-1,\lfloor\tau+1/2\rfloor)\), the exact count after truncating at the ends is \(K=2ng-g(g+1)\). At \(n=2^{26}\) each interior query visits 128 neighbors beyond its starting site. The grid still has unit spacing.
For the second example, mark every point of a \(2\times n\) mask with spacings \((2^{100},1)\). Every \(f_p\) on the final axis is zero, but the preceding axis supplied an upper bound of \(B=2^{200}\). This gives \(G=B\) and \(\tau=2^{154}\). All finite crossings lie between zero and \(2^{80}\). Every site survives. At every query the rounded window endpoints are \(-\tau\) and \(+\tau\). Each of the \(n\) queries visits exactly \(n\) candidates. The minimum at every position is zero and its winner is unique. The quadratic work in this pass comes from the scale bound it inherited.
Mean cost evaluations per query, including the starting candidate. The left panel shows measurements on lines of 64, 128 and 256 samples. The right panel shows the count derived from the unit-grid formula. Both vertical scales are logarithmic.
I also measured time. Visiting the same number of sites can have quite different memory costs. I compiled three line routines for the same CPU, the stack with a margin, a contiguous enumeration with precomputed squares, and the envelope that evaluates a single site. Each batch contained 64 lines. I pinned one logical core on a Ryzen 9 5900XT, used GCC 15.2 with -O3, and disabled floating-point contraction. Timing started after scratch allocation and included table or tolerance setup and output writes. After three warm-ups I balanced the six possible orders of the routines over twelve repetitions. The medians below are in milliseconds.
| Lines and length | Stack with margin | Enumeration | One candidate |
|---|---|---|---|
| Bernoulli, 64 | 0.0221 | 0.0679 | 0.0149 |
| Bernoulli, 256 | 0.135 | 1.04 | 0.113 |
| Bernoulli, 1,024 | 0.639 | 15.9 | 0.582 |
| Dense anisotropic, 64 | 0.220 | 0.0867 | 0.0129 |
| Dense anisotropic, 256 | 2.89 | 1.40 | 0.0487 |
| Dense anisotropic, 1,024 | 44.2 | 21.9 | 0.195 |
The Bernoulli masks had site probability 0.02 and spacings \((0.7,1.1)\). Across the three instrumented widths in the figure, the pass averaged 1.012 to 1.017 evaluations per query. In the anisotropic family, walking the entire stack cost more than contiguous enumeration. On the sandstone, I counted 378,178 extra evaluations on the second axis and 574,905 on the third, each with eight million queries. For the full final-axis batch I measured medians of 55.3 ms with the stack and 540.5 ms with enumeration. Those timings cover the last pass on this machine. The one-candidate routine produced the right answer on every timed input, although it fails on other inputs with the same definition of cost.
I also timed complete maps on three 2D masks (128, 256 and 512 samples per side) and three 3D masks (32, 64 and 96 per side). Site probability was 0.02, two opposite corners were set as sites, and the inputs were already in memory. This clock included output allocation and the square root so that both calls returned distances. On the square with side 512, the medians were 4.40 ms for the compiled stack and 11.08 ms for SciPy. On the cube with side 96 they were 28.11 and 72.46 ms. The ratio between medians ranged from 2.23 to 2.94 on the six inputs. Array layout and the cost of producing the complete map now enter the measurement. To attribute a cost to the margin, I go back to the experiment above, which used one compiler and isolated the last pass.
What the tests can distinguish
To check a comparison, I used a rational oracle that rounds back to binary64 after each operation. Rounding just once at the end would test a different specification. I ran every \(2\times3\) mask at four spacings and every \(2\times2\times2\) mask at three. That makes 1,024 mask–spacing combinations, including empty masks, decimal spacings and extreme anisotropy that passes the range checks. The CPU and GPU passes and a separate enumeration agreed with all 7,680 reference values. I also inspected the instructions for the tested GPU kernel, on an RTX 5070, to check that the relevant operations rounded separately. This records the environment in which I measured the results.
Two six-pixel examples isolate a tie at a crossing. Mark \((1,0)\) and \((0,2)\) in a \(2\times3\) mask with spacings \((2^{-26},1)\). After the first axis, row zero contains \((2^{-52},+\infty,0)\). At column 1, the left candidate costs \(1+2^{-52}\) and the right costs \(1\). The stored crossing is exactly 1 because \(\rho(4-2^{-52})=4\). Reflect the columns and the left site wins. The crossing is still 1 because \(\rho(4+2^{-52})=4\) as well. Any fixed choice of side at equality loses one of these examples. In another line of 749 samples, with four finite input costs and \(h=\rho(0.3)\), the unguarded envelope discards site 728 and returns site 729 at \(q=119\). The cost is one ulp high. This time it is construction that loses the candidate.
To measure those two decisions separately, I removed the margin either when popping a candidate or when inspecting neighbors. I reused the same 512 masks of size \(24^2\) at five spacings and 256 masks of size \(10^3\) at three. Site probabilities were 0.08 and 0.05, respectively, with the first voxel always marked. Each axis received the enumerated result of the preceding one. An error in one pass could therefore never enter an input whose errors I was about to count. The table counts queries after the first axis.
| Pass variant | Costs differing from enumeration in 3,010,560 queries |
|---|---|
| Conventional envelope, one candidate | 3,895 |
| No margin when popping from the stack | 107 |
| No margin when scanning neighbors | 2,554 |
| Both margins in place | 0 |
Those 2,554 differences were far from uniform. At \((0.1,0.3)\), removing the scan margin gave 1,688 differences and removing only the pop margin gave zero. At \((0.3,0.3,0.3)\) the respective counts were 825 and 104, all on the last axis among 256,000 queries. At unit spacing both ablations got every tested query right. The scan without a margin still evaluated the neighbor at equality. The two tie examples explain one failure, and the counts show why fixing equality alone leaves others.
Back to the 42 voxels
The Berea segmentation distributed with the OpenPNM network extraction example contains \(200^3\) voxels, with isotropic spacing stored from \(5.345\times10^{-6}\) meters. Of the eight million voxels, 1,589,722 are pores.7 I measured from center to center, with every solid voxel a candidate. This same convention has been used to study pore-size distributions in digitized sandstone.8 Here I’m counting the pore centers in a layer next to the rock. Multiplying the count by the volume of one voxel gives the layer volume in this discrete model.
I also asked SciPy for neighbor indices with return_indices=True. That lets me recompute the cost of the site it chose before taking a square root. On the original image, 415 of those squared costs exceeded the enumerated minimum, by at most two ulps. After the square root, 53 distances still differed. Taking the rounded root of the chosen site’s cost reproduced every SciPy distance. I also checked 32 randomly selected pore queries per spacing and eight diagnostic queries at the acquisition spacing with the rational calculation. Flipping the image changed 84 of SciPy’s own roots. Enumeration preserved all of them, as the sign-of-the-offset argument predicts. At unit spacing the comparisons agreed. Adding the same 1,024 randomly chosen pore voxels to the solid sites never increased a distance either.
Because this volume is isotropic, there’s a third practical convention. I can compute a unit-grid EDT and multiply the returned distance by \(h\) at the end. On this volume the result preserved both reflection and cyclic permutation. It still differed from the square root of the fixed-axis-order cost at 129,095 voxels. The geometry stayed the same throughout. What changed was where I introduced the physical spacing into the calculation.
An entire shell at one radius
For a radius \(t\), define \(C(t)\) as the number of pore centers whose distance to the nearest solid center is less than or equal to \(t\). The first four radii I tried, one, two, five and ten voxel widths, gave identical counts. After observing differences in the maps, I specified a second analysis before computing any more counts. On an isotropic grid, integer offsets whose squares sum to \(j\) occupy one shell. I took every attainable \(j\) up to the deepest pore voxel and used \(t_j=\rho(h\sqrt j)\) with one rounding. I checked each threshold by comparing \(h^2j\) as a fraction with the squared midpoints between adjacent floating-point numbers. This kept an extra rounding from creeping into the ruler I was using for the comparison.
At each radius I subtracted the SciPy count from the enumerated count on the original image. Blue circles mark agreement. Purple diamonds mark the six radii where the counts differ. The spacing was supplied in meters.
At the largest discrepancy, \(j=26\), all 8,310 voxels on the shell lie at the same geometric distance from the rock. The stored value \(t_{26}\) falls just below the real value of \(h\sqrt{26}\). In fact \(\lfloor t_{26}^2/h^2\rfloor=25\) when I use the stored values and compare them in real arithmetic. An integer rule including shells \(j\le26\) counts all 8,310. A geometric comparison with the stored physical radius excludes all 8,310. Here is what happened between those two endpoints.
| Rule applied to the volume | Included on shell 26 | Cumulative count |
|---|---|---|
| Integer grid, including the shell | 8,310 | 1,526,066 |
| Real geometry at the stored radius | 0 | 1,517,756 |
| Enumeration in axis order | 3,746 | 1,521,502 |
| SciPy on the original image | 3,704 | 1,521,460 |
| SciPy after reflecting all three axes | 3,721 | 1,521,477 |
Between enumeration and SciPy on the original image, the difference is 0.00264 percentage points of the pore space. Reflection added a net 17 voxels to SciPy’s own count at this radius. At 41 of the 163 radii, enumeration and SciPy both fell below the inclusive integer rule. The largest shortfall was 14,109 voxels on shell \(j=6\), where the two floating-point calculations agreed. Looking only for a discrepancy between methods would have hidden the threshold choice with the largest effect on the count.
Berea slice 109 and a 25 × 25 voxel crop. The dark phase is rock. In the crop, blue marks pores included by both calculations and white marks pores excluded by both. Enumeration includes the circled purple voxel. Distances were computed on the three-dimensional volume. Data from OpenPNM.
The 42 voxels lie in 36 of the 200 planes perpendicular to the first axis. I marked the one nearest the center of the volume, \((109,116,97)\) in zero-based coordinates. It’s the only one in this plane. Its three geometrically nearest solid neighbors are \((108,111,97)\), \((108,112,100)\) and \((109,111,98)\). SciPy returned the first. The offsets have the same integer squared length, 26. We can work out what each one contributes to the inclusion test.
from math import sqrt, ulp
h = 5.345e-6
radius = float.fromhex("0x1.c9402701c6e0cp-16")
for offset in ((1, 5, 0), (1, 4, -3), (0, 5, -1)):
cost = 0.0
for step in offset:
x = step * h
cost += x * x
distance = sqrt(cost)
print(offset, (distance - radius) / ulp(radius), distance <= radius)
The three rows give 1.0 False, 0.0 True and 1.0 False for the distance in ulps above the radius and the corresponding decision. Hexadecimal preserves the precise threshold used in the image. At all 42 voxels, enumeration gave 0x1.c9402701c6e0cp-16 and SciPy gave 0x1.c9402701c6e0dp-16. The last hex digit changes from c to d, or from 1100 to 1101. Here “one bit” is literal. Move the threshold to the representable number immediately below and both calculations count 1,517,756 voxels. One step above the original threshold, both count 1,526,066. This measures the change in a layer defined by that particular ruler. Measuring permeability would also require a transport calculation through the volume.
What this changes at a segmentation boundary
To get closer to the question that prompted the test, I used five public clinical volumes with reference masks and acquisition spacings that differed between axes. I took a tight crop of each labeled region, added one layer of background and measured the distance from each interior voxel to the nearest background center. I kept the original orthogonal spacings. The table counts foreground voxels whose returned distance changed. “Original” compares the root of the fixed-order minimum with SciPy. The last two columns compare each calculation with itself after undoing a cyclic permutation.9
| Mask | Interior voxels | Original | Permutation, axis order | Permutation, SciPy |
|---|---|---|---|---|
brain1 | 4,137 | 0 | 0 | 0 |
brain2 | 453 | 0 | 0 | 0 |
breast1 | 143 | 0 | 0 | 0 |
lung1 | 837 | 0 | 0 | 0 |
lung2 | 24,644 | 1 | 440 | 442 |
Only lung2 differed in the original orientation, by one ulp at one voxel. SciPy also changed one root under reflection in this mask. Fixed-order evaluation preserved all roots under reflection in all five images. The hundreds of changes under permutation in lung2 answer a different question, since permuting axes changes which term is added first.
One pixel can move a score from 0.25 to 0.50
Take two nonempty boundaries \(U,V\). Count the queries from \(U\) to \(V\) whose distance is at most \(t\), do the same from \(V\) to \(U\), and divide the sum by \(|U|+|V|\). Each pixel gets one vote. The surface Dice used by Nikolov and colleagues weights surface elements by their area. I chose centers and unit weights here so I could follow each vote individually.10
In a \(5\times9\) mask, take \(U=\{(4,3)\}\) and \(V=\{(0,0),(0,6),(4,8)\}\). Use isotropic spacing stored from 1.1 and a threshold \(t=5.5\), with zero relative margin. In grid units the three destinations are all exactly five Euclidean units away. The horizontal offset to \((4,8)\) gives a squared cost of 30.25. The offsets with legs 4 and 3 give the number two representable steps above 30.25. Their rounded square roots are 5.5 and its successor. Here’s what SciPy does on each of the four queries.
from scipy.ndimage import distance_transform_edt
u = [(4, 3)]
v = [(0, 0), (0, 6), (4, 8)]
def scipy_hits(queries, sites):
mask = [[1] * 9 for _ in range(5)]
for row, col in sites:
mask[row][col] = 0
distance = distance_transform_edt(mask, sampling=(1.1, 1.1))
return [bool(distance[row, col] <= 5.5) for row, col in queries]
print(scipy_hits(u, v), scipy_hits(v, u))
The output is [False] [False, False, True]. From \(U\) to \(V\), SciPy selected a diagonal site. Enumeration reaches the horizontal site and gives True for that query. From \(V\) to \(U\) there is just one destination. Both calculations accept only the horizontal pixel. That gives \(1/4\) with SciPy and \(2/4\) with enumeration. In real arithmetic on the stored spacing, all four distances are exactly \(5\rho(1.1)=5.5+2^{-51}\), above the threshold. If instead the input is the exact decimal \(11/10\), all four real distances equal 5.5. Allowing a relative margin of \(10^{-6}\) in the comparison also includes all four, by a separate choice in the scoring rule.
Would I see anything like that on contours drawn by people? I used both retinal vessel annotations on all 20 image pairs from STARE, each \(605\times700\) pixels. An annotated pixel belongs to the boundary if at least one of its four face neighbors is outside the mask, treating the image exterior as background. I tested spacings \((1,1)\), \((0.7,0.7)\) and \((0.7,1.3)\). The decimal spacings were numerical stress tests I imposed on the masks. For each spacing I used thresholds of one, two and five row spacings.11
There were 667,986 directed boundary queries per spacing. The square root of the minimum cost, the SciPy distance and a reevaluation of the selected neighbor agreed in their corresponding quantities. No threshold decision changed. I also checked full-site enumeration on 80 predetermined queries at each spacing. The four-vote example shows how to construct a change in score. The retinas tell me what happened on paired human annotations with the conventions and thresholds I actually tested.
Reproducing the sandstone count
I’ve included a script that takes the original segmentation, checks its SHA-256, enumerates the costs along all three axes, repeats the reflection in SciPy and constructs the 163 thresholds by rational comparison. You can recover the data behind the plot and the count table without implementing the stack from the proof. With SciPy 1.18.1 and both files in the same directory, run python reproduce_edt.py berea_100_to_300.npz. For each of the six differences it prints the hexadecimal radius and both counts. Reproduction script · Berea volume at the revision used here.
Next time I compute a boundary metric, I want to keep something alongside the score that I can actually query. For the sandstone, one index, three neighbors and the bits of the radius are enough to redo the decision at the circled voxel. Had I kept only “27.2543 µm”, I’d have lost the very information that decides whether it counts. On the retinas I could repeat the entire calculation and get the same decision at every query. Those are two outcomes I’d like to be able to tell apart when I read a number in a segmentation table.
References
-
VIANA, Rodolfo. What Dice Misses. 2026. ↩
-
SciPy Developers. Documentation for
scipy.ndimage.distance_transform_edt. Thesamplingoption specifies grid spacing andreturn_indiceslets us inspect the selected background point. ↩ -
IEEE. IEEE Standard for Floating-Point Arithmetic. IEEE Std 754-2019. DOI. ↩
-
FELZENSZWALB, Pedro F. and HUTTENLOCHER, Daniel P. Distance Transforms of Sampled Functions. Theory of Computing, vol. 8, pp. 415–428, 2012. Paper. ↩
-
MAURER, Calvin R. Jr., QI, Rensheng and RAGHAVAN, Vijay. A Linear Time Algorithm for Computing Exact Euclidean Distance Transforms of Binary Images in Arbitrary Dimensions. IEEE Transactions on Pattern Analysis and Machine Intelligence, vol. 25, pp. 265–270, 2003. DOI. ↩
-
AGGARWAL, Alok, KLAWE, Maria M., MORAN, Shlomo, SHOR, Peter and WILBER, Robert. Geometric Applications of a Matrix-Searching Algorithm. Algorithmica, vol. 2, pp. 195–208, 1987. DOI. ↩
-
OpenPNM. Network extraction example with the segmentation and acquisition spacing. ↩
-
MANWART, C., TORQUATO, S. and HILFER, R. Stochastic Reconstruction of Sandstones. Physical Review E, vol. 62, pp. 893–899, 2000. DOI. ↩
-
VAN GRIETHUYSEN, Joost J. M. et al. Computational Radiomics System to Decode the Radiographic Phenotype. Cancer Research, vol. 77, pp. e104–e107, 2017. Paper · The five masks at the revision used here. ↩
-
NIKOLOV, Stanislav et al. Clinically Applicable Segmentation of Head and Neck Anatomy for Radiotherapy: Deep Learning Algorithm Development and Validation Study. Journal of Medical Internet Research, vol. 23, e26151, 2021. Definition and use of surface Dice. ↩
-
HOOVER, Adam, KOUZNETSOVA, Valentina and GOLDBAUM, Michael. Locating Blood Vessels in Retinal Images by Piecewise Threshold Probing of a Matched Filter Response. IEEE Transactions on Medical Imaging, vol. 19, pp. 203–210, 2000. Paper · STARE images and annotations. ↩