Algorithm Search⌘K

Algorithmadvanced

Mid-surface extraction

Also called midsurface abstraction, dimensional reduction of thin solids.

Replaces a thin-walled solid by its mid-surface with thickness attributes, by pairing opposite faces or by the medial axis, so shell elements can model it.

Time
O(n^2 k + m^2) worst
Space
O(n) extra
Where
k = largest number of shrink steps for one sample; m = number of kept medial points; n = number of boundary samples
Properties
deterministicnot exactiterative
Origin
Mohsen Rezayat, 1996

A thin-walled part, such as a sheet metal bracket, a plastic housing or a ship hull, is a solid whose thickness tt is small compared with its other sizes. A mesh of solid elements through such a thin wall needs several small elements across tt, so it is large. Shell elements, such as isogeometric Kirchhoff-Love shells or subdivision shells, model the wall by a surface with a thickness value instead. Mid-surface extraction builds that surface from the CAD solid: the surface halfway between the two faces of the wall, with the local thickness at each point. There are two families. Face pairing finds pairs of opposite faces and offsets one of them by half the distance (Rezayat 1996). Medial methods take the medial axis in 2D or the medial surface in 3D and remove its branches that do not belong to the wall. This page gives the medial method on sampled boundaries in 2D, where the mid-surface is a midline of a cross-section, proves that it is exact on a strip and an annular sector, proves the error when the samples on the two sides do not line up, and measures the result.

In plain words

Think of a thin plate. For a strength check, engineers like to replace it by a flat sheet with no thickness that runs through its middle, and to write the thickness on the sheet as a number. The computation on the sheet is much faster.

To find the middle, roll a ball inside the part so that it always touches both faces of the wall. The center of the ball traces the middle, and the size of the ball gives the thickness.

The method here starts at each point of the border with a huge ball that touches it, then shrinks the ball until no other border point is inside. The final ball touches a second point, usually on the other face. Balls that touch two points on nearly opposite sides belong to the middle. Balls that touch two neighbors near a corner are thrown away.

The problem

The input is a region Ω⊂R2\Omega \subset \mathbb{R}^2, the cross-section of a thin wall, given by nn samples p1,…,pnp_1, \dots, p_n of its boundary and the unit inward normals n1,…,nnn_1, \dots, n_n there. The output is a set of polylines that approximate the midline, with a thickness 2r2r at each vertex.

The reference midline is defined by the medial axis: the set of centers of the maximal disks in Ω\Omega. A medial point cc with radius rr touches the boundary in at least two points. Its separation angle is the angle at cc between two of them. The midline is the part of the medial axis where this angle is close to 180°180°, so that the disk touches two opposite faces of the wall. The other branches run into corners, where the angle is close to 90°90° or smaller, and they are not part of the wall.

For a sample pp with inward normal nn, the disks that touch the boundary at pp from inside are B(r)={x:∣x−c(r)∣≤r}B(r) = \{x : |x - c(r)| \le r\} with c(r)=p+rnc(r) = p + r n. A sample qq lies strictly inside B(r)B(r) if and only if r>ρ(q)r > \rho(q), where

ρ(q)=∣q−p∣22 n⋅(q−p)if n⋅(q−p)>0,ρ(q)=∞otherwise,\rho(q) = \frac{|q - p|^2}{2 \, n \cdot (q - p)} \quad \text{if } n \cdot (q - p) > 0, \qquad \rho(q) = \infty \quad \text{otherwise},

is the radius of the circle tangent to the boundary at pp through qq. So the largest disk touching at pp that holds no sample in its interior has the radius ρ∗=min⁡q≠pρ(q)\rho^* = \min_{q \ne p} \rho(q).

The algorithm

  1. MIDLINE(samples p_1..p_n, inward normals n_1..n_n, start radius r_0, angle θ_min, radius r_min, link length ℓ)
  2. 1for i = 1 to n do
  3. 2c ← p_i + r n_i ▷ the center, with r = r_0 at the start
  4. 3j ← the sample nearest to c
  5. 4if j = i or |p_j - c| ≥ r then go to L6 ▷ no sample inside the disk
  6. 5r ← ρ(p_j); go to L2 ▷ shrink until p_j is on the circle
  7. 6if a sample p_k touched the disk then θ ← the angle at c between p_i and p_k, else skip p_i
  8. 7if θ ≥ θ_min and r ≥ r_min then keep (c, 2r)
  9. 8link the kept centers into polylines, joining centers closer than ℓ

Lines L2 to L5 are the shrinking ball of Ma, Bae and Choi (2012). Line L5 shrinks the disk to the circle through the nearest sample pjp_j, and this sample becomes the touching sample pkp_k of line L6. The loop stops when the nearest sample to the center is on or outside the circle. Line L7 keeps the disks that touch two nearly opposite points, θ≥θmin⁡\theta \ge \theta_{\min}, and drops the small disks that touch two neighboring samples, r<rmin⁡r < r_{\min}. The code uses θmin⁡=120°\theta_{\min} = 120°, rmin⁡=hr_{\min} = h, the largest distance from a sample to its nearest neighbor, and r0=1000r_0 = 1000 times the size of the bounding box. Line L8 builds the connected components of the graph with edges shorter than ℓ\ell and walks each from its farthest point by nearest neighbors. The code uses ℓ\ell equal to three times the largest gap between consecutive samples. In 3D the same lines give points of the mid-surface, and line L8 becomes the meshing of a point set with a thickness at each point.

Example

All runs use the code of this page, with fixed inputs.

A strip. The strip [0,10]×[−0.5,0.5][0, 10] \times [-0.5, 0.5] has t=1t = 1. Its long sides are sampled at spacing s=0.1s = 0.1, at the points x=0.05,0.15,…x = 0.05, 0.15, \dots, and the short sides at the points y=−0.45,…,0.45y = -0.45, \dots, 0.45. No sample is a corner. With aligned samples, the same xx on both sides:

