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

450 statements  

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

1""" 

2Gmsh interface to io4dolfinx. 

3 

4Reads and writes Gmsh ``.msh`` files (MSH 2.2 and 4.1, ASCII and binary) through the 

5Gmsh Python API, reusing :mod:`dolfinx.io.gmsh` for the geometry and the topology. All 

6file access happens on rank 0, and DOLFINx 0.11 or later is required. Complete Lagrange 

7elements of any order are supported: the node ordering is computed from the reference 

8coordinates Gmsh gives for each element type, so it is not limited to the orders of 

9``dolfinx.io.gmsh``. The incomplete 8-node quadrilateral and 20-node hexahedron are read 

10as serendipity geometry, which requires the main branch of DOLFINx. 

11 

12In DOLFINx terms: 

13 

14- As in :func:`dolfinx.io.gmsh.model_to_mesh`, the cells are the elements of the 

15 highest dimension in a physical group, and every cell is in exactly one physical 

16 group. Node ``i`` has node tag ``i + 1``. An MSH file holds a single mesh, so meshes 

17 are not time dependent. 

18- Point and cell data are post-processing views (``$NodeData``/``$ElementData``) keyed 

19 by node and element tags. The steps of a view are its time series. Complex data is 

20 split into the views ``real_{name}`` and ``imag_{name}``, as in 

21 :class:`dolfinx.io.XDMFFile`. 

22- Mesh tags are physical groups, with the physical tag as the tag value. 

23 

24SPDX License identifier: MIT 

25 

26Copyright: Jørgen S. Dokken and Simula Research Laboratory 

27""" 

28 

29import functools 

30from pathlib import Path 

31from typing import Any, Callable, TypeVar 

32 

33from mpi4py import MPI 

34 

35import basix 

36import dolfinx 

37import fenicsx_compat 

38import numpy as np 

39import numpy.typing as npt 

40from dolfinx.io.gmsh import cell_perm_array, extract_geometry 

41 

42try: 

43 import gmsh 

44except ImportError: 

45 raise ModuleNotFoundError("The gmsh-backend requires gmsh") 

46 

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

48from ...utils import check_file_exists, codim_names, coordinate_element, serendipity_num_nodes 

49from .. import FileMode, ReadMode 

50 

51read_mode = ReadMode.serial 

52 

53# Gmsh options changed by this backend, restored if Gmsh was initialized by the caller 

54_options = ("General.Terminal", "Mesh.Binary", "Mesh.SaveAll", "PostProcessing.SaveMesh") 

55 

56Local = TypeVar("Local") 

57Shared = TypeVar("Shared") 

58 

59# Gmsh element family, as named by getElementType, of each DOLFINx cell type 

60_gmsh_families = { 

61 "point": "Point", 

62 "interval": "Line", 

63 "triangle": "Triangle", 

64 "quadrilateral": "Quadrangle", 

65 "tetrahedron": "Tetrahedron", 

66 "hexahedron": "Hexahedron", 

67 "prism": "Prism", 

68 "pyramid": "Pyramid", 

69} 

70 

71 

72@functools.cache 

73def _reference_map(cell_type: str) -> npt.NDArray[np.float64]: 

74 """Find the affine map from Gmsh's reference cell to basix's. 

75 

76 The map is fitted to the reference vertices each library reports, paired by the 

77 first-order node ordering of :mod:`dolfinx.io.gmsh`, so it follows a change of either 

78 reference cell. Must be called in a Gmsh session. 

79 

80 Args: 

81 cell_type: DOLFINx cell type 

82 

83 Returns: 

84 Matrix ``M`` such that ``np.hstack([X, 1]) @ M`` maps Gmsh reference points ``X``, 

85 one per row, to basix reference points 

86 

87 Raises: 

88 RuntimeError: If no affine map relates the reference cells. 

89 """ 

90 gmsh_type = gmsh.model.mesh.getElementType(_gmsh_families[cell_type], 1) 

91 _, dim, _, num_vertices, coordinates, _ = gmsh.model.mesh.getElementProperties(gmsh_type) 

92 perm = cell_perm_array(dolfinx.mesh.to_type(cell_type), num_vertices) 

93 X_gmsh = np.reshape(coordinates, (num_vertices, dim))[perm] 

94 # DOLFINx numbers vertices as basix does 

95 X_basix = basix.geometry(basix.CellType[cell_type]) 

96 A = np.hstack([X_gmsh, np.ones((num_vertices, 1))]) 

97 M = np.linalg.lstsq(A, X_basix, rcond=None)[0] 

98 if not np.allclose(A @ M, X_basix, atol=1e-12): 

99 raise RuntimeError(f"Gmsh's reference {cell_type} is not an affine image of basix's.") 

100 return M 

101 

102 

103def _scratch_element_nodes(gmsh_type: int, order: int) -> tuple[int, int, npt.NDArray[np.float64]]: 

104 """Find the reference node coordinates of a prism that Gmsh cannot describe. 

105 

106 Gmsh cannot report the properties of prisms of order 3 and above, but it can create 

107 them. A first-order prism on Gmsh's reference vertices is raised to the order in a 

108 scratch model, which places the nodes at their reference coordinates. Must be called 

109 in a Gmsh session; the current model is restored. 

110 

111 Args: 

112 gmsh_type: Gmsh element type of the prism 

113 order: Order of the prism 

114 

115 Returns: 

116 Tuple of the topological dimension, the order and the reference coordinates of the 

117 nodes, of shape ``(num_nodes, dim)`` 

118 """ 

119 first_order = gmsh.model.mesh.getElementType("Prism", 1) 

120 _, dim, _, num_vertices, vertices, _ = gmsh.model.mesh.getElementProperties(first_order) 

121 x = np.zeros((num_vertices, 3)) 

122 x[:, :dim] = np.reshape(vertices, (num_vertices, dim)) 

123 current = gmsh.model.getCurrent() 

124 gmsh.model.add("io4dolfinx_reference_element") 

125 try: 

126 entity = gmsh.model.addDiscreteEntity(dim) 

127 tags = np.arange(1, num_vertices + 1) 

128 gmsh.model.mesh.addNodes(dim, entity, tags, x.reshape(-1)) 

129 gmsh.model.mesh.addElementsByType(entity, first_order, [1], tags) 

130 gmsh.model.mesh.setOrder(order) 

131 element_types, _, element_nodes = gmsh.model.mesh.getElements(dim, entity) 

132 node_tags, coordinates, _ = gmsh.model.mesh.getNodes() 

133 finally: 

134 gmsh.model.remove() 

135 gmsh.model.setCurrent(current) 

136 if list(element_types) != [gmsh_type]: 

