Source code for cardiac_geometries.check

"""Check a geometry against the standard: the rules C1 to C10 of ``geox check``."""

from dataclasses import dataclass
from itertools import combinations
from typing import Literal

from mpi4py import MPI

import basix.ufl
import dolfinx
import numpy as np

from . import standard
from .geometry import Geometry
from .metadata import FORMAT, UNITS

FIBRE_TOL = 1e-6
VALUE_TOL = 1e-8


[docs] @dataclass(frozen=True) class Problem: """A way in which a geometry departs from the standard. `code` is the rule it breaks, ``"C1"`` to ``"C10"`` (see the geometry-file docs), and an ``"error"`` makes ``geox check`` exit with 1, a ``"warning"`` does not. """ code: str severity: Literal["error", "warning"] message: str def __str__(self) -> str: return f"{self.code} {self.severity}: {self.message}"
[docs] def has_errors(problems: list[Problem]) -> bool: """Whether any of `problems` is an error, which makes ``geox check`` fail.""" return any(p.severity == "error" for p in problems)
def _tag_values(comm: MPI.Comm, tags: dolfinx.mesh.MeshTags | None) -> set[int]: local = set() if tags is None else {int(v) for v in np.unique(tags.values)} return set().union(*comm.allgather(local)) def _owned(u: dolfinx.fem.Function) -> np.ndarray: """The values of `u` at the dofs this rank owns, one row per dof.""" V = u.function_space bs = V.dofmap.bs return u.x.array[: V.dofmap.index_map.size_local * bs].reshape(-1, bs) def _element(data: object) -> tuple | None: """``(family, degree, discontinuous)`` of a scalar Function, ``("vector", ...)`` of another value shape, and None for anything that is not a Function.""" if not isinstance(data, dolfinx.fem.Function): return None el = data.function_space.ufl_element() if el.reference_value_shape != (): return ("vector", tuple(int(n) for n in el.reference_value_shape), False) return _family(el) def _family(el: basix.ufl._ElementBase) -> tuple[str, int, bool]: """``(family, degree, discontinuous)`` of an element, blocked or not.""" return ( el.family_name, int(el.degree), bool(getattr(el.basix_element, "discontinuous", False)), )
[docs] def describe_data(data: object) -> str: """The element of a Function as ``DG0`` or ``P1``, whatever its value shape, and ``mesh tags`` for a MeshTags.""" if isinstance(data, dolfinx.mesh.MeshTags): return "mesh tags" if not isinstance(data, dolfinx.fem.Function): return _describe(None) return _describe(_family(data.function_space.ufl_element()))
def _describe(element: tuple | None) -> str: if element is None: return "something that is not a function" family, degree, discontinuous = element if family == "vector": return f"a function of value shape {degree}" return f"{'DG' if discontinuous else family}{degree}" def _global_max(comm: MPI.Comm, x: np.ndarray) -> float: return float(comm.allreduce(float(np.max(x)) if x.size else 0.0, op=MPI.MAX))
[docs] def max_norm_error(comm: MPI.Comm, a: np.ndarray) -> float: """The global largest ``| |a| - 1 |`` over the rows of `a`.""" return _global_max(comm, np.abs(np.linalg.norm(a, axis=1) - 1.0))
[docs] def max_dot(comm: MPI.Comm, a1: np.ndarray, a2: np.ndarray) -> float: """The global largest ``|a1 . a2|`` over the rows.""" return _global_max(comm, np.abs(np.sum(a1 * a2, axis=1)))
def _untagged_exterior_facets(geometry: Geometry) -> tuple[int, int]: """The global number of exterior facets, and of those with no tag.""" mesh = geometry.mesh tdim = mesh.topology.dim mesh.topology.create_entities(tdim - 1) mesh.topology.create_connectivity(tdim - 1, tdim) n_owned = mesh.topology.index_map(tdim - 1).size_local exterior = dolfinx.mesh.exterior_facet_indices(mesh.topology) exterior = exterior[exterior < n_owned] tagged = np.empty(0, dtype=np.int32) if geometry.ffun is not None: tagged = geometry.ffun.indices[geometry.ffun.indices < n_owned] untagged = np.setdiff1d(exterior, tagged) comm = mesh.comm return int(comm.allreduce(len(exterior))), int(comm.allreduce(len(untagged)))
[docs] def check(geometry: Geometry) -> list[Problem]: """The problems of `geometry`: the errors first, then the warnings, each in code order. Every count is global and every set of tags is the union over the ranks, so every rank returns the same list. Every rank must call it. """ problems: list[Problem] = [] mesh = geometry.mesh comm = mesh.comm tdim = mesh.topology.dim markers = {name: (int(tag), int(dim)) for name, (tag, dim) in geometry.markers.items()} def add(code: str, severity: Literal["error", "warning"], message: str) -> None: problems.append(Problem(code, severity, message)) # C1 fmt = geometry.file_format if fmt is not None and (fmt == 0 or fmt > FORMAT): if fmt == 0: add("C1", "error", "the file has no metadata (format 0); run `geox convert`") else: add("C1", "error", f"format {fmt} is higher than the {FORMAT} this version reads") # C2 if geometry.unit is None: add("C2", "error", f"no unit; it must be one of {', '.join(UNITS)}") elif geometry.unit not in UNITS: add("C2", "error", f"unit {geometry.unit!r} is not one of {', '.join(UNITS)}") # the tags of each entity dimension; the facets are dimension tdim - 1, the cells tdim tags: dict[int, set[int]] = {0: _tag_values(comm, geometry.vfun)} if tdim == 3: tags[1] = _tag_values(comm, geometry.efun) tags[tdim - 1] = _tag_values(comm, geometry.ffun) tags[tdim] = _tag_values(comm, geometry.cfun) # C3 named = {dim: {t for t, d in markers.values() if d == dim} for dim in tags} for label, dim in (("facet", tdim - 1), ("cell", tdim)): missing = sorted(tags[dim] - named[dim]) if missing: add("C3", "error", f"{label} tags {missing} have no name in markers") # C4 for name, (_, dim) in markers.items(): if name in standard.FACET_NAMES and dim != tdim - 1: add("C4", "error", f"{name} is a facet name but has dimension {dim}, not {tdim - 1}") elif name in standard.NON_MYOCARDIUM and dim != tdim: add("C4", "error", f"{name} is a cell name but has dimension {dim}, not {tdim}") # C5 for name, (_, dim) in markers.items(): if name in standard.OLD_FACET_NAMES and dim == tdim - 1: add( "C5", "warning", f"{name} is an old facet name; the standard name is " f"{standard.OLD_FACET_NAMES[name]}", ) # C6 names = {name for name, (_, dim) in markers.items() if dim == tdim - 1} if "RV_ENDO" in names and "LV_ENDO" not in names: add("C6", "error", "RV_ENDO without LV_ENDO") if "LV_ENDO" in names: if "EPI" not in names: add("C6", "error", "LV_ENDO without EPI") if "BASE" not in names and not names & set(standard.VALVE_PLANES): add("C6", "error", "LV_ENDO without BASE or a valve plane") # C7 fibres = {n: getattr(geometry, n) for n in standard.FIBER_NAMES} fibres = {n: u for n, u in fibres.items() if u is not None} if (geometry.f0 is None) != (geometry.s0 is None): add("C7", "error", "only one of f0 and s0 is present") arrays = {n: _owned(u) for n, u in fibres.items()} for n, a in arrays.items(): dev = max_norm_error(comm, a) if dev > FIBRE_TOL: add("C7", "error", f"|{n}| - 1 is {dev:.3g} at most, above {FIBRE_TOL:g}") for (n1, a1), (n2, a2) in combinations(arrays.items(), 2): if a1.shape == a2.shape: dot = max_dot(comm, a1, a2) if dot > FIBRE_TOL: add("C7", "error", f"|{n1}·{n2}| is {dot:.3g} at most, above {FIBRE_TOL:g}") # C8 for name, data in geometry.additional_data.items(): info = geometry.additional_data_info.get(name, {}) if not any(k in info for k in standard.FIELD_INFO_KEYS): add("C8", "error", f"field {name} has no unit, values or description") values = info.get("values") if values is not None and not values: add("C8", "error", f"field {name} has an empty legend") elif values is not None and isinstance(data, dolfinx.fem.Function): legend = np.array(sorted(values.values()), dtype=float) x = _owned(data).ravel() off = np.min(np.abs(x[:, None] - legend[None, :]), axis=1) if x.size else x worst = _global_max(comm, off) if worst > VALUE_TOL: add("C8", "error", f"field {name} has values outside its legend {values}") reserved = standard.RESERVED_FIELDS.get(name) if reserved is not None: for key, expected in reserved.items(): if key == standard.ELEMENTS_KEY: continue if info.get(key) != expected: add("C8", "error", f"field {name} must have {key} {expected!r}") allowed = reserved[standard.ELEMENTS_KEY] found = _element(data) if found not in allowed: add( "C8", "error", f"field {name} is on {_describe(found)}, but must be a scalar on " + " or ".join(sorted(_describe(e) for e in allowed)), ) # C9 for name, (tag, dim) in markers.items(): if 0 <= dim <= 3 and tag not in tags.get(dim, set()): add("C9", "warning", f"marker {name} (tag {tag}, dimension {dim}) is used by no entity") # C10 total, untagged = _untagged_exterior_facets(geometry) if untagged: add("C10", "warning", f"{untagged} of {total} exterior facets have no tag") problems.sort(key=lambda p: (p.severity != "error", int(p.code[1:]))) return problems