run samples kept largest ∣y∣\lvert y \rvert of a center largest ∣r−t/2∣\lvert r - t/2 \rvert xx range chains
aligned 220 180 0 0 0.55 to 9.45 1
top side shifted by s/2s/2 219 181 0.00125 0.00125 0.5 to 9.5 1
aligned, no pruning (θmin⁡=0\theta_{\min} = 0, rmin⁡=0r_{\min} = 0) 220 220 0.45

The aligned run is exact to the last bit. With the shifted side, the error is s2/(8t)=0.00125s^2 / (8 t) = 0.00125, the bound of the correctness section, attained. Without pruning, the 40 samples near the ends give disks with a separation angle of exactly 90°90°, on the four corner bisectors. The kept centers end at about x=t/2x = t/2 and x=L−t/2x = L - t/2, not at the ends of the plate. Each midline is one chain with thickness 2r=12r = 1. The shrinking ball took 1.8 steps per sample on average and 8 at most, from r0=11000r_0 = 11000.

An annular sector. The sector 2≤ρ≤2.52 \le \rho \le 2.5, 0≤θ≤90°0 \le \theta \le 90° has t=0.5t = 0.5. Both arcs are sampled at the same 120 angles (k+1/2)⋅0.75°(k + 1/2) \cdot 0.75°, and each straight end at 10 points, 260 samples in all. The run keeps 208 centers. All lie on the mean arc ρm=2.25\rho_m = 2.25 with r=0.25r = 0.25, to 4.4×10−164.4 \times 10^{-16}. Their angles run from 6.375°6.375° to 83.625°83.625°, and the exact medial arc starts at θ0=arcsin⁡(t/(2ρm))=6.379°\theta_0 = \arcsin(t / (2 \rho_m)) = 6.379° and ends at 90°−θ090° - \theta_0, so the kept range matches it within one sample spacing. The midline is one chain.

Correctness

The proof page proves four facts, with exact arithmetic.

  1. The shrinking ball. If ρ∗<r0\rho^* < r_0, lines L2 to L5 stop after at most n−1n - 1 shrinks with r=ρ∗r = \rho^*, the largest empty disk that touches at pip_i. The key fact is that the disks B(r)B(r) are nested and that qq is inside B(r)B(r) exactly when r>ρ(q)r > \rho(q). If no sample qq has ni⋅(q−pi)>0n_i \cdot (q - p_i) > 0, the disk never shrinks and no sample touches it.
  2. The strip. For the rectangle [0,L]×[−t/2,t/2][0, L] \times [-t/2, t/2] with L>tL > t, the medial axis is the midline segment from (t/2,0)(t/2, 0) to (L−t/2,0)(L - t/2, 0), where the separation angle is 180°180°, and four corner branches, where it is 90°90°. So any θmin⁡\theta_{\min} in (90°,180°](90°, 180°] keeps exactly the segment.
  3. The sampled strip. Let pp be a sample on a long side at distance more than r∗=t/2+d2/(2t)r^* = t/2 + d^2 / (2 t) from both short sides, where dd is the smallest offset in xx from pp to a sample on the other side. Then the algorithm gives the center at distance d2/(2t)d^2 / (2 t) from the midline and the radius r∗r^*, with the separation angle 180°−2arctan⁡(d/t)180° - 2 \arctan(d / t). Aligned samples, d=0d = 0, give the exact midline, and samples shifted by s/2s/2 give the error s2/(8t)s^2 / (8 t).
  4. The annular sector. If t<r1t < r_1 and 2arcsin⁡(t/(2r1))<φ≤180°2 \arcsin(t / (2 r_1)) < \varphi \le 180°, the points of the medial axis with a separation angle above 90°+arcsin⁡(t/(2r1))90° + \arcsin(t / (2 r_1)) form exactly the arc ρ=ρm\rho = \rho_m, θ0≤θ≤φ−θ0\theta_0 \le \theta \le \varphi - \theta_0. If both arcs are sampled at the same angles, every arc sample in this range gives a center on that arc with r=t/2r = t/2 exactly.

The tests check facts 1, 3 and 4 and a tapered strip, where 2r2r is the thickness measured normal to the sides. The behavior of the samples near the ends, which the pruning removes, is measured, not proved.

Proof: The shrinking ball finds the largest empty tangent disk, and the medial midline is exact on a strip and an annular sectorfull

We use the notation of the page. Arithmetic is exact. For a sample pp with unit inward normal nn and r>0r > 0, let c(r)=p+rnc(r) = p + r n and B(r)={x:∣x−c(r)∣≤r}B(r) = \{x : |x - c(r)| \le r\}. For a sample q≠pq \ne p, let ρ(q)=∣q−p∣2/(2n⋅(q−p))\rho(q) = |q - p|^2 / (2 n \cdot (q - p)) if n⋅(q−p)>0n \cdot (q - p) > 0, and ρ(q)=∞\rho(q) = \infty otherwise. Let ρ∗=min⁡q≠pρ(q)\rho^* = \min_{q \ne p} \rho(q).

Lemma 1 (inside test). A point q≠pq \ne p lies in the interior of B(r)B(r) if and only if r>ρ(q)r > \rho(q). It lies on the circle if and only if r=ρ(q)r = \rho(q).

Proof. ∣q−c(r)∣2−r2=∣q−p∣2−2r n⋅(q−p)|q - c(r)|^2 - r^2 = |q - p|^2 - 2 r \, n \cdot (q - p), because ∣n∣=1|n| = 1. If n⋅(q−p)≤0n \cdot (q - p) \le 0, this is at least ∣q−p∣2>0|q - p|^2 > 0, so qq is outside B(r)B(r) for every rr, which matches ρ(q)=∞\rho(q) = \infty. If n⋅(q−p)>0n \cdot (q - p) > 0, the sign of the expression is the sign of ρ(q)−r\rho(q) - r. □\square

