Source code for openairbearing.core.porous_body

"""The porous part as a body of its own: Darcy flow on a mesh of hexahedra.

The restrictor models of restrictor.py describe the porous part from the
film: a column under each point of it, or the film surface extended along
its normal through a uniform thickness. That cannot describe a part whose
shape is not such an extension: a monolithic bushing with flow around its
corner, a sleeve with feed grooves cut into it, a seat that is fed from the
side.

Here the porous part is meshed as it is, with hexahedra, and steady Darcy
flow of an isothermal gas is solved in it. In the flow potential phi(p)
(gas.py, kg/(m³·s)) that is a linear problem,

    div( kappa grad(phi) ) = 0,

with kappa the permeability in m², -kappa grad(phi) the mass flux in
kg/(m² s), phi given on the faces where a pressure acts (supply, ambient)
and no flow through the others (sealed, glued to metal, a plane of
symmetry). The mass flow through a face follows from the residual of the
discrete equations, so the flows balance to rounding. The permeability may
differ along the material axes, or the flow may have inertial (Forchheimer)
resistance, which makes it nonlinear in phi; not both.

A film on a face of the body. ``on_body`` puts a film (film.py) on one of
the faces. The body then replaces both restrictor models of restrictor.py
for that film, whatever ``Porous.model`` says. The film pressure is the
pore pressure on that face, one unknown for both, and the flux into the
film is the film's own mass balance: the film equation is the boundary
condition of the body there. ``film.solve_static`` solves the two together,
as it does for the extruded volume of restrictor.py.
The mesh of the film and the face of the body must share their nodes.

Meshes. ``PorousBody`` takes any mesh of hexahedra (scikit-fem ``MeshHex2``,
quadratic so that curved faces are followed). ``revolve`` makes one for a
body of revolution from its cross-section in the (r, z) plane, a mesh of
quadrilaterals. ``section_grid`` makes such a cross-section from lines of
constant r and z, with cells left out for grooves and corners;
``section_blocks`` makes one from four-sided blocks with straight or
circular sides, for conical and spherical seats, chamfers and rounds.

What it is for, next to restrictor.py: parts that are not the film surface
extended through a thickness (grooves cut into the material, a one-piece
bushing, a part fed from the side). Where a part is such an extension the
extruded volume of restrictor.py describes it at a fraction of the cost,
and the two agree (the tests compare them). The body is solved directly in
three dimensions, so its cost per node grows with its size
(``study.BODY_WEIGHT``).

Free flow. ``core.free_flow`` of a film on a body is that of the body as a
whole. Per restrictor it is not offered for a one-piece bushing: gas passes
between its faces inside the material, so the flows of its faces taken one
by one would not add up to that of the whole.
"""

from __future__ import annotations

from collections.abc import Callable
from dataclasses import dataclass, field

import numpy as np
import scipy.sparse as sp
from scipy.sparse.csgraph import connected_components
from scipy.sparse.linalg import splu
from scipy.spatial import cKDTree
from skfem import (
    Basis,
    BilinearForm,
    ElementHex2,
    LinearForm,
    MeshHex,
    MeshHex2,
    MeshQuad,
    MeshQuad2,
)
from skfem.helpers import dot, grad

from .restrictor import factorise

__all__ = [
    "PorousBody",
    "Section",
    "on_body",
    "revolve",
    "section_blocks",
    "section_grid",
]


