"""Quasi-static hyperelastic vessel wall on quadratic tetrahedra with Warp FEM.
:class:`WarpHyperelasticWall` is a compressible Neo-Hookean solid on
quadratic (P2) tetrahedra. It is clamped at chosen vertices, optionally
tethered to its surroundings by springs on its outer surface, and can carry a
prestress so that the given geometry is in equilibrium under a given load.
It does not depend on the flow solver it is coupled to.
"""
from __future__ import annotations
import time
from typing import Any, ClassVar, Optional
import numpy as np
import warp as wp
from scipy import sparse
from scipy.spatial import cKDTree
from warp import fem
from .monai_physio_base import MONAIPhysioBase
from .process_volumetric_mesh import ProcessVolumetricMesh
from .warp_cudss_factor import WarpCuDssFactor
# Warp 1.17 FEM treats every annotation, including return, as an input. The
# wp.identity ignores are needed by the Warp 1.17 stubs, not by 1.19.
@fem.integrand
def wall_stress( # type: ignore[no-untyped-def]
s: fem.Sample,
u: fem.Field,
v: fem.Field,
prestress: wp.array(dtype=wp.mat33d), # type: ignore[valid-type]
mu: wp.float64,
lam: wp.float64,
):
"""Prestressed Neo-Hookean first Piola stress ``F S0 + P(F)`` against grad v."""
f = wp.identity(n=3, dtype=wp.float64) + fem.grad(u, s)
inverse_t = wp.transpose(wp.inverse(f))
stress = (
f * prestress[s.qp_index]
+ mu * (f - inverse_t)
+ lam * wp.log(wp.determinant(f)) * inverse_t
)
return wp.ddot(stress, fem.grad(v, s))
@fem.integrand
def wall_tangent( # type: ignore[no-untyped-def]
s: fem.Sample,
d: fem.Field,
u: fem.Field,
v: fem.Field,
prestress: wp.array(dtype=wp.mat33d), # type: ignore[valid-type]
mu: wp.float64,
lam: wp.float64,
):
"""Tangent of :func:`wall_stress` at the displacement ``d``."""
f = wp.identity(n=3, dtype=wp.float64) + fem.grad(d, s)
inverse_t = wp.transpose(wp.inverse(f))
h = fem.grad(u, s)
stress = (
h * prestress[s.qp_index]
+ mu * h
+ (mu - lam * wp.log(wp.determinant(f)))
* inverse_t
* wp.transpose(h)
* inverse_t
+ lam * wp.ddot(inverse_t, h) * inverse_t
)
return wp.ddot(stress, fem.grad(v, s))
@fem.integrand
def linear_stress( # type: ignore[no-untyped-def]
s: fem.Sample, u: fem.Field, mu: wp.float64, lam: wp.float64
):
"""Small-strain stress, used as the prestress S0."""
h = fem.grad(u, s)
identity = wp.identity(n=3, dtype=wp.float64)
return mu * (h + wp.transpose(h)) + lam * wp.trace(h) * identity
[docs]
class WarpHyperelasticWall(MONAIPhysioBase):
"""Quasi-static compressible Neo-Hookean wall on P2 tetrahedra.
The first Piola stress is ``F S0 + mu (F - F^-T) + lambda ln(J) F^-T``.
``S0`` is a prestress stored at every quadrature point (zero until
:meth:`prestress`). Nonlinear solves use modified Newton iterations with
a tangent factored by cuDSS and refreshed only when convergence slows,
so most solves reuse one factorization. Everything runs in float64: in
float32 the internal force is too inexact for the Newton tolerance.
Nodal arrays are in the canonical P2 order: vertices, then ``edges``.
"""
#: P2 triangle mass matrix times 180 / area, nodes (v0, v1, v2, e01, e12,
#: e20).
TRIANGLE_MASS: ClassVar[np.ndarray] = (
np.array(
[
[6, -1, -1, 0, -4, 0],
[-1, 6, -1, 0, 0, -4],
[-1, -1, 6, -4, 0, 0],
[0, 0, -4, 32, 16, 16],
[-4, 0, 0, 16, 32, 16],
[0, -4, 0, 16, 16, 32],
]
)
/ 180.0
)
[docs]
def __init__(
self,
points: np.ndarray,
tetrahedra: np.ndarray,
clamped: np.ndarray,
*,
young_modulus: float,
poisson_ratio: float,
tether_faces: Optional[np.ndarray] = None,
tether_stiffness: float = 0.0,
quadrature_order: int = 4,
) -> None:
"""Build the P2 space and the boundary operators.
Args:
points: Vertex positions in metres.
tetrahedra: Positively oriented vertex indices of each tetrahedron.
clamped: True for vertices held fixed; an edge node is fixed when
both of its vertices are.
young_modulus: E in Pa.
poisson_ratio: nu.
tether_faces: Boundary triangles carrying the tether springs.
tether_stiffness: Spring stiffness per area in Pa/m.
quadrature_order: Order of the cell quadrature.
"""
super().__init__(class_name=self.__class__.__name__)
self.points = np.asarray(points, dtype=np.float64)
self.tetrahedra = np.asarray(tetrahedra, dtype=np.int64)
self.edges = ProcessVolumetricMesh.tetrahedron_edges(self.tetrahedra)
self.dof_points = np.concatenate(
[self.points, self.points[self.edges].mean(axis=1)]
)
self.mu = young_modulus / (2 * (1 + poisson_ratio))
self.lam = (
young_modulus
* poisson_ratio
/ ((1 + poisson_ratio) * (1 - 2 * poisson_ratio))
)
self.geometry: Any = fem.Tetmesh(
tet_vertex_indices=wp.array(self.tetrahedra, dtype=wp.int32),
positions=wp.array(self.points, dtype=wp.vec3d),
)
self.space: Any = fem.make_polynomial_space(
self.geometry, degree=2, dtype=wp.vec3d
)
distance, index = cKDTree(self.space.node_positions().numpy()).query(
self.dof_points
)
self.index = np.asarray(index, dtype=np.int64)
if np.max(distance) > 1e-12 or len(np.unique(self.index)) != len(self.index):
raise ValueError("Warp FEM nodes do not match the canonical P2 nodes")
mask = np.asarray(clamped, dtype=bool)
self.clamped = np.r_[mask, mask[self.edges].all(axis=1)]
fixed = np.zeros(len(self.dof_points), dtype=bool)
fixed[self.index[self.clamped]] = True
self.free = np.flatnonzero(np.repeat(~fixed, 3))
domain = fem.Cells(self.geometry)
self.quadrature = fem.RegularQuadrature(domain, order=quadrature_order)
self.test = fem.make_test(space=self.space, domain=domain)
self.trial = fem.make_trial(space=self.space, domain=domain)
self.field: Any = self.space.make_field()
self.s0: Any = wp.zeros(self.quadrature.total_point_count(), dtype=wp.mat33d)
self.tether = self._tether(tether_faces, tether_stiffness)
self.factor: Optional[WarpCuDssFactor] = None
def _tether(
self, faces: Optional[np.ndarray], stiffness: float
) -> sparse.csr_matrix:
"""Spring stiffness ``k int d . v dA`` over the tether faces, Warp order."""
size = 3 * len(self.dof_points)
if faces is None or stiffness == 0:
return sparse.csr_matrix((size, size))
faces = np.asarray(faces, dtype=np.int64)
nodes = self.index[
ProcessVolumetricMesh.triangle_nodes(faces, self.edges, len(self.points))
]
corners = self.points[faces]
area = (
np.linalg.norm(
np.cross(corners[:, 1] - corners[:, 0], corners[:, 2] - corners[:, 0]),
axis=1,
)
/ 2
)
# Entry (3 i + c, 3 j + c) of face f, broadcast to shape (f, i, j, c).
shape = (len(faces), 6, 6, 3)
values = stiffness * area[:, None, None, None] * self.TRIANGLE_MASS[..., None]
rows = 3 * nodes[:, :, None, None] + np.arange(3)
columns = 3 * nodes[:, None, :, None] + np.arange(3)
return sparse.coo_matrix(
(
np.broadcast_to(values, shape).ravel(),
(
np.broadcast_to(rows, shape).ravel(),
np.broadcast_to(columns, shape).ravel(),
),
),
shape=(size, size),
).tocsr()
def _tangent(self, tether: bool) -> sparse.csr_matrix:
"""Tangent at the current displacement on the free degrees of freedom."""
matrix: Any = self.to_scipy(
fem.integrate(
wall_tangent,
quadrature=self.quadrature,
fields={"d": self.field, "u": self.trial, "v": self.test},
values={"prestress": self.s0, "mu": self.mu, "lam": self.lam},
output_dtype=wp.float64,
)
)
if tether:
matrix = matrix + self.tether
return sparse.csr_matrix(matrix[self.free][:, self.free])
def _refactor(self, matrix: sparse.csr_matrix) -> None:
if self.factor is not None:
self.factor.close()
matrix.sort_indices()
self.factor = WarpCuDssFactor(matrix, "spd")
def _warp_order(self, values: np.ndarray) -> np.ndarray:
result = np.zeros((len(self.dof_points), 3))
result[self.index] = values
return result.reshape(-1)
[docs]
def pressure_load(self, faces: np.ndarray, pressure: float) -> np.ndarray:
"""Nodal force in N of a uniform pressure pushing along the face normals.
On a flat triangle the P2 vertex functions integrate to zero and each
edge function to a third of the area.
"""
faces = np.asarray(faces, dtype=np.int64)
corners = self.points[faces]
area = np.cross(corners[:, 1] - corners[:, 0], corners[:, 2] - corners[:, 0])
load = np.zeros((len(self.dof_points), 3))
nodes = ProcessVolumetricMesh.triangle_nodes(
faces, self.edges, len(self.points)
)
for k in range(3, 6):
np.add.at(load, nodes[:, k], pressure * area / 6)
return load
[docs]
def prestress(self, load: np.ndarray) -> None:
"""Store a prestress that balances ``load`` in the given geometry.
``S0`` is the small-strain stress of the clamped wall under ``load``
without tethers, which is in exact discrete equilibrium with ``load``
at zero displacement. The tangent is then refactored with ``S0``.
"""
started = time.perf_counter()
self.s0.zero_()
self.field.dof_values.zero_()
self._refactor(self._tangent(tether=False))
assert self.factor is not None
self.factor.rhs.assign(self._warp_order(load)[self.free])
self.factor.solve()
solution = np.zeros(3 * len(self.dof_points))
solution[self.free] = self.factor.solution.numpy()
self.field.dof_values.assign(solution.reshape(-1, 3))
fem.interpolate(
linear_stress,
dest=self.s0,
at=self.quadrature,
fields={"u": self.field},
values={"mu": self.mu, "lam": self.lam},
)
self.field.dof_values.zero_()
self._refactor(self._tangent(tether=True))
self.log_info(
"Prestress: max displacement without it %.3g mm, %.1f s",
1e3 * np.abs(solution).max(),
time.perf_counter() - started,
)
[docs]
def residual(self, load: np.ndarray) -> np.ndarray:
"""Return ``load - internal force - tether force`` on the free DOFs."""
internal = fem.integrate(
wall_stress,
quadrature=self.quadrature,
fields={"u": self.field, "v": self.test},
values={"prestress": self.s0, "mu": self.mu, "lam": self.lam},
output_dtype=wp.vec3d,
)
displacement = self.field.dof_values.numpy().reshape(-1)
force = (
self._warp_order(load)
- internal.numpy().reshape(-1)
- self.tether @ displacement
)
return np.asarray(force[self.free])
[docs]
def solve(
self, load: np.ndarray, tolerance: float = 1e-6, max_iterations: int = 30
) -> dict[str, Any]:
"""Find the equilibrium displacement under nodal forces ``load`` (N).
Modified Newton starts from the current displacement and stops when
the free-DOF residual is below ``tolerance`` times the load norm, or
warns after ``max_iterations``. The
factored tangent is reused across solves and refactored at the
current displacement whenever an iteration fails to halve the
residual.
"""
if self.factor is None:
self._refactor(self._tangent(tether=True))
scale = max(float(np.linalg.norm(self._warp_order(load)[self.free])), 1e-300)
displacement = self.field.dof_values.numpy().reshape(-1)
previous, updates = np.inf, 0
for iteration in range(max_iterations + 1):
residual = self.residual(load)
relative = float(np.linalg.norm(residual)) / scale
if not np.isfinite(relative):
raise RuntimeError("Wall solve diverged")
if relative <= tolerance or iteration == max_iterations:
break
if relative > 0.5 * previous:
self._refactor(self._tangent(tether=True))
updates += 1
previous = relative
assert self.factor is not None
self.factor.rhs.assign(residual)
self.factor.solve()
displacement[self.free] += self.factor.solution.numpy()
self.field.dof_values.assign(displacement.reshape(-1, 3))
if relative > tolerance:
self.log_warning(
"Wall solve stopped after %d iterations at relative residual %.3g",
iteration,
relative,
)
return {
"iterations": iteration,
"residual": relative,
"tangent_updates": updates,
}
[docs]
def displacement(self) -> np.ndarray:
"""Return the displacement in m at the canonical P2 nodes."""
return np.asarray(self.field.dof_values.numpy()[self.index])
[docs]
def close(self) -> None:
"""Release the cuDSS factorization."""
if self.factor is not None:
self.factor.close()
self.factor = None
[docs]
@staticmethod
def to_scipy(matrix: Any) -> sparse.csr_matrix:
"""Convert a Warp BSR matrix of 3 x 3 blocks to SciPy CSR."""
count = matrix.nnz_sync()
return sparse.bsr_matrix(
(
matrix.values.numpy()[:count],
matrix.columns.numpy()[:count],
matrix.offsets.numpy()[: matrix.nrow + 1],
),
shape=(3 * matrix.nrow, 3 * matrix.ncol),
).tocsr()