So the disks B(r)B(r) grow with rr, and B(r)B(r) holds no sample in its interior exactly when r≤ρ∗r \le \rho^*.

Theorem 1 (the shrinking ball). Let r0>ρ∗r_0 > \rho^*. Lines L2 to L5 stop after at most n−1n - 1 shrinks, with r=ρ∗r = \rho^* and a touching sample pkp_k with ρ(pk)=ρ∗\rho(p_k) = \rho^*, which lies on the final circle. If ρ∗=∞\rho^* = \infty, they stop at once with r=r0r = r_0 and no touching sample.

Proof. Invariant: r≥ρ∗r \ge \rho^*. It holds at the start. Line L5 sets r=ρ(pj)r = \rho(p_j), which is at least ρ∗\rho^* by the definition of the minimum. Stop test: the sample pip_i lies on every circle, at distance rr from cc. So if the nearest sample pjp_j to cc is pip_i, or if ∣pj−c∣≥r|p_j - c| \ge r, then no sample lies in the interior of B(r)B(r), and Lemma 1 gives r≤ρ∗r \le \rho^*. With the invariant, r=ρ∗r = \rho^*. Shrink step: if the test fails, pj≠pip_j \ne p_i lies in the interior, so r>ρ(pj)r > \rho(p_j) by Lemma 1, and line L5 decreases rr strictly. Each new value of rr is ρ(q)\rho(q) for a sample q≠piq \ne p_i, and the values strictly decrease, so no sample is used twice, and there are at most n−1n - 1 shrinks. At the end the last touching sample pkp_k has ρ(pk)=r=ρ∗\rho(p_k) = r = \rho^*, so it lies on the circle by Lemma 1. If ρ∗=∞\rho^* = \infty, no sample satisfies r>ρ(q)r > \rho(q), so the first test succeeds and rr stays r0r_0. □\square

Theorem 2 (the strip). Let R=[0,L]×[−t/2,t/2]R = [0, L] \times [-t/2, t/2] with L>tL > t. The medial axis of RR is the segment SS from (t/2,0)(t/2, 0) to (L−t/2,0)(L - t/2, 0), where the maximal disks have radius t/2t/2 and the separation angle is 180°180°, together with four segments on the corner bisectors, where the separation angle is 90°90°. So pruning with any θmin⁡\theta_{\min} in (90°,180°](90°, 180°] keeps exactly SS, and SS is shorter than the midline [0,L]×{0}[0, L] \times \{0\} of the plate by t/2t/2 at each end.

Proof. For an interior point x=(x1,x2)x = (x_1, x_2), the distance to the boundary is δ(x)=min⁡(x1,L−x1,t/2−x2,t/2+x2)\delta(x) = \min(x_1, L - x_1, t/2 - x_2, t/2 + x_2), the distance to the nearest side. The nearest point on a side is the foot of the perpendicular, since xx projects inside every side of the rectangle. For a convex polygon, xx is on the medial axis exactly when at least two sides reach the minimum, or xx is a limit of such points. Two sides tie in these cases. The top and bottom tie when x2=0x_2 = 0, and they are nearest when also x1≥t/2x_1 \ge t/2 and L−x1≥t/2L - x_1 \ge t/2, which gives SS. The feet are (x1,±t/2)(x_1, \pm t/2), opposite each other through xx, so the separation angle is 180°180° and the radius is t/2t/2. A long side and a short side tie on a corner bisector, for example x1=t/2−x2x_1 = t/2 - x_2 for the left and the top side, and they are nearest for 0≤x20 \le x_2 and x1≤t/2x_1 \le t/2. The feet are (0,x2)(0, x_2) and (x1,t/2)(x_1, t/2), in the directions (−1,0)(-1, 0) and (0,1)(0, 1) from xx, so the separation angle is 90°90°. The left and right sides cannot both be nearest, because that needs x1=L/2x_1 = L/2 and L/2≤t/2L/2 \le t/2, against L>tL > t. The four bisector segments meet SS only at its ends, where the top and bottom also tie and the angle 180°180° is available. So the points with a separation angle above 90°90° form SS, and SS ends at x1=t/2x_1 = t/2 and x1=L−t/2x_1 = L - t/2. □\square

Theorem 3 (the sampled strip). Sample RR with points on its sides and with the inward normals of the sides. Let p=(xp,−t/2)p = (x_p, -t/2) be a sample on the bottom side, let dd be the smallest value of ∣xq−xp∣|x_q - x_p| over the samples q=(xq,t/2)q = (x_q, t/2) on the top side, let r∗=t/2+d2/(2t)r^* = t/2 + d^2 / (2 t), and assume min⁡(xp,L−xp)>r∗\min(x_p, L - x_p) > r^*. Then the shrinking ball at pp ends with the radius r∗r^*, the center (xp,d2/(2t))(x_p, d^2 / (2 t)), and a touching sample on the top side, and the separation angle is 180°−2arctan⁡(d/t)180° - 2 \arctan(d / t). The same holds for the top side with the sign of the center reversed. So line L7 keeps pp when rmin⁡≤r∗r_{\min} \le r^* and d≤ttan⁡((180°−θmin⁡)/2)d \le t \tan((180° - \theta_{\min}) / 2).

