"""Transmural cell types by Laplace solves: endo 0, epi 1, mid 2 (``geox celltype``).
The algorithm is that of beat's ``expand_layer_biv``: a Laplace solution that is 0 on the
endocardium and 1 on the epicardium, thresholded; in a BiV the smaller of the solutions from the
LV and from the RV endocardium. The result is stored as the reserved field ``celltype``.
"""
import logging
from typing import Any
import dolfinx
import dolfinx.fem.petsc
import numpy as np
import ufl
from .geometry import Geometry
from .mesh import transform_markers
from .standard import CELLTYPE_SPACES, CELLTYPE_VALUES
logger = logging.getLogger(__name__)
SPACES = CELLTYPE_SPACES
PETSC_OPTIONS: dict[str, Any] = {
"ksp_type": "cg",
"pc_type": "hypre",
"pc_hypre_type": "boomeramg",
"ksp_norm_type": "unpreconditioned",
"ksp_atol": 1e-15,
"ksp_rtol": 1e-10,
"ksp_max_it": 10_000,
"ksp_error_if_not_converged": False,
}
PREFIX = "cardiac_geometries_celltype_"
def _tags(geometry: Geometry) -> dict[str, list[int]]:
try:
tags = transform_markers(geometry.markers)
except KeyError:
tags = {}
if not tags.get("lv") or not tags.get("epi") or geometry.ffun is None:
raise ValueError(
"the geometry has no lv and epi markers (and facet tags) to compute celltype from"
)
return tags
def _dofs(V: dolfinx.fem.FunctionSpace, ffun: dolfinx.mesh.MeshTags, tags: list[int]) -> np.ndarray:
facets = np.unique(np.concatenate([ffun.find(t) for t in tags]))
return dolfinx.fem.locate_dofs_topological(V, ffun.dim, facets)
[docs]
def compute_celltype(
geometry: Geometry, endo: float = 0.3, epi: float = 0.3, space: str = "P_1"
) -> dolfinx.fem.Function:
"""The cell type of every node (``"P_1"``) or cell (``"DG_0"``) of `geometry`.
A value `t` of the Laplace solution (0 on the endocardium, 1 on the epicardium; the smaller
of the LV's and the RV's in a BiV) is endo (0) up to `endo`, epi (1) from `1 - epi` and mid
(2) between. Collective: every rank must call it.
Raises
------
ValueError
If `space` is not ``"P_1"`` or ``"DG_0"``, or the geometry has no ``lv`` and ``epi``
markers (:func:`~cardiac_geometries.mesh.transform_markers`).
"""
if space not in SPACES:
raise ValueError(f"space must be one of {sorted(SPACES)}, not {space!r}")
if not (0 <= endo <= 1 and 0 <= epi <= 1 and endo + epi <= 1):
raise ValueError(
f"endo ({endo}) and epi ({epi}) must each be in [0, 1] and sum to at most 1, "
"or the epi threshold overrides the endo one"
)
tags = _tags(geometry)
mesh = geometry.mesh
ffun = geometry.ffun
assert ffun is not None
mesh.topology.create_connectivity(ffun.dim, mesh.topology.dim)
V = dolfinx.fem.functionspace(mesh, ("P", 1))
u = ufl.TrialFunction(V)
v = ufl.TestFunction(V)
a = ufl.dot(ufl.grad(u), ufl.grad(v)) * ufl.dx(domain=mesh)
L = v * dolfinx.fem.Constant(mesh, dolfinx.default_scalar_type(0.0)) * ufl.dx(domain=mesh)
epi_dofs = _dofs(V, ffun, tags["epi"])
solutions = []
for key in ("lv", "rv"):
if not tags.get(key):
continue
bcs = [
dolfinx.fem.dirichletbc(0.0, _dofs(V, ffun, tags[key]), V),
dolfinx.fem.dirichletbc(1.0, epi_dofs, V),
]
problem = dolfinx.fem.petsc.LinearProblem(
a, L, bcs=bcs, petsc_options=PETSC_OPTIONS, petsc_options_prefix=PREFIX
)
solution = problem.solve()
assert isinstance(solution, dolfinx.fem.Function)
solutions.append(solution.x.array.copy())
# The whole local array, the ghosts included
t = dolfinx.fem.Function(V)
t.x.array[:] = np.min(solutions, axis=0)
W = dolfinx.fem.functionspace(mesh, SPACES[space])
if space == "P_1":
x = t.x.array
else:
smooth = dolfinx.fem.Function(W)
smooth.interpolate(t)
x = smooth.x.array
out = dolfinx.fem.Function(W, name="celltype")
values = np.full(len(x), CELLTYPE_VALUES["mid"], dtype=out.x.array.dtype)
values[x <= endo] = CELLTYPE_VALUES["endo"]
values[x >= 1 - epi] = CELLTYPE_VALUES["epi"]
out.x.array[:] = values
out.x.scatter_forward()
return out
[docs]
def add_celltype(
geometry: Geometry, endo: float = 0.3, epi: float = 0.3, space: str = "P_1"
) -> None:
"""Compute the cell type (:func:`compute_celltype`) and store it as ``celltype``,
replacing, with a warning, one that is there."""
celltype = compute_celltype(geometry, endo=endo, epi=epi, space=space)
if "celltype" in geometry.additional_data:
logger.warning("replacing the celltype the geometry already has")
geometry.additional_data["celltype"] = celltype
geometry.additional_data_info["celltype"] = {
"values": dict(CELLTYPE_VALUES),
"recipe": {"method": "laplace", "endo": endo, "epi": epi, "space": space},
"description": "Transmural cell type from Laplace solves",
}