Coverage for /dolfinx-env/lib/python3.14/site-packages/io4dolfinx/backends/openfoam/helpers.py: 94%

317 statements  

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

1""" 

2Helpers for the OpenFOAM backend: reading a case through VTK, merging regions, and 

3reading the boundary patches and cell zones of ``polyMesh`` files. 

4 

5SPDX License identifier: MIT 

6 

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

8""" 

9 

10from __future__ import annotations 

11 

12import gzip 

13import re 

14from collections.abc import Sequence 

15from dataclasses import dataclass, field 

16from functools import cached_property 

17from pathlib import Path 

18from typing import Any, Callable, NamedTuple 

19 

20import dolfinx 

21import numpy as np 

22import numpy.typing as npt 

23 

24try: 

25 import pyvista 

26except ImportError: 

27 raise ModuleNotFoundError("The openfoam-backend requires pyvista") 

28 

29from ...utils import as_rows 

30from ..vtk_cell_types import _first_order_vtk 

31 

32__all__ = [ 

33 "Case", 

34 "Patch", 

35 "read_case", 

36 "get_regions", 

37 "read_boundary", 

38 "read_faces", 

39 "read_zones", 

40 "field_exists", 

41] 

42 

43#: VTK cell type of OpenFOAM polyhedra, which DOLFINx cannot represent 

44VTK_POLYHEDRON = 42 

45 

46 

47class Patch(NamedTuple): 

48 """A boundary patch of a region.""" 

49 

50 name: str #: The patch name, ``region/patch`` in a case with several regions 

51 faces: list[npt.NDArray[np.int64]] #: Each face, as merged point indices 

52 entries: dict[str, str] #: The entries of the patch in the ``boundary`` file 

53 

54 

55@dataclass 

56class Case: 

57 """An OpenFOAM case read through VTK: its internal mesh and the fields asked for, with 

58 the regions merged into one mesh.""" 

59 

60 path: Path #: The case directory 

61 regions: list[str] #: Region names, ``""`` for the default region 

62 points: npt.NDArray[np.floating] #: Points, merged over regions 

63 #: Cells by DOLFINx cell type, as merged point indices in DOLFINx node order. The cells 

64 #: of a type are in region order, and then in OpenFOAM cell order. 

65 cells: dict[str, npt.NDArray[np.int64]] 

66 #: For each region, the merged index of each of its points, by OpenFOAM point label 

67 node_maps: list[npt.NDArray[np.int64]] 

68 #: The index of the first cell of each region, and the number of cells. For one cell 

69 #: type, cell ``i`` of a region is merged cell ``cell_offsets[region] + i``. 

70 cell_offsets: npt.NDArray[np.int64] 

71 #: The cell fields asked for, of shape ``(num_cells, num_components)`` 

72 cell_data: dict[str, np.ndarray] = field(default_factory=dict) 

73 #: The point fields asked for, of shape ``(num_points, num_components)`` 

74 point_data: dict[str, np.ndarray] = field(default_factory=dict) 

75 

76 @property 

77 def cell_types(self) -> list[str]: 

78 """The DOLFINx cell types of the mesh, sorted.""" 

79 return sorted(self.cells, key=lambda c: dolfinx.mesh.to_type(c).value) 

80 

81 def get_single_type_cells(self, what: str) -> npt.NDArray[np.int64]: 

82 """The cells of a mesh of one cell type. 

83 

84 Raises: 

85 NotImplementedError: For a mesh with several cell types. 

86 """ 

87 if len(types := self.cell_types) > 1: 

88 raise NotImplementedError( 

89 f"{what} is not supported on meshes with several cell types {types}." 

90 ) 

91 return self.cells[types[0]] 

92 

93 def get_polymesh(self, region: str) -> Path: 

94 """The ``polyMesh`` directory of a region.""" 

95 return self.path / "constant" / region / "polyMesh" 

96 

97 def _get_name(self, region: str, name: str) -> str: 

98 """The name of a patch or zone, qualified by its region if there are several.""" 

99 return name if len(self.regions) == 1 else f"{region}/{name}" 

100 

101 @cached_property 

102 def _faces(self) -> list[tuple[npt.NDArray[np.int64], npt.NDArray[np.int64]]]: 

103 """The faces of each region, as offsets into OpenFOAM point labels.""" 

104 return [read_faces(self.get_polymesh(region)) for region in self.regions] 

105 

106 def _get_region_faces( 

107 self, i: int, face_labels: npt.NDArray[np.int64] 

108 ) -> list[npt.NDArray[np.int64]]: 