Proof. Here n=(0,1)n = (0, 1). A sample qq on the bottom side has n⋅(q−p)=0n \cdot (q - p) = 0, so ρ(q)=∞\rho(q) = \infty. A sample q=(xq,t/2)q = (x_q, t/2) on the top side has n⋅(q−p)=tn \cdot (q - p) = t and ∣q−p∣2=(xq−xp)2+t2|q - p|^2 = (x_q - x_p)^2 + t^2, so ρ(q)=t/2+(xq−xp)2/(2t)\rho(q) = t/2 + (x_q - x_p)^2 / (2 t), which is smallest, equal to r∗r^*, for the offset dd. A sample qq on a short side, for example the left one, is at distance xp>r∗x_p > r^* from the vertical line through the center c(r∗)=(xp,−t/2+r∗)c(r^*) = (x_p, -t/2 + r^*), so it lies outside B(r∗)B(r^*), and Lemma 1 gives ρ(q)>r∗\rho(q) > r^*. The right side is the same with L−xpL - x_p. So ρ∗=r∗\rho^* = r^*, attained only on the top side, and Theorem 1 gives the radius r∗r^* and a touching sample qq on the top side with ρ(q)=r∗\rho(q) = r^*, so ∣xq−xp∣=d|x_q - x_p| = d. The center is (xp,−t/2+r∗)=(xp,d2/(2t))(x_p, -t/2 + r^*) = (x_p, d^2 / (2 t)). For the angle, take the touching top sample q=(xp+d,t/2)q = (x_p + d, t/2), with either sign of the offset. From cc, the vector to pp is (0,−r∗)(0, -r^*) and the vector to qq is (d,t/2−d2/(2t))(d, t/2 - d^2/(2t)), of length r∗r^*. So the cosine of the angle is −(t/2−d2/(2t))/r∗=−(t2−d2)/(t2+d2)=−cos⁡(2arctan⁡(d/t))-(t/2 - d^2/(2t)) / r^* = -(t^2 - d^2) / (t^2 + d^2) = -\cos(2 \arctan(d/t)), and the angle is 180°−2arctan⁡(d/t)180° - 2 \arctan(d/t). The last claim follows from line L7. □\square

Corollary. If both long sides are sampled at the same values of xx, then d=0d = 0, and every kept sample of Theorem 3 gives a center on the midline x2=0x_2 = 0 with radius exactly t/2t/2. If the samples are at spacing ss and the top side is shifted by s/2s/2, then d=s/2d = s/2, and the center and the radius are both off by d2/(2t)=s2/(8t)d^2 / (2t) = s^2 / (8 t), and this value is attained.

Theorem 4 (the annular sector). Let A={(ρcos⁡θ,ρsin⁡θ):r1≤ρ≤r2, 0≤θ≤φ}A = \{(\rho \cos \theta, \rho \sin \theta) : r_1 \le \rho \le r_2, \ 0 \le \theta \le \varphi\}, t=r2−r1t = r_2 - r_1, ρm=(r1+r2)/2\rho_m = (r_1 + r_2)/2, and assume t<r1t < r_1, 2β<φ≤180°2 \beta < \varphi \le 180° with β=arcsin⁡(t/(2r1))\beta = \arcsin(t / (2 r_1)). Let θ0=arcsin⁡(t/(2ρm))\theta_0 = \arcsin(t / (2 \rho_m)). (a) The points of the medial axis of AA with a separation angle above 90°+β90° + \beta form exactly the arc Γ={ρ=ρm, θ0≤θ≤φ−θ0}\Gamma = \{\rho = \rho_m, \ \theta_0 \le \theta \le \varphi - \theta_0\}, with radius t/2t/2 and angle 180°180°. (b) If both arcs are sampled at the same angles θk\theta_k, then for every sample pp on an arc with θ0≤θk≤φ−θ0\theta_0 \le \theta_k \le \varphi - \theta_0, the shrinking ball gives the center ρm(cos⁡θk,sin⁡θk)\rho_m (\cos \theta_k, \sin \theta_k) and the radius t/2t/2 exactly.

Proof. Write e(θ)=(cos⁡θ,sin⁡θ)e(\theta) = (\cos \theta, \sin \theta) and take a point x=ρ e(θ)x = \rho \, e(\theta) of AA. Its distance to the inner arc is ρ−r1\rho - r_1 and to the outer arc is r2−ρr_2 - \rho, with the nearest points r1e(θ)r_1 e(\theta) and r2e(θ)r_2 e(\theta), in the directions −e(θ)-e(\theta) and e(θ)e(\theta) from xx. So the distance to the nearer arc is at most t/2t/2. Its distance to the line of the straight end θ=0\theta = 0 is ρsin⁡θ\rho \sin \theta, with the foot in the direction (0,−1)(0, -1), and the same holds for the end θ=φ\theta = \varphi with φ−θ\varphi - \theta. The nearest point on an end segment is either this foot or a corner of AA. A corner is never strictly nearer than an arc: for the corner c=r1e(0)c = r_1 e(0), ∣x−c∣≥∣x∣−∣c∣=ρ−r1|x - c| \ge |x| - |c| = \rho - r_1, and for c=r2e(0)c = r_2 e(0), ∣x−c∣≥∣c∣−∣x∣=r2−ρ|x - c| \ge |c| - |x| = r_2 - \rho, and the same for the corners at φ\varphi. So a medial point is a tie of the minimum distance between two of the four pieces, with the nearest points as above.

