Algorithmresearch
Whisker weaving
Also called Tautges-Blacker-Mitchell whisker weaving.
Tautges, Blacker and Mitchell's hex mesher that first builds the spatial twist continuum from the boundary quad mesh, then derives the hexes from it.
- Time
- O(H α(H)) worst
- Space
- O(H) extra
- Where
- H = the number of hexes (dual sheet step)
- Model
- Real RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Timothy J. Tautges, Ted D. Blacker, Scott A. Mitchell, 1996
Whisker weaving makes an all-hex mesh from a closed quad mesh of the boundary by working on the dual of the mesh, not on the hexes. The dual of a hex mesh is its spatial twist continuum: a set of surfaces called sheets, one for each layer of hexes, which cross three at a time inside each hex. The boundary quad mesh fixes the edges of the sheets, because each chain of opposite edges on the surface, called a loop, is where one sheet meets the boundary. Whisker weaving starts from these loops and decides, by local rules on connectivity alone, where the sheets cross. Each triple crossing becomes a hex, and the geometry is placed last. This page is one method for hexahedral mesh generation, and it works only from connectivity and has no guarantee to finish, while that page states the general problem and its limits. The code on this page implements one exact core step, the dual sheets of a given hex mesh, and not the weaving loop.
In plain words
A brick wall has rows of bricks, and between two rows there is a layer of mortar. A block of bricks in 3D has such layers in three directions. Think of each layer as a thin sheet that cuts through one row of bricks. Every brick sits where three sheets cross.
On the outside of the block we see only the faces of the bricks. On that surface, each sheet shows up as a closed band of faces that goes around the block. Whisker weaving starts from these bands. It draws each sheet as a disk with short open threads, the whiskers, along its edge, and then ties threads of three sheets together, one brick at a time, until no thread is loose. Then it turns each knot of three sheets into a brick.
The rules are local, so the method can get stuck or tie a bad knot.
The problem
The input of whisker weaving is a closed quad mesh of the boundary of a solid, usually of a ball, with an even number of quads. The output is a hex mesh of the solid whose boundary quads are exactly . The method builds the combinatorial structure first: the sheets, how they cross, and so the list of hexes with their vertex ids. Vertex positions come last, by smoothing.
The code on this page solves the inverse problem, which is exact. Given a conforming hex mesh, it finds the sheets, the three sheets of each hex, the boundary quads and the loops. This is the structure that weaving must produce, and it is the test of any woven result.
The algorithm
On a face the edges and are opposite, and so are and . A sheet is a class of edges under the closure of "opposite on a common face". Inside a hex this joins the four parallel edges of each direction, so a sheet cuts each of its hexes through four parallel edges. A loop is a class of boundary edges under the same closure on the boundary quads only. A union-find structure (disjoint sets) finds both.
DUAL-SHEETS(H)- 1
make a singleton set for every edge of every hex - 2
for each hex h in H do - 3
for each class c of four parallel edges of h do - 4
union the four edges of c - 5
sheets ← the sets of the union-find structure - 6
for each hex h: crossing(h) ← the sheets of the three classes of h - 7
B ← the faces that belong to exactly one hex - 8
make a singleton set for every edge of a quad in B - 9
for each quad (a, b, c, d) in B do - 10
union ab with cd, and union bc with da - 11
loops ← the sets of the second structure - 12
return sheets, crossing, B, loops
Lines L1 to L5 find the sheets. Line L6 records the three sheet crossings of each hex. A sheet that crosses itself appears twice in the same hex. Line L7 finds the boundary by counting faces. Lines L8 to L11 find the loops of the boundary quad mesh. Each loop is inside one sheet, and each sheet that reaches the boundary has one or more loops as its edge.
The weaving loop. The published method runs in the other direction. In words, it does these steps:
- Find the loops of the boundary quad mesh . Each loop gets its own sheet, drawn as a disk. Each quad of is a point where two loops cross, so it appears on the edge of two sheet diagrams, and from it a whisker points into each disk.
- Pick three sheets whose loops cross each other near one corner of the surface, and whose whiskers are free there.
- Join the matching whiskers of the three sheets in one new crossing point. This point is a new hex, and its faces toward the surface are the quads that the whiskers came from.
- Update the free whiskers, and apply local rules that join whiskers that now face each other.
- Repeat steps 2 to 4 until no whisker is free, or stop with failure if no rule applies.
- Check the result: each sheet must be a surface and the cells of the arrangement must be simple. Then the dual of the woven arrangement gives the hexes, and smoothing places the inner vertices.
The checks of step 6 are the properties that DUAL-SHEETS computes for a finished mesh.
Example
The two cubes make the smallest mesh with an interior face.
| mesh | sheets | loops | Euler characteristic of the sheets | |||
|---|---|---|---|---|---|---|
| two cubes | 2 | 10 | 1 | 4 | 4 | 1, 1, 1, 1 |
| pillowed cube | 7 | 6 | 18 | 4 | 3 | 1, 1, 1, 2 |
In both rows . For the two cubes, the sheets are the plane through the first cube, the plane through the second cube, and the two planes and through both cubes. Each is a disk, with Euler characteristic , and each has one loop as its edge.
The pillowed cube is the cube cut into the inner cube and six hexes that join each inner face to an outer face. Its boundary is the same 6 quads as a single cube, with 3 loops. Three sheets are disks through the inner cube, bounded by the three loops. The fourth sheet goes through the six outer hexes around the inner cube. It has 8 vertices (the 8 edges from inner to outer corners), 12 edges and 6 faces, so its Euler characteristic is : it is a closed sphere with no loop. The boundary loops do not fix the sheets, and a weaving that makes one sheet per loop can never make this mesh.
Correctness
The proof below shows that DUAL-SHEETS returns the sheets and loops as defined. The key fact is that the four parallel edges of a class are linked by three faces of the hex, so the union of L4 and the relation "opposite on a common face" give the same classes. From this, each sheet cuts each of its hexes through whole classes of four parallel edges, and the sheet is a layer of quadrilateral cells, one per hex, glued across shared faces. Its free sides lie on boundary quads, so the boundary of a sheet is a union of loops. Counting the faces of all hexes gives , so the number of boundary quads is even for every hex mesh.
What is proved and what is measured are different here. The dual sheet step is proved exact. For the weaving loop, there is no general guarantee: it can stop with free whiskers, and when it ends it can give knotted sheets, degenerate hexes or inverted hexes. The survey of Pietroni and others reports that such elements are common when the boundary has self-intersecting loops. The tests compare DUAL-SHEETS with a breadth first search over the opposite-edge relation on 500 random voxel meshes, with random vertex labels and random vertex orders of each hex. They also check , that the sheet boundaries are unions of loops, and the Euler characteristic of each sheet against a direct count on its cross section.
Proof: DUAL-SHEETS finds the sheets of a hex mesh, each sheet crosses one layer of hexes through parallel edges, and the sheet boundaries are the loopsfull
Setting. A hex mesh is a finite list of hexes. Each hex is a list of 8 vertex ids in the standard order, and its 12 edges fall into three classes of 4 parallel edges (the classes , and of the reference cube). An edge is the set of its two end vertices, and a face is the set of its four vertices. The mesh is conforming: a face belongs to at most two hexes. A face that belongs to one hex is a boundary quad. Let be the number of hexes, the number of faces in two hexes, and the number of boundary quads.
On a face , the edges and are opposite, and so are and . Let be the smallest equivalence relation on the edges of the mesh in which opposite edges of each face are equivalent. A sheet is a class of . Let be the smallest equivalence relation on the edges of boundary quads in which opposite edges of each boundary quad are equivalent. A loop is a class of .
Claim.
- DUAL-SHEETS stops, and the classes of L5 are the sheets.
- (Sheet decomposition.) Each class of parallel edges of a hex is inside one sheet. So a sheet meets each hex in , , or edges, and these edges are whole classes of parallel edges. L6 gives each hex the sheets of its three classes.
- (The sheet is a layer.) Fix a sheet . Make a 2D cell complex : one vertex for each edge in , one edge for each face and each pair of opposite edges of that are both in , and one quadrilateral cell for each hex and each class of in . The four sides of the cell of are the four faces of that contain two edges of the class. Each edge of is a side of one or two cells: of two cells if its face is interior, and of one cell if its face is a boundary quad. So is a layer of hexes, one quadrilateral per hex and class, glued across the shared faces.
- L7 gives the boundary quads, and . In particular is even.
- The classes of L11 are the loops. Each loop is inside one sheet, and the boundary edges of each sheet are a union of loops. The boundary of (the edges of that are a side of one cell only) is the graph of the loops of . If every boundary edge of the mesh is in exactly two boundary quads, each loop is a cycle.
Proof of part 1. L2 to L4 visit each hex once and do 9 unions per hex, so the loop stops. Inside one hex, take a class, for example the class with the edges . The edges and are opposite on the face , the edges and on the face , and the edges and on the face . So the four edges of a class are equivalent, and L4 joins only equivalent edges. Conversely, two opposite edges of a face of a hex are parallel in that hex, so they are in the same class, and L4 joins them. The union-find classes are the classes of the smallest equivalence relation that contains the joined pairs. Both relations have the same generating pairs up to equivalence, so they are equal, and L5 gives the sheets.
Proof of part 2. By part 1 the four edges of a class of a hex are in one sheet. The 12 edges of a hex are the disjoint union of its three classes, so the edges of a hex in a sheet are a union of whole classes, which gives , , or edges. L6 reads the sheet of the first edge of each class, which is the sheet of the whole class.
Proof of part 3. Take a cell of with the class of in . Each of the four edges of is a vertex of . A face of contains two edges of as opposite edges exactly when it is one of the four faces parallel to the direction of , for example for the class the faces , , and . Each of these faces gives an edge of between two vertices of the cell. These four edges form a cycle through the four vertices in the order . So the cell is a quadrilateral. Now take an edge of , given by a face and a pair of opposite edges of in . A cell has this edge as a side exactly when is a face of and the pair is in . In each hex that contains , the pair is parallel, so it is in one class of that hex. So the edge is a side of one cell for each hex that contains : one cell for a boundary quad and two cells for an interior face. The cells of are in one to one correspondence with the pairs (hex, class in ). So meets each hex in one quadrilateral per class in , which is the layer of hexes that the sheet crosses. When the class is unique in each hex, the sheet crosses each of its hexes once, through four parallel edges.
Proof of part 4. L7 counts the occurrences of each face over all hexes and keeps the faces that occur once. Each hex has 6 faces, so the total number of occurrences is . A face in two hexes occurs twice, and a boundary quad once, and by conformity there is no other case. So , and is even.
Proof of part 5. L8 to L10 join the opposite edges of each boundary quad, so as in part 1 the classes of L11 are the loops. Two opposite edges of a boundary quad are opposite edges of a face of a hex, so they are equivalent, and each generating pair of is inside one sheet. So each loop is inside one sheet. The loops partition the boundary edges, so the boundary edges of a sheet are the union of the loops that contain them. By part 3, an edge of is a side of one cell exactly when its face is a boundary quad. These edges join opposite edges of boundary quads, which are the generating pairs of . So the boundary graph of has the boundary edges of as vertices and the generating pairs of inside as edges, and its components are the loops of . Finally, let each boundary edge be in exactly two boundary quads. In each of them has one opposite edge, so has degree 2 in this graph. A finite graph in which each vertex has degree 2 is a disjoint union of cycles, so each loop is a cycle.
Termination and cost. Each line is a finite loop over the hexes or the boundary quads. With union by size and path halving, the cost is , plus the sorting that makes the output canonical.
Complexity
DUAL-SHEETS does 9 unions per hex and one face count per face, so it runs in time with union by size and path halving, where is the inverse Ackermann function. The space is . The weaving loop makes one hex per step and each step is local, but a run can need many failed attempts and can stop without a mesh, so its cost is not a useful bound on its success.
Properties
- Connectivity first. The weaving uses no coordinates, so it does not depend on the shape of the solid. This is its strength and its weakness: the hexes have the right connectivity but can be badly shaped.
- Boundary conforming. The boundary quad mesh is not changed, which is why the method was of interest for assemblies with fixed interface meshes.
- Parity. A woven result can only exist if the number of boundary quads is even, because .
- No general guarantee. Termination, valid hexes and good shape are not proved for the weaving loop.
- Exact dual step. The sheets, crossings and loops of a given mesh are computed exactly and fast.
Variants and improvements
- Curve contraction. Folwell and Mitchell first fix the arrangement of the sheets by contracting the loops on the surface, and only then make hexes. This is more reliable than the original greedy weaving.
- More rules. Ledoux and Weill extend the rule set of reliable whisker weaving.
- Surface modification. Some methods change the boundary quad mesh first to remove self-intersecting loops, which are the main source of bad elements.
- Dual editing. The same dual view is used to edit a finished mesh, by inserting a sheet (pillowing) or by removing one (sheet extraction). See the spatial twist continuum.
When to use it
Whisker weaving is mainly of research and teaching interest. It shows how the dual view turns hex meshing into a problem about surfaces, and its checks are useful for any hex mesh. For production meshes of CAD parts, sweeping of a decomposition is the common choice, and for organic shapes polycube and frame field methods are used.
Pitfalls
- Self-intersecting loops. A loop that crosses itself must bound a sheet that crosses itself or pairs with another loop. The local rules do not find such structures in general, and the result has degenerate or inverted hexes.
- Odd boundary. With an odd number of boundary quads no hex mesh exists, so the weaving must fail. Check the parity first.
- Closed sheets. A sheet with no loop, such as the pillow sheet of the example, is never made if each sheet comes from a loop. Meshes that need such sheets need another step, such as pillowing.
- Geometry last. Good connectivity does not give good shape. The hexes must be placed and smoothed, and they can still be inverted.
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
# Shared helper of the mg4 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Exact geometry of trilinear hexahedra, shared by the mg4 pages.
A hex is a list of 8 points in the standard order: the bottom face
0, 1, 2, 3 counterclockwise seen from above, then the top face 4, 5, 6, 7
above 0, 1, 2, 3. Vertex k is the image of the reference corner
REF[k] of the unit cube, and the hex is the trilinear map of the cube with
these corner images. With int or Fraction coordinates every value here is
exact, so every sign is decided exactly.
"""
from fractions import Fraction
from typing import List, Sequence, Tuple
Point = Tuple
Hex = Sequence[Point]
REF = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0), (0, 0, 1), (1, 0, 1), (1, 1, 1), (0, 1, 1)]
# For corner k, three neighbours whose edge vectors form a right-handed frame on the unit cube.
CORNER_NEIGHBOURS = [(1, 3, 4), (2, 0, 5), (3, 1, 6), (0, 2, 7), (7, 5, 0), (4, 6, 1), (5, 7, 2), (6, 4, 3)]
# The six faces, each listed counterclockwise seen from outside the hex.
FACES = [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)]
# The twelve edges in three classes of four parallel edges (directions u, v, w).
EDGE_CLASSES = [
[(0, 1), (3, 2), (4, 5), (7, 6)],
[(0, 3), (1, 2), (4, 7), (5, 6)],
[(0, 4), (1, 5), (2, 6), (3, 7)],
]
def sub(p: Point, q: Point) -> Point:
"""p - q, componentwise."""
return tuple(a - b for a, b in zip(p, q))
def det3(a: Point, b: Point, c: Point):
"""The determinant of the 3 x 3 matrix with columns a, b, c."""
return (
a[0] * (b[1] * c[2] - b[2] * c[1])
- b[0] * (a[1] * c[2] - a[2] * c[1])
+ c[0] * (a[1] * b[2] - a[2] * b[1])
)
def corner_jacobians(h: Hex) -> List:
"""The 8 corner Jacobian determinants det(e1, e2, e3) of a hex. Cost: O(1)."""
out = []
for k, (i, j, l) in enumerate(CORNER_NEIGHBOURS):
out.append(det3(sub(h[i], h[k]), sub(h[j], h[k]), sub(h[l], h[k])))
return out
def corners_positive(h: Hex) -> bool:
"""True when all 8 corner Jacobians are positive (necessary for validity, not sufficient)."""
return all(d > 0 for d in corner_jacobians(h))
def trilinear(h: Hex, u, v, w) -> Point:
"""The point of the trilinear hex at the reference point (u, v, w)."""
out = [0, 0, 0]
for k, (a, b, c) in enumerate(REF):
wt = (u if a else 1 - u) * (v if b else 1 - v) * (w if c else 1 - w)
for t in range(3):
out[t] += wt * h[k][t]
return tuple(out)
def jacobian_det(h: Hex, u, v, w):
"""det of the Jacobian matrix of the trilinear hex at (u, v, w), exact for exact input."""
du, dv, dw = [0, 0, 0], [0, 0, 0], [0, 0, 0]
for k, (a, b, c) in enumerate(REF):
fu, fv, fw = (u if a else 1 - u), (v if b else 1 - v), (w if c else 1 - w)
su, sv, sw = (1 if a else -1), (1 if b else -1), (1 if c else -1)
for t in range(3):
du[t] += su * fv * fw * h[k][t]
dv[t] += fu * sv * fw * h[k][t]
dw[t] += fu * fv * sw * h[k][t]
return det3(du, dv, dw)
def _to_bernstein2(f0, fh, f1):
"""Bernstein coefficients of the quadratic with values f0, fh, f1 at 0, 1/2, 1."""
return (f0, 2 * fh - (f0 + f1) / Fraction(2), f1)
def jacobian_bernstein(h: Hex) -> List:
"""The 27 Bernstein coefficients of det J, which has degree 2 in each of u, v, w.
The determinant is sampled at {0, 1/2, 1}^3 and converted direction by direction.
Index order: coefficient (i, j, k) is at position 9 i + 3 j + k. Cost: O(1).
"""
half = Fraction(1, 2)
ts = (0, half, 1)
vals = [[[jacobian_det(h, ts[i], ts[j], ts[k]) for k in range(3)] for j in range(3)] for i in range(3)]
for i in range(3):
for j in range(3):
vals[i][j] = list(_to_bernstein2(*vals[i][j]))
for i in range(3):
for k in range(3):
col = _to_bernstein2(vals[i][0][k], vals[i][1][k], vals[i][2][k])
for j in range(3):
vals[i][j][k] = col[j]
for j in range(3):
for k in range(3):
col = _to_bernstein2(vals[0][j][k], vals[1][j][k], vals[2][j][k])
for i in range(3):
vals[i][j][k] = col[i]
return [vals[i][j][k] for i in range(3) for j in range(3) for k in range(3)]
def bernstein_certified(h: Hex) -> bool:
"""True when every Bernstein coefficient of det J is positive, which proves det J > 0 on the whole hex."""
return all(c > 0 for c in jacobian_bernstein(h))
def hex_volume(h: Hex):
"""The signed volume of the trilinear hex, the integral of det J over the unit cube.
Each quadratic Bernstein polynomial integrates to 1/3 on [0, 1], so the integral is
the mean of the 27 coefficients. Exact for exact input.
"""
return sum(jacobian_bernstein(h)) / Fraction(27)
def solve(a: List[List], b: List) -> List:
"""Solve a x = b by Gaussian elimination with Fraction. Raises ValueError if singular."""
n = len(a)
m = [[Fraction(x) for x in row] + [Fraction(y)] for row, y in zip(a, b)]
for c in range(n):
p = next((r for r in range(c, n) if m[r][c] != 0), None)
if p is None:
raise ValueError("singular system")
m[c], m[p] = m[p], m[c]
for r in range(n):
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][n] / m[r][r] for r in range(n)]
whisker_weaving.py 163 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/whisker-weaving/. The authors are listed in prov/4SHZ6G.jsonl.
"""The dual sheets of a hex mesh: the spatial twist continuum that whisker weaving builds.
Whisker weaving builds the sheets first and the hexes last. This module does
the opposite step, which is exact and always works: from a given conforming
hex mesh it finds the sheets, the three sheet crossings of every hex, the
boundary quads, and the loops (chords) of the boundary quad mesh. A hex is a
list of 8 vertex ids in the standard order of mg4geom. An edge is the sorted
pair of its vertex ids, and a face is identified by its set of 4 vertex ids.
"""
from typing import Dict, Hashable, List, Sequence, Tuple
from mg4geom import EDGE_CLASSES, FACES
Edge = Tuple[int, int]
class DisjointSets:
"""Union-find with path halving and union by size."""
def __init__(self) -> None:
self.parent: Dict[Hashable, Hashable] = {}
self.size: Dict[Hashable, int] = {}
def add(self, x: Hashable) -> None:
if x not in self.parent:
self.parent[x] = x
self.size[x] = 1
def find(self, x: Hashable) -> Hashable:
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]]
x = self.parent[x]
return x
def union(self, x: Hashable, y: Hashable) -> None:
rx, ry = self.find(x), self.find(y)
if rx == ry:
return
if self.size[rx] < self.size[ry]:
rx, ry = ry, rx
self.parent[ry] = rx
self.size[rx] += self.size[ry]
def classes(self) -> List[List[Hashable]]:
groups: Dict[Hashable, List[Hashable]] = {}
for x in self.parent:
groups.setdefault(self.find(x), []).append(x)
return sorted(sorted(g) for g in groups.values())
def edge(a: int, b: int) -> Edge:
return (a, b) if a < b else (b, a)
def hex_faces(h: Sequence[int]) -> List[Tuple[int, int, int, int]]:
"""The six faces of a hex as vertex tuples, counterclockwise seen from outside."""
return [tuple(h[i] for i in f) for f in FACES]
def dual_sheets(hexes: Sequence[Sequence[int]]):
"""The sheets, crossings, boundary quads and loops of a conforming hex mesh.
Returns a dict with
sheets: list of sheets, each a sorted list of edges (the dual vertices of the sheet),
sheet_of: edge -> index of its sheet,
crossing: for each hex, the sheet indices of its classes u, v and w,
boundary: the faces that belong to exactly one hex,
interior: the number of faces shared by two hexes,
loops: the chords of the boundary quad mesh, each a sorted list of edges,
loop_sheet: for each loop, the sheet that contains it.
Cost: O(H alpha(H)) for H hexes, plus sorting for a canonical output.
"""
edges = DisjointSets() # @line L1
for h in hexes: # @line L2
for cls in EDGE_CLASSES: # @line L3
es = [edge(h[i], h[j]) for i, j in cls]
for e in es:
edges.add(e)
for e in es[1:]:
edges.union(es[0], e) # @line L4
sheets = edges.classes() # @line L5
sheet_of = {e: s for s, members in enumerate(sheets) for e in members}
crossing = [tuple(sheet_of[edge(h[cls[0][0]], h[cls[0][1]])] for cls in EDGE_CLASSES) for h in hexes] # @line L6
count: Dict[frozenset, int] = {}
first: Dict[frozenset, Tuple[int, int, int, int]] = {}
for h in hexes:
for f in hex_faces(h):
key = frozenset(f)
count[key] = count.get(key, 0) + 1
first.setdefault(key, f)
boundary = sorted(first[k] for k, c in count.items() if c == 1) # @line L7
interior = sum(1 for c in count.values() if c == 2)
if any(c > 2 for c in count.values()):
raise ValueError("a face belongs to more than two hexes")
chords = DisjointSets() # @line L8
for a, b, c, d in boundary: # @line L9
e0, e1, e2, e3 = edge(a, b), edge(b, c), edge(c, d), edge(d, a)
for e in (e0, e1, e2, e3):
chords.add(e)
chords.union(e0, e2) # @line L10
chords.union(e1, e3)
loops = chords.classes() # @line L11
loop_sheet = [sheet_of[lp[0]] for lp in loops]
return { # @line L12
"sheets": sheets,
"sheet_of": sheet_of,
"crossing": crossing,
"boundary": boundary,
"interior": interior,
"loops": loops,
"loop_sheet": loop_sheet,
}
def sheet_euler(hexes: Sequence[Sequence[int]], result, s: int) -> int:
"""The Euler characteristic V - E + F of sheet s as a cell complex.
V: the edges of the sheet. E: the pairs of opposite sheet edges on a hex face
(one dual edge per such face and pair). F: one dual face per hex class in sheet s.
"""
sheet_of = result["sheet_of"]
v = len(result["sheets"][s])
seen = set()
f = 0
for h in hexes:
for cls in EDGE_CLASSES:
if sheet_of[edge(h[cls[0][0]], h[cls[0][1]])] == s:
f += 1
for a, b, c, d in hex_faces(h):
for p, q in ((edge(a, b), edge(c, d)), (edge(b, c), edge(d, a))):
if sheet_of[p] == s and sheet_of[q] == s:
seen.add((frozenset((a, b, c, d)), frozenset((p, q))))
return v - len(seen) + f
def voxel_mesh(voxels):
"""The hex mesh of a set of unit voxels (i, j, k), with the lattice point (x, y, z) as vertex id."""
ids: Dict[Tuple[int, int, int], int] = {}
hexes = []
for i, j, k in sorted(voxels):
h = []
for a, b, c in ((0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0), (0, 0, 1), (1, 0, 1), (1, 1, 1), (0, 1, 1)):
p = (i + a, j + b, k + c)
h.append(ids.setdefault(p, len(ids)))
hexes.append(h)
points = sorted(ids, key=ids.get)
return points, hexes
def pillowed_cube():
"""The cube [0, 3]^3 meshed by the inner cube [1, 2]^3 and six hexes that join it to the outer faces."""
outer = [(0, 0, 0), (3, 0, 0), (3, 3, 0), (0, 3, 0), (0, 0, 3), (3, 0, 3), (3, 3, 3), (0, 3, 3)]
inner = [(1, 1, 1), (2, 1, 1), (2, 2, 1), (1, 2, 1), (1, 1, 2), (2, 1, 2), (2, 2, 2), (1, 2, 2)]
points = outer + inner
hexes = [[8, 9, 10, 11, 12, 13, 14, 15]]
for f in FACES:
# the inner face, then the outer face, both counterclockwise seen from outside
hexes.append([8 + f[0], 8 + f[1], 8 + f[2], 8 + f[3], f[0], f[1], f[2], f[3]])
return points, hexes
test_whisker_weaving.py 189 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/whisker-weaving/. The authors are listed in prov/4SHZ6G.jsonl.
import itertools
import random
from collections import deque
import pytest
from mg4geom import EDGE_CLASSES, REF, corners_positive
from whisker_weaving import dual_sheets, edge, hex_faces, pillowed_cube, sheet_euler, voxel_mesh
def rotations():
"""The 24 orientation preserving vertex orders of the reference cube."""
out = []
for perm in itertools.permutations(range(3)):
for signs in itertools.product((1, -1), repeat=3):
m = [[signs[r] if c == perm[r] else 0 for c in range(3)] for r in range(3)]
det = (
m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1])
- m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
+ m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])
)
if det != 1:
continue
sigma = []
for c in REF:
x = [2 * t - 1 for t in c]
y = [sum(m[r][s] * x[s] for s in range(3)) for r in range(3)]
sigma.append(REF.index(tuple((t + 1) // 2 for t in y)))
out.append(sigma)
return out
ROT = rotations()
def components(nodes, pairs):
adj = {x: [] for x in nodes}
for a, b in pairs:
adj[a].append(b)
adj[b].append(a)
seen, out = set(), set()
for x in adj:
if x in seen:
continue
comp, queue = [], deque([x])
seen.add(x)
while queue:
y = queue.popleft()
comp.append(y)
for z in adj[y]:
if z not in seen:
seen.add(z)
queue.append(z)
out.add(frozenset(comp))
return out
def opposite_pairs(face):
a, b, c, d = face
return [(edge(a, b), edge(c, d)), (edge(b, c), edge(d, a))]
def brute_boundary(hexes):
out = []
for i, h in enumerate(hexes):
for f in hex_faces(h):
if not any(set(f) == set(g) for j, k in enumerate(hexes) if j != i for g in hex_faces(k)):
out.append(f)
return out
def check_mesh(points, hexes):
r = dual_sheets(hexes)
all_edges = {edge(h[i], h[j]) for h in hexes for cls in EDGE_CLASSES for i, j in cls}
pairs = [p for h in hexes for f in hex_faces(h) for p in opposite_pairs(f)]
assert {frozenset(s) for s in r["sheets"]} == components(all_edges, pairs)
# every hex lies on three sheet crossings, one for each class of four parallel edges
for h, cr in zip(hexes, r["crossing"]):
assert len(cr) == 3
for cls, s in zip(EDGE_CLASSES, cr):
assert all(r["sheet_of"][edge(h[i], h[j])] == s for i, j in cls)
bnd = brute_boundary(hexes)
assert sorted(map(frozenset, bnd), key=sorted) == sorted(map(frozenset, r["boundary"]), key=sorted)
assert 6 * len(hexes) == 2 * r["interior"] + len(r["boundary"])
bedges = {e for f in bnd for p in opposite_pairs(f) for e in p}
bpairs = [p for f in bnd for p in opposite_pairs(f)]
assert {frozenset(lp) for lp in r["loops"]} == components(bedges, bpairs)
# the boundary edges of each sheet are a union of loops
for s, members in enumerate(r["sheets"]):
own = {e for e in members if e in bedges}
from_loops = {e for lp, t in zip(r["loops"], r["loop_sheet"]) if t == s for e in lp}
assert own == from_loops
# sheets of a voxel mesh are flat: one axis and one slab per sheet
for members in r["sheets"]:
sig = set()
for a, b in members:
p, q = points[a], points[b]
axis = next(t for t in range(3) if p[t] != q[t])
sig.add((axis, min(p[axis], q[axis])))
assert len(sig) == 1
return r
def square_complex_euler(squares):
v, e = set(), set()
for x, y in squares:
cs = [(x, y), (x + 1, y), (x + 1, y + 1), (x, y + 1)]
v.update(cs)
for i in range(4):
e.add(frozenset((cs[i], cs[(i + 1) % 4])))
return len(v) - len(e) + len(squares)
def test_two_cubes():
points, hexes = voxel_mesh([(0, 0, 0), (1, 0, 0)])
r = check_mesh(points, hexes)
assert len(r["sheets"]) == 4 and len(r["boundary"]) == 10 and r["interior"] == 1
assert len(r["loops"]) == 4
assert [sheet_euler(hexes, r, s) for s in range(4)] == [1, 1, 1, 1]
@pytest.mark.parametrize("n", [(1, 1, 1), (2, 3, 1), (3, 2, 2), (4, 1, 3)])
def test_grid(n):
n1, n2, n3 = n
points, hexes = voxel_mesh([(i, j, k) for i in range(n1) for j in range(n2) for k in range(n3)])
r = check_mesh(points, hexes)
assert len(r["sheets"]) == n1 + n2 + n3
assert len(r["boundary"]) == 2 * (n1 * n2 + n2 * n3 + n3 * n1)
assert len(r["loops"]) == n1 + n2 + n3
def test_pillowed_cube_has_a_closed_sheet():
points, hexes = pillowed_cube()
assert all(corners_positive([points[i] for i in h]) for h in hexes)
r = dual_sheets(hexes)
assert len(hexes) == 7 and len(r["boundary"]) == 6 and r["interior"] == 18
assert 6 * 7 == 2 * 18 + 6
assert len(r["sheets"]) == 4 and len(r["loops"]) == 3
closed = [s for s in range(4) if s not in r["loop_sheet"]]
assert len(closed) == 1
s = closed[0]
assert sum(c.count(s) for c in r["crossing"]) == 6
assert sheet_euler(hexes, r, s) == 2 # a sphere: 8 vertices, 12 edges, 6 faces
assert sorted(sheet_euler(hexes, r, t) for t in range(4)) == [1, 1, 1, 2]
def test_face_shared_by_three_hexes_is_rejected():
hexes = [[0, 1, 2, 3, 4, 5, 6, 7], [4, 5, 6, 7, 8, 9, 10, 11], [4, 5, 6, 7, 12, 13, 14, 15]]
with pytest.raises(ValueError):
dual_sheets(hexes)
def test_random_voxel_meshes():
rng = random.Random(4061)
for trial in range(500):
n = rng.randint(1, 3)
p = rng.choice([0.3, 0.5, 0.8])
cells = [(i, j, k) for i in range(n + 1) for j in range(n) for k in range(n) if rng.random() < p]
if not cells:
cells = [(0, 0, 0)]
points, hexes = voxel_mesh(cells)
perm = list(range(len(points)))
rng.shuffle(perm)
points2 = [None] * len(points)
for old, new in enumerate(perm):
points2[new] = points[old]
hexes2 = []
for h in hexes:
sigma = rng.choice(ROT)
hexes2.append([perm[h[sigma[k]]] for k in range(8)])
for h in hexes2:
assert corners_positive([points2[i] for i in h])
r = check_mesh(points2, hexes2)
# each sheet is a flat slab section, so its Euler characteristic is that of a square complex
for s, members in enumerate(r["sheets"]):
a, b = members[0]
axis = next(t for t in range(3) if points2[a][t] != points2[b][t])
lo = min(points2[a][axis], points2[b][axis])
others = [t for t in range(3) if t != axis]
hex_ids = [i for i, c in enumerate(r["crossing"]) if s in c]
squares = []
for i in hex_ids:
corner = min(points2[v] for v in hexes2[i])
assert corner[axis] == lo
squares.append((corner[others[0]], corner[others[1]]))
assert sheet_euler(hexes2, r, s) == square_complex_euler(squares)
History
Murdoch, Benzley, Blacker and Mitchell described the spatial twist continuum, the dual of a hex mesh, in the mid 1990s. Tautges, Blacker and Mitchell published whisker weaving in 1996 as a way to build the dual from the boundary and then take the hexes from it. Folwell and Mitchell gave a more reliable version by curve contraction in 1999, and Ledoux and Weill extended it in 2008. At the same time, Mitchell and Thurston proved that the parity condition is the only topological condition for a ball, which is the subject of the hexahedral mesh existence theorem.
References
- Timothy J. Tautges, Ted Blacker and Scott A. Mitchell, The whisker weaving algorithm, a connectivity-based method for constructing all-hexahedral finite element meshes, International Journal for Numerical Methods in Engineering 39(19), 1996, 3327 to 3349, the sheet diagrams with whiskers, the local weaving rules, and the dual step that makes the hexes (general locator)
- Peter Murdoch, Steven Benzley, Ted Blacker and Scott A. Mitchell, The spatial twist continuum, a connectivity based method for representing all-hexahedral finite element meshes, Finite Elements in Analysis and Design 28(2), 1997, 137 to 149, the sheets and chords of a hex mesh and their crossings (general locator)
- N. T. Folwell and S. A. Mitchell, Reliable whisker weaving via curve contraction, Engineering with Computers 15(3), 1999, 292 to 302, the contraction of the boundary loops that fixes the sheet arrangement before the hexes are made (general locator)
- Franck Ledoux and Jean-Christophe Weill, An extension of the reliable whisker weaving algorithm, Proceedings of the 16th International Meshing Roundtable, 2008, 215 to 232, further rules for the weaving (general locator)
- Nico Pietroni, Marcel Campen, Alla Sheffer, Gianmarco Cherchi, David Bommes, Xifeng Gao, Riccardo Scateni, Franck Ledoux, Jean-François Remacle and Marco Livesu, Hex-mesh generation and processing, a survey, arXiv 2202.12670, 2022, the section on dual methods, which reports poorly shaped, inverted and degenerate elements for self-intersecting loops
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 4SHZ6G Edit this page History Report an error Markdown