Source code for cardiac_geometries.convert

"""Convert an existing geometry into one file of format 1, through a mapping (``geox convert``)."""

import json
import tomllib
import warnings
from collections.abc import Mapping
from pathlib import Path
from typing import Any

from mpi4py import MPI

import dolfinx
import io4dolfinx

from . import __version__, utils
from .check import check, has_errors
from .geometry import Geometry, find_geometry_file, infer_io_backend
from .input_tables import (
    DATA_FIELD_KEYS,
    FIELD_KEYS,
    check_field_keys,
    tag_map,
)
from .metadata import UNITS
from .standard import FIELD_INFO_KEYS

MAPPING_KEYS = ("unit", "facets", "cells", "fields", "info")


[docs] def load_mapping(path: Path) -> dict[str, Any]: """Read a mapping from the TOML file `path`. The tags of ``[cells]`` become integers.""" with open(path, "rb") as f: return _validate(tomllib.load(f))
def _validate(mapping: Mapping[str, Any]) -> dict[str, Any]: unknown = sorted(set(mapping) - set(MAPPING_KEYS)) if unknown: raise ValueError( f"Unknown keys in the mapping: {', '.join(map(repr, unknown))}. " f"A mapping has {', '.join(MAPPING_KEYS)}." ) result = dict(mapping) result["cells"] = tag_map(mapping.get("cells", {})) for name, field in mapping.get("fields", {}).items(): check_field_keys(name, field, FIELD_KEYS, "fields") missing = [k for k in ("file", "name", "element") if k not in field] if missing: raise ValueError(f"[fields.{name}] lacks {', '.join(missing)}") return result DATA_KEYS = ("cell_tags", "cells", "fibers", "fields")
[docs] def load_volume_data(path: Path) -> dict[str, Any]: """Read the TOML file of ``geox from-volume --data`` as the keyword arguments of :func:`cardiac_geometries.mesh.from_volume`: ``cell_tags``, ``cell_names`` (the tags of ``[cells]`` as integers, as in a mapping of :func:`convert`), ``fibers`` and ``fields``.""" with open(path, "rb") as f: data = tomllib.load(f) unknown = sorted(set(data) - set(DATA_KEYS)) if unknown: raise ValueError( f"Unknown keys in the data file: {', '.join(map(repr, unknown))}. " f"It has {', '.join(DATA_KEYS)}." ) result: dict[str, Any] = {} if "cell_tags" in data: if not isinstance(data["cell_tags"], str): raise ValueError(f"cell_tags must be the name of an array, got {data['cell_tags']!r}") result["cell_tags"] = data["cell_tags"] if "cells" in data: result["cell_names"] = tag_map(data["cells"]) if "fibers" in data: fibers = data["fibers"] if not isinstance(fibers, Mapping) or not all(isinstance(v, str) for v in fibers.values()): raise ValueError(f'[fibers] must be a table of name = "array", got {fibers!r}') result["fibers"] = dict(fibers) if "fields" in data: if not isinstance(data["fields"], Mapping): raise ValueError(f"[fields] must hold one table per field, got {data['fields']!r}") for name, field in data["fields"].items(): check_field_keys(name, field, DATA_FIELD_KEYS, "fields") result["fields"] = {name: dict(field) for name, field in data["fields"].items()} return result
[docs] def function_names(path: Path, backend: str) -> list[str]: """The names of the functions the io4dolfinx file `path` holds. io4dolfinx's adios2 backend cannot list them, so there they are the names that have both ``<name>_values`` and ``<name>_XDofmap`` variables.""" if backend == "adios2": import adios2 with adios2.FileReader(str(path)) as reader: variables = set(reader.available_variables()) return sorted( v[: -len("_values")] for v in variables if v.endswith("_values") and f"{v[: -len('_values')]}_XDofmap" in variables ) return list(io4dolfinx.read_function_names(path, MPI.COMM_SELF, backend=backend))
[docs] def recorded_sizes(path: Path, name: str, backend: str, field: str = "") -> tuple[int, int]: """The number of values and of cells that the io4dolfinx file `path` records for the function `name`. adios2 records the global shapes of the variables ``<name>_values`` and ``<name>_XDofmap`` (the cells plus one), h5py the datasets ``mesh/functions/<name>/<time>/array`` and ``dofmap_offsets`` (again the cells plus one). `field` is the name in the mapping, for messages. Raises ValueError if the function is not in the file, or if the file's layout is not the one this version reads, so the size cannot be verified. """ field = field or name held = function_names(path, backend) if name not in held: raise ValueError( f"The field {field!r} asks for {name!r} in {path}, which holds " f"{', '.join(map(repr, held)) or 'no functions'}" ) def unreadable(what: str) -> ValueError: return ValueError( f"cannot verify the size of field {field!r} in {path}: {what}. io4dolfinx's file " "layout is not the one this version of cardiac-geometriesx reads" ) if backend == "adios2": import adios2 with adios2.FileReader(str(path)) as reader: variables = reader.available_variables() try: values = int(variables[f"{name}_values"]["Shape"]) cells = int(variables[f"{name}_XDofmap"]["Shape"]) - 1 except (KeyError, ValueError) as e: raise unreadable(f"no usable {name}_values or {name}_XDofmap ({e!r})") from e return values, cells import h5py times = io4dolfinx.read_timestamps(path, MPI.COMM_SELF, name, backend=backend) with h5py.File(path, "r") as f: group = f[f"mesh/functions/{name}"] keys = [k for k in group if k not in ("dofmap", "dofmap_offsets")] match = [k for k in keys if len(times) and _same_time(k, times[0])] try: values = int(group[match[0]]["array"].shape[0]) cells = int(group["dofmap_offsets"].shape[0]) - 1 except (IndexError, KeyError, ValueError) as e: raise unreadable(f"no time group, array or dofmap_offsets ({e!r})") from e return values, cells
def _same_time(key: str, stamp: Any) -> bool: try: return float(key) == float(stamp) except ValueError: return False
[docs] def read_field( path: Path, mesh: dolfinx.mesh.Mesh, name: str, source_name: str, element: str ) -> dolfinx.fem.Function: """Read the field `source_name` of the io4dolfinx file `path` as `name` on `element`. Raises ValueError, naming `name`, if the file or the field is missing, or the field is of another size than the mesh and the element: the number of values and of cells are compared before anything is read.""" where = f"field {name!r} ({source_name!r} in {path})" if not path.exists(): raise ValueError(f"The file of the {where} does not exist") V = utils.space_from_string(element, mesh, dim=1) backend = infer_io_backend(path) values, cells = recorded_sizes(path, source_name, backend, field=name) expected_values = V.dofmap.index_map.size_global * V.dofmap.index_map_bs expected_cells = mesh.topology.index_map(mesh.topology.dim).size_global if (values, cells) != (expected_values, expected_cells): raise ValueError( f"The {where} does not belong to this mesh: the file holds {values} values on " f"{cells} cells, and {element} on the mesh needs {expected_values} values on " f"{expected_cells} cells" ) u = dolfinx.fem.Function(V, name=name) try: times = io4dolfinx.read_timestamps(path, MPI.COMM_SELF, source_name, backend=backend) io4dolfinx.read_function( u=u, filename=path, name=source_name, backend=backend, time=times[0] ) except Exception as e: raise ValueError(f"The {where} could not be read: {type(e).__name__}: {e}") from e return u
def _is_folder(source: Path) -> bool: """An old folder, as opposed to a geometry file. An adios2 file is a directory too, so a directory with a ``.bp`` suffix, or with a suffix and no geometry file inside, is a file.""" if not source.is_dir(): return False if source.suffix.lower() == ".bp": return False return find_geometry_file(source) is not None or not source.suffix def _refuse_to_delete_the_source(source: Path, out: Path) -> None: """Saving `out` replaces a file at `out` and deletes the JSON files of its stem, which a format-0 source keeps its markers and fibres in, so `out` must not be the source's geometry file nor share its folder and stem.""" src_file = find_geometry_file(source) if _is_folder(source) else source if src_file is None: return src_file, out = src_file.resolve(), out.resolve() same_stem = out.parent == src_file.parent and out.stem == src_file.stem if out == src_file or same_stem: raise ValueError( f"Saving {out.name} would replace the source's file {src_file.name} in " f"{src_file.parent}, or delete the JSON files of its stem: write the result under " "another name or folder" )
[docs] def convert( source: Path, out: Path, mapping: Path | Mapping[str, Any], comm: MPI.Comm = MPI.COMM_WORLD, ) -> Geometry: """Convert the geometry `source`, a file of any format or an old folder, into the file `out` of format 1, through `mapping` (a TOML file or the dict it reads as). The result is checked before anything is written; any error raises ValueError. """ if comm.size > 1: raise RuntimeError("convert runs on one rank; run it without mpirun") source, out = Path(source), Path(out) _refuse_to_delete_the_source(source, out) if isinstance(mapping, Mapping): spec, mapping_name = _validate(mapping), "inline" else: spec, mapping_name = load_mapping(Path(mapping)), Path(mapping).name if _is_folder(source): with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) geo = Geometry.from_folder(comm, source) folder = source info_file = source / "info.json" # from_folder reads the geometry file, which holds no info of the folder's own folder_info = json.loads(info_file.read_text()) if info_file.exists() else {} source_info = {**folder_info, **geo.info} else: geo = Geometry.from_file(comm, source) folder = source.parent source_info = dict(geo.info) unit = spec.get("unit") if unit is not None and unit not in UNITS: raise ValueError(f"The mapping's unit {unit!r} is not one of {', '.join(UNITS)}") if geo.unit is not None and unit is not None and geo.unit != unit: raise ValueError( f"The mapping's unit {unit!r} disagrees with the source's unit {geo.unit!r}" ) unit = unit or geo.unit if unit is None: raise ValueError( f"The source records no unit, so the mapping must give one: unit = {' | '.join(UNITS)}" ) markers = {name: (int(tag), int(dim)) for name, (tag, dim) in geo.markers.items()} tdim = geo.mesh.topology.dim fdim = tdim - 1 facets = spec.get("facets", {}) for old in facets: if old not in markers or markers[old][1] != fdim: known = sorted(n for n, (_, d) in markers.items() if d == fdim) raise ValueError( f"[facets] renames {old!r}, which is not a facet marker of the source " f"(its facet markers are {', '.join(known) or 'none'})" ) renamed: dict[str, tuple[int, int]] = {} for name, (tag, dim) in markers.items(): new_name = facets.get(name, name) if dim == fdim else name if new_name in renamed: raise ValueError( f"[facets] makes two markers named {new_name!r} (one of them from {name!r})" ) renamed[new_name] = (tag, dim) markers = renamed if "cells" in spec and spec["cells"]: markers = {n: td for n, td in markers.items() if td[1] != tdim} markers.update({name: (tag, tdim) for tag, name in spec["cells"].items()}) additional_data: dict[str, Any] = dict(geo.additional_data) additional_data_info: dict[str, dict[str, Any]] = { k: dict(v) for k, v in geo.additional_data_info.items() } for name, field in spec.get("fields", {}).items(): additional_data[name] = read_field( folder / field["file"], geo.mesh, name, field["name"], field["element"] ) additional_data_info[name] = {k: field[k] for k in FIELD_INFO_KEYS if k in field} info = { "mesh_type": "converted", "source": source.name, "mapping": mapping_name, "source_info": source_info, "cardiac_geometry_version": __version__, **spec.get("info", {}), } result = Geometry( mesh=geo.mesh, markers=markers, cfun=geo.cfun, ffun=geo.ffun, efun=geo.efun, vfun=geo.vfun, f0=geo.f0, s0=geo.s0, n0=geo.n0, info=info, additional_data=additional_data, additional_data_info=additional_data_info, unit=unit, ) problems = check(result) if has_errors(problems): listing = "\n".join(str(p) for p in problems) raise ValueError(f"The converted geometry does not conform to the standard:\n{listing}") result.save(out) return result