Coverage for /dolfinx-env/lib/python3.14/site-packages/io4dolfinx/backends/opencarp/helpers.py: 93%
123 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-11-30 11:58 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-11-30 11:58 +0000
1"""
2Helpers for the openCARP backend: file names, markers, ``.elem`` and ``.lon`` files,
3and the orientation of elements and facets.
5SPDX License identifier: MIT
7Copyright: Henrik Finsberg and Simula Research Laboratory
8"""
10from __future__ import annotations
12import json
13from pathlib import Path
14from typing import Any
16import numpy as np
17import numpy.typing as npt
19from ...ascii_helpers import read_rows, write_rows
20from ...utils import match_rows, strip_suffix
22__all__ = [
23 "mesh_suffixes",
24 "element_types",
25 "cell_types",
26 "element_tdim",
27 "dolfinx_to_opencarp",
28 "opencarp_to_dolfinx",
29 "mirror_permutation",
30 "element_faces",
31 "face_element_types",
32 "float_format",
33 "direction_names",
34 "mesh_file",
35 "marker_file",
36 "get_scale",
37 "marker_names",
38 "read_marker_index",
39 "write_marker_index",
40 "remove_marker_files",
41 "marker_value",
42 "read_elem_type",
43 "read_elem",
44 "write_elem",
45 "orientation",
46 "oriented_facets",
47 "sort_facets",
48]
50# Suffixes stripped from a filename to get the base name of the mesh files
51mesh_suffixes = (".pts", ".elem", ".lon")
53# openCARP element type of each supported DOLFINx cell type, and the reverse
54element_types = {
55 "triangle": "Tr",
56 "quadrilateral": "Qd",
57 "tetrahedron": "Tt",
58 "hexahedron": "Hx",
59}
60cell_types = {element: cell for cell, element in element_types.items()}
62# Topological dimension of each openCARP element type
63element_tdim = {"Tr": 2, "Qd": 2, "Tt": 3, "Hx": 3}
65# Node permutation ``p`` with ``opencarp[i] = dolfinx[p[i]]`` for each element type
66dolfinx_to_opencarp = {
67 "Tr": np.array([0, 1, 2]),
68 "Qd": np.array([0, 1, 3, 2]),
69 "Tt": np.array([0, 1, 2, 3]),
70 "Hx": np.array([0, 1, 3, 2, 4, 6, 7, 5]),
71}
73# Node permutation ``p`` with ``dolfinx[i] = opencarp[p[i]]``, the inverse of the above
74opencarp_to_dolfinx = {
75 element: np.argsort(permutation) for element, permutation in dolfinx_to_opencarp.items()
76}
78# Node permutation mirroring an element in openCARP ordering, flipping its orientation
79mirror_permutation = {
80 "Tr": np.array([0, 2, 1]),
81 "Qd": np.array([0, 3, 2, 1]),
82 "Tt": np.array([0, 2, 1, 3]),
83 "Hx": np.array([0, 3, 2, 1, 4, 7, 6, 5]),
84}
86# Local faces of 3D elements in openCARP ordering, with their nodes in cyclic order,
87# and the openCARP element type of the faces
88element_faces = {
89 "Tt": np.array([[1, 2, 3], [0, 2, 3], [0, 1, 3], [0, 1, 2]]),
90 "Hx": np.array(
91 [[0, 1, 2, 3], [4, 5, 6, 7], [0, 1, 7, 4], [1, 2, 6, 7], [2, 3, 5, 6], [3, 0, 4, 5]]
92 ),
93}
94face_element_types = {"Tt": "Tr", "Hx": "Qd"}
96# Format of floating point values, enough digits for µm coordinates of a heart
97float_format = "%.10g"
99# Names of the directions in ``.lon``, in column order
100direction_names = ("fiber", "sheet")
103def mesh_file(filename: Path | str, suffix: str) -> Path:
104 """Get the path of one of the mesh files, e.g. ``<base>.elem``."""
105 return Path(f"{strip_suffix(filename, mesh_suffixes)}{suffix}")
108def marker_file(filename: Path | str, name: str, suffix: str) -> Path:
109 """Get the path of the file of a marker, e.g. ``<base>_<name>.vtx``."""
110 return Path(f"{strip_suffix(filename, mesh_suffixes)}_{name}{suffix}")
113def get_scale(backend_args: dict[str, Any]) -> float:
114 """Get the factor converting mesh coordinates to µm.
116 It has no default, as a wrong unit gives a mesh that openCARP loads without
117 complaint but simulates at the wrong size.
118 """
119 try:
120 scale = float(backend_args["scale"])
121 except (KeyError, TypeError) as e:
122 raise ValueError(
123 "The openCARP backend needs backend_args['scale'], the factor converting mesh "
124 "coordinates to µm (e.g. 1000.0 for a mesh in mm, 1.0 for a mesh in µm)."
125 ) from e
126 if not scale > 0:
127 raise ValueError(f"backend_args['scale'] must be positive, got {scale}.")
128 return scale
131def marker_names(markers: dict[str, Any], dim: int) -> dict[int, str]:
132 """Get the name of each marker value of entities of a given dimension.
134 Args:
135 markers: Map from name to value, or to ``(value, dim)``
136 dim: Topological dimension of the entities
138 Returns:
139 Map from value to name. Markers with another dimension are left out.
140 """
141 names = {}
142 for name, marker in markers.items():
143 if isinstance(marker, (int, np.integer)):
144 value, marker_dim = int(marker), None
145 else:
146 value = int(marker[0])
147 marker_dim = int(marker[1]) if len(marker) > 1 else None
148 if marker_dim is None or marker_dim == dim:
149 names[value] = str(name)
150 return names
153def read_marker_index(filename: Path | str) -> dict[str, dict[str, Any]]:
154 """Read the index of the markers written for a mesh, ``<base>.markers.json``.
156 Returns:
157 Map from marker name to its ``"value"``, ``"dim"`` and whether it has a
158 ``.surf`` file (``"surf"``). Empty if there is no index.
159 """
160 path = mesh_file(filename, ".markers.json")
161 if not path.exists():
162 return {}
163 return json.loads(path.read_text())
166def write_marker_index(filename: Path | str, index: dict[str, dict[str, Any]]):
167 """Write the index of the markers of a mesh, or remove it if there are none."""
168 path = mesh_file(filename, ".markers.json")
169 if index:
170 path.write_text(json.dumps(index, indent=2, sort_keys=True) + "\n")
171 else:
172 path.unlink(missing_ok=True)
175def remove_marker_files(filename: Path | str, names: list[str]):
176 """Remove the ``.vtx`` and ``.surf`` files of markers."""
177 for name in names:
178 for suffix in (".vtx", ".surf"):
179 marker_file(filename, name, suffix).unlink(missing_ok=True)
182def marker_value(markers: dict[str, Any], index: dict[str, dict[str, Any]], name: str) -> int:
183 """Get the value of a marker read from ``<base>_<name>.vtx`` or ``.surf``.
185 Args:
186 markers: Map from name to value, or to ``(value, dim)``
187 index: The index of the markers of the mesh, see :func:`read_marker_index`
188 name: Name of the marker in the filename
190 Returns:
191 The value in ``markers``, else in ``index``, else the name itself if it is an
192 integer, else ``1``.
193 """
194 if name in markers:
195 marker = markers[name]
196 return int(marker) if isinstance(marker, (int, np.integer)) else int(marker[0])
197 if name in index:
198 return int(index[name]["value"])
199 try:
200 return int(name)
201 except ValueError:
202 return 1
205def read_elem_type(path: Path) -> str:
206 """Read the openCARP element type of the first element of an ``.elem`` file."""
207 with open(path) as f:
208 f.readline()
209 line = f.readline().split()
210 if len(line) == 0:
211 raise ValueError(f"{path} has no elements.")
212 if line[0] not in element_tdim:
213 raise NotImplementedError(
214 f"openCARP element type {line[0]} in {path} is not supported, "
215 f"only {list(element_tdim)}."
216 )
217 return line[0]
220def read_elem(
221 path: Path, local_range: tuple[int, int] | list[int] | None = None
222) -> tuple[str, npt.NDArray[np.int64], npt.NDArray[np.int32]]:
223 """Read the elements of an ``.elem`` file, or the faces of a ``.surf`` file.
225 Args:
226 path: The ``.elem`` or ``.surf`` file
227 local_range: Range of elements to read, all if ``None``
229 Returns:
230 Tuple containing:
231 - The openCARP element type
232 - Nodes of each element in openCARP ordering
233 - Region tag of each element, ``0`` if the file has none
234 """
235 elem_type = read_elem_type(path)
236 num_nodes = len(dolfinx_to_opencarp[elem_type])
237 with open(path) as f:
238 f.readline()
239 num_columns = len(f.readline().split())
240 # The type column is read as strings, the nodes and tags as integers
241 types = read_rows(path, 1, local_range, usecols=0)
242 if other := sorted(set(types[:, 0]) - {elem_type}):
243 raise NotImplementedError(
244 f"Meshes with several element types are not supported, {path} has "
245 f"{[elem_type, *other]}."
246 )
247 numbers = read_rows(
248 path, num_columns - 1, local_range, dtype=np.int64, usecols=range(1, num_columns)
249 )
250 cells = numbers[:, :num_nodes]
251 if num_columns > 1 + num_nodes:
252 tags = numbers[:, num_nodes].astype(np.int32)
253 else:
254 tags = np.zeros(len(cells), dtype=np.int32)
255 return elem_type, cells, tags
258def write_elem(
259 path: Path,
260 elem_type: str,
261 cells: npt.NDArray[np.int64],
262 tags: npt.NDArray[np.int32] | None = None,
263):
264 """Write elements, with their region tags if given, to an ``.elem`` or ``.surf`` file."""
265 rows = cells if tags is None else np.column_stack([cells, tags])
266 # Each line is the element type followed by the nodes, and the tag if given
267 fmt = " ".join([elem_type] + ["%d"] * rows.shape[1])
268 write_rows(path, [str(len(rows))], rows, fmt)
271def orientation(
272 elem_type: str, x: npt.NDArray[np.floating], cells: npt.NDArray[np.int64]
273) -> npt.NDArray:
274 """Get the orientation of each element in openCARP ordering.
276 Returns:
277 The triple product of the edges at node 0 for 3D elements, the z-component of
278 the cross product of the edges at node 0 for 2D elements. Positive for the
279 orientation of openCARP's ``mesher``.
280 """
281 p = x[cells]
282 # Nodes 1 and 2 of simplices, 1 and 3 of quadrilaterals and hexahedra, are the
283 # neighbours of node 0 in the first face
284 second = 2 if elem_type in ("Tr", "Tt") else 3
285 normal = np.cross(p[:, 1] - p[:, 0], p[:, second] - p[:, 0])
286 if element_tdim[elem_type] == 2:
287 return normal[:, 2]
288 third = 3 if elem_type == "Tt" else 4
289 return np.einsum("ij,ij->i", normal, p[:, third] - p[:, 0])
292def oriented_facets(
293 x: npt.NDArray[np.floating],
294 elem_type: str,
295 cells: npt.NDArray[np.int64],
296 facets: npt.NDArray[np.int64],
297) -> npt.NDArray[np.int64]:
298 """Orient facets of a 3D mesh to point out of an element they are a face of.
300 A facet between two elements points out of the element whose centre comes first
301 in lexicographic ``(x, y, z)`` order, so the result does not depend on the
302 ordering of the elements.
304 Args:
305 x: Node coordinates
306 elem_type: openCARP element type of the mesh
307 cells: Nodes of each element in openCARP ordering
308 facets: Nodes of each facet in cyclic order
310 Returns:
311 The oriented facets, in the order of ``facets``
312 """
313 local_faces = element_faces[elem_type]
314 faces = cells[:, local_faces].reshape(-1, local_faces.shape[1])
315 face_cell_centres = np.repeat(x[cells].mean(axis=1), len(local_faces), axis=0)
316 order = np.lexsort(face_cell_centres.T[::-1])
317 match = match_rows(faces[order], facets)
318 if np.any(match < 0):
319 raise ValueError(f"{np.count_nonzero(match < 0)} tagged facets are not faces of the mesh.")
320 cell_centres = face_cell_centres[order][match]
322 facets = facets.copy()
323 p = x[facets]
324 # A normal of each facet, from two edges of a triangle or the diagonals of a
325 # quadrilateral, with nodes in cyclic order
326 if facets.shape[1] == 3:
327 normals = np.cross(p[:, 1] - p[:, 0], p[:, 2] - p[:, 0])
328 else:
329 normals = np.cross(p[:, 2] - p[:, 0], p[:, 3] - p[:, 1])
330 outward = p.mean(axis=1) - cell_centres
331 inward = np.einsum("ij,ij->i", normals, outward) < 0
332 facets[inward] = facets[inward][:, mirror_permutation[face_element_types[elem_type]]]
333 return facets
336def sort_facets(facets: npt.NDArray[np.int64]) -> npt.NDArray[np.int64]:
337 """Start each facet with its smallest node, keeping its orientation, and sort the
338 facets, so the result does not depend on how the facets were distributed."""
339 num_nodes = facets.shape[1]
340 shift = np.argmin(facets, axis=1)[:, None]
341 facets = np.take_along_axis(facets, (shift + np.arange(num_nodes)) % num_nodes, axis=1)
342 return facets[np.lexsort(facets.T[::-1])]