137 raise RuntimeError(f"Gmsh did not create a reference element of type {gmsh_type}.") 

138 position = dict(zip(node_tags, np.reshape(coordinates, (-1, 3)))) 

139 nodes = np.array([position[tag][:dim] for tag in element_nodes[0]]) 

140 return dim, order, nodes 

141 

142 

143@functools.cache 

144def _element( 

145 gmsh_type: int, 

146) -> tuple[int, tuple[str, int, npt.NDArray[np.int64], bool] | None]: 

147 """Find the DOLFINx cell and node ordering of a Gmsh element type. 

148 

149 The node ordering matches the reference coordinates of the Gmsh nodes with the nodes of 

150 the DOLFINx coordinate element, so Lagrange elements of any order work, as do the 

151 8-node quadrilateral and 20-node hexahedron, as serendipity geometry. Gmsh cannot give 

152 the reference coordinates of prisms of order 3 and above, so for those they are taken 

153 from a reference prism Gmsh creates, see :func:`_scratch_element_nodes`. Must be 

154 called in a Gmsh session. 

155 

156 Args: 

157 gmsh_type: Gmsh element type 

158 

159 Returns: 

160 Tuple containing: 

161 - The topological dimension of the element 

162 - ``None`` if DOLFINx has no coordinate element for it, e.g. for an incomplete 

163 element other than the two above, otherwise a tuple of the DOLFINx cell type, 

164 the degree, the permutation ``perm`` such that ``gmsh_nodes[perm]`` are the 

165 nodes in DOLFINx order, and whether the geometry is serendipity 

166 

167 Raises: 

168 RuntimeError: If Gmsh does not know the element type. 

169 """ 

170 # Gmsh cannot describe prisms of order 3 to 9, and a failed Gmsh call makes every later 

171 # setOrder in the session do nothing, so these are recognised without failing calls 

172 prisms = {gmsh.model.mesh.getElementType("Prism", k): k for k in range(3, 10)} 

173 if gmsh_type in prisms: 

174 dim, order, nodes = _scratch_element_nodes(gmsh_type, prisms[gmsh_type]) 

175 cell_type = "prism" 

176 name, num_nodes, coordinates = f"type {gmsh_type}", len(nodes), nodes.reshape(-1) 

177 else: 

178 name, dim, order, num_nodes, coordinates, _ = gmsh.model.mesh.getElementProperties( 

179 gmsh_type 

180 ) 

181 # getElementProperties names quadrilaterals "Quadrilateral", getElementType "Quadrangle" 

182 families = {f: c for c, f in _gmsh_families.items()} | {"Quadrilateral": "quadrilateral"} 

183 if (cell := families.get(name.split()[0])) is None: 

184 return dim, None 

185 cell_type = cell 

186 if cell_type == "point": 

187 return dim, ("point", 0, np.zeros(1, dtype=np.int64), False) 

188 serendipity = serendipity_num_nodes.get(cell_type) == num_nodes 

189 # Lagrange geometries are equispaced in Gmsh 

190 lvar = int(basix.LagrangeVariant.equispaced) 

191 points = coordinate_element( 

192 cell_type, order, lvar, serendipity, np.float64 

193 ).basix_element.points 

194 if len(points) != num_nodes: 

195 # Other incomplete elements, e.g. the 12-node quadrilateral 

196 return dim, None 

197 X = np.hstack([np.reshape(coordinates, (num_nodes, dim)), np.ones((num_nodes, 1))]) 

198 X = X @ _reference_map(cell_type) 

199 distance = np.linalg.norm(points[:, None, :] - X[None, :, :], axis=2) 

200 perm = np.argmin(distance, axis=1) 

201 if not np.allclose(distance[np.arange(num_nodes), perm], 0, atol=1e-10): 

202 raise RuntimeError(f"The nodes of Gmsh element '{name}' do not match DOLFINx's.") 

203 return dim, (cell_type, int(order), perm.astype(np.int64), serendipity) 

204 

205 

206def _gmsh_type(cell_type: str, degree: int) -> int: 

207 """Find the Gmsh element type of a DOLFINx cell, the inverse of :func:`_element`. 

208 

209 Must be called in a Gmsh session. 

210 

211 Args: 

212 cell_type: DOLFINx cell type 

213 degree: Degree of the Lagrange element, 0 for a point 

214 

215 Returns: 

216 The Gmsh element type 

217 

218 Raises: 

219 NotImplementedError: If Gmsh has no complete Lagrange element for the cell. 

220 """ 

221 try: 

222 gmsh_type = gmsh.model.mesh.getElementType(_gmsh_families[cell_type], degree) 

223 element = _element(gmsh_type)[1] 

224 except Exception as e: 

225 raise NotImplementedError( 

226 f"Gmsh has no element for a {cell_type} of degree {degree}." 

227 ) from e 

228 if element is None or element[:2] != (cell_type, degree) or element[3]: 

229 raise NotImplementedError(f"Gmsh has no element for a {cell_type} of degree {degree}.") 

230 return gmsh_type 

231 

232 

233def _run_on_root( 

234 comm: MPI.Comm, func: Callable[[list[int]], tuple[Local, Shared]] 

235) -> tuple[Local | None, Shared]: 

236 """Run a function in a Gmsh session on rank 0 and share its outcome with all ranks. 

237 

238 If Gmsh is already initialized, e.g. by the caller, the function runs in a new model, 

239 which is removed afterwards together with the views it created, and the previous 

240 model and options are restored. Otherwise Gmsh is initialized and finalized around it. 

241 

242 Args: 

243 comm: MPI communicator. Collective on all ranks. 

244 func: Function to run on rank 0. It takes the tags of the views that existed 

245 before the session, which do not belong to the file, and returns a tuple of 

246 data kept on rank 0 and data broadcast to all ranks. 

247 

248 Returns: 

249 Tuple containing: 

250 - The first output of ``func`` on rank 0, ``None`` on other ranks 

251 - The second output of ``func`` on all ranks 

252 

253 Raises: 

254 NotImplementedError: If DOLFINx is older than 0.11. 

255 Exception: An exception raised by ``func`` is raised on all ranks. 

256 """ 

257 if fenicsx_compat.before("0.11.0.dev0"): 

258 raise NotImplementedError("The gmsh backend requires DOLFINx 0.11 or later.") 

259 

260 result: Local | None = None 

261 shared: Shared | None = None 

262 error: Exception | None = None 

263 if comm.rank == 0: 

264 initialized = gmsh.isInitialized() 

265 if initialized: 

266 previous_model = gmsh.model.getCurrent() 

267 previous_options = {option: gmsh.option.getNumber(option) for option in _options} 

268 # Views are global in gmsh, not per model, so existing ones must be skipped and kept 

