Coverage for /dolfinx-env/lib/python3.14/site-packages/io4dolfinx/backends/opencarp/backend.py: 96%

222 statements  

« prev     ^ index     » next       coverage.py v7.18.0, created at 2026-11-30 11:58 +0000

1""" 

2openCARP interface to io4dolfinx. 

3 

4openCARP stores a mesh as a set of ASCII files sharing a base name, with 0-based 

5node indices and coordinates in µm. See 

6https://opencarp.org/documentation/user-manual (section "Mesh files"). 

7 

8- ``<base>.pts``: number of nodes, then one ``x y z`` line per node. 2D meshes have 

9 ``z = 0``. 

10- ``<base>.elem``: number of elements, then one line per element with its type, its 

11 nodes and its tag, e.g. ``Tt n0 n1 n2 n3 tag``. Linear triangles (``Tr``), 

12 quadrilaterals (``Qd``), tetrahedra (``Tt``) and hexahedra (``Hx``) are supported, 

13 one type per mesh. The tag is the region of the element; in DOLFINx terms the 

14 value of a cell :class:`dolfinx.mesh.MeshTags`. 

15- ``<base>.lon``: number of directions (1 for fibers, 2 for fibers and sheets), 

16 then one ``fx fy fz [sx sy sz]`` line per element, in the order of ``.elem``. 

17- ``<base>_<marker>.vtx``: number of nodes, the domain (``extra`` for indices into the whole mesh) 

18 and one node index per line, for stimuli and boundary conditions. 

19- ``<base>_<marker>.surf``: number of faces, then one ``Tr n0 n1 n2`` or 

20 ``Qd n0 n1 n2 n3`` line per face of a 3D mesh. 

21- ``<base>.markers.json``: the name, value and dimension of each marker written by 

22 io4dolfinx, so that reading gives the original values, and writing the mesh again 

23 removes the marker files of the old mesh. openCARP does not read it. 

24 

25Each file is written by rank 0. 

26 

27Writing a mesh with markers and fibers takes the generic io4dolfinx functions, called 

28in this order with ``backend="opencarp"``: 

29 

30.. code-block:: python 

31 

32 args = {"scale": 1000.0, "markers": {"ENDO": (1, 2), "EPI": (2, 2)}} # mesh in mm 

33 io4dolfinx.write_mesh( 

34 "heart", mesh, backend="opencarp", backend_args=args, on_input_mesh=True 

35 ) 

36 for tags in (cell_tags, facet_tags): 

37 io4dolfinx.write_meshtags( 

38 "heart", mesh, tags, backend="opencarp", backend_args=args, on_input_mesh=True 

39 ) 

40 io4dolfinx.write_cell_data( 

41 "heart", f0, 0.0, io4dolfinx.FileMode.write, args, "opencarp", on_input_mesh=True 

42 ) 

43 io4dolfinx.write_cell_data( 

44 "heart", s0, 0.0, io4dolfinx.FileMode.append, args, "opencarp", on_input_mesh=True 

45 ) 

46 

47- The mesh comes first, as tags and directions are written against ``<base>.elem``. 

48- Cell tags set the regions in ``<base>.elem``, facet tags give a ``.vtx`` (and in 

49 3D a ``.surf``) file per marker value. 

50- :func:`io4dolfinx.write_cell_data` with :attr:`FileMode.write 

51 <io4dolfinx.FileMode.write>` writes the fibers, and with :attr:`FileMode.append 

52 <io4dolfinx.FileMode.append>` adds the sheets. Fields are interpolated into DG-0, 

53 so fields in a quadrature space must first be generated in a P-1 or DG-0 space. 

54 

55The ordering of nodes and elements must be the same in every step, so pass the same 

56``on_input_mesh`` to every function: 

57 

58- With ``on_input_mesh=True`` (as above), the files use the ordering of the input 

59 mesh and are the same whatever the number of processes. Use this for reproducible 

60 files. 

61- With ``on_input_mesh=False`` (the default), the files use the DOLFINx ordering, 

62 which depends on the partitioning. 

63 

64Mixing the two gives directions and markers on the wrong elements and nodes. 

65 

66The files are read with :func:`io4dolfinx.read_mesh`, :func:`io4dolfinx.read_meshtags` 

67and :func:`io4dolfinx.read_cell_data`, given the path of any of the mesh files, e.g. 

68``"heart.elem"``. 

69 

70Elements are written with the orientation used by openCARP's ``mesher``: positive 

71volume in 3D, counter-clockwise in the xy-plane in 2D. Hexahedra list one face 

72(nodes 0-3) followed by the nodes opposite nodes 0, 3, 2 and 1. 

73 

74Backend arguments: 

75 

76- ``"scale"`` (required for meshes): factor converting mesh coordinates to µm, 

77 e.g. ``1000.0`` for a mesh in mm. Coordinates are divided by it when read. 

78- ``"default_tag"``: region tag of cells without a cell tag (default ``0``). 

79- ``"markers"``: map from marker name to value, or to ``(value, dim)`` as used by 

80 cardiac-geometriesx. Names the ``.vtx`` and ``.surf`` files of a marker value, 

81 which otherwise use the value itself. When reading, it takes precedence over the 

82 values in ``<base>.markers.json``. 

83- ``"surf"``: write ``.surf`` files for facet tags of 3D meshes (default ``True``). 

84- ``"vtx_domain"``: domain written to ``.vtx`` files (default ``"extra"``, meaning 

85 indices into the whole mesh, as written; ``"intra"`` means the myocardium submesh). 

86 

87SPDX License identifier: MIT 

88 

89Copyright: Henrik Finsberg and Simula Research Laboratory 

90""" 