Arc and arc: ρ−r1=r2−ρ\rho - r_1 = r_2 - \rho gives ρ=ρm\rho = \rho_m and the distance t/2t/2, and the ends must be no nearer. If θ<θ0\theta < \theta_0, the foot on the line θ=0\theta = 0 has the abscissa ρmcos⁡θ≥ρmcos⁡θ0=ρm2−t2/4=r1r2\rho_m \cos \theta \ge \rho_m \cos \theta_0 = \sqrt{\rho_m^2 - t^2/4} = \sqrt{r_1 r_2}, which lies in [r1,r2][r_1, r_2], so the foot is on the end segment, at the distance ρmsin⁡θ<t/2\rho_m \sin \theta < t/2, and the end is strictly nearer. If θ0≤θ≤φ−θ0\theta_0 \le \theta \le \varphi - \theta_0, then sin⁡θ≥sin⁡θ0\sin \theta \ge \sin \theta_0 because φ≤180°\varphi \le 180°, so the distance to the line, and hence to the segment, is at least t/2t/2. The end θ=φ\theta = \varphi is the same with φ−θ\varphi - \theta. So the tie gives exactly θ0≤θ≤φ−θ0\theta_0 \le \theta \le \varphi - \theta_0. The nearest points are opposite through xx, so the angle is 180°180°. This is Γ\Gamma. Arc and end, for the end θ=0\theta = 0: the nearest point on the end is its foot, which needs θ<90°\theta < 90°, and the distance ρsin⁡θ\rho \sin \theta is at most t/2t/2, so sin⁡θ≤t/(2r1)\sin \theta \le t / (2 r_1) and θ≤β\theta \le \beta. The angle between ±e(θ)\pm e(\theta) and (0,−1)(0, -1) has the cosine ∓sin⁡θ\mp \sin \theta, so it is 90°±θ≤90°+β90° \pm \theta \le 90° + \beta. The end θ=φ\theta = \varphi is the same with φ−θ\varphi - \theta. End and end: the tie needs θ=φ/2\theta = \varphi / 2 and ρsin⁡(φ/2)≤t/2\rho \sin(\varphi/2) \le t/2, so sin⁡(φ/2)≤t/(2r1)\sin(\varphi/2) \le t/(2 r_1), against φ>2β\varphi > 2 \beta. An arc or an end alone has a unique nearest point, since the origin is not in AA. So the points with an angle above 90°+β90° + \beta form Γ\Gamma, which proves (a).

For (b), let p=r1e(θk)p = r_1 e(\theta_k) with n=e(θk)n = e(\theta_k). The disk B(t/2)B(t/2) has the center c=ρme(θk)c = \rho_m e(\theta_k). The outer sample r2e(θk)r_2 e(\theta_k) has ρ=t2/(2t)=t/2\rho = t^2 / (2 t) = t/2. Another outer sample q=r2e(θj)q = r_2 e(\theta_j), with γ=cos⁡(θj−θk)<1\gamma = \cos(\theta_j - \theta_k) < 1, has ∣q−p∣2=r12+r22−2r1r2γ|q - p|^2 = r_1^2 + r_2^2 - 2 r_1 r_2 \gamma and n⋅(q−p)=r2γ−r1n \cdot (q - p) = r_2 \gamma - r_1. If r2γ≤r1r_2 \gamma \le r_1, then ρ(q)=∞\rho(q) = \infty. Otherwise ρ(q)≥t/2\rho(q) \ge t/2 is r12+r22−2r1r2γ≥(r2−r1)(r2γ−r1)r_1^2 + r_2^2 - 2 r_1 r_2 \gamma \ge (r_2 - r_1)(r_2 \gamma - r_1), which expands to (r22+r1r2)(1−γ)≥0(r_2^2 + r_1 r_2)(1 - \gamma) \ge 0, true, and strict since γ<1\gamma < 1. An inner sample q=r1e(θj)q = r_1 e(\theta_j) has n⋅(q−p)=r1(γ−1)≤0n \cdot (q - p) = r_1 (\gamma - 1) \le 0, so ρ(q)=∞\rho(q) = \infty. A sample qq on the end θ=0\theta = 0 lies on a line at distance ρmsin⁡θk≥ρmsin⁡θ0=t/2\rho_m \sin \theta_k \ge \rho_m \sin \theta_0 = t/2 from cc, so it is not in the interior of B(t/2)B(t/2), and Lemma 1 gives ρ(q)≥t/2\rho(q) \ge t/2; the end θ=φ\theta = \varphi is the same. So ρ∗=t/2\rho^* = t/2, attained by r2e(θk)r_2 e(\theta_k), and Theorem 1 gives the radius t/2t/2 and the center p+(t/2)n=ρme(θk)p + (t/2) n = \rho_m e(\theta_k). A sample on the outer arc is the same with n=−e(θk)n = -e(\theta_k) and the roles of the arcs swapped. ■\blacksquare

Complexity

In the real RAM model, with nn samples, at most kk shrinks per sample and mm kept points:

  • Shrinking. Each step of line L3 is a linear scan, O(n)O(n), and each sample takes at most k+1k + 1 steps, so lines L1 to L7 cost O(n2k)O(n^2 k). Fact 1 gives k≤n−1k \le n - 1, so the worst case is O(n3)O(n^3). In the example k=8k = 8 and the mean is 1.8.
  • Nearest neighbors. A kd-tree built once over the samples answers line L3 in O(log⁡n)O(\log n) expected time for well spread samples, so the shrinking costs O(nklog⁡n)O(n k \log n) expected after an O(nlog⁡n)O(n \log n) build.
  • Linking. Line L8 compares all pairs, O(m2)O(m^2), and the default rmin⁡r_{\min} costs O(n2)O(n^2) by the same scan. Both drop to O(mlog⁡m)O(m \log m) and O(nlog⁡n)O(n \log n) with a kd-tree.
  • Space. O(n)O(n) for the samples and the kept points.

Properties

  • Local. Each sample is processed alone, so the loop of line L1 runs in parallel without change.
  • Thickness for free. The radius of each kept disk is half the local wall thickness, measured normal to the faces.
  • Needs normals. The inward normals at the samples must be known. A CAD solid gives them, a scan needs an estimate.
  • Short at free edges. The medial axis of a wall stops half a thickness before each free edge of the wall, so the result needs an extension there to match the mid-surface that an engineer expects.
  • Not exact. Sampling, pruning and linking all add errors. Only special shapes with aligned samples come out exactly.