269 preexisting_views = list(gmsh.view.getTags()) 

270 gmsh.model.add("io4dolfinx") 

271 else: 

272 gmsh.initialize(interruptible=False) 

273 preexisting_views = [] 

274 try: 

275 gmsh.option.setNumber("General.Terminal", 0) 

276 result, shared = func(preexisting_views) 

277 except Exception as e: 

278 error = e 

279 finally: 

280 if initialized: 

281 for view in gmsh.view.getTags(): 

282 if view not in preexisting_views: 

283 gmsh.view.remove(view) 

284 gmsh.model.remove() 

285 gmsh.model.setCurrent(previous_model) 

286 for option, value in previous_options.items(): 

287 gmsh.option.setNumber(option, value) 

288 else: 

289 gmsh.finalize() 

290 error, shared = comm.bcast((error, shared), root=0) 

291 if error is not None: 

292 raise error 

293 return result, shared # type: ignore[return-value] 

294 

295 

296def _find_view( 

297 name: str, preexisting_views: list[int] 

298) -> tuple[list[int], npt.NDArray[np.float64]] | None: 

299 """Find the views of the current Gmsh session holding the data with a given name. 

300 

301 A gmsh view holds all time steps of one field, each step storing its time. 

302 Complex data is stored as two views, ``real_{name}`` and ``imag_{name}``, as 

303 :class:`dolfinx.io.XDMFFile` does. 

304 

305 Args: 

306 name: Name of the data 

307 preexisting_views: Tags of the views that do not belong to the file, which are skipped 

308 

309 Returns: 

310 ``None`` if there is no such data, otherwise a tuple containing: 

311 - The view tags, ``[view]`` for real data and ``[real, imag]`` for complex data 

312 - The time of each step of the views 

313 """ 

314 views = { 

315 gmsh.view.option.getString(view, "Name"): view 

316 for view in gmsh.view.getTags() 

317 if view not in preexisting_views 

318 } 

319 real, imag = f"real_{name}", f"imag_{name}" 

320 if name in views: 

321 found = [views[name]] 

322 elif real in views and imag in views: 

323 found = [views[real], views[imag]] 

324 elif real in views or imag in views: 

325 raise RuntimeError( 

326 f"Found only one part of complex data '{name}', expected '{real}' and '{imag}'." 

327 ) 

328 else: 

329 return None 

330 num_steps = int(gmsh.view.option.getNumber(found[0], "NbTimeStep")) 

331 times = [gmsh.view.getModelData(found[0], step)[3] for step in range(num_steps)] 

332 return found, np.array(times, dtype=np.float64) 

333 

334 

335def _physical_elements() -> dict[int, tuple[np.ndarray, np.ndarray, np.ndarray]]: 

336 """Get the elements of each physical group of the current Gmsh model, by element type. 

337 

338 As :func:`dolfinx.io.gmsh.extract_topology_and_markers`, but without asking Gmsh for 

339 element properties, which it cannot give for prisms of order 3 and above (DOLFINx 

340 0.11 asks for them). An element in several physical groups appears once per group. 

341 

342 Returns: 

343 Map from Gmsh element type to a tuple of the element tags, the element nodes as 

344 zero-based node indices in Gmsh ordering, of shape 

345 ``(num_elements, num_nodes_per_element)``, and the physical tag of each element 

346 """ 

347 found: dict[int, list[tuple[np.ndarray, np.ndarray, np.ndarray]]] = {} 

348 for dim, physical_tag in gmsh.model.getPhysicalGroups(): 

349 for entity in gmsh.model.getEntitiesForPhysicalGroup(dim, physical_tag): 

350 types, element_tags, element_nodes = gmsh.model.mesh.getElements(dim, tag=entity) 

351 for gmsh_type, tags, nodes in zip(types, element_tags, element_nodes, strict=True): 

352 if len(tags) == 0: 

353 continue 

354 # Node i has node tag i + 1 

355 topology = np.reshape(nodes, (len(tags), -1)).astype(np.int64) - 1 

356 markers = np.full(len(tags), physical_tag, dtype=np.int32) 

357 found.setdefault(int(gmsh_type), []).append((tags, topology, markers)) 

358 return { 

359 gmsh_type: ( 

360 np.hstack([t for t, _, _ in parts]).astype(np.int64), 

361 np.vstack([n for _, n, _ in parts]), 

362 np.hstack([m for _, _, m in parts]), 

363 ) 

364 for gmsh_type, parts in found.items() 

365 } 

366 

367 

368def _tagged_entities() -> dict[ 

369 int, 

370 tuple[npt.NDArray[np.int64], npt.NDArray[np.int64], npt.NDArray[np.int32], str, int, bool] 

371 | None, 

372]: 

373 """Get the elements in physical groups of the current Gmsh model, by dimension. 

374 

375 As in :func:`dolfinx.io.gmsh.model_to_mesh`, the highest dimension holds the cells, and 

376 an element in several physical groups appears once per group. 

377 

378 Returns: 

379 Map from topological dimension to ``None`` if the elements of that dimension are 

380 of several types or have no DOLFINx coordinate element, otherwise to a tuple 

381 containing: 

382 - The element tags, sorted 

383 - The element nodes as zero-based node indices in DOLFINx ordering, of shape 

384 ``(num_elements, num_nodes_per_element)``, one row per element tag 

385 - The physical tag of each element 

386 - The DOLFINx cell type of the elements 

387 - The degree of the elements 

388 - Whether the elements have serendipity geometry 

389 """ 

390 topologies = _physical_elements() 

391 if len(topologies) == 0: 

392 raise ValueError("No physical groups in the Gmsh model.") 

393 types_by_dim: dict[int, list[int]] = {} 

394 for gmsh_type in topologies: 

395 types_by_dim.setdefault(_element(gmsh_type)[0], []).append(gmsh_type) 

396 

397 entities: dict[int, Any] = {} 

398 for dim, types in types_by_dim.items(): 

399 if len(types) > 1 or (element := _element(types[0])[1]) is None: 

400 entities[dim] = None 

401 continue 

402 cell_name, degree, perm, serendipity = element 

403 tags, nodes, values = topologies[types[0]] 

404 order = np.argsort(tags, kind="stable") 

405 entities[dim] = ( 

406 tags[order], 

407 nodes[order][:, perm], 

408 values[order], 

409 cell_name, 

410 degree, 

411 serendipity, 

412 ) 

413 return entities 

414 

415 

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

