| 1 |
# Copyright (C) 2023 Jørgen Schartum Dokken |
| 2 |
# |
| 3 |
# This file is part of adios4dolfinx |
| 4 |
# |
| 5 |
# SPDX-License-Identifier: MIT |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
import pathlib |
| 10 |
import typing |
| 11 |
|
| 12 |
from mpi4py import MPI |
| 13 |
|
| 14 |
import adios2 |
| 15 |
import basix |
| 16 |
import dolfinx |
| 17 |
import numpy as np |
| 18 |
import numpy.typing as npt |
| 19 |
import ufl |
| 20 |
|
| 21 |
from .adios2_helpers import ( |
| 22 |
ADIOSFile, |
| 23 |
adios_to_numpy_dtype, |
| 24 |
read_array, |
| 25 |
resolve_adios_scope, |
| 26 |
) |
| 27 |
from .comm_helpers import send_dofs_and_recv_values |
| 28 |
from .utils import ( |
| 29 |
compute_dofmap_pos, |
| 30 |
compute_insert_position, |
| 31 |
compute_local_range, |
| 32 |
index_owner, |
| 33 |
) |
| 34 |
|
| 35 |
adios2 = resolve_adios_scope(adios2) |
| 36 |
|
| 37 |
__all__ = [ |
| 38 |
"read_mesh_from_legacy_h5", |
| 39 |
"read_function_from_legacy_h5", |
| 40 |
] |
| 41 |
|
| 42 |
|
| 43 |
def read_dofmap_legacy( |
| 44 |
comm: MPI.Intracomm, |
| 45 |
filename: pathlib.Path, |
| 46 |
dofmap: str, |
| 47 |
dofmap_offsets: str, |
| 48 |
num_cells_global: np.int64, |
| 49 |
engine: str, |
| 50 |
cells: npt.NDArray[np.int64], |
| 51 |
dof_pos: npt.NDArray[np.int32], |
| 52 |
bs: int, |
| 53 |
) -> npt.NDArray[np.int64]: |
| 54 |
""" |
| 55 |
Read dofmap with given communicator, split in continuous chunks based on number of |
| 56 |
cells in the mesh (global). |
| 57 |
|
| 58 |
Args: |
| 59 |
comm: MPI communicator |
| 60 |
filename: Path to input file |
| 61 |
dofmap: Variable name for dofmap |
| 62 |
num_cells_global: Number of cells in the global mesh |
| 63 |
engine: ADIOS2 engine type |
| 64 |
cells: Cells (global index) that contain a degree of freedom |
| 65 |
dof_pos: Each entry `dof_pos[i]` corresponds to the local position in the |
| 66 |
`input_dofmap.links(cells[i])[dof_pos[i]]` |
| 67 |
|
| 68 |
Returns: |
| 69 |
The global dof index in the input data for each dof described by |
| 70 |
the (cells[i], dof_pos[i]) tuples. |
| 71 |
|
| 72 |
.. note:: |
| 73 |
No MPI communication is done during this call |
| 74 |
""" |
| 75 |
local_cell_range = compute_local_range(comm, num_cells_global) |
| 76 |
|
| 77 |
# Open ADIOS engine |
| 78 |
adios = adios2.ADIOS(comm) |
| 79 |
with ADIOSFile( |
| 80 |
adios=adios, |
| 81 |
filename=filename, |
| 82 |
mode=adios2.Mode.Read, |
| 83 |
engine=engine, |
| 84 |
io_name="DofmapReader", |
| 85 |
) as adios_file: |
| 86 |
for i in range(adios_file.file.Steps()): |
| 87 |
adios_file.file.BeginStep() |
| 88 |
if dofmap_offsets in adios_file.io.AvailableVariables().keys(): |
| 89 |
break |
| 90 |
adios_file.file.EndStep() |
| 91 |
|
| 92 |
d_offsets = adios_file.io.InquireVariable(dofmap_offsets) |
| 93 |
shape = d_offsets.Shape() |
| 94 |
|
| 95 |
# As the offsets are one longer than the number of cells, we need to read in with an overlap |
| 96 |
if len(shape) == 1: |
| 97 |
d_offsets.SetSelection( |
| 98 |
[[local_cell_range[0]], [local_cell_range[1] + 1 - local_cell_range[0]]] |
| 99 |
) |
| 100 |
in_offsets = np.empty( |
| 101 |
local_cell_range[1] + 1 - local_cell_range[0], |
| 102 |
dtype=d_offsets.Type().strip("_t"), |
| 103 |
) |
| 104 |
else: |
| 105 |
d_offsets.SetSelection( |
| 106 |
[ |
| 107 |
[local_cell_range[0], 0], |
| 108 |
[local_cell_range[1] + 1 - local_cell_range[0], shape[1]], |
| 109 |
] |
| 110 |
) |
| 111 |
in_offsets = np.empty( |
| 112 |
(local_cell_range[1] + 1 - local_cell_range[0], shape[1]), |
| 113 |
dtype=d_offsets.Type().strip("_t"), |
| 114 |
) |
| 115 |
|
| 116 |
in_offsets = in_offsets.squeeze() |
| 117 |
adios_file.file.Get(d_offsets, in_offsets, adios2.Mode.Sync) |
| 118 |
# Get the relevant part of the dofmap |
| 119 |
if dofmap not in adios_file.io.AvailableVariables().keys(): |
| 120 |
raise KeyError(f"Dof offsets not found at {dofmap}") |
| 121 |
cell_dofs = adios_file.io.InquireVariable(dofmap) |
| 122 |
|
| 123 |
if len(shape) == 1: |
| 124 |
cell_dofs.SetSelection([[in_offsets[0]], [in_offsets[-1] - in_offsets[0]]]) |
| 125 |
in_dofmap = np.empty(in_offsets[-1] - in_offsets[0], dtype=cell_dofs.Type().strip("_t")) |
| 126 |
else: |
| 127 |
cell_dofs.SetSelection([[in_offsets[0], 0], [in_offsets[-1] - in_offsets[0], shape[1]]]) |
| 128 |
in_dofmap = np.empty( |
| 129 |
(in_offsets[-1] - in_offsets[0], shape[1]), |
| 130 |
dtype=cell_dofs.Type().strip("_t"), |
| 131 |
) |
| 132 |
assert shape[1] == 1 |
| 133 |
|
| 134 |
adios_file.file.Get(cell_dofs, in_dofmap, adios2.Mode.Sync) |
| 135 |
|
| 136 |
in_dofmap = in_dofmap.reshape(-1).astype(np.int64) |
| 137 |
|
| 138 |
# Map xxxyyyzzz to xyzxyz |
| 139 |
mapped_dofmap = np.empty_like(in_dofmap) |
| 140 |
for i in range(len(in_offsets) - 1): |
| 141 |
pos_begin, pos_end = ( |
| 142 |
in_offsets[i] - in_offsets[0], |
| 143 |
in_offsets[i + 1] - in_offsets[0], |
| 144 |
) |
| 145 |
dofs_i = in_dofmap[pos_begin:pos_end] |
| 146 |
assert (pos_end - pos_begin) % bs == 0 |
| 147 |
num_dofs_local = int((pos_end - pos_begin) // bs) |
| 148 |
for k in range(bs): |
| 149 |
for j in range(num_dofs_local): |
| 150 |
mapped_dofmap[int(pos_begin + j * bs + k)] = dofs_i[int(num_dofs_local * k + j)] |
| 151 |
|
| 152 |
# Extract dofmap data |
| 153 |
global_dofs = np.zeros_like(cells, dtype=np.int64) |
| 154 |
input_cell_positions = cells - local_cell_range[0] |
| 155 |
read_pos = (in_offsets[input_cell_positions] + dof_pos - in_offsets[0]).astype(np.int32) |
| 156 |
global_dofs = mapped_dofmap[read_pos] |
| 157 |
del input_cell_positions, read_pos |
| 158 |
|
| 159 |
adios_file.file.EndStep() |
| 160 |
|
| 161 |
return global_dofs |
| 162 |
|
| 163 |
|
| 164 |
def send_cells_and_receive_dofmap_index( |
| 165 |
filename: pathlib.Path, |
| 166 |
comm: MPI.Intracomm, |
| 167 |
source_ranks: npt.NDArray[np.int32], |
| 168 |
dest_ranks: npt.NDArray[np.int32], |
| 169 |
dest_size: npt.NDArray[np.int32], |
| 170 |
output_owners: npt.NDArray[np.int32], |
| 171 |
input_cells: npt.NDArray[np.int64], |
| 172 |
dofmap_pos: npt.NDArray[np.int32], |
| 173 |
num_cells_global: np.int64, |
| 174 |
dofmap_path: str, |
| 175 |
xdofmap_path: str, |
| 176 |
engine: str, |
| 177 |
bs: int, |
| 178 |
) -> npt.NDArray[np.int64]: |
| 179 |
""" |
| 180 |
Given a set of positions in input dofmap, give the global input index of this dofmap entry |
| 181 |
in input file. |
| 182 |
""" |
| 183 |
|
| 184 |
recv_size = np.zeros(len(source_ranks), dtype=np.int32) |
| 185 |
mesh_to_data_comm = comm.Create_dist_graph_adjacent( |
| 186 |
source_ranks.tolist(), dest_ranks.tolist(), reorder=False |
| 187 |
) |
| 188 |
# Send sizes to create data structures for receiving from NeighAlltoAllv |
| 189 |
mesh_to_data_comm.Neighbor_alltoall(dest_size, recv_size) |
| 190 |
|
| 191 |
# Sort output for sending and fill send data |
| 192 |
out_cells = np.zeros(len(output_owners), dtype=np.int64) |
| 193 |
out_pos = np.zeros(len(output_owners), dtype=np.int32) |
| 194 |
proc_to_dof = np.zeros_like(input_cells, dtype=np.int32) |
| 195 |
insertion_array = compute_insert_position(output_owners, dest_ranks, dest_size) |
| 196 |
out_cells[insertion_array] = input_cells |
| 197 |
out_pos[insertion_array] = dofmap_pos |
| 198 |
proc_to_dof[insertion_array] = np.arange(len(input_cells), dtype=np.int32) |
| 199 |
del insertion_array |
| 200 |
|
| 201 |
# Prepare data-structures for receiving |
| 202 |
total_incoming = sum(recv_size) |
| 203 |
inc_cells = np.zeros(total_incoming, dtype=np.int64) |
| 204 |
inc_pos = np.zeros(total_incoming, dtype=np.intc) |
| 205 |
|
| 206 |
# Send data |
| 207 |
s_msg = [out_cells, dest_size, MPI.INT64_T] |
| 208 |
r_msg = [inc_cells, recv_size, MPI.INT64_T] |
| 209 |
mesh_to_data_comm.Neighbor_alltoallv(s_msg, r_msg) |
| 210 |
|
| 211 |
s_msg = [out_pos, dest_size, MPI.INT32_T] |
| 212 |
r_msg = [inc_pos, recv_size, MPI.INT32_T] |
| 213 |
mesh_to_data_comm.Neighbor_alltoallv(s_msg, r_msg) |
| 214 |
mesh_to_data_comm.Free() |
| 215 |
# Read dofmap from file |
| 216 |
input_dofs = read_dofmap_legacy( |
| 217 |
comm, |
| 218 |
filename, |
| 219 |
dofmap_path, |
| 220 |
xdofmap_path, |
| 221 |
num_cells_global, |
| 222 |
engine, |
| 223 |
inc_cells, |
| 224 |
inc_pos, |
| 225 |
bs, |
| 226 |
) |
| 227 |
# Send input dofs back to owning process |
| 228 |
data_to_mesh_comm = comm.Create_dist_graph_adjacent( |
| 229 |
dest_ranks.tolist(), source_ranks.tolist(), reorder=False |
| 230 |
) |
| 231 |
|
| 232 |
incoming_global_dofs = np.zeros(sum(dest_size), dtype=np.int64) |
| 233 |
s_msg = [input_dofs, recv_size, MPI.INT64_T] |
| 234 |
r_msg = [incoming_global_dofs, dest_size, MPI.INT64_T] |
| 235 |
data_to_mesh_comm.Neighbor_alltoallv(s_msg, r_msg) |
| 236 |
|
| 237 |
# Sort incoming global dofs as they were inputted |
| 238 |
sorted_global_dofs = np.zeros_like(incoming_global_dofs, dtype=np.int64) |
| 239 |
assert len(incoming_global_dofs) == len(input_cells) |
| 240 |
sorted_global_dofs[proc_to_dof] = incoming_global_dofs |
| 241 |
data_to_mesh_comm.Free() |
| 242 |
return sorted_global_dofs |
| 243 |
|
| 244 |
|
| 245 |
def read_mesh_geometry(io: adios2.ADIOS, infile: adios2.Engine, group: str): |
| 246 |
for geometry_key in [f"{group}/geometry", f"{group}/coordinates"]: |
| 247 |
if geometry_key in io.AvailableVariables().keys(): |
| 248 |
break |
| 249 |
else: |
| 250 |
raise KeyError(f"Mesh coordintes not found at '{group}/coordinates'") |
| 251 |
|
| 252 |
geometry = io.InquireVariable(geometry_key) |
| 253 |
shape = geometry.Shape() |
| 254 |
local_range = compute_local_range(MPI.COMM_WORLD, shape[0]) |
| 255 |
geometry.SetSelection([[local_range[0], 0], [local_range[1] - local_range[0], shape[1]]]) |
| 256 |
mesh_geometry = np.empty( |
| 257 |
(local_range[1] - local_range[0], shape[1]), |
| 258 |
dtype=adios_to_numpy_dtype[geometry.Type()], |
| 259 |
) |
| 260 |
|
| 261 |
infile.Get(geometry, mesh_geometry, adios2.Mode.Sync) |
| 262 |
return mesh_geometry |
| 263 |
|
| 264 |
|
| 265 |
def read_mesh_from_legacy_h5( |
| 266 |
filename: pathlib.Path, |
| 267 |
comm: MPI.Intracomm, |
| 268 |
group: str, |
| 269 |
cell_type: str = "tetrahedron", |
| 270 |
) -> dolfinx.mesh.Mesh: |
| 271 |
""" |
| 272 |
Read mesh from `h5`-file generated by legacy DOLFIN `HDF5File.write` or `XDMF.write_checkpoint`. |
| 273 |
|
| 274 |
Args: |
| 275 |
comm: MPI communicator to distribute mesh over |
| 276 |
filename: Path to `h5` or `xdmf` file |
| 277 |
group: Name of mesh in `h5`-file |
| 278 |
cell_type: What type of cell type, by default tetrahedron. |
| 279 |
""" |
| 280 |
# Make sure we use the HDF5File and check that the file is present |
| 281 |
filename = pathlib.Path(filename).with_suffix(".h5") |
| 282 |
if not filename.is_file(): |
| 283 |
raise FileNotFoundError(f"File {filename} does not exist") |
| 284 |
|
| 285 |
# Create ADIOS2 reader |
| 286 |
adios = adios2.ADIOS(comm) |
| 287 |
with ADIOSFile( |
| 288 |
adios=adios, |
| 289 |
filename=filename, |
| 290 |
mode=adios2.Mode.Read, |
| 291 |
io_name="Mesh reader", |
| 292 |
engine="HDF5", |
| 293 |
) as adios_file: |
| 294 |
# Get mesh topology (distributed) |
| 295 |
if f"{group}/topology" not in adios_file.io.AvailableVariables().keys(): |
| 296 |
raise KeyError(f"Mesh topology not found at '{group}/topology'") |
| 297 |
topology = adios_file.io.InquireVariable(f"{group}/topology") |
| 298 |
shape = topology.Shape() |
| 299 |
local_range = compute_local_range(MPI.COMM_WORLD, shape[0]) |
| 300 |
topology.SetSelection([[local_range[0], 0], [local_range[1] - local_range[0], shape[1]]]) |
| 301 |
|
| 302 |
mesh_topology = np.empty( |
| 303 |
(local_range[1] - local_range[0], shape[1]), |
| 304 |
dtype=topology.Type().strip("_t"), |
| 305 |
) |
| 306 |
adios_file.file.Get(topology, mesh_topology, adios2.Mode.Sync) |
| 307 |
|
| 308 |
# Get mesh cell type |
| 309 |
if f"{group}/topology/celltype" in adios_file.io.AvailableAttributes().keys(): |
| 310 |
celltype = adios_file.io.InquireAttribute(f"{group}/topology/celltype") |
| 311 |
cell_type = celltype.DataString()[0] |
| 312 |
|
| 313 |
# Get mesh geometry |
| 314 |
mesh_geometry = read_mesh_geometry(io=adios_file.io, infile=adios_file.file, group=group) |
| 315 |
|
| 316 |
# Create DOLFINx mesh |
| 317 |
element = basix.ufl.element( |
| 318 |
basix.ElementFamily.P, |
| 319 |
cell_type, |
| 320 |
1, |
| 321 |
basix.LagrangeVariant.equispaced, |
| 322 |
shape=(mesh_geometry.shape[1],), |
| 323 |
) |
| 324 |
domain = ufl.Mesh(element) |
| 325 |
|
| 326 |
return dolfinx.mesh.create_mesh( |
| 327 |
comm=MPI.COMM_WORLD, cells=mesh_topology, x=mesh_geometry, e=domain |
| 328 |
) |
| 329 |
|
| 330 |
|
| 331 |
def read_function_from_legacy_h5( |
| 332 |
filename: pathlib.Path, |
| 333 |
comm: MPI.Intracomm, |
| 334 |
u: dolfinx.fem.Function, |
| 335 |
group: str = "mesh", |
| 336 |
step: typing.Optional[int] = None, |
| 337 |
): |
| 338 |
""" |
| 339 |
Read function from a `h5`-file generated by legacy DOLFIN `HDF5File.write` |
| 340 |
or `XDMF.write_checkpoint`. |
| 341 |
|
| 342 |
Args: |
| 343 |
comm : MPI communicator to distribute mesh over |
| 344 |
filename : Path to `h5` or `xdmf` file |
| 345 |
u : The function used to stored the read values |
| 346 |
group : Group within the `h5` file where the function is stored, by default "mesh" |
| 347 |
step : The time step used when saving the checkpoint. If not provided it will assume that |
| 348 |
the function is saved as a regular function (i.e with `HDF5File.write`) |
| 349 |
|
| 350 |
""" |
| 351 |
|
| 352 |
# Make sure we use the HDF5File and check that the file is present |
| 353 |
filename = pathlib.Path(filename).with_suffix(".h5") |
| 354 |
if not filename.is_file(): |
| 355 |
raise FileNotFoundError(f"File {filename} does not exist") |
| 356 |
|
| 357 |
V = u.function_space |
| 358 |
mesh = u.function_space.mesh |
| 359 |
if u.function_space.element.needs_dof_transformations: |
| 360 |
raise RuntimeError( |
| 361 |
"Function-spaces requiring dof permutations are not compatible with legacy data" |
| 362 |
) |
| 363 |
# ----------------------Step 1--------------------------------- |
| 364 |
# Compute index of input cells, and position in input dofmap |
| 365 |
local_cells, dof_pos = compute_dofmap_pos(u.function_space) |
| 366 |
input_cells = mesh.topology.original_cell_index[local_cells] |
| 367 |
|
| 368 |
# Compute mesh->input communicator |
| 369 |
# 1.1 Compute mesh->input communicator |
| 370 |
num_cells_global = mesh.topology.index_map(mesh.topology.dim).size_global |
| 371 |
owners = index_owner(mesh.comm, input_cells, num_cells_global) |
| 372 |
unique_owners, owner_count = np.unique(owners, return_counts=True) |
| 373 |
# FIXME: In C++ use NBX to find neighbourhood |
| 374 |
_tmp_comm = mesh.comm.Create_dist_graph( |
| 375 |
[mesh.comm.rank], [len(unique_owners)], unique_owners, reorder=False |
| 376 |
) |
| 377 |
source, dest, _ = _tmp_comm.Get_dist_neighbors() |
| 378 |
_tmp_comm.Free() |
| 379 |
# Strip out any / |
| 380 |
group = group.strip("/") |
| 381 |
if step is not None: |
| 382 |
group = f"{group}/{group}_{step}" |
| 383 |
vector_group = "vector" |
| 384 |
else: |
| 385 |
vector_group = "vector_0" |
| 386 |
|
| 387 |
# ----------------------Step 2-------------------------------- |
| 388 |
# Get global dofmap indices from input process |
| 389 |
bs = V.dofmap.bs |
| 390 |
num_cells_global = mesh.topology.index_map(mesh.topology.dim).size_global |
| 391 |
dofmap_indices = send_cells_and_receive_dofmap_index( |
| 392 |
filename, |
| 393 |
comm, |
| 394 |
np.asarray(source, dtype=np.int32), |
| 395 |
np.asarray(dest, dtype=np.int32), |
| 396 |
owner_count.astype(np.int32), |
| 397 |
owners, |
| 398 |
input_cells, |
| 399 |
dof_pos, |
| 400 |
num_cells_global, |
| 401 |
f"/{group}/cell_dofs", |
| 402 |
f"/{group}/x_cell_dofs", |
| 403 |
"HDF5", |
| 404 |
bs, |
| 405 |
) |
| 406 |
|
| 407 |
# ----------------------Step 3--------------------------------- |
| 408 |
# Compute owner of global dof on distributed mesh |
| 409 |
num_dof_global = V.dofmap.index_map_bs * V.dofmap.index_map.size_global |
| 410 |
dof_owner = index_owner(comm=mesh.comm, indices=dofmap_indices, N=num_dof_global) |
| 411 |
# Create MPI neigh comm to owner. |
| 412 |
# NOTE: USE NBX in C++ |
| 413 |
|
| 414 |
# Read input data |
| 415 |
adios = adios2.ADIOS(comm) |
| 416 |
local_array, starting_pos = read_array( |
| 417 |
adios, filename, f"/{group}/{vector_group}", "HDF5", comm, legacy=True |
| 418 |
) |
| 419 |
|
| 420 |
# Send global dof indices to correct input process, and receive value of given dof |
| 421 |
local_values = send_dofs_and_recv_values( |
| 422 |
dofmap_indices, dof_owner, comm, local_array, starting_pos |
| 423 |
) |
| 424 |
|
| 425 |
# ----------------------Step 4--------------------------------- |
| 426 |
# Populate local part of array and scatter forward |
| 427 |
u.x.array[: len(local_values)] = local_values |
| 428 |
u.x.scatter_forward() |