91 

92import glob 

93from pathlib import Path 

94from typing import Any 

95 

96from mpi4py import MPI 

97 

98import basix 

99import dolfinx 

100import numpy as np 

101import numpy.typing as npt 

102 

103from ...ascii_helpers import check_row_count, read_count, read_rows, write_rows 

104from ...comm_helpers import gather_concatenate, gather_rows, run_on_all, run_on_root 

105from ...structures import ArrayData, FunctionData, MeshData, MeshTagsData, ReadMeshData 

106from ...utils import check_file_exists, compute_local_range, match_rows, strip_suffix 

107from .. import FileMode, ReadMode 

108from . import helpers 

109 

110read_mode = ReadMode.parallel 

111 

112 

113def get_default_backend_args(arguments: dict[str, Any] | None) -> dict[str, Any]: 

114 args = dict(arguments or {}) 

115 args.setdefault("default_tag", 0) 

116 args.setdefault("markers", {}) 

117 args.setdefault("surf", True) 

118 args.setdefault("vtx_domain", "extra") 

119 return args 

120 

121 

122def write_attributes( 

123 filename: Path | str, 

124 comm: MPI.Comm, 

125 name: str, 

126 attributes: dict[str, np.ndarray], 

127 backend_args: dict[str, Any] | None = None, 

128): 

129 """Write attributes to file. 

130 

131 Args: 

132 filename: Path to file to write to 

133 comm: MPI communicator used in storage 

134 name: Name of the attributes 

135 attributes: Dictionary of attributes to write to file 

136 backend_args: Arguments to backend 

137 """ 

138 raise NotImplementedError("The openCARP backend cannot write attributes.") 

139 

140 

141def read_attributes( 

142 filename: Path | str, 

143 comm: MPI.Comm, 

144 name: str, 

145 backend_args: dict[str, Any] | None = None, 

146) -> dict[str, Any]: 

147 """Read attributes from file. 

148 

149 Args: 

150 filename: Path to file to read from 

151 comm: MPI communicator used in storage 

152 name: Name of the attributes 

153 backend_args: Arguments to backend 

154 Returns: 

155 The attributes 

156 """ 

157 raise NotImplementedError("The openCARP backend cannot read attributes.") 

158 

159 

160def snapshot_checkpoint( 

161 filename: Path | str, 

162 mode: FileMode, 

163 u: dolfinx.fem.Function, 

164 backend_args: dict[str, Any] | None, 

165): 

166 """Create a snapshot checkpoint of a dolfinx function. 

167 

168 Args: 

169 filename: Path to file to read from 

170 mode: File-mode to store the function 

171 u: dolfinx function to create a snapshot checkpoint for 

172 backend_args: Arguments to backend 

173 """ 

174 raise NotImplementedError("The openCARP backend cannot make checkpoints.") 

175 

176 

177def read_hdf5_array( 

178 comm: MPI.Comm, 

179 filename: Path | str, 

180 group: str, 

181 backend_args: dict[str, Any] | None, 

182) -> tuple[np.ndarray, int]: 