109 """Faces of region ``i``, by face label, as merged point indices.""" 

110 offsets, labels = self._faces[i] 

111 return [ 

112 self.node_maps[i][labels[offsets[f] : offsets[f + 1]]] for f in face_labels.tolist() 

113 ] 

114 

115 @cached_property 

116 def patches(self) -> list[Patch]: 

117 """The boundary patches of each region, in region order and then as in each 

118 ``boundary`` file, read by their labels from the ``polyMesh`` files. 

119 

120 Raises: 

121 ValueError: If a patch mapped to a patch of another region does not coincide 

122 with it, so that the regions were not merged where they meet. 

123 """ 

124 patches = [] 

125 for i, region in enumerate(self.regions): 

126 for entries in read_boundary(self.get_polymesh(region)): 

127 start, num = int(entries["startFace"]), int(entries["nFaces"]) 

128 faces = self._get_region_faces(i, np.arange(start, start + num, dtype=np.int64)) 

129 patches.append(Patch(self._get_name(region, entries["name"]), faces, entries)) 

130 by_name = {p.name: {tuple(sorted(f)) for f in p.faces} for p in patches} 

131 for name, other in self.get_interfaces(patches): 

132 if by_name[name] != by_name[other]: 

133 raise ValueError( 

134 f"The faces of patch {name} do not coincide with those of {other} after " 

135 "merging the regions, whose points must match exactly." 

136 ) 

137 return patches 

138 

139 def get_interfaces(self, patches: list[Patch]) -> list[tuple[str, str]]: 

140 """The pairs of patches between regions: patches mapped to a patch of another 

141 region (``sampleRegion``, ``samplePatch``), which hold the same faces after the 

142 regions are merged.""" 

143 if len(self.regions) == 1: 

144 return [] 

145 names = {p.name for p in patches} 

146 pairs = [] 

147 for patch in patches: 

148 region = patch.name.split("/")[0] 

149 other = patch.entries.get("sampleRegion") 

150 sample = patch.entries.get("samplePatch") 

151 if other is not None and other != region and f"{other}/{sample}" in names: 

152 pairs.append((patch.name, f"{other}/{sample}")) 

153 return pairs 

154 

155 def _get_zones( 

156 self, kind: str, convert: Callable[[int, npt.NDArray[np.int64]], Any] 

157 ) -> dict[str, Any]: 

158 """The zones of a kind (``"cell"``, ``"face"``, ``"point"``) of each region, by 

159 name, with ``convert(region index, labels)`` applied to the labels of each.""" 

160 return { 

161 self._get_name(region, name): convert(i, labels) 

162 for i, region in enumerate(self.regions) 

163 for name, labels in read_zones(self.get_polymesh(region), kind).items() 

164 } 

165 

166 @cached_property 

167 def cell_zones(self) -> dict[str, npt.NDArray[np.int64]]: 

168 """The cells of each ``cellZone`` of each region, as merged cell indices.""" 

169 return self._get_zones("cell", lambda i, labels: self.cell_offsets[i] + labels) 

170 

171 @cached_property 

172 def face_zones(self) -> dict[str, list[npt.NDArray[np.int64]]]: 

173 """The faces of each ``faceZone`` of each region, as merged point indices.""" 

174 return self._get_zones("face", self._get_region_faces) 

175 

176 @cached_property 

177 def point_zones(self) -> dict[str, npt.NDArray[np.int64]]: 

178 """The points of each ``pointZone`` of each region, as merged point indices.""" 

179 return self._get_zones("point", lambda i, labels: self.node_maps[i][labels]) 

180 

181 

182def _time_value(reader: pyvista.POpenFOAMReader, time: float | str | None) -> float | None: 

183 """The time step of the case to read; the first one if ``time`` is ``None``.""" 

184 times = list(reader.time_values) 

185 if len(times) == 0: 

186 return None 

187 if time is None: 

188 return times[0] 

189 matches = [t for t in times if np.isclose(t, float(time))] 

190 if len(matches) != 1: 

191 raise KeyError(f"No time step {time} in {reader.path}. Available times: {times}") 

192 return matches[0] 

193 

194 

195def _grid_cells( 

196 grid: pyvista.UnstructuredGrid, node_map: npt.NDArray[np.int64] 

197) -> dict[str, npt.NDArray[np.int64]]: 

198 """The cells of a grid by DOLFINx cell type, as merged point indices in DOLFINx order.""" 

