Source code for design3d.fem_mesher

#!/usr/bin/env python3
"""
Finite element mesher of B-Rep models, written in Python.

It meshes volume models and 2D surfaces, and writes the mesh in the gmsh .msh 4.1 ASCII format, that can be read
back with :class:`design3d.gmsh_vm.GmshParser`. The meshing follows the same steps as gmsh:

- the curves of the model are meshed first, with a uniform element size along each curve,
- each face is then meshed in its parametric domain with a constrained Delaunay triangulation (triangle library). Its
  boundary nodes are taken from the meshed curves, so adjacent faces share their nodes,
- each closed shell is finally meshed with tetrahedra, by a Delaunay tetrahedralization (scipy) of the surface nodes
  and of interior nodes placed on a lattice. The diagonals of the surface triangles are flipped, and the surface mesh
  is refined, until each surface triangle is a face of the tetrahedralization: the volume mesh then conforms to the
  surface mesh. Its quality is improved by smoothing the interior nodes, by optimizing the position of the nodes of
  flat tetrahedra and by flipping flat tetrahedra.

Second order meshes get their middle nodes placed on the geometry: on the curves, on the surfaces, and at the middle
of the edges inside the volumes.
"""

import math
import warnings

import numpy as np
import triangle as triangle_lib
from matplotlib.path import Path
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import connected_components
from scipy.spatial import Delaunay, cKDTree

import design3d
import design3d.faces
import design3d.shells
import design3d.surfaces

# gmsh element types, by dimension and order
ELEMENT_TYPES = {0: {1: 15, 2: 15}, 1: {1: 1, 2: 8}, 2: {1: 2, 2: 9}, 3: {1: 4, 2: 11}}
# Element edges, in the gmsh order of the middle nodes of second order elements
TRIANGLE_EDGES = ((0, 1), (1, 2), (2, 0))
TETRAHEDRON_EDGES = ((0, 1), (1, 2), (2, 0), (3, 0), (2, 3), (1, 3))
# Face i of a tetrahedron is opposite to its vertex i, like the neighbors given by scipy
TETRAHEDRON_FACES = ((1, 2, 3), (0, 2, 3), (0, 1, 3), (0, 1, 2))

# Relative perturbation of the node positions. Without it, regular node patterns have co-spherical nodes, for which
# the Delaunay tetrahedralization is not unique: its faces could differ from the surface triangles.
JITTER = 1e-3
# Relative perturbation of the surface nodes in their Delaunay tetrahedralization
PERTURBATION = 1e-6
# Minimal angle of the surface triangles, in degrees
TRIANGLE_MIN_ANGLE = 28
# Maximal area of the surface triangles, relative to the square of the mesh size
TRIANGLE_AREA_FACTOR = 0.63
# Size of the cubes of the body centered cubic lattice of the volume nodes, relative to the mesh size
LATTICE_FACTOR = 1.5
MAX_RECOVERY_ITERATIONS = 50
SMOOTHING_ITERATIONS = 8
# Tetrahedra of lower quality are flat tetrahedra, removed if possible
SLIVER_QUALITY = 0.2
OPTIMIZATION_PASSES = 10
OPTIMIZATION_ROUNDS = 10
OPTIMIZATION_CANDIDATES = 30
# Amplitude of the random moves of the nodes of flat tetrahedra, relative to the mesh size
SLIVER_MOVE = 0.15
MAX_SURFACE_REFINEMENTS = 10
# Fixed directions of the rays that tell if a point is inside a closed surface
RAY_DIRECTIONS = np.array([[0.5774, 0.5832, 0.5713], [-0.3121, 0.8417, 0.4405], [0.6931, -0.1723, -0.7001]])


def _to_array(point) -> np.ndarray:
    """Converts a design3d point to a numpy array."""
    return np.array([*point], dtype=float)


def _keys(triangles: np.ndarray, number_nodes: int) -> np.ndarray:
    """Gives a unique integer key to each triangle, independent of the order of its nodes."""
    triangles = np.sort(triangles, axis=-1).astype(np.int64)
    return (triangles[..., 0] * number_nodes + triangles[..., 1]) * number_nodes + triangles[..., 2]


def _circumspheres(points: np.ndarray):
    """Centers and radii of the circles circumscribed to triangles of shape (n, 3, 3)."""
    a = points[:, 0]
    ab = points[:, 1] - a
    ac = points[:, 2] - a
    normal = np.cross(ab, ac)
    norm2 = np.maximum((normal**2).sum(axis=1), 1e-300)
    offset = (
        np.cross(normal, ab) * (ac**2).sum(axis=1)[:, None] + np.cross(ac, normal) * (ab**2).sum(axis=1)[:, None]
    ) / (2 * norm2[:, None])
    return a + offset, np.linalg.norm(offset, axis=1)


def _signed_volumes(corners: np.ndarray) -> np.ndarray:
    """Six times the signed volumes of tetrahedra of shape (n, 4, 3)."""
    return np.einsum(
        "ij,ij->i",
        np.cross(corners[:, 1] - corners[:, 0], corners[:, 2] - corners[:, 0]),
        corners[:, 3] - corners[:, 0],
    )


def _circumcenters(corners: np.ndarray) -> np.ndarray:
    """Centers of the spheres circumscribed to tetrahedra of shape (n, 4, 3)."""
    origin = corners[:, 0]
    b = corners[:, 1] - origin
    c = corners[:, 2] - origin
    d = corners[:, 3] - origin
    numerator = (
        (b**2).sum(axis=1)[:, None] * np.cross(c, d)
        + (c**2).sum(axis=1)[:, None] * np.cross(d, b)
        + (d**2).sum(axis=1)[:, None] * np.cross(b, c)
    )
    denominator = 2 * (b * np.cross(c, d)).sum(axis=1)
    denominator = np.where(np.abs(denominator) > 1e-300, denominator, 1e-300)
    return origin + numerator / denominator[:, None]


def _quality(corners: np.ndarray, signed: bool = False) -> np.ndarray:
    """
    Quality of tetrahedra of shape (n, 4, 3), between 0 for flat tetrahedra and 1 for regular ones: the volume
    compared to the sum of the squared edge lengths. If signed, inverted tetrahedra get a negative quality.
    """
    volumes = _signed_volumes(corners) / 6
    squared_lengths = sum(((corners[:, i] - corners[:, j]) ** 2).sum(axis=1) for i, j in TETRAHEDRON_EDGES)
    quality = 12 * (3 * np.abs(volumes)) ** (2 / 3) / np.maximum(squared_lengths, 1e-300)
    return np.sign(volumes) * quality if signed else quality


def _is_inside(point: np.ndarray, triangles: np.ndarray) -> bool:
    """
    Tells if a point is inside a closed triangulated surface, by the parity of the number of crossings of rays.

    :param point: The point, of shape (3,)
    :param triangles: The triangles of the surface, of shape (n, 3, 3)
    """
    votes = 0
    edge1 = triangles[:, 1] - triangles[:, 0]
    edge2 = triangles[:, 2] - triangles[:, 0]
    to_point = point - triangles[:, 0]
    for direction in RAY_DIRECTIONS:
        direction = direction / np.linalg.norm(direction)
        normal_p = np.cross(direction, edge2)
        determinant = (edge1 * normal_p).sum(axis=1)
        valid = np.abs(determinant) > 1e-300
        inverse = np.where(valid, 1.0 / np.where(valid, determinant, 1.0), 0.0)
        u = (to_point * normal_p).sum(axis=1) * inverse
        normal_q = np.cross(to_point, edge1)
        v = (normal_q @ direction) * inverse
        t = (edge2 * normal_q).sum(axis=1) * inverse
        crossings = valid & (u >= 0) & (v >= 0) & (u + v <= 1) & (t > 0)
        votes += int(crossings.sum()) % 2
    return votes >= 2


class _Nodes:
    """The nodes of the mesh, with the entity on which each of them lies."""

    def __init__(self):
        self.coordinates = []
        self.entities = []
        self._array = None

    def __len__(self):
        return len(self.coordinates)

    def add(self, points, dimension: int, index: int) -> np.ndarray:
        """Adds nodes on the entity of given dimension and index, and returns their numbers."""
        points = np.asarray(points, dtype=float).reshape(-1, 3)
        start = len(self.coordinates)
        self.coordinates.extend(points)
        self.entities.extend([(dimension, index)] * len(points))
        self._array = None
        return np.arange(start, start + len(points))

    def move(self, nodes: np.ndarray, points: np.ndarray):
        """Moves nodes to new positions."""
        for node, point in zip(nodes, points):
            self.coordinates[node] = point
        self._array = None

    @property
    def array(self) -> np.ndarray:
        """The coordinates of all the nodes, as an array of shape (n, 3)."""
        if self._array is None or len(self._array) != len(self.coordinates):
            self._array = np.array(self.coordinates, dtype=float).reshape(-1, 3)
        return self._array