183 """Read an array from an HDF5 file. 

184 

185 Args: 

186 comm: MPI communicator used in storage 

187 filename: Path to file to read from 

188 group: Group in HDF5 file where array is stored 

189 backend_args: Arguments to backend 

190 

191 Returns: 

192 Tuple containing: 

193 - Numpy array read from file 

194 - Global starting point on the process. 

195 Process 0 has [0, M), process 1 [M, N), process 2 [N, O) etc. 

196 """ 

197 raise NotImplementedError("The openCARP backend cannot read HDF5 arrays.") 

198 

199 

200def read_timestamps( 

201 filename: Path | str, 

202 comm: MPI.Comm, 

203 function_name: str, 

204 backend_args: dict[str, Any] | None = None, 

205) -> npt.NDArray[np.float64 | str]: # type: ignore[type-var] 

206 """Read time-stamps from a checkpoint file. 

207 

208 Args: 

209 filename: Path to file 

210 comm: MPI communicator 

211 function_name: Name of the function to read time-stamps for 

212 backend_args: Arguments for backend, for instance file type. 

213 

214 Returns: 

215 The time-stamps 

216 """ 

217 raise NotImplementedError("The openCARP backend cannot read timestamps.") 

218 

219 

220def write_mesh( 

221 filename: Path | str, 

222 comm: MPI.Comm, 

223 mesh: MeshData, 

224 backend_args: dict[str, Any] | None = None, 

225 mode: FileMode = FileMode.write, 

226 time: float = 0.0, 

227): 

228 """Write a linear mesh to ``<base>.pts`` and ``<base>.elem``. 

229 

230 Supports triangle and quadrilateral meshes in 2D (also with 3D coordinates in a 

231 plane of constant z), and tetrahedral and hexahedral meshes in 3D. Every cell gets 

232 the region tag ``backend_args["default_tag"]``, until cell tags are written with 

233 :func:`write_meshtags`. Elements with the opposite orientation of openCARP's 

234 ``mesher`` are mirrored. The ``<base>.lon`` and marker files of an earlier mesh 

235 are removed. 

236 

237 Args: 

238 filename: Base name of the files, or the path of one of them 

239 comm: MPI communicator used in storage 

240 mesh: Mesh data, from :func:`io4dolfinx.write_mesh` 

241 backend_args: Arguments to backend, ``"scale"`` is required 

242 mode: Only :attr:`FileMode.write` is supported 

243 time: Not used 

244 """ 

245 args = get_default_backend_args(backend_args) 

246 if mesh.cell_type not in helpers.element_types or mesh.degree != 1: 

247 raise NotImplementedError( 

248 "The openCARP backend supports linear triangle, quadrilateral, tetrahedral and " 

249 f"hexahedral meshes, got a {mesh.cell_type} mesh of degree {mesh.degree}." 

250 ) 

251 elem_type = helpers.element_types[mesh.cell_type] 

252 gdim = mesh.local_geometry.shape[1] 

253 if mode != FileMode.write: 

254 raise NotImplementedError("The openCARP backend can only write a mesh to new files.") 

255 scale = helpers.get_scale(args) 

256 

257 x = gather_rows(comm, mesh.local_geometry, mesh.local_geometry_pos, mesh.num_nodes_global) 

258 cells = gather_rows(comm, mesh.local_topology, mesh.local_topology_pos, mesh.num_cells_global) 

259 

260 def write(): 

261 assert x is not None and cells is not None 

262 points = np.zeros((len(x), 3), dtype=x.dtype) 

263 points[:, :gdim] = x 

264 if helpers.element_tdim[elem_type] == 2 and np.ptp(points[:, 2]) > 0: 

265 raise NotImplementedError( 

266 f"The {mesh.cell_type} mesh does not lie in a plane of constant z. Surface " 

267 "meshes in 3D are not supported." 

268 ) 

269 elements = cells[:, helpers.dolfinx_to_opencarp[elem_type]] 

270 orientation = helpers.orientation(elem_type, points, elements) 

271 if np.any(orientation == 0): 

272 raise ValueError(f"The mesh has {np.count_nonzero(orientation == 0)} degenerate cells.") 

273 flip = orientation < 0 

274 elements[flip] = elements[flip][:, helpers.mirror_permutation[elem_type]] 

275 

276 write_rows( 

277 helpers.mesh_file(filename, ".pts"), 

278 [str(len(points))], 

279 points * scale, 

280 helpers.float_format, 

281 ) 

282 tags = np.full(len(elements), args["default_tag"], dtype=np.int32) 

283 helpers.write_elem(helpers.mesh_file(filename, ".elem"), elem_type, elements, tags) 