199 if (num_polyhedra := np.count_nonzero(grid.celltypes == VTK_POLYHEDRON)) > 0: 

200 raise NotImplementedError( 

201 f"The mesh has {num_polyhedra} polyhedral cells, which DOLFINx does not support." 

202 ) 

203 cells: dict[str, npt.NDArray[np.int64]] = {} 

204 for vtk_type, vtk_nodes in grid.cells_dict.items(): 

205 nodes = np.asarray(vtk_nodes, dtype=np.int64) 

206 if int(vtk_type) not in _first_order_vtk: 

207 raise NotImplementedError(f"Unsupported VTK cell type {int(vtk_type)}.") 

208 cell_type = _first_order_vtk[int(vtk_type)] 

209 perm = dolfinx.cpp.io.perm_vtk(dolfinx.mesh.to_type(cell_type), nodes.shape[1]) 

210 cells[cell_type] = node_map[nodes[:, perm]] 

211 return cells 

212 

213 

214def get_regions(reader: pyvista.POpenFOAMReader, region: str | None) -> list[str]: 

215 """The regions of a case to read, from the names of the meshes VTK can read. 

216 

217 Args: 

218 reader: VTK reader of the case 

219 region: Region to read, ``""`` for the default region, all regions if ``None`` 

220 

221 Returns: 

222 The region names, ``""`` for the default region, in the order VTK reads them 

223 """ 

224 names = reader.patch_array_names 

225 # The default region (constant/polyMesh) is called "", so that a case without regions 

226 # is read like a case with one region 

227 named = sorted({n.split("/")[1] for n in names if n.startswith("/")}) 

228 available = ([""] if "internalMesh" in names else []) + named 

229 if region is None: 

230 # Without a choice, read the named regions and leave out the default region: in a 

231 # multi-region case it usually holds the mesh from before it was split into regions 

232 return named if named else available 

233 if region not in available: 

234 raise KeyError(f"No region '{region}' in {reader.path}. Regions: {available}") 

235 return [region] 

236 

237 

238def read_case( 

239 filename: Path | str, 

240 time: float | str | None, 

241 region: str | None, 

242 cell_fields: Sequence[str] = (), 

243 point_fields: Sequence[str] = (), 

244) -> Case: 

245 """Read the internal mesh of each region of an OpenFOAM case through VTK, with only 

246 the given fields. 

247 

248 VTK keeps the point and cell order of OpenFOAM in each internal mesh, so point ``i`` 

249 and cell ``i`` of a region are OpenFOAM point and cell label ``i``. The points of 

250 several regions are merged where they coincide exactly; a single region keeps its 

251 point order. 

252 

253 Args: 

254 filename: The ``.foam`` file of the case 

255 time: Time step to read, the first one if ``None`` 

256 region: Region to read, ``""`` for the default region, all regions if ``None`` 

257 cell_fields: Names of cell-centred fields (``vol*Field``) to read 

258 point_fields: Names of point fields (``point*Field``) to read 

259 

260 Raises: 

261 KeyError: If a field is not in the case, or not in every region read at this time. 

262 ValueError: If a field is asked for as cell data but is a point field, or the 

263 other way round. 

264 """ 

265 reader = pyvista.POpenFOAMReader(str(filename)) 

266 # By default VTK also makes a point field of every cell field, by averaging the cells 

267 # around each point. Cell fields are read as cell data only, so that point data holds 

268 # only the point fields of the case. 

269 reader.cell_to_point_creation = False 

270 # Check the fields asked for before reading anything, against the fields of the case 

271 case_fields = {"cell": list(reader.cell_array_names), "point": list(reader.point_array_names)} 

272 reader_name = {"cell": "read_cell_data", "point": "read_point_data"} 

273 description = {"cell": "cell-centred", "point": "a point field"} 

274 for kind, other, names in (("cell", "point", cell_fields), ("point", "cell", point_fields)): 

275 for name in names: 

276 if name in case_fields[kind]: 

277 continue 

278 if name in case_fields[other]: 

279 raise ValueError( 

280 f"'{name}' is {description[other]}; read it with {reader_name[other]}." 

281 ) 

282 raise KeyError( 

283 f"No {kind} field '{name}' in {filename}. {kind.capitalize()} fields: " 

284 f"{case_fields[kind]}" 

285 ) 

286 # VTK reads every field of the time step unless told otherwise: read only those asked for 

287 reader.disable_all_cell_arrays() 

288 reader.disable_all_point_arrays() 

289 for name in cell_fields: 

290 reader.enable_cell_array(name) 

