Source code for cardiac_geometries.export

"""Export a geometry as VTU files, which ParaView reads without extra readers."""

import json
from pathlib import Path
from typing import Any

import dolfinx
import numpy as np

from . import utils
from .geometry import Geometry
from .standard import FIBER_NAMES

PYVISTA_MESSAGE = "Exporting a geometry needs pyvista: pip install cardiac-geometriesx[pyvista]"


def _kind(u: dolfinx.fem.Function, degree: int) -> str:
    """How `u` is exported: ``"volume"`` (point data of volume.vtu), ``"cells"`` (cell data of
    volume.vtu), ``"quadrature"`` (a point cloud) or ``"own"`` (its own grid)."""
    el = u.function_space.ufl_element()
    if el.family_name == "quadrature":
        return "quadrature"
    discontinuous = bool(el.basix_element.discontinuous)
    el_degree = int(el.degree)
    if discontinuous and el_degree == 0:
        return "cells"
    if not discontinuous and el_degree == degree:
        return "volume"
    return "own"


def _values(u: dolfinx.fem.Function, n: int) -> np.ndarray:
    """The values of `u` at its first `n` dofs, as a (n, 3) array for a vector (padded with
    zeros in 2D) and a vector of n for a scalar."""
    bs = u.function_space.dofmap.index_map_bs
    return _for_vtk(u.x.array.reshape(-1, bs)[:n])


def _for_vtk(values: np.ndarray) -> np.ndarray:
    """`values`, one row per dof or cell, as VTK takes them: a vector of a scalar's values, and
    (n, 3) rows of a vector's, padded with zeros in 2D."""
    bs = values.shape[1]
    if bs == 1:
        return np.ascontiguousarray(values[:, 0])
    if bs < 3:
        values = np.hstack([values, np.zeros((len(values), 3 - bs), dtype=values.dtype)])
    return np.ascontiguousarray(values)


[docs] def export(geometry: Geometry, outdir: Path) -> list[Path]: """Write `geometry` into `outdir` as VTU files for ParaView, and return the files written. - ``volume.vtu``: the mesh on its geometry's scalar Lagrange space. Its point data is every function on exactly that space, and its cell data the ``Cell tags`` (0 where untagged) and every DG0 function. - ``facets.vtu``: the tagged facets, with ``Facet tags`` as cell data (only with facet tags). - ``<name>.vtu``: each other Lagrange or DG function, on the grid of its own space. - ``<name>_points.vtu``: each quadrature function, a point cloud at the quadrature points. - ``markers.json``: the legend of the tags. MeshTags in ``additional_data`` are not exported, only Functions. Raises ------ ImportError Without pyvista. RuntimeError On more than one rank. """ mesh = geometry.mesh if mesh.comm.size > 1: raise RuntimeError("export works in serial: run `geox export FILE` on one process") try: import pyvista as pv except ImportError as e: raise ImportError(PYVISTA_MESSAGE) from e import dolfinx.plot outdir = Path(outdir) outdir.mkdir(parents=True, exist_ok=True) written: list[Path] = [] def save(grid: Any, name: str) -> None: path = outdir / name grid.save(str(path)) written.append(path) tdim = mesh.topology.dim degree = int(mesh.geometry.cmaps[0].degree) V0 = dolfinx.fem.functionspace(mesh, ("Lagrange", degree)) cells, types, x = dolfinx.plot.vtk_mesh(V0) # type: ignore[arg-type] volume = pv.UnstructuredGrid(cells, types, x) num_cells = mesh.topology.index_map(tdim).size_local if geometry.cfun is not None: tags = np.zeros(num_cells, dtype=np.int32) local = geometry.cfun.indices < num_cells tags[geometry.cfun.indices[local]] = geometry.cfun.values[local] volume.cell_data["Cell tags"] = tags functions: dict[str, dolfinx.fem.Function] = {} for name in FIBER_NAMES: u = getattr(geometry, name) if u is not None: functions[name] = u for name, data in geometry.additional_data.items(): if isinstance(data, dolfinx.fem.Function): functions[name] = data others: dict[str, tuple[dolfinx.fem.Function, str]] = {} for name, u in functions.items(): kind = _kind(u, degree) if kind == "volume": volume.point_data[name] = _values(u, len(x)) elif kind == "cells": bs = u.function_space.dofmap.index_map_bs dofs = u.function_space.dofmap.list[:num_cells, 0] volume.cell_data[name] = _for_vtk(u.x.array.reshape(-1, bs)[dofs]) else: others[name] = (u, kind) save(volume, "volume.vtu") if geometry.ffun is not None: ffun = geometry.ffun fcells, ftypes, fx = dolfinx.plot.vtk_mesh(mesh, tdim - 1, ffun.indices) facets = pv.UnstructuredGrid(fcells, ftypes, fx) facets.cell_data["Facet tags"] = np.asarray(ffun.values) save(facets, "facets.vtu") for name, (u, kind) in others.items(): V = u.function_space n = V.dofmap.index_map.size_local + V.dofmap.index_map.num_ghosts if kind == "quadrature": points = V.tabulate_dof_coordinates()[:n] cloud = pv.PolyData(np.ascontiguousarray(points)).cast_to_unstructured_grid() cloud.point_data[name] = _values(u, n) save(cloud, f"{name}_points.vtu") else: ocells, otypes, ox = dolfinx.plot.vtk_mesh(V) # type: ignore[arg-type] grid = pv.UnstructuredGrid(ocells, otypes, ox) grid.point_data[name] = _values(u, len(ox)) save(grid, f"{name}.vtu") markers_file = outdir / "markers.json" markers_file.write_text(json.dumps(geometry.markers, default=utils.json_serial)) written.append(markers_file) return written