284 helpers.mesh_file(filename, ".lon").unlink(missing_ok=True) 

285 helpers.remove_marker_files(filename, list(helpers.read_marker_index(filename))) 

286 helpers.write_marker_index(filename, {}) 

287 

288 run_on_root(comm, write) 

289 

290 

291def read_mesh_data( 

292 filename: Path | str, 

293 comm: MPI.Comm, 

294 time: str | float | None = 0.0, 

295 read_from_partition: bool = False, 

296 backend_args: dict[str, Any] | None = None, 

297) -> ReadMeshData: 

298 """Read a linear mesh from ``<base>.pts`` and ``<base>.elem``. 

299 

300 Node and cell data is read in contiguous chunks on each process. A mesh of 2D 

301 elements must lie in a plane of constant ``z``, and gets 2D coordinates. 

302 

303 Args: 

304 filename: Base name of the files, or the path of one of them 

305 comm: The MPI communciator to distribute the mesh over 

306 time: Not used 

307 read_from_partition: Read mesh with partition from file (not supported) 

308 backend_args: Arguments to backend, ``"scale"`` is required 

309 Returns: 

310 The mesh topology, geometry, UFL domain and partition function 

311 """ 

312 if read_from_partition: 

313 raise NotImplementedError("The openCARP backend cannot read partitioning data.") 

314 args = get_default_backend_args(backend_args) 

315 scale = helpers.get_scale(args) 

316 pts = helpers.mesh_file(filename, ".pts") 

317 elem = helpers.mesh_file(filename, ".elem") 

318 check_file_exists(pts) 

319 check_file_exists(elem) 

320 elem_type = helpers.read_elem_type(elem) 

321 

322 def read(): 

323 x = read_rows(pts, 3, compute_local_range(comm, read_count(pts)), dtype=np.float64) 

324 _, cells, _ = helpers.read_elem(elem, compute_local_range(comm, read_count(elem))) 

325 return x, cells 

326 

327 x, cells = run_on_all(comm, read) 

328 if helpers.element_tdim[elem_type] == 2: 

329 z_min = comm.allreduce(x[:, 2].min(initial=np.inf), op=MPI.MIN) 

330 z_max = comm.allreduce(x[:, 2].max(initial=-np.inf), op=MPI.MAX) 

331 if z_max > z_min: 

332 raise NotImplementedError( 

333 f"{elem} has 2D elements that do not lie in a plane of constant z. Surface " 

334 "meshes in 3D are not supported." 

335 ) 

336 x = x[:, :2] 

337 return ReadMeshData( 

338 cells=cells[:, helpers.opencarp_to_dolfinx[elem_type]], 

339 cell_type=helpers.cell_types[elem_type], 

340 x=x / scale, 

341 lvar=int(basix.LagrangeVariant.equispaced), 

342 degree=1, 

343 partition_graph=None, 

344 ) 

345 

346 

347def write_meshtags( 

348 filename: str | Path, 

349 comm: MPI.Comm, 

350 data: MeshTagsData, 

351 backend_args: dict[str, Any] | None = None, 

352): 

353 """Write mesh tags to the openCARP files of a mesh written earlier. 

354 

355 - Cell tags set the region tags in ``<base>.elem``. Untagged cells keep their tag. 

356 - Other tags are written, per value, to ``<base>_<marker>.vtx`` with the nodes of 

357 the tagged entities. 

358 - Facet tags of a 3D mesh are also written to ``<base>_<marker>.surf``, as 

359 triangles or quadrilaterals with outward normals (if ``backend_args["surf"]``). 

360 A facet between two elements points out of the element whose centre comes 

361 first in lexicographic ``(x, y, z)`` order. 

362 

363 ``<marker>`` is the name of the value in ``backend_args["markers"]``, or the 

364 value itself. The markers are recorded in ``<base>.markers.json``, and replace 

365 the markers of the same dimension written earlier. 

366 

367 Args: 

368 filename: Base name of the files, or the path of one of them 

369 comm: MPI communicator used in storage 

370 data: Mesh tags with nodes in the ordering the mesh was written in, see the 

371 ``on_input_mesh`` argument of :func:`io4dolfinx.write_meshtags` 

372 backend_args: Arguments to backend 

373 """ 

374 args = get_default_backend_args(backend_args) 

375 local_indices = np.asarray(data.indices, dtype=np.int64) 

376 num_nodes = data.num_dofs_per_entity or local_indices.shape[-1] 