Variants and improvements

  • Face pairing. Rezayat (1996) finds pairs of faces of the solid that are close and nearly parallel, builds a midsurface patch between each pair, and then extends and joins the patches across the junctions. It works on the exact CAD surfaces and keeps their type, but the joining step is hard at T-joints and where the thickness changes.
  • Exact medial surfaces. A medial surface of a polyhedral solid can be traced exactly, then pruned in the same way by the angle or by the ratio of the size of a branch to its radius.
  • Shrinking ball in 3D. Ma, Bae and Choi (2012) give the method for 3D point clouds with normals. The code of this page is its 2D form.
  • Decomposition first. Split the part into thin regions and thick regions, for example at its medial axis as in medial axis decomposition meshing, and reduce only the thin regions. The thick regions stay solid and are joined to the shells.
  • Defeature first. Small features such as fillets, holes and ribs break the pairing of faces, so they are often removed by defeaturing before the extraction.

When to use it

Use mid-surface extraction when the part is a thin wall, with a ratio of span to thickness of about ten or more, and a shell model is accurate enough for the analysis. Use face pairing when the CAD solid has clean opposite faces. Use a medial method when the faces do not pair well or when only a mesh or a point set is available. Keep solid elements near thick regions, ribs and joints, where the shell assumption fails.

Pitfalls

  • The free edges. The medial axis of the strip ends at x=t/2x = t/2, so the shell is too short by t/2t/2 at each free edge, as the example shows. Extend the midline to the edge, or the model loses stiffness and mass.
  • Corner branches. Each convex corner gives a branch with separation angle 90°90° that reaches the midline. Without pruning, they become false shell pieces.
  • Small disks at the samples. A disk that touches two neighboring samples can pass the angle test. The test r≥rmin⁡r \ge r_{\min}, with rmin⁡r_{\min} about the sample spacing, removes them. With rmin⁡=0r_{\min} = 0 and the shifted strip of the example, the code keeps two such disks at the top corners, with radius 0.0625, angle 126.9°126.9° and centers at y=0.45y = 0.45.
  • Sampling. The samples on the two faces should be denser than the thickness. With the offset dd between the faces, the center moves by d2/(2t)d^2 / (2 t), so the error grows fast if the spacing approaches tt.
  • Junctions. At a T-joint or a change of thickness, the medial axis has a branch point and the shell needs a connection there. Neither pruning nor linking builds it.
  • Wrong normals. A flipped normal sends the disk outside the region. Check the orientation before the run.

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.

midsurface_extraction.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/midsurface-extraction/. The authors are listed in prov/FG99C0.jsonl.
"""Midline extraction of a thin 2D region by the shrinking ball medial axis.

The region is given by samples of its boundary with unit inward normals.
For each sample the largest disk that touches the boundary at the sample
and holds no other sample inside is found by shrinking (Ma, Bae and Choi
2012). Its center is a point of the approximate medial axis, and twice its
radius is the local thickness. Branches that run into corners are removed
by the separation angle, and the remaining points are linked into
polylines with a thickness at each point: the midline of the thin region,
the 2D form of a midsurface.
"""

from __future__ import annotations

import math
from typing import List, Optional, Sequence, Tuple

Point = Tuple[float, float]


def tangent_radius(p: Point, n: Point, q: Point) -> float:
    """Radius of the circle tangent to the boundary at p (inward normal n) that passes through q.

    It is |q - p|^2 / (2 n . (q - p)), and infinity when q is not on the inner side of the tangent.
    """
    dx, dy = q[0] - p[0], q[1] - p[1]
    h = n[0] * dx + n[1] * dy
    if h <= 0:
        return math.inf
    return (dx * dx + dy * dy) / (2 * h)


def shrinking_ball(
    pts: Sequence[Point], nrm: Sequence[Point], i: int, r0: float, rel: float = 1e-12
) -> Tuple[Point, float, Optional[int], int]:
    """(center, radius, index of the touching sample, number of shrink steps) for sample i.

    Returns touching index None if the initial disk of radius r0 holds no sample.
    """
    p, n = pts[i], nrm[i]
    r, touch, steps = r0, None, 0
    while True:
        c = (p[0] + r * n[0], p[1] + r * n[1])  # @line L2
        # nearest sample to the center, by a linear scan
        j = min(range(len(pts)), key=lambda k: (pts[k][0] - c[0]) ** 2 + (pts[k][1] - c[1]) ** 2)  # @line L3
        d = math.hypot(pts[j][0] - c[0], pts[j][1] - c[1])
        if j == i or d >= r * (1 - rel):  # @line L4
            return c, r, touch, steps
        r_new = tangent_radius(p, n, pts[j])  # @line L5
        if not r_new < r:  # round-off guard: the radius must strictly decrease
            return c, r, touch, steps
        r, touch, steps = r_new, j, steps + 1


def separation_angle(p: Point, c: Point, q: Point) -> float:
    """Angle at c between c -> p and c -> q, in degrees."""
    ax, ay = p[0] - c[0], p[1] - c[1]
    bx, by = q[0] - c[0], q[1] - c[1]
    cosv = (ax * bx + ay * by) / (math.hypot(ax, ay) * math.hypot(bx, by))
    return math.degrees(math.acos(max(-1.0, min(1.0, cosv))))


def sample_spacing(pts: Sequence[Point]) -> float:
    """h = the largest distance from a sample to its nearest other sample."""
    h = 0.0
    for i, p in enumerate(pts):
        d = min(math.hypot(q[0] - p[0], q[1] - p[1]) for j, q in enumerate(pts) if j != i)
        h = max(h, d)
    return h