291 for name in point_fields: 

292 reader.enable_point_array(name) 

293 # Read only the internal meshes, not the boundary patches: patches are read from the 

294 # polyMesh files by their labels, and skipping them saves time and memory on meshes 

295 # with many boundary faces. 

296 for name in reader.patch_array_names: 

297 if name.endswith("internalMesh"): 

298 reader.enable_patch_array(name) 

299 else: 

300 reader.disable_patch_array(name) 

301 if (t := _time_value(reader, time)) is not None: 

302 reader.set_active_time_value(t) 

303 regions = get_regions(reader, region) 

304 data = reader.read() 

305 

306 # The internal mesh of each region to read, by region name 

307 grids: dict[str, pyvista.UnstructuredGrid] = {} 

308 for name in regions: 

309 block = data if name == "" else data[name] 

310 grid = block["internalMesh"] if isinstance(block, pyvista.MultiBlock) else None 

311 if not isinstance(grid, pyvista.UnstructuredGrid): 

312 raise TypeError(f"Expected an unstructured internal mesh in {filename}.") 

313 grids[name] = grid 

314 

315 if len(regions) == 1: 

316 points = np.asarray(grids[regions[0]].points) 

317 node_maps = [np.arange(len(points), dtype=np.int64)] 

318 else: 

319 # Regions are separate meshes, joined where their points coincide exactly. 

320 # Adding 0 turns -0.0 into 0.0, which compare unequal as bytes. 

321 all_points = np.vstack([np.asarray(grids[r].points) for r in regions]) + 0.0 

322 points, inverse = np.unique(all_points, axis=0, return_inverse=True) 

323 offsets = np.cumsum(np.array([0] + [grids[r].n_points for r in regions])) 

324 node_maps = [ 

325 inverse.reshape(-1)[offsets[i] : offsets[i + 1]].astype(np.int64) 

326 for i in range(len(regions)) 

327 ] 

328 

329 # Merge the cells of each type, region after region 

330 region_cells = [_grid_cells(grids[r], m) for r, m in zip(regions, node_maps)] 

331 types = {cell_type for cells in region_cells for cell_type in cells} 

332 cells = {t: np.vstack([c[t] for c in region_cells if t in c]) for t in types} 

333 counts = [grids[r].n_cells for r in regions] 

334 

335 def check_regions(name: str, kind: str, has_field: list[bool]): 

336 """Raise if a field is missing from some of the regions read, at this time step.""" 

337 if all(has_field): 

338 return 

339 at = f" at time {t}" if t is not None else "" 

340 if len(regions) == 1: 

341 raise KeyError(f"No {kind} field '{name}'{at} in {filename}.") 

342 missing = [r for r, has in zip(regions, has_field) if not has] 

343 found = [r for r, has in zip(regions, has_field) if has] 

344 raise KeyError( 

345 f"No {kind} field '{name}'{at} in region(s) {missing} of {filename}" 

346 + (f"; found in {found}." if found else ".") 

347 ) 

348 

349 # Merge the fields asked for 

350 cell_data: dict[str, np.ndarray] = {} 

351 for name in cell_fields: 

352 check_regions(name, "cell", [name in grids[r].cell_data for r in regions]) 

353 cell_data[name] = np.vstack([as_rows(grids[r].cell_data[name]) for r in regions]) 

354 point_data: dict[str, np.ndarray] = {} 

355 for name in point_fields: 

356 check_regions(name, "point", [name in grids[r].point_data for r in regions]) 

357 # A point shared by regions takes the value of the last of them 

358 first = as_rows(grids[regions[0]].point_data[name]) 

359 values = np.zeros((len(points), first.shape[1]), dtype=first.dtype) 

360 for r, node_map in zip(regions, node_maps): 

361 values[node_map] = as_rows(grids[r].point_data[name]) 

362 point_data[name] = values 

363 

364 return Case( 

365 path=Path(filename).parent, 

366 regions=regions, 

367 points=points, 

368 cells=cells, 

369 node_maps=node_maps, 

370 cell_offsets=np.concatenate([[0], np.cumsum(counts)]).astype(np.int64), 

371 cell_data=cell_data, 

372 point_data=point_data, 

373 ) 

374 

375 

376def _find(path: Path) -> Path | None: 

377 """The file at ``path``, or its gzipped version ``path.gz``; ``None`` if neither exists.""" 

378 for candidate in (path, path.with_name(path.name + ".gz")): 

379 if candidate.exists(): 

380 return candidate 

381 return None 

382 

383 