417 """Get default backend arguments given a set of input arguments. 

418 

419 Args: 

420 arguments: Input backend arguments 

421 

422 Returns: 

423 The arguments, with defaults for: 

424 - ``"gdim"``: Geometric dimension of a mesh read from file, ``3`` as in 

425 :func:`dolfinx.io.gmsh.read_from_msh` 

426 - ``"dtype"``: Floating point type of the coordinates and data read from file, 

427 ``np.float64`` 

428 - ``"binary"``: Write binary instead of ASCII MSH. ``None`` keeps the encoding 

429 of an existing file and writes a new one as ASCII. 

430 """ 

431 args: dict[str, Any] = {"gdim": 3, "dtype": np.float64, "binary": None} 

432 args.update(arguments or {}) 

433 return args 

434 

435 

436def write_attributes( 

437 filename: Path | str, 

438 comm: MPI.Comm, 

439 name: str, 

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

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

442): 

443 """Write attributes to file. 

444 

445 Args: 

446 filename: Path to file to write to 

447 comm: MPI communicator used in storage 

448 name: Name of the attribute group 

449 attributes: Dictionary of attributes to write 

450 backend_args: Arguments to backend 

451 """ 

452 raise NotImplementedError("The gmsh backend cannot write attributes.") 

453 

454 

455def read_attributes( 

456 filename: Path | str, 

457 comm: MPI.Comm, 

458 name: str, 

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

460) -> dict[str, Any]: 

461 """Read attributes from file. 

462 

463 Args: 

464 filename: Path to file to read from 

465 comm: MPI communicator used in storage 

466 name: Name of the attribute group 

467 backend_args: Arguments to backend 

468 

469 Returns: 

470 Dictionary of attributes read from file 

471 """ 

472 raise NotImplementedError("The gmsh backend cannot read attributes.") 

473 

474 

