Algorithmresearch
B-rep reconstruction from segmented scans
Also called boundary model reconstruction.
Benko, Martin and Varady's pipeline that fits faces to segments, computes edges and vertex blends between them and stitches a consistent B-rep.
- Time
- Θ(m k + F³ + T m + T V + a V log V + F E) worst
- Space
- Θ(m + F² + V + E) extra
- Where
- E = the number of edges; F = the number of regions; T = the number of triangles of the adjacency graph; V = the number of vertices; a = the number of adjacent pairs; k = the largest number of points in the 27 grid cells around one cell; m = the number of points
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Pál Benkő, Ralph R. Martin, Tamás Várady, 2001
B-rep reconstruction from segmented scans is the last step of reverse engineering: it turns a point cloud that is already cut into regions, one region per face, into a boundary representation with faces, edges, vertices and their connections. Benkő, Martin and Várady (2001) described the full procedure for conventional engineering parts. Each region gets a surface by geometric fitting; two faces are neighbors when their regions touch; the edge of two neighbors lies on the curve where their surfaces meet; a vertex lies where three or more faces meet; blends and vertex blends are fitted in the gaps between the faces; and the pieces are stitched into one closed model whose topology is consistent. This page gives the core of that procedure for parts with planar faces and sharp edges, where every step is exact: fit a plane to each region, find the adjacent pairs, intersect planes into edge lines and vertices, cut the lines into edges, and close the face loops. The output is checked with the Euler formula.
In plain words
A scanner gives many points on the surface of a part, and an earlier step has sorted them into groups, one group for each flat side. Now a CAD model must be built. First, a flat plane is laid through each group. Then the method looks for groups that come close to each other: these sides touch, so they share an edge. Two touching planes cross in a straight line, and the edge lies on that line. Where three touching sides meet, their planes cross in one point, a corner, if the scan really comes close to that point. The corners cut each line into edges, and the edges of a side close into a ring around it. In the end the method counts corners, edges and sides, to check that the model is a closed solid.
The problem
Input. Regions of points in space, where region samples one planar face of a solid, as a segmentation into primitives gives them; a distance such that points of two faces that share an edge come within of each other; a distance such that every corner has points of each of its faces within .
Output. A boundary model: a plane with a unit normal for each face; the set of adjacent pairs of faces; vertices with the set of faces that meet at each; edges, each a pair of vertices with the two faces that meet along it; and for each face the cycle of its vertices around the boundary, or an empty loop if its edges do not close.
The algorithm
BREP-FROM-SEGMENTS(R_1..R_F, δ, η)- 1
for each region R_f: P_f ← the plane that minimizes the sum of squared orthogonal distances to R_f - 2
A ← the pairs {j, k} with some p in R_j and q in R_k and |p − q| ≤ δ - 3
for each {j, k} in A: ℓ_jk ← the line P_j ∩ P_k (none if the planes are nearly parallel) - 4
for each triangle {j, k, l} of the graph A: v ← P_j ∩ P_k ∩ P_l; keep v if R_j, R_k and R_l each have a point within η of v - 5
merge kept vertices within η of each other; a merged vertex gets the union of the face sets - 6
for each {j, k} in A: sort the vertices whose faces include j and k along ℓ_jk; join them in consecutive pairs into edges - 7
for each face f: loop_f ← the cycle formed by the edges of f, or empty if they do not form one cycle - 8
return the planes, A, the vertices, the edges and the loops
Line L1. The plane goes through the centroid of the region, with the normal along the eigenvector of the smallest eigenvalue of the covariance matrix, as in principal component analysis. It minimizes the sum of the squared orthogonal distances, which is the geometric distance; for a plane with a unit normal the algebraic distance is the same as the geometric one, so this fit has none of the bias of algebraic fits of curved primitives.
Line L2. The points go into a grid of cubes of side with spatial hashing; two points within lie in the same cube or in two cubes that touch, so each point is compared only with the points of cubes. This is a fixed-radius near neighbors search.
Lines L3 and L4. With , the line has the direction and passes through , which satisfies both plane equations. The vertex of three planes solves the system with the rows ; it is rejected when the determinant is near . The nearness test of line L4 keeps only the corners that the scan supports: three faces can be pairwise adjacent without a common corner, for example the three sides of a triangular prism, whose planes have no common point.
Lines L5 to L7. At a corner where four or more faces meet, several triangles give the same point, and line L5 joins them. A line can carry several edges of the same two faces when the faces touch at more than one place; consecutive vertices along the line, taken in pairs, give them. A face without holes has a boundary that is one cycle, which line L7 follows.
Example
The box is sampled at the centers of square cells of side on each face: points on each of the two faces and , on and , and on and , points in all. The points nearest to an edge are at distance from it on both faces, so the gap across an edge is ; opposite faces are at least apart. So any in gives the true adjacency, and the run uses .
| step | result |
|---|---|
| L1 | six planes, for example with the normal , exact to the last digit |
| L2 | adjacent pairs: each face with the four faces that are not opposite to it |
| L3 | lines, for example along the axis for the faces and |
| L4 | triangles of the graph, one from each of the pairs or , or , or ; each corner has points within on its three faces, so all are kept |
| L5 | no merge: the corners are at least apart |
| L6 | each line carries corners, which give edge: edges |
| L7 | each face has a loop of corners, for example on |
So . The tests compare this result with the true box: the same adjacent pairs, the same corners within with the same face sets, and the same edges with the same two faces each.
Rigid motions and noise. For boxes with random sides between and , a random rotation and a random shift, sampled with , and , and Gaussian noise of standard deviation on every coordinate, the code gave these results (seed ):
| boxes with the true adjacency, corners and edges | largest corner error | |
|---|---|---|
| of | ||
| of | ||
| of | ||
| of |
These are measurements with the code of this page on these boxes, not a bound. The noise-free row agrees with the theorem below up to rounding; the other rows are not covered by it.
A concave edge. An L-shaped prism, the L extruded to the height , has faces. The code finds corners, edges and faces, loops of corners on the two L-shaped faces and of on the six sides, and . The two faces at the concave edge are adjacent because their points come within of each other inside the corner.
Correctness
The correctness file proves, in exact arithmetic, that the algorithm stops, and that it returns exactly the faces, the adjacency, the vertices, the edges and the face loops of a polyhedron when the data are exact and the two distances separate the right things:
- every region lies on the plane of its face and has three points that are not on one line;
- two faces that share an edge have points within , and two faces that do not have none;
- each vertex is simple, with exactly three faces, has points of each of its faces within , and is more than from every other vertex; for three pairwise adjacent faces without a common vertex, the planes have no common point or it is farther than from one of the regions;
- two faces share at most one edge, faces are disks, and the thresholds of lines L3 and L4 are below the angles of the true edges and vertices.
Then the result has the same numbers of vertices, edges and faces as the polyhedron, so holds exactly when the polyhedron has no handles. The tests check this on random boxes ( of exact) and on the L-shaped prism. Not proved: anything for noisy data, where the corners move with the planes and and can join or split faces and corners.
Proof: From exact samples of a polyhedron with simple vertices, the algorithm stops and returns its planes, adjacency, vertices, edges and face loopsfull
Setup. is a closed polyhedron with faces . Each face is a polygon without holes in the plane with . An edge of is a segment between two distinct vertices and lies in exactly two faces. The input regions and the distances satisfy:
- H1. lies on face and has three points that are not on one line.
- H2. For faces : some and have if and only if and share an edge.
- H3. Every vertex is simple: exactly three faces contain it, and for each pair of them exactly one edge at lies in both. Two faces share at most one edge. Each of the three regions of the faces at has a point within of , and distinct vertices are more than apart.
- H4. If three faces pairwise share an edge but no vertex lies on all three, then their planes have no unique common point, or that point is farther than from one of the three regions.
- H5. At every edge between faces and , is at least the threshold of line L3, and at every vertex with faces , is at least the threshold of line L4.
Arithmetic is exact, and the symmetric eigenproblem of line L1 is solved exactly, as on the real RAM.
Lemma 1 (line L1). Under H1, line L1 returns the plane , as or .
Proof. Let be the centroid of and . Every lies in the plane moved to the origin, so and . For a unit , ; if this were , every would be orthogonal to and to , so all points would lie on the line through with the direction , against H1. So is positive semidefinite, is a simple eigenvalue with the eigenvectors , and all other eigenvalues are positive. The eigenvector of the smallest eigenvalue is , and the offset is , since lies in .
Lemma 2 (line L2). Line L2 returns exactly the pairs with , and . Under H2 this is the set of pairs of faces that share an edge.
Proof. The code puts each point in the cell and compares each point with all points of the cells whose indices differ from its own by at most in each coordinate. It adds a pair only after it tests the distance, so every pair it adds is close. Conversely, if with , , , then for each , so and differ by at most ; when the code visits it compares it with and adds , unless the pair is there already.
From now on, by Lemmas 1 and 2, the planes are the planes of the faces and is the set of pairs of faces that share an edge.
Lemma 3 (line L3). For , line L3 returns a point and a direction of the line , and every edge between and lies on this line.
Proof. Let ; by H5, and the code does not return none. By the cyclic rule of the triple product, and , while and . So has and . The direction is orthogonal to both normals, and two planes with independent normals meet in exactly one line, so the line is . An edge between and lies in both faces, so in both planes and on the line.
Lemma 4 (lines L4 and L5). After line L5 the vertices are exactly the vertices of , each once, and the face set of each is the set of the three faces that contain it.
Proof. Take a vertex with faces . By H3, each pair of them shares an edge, so is a triangle of . By H5 the normals are independent and the system of line L4 has one solution, which is , since lies on the three planes. By H3 each of the three regions has a point within of . So line L4 keeps .
Take a triangle of that is not the face set of a vertex. If some vertex lay on all three faces, then by H3 its faces would be exactly , which is excluded. So H4 applies: either the planes have no unique common point, and line L4 gets none (when the determinant is or below the threshold), or the point is farther than from one region, and line L4 drops it. So line L4 keeps no point from such a triangle.
So the kept points are the vertices of , each kept once, from the triangle of its own faces. In line L5, each new point is compared with the points kept before it; these are other vertices of , which by H3 are more than away, so no merge happens, and each vertex keeps the face set .
Lemma 5 (line L6). Line L6 returns exactly the edges of , each once, with the pair of faces that contain it.
Proof. Take , and let be the edge between and , which exists by Lemma 2 and is unique by H3. Its two endpoints lie in both faces, so by Lemma 4 they are vertices whose face sets contain and . Conversely, let be a vertex whose face set contains and . By H3 some edge at lies in both and ; by uniqueness it is , so is an endpoint of . So the list of line L6 has exactly the two endpoints of , which are distinct, the line of Lemma 3 exists, and the pairing gives the one edge with the endpoints of . Every edge of lies in two faces that then share it, so every edge of arises from its pair in , and only once.
Lemma 6 (line L7). For each face , line L7 returns the vertices of in the order of its boundary.
Proof. By Lemma 5, the edges whose face pair contains are exactly the edges of the polygon . A polygon without holes has a boundary that is one simple cycle of edges, so in the graph of these edges every vertex has exactly two distinct neighbors, and the code does not return the empty loop. The walk starts at a vertex and each step moves to the neighbor of the current vertex other than the one it came from, so it follows the cycle in one direction, visits each of the vertices once, and returns to the start after steps. The list then has vertices, which is the number of vertices of the graph, and the code returns it.
Theorem 1 (termination). On every input the algorithm stops.
Proof. Lines L1 to L6 are loops over finite sets: the regions, the points of cells for each point, the pairs in , the triples of faces, the kept vertices and the vertices on a line. In the code, the eigenproblem of line L1 uses at most a fixed number of Jacobi sweeps. In line L7, the walk starts only when every vertex of the edge graph of has exactly two neighbors. A finite graph in which every vertex has degree is a disjoint union of cycles, and the component of the start is one cycle of some length , since an edge joins two distinct vertices. For the walk follows the cycle as in Lemma 6 and is back at the start after steps. For , the start has the neighbor twice and has twice; the walk goes to , where both neighbors are , and stops. So every walk stops after at most as many steps as the graph has vertices.
Theorem 2 (correctness). Under H1 to H5 the algorithm returns the planes of the faces of , the pairs of faces of that share an edge, the vertices of with their faces, the edges of with their faces, and the boundary cycle of each face. In particular of the result equals that of , which is for a polyhedron of genus whose faces are disks; so the check passes exactly when has no handles.
Proof. Lemmas 1 to 6 give the parts in turn, and Theorem 1 shows that the algorithm returns them. The counts of the result are the counts of . For a closed polyhedral surface whose faces are disks, by the Euler-Poincaré formula.
Corollary 1 (the box of the example). For the box with , sampled at the centers of cells of side that divide the sides, with , and , the algorithm returns the corners, the edges and the faces of the box, with .
Proof. Each face has at least cell centers, which are not on one line, so H1 holds. For two faces that share an edge, the two sample points nearest to the edge are at distance from it, orthogonally in the two faces, so they are apart. Two opposite faces are at distance at least . So H2 holds. Each corner is simple, each pair of its faces shares one edge, and two faces share at most one edge. The nearest point of each face to a corner is the center of the corner cell, at , and two corners are at least apart; so H3 holds. Three pairwise adjacent faces take one face from each pair of opposite faces, so they always have a common corner, and H4 holds with nothing to check. The normals are the unit vectors of the axes, so and , and H5 holds. Theorem 2 gives the claim, with .
What is not proved. Nothing is proved for noisy data. With noise, the planes of line L1 are only near the true planes, the vertices and edges move with them, and the choice of and decides whether faces are joined and corners merged correctly; the page reports measurements for this, not a bound. Vertices with four or more faces, faces with holes, and curved faces are outside the hypotheses. In floating point, the corners of the example agree with the true corners within in the tests.
Complexity
Line L1 is , with eigenproblems. Line L2 compares each point with the points of cells, . Line L4 lists the triples of faces, , and tests each of the triangles against the points of three regions, in the worst case; line L5 compares each new vertex with the kept ones, . Line L6 finds and sorts the vertices of each of the lines, , and line L7 follows the edges of each face, . Together this is the bound in the front matter on the real RAM. For a part with bounded sampling density and faces of bounded degree, , , and are small and the work is dominated by for the fits and the hashing and for the corner tests; a list of triangles from the adjacency lists, as in triangle counting, removes the term.
Properties
- Topology from data. The adjacency, and with it the whole topology, comes from the distances between the regions, not from the planes; two planes that cross far from the part never make an edge.
- Geometry from fits. Vertices and edges come from the fitted planes, so they are sharper and more accurate than the scan points near the edges, which are often missing or noisy.
- Invariant. A rigid motion of the points moves the result with it, since every step uses distances and planes only.
- Checkable. The Euler formula and the closed loops show at once whether the model is a valid closed solid.
- Greedy merge. Line L5 joins each new vertex to the first kept vertex within , so with noise the merged vertices can depend on the order of the faces.
Variants and improvements
- Curved faces. Benkő, Martin and Várady handle faces that are simple analytic surfaces, such as cylinders, cones and spheres, and swept surfaces, and the edges come from surface-surface intersection instead of plane intersection.
- Blends. In real parts, sharp edges are often rounded. The procedure fits rolling-ball blends to the strips between the primary faces and fills the corners with vertex blends, so the edges are the boundaries of the blends, not plane intersections.
- Constraints. Faces that should be parallel, perpendicular or coaxial are fitted together with constrained fitting, so that the model keeps the design intent and the corners are better placed.
- Repair. Gaps and small slivers that remain are closed with B-rep healing, or kept with a local tolerance as in tolerant modeling.
- Candidate selection. Later methods intersect all candidate planes and choose the faces of the result by optimization, for example PolyFit by Nan and Wonka (2017), and learning methods such as Point2CAD (Liu and others, 2024) reconstruct the topology of curved faces from point clouds. The reference data for such methods are B-rep models, for example of the ABC data set (Koch and others, 2019).
When to use it
Use it when the part is made of faces of known types, the scan covers all faces and a segmentation is available, for example from efficient RANSAC or variable-order fitting, and the goal is a CAD model that a modeler can edit. For organic shapes without clear faces, a mesh from surface reconstruction, such as Poisson reconstruction, is the better target.
Pitfalls
- too small or too large. Below the gap across an edge, for samples of spacing , no faces are adjacent and nothing is built; the tests show this. Above the thickness of a thin wall, the two sides of the wall become adjacent.
- too small. The corner lies outside the data, at about from the nearest point or farther where the scan misses the edge; with a smaller no corner is kept, as the tests show.
- Vertices of four or more faces. At the apex of a square pyramid, the two pairs of opposite faces also come within of each other, and with noise the four planes meet in up to four nearby points, not one. Line L5 merges them only if they lie within ; otherwise short false edges appear.
- Nearly parallel neighbors. Two adjacent faces at a very flat angle meet in a line that moves far when the normals change a little, so a small fit error gives a large edge error.
- Wrong segments. One face split into two regions gives two coplanar planes whose line is not defined, and two faces in one region give a bad plane. The method needs a good segmentation.
- Holes and inner loops. A face with a hole has a boundary of several cycles, and line L7 then returns no loop; the full procedure needs loops with holes and the Euler formula with rings.
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/brep-reconstruction-from-scans/. The authors are listed in prov/RBGNXS.jsonl.
"""B-rep reconstruction of a polyhedral part from a segmented scan.
The input is a list of regions of 3D points, one region per face, as a
segmentation gives them. Each region is fitted by a plane; two faces are
adjacent when some of their points are close; adjacent faces meet in an edge
on the line where their planes meet; three faces that are pairwise adjacent
meet in a vertex where their planes meet, if the data come close to that
point. Edges are the segments between the vertices of their two faces, and
the edges of a face form its boundary loop. The result is checked with the
Euler formula V - E + F = 2 for a closed solid without holes.
Only planar faces with sharp edges are handled here: no curved faces, no
blends, and no faces with inner loops.
"""
from itertools import combinations
from math import sqrt
from typing import Dict, FrozenSet, List, Optional, Sequence, Set, Tuple
from re1lin import cross, dot, jacobi_eigen, norm, solve, sub
Vec3 = Tuple[float, float, float]
Plane = Tuple[Vec3, float] # unit normal n and offset c of the plane n . x = c
def fit_plane(points: Sequence[Vec3]) -> Plane:
"""Least-squares plane (orthogonal distance): the centroid and the eigenvector of the smallest eigenvalue."""
if len(points) < 3:
raise ValueError("a plane needs at least three points")
m = len(points)
c = tuple(sum(p[k] for p in points) / m for k in range(3))
cov = [[sum((p[a] - c[a]) * (p[b] - c[b]) for p in points) for b in range(3)] for a in range(3)]
values, vectors = jacobi_eigen(cov)
n = tuple(vectors[0])
s = norm(n)
n = (n[0] / s, n[1] / s, n[2] / s)
return n, dot(n, c)
def adjacent_pairs(regions: Sequence[Sequence[Vec3]], delta: float) -> Set[Tuple[int, int]]:
"""Pairs (j, k), j < k, with a point of region j within delta of a point of region k (grid hashing)."""
grid: Dict[Tuple[int, int, int], List[Tuple[int, Vec3]]] = {}
for j, reg in enumerate(regions):
for p in reg:
grid.setdefault(tuple(int(p[a] // delta) for a in range(3)), []).append((j, p))
pairs = set()
d2 = delta * delta
for cell, items in grid.items():
near = [it for dx in (-1, 0, 1) for dy in (-1, 0, 1) for dz in (-1, 0, 1)
for it in grid.get((cell[0] + dx, cell[1] + dy, cell[2] + dz), ())]
for j, p in items:
for k, q in near:
if j < k and (j, k) not in pairs and dot(sub(p, q), sub(p, q)) <= d2:
pairs.add((j, k))
return pairs
def plane_line(a: Plane, b: Plane, min_sin: float = 1e-3) -> Optional[Tuple[Vec3, Vec3]]:
"""The line where two planes meet, as (point, unit direction); None if they are nearly parallel."""
(n1, c1), (n2, c2) = a, b
d = cross(n1, n2)
s = norm(d)
if s < min_sin:
return None
u, v = cross(n2, d), cross(d, n1)
x0 = tuple((c1 * u[k] + c2 * v[k]) / (s * s) for k in range(3))
return x0, (d[0] / s, d[1] / s, d[2] / s)
def plane_vertex(a: Plane, b: Plane, c: Plane, min_det: float = 1e-6) -> Optional[Vec3]:
"""The point where three planes meet; None if their normals are nearly dependent."""
if abs(dot(a[0], cross(b[0], c[0]))) < min_det:
return None
x = solve([list(a[0]), list(b[0]), list(c[0])], [a[1], b[1], c[1]])
return tuple(x)
def _near(points: Sequence[Vec3], v: Vec3, eta: float) -> bool:
e2 = eta * eta
return any(dot(sub(p, v), sub(p, v)) <= e2 for p in points)
class BRep:
"""Faces (planes), vertices (points with their faces), edges (vertex pairs with their two faces) and loops."""
def __init__(self):
self.planes: List[Plane] = []
self.adjacency: Set[Tuple[int, int]] = set()
self.vertices: List[Vec3] = []
self.vertex_faces: List[FrozenSet[int]] = []
self.edges: List[Tuple[int, int, Tuple[int, int]]] = [] # (vertex a, vertex b, (face j, face k))
self.loops: Dict[int, List[int]] = {}
def euler(self) -> int:
return len(self.vertices) - len(self.edges) + len(self.planes)
def reconstruct(regions: Sequence[Sequence[Vec3]], delta: float, eta: float) -> BRep:
"""Build a B-rep from segmented points, one region per planar face.
delta: largest gap between points of two adjacent faces; eta: largest
distance from a vertex to the points of its faces, and the merge distance
of vertices. Precondition: every region has at least three points that do
not lie on one line. Cost: Theta(m) expected for the adjacency on m points
of bounded density, plus Theta(T m) for the T triangles of the adjacency
graph, plus Theta(F^3) to list them.
"""
B = BRep()
B.planes = [fit_plane(reg) for reg in regions] # @line L1
B.adjacency = adjacent_pairs(regions, delta) # @line L2
lines = {pair: plane_line(B.planes[pair[0]], B.planes[pair[1]]) for pair in B.adjacency} # @line L3
found: List[Tuple[Vec3, Set[int]]] = []
for j, k, l in combinations(range(len(regions)), 3):
if (j, k) in B.adjacency and (j, l) in B.adjacency and (k, l) in B.adjacency:
v = plane_vertex(B.planes[j], B.planes[k], B.planes[l]) # @line L4
if v is None or not all(_near(regions[f], v, eta) for f in (j, k, l)):
continue
for w in found: # @line L5
if norm(sub(w[0], v)) <= eta:
w[1].update((j, k, l))
break
else:
found.append((v, {j, k, l}))
B.vertices = [v for v, _ in found]
B.vertex_faces = [frozenset(fs) for _, fs in found]
for (j, k) in sorted(B.adjacency):
line = lines[(j, k)]
on = [i for i, fs in enumerate(B.vertex_faces) if j in fs and k in fs]
if line is None or len(on) < 2:
continue
on.sort(key=lambda i: dot(sub(B.vertices[i], line[0]), line[1]))
for a in range(0, len(on) - 1, 2): # @line L6
B.edges.append((on[a], on[a + 1], (j, k)))
for f in range(len(regions)):
B.loops[f] = face_loop(B, f) # @line L7
return B # @line L8
def face_loop(B: BRep, f: int) -> List[int]:
"""The vertices of face f in the order of its boundary cycle; [] if its edges do not form one cycle."""
nbr: Dict[int, List[int]] = {}
for a, b, (j, k) in B.edges:
if f in (j, k):
nbr.setdefault(a, []).append(b)
nbr.setdefault(b, []).append(a)
if not nbr or any(len(v) != 2 for v in nbr.values()):
return []
start = min(nbr)
loop, prev, cur = [start], None, start
while True:
nxt = nbr[cur][0] if nbr[cur][0] != prev else nbr[cur][1]
if nxt == start:
break
loop.append(nxt)
prev, cur = cur, nxt
return loop if len(loop) == len(nbr) else []
re1lin.py 221 lines
# SPDX-License-Identifier: MIT
# Shared helper of the re1 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small dense linear algebra for the re1 fitting pages.
Vectors are tuples or lists of numbers, matrices are lists of rows. The
elimination routines work with int, Fraction or float entries: with Fraction
they are exact. The Jacobi routine is float only. The helper holds no
fitting algorithm of any page.
"""
from fractions import Fraction
from math import atan2, cos, sin, sqrt
from typing import List, Optional, Sequence, Tuple
Vec = Sequence
Mat = List[List]
# ---- vectors ----
def dot(a: Vec, b: Vec):
return sum(x * y for x, y in zip(a, b))
def add(a: Vec, b: Vec) -> tuple:
return tuple(x + y for x, y in zip(a, b))
def sub(a: Vec, b: Vec) -> tuple:
return tuple(x - y for x, y in zip(a, b))
def scale(s, a: Vec) -> tuple:
return tuple(s * x for x in a)
def norm(a: Vec) -> float:
return sqrt(float(dot(a, a)))
def cross(a: Vec, b: Vec) -> tuple:
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])
# ---- matrices ----
def zeros(n: int, m: int, z=0) -> Mat:
return [[z] * m for _ in range(n)]
def transpose(a: Mat) -> Mat:
return [list(r) for r in zip(*a)]
def mat_vec(a: Mat, x: Vec) -> list:
return [dot(r, x) for r in a]
def mat_mul(a: Mat, b: Mat) -> Mat:
bt = transpose(b)
return [[dot(r, c) for c in bt] for r in a]
def gram(rows: Sequence[Vec]) -> Mat:
"""The matrix sum over the rows u of u u^T."""
n = len(rows[0])
g = zeros(n, n)
for u in rows:
for i in range(n):
if u[i] == 0:
continue
for j in range(n):
g[i][j] += u[i] * u[j]
return g
# ---- elimination (exact with Fraction) ----
def solve(a: Mat, b: Vec, tol: float = 0.0) -> Optional[list]:
"""Solve a x = b for a square a by Gaussian elimination with partial pivoting.
Returns None when a pivot has absolute value at most tol (singular
matrix). With Fraction entries and tol = 0 the answer is exact.
"""
n = len(a)
m = [list(a[i]) + [b[i]] for i in range(n)]
for c in range(n):
p = max(range(c, n), key=lambda r: abs(m[r][c]))
if abs(m[p][c]) <= tol:
return None
m[c], m[p] = m[p], m[c]
for r in range(c + 1, n):
f = m[r][c] / m[c][c]
if f != 0:
for k in range(c, n + 1):
m[r][k] -= f * m[c][k]
x = [0] * n
for r in range(n - 1, -1, -1):
s = m[r][n] - sum(m[r][k] * x[k] for k in range(r + 1, n))
x[r] = s / m[r][r]
return x
def lstsq(a: Mat, b: Vec, tol: float = 0.0) -> Optional[list]:
"""Least squares solution of a x = b by the normal equations (a^T a) x = a^T b."""
at = transpose(a)
return solve(mat_mul(at, a), mat_vec(at, b), tol)
def nullspace(a: Mat) -> List[list]:
"""A basis of the null space of a, by reduced row echelon form. Exact for Fraction entries."""
m = [[Fraction(x) for x in r] for r in a]
rows, cols = len(m), len(m[0])
piv = []
r = 0
for c in range(cols):
p = next((i for i in range(r, rows) if m[i][c] != 0), None)
if p is None:
continue
m[r], m[p] = m[p], m[r]
inv = 1 / m[r][c]
m[r] = [x * inv for x in m[r]]
for i in range(rows):
if i != r and m[i][c] != 0:
f = m[i][c]
m[i] = [x - f * y for x, y in zip(m[i], m[r])]
piv.append(c)
r += 1
if r == rows:
break
free = [c for c in range(cols) if c not in piv]
basis = []
for f in free:
v = [Fraction(0)] * cols
v[f] = Fraction(1)
for i, c in enumerate(piv):
v[c] = -m[i][f]
basis.append(v)
return basis
def rank(a: Mat) -> int:
return len(a[0]) - len(nullspace(a))
# ---- symmetric matrices (float) ----
def cholesky(a: Mat, rtol: float = 0.0) -> Mat:
"""Lower triangular l with l l^T = a, for a symmetric positive definite a.
Raises ValueError when a pivot is at most rtol times the largest diagonal entry.
"""
n = len(a)
l = zeros(n, n, 0.0)
big = max(abs(float(a[i][i])) for i in range(n))
for i in range(n):
for j in range(i + 1):
s = a[i][j] - sum(l[i][k] * l[j][k] for k in range(j))
if i == j:
if s <= rtol * big:
raise ValueError("matrix is not positive definite")
l[i][i] = sqrt(s)
else:
l[i][j] = s / l[j][j]
return l
def lower_solve(l: Mat, b: Vec) -> list:
x = []
for i in range(len(l)):
x.append((b[i] - sum(l[i][k] * x[k] for k in range(i))) / l[i][i])
return x
def upper_solve_t(l: Mat, b: Vec) -> list:
"""Solve l^T x = b for a lower triangular l."""
n = len(l)
x = [0.0] * n
for i in range(n - 1, -1, -1):
x[i] = (b[i] - sum(l[k][i] * x[k] for k in range(i + 1, n))) / l[i][i]
return x
def jacobi_eigen(a: Mat, sweeps: int = 100, eps: float = 1e-15) -> Tuple[list, Mat]:
"""Eigenvalues and eigenvectors of a symmetric matrix by cyclic Jacobi rotations.
Returns (values, vectors) with the values in ascending order and
vectors[k] the unit eigenvector of values[k].
"""
n = len(a)
s = [[float(x) for x in r] for r in a]
v = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
for _ in range(sweeps):
off = sum(s[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
if off <= eps * eps * max(1.0, sum(s[i][i] ** 2 for i in range(n))):
break
for p in range(n - 1):
for q in range(p + 1, n):
if s[p][q] == 0.0:
continue
th = 0.5 * atan2(2 * s[p][q], s[q][q] - s[p][p])
c, sn = cos(th), sin(th)
for k in range(n):
skp, skq = s[k][p], s[k][q]
s[k][p] = c * skp - sn * skq
s[k][q] = sn * skp + c * skq
for k in range(n):
spk, sqk = s[p][k], s[q][k]
s[p][k] = c * spk - sn * sqk
s[q][k] = sn * spk + c * sqk
for k in range(n):
vkp, vkq = v[k][p], v[k][q]
v[k][p] = c * vkp - sn * vkq
v[k][q] = sn * vkp + c * vkq
order = sorted(range(n), key=lambda i: s[i][i])
return [s[i][i] for i in order], [[v[k][i] for k in range(n)] for i in order]
test_brep_reconstruction_from_scans.py 191 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/brep-reconstruction-from-scans/. The authors are listed in prov/RBGNXS.jsonl.
"""Tests: the fitted planes of a scanned box give the adjacency, the edges and the corners of the true box."""
import os
import random
import sys
from itertools import product
from math import sqrt
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from brep_reconstruction_from_scans import ( # noqa: E402
BRep, adjacent_pairs, face_loop, fit_plane, plane_line, plane_vertex, reconstruct)
S = 0.1 # sample spacing
def face_grid(o, u, v, nu, nv, s=S):
"""Points at the centers of an nu by nv grid of cells of size s, from corner o along u and v."""
return [tuple(o[k] + (i + 0.5) * s * u[k] + (j + 0.5) * s * v[k] for k in range(3))
for i in range(nu) for j in range(nv)]
X, Y, Z = (1, 0, 0), (0, 1, 0), (0, 0, 1)
def box(a, b, c, s=S):
"""Six regions: faces x=0, x=a, y=0, y=b, z=0, z=c of the box [0,a] x [0,b] x [0,c]."""
na, nb, nc = round(a / s), round(b / s), round(c / s)
return [face_grid((0, 0, 0), Y, Z, nb, nc), face_grid((a, 0, 0), Y, Z, nb, nc),
face_grid((0, 0, 0), X, Z, na, nc), face_grid((0, b, 0), X, Z, na, nc),
face_grid((0, 0, 0), X, Y, na, nb), face_grid((0, 0, c), X, Y, na, nb)]
def true_box(a, b, c):
"""The true box: corners with their face sets, adjacency, and edges as (corner set, face pair)."""
corners = {}
for i, j, k in product((0, 1), repeat=3):
corners[(i * a, j * b, k * c)] = frozenset((i, 2 + j, 4 + k))
adjacency = {(f, g) for f in range(6) for g in range(f + 1, 6) if f // 2 != g // 2}
edges = set()
for f, g in adjacency:
ends = frozenset(p for p, fs in corners.items() if f in fs and g in fs)
edges.add((ends, (f, g)))
return corners, adjacency, edges
def rotation(rng):
q = [rng.gauss(0, 1) for _ in range(4)]
s = sqrt(sum(x * x for x in q))
w, x, y, z = (c / s for c in q)
return [[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
[2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
[2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]]
def move(p, rm, t):
return tuple(sum(rm[i][k] * p[k] for k in range(3)) + t[i] for i in range(3))
def dist(p, q):
return sqrt(sum((p[k] - q[k]) ** 2 for k in range(3)))
def match(br: BRep, true_pts, tol):
"""Map each reconstructed vertex to the true corner within tol, or None if this fails."""
m = {}
for i, v in enumerate(br.vertices):
near = [p for p in true_pts if dist(v, true_pts[p]) <= tol]
if len(near) != 1:
return None
m[i] = near[0]
return m if len(set(m.values())) == len(true_pts) == len(m) else None
def same_as_true_box(br: BRep, a, b, c, rm=None, t=(0, 0, 0), tol=1e-9):
corners, adjacency, edges = true_box(a, b, c)
rm = rm or [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
placed = {p: move(p, rm, t) for p in corners}
m = match(br, placed, tol)
if m is None or br.adjacency != adjacency:
return False
if any(br.vertex_faces[i] != corners[m[i]] for i in m):
return False
got = {(frozenset((m[x], m[y])), fj) for x, y, fj in br.edges}
return len(br.edges) == 12 and got == edges and all(len(br.loops[f]) == 4 for f in range(6))
def test_box_worked_example():
br = reconstruct(box(2.0, 1.0, 0.5), 1.5 * S, 1.5 * S)
assert same_as_true_box(br, 2.0, 1.0, 0.5, tol=1e-12)
assert (len(br.vertices), len(br.edges), len(br.planes)) == (8, 12, 6)
assert br.euler() == 2
assert br.loops[4] == [0, 2, 6, 4]
def test_random_rigid_boxes_noise_free():
rng = random.Random(1)
exact = 0
for _ in range(20):
a, b, c = (round(rng.uniform(0.5, 2.0), 1) for _ in range(3))
rm, t = rotation(rng), [rng.uniform(-5, 5) for _ in range(3)]
regs = [[move(p, rm, t) for p in r] for r in box(a, b, c)]
br = reconstruct(regs, 1.5 * S, 2 * S)
exact += same_as_true_box(br, a, b, c, rm, t, tol=1e-9) and br.euler() == 2
assert exact == 20 # 20 of 20 trials
def test_random_noisy_boxes_measured():
rng = random.Random(7)
exact = 0
for _ in range(20):
a, b, c = (round(rng.uniform(0.5, 2.0), 1) for _ in range(3))
rm, t = rotation(rng), [rng.uniform(-5, 5) for _ in range(3)]
regs = [[tuple(x + rng.gauss(0, 0.002) for x in move(p, rm, t)) for p in r] for r in box(a, b, c)]
br = reconstruct(regs, 1.5 * S, 2 * S)
exact += same_as_true_box(br, a, b, c, rm, t, tol=0.005)
assert exact == 20 # measured: 20 of 20, largest corner error 0.00195
def test_adjacency_matches_brute_force():
rng = random.Random(3)
for _ in range(10):
regs = [[tuple(rng.uniform(0, 3) for _ in range(3)) for _ in range(rng.randint(5, 30))] for _ in range(6)]
delta = rng.uniform(0.1, 0.6)
brute = {(j, k) for j in range(6) for k in range(j + 1, 6)
if any(dist(p, q) <= delta for p in regs[j] for q in regs[k])}
assert adjacent_pairs(regs, delta) == brute
def test_fit_plane_exact_on_plane_points():
rng = random.Random(5)
n = (2 / 3, -1 / 3, 2 / 3)
u, v = (1 / sqrt(2), 0, -1 / sqrt(2)), (1 / sqrt(18), 4 / sqrt(18), 1 / sqrt(18))
pts = [tuple(3 * n[k] + s * u[k] + t * v[k] for k in range(3))
for s, t in ((rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(50))]
m, c = fit_plane(pts)
sign = 1 if m[0] > 0 else -1
assert all(abs(sign * m[k] - n[k]) < 1e-12 for k in range(3))
assert abs(sign * c - 3) < 1e-12
def test_line_and_vertex_of_planes():
px, py, pz = ((1, 0, 0), 2.0), ((0, 1, 0), 3.0), ((0, 0, 1), -1.0)
x0, d = plane_line(px, py)
assert (x0[0], x0[1]) == (2.0, 3.0) and abs(abs(d[2]) - 1) < 1e-15
assert plane_vertex(px, py, pz) == (2.0, 3.0, -1.0)
assert plane_line(px, ((1, 0, 0), 5.0)) is None # parallel planes
assert plane_vertex(px, py, ((0.6, 0.8, 0.0), 1.0)) is None # three normals in one plane
def l_prism(a, b, t, h, s=S):
"""An L-shaped prism: the L is [0,a] x [0,t] united with [0,t] x [0,b], extruded from z=0 to z=h."""
cap = [(x, y) for x, y in ((S * (i + 0.5), S * (j + 0.5)) for i in range(round(a / s)) for j in range(round(b / s)))
if y < t or x < t]
nh = round(h / s)
return [[(x, y, 0.0) for x, y in cap], [(x, y, h) for x, y in cap],
face_grid((0, 0, 0), X, Z, round(a / s), nh), face_grid((a, 0, 0), Y, Z, round(t / s), nh),
face_grid((t, t, 0), X, Z, round((a - t) / s), nh), face_grid((t, t, 0), Y, Z, round((b - t) / s), nh),
face_grid((0, b, 0), X, Z, round(t / s), nh), face_grid((0, 0, 0), Y, Z, round(b / s), nh)]
def test_l_prism_with_concave_edge():
br = reconstruct(l_prism(2.0, 1.5, 0.5, 1.0), 1.5 * S, 1.5 * S)
assert (len(br.vertices), len(br.edges), len(br.planes)) == (12, 18, 8)
assert br.euler() == 2
assert len(br.loops[0]) == 6 and len(br.loops[1]) == 6
assert all(len(br.loops[f]) == 4 for f in range(2, 8))
assert (4, 5) in br.adjacency # the concave edge
corner = [v for v in br.vertices if abs(v[0] - 0.5) < 1e-9 and abs(v[1] - 0.5) < 1e-9]
assert len(corner) == 2
def test_delta_below_gap_finds_no_adjacency():
br = reconstruct(box(2.0, 1.0, 0.5), 0.5 * S, 1.5 * S) # gap across an edge is S / sqrt(2)
assert br.adjacency == set() and br.vertices == [] and br.edges == []
assert all(loop == [] for loop in br.loops.values())
def test_eta_below_gap_finds_no_vertex():
br = reconstruct(box(2.0, 1.0, 0.5), 1.5 * S, 0.5 * S) # a corner is S / sqrt(2) from its points
assert len(br.adjacency) == 12 and br.vertices == []
def test_face_loop_rejects_open_boundary():
br = reconstruct(box(2.0, 1.0, 0.5), 1.5 * S, 1.5 * S)
br.edges = [e for e in br.edges if e[2] != (0, 2)]
assert face_loop(br, 0) == [] and face_loop(br, 2) == []
assert len(face_loop(br, 1)) == 4
History
Reverse engineering of CAD models from scans grew in the 1990s, and the survey of Várady, Martin and Cox (1997) set out the pipeline from points to segmentation, surface fitting and B-rep model building. Benkő, Martin and Várady (2001) described a full procedure for conventional engineering objects bounded by simple analytic surfaces, swept surfaces and blends, with the focus on boundary models that are accurate and topologically consistent, ready for CAD and manufacturing. The same group studied constrained fitting and the segmentation of smooth regions in the following years. Later work replaced fixed rules with optimization and learning, as in PolyFit and Point2CAD.
References
- Pál Benkő, Ralph R. Martin and Tamás Várady, Algorithms for reverse engineering boundary representation models, Computer-Aided Design 33(11), 2001, 839 to 851, the whole paper, which summarizes the phases of the approach, from segmentation and surface fitting to the creation of edges, blends and vertex blends and a topologically consistent B-rep (general locator; section numbers not confirmed)
- Tamás Várady, Ralph R. Martin and Jordan Cox, Reverse engineering of geometric models, an introduction, Computer-Aided Design 29(4), 1997, 255 to 268, the sections on segmentation and surface fitting and on the creation of B-rep models, with the adjacency of regions, the intersection of the fitted surfaces and the stitching of faces
- Martti Mäntylä, An Introduction to Solid Modeling, Computer Science Press, 1988, Section 3.5.6, Euler characteristic (p. 43), for the check V − E + F = 2 of a closed solid without holes
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 RBGNXS Edit this page History Report an error Markdown