"""Steady gas film with porous feeding: one solver for every bearing geometry.
Mass balance per unit film area, for a film of thickness h between a porous
stator and a moving surface:
div( -(1+Psi) h³/12 grad(phi) + rho h U/2 ) = kappa/hp (phi_s - phi)
phi(p) is the gas flow potential (gas.py), Psi the slip factor of the porous
face and U the sum of the two surface velocities. The right-hand side is the
feed of the column restrictor model: one-dimensional Darcy flow through the
restrictor thickness hp from the supply pressure, or that in series with
a Knudsen skin at the face (restrictor.py), whose flow follows the pressure
difference across it rather than phi. The volume model
(restrictor.py, porous_body.py) replaces it by the flow in the whole
restrictor body, solved together with the film; a Knudsen skin is then a
conductance between the face of the body and the film. Pressures are
prescribed on the named boundaries (ambient, a chamber, a vent); any other
edge is a symmetry line with no flow across it.
The unknown is P = p/pa and the gap is scaled by h_ref. The weak residual is
R(v) = ∫ C3 a(P) grad P·grad v - a_c r(P) H U·grad v
- a_s (Theta_s - Theta(P)) v dA,
with C3 = (1+Psi) H³, a = phi'/phi'_a, r = rho/rho_a, Theta = phi/(phi'_a pa),
a_c = 6 rho_a/(h_ref² phi'_a pa) and a_s = 12 kappa/(hp h_ref³). Without
sliding and with Darcy feed the problem is linear in Theta; that solution is
the Newton start. One unit of the residual is a mass flow of
h_ref³ phi'_a pa/12, so the flows are sums of nodal residuals.
Generalised forces follow from virtual work, F_i = ∫ (p - pa) dh/dq_i dA, so
a geometry only has to define its gap h(x, q). F_i is the force on the body
whose motion q describes, in the direction of q_i.
"""
from __future__ import annotations
import copy
from collections.abc import Callable
from dataclasses import dataclass, field, replace
import numpy as np
from skfem import BilinearForm, Functional, LinearForm, condense, solve
from skfem.helpers import grad
from .gas import AIR, Gas
from .restrictor import WALLS, Porous, _field, factorise, restrictor_volume
__all__ = [
"WALLS",
"ContactError",
"Film",
"FilmSolveError",
"Porous",
"StaticState",
"free_flow",
"solve_static",
"stiffness",
]
[docs]
class FilmSolveError(RuntimeError):
"""The film solve did not converge."""
[docs]
@dataclass(frozen=True, eq=False)
class Film:
"""One connected film domain, ready to solve at any position q.
basis: scikit-fem basis on the film surface (unrolled for a cylinder).
boundaries: name -> (dof indices, absolute pressure in Pa).
gap: h(x, q) in m; x has shape (2, ...), q the position of the moving body.
dof_names: one name per entry of q.
porous: the restrictor (restrictor.py); its ``model`` picks the column or
the volume model.
velocity: U(x) -> (Ux, Uy), sum of the surface velocities in m/s, or None.
metric: g(x) -> (g1, g2), the lengths per unit of each film coordinate, for
a surface described in orthogonal curvilinear coordinates (for example
(s, theta) on an annulus with g = (1, r)). None for plain lengths.
Velocities and gradients are physical; the area element is g1·g2.
"""
basis: object
boundaries: dict
gap: Callable
dof_names: tuple
porous: Porous
ps: float # absolute supply pressure, Pa
pa: float = 101325.0 # ambient pressure, Pa: load and free-gas flow reference
gas: Gas = AIR
velocity: Callable | None = None
metric: Callable | None = None
h_ref: float = 10e-6 # gap scale for conditioning, m
h_floor: float = 0.0 # gap at or below this is contact, m
# name -> function of x that is true inside a part of the film whose
# supply flow should be reported separately (for example each face)
regions: dict | None = None
# The porous part as a body of its own, with this film on one of its
# faces (porous_body.on_body). It then replaces ``porous`` as the
# restrictor: ``porous`` only gives the slip at the face.
body: object = field(default=None, repr=False)
# name and unit of the two film coordinates, for plots of fields
coords: tuple = (("x", "m"), ("y", "m"))
name: str = "film"
@property
def n_q(self) -> int:
"""Number of position coordinates."""
return len(self.dof_names)
@property
def dirichlet(self) -> np.ndarray:
"""Indices of the nodes on the pressure boundaries."""
if not self.boundaries:
return np.array([], dtype=np.int64)
return np.unique(np.concatenate([d for d, _ in self.boundaries.values()]))
[docs]
def gap_shapes(self, x, q) -> np.ndarray:
"""dh/dq_j at x for every position coordinate, shape (n_q, ...)."""
q = np.asarray(q, dtype=float)
# Step in m or rad. Rigid motion changes the gap linearly, so the
# central difference is exact to roundoff.
eps = 1e-7
out = []
for j in range(self.n_q):
e = np.zeros(self.n_q)
e[j] = eps
out.append((self.gap(x, q + e) - self.gap(x, q - e)) / (2.0 * eps))
return np.array(out)
[docs]
def thinnest(self, q) -> float:
"""Smallest gap at position q, m: over the nodes and the quadrature points.
The solver takes the gap at the quadrature points, so those decide
whether it can solve; the nodes add the edges of the film, where a
tilted face is thinnest and no quadrature point lies. Between the
nodes the gap of an eccentric bore is below its nodal values, by up
to e·(1 - cos(half the node spacing)) for an eccentricity e, and a
shape with a feature narrower than an element by as much as the
feature is deep. It is still a sample: a feature that falls between
all of these points is not seen, here or by the solver.
"""
q = np.asarray(q, dtype=float)
basis = self.basis
at_nodes = np.min(self.gap(basis.doflocs, q))
at_quadrature = np.min(self.gap(basis.mapping.F(basis.X), q))
return float(min(at_nodes, at_quadrature))
[docs]
@dataclass
class StaticState:
"""Solution of one film at one position."""
film: Film
q: np.ndarray # position, one value per Film.dof_names, m or rad
p: np.ndarray # nodal absolute pressure in the film, Pa
wrench: np.ndarray # generalised forces conjugate to q, N or N·m
# Supply mass flow, kg/s: through the restrictor into the film (column
# model), or into the restrictor through the fed part of its back (volume).
flow_supply: float
# boundary name -> mass flow leaving through it, kg/s; in the volume model
# also "restrictor_rim", the flow leaving through an open rim
flow_out: dict
shear: np.ndarray # viscous force on the moving surface in film coordinates, N
h_min: float # smallest gap, m (Film.thinnest)
iterations: int # Newton iterations taken
# scaled nodal residual: of the film, or of film and restrictor volume
# together (their unknowns) in the volume model
residual: np.ndarray = field(repr=False, default=None)
# supply mass flow of each named region of the film (Film.regions), kg/s;
# column model only
flow_regions: dict = field(default_factory=dict)
# the solved restrictor volume (restrictor.py) or porous body
# (porous_body.py), when the film was solved with one
restrictor: object = field(repr=False, default=None)
@property
def flow_normal(self) -> float:
"""Supply flow as free gas at pa and the gas temperature, m³/s."""
return self.flow_supply / float(self.film.gas.rho(self.film.pa))
@property
def mass_imbalance(self) -> float:
"""(supply - total outflow) / supply. Measures solver convergence only."""
if self.flow_supply == 0.0:
return 0.0
return (self.flow_supply - sum(self.flow_out.values())) / self.flow_supply
[docs]
def force(self, name: str) -> float:
"""Generalised force conjugate to the named coordinate, N or N·m."""
return float(self.wrench[self.film.dof_names.index(name)])
def _aniso(w, gu, gv):
"""C3 grad u·grad v with the metric folded into the two coefficients."""
return w.C3x * gu[0] * gv[0] + w.C3y * gu[1] * gv[1]
@BilinearForm
def _theta_form(u, v, w):
return _aniso(w, grad(u), grad(v)) + w.a_s * u * v
@LinearForm
def _theta_load(v, w):
return w.a_s * w.theta_s * v
@BilinearForm
def _jacobian(u, v, w):
gP = grad(w.P)
return (
_aniso(w, w.da * u * gP + w.a * grad(u), grad(v))
- w.dr * u * (w.Cx * grad(v)[0] + w.Cy * grad(v)[1])
+ w.dfeed * w.a * u * v
)
@LinearForm
def _residual(v, w):
return (
w.a * _aniso(w, grad(w.P), grad(v))
- w.r * (w.Cx * grad(v)[0] + w.Cy * grad(v)[1])
- w.feed * v
)
class _Scaled:
"""Scaled coefficient fields of a film at one position."""
def __init__(self, film: Film, q):
gas, pa, h_ref = film.gas, film.pa, film.h_ref
self.film = film
self.xq = xq = film.basis.mapping.F(film.basis.X)
# the restrictor here: options given face by face, at these points
self.porous = film.porous.at(xq)
# the film the gas flows in: the gap plus the equivalent clearance
self.hq = (
_field(lambda x: film.gap(x, q), xq) + self.porous.equivalent_clearance
)
self.H = H = self.hq / h_ref
self.dphi_a = float(gas.dphi_dp(pa))
self.rho_a = float(gas.rho(pa))
self.a_c = a_c = 6.0 * self.rho_a / (h_ref**2 * self.dphi_a * pa)
if film.velocity is None:
Ux = Uy = np.zeros_like(H)
else:
Ux, Uy = (_field(u, xq) for u in film.velocity(xq))
self.Uq = (Ux, Uy)
# what the film sees of the restrictor: nothing where the face is sealed
self.kappa = _field(film.porous.kappa, xq) * film.porous.face_open(xq)
self.hp = _field(film.porous.hp, xq)
self.kappa_hp = self.kappa / self.porous.equivalent_thickness(self.hp)
if film.metric is None:
g1 = g2 = np.ones_like(H)
else:
g1, g2 = (_field(g, xq) for g in film.metric(xq))
self.g = (g1, g2)
self.area = area = g1 * g2 # area per unit of film coordinates
psi, _ = self.porous.slip_factor(self.hq, self.kappa)
C3 = (1.0 + psi) * H**3
self.C = {
"C3x": C3 * area / g1**2,
"C3y": C3 * area / g2**2,
"Cx": a_c * H * Ux * area / g1,
"Cy": a_c * H * Uy * area / g2,
"a_s": 12.0 * self.kappa_hp / h_ref**3 * area,
}
self.sliding = bool(np.any(Ux) or np.any(Uy))
self.theta_s = float(gas.phi(film.ps)) / (self.dphi_a * pa)
# mass flow per unit of scaled residual
self.mass_scale = h_ref**3 * self.dphi_a * pa / 12.0
# A Knudsen skin makes the feed nonlinear in Theta. The Newton start
# then takes the secant conductance of the free flow, which the
# skin's drop dominates, in place of the bulk's a_s.
self.skin = bool(np.any(self.porous.knudsen_resistance))
self.a_guess = self.C["a_s"]
if self.skin:
free = self.theta_s - float(self.theta(pa))
self.a_guess = self.feed(np.full(H.shape, free))[0] / free
def theta(self, p):
"""Theta at the absolute pressure p (Pa)."""
return self.film.gas.phi(p) / (self.dphi_a * self.film.pa)
def gas_fields(self, Pq):
"""a, r, their slopes in P, and Theta_s - Theta at the scaled pressure Pq."""
gas, pa = self.film.gas, self.film.pa
p = pa * Pq
return {
"a": gas.dphi_dp(p) / self.dphi_a,
"da": gas.d2phi_dp2(p) * pa / self.dphi_a,
"r": gas.rho(p) / self.rho_a,
"dr": gas.drho_dp(p) * pa / self.rho_a,
"dtheta": self.theta_s - self.theta(p),
}
def feed(self, dtheta):
"""Scaled feed through the restrictor and its slope in Theta.
Both include the area factor. Darcy flow gives a_s·dtheta and a_s.
"""
porous = self.porous
if not (np.any(porous.inertial_resistance) or self.skin):
return self.C["a_s"] * dtheta, self.C["a_s"]
film = self.film
unit = self.dphi_a * film.pa # phi per unit of Theta
mu = float(film.gas.mu(film.ps))
flux, slope = porous.mass_flux(
dtheta * unit, mu, self.kappa, self.hp, gas=film.gas, p_supply=film.ps
)
return (
flux * self.area / self.mass_scale,
slope * unit * self.area / self.mass_scale,
)
def residual(self, Pf, g, with_feed: bool = True):
"""Film residual; with_feed=False leaves the restrictor out of it."""
C = self.C
feed = self.feed(g["dtheta"])[0] if with_feed else 0.0 * g["dtheta"]
return _residual.assemble(
self.film.basis, P=Pf, a=g["a"], r=g["r"], feed=feed,
C3x=C["C3x"], C3y=C["C3y"], Cx=C["Cx"], Cy=C["Cy"],
) # fmt: skip
def jacobian(self, Pf, g, with_feed: bool = True):
"""Derivative of ``residual`` with respect to the nodal P."""
C = self.C
dfeed = self.feed(g["dtheta"])[1] if with_feed else 0.0 * g["dtheta"]
return _jacobian.assemble(
self.film.basis, P=Pf, a=g["a"], da=g["da"], dr=g["dr"],
C3x=C["C3x"], C3y=C["C3y"], Cx=C["Cx"], Cy=C["Cy"],
dfeed=dfeed,
) # fmt: skip
[docs]
def free_flow(film: Film) -> float:
"""Free-gas flow through the bare restrictor of a film, m³/s at pa.
The restrictor vents from the supply pressure straight to ambient over
the whole film face, with nothing in front of it: the usual way
permeability is measured. It is the feed of the column model
(``Porous.mass_flux``) with ambient pressure everywhere on the face,
integrated over the film surface, so permeability and thickness may vary
over the face and a curved wall counts. For a uniform restrictor of
known area it equals ``Porous.free_flow``.
Gas moves through the thickness only. That is exact when the whole back
is fed and the sides are sealed, whichever restrictor model the film
uses. A partial feed (``Porous.feed_area``), or an open rim in the volume
model, is not covered and raises ValueError.
A film on a porous body (``film.body``, porous_body.py) has the free
flow of that body, with the flow in it in all directions: its supply
faces at supply pressure, its film face at ambient pressure and its open
faces at theirs, the flow being what enters through the supply faces.
``film.porous`` plays no part in it, so changing ``film.porous`` of such
a film does not change its free flow: the permeability is that of the
body.
"""
if film.body is not None:
_no_skin_on_body(film)
return film.body.free_flow() / float(film.gas.rho(film.pa))
porous = film.porous
if porous.feed_area is not None:
raise ValueError(
f"{film.name}: the free flow of a restrictor fed over part of its "
"back is not available, because gas then spreads along the face."
)
if porous.model == "volume" and porous.rim_open:
raise ValueError(
f"{film.name}: the free flow of a restrictor with an open rim is "
"not available, because part of the gas leaves through the sides."
)
gas = film.gas
xq = film.basis.mapping.F(film.basis.X)
porous = porous.at(xq) # options given face by face, at these points
kappa = _field(porous.kappa, xq) * porous.face_open(xq)
area = np.ones(xq.shape[1:])
if film.metric is not None:
g1, g2 = (_field(g, xq) for g in film.metric(xq))
area = g1 * g2
flux, _ = porous.mass_flux(
float(gas.phi(film.ps) - gas.phi(film.pa)),
float(gas.mu(film.ps)),
kappa,
_field(porous.hp, xq),
gas=gas,
p_supply=film.ps,
)
total = Functional(lambda w: w["c"]).assemble(film.basis, c=flux * area)
return float(total) / float(gas.rho(film.pa))
def _no_skin_on_body(film: Film) -> None:
"""Refuse a Knudsen skin on the restrictor of a film that lies on a body.
The body has a flow law of its own and ``film.porous`` plays no part in
it, so a skin given there would be dropped without a word.
"""
skin = film.porous.knudsen_resistance
if callable(skin) or skin:
raise NotImplementedError(
f"{film.name}: a Knudsen skin (Porous.knudsen_resistance) is not "
"implemented on a porous body (porous_body.py); the body does not "
"take it, and the film's restrictor plays no part in its flow."
)
def _boundary_values(film: Film) -> np.ndarray:
"""Nodal P: the prescribed value on the pressure boundaries, zero elsewhere."""
P = film.basis.zeros()
for dofs, p in film.boundaries.values():
P[dofs] = p / film.pa
return P
def _linear_guess(film: Film, sc: _Scaled, Pbc) -> np.ndarray:
"""Newton start: the solution without sliding and with Darcy feed.
The problem is then linear in Theta. The result is kept between the
lowest and the highest prescribed pressure. With a Knudsen skin the feed
is taken at its secant conductance of the free flow (``_Scaled``).
"""
basis, D = film.basis, film.dirichlet
A = _theta_form.assemble(basis, C3x=sc.C["C3x"], C3y=sc.C["C3y"], a_s=sc.a_guess)
b = _theta_load.assemble(basis, a_s=sc.a_guess, theta_s=sc.theta_s)
theta = basis.zeros()
theta[D] = sc.theta(film.pa * Pbc[D])
if len(D) == 0 and not np.any(sc.a_guess):
raise FilmSolveError(f"{film.name}: no pressure boundary and no feed")
theta = solve(*condense(A, b, x=theta, D=D))
lo = min([sc.theta_s] + [float(sc.theta(p)) for _, p in film.boundaries.values()])
hi = max([sc.theta_s] + [float(sc.theta(p)) for _, p in film.boundaries.values()])
return film.gas.p_from_phi(np.clip(theta, lo, hi) * sc.dphi_a * film.pa) / film.pa
[docs]
def solve_static(
film: Film, q, *, tol: float = 1e-10, max_iter: int = 40
) -> StaticState:
"""Solve the film at position q.
q: one value per entry of ``film.dof_names``, m or rad.
tol: Newton stops when its step is below tol times the solution.
max_iter: largest number of Newton iterations (three times as many for a
porous body with a flow law of its own that is not linear).
The restrictor model is ``film.porous.model``, "column" or "volume", or
the porous body if the film lies on one (``film.body``). Raises
ContactError if the smallest gap (``Film.thinnest``) is at or below
``film.h_floor``,
FilmSolveError if Newton does not converge, and ValueError for a position
of the wrong length or a partial feed with the column model.
"""
q = np.atleast_1d(np.asarray(q, dtype=float))
if q.shape != (film.n_q,):
raise ValueError(
f"{film.name}: position needs {film.n_q} values {film.dof_names}"
)
basis, D = film.basis, film.dirichlet
h_min = film.thinnest(q)
if h_min <= film.h_floor:
raise ContactError(f"{film.name}: film thickness {h_min * 1e6:.3g} µm")
if film.body is not None:
_no_skin_on_body(film)
return _solve_static_volume(film, q, h_min, tol=tol, max_iter=max_iter)
if film.porous.model not in ("column", "volume"):
raise ValueError("Restrictor model must be 'column' or 'volume'.")
if film.porous.model == "column" and film.porous.feed_area is not None:
raise ValueError(
f"{film.name}: a restrictor fed over part of its back needs the "
"volume model (Porous(model='volume')); the column model has no "
"flow along the face to carry gas to the rest of the film."
)
if film.porous.model == "volume":
return _solve_static_volume(film, q, h_min, tol=tol, max_iter=max_iter)
sc = _Scaled(film, q)
Pbc = _boundary_values(film)
P = _linear_guess(film, sc, Pbc)
P[D] = Pbc[D]
I = basis.complement_dofs(D) # noqa: E741
P_floor = 0.05 * min([film.ps] + [p for _, p in film.boundaries.values()]) / film.pa
r = rn = r0 = None
for iterations in range(1, max_iter + 1): # noqa: B007 (used after the loop)
Pf = basis.interpolate(P)
g = sc.gas_fields(np.asarray(Pf))
r = sc.residual(Pf, g)
rn = float(np.linalg.norm(r[I]))
r0 = rn if r0 is None else r0
J = sc.jacobian(Pf, g)
dP = solve(*condense(J, -r, D=D))
step = 1.0
while np.any(P + step * dP < P_floor) and step > 1e-3:
step *= 0.5
P = P + step * dP
if np.linalg.norm(dP[I]) <= tol * np.linalg.norm(P[I]):
break
else:
raise FilmSolveError(
f"{film.name}: Newton did not converge in {max_iter} iterations "
f"(|r| {rn:.3e}, start {r0:.3e})"
)
return _post_process(film, sc, q, P, h_min, iterations)
def _post_process(film, sc, q, P, h_min, iterations) -> StaticState:
"""Forces, flows and shear of a converged column-model solution."""
basis, gas, pa = film.basis, film.gas, film.pa
Pf = basis.interpolate(P)
Pq = np.asarray(Pf)
g = sc.gas_fields(Pq)
r = sc.residual(Pf, g)
def integral(values):
return float(Functional(lambda w: w["c"]).assemble(basis, c=values * sc.area))
# The residual of a test function equals minus the mass flow leaving
# through the boundary it lives on, so boundary flows need no gradients.
flow_out, seen = {}, np.zeros(basis.N, dtype=bool)
for name, (dofs, _) in film.boundaries.items():
own = dofs[~seen[dofs]] # a corner shared by two boundaries counts once
seen[own] = True
flow_out[name] = -float(r[own].sum()) * sc.mass_scale
# mass flux through the restrictor at every point, kg/(m² s)
flux = sc.feed(g["dtheta"])[0] / sc.area * sc.mass_scale
flow_supply = integral(flux)
flow_regions = {
name: integral(flux * _field(inside, sc.xq))
for name, inside in (film.regions or {}).items()
}
dh = film.gap_shapes(sc.xq, q)
wrench = np.array([integral(pa * (Pq - 1.0) * dh_j) for dh_j in dh])
mu = gas.mu(pa * Pq)
gP = pa * np.asarray(Pf.grad)
shear = np.array(
[
integral(-(mu * sc.Uq[k] / sc.hq + 0.5 * sc.hq * gP[k] / sc.g[k]))
if film.velocity is not None
else 0.0
for k in range(2)
]
)
return StaticState(
film=film, q=q, p=pa * P, wrench=wrench, flow_supply=flow_supply,
flow_out=flow_out, shear=shear, h_min=h_min, iterations=iterations, residual=r,
flow_regions=flow_regions,
) # fmt: skip
def _solve_static_volume(
film: Film, q, h_min: float, *, tol: float = 1e-10, max_iter: int = 40
) -> StaticState:
"""Solve the film together with its restrictor volume or porous body."""
sc = _Scaled(film, q)
basis, pa = film.basis, film.pa
if film.body is not None:
# the porous part meshed as a body of its own (porous_body.py)
vol = copy.copy(film.body) # one solved state per solve
X = vol.start(film, sc)
else:
vol = restrictor_volume(film, sc)
# start from the column model of the same restrictor, fed where it is fed
start = replace(film.porous, model="column", feed_area=None)
if film.porous.feed_area is not None:
kappa = film.porous.kappa
start = replace(
start,
kappa=lambda x: (
_field(kappa, x)
* np.asarray(_field(film.porous.feed_area, x), dtype=bool)
),
)
P1 = solve_static(replace(film, porous=start), q).p / pa
X = vol.column_start(P1, sc)
fixed = {}
for dofs, p in film.boundaries.values():
fixed.update(dict.fromkeys(vol.film_index[dofs], p / pa))
# (behind a Knudsen skin the face of the body has the drop across it
# as unknown, zero on a rim where the film has the same pressure)
is_drop = getattr(vol, "is_drop", np.zeros(X.size, dtype=bool))
for i, p in zip(vol.rim, vol.rim_pressure, strict=True):
fixed.setdefault(i, 0.0 if is_drop[i] else sc.theta(p))
for i in vol.supply:
fixed[i] = sc.theta_s # the supply wins where a fed node is also on the rim
for i in vol.sealed:
fixed.setdefault(i, sc.theta(pa)) # no flow there: any value will do
D = np.fromiter(fixed.keys(), dtype=np.int64)
X[D] = np.fromiter(fixed.values(), dtype=float)
free = np.setdiff1d(np.arange(X.size), D)
P_floor = 0.05 * min([film.ps] + [p for _, p in film.boundaries.values()]) / pa
def too_low(X):
# every pressure: the film, and the face of the body behind a skin
if np.any(X[vol.film_index] < P_floor):
return True
return bool(is_drop.any() and np.any(vol.face_pressure(X) < P_floor))
def residual(X):
Pf = basis.interpolate(X[vol.film_index])
g = sc.gas_fields(np.asarray(Pf))
r = vol.flow(X, sc)
r[vol.film_index] += sc.residual(Pf, g, with_feed=False)
return r, Pf, g
# Factorising the Jacobian is nearly all of the cost, and the start is
# close, so a factorisation is kept for as long as each step is at least
# four times smaller than the one before.
lu, last = None, np.inf
nonlinear = getattr(vol, "nonlinear", False) # the body's own flow law
start_size = None
if nonlinear:
max_iter = 3 * max_iter # the first steps only halve the error
for iterations in range(1, max_iter + 1): # noqa: B007 (used after the loop)
r, Pf, g = residual(X)
if lu is None:
if nonlinear:
# far from the solution the secant matrix, close to it the
# true derivative (porous_body: flow_jacobian)
here = float(np.linalg.norm(r[free]))
start_size = here if start_size is None else start_size
J = vol.flow_jacobian(X, sc, secant=here > 1e-3 * start_size)
else:
J = vol.flow_jacobian(X, sc)
J = (J + vol.embed(sc.jacobian(Pf, g, with_feed=False))).tocsr()
lu = factorise(J[free][:, free])
dX = np.zeros_like(X)
dX[free] = lu.solve(-r[free])
size = float(np.linalg.norm(dX[free]))
# (a body whose own flow law is not linear gets a new one every time)
if size > 0.25 * last or nonlinear:
lu = None
last = size
step = 1.0
while too_low(X + step * dX) and step > 1e-3:
step *= 0.5
if nonlinear:
# shorten the step until the residual is smaller than before
before = np.linalg.norm(r[free])
while step > 1.0 / 64.0:
trial = residual(X + step * dX)[0]
if np.linalg.norm(trial[free]) < (1.0 - 1e-4 * step) * before:
break
step *= 0.5
X = X + step * dX
if step * size <= tol * np.linalg.norm(X[free]):
break
else:
raise FilmSolveError(
f"{film.name}: restrictor volume did not converge in {max_iter} iterations"
)
vol.X = X
return _volume_state(
film, sc, vol, np.asarray(q, dtype=float), X, h_min, iterations
)
def _volume_state(film, sc, vol, q, X, h_min, iterations) -> StaticState:
"""Forces, flows and shear of a converged solution with a restrictor volume."""
basis, gas, pa = film.basis, film.gas, film.pa
P = X[vol.film_index]
Pf = basis.interpolate(P)
Pq = np.asarray(Pf)
g = sc.gas_fields(Pq)
r = vol.flow(X, sc)
r[vol.film_index] += sc.residual(Pf, g, with_feed=False)
def integral(values):
return float(Functional(lambda w: w["c"]).assemble(basis, c=values * sc.area))
# The residual at a node held at a given pressure is the mass flow that
# enters the model there: in through the fed back, out through the film
# edges and, if it is open, the rim.
flow_supply = float(r[vol.supply].sum()) * sc.mass_scale
flow_out, seen = {}, np.zeros(X.size, dtype=bool)
seen[vol.supply] = True
for name, (dofs, _) in film.boundaries.items():
own = vol.film_index[dofs]
own = own[~seen[own]]
seen[own] = True
flow_out[name] = -float(r[own].sum()) * sc.mass_scale
if vol.rim.size:
own = vol.rim[~seen[vol.rim]]
flow_out["restrictor_rim"] = -float(r[own].sum()) * sc.mass_scale
dh = film.gap_shapes(sc.xq, q)
wrench = np.array([integral(pa * (Pq - 1.0) * dh_j) for dh_j in dh])
mu = gas.mu(pa * Pq)
gP = pa * np.asarray(Pf.grad)
shear = np.array(
[
integral(-(mu * sc.Uq[k] / sc.hq + 0.5 * sc.hq * gP[k] / sc.g[k]))
if film.velocity is not None
else 0.0
for k in range(2)
]
)
# supply flow of each face of a film of several faces: each face has a
# volume of its own, and its supply nodes are its own
flow_regions = {}
if getattr(vol, "parts", None) is not None:
for name, part, index in zip(film.regions, vol.parts, vol.index, strict=True):
flow_regions[name] = float(r[index[part.supply]].sum()) * sc.mass_scale
return StaticState(
film=film, q=q, p=pa * P, wrench=wrench, flow_supply=flow_supply,
flow_out=flow_out, shear=shear, h_min=h_min, iterations=iterations, residual=r,
restrictor=vol, flow_regions=flow_regions,
) # fmt: skip
[docs]
def stiffness(film: Film, q, *, rel_step: float = 1e-3) -> np.ndarray:
"""Static stiffness K_ij = -dF_i/dq_j at position q by central differences.
Shape (n_q, n_q), in N/m, N/rad, N·m/m or N·m/rad, with the restrictor
model of ``film.porous.model``: two static solves per coordinate. Each
position coordinate is stepped so that the gap changes by at most
rel_step times the minimum film thickness. A coordinate that does not
change the gap gives a zero column, and a coupling term below 1e-9 of
the scale of its two diagonal terms is returned as exactly zero.
"""
q = np.atleast_1d(np.asarray(q, dtype=float))
x = film.basis.doflocs
h_min = film.thinnest(q)
dh = np.abs(film.gap_shapes(x, q)).reshape(film.n_q, -1).max(axis=1)
K = np.zeros((film.n_q, film.n_q))
for j in range(film.n_q):
if dh[j] == 0.0:
continue # this coordinate does not change the gap
e = np.zeros(film.n_q)
e[j] = rel_step * h_min / dh[j]
Fp = solve_static(film, q + e).wrench
Fm = solve_static(film, q - e).wrench
K[:, j] = -(Fp - Fm) / (2.0 * e[j])
# A coupling term that vanishes by symmetry comes out as roundoff of the
# difference. Anything below 1e-9 of the scale set by the two diagonal
# terms is reported as exactly zero.
scale = np.sqrt(np.abs(np.outer(np.diag(K), np.diag(K))))
K[np.abs(K) < 1e-9 * scale] = 0.0
return K