475def read_timestamps( 

476 filename: Path | str, 

477 comm: MPI.Comm, 

478 function_name: str, 

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

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

481 """Read the times of the steps of point or cell data. 

482 

483 Args: 

484 filename: Path to file to read from 

485 comm: MPI communicator used in storage 

486 function_name: Name of the point or cell data 

487 backend_args: Arguments to backend 

488 

489 Returns: 

490 The time of each step, on all ranks 

491 """ 

492 check_file_exists(filename) 

493 

494 def read(preexisting_views: list[int]) -> tuple[None, npt.NDArray[np.float64]]: 

495 gmsh.merge(str(filename)) 

496 if (found := _find_view(function_name, preexisting_views)) is None: 

497 raise KeyError(f"Could not find data '{function_name}' in {filename}.") 

498 return None, found[1] 

499 

500 return _run_on_root(comm, read)[1] 

501 

502 

503def read_function_names( 

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

505) -> list[str]: 

506 """Read the names of all point and cell data in a file. 

507 

508 Args: 

509 filename: Path to file 

510 comm: MPI communicator to launch IO on. 

511 backend_args: Arguments to backend 

512 

513 Returns: 

514 The names of the views in the file, on all ranks. A complex pair of views 

515 ``real_{name}`` and ``imag_{name}`` is listed as ``name``. 

516 """ 

517 check_file_exists(filename) 

518 

519 def read(preexisting_views: list[int]) -> tuple[None, list[str]]: 

520 gmsh.merge(str(filename)) 

521 views = [view for view in gmsh.view.getTags() if view not in preexisting_views] 

522 names = [gmsh.view.option.getString(view, "Name") for view in views] 

523 complex_names = {n[5:] for n in names if n.startswith("real_") and f"imag_{n[5:]}" in names} 

524 functions = [ 

525 n[5:] if n.startswith(("real_", "imag_")) and n[5:] in complex_names else n 

526 for n in names 

527 ] 

528 return None, list(dict.fromkeys(functions)) 

529 

530 return _run_on_root(comm, read)[1] 

531 

532 

533def write_mesh( 

534 filename: Path | str, 

535 comm: MPI.Comm, 

536 mesh: MeshData, 

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

538 mode: FileMode = FileMode.write, 

539 time: float = 0.0, 

540): 

541 """Write a mesh to a Gmsh file. 

542 

543 Nodes and cells get the tag one above their global index. The cells form a single 

544 entity in the physical group with tag 1, the default cell marker, as every cell must 

545 be in a physical group (see :func:`dolfinx.io.gmsh.model_to_mesh`). Cell tags written 

546 with :func:`write_meshtags` replace it. 

547 

548 Args: 

549 filename: Path to file to write to, with suffix ``.msh`` 

550 comm: MPI communicator used in storage 

551 mesh: Internal data structure for the mesh data to save to file 

552 backend_args: Arguments to backend, ``"binary"`` selects binary MSH 

553 mode: Only :attr:`FileMode.write`, as an MSH file holds one mesh 

554 time: Ignored, as an MSH file holds one mesh 

555 """ 

556 if mode != FileMode.write: 

557 raise NotImplementedError("The gmsh backend writes a single mesh per file.") 

558 if Path(filename).suffix != ".msh": 

559 raise ValueError(f"Expected a filename with suffix .msh, got {filename}.") 

560 if mesh.degree > 2 and mesh.lagrange_variant != int(basix.LagrangeVariant.equispaced): 

561 raise NotImplementedError("Gmsh only supports equispaced Lagrange geometries.") 

562 backend_args = get_default_backend_args(backend_args) 

563 

564 # Rank order is global index order 

565 nodes = comm.gather(mesh.local_geometry, root=0) 

566 cells = comm.gather(mesh.local_topology, root=0) 

567 

568 def write(preexisting_views: list[int]) -> tuple[None, None]: 

569 assert nodes is not None and cells is not None 

570 x = np.vstack(nodes) 

571 x_3d = np.zeros((x.shape[0], 3), dtype=np.float64) 

572 x_3d[:, : x.shape[1]] = x 

573 topology = np.vstack(cells) 

574 gmsh_type = _gmsh_type(mesh.cell_type, mesh.degree) 

575 perm = _element(gmsh_type)[1][2] # type: ignore[index] 

576 if topology.shape[1] != len(perm): 

577 raise NotImplementedError("The gmsh backend writes Lagrange geometries only.") 

578 gmsh_topology = np.empty_like(topology) 

579 gmsh_topology[:, perm] = topology 

580 

581 tdim = dolfinx.mesh.cell_dim(dolfinx.mesh.to_type(mesh.cell_type)) 

582 gmsh.model.addDiscreteEntity(tdim, 1) 

583 gmsh.model.mesh.addNodes(tdim, 1, np.arange(1, x.shape[0] + 1), x_3d.reshape(-1)) 

584 gmsh.model.mesh.addElementsByType( 

585 1, 

586 gmsh_type, 

587 np.arange(1, topology.shape[0] + 1), 

588 gmsh_topology.reshape(-1) + 1, 

589 ) 

590 gmsh.model.addPhysicalGroup(tdim, [1], 1) 

591 gmsh.option.setNumber("Mesh.Binary", int(bool(backend_args["binary"]))) 

592 gmsh.option.setNumber("Mesh.SaveAll", 1) 

593 gmsh.write(str(filename)) 

594 return None, None 

595 

596 _run_on_root(comm, write) 

597 

598 

599def read_mesh_data( 

600 filename: Path | str, 

601 comm: MPI.Comm, 

602 time: str | float | None = None, 

603 read_from_partition: bool = False, 

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

605) -> ReadMeshData: 

606 """Read mesh data from a Gmsh file. 

607 

608 As in :func:`dolfinx.io.gmsh.model_to_mesh`, the cells are the elements of the 

609 highest dimension in a physical group, and every cell must be in exactly one physical 

610 group. The cells must be of one type, and node tags contiguous. All data is read on 

611 rank 0. 

612 

613 Args: 

614 filename: Path to file to read from 

615 comm: MPI communicator to distribute the mesh over 

616 time: Ignored, as an MSH file holds one mesh 

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

618 backend_args: Arguments to backend, see :func:`get_default_backend_args` 

619 

620 Returns: 

621 Internal data structure for the mesh data read from file 

622 """ 

623 if read_from_partition: 

624 raise NotImplementedError("The gmsh backend cannot read partitioning data.") 

625 check_file_exists(filename) 

626 backend_args = get_default_backend_args(backend_args) 

627 gdim = backend_args["gdim"] 

628 

629 def read( 

630 preexisting_views: list[int], 

631 ) -> tuple[tuple[npt.NDArray[np.float64], npt.NDArray[np.int64]], tuple[str, int, int, bool]]: 

632 gmsh.merge(str(filename)) 

633 x = extract_geometry(gmsh.model)[:, :gdim] 

634 tagged = _tagged_entities() 

635 tdim = max(tagged) 

636 if (cell_data := tagged[tdim]) is None: 

637 raise NotImplementedError(f"Mixed or unsupported cell types in {filename}.") 

638 tags, cells, _, cell_type, degree, serendipity = cell_data 

639 num_cells = sum(len(t) for t in gmsh.model.mesh.getElements(dim=tdim, tag=-1)[1]) 

640 if len(tags) != num_cells or len(np.unique(tags)) != len(tags): 

641 raise ValueError( 

642 f"All cells are expected to be in exactly one physical group, as in " 

643 f"dolfinx.io.gmsh.model_to_mesh; found {len(tags)} tags for {num_cells} cells." 

644 ) 

645 return (x, cells), (cell_type, degree, cells.shape[1], serendipity) 

646 

647 local, (cell_type, degree, num_nodes_per_cell, serendipity) = _run_on_root(comm, read) 

648 if cell_type == "prism" and degree > 2 and fenicsx_compat.before("0.12.0.dev0"): 

649 # From degree 3, both the triangle and the quadrilateral faces of a prism hold nodes, 

650 # which DOLFINx 0.11 cannot build a geometry for 

651 raise NotImplementedError( 

652 f"Prisms of degree {degree} require DOLFINx 0.12 or later; DOLFINx " 

653 f"{dolfinx.__version__} reads prisms up to degree 2." 

654 ) 

655 if local is None: 

656 x = np.zeros((0, gdim), dtype=np.float64) 

657 cells = np.zeros((0, num_nodes_per_cell), dtype=np.int64) 

658 else: 

659 x, cells = local 

660 return ReadMeshData( 

661 cells=cells, 

662 cell_type=cell_type, 

663 x=x.astype(backend_args["dtype"]), 

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

665 degree=degree, 

666 serendipity=serendipity, 

667 ) 

668 

669 

670def write_meshtags( 

671 filename: str | Path, 

672 comm: MPI.Comm, 

673 data: MeshTagsData, 

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

675): 

676 """Write mesh tags to a Gmsh file as physical groups. 

677 

678 Each tag value becomes a physical group with the value as tag, named 

679 ``f"{data.name}_{value}"``. Gmsh physical tags are positive and unique per 

680 dimension, so tag values must be positive. 

681 

682 Cell tags replace the marker of the cells they cover, moving them to the physical 

683 group of their value, while other cells keep their marker, e.g. the default marker 1 

684 of :func:`write_mesh`. Markers no cell has any more are removed. Entities of lower 

685 dimension are added as new elements, and only one set of mesh tags can be written 

686 per lower dimension. 

687 

688 Args: 

689 filename: Path to file to write to, holding a mesh written with 

690 :func:`write_mesh` 

691 comm: MPI communicator used in storage 

692 data: Internal data structure for the mesh tags to save to file 

693 backend_args: Arguments to backend, ``"binary"`` selects binary MSH 

694 """ 

695 check_file_exists(filename) 

696 backend_args = get_default_backend_args(backend_args) 

697 indices = comm.gather(data.indices, root=0) 

698 values = comm.gather(data.values, root=0) 

699 

700 def write(preexisting_views: list[int]) -> tuple[None, None]: 

701 assert indices is not None and values is not None 

702 entities = np.vstack(indices).astype(np.int64) 

703 tag_values = np.hstack(values).astype(np.int32) 

704 if np.any(tag_values <= 0): 

705 raise ValueError(f"Gmsh physical tags must be positive, got {np.unique(tag_values)}.") 

706 if (binary := backend_args["binary"]) is None: 

707 # The second line of an MSH file is "version file-type data-size" 

708 with open(filename, "rb") as file: 

709 file.readline() 

710 binary = file.readline().split()[1] == b"1" 

711 

712 gmsh.merge(str(filename)) 

713 tagged = _tagged_entities() 

714 tdim = max(tagged) 

715 if (cell_data := tagged[tdim]) is None: 

716 raise NotImplementedError(f"Mixed or unsupported cell types in {filename}.") 

717 cell_tags, cells, _, _, degree, _ = cell_data 

718 dim = data.dim 

719 groups = [tag for d, tag in gmsh.model.getPhysicalGroups() if d == dim] 

720 if dim < tdim and len(groups) > 0: 

721 raise NotImplementedError( 

722 f"{filename} already has physical groups of dimension {dim}, and only one " 

723 "set of mesh tags can be written per dimension below the cells." 

724 ) 

725 

726 assert data.cell_type is not None 

727 gmsh_type = _gmsh_type(data.cell_type, 0 if data.cell_type == "point" else degree) 

728 gmsh_entities = np.empty_like(entities) 

729 gmsh_entities[:, _element(gmsh_type)[1][2]] = entities # type: ignore[index] 

730 

731 if dim == tdim: 

732 # Find the element tag of each tagged cell by matching node sets 

733 _, inverse = np.unique( 

734 np.sort(np.vstack([cells, entities]), axis=1), axis=0, return_inverse=True 

735 ) 

736 inverse = inverse.reshape(-1) 

737 cell_position = np.empty(inverse.max() + 1, dtype=np.int64) 

738 cell_position[inverse[: len(cells)]] = np.arange(len(cells)) 

739 element_tags = cell_tags[cell_position[inverse[len(cells) :]]] 

740 # Gmsh rejects removing elements an entity does not hold 

741 for d, entity in gmsh.model.getEntities(tdim): 

742 entity_tags = gmsh.model.mesh.getElements(d, entity)[1] 

743 held = np.intersect1d(np.hstack([*entity_tags, []]), element_tags) 

744 if len(held) > 0: 

745 gmsh.model.mesh.removeElements(d, entity, held.astype(np.int64)) 

746 else: 

747 first = gmsh.model.mesh.getMaxElementTag() + 1 

748 element_tags = np.arange(first, first + len(entities), dtype=np.int64) 

749 

750 for value in np.unique(tag_values): 

751 selected = tag_values == value 

752 if value in groups: 

753 # A marker the cells already have, e.g. the default marker 1 

754 entity = gmsh.model.getEntitiesForPhysicalGroup(dim, int(value))[0] 

755 gmsh.model.setPhysicalName(dim, int(value), f"{data.name}_{value}") 

756 else: 

757 entity = gmsh.model.addDiscreteEntity(dim) 

758 gmsh.model.addPhysicalGroup(dim, [entity], int(value), f"{data.name}_{value}") 

759 gmsh.model.mesh.addElementsByType( 

760 entity, gmsh_type, element_tags[selected], gmsh_entities[selected].reshape(-1) + 1 

761 ) 

762 if dim == tdim: 

763 # Remove the markers no cell has any more 

764 for tag in groups: 

765 group_entities = gmsh.model.getEntitiesForPhysicalGroup(dim, tag) 

766 num_cells = sum( 

767 len(t) for e in group_entities for t in gmsh.model.mesh.getElements(dim, e)[1] 

768 ) 

769 if num_cells == 0: 

770 gmsh.model.removePhysicalGroups([(dim, tag)]) 

771 

772 gmsh.option.setNumber("Mesh.Binary", int(binary)) 

773 gmsh.option.setNumber("Mesh.SaveAll", 1) 

774 gmsh.write(str(filename)) 

775 # Append the views without repeating the mesh 

776 gmsh.option.setNumber("PostProcessing.SaveMesh", 0) 

777 for view in gmsh.view.getTags(): 

778 if view not in preexisting_views: 

779 gmsh.view.write(view, str(filename), append=True) 

780 return None, None 

781 

782 _run_on_root(comm, write) 

783 

784 

785def read_meshtags_data( 

786 filename: str | Path, 

787 comm: MPI.Comm, 

788 name: str, 

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

790) -> MeshTagsData: 

791 """Read mesh tags from the physical groups of a Gmsh file. 

792 

793 Args: 

794 filename: Path to file to read from 

795 comm: MPI communicator used in storage 

796 name: ``"cell"``, ``"facet"``, ``"ridge"`` or ``"peak"`` for all physical groups of 

797 that codimension, as in :func:`dolfinx.io.gmsh.model_to_mesh`. Otherwise the 

798 physical group called ``name``, or the groups called ``f"{name}_{tag}"``, as 

799 written by :func:`write_meshtags`. 

800 backend_args: Arguments to backend 

801 

802 Returns: 

803 Internal data structure for the mesh tags read from file, with the physical tag as 

804 value. All data is on rank 0. 

805 """ 

806 check_file_exists(filename) 

807 

808 def read( 

809 preexisting_views: list[int], 

810 ) -> tuple[tuple[npt.NDArray[np.int64], npt.NDArray[np.int32]], tuple[int, int]]: 

811 gmsh.merge(str(filename)) 

812 tagged = _tagged_entities() 

813 tdim = max(tagged) 

814 groups = gmsh.model.getPhysicalGroups() 

815 if name in codim_names: 

816 dim = tdim - codim_names[name] 

817 group_tags = [tag for d, tag in groups if d == dim] 

818 else: 

819 matches = [ 

820 (d, tag) 

821 for d, tag in groups 

822 if gmsh.model.getPhysicalName(d, tag) in (name, f"{name}_{tag}") 

823 ] 

824 if len(matches) == 0: 

825 available = sorted(gmsh.model.getPhysicalName(d, tag) for d, tag in groups) 

826 raise KeyError( 

827 f"Could not find physical group '{name}' in {filename}. Available: {available}" 

828 ) 

829 if len(dims := {d for d, _ in matches}) != 1: 

830 raise RuntimeError(f"Physical groups '{name}' have several dimensions {dims}.") 

831 dim = dims.pop() 

832 group_tags = [tag for _, tag in matches] 

833 if dim not in tagged: 

834 return (np.zeros((0, 0), dtype=np.int64), np.zeros(0, dtype=np.int32)), (dim, 0) 

835 if (entity_data := tagged[dim]) is None: 

836 raise NotImplementedError(f"Mixed or unsupported element types of dimension {dim}.") 

837 _, entities, tag_values, *_ = entity_data 

838 keep = np.isin(tag_values, group_tags) 

839 return (entities[keep], tag_values[keep]), (dim, entities.shape[1]) 

840 

841 local, (dim, num_nodes_per_entity) = _run_on_root(comm, read) 

842 if local is None: 

843 local = (np.zeros((0, num_nodes_per_entity), dtype=np.int64), np.zeros(0, dtype=np.int32)) 

844 return MeshTagsData(name=name, values=local[1], indices=local[0], dim=dim) 

845 

846 

847def read_dofmap( 

848 filename: str | Path, 

849 comm: MPI.Comm, 

850 name: str, 

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

852) -> dolfinx.graph.AdjacencyList: 

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

854 

855 Args: 

856 filename: Path to file to read from 

857 comm: MPI communicator used in storage 

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

859 backend_args: Arguments to backend 

860 

861 Returns: 

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

863 """ 

864 raise NotImplementedError("The gmsh backend cannot make checkpoints.") 

865 

866 

867def read_dofs( 

868 filename: str | Path, 

869 comm: MPI.Comm, 

870 name: str, 

871 time: float, 

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

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

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

875 

876 Args: 

877 filename: Path to file to read from 

878 comm: MPI communicator used in storage 

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

880 time: Time stamp associated with the function to read 

881 backend_args: Arguments to backend 

882 

883 Returns: 

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

885 and the global starting point on the process. 

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

887 """ 

888 raise NotImplementedError("The gmsh backend cannot make checkpoints.") 

889 

890 

891def read_cell_perms( 

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

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

894 """ 

895 Read cell permutation from file with given communicator, 

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

897 

898 Args: 

899 comm: MPI communicator used in storage 

900 filename: Path to file to read from 

901 backend_args: Arguments to backend 

902 

903 Returns: 

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

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

906 """ 

907 raise NotImplementedError("The gmsh backend cannot make checkpoints.") 

908 

909 

910def write_function( 

911 filename: Path | str, 

912 comm: MPI.Comm, 

913 u: FunctionData, 

914 time: float, 

915 mode: FileMode, 

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

917): 

918 """Write a function to file. 

919 

920 Args: 

921 filename: Path to file to write to 

922 comm: MPI communicator used in storage 

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

924 time: Time stamp associated with function 

925 mode: File-mode to store the function 

926 backend_args: Arguments to backend 

927 """ 

928 raise NotImplementedError("The gmsh backend cannot make checkpoints.") 

929 

930 

931def read_legacy_mesh( 

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

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

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

935 legacy DOLFIN HDF5-file. 

936 

937 Args: 

938 filename: Path to file to read from 

939 comm: MPI communicator used in storage 

940 group: Group in HDF5 file where mesh is stored 

941 

942 Returns: 

943 Tuple containing: 

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

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

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

947 """ 

948 raise NotImplementedError("The gmsh backend cannot read legacy DOLFIN meshes.") 

949 

950 

951def snapshot_checkpoint( 

952 filename: Path | str, 

953 mode: FileMode, 

954 u: dolfinx.fem.Function, 

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

956): 

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

958 

959 Args: 

960 filename: Path to file to read from 

961 mode: File-mode to store the function 

962 u: dolfinx function to create a snapshot checkpoint for 

963 backend_args: Arguments to backend 

964 """ 

965 raise NotImplementedError("The gmsh backend cannot make checkpoints.") 

966 

967 

968def read_hdf5_array( 

969 comm: MPI.Comm, 

970 filename: Path | str, 

971 group: str, 

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

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

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

975 

976 Args: 

977 comm: MPI communicator used in storage 

978 filename: Path to file to read from 

979 group: Group in HDF5 file where array is stored 

980 backend_args: Arguments to backend 

981 

982 Returns: 

983 Tuple containing: 

984 - Numpy array read from file 

985 - Global starting point on the process. 

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

987 """ 

988 raise NotImplementedError("The gmsh backend cannot read HDF5 arrays.") 

989 

990 

991def read_point_data( 

992 filename: Path | str, 

993 name: str, 

994 comm: MPI.Comm, 

995 time: str | float | None, 

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

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

998 """Read point data (``$NodeData``) from a Gmsh file. 

999 

1000 Args: 

1001 filename: Path to file 

1002 name: Name of point data 

1003 comm: Communicator to launch IO on. 

1004 time: Time of the step to read, ``None`` for the first step 

1005 backend_args: Arguments to backend, ``"dtype"`` sets the type of the data, or of 

1006 its real and imaginary parts for complex data 

1007 

1008 Returns: 

1009 Tuple containing: 

1010 - The data of shape ``(num_nodes, num_components)``, ordered by node tag, on 

1011 rank 0. Nodes without data get zeros. Complex data, stored as the views 

1012 ``real_{name}`` and ``imag_{name}``, is combined. 

1013 - The global start of the data on this process, ``0`` 

1014 """ 

1015 check_file_exists(filename) 

1016 backend_args = get_default_backend_args(backend_args) 

1017 

1018 def read( 

1019 preexisting_views: list[int], 

1020 ) -> tuple[npt.NDArray[np.float64 | np.complex128], tuple[int, bool]]: 

1021 gmsh.merge(str(filename)) 

1022 if (found := _find_view(name, preexisting_views)) is None: 

1023 raise KeyError(f"Could not find point data '{name}' in {filename}.") 

1024 views, times = found 

1025 if time is None: 

1026 step = 0 

1027 else: 

1028 steps = np.flatnonzero(np.isclose(times, float(time))) 

1029 if len(steps) != 1: 

1030 raise KeyError( 

1031 f"Expected one step of '{name}' at time {time} in {filename}, found " 

1032 f"{len(steps)}. Available times: {times.tolist()}" 

1033 ) 

1034 step = int(steps[0]) 

1035 parts = [] 

1036 for view in views: 

1037 data_type, tags, data, _, num_components = gmsh.view.getModelData(view, step) 

1038 if data_type != "NodeData": 

1039 raise ValueError(f"'{name}' in {filename} is {data_type}, not NodeData.") 

1040 part = np.zeros((gmsh.model.mesh.getMaxNodeTag(), num_components), dtype=np.float64) 

1041 part[np.asarray(tags, dtype=np.int64) - 1] = np.asarray(data).reshape( 

1042 len(tags), num_components 

1043 ) 

1044 parts.append(part) 

1045 values = parts[0] if len(parts) == 1 else parts[0] + 1j * parts[1] 

1046 return values, (num_components, len(parts) == 2) 

1047 

1048 values, (num_components, is_complex) = _run_on_root(comm, read) 

1049 dtype = backend_args["dtype"] 

1050 if is_complex: 

1051 # complex64 from float32 parts, complex128 from float64 

1052 dtype = np.result_type(dtype, np.complex64) 

1053 if values is None: 

1054 values = np.zeros((0, num_components), dtype=dtype) 

1055 return values.astype(dtype), 0 

1056 

1057 

1058def read_cell_data( 

1059 filename: Path | str, 

1060 name: str, 

1061 comm: MPI.Comm, 

1062 time: str | float | None, 

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

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

1065 """Read cell data (``$ElementData``) from a Gmsh file. 

1066 

1067 Args: 

1068 filename: Path to file 

1069 name: Name of cell data 

1070 comm: Communicator to launch IO on. 

1071 time: Time of the step to read, ``None`` for the first step 

1072 backend_args: Arguments to backend, ``"dtype"`` sets the type of the data, or of 

1073 its real and imaginary parts for complex data 

1074 

1075 Returns: 

1076 Tuple containing: 

1077 - The nodes of the cells with data, as zero-based node indices in DOLFINx 

1078 ordering, on rank 0 

1079 - The data of these cells, of shape ``(num_cells, num_components)``, on rank 0. 

1080 Complex data, stored as the views ``real_{name}`` and ``imag_{name}``, is 

1081 combined. 

1082 """ 

1083 check_file_exists(filename) 

1084 backend_args = get_default_backend_args(backend_args) 

1085 

1086 def read( 

1087 preexisting_views: list[int], 

1088 ) -> tuple[ 

1089 tuple[npt.NDArray[np.int64], npt.NDArray[np.float64 | np.complex128]], 

1090 tuple[int, int, bool], 

1091 ]: 

1092 gmsh.merge(str(filename)) 

1093 if (found := _find_view(name, preexisting_views)) is None: 

1094 raise KeyError(f"Could not find cell data '{name}' in {filename}.") 

1095 views, times = found 

1096 if time is None: 

1097 step = 0 

1098 else: 

1099 steps = np.flatnonzero(np.isclose(times, float(time))) 

1100 if len(steps) != 1: 

1101 raise KeyError( 

1102 f"Expected one step of '{name}' at time {time} in {filename}, found " 

1103 f"{len(steps)}. Available times: {times.tolist()}" 

1104 ) 

1105 step = int(steps[0]) 

1106 tagged = _tagged_entities() 

1107 if (cell_data := tagged[max(tagged)]) is None: 

1108 raise NotImplementedError(f"Mixed or unsupported cell types in {filename}.") 

1109 element_tags, cells = cell_data[:2] 

1110 parts, part_tags = [], [] 

1111 for view in views: 

1112 data_type, tags, data, _, num_components = gmsh.view.getModelData(view, step) 

1113 if data_type != "ElementData": 

1114 raise ValueError(f"'{name}' in {filename} is {data_type}, not ElementData.") 

1115 part_tags.append(np.asarray(tags, dtype=np.int64)) 

1116 parts.append(np.asarray(data, dtype=np.float64).reshape(len(tags), num_components)) 

1117 if len(parts) == 2 and not np.array_equal(part_tags[0], part_tags[1]): 

1118 raise ValueError(f"The real and imaginary parts of '{name}' are on different cells.") 

1119 rows = np.searchsorted(element_tags, part_tags[0]) 

1120 if np.any(rows >= len(element_tags)) or np.any(element_tags[rows] != part_tags[0]): 

1121 raise ValueError(f"'{name}' in {filename} holds data on elements that are not cells.") 

1122 values = parts[0] if len(parts) == 1 else parts[0] + 1j * parts[1] 

1123 return (cells[rows], values), (num_components, cells.shape[1], len(parts) == 2) 

1124 

1125 local, (num_components, num_nodes_per_cell, is_complex) = _run_on_root(comm, read) 

1126 dtype = backend_args["dtype"] 

1127 if is_complex: 

1128 # complex64 from float32 parts, complex128 from float64 

1129 dtype = np.result_type(dtype, np.complex64) 

1130 if local is None: 

1131 local = ( 

1132 np.zeros((0, num_nodes_per_cell), dtype=np.int64), 

1133 np.zeros((0, num_components), dtype=dtype), 

1134 ) 

1135 return local[0], local[1].astype(dtype) 

1136 

1137 

1138def write_data( 

1139 filename: Path | str, 

1140 array_data: ArrayData, 

1141 comm: MPI.Comm, 

1142 time: str | float | None, 

1143 mode: FileMode, 

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

1145): 

1146 """Write point or cell data to a Gmsh file, as a step of the view named after it. 

1147 

1148 Point data is written as ``$NodeData`` and cell data as ``$ElementData``, keyed by 

1149 global index + 1. Complex data is split into the views ``real_{name}`` and 

1150 ``imag_{name}``, as :class:`dolfinx.io.XDMFFile` does. The mesh must have been 

1151 written to the file with :func:`write_mesh`, from the same mesh. 

1152 

1153 Args: 

1154 filename: Path to file 

1155 array_data: Data to write to file 

1156 comm: MPI communicator to open the file with 

1157 time: Time of the step, ``None`` for ``0`` 

1158 mode: :attr:`FileMode.append` adds the step, or replaces the step at the same 

1159 time; :attr:`FileMode.write` replaces all steps of the data 

1160 backend_args: Arguments to backend, ``"binary"`` selects binary MSH 

1161 """ 

1162 if (data_type := {"Point": "NodeData", "Cell": "ElementData"}.get(array_data.type)) is None: 

1163 raise ValueError(f"Unknown data type {array_data.type}, expected 'Point' or 'Cell'.") 

1164 check_file_exists(filename) 

1165 backend_args = get_default_backend_args(backend_args) 

1166 step_time = 0.0 if time is None else float(time) 

1167 values = comm.gather(array_data.values, root=0) 

1168 

1169 def write(preexisting_views: list[int]) -> tuple[None, None]: 

1170 assert values is not None 

1171 if (binary := backend_args["binary"]) is None: 

1172 # The second line of an MSH file is "version file-type data-size" 

1173 with open(filename, "rb") as file: 

1174 file.readline() 

1175 binary = file.readline().split()[1] == b"1" 

1176 

1177 gmsh.merge(str(filename)) 

1178 data = np.vstack(values) 

1179 name = array_data.name 

1180 if np.iscomplexobj(data): 

1181 parts = [(f"real_{name}", data.real), (f"imag_{name}", data.imag)] 

1182 else: 

1183 parts = [(name, data)] 

1184 for part_name, part in parts: 

1185 found = _find_view(part_name, preexisting_views) 

1186 if found is not None and len(found[0]) > 1: 

1187 raise ValueError(f"'{part_name}' in {filename} is complex data.") 

1188 if found is not None and mode == FileMode.write: 

1189 gmsh.view.remove(found[0][0]) 

1190 found = None 

1191 if found is None: 

1192 view = gmsh.view.add(part_name) 

1193 step = 0 

1194 else: 

1195 view, times = found[0][0], found[1] 

1196 if (existing := gmsh.view.getModelData(view, 0)[0]) != data_type: 

1197 raise ValueError(f"'{part_name}' in {filename} is {existing}.") 

1198 same_time = np.flatnonzero(np.isclose(times, step_time)) 

1199 step = int(same_time[0]) if len(same_time) > 0 else len(times) 

1200 gmsh.view.addModelData( 

1201 view, 

1202 step, 

1203 gmsh.model.getCurrent(), 

1204 data_type, 

1205 np.arange(1, part.shape[0] + 1), 

1206 part.astype(np.float64), 

1207 time=step_time, 

1208 numComponents=part.shape[1], 

1209 ) 

1210 

1211 gmsh.option.setNumber("Mesh.Binary", int(binary)) 

1212 gmsh.option.setNumber("Mesh.SaveAll", 1) 

1213 gmsh.write(str(filename)) 

1214 # Append the views without repeating the mesh 

1215 gmsh.option.setNumber("PostProcessing.SaveMesh", 0) 

1216 for v in gmsh.view.getTags(): 

1217 if v not in preexisting_views: 

1218 gmsh.view.write(v, str(filename), append=True) 

1219 return None, None 

1220 

1221 _run_on_root(comm, write)