class _Curve:
    """A curve of the model: a unique edge, shared by the faces it bounds, and its discretization."""

    def __init__(self, edge, tolerance: float):
        self.edge = edge
        self.length = edge.length()
        self.tolerance = tolerance
        self.closed = edge.start.point_distance(edge.end) < tolerance
        samples = np.array([_to_array(edge.point_at_abscissa(s)) for s in np.linspace(0, self.length, 33)])
        self.box = (samples.min(axis=0) - tolerance, samples.max(axis=0) + tolerance)
        tangents = np.diff(samples, axis=0)
        tangents = tangents[np.linalg.norm(tangents, axis=1) > 1e-12 * max(self.length, 1e-300)]
        if len(tangents) > 1:
            tangents /= np.linalg.norm(tangents, axis=1)[:, None]
            cosines = np.clip((tangents[:-1] * tangents[1:]).sum(axis=1), -1.0, 1.0)
            self.turning_angle = float(np.arccos(cosines).sum())
        else:
            self.turning_angle = 0.0
        self.size = math.inf
        self.marks = []
        self.surfaces = set()
        self.abscissas = None
        self.nodes = None
        self.middle_nodes = None

    def contains(self, point: np.ndarray) -> bool:
        """Tells if a point is in the bounding box of the curve."""
        return bool(np.all(point >= self.box[0]) and np.all(point <= self.box[1]))

    def abscissa(self, point) -> float | None:
        """Gives the abscissa of a point on the curve, or None if the point is not on it."""
        try:
            abscissa = self.edge.abscissa(point)
        except Exception:  # noqa: BLE001 pylint: disable=broad-except
            return None
        if abscissa is None:
            return None
        abscissa = min(max(float(abscissa), 0.0), self.length)
        if self.edge.point_at_abscissa(abscissa).point_distance(point) > 10 * self.tolerance:
            return None
        if self.closed:
            abscissa %= self.length
            if self.length - abscissa < self.tolerance:
                abscissa = 0.0
        return abscissa

    def add_mark(self, abscissa: float, vertex: int):
        """Imposes a node of a vertex at the given abscissa."""
        for other_abscissa, _ in self.marks:
            if abs(other_abscissa - abscissa) < self.tolerance:
                return
        self.marks.append((abscissa, vertex))

    def path(self, start: float, end: float, forward: bool):
        """
        Gives the positions of the nodes of the curve between two abscissas, with their relative abscissa along this
        path.
        """
        number = len(self.nodes)
        first = int(np.argmin(np.abs(self.abscissas - start)))
        last = int(np.argmin(np.abs(self.abscissas - end)))
        if self.closed:
            if self.length - start < self.tolerance:
                first = 0
            if self.length - end < self.tolerance:
                last = 0
            steps = (last - first) % number if forward else (first - last) % number
            if steps == 0:
                steps = number
            sign = 1 if forward else -1
            positions = [(first + sign * i) % number for i in range(steps + 1)]
            lengths = [0.0]
            for position1, position2 in zip(positions[:-1], positions[1:]):
                delta = (self.abscissas[position2] - self.abscissas[position1]) * sign
                lengths.append(lengths[-1] + delta % self.length)
        else:
            positions = list(range(first, last + 1)) if forward else list(range(first, last - 1, -1))
            lengths = [abs(self.abscissas[position] - self.abscissas[first]) for position in positions]
        total = lengths[-1] if lengths[-1] > 0 else 1.0
        return positions, [length / total for length in lengths]

    def segments(self):
        """Gives the pairs of positions of consecutive nodes of the curve."""
        number = len(self.nodes)
        if self.closed:
            return [(i, (i + 1) % number) for i in range(number)]
        return [(i, i + 1) for i in range(number - 1)]

    def segment_middle_abscissa(self, position1: int, position2: int) -> float:
        """Gives the abscissa of the middle of a segment of the curve."""
        start = self.abscissas[position1]
        end = self.abscissas[position2]
        if position2 < position1:
            end += self.length
        return ((start + end) / 2) % self.length if self.closed else (start + end) / 2


class _LoopItem:
    """A primitive of a face contour, defined by a portion of a curve, or by a vertex for degenerated primitives."""

    def __init__(self, primitive2d, curve=None, start=0.0, end=0.0, forward=True, vertex=None):
        self.primitive2d = primitive2d
        self.curve = curve
        self.start = start
        self.end = end
        self.forward = forward
        self.vertex = vertex


class _Surface:
    """A face of the model and its triangulation in its parametric domain."""

    def __init__(self, face, loops: list[list[_LoopItem]]):
        self.face = face
        self.surface3d = face.surface3d
        self.loops = loops
        self.size = math.inf
        self.planar = isinstance(self.surface3d, design3d.surfaces.Plane3D)
        self.periodicity = (
            getattr(self.surface3d, "x_periodicity", None),
            getattr(self.surface3d, "y_periodicity", None),
        )
        self.scale = np.ones(2)
        self.local_uv = None
        self.local_nodes = None
        self.local_singular = None
        self.local_triangles = None
        self.triangles = np.empty((0, 3), dtype=int)

    def curves(self) -> set[int]:
        """Gives the indices of the curves bounding the face."""
        return {item.curve for loop in self.loops for item in loop if item.curve is not None}

    def signature(self):
        """Gives the bounding curves and vertices, that identify the face among faces sharing their boundary."""
        return tuple(
            sorted(
                (0, item.curve) if item.curve is not None else (1, item.vertex) for loop in self.loops for item in loop
            )
        )

    def points3d(self, uv: np.ndarray) -> np.ndarray:
        """Evaluates the surface at parametric points."""
        if len(uv) == 0:
            return np.empty((0, 3))
        return np.asarray(self.surface3d.parametric_points_to_3d(np.asarray(uv, dtype=float)), dtype=float)

    def normals(self, uv: np.ndarray) -> np.ndarray:
        """Normals of the surface at parametric points, computed by finite differences."""
        step = 1e-5 * max(float(np.ptp(uv, axis=0).max()) if len(uv) > 1 else 1.0, 1e-9)
        du = self.points3d(uv + [step, 0]) - self.points3d(uv - [step, 0])
        dv = self.points3d(uv + [0, step]) - self.points3d(uv - [0, step])
        normals = np.cross(du, dv)
        norms = np.linalg.norm(normals, axis=1)
        with np.errstate(invalid="ignore", divide="ignore"):
            return normals / norms[:, None]


class _Volume:
    """A closed shell of the model, and its tetrahedra."""

    def __init__(self, shell, surfaces: list[int], size: float):
        self.shell = shell
        self.surfaces = surfaces
        self.size = size
        self.tetrahedra = np.empty((0, 4), dtype=int)


