import functools
import json
import logging
import math
import warnings
from importlib.metadata import metadata
from pathlib import Path
from mpi4py import MPI
import dolfinx
import rich_click as click
from . import mesh
from .geometry import DEFAULT_IO_BACKEND, IO_BACKENDS, find_geometry_file, geometry_path
from .metadata import UNITS
from .standard import CELLTYPE_SPACES
logger = logging.getLogger(__name__)
meta = metadata("cardiac-geometriesx")
__version__ = meta["Version"]
__author__ = meta["Author-email"]
__license__ = meta["License"]
__email__ = meta["Author-email"]
__program_name__ = meta["Name"]
def init_logging(verbose: bool = False):
loglevel = logging.DEBUG if verbose else logging.INFO
logging.basicConfig(level=loglevel)
for name in ["numba"]:
logging.getLogger(name).setLevel(logging.WARNING)
io_backend_option = click.option(
"--io-backend",
default=DEFAULT_IO_BACKEND,
type=click.Choice(IO_BACKENDS),
help=(
"io4dolfinx backend used to write the geometry, h5py (geometry.h5) or adios2 (geometry.bp)"
),
show_default=True,
)
[docs]
def export_option(command):
"""Add ``--export/--no-export`` to a generator command, and after it ran, export the
geometry it wrote into ``OUTDIR/viz/`` (a warning instead, and still exit code 0, without
pyvista or on more than one rank)."""
@functools.wraps(command)
def wrapper(*args, export: bool = True, **kwargs):
command(*args, **kwargs)
if export:
_export_generated(Path(kwargs["outdir"]), kwargs.get("io_backend", DEFAULT_IO_BACKEND))
return click.option(
"--export/--no-export",
default=True,
show_default=True,
help="Write VTU files for ParaView into OUTDIR/viz/",
)(wrapper)
def _export_generated(outdir: Path, io_backend: str) -> None:
from .export import PYVISTA_MESSAGE, export
from .geometry import Geometry
comm = MPI.COMM_WORLD
if comm.size > 1:
if comm.rank == 0:
logger.warning(
"Not exporting for ParaView on more than one rank. "
f"Run `geox export {geometry_path(outdir, io_backend)}` on one process."
)
return
try:
import pyvista # noqa: F401
except ImportError:
has_pyvista = False
else:
has_pyvista = True
if not has_pyvista:
logger.warning(f"Not exporting for ParaView. {PYVISTA_MESSAGE}")
return
path = geometry_path(outdir, io_backend)
# The geometry is written by now, so a failing export must not fail the command
try:
geo = Geometry.from_file(comm=comm, path=path)
export(geo, outdir / "viz")
except Exception as e:
logger.warning(
f"The geometry was written to {path}, but exporting it for ParaView failed "
f"({type(e).__name__}: {e}). Run `geox export {path}` to try again."
)
[docs]
def unit_option(default: str | None = None, required: bool = False):
"""The ``--unit`` option: the unit of the geometry's coordinates."""
return click.option(
"--unit",
default=default,
required=required,
type=click.Choice(UNITS),
help="The unit of the coordinates of the geometry",
show_default=default is not None,
)
@click.group()
@click.version_option(__version__, prog_name="cardiac_geometriesx")
def app():
"""
Cardiac Geometries - A library for creating meshes of
cardiac geometries
"""
pass
@click.command(help="Create UK Biobank geometry")
@click.argument(
"outdir",
required=True,
type=click.Path(
file_okay=False,
dir_okay=True,
writable=True,
readable=True,
resolve_path=True,
),
)
@click.option(
"--mode",
default=-1,
type=int,
help="Mode of the geometry",
show_default=True,
)
@click.option(
"--score",
multiple=True,
type=float,
help=(
"PCA score of one mode, in standard deviations; repeat it for modes 0, 1, 2, ... "
"Replaces --mode and --std"
),
)
@click.option(
"--std",
default=1.5,
type=float,
help="Standard deviation of the geometry",
show_default=True,
)
@click.option(
"--case",
default="ED",
type=str,
help="Case of the geometry",
show_default=True,
)
@click.option(
"--char-length-max",
default=2.0,
type=float,
help="Maximum characteristic length of the mesh",
show_default=True,
)
@click.option(
"--char-length-min",
default=2.0,
type=float,
help="Minimum characteristic length of the mesh",
show_default=True,
)
@click.option(
"--fiber-angle-endo",
default=60,
type=float,
help="Angle for the endocardium",
show_default=True,
)
@click.option(
"--fiber-angle-epi",
default=-60,
type=float,
help="Angle for the epicardium",
show_default=True,
)
@click.option(
"--fiber-space",
default="P_1",
type=str,
help="Function space for fibers of the form family_degree",
show_default=True,
)
@click.option(
"--clipped/--no-clipped",
default=False,
is_flag=True,
type=bool,
help="If True create clip away the outflow tracts",
show_default=True,
)
@click.option(
"--create-fibers",
default=False,
is_flag=True,
help="If True create rule-based fibers",
show_default=True,
)
@click.option(
"--ghost-mode",
default=dolfinx.mesh.GhostMode.none,
type=click.Choice(
dolfinx.mesh.GhostMode,
case_sensitive=False,
),
help="Ghost mode for the mesh",
show_default=True,
)
@click.option(
"--geometry",
default="biv",
type=click.Choice(mesh.UKB_GEOMETRIES),
help=(
"Biventricular (biv) or LV only (lv) geometry, with open valves or with the "
"valves closed by caps and the cavities meshed (biv-closed, lv-closed)"
),
show_default=True,
)
@click.option(
"--fiber-method",
default=None,
type=click.Choice(["doste", "ldrb"]),
help=(
"Rule-based method for the fibers: Doste et al. (2019), which handles the outflow "
"tracts, or Bayer et al. (2012). By default doste, or ldrb with --clipped"
),
)
@click.option(
"--refine",
default=0,
type=int,
help=(
"Number of times to refine the surfaces of the atlas, placing the new nodes on "
"smooth surfaces through the nodes of the atlas"
),
show_default=True,
)
@click.option(
"--order",
default=1,
type=int,
help="Order of the mesh elements",
show_default=True,
)
@click.option(
"--aha/--no-aha",
default=False,
is_flag=True,
type=bool,
help="If True tag the cells with the 17 AHA segments, the RV free wall and the LVOT",
show_default=True,
)
@click.option(
"--rv-regions/--no-rv-regions",
default=False,
is_flag=True,
type=bool,
help=(
"With --aha, divide the RV into the 15 regions of Zhong et al. (2012) and split the "
"septum between the LV and the RV"
),
show_default=True,
)
@click.option(
"--rv-septum-fraction",
default=None,
type=float,
help=(
"With --rv-regions, the share of the septal thickness (from the RV side) that belongs "
"to the RV, in [0, 1] [default: 0.5]"
),
)
@io_backend_option
@export_option
def ukb(
outdir: Path | str,
mode: int = -1,
std: float = 1.5,
case: str = "ED",
char_length_max: float = 2.0,
char_length_min: float = 2.0,
fiber_angle_endo: float = 60,
fiber_angle_epi: float = -60,
fiber_space: str = "P_1",
clipped: bool = False,
create_fibers: bool = True,
ghost_mode: dolfinx.mesh.GhostMode = dolfinx.mesh.GhostMode.none,
geometry: str = "biv",
fiber_method: str | None = None,
order: int = 1,
refine: int = 0,
aha: bool = False,
rv_regions: bool = False,
rv_septum_fraction: float | None = None,
io_backend: str = DEFAULT_IO_BACKEND,
score: tuple[float, ...] = (),
):
outdir = Path(outdir)
outdir.mkdir(exist_ok=True)
mesh.ukb(
outdir=outdir,
mode=mode,
std=std,
case=case,
char_length_max=char_length_max,
char_length_min=char_length_min,
fiber_angle_endo=fiber_angle_endo,
fiber_angle_epi=fiber_angle_epi,
fiber_space=fiber_space,
clipped=clipped,
create_fibers=create_fibers,
ghost_mode=ghost_mode,
geometry=geometry,
fiber_method=fiber_method,
order=order,
refine=refine,
io_backend=io_backend,
aha=aha,
rv_regions=rv_regions,
rv_septum_fraction=rv_septum_fraction,
score=list(score) or None,
)
@click.command(
"from-volume",
help=(
"Create a geometry from a tetrahedral volume mesh and labelled boundary surfaces (e.g. a "
"patient mesh): every boundary face must lie on exactly one surface"
),
)
@click.argument(
"outdir",
required=True,
type=click.Path(file_okay=False, dir_okay=True, writable=True, resolve_path=True),
)
@click.argument("volume", required=True, type=click.Path(exists=True, dir_okay=False))
@click.option(
"--surface",
"surfaces",
multiple=True,
required=True,
help="NAME=FILE, e.g. LV_ENDO=endo_lv.ply (repeat for each marker)",
)
@click.option(
"--scale", default=1.0, type=float, help="Multiply all coordinates", show_default=True
)
@click.option(
"--tol",
default=None,
type=float,
help="Distance within which surface and volume nodes match (default: exact)",
)
@click.option(
"--create-fibers/--no-create-fibers", default=False, help="Create fibers", show_default=True
)
@click.option(
"--fiber-method",
default="ldrb",
type=click.Choice(["ldrb", "doste"]),
help="Bayer et al. (ldrb) or Doste et al. (doste, needs the valves)",
show_default=True,
)
@click.option("--fiber-space", default="P_1", type=str, help="Fiber space", show_default=True)
@click.option(
"--data",
"data_file",
default=None,
type=click.Path(exists=True, dir_okay=False),
help=(
"TOML file with cell_tags = ARRAY, [cells] (tag = name), [fibers] (f0 = ARRAY, ...) and "
"[fields.NAME] (array, unit, values or description): arrays of the volume to read"
),
)
@unit_option(required=True)
@io_backend_option
@export_option
def from_volume(
outdir: str,
volume: str,
surfaces: tuple[str, ...],
scale: float = 1.0,
tol: float | None = None,
create_fibers: bool = False,
fiber_method: str = "ldrb",
fiber_space: str = "P_1",
data_file: str | None = None,
unit: str | None = None,
io_backend: str = DEFAULT_IO_BACKEND,
):
parsed = {}
for item in surfaces:
name, sep, file = item.partition("=")
if not sep or not name or not file:
raise click.BadParameter(f"Expected NAME=FILE, got {item!r}", param_hint="--surface")
parsed[name] = Path(file)
data: dict = {}
try:
if data_file is not None:
from .convert import load_volume_data
data = load_volume_data(Path(data_file))
mesh.from_volume(
outdir=Path(outdir),
volume=Path(volume),
surfaces=parsed,
scale=scale,
tol=tol,
create_fibers=create_fibers,
fiber_method=fiber_method,
fiber_space=fiber_space,
unit=unit,
io_backend=io_backend,
**data,
)
except ValueError as e:
if data_file is None:
raise
raise click.ClickException(str(e)) from e
@click.command(help="Create LV ellipsoidal geometry")
@click.argument(
"outdir",
required=True,
type=click.Path(
file_okay=False,
dir_okay=True,
writable=True,
readable=True,
resolve_path=True,
),
)
@click.option(
"--r-short-endo",
default=7.0,
type=float,
help="Shortest radius on the endocardium layer",
show_default=True,
)
@click.option(
"--r-short-epi",
default=10.0,
type=float,
help="Shortest radius on the epicardium layer",
show_default=True,
)
@click.option(
"--r-long-endo",
default=17.0,
type=float,
help="Longest radius on the endocardium layer",
show_default=True,
)
@click.option(
"--r-long-epi",
default=20.0,
type=float,
help="Longest radius on the epicardium layer",
show_default=True,
)
@click.option(
"--psize-ref",
default=3.0,
type=float,
help="The reference point size (smaller values yield as finer mesh",
show_default=True,
)
@click.option(
"--mu-apex-endo",
default=-math.pi,
type=float,
help="Angle for the endocardial apex",
show_default=True,
)
@click.option(
"--mu-base-endo",
default=-math.acos(5 / 17),
type=float,
help="Angle for the endocardial base",
show_default=True,
)
@click.option(
"--mu-apex-epi",
default=-math.pi,
type=float,
help="Angle for the epicardial apex",
show_default=True,
)
@click.option(
"--mu-base-epi",
default=-math.acos(5 / 20),
type=float,
help="Angle for the epicardial base",
show_default=True,
)
@click.option(
"--create-fibers",
default=False,
is_flag=True,
help="If True create analytic fibers",
show_default=True,
)
@click.option(
"--fiber-angle-endo",
default=-60,
type=float,
help="Angle for the endocardium",
show_default=True,
)
@click.option(
"--fiber-angle-epi",
default=+60,
type=float,
help="Angle for the epicardium",
show_default=True,
)
@click.option(
"--fiber-space",
default="P_1",
type=str,
help="Function space for fibers of the form family_degree",
show_default=True,
)
@click.option(
"--aha/--no-aha",
default=False,
is_flag=True,
type=bool,
help="If True create 17-segment AHA regions",
show_default=True,
)
@click.option(
"--dmu-factor",
default=1 / 4,
type=float,
help="Factor for adjusting the thickness of the AHA segments",
show_default=True,
)
@click.option(
"--ghost-mode",
default=dolfinx.mesh.GhostMode.none,
type=click.Choice(
dolfinx.mesh.GhostMode,
case_sensitive=False,
),
help="Ghost mode for the mesh",
show_default=True,
)
@click.option(
"--order",
default=1,
type=int,
help="Order of the mesh elements",
show_default=True,
)
@unit_option("mm")
@io_backend_option
@export_option
def lv_ellipsoid(
outdir: Path,
r_short_endo: float = 7.0,
r_short_epi: float = 10.0,
r_long_endo: float = 17.0,
r_long_epi: float = 20.0,
psize_ref: float = 3,
mu_apex_endo: float = -math.pi,
mu_base_endo: float = -math.acos(5 / 17),
mu_apex_epi: float = -math.pi,
mu_base_epi: float = -math.acos(5 / 20),
create_fibers: bool = False,
fiber_angle_endo: float = -60,
fiber_angle_epi: float = +60,
fiber_space: str = "P_1",
aha: bool = False,
dmu_factor: float = 1 / 4,
ghost_mode: dolfinx.mesh.GhostMode = dolfinx.mesh.GhostMode.none,
order: int = 1,
unit: str = "mm",
io_backend: str = DEFAULT_IO_BACKEND,
):
outdir = Path(outdir)
outdir.mkdir(exist_ok=True)
mesh.lv_ellipsoid(
outdir=outdir,
r_short_endo=r_short_endo,
r_short_epi=r_short_epi,
r_long_endo=r_long_endo,
r_long_epi=r_long_epi,
mu_base_endo=mu_base_endo,
mu_base_epi=mu_base_epi,
mu_apex_endo=mu_apex_endo,
mu_apex_epi=mu_apex_epi,
psize_ref=psize_ref,
create_fibers=create_fibers,
fiber_angle_endo=fiber_angle_endo,
fiber_angle_epi=fiber_angle_epi,
fiber_space=fiber_space,
aha=aha,
dmu_factor=dmu_factor,
ghost_mode=ghost_mode,
order=order,
unit=unit,
io_backend=io_backend,
)
@click.command(help="Create the meridian of an LV ellipsoid, for axisymmetric problems")
@click.argument(
"outdir",
required=True,
type=click.Path(
file_okay=False,
dir_okay=True,
writable=True,
readable=True,
resolve_path=True,
),
)
@click.option(
"--r-short-endo",
default=7.0,
type=float,
help="Shortest radius on the endocardium layer",
show_default=True,
)
@click.option(
"--r-short-epi",
default=10.0,
type=float,
help="Shortest radius on the epicardium layer",
show_default=True,
)
@click.option(
"--r-long-endo",
default=17.0,
type=float,
help="Longest radius on the endocardium layer",
show_default=True,
)
@click.option(
"--r-long-epi",
default=20.0,
type=float,
help="Longest radius on the epicardium layer",
show_default=True,
)
@click.option(
"--psize-ref",
default=3.0,
type=float,
help="The reference point size (smaller values yield as finer mesh",
show_default=True,
)
@click.option(
"--mu-apex-endo",
default=math.pi,
type=float,
help="Angle for the endocardial apex",
show_default=True,
)
@click.option(
"--mu-base-endo",
default=math.acos(5 / 17),
type=float,
help="Angle for the endocardial base",
show_default=True,
)
@click.option(
"--mu-apex-epi",
default=math.pi,
type=float,
help="Angle for the epicardial apex",
show_default=True,
)
@click.option(
"--mu-base-epi",
default=math.acos(5 / 20),
type=float,
help="Angle for the epicardial base",
show_default=True,
)
@click.option(
"--create-fibers",
default=False,
is_flag=True,
help="If True create analytic fibers",
show_default=True,
)
@click.option(
"--fiber-angle-endo",
default=-60,
type=float,
help="Angle for the endocardium",
show_default=True,
)
@click.option(
"--fiber-angle-epi",
default=+60,
type=float,
help="Angle for the epicardium",
show_default=True,
)
@click.option(
"--fiber-space",
default="P_1",
type=str,
help="Function space for fibers of the form family_degree",
show_default=True,
)
@click.option(
"--ghost-mode",
default=dolfinx.mesh.GhostMode.none,
type=click.Choice(
dolfinx.mesh.GhostMode,
case_sensitive=False,
),
help="Ghost mode for the mesh",
show_default=True,
)
@click.option(
"--order",
default=1,
type=int,
help="Order of the mesh elements",
show_default=True,
)
@unit_option("mm")
@io_backend_option
@export_option
def lv_ellipsoid_2D(
outdir: Path,
r_short_endo: float = 7.0,
r_short_epi: float = 10.0,
r_long_endo: float = 17.0,
r_long_epi: float = 20.0,
psize_ref: float = 3,
mu_apex_endo: float = math.pi,
mu_base_endo: float = math.acos(5 / 17),
mu_apex_epi: float = math.pi,
mu_base_epi: float = math.acos(5 / 20),
create_fibers: bool = False,
fiber_angle_endo: float = -60,
fiber_angle_epi: float = +60,
fiber_space: str = "P_1",
ghost_mode: dolfinx.mesh.GhostMode = dolfinx.mesh.GhostMode.none,
order: int = 1,
unit: str = "mm",
io_backend: str = DEFAULT_IO_BACKEND,
):
outdir = Path(outdir)
outdir.mkdir(exist_ok=True)
mesh.lv_ellipsoid_2D(
outdir=outdir,
r_short_endo=r_short_endo,
r_short_epi=r_short_epi,
r_long_endo=r_long_endo,
r_long_epi=r_long_epi,
mu_base_endo=mu_base_endo,
mu_base_epi=mu_base_epi,
mu_apex_endo=mu_apex_endo,
mu_apex_epi=mu_apex_epi,
psize_ref=psize_ref,
create_fibers=create_fibers,
fiber_angle_endo=fiber_angle_endo,
fiber_angle_epi=fiber_angle_epi,
fiber_space=fiber_space,
ghost_mode=ghost_mode,
order=order,
unit=unit,
io_backend=io_backend,
)
@click.command(help="Create BiV ellipsoidal geometry")
@click.argument(
"outdir",
required=True,
type=click.Path(
file_okay=False,
dir_okay=True,
writable=True,
readable=True,
resolve_path=True,
),
)
@click.option(
"--char-length",
default=0.4,
type=float,
help="Characteristic length of mesh",
show_default=True,
)
@click.option(
"--base-cut-z",
default=1.0,
type=float,
help="Z-coordinate of the base cut",
show_default=True,
)
@click.option(
"--box-size",
default=20.0,
type=float,
help="Size of the cutting box",
show_default=True,
)
@click.option(
"--rv-wall-thickness",
default=0.3,
type=float,
help="Thickness of the right ventricle wall",
show_default=True,
)
@click.option(
"--lv-wall-thickness",
default=0.5,
type=float,
help="Thickness of the left ventricle wall",
show_default=True,
)
@click.option(
"--rv-offset-x",
default=1.0,
type=float,
help="X-offset of the right ventricle",
show_default=True,
)
@click.option(
"--lv-radius-x",
default=2.2,
type=float,
help="X-radius of the left ventricle",
show_default=True,
)
@click.option(
"--lv-radius-y",
default=2.2,
type=float,
help="Y-radius of the left ventricle",
show_default=True,
)
@click.option(
"--lv-radius-z",
default=4.5,
type=float,
help="Z-radius of the left ventricle",
show_default=True,
)
@click.option(
"--rv-radius-x",
default=3.2,
type=float,
help="X-radius of the right ventricle",
show_default=True,
)
@click.option(
"--rv-radius-y",
default=2.3,
type=float,
help="Y-radius of the right ventricle",
show_default=True,
)
@click.option(
"--rv-radius-z",
default=4.3,
type=float,
help="Z-radius of the right ventricle",
show_default=True,
)
@click.option(
"--create-fibers",
default=False,
is_flag=True,
help="If True create rule-based fibers with fenicsx-ldrb (Bayer et al. 2012)",
show_default=True,
)
@click.option(
"--fiber-angle-endo",
default=-60,
type=float,
help="Angle for the endocardium",
show_default=True,
)
@click.option(
"--fiber-angle-epi",
default=+60,
type=float,
help="Angle for the epicardium",
show_default=True,
)
@click.option(
"--fiber-space",
default="P_1",
type=str,
help="Function space for fibers of the form family_degree",
show_default=True,
)
@click.option(
"-v",
"--verbose",
is_flag=True,
help="Enable verbose output",
show_default=True,
)
@click.option(
"--ghost-mode",
default=dolfinx.mesh.GhostMode.none,
type=click.Choice(
dolfinx.mesh.GhostMode,
case_sensitive=False,
),
help="Ghost mode for the mesh",
show_default=True,
)
@click.option(
"--order",
default=1,
type=int,
help="Order of the mesh elements",
show_default=True,
)
@unit_option("cm")
@io_backend_option
@export_option
def biv_ellipsoid(
outdir: Path,
char_length: float = 0.4, # cm
base_cut_z: float = 2.5,
box_size: float = 20.0, # Size of the cutting box
rv_wall_thickness: float = 0.4, # cm
lv_wall_thickness: float = 0.5, # cm
rv_offset_x: float = 1.4,
lv_radius_x: float = 2.0,
lv_radius_y: float = 1.8,
lv_radius_z: float = 4.0,
rv_radius_x: float = 3.8,
rv_radius_y: float = 2.6,
rv_radius_z: float = 4.0,
create_fibers: bool = False,
fiber_angle_endo: float = -60,
fiber_angle_epi: float = +60,
fiber_space: str = "P_1",
verbose: bool = False,
ghost_mode: dolfinx.mesh.GhostMode = dolfinx.mesh.GhostMode.none,
order: int = 1,
unit: str = "cm",
io_backend: str = DEFAULT_IO_BACKEND,
):
init_logging(verbose=verbose)
outdir = Path(outdir)
outdir.mkdir(exist_ok=True)
mesh.biv_ellipsoid(
outdir=outdir,
char_length=char_length,
base_cut_z=base_cut_z,
box_size=box_size,
rv_wall_thickness=rv_wall_thickness,
lv_wall_thickness=lv_wall_thickness,
rv_offset_x=rv_offset_x,
lv_radius_x=lv_radius_x,
lv_radius_y=lv_radius_y,
lv_radius_z=lv_radius_z,
rv_radius_x=rv_radius_x,
rv_radius_y=rv_radius_y,
rv_radius_z=rv_radius_z,
create_fibers=create_fibers,
fiber_angle_endo=fiber_angle_endo,
fiber_angle_epi=fiber_angle_epi,
fiber_space=fiber_space,
verbose=verbose,
ghost_mode=ghost_mode,
order=order,
unit=unit,
io_backend=io_backend,
)
@click.command(help="Create slab geometry")
@click.argument(
"outdir",
required=True,
type=click.Path(
file_okay=False,
dir_okay=True,
writable=True,
readable=True,
resolve_path=True,
),
)
@click.option(
"--lx",
default=20.0,
type=float,
help="Length of slab in the x-direction",
show_default=True,
)
@click.option(
"--ly",
default=7.0,
type=float,
help="Length of slab in the y-direction",
show_default=True,
)
@click.option(
"--lz",
default=1.0,
type=float,
help="Length of slab in the z-direction",
show_default=True,
)
@click.option(
"--dx",
default=1.0,
type=float,
help="Element size",
show_default=True,
)
@click.option(
"--create-fibers",
default=False,
is_flag=True,
help="If True create analytic fibers",
show_default=True,
)
@click.option(
"--fiber-angle-endo",
default=-60,
type=float,
help="Angle for the endocardium",
show_default=True,
)
@click.option(
"--fiber-angle-epi",
default=+60,
type=float,
help="Angle for the epicardium",
show_default=True,
)
@click.option(
"--fiber-space",
default="P_1",
type=str,
help="Function space for fibers of the form family_degree",
show_default=True,
)
@click.option(
"--ghost-mode",
default=dolfinx.mesh.GhostMode.none,
type=click.Choice(
dolfinx.mesh.GhostMode,
case_sensitive=False,
),
help="Ghost mode for the mesh",
show_default=True,
)
@click.option(
"--order",
default=1,
type=int,
help="Order of the mesh elements",
show_default=True,
)
@unit_option("mm")
@io_backend_option
@export_option
def slab(
outdir: Path,
lx: float = 20.0,
ly: float = 7.0,
lz: float = 3.0,
dx: float = 1.0,
create_fibers: bool = True,
fiber_angle_endo: float = -60,
fiber_angle_epi: float = +60,
fiber_space: str = "P_1",
ghost_mode: dolfinx.mesh.GhostMode = dolfinx.mesh.GhostMode.none,
order: int = 1,
unit: str = "mm",
io_backend: str = DEFAULT_IO_BACKEND,
):
outdir = Path(outdir)
outdir.mkdir(exist_ok=True)
mesh.slab(
outdir=outdir,
lx=lx,
ly=ly,
lz=lz,
dx=dx,
create_fibers=create_fibers,
fiber_angle_endo=fiber_angle_endo,
fiber_angle_epi=fiber_angle_epi,
fiber_space=fiber_space,
ghost_mode=ghost_mode,
order=order,
unit=unit,
io_backend=io_backend,
)
@click.command(help="Create slab in bath geometry")
@click.argument(
"outdir",
required=True,
type=click.Path(
file_okay=False,
dir_okay=True,
writable=True,
readable=True,
resolve_path=True,
),
)
@click.option(
"--lx",
default=1.0,
type=float,
help="Length of slab in the x-direction",
show_default=True,
)
@click.option(
"--ly",
default=0.01,
type=float,
help="Length of slab in the y-direction",
show_default=True,
)
@click.option(
"--lz",
default=0.5,
type=float,
help="Length of slab in the z-direction",
show_default=True,
)
@click.option(
"--bx",
default=0.0,
type=float,
help="Thickness of bath in the x-direction",
show_default=True,
)
@click.option(
"--by",
default=0.0,
type=float,
help="Thickness of bath in the y-direction",
show_default=True,
)
@click.option(
"--bz",
default=0.1,
type=float,
help="Thickness of bath in the z-direction",
show_default=True,
)
@click.option(
"--dx",
default=0.01,
type=float,
help="Element size",
show_default=True,
)
@click.option(
"--ghost-mode",
default=dolfinx.mesh.GhostMode.none,
type=click.Choice(
dolfinx.mesh.GhostMode,
case_sensitive=False,
),
help="Ghost mode for the mesh",
show_default=True,
)
@click.option(
"--order",
default=1,
type=int,
help="Order of the mesh elements",
show_default=True,
)
@unit_option()
@io_backend_option
@export_option
def slab_in_bath(
outdir: Path,
lx: float = 1.0,
ly: float = 0.01,
lz: float = 0.5,
bx: float = 0.0,
by: float = 0.0,
bz: float = 0.1,
dx: float = 0.01,
ghost_mode: dolfinx.mesh.GhostMode = dolfinx.mesh.GhostMode.none,
order: int = 1,
unit: str | None = None,
io_backend: str = DEFAULT_IO_BACKEND,
):
outdir = Path(outdir)
outdir.mkdir(exist_ok=True)
mesh.slab_in_bath(
outdir=outdir,
lx=lx,
ly=ly,
lz=lz,
bx=bx,
by=by,
bz=bz,
dx=dx,
ghost_mode=ghost_mode,
order=order,
unit=unit,
io_backend=io_backend,
)
@click.command(help="Create cylinder geometry")
@click.argument(
"outdir",
required=True,
type=click.Path(
file_okay=False,
dir_okay=True,
writable=True,
readable=True,
resolve_path=True,
),
)
@click.option(
"--char-length",
default=5.0,
type=float,
help="Characteristic length of mesh",
show_default=True,
)
@click.option(
"--r-inner",
default=10.0,
type=float,
help="Inner radius of the cylinder",
show_default=True,
)
@click.option(
"--r-outer",
default=15.0,
type=float,
help="Outer radius of the cylinder",
show_default=True,
)
@click.option(
"--height",
default=40.0,
type=float,
help="Height of the cylinder",
show_default=True,
)
@click.option(
"--floor-thickness",
default=0.0,
type=float,
help="Thickness of the floor",
show_default=True,
)
@click.option(
"--roof-thickness",
default=0.0,
type=float,
help="Thickness of the roof",
show_default=True,
)
@click.option(
"--create-fibers",
default=False,
is_flag=True,
help="If True create analytic fibers",
show_default=True,
)
@click.option(
"--fiber-angle-endo",
default=-60,
type=float,
help="Angle for the endocardium",
show_default=True,
)
@click.option(
"--fiber-angle-epi",
default=+60,
type=float,
help="Angle for the epicardium",
show_default=True,
)
@click.option(
"--fiber-space",
default="P_1",
type=str,
help="Function space for fibers of the form family_degree",
show_default=True,
)
@click.option(
"--ghost-mode",
default=dolfinx.mesh.GhostMode.none,
type=click.Choice(
dolfinx.mesh.GhostMode,
case_sensitive=False,
),
help="Ghost mode for the mesh",
show_default=True,
)
@click.option(
"--order",
default=1,
type=int,
help="Order of the mesh elements",
show_default=True,
)
@unit_option("mm")
@io_backend_option
@export_option
def cylinder(
outdir: Path,
char_length: float = 5.0,
r_inner: float = 10.0,
r_outer: float = 15.0,
height: float = 40.0,
floor_thickness: float = 0.0,
roof_thickness: float = 0.0,
create_fibers: bool = False,
fiber_angle_endo: float = -60,
fiber_angle_epi: float = +60,
fiber_space: str = "P_1",
ghost_mode: dolfinx.mesh.GhostMode = dolfinx.mesh.GhostMode.none,
order: int = 1,
unit: str = "mm",
io_backend: str = DEFAULT_IO_BACKEND,
):
outdir = Path(outdir)
outdir.mkdir(exist_ok=True)
mesh.cylinder(
outdir=outdir,
r_inner=r_inner,
r_outer=r_outer,
height=height,
floor_thickness=floor_thickness,
roof_thickness=roof_thickness,
char_length=char_length,
create_fibers=create_fibers,
fiber_angle_endo=fiber_angle_endo,
fiber_angle_epi=fiber_angle_epi,
fiber_space=fiber_space,
ghost_mode=ghost_mode,
order=order,
unit=unit,
io_backend=io_backend,
)
@click.command(help="Create elliptical cylinder geometry")
@click.argument(
"outdir",
required=True,
type=click.Path(
file_okay=False,
dir_okay=True,
writable=True,
readable=True,
resolve_path=True,
),
)
@click.option(
"--char-length",
default=10.0,
type=float,
help="Characteristic length of mesh",
show_default=True,
)
@click.option(
"--r-inner-x",
default=10.0,
type=float,
help="Inner radius of the cylinder in the x-direction",
show_default=True,
)
@click.option(
"--r-inner-y",
default=10.0,
type=float,
help="Inner radius of the cylinder in the y-direction",
show_default=True,
)
@click.option(
"--r-outer-x",
default=20.0,
type=float,
help="Outer radius of the cylinder in the x-direction",
show_default=True,
)
@click.option(
"--r-outer-y",
default=20.0,
type=float,
help="Outer radius of the cylinder in the y-direction",
show_default=True,
)
@click.option(
"--height",
default=40.0,
type=float,
help="Height of the cylinder",
show_default=True,
)
@click.option(
"--create-fibers",
default=False,
is_flag=True,
help="If True create analytic fibers",
show_default=True,
)
@click.option(
"--fiber-angle-endo",
default=-60,
type=float,
help="Angle for the endocardium",
show_default=True,
)
@click.option(
"--fiber-angle-epi",
default=+60,
type=float,
help="Angle for the epicardium",
show_default=True,
)
@click.option(
"--fiber-space",
default="P_1",
type=str,
help="Function space for fibers of the form family_degree",
show_default=True,
)
@click.option(
"--order",
default=1,
type=int,
help="Order of the mesh elements",
show_default=True,
)
@unit_option("mm")
@io_backend_option
@export_option
def cylinder_elliptical(
outdir: Path,
char_length: float = 10.0,
r_inner_x: float = 10.0,
r_inner_y: float = 10.0,
r_outer_x: float = 20.0,
r_outer_y: float = 20.0,
height: float = 40.0,
create_fibers: bool = False,
fiber_angle_endo: float = -60,
fiber_angle_epi: float = +60,
fiber_space: str = "P_1",
order: int = 1,
unit: str = "mm",
io_backend: str = DEFAULT_IO_BACKEND,
):
outdir = Path(outdir)
outdir.mkdir(exist_ok=True)
mesh.cylinder_elliptical(
outdir=outdir,
r_inner_x=r_inner_x,
r_inner_y=r_inner_y,
r_outer_x=r_outer_x,
r_outer_y=r_outer_y,
height=height,
char_length=char_length,
create_fibers=create_fibers,
fiber_angle_endo=fiber_angle_endo,
fiber_angle_epi=fiber_angle_epi,
fiber_space=fiber_space,
order=order,
unit=unit,
io_backend=io_backend,
)
@click.command(help="Create racetrack cylinder geometry")
@click.argument(
"outdir",
required=True,
type=click.Path(
file_okay=False,
dir_okay=True,
writable=True,
readable=True,
resolve_path=True,
),
)
@click.option(
"--char-length",
default=10.0,
type=float,
help="Characteristic length of mesh",
show_default=True,
)
@click.option(
"--r-inner",
default=13.0,
type=float,
help="Inner radius of the cylinder",
show_default=True,
)
@click.option(
"--r-outer",
default=20.0,
type=float,
help="Outer radius of the cylinder",
show_default=True,
)
@click.option(
"--height",
default=40.0,
type=float,
help="Height of the cylinder",
show_default=True,
)
@click.option(
"--inner-flat-face-distance",
default=10.0,
type=float,
help="Distance from the inner flat face to the center",
show_default=True,
)
@click.option(
"--outer-flat-face-distance",
default=17.0,
type=float,
help="Distance from the outer flat face to the center",
show_default=True,
)
@click.option(
"--create-fibers",
default=False,
is_flag=True,
help="If True create analytic fibers",
show_default=True,
)
@click.option(
"--fiber-angle-endo",
default=-60,
type=float,
help="Angle for the endocardium",
show_default=True,
)
@click.option(
"--fiber-angle-epi",
default=+60,
type=float,
help="Angle for the epicardium",
show_default=True,
)
@click.option(
"--fiber-space",
default="P_1",
type=str,
help="Function space for fibers of the form family_degree",
show_default=True,
)
@click.option(
"--fillet-radius",
default=None,
type=float,
help="Radius for filleting the corners",
show_default=True,
)
@click.option(
"--ghost-mode",
default=dolfinx.mesh.GhostMode.none,
type=click.Choice(
dolfinx.mesh.GhostMode,
case_sensitive=False,
),
help="Ghost mode for the mesh",
show_default=True,
)
@click.option(
"--order",
default=1,
type=int,
help="Order of the mesh elements",
show_default=True,
)
@unit_option("mm")
@io_backend_option
@export_option
def cylinder_racetrack(
outdir: Path,
char_length: float = 10.0,
r_inner: float = 13.0,
r_outer: float = 20.0,
height: float = 40.0,
inner_flat_face_distance: float = 10.0,
outer_flat_face_distance: float = 17.0,
create_fibers: bool = False,
fiber_angle_endo: float = -60,
fiber_angle_epi: float = +60,
fiber_space: str = "P_1",
fillet_radius: float | None = None,
ghost_mode: dolfinx.mesh.GhostMode = dolfinx.mesh.GhostMode.none,
order: int = 1,
unit: str = "mm",
io_backend: str = DEFAULT_IO_BACKEND,
):
outdir = Path(outdir)
outdir.mkdir(exist_ok=True)
mesh.cylinder_racetrack(
outdir=outdir,
r_inner=r_inner,
r_outer=r_outer,
height=height,
inner_flat_face_distance=inner_flat_face_distance,
outer_flat_face_distance=outer_flat_face_distance,
char_length=char_length,
create_fibers=create_fibers,
fiber_angle_endo=fiber_angle_endo,
fiber_angle_epi=fiber_angle_epi,
fiber_space=fiber_space,
ghost_mode=ghost_mode,
fillet_radius=fillet_radius,
order=order,
unit=unit,
io_backend=io_backend,
)
@click.command(help="Create D-shaped cylinder geometry")
@click.argument(
"outdir",
required=True,
type=click.Path(
file_okay=False,
dir_okay=True,
writable=True,
readable=True,
resolve_path=True,
),
)
@click.option(
"--char-length",
default=10.0,
type=float,
help="Characteristic length of mesh",
show_default=True,
)
@click.option(
"--r-inner",
default=13.0,
type=float,
help="Inner radius of the cylinder",
show_default=True,
)
@click.option(
"--r-outer",
default=20.0,
type=float,
help="Outer radius of the cylinder",
show_default=True,
)
@click.option(
"--height",
default=40.0,
type=float,
help="Height of the cylinder",
show_default=True,
)
@click.option(
"--inner-flat-face-distance",
default=10.0,
type=float,
help="Distance from the inner flat face to the center",
show_default=True,
)
@click.option(
"--outer-flat-face-distance",
default=17.0,
type=float,
help="Distance from the outer flat face to the center",
show_default=True,
)
@click.option(
"--floor-thickness",
default=0.0,
type=float,
help="Thickness of the floor",
show_default=True,
)
@click.option(
"--roof-thickness",
default=0.0,
type=float,
help="Thickness of the roof",
show_default=True,
)
@click.option(
"--create-fibers",
default=False,
is_flag=True,
help="If True create analytic fibers",
show_default=True,
)
@click.option(
"--fiber-angle-endo",
default=-60,
type=float,
help="Angle for the endocardium",
show_default=True,
)
@click.option(
"--fiber-angle-epi",
default=+60,
type=float,
help="Angle for the epicardium",
show_default=True,
)
@click.option(
"--fiber-space",
default="P_1",
type=str,
help="Function space for fibers of the form family_degree",
show_default=True,
)
@click.option(
"--fillet-radius",
default=None,
type=float,
help="Radius for filleting the corners",
show_default=True,
)
@click.option(
"--ghost-mode",
default=dolfinx.mesh.GhostMode.none,
type=click.Choice(
dolfinx.mesh.GhostMode,
case_sensitive=False,
),
help="Ghost mode for the mesh",
show_default=True,
)
@click.option(
"--order",
default=1,
type=int,
help="Order of the mesh elements",
show_default=True,
)
@unit_option("mm")
@io_backend_option
@export_option
def cylinder_D_shaped(
outdir: Path,
char_length: float = 10.0,
r_inner: float = 13.0,
r_outer: float = 20.0,
height: float = 40.0,
inner_flat_face_distance: float = 10.0,
outer_flat_face_distance: float = 17.0,
floor_thickness: float = 0.0,
roof_thickness: float = 0.0,
create_fibers: bool = False,
fiber_angle_endo: float = -60,
fiber_angle_epi: float = +60,
fiber_space: str = "P_1",
fillet_radius: float | None = None,
ghost_mode: dolfinx.mesh.GhostMode = dolfinx.mesh.GhostMode.none,
order: int = 1,
unit: str = "mm",
io_backend: str = DEFAULT_IO_BACKEND,
):
outdir = Path(outdir)
outdir.mkdir(exist_ok=True)
mesh.cylinder_D_shaped(
outdir=outdir,
r_inner=r_inner,
r_outer=r_outer,
height=height,
inner_flat_face_distance=inner_flat_face_distance,
outer_flat_face_distance=outer_flat_face_distance,
floor_thickness=floor_thickness,
roof_thickness=roof_thickness,
char_length=char_length,
create_fibers=create_fibers,
fiber_angle_endo=fiber_angle_endo,
fiber_angle_epi=fiber_angle_epi,
fiber_space=fiber_space,
ghost_mode=ghost_mode,
fillet_radius=fillet_radius,
order=order,
unit=unit,
io_backend=io_backend,
)
@click.command("gui")
def gui():
# Make sure we can import the required packages
from . import gui # noqa: F401
gui_path = Path(__file__).parent.joinpath("gui.py")
import subprocess as sp
sp.run(["streamlit", "run", gui_path.as_posix()])
@click.command(help="Rotate a mesh to align with a target normal")
@click.argument(
"folder",
required=True,
type=click.Path(
file_okay=False,
dir_okay=True,
writable=True,
readable=True,
resolve_path=True,
),
)
@click.option(
"-o",
"--outdir",
required=True,
type=click.Path(
file_okay=False,
dir_okay=True,
writable=True,
readable=True,
resolve_path=True,
),
)
@click.option(
"--target-normal",
required=True,
type=float,
nargs=3,
help="Target normal vector to align the base normal with",
)
@click.option(
"--base-marker",
default="BASE",
type=str,
help="Marker name for the base",
show_default=True,
)
@click.option(
"-v",
"--verbose",
is_flag=True,
help="Enable verbose output",
show_default=True,
)
@click.option(
"--ghost-mode",
default=dolfinx.mesh.GhostMode.none,
type=click.Choice(
dolfinx.mesh.GhostMode,
case_sensitive=False,
),
help="Ghost mode for the mesh",
show_default=True,
)
@io_backend_option
def rotate(
folder: Path,
outdir: Path,
target_normal: list[float],
base_marker: str = "BASE",
verbose: bool = False,
ghost_mode: dolfinx.mesh.GhostMode = dolfinx.mesh.GhostMode.none,
io_backend: str = DEFAULT_IO_BACKEND,
):
from .geometry import Geometry
init_logging(verbose=verbose)
comm = MPI.COMM_WORLD
path = find_geometry_file(folder)
if path is not None:
geo = Geometry.from_file(comm=comm, path=path, ghost_mode=ghost_mode)
else:
# an old folder: mesh.xdmf and the microstructure files
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
geo = Geometry.from_folder(comm=comm, folder=Path(folder), ghost_mode=ghost_mode)
rotated = geo.rotate(target_normal=target_normal, base_marker=base_marker)
outdir = Path(outdir)
outdir.mkdir(parents=True, exist_ok=True)
rotated.save(geometry_path(outdir, io_backend), backend=io_backend)
if comm.rank == 0:
(outdir / "markers.json").write_text(json.dumps(rotated.markers, indent=4))
(outdir / "info.json").write_text(json.dumps(rotated.info, indent=4))
def _geometry_file(file: Path | str) -> Path:
"""`file` as the path of a geometry file. A folder (but an adios2 ``.bp`` directory) is not
one: raise a ClickException that names the file inside it, or suggests `geox convert`."""
path = Path(file)
if path.is_dir() and path.suffix.lower() != ".bp":
inside = find_geometry_file(path)
if inside is not None:
raise click.ClickException(f"{path} is a folder; give the file {inside}")
raise click.ClickException(
f"{path} is a folder with no geometry.h5 or geometry.bp. If it holds a geometry "
"in an older layout, convert it into a file with `geox convert`"
)
return path
def _read_geometry(comm: MPI.Comm, path: Path):
"""The geometry in the file `path`, or a ClickException if its format is too new."""
from .geometry import Geometry
from .metadata import FormatError
try:
return Geometry.from_file(comm=comm, path=path)
except FormatError as e:
raise click.ClickException(str(e)) from e
@click.command(name="check", help="Check a geometry file against the standard")
@click.argument("file", required=True, type=click.Path(exists=True, dir_okay=True))
def check_command(file: Path):
from .check import Problem, check, has_errors
from .geometry import Geometry
from .metadata import FormatError
comm = MPI.COMM_WORLD
file = _geometry_file(file)
try:
geo = Geometry.from_file(comm=comm, path=file)
except FormatError as e:
problems = [Problem("C1", "error", str(e))]
else:
problems = check(geo)
if comm.rank == 0:
if problems:
for problem in problems:
click.echo(str(problem))
else:
click.echo("no problems")
if has_errors(problems):
raise SystemExit(1)
@click.command(name="inspect", help="Print what a geometry file holds")
@click.argument("file", required=True, type=click.Path(exists=True, dir_okay=True))
@click.option("--json", "as_json", is_flag=True, help="Print the summary as JSON")
def inspect_command(file: Path, as_json: bool):
from .summary import format_summary, summarize
comm = MPI.COMM_WORLD
file = _geometry_file(file)
geo = _read_geometry(comm, file)
summary = summarize(geo, Path(file))
if comm.rank == 0:
click.echo(json.dumps(summary, default=str) if as_json else format_summary(summary))
@click.command(name="convert", help="Convert an existing geometry into one file of format 1")
@click.argument("source", required=True, type=click.Path(exists=True))
@click.argument("out", required=True, type=click.Path(dir_okay=False))
@click.option(
"--mapping",
required=True,
type=click.Path(exists=True, dir_okay=False),
help="TOML file with unit, [facets], [cells], [fields.<name>] and [info]",
)
def convert_command(source: Path, out: Path, mapping: Path):
from .convert import convert
try:
convert(Path(source), Path(out), Path(mapping), comm=MPI.COMM_WORLD)
except (ValueError, RuntimeError) as e:
raise click.ClickException(str(e)) from e
click.echo(f"Wrote {out}")
@click.command(name="export", help="Write VTU files of a geometry file for ParaView")
@click.argument("file", required=True, type=click.Path(exists=True, dir_okay=True))
@click.option(
"-o",
"--outdir",
type=click.Path(file_okay=False),
default=None,
help="Folder of the VTU files, by default <file's folder>/<stem>-viz",
)
def export_command(file: Path, outdir: Path | None):
from .export import export
comm = MPI.COMM_WORLD
file = _geometry_file(file)
if comm.size > 1:
raise click.ClickException("export works in serial: run it on one process")
folder = Path(outdir) if outdir is not None else file.parent / f"{file.stem}-viz"
geo = _read_geometry(comm, file)
try:
written = export(geo, folder)
except ImportError as e:
raise click.ClickException(str(e)) from e
for path in written:
click.echo(str(path))
@click.command(name="celltype", help="Compute the transmural cell type into a geometry file")
@click.argument("file", required=True, type=click.Path(exists=True, dir_okay=True))
@click.option("--endo", default=0.3, show_default=True, help="Endocardial fraction of the wall")
@click.option("--epi", default=0.3, show_default=True, help="Epicardial fraction of the wall")
@click.option(
"--space",
default="P_1",
show_default=True,
type=click.Choice(list(CELLTYPE_SPACES)),
help="Function space of the field",
)
def celltype_command(file: Path, endo: float, epi: float, space: str):
from .celltype import add_celltype
comm = MPI.COMM_WORLD
path = _geometry_file(file)
geo = _read_geometry(comm, path)
if geo.file_format == 0:
# It has no unit, and the JSON files beside it would be left describing a format-1 file
raise click.ClickException(
f"{path} is a geometry file of format 0. Convert it into format 1 with "
"`geox convert` first, and run celltype on the result"
)
try:
add_celltype(geo, endo=endo, epi=epi, space=space)
except ValueError as e:
raise click.ClickException(str(e)) from e
try:
geo.save_replacing(path)
except RuntimeError as e:
raise click.ClickException(str(e)) from e
if comm.rank == 0:
click.echo(f"Wrote celltype to {file}")
app.add_command(check_command)
app.add_command(celltype_command)
app.add_command(convert_command)
app.add_command(export_command)
app.add_command(inspect_command)
app.add_command(lv_ellipsoid)
app.add_command(lv_ellipsoid_2D)
app.add_command(biv_ellipsoid)
app.add_command(slab)
app.add_command(slab_in_bath)
app.add_command(gui)
app.add_command(ukb)
app.add_command(from_volume)
app.add_command(cylinder)
app.add_command(cylinder_elliptical)
app.add_command(cylinder_racetrack)
app.add_command(cylinder_D_shaped)
app.add_command(rotate)