377 indices = gather_concatenate(comm, local_indices.reshape(-1, num_nodes)) 

378 values = gather_concatenate(comm, np.asarray(data.values, dtype=np.int32)) 

379 elem = helpers.mesh_file(filename, ".elem") 

380 

381 def write(): 

382 assert indices is not None and values is not None 

383 check_file_exists(elem) 

384 elem_type, cells, tags = helpers.read_elem(elem) 

385 if data.dim == helpers.element_tdim[elem_type]: 

386 rows = match_rows(cells, indices) 

387 if np.any(rows < 0): 

388 raise ValueError(f"{np.count_nonzero(rows < 0)} tagged cells are not in {elem}.") 

389 tags[rows] = values 

390 helpers.write_elem(elem, elem_type, cells, tags) 

391 return 

392 

393 names = helpers.marker_names(args["markers"], data.dim) 

394 marker_values = np.unique(values) 

395 marker_names = [names.get(int(value), str(value)) for value in marker_values] 

396 if len(set(marker_names)) < len(marker_names): 

397 raise ValueError( 

398 f"Marker values {marker_values.tolist()} of dimension {data.dim} get the " 

399 f"file names {marker_names}, which are not unique." 

400 ) 

401 index = helpers.read_marker_index(filename) 

402 replaced = [name for name, marker in index.items() if marker["dim"] == data.dim] 

403 if clash := sorted(set(marker_names) & (set(index) - set(replaced))): 

404 index_file = helpers.mesh_file(filename, ".markers.json") 

405 raise ValueError( 

406 f"Markers {clash} of dimension {data.dim} have the same name as markers of " 

407 f"another dimension in {index_file}." 

408 ) 

409 helpers.remove_marker_files(filename, replaced) 

410 index = {name: marker for name, marker in index.items() if name not in replaced} 

411 

412 write_surf = args["surf"] and helpers.element_tdim[elem_type] == 3 and data.dim == 2 

413 if write_surf: 

414 pts = helpers.mesh_file(filename, ".pts") 

415 x = read_rows(pts, 3, dtype=np.float64) 

416 face_type = helpers.face_element_types[elem_type] 

417 # DOLFINx orders the nodes of a quadrilateral facet as a tensor product 

418 facets = indices[:, helpers.dolfinx_to_opencarp[face_type]] 

419 facets = helpers.oriented_facets(x, elem_type, cells, facets) 

420 for value, name in zip(marker_values, marker_names): 

421 marked = values == value 

422 nodes = np.unique(indices[marked]) 

423 write_rows( 

424 helpers.marker_file(filename, name, ".vtx"), 

425 [str(len(nodes)), args["vtx_domain"]], 

426 nodes, 

427 "%d", 

428 ) 

429 if write_surf: 

430 faces = helpers.sort_facets(facets[marked]) 

431 helpers.write_elem(helpers.marker_file(filename, name, ".surf"), face_type, faces) 

432 index[name] = {"value": int(value), "dim": int(data.dim), "surf": bool(write_surf)} 

433 helpers.write_marker_index(filename, index) 

434 

435 run_on_root(comm, write) 

436 

437 

438def read_meshtags_data( 

439 filename: str | Path, 

440 comm: MPI.Comm, 

441 name: str, 

442 backend_args: dict[str, Any] | None = None, 

443) -> MeshTagsData: 

444 """Read mesh tags from openCARP files. 

445 

446 Args: 

447 filename: Base name of the files, or the path of one of them 

448 comm: MPI communicator used in storage 

449 name: ``"cell"`` for the region tags in ``<base>.elem``, ``"facet"`` for the 

450 faces of the ``.surf`` files of all facet markers in 

451 ``<base>.markers.json``, otherwise the name of a marker: the faces of 

452 ``<base>_<name>.surf`` or, if there is none, the nodes of 

453 ``<base>_<name>.vtx``. 

454 backend_args: Arguments to backend. The value of a marker is taken from 

455 ``"markers"``, else from ``<base>.markers.json``, else from its name if 

456 that is an integer, else it is ``1``. 

457 

458 Returns: 

459 Internal data structure for the mesh tags read from file 

460 """ 

461 args = get_default_backend_args(backend_args) 

462 if name == "cell": 

463 elem = helpers.mesh_file(filename, ".elem") 

464 check_file_exists(elem) 

465 elem_type, cells, tags = run_on_all( 

466 comm, lambda: helpers.read_elem(elem, compute_local_range(comm, read_count(elem))) 

467 ) 