def medial_points(
    pts: Sequence[Point],
    nrm: Sequence[Point],
    theta_min: float = 120.0,
    r_min: Optional[float] = None,
    r0: Optional[float] = None,
) -> List[Tuple[Point, float, int, int, float]]:
    """Medial points (center, radius, sample, touching sample, angle) with angle >= theta_min and radius >= r_min.

    The default r_min is the sample spacing h: smaller disks touch neighboring samples and come
    from the sampling, for example at a corner, not from the shape.
    """
    if r0 is None:
        xs = [p[0] for p in pts]
        ys = [p[1] for p in pts]
        r0 = 1e3 * (max(xs) - min(xs) + max(ys) - min(ys))
    if r_min is None:
        r_min = sample_spacing(pts)
    out = []
    for i in range(len(pts)):  # @line L1
        c, r, j, _ = shrinking_ball(pts, nrm, i, r0)
        if j is None:
            continue
        ang = separation_angle(pts[i], c, pts[j])  # @line L6
        if ang >= theta_min and r >= r_min:  # @line L7
            out.append((c, r, i, j, ang))
    return out


def link_chains(centers: Sequence[Point], max_link: float) -> List[List[int]]:
    """Order the points into chains: components of the graph with edges shorter than max_link,
    each walked by nearest neighbors from an end point."""
    m = len(centers)

    def dist(a, b):
        return math.hypot(centers[a][0] - centers[b][0], centers[a][1] - centers[b][1])

    seen = [False] * m
    chains = []
    for s in range(m):
        if seen[s]:
            continue
        comp, stack = [], [s]
        seen[s] = True
        while stack:
            a = stack.pop()
            comp.append(a)
            for b in range(m):
                if not seen[b] and dist(a, b) <= max_link:
                    seen[b] = True
                    stack.append(b)
        # an end point: the point farthest from an arbitrary point of the component
        start = max(comp, key=lambda b: dist(comp[0], b))
        order, left = [start], set(comp) - {start}
        while left:
            nxt = min(left, key=lambda b: dist(order[-1], b))
            order.append(nxt)
            left.remove(nxt)
        chains.append(order)
    return chains


def midline(
    pts: Sequence[Point], nrm: Sequence[Point], theta_min: float = 120.0, max_link: Optional[float] = None
) -> List[List[Tuple[float, float, float]]]:
    """Polylines of (x, y, thickness) that approximate the midline of a thin region."""
    mp = medial_points(pts, nrm, theta_min)
    centers = [m[0] for m in mp]
    if max_link is None:
        gaps = [math.hypot(pts[k + 1][0] - pts[k][0], pts[k + 1][1] - pts[k][1]) for k in range(len(pts) - 1)]
        max_link = 3 * max(gaps)
    chains = link_chains(centers, max_link)  # @line L8
    return [[(centers[k][0], centers[k][1], 2 * mp[k][1]) for k in ch] for ch in chains]


def strip_samples(length: float, t: float, s: float, stagger: bool = False, s_end: Optional[float] = None):
    """Boundary samples and inward normals of the strip [0, length] x [-t/2, t/2].

    The long sides are sampled at spacing s, at the midpoints (k + 1/2) s; with stagger the top side
    is shifted by s/2. The short sides are sampled at spacing s_end (default s). No sample is a corner.
    """
    s_end = s_end or s
    pts, nrm = [], []
    m = int(round(length / s))
    for k in range(m):
        pts.append(((k + 0.5) * s, -t / 2))
        nrm.append((0.0, 1.0))
    top = [(k + 1) * s for k in range(m - 1)] if stagger else [(k + 0.5) * s for k in range(m)]
    for x in top:
        pts.append((x, t / 2))
        nrm.append((0.0, -1.0))
    me = max(1, int(round(t / s_end)))
    for k in range(me):
        y = -t / 2 + (k + 0.5) * t / me
        pts += [(0.0, y), (length, y)]
        nrm += [(1.0, 0.0), (-1.0, 0.0)]
    return pts, nrm


def sector_samples(r1: float, r2: float, phi: float, m_arc: int, m_end: int):
    """Samples and inward normals of the annular sector r1 <= rho <= r2, 0 <= theta <= phi.

    Both arcs are sampled at the same m_arc angles (k + 1/2) phi / m_arc, and each radial end at m_end points.
    """
    pts, nrm = [], []
    for k in range(m_arc):
        th = (k + 0.5) * phi / m_arc
        c, s = math.cos(th), math.sin(th)
        pts += [(r1 * c, r1 * s), (r2 * c, r2 * s)]
        nrm += [(c, s), (-c, -s)]
    for k in range(m_end):
        rho = r1 + (k + 0.5) * (r2 - r1) / m_end
        pts.append((rho, 0.0))
        nrm.append((0.0, 1.0))
        c, s = math.cos(phi), math.sin(phi)
        pts.append((rho * c, rho * s))
        nrm.append((s, -c))
    return pts, nrm
test_midsurface_extraction.py 116 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/midsurface-extraction/. The authors are listed in prov/FG99C0.jsonl.

import math
import random

from midsurface_extraction import (
    medial_points,
    midline,
    sector_samples,
    shrinking_ball,
    strip_samples,
    tangent_radius,
)

L, T, S = 10.0, 1.0, 0.1


def test_shrinking_ball_returns_the_smallest_tangent_radius() -> None:
    """Lemma 1: the loop stops at r* = min over samples of the tangent radius, for any point set."""
    rng = random.Random(7)
    found = 0
    for _ in range(30):
        pts = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(40)]
        a = rng.uniform(0, 2 * math.pi)
        nrm = [(math.cos(a), math.sin(a))] * len(pts)
        for i in range(0, 40, 7):
            c, r, j, _ = shrinking_ball(pts, nrm, i, 1e6)
            best = min(tangent_radius(pts[i], nrm[i], q) for k, q in enumerate(pts) if k != i)
            if best == math.inf:  # no sample on the inner side: the disk never shrinks
                assert j is None and r == 1e6
                continue
            found += 1
            assert j is not None and abs(r - best) <= 1e-12 * max(1.0, best)
            assert abs(tangent_radius(pts[i], nrm[i], pts[j]) - r) <= 1e-12 * max(1.0, r)
            # no sample lies strictly inside the final disk
            assert all(math.hypot(q[0] - c[0], q[1] - c[1]) >= r * (1 - 1e-9) for q in pts)
    assert found > 100


