Source code for monai_physio.warp_fluid_structure_ns

"""Two-way coupling of Navier-Stokes (NS) flow and a hyperelastic wall.

:class:`WarpFluidStructureNS` couples :class:`WarpFlowNS` to a
:class:`WarpHyperelasticWall` across a conforming interface whose P2 nodes
coincide. Each time step moves the fluid mesh once, by a harmonic (Laplace)
extension of the predicted wall displacement, and then iterates
Dirichlet-Neumann: the fluid takes the wall velocity, the wall takes the fluid
force, and an interface quasi-Newton method with an inverse Jacobian from a
least-squares model (IQN-ILS) updates the interface displacement.
"""

from __future__ import annotations

from typing import Any, Optional

import numpy as np
import torch
import warp as wp
from scipy import sparse
from scipy.spatial import cKDTree

from .monai_physio_base import MONAIPhysioBase
from .warp_cudss_factor import WarpCuDssFactor
from .warp_flow_ns import WarpFlowNS
from .warp_hyperelastic_wall import WarpHyperelasticWall


[docs] class WarpFluidStructureNS(MONAIPhysioBase): """Partitioned two-way coupling of :class:`WarpFlowNS` and a wall. The wall is prestressed so that the given geometry is its equilibrium at ``reference_pressure`` (uniform on the interface). Each :meth:`step`: 1. predicts the interface displacement by linear extrapolation, extends it harmonically into the fluid and moves the fluid mesh (once per step; interface caps stay fixed); 2. repeats until the interface displacement converges: fluid step with the wall velocity of the current guess, wall solve under the fluid force, quasi-Newton update of the guess. The update is IQN-ILS (Degroote, Bathe and Vierendeels, Computers and Structures 87:793-801, 2009). With guess ``x``, wall response ``x~`` and residual ``r = x~ - x``, every iteration stores the differences of ``r`` and of ``x~`` from the previous iteration as columns of ``V`` and ``W``. With ``c`` minimizing ``|V c + r|``, the guess moves by ``(W - V) c``, the quasi-Newton step for the part of ``r`` that the columns explain, plus ``relaxation`` times the rest, ``r + V c`` (all of ``r`` while there are no columns). With ``relaxation = 1`` after the first iteration this is IQN-ILS; a light wall needs less, because an unrelaxed step along a direction not yet sampled can invert it. This relaxed form is Anderson mixing (Walker and Ni, SIAM J. Numer. Anal. 49:1715-1735, 2011). Columns of the last ``reuse`` steps are kept, newest first; a column whose part orthogonal to the newer ones is below ``filter_tolerance`` of its norm is dropped (the QR2 filter of Haelterman et al., Computers and Structures 171:9-17, 2016). A step converges when the RMS interface residual is at most ``tolerance`` times the RMS interface motion of the step (guess minus the start-of-step displacement) plus ``absolute_tolerance``. The reported coupling residual is the relative part only, so a converged step can report more than ``tolerance`` when its motion is small. A step still unconverged after ``max_iterations`` is solved once more at its lowest-residual iterate, which it keeps (so the fluid and wall states belong to the kept interface), and all columns are dropped, so the next step starts without reused columns. Such a step usually stalls at the residual noise of the fluid and wall solves, and reused columns may have misled it; columns from either would mislead the next steps. It is reported, not rejected; its re-solve may also meet the convergence criterion. """
[docs] def __init__( self, fluid: WarpFlowNS, wall: WarpHyperelasticWall, boundary_regions: np.ndarray, *, reference_pressure: float, relaxation: float = 0.1, reuse: int = 2, filter_tolerance: float = 1e-2, tolerance: float = 1e-3, absolute_tolerance: float = 1e-9, max_iterations: int = 20, ) -> None: """Match the interface, prestress the wall and factor the mesh extension. Args: fluid: Flow solver whose wall (region 0) nodes are wall nodes. wall: Wall solver sharing the interface nodes. boundary_regions: Region of each fluid boundary face (0 = wall). reference_pressure: Uniform interface pressure (Pa) at which the given geometry is in equilibrium. relaxation: Relaxation of the residual part that the quasi-Newton columns do not explain (all of it without columns). reuse: Number of previous steps whose quasi-Newton columns are kept. filter_tolerance: Relative QR filter threshold of the columns. tolerance: Stop when the RMS interface residual is at most this fraction of the RMS interface motion over the step... absolute_tolerance: ...plus this many metres. max_iterations: Coupling iteration limit per step, after which the best iterate is solved once more and kept. """ super().__init__(class_name=self.__class__.__name__) self.fluid, self.wall = fluid, wall self.relaxation, self.tolerance = float(relaxation), float(tolerance) self.reuse, self.filter_tolerance = int(reuse), float(filter_tolerance) self.absolute_tolerance = float(absolute_tolerance) self.max_iterations = int(max_iterations) # (residual difference, response difference, step) columns, newest # first, kept on the GPU, where their QR factorization is cheap. self.columns: list[tuple[torch.Tensor, torch.Tensor, int]] = [] self.step_count = 0 self.device = wp.device_to_torch(wp.get_device()) distance, nodes = cKDTree(wall.dof_points).query( fluid.dof_points[fluid.wall_dofs] ) if np.max(distance) > 1e-9: raise ValueError("Fluid wall nodes are not wall nodes") nodes = np.asarray(nodes, dtype=np.int64) self.interface = nodes vertex_count = len(fluid.points) self.wall_vertices = fluid.wall_dofs < vertex_count to_wall = np.full(vertex_count, -1) to_wall[fluid.wall_dofs[self.wall_vertices]] = nodes[self.wall_vertices] wall_faces = to_wall[fluid.face_dofs[np.asarray(boundary_regions) == 0, :3]] wall.prestress(wall.pressure_load(wall_faces, reference_pressure)) # Harmonic mesh extension: wall vertices follow the wall, caps stay put. boundary = np.zeros(vertex_count, dtype=bool) boundary[fluid.face_dofs[:, :3].ravel()] = True self.boundary = np.flatnonzero(boundary) self.inner = np.flatnonzero(~boundary) matrix: Any = self.laplacian(fluid.points, fluid.tetrahedra) self.coupling = matrix[self.inner][:, self.boundary].tocsr() inner = matrix[self.inner][:, self.inner].tocsr() inner.sort_indices() self.extension = WarpCuDssFactor(inner, "spd") self.boundary_values = np.zeros((vertex_count, 3)) self.mesh_displacement = np.zeros((vertex_count, 3)) self.previous = np.zeros((len(self.interface), 3)) self.volume = self.fluid_volume()
[docs] def extend(self, interface_displacement: np.ndarray) -> np.ndarray: """Extend the interface displacement harmonically to all fluid vertices.""" values = self.boundary_values values[self.fluid.wall_dofs[self.wall_vertices]] = interface_displacement[ self.wall_vertices ] result = values.copy() known = values[self.boundary] for axis in range(3): self.extension.rhs.assign(-(self.coupling @ known[:, axis])) self.extension.solve() result[self.inner, axis] = self.extension.solution.numpy() return result
[docs] def fluid_volume(self) -> float: """Volume in m^3 of the current (moved) fluid mesh.""" corners = (self.fluid.points + self.mesh_displacement)[self.fluid.tetrahedra] edges = corners[:, 1:] - corners[:, :1] return float(np.linalg.det(edges).sum() / 6)
[docs] def step(self, inlet_flow: float) -> dict[str, Any]: """Advance the coupled system one fluid time step. Returns: The last fluid step result plus coupling iterations (fluid and wall solves; ``max_iterations + 1`` for a capped step, whose re-solve can still meet the criterion), whether the interface converged, the relative and the RMS (m) residual of the kept iterate, the summed GMRES and wall Newton iterations, the wall tangent refactorizations, the interface displacement extremes in m, and the fluid volume in m^3 and its rate of change in m^3/s. """ fluid, wall, dt = self.fluid, self.wall, self.fluid.dt current = wall.displacement()[self.interface] guess = 2 * current - self.previous moved = self.extend(guess) fluid.move(moved, (moved - self.mesh_displacement) / dt) self.mesh_displacement = moved volume = self.fluid_volume() start_velocity = wp.clone(fluid.u_field.dof_values) start_pressure = {r: w.pressure for r, w in fluid.outlets.items()} wall_velocity = np.zeros_like(fluid.dof_points) load = np.zeros_like(wall.dof_points) self.step_count += 1 self.columns = [c for c in self.columns if c[2] >= self.step_count - self.reuse] last: Optional[tuple[torch.Tensor, torch.Tensor]] = None gmres = newton = updates = 0 best = (np.inf, guess) for iteration in range(1, self.max_iterations + 2): if iteration > self.max_iterations: self.columns, guess = [], best[1] if iteration > 1: fluid.u_field.dof_values.assign(start_velocity) for region, windkessel in fluid.outlets.items(): windkessel.pressure = start_pressure[region] wall_velocity[fluid.wall_dofs] = (guess - current) / dt result = fluid.step(inlet_flow, wall_velocity) load[self.interface] = fluid.wall_force()[fluid.wall_dofs] solid = wall.solve(load) gmres += result["iterations"] newton += solid["iterations"] updates += solid["tangent_updates"] response = wall.displacement()[self.interface] residual = response - guess size = np.sqrt(np.mean(residual**2)) change = np.sqrt(np.mean((guess - current) ** 2)) relative = float(size / max(change, 1e-300)) converged = size <= self.tolerance * change + self.absolute_tolerance if ( converged or iteration > self.max_iterations or not np.all(np.isfinite(residual)) ): break if size < best[0]: best = (size, guess) pair = ( torch.from_numpy(residual.ravel()).to(self.device), torch.from_numpy(response.ravel()).to(self.device), ) if last is not None: self.columns.insert( 0, (pair[0] - last[0], pair[1] - last[1], self.step_count) ) last = pair update = self.quasi_newton_update( pair[0], self.columns, self.relaxation, self.filter_tolerance ) guess = guess + update.cpu().numpy().reshape(guess.shape) if not np.all(np.isfinite(residual)): raise RuntimeError("Coupled step diverged") self.previous = current displacement = wall.displacement()[self.interface] magnitude = np.linalg.norm(displacement, axis=1) volume_rate = (volume - self.volume) / dt self.volume = volume return { **result, "coupling_iterations": iteration, "converged": bool(converged), "coupling_residual": relative, "coupling_residual_m": float(size), "gmres_iterations": gmres, "wall_iterations": newton, "wall_tangent_updates": updates, "max_displacement_m": float(magnitude.max()), "mean_displacement_m": float(magnitude.mean()), "volume_m3": volume, "volume_rate_m3_s": volume_rate, }
[docs] def close(self) -> None: """Release the factorizations of the fluid, the wall and the extension.""" self.fluid.close() self.wall.close() self.extension.close()
[docs] @staticmethod def laplacian(points: np.ndarray, tetrahedra: np.ndarray) -> sparse.csr_matrix: """Linear (P1) finite-element Laplacian of a tetrahedral mesh.""" corners = points[tetrahedra] edges = corners[:, 1:] - corners[:, :1] inverse = np.linalg.inv(edges) gradients = np.concatenate( [-inverse.sum(axis=2, keepdims=True), inverse], axis=2 ) volume = np.abs(np.linalg.det(edges)) / 6 local = np.einsum("tki,tkj->tij", gradients, gradients) * volume[:, None, None] rows = np.repeat(tetrahedra, 4, axis=1) columns = np.tile(tetrahedra, (1, 4)) size = len(points) return sparse.coo_matrix( (local.ravel(), (rows.ravel(), columns.ravel())), shape=(size, size) ).tocsr()
[docs] @staticmethod def quasi_newton_update( residual: torch.Tensor, columns: list[tuple[torch.Tensor, torch.Tensor, int]], relaxation: float, filter_tolerance: float, ) -> torch.Tensor: """Change of the interface guess for ``residual`` (IQN-ILS, relaxed). ``columns`` holds (residual difference, response difference, step) pairs, newest first. Columns beyond the length of ``residual``, and columns whose part orthogonal to the newer ones is below ``filter_tolerance`` of their norm, are removed from it in place. See :class:`WarpFluidStructureNS` for the method. """ update = relaxation * residual # At most len(residual) columns can be independent; keep the newest. del columns[len(residual) :] while columns: v = torch.stack([column[0] for column in columns], dim=1) q, r = torch.linalg.qr(v) norms = torch.linalg.vector_norm(v, dim=0) small = r.diagonal().abs() <= filter_tolerance * norms if small.any(): del columns[int(torch.nonzero(small)[0])] continue c = torch.linalg.solve_triangular(r, -(q.T @ residual)[:, None], upper=True) w = torch.stack([column[1] for column in columns], dim=1) update += ((w - (1 - relaxation) * v) @ c)[:, 0] break return update