468 cells = cells[:, helpers.opencarp_to_dolfinx[elem_type]] 

469 return MeshTagsData( 

470 name=name, values=tags, indices=cells, dim=helpers.element_tdim[elem_type] 

471 ) 

472 

473 base = strip_suffix(filename, helpers.mesh_suffixes) 

474 index = helpers.read_marker_index(filename) 

475 if name == "facet": 

476 files = [ 

477 helpers.marker_file(filename, marker, ".surf") 

478 for marker, entry in sorted(index.items()) 

479 if entry["dim"] == 2 and entry["surf"] 

480 ] 

481 if len(files) == 0: 

482 index_file = helpers.mesh_file(filename, ".markers.json") 

483 raise FileNotFoundError( 

484 f"{index_file} lists no facet markers with .surf files. " 

485 "Read the markers of other files by name." 

486 ) 

487 dim = 2 

488 elif (surf := helpers.marker_file(filename, name, ".surf")).exists(): 

489 files, dim = [surf], 2 

490 elif (vtx := helpers.marker_file(filename, name, ".vtx")).exists(): 

491 files, dim = [vtx], 0 

492 else: 

493 available = sorted( 

494 p.name[len(base.name) + 1 :].rsplit(".", 1)[0] 

495 for p in base.parent.glob(f"{glob.escape(base.name)}_*") 

496 if p.suffix in (".surf", ".vtx") 

497 ) 

498 raise KeyError(f"Could not find marker '{name}' for {base}. Available: {available}") 

499 

500 # Marker files are small, so rank 0 reads them all. read_meshtags reshapes the 

501 # empty indices of the other ranks. 

502 def read(): 

503 all_indices, all_values = [], [] 

504 for path in files: 

505 marker = path.name[len(base.name) + 1 : -len(path.suffix)] 

506 if dim == 2: 

507 if read_count(path) == 0: 

508 entities = np.zeros((0, 3), dtype=np.int64) 

509 else: 

510 face_type, faces, _ = helpers.read_elem(path) 

511 if face_type not in helpers.face_element_types.values(): 

512 raise NotImplementedError(f"Unsupported face type {face_type} in {path}.") 

513 entities = faces[:, helpers.opencarp_to_dolfinx[face_type]] 

514 else: 

515 entities = read_rows(path, 1, header=2, dtype=np.int64) 

516 all_indices.append(entities) 

517 all_values.append( 

518 np.full(len(entities), helpers.marker_value(args["markers"], index, marker)) 

519 ) 

520 return np.vstack(all_indices), np.concatenate(all_values).astype(np.int32) 

521 

522 indices, values = np.zeros((0, 1), dtype=np.int64), np.zeros(0, dtype=np.int32) 

523 result = run_on_root(comm, read) 

524 if result is not None: 

525 indices, values = result 

526 return MeshTagsData(name=name, values=values, indices=indices, dim=dim) 

527 

528 

529def read_dofmap( 

530 filename: str | Path, 

531 comm: MPI.Comm, 

532 name: str, 

533 backend_args: dict[str, Any] | None, 

534) -> dolfinx.graph.AdjacencyList: 

535 """Read the dofmap of a function with a given name. 

536 

537 Args: 

538 filename: Path to file to read from 

539 comm: MPI communicator used in storage 

540 name: Name of the function to read the dofmap for 

541 backend_args: Arguments to backend 

542 

543 Returns: 

544 Dofmap as an :class:`dolfinx.graph.AdjacencyList` 

545 """ 

546 raise NotImplementedError("The openCARP backend cannot read dofmap.") 

547 

548 

549def read_dofs( 

550 filename: str | Path, 

551 comm: MPI.Comm, 

552 name: str, 

553 time: float, 

554 backend_args: dict[str, Any] | None, 

555) -> tuple[npt.NDArray[np.float32 | np.float64 | np.complex64 | np.complex128], int]: 

556 """Read the dofs (values) of a function with a given name from a given timestep. 

557 

558 Args: 

559 filename: Path to file to read from 

560 comm: MPI communicator used in storage 

561 name: Name of the function to read the dofs for 

562 time: Time stamp associated with the function to read 

563 backend_args: Arguments to backend 

564 

565 Returns: 

566 Contiguous sequence of degrees of freedom (with respect to input data) 

567 and the global starting point on the process. 

568 Process 0 has [0, M), process 1 [M, N), process 2 [N, O) etc. 

569 """ 

