Algorithmadvanced
Medial surface of a solid
Also called 3D medial axis of a polyhedron, Sherbrooke-Patrikalakis-Brisson medial axis.
Computes the centres of maximal inscribed balls of a polyhedral solid, a complex of sheets, seams and junctions, by tracing seams from junction to junction as Sherbrooke, Patrikalakis and Brisson did.
- Time
- O(k^3 n^3) worst
- Space
- O(n^2) extra
- Where
- k = the largest number of faces that are nearest to one point; n = the number of faces of the polyhedron
- Model
- Real RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Evan C. Sherbrooke, Nicholas M. Patrikalakis, Erik Brisson, 1996
The medial surface of a solid in is the set of interior points that have two or more nearest points on the boundary, or, up to closure, the set of centres of the maximal balls inside . It is the three-dimensional medial axis: together with the radius of the ball at each point, the medial axis transform, it determines the solid, since is the union of its maximal balls. In the plane the medial axis of a polygon is a graph of curves. In space it is a two-dimensional complex. Its sheets are surfaces where two boundary elements are nearest. Its seams are curves where three or more sheets meet. Its junctions are points where seams meet. For a polyhedron the sheets are pieces of planes and quadric surfaces; curved sheets come only from reflex edges and reflex vertices. Sherbrooke, Patrikalakis and Brisson computed this complex for general polyhedra by tracing the seams from junction to junction and then filling in the sheets. This page states their method and implements its core step exactly for convex polyhedra, where every sheet is flat and the trace becomes a walk on the edges of a four-dimensional polytope.
In plain words
Blow up a balloon inside a solid until it touches the walls. If it touches two walls at once, its centre is on the medial surface. Move the balloon around, keeping it as big as it can be, and its centre draws a set of thin sheets inside the solid, like the walls of a honeycomb.
Where three walls are touched at once, the centre runs along a line, a seam where sheets meet. Where four are touched, the seams meet at a point, a junction.
The method starts at the corners of the solid, where several faces meet. From each corner it follows a seam inward until the balloon touches one more wall. That point is a junction, and new seams leave from it. When every seam has been followed, the sheets are the flat or curved pieces between the seams.
The problem
Input. A polyhedral solid : a bounded closed set with a boundary made of planar polygons. For the implemented case is convex, given as with unit normals , one for each facet. The normals have rational coordinates, such as , so every quantity below is rational.
Output. The medial surface as a cell complex: the junctions, each with its radius and its set of nearest boundary elements; the seams, as curves between junctions with the elements nearest along them; and the sheets, as regions bounded by seams and by the edges of .
Definitions. For , is the distance from to the boundary of . A ball is maximal if no other ball inside contains it. The medial surface is the closure of the set of interior points with at least two nearest boundary points. The medial axis transform is the map on .
For a convex , the distance to the plane of facet is , and . The set of facets that attain the minimum is the tie set of . Then is in a sheet when , on a seam when , and a junction when the seams through end there.
The algorithm
TRACE-SEAMS(P)- 1
Q ← the vertices of P ▷ seams start on the boundary - 2
J ← an empty map from points to (radius, tie set) - 3
while Q is not empty do - 4
x ← POP(Q) - 5
if x is in J then continue - 6
(ρ, T) ← the distance from x to the boundary and the faces that attain it; J[x] ← (ρ, T) - 7
for each triple i, j, k in T and each sign of w = ±(n_i − n_j) × (n_i − n_k) do - 8
r ← max of n_l · w over l in T; S ← the faces l in T with n_l · w = r - 9
if i is not in S, or ρ = 0 and r ≥ 0, then skip this w ▷ not a seam, or leaves P - 10
t* ← the least t > 0 at which a face outside S is as near as S, or ρ / r if r > 0 and that is less - 11
y ← x + t* w; record the seam (x, y, S); push y on Q - 12
return J and the seams
Along the faces of are at distance and stay nearest; the faces of outside fall behind at once, since their is smaller. A face outside catches up at when , and line L10 takes the first such event. If the seam runs toward the boundary and reaches it at , at a vertex of . The sheets are not traced. The sheet of two faces and is the convex polygon spanned by the traced points whose tie set contains both, because its corners are junctions or vertices of .
The general case. For a nonconvex polyhedron, Sherbrooke, Patrikalakis and Brisson use the same plan with more kinds of boundary elements: faces, reflex edges and reflex vertices. A point of a seam is equidistant from three elements, so a seam is a curve on which a system of polynomial equations holds, and a junction solves a system with one more equation. The method finds the junctions at the vertices of the solid, traces each seam numerically from one junction to the next, and stops it where a fourth element becomes as near. It then forms each sheet from the cycle of seams and boundary edges around it. Two complications do not occur in the convex case. A nearest element must be checked against the whole boundary, not only against the planes. And seams are curved, so the trace steps along them and solves for the junction at the end.
Example
Let , with faces 0 to 5 on the planes , , , , and . The trace starts at the 8 corners.
| step | point | tie set | seams found | |
|---|---|---|---|---|
| corner | 0 | , : faces 2 and 4 catch up at , so the seam ends at | ||
| junction | 1 | 4 seams back to the corners at , and with , : face 0 catches up at , at | ||
| junction | 1 | the seam back to and 4 seams to the corners at |
The result has 2 junctions and 9 seams: 8 from the corners, each with 3 nearest faces and a radius that grows from 0 to 1, and the middle seam from to , with 4 nearest faces and a constant radius 1. The 12 sheets belong to the 12 pairs of adjacent faces. The 8 sheets between an end face and a side face are triangles, such as for faces 1 and 2. The 4 sheets between two side faces are trapezoids, such as for faces 2 and 4. The opposite faces and are both nearest only along the middle seam, so they have no sheet of their own. For the cube the two junctions merge into the centre, whose tie set has all 6 faces, and only the 8 corner seams remain.
Correctness
For a convex and an interior , the ball lies in every half-space, so it lies in . Its foot on each nearest plane is a boundary point, and every nearest boundary point is such a foot. So the nearest boundary points match the faces of one to one, and is on the medial surface exactly when .
The trace is a walk on a polytope. Lift to
the region under the graph of . The upper boundary of is the graph of . Its 2-faces project to the sheets, its edges off the floor project to the seams, and its vertices project to the junctions and to the vertices of . Lines L7 to L9 find every edge of at a vertex, except the edges in the floor. Line L10 finds the far end of each edge. Every junction is reached because of a simplex method argument. A vertex of with does not minimize , so it has an edge on which decreases. Following such edges reaches a vertex of in the floor, and the trace explores this path in reverse. The full proof is in the proof file.
These facts are checked by the tests, with Fraction. Random convex polyhedra are built from the 6 axis planes and 2 to 6 planes whose normals come from Pythagorean quadruples. On each one the tests check four things. A point on a traced seam has exactly the seam's faces as nearest; this is checked at over 500 rational points. The junctions equal those of a brute force, which solves for every 4 faces. For every triple of faces, the traced seams that contain it tile exactly the interval of the bisector line on which the three are nearest. And on the bisector plane of two faces, a rational point is in the polygon of the traced sheet corners exactly when both faces are nearest.
Proof: TRACE-SEAMS finds every junction and seam of the medial surface of a convex polyhedronfull
We use the pseudocode of the page. is a bounded convex polyhedron with nonempty interior, where indexes the facets of , one plane per facet, and each is a unit vector. Distinct facets have distinct outer normals. For , , and .
Lemma 1 (nearest points are feet on nearest facets). For in the interior of , the distance from to the boundary is , and the nearest boundary points are the points for , which are distinct. So has two or more nearest boundary points exactly when .
Proof. Let . For and every , , so the open ball lies in the interior of and every boundary point is at distance at least . For the point satisfies and for every , so is on the plane of facet , a boundary point at distance . Conversely, let be a boundary point with . Then for some , and . So , , and equality in the Cauchy-Schwarz step gives . Distinct facets have distinct normals, so their feet are distinct.
The lifted polytope. Let . It is bounded, since and , and it is the set of with and . Call the floor constraint and the constraint of facet ; its row is . A face of is the set where a given set of constraints is tight, and its dimension is minus the rank of the tight rows (for a face that is not empty).
Lemma 2 (rank of tie rows). For three distinct facets , the rows are linearly independent, and .
Proof. Three distinct unit vectors are not on one line, since a line meets the unit sphere in at most two points. So and are independent and . If , the last coordinate gives , so and .
Lemma 3 (edges and vertices). (a) A vertex of with is for a vertex of , and conversely. (b) An edge of that is not in the floor has, at each relative interior point , and exactly the facet constraints of a set with tight, and .
Proof. (a) The floor face is , whose faces are faces of , and its vertices are for the vertices of . (b) On the relative interior of an edge the tight set is constant and has rank 3. The floor is not tight there, so the tight set consists of facet constraints of some set , and for rank 3. Tightness gives for , and for all gives and .
Lemma 4 (local tie sets). Let with and , and let . For all small , for , and the facets of with the largest are exactly the facets nearest to , provided .
Proof. For , , so by continuity stays larger than every , , for small . Among the facets of the smallest distance belongs to the largest .
Lemma 5 (one step). Let be a vertex of and . The pairs that pass line L9 correspond one to one, up to the order in which they are found, to the edges of at that are not in the floor. For each, line L11 returns the other end of the edge, which is a vertex of , and is the tie set on the open edge.
Proof. Let be an edge at not in the floor, and let , , be a parametrization of it, with . (If the edge would be vertical, but on an open vertical segment below the graph of no facet constraint is tight, and on one above it the point is not in .) By Lemma 3, the open edge has a constant tie set with , and by Lemma 4, is the set of with the largest , and is that largest value. Take in . Then , so is orthogonal to and and is a nonzero multiple of by Lemma 2. One of the two signs of line L7 makes a positive multiple of . For it, line L8 computes and , and . If , the edge leaves the floor, so its coordinate grows, and . So the pair passes line L9.
Conversely, let pass line L9, with . For small the point has , because either or . By Lemma 4 it lies in on the graph of , with exactly the facet constraints of tight, which have rank at least 3 by Lemma 2. So it is on an edge (a face of dimension at most 1 that contains a segment) not in the floor, and this edge contains and the direction . Two passing pairs with the same edge have parallel of the same sign, and line L11 records both under one key, so each edge is recorded once.
Along the edge, the facet has . A facet has , and , with equality only for , where . So stays farther than for all if , and it becomes as near at otherwise. The floor is reached at when . The edge ends at the first of these events, which is of line L10. The set is bounded, so some event happens. At the end point a new constraint is tight: the floor, whose row has product with the direction , or a facet , whose row has product . All rows of have product 0 with the direction. So the new row is not in the span of the rows of , the tight rows at have rank 4, and is a vertex.
Lemma 6 (descent). Every vertex of with is joined to a vertex in the floor by a path of edges of that are not in the floor.
Proof. The linear function has its minimum 0 over , so does not minimize it. At a vertex of a polytope that does not minimize a linear function, some edge at the vertex decreases the function, since the edge directions at a vertex generate the cone of feasible directions there. That edge starts at , so it is not in the floor. Its other end is a vertex with a smaller . The polytope has finitely many vertices, so repeating this ends at a vertex with .
Theorem. TRACE-SEAMS terminates. The keys of are exactly the vertices of and the projections of the vertices of with , each with its and . The recorded seams are exactly the projections of the edges of not in the floor, each with its tie set.
Proof. Every point pushed on is a vertex of projected: those of line L1 by Lemma 3(a), and those of line L11 by Lemma 5. Line L5 processes each point at most once, there are finitely many vertices, and each processed point pushes finitely many points, so the loop terminates. Every recorded seam is an edge by Lemma 5.
For completeness, consider the graph whose nodes are the vertices of and whose arcs are the edges of not in the floor. When a node is processed, Lemma 5 records all its arcs and pushes all its neighbours. So the processed nodes are closed under neighbours, and they include every floor vertex by line L1. By Lemma 6 every node is connected in to a floor vertex, so every node is processed. Every arc has a processed end, so every arc is recorded.
Corollary (the medial surface). An interior point of lies on the medial surface exactly when , by Lemma 1, and then lies on a face of of dimension at most 2 that is not in the floor. Such a face is a 2-face where the constraints of two facets and are tight (a sheet), or an edge (a seam), or a vertex (a junction). The sheet of and is the projection of the 2-face . This is a convex polygon whose vertices are vertices of with , so it is the convex hull of the keys of whose tie sets contain and . This is what sheet_points returns. If that 2-face has dimension below 2, the pair has no sheet.
Corollary (size). is a 4-polytope with at most facets. By the upper bound theorem, a -polytope with facets has faces, so has vertices, edges and 2-faces, and the medial surface of a convex polyhedron with facets has junctions, seams and sheets.
Complexity
- The size of the output. is a polytope in with at most facets. By the upper bound theorem of McMullen it has vertices and edges, so the medial surface of a convex polyhedron with faces has junctions, seams and sheets. This is proved, not measured.
- The trace. Each traced point costs for its tie set at line L6. It tries triples at line L7, and each triple costs for the event search at line L10. Over points that is time. If no five faces are nearest to one point, and the bound is . The space is for the map and the seams.
- The input step. The code finds the vertices and the facets of from its half-spaces by brute force, in time. A B-rep gives them directly.
- The general case. For a nonconvex polyhedron the medial surface is part of the Voronoi diagram of the faces, edges and vertices, and its size can grow faster than quadratically in . The cost of the method of Sherbrooke, Patrikalakis and Brisson depends on the number of seams and on the numerical trace of each, through its step size and tolerance; this page states no worst-case bound for it.
Properties
- Exact in the convex case. Each junction solves a linear system, and each seam end is a ratio of rational numbers, so the code computes every point with Fraction. In the general case the junctions are algebraic numbers. Floating-point tracing can then miss a short seam or join two seams that should stay apart, and Culver, Keyser and Manocha compute them exactly for this reason.
- Degenerate ties. A point with five or more nearest faces, such as the centre of a cube, needs no special case. Line L8 groups all faces that stay nearest in a direction, and a seam with four or more nearest faces, such as the middle seam of the example, is traced once.
- Not stable. As in the plane, a small change to the solid can add a large sheet. A tiny bump on a face of a cube adds sheets that reach from the bump to the middle of the cube. Applications usually prune sheets whose radius changes fast relative to their size.
- Homotopy. The medial surface of a bounded open set has the same homotopy type as the set, so it keeps the handles and cavities of the solid.
- The convex case is the 3D straight skeleton. For a convex polyhedron the medial surface is the trace of the faces as they move inward at unit speed, the three-dimensional analogue of the straight skeleton of a convex polygon.
Variants and improvements
- Exact computation. Culver, Keyser and Manocha compute the seams and junctions of a general polyhedron with exact algebraic arithmetic, which removes the failures of floating-point tracing at the cost of much slower arithmetic.
- From the Voronoi diagram of samples. Sample the boundary densely and compute the Voronoi diagram of the samples. Its poles, the Voronoi vertices far from the sample, approximate the medial surface, and the power crust of Amenta, Choi and Kolluri uses them to rebuild the surface and the medial axis together. This works on any input but gives only an approximation, with spurious sheets that must be pruned.
- From a voxel grid. A distance transform on voxels and a thinning step give a discrete medial surface. It is simple and robust, but its accuracy is limited by the voxel size.
- Shrinking balls. For each boundary sample, shrink a ball tangent at the sample until it touches the boundary at one more point. Its centre is a medial point, and mid-surface extraction uses this to reduce thin solids.
- Curved solids. For solids bounded by NURBS surfaces, seams are traced by solving systems of equations on the surfaces, with the same plan of junctions, seams and sheets.
When to use it
Use the medial surface when the question is about local thickness or shape. Examples are hot spots in castings, where the largest inscribed balls show the last metal to solidify; thin walls in molded and printed parts; the reduction of thin solids to shells by mid-surface extraction; and the split of a solid into simple pieces for meshing. Use the exact convex trace when the solid or its pieces are convex polyhedra, and tracing with exact arithmetic for general polyhedra when the topology of the result matters. When only an approximate skeleton is needed, as in shape matching or animation, sampled or voxel methods are simpler and more robust. For thickness at single points, a shape diameter function is cheaper still.
Pitfalls
- Distance to planes, not to faces. In a nonconvex solid, the nearest point of a face plane may lie off the face, and a far face can be nearer than its plane suggests. The rule holds only for convex solids.
- Redundant planes. A plane that touches only at a vertex or an edge is at distance 0 there and would join the tie sets. Use only the planes of the facets, as the code does.
- Only one sign of the seam direction. The cross product gives the line of a seam, not its side. Test both signs and reject the one that leaves the solid or loses one of the three faces, as line L9 does.
- Missing seams in floating point. A junction with five or more nearest elements splits into several close junctions under rounding, and short seams appear or vanish. Use exact arithmetic or merge junctions closer than a tolerance, and accept that the topology may then be wrong.
- Expecting a curve skeleton. The medial surface of a solid is two-dimensional. A long square bar has four strips that run from its long edges to its axis, not a single curve, so curve skeletons need a further reduction.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/medial-surface-of-a-solid/. The authors are listed in prov/B7FYY7.jsonl.
"""The seams and junctions of the medial surface of a convex polyhedron.
The polyhedron is P = {x : n_i . x <= b_i} with unit normals n_i whose
coordinates are rational, such as (1, 2, 2)/3, so that the distance
b_i - n_i . x from an inside point to the plane of face i is rational and
every computation is exact with Fraction.
For an inside point x of a convex polyhedron, the nearest boundary points
are the feet on the nearest face planes, so x is on the medial surface
exactly when two or more faces are nearest. The medial surface is made of
flat sheets (two faces nearest), seams (three or more faces nearest along a
line) and junctions (the ends of seams inside P). The code traces the seams
from the vertices of P, as Sherbrooke, Patrikalakis and Brisson trace seams
from the boundary in the general case. Degenerate ties, such as the centre
of a cube where six faces are nearest, are handled.
Cost: finding the vertices and faces of P by brute force takes O(F^4) for F
planes. Each junction with a tie set T tries O(|T|^3) directions, and each
seam takes O(F) time to find its end, so the trace takes O(J (|T|^3 + F))
for J junctions and vertices.
"""
from __future__ import annotations
from fractions import Fraction
from itertools import combinations
from typing import Sequence
Vec = tuple[Fraction, Fraction, Fraction]
Plane = tuple[Vec, Fraction]
def dot(a: Vec, b: Vec) -> Fraction:
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
def sub(a: Vec, b: Vec) -> Vec:
return (a[0] - b[0], a[1] - b[1], a[2] - b[2])
def cross(a: Vec, b: Vec) -> Vec:
return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])
def det3(a: Vec, b: Vec, c: Vec) -> Fraction:
return dot(a, cross(b, c))
def solve3(rows: Sequence[Vec], rhs: Sequence[Fraction]) -> Vec | None:
"""Cramer's rule for a 3 by 3 system; None if it is singular."""
d = det3(rows[0], rows[1], rows[2])
if d == 0:
return None
cols = [tuple(r[k] for r in rows) for k in range(3)]
out = []
for k in range(3):
c = list(cols)
c[k] = tuple(rhs)
out.append(det3(c[0], c[1], c[2]) / d) # transpose has the same det
return (out[0], out[1], out[2])
class ConvexPolyhedron:
"""P = {x : n_i . x <= b_i}. Precondition: every n_i has length 1, all
data are Fractions, and P is bounded with nonempty interior."""
def __init__(self, planes: Sequence[tuple[Sequence[Fraction], Fraction]]):
self.planes: list[Plane] = [((Fraction(n[0]), Fraction(n[1]), Fraction(n[2])), Fraction(b))
for n, b in planes]
for n, _ in self.planes:
if dot(n, n) != 1:
raise ValueError("normals must be unit vectors")
self.vertices = self._vertices()
self.faces = self._faces()
def dist(self, i: int, x: Vec) -> Fraction:
n, b = self.planes[i]
return b - dot(n, x)
def inside(self, x: Vec) -> bool:
return all(self.dist(i, x) >= 0 for i in range(len(self.planes)))
def _vertices(self) -> list[Vec]:
out: set[Vec] = set()
for i, j, k in combinations(range(len(self.planes)), 3):
x = solve3([self.planes[i][0], self.planes[j][0], self.planes[k][0]],
[self.planes[i][1], self.planes[j][1], self.planes[k][1]])
if x is not None and self.inside(x):
out.add(x)
return sorted(out)
def _faces(self) -> list[int]:
"""The planes that carry a facet: at least three vertices on the plane
that are not on one line."""
out = []
for i in range(len(self.planes)):
on = [v for v in self.vertices if self.dist(i, v) == 0]
if any(cross(sub(b, a), sub(c, a)) != (0, 0, 0) for a, b, c in combinations(on, 3)):
out.append(i)
return out
def nearest(self, x: Vec) -> tuple[Fraction, frozenset[int]]:
"""The distance from x to the boundary and the faces that attain it."""
ds = {i: self.dist(i, x) for i in self.faces}
r = min(ds.values())
return r, frozenset(i for i, d in ds.items() if d == r)
Seam = tuple[Vec, Vec, frozenset[int]]
def medial_seams(P: ConvexPolyhedron) -> tuple[dict[Vec, tuple[Fraction, frozenset[int]]], list[Seam]]:
"""Trace the seam graph of the medial surface of P.
Returns the junctions and vertices of P, each with its radius and its set
of nearest faces, and the seams as (start, end, faces nearest along it)."""
queue: list[Vec] = list(P.vertices) # @line L1
junctions: dict[Vec, tuple[Fraction, frozenset[int]]] = {} # @line L2
seams: dict[tuple[frozenset[Vec], frozenset[int]], Seam] = {}
while queue: # @line L3
x = queue.pop() # @line L4
if x in junctions: # @line L5
continue
rho, T = P.nearest(x) # @line L6
junctions[x] = (rho, T)
ns = {i: P.planes[i][0] for i in P.faces}
for i, j, k in combinations(sorted(T), 3): # @line L7
w = cross(sub(ns[i], ns[j]), sub(ns[i], ns[k]))
if w == (0, 0, 0):
continue
for v in (w, (-w[0], -w[1], -w[2])):
r = max(dot(ns[l], v) for l in T) # @line L8
S = frozenset(l for l in T if dot(ns[l], v) == r)
if dot(ns[i], v) != r or not (rho > 0 or r < 0): # @line L9
continue
# along x + t v the faces of S are at distance rho - t r
best = rho / r if r > 0 else None # @line L10
for l in P.faces:
if l in S:
continue
a = dot(ns[l], v)
if a > r:
t = (P.dist(l, x) - rho) / (a - r)
if best is None or t < best:
best = t
assert best is not None and best > 0, "P must be bounded"
y = (x[0] + best * v[0], x[1] + best * v[1], x[2] + best * v[2]) # @line L11
key = (frozenset((x, y)), S)
if key not in seams:
seams[key] = (x, y, S)
queue.append(y)
return junctions, list(seams.values()) # @line L12
def sheet_points(junctions: dict[Vec, tuple[Fraction, frozenset[int]]], i: int, j: int) -> list[Vec]:
"""The corners of the sheet of faces i and j: the traced points whose
nearest faces include both. The sheet is their convex hull."""
return sorted(x for x, (_, T) in junctions.items() if i in T and j in T)
def in_convex_hull_planar(pts: Sequence[Vec], x: Vec) -> bool:
"""Is x in the convex hull of the coplanar points pts? Exact, by
projection to the coordinate plane where the points are not degenerate."""
if not pts:
return False
if len(pts) == 1:
return x == pts[0]
a = pts[0]
# the plane (or line) of the points
b = next((p for p in pts if p != a), None)
if b is None:
return x == a
c = next((p for p in pts if cross(sub(b, a), sub(p, a)) != (0, 0, 0)), None)
if c is None: # collinear: a segment
d = sub(b, a)
if cross(d, sub(x, a)) != (0, 0, 0):
return False
ts = [dot(sub(p, a), d) for p in pts]
tx = dot(sub(x, a), d)
return min(ts) <= tx <= max(ts)
n = cross(sub(b, a), sub(c, a))
if dot(n, sub(x, a)) != 0:
return False
k = max(range(3), key=lambda q: abs(n[q]))
ax = [q for q in range(3) if q != k]
pr = sorted({(p[ax[0]], p[ax[1]]) for p in pts})
q = (x[ax[0]], x[ax[1]])
def turn(o, p1, p2):
return (p1[0] - o[0]) * (p2[1] - o[1]) - (p1[1] - o[1]) * (p2[0] - o[0])
lower: list = []
for p in pr:
while len(lower) >= 2 and turn(lower[-2], lower[-1], p) <= 0:
lower.pop()
lower.append(p)
upper: list = []
for p in reversed(pr):
while len(upper) >= 2 and turn(upper[-2], upper[-1], p) <= 0:
upper.pop()
upper.append(p)
hull = lower[:-1] + upper[:-1]
return all(turn(hull[m], hull[(m + 1) % len(hull)], q) >= 0 for m in range(len(hull)))
test_medial_surface_of_a_solid.py 206 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/medial-surface-of-a-solid/. The authors are listed in prov/B7FYY7.jsonl.
import itertools
import random
import unittest
from fractions import Fraction as Fr
from medial_surface_of_a_solid import (ConvexPolyhedron, cross, dot, in_convex_hull_planar, medial_seams,
sheet_points, sub)
AXES = [((1, 0, 0), 1), ((-1, 0, 0), 1), ((0, 1, 0), 1), ((0, -1, 0), 1), ((0, 0, 1), 1), ((0, 0, -1), 1)]
def rational_unit_normals():
"""Unit vectors with rational coordinates from Pythagorean quadruples."""
out = set()
for (a, b, c), d in [((1, 2, 2), 3), ((2, 3, 6), 7), ((1, 4, 8), 9), ((4, 4, 7), 9), ((2, 6, 9), 11),
((6, 6, 7), 11)]:
for p in itertools.permutations((a, b, c)):
for s in itertools.product((1, -1), repeat=3):
out.add(tuple(Fr(s[k] * p[k], d) for k in range(3)))
return sorted(out)
NORMALS = rational_unit_normals()
def box(a, b, c):
return ConvexPolyhedron([((1, 0, 0), a), ((-1, 0, 0), 0), ((0, 1, 0), b), ((0, -1, 0), 0),
((0, 0, 1), c), ((0, 0, -1), 0)])
def random_polyhedron(rng):
planes = [(n, Fr(rng.randrange(6, 13), 3)) for n, _ in AXES]
for n in rng.sample(NORMALS, rng.randrange(2, 7)):
planes.append((n, Fr(rng.randrange(3, 10), 3)))
return ConvexPolyhedron(planes)
def solve(rows, rhs):
"""Gaussian elimination over Fractions; None if singular."""
m = [list(r) + [v] for r, v in zip(rows, rhs)]
k = len(m)
for c in range(k):
p = next((r for r in range(c, k) if m[r][c] != 0), None)
if p is None:
return None
m[c], m[p] = m[p], m[c]
for r in range(k):
if r != c and m[r][c] != 0:
f = m[r][c] / m[c][c]
m[r] = [x - f * y for x, y in zip(m[r], m[c])]
return [m[r][k] / m[r][r] for r in range(k)]
def brute_junctions(P):
"""Every interior point where four faces with independent equations tie
for nearest: solve b_l - n_l . x = rho for each 4-subset."""
out = set()
for quad in itertools.combinations(P.faces, 4):
s = solve([list(P.planes[l][0]) + [Fr(1)] for l in quad], [P.planes[l][1] for l in quad])
if s is None:
continue
x, rho = (s[0], s[1], s[2]), s[3]
if rho > 0 and P.inside(x) and set(quad) <= P.nearest(x)[1]:
out.add(x)
return out
def brute_seam_interval(P, i, j, k):
"""The parameter interval on the line equidistant from faces i, j, k on
which all three are nearest, by checking each other face in turn."""
ni, nj, nk = (P.planes[l][0] for l in (i, j, k))
w = cross(sub(ni, nj), sub(ni, nk))
x0 = solve([list(sub(ni, nj)), list(sub(ni, nk)), list(w)],
[P.planes[i][1] - P.planes[j][1], P.planes[i][1] - P.planes[k][1], Fr(0)])
x0 = tuple(x0)
lo, hi = None, None
# constraints of the form a + t c >= 0
cons = [(P.dist(i, x0), -dot(ni, w))]
for l in P.faces:
cons.append((P.dist(l, x0) - P.dist(i, x0), -dot(P.planes[l][0], w) + dot(ni, w)))
for a, c in cons:
if c == 0:
if a < 0:
return None
elif c > 0:
t = -a / c
lo = t if lo is None else max(lo, t)
else:
t = -a / c
hi = t if hi is None else min(hi, t)
if lo is None or hi is None or lo >= hi:
return None
return x0, w, lo, hi
def param(x0, w, y):
return dot(sub(y, x0), w) / dot(w, w)
class TestHandCases(unittest.TestCase):
def test_cube(self):
P = box(2, 2, 2)
J, S = medial_seams(P)
inner = {x: v for x, v in J.items() if v[0] > 0}
self.assertEqual(list(inner), [(1, 1, 1)])
self.assertEqual(inner[(1, 1, 1)], (1, frozenset(range(6))))
self.assertEqual(len(S), 8)
self.assertTrue(all(len(s[2]) == 3 for s in S))
def test_long_box(self):
P = box(4, 2, 2)
J, S = medial_seams(P)
inner = sorted(x for x, v in J.items() if v[0] > 0)
self.assertEqual(inner, [(1, 1, 1), (3, 1, 1)])
self.assertEqual(len(S), 9)
mid = [s for s in S if len(s[2]) == 4]
self.assertEqual(len(mid), 1)
self.assertEqual(mid[0][2], frozenset({2, 3, 4, 5}))
def test_sheet_of_cube(self):
P = box(2, 2, 2)
J, _ = medial_seams(P)
# the sheet of faces x = 2 and y = 2 is the triangle (2,2,0), (2,2,2), (1,1,1)
self.assertEqual(sheet_points(J, 0, 2), sorted([(2, 2, 0), (2, 2, 2), (1, 1, 1)]))
class TestRandom(unittest.TestCase):
def test_seams_are_equidistant(self):
"""Every rational point inside a traced seam has exactly the seam's
faces as nearest, and they number three or more."""
rng = random.Random(1)
checked = 0
for _ in range(30):
P = random_polyhedron(rng)
J, S = medial_seams(P)
for a, b, faces in S:
self.assertGreaterEqual(len(faces), 3)
for _ in range(4):
t = Fr(rng.randrange(1, 100), 100)
x = tuple(a[q] + t * (b[q] - a[q]) for q in range(3))
self.assertTrue(P.inside(x))
self.assertEqual(P.nearest(x)[1], faces)
checked += 1
for x, (rho, T) in J.items():
self.assertEqual(P.nearest(x), (rho, T))
self.assertGreater(checked, 500)
def test_junctions_against_brute_force(self):
rng = random.Random(2)
for _ in range(18):
P = random_polyhedron(rng)
J, _ = medial_seams(P)
self.assertEqual({x for x, v in J.items() if v[0] > 0}, brute_junctions(P))
self.assertEqual({x for x, v in J.items() if v[0] == 0}, set(P.vertices))
def test_seams_against_brute_force(self):
"""For every triple of faces, the traced seams that contain it tile
exactly the interval of the bisector line where the three are nearest."""
rng = random.Random(3)
for _ in range(18):
P = random_polyhedron(rng)
_, S = medial_seams(P)
for tri in itertools.combinations(P.faces, 3):
got = [s for s in S if set(tri) <= s[2]]
want = brute_seam_interval(P, *tri)
if want is None:
self.assertEqual(got, [])
continue
x0, w, lo, hi = want
ivs = sorted(tuple(sorted((param(x0, w, a), param(x0, w, b)))) for a, b, _ in got)
self.assertTrue(ivs)
self.assertEqual(ivs[0][0], lo)
self.assertEqual(ivs[-1][1], hi)
for p, q in zip(ivs, ivs[1:]):
self.assertEqual(p[1], q[0])
def test_sheets_against_nearest_faces(self):
"""A rational point of the bisector plane of faces i and j is in the
hull of the traced sheet corners exactly when i and j are nearest."""
rng = random.Random(4)
checked = 0
for _ in range(20):
P = random_polyhedron(rng)
J, _ = medial_seams(P)
for i, j in itertools.combinations(P.faces, 2):
pts = sheet_points(J, i, j)
if len(pts) < 3:
continue
m = sub(P.planes[i][0], P.planes[j][0])
e = next(cross(m, a) for a in ((1, 0, 0), (0, 1, 0), (0, 0, 1)) if cross(m, a) != (0, 0, 0))
f = cross(m, e)
c = tuple(sum(p[q] for p in pts) / len(pts) for q in range(3))
for _ in range(6):
s, t = Fr(rng.randrange(-40, 41), 20), Fr(rng.randrange(-40, 41), 20)
x = tuple(c[q] + s * e[q] + t * f[q] for q in range(3))
want = P.inside(x) and {i, j} <= P.nearest(x)[1]
self.assertEqual(in_convex_hull_planar(pts, x), want)
checked += 1
self.assertGreater(checked, 500)
if __name__ == "__main__":
unittest.main()
History
Blum introduced the medial axis in 1967 for shapes in the plane, and the definition carries over to any dimension. For polyhedra, Milenkovic computed the Voronoi diagram of a polyhedron by tracing in 1993. Sherbrooke, Patrikalakis and Brisson gave a conference version of their algorithm at the ACM Symposium on Solid Modeling and Applications in 1995 and the full algorithm in 1996. It handles polyhedra of any genus with nonconvex vertices and edges and finds the medial axis transform with its radius function. Culver, Keyser and Manocha made the computation exact in 1999 and 2004. From the late 1990s, approximations from boundary samples, such as the power crust of Amenta, Choi and Kolluri in 2001, became the usual choice for meshes and scanned shapes. Exact tracing remained the method for CAD solids with few faces.
References
- Evan C. Sherbrooke, Nicholas M. Patrikalakis and Erik Brisson, An algorithm for the medial axis transform of 3D polyhedral solids, IEEE Transactions on Visualization and Computer Graphics 2(1), 44 to 61, 1996, the classification of medial points into sheets, seams and junctions, the tracing of seams between junctions, and the examples on convex and nonconvex polyhedra with holes
- Tim Culver, John Keyser and Dinesh Manocha, Exact computation of the medial axis of a polyhedron, Computer Aided Geometric Design 21(1), 65 to 98, 2004, the exact computation of seams and junctions with algebraic numbers and its comparison with floating-point tracing
- Nina Amenta, Sunghee Choi and Ravi Krishna Kolluri, The power crust, Proceedings of the Sixth ACM Symposium on Solid Modeling and Applications, 2001, the approximation of the medial axis by the Voronoi poles of a dense boundary sample
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag B7FYY7 Edit this page History Report an error Markdown