384def field_exists(case_dir: Path, time_name: str, region: str, name: str) -> bool: 

385 """Whether a field file exists in a time directory, gzipped or not.""" 

386 return _find(case_dir / time_name / region / name) is not None 

387 

388 

389# --------------------------------------------------------------------------------------- 

390# Reading polyMesh files. Only the entries needed here are read: the faces and patches, 

391# and the cell zones. Lists can be ASCII or binary, and files gzipped. 

392 

393 

394def _read_bytes(path: Path) -> bytes: 

395 """The contents of a file that may be gzipped.""" 

396 if (found := _find(path)) is None: 

397 raise FileNotFoundError(f"Could not find {path} or {path.name}.gz") 

398 return gzip.decompress(found.read_bytes()) if found.suffix == ".gz" else found.read_bytes() 

399 

400 

401class _Scanner: 

402 """Reads the tokens and lists of a ``FoamFile``, after its header.""" 

403 

404 def __init__(self, path: Path): 

405 self.path = path 

406 self.data = _read_bytes(path) 

407 match = re.search(rb"FoamFile\s*\{(.*?)\}", self.data, re.S) 

408 if match is None: 

409 raise ValueError(f"No FoamFile header in {path}") 

410 entries = re.findall(rb'(\w+)\s+("[^"]*"|[^;]*);', match.group(1)) 

411 self.header = {k.decode(): v.strip().strip(b'"').decode() for k, v in entries} 

412 self.binary = self.header.get("format", "ascii") == "binary" 

413 arch = re.search(r"label=(\d+)", self.header.get("arch", "")) 

414 self.label_dtype = np.dtype("<i8") if arch and arch.group(1) == "64" else np.dtype("<i4") 

415 self.pos = match.end() 

416 

417 def skip(self): 

418 """Skip white space and comments.""" 

419 data = self.data 

420 while self.pos < len(data): 

421 if data[self.pos : self.pos + 1].isspace(): 

422 self.pos += 1 

423 elif data.startswith(b"//", self.pos): 

424 end = data.find(b"\n", self.pos) 

425 self.pos = len(data) if end < 0 else end 

426 elif data.startswith(b"/*", self.pos): 

427 end = data.find(b"*/", self.pos) 

428 self.pos = len(data) if end < 0 else end + 2 

429 else: 

430 break 

431 

432 def peek(self) -> bytes: 

433 self.skip() 

434 return self.data[self.pos : self.pos + 1] 

435 

436 def expect(self, char: bytes): 

437 if self.peek() != char: 

438 raise ValueError(f"Expected {char!r} at byte {self.pos} of {self.path}") 

439 self.pos += 1 

440 

441 def word(self) -> str: 

442 """The next token: a word, number or punctuation character.""" 

443 self.skip() 

444 if self.data[self.pos : self.pos + 1] in (b"(", b")", b"{", b"}", b";"): 

445 self.pos += 1 

446 return self.data[self.pos - 1 : self.pos].decode() 

447 match = re.compile(rb"[^\s(){};]+").match(self.data, self.pos) 

448 if match is None: 

449 raise ValueError(f"Unexpected end of {self.path}") 

450 self.pos = match.end() 

451 return match.group().decode() 

452 

453 def label_list(self, binary_dtype: np.dtype | None = None) -> npt.NDArray[np.int64]: 

454 """A list of integers: ``N(...)``, binary or ASCII, or uniform ``N{value}``. 

455 

456 Args: 

457 binary_dtype: Type of the items in a binary list, labels by default. Lists of 

458 booleans have one byte per item. 

459 """ 

460 dtype = self.label_dtype if binary_dtype is None else binary_dtype 

461 count = int(self.word()) 

462 if self.peek() == b"{": 

463 self.pos += 1 

464 value = int(self.word()) 

465 self.expect(b"}") 

466 return np.full(count, value, dtype=np.int64) 

467 self.expect(b"(") 

468 if self.binary: 

469 labels = np.frombuffer(self.data, dtype, count, self.pos) 

470 self.pos += count * dtype.itemsize 

471 else: 

472 end = self.data.index(b")", self.pos) 

473 labels = np.array(self.data[self.pos : end].split(), dtype=np.int64) 

474 self.pos = end 

475 self.expect(b")") 

476 if len(labels) != count: 

477 raise ValueError(f"Expected {count} items in {self.path}, found {len(labels)}") 

478 return labels.astype(np.int64) 

479 

480 def dictionaries(self, read_value: Callable[[str], Any]) -> list[tuple[str, dict[str, Any]]]: 