[docs] class FEMMesher: """ Finite element mesher of shells, that writes the mesh in the gmsh .msh format. :param shells: The shells to mesh. Closed shells are meshed with tetrahedra up to mesh dimension 3, open shells are meshed with triangles only. Faces and edges shared by shells are meshed once, so the meshes of the shells are conformal :type shells: list[design3d.shells.Shell3D] :param sizes: The target size of the elements of each shell :type sizes: list[float] :param curvature_mesh_size: The minimal number of elements per 2*pi radians along curved edges and surfaces. 0 disables the refinement from curvature, defaults to 0 :type curvature_mesh_size: int, optional :param min_points: The minimal number of nodes on the edges shorter than min_points times the mesh size, defaults to None :type min_points: int, optional :param seed: The seed of the small random perturbations of the nodes, for reproducible meshes, defaults to 0 :type seed: int, optional """ def __init__( self, shells: list, sizes: list[float], curvature_mesh_size: int = 0, min_points: int | None = None, seed: int = 0, ): if len(shells) != len(sizes): raise ValueError("One mesh size is expected for each shell") self.shells = shells self.sizes = sizes self.curvature_mesh_size = curvature_mesh_size or 0 self.min_points = min_points self.random = np.random.default_rng(seed) self.nodes = _Nodes() self.vertices = [] self.curves = [] self.surfaces = [] self.volumes = [] self.middle_nodes = {} self._perturbations = np.empty((0, 3)) self.mesh_dimension = None self.mesh_order = None boxes = [shell.bounding_box for shell in shells] diagonal = max( (math.sqrt((b.xmax - b.xmin) ** 2 + (b.ymax - b.ymin) ** 2 + (b.zmax - b.zmin) ** 2) for b in boxes), default=1.0, ) self.tolerance = 1e-6 * max(diagonal, 1e-9)
[docs] @staticmethod def element_size(factor: float, length: float, initial_mesh_size: float = 5) -> float: """ Computes the element size from a characteristic length, like the gmsh .geo files written by design3d. :param factor: A float, between 0 and 1, that describes the mesh quality (1 for coarse mesh - 0 for fine mesh) :param length: The characteristic length of the meshed object :param initial_mesh_size: If factor=1, there will be initial_mesh_size elements per dimension """ if factor == 0: factor = 1e-3 return length / initial_mesh_size * factor
[docs] @classmethod def from_volume_model( cls, volume_model, factor: float, curvature_mesh_size: int = 0, min_points: int | None = None, initial_mesh_size: float = 5, ): """ Defines a mesher of the shells of a volume model. The element size of a closed shell is the cubic root of the volume of its bounding box, divided by initial_mesh_size and multiplied by factor. For an open shell, the square root of its area is used. :param volume_model: The volume model to mesh :type volume_model: design3d.core.VolumeModel :param factor: A float, between 0 and 1, that describes the mesh quality (1 for coarse mesh - 0 for fine mesh) :type factor: float :param curvature_mesh_size: The minimal number of elements per 2*pi radians, defaults to 0 :type curvature_mesh_size: int, optional :param min_points: The minimal number of nodes on the edges shorter than min_points times the mesh size, defaults to None :type min_points: int, optional :param initial_mesh_size: If factor=1, there will be initial_mesh_size elements per dimension, defaults to 5 :type initial_mesh_size: float, optional """ shells, sizes = [], [] for shell in volume_model.get_shells(): if not isinstance(shell, design3d.shells.Shell3D): continue if isinstance(shell, design3d.shells.ClosedShell3D): box = shell.bounding_box length = ((box.xmax - box.xmin) * (box.ymax - box.ymin) * (box.zmax - box.zmin)) ** (1 / 3) else: length = math.sqrt(sum(face.area() for face in shell.faces)) shells.append(shell) sizes.append(cls.element_size(factor, length, initial_mesh_size)) return cls(shells, sizes, curvature_mesh_size=curvature_mesh_size, min_points=min_points)
[docs] @classmethod def from_surface2d( cls, surface2d, factor: float, curvature_mesh_size: int = 0, min_points: int | None = None, initial_mesh_size: float = 5, ): """ Defines a mesher of a 2D surface, in the plane z=0. The element size is the square root of the surface area, divided by initial_mesh_size and multiplied by factor. :param surface2d: The surface to mesh :type surface2d: design3d.surfaces.Surface2D :param factor: A float, between 0 and 1, that describes the mesh quality (1 for coarse mesh - 0 for fine mesh) :type factor: float :param curvature_mesh_size: The minimal number of elements per 2*pi radians, defaults to 0 :type curvature_mesh_size: int, optional :param min_points: The minimal number of nodes on the edges shorter than min_points times the mesh size, defaults to None :type min_points: int, optional :param initial_mesh_size: If factor=1, there will be initial_mesh_size elements per dimension, defaults to 5 :type initial_mesh_size: float, optional """ face = design3d.faces.PlaneFace3D(design3d.surfaces.Plane3D(design3d.OXYZ), surface2d) shell = design3d.shells.OpenShell3D([face]) size = cls.element_size(factor, math.sqrt(surface2d.area()), initial_mesh_size) return cls([shell], [size], curvature_mesh_size=curvature_mesh_size, min_points=min_points)
# ------------------------------------------------------------------------------------------------------------------ # Topology # ------------------------------------------------------------------------------------------------------------------ def _vertex(self, point) -> int: """Gives the index of the vertex at a point, creating it if needed.""" coordinates = _to_array(point) for index, vertex_node in enumerate(self.vertices): if np.linalg.norm(self.nodes.coordinates[vertex_node] - coordinates) < self.tolerance: return index self.vertices.append(int(self.nodes.add(coordinates, 0, len(self.vertices))[0])) return len(self.vertices) - 1 def _register_edge(self, edge): """Finds the curve on which an edge lies, or creates it. Returns the curve and the edge position on it.""" start_vertex = self._vertex(edge.start) end_vertex = self._vertex(edge.end) length = edge.length() quarter = edge.point_at_abscissa(0.25 * length) middle = edge.point_at_abscissa(0.5 * length) tested_points = [_to_array(edge.start), _to_array(edge.end), _to_array(quarter), _to_array(middle)] for index, curve in enumerate(self.curves): if not all(curve.contains(point) for point in tested_points): continue abscissas = [curve.abscissa(point) for point in (edge.start, edge.end, quarter, middle)] if any(abscissa is None for abscissa in abscissas): continue start, end, quarter_abscissa, _ = abscissas if curve.closed: forward = (quarter_abscissa - start) % curve.length < 0.5 * curve.length travelled = ((end - start) if forward else (start - end)) % curve.length if travelled < self.tolerance: travelled = curve.length else: forward = quarter_abscissa > start travelled = abs(end - start) if abs(travelled - length) > 1e-3 * length + 10 * self.tolerance: continue curve.add_mark(start, start_vertex) curve.add_mark(end, end_vertex) return index, start, end, forward curve = _Curve(edge, self.tolerance) curve.add_mark(0.0, start_vertex) if not curve.closed: curve.add_mark(curve.length, end_vertex) self.curves.append(curve) return len(self.curves) - 1, 0.0, 0.0 if curve.closed else curve.length, True def _build_topology(self): """Defines the vertices, curves, surfaces and volumes of the model, sharing the common entities of shells.""" shell_faces = [] edges = {} for shell in self.shells: faces = [] for face in shell.faces: mapping = face.primitives_mapping contours = [face.surface2d.outer_contour, *face.surface2d.inner_contours] faces.append((face, contours, mapping)) for contour in contours: for primitive2d in contour.primitives: edge = mapping.get(primitive2d) if edge is not None: edges[id(edge)] = edge shell_faces.append(faces) positions = {} for edge in sorted(edges.values(), key=lambda edge: -edge.length()): positions[id(edge)] = self._register_edge(edge) for shell, faces, size in zip(self.shells, shell_faces, self.sizes): surfaces = [] for face, contours, mapping in faces: loops = [] for contour in contours: loop = [] for primitive2d in contour.primitives: edge = mapping.get(primitive2d) if edge is None: if not face.surface3d.is_degenerated_brep(primitive2d): raise ValueError(f"Can not mesh the face {face}: an edge is missing in its contour") vertex = self._vertex(face.surface3d.point2d_to_3d(primitive2d.start)) loop.append(_LoopItem(primitive2d, vertex=vertex)) else: curve, start, end, forward = positions[id(edge)] loop.append(_LoopItem(primitive2d, curve, start, end, forward)) loops.append(loop) surface = _Surface(face, loops) index = self._find_surface(surface) if index is None: self.surfaces.append(surface) index = len(self.surfaces) - 1 self.surfaces[index].size = min(self.surfaces[index].size, size) for curve in self.surfaces[index].curves(): self.curves[curve].surfaces.add(index) self.curves[curve].size = min(self.curves[curve].size, size) surfaces.append(index) if isinstance(shell, design3d.shells.ClosedShell3D): self.volumes.append(_Volume(shell, surfaces, size)) def _find_surface(self, surface: _Surface) -> int | None: """Finds a face of the model equal to a face of another shell.""" signature = surface.signature() box = surface.face.bounding_box for index, other in enumerate(self.surfaces): if other.signature() != signature: continue other_box = other.face.bounding_box if np.allclose( [box.xmin, box.xmax, box.ymin, box.ymax, box.zmin, box.zmax], [other_box.xmin, other_box.xmax, other_box.ymin, other_box.ymax, other_box.zmin, other_box.zmax], atol=10 * self.tolerance, ) and other.face.point_belongs(surface.face.random_point_inside(), 10 * self.tolerance): return index return None # ------------------------------------------------------------------------------------------------------------------ # Curves # ------------------------------------------------------------------------------------------------------------------ def _number_of_segments(self, curve: _Curve, length: float) -> int: """Gives the number of elements on a portion of a curve.""" size = curve.size if self.min_points and length < self.min_points * size: return max(self.min_points - 1, 1) number = length / size if self.curvature_mesh_size and curve.length > 0: number = max(number, self.curvature_mesh_size * curve.turning_angle * length / curve.length / (2 * math.pi)) return max(1, int(number + 0.99)) def _mesh_curve(self, index: int): """Meshes a curve with a uniform element size between its vertices.""" curve = self.curves[index] marks = sorted(curve.marks) bounds = marks + [(marks[0][0] + curve.length, marks[0][1])] if curve.closed else marks abscissas, nodes = [], [] for (start, vertex), (end, _) in zip(bounds[:-1], bounds[1:]): length = end - start number = self._number_of_segments(curve, length) if curve.closed and len(marks) == 1: number = max(number, 3) abscissas.append(start) nodes.append(self.vertices[vertex]) if number > 1: relative = (np.arange(1, number) + self.random.uniform(-JITTER, JITTER, number - 1)) / number new_abscissas = start + relative * length points = [_to_array(curve.edge.point_at_abscissa(s % curve.length)) for s in new_abscissas] abscissas.extend(new_abscissas) nodes.extend(self.nodes.add(points, 1, index)) if not curve.closed: abscissas.append(marks[-1][0]) nodes.append(self.vertices[marks[-1][1]]) curve.abscissas = np.array(abscissas) curve.nodes = [int(node) for node in nodes] def _split_curve_segment(self, index: int, position: int) -> int: """Splits a segment of a curve at its middle, and returns the new node.""" curve = self.curves[index] abscissa = curve.segment_middle_abscissa(position, (position + 1) % len(curve.nodes)) node = int(self.nodes.add(_to_array(curve.edge.point_at_abscissa(abscissa)), 1, index)[0]) curve.abscissas = np.insert(curve.abscissas, position + 1, abscissa) curve.nodes.insert(position + 1, node) return node # ------------------------------------------------------------------------------------------------------------------ # Surfaces # ------------------------------------------------------------------------------------------------------------------ def _metric(self, surface: _Surface) -> np.ndarray: """Average lengths of the derivatives of the surface, that make its parametric domain close to isometric.""" if surface.planar: return np.ones(2) rectangle = surface.face.surface2d.outer_contour.bounding_rectangle u_values = np.linspace(rectangle.xmin, rectangle.xmax, 9)[1:-1] v_values = np.linspace(rectangle.ymin, rectangle.ymax, 9)[1:-1] uv = np.array([[u, v] for u in u_values for v in v_values]) step = 1e-5 * max(rectangle.xmax - rectangle.xmin, rectangle.ymax - rectangle.ymin, 1e-9) du = np.linalg.norm(surface.points3d(uv + [step, 0]) - surface.points3d(uv - [step, 0]), axis=1) / (2 * step) dv = np.linalg.norm(surface.points3d(uv + [0, step]) - surface.points3d(uv - [0, step]), axis=1) / (2 * step) scale = np.array([du.mean(), dv.mean()]) scale[~np.isfinite(scale) | (scale < 1e-12)] = 1.0 return scale def _item_nodes(self, surface: _Surface, item: _LoopItem): """Gives the parametric coordinates, the nodes and the singular axis of the nodes of a contour primitive.""" primitive2d = item.primitive2d length2d = primitive2d.length() start = _to_array(primitive2d.start) end = _to_array(primitive2d.end) if item.curve is None: axis = 0 if abs(end[0] - start[0]) >= abs(end[1] - start[1]) else 1 number = max(2, int(length2d * surface.scale[axis] / surface.size + 0.99)) uv = [_to_array(primitive2d.point_at_abscissa(i * length2d / number)) for i in range(number)] + [end] return uv, [self.vertices[item.vertex]] * (number + 1), [axis] * (number + 1) curve = self.curves[item.curve] positions, fractions = curve.path(item.start, item.end, item.forward) uv, nodes = [], [] for i, (position, fraction) in enumerate(zip(positions, fractions)): node = curve.nodes[position] nodes.append(node) if i == 0: uv.append(start) elif i == len(positions) - 1: uv.append(end) else: reference = _to_array(primitive2d.point_at_abscissa(fraction * length2d)) uv.append(self._parametric_point(surface, node, reference)) return uv, nodes, [-1] * len(nodes) def _parametric_point(self, surface: _Surface, node: int, reference: np.ndarray) -> np.ndarray: """ Parametric coordinates of a node on a face. On periodic surfaces, the period closest to a reference point is chosen. """ point = design3d.Point3D(*self.nodes.coordinates[node]) try: uv = _to_array(surface.surface3d.point3d_to_2d(point)) except Exception: # noqa: BLE001 pylint: disable=broad-except return reference for axis, period in enumerate(surface.periodicity): if period: uv[axis] += round((reference[axis] - uv[axis]) / period) * period return uv def _boundary(self, surface: _Surface): """Gives the boundary nodes of a face, with their parametric coordinates, and the boundary segments.""" uv, nodes, singular, segments, loops = [], [], [], [], [] for loop in surface.loops: first = len(uv) for item in loop: item_uv, item_nodes, item_singular = self._item_nodes(surface, item) uv.extend(item_uv[:-1]) nodes.extend(item_nodes[:-1]) singular.extend(item_singular[:-1]) number = len(uv) - first segments.extend([(first + i, first + (i + 1) % number) for i in range(number)]) loops.append((first, len(uv))) return np.array(uv), np.array(nodes, dtype=int), np.array(singular, dtype=int), np.array(segments), loops def _holes(self, xy: np.ndarray, segments: np.ndarray, loops) -> np.ndarray: """Gives a point inside each inner contour of a face, as a hole for the triangulation.""" if len(loops) < 2: return np.empty((0, 2)) triangulation = triangle_lib.triangulate({"vertices": xy, "segments": segments}, "pQ") centers = triangulation["vertices"][triangulation["triangles"]].mean(axis=1) holes = [] for first, last in loops[1:]: inside = Path(xy[first:last]).contains_points(centers) if inside.any(): holes.append(centers[np.argmax(inside)]) return np.array(holes).reshape(-1, 2) def _mesh_surface(self, index: int): """ Meshes a face: triangulation of quality in the parametric domain, refined to the element size on the surface, and finally made Delaunay again after a small perturbation of its interior nodes. """ surface = self.surfaces[index] surface.scale = self._metric(surface) uv_boundary, nodes_boundary, singular_boundary, segments, loops = self._boundary(surface) xy_boundary = uv_boundary * surface.scale data = {"vertices": xy_boundary, "segments": segments} holes = self._holes(xy_boundary, segments, loops) if len(holes): data["holes"] = holes max_area = TRIANGLE_AREA_FACTOR * surface.size**2 triangulation = triangle_lib.triangulate(data, f"pq{TRIANGLE_MIN_ANGLE}Ya{max_area:.12g}Q") if not surface.planar: triangulation = self._refine_on_surface(surface, triangulation, data, nodes_boundary) number_boundary = len(xy_boundary) steiner = triangulation["vertices"][number_boundary:].copy() steiner += self.random.uniform(-JITTER, JITTER, steiner.shape) * surface.size interior_uv = steiner / surface.scale interior_nodes = self.nodes.add(surface.points3d(interior_uv), 2, index) uv = np.vstack([uv_boundary, interior_uv]) nodes = np.concatenate([nodes_boundary, interior_nodes]).astype(int) triangulation = triangle_lib.triangulate(dict(data, vertices=uv * surface.scale), "pYQ") if len(triangulation["vertices"]) != len(uv): raise RuntimeError(f"The triangulation of the face {index} added nodes: its contours may be intersecting") local_triangles = triangulation["triangles"] triangles = nodes[local_triangles] # Triangles with a side on a degenerated edge of the contour, at a singular point of the surface, are flat valid = ( (triangles[:, 0] != triangles[:, 1]) & (triangles[:, 1] != triangles[:, 2]) & (triangles[:, 2] != triangles[:, 0]) ) surface.local_uv = uv surface.local_nodes = nodes surface.local_singular = np.concatenate([singular_boundary, -np.ones(len(interior_nodes), dtype=int)]) surface.local_triangles = local_triangles[valid] surface.triangles = triangles[valid] def _refine_on_surface(self, surface: _Surface, triangulation: dict, data: dict, nodes_boundary: np.ndarray): """Refines a triangulation in the parametric domain until its triangles have the expected size in 3D.""" number_boundary = len(nodes_boundary) boundary_points = self.nodes.array[nodes_boundary] max_angle = 2 * math.pi / self.curvature_mesh_size if self.curvature_mesh_size else None for _ in range(MAX_SURFACE_REFINEMENTS): xy = triangulation["vertices"] triangles = triangulation["triangles"] uv = xy / surface.scale points = np.vstack([boundary_points, surface.points3d(uv[number_boundary:])]) corners = points[triangles] lengths = np.linalg.norm(corners - corners[:, [1, 2, 0]], axis=2).max(axis=1) bad = lengths > 1.4 * surface.size if max_angle: normals = surface.normals(uv)[triangles] cosines = np.stack([(normals[:, i] * normals[:, j]).sum(axis=1) for i, j in TRIANGLE_EDGES], axis=1) with np.errstate(invalid="ignore"): bad |= np.nanmin(cosines, axis=1) < math.cos(max_angle) if not bad.any(): break edge1 = xy[triangles[:, 1]] - xy[triangles[:, 0]] edge2 = xy[triangles[:, 2]] - xy[triangles[:, 0]] areas = 0.5 * np.abs(edge1[:, 0] * edge2[:, 1] - edge1[:, 1] * edge2[:, 0]) ratio = np.where(bad, np.minimum(0.25, (surface.size / np.maximum(lengths, 1e-300)) ** 2), 4.0) refine_data = dict(data, vertices=xy, triangles=triangles, triangle_max_area=areas * ratio) refine_data.pop("holes", None) triangulation = triangle_lib.triangulate(refine_data, f"rpq{TRIANGLE_MIN_ANGLE}YaQ") return triangulation def _middle_uv(self, surface: _Surface, local1: int, local2: int) -> np.ndarray: """Parametric coordinates of the middle of a triangle edge, handling the singular points of the surface.""" uv1 = surface.local_uv[local1].copy() uv2 = surface.local_uv[local2].copy() axis1 = surface.local_singular[local1] axis2 = surface.local_singular[local2] if axis1 >= 0 and axis2 < 0: uv1[axis1] = uv2[axis1] elif axis2 >= 0 and axis1 < 0: uv2[axis2] = uv1[axis2] return (uv1 + uv2) / 2 # ------------------------------------------------------------------------------------------------------------------ # Volumes # ------------------------------------------------------------------------------------------------------------------ def _surface_triangles(self, volume: _Volume): """Gives the triangles of the faces of a closed shell, with their face and local triangle.""" triangles, owners = [], [] for index in volume.surfaces: surface = self.surfaces[index] triangles.append(surface.triangles) owners.extend((index, i) for i in range(len(surface.triangles))) return np.vstack(triangles), owners def _perturbation(self, nodes: np.ndarray, size: float) -> np.ndarray: """ Small fixed perturbations of nodes, for their Delaunay tetrahedralization only. Nodes on a sphere are co-spherical, and their Delaunay tetrahedralization would be degenerated without it. """ missing = len(self.nodes) - len(self._perturbations) if missing > 0: self._perturbations = np.vstack([self._perturbations, self.random.uniform(-1, 1, (missing, 3))]) return self._perturbations[nodes] * PERTURBATION * size def _tetrahedralize(self, volume: _Volume, interior: np.ndarray): """ Delaunay tetrahedralization of the surface nodes of a closed shell and of interior points. :return: The Delaunay object, the surface nodes, the surface triangles in local numbering, their keys, the keys of the tetrahedra faces, and a mask of the surface triangles missing in the tetrahedralization """ triangles, owners = self._surface_triangles(volume) surface_nodes = np.unique(triangles) points = np.vstack([self.nodes.array[surface_nodes] + self._perturbation(surface_nodes, volume.size), interior]) delaunay = Delaunay(points) number = len(points) local_triangles = np.searchsorted(surface_nodes, triangles) surface_keys = _keys(local_triangles, number) face_keys = _keys(delaunay.simplices[:, TETRAHEDRON_FACES], number) missing = ~np.isin(surface_keys, face_keys) return { "delaunay": delaunay, "surface_nodes": surface_nodes, "triangles": triangles, "owners": owners, "local_triangles": local_triangles, "surface_keys": surface_keys, "face_keys": face_keys, "missing": missing, } def _split_missing_triangles(self, triangles: np.ndarray, owners: list) -> set[int]: """ Refines the surface mesh where triangles are missing in the tetrahedralization, by splitting their longest edge at its middle: on its curve for an edge on a curve, else on the face. :return: The indices of the modified faces """ curve_segments = self._curve_segments() points = self.nodes.array curve_splits = {} surface_splits = {} for triangle, (surface_index, row) in zip(triangles, owners): lengths = [np.linalg.norm(points[triangle[i]] - points[triangle[j]]) for i, j in TRIANGLE_EDGES] i, j = TRIANGLE_EDGES[int(np.argmax(lengths))] key = (min(triangle[i], triangle[j]), max(triangle[i], triangle[j])) if key in curve_segments: curve_splits[key] = curve_segments[key] else: surface_splits[key] = surface_index modified = set() for key, (curve_index, position) in sorted(curve_splits.items(), key=lambda item: (item[1][0], -item[1][1])): node = self._split_curve_segment(curve_index, position) for surface_index in self.curves[curve_index].surfaces: if self._split_surface_edges(surface_index, key, node, on_curve=True): modified.add(surface_index) for key, surface_index in surface_splits.items(): self._split_surface_edges(surface_index, key, None, on_curve=False) modified.add(surface_index) return modified def _split_surface_edges(self, surface_index: int, key: tuple[int, int], node: int | None, on_curve: bool) -> bool: """ Splits the triangle edges of a face between two nodes, at a node on a curve, or at a new node on the face. Nodes at singular points of the surface, or on seams, may have several copies in the parametric domain: all their edges are split. """ surface = self.surfaces[surface_index] triangles = surface.triangles local_edges = set() for i, j in TRIANGLE_EDGES: on_edge = ((triangles[:, i] == key[0]) & (triangles[:, j] == key[1])) | ( (triangles[:, i] == key[1]) & (triangles[:, j] == key[0]) ) for local_triangle in surface.local_triangles[on_edge]: local_edges.add((min(local_triangle[i], local_triangle[j]), max(local_triangle[i], local_triangle[j]))) if not local_edges: return False if not on_curve: uv = self._middle_uv(surface, *min(local_edges)) node = int(self.nodes.add(surface.points3d(uv[None, :]), 2, surface_index)[0]) for local1, local2 in local_edges: if on_curve: uv = self._parametric_point(surface, node, (surface.local_uv[local1] + surface.local_uv[local2]) / 2) else: uv = self._middle_uv(surface, local1, local2) self._bisect(surface, local1, local2, uv, node) return True @staticmethod def _bisect(surface: _Surface, local1: int, local2: int, uv: np.ndarray, node: int): """Splits the triangles of a face sharing an edge, by a new node on this edge.""" new_local = len(surface.local_uv) surface.local_uv = np.vstack([surface.local_uv, uv]) surface.local_nodes = np.append(surface.local_nodes, node) surface.local_singular = np.append(surface.local_singular, -1) triangles = surface.local_triangles rows = np.flatnonzero((triangles == local1).any(axis=1) & (triangles == local2).any(axis=1)) new_triangles = [] for row in rows: triangle = list(triangles[row]) i, j = triangle.index(local1), triangle.index(local2) first, second = (local1, local2) if (j - i) % 3 == 1 else (local2, local1) third = triangle[3 - i - j] triangles[row] = [first, new_local, third] new_triangles.append([new_local, second, third]) surface.local_triangles = np.vstack([triangles, np.array(new_triangles, dtype=int).reshape(-1, 3)]) surface.triangles = surface.local_nodes[surface.local_triangles] def _inside_tetrahedra(self, tetrahedralization: dict, points: np.ndarray) -> np.ndarray: """Tells which tetrahedra are inside the closed shell, the regions being separated by surface triangles.""" delaunay = tetrahedralization["delaunay"] simplices = delaunay.simplices neighbors = delaunay.neighbors number = len(simplices) on_surface = np.isin(tetrahedralization["face_keys"], tetrahedralization["surface_keys"]) linked = (neighbors >= 0) & ~on_surface rows = np.repeat(np.arange(number), 4)[linked.ravel()] columns = neighbors.ravel()[linked.ravel()] graph = coo_matrix((np.ones(len(rows)), (rows, columns)), shape=(number, number)) _, labels = connected_components(graph, directed=False) outside_labels = set(labels[np.any((neighbors < 0) & ~on_surface, axis=1)].tolist()) corners = points[simplices] volumes = np.abs(_signed_volumes(corners)) triangles = points[tetrahedralization["local_triangles"]] inside_labels = set() for label in np.unique(labels): if label in outside_labels: continue members = np.flatnonzero(labels == label) best = members[np.argmax(volumes[members])] if _is_inside(corners[best].mean(axis=0), triangles): inside_labels.add(label) return np.isin(labels, list(inside_labels)) def _curve_segments(self) -> dict: """Gives the curve and the position of the first node of each curve segment, by its pair of nodes.""" curve_segments = {} for curve_index, curve in enumerate(self.curves): for position1, position2 in curve.segments(): node1, node2 = curve.nodes[position1], curve.nodes[position2] curve_segments[(min(node1, node2), max(node1, node2))] = (curve_index, position1) return curve_segments def _flip_missing_triangles(self, tetrahedralization: dict) -> bool: """ Flips the diagonal of pairs of adjacent surface triangles, when the tetrahedralization has the other diagonal. Nearly coplanar nodes on curved surfaces have such ambiguous diagonals. :return: True if triangles were flipped """ surface_nodes = tetrahedralization["surface_nodes"] number = len(tetrahedralization["delaunay"].points) face_keys = set(tetrahedralization["face_keys"].ravel().tolist()) missing = tetrahedralization["missing"] owners = [owner for owner, is_missing in zip(tetrahedralization["owners"], missing) if is_missing] curve_segments = self._curve_segments() points = self.nodes.array edges_maps = {} modified = set() flipped = set() for surface_index, row in owners: if (surface_index, row) in modified: continue surface = self.surfaces[surface_index] if surface_index not in edges_maps: edges_map = {} for index, triangle in enumerate(surface.triangles): for i, j in TRIANGLE_EDGES: edges_map.setdefault((min(triangle[i], triangle[j]), max(triangle[i], triangle[j])), []).append( index ) edges_maps[surface_index] = edges_map edges_map = edges_maps[surface_index] triangle = surface.triangles[row] for i, j in TRIANGLE_EDGES: k = 3 - i - j p, q, r = triangle[i], triangle[j], triangle[k] edge = (min(p, q), max(p, q)) if edge in curve_segments: continue others = [index for index in edges_map[edge] if index != row] if len(others) != 1 or (surface_index, others[0]) in modified: continue other = others[0] position = [n for n in range(3) if surface.triangles[other][n] not in (p, q)][0] s = surface.triangles[other][position] if len({p, q, r, s}) < 4: continue local = np.searchsorted(surface_nodes, [p, s, q, r]) keys = _keys(np.array([[local[0], local[1], local[3]], [local[1], local[2], local[3]]]), number) if not (int(keys[0]) in face_keys and int(keys[1]) in face_keys): continue normal = np.cross(points[q] - points[p], points[r] - points[p]) + np.cross( points[p] - points[q], points[s] - points[q] ) if ( np.dot(np.cross(points[s] - points[p], points[r] - points[p]), normal) <= 0 or np.dot(np.cross(points[q] - points[s], points[r] - points[s]), normal) <= 0 ): continue local_triangle = surface.local_triangles[row] local_s = surface.local_triangles[other][position] local_p, local_q, local_r = local_triangle[i], local_triangle[j], local_triangle[k] surface.local_triangles[row] = [local_p, local_s, local_r] surface.local_triangles[other] = [local_s, local_q, local_r] modified.update({(surface_index, row), (surface_index, other)}) flipped.add(surface_index) break for surface_index in flipped: surface = self.surfaces[surface_index] surface.triangles = surface.local_nodes[surface.local_triangles] return bool(flipped) def _recover_surface(self, volume: _Volume) -> bool: """ Modifies the surface mesh of a closed shell until all its triangles are faces of the Delaunay tetrahedralization of its nodes: by flipping diagonals, else by refining the surface mesh. :return: True if faces of the shell were modified """ modified = False for _ in range(MAX_RECOVERY_ITERATIONS): tetrahedralization = self._tetrahedralize(volume, np.empty((0, 3))) if not tetrahedralization["missing"].any(): return modified modified = True while self._flip_missing_triangles(tetrahedralization): tetrahedralization = self._tetrahedralize(volume, np.empty((0, 3))) if not tetrahedralization["missing"].any(): return modified missing = tetrahedralization["missing"] owners = [owner for owner, is_missing in zip(tetrahedralization["owners"], missing) if is_missing] self._split_missing_triangles(tetrahedralization["triangles"][missing], owners) warnings.warn( "The surface mesh of a shell could not be recovered in its tetrahedral mesh, which may be non-conformal", stacklevel=3, ) return modified def _lattice(self, points: np.ndarray, size: float) -> np.ndarray: """Nodes of a perturbed body centered cubic lattice covering the bounding box of points.""" spacing = LATTICE_FACTOR * size minimum = points.min(axis=0) maximum = points.max(axis=0) axes = [np.arange(low + spacing / 2, high, spacing) for low, high in zip(minimum, maximum)] grid = np.stack(np.meshgrid(*axes, indexing="ij"), axis=-1).reshape(-1, 3) lattice = np.vstack([grid, grid + spacing / 2]) return lattice + self.random.uniform(-0.1, 0.1, lattice.shape) * spacing def _conform(self, volume: _Volume, interior: np.ndarray) -> dict: """Tetrahedralization of a closed shell, after flipping the surface diagonals that it does not have.""" tetrahedralization = self._tetrahedralize(volume, interior) while tetrahedralization["missing"].any() and self._flip_missing_triangles(tetrahedralization): tetrahedralization = self._tetrahedralize(volume, interior) return tetrahedralization def _mesh_volume(self, index: int): """Meshes a closed shell with tetrahedra conforming to its surface mesh.""" volume = self.volumes[index] size = volume.size surface_only = self._tetrahedralize(volume, np.empty((0, 3))) surface_points = self.nodes.array[surface_only["surface_nodes"]] domain = (surface_only["delaunay"], self._inside_tetrahedra(surface_only, surface_points)) protection = _circumspheres(surface_points[surface_only["local_triangles"]]) interior = self._lattice(surface_points, size) interior = interior[self._in_domain(domain, interior)] if len(interior): distances, _ = cKDTree(surface_points).query(interior) interior = interior[distances > 0.5 * size] interior = np.delete(interior, self._encroaching(interior, *protection), axis=0) for _ in range(MAX_RECOVERY_ITERATIONS): tetrahedralization = self._conform(volume, interior) missing = tetrahedralization["missing"] if not missing.any(): break triangles = tetrahedralization["triangles"][missing] encroaching = self._encroaching(interior, *_circumspheres(self.nodes.array[triangles])) if len(encroaching): interior = np.delete(interior, encroaching, axis=0) continue owners = [owner for owner, is_missing in zip(tetrahedralization["owners"], missing) if is_missing] self._split_missing_triangles(triangles, owners) triangles = self._surface_triangles(volume)[0] interior = np.delete( interior, self._encroaching(interior, *_circumspheres(self.nodes.array[triangles])), axis=0 ) if tetrahedralization["missing"].any(): warnings.warn( "The surface mesh of a shell is not recovered in its tetrahedral mesh, which may be non-conformal", stacklevel=2, ) else: protection = _circumspheres(self.nodes.array[tetrahedralization["triangles"]]) interior, tetrahedralization = self._smooth(volume, interior, tetrahedralization, domain, protection) surface_points = self.nodes.array[tetrahedralization["surface_nodes"]] points = np.vstack([surface_points, interior]) tetrahedra = tetrahedralization["delaunay"].simplices[self._inside_tetrahedra(tetrahedralization, points)] if not tetrahedralization["missing"].any(): tetrahedra = self._peel_slivers(tetrahedralization, tetrahedra, points) number_surface = len(surface_points) used_interior = np.unique(tetrahedra[tetrahedra >= number_surface]) - number_surface local_to_global = np.full(len(points), -1, dtype=int) local_to_global[:number_surface] = tetrahedralization["surface_nodes"] local_to_global[used_interior + number_surface] = self.nodes.add(interior[used_interior], 3, index) tetrahedra = local_to_global[tetrahedra] orientation = _signed_volumes(self.nodes.array[tetrahedra]) tetrahedra[orientation < 0] = tetrahedra[orientation < 0][:, [0, 2, 1, 3]] volume.tetrahedra = tetrahedra for _ in range(OPTIMIZATION_ROUNDS): self._optimize_nodes(index) if not self._flip_tetrahedra(index): break def _is_conformal(self, index: int) -> bool: """Tells if the boundary of the tetrahedra of a volume is made of the triangles of its faces.""" volume = self.volumes[index] number = len(self.nodes) keys = _keys(volume.tetrahedra[:, TETRAHEDRON_FACES], number).ravel() unique, counts = np.unique(keys, return_counts=True) surface_keys = _keys(self._surface_triangles(volume)[0], number) return np.array_equal(unique[counts == 1], np.unique(surface_keys)) def _flip_tetrahedra(self, index: int) -> bool: """ Removes flat tetrahedra of a volume by flips of its interior faces and edges, when they improve the minimal quality: two tetrahedra sharing a face become three tetrahedra sharing an edge (2-3 flip), and three tetrahedra around an edge become two tetrahedra (3-2 flip). The boundary of the volume mesh is unchanged. :return: True if tetrahedra were flipped """ volume = self.volumes[index] tetrahedra = volume.tetrahedra points = self.nodes.array number = len(points) quality = _quality(points[tetrahedra]) bad = np.flatnonzero(quality < SLIVER_QUALITY) if len(bad) == 0: return False face_keys = _keys(tetrahedra[:, TETRAHEDRON_FACES], number) faces = {} for tetrahedron_index, keys in enumerate(face_keys.tolist()): for face, key in enumerate(keys): faces.setdefault(key, []).append((tetrahedron_index, face)) edges = {} for tetrahedron_index, tetrahedron in enumerate(tetrahedra.tolist()): for i, j in TETRAHEDRON_EDGES: edges.setdefault((min(tetrahedron[i], tetrahedron[j]), max(tetrahedron[i], tetrahedron[j])), []).append( tetrahedron_index ) def oriented(new_tetrahedra): new_tetrahedra = np.array(new_tetrahedra) corners = points[new_tetrahedra] negative = _signed_volumes(corners) < 0 new_tetrahedra[negative] = new_tetrahedra[negative][:, [0, 2, 1, 3]] return new_tetrahedra, _quality(points[new_tetrahedra], signed=False) touched = set() removed, added = [], [] for tetrahedron_index in bad[np.argsort(quality[bad])]: if tetrahedron_index in touched: continue tetrahedron = tetrahedra[tetrahedron_index] done = False # 3-2 flips of the edges of the tetrahedron for i, j in TETRAHEDRON_EDGES: edge = (min(tetrahedron[i], tetrahedron[j]), max(tetrahedron[i], tetrahedron[j])) around = edges[edge] if len(around) != 3 or touched.intersection(around): continue others = [n for t in around for n in tetrahedra[t] if n not in edge] ring, counts = np.unique(others, return_counts=True) if len(ring) != 3 or np.any(counts != 2): continue new_tetrahedra, new_quality = oriented([[*ring, edge[0]], [*ring, edge[1]]]) volumes = np.abs(_signed_volumes(points[new_tetrahedra])).sum() old_volumes = np.abs(_signed_volumes(points[tetrahedra[around]])).sum() if abs(volumes - old_volumes) > 1e-9 * old_volumes or new_quality.min() <= quality[around].min(): continue removed.extend(around) added.extend(new_tetrahedra) touched.update(around) done = True break if done: continue # 2-3 flips of the faces of the tetrahedron for face, key in enumerate(face_keys[tetrahedron_index].tolist()): sharing = faces[key] if len(sharing) != 2: continue other_index, other_face = [item for item in sharing if item[0] != tetrahedron_index][0] if other_index in touched: continue apex1 = tetrahedron[face] apex2 = tetrahedra[other_index][other_face] triangle = [n for n in tetrahedron if n != apex1] new_tetrahedra, new_quality = oriented( [ [triangle[0], triangle[1], apex1, apex2], [triangle[1], triangle[2], apex1, apex2], [triangle[2], triangle[0], apex1, apex2], ] ) volumes = np.abs(_signed_volumes(points[new_tetrahedra])).sum() old_volumes = np.abs(_signed_volumes(points[tetrahedra[[tetrahedron_index, other_index]]])).sum() if abs(volumes - old_volumes) > 1e-9 * old_volumes: continue if new_quality.min() <= min(quality[tetrahedron_index], quality[other_index]): continue removed.extend([tetrahedron_index, other_index]) added.extend(new_tetrahedra) touched.update({tetrahedron_index, other_index}) break if not removed: return False volume.tetrahedra = np.vstack([np.delete(tetrahedra, removed, axis=0), np.array(added).reshape(-1, 4)]) return True def _optimize_nodes(self, index: int): """ Moves the interior nodes of the flat tetrahedra of a volume, keeping the connectivity of the mesh: each node takes the best of random positions around it, for the minimal quality of its tetrahedra. """ volume = self.volumes[index] tetrahedra = volume.tetrahedra if len(tetrahedra) == 0: return points = self.nodes.array.copy() movable = np.array([entity == (3, index) for entity in self.nodes.entities]) flat = tetrahedra.ravel() order = np.argsort(flat, kind="stable") starts = np.searchsorted(flat[order], np.arange(len(points) + 1)) for _ in range(OPTIMIZATION_PASSES): quality = _quality(points[tetrahedra], signed=True) bad_nodes = np.unique(tetrahedra[quality < SLIVER_QUALITY]) bad_nodes = bad_nodes[movable[bad_nodes]] if len(bad_nodes) == 0: break for node in bad_nodes: star = order[starts[node] : starts[node + 1]] // 4 corners = points[tetrahedra[star]] is_node = tetrahedra[star] == node current = _quality(corners, signed=True).min() neighbors = np.unique(tetrahedra[star]) candidates = np.vstack( [ points[neighbors[neighbors != node]].mean(axis=0), points[node] + self.random.uniform(-1, 1, (OPTIMIZATION_CANDIDATES, 3)) * SLIVER_MOVE * volume.size, ] ) trials = np.repeat(corners[None], len(candidates), axis=0) trials[:, is_node] = candidates[:, None, :] scores = _quality(trials.reshape(-1, 4, 3), signed=True).reshape(len(candidates), -1).min(axis=1) best = int(np.argmax(scores)) if scores[best] > current: points[node] = candidates[best] self.nodes.move(np.flatnonzero(movable), points[movable]) def _evaluate(self, tetrahedralization: dict, interior: np.ndarray): """Gives the points, the tetrahedra inside the shell and their quality.""" points = np.vstack([self.nodes.array[tetrahedralization["surface_nodes"]], interior]) tetrahedra = tetrahedralization["delaunay"].simplices[self._inside_tetrahedra(tetrahedralization, points)] return points, tetrahedra, _quality(points[tetrahedra]) def _peel_slivers(self, tetrahedralization: dict, tetrahedra: np.ndarray, points: np.ndarray) -> np.ndarray: """ Removes the flat tetrahedra made of four surface nodes and having two faces on a same face of the model: the face triangulation takes the two other faces of the tetrahedron instead. """ quality = _quality(points[tetrahedra]) candidates = np.flatnonzero(quality < SLIVER_QUALITY) number_surface = len(tetrahedralization["surface_nodes"]) if len(candidates) == 0: return tetrahedra number = len(points) surface_keys = tetrahedralization["surface_keys"] key_rows = {int(key): row for row, key in enumerate(surface_keys)} owners = tetrahedralization["owners"] curve_segments = self._curve_segments() surface_nodes = tetrahedralization["surface_nodes"] removed = [] used_rows = set() modified = set() for index in candidates: tetrahedron = tetrahedra[index] if (tetrahedron >= number_surface).any(): continue face_keys = _keys(tetrahedron[list(TETRAHEDRON_FACES)], number) rows = [key_rows.get(int(key)) for key in face_keys] surface_faces = [face for face, row in enumerate(rows) if row is not None] if len(surface_faces) != 2: continue row1, row2 = rows[surface_faces[0]], rows[surface_faces[1]] if row1 in used_rows or row2 in used_rows or owners[row1][0] != owners[row2][0]: continue # The face i of the tetrahedron is opposite to its vertex i opposite1, opposite2 = tetrahedron[surface_faces[0]], tetrahedron[surface_faces[1]] shared = [node for node in tetrahedron if node not in (opposite1, opposite2)] edge = tuple(sorted(int(surface_nodes[node]) for node in shared)) if edge in curve_segments: continue surface = self.surfaces[owners[row1][0]] local1 = surface.local_triangles[owners[row1][1]] local2 = surface.local_triangles[owners[row2][1]] global1 = surface.local_nodes[local1] global2 = surface.local_nodes[local2] # Triangle 1 contains opposite2 (it is opposite to opposite1), triangle 2 contains opposite1 node_u = int(surface_nodes[opposite2]) node_w = int(surface_nodes[opposite1]) local_u = local1[list(global1).index(node_u)] local_w = local2[list(global2).index(node_w)] normal = np.cross( *( points[np.searchsorted(surface_nodes, global1[1:])] - points[np.searchsorted(surface_nodes, global1[0])] ) ) new_rows = [] for node in shared: global_node = int(surface_nodes[node]) local_node = local1[list(global1).index(global_node)] triangle = [local_u, local_w, local_node] corners = points[np.searchsorted(surface_nodes, surface.local_nodes[triangle])] if np.dot(np.cross(corners[1] - corners[0], corners[2] - corners[0]), normal) < 0: triangle = [local_w, local_u, local_node] new_rows.append(triangle) surface.local_triangles[owners[row1][1]] = new_rows[0] surface.local_triangles[owners[row2][1]] = new_rows[1] used_rows.update({row1, row2}) modified.add(owners[row1][0]) removed.append(index) for surface_index in modified: surface = self.surfaces[surface_index] surface.triangles = surface.local_nodes[surface.local_triangles] return np.delete(tetrahedra, removed, axis=0) @staticmethod def _witness_spheres(tetrahedralization: dict): """ For each surface triangle, the smallest circumsphere of the tetrahedra having it as face. It is empty of nodes, which proves that the triangle is a face of the Delaunay tetrahedralization. """ delaunay = tetrahedralization["delaunay"] corners = delaunay.points[delaunay.simplices] centers = _circumcenters(corners) radii = np.linalg.norm(centers - corners[:, 0], axis=1) face_keys = tetrahedralization["face_keys"].ravel() order = np.argsort(face_keys) sorted_keys = face_keys[order] keys = tetrahedralization["surface_keys"] first = np.minimum(np.searchsorted(sorted_keys, keys, side="left"), len(order) - 1) last = np.searchsorted(sorted_keys, keys, side="right") found = sorted_keys[first] == keys tetrahedra1 = order[first] // 4 tetrahedra2 = order[np.minimum(first + 1, len(order) - 1)] // 4 use_second = (last - first == 2) & (radii[tetrahedra2] < radii[tetrahedra1]) tetrahedra = np.where(use_second, tetrahedra2, tetrahedra1) return centers[tetrahedra], radii[tetrahedra] * (1 + 1e-9), found @staticmethod def _in_domain(domain, points: np.ndarray) -> np.ndarray: """Tells which points are inside a closed shell, from the tetrahedra inside its surface only Delaunay.""" delaunay, inside = domain if len(points) == 0: return np.zeros(0, dtype=bool) simplex = delaunay.find_simplex(points) return (simplex >= 0) & inside[np.maximum(simplex, 0)] @staticmethod def _encroaching(points: np.ndarray, centers: np.ndarray, radii: np.ndarray) -> np.ndarray: """Gives the indices of the points inside balls.""" if len(points) == 0 or len(centers) == 0: return np.empty(0, dtype=int) close = cKDTree(points).query_ball_point(centers, radii) return np.unique(np.concatenate([np.asarray(c, dtype=int) for c in close] + [np.empty(0, dtype=int)])) def _smooth(self, volume: _Volume, interior: np.ndarray, tetrahedralization: dict, domain, protection): """ Improves the quality of the tetrahedra by optimal Delaunay triangulation smoothing: each interior node moves to the average of the circumcenters of its tetrahedra, weighted by their volume. The moves that leave the shell or enter the protection balls of the surface triangles are canceled, and the smoothing stops when the surface triangles are not recovered anymore. """ surface_points = self.nodes.array[tetrahedralization["surface_nodes"]] number_surface = len(surface_points) best = None for iteration in range(SMOOTHING_ITERATIONS + 1): if iteration: surface_triangles = tetrahedralization["triangles"] tetrahedralization = self._conform(volume, interior) if tetrahedralization["missing"].any(): break if not np.array_equal(surface_triangles, tetrahedralization["triangles"]): best = None points = np.vstack([surface_points, interior]) simplices = tetrahedralization["delaunay"].simplices inside = self._inside_tetrahedra(tetrahedralization, points) corners = points[simplices[inside]] quality = _quality(corners) score = (round(float(quality.min()), 3), float(quality.mean())) if best is None or score > best[0]: best = (score, interior, tetrahedralization) if iteration == SMOOTHING_ITERATIONS or not len(interior): break tetrahedra = simplices[inside] volumes = np.abs(_signed_volumes(corners)) centers = _circumcenters(corners) weighted = np.zeros((len(points), 3)) weights = np.zeros(len(points)) np.add.at(weighted, tetrahedra.ravel(), np.repeat(volumes[:, None] * centers, 4, axis=0)) np.add.at(weights, tetrahedra.ravel(), np.repeat(volumes, 4)) weights = weights[number_surface:] moved = interior.copy() valid = weights > 0 moved[valid] = weighted[number_surface:][valid] / weights[valid, None] rejected = ~self._in_domain(domain, moved) rejected[self._encroaching(moved, *protection)] = True moved[rejected] = interior[rejected] interior = moved if best is None or not np.array_equal(best[2]["triangles"], self._surface_triangles(volume)[0]): return interior, tetrahedralization return best[1], best[2] # ------------------------------------------------------------------------------------------------------------------ # Mesh generation # ------------------------------------------------------------------------------------------------------------------
[docs] def generate(self, mesh_dimension: int, mesh_order: int = 1): """ Generates the mesh. :param mesh_dimension: The mesh dimension (1: edges, 2: triangles, 3: tetrahedra) :type mesh_dimension: int :param mesh_order: The mesh order (1: linear, 2: second order), defaults to 1 :type mesh_order: int, optional :return: The mesher itself """ if mesh_dimension not in (1, 2, 3): raise ValueError("The mesh dimension must be 1, 2 or 3") if mesh_order not in (1, 2): raise ValueError("The mesh order must be 1 or 2") if self.mesh_dimension is not None: raise RuntimeError("The mesh has already been generated") self.mesh_dimension = mesh_dimension self.mesh_order = mesh_order self._build_topology() for index in range(len(self.curves)): self._mesh_curve(index) if mesh_dimension >= 2: for index in range(len(self.surfaces)): self._mesh_surface(index) if mesh_dimension == 3 and self.volumes: for _ in range(len(self.volumes) + 1): modified = False for volume in self.volumes: modified = self._recover_surface(volume) or modified if not modified: break to_mesh = list(range(len(self.volumes))) for _ in range(len(self.volumes) + 1): for index in to_mesh: self._mesh_volume(index) # Meshing a volume may flip triangles of a face shared with a volume meshed before to_mesh = [index for index in range(len(self.volumes)) if not self._is_conformal(index)] if not to_mesh: break else: warnings.warn("The volume meshes are not conformal on their shared faces", stacklevel=2) if mesh_order == 2: self._add_middle_nodes() return self
def _add_middle_nodes(self): """Adds the middle nodes of the second order elements, placed on the geometry.""" middle = {} for index, curve in enumerate(self.curves): curve.middle_nodes = [] for position1, position2 in curve.segments(): abscissa = curve.segment_middle_abscissa(position1, position2) node = int(self.nodes.add(_to_array(curve.edge.point_at_abscissa(abscissa)), 1, index)[0]) curve.middle_nodes.append(node) key = ( min(curve.nodes[position1], curve.nodes[position2]), max(curve.nodes[position1], curve.nodes[position2]), ) middle.setdefault(key, node) if self.mesh_dimension >= 2: for index, surface in enumerate(self.surfaces): keys, uv = [], [] for local_triangle in surface.local_triangles: for i, j in TRIANGLE_EDGES: node1 = surface.local_nodes[local_triangle[i]] node2 = surface.local_nodes[local_triangle[j]] key = (min(node1, node2), max(node1, node2)) if key not in middle: middle[key] = -1 keys.append(key) uv.append(self._middle_uv(surface, local_triangle[i], local_triangle[j])) if keys: for key, node in zip(keys, self.nodes.add(surface.points3d(np.array(uv)), 2, index)): middle[key] = int(node) if self.mesh_dimension == 3: points = self.nodes.array for index, volume in enumerate(self.volumes): keys = [] for tetrahedron in volume.tetrahedra: for i, j in TETRAHEDRON_EDGES: key = (min(tetrahedron[i], tetrahedron[j]), max(tetrahedron[i], tetrahedron[j])) if key not in middle: middle[key] = -1 keys.append(key) if keys: keys_array = np.array(keys) nodes = self.nodes.add((points[keys_array[:, 0]] + points[keys_array[:, 1]]) / 2, 3, index) for key, node in zip(keys, nodes): middle[key] = int(node) self.middle_nodes = middle # ------------------------------------------------------------------------------------------------------------------ # Export # ------------------------------------------------------------------------------------------------------------------ def _middle(self, node1: int, node2: int) -> int: return self.middle_nodes[(min(node1, node2), max(node1, node2))] def _elements(self): """Gives the element blocks: entity dimension, entity index, element type and elements nodes.""" order = self.mesh_order blocks = [] for index, node in enumerate(self.vertices): blocks.append((0, index, ELEMENT_TYPES[0][order], [[node]])) for index, curve in enumerate(self.curves): elements = [] for segment, (position1, position2) in enumerate(curve.segments()): element = [curve.nodes[position1], curve.nodes[position2]] if order == 2: element.append(curve.middle_nodes[segment]) elements.append(element) blocks.append((1, index, ELEMENT_TYPES[1][order], elements)) if self.mesh_dimension >= 2: for index, surface in enumerate(self.surfaces): elements = [list(triangle) for triangle in surface.triangles] if order == 2: elements = [e + [self._middle(e[i], e[j]) for i, j in TRIANGLE_EDGES] for e in elements] blocks.append((2, index, ELEMENT_TYPES[2][order], elements)) if self.mesh_dimension == 3: for index, volume in enumerate(self.volumes): elements = [list(tetrahedron) for tetrahedron in volume.tetrahedra] if order == 2: elements = [e + [self._middle(e[i], e[j]) for i, j in TETRAHEDRON_EDGES] for e in elements] blocks.append((3, index, ELEMENT_TYPES[3][order], elements)) return [block for block in blocks if block[3]] @staticmethod def _format(value: float) -> str: return f"{value:.16g}" def _entities_lines(self, points: np.ndarray) -> list[str]: """Lines of the $Entities section, with the bounding boxes and the boundaries of the entities.""" fmt = self._format def box_line(coordinates): minimum = coordinates.min(axis=0) - 1e-7 maximum = coordinates.max(axis=0) + 1e-7 return " ".join(fmt(value) for value in [*minimum, *maximum]) lines = ["$Entities", f"{len(self.vertices)} {len(self.curves)} {len(self.surfaces)} {len(self.volumes)}"] for index, node in enumerate(self.vertices): lines.append(f"{index + 1} " + " ".join(fmt(value) for value in points[node]) + " 0") for index, curve in enumerate(self.curves): start = min(curve.marks)[1] end = start if curve.closed else max(curve.marks)[1] lines.append(f"{index + 1} {box_line(points[curve.nodes])} 0 2 {start + 1} -{end + 1}") for index, surface in enumerate(self.surfaces): bounding = [] for loop in surface.loops: for item in loop: if item.curve is not None: tag = (item.curve + 1) * (1 if item.forward else -1) if tag not in bounding: bounding.append(tag) nodes = [self.curves[item.curve].nodes for loop in surface.loops for item in loop if item.curve is not None] nodes.extend( [[self.vertices[item.vertex]] for loop in surface.loops for item in loop if item.curve is None] ) nodes.append(list(surface.triangles.ravel())) coordinates = points[np.unique(np.concatenate([np.asarray(n, dtype=int) for n in nodes]))] lines.append( f"{index + 1} {box_line(coordinates)} 0 {len(bounding)} " + " ".join(str(tag) for tag in bounding) ) for index, volume in enumerate(self.volumes): nodes = np.unique(np.concatenate([self.surfaces[s].triangles.ravel() for s in volume.surfaces])) if len(nodes) == 0: nodes = np.unique( np.concatenate([self.curves[c].nodes for s in volume.surfaces for c in self.surfaces[s].curves()]) ) lines.append( f"{index + 1} {box_line(points[nodes])} 0 {len(volume.surfaces)} " + " ".join(str(surface + 1) for surface in volume.surfaces) ) lines.append("$EndEntities") return lines
[docs] def to_msh_lines(self) -> list[str]: """Gives the lines of the .msh file (format 4.1, ASCII) of the generated mesh.""" if self.mesh_dimension is None: raise RuntimeError("The mesh must be generated before being exported") points = self.nodes.array blocks = self._elements() used = np.unique(np.concatenate([np.asarray(block[3], dtype=int).ravel() for block in blocks])) entities = [(0, index) for index in range(len(self.vertices))] entities.extend((1, index) for index in range(len(self.curves))) entities.extend((2, index) for index in range(len(self.surfaces))) entities.extend((3, index) for index in range(len(self.volumes))) nodes_by_entity = {entity: [] for entity in entities} for node in used: nodes_by_entity[self.nodes.entities[node]].append(int(node)) tags = np.zeros(len(self.nodes), dtype=int) tag = 1 for entity in entities: for node in nodes_by_entity[entity]: tags[node] = tag tag += 1 lines = ["$MeshFormat", "4.1 0 8", "$EndMeshFormat"] lines.extend(self._entities_lines(points)) lines.extend(["$Nodes", f"{len(entities)} {len(used)} 1 {len(used)}"]) for dimension, index in entities: nodes = nodes_by_entity[(dimension, index)] lines.append(f"{dimension} {index + 1} 0 {len(nodes)}") lines.extend(str(tags[node]) for node in nodes) lines.extend(" ".join(self._format(value) for value in points[node]) for node in nodes) lines.append("$EndNodes") number_elements = sum(len(block[3]) for block in blocks) lines.extend(["$Elements", f"{len(blocks)} {number_elements} 1 {number_elements}"]) element_tag = 1 for dimension, index, element_type, elements in blocks: lines.append(f"{dimension} {index + 1} {element_type} {len(elements)}") for element in elements: lines.append(f"{element_tag} " + " ".join(str(tags[node]) for node in element)) element_tag += 1 lines.append("$EndElements") return lines
[docs] def to_msh_stream(self, stream): """Writes the generated mesh in a stream, in the gmsh .msh format (version 4.1, ASCII).""" stream.write("\n".join(self.to_msh_lines()) + "\n")
[docs] def to_msh(self, file_name: str): """ Writes the generated mesh in a file, in the gmsh .msh format (version 4.1, ASCII). :param file_name: The file name, with the .msh extension added if missing :type file_name: str """ if not file_name.endswith(".msh"): file_name += ".msh" with open(file_name, "w", encoding="utf-8") as file: self.to_msh_stream(file) return file_name