Source code for beat.utils

from __future__ import annotations

import logging
import math
from collections.abc import Iterator
from typing import Any

from mpi4py import MPI

import basix
import dolfinx
import dolfinx.fem.petsc
import numpy as np
import ufl
from packaging.version import Version

logger = logging.getLogger(__name__)


_dolfinx_version = Version(dolfinx.__version__)


def interpolation_points(V):
    if _dolfinx_version >= Version("0.10"):
        return V.element.interpolation_points
    else:
        return V.element.interpolation_points()


[docs] def real_function_space(mesh: dolfinx.mesh.Mesh) -> dolfinx.fem.FunctionSpace: """A scalar space holding a single global degree of freedom. dolfinx supports real spaces natively from 0.11; before that, ``basix.ufl.real_element`` exists but cannot be compiled into a function space, so fall back to scifem's implementation. Parameters ---------- mesh : dolfinx.mesh.Mesh The mesh the space is defined on Returns ------- dolfinx.fem.FunctionSpace The real function space """ if _dolfinx_version >= Version("0.11"): return dolfinx.fem.functionspace( mesh, basix.ufl.real_element(mesh.basix_cell(), value_shape=()), ) else: import scifem return scifem.create_real_functionspace(mesh, value_shape=())
[docs] def cpp_function_space(V): """The C++ function space behind ``V``, whichever wrapper ``V`` arrives in. Some dolfinx APIs return the Python ``FunctionSpace`` and others the C++ space it wraps; ``DirichletBC.function_space`` has returned each of them in different releases. Comparisons such as ``contains`` are only defined between two C++ spaces, so bring both sides down to that one shape rather than assuming either. Parameters ---------- V : dolfinx.fem.FunctionSpace | dolfinx.cpp.fem.FunctionSpace The function space, in either wrapper Returns ------- dolfinx.cpp.fem.FunctionSpace The C++ function space """ return getattr(V, "_cpp_object", V)
[docs] def local_project( v: dolfinx.fem.Function, V: dolfinx.fem.FunctionSpace, u: dolfinx.fem.Function | None = None, ) -> dolfinx.fem.Function | None: """Element-wise projection using LocalSolver Parameters ---------- v : dolfinx.fem.Function Function to be projected V : dolfinx.fem.FunctionSpace Function space to project into u : dolfinx.fem.Function | None, optional Optional function to save the projected function, by default None Returns ------- dolfinx.fem.Function | None The projected function """ if u is None: U = dolfinx.fem.Function(V) else: U = u if v.x.array.size == U.x.array.size: U.x.array[:] = v.x.array[:] return U expr = dolfinx.fem.Expression(v, interpolation_points(V)) U.interpolate(expr) return U
[docs] def parse_element(space_string: str, mesh: dolfinx.mesh.Mesh, dim: int) -> basix.ufl._ElementBase: """ Parse a string representation of a basix element family """ family_str, degree_str = space_string.split("_") kwargs: dict[str, Any] = {"degree": int(degree_str), "cell": mesh.basix_cell()} if dim > 1: if family_str in ["Quadrature", "Q", "Quad"]: kwargs["value_shape"] = (dim,) else: kwargs["shape"] = (dim,) el: basix.ufl._ElementBase if family_str in ["Lagrange", "P", "CG"]: el = basix.ufl.element(family=basix.ElementFamily.P, discontinuous=False, **kwargs) elif family_str in ["Discontinuous Lagrange", "DG", "dP"]: el = basix.ufl.element(family=basix.ElementFamily.P, discontinuous=True, **kwargs) elif family_str in ["Quadrature", "Q", "Quad"]: el = basix.ufl.quadrature_element(scheme="default", **kwargs) else: families = list(basix.ElementFamily.__members__.keys()) msg = f"Unknown element family: {family_str}, available families: {families}" raise ValueError(msg) return el
[docs] def space_from_string( space_string: str, mesh: dolfinx.mesh.Mesh, dim: int = 1, ) -> dolfinx.fem.FunctionSpace: """ Constructed a finite elements space from a string representation of the space Arguments --------- space_string : str A string on the form {family}_{degree} which determines the space. Example 'Lagrange_1'. mesh : df.Mesh The mesh dim : int 1 for scalar space, 3 for vector space. Returns ------- df.FunctionSpace The function space """ el = parse_element(space_string, mesh, dim) return dolfinx.fem.functionspace(mesh, el)
[docs] def expand_layer( V: dolfinx.fem.FunctionSpace, ft: dolfinx.mesh.MeshTags, endo_marker: int, epi_marker: int, endo_size: float, epi_size: float, output_mid_marker: int = 0, output_endo_marker: int = 1, output_epi_marker: int = 2, ) -> dolfinx.fem.Function: """Expand the endo and epi markers to the rest of the mesh with a given size Parameters ---------- V : dolfinx.fem.FunctionSpace The function space for your return function ft : dolfinx.mesh.MeshTags The facet tags endo_marker : int The endocardium marker epi_marker : int The epicardium marker endo_size : float The endocardium size epi_size : float The epicardium size output_mid_marker : int, optional The marker to be set for the midwall, by default 0 output_endo_marker : int, optional The marker to be set for the endocardium, by default 1 output_epi_marker : int, optional The marker to be set for the epicardium, by default 2 Returns ------- dolfinx.fem.Function The expanded markers as a function in ``V`` """ logger.info("Expanding endo and epi markers to the rest of the mesh") logger.debug( f"endo_marker: {endo_marker}, epi_marker: {epi_marker}\n" f"endo_size: {endo_size}, epi_size: {epi_size}\n" f"Output markers: endo: {output_endo_marker}, " f"epi: {output_epi_marker} mid: {output_mid_marker}", ) # Find the rest of the laplace solutions u = ufl.TrialFunction(V) v = ufl.TestFunction(V) mesh = V.mesh 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) u_endo = dolfinx.fem.Function(V) u_endo.x.array[:] = 0 u_epi = dolfinx.fem.Function(V) u_epi.x.array[:] = 1 endo_dofs = dolfinx.fem.locate_dofs_topological(V, ft.dim, ft.find(endo_marker)) epi_dofs = dolfinx.fem.locate_dofs_topological(V, ft.dim, ft.find(epi_marker)) # Apply Dirichlet BC on the outer boundary bcs = [ dolfinx.fem.dirichletbc(0.0, endo_dofs, V), dolfinx.fem.dirichletbc(1.0, epi_dofs, V), ] kwargs: dict[str, Any] = {} if _dolfinx_version >= Version("0.10"): kwargs["petsc_options_prefix"] = "beat_utils_expand_layer_" problem = dolfinx.fem.petsc.LinearProblem( a, L, bcs=bcs, # form_compiler_options=form_compiler_options, # jit_options=jit_options, petsc_options={ "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, }, **kwargs, ) uh_result = problem.solve() assert isinstance(uh_result, dolfinx.fem.Function) uh = uh_result arr = uh.x.array.copy() uh.x.array[:] = output_mid_marker uh.x.array[arr <= endo_size] = output_endo_marker uh.x.array[arr >= 1 - epi_size] = output_epi_marker uh.name = "endo_epi" with dolfinx.io.XDMFFile(mesh.comm, "endo_epi_lv.xdmf", "w") as xdmf: xdmf.write_mesh(mesh) xdmf.write_function(uh) return uh
[docs] def expand_layer_biv( V: dolfinx.fem.FunctionSpace, ft: dolfinx.mesh.MeshTags, endo_lv_marker: int, endo_rv_marker: int, epi_marker: int, endo_size: float, epi_size: float, output_mid_marker: int = 0, output_endo_marker: int = 1, output_epi_marker: int = 2, ) -> dolfinx.fem.Function: """Expand the endo and epi markers to the rest of the mesh with a given size Parameters ---------- V : dolfinx.fem.FunctionSpace The function space for your return function ft : dolfinx.mesh.MeshTags The facet tags endo_lv_marker : int The LV endocardium marker endo_rv_marker : int The LV endocardium marker epi_marker : int The epicardium marker endo_size : float The endocardium size epi_size : float The epicardium size output_mid_marker : int, optional The marker to be set for the midwall, by default 0 output_endo_marker : int, optional The marker to be set for the endocardium, by default 1 output_epi_marker : int, optional The marker to be set for the epicardium, by default 2 Returns ------- dolfinx.fem.Function The expanded markers as a function in ``V`` """ logger.info("Expanding endo and epi markers to the rest of the mesh") logger.debug( f"endo_lv_marker: {endo_lv_marker}, " f"endo_rv_marker: {endo_rv_marker}, " f"epi_marker: {epi_marker}\n" f"endo_size: {endo_size}, epi_size: {epi_size}\n" f"Output markers: endo: {output_endo_marker}, " f"epi: {output_epi_marker} mid: {output_mid_marker}", ) # Find the rest of the laplace solutions petsc_options = { "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, } u = ufl.TrialFunction(V) v = ufl.TestFunction(V) mesh = V.mesh 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) u_endo = dolfinx.fem.Function(V) u_endo.x.array[:] = 0 u_epi = dolfinx.fem.Function(V) u_epi.x.array[:] = 1 endo_lv_dofs = dolfinx.fem.locate_dofs_topological(V, ft.dim, ft.find(endo_lv_marker)) endo_rv_dofs = dolfinx.fem.locate_dofs_topological(V, ft.dim, ft.find(endo_rv_marker)) epi_dofs = dolfinx.fem.locate_dofs_topological(V, ft.dim, ft.find(epi_marker)) lv_kwargs: dict[str, Any] = {} if _dolfinx_version >= Version("0.10"): lv_kwargs["petsc_options_prefix"] = "beat_utils_expand_layer_biv_" lv_problem = dolfinx.fem.petsc.LinearProblem( a, L, bcs=[ dolfinx.fem.dirichletbc(0.0, endo_lv_dofs, V), dolfinx.fem.dirichletbc(1.0, epi_dofs, V), ], petsc_options=petsc_options, **lv_kwargs, ) uh_lv_result = lv_problem.solve() assert isinstance(uh_lv_result, dolfinx.fem.Function) uh_lv = uh_lv_result rv_kwargs: dict[str, Any] = {} if _dolfinx_version >= Version("0.10"): rv_kwargs["petsc_options_prefix"] = "beat_utils_expand_layer_biv_" rv_problem = dolfinx.fem.petsc.LinearProblem( a, L, bcs=[ dolfinx.fem.dirichletbc(0.0, endo_rv_dofs, V), dolfinx.fem.dirichletbc(1.0, epi_dofs, V), ], petsc_options=petsc_options, **rv_kwargs, ) uh_rv_result = rv_problem.solve() assert isinstance(uh_rv_result, dolfinx.fem.Function) uh_rv = uh_rv_result # In BiV we have have one epi and two endo solutions # We take the minimum of the two endo solutions arr = np.min([uh_rv.x.array, uh_lv.x.array], axis=0) uh_rv.x.array[:] = output_mid_marker uh_rv.x.array[arr <= endo_size] = output_endo_marker uh_rv.x.array[arr >= 1 - epi_size] = output_epi_marker uh_rv.name = "endo_epi" with dolfinx.io.XDMFFile(mesh.comm, "endo_epi_biv.xdmf", "w") as xdmf: xdmf.write_mesh(mesh) xdmf.write_function(uh_rv) return uh_rv
[docs] class PointEvaluator: """Evaluate a Function at fixed points; the point location is done once ``points`` has shape ``(N, 3)`` (pad 2D points with a zero) and must be the same on every rank. Calling the evaluator returns the values at all points on every rank, NaN where a point is outside the mesh. Unlike ``scifem.evaluate_function`` the collision search is not repeated on every call. Each point takes its value from one rank, the lowest one that finds it, so NaN values come back as NaN and every rank gets the same result. """ def __init__(self, mesh: dolfinx.mesh.Mesh, points: np.ndarray) -> None: points = np.ascontiguousarray(points, dtype=np.float64) self.comm = mesh.comm self.num_points = len(points) tree = dolfinx.geometry.bb_tree(mesh, mesh.topology.dim) candidates = dolfinx.geometry.compute_collisions_points(tree, points) cells = dolfinx.geometry.compute_colliding_cells(mesh, candidates, points) found = np.flatnonzero(cells.offsets[1:] - cells.offsets[:-1]) # The lowest rank that finds a point owns it; comm.size marks points outside the mesh owner = np.full(self.num_points, self.comm.size, dtype=np.int32) owner[found] = self.comm.rank self.comm.Allreduce(MPI.IN_PLACE, owner, op=MPI.MIN) self.outside = owner == self.comm.size self.indices = found[owner[found] == self.comm.rank] self.cells = cells.array[cells.offsets[self.indices]] self.points = points[self.indices] def __call__(self, u: dolfinx.fem.Function) -> np.ndarray: u.x.scatter_forward() # Only the owner of a point writes its value, so the sum passes it (and NaN) through out = np.zeros(self.num_points) if len(self.indices) > 0: out[self.indices] = u.eval(self.points, self.cells).ravel() self.comm.Allreduce(MPI.IN_PLACE, out, op=MPI.SUM) out[self.outside] = np.nan return out
[docs] def time_steps( interval: tuple[float, float], dt: float | None, ) -> Iterator[tuple[float, float]]: """The steps ``(t0, t1)`` of length ``dt`` that cover ``interval = (T0, T)`` The number of steps is ``floor((T - T0) / dt)``, up to round-off in that one division, so a ``dt`` that does not divide the interval leaves the remainder out. The times accumulate (``t1 = t0 + dt``), as the time loops have always done. ``dt=None`` is one step over the whole interval. Raises ------ ValueError If ``dt`` is not positive or is longer than the interval. """ T0, T = interval if dt is None: yield (T0, T) return if dt <= 0: raise ValueError(f"dt must be positive, got {dt}") # Count the steps from one division (its round-off does not grow with the number of steps, # unlike the accumulated times), allowing for that round-off when dt divides the interval. num_steps = math.floor((T - T0) / dt + 1e-9) if num_steps < 1: raise ValueError(f"dt={dt} is longer than the interval {interval}") t0, t1 = T0, T0 + dt for _ in range(num_steps): yield (t0, t1) t0, t1 = t1, t1 + dt