481 """A list of named dictionaries, ``N ( name { key value; ... } ... )``, as in the 

482 ``boundary`` and zones files. 

483 

484 Args: 

485 read_value: Reads the value of an entry, from after its key up to and 

486 including its ``;``, given the key 

487 

488 Returns: 

489 The name and entries of each dictionary, in order 

490 """ 

491 count = int(self.word()) 

492 self.expect(b"(") 

493 result = [] 

494 for _ in range(count): 

495 name = self.word() 

496 self.expect(b"{") 

497 entries = {} 

498 while self.peek() != b"}": 

499 key = self.word() 

500 entries[key] = read_value(key) 

501 self.expect(b"}") 

502 result.append((name, entries)) 

503 return result 

504 

505 def skip_entry(self): 

506 """Skip the value of a dictionary entry, up to and including its ``;``.""" 

507 depth = 0 

508 while True: 

509 token = self.word() 

510 if token in ("(", "{"): 

511 depth += 1 

512 elif token in (")", "}"): 

513 depth -= 1 

514 elif token == ";" and depth == 0: 

515 return 

516 

517 

518def read_faces(polymesh: Path) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.int64]]: 

519 """The faces of a mesh, from its ``faces`` file. 

520 

521 Each face is given by the indices of its points in the ``points`` file (OpenFOAM's 

522 "point labels"), e.g. ``4(0 1 5 4)`` for a quadrilateral. 

523 

524 Returns: 

525 The offsets of the faces, and the point indices of all faces, one face after 

526 another: face ``f`` is ``indices[offsets[f]:offsets[f + 1]]`` 

527 """ 

528 scanner = _Scanner(polymesh / "faces") 

529 if scanner.header.get("class") == "faceCompactList": 

530 offsets = scanner.label_list() 

531 labels = scanner.label_list() 

532 return offsets, labels 

533 if scanner.binary: 

534 raise NotImplementedError(f"Binary faceList in {scanner.path} is not supported.") 

535 count = int(scanner.word()) 

536 scanner.expect(b"(") 

537 sizes, labels_list = [], [] 

538 for _ in range(count): 

539 faces = scanner.label_list() 

540 sizes.append(len(faces)) 

541 labels_list.append(faces) 

542 offsets = np.concatenate([[0], np.cumsum(sizes)]).astype(np.int64) 

543 labels = np.concatenate(labels_list) if labels_list else np.zeros(0, dtype=np.int64) 

544 return offsets, labels 

545 

546 

547def read_boundary(polymesh: Path) -> list[dict[str, str]]: 

548 """The patches of a mesh, in order, with their simple entries, e.g. ``nFaces``, 

549 ``startFace``, ``type``, and for mapped patches ``sampleRegion`` and ``samplePatch``.""" 

550 scanner = _Scanner(polymesh / "boundary") 

551 

552 def raw_text(key: str) -> str: 

553 start = scanner.pos 

554 scanner.skip_entry() 

555 return scanner.data[start : scanner.pos - 1].decode(errors="replace").strip() 

556 

557 return [{"name": name, **entries} for name, entries in scanner.dictionaries(raw_text)] 

558 

559 

560def read_zones(polymesh: Path, kind: str) -> dict[str, npt.NDArray[np.int64]]: 

561 """The labels of each zone of a mesh, in order; empty if there are no such zones. 

562 

563 Args: 

564 polymesh: The ``polyMesh`` directory 

565 kind: ``"cell"``, ``"face"`` or ``"point"``, for the ``cellZones``, ``faceZones`` 

566 or ``pointZones`` file and the cell, face or point labels of each zone 

567 """ 

568 if _find(polymesh / f"{kind}Zones") is None: 

569 return {} 

570 scanner = _Scanner(polymesh / f"{kind}Zones") 

571 

572 def labels(key: str) -> npt.NDArray[np.int64] | None: 

573 if key not in (f"{kind}Labels", "flipMap"): 

574 scanner.skip_entry() 

575 return None 

576 if not scanner.peek().isdigit(): 

577 scanner.word() # List<label> or List<bool> 

578 # The flipMap of a face zone is a list of booleans, one byte each if binary 

579 values = scanner.label_list(np.dtype("u1") if key == "flipMap" else None) 

580 scanner.expect(b";") 

581 return values 

582 

583 zones = scanner.dictionaries(labels) 

584 empty = np.zeros(0, dtype=np.int64) 

585 return {name: entries.get(f"{kind}Labels", empty) for name, entries in zones}