def test_strip_aligned_samples_give_the_exact_midline() -> None:
    """Theorem 2: aligned samples on a strip give centers on y = 0 with radius t/2 exactly."""
    pts, nrm = strip_samples(L, T, S)
    mp = medial_points(pts, nrm, 120.0)
    assert len(mp) > 150
    for c, r, _, _, ang in mp:
        assert abs(c[1]) < 1e-12 and abs(r - T / 2) < 1e-12 and ang > 179.9
    xs = [m[0][0] for m in mp]
    # the medial axis of the strip runs from x = t/2 to x = L - t/2
    assert T / 2 - 1e-9 <= min(xs) <= T / 2 + S and L - T / 2 - S <= max(xs) <= L - T / 2 + 1e-9


def test_strip_staggered_samples_meet_the_error_bound() -> None:
    """Theorem 2: with offset d between the sides, the error of the center and of the radius is d^2 / (2t)."""
    pts, nrm = strip_samples(L, T, S, stagger=True)
    mp = medial_points(pts, nrm, 120.0)
    bound = S * S / (8 * T)
    errs = [abs(c[1]) for c, _, _, _, _ in mp] + [abs(r - T / 2) for _, r, _, _, _ in mp]
    assert max(errs) <= bound * (1 + 1e-9)
    assert max(errs) >= bound * (1 - 1e-9)  # the bound is attained for d = s/2


def test_separation_angle_prunes_the_corner_branches() -> None:
    pts, nrm = strip_samples(L, T, S)
    raw = medial_points(pts, nrm, 0.0, r_min=0.0)
    assert any(abs(c[1]) > T / 4 for c, _, _, _, _ in raw)  # corner bisector points exist
    assert all(abs(ang - 90) < 1e-6 or ang > 179.9 for _, _, _, _, ang in raw)
    kept = medial_points(pts, nrm, 120.0)
    assert all(abs(c[1]) < 1e-12 for c, _, _, _, _ in kept)


def test_annular_sector_midline_is_the_mean_arc() -> None:
    r1, r2, phi = 2.0, 2.5, math.pi / 2
    pts, nrm = sector_samples(r1, r2, phi, 120, 10)
    mp = medial_points(pts, nrm, 120.0)
    rm, t = (r1 + r2) / 2, r2 - r1
    theta0 = math.asin(t / (2 * rm))
    angles = []
    for c, r, _, _, _ in mp:
        assert abs(math.hypot(*c) - rm) < 1e-12 and abs(r - t / 2) < 1e-12
        angles.append(math.atan2(c[1], c[0]))
    h = phi / 120
    assert theta0 - h <= min(angles) <= theta0 + h
    assert phi - theta0 - h <= max(angles) <= phi - theta0 + h


def test_tapered_strip_gives_the_perpendicular_thickness() -> None:
    """Sides y = +-(t0/2 + k x): the midline is y = 0 and 2r is the thickness normal to the sides."""
    t0, k, n = 1.0, 0.05, 100
    pts, nrm = [], []
    m = 1 / math.sqrt(1 + k * k)
    for i in range(n):
        x = (i + 0.5) * L / n
        h = t0 / 2 + k * x
        pts += [(x, -h), (x, h)]
        nrm += [(k * m, m), (k * m, -m)]
    for i in range(10):
        y = -0.5 + (i + 0.5) / 10
        pts += [(0.0, y * t0), (L, y * (t0 + 2 * k * L))]
        nrm += [(1.0, 0.0), (-1.0, 0.0)]
    mp = medial_points(pts, nrm, 120.0)
    assert len(mp) > 150
    for c, r, _, _, _ in mp:
        assert abs(c[1]) < 1e-12
        assert abs(r - (t0 / 2 + k * c[0]) * m) < 1e-12


def test_midline_is_one_ordered_chain_with_thickness() -> None:
    pts, nrm = strip_samples(L, T, S)
    chains = midline(pts, nrm)
    assert len(chains) == 1
    ch = chains[0]
    xs = [p[0] for p in ch]
    assert xs == sorted(xs) or xs == sorted(xs, reverse=True)
    assert all(abs(p[2] - T) < 1e-12 for p in ch)
    assert abs(abs(xs[-1] - xs[0]) - (L - T)) < 2 * S

History

Blum (1967) introduced the medial axis as a shape descriptor. Rezayat (1996) gave the name midsurface abstraction and built it by pairing faces of the CAD solid. Medial methods for the dimensional reduction of thin solids were developed in parallel, as surveyed by Thakur, Banerjee and Gupta (2009). Ma, Bae and Choi (2012) gave the shrinking ball construction of medial points from samples and normals, which this page uses in 2D.

References

  1. M. Rezayat, Midsurface abstraction from 3D solid models, general theory and applications, Computer-Aided Design 28(11), 1996, 905 to 915, the whole paper (pairing of opposite faces, construction of the midsurface patches, and their joining)
  2. J. Ma, S. W. Bae and S. Choi, 3D medial axis point approximation using nearest neighbors and the normal field, The Visual Computer 28(1), 2012, 7 to 19, the whole paper, the shrinking ball algorithm that this page implements in 2D, and its pruning by the separation angle
  3. A. Thakur, A. G. Banerjee and S. K. Gupta, A survey of CAD model simplification techniques for physics-based simulation applications, Computer-Aided Design 41(2), 2009, 65 to 80, the part of the survey on dimensional reduction, which covers midsurface methods by face pairing and by the medial axis

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