570 raise NotImplementedError("The openCARP backend cannot read dofs.") 

571 

572 

573def read_cell_perms( 

574 comm: MPI.Comm, filename: Path | str, backend_args: dict[str, Any] | None 

575) -> npt.NDArray[np.uint32]: 

576 """ 

577 Read cell permutation from file with given communicator, 

578 Split in continuous chunks based on number of cells in the input data. 

579 

580 Args: 

581 comm: MPI communicator used in storage 

582 filename: Path to file to read from 

583 backend_args: Arguments to backend 

584 

585 Returns: 

586 Contiguous sequence of permutations (with respect to input data) 

587 Process 0 has [0, M), process 1 [M, N), process 2 [N, O) etc. 

588 """ 

589 raise NotImplementedError("The openCARP backend cannot read cell perms.") 

590 

591 

592def write_function( 

593 filename: str | Path, 

594 comm: MPI.Comm, 

595 u: FunctionData, 

596 time: float, 

597 mode: FileMode, 

598 backend_args: dict[str, Any] | None = None, 

599): 

600 """Write a function to file. 

601 

602 Args: 

603 filename: Path to file to write to 

604 comm: MPI communicator used in storage 

605 u: Internal data structure for the function data to save to file 

606 time: Time stamp associated with function 

607 mode: File-mode to store the function 

608 backend_args: Arguments to backend 

609 """ 

610 raise NotImplementedError( 

611 "The openCARP backend cannot write functions. Use io4dolfinx.write_cell_data for fibers." 

612 ) 

613 

614 

615def read_legacy_mesh( 

616 filename: Path | str, comm: MPI.Comm, group: str 

617) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.floating], str | None]: 

618 """Read in the mesh topology, geometry and (optionally) cell type from a 

619 legacy DOLFIN HDF5-file. 

620 

621 Args: 

622 filename: Path to file to read from 

623 comm: MPI communicator used in storage 

624 group: Group in HDF5 file where mesh is stored 

625 

626 Returns: 

627 Tuple containing: 

628 - Topology as a (num_cells, num_vertices_per_cell) array of global vertex indices 

629 - Geometry as a (num_vertices, geometric_dimension) array of vertex coordinates 

630 - Cell type as a string (e.g. "tetrahedron") or None if not found 

631 """ 

632 raise NotImplementedError("The openCARP backend cannot read legacy meshes.") 

633 

634 

635def read_point_data( 

636 filename: Path | str, 

637 name: str, 

638 comm: MPI.Comm, 

639 time: float | str | None, 

640 backend_args: dict[str, Any] | None, 

641) -> tuple[np.ndarray, int]: 

642 """Read data from the nodes of a mesh. 

643 

644 Args: 

645 filename: Path to file 

646 name: Name of point data 

647 comm: Communicator to launch IO on. 

648 time: The time stamp 

649 backend_args: The backend arguments 

650 

651 Returns: 

652 Data local to process (contiguous, no mpi comm) and local start range 

653 """ 

654 raise NotImplementedError("The openCARP backend cannot read point data.") 

655 

656 

657def read_cell_data( 

658 filename: Path | str, 

659 name: str, 

660 comm: MPI.Comm, 

661 time: str | float | None, 

662 backend_args: dict[str, Any] | None, 

663) -> tuple[npt.NDArray[np.int64], np.ndarray]: 

664 """Read the fiber or sheet direction of each element from ``<base>.lon``. 

665 

666 Args: 

667 filename: Base name of the files, or the path of one of them 

668 name: ``"fiber"`` or ``"sheet"`` 

669 comm: Communicator to launch IO on. 

670 time: Not used 

671 backend_args: The backend arguments 

672 Returns: 

673 A tuple (topology, dofs) where topology contains the 

674 vertex indices of the cells, dofs the degrees of 

675 freedom within that cell. A 2D mesh gets the x- and y-components. 

676 """ 

677 lon = helpers.mesh_file(filename, ".lon") 

678 elem = helpers.mesh_file(filename, ".elem") 

679 check_file_exists(lon) 

680 check_file_exists(elem) 

681 num_directions = read_count(lon) 

682 if name not in helpers.direction_names[:num_directions]: 

683 raise KeyError( 

684 f"Could not find '{name}' in {lon}. " 

685 f"Available: {list(helpers.direction_names[:num_directions])}" 

686 ) 

687 