[docs] @dataclass(frozen=True) class Section: """Cross-section of a body of revolution: quadrilaterals in the (r, z) plane. mesh holds the corners. nodes holds the position of every node of the quadratic mesh made from it (corners, edge midpoints, centres, in the order of ``MeshQuad2.from_mesh(mesh).doflocs``): on a curved side the midpoints lie on the curve, not on the chord between the corners. """ mesh: MeshQuad nodes: np.ndarray
def _key(points, scale): """Points as integers, for finding the same point again.""" return [ tuple(q) for q in np.round(np.asarray(points).T / (1e-9 * scale)).astype(np.int64) ] def _section(points, cells, lattice, lattice_true) -> Section: """A Section from corners and cells. lattice -> lattice_true maps every straight-sided node position to its position on the true outline. """ scale = float(np.abs(points).max()) index = {} for k, key in enumerate(_key(points, scale)): index.setdefault(key, k) first = np.array([index[key] for key in _key(points, scale)]) used = np.unique(first[cells]) renumber = -np.ones(points.shape[1], dtype=np.int64) renumber[used] = np.arange(used.size) mesh = MeshQuad(points[:, used], renumber[first[cells]]) # counter-clockwise cells, whatever they came as a, b, c, d = (mesh.p[:, mesh.t[k]] for k in range(4)) area = 0.5 * ((c[0] - a[0]) * (d[1] - b[1]) - (d[0] - b[0]) * (c[1] - a[1])) if np.any(area == 0.0): raise ValueError("the section has a cell without area") mesh = MeshQuad(mesh.p, np.where(area[None, :] < 0.0, mesh.t[::-1], mesh.t)) # A corner of one cell in the middle of the side of another: two blocks # that share a side without sharing its nodes. The mesh would have a # crack there that nothing flows across. for k in mesh.boundary_facets(): start, end = mesh.p[:, mesh.facets[0, k]], mesh.p[:, mesh.facets[1, k]] along = end - start offset = mesh.p - start[:, None] t = (along @ offset) / (along @ along) away = np.abs(along[0] * offset[1] - along[1] * offset[0]) / np.hypot(*along) if np.any((t > 1e-6) & (t < 1 - 1e-6) & (away < 1e-9 * scale)): raise ValueError("blocks do not meet node to node") true = dict(zip(_key(lattice, scale), np.asarray(lattice_true).T, strict=True)) straight = MeshQuad2.from_mesh(mesh).doflocs try: nodes = np.array([true[key] for key in _key(straight, scale)]).T except KeyError: raise ValueError("blocks do not meet node to node") from None return Section(mesh, nodes)
[docs] def section_grid(r, z, solid: Callable | None = None) -> Section: """Cross-section on lines of constant r and z. r, z: increasing node positions in m. solid(r, z) says for the centre of each cell whether it is material (default: all of them); cells that are not are left out, which is how a groove, a relief or the corner of an L-shaped section is made. ValueError if no cell is left. """ r, z = np.asarray(r, dtype=float), np.asarray(z, dtype=float) # the lattice of corners, edge midpoints and centres r2 = np.sort(np.concatenate([r, 0.5 * (r[1:] + r[:-1])])) z2 = np.sort(np.concatenate([z, 0.5 * (z[1:] + z[:-1])])) R, Z = np.meshgrid(r, z, indexing="ij") points = np.vstack([R.ravel(), Z.ravel()]) cells = [] for i in range(r.size - 1): for j in range(z.size - 1): centre = (0.5 * (r[i] + r[i + 1]), 0.5 * (z[j] + z[j + 1])) if solid is None or solid(*centre): a = i * z.size + j cells.append([a, a + z.size, a + z.size + 1, a + 1]) if not cells: raise ValueError("the section has no material") R2, Z2 = np.meshgrid(r2, z2, indexing="ij") lattice = np.vstack([R2.ravel(), Z2.ravel()]) return _section(points, np.array(cells, dtype=np.int64).T, lattice, lattice)
def _side(start, end, centre, t): """Points along one side of a block at the parameters t in [0, 1]. Straight, or with a centre an arc of a circle, the short way around. """ start, end = np.asarray(start, dtype=float), np.asarray(end, dtype=float) if centre is None: return start[:, None] + (end - start)[:, None] * t[None, :] centre = np.asarray(centre, dtype=float) a, b = start - centre, end - centre ra, rb = np.hypot(*a), np.hypot(*b) if abs(ra - rb) > 1e-9 * max(ra, rb): raise ValueError("an arc needs both ends at the same distance from its centre") a0 = np.arctan2(a[1], a[0]) sweep = ( np.mod(np.arctan2(b[1], b[0]) - a0 + np.pi, 2.0 * np.pi) - np.pi ) # the short way angle = a0 + sweep * t return centre[:, None] + ra * np.vstack([np.cos(angle), np.sin(angle)])
[docs] def section_blocks(blocks) -> Section: """Cross-section made of four-sided blocks with straight or circular sides. Each block is a dict with - ``corners``: four points (r, z) in m, going around the block; - ``n``: (elements along the side from corner 0 to 1, elements along the side from corner 1 to 2), or the node positions along them as arrays from 0 to 1, for example to pack elements toward one end; - ``arcs``: optional, {side: centre (r, z)} for sides that are arcs of a circle, less than half of it; side k runs from corner k to corner k + 1. Other sides are straight, which makes a cone when revolved. Blocks that share a side must have the same nodes along it (ValueError otherwise). The inside of a block is filled by blending its four sides, so a conical or spherical seat, the chamfer of a bushing and a rounded corner are all followed exactly at the nodes. """ points, cells, lattice, lattice_true, offset = [], [], [], [], 0 for block in blocks: c = [np.asarray(q, dtype=float) for q in block["corners"]] if len(c) != 4: raise ValueError("a block has four corners") arcs = block.get("arcs", {}) u, v = ( np.linspace(0.0, 1.0, n + 1) if np.isscalar(n) else np.asarray(n, float) for n in block["n"] ) # with the midpoints: the lattice of the quadratic mesh u2 = np.sort(np.concatenate([u, 0.5 * (u[1:] + u[:-1])])) v2 = np.sort(np.concatenate([v, 0.5 * (v[1:] + v[:-1])])) U, V = np.meshgrid(u2, v2, indexing="ij") def patch(curved, c=c, arcs=arcs, u2=u2, v2=v2, U=U, V=V): """Blend of the four sides (a Coons patch).""" pick = arcs.get if curved else (lambda k: None) south = _side(c[0], c[1], pick(0), u2)[:, :, None] east = _side(c[1], c[2], pick(1), v2)[:, None, :] north = _side(c[3], c[2], pick(2), u2)[:, :, None] west = _side(c[0], c[3], pick(3), v2)[:, None, :] corners = ( (1 - U) * (1 - V) * c[0][:, None, None] + U * (1 - V) * c[1][:, None, None] + U * V * c[2][:, None, None] + (1 - U) * V * c[3][:, None, None] ) return (1 - V) * south + V * north + (1 - U) * west + U * east - corners true = patch(True) if any(k in arcs for k in range(4)): # the straight-sided mesh has its midpoints between the corners # of the true one even = true[:, ::2, ::2] straight = np.empty_like(true) straight[:, ::2, ::2] = even straight[:, 1::2, ::2] = 0.5 * (even[:, 1:, :] + even[:, :-1, :]) straight[:, ::2, 1::2] = 0.5 * (even[:, :, 1:] + even[:, :, :-1]) straight[:, 1::2, 1::2] = 0.25 * ( even[:, 1:, 1:] + even[:, :-1, 1:] + even[:, 1:, :-1] + even[:, :-1, :-1] ) else: straight = true nu, nv = u.size, v.size points.append(true[:, ::2, ::2].reshape(2, -1)) for i in range(nu - 1): for j in range(nv - 1): a = offset + i * nv + j cells.append([a, a + nv, a + nv + 1, a + 1]) offset += nu * nv lattice.append(straight.reshape(2, -1)) lattice_true.append(true.reshape(2, -1)) if not cells: raise ValueError("the section has no material") return _section( np.hstack(points), np.array(cells, dtype=np.int64).T, np.hstack(lattice), np.hstack(lattice_true), ) # fmt: skip
[docs] def revolve(section: Section, n_theta: int = 48) -> MeshHex2: """The body made by turning a cross-section once around the z axis. Each quadrilateral of the section becomes a ring of n_theta hexahedra (at least three). The section must lie at r > 0. The mesh is quadratic: nodes between two angles are put on the circle, and nodes on a curved side of the section on its curve, so cylindrical, conical and spherical faces are followed closely with few elements. """ if n_theta < 3: raise ValueError("at least three elements around") rz, quads = section.mesh.p, section.mesh.t if np.any(section.nodes[0] <= 0.0): raise ValueError("the section must lie at r > 0") n_rz = rz.shape[1] theta = 2.0 * np.pi * np.arange(n_theta) / n_theta points = np.vstack( [ np.outer(np.cos(theta), rz[0]).ravel(), np.outer(np.sin(theta), rz[0]).ravel(), np.tile(rz[1], n_theta), ] ) # Local corner order of a scikit-fem hexahedron, with (u, v) in the # section and w around: (0,0,0) (0,1,0) (1,0,0) (0,0,1) (1,1,0) (0,1,1) # (1,0,1) (1,1,1). In the section the corners are q0 (0,0), q1 (1,0), # q2 (1,1), q3 (0,1). (r, z, theta) is left-handed, so w runs backwards. q0, q1, q2, q3 = quads cells = [] for j in range(n_theta): near, far = ((j + 1) % n_theta) * n_rz, j * n_rz cells.append( np.array( [ q0 + near, q3 + near, q1 + near, q0 + far, q2 + near, q3 + far, q1 + far, q2 + far, ] ) ) # fmt: skip mesh = MeshHex2.from_mesh(MeshHex(points, np.hstack(cells))) # The nodes this gives lie on chords: between two angles, and between # the corners of a curved side of the section. Each is moved to where # it belongs: its place in the section, at its angle. x = mesh.doflocs step = 2.0 * np.pi / n_theta angle = np.arctan2(x[1], x[0]) between = np.abs(np.mod(angle / step, 1.0) - 0.5) < 0.25 r_chord = np.hypot(x[0], x[1]) / np.where(between, np.cos(0.5 * step), 1.0) scale = float(np.abs(rz).max()) straight = MeshQuad2.from_mesh(section.mesh).doflocs true = dict(zip(_key(straight, scale), section.nodes.T, strict=True)) placed = np.array([true[key] for key in _key(np.vstack([r_chord, x[2]]), scale)]).T return MeshHex2( np.vstack([placed[0] * np.cos(angle), placed[0] * np.sin(angle), placed[1]]), mesh.t, )
@BilinearForm def _darcy(u, v, w): return w.kappa * dot(grad(u), grad(v)) @BilinearForm def _darcy_axes(u, v, w): """Darcy flow with a permeability of its own along each of three axes.""" gu, gv = grad(u), grad(v) total = 0.0 for k in range(3): axis = w[f"e{k}"] along_u = sum(axis[i] * gu[i] for i in range(3)) along_v = sum(axis[i] * gv[i] for i in range(3)) total = total + w[f"k{k}"] * along_u * along_v return total @LinearForm def _inertial_residual(v, w): return w.keff * dot(grad(w.T), grad(v)) @BilinearForm def _inertial_tangent(u, v, w): slope = grad(w.T) return w.keff * dot(grad(u), grad(v)) + w.dk * dot(slope, grad(u)) * dot( slope, grad(v) ) def _axes(name, X): """Unit vectors of the material axes at the points X, each of shape (3, ...).""" zero, one = 0.0 * X[0], 1.0 + 0.0 * X[0] if name == "cartesian": return [(one, zero, zero), (zero, one, zero), (zero, zero, one)] if name == "cylindrical": # radial, circumferential, axial about z rho = np.hypot(X[0], X[1]) c, s = X[0] / rho, X[1] / rho return [(c, s, zero), (-s, c, zero), (zero, zero, one)] raise ValueError("axes must be 'cylindrical' or 'cartesian'")
[docs] @dataclass class PorousBody: """A porous part with Darcy flow in it. mesh: hexahedra (``MeshHex2``), positions in m. kappa: permeability in m², a number or a function of position X (shape (3, ...)), so it may be graded or differ from one region to another. faces: name -> function of X that is true on that part of the surface; it is asked at the centre of every boundary facet (on the surface itself, also where it is curved). Surface that no name claims is sealed. A face that covers nothing or overlaps another is a ValueError. ``nodes[name]`` are the nodes of each face and ``K`` is the Darcy operator on nodal values of the flow potential. """ mesh: MeshHex2 kappa: float | Callable faces: dict = field(default_factory=dict) # Anisotropy: the permeability along each material axis is kappa times # one of these three numbers (or functions of X). The axes are # "cylindrical" (radial, circumferential, axial about z) or "cartesian" # (x, y, z): those of the material, not of whichever face is nearest. ratios: tuple = (1.0, 1.0, 1.0) axes: str = "cylindrical" # Inertial (Forchheimer) resistance beta in 1/m, a number or a function # of X: the pressure gradient is -(mu/kappa·v + beta·rho·|v|·v). The flow # is then no longer linear in the potential; it needs the gas viscosity, # and is not combined with anisotropy. inertial_resistance: float | Callable = 0.0 def __post_init__(self): self.basis = Basis(self.mesh, ElementHex2()) X = np.asarray(self.basis.global_coordinates()) kappa = self.kappa(X) if callable(self.kappa) else self.kappa kappa = kappa + 0.0 * X[0] if len(self.ratios) != 3: raise ValueError("ratios: one number for each of the three axes") if all(not callable(r) and r == 1.0 for r in self.ratios): self.K = _darcy.assemble(self.basis, kappa=kappa).tocsr() else: fields = {} for k, (ratio, axis) in enumerate( zip(self.ratios, _axes(self.axes, X), strict=True) ): fields[f"k{k}"] = kappa * (ratio(X) if callable(ratio) else ratio) fields[f"e{k}"] = np.array(axis) self.K = _darcy_axes.assemble(self.basis, **fields).tocsr() beta = self.inertial_resistance self.beta_q = (beta(X) if callable(beta) else beta) + 0.0 * X[0] self.kappa_q = kappa self.inertial = bool(np.any(self.beta_q)) if ( self.inertial and self.K is not None and not all(not callable(r) and r == 1.0 for r in self.ratios) ): raise NotImplementedError( "Inertial flow in an anisotropic body is not implemented." ) boundary = self.mesh.boundary_facets() # the node at the centre of each facet, which lies on a curved face centre = self.basis.doflocs[:, self.basis.facet_dofs[0, boundary]] self.facets, self.nodes = {}, {} claimed = np.zeros(boundary.size, dtype=bool) for name, on_face in self.faces.items(): mine = np.asarray(on_face(centre), dtype=bool) if not mine.any(): raise ValueError(f"face {name!r} covers no part of the surface") if np.any(mine & claimed): raise ValueError(f"face {name!r} overlaps another face") claimed |= mine self.facets[name] = boundary[mine] self.nodes[name] = self.basis.get_dofs(facets=boundary[mine]).all()
[docs] def inertial_flow(self, potential, mu, unit=1.0, tangent=False): """Residual of Darcy-Forchheimer flow, and its tangent matrix. potential: nodal values in units of ``unit`` (so the flow potential in kg/(m³·s) is unit·potential); mu: gas viscosity, Pa·s, taken as uniform in the body. The mass flux m obeys beta·|m|·m + (mu/kappa)·m = -mu·grad(phi), which is an effective permeability kappa_eff(|grad(phi)|) below kappa. Returns the residual, in the units of K @ potential, and with tangent=True also its derivative with respect to the nodal values; tangent="secant" gives the matrix with kappa_eff held fixed in its place. """ T = self.basis.interpolate(np.asarray(potential, dtype=float)) steep = np.sqrt(sum(T.grad[k] ** 2 for k in range(3))) # In a solid part (kappa = 0) b is infinite and keff comes out as 0: # nothing flows there. with np.errstate(divide="ignore"): b = mu / self.kappa_q root = np.sqrt(b**2 + 4.0 * self.beta_q * mu * unit * steep) keff = 2.0 * mu / (b + root) residual = _inertial_residual.assemble(self.basis, T=T, keff=keff) if not tangent: return residual # d(keff)/d|grad(phi)|, times unit/|grad(potential)| for the tangent with np.errstate(divide="ignore", invalid="ignore"): dk = np.where( steep > 0.0, -2.0 * mu / (b + root) ** 2 * (2.0 * self.beta_q * mu / root) * unit / np.where(steep > 0.0, steep, 1.0), 0.0, ) # fmt: skip if tangent == "secant": # the effective permeability held fixed: not the true derivative, # but a step with it never overshoots (see _BodyRestrictor) dk = 0.0 * dk return residual, _inertial_tangent.assemble(self.basis, T=T, keff=keff, dk=dk)
[docs] def solve(self, potential: dict, mu: float | None = None) -> np.ndarray: """Flow potential at every node, given its value on some faces. potential: face name -> phi in kg/(m³·s) (a number, or one value per node of that face in the order of ``nodes[name]``). Faces left out are sealed. At least one face must be given. mu: the gas viscosity, Pa·s, needed with an inertial resistance; the flow is then found by Newton iteration from the Darcy solution (RuntimeError if that does not converge). """ if not potential: raise ValueError("the potential must be given on at least one face") if self.inertial and mu is None: raise ValueError("inertial flow needs the gas viscosity mu") phi = np.zeros(self.basis.N) fixed = [] for name, value in potential.items(): phi[self.nodes[name]] = value fixed.append(self.nodes[name]) fixed = np.unique(np.concatenate(fixed)) free = np.setdiff1d(np.arange(self.basis.N), fixed) rhs = -(self.K @ phi)[free] phi[free] = splu(self.K[free][:, free].tocsc()).solve(rhs) if not self.inertial: return phi for _ in range(50): # Newton from the Darcy solution residual, tangent = self.inertial_flow(phi, mu, tangent=True) step = splu(tangent.tocsr()[free][:, free].tocsc()).solve(-residual[free]) phi[free] += step if np.linalg.norm(step) <= 1e-12 * np.linalg.norm(phi): return phi raise RuntimeError("inertial flow in the body did not converge")
[docs] def flow(self, phi: np.ndarray, name: str, mu: float | None = None) -> float: """Mass flow leaving the body through a face, kg/s (negative: entering). phi: the flow potential at the nodes in kg/(m³·s) (gas.py), so that -kappa·grad(phi) is the mass flux; mu as in ``solve``. Taken from the residual at the nodes of the face, which makes the flows of all faces sum to zero to rounding. A node shared by two faces is counted with the first of them in ``faces``. """ if self.inertial and mu is None: raise ValueError("inertial flow needs the gas viscosity mu") residual = self.inertial_flow(phi, mu) if self.inertial else self.K @ phi taken = np.zeros(self.basis.N, dtype=bool) for other in self.faces: nodes = self.nodes[other] own = nodes[~taken[nodes]] taken[own] = True if other == name: return -float(residual[own].sum()) raise KeyError(name)
@BilinearForm def _mass(u, v, w): return w.c * u * v class _BodyRestrictor: """A porous body as the restrictor of a film: what the film solvers ask for. The unknowns are those of the body, numbered as its nodes: Theta, the scaled flow potential of film.py, everywhere except on the film's face, where the unknown is the film pressure P = p/pa. Under a seal, and everywhere with a surface layer, the node of the body keeps Theta of the pores and the film has an unknown of its own after those of the body. Same interface as ``restrictor.RestrictorVolume``, with ``start`` in place of ``column_start``. """ def __init__( self, film, body, face, position, supply, ambient, layer=None, seal=None ): self.film, self.body = film, body basis = body.basis # the body node of every film node where = np.asarray(position(film.basis.doflocs), dtype=float) on_face = body.nodes[face] distance, nearest = cKDTree(basis.doflocs[:, on_face].T).query(where.T) size = float(np.ptp(basis.doflocs, axis=1).max()) if distance.max() > 1e-7 * size or np.unique(nearest).size != nearest.size: raise ValueError( "The film mesh and the face of the body do not share their nodes " f"(largest distance {distance.max():.3g} m)." ) if nearest.size != on_face.size: raise ValueError( f"The film covers {nearest.size} of the {on_face.size} nodes of " f"face {face!r}: the face must be the film surface, no more." ) self.scale = 12.0 / film.h_ref**3 under_film = on_face[nearest] N = basis.N # where the face is sealed nothing passes between pores and film sealed_node = np.zeros(nearest.size, dtype=bool) if seal is not None: sealed_node = np.asarray(seal(where), dtype=bool) self._K_body = self.scale * body.K self._K_layer = None if layer is None: # Film pressure and pore pressure on the face are one unknown, # except under a seal: there the film gets an unknown of its own # after those of the body, and nothing ties the two. n_own = int(sealed_node.sum()) self.film_index = under_film.copy() self.film_index[sealed_node] = N + np.arange(n_own) self.n_total = N + n_own self.K = sp.block_diag( [self._K_body, sp.csr_matrix((n_own, n_own))], format="csr" ) else: # A surface-restrictive layer between them: the film gets # unknowns of its own after those of the body, and gas passes # from the pores at the face to the film through the resistance # of the layer, thickness over permeability, per unit of area. thickness, kappa = layer xq = np.asarray(film.basis.global_coordinates()) g1, g2 = film.metric(xq) if film.metric is not None else (1.0, 1.0) X = np.asarray(position(xq), dtype=float) thickness, kappa = ( (value(X) if callable(value) else value) + 0.0 * xq[0] for value in (thickness, kappa) ) face_area = g1 * g2 + 0.0 * xq[0] M = _mass.assemble(film.basis, c=kappa / thickness * face_area) M = (self.scale * M).tocoo() # No way through the layer at a sealed node: the seal is taken # node by node, as without a layer, so the two agree. keep = ~(sealed_node[M.row] | sealed_node[M.col]) M = sp.coo_matrix((M.data[keep], (M.row[keep], M.col[keep])), shape=M.shape) n_film = nearest.size self.film_index = N + np.arange(n_film) self.n_total = N + n_film pore, gas_film = under_film, self.film_index rows = np.concatenate( [pore[M.row], pore[M.row], gas_film[M.row], gas_film[M.row]] ) cols = np.concatenate( [pore[M.col], gas_film[M.col], pore[M.col], gas_film[M.col]] ) data = np.concatenate([M.data, -M.data, -M.data, M.data]) shape = (self.n_total, self.n_total) padded = sp.block_diag( [self._K_body, sp.csr_matrix((n_film, n_film))], format="csr" ) self._K_layer = sp.csr_matrix((data, (rows, cols)), shape=shape) self.K = (padded + self._K_layer).tocsr() self.coupled = np.ones(nearest.size, dtype=bool) # Nodes under supply pressure and at a given ambient pressure. A node # that also carries the film keeps the film equation. is_film = np.zeros(self.n_total, dtype=bool) is_film[self.film_index] = True fed = np.unique(np.concatenate([body.nodes[name] for name in supply])) self.supply = fed[~is_film[fed]] # a supply face that meets the film face along an edge (free_flow) self._fed_at_film = bool(is_film[fed].any()) if self.supply.size == 0: raise ValueError("The body has no face under supply pressure.") rim, rim_p = [], [] for name, pressure in ambient.items(): nodes = body.nodes[name] nodes = nodes[~is_film[nodes]] rim.append(nodes) rim_p.append(np.full(nodes.size, float(pressure))) self.rim = np.concatenate(rim) if rim else np.array([], dtype=np.int64) self.rim_pressure = np.concatenate(rim_p) if rim_p else np.array([]) if np.intersect1d(self.rim, self.supply).size: raise ValueError( "A face under supply pressure touches a face at ambient pressure. " "Where the two meet along one edge the flow through that edge has " "no limit as the mesh is refined: leave a sealed margin between them." ) # Where the body is impermeable (kappa = 0 in a solid part) nothing # flows and the pore pressure is not defined: those nodes are left # out of every solve, as in free_flow. A film node keeps its film # equation; a pore node under a layer is tied to the film by it. solid = np.flatnonzero(self.K.diagonal() == 0.0) kept = np.concatenate([self.film_index, self.rim, self.supply]) sealed = np.setdiff1d(solid, kept) # Open material that the solid parts cut off from every face with a # pressure (a pocket inside a solid part) has no pressure of its own # either: it is left out too. Found as the connected parts of the # flow operator that reach no film, supply or rim node. live = np.ones(self.n_total, dtype=bool) live[sealed] = False graph = abs(self.K[live][:, live]) > 0.0 _, part = connected_components(graph, directed=False) anchored = np.zeros(part.max() + 1 if part.size else 0, dtype=bool) where = np.full(self.n_total, -1) where[live] = np.arange(int(live.sum())) anchored[part[where[kept[where[kept] >= 0]]]] = True cut_off = np.flatnonzero(live)[~anchored[part]] self.sealed = np.union1d(sealed, cut_off) self.layered = layer is not None self.nonlinear = body.inertial # the flow in the body, in Theta self.X = None def theta(self, X, sc): """Theta at every unknown (from P where the unknown is the film's).""" T = X.copy() T[self.film_index] = sc.theta(self.film.pa * X[self.film_index]) return T def _inertial(self, X, sc, tangent): """Flow in a body with inertial resistance, in the scaled unknowns.""" body, N = self.body, self.body.basis.N T = self.theta(X, sc) mu = float(self.film.gas.mu(self.film.ps)) unit = sc.dphi_a * self.film.pa # flow potential per unit of Theta out = body.inertial_flow(T[:N], mu, unit, tangent) residual, matrix = out if tangent else (out, None) r = np.zeros(self.n_total) r[:N] = self.scale * residual if self._K_layer is not None: r += self._K_layer @ T if not tangent: return r extra = self.n_total - N J = sp.block_diag( [self.scale * matrix, sp.csr_matrix((extra, extra))], format="csr" ) if self._K_layer is not None: J = J + self._K_layer return r, J def flow(self, X, sc): """Residual of the flow in the body: what leaves each node.""" if self.body.inertial: return self._inertial(X, sc, tangent=False) return self.K @ self.theta(X, sc) def flow_jacobian(self, X, sc, secant=False): """Derivative of ``flow`` with respect to the unknowns. secant: for a nonlinear flow law, the matrix with the effective permeability held fixed instead of the true derivative. Where the flow nearly stands still under the film, inertial flow goes with the square root of the pressure gradient, and a Newton step from far away swings from one side to the other; a step with the secant matrix halves the error every time without overshooting. The film solver starts with it and changes to the true derivative close to the solution. """ if self.body.inertial: kind = "secant" if secant else True return self._inertial(X, sc, tangent=kind)[1] @ self.dtheta(X, sc) return self.K @ self.dtheta(X, sc) def dtheta(self, X, sc): """d(Theta)/d(unknown) as a diagonal matrix: 1 except where it is P.""" d = np.ones_like(X) p = self.film.pa * X[self.film_index] d[self.film_index] = self.film.gas.dphi_dp(p) / sc.dphi_a return sp.diags(d) def embed(self, A2): """A film matrix placed on the film's unknowns.""" A2 = A2.tocoo() index, N = self.film_index, self.n_total return sp.csr_matrix((A2.data, (index[A2.row], index[A2.col])), shape=(N, N)) def start(self, film, sc): """Unknowns to start from. A film midway between ambient and supply pressure, at the given pressure on its boundaries, and the Darcy flow in the body that goes with it. """ pa = film.pa P = np.full(film.basis.N, 0.5 * (film.ps + pa) / pa) for dofs, p in film.boundaries.values(): P[dofs] = p / pa T = np.zeros(self.n_total) T[self.film_index] = sc.theta(pa * P) T[self.rim] = sc.theta(self.rim_pressure) T[self.supply] = sc.theta_s T[self.sealed] = sc.theta(pa) # no flow there: any value will do fixed = np.concatenate([self.film_index, self.rim, self.supply, self.sealed]) free = np.setdiff1d(np.arange(self.n_total), np.unique(fixed)) T[free] = splu(self.K[free][:, free].tocsc()).solve(-(self.K @ T)[free]) T[self.film_index] = P return T def free_flow(self) -> float: """Mass flow through the bare body, with no film on its face, kg/s. The supply faces are at the supply pressure of the film, the whole film face at its ambient pressure, and the faces open to a given pressure at theirs. A surface layer on the film face and a seal on it count as they do under the film. Returns the flow that enters through the supply faces, which a flow meter in the supply line would read; with faces open to a given pressure, part of it leaves through them and not through the film face. Darcy flow is one linear solve. With an inertial resistance it is found by Newton iteration from the Darcy solution, as in ``PorousBody.solve`` (RuntimeError if that does not converge). Where a part of the body is impermeable (kappa = 0) nothing flows and the pore pressure is not defined: its nodes are left out. Raises ValueError where a supply face meets the film face along an edge and no surface layer lies between them. Under a film that is well posed, because the film limits the flow; in the bare body supply and ambient pressure then meet on that edge and the flow through it has no limit as the mesh is refined. """ if self._fed_at_film and not self.layered: raise ValueError( "The free flow of this body is not defined: a face under supply " "pressure meets the film face along an edge, where supply and " "ambient pressure would meet with nothing between them. Leave a " "sealed margin between the two, or give the film face a surface " "layer." ) film, body, gas = self.film, self.body, self.film.gas N = body.basis.N unit = float(gas.dphi_dp(film.pa)) * film.pa # flow potential per Theta T = np.zeros(self.n_total) T[self.rim] = gas.phi(self.rim_pressure) / unit T[self.film_index] = float(gas.phi(film.pa)) / unit T[self.supply] = float(gas.phi(film.ps)) / unit fixed = np.concatenate([self.film_index, self.rim, self.supply]) free = np.setdiff1d( np.arange(self.n_total), np.concatenate([fixed, self.sealed]) ) # (symmetric with a strong diagonal: restrictor.factorise is several # times faster here than partial pivoting) T[free] = factorise(self.K[free][:, free]).solve(-(self.K @ T)[free]) residual = self.K @ T if body.inertial: mu = float(gas.mu(film.ps)) extra = self.n_total - N def flow(tangent): out = body.inertial_flow(T[:N], mu, unit, tangent) r = np.zeros(self.n_total) r[:N] = self.scale * (out[0] if tangent else out) if self._K_layer is not None: r += self._K_layer @ T if not tangent: return r J = sp.block_diag( [self.scale * out[1], sp.csr_matrix((extra, extra))], format="csr" ) return r, J if self._K_layer is None else J + self._K_layer for _ in range(50): residual, J = flow(True) step = factorise(J.tocsr()[free][:, free]).solve(-residual[free]) T[free] += step # the same stop as PorousBody.solve: the step is at rounding if np.linalg.norm(step) <= 1e-12 * np.linalg.norm(T): break else: raise RuntimeError("inertial flow in the body did not converge") residual = flow(False) # the residual at a node held at a pressure is the flow entering # there, in units of unit/scale (film._volume_state) return float(residual[self.supply].sum()) * unit / self.scale
[docs] def on_body( film, body: PorousBody, face: str, position: Callable, supply, ambient=None, layer=None, seal=None, ): # fmt: skip """The film with the porous body as its restrictor. face: the face of the body that the film lies on; it must be the film surface, no more and no less, with the same nodes (ValueError otherwise). position(x) gives the place in space, X of shape (3, ...) in m, of a point x of the film's own coordinates, which is how the two are matched. supply: name or names of the faces under the film's supply pressure. ambient: {face name: absolute pressure in Pa} for faces open to a given pressure. All other faces are sealed. A supply face must not touch an ambient one. layer: a surface-restrictive layer on the film face, as (thickness in m, permeability in m²), each a number or a function of X. It lies between the pores at the face and the film: a resistance in series, thin enough that nothing moves along it. Without a layer the film pressure is the pore pressure at the face. seal: a function of X that is true where the film face is sealed (lacquered, smeared shut): nothing passes between the pores and the film there, while the body behind it still carries gas. It is taken at the nodes of the film, so its edge is as sharp as the mesh; put a line of nodes on it (``axial_marks`` of a journal) to make it exact. Returns a copy of the film with the body as its restrictor. The body replaces ``film.porous`` there; ``film.porous`` still gives the slip at the face (the Beavers-Joseph model with its own kappa) and an equivalent clearance, and nothing else of it is used. """ from dataclasses import replace names = [supply] if isinstance(supply, str) else list(supply) restrictor = _BodyRestrictor( film, body, face, position, names, ambient or {}, layer, seal ) return replace(film, body=restrictor)