import json
import logging
import os
import shutil
import warnings
from dataclasses import dataclass, field
from importlib.metadata import version
from pathlib import Path
from typing import Any
from mpi4py import MPI
import dolfinx
import io4dolfinx
import ufl
from . import utils
from .metadata import FORMAT, FormatError, read_metadata, write_metadata
from .standard import FIBER_NAMES
logger = logging.getLogger(__name__)
#: io4dolfinx backends that support checkpointing (mesh, meshtags and functions),
#: mapped to the file suffix used for the geometry file.
IO_BACKEND_SUFFIXES: dict[str, str] = {"adios2": ".bp", "h5py": ".h5"}
IO_BACKENDS: tuple[str, ...] = tuple(IO_BACKEND_SUFFIXES)
#: io4dolfinx 2.0's default, and what pulse, beat and simcardemsx write.
DEFAULT_IO_BACKEND = "h5py"
def check_io_backend(backend: str) -> str:
if backend not in IO_BACKEND_SUFFIXES:
raise ValueError(f"Unsupported io backend {backend!r}, expected one of {IO_BACKENDS}")
return backend
[docs]
def geometry_path(folder: str | Path, backend: str = DEFAULT_IO_BACKEND) -> Path:
"""Path of the geometry file in `folder` written with `backend`,
i.e. ``geometry.bp`` for adios2 and ``geometry.h5`` for h5py."""
return Path(folder) / f"geometry{IO_BACKEND_SUFFIXES[check_io_backend(backend)]}"
#: The order in which :func:`find_geometry_file` looks for a folder's geometry file.
FIND_ORDER: tuple[str, ...] = ("h5py", "adios2")
[docs]
def find_geometry_file(folder: str | Path) -> Path | None:
"""The geometry file in `folder`: ``geometry.h5``, else ``geometry.bp``, else None."""
found = [
path for path in (geometry_path(folder, backend) for backend in FIND_ORDER) if path.exists()
]
if len(found) > 1:
logger.warning(
f"{folder} holds both {found[0].name} and {found[1].name}; reading {found[0].name}"
)
return found[0] if found else None
[docs]
def infer_io_backend(path: str | Path) -> str:
"""Infer the io4dolfinx backend from the suffix of `path`: adios2 for ``.bp``,
h5py for ``.h5``/``.hdf5``, and :data:`DEFAULT_IO_BACKEND` for any other suffix."""
suffix = Path(path).suffix.lower()
if suffix == ".bp":
return "adios2"
if suffix in (".h5", ".hdf5"):
return "h5py"
return DEFAULT_IO_BACKEND
def _remove_path(path: Path) -> None:
if path.is_dir():
shutil.rmtree(path, ignore_errors=True)
else:
path.unlink(missing_ok=True)
def info_path(path: Path) -> Path:
return path.parent / f"info_{path.stem}.json"
def markers_path(path: Path) -> Path:
return path.parent / f"markers_{path.stem}.json"
def microstructure_path(path: Path) -> Path:
return path.parent / f"microstructure_{path.stem}.json"
def additional_data_path(path: Path) -> Path:
return path.parent / f"additional_data_{path.stem}.json"
def _read_json(path: Path, comm: MPI.Comm) -> Any:
"""The JSON document in `path`, read on rank 0 and sent to every rank, or {} if there is
no such file."""
content = json.loads(path.read_text()) if comm.rank == 0 and path.exists() else {}
return comm.bcast(content, root=0)
def _read_additional_data(
attributes: dict[str, dict[str, Any]],
path: Path,
mesh: dolfinx.mesh.Mesh,
backend: str,
) -> tuple[dict[str, dolfinx.mesh.MeshTags | dolfinx.fem.Function], dict[str, dict[str, Any]]]:
"""Read the entries of ``additional_data`` that `attributes` describes from `path`.
Returns the data, and for each entry read its attributes other than its ``type`` and
``element`` (its ``unit``, ``values``, ``description`` and ``recipe``).
"""
additional_data: dict[str, dolfinx.mesh.MeshTags | dolfinx.fem.Function] = {}
additional_data_info: dict[str, dict[str, Any]] = {}
for name, attr in attributes.items():
if attr["type"] == "MeshTags":
additional_data[name] = io4dolfinx.read_meshtags(
mesh=mesh, meshtag_name=name, filename=path, backend=backend
)
elif attr["type"] == "Function":
V = utils.array2functionspace(mesh, tuple(attr["element"]))
f = dolfinx.fem.Function(V, name=name)
io4dolfinx.read_function(u=f, filename=path, name=name, backend=backend)
additional_data[name] = f
else:
logger.warning(
f"Additional data '{name}' of type {attr['type']} "
"is not supported and will not be loaded."
)
continue
additional_data_info[name] = {
key: value for key, value in attr.items() if key not in ("type", "element")
}
return additional_data, additional_data_info
[docs]
def load_additional_data(
path: Path,
mesh: dolfinx.mesh.Mesh,
backend: str | None = None,
) -> dict[str, dolfinx.mesh.MeshTags | dolfinx.fem.Function]:
"""Read the ``additional_data`` of the file `path`, which its metadata describes (format 1)
or ``additional_data_<stem>.json`` beside it (format 0)."""
backend = check_io_backend(backend or infer_io_backend(path))
document = read_metadata(path, mesh.comm, backend)
if document is None:
attributes = _read_json(additional_data_path(path), mesh.comm)
else:
attributes = document["additional_data"]
return _read_additional_data(attributes, path, mesh, backend)[0]
def _other_backend_files(path: Path) -> list[Path]:
"""The geometry files of the same stem as `path` beside it, written with another backend.
A warning names them: a folder that holds both is read through :func:`find_geometry_file`."""
others = [
path.with_suffix(suffix)
for suffix in IO_BACKEND_SUFFIXES.values()
if suffix != path.suffix and path.with_suffix(suffix).exists()
]
if others:
preferred = path.with_suffix(IO_BACKEND_SUFFIXES[FIND_ORDER[0]])
names = ", ".join(other.name for other in others)
logger.warning(
f"{path.parent} holds {names} beside {path.name}, and saving keeps it. Where a "
f"folder holds both, find_geometry_file reads {preferred.name}; remove the one you "
"do not want."
)
return others
[docs]
def save_geometry(
path: Path,
mesh: dolfinx.mesh.Mesh,
markers: dict[str, tuple[int, int]] | None = None,
info: dict[str, Any] | None = None,
cfun: dolfinx.mesh.MeshTags | None = None,
ffun: dolfinx.mesh.MeshTags | None = None,
efun: dolfinx.mesh.MeshTags | None = None,
vfun: dolfinx.mesh.MeshTags | None = None,
f0: dolfinx.fem.Function | None = None,
s0: dolfinx.fem.Function | None = None,
n0: dolfinx.fem.Function | None = None,
additional_data: dict[str, dolfinx.mesh.MeshTags | dolfinx.fem.Function] | None = None,
backend: str | None = None,
unit: str | None = None,
additional_data_info: dict[str, dict[str, Any]] | None = None,
) -> None:
"""Save a geometry to `path` as one io4dolfinx file of format 1.
The file holds the mesh, the tags, the fibres, `additional_data` and, written last, the
metadata (:mod:`cardiac_geometries.metadata`): `markers`, the fibres' elements, the type and
element of each entry of `additional_data` with its `additional_data_info`, `info`, `unit`
and the format. Nothing is written beside the file. The metadata's copy of `info` records
the version of cardiac-geometriesx that wrote the file as ``cardiac_geometry_version``,
replacing any earlier value; `info` itself is not changed.
Deleted first, on rank 0: any file at `path`, and the JSON files that a format-0 file of
the same stem kept beside it (``markers_<stem>.json``, ``info_<stem>.json``,
``microstructure_<stem>.json`` and ``additional_data_<stem>.json``), which would describe
another file. A file of the same stem written with the other backend is kept, with a
warning, and so are the JSON files, which may be that file's: a folder that holds both is
read through :func:`find_geometry_file`, which picks ``geometry.h5``, and the format-1 file
ignores them.
`backend` is the io4dolfinx backend ("adios2" or "h5py"). If None it is
inferred from the suffix of `path` (:func:`infer_io_backend`).
"""
path = Path(path)
backend = check_io_backend(backend or infer_io_backend(path))
comm = mesh.comm
if comm.rank == 0:
_remove_path(path)
# The JSON files of the stem belong to a format-0 file of the other backend, if any
if not _other_backend_files(path):
for sidecar in (markers_path, info_path, microstructure_path, additional_data_path):
_remove_path(sidecar(path))
comm.barrier()
io4dolfinx.write_mesh(mesh=mesh, filename=path, backend=backend)
for tags, meshtag_name in (
(cfun, "Cell tags"),
(ffun, "Facet tags"),
(efun, "Edge tags"),
(vfun, "Vertex tags"),
):
if tags is not None:
# The tags of edges need the edges, which writing a mesh to XDMF used to create
mesh.topology.create_entities(tags.dim)
io4dolfinx.write_meshtags(
meshtags=tags,
mesh=mesh,
filename=path,
meshtag_name=meshtag_name,
backend=backend,
)
microstructure: dict[str, Any] = {}
for name, u in zip(FIBER_NAMES, (f0, s0, n0)):
if u is not None:
io4dolfinx.write_function(u=u, filename=path, name=name, backend=backend)
microstructure[name] = utils.element2array(u.ufl_element())
data_info = additional_data_info or {}
for name in data_info.keys() - (additional_data or {}).keys():
logger.warning(f"Not saving the info of {name!r}, which has no data in additional_data")
additional_data_attributes: dict[str, dict[str, Any]] = {}
for name, data in (additional_data or {}).items():
attributes: dict[str, Any]
if isinstance(data, dolfinx.mesh.MeshTags):
io4dolfinx.write_meshtags(
meshtags=data,
mesh=mesh,
filename=path,
meshtag_name=name,
backend=backend,
)
attributes = {"type": "MeshTags"}
elif isinstance(data, dolfinx.fem.Function):
io4dolfinx.write_function(u=data, filename=path, name=name, backend=backend)
attributes = {"type": "Function", "element": utils.element2array(data.ufl_element())}
else:
logger.warning(
f"Additional data '{name}' of type {type(data)} "
"is not supported and will not be saved."
)
continue
# The type and element describe what was written, so the info cannot replace them
for key, value in data_info.get(name, {}).items():
attributes.setdefault(key, value)
additional_data_attributes[name] = attributes
write_metadata(
path,
comm,
{
"format": FORMAT,
"unit": unit,
"markers": markers or {},
"microstructure": microstructure,
"additional_data": additional_data_attributes,
# The version that wrote the file, which a reader of a later format names
"info": {**(info or {}), "cardiac_geometry_version": version("cardiac-geometriesx")},
},
backend,
)
comm.barrier()
[docs]
@dataclass
class Geometry:
mesh: dolfinx.mesh.Mesh
markers: dict[str, tuple[int, int]] = field(default_factory=dict)
cfun: dolfinx.mesh.MeshTags | None = None
ffun: dolfinx.mesh.MeshTags | None = None
efun: dolfinx.mesh.MeshTags | None = None
vfun: dolfinx.mesh.MeshTags | None = None
f0: dolfinx.fem.Function | None = None
s0: dolfinx.fem.Function | None = None
n0: dolfinx.fem.Function | None = None
info: dict[str, Any] = field(default_factory=dict)
additional_data: dict[str, dolfinx.mesh.MeshTags | dolfinx.fem.Function] = field(
default_factory=dict
)
quadrature_degree: int = 4
#: The unit of the coordinates, one of :data:`~cardiac_geometries.metadata.UNITS`.
unit: str | None = None
#: Per entry of `additional_data`, its ``unit``, ``values``, ``description`` and ``recipe``.
additional_data_info: dict[str, dict[str, Any]] = field(default_factory=dict)
#: The format of the file the geometry was read from, 0 or 1; None in memory.
file_format: int | None = None
[docs]
def save(self, path: str | Path, backend: str | None = None) -> None:
"""Save the geometry to one file using io4dolfinx (:func:`save_geometry`).
The file is of format 1: its metadata is inside it, and nothing is written beside it.
Parameters
----------
path : str | Path
The path to the file where the geometry will be saved.
The file will be created if it does not exist, or overwritten if it does.
backend : str | None, optional
The io4dolfinx backend, "adios2" or "h5py". By default it is inferred
from the suffix of `path` (:func:`infer_io_backend`).
"""
path = Path(path)
save_geometry(
path=path,
mesh=self.mesh,
markers=self.markers,
info=self.info,
cfun=self.cfun,
ffun=self.ffun,
efun=self.efun,
vfun=self.vfun,
f0=self.f0,
s0=self.s0,
n0=self.n0,
additional_data=self.additional_data,
backend=backend,
unit=self.unit,
additional_data_info=self.additional_data_info,
)
[docs]
def save_replacing(self, path: str | Path) -> None:
"""Save the geometry over the existing file `path` (:meth:`save`), so that a failure
leaves the original file.
The geometry is saved beside `path` under a hidden name, and rank 0 then swaps it in.
`path` may be a directory (adios2's ``.bp``), which :func:`os.replace` cannot put over a
non-empty one, so the original is first moved aside, and removed once the new file is in
place. Every rank raises :class:`RuntimeError` if the swap fails, so that no rank is left
waiting at a collective call.
"""
path = Path(path)
comm = self.mesh.comm
tmp = path.with_name(f".{path.stem}.save-tmp{path.suffix}")
old = path.with_name(f".{path.stem}.save-old{path.suffix}")
def restore() -> None:
if comm.rank == 0:
if not path.exists() and old.exists():
os.replace(old, path)
_remove_path(tmp)
try:
self.save(tmp)
except BaseException:
restore()
raise
comm.Barrier()
error: str | None = None
if comm.rank == 0:
try:
_remove_path(old)
os.replace(path, old)
os.replace(tmp, path)
_remove_path(old)
except Exception as e:
error = f"{type(e).__name__}: {e}"
try:
restore()
except Exception as e2:
error += f" (and restoring the original failed: {type(e2).__name__}: {e2})"
except BaseException:
restore()
raise
error = comm.bcast(error, root=0)
if error is not None:
raise RuntimeError(f"Could not replace {path} with the saved geometry: {error}")
[docs]
def save_folder(self, folder: str | Path, backend: str = DEFAULT_IO_BACKEND) -> None:
"""Save the geometry to a folder containing mesh and markers files.
.. deprecated::
Use :meth:`Geometry.save`, which writes one self-describing file.
Parameters
----------
folder : str | Path
The path to the folder where the geometry will be saved.
The folder will be created if it does not exist.
backend : str, optional
The io4dolfinx backend used for the geometry file, "adios2" (written to
``geometry.bp``) or "h5py" (written to ``geometry.h5``), by default "h5py".
"""
warnings.warn(
"Geometry.save_folder is deprecated; use Geometry.save, which writes one file "
"that holds the metadata too.",
DeprecationWarning,
stacklevel=2,
)
comm = self.mesh.comm
folder = Path(folder)
folder.mkdir(parents=True, exist_ok=True)
utils.save_mesh_to_xdmf(
comm=comm,
fname=folder / "mesh.xdmf",
mesh=self.mesh,
ct=self.cfun,
ft=self.ffun,
et=self.efun,
vt=self.vfun,
)
if comm.rank == 0:
(folder / "markers.json").write_text(json.dumps(self.markers, indent=4))
(folder / "info.json").write_text(json.dumps(self.info, indent=4))
self.save(geometry_path(folder, backend), backend=backend)
logger.info(f"Geometry saved to {folder}")
@property
def dx(self):
"""Volume measure for the mesh using
the cell function `cfun` if it exists as subdomain data.
"""
return ufl.Measure(
"dx",
domain=self.mesh,
subdomain_data=self.cfun,
metadata={"quadrature_degree": self.quadrature_degree},
)
@property
def ds(self):
"""Surface measure for the mesh using
the facet function `ffun` if it exists as subdomain data.
"""
return ufl.Measure(
"ds",
domain=self.mesh,
subdomain_data=self.ffun,
metadata={"quadrature_degree": self.quadrature_degree},
)
@property
def facet_normal(self) -> ufl.FacetNormal:
"""Facet normal vector for the mesh."""
return ufl.FacetNormal(self.mesh)
@property
def facet_tags(self) -> dolfinx.mesh.MeshTags | None:
return self.ffun
[docs]
def refine(self, n=1, outdir: Path | None = None) -> "Geometry":
"""
Refine the mesh and transfer the meshtags to new geometry.
Also regenerate fibers if `self.info` is found.
If `self.info` is not found, it currently raises a
NotImplementedError, however fiber could be interpolated
from the old mesh to the new mesh but this will result in a
loss of information about the fiber orientation.
Parameters
----------
n : int, optional
Number of times to refine the mesh, by default 1
outdir : Path | None, optional
Output directory to save the refined mesh and meshtags,
by default None in which case the mesh is not saved.
Returns
-------
Geometry
A new Geometry object with the refined mesh and updated meshtags.
Raises
------
NotImplementedError
If `self.info` is not found, indicating that fiber
interpolation after refinement is not implemented yet.
"""
mesh = self.mesh
cfun = self.cfun
ffun = self.ffun
for _ in range(n):
# Newer versions of dolfinx require the edges to be created before refining
mesh.topology.create_entities(1)
new_mesh, parent_cell, parent_facet = dolfinx.mesh.refine(
mesh,
partitioner=None,
option=dolfinx.mesh.RefinementOption.parent_cell_and_facet,
)
assert parent_cell is not None
new_mesh.name = mesh.name
mesh = new_mesh
new_mesh.topology.create_entities(1)
new_mesh.topology.create_connectivity(2, 3)
if cfun is not None:
new_cfun = dolfinx.mesh.transfer_meshtag(cfun, new_mesh, parent_cell, parent_facet)
new_cfun.name = cfun.name
cfun = new_cfun
else:
new_cfun = None
if ffun is not None:
new_ffun = dolfinx.mesh.transfer_meshtag(ffun, new_mesh, parent_cell, parent_facet)
new_ffun.name = ffun.name
ffun = new_ffun
else:
new_ffun = None
if outdir is not None:
outdir = Path(outdir)
outdir.mkdir(parents=True, exist_ok=True)
utils.save_mesh_to_xdmf(
new_mesh.comm, outdir / "mesh.xdmf", new_mesh, cfun, ffun, None, None
)
if self.info is not None:
info = self.info.copy()
info["refinement"] = n
info.pop("outdir", None)
if outdir is not None:
info["outdir"] = str(outdir)
from .fibers import generate_fibers
f0, s0, n0 = generate_fibers(
mesh=new_mesh, ffun=new_ffun, cfun=new_cfun, markers=self.markers, **info
)
else:
info = None
# Interpolate fibers
raise NotImplementedError(
"Interpolating fibers after refinement is not implemented yet."
)
return Geometry(
mesh=new_mesh,
markers=self.markers,
cfun=new_cfun,
ffun=new_ffun,
f0=f0,
s0=s0,
n0=n0,
unit=self.unit,
)
[docs]
@classmethod
def from_file(
cls,
comm: MPI.Comm,
path: str | Path,
ghost_mode: dolfinx.mesh.GhostMode = dolfinx.mesh.GhostMode.none,
backend: str | None = None,
) -> "Geometry":
"""Read geometry from a file using io4dolfinx.
A file of format 1 holds its metadata. A file without it is of format 0, written
before format 1, whose metadata is read from the JSON files beside it
(``markers_<stem>.json``, ``info_<stem>.json``, ``microstructure_<stem>.json`` and
``additional_data_<stem>.json``), those that exist.
Parameters
----------
comm : MPI.Comm
The MPI communicator to use for reading the mesh.
path : str | Path
The path to the file containing the geometry data.
ghost_mode : dolfinx.mesh.GhostMode, optional
The ghost mode to use when reading the mesh, by default
dolfinx.mesh.GhostMode.none.
Note that if you need to refine the mesh later, you should
use dolfinx.mesh.GhostMode.none.
backend : str | None, optional
The io4dolfinx backend, "adios2" or "h5py". By default it is inferred
from the suffix of `path` (:func:`infer_io_backend`).
Returns
-------
Geometry
An instance of the Geometry class containing the mesh, markers, and functions.
Raises
------
ValueError
If `path` does not exist.
FormatError
If the file is of a higher format than this version of cardiac-geometriesx reads.
"""
path = Path(path)
if not path.exists():
raise ValueError(f"File {path} does not exist")
backend = check_io_backend(backend or infer_io_backend(path))
document = read_metadata(path, comm, backend)
if document is None:
file_format = 0
unit = None
markers = _read_json(markers_path(path), comm)
info = _read_json(info_path(path), comm)
microstructure = _read_json(microstructure_path(path), comm)
additional_data_attributes = _read_json(additional_data_path(path), comm)
else:
file_format = document["format"]
if file_format > FORMAT:
# Only `format` is known to mean the same in every format
version = document.get("info", {}).get("cardiac_geometry_version", "unknown")
needed = (
"a later cardiac-geometriesx (the version that wrote it is unknown)"
if version == "unknown"
else f"cardiac-geometriesx {version}, the version that wrote it, or later"
)
raise FormatError(
f"{path} is a geometry file of format {file_format}, and this version of "
f"cardiac-geometriesx reads format {FORMAT} and older. Reading it needs "
f"{needed}."
)
info = document["info"]
unit = document["unit"]
markers = document["markers"]
microstructure = document["microstructure"]
additional_data_attributes = document["additional_data"]
mesh = io4dolfinx.read_mesh(
comm=comm,
filename=path,
ghost_mode=ghost_mode,
backend=backend,
)
tags: dict[str, dolfinx.mesh.MeshTags | None] = {}
for name, meshtag_name in (
("cfun", "Cell tags"),
("ffun", "Facet tags"),
("efun", "Edge tags"),
("vfun", "Vertex tags"),
):
try:
tags[name] = io4dolfinx.read_meshtags(
mesh=mesh, meshtag_name=meshtag_name, filename=path, backend=backend
)
except (KeyError, IndexError):
logger.debug(f"{name} not found in {path}")
tags[name] = None
functions: dict[str, dolfinx.fem.Function] = {}
assert isinstance(microstructure, dict), "microstructure must be a dictionary"
for name, el in microstructure.items():
V = utils.array2functionspace(mesh, tuple(el))
f = dolfinx.fem.Function(V, name=name)
try:
io4dolfinx.read_function(u=f, filename=path, name=name, backend=backend)
except KeyError:
if file_format >= 1:
raise KeyError(
f"{path} lists the fibre {name!r} in its metadata, but holds no "
"such function: the file is corrupt"
) from None
continue
else:
functions[name] = f
additional_data, additional_data_info = _read_additional_data(
additional_data_attributes, path, mesh, backend
)
return cls(
mesh=mesh,
markers=markers,
info=info,
additional_data=additional_data,
cfun=tags.get("cfun"),
ffun=tags.get("ffun"),
efun=tags.get("efun"),
vfun=tags.get("vfun"),
f0=functions.get("f0"),
s0=functions.get("s0"),
n0=functions.get("n0"),
unit=unit,
additional_data_info=additional_data_info,
file_format=file_format,
)
[docs]
@classmethod
def from_folder(
cls,
comm: MPI.Comm,
folder: str | Path,
ghost_mode: dolfinx.mesh.GhostMode = dolfinx.mesh.GhostMode.none,
) -> "Geometry":
"""Read geometry from a folder containing mesh and markers files.
.. deprecated::
Use :meth:`Geometry.from_file`, which reads one self-describing file.
Parameters
----------
comm : MPI.Comm
The MPI communicator to use for reading the mesh and markers.
folder : str | Path
The path to the folder containing the geometry data.
ghost_mode : dolfinx.mesh.GhostMode, optional
The ghost mode to use when reading the mesh, by default
dolfinx.mesh.GhostMode.none.
Note that if you need to refine the mesh later, you should
use dolfinx.mesh.GhostMode.none.
Returns
-------
Geometry
An instance of the Geometry class containing the mesh, markers, and functions.
Raises
------
ValueError
If the required mesh file is not found in the specified folder.
"""
warnings.warn(
"Geometry.from_folder is deprecated; use Geometry.from_file on the geometry "
"file, geometry.h5 or geometry.bp.",
DeprecationWarning,
stacklevel=2,
)
folder = Path(folder)
logger.info(f"Reading geometry from {folder}")
if not folder.exists():
raise ValueError(f"Folder {folder} does not exist")
path = find_geometry_file(folder)
if path is not None:
logger.debug(f"Reading geometry from {path.name}")
return cls.from_file(comm=comm, path=path, ghost_mode=ghost_mode)
logger.warning(
"geometry.bp/geometry.h5 not found, reading mesh and microstructure separately. "
"This may lead to inconsistent dof numbering in the mesh and microstructure. "
"Try deleting the folder and regenerating the mesh."
)
# Read mesh
if (folder / "mesh.xdmf").exists():
logger.debug("Reading mesh")
mesh, tags = utils.read_mesh(
comm=comm, filename=folder / "mesh.xdmf", ghost_mode=ghost_mode
)
else:
raise ValueError("No mesh file found")
# Read markers
if (folder / "markers.json").exists():
logger.debug("Reading markers")
if comm.rank == 0:
markers = json.loads((folder / "markers.json").read_text())
else:
markers = {}
markers = comm.bcast(markers, root=0)
else:
markers = {}
if (folder / "microstructure.json").exists():
if comm.rank == 0:
microstructure = json.loads((folder / "microstructure.json").read_text())
else:
microstructure = {}
microstructure = comm.bcast(microstructure, root=0)
else:
microstructure = {}
functions: dict[str, dolfinx.fem.Function] = {}
microstructure_path = folder / "microstructure.bp"
if microstructure_path.exists():
logger.debug("Reading microstructure")
# function_space = io4dolfinx.read_attributes(
# comm=MPI.COMM_WORLD, filename=microstructure_path, name="function_space"
# )
for name, el in microstructure.items():
logger.debug(f"Reading {name}")
V = utils.array2functionspace(mesh, tuple(el))
f = dolfinx.fem.Function(V, name=name)
try:
io4dolfinx.read_function(u=f, filename=microstructure_path, name=name)
except KeyError:
continue
else:
functions[name] = f
if (folder / "info.json").exists():
logger.debug("Reading info")
if comm.rank == 0:
info = json.loads((folder / "info.json").read_text())
else:
info = {}
info = comm.bcast(info, root=0)
else:
info = {}
return cls(
mesh=mesh,
markers=markers,
info=info,
cfun=tags.get("cfun"),
ffun=tags.get("ffun"),
efun=tags.get("efun"),
vfun=tags.get("vfun"),
f0=functions.get("f0"),
s0=functions.get("s0"),
n0=functions.get("n0"),
)
[docs]
def rotate(self, target_normal, base_marker):
"""Rotate the geometry so that the base normal aligns with the target normal.
Parameters
----------
target_normal : np.ndarray
The target normal vector to align the base normal with.
base_marker : str
The marker for the base of the geometry.
Returns
-------
Geometry
The rotated Geometry object. Only returned if inplace is False.
"""
from . import utils
msg = (
f"Base marker '{base_marker}' not found in markers. "
f"Available markers: {list(self.markers.keys())}"
)
assert base_marker in self.markers, msg
fields = [f for f in (self.f0, self.s0, self.n0) if f is not None]
mesh_rotated, R_matrix, fields_rotated = utils.rotate_geometry_and_fields(
mesh=self.mesh,
ffun=self.ffun,
base_marker=self.markers[base_marker][0],
target_normal=target_normal,
fields=fields,
)
if self.f0 is not None:
f0, s0, n0 = fields_rotated
else:
f0 = None
s0 = None
n0 = None
self.info["rotation_matrix"] = R_matrix.tolist()
if self.additional_data:
logger.warning(
"rotate does not carry additional_data over: dropping "
f"{', '.join(map(repr, self.additional_data))}"
)
return Geometry(
mesh=mesh_rotated,
markers=self.markers,
cfun=self.cfun,
ffun=self.ffun,
efun=self.efun,
vfun=self.vfun,
f0=f0,
s0=s0,
n0=n0,
info=self.info,
unit=self.unit,
additional_data_info={},
)