688 run_on_root(comm, lambda: check_row_count(lon, read_count(elem))) 

689 

690 def read(): 

691 local_range = compute_local_range(comm, read_count(elem)) 

692 elem_type, cells, _ = helpers.read_elem(elem, local_range) 

693 rows = read_rows(lon, 3 * num_directions, local_range, dtype=np.float64) 

694 return elem_type, cells, rows 

695 

696 elem_type, cells, rows = run_on_all(comm, read) 

697 column = 3 * helpers.direction_names.index(name) 

698 dofs = rows[:, column : column + helpers.element_tdim[elem_type]] 

699 cells = cells[:, helpers.opencarp_to_dolfinx[elem_type]] 

700 return cells, np.ascontiguousarray(dofs) 

701 

702 

703def read_function_names( 

704 filename: Path | str, comm: MPI.Comm, backend_args: dict[str, Any] | None 

705) -> list[str]: 

706 """Read the names of the directions in ``<base>.lon``. 

707 

708 Args: 

709 filename: Base name of the files, or the path of one of them 

710 comm: MPI communicator to launch IO on. 

711 backend_args: Arguments to backend 

712 

713 Returns: 

714 ``["fiber"]`` or ``["fiber", "sheet"]`` 

715 """ 

716 lon = helpers.mesh_file(filename, ".lon") 

717 check_file_exists(lon) 

718 return list(helpers.direction_names[: read_count(lon)]) 

719 

720 

721def write_data( 

722 filename: Path | str, 

723 array_data: ArrayData, 

724 comm: MPI.Comm, 

725 time: str | float | None, 

726 mode: FileMode, 

727 backend_args: dict[str, Any] | None, 

728): 

729 """Write a direction per element to ``<base>.lon``, normalised to unit length. 

730 

731 2D directions get ``z = 0``. 

732 

733 Writing with :attr:`FileMode.write` gives the fiber direction. Writing again 

734 with :attr:`FileMode.append` adds the sheet direction. 

735 

736 Args: 

737 filename: Base name of the files, or the path of one of them 

738 array_data: Cell data in the ordering the mesh was written in, see the 

739 ``on_input_mesh`` argument of :func:`io4dolfinx.write_cell_data` 

740 comm: MPI communicator to open the file with 

741 time: Not used 

742 mode: Write for the fiber, append for the sheet direction 

743 backend_args: The backend arguments 

744 """ 

745 if array_data.type != "Cell": 

746 raise NotImplementedError( 

747 "The openCARP backend can only write cell data (fibers and sheets)." 

748 ) 

749 if np.iscomplexobj(array_data.values): 

750 raise NotImplementedError("openCARP directions are real, got complex cell data.") 

751 num_cells, num_components = array_data.global_shape 

752 if num_components not in (2, 3): 

753 raise ValueError(f"Expected a 2D or 3D vector per cell, got {num_components} components.") 

754 directions = gather_rows(comm, array_data.values, array_data.local_range, num_cells) 

755 lon = helpers.mesh_file(filename, ".lon") 

756 elem = helpers.mesh_file(filename, ".elem") 

757 

758 def write(): 

759 assert directions is not None 

760 check_file_exists(elem) 

761 if (num_elements := read_count(elem)) != num_cells: 

762 raise ValueError(f"Got data for {num_cells} cells, but {elem} has {num_elements}.") 

763 if num_components < (tdim := helpers.element_tdim[helpers.read_elem_type(elem)]): 

764 raise ValueError(f"Expected a {tdim}D vector per cell, got {num_components}D.") 

765 # openCARP directions are 3D, also for 2D meshes 

766 vectors = np.zeros((num_cells, 3), dtype=np.float64) 

767 vectors[:, :num_components] = directions 

768 norms = np.linalg.norm(vectors, axis=1) 

769 if np.any(norms == 0): 

770 raise ValueError(f"{np.count_nonzero(norms == 0)} cells have a zero direction.") 

771 rows = vectors / norms[:, None] 

772 

773 if mode == FileMode.append: 

774 check_file_exists(lon) 

775 if read_count(lon) != 1: 

776 raise ValueError(f"{lon} already holds fibers and sheets.") 

777 check_row_count(lon, num_cells) 

778 fibers = read_rows(lon, 3, (0, num_cells), dtype=np.float64) 

779 rows = np.hstack([fibers, rows]) 

780 write_rows(lon, [str(rows.shape[1] // 3)], rows, helpers.float_format) 

781 

782 run_on_root(comm, write)